@torrent-tv/proxy 2.89.6 → 2.89.8

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 (92) hide show
  1. package/AGENTS.md +32 -12
  2. package/CHANGELOG.md +2340 -2330
  3. package/assets/calibration/audio/NOTICE.md +19 -19
  4. package/assets/calibration/audio/manifest.json +98 -98
  5. package/biome.json +412 -412
  6. package/docs/browser-proxy-contract.md +155 -155
  7. package/docs/container-architecture.md +273 -273
  8. package/docs/encode-run-state.md +1 -1
  9. package/docs/playback-start-forecast.md +113 -98
  10. package/package.json +51 -50
  11. package/routes/api/sources/files/get.js +106 -106
  12. package/scripts/build-audio-samples.mjs +31 -31
  13. package/services/encode/EncodeRun.js +67 -15
  14. package/services/encode/EncodeRuns.js +19 -7
  15. package/services/encode/OutputOpening.js +784 -784
  16. package/services/encode/audio-calibration.js +67 -67
  17. package/services/encode/audio-work-rate.js +15 -15
  18. package/services/encode/encode-exit.js +2 -0
  19. package/services/encode/hwaccel.js +1894 -1894
  20. package/services/encode/output/index.js +24 -24
  21. package/services/encode/piece-completeness.js +60 -2
  22. package/services/encode/run-command.js +757 -755
  23. package/services/encode/segment-formats/index.js +1 -0
  24. package/services/encode/segment-formats/mp4-boxes.js +8 -1
  25. package/services/media/ContainerOrchestrator.js +202 -202
  26. package/services/media/KeyframeTables.js +356 -356
  27. package/services/media/SubtitleCues.js +592 -592
  28. package/services/media/audio-inventory.js +299 -299
  29. package/services/media/container/AviContainer.js +268 -268
  30. package/services/media/container/Container.js +632 -632
  31. package/services/media/container/ContainerFactory.js +38 -38
  32. package/services/media/container/MatroskaContainer.js +1031 -1031
  33. package/services/media/container/Mp4Container.js +1354 -1354
  34. package/services/media/container/SubtitleFileContainer.js +339 -339
  35. package/services/media/container/ebml-stream.js +174 -174
  36. package/services/media/container/matroska-clusters.js +1165 -1165
  37. package/services/media/container/unavailable.js +77 -77
  38. package/services/media/tracks/ContainerTrack.js +84 -84
  39. package/services/media/tracks/TextSubtitleTrack.js +295 -295
  40. package/services/storage/piece-store/shared-piece-store.js +1937 -1937
  41. package/services/storage/segment-store/SegmentStore.js +1294 -1294
  42. package/services/torrent/Contents.js +382 -382
  43. package/services/torrent/episode-naming.js +182 -182
  44. package/services/torrent/torrent-pool.js +2688 -2688
  45. package/services/torrent/worker/client.js +836 -836
  46. package/services/torrent/worker/held-bytes.js +231 -231
  47. package/services/torrent/worker/worker.js +1137 -1137
  48. package/services/transport/data-channel-handler.js +1373 -1373
  49. package/services/viewer/PriorityMap.js +421 -421
  50. package/test/audio-calibration.test.js +23 -23
  51. package/test/auto-quality-step.test.js +762 -762
  52. package/test/coalesce.test.js +39 -39
  53. package/test/coverage-follows-the-disk.test.js +5 -0
  54. package/test/decode-cost.test.js +475 -475
  55. package/test/encode-run.test.js +58 -0
  56. package/test/episode-naming.test.js +131 -131
  57. package/test/failed-encoder-still-serves-what-exists.test.js +1 -1
  58. package/test/fixtures/audio-frame-boundary.json +1 -1
  59. package/test/fixtures/refused-audio-20261002.json +10 -0
  60. package/test/fmp4-presentation-clock.test.js +4 -2
  61. package/test/format-keyed-outputs.test.js +78 -78
  62. package/test/health-metrics.test.js +11 -13
  63. package/test/held-read-ownership.test.js +77 -77
  64. package/test/helpers/encode-run.js +14 -6
  65. package/test/helpers/held-file.js +77 -77
  66. package/test/helpers/manager.js +62 -62
  67. package/test/helpers/matroska-file.js +296 -296
  68. package/test/keyframe-table-budget.test.js +123 -123
  69. package/test/matroska-cluster-discovery.test.js +323 -323
  70. package/test/one-output-one-session.test.js +273 -273
  71. package/test/output-speed.test.js +6 -1
  72. package/test/piece-completeness.test.js +37 -1
  73. package/test/quality-variants.test.js +1274 -1270
  74. package/test/rate-control-in-the-output.test.js +4 -3
  75. package/test/reads-not-yet-arrived.test.js +218 -218
  76. package/test/seek-frees-the-viewers-requests.test.js +1 -1
  77. package/test/segment-closed-on-both-branches.test.js +114 -114
  78. package/test/segment-judged-by-its-own-header.test.js +222 -222
  79. package/test/segment-serve-wiring.test.js +481 -481
  80. package/test/serving-existing-output.test.js +111 -111
  81. package/test/source-files-route.test.js +113 -113
  82. package/test/subtitle-cue-walk.test.js +385 -385
  83. package/test/subtitle-metadata.test.js +15 -15
  84. package/test/subtitle-plan-waits.test.js +125 -125
  85. package/test/subtitle-track-numbering.test.js +391 -391
  86. package/test/two-viewers-one-picture.test.js +508 -508
  87. package/test/viewer-requests-admission.test.js +92 -92
  88. package/test/viewer-starts-on-map.test.js +27 -27
  89. package/test/viewer-states.test.js +5 -2
  90. package/test/viewing-generations.test.js +390 -390
  91. package/test/whole-file-held-read.test.js +30 -30
  92. package/utils/coalesce.js +41 -41
