@torrent-tv/proxy 2.89.6 → 2.89.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/AGENTS.md +32 -12
  2. package/CHANGELOG.md +2340 -2330
  3. package/assets/calibration/audio/NOTICE.md +19 -19
  4. package/assets/calibration/audio/manifest.json +98 -98
  5. package/biome.json +412 -412
  6. package/docs/browser-proxy-contract.md +155 -155
  7. package/docs/container-architecture.md +273 -273
  8. package/docs/encode-run-state.md +1 -1
  9. package/docs/playback-start-forecast.md +113 -98
  10. package/package.json +51 -50
  11. package/routes/api/sources/files/get.js +106 -106
  12. package/scripts/build-audio-samples.mjs +31 -31
  13. package/services/encode/EncodeRun.js +67 -15
  14. package/services/encode/EncodeRuns.js +19 -7
  15. package/services/encode/OutputOpening.js +784 -784
  16. package/services/encode/audio-calibration.js +67 -67
  17. package/services/encode/audio-work-rate.js +15 -15
  18. package/services/encode/encode-exit.js +2 -0
  19. package/services/encode/hwaccel.js +1894 -1894
  20. package/services/encode/output/index.js +24 -24
  21. package/services/encode/piece-completeness.js +60 -2
  22. package/services/encode/run-command.js +757 -755
  23. package/services/encode/segment-formats/index.js +1 -0
  24. package/services/encode/segment-formats/mp4-boxes.js +8 -1
  25. package/services/media/ContainerOrchestrator.js +202 -202
  26. package/services/media/KeyframeTables.js +356 -356
  27. package/services/media/SubtitleCues.js +592 -592
  28. package/services/media/audio-inventory.js +299 -299
  29. package/services/media/container/AviContainer.js +268 -268
  30. package/services/media/container/Container.js +632 -632
  31. package/services/media/container/ContainerFactory.js +38 -38
  32. package/services/media/container/MatroskaContainer.js +1031 -1031
  33. package/services/media/container/Mp4Container.js +1354 -1354
  34. package/services/media/container/SubtitleFileContainer.js +339 -339
  35. package/services/media/container/ebml-stream.js +174 -174
  36. package/services/media/container/matroska-clusters.js +1165 -1165
  37. package/services/media/container/unavailable.js +77 -77
  38. package/services/media/tracks/ContainerTrack.js +84 -84
  39. package/services/media/tracks/TextSubtitleTrack.js +295 -295
  40. package/services/storage/piece-store/shared-piece-store.js +1937 -1937
  41. package/services/storage/segment-store/SegmentStore.js +1294 -1294
  42. package/services/torrent/Contents.js +382 -382
  43. package/services/torrent/episode-naming.js +182 -182
  44. package/services/torrent/torrent-pool.js +2688 -2688
  45. package/services/torrent/worker/client.js +836 -836
  46. package/services/torrent/worker/held-bytes.js +231 -231
  47. package/services/torrent/worker/worker.js +1137 -1137
  48. package/services/transport/data-channel-handler.js +1373 -1373
  49. package/services/viewer/PriorityMap.js +421 -421
  50. package/test/audio-calibration.test.js +23 -23
  51. package/test/auto-quality-step.test.js +762 -762
  52. package/test/coalesce.test.js +39 -39
  53. package/test/coverage-follows-the-disk.test.js +5 -0
  54. package/test/decode-cost.test.js +475 -475
  55. package/test/encode-run.test.js +58 -0
  56. package/test/episode-naming.test.js +131 -131
  57. package/test/failed-encoder-still-serves-what-exists.test.js +1 -1
  58. package/test/fixtures/audio-frame-boundary.json +1 -1
  59. package/test/fixtures/refused-audio-20261002.json +10 -0
  60. package/test/fmp4-presentation-clock.test.js +4 -2
  61. package/test/format-keyed-outputs.test.js +78 -78
  62. package/test/health-metrics.test.js +11 -13
  63. package/test/held-read-ownership.test.js +77 -77
  64. package/test/helpers/encode-run.js +14 -6
  65. package/test/helpers/held-file.js +77 -77
  66. package/test/helpers/manager.js +62 -62
  67. package/test/helpers/matroska-file.js +296 -296
  68. package/test/keyframe-table-budget.test.js +123 -123
  69. package/test/matroska-cluster-discovery.test.js +323 -323
  70. package/test/one-output-one-session.test.js +273 -273
  71. package/test/output-speed.test.js +6 -1
  72. package/test/piece-completeness.test.js +37 -1
  73. package/test/quality-variants.test.js +1274 -1270
  74. package/test/rate-control-in-the-output.test.js +4 -3
  75. package/test/reads-not-yet-arrived.test.js +218 -218
  76. package/test/seek-frees-the-viewers-requests.test.js +1 -1
  77. package/test/segment-closed-on-both-branches.test.js +114 -114
  78. package/test/segment-judged-by-its-own-header.test.js +222 -222
  79. package/test/segment-serve-wiring.test.js +481 -481
  80. package/test/serving-existing-output.test.js +111 -111
  81. package/test/source-files-route.test.js +113 -113
  82. package/test/subtitle-cue-walk.test.js +385 -385
  83. package/test/subtitle-metadata.test.js +15 -15
  84. package/test/subtitle-plan-waits.test.js +125 -125
  85. package/test/subtitle-track-numbering.test.js +391 -391
  86. package/test/two-viewers-one-picture.test.js +508 -508
  87. package/test/viewer-requests-admission.test.js +92 -92
  88. package/test/viewer-starts-on-map.test.js +27 -27
  89. package/test/viewer-states.test.js +5 -2
  90. package/test/viewing-generations.test.js +390 -390
  91. package/test/whole-file-held-read.test.js +30 -30
  92. package/utils/coalesce.js +41 -41
