@torrent-tv/proxy 2.73.0 → 2.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +1447 -1432
  2. package/CLAUDE.md +165 -160
  3. package/docs/container-architecture.md +192 -184
  4. package/package.json +1 -1
  5. package/routes/api/subtitles/get.js +205 -205
  6. package/services/container/Container.js +354 -135
  7. package/services/container/MatroskaContainer.js +1155 -516
  8. package/services/container/Mp4Container.js +858 -392
  9. package/services/container/SubtitleFileContainer.js +323 -261
  10. package/services/controllers/SubtitleController.js +128 -127
  11. package/services/delivery-probe.js +64 -6
  12. package/services/hls-session-manager.js +32 -35
  13. package/services/language-detect.js +174 -228
  14. package/services/orchestrators/SubtitleOrchestrator.js +64 -5
  15. package/services/playback-planner.js +747 -747
  16. package/services/produced-index.js +300 -0
  17. package/services/torrent-worker/subtitle-cues.js +582 -618
  18. package/services/tracks/TextSubtitleTrack.js +287 -47
  19. package/services/tracks/index.js +14 -14
  20. package/test/delivery-probe.test.js +67 -0
  21. package/test/matroska-blocks.test.js +0 -0
  22. package/test/mp4-subtitles.test.js +173 -127
  23. package/test/produced-index.test.js +188 -0
  24. package/test/subtitle-cue-framing.test.js +200 -202
  25. package/test/subtitle-cue-source.test.js +104 -0
  26. package/test/subtitle-cue-walk.test.js +369 -0
  27. package/test/subtitle-defaults.test.js +97 -97
  28. package/test/subtitle-language.test.js +252 -252
  29. package/test/subtitle-track-numbering.test.js +370 -370
  30. package/services/container-index/matroska-blocks.js +0 -202
  31. package/services/container-index/matroska-subtitles.js +0 -372
  32. package/services/container-index/mp4-subtitles.js +0 -404
  33. package/services/subtitle-convert.js +0 -144
  34. package/services/subtitle-defaults.js +0 -157
  35. package/services/tracks/subtitle-markup.js +0 -104
