@torrent-tv/proxy 2.89.3 → 2.89.4

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 (49) hide show
  1. package/AGENTS.md +338 -336
  2. package/CHANGELOG.md +12 -0
  3. package/docs/encode-architecture.md +55 -19
  4. package/docs/playback-start-forecast.md +13 -5
  5. package/docs/storage-architecture.md +6 -0
  6. package/package.json +1 -1
  7. package/routes/stream/get.js +38 -2
  8. package/server.js +748 -745
  9. package/services/encode/EncodeOrchestrator.js +24 -49
  10. package/services/encode/EncodePlan.js +5 -3
  11. package/services/encode/EncodeRun.js +80 -17
  12. package/services/encode/EncodeRuns.js +1339 -1239
  13. package/services/encode/Renditions.js +2 -1
  14. package/services/encode/RunClock.js +87 -0
  15. package/services/encode/RunProgress.js +1 -6
  16. package/services/encode/encoder-readings.js +26 -28
  17. package/services/encode/piece-completeness.js +46 -0
  18. package/services/encode/quality/EncodeCost.js +1043 -1167
  19. package/services/encode/quality/OutputQualityState.js +1 -5
  20. package/services/encode/quality/QualityController.js +213 -390
  21. package/services/encode/quality/link-budget.js +5 -17
  22. package/services/encode/run-inputs.js +13 -2
  23. package/services/server/SegmentServing.js +3 -1
  24. package/services/server/ViewerRequests.js +2 -7
  25. package/services/server/wire-outputs.js +12 -7
  26. package/services/storage/segment-store/SegmentStore.js +46 -29
  27. package/services/torrent/supply-margin.js +7 -5
  28. package/test/auto-quality-step.test.js +75 -29
  29. package/test/decode-cost.test.js +1 -1
  30. package/test/encode-cost.test.js +31 -39
  31. package/test/encode-orchestrator.test.js +15 -8
  32. package/test/encode-plan-viewers.test.js +34 -27
  33. package/test/encode-run.test.js +34 -6
  34. package/test/encoder-readings.test.js +48 -26
  35. package/test/helpers/encode-run.js +113 -9
  36. package/test/link-budget.test.js +4 -5
  37. package/test/manager-surface.test.js +1 -2
  38. package/test/orchestrator-wired.test.js +5 -4
  39. package/test/output-speed.test.js +0 -1
  40. package/test/piece-completeness.test.js +42 -0
  41. package/test/quality-offer.test.js +1 -3
  42. package/test/quality-variants.test.js +1 -1
  43. package/test/run-progress.test.js +2 -3
  44. package/test/same-height-switch.test.js +1 -2
  45. package/test/segment-store.test.js +15 -15
  46. package/test/stream-route.test.js +28 -0
  47. package/test/supply-margin.test.js +13 -0
  48. package/test/two-viewers-one-picture.test.js +1 -1
  49. package/test/viewer-outputs.test.js +1 -1
