@torrent-tv/proxy 2.88.5 → 2.89.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 (50) hide show
  1. package/AGENTS.md +21 -12
  2. package/CHANGELOG.md +18 -0
  3. package/assets/calibration/audio/NOTICE.md +19 -19
  4. package/assets/calibration/audio/manifest.json +98 -98
  5. package/docs/container-architecture.md +77 -22
  6. package/docs/playback-start-forecast.md +56 -56
  7. package/main2.cpuprofile +1 -0
  8. package/package.json +1 -1
  9. package/scripts/build-audio-samples.mjs +31 -31
  10. package/server.js +42 -27
  11. package/services/encode/EncodeRuns.js +3 -1
  12. package/services/encode/OutputOpening.js +5 -4
  13. package/services/encode/audio-calibration.js +67 -67
  14. package/services/encode/audio-work-rate.js +15 -15
  15. package/services/encode/output/index.js +4 -0
  16. package/services/encode/run-command.js +2 -1
  17. package/services/media/ContainerOrchestrator.js +99 -46
  18. package/services/media/KeyframeTables.js +61 -21
  19. package/services/media/SubtitleCues.js +255 -183
  20. package/services/media/container/AviContainer.js +5 -3
  21. package/services/media/container/Container.js +66 -43
  22. package/services/media/container/ContainerFactory.js +8 -26
  23. package/services/media/container/MatroskaContainer.js +719 -1182
  24. package/services/media/container/Mp4Container.js +83 -73
  25. package/services/media/container/ebml-stream.js +174 -0
  26. package/services/media/container/matroska-clusters.js +1165 -0
  27. package/services/media/container/unavailable.js +77 -0
  28. package/services/media/tracks/ContainerTrack.js +9 -0
  29. package/services/media/tracks/TextSubtitleTrack.js +9 -1
  30. package/services/server/ViewerRequests.js +3 -2
  31. package/services/server/playback-readiness.js +516 -516
  32. package/services/torrent/worker/client.js +6 -2
  33. package/services/torrent/worker/held-bytes.js +84 -8
  34. package/services/torrent/worker/worker.js +10 -2
  35. package/services/transport/data-channel-handler.js +7 -3
  36. package/services/viewer/PriorityMap.js +31 -0
  37. package/test/audio-calibration.test.js +23 -23
  38. package/test/coalesce.test.js +39 -0
  39. package/test/held-read-ownership.test.js +77 -0
  40. package/test/helpers/held-file.js +50 -2
  41. package/test/helpers/matroska-file.js +296 -0
  42. package/test/keyframe-table-budget.test.js +21 -0
  43. package/test/matroska-cluster-discovery.test.js +323 -0
  44. package/test/reads-not-yet-arrived.test.js +218 -0
  45. package/test/segment-store.test.js +14 -0
  46. package/test/subtitle-cue-walk.test.js +16 -1
  47. package/test/subtitle-plan-waits.test.js +125 -0
  48. package/test/subtitle-track-numbering.test.js +8 -3
  49. package/test/viewer-starts-on-map.test.js +27 -0
  50. package/utils/coalesce.js +41 -0
