@torrent-tv/proxy 2.73.1 → 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 (33) hide show
  1. package/CHANGELOG.md +1447 -1437
  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/playback-planner.js +747 -747
  15. package/services/produced-index.js +300 -0
  16. package/services/torrent-worker/subtitle-cues.js +582 -633
  17. package/services/tracks/TextSubtitleTrack.js +287 -47
  18. package/services/tracks/index.js +14 -14
  19. package/test/delivery-probe.test.js +67 -0
  20. package/test/matroska-blocks.test.js +0 -0
  21. package/test/mp4-subtitles.test.js +173 -127
  22. package/test/produced-index.test.js +188 -0
  23. package/test/subtitle-cue-framing.test.js +200 -202
  24. package/test/subtitle-cue-walk.test.js +369 -0
  25. package/test/subtitle-defaults.test.js +97 -97
  26. package/test/subtitle-language.test.js +252 -252
  27. package/test/subtitle-track-numbering.test.js +370 -370
  28. package/services/container-index/matroska-blocks.js +0 -202
  29. package/services/container-index/matroska-subtitles.js +0 -372
  30. package/services/container-index/mp4-subtitles.js +0 -404
  31. package/services/subtitle-convert.js +0 -144
  32. package/services/subtitle-defaults.js +0 -157
  33. package/services/tracks/subtitle-markup.js +0 -104
