@torrent-tv/proxy 2.36.1 → 2.36.2

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/CHANGELOG.md CHANGED
@@ -1,3 +1,8 @@
1
+ ## 2.36.2
2
+
3
+ - **Fix**: A live session no longer answers 404 to the master playlist it has just published. The browser is handed `master.m3u8` when the session is created, and which rungs are worth OFFERING is recomputed every five seconds — so on 2026-08-18 a five-rung offer became a one-rung offer **192 ms** after creation (the session's own encoder started, charging the contention penalty of 2.35.0, and the first supply reading raised the bar of 2.36.0 from 1.00x to 1.06x), `buildMasterPlaylist` returned null for having fewer than two rungs, and the master answered 404. hls.js treats that as fatal and unrecoverable, so nothing played at all. The master now lists what CAN be spliced onto this session's cut grid — a fact about the source, settled once — while the live judgement stays where it belongs, in `offeredHeights` and in every progress report, which is what the viewer's menu already follows. The variant routes honour the published set too, so a quality switch can no longer meet a 404 on a rung the master named.
4
+ - **Fix**: Peer discovery no longer starves behind name resolution. Node resolves host names on the libuv thread pool, which holds four threads by default; a torrent announces to every tracker in its file at once, so four names resolve and the rest queue — and a tracker that no longer exists holds its thread for the resolver's full ten-second timeout while every announce behind it blows its own fifteen-second deadline. Measured inside the addon container: the ten trackers of one film took **7.58 s** to resolve as a burst and **27-42 ms** each with a larger pool. That film has 517 seeders on a tracker that answers in 50 ms, and it spent eleven minutes with **zero peers** while four other torrents in the same process were fine — they were the ones whose live trackers happened to fall in the first four. The pool is now stated before anything can create it (`services/thread-pool.js`, imported first by the entry point), and a deployment that states its own size is left alone.
5
+
1
6
  ## 2.36.1
2
7
 
3
8
  - **Fix**: The cut list of a copied picture is built from the picture's own keyframes, and no longer from every entry in the container's table. A Matroska CuePoint belongs to the track named inside it, and RFC 9559 leaves the muxer free to index whichever tracks it likes — both field files index their subtitles as well. Measured over the swarm on 2026-08-18, reading only the head and the table: `Minions.and.Monsters.1080p.mkv` has **2778 video entries, one every 2.002 s, and 4669 more across four subtitle tracks**; `Moana.2.2024.720p.BluRay … MegaPeer.mkv` has **1055 video entries and 5007 across five**. Read without the track, the extra times entered the cut list as though they were keyframes; ffmpeg can only cut a copied picture at a real keyframe at or after the time it is given, so each such cut landed at the next one instead — which is exactly the disagreement the field measured, and why it was always positive: 2.002 s on the first file (its own keyframe spacing), a median of 6.3 s and a worst case of 21 s on the second. The reader now takes the first video track's number from Tracks — already inside the head it fetches, with one short extra read only for a file that keeps Tracks elsewhere — and keeps the entries of that track. Nothing else about the two-read approach changes, and a session costs nothing more. With the fix the same two files read 2778 and 1055 times, all of them keyframes. When the filter leaves NOTHING — a table whose entries name a track number Tracks never declares — the unfiltered table is used rather than no table: that case is this reader failing to recognise the file, and answering with nothing would put an even grid on a copied picture, which is the failure it exists to prevent.
package/bin/cli.js CHANGED
@@ -8,6 +8,11 @@
8
8
  * automatically on reconnect so the server's in-memory store stays consistent.
9
9
  */
10
10
 
11
+ // FIRST, and it must stay first: it sets how many blocking calls this process
12
+ // can have in flight, and a module's imports are evaluated before its body, so
13
+ // anything imported above it would get the default pool. See the file itself
14
+ // for the measurement that made it necessary.
15
+ import "../services/thread-pool.js";
11
16
  import { Command } from "commander";
12
17
  import crypto from "node:crypto";
13
18
  import { spawnSync } from "node:child_process";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.36.1",
3
+ "version": "2.36.2",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -2065,7 +2065,7 @@ export class HlsSessionManager {
2065
2065
  // flip the arrangement under a stream that is playing.
2066
2066
  session.audioSeparate = inheritedAudioSeparate === null
2067
2067
  ? audioRenditions === true &&
2068
- this.#variantHeights(session).length >= 2 &&
2068
+ this.#splicableHeights(session).length >= 2 &&
2069
2069
  this.#audioRenditionsOf(session).length > 0
2070
2070
  : inheritedAudioSeparate === true;
2071
2071
 
@@ -5379,6 +5379,42 @@ export class HlsSessionManager {
5379
5379
  return session.variantHeight;
5380
5380
  }
5381
5381
 
5382
+ /**
5383
+ * The heights this file's variants CAN be spliced at — a fact about the
5384
+ * source and the cut grid, settled once and never moved.
5385
+ *
5386
+ * Separate from {@link #variantHeights}, which answers a different question:
5387
+ * which of them are worth OFFERING to the viewer right now, on a machine
5388
+ * whose load moves every five seconds. Both were the same list until
5389
+ * 2026-08-18, and that is what broke playback outright: the browser is told
5390
+ * at session creation that a master playlist exists, and 192 ms later — after
5391
+ * the session's own encoder had started and the first supply reading had
5392
+ * arrived — the live list had fallen from five rungs to one, `buildMaster
5393
+ * Playlist` returned null for having fewer than two, and the master answered
5394
+ * 404 to the very session that had just published it. hls.js treats that as
5395
+ * fatal and unrecoverable, so nothing played at all (session `4ef731d8`,
5396
+ * "Moana (2016).mkv", 17:43:01).
5397
+ *
5398
+ * A live figure may decide what to offer. It may not decide whether a
5399
+ * published document exists.
5400
+ *
5401
+ * @param {HlsSession} session
5402
+ * @returns {number[]} Largest first.
5403
+ */
5404
+ #splicableHeights(session) {
5405
+ const owner = this.#baseOf(session);
5406
+ if (Array.isArray(owner.splicableHeights)) {
5407
+ return owner.splicableHeights;
5408
+ }
5409
+ const heights = new Set(variantHeightsFor(Number(owner.sourceHeight) || 0));
5410
+ const own = this.variantHeightOf(owner);
5411
+ if (own > 0) {
5412
+ heights.add(own);
5413
+ }
5414
+ owner.splicableHeights = [...heights].sort((left, right) => right - left);
5415
+ return owner.splicableHeights;
5416
+ }
5417
+
5382
5418
  /**
5383
5419
  * The heights this session's file is offered at, largest first.
5384
5420
  *
@@ -6540,8 +6576,11 @@ export class HlsSessionManager {
6540
6576
  return null;
6541
6577
  }
6542
6578
  // Only the heights the master offers. Anything else is a made-up request,
6543
- // and honouring it would let a client start encoder runs at will.
6544
- if (!this.#variantHeights(base).includes(height)) {
6579
+ // and honouring it would let a client start encoder runs at will. The
6580
+ // MASTER's list, not the live one: a rung is published for the session's
6581
+ // whole life, and refusing what we published is how a quality switch became
6582
+ // a 404 storm across every level.
6583
+ if (!this.#splicableHeights(base).includes(height)) {
6545
6584
  return null;
6546
6585
  }
6547
6586
  if (height === this.variantHeightOf(base)) {
@@ -6690,7 +6729,7 @@ export class HlsSessionManager {
6690
6729
  if (!isPlaylist && !isInit && !isSegment) {
6691
6730
  return { sessionId: null };
6692
6731
  }
6693
- if (!this.#variantHeights(base).includes(height)) {
6732
+ if (!this.#splicableHeights(base).includes(height)) {
6694
6733
  return { sessionId: null };
6695
6734
  }
6696
6735
  // Answered from the base, and no encoder is started for it. Every variant of
@@ -6945,7 +6984,11 @@ export class HlsSessionManager {
6945
6984
  return null;
6946
6985
  }
6947
6986
  const sourceHeight = Number(session.sourceHeight) || 0;
6948
- const rungs = this.#variantHeights(session);
6987
+ // What CAN be spliced, not what is worth offering this second. The live
6988
+ // judgement travels in `offeredHeights` and in every progress report, which
6989
+ // is what the viewer's menu follows; letting it decide the master's
6990
+ // existence made a live session answer 404 to its own published address.
6991
+ const rungs = this.#splicableHeights(session);
6949
6992
  if (rungs.length < 2) {
6950
6993
  return null;
6951
6994
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @file How many blocking calls this process can have in flight — set before
3
+ * anything makes one.
4
+ *
5
+ * Node resolves host names with `getaddrinfo`, which runs on the libuv thread
6
+ * pool, and that pool holds FOUR threads by default. A torrent announces to
7
+ * every tracker in its file at once — ten or thirteen of them — so four names
8
+ * are resolved and the rest queue; a tracker that no longer exists holds its
9
+ * thread for the resolver's full ten-second timeout, and every announce behind
10
+ * it blows its own fifteen-second deadline.
11
+ *
12
+ * Measured inside the addon container on 2026-08-18, resolving the ten trackers
13
+ * of one film: as a burst on the default pool, two names answered in 30-40 ms
14
+ * and the other seven took **7.58 s**; with a larger pool every live name
15
+ * answered in **27-42 ms**. The film itself had 517 seeders on a tracker that
16
+ * answers in 50 ms, and spent eleven minutes with zero peers, because every
17
+ * announce — UDP and HTTP alike — timed out waiting for a name.
18
+ *
19
+ * Sized to hold several torrents' announce lists at once, since the same pool
20
+ * also serves this process's file reads. Idle threads cost memory and nothing
21
+ * else, and a deployment that states its own size is left alone.
22
+ *
23
+ * Imported FIRST by the entry point, because a module's imports are evaluated
24
+ * before its body: written as a statement in `cli.js` this would run after
25
+ * every other import had already had its chance to create the pool.
26
+ */
27
+
28
+ if (!process.env.UV_THREADPOOL_SIZE) {
29
+ process.env.UV_THREADPOOL_SIZE = "64";
30
+ }
@@ -288,7 +288,7 @@ test("the source's decode figures come off the probe, or not at all", () => {
288
288
  assert.equal(sourceDecodeCharacteristics(null), null);
289
289
  });
290
290
 
291
- test("the master playlist drops the rungs the host cannot hold", async (t) => {
291
+ test("the OFFER drops the rungs the host cannot hold, and the master keeps addressing them", async (t) => {
292
292
  const dirPath = await mkdtemp(path.join(os.tmpdir(), "decode-cost-"));
293
293
  const manager = new HlsSessionManager({
294
294
  enabled: true,
@@ -339,15 +339,22 @@ test("the master playlist drops the rungs the host cannot hold", async (t) => {
339
339
  };
340
340
  manager.sessionsById.set(session.id, session);
341
341
 
342
- assert.equal(
343
- manager.buildMasterPlaylist(session.id),
344
- null,
345
- "every rung under the copy runs below realtime here, so there is nothing to switch to"
346
- );
347
342
  assert.deepEqual(
348
343
  manager.offeredHeights(session),
349
344
  [1080],
350
- "and the list the browser is given says the same, since both come from one answer"
345
+ "every rung under the copy runs below realtime here, so there is nothing to switch to"
346
+ );
347
+ // The master is NOT that answer. It says which rungs can be spliced onto this
348
+ // cut grid, which is a fact about the file, and it has to hold still for the
349
+ // session's life: the browser is handed its address at creation, and a live
350
+ // figure that withdrew it left a session answering 404 to itself (field
351
+ // 2026-08-18, "Moana (2016).mkv" — nothing played at all).
352
+ const weakMaster = manager.buildMasterPlaylist(session.id);
353
+ assert.ok(weakMaster, "published once, whatever the host is managing this second");
354
+ assert.deepEqual(
355
+ [...weakMaster.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1])),
356
+ [1080, 720, 540, 480, 360, 240],
357
+ "the ladder of the source, addressable — the menu the viewer sees is offeredHeights"
351
358
  );
352
359
 
353
360
  // A host with a little more encoder keeps the rungs it can actually hold. A
@@ -355,11 +362,18 @@ test("the master playlist drops the rungs the host cannot hold", async (t) => {
355
362
  manager.softwarePresetBenchmark = [{ preset: "ultrafast", pixelsPerSec: 12e6 }];
356
363
  const stronger = { ...session, id: "dddddddd-eeee-ffff-0000-111111111111", offeredHeightsCache: undefined };
357
364
  manager.sessionsById.set(stronger.id, stronger);
365
+ assert.deepEqual(
366
+ manager.offeredHeights(stronger),
367
+ [1080, 360, 240],
368
+ "nothing is known about this swarm, so the bar is realtime"
369
+ );
358
370
  const master = manager.buildMasterPlaylist(stronger.id);
359
- assert.ok(master, "1080p copied plus the rungs this host can produce");
360
- const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
361
- assert.deepEqual(heights, [1080, 360, 240], "nothing is known about this swarm, so the bar is realtime");
362
- assert.deepEqual(manager.offeredHeights(stronger), heights);
371
+ assert.ok(master, "1080p copied plus every rung that can be spliced beside it");
372
+ assert.deepEqual(
373
+ [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1])),
374
+ [1080, 720, 540, 480, 360, 240],
375
+ "the same published set as before: what the host manages is the offer's business, not the document's"
376
+ );
363
377
 
364
378
  // The same host, once the reader has measured what this file's supply
365
379
  // demands: waits arriving as they did on the field torrent of 2026-08-17 ask
@@ -813,3 +813,49 @@ test("a quality step being warmed is not refused by its own cost", async (t) =>
813
813
  "offer by the act of warming it — and its next segment 404s on a stream that is playing"
814
814
  );
815
815
  });
816
+
817
+ test("the master survives a live offer that has collapsed to one rung", async (t) => {
818
+ // The field case of 2026-08-18, in the smallest form that reproduces it: a
819
+ // host too slow for any re-encoded rung, and a swarm whose interruptions
820
+ // demand far more than realtime. The live offer then holds only the height an
821
+ // encoder is already producing — and until this test existed, that made
822
+ // `buildMasterPlaylist` answer null and the route answer 404 to a session
823
+ // that had just published the address.
824
+ const dirPath = await mkdtemp(path.join(os.tmpdir(), "quality-variants-collapse-"));
825
+ const manager = new HlsSessionManager({
826
+ enabled: true,
827
+ ffmpegBin: "ffmpeg",
828
+ localBindHost: "127.0.0.1",
829
+ localPort: 9090,
830
+ // A megapixel a second: every rung below the source costs more than the
831
+ // machine has.
832
+ softwarePresetBenchmark: [{ preset: "veryfast", pixelsPerSec: 1_000_000 }],
833
+ decodeCostModel: { pixelTerm: 0.01, bitrateTerm: 0, constantTerm: 0 }
834
+ });
835
+ const base = fakeSession({ id: BASE_ID, encodeHeight: 812, dirPath });
836
+ base.sourceDecode = { megapixelsPerSecond: 50, megabitsPerSecond: 10 };
837
+ // What this file's own reader measured: a step must run at eight times
838
+ // realtime to survive this swarm.
839
+ base.supplyFigures = { requiredSpeed: 8 };
840
+ manager.sessionsById.set(BASE_ID, base);
841
+ t.after(async () => {
842
+ await manager.disposeAll();
843
+ await rm(dirPath, { recursive: true, force: true });
844
+ });
845
+
846
+ assert.deepEqual(
847
+ manager.offeredHeights(base),
848
+ [812],
849
+ "the live judgement is unchanged: nothing but the running height is worth offering"
850
+ );
851
+
852
+ const master = manager.buildMasterPlaylist(BASE_ID);
853
+
854
+ assert.ok(master, "the master is a published document, not a live figure");
855
+ const heights = [...master.matchAll(/^v\/(\d+)\/index\.m3u8$/gm)].map((match) => Number(match[1]));
856
+ assert.deepEqual(
857
+ heights,
858
+ [1080, 812, 720, 540, 480, 360, 240],
859
+ "every rung that can be spliced onto this cut grid stays addressable"
860
+ );
861
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @file The blocking-call pool is stated before anything can create it.
3
+ *
4
+ * Field 2026-08-18: a film with 517 seeders spent eleven minutes with zero
5
+ * peers on the addon host. Every announce timed out — UDP and HTTP alike — and
6
+ * the cause was not the network: resolving that torrent's ten tracker names as
7
+ * a burst took 7.58 s on the default four-thread pool, against 27-42 ms each
8
+ * when the pool was larger. A dead tracker holds a thread for the resolver's
9
+ * whole timeout, and every announce queued behind it misses its own deadline.
10
+ */
11
+
12
+ import test from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { readFile } from "node:fs/promises";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const here = path.dirname(fileURLToPath(import.meta.url));
19
+
20
+ test("the pool is set, and left alone when the deployment states its own", async () => {
21
+ const previous = process.env.UV_THREADPOOL_SIZE;
22
+ try {
23
+ process.env.UV_THREADPOOL_SIZE = "";
24
+ await import(`../services/thread-pool.js?first=${Date.now()}`);
25
+ assert.equal(
26
+ Number(process.env.UV_THREADPOOL_SIZE) >= 16,
27
+ true,
28
+ "enough threads for a torrent's whole announce list to resolve at once"
29
+ );
30
+
31
+ process.env.UV_THREADPOOL_SIZE = "8";
32
+ await import(`../services/thread-pool.js?stated=${Date.now()}`);
33
+ assert.equal(process.env.UV_THREADPOOL_SIZE, "8", "a stated size is the deployment's to choose");
34
+ } finally {
35
+ if (previous === undefined) {
36
+ delete process.env.UV_THREADPOOL_SIZE;
37
+ } else {
38
+ process.env.UV_THREADPOOL_SIZE = previous;
39
+ }
40
+ }
41
+ });
42
+
43
+ test("the entry point imports it before anything that could create the pool", async () => {
44
+ const cli = await readFile(path.join(here, "..", "bin", "cli.js"), "utf8");
45
+ const imports = [...cli.matchAll(/^import\s.*?from\s+["'](.+?)["'];|^import\s+["'](.+?)["'];/gm)]
46
+ .map((match) => match[1] ?? match[2]);
47
+
48
+ assert.equal(
49
+ imports[0],
50
+ "../services/thread-pool.js",
51
+ "a module's imports run before its body, so this cannot be a statement in cli.js"
52
+ );
53
+ });