@@ -1,1239 +1,1339 @@
1
- /**
2
- * The encoders of this proxy, from the plan's decision to the end of the process.
3
- *
4
- * The plan (`EncodePlan`, through `EncodeOrchestrator`) decides where a run goes;
5
- * this builds it with the arguments its output needs, follows what it produces,
6
- * says how far it got, and accounts for how it ended. Nothing here decides where
7
- * an encoder should be.
8
- */
9
-
10
- import path from "node:path";
11
- import { spawn } from "node:child_process";
12
- import { contentionPenalty } from "./contention.js";
13
- import { ENCODE_RUN_STATE, liveRunsOf, runStateOf, wireState } from "./encode-run-state.js";
14
- import { ENCODE_EXIT } from "./encode-exit.js";
15
- import { EncodeRun } from "./EncodeRun.js";
16
- import { computeOutputDimensions } from "./args.js";
17
- import { buildRunCommand, trueStartOf } from "./run-command.js";
18
- import { SEGMENT_CUT_TIME_DELTA_SECONDS } from "./output/index.js";
19
-
20
- /**
21
- * @typedef {Object} SegmentFiles
22
- * @property {(address: string) => string} pathFor
23
- * @property {(address: string) => Buffer | null} initOf
24
- * @property {(address: string) => string} directoryFor
25
- * @property {(address: string, makingName: string, format: object) => string | null} publish
26
- */
27
- // How far the accounting of a backward restart looks for work about to be done
28
- // twice. It runs on the restart path and a session an hour in has thousands of
29
- // segments; the figure is for a comparison, not an inventory.
30
- const BACKWARD_RESTART_SCAN_SEGMENTS = 300;
31
- const PROGRESS_LOG_INTERVAL_MS = 5_000;
32
- /**
33
- * Format a seconds value as `HH:MM:SS`, or `"n/a"` if not finite.
34
- *
35
- * @param {number} seconds
36
- * @returns {string}
37
- */
38
- export function formatSeconds(seconds) {
39
- if (!Number.isFinite(seconds) || seconds < 0) {
40
- return "n/a";
41
- }
42
- const total = Math.floor(seconds);
43
- const hours = Math.floor(total / 3600);
44
- const minutes = Math.floor((total % 3600) / 60);
45
- const rest = total % 60;
46
- return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
47
- }
48
- /**
49
- * Where this session's encoding begins: the earliest number any live run of it
50
- * was given.
51
- *
52
- * @param {object[] | Set<object>} runs
53
- * @returns {number | null}
54
- */
55
- export function earliestRunStart(runs) {
56
- const live = liveRunsOf(runs);
57
- return live.length > 0 ? live[0].from : null;
58
- }
59
- /**
60
- * The live run of this session that was given this number, if any.
61
- *
62
- * A run with an explicit stretch owns the whole of it. One WITHOUT an end owns
63
- * only as far as it has actually got: claiming the rest of the film would make
64
- * it the owner of every number in front of it, including ones another run was
65
- * expressly given.
66
- *
67
- * @param {object[] | Set<object>} runs
68
- * @param {number} index
69
- * @returns {object | null}
70
- */
71
- function ownRunMaking(runs, index) {
72
- let answer = null;
73
- for (const run of liveRunsOf(runs)) {
74
- if (run.from > index) {
75
- break; // Ordered by start, so nothing further can hold this number.
76
- }
77
- if (Number.isInteger(run.to) && run.to >= run.from && index > run.to) {
78
- continue; // Its stretch ends before this number.
79
- }
80
- answer = run;
81
- }
82
- return answer;
83
- }
84
-
85
- /**
86
- * Whether an encoder run died because its INPUT went away, rather than because
87
- * of anything about the encode itself.
88
- *
89
- * These are the messages the read path and ffmpeg's HTTP client produce when
90
- * the torrent is gone, being re-added, or has no data for the range yet — all
91
- * of them temporary by nature: the source can be added again and the pieces
92
- * fetched again.
93
- *
94
- * @param {string} message
95
- * @returns {boolean}
96
- */
97
- export function isInputUnavailable(message) {
98
- const text = typeof message === "string" ? message : "";
99
- return (
100
- /Error reading HTTP response/i.test(text) ||
101
- /not found in (?:magnet|torrent):/i.test(text) ||
102
- /Unknown source/i.test(text) ||
103
- /is gone and cannot be re-added/i.test(text) ||
104
- /Read error at pos/i.test(text) ||
105
- /Server returned 5\d\d/i.test(text) ||
106
- /Input\/output error/i.test(text) ||
107
- /Connection reset by peer/i.test(text) ||
108
- /End of file/i.test(text)
109
- );
110
- }
111
-
112
- /**
113
- * The ffmpeg command as one readable line.
114
- *
115
- * Everything is shown as passed except the list of cut times, which is one
116
- * value per segment — 830 of them on a two-hour film, about 7 KB of log for a
117
- * single run, repeated on every restart. The count and the two ends say
118
- * everything the list is ever consulted for: whether cutting was explicit at
119
- * all, how far it reaches, and where it starts.
120
- *
121
- * @param {string[]} args
122
- * @returns {string}
123
- */
124
- export function describeFfmpegArgs(args) {
125
- const parts = [];
126
- for (let index = 0; index < args.length; index += 1) {
127
- const value = args[index];
128
- // Both take the same list, and a keyframe-grid variant passes it twice.
129
- // `-force_key_frames` also takes an expression, which is short and is left
130
- // alone — only a list is folded.
131
- if (
132
- (value === "-segment_times" || value === "-force_key_frames") &&
133
- typeof args[index + 1] === "string" &&
134
- args[index + 1].includes(",")
135
- ) {
136
- const times = args[index + 1].split(",");
137
- parts.push(value, `<${times.length} cuts ${times[0]}..${times[times.length - 1]}>`);
138
- index += 1;
139
- continue;
140
- }
141
- parts.push(value);
142
- }
143
- return parts.join(" ");
144
- }
145
-
146
- export class EncodeRuns {
147
- #inputState = new WeakMap();
148
- /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
149
- #host;
150
-
151
- /**
152
- * Whether a re-decision of what encoders should exist is already queued for
153
- * the end of this turn. See `planEncodersSoon`.
154
- * @type {boolean}
155
- */
156
- #planScheduled = false;
157
-
158
- /**
159
- * @param {object} host - `logger`, `viewerSecondsOn`, `noteRunStarting`, `inputOf`, `producedNumbers`, `servesAudioSeparately`, `disposeSession`, `contentionPenalties`, `encodeCost`, `encodeOrchestrator`, `encoders`, `ffmpegBin`, `outputTimes`, `outputs`, `priority`, `segmentDurationSec`, `segmentFiles`, `videoEncoder`
160
- * @param {SegmentFiles} host.segmentFiles - The storage operations used to
161
- * write and inspect output files.
162
- */
163
- constructor(host) {
164
- this.#host = host;
165
- }
166
-
167
- #inputStateFor(output) {
168
- let state = this.#inputState.get(output);
169
- if (!state) {
170
- state = {
171
- readWindowBytes: 0,
172
- inputRetryCount: 0,
173
- backwardRestarts: { count: 0, segmentsBack: 0, worstBack: 0, remade: 0 },
174
- firstWantedAt: new Map(),
175
- /** Bytes the swarm has delivered to this output's own input reads. */
176
- inputBytes: 0,
177
- /** The mismatch between the held init and the run's size last said, so it is said once. */
178
- initSizeSaid: ""
179
- };
180
- this.#inputState.set(output, state);
181
- }
182
- return state;
183
- }
184
-
185
- setReadWindow(output, bytes) {
186
- this.#inputStateFor(output).readWindowBytes = Number.isFinite(bytes) ? bytes : 0;
187
- }
188
-
189
- readWindowFor(output) {
190
- return this.#inputStateFor(output).readWindowBytes;
191
- }
192
-
193
- noteWanted(output, index, at = Date.now()) {
194
- const wanted = this.#inputStateFor(output).firstWantedAt;
195
- if (!wanted.has(index)) wanted.set(index, at);
196
- }
197
-
198
- resetInputRetry(output) {
199
- this.#inputStateFor(output).inputRetryCount = 0;
200
- }
201
-
202
- /**
203
- * Count bytes the swarm has delivered to one output's own input read.
204
- *
205
- * Called by the `/stream` route for every fragment it writes to an encoder.
206
- * Cheap on purpose — one addition, no clock, no log — because it runs per
207
- * fragment on the path that feeds ffmpeg.
208
- *
209
- * @param {string} outputId
210
- * @param {number} bytes
211
- * @returns {void}
212
- */
213
- noteInputBytes(outputId, bytes) {
214
- if (!outputId || !(bytes > 0)) {
215
- return;
216
- }
217
- const output = this.#host.outputs.get(outputId);
218
- if (output) {
219
- this.#inputStateFor(output).inputBytes += bytes;
220
- }
221
- }
222
-
223
- /**
224
- * @param {object} output
225
- * @returns {number}
226
- */
227
- inputBytesOf(output) {
228
- return output ? this.#inputStateFor(output).inputBytes : 0;
229
- }
230
-
231
- runsOf(output) {
232
- return output ? this.#host.encodeOrchestrator.runsOn(output.outputKey) : [];
233
- }
234
-
235
- /**
236
- * Where the earliest live encoder of this output began, or null with none.
237
- *
238
- * @param {object} output
239
- * @returns {number | null}
240
- */
241
- earliestStartOf(output) {
242
- return earliestRunStart(this.runsOf(output));
243
- }
244
-
245
- isLive(output) {
246
- return Boolean(output && this.#host.outputs.get(output.id) === output);
247
- }
248
-
249
- liveRunsOf(output) {
250
- return liveRunsOf(this.runsOf(output));
251
- }
252
-
253
- runStateOf(output) {
254
- return output ? this.#host.encodeOrchestrator.stateOf(output.outputKey) : runStateOf([]);
255
- }
256
-
257
- lastErrorOf(output) {
258
- return output ? this.#host.encodeOrchestrator.errorOf(output.outputKey) : "";
259
- }
260
-
261
- /**
262
- * Whether this output's encoding has failed for good.
263
- *
264
- * @param {object} output
265
- * @returns {boolean}
266
- */
267
- hasFailed(output) {
268
- return this.runStateOf(output) === ENCODE_RUN_STATE.ENDED_FAILED;
269
- }
270
-
271
- /**
272
- * Whether this output's input went away and is being fetched again.
273
- *
274
- * @param {object} output
275
- * @returns {boolean}
276
- */
277
- isWaitingForInput(output) {
278
- return this.runStateOf(output) === ENCODE_RUN_STATE.RETRY_WAIT;
279
- }
280
-
281
- /**
282
- * The run state in the words the browser is told.
283
- *
284
- * @param {object} output
285
- * @returns {string}
286
- */
287
- wireStateOf(output) {
288
- return wireState(this.runStateOf(output));
289
- }
290
-
291
- /**
292
- * What went wrong, when this output's encoding has failed; empty otherwise.
293
- *
294
- * @param {object} output
295
- * @returns {string}
296
- */
297
- failureOf(output) {
298
- return this.hasFailed(output) ? this.lastErrorOf(output) : "";
299
- }
300
-
301
- progressOf(output, index = null) {
302
- if (!output) {
303
- return null;
304
- }
305
- const at = Number.isInteger(index)
306
- ? index
307
- : this.#host.outputTimes.segmentIndexForTime(output, this.#host.viewerSecondsOn(output));
308
- const progress = this.#host.encodeOrchestrator.progressOf(output.outputKey, at);
309
- if (progress) {
310
- return progress;
311
- }
312
- const start = this.#host.viewerSecondsOn(output);
313
- const total = Number(output.file?.durationSeconds);
314
- return {
315
- processedSeconds: start,
316
- startPositionSeconds: start,
317
- totalSeconds: Number.isFinite(total) && total > 0 ? total : null,
318
- percent: 0,
319
- remainingSeconds: Number.isFinite(total) && total > 0 ? Math.max(0, total - start) : null,
320
- speed: "",
321
- updatedAt: this.#host.outputs.startedAt(output) ?? Date.now()
322
- };
323
- }
324
-
325
- planEncodersNow() {
326
- const byOutput = this.#outputsWithSessions();
327
- for (const [address, sessions] of byOutput) {
328
- // From the TIMELINE, which is where how a file is cut has lived since
329
- // 2.76.0. Read off the session it left, this was `undefined` on every
330
- // session ever made: the map then held no length, and the walk that
331
- // gives a run its end ran to MAX_SAFE_INTEGER — the main thread spun at
332
- // 100% and the proxy answered nothing, measured on the addon host
333
- // 2026-09-05 with the stack read out of the live process.
334
- const segmentCount = Number(sessions[0].timeline?.segmentCount) || 0;
335
- if (segmentCount > 0) {
336
- this.#host.encodeOrchestrator.setSegmentCount(address, segmentCount);
337
- }
338
- }
339
- // THE MAP IS BUILT ONCE, IN ITS OWN LAYER, AND BOTH SIDES READ THAT ONE.
340
- //
341
- // It used to be built twice: once here, per viewer, converted and stated to
342
- // the encoding as a window each, and once again inside `publishFor` for the
343
- // downloading. Two answers to one question, and the encoding's copy carried
344
- // the viewer's NAME as the key of a claim — against the rule that the
345
- // encoding and the viewer are not connected at all.
346
- this.#host.priority.publishFor({
347
- sessionGroups: byOutput.values(),
348
- });
349
- // FROM THE VIEWERS OF THAT OUTPUT, not from the viewers of the film.
350
- //
351
- // Both scopes are right for what asks them: the swarm is asked for bytes of
352
- // a FILE, which every output of it reads, and encoders are placed per
353
- // OUTPUT, which a person watching 480p wants nothing of at 1080p. Handed the
354
- // film's map, the plan wanted an encoder on every output of it, and what
355
- // stopped the unwatched ones was this class killing them by its own
356
- // judgement — while the viewer's own move announced itself and had the plan
357
- // start them again.
358
- //
359
- // Converted into each output's own numbering, because two outputs of one
360
- // film are cut independently and the same second is a different number in
361
- // each: 454 pieces against 401 on the field file.
362
- for (const [address, sessions] of byOutput) {
363
- const timeline = sessions[0].timeline;
364
- this.#host.encodeOrchestrator.notePriorityMap(
365
- address,
366
- timeline?.inSegments?.(
367
- this.#host.priority.mapForOutput(address),
368
- Number(timeline?.segmentCount) || 0
369
- ) ?? []
370
- );
371
- }
372
- this.#host.encodeOrchestrator.reconcile();
373
- }
374
-
375
- /**
376
- * Re-decide what encoders should exist, once, after the change that is being
377
- * made now.
378
- *
379
- * COALESCED, NOT DELAYED. One turn of the event loop may carry several
380
- * changes — a viewer arrives and is placed and states their soundtrack — and
381
- * each of them is a reason to re-decide, while re-deciding three times in a
382
- * row would give the same answer three times and could act on a half-built
383
- * state. So the decision is taken once, after the current turn, and no
384
- * interval is involved: there is nothing to choose and nothing to tune.
385
- *
386
- * @returns {void}
387
- */
388
- planEncodersSoon() {
389
- if (this.#planScheduled) {
390
- return;
391
- }
392
- this.#planScheduled = true;
393
- queueMicrotask(() => {
394
- this.#planScheduled = false;
395
- try {
396
- this.planEncodersNow();
397
- } catch (error) {
398
- const message = error instanceof Error ? error.message : String(error);
399
- this.#host.logger.warn(`transcode could not re-plan encoders: ${message}`);
400
- }
401
- });
402
- }
403
-
404
- /**
405
- * The live sessions grouped by the output they produce.
406
- *
407
- * @returns {Map<string, HlsSession[]>}
408
- */
409
- #outputsWithSessions() {
410
- /** @type {Map<string, HlsSession[]>} */
411
- const byOutput = new Map();
412
- for (const session of this.#host.outputs.values()) {
413
- const address = session.outputKey ?? "";
414
- if (!address) {
415
- continue;
416
- }
417
- byOutput.set(address, [...(byOutput.get(address) ?? []), session]);
418
- }
419
- return byOutput;
420
- }
421
-
422
- forgetEncodingOfGone(output) {
423
- if (this.#host.outputs.outputsOn(output.outputKey).length === 0) {
424
- this.#host.encodeOrchestrator.forgetOutput(output.outputKey);
425
- }
426
- }
427
-
428
- /**
429
- * Make an encoder for this output, beginning at this segment.
430
- *
431
- * Another run of the SAME session, not another session. A run at another
432
- * position is not a different output — the material, the tracks, the grid and
433
- * the box are all the same, and only where it begins differs, which changes
434
- * no byte of what is produced. Both write into the output's one directory and
435
- * either viewer is served whatever either has made.
436
- *
437
- * @param {string} address
438
- * @param {number} from
439
- * @param {number} to
440
- * @param {string} because - The plan's own words for why it placed this one.
441
- * @returns {object | null}
442
- */
443
- makeRunAt(address, from, to, because) {
444
- let base = null;
445
- for (const session of this.#host.outputs.values()) {
446
- if (session.outputKey === address) {
447
- base = session;
448
- break;
449
- }
450
- }
451
- if (!base) {
452
- return null;
453
- }
454
- // A position that has already failed to start, this many times running,
455
- // will fail again: nothing about it has changed between the attempts, which
456
- // is exactly why the attempts keep taking the same fraction of a second and
457
- // ending the same way.
458
- //
459
- // The plan is arithmetic over coverage and demand, and neither of them
460
- // knows that a process refused to start — so without asking here, the plan
461
- // commands the same start, the run ends, the ended stretch goes back to the
462
- // map, and the plan commands it again. Measured 2026-09-05 with ffmpeg
463
- // absent: fifty passes of the plan in the time a probe took to notice, as
464
- // fast as spawning could fail. The five-second timer this decision used to
465
- // sit on hid that, at the price of hiding it in the field too — the loop
466
- // seen there ran for sixteen minutes and read as "a restart every five
467
- // seconds".
468
- //
469
- // A DIFFERENT position is unaffected and gets its own budget, and the count
470
- // resets the moment a run at this one does real work.
471
- if (!this.#host.encodeOrchestrator.mayStartAt(address, from)) {
472
- return null;
473
- }
474
- // The encoder is built and handed back in this same call. Nothing here
475
- // waits: the one thing this path used to wait for was the death of the run
476
- // it was replacing, and that killing is gone. Answering with nothing while
477
- // the encoder was built behind the answer is what let the same stretch be
478
- // started over and over — 684 starts in 482 seconds of field 2026-09-05.
479
- try {
480
- return this.#startEncodeRun(base, from, because, { to });
481
- } catch (error) {
482
- const message = error instanceof Error ? error.message : String(error);
483
- this.#host.logger.warn(`transcode could not start a run at #${from} of ${address}: ${message}`);
484
- return null;
485
- }
486
- }
487
-
488
- /**
489
- * How many encoders this machine can afford on one output at once.
490
- *
491
- * Measured rather than chosen, and it is the same arithmetic that decides
492
- * which quality steps are offered: what a second job costs here is not
493
- * assumed to be nothing. Field 2026-09-03 on the addon host, `testsrc2`
494
- * through libx264 `ultrafast` — at 854x480 one run makes 7.12x and two make
495
- * 4.20x and 4.16x, so both stay far above realtime and a second is
496
- * affordable; at 1920x1080 one makes 1.96x and two make 0.99x and 0.98x, so
497
- * the machine is full at one.
498
- *
499
- * @param {string} address
500
- * @returns {number}
501
- */
502
- maxRunsForOutput(address) {
503
- const alone = this.#host.encodeCost.speedForOutput(address);
504
- if (!(alone > 0)) {
505
- // The host measured nothing at all, which is a broken startup rather than
506
- // a state to plan around. One encoder is what it keeps.
507
- return 1;
508
- }
509
- let affordable = 1;
510
- for (;;) {
511
- const { penalty, measured, from } = contentionPenalty(affordable, this.#host.contentionPenalties);
512
- // An UNMEASURED penalty is 1, and that is the honest answer to "what does
513
- // a second job cost" only in the sense that nothing has been measured —
514
- // it is not a statement that a second job is free. Measured on the addon
515
- // host it is 1.70x at 854x480 and 1.98x at 1920x1080, so taking 1 would
516
- // let a machine that cannot hold two runs start two. Where nothing has
517
- // been measured, one is what it has.
518
- //
519
- // `from` is the concurrency the reading came from, and past the measured
520
- // range `contentionPenalty` HOLDS the largest reading rather than continue
521
- // a curve two points cannot describe. Held is the right answer to "what
522
- // does this cost", and the wrong one to "may I start another": it would
523
- // price a fifth encoder at what a second was measured to cost, and a fast
524
- // host would keep dividing until some chosen ceiling stopped it. So the
525
- // ladder stops where the measurements stop — the bound on how many
526
- // encoders may run is measured, like the budget itself, and there is no
527
- // constant here to overrule it.
528
- if (!measured || from !== affordable || !(alone / penalty >= 1)) {
529
- break;
530
- }
531
- affordable += 1;
532
- }
533
- return affordable;
534
- }
535
-
536
- /**
537
- * A segment this run made has just been served.
538
- *
539
- * The one event whose raising is guarded by the state, and the guard is a
540
- * READ of the state rather than a second copy of it: "something has been
541
- * produced" is a level, not an edge, so without the guard every served
542
- * segment would raise it and the log would fill with refusals.
543
- *
544
- * Whose file it is decides the rest, and the directory answers that outright:
545
- * runs write into one each, and serving searches them newest-first, so a
546
- * segment left by an EARLIER run is served routinely. Comparing indices
547
- * instead would have been fooled by the ordinary case of a backward seek —
548
- * the new run starts at #10, the old one left #50 on disk, and #50 is above
549
- * the new run's start index while saying nothing about it.
550
- *
551
- * @param {HlsSession} session
552
- * @param {string} filePath - Where the served segment was actually found.
553
- * @returns {void}
554
- */
555
- noteRunProducedSegment(session, filePath) {
556
- if (typeof filePath !== "string" || path.dirname(filePath) !== this.#host.segmentFiles.pathFor(session.outputKey ?? "")) {
557
- return;
558
- }
559
- const index = session.segmentFormat.segmentIndexFromName(path.basename(filePath));
560
- if (index === null) {
561
- return;
562
- }
563
- // Whichever run was given this number. An output has as many runs as the
564
- // machine affords, and a segment moves the one it belongs to out of
565
- // starting — not whichever happens to be listed first.
566
- ownRunMaking(this.runsOf(session), index)?.noteProduced(index);
567
- }
568
-
569
- /**
570
- * Say so when a run is about to encode a picture the init segment already in
571
- * the player's hands does not describe.
572
- *
573
- * This is the whole class of fault named in one line, and it exists because
574
- * the fault is otherwise SILENT: no layer reports an error, the encoder is
575
- * healthy, segments are served in milliseconds, and what the viewer gets is
576
- * either a band of macroblock garbage or a picture that never appears. The
577
- * shape is the one 2.48.0 uses for the TIME a run begins at — a run states
578
- * where it really landed, and a disagreement with what was published is
579
- * named rather than left to be inferred from a browser's own reading.
580
- *
581
- * The size the init describes is read from the init's own bytes, not taken
582
- * from our record of what the encoder was told, because those two disagreeing
583
- * IS the fault. The size the run will produce is computed by the same
584
- * arithmetic the scale filter performs, so a source smaller than the target
585
- * box is not reported as a disagreement.
586
- *
587
- * Said once per distinct pair of sizes: a run repeated at the same wrong size
588
- * has nothing further to say.
589
- *
590
- * @param {HlsSession} session
591
- * @returns {void}
592
- */
593
- #warnIfRunLeavesTheInitBehind(session) {
594
- const initBytes = this.#host.segmentFiles.initOf(session.outputKey ?? "");
595
- if (!session.spec.transcodesVideo || !initBytes || initBytes.length === 0) {
596
- return; // nothing served yet, or nothing being encoded
597
- }
598
- const format = session.segmentFormat;
599
- if (typeof format?.initVideoSize !== "function") {
600
- return; // a self-describing container (MPEG-TS) cannot have this fault
601
- }
602
- const described = format.initVideoSize(initBytes);
603
- if (!described) {
604
- return;
605
- }
606
- if (!(session.output.encodeWidth > 0) || !(session.output.encodeHeight > 0)) {
607
- return; // the run keeps the encoder's own default box; nothing was told
608
- }
609
- const producing = computeOutputDimensions(
610
- session.output.encodeWidth,
611
- session.output.encodeHeight,
612
- session.file.width,
613
- session.file.height
614
- );
615
- if (!producing) {
616
- return; // the source size is unknown, so nothing can be predicted
617
- }
618
- if (described.width === producing.w && described.height === producing.h) {
619
- return;
620
- }
621
- const said = `${described.width}x${described.height}->${producing.w}x${producing.h}`;
622
- const inputState = this.#inputStateFor(session);
623
- if (inputState.initSizeSaid === said) {
624
- return;
625
- }
626
- inputState.initSizeSaid = said;
627
- this.#host.logger.warn(
628
- `transcode ${session.id} is about to encode ${producing.w}x${producing.h} while the init segment ` +
629
- `the player holds describes ${described.width}x${described.height} "${session.file.name}" — ` +
630
- `every fragment of this run will be decoded against parameter sets for a picture that is not ` +
631
- `being made. A change of size is a change of variant; nothing here should have moved it.`
632
- );
633
- }
634
-
635
- /**
636
- * How far a run starting here may work before it meets somebody else's
637
- * material — read off the ONE coverage map, never worked out again here.
638
- *
639
- * This replaced `planRunInterval`, which was a second authority over the same
640
- * question and answered it by different rules: it walked the whole track for
641
- * the first free number, MOVED the start there itself, and counted every live
642
- * run as claiming up to `head + look-ahead`. Measured in the field
643
- * 2026-09-05: the plan commanded a start at #46, this moved it to #78 — the
644
- * "run moved forward from #46 to #78" line — and the plan, seeing a run
645
- * outside the window it had asked for, killed it as unwanted and commanded
646
- * the same start again, 350-700ms per cycle, dozens of times, the viewer's
647
- * picture stopped for 125 seconds.
648
- *
649
- * Where a run STARTS is the plan's decision and arrives here as an argument.
650
- * All this answers is where it must stop, and the answer is a fact of the
651
- * map: the free stretch from that number on. `-1` means the end of the track,
652
- * which is what "no end" is written as everywhere here.
653
- *
654
- * @param {object} session
655
- * @param {number} startIndex
656
- * @param {object | null} exceptRun - The run being replaced, whose own claim
657
- * is not somebody else's material.
658
- * @returns {number} The last number to work through, or `-1` for the end.
659
- */
660
- #runEndFrom(session, startIndex, exceptRun = null) {
661
- return this.#host.encodeOrchestrator.freeStretchEnd({
662
- address: session.outputKey ?? "",
663
- from: startIndex,
664
- exceptRun,
665
- segmentCount: Number(session.timeline?.segmentCount) || 0
666
- });
667
- }
668
-
669
- // Returns the encoder it built, or nothing when there was nothing to build.
670
- // It waits for nothing: the one thing it used to wait for was the death of
671
- // the run it was replacing, and that killing is gone.
672
- #startEncodeRun(session, startIndex, because, ordered = null) {
673
- if (!this.isLive(session)) {
674
- return null;
675
- }
676
- // A new run starts the quality budget's reckoning afresh: a pair of
677
- // readings spanning the restart would count the gap between two runs as
678
- // slow encoding. Told, not written: those readings are the budget's.
679
- this.#host.noteRunStarting(session);
680
- // Where a restart's seconds go. A seek costs 5-8 s in the field and the
681
- // recorded reason — waiting for the previous ffmpeg to exit, measured at
682
- // 0.54-1.47 s — does not account for it. Before rebuilding the hottest path
683
- // in the proxy on a guess, make each stage state its own cost.
684
- const restartEnteredAt = Date.now();
685
- // Reads where the old run began BEFORE the new one takes its place, and
686
- // does not await: everything below is the restart path, which is measured
687
- // in milliseconds and has been worked on twice to keep it that way.
688
- this.#accountBackwardRestart(session, startIndex);
689
- // STARTING AN ENCODER STOPS NOTHING. It used to stop any live run whose own
690
- // start was not below this one's — a rule left over from when a session
691
- // held exactly one run and "the previous one" meant "the only one". Once a
692
- // an output could hold several, that rule began killing runs the plan had
693
- // decided to keep: 294 stops for this reason in eight minutes of field
694
- // 2026-09-05, against four starts asked for by a viewer. Who is stopped is
695
- // decided in one place, and it is not this one.
696
- //
697
- // HOW FAR IT MAY WORK is decided by the same one place and arrives here as
698
- // an argument. Reading it off the coverage map a second time was the last
699
- // remaining second answer to that question: the plan computed `to`, passed
700
- // it, and the parameter list did not name it.
701
- const runEnd = Number.isInteger(ordered?.to)
702
- ? ordered.to
703
- : this.#runEndFrom(session, startIndex, null);
704
- // The restart backs off a segment or two from what was asked for, so the
705
- // request that prompted it is recorded under a HIGHER index than the run
706
- // starts at. Looking it up by the start index alone found nothing and the
707
- // line never printed once.
708
- let wantedAt = null;
709
- const inputState = this.#inputStateFor(session);
710
- for (const [index, at] of inputState.firstWantedAt) {
711
- if (index >= startIndex && (wantedAt === null || at < wantedAt)) {
712
- wantedAt = at;
713
- }
714
- }
715
- if (typeof wantedAt === "number") {
716
- this.#host.logger.info(
717
- `transcode ${session.id} restart for #${startIndex} decided ` +
718
- `${restartEnteredAt - wantedAt}ms after it was first asked for`
719
- );
720
- }
721
- // Cleared with the run that could not answer them. These are "how long has
722
- // this segment gone unanswered", and the question only means anything about
723
- // the run in force: a timestamp kept from an abandoned scan probe minutes
724
- // ago says a fresh request has already waited long enough, which is how the
725
- // behind-head repair came to fire on the very first poll instead of waiting
726
- // for the seek that should move the encoder. It also stops the map growing
727
- // for the life of a session.
728
- inputState.firstWantedAt.clear();
729
- // WHERE THIS NUMBER REALLY BEGINS, when a produced piece has said so and
730
- // the table the player holds still says otherwise.
731
- //
732
- // Only a soundtrack, and only because a soundtrack has no keyframes: it
733
- // begins exactly where it is asked to, to within one audio frame, while the
734
- // picture can begin nowhere but a real keyframe and so moves forward to the
735
- // next one — up to three seconds, measured 2026-08-17. Left at the published
736
- // time, the sound of one film starts up to that far from its picture after
737
- // every restart, each correctly labelled with where it really is, and the
738
- // viewer gets sound with no new picture for the difference.
739
- //
740
- // DERIVED HERE rather than handed in. It used to arrive as an argument from
741
- // the one caller that knew it — the correction that had just measured it —
742
- // which meant the instant was only ever right for a run that caller
743
- // started. Any run the plan placed at a corrected number got the published
744
- // time and landed apart again. It is a fact of the FILE's cutting, held in
745
- // the live table every session of the file shares, so it is read from
746
- // there.
747
- const positionSecondsOverride = session.spec.carries === "audio-only"
748
- ? trueStartOf(session.timeline, startIndex)
749
- : undefined;
750
-
751
- // What is still read off the session for a run. The list is the measure of
752
- // how far a session still is from being the three things a run is built
753
- // from — the material, what is produced of it, and the stretch — and it
754
- // shrinks in place as those are taken off. There is deliberately no method
755
- // wrapping it: a named adapter with one caller is a thing to remember to
756
- // delete, and this is a thing that disappears by being emptied.
757
- const inputs = this.#host.inputOf(session);
758
- const { args, safeIndex, startSeconds, cutTimes } = buildRunCommand({
759
- keyframes: session.keyframes,
760
- inputFile: inputs.inputFile,
761
- audioFile: inputs.audioFile,
762
- inputUrl: inputs.inputUrl,
763
- audioInputUrl: inputs.audioInputUrl,
764
- timeline: session.timeline,
765
- output: session.output,
766
- segmentFormat: session.segmentFormat,
767
- transcodeVideo: session.spec.transcodesVideo,
768
- transcodeAudio: session.spec.transcodesAudio,
769
- audioOnly: session.spec.carries === "audio-only",
770
- audioSeparate: this.#host.servesAudioSeparately(session),
771
- audioSourceTrackIndex: session.spec.audioSourceTrackIndex,
772
- rateControl: session.spec.video?.encode?.rateControl ?? null,
773
- startIndex,
774
- endIndex: runEnd,
775
- positionSecondsOverride,
776
- videoEncoder: this.#host.videoEncoder,
777
- segmentDurationSec: this.#host.segmentDurationSec
778
- });
779
-
780
- // The exact command, every run. An encode failure is otherwise reported
781
- // with ffmpeg's message and nothing about what it was asked to do, and the
782
- // two are not always deducible from each other: 2026-08-04 a run died with
783
- // "Cannot write moov atom before AC3 packets" although both muxing paths
784
- // were verified to handle a copied AC-3 track on this very host, so the
785
- // arguments that run actually received are the missing evidence. One line
786
- // per run, and a run happens at most every few seconds.
787
- // Numbered, because a burst of seeks starts several runs in one second and
788
- // every line about them carries the SESSION id, which is the same for all.
789
- // Without a run number the command that failed cannot be told from the two
790
- // that succeeded around it — which is exactly the state the unexplained
791
- // `Cannot write moov atom before AC3 packets` was found in.
792
-
793
- // One directory for the output, and every run writes straight into it.
794
- //
795
- // Runs used to be kept apart by a directory each, because two of them
796
- // writing one segment name at the same time produce a file belonging to
797
- // neither — which was also the only reason a restart ever had to wait for
798
- // its predecessor to die. Intervals remove that by construction: a run is
799
- // given a stretch nobody else holds and stops at the end of it, so no two
800
- // runs ever want the same number. What is left of the old reason — a run
801
- // killed mid-piece leaving a partial file — is not a correctness problem
802
- // either, because the store serves a segment only once its closure is
803
- // proven, and it is cleared up when the run ends.
804
- const run = new EncodeRun({
805
- address: session.outputKey ?? session.id,
806
- encoder: this.#host.videoEncoder,
807
- from: safeIndex,
808
- to: runEnd,
809
- buildArgs: () => args,
810
- argsDescribed: describeFfmpegArgs(args),
811
- // Whether this run cuts at times we gave it. Decides how a segment is
812
- // judged finished — see getFileStream.
813
- usesExplicitCuts: Boolean(cutTimes && cutTimes.length > 0),
814
- startSeconds,
815
- totalSeconds: Number(session.file.durationSeconds) || null,
816
- spawn: (spawnArgs) =>
817
- spawn(this.#host.ffmpegBin, spawnArgs, {
818
- cwd: this.#host.segmentFiles.directoryFor(session.outputKey ?? ""),
819
- // A fourth channel: the encoder names every piece it has CLOSED on it,
820
- // which is the only proof a piece is whole.
821
- stdio: ["ignore", "pipe", "pipe", "pipe"]
822
- }),
823
- logger: this.#host.logger,
824
- // The film's last segment number, which is what tells "it reached the
825
- // end" from "its input dried up": ffmpeg exits zero for both and over a
826
- // torrent cannot tell them apart.
827
- lastSegmentIndex: () =>
828
- session.timeline?.segmentCount > 0 ? session.timeline.segmentCount - 1 : null,
829
- inputUnavailable: (message) => isInputUnavailable(message),
830
- onProgress: (report) => this.#noteRunProgress(session, run, report),
831
- indexOfName: (name) => session.segmentFormat.segmentIndexFromName(
832
- session.segmentFormat.servedNameOf?.(name) ?? name),
833
- // Why this encoder exists, recorded with its argument list. It used to be
834
- // handed to a separate `start` call; there is no separate call now.
835
- because,
836
- onClosed: (name) => {
837
- const index = session.segmentFormat.segmentIndexFromName(
838
- session.segmentFormat.servedNameOf?.(name) ?? name);
839
- if (Number.isInteger(index) && index < safeIndex) return null;
840
- return this.#host.segmentFiles.publish(session.outputKey ?? "", name, session.segmentFormat, {
841
- endSeconds: index < session.timeline.segmentCount - 1 ?
842
- session.timeline.publishedStartOf(index + 1) - SEGMENT_CUT_TIME_DELTA_SECONDS : undefined
843
- });
844
- },
845
- onEnded: (ended) => this.noteRunEnded(session, run, ended)
846
- });
847
- // THE ONE FAULT THAT IS OTHERWISE SILENT, asked before this run produces a
848
- // frame. It lost its caller in a refactor on 2026-09-04 and had none until
849
- // 2026-09-15 — not by a decision, which is why it is back rather than gone.
850
- this.#warnIfRunLeavesTheInitBehind(session);
851
-
852
- this.#host.logger.info(
853
- `transcode ${session.id} encode-run #${safeIndex}..#${runEnd} from segment #${safeIndex} ` +
854
- `(+${Date.now() - restartEnteredAt}ms since the restart was asked for) ` +
855
- `(${formatSeconds(startSeconds)}) "${session.file.name}"`
856
- );
857
- // The four numbers a run is positioned by, said once, because their
858
- // disagreement is invisible everywhere else. The two tables are printed
859
- // side by side: while they differ, every cut of this run is off by the
860
- // difference, and nothing downstream can tell that from a bad index.
861
- const liveStart = this.#host.outputTimes.segmentStartTime(session, safeIndex);
862
- this.#host.logger.info(
863
- `transcode ${session.id} run #${safeIndex}..#${runEnd} positioned at ${startSeconds.toFixed(3)}s ` +
864
- `for boundary #${safeIndex} (published ${startSeconds.toFixed(3)}s, ` +
865
- `live ${liveStart.toFixed(3)}s, apart ${(liveStart - startSeconds).toFixed(3)}s), ` +
866
- `numbering from #${safeIndex}`
867
- );
868
- return run;
869
- }
870
-
871
- /**
872
- * Log a report from a run that still belongs to this output. The run owns the
873
- * clock and has already placed its relative ffmpeg time on the source
874
- * timeline.
875
- *
876
- * @param {HlsSession} session
877
- * @param {import("./EncodeRun.js").EncodeRun} run
878
- * @param {object} progress
879
- * @returns {void}
880
- */
881
- #noteRunProgress(session, run, progress) {
882
- if (!this.isLive(session) || !this.runsOf(session).includes(run)) {
883
- return;
884
- }
885
- if (run.progress.shouldLog(PROGRESS_LOG_INTERVAL_MS)) {
886
- this.#host.logger.info(
887
- `transcode ${session.id} "${session.file.name}" ${progress.percent.toFixed(1)}% ` +
888
- `(${formatSeconds(progress.processedSeconds)} / ${formatSeconds(progress.totalSeconds)})` +
889
- ` speed=${progress.speed || "n/a"}`
890
- );
891
- }
892
- }
893
-
894
- /**
895
- * What to do about a run that has ended.
896
- *
897
- * The run says how it ended and why; this decides what follows, which is a
898
- * question about the SESSION and the machine rather than about the process:
899
- * whether to condemn a hardware encoder, whether to wait for the input to
900
- * come back, whether a position has failed often enough to stop retrying it.
901
- *
902
- * An ending from a run the session has already replaced is not ignored — it
903
- * is simply not about this session's current run, so nothing that describes
904
- * the current run is written from it. That is what the identity check used to
905
- * be for, and it is one condition now instead of one at the head of every
906
- * handler.
907
- *
908
- * @param {HlsSession} session
909
- * @param {import("./EncodeRun.js").EncodeRun} run
910
- * @param {import("./EncodeRun.js").RunEnded} ended
911
- * @returns {void}
912
- */
913
- noteRunEnded(session, run, ended) {
914
- // First, and for every run whatever else follows: the stretch it held goes
915
- // back to the map. A run whose claim is never released tells the plan that
916
- // numbers nobody is making are being made, and nothing is ever started
917
- // there again.
918
- // WAS this run still the session's when it ended? Asked before it is
919
- // removed, because after the removal the question always answers "no" —
920
- // and it was asked after, so every line below this point was unreachable.
921
- //
922
- // Measured 2026-09-05 over both of the field host's log files: zero
923
- // occurrences of this handler's own `encode-run #… failed:` line and zero
924
- // of `fast failure at segment`, across every session this proxy has ever
925
- // run. So the fallback from a failed hardware encoder to software, the
926
- // retry when the torrent data goes away, the limit on retrying a position
927
- // that keeps failing, and the error line naming the ffmpeg command have all
928
- // been dead code — which is also why nothing ever stopped the restart loop
929
- // recorded in the field the same day.
930
- const wasCurrent = this.runsOf(session).includes(run);
931
- this.#host.encodeOrchestrator.noteEnded(ended);
932
- // What this admitted encode was seen to do, kept for the next time this
933
- // host prices the same mode (roadmap item 97, step 14). Whatever the
934
- // ending: a run that failed still ran at the speed it ran at, and the
935
- // segments it closed still carried what they carried.
936
- this.#host.observeEncodeEnded?.(session);
937
- // A stretch went back to the map, so what should be running has changed.
938
- // Said here rather than waited for: this is the moment it became true.
939
- this.planEncodersSoon();
940
- // ANYBODY ALREADY WAITING IS TOLD, and it is asked HERE because every
941
- // ending passes this line while the handlers below return one by one. It
942
- // used to be the last statement of this method, which the `SHORT` branch —
943
- // ffmpeg exiting 0 having produced less than the playlist promises —
944
- // returns before reaching. That ending is terminal (`ENDED_FAILED`), so a
945
- // request arriving after it is answered with the failure at once while a
946
- // wait that BEGAN before it sat out its whole deadline, or, where the page
947
- // states none, until the viewer disconnected.
948
- //
949
- // THE CONDITION IS THE OUTPUT'S ACTUAL STATE, not this run's ending.
950
- // `stateOf` answers from the LIVE runs and falls back to the last ending
951
- // only when none remain, so one run of several ending in failure wakes
952
- // nobody — something is still making it — and the last one does. Asked
953
- // after `noteEnded` has recorded the ending, so the woken request reads the
954
- // final state; and it re-reads the disk first, because a piece already made
955
- // is served whatever became of the encoder.
956
- if (this.hasFailed(session)) {
957
- this.#host.invalidateWaits(session);
958
- // A move to this output being prepared for a viewer waits for a segment
959
- // that nothing will now make, and no publication will ever end that wait.
960
- // This is the event that does (roadmap item 97, step 12).
961
- this.#host.productionFailed(session);
962
- }
963
- if (!this.isLive(session)) {
964
- this.forgetEncodingOfGone(session);
965
- return;
966
- }
967
- if (!wasCurrent) {
968
- // A run the session had already replaced. It has logged its own ending;
969
- // nothing about the session follows from it.
970
- return;
971
- }
972
- const lastError = this.lastErrorOf(session) || ended.because;
973
- if (ended.ending === ENCODE_EXIT.STOPPED || ended.ending === ENCODE_EXIT.GONE) {
974
- return;
975
- }
976
- if (ended.ending === ENCODE_EXIT.COMPLETE) {
977
- this.#host.logger.info(`transcode ${session.id} encode-run complete "${session.file.name}"`);
978
- return;
979
- }
980
- if (ended.ending === ENCODE_EXIT.SHORT) {
981
- // ffmpeg exits 0 both when it reaches the end of the file and when its
982
- // input simply stops producing bytes — over HTTP the two look identical
983
- // to it. Field 2026-08-05: the torrent's download died, the read ended,
984
- // and a run that had made 188 segments of 624 reported itself complete;
985
- // the player then consumed what was on disk and froze on the first
986
- // segment nobody was making. So the claim is checked against the playlist
987
- // we published, and a run that stopped short is a FAILURE that can be
988
- // restarted, not a finished file.
989
- this.#host.logger.error(
990
- `transcode ${session.id} encode-run #${ended.from}..#${ended.to} ended early: ` +
991
- `${ended.because} "${session.file.name}"`
992
- );
993
- return;
994
- }
995
- // Runtime safety net: if a hardware encode fails, downgrade this proxy to
996
- // software encoding for all sessions and restart this one, so playback is
997
- // never permanently broken by a hardware/driver issue.
998
- //
999
- // Asked only of a genuine encoder failure. It used to be asked of every
1000
- // non-zero exit, so a run whose TORRENT DATA went away — which says nothing
1001
- // whatever about the encoder — condemned a working NVENC or QuickSync to
1002
- // software for the life of the process, and started an extra run at the old
1003
- // index while it was at it.
1004
- if (ended.ending === ENCODE_EXIT.FAILED && session.spec.transcodesVideo && this.#host.videoEncoder.kind !== "software") {
1005
- const failed = this.#host.encoders.useSoftware();
1006
- const failedEncoder = failed?.name ?? this.#host.videoEncoder.name;
1007
- this.#host.logger.warn(
1008
- `transcode ${session.id} hardware encoder ${failedEncoder} failed ` +
1009
- `(${lastError}); falling back to software libx264, and every output named by ${failedEncoder} is closed`
1010
- );
1011
- // An output IS its format, and the encoder is part of it: pieces from
1012
- // another encoder cannot be decoded with the header this output's viewers
1013
- // already hold. So the outputs made by the failed encoder end here, and
1014
- // the next request for that picture names a format built on the new one.
1015
- //
1016
- // THE ONE DISPOSAL THAT DOES NOT ASK WHETHER ASSIGNMENTS STILL HOLD IT, and
1017
- // deliberately. Every other one asks, because a repeat of a request must be
1018
- // answered by what answered it first. Here what answered it first has no
1019
- // encoder that can go on making it: holding the output keeps only a name
1020
- // whose next segment nobody will produce. A response already being sent is
1021
- // not cut short by this — it reads from a file already opened.
1022
- for (const other of [...this.#host.outputs.values()]) {
1023
- if (other.spec.video?.encode?.encoder === failedEncoder) {
1024
- void this.#host.disposeSession(other.id);
1025
- }
1026
- }
1027
- this.planEncodersSoon();
1028
- return;
1029
- }
1030
- // Losing the INPUT is not the session failing — it is the data not being
1031
- // there YET. The torrent can be re-added and re-downloaded, so the honest
1032
- // answer to the viewer is "still working", not an error screen. Field
1033
- // 2026-08-06: a torrent evicted mid-seek took the film with it, the run
1034
- // died on `File 0 not found`, the session went terminal and answered 500 to
1035
- // every request from then on — although the swarm was there and the data
1036
- // would have come back in seconds. The circuit breaker below stays for what
1037
- // it was built for, a target that genuinely cannot be encoded; it must not
1038
- // condemn a session whose data merely went away.
1039
- if (ended.ending === ENCODE_EXIT.INPUT_LOST) {
1040
- const inputState = this.#inputStateFor(session);
1041
- inputState.inputRetryCount += 1;
1042
- this.#host.logger.warn(
1043
- `transcode ${session.id} encode-run #${ended.from}..#${ended.to} lost its input ` +
1044
- `(${lastError}) (attempt ${inputState.inputRetryCount})`
1045
- );
1046
- // HOW LONG TO WAIT IS THE PLAN'S, and this says only what happened. The
1047
- // delay used to be timed here, against the dead run, which the plan never
1048
- // consults — so it placed a fresh run at the same spot as fast as ffmpeg
1049
- // could fail there: 2432 starts in 23 minutes in the field 2026-09-12,
1050
- // against a delay that had reached its 15 s ceiling long before. The
1051
- // orchestrator holds it now, beside the decision it governs.
1052
- if (run.state === ENCODE_RUN_STATE.RETRY_WAIT) {
1053
- run.retryDue();
1054
- }
1055
- return;
1056
- }
1057
- // A run that exits THIS fast never did real work: it failed at the start
1058
- // itself — opening the input, spawning the process — rather than
1059
- // mid-stream. Consecutive fast failures at the SAME position are counted so
1060
- // that whoever commands a start can stop commanding one that keeps failing.
1061
- //
1062
- // COUNTED AT EVERY POSITION, #0 included. It used to be counted only past
1063
- // #0, because it was written for seek restarts and a seek is never to the
1064
- // beginning. That left the one position the plan commands FIRST with no
1065
- // count at all, and the plan re-commanding a start that cannot succeed is
1066
- // an unbounded loop: measured 2026-09-05, ffmpeg failing to spawn produced
1067
- // fifty passes of the plan before a probe stopped it, as fast as the
1068
- // failures arrived.
1069
- const failure = this.#host.encodeOrchestrator.noteStartFailure(
1070
- session.outputKey,
1071
- ended.from,
1072
- ended.livedMs
1073
- );
1074
- if (failure.count > 0) {
1075
- this.#host.logger.warn(
1076
- `transcode ${session.id} fast failure at segment #${ended.from} ` +
1077
- `(${ended.livedMs}ms) — ${failure.count}/${failure.limit} consecutive`
1078
- );
1079
- if (failure.blocked) {
1080
- this.#host.logger.error(
1081
- `transcode ${session.id} will not be started at #${ended.from} again: ` +
1082
- `${failure.count} starts there failed within ${failure.fastMs}ms each ` +
1083
- `(${lastError}) "${session.file.name}"`
1084
- );
1085
- }
1086
- }
1087
- this.#host.logger.error(
1088
- `transcode ${session.id} encode-run #${ended.from}..#${ended.to} failed: ${lastError}` +
1089
- ` — ${this.#describeTrackSelection(session)}` +
1090
- `\n ffmpeg ${run.argsDescribed || "(command not recorded)"}`
1091
- );
1092
- }
1093
-
1094
- /**
1095
- * What this run asked the source for, against what the source said it has.
1096
- *
1097
- * Written for one failure in particular: every `-map` this proxy builds ends
1098
- * in `?`, so ffmpeg drops a mapping for an absent stream without complaint,
1099
- * and a run whose mappings ALL drop produces a file with nothing in it —
1100
- * reported as `Output file does not contain any stream`, exit 255. Read from
1101
- * the exit code alone that is indistinguishable from any other refusal. Read
1102
- * beside the tracks the file actually holds it is unmistakable, and it names
1103
- * which side is wrong: an audio index past the end of the list is ours, no
1104
- * streams at all is the source's.
1105
- *
1106
- * @param {HlsSession} session
1107
- * @returns {string}
1108
- */
1109
- #describeTrackSelection(session) {
1110
- const wanted = [];
1111
- // Named exactly as the command line names them, second input included: a
1112
- // refusal whose message describes a different mapping than the one that was
1113
- // refused is the reading that cost a wrong diagnosis before.
1114
- const inputs = this.#host.inputOf(session);
1115
- const audioInput = inputs.audioInputUrl.length > 0 ? 1 : 0;
1116
- const audioTrack = session.spec.audioSourceTrackIndex;
1117
- if (session.spec.carries === "audio-only") {
1118
- wanted.push(`audio 0:a:${audioTrack}`);
1119
- } else if (this.#host.servesAudioSeparately(session)) {
1120
- wanted.push("video 0:v:0");
1121
- } else {
1122
- wanted.push("video 0:v:0", `audio ${audioInput}:a:${audioTrack}`);
1123
- }
1124
- const counts = session.file.streamCounts;
1125
- const held = counts
1126
- ? `the source holds ${counts.video} video, ${counts.audio} audio, ` +
1127
- `${counts.subtitle} subtitle` +
1128
- (counts.other > 0 ? `, ${counts.other} other` : "")
1129
- : "what the source holds was not recorded";
1130
- return `this run asked for ${wanted.join(" + ")}, and ${held}`;
1131
- }
1132
-
1133
- /**
1134
- * Stop this session's encoder without replacing it.
1135
- *
1136
- * A variant nobody is watching must not go on encoding: the host has one
1137
- * encoder's worth of capacity, and the whole point of switching quality
1138
- * seamlessly is that the new rung gets it. The session itself stays — its
1139
- * produced segments remain servable, and switching back restarts it from
1140
- * where the viewer then is.
1141
- *
1142
- * @param {HlsSession} session
1143
- * @param {string} reason - Named in the log; a stopped encoder is otherwise
1144
- * indistinguishable from one that died.
1145
- * @returns {void}
1146
- */
1147
- stopEncodeRun(session, reason) {
1148
- const running = this.liveRunsOf(session);
1149
- if (running.length === 0) {
1150
- return;
1151
- }
1152
- // Every run this session has going. The callers all mean the session's
1153
- // encoding as a whole: a rung nobody is watching any more, a session being
1154
- // disposed. A run that had already finished or failed is not among them,
1155
- // which is what keeps a stop from erasing how it actually ended.
1156
- for (const run of running) {
1157
- // The run resumes itself if it was suspended — a stopped process does not
1158
- // act on SIGTERM until it is continued — records the cause, and answers
1159
- // its own exit. Nothing here has to null a field so that the exit is read
1160
- // correctly, because there is no shared field left to misread.
1161
- run.stop(reason);
1162
- // Nothing is cleared up from here. What this run left open is under its
1163
- // own working name, and the encoding layer removes it when the run's
1164
- // ending reaches it — one place, and it needs neither the stretch nor the
1165
- // init bytes this method used to fetch to judge a file by its contents.
1166
- }
1167
- this.#host.logger.info(`transcode ${session.id} ${running.length} encoder(s) stopped: ${reason}`);
1168
- }
1169
-
1170
- /**
1171
- * What moving the encoder BACKWARDS costs, said out loud when it happens.
1172
- *
1173
- * Nothing already written is lost — every run keeps its own directory and
1174
- * {@link SegmentStore#pathOfName} serves the union of all of them
1175
- * — so the price of a restart is not the files. It is two other things, and
1176
- * neither was ever counted:
1177
- *
1178
- * - **work done twice.** The new run begins at the target and encodes
1179
- * forward through segments the old run had already finished. ffmpeg cannot
1180
- * know they exist, so it makes them again.
1181
- * - **the viewer in front.** While the run walks back up to where it already
1182
- * was, nothing new is being made ahead of them, and their cushion drains.
1183
- *
1184
- * Both are what decides whether a session should be allowed a SECOND
1185
- * concurrent run instead — roadmap item 64. That question cannot be answered
1186
- * from taste, and this is the reading it needs: how often it happens at all,
1187
- * how far back, and how much of the walk is a repeat.
1188
- *
1189
- * Nothing here is awaited by the caller. Everything below the call site is
1190
- * the restart path, which is measured in milliseconds and has been worked on
1191
- * twice to keep it that way; a reading that delays the thing it is reading
1192
- * about is not a reading. The figures that MUST be taken before the new run
1193
- * exists are taken synchronously, and only the file counting is left to run
1194
- * on its own — against the directories that existed at this instant, so what
1195
- * the new run is about to write cannot be counted as already there.
1196
- *
1197
- * @param {HlsSession} session
1198
- * @param {number} startIndex - Where the new run will begin.
1199
- * @returns {void}
1200
- */
1201
- #accountBackwardRestart(session, startIndex) {
1202
- const previousStart = earliestRunStart(this.runsOf(session));
1203
- if (!Number.isInteger(previousStart) || !Number.isInteger(startIndex) || startIndex >= previousStart) {
1204
- // A first run, or one moving forward. Neither costs anything here: a
1205
- // forward restart skips material it never made.
1206
- return;
1207
- }
1208
- const processed = Number(this.progressOf(session)?.processedSeconds);
1209
- const head = Number.isFinite(processed)
1210
- ? Math.max(previousStart, this.#host.outputTimes.segmentIndexForTime(session, processed))
1211
- : previousStart;
1212
- // Bounded: a session an hour in has thousands of segments, and the count is
1213
- // for a comparison, not an inventory.
1214
- const last = Math.min(head, startIndex + BACKWARD_RESTART_SCAN_SEGMENTS);
1215
- const accounting = this.#inputStateFor(session).backwardRestarts;
1216
- accounting.count += 1;
1217
- accounting.segmentsBack += previousStart - startIndex;
1218
- accounting.worstBack = Math.max(accounting.worstBack, previousStart - startIndex);
1219
-
1220
- void (async () => {
1221
- let alreadyOnDisk = 0;
1222
- for (const index of this.#host.producedNumbers(session)) {
1223
- if (index >= startIndex && index <= last) {
1224
- alreadyOnDisk += 1;
1225
- }
1226
- }
1227
- accounting.remade += alreadyOnDisk;
1228
- this.#host.logger.info(
1229
- `transcode ${session.id} moving the encoder BACK from #${previousStart} to #${startIndex} ` +
1230
- `(head was #${head}): ${alreadyOnDisk} of the ${last - startIndex + 1} segment(s) it will walk through ` +
1231
- `are already on disk and will be made again, and nothing is produced ahead of #${head} until it gets ` +
1232
- `back there — ${accounting.count} backward restart(s) this session, worst ${accounting.worstBack} ` +
1233
- `segment(s) back, ${accounting.remade} segment(s) remade in total (roadmap 64)`
1234
- );
1235
- })().catch(() => {
1236
- // silent-ok: a reading that fails is not worth ending a restart over.
1237
- });
1238
- }
1239
- }
1
+ /**
2
+ * The encoders of this proxy, from the plan's decision to the end of the process.
3
+ *
4
+ * The plan (`EncodePlan`, through `EncodeOrchestrator`) decides where a run goes;
5
+ * this builds it with the arguments its output needs, follows what it produces,
6
+ * says how far it got, and accounts for how it ended. Nothing here decides where
7
+ * an encoder should be.
8
+ */
9
+
10
+ import path from "node:path";
11
+ import { spawn } from "node:child_process";
12
+ import { contentionPenalty } from "./contention.js";
13
+ import { ENCODE_RUN_STATE, liveRunsOf, runStateOf, wireState } from "./encode-run-state.js";
14
+ import { ENCODE_EXIT } from "./encode-exit.js";
15
+ import { EncodeRun } from "./EncodeRun.js";
16
+ import { computeOutputDimensions } from "./args.js";
17
+ import { buildRunCommand, trueStartOf } from "./run-command.js";
18
+ import { cutOf, judgePiece } from "./piece-completeness.js";
19
+
20
+ /**
21
+ * @typedef {Object} SegmentFiles
22
+ * @property {(address: string) => string} pathFor
23
+ * @property {(address: string) => Buffer | null} initOf
24
+ * @property {(address: string) => string} directoryFor
25
+ * @property {(address: string, makingName: string, format: object, read?: { mediaRanges?: object | null }) => string | null} publish
26
+ * @property {(address: string, makingName: string) => Buffer} closedBytesOf
27
+ * @property {(address: string, index: number, where?: { startSeconds?: number }) => object | undefined} mediaRangesOf
28
+ * @property {(address: string, index: number, because: string) => void} remove
29
+ */
30
+ // How far the accounting of a backward restart looks for work about to be done
31
+ // twice. It runs on the restart path and a session an hour in has thousands of
32
+ // segments; the figure is for a comparison, not an inventory.
33
+ const BACKWARD_RESTART_SCAN_SEGMENTS = 300;
34
+ const PROGRESS_LOG_INTERVAL_MS = 5_000;
35
+ /**
36
+ * Format a seconds value as `HH:MM:SS`, or `"n/a"` if not finite.
37
+ *
38
+ * @param {number} seconds
39
+ * @returns {string}
40
+ */
41
+ export function formatSeconds(seconds) {
42
+ if (!Number.isFinite(seconds) || seconds < 0) {
43
+ return "n/a";
44
+ }
45
+ const total = Math.floor(seconds);
46
+ const hours = Math.floor(total / 3600);
47
+ const minutes = Math.floor((total % 3600) / 60);
48
+ const rest = total % 60;
49
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
50
+ }
51
+ /**
52
+ * Where this session's encoding begins: the earliest number any live run of it
53
+ * was given.
54
+ *
55
+ * @param {object[] | Set<object>} runs
56
+ * @returns {number | null}
57
+ */
58
+ export function earliestRunStart(runs) {
59
+ const live = liveRunsOf(runs);
60
+ return live.length > 0 ? live[0].from : null;
61
+ }
62
+ /**
63
+ * The live run of this session that was given this number, if any.
64
+ *
65
+ * A run with an explicit stretch owns the whole of it. One WITHOUT an end owns
66
+ * only as far as it has actually got: claiming the rest of the film would make
67
+ * it the owner of every number in front of it, including ones another run was
68
+ * expressly given.
69
+ *
70
+ * @param {object[] | Set<object>} runs
71
+ * @param {number} index
72
+ * @returns {object | null}
73
+ */
74
+ function ownRunMaking(runs, index) {
75
+ let answer = null;
76
+ for (const run of liveRunsOf(runs)) {
77
+ if (run.from > index) {
78
+ break; // Ordered by start, so nothing further can hold this number.
79
+ }
80
+ if (Number.isInteger(run.to) && run.to >= run.from && index > run.to) {
81
+ continue; // Its stretch ends before this number.
82
+ }
83
+ answer = run;
84
+ }
85
+ return answer;
86
+ }
87
+
88
+ /**
89
+ * Whether an encoder run died because its INPUT went away, rather than because
90
+ * of anything about the encode itself.
91
+ *
92
+ * These are the messages the read path and ffmpeg's HTTP client produce when
93
+ * the torrent is gone, being re-added, or has no data for the range yet — all
94
+ * of them temporary by nature: the source can be added again and the pieces
95
+ * fetched again.
96
+ *
97
+ * @param {string} message
98
+ * @returns {boolean}
99
+ */
100
+ export function isInputUnavailable(message) {
101
+ const text = typeof message === "string" ? message : "";
102
+ return (
103
+ /Error reading HTTP response/i.test(text) ||
104
+ /not found in (?:magnet|torrent):/i.test(text) ||
105
+ /Unknown source/i.test(text) ||
106
+ /is gone and cannot be re-added/i.test(text) ||
107
+ /Read error at pos/i.test(text) ||
108
+ /Server returned 5\d\d/i.test(text) ||
109
+ /Input\/output error/i.test(text) ||
110
+ /Connection reset by peer/i.test(text) ||
111
+ /End of file/i.test(text)
112
+ );
113
+ }
114
+
115
+ /**
116
+ * The ffmpeg command as one readable line.
117
+ *
118
+ * Everything is shown as passed except the list of cut times, which is one
119
+ * value per segment — 830 of them on a two-hour film, about 7 KB of log for a
120
+ * single run, repeated on every restart. The count and the two ends say
121
+ * everything the list is ever consulted for: whether cutting was explicit at
122
+ * all, how far it reaches, and where it starts.
123
+ *
124
+ * @param {string[]} args
125
+ * @returns {string}
126
+ */
127
+ export function describeFfmpegArgs(args) {
128
+ const parts = [];
129
+ for (let index = 0; index < args.length; index += 1) {
130
+ const value = args[index];
131
+ // Both take the same list, and a keyframe-grid variant passes it twice.
132
+ // `-force_key_frames` also takes an expression, which is short and is left
133
+ // alone — only a list is folded.
134
+ if (
135
+ (value === "-segment_times" || value === "-force_key_frames") &&
136
+ typeof args[index + 1] === "string" &&
137
+ args[index + 1].includes(",")
138
+ ) {
139
+ const times = args[index + 1].split(",");
140
+ parts.push(value, `<${times.length} cuts ${times[0]}..${times[times.length - 1]}>`);
141
+ index += 1;
142
+ continue;
143
+ }
144
+ parts.push(value);
145
+ }
146
+ return parts.join(" ");
147
+ }
148
+
149
+ export class EncodeRuns {
150
+ #inputState = new WeakMap();
151
+
152
+ /**
153
+ * Live runs by the number their input reads carry, so the stream route can
154
+ * say which run's input is waiting.
155
+ *
156
+ * @type {Map<number, import("./EncodeRun.js").EncodeRun>}
157
+ */
158
+ #runsByInputToken = new Map();
159
+
160
+ #lastInputToken = 0;
161
+ /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
162
+ #host;
163
+
164
+ /**
165
+ * Whether a re-decision of what encoders should exist is already queued for
166
+ * the end of this turn. See `planEncodersSoon`.
167
+ * @type {boolean}
168
+ */
169
+ #planScheduled = false;
170
+
171
+ /**
172
+ * @param {object} host - `logger`, `viewerSecondsOn`, `noteRunSpeedMeasured`, `inputOf`, `producedNumbers`, `servesAudioSeparately`, `disposeSession`, `contentionPenalties`, `encodeCost`, `encodeOrchestrator`, `encoders`, `ffmpegBin`, `outputTimes`, `outputs`, `priority`, `segmentDurationSec`, `segmentFiles`, `videoEncoder`
173
+ * @param {(session: object, run: object) => void} [host.noteRunSpeedMeasured] -
174
+ * A run of this output has measured its processing speed.
175
+ * @param {(session: object, runToken: number) => object} host.inputOf - The
176
+ * addresses a run reads; `runToken` marks them as that run's.
177
+ * @param {SegmentFiles} host.segmentFiles - The storage operations used to
178
+ * write and inspect output files.
179
+ */
180
+ constructor(host) {
181
+ this.#host = host;
182
+ }
183
+
184
+ #inputStateFor(output) {
185
+ let state = this.#inputState.get(output);
186
+ if (!state) {
187
+ state = {
188
+ readWindowBytes: 0,
189
+ inputRetryCount: 0,
190
+ backwardRestarts: { count: 0, segmentsBack: 0, worstBack: 0, remade: 0 },
191
+ firstWantedAt: new Map(),
192
+ /** Bytes the swarm has delivered to this output's own input reads. */
193
+ inputBytes: 0,
194
+ /** The mismatch between the held init and the run's size last said, so it is said once. */
195
+ initSizeSaid: ""
196
+ };
197
+ this.#inputState.set(output, state);
198
+ }
199
+ return state;
200
+ }
201
+
202
+ setReadWindow(output, bytes) {
203
+ this.#inputStateFor(output).readWindowBytes = Number.isFinite(bytes) ? bytes : 0;
204
+ }
205
+
206
+ readWindowFor(output) {
207
+ return this.#inputStateFor(output).readWindowBytes;
208
+ }
209
+
210
+ noteWanted(output, index, at = Date.now()) {
211
+ const wanted = this.#inputStateFor(output).firstWantedAt;
212
+ if (!wanted.has(index)) wanted.set(index, at);
213
+ }
214
+
215
+ resetInputRetry(output) {
216
+ this.#inputStateFor(output).inputRetryCount = 0;
217
+ }
218
+
219
+ /**
220
+ * Count bytes the swarm has delivered to one output's own input read.
221
+ *
222
+ * Called by the `/stream` route for every fragment it writes to an encoder.
223
+ * Cheap on purpose — one addition, no clock, no log — because it runs per
224
+ * fragment on the path that feeds ffmpeg.
225
+ *
226
+ * @param {string} outputId
227
+ * @param {number} bytes
228
+ * @returns {void}
229
+ */
230
+ noteInputBytes(outputId, bytes) {
231
+ if (!outputId || !(bytes > 0)) {
232
+ return;
233
+ }
234
+ const output = this.#host.outputs.get(outputId);
235
+ if (output) {
236
+ this.#inputStateFor(output).inputBytes += bytes;
237
+ }
238
+ }
239
+
240
+ /**
241
+ * An input read of one run starts or stops waiting for bytes. Called by the
242
+ * `/stream` route around every wait for the next part of the file; see
243
+ * `RunClock` for what the time is used for.
244
+ *
245
+ * @param {number} runToken - From the read's own URL.
246
+ * @param {boolean} waiting
247
+ * @returns {void}
248
+ */
249
+ noteInputWaiting(runToken, waiting) {
250
+ const run = this.#runsByInputToken.get(runToken);
251
+ if (!run) {
252
+ return;
253
+ }
254
+ if (waiting) {
255
+ run.inputWaitBegins();
256
+ } else {
257
+ run.inputWaitEnds();
258
+ }
259
+ }
260
+
261
+ /**
262
+ * @param {object} output
263
+ * @returns {number}
264
+ */
265
+ inputBytesOf(output) {
266
+ return output ? this.#inputStateFor(output).inputBytes : 0;
267
+ }
268
+
269
+ runsOf(output) {
270
+ return output ? this.#host.encodeOrchestrator.runsOn(output.outputKey) : [];
271
+ }
272
+
273
+ /**
274
+ * Where the earliest live encoder of this output began, or null with none.
275
+ *
276
+ * @param {object} output
277
+ * @returns {number | null}
278
+ */
279
+ earliestStartOf(output) {
280
+ return earliestRunStart(this.runsOf(output));
281
+ }
282
+
283
+ isLive(output) {
284
+ return Boolean(output && this.#host.outputs.get(output.id) === output);
285
+ }
286
+
287
+ liveRunsOf(output) {
288
+ return liveRunsOf(this.runsOf(output));
289
+ }
290
+
291
+ runStateOf(output) {
292
+ return output ? this.#host.encodeOrchestrator.stateOf(output.outputKey) : runStateOf([]);
293
+ }
294
+
295
+ lastErrorOf(output) {
296
+ return output ? this.#host.encodeOrchestrator.errorOf(output.outputKey) : "";
297
+ }
298
+
299
+ /**
300
+ * Whether this output's encoding has failed for good.
301
+ *
302
+ * @param {object} output
303
+ * @returns {boolean}
304
+ */
305
+ hasFailed(output) {
306
+ return this.runStateOf(output) === ENCODE_RUN_STATE.ENDED_FAILED;
307
+ }
308
+
309
+ /**
310
+ * Whether this output's input went away and is being fetched again.
311
+ *
312
+ * @param {object} output
313
+ * @returns {boolean}
314
+ */
315
+ isWaitingForInput(output) {
316
+ return this.runStateOf(output) === ENCODE_RUN_STATE.RETRY_WAIT;
317
+ }
318
+
319
+ /**
320
+ * The run state in the words the browser is told.
321
+ *
322
+ * @param {object} output
323
+ * @returns {string}
324
+ */
325
+ wireStateOf(output) {
326
+ return wireState(this.runStateOf(output));
327
+ }
328
+
329
+ /**
330
+ * What went wrong, when this output's encoding has failed; empty otherwise.
331
+ *
332
+ * @param {object} output
333
+ * @returns {string}
334
+ */
335
+ failureOf(output) {
336
+ return this.hasFailed(output) ? this.lastErrorOf(output) : "";
337
+ }
338
+
339
+ /**
340
+ * The media intervals of a closed file that holds the whole of its piece,
341
+ * null where its format reads none, or false where it is not to be published:
342
+ * short of its cut, without playable media, or unreadable.
343
+ *
344
+ * @param {HlsSession} session
345
+ * @param {string} name - The working name the encoder closed it under.
346
+ * @param {number} index
347
+ * @returns {object | null | false}
348
+ */
349
+ #wholeClosedPiece(session, name, index) {
350
+ const format = session.segmentFormat;
351
+ if (!format?.readMediaRanges || !Number.isInteger(index) || index < 0) {
352
+ return null;
353
+ }
354
+ const address = session.outputKey ?? "";
355
+ try {
356
+ const mediaRanges = format.readMediaRanges(this.#host.segmentFiles.closedBytesOf(address, name));
357
+ const cut = cutOf(session.timeline, index);
358
+ const { whole, throughSeconds } = judgePiece(format, mediaRanges, cut);
359
+ if (!whole) {
360
+ this.#host.logger.warn(
361
+ `encode: not publishing piece ${index} of ${address.slice(0, 60)}: ` +
362
+ (throughSeconds === null ? "it holds no playable media" : `produced through ${throughSeconds}s, cut ${cut}s`)
363
+ );
364
+ return false;
365
+ }
366
+ return mediaRanges;
367
+ } catch (error) {
368
+ this.#host.logger.warn(`encode: could not read the media of ${name}: ${error instanceof Error ? error.message : String(error)}`);
369
+ return false;
370
+ }
371
+ }
372
+
373
+ /**
374
+ * The media intervals of a stored piece of this output that holds the whole
375
+ * of its stretch, or undefined. A stored piece short of its cut — left by an
376
+ * earlier process — is taken off the disk here, where its cut is known.
377
+ *
378
+ * @param {HlsSession} output
379
+ * @param {number} index
380
+ * @returns {object | undefined}
381
+ */
382
+ finishedMediaRangesOf(output, index) {
383
+ const address = output.outputKey ?? "";
384
+ const timeline = output.timeline;
385
+ const ranges = this.#host.segmentFiles.mediaRangesOf(address, index, {
386
+ startSeconds: timeline.publishedStartOf(index)
387
+ });
388
+ if (!ranges || !output.segmentFormat?.producedThroughSeconds) {
389
+ return ranges;
390
+ }
391
+ const cut = cutOf(timeline, index);
392
+ const { whole, throughSeconds } = judgePiece(output.segmentFormat, ranges, cut);
393
+ if (whole || throughSeconds === null) {
394
+ return ranges;
395
+ }
396
+ this.#host.segmentFiles.remove(address, index, `produced through ${throughSeconds}s, short of its cut at ${cut}s`);
397
+ return undefined;
398
+ }
399
+
400
+ progressOf(output, index = null) {
401
+ if (!output) {
402
+ return null;
403
+ }
404
+ const at = Number.isInteger(index)
405
+ ? index
406
+ : this.#host.outputTimes.segmentIndexForTime(output, this.#host.viewerSecondsOn(output));
407
+ const progress = this.#host.encodeOrchestrator.progressOf(output.outputKey, at);
408
+ if (progress) {
409
+ return progress;
410
+ }
411
+ const start = this.#host.viewerSecondsOn(output);
412
+ const total = Number(output.file?.durationSeconds);
413
+ return {
414
+ processedSeconds: start,
415
+ startPositionSeconds: start,
416
+ totalSeconds: Number.isFinite(total) && total > 0 ? total : null,
417
+ percent: 0,
418
+ remainingSeconds: Number.isFinite(total) && total > 0 ? Math.max(0, total - start) : null,
419
+ updatedAt: this.#host.outputs.startedAt(output) ?? Date.now()
420
+ };
421
+ }
422
+
423
+ planEncodersNow() {
424
+ const byOutput = this.#outputsWithSessions();
425
+ for (const [address, sessions] of byOutput) {
426
+ // From the TIMELINE, which is where how a file is cut has lived since
427
+ // 2.76.0. Read off the session it left, this was `undefined` on every
428
+ // session ever made: the map then held no length, and the walk that
429
+ // gives a run its end ran to MAX_SAFE_INTEGER — the main thread spun at
430
+ // 100% and the proxy answered nothing, measured on the addon host
431
+ // 2026-09-05 with the stack read out of the live process.
432
+ const segmentCount = Number(sessions[0].timeline?.segmentCount) || 0;
433
+ if (segmentCount > 0) {
434
+ this.#host.encodeOrchestrator.setSegmentCount(address, segmentCount);
435
+ }
436
+ }
437
+ // THE MAP IS BUILT ONCE, IN ITS OWN LAYER, AND BOTH SIDES READ THAT ONE.
438
+ //
439
+ // It used to be built twice: once here, per viewer, converted and stated to
440
+ // the encoding as a window each, and once again inside `publishFor` for the
441
+ // downloading. Two answers to one question, and the encoding's copy carried
442
+ // the viewer's NAME as the key of a claim — against the rule that the
443
+ // encoding and the viewer are not connected at all.
444
+ this.#host.priority.publishFor({
445
+ sessionGroups: byOutput.values(),
446
+ });
447
+ // FROM THE VIEWERS OF THAT OUTPUT, not from the viewers of the film.
448
+ //
449
+ // Both scopes are right for what asks them: the swarm is asked for bytes of
450
+ // a FILE, which every output of it reads, and encoders are placed per
451
+ // OUTPUT, which a person watching 480p wants nothing of at 1080p. Handed the
452
+ // film's map, the plan wanted an encoder on every output of it, and what
453
+ // stopped the unwatched ones was this class killing them by its own
454
+ // judgement — while the viewer's own move announced itself and had the plan
455
+ // start them again.
456
+ //
457
+ // Converted into each output's own numbering, because two outputs of one
458
+ // film are cut independently and the same second is a different number in
459
+ // each: 454 pieces against 401 on the field file.
460
+ for (const [address, sessions] of byOutput) {
461
+ const timeline = sessions[0].timeline;
462
+ this.#host.encodeOrchestrator.notePriorityMap(
463
+ address,
464
+ timeline?.inSegments?.(
465
+ this.#host.priority.mapForOutput(address),
466
+ Number(timeline?.segmentCount) || 0
467
+ ) ?? []
468
+ );
469
+ }
470
+ this.#host.encodeOrchestrator.reconcile();
471
+ }
472
+
473
+ /**
474
+ * Re-decide what encoders should exist, once, after the change that is being
475
+ * made now.
476
+ *
477
+ * COALESCED, NOT DELAYED. One turn of the event loop may carry several
478
+ * changes — a viewer arrives and is placed and states their soundtrack — and
479
+ * each of them is a reason to re-decide, while re-deciding three times in a
480
+ * row would give the same answer three times and could act on a half-built
481
+ * state. So the decision is taken once, after the current turn, and no
482
+ * interval is involved: there is nothing to choose and nothing to tune.
483
+ *
484
+ * @returns {void}
485
+ */
486
+ planEncodersSoon() {
487
+ if (this.#planScheduled) {
488
+ return;
489
+ }
490
+ this.#planScheduled = true;
491
+ queueMicrotask(() => {
492
+ this.#planScheduled = false;
493
+ try {
494
+ this.planEncodersNow();
495
+ } catch (error) {
496
+ const message = error instanceof Error ? error.message : String(error);
497
+ this.#host.logger.warn(`transcode could not re-plan encoders: ${message}`);
498
+ }
499
+ });
500
+ }
501
+
502
+ /**
503
+ * The live sessions grouped by the output they produce.
504
+ *
505
+ * @returns {Map<string, HlsSession[]>}
506
+ */
507
+ #outputsWithSessions() {
508
+ /** @type {Map<string, HlsSession[]>} */
509
+ const byOutput = new Map();
510
+ for (const session of this.#host.outputs.values()) {
511
+ const address = session.outputKey ?? "";
512
+ if (!address) {
513
+ continue;
514
+ }
515
+ byOutput.set(address, [...(byOutput.get(address) ?? []), session]);
516
+ }
517
+ return byOutput;
518
+ }
519
+
520
+ forgetEncodingOfGone(output) {
521
+ if (this.#host.outputs.outputsOn(output.outputKey).length === 0) {
522
+ this.#host.encodeOrchestrator.forgetOutput(output.outputKey);
523
+ }
524
+ }
525
+
526
+ /**
527
+ * Make an encoder for this output, beginning at this segment.
528
+ *
529
+ * Another run of the SAME session, not another session. A run at another
530
+ * position is not a different output — the material, the tracks, the grid and
531
+ * the box are all the same, and only where it begins differs, which changes
532
+ * no byte of what is produced. Both write into the output's one directory and
533
+ * either viewer is served whatever either has made.
534
+ *
535
+ * @param {string} address
536
+ * @param {number} from
537
+ * @param {number} to
538
+ * @param {string} because - The plan's own words for why it placed this one.
539
+ * @returns {object | null}
540
+ */
541
+ makeRunAt(address, from, to, because) {
542
+ let base = null;
543
+ for (const session of this.#host.outputs.values()) {
544
+ if (session.outputKey === address) {
545
+ base = session;
546
+ break;
547
+ }
548
+ }
549
+ if (!base) {
550
+ return null;
551
+ }
552
+ // A position that has already failed to start, this many times running,
553
+ // will fail again: nothing about it has changed between the attempts, which
554
+ // is exactly why the attempts keep taking the same fraction of a second and
555
+ // ending the same way.
556
+ //
557
+ // The plan is arithmetic over coverage and demand, and neither of them
558
+ // knows that a process refused to start — so without asking here, the plan
559
+ // commands the same start, the run ends, the ended stretch goes back to the
560
+ // map, and the plan commands it again. Measured 2026-09-05 with ffmpeg
561
+ // absent: fifty passes of the plan in the time a probe took to notice, as
562
+ // fast as spawning could fail. The five-second timer this decision used to
563
+ // sit on hid that, at the price of hiding it in the field too — the loop
564
+ // seen there ran for sixteen minutes and read as "a restart every five
565
+ // seconds".
566
+ //
567
+ // A DIFFERENT position is unaffected and gets its own budget, and the count
568
+ // resets the moment a run at this one does real work.
569
+ if (!this.#host.encodeOrchestrator.mayStartAt(address, from)) {
570
+ return null;
571
+ }
572
+ // The encoder is built and handed back in this same call. Nothing here
573
+ // waits: the one thing this path used to wait for was the death of the run
574
+ // it was replacing, and that killing is gone. Answering with nothing while
575
+ // the encoder was built behind the answer is what let the same stretch be
576
+ // started over and over — 684 starts in 482 seconds of field 2026-09-05.
577
+ try {
578
+ return this.#startEncodeRun(base, from, because, { to });
579
+ } catch (error) {
580
+ const message = error instanceof Error ? error.message : String(error);
581
+ this.#host.logger.warn(`transcode could not start a run at #${from} of ${address}: ${message}`);
582
+ return null;
583
+ }
584
+ }
585
+
586
+ /**
587
+ * How many encoders this machine can afford on one output at once.
588
+ *
589
+ * Measured rather than chosen, and it is the same arithmetic that decides
590
+ * which quality steps are offered: what a second job costs here is not
591
+ * assumed to be nothing. Field 2026-09-03 on the addon host, `testsrc2`
592
+ * through libx264 `ultrafast` — at 854x480 one run makes 7.12x and two make
593
+ * 4.20x and 4.16x, so both stay far above realtime and a second is
594
+ * affordable; at 1920x1080 one makes 1.96x and two make 0.99x and 0.98x, so
595
+ * the machine is full at one.
596
+ *
597
+ * @param {string} address
598
+ * @returns {number}
599
+ */
600
+ maxRunsForOutput(address) {
601
+ const alone = this.#host.encodeCost.speedForOutput(address);
602
+ if (!(alone > 0)) {
603
+ // The host measured nothing at all, which is a broken startup rather than
604
+ // a state to plan around. One encoder is what it keeps.
605
+ return 1;
606
+ }
607
+ let affordable = 1;
608
+ for (;;) {
609
+ const { penalty, measured, from } = contentionPenalty(affordable, this.#host.contentionPenalties);
610
+ // An UNMEASURED penalty is 1, and that is the honest answer to "what does
611
+ // a second job cost" only in the sense that nothing has been measured —
612
+ // it is not a statement that a second job is free. Measured on the addon
613
+ // host it is 1.70x at 854x480 and 1.98x at 1920x1080, so taking 1 would
614
+ // let a machine that cannot hold two runs start two. Where nothing has
615
+ // been measured, one is what it has.
616
+ //
617
+ // `from` is the concurrency the reading came from, and past the measured
618
+ // range `contentionPenalty` HOLDS the largest reading rather than continue
619
+ // a curve two points cannot describe. Held is the right answer to "what
620
+ // does this cost", and the wrong one to "may I start another": it would
621
+ // price a fifth encoder at what a second was measured to cost, and a fast
622
+ // host would keep dividing until some chosen ceiling stopped it. So the
623
+ // ladder stops where the measurements stop — the bound on how many
624
+ // encoders may run is measured, like the budget itself, and there is no
625
+ // constant here to overrule it.
626
+ if (!measured || from !== affordable || !(alone / penalty >= 1)) {
627
+ break;
628
+ }
629
+ affordable += 1;
630
+ }
631
+ return affordable;
632
+ }
633
+
634
+ /**
635
+ * A segment this run made has just been served.
636
+ *
637
+ * The one event whose raising is guarded by the state, and the guard is a
638
+ * READ of the state rather than a second copy of it: "something has been
639
+ * produced" is a level, not an edge, so without the guard every served
640
+ * segment would raise it and the log would fill with refusals.
641
+ *
642
+ * Whose file it is decides the rest, and the directory answers that outright:
643
+ * runs write into one each, and serving searches them newest-first, so a
644
+ * segment left by an EARLIER run is served routinely. Comparing indices
645
+ * instead would have been fooled by the ordinary case of a backward seek —
646
+ * the new run starts at #10, the old one left #50 on disk, and #50 is above
647
+ * the new run's start index while saying nothing about it.
648
+ *
649
+ * @param {HlsSession} session
650
+ * @param {string} filePath - Where the served segment was actually found.
651
+ * @returns {void}
652
+ */
653
+ noteRunProducedSegment(session, filePath) {
654
+ if (typeof filePath !== "string" || path.dirname(filePath) !== this.#host.segmentFiles.pathFor(session.outputKey ?? "")) {
655
+ return;
656
+ }
657
+ const index = session.segmentFormat.segmentIndexFromName(path.basename(filePath));
658
+ if (index === null) {
659
+ return;
660
+ }
661
+ // Whichever run was given this number. An output has as many runs as the
662
+ // machine affords, and a segment moves the one it belongs to out of
663
+ // starting — not whichever happens to be listed first.
664
+ ownRunMaking(this.runsOf(session), index)?.noteProduced(index);
665
+ }
666
+
667
+ /**
668
+ * Say so when a run is about to encode a picture the init segment already in
669
+ * the player's hands does not describe.
670
+ *
671
+ * This is the whole class of fault named in one line, and it exists because
672
+ * the fault is otherwise SILENT: no layer reports an error, the encoder is
673
+ * healthy, segments are served in milliseconds, and what the viewer gets is
674
+ * either a band of macroblock garbage or a picture that never appears. The
675
+ * shape is the one 2.48.0 uses for the TIME a run begins at — a run states
676
+ * where it really landed, and a disagreement with what was published is
677
+ * named rather than left to be inferred from a browser's own reading.
678
+ *
679
+ * The size the init describes is read from the init's own bytes, not taken
680
+ * from our record of what the encoder was told, because those two disagreeing
681
+ * IS the fault. The size the run will produce is computed by the same
682
+ * arithmetic the scale filter performs, so a source smaller than the target
683
+ * box is not reported as a disagreement.
684
+ *
685
+ * Said once per distinct pair of sizes: a run repeated at the same wrong size
686
+ * has nothing further to say.
687
+ *
688
+ * @param {HlsSession} session
689
+ * @returns {void}
690
+ */
691
+ #warnIfRunLeavesTheInitBehind(session) {
692
+ const initBytes = this.#host.segmentFiles.initOf(session.outputKey ?? "");
693
+ if (!session.spec.transcodesVideo || !initBytes || initBytes.length === 0) {
694
+ return; // nothing served yet, or nothing being encoded
695
+ }
696
+ const format = session.segmentFormat;
697
+ if (typeof format?.initVideoSize !== "function") {
698
+ return; // a self-describing container (MPEG-TS) cannot have this fault
699
+ }
700
+ const described = format.initVideoSize(initBytes);
701
+ if (!described) {
702
+ return;
703
+ }
704
+ if (!(session.output.encodeWidth > 0) || !(session.output.encodeHeight > 0)) {
705
+ return; // the run keeps the encoder's own default box; nothing was told
706
+ }
707
+ const producing = computeOutputDimensions(
708
+ session.output.encodeWidth,
709
+ session.output.encodeHeight,
710
+ session.file.width,
711
+ session.file.height
712
+ );
713
+ if (!producing) {
714
+ return; // the source size is unknown, so nothing can be predicted
715
+ }
716
+ if (described.width === producing.w && described.height === producing.h) {
717
+ return;
718
+ }
719
+ const said = `${described.width}x${described.height}->${producing.w}x${producing.h}`;
720
+ const inputState = this.#inputStateFor(session);
721
+ if (inputState.initSizeSaid === said) {
722
+ return;
723
+ }
724
+ inputState.initSizeSaid = said;
725
+ this.#host.logger.warn(
726
+ `transcode ${session.id} is about to encode ${producing.w}x${producing.h} while the init segment ` +
727
+ `the player holds describes ${described.width}x${described.height} "${session.file.name}" — ` +
728
+ `every fragment of this run will be decoded against parameter sets for a picture that is not ` +
729
+ `being made. A change of size is a change of variant; nothing here should have moved it.`
730
+ );
731
+ }
732
+
733
+ /**
734
+ * How far a run starting here may work before it meets somebody else's
735
+ * material — read off the ONE coverage map, never worked out again here.
736
+ *
737
+ * This replaced `planRunInterval`, which was a second authority over the same
738
+ * question and answered it by different rules: it walked the whole track for
739
+ * the first free number, MOVED the start there itself, and counted every live
740
+ * run as claiming up to `head + look-ahead`. Measured in the field
741
+ * 2026-09-05: the plan commanded a start at #46, this moved it to #78 — the
742
+ * "run moved forward from #46 to #78" line — and the plan, seeing a run
743
+ * outside the window it had asked for, killed it as unwanted and commanded
744
+ * the same start again, 350-700ms per cycle, dozens of times, the viewer's
745
+ * picture stopped for 125 seconds.
746
+ *
747
+ * Where a run STARTS is the plan's decision and arrives here as an argument.
748
+ * All this answers is where it must stop, and the answer is a fact of the
749
+ * map: the free stretch from that number on. `-1` means the end of the track,
750
+ * which is what "no end" is written as everywhere here.
751
+ *
752
+ * @param {object} session
753
+ * @param {number} startIndex
754
+ * @param {object | null} exceptRun - The run being replaced, whose own claim
755
+ * is not somebody else's material.
756
+ * @returns {number} The last number to work through, or `-1` for the end.
757
+ */
758
+ #runEndFrom(session, startIndex, exceptRun = null) {
759
+ return this.#host.encodeOrchestrator.freeStretchEnd({
760
+ address: session.outputKey ?? "",
761
+ from: startIndex,
762
+ exceptRun,
763
+ segmentCount: Number(session.timeline?.segmentCount) || 0
764
+ });
765
+ }
766
+
767
+ // Returns the encoder it built, or nothing when there was nothing to build.
768
+ // It waits for nothing: the one thing it used to wait for was the death of
769
+ // the run it was replacing, and that killing is gone.
770
+ #startEncodeRun(session, startIndex, because, ordered = null) {
771
+ if (!this.isLive(session)) {
772
+ return null;
773
+ }
774
+ // Where a restart's seconds go. A seek costs 5-8 s in the field and the
775
+ // recorded reason — waiting for the previous ffmpeg to exit, measured at
776
+ // 0.54-1.47 s — does not account for it. Before rebuilding the hottest path
777
+ // in the proxy on a guess, make each stage state its own cost.
778
+ const restartEnteredAt = Date.now();
779
+ // Reads where the old run began BEFORE the new one takes its place, and
780
+ // does not await: everything below is the restart path, which is measured
781
+ // in milliseconds and has been worked on twice to keep it that way.
782
+ this.#accountBackwardRestart(session, startIndex);
783
+ // STARTING AN ENCODER STOPS NOTHING. It used to stop any live run whose own
784
+ // start was not below this one's — a rule left over from when a session
785
+ // held exactly one run and "the previous one" meant "the only one". Once a
786
+ // an output could hold several, that rule began killing runs the plan had
787
+ // decided to keep: 294 stops for this reason in eight minutes of field
788
+ // 2026-09-05, against four starts asked for by a viewer. Who is stopped is
789
+ // decided in one place, and it is not this one.
790
+ //
791
+ // HOW FAR IT MAY WORK is decided by the same one place and arrives here as
792
+ // an argument. Reading it off the coverage map a second time was the last
793
+ // remaining second answer to that question: the plan computed `to`, passed
794
+ // it, and the parameter list did not name it.
795
+ const runEnd = Number.isInteger(ordered?.to)
796
+ ? ordered.to
797
+ : this.#runEndFrom(session, startIndex, null);
798
+ // The restart backs off a segment or two from what was asked for, so the
799
+ // request that prompted it is recorded under a HIGHER index than the run
800
+ // starts at. Looking it up by the start index alone found nothing and the
801
+ // line never printed once.
802
+ let wantedAt = null;
803
+ const inputState = this.#inputStateFor(session);
804
+ for (const [index, at] of inputState.firstWantedAt) {
805
+ if (index >= startIndex && (wantedAt === null || at < wantedAt)) {
806
+ wantedAt = at;
807
+ }
808
+ }
809
+ if (typeof wantedAt === "number") {
810
+ this.#host.logger.info(
811
+ `transcode ${session.id} restart for #${startIndex} decided ` +
812
+ `${restartEnteredAt - wantedAt}ms after it was first asked for`
813
+ );
814
+ }
815
+ // Cleared with the run that could not answer them. These are "how long has
816
+ // this segment gone unanswered", and the question only means anything about
817
+ // the run in force: a timestamp kept from an abandoned scan probe minutes
818
+ // ago says a fresh request has already waited long enough, which is how the
819
+ // behind-head repair came to fire on the very first poll instead of waiting
820
+ // for the seek that should move the encoder. It also stops the map growing
821
+ // for the life of a session.
822
+ inputState.firstWantedAt.clear();
823
+ // WHERE THIS NUMBER REALLY BEGINS, when a produced piece has said so and
824
+ // the table the player holds still says otherwise.
825
+ //
826
+ // Only a soundtrack, and only because a soundtrack has no keyframes: it
827
+ // begins exactly where it is asked to, to within one audio frame, while the
828
+ // picture can begin nowhere but a real keyframe and so moves forward to the
829
+ // next one — up to three seconds, measured 2026-08-17. Left at the published
830
+ // time, the sound of one film starts up to that far from its picture after
831
+ // every restart, each correctly labelled with where it really is, and the
832
+ // viewer gets sound with no new picture for the difference.
833
+ //
834
+ // DERIVED HERE rather than handed in. It used to arrive as an argument from
835
+ // the one caller that knew it — the correction that had just measured it —
836
+ // which meant the instant was only ever right for a run that caller
837
+ // started. Any run the plan placed at a corrected number got the published
838
+ // time and landed apart again. It is a fact of the FILE's cutting, held in
839
+ // the live table every session of the file shares, so it is read from
840
+ // there.
841
+ const positionSecondsOverride = session.spec.carries === "audio-only"
842
+ ? trueStartOf(session.timeline, startIndex)
843
+ : undefined;
844
+
845
+ // What is still read off the session for a run. The list is the measure of
846
+ // how far a session still is from being the three things a run is built
847
+ // from — the material, what is produced of it, and the stretch — and it
848
+ // shrinks in place as those are taken off. There is deliberately no method
849
+ // wrapping it: a named adapter with one caller is a thing to remember to
850
+ // delete, and this is a thing that disappears by being emptied.
851
+ this.#lastInputToken += 1;
852
+ const inputToken = this.#lastInputToken;
853
+ const inputs = this.#host.inputOf(session, inputToken);
854
+ const { args, safeIndex, startSeconds, cutTimes } = buildRunCommand({
855
+ keyframes: session.keyframes,
856
+ inputFile: inputs.inputFile,
857
+ audioFile: inputs.audioFile,
858
+ inputUrl: inputs.inputUrl,
859
+ audioInputUrl: inputs.audioInputUrl,
860
+ timeline: session.timeline,
861
+ output: session.output,
862
+ segmentFormat: session.segmentFormat,
863
+ transcodeVideo: session.spec.transcodesVideo,
864
+ transcodeAudio: session.spec.transcodesAudio,
865
+ audioOnly: session.spec.carries === "audio-only",
866
+ audioSeparate: this.#host.servesAudioSeparately(session),
867
+ audioSourceTrackIndex: session.spec.audioSourceTrackIndex,
868
+ rateControl: session.spec.video?.encode?.rateControl ?? null,
869
+ startIndex,
870
+ endIndex: runEnd,
871
+ positionSecondsOverride,
872
+ videoEncoder: this.#host.videoEncoder,
873
+ segmentDurationSec: this.#host.segmentDurationSec
874
+ });
875
+
876
+ // The exact command, every run. An encode failure is otherwise reported
877
+ // with ffmpeg's message and nothing about what it was asked to do, and the
878
+ // two are not always deducible from each other: 2026-08-04 a run died with
879
+ // "Cannot write moov atom before AC3 packets" although both muxing paths
880
+ // were verified to handle a copied AC-3 track on this very host, so the
881
+ // arguments that run actually received are the missing evidence. One line
882
+ // per run, and a run happens at most every few seconds.
883
+ // Numbered, because a burst of seeks starts several runs in one second and
884
+ // every line about them carries the SESSION id, which is the same for all.
885
+ // Without a run number the command that failed cannot be told from the two
886
+ // that succeeded around it — which is exactly the state the unexplained
887
+ // `Cannot write moov atom before AC3 packets` was found in.
888
+
889
+ // One directory for the output, and every run writes straight into it.
890
+ //
891
+ // Runs used to be kept apart by a directory each, because two of them
892
+ // writing one segment name at the same time produce a file belonging to
893
+ // neither — which was also the only reason a restart ever had to wait for
894
+ // its predecessor to die. Intervals remove that by construction: a run is
895
+ // given a stretch nobody else holds and stops at the end of it, so no two
896
+ // runs ever want the same number. What is left of the old reason — a run
897
+ // killed mid-piece leaving a partial file — is not a correctness problem
898
+ // either, because the store serves a segment only once its closure is
899
+ // proven, and it is cleared up when the run ends.
900
+ const run = new EncodeRun({
901
+ address: session.outputKey ?? session.id,
902
+ encoder: this.#host.videoEncoder,
903
+ from: safeIndex,
904
+ to: runEnd,
905
+ buildArgs: () => args,
906
+ argsDescribed: describeFfmpegArgs(args),
907
+ // Whether this run cuts at times we gave it. Decides how a segment is
908
+ // judged finished — see getFileStream.
909
+ usesExplicitCuts: Boolean(cutTimes && cutTimes.length > 0),
910
+ startSeconds,
911
+ totalSeconds: Number(session.file.durationSeconds) || null,
912
+ spawn: (spawnArgs) =>
913
+ spawn(this.#host.ffmpegBin, spawnArgs, {
914
+ cwd: this.#host.segmentFiles.directoryFor(session.outputKey ?? ""),
915
+ // A fourth channel: the encoder names every piece it has CLOSED on it,
916
+ // which is the only proof a piece is whole.
917
+ stdio: ["ignore", "pipe", "pipe", "pipe"]
918
+ }),
919
+ logger: this.#host.logger,
920
+ // The film's last segment number, which is what tells "it reached the
921
+ // end" from "its input dried up": ffmpeg exits zero for both and over a
922
+ // torrent cannot tell them apart.
923
+ lastSegmentIndex: () =>
924
+ session.timeline?.segmentCount > 0 ? session.timeline.segmentCount - 1 : null,
925
+ inputUnavailable: (message) => isInputUnavailable(message),
926
+ onProgress: (report) => this.#noteRunProgress(session, run, report),
927
+ indexOfName: (name) => session.segmentFormat.segmentIndexFromName(
928
+ session.segmentFormat.servedNameOf?.(name) ?? name),
929
+ // Why this encoder exists, recorded with its argument list. It used to be
930
+ // handed to a separate `start` call; there is no separate call now.
931
+ because,
932
+ onClosed: (name) => {
933
+ const index = session.segmentFormat.segmentIndexFromName(
934
+ session.segmentFormat.servedNameOf?.(name) ?? name);
935
+ if (Number.isInteger(index) && index < safeIndex) return null;
936
+ const mediaRanges = this.#wholeClosedPiece(session, name, index);
937
+ if (mediaRanges === false) return null;
938
+ return this.#host.segmentFiles.publish(session.outputKey ?? "", name, session.segmentFormat, { mediaRanges });
939
+ },
940
+ onSpeedMeasured: () => this.#host.noteRunSpeedMeasured?.(session, run),
941
+ onEnded: (ended) => {
942
+ this.#runsByInputToken.delete(inputToken);
943
+ this.noteRunEnded(session, run, ended);
944
+ }
945
+ });
946
+ this.#runsByInputToken.set(inputToken, run);
947
+ // THE ONE FAULT THAT IS OTHERWISE SILENT, asked before this run produces a
948
+ // frame. It lost its caller in a refactor on 2026-09-04 and had none until
949
+ // 2026-09-15 — not by a decision, which is why it is back rather than gone.
950
+ this.#warnIfRunLeavesTheInitBehind(session);
951
+
952
+ this.#host.logger.info(
953
+ `transcode ${session.id} encode-run #${safeIndex}..#${runEnd} from segment #${safeIndex} ` +
954
+ `(+${Date.now() - restartEnteredAt}ms since the restart was asked for) ` +
955
+ `(${formatSeconds(startSeconds)}) "${session.file.name}"`
956
+ );
957
+ // The four numbers a run is positioned by, said once, because their
958
+ // disagreement is invisible everywhere else. The two tables are printed
959
+ // side by side: while they differ, every cut of this run is off by the
960
+ // difference, and nothing downstream can tell that from a bad index.
961
+ const liveStart = this.#host.outputTimes.segmentStartTime(session, safeIndex);
962
+ this.#host.logger.info(
963
+ `transcode ${session.id} run #${safeIndex}..#${runEnd} positioned at ${startSeconds.toFixed(3)}s ` +
964
+ `for boundary #${safeIndex} (published ${startSeconds.toFixed(3)}s, ` +
965
+ `live ${liveStart.toFixed(3)}s, apart ${(liveStart - startSeconds).toFixed(3)}s), ` +
966
+ `numbering from #${safeIndex}`
967
+ );
968
+ return run;
969
+ }
970
+
971
+ /**
972
+ * Log a report from a run that still belongs to this output. The run owns the
973
+ * clock and has already placed its relative ffmpeg time on the source
974
+ * timeline.
975
+ *
976
+ * @param {HlsSession} session
977
+ * @param {import("./EncodeRun.js").EncodeRun} run
978
+ * @param {object} progress
979
+ * @returns {void}
980
+ */
981
+ #noteRunProgress(session, run, progress) {
982
+ if (!this.isLive(session) || !this.runsOf(session).includes(run)) {
983
+ return;
984
+ }
985
+ if (run.progress.shouldLog(PROGRESS_LOG_INTERVAL_MS)) {
986
+ this.#host.logger.info(
987
+ `transcode ${session.id} "${session.file.name}" ${progress.percent.toFixed(1)}% ` +
988
+ `(${formatSeconds(progress.processedSeconds)} / ${formatSeconds(progress.totalSeconds)})` +
989
+ ` speed=${run.speedX > 0 ? `${run.speedX.toFixed(2)}x` : "n/a"}`
990
+ );
991
+ }
992
+ }
993
+
994
+ /**
995
+ * What to do about a run that has ended.
996
+ *
997
+ * The run says how it ended and why; this decides what follows, which is a
998
+ * question about the SESSION and the machine rather than about the process:
999
+ * whether to condemn a hardware encoder, whether to wait for the input to
1000
+ * come back, whether a position has failed often enough to stop retrying it.
1001
+ *
1002
+ * An ending from a run the session has already replaced is not ignored — it
1003
+ * is simply not about this session's current run, so nothing that describes
1004
+ * the current run is written from it. That is what the identity check used to
1005
+ * be for, and it is one condition now instead of one at the head of every
1006
+ * handler.
1007
+ *
1008
+ * @param {HlsSession} session
1009
+ * @param {import("./EncodeRun.js").EncodeRun} run
1010
+ * @param {import("./EncodeRun.js").RunEnded} ended
1011
+ * @returns {void}
1012
+ */
1013
+ noteRunEnded(session, run, ended) {
1014
+ // First, and for every run whatever else follows: the stretch it held goes
1015
+ // back to the map. A run whose claim is never released tells the plan that
1016
+ // numbers nobody is making are being made, and nothing is ever started
1017
+ // there again.
1018
+ // WAS this run still the session's when it ended? Asked before it is
1019
+ // removed, because after the removal the question always answers "no" —
1020
+ // and it was asked after, so every line below this point was unreachable.
1021
+ //
1022
+ // Measured 2026-09-05 over both of the field host's log files: zero
1023
+ // occurrences of this handler's own `encode-run #… failed:` line and zero
1024
+ // of `fast failure at segment`, across every session this proxy has ever
1025
+ // run. So the fallback from a failed hardware encoder to software, the
1026
+ // retry when the torrent data goes away, the limit on retrying a position
1027
+ // that keeps failing, and the error line naming the ffmpeg command have all
1028
+ // been dead code — which is also why nothing ever stopped the restart loop
1029
+ // recorded in the field the same day.
1030
+ const wasCurrent = this.runsOf(session).includes(run);
1031
+ this.#host.encodeOrchestrator.noteEnded(ended);
1032
+ // What this admitted encode was seen to do, kept for the next time this
1033
+ // host prices the same mode (roadmap item 97, step 14). Whatever the
1034
+ // ending: a run that failed still ran at the speed it ran at, and the
1035
+ // segments it closed still carried what they carried.
1036
+ this.#host.observeEncodeEnded?.(session);
1037
+ // A stretch went back to the map, so what should be running has changed.
1038
+ // Said here rather than waited for: this is the moment it became true.
1039
+ this.planEncodersSoon();
1040
+ // ANYBODY ALREADY WAITING IS TOLD, and it is asked HERE because every
1041
+ // ending passes this line while the handlers below return one by one. It
1042
+ // used to be the last statement of this method, which the `SHORT` branch —
1043
+ // ffmpeg exiting 0 having produced less than the playlist promises —
1044
+ // returns before reaching. That ending is terminal (`ENDED_FAILED`), so a
1045
+ // request arriving after it is answered with the failure at once while a
1046
+ // wait that BEGAN before it sat out its whole deadline, or, where the page
1047
+ // states none, until the viewer disconnected.
1048
+ //
1049
+ // THE CONDITION IS THE OUTPUT'S ACTUAL STATE, not this run's ending.
1050
+ // `stateOf` answers from the LIVE runs and falls back to the last ending
1051
+ // only when none remain, so one run of several ending in failure wakes
1052
+ // nobody — something is still making it — and the last one does. Asked
1053
+ // after `noteEnded` has recorded the ending, so the woken request reads the
1054
+ // final state; and it re-reads the disk first, because a piece already made
1055
+ // is served whatever became of the encoder.
1056
+ if (this.hasFailed(session)) {
1057
+ this.#host.invalidateWaits(session);
1058
+ // A move to this output being prepared for a viewer waits for a segment
1059
+ // that nothing will now make, and no publication will ever end that wait.
1060
+ // This is the event that does (roadmap item 97, step 12).
1061
+ this.#host.productionFailed(session);
1062
+ }
1063
+ if (!this.isLive(session)) {
1064
+ this.forgetEncodingOfGone(session);
1065
+ return;
1066
+ }
1067
+ if (!wasCurrent) {
1068
+ // A run the session had already replaced. It has logged its own ending;
1069
+ // nothing about the session follows from it.
1070
+ return;
1071
+ }
1072
+ const lastError = this.lastErrorOf(session) || ended.because;
1073
+ if (ended.ending === ENCODE_EXIT.STOPPED || ended.ending === ENCODE_EXIT.GONE) {
1074
+ return;
1075
+ }
1076
+ if (ended.ending === ENCODE_EXIT.COMPLETE) {
1077
+ this.#host.logger.info(`transcode ${session.id} encode-run complete "${session.file.name}"`);
1078
+ return;
1079
+ }
1080
+ if (ended.ending === ENCODE_EXIT.SHORT) {
1081
+ // ffmpeg exits 0 both when it reaches the end of the file and when its
1082
+ // input simply stops producing bytes — over HTTP the two look identical
1083
+ // to it. Field 2026-08-05: the torrent's download died, the read ended,
1084
+ // and a run that had made 188 segments of 624 reported itself complete;
1085
+ // the player then consumed what was on disk and froze on the first
1086
+ // segment nobody was making. So the claim is checked against the playlist
1087
+ // we published, and a run that stopped short is a FAILURE that can be
1088
+ // restarted, not a finished file.
1089
+ this.#host.logger.error(
1090
+ `transcode ${session.id} encode-run #${ended.from}..#${ended.to} ended early: ` +
1091
+ `${ended.because} "${session.file.name}"`
1092
+ );
1093
+ return;
1094
+ }
1095
+ // Runtime safety net: if a hardware encode fails, downgrade this proxy to
1096
+ // software encoding for all sessions and restart this one, so playback is
1097
+ // never permanently broken by a hardware/driver issue.
1098
+ //
1099
+ // Asked only of a genuine encoder failure. It used to be asked of every
1100
+ // non-zero exit, so a run whose TORRENT DATA went away — which says nothing
1101
+ // whatever about the encoder — condemned a working NVENC or QuickSync to
1102
+ // software for the life of the process, and started an extra run at the old
1103
+ // index while it was at it.
1104
+ if (ended.ending === ENCODE_EXIT.FAILED && session.spec.transcodesVideo && this.#host.videoEncoder.kind !== "software") {
1105
+ const failed = this.#host.encoders.useSoftware();
1106
+ const failedEncoder = failed?.name ?? this.#host.videoEncoder.name;
1107
+ this.#host.logger.warn(
1108
+ `transcode ${session.id} hardware encoder ${failedEncoder} failed ` +
1109
+ `(${lastError}); falling back to software libx264, and every output named by ${failedEncoder} is closed`
1110
+ );
1111
+ // An output IS its format, and the encoder is part of it: pieces from
1112
+ // another encoder cannot be decoded with the header this output's viewers
1113
+ // already hold. So the outputs made by the failed encoder end here, and
1114
+ // the next request for that picture names a format built on the new one.
1115
+ //
1116
+ // THE ONE DISPOSAL THAT DOES NOT ASK WHETHER ASSIGNMENTS STILL HOLD IT, and
1117
+ // deliberately. Every other one asks, because a repeat of a request must be
1118
+ // answered by what answered it first. Here what answered it first has no
1119
+ // encoder that can go on making it: holding the output keeps only a name
1120
+ // whose next segment nobody will produce. A response already being sent is
1121
+ // not cut short by this — it reads from a file already opened.
1122
+ for (const other of [...this.#host.outputs.values()]) {
1123
+ if (other.spec.video?.encode?.encoder === failedEncoder) {
1124
+ void this.#host.disposeSession(other.id);
1125
+ }
1126
+ }
1127
+ this.planEncodersSoon();
1128
+ return;
1129
+ }
1130
+ // Losing the INPUT is not the session failing — it is the data not being
1131
+ // there YET. The torrent can be re-added and re-downloaded, so the honest
1132
+ // answer to the viewer is "still working", not an error screen. Field
1133
+ // 2026-08-06: a torrent evicted mid-seek took the film with it, the run
1134
+ // died on `File 0 not found`, the session went terminal and answered 500 to
1135
+ // every request from then on — although the swarm was there and the data
1136
+ // would have come back in seconds. The circuit breaker below stays for what
1137
+ // it was built for, a target that genuinely cannot be encoded; it must not
1138
+ // condemn a session whose data merely went away.
1139
+ if (ended.ending === ENCODE_EXIT.INPUT_LOST) {
1140
+ const inputState = this.#inputStateFor(session);
1141
+ inputState.inputRetryCount += 1;
1142
+ this.#host.logger.warn(
1143
+ `transcode ${session.id} encode-run #${ended.from}..#${ended.to} lost its input ` +
1144
+ `(${lastError}) (attempt ${inputState.inputRetryCount})`
1145
+ );
1146
+ // HOW LONG TO WAIT IS THE PLAN'S, and this says only what happened. The
1147
+ // delay used to be timed here, against the dead run, which the plan never
1148
+ // consults — so it placed a fresh run at the same spot as fast as ffmpeg
1149
+ // could fail there: 2432 starts in 23 minutes in the field 2026-09-12,
1150
+ // against a delay that had reached its 15 s ceiling long before. The
1151
+ // orchestrator holds it now, beside the decision it governs.
1152
+ if (run.state === ENCODE_RUN_STATE.RETRY_WAIT) {
1153
+ run.retryDue();
1154
+ }
1155
+ return;
1156
+ }
1157
+ // A run that exits THIS fast never did real work: it failed at the start
1158
+ // itself — opening the input, spawning the process — rather than
1159
+ // mid-stream. Consecutive fast failures at the SAME position are counted so
1160
+ // that whoever commands a start can stop commanding one that keeps failing.
1161
+ //
1162
+ // COUNTED AT EVERY POSITION, #0 included. It used to be counted only past
1163
+ // #0, because it was written for seek restarts and a seek is never to the
1164
+ // beginning. That left the one position the plan commands FIRST with no
1165
+ // count at all, and the plan re-commanding a start that cannot succeed is
1166
+ // an unbounded loop: measured 2026-09-05, ffmpeg failing to spawn produced
1167
+ // fifty passes of the plan before a probe stopped it, as fast as the
1168
+ // failures arrived.
1169
+ const failure = this.#host.encodeOrchestrator.noteStartFailure(
1170
+ session.outputKey,
1171
+ ended.from,
1172
+ ended.livedMs
1173
+ );
1174
+ if (failure.count > 0) {
1175
+ this.#host.logger.warn(
1176
+ `transcode ${session.id} fast failure at segment #${ended.from} ` +
1177
+ `(${ended.livedMs}ms) — ${failure.count}/${failure.limit} consecutive`
1178
+ );
1179
+ if (failure.blocked) {
1180
+ this.#host.logger.error(
1181
+ `transcode ${session.id} will not be started at #${ended.from} again: ` +
1182
+ `${failure.count} starts there failed within ${failure.fastMs}ms each ` +
1183
+ `(${lastError}) "${session.file.name}"`
1184
+ );
1185
+ }
1186
+ }
1187
+ this.#host.logger.error(
1188
+ `transcode ${session.id} encode-run #${ended.from}..#${ended.to} failed: ${lastError}` +
1189
+ ` — ${this.#describeTrackSelection(session)}` +
1190
+ `\n ffmpeg ${run.argsDescribed || "(command not recorded)"}`
1191
+ );
1192
+ }
1193
+
1194
+ /**
1195
+ * What this run asked the source for, against what the source said it has.
1196
+ *
1197
+ * Written for one failure in particular: every `-map` this proxy builds ends
1198
+ * in `?`, so ffmpeg drops a mapping for an absent stream without complaint,
1199
+ * and a run whose mappings ALL drop produces a file with nothing in it —
1200
+ * reported as `Output file does not contain any stream`, exit 255. Read from
1201
+ * the exit code alone that is indistinguishable from any other refusal. Read
1202
+ * beside the tracks the file actually holds it is unmistakable, and it names
1203
+ * which side is wrong: an audio index past the end of the list is ours, no
1204
+ * streams at all is the source's.
1205
+ *
1206
+ * @param {HlsSession} session
1207
+ * @returns {string}
1208
+ */
1209
+ #describeTrackSelection(session) {
1210
+ const wanted = [];
1211
+ // Named exactly as the command line names them, second input included: a
1212
+ // refusal whose message describes a different mapping than the one that was
1213
+ // refused is the reading that cost a wrong diagnosis before.
1214
+ const inputs = this.#host.inputOf(session);
1215
+ const audioInput = inputs.audioInputUrl.length > 0 ? 1 : 0;
1216
+ const audioTrack = session.spec.audioSourceTrackIndex;
1217
+ if (session.spec.carries === "audio-only") {
1218
+ wanted.push(`audio 0:a:${audioTrack}`);
1219
+ } else if (this.#host.servesAudioSeparately(session)) {
1220
+ wanted.push("video 0:v:0");
1221
+ } else {
1222
+ wanted.push("video 0:v:0", `audio ${audioInput}:a:${audioTrack}`);
1223
+ }
1224
+ const counts = session.file.streamCounts;
1225
+ const held = counts
1226
+ ? `the source holds ${counts.video} video, ${counts.audio} audio, ` +
1227
+ `${counts.subtitle} subtitle` +
1228
+ (counts.other > 0 ? `, ${counts.other} other` : "")
1229
+ : "what the source holds was not recorded";
1230
+ return `this run asked for ${wanted.join(" + ")}, and ${held}`;
1231
+ }
1232
+
1233
+ /**
1234
+ * Stop this session's encoder without replacing it.
1235
+ *
1236
+ * A variant nobody is watching must not go on encoding: the host has one
1237
+ * encoder's worth of capacity, and the whole point of switching quality
1238
+ * seamlessly is that the new rung gets it. The session itself stays — its
1239
+ * produced segments remain servable, and switching back restarts it from
1240
+ * where the viewer then is.
1241
+ *
1242
+ * @param {HlsSession} session
1243
+ * @param {string} reason - Named in the log; a stopped encoder is otherwise
1244
+ * indistinguishable from one that died.
1245
+ * @returns {void}
1246
+ */
1247
+ stopEncodeRun(session, reason) {
1248
+ const running = this.liveRunsOf(session);
1249
+ if (running.length === 0) {
1250
+ return;
1251
+ }
1252
+ // Every run this session has going. The callers all mean the session's
1253
+ // encoding as a whole: a rung nobody is watching any more, a session being
1254
+ // disposed. A run that had already finished or failed is not among them,
1255
+ // which is what keeps a stop from erasing how it actually ended.
1256
+ for (const run of running) {
1257
+ // The run resumes itself if it was suspended — a stopped process does not
1258
+ // act on SIGTERM until it is continued — records the cause, and answers
1259
+ // its own exit. Nothing here has to null a field so that the exit is read
1260
+ // correctly, because there is no shared field left to misread.
1261
+ run.stop(reason);
1262
+ // Nothing is cleared up from here. What this run left open is under its
1263
+ // own working name, and the encoding layer removes it when the run's
1264
+ // ending reaches it — one place, and it needs neither the stretch nor the
1265
+ // init bytes this method used to fetch to judge a file by its contents.
1266
+ }
1267
+ this.#host.logger.info(`transcode ${session.id} ${running.length} encoder(s) stopped: ${reason}`);
1268
+ }
1269
+
1270
+ /**
1271
+ * What moving the encoder BACKWARDS costs, said out loud when it happens.
1272
+ *
1273
+ * Nothing already written is lost — every run keeps its own directory and
1274
+ * {@link SegmentStore#pathOfName} serves the union of all of them
1275
+ * — so the price of a restart is not the files. It is two other things, and
1276
+ * neither was ever counted:
1277
+ *
1278
+ * - **work done twice.** The new run begins at the target and encodes
1279
+ * forward through segments the old run had already finished. ffmpeg cannot
1280
+ * know they exist, so it makes them again.
1281
+ * - **the viewer in front.** While the run walks back up to where it already
1282
+ * was, nothing new is being made ahead of them, and their cushion drains.
1283
+ *
1284
+ * Both are what decides whether a session should be allowed a SECOND
1285
+ * concurrent run instead — roadmap item 64. That question cannot be answered
1286
+ * from taste, and this is the reading it needs: how often it happens at all,
1287
+ * how far back, and how much of the walk is a repeat.
1288
+ *
1289
+ * Nothing here is awaited by the caller. Everything below the call site is
1290
+ * the restart path, which is measured in milliseconds and has been worked on
1291
+ * twice to keep it that way; a reading that delays the thing it is reading
1292
+ * about is not a reading. The figures that MUST be taken before the new run
1293
+ * exists are taken synchronously, and only the file counting is left to run
1294
+ * on its own — against the directories that existed at this instant, so what
1295
+ * the new run is about to write cannot be counted as already there.
1296
+ *
1297
+ * @param {HlsSession} session
1298
+ * @param {number} startIndex - Where the new run will begin.
1299
+ * @returns {void}
1300
+ */
1301
+ #accountBackwardRestart(session, startIndex) {
1302
+ const previousStart = earliestRunStart(this.runsOf(session));
1303
+ if (!Number.isInteger(previousStart) || !Number.isInteger(startIndex) || startIndex >= previousStart) {
1304
+ // A first run, or one moving forward. Neither costs anything here: a
1305
+ // forward restart skips material it never made.
1306
+ return;
1307
+ }
1308
+ const processed = Number(this.progressOf(session)?.processedSeconds);
1309
+ const head = Number.isFinite(processed)
1310
+ ? Math.max(previousStart, this.#host.outputTimes.segmentIndexForTime(session, processed))
1311
+ : previousStart;
1312
+ // Bounded: a session an hour in has thousands of segments, and the count is
1313
+ // for a comparison, not an inventory.
1314
+ const last = Math.min(head, startIndex + BACKWARD_RESTART_SCAN_SEGMENTS);
1315
+ const accounting = this.#inputStateFor(session).backwardRestarts;
1316
+ accounting.count += 1;
1317
+ accounting.segmentsBack += previousStart - startIndex;
1318
+ accounting.worstBack = Math.max(accounting.worstBack, previousStart - startIndex);
1319
+
1320
+ void (async () => {
1321
+ let alreadyOnDisk = 0;
1322
+ for (const index of this.#host.producedNumbers(session)) {
1323
+ if (index >= startIndex && index <= last) {
1324
+ alreadyOnDisk += 1;
1325
+ }
1326
+ }
1327
+ accounting.remade += alreadyOnDisk;
1328
+ this.#host.logger.info(
1329
+ `transcode ${session.id} moving the encoder BACK from #${previousStart} to #${startIndex} ` +
1330
+ `(head was #${head}): ${alreadyOnDisk} of the ${last - startIndex + 1} segment(s) it will walk through ` +
1331
+ `are already on disk and will be made again, and nothing is produced ahead of #${head} until it gets ` +
1332
+ `back there — ${accounting.count} backward restart(s) this session, worst ${accounting.worstBack} ` +
1333
+ `segment(s) back, ${accounting.remade} segment(s) remade in total (roadmap 64)`
1334
+ );
1335
+ })().catch(() => {
1336
+ // silent-ok: a reading that fails is not worth ending a restart over.
1337
+ });
1338
+ }
1339
+ }