@torrent-tv/proxy 2.91.0 → 2.92.1

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 (145) hide show
  1. package/bin/cli.js +3 -2
  2. package/package.json +18 -2
  3. package/routes/api/playback-plan/post.js +21 -4
  4. package/routes/api/sources/files/get.js +20 -28
  5. package/routes/api/sources/post.js +4 -2
  6. package/routes/api/sources/stats/get.js +4 -11
  7. package/routes/api/sources/viewer/post.js +16 -0
  8. package/routes/api/sources/warm/post.js +6 -215
  9. package/routes/api/subtitles/get.js +22 -125
  10. package/routes/api/subtitles/post.js +26 -0
  11. package/routes/api/transcode-sessions/post.js +24 -2
  12. package/routes/media/get.js +80 -0
  13. package/routes/stream/get.js +26 -94
  14. package/routes/transcode/audio-warm/get.js +9 -21
  15. package/routes/transcode/variant-warm/get.js +8 -14
  16. package/server.js +410 -46
  17. package/services/encode/AdmittedInput.js +136 -0
  18. package/services/encode/CushionReport.js +1 -76
  19. package/services/encode/EncodeInputs.js +142 -0
  20. package/services/encode/EncodeOrchestrator.js +4 -1
  21. package/services/encode/EncodeRun.js +13 -4
  22. package/services/encode/EncodeRuns.js +132 -52
  23. package/services/encode/InputFailures.js +37 -0
  24. package/services/encode/MatroskaInput.js +158 -0
  25. package/services/encode/OutputOpening.js +16 -64
  26. package/services/encode/Renditions.js +1 -17
  27. package/services/encode/admitted-command.js +60 -0
  28. package/services/encode/annex-b-input.js +37 -0
  29. package/services/encode/bit-payload.js +29 -0
  30. package/services/encode/output/OutputCatalog.js +1 -1
  31. package/services/encode/output/Timeline.js +11 -0
  32. package/services/encode/pcm-normalization.js +30 -0
  33. package/services/encode/piece-completeness.js +54 -1
  34. package/services/encode/quality/HostLoad.js +19 -73
  35. package/services/encode/quality/QualityOffer.js +1 -1
  36. package/services/encode/run-command.js +1 -589
  37. package/services/encode/segment-formats/mp4-boxes.js +3 -1
  38. package/services/encode/segment-formats/presentation-segment.js +114 -0
  39. package/services/media/ContainerOrchestrator.js +118 -48
  40. package/services/media/KeyframeTables.js +16 -115
  41. package/services/media/MediaReadRequests.js +120 -0
  42. package/services/media/ProbeRequests.js +135 -0
  43. package/services/media/SegmentInputs.js +48 -0
  44. package/services/media/SourceFile.js +6 -0
  45. package/services/media/SubtitleOrchestrator.js +190 -4
  46. package/services/media/await-plan.js +47 -0
  47. package/services/media/container/AsfContainer.js +217 -0
  48. package/services/media/container/AviContainer.js +343 -34
  49. package/services/media/container/CadencedPictureOrder.js +45 -0
  50. package/services/media/container/Container.js +7 -3
  51. package/services/media/container/ContainerFactory.js +10 -3
  52. package/services/media/container/FfprobeContainer.js +222 -0
  53. package/services/media/container/MatroskaContainer.js +72 -46
  54. package/services/media/container/Mp4Container.js +472 -139
  55. package/services/media/container/MpegPsContainer.js +281 -0
  56. package/services/media/container/MpegTsContainer.js +277 -0
  57. package/services/media/container/PacketIndex.js +270 -0
  58. package/services/media/container/PacketRecords.js +237 -0
  59. package/services/media/container/RetainedBytes.js +39 -0
  60. package/services/media/container/RetainedReads.js +51 -0
  61. package/services/media/container/ac3-frame.js +46 -0
  62. package/services/media/container/asf-packets.js +153 -0
  63. package/services/media/container/avc-picture-order.js +50 -0
  64. package/services/media/container/avi-open-dml.js +47 -0
  65. package/services/media/container/dts-frame.js +51 -0
  66. package/services/media/container/ebml-stream.js +12 -1
  67. package/services/media/container/ffprobe-record.js +45 -0
  68. package/services/media/container/flv-packet-ranges.js +27 -0
  69. package/services/media/container/following-packet-time.js +37 -0
  70. package/services/media/container/h264-configuration.js +183 -0
  71. package/services/media/container/h264-elementary-index.js +245 -0
  72. package/services/media/container/hevc-configuration.js +165 -0
  73. package/services/media/container/hevc-elementary-index.js +132 -0
  74. package/services/media/container/hevc-picture-order.js +66 -0
  75. package/services/media/container/latm-frame.js +99 -0
  76. package/services/media/container/matroska-packets.js +207 -0
  77. package/services/media/container/memory-unavailable.js +8 -0
  78. package/services/media/container/mp3-packet-dependencies.js +41 -0
  79. package/services/media/container/mp4-fragments.js +148 -0
  80. package/services/media/container/mpeg-audio-frame.js +19 -0
  81. package/services/media/container/mpeg-audio-reservoir.js +27 -0
  82. package/services/media/container/mpeg-elementary-index.js +196 -0
  83. package/services/media/container/mpeg-sequence-reader.js +69 -0
  84. package/services/media/container/mpeg-ts-packets.js +93 -0
  85. package/services/media/container/mpeg-video-configuration.js +50 -0
  86. package/services/media/container/mpeg4-picture-timing.js +108 -0
  87. package/services/media/container/pes-header.js +34 -0
  88. package/services/media/playback-declarations.js +57 -0
  89. package/services/media/playback-planner.js +72 -230
  90. package/services/media/probe-packets.js +66 -0
  91. package/services/media/read-playback-declarations.js +18 -0
  92. package/services/media/tracks/AudioTrack.js +9 -0
  93. package/services/media/tracks/TextSubtitleTrack.js +4 -1
  94. package/services/server/OutputLifecycle.js +2 -0
  95. package/services/server/SegmentServing.js +40 -33
  96. package/services/server/ViewerRequests.js +22 -41
  97. package/services/server/controllers/PlaybackController.js +4 -0
  98. package/services/server/controllers/SubtitleController.js +8 -29
  99. package/services/server/transcode-session-files.js +58 -99
  100. package/services/server/wire-outputs.js +58 -15
  101. package/services/storage/IndexMemory.js +85 -0
  102. package/services/storage/MachineBudget.js +27 -3
  103. package/services/storage/allowance.js +8 -1
  104. package/services/storage/piece-store/piece-disk-store.js +18 -3
  105. package/services/storage/piece-store/piece-lru.js +8 -4
  106. package/services/storage/piece-store/shared-piece-store.js +26 -11
  107. package/services/storage/segment-store/SegmentStore.js +49 -18
  108. package/services/storage/wire.js +7 -0
  109. package/services/torrent/Contents.js +52 -20
  110. package/services/torrent/demand/DemandRegister.js +13 -4
  111. package/services/torrent/demand/Window.js +13 -2
  112. package/services/torrent/demand-progress.js +25 -0
  113. package/services/torrent/download/DeadlineScheduler.js +167 -0
  114. package/services/torrent/download/FutureDownload.js +166 -0
  115. package/services/torrent/download/SwarmSelection.js +30 -59
  116. package/services/torrent/download/registry.js +45 -5
  117. package/services/torrent/download/withdraw-claim.js +2 -0
  118. package/services/torrent/torrent-pool.js +39 -600
  119. package/services/torrent/worker/channel.js +8 -1
  120. package/services/torrent/worker/client.js +74 -72
  121. package/services/torrent/worker/files-in-use.js +9 -0
  122. package/services/torrent/worker/handle-state.js +12 -0
  123. package/services/torrent/worker/held-bytes.js +82 -99
  124. package/services/torrent/worker/held-file-bytes.js +17 -0
  125. package/services/torrent/worker/piece-reader.js +67 -683
  126. package/services/torrent/worker/pool-adapter.js +37 -123
  127. package/services/torrent/worker/protocol.js +6 -17
  128. package/services/torrent/worker/whole-file-stats.js +2 -0
  129. package/services/torrent/worker/worker.js +86 -156
  130. package/services/transport/data-channel-handler.js +56 -13
  131. package/services/viewer/DownloadMaps.js +168 -0
  132. package/services/viewer/NativeSourceMap.js +33 -0
  133. package/services/viewer/PriorityMap.js +49 -40
  134. package/services/viewer/PriorityOrchestrator.js +42 -13
  135. package/services/viewer/SourcePreparation.js +278 -0
  136. package/services/viewer/Viewer.js +11 -0
  137. package/services/viewer/Viewers.js +109 -2
  138. package/services/viewer/playback-readiness.js +50 -63
  139. package/services/viewer/segment-demands.js +37 -0
  140. package/services/viewer/urgent-output-ready.js +26 -0
  141. package/services/encode/run-inputs.js +0 -53
  142. package/services/media/keyframe-probe.js +0 -157
  143. package/services/media/media-info-probe.js +0 -93
  144. package/services/torrent/worker/background-fill.js +0 -213
  145. package/services/torrent/worker/resume-warm.js +0 -107
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @file The full argument list for one encoder run.
2
+ * @file Shared published-timeline calculations for an admitted encoder run.
3
3
  *
