@torrent-tv/proxy 2.68.0 → 2.69.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.
@@ -0,0 +1,241 @@
1
+ /**
2
+ * @file What the language detector is FED.
3
+ *
4
+ * Field 2026-09-01: a Russian subtitle file was offered to the viewer as
5
+ * `English (Stan WarHammer & Nesitach)`. The detector was not at fault — it was
6
+ * handed the raw `.ass` file, which is half Latin markup, while the markup-free
7
+ * WebVTT it was about to serve sat in the variable beside it. Measured on that
8
+ * file: 5040 Latin characters against 5983 Cyrillic, `franc(the file) = eng`,
9
+ * `franc(the dialogue) = rus`.
10
+ * `research/subtitle-language-ass-markup-2026-09-01.md`.
11
+ *
12
+ * These checks pin the input at each of the three places a language is read.
13
+ *
14
+ * **On the size of the fixtures.** franc's answer among the Cyrillic languages
15
+ * is not stable on a small sample: measured 2026-09-01 by growing one Russian
16
+ * text line by line, it answered `bul` at 129 characters, `srp` at 158, 241 and
17
+ * `bul` again at 292, then `rus` at every length from 337 to 881. So the
18
+ * dialogue here is ~880 Cyrillic characters — past that boundary by a factor of
19
+ * about 2.6, and still an order of magnitude below a real episode's 5983. The
20
+ * fixtures are NOT sized to make these checks pass; they are sized to resemble
21
+ * the thing. That instability is a separate defect and is recorded as one.
22
+ */
23
+
24
+ import test from "node:test";
25
+ import assert from "node:assert/strict";
26
+
27
+ import { cueTextOfVtt, detectLanguage, detectLanguageFromVtt } from "../services/language-detect.js";
28
+ import { convertSubtitleToVtt } from "../services/subtitle-convert.js";
29
+ import { finalizeCues } from "../services/torrent-worker/subtitle-cues.js";
30
+
31
+ /** Varied Russian dialogue, the length a few minutes of an episode carries. */
32
+ const RUSSIAN_DIALOGUE = [
33
+ "Ты видишь их?",
34
+ "Да.",
35
+ "Но не столько вижу, сколько чувствую.",
36
+ "Скорее всего, они будут здесь с минуты на минуту.",
37
+ "Почему господа октябристы решили напасть именно сейчас?",
38
+ "Им никогда не преодолеть эти стены.",
39
+ "Мы держали эту крепость три года и продержим ещё столько же.",
40
+ "Готовьте лучников на восточной стороне.",
41
+ "Если они подойдут ближе, мы откроем огонь без предупреждения.",
42
+ "Я не собираюсь умирать здесь, в этой богом забытой дыре.",
43
+ "Тогда возьми меч и вставай рядом со мной.",
44
+ "Сколько у нас осталось воды и хлеба?",
45
+ "На неделю, если не считать раненых.",
46
+ "Раненых считать придётся, они тоже люди.",
47
+ "Отправь гонца к южным воротам и передай приказ отступать.",
48
+ "Он не успеет, дорога перерезана ещё вчера вечером.",
49
+ "Значит пойду сам, а ты останешься за меня командовать.",
50
+ "Это безумие, и ты прекрасно об этом знаешь.",
51
+ "Безумие — это сидеть и ждать, пока нас перебьют по одному.",
52
+ "Хорошо. Но возьми с собой хотя бы двоих.",
53
+ "Двоих я возьму. Больше не могу себе позволить.",
54
+ "Береги себя. Мы будем держать стену до последнего.",
55
+ "Я знаю. Именно поэтому я и ухожу спокойно.",
56
+ "Смотри, дым над лесом. Они уже жгут деревни.",
57
+ "Тогда времени у нас меньше, чем мы думали."
58
+ ];
59
+
60
+ /** `hh:mm:ss.cc` for the ASS `Start`/`End` fields. */
61
+ function assTime(seconds) {
62
+ const mm = String(Math.floor(seconds / 60)).padStart(2, "0");
63
+ const ss = String(seconds % 60).padStart(2, "0");
64
+ return `0:${mm}:${ss}.00`;
65
+ }
66
+
67
+ /**
68
+ * An ASS file in the shape a fansub release ships: an Aegisub header, a styles
69
+ * section with English font and style names, and Russian dialogue carrying
70
+ * override groups. Modelled on the field file.
71
+ */
72
+ const RUSSIAN_ASS = `[Script Info]
73
+ Title: Default Aegisub file
74
+ ScriptType: v4.00+
75
+ PlayResX: 1280
76
+ PlayResY: 720
77
+ Original Translation: Nesitach
78
+ Original Editing: Stan WarHammer
79
+ WrapStyle: 0
80
+ ScaledBorderAndShadow: no
81
+ Video Aspect Ratio: c1.77778
82
+ YCbCr Matrix: TV.601
83
+ Aegisub Video Aspect Ratio: c1.777778
84
+
85
+ [Aegisub Project Garbage]
86
+ Last Style Storage: Default
87
+ Audio File: [HorribleSubs] Drifters - 03 [720p].mkv
88
+ Video File: [HorribleSubs] Drifters - 03 [720p].mkv
89
+ Video AR Mode: 4
90
+ Video AR Value: 1.777778
91
+ Video Zoom Percent: 0.600000
92
+ Scroll Position: 256
93
+ Active Line: 257
94
+ Video Position: 33159
95
+
96
+ [V4+ Styles]
97
+ Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
98
+ Style: Default,Trebuchet MS,54,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2.5,1.5,2,20,20,25,1
99
+ Style: Signs,Times New Roman,48,&H00FFFF00,&H000000FF,&H00202020,&H00000000,-1,0,0,0,100,100,0,0,1,2,1,8,20,20,20,1
100
+ Style: Italics,Trebuchet MS Italic,54,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,-1,0,0,100,100,0,0,1,2.5,1.5,2,20,20,25,1
101
+
102
+ [Events]
103
+ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
104
+ ${RUSSIAN_DIALOGUE.map((line, index) => {
105
+ const style = index % 7 === 6 ? "Signs" : "Default";
106
+ const tag = index % 5 === 4 ? "{\\pos(640,620)}" : "";
107
+ return `Dialogue: 0,${assTime(index * 4)},${assTime(index * 4 + 3)},${style},,0,0,0,,${tag}${line}`;
108
+ }).join("\n")}
109
+ `;
110
+
111
+ test("a Russian .ass is reported as Russian, and its markup does not reach the detector", () => {
112
+ const vtt = convertSubtitleToVtt(RUSSIAN_ASS, ".ass");
113
+ assert.ok(vtt.startsWith("WEBVTT"), "the conversion produced a WebVTT document");
114
+
115
+ const spoken = cueTextOfVtt(vtt);
116
+ // Every one of these is a piece of the file the viewer never reads, and each
117
+ // was competing with the dialogue for the detector's answer.
118
+ for (const markup of [
119
+ "Aegisub", "Script Info", "V4+ Styles", "Format:", "Dialogue:",
120
+ "Trebuchet MS", "Times New Roman", "Default", "Signs", "pos(",
121
+ "-->", "0:00:12"
122
+ ]) {
123
+ assert.ok(!spoken.includes(markup), `cue text still carries "${markup}"`);
124
+ }
125
+ assert.ok(spoken.includes("Ты видишь их?"), "cue text keeps the dialogue");
126
+
127
+ assert.deepEqual(detectLanguageFromVtt(vtt), { code: "ru", name: "Russian" });
128
+ });
129
+
130
+ test("the fixture is the hard case: the file itself is nearly half Latin", () => {
131
+ // Not an assertion about franc — an assertion that this fixture reproduces the
132
+ // field file's proportions. A fixture whose markup were negligible would pass
133
+ // the check above with or without the fix.
134
+ const cyrillic = (RUSSIAN_ASS.match(/[Ѐ-ӿ]/gu) ?? []).length;
135
+ const latin = (RUSSIAN_ASS.match(/[A-Za-z]/g) ?? []).length;
136
+ assert.ok(cyrillic > 800, `too little dialogue: ${cyrillic} Cyrillic characters`);
137
+ assert.ok(latin > cyrillic * 0.5, `markup too small to reproduce the fault: ${latin} vs ${cyrillic}`);
138
+ });
139
+
140
+ test("cue identifiers, NOTE, STYLE and REGION blocks are not text", () => {
141
+ const vtt = [
142
+ "WEBVTT - This file has cues.",
143
+ "Kind: captions",
144
+ "Language: en",
145
+ "",
146
+ "NOTE",
147
+ "Translated by an English speaking volunteer, all rights reserved.",
148
+ "",
149
+ "STYLE",
150
+ "::cue { background-image: linear-gradient(to bottom, dimgray, lightgray); }",
151
+ "",
152
+ "REGION",
153
+ "id:speaker width:40% lines:3 regionanchor:0%,100%",
154
+ "",
155
+ "opening-line",
156
+ "00:00:12.060 --> 00:00:13.270 align:start position:0%",
157
+ "<v Тоёхиса>Ты видишь их?</v>",
158
+ "",
159
+ "2",
160
+ "00:00:15.400 --> 00:00:16.650",
161
+ "<i>Но не столько вижу,</i>",
162
+ "сколько чувствую &amp; ощущаю.",
163
+ ""
164
+ ].join("\n");
165
+
166
+ const spoken = cueTextOfVtt(vtt);
167
+ assert.equal(
168
+ spoken,
169
+ "Ты видишь их?\nНо не столько вижу,\nсколько чувствую ощущаю."
170
+ );
171
+ });
172
+
173
+ test("a document with no cues yields no language rather than a guess", () => {
174
+ assert.equal(cueTextOfVtt("WEBVTT\n"), "");
175
+ assert.equal(detectLanguageFromVtt("WEBVTT\n"), null);
176
+ assert.equal(detectLanguageFromVtt(null), null);
177
+ });
178
+
179
+ test("an embedded ASS cue is read through finalizeCues, not raw", () => {
180
+ // What the cluster walk holds: the dialogue row without its `Dialogue:`
181
+ // header — nine comma-separated fields, then the text with override groups.
182
+ const cues = RUSSIAN_DIALOGUE.map((line, index) => ({
183
+ startSeconds: index * 4,
184
+ endSeconds: index * 4 + 3,
185
+ text: `0,${assTime(index * 4)},${assTime(index * 4 + 3)},Default,,0,0,0,,` +
186
+ `${index % 5 === 4 ? "{\\pos(640,620)}" : ""}${line}`
187
+ }));
188
+
189
+ const spoken = finalizeCues(cues, "S_TEXT/ASS").map((cue) => cue.text).join("\n");
190
+ assert.ok(!spoken.includes("Default"), "the style field survived into the text");
191
+ assert.ok(!spoken.includes("pos("), "an override group survived into the text");
192
+ assert.ok(!spoken.includes("0:00:12"), "a timestamp field survived into the text");
193
+ assert.deepEqual(detectLanguage(spoken), { code: "ru", name: "Russian" });
194
+ });
195
+
196
+ test("too little text is answered with nothing, not with a guess", () => {
197
+ // Measured 2026-09-02 (`research/franc-boundary-2026-09-02.md`): franc's
198
+ // answer for Russian walks between Bulgarian, Serbian and Russian until about
199
+ // 650 characters. Below that the honest answer is none — the browser then
200
+ // shows "Unknown", and the label moves when enough of the file has arrived.
201
+ const short = RUSSIAN_DIALOGUE.slice(0, 6).join("\n");
202
+ assert.ok(short.length < 300, `the fixture must be short: ${short.length}`);
203
+ assert.equal(detectLanguage(short), null);
204
+
205
+ const long = RUSSIAN_DIALOGUE.join("\n");
206
+ assert.ok(long.length > 650, `the fixture must be long enough: ${long.length}`);
207
+ assert.deepEqual(detectLanguage(long), { code: "ru", name: "Russian" });
208
+ });
209
+
210
+ test("an answer that does not survive losing half the text is not an answer", () => {
211
+ // A file carrying two languages — a bilingual release, or a track that turns
212
+ // into signs-only English partway. franc answers something for the whole; the
213
+ // halves disagree with it, and that disagreement is the text saying the
214
+ // answer rests on where it happened to be cut.
215
+ const english = [
216
+ "Do you see them out there beyond the wall?",
217
+ "I do, though not as clearly as I would like to.",
218
+ "They have been gathering since the morning came.",
219
+ "We should send word to the southern gate at once.",
220
+ "The road was cut yesterday and no rider will pass.",
221
+ "Then we hold what we have and wait for the dawn."
222
+ ].join("\n");
223
+ const mixed = `${RUSSIAN_DIALOGUE.slice(0, 13).join("\n")}\n${english}`;
224
+ assert.equal(detectLanguage(mixed), null);
225
+ });
226
+
227
+ test("a WebVTT body is decoded whole, so no character is cut in half", () => {
228
+ // The ffmpeg extraction path used to detect on `String(body.subarray(0, 4096))`.
229
+ // Two faults: a byte cut lands mid-character on any non-Latin track, and most
230
+ // of those bytes are timestamps rather than words. Cyrillic is two bytes per
231
+ // character in UTF-8, so 4096 bytes of this document is a few hundred
232
+ // characters of dialogue — inside the unstable region measured above.
233
+ const cues = RUSSIAN_DIALOGUE.map((line, index) => {
234
+ const start = `00:00:${String(index * 2).padStart(2, "0")}.000`;
235
+ const end = `00:00:${String(index * 2 + 1).padStart(2, "0")}.000`;
236
+ return `${start} --> ${end}\n${line}`;
237
+ });
238
+ const body = Buffer.from(`WEBVTT\n\n${cues.join("\n\n")}\n`, "utf8");
239
+
240
+ assert.deepEqual(detectLanguageFromVtt(body.toString("utf8")), { code: "ru", name: "Russian" });
241
+ });
@@ -75,9 +75,17 @@ test("chunks arrive with their contents intact", async () => {
75
75
  const { port1, port2 } = new MessageChannel();
76
76
  try {
77
77
  const received = [];
78
+ // Waited on rather than slept through. This test used to sleep 50 ms and
79
+ // then assert, so it failed whenever the run was busy — recorded as flaky in
80
+ // roadmap items 53 and 54, and it failed again on 2026-09-02 for a reason
81
+ // that shows exactly how little a chosen interval is worth: the worker had
82
+ // gained one more module to load, and 50 ms stopped being enough.
83
+ let arrived;
84
+ const firstChunk = new Promise((resolve) => { arrived = resolve; });
78
85
  port2.on("message", (message) => {
79
86
  if (message?.type === "chunk") {
80
87
  received.push(Buffer.from(message.bytes));
88
+ arrived();
81
89
  }
82
90
  });
83
91
 
@@ -86,7 +94,7 @@ test("chunks arrive with their contents intact", async () => {
86
94
  await sender.send(piece);
87
95
  sender.end();
88
96
 
89
- await new Promise((resolve) => setTimeout(resolve, 50));
97
+ await firstChunk;
90
98
  assert.equal(received.length, 1);
91
99
  assert.equal(received[0].length, 256 * 1024);
92
100
  assert.equal(received[0][0], 42);