@torrent-tv/proxy 2.74.1 → 2.76.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 (124) hide show
  1. package/CHANGELOG.md +1504 -1453
  2. package/CLAUDE.md +19 -6
  3. package/biome.json +182 -1
  4. package/docs/container-architecture.md +27 -6
  5. package/docs/encode-run-state.md +1 -1
  6. package/knip.json +14 -0
  7. package/package.json +1 -1
  8. package/routes/api/sources/warm/post.js +1 -1
  9. package/routes/api/transcode-sessions/post.js +185 -185
  10. package/routes/api/transcode-sessions/progress/get.js +5 -1
  11. package/routes/transcode/audio-file/get.js +11 -1
  12. package/routes/transcode/audio-warm/get.js +11 -1
  13. package/routes/transcode/session-file/get.js +1 -1
  14. package/routes/transcode/variant-file/get.js +10 -1
  15. package/scripts/render-run-graph.js +2 -2
  16. package/server.js +25 -0
  17. package/services/audio-inventory.js +9 -214
  18. package/services/container/AviContainer.js +266 -81
  19. package/services/container/Container.js +281 -80
  20. package/services/container/ContainerFactory.js +67 -0
  21. package/services/container/MatroskaContainer.js +327 -8
  22. package/services/container/Mp4Container.js +373 -27
  23. package/services/container/SubtitleFileContainer.js +0 -1
  24. package/services/controllers/SubtitleController.js +128 -128
  25. package/services/demand/index.js +7 -10
  26. package/services/download/registry.js +0 -14
  27. package/services/encode/CoverageMap.js +281 -0
  28. package/services/encode/EncodePlan.js +255 -0
  29. package/services/encode/EncodeRun.js +587 -0
  30. package/services/encode/Encoder.js +84 -0
  31. package/services/encode/NvencEncoder.js +45 -0
  32. package/services/encode/QsvEncoder.js +47 -0
  33. package/services/encode/SegmentDemand.js +0 -0
  34. package/services/encode/SegmentStore.js +529 -0
  35. package/services/encode/SoftwareEncoder.js +111 -0
  36. package/services/encode/V4l2m2mEncoder.js +53 -0
  37. package/services/encode/VaapiEncoder.js +53 -0
  38. package/services/encode/args.js +200 -0
  39. package/services/{encode-exit.js → encode/encode-exit.js} +17 -0
  40. package/services/encode/index.js +9 -0
  41. package/services/encode/run-command.js +647 -0
  42. package/services/hls-session-manager.js +11073 -10711
  43. package/services/hwaccel.js +1688 -1992
  44. package/services/orchestrators/EncodeOrchestrator.js +359 -0
  45. package/services/output/LiveOutputs.js +213 -0
  46. package/services/output/Output.js +94 -0
  47. package/services/output/OutputSpec.js +195 -0
  48. package/services/output/Timeline.js +220 -0
  49. package/services/output/index.js +1 -0
  50. package/services/output/ladder.js +26 -0
  51. package/services/playback-planner.js +806 -747
  52. package/services/produced-index.js +222 -300
  53. package/services/source/SourceFile.js +346 -0
  54. package/services/{sidecar-files.js → torrent/files.js} +107 -11
  55. package/services/torrent/naming.js +619 -0
  56. package/services/torrent-worker/client.js +10 -0
  57. package/services/torrent-worker/container-tracks.js +71 -43
  58. package/services/torrent-worker/pool-adapter.js +370 -333
  59. package/services/torrent-worker/protocol.js +7 -0
  60. package/services/torrent-worker/subtitle-cues.js +549 -549
  61. package/services/torrent-worker/worker.js +18 -0
  62. package/services/tracks/AudioTrack.js +131 -40
  63. package/services/tracks/TextSubtitleTrack.js +287 -287
  64. package/services/tracks/index.js +15 -14
  65. package/services/viewer/Viewer.js +145 -0
  66. package/services/viewer/Viewers.js +124 -0
  67. package/test/audio-inventory.test.js +176 -177
  68. package/test/auto-quality-step.test.js +508 -506
  69. package/test/behind-head-repair.test.js +17 -7
  70. package/test/coverage-map.test.js +153 -0
  71. package/test/cut-times-timeline.test.js +6 -5
  72. package/test/cuts-follow-published-grid.test.js +4 -4
  73. package/test/decode-cost.test.js +31 -12
  74. package/test/encode-exit.test.js +1 -1
  75. package/test/encode-orchestrator.test.js +196 -0
  76. package/test/encode-plan.test.js +245 -0
  77. package/test/encode-run-state.test.js +2 -2
  78. package/test/encode-run.test.js +168 -0
  79. package/test/encoder-kinds.test.js +122 -0
  80. package/test/held-request-width.test.js +9 -3
  81. package/test/helpers/encode-run.js +128 -0
  82. package/test/keyframe-index-accuracy.test.js +19 -12
  83. package/test/keyframes-belong-to-the-file.test.js +132 -0
  84. package/test/matroska-cues-track.test.js +192 -192
  85. package/test/mp4-composition-times.test.js +0 -0
  86. package/test/orchestrator-wired.test.js +164 -0
  87. package/test/output-shape.test.js +68 -0
  88. package/test/output-spec.test.js +157 -0
  89. package/test/produced-copy-choice.test.js +58 -92
  90. package/test/produced-index.test.js +142 -188
  91. package/test/quality-variants.test.js +1079 -1075
  92. package/test/run-graph-drift.test.js +1 -1
  93. package/test/run-intervals.test.js +329 -0
  94. package/test/run-position-follows-published-grid.test.js +4 -4
  95. package/test/seek-landing.test.js +8 -8
  96. package/test/seek-target-not-superseded.test.js +21 -9
  97. package/test/segment-demand.test.js +82 -0
  98. package/test/segment-serve-wiring.test.js +47 -52
  99. package/test/segment-store.test.js +187 -0
  100. package/test/segments-are-shared.test.js +175 -0
  101. package/test/sidecar-naming.test.js +142 -0
  102. package/test/source-file.test.js +133 -0
  103. package/test/stale-request-after-seek.test.js +18 -12
  104. package/test/subtitle-language.test.js +252 -252
  105. package/test/timeline.test.js +95 -0
  106. package/test/{sidecar-files.test.js → torrent-files.test.js} +44 -1
  107. package/test/torrent-naming.test.js +255 -0
  108. package/test/tracks-begin-together.test.js +44 -32
  109. package/test/two-viewers-one-picture.test.js +347 -0
  110. package/test/video-facts.test.js +102 -0
  111. package/test/viewer-outputs.test.js +273 -0
  112. package/test/viewer.test.js +91 -0
  113. package/utils/perf.js +1 -63
  114. package/services/container/index.js +0 -6
  115. package/services/container-index/avi.js +0 -167
  116. package/services/container-index/index.js +0 -118
  117. package/services/container-index/matroska.js +0 -336
  118. package/services/container-index/mp4.js +0 -358
  119. package/services/controllers/index.js +0 -2
  120. package/services/download/index.js +0 -8
  121. package/services/orchestrators/index.js +0 -2
  122. /package/services/{container-index → container}/ebml-reader.js +0 -0
  123. /package/services/{encode-run-state.js → encode/encode-run-state.js} +0 -0
  124. /package/services/{language-detect.js → tracks/language-detect.js} +0 -0