@@ -1,202 +1,200 @@
1
- /**
2
- * @file Two axes, kept apart: the framing a CONTAINER puts round a cue, and the
3
- * markup the CODEC puts inside it.
4
- *
5
- * Field 2026-09-03, an English track of an embedded `.mkv`: the viewer was
6
- * shown `21,0,Default,,0000,0000,0000,,I am the powerful Demon King of the
7
- * Sixth Heaven.` — the whole dialogue row, fields and all. The cause was one
8
- * function doing both jobs and deciding which framing it held by counting
9
- * commas: it expected the ten fields a row has in a FILE, a Matroska block
10
- * carries nine, so it returned the row untouched.
11
- *
12
- * What each check here pins is therefore not "ASS is stripped" but "the right
13
- * side answers": the container takes off what it put on, and the codec takes
14
- * off what it put in. The case that matters most is the last one — the same
15
- * line of dialogue, stored two ways, coming out identical.
16
- */
17
-
18
- import test from "node:test";
19
- import assert from "node:assert/strict";
20
-
21
- import { AviContainer } from "../services/container/AviContainer.js";
22
- import { MatroskaContainer } from "../services/container/MatroskaContainer.js";
23
- import { Mp4Container } from "../services/container/Mp4Container.js";
24
- import { SubtitleFileContainer } from "../services/container/SubtitleFileContainer.js";
25
- import { convertSubtitleToVtt, cuesToVtt, finalizeCues } from "../services/subtitle-convert.js";
26
- import { MarkupKind, markupKindOf, plainCueText } from "../services/tracks/subtitle-markup.js";
27
- import { TextSubtitleTrack } from "../services/tracks/TextSubtitleTrack.js";
28
-
29
- /** The line from the field report, as Matroska stores it. */
30
- const FIELD_BLOCK =
31
- "21,0,Default,,0000,0000,0000,,I am the powerful Demon King of the Sixth Heaven. Good... Evil...";
32
-
33
- function block(text) {
34
- return Buffer.from(text, "utf8");
35
- }
36
-
37
- test("a Matroska ASS block gives up its text and nothing else", () => {
38
- // Nine fields exactly, and no comma in the dialogue: the shape that defeated
39
- // the old field count and put the whole row on the viewer's screen.
40
- assert.equal(
41
- MatroskaContainer.cueTextOf(block(FIELD_BLOCK), "S_TEXT/ASS"),
42
- "I am the powerful Demon King of the Sixth Heaven. Good... Evil..."
43
- );
44
- });
45
-
46
- test("commas in the dialogue are dialogue, not fields", () => {
47
- assert.equal(
48
- MatroskaContainer.cueTextOf(block("7,0,Main,Nobunaga,0000,0000,0000,,Yes, of course, my lord"), "S_TEXT/ASS"),
49
- "Yes, of course, my lord"
50
- );
51
- });
52
-
53
- test("an SSA block is framed the same way as an ASS one", () => {
54
- // SSA writes `Marked` where ASS writes `Layer`; the count is the same and so
55
- // is the answer.
56
- assert.equal(
57
- MatroskaContainer.cueTextOf(block("3,,Default,,0000,0000,0000,,Toujours rien."), "S_TEXT/SSA"),
58
- "Toujours rien."
59
- );
60
- });
61
-
62
- test("a row too short to hold a text field yields nothing to show", () => {
63
- assert.equal(MatroskaContainer.cueTextOf(block("21,0,Default,,0000"), "S_TEXT/ASS"), "");
64
- assert.equal(MatroskaContainer.cueTextOf(block("21,0,Default,,0000,0000,0000,,"), "S_TEXT/ASS"), "");
65
- });
66
-
67
- test("a plain-text Matroska block is not touched at all", () => {
68
- // `S_TEXT/UTF8` has no framing: the block IS the text, commas included.
69
- const line = "Yes, of course, my lord";
70
- assert.equal(MatroskaContainer.cueTextOf(block(line), "S_TEXT/UTF8"), line);
71
- assert.equal(MatroskaContainer.cueTextOf(block(line), "S_TEXT/WEBVTT"), line);
72
- });
73
-
74
- test("an MP4 sample is unframed by the MP4, length prefix and all", () => {
75
- const text = Buffer.from("Yes, of course, my lord", "utf8");
76
- const sample = Buffer.concat([Buffer.from([0x00, text.length]), text]);
77
- assert.equal(Mp4Container.cueTextOf(sample, "tx3g"), "Yes, of course, my lord");
78
- });
79
-
80
- test("a container with no framing of its own refuses to guess", () => {
81
- // AVI declares no subtitle tracks, so no cue can reach it. If one ever did,
82
- // the answer must be an error and not a guess at somebody else's framing.
83
- assert.throws(() => AviContainer.cueTextOf(block("x"), "S_TEXT/ASS"), /cueTextOf not implemented/);
84
- });
85
-
86
- test("ASS markup is taken off wherever the text came from", () => {
87
- assert.equal(plainCueText("{\\pos(640,620)}Hello{\\i1} there{\\i0}", "S_TEXT/ASS"), "Hello there");
88
- assert.equal(plainCueText("First\\NSecond\\nThird", "S_TEXT/ASS"), "First\nSecond\nThird");
89
- assert.equal(plainCueText("Wide\\hspace", "S_TEXT/ASS"), "Wide space");
90
- // The same text under a codec that has no such markup keeps its characters.
91
- assert.equal(plainCueText("{\\pos(1,2)}Hello", "S_TEXT/UTF8"), "{\\pos(1,2)}Hello");
92
- });
93
-
94
- test("a codec is known by any of its names", () => {
95
- assert.equal(markupKindOf("S_TEXT/ASS"), MarkupKind.ASS);
96
- assert.equal(markupKindOf(".ASS"), MarkupKind.ASS);
97
- assert.equal(markupKindOf("S_TEXT/UTF8"), MarkupKind.NONE);
98
- assert.equal(markupKindOf("wvtt"), MarkupKind.NONE);
99
- // Unknown: shown as it is, rather than refused.
100
- assert.equal(markupKindOf("S_TEXT/SOMETHING"), MarkupKind.NONE);
101
- });
102
-
103
- test("a text track answers for its own markup", () => {
104
- const track = new TextSubtitleTrack({ trackNumber: 3, declaredIndex: 0, codecId: "S_TEXT/ASS" });
105
- assert.equal(track.markupKind, MarkupKind.ASS);
106
- assert.equal(track.plainText("{\\be1}Готовьте лучников"), "Готовьте лучников");
107
- });
108
-
109
- test("a file states its own column order and is obeyed", () => {
110
- // This `Format:` has no `Name` column, so the text is the ninth field and not
111
- // the tenth. A reader that assumed a position would take the effect field as
112
- // the line — which is the file-side form of the defect this suite is about.
113
- const file = [
114
- "[Script Info]",
115
- "ScriptType: v4.00+",
116
- "[Events]",
117
- "Format: Layer, Start, End, Style, MarginL, MarginR, MarginV, Effect, Text",
118
- "Dialogue: 0,0:00:01.00,0:00:03.50,Default,0000,0000,0000,,Ты видишь их?",
119
- ""
120
- ].join("\n");
121
-
122
- const cues = new SubtitleFileContainer({ extension: ".ass" }).readCues(file);
123
- assert.deepEqual(cues, [{ startSeconds: 1, endSeconds: 3.5, text: "Ты видишь их?" }]);
124
- });
125
-
126
- test("a dialogue row before any Format line is not guessed at", () => {
127
- const file = ["[Events]", "Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,Ignored", ""].join("\n");
128
- assert.deepEqual(new SubtitleFileContainer({ extension: ".ass" }).readCues(file), []);
129
- });
130
-
131
- test("SubRip cues keep their words and lose their numbering", () => {
132
- const file = [
133
- "1",
134
- "00:00:01,000 --> 00:00:03,500",
135
- "Ты видишь их?",
136
- "",
137
- "2",
138
- "00:01:02,250 --> 00:01:04,000",
139
- "<i>Да.</i>",
140
- "Но не столько вижу.",
141
- ""
142
- ].join("\n");
143
-
144
- const cues = new SubtitleFileContainer({ extension: ".srt" }).readCues(file);
145
- assert.deepEqual(cues, [
146
- { startSeconds: 1, endSeconds: 3.5, text: "Ты видишь их?" },
147
- { startSeconds: 62.25, endSeconds: 64, text: "<i>Да.</i>\nНо не столько вижу." }
148
- ]);
149
- });
150
-
151
- test("a SubRip file with no blank line between cues does not swallow the ordinal", () => {
152
- const file = [
153
- "1",
154
- "00:00:01,000 --> 00:00:02,000",
155
- "First",
156
- "2",
157
- "00:00:03,000 --> 00:00:04,000",
158
- "Second"
159
- ].join("\n");
160
-
161
- const cues = new SubtitleFileContainer({ extension: ".srt" }).readCues(file);
162
- assert.deepEqual(cues.map((cue) => cue.text), ["First", "Second"]);
163
- });
164
-
165
- test("a WebVTT file is passed through, not taken apart", () => {
166
- const file = "WEBVTT\n\nSTYLE\n::cue { color: yellow }\n\nintro\n00:00:01.000 --> 00:00:02.000\nHello\n";
167
- assert.equal(convertSubtitleToVtt(file, ".vtt"), file);
168
- assert.equal(new SubtitleFileContainer({ extension: ".vtt" }).readCues(file), null);
169
- });
170
-
171
- test("a format nothing here reads is refused rather than mangled", () => {
172
- assert.equal(convertSubtitleToVtt("whatever", ".sup"), null);
173
- assert.equal(convertSubtitleToVtt("whatever", ".ttml"), null);
174
- });
175
-
176
- test("one line of dialogue, two framings, one result", () => {
177
- // The whole point of the split. The same ASS line stored in a Matroska block
178
- // and in a file must reach the viewer identically, and neither path may know
179
- // anything about the other.
180
- const spoken = "Yes, of course, my lord";
181
- const markup = `{\\pos(640,620)}${spoken}`;
182
-
183
- const fromBlock = finalizeCues(
184
- [{
185
- startSeconds: 1,
186
- endSeconds: 3,
187
- text: MatroskaContainer.cueTextOf(block(`21,0,Default,,0000,0000,0000,,${markup}`), "S_TEXT/ASS")
188
- }],
189
- "S_TEXT/ASS"
190
- );
191
-
192
- const fromFile = new SubtitleFileContainer({ extension: ".ass" }).readCues([
193
- "[Events]",
194
- "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
195
- `Dialogue: 0,0:00:01.00,0:00:03.00,Default,,0000,0000,0000,,${markup}`,
196
- ""
197
- ].join("\n"));
198
-
199
- assert.equal(fromBlock[0].text, spoken);
200
- assert.equal(finalizeCues(fromFile, ".ass")[0].text, spoken);
201
- assert.equal(cuesToVtt(fromBlock, "S_TEXT/ASS"), cuesToVtt(fromFile, ".ass"));
202
- });
1
+ /**
2
+ * @file Two axes, kept apart: the framing a CONTAINER puts round a cue, and the
3
+ * markup the CODEC puts inside it.
4
+ *
5
+ * Field 2026-09-03, an English track of an embedded `.mkv`: the viewer was
6
+ * shown `21,0,Default,,0000,0000,0000,,I am the powerful Demon King of the
7
+ * Sixth Heaven.` — the whole dialogue row, fields and all. The cause was one
8
+ * function doing both jobs and deciding which framing it held by counting
9
+ * commas: it expected the ten fields a row has in a FILE, a Matroska block
10
+ * carries nine, so it returned the row untouched.
11
+ *
12
+ * What each check here pins is therefore not "ASS is stripped" but "the right
13
+ * side answers": the container takes off what it put on, and the codec takes
14
+ * off what it put in. The case that matters most is the last one — the same
15
+ * line of dialogue, stored two ways, coming out identical.
16
+ */
17
+
18
+ import test from "node:test";
19
+ import assert from "node:assert/strict";
20
+
21
+ import { AviContainer } from "../services/container/AviContainer.js";
22
+ import { MatroskaContainer } from "../services/container/MatroskaContainer.js";
23
+ import { Mp4Container } from "../services/container/Mp4Container.js";
24
+ import { SubtitleFileContainer } from "../services/container/SubtitleFileContainer.js";
25
+ import { MarkupKind, TextSubtitleTrack } from "../services/tracks/TextSubtitleTrack.js";
26
+
27
+ /** The line from the field report, as Matroska stores it. */
28
+ const FIELD_BLOCK =
29
+ "21,0,Default,,0000,0000,0000,,I am the powerful Demon King of the Sixth Heaven. Good... Evil...";
30
+
31
+ function block(text) {
32
+ return Buffer.from(text, "utf8");
33
+ }
34
+
35
+ test("a Matroska ASS block gives up its text and nothing else", () => {
36
+ // Nine fields exactly, and no comma in the dialogue: the shape that defeated
37
+ // the old field count and put the whole row on the viewer's screen.
38
+ assert.equal(
39
+ MatroskaContainer.cueTextOf(block(FIELD_BLOCK), "S_TEXT/ASS"),
40
+ "I am the powerful Demon King of the Sixth Heaven. Good... Evil..."
41
+ );
42
+ });
43
+
44
+ test("commas in the dialogue are dialogue, not fields", () => {
45
+ assert.equal(
46
+ MatroskaContainer.cueTextOf(block("7,0,Main,Nobunaga,0000,0000,0000,,Yes, of course, my lord"), "S_TEXT/ASS"),
47
+ "Yes, of course, my lord"
48
+ );
49
+ });
50
+
51
+ test("an SSA block is framed the same way as an ASS one", () => {
52
+ // SSA writes `Marked` where ASS writes `Layer`; the count is the same and so
53
+ // is the answer.
54
+ assert.equal(
55
+ MatroskaContainer.cueTextOf(block("3,,Default,,0000,0000,0000,,Toujours rien."), "S_TEXT/SSA"),
56
+ "Toujours rien."
57
+ );
58
+ });
59
+
60
+ test("a row too short to hold a text field yields nothing to show", () => {
61
+ assert.equal(MatroskaContainer.cueTextOf(block("21,0,Default,,0000"), "S_TEXT/ASS"), "");
62
+ assert.equal(MatroskaContainer.cueTextOf(block("21,0,Default,,0000,0000,0000,,"), "S_TEXT/ASS"), "");
63
+ });
64
+
65
+ test("a plain-text Matroska block is not touched at all", () => {
66
+ // `S_TEXT/UTF8` has no framing: the block IS the text, commas included.
67
+ const line = "Yes, of course, my lord";
68
+ assert.equal(MatroskaContainer.cueTextOf(block(line), "S_TEXT/UTF8"), line);
69
+ assert.equal(MatroskaContainer.cueTextOf(block(line), "S_TEXT/WEBVTT"), line);
70
+ });
71
+
72
+ test("an MP4 sample is unframed by the MP4, length prefix and all", () => {
73
+ const text = Buffer.from("Yes, of course, my lord", "utf8");
74
+ const sample = Buffer.concat([Buffer.from([0x00, text.length]), text]);
75
+ assert.equal(Mp4Container.cueTextOf(sample, "tx3g"), "Yes, of course, my lord");
76
+ });
77
+
78
+ test("a container with no framing of its own refuses to guess", () => {
79
+ // AVI declares no subtitle tracks, so no cue can reach it. If one ever did,
80
+ // the answer must be an error and not a guess at somebody else's framing.
81
+ assert.throws(() => AviContainer.cueTextOf(block("x"), "S_TEXT/ASS"), /cueTextOf not implemented/);
82
+ });
83
+
84
+ test("ASS markup is taken off wherever the text came from", () => {
85
+ assert.equal(TextSubtitleTrack.plainTextOf("{\\pos(640,620)}Hello{\\i1} there{\\i0}", "S_TEXT/ASS"), "Hello there");
86
+ assert.equal(TextSubtitleTrack.plainTextOf("First\\NSecond\\nThird", "S_TEXT/ASS"), "First\nSecond\nThird");
87
+ assert.equal(TextSubtitleTrack.plainTextOf("Wide\\hspace", "S_TEXT/ASS"), "Wide space");
88
+ // The same text under a codec that has no such markup keeps its characters.
89
+ assert.equal(TextSubtitleTrack.plainTextOf("{\\pos(1,2)}Hello", "S_TEXT/UTF8"), "{\\pos(1,2)}Hello");
90
+ });
91
+
92
+ test("a codec is known by any of its names", () => {
93
+ assert.equal(TextSubtitleTrack.markupKindOf("S_TEXT/ASS"), MarkupKind.ASS);
94
+ assert.equal(TextSubtitleTrack.markupKindOf(".ASS"), MarkupKind.ASS);
95
+ assert.equal(TextSubtitleTrack.markupKindOf("S_TEXT/UTF8"), MarkupKind.NONE);
96
+ assert.equal(TextSubtitleTrack.markupKindOf("wvtt"), MarkupKind.NONE);
97
+ // Unknown: shown as it is, rather than refused.
98
+ assert.equal(TextSubtitleTrack.markupKindOf("S_TEXT/SOMETHING"), MarkupKind.NONE);
99
+ });
100
+
101
+ test("a text track answers for its own markup", () => {
102
+ const track = new TextSubtitleTrack({ trackNumber: 3, declaredIndex: 0, codecId: "S_TEXT/ASS" });
103
+ assert.equal(track.markupKind, MarkupKind.ASS);
104
+ assert.equal(track.plainText("{\\be1}Готовьте лучников"), "Готовьте лучников");
105
+ });
106
+
107
+ test("a file states its own column order and is obeyed", () => {
108
+ // This `Format:` has no `Name` column, so the text is the ninth field and not
109
+ // the tenth. A reader that assumed a position would take the effect field as
110
+ // the line which is the file-side form of the defect this suite is about.
111
+ const file = [
112
+ "[Script Info]",
113
+ "ScriptType: v4.00+",
114
+ "[Events]",
115
+ "Format: Layer, Start, End, Style, MarginL, MarginR, MarginV, Effect, Text",
116
+ "Dialogue: 0,0:00:01.00,0:00:03.50,Default,0000,0000,0000,,Ты видишь их?",
117
+ ""
118
+ ].join("\n");
119
+
120
+ const cues = new SubtitleFileContainer({ extension: ".ass" }).readCues(file);
121
+ assert.deepEqual(cues, [{ startSeconds: 1, endSeconds: 3.5, text: "Ты видишь их?" }]);
122
+ });
123
+
124
+ test("a dialogue row before any Format line is not guessed at", () => {
125
+ const file = ["[Events]", "Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,Ignored", ""].join("\n");
126
+ assert.deepEqual(new SubtitleFileContainer({ extension: ".ass" }).readCues(file), []);
127
+ });
128
+
129
+ test("SubRip cues keep their words and lose their numbering", () => {
130
+ const file = [
131
+ "1",
132
+ "00:00:01,000 --> 00:00:03,500",
133
+ "Ты видишь их?",
134
+ "",
135
+ "2",
136
+ "00:01:02,250 --> 00:01:04,000",
137
+ "<i>Да.</i>",
138
+ "Но не столько вижу.",
139
+ ""
140
+ ].join("\n");
141
+
142
+ const cues = new SubtitleFileContainer({ extension: ".srt" }).readCues(file);
143
+ assert.deepEqual(cues, [
144
+ { startSeconds: 1, endSeconds: 3.5, text: "Ты видишь их?" },
145
+ { startSeconds: 62.25, endSeconds: 64, text: "<i>Да.</i>\nНо не столько вижу." }
146
+ ]);
147
+ });
148
+
149
+ test("a SubRip file with no blank line between cues does not swallow the ordinal", () => {
150
+ const file = [
151
+ "1",
152
+ "00:00:01,000 --> 00:00:02,000",
153
+ "First",
154
+ "2",
155
+ "00:00:03,000 --> 00:00:04,000",
156
+ "Second"
157
+ ].join("\n");
158
+
159
+ const cues = new SubtitleFileContainer({ extension: ".srt" }).readCues(file);
160
+ assert.deepEqual(cues.map((cue) => cue.text), ["First", "Second"]);
161
+ });
162
+
163
+ test("a WebVTT file is passed through, not taken apart", () => {
164
+ const file = "WEBVTT\n\nSTYLE\n::cue { color: yellow }\n\nintro\n00:00:01.000 --> 00:00:02.000\nHello\n";
165
+ assert.equal(SubtitleFileContainer.toVtt(file, ".vtt"), file);
166
+ assert.equal(new SubtitleFileContainer({ extension: ".vtt" }).readCues(file), null);
167
+ });
168
+
169
+ test("a format nothing here reads is refused rather than mangled", () => {
170
+ assert.equal(SubtitleFileContainer.toVtt("whatever", ".sup"), null);
171
+ assert.equal(SubtitleFileContainer.toVtt("whatever", ".ttml"), null);
172
+ });
173
+
174
+ test("one line of dialogue, two framings, one result", () => {
175
+ // The whole point of the split. The same ASS line stored in a Matroska block
176
+ // and in a file must reach the viewer identically, and neither path may know
177
+ // anything about the other.
178
+ const spoken = "Yes, of course, my lord";
179
+ const markup = `{\\pos(640,620)}${spoken}`;
180
+
181
+ const fromBlock = TextSubtitleTrack.finalizeCues(
182
+ [{
183
+ startSeconds: 1,
184
+ endSeconds: 3,
185
+ text: MatroskaContainer.cueTextOf(block(`21,0,Default,,0000,0000,0000,,${markup}`), "S_TEXT/ASS")
186
+ }],
187
+ "S_TEXT/ASS"
188
+ );
189
+
190
+ const fromFile = new SubtitleFileContainer({ extension: ".ass" }).readCues([
191
+ "[Events]",
192
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
193
+ `Dialogue: 0,0:00:01.00,0:00:03.00,Default,,0000,0000,0000,,${markup}`,
194
+ ""
195
+ ].join("\n"));
196
+
197
+ assert.equal(fromBlock[0].text, spoken);
198
+ assert.equal(TextSubtitleTrack.finalizeCues(fromFile, ".ass")[0].text, spoken);
199
+ assert.equal(TextSubtitleTrack.cuesToVtt(fromBlock, "S_TEXT/ASS"), TextSubtitleTrack.cuesToVtt(fromFile, ".ass"));
200
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @file WHICH THREAD answers a pull for subtitle cues.
3
+ *
4
+ * Field 2026-09-03, on `[HorribleSubs] Drifters - 04 [1080p].mkv`. The file had
5
+ * been downloaded in an earlier sitting, so the torrent worker's cluster walk
6
+ * found cues 1.5 s after the file was opened and pushed four batches — cursor 1
7
+ * to 31, covering everything up to 81.7 s — before the browser had subscribed.
8
+ * The browser's catch-up pull, which exists for exactly that case, answered a
9
+ * seven-byte `WEBVTT` with `x-subtitle-covered-clusters: 0` against 283
10
+ * indexed. So the viewer watched the first 82 s with no subtitles and the rest
11
+ * of the episode with them.
12
+ *
13
+ * The pull ran on the MAIN thread, where the torrent is a stand-in carrying
14
+ * `infoHash`, `name` and a `files` list — no `bitfield`, no `pieceLength`. The
15
+ * walk decides what it may read from those two, so every range read as "not
16
+ * downloaded", nothing was walked, and an empty document came back. An empty
17
+ * document is also the right answer for a file that holds no cues yet, which is
18
+ * why nothing reported a failure.
19
+ *
20
+ * These checks pin the two halves of the repair: the pull is addressed to the
21
+ * thread that owns the torrent, and a walk asked of a torrent that cannot say
22
+ * what it holds says so rather than answering emptily.
23
+ */
24
+
25
+ import test from "node:test";
26
+ import assert from "node:assert/strict";
27
+
28
+ import { SubtitleOrchestrator } from "../services/orchestrators/SubtitleOrchestrator.js";
29
+ import { cuesHeldFor } from "../services/torrent-worker/subtitle-cues.js";
30
+
31
+ /** The stand-in the main thread holds: a name, a file list, and no pieces. */
32
+ function mainThreadTorrent() {
33
+ return {
34
+ infoHash: "0".repeat(40),
35
+ name: "[HorribleSubs] Drifters - 04 [1080p].mkv",
36
+ sourceKey: "a".repeat(40),
37
+ files: [{ name: "[HorribleSubs] Drifters - 04 [1080p].mkv", length: 567_535_843, createReadStream: () => { throw new Error("not reached"); } }]
38
+ };
39
+ }
40
+
41
+ test("a pull is answered by the thread that owns the torrent, not walked here", async () => {
42
+ const asked = [];
43
+ const pool = {
44
+ async getSubtitleCues(torrent, fileIndex, trackNumber) {
45
+ asked.push({ sourceKey: torrent.sourceKey, fileIndex, trackNumber });
46
+ return {
47
+ cues: [{ startSeconds: 5.4, endSeconds: 9.1, text: "So what if you brought them over?", seq: 1 }],
48
+ coveredClusters: 283,
49
+ indexedClusters: 283,
50
+ codecId: "S_TEXT/ASS",
51
+ codecPrivate: "",
52
+ language: ""
53
+ };
54
+ }
55
+ };
56
+
57
+ const orchestrator = new SubtitleOrchestrator({ forget() {} });
58
+ const held = await orchestrator.getCues(pool, mainThreadTorrent(), 33, "a".repeat(40), 3);
59
+
60
+ assert.deepEqual(asked, [{ sourceKey: "a".repeat(40), fileIndex: 33, trackNumber: 3 }]);
61
+ assert.equal(held.cues.length, 1);
62
+ assert.equal(held.coveredClusters, 283, "the walk's own figure travels back, so the header cannot claim 0 of 283");
63
+ // The worker answers with the track's fields flat — only plain objects cross
64
+ // the boundary — and the caller reads them through `held.track`.
65
+ assert.equal(held.track.codecId, "S_TEXT/ASS");
66
+ });
67
+
68
+ test("the cursor of a pulled cue is the found-order the worker assigned", async () => {
69
+ // The browser mixes cursors from pulls and pushes. Walking a second time on
70
+ // another thread would start a second `seq` counter and the two would not be
71
+ // comparable, which is the deeper reason the pull is not served locally.
72
+ const pool = {
73
+ async getSubtitleCues() {
74
+ return {
75
+ cues: [
76
+ { startSeconds: 5.4, endSeconds: 9.1, text: "one", seq: 1 },
77
+ { startSeconds: 81.7, endSeconds: 84.0, text: "two", seq: 31 }
78
+ ],
79
+ coveredClusters: 12,
80
+ indexedClusters: 283,
81
+ codecId: "S_TEXT/ASS",
82
+ codecPrivate: "",
83
+ language: ""
84
+ };
85
+ }
86
+ };
87
+ const orchestrator = new SubtitleOrchestrator({ forget() {} });
88
+ const held = await orchestrator.getCues(pool, mainThreadTorrent(), 33, "a".repeat(40), 3);
89
+ assert.deepEqual(held.cues.map((cue) => cue.seq), [1, 31]);
90
+ });
91
+
92
+ test("a pool with no channel to the worker is refused, not answered emptily", async () => {
93
+ const orchestrator = new SubtitleOrchestrator({ forget() {} });
94
+ const held = await orchestrator.getCues({}, mainThreadTorrent(), 33, "a".repeat(40), 3);
95
+ assert.deepEqual(held, { cues: [], coveredClusters: 0, indexedClusters: 0, track: null });
96
+ });
97
+
98
+ test("the walk refuses a torrent that cannot say which pieces it holds", async () => {
99
+ // Called directly, as the main thread used to call it. Without this guard the
100
+ // answer is an empty list indistinguishable from a file with no cues, which
101
+ // is what hid the defect for a whole session.
102
+ const held = await cuesHeldFor(mainThreadTorrent(), 33, "b".repeat(40), 3);
103
+ assert.deepEqual(held, { cues: [], coveredClusters: 0, indexedClusters: 0, track: null });
104
+ });