@torrent-tv/proxy 2.87.3 → 2.87.5

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,848 +1,856 @@
1
- /**
2
- * @file Playback planner service.
3
- *
4
- * Determines whether a torrent file can be served directly or requires
5
- * HLS audio transcoding by probing the stream codecs with ffmpeg.
6
- * Results are cached indefinitely (keyed by source + file index).
7
- */
8
-
9
- import { spawn } from "node:child_process";
10
- import { logger } from "../../utils/logger.js";
11
- import { Container } from "./container/Container.js";
12
- import { buildAudioInventory } from "./audio-inventory.js";
13
- import {
14
- parseFfmpegDurationSeconds,
15
- parseFfmpegStartTimeSeconds,
16
- parseFfmpegBitDepth,
17
- parseFfmpegBitrateKbps,
18
- parseFfmpegVideoFps,
19
- parseFfmpegHdr
20
- } from "./ffmpeg-banner.js";
21
-
22
- /** Audio codecs that browsers can decode natively without transcoding. */
23
- const DIRECT_AUDIO_CODECS = new Set(["aac", "mp3", "opus", "vorbis", "flac"]);
24
-
25
- // Once the plan probe succeeds, warm the START of the file body so the
26
- // transcode session's ffmpeg reads hit downloaded data instead of paying
27
- // piece latency at encode time (the edge prefetch only covers head+tail for
28
- // the codec probe). ~16 MB ≈ the first segments of typical media.
29
- const BODY_PREFETCH_BYTES = 16 * 1024 * 1024;
30
-
31
- /**
32
- * How long the plan waits for a file's own header before offering its
33
- * soundtrack without what that header would have said.
34
- *
35
- * Not a measurement, and nothing is derived from it: it is the point past which
36
- * holding the viewer costs more than the language and flags being waited for —
37
- * which the folder name supplies anyway, from the torrent's file list, at no
38
- * cost. The reading itself carries on in the worker and is kept there.
39
- */
40
- const SIDECAR_HEADER_WAIT_MS = 3_000;
41
-
42
- /** Subtitle codecs that can be converted to WebVTT (text-based). */
43
- const TEXT_SUBTITLE_CODECS = new Set(["subrip", "srt", "ass", "ssa", "webvtt", "vtt", "mov_text", "text"]);
44
-
45
- /**
46
- * Parse every stream from the ffmpeg `-i` banner: type, codec, language tag,
47
- * default disposition and (when present) the stream's `title` metadata line.
48
- *
49
- * @param {string} ffmpegOutput
50
- * @returns {Array<{ streamIndex: number, type: string, codec: string, language: string, title: string, isDefault: boolean }>}
51
- */
52
- /**
53
- * The bitrate a stream line states for that stream, in kbit/s, or null.
54
- *
55
- * @param {string} line
56
- * @returns {number | null}
57
- */
58
- function kbpsFromStreamLine(line) {
59
- const match = line.match(/,\s*(\d+)\s*kb\/s/);
60
- const kbps = match ? Number(match[1]) : Number.NaN;
61
- return Number.isFinite(kbps) && kbps > 0 ? kbps : null;
62
- }
63
-
64
- function parseStreams(ffmpegOutput) {
65
- // Only the Input section: ffmpeg prints Stream lines for the null OUTPUT
66
- // too (wrapped_avframe / pcm_s16le), which would duplicate every track.
67
- const inputSection = ffmpegOutput.split(/^(?:Output #|Stream mapping:)/m)[0] ?? ffmpegOutput;
68
- const lines = inputSection.split(/\r?\n/);
69
- const streams = [];
70
- let current = null;
71
- for (const line of lines) {
72
- const streamMatch = line.match(
73
- /^\s*Stream #0:(\d+)(?:\[[^\]]*\])?(?:\(([A-Za-z0-9]{2,3})\))?: (Audio|Video|Subtitle): ([A-Za-z0-9_]+)/
74
- );
75
- if (streamMatch) {
76
- current = {
77
- streamIndex: Number(streamMatch[1]),
78
- type: streamMatch[3].toLowerCase(),
79
- codec: String(streamMatch[4]).toLowerCase(),
80
- language: (streamMatch[2] ?? "").toLowerCase(),
81
- title: "",
82
- isDefault: /\(default\)/.test(line),
83
- // What the stream line states for THIS stream, e.g. "…, 128 kb/s". A
84
- // Matroska stream usually states none here and carries its rate as a
85
- // statistics tag instead (`BPS`, read below). Never the file's total.
86
- bitrateKbps: kbpsFromStreamLine(line)
87
- };
88
- streams.push(current);
89
- continue;
90
- }
91
- if (current) {
92
- const bpsMatch = line.match(/^\s+BPS(?:-[A-Za-z]+)?\s*:\s*(\d+)\s*$/);
93
- if (bpsMatch && current.bitrateKbps === null) {
94
- current.bitrateKbps = Math.round(Number(bpsMatch[1]) / 1000);
95
- continue;
96
- }
97
- const titleMatch = line.match(/^\s+title\s*:\s*(.+)$/);
98
- if (titleMatch && current.title.length === 0) {
99
- current.title = titleMatch[1].trim();
100
- continue;
101
- }
102
- // A new top-level section (non-indented line) ends the stream's block.
103
- if (!/^\s/.test(line)) {
104
- current = null;
105
- }
106
- }
107
- }
108
- return streams;
109
- }
110
-
111
- /**
112
- * Parse audio and video codec names from ffmpeg stderr output.
113
- *
114
- * @param {string} ffmpegOutput
115
- * @returns {{ audioCodec: string, videoCodec: string }}
116
- */
117
- export function parseStreamCodecs(ffmpegOutput) {
118
- const audioMatch = ffmpegOutput.match(/Audio:\s*([A-Za-z0-9_]+)/i);
119
- const videoMatch = ffmpegOutput.match(/Video:\s*([A-Za-z0-9_]+)/i);
120
- // Coded resolution from the video Stream line ("Video: h264 …, 1280x720, …").
121
- // The first WxH is the coded size (any trailing "[SAR …]" is ignored).
122
- const videoLineMatch = ffmpegOutput.match(/Video:[^\n]*/i);
123
- let videoWidth = 0;
124
- let videoHeight = 0;
125
- if (videoLineMatch) {
126
- const dim = videoLineMatch[0].match(/\b(\d{2,5})x(\d{2,5})\b/);
127
- if (dim) {
128
- videoWidth = Number(dim[1]);
129
- videoHeight = Number(dim[2]);
130
- }
131
- }
132
- const containerMatch = ffmpegOutput.match(/Input #0,\s*([^,]+(?:,[^,]+)*?),\s*from/i);
133
- const durationMatch = ffmpegOutput.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/i);
134
- let durationSeconds = 0;
135
- if (durationMatch) {
136
- const value =
137
- Number(durationMatch[1]) * 3600 + Number(durationMatch[2]) * 60 + Number(durationMatch[3]);
138
- durationSeconds = Number.isFinite(value) ? value : 0;
139
- }
140
- const streams = parseStreams(ffmpegOutput);
141
- const audioTracks = streams
142
- .filter((s) => s.type === "audio")
143
- .map((s, i) => ({
144
- // Type-relative index — what ffmpeg's `-map 0:a:N` selects.
145
- index: i,
146
- streamIndex: s.streamIndex,
147
- codec: s.codec,
148
- language: s.language,
149
- title: s.title,
150
- isDefault: s.isDefault,
151
- bitrateKbps: s.bitrateKbps
152
- }));
153
- const subtitleTracks = streams
154
- .filter((s) => s.type === "subtitle")
155
- .map((s, i) => ({
156
- // Type-relative index — what ffmpeg's `-map 0:s:N` selects.
157
- index: i,
158
- streamIndex: s.streamIndex,
159
- codec: s.codec,
160
- language: s.language,
161
- title: s.title,
162
- isDefault: s.isDefault,
163
- // Image-based subtitles (PGS/VobSub) cannot become WebVTT.
164
- textBased: TEXT_SUBTITLE_CODECS.has(s.codec)
165
- }));
166
- return {
167
- audioCodec: audioMatch ? String(audioMatch[1]).toLowerCase() : "",
168
- videoCodec: videoMatch ? String(videoMatch[1]).toLowerCase() : "",
169
- container: containerMatch ? String(containerMatch[1]).trim().toLowerCase() : "",
170
- durationSeconds,
171
- videoWidth,
172
- videoHeight,
173
- audioTracks,
174
- subtitleTracks
175
- };
176
- }
177
-
178
- /**
179
- * Run a brief ffmpeg probe to identify the audio and video codecs of a stream.
180
- * Times out after `timeoutMs` and returns empty strings on failure.
181
- *
182
- * @param {object} options
183
- * @param {string} options.ffmpegBin
184
- * @param {string} options.inputUrl
185
- * @param {string} [options.userAgent=""]
186
- * @param {number} [options.timeoutMs=8000]
187
- * @returns {Promise<{ audioCodec: string, videoCodec: string, container: string, durationSeconds: number, videoWidth: number, videoHeight: number, audioTracks: object[], subtitleTracks: object[], stderr: string }>}
188
- * Parsed banner fields plus the raw `stderr`, so the caller can derive the
189
- * full media info (fps/startTime/HDR) without a second ffmpeg scan.
190
- */
191
- function probeStreamCodecs({ ffmpegBin, inputUrl, userAgent = "", timeoutMs = 8_000 }) {
192
- return new Promise((resolve) => {
193
- const args = ["-hide_banner", "-loglevel", "info"];
194
- if (typeof userAgent === "string" && userAgent.trim().length > 0) {
195
- args.push("-user_agent", userAgent.trim());
196
- }
197
- // Decode a tiny slice of all streams (no per-stream -map, so video-only
198
- // files probe correctly too). The ffmpeg banner that precedes decoding
199
- // gives us audio/video codecs, the container format and the duration in a
200
- // single pass.
201
- args.push("-i", inputUrl, "-t", "0.1", "-f", "null", "-");
202
-
203
- const ffmpeg = spawn(ffmpegBin, args, {
204
- stdio: ["ignore", "ignore", "pipe"],
205
- windowsHide: true
206
- });
207
- let stderr = "";
208
- let settled = false;
209
-
210
- const finish = (codecs) => {
211
- if (settled) {
212
- return;
213
- }
214
- settled = true;
215
- resolve(codecs);
216
- };
217
-
218
- const timeoutId = setTimeout(() => {
219
- if (!ffmpeg.killed) {
220
- ffmpeg.kill("SIGTERM");
221
- }
222
- finish({ ...parseStreamCodecs(stderr), stderr });
223
- }, timeoutMs);
224
-
225
- ffmpeg.stderr.on("data", (chunk) => {
226
- stderr += String(chunk);
227
- });
228
-
229
- ffmpeg.on("error", () => {
230
- clearTimeout(timeoutId);
231
- finish({ audioCodec: "", videoCodec: "", stderr: "" });
232
- });
233
-
234
- ffmpeg.on("exit", () => {
235
- clearTimeout(timeoutId);
236
- finish({ ...parseStreamCodecs(stderr), stderr });
237
- });
238
- });
239
- }
240
-
241
- /**
242
- * Resolve after a given number of milliseconds.
243
- *
244
- * @param {number} ms
245
- * @returns {Promise<void>}
246
- */
247
- function delay(ms) {
248
- return new Promise((resolve) => {
249
- setTimeout(resolve, ms);
250
- });
251
- }
252
-
253
- /**
254
- * Build the direct stream URL for a source file served by the local proxy.
255
- *
256
- * @param {string} localBaseUrl - e.g. "http://127.0.0.1:9090"
257
- * @param {string} sourceKey
258
- * @param {number} fileIndex
259
- * @returns {string}
260
- */
261
- function buildDirectUrl(localBaseUrl, sourceKey, fileIndex) {
262
- const directUrl = new URL("/stream", `${localBaseUrl}/`);
263
- directUrl.searchParams.set("sourceKey", sourceKey);
264
- directUrl.searchParams.set("fileIndex", String(fileIndex));
265
- return directUrl.toString();
266
- }
267
-
268
- /**
269
- * @typedef {Object} PlaybackPlan
270
- * @property {"direct" | "hls"} mode
271
- * @property {string} directUrl
272
- * @property {string} reason - Human-readable explanation of the chosen mode.
273
- * @property {string} audioCodec
274
- * @property {string} videoCodec
275
- * @property {string} container - Demuxer/container name(s) reported by ffmpeg.
276
- * @property {number} durationSeconds - Total media duration in seconds (0 if unknown).
277
- * @property {number} videoWidth - Source coded width (0 if unknown).
278
- * @property {number} videoHeight - Source coded height (0 if unknown).
279
- */
280
-
281
- /**
282
- * @typedef {Object} PlaybackPlannerOptions
283
- * @property {string} ffmpegBin
284
- * @property {boolean} transcodeAudioEnabled
285
- * @property {string} localBaseUrl
286
- * @property {ReturnType<import("../../store/source-registry.js").createSourceRegistry>} sourceRegistry
287
- * @property {import("../torrent/torrent-pool.js").TorrentPool} torrentPool
288
- */
289
-
290
- /**
291
- * Create a playback planner that decides the optimal streaming mode for
292
- * a torrent file. Plans are cached per (sourceKey, fileIndex) pair.
293
- *
294
- * @param {PlaybackPlannerOptions} options
295
- * @returns {{ getPlan: (params: { sourceKey: string, fileIndex: number, userAgent?: string }) => Promise<PlaybackPlan> }}
296
- */
297
- export function createPlaybackPlanner({
298
- ffmpegBin,
299
- transcodeAudioEnabled,
300
- localBaseUrl,
301
- sourceRegistry,
302
- torrentPool,
303
- // Optional. Reports what this host typically takes to produce a session's
304
- // first segment. The browser needs it for the gap between "the file is
305
- // downloaded" and "a segment exists": until now it assumed the pipeline
306
- // merely keeps up with realtime, and showed 15 s where 3.8 s were left.
307
- expectedFirstSegmentMs,
308
- expectedSessionCreateMs,
309
- // What the torrent holds beside this picture — its dubs, its subtitle files,
310
- // its contact sheets — grouped by whoever knows what a torrent contains. This
311
- // layer answers about ONE file and must not read a torrent's file list.
312
- sidecarsFromTorrent = null,
313
- // What a file DECLARES about its own tracks, read from its header. Handed in
314
- // rather than asked of the torrent pool: this layer used to call
315
- // `torrentPool.getDeclaredAudioTracks` and friends, which is the media layer
316
- // asking the torrent layer to parse a container on its behalf — the parse
317
- // happened in the torrent thread and came back over the channel. It happens
318
- // on this thread now, and what is passed here is the ordinary container read.
319
- declaredTracksOf = null,
320
- // Optional. Called once the file's edges are downloaded, so the keyframe
321
- // index — which reads the same tail of the file — is fetched alongside the
322
- // codec probe instead of after it. It goes straight to `KeyframeTables`,
323
- // which owns that table: it used to be routed through the session manager,
324
- // which held a second copy of it and a second reader for it.
325
- warmKeyframeIndex,
326
- // Optional. The heights this host could actually serve this source at, for
327
- // both playback branches, so the quality menu is right from the moment the
328
- // file is opened rather than from the moment an encoder exists.
329
- predictOfferedHeights
330
- }) {
331
- /** @type {Map<string, PlaybackPlan>} */
332
- const cache = new Map();
333
- /**
334
- * Full media info parsed from the SAME probe that produced the plan, cached
335
- * under the same key so a transcode session can reuse it instead of running
336
- * a second ffmpeg scan. Only set when the plan is cached (codecs detected).
337
- * @type {Map<string, { durationSeconds: number | null, width: number | null, height: number | null, fps: number | null, startTime: number, isHdr: boolean }>}
338
- */
339
- const mediaInfoCache = new Map();
340
-
341
- /**
342
- * Attach what this host currently measures itself taking to create a session
343
- * and to produce a first segment.
344
- *
345
- * Read at RESPONSE time, deliberately. Both are medians of sessions that have
346
- * already finished on this host, so at the moment a plan is BUILT the very
347
- * first file opened after a restart has none and gets `null` — and the plan
348
- * is then cached, so that file kept answering `null` for the life of the
349
- * process however many sessions ran afterwards. Measured 2026-08-05: a fresh
350
- * 2.9.103 answered `null` for both, then produced the session in 6 ms and the
351
- * first segment in 21 479 ms. The figures existed; the plan could not carry
352
- * them, and the browser's estimate fell back to its own guess in exactly the
353
- * cold-start case the feature was built for.
354
- *
355
- * @param {PlaybackPlan} plan
356
- * @returns {PlaybackPlan}
357
- */
358
- /**
359
- * The probe's subtitle tracks, with `FlagDefault` read from the container
360
- * instead of inferred from ffmpeg's banner.
361
- *
362
- * Best-effort by construction: a container that cannot be read this way, or a
363
- * reading that does not line up with the probe, leaves the tracks as they
364
- * were with `declaresDefault: false` — which the browser reads as "the file
365
- * has no opinion", and then nothing is shown unasked.
366
- *
367
- * @param {object} torrent
368
- * @param {number} fileIndex
369
- * @param {object[]} subtitleTracks
370
- * @returns {Promise<object[]>}
371
- */
372
- /**
373
- * The files beside this picture that belong to it, in three groups.
374
- *
375
- * HANDED IN, because what a torrent contains is the torrent layer's to say
376
- * and this is the media layer. It works the grouping out once and keeps it;
377
- * it used to be worked out here on every call, and again on the warm-up's own
378
- * path over the same list, so one opened film paired the same files several
379
- * times and neither side could be sure of the other's answer.
380
- *
381
- * Absent, a file has no companions — which is what a proxy with no torrent
382
- * behind it should answer, rather than failing.
383
- *
384
- * @param {object} torrent
385
- * @param {number} fileIndex
386
- * @returns {{ audio: object[], subtitles: object[], images: object[] }}
387
- */
388
- function sidecarsOf(torrent, fileIndex) {
389
- return sidecarsFromTorrent?.(torrent ?? {}, fileIndex) ?? { audio: [], subtitles: [], images: [] };
390
- }
391
-
392
- async function withContainerDefaults(sourceKey, torrent, fileIndex, subtitleTracks) {
393
- if (subtitleTracks.length === 0 || typeof declaredTracksOf !== "function") {
394
- return subtitleTracks.map((track) => ({ ...track, declaresDefault: false }));
395
- }
396
- let declared = [];
397
- try {
398
- declared = (await declaredTracksOf({ sourceKey, fileIndex })).filter((track) => track?.type === "subtitle");
399
- } catch (error) {
400
- logger.info(`subtitle defaults: the container could not be read (${error?.message ?? error})`);
401
- }
402
- const merged = Container.mergeSubtitleFlags(subtitleTracks, declared);
403
- logger.info(
404
- merged.aligned
405
- ? "subtitle defaults: the container wrote FlagDefault on " +
406
- `${merged.tracks.filter((track) => track.declaresDefault).length} of ${merged.tracks.length} ` +
407
- `subtitle tracks, marking ${merged.tracks.filter((track) => track.declaresDefault && track.isDefault).length}`
408
- : `subtitle defaults: using the probe's own flags — ${merged.reason}`
409
- );
410
- return merged.tracks;
411
- }
412
-
413
- /**
414
- * Every soundtrack this file can be watched with, as one numbered list: its
415
- * own tracks and the ones shipped as separate files beside it.
416
- *
417
- * Built here, in the plan, because the plan is what the viewer's menu is drawn
418
- * from — so the offer is complete the moment a file is opened, with nothing
419
- * arriving late and nothing measured while the viewer waits. It is also what
420
- * the master playlist's rendition group is built from, so the number in the
421
- * menu and the number in the `a/<n>/` address are the same number by
422
- * construction rather than by agreement.
423
- *
424
- * @param {string} sourceKey
425
- * @param {object} torrent
426
- * @param {number} fileIndex
427
- * @param {object[]} bannerAudioTracks - The probe's own audio streams.
428
- * @returns {Promise<import("./audio-inventory.js").AudioInventoryEntry[]>}
429
- */
430
- async function buildInventory(sourceKey, torrent, fileIndex, bannerAudioTracks) {
431
- const banner = Array.isArray(bannerAudioTracks) ? bannerAudioTracks : [];
432
- /**
433
- * Read a file's declared audio tracks, or give up quickly.
434
- *
435
- * The plan is on the path to the first frame, and reading a sidecar's header
436
- * waits on the swarm: that file has usually had nothing downloaded when this
437
- * runs, and a header that never arrives would hold the plan — and the
438
- * viewer — for the whole of the read's own patience. What a timeout costs is
439
- * small and deliberate: the track is still offered, still numbered and still
440
- * playable, only without the language and flags its own header would have
441
- * given. The language the viewer actually sees is read from the FOLDER the
442
- * release put it in, which is in the torrent's file list and needs no bytes
443
- * at all.
444
- *
445
- * @param {number} wantedFileIndex
446
- * @param {string} label
447
- * @returns {Promise<object[]>}
448
- */
449
- const declaredAudioOf = async (wantedFileIndex, label) => {
450
- if (typeof declaredTracksOf !== "function") {
451
- return [];
452
- }
453
- let timer = null;
454
- try {
455
- return await Promise.race([
456
- declaredTracksOf({ sourceKey, fileIndex: wantedFileIndex }).then((tracks) => tracks
457
- .filter((track) => track?.type === "audio")
458
- .sort((left, right) => (left.declaredIndex ?? 0) - (right.declaredIndex ?? 0))),
459
- new Promise((resolve) => {
460
- timer = setTimeout(() => resolve(null), SIDECAR_HEADER_WAIT_MS);
461
- timer.unref?.();
462
- })
463
- ]).then((tracks) => {
464
- if (tracks === null) {
465
- logger.info(
466
- `audio tracks: "${label}" did not answer within ` +
467
- `${SIDECAR_HEADER_WAIT_MS / 1000}s — offered without what its header would say`
468
- );
469
- return [];
470
- }
471
- return Array.isArray(tracks) ? tracks : [];
472
- });
473
- } catch (error) {
474
- logger.info(`audio tracks: "${label}" could not be read (${error?.message ?? error})`);
475
- return [];
476
- } finally {
477
- if (timer !== null) {
478
- clearTimeout(timer);
479
- }
480
- }
481
- };
482
- // The picture's own tracks: ffmpeg numbers them, the container declares what
483
- // they are. Both readings, lined up and checked — see `audio-inventory.js`.
484
- let embedded = banner.map((track) => ({ ...track, declaresDefault: false }));
485
- if (banner.length > 0) {
486
- // The picture's head is already downloaded — the codec probe just read it
487
- // — so this is a parse and not a wait, but it is bounded like the rest.
488
- const declared = await declaredAudioOf(fileIndex, "the picture");
489
- const merged = Container.mergeAudioFlags(banner, declared);
490
- embedded = merged.tracks;
491
- logger.info(
492
- merged.aligned
493
- ? `audio tracks: the container describes all ${merged.tracks.length}` +
494
- `${merged.tracks.some((track) => track.isCommentary) ? ", one of them commentary" : ""}` +
495
- `${merged.tracks.some((track) => track.isVisualImpaired) ? ", one of them described" : ""}`
496
- : `audio tracks: using the probe's own fields — ${merged.reason}`
497
- );
498
- }
499
-
500
- const sidecarFiles = sidecarsOf(torrent, fileIndex);
501
- // All of them at once. They are separate files with separate headers, and
502
- // read one after another the waits add up on the path to the first frame.
503
- const sidecars = await Promise.all(
504
- sidecarFiles.audio.map(async (file) => ({
505
- file,
506
- // A bare elementary stream — `.ac3`, `.dts`, `.mp3` — has no table to
507
- // read, so nothing is asked of the swarm for it at all.
508
- tracks: file.declaresTracks ? await declaredAudioOf(file.fileIndex, file.name) : []
509
- }))
510
- );
511
- const inventory = buildAudioInventory({ embedded, videoFileIndex: fileIndex, sidecars });
512
- if (sidecars.length > 0) {
513
- logger.info(
514
- `audio tracks: ${sidecars.length} file(s) beside the picture carry sound — ` +
515
- inventory
516
- .filter((entry) => entry.kind === "sidecar")
517
- .map((entry) =>
518
- `a:${entry.index}=${entry.folders.join("/") || "."}/${entry.fileName}` +
519
- `#${entry.sourceTrackIndex}${entry.codec ? `(${entry.codec})` : ""}`
520
- )
521
- .join(" ")
522
- );
523
- }
524
- return inventory;
525
- }
526
-
527
- function withHostTimings(plan) {
528
- const withOffer = {
529
- ...plan,
530
- expectedFirstSegmentMs: expectedFirstSegmentMs?.() ?? null,
531
- expectedSessionCreateMs: expectedSessionCreateMs?.() ?? null,
532
- // Answered here for the same reason as the two above: a plan is cached for
533
- // the life of the process, and what this host will serve a file at is not.
534
- // It starts as a prediction from the startup benchmarks and is replaced by
535
- // what an encoder running on this very source turns out to cost — frozen
536
- // into the cache, every later open of the file would hand the browser the
537
- // first guess again and undo that. This is the 2.9.106 defect exactly.
538
- offeredHeights: plan.mediaInfoForOffer
539
- ? (predictOfferedHeights?.(plan.mediaInfoForOffer) ?? null)
540
- : null,
541
- // The description the rest of the pool answers by arithmetic. Carried
542
- // on every plan, not only on a refusal here: the output opened next can
543
- // still be refused for want of a place on this machine (roadmap item 97,
544
- // step 14), and the page then asks the pool the same question before
545
- // anything plays — which it can only do with this in hand.
546
- mediaInfoForOffer: plan.mediaInfoForOffer
547
- };
548
- // Refused rather than served badly. Both lists empty means this machine
549
- // cannot sustain this file at ANY height — not even by copying the picture,
550
- // which costs no encoder at all — so a session made here would produce a
551
- // slideshow and take the swarm and the processor from whoever is already
552
- // watching. Field 2026-08-28: five sessions on one file put every rung at
553
- // 0.04x of realtime and the viewer watched one before the process was
554
- // killed. The viewer is told why, which is a different thing from a spinner
555
- // that never ends.
556
- const offer = withOffer.offeredHeights;
557
- if (offer && offer.copy.length === 0 && offer.transcode.length === 0) {
558
- withOffer.cannotServe =
559
- "This proxy cannot keep up with this file at any quality right now.";
560
- // The description travels with the plan (above). It is what lets the
561
- // browser ask the rest of the pool the same question without anybody
562
- // else adding the torrent, fetching a byte or running ffmpeg — the
563
- // expensive half of finding out what this file IS has been paid here,
564
- // once. Everyone else answers by arithmetic against their own startup
565
- // benchmarks.
566
- }
567
- return withOffer;
568
- }
569
-
570
- return {
571
- /**
572
- * Media info the planner already probed for this file, or `null`. Lets the
573
- * HLS session manager skip its own duplicate `probeInputMediaInfo` scan.
574
- *
575
- * @param {{ sourceKey: string, fileIndex: number }} params
576
- * @returns {{ durationSeconds: number | null, width: number | null, height: number | null, fps: number | null, startTime: number, isHdr: boolean } | null}
577
- */
578
- /**
579
- * The audio tracks this file was probed to have, or an empty list. The
580
- * master playlist publishes one rendition per track, and the inventory is
581
- * already here — probing again for it would be a second scan of a file the
582
- * proxy is in the middle of serving.
583
- *
584
- * @param {{ sourceKey: string, fileIndex: number }} params
585
- * @returns {object[]}
586
- */
587
- getCachedAudioTracks({ sourceKey, fileIndex }) {
588
- const plan = cache.get(`${sourceKey}:${fileIndex}`);
589
- return Array.isArray(plan?.audioTracks) ? plan.audioTracks : [];
590
- },
591
-
592
- getCachedMediaInfo({ sourceKey, fileIndex }) {
593
- return mediaInfoCache.get(`${sourceKey}:${fileIndex}`) ?? null;
594
- },
595
-
596
- /**
597
- * Return the playback plan for the given source file.
598
- * Throws with `error.code === "SOURCE_NOT_FOUND"` or `"FILE_NOT_FOUND"`
599
- * when the source or file cannot be located.
600
- *
601
- * When the file header has not downloaded yet (cold torrent, peers still
602
- * connecting) the codec probe cannot succeed. Rather than block the HTTP
603
- * response until it can, the planner prioritises the header, probes for at
604
- * most `maxWaitMs`, and if still undetectable returns a plan flagged
605
- * `pending: true` (NOT cached). The caller polls again — each call keeps the
606
- * header prioritised and downloading — until a real plan comes back. This
607
- * avoids a single long request racing the transport's request timeout.
608
- *
609
- * @param {object} params
610
- * @param {string} params.sourceKey
611
- * @param {number} params.fileIndex
612
- * @param {string} [params.userAgent=""]
613
- * @param {number} [params.maxWaitMs=60000] - Max time to wait for the header within ONE call.
614
- * @returns {Promise<PlaybackPlan & { pending?: boolean }>}
615
- */
616
- async getPlan({ sourceKey, fileIndex, userAgent = "", maxWaitMs = 60_000 }) {
617
- const cacheKey = `${sourceKey}:${fileIndex}`;
618
- const cached = cache.get(cacheKey);
619
- if (cached) {
620
- return withHostTimings(cached);
621
- }
622
- // Where the time before playback goes. `cold-start` already breaks down
623
- // everything from the transcode-session request onwards, but the plan
624
- // runs BEFORE that and was a single opaque wait: a field session spent
625
- // 5.7 s here on a torrent already in the store, with the codec probe
626
- // cached, and nothing said which part of it was slow.
627
- const planEntryMs = Date.now();
628
- let torrentReadyMs = 0;
629
- let edgesReadyMs = 0;
630
-
631
- const sourceRecord = sourceRegistry.get(sourceKey);
632
- if (!sourceRecord) {
633
- const error = new Error("Source key was not found.");
634
- error.code = "SOURCE_NOT_FOUND";
635
- throw error;
636
- }
637
-
638
- const torrent = await torrentPool.getTorrent(sourceRecord.sourceType, sourceRecord.source);
639
- torrentReadyMs = Date.now() - planEntryMs;
640
- const file = torrent.files[fileIndex];
641
- if (!file) {
642
- const error = new Error("File index was not found in torrent.");
643
- error.code = "FILE_NOT_FOUND";
644
- throw error;
645
- }
646
-
647
- const directUrl = buildDirectUrl(localBaseUrl, sourceKey, fileIndex);
648
- if (!transcodeAudioEnabled) {
649
- const plan = {
650
- mode: "direct",
651
- directUrl,
652
- reason: "transcode-disabled",
653
- audioCodec: "",
654
- videoCodec: "",
655
- container: "",
656
- durationSeconds: 0,
657
- videoWidth: 0,
658
- videoHeight: 0,
659
- audioTracks: [],
660
- subtitleTracks: []
661
- };
662
- cache.set(cacheKey, plan);
663
- return withHostTimings(plan);
664
- }
665
-
666
- // Pre-fetch file edges (head + tail), then probe — retrying while the
667
- // file header is still downloading. In a multi-file torrent the pieces
668
- // for a given file arrive unevenly, so the first probe can return empty
669
- // codecs. A transient empty probe must NOT be cached: otherwise the wrong
670
- // plan (file treated as directly playable) sticks permanently for this
671
- // file, and an unsupported codec like xvid gets copied → black video.
672
- // Awaited in the literal sense: this answer cannot be given until the
673
- // file has said what is in it, and a person is watching a loading screen
674
- // for as long as that takes.
675
- await torrentPool.prefetchFileEdges(torrent, fileIndex, { awaited: true });
676
- edgesReadyMs = Date.now() - planEntryMs;
677
- // The keyframe index reads the tail of the file, which the probe has just
678
- // waited for as well. Started here it overlaps the probe instead of
679
- // following the whole plan — worth 311-430 ms of the time before the
680
- // first segment. Fire and forget: a session that finds the table
681
- // unanswered joins this very read rather than starting a second one.
682
- warmKeyframeIndex?.({ sourceKey, fileIndex, logName: file.name });
683
- let probe = await probeStreamCodecs({ ffmpegBin, inputUrl: directUrl, userAgent });
684
- const probeDeadline = Date.now() + Math.max(0, maxWaitMs);
685
- let attempt = 0;
686
- while (
687
- probe.audioCodec.length === 0 &&
688
- probe.videoCodec.length === 0 &&
689
- Date.now() < probeDeadline
690
- ) {
691
- attempt += 1;
692
- await delay(Math.min(3_000, 500 + attempt * 250));
693
- await torrentPool.prefetchFileEdges(torrent, fileIndex, { awaited: true });
694
- probe = await probeStreamCodecs({ ffmpegBin, inputUrl: directUrl, userAgent });
695
- }
696
- const { audioCodec, videoCodec, container, durationSeconds, videoWidth, videoHeight, audioTracks, subtitleTracks } = probe;
697
- const codecsDetected = audioCodec.length > 0 || videoCodec.length > 0;
698
- logger.info(
699
- `plan ${sourceKey.slice(0, 8)}:${fileIndex} torrent-ready=${torrentReadyMs}ms ` +
700
- `file-edges=${edgesReadyMs - torrentReadyMs}ms probe=${Date.now() - planEntryMs - edgesReadyMs}ms ` +
701
- `total=${Date.now() - planEntryMs}ms attempts=${attempt + 1} ` +
702
- `${codecsDetected ? `${videoCodec || "-"}/${audioCodec || "-"}` : "codecs NOT detected (will be polled again)"}`
703
- );
704
-
705
- // The picture's own facts come from two readings and only one was ever
706
- // used: every figure the encode is planned from came from ffmpeg's
707
- // banner, while the `VideoTrack` the container declares was read and used
708
- // for nothing but a line in the log.
709
- let declaredVideo = null;
710
- if (typeof declaredTracksOf === "function") {
711
- try {
712
- // One, because ffmpeg's `0:v:0` is what everything downstream is built
713
- // on and a second video stream is a cover image far more often than a
714
- // second film.
715
- declaredVideo = (await declaredTracksOf({ sourceKey, fileIndex }))
716
- .filter((track) => track?.type === "video")
717
- .sort((left, right) => (left.declaredIndex ?? 0) - (right.declaredIndex ?? 0))[0] ?? null;
718
- } catch (error) {
719
- logger.info(`video track: could not be read (${error?.message ?? error})`);
720
- }
721
- }
722
- // `mode` is advisory only (audio-codec based). The browser makes the
723
- // authoritative decision independently per stream via canPlayType /
724
- // mediaCapabilities, transcoding only what it cannot play.
725
- const requiresTranscode = audioCodec.length > 0 && !DIRECT_AUDIO_CODECS.has(audioCodec);
726
- // The two readings of the picture, lined up. Which one answers is decided
727
- // per field by what each IS — see `Container.mergeVideoFacts`.
728
- const videoFacts = Container.mergeVideoFacts(
729
- {
730
- width: videoWidth,
731
- height: videoHeight,
732
- fps: parseFfmpegVideoFps(probe.stderr),
733
- isHdr: parseFfmpegHdr(probe.stderr),
734
- bitDepth: parseFfmpegBitDepth(probe.stderr)
735
- },
736
- declaredVideo
737
- );
738
- if (videoFacts.disagreements.length > 0) {
739
- logger.info(
740
- `video track: the file and the probe disagree — ${videoFacts.disagreements.join("; ")}; ` +
741
- "the size and frame rate are the probe's, the bit depth and HDR the file's"
742
- );
743
- }
744
- const sidecars = sidecarsOf(torrent, fileIndex);
745
- const plan = {
746
- mode: requiresTranscode ? "hls" : "direct",
747
- directUrl,
748
- reason: requiresTranscode ? "audio-codec-transcode-required" : "audio-codec-supported",
749
- audioCodec,
750
- videoCodec,
751
- container,
752
- durationSeconds,
753
- // Source coded resolution — drives the browser's manual quality menu
754
- // (list of forced resolutions <= source). 0 when unknown.
755
- videoWidth: videoFacts.width ?? 0,
756
- videoHeight: videoFacts.height ?? 0,
757
- // Full track inventory for the browser's audio/subtitle menus. The audio
758
- // half spans the picture's own tracks AND the soundtracks shipped as
759
- // files beside it, under one numbering — see `buildInventory`.
760
- audioTracks: await buildInventory(sourceKey, torrent, fileIndex, audioTracks ?? []),
761
- subtitleTracks: await withContainerDefaults(sourceKey, torrent, fileIndex, subtitleTracks ?? []),
762
- // The files BESIDE this picture that belong to it, and what each one's
763
- // own path says about the track in it. Both answers are made here, by
764
- // one grammar, because the browser used to make them again: it paired
765
- // with a looser rule and read the names with a stricter one, and nothing
766
- // compared the two. Measured 2026-09-04 over 115 real torrents — 1249
767
- // video files, ten pairings differing — and the difference reached the
768
- // viewer as a subtitle track offered but never warmed.
769
- //
770
- // The soundtracks are NOT repeated here: they are already in
771
- // `audioTracks`, under the one flat numbering the browser addresses them
772
- // by. What this adds is the two groups that had no place in the plan at
773
- // all.
774
- sidecarSubtitles: sidecars.subtitles,
775
- sidecarImages: sidecars.images,
776
- // Both host timings are filled in by `withHostTimings` on the way out,
777
- // never here: read at build time they would be frozen into the cached
778
- // plan, which is the bug fixed in 2.9.106.
779
- expectedFirstSegmentMs: null,
780
- expectedSessionCreateMs: null,
781
- offeredHeights: null,
782
- // What the offer is computed FROM, kept on the cached plan so the offer
783
- // itself can be recomputed on every response. The figures are the
784
- // probe's own and never change for a file; the answer derived from them
785
- // does, as the host learns what this source costs. Stripped on the way
786
- // out — it is not part of the plan the browser is given.
787
- mediaInfoForOffer: {
788
- width: videoFacts.width,
789
- height: videoFacts.height,
790
- fps: videoFacts.fps,
791
- bitrateKbps: parseFfmpegBitrateKbps(probe.stderr),
792
- // Which family of the decode measurement prices this source. A video
793
- // that has to be re-encoded is one the browser could not play, so it
794
- // is usually NOT H.264, and H.264 constants are wrong for it.
795
- codec: videoCodec,
796
- bitDepth: videoFacts.bitDepth,
797
- // Which file this is, so the offer can be answered from what an
798
- // encoder has already learned about THIS source rather than from the
799
- // startup clips — the same correction a live session applies.
800
- sourceKey,
801
- fileIndex
802
- }
803
- };
804
- // Only cache a plan whose codecs were actually detected. An empty probe is
805
- // a "header not downloaded yet" signal, not a valid result — caching it
806
- // would permanently mis-plan the file. In that case flag the plan
807
- // `pending` so the caller polls again (the header keeps downloading,
808
- // prioritised by the prefetch above).
809
- if (codecsDetected) {
810
- cache.set(cacheKey, plan);
811
- // Cache the full media info from THIS probe's banner (same helpers the
812
- // session manager uses) so createSession can skip its own probe.
813
- mediaInfoCache.set(cacheKey, {
814
- // The codecs, because the session manager asks this cache which
815
- // tracks the output will carry — and they were never stored here. It
816
- // read `videoCodec`/`audioCodec` off an object that has only ever had
817
- // dimensions and duration, got `undefined` for both, and declared
818
- // `{video: false, audio: false}` for EVERY session since the check was
819
- // written. Measured 2026-08-11: `declared tracks video=false
820
- // audio=false`, which left the browser unable to tell "this file has
821
- // no video" from "the video was lost on the way", and left the init
822
- // guard expecting zero tracks and therefore accepting any header.
823
- videoCodec: plan.videoCodec,
824
- audioCodec: plan.audioCodec,
825
- durationSeconds: parseFfmpegDurationSeconds(probe.stderr),
826
- width: videoFacts.width,
827
- height: videoFacts.height,
828
- bitrateKbps: parseFfmpegBitrateKbps(probe.stderr),
829
- fps: videoFacts.fps,
830
- startTime: parseFfmpegStartTimeSeconds(probe.stderr),
831
- isHdr: videoFacts.isHdr,
832
- bitDepth: videoFacts.bitDepth
833
- });
834
- // Warm the file-body start for the transcode session that follows.
835
- // Fire-and-forget: never delays the plan response.
836
- void torrentPool
837
- .prefetchFileEdges(torrent, fileIndex, {
838
- headBytes: BODY_PREFETCH_BYTES,
839
- tailBytes: 0,
840
- timeoutMs: 60_000
841
- })
842
- .catch(() => {});
843
- return withHostTimings(plan);
844
- }
845
- return withHostTimings({ ...plan, pending: true });
846
- }
847
- };
848
- }
1
+ /**
2
+ * @file Playback planner service.
3
+ *
4
+ * Determines whether a torrent file can be served directly or requires
5
+ * HLS audio transcoding by probing the stream codecs with ffmpeg.
6
+ * Results are cached indefinitely (keyed by source + file index).
7
+ */
8
+
9
+ import { spawn } from "node:child_process";
10
+ import { logger } from "../../utils/logger.js";
11
+ import { Container } from "./container/Container.js";
12
+ import { buildAudioInventory } from "./audio-inventory.js";
13
+ import {
14
+ parseFfmpegDurationSeconds,
15
+ parseFfmpegStartTimeSeconds,
16
+ parseFfmpegBitDepth,
17
+ parseFfmpegBitrateKbps,
18
+ parseFfmpegVideoFps,
19
+ parseFfmpegHdr
20
+ } from "./ffmpeg-banner.js";
21
+
22
+ /** Audio codecs that browsers can decode natively without transcoding. */
23
+ const DIRECT_AUDIO_CODECS = new Set(["aac", "mp3", "opus", "vorbis", "flac"]);
24
+
25
+ // Once the plan probe succeeds, warm the START of the file body so the
26
+ // transcode session's ffmpeg reads hit downloaded data instead of paying
27
+ // piece latency at encode time (the edge prefetch only covers head+tail for
28
+ // the codec probe). ~16 MB ≈ the first segments of typical media.
29
+ const BODY_PREFETCH_BYTES = 16 * 1024 * 1024;
30
+
31
+ /**
32
+ * How long the plan waits for a file's own header before offering its
33
+ * soundtrack without what that header would have said.
34
+ *
35
+ * Not a measurement, and nothing is derived from it: it is the point past which
36
+ * holding the viewer costs more than the language and flags being waited for —
37
+ * which the folder name supplies anyway, from the torrent's file list, at no
38
+ * cost. The reading itself carries on in the worker and is kept there.
39
+ */
40
+ const SIDECAR_HEADER_WAIT_MS = 3_000;
41
+
42
+ /** Subtitle codecs that can be converted to WebVTT (text-based). */
43
+ const TEXT_SUBTITLE_CODECS = new Set(["subrip", "srt", "ass", "ssa", "webvtt", "vtt", "mov_text", "text"]);
44
+
45
+ /**
46
+ * Parse every stream from the ffmpeg `-i` banner: type, codec, language tag,
47
+ * default disposition and (when present) the stream's `title` metadata line.
48
+ *
49
+ * @param {string} ffmpegOutput
50
+ * @returns {Array<{ streamIndex: number, type: string, codec: string, language: string, title: string, isDefault: boolean }>}
51
+ */
52
+ /**
53
+ * The bitrate a stream line states for that stream, in kbit/s, or null.
54
+ *
55
+ * @param {string} line
56
+ * @returns {number | null}
57
+ */
58
+ function kbpsFromStreamLine(line) {
59
+ const match = line.match(/,\s*(\d+)\s*kb\/s/);
60
+ const kbps = match ? Number(match[1]) : Number.NaN;
61
+ return Number.isFinite(kbps) && kbps > 0 ? kbps : null;
62
+ }
63
+
64
+ function parseStreams(ffmpegOutput) {
65
+ // Only the Input section: ffmpeg prints Stream lines for the null OUTPUT
66
+ // too (wrapped_avframe / pcm_s16le), which would duplicate every track.
67
+ const inputSection = ffmpegOutput.split(/^(?:Output #|Stream mapping:)/m)[0] ?? ffmpegOutput;
68
+ const lines = inputSection.split(/\r?\n/);
69
+ const streams = [];
70
+ let current = null;
71
+ for (const line of lines) {
72
+ const streamMatch = line.match(
73
+ /^\s*Stream #0:(\d+)(?:\[[^\]]*\])?(?:\(([A-Za-z0-9]{2,3})\))?: (Audio|Video|Subtitle): ([A-Za-z0-9_]+)/
74
+ );
75
+ if (streamMatch) {
76
+ current = {
77
+ streamIndex: Number(streamMatch[1]),
78
+ type: streamMatch[3].toLowerCase(),
79
+ codec: String(streamMatch[4]).toLowerCase(),
80
+ language: (streamMatch[2] ?? "").toLowerCase(),
81
+ title: "",
82
+ isDefault: /\(default\)/.test(line),
83
+ // What the stream line states for THIS stream, e.g. "…, 128 kb/s". A
84
+ // Matroska stream usually states none here and carries its rate as a
85
+ // statistics tag instead (`BPS`, read below). Never the file's total.
86
+ bitrateKbps: kbpsFromStreamLine(line)
87
+ };
88
+ streams.push(current);
89
+ continue;
90
+ }
91
+ if (current) {
92
+ const bpsMatch = line.match(/^\s+BPS(?:-[A-Za-z]+)?\s*:\s*(\d+)\s*$/);
93
+ if (bpsMatch && current.bitrateKbps === null) {
94
+ current.bitrateKbps = Math.round(Number(bpsMatch[1]) / 1000);
95
+ continue;
96
+ }
97
+ const titleMatch = line.match(/^\s+title\s*:\s*(.+)$/);
98
+ if (titleMatch && current.title.length === 0) {
99
+ current.title = titleMatch[1].trim();
100
+ continue;
101
+ }
102
+ // A new top-level section (non-indented line) ends the stream's block.
103
+ if (!/^\s/.test(line)) {
104
+ current = null;
105
+ }
106
+ }
107
+ }
108
+ return streams;
109
+ }
110
+
111
+ /**
112
+ * Parse audio and video codec names from ffmpeg stderr output.
113
+ *
114
+ * @param {string} ffmpegOutput
115
+ * @returns {{ audioCodec: string, videoCodec: string }}
116
+ */
117
+ export function parseStreamCodecs(ffmpegOutput) {
118
+ const audioMatch = ffmpegOutput.match(/Audio:\s*([A-Za-z0-9_]+)/i);
119
+ const videoMatch = ffmpegOutput.match(/Video:\s*([A-Za-z0-9_]+)/i);
120
+ // Coded resolution from the video Stream line ("Video: h264 …, 1280x720, …").
121
+ // The first WxH is the coded size (any trailing "[SAR …]" is ignored).
122
+ const videoLineMatch = ffmpegOutput.match(/Video:[^\n]*/i);
123
+ let videoWidth = 0;
124
+ let videoHeight = 0;
125
+ if (videoLineMatch) {
126
+ const dim = videoLineMatch[0].match(/\b(\d{2,5})x(\d{2,5})\b/);
127
+ if (dim) {
128
+ videoWidth = Number(dim[1]);
129
+ videoHeight = Number(dim[2]);
130
+ }
131
+ }
132
+ const containerMatch = ffmpegOutput.match(/Input #0,\s*([^,]+(?:,[^,]+)*?),\s*from/i);
133
+ const durationMatch = ffmpegOutput.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/i);
134
+ let durationSeconds = 0;
135
+ if (durationMatch) {
136
+ const value =
137
+ Number(durationMatch[1]) * 3600 + Number(durationMatch[2]) * 60 + Number(durationMatch[3]);
138
+ durationSeconds = Number.isFinite(value) ? value : 0;
139
+ }
140
+ const streams = parseStreams(ffmpegOutput);
141
+ const audioTracks = streams
142
+ .filter((s) => s.type === "audio")
143
+ .map((s, i) => ({
144
+ // Type-relative index — what ffmpeg's `-map 0:a:N` selects.
145
+ index: i,
146
+ streamIndex: s.streamIndex,
147
+ codec: s.codec,
148
+ language: s.language,
149
+ title: s.title,
150
+ isDefault: s.isDefault,
151
+ bitrateKbps: s.bitrateKbps
152
+ }));
153
+ const subtitleTracks = streams
154
+ .filter((s) => s.type === "subtitle")
155
+ .map((s, i) => ({
156
+ // Type-relative index — what ffmpeg's `-map 0:s:N` selects.
157
+ index: i,
158
+ streamIndex: s.streamIndex,
159
+ codec: s.codec,
160
+ language: s.language,
161
+ title: s.title,
162
+ isDefault: s.isDefault,
163
+ // Image-based subtitles (PGS/VobSub) cannot become WebVTT.
164
+ textBased: TEXT_SUBTITLE_CODECS.has(s.codec)
165
+ }));
166
+ return {
167
+ audioCodec: audioMatch ? String(audioMatch[1]).toLowerCase() : "",
168
+ videoCodec: videoMatch ? String(videoMatch[1]).toLowerCase() : "",
169
+ container: containerMatch ? String(containerMatch[1]).trim().toLowerCase() : "",
170
+ durationSeconds,
171
+ videoWidth,
172
+ videoHeight,
173
+ audioTracks,
174
+ subtitleTracks
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Run a brief ffmpeg probe to identify the audio and video codecs of a stream.
180
+ * Times out after `timeoutMs` and returns empty strings on failure.
181
+ *
182
+ * @param {object} options
183
+ * @param {string} options.ffmpegBin
184
+ * @param {string} options.inputUrl
185
+ * @param {string} [options.userAgent=""]
186
+ * @param {number} [options.timeoutMs=8000]
187
+ * @returns {Promise<{ audioCodec: string, videoCodec: string, container: string, durationSeconds: number, videoWidth: number, videoHeight: number, audioTracks: object[], subtitleTracks: object[], stderr: string }>}
188
+ * Parsed banner fields plus the raw `stderr`, so the caller can derive the
189
+ * full media info (fps/startTime/HDR) without a second ffmpeg scan.
190
+ */
191
+ function probeStreamCodecs({ ffmpegBin, inputUrl, userAgent = "", timeoutMs = 8_000 }) {
192
+ return new Promise((resolve) => {
193
+ const args = ["-hide_banner", "-loglevel", "info"];
194
+ if (typeof userAgent === "string" && userAgent.trim().length > 0) {
195
+ args.push("-user_agent", userAgent.trim());
196
+ }
197
+ // Decode a tiny slice of all streams (no per-stream -map, so video-only
198
+ // files probe correctly too). The ffmpeg banner that precedes decoding
199
+ // gives us audio/video codecs, the container format and the duration in a
200
+ // single pass.
201
+ args.push("-i", inputUrl, "-t", "0.1", "-f", "null", "-");
202
+
203
+ const ffmpeg = spawn(ffmpegBin, args, {
204
+ stdio: ["ignore", "ignore", "pipe"],
205
+ windowsHide: true
206
+ });
207
+ let stderr = "";
208
+ let settled = false;
209
+
210
+ const finish = (codecs) => {
211
+ if (settled) {
212
+ return;
213
+ }
214
+ settled = true;
215
+ resolve(codecs);
216
+ };
217
+
218
+ const timeoutId = setTimeout(() => {
219
+ if (!ffmpeg.killed) {
220
+ ffmpeg.kill("SIGTERM");
221
+ }
222
+ finish({ ...parseStreamCodecs(stderr), stderr });
223
+ }, timeoutMs);
224
+
225
+ ffmpeg.stderr.on("data", (chunk) => {
226
+ stderr += String(chunk);
227
+ });
228
+
229
+ ffmpeg.on("error", () => {
230
+ clearTimeout(timeoutId);
231
+ finish({ audioCodec: "", videoCodec: "", stderr: "" });
232
+ });
233
+
234
+ ffmpeg.on("exit", () => {
235
+ clearTimeout(timeoutId);
236
+ finish({ ...parseStreamCodecs(stderr), stderr });
237
+ });
238
+ });
239
+ }
240
+
241
+ /**
242
+ * Resolve after a given number of milliseconds.
243
+ *
244
+ * @param {number} ms
245
+ * @returns {Promise<void>}
246
+ */
247
+ function delay(ms) {
248
+ return new Promise((resolve) => {
249
+ setTimeout(resolve, ms);
250
+ });
251
+ }
252
+
253
+ /**
254
+ * Build the direct stream URL for a source file served by the local proxy.
255
+ *
256
+ * @param {string} localBaseUrl - e.g. "http://127.0.0.1:9090"
257
+ * @param {string} sourceKey
258
+ * @param {number} fileIndex
259
+ * @returns {string}
260
+ */
261
+ function buildDirectUrl(localBaseUrl, sourceKey, fileIndex) {
262
+ const directUrl = new URL("/stream", `${localBaseUrl}/`);
263
+ directUrl.searchParams.set("sourceKey", sourceKey);
264
+ directUrl.searchParams.set("fileIndex", String(fileIndex));
265
+ return directUrl.toString();
266
+ }
267
+
268
+ /**
269
+ * @typedef {Object} PlaybackPlan
270
+ * @property {"direct" | "hls"} mode
271
+ * @property {string} directUrl
272
+ * @property {string} reason - Human-readable explanation of the chosen mode.
273
+ * @property {string} audioCodec
274
+ * @property {string} videoCodec
275
+ * @property {string} container - Demuxer/container name(s) reported by ffmpeg.
276
+ * @property {number} durationSeconds - Total media duration in seconds (0 if unknown).
277
+ * @property {number} videoWidth - Source coded width (0 if unknown).
278
+ * @property {number} videoHeight - Source coded height (0 if unknown).
279
+ */
280
+
281
+ /**
282
+ * @typedef {Object} PlaybackPlannerOptions
283
+ * @property {string} ffmpegBin
284
+ * @property {boolean} transcodeAudioEnabled
285
+ * @property {string} localBaseUrl
286
+ * @property {ReturnType<import("../../store/source-registry.js").createSourceRegistry>} sourceRegistry
287
+ * @property {import("../torrent/torrent-pool.js").TorrentPool} torrentPool
288
+ */
289
+
290
+ /**
291
+ * Create a playback planner that decides the optimal streaming mode for
292
+ * a torrent file. Plans are cached per (sourceKey, fileIndex) pair.
293
+ *
294
+ * @param {PlaybackPlannerOptions} options
295
+ * @returns {{ getPlan: (params: { sourceKey: string, fileIndex: number, userAgent?: string }) => Promise<PlaybackPlan> }}
296
+ */
297
+ export function createPlaybackPlanner({
298
+ ffmpegBin,
299
+ transcodeAudioEnabled,
300
+ localBaseUrl,
301
+ sourceRegistry,
302
+ torrentPool,
303
+ // Optional. Reports what this host typically takes to produce a session's
304
+ // first segment. The browser needs it for the gap between "the file is
305
+ // downloaded" and "a segment exists": until now it assumed the pipeline
306
+ // merely keeps up with realtime, and showed 15 s where 3.8 s were left.
307
+ expectedFirstSegmentMs,
308
+ expectedSessionCreateMs,
309
+ // What the torrent holds beside this picture — its dubs, its subtitle files,
310
+ // its contact sheets — grouped by whoever knows what a torrent contains. This
311
+ // layer answers about ONE file and must not read a torrent's file list.
312
+ sidecarsFromTorrent = null,
313
+ // What a file DECLARES about its own tracks, read from its header. Handed in
314
+ // rather than asked of the torrent pool: this layer used to call
315
+ // `torrentPool.getDeclaredAudioTracks` and friends, which is the media layer
316
+ // asking the torrent layer to parse a container on its behalf — the parse
317
+ // happened in the torrent thread and came back over the channel. It happens
318
+ // on this thread now, and what is passed here is the ordinary container read.
319
+ declaredTracksOf = null,
320
+ // Optional. Called once the file's edges are downloaded, so the keyframe
321
+ // index — which reads the same tail of the file — is fetched alongside the
322
+ // codec probe instead of after it. It goes straight to `KeyframeTables`,
323
+ // which owns that table: it used to be routed through the session manager,
324
+ // which held a second copy of it and a second reader for it.
325
+ warmKeyframeIndex,
326
+ // Optional. The heights this host could actually serve this source at, for
327
+ // both playback branches, so the quality menu is right from the moment the
328
+ // file is opened rather than from the moment an encoder exists.
329
+ predictOfferedHeights
330
+ }) {
331
+ /** @type {Map<string, PlaybackPlan>} */
332
+ const cache = new Map();
333
+ /**
334
+ * Full media info parsed from the SAME probe that produced the plan, cached
335
+ * under the same key so a transcode session can reuse it instead of running
336
+ * a second ffmpeg scan. Only set when the plan is cached (codecs detected).
337
+ * @type {Map<string, { durationSeconds: number | null, width: number | null, height: number | null, fps: number | null, startTime: number, isHdr: boolean }>}
338
+ */
339
+ const mediaInfoCache = new Map();
340
+
341
+ /**
342
+ * Attach what this host currently measures itself taking to create a session
343
+ * and to produce a first segment.
344
+ *
345
+ * Read at RESPONSE time, deliberately. Both are medians of sessions that have
346
+ * already finished on this host, so at the moment a plan is BUILT the very
347
+ * first file opened after a restart has none and gets `null` — and the plan
348
+ * is then cached, so that file kept answering `null` for the life of the
349
+ * process however many sessions ran afterwards. Measured 2026-08-05: a fresh
350
+ * 2.9.103 answered `null` for both, then produced the session in 6 ms and the
351
+ * first segment in 21 479 ms. The figures existed; the plan could not carry
352
+ * them, and the browser's estimate fell back to its own guess in exactly the
353
+ * cold-start case the feature was built for.
354
+ *
355
+ * @param {PlaybackPlan} plan
356
+ * @returns {PlaybackPlan}
357
+ */
358
+ /**
359
+ * The probe's subtitle tracks, with `FlagDefault` read from the container
360
+ * instead of inferred from ffmpeg's banner.
361
+ *
362
+ * Best-effort by construction: a container that cannot be read this way, or a
363
+ * reading that does not line up with the probe, leaves the tracks as they
364
+ * were with `declaresDefault: false` — which the browser reads as "the file
365
+ * has no opinion", and then nothing is shown unasked.
366
+ *
367
+ * @param {object} torrent
368
+ * @param {number} fileIndex
369
+ * @param {object[]} subtitleTracks
370
+ * @returns {Promise<object[]>}
371
+ */
372
+ /**
373
+ * The files beside this picture that belong to it, in three groups.
374
+ *
375
+ * HANDED IN, because what a torrent contains is the torrent layer's to say
376
+ * and this is the media layer. It works the grouping out once and keeps it;
377
+ * it used to be worked out here on every call, and again on the warm-up's own
378
+ * path over the same list, so one opened film paired the same files several
379
+ * times and neither side could be sure of the other's answer.
380
+ *
381
+ * Absent, a file has no companions — which is what a proxy with no torrent
382
+ * behind it should answer, rather than failing.
383
+ *
384
+ * @param {object} torrent
385
+ * @param {number} fileIndex
386
+ * @returns {{ audio: object[], subtitles: object[], images: object[] }}
387
+ */
388
+ function sidecarsOf(torrent, fileIndex) {
389
+ return sidecarsFromTorrent?.(torrent ?? {}, fileIndex) ?? { audio: [], subtitles: [], images: [] };
390
+ }
391
+
392
+ async function withContainerDefaults(sourceKey, torrent, fileIndex, subtitleTracks) {
393
+ if (subtitleTracks.length === 0 || typeof declaredTracksOf !== "function") {
394
+ return subtitleTracks.map((track) => ({ ...track, declaresDefault: false }));
395
+ }
396
+ let declared = [];
397
+ try {
398
+ declared = (await declaredTracksOf({ sourceKey, fileIndex })).filter((track) => track?.type === "subtitle");
399
+ } catch (error) {
400
+ logger.info(`subtitle defaults: the container could not be read (${error?.message ?? error})`);
401
+ }
402
+ const merged = Container.mergeSubtitleFlags(subtitleTracks, declared);
403
+ logger.info(
404
+ merged.aligned
405
+ ? "subtitle defaults: the container wrote FlagDefault on " +
406
+ `${merged.tracks.filter((track) => track.declaresDefault).length} of ${merged.tracks.length} ` +
407
+ `subtitle tracks, marking ${merged.tracks.filter((track) => track.declaresDefault && track.isDefault).length}`
408
+ : `subtitle defaults: using the probe's own flags — ${merged.reason}`
409
+ );
410
+ return merged.tracks;
411
+ }
412
+
413
+ /**
414
+ * Every soundtrack this file can be watched with, as one numbered list: its
415
+ * own tracks and the ones shipped as separate files beside it.
416
+ *
417
+ * Built here, in the plan, because the plan is what the viewer's menu is drawn
418
+ * from — so the offer is complete the moment a file is opened, with nothing
419
+ * arriving late and nothing measured while the viewer waits. It is also what
420
+ * the master playlist's rendition group is built from, so the number in the
421
+ * menu and the number in the `a/<n>/` address are the same number by
422
+ * construction rather than by agreement.
423
+ *
424
+ * @param {string} sourceKey
425
+ * @param {object} torrent
426
+ * @param {number} fileIndex
427
+ * @param {object[]} bannerAudioTracks - The probe's own audio streams.
428
+ * @returns {Promise<import("./audio-inventory.js").AudioInventoryEntry[]>}
429
+ */
430
+ async function buildInventory(sourceKey, torrent, fileIndex, bannerAudioTracks) {
431
+ const banner = Array.isArray(bannerAudioTracks) ? bannerAudioTracks : [];
432
+ /**
433
+ * Read a file's declared audio tracks, or give up quickly.
434
+ *
435
+ * The plan is on the path to the first frame, and reading a sidecar's header
436
+ * waits on the swarm: that file has usually had nothing downloaded when this
437
+ * runs, and a header that never arrives would hold the plan — and the
438
+ * viewer — for the whole of the read's own patience. What a timeout costs is
439
+ * small and deliberate: the track is still offered, still numbered and still
440
+ * playable, only without the language and flags its own header would have
441
+ * given. The language the viewer actually sees is read from the FOLDER the
442
+ * release put it in, which is in the torrent's file list and needs no bytes
443
+ * at all.
444
+ *
445
+ * @param {number} wantedFileIndex
446
+ * @param {string} label
447
+ * @returns {Promise<object[]>}
448
+ */
449
+ const declaredAudioOf = async (wantedFileIndex, label) => {
450
+ if (typeof declaredTracksOf !== "function") {
451
+ return [];
452
+ }
453
+ let timer = null;
454
+ try {
455
+ return await Promise.race([
456
+ declaredTracksOf({ sourceKey, fileIndex: wantedFileIndex }).then((tracks) => tracks
457
+ .filter((track) => track?.type === "audio")
458
+ .sort((left, right) => (left.declaredIndex ?? 0) - (right.declaredIndex ?? 0))),
459
+ new Promise((resolve) => {
460
+ timer = setTimeout(() => resolve(null), SIDECAR_HEADER_WAIT_MS);
461
+ timer.unref?.();
462
+ })
463
+ ]).then((tracks) => {
464
+ if (tracks === null) {
465
+ logger.info(
466
+ `audio tracks: "${label}" did not answer within ` +
467
+ `${SIDECAR_HEADER_WAIT_MS / 1000}s — offered without what its header would say`
468
+ );
469
+ return [];
470
+ }
471
+ return Array.isArray(tracks) ? tracks : [];
472
+ });
473
+ } catch (error) {
474
+ logger.info(`audio tracks: "${label}" could not be read (${error?.message ?? error})`);
475
+ return [];
476
+ } finally {
477
+ if (timer !== null) {
478
+ clearTimeout(timer);
479
+ }
480
+ }
481
+ };
482
+ // The picture's own tracks: ffmpeg numbers them, the container declares what
483
+ // they are. Both readings, lined up and checked — see `audio-inventory.js`.
484
+ let embedded = banner.map((track) => ({ ...track, declaresDefault: false }));
485
+ if (banner.length > 0) {
486
+ // The picture's head is already downloaded — the codec probe just read it
487
+ // — so this is a parse and not a wait, but it is bounded like the rest.
488
+ const declared = await declaredAudioOf(fileIndex, "the picture");
489
+ const merged = Container.mergeAudioFlags(banner, declared);
490
+ embedded = merged.tracks;
491
+ logger.info(
492
+ merged.aligned
493
+ ? `audio tracks: the container describes all ${merged.tracks.length}` +
494
+ `${merged.tracks.some((track) => track.isCommentary) ? ", one of them commentary" : ""}` +
495
+ `${merged.tracks.some((track) => track.isVisualImpaired) ? ", one of them described" : ""}`
496
+ : `audio tracks: using the probe's own fields — ${merged.reason}`
497
+ );
498
+ }
499
+
500
+ const sidecarFiles = sidecarsOf(torrent, fileIndex);
501
+ // All of them at once. They are separate files with separate headers, and
502
+ // read one after another the waits add up on the path to the first frame.
503
+ const sidecars = await Promise.all(
504
+ sidecarFiles.audio.map(async (file) => ({
505
+ file,
506
+ // A bare elementary stream — `.ac3`, `.dts`, `.mp3` — has no table to
507
+ // read, so nothing is asked of the swarm for it at all.
508
+ tracks: file.declaresTracks ? await declaredAudioOf(file.fileIndex, file.name) : []
509
+ }))
510
+ );
511
+ const inventory = buildAudioInventory({ embedded, videoFileIndex: fileIndex, sidecars });
512
+ if (sidecars.length > 0) {
513
+ logger.info(
514
+ `audio tracks: ${sidecars.length} file(s) beside the picture carry sound — ` +
515
+ inventory
516
+ .filter((entry) => entry.kind === "sidecar")
517
+ .map((entry) =>
518
+ `a:${entry.index}=${entry.folders.join("/") || "."}/${entry.fileName}` +
519
+ `#${entry.sourceTrackIndex}${entry.codec ? `(${entry.codec})` : ""}`
520
+ )
521
+ .join(" ")
522
+ );
523
+ }
524
+ return inventory;
525
+ }
526
+
527
+ function withHostTimings(plan) {
528
+ const withOffer = {
529
+ ...plan,
530
+ expectedFirstSegmentMs: expectedFirstSegmentMs?.() ?? null,
531
+ expectedSessionCreateMs: expectedSessionCreateMs?.() ?? null,
532
+ // Answered here for the same reason as the two above: a plan is cached for
533
+ // the life of the process, and what this host will serve a file at is not.
534
+ // It starts as a prediction from the startup benchmarks and is replaced by
535
+ // what an encoder running on this very source turns out to cost — frozen
536
+ // into the cache, every later open of the file would hand the browser the
537
+ // first guess again and undo that. This is the 2.9.106 defect exactly.
538
+ offeredHeights: plan.mediaInfoForOffer
539
+ ? (predictOfferedHeights?.(plan.mediaInfoForOffer) ?? null)
540
+ : null,
541
+ // The description the rest of the pool answers by arithmetic. Carried
542
+ // on every plan, not only on a refusal here: the output opened next can
543
+ // still be refused for want of a place on this machine (roadmap item 97,
544
+ // step 14), and the page then asks the pool the same question before
545
+ // anything plays — which it can only do with this in hand.
546
+ mediaInfoForOffer: plan.mediaInfoForOffer
547
+ };
548
+ // Refused rather than served badly. Both lists empty means this machine
549
+ // cannot sustain this file at ANY height — not even by copying the picture,
550
+ // which costs no encoder at all — so a session made here would produce a
551
+ // slideshow and take the swarm and the processor from whoever is already
552
+ // watching. Field 2026-08-28: five sessions on one file put every rung at
553
+ // 0.04x of realtime and the viewer watched one before the process was
554
+ // killed. The viewer is told why, which is a different thing from a spinner
555
+ // that never ends.
556
+ const offer = withOffer.offeredHeights;
557
+ if (offer && offer.copy.length === 0 && offer.transcode.length === 0) {
558
+ withOffer.cannotServe =
559
+ "This proxy cannot keep up with this file at any quality right now.";
560
+ // The description travels with the plan (above). It is what lets the
561
+ // browser ask the rest of the pool the same question without anybody
562
+ // else adding the torrent, fetching a byte or running ffmpeg — the
563
+ // expensive half of finding out what this file IS has been paid here,
564
+ // once. Everyone else answers by arithmetic against their own startup
565
+ // benchmarks.
566
+ }
567
+ return withOffer;
568
+ }
569
+
570
+ return {
571
+ /**
572
+ * Media info the planner already probed for this file, or `null`. Lets the
573
+ * HLS session manager skip its own duplicate `probeInputMediaInfo` scan.
574
+ *
575
+ * @param {{ sourceKey: string, fileIndex: number }} params
576
+ * @returns {{ durationSeconds: number | null, width: number | null, height: number | null, fps: number | null, startTime: number, isHdr: boolean } | null}
577
+ */
578
+ /**
579
+ * The audio tracks this file was probed to have, or an empty list. The
580
+ * master playlist publishes one rendition per track, and the inventory is
581
+ * already here — probing again for it would be a second scan of a file the
582
+ * proxy is in the middle of serving.
583
+ *
584
+ * @param {{ sourceKey: string, fileIndex: number }} params
585
+ * @returns {object[]}
586
+ */
587
+ getCachedAudioTracks({ sourceKey, fileIndex }) {
588
+ const plan = cache.get(`${sourceKey}:${fileIndex}`);
589
+ return Array.isArray(plan?.audioTracks) ? plan.audioTracks : [];
590
+ },
591
+
592
+ getCachedMediaInfo({ sourceKey, fileIndex }) {
593
+ return mediaInfoCache.get(`${sourceKey}:${fileIndex}`) ?? null;
594
+ },
595
+
596
+ /**
597
+ * Return the playback plan for the given source file.
598
+ * Throws with `error.code === "SOURCE_NOT_FOUND"` or `"FILE_NOT_FOUND"`
599
+ * when the source or file cannot be located.
600
+ *
601
+ * When the file header has not downloaded yet (cold torrent, peers still
602
+ * connecting) the codec probe cannot succeed. Rather than block the HTTP
603
+ * response until it can, the planner prioritises the header, probes for at
604
+ * most `maxWaitMs`, and if still undetectable returns a plan flagged
605
+ * `pending: true` (NOT cached). The caller polls again — each call keeps the
606
+ * header prioritised and downloading — until a real plan comes back. This
607
+ * avoids a single long request racing the transport's request timeout.
608
+ *
609
+ * @param {object} params
610
+ * @param {string} params.sourceKey
611
+ * @param {number} params.fileIndex
612
+ * @param {string} [params.userAgent=""]
613
+ * @param {number} [params.maxWaitMs=60000] - Max time to wait for the header within ONE call.
614
+ * @returns {Promise<PlaybackPlan & { pending?: boolean }>}
615
+ */
616
+ async getPlan({ sourceKey, fileIndex, userAgent = "", maxWaitMs = 60_000, background = false }) {
617
+ const cacheKey = `${sourceKey}:${fileIndex}`;
618
+ const cached = cache.get(cacheKey);
619
+ if (cached) {
620
+ return withHostTimings(cached);
621
+ }
622
+ // Where the time before playback goes. `cold-start` already breaks down
623
+ // everything from the transcode-session request onwards, but the plan
624
+ // runs BEFORE that and was a single opaque wait: a field session spent
625
+ // 5.7 s here on a torrent already in the store, with the codec probe
626
+ // cached, and nothing said which part of it was slow.
627
+ const planEntryMs = Date.now();
628
+ let torrentReadyMs = 0;
629
+ let edgesReadyMs = 0;
630
+
631
+ const sourceRecord = sourceRegistry.get(sourceKey);
632
+ if (!sourceRecord) {
633
+ const error = new Error("Source key was not found.");
634
+ error.code = "SOURCE_NOT_FOUND";
635
+ throw error;
636
+ }
637
+
638
+ const torrent = await torrentPool.getTorrent(sourceRecord.sourceType, sourceRecord.source);
639
+ torrentReadyMs = Date.now() - planEntryMs;
640
+ const file = torrent.files[fileIndex];
641
+ if (!file) {
642
+ const error = new Error("File index was not found in torrent.");
643
+ error.code = "FILE_NOT_FOUND";
644
+ throw error;
645
+ }
646
+
647
+ const directUrl = buildDirectUrl(localBaseUrl, sourceKey, fileIndex);
648
+ if (!transcodeAudioEnabled) {
649
+ const plan = {
650
+ mode: "direct",
651
+ directUrl,
652
+ reason: "transcode-disabled",
653
+ audioCodec: "",
654
+ videoCodec: "",
655
+ container: "",
656
+ durationSeconds: 0,
657
+ videoWidth: 0,
658
+ videoHeight: 0,
659
+ audioTracks: [],
660
+ subtitleTracks: []
661
+ };
662
+ cache.set(cacheKey, plan);
663
+ return withHostTimings(plan);
664
+ }
665
+
666
+ // Pre-fetch file edges (head + tail), then probe — retrying while the
667
+ // file header is still downloading. In a multi-file torrent the pieces
668
+ // for a given file arrive unevenly, so the first probe can return empty
669
+ // codecs. A transient empty probe must NOT be cached: otherwise the wrong
670
+ // plan (file treated as directly playable) sticks permanently for this
671
+ // file, and an unsupported codec like xvid gets copied → black video.
672
+ // Awaited in the literal sense: this answer cannot be given until the
673
+ // file has said what is in it, and a person is watching a loading screen
674
+ // for as long as that takes.
675
+ await torrentPool.prefetchFileEdges(torrent, fileIndex, {
676
+ awaited: !background,
677
+ timeoutMs: background ? 10_000 : 300_000
678
+ });
679
+ edgesReadyMs = Date.now() - planEntryMs;
680
+ // The keyframe index reads the tail of the file, which the probe has just
681
+ // waited for as well. Started here it overlaps the probe instead of
682
+ // following the whole plan — worth 311-430 ms of the time before the
683
+ // first segment. Fire and forget: a session that finds the table
684
+ // unanswered joins this very read rather than starting a second one.
685
+ if (!background) {
686
+ warmKeyframeIndex?.({ sourceKey, fileIndex, logName: file.name });
687
+ }
688
+ let probe = await probeStreamCodecs({ ffmpegBin, inputUrl: directUrl, userAgent });
689
+ const probeDeadline = Date.now() + Math.max(0, maxWaitMs);
690
+ let attempt = 0;
691
+ while (
692
+ probe.audioCodec.length === 0 &&
693
+ probe.videoCodec.length === 0 &&
694
+ Date.now() < probeDeadline
695
+ ) {
696
+ attempt += 1;
697
+ await delay(Math.min(3_000, 500 + attempt * 250));
698
+ await torrentPool.prefetchFileEdges(torrent, fileIndex, {
699
+ awaited: !background,
700
+ timeoutMs: background ? 10_000 : 300_000
701
+ });
702
+ probe = await probeStreamCodecs({ ffmpegBin, inputUrl: directUrl, userAgent });
703
+ }
704
+ const { audioCodec, videoCodec, container, durationSeconds, videoWidth, videoHeight, audioTracks, subtitleTracks } = probe;
705
+ const codecsDetected = audioCodec.length > 0 || videoCodec.length > 0;
706
+ logger.info(
707
+ `plan ${sourceKey.slice(0, 8)}:${fileIndex} torrent-ready=${torrentReadyMs}ms ` +
708
+ `file-edges=${edgesReadyMs - torrentReadyMs}ms probe=${Date.now() - planEntryMs - edgesReadyMs}ms ` +
709
+ `total=${Date.now() - planEntryMs}ms attempts=${attempt + 1} ` +
710
+ `${codecsDetected ? `${videoCodec || "-"}/${audioCodec || "-"}` : "codecs NOT detected (will be polled again)"}`
711
+ );
712
+
713
+ // The picture's own facts come from two readings and only one was ever
714
+ // used: every figure the encode is planned from came from ffmpeg's
715
+ // banner, while the `VideoTrack` the container declares was read and used
716
+ // for nothing but a line in the log.
717
+ let declaredVideo = null;
718
+ if (typeof declaredTracksOf === "function") {
719
+ try {
720
+ // One, because ffmpeg's `0:v:0` is what everything downstream is built
721
+ // on and a second video stream is a cover image far more often than a
722
+ // second film.
723
+ declaredVideo = (await declaredTracksOf({ sourceKey, fileIndex }))
724
+ .filter((track) => track?.type === "video")
725
+ .sort((left, right) => (left.declaredIndex ?? 0) - (right.declaredIndex ?? 0))[0] ?? null;
726
+ } catch (error) {
727
+ logger.info(`video track: could not be read (${error?.message ?? error})`);
728
+ }
729
+ }
730
+ // `mode` is advisory only (audio-codec based). The browser makes the
731
+ // authoritative decision independently per stream via canPlayType /
732
+ // mediaCapabilities, transcoding only what it cannot play.
733
+ const requiresTranscode = audioCodec.length > 0 && !DIRECT_AUDIO_CODECS.has(audioCodec);
734
+ // The two readings of the picture, lined up. Which one answers is decided
735
+ // per field by what each IS — see `Container.mergeVideoFacts`.
736
+ const videoFacts = Container.mergeVideoFacts(
737
+ {
738
+ width: videoWidth,
739
+ height: videoHeight,
740
+ fps: parseFfmpegVideoFps(probe.stderr),
741
+ isHdr: parseFfmpegHdr(probe.stderr),
742
+ bitDepth: parseFfmpegBitDepth(probe.stderr)
743
+ },
744
+ declaredVideo
745
+ );
746
+ if (videoFacts.disagreements.length > 0) {
747
+ logger.info(
748
+ `video track: the file and the probe disagree — ${videoFacts.disagreements.join("; ")}; ` +
749
+ "the size and frame rate are the probe's, the bit depth and HDR the file's"
750
+ );
751
+ }
752
+ const sidecars = sidecarsOf(torrent, fileIndex);
753
+ const plan = {
754
+ mode: requiresTranscode ? "hls" : "direct",
755
+ directUrl,
756
+ reason: requiresTranscode ? "audio-codec-transcode-required" : "audio-codec-supported",
757
+ audioCodec,
758
+ videoCodec,
759
+ container,
760
+ durationSeconds,
761
+ // Source coded resolution — drives the browser's manual quality menu
762
+ // (list of forced resolutions <= source). 0 when unknown.
763
+ videoWidth: videoFacts.width ?? 0,
764
+ videoHeight: videoFacts.height ?? 0,
765
+ // Full track inventory for the browser's audio/subtitle menus. The audio
766
+ // half spans the picture's own tracks AND the soundtracks shipped as
767
+ // files beside it, under one numbering — see `buildInventory`.
768
+ audioTracks: await buildInventory(sourceKey, torrent, fileIndex, audioTracks ?? []),
769
+ subtitleTracks: await withContainerDefaults(sourceKey, torrent, fileIndex, subtitleTracks ?? []),
770
+ // The files BESIDE this picture that belong to it, and what each one's
771
+ // own path says about the track in it. Both answers are made here, by
772
+ // one grammar, because the browser used to make them again: it paired
773
+ // with a looser rule and read the names with a stricter one, and nothing
774
+ // compared the two. Measured 2026-09-04 over 115 real torrents — 1249
775
+ // video files, ten pairings differing — and the difference reached the
776
+ // viewer as a subtitle track offered but never warmed.
777
+ //
778
+ // The soundtracks are NOT repeated here: they are already in
779
+ // `audioTracks`, under the one flat numbering the browser addresses them
780
+ // by. What this adds is the two groups that had no place in the plan at
781
+ // all.
782
+ sidecarSubtitles: sidecars.subtitles,
783
+ sidecarImages: sidecars.images,
784
+ // Both host timings are filled in by `withHostTimings` on the way out,
785
+ // never here: read at build time they would be frozen into the cached
786
+ // plan, which is the bug fixed in 2.9.106.
787
+ expectedFirstSegmentMs: null,
788
+ expectedSessionCreateMs: null,
789
+ offeredHeights: null,
790
+ // What the offer is computed FROM, kept on the cached plan so the offer
791
+ // itself can be recomputed on every response. The figures are the
792
+ // probe's own and never change for a file; the answer derived from them
793
+ // does, as the host learns what this source costs. Stripped on the way
794
+ // out — it is not part of the plan the browser is given.
795
+ mediaInfoForOffer: {
796
+ width: videoFacts.width,
797
+ height: videoFacts.height,
798
+ fps: videoFacts.fps,
799
+ bitrateKbps: parseFfmpegBitrateKbps(probe.stderr),
800
+ // Which family of the decode measurement prices this source. A video
801
+ // that has to be re-encoded is one the browser could not play, so it
802
+ // is usually NOT H.264, and H.264 constants are wrong for it.
803
+ codec: videoCodec,
804
+ bitDepth: videoFacts.bitDepth,
805
+ // Which file this is, so the offer can be answered from what an
806
+ // encoder has already learned about THIS source rather than from the
807
+ // startup clips — the same correction a live session applies.
808
+ sourceKey,
809
+ fileIndex
810
+ }
811
+ };
812
+ // Only cache a plan whose codecs were actually detected. An empty probe is
813
+ // a "header not downloaded yet" signal, not a valid result — caching it
814
+ // would permanently mis-plan the file. In that case flag the plan
815
+ // `pending` so the caller polls again (the header keeps downloading,
816
+ // prioritised by the prefetch above).
817
+ if (codecsDetected) {
818
+ cache.set(cacheKey, plan);
819
+ // Cache the full media info from THIS probe's banner (same helpers the
820
+ // session manager uses) so createSession can skip its own probe.
821
+ mediaInfoCache.set(cacheKey, {
822
+ // The codecs, because the session manager asks this cache which
823
+ // tracks the output will carry — and they were never stored here. It
824
+ // read `videoCodec`/`audioCodec` off an object that has only ever had
825
+ // dimensions and duration, got `undefined` for both, and declared
826
+ // `{video: false, audio: false}` for EVERY session since the check was
827
+ // written. Measured 2026-08-11: `declared tracks video=false
828
+ // audio=false`, which left the browser unable to tell "this file has
829
+ // no video" from "the video was lost on the way", and left the init
830
+ // guard expecting zero tracks and therefore accepting any header.
831
+ videoCodec: plan.videoCodec,
832
+ audioCodec: plan.audioCodec,
833
+ durationSeconds: parseFfmpegDurationSeconds(probe.stderr),
834
+ width: videoFacts.width,
835
+ height: videoFacts.height,
836
+ bitrateKbps: parseFfmpegBitrateKbps(probe.stderr),
837
+ fps: videoFacts.fps,
838
+ startTime: parseFfmpegStartTimeSeconds(probe.stderr),
839
+ isHdr: videoFacts.isHdr,
840
+ bitDepth: videoFacts.bitDepth
841
+ });
842
+ // Warm the file-body start for the transcode session that follows.
843
+ // Fire-and-forget: never delays the plan response.
844
+ void torrentPool
845
+ .prefetchFileEdges(torrent, fileIndex, {
846
+ headBytes: BODY_PREFETCH_BYTES,
847
+ tailBytes: 0,
848
+ timeoutMs: 60_000
849
+ })
850
+ .catch(() => {});
851
+ return withHostTimings(plan);
852
+ }
853
+ return withHostTimings({ ...plan, pending: true });
854
+ }
855
+ };
856
+ }