@torrent-tv/proxy 2.80.19 → 2.81.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 (58) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +1 -1
  3. package/research/double-spawn-2026-09-10.md +171 -0
  4. package/services/disk/DiskSpace.js +146 -0
  5. package/services/disk/wire.js +60 -0
  6. package/services/encode/EncodeRun.js +25 -3
  7. package/services/encode/SegmentStore.js +137 -9
  8. package/services/hls-session-manager.js +26 -45
  9. package/services/orchestrators/EncodeOrchestrator.js +4 -1
  10. package/services/piece-store/allowance.js +107 -0
  11. package/services/piece-store/piece-disk-store.js +365 -0
  12. package/services/piece-store/shared-piece-store.js +1549 -1535
  13. package/services/torrent-worker/client.js +32 -0
  14. package/services/torrent-worker/pool-adapter.js +15 -0
  15. package/services/torrent-worker/protocol.js +9 -0
  16. package/services/torrent-worker/worker.js +8 -1
  17. package/services/viewer/positions.js +48 -0
  18. package/test/audio-inventory.test.js +176 -176
  19. package/test/auto-quality-step.test.js +514 -514
  20. package/test/concurrent-cost.test.js +138 -138
  21. package/test/coverage-follows-the-disk.test.js +191 -191
  22. package/test/coverage-map.test.js +195 -195
  23. package/test/declared-tracks.test.js +35 -35
  24. package/test/disk-space.test.js +138 -0
  25. package/test/encode-orchestrator.test.js +0 -3
  26. package/test/encode-run.test.js +5 -12
  27. package/test/held-request-width.test.js +155 -155
  28. package/test/helpers/encode-run.js +2 -2
  29. package/test/matroska-blocks.test.js +0 -0
  30. package/test/matroska-cues-track.test.js +192 -192
  31. package/test/mp4-composition-times.test.js +0 -0
  32. package/test/mp4-subtitles.test.js +173 -173
  33. package/test/one-authority.test.js +281 -220
  34. package/test/orchestrator-wired.test.js +199 -199
  35. package/test/packet-witness-ring.test.js +236 -236
  36. package/test/packet-witness.test.js +148 -148
  37. package/test/piece-disk-store.test.js +267 -0
  38. package/test/piece-reader.test.js +4 -4
  39. package/test/piece-store-eviction.test.js +17 -17
  40. package/test/piece-store-reservations.test.js +20 -1
  41. package/test/piece-store-slow-disk.test.js +16 -1
  42. package/test/read-window.test.js +6 -6
  43. package/test/run-intervals.test.js +100 -100
  44. package/test/seek-landing.test.js +109 -109
  45. package/test/segment-store-eviction.test.js +232 -0
  46. package/test/segments-are-shared.test.js +1 -1
  47. package/test/shared-piece-store.test.js +12 -12
  48. package/test/sidecar-naming.test.js +142 -142
  49. package/test/subtitle-cue-framing.test.js +200 -200
  50. package/test/subtitle-cue-walk.test.js +369 -369
  51. package/test/subtitle-defaults.test.js +97 -97
  52. package/test/subtitle-track-numbering.test.js +370 -370
  53. package/test/tail-duplication.test.js +167 -167
  54. package/test/tracks-begin-together.test.js +195 -195
  55. package/test/two-viewers-one-picture.test.js +374 -374
  56. package/test/video-facts.test.js +102 -102
  57. package/test/wedge-certainty.test.js +131 -131
  58. package/services/piece-store/disk-tier.js +0 -151
