@torrent-tv/proxy 2.73.1 → 2.74.0

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 (33) hide show
  1. package/CHANGELOG.md +1447 -1437
  2. package/CLAUDE.md +165 -160
  3. package/docs/container-architecture.md +192 -184
  4. package/package.json +1 -1
  5. package/routes/api/subtitles/get.js +205 -205
  6. package/services/container/Container.js +354 -135
  7. package/services/container/MatroskaContainer.js +1155 -516
  8. package/services/container/Mp4Container.js +858 -392
  9. package/services/container/SubtitleFileContainer.js +323 -261
  10. package/services/controllers/SubtitleController.js +128 -127
  11. package/services/delivery-probe.js +64 -6
  12. package/services/hls-session-manager.js +32 -35
  13. package/services/language-detect.js +174 -228
  14. package/services/playback-planner.js +747 -747
  15. package/services/produced-index.js +300 -0
  16. package/services/torrent-worker/subtitle-cues.js +582 -633
  17. package/services/tracks/TextSubtitleTrack.js +287 -47
  18. package/services/tracks/index.js +14 -14
  19. package/test/delivery-probe.test.js +67 -0
  20. package/test/matroska-blocks.test.js +0 -0
  21. package/test/mp4-subtitles.test.js +173 -127
  22. package/test/produced-index.test.js +188 -0
  23. package/test/subtitle-cue-framing.test.js +200 -202
  24. package/test/subtitle-cue-walk.test.js +369 -0
  25. package/test/subtitle-defaults.test.js +97 -97
  26. package/test/subtitle-language.test.js +252 -252
  27. package/test/subtitle-track-numbering.test.js +370 -370
  28. package/services/container-index/matroska-blocks.js +0 -202
  29. package/services/container-index/matroska-subtitles.js +0 -372
  30. package/services/container-index/mp4-subtitles.js +0 -404
  31. package/services/subtitle-convert.js +0 -144
  32. package/services/subtitle-defaults.js +0 -157
  33. package/services/tracks/subtitle-markup.js +0 -104
