@torrent-tv/proxy 2.89.19 → 2.89.20

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.89.19",
3
+ "version": "2.89.20",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -105,3 +105,38 @@ export function computeCutGrid({ useKeyframeGrid, durationSeconds, segDur, keyfr
105
105
  // all, and an even one serves better than a table with a single entry.
106
106
  return boundaries.length >= 2 ? { boundaries, sourceTimes } : uniform();
107
107
  }
108
+
109
+ /**
110
+ * Whether an output is cut at times we hand the muxer, rather than at a
111
+ * duration the muxer chooses for itself.
112
+ *
113
+ * One answer for the command a run is given and for the serving of what it
114
+ * made, because both follow from it: given times mean the `segment` muxer,
115
+ * which writes each piece self-contained under a working name and says when it
116
+ * has closed it; without them the `hls` muxer names its pieces itself and
117
+ * writes one init file beside them.
118
+ *
119
+ * Every grid is handed over, the even one included. The `hls` muxer finishes
120
+ * the piece it has open whenever it ends — on our SIGTERM, and when its input
121
+ * stops — and gives that piece its served name, so a piece shorter than its
122
+ * span became servable with nothing to say so. Field 2026-09-27, on the
123
+ * `segment` muxer before its own guard existed: a run stopped while it wrote
124
+ * #111 left 0.37 s of a 4.2 s piece, the browser appended it, counted the
125
+ * fragment as loaded and went on to the next one, and the picture stood at
126
+ * 463.3 s while the player fetched 515.7 s and beyond.
127
+ *
128
+ * What is left without times is an output with no grid at all, which has no
129
+ * duration to cut.
130
+ *
131
+ * @param {{ segmentFormat?: { explicitTimesMuxerArgs?: () => string[] | null } | null,
132
+ * timeline?: { published?: number[], boundaries?: number[] } | null }} output
133
+ * @returns {boolean}
134
+ */
135
+ export function cutsAtGivenTimes(output) {
136
+ if (!output?.segmentFormat?.explicitTimesMuxerArgs?.()) {
137
+ return false;
138
+ }
139
+ const published = output.timeline?.published;
140
+ const grid = Array.isArray(published) && published.length > 0 ? published : output.timeline?.boundaries;
141
+ return Array.isArray(grid) && grid.length >= 2;
142
+ }
@@ -1,5 +1,6 @@
1
1
  export { OutputSpec, VideoOutput, AudioOutput, CutGrid, isOutputName } from "./OutputSpec.js";
2
2
  export { PLAYLIST_FILE_NAME } from "./playlists.js";
3
+ export { cutsAtGivenTimes } from "./cut-grid.js";
3
4
 
4
5
  // FFmpeg may close a segment this far before its requested cut. Both the
5
6
  // command and coverage validation use this existing muxer configuration.
@@ -17,7 +17,7 @@
17
17
 
18
18
  import { PLAYLIST_FILE_NAME } from "./output/playlists.js";
19
19
  import { AUDIO_TRANSCODE_KBPS } from "./args.js";
20
- import { SEGMENT_CUT_TIME_DELTA_SECONDS } from "./output/index.js";
20
+ import { cutsAtGivenTimes, SEGMENT_CUT_TIME_DELTA_SECONDS } from "./output/index.js";
21
21
 
22
22
  /**
23
23
  * What ffmpeg's own CLI subtracts from an input seek, and therefore what has to
@@ -364,15 +364,26 @@ export function buildRunCommand({
364
364
  // the first requested cut. It is never published over another run's output.
365
365
  const inputIndex = !transcodeVideo && !audioOnly && explicitTimes && safeIndex > 0
366
366
  ? safeIndex - 1 : safeIndex;
367
- // A COPY is cut by this list whatever grid it ended up on. Even when no
368
- // keyframe index could be read and the boundaries are a plain grid, saying
369
- // them outright is what keeps the playlist and the muxer agreeing — ffmpeg
370
- // moves each cut forward to the first real keyframe, and serving reads back
371
- // where the piece truly begins. Requiring a keyframe grid here dropped a
372
- // copy with no index onto the `hls` muxer, which takes no cut list and
373
- // writes no self-contained pieces, so nothing could read a true start and
374
- // segments were stamped with times the file does not have — the 4.17 s
375
- // speech-against-subtitles drift, back again.
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.
376
387
  //
377
388
  // Cut on the grid the PLAYER WAS GIVEN, not on the corrected one. A player
378
389
  // places a fragment by the playlist it holds, and that text was written
@@ -387,7 +398,7 @@ export function buildRunCommand({
387
398
  // created later inherits the corrected table and PUBLISHES it, so its own
388
399
  // playlist and its own cuts agree from the start. What they may not do is
389
400
  // move the cuts of a session whose playlist is already being read.
390
- const gridCutTimes = explicitTimes && (!transcodeVideo || timeline.cutGrid === "keyframe")
401
+ const gridCutTimes = cutsAtGivenTimes({ segmentFormat, timeline })
391
402
  ? segmentCutTimesFrom(publishedGridFor(timeline), inputIndex)
392
403
  : null;
393
404
  // Cut times are stated on the grid, for both branches.
@@ -721,9 +732,10 @@ export function buildRunCommand({
721
732
  // into the same directory — and the name arrives on the channel above the
722
733
  // instant ffmpeg closes it, which is what turns it into the served one.
723
734
  //
724
- // The other branch needs none of this: the HLS muxer writes through a
725
- // temporary name of its own (`+temp_file`), so its files appear under
726
- // their final name whole.
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.
727
739
  //
728
740
  // TAGGED WITH THE STRETCH IT WAS GIVEN, which names the run without any
729
741
  // counter to keep: intervals never overlap, so two live runs of one output
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import { logger } from "../../utils/logger.js";
11
- import { isOutputName } from "../encode/output/index.js";
11
+ import { isOutputName, PLAYLIST_FILE_NAME } from "../encode/output/index.js";
12
12
  import { IDLE_KEEP_MS } from "../storage/keep.js";
13
13
  /**
14
14
  * How long produced segments are kept after the last request for them.
@@ -273,7 +273,12 @@ export class OutputLifecycle {
273
273
  adoptSegmentsLeftBehind() {
274
274
  // Which container the segments are in is stated by the key itself; a key
275
275
  // that cannot say is a directory that goes (`encode/output-key-format.js`).
276
- return this.#host.segmentStore.adoptWhatSurvived((key) => this.#host.segmentFormatOfKey(key));
276
+ // The `hls` muxer writes its own list, under the playlist's name, beside the
277
+ // pieces it named itself; none of those pieces is proven whole.
278
+ return this.#host.segmentStore.adoptWhatSurvived(
279
+ (key) => this.#host.segmentFormatOfKey(key),
280
+ { selfNamedListFileName: PLAYLIST_FILE_NAME }
281
+ );
277
282
  }
278
283
 
279
284
  /**
@@ -13,7 +13,7 @@ import { access, readFile, stat, unlink } from "node:fs/promises";
13
13
  import { Readable } from "node:stream";
14
14
  import path from "node:path";
15
15
  import { logger } from "../../utils/logger.js";
16
- import { isOutputName, PLAYLIST_FILE_NAME } from "../encode/output/index.js";
16
+ import { cutsAtGivenTimes, isOutputName, PLAYLIST_FILE_NAME } from "../encode/output/index.js";
17
17
  // The index of variants. Served from the same route as the media playlist, so
18
18
  // it needs no path of its own.
19
19
  export const MASTER_PLAYLIST_FILE_NAME = "master.m3u8";
@@ -50,25 +50,6 @@ function isSafeFileName(fileName, segmentFormat) {
50
50
  segmentFormat.isSegmentFileName(fileName)
51
51
  );
52
52
  }
53
- /**
54
- * Whether this output is cut at times we hand the muxer, rather than at a
55
- * duration it chooses for itself.
56
- *
57
- * A property of the output and not of a run: the cut grid and the branch decide
58
- * it, so every run of one output answers alike. It decides how a segment is
59
- * judged finished — see getFileStream.
60
- *
61
- * @param {object} session
62
- * @returns {boolean}
63
- */
64
- function cutsAtGivenTimes(session) {
65
- const explicit = session?.segmentFormat?.explicitTimesMuxerArgs?.() ?? null;
66
- if (!explicit) {
67
- return false;
68
- }
69
- return !session.spec.transcodesVideo || session.timeline?.cutGrid === "keyframe";
70
- }
71
-
72
53
  export class SegmentServing {
73
54
  /** Serving state keyed by the output object it belongs to. */
74
55
  #states = new WeakMap();
@@ -275,14 +256,12 @@ export class SegmentServing {
275
256
  return this.#holdForProduction(session, fileName, isPlaylist, options);
276
257
  }
277
258
  try {
278
- // Existing is not the same as finished. The `hls` muxer wrote each
279
- // segment to a temporary name and renamed it once complete, so a file
280
- // appearing WAS a finished segment. The `segment` muxer has no such
281
- // option: the file appears when writing begins. Serving it then hands the
282
- // player a truncated segment, which it rejects and then simply stops —
283
- // observed as playback dying a few seconds in with the encoder still
284
- // running happily ahead. A segment is finished once the NEXT one has been
285
- // started, or once the run producing it has ended.
259
+ // Existing is not the same as finished. The `hls` muxer writes each
260
+ // segment to a temporary name and renames it when it ends the segment —
261
+ // at its cut, but also on SIGTERM and when its input stops, so a file
262
+ // appearing there proves only that the muxer let go of it. Every output
263
+ // with a grid is therefore cut by the `segment` muxer, whose file appears
264
+ // when writing begins and is served only once it is published below.
286
265
  if (!isPlaylist && cutsAtGivenTimes(session)) {
287
266
  // WHAT PROVES A PIECE IS WHOLE is the encoder's own word for it: it
288
267
  // names each file on a channel of its own the moment it closes it, and
@@ -403,6 +403,74 @@ export class SegmentStore {
403
403
  return removed;
404
404
  }
405
405
 
406
+ /**
407
+ * Remove the pieces a muxer that names its own pieces left in a directory,
408
+ * and the list it named them in.
409
+ *
410
+ * Asked only of what a previous life of the process left. The `hls` muxer
411
+ * renames the piece it has open when it ends, so a stopped run leaves a
412
+ * piece shorter than its span under the served name — the shape of field
413
+ * 2026-09-27, where #111 held 0.37 s of 4.2 s, the browser appended it and
414
+ * never asked for that stretch again. The list cannot say which piece is the
415
+ * short one, so every piece it names goes and is made again.
416
+ *
417
+ * @param {string} key
418
+ * @param {string} dir
419
+ * @param {{ isSegmentFileName?: (name: string) => boolean, initFileName?: string | null }} format
420
+ * @param {string | null} listFileName
421
+ * @returns {number} How many pieces were removed.
422
+ */
423
+ #sweepSelfNamed(key, dir, format, listFileName) {
424
+ if (!listFileName) {
425
+ return 0;
426
+ }
427
+ const listPath = path.join(dir, listFileName);
428
+ let text;
429
+ try {
430
+ text = readFileSync(listPath, "utf8");
431
+ } catch {
432
+ return 0;
433
+ }
434
+ let removed = 0;
435
+ for (const line of text.split(/\r?\n/)) {
436
+ const name = line.trim();
437
+ if (name.length === 0 || name.startsWith("#") || !format?.isSegmentFileName?.(name)) {
438
+ continue;
439
+ }
440
+ const piecePath = path.join(dir, name);
441
+ if (!existsSync(piecePath)) {
442
+ continue;
443
+ }
444
+ try {
445
+ rmSync(piecePath, { force: true });
446
+ removed += 1;
447
+ } catch {
448
+ // Then it stays, and is served as it was before this sweep existed.
449
+ }
450
+ }
451
+ // The list goes with the pieces it named, and so does the init file the
452
+ // same muxer wrote beside them: nothing else writes one into this
453
+ // directory, and a piece cut by the list carries its own header.
454
+ for (const leftover of [listFileName, format?.initFileName]) {
455
+ if (!leftover) {
456
+ continue;
457
+ }
458
+ try {
459
+ rmSync(path.join(dir, leftover), { force: true });
460
+ } catch {
461
+ // It names or describes pieces that are gone; reading it again removes nothing.
462
+ }
463
+ }
464
+ if (removed > 0) {
465
+ this.#held.delete(key);
466
+ this.#logger.info(
467
+ `segment-store removed ${removed} piece(s) of ${path.basename(dir)} that the hls muxer ` +
468
+ "named itself: nothing proves they reach their cut"
469
+ );
470
+ }
471
+ return removed;
472
+ }
473
+
406
474
  /**
407
475
  * The encoder has closed a piece: give it the name it is served under.
408
476
  *
@@ -564,10 +632,11 @@ export class SegmentStore {
564
632
  * muxer writes under a working name and reports the closure on a channel of
565
633
  * its own (`publish`); the `hls` muxer writes through a temporary name of its
566
634
  * own (`+temp_file`) and reports nothing, so the file simply appears under the
567
- * name it is served as. That branch is taken by every re-encoded output on the
568
- * even grid — the ordinary quality step — and for those `waitFor` could only
569
- * end on its deadline: the segment was on disk and the request that wanted it
570
- * went on waiting, up to a full minute, and was then answered 503.
635
+ * name it is served as. That branch was then taken by every re-encoded output
636
+ * on the even grid — the ordinary quality step — and for those `waitFor` could
637
+ * only end on its deadline: the segment was on disk and the request that
638
+ * wanted it went on waiting, up to a full minute, and was then answered 503.
639
+ * It is now taken only by a run given no cut list.
571
640
  *
572
641
  * So the store watches what it owns. The rename into place moves the
573
642
  * directory's modification time, the kernel says so, and both branches reach
@@ -1243,9 +1312,12 @@ export class SegmentStore {
1243
1312
  * @param {(key: string) => object | null} formatFor - How to read the file
1244
1313
  * names of an output, given its key. Null when this proxy cannot serve that
1245
1314
  * output at all, and then the directory goes.
1315
+ * @param {{ selfNamedListFileName?: string | null }} [writers] - The list a
1316
+ * muxer that names its own pieces writes beside them. Every piece in it was
1317
+ * given its served name by that muxer and not by a closure we were told of.
1246
1318
  * @returns {{ adopted: number, dropped: number, unprovenRemoved: number }}
1247
1319
  */
1248
- adoptWhatSurvived(formatFor) {
1320
+ adoptWhatSurvived(formatFor, { selfNamedListFileName = null } = {}) {
1249
1321
  const swept = this.sweep();
1250
1322
  let adopted = 0;
1251
1323
  let dropped = 0;
@@ -1266,15 +1338,21 @@ export class SegmentStore {
1266
1338
  continue;
1267
1339
  }
1268
1340
  this.#formats.set(entry.key, format);
1269
- // EVERY SEGMENT FOUND IS COMPLETE, because a piece is given its served
1270
- // name only once the encoder has said it is closed. So there is nothing to
1271
- // prove here and nothing to un-prove: what the directory holds under
1272
- // served names is what a killed process finished.
1341
+ // A SEGMENT GIVEN ITS SERVED NAME BY US IS COMPLETE, because we give it
1342
+ // only once the encoder has said it is closed and its media reaches its
1343
+ // cut. So there is nothing to prove here and nothing to un-prove: what
1344
+ // the directory holds under those names is what a killed process
1345
+ // finished.
1273
1346
  //
1274
1347
  // What it may also hold is pieces it was in the middle of, under their
1275
1348
  // working names, and those are swept — the file a run was writing when the
1276
1349
  // kernel took the process is exactly this.
1277
1350
  unprovenRemoved += this.#sweepUnfinished(entry.key, entry.dir, format);
1351
+ // And pieces the `hls` muxer renamed itself. It renames the piece it has
1352
+ // open whenever it ends, on SIGTERM and when its input stops, so nothing
1353
+ // says any of them reaches its cut; an earlier version cut every
1354
+ // re-encode on the even grid that way. The muxer's own list names them.
1355
+ unprovenRemoved += this.#sweepSelfNamed(entry.key, entry.dir, format, selfNamedListFileName);
1278
1356
  adopted += 1;
1279
1357
  this.#logger.info(
1280
1358
  `segment-store adopted ${path.basename(entry.dir)}: ${this.provenNumbers(entry.key).length} ` +