@@ -1,374 +1,374 @@
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
- /**
29
- * Whether anybody is still watching this output.
30
- *
31
- * WHAT REPLACED "ITS ENCODER WAS KILLED HERE". Leaving an output is a fact
32
- * about a viewer; whether an encoder on it should go on running is the same
33
- * question as where encoders belong, and one party answers that — an output
34
- * with nobody on it has a priority map with nothing in it, and the plan stops
35
- * what is on it (`encode-plan.test.js`, "every encoder stops when nobody is
36
- * watching the output"; `priority-map-per-output.test.js` for the map).
37
- *
38
- * Answered here as well, the two fought: this class killed the run, and the
39
- * viewer's own move — which announces itself — had the plan start it again on
40
- * the very next pass, several times a second.
41
- *
42
- * @param {object} session
43
- * @returns {boolean}
44
- */
45
- function watched(session) {
46
- return [...(session?.viewers ?? new Map()).values()].length > 0;
47
- }
48
-
49
- import assert from "node:assert/strict";
50
- import { SourceFile } from "../services/source/SourceFile.js";
51
- import { Timeline } from "../services/output/Timeline.js";
52
- import { mkdtemp, rm } from "node:fs/promises";
53
- import os from "node:os";
54
- import path from "node:path";
55
- import { audioRenditionKey, HlsSessionManager } from "../services/hls-session-manager.js";
56
- import { viewerOf } from "../services/viewer/Viewer.js";
57
- import { fmp4Format } from "../services/segment-formats/fmp4.js";
58
- import { Output } from "../services/output/Output.js";
59
-
60
- const BASE_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
61
- const SEGMENT_SECONDS = 4;
62
- const FIRST = "viewer-one";
63
- const SECOND = "viewer-two";
64
-
65
- /**
66
- * A session shaped like a live one, without the ffmpeg run behind it.
67
- *
68
- * @param {{ id: string, dirPath: string, audioTrackIndex?: number, transcodeAudio?: boolean }} params
69
- * @returns {object}
70
- */
71
- function fakeSession({ id, dirPath, audioTrackIndex = 0, transcodeAudio = true }) {
72
- return {
73
- id,
74
- dirPath,
75
- // Where this file is cut, held by the file. A fixture that stated it
76
- // on the session was describing what production no longer does.
77
- timeline: new Timeline({
78
- boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
79
- cutGrid: "keyframe"
80
- }),
81
- state: "ready",
82
- file: new SourceFile({ sourceKey: "torrent:abc", fileIndex: 0, name: "video.mkv" }).learn({ width: 1920, height: 1080 }),
83
- // An ordinary session reads its own file, and its sound is inside it. The
84
- // three differ only for a soundtrack shipped as a file of its own.
85
- get inputFile() { return this.file; },
86
- get audioFile() { return this.file; },
87
- startedAt: Date.now(),
88
- createEntryMs: Date.now(),
89
- lastAccessedAt: Date.now(),
90
- ffmpeg: null,
91
- lastError: "",
92
- consumers: new Set(),
93
- viewers: new Map(),
94
-
95
- segmentFormat: fmp4Format,
96
- transcodeVideo: false,
97
- transcodeAudio,
98
- audioTrackIndex,
99
- audioSourceTrackIndex: audioTrackIndex,
100
- // The shape this output is encoded AS, decided once for the output.
101
- output: new Output({
102
- encodeWidth: 0,
103
- encodeHeight: 0,
104
- outputFps: 24,
105
- softwarePreset: null,
106
- applyTonemap: false
107
- }),
108
- encodeRunGeneration: 0,
109
- encodeStartIndex: 0,
110
- waitEpoch: 0,
111
- useSyntheticPlaylist: true,
112
- playlistText: "#EXTM3U\n",
113
- segmentCount: 100,
114
- progress: { state: "running", processedSeconds: 0, startPositionSeconds: 0, speed: "1.0x" }
115
- };
116
- }
117
-
118
-
119
- /**
120
- * A base picture serving two viewers, with its audio published separately and
121
- * every rendition created by a stub instead of an encoder.
122
- *
123
- * @returns {Promise<{ manager: HlsSessionManager, base: object, dirPath: string, renditions: Map<string, object> }>}
124
- */
125
- async function pictureWithTwoViewers() {
126
- const dirPath = await mkdtemp(path.join(os.tmpdir(), "two-viewers-"));
127
- const manager = new HlsSessionManager({
128
- enabled: true,
129
- ffmpegBin: "ffmpeg",
130
- localBindHost: "127.0.0.1",
131
- localPort: 9090
132
- });
133
- const base = fakeSession({ id: BASE_ID, dirPath });
134
- base.audioSeparate = true;
135
- base.consumers = new Set([FIRST, SECOND]);
136
- // Both viewers are watching the picture, which is what keeps their choices
137
- // alive; a viewer whose head has expired holds no encoder.
138
- viewerOf(base, FIRST).position = { segment: 3, seconds: 12, at: Date.now() };
139
- viewerOf(base, SECOND).position = { segment: 3, seconds: 12, at: Date.now() };
140
- viewerOf(base, FIRST).audio = { trackIndex: 0, transcode: true };
141
- viewerOf(base, SECOND).audio = { trackIndex: 1, transcode: true };
142
- manager.sessionsById.set(BASE_ID, base);
143
- manager.getCachedAudioTracks = () => [
144
- { index: 0, language: "rus", title: "Дубляж", isDefault: true, fileIndex: 0, sourceTrackIndex: 0 },
145
- { index: 1, language: "eng", title: "", isDefault: false, fileIndex: 0, sourceTrackIndex: 1 }
146
- ];
147
- manager.getCachedMediaInfo = () => ({ height: 1080, width: 1920, durationSeconds: 400 });
148
-
149
- /** @type {Map<string, object>} */
150
- const renditions = new Map();
151
- manager.createOrGetSession = async (params) => {
152
- const key = audioRenditionKey(params.audioTrackIndex, params.transcodeAudio);
153
- const existing = renditions.get(key);
154
- if (existing) {
155
- return existing;
156
- }
157
- const rendition = fakeSession({
158
- id: `rendition-${key}`,
159
- dirPath,
160
- audioTrackIndex: params.audioTrackIndex,
161
- transcodeAudio: params.transcodeAudio
162
- });
163
- rendition.audioOnly = true;
164
- startRunOn(rendition, { process: fakeEncoder() });
165
- manager.sessionsById.set(rendition.id, rendition);
166
- renditions.set(key, rendition);
167
- return rendition;
168
- };
169
- return { manager, base, dirPath, renditions };
170
- }
171
-
172
- test("one viewer fetching their soundtrack does not stop the other viewer's", async (t) => {
173
- const { manager, renditions, dirPath } = await pictureWithTwoViewers();
174
- t.after(async () => {
175
- await manager.disposeAll();
176
- await rm(dirPath, { recursive: true, force: true });
177
- });
178
-
179
- const first = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
180
- const second = await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00003.mp4", SECOND);
181
-
182
- assert.notEqual(first.sessionId, second.sessionId, "two soundtracks are two encodes");
183
- for (const [key, rendition] of renditions) {
184
- assert.ok([...rendition.runs][0]?.process, `the encoder of ${key} is still running`);
185
- assert.deepEqual([...rendition.runs][0].process.signals, [], `nothing signalled ${key}`);
186
- }
187
-
188
- // And it holds under the traffic that actually happens: they alternate.
189
- await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00004.mp4", FIRST);
190
- await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", SECOND);
191
- for (const [key, rendition] of renditions) {
192
- assert.deepEqual([...rendition.runs][0]?.process?.signals ?? [], [], `nothing signalled ${key} on the second round`);
193
- }
194
- });
195
-
196
- test("a soundtrack nobody is listening to any more is let go of", 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
- // One viewer only, so what they leave is left for nobody. This is the case
203
- // the stop exists for: an encoder AND a reader holding pieces of the torrent.
204
- base.consumers = new Set([FIRST]);
205
- base.viewers.delete(SECOND);
206
- base.viewers.delete(SECOND);
207
-
208
- await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
209
- await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", FIRST);
210
-
211
- const left = renditions.get(audioRenditionKey(0, true));
212
- const moved = renditions.get(audioRenditionKey(1, true));
213
- assert.equal(watched(left), false, "the track the viewer left is nobody's now");
214
- assert.ok(watched(moved), "and the track they moved to is theirs");
215
- assert.deepEqual(
216
- [...left.runs][0]?.process?.signals ?? [],
217
- [],
218
- "and it is not killed from here, which is what the plan then undid"
219
- );
220
- });
221
-
222
- test("each viewer's browser decides for itself whether its soundtrack is re-encoded", async (t) => {
223
- const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
224
- t.after(async () => {
225
- await manager.disposeAll();
226
- await rm(dirPath, { recursive: true, force: true });
227
- });
228
- // The same track, two browsers: one can decode it as it stands, the other
229
- // cannot. Answering both from the session's own flag would leave the second
230
- // viewer with silence.
231
- viewerOf(base, FIRST).audio = { trackIndex: 0, transcode: false };
232
- viewerOf(base, SECOND).audio = { trackIndex: 0, transcode: true };
233
-
234
- const copied = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
235
- const encoded = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", SECOND);
236
-
237
- assert.notEqual(copied.sessionId, encoded.sessionId);
238
- assert.equal(renditions.get(audioRenditionKey(0, false)).transcodeAudio, false);
239
- assert.equal(renditions.get(audioRenditionKey(0, true)).transcodeAudio, true);
240
- // Both are wanted, so neither is stopped.
241
- assert.ok(encoding(renditions.get(audioRenditionKey(0, false))));
242
- assert.ok(encoding(renditions.get(audioRenditionKey(0, true))));
243
- });
244
-
245
- test("the master marks each viewer's own soundtrack as the default one", async (t) => {
246
- const { manager, dirPath } = await pictureWithTwoViewers();
247
- t.after(async () => {
248
- await manager.disposeAll();
249
- await rm(dirPath, { recursive: true, force: true });
250
- });
251
-
252
- const forFirst = manager.buildMasterPlaylist(BASE_ID, FIRST);
253
- const forSecond = manager.buildMasterPlaylist(BASE_ID, SECOND);
254
-
255
- const defaultsOf = (master) =>
256
- [...master.matchAll(/^#EXT-X-MEDIA:.*?NAME="([^"]+)".*?DEFAULT=(YES|NO)/gm)]
257
- .filter((match) => match[2] === "YES")
258
- .map((match) => match[1]);
259
- assert.deepEqual(defaultsOf(forFirst), ["Дубляж"]);
260
- assert.deepEqual(defaultsOf(forSecond).length, 1);
261
- assert.notDeepEqual(defaultsOf(forFirst), defaultsOf(forSecond));
262
- });
263
-
264
- test("one viewer changing quality does not take the other off their step", async (t) => {
265
- const { manager, base, dirPath } = await pictureWithTwoViewers();
266
- t.after(async () => {
267
- await manager.disposeAll();
268
- await rm(dirPath, { recursive: true, force: true });
269
- });
270
- /** @type {Map<number, object>} */
271
- const variants = new Map();
272
- manager.createOrGetSession = async (params) => {
273
- const height = params.targetHeight;
274
- const existing = variants.get(height);
275
- if (existing) {
276
- return existing;
277
- }
278
- const variant = fakeSession({ id: `variant-${height}`, dirPath });
279
- variant.transcodeVideo = true;
280
- variant.output.encodeHeight = height;
281
- variant.variantHeight = height;
282
- variant.isStep = true;
283
- variant.file = base.file;
284
- startRunOn(variant, { process: fakeEncoder() });
285
- manager.sessionsById.set(variant.id, variant);
286
- variants.set(height, variant);
287
- return variant;
288
- };
289
-
290
- await manager.resolveVariantFile(BASE_ID, 720, "segment-00003.mp4", FIRST);
291
- await manager.resolveVariantFile(BASE_ID, 540, "segment-00003.mp4", SECOND);
292
- // Both viewers go on watching their own step, which is what a player does
293
- // every few seconds.
294
- await manager.resolveVariantFile(BASE_ID, 720, "segment-00004.mp4", FIRST);
295
- await manager.resolveVariantFile(BASE_ID, 540, "segment-00004.mp4", SECOND);
296
-
297
- assert.ok(encoding(variants.get(720)), "the first viewer's step is still encoding");
298
- assert.ok(encoding(variants.get(540)), "and so is the second viewer's");
299
-
300
- // Now the first viewer steps down. Theirs is left for nobody and stops; the
301
- // other viewer's is untouched.
302
- await manager.resolveVariantFile(BASE_ID, 480, "segment-00005.mp4", FIRST);
303
-
304
- assert.equal(watched(variants.get(720)), false, "the step nobody is on is nobody's");
305
- assert.ok(watched(variants.get(540)), "the step the other viewer is watching stays theirs");
306
- assert.ok(watched(variants.get(480)), "and the one they moved to is now theirs");
307
- assert.ok(encoding(variants.get(540)), "and nothing here touched the other viewer's encoder");
308
- });
309
-
310
- test("a step somebody is watching is never withdrawn from the offer", async (t) => {
311
- const { manager, base, dirPath } = await pictureWithTwoViewers();
312
- t.after(async () => {
313
- await manager.disposeAll();
314
- await rm(dirPath, { recursive: true, force: true });
315
- });
316
- // A host that can re-encode 240p and nothing above it — the shape of the
317
- // field case of 2026-08-15.
318
- base.output.encodeHeight = 1080;
319
- base.variantHeight = 1080;
320
- manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 12_000_000 }];
321
- manager.decodeCostModel = { pixelTerm: 0.00793, bitrateTerm: 0, constantTerm: 0 };
322
- // 1080p24 at 8 Mbit/s, stated as the file's own facts — what decoding costs
323
- // is derived from them.
324
- base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 8000 });
325
-
326
- const variant = fakeSession({ id: "variant-720", dirPath });
327
- variant.transcodeVideo = true;
328
- variant.output.encodeHeight = 720;
329
- variant.variantHeight = 720;
330
- // One file, two sessions of it.
331
- variant.file = base.file;
332
- variant.isStep = true;
333
- variant.file = base.file;
334
- manager.sessionsById.set(variant.id, variant);
335
- base.file.stepHeights.set(720, 720);
336
-
337
- // Nobody on it: measured below realtime, it is withdrawn. This half is the
338
- // control — without it the other half proves nothing.
339
- const withoutAViewer = manager.offeredHeights(base);
340
- assert.ok(
341
- !withoutAViewer.includes(720),
342
- `a step nobody is on and that cannot keep up is withdrawn: ${withoutAViewer.join(" ")}`
343
- );
344
-
345
- viewerOf(base, SECOND).activeVariantId = variant.id;
346
- const withAViewer = manager.offeredHeights(base);
347
-
348
- assert.ok(
349
- withAViewer.includes(720),
350
- `a step on somebody's screen stays offered, whatever it is measured at: ${withAViewer.join(" ")}`
351
- );
352
- });
353
-
354
- test("a viewer whose picture has gone quiet holds no soundtrack encoder", async (t) => {
355
- const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
356
- t.after(async () => {
357
- await manager.disposeAll();
358
- await rm(dirPath, { recursive: true, force: true });
359
- });
360
- await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
361
- await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00003.mp4", SECOND);
362
- // The second viewer's tab is gone. Nothing releases the session when a
363
- // channel closes (roadmap item 54), so what expires is their head on the
364
- // picture — and with it their claim on an encoder.
365
- base.viewers.delete(SECOND);
366
-
367
- await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", FIRST);
368
-
369
- assert.equal(
370
- watched(renditions.get(audioRenditionKey(0, true))),
371
- false,
372
- "the first viewer moved on, so their old track is nobody's"
373
- );
374
- });
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
+ /**
29
+ * Whether anybody is still watching this output.
30
+ *
31
+ * WHAT REPLACED "ITS ENCODER WAS KILLED HERE". Leaving an output is a fact
32
+ * about a viewer; whether an encoder on it should go on running is the same
33
+ * question as where encoders belong, and one party answers that — an output
34
+ * with nobody on it has a priority map with nothing in it, and the plan stops
35
+ * what is on it (`encode-plan.test.js`, "every encoder stops when nobody is
36
+ * watching the output"; `priority-map-per-output.test.js` for the map).
37
+ *
38
+ * Answered here as well, the two fought: this class killed the run, and the
39
+ * viewer's own move — which announces itself — had the plan start it again on
40
+ * the very next pass, several times a second.
41
+ *
42
+ * @param {object} session
43
+ * @returns {boolean}
44
+ */
45
+ function watched(session) {
46
+ return [...(session?.viewers ?? new Map()).values()].length > 0;
47
+ }
48
+
49
+ import assert from "node:assert/strict";
50
+ import { SourceFile } from "../services/source/SourceFile.js";
51
+ import { Timeline } from "../services/output/Timeline.js";
52
+ import { mkdtemp, rm } from "node:fs/promises";
53
+ import os from "node:os";
54
+ import path from "node:path";
55
+ import { audioRenditionKey, HlsSessionManager } from "../services/hls-session-manager.js";
56
+ import { viewerOf } from "../services/viewer/Viewer.js";
57
+ import { fmp4Format } from "../services/segment-formats/fmp4.js";
58
+ import { Output } from "../services/output/Output.js";
59
+
60
+ const BASE_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
61
+ const SEGMENT_SECONDS = 4;
62
+ const FIRST = "viewer-one";
63
+ const SECOND = "viewer-two";
64
+
65
+ /**
66
+ * A session shaped like a live one, without the ffmpeg run behind it.
67
+ *
68
+ * @param {{ id: string, dirPath: string, audioTrackIndex?: number, transcodeAudio?: boolean }} params
69
+ * @returns {object}
70
+ */
71
+ function fakeSession({ id, dirPath, audioTrackIndex = 0, transcodeAudio = true }) {
72
+ return {
73
+ id,
74
+ dirPath,
75
+ // Where this file is cut, held by the file. A fixture that stated it
76
+ // on the session was describing what production no longer does.
77
+ timeline: new Timeline({
78
+ boundaries: Array.from({ length: 101 }, (_, index) => index * SEGMENT_SECONDS),
79
+ cutGrid: "keyframe"
80
+ }),
81
+ state: "ready",
82
+ file: new SourceFile({ sourceKey: "torrent:abc", fileIndex: 0, name: "video.mkv" }).learn({ width: 1920, height: 1080 }),
83
+ // An ordinary session reads its own file, and its sound is inside it. The
84
+ // three differ only for a soundtrack shipped as a file of its own.
85
+ get inputFile() { return this.file; },
86
+ get audioFile() { return this.file; },
87
+ startedAt: Date.now(),
88
+ createEntryMs: Date.now(),
89
+ lastAccessedAt: Date.now(),
90
+ ffmpeg: null,
91
+ lastError: "",
92
+ consumers: new Set(),
93
+ viewers: new Map(),
94
+
95
+ segmentFormat: fmp4Format,
96
+ transcodeVideo: false,
97
+ transcodeAudio,
98
+ audioTrackIndex,
99
+ audioSourceTrackIndex: audioTrackIndex,
100
+ // The shape this output is encoded AS, decided once for the output.
101
+ output: new Output({
102
+ encodeWidth: 0,
103
+ encodeHeight: 0,
104
+ outputFps: 24,
105
+ softwarePreset: null,
106
+ applyTonemap: false
107
+ }),
108
+ encodeRunGeneration: 0,
109
+ encodeStartIndex: 0,
110
+ waitEpoch: 0,
111
+ useSyntheticPlaylist: true,
112
+ playlistText: "#EXTM3U\n",
113
+ segmentCount: 100,
114
+ progress: { state: "running", processedSeconds: 0, startPositionSeconds: 0, speed: "1.0x" }
115
+ };
116
+ }
117
+
118
+
119
+ /**
120
+ * A base picture serving two viewers, with its audio published separately and
121
+ * every rendition created by a stub instead of an encoder.
122
+ *
123
+ * @returns {Promise<{ manager: HlsSessionManager, base: object, dirPath: string, renditions: Map<string, object> }>}
124
+ */
125
+ async function pictureWithTwoViewers() {
126
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "two-viewers-"));
127
+ const manager = new HlsSessionManager({
128
+ enabled: true,
129
+ ffmpegBin: "ffmpeg",
130
+ localBindHost: "127.0.0.1",
131
+ localPort: 9090
132
+ });
133
+ const base = fakeSession({ id: BASE_ID, dirPath });
134
+ base.audioSeparate = true;
135
+ base.consumers = new Set([FIRST, SECOND]);
136
+ // Both viewers are watching the picture, which is what keeps their choices
137
+ // alive; a viewer whose head has expired holds no encoder.
138
+ viewerOf(base, FIRST).position = { segment: 3, seconds: 12, at: Date.now() };
139
+ viewerOf(base, SECOND).position = { segment: 3, seconds: 12, at: Date.now() };
140
+ viewerOf(base, FIRST).audio = { trackIndex: 0, transcode: true };
141
+ viewerOf(base, SECOND).audio = { trackIndex: 1, transcode: true };
142
+ manager.sessionsById.set(BASE_ID, base);
143
+ manager.getCachedAudioTracks = () => [
144
+ { index: 0, language: "rus", title: "Дубляж", isDefault: true, fileIndex: 0, sourceTrackIndex: 0 },
145
+ { index: 1, language: "eng", title: "", isDefault: false, fileIndex: 0, sourceTrackIndex: 1 }
146
+ ];
147
+ manager.getCachedMediaInfo = () => ({ height: 1080, width: 1920, durationSeconds: 400 });
148
+
149
+ /** @type {Map<string, object>} */
150
+ const renditions = new Map();
151
+ manager.createOrGetSession = async (params) => {
152
+ const key = audioRenditionKey(params.audioTrackIndex, params.transcodeAudio);
153
+ const existing = renditions.get(key);
154
+ if (existing) {
155
+ return existing;
156
+ }
157
+ const rendition = fakeSession({
158
+ id: `rendition-${key}`,
159
+ dirPath,
160
+ audioTrackIndex: params.audioTrackIndex,
161
+ transcodeAudio: params.transcodeAudio
162
+ });
163
+ rendition.audioOnly = true;
164
+ startRunOn(rendition, { process: fakeEncoder() });
165
+ manager.sessionsById.set(rendition.id, rendition);
166
+ renditions.set(key, rendition);
167
+ return rendition;
168
+ };
169
+ return { manager, base, dirPath, renditions };
170
+ }
171
+
172
+ test("one viewer fetching their soundtrack does not stop the other viewer's", async (t) => {
173
+ const { manager, renditions, dirPath } = await pictureWithTwoViewers();
174
+ t.after(async () => {
175
+ await manager.disposeAll();
176
+ await rm(dirPath, { recursive: true, force: true });
177
+ });
178
+
179
+ const first = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
180
+ const second = await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00003.mp4", SECOND);
181
+
182
+ assert.notEqual(first.sessionId, second.sessionId, "two soundtracks are two encodes");
183
+ for (const [key, rendition] of renditions) {
184
+ assert.ok([...rendition.runs][0]?.process, `the encoder of ${key} is still running`);
185
+ assert.deepEqual([...rendition.runs][0].process.signals, [], `nothing signalled ${key}`);
186
+ }
187
+
188
+ // And it holds under the traffic that actually happens: they alternate.
189
+ await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00004.mp4", FIRST);
190
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", SECOND);
191
+ for (const [key, rendition] of renditions) {
192
+ assert.deepEqual([...rendition.runs][0]?.process?.signals ?? [], [], `nothing signalled ${key} on the second round`);
193
+ }
194
+ });
195
+
196
+ test("a soundtrack nobody is listening to any more is let go of", 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
+ // One viewer only, so what they leave is left for nobody. This is the case
203
+ // the stop exists for: an encoder AND a reader holding pieces of the torrent.
204
+ base.consumers = new Set([FIRST]);
205
+ base.viewers.delete(SECOND);
206
+ base.viewers.delete(SECOND);
207
+
208
+ await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
209
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", FIRST);
210
+
211
+ const left = renditions.get(audioRenditionKey(0, true));
212
+ const moved = renditions.get(audioRenditionKey(1, true));
213
+ assert.equal(watched(left), false, "the track the viewer left is nobody's now");
214
+ assert.ok(watched(moved), "and the track they moved to is theirs");
215
+ assert.deepEqual(
216
+ [...left.runs][0]?.process?.signals ?? [],
217
+ [],
218
+ "and it is not killed from here, which is what the plan then undid"
219
+ );
220
+ });
221
+
222
+ test("each viewer's browser decides for itself whether its soundtrack is re-encoded", async (t) => {
223
+ const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
224
+ t.after(async () => {
225
+ await manager.disposeAll();
226
+ await rm(dirPath, { recursive: true, force: true });
227
+ });
228
+ // The same track, two browsers: one can decode it as it stands, the other
229
+ // cannot. Answering both from the session's own flag would leave the second
230
+ // viewer with silence.
231
+ viewerOf(base, FIRST).audio = { trackIndex: 0, transcode: false };
232
+ viewerOf(base, SECOND).audio = { trackIndex: 0, transcode: true };
233
+
234
+ const copied = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
235
+ const encoded = await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", SECOND);
236
+
237
+ assert.notEqual(copied.sessionId, encoded.sessionId);
238
+ assert.equal(renditions.get(audioRenditionKey(0, false)).transcodeAudio, false);
239
+ assert.equal(renditions.get(audioRenditionKey(0, true)).transcodeAudio, true);
240
+ // Both are wanted, so neither is stopped.
241
+ assert.ok(encoding(renditions.get(audioRenditionKey(0, false))));
242
+ assert.ok(encoding(renditions.get(audioRenditionKey(0, true))));
243
+ });
244
+
245
+ test("the master marks each viewer's own soundtrack as the default one", async (t) => {
246
+ const { manager, dirPath } = await pictureWithTwoViewers();
247
+ t.after(async () => {
248
+ await manager.disposeAll();
249
+ await rm(dirPath, { recursive: true, force: true });
250
+ });
251
+
252
+ const forFirst = manager.buildMasterPlaylist(BASE_ID, FIRST);
253
+ const forSecond = manager.buildMasterPlaylist(BASE_ID, SECOND);
254
+
255
+ const defaultsOf = (master) =>
256
+ [...master.matchAll(/^#EXT-X-MEDIA:.*?NAME="([^"]+)".*?DEFAULT=(YES|NO)/gm)]
257
+ .filter((match) => match[2] === "YES")
258
+ .map((match) => match[1]);
259
+ assert.deepEqual(defaultsOf(forFirst), ["Дубляж"]);
260
+ assert.deepEqual(defaultsOf(forSecond).length, 1);
261
+ assert.notDeepEqual(defaultsOf(forFirst), defaultsOf(forSecond));
262
+ });
263
+
264
+ test("one viewer changing quality does not take the other off their step", async (t) => {
265
+ const { manager, base, dirPath } = await pictureWithTwoViewers();
266
+ t.after(async () => {
267
+ await manager.disposeAll();
268
+ await rm(dirPath, { recursive: true, force: true });
269
+ });
270
+ /** @type {Map<number, object>} */
271
+ const variants = new Map();
272
+ manager.createOrGetSession = async (params) => {
273
+ const height = params.targetHeight;
274
+ const existing = variants.get(height);
275
+ if (existing) {
276
+ return existing;
277
+ }
278
+ const variant = fakeSession({ id: `variant-${height}`, dirPath });
279
+ variant.transcodeVideo = true;
280
+ variant.output.encodeHeight = height;
281
+ variant.variantHeight = height;
282
+ variant.isStep = true;
283
+ variant.file = base.file;
284
+ startRunOn(variant, { process: fakeEncoder() });
285
+ manager.sessionsById.set(variant.id, variant);
286
+ variants.set(height, variant);
287
+ return variant;
288
+ };
289
+
290
+ await manager.resolveVariantFile(BASE_ID, 720, "segment-00003.mp4", FIRST);
291
+ await manager.resolveVariantFile(BASE_ID, 540, "segment-00003.mp4", SECOND);
292
+ // Both viewers go on watching their own step, which is what a player does
293
+ // every few seconds.
294
+ await manager.resolveVariantFile(BASE_ID, 720, "segment-00004.mp4", FIRST);
295
+ await manager.resolveVariantFile(BASE_ID, 540, "segment-00004.mp4", SECOND);
296
+
297
+ assert.ok(encoding(variants.get(720)), "the first viewer's step is still encoding");
298
+ assert.ok(encoding(variants.get(540)), "and so is the second viewer's");
299
+
300
+ // Now the first viewer steps down. Theirs is left for nobody and stops; the
301
+ // other viewer's is untouched.
302
+ await manager.resolveVariantFile(BASE_ID, 480, "segment-00005.mp4", FIRST);
303
+
304
+ assert.equal(watched(variants.get(720)), false, "the step nobody is on is nobody's");
305
+ assert.ok(watched(variants.get(540)), "the step the other viewer is watching stays theirs");
306
+ assert.ok(watched(variants.get(480)), "and the one they moved to is now theirs");
307
+ assert.ok(encoding(variants.get(540)), "and nothing here touched the other viewer's encoder");
308
+ });
309
+
310
+ test("a step somebody is watching is never withdrawn from the offer", async (t) => {
311
+ const { manager, base, dirPath } = await pictureWithTwoViewers();
312
+ t.after(async () => {
313
+ await manager.disposeAll();
314
+ await rm(dirPath, { recursive: true, force: true });
315
+ });
316
+ // A host that can re-encode 240p and nothing above it — the shape of the
317
+ // field case of 2026-08-15.
318
+ base.output.encodeHeight = 1080;
319
+ base.variantHeight = 1080;
320
+ manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 12_000_000 }];
321
+ manager.decodeCostModel = { pixelTerm: 0.00793, bitrateTerm: 0, constantTerm: 0 };
322
+ // 1080p24 at 8 Mbit/s, stated as the file's own facts — what decoding costs
323
+ // is derived from them.
324
+ base.file.learn({ width: 1920, height: 1080, fps: 24, bitrateKbps: 8000 });
325
+
326
+ const variant = fakeSession({ id: "variant-720", dirPath });
327
+ variant.transcodeVideo = true;
328
+ variant.output.encodeHeight = 720;
329
+ variant.variantHeight = 720;
330
+ // One file, two sessions of it.
331
+ variant.file = base.file;
332
+ variant.isStep = true;
333
+ variant.file = base.file;
334
+ manager.sessionsById.set(variant.id, variant);
335
+ base.file.stepHeights.set(720, 720);
336
+
337
+ // Nobody on it: measured below realtime, it is withdrawn. This half is the
338
+ // control — without it the other half proves nothing.
339
+ const withoutAViewer = manager.offeredHeights(base);
340
+ assert.ok(
341
+ !withoutAViewer.includes(720),
342
+ `a step nobody is on and that cannot keep up is withdrawn: ${withoutAViewer.join(" ")}`
343
+ );
344
+
345
+ viewerOf(base, SECOND).activeVariantId = variant.id;
346
+ const withAViewer = manager.offeredHeights(base);
347
+
348
+ assert.ok(
349
+ withAViewer.includes(720),
350
+ `a step on somebody's screen stays offered, whatever it is measured at: ${withAViewer.join(" ")}`
351
+ );
352
+ });
353
+
354
+ test("a viewer whose picture has gone quiet holds no soundtrack encoder", async (t) => {
355
+ const { manager, base, renditions, dirPath } = await pictureWithTwoViewers();
356
+ t.after(async () => {
357
+ await manager.disposeAll();
358
+ await rm(dirPath, { recursive: true, force: true });
359
+ });
360
+ await manager.resolveAudioRenditionFile(BASE_ID, 0, "segment-00003.mp4", FIRST);
361
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00003.mp4", SECOND);
362
+ // The second viewer's tab is gone. Nothing releases the session when a
363
+ // channel closes (roadmap item 54), so what expires is their head on the
364
+ // picture — and with it their claim on an encoder.
365
+ base.viewers.delete(SECOND);
366
+
367
+ await manager.resolveAudioRenditionFile(BASE_ID, 1, "segment-00004.mp4", FIRST);
368
+
369
+ assert.equal(
370
+ watched(renditions.get(audioRenditionKey(0, true))),
371
+ false,
372
+ "the first viewer moved on, so their old track is nobody's"
373
+ );
374
+ });