@@ -1,516 +1,1155 @@
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
- * Delegates low-level Cues/cluster and keyframe work to existing readers
14
- * (ebml-reader, matroska.js, matroska-subtitles.js) but centralizes the single Tracks walk.
15
- */
16
-
17
- import { Container } from "./Container.js";
18
- import { isMatroska, readMatroskaKeyframeTimes } from "../container-index/matroska.js";
19
- import { readSubtitlePlan } from "../container-index/matroska-subtitles.js";
20
- import { VideoTrack } from "../tracks/VideoTrack.js";
21
- import { AudioTrack } from "../tracks/AudioTrack.js";
22
- import { TextSubtitleTrack, TEXT_CODECS_MATROSKA } from "../tracks/TextSubtitleTrack.js";
23
- import { ImageSubtitleTrack } from "../tracks/ImageSubtitleTrack.js";
24
- import { ContainerTrack } from "../tracks/ContainerTrack.js";
25
- import { findElement, iterateElements, readFloat, readUint } from "../container-index/ebml-reader.js";
26
-
27
- const HEAD_BYTES = 64 * 1024;
28
- const ID_SEGMENT = 0x18538067;
29
- const ID_SEEK_HEAD = 0x114d9b74;
30
- const ID_SEEK = 0x4dbb;
31
- const ID_SEEK_ID = 0x53ab;
32
- const ID_SEEK_POSITION = 0x53ac;
33
- const ID_INFO = 0x1549a966;
34
- const ID_TIMESTAMP_SCALE = 0x2ad7b1;
35
- const ID_DURATION = 0x4489;
36
- const ID_CLUSTER = 0x1f43b675;
37
- const ID_TIMESTAMP = 0xe7;
38
- const ID_SIMPLE_BLOCK = 0xa3;
39
- const ID_BLOCK_GROUP = 0xa0;
40
- /** RFC 9559 §5.1.2.1: nanoseconds per tick when Info omits TimestampScale. */
41
- const DEFAULT_TIMESTAMP_SCALE = 1_000_000;
42
- /**
43
- * How much to read at a cluster whose position came from the SeekHead. A
44
- * cluster's Timestamp is the first child every muxer writes, so this only has
45
- * to cover the element header and that one field.
46
- */
47
- const CLUSTER_PROBE_BYTES = 4 * 1024;
48
- const ID_TRACKS = 0x1654ae6b;
49
- const ID_TRACK_ENTRY = 0xae;
50
- const ID_TRACK_NUMBER = 0xd7;
51
- const ID_TRACK_TYPE = 0x83;
52
- const ID_FLAG_ENABLED = 0xb9;
53
- const ID_FLAG_DEFAULT = 0x88;
54
- const ID_FLAG_FORCED = 0x55aa;
55
- const ID_FLAG_HEARING = 0x55ab;
56
- const ID_FLAG_VISUAL = 0x55ac;
57
- const ID_FLAG_TEXT_DESCR = 0x55ad;
58
- const ID_FLAG_ORIGINAL = 0x55ae;
59
- const ID_FLAG_COMMENTARY = 0x55af;
60
- const ID_CODEC_ID = 0x86;
61
- const ID_CODEC_PRIVATE = 0x63a2;
62
- const ID_LANGUAGE = 0x22b59c;
63
- const ID_LANGUAGE_BCP47 = 0x22b59d;
64
- const ID_NAME = 0x536e;
65
- const ID_VIDEO = 0xe0;
66
- const ID_AUDIO = 0xe1;
67
- const ID_PIXEL_WIDTH = 0xb0;
68
- const ID_PIXEL_HEIGHT = 0xba;
69
- const ID_DISPLAY_WIDTH = 0x54b0;
70
- const ID_DISPLAY_HEIGHT = 0x54ba;
71
- const ID_SAMPLING_FREQUENCY = 0xb5;
72
- const ID_CHANNELS = 0x9f;
73
- /**
74
- * ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect — the eight
75
- * fields Matroska writes before the text of an SSA/ASS event. See
76
- * {@link MatroskaContainer.cueTextOf} for the quotation this comes from.
77
- */
78
- const ASS_FIELDS_BEFORE_TEXT = 8;
79
-
80
- function readString(buf, el) {
81
- return buf.toString("utf8", el.dataOffset, el.dataOffset + el.size).replace(/\0+$/, "");
82
- }
83
-
84
- export class MatroskaContainer extends Container {
85
- get formatName() {
86
- return "matroska";
87
- }
88
-
89
- static detect(head) {
90
- return isMatroska(head);
91
- }
92
-
93
- /**
94
- * Duration and the start of this file's own timeline, per RFC 9559 §5.1.2.
95
- *
96
- * Duration is stated in `Info` as a FLOAT in ticks, so it needs the file's
97
- * `TimestampScale` to become seconds. The start of the timeline is not stated
98
- * anywhere — Matroska has no such element — so it is the timestamp of the
99
- * first Cluster, which is what the first frame is placed against.
100
- *
101
- * @returns {Promise<import("./Container.js").ContainerMediaInfo>}
102
- */
103
- async readMediaInfo() {
104
- if (this.mediaInfo) {
105
- return this.mediaInfo;
106
- }
107
- /** @type {import("./Container.js").ContainerMediaInfo} */
108
- const info = { format: this.formatName, durationSeconds: null, startTimeSeconds: null };
109
- this.mediaInfo = info;
110
- const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
111
- if (!head || !isMatroska(head)) {
112
- return info;
113
- }
114
- const segment = findElement(head, ID_SEGMENT, []);
115
- if (!segment) {
116
- return info;
117
- }
118
- const scale = MatroskaContainer.#timestampScaleOf(head, segment.dataOffset);
119
- const infoElement = findElement(head, ID_INFO, [], segment.dataOffset);
120
- if (infoElement) {
121
- const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
122
- for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
123
- if (field.id !== ID_DURATION) {
124
- continue;
125
- }
126
- const ticks = readFloat(head, field.dataOffset, field.size);
127
- if (ticks !== null && ticks > 0) {
128
- info.durationSeconds = (ticks * scale) / 1e9;
129
- }
130
- break;
131
- }
132
- }
133
- info.startTimeSeconds = await this.#firstClusterSeconds(head, segment.dataOffset, scale);
134
- return info;
135
- }
136
-
137
- /**
138
- * `TimestampScale` from Info, or the specification's default.
139
- *
140
- * @param {Buffer} head
141
- * @param {number} segmentDataOffset
142
- * @returns {number} Nanoseconds per tick.
143
- */
144
- static #timestampScaleOf(head, segmentDataOffset) {
145
- const infoElement = findElement(head, ID_INFO, [], segmentDataOffset);
146
- if (!infoElement) {
147
- return DEFAULT_TIMESTAMP_SCALE;
148
- }
149
- const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
150
- for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
151
- if (field.id === ID_TIMESTAMP_SCALE) {
152
- const scale = readUint(head, field.dataOffset, field.size);
153
- return scale > 0 ? scale : DEFAULT_TIMESTAMP_SCALE;
154
- }
155
- }
156
- return DEFAULT_TIMESTAMP_SCALE;
157
- }
158
-
159
- /**
160
- * The timestamp of the first Cluster, in seconds.
161
- *
162
- * Tried in the head window first, because a muxer writes the first cluster
163
- * straight after Tracks and both usually fit; a file whose Tracks element is
164
- * large enough to push it out is answered from the SeekHead instead, with one
165
- * short read at the position it names.
166
- *
167
- * @param {Buffer} head
168
- * @param {number} segmentDataOffset
169
- * @param {number} scale - Nanoseconds per tick.
170
- * @returns {Promise<number | null>} Null when no cluster could be read.
171
- */
172
- async #firstClusterSeconds(head, segmentDataOffset, scale) {
173
- /**
174
- * @param {Buffer} buffer
175
- * @param {number} dataOffset
176
- * @param {number} end
177
- * @returns {number | null}
178
- */
179
- const timestampIn = (buffer, dataOffset, end) => {
180
- for (const field of iterateElements(buffer, dataOffset, end)) {
181
- if (field.id === ID_TIMESTAMP) {
182
- const ticks = readUint(buffer, field.dataOffset, field.size);
183
- return Number.isFinite(ticks) ? (ticks * scale) / 1e9 : null;
184
- }
185
- // Timestamp is written before any frame. Stopping at the first one keeps
186
- // this from walking a cluster's whole payload, which is megabytes and
187
- // usually not in the buffer at all.
188
- if (field.id === ID_SIMPLE_BLOCK || field.id === ID_BLOCK_GROUP) {
189
- return null;
190
- }
191
- }
192
- return null;
193
- };
194
-
195
- for (const element of iterateElements(head, segmentDataOffset, head.length)) {
196
- if (element.id !== ID_CLUSTER) {
197
- continue;
198
- }
199
- return timestampIn(head, element.dataOffset, Math.min(head.length, element.dataOffset + element.size));
200
- }
201
-
202
- const position = MatroskaContainer.#seekPositionOf(head, segmentDataOffset, ID_CLUSTER);
203
- if (position === null) {
204
- return null;
205
- }
206
- const at = segmentDataOffset + position;
207
- if (at >= this.fileSize) {
208
- return null;
209
- }
210
- const chunk = await this.readRange(at, Math.min(this.fileSize - 1, at + CLUSTER_PROBE_BYTES - 1));
211
- if (!chunk) {
212
- return null;
213
- }
214
- for (const element of iterateElements(chunk, 0, chunk.length)) {
215
- if (element.id !== ID_CLUSTER) {
216
- continue;
217
- }
218
- return timestampIn(chunk, element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
219
- }
220
- return null;
221
- }
222
-
223
- /**
224
- * Where the SeekHead says an element lives, relative to the Segment's payload.
225
- *
226
- * @param {Buffer} head
227
- * @param {number} segmentDataOffset
228
- * @param {number} wantedId
229
- * @returns {number | null}
230
- */
231
- static #seekPositionOf(head, segmentDataOffset, wantedId) {
232
- const seekHead = findElement(head, ID_SEEK_HEAD, [], segmentDataOffset);
233
- if (!seekHead) {
234
- return null;
235
- }
236
- const seekHeadEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
237
- for (const seek of iterateElements(head, seekHead.dataOffset, seekHeadEnd)) {
238
- if (seek.id !== ID_SEEK) {
239
- continue;
240
- }
241
- const seekEnd = Math.min(seekHeadEnd, seek.dataOffset + seek.size);
242
- let targetId = null;
243
- let position = null;
244
- for (const field of iterateElements(head, seek.dataOffset, seekEnd)) {
245
- if (field.id === ID_SEEK_ID) {
246
- targetId = readUint(head, field.dataOffset, field.size);
247
- } else if (field.id === ID_SEEK_POSITION) {
248
- position = readUint(head, field.dataOffset, field.size);
249
- }
250
- }
251
- if (targetId === wantedId && position !== null) {
252
- return position;
253
- }
254
- }
255
- return null;
256
- }
257
-
258
- async readTracks() {
259
- const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
260
- if (!head || !isMatroska(head)) return [];
261
-
262
- // Delegate to subtitle plan reader for subtitle tracks (already handles Flags spec-correct),
263
- // but we need video/audio tracks too. Do a dedicated Tracks walk here for all types,
264
- // then merge subtitle detail (clusterPositions, declaresDefault etc.) from the plan.
265
- const seg = findElement(head, 0x18538067, []);
266
- if (!seg) return [];
267
- const tracksEl = findElement(head, ID_TRACKS, [], seg.dataOffset);
268
- if (!tracksEl) return [];
269
-
270
- const tracksEnd = Math.min(head.length, tracksEl.dataOffset + tracksEl.size);
271
- /** @type {import("../tracks/index.js").ContainerTrack[]} */
272
- const result = [];
273
- // Subtitle declaredIndex is position among subtitle tracks, not global — track per-type counters.
274
- let subtitleDeclaredIndex = -1;
275
- let audioDeclaredIndex = -1;
276
- let videoDeclaredIndex = -1;
277
-
278
- // For subtitle flag enrichment, read the existing plan (it already does Cues walk)
279
- let subtitlePlan = null;
280
- try {
281
- const shim = async (s, e) => this.readRange(s, Math.min(e, this.fileSize - 1));
282
- subtitlePlan = await readSubtitlePlan(shim, this.fileSize);
283
- } catch {
284
- subtitlePlan = null;
285
- }
286
- const declaredByNumber = new Map();
287
- const planTracksByNumber = new Map();
288
- if (subtitlePlan?.declared) {
289
- for (const d of subtitlePlan.declared) declaredByNumber.set(d.trackNumber, d);
290
- }
291
- if (subtitlePlan?.tracks) {
292
- for (const t of subtitlePlan.tracks) planTracksByNumber.set(t.trackNumber, t);
293
- }
294
-
295
- for (const entry of iterateElements(head, tracksEl.dataOffset, tracksEnd)) {
296
- if (entry.id !== ID_TRACK_ENTRY) continue;
297
- const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
298
- let trackNumber = null;
299
- let typeNum = null;
300
- let codecId = "";
301
- let language = "";
302
- let languageBcp47 = "";
303
- let name = "";
304
- let codecPrivateB64 = "";
305
- let isEnabled = true;
306
- let isDefault = true;
307
- let declaresDefault = false;
308
- let isForced = false;
309
- let isHearing = false;
310
- let isVisual = false;
311
- let isOriginal = false;
312
- let isCommentary = false;
313
- let pixelWidth = null;
314
- let pixelHeight = null;
315
- let displayWidth = null;
316
- let displayHeight = null;
317
- let samplingFreq = null;
318
- let channels = null;
319
-
320
- for (const f of iterateElements(head, entry.dataOffset, entryEnd)) {
321
- switch (f.id) {
322
- case ID_TRACK_NUMBER: trackNumber = readUint(head, f.dataOffset, f.size); break;
323
- case ID_TRACK_TYPE: typeNum = readUint(head, f.dataOffset, f.size); break;
324
- case ID_CODEC_ID: codecId = readString(head, f); break;
325
- case ID_CODEC_PRIVATE: codecPrivateB64 = head.toString("base64", f.dataOffset, f.dataOffset + f.size); break;
326
- case ID_LANGUAGE: language = readString(head, f); break;
327
- case ID_LANGUAGE_BCP47: languageBcp47 = readString(head, f); break;
328
- case ID_NAME: name = readString(head, f); break;
329
- case ID_FLAG_ENABLED: isEnabled = f.size === 0 || readUint(head, f.dataOffset, f.size) !== 0; break;
330
- case ID_FLAG_DEFAULT: isDefault = f.size === 0 || readUint(head, f.dataOffset, f.size) === 1; declaresDefault = true; break;
331
- case ID_FLAG_FORCED: isForced = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
332
- case ID_FLAG_HEARING: isHearing = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
333
- case ID_FLAG_VISUAL: isVisual = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
334
- case ID_FLAG_TEXT_DESCR: break;
335
- case ID_FLAG_ORIGINAL: isOriginal = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
336
- case ID_FLAG_COMMENTARY: isCommentary = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
337
- default: break;
338
- }
339
- // Video/Audio sub-elements are nested, not at entry levelread separately below.
340
- }
341
- if (trackNumber === null) continue;
342
-
343
- // Parse Video/Audio sub-elements if present
344
- const videoEl = findElement(head, ID_VIDEO, [], entry.dataOffset, entryEnd);
345
- if (videoEl) {
346
- for (const vf of iterateElements(head, videoEl.dataOffset, Math.min(entryEnd, videoEl.dataOffset + videoEl.size))) {
347
- if (vf.id === ID_PIXEL_WIDTH) pixelWidth = readUint(head, vf.dataOffset, vf.size);
348
- else if (vf.id === ID_PIXEL_HEIGHT) pixelHeight = readUint(head, vf.dataOffset, vf.size);
349
- else if (vf.id === ID_DISPLAY_WIDTH) displayWidth = readUint(head, vf.dataOffset, vf.size);
350
- else if (vf.id === ID_DISPLAY_HEIGHT) displayHeight = readUint(head, vf.dataOffset, vf.size);
351
- }
352
- }
353
- const audioEl = findElement(head, ID_AUDIO, [], entry.dataOffset, entryEnd);
354
- if (audioEl) {
355
- for (const af of iterateElements(head, audioEl.dataOffset, Math.min(entryEnd, audioEl.dataOffset + audioEl.size))) {
356
- if (af.id === ID_SAMPLING_FREQUENCY) {
357
- // SamplingFrequency is float64
358
- if (af.size === 8) samplingFreq = head.readDoubleBE(af.dataOffset);
359
- else samplingFreq = readUint(head, af.dataOffset, af.size);
360
- } else if (af.id === ID_CHANNELS) channels = readUint(head, af.dataOffset, af.size);
361
- }
362
- }
363
-
364
- // RFC 9559 LanguageBCP47 MUST when present, Language ignored
365
- const resolvedLang = languageBcp47 || language;
366
- const bcpTag = languageBcp47;
367
-
368
- if (typeNum === 1) {
369
- videoDeclaredIndex += 1;
370
- result.push(new VideoTrack({
371
- trackNumber,
372
- declaredIndex: videoDeclaredIndex,
373
- codecId,
374
- language: resolvedLang,
375
- languageBcp47: bcpTag,
376
- name,
377
- isEnabled,
378
- isDefault,
379
- declaresDefault,
380
- codecPrivateB64,
381
- width: pixelWidth,
382
- height: pixelHeight,
383
- displayWidth,
384
- displayHeight
385
- }));
386
- } else if (typeNum === 2) {
387
- audioDeclaredIndex += 1;
388
- result.push(new AudioTrack({
389
- trackNumber,
390
- declaredIndex: audioDeclaredIndex,
391
- codecId,
392
- language: resolvedLang,
393
- languageBcp47: bcpTag,
394
- name,
395
- isEnabled,
396
- isDefault,
397
- declaresDefault,
398
- codecPrivateB64,
399
- isOriginal,
400
- isCommentary,
401
- isVisualImpaired: isVisual,
402
- channels,
403
- samplingFrequency: samplingFreq
404
- }));
405
- } else if (typeNum === 17) {
406
- subtitleDeclaredIndex += 1;
407
- // Only Forced/Hearing belong to subtitles; Original/Commentary must not leak.
408
- const declared = declaredByNumber.get(trackNumber);
409
- const planTrack = planTracksByNumber.get(trackNumber);
410
- // Prefer plan's flags when available (already spec-correct), else use parsed.
411
- const finalForced = planTrack ? !!planTrack.isForced : isForced;
412
- const finalHearing = planTrack ? !!planTrack.isHearingImpaired : isHearing;
413
- const finalEnabled = declared ? declared.isEnabled !== false : isEnabled;
414
- const finalDefault = declared ? !!declared.isDefault : isDefault;
415
- const finalDeclares = declared ? !!declared.declaresDefault : declaresDefault;
416
- const clusterPositions = planTrack ? planTrack.clusterPositions ?? [] : [];
417
- const isText = TEXT_CODECS_MATROSKA.has(codecId);
418
- // disabled image/text tracks still counted (declaredIndex above) — offerable flag controls visibility
419
- if (isText && finalEnabled) {
420
- result.push(new TextSubtitleTrack({
421
- trackNumber,
422
- declaredIndex: subtitleDeclaredIndex,
423
- codecId,
424
- language: resolvedLang,
425
- languageBcp47: bcpTag,
426
- name,
427
- isEnabled: finalEnabled,
428
- isDefault: finalDefault,
429
- declaresDefault: finalDeclares,
430
- codecPrivateB64,
431
- isForced: finalForced,
432
- isHearingImpaired: finalHearing,
433
- clusterPositions
434
- }));
435
- } else {
436
- // Image or disabled — keep declaredIndex, not offerable if disabled
437
- const Target = isText ? TextSubtitleTrack : ImageSubtitleTrack;
438
- result.push(new Target({
439
- trackNumber,
440
- declaredIndex: subtitleDeclaredIndex,
441
- codecId,
442
- language: resolvedLang,
443
- languageBcp47: bcpTag,
444
- name,
445
- isEnabled: finalEnabled,
446
- isDefault: finalDefault,
447
- declaresDefault: finalDeclares,
448
- codecPrivateB64,
449
- isForced: finalForced,
450
- isHearingImpaired: finalHearing,
451
- clusterPositions: isText ? clusterPositions : []
452
- }));
453
- }
454
- } else {
455
- // Other TrackType (complex, logo, buttons, control) — keep as generic, not video
456
- result.push(new ContainerTrack({
457
- trackNumber,
458
- declaredIndex: -1,
459
- type: "other",
460
- codecId,
461
- language: resolvedLang,
462
- languageBcp47: bcpTag,
463
- name,
464
- isEnabled,
465
- isDefault,
466
- declaresDefault,
467
- codecPrivateB64
468
- }));
469
- }
470
- }
471
- return result;
472
- }
473
-
474
- /**
475
- * The text field of one cue as Matroska frames it.
476
- *
477
- * Two rules, both from `matroska.org/technical/subtitles.html`, "Now, how are
478
- * they stored in Matroska?":
479
- *
480
- * 1. "All text is converted to UTF-8", so the block is decoded as UTF-8 and
481
- * no other encoding is guessed at. A subtitle FILE is a different matter
482
- * there the bytes may be Windows-1251 and `decodeSubtitleBytes` sniffs for
483
- * it but a muxer had to convert before writing the block.
484
- * 2. "Events are stored in the Block in this order: ReadOrder, Layer, Style,
485
- * Name, MarginL, MarginR, MarginV, Effect, Text", and "Start & End field
486
- * are used to set TimeStamp and the BlockDuration element". So eight fields
487
- * stand before the text, the two timing fields of the file's own row are
488
- * NOT among them, and a read order takes their place at the front. The text
489
- * itself may hold commas, so everything from the ninth field on is joined
490
- * back together.
491
- *
492
- * `S_TEXT/UTF8` and `S_TEXT/WEBVTT` have no such framing: the block holds the
493
- * cue text and nothing else. (A WebVTT cue's settings, identifier and
494
- * preceding comments live in a BlockAddition, which this proxy does not read;
495
- * losing them costs positioning, not words.)
496
- *
497
- * @param {Buffer} payload - The block's own bytes.
498
- * @param {string} codecId - Matroska CodecID of the track the block belongs to.
499
- * @returns {string}
500
- */
501
- static cueTextOf(payload, codecId) {
502
- const text = Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "");
503
- if (codecId !== "S_TEXT/ASS" && codecId !== "S_TEXT/SSA") {
504
- return text;
505
- }
506
- const fields = text.split(",");
507
- return fields.length > ASS_FIELDS_BEFORE_TEXT ? fields.slice(ASS_FIELDS_BEFORE_TEXT).join(",") : "";
508
- }
509
-
510
- async readKeyframeIndex() {
511
- const times = await readMatroskaKeyframeTimes(this.readRange, this.fileSize);
512
- if (!times) return null;
513
- if (Array.isArray(times)) return { times, tolerance: 0 };
514
- return times;
515
- }
516
- }
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
+ * Keyframe reading is delegated to matroska.js and byte-level EBML walking to
14
+ * ebml-reader.js. Everything this container states about its own subtitles —
15
+ * the Tracks walk, the Cues table, the cluster positions it names, and the
16
+ * blocks inside a cluster — is read in this module: each of those is RFC 9559
17
+ * speaking about Matroska, and the class is the only way in.
18
+ */
19
+
20
+ import { Container } from "./Container.js";
21
+ import { isMatroska, readMatroskaKeyframeTimes } from "../container-index/matroska.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 "../container-index/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
+ * This container's subtitle tracks, its Cues table and the cluster positions
106
+ * they name — RFC 9559 §5.1.4 and §5.1.3.
107
+ *
108
+ * @param {(start:number,end:number)=>Promise<Buffer|null>} readRange
109
+ * @param {number} fileSize
110
+ * @returns {Promise<object|null>}
111
+ */
112
+ static readSubtitlePlan(readRange, fileSize) {
113
+ return readSubtitlePlan(readRange, fileSize);
114
+ }
115
+
116
+ /**
117
+ * The same reading, over the file this container was built on.
118
+ *
119
+ * The static form exists for a caller that has bytes and no container; this
120
+ * is the one to use otherwise, because the reader is already here.
121
+ *
122
+ * @returns {Promise<object|null>}
123
+ */
124
+ readSubtitlePlan() {
125
+ return MatroskaContainer.readSubtitlePlan(this.readRange, this.fileSize);
126
+ }
127
+
128
+ /**
129
+ * The blocks one track has inside a cluster, with their times.
130
+ *
131
+ * The payload is handed back as BYTES: what those bytes mean is
132
+ * {@link MatroskaContainer.cueTextOf}'s answer, and this method's subject is
133
+ * only where a block sits and how long it lasts.
134
+ *
135
+ * @param {Buffer} bytes - The cluster, from its own element header onward.
136
+ * @param {number} trackNumber
137
+ * @param {number} secondsPerTick
138
+ * @returns {{ startSeconds: number, endSeconds: number | null, payload: Buffer }[]}
139
+ */
140
+ static blocksInCluster(bytes, trackNumber, secondsPerTick) {
141
+ return harvestCluster(bytes, trackNumber, secondsPerTick);
142
+ }
143
+
144
+ /**
145
+ * The blocks one track has inside a cluster whose bounds are already known —
146
+ * RFC 9559 §5.1.3.4 (SimpleBlock) and §5.1.3.5 (BlockGroup).
147
+ *
148
+ * The same reading as {@link MatroskaContainer.blocksInCluster}, entered where
149
+ * the caller has already parsed the cluster's own header.
150
+ *
151
+ * @param {Buffer} buffer
152
+ * @param {{ dataOffset: number, size: number }} cluster
153
+ * @param {number} trackNumber
154
+ * @param {number} secondsPerTick
155
+ * @returns {{ startSeconds: number, durationSeconds: number | null, payload: Buffer }[]}
156
+ */
157
+ static blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick) {
158
+ return blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick);
159
+ }
160
+
161
+ /**
162
+ * Duration and the start of this file's own timeline, per RFC 9559 §5.1.2.
163
+ *
164
+ * Duration is stated in `Info` as a FLOAT in ticks, so it needs the file's
165
+ * `TimestampScale` to become seconds. The start of the timeline is not stated
166
+ * anywhere — Matroska has no such element — so it is the timestamp of the
167
+ * first Cluster, which is what the first frame is placed against.
168
+ *
169
+ * @returns {Promise<import("./Container.js").ContainerMediaInfo>}
170
+ */
171
+ async readMediaInfo() {
172
+ if (this.mediaInfo) {
173
+ return this.mediaInfo;
174
+ }
175
+ /** @type {import("./Container.js").ContainerMediaInfo} */
176
+ const info = { format: this.formatName, durationSeconds: null, startTimeSeconds: null };
177
+ this.mediaInfo = info;
178
+ const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
179
+ if (!head || !isMatroska(head)) {
180
+ return info;
181
+ }
182
+ const segment = findElement(head, ID_SEGMENT, []);
183
+ if (!segment) {
184
+ return info;
185
+ }
186
+ const scale = MatroskaContainer.#timestampScaleOf(head, segment.dataOffset);
187
+ const infoElement = findElement(head, ID_INFO, [], segment.dataOffset);
188
+ if (infoElement) {
189
+ const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
190
+ for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
191
+ if (field.id !== ID_DURATION) {
192
+ continue;
193
+ }
194
+ const ticks = readFloat(head, field.dataOffset, field.size);
195
+ if (ticks !== null && ticks > 0) {
196
+ info.durationSeconds = (ticks * scale) / 1e9;
197
+ }
198
+ break;
199
+ }
200
+ }
201
+ info.startTimeSeconds = await this.#firstClusterSeconds(head, segment.dataOffset, scale);
202
+ return info;
203
+ }
204
+
205
+ /**
206
+ * `TimestampScale` from Info, or the specification's default.
207
+ *
208
+ * @param {Buffer} head
209
+ * @param {number} segmentDataOffset
210
+ * @returns {number} Nanoseconds per tick.
211
+ */
212
+ static #timestampScaleOf(head, segmentDataOffset) {
213
+ const infoElement = findElement(head, ID_INFO, [], segmentDataOffset);
214
+ if (!infoElement) {
215
+ return DEFAULT_TIMESTAMP_SCALE;
216
+ }
217
+ const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
218
+ for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
219
+ if (field.id === ID_TIMESTAMP_SCALE) {
220
+ const scale = readUint(head, field.dataOffset, field.size);
221
+ return scale > 0 ? scale : DEFAULT_TIMESTAMP_SCALE;
222
+ }
223
+ }
224
+ return DEFAULT_TIMESTAMP_SCALE;
225
+ }
226
+
227
+ /**
228
+ * The timestamp of the first Cluster, in seconds.
229
+ *
230
+ * Tried in the head window first, because a muxer writes the first cluster
231
+ * straight after Tracks and both usually fit; a file whose Tracks element is
232
+ * large enough to push it out is answered from the SeekHead instead, with one
233
+ * short read at the position it names.
234
+ *
235
+ * @param {Buffer} head
236
+ * @param {number} segmentDataOffset
237
+ * @param {number} scale - Nanoseconds per tick.
238
+ * @returns {Promise<number | null>} Null when no cluster could be read.
239
+ */
240
+ async #firstClusterSeconds(head, segmentDataOffset, scale) {
241
+ /**
242
+ * @param {Buffer} buffer
243
+ * @param {number} dataOffset
244
+ * @param {number} end
245
+ * @returns {number | null}
246
+ */
247
+ const timestampIn = (buffer, dataOffset, end) => {
248
+ for (const field of iterateElements(buffer, dataOffset, end)) {
249
+ if (field.id === ID_TIMESTAMP) {
250
+ const ticks = readUint(buffer, field.dataOffset, field.size);
251
+ return Number.isFinite(ticks) ? (ticks * scale) / 1e9 : null;
252
+ }
253
+ // Timestamp is written before any frame. Stopping at the first one keeps
254
+ // this from walking a cluster's whole payload, which is megabytes and
255
+ // usually not in the buffer at all.
256
+ if (field.id === ID_SIMPLE_BLOCK || field.id === ID_BLOCK_GROUP) {
257
+ return null;
258
+ }
259
+ }
260
+ return null;
261
+ };
262
+
263
+ for (const element of iterateElements(head, segmentDataOffset, head.length)) {
264
+ if (element.id !== ID_CLUSTER) {
265
+ continue;
266
+ }
267
+ return timestampIn(head, element.dataOffset, Math.min(head.length, element.dataOffset + element.size));
268
+ }
269
+
270
+ const position = MatroskaContainer.#seekPositionOf(head, segmentDataOffset, ID_CLUSTER);
271
+ if (position === null) {
272
+ return null;
273
+ }
274
+ const at = segmentDataOffset + position;
275
+ if (at >= this.fileSize) {
276
+ return null;
277
+ }
278
+ const chunk = await this.readRange(at, Math.min(this.fileSize - 1, at + CLUSTER_PROBE_BYTES - 1));
279
+ if (!chunk) {
280
+ return null;
281
+ }
282
+ for (const element of iterateElements(chunk, 0, chunk.length)) {
283
+ if (element.id !== ID_CLUSTER) {
284
+ continue;
285
+ }
286
+ return timestampIn(chunk, element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
287
+ }
288
+ return null;
289
+ }
290
+
291
+ /**
292
+ * Where the SeekHead says an element lives, relative to the Segment's payload.
293
+ *
294
+ * @param {Buffer} head
295
+ * @param {number} segmentDataOffset
296
+ * @param {number} wantedId
297
+ * @returns {number | null}
298
+ */
299
+ static #seekPositionOf(head, segmentDataOffset, wantedId) {
300
+ const seekHead = findElement(head, ID_SEEK_HEAD, [], segmentDataOffset);
301
+ if (!seekHead) {
302
+ return null;
303
+ }
304
+ const seekHeadEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
305
+ for (const seek of iterateElements(head, seekHead.dataOffset, seekHeadEnd)) {
306
+ if (seek.id !== ID_SEEK) {
307
+ continue;
308
+ }
309
+ const seekEnd = Math.min(seekHeadEnd, seek.dataOffset + seek.size);
310
+ let targetId = null;
311
+ let position = null;
312
+ for (const field of iterateElements(head, seek.dataOffset, seekEnd)) {
313
+ if (field.id === ID_SEEK_ID) {
314
+ targetId = readUint(head, field.dataOffset, field.size);
315
+ } else if (field.id === ID_SEEK_POSITION) {
316
+ position = readUint(head, field.dataOffset, field.size);
317
+ }
318
+ }
319
+ if (targetId === wantedId && position !== null) {
320
+ return position;
321
+ }
322
+ }
323
+ return null;
324
+ }
325
+
326
+
327
+ /**
328
+ * Walk the clusters this file's Cues table names and give up the blocks in
329
+ * every one that is READABLE now, for every track at once.
330
+ *
331
+ * One walk for the whole file, not one per track: a Matroska cluster carries
332
+ * the blocks of every track that has anything to say over its span, so the
333
+ * bytes that answer one track answer them all. Reading them once per track
334
+ * meant the same cluster was fetched and parsed as many times as the film has
335
+ * subtitle tracks measured 2026-08-20 on a film with five: five requests
336
+ * every fifteen seconds, each costing 0.2-5.2 s, for a few kilobytes of cues.
337
+ *
338
+ * Nothing is fetched. `isHeld` decides whether a cluster can be read at all,
339
+ * and one that is not here yet is left for the next call turning subtitles
340
+ * on must not pull bytes the viewer is not waiting for.
341
+ *
342
+ * @param {object} plan - From {@link MatroskaContainer.readSubtitlePlan}.
343
+ * @param {Set<number>} walked - Cluster positions already read; added to.
344
+ * @returns {Promise<Map<number, {startSeconds: number, endSeconds: number|null, text: string}[]>>}
345
+ * Track number to the cues found in THIS pass.
346
+ */
347
+ async walkHeldClusters(plan, walked) {
348
+ /** @type {Map<number, object[]>} */
349
+ const found = new Map();
350
+ // The union of the tracks' cluster lists: each track's list comes from its
351
+ // own Cues entries, so they overlap but do not coincide.
352
+ const positions = new Set();
353
+ for (const candidate of plan?.tracks ?? []) {
354
+ for (const position of candidate.clusterPositions ?? []) {
355
+ positions.add(position);
356
+ }
357
+ }
358
+ for (const position of [...positions].sort((left, right) => left - right)) {
359
+ if (walked.has(position)) {
360
+ continue;
361
+ }
362
+ // The header first: it says how long the cluster is, and a cluster whose
363
+ // bytes are not all here is left for the next time round.
364
+ const probeEnd = Math.min(this.fileSize - 1, position + CLUSTER_HEADER_PROBE - 1);
365
+ if (!this.isHeld(position, probeEnd)) {
366
+ continue;
367
+ }
368
+ const probe = await this.readHeld(position, probeEnd);
369
+ const header = probe && [...iterateElements(probe, 0, probe.length)][0];
370
+ if (!header || header.size <= 0 || header.size > MAX_CLUSTER_BYTES) {
371
+ walked.add(position); // not a cluster this can read; do not look again
372
+ continue;
373
+ }
374
+ const last = Math.min(this.fileSize - 1, position + header.dataOffset + header.size - 1);
375
+ if (!this.isHeld(position, last)) {
376
+ continue;
377
+ }
378
+ const bytes = await this.readHeld(position, last);
379
+ if (!bytes) {
380
+ continue;
381
+ }
382
+ walked.add(position);
383
+ for (const candidate of plan.tracks) {
384
+ const blocks = MatroskaContainer.blocksInCluster(bytes, candidate.trackNumber, plan.secondsPerTick);
385
+ if (blocks.length === 0) {
386
+ continue;
387
+ }
388
+ const into = found.get(candidate.trackNumber) ?? [];
389
+ for (const block of blocks) {
390
+ // The block's bytes become text HERE, where the container that framed
391
+ // them is known. A cue kept framed and unframed later cannot be
392
+ // unframed at all: nothing downstream knows which container it came
393
+ // out of, and guessing from the field count is what showed the
394
+ // dialogue row's own fields to the viewer.
395
+ into.push({
396
+ startSeconds: block.startSeconds,
397
+ endSeconds: block.endSeconds,
398
+ text: MatroskaContainer.cueTextOf(block.payload, candidate.codecId)
399
+ });
400
+ }
401
+ found.set(candidate.trackNumber, into);
402
+ }
403
+ }
404
+ return found;
405
+ }
406
+
407
+ async readTracks() {
408
+ const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
409
+ if (!head || !isMatroska(head)) return [];
410
+
411
+ // Delegate to subtitle plan reader for subtitle tracks (already handles Flags spec-correct),
412
+ // but we need video/audio tracks too. Do a dedicated Tracks walk here for all types,
413
+ // then merge subtitle detail (clusterPositions, declaresDefault etc.) from the plan.
414
+ const seg = findElement(head, 0x18538067, []);
415
+ if (!seg) return [];
416
+ const tracksEl = findElement(head, ID_TRACKS, [], seg.dataOffset);
417
+ if (!tracksEl) return [];
418
+
419
+ const tracksEnd = Math.min(head.length, tracksEl.dataOffset + tracksEl.size);
420
+ /** @type {import("../tracks/index.js").ContainerTrack[]} */
421
+ const result = [];
422
+ // Subtitle declaredIndex is position among subtitle tracks, not global — track per-type counters.
423
+ let subtitleDeclaredIndex = -1;
424
+ let audioDeclaredIndex = -1;
425
+ let videoDeclaredIndex = -1;
426
+
427
+ // For subtitle flag enrichment, read the existing plan (it already does Cues walk)
428
+ let subtitlePlan = null;
429
+ try {
430
+ const shim = async (s, e) => this.readRange(s, Math.min(e, this.fileSize - 1));
431
+ subtitlePlan = await readSubtitlePlan(shim, this.fileSize);
432
+ } catch {
433
+ subtitlePlan = null;
434
+ }
435
+ const declaredByNumber = new Map();
436
+ const planTracksByNumber = new Map();
437
+ if (subtitlePlan?.declared) {
438
+ for (const d of subtitlePlan.declared) declaredByNumber.set(d.trackNumber, d);
439
+ }
440
+ if (subtitlePlan?.tracks) {
441
+ for (const t of subtitlePlan.tracks) planTracksByNumber.set(t.trackNumber, t);
442
+ }
443
+
444
+ for (const entry of iterateElements(head, tracksEl.dataOffset, tracksEnd)) {
445
+ if (entry.id !== ID_TRACK_ENTRY) continue;
446
+ const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
447
+ let trackNumber = null;
448
+ let typeNum = null;
449
+ let codecId = "";
450
+ let language = "";
451
+ let languageBcp47 = "";
452
+ let name = "";
453
+ let codecPrivateB64 = "";
454
+ let isEnabled = true;
455
+ let isDefault = true;
456
+ let declaresDefault = false;
457
+ let isForced = false;
458
+ let isHearing = false;
459
+ let isVisual = false;
460
+ let isOriginal = false;
461
+ let isCommentary = false;
462
+ let pixelWidth = null;
463
+ let pixelHeight = null;
464
+ let displayWidth = null;
465
+ let displayHeight = null;
466
+ let samplingFreq = null;
467
+ let channels = null;
468
+
469
+ for (const f of iterateElements(head, entry.dataOffset, entryEnd)) {
470
+ switch (f.id) {
471
+ case ID_TRACK_NUMBER: trackNumber = readUint(head, f.dataOffset, f.size); break;
472
+ case ID_TRACK_TYPE: typeNum = readUint(head, f.dataOffset, f.size); break;
473
+ case ID_CODEC_ID: codecId = readString(head, f); break;
474
+ case ID_CODEC_PRIVATE: codecPrivateB64 = head.toString("base64", f.dataOffset, f.dataOffset + f.size); break;
475
+ case ID_LANGUAGE: language = readString(head, f); break;
476
+ case ID_LANGUAGE_BCP47: languageBcp47 = readString(head, f); break;
477
+ case ID_NAME: name = readString(head, f); break;
478
+ case ID_FLAG_ENABLED: isEnabled = f.size === 0 || readUint(head, f.dataOffset, f.size) !== 0; break;
479
+ case ID_FLAG_DEFAULT: isDefault = f.size === 0 || readUint(head, f.dataOffset, f.size) === 1; declaresDefault = true; break;
480
+ case ID_FLAG_FORCED: isForced = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
481
+ case ID_FLAG_HEARING: isHearing = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
482
+ case ID_FLAG_VISUAL: isVisual = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
483
+ case ID_FLAG_TEXT_DESCR: break;
484
+ case ID_FLAG_ORIGINAL: isOriginal = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
485
+ case ID_FLAG_COMMENTARY: isCommentary = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
486
+ default: break;
487
+ }
488
+ // Video/Audio sub-elements are nested, not at entry level read separately below.
489
+ }
490
+ if (trackNumber === null) continue;
491
+
492
+ // Parse Video/Audio sub-elements if present
493
+ const videoEl = findElement(head, ID_VIDEO, [], entry.dataOffset, entryEnd);
494
+ if (videoEl) {
495
+ for (const vf of iterateElements(head, videoEl.dataOffset, Math.min(entryEnd, videoEl.dataOffset + videoEl.size))) {
496
+ if (vf.id === ID_PIXEL_WIDTH) pixelWidth = readUint(head, vf.dataOffset, vf.size);
497
+ else if (vf.id === ID_PIXEL_HEIGHT) pixelHeight = readUint(head, vf.dataOffset, vf.size);
498
+ else if (vf.id === ID_DISPLAY_WIDTH) displayWidth = readUint(head, vf.dataOffset, vf.size);
499
+ else if (vf.id === ID_DISPLAY_HEIGHT) displayHeight = readUint(head, vf.dataOffset, vf.size);
500
+ }
501
+ }
502
+ const audioEl = findElement(head, ID_AUDIO, [], entry.dataOffset, entryEnd);
503
+ if (audioEl) {
504
+ for (const af of iterateElements(head, audioEl.dataOffset, Math.min(entryEnd, audioEl.dataOffset + audioEl.size))) {
505
+ if (af.id === ID_SAMPLING_FREQUENCY) {
506
+ // SamplingFrequency is float64
507
+ if (af.size === 8) samplingFreq = head.readDoubleBE(af.dataOffset);
508
+ else samplingFreq = readUint(head, af.dataOffset, af.size);
509
+ } else if (af.id === ID_CHANNELS) channels = readUint(head, af.dataOffset, af.size);
510
+ }
511
+ }
512
+
513
+ // RFC 9559 LanguageBCP47 MUST — when present, Language ignored
514
+ const resolvedLang = languageBcp47 || language;
515
+ const bcpTag = languageBcp47;
516
+
517
+ if (typeNum === 1) {
518
+ videoDeclaredIndex += 1;
519
+ result.push(new VideoTrack({
520
+ trackNumber,
521
+ declaredIndex: videoDeclaredIndex,
522
+ codecId,
523
+ language: resolvedLang,
524
+ languageBcp47: bcpTag,
525
+ name,
526
+ isEnabled,
527
+ isDefault,
528
+ declaresDefault,
529
+ codecPrivateB64,
530
+ width: pixelWidth,
531
+ height: pixelHeight,
532
+ displayWidth,
533
+ displayHeight
534
+ }));
535
+ } else if (typeNum === 2) {
536
+ audioDeclaredIndex += 1;
537
+ result.push(new AudioTrack({
538
+ trackNumber,
539
+ declaredIndex: audioDeclaredIndex,
540
+ codecId,
541
+ language: resolvedLang,
542
+ languageBcp47: bcpTag,
543
+ name,
544
+ isEnabled,
545
+ isDefault,
546
+ declaresDefault,
547
+ codecPrivateB64,
548
+ isOriginal,
549
+ isCommentary,
550
+ isVisualImpaired: isVisual,
551
+ channels,
552
+ samplingFrequency: samplingFreq
553
+ }));
554
+ } else if (typeNum === 17) {
555
+ subtitleDeclaredIndex += 1;
556
+ // Only Forced/Hearing belong to subtitles; Original/Commentary must not leak.
557
+ const declared = declaredByNumber.get(trackNumber);
558
+ const planTrack = planTracksByNumber.get(trackNumber);
559
+ // Prefer plan's flags when available (already spec-correct), else use parsed.
560
+ const finalForced = planTrack ? !!planTrack.isForced : isForced;
561
+ const finalHearing = planTrack ? !!planTrack.isHearingImpaired : isHearing;
562
+ const finalEnabled = declared ? declared.isEnabled !== false : isEnabled;
563
+ const finalDefault = declared ? !!declared.isDefault : isDefault;
564
+ const finalDeclares = declared ? !!declared.declaresDefault : declaresDefault;
565
+ const clusterPositions = planTrack ? planTrack.clusterPositions ?? [] : [];
566
+ const isText = TEXT_CODECS_MATROSKA.has(codecId);
567
+ // disabled image/text tracks still counted (declaredIndex above) — offerable flag controls visibility
568
+ if (isText && finalEnabled) {
569
+ result.push(new TextSubtitleTrack({
570
+ trackNumber,
571
+ declaredIndex: subtitleDeclaredIndex,
572
+ codecId,
573
+ language: resolvedLang,
574
+ languageBcp47: bcpTag,
575
+ name,
576
+ isEnabled: finalEnabled,
577
+ isDefault: finalDefault,
578
+ declaresDefault: finalDeclares,
579
+ codecPrivateB64,
580
+ isForced: finalForced,
581
+ isHearingImpaired: finalHearing,
582
+ clusterPositions
583
+ }));
584
+ } else {
585
+ // Image or disabled — keep declaredIndex, not offerable if disabled
586
+ const Target = isText ? TextSubtitleTrack : ImageSubtitleTrack;
587
+ result.push(new Target({
588
+ trackNumber,
589
+ declaredIndex: subtitleDeclaredIndex,
590
+ codecId,
591
+ language: resolvedLang,
592
+ languageBcp47: bcpTag,
593
+ name,
594
+ isEnabled: finalEnabled,
595
+ isDefault: finalDefault,
596
+ declaresDefault: finalDeclares,
597
+ codecPrivateB64,
598
+ isForced: finalForced,
599
+ isHearingImpaired: finalHearing,
600
+ clusterPositions: isText ? clusterPositions : []
601
+ }));
602
+ }
603
+ } else {
604
+ // Other TrackType (complex, logo, buttons, control) — keep as generic, not video
605
+ result.push(new ContainerTrack({
606
+ trackNumber,
607
+ declaredIndex: -1,
608
+ type: "other",
609
+ codecId,
610
+ language: resolvedLang,
611
+ languageBcp47: bcpTag,
612
+ name,
613
+ isEnabled,
614
+ isDefault,
615
+ declaresDefault,
616
+ codecPrivateB64
617
+ }));
618
+ }
619
+ }
620
+ return result;
621
+ }
622
+
623
+ /**
624
+ * The text field of one cue as Matroska frames it.
625
+ *
626
+ * Two rules, both from `matroska.org/technical/subtitles.html`, "Now, how are
627
+ * they stored in Matroska?":
628
+ *
629
+ * 1. "All text is converted to UTF-8", so the block is decoded as UTF-8 and
630
+ * no other encoding is guessed at. A subtitle FILE is a different matter —
631
+ * there the bytes may be Windows-1251 and `decodeSubtitleBytes` sniffs for
632
+ * it — but a muxer had to convert before writing the block.
633
+ * 2. "Events are stored in the Block in this order: ReadOrder, Layer, Style,
634
+ * Name, MarginL, MarginR, MarginV, Effect, Text", and "Start & End field
635
+ * are used to set TimeStamp and the BlockDuration element". So eight fields
636
+ * stand before the text, the two timing fields of the file's own row are
637
+ * NOT among them, and a read order takes their place at the front. The text
638
+ * itself may hold commas, so everything from the ninth field on is joined
639
+ * back together.
640
+ *
641
+ * `S_TEXT/UTF8` and `S_TEXT/WEBVTT` have no such framing: the block holds the
642
+ * cue text and nothing else. (A WebVTT cue's settings, identifier and
643
+ * preceding comments live in a BlockAddition, which this proxy does not read;
644
+ * losing them costs positioning, not words.)
645
+ *
646
+ * @param {Buffer} payload - The block's own bytes.
647
+ * @param {string} codecId - Matroska CodecID of the track the block belongs to.
648
+ * @returns {string}
649
+ */
650
+ static cueTextOf(payload, codecId) {
651
+ const text = Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "");
652
+ if (codecId !== "S_TEXT/ASS" && codecId !== "S_TEXT/SSA") {
653
+ return text;
654
+ }
655
+ const fields = text.split(",");
656
+ return fields.length > ASS_FIELDS_BEFORE_TEXT ? fields.slice(ASS_FIELDS_BEFORE_TEXT).join(",") : "";
657
+ }
658
+
659
+ async readKeyframeIndex() {
660
+ const times = await readMatroskaKeyframeTimes(this.readRange, this.fileSize);
661
+ if (!times) return null;
662
+ if (Array.isArray(times)) return { times, tolerance: 0 };
663
+ return times;
664
+ }
665
+ }
666
+
667
+ // ---------------------------------------------------------------------------
668
+ // Matroska's own reading of its subtitle tracks and its clusters. It lives in
669
+ // this module because every line of it is a statement of RFC 9559 about how
670
+ // this container stores a subtitle, and the class is the only way in.
671
+ // ---------------------------------------------------------------------------
672
+
673
+ const ID_BLOCK = 0xa1;
674
+ const ID_BLOCK_DURATION = 0x9b;
675
+
676
+ /** Bits 1-2 of the flags byte say how a block is laced, or that it is not. */
677
+ const LACING_MASK = 0x06;
678
+ const LACING_NONE = 0x00;
679
+ const LACING_XIPH = 0x02;
680
+ const LACING_FIXED = 0x04;
681
+ const LACING_EBML = 0x06;
682
+
683
+ /**
684
+ * @typedef {object} SubtitleBlock
685
+ * @property {number} startSeconds - When the cue appears.
686
+ * @property {number | null} durationSeconds - How long it stays, or null when
687
+ * the block carried no duration (a SimpleBlock; the caller decides).
688
+ * @property {Buffer} payload - The block's own bytes, still in the codec's form.
689
+ */
690
+
691
+ /**
692
+ * Read one block's header.
693
+ *
694
+ * @param {Buffer} buffer
695
+ * @param {number} start - First byte of the block's payload.
696
+ * @param {number} end - One past its last byte.
697
+ * @returns {{ trackNumber: number, relativeTicks: number, flags: number, dataOffset: number } | null}
698
+ */
699
+ function readBlockHeader(buffer, start, end) {
700
+ const track = readVint(buffer, start, false);
701
+ if (!track || track.value === null) {
702
+ return null;
703
+ }
704
+ const timestampAt = start + track.length;
705
+ // Signed, and it can be negative: a block may belong slightly before the
706
+ // cluster it is stored in.
707
+ if (timestampAt + 3 > end) {
708
+ return null;
709
+ }
710
+ return {
711
+ trackNumber: Number(track.value),
712
+ relativeTicks: buffer.readInt16BE(timestampAt),
713
+ flags: buffer[timestampAt + 2],
714
+ dataOffset: timestampAt + 3
715
+ };
716
+ }
717
+
718
+ /**
719
+ * Where a laced block's first frame begins.
720
+ *
721
+ * Subtitles are rarely laced, but a block that IS laced starts with a frame
722
+ * count and a table of sizes, and reading the payload without stepping over
723
+ * them yields the table as though it were text.
724
+ *
725
+ * @param {Buffer} buffer
726
+ * @param {number} dataOffset - First byte after the block header.
727
+ * @param {number} end
728
+ * @param {number} flags
729
+ * @returns {number | null} The offset of the first frame, or null when the
730
+ * lacing cannot be read.
731
+ */
732
+ function firstFrameOffset(buffer, dataOffset, end, flags) {
733
+ const lacing = flags & LACING_MASK;
734
+ if (lacing === LACING_NONE) {
735
+ return dataOffset;
736
+ }
737
+ if (dataOffset >= end) {
738
+ return null;
739
+ }
740
+ const frames = buffer[dataOffset] + 1;
741
+ let at = dataOffset + 1;
742
+ if (lacing === LACING_FIXED) {
743
+ return at;
744
+ }
745
+ if (lacing === LACING_XIPH) {
746
+ // Each size but the last is a run of 0xFF bytes ending in a smaller one.
747
+ for (let frame = 0; frame < frames - 1; frame += 1) {
748
+ while (at < end && buffer[at] === 0xff) {
749
+ at += 1;
750
+ }
751
+ at += 1;
752
+ }
753
+ return at <= end ? at : null;
754
+ }
755
+ if (lacing === LACING_EBML) {
756
+ // The first size is a plain variable-length integer, the rest are signed
757
+ // differences from it; either way each is one such integer to step over.
758
+ for (let frame = 0; frame < frames - 1; frame += 1) {
759
+ const size = readVint(buffer, at, false);
760
+ if (!size) {
761
+ return null;
762
+ }
763
+ at += size.length;
764
+ }
765
+ return at <= end ? at : null;
766
+ }
767
+ return null;
768
+ }
769
+
770
+ /**
771
+ * Every block of one track inside one cluster.
772
+ *
773
+ * @param {Buffer} buffer - Bytes holding the cluster's payload.
774
+ * @param {{ dataOffset: number, size: number }} cluster - Where that payload is.
775
+ * @param {number} trackNumber - The track to keep.
776
+ * @param {number} secondsPerTick - From the segment's timestamp scale.
777
+ * @returns {SubtitleBlock[]}
778
+ */
779
+ function blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick) {
780
+ const end = Math.min(buffer.length, cluster.dataOffset + cluster.size);
781
+ /** @type {SubtitleBlock[]} */
782
+ const blocks = [];
783
+ let clusterTicks = null;
784
+
785
+ const take = (blockStart, blockEnd, durationTicks) => {
786
+ const header = readBlockHeader(buffer, blockStart, blockEnd);
787
+ if (!header || header.trackNumber !== trackNumber || clusterTicks === null) {
788
+ return;
789
+ }
790
+ const payloadAt = firstFrameOffset(buffer, header.dataOffset, blockEnd, header.flags);
791
+ if (payloadAt === null || payloadAt >= blockEnd) {
792
+ return;
793
+ }
794
+ blocks.push({
795
+ startSeconds: (clusterTicks + header.relativeTicks) * secondsPerTick,
796
+ durationSeconds: durationTicks === null ? null : durationTicks * secondsPerTick,
797
+ payload: buffer.subarray(payloadAt, blockEnd)
798
+ });
799
+ };
800
+
801
+ for (const element of iterateElements(buffer, cluster.dataOffset, end)) {
802
+ const elementEnd = Math.min(end, element.dataOffset + element.size);
803
+ if (element.id === ID_TIMESTAMP) {
804
+ clusterTicks = readUint(buffer, element.dataOffset, element.size);
805
+ continue;
806
+ }
807
+ if (element.id === ID_SIMPLE_BLOCK) {
808
+ take(element.dataOffset, elementEnd, null);
809
+ continue;
810
+ }
811
+ if (element.id !== ID_BLOCK_GROUP) {
812
+ continue;
813
+ }
814
+ // A group holds the block and, for a subtitle, the duration that says when
815
+ // the cue leaves the screen. Both are read before either is used, because
816
+ // the duration may be written after the block.
817
+ let blockStart = null;
818
+ let blockEnd = null;
819
+ let durationTicks = null;
820
+ for (const field of iterateElements(buffer, element.dataOffset, elementEnd)) {
821
+ const fieldEnd = Math.min(elementEnd, field.dataOffset + field.size);
822
+ if (field.id === ID_BLOCK) {
823
+ blockStart = field.dataOffset;
824
+ blockEnd = fieldEnd;
825
+ } else if (field.id === ID_BLOCK_DURATION) {
826
+ durationTicks = readUint(buffer, field.dataOffset, field.size);
827
+ }
828
+ }
829
+ if (blockStart !== null) {
830
+ take(blockStart, blockEnd, durationTicks);
831
+ }
832
+ }
833
+ return blocks;
834
+ }
835
+
836
+
837
+ /**
838
+ * The rest of what a TrackEntry says about itself, RFC 9559 §5.1.4.1. Read
839
+ * because the file states them and a releaser's own wording in `Name` is the
840
+ * only thing we had before: "fors" and "SDH" in a menu were whatever text
841
+ * someone happened to type.
842
+ *
843
+ * `FlagEnabled` defaults to 1 and means "the track is usable"; a track that
844
+ * says 0 is counted but not offered. `FlagForced` applies only to subtitles and
845
+ * defaults to 0. `FlagHearingImpaired` is set "if and only if the track is
846
+ * suitable for users with hearing impairments". `FlagVisualImpaired`,
847
+ * `FlagOriginal` and `FlagCommentary` bear on the AUDIO choice and are read
848
+ * with that work, not here — see roadmap item 55.
849
+ */
850
+ const ID_FLAG_HEARING_IMPAIRED = 0x55ab;
851
+ /**
852
+ * The language as RFC 5646 writes it. The specification is a MUST: "If this
853
+ * element is used, then any Language elements used in the same TrackEntry MUST
854
+ * be ignored" — so where both are present, this one is the answer and the
855
+ * three-letter code is not.
856
+ */
857
+ const ID_CUES = 0x1c53bb6b;
858
+ const ID_CUE_POINT = 0xbb;
859
+ const ID_CUE_TRACK_POSITIONS = 0xb7;
860
+ const ID_CUE_TRACK = 0xf7;
861
+ const ID_CUE_CLUSTER_POSITION = 0xf1;
862
+
863
+ /** TrackType 17 is subtitles; 1 is video and 2 audio. */
864
+ const TRACK_TYPE_SUBTITLE = 17;
865
+ /** How much of the file start to read: the same window the keyframe reader uses. */
866
+ /** Cap on the Cues read; a long film indexes to tens of KB. */
867
+ const MAX_CUES_BYTES = 8 * 1024 * 1024;
868
+
869
+ /**
870
+ * The codecs whose blocks are text this proxy can turn into WebVTT.
871
+ *
872
+ * `S_TEXT/UTF8` is a plain line of text and needs nothing. `S_TEXT/ASS` and
873
+ * `S_TEXT/SSA` carry a dialogue row whose fields have to be stripped, and their
874
+ * header lives in CodecPrivate — supported, with the stripping done where the
875
+ * cue is turned into WebVTT. `S_HDMV/PGS` and `S_VOBSUB` are pictures, not
876
+ * text, and are deliberately absent: offering them would promise something this
877
+ * path cannot deliver.
878
+ */
879
+ const TEXT_CODECS = new Set(["S_TEXT/UTF8", "S_TEXT/ASS", "S_TEXT/SSA"]);
880
+
881
+ /**
882
+ * @typedef {object} SubtitleTrackPlan
883
+ * @property {number} trackNumber - As the blocks name it.
884
+ * @property {number} declaredIndex - Its position among ALL of the file's
885
+ * subtitle tracks, picture-based ones included — which is the number ffmpeg
886
+ * gives the same stream in `0:s:N`, and therefore the only number the browser
887
+ * ever names. Text tracks alone are not a numbering: a file whose PGS track
888
+ * comes first would have every text track one lower here than in the browser.
889
+ * @property {string} codecId
890
+ * @property {string} language - The language the file declares: its RFC 5646
891
+ * tag where it writes one, and the three-letter code otherwise. The
892
+ * specification requires that order — where `LanguageBCP47` is present, the
893
+ * `Language` element MUST be ignored.
894
+ * @property {string} languageBcp47 - The RFC 5646 tag alone, or "".
895
+ * @property {string} name - What the file calls the track, if anything.
896
+ * @property {boolean} isDefault
897
+ * @property {boolean} isForced - `FlagForced`: the track carries what a viewer
898
+ * needs even when they asked for no subtitles — signs, and dialogue in
899
+ * another language. It does NOT carry the film's own dialogue.
900
+ * @property {boolean} isHearingImpaired - `FlagHearingImpaired`: suitable for
901
+ * viewers who cannot hear, so it carries non-speech sound as well as speech.
902
+ * @property {string} codecPrivate - The ASS/SSA header, base64, or "".
903
+ * @property {number[]} clusterPositions - File offsets of clusters whose cue
904
+ * points name this track, ascending. Empty when the file indexes only its
905
+ * picture, and then the caller has to walk clusters as they arrive instead.
906
+ */
907
+
908
+
909
+ /**
910
+ * Everything about a file's text subtitle tracks that can be learned without
911
+ * reading the film.
912
+ *
913
+ * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
914
+ * @param {number} fileSize
915
+ * @returns {Promise<{ tracks: SubtitleTrackPlan[], declared: object[], secondsPerTick: number, segmentDataOffset: number } | null>}
916
+ */
917
+ async function readSubtitlePlan(readRange, fileSize) {
918
+ const head = await readRange(0, Math.min(HEAD_BYTES, Math.max(0, fileSize - 1)));
919
+ if (!head || head.length < 4 || head.readUInt32BE(0) !== 0x1a45dfa3) {
920
+ return null;
921
+ }
922
+ const segment = findElement(head, ID_SEGMENT, []);
923
+ if (!segment) {
924
+ return null;
925
+ }
926
+ const base = segment.dataOffset;
927
+
928
+ const info = findElement(head, ID_INFO, [], base);
929
+ let scale = DEFAULT_TIMESTAMP_SCALE;
930
+ if (info) {
931
+ const declared = findElement(head, ID_TIMESTAMP_SCALE, [], info.dataOffset, info.dataOffset + info.size);
932
+ if (declared) {
933
+ const value = readUint(head, declared.dataOffset, declared.size);
934
+ if (value > 0) {
935
+ scale = value;
936
+ }
937
+ }
938
+ }
939
+
940
+ const tracksElement = findElement(head, ID_TRACKS, [], base);
941
+ if (!tracksElement) {
942
+ return null;
943
+ }
944
+ const tracksEnd = Math.min(head.length, tracksElement.dataOffset + tracksElement.size);
945
+ /** @type {SubtitleTrackPlan[]} */
946
+ const tracks = [];
947
+ /**
948
+ * Every subtitle track the file declares, in the order the Tracks element
949
+ * names them, text or picture. This is not for extraction — `tracks` is —
950
+ * but for lining ffmpeg's `0:s:N` numbering up against the container, which
951
+ * only holds while nothing is missing from the middle of the list.
952
+ *
953
+ * @type {Array<{ trackNumber: number, codecId: string, language: string, name: string, isDefault: boolean, declaresDefault: boolean }>}
954
+ */
955
+ const declared = [];
956
+ for (const entry of iterateElements(head, tracksElement.dataOffset, tracksEnd)) {
957
+ if (entry.id !== ID_TRACK_ENTRY) {
958
+ continue;
959
+ }
960
+ const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
961
+ let trackNumber = null;
962
+ let type = null;
963
+ let codecId = "";
964
+ let language = "";
965
+ let name = "";
966
+ let codecPrivate = "";
967
+ // Matroska's `FlagDefault` DEFAULTS TO 1, so a file whose muxer wrote it on
968
+ // no track is indistinguishable, once the default has been applied, from
969
+ // one that wrote it on every track — which is how ffmpeg's banner prints it
970
+ // and why the banner cannot answer this. Both are kept: what the flag
971
+ // amounts to, and whether the file said anything at all.
972
+ let isDefault = true;
973
+ let declaresDefault = false;
974
+ // Defaults straight from RFC 9559: a track is usable and not forced unless
975
+ // the file says otherwise, and the impaired flags are absent until claimed.
976
+ let isEnabled = true;
977
+ let isForced = false;
978
+ let isHearingImpaired = false;
979
+ let languageBcp47 = "";
980
+ for (const field of iterateElements(head, entry.dataOffset, entryEnd)) {
981
+ if (field.id === ID_TRACK_NUMBER) {
982
+ trackNumber = readUint(head, field.dataOffset, field.size);
983
+ } else if (field.id === ID_TRACK_TYPE) {
984
+ type = readUint(head, field.dataOffset, field.size);
985
+ } else if (field.id === ID_CODEC_ID) {
986
+ codecId = readString(head, field);
987
+ } else if (field.id === ID_LANGUAGE) {
988
+ language = readString(head, field);
989
+ } else if (field.id === ID_LANGUAGE_BCP47) {
990
+ languageBcp47 = readString(head, field);
991
+ } else if (field.id === ID_NAME) {
992
+ name = readString(head, field);
993
+ } else if (field.id === ID_FLAG_DEFAULT) {
994
+ isDefault = readUint(head, field.dataOffset, field.size) === 1;
995
+ declaresDefault = true;
996
+ } else if (field.id === ID_FLAG_ENABLED) {
997
+ // An element written with zero length carries its default, which for
998
+ // this one is 1 — so an empty element must not read as "unusable", and
999
+ // neither must a value outside the declared 0-1 range. Only an explicit
1000
+ // zero takes a track away.
1001
+ isEnabled = field.size === 0 || readUint(head, field.dataOffset, field.size) !== 0;
1002
+ } else if (field.id === ID_FLAG_FORCED) {
1003
+ isForced = field.size > 0 && readUint(head, field.dataOffset, field.size) !== 0;
1004
+ } else if (field.id === ID_FLAG_HEARING_IMPAIRED) {
1005
+ isHearingImpaired = field.size > 0 && readUint(head, field.dataOffset, field.size) !== 0;
1006
+ } else if (field.id === ID_CODEC_PRIVATE) {
1007
+ codecPrivate = head.toString("base64", field.dataOffset, field.dataOffset + field.size);
1008
+ }
1009
+ }
1010
+ if (type !== TRACK_TYPE_SUBTITLE || trackNumber === null) {
1011
+ continue;
1012
+ }
1013
+ // A track the file marks unusable is still COUNTED. FlagEnabled says "the
1014
+ // track is usable", and a player should not offer it — but ffmpeg does not
1015
+ // drop it: `matroskadec.c` parses `MATROSKA_ID_TRACKFLAGENABLED` as
1016
+ // `EBML_NONE`, reading the element and keeping nothing, so the stream is
1017
+ // created and numbered like any other. Leaving it out of this list would
1018
+ // therefore shift `declaredIndex` off ffmpeg's `0:s:N` for every track
1019
+ // after it, which is the numbering defect this file was fixed for a day
1020
+ // earlier. It is counted here and refused where it is offered instead.
1021
+ //
1022
+ // `language` here stays the three-letter code, because this list exists to
1023
+ // be lined up against ffmpeg's banner, which prints that code. The RFC 5646
1024
+ // tag rides beside it for whoever displays the track.
1025
+ declared.push({
1026
+ trackNumber,
1027
+ codecId,
1028
+ language,
1029
+ languageBcp47,
1030
+ name,
1031
+ isDefault,
1032
+ declaresDefault,
1033
+ isEnabled,
1034
+ isForced,
1035
+ isHearingImpaired
1036
+ });
1037
+ if (!TEXT_CODECS.has(codecId) || !isEnabled) {
1038
+ continue;
1039
+ }
1040
+ tracks.push({
1041
+ trackNumber,
1042
+ declaredIndex: declared.length - 1,
1043
+ codecId,
1044
+ // This list is ours and is not compared with ffmpeg's, so it carries the
1045
+ // language the file states most precisely: where RFC 5646 is written, the
1046
+ // three-letter code MUST be ignored.
1047
+ language: languageBcp47 || language,
1048
+ languageBcp47,
1049
+ name,
1050
+ isDefault,
1051
+ isForced,
1052
+ isHearingImpaired,
1053
+ codecPrivate,
1054
+ clusterPositions: []
1055
+ });
1056
+ }
1057
+ if (tracks.length === 0) {
1058
+ return { tracks, declared, secondsPerTick: scale / 1e9, segmentDataOffset: base };
1059
+ }
1060
+
1061
+ // Where the clusters holding those tracks are. A file that indexes only its
1062
+ // picture leaves these empty, which is not a failure: the caller then reads
1063
+ // the clusters the viewer's own playback brings in.
1064
+ const seekHead = findElement(head, ID_SEEK_HEAD, [], base);
1065
+ let cuesRelative;
1066
+ if (seekHead) {
1067
+ const seekEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
1068
+ for (const seek of iterateElements(head, seekHead.dataOffset, seekEnd)) {
1069
+ if (seek.id !== ID_SEEK) {
1070
+ continue;
1071
+ }
1072
+ let target = null;
1073
+ let position = null;
1074
+ for (const field of iterateElements(head, seek.dataOffset, Math.min(seekEnd, seek.dataOffset + seek.size))) {
1075
+ if (field.id === ID_SEEK_ID) {
1076
+ target = readUint(head, field.dataOffset, field.size);
1077
+ } else if (field.id === ID_SEEK_POSITION) {
1078
+ position = readUint(head, field.dataOffset, field.size);
1079
+ }
1080
+ }
1081
+ if (target === ID_CUES && position !== null) {
1082
+ cuesRelative = position;
1083
+ }
1084
+ }
1085
+ }
1086
+ if (cuesRelative !== undefined) {
1087
+ const cuesAt = base + cuesRelative;
1088
+ if (cuesAt > 0 && cuesAt < fileSize) {
1089
+ const chunk = await readRange(cuesAt, Math.min(fileSize - 1, cuesAt + MAX_CUES_BYTES));
1090
+ const element = chunk && [...iterateElements(chunk, 0, chunk.length)][0];
1091
+ if (element && element.id === ID_CUES) {
1092
+ const body = chunk.subarray(element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
1093
+ const byTrack = new Map(tracks.map((track) => [track.trackNumber, new Set()]));
1094
+ for (const point of iterateElements(body, 0, body.length)) {
1095
+ if (point.id !== ID_CUE_POINT) {
1096
+ continue;
1097
+ }
1098
+ const pointEnd = Math.min(body.length, point.dataOffset + point.size);
1099
+ for (const field of iterateElements(body, point.dataOffset, pointEnd)) {
1100
+ if (field.id !== ID_CUE_TRACK_POSITIONS) {
1101
+ continue;
1102
+ }
1103
+ let cueTrack = null;
1104
+ let position = null;
1105
+ for (const inner of iterateElements(body, field.dataOffset, Math.min(pointEnd, field.dataOffset + field.size))) {
1106
+ if (inner.id === ID_CUE_TRACK) {
1107
+ cueTrack = readUint(body, inner.dataOffset, inner.size);
1108
+ } else if (inner.id === ID_CUE_CLUSTER_POSITION) {
1109
+ position = readUint(body, inner.dataOffset, inner.size);
1110
+ }
1111
+ }
1112
+ if (position !== null && byTrack.has(cueTrack)) {
1113
+ byTrack.get(cueTrack).add(base + position);
1114
+ }
1115
+ }
1116
+ }
1117
+ for (const track of tracks) {
1118
+ track.clusterPositions = [...byTrack.get(track.trackNumber)].sort((left, right) => left - right);
1119
+ }
1120
+ }
1121
+ }
1122
+ }
1123
+ return { tracks, declared, secondsPerTick: scale / 1e9, segmentDataOffset: base };
1124
+ }
1125
+
1126
+ /**
1127
+ * The cues of one track inside one cluster.
1128
+ *
1129
+ * @param {Buffer} bytes - The cluster, from its own element header onward.
1130
+ * @param {number} trackNumber
1131
+ * @param {number} secondsPerTick
1132
+ * @returns {{ startSeconds: number, endSeconds: number | null, text: string }[]}
1133
+ */
1134
+ function harvestCluster(bytes, trackNumber, secondsPerTick) {
1135
+ const header = [...iterateElements(bytes, 0, bytes.length)][0];
1136
+ if (!header) {
1137
+ return [];
1138
+ }
1139
+ const blocks = blocksOfTrack(
1140
+ bytes,
1141
+ { dataOffset: header.dataOffset, size: header.size },
1142
+ trackNumber,
1143
+ secondsPerTick
1144
+ );
1145
+ // The payload is handed on as BYTES. What those bytes mean — which of them
1146
+ // are the text and which are the eight fields Matroska puts before it — is
1147
+ // stated by the container's specification and answered by
1148
+ // `MatroskaContainer.cueTextOf`, not here: this function's subject is where a
1149
+ // block sits and how long it lasts.
1150
+ return blocks.map((block) => ({
1151
+ startSeconds: block.startSeconds,
1152
+ endSeconds: block.durationSeconds === null ? null : block.startSeconds + block.durationSeconds,
1153
+ payload: block.payload
1154
+ }));
1155
+ }