@torrent-tv/proxy 2.38.1 → 2.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,755 +1,755 @@
1
- /**
2
- * @file Reading a byte range as positions in shared memory, not as bytes.
3
- *
4
- * The pieces already live in a `SharedArrayBuffer` the main thread can map. So
5
- * the torrent thread does not need to hand over any bytes at all: it can say
6
- * *where* a piece sits and let the other side read it there. What crosses the
7
- * boundary is two numbers per piece.
8
- *
9
- * That is the whole point of the exercise. The alternative — copying each piece
10
- * into memory we own and transferring it — costs 18.84 ms per 10 MB segment on
11
- * the field host, and costs it **on the critical path**, in the thread that is
12
- * also running the torrent, at the moment a viewer is waiting for that segment.
13
- * Here the copy is gone entirely rather than moved.
14
- *
15
- * Two obligations come with it, and both are enforced rather than assumed:
16
- *
17
- * - a piece being read is **pinned**, so eviction cannot take the memory out
18
- * from under the reader mid-read;
19
- * - the pin is released only once the other thread reports it has finished
20
- * with those bytes — not when they were sent, because nothing was sent.
21
- */
22
-
23
- import { findSharedStore } from "../piece-store/shared-piece-store.js";
24
- import { logger } from "../../utils/logger.js";
25
- import { askFastestWiresFor, canPlaceRequests, describePieceTail } from "./fastest-wires.js";
26
- import { minimumBufferFrom, requiredSpeedFrom } from "../supply-margin.js";
27
-
28
- /** Only waits at least this long are reported; sequential reading stays silent. */
29
- const PIECE_WAIT_LOG_MS = 1_000;
30
-
31
- /** Distinguishes concurrent readers to the piece store. Never reused. */
32
- let readerSequence = 0;
33
-
34
- /**
35
- * How far ahead of the read head pieces are asked for.
36
- *
37
- * A read is open-ended — ffmpeg opens its input as `bytes <position>-<EOF>` and
38
- * keeps it for the whole film — so taking the requested range literally asks
39
- * for everything from the seek point to the end of the file at once. That is
40
- * what a seek used to do: the swarm was told the entire tail was wanted, went
41
- * at it from its first missing piece, and the one piece the decoder was blocked
42
- * on arrived only when the sequential scan reached it. Measured on a 4.7 GB
43
- * film: a seek to 89.1% took 93 s and pulled 2.47 GB.
44
- *
45
- * So the reader asks for a window and moves it as it goes. The size is a
46
- * compromise the caller cannot yet express: the right unit is seconds of
47
- * playback (duration and size are both known — to the transcode session, not to
48
- * this thread), and 32 MB is about 34 s of a 1080p film but only a few seconds
49
- * of a disc remux. Sizing it from the real byte rate is a follow-up; what
50
- * matters here is that it is bounded and moving rather than "to the end".
51
- */
52
- const READ_WINDOW_BYTES = 32 * 1024 * 1024;
53
-
54
- /**
55
- * The pieces a reader at `pieceIndex` wants next, clamped to its own range.
56
- *
57
- * @param {{ pieceIndex: number, lastPiece: number, windowPieces: number }} params
58
- * @returns {{ from: number, to: number }}
59
- */
60
- export function readWindowFor({ pieceIndex, lastPiece, windowPieces }) {
61
- const span = Math.max(1, windowPieces);
62
- return { from: pieceIndex, to: Math.min(lastPiece, pieceIndex + span - 1) };
63
- }
64
-
65
- /**
66
- * How wide the window should be after a piece that made the reader wait — or
67
- * did not.
68
- *
69
- * The swarm's surplus is what pays for this. Measured 2026-08-17 on the field
70
- * torrent: 5.1-5.9 MB/s delivered against a film consumed at about 1 MB/s, and
71
- * the reader still blocked 47 times in two minutes, median 1.5 s, worst 4.5 s.
72
- * A fivefold surplus never became distance ahead of the head, because the
73
- * window is a fixed number of seconds of playback and everything past it is
74
- * ordinary background fill at no priority.
75
- *
76
- * So the window follows the evidence: every wait that mattered widens it by a
77
- * piece, every piece that was already there narrows it back toward the size the
78
- * caller asked for. Nothing here is chosen — the wait is measured, the
79
- * threshold is the one that already defines "a wait worth recording", and the
80
- * ceiling is this reader's share of the store's memory, so widening can never
81
- * cost more than the store can hold.
82
- *
83
- * @param {{ current: number, base: number, ceiling: number, waitedMs: number, waitThresholdMs: number }} params
84
- * @returns {number}
85
- */
86
- export function nextWindowPieces({ current, base, ceiling, waitedMs, waitThresholdMs }) {
87
- const floor = Math.max(1, Math.floor(base));
88
- const top = Math.max(floor, Math.floor(ceiling));
89
- const now = Math.min(top, Math.max(floor, Math.floor(current)));
90
- if (waitedMs >= waitThresholdMs) {
91
- return Math.min(top, now + 1);
92
- }
93
- return Math.max(floor, now - 1);
94
- }
95
-
96
- /**
97
- * Add this reader's window to the download set as a stream selection.
98
- *
99
- * `_select`/`_deselect` with the stream flag are what WebTorrent's own
100
- * `FileIterator` uses; there is no public call for it, because the public
101
- * `select` produces the merging, interval-subtracted kind whose bookkeeping
102
- * cannot express "one of several readers wants this". Falls back to the public
103
- * call if a future version drops the private one.
104
- *
105
- * @param {import("webtorrent").Torrent} torrent
106
- * @param {{ from: number, to: number }} window
107
- * @param {number} [priority] - 1 for what a reader needs next, 0 for the
108
- * background fill of the rest of the file.
109
- * @returns {void}
110
- */
111
- function claimWindow(torrent, { from, to }, priority = 1) {
112
- try {
113
- if (typeof torrent._select === "function") {
114
- torrent._select(from, to, priority, null, true);
115
- } else if (typeof torrent.select === "function") {
116
- torrent.select(from, to, priority);
117
- }
118
- } catch {
119
- // Best effort — never fail a read because selection bookkeeping refused.
120
- }
121
- }
122
-
123
- /**
124
- * Take this reader's window back out of the download set.
125
- *
126
- * The bounds must match the ones given to {@link claimWindow} exactly: a stream
127
- * selection is removed by equality, not by overlap.
128
- *
129
- * @param {import("webtorrent").Torrent} torrent
130
- * @param {{ from: number, to: number }} window
131
- * @returns {void}
132
- */
133
- function releaseWindow(torrent, { from, to }) {
134
- try {
135
- if (typeof torrent._deselect === "function") {
136
- torrent._deselect(from, to, true);
137
- } else if (typeof torrent.deselect === "function") {
138
- torrent.deselect(from, to);
139
- }
140
- } catch {
141
- // Best effort.
142
- }
143
- }
144
-
145
- /**
146
- * Mark the piece a reader is blocked on, clearing the mark it set before.
147
- *
148
- * Criticality is never cleared by WebTorrent itself, so a reader that walked a
149
- * film would leave every piece of it marked. Only the indices this reader set
150
- * are cleared, so a second reader's mark on the same piece is not stolen — and
151
- * the flag is advisory anyway.
152
- *
153
- * @param {import("webtorrent").Torrent} torrent
154
- * @param {number} from
155
- * @param {number} to
156
- * @param {{ from: number, to: number } | null} previous
157
- * @returns {{ from: number, to: number } | null}
158
- */
159
- function markCritical(torrent, from, to, previous) {
160
- if (previous && previous.from === from && previous.to === to) {
161
- return previous;
162
- }
163
- if (previous) {
164
- clearCritical(torrent, previous);
165
- }
166
- try {
167
- torrent.critical?.(from, to);
168
- } catch {
169
- return null;
170
- }
171
- return { from, to };
172
- }
173
-
174
- /**
175
- * Drop critical marks this reader set.
176
- *
177
- * @param {import("webtorrent").Torrent} torrent
178
- * @param {{ from: number, to: number }} mark
179
- * @returns {void}
180
- */
181
- function clearCritical(torrent, { from, to }) {
182
- if (!Array.isArray(torrent._critical)) {
183
- return;
184
- }
185
- for (let index = from; index <= to; index += 1) {
186
- torrent._critical[index] = false;
187
- }
188
- }
189
-
190
- /**
191
- * Who is working on the piece a reader is blocked on, right now.
192
- *
193
- * The open question about a seek: a single 8 MiB piece takes 3.0-4.6 s to
194
- * arrive while the swarm as a whole is moving 4-6 MB/s, so roughly 2 MB/s is
195
- * reaching the piece that is actually being waited for. Whether that is because
196
- * few peers hold it, few are being asked, or each is slow cannot be told apart
197
- * from the outside — these three counts tell them apart.
198
- *
199
- * `wire.requests` is what has been asked of that peer and not yet answered; a
200
- * block is 16 KB, so `blocks x 16 KB` is the work in flight on this piece.
201
- *
202
- * @param {import("webtorrent").Torrent} torrent
203
- * @param {number} pieceIndex
204
- * @returns {{ peers: number, holders: number, askedOf: number, blocks: number }}
205
- */
206
- export function pieceSupply(torrent, pieceIndex) {
207
- const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
208
- let holders = 0;
209
- let askedOf = 0;
210
- let blocks = 0;
211
- for (const wire of wires) {
212
- if (wire?.peerPieces?.get?.(pieceIndex)) {
213
- holders += 1;
214
- }
215
- const requests = Array.isArray(wire?.requests) ? wire.requests : [];
216
- const forThisPiece = requests.filter((request) => request?.piece === pieceIndex).length;
217
- if (forThisPiece > 0) {
218
- askedOf += 1;
219
- blocks += forThisPiece;
220
- }
221
- }
222
- return { peers: wires.length, holders, askedOf, blocks };
223
- }
224
-
225
- /**
226
- * Wait until a piece has been downloaded and verified.
227
- *
228
- * WebTorrent announces this as `verified`. The bitfield is re-checked after the
229
- * listener is attached because the piece can complete in between, and a missed
230
- * event here would wait forever.
231
- *
232
- * @param {import("webtorrent").Torrent} torrent
233
- * @param {number} index
234
- * @param {{ isCancelled: () => boolean }} cancellation
235
- * @returns {Promise<void>}
236
- */
237
- function whenPieceReady(torrent, index, cancellation) {
238
- if (torrent.bitfield?.get(index)) {
239
- return Promise.resolve();
240
- }
241
-
242
- return new Promise((resolve, reject) => {
243
- /** @param {number} verifiedIndex */
244
- const onVerified = (verifiedIndex) => {
245
- if (verifiedIndex === index) {
246
- cleanup();
247
- resolve();
248
- }
249
- };
250
- const onDestroyed = () => {
251
- cleanup();
252
- reject(new Error(`Torrent went away while waiting for piece ${index}.`));
253
- };
254
- // Cancellation is polled rather than pushed: a superseded seek destroys the
255
- // read, and without this the wait would outlive it and hold a pin.
256
- const poll = setInterval(() => {
257
- if (cancellation.isCancelled()) {
258
- cleanup();
259
- reject(new Error(`Read cancelled while waiting for piece ${index}.`));
260
- }
261
- }, 250);
262
-
263
- function cleanup() {
264
- clearInterval(poll);
265
- torrent.removeListener("verified", onVerified);
266
- torrent.removeListener("close", onDestroyed);
267
- }
268
-
269
- torrent.on("verified", onVerified);
270
- torrent.once("close", onDestroyed);
271
-
272
- // The piece may have arrived between the check above and this listener.
273
- if (torrent.bitfield?.get(index)) {
274
- cleanup();
275
- resolve();
276
- }
277
- });
278
- }
279
-
280
- /**
281
- * A fragment of a read: where to find it, and how to let it go.
282
- *
283
- * @typedef {object} PieceFragment
284
- * @property {number} pieceIndex
285
- * @property {number} offset - Byte offset into the shared pool.
286
- * @property {number} length
287
- * @property {() => void} release - Drops this fragment's pin. Call exactly once.
288
- */
289
-
290
- /**
291
- * Walk a byte range of a file, yielding each piece's position in shared memory.
292
- *
293
- * Yields at most one fragment per piece; the first and last are usually partial.
294
- * The caller must `release()` every fragment it receives, including on failure —
295
- * an unreleased pin permanently costs a slot.
296
- *
297
- * @param {object} params
298
- * @param {import("webtorrent").Torrent} params.torrent
299
- * @param {number} params.fileIndex
300
- * @param {number} params.start - Inclusive, relative to the file.
301
- * @param {number} params.end - Inclusive, relative to the file.
302
- * @param {{ isCancelled: () => boolean }} params.cancellation
303
- * @param {number} [params.windowBytes] - How far ahead of the read head to ask
304
- * the swarm for. Defaults to {@link READ_WINDOW_BYTES}; a caller that knows
305
- * the media's byte rate should size it in seconds of playback instead.
306
- * @returns {AsyncGenerator<PieceFragment>}
307
- */
308
- /**
309
- * The last interruptions this file's readers met, newest last.
310
- *
311
- * Bounded and per file, because both figures derived from it describe THIS
312
- * file on THIS swarm: a piece is 8 MiB here and 512 KiB elsewhere, and a swarm
313
- * that answers in 200 ms today may not tomorrow. Nothing is stored beyond the
314
- * process — a restart starts from no evidence, which is the honest state.
315
- *
316
- * @type {Map<string, Array<{ waitedMs: number, at: number }>>}
317
- */
318
- const supplyWaits = new Map();
319
-
320
- /** How many interruptions are kept per file. */
321
- const SUPPLY_WAIT_HISTORY = 40;
322
-
323
- /** How often the derived figures are printed, at most. */
324
- const SUPPLY_REPORT_INTERVAL_MS = 30_000;
325
-
326
- /** When each file's figures were last printed. */
327
- const supplyReportedAt = new Map();
328
-
329
- /**
330
- * Record one interruption and, at most twice a minute, say what it implies.
331
- *
332
- * The two figures are the whole of roadmap item 3: the speed a step must
333
- * sustain to survive this supply (`1 + worst wait / median interval`), and the
334
- * smallest buffer that hides an interruption from the viewer. Both are printed
335
- * before either is USED, so the field says whether the arithmetic describes
336
- * reality before anything is decided by it.
337
- *
338
- * @param {string} key - Something stable per file.
339
- * @param {string} label - What to call it in the log.
340
- * @param {number} waitedMs
341
- * @returns {void}
342
- */
343
- /**
344
- * What this file's recent interruptions demand, for a caller that has to decide
345
- * something with them.
346
- *
347
- * Exported because the figures are measured HERE — the reader is the only place
348
- * that knows how long it waited — while the decisions they feed are made
349
- * elsewhere: the smallest buffer that hides an interruption goes to the browser,
350
- * and the speed a step must sustain goes to the quality offer.
351
- *
352
- * @param {string} infoHash
353
- * @param {string} fileName
354
- * @param {number} segmentSeconds - The session's own segment duration.
355
- * @returns {{ requiredSpeed: number, worstWaitSec: number, medianIntervalSec: number, samples: number, minimumBufferSec: number } | null}
356
- */
357
- export function supplyFiguresFor(infoHash, fileName, segmentSeconds) {
358
- const history = supplyWaits.get(`${infoHash ?? "?"}/${fileName ?? "?"}`);
359
- const demand = requiredSpeedFrom(history ?? []);
360
- if (!demand) {
361
- return null;
362
- }
363
- const buffer = minimumBufferFrom({
364
- segmentSeconds,
365
- worstSupplyWaitSec: demand.worstWaitSec
366
- });
367
- return {
368
- requiredSpeed: demand.requiredSpeed,
369
- worstWaitSec: demand.worstWaitSec,
370
- medianIntervalSec: demand.medianIntervalSec,
371
- samples: demand.samples,
372
- minimumBufferSec: buffer ? buffer.seconds : null
373
- };
374
- }
375
-
376
- function noteSupplyWait(key, label, waitedMs) {
377
- const history = supplyWaits.get(key) ?? [];
378
- history.push({ waitedMs, at: Date.now() });
379
- while (history.length > SUPPLY_WAIT_HISTORY) {
380
- history.shift();
381
- }
382
- supplyWaits.set(key, history);
383
-
384
- const now = Date.now();
385
- if (now - (supplyReportedAt.get(key) ?? 0) < SUPPLY_REPORT_INTERVAL_MS) {
386
- return;
387
- }
388
- const demand = requiredSpeedFrom(history);
389
- if (!demand) {
390
- return;
391
- }
392
- supplyReportedAt.set(key, now);
393
- const buffer = minimumBufferFrom({
394
- segmentSeconds: SEGMENT_SECONDS_FOR_BUFFER,
395
- worstSupplyWaitSec: demand.worstWaitSec
396
- });
397
- logger.info(
398
- `supply "${label.slice(0, 40)}": a step must run at ${demand.requiredSpeed.toFixed(2)}x ` +
399
- `to survive this swarm (worst wait ${demand.worstWaitSec.toFixed(2)}s, one every ` +
400
- `${demand.medianIntervalSec.toFixed(2)}s, ${demand.samples} measured) — ` +
401
- `and the smallest buffer that hides it is ${buffer ? buffer.seconds.toFixed(1) : "?"}s`
402
- );
403
- }
404
-
405
- /**
406
- * The segment length the buffer figure is stated against. The reader does not
407
- * know the session's own, and this is a REPORT rather than a decision — the
408
- * decision, when it is made, will use the session's real one.
409
- */
410
- const SEGMENT_SECONDS_FOR_BUFFER = 4;
411
-
412
- export async function* readFragments({
413
- torrent,
414
- fileIndex,
415
- start,
416
- end,
417
- cancellation,
418
- windowBytes = READ_WINDOW_BYTES
419
- }) {
420
- const store = findSharedStore(torrent);
421
- if (!store) {
422
- throw new Error("This torrent is not backed by a shared piece store.");
423
- }
424
-
425
- const file = torrent.files?.[fileIndex];
426
- if (!file) {
427
- throw new Error(`File ${fileIndex} not found.`);
428
- }
429
-
430
- const pieceLength = torrent.pieceLength;
431
- // Piece numbers are torrent-wide, so a file's own offsets have to be lifted
432
- // into the torrent's address space first.
433
- const absoluteStart = file.offset + start;
434
- const absoluteEnd = file.offset + end;
435
- const firstPiece = Math.floor(absoluteStart / pieceLength);
436
- const lastPiece = Math.floor(absoluteEnd / pieceLength);
437
-
438
- // This reader owns what it asks for, and gives it back when it is done. The
439
- // window is a STREAM selection: those are removed by exact bounds and several
440
- // identical ones coexist — WebTorrent's own source calls that "in a way a
441
- // count" — so N readers on one torrent produce the union of their windows,
442
- // and each one leaving takes away only its own. That is what makes several
443
- // parallel readers (the codec probe's head and tail, subtitles, one input per
444
- // viewer) cooperate instead of overwrite each other.
445
- //
446
- // The previous code selected the whole requested range, marked all of it
447
- // critical, and never deselected anything — so ffmpeg's opening
448
- // `bytes 0-<EOF>` left a permanent selection over the entire file, and no
449
- // later prioritisation could outrank it.
450
- const basePieces = Math.max(1, Math.ceil(Math.max(1, windowBytes) / pieceLength));
451
- // What the window is RIGHT NOW. It starts at what the caller sized in seconds
452
- // of playback and grows while the reader keeps being made to wait — see
453
- // `nextWindowPieces`.
454
- let windowPieces = basePieces;
455
- /**
456
- * The widest this reader may go: its share of what the store can hold in
457
- * memory. Measured rather than chosen — the capacity is the store's own, and
458
- * the number of readers is how many windows are declared on it right now.
459
- *
460
- * @returns {number}
461
- */
462
- const ceilingPieces = () => {
463
- const capacity = Number(store?.capacity);
464
- if (!Number.isFinite(capacity) || capacity <= 0) {
465
- return basePieces;
466
- }
467
- const readers = Math.max(1, store.protectedRanges?.().length ?? 1);
468
- return Math.max(basePieces, Math.floor(capacity / readers));
469
- };
470
- /** @type {{ from: number, to: number } | null} */
471
- let window = null;
472
- /** @type {{ from: number, to: number } | null} */
473
- let criticalMark = null;
474
- /**
475
- * Drops the pin of the fragment currently in the consumer's hands, if it
476
- * still holds one. See where it is assigned.
477
- *
478
- * @type {(() => void) | null}
479
- */
480
- let releaseHeldPin = null;
481
-
482
- // Identity of this read, so the store can tell one reader's window from
483
- // another's. Each read gets its own; `readerSequence` never repeats within a
484
- // process.
485
- const readerId = `read-${(readerSequence += 1)}`;
486
-
487
- /**
488
- * Set when the window JUMPS, cleared by the first wait after it.
489
- *
490
- * The wait that follows a jump is the cost of the jump: the pieces at the new
491
- * position have not been asked for yet, and the encoder is restarting. It is
492
- * not evidence about how well this swarm SUSTAINS a read, which is the only
493
- * thing `requiredSpeed` is about — and letting it in is what collapsed the
494
- * quality offer 131 ms after the seek measured on 2026-08-18, refusing every
495
- * re-encoded rung on the strength of one jump.
496
- *
497
- * @type {boolean}
498
- */
499
- let waitBelongsToJump = false;
500
-
501
- const moveWindowTo = (pieceIndex) => {
502
- const next = readWindowFor({ pieceIndex, lastPiece, windowPieces });
503
- if (window && window.from === next.from && window.to === next.to) {
504
- return;
505
- }
506
- const isJump = !window || next.from > window.to || next.from < window.from;
507
- if (window) {
508
- releaseWindow(torrent, window);
509
- }
510
- claimWindow(torrent, next);
511
- window = next;
512
- // Tell the store these pieces are wanted, so it evicts something else.
513
- // Without it the piece the decoder reads next looks exactly as stale as one
514
- // the encoder fetched forty minutes ahead, and the second kind is what
515
- // fills the store while the encoder runs ahead of the viewer.
516
- store.protectRange?.(readerId, next.from, next.to);
517
- if (isJump) {
518
- waitBelongsToJump = true;
519
- // A jump — a seek, not the window sliding along — can land on pieces that
520
- // are already downloaded but have been spilled to disk. Bring the whole
521
- // window back at once instead of one disk round trip per piece as the
522
- // reader reaches them.
523
- const revived = store.warmRange?.(next.from, next.to) ?? 0;
524
- if (revived > 0) {
525
- logger.info(
526
- `piece-reader: reviving ${revived} spilled piece(s) of ${next.from}-${next.to} ` +
527
- `for a jump to ${(start / 1024 / 1024).toFixed(0)}MB of "${file.name}"`
528
- );
529
- }
530
- }
531
- };
532
-
533
- try {
534
- for (let pieceIndex = firstPiece; pieceIndex <= lastPiece; pieceIndex += 1) {
535
- if (cancellation.isCancelled()) {
536
- return;
537
- }
538
-
539
- const pieceStart = pieceIndex * pieceLength;
540
- const fromWithinPiece = Math.max(absoluteStart, pieceStart) - pieceStart;
541
- const toWithinPiece = Math.min(absoluteEnd, pieceStart + pieceLength - 1) - pieceStart;
542
-
543
- moveWindowTo(pieceIndex);
544
-
545
- if (!torrent.bitfield?.get(pieceIndex)) {
546
- // Everything from here to the end of the window is wanted NOW, so all
547
- // of it is marked, not just the piece under the head. `critical`
548
- // enables hotswap: a block reserved by a slow peer is re-requested from
549
- // a faster one instead of holding up the reader. Measured 2026-08-04
550
- // with only the blocked piece marked, the first segment after a seek
551
- // took 7.2 s while its four 4 MB pieces arrived one after another at
552
- // ~2.2 MB/s, with waits of 1.3 s and 2.8 s on single pieces.
553
- //
554
- // This is not the old behaviour returning: that marked the whole
555
- // REQUESTED RANGE, which for ffmpeg's input means every piece to the
556
- // end of the file — hundreds of them, at which point the flag says
557
- // nothing. A window is what a reader genuinely needs next.
558
- criticalMark = markCritical(torrent, pieceIndex, window.to, criticalMark);
559
- }
560
-
561
- const waitStartedAt = Date.now();
562
- // The reader is blocked, so this piece is now the only thing that matters
563
- // on this torrent: hand it to the fastest wires that hold it. A block is
564
- // reserved for exactly one wire, and the read ends when the slowest
565
- // holder delivers — measured 2026-08-17, the swarm had a fivefold surplus
566
- // of bandwidth and the reader still waited 1.0-4.5 s, 47 times in two
567
- // minutes, on pieces five peers already had.
568
- let pushed = { asked: 0, attempted: 0, considered: 0, fastestBytesPerSecond: 0 };
569
- // The tail as it stood at an attempt that placed NOTHING — the state the
570
- // duplication work has to answer, and the only one worth a line. Sampled
571
- // at that instant rather than once up front, because the steering runs
572
- // again every half second and the piece changes under it; the last such
573
- // reading is kept, so the line describes the most recent failure.
574
- let tailWhenNothingPlaced = null;
575
- const pushToFastest = () => {
576
- try {
577
- const result = askFastestWiresFor(torrent, pieceIndex);
578
- if (result.asked === 0) {
579
- tailWhenNothingPlaced = describePieceTail(torrent, pieceIndex);
580
- }
581
- pushed = {
582
- asked: pushed.asked + result.asked,
583
- // Summed like the successes, so the line compares two totals over
584
- // the same attempts instead of a total against a snapshot.
585
- attempted: (pushed.attempted ?? 0) + result.attempted,
586
- considered: result.considered,
587
- fastestBytesPerSecond: result.fastestBytesPerSecond
588
- };
589
- } catch (error) {
590
- // The entry is internal to the library; if a version changes it, this
591
- // lever stops working and that must be visible rather than silent.
592
- logger.warn(`piece-reader: could not steer piece ${pieceIndex} — ${error?.message ?? error}`);
593
- }
594
- };
595
- if (canPlaceRequests(torrent)) {
596
- pushToFastest();
597
- } else {
598
- // Nothing can be placed at all on this build, so the tail is the whole
599
- // of the answer.
600
- tailWhenNothingPlaced = describePieceTail(torrent, pieceIndex);
601
- logger.warn(
602
- "piece-reader: this webtorrent build offers no way to place a request; " +
603
- "the blocked piece cannot be steered onto a faster peer"
604
- );
605
- }
606
- // Sampled while waiting rather than after: once the piece lands, nothing
607
- // is outstanding on it any more and every count reads zero.
608
- let supply = null;
609
- const supplyProbe = setInterval(() => {
610
- const sample = pieceSupply(torrent, pieceIndex);
611
- if (!supply || sample.blocks > supply.blocks) {
612
- supply = sample;
613
- }
614
- // Wires come and go, and their speeds change: a holder that was slow a
615
- // moment ago may now be the fastest one available.
616
- pushToFastest();
617
- }, 500);
618
- try {
619
- await whenPieceReady(torrent, pieceIndex, cancellation);
620
- } finally {
621
- clearInterval(supplyProbe);
622
- }
623
- // What a reader spent waiting for data, attributed to the exact piece. A
624
- // seek's cost is dominated by the first segment after the encoder
625
- // restarts (measured 9.2-9.4 s), and without this there is no way to say
626
- // whether that is the swarm, the picker, or ffmpeg. Logged only when the
627
- // wait is long enough to matter, so ordinary sequential reading is silent.
628
- const waitedMs = Date.now() - waitStartedAt;
629
- // The window answers to what just happened: a wait means the lead was too
630
- // short, an immediate hit means it is longer than it needs to be. Applied
631
- // before the logging below so the line reports the window the next piece
632
- // will actually use.
633
- if (waitBelongsToJump) {
634
- // Recorded nowhere: see `waitBelongsToJump`. Said out loud, because a
635
- // gap in the supply history is otherwise indistinguishable from a swarm
636
- // that never made the reader wait.
637
- logger.info(
638
- `piece-reader: ${waitedMs}ms on the first piece after a jump — the cost of moving, ` +
639
- `not of this swarm's supply, so it is not counted against the quality offer`
640
- );
641
- waitBelongsToJump = false;
642
- } else {
643
- noteSupplyWait(`${torrent?.infoHash ?? "?"}/${file?.name ?? "?"}`, file?.name ?? "", waitedMs);
644
- }
645
- const widened = nextWindowPieces({
646
- current: windowPieces,
647
- base: basePieces,
648
- ceiling: ceilingPieces(),
649
- waitedMs,
650
- waitThresholdMs: PIECE_WAIT_LOG_MS
651
- });
652
- if (widened !== windowPieces) {
653
- windowPieces = widened;
654
- }
655
- if (waitedMs >= PIECE_WAIT_LOG_MS) {
656
- const rateKbps = Math.round(pieceLength / 1024 / (waitedMs / 1000));
657
- logger.info(
658
- `piece-reader: waited ${waitedMs}ms for piece ${pieceIndex} ` +
659
- `(${pieceIndex - firstPiece + 1} of ${lastPiece - firstPiece + 1} in a read from ` +
660
- `${(start / 1024 / 1024).toFixed(0)}MB of "${file.name}") ` +
661
- `— ${rateKbps}KB/s on this piece; ` +
662
- (supply
663
- ? `${supply.holders}/${supply.peers} peers had it, ${supply.askedOf} were asked, ` +
664
- `${supply.blocks} blocks (${Math.round((supply.blocks * 16384) / 1024)}KB) in flight at peak`
665
- : "no sample taken") +
666
- // What WE did about it, so the next session says whether steering
667
- // the piece onto faster holders shortens the tail — by number
668
- // rather than by impression.
669
- `; steered onto ${pushed.asked} of ${pushed.attempted} asks (${pushed.considered} peers held it)` +
670
- (pushed.fastestBytesPerSecond > 0
671
- ? `, fastest ${Math.round(pushed.fastestBytesPerSecond / 1024)}KB/s`
672
- : "") +
673
- // Only when the steering placed nothing, which is the case that
674
- // decides whether duplicating the tail is worth building: it says
675
- // how much of the piece is still missing and which wires are
676
- // holding it, slowest first.
677
- (tailWhenNothingPlaced
678
- ? `; tail ${tailWhenNothingPlaced.missing}/${tailWhenNothingPlaced.chunks} blocks missing, held by ` +
679
- (tailWhenNothingPlaced.outstanding.length > 0
680
- ? tailWhenNothingPlaced.outstanding
681
- .map((wire) => `${wire.blocks}@${Math.round(wire.bytesPerSecond / 1024)}KB/s` +
682
- (wire.choking ? " (choking)" : ""))
683
- .join(" ")
684
- : "nobody")
685
- : "")
686
- );
687
- }
688
-
689
- // Pinned BEFORE it is located, and before any await that could let an
690
- // eviction run: the offset is only meaningful while the piece is held.
691
- store.pin(pieceIndex);
692
- let located = null;
693
- try {
694
- located = await store.reside(pieceIndex);
695
- } catch (error) {
696
- store.unpin(pieceIndex);
697
- throw error;
698
- }
699
-
700
- if (!located) {
701
- store.unpin(pieceIndex);
702
- throw new Error(`Piece ${pieceIndex} is verified but absent from the store.`);
703
- }
704
-
705
- let releasedThisPiece = false;
706
- // Remembered so the generator can drop it itself. The pin is taken here
707
- // and the consumer is expected to release it — but a consumer that
708
- // ABANDONS the iterator never gets the chance, and a seek abandons it
709
- // every time: the encoder is killed, the response is torn down, and the
710
- // loop is left between two fragments. Field 2026-08-06: after one seek
711
- // every slot in the store was pinned, the store answered
712
- // `Every resident piece is pinned; no slot can be freed` — to the
713
- // WebTorrent client, which closed the store and destroyed the torrent —
714
- // and the session died with `File 0 not found`.
715
- releaseHeldPin = () => {
716
- if (!releasedThisPiece) {
717
- releasedThisPiece = true;
718
- store.unpin(pieceIndex);
719
- }
720
- };
721
- yield {
722
- pieceIndex,
723
- offset: located.offset + fromWithinPiece,
724
- length: toWithinPiece - fromWithinPiece + 1,
725
- release() {
726
- if (releasedThisPiece) {
727
- return;
728
- }
729
- releasedThisPiece = true;
730
- store.unpin(pieceIndex);
731
- }
732
- };
733
- // Handed back, and released by the consumer or not at all — either way
734
- // this reader no longer owes anything for it.
735
- releaseHeldPin = null;
736
- }
737
- } finally {
738
- // A fragment handed out and never released is a slot lost for the life of
739
- // the process. Reached on every exit, including the consumer walking away.
740
- if (releaseHeldPin) {
741
- releaseHeldPin();
742
- releaseHeldPin = null;
743
- }
744
- // Reached on completion, on cancellation, on a throw, and when the consumer
745
- // stops iterating — a window left behind would keep the swarm fetching for
746
- // a reader that no longer exists.
747
- if (window) {
748
- releaseWindow(torrent, window);
749
- }
750
- store.releaseProtection?.(readerId);
751
- if (criticalMark) {
752
- clearCritical(torrent, criticalMark);
753
- }
754
- }
755
- }
1
+ /**
2
+ * @file Reading a byte range as positions in shared memory, not as bytes.
3
+ *
4
+ * The pieces already live in a `SharedArrayBuffer` the main thread can map. So
5
+ * the torrent thread does not need to hand over any bytes at all: it can say
6
+ * *where* a piece sits and let the other side read it there. What crosses the
7
+ * boundary is two numbers per piece.
8
+ *
9
+ * That is the whole point of the exercise. The alternative — copying each piece
10
+ * into memory we own and transferring it — costs 18.84 ms per 10 MB segment on
11
+ * the field host, and costs it **on the critical path**, in the thread that is
12
+ * also running the torrent, at the moment a viewer is waiting for that segment.
13
+ * Here the copy is gone entirely rather than moved.
14
+ *
15
+ * Two obligations come with it, and both are enforced rather than assumed:
16
+ *
17
+ * - a piece being read is **pinned**, so eviction cannot take the memory out
18
+ * from under the reader mid-read;
19
+ * - the pin is released only once the other thread reports it has finished
20
+ * with those bytes — not when they were sent, because nothing was sent.
21
+ */
22
+
23
+ import { findSharedStore } from "../piece-store/shared-piece-store.js";
24
+ import { logger } from "../../utils/logger.js";
25
+ import { askFastestWiresFor, canPlaceRequests, describePieceTail } from "./fastest-wires.js";
26
+ import { minimumBufferFrom, requiredSpeedFrom } from "../supply-margin.js";
27
+
28
+ /** Only waits at least this long are reported; sequential reading stays silent. */
29
+ const PIECE_WAIT_LOG_MS = 1_000;
30
+
31
+ /** Distinguishes concurrent readers to the piece store. Never reused. */
32
+ let readerSequence = 0;
33
+
34
+ /**
35
+ * How far ahead of the read head pieces are asked for.
36
+ *
37
+ * A read is open-ended — ffmpeg opens its input as `bytes <position>-<EOF>` and
38
+ * keeps it for the whole film — so taking the requested range literally asks
39
+ * for everything from the seek point to the end of the file at once. That is
40
+ * what a seek used to do: the swarm was told the entire tail was wanted, went
41
+ * at it from its first missing piece, and the one piece the decoder was blocked
42
+ * on arrived only when the sequential scan reached it. Measured on a 4.7 GB
43
+ * film: a seek to 89.1% took 93 s and pulled 2.47 GB.
44
+ *
45
+ * So the reader asks for a window and moves it as it goes. The size is a
46
+ * compromise the caller cannot yet express: the right unit is seconds of
47
+ * playback (duration and size are both known — to the transcode session, not to
48
+ * this thread), and 32 MB is about 34 s of a 1080p film but only a few seconds
49
+ * of a disc remux. Sizing it from the real byte rate is a follow-up; what
50
+ * matters here is that it is bounded and moving rather than "to the end".
51
+ */
52
+ const READ_WINDOW_BYTES = 32 * 1024 * 1024;
53
+
54
+ /**
55
+ * The pieces a reader at `pieceIndex` wants next, clamped to its own range.
56
+ *
57
+ * @param {{ pieceIndex: number, lastPiece: number, windowPieces: number }} params
58
+ * @returns {{ from: number, to: number }}
59
+ */
60
+ export function readWindowFor({ pieceIndex, lastPiece, windowPieces }) {
61
+ const span = Math.max(1, windowPieces);
62
+ return { from: pieceIndex, to: Math.min(lastPiece, pieceIndex + span - 1) };
63
+ }
64
+
65
+ /**
66
+ * How wide the window should be after a piece that made the reader wait — or
67
+ * did not.
68
+ *
69
+ * The swarm's surplus is what pays for this. Measured 2026-08-17 on the field
70
+ * torrent: 5.1-5.9 MB/s delivered against a film consumed at about 1 MB/s, and
71
+ * the reader still blocked 47 times in two minutes, median 1.5 s, worst 4.5 s.
72
+ * A fivefold surplus never became distance ahead of the head, because the
73
+ * window is a fixed number of seconds of playback and everything past it is
74
+ * ordinary background fill at no priority.
75
+ *
76
+ * So the window follows the evidence: every wait that mattered widens it by a
77
+ * piece, every piece that was already there narrows it back toward the size the
78
+ * caller asked for. Nothing here is chosen — the wait is measured, the
79
+ * threshold is the one that already defines "a wait worth recording", and the
80
+ * ceiling is this reader's share of the store's memory, so widening can never
81
+ * cost more than the store can hold.
82
+ *
83
+ * @param {{ current: number, base: number, ceiling: number, waitedMs: number, waitThresholdMs: number }} params
84
+ * @returns {number}
85
+ */
86
+ export function nextWindowPieces({ current, base, ceiling, waitedMs, waitThresholdMs }) {
87
+ const floor = Math.max(1, Math.floor(base));
88
+ const top = Math.max(floor, Math.floor(ceiling));
89
+ const now = Math.min(top, Math.max(floor, Math.floor(current)));
90
+ if (waitedMs >= waitThresholdMs) {
91
+ return Math.min(top, now + 1);
92
+ }
93
+ return Math.max(floor, now - 1);
94
+ }
95
+
96
+ /**
97
+ * Add this reader's window to the download set as a stream selection.
98
+ *
99
+ * `_select`/`_deselect` with the stream flag are what WebTorrent's own
100
+ * `FileIterator` uses; there is no public call for it, because the public
101
+ * `select` produces the merging, interval-subtracted kind whose bookkeeping
102
+ * cannot express "one of several readers wants this". Falls back to the public
103
+ * call if a future version drops the private one.
104
+ *
105
+ * @param {import("webtorrent").Torrent} torrent
106
+ * @param {{ from: number, to: number }} window
107
+ * @param {number} [priority] - 1 for what a reader needs next, 0 for the
108
+ * background fill of the rest of the file.
109
+ * @returns {void}
110
+ */
111
+ function claimWindow(torrent, { from, to }, priority = 1) {
112
+ try {
113
+ if (typeof torrent._select === "function") {
114
+ torrent._select(from, to, priority, null, true);
115
+ } else if (typeof torrent.select === "function") {
116
+ torrent.select(from, to, priority);
117
+ }
118
+ } catch {
119
+ // Best effort — never fail a read because selection bookkeeping refused.
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Take this reader's window back out of the download set.
125
+ *
126
+ * The bounds must match the ones given to {@link claimWindow} exactly: a stream
127
+ * selection is removed by equality, not by overlap.
128
+ *
129
+ * @param {import("webtorrent").Torrent} torrent
130
+ * @param {{ from: number, to: number }} window
131
+ * @returns {void}
132
+ */
133
+ function releaseWindow(torrent, { from, to }) {
134
+ try {
135
+ if (typeof torrent._deselect === "function") {
136
+ torrent._deselect(from, to, true);
137
+ } else if (typeof torrent.deselect === "function") {
138
+ torrent.deselect(from, to);
139
+ }
140
+ } catch {
141
+ // Best effort.
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Mark the piece a reader is blocked on, clearing the mark it set before.
147
+ *
148
+ * Criticality is never cleared by WebTorrent itself, so a reader that walked a
149
+ * film would leave every piece of it marked. Only the indices this reader set
150
+ * are cleared, so a second reader's mark on the same piece is not stolen — and
151
+ * the flag is advisory anyway.
152
+ *
153
+ * @param {import("webtorrent").Torrent} torrent
154
+ * @param {number} from
155
+ * @param {number} to
156
+ * @param {{ from: number, to: number } | null} previous
157
+ * @returns {{ from: number, to: number } | null}
158
+ */
159
+ function markCritical(torrent, from, to, previous) {
160
+ if (previous && previous.from === from && previous.to === to) {
161
+ return previous;
162
+ }
163
+ if (previous) {
164
+ clearCritical(torrent, previous);
165
+ }
166
+ try {
167
+ torrent.critical?.(from, to);
168
+ } catch {
169
+ return null;
170
+ }
171
+ return { from, to };
172
+ }
173
+
174
+ /**
175
+ * Drop critical marks this reader set.
176
+ *
177
+ * @param {import("webtorrent").Torrent} torrent
178
+ * @param {{ from: number, to: number }} mark
179
+ * @returns {void}
180
+ */
181
+ function clearCritical(torrent, { from, to }) {
182
+ if (!Array.isArray(torrent._critical)) {
183
+ return;
184
+ }
185
+ for (let index = from; index <= to; index += 1) {
186
+ torrent._critical[index] = false;
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Who is working on the piece a reader is blocked on, right now.
192
+ *
193
+ * The open question about a seek: a single 8 MiB piece takes 3.0-4.6 s to
194
+ * arrive while the swarm as a whole is moving 4-6 MB/s, so roughly 2 MB/s is
195
+ * reaching the piece that is actually being waited for. Whether that is because
196
+ * few peers hold it, few are being asked, or each is slow cannot be told apart
197
+ * from the outside — these three counts tell them apart.
198
+ *
199
+ * `wire.requests` is what has been asked of that peer and not yet answered; a
200
+ * block is 16 KB, so `blocks x 16 KB` is the work in flight on this piece.
201
+ *
202
+ * @param {import("webtorrent").Torrent} torrent
203
+ * @param {number} pieceIndex
204
+ * @returns {{ peers: number, holders: number, askedOf: number, blocks: number }}
205
+ */
206
+ export function pieceSupply(torrent, pieceIndex) {
207
+ const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
208
+ let holders = 0;
209
+ let askedOf = 0;
210
+ let blocks = 0;
211
+ for (const wire of wires) {
212
+ if (wire?.peerPieces?.get?.(pieceIndex)) {
213
+ holders += 1;
214
+ }
215
+ const requests = Array.isArray(wire?.requests) ? wire.requests : [];
216
+ const forThisPiece = requests.filter((request) => request?.piece === pieceIndex).length;
217
+ if (forThisPiece > 0) {
218
+ askedOf += 1;
219
+ blocks += forThisPiece;
220
+ }
221
+ }
222
+ return { peers: wires.length, holders, askedOf, blocks };
223
+ }
224
+
225
+ /**
226
+ * Wait until a piece has been downloaded and verified.
227
+ *
228
+ * WebTorrent announces this as `verified`. The bitfield is re-checked after the
229
+ * listener is attached because the piece can complete in between, and a missed
230
+ * event here would wait forever.
231
+ *
232
+ * @param {import("webtorrent").Torrent} torrent
233
+ * @param {number} index
234
+ * @param {{ isCancelled: () => boolean }} cancellation
235
+ * @returns {Promise<void>}
236
+ */
237
+ function whenPieceReady(torrent, index, cancellation) {
238
+ if (torrent.bitfield?.get(index)) {
239
+ return Promise.resolve();
240
+ }
241
+
242
+ return new Promise((resolve, reject) => {
243
+ /** @param {number} verifiedIndex */
244
+ const onVerified = (verifiedIndex) => {
245
+ if (verifiedIndex === index) {
246
+ cleanup();
247
+ resolve();
248
+ }
249
+ };
250
+ const onDestroyed = () => {
251
+ cleanup();
252
+ reject(new Error(`Torrent went away while waiting for piece ${index}.`));
253
+ };
254
+ // Cancellation is polled rather than pushed: a superseded seek destroys the
255
+ // read, and without this the wait would outlive it and hold a pin.
256
+ const poll = setInterval(() => {
257
+ if (cancellation.isCancelled()) {
258
+ cleanup();
259
+ reject(new Error(`Read cancelled while waiting for piece ${index}.`));
260
+ }
261
+ }, 250);
262
+
263
+ function cleanup() {
264
+ clearInterval(poll);
265
+ torrent.removeListener("verified", onVerified);
266
+ torrent.removeListener("close", onDestroyed);
267
+ }
268
+
269
+ torrent.on("verified", onVerified);
270
+ torrent.once("close", onDestroyed);
271
+
272
+ // The piece may have arrived between the check above and this listener.
273
+ if (torrent.bitfield?.get(index)) {
274
+ cleanup();
275
+ resolve();
276
+ }
277
+ });
278
+ }
279
+
280
+ /**
281
+ * A fragment of a read: where to find it, and how to let it go.
282
+ *
283
+ * @typedef {object} PieceFragment
284
+ * @property {number} pieceIndex
285
+ * @property {number} offset - Byte offset into the shared pool.
286
+ * @property {number} length
287
+ * @property {() => void} release - Drops this fragment's pin. Call exactly once.
288
+ */
289
+
290
+ /**
291
+ * Walk a byte range of a file, yielding each piece's position in shared memory.
292
+ *
293
+ * Yields at most one fragment per piece; the first and last are usually partial.
294
+ * The caller must `release()` every fragment it receives, including on failure —
295
+ * an unreleased pin permanently costs a slot.
296
+ *
297
+ * @param {object} params
298
+ * @param {import("webtorrent").Torrent} params.torrent
299
+ * @param {number} params.fileIndex
300
+ * @param {number} params.start - Inclusive, relative to the file.
301
+ * @param {number} params.end - Inclusive, relative to the file.
302
+ * @param {{ isCancelled: () => boolean }} params.cancellation
303
+ * @param {number} [params.windowBytes] - How far ahead of the read head to ask
304
+ * the swarm for. Defaults to {@link READ_WINDOW_BYTES}; a caller that knows
305
+ * the media's byte rate should size it in seconds of playback instead.
306
+ * @returns {AsyncGenerator<PieceFragment>}
307
+ */
308
+ /**
309
+ * The last interruptions this file's readers met, newest last.
310
+ *
311
+ * Bounded and per file, because both figures derived from it describe THIS
312
+ * file on THIS swarm: a piece is 8 MiB here and 512 KiB elsewhere, and a swarm
313
+ * that answers in 200 ms today may not tomorrow. Nothing is stored beyond the
314
+ * process — a restart starts from no evidence, which is the honest state.
315
+ *
316
+ * @type {Map<string, Array<{ waitedMs: number, at: number }>>}
317
+ */
318
+ const supplyWaits = new Map();
319
+
320
+ /** How many interruptions are kept per file. */
321
+ const SUPPLY_WAIT_HISTORY = 40;
322
+
323
+ /** How often the derived figures are printed, at most. */
324
+ const SUPPLY_REPORT_INTERVAL_MS = 30_000;
325
+
326
+ /** When each file's figures were last printed. */
327
+ const supplyReportedAt = new Map();
328
+
329
+ /**
330
+ * Record one interruption and, at most twice a minute, say what it implies.
331
+ *
332
+ * The two figures are the whole of roadmap item 3: the speed a step must
333
+ * sustain to survive this supply (`1 + worst wait / median interval`), and the
334
+ * smallest buffer that hides an interruption from the viewer. Both are printed
335
+ * before either is USED, so the field says whether the arithmetic describes
336
+ * reality before anything is decided by it.
337
+ *
338
+ * @param {string} key - Something stable per file.
339
+ * @param {string} label - What to call it in the log.
340
+ * @param {number} waitedMs
341
+ * @returns {void}
342
+ */
343
+ /**
344
+ * What this file's recent interruptions demand, for a caller that has to decide
345
+ * something with them.
346
+ *
347
+ * Exported because the figures are measured HERE — the reader is the only place
348
+ * that knows how long it waited — while the decisions they feed are made
349
+ * elsewhere: the smallest buffer that hides an interruption goes to the browser,
350
+ * and the speed a step must sustain goes to the quality offer.
351
+ *
352
+ * @param {string} infoHash
353
+ * @param {string} fileName
354
+ * @param {number} segmentSeconds - The session's own segment duration.
355
+ * @returns {{ requiredSpeed: number, worstWaitSec: number, medianIntervalSec: number, samples: number, minimumBufferSec: number } | null}
356
+ */
357
+ export function supplyFiguresFor(infoHash, fileName, segmentSeconds) {
358
+ const history = supplyWaits.get(`${infoHash ?? "?"}/${fileName ?? "?"}`);
359
+ const demand = requiredSpeedFrom(history ?? []);
360
+ if (!demand) {
361
+ return null;
362
+ }
363
+ const buffer = minimumBufferFrom({
364
+ segmentSeconds,
365
+ worstSupplyWaitSec: demand.worstWaitSec
366
+ });
367
+ return {
368
+ requiredSpeed: demand.requiredSpeed,
369
+ worstWaitSec: demand.worstWaitSec,
370
+ medianIntervalSec: demand.medianIntervalSec,
371
+ samples: demand.samples,
372
+ minimumBufferSec: buffer ? buffer.seconds : null
373
+ };
374
+ }
375
+
376
+ function noteSupplyWait(key, label, waitedMs) {
377
+ const history = supplyWaits.get(key) ?? [];
378
+ history.push({ waitedMs, at: Date.now() });
379
+ while (history.length > SUPPLY_WAIT_HISTORY) {
380
+ history.shift();
381
+ }
382
+ supplyWaits.set(key, history);
383
+
384
+ const now = Date.now();
385
+ if (now - (supplyReportedAt.get(key) ?? 0) < SUPPLY_REPORT_INTERVAL_MS) {
386
+ return;
387
+ }
388
+ const demand = requiredSpeedFrom(history);
389
+ if (!demand) {
390
+ return;
391
+ }
392
+ supplyReportedAt.set(key, now);
393
+ const buffer = minimumBufferFrom({
394
+ segmentSeconds: SEGMENT_SECONDS_FOR_BUFFER,
395
+ worstSupplyWaitSec: demand.worstWaitSec
396
+ });
397
+ logger.info(
398
+ `supply "${label.slice(0, 40)}": a step must run at ${demand.requiredSpeed.toFixed(2)}x ` +
399
+ `to survive this swarm (worst wait ${demand.worstWaitSec.toFixed(2)}s, one every ` +
400
+ `${demand.medianIntervalSec.toFixed(2)}s, ${demand.samples} measured) — ` +
401
+ `and the smallest buffer that hides it is ${buffer ? buffer.seconds.toFixed(1) : "?"}s`
402
+ );
403
+ }
404
+
405
+ /**
406
+ * The segment length the buffer figure is stated against. The reader does not
407
+ * know the session's own, and this is a REPORT rather than a decision — the
408
+ * decision, when it is made, will use the session's real one.
409
+ */
410
+ const SEGMENT_SECONDS_FOR_BUFFER = 4;
411
+
412
+ export async function* readFragments({
413
+ torrent,
414
+ fileIndex,
415
+ start,
416
+ end,
417
+ cancellation,
418
+ windowBytes = READ_WINDOW_BYTES
419
+ }) {
420
+ const store = findSharedStore(torrent);
421
+ if (!store) {
422
+ throw new Error("This torrent is not backed by a shared piece store.");
423
+ }
424
+
425
+ const file = torrent.files?.[fileIndex];
426
+ if (!file) {
427
+ throw new Error(`File ${fileIndex} not found.`);
428
+ }
429
+
430
+ const pieceLength = torrent.pieceLength;
431
+ // Piece numbers are torrent-wide, so a file's own offsets have to be lifted
432
+ // into the torrent's address space first.
433
+ const absoluteStart = file.offset + start;
434
+ const absoluteEnd = file.offset + end;
435
+ const firstPiece = Math.floor(absoluteStart / pieceLength);
436
+ const lastPiece = Math.floor(absoluteEnd / pieceLength);
437
+
438
+ // This reader owns what it asks for, and gives it back when it is done. The
439
+ // window is a STREAM selection: those are removed by exact bounds and several
440
+ // identical ones coexist — WebTorrent's own source calls that "in a way a
441
+ // count" — so N readers on one torrent produce the union of their windows,
442
+ // and each one leaving takes away only its own. That is what makes several
443
+ // parallel readers (the codec probe's head and tail, subtitles, one input per
444
+ // viewer) cooperate instead of overwrite each other.
445
+ //
446
+ // The previous code selected the whole requested range, marked all of it
447
+ // critical, and never deselected anything — so ffmpeg's opening
448
+ // `bytes 0-<EOF>` left a permanent selection over the entire file, and no
449
+ // later prioritisation could outrank it.
450
+ const basePieces = Math.max(1, Math.ceil(Math.max(1, windowBytes) / pieceLength));
451
+ // What the window is RIGHT NOW. It starts at what the caller sized in seconds
452
+ // of playback and grows while the reader keeps being made to wait — see
453
+ // `nextWindowPieces`.
454
+ let windowPieces = basePieces;
455
+ /**
456
+ * The widest this reader may go: its share of what the store can hold in
457
+ * memory. Measured rather than chosen — the capacity is the store's own, and
458
+ * the number of readers is how many windows are declared on it right now.
459
+ *
460
+ * @returns {number}
461
+ */
462
+ const ceilingPieces = () => {
463
+ const capacity = Number(store?.capacity);
464
+ if (!Number.isFinite(capacity) || capacity <= 0) {
465
+ return basePieces;
466
+ }
467
+ const readers = Math.max(1, store.protectedRanges?.().length ?? 1);
468
+ return Math.max(basePieces, Math.floor(capacity / readers));
469
+ };
470
+ /** @type {{ from: number, to: number } | null} */
471
+ let window = null;
472
+ /** @type {{ from: number, to: number } | null} */
473
+ let criticalMark = null;
474
+ /**
475
+ * Drops the pin of the fragment currently in the consumer's hands, if it
476
+ * still holds one. See where it is assigned.
477
+ *
478
+ * @type {(() => void) | null}
479
+ */
480
+ let releaseHeldPin = null;
481
+
482
+ // Identity of this read, so the store can tell one reader's window from
483
+ // another's. Each read gets its own; `readerSequence` never repeats within a
484
+ // process.
485
+ const readerId = `read-${(readerSequence += 1)}`;
486
+
487
+ /**
488
+ * Set when the window JUMPS, cleared by the first wait after it.
489
+ *
490
+ * The wait that follows a jump is the cost of the jump: the pieces at the new
491
+ * position have not been asked for yet, and the encoder is restarting. It is
492
+ * not evidence about how well this swarm SUSTAINS a read, which is the only
493
+ * thing `requiredSpeed` is about — and letting it in is what collapsed the
494
+ * quality offer 131 ms after the seek measured on 2026-08-18, refusing every
495
+ * re-encoded rung on the strength of one jump.
496
+ *
497
+ * @type {boolean}
498
+ */
499
+ let waitBelongsToJump = false;
500
+
501
+ const moveWindowTo = (pieceIndex) => {
502
+ const next = readWindowFor({ pieceIndex, lastPiece, windowPieces });
503
+ if (window && window.from === next.from && window.to === next.to) {
504
+ return;
505
+ }
506
+ const isJump = !window || next.from > window.to || next.from < window.from;
507
+ if (window) {
508
+ releaseWindow(torrent, window);
509
+ }
510
+ claimWindow(torrent, next);
511
+ window = next;
512
+ // Tell the store these pieces are wanted, so it evicts something else.
513
+ // Without it the piece the decoder reads next looks exactly as stale as one
514
+ // the encoder fetched forty minutes ahead, and the second kind is what
515
+ // fills the store while the encoder runs ahead of the viewer.
516
+ store.protectRange?.(readerId, next.from, next.to);
517
+ if (isJump) {
518
+ waitBelongsToJump = true;
519
+ // A jump — a seek, not the window sliding along — can land on pieces that
520
+ // are already downloaded but have been spilled to disk. Bring the whole
521
+ // window back at once instead of one disk round trip per piece as the
522
+ // reader reaches them.
523
+ const revived = store.warmRange?.(next.from, next.to) ?? 0;
524
+ if (revived > 0) {
525
+ logger.info(
526
+ `piece-reader: reviving ${revived} spilled piece(s) of ${next.from}-${next.to} ` +
527
+ `for a jump to ${(start / 1024 / 1024).toFixed(0)}MB of "${file.name}"`
528
+ );
529
+ }
530
+ }
531
+ };
532
+
533
+ try {
534
+ for (let pieceIndex = firstPiece; pieceIndex <= lastPiece; pieceIndex += 1) {
535
+ if (cancellation.isCancelled()) {
536
+ return;
537
+ }
538
+
539
+ const pieceStart = pieceIndex * pieceLength;
540
+ const fromWithinPiece = Math.max(absoluteStart, pieceStart) - pieceStart;
541
+ const toWithinPiece = Math.min(absoluteEnd, pieceStart + pieceLength - 1) - pieceStart;
542
+
543
+ moveWindowTo(pieceIndex);
544
+
545
+ if (!torrent.bitfield?.get(pieceIndex)) {
546
+ // Everything from here to the end of the window is wanted NOW, so all
547
+ // of it is marked, not just the piece under the head. `critical`
548
+ // enables hotswap: a block reserved by a slow peer is re-requested from
549
+ // a faster one instead of holding up the reader. Measured 2026-08-04
550
+ // with only the blocked piece marked, the first segment after a seek
551
+ // took 7.2 s while its four 4 MB pieces arrived one after another at
552
+ // ~2.2 MB/s, with waits of 1.3 s and 2.8 s on single pieces.
553
+ //
554
+ // This is not the old behaviour returning: that marked the whole
555
+ // REQUESTED RANGE, which for ffmpeg's input means every piece to the
556
+ // end of the file — hundreds of them, at which point the flag says
557
+ // nothing. A window is what a reader genuinely needs next.
558
+ criticalMark = markCritical(torrent, pieceIndex, window.to, criticalMark);
559
+ }
560
+
561
+ const waitStartedAt = Date.now();
562
+ // The reader is blocked, so this piece is now the only thing that matters
563
+ // on this torrent: hand it to the fastest wires that hold it. A block is
564
+ // reserved for exactly one wire, and the read ends when the slowest
565
+ // holder delivers — measured 2026-08-17, the swarm had a fivefold surplus
566
+ // of bandwidth and the reader still waited 1.0-4.5 s, 47 times in two
567
+ // minutes, on pieces five peers already had.
568
+ let pushed = { asked: 0, attempted: 0, considered: 0, fastestBytesPerSecond: 0 };
569
+ // The tail as it stood at an attempt that placed NOTHING — the state the
570
+ // duplication work has to answer, and the only one worth a line. Sampled
571
+ // at that instant rather than once up front, because the steering runs
572
+ // again every half second and the piece changes under it; the last such
573
+ // reading is kept, so the line describes the most recent failure.
574
+ let tailWhenNothingPlaced = null;
575
+ const pushToFastest = () => {
576
+ try {
577
+ const result = askFastestWiresFor(torrent, pieceIndex);
578
+ if (result.asked === 0) {
579
+ tailWhenNothingPlaced = describePieceTail(torrent, pieceIndex);
580
+ }
581
+ pushed = {
582
+ asked: pushed.asked + result.asked,
583
+ // Summed like the successes, so the line compares two totals over
584
+ // the same attempts instead of a total against a snapshot.
585
+ attempted: (pushed.attempted ?? 0) + result.attempted,
586
+ considered: result.considered,
587
+ fastestBytesPerSecond: result.fastestBytesPerSecond
588
+ };
589
+ } catch (error) {
590
+ // The entry is internal to the library; if a version changes it, this
591
+ // lever stops working and that must be visible rather than silent.
592
+ logger.warn(`piece-reader: could not steer piece ${pieceIndex} — ${error?.message ?? error}`);
593
+ }
594
+ };
595
+ if (canPlaceRequests(torrent)) {
596
+ pushToFastest();
597
+ } else {
598
+ // Nothing can be placed at all on this build, so the tail is the whole
599
+ // of the answer.
600
+ tailWhenNothingPlaced = describePieceTail(torrent, pieceIndex);
601
+ logger.warn(
602
+ "piece-reader: this webtorrent build offers no way to place a request; " +
603
+ "the blocked piece cannot be steered onto a faster peer"
604
+ );
605
+ }
606
+ // Sampled while waiting rather than after: once the piece lands, nothing
607
+ // is outstanding on it any more and every count reads zero.
608
+ let supply = null;
609
+ const supplyProbe = setInterval(() => {
610
+ const sample = pieceSupply(torrent, pieceIndex);
611
+ if (!supply || sample.blocks > supply.blocks) {
612
+ supply = sample;
613
+ }
614
+ // Wires come and go, and their speeds change: a holder that was slow a
615
+ // moment ago may now be the fastest one available.
616
+ pushToFastest();
617
+ }, 500);
618
+ try {
619
+ await whenPieceReady(torrent, pieceIndex, cancellation);
620
+ } finally {
621
+ clearInterval(supplyProbe);
622
+ }
623
+ // What a reader spent waiting for data, attributed to the exact piece. A
624
+ // seek's cost is dominated by the first segment after the encoder
625
+ // restarts (measured 9.2-9.4 s), and without this there is no way to say
626
+ // whether that is the swarm, the picker, or ffmpeg. Logged only when the
627
+ // wait is long enough to matter, so ordinary sequential reading is silent.
628
+ const waitedMs = Date.now() - waitStartedAt;
629
+ // The window answers to what just happened: a wait means the lead was too
630
+ // short, an immediate hit means it is longer than it needs to be. Applied
631
+ // before the logging below so the line reports the window the next piece
632
+ // will actually use.
633
+ if (waitBelongsToJump) {
634
+ // Recorded nowhere: see `waitBelongsToJump`. Said out loud, because a
635
+ // gap in the supply history is otherwise indistinguishable from a swarm
636
+ // that never made the reader wait.
637
+ logger.info(
638
+ `piece-reader: ${waitedMs}ms on the first piece after a jump — the cost of moving, ` +
639
+ `not of this swarm's supply, so it is not counted against the quality offer`
640
+ );
641
+ waitBelongsToJump = false;
642
+ } else {
643
+ noteSupplyWait(`${torrent?.infoHash ?? "?"}/${file?.name ?? "?"}`, file?.name ?? "", waitedMs);
644
+ }
645
+ const widened = nextWindowPieces({
646
+ current: windowPieces,
647
+ base: basePieces,
648
+ ceiling: ceilingPieces(),
649
+ waitedMs,
650
+ waitThresholdMs: PIECE_WAIT_LOG_MS
651
+ });
652
+ if (widened !== windowPieces) {
653
+ windowPieces = widened;
654
+ }
655
+ if (waitedMs >= PIECE_WAIT_LOG_MS) {
656
+ const rateKbps = Math.round(pieceLength / 1024 / (waitedMs / 1000));
657
+ logger.info(
658
+ `piece-reader: waited ${waitedMs}ms for piece ${pieceIndex} ` +
659
+ `(${pieceIndex - firstPiece + 1} of ${lastPiece - firstPiece + 1} in a read from ` +
660
+ `${(start / 1024 / 1024).toFixed(0)}MB of "${file.name}") ` +
661
+ `— ${rateKbps}KB/s on this piece; ` +
662
+ (supply
663
+ ? `${supply.holders}/${supply.peers} peers had it, ${supply.askedOf} were asked, ` +
664
+ `${supply.blocks} blocks (${Math.round((supply.blocks * 16384) / 1024)}KB) in flight at peak`
665
+ : "no sample taken") +
666
+ // What WE did about it, so the next session says whether steering
667
+ // the piece onto faster holders shortens the tail — by number
668
+ // rather than by impression.
669
+ `; steered onto ${pushed.asked} of ${pushed.attempted} asks (${pushed.considered} peers held it)` +
670
+ (pushed.fastestBytesPerSecond > 0
671
+ ? `, fastest ${Math.round(pushed.fastestBytesPerSecond / 1024)}KB/s`
672
+ : "") +
673
+ // Only when the steering placed nothing, which is the case that
674
+ // decides whether duplicating the tail is worth building: it says
675
+ // how much of the piece is still missing and which wires are
676
+ // holding it, slowest first.
677
+ (tailWhenNothingPlaced
678
+ ? `; tail ${tailWhenNothingPlaced.missing}/${tailWhenNothingPlaced.chunks} blocks missing, held by ` +
679
+ (tailWhenNothingPlaced.outstanding.length > 0
680
+ ? tailWhenNothingPlaced.outstanding
681
+ .map((wire) => `${wire.blocks}@${Math.round(wire.bytesPerSecond / 1024)}KB/s` +
682
+ (wire.choking ? " (choking)" : ""))
683
+ .join(" ")
684
+ : "nobody")
685
+ : "")
686
+ );
687
+ }
688
+
689
+ // Pinned BEFORE it is located, and before any await that could let an
690
+ // eviction run: the offset is only meaningful while the piece is held.
691
+ store.pin(pieceIndex);
692
+ let located = null;
693
+ try {
694
+ located = await store.reside(pieceIndex);
695
+ } catch (error) {
696
+ store.unpin(pieceIndex);
697
+ throw error;
698
+ }
699
+
700
+ if (!located) {
701
+ store.unpin(pieceIndex);
702
+ throw new Error(`Piece ${pieceIndex} is verified but absent from the store.`);
703
+ }
704
+
705
+ let releasedThisPiece = false;
706
+ // Remembered so the generator can drop it itself. The pin is taken here
707
+ // and the consumer is expected to release it — but a consumer that
708
+ // ABANDONS the iterator never gets the chance, and a seek abandons it
709
+ // every time: the encoder is killed, the response is torn down, and the
710
+ // loop is left between two fragments. Field 2026-08-06: after one seek
711
+ // every slot in the store was pinned, the store answered
712
+ // `Every resident piece is pinned; no slot can be freed` — to the
713
+ // WebTorrent client, which closed the store and destroyed the torrent —
714
+ // and the session died with `File 0 not found`.
715
+ releaseHeldPin = () => {
716
+ if (!releasedThisPiece) {
717
+ releasedThisPiece = true;
718
+ store.unpin(pieceIndex);
719
+ }
720
+ };
721
+ yield {
722
+ pieceIndex,
723
+ offset: located.offset + fromWithinPiece,
724
+ length: toWithinPiece - fromWithinPiece + 1,
725
+ release() {
726
+ if (releasedThisPiece) {
727
+ return;
728
+ }
729
+ releasedThisPiece = true;
730
+ store.unpin(pieceIndex);
731
+ }
732
+ };
733
+ // Handed back, and released by the consumer or not at all — either way
734
+ // this reader no longer owes anything for it.
735
+ releaseHeldPin = null;
736
+ }
737
+ } finally {
738
+ // A fragment handed out and never released is a slot lost for the life of
739
+ // the process. Reached on every exit, including the consumer walking away.
740
+ if (releaseHeldPin) {
741
+ releaseHeldPin();
742
+ releaseHeldPin = null;
743
+ }
744
+ // Reached on completion, on cancellation, on a throw, and when the consumer
745
+ // stops iterating — a window left behind would keep the swarm fetching for
746
+ // a reader that no longer exists.
747
+ if (window) {
748
+ releaseWindow(torrent, window);
749
+ }
750
+ store.releaseProtection?.(readerId);
751
+ if (criticalMark) {
752
+ clearCritical(torrent, criticalMark);
753
+ }
754
+ }
755
+ }