4
4
  * What a run is given is a fact about WHAT is being produced and WHERE it
5
5
  * begins, and about nothing else — not the session it belongs to, not who is
@@ -15,40 +15,6 @@
15
15
  * killing and resuming belong to whoever owns the process.
16
16
  */
17
17
 
18
- import { PLAYLIST_FILE_NAME } from "./output/playlists.js";
19
- import { AUDIO_TRANSCODE_KBPS } from "./args.js";
20
- import { cutsAtGivenTimes, SEGMENT_CUT_TIME_DELTA_SECONDS } from "./output/index.js";
21
-
22
- /**
23
- * What ffmpeg's own CLI subtracts from an input seek, and therefore what has to
24
- * be added back to land where we asked.
25
- *
26
- * `fftools/ffmpeg_demux.c`, in `ifile_open`: when the container does not
27
- * declare `AVFMT_SEEK_TO_PTS` — Matroska does not — and any stream carries
28
- * B-frames, the seek target is moved back by `3*AV_TIME_BASE / 23` before
29
- * `avformat_seek_file` is called. Its purpose is sound: such containers seek in
30
- * decode order while the caller asks in presentation order, and with B-frames
31
- * the two differ, so it backs off far enough to be sure of reaching the frame
32
- * asked for.
33
- *
34
- * The consequence for a COPY is that asking for a keyframe lands on the one
35
- * BEFORE it — deterministically, every time. Measured 2026-08-21 on a Matroska
36
- * file with keyframes every 2 s: `-ss 10` produced a first segment starting at
37
- * 8.000; `-ss 10.130435` produced one starting at 10.000. On MP4, where the
38
- * heuristic does not fire, all of 10, 10.130435 and 10.2 produced 10.000 — so
39
- * adding this is right in one case and harmless in the other.
40
- *
41
- * That landing is what `-segment_times` is measured from, while this code
42
- * computes those offsets from the time it ASKED for. One keyframe interval
43
- * apart, inherited by every cut of the run: 119 of 125 segments arriving a
44
- * uniform 2.002 s early in the field, four times what a player bridges.
45
- *
46
- * Not applied when the picture is re-encoded: a re-encode decodes from the
47
- * keyframe and discards frames up to the requested time, so its output already
48
- * begins exactly where asked (measured the same day: `-ss 11` copied starts at
49
- * 10.000, re-encoded at 11.000).
50
- */
51
- export const SEEK_LANDING_OFFSET_SEC = 3 / 23;
52
18
 