@@ -0,0 +1,347 @@
1
+ /**
2
+ * @file Two viewers of one picture, each with their own soundtrack.
3
+ *
4
+ * Measured 2026-09-03 (`research/two-viewers-one-file-2026-09-03.md`): two
5
+ * browsers on one copied file got two picture sessions with byte-identical
6
+ * output, because the key carried the soundtrack a picture without sound does
7
+ * not have. Once they share one picture, everything about the sound that used
8
+ * to be a field of the session has to be a fact about a viewer — otherwise they
9
+ * switch each other's soundtrack off, once per segment, for the whole film.
10
+ */
11
+
12
+ import test from "node:test";
13
+ import { fakeProcess as fakeEncoder, startRunOn } from "./helpers/encode-run.js";
14
+
15
+ /**
16
+ * Whether anything of this session is encoding.
17
+ *
18
+ * A session holds a SET of runs, so the question is about the set and not about
19
+ * a field: a run told to stop is not encoding, whatever its process is still
20
+ * doing about the signal.
21
+ *
22
+ * @param {object} session
23
+ * @returns {boolean}
24
+ */
25
+ function encoding(session) {
26
+ return [...(session?.runs ?? [])].some((run) => run.isAlive);
27
+ }
28
+ import assert from "node:assert/strict";
29
+ import { SourceFile } from "../services/source/SourceFile.js";
30
+ import { Timeline } from "../services/output/Timeline.js";
31
+ import { mkdtemp, rm } from "node:fs/promises";
32
+ import os from "node:os";
33
+ import path from "node:path";
34
+ import { audioRenditionKey, HlsSessionManager } from "../services/hls-session-manager.js";
35
+ import { viewerOf } from "../services/viewer/Viewer.js";
36
+ import { fmp4Format } from "../services/segment-formats/fmp4.js";
37
+ import { Output } from "../services/output/Output.js";
38
+
39
+ const BASE_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
40
+ const SEGMENT_SECONDS = 4;
41
+ const FIRST = "viewer-one";
42
+ const SECOND = "viewer-two";
43
+
44
+ /**
45
+ * A session shaped like a live one, without the ffmpeg run behind it.
46
+ *
47
+ * @param {{ id: string, dirPath: string, audioTrackIndex?: number, transcodeAudio?: boolean }} params
48
+ * @returns {object}
49
+ */
50
+ function fakeSession({ id, dirPath, audioTrackIndex = 0, transcodeAudio = true }) {
51
+ return {
52
+ id,
53
+ dirPath,
54
+ // Where this file is cut, held by the file. A fixture that stated it
55
+ // on the session was describing what production no longer does.
56
+ timeline: new Timeline({
57
+ boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
58
+ cutGrid: "keyframe"
59
+ }),
60
+ state: "ready",
61
+ file: new SourceFile({ sourceKey: "torrent:abc", fileIndex: 0, name: "video.mkv" }).learn({ width: 1920, height: 1080 }),
62
+ // An ordinary session reads its own file, and its sound is inside it. The
63
+ // three differ only for a soundtrack shipped as a file of its own.
64
+ get inputFile() { return this.file; },
65
+ get audioFile() { return this.file; },
66
+ startedAt: Date.now(),
67
+ createEntryMs: Date.now(),
68
+ lastAccessedAt: Date.now(),
69
+ ffmpeg: null,
70
+ lastError: "",
71
+ consumers: new Set(),
72
+ viewers: new Map(),
73
+
74
+ segmentFormat: fmp4Format,
75
+ transcodeVideo: false,
76
+ transcodeAudio,
77
+ audioTrackIndex,
78
+ audioSourceTrackIndex: audioTrackIndex,
79
+ // The shape this output is encoded AS, decided once for the output.
80
+ output: new Output({
81
+ encodeWidth: 0,
82
+ encodeHeight: 0,
83
+ outputFps: 24,
84
+ softwarePreset: null,
85
+ applyTonemap: false
86
+ }),
87
+ encodeRunGeneration: 0,
88
+ encodeStartIndex: 0,
89
+ waitEpoch: 0,
90
+ useSyntheticPlaylist: true,
91
+ playlistText: "#EXTM3U\n",
92
+ segmentCount: 100,
93
+ progress: { state: "running", processedSeconds: 0, startPositionSeconds: 0, speed: "1.0x" }
94
+ };
95
+ }
96
+
97
+
98
+ /**
99
+ * A base picture serving two viewers, with its audio published separately and
100
+ * every rendition created by a stub instead of an encoder.
101
+ *
102
+ * @returns {Promise<{ manager: HlsSessionManager, base: object, dirPath: string, renditions: Map<string, object> }>}
103
+ */
104
+ async function pictureWithTwoViewers() {
105
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "two-viewers-"));
106
+ const manager = new HlsSessionManager({
107
+ enabled: true,
108
+ ffmpegBin: "ffmpeg",
109
+ localBindHost: "127.0.0.1",
110
+ localPort: 9090
111
+ });
112
+ const base = fakeSession({ id: BASE_ID, dirPath });
113
+ base.audioSeparate = true;
114
+ base.consumers = new Set([FIRST, SECOND]);
115
+ // Both viewers are watching the picture, which is what keeps their choices
116
+ // alive; a viewer whose head has expired holds no encoder.
117
+ viewerOf(base, FIRST).head = { segment: 3, seconds: 12, at: Date.now() };
118
+ viewerOf(base, SECOND).head = { segment: 3, seconds: 12, at: Date.now() };
119
+ viewerOf(base, FIRST).audio = { trackIndex: 0, transcode: true };
120
+ viewerOf(base, SECOND).audio = { trackIndex: 1, transcode: true };
121
+ manager.sessionsById.set(BASE_ID, base);
122
+ manager.getCachedAudioTracks = () => [
123
+ { index: 0, language: "rus", title: "Дубляж", isDefault: true, fileIndex: 0, sourceTrackIndex: 0 },
124
+ { index: 1, language: "eng", title: "", isDefault: false, fileIndex: 0, sourceTrackIndex: 1 }
125
+ ];
126
+ manager.getCachedMediaInfo = () => ({ height: 1080, width: 1920, durationSeconds: 400 });
127
+
128
+ /** @type {Map<string, object>} */
129
+ const renditions = new Map();
130
+ manager.createOrGetSession = async (params) => {
131
+ const key = audioRenditionKey(params.audioTrackIndex, params.transcodeAudio);
132
+ const existing = renditions.get(key);
133
+ if (existing) {
134
+ return existing;
135
+ }
136
+ const rendition = fakeSession({
137
+ id: `rendition-${key}`,
138
+ dirPath,
139
+ audioTrackIndex: params.audioTrackIndex,
140
+ transcodeAudio: params.transcodeAudio
141
+ });
142
+ rendition.audioOnly = true;
143
+ startRunOn(rendition, { process: fakeEncoder() });
144
+ manager.sessionsById.set(rendition.id, rendition);
145
+ renditions.set(key, rendition);
146
+ return rendition;
147
+ };
148
+ return { manager, base, dirPath, renditions };
149
+ }
150
+
151
+ test("one viewer fetching their soundtrack does not stop the other viewer's", async (t) => {
152
+ const { manager, renditions, dirPath } = await pictureWithTwoViewers();
153
+ t.after(async () => {
154
+ await manager.disposeAll();
155
+ await rm(dirPath, { recursive: true, force: true });
156
+ });
157
+
158
+ const first = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
159
+ const second = await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00003.mp4", SECOND);
160
+
161
+ assert.notEqual(first.sessionId, second.sessionId, "two soundtracks are two encodes");
162
+ for (const [key, rendition] of renditions) {
163
+ assert.ok([...rendition.runs][0]?.process, `the encoder of ${key} is still running`);
164
+ assert.deepEqual([...rendition.runs][0].process.signals, [], `nothing signalled ${key}`);
165
+ }
166
+
167
+ // And it holds under the traffic that actually happens: they alternate.
168
+ await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00004.mp4", FIRST);
169
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", SECOND);
170
+ for (const [key, rendition] of renditions) {
171
+ assert.deepEqual([...rendition.runs][0]?.process?.signals ?? [], [], `nothing signalled ${key} on the second round`);
172
+ }
173
+ });
174
+
175
+ test("a soundtrack nobody is listening to any more is stopped", async (t) => {
176
+ const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
177
+ t.after(async () => {
178
+ await manager.disposeAll();
179
+ await rm(dirPath, { recursive: true, force: true });
180
+ });
181
+ // One viewer only, so what they leave is left for nobody. This is the case
182
+ // the stop exists for: an encoder AND a reader holding pieces of the torrent.
183
+ base.consumers = new Set([FIRST]);
184
+ base.viewers.delete(SECOND);
185
+ base.viewers.delete(SECOND);
186
+
187
+ await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
188
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", FIRST);
189
+
190
+ const left = renditions.get(audioRenditionKey(0, true));
191
+ const moved = renditions.get(audioRenditionKey(1, true));
192
+ assert.equal(encoding(left), false, "the track the viewer left is not encoding for anybody");
193
+ assert.ok(encoding(moved), "the track they moved to is");
194
+ });
195
+
196
+ test("each viewer's browser decides for itself whether its soundtrack is re-encoded", async (t) => {
197
+ const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
198
+ t.after(async () => {
199
+ await manager.disposeAll();
200
+ await rm(dirPath, { recursive: true, force: true });
201
+ });
202
+ // The same track, two browsers: one can decode it as it stands, the other
203
+ // cannot. Answering both from the session's own flag would leave the second
204
+ // viewer with silence.
205
+ viewerOf(base, FIRST).audio = { trackIndex: 0, transcode: false };
206
+ viewerOf(base, SECOND).audio = { trackIndex: 0, transcode: true };
207
+
208
+ const copied = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
209
+ const encoded = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", SECOND);
210
+
211
+ assert.notEqual(copied.sessionId, encoded.sessionId);
212
+ assert.equal(renditions.get(audioRenditionKey(0, false)).transcodeAudio, false);
213
+ assert.equal(renditions.get(audioRenditionKey(0, true)).transcodeAudio, true);
214
+ // Both are wanted, so neither is stopped.
215
+ assert.ok(encoding(renditions.get(audioRenditionKey(0, false))));
216
+ assert.ok(encoding(renditions.get(audioRenditionKey(0, true))));
217
+ });
218
+
219
+ test("the master marks each viewer's own soundtrack as the default one", async (t) => {
220
+ const { manager, dirPath } = await pictureWithTwoViewers();
221
+ t.after(async () => {
222
+ await manager.disposeAll();
223
+ await rm(dirPath, { recursive: true, force: true });
224
+ });
225
+
226
+ const forFirst = manager.buildMasterPlaylist(BASE_ID, FIRST);
227
+ const forSecond = manager.buildMasterPlaylist(BASE_ID, SECOND);
228
+
229
+ const defaultsOf = (master) =>
230
+ [...master.matchAll(/^#EXT-X-MEDIA:.*?NAME="([^"]+)".*?DEFAULT=(YES|NO)/gm)]
231
+ .filter((match) => match[2] === "YES")
232
+ .map((match) => match[1]);
233
+ assert.deepEqual(defaultsOf(forFirst), ["Дубляж"]);
234
+ assert.deepEqual(defaultsOf(forSecond).length, 1);
235
+ assert.notDeepEqual(defaultsOf(forFirst), defaultsOf(forSecond));
236
+ });
237
+
238
+ test("one viewer changing quality does not take the other off their step", async (t) => {
239
+ const { manager, base, dirPath } = await pictureWithTwoViewers();
240
+ t.after(async () => {
241
+ await manager.disposeAll();
242
+ await rm(dirPath, { recursive: true, force: true });
243
+ });
244
+ /** @type {Map<number, object>} */
245
+ const variants = new Map();
246
+ manager.createOrGetSession = async (params) => {
247
+ const height = params.targetHeight;
248
+ const existing = variants.get(height);
249
+ if (existing) {
250
+ return existing;
251
+ }
252
+ const variant = fakeSession({ id: `variant-${height}`, dirPath });
253
+ variant.transcodeVideo = true;
254
+ variant.output.encodeHeight = height;
255
+ variant.variantHeight = height;
256
+ variant.isStep = true;
257
+ variant.file = base.file;
258
+ startRunOn(variant, { process: fakeEncoder() });
259
+ manager.sessionsById.set(variant.id, variant);
260
+ variants.set(height, variant);
261
+ return variant;
262
+ };
263
+
264
+ await manager.resolveVariantFile(BASE_ID, 720, "segment-00003.mp4", FIRST);
265
+ await manager.resolveVariantFile(BASE_ID, 540, "segment-00003.mp4", SECOND);
266
+ // Both viewers go on watching their own step, which is what a player does
267
+ // every few seconds.
268
+ await manager.resolveVariantFile(BASE_ID, 720, "segment-00004.mp4", FIRST);
269
+ await manager.resolveVariantFile(BASE_ID, 540, "segment-00004.mp4", SECOND);
270
+
271
+ assert.ok(encoding(variants.get(720)), "the first viewer's step is still encoding");
272
+ assert.ok(encoding(variants.get(540)), "and so is the second viewer's");
273
+
274
+ // Now the first viewer steps down. Theirs is left for nobody and stops; the
275
+ // other viewer's is untouched.
276
+ await manager.resolveVariantFile(BASE_ID, 480, "segment-00005.mp4", FIRST);
277
+
278
+ assert.equal(encoding(variants.get(720)), false, "the step nobody is on stops");
279
+ assert.ok(encoding(variants.get(540)), "the step the other viewer is watching does not");
280
+ assert.ok(encoding(variants.get(480)), "and the one they moved to is encoding");
281
+ });
282
+
283
+ test("a step somebody is watching is never withdrawn from the offer", async (t) => {
284
+ const { manager, base, dirPath } = await pictureWithTwoViewers();
285
+ t.after(async () => {
286
+ await manager.disposeAll();
287
+ await rm(dirPath, { recursive: true, force: true });
288
+ });
289
+ // A host that can re-encode 240p and nothing above it — the shape of the
290
+ // field case of 2026-08-15.
291
+ base.output.encodeHeight = 1080;
292
+ base.variantHeight = 1080;
293
+ manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 12_000_000 }];
294
+ manager.decodeCostModel = { pixelTerm: 0.00793, bitrateTerm: 0, constantTerm: 0 };
295
+ // 1080p24 at 8 Mbit/s, stated as the file's own facts — what decoding costs
296
+ // is derived from them.
297
+ base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 8000 });
298
+
299
+ const variant = fakeSession({ id: "variant-720", dirPath });
300
+ variant.transcodeVideo = true;
301
+ variant.output.encodeHeight = 720;
302
+ variant.variantHeight = 720;
303
+ // One file, two sessions of it.
304
+ variant.file = base.file;
305
+ variant.isStep = true;
306
+ variant.file = base.file;
307
+ manager.sessionsById.set(variant.id, variant);
308
+ base.file.stepHeights.set(720, 720);
309
+
310
+ // Nobody on it: measured below realtime, it is withdrawn. This half is the
311
+ // control — without it the other half proves nothing.
312
+ const withoutAViewer = manager.offeredHeights(base);
313
+ assert.ok(
314
+ !withoutAViewer.includes(720),
315
+ `a step nobody is on and that cannot keep up is withdrawn: ${withoutAViewer.join(" ")}`
316
+ );
317
+
318
+ viewerOf(base, SECOND).activeVariantId = variant.id;
319
+ const withAViewer = manager.offeredHeights(base);
320
+
321
+ assert.ok(
322
+ withAViewer.includes(720),
323
+ `a step on somebody's screen stays offered, whatever it is measured at: ${withAViewer.join(" ")}`
324
+ );
325
+ });
326
+
327
+ test("a viewer whose picture has gone quiet holds no soundtrack encoder", async (t) => {
328
+ const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
329
+ t.after(async () => {
330
+ await manager.disposeAll();
331
+ await rm(dirPath, { recursive: true, force: true });
332
+ });
333
+ await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
334
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00003.mp4", SECOND);
335
+ // The second viewer's tab is gone. Nothing releases the session when a
336
+ // channel closes (roadmap item 54), so what expires is their head on the
337
+ // picture — and with it their claim on an encoder.
338
+ base.viewers.delete(SECOND);
339
+
340
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", FIRST);
341
+
342
+ assert.equal(
343
+ encoding(renditions.get(audioRenditionKey(0, true))),
344
+ false,
345
+ "the first viewer moved on, so their old track is stopped"
346
+ );
347
+ });
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @file The picture's facts, from the two readings that state them.
3
+ *
4
+ * Audio and subtitles have had this reconciliation since their flags were first
5
+ * read from the file. Video never did: every figure the encode is planned from
6
+ * came from ffmpeg's `-i` banner alone, and the `VideoTrack` the container
7
+ * declares was read and then used for nothing but a line in the log — so a file
8
+ * that states its bit depth or its HDR signalling, against a probe that does
9
+ * not print them, disagreed with nobody watching.
10
+ *
11
+ * What each check pins is WHICH reading answers, and why: the size and the
12
+ * frame rate are what the decoder will produce, so the probe answers; the bit
13
+ * depth and the HDR signalling are the file saying how its samples are to be
14
+ * read, so the container answers.
15
+ */
16
+
17
+ import test from "node:test";
18
+ import assert from "node:assert/strict";
19
+
20
+ import { Container } from "../services/container/Container.js";
21
+
22
+ const banner = (fields) => ({ width: null, height: null, fps: null, isHdr: false, bitDepth: null, ...fields });
23
+
24
+ test("with no container reading the probe answers for everything", () => {
25
+ const facts = Container.mergeVideoFacts(
26
+ banner({ width: 1920, height: 1080, fps: 23.976, isHdr: true, bitDepth: 10 }),
27
+ null
28
+ );
29
+ assert.equal(facts.width, 1920);
30
+ assert.equal(facts.height, 1080);
31
+ assert.equal(facts.fps, 23.976);
32
+ assert.equal(facts.isHdr, true);
33
+ assert.equal(facts.bitDepth, 10);
34
+ assert.deepEqual(facts.disagreements, []);
35
+ });
36
+
37
+ test("the size and the frame rate are the probe's, because that is what will be decoded", () => {
38
+ const facts = Container.mergeVideoFacts(
39
+ banner({ width: 1920, height: 1080, fps: 24 }),
40
+ { width: 1440, height: 1080, fps: 25, displayWidth: 1920, displayHeight: 1080 }
41
+ );
42
+ assert.equal(facts.width, 1920, "the ladder and the scale filter are sized to the decoded frame");
43
+ assert.equal(facts.height, 1080);
44
+ assert.equal(facts.fps, 24);
45
+ });
46
+
47
+ test("the bit depth and the HDR signalling are the file's, because the file states them", () => {
48
+ // A ten-bit HEVC whose probe printed neither: this is the case that decides
49
+ // whether tone mapping runs and how the decode cost is priced.
50
+ const facts = Container.mergeVideoFacts(
51
+ banner({ width: 3840, height: 2160, fps: 24 }),
52
+ { width: 3840, height: 2160, bitDepth: 10, isHdr: true }
53
+ );
54
+ assert.equal(facts.bitDepth, 10);
55
+ assert.equal(facts.isHdr, true);
56
+ assert.deepEqual(facts.disagreements, [], "one side saying nothing is not a disagreement");
57
+ });
58
+
59
+ test("a field only the probe states is still answered", () => {
60
+ const facts = Container.mergeVideoFacts(
61
+ banner({ width: 1280, height: 720, fps: 30, bitDepth: 8 }),
62
+ { width: null, height: null, fps: null, bitDepth: null }
63
+ );
64
+ assert.equal(facts.width, 1280);
65
+ assert.equal(facts.bitDepth, 8);
66
+ });
67
+
68
+ test("a real disagreement is reported, with both values and which is which", () => {
69
+ const facts = Container.mergeVideoFacts(
70
+ banner({ width: 1920, height: 1080, bitDepth: 8, isHdr: false }),
71
+ { width: 1280, height: 720, bitDepth: 10, isHdr: true }
72
+ );
73
+ assert.equal(facts.disagreements.length, 3);
74
+ assert.ok(facts.disagreements.some((line) => /width 1280 in the container against 1920 in the probe/.test(line)));
75
+ assert.ok(facts.disagreements.some((line) => /bit depth 10 in the container against 8 in the probe/.test(line)));
76
+ // HDR is not among them, and cannot be: see `mergeVideoFacts`.
77
+ assert.ok(!facts.disagreements.some((line) => /HDR/.test(line)));
78
+ // And the rule still decides: the probe for the size, the file for the rest.
79
+ assert.equal(facts.width, 1920);
80
+ assert.equal(facts.bitDepth, 10);
81
+ assert.equal(facts.isHdr, true);
82
+ });
83
+
84
+ test("the display size is the container's alone — the probe has no such field", () => {
85
+ const facts = Container.mergeVideoFacts(
86
+ banner({ width: 1440, height: 1080 }),
87
+ { width: 1440, height: 1080, displayWidth: 1920, displayHeight: 1080 }
88
+ );
89
+ assert.equal(facts.displayWidth, 1920);
90
+ assert.equal(facts.displayHeight, 1080);
91
+ });
92
+
93
+ test("zero and nonsense are not values", () => {
94
+ const facts = Container.mergeVideoFacts(
95
+ banner({ width: 0, height: 0, fps: 0, bitDepth: 0 }),
96
+ { width: 1920, height: 1080, fps: 24, bitDepth: 8 }
97
+ );
98
+ assert.equal(facts.width, 1920, "a probe that printed nothing does not outrank a file that speaks");
99
+ assert.equal(facts.fps, 24);
100
+ assert.equal(facts.bitDepth, 8);
101
+ assert.deepEqual(facts.disagreements, []);
102
+ });