@torrent-tv/proxy 2.80.1 → 2.80.3

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.
@@ -1,662 +1,697 @@
1
- /**
2
- * @file The full argument list for one encoder run.
3
- *
4
- * What a run is given is a fact about WHAT is being produced and WHERE it
5
- * begins, and about nothing else — not the session it belongs to, not who is
6
- * watching, not how many viewers there are. It was a 377-line method of the
7
- * session manager reading fifteen of its fields, which is why a run could only
8
- * ever be built by that class, for the one session it holds.
9
- *
10
- * Stated here, over the material and the stretch alone, a run can be built by
11
- * whoever needs one. That is what lets an output have more than a single
12
- * encoder.
13
- *
14
- * **Nothing in this file runs anything.** It returns an argument list; spawning,
15
- * killing and resuming belong to whoever owns the process.
16
- */
17
-
18
- /** The name ffmpeg writes its own playlist to, and the name that is served. */
19
- export const PLAYLIST_FILE_NAME = "index.m3u8";
20
-
21
- /**
22
- * What ffmpeg's own CLI subtracts from an input seek, and therefore what has to
23
- * be added back to land where we asked.
24
- *
25
- * `fftools/ffmpeg_demux.c`, in `ifile_open`: when the container does not
26
- * declare `AVFMT_SEEK_TO_PTS` — Matroska does not — and any stream carries
27
- * B-frames, the seek target is moved back by `3*AV_TIME_BASE / 23` before
28
- * `avformat_seek_file` is called. Its purpose is sound: such containers seek in
29
- * decode order while the caller asks in presentation order, and with B-frames
30
- * the two differ, so it backs off far enough to be sure of reaching the frame
31
- * asked for.
32
- *
33
- * The consequence for a COPY is that asking for a keyframe lands on the one
34
- * BEFORE it — deterministically, every time. Measured 2026-08-21 on a Matroska
35
- * file with keyframes every 2 s: `-ss 10` produced a first segment starting at
36
- * 8.000; `-ss 10.130435` produced one starting at 10.000. On MP4, where the
37
- * heuristic does not fire, all of 10, 10.130435 and 10.2 produced 10.000 — so
38
- * adding this is right in one case and harmless in the other.
39
- *
40
- * That landing is what `-segment_times` is measured from, while this code
41
- * computes those offsets from the time it ASKED for. One keyframe interval
42
- * apart, inherited by every cut of the run: 119 of 125 segments arriving a
43
- * uniform 2.002 s early in the field, four times what a player bridges.
44
- *
45
- * Not applied when the picture is re-encoded: a re-encode decodes from the
46
- * keyframe and discards frames up to the requested time, so its output already
47
- * begins exactly where asked (measured the same day: `-ss 11` copied starts at
48
- * 10.000, re-encoded at 11.000).
49
- */
50
- export const SEEK_LANDING_OFFSET_SEC = 3 / 23;
51
-
52
- /**
53
- * A number of seconds as ffmpeg will accept it.
54
- *
55
- * `String(n)` switches to exponential notation below 1e-6, and ffmpeg's
56
- * duration parser rejects that outright: a field session died on
57
- * `Invalid duration for option ss: 3.3333333249174757e-7`, after which the
58
- * transcode was in state `failed` and every segment request answered 500 for
59
- * as long as the viewer kept trying. Anything under a millisecond is also not a
60
- * real offset — it is the residue of subtracting two nearly equal floats — so
61
- * it is dropped rather than passed on.
62
- *
63
- * @param {number} value
64
- * @returns {string}
65
- */
66
- export function ffmpegSeconds(value) {
67
- if (!Number.isFinite(value) || Math.abs(value) < 0.001) {
68
- return "0";
69
- }
70
- // Microsecond resolution, fixed notation, no trailing zero noise.
71
- return value.toFixed(6).replace(/\.?0+$/, "");
72
- }
73
-
74
- /**
75
- * Which timeline an output's own ffmpeg works on.
76
- *
77
- * True — the COPY branch: the source's timestamps are kept (`-copyts`) and the
78
- * output is re-labelled 0-based. Everything handed to the muxer is therefore
79
- * stated in the source's terms, and everything read back out of a produced
80
- * piece is 0-based.
81
- *
82
- * False — the re-encode branch: the output is labelled from the run's start on
83
- * the 0-based timeline, and the muxer is addressed in those same terms.
84
- *
85
- * One predicate for both callers, because the two used to answer it separately
86
- * and a disagreement between them is exactly what desynced picture from sound.
87
- *
88
- * @param {{ audioOnly?: boolean, timeline?: { cutGrid?: string }, transcodeVideo?: boolean }} material
89
- * @returns {boolean}
90
- */
91
- export function onKeyframeGridFor(material) {
92
- return material?.audioOnly === true
93
- ? material?.timeline?.cutGrid === "keyframe"
94
- : material?.transcodeVideo !== true;
95
- }
96
-
97
- /**
98
- * The boundary table the player is working from: the one its playlist was
99
- * written from, falling back to the live table when no playlist was built from
100
- * a table at all (no duration, so no synthetic playlist — and then nothing the
101
- * player holds contradicts it).
102
- *
103
- * @param {{ published?: number[], boundaries?: number[] }} timeline
104
- * @returns {number[]}
105
- */
106
- export function publishedGridFor(timeline) {
107
- return Array.isArray(timeline?.published) && timeline.published.length > 0
108
- ? timeline.published
109
- : (timeline?.boundaries ?? []);
110
- }
111
-
112
- /**
113
- * Where a run beginning at `index` must be positioned: the time the PLAYER was
114
- * told that segment starts at.
115
- *
116
- * Two tables, deliberately: the live one is corrected as produced segments
117
- * reveal where the file's cuts truly are, and those corrections are what let a
118
- * re-encoded rung be forced onto a copied stream's real grid. But the playlist
119
- * a player is holding was written once and never changes, so a position taken
120
- * from the corrected table describes a timeline nobody sent the player. That is
121
- * not a subtlety: it cost ten minutes of a dead film on 2026-08-17, the browser
122
- * asking for two segments 1908 times each.
123
- *
124
- * @param {{ published?: number[], boundaries?: number[] }} timeline
125
- * @param {number} index
126
- * @param {number} segmentDurationSec - Used only when the file has no table at
127
- * all, where a segment is a plain multiple of the nominal length.
128
- * @returns {number}
129
- */
130
- export function publishedStartTime(timeline, index, segmentDurationSec) {
131
- const published = Array.isArray(timeline?.published) && timeline.published.length > 0 ? timeline.published : null;
132
- const table = published ?? (Array.isArray(timeline?.boundaries) ? timeline.boundaries : []);
133
- if (table.length === 0) {
134
- return index * segmentDurationSec;
135
- }
136
- const clamped = Math.max(0, Math.min(index, table.length - 1));
137
- return table[clamped];
138
- }
139
-
140
- /**
141
- * The cut times to hand ffmpeg for a run that starts at `startIndex`.
142
- *
143
- * Two adjustments, both of which cost a broken session to learn:
144
- *
145
- * - **Rebased.** `-segment_times` is measured from the start of the run, not
146
- * of the file. Measured: starting at 12 s and asking for a cut at 18 s put
147
- * it at 29.4 s — 12 + 18. So every boundary has the run's own start
148
- * subtracted.
149
- * - **Interior only.** The first boundary is where the run begins and the last
150
- * is where the file ends; neither is a cut. Sending them would produce an
151
- * empty leading segment and a spurious trailing one.
152
- *
153
- * @param {number[]} boundaries
154
- * @param {number} startIndex
155
- * @returns {number[] | null}
156
- */
157
- export function segmentCutTimesFrom(boundaries, startIndex) {
158
- if (!Array.isArray(boundaries) || boundaries.length < 2) {
159
- return null;
160
- }
161
- const index = Number.isInteger(startIndex) && startIndex > 0 ? startIndex : 0;
162
- if (index >= boundaries.length - 1) {
163
- return null;
164
- }
165
- const base = boundaries[index];
166
- const times = [];
167
- for (let at = index + 1; at < boundaries.length - 1; at += 1) {
168
- times.push(Number((boundaries[at] - base).toFixed(6)));
169
- }
170
- return times;
171
- }
172
-
173
- /**
174
- * The largest keyframe time that does not exceed `target`, from a SORTED
175
- * (ascending) array of keyframe times. Null when `target` is before the first
176
- * keyframe or the array is empty — the caller then falls back to its unsnapped
177
- * target.
178
- *
179
- * @param {number[]} keyframeTimes - Sorted ascending.
180
- * @param {number} target
181
- * @returns {number | null}
182
- */
183
- export function nearestKeyframeAtOrBefore(keyframeTimes, target) {
184
- let result = null;
185
- for (const time of keyframeTimes) {
186
- if (time > target) {
187
- break;
188
- }
189
- result = time;
190
- }
191
- return result;
192
- }
193
-
194
- /**
195
- * How much later than a keyframe to ASK, so that ffmpeg lands on that keyframe.
196
- *
197
- * Bounded by half the distance to the next keyframe, which matters only where
198
- * keyframes stand closer together than twice the offset. There no single value
199
- * can satisfy both worlds — asking too little lands a keyframe early when the
200
- * heuristic fires, asking too much lands a keyframe late when it does not — and
201
- * the bound picks the smaller error, which is then under one keyframe interval
202
- * and therefore under what a player bridges.
203
- *
204
- * @param {{ transcodeVideo?: boolean, file?: { keyframeTimes?: number[], keyframeTolerance?: number } }} material
205
- * @param {number} keyframe - A real keyframe time the run is to begin at.
206
- * @returns {number} Seconds to add to the request.
207
- */
208
- export function seekLandingOffsetFor(material, keyframe) {
209
- // A re-encode trims to the requested time itself, so it needs no help and
210
- // must not be pushed past what it was asked for.
211
- if (material?.transcodeVideo === true) {
212
- return 0;
213
- }
214
- // A grid whose times are approximate needs that error added on top, or a name
215
- // sitting just below its real keyframe seeks to before it and lands on the
216
- // one before that. Only AVI declares one.
217
- const tolerance = Number.isFinite(material?.file?.keyframeTolerance)
218
- ? Math.max(0, material.file.keyframeTolerance)
219
- : 0;
220
- const wanted = SEEK_LANDING_OFFSET_SEC + tolerance;
221
- const times = Array.isArray(material?.file?.keyframeTimes) ? material.file.keyframeTimes : [];
222
- const next = times.find((time) => time > keyframe + 0.001);
223
- if (next === undefined) {
224
- return wanted;
225
- }
226
- return Math.min(wanted, (next - keyframe) / 2);
227
- }
228
-
229
- /**
230
- * Everything ffmpeg is told for one run.
231
- *
232
- * @param {object} params
233
- * @param {{ keyframeTimes?: number[], keyframeTolerance?: number }} params.file - The
234
- * PICTURE's file: whose keyframes a seek snaps to.
235
- * @param {{ startTime: number }} params.inputFile - The file this run reads.
236
- * @param {{ startTime: number }} params.audioFile - The file the chosen
237
- * soundtrack lives in, which for a dub shipped beside the picture is not the
238
- * picture's own.
239
- * @param {string} params.inputUrl
240
- * @param {string} params.audioInputUrl - Empty unless a browser that takes its
241
- * audio muxed is watching a release whose soundtrack is a file of its own.
242
- * @param {{ published?: number[], boundaries?: number[], cutGrid?: string }} params.timeline
243
- * @param {{ encodeWidth: number, encodeHeight: number, outputFps: number, softwarePreset: string | null, applyTonemap: boolean }} params.output
244
- * @param {object} params.segmentFormat
245
- * @param {boolean} params.transcodeVideo
246
- * @param {boolean} params.transcodeAudio
247
- * @param {boolean} params.audioOnly - An audio rendition: one track, no picture.
248
- * @param {boolean} params.audioSeparate - The picture's sound is published as a
249
- * rendition, so this output carries none.
250
- * @param {number} params.audioSourceTrackIndex - `0:a:N` within its own file.
251
- * @param {number | null} params.rateCapKbps
252
- * @param {number} params.startIndex - First segment number this run makes.
253
- * @param {number} params.endIndex - Last it makes, inclusive; below the start
254
- * means it has no end.
255
- * @param {number | undefined} params.positionSecondsOverride - Where to begin,
256
- * when the caller knows better than the table.
257
- * @param {object} params.videoEncoder
258
- * @param {number} params.segmentDurationSec
259
- * @returns {{ args: string[], safeIndex: number, startSeconds: number, cutTimes: number[] | null }}
260
- */
261
- export function buildRunCommand({
262
- file,
263
- inputFile,
264
- audioFile,
265
- inputUrl,
266
- audioInputUrl: audioInputUrlGiven,
267
- timeline,
268
- output,
269
- segmentFormat,
270
- transcodeVideo,
271
- transcodeAudio,
272
- audioOnly,
273
- audioSeparate,
274
- audioSourceTrackIndex,
275
- rateCapKbps,
276
- startIndex,
277
- endIndex,
278
- positionSecondsOverride,
279
- videoEncoder,
280
- segmentDurationSec
281
- }) {
282
- const safeIndex = Number.isInteger(startIndex) && startIndex > 0 ? startIndex : 0;
283
- // 0-based output time of this segment, from the table the PLAYER holds —
284
- // the same one the cut list below is taken from.
285
- //
286
- // These two were read from different tables until 2026-08-21, and that is
287
- // one fault, not two: `-segment_times` are measured from wherever the run
288
- // really began, so any distance between the position and the cut list moves
289
- // EVERY cut of that run by it. The live table keeps being corrected as
290
- // produced segments reveal where the file's cuts truly are, and those
291
- // corrections run backwards, so each restart began a little earlier than
292
- // the grid the cuts were stated on — and since the corrections accumulate,
293
- // so did the distance. Measured on `JUFD665.mp4`: after one seek restart a
294
- // produced segment held the boundary two places before its own number
295
- // (16.684 s, exactly 2.0000 segments), after the next it held the one four
296
- // places before (33.5 s). The player's buffer then stops extending at all,
297
- // because the content of every fragment lands before the time its playlist
298
- // entry names: `bufferEnd` stood still at 4571.1 s through four `frag-far`
299
- // warnings until hls.js gave up and jumped the viewer 16.8 s forward.
300
- //
301
- // 2.45.0 moved the CUT LIST onto the published table for this same reason
302
- // and left the position on the live one. Both belong on the published
303
- // table: a run must begin where the player was told the segment begins.
304
- const startSeconds = Number.isFinite(positionSecondsOverride)
305
- ? positionSecondsOverride
306
- : publishedStartTime(timeline, safeIndex, segmentDurationSec);
307
- // Where each of the two timelines begins, asked of the files themselves.
308
- // Fresh by construction: the session may have been created before the
309
- // soundtrack file's header could be read, and the reading lands on the file
310
- // object this session holds — so there is nothing to re-read and nothing
311
- // that can be stale. Same property as `file.keyframeTimes`,
312
- // which is one table shared by every session of the file.
313
- // Which timeline this run works on. Asked once, because the closure that
314
- // adds the second input reads it too, and two readings of one predicate is
315
- // how the picture and the sound came apart before.
316
- const keyframeGrid = onKeyframeGridFor({ audioOnly, timeline, transcodeVideo });
317
- const servesAudioSeparately = audioOnly !== true && audioSeparate === true;
318
- const audioFileStartTime = audioFile.startTime;
319
- // The start time of the file this run READS, which is the picture's own for
320
- // every session except one whose soundtrack is a separate file.
321
- const sourceStartTime = inputFile.startTime;
322
- // Cut where this session's grid says, whoever is producing the frames. The
323
- // times are measured from the start of THIS run; the same list serves as
324
- // the cut points and, when re-encoding, as the keyframes to force — one
325
- // list, so the two cannot drift apart.
326
- const explicitTimes = segmentFormat.explicitTimesMuxerArgs?.() ?? null;
327
- // A COPY is cut by this list whatever grid it ended up on. Even when no
328
- // keyframe index could be read and the boundaries are a plain grid, saying
329
- // them outright is what keeps the playlist and the muxer agreeing — ffmpeg
330
- // moves each cut forward to the first real keyframe, and serving reads back
331
- // where the piece truly begins. Requiring a keyframe grid here dropped a
332
- // copy with no index onto the `hls` muxer, which takes no cut list and
333
- // writes no self-contained pieces, so nothing could read a true start and
334
- // segments were stamped with times the file does not have — the 4.17 s
335
- // speech-against-subtitles drift, back again.
336
- //
337
- // Cut on the grid the PLAYER WAS GIVEN, not on the corrected one. A player
338
- // places a fragment by the playlist it holds, and that text was written
339
- // once and never changes; the live table keeps moving as produced segments
340
- // reveal where the file's cuts really are. Cutting on the moved table makes
341
- // every run faithful to a timeline nobody sent the player — measured
342
- // 2026-08-20, the picture's segments arriving a uniform 2.002 s before the
343
- // times the playlist named for them, which is four times what hls.js will
344
- // bridge, so the fragment does not land and is asked for again.
345
- //
346
- // The corrections keep their purpose: they describe the file, and a variant
347
- // created later inherits the corrected table and PUBLISHES it, so its own
348
- // playlist and its own cuts agree from the start. What they may not do is
349
- // move the cuts of a session whose playlist is already being read.
350
- const gridCutTimes = explicitTimes && (!transcodeVideo || timeline.cutGrid === "keyframe")
351
- ? segmentCutTimesFrom(publishedGridFor(timeline), safeIndex)
352
- : null;
353
- // Cut times are stated on the grid, for both branches.
354
- //
355
- // 2.28.0 added `sourceStartTime` to them on the copy branch, reasoning that
356
- // the muxer decides its cuts before the output is relabelled. The field
357
- // measured it the next session and the reasoning was wrong: of 75 pieces
358
- // the picture produced, only NINE began at a time the container's own
359
- // keyframe table names (the soundtrack, untouched by the change, scored 70
360
- // of 75). Before it, every piece began exactly on a named keyframe and it
361
- // was the PLAYLIST that disagreed with them. So the shift moved the cuts
362
- // OFF the keyframes rather than onto them, and it is gone.
363
- //
364
- // What remains true, and is what that measurement is really about: the
365
- // picture cuts where the source's keyframes are, and the playlist must be
366
- // built from those same times. That is the correction path's job, not the
367
- // cut list's.
368
- const cutTimes = gridCutTimes;
369
-
370
- // Video: re-encode only when required, using the detected encoder
371
- // (hardware-accelerated or software). The descriptor builds the filter +
372
- // codec args (including keyframe alignment on segment boundaries).
373
- const videoCodecArgs = transcodeVideo
374
- ? videoEncoder.buildVideoArgs({
375
- // Budget-selected encode box (may be below the client target on weak
376
- // software hosts); falls back to the client target for hardware.
377
- targetWidth: output.encodeWidth,
378
- targetHeight: output.encodeHeight,
379
- segmentDurationSec: segmentDurationSec,
380
- // Source-inherited output rate (integer, capped); descriptors that
381
- // use time-based keyframes just apply it as the frame rate.
382
- fps: output.outputFps,
383
- // Software-only; hardware descriptors ignore it.
384
- preset: output.softwarePreset ?? undefined,
385
- // HDR→SDR tone map (software path only; gated on filter availability).
386
- tonemap: output.applyTonemap === true,
387
- // On the source's grid the cuts are not evenly spaced, so no frame
388
- // count can describe them: the encoder is told the times outright,
389
- // the same ones the muxer will cut at.
390
- forcedKeyframeTimes: cutTimes,
391
- // A ceiling the VIEWER's measured link put on this picture, when one
392
- // has been measured. Null means the rung's own nominal rate stands.
393
- nominalKbps: rateCapKbps ?? null
394
- })
395
- : ["-c:v", "copy"];
396
- const audioCodecArgs = transcodeAudio
397
- ? ["-c:a", "aac", "-ac", "2", "-b:a", "128k"]
398
- : ["-c:a", "copy"];
399
-
400
- const args = ["-hide_banner", "-nostats", "-loglevel", "error", "-progress", "pipe:1"];
401
- // Hardware decode/encode setup (e.g. VAAPI device) must precede -i, and
402
- // only applies when we actually re-encode the video track.
403
- if (transcodeVideo && Array.isArray(videoEncoder.inputArgs)) {
404
- args.push(...videoEncoder.inputArgs);
405
- }
406
- // Seek position in SOURCE time. On the keyframe grid `startSeconds` is a
407
- // real keyframe's offset from zero, so the container's own start time goes
408
- // back on to reach it; on the uniform grid it is a plain offset. This
409
- // follows the GRID, not whether the video is re-encoded — a variant cut on
410
- // the source's keyframes has to seek to them like the copy it accompanies.
411
- const seekSeconds = timeline.cutGrid === "keyframe"
412
- ? startSeconds + sourceStartTime
413
- : startSeconds;
414
- // Two-step seek when we have a real keyframe map: jump to a KNOWN-valid
415
- // keyframe (coarse, before -i — safe because WE sourced it from ffprobe,
416
- // not the container's own on-the-fly seek/index) and trim the short
417
- // residual (bounded by the keyframe interval) precisely AFTER -i, which is
418
- // always frame-accurate regardless of -accurate_seek.
419
- //
420
- // Root cause this works around: `-accurate_seek -ss X` before -i trusts the
421
- // CONTAINER's own seek to land near X. For some containers (observed: AVI
422
- // with VBR MP3 audio) that on-the-fly seek can point at a position with no
423
- // valid frame boundary at all — ffmpeg fails outright ("Seek failed" /
424
- // "Header missing"), not just imprecisely, and repeatedly so since every
425
- // retry re-tries the SAME bad container-computed position. A keyframe we
426
- // read directly from the packet list is a position ffmpeg has already
427
- // proven it can decode.
428
- const snappedKeyframe = Array.isArray(file.keyframeTimes) && file.keyframeTimes.length > 0
429
- ? nearestKeyframeAtOrBefore(file.keyframeTimes, seekSeconds)
430
- : null;
431
- // A second input, and it exists for exactly one case: a browser that takes
432
- // its audio muxed into the picture, watching a release whose soundtrack is a
433
- // file of its own. An audio RENDITION reads that file as its only input and
434
- // has none of this — which is why the ordinary path, and every browser that
435
- // understands rendition groups, still runs on a single input.
436
- const audioInputUrl =
437
- typeof audioInputUrlGiven === "string" && audioInputUrlGiven.length > 0
438
- ? audioInputUrlGiven
439
- : "";
440
- // Where the picture's own start sits on the soundtrack file's timeline. Both
441
- // files begin at their own container start time, and those need not be the
442
- // same number; the difference is what keeps the two aligned.
443
- const audioTimelineShift = audioInputUrl
444
- ? audioFileStartTime - sourceStartTime
445
- : 0;
446
- /**
447
- * Add the second input, if there is one, with its own seek.
448
- *
449
- * Called between the first `-i` and any OUTPUT option, because ffmpeg reads
450
- * these positionally: an option written after the last `-i` applies to the
451
- * output, and the residual seek below is exactly such an option. Getting the
452
- * order wrong would silently turn the audio file's seek into a trim of the
453
- * finished stream.
454
- *
455
- * @param {number} inputSeekSeconds - Where to start, on the PICTURE's
456
- * timeline. Translated to the soundtrack file's own here.
457
- */
458
- const pushAudioInput = (inputSeekSeconds) => {
459
- if (!audioInputUrl) {
460
- return;
461
- }
462
- // `-itsoffset` states the soundtrack's timestamps on the picture's
463
- // timeline, so everything after this point `-copyts`, the output offset,
464
- // the cut list — goes on treating the two as one timeline, unchanged.
465
- //
466
- // ONLY on the branch that keeps the source's own timestamps. Without
467
- // `-copyts` ffmpeg rebases each input from its own seek point, and both
468
- // inputs are seeked to the same instant just below so the two are
469
- // already aligned and adding the offset would pull them apart by exactly
470
- // the amount it exists to remove.
471
- if (audioTimelineShift !== 0 && keyframeGrid) {
472
- args.push("-itsoffset", ffmpegSeconds(-audioTimelineShift));
473
- }
474
- const audioSeek = Math.max(0, inputSeekSeconds + audioTimelineShift);
475
- if (audioSeek > 0) {
476
- // No keyframe to snap to and none needed: every audio frame is a sync
477
- // point, so the seek can be accurate outright.
478
- args.push("-accurate_seek", "-ss", ffmpegSeconds(audioSeek));
479
- }
480
- args.push("-i", audioInputUrl);
481
- };
482
-
483
- if (snappedKeyframe !== null) {
484
- const residualSeconds = Math.max(0, seekSeconds - snappedKeyframe);
485
- if (snappedKeyframe > 0) {
486
- args.push("-ss", ffmpegSeconds(snappedKeyframe + seekLandingOffsetFor({ transcodeVideo, file }, snappedKeyframe)));
487
- }
488
- args.push("-i", inputUrl);
489
- // The coarse landing, not the exact target: the residual below is discarded
490
- // from the OUTPUT and so takes the same slice off every stream. Seeking the
491
- // soundtrack to the exact target as well would take that slice twice and
492
- // leave the sound running ahead of the picture by it.
493
- pushAudioInput(snappedKeyframe);
494
- if (residualSeconds > 0) {
495
- args.push("-ss", ffmpegSeconds(residualSeconds));
496
- }
497
- } else {
498
- if (seekSeconds > 0) {
499
- // No keyframe map (probe failed/timed out) — fall back to the previous
500
- // behaviour: trust the container's own accurate seek.
501
- args.push("-accurate_seek", "-ss", ffmpegSeconds(seekSeconds));
502
- }
503
- args.push("-i", inputUrl);
504
- pushAudioInput(seekSeconds);
505
- }
506
- // Which timeline the output is labelled on. An audio rendition has no
507
- // picture of its own to follow, so it follows the grid it was given — the
508
- // same one the video it plays with is on. Deciding by `transcodeVideo`, as
509
- // everything else here does, would put the audio of a re-encoded stream on
510
- // the copy branch: `-copyts` and a shift by the container's start time,
511
- // against a picture labelled from zero. The two would be offset by
512
- // `sourceStartTime` for the whole file.
513
- if (!keyframeGrid) {
514
- // Branch A (re-encode): fixed GOP makes keyframes land exactly on the
515
- // segment grid; relabel output onto the original timeline so segment N
516
- // carries PTS = N × segmentDuration.
517
- if (startSeconds > 0) {
518
- args.push("-output_ts_offset", ffmpegSeconds(startSeconds));
519
- }
520
- } else {
521
- // Branch B (video copied only audio is transcoded): we cannot insert
522
- // keyframes, so segments are cut at the source's own keyframes (the
523
- // playlist boundaries were built from those keyframes). Keep the source's
524
- // real timestamps (`-copyts`) so copied frames stay continuous across
525
- // boundaries/seeks, and shift by -startTime so the output timeline is
526
- // 0-based (a non-zero container start otherwise puts a hole at the very
527
- // beginning and desyncs audio/video). Audio is transcoded on this timeline.
528
- args.push("-copyts");
529
- if (sourceStartTime !== 0) {
530
- args.push("-output_ts_offset", ffmpegSeconds(-sourceStartTime));
531
- }
532
- }
533
- // Where this run STOPS. Until now a run had a start and no end — neither
534
- // `-to` nor `-t` appeared anywhere in the arguments this proxy builds — so
535
- // every stop was a kill from outside, and two runs on one output could only
536
- // be kept apart by giving each its own directory. With an end they cannot
537
- // reach each other's numbers at all, and a run that finishes its stretch
538
- // exits by itself instead of having to be noticed and killed.
539
- //
540
- // WHICH argument states it is a property of the branch, and it is measured
541
- // rather than reasoned (2026-09-04, `research/encoder-layer-2026-09-04.md`
542
- // §11): `-t` is a duration on the output's own clock, and `-to` a point on
543
- // the input's. The copy branch runs with `-copyts`, where the input's clock
544
- // IS the source's, so `-to` takes the absolute time; the re-encode branch
545
- // has no `-copyts` and takes the duration. Swapping them is not a near
546
- // miss on the copy branch `-t` produced one segment where five were
547
- // wanted, because the time it names is already past when the run starts.
548
- const runEnd = Number.isInteger(endIndex) ? endIndex : -1;
549
- const publishedGrid = publishedGridFor(timeline);
550
- if (runEnd >= safeIndex && Array.isArray(publishedGrid) && publishedGrid[runEnd + 1] > 0) {
551
- const endsAt = publishedGrid[runEnd + 1];
552
- if (transcodeVideo) {
553
- args.push("-t", ffmpegSeconds(Math.max(0.1, endsAt - publishedGrid[safeIndex])));
554
- } else {
555
- args.push("-to", ffmpegSeconds(endsAt));
556
- }
557
- }
558
- if (audioOnly === true) {
559
- // An audio RENDITION: one track, no picture. Published as its own
560
- // `#EXT-X-MEDIA` and shared by every video variant, so the track is
561
- // encoded once for the file instead of once per rung, and changing it is
562
- // the player switching rendition rather than this proxy rebuilding the
563
- // session. Cut on the same grid as the video it accompanies, which is
564
- // what lets the two be played together.
565
- // `0:` because a rendition's only input IS the file its track lives in —
566
- // the picture's own file, or the one beside it that carries this dub.
567
- args.push("-vn", "-map", `0:a:${audioSourceTrackIndex}?`, ...audioCodecArgs);
568
- } else if (servesAudioSeparately) {
569
- // The other half of the same arrangement: the picture alone, because its
570
- // audio is published as a rendition and would otherwise play twice.
571
- args.push("-an", "-map", "0:v:0?", ...videoCodecArgs);
572
- } else {
573
- args.push(
574
- "-map",
575
- "0:v:0?",
576
- "-map",
577
- // The audio track the viewer chose: input 1 when their choice is a
578
- // soundtrack shipped as its own file, input 0 when it is one of the
579
- // picture's own. Type-relative within that input, which is what
580
- // `audioSourceTrackIndex` holds the number the browser sent is flat
581
- // across both files and was resolved when the session was made.
582
- `${audioInputUrl ? 1 : 0}:a:${audioSourceTrackIndex}?`,
583
- ...videoCodecArgs,
584
- ...audioCodecArgs
585
- );
586
- }
587
-
588
- // Where the cuts come from. On the copy path they are the source's own
589
- // keyframes, and until now they were only ever GUESSED: ffmpeg got a target
590
- // duration and chose its own cut points, while the playlist was built from
591
- // the container index — two independent calculations with nothing tying
592
- // them together but the hope that they agree. They do not. The index is a
593
- // navigation table and is not obliged to list every keyframe; for a field
594
- // file it held 1902 while ffmpeg found roughly twice as many and cut twice
595
- // as often. Segment #876 then meant 1:26:50 to the player and about minute
596
- // 58 to ffmpeg, which is why a seek landed nowhere near where it was aimed
597
- // and the reported duration drifted.
598
- //
599
- // So stop guessing and say it: the `segment` muxer takes the list of times
600
- // outright. Passing the very boundaries the playlist was built from makes
601
- // the two agree by construction. Only cut points already known to be real
602
- // keyframes are sent, so ffmpeg never has to move one forward.
603
- //
604
- // The list is built above, before the encoder args, because a re-encoded
605
- // variant of a copied stream needs the same times twice over: once as the
606
- // cuts, once as the keyframes to force at them.
607
- if (cutTimes && cutTimes.length > 0) {
608
- args.push(
609
- "-f",
610
- "segment",
611
- // Times are measured from the START OF THIS RUN, not from the start of
612
- // the file — verified: starting at 12 s and asking for a cut at 18 s
613
- // produced one at 29.4 s. `segmentCutTimesFrom` rebases them.
614
- "-segment_times",
615
- cutTimes.join(","),
616
- // A cut lands on the first keyframe at or after its time, so a boundary
617
- // recorded a hair late would skip to the next one and double the
618
- // segment. The tolerance absorbs that rounding.
619
- "-segment_time_delta",
620
- "0.05",
621
- "-segment_start_number",
622
- String(safeIndex),
623
- // THE ENCODER SAYS WHEN A PIECE IS FINISHED, on a channel of its own.
624
- //
625
- // Measured on the addon host 2026-09-05: a name appears in this list when
626
- // the file is CLOSED, not when it is created — at the third sample
627
- // `seg-000.mp4` was on disk and absent from the list, and it appeared at
628
- // the fourth, in the same moment `seg-001.mp4` came into being. So a name
629
- // here is the writer's own statement that the piece is whole.
630
- //
631
- // Without it, a finished file is indistinguishable from one still being
632
- // written, and the only proof available was the existence of the NEXT
633
- // one — which never comes for the last piece of every run.
634
- "-segment_list",
635
- "pipe:3",
636
- "-segment_list_flags",
637
- "+live",
638
- ...explicitTimes,
639
- segmentFormat.segmentFileNameTemplate()
640
- );
641
- } else {
642
- args.push(
643
- "-f",
644
- "hls",
645
- "-hls_time",
646
- String(segmentDurationSec),
647
- "-hls_list_size",
648
- "0",
649
- "-hls_flags",
650
- "independent_segments+temp_file",
651
- // Container selection + segment naming, from the active format module.
652
- ...segmentFormat.muxerArgs(),
653
- "-start_number",
654
- String(safeIndex),
655
- // ffmpeg writes its own playlist here; we ignore it and serve the
656
- // synthetic VOD playlist instead (see getFileStream).
657
- PLAYLIST_FILE_NAME
658
- );
659
- }
660
- return { args, safeIndex, startSeconds, cutTimes };
661
-
662
- }
1
+ /**
2
+ * @file The full argument list for one encoder run.
3
+ *
4
+ * What a run is given is a fact about WHAT is being produced and WHERE it
5
+ * begins, and about nothing else — not the session it belongs to, not who is
6
+ * watching, not how many viewers there are. It was a 377-line method of the
7
+ * session manager reading fifteen of its fields, which is why a run could only
8
+ * ever be built by that class, for the one session it holds.
9
+ *
10
+ * Stated here, over the material and the stretch alone, a run can be built by
11
+ * whoever needs one. That is what lets an output have more than a single
12
+ * encoder.
13
+ *
14
+ * **Nothing in this file runs anything.** It returns an argument list; spawning,
15
+ * killing and resuming belong to whoever owns the process.
16
+ */
17
+
18
+ /** The name ffmpeg writes its own playlist to, and the name that is served. */
19
+ export const PLAYLIST_FILE_NAME = "index.m3u8";
20
+
21
+ /**
22
+ * What ffmpeg's own CLI subtracts from an input seek, and therefore what has to
23
+ * be added back to land where we asked.
24
+ *
25
+ * `fftools/ffmpeg_demux.c`, in `ifile_open`: when the container does not
26
+ * declare `AVFMT_SEEK_TO_PTS` — Matroska does not — and any stream carries
27
+ * B-frames, the seek target is moved back by `3*AV_TIME_BASE / 23` before
28
+ * `avformat_seek_file` is called. Its purpose is sound: such containers seek in
29
+ * decode order while the caller asks in presentation order, and with B-frames
30
+ * the two differ, so it backs off far enough to be sure of reaching the frame
31
+ * asked for.
32
+ *
33
+ * The consequence for a COPY is that asking for a keyframe lands on the one
34
+ * BEFORE it — deterministically, every time. Measured 2026-08-21 on a Matroska
35
+ * file with keyframes every 2 s: `-ss 10` produced a first segment starting at
36
+ * 8.000; `-ss 10.130435` produced one starting at 10.000. On MP4, where the
37
+ * heuristic does not fire, all of 10, 10.130435 and 10.2 produced 10.000 — so
38
+ * adding this is right in one case and harmless in the other.
39
+ *
40
+ * That landing is what `-segment_times` is measured from, while this code
41
+ * computes those offsets from the time it ASKED for. One keyframe interval
42
+ * apart, inherited by every cut of the run: 119 of 125 segments arriving a
43
+ * uniform 2.002 s early in the field, four times what a player bridges.
44
+ *
45
+ * Not applied when the picture is re-encoded: a re-encode decodes from the
46
+ * keyframe and discards frames up to the requested time, so its output already
47
+ * begins exactly where asked (measured the same day: `-ss 11` copied starts at
48
+ * 10.000, re-encoded at 11.000).
49
+ */
50
+ export const SEEK_LANDING_OFFSET_SEC = 3 / 23;
51
+
52
+ /**
53
+ * A number of seconds as ffmpeg will accept it.
54
+ *
55
+ * `String(n)` switches to exponential notation below 1e-6, and ffmpeg's
56
+ * duration parser rejects that outright: a field session died on
57
+ * `Invalid duration for option ss: 3.3333333249174757e-7`, after which the
58
+ * transcode was in state `failed` and every segment request answered 500 for
59
+ * as long as the viewer kept trying. Anything under a millisecond is also not a
60
+ * real offset — it is the residue of subtracting two nearly equal floats — so
61
+ * it is dropped rather than passed on.
62
+ *
63
+ * @param {number} value
64
+ * @returns {string}
65
+ */
66
+ export function ffmpegSeconds(value) {
67
+ if (!Number.isFinite(value) || Math.abs(value) < 0.001) {
68
+ return "0";
69
+ }
70
+ // Microsecond resolution, fixed notation, no trailing zero noise.
71
+ return value.toFixed(6).replace(/\.?0+$/, "");
72
+ }
73
+
74
+ /**
75
+ * Which timeline an output's own ffmpeg works on.
76
+ *
77
+ * True — the COPY branch: the source's timestamps are kept (`-copyts`) and the
78
+ * output is re-labelled 0-based. Everything handed to the muxer is therefore
79
+ * stated in the source's terms, and everything read back out of a produced
80
+ * piece is 0-based.
81
+ *
82
+ * False — the re-encode branch: the output is labelled from the run's start on
83
+ * the 0-based timeline, and the muxer is addressed in those same terms.
84
+ *
85
+ * One predicate for both callers, because the two used to answer it separately
86
+ * and a disagreement between them is exactly what desynced picture from sound.
87
+ *
88
+ * @param {{ audioOnly?: boolean, timeline?: { cutGrid?: string }, transcodeVideo?: boolean }} material
89
+ * @returns {boolean}
90
+ */
91
+ export function onKeyframeGridFor(material) {
92
+ return material?.audioOnly === true
93
+ ? material?.timeline?.cutGrid === "keyframe"
94
+ : material?.transcodeVideo !== true;
95
+ }
96
+
97
+ /**
98
+ * The boundary table the player is working from: the one its playlist was
99
+ * written from, falling back to the live table when no playlist was built from
100
+ * a table at all (no duration, so no synthetic playlist — and then nothing the
101
+ * player holds contradicts it).
102
+ *
103
+ * @param {{ published?: number[], boundaries?: number[] }} timeline
104
+ * @returns {number[]}
105
+ */
106
+ export function publishedGridFor(timeline) {
107
+ return Array.isArray(timeline?.published) && timeline.published.length > 0
108
+ ? timeline.published
109
+ : (timeline?.boundaries ?? []);
110
+ }
111
+
112
+ /**
113
+ * Where a run beginning at `index` must be positioned: the time the PLAYER was
114
+ * told that segment starts at.
115
+ *
116
+ * Two tables, deliberately: the live one is corrected as produced segments
117
+ * reveal where the file's cuts truly are, and those corrections are what let a
118
+ * re-encoded rung be forced onto a copied stream's real grid. But the playlist
119
+ * a player is holding was written once and never changes, so a position taken
120
+ * from the corrected table describes a timeline nobody sent the player. That is
121
+ * not a subtlety: it cost ten minutes of a dead film on 2026-08-17, the browser
122
+ * asking for two segments 1908 times each.
123
+ *
124
+ * @param {{ published?: number[], boundaries?: number[] }} timeline
125
+ * @param {number} index
126
+ * @param {number} segmentDurationSec - Used only when the file has no table at
127
+ * all, where a segment is a plain multiple of the nominal length.
128
+ * @returns {number}
129
+ */
130
+ export function publishedStartTime(timeline, index, segmentDurationSec) {
131
+ const published = Array.isArray(timeline?.published) && timeline.published.length > 0 ? timeline.published : null;
132
+ const table = published ?? (Array.isArray(timeline?.boundaries) ? timeline.boundaries : []);
133
+ if (table.length === 0) {
134
+ return index * segmentDurationSec;
135
+ }
136
+ const clamped = Math.max(0, Math.min(index, table.length - 1));
137
+ return table[clamped];
138
+ }
139
+
140
+ /**
141
+ * The cut times to hand ffmpeg for a run that starts at `startIndex`.
142
+ *
143
+ * Two adjustments, both of which cost a broken session to learn:
144
+ *
145
+ * - **Rebased.** `-segment_times` is measured from the start of the run, not
146
+ * of the file. Measured: starting at 12 s and asking for a cut at 18 s put
147
+ * it at 29.4 s — 12 + 18. So every boundary has the run's own start
148
+ * subtracted.
149
+ * - **Interior only.** The first boundary is where the run begins and the last
150
+ * is where the file ends; neither is a cut. Sending them would produce an
151
+ * empty leading segment and a spurious trailing one.
152
+ *
153
+ * @param {number[]} boundaries
154
+ * @param {number} startIndex
155
+ * @returns {number[] | null}
156
+ */
157
+ export function segmentCutTimesFrom(boundaries, startIndex) {
158
+ if (!Array.isArray(boundaries) || boundaries.length < 2) {
159
+ return null;
160
+ }
161
+ const index = Number.isInteger(startIndex) && startIndex > 0 ? startIndex : 0;
162
+ if (index >= boundaries.length - 1) {
163
+ return null;
164
+ }
165
+ const base = boundaries[index];
166
+ const times = [];
167
+ for (let at = index + 1; at < boundaries.length - 1; at += 1) {
168
+ times.push(Number((boundaries[at] - base).toFixed(6)));
169
+ }
170
+ return times;
171
+ }
172
+
173
+ /**
174
+ * The largest keyframe time that does not exceed `target`, from a SORTED
175
+ * (ascending) array of keyframe times. Null when `target` is before the first
176
+ * keyframe or the array is empty — the caller then falls back to its unsnapped
177
+ * target.
178
+ *
179
+ * @param {number[]} keyframeTimes - Sorted ascending.
180
+ * @param {number} target
181
+ * @returns {number | null}
182
+ */
183
+ export function nearestKeyframeAtOrBefore(keyframeTimes, target) {
184
+ let result = null;
185
+ for (const time of keyframeTimes) {
186
+ if (time > target) {
187
+ break;
188
+ }
189
+ result = time;
190
+ }
191
+ return result;
192
+ }
193
+
194
+ /**
195
+ * How much later than a keyframe to ASK, so that ffmpeg lands on that keyframe.
196
+ *
197
+ * Bounded by half the distance to the next keyframe, which matters only where
198
+ * keyframes stand closer together than twice the offset. There no single value
199
+ * can satisfy both worlds — asking too little lands a keyframe early when the
200
+ * heuristic fires, asking too much lands a keyframe late when it does not — and
201
+ * the bound picks the smaller error, which is then under one keyframe interval
202
+ * and therefore under what a player bridges.
203
+ *
204
+ * @param {{ transcodeVideo?: boolean, file?: { keyframeTimes?: number[], keyframeTolerance?: number } }} material
205
+ * @param {number} keyframe - A real keyframe time the run is to begin at.
206
+ * @returns {number} Seconds to add to the request.
207
+ */
208
+ export function seekLandingOffsetFor(material, keyframe) {
209
+ // A re-encode trims to the requested time itself, so it needs no help and
210
+ // must not be pushed past what it was asked for.
211
+ if (material?.transcodeVideo === true) {
212
+ return 0;
213
+ }
214
+ // A grid whose times are approximate needs that error added on top, or a name
215
+ // sitting just below its real keyframe seeks to before it and lands on the
216
+ // one before that. Only AVI declares one.
217
+ const tolerance = Number.isFinite(material?.file?.keyframeTolerance)
218
+ ? Math.max(0, material.file.keyframeTolerance)
219
+ : 0;
220
+ const wanted = SEEK_LANDING_OFFSET_SEC + tolerance;
221
+ const times = Array.isArray(material?.file?.keyframeTimes) ? material.file.keyframeTimes : [];
222
+ const next = times.find((time) => time > keyframe + 0.001);
223
+ if (next === undefined) {
224
+ return wanted;
225
+ }
226
+ return Math.min(wanted, (next - keyframe) / 2);
227
+ }
228
+
229
+ /**
230
+ * Everything ffmpeg is told for one run.
231
+ *
232
+ * @param {object} params
233
+ * @param {{ keyframeTimes?: number[], keyframeTolerance?: number }} params.file - The
234
+ * PICTURE's file: whose keyframes a seek snaps to.
235
+ * @param {{ startTime: number }} params.inputFile - The file this run reads.
236
+ * @param {{ startTime: number }} params.audioFile - The file the chosen
237
+ * soundtrack lives in, which for a dub shipped beside the picture is not the
238
+ * picture's own.
239
+ * @param {string} params.inputUrl
240
+ * @param {string} params.audioInputUrl - Empty unless a browser that takes its
241
+ * audio muxed is watching a release whose soundtrack is a file of its own.
242
+ * @param {{ published?: number[], boundaries?: number[], cutGrid?: string }} params.timeline
243
+ * @param {{ encodeWidth: number, encodeHeight: number, outputFps: number, softwarePreset: string | null, applyTonemap: boolean }} params.output
244
+ * @param {object} params.segmentFormat
245
+ * @param {boolean} params.transcodeVideo
246
+ * @param {boolean} params.transcodeAudio
247
+ * @param {boolean} params.audioOnly - An audio rendition: one track, no picture.
248
+ * @param {boolean} params.audioSeparate - The picture's sound is published as a
249
+ * rendition, so this output carries none.
250
+ * @param {number} params.audioSourceTrackIndex - `0:a:N` within its own file.
251
+ * @param {number | null} params.rateCapKbps
252
+ * @param {number} params.startIndex - First segment number this run makes.
253
+ * @param {number} params.endIndex - Last it makes, inclusive; below the start
254
+ * means it has no end.
255
+ * @param {number | undefined} params.positionSecondsOverride - Where to begin,
256
+ * when the caller knows better than the table.
257
+ * @param {object} params.videoEncoder
258
+ * @param {number} params.segmentDurationSec
259
+ * @returns {{ args: string[], safeIndex: number, startSeconds: number, cutTimes: number[] | null }}
260
+ */
261
+ export function buildRunCommand({
262
+ file,
263
+ inputFile,
264
+ audioFile,
265
+ inputUrl,
266
+ audioInputUrl: audioInputUrlGiven,
267
+ timeline,
268
+ output,
269
+ segmentFormat,
270
+ transcodeVideo,
271
+ transcodeAudio,
272
+ audioOnly,
273
+ audioSeparate,
274
+ audioSourceTrackIndex,
275
+ rateCapKbps,
276
+ startIndex,
277
+ endIndex,
278
+ positionSecondsOverride,
279
+ videoEncoder,
280
+ segmentDurationSec
281
+ }) {
282
+ const safeIndex = Number.isInteger(startIndex) && startIndex > 0 ? startIndex : 0;
283
+ // 0-based output time of this segment, from the table the PLAYER holds —
284
+ // the same one the cut list below is taken from.
285
+ //
286
+ // These two were read from different tables until 2026-08-21, and that is
287
+ // one fault, not two: `-segment_times` are measured from wherever the run
288
+ // really began, so any distance between the position and the cut list moves
289
+ // EVERY cut of that run by it. The live table keeps being corrected as
290
+ // produced segments reveal where the file's cuts truly are, and those
291
+ // corrections run backwards, so each restart began a little earlier than
292
+ // the grid the cuts were stated on — and since the corrections accumulate,
293
+ // so did the distance. Measured on `JUFD665.mp4`: after one seek restart a
294
+ // produced segment held the boundary two places before its own number
295
+ // (16.684 s, exactly 2.0000 segments), after the next it held the one four
296
+ // places before (33.5 s). The player's buffer then stops extending at all,
297
+ // because the content of every fragment lands before the time its playlist
298
+ // entry names: `bufferEnd` stood still at 4571.1 s through four `frag-far`
299
+ // warnings until hls.js gave up and jumped the viewer 16.8 s forward.
300
+ //
301
+ // 2.45.0 moved the CUT LIST onto the published table for this same reason
302
+ // and left the position on the live one. Both belong on the published
303
+ // table: a run must begin where the player was told the segment begins.
304
+ const startSeconds = Number.isFinite(positionSecondsOverride)
305
+ ? positionSecondsOverride
306
+ : publishedStartTime(timeline, safeIndex, segmentDurationSec);
307
+ // Where each of the two timelines begins, asked of the files themselves.
308
+ // Fresh by construction: the session may have been created before the
309
+ // soundtrack file's header could be read, and the reading lands on the file
310
+ // object this session holds — so there is nothing to re-read and nothing
311
+ // that can be stale. Same property as `file.keyframeTimes`,
312
+ // which is one table shared by every session of the file.
313
+ // Which timeline this run works on. Asked once, because the closure that
314
+ // adds the second input reads it too, and two readings of one predicate is
315
+ // how the picture and the sound came apart before.
316
+ const keyframeGrid = onKeyframeGridFor({ audioOnly, timeline, transcodeVideo });
317
+ const servesAudioSeparately = audioOnly !== true && audioSeparate === true;
318
+ const audioFileStartTime = audioFile.startTime;
319
+ // The start time of the file this run READS, which is the picture's own for
320
+ // every session except one whose soundtrack is a separate file.
321
+ const sourceStartTime = inputFile.startTime;
322
+ // Cut where this session's grid says, whoever is producing the frames. The
323
+ // times are measured from the start of THIS run; the same list serves as
324
+ // the cut points and, when re-encoding, as the keyframes to force — one
325
+ // list, so the two cannot drift apart.
326
+ const explicitTimes = segmentFormat.explicitTimesMuxerArgs?.() ?? null;
327
+ // A COPY is cut by this list whatever grid it ended up on. Even when no
328
+ // keyframe index could be read and the boundaries are a plain grid, saying
329
+ // them outright is what keeps the playlist and the muxer agreeing — ffmpeg
330
+ // moves each cut forward to the first real keyframe, and serving reads back
331
+ // where the piece truly begins. Requiring a keyframe grid here dropped a
332
+ // copy with no index onto the `hls` muxer, which takes no cut list and
333
+ // writes no self-contained pieces, so nothing could read a true start and
334
+ // segments were stamped with times the file does not have — the 4.17 s
335
+ // speech-against-subtitles drift, back again.
336
+ //
337
+ // Cut on the grid the PLAYER WAS GIVEN, not on the corrected one. A player
338
+ // places a fragment by the playlist it holds, and that text was written
339
+ // once and never changes; the live table keeps moving as produced segments
340
+ // reveal where the file's cuts really are. Cutting on the moved table makes
341
+ // every run faithful to a timeline nobody sent the player — measured
342
+ // 2026-08-20, the picture's segments arriving a uniform 2.002 s before the
343
+ // times the playlist named for them, which is four times what hls.js will
344
+ // bridge, so the fragment does not land and is asked for again.
345
+ //
346
+ // The corrections keep their purpose: they describe the file, and a variant
347
+ // created later inherits the corrected table and PUBLISHES it, so its own
348
+ // playlist and its own cuts agree from the start. What they may not do is
349
+ // move the cuts of a session whose playlist is already being read.
350
+ const gridCutTimes = explicitTimes && (!transcodeVideo || timeline.cutGrid === "keyframe")
351
+ ? segmentCutTimesFrom(publishedGridFor(timeline), safeIndex)
352
+ : null;
353
+ // Cut times are stated on the grid, for both branches.
354
+ //
355
+ // 2.28.0 added `sourceStartTime` to them on the copy branch, reasoning that
356
+ // the muxer decides its cuts before the output is relabelled. The field
357
+ // measured it the next session and the reasoning was wrong: of 75 pieces
358
+ // the picture produced, only NINE began at a time the container's own
359
+ // keyframe table names (the soundtrack, untouched by the change, scored 70
360
+ // of 75). Before it, every piece began exactly on a named keyframe and it
361
+ // was the PLAYLIST that disagreed with them. So the shift moved the cuts
362
+ // OFF the keyframes rather than onto them, and it is gone.
363
+ //
364
+ // What remains true, and is what that measurement is really about: the
365
+ // picture cuts where the source's keyframes are, and the playlist must be
366
+ // built from those same times. That is the correction path's job, not the
367
+ // cut list's.
368
+ const cutTimes = gridCutTimes;
369
+
370
+ // Video: re-encode only when required, using the detected encoder
371
+ // (hardware-accelerated or software). The descriptor builds the filter +
372
+ // codec args (including keyframe alignment on segment boundaries).
373
+ const videoCodecArgs = transcodeVideo
374
+ ? videoEncoder.buildVideoArgs({
375
+ // Budget-selected encode box (may be below the client target on weak
376
+ // software hosts); falls back to the client target for hardware.
377
+ targetWidth: output.encodeWidth,
378
+ targetHeight: output.encodeHeight,
379
+ segmentDurationSec: segmentDurationSec,
380
+ // Source-inherited output rate (integer, capped); descriptors that
381
+ // use time-based keyframes just apply it as the frame rate.
382
+ fps: output.outputFps,
383
+ // Software-only; hardware descriptors ignore it.
384
+ preset: output.softwarePreset ?? undefined,
385
+ // HDR→SDR tone map (software path only; gated on filter availability).
386
+ tonemap: output.applyTonemap === true,
387
+ // On the source's grid the cuts are not evenly spaced, so no frame
388
+ // count can describe them: the encoder is told the times outright,
389
+ // the same ones the muxer will cut at.
390
+ forcedKeyframeTimes: cutTimes,
391
+ // A ceiling the VIEWER's measured link put on this picture, when one
392
+ // has been measured. Null means the rung's own nominal rate stands.
393
+ nominalKbps: rateCapKbps ?? null
394
+ })
395
+ : ["-c:v", "copy"];
396
+ const audioCodecArgs = transcodeAudio
397
+ ? ["-c:a", "aac", "-ac", "2", "-b:a", "128k"]
398
+ : ["-c:a", "copy"];
399
+
400
+ const args = ["-hide_banner", "-nostats", "-loglevel", "error", "-progress", "pipe:1"];
401
+ // Hardware decode/encode setup (e.g. VAAPI device) must precede -i, and
402
+ // only applies when we actually re-encode the video track.
403
+ if (transcodeVideo && Array.isArray(videoEncoder.inputArgs)) {
404
+ args.push(...videoEncoder.inputArgs);
405
+ }
406
+ // Seek position in SOURCE time. On the keyframe grid `startSeconds` is a
407
+ // real keyframe's offset from zero, so the container's own start time goes
408
+ // back on to reach it; on the uniform grid it is a plain offset. This
409
+ // follows the GRID, not whether the video is re-encoded — a variant cut on
410
+ // the source's keyframes has to seek to them like the copy it accompanies.
411
+ const seekSeconds = timeline.cutGrid === "keyframe"
412
+ ? startSeconds + sourceStartTime
413
+ : startSeconds;
414
+ // Two-step seek when we have a real keyframe map: jump to a KNOWN-valid
415
+ // keyframe (coarse, before -i — safe because WE sourced it from ffprobe,
416
+ // not the container's own on-the-fly seek/index) and trim the short
417
+ // residual (bounded by the keyframe interval) precisely AFTER -i, which is
418
+ // always frame-accurate regardless of -accurate_seek.
419
+ //
420
+ // Root cause this works around: `-accurate_seek -ss X` before -i trusts the
421
+ // CONTAINER's own seek to land near X. For some containers (observed: AVI
422
+ // with VBR MP3 audio) that on-the-fly seek can point at a position with no
423
+ // valid frame boundary at all — ffmpeg fails outright ("Seek failed" /
424
+ // "Header missing"), not just imprecisely, and repeatedly so since every
425
+ // retry re-tries the SAME bad container-computed position. A keyframe we
426
+ // read directly from the packet list is a position ffmpeg has already
427
+ // proven it can decode.
428
+ //
429
+ // The keyframe is CARRIED from the table that named this boundary, not looked
430
+ // up by value. A boundary is stored on the player's clock, rounded, and
431
+ // `seekSeconds` above puts the container's start time back on to reach the
432
+ // file's clock a lossy round trip. A keyframe at 26.234 s in a container
433
+ // starting at 0.083 s comes back as 26.233999999999998, and "the keyframe at
434
+ // or before that" is then the PREVIOUS one, 8.717 s earlier: two parts in a
435
+ // quadrillion, one whole keyframe interval. That interval became a trim, the
436
+ // trim moved every cut of the run backwards by another interval, and the
437
+ // run's files were numbered from #36 while carrying film 17.4 s before what
438
+ // the playlist says #36 holds (field 2026-09-05: the picture covered the
439
+ // playhead, the sound had a 17.4 s hole across it, and the viewer waited two
440
+ // minutes for a buffer that could never fill).
441
+ //
442
+ // The search stays for a grid restored without its source clock, which is the
443
+ // only case that has nothing to carry.
444
+ const carriedKeyframe = timeline.cutGrid === "keyframe" && typeof timeline.sourceStartOf === "function"
445
+ ? timeline.sourceStartOf(safeIndex)
446
+ : null;
447
+ const snappedKeyframe = Number.isFinite(carriedKeyframe)
448
+ ? carriedKeyframe
449
+ : (Array.isArray(file.keyframeTimes) && file.keyframeTimes.length > 0
450
+ ? nearestKeyframeAtOrBefore(file.keyframeTimes, seekSeconds)
451
+ : null);
452
+ // A second input, and it exists for exactly one case: a browser that takes
453
+ // its audio muxed into the picture, watching a release whose soundtrack is a
454
+ // file of its own. An audio RENDITION reads that file as its only input and
455
+ // has none of this which is why the ordinary path, and every browser that
456
+ // understands rendition groups, still runs on a single input.
457
+ const audioInputUrl =
458
+ typeof audioInputUrlGiven === "string" && audioInputUrlGiven.length > 0
459
+ ? audioInputUrlGiven
460
+ : "";
461
+ // Where the picture's own start sits on the soundtrack file's timeline. Both
462
+ // files begin at their own container start time, and those need not be the
463
+ // same number; the difference is what keeps the two aligned.
464
+ const audioTimelineShift = audioInputUrl
465
+ ? audioFileStartTime - sourceStartTime
466
+ : 0;
467
+ /**
468
+ * Add the second input, if there is one, with its own seek.
469
+ *
470
+ * Called between the first `-i` and any OUTPUT option, because ffmpeg reads
471
+ * these positionally: an option written after the last `-i` applies to the
472
+ * output, and the residual seek below is exactly such an option. Getting the
473
+ * order wrong would silently turn the audio file's seek into a trim of the
474
+ * finished stream.
475
+ *
476
+ * @param {number} inputSeekSeconds - Where to start, on the PICTURE's
477
+ * timeline. Translated to the soundtrack file's own here.
478
+ */
479
+ const pushAudioInput = (inputSeekSeconds) => {
480
+ if (!audioInputUrl) {
481
+ return;
482
+ }
483
+ // `-itsoffset` states the soundtrack's timestamps on the picture's
484
+ // timeline, so everything after this point — `-copyts`, the output offset,
485
+ // the cut list — goes on treating the two as one timeline, unchanged.
486
+ //
487
+ // ONLY on the branch that keeps the source's own timestamps. Without
488
+ // `-copyts` ffmpeg rebases each input from its own seek point, and both
489
+ // inputs are seeked to the same instant just below so the two are
490
+ // already aligned and adding the offset would pull them apart by exactly
491
+ // the amount it exists to remove.
492
+ if (audioTimelineShift !== 0 && keyframeGrid) {
493
+ args.push("-itsoffset", ffmpegSeconds(-audioTimelineShift));
494
+ }
495
+ const audioSeek = Math.max(0, inputSeekSeconds + audioTimelineShift);
496
+ if (audioSeek > 0) {
497
+ // No keyframe to snap to and none needed: every audio frame is a sync
498
+ // point, so the seek can be accurate outright.
499
+ args.push("-accurate_seek", "-ss", ffmpegSeconds(audioSeek));
500
+ }
501
+ args.push("-i", audioInputUrl);
502
+ };
503
+
504
+ if (snappedKeyframe !== null) {
505
+ const residualSeconds = Math.max(0, seekSeconds - snappedKeyframe);
506
+ if (snappedKeyframe > 0) {
507
+ args.push("-ss", ffmpegSeconds(snappedKeyframe + seekLandingOffsetFor({ transcodeVideo, file }, snappedKeyframe)));
508
+ }
509
+ args.push("-i", inputUrl);
510
+ // The coarse landing, not the exact target: the residual below is discarded
511
+ // from the OUTPUT and so takes the same slice off every stream. Seeking the
512
+ // soundtrack to the exact target as well would take that slice twice and
513
+ // leave the sound running ahead of the picture by it.
514
+ pushAudioInput(snappedKeyframe);
515
+ // An output-side trim, and ONLY where the output is labelled from zero.
516
+ //
517
+ // Beside `-copyts` it does the opposite of what it says. Measured
518
+ // 2026-09-06 on a file with a 5 s keyframe interval: a run landed at 15 s
519
+ // and asked to trim to the cut at 20 s produced its first file starting at
520
+ // 10 s, and a run asked to trim to 17 s produced cuts at 13.129, 18.129,
521
+ // 23.129 the whole grid moved back by the trim itself. The muxer's cut
522
+ // times are absolute under `-copyts` while the trim is not, so every cut of
523
+ // the run inherits the difference and the numbering, fixed at spawn, is
524
+ // wrong by however many cuts that is.
525
+ //
526
+ // On the keyframe grid the run begins AT a cut, so there is nothing to
527
+ // trim: the carried keyframe above makes this exactly zero rather than
528
+ // nearly zero.
529
+ if (residualSeconds > 0 && !keyframeGrid) {
530
+ args.push("-ss", ffmpegSeconds(residualSeconds));
531
+ }
532
+ } else {
533
+ if (seekSeconds > 0) {
534
+ // No keyframe map (probe failed/timed out) fall back to the previous
535
+ // behaviour: trust the container's own accurate seek.
536
+ args.push("-accurate_seek", "-ss", ffmpegSeconds(seekSeconds));
537
+ }
538
+ args.push("-i", inputUrl);
539
+ pushAudioInput(seekSeconds);
540
+ }
541
+ // Which timeline the output is labelled on. An audio rendition has no
542
+ // picture of its own to follow, so it follows the grid it was given — the
543
+ // same one the video it plays with is on. Deciding by `transcodeVideo`, as
544
+ // everything else here does, would put the audio of a re-encoded stream on
545
+ // the copy branch: `-copyts` and a shift by the container's start time,
546
+ // against a picture labelled from zero. The two would be offset by
547
+ // `sourceStartTime` for the whole file.
548
+ if (!keyframeGrid) {
549
+ // Branch A (re-encode): fixed GOP makes keyframes land exactly on the
550
+ // segment grid; relabel output onto the original timeline so segment N
551
+ // carries PTS = N × segmentDuration.
552
+ if (startSeconds > 0) {
553
+ args.push("-output_ts_offset", ffmpegSeconds(startSeconds));
554
+ }
555
+ } else {
556
+ // Branch B (video copied — only audio is transcoded): we cannot insert
557
+ // keyframes, so segments are cut at the source's own keyframes (the
558
+ // playlist boundaries were built from those keyframes). Keep the source's
559
+ // real timestamps (`-copyts`) so copied frames stay continuous across
560
+ // boundaries/seeks, and shift by -startTime so the output timeline is
561
+ // 0-based (a non-zero container start otherwise puts a hole at the very
562
+ // beginning and desyncs audio/video). Audio is transcoded on this timeline.
563
+ args.push("-copyts");
564
+ if (sourceStartTime !== 0) {
565
+ args.push("-output_ts_offset", ffmpegSeconds(-sourceStartTime));
566
+ }
567
+ }
568
+ // Where this run STOPS. Until now a run had a start and no end — neither
569
+ // `-to` nor `-t` appeared anywhere in the arguments this proxy builds so
570
+ // every stop was a kill from outside, and two runs on one output could only
571
+ // be kept apart by giving each its own directory. With an end they cannot
572
+ // reach each other's numbers at all, and a run that finishes its stretch
573
+ // exits by itself instead of having to be noticed and killed.
574
+ //
575
+ // WHICH argument states it is a property of the branch, and it is measured
576
+ // rather than reasoned (2026-09-04, `research/encoder-layer-2026-09-04.md`
577
+ // §11): `-t` is a duration on the output's own clock, and `-to` a point on
578
+ // the input's. The copy branch runs with `-copyts`, where the input's clock
579
+ // IS the source's, so `-to` takes the absolute time; the re-encode branch
580
+ // has no `-copyts` and takes the duration. Swapping them is not a near
581
+ // miss on the copy branch `-t` produced one segment where five were
582
+ // wanted, because the time it names is already past when the run starts.
583
+ const runEnd = Number.isInteger(endIndex) ? endIndex : -1;
584
+ const publishedGrid = publishedGridFor(timeline);
585
+ if (runEnd >= safeIndex && Array.isArray(publishedGrid) && publishedGrid[runEnd + 1] > 0) {
586
+ const endsAt = publishedGrid[runEnd + 1];
587
+ if (transcodeVideo) {
588
+ args.push("-t", ffmpegSeconds(Math.max(0.1, endsAt - publishedGrid[safeIndex])));
589
+ } else {
590
+ args.push("-to", ffmpegSeconds(endsAt));
591
+ }
592
+ }
593
+ if (audioOnly === true) {
594
+ // An audio RENDITION: one track, no picture. Published as its own
595
+ // `#EXT-X-MEDIA` and shared by every video variant, so the track is
596
+ // encoded once for the file instead of once per rung, and changing it is
597
+ // the player switching rendition rather than this proxy rebuilding the
598
+ // session. Cut on the same grid as the video it accompanies, which is
599
+ // what lets the two be played together.
600
+ // `0:` because a rendition's only input IS the file its track lives in —
601
+ // the picture's own file, or the one beside it that carries this dub.
602
+ args.push("-vn", "-map", `0:a:${audioSourceTrackIndex}?`, ...audioCodecArgs);
603
+ } else if (servesAudioSeparately) {
604
+ // The other half of the same arrangement: the picture alone, because its
605
+ // audio is published as a rendition and would otherwise play twice.
606
+ args.push("-an", "-map", "0:v:0?", ...videoCodecArgs);
607
+ } else {
608
+ args.push(
609
+ "-map",
610
+ "0:v:0?",
611
+ "-map",
612
+ // The audio track the viewer chose: input 1 when their choice is a
613
+ // soundtrack shipped as its own file, input 0 when it is one of the
614
+ // picture's own. Type-relative within that input, which is what
615
+ // `audioSourceTrackIndex` holds — the number the browser sent is flat
616
+ // across both files and was resolved when the session was made.
617
+ `${audioInputUrl ? 1 : 0}:a:${audioSourceTrackIndex}?`,
618
+ ...videoCodecArgs,
619
+ ...audioCodecArgs
620
+ );
621
+ }
622
+
623
+ // Where the cuts come from. On the copy path they are the source's own
624
+ // keyframes, and until now they were only ever GUESSED: ffmpeg got a target
625
+ // duration and chose its own cut points, while the playlist was built from
626
+ // the container index two independent calculations with nothing tying
627
+ // them together but the hope that they agree. They do not. The index is a
628
+ // navigation table and is not obliged to list every keyframe; for a field
629
+ // file it held 1902 while ffmpeg found roughly twice as many and cut twice
630
+ // as often. Segment #876 then meant 1:26:50 to the player and about minute
631
+ // 58 to ffmpeg, which is why a seek landed nowhere near where it was aimed
632
+ // and the reported duration drifted.
633
+ //
634
+ // So stop guessing and say it: the `segment` muxer takes the list of times
635
+ // outright. Passing the very boundaries the playlist was built from makes
636
+ // the two agree by construction. Only cut points already known to be real
637
+ // keyframes are sent, so ffmpeg never has to move one forward.
638
+ //
639
+ // The list is built above, before the encoder args, because a re-encoded
640
+ // variant of a copied stream needs the same times twice over: once as the
641
+ // cuts, once as the keyframes to force at them.
642
+ if (cutTimes && cutTimes.length > 0) {
643
+ args.push(
644
+ "-f",
645
+ "segment",
646
+ // Times are measured from the START OF THIS RUN, not from the start of
647
+ // the file — verified: starting at 12 s and asking for a cut at 18 s
648
+ // produced one at 29.4 s. `segmentCutTimesFrom` rebases them.
649
+ "-segment_times",
650
+ cutTimes.join(","),
651
+ // A cut lands on the first keyframe at or after its time, so a boundary
652
+ // recorded a hair late would skip to the next one and double the
653
+ // segment. The tolerance absorbs that rounding.
654
+ "-segment_time_delta",
655
+ "0.05",
656
+ "-segment_start_number",
657
+ String(safeIndex),
658
+ // THE ENCODER SAYS WHEN A PIECE IS FINISHED, on a channel of its own.
659
+ //
660
+ // Measured on the addon host 2026-09-05: a name appears in this list when
661
+ // the file is CLOSED, not when it is created — at the third sample
662
+ // `seg-000.mp4` was on disk and absent from the list, and it appeared at
663
+ // the fourth, in the same moment `seg-001.mp4` came into being. So a name
664
+ // here is the writer's own statement that the piece is whole.
665
+ //
666
+ // Without it, a finished file is indistinguishable from one still being
667
+ // written, and the only proof available was the existence of the NEXT
668
+ // one — which never comes for the last piece of every run.
669
+ "-segment_list",
670
+ "pipe:3",
671
+ "-segment_list_flags",
672
+ "+live",
673
+ ...explicitTimes,
674
+ segmentFormat.segmentFileNameTemplate()
675
+ );
676
+ } else {
677
+ args.push(
678
+ "-f",
679
+ "hls",
680
+ "-hls_time",
681
+ String(segmentDurationSec),
682
+ "-hls_list_size",
683
+ "0",
684
+ "-hls_flags",
685
+ "independent_segments+temp_file",
686
+ // Container selection + segment naming, from the active format module.
687
+ ...segmentFormat.muxerArgs(),
688
+ "-start_number",
689
+ String(safeIndex),
690
+ // ffmpeg writes its own playlist here; we ignore it and serve the
691
+ // synthetic VOD playlist instead (see getFileStream).
692
+ PLAYLIST_FILE_NAME
693
+ );
694
+ }
695
+ return { args, safeIndex, startSeconds, cutTimes };
696
+
697
+ }