@torrent-tv/proxy 2.38.0 → 2.39.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,12 @@
1
+ ## 2.39.0
2
+
3
+ - **New**: When a reader is blocked and nothing can be steered, the blocks it is still waiting on are asked of a second wire as well. WebTorrent reserves each block for exactly one wire, so once `Piece.reserve()` answers -1 the read ends when the holder of the last block delivers it, however fast the rest of the swarm is. The library's own `_hotswap` does exactly the right thing — `piece.cancel(block)` frees the reservation while the first request stays in flight — but only for a wire under 48 KB/s and twice as slow as the asker, and measured on a real swarm the tails a reader waits on sit at 109-886 KB/s. Peers the library rightly calls good, because for bulk downloading they are; the gate is about throughput across a torrent and knows nothing about a reader blocked on one piece now. Speed is not even what is wrong with them: two blocks — 32 KB — on a wire measured at 109 KB/s is 0.3 s of transfer, and that read waited 4.6 s, because the blocks are queued behind that wire's other work. **Measured against itself, same film, same positions, arms alternated, six pairs across two pacing rates: the median wait for a piece fell in all six — 39 %, 48 %, 68 %, 6 %, 50 % and 28 %.** In the one pair where the swarm had spare capacity throughout, the wait fell 7226→5174 ms and the lead the reader kept ended at +2.0 MB instead of +0.3 MB. Cost: one duplicate per candidate wire per attempt, about 3 % extra traffic, and only while a reader is blocked with every block already spoken for. The tail measurement added in 2.38.1 reports what it placed: `duplicated 14 blocks`.
4
+ - **Chore**: The first attempt at this was reverted the same day on a measurement that could not have shown it. That probe read 64 MB flat out, so its total time was bytes ÷ aggregate rate by construction — a quantity no reordering of requests can change. Reordering moves latency between pieces; it does not add throughput. The corrected probe consumes at a film's own byte rate and keeps a lead, which is the state a viewer is in, and there the effect is plain. Recorded in `research/blocked-piece-tail-2026-08-19.md` so the next such decision is not made on the wrong quantity.
5
+
6
+ ## 2.38.1
7
+
8
+ - **New**: When a blocked piece cannot be steered anywhere, the wait line says what is holding it. The steering added in 2.29.0 often places nothing — `steered onto 0 of 9 asks (8 peers held it)`, measured 2026-08-18 while eight peers had the piece — because every block is already reserved and WebTorrent will not hand out a second request for the same block (`Piece.reserve()` answers -1; the only mention of an endgame in the library is a commented-out line). Duplicating those blocks is the standard remedy and costs a block's traffic each time, so this measures the tail before anything is built on it: `tail 2/512 blocks missing, held by 1@12KB/s 1@900KB/s`, slowest wire first, and `held by nobody` when the piece has not been asked for at all. Sampled at the instant an attempt placed nothing rather than once at the start, so the numbers and the reason they are printed describe the same moment. If the missing blocks turn out to sit on one slow wire, duplication is aimed at the right thing; if they are spread across fast ones, the wait has another cause and that work should not be done.
9
+
1
10
  ## 2.38.0
2
11
 
3
12
  - **Fix**: An MP4's keyframe times are read as composition times, on the track the handler names. Two faults, both measured on real releases over the swarm (`research/mp4-composition-times-2026-08-19.md`). (1) The reader took sample times from `stts`, which is DECODE order, and used neither `ctts` nor `elst`: ISO/IEC 14496-12 says `CT(n) = DT(n) + CTTS(n)` (§8.6.1.3) and the edit list then shifts that (§8.6.6.3). Every LostFilm MP4 measured carries a composition offset AND an edit list cancelling it exactly, which is why decode times had been right on them; `Firefly.S01E03.720p.mp4` carries the same 2002-tick offset with NO edit list, and its times were **62.1 ms early on all 34 keyframes** compared against ffmpeg's own `pts_time` — a constant that closes to four decimals as offset (0.08342 s) minus the container start (0.02133 s). After the fix that file matches ffmpeg to the container start, which `computeSegmentBoundaries` already subtracts, and `Superman.720p` — where the terms cancel — is unchanged and exact to 0.0000 s. Version 1 offsets are read as SIGNED, which is what that version exists for; an empty edit (`media_time = -1`) is skipped rather than treated as a shift. (2) The video track was "the first one carrying sync samples", and the handler was never read. That worked only because all seven measured files put video first; the standard identifies a track by `hdlr`, and a file whose audio track carries sync samples, or one leading with a cover-art video track, would have been read from the wrong place — the same defect fixed in the Matroska reader the day before, arrived at from the other side.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.38.0",