@@ -1,339 +1,339 @@
1
- /**
2
- * @file A file of subtitles as a container of its own — `.srt`, `.ass`, `.ssa`,
3
- * `.vtt` shipped beside the film.
4
- *
5
- * It belongs in this folder for the same reason `.mka` does: "a file of its
6
- * own" is not a KIND of track, only the answer to where a track's bytes are,
7
- * and the question this folder answers is how a format frames what it carries.
8
- * SubRip frames a cue as an ordinal, a timing line and the lines under it; ASS
9
- * frames one as a `Dialogue:` row whose FIELD ORDER the file itself states in
10
- * `[Events]`; WebVTT is already what a browser reads.
11
- *
12
- * That last point about ASS is what makes the file different from Matroska and
13
- * the reason both need their own answer. Matroska fixes the order in its own
14
- * specification, so eight fields always stand before the text. A file does not:
15
- * `Format:` may list the columns in any order, and the specification is that
16
- * the reader obeys it. Two framings of one subtitle format, each stated by
17
- * whoever stores it.
18
- *
19
- * What this file does NOT do is take off ASS's own markup — `{\pos(…)}`, `\N`,
20
- * `\h`. That is the same wherever ASS is stored and lives in
21
- * `TextSubtitleTrack`, because it belongs to the codec rather than the store.
22
- */
23
-
24
- import { Container } from "./Container.js";
25
- import { TextSubtitleTrack } from "../tracks/TextSubtitleTrack.js";
26
-
27
- /** A leading UTF-8 BOM, which must never reach the WEBVTT signature or a cue. */
28
- function stripBom(text) {
29
- return typeof text === "string" && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
30
- }
31
-
32
- /** The extensions this reads. `.vtt` is included and passes through unparsed. */
33
- const EXTENSIONS = new Set([".srt", ".ass", ".ssa", ".vtt", ".webvtt"]);
34
-
35
- /**
36
- * A SubRip timing line. The specification writes a comma before the
37
- * milliseconds; WebVTT writes a dot, which is the only difference between the
38
- * two lines.
39
- */
40
- const SRT_TIMING = /^(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})/;
41
-
42
- /** An ASS timing field: `h:mm:ss.cc`, centiseconds. */
43
- const ASS_TIMING = /^(\d+):(\d{2}):(\d{2})\.(\d{1,2})$/;
44
-
45
- /**
46
- * Seconds from a SubRip timing line's four captured parts.
47
- *
48
- * @param {string[]} parts - [hours, minutes, seconds, fraction]
49
- * @returns {number}
50
- */
51
- function srtSeconds([hours, minutes, seconds, fraction]) {
52
- const ms = Number(String(fraction).padEnd(3, "0"));
53
- return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds) + ms / 1000;
54
- }
55
-
56
- /**
57
- * Seconds from an ASS timing field.
58
- *
59
- * @param {string} field
60
- * @returns {number | null} Null when the field is not a timing at all, which is
61
- * a malformed row and not a cue at zero.
62
- */
63
- function assSeconds(field) {
64
- const match = ASS_TIMING.exec(String(field ?? "").trim());
65
- if (!match) {
66
- return null;
67
- }
68
- const centiseconds = Number(String(match[4]).padEnd(2, "0"));
69
- return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]) + centiseconds / 100;
70
- }
71
-
72
- export class SubtitleFileContainer extends Container {
73
- /**
74
- * @param {object} params
75
- * @param {string} params.extension - Lowercase, including the dot.
76
- * @param {string} [params.label]
77
- */
78
- constructor({ extension, label = "" }) {
79
- // A subtitle file is read whole — it is kilobytes — so there is no range
80
- // reading and no size to bound it by. `readTracks` and `readCues` take the
81
- // decoded text directly, which is why the base's `readRange` is unused.
82
- super({ readRange: null, fileSize: 0, label });
83
- this.extension = String(extension ?? "").toLowerCase();
84
- /** Column order from `[Events]`'s `Format:`, once a file has been read. */
85
- this.eventColumns = null;
86
- }
87
-
88
- get formatName() {
89
- return "subtitle-file";
90
- }
91
-
92
- /**
93
- * @param {string} extension - Lowercase, including the dot.
94
- * @returns {boolean}
95
- */
96
-
97
- /**
98
- * Decode a subtitle file's bytes to text.
99
- *
100
- * UTF-8 is preferred and a BOM settles it. Where the UTF-8 decode produces
101
- * many replacement characters the bytes are read again as Windows-1251, which
102
- * is what most Russian `.srt` files are written in — otherwise both what the
103
- * viewer reads and what the language detector reads would be mojibake.
104
- *
105
- * @param {Buffer | Uint8Array} bytes
106
- * @returns {string}
107
- */
108
- static decodeBytes(bytes) {
109
- const buffer = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
110
- if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
111
- return new TextDecoder("utf-8").decode(buffer);
112
- }
113
- const utf8 = new TextDecoder("utf-8").decode(buffer);
114
- const replacements = (utf8.match(/�/g) || []).length;
115
- // More than half a per cent of the text unreadable is not UTF-8 at all.
116
- if (replacements > Math.max(2, utf8.length * 0.005)) {
117
- try {
118
- return new TextDecoder("windows-1251").decode(buffer);
119
- } catch {
120
- // The decoder needs a full-ICU build; fall back to the UTF-8 attempt.
121
- }
122
- }
123
- return utf8;
124
- }
125
-
126
- /**
127
- * A subtitle file as a WebVTT document, or null for a format that cannot be
128
- * converted in place — image-based `.sup`, ambiguous `.sub`, `.ttml`.
129
- *
130
- * The reading is this class's, because the file states how its own cues are
131
- * framed; the writing is the track's, because what is inside a cue's text
132
- * belongs to the codec.
133
- *
134
- * @param {string} text
135
- * @param {string} extension - Lowercase, including the dot.
136
- * @returns {string | null}
137
- */
138
- static toVtt(text, extension) {
139
- const clean = stripBom(text);
140
- const ext = String(extension ?? "").toLowerCase();
141
- if (ext === ".vtt" || ext === ".webvtt") {
142
- return clean.trimStart().startsWith("WEBVTT") ? clean : `WEBVTT
143
-
144
- ${clean}`;
145
- }
146
- if (!SubtitleFileContainer.detect(ext)) {
147
- return null;
148
- }
149
- const cues = new SubtitleFileContainer({ extension: ext }).readCues(clean);
150
- if (cues === null) return null;
151
- const vtt = TextSubtitleTrack.cuesToVtt(cues, ext);
152
- if (ext !== ".ass" && ext !== ".ssa") return vtt;
153
- const header = clean.slice(0, 16384).match(/\[Script Info\]([^]*?)(?=\n\[|$)/iu)?.[1] ?? "";
154
- const metadata = { titles: [], genericTitles: [], years: [] };
155
- for (const line of header.split(/\r?\n/u)) {
156
- const field = line.match(/^\s*(Title|Movie Title|Series Title|Original Title|Year|Release Year)\s*:\s*(.{1,160})$/iu);
157
- if (!field) continue;
158
- const key = field[1].toLowerCase();
159
- const value = field[2].trim();
160
- if (key.includes("year")) {
161
- if (/^(18|19|20)\d{2}$/u.test(value)) metadata.years.push(Number(value));
162
- } else if (key === "title") metadata.genericTitles.push(value);
163
- else metadata.titles.push(value);
164
- }
165
- for (const key of Object.keys(metadata)) metadata[key] = [...new Set(metadata[key])].slice(0, 4);
166
- if (!Object.values(metadata).some(values => values.length)) return vtt;
167
- return vtt.replace(/^WEBVTT\r?\n\r?\n/u, `WEBVTT\n\nNOTE TORRENT-TV-METADATA\n${JSON.stringify(metadata)}\n\n`);
168
- }
169
-
170
- static detect(extension) {
171
- return EXTENSIONS.has(String(extension ?? "").toLowerCase());
172
- }
173
-
174
- /**
175
- * The single track a subtitle file carries.
176
- *
177
- * Its `codecId` is the extension, which is the only thing the file says about
178
- * its own format, and the markup table accepts extensions alongside
179
- * container codec names for exactly this reason.
180
- *
181
- * @returns {Promise<TextSubtitleTrack[]>}
182
- */
183
- async readTracks() {
184
- return [new TextSubtitleTrack({
185
- trackNumber: 0,
186
- declaredIndex: 0,
187
- codecId: this.extension,
188
- language: "",
189
- languageBcp47: "",
190
- name: this.label,
191
- isEnabled: true,
192
- isDefault: false,
193
- declaresDefault: false
194
- })];
195
- }
196
-
197
- /**
198
- * The text field of one ASS `Dialogue:` row, by the order the file declared.
199
- *
200
- * Not static, unlike the other containers': the order is read out of the
201
- * file's own header, so the answer depends on which file this is. A row
202
- * arriving before any `Format:` line has been seen has no declared order and
203
- * is not guessed at.
204
- *
205
- * @param {string} row - The row after `Dialogue:`.
206
- * @param {string} [codecId]
207
- * @returns {string}
208
- */
209
- cueTextOf(row, codecId = this.extension) {
210
- if (codecId !== ".ass" && codecId !== ".ssa") {
211
- return String(row ?? "");
212
- }
213
- const at = this.eventColumns ? this.eventColumns.indexOf("text") : -1;
214
- if (at < 0) {
215
- return "";
216
- }
217
- // The text field is last by the specification and may hold commas, so
218
- // everything from its column on is joined back together.
219
- return String(row ?? "").split(",").slice(at).join(",");
220
- }
221
-
222
- /**
223
- * Every cue in the file, with its markup still in place.
224
- *
225
- * @param {string} text - The file, already decoded to characters.
226
- * @returns {{ startSeconds: number, endSeconds: number, text: string }[] | null}
227
- * Null for WebVTT, which is not parsed: it is already what a browser reads,
228
- * and taking it apart to write it back would drop its styles, its regions
229
- * and its cue identifiers for nothing.
230
- */
231
- readCues(text) {
232
- const lines = String(text ?? "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
233
- if (this.extension === ".ass" || this.extension === ".ssa") {
234
- return this.#assCues(lines);
235
- }
236
- if (this.extension === ".srt") {
237
- return this.#srtCues(lines);
238
- }
239
- return null;
240
- }
241
-
242
- /**
243
- * @param {string[]} lines
244
- * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
245
- */
246
- #assCues(lines) {
247
- const cues = [];
248
- let inEvents = false;
249
- this.eventColumns = null;
250
- for (const line of lines) {
251
- const trimmed = line.trim();
252
- if (/^\[.*\]$/.test(trimmed)) {
253
- inEvents = trimmed === "[Events]";
254
- continue;
255
- }
256
- if (!inEvents) {
257
- continue;
258
- }
259
- if (trimmed.startsWith("Format:")) {
260
- this.eventColumns = trimmed
261
- .slice("Format:".length)
262
- .split(",")
263
- .map((column) => column.trim().toLowerCase());
264
- continue;
265
- }
266
- if (!trimmed.startsWith("Dialogue:") || !this.eventColumns) {
267
- continue;
268
- }
269
- const row = trimmed.slice("Dialogue:".length);
270
- const fields = row.split(",");
271
- const startAt = this.eventColumns.indexOf("start");
272
- const endAt = this.eventColumns.indexOf("end");
273
- if (startAt < 0 || endAt < 0) {
274
- continue;
275
- }
276
- const startSeconds = assSeconds(fields[startAt]);
277
- const endSeconds = assSeconds(fields[endAt]);
278
- const cueText = this.cueTextOf(row);
279
- if (startSeconds === null || endSeconds === null || !cueText) {
280
- continue;
281
- }
282
- cues.push({ startSeconds, endSeconds, text: cueText });
283
- }
284
- return cues;
285
- }
286
-
287
- /**
288
- * @param {string[]} lines
289
- * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
290
- */
291
- #srtCues(lines) {
292
- const cues = [];
293
- /** @type {{ startSeconds: number, endSeconds: number, text: string[] } | null} */
294
- let open = null;
295
- const close = () => {
296
- if (!open) {
297
- return;
298
- }
299
- // A file with no blank line between cues leaves the next cue's ordinal as
300
- // the last line of this one. It is SubRip's own numbering, never
301
- // dialogue, so it goes rather than being shown.
302
- while (open.text.length > 0 && /^\d+$/.test(open.text[open.text.length - 1].trim())) {
303
- open.text.pop();
304
- }
305
- const text = open.text.join("\n").trim();
306
- if (text) {
307
- cues.push({ startSeconds: open.startSeconds, endSeconds: open.endSeconds, text });
308
- }
309
- open = null;
310
- };
311
- for (const line of lines) {
312
- const timing = SRT_TIMING.exec(line.trim());
313
- if (timing) {
314
- // A timing line opens a cue and closes the one before it. The ordinal
315
- // above it is SubRip's own numbering and carries nothing a player needs,
316
- // so it is dropped rather than carried into the cue's text — which is
317
- // what taking the lines between timings would do.
318
- close();
319
- open = {
320
- startSeconds: srtSeconds(timing.slice(1, 5)),
321
- endSeconds: srtSeconds(timing.slice(5, 9)),
322
- text: []
323
- };
324
- continue;
325
- }
326
- if (!open) {
327
- continue;
328
- }
329
- if (line.trim() === "") {
330
- close();
331
- continue;
332
- }
333
- open.text.push(line);
334
- }
335
- close();
336
- return cues;
337
- }
338
- }
339
-
1
+ /**
2
+ * @file A file of subtitles as a container of its own — `.srt`, `.ass`, `.ssa`,
3
+ * `.vtt` shipped beside the film.
4
+ *
5
+ * It belongs in this folder for the same reason `.mka` does: "a file of its
6
+ * own" is not a KIND of track, only the answer to where a track's bytes are,
7
+ * and the question this folder answers is how a format frames what it carries.
8
+ * SubRip frames a cue as an ordinal, a timing line and the lines under it; ASS
9
+ * frames one as a `Dialogue:` row whose FIELD ORDER the file itself states in
10
+ * `[Events]`; WebVTT is already what a browser reads.
11
+ *
12
+ * That last point about ASS is what makes the file different from Matroska and
13
+ * the reason both need their own answer. Matroska fixes the order in its own
14
+ * specification, so eight fields always stand before the text. A file does not:
15
+ * `Format:` may list the columns in any order, and the specification is that
16
+ * the reader obeys it. Two framings of one subtitle format, each stated by
17
+ * whoever stores it.
18
+ *
19
+ * What this file does NOT do is take off ASS's own markup — `{\pos(…)}`, `\N`,
20
+ * `\h`. That is the same wherever ASS is stored and lives in
21
+ * `TextSubtitleTrack`, because it belongs to the codec rather than the store.
22
+ */
23
+
24
+ import { Container } from "./Container.js";
25
+ import { TextSubtitleTrack } from "../tracks/TextSubtitleTrack.js";
26
+
27
+ /** A leading UTF-8 BOM, which must never reach the WEBVTT signature or a cue. */
28
+ function stripBom(text) {
29
+ return typeof text === "string" && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
30
+ }
31
+
32
+ /** The extensions this reads. `.vtt` is included and passes through unparsed. */
33
+ const EXTENSIONS = new Set([".srt", ".ass", ".ssa", ".vtt", ".webvtt"]);
34
+
35
+ /**
36
+ * A SubRip timing line. The specification writes a comma before the
37
+ * milliseconds; WebVTT writes a dot, which is the only difference between the
38
+ * two lines.
39
+ */
40
+ const SRT_TIMING = /^(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})/;
41
+
42
+ /** An ASS timing field: `h:mm:ss.cc`, centiseconds. */
43
+ const ASS_TIMING = /^(\d+):(\d{2}):(\d{2})\.(\d{1,2})$/;
44
+
45
+ /**
46
+ * Seconds from a SubRip timing line's four captured parts.
47
+ *
48
+ * @param {string[]} parts - [hours, minutes, seconds, fraction]
49
+ * @returns {number}
50
+ */
51
+ function srtSeconds([hours, minutes, seconds, fraction]) {
52
+ const ms = Number(String(fraction).padEnd(3, "0"));
53
+ return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds) + ms / 1000;
54
+ }
55
+
56
+ /**
57
+ * Seconds from an ASS timing field.
58
+ *
59
+ * @param {string} field
60
+ * @returns {number | null} Null when the field is not a timing at all, which is
61
+ * a malformed row and not a cue at zero.
62
+ */
63
+ function assSeconds(field) {
64
+ const match = ASS_TIMING.exec(String(field ?? "").trim());
65
+ if (!match) {
66
+ return null;
67
+ }
68
+ const centiseconds = Number(String(match[4]).padEnd(2, "0"));
69
+ return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]) + centiseconds / 100;
70
+ }
71
+
72
+ export class SubtitleFileContainer extends Container {
73
+ /**
74
+ * @param {object} params
75
+ * @param {string} params.extension - Lowercase, including the dot.
76
+ * @param {string} [params.label]
77
+ */
78
+ constructor({ extension, label = "" }) {
79
+ // A subtitle file is read whole — it is kilobytes — so there is no range
80
+ // reading and no size to bound it by. `readTracks` and `readCues` take the
81
+ // decoded text directly, which is why the base's `readRange` is unused.
82
+ super({ readRange: null, fileSize: 0, label });
83
+ this.extension = String(extension ?? "").toLowerCase();
84
+ /** Column order from `[Events]`'s `Format:`, once a file has been read. */
85
+ this.eventColumns = null;
86
+ }
87
+
88
+ get formatName() {
89
+ return "subtitle-file";
90
+ }
91
+
92
+ /**
93
+ * @param {string} extension - Lowercase, including the dot.
94
+ * @returns {boolean}
95
+ */
96
+
97
+ /**
98
+ * Decode a subtitle file's bytes to text.
99
+ *
100
+ * UTF-8 is preferred and a BOM settles it. Where the UTF-8 decode produces
101
+ * many replacement characters the bytes are read again as Windows-1251, which
102
+ * is what most Russian `.srt` files are written in — otherwise both what the
103
+ * viewer reads and what the language detector reads would be mojibake.
104
+ *
105
+ * @param {Buffer | Uint8Array} bytes
106
+ * @returns {string}
107
+ */
108
+ static decodeBytes(bytes) {
109
+ const buffer = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
110
+ if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
111
+ return new TextDecoder("utf-8").decode(buffer);
112
+ }
113
+ const utf8 = new TextDecoder("utf-8").decode(buffer);
114
+ const replacements = (utf8.match(/�/g) || []).length;
115
+ // More than half a per cent of the text unreadable is not UTF-8 at all.
116
+ if (replacements > Math.max(2, utf8.length * 0.005)) {
117
+ try {
118
+ return new TextDecoder("windows-1251").decode(buffer);
119
+ } catch {
120
+ // The decoder needs a full-ICU build; fall back to the UTF-8 attempt.
121
+ }
122
+ }
123
+ return utf8;
124
+ }
125
+
126
+ /**
127
+ * A subtitle file as a WebVTT document, or null for a format that cannot be
128
+ * converted in place — image-based `.sup`, ambiguous `.sub`, `.ttml`.
129
+ *
130
+ * The reading is this class's, because the file states how its own cues are
131
+ * framed; the writing is the track's, because what is inside a cue's text
132
+ * belongs to the codec.
133
+ *
134
+ * @param {string} text
135
+ * @param {string} extension - Lowercase, including the dot.
136
+ * @returns {string | null}
137
+ */
138
+ static toVtt(text, extension) {
139
+ const clean = stripBom(text);
140
+ const ext = String(extension ?? "").toLowerCase();
141
+ if (ext === ".vtt" || ext === ".webvtt") {
142
+ return clean.trimStart().startsWith("WEBVTT") ? clean : `WEBVTT
143
+
144
+ ${clean}`;
145
+ }
146
+ if (!SubtitleFileContainer.detect(ext)) {
147
+ return null;
148
+ }
149
+ const cues = new SubtitleFileContainer({ extension: ext }).readCues(clean);
150
+ if (cues === null) return null;
151
+ const vtt = TextSubtitleTrack.cuesToVtt(cues, ext);
152
+ if (ext !== ".ass" && ext !== ".ssa") return vtt;
153
+ const header = clean.slice(0, 16384).match(/\[Script Info\]([^]*?)(?=\n\[|$)/iu)?.[1] ?? "";
154
+ const metadata = { titles: [], genericTitles: [], years: [] };
155
+ for (const line of header.split(/\r?\n/u)) {
156
+ const field = line.match(/^\s*(Title|Movie Title|Series Title|Original Title|Year|Release Year)\s*:\s*(.{1,160})$/iu);
157
+ if (!field) continue;
158
+ const key = field[1].toLowerCase();
159
+ const value = field[2].trim();
160
+ if (key.includes("year")) {
161
+ if (/^(18|19|20)\d{2}$/u.test(value)) metadata.years.push(Number(value));
162
+ } else if (key === "title") metadata.genericTitles.push(value);
163
+ else metadata.titles.push(value);
164
+ }
165
+ for (const key of Object.keys(metadata)) metadata[key] = [...new Set(metadata[key])].slice(0, 4);
166
+ if (!Object.values(metadata).some(values => values.length)) return vtt;
167
+ return vtt.replace(/^WEBVTT\r?\n\r?\n/u, `WEBVTT\n\nNOTE TORRENT-TV-METADATA\n${JSON.stringify(metadata)}\n\n`);
168
+ }
169
+
170
+ static detect(extension) {
171
+ return EXTENSIONS.has(String(extension ?? "").toLowerCase());
172
+ }
173
+
174
+ /**
175
+ * The single track a subtitle file carries.
176
+ *
177
+ * Its `codecId` is the extension, which is the only thing the file says about
178
+ * its own format, and the markup table accepts extensions alongside
179
+ * container codec names for exactly this reason.
180
+ *
181
+ * @returns {Promise<TextSubtitleTrack[]>}
182
+ */
183
+ async readTracks() {
184
+ return [new TextSubtitleTrack({
185
+ trackNumber: 0,
186
+ declaredIndex: 0,
187
+ codecId: this.extension,
188
+ language: "",
189
+ languageBcp47: "",
190
+ name: this.label,
191
+ isEnabled: true,
192
+ isDefault: false,
193
+ declaresDefault: false
194
+ })];
195
+ }
196
+
197
+ /**
198
+ * The text field of one ASS `Dialogue:` row, by the order the file declared.
199
+ *
200
+ * Not static, unlike the other containers': the order is read out of the
201
+ * file's own header, so the answer depends on which file this is. A row
202
+ * arriving before any `Format:` line has been seen has no declared order and
203
+ * is not guessed at.
204
+ *
205
+ * @param {string} row - The row after `Dialogue:`.
206
+ * @param {string} [codecId]
207
+ * @returns {string}
208
+ */
209
+ cueTextOf(row, codecId = this.extension) {
210
+ if (codecId !== ".ass" && codecId !== ".ssa") {
211
+ return String(row ?? "");
212
+ }
213
+ const at = this.eventColumns ? this.eventColumns.indexOf("text") : -1;
214
+ if (at < 0) {
215
+ return "";
216
+ }
217
+ // The text field is last by the specification and may hold commas, so
218
+ // everything from its column on is joined back together.
219
+ return String(row ?? "").split(",").slice(at).join(",");
220
+ }
221
+
222
+ /**
223
+ * Every cue in the file, with its markup still in place.
224
+ *
225
+ * @param {string} text - The file, already decoded to characters.
226
+ * @returns {{ startSeconds: number, endSeconds: number, text: string }[] | null}
227
+ * Null for WebVTT, which is not parsed: it is already what a browser reads,
228
+ * and taking it apart to write it back would drop its styles, its regions
229
+ * and its cue identifiers for nothing.
230
+ */
231
+ readCues(text) {
232
+ const lines = String(text ?? "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
233
+ if (this.extension === ".ass" || this.extension === ".ssa") {
234
+ return this.#assCues(lines);
235
+ }
236
+ if (this.extension === ".srt") {
237
+ return this.#srtCues(lines);
238
+ }
239
+ return null;
240
+ }
241
+
242
+ /**
243
+ * @param {string[]} lines
244
+ * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
245
+ */
246
+ #assCues(lines) {
247
+ const cues = [];
248
+ let inEvents = false;
249
+ this.eventColumns = null;
250
+ for (const line of lines) {
251
+ const trimmed = line.trim();
252
+ if (/^\[.*\]$/.test(trimmed)) {
253
+ inEvents = trimmed === "[Events]";
254
+ continue;
255
+ }
256
+ if (!inEvents) {
257
+ continue;
258
+ }
259
+ if (trimmed.startsWith("Format:")) {
260
+ this.eventColumns = trimmed
261
+ .slice("Format:".length)
262
+ .split(",")
263
+ .map((column) => column.trim().toLowerCase());
264
+ continue;
265
+ }
266
+ if (!trimmed.startsWith("Dialogue:") || !this.eventColumns) {
267
+ continue;
268
+ }
269
+ const row = trimmed.slice("Dialogue:".length);
270
+ const fields = row.split(",");
271
+ const startAt = this.eventColumns.indexOf("start");
272
+ const endAt = this.eventColumns.indexOf("end");
273
+ if (startAt < 0 || endAt < 0) {
274
+ continue;
275
+ }
276
+ const startSeconds = assSeconds(fields[startAt]);
277
+ const endSeconds = assSeconds(fields[endAt]);
278
+ const cueText = this.cueTextOf(row);
279
+ if (startSeconds === null || endSeconds === null || !cueText) {
280
+ continue;
281
+ }
282
+ cues.push({ startSeconds, endSeconds, text: cueText });
283
+ }
284
+ return cues;
285
+ }
286
+
287
+ /**
288
+ * @param {string[]} lines
289
+ * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
290
+ */
291
+ #srtCues(lines) {
292
+ const cues = [];
293
+ /** @type {{ startSeconds: number, endSeconds: number, text: string[] } | null} */
294
+ let open = null;
295
+ const close = () => {
296
+ if (!open) {
297
+ return;
298
+ }
299
+ // A file with no blank line between cues leaves the next cue's ordinal as
300
+ // the last line of this one. It is SubRip's own numbering, never
301
+ // dialogue, so it goes rather than being shown.
302
+ while (open.text.length > 0 && /^\d+$/.test(open.text[open.text.length - 1].trim())) {
303
+ open.text.pop();
304
+ }
305
+ const text = open.text.join("\n").trim();
306
+ if (text) {
307
+ cues.push({ startSeconds: open.startSeconds, endSeconds: open.endSeconds, text });
308
+ }
309
+ open = null;
310
+ };
311
+ for (const line of lines) {
312
+ const timing = SRT_TIMING.exec(line.trim());
313
+ if (timing) {
314
+ // A timing line opens a cue and closes the one before it. The ordinal
315
+ // above it is SubRip's own numbering and carries nothing a player needs,
316
+ // so it is dropped rather than carried into the cue's text — which is
317
+ // what taking the lines between timings would do.
318
+ close();
319
+ open = {
320
+ startSeconds: srtSeconds(timing.slice(1, 5)),
321
+ endSeconds: srtSeconds(timing.slice(5, 9)),
322
+ text: []
323
+ };
324
+ continue;
325
+ }
326
+ if (!open) {
327
+ continue;
328
+ }
329
+ if (line.trim() === "") {
330
+ close();
331
+ continue;
332
+ }
333
+ open.text.push(line);
334
+ }
335
+ close();
336
+ return cues;
337
+ }
338
+ }
339
+