@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,47 +1,287 @@
1
- /**
2
- * @file Text subtitle track convertible to WebVTT.
3
- *
4
- * Matroska: S_TEXT/UTF8, S_TEXT/ASS, S_TEXT/SSA, S_TEXT/WEBVTT (RFC 9559)
5
- * MP4: tx3g, text, wvtt (stpp/TTML is NOT text for this pipeline — excluded)
6
- * External files: .srt .ass .ssa .vtt modelled as TextSubtitleTrack with no container backing.
7
- */
8
-
9
- import { SubtitleTrack } from "./SubtitleTrack.js";
10
- import { markupKindOf, plainCueText } from "./subtitle-markup.js";
11
-
12
- const TEXT_CODECS_MATROSKA = new Set(["S_TEXT/UTF8", "S_TEXT/ASS", "S_TEXT/SSA", "S_TEXT/WEBVTT"]);
13
- const TEXT_FORMATS_MP4 = new Set(["tx3g", "text", "wvtt"]);
14
-
15
- export class TextSubtitleTrack extends SubtitleTrack {
16
- constructor(params) {
17
- super(params);
18
- this.textCodec = params.codecId ?? "";
19
- }
20
-
21
- isTextBased() {
22
- return true;
23
- }
24
-
25
- /** Which markup this track's cue text carries — see `subtitle-markup.js`. */
26
- get markupKind() {
27
- return markupKindOf(this.textCodec);
28
- }
29
-
30
- /**
31
- * The visible text of one of this track's cues.
32
- *
33
- * @param {string} textField - The cue's text field, already out of its
34
- * container's framing. This method knows the codec and not the container,
35
- * which is why it cannot be handed a whole dialogue row.
36
- * @returns {string}
37
- */
38
- plainText(textField) {
39
- return plainCueText(textField, this.textCodec);
40
- }
41
-
42
- static isTextCodec(codecId) {
43
- return TEXT_CODECS_MATROSKA.has(codecId) || TEXT_FORMATS_MP4.has(codecId);
44
- }
45
- }
46
-
47
- export { TEXT_CODECS_MATROSKA, TEXT_FORMATS_MP4 };
1
+ /**
2
+ * @file A subtitle track whose cues are text, and everything that follows from
3
+ * that being true.
4
+ *
5
+ * Matroska: `S_TEXT/UTF8`, `S_TEXT/ASS`, `S_TEXT/SSA`, `S_TEXT/WEBVTT`
6
+ * (RFC 9559). MP4: `tx3g`, `text`, `wvtt` (`stpp`/TTML is XML and is not text
7
+ * for this pipeline). A file beside the film is one of these too, with no
8
+ * container behind it.
9
+ *
10
+ * Two axes meet on a subtitle cue and only ONE of them is here. How a cue's
11
+ * bytes are FRAMED is stated by the container's specification and is answered
12
+ * by `container/`: Matroska reorders an ASS dialogue row and drops its two
13
+ * timing fields (`matroska.org/technical/subtitles.html`), a `.ass` file states
14
+ * its own field order in the `Format:` line of `[Events]`, an MP4 carries each
15
+ * cue as a sample with a length prefix. What the CODEC then puts inside that
16
+ * text — override groups in braces, `\N` and `\n` for a break, `\h` for a hard
17
+ * space — is a fact about ASS wherever it is stored, and that is this file,
18
+ * along with writing the cues out as WebVTT.
19
+ *
20
+ * The two were one function until 2.72.1, which is what showed English
21
+ * subtitles as `21,0,Default,,0000,0000,0000,,I am the powerful Demon King`:
22
+ * it counted commas to guess which framing it held, expected the ten fields of
23
+ * a row in a FILE, and a Matroska block carries nine. A function that has to
24
+ * guess the shape of its input is being called by someone who knew and did not
25
+ * say.
26
+ */
27
+
28
+ import { SubtitleTrack } from "./SubtitleTrack.js";
29
+ import { detectLanguage } from "../language-detect.js";
30
+
31
+ const TEXT_CODECS_MATROSKA = new Set(["S_TEXT/UTF8", "S_TEXT/ASS", "S_TEXT/SSA", "S_TEXT/WEBVTT"]);
32
+ const TEXT_FORMATS_MP4 = new Set(["tx3g", "text", "wvtt"]);
33
+
34
+ /** How a cue's text is marked up, once the container's framing is off. */
35
+ export const MarkupKind = {
36
+ /** Sub Station Alpha and its advanced form: `{\pos(…)}`, `\N`, `\h`. */
37
+ ASS: "ass",
38
+ /** Nothing to strip: the text is what is shown. */
39
+ NONE: "none"
40
+ };
41
+
42
+ /**
43
+ * Which markup a codec's cue text carries, by any of the codec's names.
44
+ *
45
+ * The keys are every name this proxy has for a text subtitle codec: Matroska
46
+ * CodecIDs (RFC 9559 §5.1.4.1.28 and the codec mappings beside it), MP4 sample
47
+ * entry types (ISO/IEC 14496-12 §12.6, plus Apple's `tx3g`), and the file
48
+ * extensions a subtitle shipped beside the film uses. They are listed together
49
+ * because the ANSWER is the same for all of them — ASS is ASS whether it sits
50
+ * in a Matroska block, in a file, or nowhere yet — and keeping three tables
51
+ * would mean three places to forget.
52
+ *
53
+ * @type {Map<string, string>}
54
+ */
55
+ const MARKUP_BY_CODEC = new Map([
56
+ ["S_TEXT/ASS", MarkupKind.ASS],
57
+ ["S_TEXT/SSA", MarkupKind.ASS],
58
+ [".ass", MarkupKind.ASS],
59
+ [".ssa", MarkupKind.ASS],
60
+ ["S_TEXT/UTF8", MarkupKind.NONE],
61
+ ["S_TEXT/WEBVTT", MarkupKind.NONE],
62
+ [".srt", MarkupKind.NONE],
63
+ [".vtt", MarkupKind.NONE],
64
+ [".webvtt", MarkupKind.NONE],
65
+ ["tx3g", MarkupKind.NONE],
66
+ ["text", MarkupKind.NONE],
67
+ ["wvtt", MarkupKind.NONE]
68
+ ]);
69
+
70
+ /** How long a cue with no stated end is shown, when no cue follows it. */
71
+ const OPEN_ENDED_CUE_SECONDS = 4;
72
+
73
+ export class TextSubtitleTrack extends SubtitleTrack {
74
+ constructor(params) {
75
+ super(params);
76
+ this.textCodec = params.codecId ?? "";
77
+ }
78
+
79
+ isTextBased() {
80
+ return true;
81
+ }
82
+
83
+ /**
84
+ * Which markup a codec's cue text carries.
85
+ *
86
+ * An unknown codec is answered `NONE` rather than refused: the text is then
87
+ * shown as it is, which is wrong only in so far as some markup stays visible,
88
+ * where a refusal would show nothing at all.
89
+ *
90
+ * @param {string} codecId - Matroska CodecID, MP4 sample entry type, or a
91
+ * file extension including the dot. Case is ignored for extensions, which
92
+ * arrive from file names, and kept for the others, which a spec spells.
93
+ * @returns {string} One of {@link MarkupKind}.
94
+ */
95
+ static markupKindOf(codecId) {
96
+ const name = String(codecId ?? "");
97
+ return MARKUP_BY_CODEC.get(name) ?? MARKUP_BY_CODEC.get(name.toLowerCase()) ?? MarkupKind.NONE;
98
+ }
99
+
100
+ /**
101
+ * The visible text of one cue: its markup taken off, nothing else touched.
102
+ *
103
+ * @param {string} text - The cue's text FIELD, already out of the container's
104
+ * framing. Handing a whole dialogue row to this is the mistake described at
105
+ * the top of this file.
106
+ * @param {string} codecId
107
+ * @returns {string} Possibly empty — a cue whose text is only a drawing
108
+ * command or a positioning group has nothing to show, and the caller drops
109
+ * it.
110
+ */
111
+ static plainTextOf(text, codecId) {
112
+ const raw = String(text ?? "");
113
+ if (TextSubtitleTrack.markupKindOf(codecId) !== MarkupKind.ASS) {
114
+ return raw.trim();
115
+ }
116
+ return raw
117
+ // An override group. Any brace content is a directive, never dialogue:
118
+ // drawing commands, karaoke timing, positioning, font changes.
119
+ .replace(/\{[^}]*\}/g, "")
120
+ // Both breaks reach a player as a break. ASS distinguishes them — `\N` is
121
+ // always a break, `\n` only where the style does not wrap — and a WebVTT
122
+ // cue has no way to express the difference, so it takes the break.
123
+ .replace(/\\N/g, "\n")
124
+ .replace(/\\n/g, "\n")
125
+ // A space the renderer may not collapse.
126
+ .replace(/\\h/g, " ")
127
+ .trim();
128
+ }
129
+
130
+ /**
131
+ * One cue's start or end as WebVTT writes it: `hh:mm:ss.mmm`.
132
+ *
133
+ * @param {number} seconds
134
+ * @returns {string}
135
+ */
136
+ static vttTime(seconds) {
137
+ const safe = Math.max(0, Number(seconds) || 0);
138
+ const hours = Math.floor(safe / 3600);
139
+ const minutes = Math.floor((safe % 3600) / 60);
140
+ const rest = safe % 60;
141
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${rest.toFixed(3).padStart(6, "0")}`;
142
+ }
143
+
144
+ /**
145
+ * Resolve what a cue is missing and take its codec's markup off, so what is
146
+ * left is what a player shows.
147
+ *
148
+ * A cue with no duration — a Matroska SimpleBlock, which subtitles rarely use
149
+ * — is given the time until the next one IN THIS LIST, and the last such cue
150
+ * a few seconds. Not an invention about the film: it is what a player does
151
+ * with an open-ended cue, made explicit so every consumer agrees on it.
152
+ *
153
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
154
+ * @param {string} codecId
155
+ * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
156
+ */
157
+ static finalizeCues(cues, codecId) {
158
+ const result = [];
159
+ (Array.isArray(cues) ? cues : []).forEach((cue, index) => {
160
+ const next = cues[index + 1];
161
+ const endSeconds =
162
+ cue.endSeconds ?? (next ? next.startSeconds : cue.startSeconds + OPEN_ENDED_CUE_SECONDS);
163
+ const text = TextSubtitleTrack.plainTextOf(cue.text, codecId);
164
+ if (!text) {
165
+ return;
166
+ }
167
+ result.push({ startSeconds: cue.startSeconds, endSeconds, text });
168
+ });
169
+ return result;
170
+ }
171
+
172
+ /**
173
+ * A WebVTT document from a list of cues — the one writer, used by every path
174
+ * that produces subtitles: a file beside the film, a track inside it, a pull
175
+ * and a push.
176
+ *
177
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
178
+ * @param {string} codecId
179
+ * @returns {string}
180
+ */
181
+ static cuesToVtt(cues, codecId) {
182
+ const lines = ["WEBVTT", ""];
183
+ for (const cue of TextSubtitleTrack.finalizeCues(cues, codecId)) {
184
+ lines.push(`${TextSubtitleTrack.vttTime(cue.startSeconds)} --> ${TextSubtitleTrack.vttTime(cue.endSeconds)}`);
185
+ lines.push(cue.text);
186
+ lines.push("");
187
+ }
188
+ return lines.join("\n");
189
+ }
190
+
191
+ /**
192
+ * The words of a WebVTT document — what a viewer reads, with everything the
193
+ * format puts around them removed.
194
+ *
195
+ * A WebVTT document is a series of blocks separated by blank lines. A block
196
+ * that holds a timing line (`00:00:12.060 --> 00:00:13.270`) is a cue, and the
197
+ * lines after that timing line are its text; the lines before it are the cue's
198
+ * optional identifier. A block with NO timing line is the `WEBVTT` header or a
199
+ * `NOTE` / `STYLE` / `REGION` block, and none of those is anybody's language.
200
+ * That one rule removes the identifiers, the timings and the headers together.
201
+ *
202
+ * What is left can still carry WebVTT's own inline markup — `<v Speaker>`,
203
+ * `<i>`, `<c.yellow>` — and character references. Both are dropped: a speaker
204
+ * name and a class name are written in whatever language the releaser's tooling
205
+ * used, which is not the language of the film.
206
+ *
207
+ * @param {string} vtt - A WebVTT document.
208
+ * @returns {string} The cue text, blocks joined by newlines.
209
+ */
210
+ static cueTextOfVtt(vtt) {
211
+ if (typeof vtt !== "string") {
212
+ return "";
213
+ }
214
+ const blocks = vtt.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
215
+ const spoken = [];
216
+ for (const block of blocks) {
217
+ const lines = block.split("\n");
218
+ const timingAt = lines.findIndex((line) => line.includes("-->"));
219
+ if (timingAt < 0) {
220
+ continue;
221
+ }
222
+ for (const line of lines.slice(timingAt + 1)) {
223
+ spoken.push(line);
224
+ }
225
+ }
226
+ return spoken
227
+ .join("\n")
228
+ .replace(/<[^>]*>/g, "")
229
+ // A character reference stands for one character and never for a word, so a
230
+ // space in its place keeps the neighbouring words apart and adds nothing.
231
+ .replace(/&[a-z]+;|&#\d+;|&#x[0-9a-f]+;/gi, " ")
232
+ .trim();
233
+ }
234
+
235
+ /**
236
+ * Detect the language of a WebVTT document, reading only its cue text.
237
+ *
238
+ * @param {string} vtt - A WebVTT document.
239
+ * @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
240
+ */
241
+ static detectLanguageFromVtt(vtt) {
242
+ return detectLanguage(TextSubtitleTrack.cueTextOfVtt(vtt));
243
+ }
244
+
245
+ static isTextCodec(codecId) {
246
+ return TEXT_CODECS_MATROSKA.has(codecId) || TEXT_FORMATS_MP4.has(codecId);
247
+ }
248
+
249
+ /** Which markup this track's cue text carries. */
250
+ get markupKind() {
251
+ return TextSubtitleTrack.markupKindOf(this.textCodec);
252
+ }
253
+
254
+ /**
255
+ * The visible text of one of this track's cues.
256
+ *
257
+ * @param {string} textField - The cue's text field, already out of its
258
+ * container's framing. This method knows the codec and not the container,
259
+ * which is why it cannot be handed a whole dialogue row.
260
+ * @returns {string}
261
+ */
262
+ plainText(textField) {
263
+ return TextSubtitleTrack.plainTextOf(textField, this.textCodec);
264
+ }
265
+
266
+ /**
267
+ * This track's cues, resolved and stripped, as a player reads them.
268
+ *
269
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
270
+ * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
271
+ */
272
+ finalize(cues) {
273
+ return TextSubtitleTrack.finalizeCues(cues, this.textCodec);
274
+ }
275
+
276
+ /**
277
+ * This track's cues as a WebVTT document.
278
+ *
279
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
280
+ * @returns {string}
281
+ */
282
+ toVtt(cues) {
283
+ return TextSubtitleTrack.cuesToVtt(cues, this.textCodec);
284
+ }
285
+ }
286
+
287
+ export { TEXT_CODECS_MATROSKA, TEXT_FORMATS_MP4 };
@@ -1,14 +1,14 @@
1
- export { ContainerTrack } from "./ContainerTrack.js";
2
- export { VideoTrack } from "./VideoTrack.js";
3
- export { AudioTrack } from "./AudioTrack.js";
4
- export { SubtitleTrack } from "./SubtitleTrack.js";
5
- export { TextSubtitleTrack, TEXT_CODECS_MATROSKA, TEXT_FORMATS_MP4 } from "./TextSubtitleTrack.js";
6
- export { ImageSubtitleTrack } from "./ImageSubtitleTrack.js";
7
- export { MarkupKind, markupKindOf, plainCueText } from "./subtitle-markup.js";
8
- // There is deliberately no class for a track that lives in a file of its own.
9
- // `<name>.mka` is a Matroska container holding an `AudioTrack`, and
10
- // `MatroskaContainer` reads it exactly as it reads the picture's — so "external"
11
- // is not a KIND of track, only the answer to where a track's bytes are. That
12
- // answer belongs to the application layer, which knows about torrents; this one
13
- // describes what a container declares and must not. `ExternalSubtitleFile`,
14
- // which asserted the opposite, was never used by anything and is gone.
1
+ export { ContainerTrack } from "./ContainerTrack.js";
2
+ export { VideoTrack } from "./VideoTrack.js";
3
+ export { AudioTrack } from "./AudioTrack.js";
4
+ export { SubtitleTrack } from "./SubtitleTrack.js";
5
+ export { TextSubtitleTrack, TEXT_CODECS_MATROSKA, TEXT_FORMATS_MP4 } from "./TextSubtitleTrack.js";
6
+ export { ImageSubtitleTrack } from "./ImageSubtitleTrack.js";
7
+ export { MarkupKind } from "./TextSubtitleTrack.js";
8
+ // There is deliberately no class for a track that lives in a file of its own.
9
+ // `<name>.mka` is a Matroska container holding an `AudioTrack`, and
10
+ // `MatroskaContainer` reads it exactly as it reads the picture's — so "external"
11
+ // is not a KIND of track, only the answer to where a track's bytes are. That
12
+ // answer belongs to the application layer, which knows about torrents; this one
13
+ // describes what a container declares and must not. `ExternalSubtitleFile`,
14
+ // which asserted the opposite, was never used by anything and is gone.
@@ -211,3 +211,70 @@ test("a browser that does not report its bytes is judged as before", () => {
211
211
  assert.equal(reading.verdict, "association-stopped");
212
212
  assert.doesNotMatch(reading.detail, /peerBytes=/);
213
213
  });
214
+
215
+ test("a frozen tab's own event-loop delay counts toward the allowance", () => {
216
+ // Field case 2026-09-03, session 03f211b8. The viewer paused at 15:24:21 with
217
+ // 121.5 s buffered; the tab went hidden at 15:24:35 and its event loop fell
218
+ // behind — loopLag 681 → 1881 → 4297 → 5957 ms. At 15:26:05 the probes read
219
+ // `gap 12 of 11` and printed `association-stopped`, the ring files were kept
220
+ // and a 180 s capture was taken; seven seconds later the same connection read
221
+ // `flowing`. Nothing had stopped: the browser simply could not run the timer
222
+ // that answers a probe.
223
+ // The line printed `gap 12 of 11`; the queue was empty and the round trip
224
+ // 162 ms, so the cadence term is whatever makes the allowance 11.
225
+ const measured = {
226
+ queuedBytes: 0,
227
+ bytesPerSecond: 300,
228
+ rttMs: 162,
229
+ echoIntervalMs: 5000
230
+ };
231
+ const withoutLag = allowedGap(measured);
232
+ const withLag = allowedGap({ ...measured, peerLoopLagMs: 1881 });
233
+ assert.equal(withoutLag, 11, `the field allowance was 11, not ${withoutLag}`);
234
+ assert.ok(withLag > 12, `a gap of 12 must fit inside ${withLag}`);
235
+ const allowed = Object.fromEntries(ALL.map((label) => [label, withLag]));
236
+ const { verdict, detail } = readProbeState(
237
+ state(
238
+ { proxy: 9547, "proxy-control": 9547, "proxy-fast": 9547 },
239
+ {
240
+ seq: 9559,
241
+ allowed,
242
+ echoAgeMs: 5963,
243
+ echoStaleMs: 11 * PROBE_INTERVAL_MS + 162 + 5000 + 1881,
244
+ peerBytesAdvancing: false,
245
+ peerLoopLagMs: 1881,
246
+ peerVisibility: "hidden"
247
+ }
248
+ )
249
+ );
250
+ assert.equal(verdict, "flowing");
251
+ assert.match(detail, /peerLoopLag=1881ms/);
252
+ assert.match(detail, /peerTab=hidden/);
253
+ });
254
+
255
+ test("the peer's lag widens the bound on a stale echo without removing it", () => {
256
+ // The same term must not make `reverse-direction-gone` unreachable: a peer
257
+ // that has genuinely gone silent is still silent for far longer than its own
258
+ // loop delay explains.
259
+ const { verdict } = readProbeState(
260
+ state(
261
+ { proxy: 99, "proxy-control": 99, "proxy-fast": 99 },
262
+ {
263
+ echoAgeMs: 120_000,
264
+ echoStaleMs: 5500 + 162 + 1000 + 4297,
265
+ peerLoopLagMs: 4297,
266
+ peerVisibility: "hidden"
267
+ }
268
+ )
269
+ );
270
+ assert.equal(verdict, "reverse-direction-gone");
271
+ });
272
+
273
+ test("a peer that reports no loop delay is judged exactly as before", () => {
274
+ const reading = readProbeState(
275
+ state({ proxy: 90, "proxy-control": 90, "proxy-fast": 90 }, { peerBytesAdvancing: false })
276
+ );
277
+ assert.equal(reading.verdict, "association-stopped");
278
+ assert.doesNotMatch(reading.detail, /peerLoopLag=/);
279
+ assert.doesNotMatch(reading.detail, /peerTab=/);
280
+ });
Binary file