3
+ "version": "2.39.0",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -1,128 +1,279 @@
1
- /**
2
- * @file Put the piece a reader is blocked on onto the fastest wires that hold
3
- * it.
4
- *
5
- * Measured 2026-08-17: the swarm delivered 5.1-5.9 MB/s against a film consumed
6
- * at about 1 MB/s — a fivefold surplus — and the reader still blocked 47 times
7
- * in two minutes, 1.0-4.5 s each. So the shortage is not bandwidth. The piece
8
- * that blocked had been requested from a median of five peers, and what set the
9
- * tail was WHICH wire held the last outstanding block: a block is reserved for
10
- * exactly one wire, and the read finishes when the slowest holder delivers.
11
- *
12
- * What the library already does, and what it does not: `torrent.critical()`
13
- * (which the reader already sets over its window) enables HOTSWAP — an idle
14
- * wire may take a block away from the SLOWEST holder. It does not duplicate:
15
- * `piece.reserve()` returns -1 once every block is spoken for, and the
16
- * end-game that would ask a second peer for the same block is commented out in
17
- * `webtorrent/lib/torrent.js`. Hotswap therefore fires only when the library's
18
- * own picker happens to visit an idle wire while our piece is critical.
19
- *
20
- * This asks for it on purpose, and chooses who: the wires that are unchoked,
21
- * hold the piece and are measurably fastest are handed the piece through the
22
- * same entry the library's picker uses, with hotswap enabled. Nothing is
23
- * duplicated and no protocol rule is bent — the block moves to a faster holder
24
- * instead of staying with whoever got it first.
25
- */
26
-
27
- /**
28
- * The library's own request entry. Internal, so its absence must be noticed
29
- * rather than swallowed: without it this lever silently does nothing.
30
- *
31
- * @param {object} torrent
32
- * @returns {boolean}
33
- */
34
- export function canPlaceRequests(torrent) {
35
- return typeof torrent?._request === "function";
36
- }
37
-
38
- /**
39
- * Wires that could deliver this piece right now, fastest first.
40
- *
41
- * Excluded, each for its own reason: a wire that is choking us cannot be asked
42
- * at all; one that does not hold the piece has nothing to give; a destroyed one
43
- * is a corpse. Speed is the library's own measurement over its own window, so
44
- * nothing here needs a history of its own.
45
- *
46
- * @param {object} torrent
47
- * @param {number} pieceIndex
48
- * @returns {object[]}
49
- */
50
- export function wiresForPiece(torrent, pieceIndex) {
51
- const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
52
- const usable = [];
53
- for (const wire of wires) {
54
- if (!wire || wire.destroyed || wire.peerChoking) {
55
- continue;
56
- }
57
- if (wire.peerPieces?.get?.(pieceIndex) !== true) {
58
- continue;
59
- }
60
- usable.push(wire);
61
- }
62
- return usable.sort((left, right) => speedOf(right) - speedOf(left));
63
- }
64
-
65
- /**
66
- * A wire's measured download speed in bytes per second, or 0 when it has not
67
- * been measured. Wrapped because `downloadSpeed` is a method on the wire and a
68
- * throw from a destroyed one must not take the caller with it.
69
- *
70
- * @param {object} wire
71
- * @returns {number}
72
- */
73
- function speedOf(wire) {
74
- try {
75
- const speed = wire?.downloadSpeed?.();
76
- return Number.isFinite(speed) ? speed : 0;
77
- } catch {
78
- // A wire that cannot say how fast it is ranks last, which is the honest
79
- // answer — and the caller's own log line reports how many were asked.
80
- return 0;
81
- }
82
- }
83
-
84
- /**
85
- * Ask the fastest holders of `pieceIndex` for it.
86
- *
87
- * @param {object} torrent
88
- * @param {number} pieceIndex
89
- * @param {number} [limit] - How many wires to push it onto.
90
- * @returns {{ asked: number, attempted: number, considered: number, fastestBytesPerSecond: number }}
91
- * `asked` counts requests the library actually placed: it refuses when a
92
- * wire's pipeline is full or when nothing can be reserved even with hotswap,
93
- * and that refusal is information — a piece nobody can be asked for is
94
- * waiting on the wire, not on the picker.
95
- */
96
- export function askFastestWiresFor(torrent, pieceIndex, limit = 3) {
97
- if (!canPlaceRequests(torrent) || !Number.isInteger(pieceIndex) || pieceIndex < 0) {
98
- return { asked: 0, attempted: 0, considered: 0, fastestBytesPerSecond: 0 };
99
- }
100
- const candidates = wiresForPiece(torrent, pieceIndex);
101
- let asked = 0;
102
- for (const wire of candidates.slice(0, Math.max(1, limit))) {
103
- try {
104
- // `true` is hotswap: if every block is reserved, take one from the
105
- // slowest holder. That is the whole point — the reader is blocked
106
- // precisely because a slow holder has one.
107
- if (torrent._request(wire, pieceIndex, true) === true) {
108
- asked += 1;
109
- }
110
- } catch (error) {
111
- // Internal call: report it once per attempt rather than letting the lever
112
- // fail in silence.
113
- throw new Error(`could not place a request for piece ${pieceIndex}: ${error?.message ?? error}`);
114
- }
115
- }
116
- return {
117
- asked,
118
- considered: candidates.length,
119
- // How many of the asks the library placed, against how many it was asked
120
- // for. The caller sums these over the whole wait, and summing `asked`
121
- // against a `considered` taken from the LAST attempt is how the field log
122
- // came to read "steered onto 12 of 6 holders" — a ratio of two different
123
- // things. Both halves are returned per attempt so the caller can add each
124
- // to its own total.
125
- attempted: Math.min(candidates.length, Math.max(1, limit)),
126
- fastestBytesPerSecond: candidates.length > 0 ? speedOf(candidates[0]) : 0
127
- };
128
- }
1
+ /**
2
+ * @file Put the piece a reader is blocked on onto the fastest wires that hold
3
+ * it.
4
+ *
5
+ * Measured 2026-08-17: the swarm delivered 5.1-5.9 MB/s against a film consumed
6
+ * at about 1 MB/s — a fivefold surplus — and the reader still blocked 47 times
7
+ * in two minutes, 1.0-4.5 s each. So the shortage is not bandwidth. The piece
8
+ * that blocked had been requested from a median of five peers, and what set the
9
+ * tail was WHICH wire held the last outstanding block: a block is reserved for
10
+ * exactly one wire, and the read finishes when the slowest holder delivers.
11
+ *
12
+ * What the library already does, and what it does not: `torrent.critical()`
13
+ * (which the reader already sets over its window) enables HOTSWAP — an idle
14
+ * wire may take a block away from the SLOWEST holder. It does not duplicate:
15
+ * `piece.reserve()` returns -1 once every block is spoken for, and the
16
+ * end-game that would ask a second peer for the same block is commented out in
17
+ * `webtorrent/lib/torrent.js`. Hotswap therefore fires only when the library's
18
+ * own picker happens to visit an idle wire while our piece is critical.
19
+ *
20
+ * This asks for it on purpose, and chooses who: the wires that are unchoked,
21
+ * hold the piece and are measurably fastest are handed the piece through the
22
+ * same entry the library's picker uses, with hotswap enabled. Nothing is
23
+ * duplicated and no protocol rule is bent — the block moves to a faster holder
24
+ * instead of staying with whoever got it first.
25
+ */
26
+
27
+ /**
28
+ * The library's own request entry. Internal, so its absence must be noticed
29
+ * rather than swallowed: without it this lever silently does nothing.
30
+ *
31
+ * @param {object} torrent
32
+ * @returns {boolean}
33
+ */
34
+ export function canPlaceRequests(torrent) {
35
+ return typeof torrent?._request === "function";
36
+ }
37
+
38
+ /**
39
+ * Wires that could deliver this piece right now, fastest first.
40
+ *
41
+ * Excluded, each for its own reason: a wire that is choking us cannot be asked
42
+ * at all; one that does not hold the piece has nothing to give; a destroyed one
43
+ * is a corpse. Speed is the library's own measurement over its own window, so
44
+ * nothing here needs a history of its own.
45
+ *
46
+ * @param {object} torrent
47
+ * @param {number} pieceIndex
48
+ * @returns {object[]}
49
+ */
50
+ export function wiresForPiece(torrent, pieceIndex) {
51
+ const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
52
+ const usable = [];
53
+ for (const wire of wires) {
54
+ if (!wire || wire.destroyed || wire.peerChoking) {
55
+ continue;
56
+ }
57
+ if (wire.peerPieces?.get?.(pieceIndex) !== true) {
58
+ continue;
59
+ }
60
+ usable.push(wire);
61
+ }
62
+ return usable.sort((left, right) => speedOf(right) - speedOf(left));
63
+ }
64
+
65
+ /**
66
+ * A wire's measured download speed in bytes per second, or 0 when it has not
67
+ * been measured. Wrapped because `downloadSpeed` is a method on the wire and a
68
+ * throw from a destroyed one must not take the caller with it.
69
+ *
70
+ * @param {object} wire
71
+ * @returns {number}
72
+ */
73
+ function speedOf(wire) {
74
+ try {
75
+ const speed = wire?.downloadSpeed?.();
76
+ return Number.isFinite(speed) ? speed : 0;
77
+ } catch {
78
+ // A wire that cannot say how fast it is ranks last, which is the honest
79
+ // answer — and the caller's own log line reports how many were asked.
80
+ return 0;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Ask the fastest holders of `pieceIndex` for it.
86
+ *
87
+ * @param {object} torrent
88
+ * @param {number} pieceIndex
89
+ * @param {number} [limit] - How many wires to push it onto.
90
+ * @returns {{ asked: number, attempted: number, considered: number, fastestBytesPerSecond: number }}
91
+ * `asked` counts requests the library actually placed: it refuses when a
92
+ * wire's pipeline is full or when nothing can be reserved even with hotswap,
93
+ * and that refusal is information — a piece nobody can be asked for is
94
+ * waiting on the wire, not on the picker.
95
+ */
96
+ export function askFastestWiresFor(torrent, pieceIndex, limit = 3) {
97
+ if (!canPlaceRequests(torrent) || !Number.isInteger(pieceIndex) || pieceIndex < 0) {
98
+ return { asked: 0, attempted: 0, considered: 0, fastestBytesPerSecond: 0 };
99
+ }
100
+ const candidates = wiresForPiece(torrent, pieceIndex);
101
+ let asked = 0;
102
+ for (const wire of candidates.slice(0, Math.max(1, limit))) {
103
+ try {
104
+ // `true` is hotswap: if every block is reserved, take one from the
105
+ // slowest holder. That is the whole point — the reader is blocked
106
+ // precisely because a slow holder has one.
107
+ if (torrent._request(wire, pieceIndex, true) === true) {
108
+ asked += 1;
109
+ }
110
+ } catch (error) {
111
+ // Internal call: report it once per attempt rather than letting the lever
112
+ // fail in silence.
113
+ throw new Error(`could not place a request for piece ${pieceIndex}: ${error?.message ?? error}`);
114
+ }
115
+ }
116
+ return {
117
+ asked,
118
+ considered: candidates.length,
119
+ // How many of the asks the library placed, against how many it was asked
120
+ // for. The caller sums these over the whole wait, and summing `asked`
121
+ // against a `considered` taken from the LAST attempt is how the field log
122
+ // came to read "steered onto 12 of 6 holders" — a ratio of two different
123
+ // things. Both halves are returned per attempt so the caller can add each
124
+ // to its own total.
125
+ attempted: Math.min(candidates.length, Math.max(1, limit)),
126
+ fastestBytesPerSecond: candidates.length > 0 ? speedOf(candidates[0]) : 0
127
+ };
128
+ }
129
+
130
+ /**
131
+ * What is actually holding up a piece the reader is blocked on.
132
+ *
133
+ * The steering above can only move a block that the library will hand over, and
134
+ * the field says it often hands over nothing: `steered onto 0 of 9 asks (8
135
+ * peers held it)`, recorded 2026-08-18 while eight peers had the piece. When
136
+ * every block of a piece is already reserved, `Piece.reserve()` answers -1 and
137
+ * there is no request left to place — the read then ends when the SLOWEST
138
+ * holder delivers its block, however fast the rest of the swarm is.
139
+ *
140
+ * Duplicating those last blocks onto faster wires is the standard remedy, and
141
+ * it is not free: every duplicate is a block's worth of traffic paid twice. So
142
+ * this describes the tail before anything is built with it — how many blocks
143
+ * are still missing, and on which wires they sit, with each wire's speed. If
144
+ * the missing blocks turn out to sit on one slow wire, duplication is aimed at
145
+ * exactly the right thing; if they are spread across fast ones, the wait has
146
+ * another cause and this work should not be done at all.
147
+ *
148
+ * Reads only: nothing here changes a reservation or places a request.
149
+ *
150
+ * @param {import("webtorrent").Torrent} torrent
151
+ * @param {number} pieceIndex
152
+ * @returns {{ chunks: number, missing: number,
153
+ * outstanding: Array<{ blocks: number, bytesPerSecond: number, choking: boolean }> } | null}
154
+ * Null only when the piece object is gone — it completed and was cleared.
155
+ * A piece nobody has reserved a block of yet is NOT null: `torrent-piece`
156
+ * creates its buffer lazily on the first reserve, so a piece the picker has
157
+ * not reached reads as every block missing and nothing outstanding, which is
158
+ * the most informative answer this can give — the wait is not on a slow
159
+ * holder, it is on nobody having been asked.
160
+ */
161
+ export function describePieceTail(torrent, pieceIndex) {
162
+ const piece = torrent?.pieces?.[pieceIndex];
163
+ if (!piece) {
164
+ return null;
165
+ }
166
+ const buffer = Array.isArray(piece._buffer) ? piece._buffer : null;
167
+ const chunks = Number.isFinite(piece._chunks)
168
+ ? piece._chunks
169
+ : (buffer ? buffer.length : 0);
170
+ // No buffer means no block of this piece has been reserved yet, so all of it
171
+ // is missing. Reading that as "no tail" hid the case worth seeing most.
172
+ let missing = chunks;
173
+ if (buffer) {
174
+ missing = 0;
175
+ for (let index = 0; index < chunks; index += 1) {
176
+ if (!buffer[index]) {
177
+ missing += 1;
178
+ }
179
+ }
180
+ }
181
+
182
+ const wires = Array.isArray(torrent?.wires) ? torrent.wires : [];
183
+ const outstanding = [];
184
+ for (const wire of wires) {
185
+ const requests = Array.isArray(wire?.requests) ? wire.requests : [];
186
+ const blocks = requests.filter((request) => request?.piece === pieceIndex).length;
187
+ if (blocks > 0) {
188
+ outstanding.push({
189
+ blocks,
190
+ bytesPerSecond: speedOf(wire),
191
+ choking: wire?.peerChoking === true
192
+ });
193
+ }
194
+ }
195
+ // Slowest first: that is the wire the read is waiting on, and the one a
196
+ // duplicate would be aimed past.
197
+ outstanding.sort((left, right) => left.bytesPerSecond - right.bytesPerSecond);
198
+ return { chunks, missing, outstanding };
199
+ }
200
+
201
+ /**
202
+ * Ask a second wire for blocks the reader is still waiting on.
203
+ *
204
+ * WebTorrent reserves each block for exactly one wire, so once `Piece.reserve()`
205
+ * answers -1 there is no request left to place and the read ends when the
206
+ * holder of the last block delivers it — however fast the rest of the swarm is.
207
+ * The library's own remedy is `_hotswap`, and it does precisely the right
208
+ * thing: `piece.cancel(blockIndex)` frees the reservation while leaving the
209
+ * first wire's request in flight, so a second wire can be asked for the same
210
+ * block and whichever arrives first wins. What it will not do is apply that to
211
+ * these tails. It is gated on speed — the held-up wire must be under 48 KB/s
212
+ * (`3 * BLOCK_LENGTH`) and at least twice as slow as the asker — and measured
213
+ * on a real swarm 2026-08-19, the tails a reader waits on sit at 109, 317 and
214
+ * 870 KB/s. Peers the library rightly considers good, because for bulk
215
+ * downloading they are; the gate is about throughput across a torrent and knows
216
+ * nothing about a reader blocked on one piece now.
217
+ *
218
+ * Speed is not even what is wrong with them: two blocks — 32 KB — on a wire
219
+ * measured at 109 KB/s is 0.3 s of transfer, and that read waited 4.6 s. The
220
+ * blocks are not travelling slowly, they are queued behind that wire's other
221
+ * work, which no average speed can show.
222
+ *
223
+ * The cost is bounded by the same measurement: the tails were 2 to 14 blocks of
224
+ * 512, so 32 to 224 KB against the 8 MiB piece they hold up. At most one
225
+ * duplicate is asked per candidate wire per call, and the caller repeats every
226
+ * half second, so a longer tail is covered across attempts rather than in one
227
+ * burst.
228
+ *
229
+ * Safe against the completion path: a block that arrives twice is dropped by
230
+ * `Piece.set`, which writes only into an empty slot, and a piece already
231
+ * flushed answers `false` from `Piece.init` so the second arrival returns
232
+ * before `flush()` is reached.
233
+ *
234
+ * @param {object} torrent
235
+ * @param {number} pieceIndex
236
+ * @returns {{ duplicated: number, missing: number, wires: number }}
237
+ * `duplicated` counts requests the library actually placed for a block that
238
+ * was already outstanding elsewhere.
239
+ */
240
+ export function duplicateTailFor(torrent, pieceIndex) {
241
+ const piece = torrent?.pieces?.[pieceIndex];
242
+ const buffer = Array.isArray(piece?._buffer) ? piece._buffer : null;
243
+ if (!piece || !buffer || typeof piece.cancel !== "function") {
244
+ return { duplicated: 0, missing: 0, wires: 0 };
245
+ }
246
+ const chunks = Number.isFinite(piece._chunks) ? piece._chunks : buffer.length;
247
+ const missing = [];
248
+ for (let index = 0; index < chunks; index += 1) {
249
+ if (!buffer[index]) {
250
+ missing.push(index);
251
+ }
252
+ }
253
+ const candidates = wiresForPiece(torrent, pieceIndex);
254
+ if (missing.length === 0 || candidates.length === 0) {
255
+ return { duplicated: 0, missing: missing.length, wires: candidates.length };
256
+ }
257
+
258
+ let duplicated = 0;
259
+ // One block per wire: that is what the pipelines can usefully take at once,
260
+ // and it needs no number of its own.
261
+ for (let index = 0; index < Math.min(missing.length, candidates.length); index += 1) {
262
+ // Freeing the reservation is what makes the block askable again; the
263
+ // request already in flight is deliberately left alone, because the point
264
+ // is to have two of them.
265
+ piece.cancel(missing[index]);
266
+ // `false` is hotswap: the library's own swap must not run on top of this,
267
+ // or it would free a THIRD wire's block as well.
268
+ if (torrent._request(candidates[index], pieceIndex, false) === true) {
269
+ duplicated += 1;
270
+ continue;
271
+ }
272
+ // The wire's pipeline is full. The block stays in the piece's cancellation
273
+ // stack and will be handed to whoever asks next, which is harmless — it is
274
+ // already in flight elsewhere — but there is no point asking the remaining
275
+ // wires, whose pipelines are no emptier.
276
+ break;
277
+ }
278
+ return { duplicated, missing: missing.length, wires: candidates.length };
279
+ }