@@ -1,135 +1,354 @@
1
- /**
2
- * @file Base Container — abstract per RFC 9559 / ISO 14496-12.
3
- *
4
- * A Container knows how to read its own format's track table and index.
5
- * Concrete containers (MatroskaContainer, Mp4Container, AviContainer) implement
6
- * spec-specific parsing. All byte access goes through `readRange(start,end)` so
7
- * the class works over torrent piece windows.
8
- *
9
- * Spec refs:
10
- * - Matroska RFC 9559 §5: EBML, Segment, SeekHead, Tracks, Cues, Clusters
11
- * - MP4 ISO/IEC 14496-12 §8: ftyp, moov, trak, tkhd, mdhd, hdlr, elng, stbl
12
- * - AVI RIFF §: LIST hdrl, idx1
13
- */
14
-
15
- /**
16
- * What one file declares about itself. Every field is either a value the
17
- * container states or `null`, which means the container does not state it —
18
- * a defined absence, not "nobody has looked yet".
19
- *
20
- * @typedef {object} ContainerMediaInfo
21
- * @property {string} format - "matroska" | "mp4" | "avi" | "unknown".
22
- * @property {number | null} durationSeconds
23
- * @property {number | null} startTimeSeconds - Where this file's own timeline
24
- * begins. Two files of one release need not agree on it, and the difference
25
- * is what keeps a soundtrack shipped separately aligned with its picture.
26
- */
27
-
28
- export class Container {
29
- /**
30
- * @param {object} params
31
- * @param {(start:number,end:number)=>Promise<Buffer|null>} params.readRange
32
- * @param {number} params.fileSize
33
- * @param {string} [params.label]
34
- */
35
- constructor({ readRange, fileSize, label = "" }) {
36
- this.readRange = readRange;
37
- this.fileSize = fileSize;
38
- this.label = label;
39
- }
40
-
41
- /** @returns {string} Human name: "matroska" | "mp4" | "avi" | "unknown" */
42
- get formatName() {
43
- return "unknown";
44
- }
45
-
46
- /** Whether `head` (first bytes) looks like this container. */
47
- static detect(_head) {
48
- return false;
49
- }
50
-
51
- /**
52
- * All tracks declared by the container, in container order.
53
- * Includes disabled tracks (isEnabled=false) to preserve declaredIndex alignment with ffmpeg.
54
- * @returns {Promise<import("../tracks/index.js").ContainerTrack[]>}
55
- */
56
- async readTracks() {
57
- throw new Error("readTracks not implemented");
58
- }
59
-
60
- /**
61
- * Keyframe times for the video track, ascending seconds. Null when index absent (MPEG-TS, fragmented MP4, truncated).
62
- * @returns {Promise<{times:number[],tolerance:number}|null>}
63
- */
64
- async readKeyframeIndex() {
65
- return null;
66
- }
67
-
68
- /**
69
- * What this file DECLARES about itself as a whole, as distinct from what its
70
- * individual tracks declare.
71
- *
72
- * The rule this method exists to hold: a fact the container declares is read
73
- * from the container; a fact only the media itself has is measured from the
74
- * media. Both halves used to be asked of ffmpeg, so the same header was read
75
- * twice — measured 2026-09-03, this layer read one `.mka` header in 8 ms while
76
- * a second ffmpeg read the same header over HTTP for 8121 ms, in the same
77
- * second, on the same file.
78
- *
79
- * `null` is not "unknown, ask someone else". It means the container does not
80
- * declare the field, which is a final answer about the container and the point
81
- * at which a caller may go to the media — see `docs/container-architecture.md`.
82
- *
83
- * @returns {Promise<import("./Container.js").ContainerMediaInfo>}
84
- */
85
- async readMediaInfo() {
86
- if (!this.mediaInfo) {
87
- this.mediaInfo = {
88
- format: this.formatName,
89
- durationSeconds: null,
90
- startTimeSeconds: null
91
- };
92
- }
93
- return this.mediaInfo;
94
- }
95
-
96
- /**
97
- * Subtitle-specific: where cues live (Matroska cluster positions or MP4 sample ranges).
98
- * Returned via track objects' clusterPositions/samples, so base has no extra method — tracks carry it.
99
- */
100
-
101
- /**
102
- * The TEXT FIELD of one subtitle cue, taken out of this container's framing.
103
- *
104
- * How a cue's bytes are wrapped is stated by the container's own
105
- * specification, so each subclass answers for itself: Matroska reorders an ASS
106
- * dialogue row, drops its two timing fields and prepends a read order
107
- * (`matroska.org/technical/subtitles.html`); an MP4 prefixes a `tx3g` sample
108
- * with its length (ISO/IEC 14496-12 §12.6); a subtitle FILE states its own
109
- * field order in `[Events]`. None of that is a fact about the subtitle format,
110
- * and the format's own markup — `{\pos()}`, `\N` is not a fact about the
111
- * container. The second half is `tracks/subtitle-markup.js`; this is the
112
- * first, and the two are applied in that order.
113
- *
114
- * Static because de-framing reads no instance state: a caller that has bytes
115
- * and knows the format needs no container built over the whole file. The
116
- * instance form below exists so a caller that DOES hold a container gets the
117
- * right answer without naming the subclass.
118
- *
119
- * @param {Buffer} _payload - The cue's bytes as the container stores them.
120
- * @param {string} _codecId - CodecID / sample entry type / file extension.
121
- * @returns {string} The text field, markup still in place.
122
- */
123
- static cueTextOf(_payload, _codecId) {
124
- throw new Error("cueTextOf not implemented");
125
- }
126
-
127
- /**
128
- * @param {Buffer} payload
129
- * @param {string} codecId
130
- * @returns {string}
131
- */
132
- cueTextOf(payload, codecId) {
133
- return /** @type {typeof Container} */ (this.constructor).cueTextOf(payload, codecId);
134
- }
135
- }
1
+ /**
2
+ * @file Base Container — abstract per RFC 9559 / ISO 14496-12.
3
+ *
4
+ * A Container knows how to read its own format's track table and index.
5
+ * Concrete containers (MatroskaContainer, Mp4Container, AviContainer) implement
6
+ * spec-specific parsing. All byte access goes through `readRange(start,end)` so
7
+ * the class works over torrent piece windows.
8
+ *
9
+ * Spec refs:
10
+ * - Matroska RFC 9559 §5: EBML, Segment, SeekHead, Tracks, Cues, Clusters
11
+ * - MP4 ISO/IEC 14496-12 §8: ftyp, moov, trak, tkhd, mdhd, hdlr, elng, stbl
12
+ * - AVI RIFF §: LIST hdrl, idx1
13
+ */
14
+
15
+ /**
16
+ * What one file declares about itself. Every field is either a value the
17
+ * container states or `null`, which means the container does not state it —
18
+ * a defined absence, not "nobody has looked yet".
19
+ *
20
+ * @typedef {object} ContainerMediaInfo
21
+ * @property {string} format - "matroska" | "mp4" | "avi" | "unknown".
22
+ * @property {number | null} durationSeconds
23
+ * @property {number | null} startTimeSeconds - Where this file's own timeline
24
+ * begins. Two files of one release need not agree on it, and the difference
25
+ * is what keeps a soundtrack shipped separately aligned with its picture.
26
+ */
27
+
28
+ export class Container {
29
+ /**
30
+ * Two ways of reading, because two readers of one file want different things
31
+ * and the file is opened once.
32
+ *
33
+ * `readRange` fetches what is missing: the head and the track table are
34
+ * kilobytes, they are needed before anything can be offered, and the codec
35
+ * probe has already pulled the head of every file that plays. `readHeld`
36
+ * reads only what is already downloaded and asks the swarm for nothing, which
37
+ * is what the cue walk needs — turning subtitles on must not pull bytes the
38
+ * viewer is not waiting for. `isHeld` says whether a range can be read that
39
+ * way at all, so the walk can leave a cluster for next time instead of
40
+ * blocking on it.
41
+ *
42
+ * They are given per container rather than per call because a container is
43
+ * cached per file and both readers want the same parsed head. Where the
44
+ * caller supplies only `readRange`, the held reader is that one and every
45
+ * range counts as held — which is the right answer for a local file, and for
46
+ * a torrent it is the caller's job to say otherwise.
47
+ *
48
+ * The torrent is NOT passed in and must not be: `readHeld` and `isHeld` are
49
+ * the only two facts about it this layer needs, and reducing it to two
50
+ * functions is what keeps the container ignorant of where its bytes live.
51
+ *
52
+ * @param {object} params
53
+ * @param {(start:number,end:number)=>Promise<Buffer|null>} params.readRange
54
+ * @param {number} params.fileSize
55
+ * @param {string} [params.label]
56
+ * @param {(start:number,end:number)=>Promise<Buffer|null>} [params.readHeld]
57
+ * @param {(start:number,end:number)=>boolean} [params.isHeld]
58
+ */
59
+ constructor({ readRange, fileSize, label = "", readHeld, isHeld }) {
60
+ this.readRange = readRange;
61
+ this.fileSize = fileSize;
62
+ this.label = label;
63
+ this.readHeld = typeof readHeld === "function" ? readHeld : readRange;
64
+ this.isHeld = typeof isHeld === "function" ? isHeld : () => true;
65
+ }
66
+
67
+
68
+ /**
69
+ * Whether one of ffmpeg's banner streams and one of this container's tracks
70
+ * can be the same track.
71
+ *
72
+ * @param {{ language?: string, title?: string }} banner
73
+ * @param {{ language?: string, name?: string }} container
74
+ * @returns {boolean}
75
+ */
76
+ static pairingHolds(banner, container) {
77
+ return pairingHolds(banner, container);
78
+ }
79
+
80
+ /**
81
+ * ffmpeg's description of a file's subtitle streams, corrected by what the
82
+ * container itself declares.
83
+ *
84
+ * The banner cannot express the difference between "no track is marked" and
85
+ * "every track is marked", because Matroska's `FlagDefault` defaults to 1 and
86
+ * ffmpeg has already applied that default by the time it prints. The
87
+ * container can be asked, and this is where the two readings are lined up —
88
+ * by position, checked pair by pair rather than assumed.
89
+ *
90
+ * @param {object[]} bannerTracks
91
+ * @param {object[]} declared - This container's own subtitle tracks, in its order.
92
+ * @returns {object[]}
93
+ */
94
+ static mergeSubtitleFlags(bannerTracks, declared) {
95
+ return mergeContainerSubtitleFlags(bannerTracks, declared);
96
+ }
97
+
98
+ /** @returns {string} Human name: "matroska" | "mp4" | "avi" | "unknown" */
99
+ get formatName() {
100
+ return "unknown";
101
+ }
102
+
103
+ /** Whether `head` (first bytes) looks like this container. */
104
+ static detect(_head) {
105
+ return false;
106
+ }
107
+
108
+ /**
109
+ * All tracks declared by the container, in container order.
110
+ * Includes disabled tracks (isEnabled=false) to preserve declaredIndex alignment with ffmpeg.
111
+ * @returns {Promise<import("../tracks/index.js").ContainerTrack[]>}
112
+ */
113
+ async readTracks() {
114
+ throw new Error("readTracks not implemented");
115
+ }
116
+
117
+ /**
118
+ * Keyframe times for the video track, ascending seconds. Null when index absent (MPEG-TS, fragmented MP4, truncated).
119
+ * @returns {Promise<{times:number[],tolerance:number}|null>}
120
+ */
121
+ async readKeyframeIndex() {
122
+ return null;
123
+ }
124
+
125
+ /**
126
+ * What this file DECLARES about itself as a whole, as distinct from what its
127
+ * individual tracks declare.
128
+ *
129
+ * The rule this method exists to hold: a fact the container declares is read
130
+ * from the container; a fact only the media itself has is measured from the
131
+ * media. Both halves used to be asked of ffmpeg, so the same header was read
132
+ * twice — measured 2026-09-03, this layer read one `.mka` header in 8 ms while
133
+ * a second ffmpeg read the same header over HTTP for 8121 ms, in the same
134
+ * second, on the same file.
135
+ *
136
+ * `null` is not "unknown, ask someone else". It means the container does not
137
+ * declare the field, which is a final answer about the container and the point
138
+ * at which a caller may go to the media — see `docs/container-architecture.md`.
139
+ *
140
+ * @returns {Promise<import("./Container.js").ContainerMediaInfo>}
141
+ */
142
+ async readMediaInfo() {
143
+ if (!this.mediaInfo) {
144
+ this.mediaInfo = {
145
+ format: this.formatName,
146
+ durationSeconds: null,
147
+ startTimeSeconds: null
148
+ };
149
+ }
150
+ return this.mediaInfo;
151
+ }
152
+
153
+ /**
154
+ * Subtitle-specific: where cues live (Matroska cluster positions or MP4 sample ranges).
155
+ * Returned via track objects' clusterPositions/samples, so base has no extra method — tracks carry it.
156
+ */
157
+
158
+ /**
159
+ * The TEXT FIELD of one subtitle cue, taken out of this container's framing.
160
+ *
161
+ * How a cue's bytes are wrapped is stated by the container's own
162
+ * specification, so each subclass answers for itself: Matroska reorders an ASS
163
+ * dialogue row, drops its two timing fields and prepends a read order
164
+ * (`matroska.org/technical/subtitles.html`); an MP4 prefixes a `tx3g` sample
165
+ * with its length (ISO/IEC 14496-12 §12.6); a subtitle FILE states its own
166
+ * field order in `[Events]`. None of that is a fact about the subtitle format,
167
+ * and the format's own markup — `{\pos(…)}`, `\N` — is not a fact about the
168
+ * container. The second half is `TextSubtitleTrack`; this is the
169
+ * first, and the two are applied in that order.
170
+ *
171
+ * Static because de-framing reads no instance state: a caller that has bytes
172
+ * and knows the format needs no container built over the whole file. The
173
+ * instance form below exists so a caller that DOES hold a container gets the
174
+ * right answer without naming the subclass.
175
+ *
176
+ * @param {Buffer} _payload - The cue's bytes as the container stores them.
177
+ * @param {string} _codecId - CodecID / sample entry type / file extension.
178
+ * @returns {string} The text field, markup still in place.
179
+ */
180
+ static cueTextOf(_payload, _codecId) {
181
+ throw new Error("cueTextOf not implemented");
182
+ }
183
+
184
+ /**
185
+ * @param {Buffer} payload
186
+ * @param {string} codecId
187
+ * @returns {string}
188
+ */
189
+ cueTextOf(payload, codecId) {
190
+ return /** @type {typeof Container} */ (this.constructor).cueTextOf(payload, codecId);
191
+ }
192
+ }
193
+
194
+ // ---------------------------------------------------------------------------
195
+ // Lining ffmpeg's banner up with what a container declares. Here because the
196
+ // correction is about what a CONTAINER states and the banner cannot.
197
+ // ---------------------------------------------------------------------------
198
+ /**
199
+ * Which subtitle track the FILE says to show, read from the file rather than
200
+ * from ffmpeg's description of it.
201
+ *
202
+ * Why this exists. The browser decides which subtitle track to turn on from
203
+ * `isDefault`, and until now that came from ffmpeg's `-i` banner, which prints
204
+ * `(default)`. In Matroska `FlagDefault` DEFAULTS TO 1 and ffmpeg has already
205
+ * applied that default by the time it prints — so a file whose muxer wrote the
206
+ * flag on no track arrives looking exactly like one that wrote it on every
207
+ * track: everything marked. The banner cannot tell the two apart, and the
208
+ * difference is the whole question, because one of them means "show this one"
209
+ * and the other means "the file has no opinion".
210
+ *
211
+ * The container itself can be asked, and the EBML reader already walks the
212
+ * Tracks element for subtitle extraction. What it now also records is whether
213
+ * the element was WRITTEN, which is the fact the banner destroys.
214
+ *
215
+ * The awkward part is lining the two readings up. ffmpeg numbers its subtitle
216
+ * streams `0:s:0`, `0:s:1`, … over EVERY subtitle stream, picture-based ones
217
+ * included, in the order the container declares them; the container reading is
218
+ * a list in that same order. So position is the correspondence — but a position
219
+ * match that is merely assumed is worth nothing, so it is CHECKED: each pair
220
+ * has to agree on language or on title. One pair that agrees on neither, or a
221
+ * length that differs, means the two readings are not describing the same
222
+ * thing in the same order, and then the container reading is not used at all.
223
+ */
224
+
225
+ /**
226
+ * Language codes that carry no information, and so cannot confirm a pairing.
227
+ *
228
+ * ffmpeg prints `und` for a stream with no language; Matroska's own default
229
+ * for `Language` is `eng`, which is why an absent element cannot be read as a
230
+ * statement either — but `eng` is also a real answer, so it is not listed here
231
+ * and is compared like any other.
232
+ */
233
+ const EMPTY_LANGUAGES = new Set(["", "und", "unknown"]);
234
+
235
+ /**
236
+ * @param {unknown} value
237
+ * @returns {string}
238
+ */
239
+ function normalise(value) {
240
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
241
+ }
242
+
243
+ /**
244
+ * Whether one banner stream and one container track can be the same track.
245
+ *
246
+ * Agreement on either the language or the name is enough; both being empty is
247
+ * not agreement, because two tracks that say nothing about themselves say
248
+ * nothing about their pairing either.
249
+ *
250
+ * @param {{ language?: string, title?: string }} banner
251
+ * @param {{ language?: string, name?: string }} container
252
+ * @returns {boolean}
253
+ */
254
+ function pairingHolds(banner, container) {
255
+ const bannerLanguage = normalise(banner?.language);
256
+ const containerLanguage = normalise(container?.language);
257
+ if (
258
+ !EMPTY_LANGUAGES.has(bannerLanguage) &&
259
+ !EMPTY_LANGUAGES.has(containerLanguage) &&
260
+ bannerLanguage === containerLanguage
261
+ ) {
262
+ return true;
263
+ }
264
+ const bannerTitle = normalise(banner?.title);
265
+ const containerName = normalise(container?.name);
266
+ if (bannerTitle.length > 0 && bannerTitle === containerName) {
267
+ return true;
268
+ }
269
+ // Nothing to compare on either side. Not a disagreement — a file may name
270
+ // neither — so it does not break the alignment; it simply adds no support.
271
+ return (
272
+ (EMPTY_LANGUAGES.has(bannerLanguage) || EMPTY_LANGUAGES.has(containerLanguage)) &&
273
+ (bannerTitle.length === 0 || containerName.length === 0)
274
+ );
275
+ }
276
+
277
+ /**
278
+ * The banner's subtitle tracks, with what the container says about each.
279
+ *
280
+ * Every returned track gains `declaresDefault`: whether the FILE wrote the flag
281
+ * for it. When the container reading cannot be trusted — no declarations, a
282
+ * different number of them, or a pair that agrees on neither language nor name
283
+ * — every track gets `declaresDefault: false` and its `isDefault` is left as
284
+ * the banner had it. That is the honest answer for a file we cannot read this
285
+ * way: the container has not been heard from, so nothing is shown unasked.
286
+ *
287
+ * @param {Array<{ index?: number, language?: string, title?: string, isDefault?: boolean }>} bannerTracks
288
+ * @param {Array<{ language?: string, name?: string, isDefault?: boolean, declaresDefault?: boolean }>} declared
289
+ * @returns {{ tracks: object[], aligned: boolean, reason: string }}
290
+ */
291
+ function mergeContainerSubtitleFlags(bannerTracks, declared) {
292
+ const banner = Array.isArray(bannerTracks) ? bannerTracks : [];
293
+ const container = Array.isArray(declared) ? declared : [];
294
+ const undecided = () => ({
295
+ // The container reading could not be lined up, so nothing of it is used —
296
+ // including the flags, which would otherwise be attributed to the wrong
297
+ // track.
298
+ tracks: banner.map((track) => ({
299
+ ...track,
300
+ declaresDefault: false,
301
+ isForced: false,
302
+ isHearingImpaired: false,
303
+ // Not "the container says this track is unusable" — nothing of the
304
+ // container is being used here. A track is offered unless it was read to
305
+ // say otherwise.
306
+ isEnabled: true,
307
+ languageBcp47: ""
308
+ }))
309
+ });
310
+ if (container.length === 0) {
311
+ return { ...undecided(), aligned: false, reason: "the container declares no subtitle track" };
312
+ }
313
+ if (container.length !== banner.length) {
314
+ return {
315
+ ...undecided(),
316
+ aligned: false,
317
+ reason: `the container declares ${container.length} subtitle tracks and the probe found ${banner.length}`
318
+ };
319
+ }
320
+ for (const [order, track] of banner.entries()) {
321
+ if (!pairingHolds(track, container[order])) {
322
+ return {
323
+ ...undecided(),
324
+ aligned: false,
325
+ reason:
326
+ `subtitle ${order} is "${normalise(track?.title) || "-"}"/${normalise(track?.language) || "-"} ` +
327
+ `in the probe and "${normalise(container[order]?.name) || "-"}"/` +
328
+ `${normalise(container[order]?.language) || "-"} in the container`
329
+ };
330
+ }
331
+ }
332
+ return {
333
+ tracks: banner.map((track, order) => ({
334
+ ...track,
335
+ isDefault: container[order].isDefault === true,
336
+ declaresDefault: container[order].declaresDefault === true,
337
+ // Read from the file rather than guessed from the track's name. Both are
338
+ // stated by the container itself (RFC 9559 §5.1.4.1) and neither reaches
339
+ // ffmpeg's `-i` banner, which is where every other field here comes from.
340
+ isForced: container[order].isForced === true,
341
+ isHearingImpaired: container[order].isHearingImpaired === true,
342
+ // FlagEnabled, so the browser can leave an unusable track out of the
343
+ // menu. It stays in this list and keeps its number: ffmpeg creates a
344
+ // stream for it either way.
345
+ isEnabled: container[order].isEnabled !== false,
346
+ // The RFC 5646 tag, where the file writes one. Kept beside the code
347
+ // rather than replacing it: what this list is aligned against is ffmpeg's
348
+ // banner, which prints the three-letter form.
349
+ languageBcp47: typeof container[order].languageBcp47 === "string" ? container[order].languageBcp47 : ""
350
+ })),
351
+ aligned: true,
352
+ reason: ""
353
+ };
354
+ }