53
19
  /**
54
20
  * A number of seconds as ffmpeg will accept it.
@@ -213,557 +179,3 @@ export function nearestKeyframeAtOrBefore(keyframeTimes, target) {
213
179
  }
214
180
  return result;
215
181
  }
216
-
217
- /**
218
- * How much later than a keyframe to ASK, so that ffmpeg lands on that keyframe.
219
- *
220
- * Bounded by half the distance to the next keyframe, which matters only where
221
- * keyframes stand closer together than twice the offset. There no single value
222
- * can satisfy both worlds — asking too little lands a keyframe early when the
223
- * heuristic fires, asking too much lands a keyframe late when it does not — and
224
- * the bound picks the smaller error, which is then under one keyframe interval
225
- * and therefore under what a player bridges.
226
- *
227
- * @param {{ transcodeVideo?: boolean, audioOnly?: boolean, keyframes?: { times?: number[] | null, tolerance?: number } }} material
228
- * @param {number} keyframe - A real keyframe time the run is to begin at.
229
- * @returns {number} Seconds to add to the request.
230
- */
231
- export function seekLandingOffsetFor(material, keyframe) {
232
- // A re-encode trims to the requested time itself, so it needs no help and
233
- // must not be pushed past what it was asked for.
234
- //
235
- // AN OUTPUT CARRYING ONLY SOUND IS SUCH A RE-ENCODE, and asking about the
236
- // picture missed it: the flag says whether the PICTURE is re-encoded, and an
237
- // output with no picture answers no. So the whole offset was added to the
238
- // soundtrack's own seek, and the sound then played 130 ms ahead of the picture
239
- // from every restart onward — reported by the viewer 2026-09-06 as lips out of
240
- // step with the voice from two minutes in, and measured: both outputs were
241
- // repositioned to the same boundary and both given `-ss 166.963435`, after
242
- // which the copied picture landed on the keyframe at 166.833 while the
243
- // re-encoded sound began where it was asked.
244
- if (material?.transcodeVideo === true || material?.audioOnly === true) {
245
- return 0;
246
- }
247
- // A grid whose times are approximate needs that error added on top, or a name
248
- // sitting just below its real keyframe seeks to before it and lands on the
249
- // one before that. Only AVI declares one.
250
- const tolerance = Number.isFinite(material?.keyframes?.tolerance)
251
- ? Math.max(0, material.keyframes.tolerance)
252
- : 0;
253
- const wanted = SEEK_LANDING_OFFSET_SEC + tolerance;
254
- const times = Array.isArray(material?.keyframes?.times) ? material.keyframes.times : [];
255
- const next = times.find((time) => time > keyframe + 0.001);
256
- if (next === undefined) {
257
- return wanted;
258
- }
259
- return Math.min(wanted, (next - keyframe) / 2);
260
- }
261
-
262
- /**
263
- * Everything ffmpeg is told for one run.
264
- *
265
- * @param {object} params
266
- * @param {{ times?: number[] | null, tolerance?: number }} params.keyframes - Where
267
- * the PICTURE's file has its keyframes: what a seek snaps to. Plain values,
268
- * so this can be asked without a container, a torrent or a session.
269
- * @param {{ startTime: number }} params.inputFile - The file this run reads.
270
- * @param {{ startTime: number }} params.audioFile - The file the chosen
271
- * soundtrack lives in, which for a dub shipped beside the picture is not the
272
- * picture's own.
273
- * @param {string} params.inputUrl
274
- * @param {string} params.audioInputUrl - Empty unless a browser that takes its
275
- * audio muxed is watching a release whose soundtrack is a file of its own.
276
- * @param {{ published?: number[], boundaries?: number[], cutGrid?: string }} params.timeline
277
- * @param {{ encodeWidth: number, encodeHeight: number, outputFps: number, softwarePreset: string | null, applyTonemap: boolean }} params.output
278
- * @param {object} params.segmentFormat
279
- * @param {boolean} params.transcodeVideo
280
- * @param {boolean} params.transcodeAudio
281
- * @param {boolean} params.audioOnly - An audio rendition: one track, no picture.
282
- * @param {boolean} params.audioSeparate - The picture's sound is published as a
283
- * rendition, so this output carries none.
284
- * @param {number} params.audioSourceTrackIndex - `0:a:N` within its own file.
285
- * @param {{ maxrateKbps: number, bufsizeKbps: number, level: string | null } | null} params.rateControl
286
- * The output's own, as its key names it; null where nothing bounds the rate.
287
- * @param {number} params.startIndex - First segment number this run makes.
288
- * @param {number} params.endIndex - Last it makes, inclusive; below the start
289
- * means it has no end.
290
- * @param {number | undefined} params.positionSecondsOverride - Where to begin,
291
- * when the caller knows better than the table.
292
- * @param {object} params.videoEncoder
293
- * @param {number} params.segmentDurationSec
294
- * @returns {{ args: string[], safeIndex: number, startSeconds: number, cutTimes: number[] | null }}
295
- */
296
- export function buildRunCommand({
297
- keyframes,
298
- inputFile,
299
- audioFile,
300
- inputUrl,
301
- audioInputUrl: audioInputUrlGiven,
302
- timeline,
303
- output,
304
- segmentFormat,
305
- transcodeVideo,
306
- transcodeAudio,
307
- audioOnly,
308
- audioSeparate,
309
- audioSourceTrackIndex,
310
- rateControl,
311
- startIndex,
312
- endIndex,
313
- positionSecondsOverride,
314
- videoEncoder,
315
- segmentDurationSec
316
- }) {
317
- const safeIndex = Number.isInteger(startIndex) && startIndex > 0 ? startIndex : 0;
318
- // 0-based output time of this segment, from the table the PLAYER holds —
319
- // the same one the cut list below is taken from.
320
- //
321
- // These two were read from different tables until 2026-08-21, and that is
322
- // one fault, not two: `-segment_times` are measured from wherever the run
323
- // really began, so any distance between the position and the cut list moves
324
- // EVERY cut of that run by it. The live table keeps being corrected as
325
- // produced segments reveal where the file's cuts truly are, and those
326
- // corrections run backwards, so each restart began a little earlier than
327
- // the grid the cuts were stated on — and since the corrections accumulate,
328
- // so did the distance. Measured on `JUFD665.mp4`: after one seek restart a
329
- // produced segment held the boundary two places before its own number
330
- // (16.684 s, exactly 2.0000 segments), after the next it held the one four
331
- // places before (33.5 s). The player's buffer then stops extending at all,
332
- // because the content of every fragment lands before the time its playlist
333
- // entry names: `bufferEnd` stood still at 4571.1 s through four `frag-far`
334
- // warnings until hls.js gave up and jumped the viewer 16.8 s forward.
335
- //
336
- // 2.45.0 moved the CUT LIST onto the published table for this same reason
337
- // and left the position on the live one. Both belong on the published
338
- // table: a run must begin where the player was told the segment begins.
339
- const startSeconds = Number.isFinite(positionSecondsOverride)
340
- ? positionSecondsOverride
341
- : publishedStartTime(timeline, safeIndex, segmentDurationSec);
342
- // Where each of the two timelines begins, asked of the files themselves.
343
- // Fresh by construction: the session may have been created before the
344
- // soundtrack file's header could be read, and the reading lands on the file
345
- // object this session holds — so there is nothing to re-read and nothing
346
- // that can be stale. Same property as the keyframe table, which is one
347
- // object shared by every session of the file.
348
- // Which timeline this run works on. Asked once, because the closure that
349
- // adds the second input reads it too, and two readings of one predicate is
350
- // how the picture and the sound came apart before.
351
- const keyframeGrid = onKeyframeGridFor({ audioOnly, timeline, transcodeVideo });
352
- const servesAudioSeparately = audioOnly !== true && audioSeparate === true;
353
- const audioFileStartTime = audioFile.startTime;
354
- // The start time of the file this run READS, which is the picture's own for
355
- // every session except one whose soundtrack is a separate file.
356
- const sourceStartTime = inputFile.startTime;
357
- // Cut where this session's grid says, whoever is producing the frames. The
358
- // times are measured from the start of THIS run; the same list serves as
359
- // the cut points and, when re-encoding, as the keyframes to force — one
360
- // list, so the two cannot drift apart.
361
- const explicitTimes = segmentFormat.explicitTimesMuxerArgs?.() ?? null;
362
- // Matroska seeks begin without the preceding decode timestamps. Copy one
363
- // preceding cut privately so reordered frames have established DTS before
364
- // the first requested cut. It is never published over another run's output.
365
- const inputIndex = !transcodeVideo && !audioOnly && explicitTimes && safeIndex > 0
366
- ? safeIndex - 1 : safeIndex;
367
- // EVERY OUTPUT WITH A GRID is cut by this list, whatever the grid is and
368
- // whether the picture is copied or re-encoded (`cutsAtGivenTimes`).
369
- //
370
- // A copy needs it even when no keyframe index could be read and the
371
- // boundaries are a plain grid: saying them outright is what keeps the
372
- // playlist and the muxer agreeing — ffmpeg moves each cut forward to the
373
- // first real keyframe, and serving reads back where the piece truly begins.
374
- // Requiring a keyframe grid here dropped a copy with no index onto the `hls`
375
- // muxer, which takes no cut list and writes no self-contained pieces, so
376
- // nothing could read a true start and segments were stamped with times the
377
- // file does not have — the 4.17 s speech-against-subtitles drift, back again.
378
- //
379
- // A re-encode on the even grid needs it for the proof of a closed piece. The
380
- // `hls` muxer finishes the piece it has open whenever it ends, on our SIGTERM
381
- // and when its input stops, and renames it to the served name itself, so a
382
- // stopped run left a piece shorter than its span where any request could
383
- // take it. Measured 2026-10-05 with ffmpeg 8.1.2 on the addon host, a
384
- // 4 s piece stopped 3 s in stayed as `segment-00001.mp4` with 3.04 s in it.
385
- // Through the `segment` muxer the piece is published only on the encoder's
386
- // word and only after its media is shown to reach its cut.
387
- //
388
- // Cut on the grid the PLAYER WAS GIVEN, not on the corrected one. A player
389
- // places a fragment by the playlist it holds, and that text was written
390
- // once and never changes; the live table keeps moving as produced segments
391
- // reveal where the file's cuts really are. Cutting on the moved table makes
392
- // every run faithful to a timeline nobody sent the player — measured
393
- // 2026-08-20, the picture's segments arriving a uniform 2.002 s before the
394
- // times the playlist named for them, which is four times what hls.js will
395
- // bridge, so the fragment does not land and is asked for again.
396
- //
397
- // The corrections keep their purpose: they describe the file, and a variant
398
- // created later inherits the corrected table and PUBLISHES it, so its own
399
- // playlist and its own cuts agree from the start. What they may not do is
400
- // move the cuts of a session whose playlist is already being read.
401
- const gridCutTimes = cutsAtGivenTimes({ segmentFormat, timeline })
402
- ? segmentCutTimesFrom(publishedGridFor(timeline), inputIndex)
403
- : null;
404
- // Cut times are stated on the grid, for both branches.
405
- //
406
- // 2.28.0 added `sourceStartTime` to them on the copy branch, reasoning that
407
- // the muxer decides its cuts before the output is relabelled. The field
408
- // measured it the next session and the reasoning was wrong: of 75 pieces
409
- // the picture produced, only NINE began at a time the container's own
410
- // keyframe table names (the soundtrack, untouched by the change, scored 70
411
- // of 75). Before it, every piece began exactly on a named keyframe and it
412
- // was the PLAYLIST that disagreed with them. So the shift moved the cuts
413
- // OFF the keyframes rather than onto them, and it is gone.
414
- //
415
- // What remains true, and is what that measurement is really about: the
416
- // picture cuts where the source's keyframes are, and the playlist must be
417
- // built from those same times. That is the correction path's job, not the
418
- // cut list's.
419
- const cutTimes = gridCutTimes;
420
-
421
- // Video: re-encode only when required, using the detected encoder
422
- // (hardware-accelerated or software). The descriptor builds the filter +
423
- // codec args (including keyframe alignment on segment boundaries).
424
- const videoCodecArgs = transcodeVideo
425
- ? videoEncoder.buildVideoArgs({
426
- // Budget-selected encode box (may be below the client target on weak
427
- // software hosts); falls back to the client target for hardware.
428
- targetWidth: output.encodeWidth,
429
- targetHeight: output.encodeHeight,
430
- segmentDurationSec: segmentDurationSec,
431
- // Source-inherited output rate (integer, capped); descriptors that
432
- // use time-based keyframes just apply it as the frame rate.
433
- fps: output.outputFps,
434
- // Software-only; hardware descriptors ignore it.
435
- preset: output.softwarePreset ?? undefined,
436
- // HDR→SDR tone map (software path only; gated on filter availability).
437
- tonemap: output.applyTonemap === true,
438
- // On the source's grid the cuts are not evenly spaced, so no frame
439
- // count can describe them: the encoder is told the times outright,
440
- // the same ones the muxer will cut at.
441
- forcedKeyframeTimes: cutTimes,
442
- // The output's own rate control and level. Read off the output, whose
443
- // key names them: two limits are two outputs, and nothing moves a
444
- // limit under an output that already exists.
445
- rateControl: rateControl ?? null
446
- })
447
- : ["-c:v", "copy"];
448
- const audioCodecArgs = transcodeAudio
449
- ? ["-c:a", "aac", "-ac", "2", "-b:a", `${AUDIO_TRANSCODE_KBPS}k`]
450
- : ["-c:a", "copy"];
451
-
452
- const args = ["-hide_banner", "-nostats", "-loglevel", "error", "-progress", "pipe:1"];
453
- // Hardware decode/encode setup (e.g. VAAPI device) must precede -i, and
454
- // only applies when we actually re-encode the video track.
455
- if (transcodeVideo && Array.isArray(videoEncoder.inputArgs)) {
456
- args.push(...videoEncoder.inputArgs);
457
- }
458
- // Seek position in SOURCE time. On the keyframe grid `startSeconds` is a
459
- // real keyframe's offset from zero, so the container's own start time goes
460
- // back on to reach it; on the uniform grid it is a plain offset. This
461
- // follows the GRID, not whether the video is re-encoded — a variant cut on
462
- // the source's keyframes has to seek to them like the copy it accompanies.
463
- const inputStartSeconds = inputIndex === safeIndex ? startSeconds :
464
- publishedStartTime(timeline, inputIndex, segmentDurationSec);
465
- const seekSeconds = timeline.cutGrid === "keyframe"
466
- ? inputStartSeconds + sourceStartTime
467
- : inputStartSeconds;
468
- // Two-step seek when we have a real keyframe map: jump to a KNOWN-valid
469
- // keyframe (coarse, before -i — safe because WE sourced it from ffprobe,
470
- // not the container's own on-the-fly seek/index) and trim the short
471
- // residual (bounded by the keyframe interval) precisely AFTER -i, which is
472
- // always frame-accurate regardless of -accurate_seek.
473
- //
474
- // Root cause this works around: `-accurate_seek -ss X` before -i trusts the
475
- // CONTAINER's own seek to land near X. For some containers (observed: AVI
476
- // with VBR MP3 audio) that on-the-fly seek can point at a position with no
477
- // valid frame boundary at all — ffmpeg fails outright ("Seek failed" /
478
- // "Header missing"), not just imprecisely, and repeatedly so since every
479
- // retry re-tries the SAME bad container-computed position. A keyframe we
480
- // read directly from the packet list is a position ffmpeg has already
481
- // proven it can decode.
482
- //
483
- // The keyframe is CARRIED from the table that named this boundary, not looked
484
- // up by value. A boundary is stored on the player's clock, rounded, and
485
- // `seekSeconds` above puts the container's start time back on to reach the
486
- // file's clock — a lossy round trip. A keyframe at 26.234 s in a container
487
- // starting at 0.083 s comes back as 26.233999999999998, and "the keyframe at
488
- // or before that" is then the PREVIOUS one, 8.717 s earlier: two parts in a
489
- // quadrillion, one whole keyframe interval. That interval became a trim, the
490
- // trim moved every cut of the run backwards by another interval, and the
491
- // run's files were numbered from #36 while carrying film 17.4 s before what
492
- // the playlist says #36 holds (field 2026-09-05: the picture covered the
493
- // playhead, the sound had a 17.4 s hole across it, and the viewer waited two
494
- // minutes for a buffer that could never fill).
495
- //
496
- // The search stays for a grid restored without its source clock, which is the
497
- // only case that has nothing to carry.
498
- const carriedKeyframe = timeline.cutGrid === "keyframe" && typeof timeline.sourceStartOf === "function"
499
- ? timeline.sourceStartOf(inputIndex)
500
- : null;
501
- const snappedKeyframe = Number.isFinite(carriedKeyframe)
502
- ? carriedKeyframe
503
- : (Array.isArray(keyframes?.times) && keyframes.times.length > 0
504
- ? nearestKeyframeAtOrBefore(keyframes.times, seekSeconds)
505
- : null);
506
- // A second input, and it exists for exactly one case: a browser that takes
507
- // its audio muxed into the picture, watching a release whose soundtrack is a
508
- // file of its own. An audio RENDITION reads that file as its only input and
509
- // has none of this — which is why the ordinary path, and every browser that
510
- // understands rendition groups, still runs on a single input.
511
- const audioInputUrl =
512
- typeof audioInputUrlGiven === "string" && audioInputUrlGiven.length > 0
513
- ? audioInputUrlGiven
514
- : "";
515
- // Where the picture's own start sits on the soundtrack file's timeline. Both
516
- // files begin at their own container start time, and those need not be the
517
- // same number; the difference is what keeps the two aligned.
518
- const audioTimelineShift = audioInputUrl
519
- ? audioFileStartTime - sourceStartTime
520
- : 0;
521
- /**
522
- * Add the second input, if there is one, with its own seek.
523
- *
524
- * Called between the first `-i` and any OUTPUT option, because ffmpeg reads
525
- * these positionally: an option written after the last `-i` applies to the
526
- * output, and the residual seek below is exactly such an option. Getting the
527
- * order wrong would silently turn the audio file's seek into a trim of the
528
- * finished stream.
529
- *
530
- * @param {number} inputSeekSeconds - Where to start, on the PICTURE's
531
- * timeline. Translated to the soundtrack file's own here.
532
- */
533
- const pushAudioInput = (inputSeekSeconds) => {
534
- if (!audioInputUrl) {
535
- return;
536
- }
537
- // `-itsoffset` states the soundtrack's timestamps on the picture's
538
- // timeline, so everything after this point — `-copyts`, the output offset,
539
- // the cut list — goes on treating the two as one timeline, unchanged.
540
- //
541
- // ONLY on the branch that keeps the source's own timestamps. Without
542
- // `-copyts` ffmpeg rebases each input from its own seek point, and both
543
- // inputs are seeked to the same instant just below — so the two are
544
- // already aligned and adding the offset would pull them apart by exactly
545
- // the amount it exists to remove.
546
- if (audioTimelineShift !== 0 && keyframeGrid) {
547
- args.push("-itsoffset", ffmpegSeconds(-audioTimelineShift));
548
- }
549
- const audioSeek = Math.max(0, inputSeekSeconds + audioTimelineShift);
550
- if (audioSeek > 0) {
551
- // No keyframe to snap to and none needed: every audio frame is a sync
552
- // point, so the seek can be accurate outright.
553
- args.push("-accurate_seek", "-ss", ffmpegSeconds(audioSeek));
554
- }
555
- args.push("-i", audioInputUrl);
556
- };
557
-
558
- if (snappedKeyframe !== null) {
559
- const residualSeconds = Math.max(0, seekSeconds - snappedKeyframe);
560
- if (snappedKeyframe > 0) {
561
- args.push("-ss", ffmpegSeconds(snappedKeyframe + seekLandingOffsetFor({ audioOnly, transcodeVideo, keyframes }, snappedKeyframe)));
562
- }
563
- args.push("-i", inputUrl);
564
- // The coarse landing, not the exact target: the residual below is discarded
565
- // from the OUTPUT and so takes the same slice off every stream. Seeking the
566
- // soundtrack to the exact target as well would take that slice twice and
567
- // leave the sound running ahead of the picture by it.
568
- pushAudioInput(snappedKeyframe);
569
- // An output-side trim, and ONLY where the output is labelled from zero.
570
- //
571
- // Beside `-copyts` it does the opposite of what it says. Measured
572
- // 2026-09-06 on a file with a 5 s keyframe interval: a run landed at 15 s
573
- // and asked to trim to the cut at 20 s produced its first file starting at
574
- // 10 s, and a run asked to trim to 17 s produced cuts at 13.129, 18.129,
575
- // 23.129 — the whole grid moved back by the trim itself. The muxer's cut
576
- // times are absolute under `-copyts` while the trim is not, so every cut of
577
- // the run inherits the difference and the numbering, fixed at spawn, is
578
- // wrong by however many cuts that is.
579
- //
580
- // On the keyframe grid the run begins AT a cut, so there is nothing to
581
- // trim: the carried keyframe above makes this exactly zero rather than
582
- // nearly zero.
583
- if (residualSeconds > 0 && !keyframeGrid) {
584
- args.push("-ss", ffmpegSeconds(residualSeconds));
585
- }
586
- } else {
587
- if (seekSeconds > 0) {
588
- // No keyframe map (probe failed/timed out) — fall back to the previous
589
- // behaviour: trust the container's own accurate seek.
590
- args.push("-accurate_seek", "-ss", ffmpegSeconds(seekSeconds));
591
- }
592
- args.push("-i", inputUrl);
593
- pushAudioInput(seekSeconds);
594
- }
595
- // Which timeline the output is labelled on. An audio rendition has no
596
- // picture of its own to follow, so it follows the grid it was given — the
597
- // same one the video it plays with is on. Deciding by `transcodeVideo`, as
598
- // everything else here does, would put the audio of a re-encoded stream on
599
- // the copy branch: `-copyts` and a shift by the container's start time,
600
- // against a picture labelled from zero. The two would be offset by
601
- // `sourceStartTime` for the whole file.
602
- if (!keyframeGrid) {
603
- // Branch A (re-encode): fixed GOP makes keyframes land exactly on the
604
- // segment grid; relabel output onto the original timeline so segment N
605
- // carries PTS = N × segmentDuration.
606
- if (startSeconds > 0) {
607
- args.push("-output_ts_offset", ffmpegSeconds(startSeconds));
608
- }
609
- } else {
610
- // Branch B (video copied — only audio is transcoded): we cannot insert
611
- // keyframes, so segments are cut at the source's own keyframes (the
612
- // playlist boundaries were built from those keyframes). Keep the source's
613
- // real timestamps (`-copyts`) so copied frames stay continuous across
614
- // boundaries/seeks, and shift by -startTime so the output timeline is
615
- // 0-based (a non-zero container start otherwise puts a hole at the very
616
- // beginning and desyncs audio/video). Audio is transcoded on this timeline.
617
- args.push("-copyts");
618
- if (sourceStartTime !== 0) {
619
- args.push("-output_ts_offset", ffmpegSeconds(-sourceStartTime));
620
- }
621
- }
622
- // Where this run STOPS. Until now a run had a start and no end — neither
623
- // `-to` nor `-t` appeared anywhere in the arguments this proxy builds — so
624
- // every stop was a kill from outside, and two runs on one output could only
625
- // be kept apart by giving each its own directory. With an end they cannot
626
- // reach each other's numbers at all, and a run that finishes its stretch
627
- // exits by itself instead of having to be noticed and killed.
628
- //
629
- // WHICH argument states it is a property of the branch, and it is measured
630
- // rather than reasoned (2026-09-04, `research/encoder-layer-2026-09-04.md`
631
- // §11): `-t` is a duration on the output's own clock, and `-to` a point on
632
- // the input's. The copy branch runs with `-copyts`, where the input's clock
633
- // IS the source's, so `-to` takes the absolute time; the re-encode branch
634
- // has no `-copyts` and takes the duration. Swapping them is not a near
635
- // miss — on the copy branch `-t` produced one segment where five were
636
- // wanted, because the time it names is already past when the run starts.
637
- const runEnd = Number.isInteger(endIndex) ? endIndex : -1;
638
- const publishedGrid = publishedGridFor(timeline);
639
- if (runEnd >= safeIndex && Array.isArray(publishedGrid) && publishedGrid[runEnd + 1] > 0) {
640
- const endsAt = publishedGrid[runEnd + 1];
641
- if (transcodeVideo) {
642
- args.push("-t", ffmpegSeconds(Math.max(0.1, endsAt - publishedGrid[safeIndex])));
643
- } else {
644
- args.push("-to", ffmpegSeconds(endsAt));
645
- }
646
- }
647
- if (audioOnly === true) {
648
- // An audio RENDITION: one track, no picture. Published as its own
649
- // `#EXT-X-MEDIA` and shared by every video variant, so the track is
650
- // encoded once for the file instead of once per rung, and changing it is
651
- // the player switching rendition rather than this proxy rebuilding the
652
- // session. Cut on the same grid as the video it accompanies, which is
653
- // what lets the two be played together.
654
- // `0:` because a rendition's only input IS the file its track lives in —
655
- // the picture's own file, or the one beside it that carries this dub.
656
- args.push("-vn", "-map", `0:a:${audioSourceTrackIndex}?`, ...audioCodecArgs);
657
- } else if (servesAudioSeparately) {
658
- // The other half of the same arrangement: the picture alone, because its
659
- // audio is published as a rendition and would otherwise play twice.
660
- args.push("-an", "-map", "0:v:0?", ...videoCodecArgs);
661
- } else {
662
- args.push(
663
- "-map",
664
- "0:v:0?",
665
- "-map",
666
- // The audio track the viewer chose: input 1 when their choice is a
667
- // soundtrack shipped as its own file, input 0 when it is one of the
668
- // picture's own. Type-relative within that input, which is what
669
- // `audioSourceTrackIndex` holds — the number the browser sent is flat
670
- // across both files and was resolved when the session was made.
671
- `${audioInputUrl ? 1 : 0}:a:${audioSourceTrackIndex}?`,
672
- ...videoCodecArgs,
673
- ...audioCodecArgs
674
- );
675
- }
676
-
677
- // Where the cuts come from. On the copy path they are the source's own
678
- // keyframes, and until now they were only ever GUESSED: ffmpeg got a target
679
- // duration and chose its own cut points, while the playlist was built from
680
- // the container index — two independent calculations with nothing tying
681
- // them together but the hope that they agree. They do not. The index is a
682
- // navigation table and is not obliged to list every keyframe; for a field
683
- // file it held 1902 while ffmpeg found roughly twice as many and cut twice
684
- // as often. Segment #876 then meant 1:26:50 to the player and about minute
685
- // 58 to ffmpeg, which is why a seek landed nowhere near where it was aimed
686
- // and the reported duration drifted.
687
- //
688
- // So stop guessing and say it: the `segment` muxer takes the list of times
689
- // outright. Passing the very boundaries the playlist was built from makes
690
- // the two agree by construction. Only cut points already known to be real
691
- // keyframes are sent, so ffmpeg never has to move one forward.
692
- //
693
- // The list is built above, before the encoder args, because a re-encoded
694
- // variant of a copied stream needs the same times twice over: once as the
695
- // cuts, once as the keyframes to force at them.
696
- if (cutTimes && cutTimes.length > 0) {
697
- args.push(
698
- "-f",
699
- "segment",
700
- // Times are measured from the START OF THIS RUN, not from the start of
701
- // the file — verified: starting at 12 s and asking for a cut at 18 s
702
- // produced one at 29.4 s. `segmentCutTimesFrom` rebases them.
703
- "-segment_times",
704
- cutTimes.join(","),
705
- // A cut lands on the first keyframe at or after its time, so a boundary
706
- // recorded a hair late would skip to the next one and double the
707
- // segment. The tolerance absorbs that rounding.
708
- "-segment_time_delta",
709
- String(SEGMENT_CUT_TIME_DELTA_SECONDS),
710
- "-segment_start_number",
711
- String(inputIndex),
712
- // THE ENCODER SAYS WHEN A PIECE IS FINISHED, on a channel of its own.
713
- //
714
- // Measured on the addon host 2026-09-05: a name appears in this list when
715
- // the file is CLOSED, not when it is created — at the third sample
716
- // `seg-000.mp4` was on disk and absent from the list, and it appeared at
717
- // the fourth, in the same moment `seg-001.mp4` came into being. So a name
718
- // here is the writer's own statement that the piece is whole.
719
- //
720
- // Without it, a finished file is indistinguishable from one still being
721
- // written, and the only proof available was the existence of the NEXT
722
- // one — which never comes for the last piece of every run.
723
- "-segment_list",
724
- "pipe:3",
725
- "-segment_list_type",
726
- "csv",
727
- "-segment_list_flags",
728
- "+live",
729
- ...explicitTimes,
730
- // UNDER A WORKING NAME, not the one it is served as. A piece under its
731
- // served name is complete by construction then, whoever else is writing
732
- // into the same directory — and the name arrives on the channel above the
733
- // instant ffmpeg closes it, which is what turns it into the served one.
734
- //
735
- // The other branch cannot do this: the HLS muxer writes through a
736
- // temporary name of its own (`+temp_file`) and renames each file itself,
737
- // including the one it was writing when it ended. It is left for the runs
738
- // that have no cut list at all.
739
- //
740
- // TAGGED WITH THE STRETCH IT WAS GIVEN, which names the run without any
741
- // counter to keep: intervals never overlap, so two live runs of one output
742
- // begin at different numbers by construction. That is what makes clearing
743
- // up after a dead run a well-formed question — its unfinished pieces are
744
- // the ones carrying its own tag — where before it was answered by taking
745
- // the highest SERVED name inside its stretch and judging the bytes.
746
- segmentFormat.makingFileNameTemplate(String(safeIndex))
747
- );
748
- } else {
749
- args.push(
750
- "-f",
751
- "hls",
752
- "-hls_time",
753
- String(segmentDurationSec),
754
- "-hls_list_size",
755
- "0",
756
- "-hls_flags",
757
- "independent_segments+temp_file",
758
- // Container selection + segment naming, from the active format module.
759
- ...segmentFormat.muxerArgs(),
760
- "-start_number",
761
- String(safeIndex),
762
- // ffmpeg writes its own playlist here; we ignore it and serve the
763
- // synthetic VOD playlist instead (see getFileStream).
764
- PLAYLIST_FILE_NAME
765
- );
766
- }
767
- return { args, safeIndex, inputIndex, startSeconds, cutTimes };
768
-
769
- }
@@ -335,8 +335,10 @@ export function readPresentationRanges(raw) {
335
335
  }
336
336
  }
337
337
  const edit = edits.get(id);
338
- tracks.push({ id, kind: kinds.get(id), timescale: edit.timescale, ranges,
338
+ const productionFrame = samples.reduce((maximum, sample) => sample.duration > maximum ? sample.duration : maximum, 0n);
339
+ tracks.push({ id, kind: kinds.get(id), timescale: edit.timescale, productionFrame, ranges,
339
340
  firstSampleStart: samples[0].start, positionErrorTicks: edit.positionErrorTicks ?? 0n });
341
+
340
342
  }
341
343
  return { tracks };
342
344
  }