@torrent-tv/proxy 2.9.36 → 2.9.37

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,6 +1,13 @@
1
- ## 2.9.35
1
+ ## 2.9.37
2
+
3
+ - **Fix**: Scrubbing (server-side seek) no longer hangs the player. A far segment request restarts ffmpeg at that position; native players (notably iOS HLS) issue a burst of scattered far requests after a scrub (observed: `367 → 732 → 369 → 368 → 370`, tens of seconds apart), and the old fixed 4 s cooldown only suppressed restarts within 4 s of the last — so each scattered request restarted ffmpeg and it ping-ponged between positions, producing nothing and stalling playback. Far requests are now **debounced**: the target index is recorded and a short settle timer armed (1.2 s quiet period, 2.5 s hard cap from the burst's first request); further far requests re-arm it and update the target to the latest index; when it settles, ffmpeg restarts once at that index. "Last index wins" self-corrects — a wrong target costs at most one extra settle, never the old infinite loop. The settle timer is cleared on session disposal. (OpenSpec change `seek-debounce`.)
4
+
5
+ ## 2.9.36
2
6
 
3
7
  - **New**: Chunked request bodies over the data channel (OpenSpec change `chunked-request-bodies`). Large request bodies — notably the source registration, whose body is the base64 `.torrent` (hundreds of KB for a multi-season pack) — now arrive as bounded binary frames (the response-frame layout) announced by a `request-start` message, and are reassembled and run through the same path as a single-message request. Bounded: 32 MB per-body cap, a 60 s TTL for incomplete bodies, an abort frame that drops partial state at once, and all per-channel state freed on channel close. This removes the single-message size ceiling symmetrically with responses (which already stream in chunks). Logged as `body=<bytes> bytes (chunked)`.
8
+
9
+ ## 2.9.35
10
+
4
11
  - **Fix**: Large torrents (many files / seasons) no longer fail with "Trying to send message larger than max-message-size" when a file is picked. The browser sends the source registration body — the base64-encoded `.torrent` — in a single data-channel message; a big multi-season pack's `.torrent` carries thousands of piece hashes (e.g. Poirot, 13 seasons: 420 KB → ~560 KB base64), exceeding libdatachannel's default advertised limit of 256 KB, so the browser's `channel.send()` threw. The proxy now advertises a 16 MB `a=max-message-size`, so a large single send still works while already-open tabs run the old bundle. Verified the SDP now carries `a=max-message-size:16777216` (was `262144`).
5
12
 
6
13
  ## 2.9.34
File without changes
@@ -0,0 +1,118 @@
1
+ # Design: Debounce server-side seek restarts
2
+
3
+ Normative — member names, constants, and edge cases as written. Read before
4
+ coding:
5
+
6
+ - `services/hls-session-manager.js`: `#ensureEncodingFor(session, index)`
7
+ (line ~1478 — the restart decision), the session object shape where
8
+ `lastRestartAt` / `pendingRestartIndex` / `encodeStartIndex` live (~883),
9
+ `#startEncodeRun`, `disposeSession` (must clear timers), and the constants
10
+ block (~36–58).
11
+
12
+ ## Current behaviour (what we are replacing)
13
+
14
+ `#ensureEncodingFor` runs per segment request:
15
+
16
+ 1. Compute the look-ahead window `[head, currentSeg + MAX_LOOKAHEAD_SEGMENTS]`.
17
+ 2. In window → return (the running encode will reach it).
18
+ 3. Out of window (a seek) → if `now - lastRestartAt < RESTART_COOLDOWN_MS`,
19
+ skip; else `#startEncodeRun(session, index)` immediately.
20
+
21
+ The cooldown is a fixed 4 s gap. Requests spaced wider than 4 s each restart
22
+ → ping-pong. That is the bug.
23
+
24
+ ## New behaviour: settle window (debounce)
25
+
26
+ Keep steps 1–2. Replace step 3 with a debounce:
27
+
28
+ far request (index outside window):
29
+ session.seekTarget = index // last far index wins
30
+ if (!session.seekSettleTimer):
31
+ session.seekFirstFarAt = now()
32
+ else:
33
+ clearTimeout(session.seekSettleTimer)
34
+ const waited = now() - session.seekFirstFarAt
35
+ const delay = waited >= SEEK_SETTLE_MAX_MS ? 0
36
+ : Math.min(SEEK_SETTLE_MS, SEEK_SETTLE_MAX_MS - waited)
37
+ session.seekSettleTimer = setTimeout(() => fireSettledSeek(session), delay)
38
+ return // do NOT restart now
39
+
40
+ fireSettledSeek(session):
41
+ const target = session.seekTarget
42
+ session.seekSettleTimer = null
43
+ session.seekTarget = null
44
+ session.seekFirstFarAt = 0
45
+ if (session disposed or target == null) return
46
+ // Minimum gap between actual restarts (defensive; the settle already
47
+ // collapses bursts). If still cooling down, re-arm once for the
48
+ // remaining cooldown instead of restarting.
49
+ const sinceRestart = now() - (session.lastRestartAt ?? 0)
50
+ if (sinceRestart < RESTART_COOLDOWN_MS):
51
+ session.seekFirstFarAt = now()
52
+ session.seekTarget = target
53
+ session.seekSettleTimer = setTimeout(() => fireSettledSeek(session),
54
+ RESTART_COOLDOWN_MS - sinceRestart)
55
+ return
56
+ log(`transcode ${id} seek settle → restart at #${target}`)
57
+ this.#startEncodeRun(session, target) // sets lastRestartAt
58
+
59
+ Notes:
60
+ - `timer.unref?.()` on each `setTimeout` so a pending settle never keeps the
61
+ process alive (mirror the codebase's other timers).
62
+ - A far request whose `index` equals the current `seekTarget` still re-arms
63
+ the timer (the player is still asking for the same place — that is fine, it
64
+ just extends the quiet period up to the cap).
65
+ - If, while a settle is pending, the running encode advances so a later
66
+ request falls back INSIDE the window, that request returns at step 2 and
67
+ does not touch the settle. The pending settle still fires for the recorded
68
+ target; that is acceptable (it restarts at a position the player recently
69
+ wanted). Simplicity over cleverness.
70
+
71
+ ## Constants (add to the constants block)
72
+
73
+ // Quiet period after a far (seek) segment request before ffmpeg is
74
+ // restarted at it. Further far requests within the period re-arm it, so a
75
+ // scrub that emits a burst of scattered requests collapses to ONE restart
76
+ // at the position the player ended on.
77
+ SEEK_SETTLE_MS = 1200
78
+ // Hard cap on the total settle wait measured from the first far request of
79
+ // a burst, so a still-moving scrubber cannot delay a real seek forever.
80
+ SEEK_SETTLE_MAX_MS = 2500
81
+
82
+ `MAX_LOOKAHEAD_SEGMENTS` and `RESTART_COOLDOWN_MS` keep their current values;
83
+ `RESTART_COOLDOWN_MS` is now only the floor between actual restarts.
84
+
85
+ ## Session state (add where lastRestartAt is initialised, ~883)
86
+
87
+ seekSettleTimer: null, // pending settle timer handle or null
88
+ seekTarget: null, // pending far segment index to restart at
89
+ seekFirstFarAt: 0, // timestamp of the first far request in the burst
90
+
91
+ ## Disposal
92
+
93
+ `disposeSession` (and any teardown that abandons a session) MUST
94
+ `clearTimeout(session.seekSettleTimer)` and null it, so a settle cannot fire
95
+ after disposal and restart a dead session.
96
+
97
+ ## Why proxy-side, not client-side (the user's original framing)
98
+
99
+ The user asked for a scrubber-release debounce. On the in-page media-chrome
100
+ control that is possible but fragile, and — decisively — it cannot cover the
101
+ iOS **native fullscreen** player, whose scrubber the web app does not control;
102
+ the failing session was exactly iOS. The proxy sees the segment requests from
103
+ EVERY client (native iOS, hls.js, direct `<video>`), so debouncing the
104
+ restart here is the one place that fixes all of them. An in-page scrubber
105
+ debounce may still be added later as a responsiveness nicety; it is not a
106
+ substitute and is out of scope here.
107
+
108
+ ## Verification
109
+
110
+ - Unit-test the timing/target logic in isolation (a fake session + a fake
111
+ clock/`setTimeout`): a burst of far requests `367,732,369,368,370` within
112
+ the window collapses to a single `#startEncodeRun` at the LAST index (370),
113
+ and a lone later far request triggers exactly one more restart.
114
+ - `node --check`.
115
+ - Field: the earlier hang scenario (scrub Poirot on iOS) should now produce a
116
+ single `seek settle → restart` log line per scrub instead of a train of
117
+ `seek → restart` lines, and playback should resume after one settle + the
118
+ (separate, unavoidable) cold-segment wait.
@@ -0,0 +1,59 @@
1
+ # Proposal: Debounce server-side seek restarts
2
+
3
+ ## Why
4
+
5
+ Field evidence (iPhone/Safari, Poirot, 2026-07-09): after a scrub the player
6
+ hung indefinitely. The proxy restarts ffmpeg at a requested segment when the
7
+ request lands outside the look-ahead window (server-side seek). The native
8
+ iOS player issued scattered segment requests after the seek —
9
+ `367 → 732 → 369 → 368 → 370` — each 25–35 s apart. The existing guard
10
+ (`RESTART_COOLDOWN_MS = 4000`) only suppresses restarts within 4 s of the
11
+ last one, so with requests spaced far wider than that, EVERY scattered
12
+ request restarted ffmpeg at a new position. ffmpeg ping-ponged between
13
+ positions and never finished a single segment, so playback stalled at
14
+ `currentTime` with `bufferedAhead=0` — "заглохло наглухо".
15
+
16
+ The fix is the user's idea placed where every client is covered (including
17
+ the iOS native fullscreen player, whose scrubber the web app cannot control):
18
+ don't act on the first far request — wait for the burst to settle, then
19
+ restart ONCE at the position the player ended on.
20
+
21
+ ## What Changes
22
+
23
+ - Replace the fixed post-restart cooldown as the anti-thrash mechanism with a
24
+ **settle window**. When a segment request lands outside the look-ahead
25
+ window (a seek), the proxy does NOT restart immediately: it records the
26
+ requested index as the pending seek target and arms a short quiet-period
27
+ timer. Each further far request updates the target to the latest index and
28
+ re-arms the timer (debounce). When the quiet period elapses with no new far
29
+ request, ffmpeg restarts ONCE at the pending target. A hard cap bounds the
30
+ total wait so a genuine seek is never delayed more than a fixed budget even
31
+ while the scrubber is still moving.
32
+ - Meanwhile the segment route behaves exactly as today — it long-polls and
33
+ the client retries — so the player simply waits out the (short) settle
34
+ instead of driving restarts.
35
+ - "Last far index wins" self-corrects: if the settle resolves on the wrong
36
+ position (e.g. a lone probe request), the player's next request re-arms one
37
+ more settle — at most one extra cycle, never the old infinite ping-pong.
38
+
39
+ Out of scope (documented in design.md): an optional client-side scrubber
40
+ debounce for the in-page media-chrome control (helps responsiveness but does
41
+ NOT cover iOS native fullscreen, so the proxy-side settle is the must-have);
42
+ the cold-torrent piece-download and weak-host encode latency that make the
43
+ FIRST post-seek segment slow regardless — the settle removes the infinite
44
+ thrash, not the one-time seek latency.
45
+
46
+ ## Capabilities
47
+
48
+ ### Modified Capabilities
49
+
50
+ - `seek-debounce` (server-side HLS seeking): far-segment requests are
51
+ debounced into a single ffmpeg restart at the settled position.
52
+
53
+ ## Impact
54
+
55
+ - `services/hls-session-manager.js` — `#ensureEncodingFor` gains the settle
56
+ window; per-session settle state; `disposeSession` clears the timer;
57
+ constants. `RESTART_COOLDOWN_MS` is retained only as a minimum gap between
58
+ actual restarts.
59
+ - Proxy release + ha-addon version bump (per release rules).
@@ -0,0 +1,41 @@
1
+ # seek-debounce — delta spec (proxy)
2
+
3
+ ## ADDED Requirements
4
+
5
+ ### Requirement: Scattered post-seek segment requests collapse to one restart
6
+
7
+ When segment requests land outside the running encode's look-ahead window
8
+ (server-side seeks), the proxy SHALL NOT restart ffmpeg on each one. It SHALL
9
+ wait a short settle period, treating further out-of-window requests as
10
+ re-arming the period and updating the target to the most recently requested
11
+ index, and then restart the encoder exactly once at the settled target. A
12
+ fixed cap SHALL bound the total settle wait so a genuine seek is not delayed
13
+ indefinitely while the scrubber is still moving. During the settle the
14
+ segment route behaves as before (long-poll / client retry).
15
+
16
+ #### Scenario: Scrub emits a burst of scattered requests
17
+ - **WHEN** a player, after a seek, requests several far-apart segments in
18
+ quick succession (e.g. 367, 732, 369, 368, 370)
19
+ - **THEN** ffmpeg is restarted only once, at the last requested index, and
20
+ produces a continuous run from there — no ping-pong between positions
21
+
22
+ #### Scenario: Settle resolves on the wrong position
23
+ - **WHEN** the settled restart target turns out not to be where the player
24
+ ultimately needs to play (e.g. it was a lone probe request)
25
+ - **THEN** the player's next out-of-window request arms exactly one more
26
+ settle and one more restart — never an unbounded restart loop
27
+
28
+ #### Scenario: Request falls back inside the window
29
+ - **WHEN** a requested segment is within the current run's look-ahead window
30
+ - **THEN** it is served by the running encode with no restart and without
31
+ affecting any pending settle
32
+
33
+ ### Requirement: A pending settle never outlives its session
34
+
35
+ When a session is disposed, any pending settle timer SHALL be cleared so it
36
+ cannot fire and restart a disposed session.
37
+
38
+ #### Scenario: Session disposed mid-settle
39
+ - **WHEN** a session with a pending seek-settle timer is disposed (idle TTL,
40
+ shutdown, or teardown)
41
+ - **THEN** the timer is cleared and no encode restart occurs afterwards
@@ -0,0 +1,33 @@
1
+ # Tasks: Debounce server-side seek restarts
2
+
3
+ ## 1. Implementation (proxy)
4
+
5
+ - [x] 1.1 Add `SEEK_SETTLE_MS = 1200` and `SEEK_SETTLE_MAX_MS = 2500` to the
6
+ constants block in `hls-session-manager.js`.
7
+ - [x] 1.2 Add session state `seekSettleTimer: null`, `seekTarget: null`,
8
+ `seekFirstFarAt: 0` where `lastRestartAt` is initialised.
9
+ - [x] 1.3 Rewrite the out-of-window branch of `#ensureEncodingFor` as the
10
+ settle/debounce (design.md): record target, arm/re-arm the timer with
11
+ the capped delay, restart once on fire (`#fireSettledSeek`), re-arm for
12
+ the cooldown remainder if still cooling down. `timer.unref?.()`.
13
+ - [x] 1.4 `disposeSession`: clear `seekSettleTimer` and null it.
14
+ - [x] 1.5 Restart log line: `transcode <id> seek settle → restart at segment #<target>`.
15
+
16
+ ## 2. Verification
17
+
18
+ - [x] 2.1 Timing/target logic verified with a fake-clock replica: burst
19
+ `367,732,369,368,370` → one restart at 370; lone later far request →
20
+ exactly one more restart (900); disposal mid-settle → no restart; the
21
+ 2.5 s cap forces a fire while the scrubber keeps moving. (Replica, not
22
+ the wired private method — the methods are private and `#startEncodeRun`
23
+ spawns ffmpeg; the wired code mirrors the replica.)
24
+ - [x] 2.2 `node --check services/hls-session-manager.js`.
25
+
26
+ ## 3. Release
27
+
28
+ - [ ] 3.1 CHANGELOG (proxy, next patch) + `npm run patch` (user OTP).
29
+ - [ ] 3.2 Bump `ha-addon/torrent_tv_proxy/config.yaml` + CHANGELOG; push;
30
+ update the addon in HA.
31
+ - [ ] 3.3 Field: scrub Poirot on iOS → a single `seek settle → restart` per
32
+ scrub (not a train of `seek → restart`), playback resumes after the
33
+ settle + the unavoidable cold-segment wait.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torrent-tv/proxy",
3
- "version": "2.9.36",
3
+ "version": "2.9.37",
4
4
  "description": "Torrent proxy client that exposes webseed-like HTTP stream endpoint.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "publishConfig": {
@@ -43,6 +43,17 @@ const MAX_LOOKAHEAD_SEGMENTS = 8;
43
43
  // succession (stall-recovery seeks); without a cooldown ffmpeg ping-pongs
44
44
  // between positions, restarting endlessly and producing nothing.
45
45
  const RESTART_COOLDOWN_MS = 4_000;
46
+ // Seek debounce. A far (out-of-window) segment request is a server-side seek.
47
+ // Rather than restart ffmpeg on the first one, wait a short quiet period:
48
+ // further far requests re-arm it and update the target to the latest index, so
49
+ // a scrub that emits a burst of scattered requests (e.g. iOS native HLS firing
50
+ // 367,732,369,368,370 seconds apart) collapses to ONE restart at the position
51
+ // the player ended on, instead of ping-ponging ffmpeg between positions and
52
+ // producing nothing.
53
+ const SEEK_SETTLE_MS = 1_200;
54
+ // Hard cap on the total settle wait, measured from the first far request of a
55
+ // burst, so a still-moving scrubber cannot delay a genuine seek forever.
56
+ const SEEK_SETTLE_MAX_MS = 2_500;
46
57
  // Idle TTL: a session is disposed this long after the last segment/playlist
47
58
  // access. Kept short so an ffmpeg process does not keep burning CPU after the
48
59
  // viewer stops or navigates away. Active playback refreshes the timer on every
@@ -884,6 +895,12 @@ export class HlsSessionManager {
884
895
  pendingRestartIndex: -1,
885
896
  // Timestamp of the last encode (re)start, for the restart cooldown.
886
897
  lastRestartAt: 0,
898
+ // Seek debounce: pending settle timer, the far segment index to restart
899
+ // at once the burst settles, and the timestamp of the burst's first far
900
+ // request (for the SEEK_SETTLE_MAX_MS cap).
901
+ seekSettleTimer: null,
902
+ seekTarget: null,
903
+ seekFirstFarAt: 0,
887
904
  progress: {
888
905
  state: "starting",
889
906
  processedSeconds: 0,
@@ -1492,22 +1509,52 @@ export class HlsSessionManager {
1492
1509
  if (withinWindow) {
1493
1510
  return;
1494
1511
  }
1495
- if (session.pendingRestartIndex === index) {
1512
+ // Far request = a server-side seek. Do NOT restart on the first one:
1513
+ // debounce a burst of scattered requests into a single restart at the
1514
+ // position the player ended on. Record the latest target and (re)arm the
1515
+ // settle timer; the caller long-polls / the client retries meanwhile.
1516
+ session.seekTarget = index;
1517
+ if (session.seekSettleTimer) {
1518
+ clearTimeout(session.seekSettleTimer);
1519
+ } else {
1520
+ session.seekFirstFarAt = Date.now();
1521
+ }
1522
+ const waited = Date.now() - session.seekFirstFarAt;
1523
+ const delay = waited >= SEEK_SETTLE_MAX_MS ? 0 : Math.min(SEEK_SETTLE_MS, SEEK_SETTLE_MAX_MS - waited);
1524
+ session.seekSettleTimer = setTimeout(() => this.#fireSettledSeek(session), delay);
1525
+ session.seekSettleTimer.unref?.();
1526
+ }
1527
+
1528
+ /**
1529
+ * Fire a settled server-side seek: restart the encoder once at the target
1530
+ * recorded during the settle window. Enforces the restart cooldown as a
1531
+ * floor between actual restarts (re-arming for the remainder if still
1532
+ * cooling down). No-op for a disposed session or a cleared target.
1533
+ *
1534
+ * @param {HlsSession} session
1535
+ * @returns {void}
1536
+ */
1537
+ #fireSettledSeek(session) {
1538
+ const target = session.seekTarget;
1539
+ session.seekSettleTimer = null;
1540
+ if (!session || session.state === "disposed" || target == null) {
1541
+ session.seekTarget = null;
1542
+ session.seekFirstFarAt = 0;
1496
1543
  return;
1497
1544
  }
1498
- // Restart cooldown: a stalled player requests several distant segments in
1499
- // quick succession; without this guard ffmpeg ping-pongs between them and
1500
- // never makes progress. Skip the restart during the cooldown the caller
1501
- // long-polls / the client retries, and a genuine seek is honored once the
1502
- // cooldown elapses.
1545
+ // Minimum gap between actual restarts (the settle already collapses bursts;
1546
+ // this only guards back-to-back seeks). If still cooling down, re-arm once
1547
+ // for the remaining cooldown instead of restarting now.
1503
1548
  const sinceLastRestart = Date.now() - (session.lastRestartAt ?? 0);
1504
1549
  if (sinceLastRestart < RESTART_COOLDOWN_MS) {
1550
+ session.seekSettleTimer = setTimeout(() => this.#fireSettledSeek(session), RESTART_COOLDOWN_MS - sinceLastRestart);
1551
+ session.seekSettleTimer.unref?.();
1505
1552
  return;
1506
1553
  }
1507
- logger.info(
1508
- `transcode ${session.id} seek → restart at segment #${index} (encode head #${head}, current #${currentSeg})`
1509
- );
1510
- this.#startEncodeRun(session, index);
1554
+ session.seekTarget = null;
1555
+ session.seekFirstFarAt = 0;
1556
+ logger.info(`transcode ${session.id} seek settle → restart at segment #${target}`);
1557
+ this.#startEncodeRun(session, target);
1511
1558
  }
1512
1559
 
1513
1560
  /**
@@ -1743,6 +1790,13 @@ export class HlsSessionManager {
1743
1790
  this.sessionsById.delete(sessionId);
1744
1791
  this.sessionIdBySource.delete(session.sourceMapKey);
1745
1792
 
1793
+ // Clear any pending seek-settle timer so it cannot fire and restart a
1794
+ // disposed session.
1795
+ if (session.seekSettleTimer) {
1796
+ clearTimeout(session.seekSettleTimer);
1797
+ session.seekSettleTimer = null;
1798
+ }
1799
+
1746
1800
  if (session.ffmpeg && !session.ffmpeg.killed) {
1747
1801
  session.ffmpeg.kill("SIGTERM");
1748
1802
  await waitForChildExit(session.ffmpeg);