@torrent-tv/proxy 2.55.14 → 2.57.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.
@@ -0,0 +1,262 @@
1
+ /**
2
+ * @file The number a subtitle track is asked for by, and one walk per file.
3
+ *
4
+ * Two rules, both found by reading on 2026-08-26 after the report that embedded
5
+ * subtitles appear late (`research/subtitle-delay-2026-08-26.md`):
6
+ *
7
+ * 1. The browser names a track by ffmpeg's `0:s:N`, which counts EVERY subtitle
8
+ * stream. The container plan drops the picture-based ones — PGS, VobSub —
9
+ * because they cannot become WebVTT, so counting the kept ones is a
10
+ * different numbering as soon as a file carries one of each. What that cost:
11
+ * the push landed on a track the browser does not know, and the browser's
12
+ * own request found no track at all and fell through to the ffmpeg
13
+ * extraction, which reads the whole film (752 s measured, 2026-08-19).
14
+ * 2. A file is walked once at a time. The walk marks a cluster as read only
15
+ * after two suspension points, and it is started both on every verified
16
+ * piece and on a 3 s timer, so two passes could read and parse the same
17
+ * cluster and push the same line twice.
18
+ */
19
+
20
+ import test from "node:test";
21
+ import assert from "node:assert/strict";
22
+ import { Readable } from "node:stream";
23
+ import { readSubtitlePlan } from "../services/container-index/matroska-subtitles.js";
24
+ import { cuesHeldFor, forgetSubtitles } from "../services/torrent-worker/subtitle-cues.js";
25
+
26
+ const ID_EBML = 0x1a45dfa3;
27
+ const ID_SEGMENT = 0x18538067;
28
+ const ID_SEEK_HEAD = 0x114d9b74;
29
+ const ID_SEEK = 0x4dbb;
30
+ const ID_SEEK_ID = 0x53ab;
31
+ const ID_SEEK_POSITION = 0x53ac;
32
+ const ID_INFO = 0x1549a966;
33
+ const ID_TIMESTAMP_SCALE = 0x2ad7b1;
34
+ const ID_TRACKS = 0x1654ae6b;
35
+ const ID_TRACK_ENTRY = 0xae;
36
+ const ID_TRACK_NUMBER = 0xd7;
37
+ const ID_TRACK_TYPE = 0x83;
38
+ const ID_CODEC_ID = 0x86;
39
+ const ID_LANGUAGE = 0x22b59c;
40
+ const ID_CUES = 0x1c53bb6b;
41
+ const ID_CUE_POINT = 0xbb;
42
+ const ID_CUE_TIME = 0xb3;
43
+ const ID_CUE_TRACK_POSITIONS = 0xb7;
44
+ const ID_CUE_TRACK = 0xf7;
45
+ const ID_CUE_CLUSTER_POSITION = 0xf1;
46
+ const ID_CLUSTER = 0x1f43b675;
47
+ const ID_TIMESTAMP = 0xe7;
48
+
49
+ /** An element id, as the bytes the specification gives it. */
50
+ function idBytes(id) {
51
+ const bytes = [];
52
+ let rest = id;
53
+ while (rest > 0) {
54
+ bytes.unshift(rest & 0xff);
55
+ rest = Math.floor(rest / 256);
56
+ }
57
+ return Buffer.from(bytes);
58
+ }
59
+
60
+ /** A size, as a four-byte EBML variable-length integer. */
61
+ function sizeBytes(size) {
62
+ const buffer = Buffer.alloc(4);
63
+ buffer.writeUInt32BE(size, 0);
64
+ buffer[0] |= 0x10;
65
+ return buffer;
66
+ }
67
+
68
+ function element(id, payload) {
69
+ return Buffer.concat([idBytes(id), sizeBytes(payload.length), payload]);
70
+ }
71
+
72
+ function uintElement(id, value) {
73
+ const bytes = [];
74
+ let rest = value;
75
+ do {
76
+ bytes.unshift(rest & 0xff);
77
+ rest = Math.floor(rest / 256);
78
+ } while (rest > 0);
79
+ return element(id, Buffer.from(bytes));
80
+ }
81
+
82
+ function stringElement(id, value) {
83
+ return element(id, Buffer.from(value, "utf8"));
84
+ }
85
+
86
+ /**
87
+ * An unsigned value at a FIXED four bytes. A cue's cluster position has to be
88
+ * written twice — once to measure the table, once with the position that
89
+ * measurement produced — and a value-sized element would make the second table
90
+ * a different length from the first, moving the very cluster it names.
91
+ */
92
+ function uint32Element(id, value) {
93
+ const payload = Buffer.alloc(4);
94
+ payload.writeUInt32BE(value, 0);
95
+ return element(id, payload);
96
+ }
97
+
98
+ function trackEntry({ number, type, codecId, language }) {
99
+ return element(ID_TRACK_ENTRY, Buffer.concat([
100
+ uintElement(ID_TRACK_NUMBER, number),
101
+ uintElement(ID_TRACK_TYPE, type),
102
+ stringElement(ID_CODEC_ID, codecId),
103
+ stringElement(ID_LANGUAGE, language)
104
+ ]));
105
+ }
106
+
107
+ /**
108
+ * A file whose subtitle tracks are, in the container's own order: a picture
109
+ * one, then two text ones. ffmpeg numbers those `0:s:0`, `0:s:1`, `0:s:2`;
110
+ * the plan can only read the last two.
111
+ *
112
+ * The Cues table points both text tracks at one cluster, which is written after
113
+ * the table so its position can be stated.
114
+ *
115
+ * @returns {{ file: Buffer, clusterAt: number }}
116
+ */
117
+ function buildFile() {
118
+ const info = element(ID_INFO, uintElement(ID_TIMESTAMP_SCALE, 1_000_000));
119
+ const tracks = element(ID_TRACKS, Buffer.concat([
120
+ trackEntry({ number: 1, type: 1, codecId: "V_MPEG4/ISO/AVC", language: "und" }),
121
+ trackEntry({ number: 2, type: 17, codecId: "S_HDMV/PGS", language: "eng" }),
122
+ trackEntry({ number: 3, type: 17, codecId: "S_TEXT/UTF8", language: "rus" }),
123
+ trackEntry({ number: 4, type: 17, codecId: "S_TEXT/ASS", language: "eng" })
124
+ ]));
125
+
126
+ // Built twice: the cue points state where the cluster is, and that position
127
+ // is only known once everything before it has its final length. Every size
128
+ // and position here is written at a fixed width, so the draft and the final
129
+ // table are the same length.
130
+ const cuesWith = (clusterAt) => element(ID_CUES, Buffer.concat([
131
+ element(ID_CUE_POINT, Buffer.concat([
132
+ uintElement(ID_CUE_TIME, 1000),
133
+ element(ID_CUE_TRACK_POSITIONS, Buffer.concat([
134
+ uintElement(ID_CUE_TRACK, 3),
135
+ uint32Element(ID_CUE_CLUSTER_POSITION, clusterAt)
136
+ ])),
137
+ element(ID_CUE_TRACK_POSITIONS, Buffer.concat([
138
+ uintElement(ID_CUE_TRACK, 4),
139
+ uint32Element(ID_CUE_CLUSTER_POSITION, clusterAt)
140
+ ]))
141
+ ]))
142
+ ]));
143
+
144
+ const seekEntry = (targetId, position) => element(ID_SEEK, Buffer.concat([
145
+ element(ID_SEEK_ID, idBytes(targetId)),
146
+ element(ID_SEEK_POSITION, (() => {
147
+ const buffer = Buffer.alloc(4);
148
+ buffer.writeUInt32BE(position, 0);
149
+ return buffer;
150
+ })())
151
+ ]));
152
+ const seekHeadWith = (infoAt, tracksAt, cuesAt) => element(ID_SEEK_HEAD, Buffer.concat([
153
+ seekEntry(ID_INFO, infoAt),
154
+ seekEntry(ID_TRACKS, tracksAt),
155
+ seekEntry(ID_CUES, cuesAt)
156
+ ]));
157
+
158
+ const headLength = seekHeadWith(0, 0, 0).length;
159
+ const infoAt = headLength;
160
+ const tracksAt = infoAt + info.length;
161
+ const cuesAt = tracksAt + tracks.length;
162
+ // A position in the Cues table is measured from the Segment's payload, and so
163
+ // is the one the reader turns it into.
164
+ const clusterRelative = cuesAt + cuesWith(0).length;
165
+
166
+ // Enough of a cluster to be read and recognised: its own header and a
167
+ // timestamp. No blocks, so it yields no cues — what the walk test counts is
168
+ // that its bytes are fetched once, and that does not depend on their content.
169
+ const cluster = element(ID_CLUSTER, uintElement(ID_TIMESTAMP, 1000));
170
+
171
+ const segmentPayload = Buffer.concat([
172
+ seekHeadWith(infoAt, tracksAt, cuesAt),
173
+ info,
174
+ tracks,
175
+ cuesWith(clusterRelative),
176
+ cluster
177
+ ]);
178
+ const ebml = element(ID_EBML, Buffer.from([0x42, 0x86, 0x81, 0x01]));
179
+ const segment = element(ID_SEGMENT, segmentPayload);
180
+ const segmentDataOffset = ebml.length + segment.length - segmentPayload.length;
181
+ return {
182
+ file: Buffer.concat([ebml, segment]),
183
+ clusterAt: segmentDataOffset + clusterRelative
184
+ };
185
+ }
186
+
187
+ function readerOver(file) {
188
+ return async (start, end) => {
189
+ const last = Math.min(end, file.length - 1);
190
+ return start > last ? null : file.subarray(start, last + 1);
191
+ };
192
+ }
193
+
194
+ test("a text track is numbered as ffmpeg numbers it, past the picture ones", async () => {
195
+ const { file } = buildFile();
196
+
197
+ const plan = await readSubtitlePlan(readerOver(file), file.length);
198
+
199
+ assert.equal(plan.declared.length, 3, "all three subtitle tracks are declared");
200
+ assert.deepEqual(plan.tracks.map((track) => track.trackNumber), [3, 4], "only the text ones are readable");
201
+ assert.deepEqual(
202
+ plan.tracks.map((track) => track.declaredIndex),
203
+ [1, 2],
204
+ "the PGS track is 0:s:0, so the text tracks are 0:s:1 and 0:s:2 — not 0 and 1"
205
+ );
206
+ });
207
+
208
+ /**
209
+ * A torrent holding one file entirely, counting the byte ranges read from it.
210
+ *
211
+ * @param {Buffer} bytes
212
+ * @returns {{ torrent: object, reads: Array<{ start: number, end: number }> }}
213
+ */
214
+ function torrentOver(bytes) {
215
+ const reads = [];
216
+ const file = {
217
+ name: "film.mkv",
218
+ length: bytes.length,
219
+ offset: 0,
220
+ createReadStream({ start = 0, end = bytes.length - 1 } = {}) {
221
+ reads.push({ start, end });
222
+ // Asynchronous on purpose: a read that resolves in the same tick would
223
+ // hide exactly the interleaving this test is about.
224
+ return Readable.from((async function* chunks() {
225
+ await new Promise((resolve) => setImmediate(resolve));
226
+ yield bytes.subarray(start, end + 1);
227
+ })());
228
+ }
229
+ };
230
+ return {
231
+ reads,
232
+ torrent: {
233
+ pieceLength: 1024,
234
+ bitfield: { get: () => true },
235
+ files: [file]
236
+ }
237
+ };
238
+ }
239
+
240
+ test("two walks of one file at the same time read each cluster once", async () => {
241
+ const { file, clusterAt } = buildFile();
242
+ const { torrent, reads } = torrentOver(file);
243
+ const sourceKey = "torrent:numbering-test";
244
+ forgetSubtitles(sourceKey);
245
+
246
+ // Both text tracks at once, which is what the warmup does on every verified
247
+ // piece and every three seconds.
248
+ const [first, second] = await Promise.all([
249
+ cuesHeldFor(torrent, 0, sourceKey, 3),
250
+ cuesHeldFor(torrent, 0, sourceKey, 4)
251
+ ]);
252
+
253
+ assert.equal(first.coveredClusters, 1, "the cluster the table names was walked");
254
+ assert.equal(second.coveredClusters, 1, "and the second track sees the same walk, not its own");
255
+ const clusterReads = reads.filter((range) => range.start === clusterAt);
256
+ assert.equal(
257
+ clusterReads.length,
258
+ 2,
259
+ "one probe of the cluster's header and one read of its body — not two of each"
260
+ );
261
+ forgetSubtitles(sourceKey);
262
+ });
@@ -0,0 +1,131 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+
4
+ import { wedgeIsCertain } from "../services/data-channel-handler.js";
5
+ import { PROBE_INTERVAL_MS } from "../services/delivery-probe.js";
6
+
7
+ const MEGABYTE = 1024 * 1024;
8
+
9
+ test("a queue draining at the rate this link was measured at is not a wedge", () => {
10
+ // 8 MB at 16 MB/s is half a second of draining. Half a second in is normal.
11
+ const verdict = wedgeIsCertain({
12
+ queuedBytes: 8 * MEGABYTE,
13
+ bytesPerSecond: 16 * MEGABYTE,
14
+ flatForMs: 200
15
+ });
16
+ assert.equal(verdict.certain, false);
17
+ });
18
+
19
+ test("the counter standing still past the queue's own drain time is a wedge", () => {
20
+ const verdict = wedgeIsCertain({
21
+ queuedBytes: 8 * MEGABYTE,
22
+ bytesPerSecond: 16 * MEGABYTE,
23
+ flatForMs: 4000
24
+ });
25
+ assert.equal(verdict.certain, true);
26
+ assert.equal(verdict.needMs, 500);
27
+ });
28
+
29
+ test("a big queue on a slow link is given the time it genuinely needs", () => {
30
+ // 67 MB at 1 MB/s is 67 seconds of honest draining — the field's own numbers
31
+ // for the wedged channel, at a rate a thin link could really be running at.
32
+ const patient = wedgeIsCertain({
33
+ queuedBytes: 67 * MEGABYTE,
34
+ bytesPerSecond: MEGABYTE,
35
+ flatForMs: 30_000
36
+ });
37
+ assert.equal(patient.certain, false);
38
+ const later = wedgeIsCertain({
39
+ queuedBytes: 67 * MEGABYTE,
40
+ bytesPerSecond: MEGABYTE,
41
+ flatForMs: 70_000
42
+ });
43
+ assert.equal(later.certain, true);
44
+ });
45
+
46
+ test("the same queue on the link the field actually had is called quickly", () => {
47
+ // 67 MB at 18 MB/s is under four seconds. The field episode stood still for
48
+ // 3217 s; the previous rule waited a flat 30 s before recording anything.
49
+ const verdict = wedgeIsCertain({
50
+ queuedBytes: 67 * MEGABYTE,
51
+ bytesPerSecond: 18 * MEGABYTE,
52
+ flatForMs: 5000
53
+ });
54
+ assert.equal(verdict.certain, true);
55
+ assert.ok(verdict.needMs < 30_000);
56
+ });
57
+
58
+ test("a tiny queue still waits for one round of probes", () => {
59
+ const verdict = wedgeIsCertain({
60
+ queuedBytes: 512,
61
+ bytesPerSecond: 16 * MEGABYTE,
62
+ flatForMs: PROBE_INTERVAL_MS - 1
63
+ });
64
+ assert.equal(verdict.certain, false);
65
+ assert.equal(verdict.needMs, PROBE_INTERVAL_MS);
66
+ });
67
+
68
+ test("nothing queued is not a wedge however long the counter has been still", () => {
69
+ const verdict = wedgeIsCertain({
70
+ queuedBytes: 0,
71
+ bytesPerSecond: 16 * MEGABYTE,
72
+ flatForMs: 600_000
73
+ });
74
+ assert.equal(verdict.certain, false);
75
+ assert.equal(verdict.needMs, null);
76
+ });
77
+
78
+ test("with no rate measured the answer is that nothing can be said", () => {
79
+ const verdict = wedgeIsCertain({
80
+ queuedBytes: 8 * MEGABYTE,
81
+ bytesPerSecond: 0,
82
+ flatForMs: 600_000
83
+ });
84
+ assert.equal(verdict.certain, false);
85
+ assert.equal(verdict.needMs, null);
86
+ });
87
+
88
+ test("a pause no longer than this link's own longest healthy pause is not a wedge", () => {
89
+ // A retransmission timeout stops the accepted-byte counter dead: a full send
90
+ // buffer accepts nothing. If this connection has already paused 3 s while
91
+ // healthy, a 3 s pause says nothing.
92
+ const verdict = wedgeIsCertain({
93
+ queuedBytes: 8 * MEGABYTE,
94
+ bytesPerSecond: 18 * MEGABYTE,
95
+ flatForMs: 2500,
96
+ longestHealthyFlatMs: 3000
97
+ });
98
+ assert.equal(verdict.certain, false);
99
+ assert.equal(verdict.needMs, 3000);
100
+ });
101
+
102
+ test("a pause longer than any this link has shown is a wedge", () => {
103
+ const verdict = wedgeIsCertain({
104
+ queuedBytes: 8 * MEGABYTE,
105
+ bytesPerSecond: 18 * MEGABYTE,
106
+ flatForMs: 3500,
107
+ longestHealthyFlatMs: 3000
108
+ });
109
+ assert.equal(verdict.certain, true);
110
+ });
111
+
112
+ test("the quiet-probe rate cannot be what the queue is divided by", () => {
113
+ // With the browser's buffer full, the only traffic is the probe: three
114
+ // channels, a few dozen bytes, twice a second. Dividing 8 MB by that gives
115
+ // six hours, and the wedge would never be called. The BEST rate seen is what
116
+ // the watcher keeps, so this case must not arise — pinned here as the
117
+ // arithmetic that made it matter.
118
+ const wrong = wedgeIsCertain({
119
+ queuedBytes: 8 * MEGABYTE,
120
+ bytesPerSecond: 360,
121
+ flatForMs: 60_000
122
+ });
123
+ assert.equal(wrong.certain, false);
124
+ assert.ok(wrong.needMs > 6 * 60 * 60 * 1000 - 1);
125
+ const right = wedgeIsCertain({
126
+ queuedBytes: 8 * MEGABYTE,
127
+ bytesPerSecond: 18 * MEGABYTE,
128
+ flatForMs: 60_000
129
+ });
130
+ assert.equal(right.certain, true);
131
+ });