@@ -0,0 +1,1165 @@
1
+ /**
2
+ * @file Where a Matroska file's clusters are, found from the bytes already
3
+ * downloaded, and the subtitle blocks inside them — RFC 9559 §5.1.3.
4
+ *
5
+ * **Why the Cues table is not enough.** It used to be the only way in: the walk
6
+ * read the clusters the Cues table names for a subtitle track and nothing else.
7
+ * RFC 9559 §22.1 says each subtitle frame SHOULD be referenced there — a
8
+ * recommendation, not a guarantee — and a file may have no Cues at all. Such a
9
+ * file showed no subtitles, ever, while a comment promised the walk would read
10
+ * "the clusters the viewer's own playback brings in" instead. Nothing did.
11
+ *
12
+ * **Where a cluster begins is established three ways, and only the first two
13
+ * are proof:**
14
+ *
15
+ * 1. the file says so — the first cluster after the head, and every
16
+ * `CueClusterPosition` of every track (the video's name nearly every
17
+ * cluster, because §22.1 has each keyframe referenced);
18
+ * 2. a chain from a position already established: a level-1 element begins
19
+ * exactly where the one before it ends, so from a cluster whose header is
20
+ * downloaded the next one is known without reading anything else;
21
+ * 3. a search of downloaded bytes for the Cluster id, used only where the file
22
+ * has no Cues. What it finds is a CANDIDATE, checked against the structure a
23
+ * cluster must have before anything is read out of it, and taken back —
24
+ * together with every cue it gave — if a position established by the first
25
+ * two ways later lands inside it.
26
+ *
27
+ * **What is kept between passes, and what is not.** A cluster read whole is
28
+ * DONE and never read again. One whose bytes are not all downloaded is left as
29
+ * it is: nothing about it is recorded, because "not here yet" is not a fact
30
+ * about the cluster (`unavailable.js`). One whose downloaded, hash-verified
31
+ * bytes do not parse is UNREADABLE, with its reason, and not tried again —
32
+ * reading the same bytes again gives the same answer.
33
+ *
34
+ * **Order, and when a pass ends.** The cluster a viewer is standing in is read
35
+ * first, then the one before it — a line on screen now may have started there.
36
+ * A pass that had such clusters to read ends with them, so what is on screen is
37
+ * pushed after two clusters rather than after the whole file; it says `more`,
38
+ * and the caller runs the next pass at once. A pass with nothing of that kind
39
+ * reads onward from the viewers, one viewer's next cluster after another's, and
40
+ * then the rest — and stops, saying `more`, the moment a viewer is somewhere
41
+ * else, so a seek is answered by the next pass and not after the whole film.
42
+ */
43
+
44
+ import { crc32 } from "node:zlib";
45
+ import { readUint, readVint } from "./ebml-reader.js";
46
+ import { ElementReader, MAX_HEADER_BYTES } from "./ebml-stream.js";
47
+ import { isUnavailable } from "./unavailable.js";
48
+
49
+ const ID_CLUSTER = 0x1f43b675;
50
+ const CLUSTER_ID_BYTES = Buffer.from([0x1f, 0x43, 0xb6, 0x75]);
51
+
52
+ /** The top-level elements of a Segment (RFC 9559 §5.1), Void and CRC-32 aside. */
53
+ const LEVEL_ONE = new Set([
54
+ ID_CLUSTER,
55
+ 0x1c53bb6b, // Cues
56
+ 0x114d9b74, // SeekHead
57
+ 0x1549a966, // Info
58
+ 0x1654ae6b, // Tracks
59
+ 0x1043a770, // Chapters
60
+ 0x1941a469, // Attachments
61
+ 0x1254c367 // Tags
62
+ ]);
63
+
64
+ const ID_CRC32 = 0xbf;
65
+ const ID_VOID = 0xec;
66
+ const ID_TIMESTAMP = 0xe7;
67
+ const ID_SILENT_TRACKS = 0x5854;
68
+ const ID_POSITION = 0xa7;
69
+ const ID_PREV_SIZE = 0xab;
70
+ const ID_SIMPLE_BLOCK = 0xa3;
71
+ const ID_BLOCK_GROUP = 0xa0;
72
+ const ID_ENCRYPTED_BLOCK = 0xaf;
73
+ const ID_BLOCK = 0xa1;
74
+ const ID_BLOCK_DURATION = 0x9b;
75
+
76
+ /** The children RFC 9559 §5.1.3 allows inside a Cluster, the global two included. */
77
+ const CLUSTER_CHILDREN = new Set([
78
+ ID_CRC32,
79
+ ID_VOID,
80
+ ID_TIMESTAMP,
81
+ ID_SILENT_TRACKS,
82
+ ID_POSITION,
83
+ ID_PREV_SIZE,
84
+ ID_SIMPLE_BLOCK,
85
+ ID_BLOCK_GROUP,
86
+ ID_ENCRYPTED_BLOCK
87
+ ]);
88
+
89
+ /**
90
+ * Enough of a cluster's start to hold its header, a CRC-32 and the Timestamp
91
+ * that follows it (§5.1.3.1: first, or second after a CRC-32).
92
+ */
93
+ const CLUSTER_START_PROBE = 64;
94
+
95
+ /**
96
+ * The bytes one read of a cluster's structure takes: an element header and the
97
+ * start of a block's data, which names the block's track — a track number is a
98
+ * vint of at most 8 bytes (RFC 9559 §10.1). Reading a cluster this way moves
99
+ * the headers of its video and audio blocks across the thread boundary and
100
+ * none of their frames.
101
+ */
102
+ const STRUCTURE_READ_BYTES = MAX_HEADER_BYTES + 8;
103
+
104
+ /** Bits 1-2 of a block's flags byte say how it is laced, or that it is not. */
105
+ const LACING_MASK = 0x06;
106
+ const LACING_NONE = 0x00;
107
+ const LACING_XIPH = 0x02;
108
+ const LACING_FIXED = 0x04;
109
+ const LACING_EBML = 0x06;
110
+
111
+ /**
112
+ * A block's own header: its track, its time relative to the cluster, its flags.
113
+ *
114
+ * @param {Buffer} buffer
115
+ * @param {number} start - First byte of the block's data.
116
+ * @param {number} end - One past its last byte.
117
+ * @returns {{ trackNumber: number, relativeTicks: number, flags: number, dataOffset: number } | null}
118
+ */
119
+ export function readBlockHeader(buffer, start, end) {
120
+ const track = readVint(buffer, start, false);
121
+ if (!track || track.value === null) {
122
+ return null;
123
+ }
124
+ const timestampAt = start + track.length;
125
+ // Signed, and it can be negative: a block may belong slightly before the
126
+ // cluster it is stored in.
127
+ if (timestampAt + 3 > end) {
128
+ return null;
129
+ }
130
+ return {
131
+ trackNumber: Number(track.value),
132
+ relativeTicks: buffer.readInt16BE(timestampAt),
133
+ flags: buffer[timestampAt + 2],
134
+ dataOffset: timestampAt + 3
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Where a laced block's first frame begins.
140
+ *
141
+ * @param {Buffer} buffer
142
+ * @param {number} dataOffset - First byte after the block header.
143
+ * @param {number} end
144
+ * @param {number} flags
145
+ * @returns {number | null}
146
+ */
147
+ export function firstFrameOffset(buffer, dataOffset, end, flags) {
148
+ const lacing = flags & LACING_MASK;
149
+ if (lacing === LACING_NONE) {
150
+ return dataOffset;
151
+ }
152
+ if (dataOffset >= end) {
153
+ return null;
154
+ }
155
+ const frames = buffer[dataOffset] + 1;
156
+ let at = dataOffset + 1;
157
+ if (lacing === LACING_FIXED) {
158
+ return at;
159
+ }
160
+ if (lacing === LACING_XIPH) {
161
+ for (let frame = 0; frame < frames - 1; frame += 1) {
162
+ while (at < end && buffer[at] === 0xff) {
163
+ at += 1;
164
+ }
165
+ at += 1;
166
+ }
167
+ return at <= end ? at : null;
168
+ }
169
+ if (lacing === LACING_EBML) {
170
+ for (let frame = 0; frame < frames - 1; frame += 1) {
171
+ const size = readVint(buffer, at, false);
172
+ if (!size) {
173
+ return null;
174
+ }
175
+ at += size.length;
176
+ }
177
+ return at <= end ? at : null;
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /**
183
+ * The walk's own record of one file, kept by the caller between passes.
184
+ *
185
+ * @typedef {object} ClusterStart
186
+ * @property {"first" | "cues" | "chain" | "search"} source
187
+ * @property {number | null} parent - The start this one was chained from.
188
+ * @property {number | null} seconds - The cluster's Timestamp, once read.
189
+ * @property {"cluster" | "other" | null} kind - Null until its header is read.
190
+ * @property {number | null} end - One past its last byte, null while unknown.
191
+ * @property {boolean} stepped - Whether the next start has been taken from it.
192
+ */
193
+
194
+ /**
195
+ * @param {object} progress
196
+ * @returns {object}
197
+ */
198
+ function stateOf(progress) {
199
+ if (!progress.matroska) {
200
+ progress.matroska = {
201
+ seeded: false,
202
+ /** @type {Map<number, ClusterStart>} */
203
+ starts: new Map(),
204
+ done: new Set(),
205
+ /** @type {Map<number, string>} */
206
+ unreadable: new Map(),
207
+ /** Candidates whose bytes are not all here yet. @type {Set<number>} */
208
+ candidates: new Set(),
209
+ /** Candidates the structure check refused. @type {Set<number>} */
210
+ rejected: new Set(),
211
+ /** Inclusive intervals the search has finished with. @type {Array<[number, number]>} */
212
+ scanned: [],
213
+ stats: { refusedElements: 0, rejectedCandidates: 0, contradictions: 0, bytesWalked: 0, fromSearch: 0 }
214
+ };
215
+ }
216
+ return progress.matroska;
217
+ }
218
+
219
+ /**
220
+ * The start a chain of starts began from.
221
+ *
222
+ * @param {Map<number, ClusterStart>} starts
223
+ * @param {number} at
224
+ * @returns {ClusterStart | undefined}
225
+ */
226
+ function rootOf(starts, at) {
227
+ let current = starts.get(at);
228
+ const seen = new Set();
229
+ while (current && current.parent !== null && !seen.has(current.parent)) {
230
+ seen.add(current.parent);
231
+ const parent = starts.get(current.parent);
232
+ if (!parent) {
233
+ break;
234
+ }
235
+ current = parent;
236
+ }
237
+ return current;
238
+ }
239
+
240
+ /**
241
+ * Whether every byte of an inclusive range lies in one downloaded run.
242
+ *
243
+ * @param {Array<[number, number]>} ranges
244
+ * @param {number} start
245
+ * @returns {number} One past the end of the run holding `start`, or `start`.
246
+ */
247
+ function runEndFrom(ranges, start) {
248
+ for (const [from, to] of ranges) {
249
+ if (start >= from && start <= to) {
250
+ return to + 1;
251
+ }
252
+ }
253
+ return start;
254
+ }
255
+
256
+ /**
257
+ * The Timestamp of a cluster, read from its first children.
258
+ *
259
+ * Only the children inside the probe are looked at: the Timestamp is the first
260
+ * child or the second after a CRC-32, and a cluster that puts it later is read
261
+ * whole when it is processed.
262
+ *
263
+ * @param {ElementReader} reader
264
+ * @param {{ dataOffset: number, end: number | null }} header
265
+ * @param {number} limit
266
+ * @param {number} secondsPerTick
267
+ * @returns {Promise<number | null>}
268
+ */
269
+ async function leadingTimestamp(reader, header, limit, secondsPerTick) {
270
+ let at = header.dataOffset;
271
+ const stop = Math.min(limit, header.end ?? limit, header.dataOffset + CLUSTER_START_PROBE);
272
+ while (at < stop) {
273
+ const child = await reader.header(at, header.end ?? limit);
274
+ if (!child || child.size === null) {
275
+ return null;
276
+ }
277
+ if (child.id === ID_TIMESTAMP) {
278
+ const bytes = await reader.bytes(child.dataOffset, child.size);
279
+ return readUint(bytes, 0, child.size) * secondsPerTick;
280
+ }
281
+ if (child.id !== ID_CRC32 && child.id !== ID_VOID) {
282
+ return null;
283
+ }
284
+ at = child.end;
285
+ }
286
+ return null;
287
+ }
288
+
289
+ /**
290
+ * Take the next start from every start whose header is downloaded.
291
+ *
292
+ * @param {object} state
293
+ * @param {object} plan
294
+ * @param {import("./Container.js").HeldReader} held
295
+ * @param {ElementReader} reader
296
+ * @returns {Promise<void>}
297
+ */
298
+ async function extendChains(state, plan, held, reader) {
299
+ const queue = [...state.starts.entries()].filter(([, start]) => !start.stepped).map(([at]) => at);
300
+ while (queue.length > 0) {
301
+ const at = queue.shift();
302
+ const start = state.starts.get(at);
303
+ if (!start || start.stepped || state.unreadable.has(at)) {
304
+ continue;
305
+ }
306
+ const probeEnd = Math.min(plan.fileSize, at + CLUSTER_START_PROBE) - 1;
307
+ if (!held.isHeld(at, Math.min(probeEnd, at + MAX_HEADER_BYTES - 1))) {
308
+ continue;
309
+ }
310
+ let header;
311
+ try {
312
+ header = await reader.header(at, plan.segmentEnd);
313
+ } catch (error) {
314
+ if (isUnavailable(error)) {
315
+ continue;
316
+ }
317
+ throw error;
318
+ }
319
+ start.stepped = true;
320
+ if (!header || !(LEVEL_ONE.has(header.id) || header.id === ID_VOID || header.id === ID_CRC32)) {
321
+ // A position the file itself names (or one a chain led to) that holds no
322
+ // top-level element: the file is damaged here, and reading it again gives
323
+ // the same bytes.
324
+ state.unreadable.set(at, "no top-level element at a position established as a cluster start");
325
+ continue;
326
+ }
327
+ start.kind = header.id === ID_CLUSTER ? "cluster" : "other";
328
+ start.end = header.end;
329
+ if (start.kind === "cluster" && start.seconds === null && held.isHeld(at, probeEnd)) {
330
+ try {
331
+ start.seconds = await leadingTimestamp(reader, header, plan.segmentEnd, plan.secondsPerTick);
332
+ } catch (error) {
333
+ if (!isUnavailable(error)) {
334
+ throw error;
335
+ }
336
+ }
337
+ }
338
+ if (header.end === null) {
339
+ // An unknown size is legal for a cluster (RFC 9559 §5.1.3); where it ends
340
+ // is learned when it is read.
341
+ continue;
342
+ }
343
+ addStart(state, header.end, plan, { source: "chain", parent: at }, queue);
344
+ }
345
+ }
346
+
347
+ /**
348
+ * @param {object} state
349
+ * @param {number} at
350
+ * @param {object} plan
351
+ * @param {{ source: ClusterStart["source"], parent: number | null, seconds?: number | null }} origin
352
+ * @param {number[]} [queue]
353
+ * @returns {void}
354
+ */
355
+ function addStart(state, at, plan, origin, queue) {
356
+ if (!(at < plan.segmentEnd) || at < plan.firstClusterAt) {
357
+ return;
358
+ }
359
+ const known = state.starts.get(at);
360
+ if (known) {
361
+ // The same position reached a second way. A start the file established
362
+ // outranks one the search found, and keeps nothing of its doubt.
363
+ if (known.source === "search" && origin.source !== "search") {
364
+ known.source = origin.source;
365
+ known.parent = origin.parent;
366
+ }
367
+ if (known.seconds === null && Number.isFinite(origin.seconds)) {
368
+ known.seconds = origin.seconds;
369
+ }
370
+ return;
371
+ }
372
+ state.starts.set(at, {
373
+ source: origin.source,
374
+ parent: origin.parent,
375
+ seconds: Number.isFinite(origin.seconds) ? origin.seconds : null,
376
+ kind: null,
377
+ end: null,
378
+ stepped: false
379
+ });
380
+ state.candidates.delete(at);
381
+ queue?.push(at);
382
+ }
383
+
384
+ /**
385
+ * The spans of the clusters already known, as inclusive intervals.
386
+ *
387
+ * @param {object} state
388
+ * @returns {Array<[number, number]>}
389
+ */
390
+ function knownSpans(state) {
391
+ const spans = [];
392
+ for (const [at, start] of state.starts) {
393
+ if (start.kind !== null && start.end !== null) {
394
+ spans.push([at, start.end - 1]);
395
+ }
396
+ }
397
+ return spans.sort((left, right) => left[0] - right[0]);
398
+ }
399
+
400
+ /**
401
+ * `[from, to]` with every interval in `taken` removed.
402
+ *
403
+ * @param {number} from
404
+ * @param {number} to
405
+ * @param {Array<[number, number]>} taken - Sorted.
406
+ * @returns {Array<[number, number]>}
407
+ */
408
+ function subtract(from, to, taken) {
409
+ const left = [];
410
+ let cursor = from;
411
+ for (const [start, end] of taken) {
412
+ if (end < cursor || start > to) {
413
+ continue;
414
+ }
415
+ if (start > cursor) {
416
+ left.push([cursor, start - 1]);
417
+ }
418
+ cursor = Math.max(cursor, end + 1);
419
+ if (cursor > to) {
420
+ break;
421
+ }
422
+ }
423
+ if (cursor <= to) {
424
+ left.push([cursor, to]);
425
+ }
426
+ return left;
427
+ }
428
+
429
+ /**
430
+ * Search downloaded bytes the search has not finished with for the Cluster id.
431
+ *
432
+ * The last `MAX_HEADER_BYTES - 1` bytes of every downloaded run are left
433
+ * unfinished: an id and a size cut by the end of the run are found when the run
434
+ * grows, by searching those bytes again.
435
+ *
436
+ * Each position found is decided at once ({@link settleCandidate}); one that is
437
+ * accepted is followed by its chain, and the search goes on after the chain
438
+ * ends. A file whose clusters follow one another is therefore searched only up
439
+ * to its first cluster after each gap, and the rest is known by its headers.
440
+ *
441
+ * @param {object} state
442
+ * @param {object} plan
443
+ * @param {import("./Container.js").HeldReader} held
444
+ * @param {{ whole: ElementReader, structure: ElementReader }} readers
445
+ * @returns {Promise<void>}
446
+ */
447
+ async function searchForClusters(state, plan, held, readers) {
448
+ const portion = Number.isFinite(held.portionBytes) && held.portionBytes > 0 ? held.portionBytes : plan.fileSize;
449
+ const idLength = CLUSTER_ID_BYTES.length;
450
+ for (const [runFrom, runTo] of held.ranges) {
451
+ const from = Math.max(runFrom, plan.firstClusterAt);
452
+ const to = Math.min(runTo, plan.segmentEnd - 1);
453
+ let at = from;
454
+ while (at + idLength - 1 <= to) {
455
+ // What is left to look at is worked out afresh at every step: a cluster
456
+ // accepted below starts a chain, and the bytes the chain covers are
457
+ // stepped over rather than searched. They are not marked as searched, so
458
+ // if the chain is ever taken back they are searched then.
459
+ const taken = [...state.scanned, ...knownSpans(state)].sort((left, right) => left[0] - right[0]);
460
+ const next = subtract(at, to, taken)[0];
461
+ if (!next || next[1] - next[0] + 1 < idLength) {
462
+ break;
463
+ }
464
+ const [start, end] = next;
465
+ const last = Math.min(end, start + portion - 1);
466
+ const bytes = await held.read(start, last);
467
+ state.stats.bytesWalked += bytes.length;
468
+ let accepted = null;
469
+ let found = bytes.indexOf(CLUSTER_ID_BYTES);
470
+ while (found >= 0) {
471
+ const position = start + found;
472
+ if (!state.starts.has(position) && !state.rejected.has(position)) {
473
+ const outcome = await settleCandidate(state, plan, held, readers, position);
474
+ if (outcome === "accepted") {
475
+ accepted = position;
476
+ break;
477
+ }
478
+ }
479
+ found = bytes.indexOf(CLUSTER_ID_BYTES, found + 1);
480
+ }
481
+ if (accepted !== null) {
482
+ if (accepted - 1 >= start) {
483
+ state.scanned = mergeIntervals([...state.scanned, [start, accepted - 1]]);
484
+ }
485
+ at = accepted;
486
+ continue;
487
+ }
488
+ if (last < end) {
489
+ // Every position whose whole id lies in this portion has been looked
490
+ // at; the next portion overlaps by the id's length less one, so an id
491
+ // cut by the boundary is found there.
492
+ state.scanned = mergeIntervals([...state.scanned, [start, last - idLength + 1]]);
493
+ at = last - idLength + 2;
494
+ continue;
495
+ }
496
+ // Held back only where the RUN ends here: a span that ends at a known
497
+ // element's boundary has nothing after it that could complete an id.
498
+ const runEndsHere = end === to && runTo < plan.segmentEnd - 1;
499
+ const finished = runEndsHere ? end - (MAX_HEADER_BYTES - 1) : end;
500
+ if (finished >= start) {
501
+ state.scanned = mergeIntervals([...state.scanned, [start, finished]]);
502
+ }
503
+ at = end + 1;
504
+ }
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Decide one position the search found the Cluster ID at.
510
+ *
511
+ * Accepted, it becomes a start and its chain is followed at once, so the
512
+ * clusters after it are known by their headers and never searched for.
513
+ *
514
+ * @param {object} state
515
+ * @param {object} plan
516
+ * @param {import("./Container.js").HeldReader} held
517
+ * @param {{ whole: ElementReader, structure: ElementReader }} readers
518
+ * @param {number} at
519
+ * @returns {Promise<"accepted" | "rejected" | "pending">}
520
+ */
521
+ async function settleCandidate(state, plan, held, readers, at) {
522
+ if (knownSpans(state).some(([from, to]) => at > from && at <= to)) {
523
+ // Inside an element whose bounds are known: not a cluster start.
524
+ state.candidates.delete(at);
525
+ state.rejected.add(at);
526
+ return "rejected";
527
+ }
528
+ const verdict = await verifyCandidate(readers.whole, at, plan, state, held);
529
+ if (verdict.status === "pending") {
530
+ state.candidates.add(at);
531
+ return "pending";
532
+ }
533
+ state.candidates.delete(at);
534
+ if (verdict.status === "rejected") {
535
+ state.rejected.add(at);
536
+ state.stats.rejectedCandidates += 1;
537
+ return "rejected";
538
+ }
539
+ addStart(state, at, plan, { source: "search", parent: null, seconds: verdict.seconds });
540
+ const start = state.starts.get(at);
541
+ if (start) {
542
+ start.kind = "cluster";
543
+ start.end = verdict.end;
544
+ }
545
+ await extendChains(state, plan, held, readers.structure);
546
+ return "accepted";
547
+ }
548
+
549
+ /**
550
+ * @param {Array<[number, number]>} intervals
551
+ * @returns {Array<[number, number]>}
552
+ */
553
+ function mergeIntervals(intervals) {
554
+ const sorted = [...intervals].sort((left, right) => left[0] - right[0]);
555
+ const merged = [];
556
+ for (const [start, end] of sorted) {
557
+ const last = merged[merged.length - 1];
558
+ if (last && start <= last[1] + 1) {
559
+ last[1] = Math.max(last[1], end);
560
+ } else {
561
+ merged.push([start, end]);
562
+ }
563
+ }
564
+ return merged;
565
+ }
566
+
567
+ /**
568
+ * The confirmed starts nearest a position on either side, with their times.
569
+ *
570
+ * @param {object} state
571
+ * @param {number} at
572
+ * @returns {{ before: { at: number, start: ClusterStart } | null, after: { at: number, start: ClusterStart } | null }}
573
+ */
574
+ function neighboursOf(state, at) {
575
+ let before = null;
576
+ let after = null;
577
+ for (const [position, start] of state.starts) {
578
+ if (start.kind !== "cluster") {
579
+ continue;
580
+ }
581
+ if (position < at && (!before || position > before.at)) {
582
+ before = { at: position, start };
583
+ } else if (position > at && (!after || position < after.at)) {
584
+ after = { at: position, start };
585
+ }
586
+ }
587
+ return { before, after };
588
+ }
589
+
590
+ /**
591
+ * Check a candidate against everything a cluster must be.
592
+ *
593
+ * Every child is one RFC 9559 §5.1.3 allows; there is exactly one Timestamp,
594
+ * wherever it stands; the children fill the cluster exactly; every block names a
595
+ * track the file declares; a CRC-32, where there is one, matches; a PrevSize,
596
+ * where there is one and the cluster before is known, matches; and the time
597
+ * lies between the times of the known clusters either side.
598
+ *
599
+ * @param {ElementReader} reader
600
+ * @param {number} at
601
+ * @param {object} plan
602
+ * @param {object} state
603
+ * @param {import("./Container.js").HeldReader} held
604
+ * @returns {Promise<{ status: "pending" } | { status: "rejected", reason: string } | { status: "confirmed", end: number, seconds: number }>}
605
+ */
606
+ async function verifyCandidate(reader, at, plan, state, held) {
607
+ try {
608
+ const header = await reader.header(at, plan.segmentEnd);
609
+ if (!header || header.id !== ID_CLUSTER) {
610
+ return { status: "rejected", reason: "no cluster header" };
611
+ }
612
+ if (header.end !== null && header.end > plan.segmentEnd) {
613
+ return { status: "rejected", reason: "runs past the segment" };
614
+ }
615
+ if (header.end !== null && !held.isHeld(at, header.end - 1)) {
616
+ return { status: "pending" };
617
+ }
618
+ const limit = header.end ?? plan.segmentEnd;
619
+ let cursor = header.dataOffset;
620
+ let timestamps = 0;
621
+ let ticks = null;
622
+ let crc = null;
623
+ let crcEnd = null;
624
+ let prevSize = null;
625
+ let end = header.end;
626
+ let first = true;
627
+ while (cursor < limit) {
628
+ if (!held.isHeld(cursor, Math.min(plan.fileSize, cursor + MAX_HEADER_BYTES) - 1)) {
629
+ return { status: "pending" };
630
+ }
631
+ const child = await reader.header(cursor, limit);
632
+ if (!child) {
633
+ return { status: "rejected", reason: "a child header does not parse" };
634
+ }
635
+ if (header.end === null && LEVEL_ONE.has(child.id)) {
636
+ end = cursor;
637
+ break;
638
+ }
639
+ if (!CLUSTER_CHILDREN.has(child.id)) {
640
+ return { status: "rejected", reason: `0x${child.id.toString(16)} is not a cluster child` };
641
+ }
642
+ if (child.size === null || child.end > limit) {
643
+ return { status: "rejected", reason: "a child runs past the cluster" };
644
+ }
645
+ if (child.id === ID_CRC32) {
646
+ if (!first || child.size !== 4) {
647
+ return { status: "rejected", reason: "a CRC-32 that is not the first child" };
648
+ }
649
+ crc = (await reader.bytes(child.dataOffset, 4)).readUInt32LE(0);
650
+ crcEnd = child.end;
651
+ } else if (child.id === ID_TIMESTAMP) {
652
+ timestamps += 1;
653
+ ticks = readUint(await reader.bytes(child.dataOffset, child.size), 0, child.size);
654
+ } else if (child.id === ID_PREV_SIZE) {
655
+ prevSize = readUint(await reader.bytes(child.dataOffset, child.size), 0, child.size);
656
+ } else if (child.id === ID_SIMPLE_BLOCK || child.id === ID_BLOCK_GROUP) {
657
+ const track = await blockTrackOf(reader, child);
658
+ if (track === null || !plan.allTrackNumbers.includes(track)) {
659
+ return { status: "rejected", reason: "a block names no declared track" };
660
+ }
661
+ }
662
+ first = false;
663
+ cursor = child.end;
664
+ }
665
+ if (end === null) {
666
+ end = limit;
667
+ }
668
+ if (cursor !== end) {
669
+ return { status: "rejected", reason: "the children do not fill the cluster" };
670
+ }
671
+ if (timestamps !== 1) {
672
+ return { status: "rejected", reason: `${timestamps} Timestamp elements` };
673
+ }
674
+ if (crc !== null) {
675
+ // RFC 8794 §11.3.1: the CRC covers every byte of the parent's data after
676
+ // the CRC-32 element itself, stored little-endian.
677
+ const computed = await crcOf(reader, crcEnd, end, held.portionBytes);
678
+ if (computed !== crc) {
679
+ return { status: "rejected", reason: "CRC-32 does not match" };
680
+ }
681
+ }
682
+ const seconds = ticks * plan.secondsPerTick;
683
+ const { before, after } = neighboursOf(state, at);
684
+ if (prevSize !== null && before && before.start.end === at && prevSize !== at - before.at) {
685
+ return { status: "rejected", reason: "PrevSize does not match the cluster before" };
686
+ }
687
+ if (before && before.start.seconds !== null && seconds < before.start.seconds) {
688
+ return { status: "rejected", reason: "earlier than the cluster before it" };
689
+ }
690
+ if (after && after.start.seconds !== null && seconds > after.start.seconds) {
691
+ return { status: "rejected", reason: "later than the cluster after it" };
692
+ }
693
+ return { status: "confirmed", end, seconds };
694
+ } catch (error) {
695
+ if (isUnavailable(error)) {
696
+ return { status: "pending" };
697
+ }
698
+ throw error;
699
+ }
700
+ }
701
+
702
+ /**
703
+ * CRC-32 (IEEE 802.3, RFC 8794 §11.3.1) of a span, a portion at a time.
704
+ *
705
+ * @param {ElementReader} reader
706
+ * @param {number} from
707
+ * @param {number} to - One past the last byte.
708
+ * @param {number} portionBytes
709
+ * @returns {Promise<number>}
710
+ */
711
+ async function crcOf(reader, from, to, portionBytes) {
712
+ const step = Number.isFinite(portionBytes) && portionBytes > 0 ? portionBytes : to - from;
713
+ let value = 0;
714
+ for (let at = from; at < to; at += step) {
715
+ value = crc32(await reader.bytes(at, Math.min(step, to - at)), value);
716
+ }
717
+ return value >>> 0;
718
+ }
719
+
720
+ /**
721
+ * The track a SimpleBlock or a BlockGroup's Block belongs to, read from its
722
+ * first bytes only.
723
+ *
724
+ * @param {ElementReader} reader
725
+ * @param {import("./ebml-stream.js").ElementHeader} child
726
+ * @returns {Promise<number | null>}
727
+ */
728
+ async function blockTrackOf(reader, child) {
729
+ if (child.id === ID_SIMPLE_BLOCK) {
730
+ const head = await reader.peek(child, 8);
731
+ const track = readVint(head, 0, false);
732
+ return track ? track.value : null;
733
+ }
734
+ let at = child.dataOffset;
735
+ while (at < child.end) {
736
+ const inner = await reader.header(at, child.end);
737
+ if (!inner || inner.size === null) {
738
+ return null;
739
+ }
740
+ if (inner.id === ID_BLOCK) {
741
+ const head = await reader.peek(inner, 8);
742
+ const track = readVint(head, 0, false);
743
+ return track ? track.value : null;
744
+ }
745
+ at = inner.end;
746
+ }
747
+ return null;
748
+ }
749
+
750
+ /**
751
+ * Take back a start the search found, and everything chained from it, when a
752
+ * start the file established lands inside it — or it inside one.
753
+ *
754
+ * @param {object} state
755
+ * @returns {number[]} The cluster starts withdrawn, whose cues must be taken back.
756
+ */
757
+ function withdrawContradicted(state) {
758
+ const established = [];
759
+ const searched = [];
760
+ for (const [at, start] of state.starts) {
761
+ if (start.kind !== "cluster") {
762
+ continue;
763
+ }
764
+ const root = rootOf(state.starts, at);
765
+ (root?.source === "search" ? searched : established).push([at, start]);
766
+ }
767
+ const contradicted = new Set();
768
+ for (const [at, start] of searched) {
769
+ for (const [other, otherStart] of established) {
770
+ const insideIt = start.end !== null && other > at && other < start.end;
771
+ const itInside = otherStart.end !== null && at > other && at < otherStart.end;
772
+ if (insideIt || itInside) {
773
+ contradicted.add(at);
774
+ break;
775
+ }
776
+ }
777
+ }
778
+ if (contradicted.size === 0) {
779
+ return [];
780
+ }
781
+ // Everything chained from a withdrawn start goes with it.
782
+ let grew = true;
783
+ while (grew) {
784
+ grew = false;
785
+ for (const [at, start] of state.starts) {
786
+ if (!contradicted.has(at) && start.parent !== null && contradicted.has(start.parent)) {
787
+ contradicted.add(at);
788
+ grew = true;
789
+ }
790
+ }
791
+ }
792
+ const withdrawn = [];
793
+ for (const at of contradicted) {
794
+ const start = state.starts.get(at);
795
+ state.starts.delete(at);
796
+ state.rejected.add(at);
797
+ if (state.done.delete(at) && start?.kind === "cluster") {
798
+ withdrawn.push(at);
799
+ }
800
+ }
801
+ state.stats.contradictions += contradicted.size;
802
+ return withdrawn;
803
+ }
804
+
805
+ /**
806
+ * The order to read pending clusters in: the ones viewers stand in now, and the
807
+ * rest.
808
+ *
809
+ * Which cluster a viewer stands in is decided over EVERY cluster whose time is
810
+ * known, read or not: deciding it over the pending ones only would name an
811
+ * earlier cluster whenever the viewer's own one had already been read.
812
+ *
813
+ * @param {Array<[number, ClusterStart]>} pending
814
+ * @param {Array<[number, ClusterStart]>} clusters - Every known cluster start.
815
+ * @param {number[]} wantedSeconds
816
+ * @returns {{ urgent: number[], rest: number[] }}
817
+ */
818
+ function readingOrder(pending, clusters, wantedSeconds) {
819
+ const isPending = new Set(pending.map(([at]) => at));
820
+ const timed = clusters.filter(([, start]) => start.seconds !== null).sort((left, right) => left[1].seconds - right[1].seconds);
821
+ const lists = [];
822
+ const urgent = [];
823
+ for (const seconds of wantedSeconds ?? []) {
824
+ if (!Number.isFinite(seconds)) {
825
+ continue;
826
+ }
827
+ let containing = -1;
828
+ for (let index = 0; index < timed.length; index += 1) {
829
+ if (timed[index][1].seconds <= seconds) {
830
+ containing = index;
831
+ } else {
832
+ break;
833
+ }
834
+ }
835
+ if (containing >= 0) {
836
+ urgent.push(timed[containing][0]);
837
+ if (containing > 0) {
838
+ urgent.push(timed[containing - 1][0]);
839
+ }
840
+ }
841
+ const list = [];
842
+ for (let index = containing + 1; index < timed.length; index += 1) {
843
+ list.push(timed[index][0]);
844
+ }
845
+ lists.push(list.filter((at) => isPending.has(at)));
846
+ }
847
+ const now = [...new Set(urgent.filter((at) => isPending.has(at)))];
848
+ const order = [];
849
+ const seen = new Set(now);
850
+ // One viewer's next cluster after another's, so nobody waits for another
851
+ // viewer's whole film.
852
+ for (let step = 0; lists.some((list) => step < list.length); step += 1) {
853
+ for (const list of lists) {
854
+ const at = list[step];
855
+ if (at !== undefined && !seen.has(at)) {
856
+ seen.add(at);
857
+ order.push(at);
858
+ }
859
+ }
860
+ }
861
+ for (const [at] of [...pending].sort((left, right) => left[0] - right[0])) {
862
+ if (!seen.has(at)) {
863
+ order.push(at);
864
+ }
865
+ }
866
+ return { urgent: now, rest: order };
867
+ }
868
+
869
+ /**
870
+ * Where the viewers stand right now, however the reader states it.
871
+ *
872
+ * @param {import("./Container.js").HeldReader} held
873
+ * @returns {number[]}
874
+ */
875
+ function wantedNow(held) {
876
+ const stated = typeof held.wantedSeconds === "function" ? held.wantedSeconds() : held.wantedSeconds;
877
+ return Array.isArray(stated) ? stated.filter((value) => Number.isFinite(value)) : [];
878
+ }
879
+
880
+ /**
881
+ * Whether a cluster's bytes are all here to be read now — known only for a
882
+ * cluster whose size is known.
883
+ *
884
+ * @param {Map<number, ClusterStart>} starts
885
+ * @param {number} at
886
+ * @param {import("./Container.js").HeldReader} held
887
+ * @returns {boolean}
888
+ */
889
+ function readableNow(starts, at, held) {
890
+ const start = starts.get(at);
891
+ return Boolean(start && start.end !== null && held.isHeld(at, start.end - 1));
892
+ }
893
+
894
+ /**
895
+ * Read one cluster's subtitle blocks.
896
+ *
897
+ * @param {{ structure: ElementReader, exact: ElementReader }} readers - Headers
898
+ * and track numbers through `structure`; a subtitle block's data through
899
+ * `exact`, which reads that element and nothing more.
900
+ * @param {number} at
901
+ * @param {ClusterStart} start
902
+ * @param {object} plan
903
+ * @param {object} state
904
+ * @param {import("./Container.js").HeldReader} held
905
+ * @returns {Promise<{ status: "pending" } | { status: "unreadable", reason: string } | { status: "done", blocks: object[], end: number }>}
906
+ */
907
+ async function readCluster({ structure: reader, exact }, at, start, plan, state, held) {
908
+ try {
909
+ if (start.end !== null && !held.isHeld(at, start.end - 1)) {
910
+ return { status: "pending" };
911
+ }
912
+ const header = await reader.header(at, plan.segmentEnd);
913
+ if (!header || header.id !== ID_CLUSTER) {
914
+ return { status: "unreadable", reason: "no cluster header" };
915
+ }
916
+ const limit = header.end ?? plan.segmentEnd;
917
+ const wanted = new Set(plan.subtitleTrackNumbers);
918
+ const raw = [];
919
+ let ticks = null;
920
+ let cursor = header.dataOffset;
921
+ let end = header.end;
922
+ while (cursor < limit) {
923
+ if (!held.isHeld(cursor, Math.min(plan.fileSize, cursor + MAX_HEADER_BYTES) - 1)) {
924
+ return { status: "pending" };
925
+ }
926
+ const child = await reader.header(cursor, limit);
927
+ if (!child) {
928
+ return { status: "unreadable", reason: "a child header does not parse" };
929
+ }
930
+ if (header.end === null && LEVEL_ONE.has(child.id)) {
931
+ end = cursor;
932
+ break;
933
+ }
934
+ if (child.size === null || child.end > limit) {
935
+ return { status: "unreadable", reason: "a child runs past the cluster" };
936
+ }
937
+ if (header.end === null && !held.isHeld(child.at, child.end - 1)) {
938
+ return { status: "pending" };
939
+ }
940
+ if (child.id === ID_TIMESTAMP) {
941
+ ticks = readUint(await reader.bytes(child.dataOffset, child.size), 0, child.size);
942
+ } else if (child.id === ID_SIMPLE_BLOCK || child.id === ID_BLOCK_GROUP) {
943
+ const track = await blockTrackOf(reader, child);
944
+ if (track !== null && wanted.has(track)) {
945
+ const data = await exact.data(child);
946
+ if (data === null) {
947
+ state.stats.refusedElements += 1;
948
+ } else {
949
+ const block = child.id === ID_SIMPLE_BLOCK ? simpleBlockOf(data) : blockGroupOf(data);
950
+ if (block) {
951
+ raw.push(block);
952
+ }
953
+ }
954
+ }
955
+ }
956
+ cursor = child.end;
957
+ }
958
+ if (end === null) {
959
+ end = limit;
960
+ }
961
+ if (ticks === null) {
962
+ return { status: "unreadable", reason: "a cluster with no Timestamp" };
963
+ }
964
+ state.stats.bytesWalked += end - at;
965
+ const blocks = raw.map((block) => {
966
+ const startSeconds = (ticks + block.relativeTicks) * plan.secondsPerTick;
967
+ return {
968
+ trackNumber: block.trackNumber,
969
+ startSeconds,
970
+ endSeconds: block.durationTicks === null ? null : startSeconds + block.durationTicks * plan.secondsPerTick,
971
+ payload: block.payload,
972
+ source: at
973
+ };
974
+ });
975
+ return { status: "done", blocks, end, seconds: ticks * plan.secondsPerTick };
976
+ } catch (error) {
977
+ if (isUnavailable(error)) {
978
+ return { status: "pending" };
979
+ }
980
+ throw error;
981
+ }
982
+ }
983
+
984
+ /**
985
+ * @param {Buffer} data - A SimpleBlock's data.
986
+ * @returns {{ trackNumber: number, relativeTicks: number, durationTicks: null, payload: Buffer } | null}
987
+ */
988
+ function simpleBlockOf(data) {
989
+ const header = readBlockHeader(data, 0, data.length);
990
+ if (!header) {
991
+ return null;
992
+ }
993
+ const payloadAt = firstFrameOffset(data, header.dataOffset, data.length, header.flags);
994
+ if (payloadAt === null || payloadAt >= data.length) {
995
+ return null;
996
+ }
997
+ return { trackNumber: header.trackNumber, relativeTicks: header.relativeTicks, durationTicks: null, payload: data.subarray(payloadAt) };
998
+ }
999
+
1000
+ /**
1001
+ * @param {Buffer} data - A BlockGroup's data.
1002
+ * @returns {{ trackNumber: number, relativeTicks: number, durationTicks: number | null, payload: Buffer } | null}
1003
+ */
1004
+ function blockGroupOf(data) {
1005
+ let block = null;
1006
+ let durationTicks = null;
1007
+ let at = 0;
1008
+ while (at < data.length) {
1009
+ const id = readVint(data, at, true);
1010
+ const size = id && readVint(data, at + id.length, false);
1011
+ if (!id || !size) {
1012
+ return null;
1013
+ }
1014
+ const dataOffset = at + id.length + size.length;
1015
+ const end = dataOffset + size.value;
1016
+ if (end > data.length) {
1017
+ return null;
1018
+ }
1019
+ if (id.value === ID_BLOCK) {
1020
+ block = { start: dataOffset, end };
1021
+ } else if (id.value === ID_BLOCK_DURATION) {
1022
+ durationTicks = readUint(data, dataOffset, size.value);
1023
+ }
1024
+ at = end;
1025
+ }
1026
+ if (!block) {
1027
+ return null;
1028
+ }
1029
+ const header = readBlockHeader(data, block.start, block.end);
1030
+ if (!header) {
1031
+ return null;
1032
+ }
1033
+ const payloadAt = firstFrameOffset(data, header.dataOffset, block.end, header.flags);
1034
+ if (payloadAt === null || payloadAt >= block.end) {
1035
+ return null;
1036
+ }
1037
+ return { trackNumber: header.trackNumber, relativeTicks: header.relativeTicks, durationTicks, payload: data.subarray(payloadAt, block.end) };
1038
+ }
1039
+
1040
+ /**
1041
+ * One pass over what a Matroska file holds now.
1042
+ *
1043
+ * @param {object} params
1044
+ * @param {object} params.plan - From `MatroskaContainer.readSubtitlePlan`.
1045
+ * @param {object} params.progress - Kept by the caller between passes.
1046
+ * @param {import("./Container.js").HeldReader} params.held
1047
+ * @returns {Promise<{ found: Map<number, object[]>, covered: number, indexed: number, withdrawn: number[], more: boolean, stats: object }>}
1048
+ * `more` says clusters are readable now that this pass left for the next.
1049
+ */
1050
+ export async function walkHeldClusters({ plan, progress, held }) {
1051
+ const state = stateOf(progress);
1052
+ const reader = new ElementReader({
1053
+ read: held.read,
1054
+ fileSize: plan.fileSize,
1055
+ portionBytes: held.portionBytes,
1056
+ prefetch: true,
1057
+ readableUntil: (start) => runEndFrom(held.ranges, start)
1058
+ });
1059
+ if (!state.seeded) {
1060
+ state.seeded = true;
1061
+ if (Number.isFinite(plan.firstClusterAt)) {
1062
+ addStart(state, plan.firstClusterAt, plan, { source: "first", parent: null });
1063
+ }
1064
+ for (const entry of plan.entryPoints ?? []) {
1065
+ addStart(state, entry.at, plan, { source: "cues", parent: null, seconds: entry.seconds });
1066
+ }
1067
+ }
1068
+
1069
+ // The structure of clusters is read a header at a time, and a subtitle
1070
+ // block's data by its own size. The reader above takes a whole portion per
1071
+ // read and is for checking a candidate the search found, whose every byte is
1072
+ // needed; used for structure, it moved every frame of the film into this
1073
+ // thread — measured on the addon host 2026-10-01, the collector then spent
1074
+ // three times as long as the walk itself, and the loop's 99th-percentile
1075
+ // delay doubled.
1076
+ const structure = new ElementReader({
1077
+ read: held.read,
1078
+ fileSize: plan.fileSize,
1079
+ portionBytes: STRUCTURE_READ_BYTES,
1080
+ prefetch: true,
1081
+ readableUntil: (start) => runEndFrom(held.ranges, start)
1082
+ });
1083
+ const exact = new ElementReader({ read: held.read, fileSize: plan.fileSize, portionBytes: held.portionBytes });
1084
+ await extendChains(state, plan, held, structure);
1085
+
1086
+ if (plan.cuesState === "absent") {
1087
+ const readers = { whole: reader, structure };
1088
+ // Candidates left waiting for bytes by an earlier pass, then the bytes not
1089
+ // yet looked at.
1090
+ for (const at of [...state.candidates].sort((left, right) => left - right)) {
1091
+ if (state.starts.has(at)) {
1092
+ state.candidates.delete(at);
1093
+ continue;
1094
+ }
1095
+ await settleCandidate(state, plan, held, readers, at);
1096
+ }
1097
+ await searchForClusters(state, plan, held, readers);
1098
+ }
1099
+
1100
+ const withdrawn = withdrawContradicted(state);
1101
+
1102
+ /** @type {Map<number, object[]>} */
1103
+ const found = new Map();
1104
+ const clusters = [...state.starts.entries()].filter(([, start]) => start.kind === "cluster");
1105
+ const pending = clusters.filter(([at]) => !state.done.has(at) && !state.unreadable.has(at));
1106
+ const wanted = wantedNow(held);
1107
+ const { urgent, rest } = readingOrder(pending, clusters, wanted);
1108
+ const urgentReadable = urgent.filter((at) => readableNow(state.starts, at, held));
1109
+ let more = false;
1110
+ /** @type {number[]} */
1111
+ let order;
1112
+ if (urgentReadable.length > 0) {
1113
+ order = urgentReadable;
1114
+ more = rest.some((at) => readableNow(state.starts, at, held));
1115
+ } else {
1116
+ order = [...urgent, ...rest];
1117
+ }
1118
+ const asked = JSON.stringify(wanted);
1119
+ for (const at of order) {
1120
+ if (urgentReadable.length === 0 && JSON.stringify(wantedNow(held)) !== asked) {
1121
+ // A viewer is somewhere else now: the next pass starts from there.
1122
+ more = true;
1123
+ break;
1124
+ }
1125
+ const start = state.starts.get(at);
1126
+ if (!start) {
1127
+ continue;
1128
+ }
1129
+ const result = await readCluster({ structure, exact }, at, start, plan, state, held);
1130
+ if (result.status === "pending") {
1131
+ continue;
1132
+ }
1133
+ if (result.status === "unreadable") {
1134
+ state.unreadable.set(at, result.reason);
1135
+ continue;
1136
+ }
1137
+ state.done.add(at);
1138
+ if (start.end === null) {
1139
+ start.end = result.end;
1140
+ addStart(state, result.end, plan, { source: "chain", parent: at });
1141
+ }
1142
+ if (start.seconds === null) {
1143
+ start.seconds = result.seconds;
1144
+ }
1145
+ if (rootOf(state.starts, at)?.source === "search") {
1146
+ state.stats.fromSearch += 1;
1147
+ }
1148
+ for (const block of result.blocks) {
1149
+ const into = found.get(block.trackNumber) ?? [];
1150
+ into.push(block);
1151
+ found.set(block.trackNumber, into);
1152
+ }
1153
+ }
1154
+ // A cluster read whole may have made the start after an unknown-sized one
1155
+ // known; its header is taken on the next pass, with everything else new.
1156
+
1157
+ return {
1158
+ found,
1159
+ covered: state.done.size,
1160
+ indexed: [...state.starts.values()].filter((start) => start.kind === "cluster").length,
1161
+ withdrawn,
1162
+ more,
1163
+ stats: { ...state.stats, unreadable: state.unreadable.size, pendingCandidates: state.candidates.size }
1164
+ };
1165
+ }