@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,295 +1,295 @@
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
- // The found-order number travels with the cue where it has one: it is
168
- // how a browser names a cue it may be asked to take back.
169
- result.push(Number.isInteger(cue.seq) ? { startSeconds: cue.startSeconds, endSeconds, text, seq: cue.seq } : { startSeconds: cue.startSeconds, endSeconds, text });
170
- });
171
- return result;
172
- }
173
-
174
- /**
175
- * A WebVTT document from a list of cues — the one writer, used by every path
176
- * that produces subtitles: a file beside the film, a track inside it, a pull
177
- * and a push.
178
- *
179
- * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
180
- * @param {string} codecId
181
- * @returns {string}
182
- */
183
- static cuesToVtt(cues, codecId) {
184
- const lines = ["WEBVTT", ""];
185
- for (const cue of TextSubtitleTrack.finalizeCues(cues, codecId)) {
186
- // WebVTT's cue identifier (W3C WebVTT §4.1): the found-order number,
187
- // where the cue has one, so a cue delivered in a document can be named
188
- // later exactly as a pushed one is.
189
- if (Number.isInteger(cue.seq)) {
190
- lines.push(String(cue.seq));
191
- }
192
- lines.push(`${TextSubtitleTrack.vttTime(cue.startSeconds)} --> ${TextSubtitleTrack.vttTime(cue.endSeconds)}`);
193
- lines.push(cue.text);
194
- lines.push("");
195
- }
196
- return lines.join("\n");
197
- }
198
-
199
- /**
200
- * The words of a WebVTT document — what a viewer reads, with everything the
201
- * format puts around them removed.
202
- *
203
- * A WebVTT document is a series of blocks separated by blank lines. A block
204
- * that holds a timing line (`00:00:12.060 --> 00:00:13.270`) is a cue, and the
205
- * lines after that timing line are its text; the lines before it are the cue's
206
- * optional identifier. A block with NO timing line is the `WEBVTT` header or a
207
- * `NOTE` / `STYLE` / `REGION` block, and none of those is anybody's language.
208
- * That one rule removes the identifiers, the timings and the headers together.
209
- *
210
- * What is left can still carry WebVTT's own inline markup — `<v Speaker>`,
211
- * `<i>`, `<c.yellow>` — and character references. Both are dropped: a speaker
212
- * name and a class name are written in whatever language the releaser's tooling
213
- * used, which is not the language of the film.
214
- *
215
- * @param {string} vtt - A WebVTT document.
216
- * @returns {string} The cue text, blocks joined by newlines.
217
- */
218
- static cueTextOfVtt(vtt) {
219
- if (typeof vtt !== "string") {
220
- return "";
221
- }
222
- const blocks = vtt.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
223
- const spoken = [];
224
- for (const block of blocks) {
225
- const lines = block.split("\n");
226
- const timingAt = lines.findIndex((line) => line.includes("-->"));
227
- if (timingAt < 0) {
228
- continue;
229
- }
230
- for (const line of lines.slice(timingAt + 1)) {
231
- spoken.push(line);
232
- }
233
- }
234
- return spoken
235
- .join("\n")
236
- .replace(/<[^>]*>/g, "")
237
- // A character reference stands for one character and never for a word, so a
238
- // space in its place keeps the neighbouring words apart and adds nothing.
239
- .replace(/&[a-z]+;|&#\d+;|&#x[0-9a-f]+;/gi, " ")
240
- .trim();
241
- }
242
-
243
- /**
244
- * Detect the language of a WebVTT document, reading only its cue text.
245
- *
246
- * @param {string} vtt - A WebVTT document.
247
- * @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
248
- */
249
- static detectLanguageFromVtt(vtt) {
250
- return detectLanguage(TextSubtitleTrack.cueTextOfVtt(vtt));
251
- }
252
-
253
- static isTextCodec(codecId) {
254
- return TEXT_CODECS_MATROSKA.has(codecId) || TEXT_FORMATS_MP4.has(codecId);
255
- }
256
-
257
- /** Which markup this track's cue text carries. */
258
- get markupKind() {
259
- return TextSubtitleTrack.markupKindOf(this.textCodec);
260
- }
261
-
262
- /**
263
- * The visible text of one of this track's cues.
264
- *
265
- * @param {string} textField - The cue's text field, already out of its
266
- * container's framing. This method knows the codec and not the container,
267
- * which is why it cannot be handed a whole dialogue row.
268
- * @returns {string}
269
- */
270
- plainText(textField) {
271
- return TextSubtitleTrack.plainTextOf(textField, this.textCodec);
272
- }
273
-
274
- /**
275
- * This track's cues, resolved and stripped, as a player reads them.
276
- *
277
- * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
278
- * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
279
- */
280
- finalize(cues) {
281
- return TextSubtitleTrack.finalizeCues(cues, this.textCodec);
282
- }
283
-
284
- /**
285
- * This track's cues as a WebVTT document.
286
- *
287
- * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
288
- * @returns {string}
289
- */
290
- toVtt(cues) {
291
- return TextSubtitleTrack.cuesToVtt(cues, this.textCodec);
292
- }
293
- }
294
-
295
- 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
+ // The found-order number travels with the cue where it has one: it is
168
+ // how a browser names a cue it may be asked to take back.
169
+ result.push(Number.isInteger(cue.seq) ? { startSeconds: cue.startSeconds, endSeconds, text, seq: cue.seq } : { startSeconds: cue.startSeconds, endSeconds, text });
170
+ });
171
+ return result;
172
+ }
173
+
174
+ /**
175
+ * A WebVTT document from a list of cues — the one writer, used by every path
176
+ * that produces subtitles: a file beside the film, a track inside it, a pull
177
+ * and a push.
178
+ *
179
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
180
+ * @param {string} codecId
181
+ * @returns {string}
182
+ */
183
+ static cuesToVtt(cues, codecId) {
184
+ const lines = ["WEBVTT", ""];
185
+ for (const cue of TextSubtitleTrack.finalizeCues(cues, codecId)) {
186
+ // WebVTT's cue identifier (W3C WebVTT §4.1): the found-order number,
187
+ // where the cue has one, so a cue delivered in a document can be named
188
+ // later exactly as a pushed one is.
189
+ if (Number.isInteger(cue.seq)) {
190
+ lines.push(String(cue.seq));
191
+ }
192
+ lines.push(`${TextSubtitleTrack.vttTime(cue.startSeconds)} --> ${TextSubtitleTrack.vttTime(cue.endSeconds)}`);
193
+ lines.push(cue.text);
194
+ lines.push("");
195
+ }
196
+ return lines.join("\n");
197
+ }
198
+
199
+ /**
200
+ * The words of a WebVTT document — what a viewer reads, with everything the
201
+ * format puts around them removed.
202
+ *
203
+ * A WebVTT document is a series of blocks separated by blank lines. A block
204
+ * that holds a timing line (`00:00:12.060 --> 00:00:13.270`) is a cue, and the
205
+ * lines after that timing line are its text; the lines before it are the cue's
206
+ * optional identifier. A block with NO timing line is the `WEBVTT` header or a
207
+ * `NOTE` / `STYLE` / `REGION` block, and none of those is anybody's language.
208
+ * That one rule removes the identifiers, the timings and the headers together.
209
+ *
210
+ * What is left can still carry WebVTT's own inline markup — `<v Speaker>`,
211
+ * `<i>`, `<c.yellow>` — and character references. Both are dropped: a speaker
212
+ * name and a class name are written in whatever language the releaser's tooling
213
+ * used, which is not the language of the film.
214
+ *
215
+ * @param {string} vtt - A WebVTT document.
216
+ * @returns {string} The cue text, blocks joined by newlines.
217
+ */
218
+ static cueTextOfVtt(vtt) {
219
+ if (typeof vtt !== "string") {
220
+ return "";
221
+ }
222
+ const blocks = vtt.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
223
+ const spoken = [];
224
+ for (const block of blocks) {
225
+ const lines = block.split("\n");
226
+ const timingAt = lines.findIndex((line) => line.includes("-->"));
227
+ if (timingAt < 0) {
228
+ continue;
229
+ }
230
+ for (const line of lines.slice(timingAt + 1)) {
231
+ spoken.push(line);
232
+ }
233
+ }
234
+ return spoken
235
+ .join("\n")
236
+ .replace(/<[^>]*>/g, "")
237
+ // A character reference stands for one character and never for a word, so a
238
+ // space in its place keeps the neighbouring words apart and adds nothing.
239
+ .replace(/&[a-z]+;|&#\d+;|&#x[0-9a-f]+;/gi, " ")
240
+ .trim();
241
+ }
242
+
243
+ /**
244
+ * Detect the language of a WebVTT document, reading only its cue text.
245
+ *
246
+ * @param {string} vtt - A WebVTT document.
247
+ * @returns {{ code: string, name: string } | null} Detected language, or null when uncertain.
248
+ */
249
+ static detectLanguageFromVtt(vtt) {
250
+ return detectLanguage(TextSubtitleTrack.cueTextOfVtt(vtt));
251
+ }
252
+
253
+ static isTextCodec(codecId) {
254
+ return TEXT_CODECS_MATROSKA.has(codecId) || TEXT_FORMATS_MP4.has(codecId);
255
+ }
256
+
257
+ /** Which markup this track's cue text carries. */
258
+ get markupKind() {
259
+ return TextSubtitleTrack.markupKindOf(this.textCodec);
260
+ }
261
+
262
+ /**
263
+ * The visible text of one of this track's cues.
264
+ *
265
+ * @param {string} textField - The cue's text field, already out of its
266
+ * container's framing. This method knows the codec and not the container,
267
+ * which is why it cannot be handed a whole dialogue row.
268
+ * @returns {string}
269
+ */
270
+ plainText(textField) {
271
+ return TextSubtitleTrack.plainTextOf(textField, this.textCodec);
272
+ }
273
+
274
+ /**
275
+ * This track's cues, resolved and stripped, as a player reads them.
276
+ *
277
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
278
+ * @returns {{ startSeconds: number, endSeconds: number, text: string }[]}
279
+ */
280
+ finalize(cues) {
281
+ return TextSubtitleTrack.finalizeCues(cues, this.textCodec);
282
+ }
283
+
284
+ /**
285
+ * This track's cues as a WebVTT document.
286
+ *
287
+ * @param {{ startSeconds: number, endSeconds?: number | null, text: string }[]} cues
288
+ * @returns {string}
289
+ */
290
+ toVtt(cues) {
291
+ return TextSubtitleTrack.cuesToVtt(cues, this.textCodec);
292
+ }
293
+ }
294
+
295
+ export { TEXT_CODECS_MATROSKA, TEXT_FORMATS_MP4 };