@@ -1,784 +1,784 @@
1
- /**
2
- * @file Which output answers a request for a file, made if it is not here yet.
3
- *
4
- * A request names a file, the tracks wanted and a size; what answers it is an
5
- * OUTPUT, and deciding which is the encoding component's: the arrangement of
6
- * the sound, the cut grid, the format the budget settles on, and whether an
7
- * output already here serves the request instead. Two requests whose outputs
8
- * agree ARE one output. Who asked is not a parameter: placing the requester on
9
- * the output is the server operation's business (`server/ViewerRequests.js`),
10
- * and nothing about a viewer enters what is decided here.
11
- *
12
- * What the file says about itself is read by the media component and handed in
13
- * (`probeMediaInfo`, `probeKeyframeTimes`), as is everything else this reads.
14
- */
15
-
16
- import { createRequire } from "node:module";
17
- import { buildResolutionLadder, chooseOutputFps } from "./hwaccel.js";
18
- import { resolveSegmentFormat, SEGMENT_FORMAT_IDS } from "./segment-formats/index.js";
19
- import { AudioOutput, CutGrid, OUTPUT_NO_CAPACITY, OUTPUT_UNAVAILABLE, OutputSpec, VideoOutput } from "./output/index.js";
20
- import { Timeline, Timelines } from "./output/Timeline.js";
21
- import { computeCutGrid } from "./output/cut-grid.js";
22
- import { Output } from "./output/Output.js";
23
- import { mediaPlaylistText } from "./output/playlists.js";
24
- import { formatSeconds } from "./EncodeRuns.js";
25
- import { EncodedOutput } from "./output/EncodedOutput.js";
26
- import { decideOutputFormat } from "./quality/output-format.js";
27
- import { rungForVisiblePicture } from "./quality/visible-rung.js";
28
- import { SOUNDTRACK_MODE_CAUSE, chooseSoundtrackMode, linkAnswerFigures as linkFiguresOf, soundtrackLoadOf } from "./quality/link-budget.js";
29
-
30
- /**
31
- * @typedef {Object} SegmentOutputFiles
32
- * @property {() => string[]} addresses
33
- * @property {(address: string, index: number) => boolean} isClosed
34
- * @property {(address: string) => number | null} lastReadAt
35
- * @property {(address: string) => string} directoryFor
36
- * @property {(address: string, format: object) => void} useFormat
37
- */
38
-
39
- /** Own package version, stamped onto output-start log lines. */
40
- const PROXY_VERSION = createRequire(import.meta.url)("../../package.json").version;
41
-
42
- export class OutputOpening {
43
- /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
44
- #host;
45
-
46
- /**
47
- * @param {object} host - `logger`, `probeMediaInfo`, `probeKeyframeTimes`, `enabled`, `segmentFormat`, `renditions`, `sourceFiles`, `getCachedMediaInfo`, `localBaseUrl`, `tonemapSupported`, `videoEncoder`, `hostLoad`, `keyframeTables`, `timelines`, `segmentDurationSec`, `softwarePresetBenchmark`, `decodeCostModel`, `encodeCost`, `admission`, `outputs`, `segmentOutputFiles`, `hostTimings`, `returns`, `encodeRuns`
48
- * @param {SegmentOutputFiles} host.segmentOutputFiles - The storage
49
- * operations needed while selecting or opening an output.
50
- */
51
- constructor(host) {
52
- this.#host = host;
53
- }
54
-
55
- /**
56
- * The box a re-encoded picture is fitted into.
57
- *
58
- * A box the request names is the box (a quality step names its height). With
59
- * none named, the picture the viewer sees decides: the smallest rung of the
60
- * source's ladder whose frame is not smaller than it (roadmap item 98). With
61
- * neither, zeroes — the source's own size.
62
- *
63
- * @param {{ normalizedTargetWidth: number, normalizedTargetHeight: number, visiblePicture: { width: number, height: number } | null, sourceWidth: number, sourceHeight: number }} params
64
- * @returns {{ width: number, height: number }}
65
- */
66
- #targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }) {
67
- if (normalizedTargetWidth > 0 || normalizedTargetHeight > 0) {
68
- return { width: normalizedTargetWidth, height: normalizedTargetHeight };
69
- }
70
- const rung = rungForVisiblePicture(
71
- buildResolutionLadder(Math.round(Number(sourceWidth) || 0), Math.round(Number(sourceHeight) || 0)),
72
- visiblePicture
73
- );
74
- return rung ? { width: rung.width, height: rung.height } : { width: 0, height: 0 };
75
- }
76
-
77
- /**
78
- * Ask the requester's call whether they may be put on this output, and throw
79
- * the refusal the way the route answers it.
80
- *
81
- * @param {((output: object) => { admitted: boolean, reason: string, speedX: number | null }) | null} claim
82
- * @param {object} output
83
- * @param {string} logName
84
- * @returns {void}
85
- */
86
- #claimOrRefuse(claim, output, logName) {
87
- if (typeof claim !== "function") {
88
- return;
89
- }
90
- const answer = claim(output);
91
- if (answer?.admitted) {
92
- return;
93
- }
94
- const reason = answer?.reason || "this machine has no place for one more encoder";
95
- this.#host.logger.info(`transcode "${logName}": not opened for this viewer — ${reason} (key=${output.outputKey})`);
96
- const error = new Error(`This proxy cannot take this video now: ${reason}.`);
97
- error.code = OUTPUT_NO_CAPACITY;
98
- error.details = {
99
- reason,
100
- figures: { speedX: Number.isFinite(answer?.speedX) ? Number(answer.speedX.toFixed(3)) : null, outputKey: output.outputKey }
101
- };
102
- throw error;
103
- }
104
-
105
- /**
106
- * The output that answers this request: one already here, or one made now.
107
- * No encoder is started here — where encoders go is the plan's.
108
- *
109
- * Throws with `error.code === "TRANSCODE_DISABLED"` when transcoding is
110
- * disabled on this proxy instance.
111
- *
112
- * @param {object} options
113
- * @param {string} options.sourceKey - Registry source key.
114
- * @param {number} options.fileIndex - Zero-based file index in the torrent.
115
- * @param {boolean} [options.transcodeVideo=false]
116
- * @param {boolean} [options.transcodeAudio=false]
117
- * @param {string} [options.fileName=""] - Display name for log output.
118
- * @param {number} [options.targetWidth=0] - Target video width (0 = keep source).
119
- * @param {number} [options.targetHeight=0] - Target video height (0 = keep source).
120
- * @param {number} [options.startPositionSeconds=0] - Seek start position in seconds.
121
- * @param {number} [options.audioTrackIndex=0] - Type-relative audio track to map (0:a:N).
122
- * @param {boolean} [options.exactSize=false] - Produce the target box exactly (capped to source), with no budget downscale and no runtime downswitch. Says nothing about who asked: every rung of a master sets it.
123
- * @param {number | null} [options.capKbps=null] - Nominal bitrate limit in kbit/s; null for the size's own. Above the size's own it is refused.
124
- * @param {{ width: number, height: number } | null} [options.visiblePicture=null] - The picture as the requesting viewer sees it, in physical pixels. With no target box given, a re-encoded picture's box is the smallest rung whose frame is not smaller than this (roadmap item 98).
125
- * @returns {Promise<{ output: EncodedOutput, existed: boolean, audio: { trackIndex: number, transcode: boolean }, verdict: object | null }>}
126
- */
127
- async open({
128
- sourceKey,
129
- fileIndex,
130
- transcodeVideo = false,
131
- transcodeAudio = false,
132
- fileName = "",
133
- targetWidth = 0,
134
- targetHeight = 0,
135
- startPositionSeconds = 0,
136
- audioTrackIndex = 0,
137
- exactSize = false,
138
- // The caller takes its audio from a rendition group, so the picture is
139
- // encoded without it and each audio track is encoded once for the file
140
- // instead of once per rung. Off unless asked for: a browser that does not
141
- // know about renditions must still get its audio in the stream.
142
- audioRenditions = false,
143
- // This session IS one of those renditions: one audio track, no picture, cut
144
- // on the same grid as the video it accompanies.
145
- audioOnly = false,
146
- // The arrangement decided by the session this one belongs to — a variant or
147
- // a rendition of it. Every session of one master must agree about where the
148
- // audio is, and only the base is in a position to decide: a variant asked on
149
- // its own would answer about the rungs IT would be offered at, which is a
150
- // different list. Null means "decide it here", which is what a base does.
151
- inheritedAudioSeparate = null,
152
- segmentFormatId = "",
153
- // The cut grid of the session this one is a quality variant of: its
154
- // keyframe times and which container they were read from. Present only for
155
- // a variant of a session cut at the source's keyframes, and it is what
156
- // makes the two interchangeable.
157
- inheritedGrid = null,
158
- // "manual" when the viewer chose this size by hand, "auto" when it is the
159
- // automatic choice; left out, a size produced exactly counts as chosen by
160
- // hand. Decides whether an output already here may serve them instead.
161
- servingMode = null,
162
- // What the requesting viewer's link measured, or null.
163
- viewerLinkMbps = null,
164
- // The nominal bitrate limit asked for, in kbit/s, or null for the size's
165
- // own. Part of the output's identity: another limit is another output.
166
- capKbps = null,
167
- // The soundtrack THIS viewer receives with the picture — from this output
168
- // or beside it — as `{ transcode, entry }`. Left out, the one this
169
- // request names is theirs. A step opened on a viewer's behalf passes the
170
- // track they chose, which need not be the one the picture was opened with.
171
- viewerAudio = undefined,
172
- visiblePicture = null,
173
- // WHETHER THE REQUESTER MAY BE PUT ON THE OUTPUT, and putting them there,
174
- // in one synchronous call (roadmap item 97, step 14). Called with the
175
- // output the moment it answers the request — a new one registered, or one
176
- // already here — and before anything else can run, so that the place it
177
- // takes on this machine is counted before the next opening is asked.
178
- // Returns `{ admitted, reason, speedX }`; a refusal is thrown as
179
- // OUTPUT_NO_CAPACITY and a new output made for it is withdrawn. Who the
180
- // requester is stays with the caller: this is handed an opaque call.
181
- // Absent — a step or a soundtrack opened on a viewer's behalf, whose place
182
- // the preparation already holds — nothing is asked.
183
- claim = null
184
- }) {
185
- if (!this.#host.enabled) {
186
- const error = new Error("Audio transcoding is disabled on this proxy.");
187
- error.code = "TRANSCODE_DISABLED";
188
- throw error;
189
- }
190
-
191
- // The container is the viewer's to choose, because the viewer's browser is
192
- // what has to decode the result and only it knows what its media stack
193
- // accepts. A copied MP3 track is the case that forced this: hls.js demuxes
194
- // MPEG-TS itself and hands raw MP3 to an `audio/mpeg` buffer, which every
195
- // browser supports, while an fMP4 segment goes to MSE untouched and
196
- // `audio/mp4; codecs="mp3"` is refused — measured false in Chromium, where
197
- // `canPlayType` cheerfully answers "probably". Same file, same browser:
198
- // plays as MPEG-TS, silent loop as fMP4. The proxy's `--segment-format`
199
- // stays the default for a client that expresses no preference.
200
- // An unrecognised value falls back to the operator's choice rather than to
201
- // the library default — `resolveSegmentFormat` cannot tell the two apart,
202
- // and this value arrives from a client.
203
- const segmentFormat = SEGMENT_FORMAT_IDS.includes(segmentFormatId)
204
- ? resolveSegmentFormat(segmentFormatId)
205
- : this.#host.segmentFormat;
206
-
207
- const normalizedTargetWidth = Number.isInteger(targetWidth) && targetWidth > 0 ? targetWidth : 0;
208
- const normalizedTargetHeight = Number.isInteger(targetHeight) && targetHeight > 0 ? targetHeight : 0;
209
- // Round seek position to the nearest 10 s so that two consumers seeking
210
- // to similar positions can share the same ffmpeg session.
211
- const normalizedStartPosition =
212
- Number.isFinite(startPositionSeconds) && startPositionSeconds > 0
213
- ? Math.round(startPositionSeconds / 10) * 10
214
- : 0;
215
- const normalizedAudioTrack =
216
- Number.isInteger(audioTrackIndex) && audioTrackIndex > 0 ? audioTrackIndex : 0;
217
- // Which FILE the chosen soundtrack lives in, and which track it is inside
218
- // that file. A release often ships its dub as a file of its own beside the
219
- // picture, and the number that travels between the browser, this route and
220
- // the `a/<n>/` address is flat across both — see `audio-inventory.js`. This
221
- // is the one place that resolves it, so nothing downstream carries two
222
- // vocabularies.
223
- const audioSource = this.#host.renditions.resolveAudioSource(sourceKey, fileIndex, normalizedAudioTrack);
224
- // HOW the soundtrack is produced, decided here, before anything is named by
225
- // it, by the rule every choice of a track uses (`chooseSoundtrackMode`):
226
- // the request says whether the browser plays the track as it is, and the
227
- // inventory whether anything states what a copy of it weighs. A track with
228
- // no figure is re-encoded even for a browser that would play it, because a
229
- // copy of it is a load no link can be asked about. Whatever is decided is
230
- // what the output IS — its key, its ffmpeg arguments, the link's question —
231
- // and what the viewer is recorded as receiving.
232
- const soundtrackMode = chooseSoundtrackMode({
233
- entry: audioSource.entry,
234
- browserPlays: transcodeAudio !== true,
235
- // Nothing reaches this line on a proxy whose transcoding is off: the
236
- // opening refuses every request above, so here re-encoding is allowed.
237
- transcodeAllowed: true
238
- });
239
- const audioTranscoded = soundtrackMode.transcode === true;
240
- if (soundtrackMode.cause === SOUNDTRACK_MODE_CAUSE.NO_FIGURE) {
241
- this.#host.logger.info(
242
- `transcode "${fileName || `file ${fileIndex}`}": audio track ${normalizedAudioTrack} — ${soundtrackMode.cause}; it is sent as AAC`
243
- );
244
- }
245
- // What the requester receives of the sound, handed back so the viewer who
246
- // asked can be told apart from another viewer of the same output.
247
- const audio = { trackIndex: normalizedAudioTrack, transcode: audioTranscoded };
248
- // The file itself, held once for every session of it. Its name, its key and
249
- // the facts a probe of it returned used to be copied onto each session, so
250
- // two viewers of one film held two copies of numbers that cannot differ —
251
- // and twenty places assembled its key by hand to reach the caches that are
252
- // keyed by a file.
253
- const file = this.#host.sourceFiles.get(sourceKey, fileIndex, fileName);
254
- const forceExactSize = exactSize === true && transcodeVideo;
255
- // Whether this output carries its sound at all — decided HERE, before the
256
- // key, and never derived a second time.
257
- //
258
- // It used to be settled after the session had already been put in the map,
259
- // which was survivable only while the key carried the audio parameters
260
- // unconditionally: the key could say "no sound in this output" while the
261
- // output muxed it, and two viewers who chose different languages would then
262
- // have shared one encode and one of them would have heard the other's.
263
- const audioSeparate = inheritedAudioSeparate === null
264
- ? this.#host.renditions.audioTravelsSeparately({
265
- sourceKey,
266
- fileIndex,
267
- audioRenditions,
268
- // The rung this session will be NAMED by. The budget may still
269
- // downscale the encode below it, and that cannot change the answer:
270
- // what it picks is a rung of the same ladder, already in the set.
271
- ownHeight: normalizedTargetHeight
272
- })
273
- : inheritedAudioSeparate === true;
274
- // A rendition IS the sound, so it carries it whatever the arrangement says;
275
- // a picture carries it only when the browser is not taking it separately.
276
- const carriesAudio = audioOnly === true || !audioSeparate;
277
- const carriesVideo = audioOnly !== true;
278
- const createEntryMs = Date.now();
279
- // The directory belongs to the OUTPUT, not to this session: two sessions
280
- // whose parameters agree produce interchangeable segments, so they write
281
- // into one place and each serves what the other has already made. The start
282
- // position is deliberately not part of it — segment 42 covers the same span
283
- // whoever began where.
284
- // The file this session's encoder READS. A soundtrack shipped as its own
285
- // file is encoded FROM that file, and an audio rendition carries nothing
286
- // else — so it reads the sidecar directly and needs no second input at all.
287
- // The muxed case, where a browser takes its audio inside the picture's own
288
- // stream, is the one that reads two files.
289
- //
290
- // Which of the two this is used to be a boolean on the session
291
- // (`readsSidecarAlone`) beside a string URL built from it. It is the same
292
- // statement as "the file it reads is not the file of the picture", so it is
293
- // that comparison now and there is nothing to keep in step.
294
- const audioFile = this.#host.sourceFiles.get(sourceKey, audioSource.fileIndex, audioSource.name);
295
- const inputFile = audioOnly === true && audioSource.isSidecar ? audioFile : file;
296
- // Media info (duration/resolution/fps/startTime/HDR) up front, so we can
297
- // serve a complete VOD playlist (#EXT-X-ENDLIST) with the correct total
298
- // duration and a fully seekable timeline before a single segment exists.
299
- // Reuse the planner's probe when it is available and complete — the plan
300
- // request just ran the same ffmpeg scan over the same input. Fall back to
301
- // a fresh probe otherwise (proxy restarted between plan and session, or a
302
- // critical field is missing).
303
- const mediaInfoStartMs = Date.now();
304
- const cachedMediaInfo = this.#host.getCachedMediaInfo?.({ sourceKey, fileIndex }) ?? null;
305
- const cachedUsable =
306
- cachedMediaInfo &&
307
- Number.isFinite(cachedMediaInfo.durationSeconds) &&
308
- cachedMediaInfo.durationSeconds > 0 &&
309
- Number.isFinite(cachedMediaInfo.width) &&
310
- cachedMediaInfo.width > 0 &&
311
- Number.isFinite(cachedMediaInfo.height) &&
312
- cachedMediaInfo.height > 0;
313
- // Always the PICTURE's, even when this session reads a soundtrack from
314
- // another file: the timeline, the duration and the cut grid are the
315
- // picture's, and a rendition exists to be played WITH it. Only where the
316
- // sidecar's own timeline begins is read from the sidecar, just below.
317
- // No session id on it: this read is a probe of the picture, not this
318
- // session's own delivery, and counting it against the session would tell a
319
- // waiting browser that its film is arriving when what arrived was a header.
320
- const pictureUrl = file.streamUrl(this.#host.localBaseUrl);
321
- const mediaInfo = cachedUsable
322
- ? cachedMediaInfo
323
- : await this.#host.probeMediaInfo(pictureUrl.toString());
324
- const mediaInfoMs = Date.now() - mediaInfoStartMs;
325
- const mediaInfoSource = cachedUsable ? "cached" : "probed";
326
- // The file takes in what the probe said. It is the same answer for every
327
- // session of this file — a quality step, a soundtrack, a second viewer — so
328
- // it is kept once instead of being copied into each. A later session with a
329
- // fresher reading updates it: on a cold torrent the first probe can come
330
- // back without a duration, and the second is the one that has it.
331
- file.learn(mediaInfo);
332
- const durationSeconds = file.durationSeconds ?? 0;
333
- const sourceWidth = file.width;
334
- const sourceHeight = file.height;
335
- const sourceStartTime = file.startTime;
336
- // Where the timeline of a soundtrack shipped as its own file begins.
337
- //
338
- // A soundtrack in another file has a start time of its own, and it is the
339
- // one that must be subtracted when the output is relabelled onto a
340
- // zero-based timeline: subtract the picture's instead and the sound sits at
341
- // a fixed offset from it for the whole film. Read from the file rather than
342
- // assumed to be zero, because assuming it is exactly the fault being
343
- // avoided.
344
- //
345
- // NOT awaited. Creating a session used to stop here until the answer came
346
- // back, and on a cold start the answer needs the sidecar's header off the
347
- // swarm — 8121 ms of every session created, measured three times out of
348
- // three on 2026-09-03. What is known now is used now, and the reading runs
349
- // behind; when it lands it lands on the FILE, which every session of that
350
- // soundtrack shares, so the spawn path sees it without re-reading anything.
351
- //
352
- // Unknown means "no difference between the two timelines", not "the
353
- // soundtrack starts at zero". The shift exists to correct a difference
354
- // between two containers; asserting one that has not been read is inventing
355
- // a number, while assuming none leaves the sound exactly where a release
356
- // remuxed from a single source puts it.
357
- if (audioSource.isSidecar) {
358
- this.#host.renditions.warmFileStartTime(audioFile);
359
- }
360
- // Tone-map an HDR source to SDR only when re-encoding video on the software
361
- // path and this ffmpeg has the filters. Hardware encoders keep their own
362
- // (untone-mapped) path for now; when unavailable, HDR falls back to a plain
363
- // 8-bit convert (washed-out but playable).
364
- const applyTonemap =
365
- transcodeVideo === true &&
366
- mediaInfo.isHdr === true &&
367
- this.#host.tonemapSupported &&
368
- this.#host.videoEncoder?.kind === "software";
369
- // Output frame rate inherited from the source (integer, capped) so 25/30
370
- // fps content is not resampled to 24. Fixed-GOP encoders keep the fps↔GOP
371
- // relationship exact; time-based-keyframe encoders just use it as the rate.
372
- const outputFps = chooseOutputFps(mediaInfo.fps);
373
- const hasDuration = Number.isFinite(durationSeconds) && durationSeconds > 0;
374
- const logName = file.name;
375
-
376
- // Size the reader's window in seconds of playback rather than bytes. Needs
377
- // the file's own average byte rate, which is size ÷ duration; the size
378
- // comes from the same stats call the realtime budget uses. Best effort —
379
- // without it the reader keeps its own byte default.
380
- //
381
- // Sized for the file being READ, which for a soundtrack shipped separately
382
- // is that file: it is a twentieth of the picture's size over the same
383
- // duration, so the picture's byte rate would buy a window twenty times
384
- // wider than the seconds it is meant to represent, and the piece store
385
- // would hold it.
386
- const readWindowBytes = await this.#host.hostLoad.readWindowBytesFor(
387
- inputFile.sourceKey,
388
- inputFile.fileIndex,
389
- durationSeconds
390
- );
391
- if (!hasDuration) {
392
- this.#host.logger.warn(
393
- `transcode "${logName}": could not probe duration; falling back to ` +
394
- "ffmpeg-managed (growing) playlist"
395
- );
396
- }
397
-
398
- // For the video-copy path we cannot insert keyframes, so the playlist's
399
- // segment boundaries must match the source's real keyframes (otherwise the
400
- // player sees gaps on seek). Re-encoded video uses a uniform grid for
401
- // segment boundaries instead (its fixed GOP makes the cuts land there —
402
- // computeSegmentBoundaries ignores keyframeTimes when transcodeVideo).
403
- //
404
- // But the probe is ALSO used for something both branches need: choosing a
405
- // SOURCE seek position ffmpeg can actually land on. `-ss` before `-i` trusts
406
- // the container's own on-the-fly seek/index, which for some containers
407
- // (observed: AVI with VBR MP3 audio) can point at a position with no valid
408
- // frame boundary at all — ffmpeg then fails outright ("Seek failed" /
409
- // "Header missing"), not just imprecisely. Snapping the seek to the nearest
410
- // KNOWN real keyframe (see #startEncodeRun) avoids that. So probe for both
411
- // branches; on failure both fall back to their current behaviour (uniform
412
- // grid for boundaries, raw target for seeking) — no regression.
413
- // The file's own table — the object every reader of this file holds, so a
414
- // read that answers after this session was made still reaches it.
415
- const keyframes = this.#host.keyframeTables.of({ sourceKey, fileIndex });
416
- let keyframeMs = -1; // -1 = not run (skipped), -2 = running in the background
417
- // A quality variant of a session whose cuts are the source's keyframes must
418
- // be cut at exactly those same times, or its segments cannot stand where
419
- // the other's would have. Nothing has to be handed over for that: the table
420
- // is the FILE's, and a variant is a session of the same file, so it reads
421
- // the one answer. What the inherited grid still carries is the CORRECTED
422
- // boundaries and the published playlist, which are properties of the family
423
- // rather than of the file.
424
- if (inheritedGrid) {
425
- // Nothing to read: the table above IS the file's, corrections included.
426
- } else if (hasDuration && !transcodeVideo && !audioOnly) {
427
- // Video-COPY path: the keyframe times are REQUIRED to build correct
428
- // segment boundaries (the playlist itself), so this MUST block session
429
- // creation — an incorrect playlist is worse than a slower start.
430
- //
431
- // The wait is bounded, and the bound is what the read costs on a real
432
- // host rather than a figure picked here (`KEYFRAME_TABLE_BUDGET_MS`). A
433
- // comment in this place used to promise a short timeout and "never more
434
- // than ~6 s to session start" when no timeout existed at all; the file
435
- // comes off a torrent, so the bytes the table lives in may still be
436
- // arriving, and a session used to wait for them without limit.
437
- //
438
- // What is read is the container's OWN table (Cues/stss) rather than a
439
- // scan of the media. On the copy path ffmpeg can only cut at the source's
440
- // existing keyframes, so these times ARE the segment boundaries —
441
- // declaring an even grid instead is a falsehood the player punishes: it
442
- // walks the whole file to rebuild the timeline, or presents audio with no
443
- // picture because a segment starts with nothing decodable (both
444
- // field-observed 2026-08-02). Scanning cannot supply them here — the file
445
- // comes off a torrent, and a full packet scan of 5.5 GB found 77
446
- // keyframes in 45 s without finishing, while the container index yields
447
- // all 570 in 0.8 s from two point reads (16 KB).
448
- const keyframeStartMs = Date.now();
449
- const { arrived } = await this.#host.keyframeTables.within({ sourceKey, fileIndex, logName });
450
- keyframeMs = Date.now() - keyframeStartMs;
451
- if (!arrived) {
452
- // A read that ran out of its budget is still running, and one that
453
- // found its bytes not downloaded yet is made again when they arrive;
454
- // either way the table is still unanswered — which is not the same as a file with no keyframes,
455
- // and the distinction is the table's own (`answered` against
456
- // `readable`). Recorded as an absence it would make a passing shortage
457
- // of bytes look like a property of the bytes, and every later session
458
- // of the file would re-encode a picture that can be copied.
459
- this.#host.logger.warn(
460
- `transcode: the keyframe table for "${logName}" has not arrived after ${keyframeMs}ms ` +
461
- `(budget ${Math.round(this.#host.keyframeTables.budgetMs / 1000)}s), so this session re-encodes the picture ` +
462
- "instead of copying it; the read goes on and the next session of this file gets the copy"
463
- );
464
- }
465
- if (!keyframes.readable) {
466
- // No index, so there is no honest grid for a COPY: a copied picture can
467
- // only be cut at the source's own keyframes, and we do not know where
468
- // they are. Declaring an even grid instead is a falsehood the player
469
- // punishes — it walks the whole file to rebuild the timeline, or shows
470
- // audio with no picture because a segment begins with nothing
471
- // decodable (both field-observed 2026-08-02).
472
- //
473
- // Re-encoding is the honest answer and costs an encoder: keyframes are
474
- // then PLACED at our own cut times rather than found, so the grid is
475
- // correct by construction whatever the container. MPEG-TS is the case
476
- // this exists for — measured 2026-08-21, 669 real keyframes and no
477
- // index of any kind to read them from — and a container whose index
478
- // could not be read in the budget lands here too, which is right for
479
- // the same reason.
480
- transcodeVideo = true;
481
- if (keyframes.answered) {
482
- this.#host.logger.warn(
483
- `transcode: no keyframe index in the ${keyframes.format} container for ` +
484
- `"${logName}" — a copied picture has no honest grid without one, so the video is ` +
485
- "re-encoded instead and its keyframes are placed on our own cuts"
486
- );
487
- }
488
- }
489
- } else if (hasDuration && transcodeVideo) {
490
- // Re-encode path: keyframeTimes are ONLY used to snap a LATER seek (see
491
- // #startEncodeRun) — segment boundaries stay on the uniform grid either
492
- // way. So this does NOT need to block session creation / the first
493
- // segment's start. Run it in the background with a FULL budget instead of
494
- // the 6 s cap: AVI-class containers need a full packet scan, which 6 s can
495
- // never afford without delaying playback start — that starved budget is
496
- // exactly why the probe kept missing on the container where the seek bug
497
- // was field-diagnosed. A run reads the file's table on every call, so a
498
- // seek that happens AFTER this finishes picks it up automatically; one
499
- // that happens before falls back to the existing circuit breaker as a
500
- // safety net (no regression either way).
501
- keyframeMs = -2;
502
- const backgroundStartedAt = Date.now();
503
- void this.#host.probeKeyframeTimes(inputFile.streamUrl(this.#host.localBaseUrl).toString(), 25_000).then((times) => {
504
- // Into the FILE's table, which the picture, its quality steps and a
505
- // second viewer's session all hold — so nothing has to be alive for the
506
- // answer to be kept, and the session this probe was started for may
507
- // long since have gone. It used to be written onto whichever session
508
- // was still there, and dropped outright when none was.
509
- this.#host.keyframeTables.learn({ sourceKey, fileIndex }, { times, format: "packet probe" });
510
- const elapsedMs = Date.now() - backgroundStartedAt;
511
- this.#host.logger.info(
512
- times
513
- ? `transcode: background keyframe probe found ${times.length} keyframes ` +
514
- `(${elapsedMs}ms) for "${logName}" — later seeks will snap to them`
515
- : `transcode: background keyframe probe unavailable (${elapsedMs}ms) for "${logName}" ` +
516
- `— seeks keep using the raw target (falls back to the circuit breaker on failure)`
517
- );
518
- });
519
- }
520
- this.#host.logger.info(
521
- `cold-start "${logName}": media-info=${mediaInfoMs}ms (${mediaInfoSource}) ` +
522
- `keyframes=${keyframeMs === -1 ? "skipped" : keyframeMs === -2 ? "background" : `${keyframeMs}ms`} ` +
523
- `create-total=${Date.now() - createEntryMs}ms`
524
- );
525
- // Which grid this session is cut on. A copy has no choice: only where the
526
- // source already has a keyframe. A re-encode normally takes the even grid —
527
- // it produces every frame and may put keyframes where it likes — unless it
528
- // is a variant of a keyframe-cut session, in which case it must land on the
529
- // same times to be interchangeable with it.
530
- // An audio rendition carries no picture, so it has no keyframes of its own
531
- // to be cut at: it takes the grid of the video it accompanies, whatever that
532
- // is. Handed one, it uses it; handed none, the base is on the even grid and
533
- // so is this. Falling into the COPY branch instead — which is what
534
- // `transcodeVideo: false` means everywhere else — would put the audio of a
535
- // re-encoded stream on the source's keyframe times while the player was
536
- // told the even grid, and the two drift further apart with every segment.
537
- const useKeyframeGrid = hasDuration &&
538
- keyframes.readable &&
539
- (audioOnly ? inheritedGrid != null : (!transcodeVideo || inheritedGrid != null));
540
- // A rung takes the grid it was handed, rather than working one out again
541
- // from the same index. The two are not the same table: the one it is handed
542
- // has been CORRECTED wherever a produced segment showed the index to be
543
- // wrong, and it is those corrected times the copy actually cuts at. Building
544
- // it afresh here would put the rung back on the index's fiction and undo the
545
- // alignment it exists for.
546
- // The file's own table, made once and shared by every session of it. A
547
- // quality step is a different OUTPUT and the same cuts — which is exactly
548
- // the agreement `inheritedGrid` used to arrange by handing a copy to each
549
- // new session — so it is keyed by the file and the kind of grid, and
550
- // nothing else.
551
- const timeline = this.#host.timelines.get(
552
- Timelines.keyFor(sourceKey, fileIndex, useKeyframeGrid ? "keyframe" : "uniform"),
553
- () => {
554
- const cut = hasDuration
555
- ? computeCutGrid({
556
- useKeyframeGrid,
557
- durationSeconds,
558
- segDur: this.#host.segmentDurationSec,
559
- keyframeTimes: keyframes.times,
560
- startTime: sourceStartTime
561
- })
562
- : { boundaries: [], sourceTimes: [] };
563
- const inherited = Array.isArray(inheritedGrid?.boundaries) && inheritedGrid.boundaries.length > 1;
564
- return new Timeline({
565
- boundaries: inherited ? [...inheritedGrid.boundaries] : cut.boundaries,
566
- // The file's own clock for those cuts. An inherited table brings its
567
- // boundaries and not this, so the seek falls back to searching there.
568
- sourceTimes: inherited ? null : cut.sourceTimes,
569
- cutGrid: useKeyframeGrid ? "keyframe" : "uniform"
570
- });
571
- }
572
- );
573
- // What this session will PUBLISH. A member of a family takes its base's
574
- // published table verbatim; a session with no base publishes what it cuts
575
- // at. The two differ exactly by the corrections made since the family's
576
- // first playlist was written, and that difference is what must never reach
577
- // the player as two different timelines.
578
- const publishedGrid = timeline.published.length > 1 ? timeline.published : null;
579
- const segmentCount = timeline.segmentCount;
580
-
581
- // THE FORMAT, decided before the output is named, and possibly an output
582
- // already here instead (`encode/quality/output-format.js`).
583
- const decided = decideOutputFormat({
584
- encodesPicture: transcodeVideo && carriesVideo,
585
- exact: forceExactSize,
586
- target: this.#targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }),
587
- source: { width: sourceWidth, height: sourceHeight, megabitsPerSecond: file.decode?.megabitsPerSecond ?? null, decode: file.decode },
588
- fps: outputFps,
589
- encoder: this.#host.videoEncoder,
590
- benchmark: this.#host.softwarePresetBenchmark,
591
- cost: {
592
- decodeModel: this.#host.decodeCostModel,
593
- observedDecodeCostSec: this.#host.encodeCost.decodeCostFor(file.key)?.costSec ?? null,
594
- requiredSpeed: this.#host.hostLoad.requiredSpeedFor(sourceKey, fileIndex)
595
- },
596
- chooseBudget: (params) => this.#host.encodeCost.chooseEncodeBudget(params),
597
- machineAdmission: this.#host.admission
598
- ? (candidate) => this.#host.admission.previewCandidate(candidate, file)
599
- : null,
600
- tonemap: applyTonemap,
601
- capKbps,
602
- limitsFor: (frame) => this.#host.limitsFor(frame),
603
- audioLoad: viewerAudio !== undefined
604
- ? soundtrackLoadOf(viewerAudio?.entry ?? null, viewerAudio ? viewerAudio.transcode : null)
605
- : soundtrackLoadOf(audioSource.entry, audioTranscoded),
606
- specWith: (encode) => new OutputSpec({
607
- sourceKey,
608
- segmentFormatId: segmentFormat.id,
609
- // Where it is ACTUALLY cut: a copy whose container states no keyframes
610
- // is re-encoded onto the even grid, and is named so.
611
- grid: new CutGrid({ kind: useKeyframeGrid ? "keyframe" : "uniform", fileIndex }),
612
- video: carriesVideo ? new VideoOutput({ fileIndex, encode }) : null,
613
- audio: carriesAudio
614
- ? new AudioOutput({ fileIndex: audioSource.fileIndex, trackIndex: audioSource.sourceTrackIndex, transcode: audioTranscoded })
615
- : null
616
- }),
617
- serving: {
618
- mode: servingMode ?? (forceExactSize ? "manual" : "auto"),
619
- linkMbps: viewerLinkMbps,
620
- keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentOutputFiles.addresses()),
621
- readyAt: (key) => this.#host.segmentOutputFiles.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
622
- observedPeakMbps: (candidate) => this.#host.observedPeakMbps?.(candidate) ?? null
623
- }
624
- });
625
- if (decided.unavailable) {
626
- this.#host.logger.info(
627
- `transcode "${logName}": no output suits this viewer — ${decided.unavailable.reason} ` +
628
- `${JSON.stringify(decided.unavailable.figures)} (wanted ${decided.wantedKey})`
629
- );
630
- const error = new Error(`No output suits this viewer: ${decided.unavailable.reason}.`);
631
- // Bound by the MACHINE rather than by the viewer's link, for the output a
632
- // viewer is opening: another proxy is the answer, found before anything
633
- // plays. A step asked for on their behalf stays "unavailable", which is
634
- // how every caller of a step already reads a refusal.
635
- error.code = decided.unavailable.bound === "machine" && typeof claim === "function"
636
- ? OUTPUT_NO_CAPACITY
637
- : OUTPUT_UNAVAILABLE;
638
- error.details = {
639
- reason: decided.unavailable.reason,
640
- // How many soundtracks the viewer could choose instead, so the page can
641
- // offer another one only where there is one to offer.
642
- figures: decided.unavailable.figures
643
- ? { ...decided.unavailable.figures, soundtracks: this.#host.renditions.offeredSoundtrackCount(sourceKey, fileIndex) }
644
- : null,
645
- wantedKey: decided.wantedKey
646
- };
647
- throw error;
648
- }
649
- if (decided.answer) {
650
- this.#host.logger.info(
651
- `transcode "${logName}": ${decided.answer.verdict} for this viewer ${JSON.stringify(linkFiguresOf(decided.answer))}`
652
- );
653
- }
654
- const spec = decided.spec;
655
- const budget = decided.budget;
656
- if (decided.reusedKey) {
657
- this.#host.logger.info(`transcode "${logName}": served by an output already here, ${decided.reusedKey}, instead of ${decided.wantedKey}`);
658
- }
659
- transcodeVideo = carriesVideo ? spec.transcodesVideo : transcodeVideo;
660
- const width = spec.video?.encode?.width ?? 0;
661
- const height = spec.video?.encode?.height ?? 0;
662
- const outputKey = spec.toKey();
663
- // THE NAME FOLLOWS FROM THE KEY, so there is nothing to look it up in. A
664
- // second table held key → name, which is a fact that can go out of step
665
- // with the thing it points at: a session disposed without the table being
666
- // cleared leaves a name pointing at nothing, and the next viewer of that
667
- // output is handed it.
668
- const existingId = spec.toName();
669
- if (existingId) {
670
- const existing = this.#host.outputs.get(existingId);
671
- if (existing) {
672
- this.#claimOrRefuse(claim, existing, logName);
673
- return { output: existing, existed: true, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
674
- }
675
- }
676
-
677
- // Only a session actually made is timed: a viewer joining one costs none
678
- // of what this figure predicts for the next viewer who has to wait.
679
- this.#host.hostTimings.rememberSessionCreateLatency(Date.now() - createEntryMs);
680
- const sessionId = spec.toName();
681
- const output = new Output({
682
- encodeWidth: width,
683
- encodeHeight: height,
684
- outputFps,
685
- softwarePreset: spec.video?.encode?.preset ?? null,
686
- applyTonemap: spec.video?.encode?.tonemap === true
687
- });
688
-
689
- const session = new EncodedOutput({
690
- id: sessionId,
691
- spec,
692
- file,
693
- keyframes,
694
- timeline,
695
- segmentFormat,
696
- output,
697
- useSyntheticPlaylist: hasDuration,
698
- playlistText: hasDuration ? mediaPlaylistText({ boundaries: publishedGrid, segmentFormat }) : "",
699
- variantHeight: forceExactSize && height > 0 ? height : undefined
700
- });
701
- this.#host.outputs.set(sessionId, session);
702
- // THE PLACE ON THIS MACHINE, taken in the same synchronous stretch as the
703
- // registration: priced as registered, and withdrawn whole if refused, so a
704
- // refused opening leaves nothing behind — no directory, no timing.
705
- try {
706
- this.#claimOrRefuse(claim, session, logName);
707
- } catch (error) {
708
- this.#host.outputs.delete(sessionId);
709
- throw error;
710
- }
711
-
712
- // Only now, when nothing above can still throw. Everything from the probe
713
- // to the keyframe index used to run with the directory already made, so a
714
- // failure between the two left it behind: nothing tracks a directory whose
715
- // session was never registered, and no sweep looks for one. Proxy
716
- // 2.9.101-2.9.102 failed here on every single request and the leftovers
717
- // were the only trace of it on disk.
718
- // A RETURN, if this output was held before — and its age, which is the one
719
- // term of the keeping period that nothing measures. Read BEFORE the
720
- // directory is claimed, since claiming it is what marks it read.
721
- this.#host.returns.note({ lastReadAt: this.#host.segmentOutputFiles.lastReadAt(spec.toKey()), now: Date.now() });
722
- this.#host.segmentOutputFiles.directoryFor(spec.toKey());
723
- this.#host.segmentOutputFiles.useFormat(spec.toKey(), segmentFormat);
724
- this.#host.hostTimings.noteOutputCreated(session, createEntryMs);
725
- this.#host.encodeRuns.setReadWindow(session, readWindowBytes);
726
- this.#host.encodeCost.notePredictionFor(session, output.encodeHeight);
727
- // Decided before the key was built and only recorded here. Whether the audio
728
- // travels separately decides the ffmpeg arguments, what the master says,
729
- // whether the rendition route answers at all AND what the session is keyed
730
- // on, and those four must agree for the whole life of the session — a
731
- // session whose picture was encoded without audio cannot start muxing it in
732
- // at the next restart without either playing it twice or refusing the
733
- // append, and one keyed as carrying no sound must never mux somebody else's
734
- // language into a picture two viewers share.
735
- //
736
- // It must not be asked a second time, because the answer moves: the offered
737
- // list is recomputed as the host learns what this source costs, and
738
- // crossing "two rungs" would flip the arrangement under a stream that is
739
- // playing.
740
- this.#host.logger.info(
741
- // Proxy version on the session-start line: a field report always includes
742
- // one of these, so "is the host actually running the build I published?"
743
- // is answered by the log itself instead of a round trip to the machine.
744
- `transcode ${sessionId} start (proxy ${PROXY_VERSION}) "${logName}" ` +
745
- // Where the browser asked the encoder to begin. A resume that reaches
746
- // hls.js but not this call makes the player request a segment nobody
747
- // was told to produce: measured 2026-08-06, the session began at #0
748
- // while the player asked for #127 and gave up 45.6 s later. Neither
749
- // side saying what it meant is why that took three attempts to place.
750
- `start=${Math.round(normalizedStartPosition)}s ` +
751
- `video=${transcodeVideo ? `${this.#host.videoEncoder.name}${output.softwarePreset ? `/${output.softwarePreset}` : ""}` : "copy"} ` +
752
- `audio=${audioTranscoded ? "aac" : "copy"} ` +
753
- // Branch tag for log correlation: A = video re-encode (fixed GOP, grid
754
- // aligned, ts-offset); B = video copy (cut at source keyframes, copyts).
755
- `branch=${transcodeVideo ? "A(reencode,fixed-gop)" : "B(copy,copyts)"} ` +
756
- `seg=${timeline.cutGrid} ` +
757
- `${sourceWidth && sourceHeight ? `src=${sourceWidth}x${sourceHeight} ` : ""}` +
758
- // The size produced, and how it was arrived at: exactly as asked, the
759
- // budget's rung of the viewer's own ladder, or the box asked for where
760
- // there is no ladder to choose from.
761
- `${transcodeVideo
762
- ? `enc=${output.encodeWidth || "src"}x${output.encodeHeight || "src"}@${output.outputFps} ` +
763
- `size=${forceExactSize ? "exact" : budget ? `budget rung ${budget.rungIndex + 1}/${budget.ladder.length}` : "asked"} `
764
- : ""}` +
765
- // HDR source and whether the tone-map chain was applied (vs washed-out
766
- // fallback when the filters are missing or on a hardware encoder).
767
- `${transcodeVideo && mediaInfo.isHdr ? `hdr=1 tonemap=${applyTonemap ? "on" : "off"} ` : ""}` +
768
- `${sourceStartTime ? `start=${sourceStartTime.toFixed(3)} ` : ""}` +
769
- `duration=${hasDuration ? formatSeconds(durationSeconds) : "unknown"} segments=${segmentCount} ` +
770
- // What this session was keyed on, which is what decides whether the next
771
- // viewer joins it or starts a second encoder beside it. Printed because
772
- // a fork was undiagnosable without it: on 2026-09-03 two viewers of one
773
- // copied picture got two sessions with identical descriptions and
774
- // byte-identical output, both create requests were 265 bytes, and
775
- // nothing anywhere said what the two had been told apart by.
776
- `key=${outputKey}`
777
- );
778
-
779
- // Where the first encoder goes is the plan's, placed by the same arithmetic
780
- // as every later one from where the viewers stand; the requester is placed
781
- // by the operation that asked for this output.
782
- return { output: session, existed: false, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
783
- }
784
- }
1
+ /**
2
+ * @file Which output answers a request for a file, made if it is not here yet.
3
+ *
4
+ * A request names a file, the tracks wanted and a size; what answers it is an
5
+ * OUTPUT, and deciding which is the encoding component's: the arrangement of
6
+ * the sound, the cut grid, the format the budget settles on, and whether an
7
+ * output already here serves the request instead. Two requests whose outputs
8
+ * agree ARE one output. Who asked is not a parameter: placing the requester on
9
+ * the output is the server operation's business (`server/ViewerRequests.js`),
10
+ * and nothing about a viewer enters what is decided here.
11
+ *
12
+ * What the file says about itself is read by the media component and handed in
13
+ * (`probeMediaInfo`, `probeKeyframeTimes`), as is everything else this reads.
14
+ */
15
+
16
+ import { createRequire } from "node:module";
17
+ import { buildResolutionLadder, chooseOutputFps } from "./hwaccel.js";
18
+ import { resolveSegmentFormat, SEGMENT_FORMAT_IDS } from "./segment-formats/index.js";
19
+ import { AudioOutput, CutGrid, OUTPUT_NO_CAPACITY, OUTPUT_UNAVAILABLE, OutputSpec, VideoOutput } from "./output/index.js";
20
+ import { Timeline, Timelines } from "./output/Timeline.js";
21
+ import { computeCutGrid } from "./output/cut-grid.js";
22
+ import { Output } from "./output/Output.js";
23
+ import { mediaPlaylistText } from "./output/playlists.js";
24
+ import { formatSeconds } from "./EncodeRuns.js";
25
+ import { EncodedOutput } from "./output/EncodedOutput.js";
26
+ import { decideOutputFormat } from "./quality/output-format.js";
27
+ import { rungForVisiblePicture } from "./quality/visible-rung.js";
28
+ import { SOUNDTRACK_MODE_CAUSE, chooseSoundtrackMode, linkAnswerFigures as linkFiguresOf, soundtrackLoadOf } from "./quality/link-budget.js";
29
+
30
+ /**
31
+ * @typedef {Object} SegmentOutputFiles
32
+ * @property {() => string[]} addresses
33
+ * @property {(address: string, index: number) => boolean} isClosed
34
+ * @property {(address: string) => number | null} lastReadAt
35
+ * @property {(address: string) => string} directoryFor
36
+ * @property {(address: string, format: object) => void} useFormat
37
+ */
38
+
39
+ /** Own package version, stamped onto output-start log lines. */
40
+ const PROXY_VERSION = createRequire(import.meta.url)("../../package.json").version;
41
+
42
+ export class OutputOpening {
43
+ /** What this reads and asks of the rest of the proxy, and nothing else. @type {object} */
44
+ #host;
45
+
46
+ /**
47
+ * @param {object} host - `logger`, `probeMediaInfo`, `probeKeyframeTimes`, `enabled`, `segmentFormat`, `renditions`, `sourceFiles`, `getCachedMediaInfo`, `localBaseUrl`, `tonemapSupported`, `videoEncoder`, `hostLoad`, `keyframeTables`, `timelines`, `segmentDurationSec`, `softwarePresetBenchmark`, `decodeCostModel`, `encodeCost`, `admission`, `outputs`, `segmentOutputFiles`, `hostTimings`, `returns`, `encodeRuns`
48
+ * @param {SegmentOutputFiles} host.segmentOutputFiles - The storage
49
+ * operations needed while selecting or opening an output.
50
+ */
51
+ constructor(host) {
52
+ this.#host = host;
53
+ }
54
+
55
+ /**
56
+ * The box a re-encoded picture is fitted into.
57
+ *
58
+ * A box the request names is the box (a quality step names its height). With
59
+ * none named, the picture the viewer sees decides: the smallest rung of the
60
+ * source's ladder whose frame is not smaller than it (roadmap item 98). With
61
+ * neither, zeroes — the source's own size.
62
+ *
63
+ * @param {{ normalizedTargetWidth: number, normalizedTargetHeight: number, visiblePicture: { width: number, height: number } | null, sourceWidth: number, sourceHeight: number }} params
64
+ * @returns {{ width: number, height: number }}
65
+ */
66
+ #targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }) {
67
+ if (normalizedTargetWidth > 0 || normalizedTargetHeight > 0) {
68
+ return { width: normalizedTargetWidth, height: normalizedTargetHeight };
69
+ }
70
+ const rung = rungForVisiblePicture(
71
+ buildResolutionLadder(Math.round(Number(sourceWidth) || 0), Math.round(Number(sourceHeight) || 0)),
72
+ visiblePicture
73
+ );
74
+ return rung ? { width: rung.width, height: rung.height } : { width: 0, height: 0 };
75
+ }
76
+
77
+ /**
78
+ * Ask the requester's call whether they may be put on this output, and throw
79
+ * the refusal the way the route answers it.
80
+ *
81
+ * @param {((output: object) => { admitted: boolean, reason: string, speedX: number | null }) | null} claim
82
+ * @param {object} output
83
+ * @param {string} logName
84
+ * @returns {void}
85
+ */
86
+ #claimOrRefuse(claim, output, logName) {
87
+ if (typeof claim !== "function") {
88
+ return;
89
+ }
90
+ const answer = claim(output);
91
+ if (answer?.admitted) {
92
+ return;
93
+ }
94
+ const reason = answer?.reason || "this machine has no place for one more encoder";
95
+ this.#host.logger.info(`transcode "${logName}": not opened for this viewer — ${reason} (key=${output.outputKey})`);
96
+ const error = new Error(`This proxy cannot take this video now: ${reason}.`);
97
+ error.code = OUTPUT_NO_CAPACITY;
98
+ error.details = {
99
+ reason,
100
+ figures: { speedX: Number.isFinite(answer?.speedX) ? Number(answer.speedX.toFixed(3)) : null, outputKey: output.outputKey }
101
+ };
102
+ throw error;
103
+ }
104
+
105
+ /**
106
+ * The output that answers this request: one already here, or one made now.
107
+ * No encoder is started here — where encoders go is the plan's.
108
+ *
109
+ * Throws with `error.code === "TRANSCODE_DISABLED"` when transcoding is
110
+ * disabled on this proxy instance.
111
+ *
112
+ * @param {object} options
113
+ * @param {string} options.sourceKey - Registry source key.
114
+ * @param {number} options.fileIndex - Zero-based file index in the torrent.
115
+ * @param {boolean} [options.transcodeVideo=false]
116
+ * @param {boolean} [options.transcodeAudio=false]
117
+ * @param {string} [options.fileName=""] - Display name for log output.
118
+ * @param {number} [options.targetWidth=0] - Target video width (0 = keep source).
119
+ * @param {number} [options.targetHeight=0] - Target video height (0 = keep source).
120
+ * @param {number} [options.startPositionSeconds=0] - Seek start position in seconds.
121
+ * @param {number} [options.audioTrackIndex=0] - Type-relative audio track to map (0:a:N).
122
+ * @param {boolean} [options.exactSize=false] - Produce the target box exactly (capped to source), with no budget downscale and no runtime downswitch. Says nothing about who asked: every rung of a master sets it.
123
+ * @param {number | null} [options.capKbps=null] - Nominal bitrate limit in kbit/s; null for the size's own. Above the size's own it is refused.
124
+ * @param {{ width: number, height: number } | null} [options.visiblePicture=null] - The picture as the requesting viewer sees it, in physical pixels. With no target box given, a re-encoded picture's box is the smallest rung whose frame is not smaller than this (roadmap item 98).
125
+ * @returns {Promise<{ output: EncodedOutput, existed: boolean, audio: { trackIndex: number, transcode: boolean }, verdict: object | null }>}
126
+ */
127
+ async open({
128
+ sourceKey,
129
+ fileIndex,
130
+ transcodeVideo = false,
131
+ transcodeAudio = false,
132
+ fileName = "",
133
+ targetWidth = 0,
134
+ targetHeight = 0,
135
+ startPositionSeconds = 0,
136
+ audioTrackIndex = 0,
137
+ exactSize = false,
138
+ // The caller takes its audio from a rendition group, so the picture is
139
+ // encoded without it and each audio track is encoded once for the file
140
+ // instead of once per rung. Off unless asked for: a browser that does not
141
+ // know about renditions must still get its audio in the stream.
142
+ audioRenditions = false,
143
+ // This session IS one of those renditions: one audio track, no picture, cut
144
+ // on the same grid as the video it accompanies.
145
+ audioOnly = false,
146
+ // The arrangement decided by the session this one belongs to — a variant or
147
+ // a rendition of it. Every session of one master must agree about where the
148
+ // audio is, and only the base is in a position to decide: a variant asked on
149
+ // its own would answer about the rungs IT would be offered at, which is a
150
+ // different list. Null means "decide it here", which is what a base does.
151
+ inheritedAudioSeparate = null,
152
+ segmentFormatId = "",
153
+ // The cut grid of the session this one is a quality variant of: its
154
+ // keyframe times and which container they were read from. Present only for
155
+ // a variant of a session cut at the source's keyframes, and it is what
156
+ // makes the two interchangeable.
157
+ inheritedGrid = null,
158
+ // "manual" when the viewer chose this size by hand, "auto" when it is the
159
+ // automatic choice; left out, a size produced exactly counts as chosen by
160
+ // hand. Decides whether an output already here may serve them instead.
161
+ servingMode = null,
162
+ // What the requesting viewer's link measured, or null.
163
+ viewerLinkMbps = null,
164
+ // The nominal bitrate limit asked for, in kbit/s, or null for the size's
165
+ // own. Part of the output's identity: another limit is another output.
166
+ capKbps = null,
167
+ // The soundtrack THIS viewer receives with the picture — from this output
168
+ // or beside it — as `{ transcode, entry }`. Left out, the one this
169
+ // request names is theirs. A step opened on a viewer's behalf passes the
170
+ // track they chose, which need not be the one the picture was opened with.
171
+ viewerAudio = undefined,
172
+ visiblePicture = null,
173
+ // WHETHER THE REQUESTER MAY BE PUT ON THE OUTPUT, and putting them there,
174
+ // in one synchronous call (roadmap item 97, step 14). Called with the
175
+ // output the moment it answers the request — a new one registered, or one
176
+ // already here — and before anything else can run, so that the place it
177
+ // takes on this machine is counted before the next opening is asked.
178
+ // Returns `{ admitted, reason, speedX }`; a refusal is thrown as
179
+ // OUTPUT_NO_CAPACITY and a new output made for it is withdrawn. Who the
180
+ // requester is stays with the caller: this is handed an opaque call.
181
+ // Absent — a step or a soundtrack opened on a viewer's behalf, whose place
182
+ // the preparation already holds — nothing is asked.
183
+ claim = null
184
+ }) {
185
+ if (!this.#host.enabled) {
186
+ const error = new Error("Audio transcoding is disabled on this proxy.");
187
+ error.code = "TRANSCODE_DISABLED";
188
+ throw error;
189
+ }
190
+
191
+ // The container is the viewer's to choose, because the viewer's browser is
192
+ // what has to decode the result and only it knows what its media stack
193
+ // accepts. A copied MP3 track is the case that forced this: hls.js demuxes
194
+ // MPEG-TS itself and hands raw MP3 to an `audio/mpeg` buffer, which every
195
+ // browser supports, while an fMP4 segment goes to MSE untouched and
196
+ // `audio/mp4; codecs="mp3"` is refused — measured false in Chromium, where
197
+ // `canPlayType` cheerfully answers "probably". Same file, same browser:
198
+ // plays as MPEG-TS, silent loop as fMP4. The proxy's `--segment-format`
199
+ // stays the default for a client that expresses no preference.
200
+ // An unrecognised value falls back to the operator's choice rather than to
201
+ // the library default — `resolveSegmentFormat` cannot tell the two apart,
202
+ // and this value arrives from a client.
203
+ const segmentFormat = SEGMENT_FORMAT_IDS.includes(segmentFormatId)
204
+ ? resolveSegmentFormat(segmentFormatId)
205
+ : this.#host.segmentFormat;
206
+
207
+ const normalizedTargetWidth = Number.isInteger(targetWidth) && targetWidth > 0 ? targetWidth : 0;
208
+ const normalizedTargetHeight = Number.isInteger(targetHeight) && targetHeight > 0 ? targetHeight : 0;
209
+ // Round seek position to the nearest 10 s so that two consumers seeking
210
+ // to similar positions can share the same ffmpeg session.
211
+ const normalizedStartPosition =
212
+ Number.isFinite(startPositionSeconds) && startPositionSeconds > 0
213
+ ? Math.round(startPositionSeconds / 10) * 10
214
+ : 0;
215
+ const normalizedAudioTrack =
216
+ Number.isInteger(audioTrackIndex) && audioTrackIndex > 0 ? audioTrackIndex : 0;
217
+ // Which FILE the chosen soundtrack lives in, and which track it is inside
218
+ // that file. A release often ships its dub as a file of its own beside the
219
+ // picture, and the number that travels between the browser, this route and
220
+ // the `a/<n>/` address is flat across both — see `audio-inventory.js`. This
221
+ // is the one place that resolves it, so nothing downstream carries two
222
+ // vocabularies.
223
+ const audioSource = this.#host.renditions.resolveAudioSource(sourceKey, fileIndex, normalizedAudioTrack);
224
+ // HOW the soundtrack is produced, decided here, before anything is named by
225
+ // it, by the rule every choice of a track uses (`chooseSoundtrackMode`):
226
+ // the request says whether the browser plays the track as it is, and the
227
+ // inventory whether anything states what a copy of it weighs. A track with
228
+ // no figure is re-encoded even for a browser that would play it, because a
229
+ // copy of it is a load no link can be asked about. Whatever is decided is
230
+ // what the output IS — its key, its ffmpeg arguments, the link's question —
231
+ // and what the viewer is recorded as receiving.
232
+ const soundtrackMode = chooseSoundtrackMode({
233
+ entry: audioSource.entry,
234
+ browserPlays: transcodeAudio !== true,
235
+ // Nothing reaches this line on a proxy whose transcoding is off: the
236
+ // opening refuses every request above, so here re-encoding is allowed.
237
+ transcodeAllowed: true
238
+ });
239
+ const audioTranscoded = soundtrackMode.transcode === true;
240
+ if (soundtrackMode.cause === SOUNDTRACK_MODE_CAUSE.NO_FIGURE) {
241
+ this.#host.logger.info(
242
+ `transcode "${fileName || `file ${fileIndex}`}": audio track ${normalizedAudioTrack} — ${soundtrackMode.cause}; it is sent as AAC`
243
+ );
244
+ }
245
+ // What the requester receives of the sound, handed back so the viewer who
246
+ // asked can be told apart from another viewer of the same output.
247
+ const audio = { trackIndex: normalizedAudioTrack, transcode: audioTranscoded };
248
+ // The file itself, held once for every session of it. Its name, its key and
249
+ // the facts a probe of it returned used to be copied onto each session, so
250
+ // two viewers of one film held two copies of numbers that cannot differ —
251
+ // and twenty places assembled its key by hand to reach the caches that are
252
+ // keyed by a file.
253
+ const file = this.#host.sourceFiles.get(sourceKey, fileIndex, fileName);
254
+ const forceExactSize = exactSize === true && transcodeVideo;
255
+ // Whether this output carries its sound at all — decided HERE, before the
256
+ // key, and never derived a second time.
257
+ //
258
+ // It used to be settled after the session had already been put in the map,
259
+ // which was survivable only while the key carried the audio parameters
260
+ // unconditionally: the key could say "no sound in this output" while the
261
+ // output muxed it, and two viewers who chose different languages would then
262
+ // have shared one encode and one of them would have heard the other's.
263
+ const audioSeparate = inheritedAudioSeparate === null
264
+ ? this.#host.renditions.audioTravelsSeparately({
265
+ sourceKey,
266
+ fileIndex,
267
+ audioRenditions,
268
+ // The rung this session will be NAMED by. The budget may still
269
+ // downscale the encode below it, and that cannot change the answer:
270
+ // what it picks is a rung of the same ladder, already in the set.
271
+ ownHeight: normalizedTargetHeight
272
+ })
273
+ : inheritedAudioSeparate === true;
274
+ // A rendition IS the sound, so it carries it whatever the arrangement says;
275
+ // a picture carries it only when the browser is not taking it separately.
276
+ const carriesAudio = audioOnly === true || !audioSeparate;
277
+ const carriesVideo = audioOnly !== true;
278
+ const createEntryMs = Date.now();
279
+ // The directory belongs to the OUTPUT, not to this session: two sessions
280
+ // whose parameters agree produce interchangeable segments, so they write
281
+ // into one place and each serves what the other has already made. The start
282
+ // position is deliberately not part of it — segment 42 covers the same span
283
+ // whoever began where.
284
+ // The file this session's encoder READS. A soundtrack shipped as its own
285
+ // file is encoded FROM that file, and an audio rendition carries nothing
286
+ // else — so it reads the sidecar directly and needs no second input at all.
287
+ // The muxed case, where a browser takes its audio inside the picture's own
288
+ // stream, is the one that reads two files.
289
+ //
290
+ // Which of the two this is used to be a boolean on the session
291
+ // (`readsSidecarAlone`) beside a string URL built from it. It is the same
292
+ // statement as "the file it reads is not the file of the picture", so it is
293
+ // that comparison now and there is nothing to keep in step.
294
+ const audioFile = this.#host.sourceFiles.get(sourceKey, audioSource.fileIndex, audioSource.name);
295
+ const inputFile = audioOnly === true && audioSource.isSidecar ? audioFile : file;
296
+ // Media info (duration/resolution/fps/startTime/HDR) up front, so we can
297
+ // serve a complete VOD playlist (#EXT-X-ENDLIST) with the correct total
298
+ // duration and a fully seekable timeline before a single segment exists.
299
+ // Reuse the planner's probe when it is available and complete — the plan
300
+ // request just ran the same ffmpeg scan over the same input. Fall back to
301
+ // a fresh probe otherwise (proxy restarted between plan and session, or a
302
+ // critical field is missing).
303
+ const mediaInfoStartMs = Date.now();
304
+ const cachedMediaInfo = this.#host.getCachedMediaInfo?.({ sourceKey, fileIndex }) ?? null;
305
+ const cachedUsable =
306
+ cachedMediaInfo &&
307
+ Number.isFinite(cachedMediaInfo.durationSeconds) &&
308
+ cachedMediaInfo.durationSeconds > 0 &&
309
+ Number.isFinite(cachedMediaInfo.width) &&
310
+ cachedMediaInfo.width > 0 &&
311
+ Number.isFinite(cachedMediaInfo.height) &&
312
+ cachedMediaInfo.height > 0;
313
+ // Always the PICTURE's, even when this session reads a soundtrack from
314
+ // another file: the timeline, the duration and the cut grid are the
315
+ // picture's, and a rendition exists to be played WITH it. Only where the
316
+ // sidecar's own timeline begins is read from the sidecar, just below.
317
+ // No session id on it: this read is a probe of the picture, not this
318
+ // session's own delivery, and counting it against the session would tell a
319
+ // waiting browser that its film is arriving when what arrived was a header.
320
+ const pictureUrl = file.streamUrl(this.#host.localBaseUrl);
321
+ const mediaInfo = cachedUsable
322
+ ? cachedMediaInfo
323
+ : await this.#host.probeMediaInfo(pictureUrl.toString());
324
+ const mediaInfoMs = Date.now() - mediaInfoStartMs;
325
+ const mediaInfoSource = cachedUsable ? "cached" : "probed";
326
+ // The file takes in what the probe said. It is the same answer for every
327
+ // session of this file — a quality step, a soundtrack, a second viewer — so
328
+ // it is kept once instead of being copied into each. A later session with a
329
+ // fresher reading updates it: on a cold torrent the first probe can come
330
+ // back without a duration, and the second is the one that has it.
331
+ file.learn(mediaInfo);
332
+ const durationSeconds = file.durationSeconds ?? 0;
333
+ const sourceWidth = file.width;
334
+ const sourceHeight = file.height;
335
+ const sourceStartTime = file.startTime;
336
+ // Where the timeline of a soundtrack shipped as its own file begins.
337
+ //
338
+ // A soundtrack in another file has a start time of its own, and it is the
339
+ // one that must be subtracted when the output is relabelled onto a
340
+ // zero-based timeline: subtract the picture's instead and the sound sits at
341
+ // a fixed offset from it for the whole film. Read from the file rather than
342
+ // assumed to be zero, because assuming it is exactly the fault being
343
+ // avoided.
344
+ //
345
+ // NOT awaited. Creating a session used to stop here until the answer came
346
+ // back, and on a cold start the answer needs the sidecar's header off the
347
+ // swarm — 8121 ms of every session created, measured three times out of
348
+ // three on 2026-09-03. What is known now is used now, and the reading runs
349
+ // behind; when it lands it lands on the FILE, which every session of that
350
+ // soundtrack shares, so the spawn path sees it without re-reading anything.
351
+ //
352
+ // Unknown means "no difference between the two timelines", not "the
353
+ // soundtrack starts at zero". The shift exists to correct a difference
354
+ // between two containers; asserting one that has not been read is inventing
355
+ // a number, while assuming none leaves the sound exactly where a release
356
+ // remuxed from a single source puts it.
357
+ if (audioSource.isSidecar) {
358
+ this.#host.renditions.warmFileStartTime(audioFile);
359
+ }
360
+ // Tone-map an HDR source to SDR only when re-encoding video on the software
361
+ // path and this ffmpeg has the filters. Hardware encoders keep their own
362
+ // (untone-mapped) path for now; when unavailable, HDR falls back to a plain
363
+ // 8-bit convert (washed-out but playable).
364
+ const applyTonemap =
365
+ transcodeVideo === true &&
366
+ mediaInfo.isHdr === true &&
367
+ this.#host.tonemapSupported &&
368
+ this.#host.videoEncoder?.kind === "software";
369
+ // Output frame rate inherited from the source (integer, capped) so 25/30
370
+ // fps content is not resampled to 24. Fixed-GOP encoders keep the fps↔GOP
371
+ // relationship exact; time-based-keyframe encoders just use it as the rate.
372
+ const outputFps = chooseOutputFps(mediaInfo.fps);
373
+ const hasDuration = Number.isFinite(durationSeconds) && durationSeconds > 0;
374
+ const logName = file.name;
375
+
376
+ // Size the reader's window in seconds of playback rather than bytes. Needs
377
+ // the file's own average byte rate, which is size ÷ duration; the size
378
+ // comes from the same stats call the realtime budget uses. Best effort —
379
+ // without it the reader keeps its own byte default.
380
+ //
381
+ // Sized for the file being READ, which for a soundtrack shipped separately
382
+ // is that file: it is a twentieth of the picture's size over the same
383
+ // duration, so the picture's byte rate would buy a window twenty times
384
+ // wider than the seconds it is meant to represent, and the piece store
385
+ // would hold it.
386
+ const readWindowBytes = await this.#host.hostLoad.readWindowBytesFor(
387
+ inputFile.sourceKey,
388
+ inputFile.fileIndex,
389
+ durationSeconds
390
+ );
391
+ if (!hasDuration) {
392
+ this.#host.logger.warn(
393
+ `transcode "${logName}": could not probe duration; falling back to ` +
394
+ "ffmpeg-managed (growing) playlist"
395
+ );
396
+ }
397
+
398
+ // For the video-copy path we cannot insert keyframes, so the playlist's
399
+ // segment boundaries must match the source's real keyframes (otherwise the
400
+ // player sees gaps on seek). Re-encoded video uses a uniform grid for
401
+ // segment boundaries instead (its fixed GOP makes the cuts land there —
402
+ // computeSegmentBoundaries ignores keyframeTimes when transcodeVideo).
403
+ //
404
+ // But the probe is ALSO used for something both branches need: choosing a
405
+ // SOURCE seek position ffmpeg can actually land on. `-ss` before `-i` trusts
406
+ // the container's own on-the-fly seek/index, which for some containers
407
+ // (observed: AVI with VBR MP3 audio) can point at a position with no valid
408
+ // frame boundary at all — ffmpeg then fails outright ("Seek failed" /
409
+ // "Header missing"), not just imprecisely. Snapping the seek to the nearest
410
+ // KNOWN real keyframe (see #startEncodeRun) avoids that. So probe for both
411
+ // branches; on failure both fall back to their current behaviour (uniform
412
+ // grid for boundaries, raw target for seeking) — no regression.
413
+ // The file's own table — the object every reader of this file holds, so a
414
+ // read that answers after this session was made still reaches it.
415
+ const keyframes = this.#host.keyframeTables.of({ sourceKey, fileIndex });
416
+ let keyframeMs = -1; // -1 = not run (skipped), -2 = running in the background
417
+ // A quality variant of a session whose cuts are the source's keyframes must
418
+ // be cut at exactly those same times, or its segments cannot stand where
419
+ // the other's would have. Nothing has to be handed over for that: the table
420
+ // is the FILE's, and a variant is a session of the same file, so it reads
421
+ // the one answer. What the inherited grid still carries is the CORRECTED
422
+ // boundaries and the published playlist, which are properties of the family
423
+ // rather than of the file.
424
+ if (inheritedGrid) {
425
+ // Nothing to read: the table above IS the file's, corrections included.
426
+ } else if (hasDuration && !transcodeVideo && !audioOnly) {
427
+ // Video-COPY path: the keyframe times are REQUIRED to build correct
428
+ // segment boundaries (the playlist itself), so this MUST block session
429
+ // creation — an incorrect playlist is worse than a slower start.
430
+ //
431
+ // The wait is bounded, and the bound is what the read costs on a real
432
+ // host rather than a figure picked here (`KEYFRAME_TABLE_BUDGET_MS`). A
433
+ // comment in this place used to promise a short timeout and "never more
434
+ // than ~6 s to session start" when no timeout existed at all; the file
435
+ // comes off a torrent, so the bytes the table lives in may still be
436
+ // arriving, and a session used to wait for them without limit.
437
+ //
438
+ // What is read is the container's OWN table (Cues/stss) rather than a
439
+ // scan of the media. On the copy path ffmpeg can only cut at the source's
440
+ // existing keyframes, so these times ARE the segment boundaries —
441
+ // declaring an even grid instead is a falsehood the player punishes: it
442
+ // walks the whole file to rebuild the timeline, or presents audio with no
443
+ // picture because a segment starts with nothing decodable (both
444
+ // field-observed 2026-08-02). Scanning cannot supply them here — the file
445
+ // comes off a torrent, and a full packet scan of 5.5 GB found 77
446
+ // keyframes in 45 s without finishing, while the container index yields
447
+ // all 570 in 0.8 s from two point reads (16 KB).
448
+ const keyframeStartMs = Date.now();
449
+ const { arrived } = await this.#host.keyframeTables.within({ sourceKey, fileIndex, logName });
450
+ keyframeMs = Date.now() - keyframeStartMs;
451
+ if (!arrived) {
452
+ // A read that ran out of its budget is still running, and one that
453
+ // found its bytes not downloaded yet is made again when they arrive;
454
+ // either way the table is still unanswered — which is not the same as a file with no keyframes,
455
+ // and the distinction is the table's own (`answered` against
456
+ // `readable`). Recorded as an absence it would make a passing shortage
457
+ // of bytes look like a property of the bytes, and every later session
458
+ // of the file would re-encode a picture that can be copied.
459
+ this.#host.logger.warn(
460
+ `transcode: the keyframe table for "${logName}" has not arrived after ${keyframeMs}ms ` +
461
+ `(budget ${Math.round(this.#host.keyframeTables.budgetMs / 1000)}s), so this session re-encodes the picture ` +
462
+ "instead of copying it; the read goes on and the next session of this file gets the copy"
463
+ );
464
+ }
465
+ if (!keyframes.readable) {
466
+ // No index, so there is no honest grid for a COPY: a copied picture can
467
+ // only be cut at the source's own keyframes, and we do not know where
468
+ // they are. Declaring an even grid instead is a falsehood the player
469
+ // punishes — it walks the whole file to rebuild the timeline, or shows
470
+ // audio with no picture because a segment begins with nothing
471
+ // decodable (both field-observed 2026-08-02).
472
+ //
473
+ // Re-encoding is the honest answer and costs an encoder: keyframes are
474
+ // then PLACED at our own cut times rather than found, so the grid is
475
+ // correct by construction whatever the container. MPEG-TS is the case
476
+ // this exists for — measured 2026-08-21, 669 real keyframes and no
477
+ // index of any kind to read them from — and a container whose index
478
+ // could not be read in the budget lands here too, which is right for
479
+ // the same reason.
480
+ transcodeVideo = true;
481
+ if (keyframes.answered) {
482
+ this.#host.logger.warn(
483
+ `transcode: no keyframe index in the ${keyframes.format} container for ` +
484
+ `"${logName}" — a copied picture has no honest grid without one, so the video is ` +
485
+ "re-encoded instead and its keyframes are placed on our own cuts"
486
+ );
487
+ }
488
+ }
489
+ } else if (hasDuration && transcodeVideo) {
490
+ // Re-encode path: keyframeTimes are ONLY used to snap a LATER seek (see
491
+ // #startEncodeRun) — segment boundaries stay on the uniform grid either
492
+ // way. So this does NOT need to block session creation / the first
493
+ // segment's start. Run it in the background with a FULL budget instead of
494
+ // the 6 s cap: AVI-class containers need a full packet scan, which 6 s can
495
+ // never afford without delaying playback start — that starved budget is
496
+ // exactly why the probe kept missing on the container where the seek bug
497
+ // was field-diagnosed. A run reads the file's table on every call, so a
498
+ // seek that happens AFTER this finishes picks it up automatically; one
499
+ // that happens before falls back to the existing circuit breaker as a
500
+ // safety net (no regression either way).
501
+ keyframeMs = -2;
502
+ const backgroundStartedAt = Date.now();
503
+ void this.#host.probeKeyframeTimes(inputFile.streamUrl(this.#host.localBaseUrl).toString(), 25_000).then((times) => {
504
+ // Into the FILE's table, which the picture, its quality steps and a
505
+ // second viewer's session all hold — so nothing has to be alive for the
506
+ // answer to be kept, and the session this probe was started for may
507
+ // long since have gone. It used to be written onto whichever session
508
+ // was still there, and dropped outright when none was.
509
+ this.#host.keyframeTables.learn({ sourceKey, fileIndex }, { times, format: "packet probe" });
510
+ const elapsedMs = Date.now() - backgroundStartedAt;
511
+ this.#host.logger.info(
512
+ times
513
+ ? `transcode: background keyframe probe found ${times.length} keyframes ` +
514
+ `(${elapsedMs}ms) for "${logName}" — later seeks will snap to them`
515
+ : `transcode: background keyframe probe unavailable (${elapsedMs}ms) for "${logName}" ` +
516
+ `— seeks keep using the raw target (falls back to the circuit breaker on failure)`
517
+ );
518
+ });
519
+ }
520
+ this.#host.logger.info(
521
+ `cold-start "${logName}": media-info=${mediaInfoMs}ms (${mediaInfoSource}) ` +
522
+ `keyframes=${keyframeMs === -1 ? "skipped" : keyframeMs === -2 ? "background" : `${keyframeMs}ms`} ` +
523
+ `create-total=${Date.now() - createEntryMs}ms`
524
+ );
525
+ // Which grid this session is cut on. A copy has no choice: only where the
526
+ // source already has a keyframe. A re-encode normally takes the even grid —
527
+ // it produces every frame and may put keyframes where it likes — unless it
528
+ // is a variant of a keyframe-cut session, in which case it must land on the
529
+ // same times to be interchangeable with it.
530
+ // An audio rendition carries no picture, so it has no keyframes of its own
531
+ // to be cut at: it takes the grid of the video it accompanies, whatever that
532
+ // is. Handed one, it uses it; handed none, the base is on the even grid and
533
+ // so is this. Falling into the COPY branch instead — which is what
534
+ // `transcodeVideo: false` means everywhere else — would put the audio of a
535
+ // re-encoded stream on the source's keyframe times while the player was
536
+ // told the even grid, and the two drift further apart with every segment.
537
+ const useKeyframeGrid = hasDuration &&
538
+ keyframes.readable &&
539
+ (audioOnly ? inheritedGrid != null : (!transcodeVideo || inheritedGrid != null));
540
+ // A rung takes the grid it was handed, rather than working one out again
541
+ // from the same index. The two are not the same table: the one it is handed
542
+ // has been CORRECTED wherever a produced segment showed the index to be
543
+ // wrong, and it is those corrected times the copy actually cuts at. Building
544
+ // it afresh here would put the rung back on the index's fiction and undo the
545
+ // alignment it exists for.
546
+ // The file's own table, made once and shared by every session of it. A
547
+ // quality step is a different OUTPUT and the same cuts — which is exactly
548
+ // the agreement `inheritedGrid` used to arrange by handing a copy to each
549
+ // new session — so it is keyed by the file and the kind of grid, and
550
+ // nothing else.
551
+ const timeline = this.#host.timelines.get(
552
+ Timelines.keyFor(sourceKey, fileIndex, useKeyframeGrid ? "keyframe" : "uniform"),
553
+ () => {
554
+ const cut = hasDuration
555
+ ? computeCutGrid({
556
+ useKeyframeGrid,
557
+ durationSeconds,
558
+ segDur: this.#host.segmentDurationSec,
559
+ keyframeTimes: keyframes.times,
560
+ startTime: sourceStartTime
561
+ })
562
+ : { boundaries: [], sourceTimes: [] };
563
+ const inherited = Array.isArray(inheritedGrid?.boundaries) && inheritedGrid.boundaries.length > 1;
564
+ return new Timeline({
565
+ boundaries: inherited ? [...inheritedGrid.boundaries] : cut.boundaries,
566
+ // The file's own clock for those cuts. An inherited table brings its
567
+ // boundaries and not this, so the seek falls back to searching there.
568
+ sourceTimes: inherited ? null : cut.sourceTimes,
569
+ cutGrid: useKeyframeGrid ? "keyframe" : "uniform"
570
+ });
571
+ }
572
+ );
573
+ // What this session will PUBLISH. A member of a family takes its base's
574
+ // published table verbatim; a session with no base publishes what it cuts
575
+ // at. The two differ exactly by the corrections made since the family's
576
+ // first playlist was written, and that difference is what must never reach
577
+ // the player as two different timelines.
578
+ const publishedGrid = timeline.published.length > 1 ? timeline.published : null;
579
+ const segmentCount = timeline.segmentCount;
580
+
581
+ // THE FORMAT, decided before the output is named, and possibly an output
582
+ // already here instead (`encode/quality/output-format.js`).
583
+ const decided = decideOutputFormat({
584
+ encodesPicture: transcodeVideo && carriesVideo,
585
+ exact: forceExactSize,
586
+ target: this.#targetFor({ normalizedTargetWidth, normalizedTargetHeight, visiblePicture, sourceWidth, sourceHeight }),
587
+ source: { width: sourceWidth, height: sourceHeight, megabitsPerSecond: file.decode?.megabitsPerSecond ?? null, decode: file.decode },
588
+ fps: outputFps,
589
+ encoder: this.#host.videoEncoder,
590
+ benchmark: this.#host.softwarePresetBenchmark,
591
+ cost: {
592
+ decodeModel: this.#host.decodeCostModel,
593
+ observedDecodeCostSec: this.#host.encodeCost.decodeCostFor(file.key)?.costSec ?? null,
594
+ requiredSpeed: this.#host.hostLoad.requiredSpeedFor(sourceKey, fileIndex)
595
+ },
596
+ chooseBudget: (params) => this.#host.encodeCost.chooseEncodeBudget(params),
597
+ machineAdmission: this.#host.admission
598
+ ? (candidate) => this.#host.admission.previewCandidate(candidate, file)
599
+ : null,
600
+ tonemap: applyTonemap,
601
+ capKbps,
602
+ limitsFor: (frame) => this.#host.limitsFor(frame),
603
+ audioLoad: viewerAudio !== undefined
604
+ ? soundtrackLoadOf(viewerAudio?.entry ?? null, viewerAudio ? viewerAudio.transcode : null)
605
+ : soundtrackLoadOf(audioSource.entry, audioTranscoded),
606
+ specWith: (encode) => new OutputSpec({
607
+ sourceKey,
608
+ segmentFormatId: segmentFormat.id,
609
+ // Where it is ACTUALLY cut: a copy whose container states no keyframes
610
+ // is re-encoded onto the even grid, and is named so.
611
+ grid: new CutGrid({ kind: useKeyframeGrid ? "keyframe" : "uniform", fileIndex }),
612
+ video: carriesVideo ? new VideoOutput({ fileIndex, encode }) : null,
613
+ audio: carriesAudio
614
+ ? new AudioOutput({ fileIndex: audioSource.fileIndex, trackIndex: audioSource.sourceTrackIndex, transcode: audioTranscoded })
615
+ : null
616
+ }),
617
+ serving: {
618
+ mode: servingMode ?? (forceExactSize ? "manual" : "auto"),
619
+ linkMbps: viewerLinkMbps,
620
+ keys: [...this.#host.outputs.values()].map((other) => other.outputKey).concat(this.#host.segmentOutputFiles.addresses()),
621
+ readyAt: (key) => this.#host.segmentOutputFiles.isClosed(key, timeline.indexForTime(Math.max(0, startPositionSeconds))),
622
+ observedPeakMbps: (candidate) => this.#host.observedPeakMbps?.(candidate) ?? null
623
+ }
624
+ });
625
+ if (decided.unavailable) {
626
+ this.#host.logger.info(
627
+ `transcode "${logName}": no output suits this viewer — ${decided.unavailable.reason} ` +
628
+ `${JSON.stringify(decided.unavailable.figures)} (wanted ${decided.wantedKey})`
629
+ );
630
+ const error = new Error(`No output suits this viewer: ${decided.unavailable.reason}.`);
631
+ // Bound by the MACHINE rather than by the viewer's link, for the output a
632
+ // viewer is opening: another proxy is the answer, found before anything
633
+ // plays. A step asked for on their behalf stays "unavailable", which is
634
+ // how every caller of a step already reads a refusal.
635
+ error.code = decided.unavailable.bound === "machine" && typeof claim === "function"
636
+ ? OUTPUT_NO_CAPACITY
637
+ : OUTPUT_UNAVAILABLE;
638
+ error.details = {
639
+ reason: decided.unavailable.reason,
640
+ // How many soundtracks the viewer could choose instead, so the page can
641
+ // offer another one only where there is one to offer.
642
+ figures: decided.unavailable.figures
643
+ ? { ...decided.unavailable.figures, soundtracks: this.#host.renditions.offeredSoundtrackCount(sourceKey, fileIndex) }
644
+ : null,
645
+ wantedKey: decided.wantedKey
646
+ };
647
+ throw error;
648
+ }
649
+ if (decided.answer) {
650
+ this.#host.logger.info(
651
+ `transcode "${logName}": ${decided.answer.verdict} for this viewer ${JSON.stringify(linkFiguresOf(decided.answer))}`
652
+ );
653
+ }
654
+ const spec = decided.spec;
655
+ const budget = decided.budget;
656
+ if (decided.reusedKey) {
657
+ this.#host.logger.info(`transcode "${logName}": served by an output already here, ${decided.reusedKey}, instead of ${decided.wantedKey}`);
658
+ }
659
+ transcodeVideo = carriesVideo ? spec.transcodesVideo : transcodeVideo;
660
+ const width = spec.video?.encode?.width ?? 0;
661
+ const height = spec.video?.encode?.height ?? 0;
662
+ const outputKey = spec.toKey();
663
+ // THE NAME FOLLOWS FROM THE KEY, so there is nothing to look it up in. A
664
+ // second table held key → name, which is a fact that can go out of step
665
+ // with the thing it points at: a session disposed without the table being
666
+ // cleared leaves a name pointing at nothing, and the next viewer of that
667
+ // output is handed it.
668
+ const existingId = spec.toName();
669
+ if (existingId) {
670
+ const existing = this.#host.outputs.get(existingId);
671
+ if (existing) {
672
+ this.#claimOrRefuse(claim, existing, logName);
673
+ return { output: existing, existed: true, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
674
+ }
675
+ }
676
+
677
+ // Only a session actually made is timed: a viewer joining one costs none
678
+ // of what this figure predicts for the next viewer who has to wait.
679
+ this.#host.hostTimings.rememberSessionCreateLatency(Date.now() - createEntryMs);
680
+ const sessionId = spec.toName();
681
+ const output = new Output({
682
+ encodeWidth: width,
683
+ encodeHeight: height,
684
+ outputFps,
685
+ softwarePreset: spec.video?.encode?.preset ?? null,
686
+ applyTonemap: spec.video?.encode?.tonemap === true
687
+ });
688
+
689
+ const session = new EncodedOutput({
690
+ id: sessionId,
691
+ spec,
692
+ file,
693
+ keyframes,
694
+ timeline,
695
+ segmentFormat,
696
+ output,
697
+ useSyntheticPlaylist: hasDuration,
698
+ playlistText: hasDuration ? mediaPlaylistText({ boundaries: publishedGrid, segmentFormat }) : "",
699
+ variantHeight: forceExactSize && height > 0 ? height : undefined
700
+ });
701
+ this.#host.outputs.set(sessionId, session);
702
+ // THE PLACE ON THIS MACHINE, taken in the same synchronous stretch as the
703
+ // registration: priced as registered, and withdrawn whole if refused, so a
704
+ // refused opening leaves nothing behind — no directory, no timing.
705
+ try {
706
+ this.#claimOrRefuse(claim, session, logName);
707
+ } catch (error) {
708
+ this.#host.outputs.delete(sessionId);
709
+ throw error;
710
+ }
711
+
712
+ // Only now, when nothing above can still throw. Everything from the probe
713
+ // to the keyframe index used to run with the directory already made, so a
714
+ // failure between the two left it behind: nothing tracks a directory whose
715
+ // session was never registered, and no sweep looks for one. Proxy
716
+ // 2.9.101-2.9.102 failed here on every single request and the leftovers
717
+ // were the only trace of it on disk.
718
+ // A RETURN, if this output was held before — and its age, which is the one
719
+ // term of the keeping period that nothing measures. Read BEFORE the
720
+ // directory is claimed, since claiming it is what marks it read.
721
+ this.#host.returns.note({ lastReadAt: this.#host.segmentOutputFiles.lastReadAt(spec.toKey()), now: Date.now() });
722
+ this.#host.segmentOutputFiles.directoryFor(spec.toKey());
723
+ this.#host.segmentOutputFiles.useFormat(spec.toKey(), segmentFormat);
724
+ this.#host.hostTimings.noteOutputCreated(session, createEntryMs);
725
+ this.#host.encodeRuns.setReadWindow(session, readWindowBytes);
726
+ this.#host.encodeCost.notePredictionFor(session, output.encodeHeight);
727
+ // Decided before the key was built and only recorded here. Whether the audio
728
+ // travels separately decides the ffmpeg arguments, what the master says,
729
+ // whether the rendition route answers at all AND what the session is keyed
730
+ // on, and those four must agree for the whole life of the session — a
731
+ // session whose picture was encoded without audio cannot start muxing it in
732
+ // at the next restart without either playing it twice or refusing the
733
+ // append, and one keyed as carrying no sound must never mux somebody else's
734
+ // language into a picture two viewers share.
735
+ //
736
+ // It must not be asked a second time, because the answer moves: the offered
737
+ // list is recomputed as the host learns what this source costs, and
738
+ // crossing "two rungs" would flip the arrangement under a stream that is
739
+ // playing.
740
+ this.#host.logger.info(
741
+ // Proxy version on the session-start line: a field report always includes
742
+ // one of these, so "is the host actually running the build I published?"
743
+ // is answered by the log itself instead of a round trip to the machine.
744
+ `transcode ${sessionId} start (proxy ${PROXY_VERSION}) "${logName}" ` +
745
+ // Where the browser asked the encoder to begin. A resume that reaches
746
+ // hls.js but not this call makes the player request a segment nobody
747
+ // was told to produce: measured 2026-08-06, the session began at #0
748
+ // while the player asked for #127 and gave up 45.6 s later. Neither
749
+ // side saying what it meant is why that took three attempts to place.
750
+ `start=${Math.round(normalizedStartPosition)}s ` +
751
+ `video=${transcodeVideo ? `${this.#host.videoEncoder.name}${output.softwarePreset ? `/${output.softwarePreset}` : ""}` : "copy"} ` +
752
+ `audio=${audioTranscoded ? "aac" : "copy"} ` +
753
+ // Branch tag for log correlation: A = video re-encode (fixed GOP, grid
754
+ // aligned, ts-offset); B = video copy (cut at source keyframes, copyts).
755
+ `branch=${transcodeVideo ? "A(reencode,fixed-gop)" : "B(copy,copyts)"} ` +
756
+ `seg=${timeline.cutGrid} ` +
757
+ `${sourceWidth && sourceHeight ? `src=${sourceWidth}x${sourceHeight} ` : ""}` +
758
+ // The size produced, and how it was arrived at: exactly as asked, the
759
+ // budget's rung of the viewer's own ladder, or the box asked for where
760
+ // there is no ladder to choose from.
761
+ `${transcodeVideo
762
+ ? `enc=${output.encodeWidth || "src"}x${output.encodeHeight || "src"}@${output.outputFps} ` +
763
+ `size=${forceExactSize ? "exact" : budget ? `budget rung ${budget.rungIndex + 1}/${budget.ladder.length}` : "asked"} `
764
+ : ""}` +
765
+ // HDR source and whether the tone-map chain was applied (vs washed-out
766
+ // fallback when the filters are missing or on a hardware encoder).
767
+ `${transcodeVideo && mediaInfo.isHdr ? `hdr=1 tonemap=${applyTonemap ? "on" : "off"} ` : ""}` +
768
+ `${sourceStartTime ? `start=${sourceStartTime.toFixed(3)} ` : ""}` +
769
+ `duration=${hasDuration ? formatSeconds(durationSeconds) : "unknown"} segments=${segmentCount} ` +
770
+ // What this session was keyed on, which is what decides whether the next
771
+ // viewer joins it or starts a second encoder beside it. Printed because
772
+ // a fork was undiagnosable without it: on 2026-09-03 two viewers of one
773
+ // copied picture got two sessions with identical descriptions and
774
+ // byte-identical output, both create requests were 265 bytes, and
775
+ // nothing anywhere said what the two had been told apart by.
776
+ `key=${outputKey}`
777
+ );
778
+
779
+ // Where the first encoder goes is the plan's, placed by the same arithmetic
780
+ // as every later one from where the viewers stand; the requester is placed
781
+ // by the operation that asked for this output.
782
+ return { output: session, existed: false, audio, verdict: decided.answer ? linkFiguresOf(decided.answer) : null };
783
+ }
784
+ }