@torrent-tv/proxy 2.9.35 → 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 +9 -1
- package/openspec/changes/chunked-request-bodies/design.md +81 -0
- package/openspec/changes/chunked-request-bodies/proposal.md +53 -0
- package/openspec/changes/chunked-request-bodies/specs/chunked-request-bodies/spec.md +30 -0
- package/openspec/changes/chunked-request-bodies/tasks.md +40 -0
- package/openspec/changes/seek-debounce/.openspec.yaml +0 -0
- package/openspec/changes/seek-debounce/design.md +118 -0
- package/openspec/changes/seek-debounce/proposal.md +59 -0
- package/openspec/changes/seek-debounce/specs/seek-debounce/spec.md +41 -0
- package/openspec/changes/seek-debounce/tasks.md +33 -0
- package/package.json +1 -1
- package/services/data-channel-handler.js +147 -14
- package/services/hls-session-manager.js +64 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
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
|
|
6
|
+
|
|
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
|
+
|
|
1
9
|
## 2.9.35
|
|
2
10
|
|
|
3
|
-
- **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
|
|
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`).
|
|
4
12
|
|
|
5
13
|
## 2.9.34
|
|
6
14
|
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Design: Chunked request bodies (proxy side)
|
|
2
|
+
|
|
3
|
+
Written to be executed as specified — the wire format, constants, limits
|
|
4
|
+
and do-NOT list are normative. Read before coding:
|
|
5
|
+
|
|
6
|
+
- `services/data-channel-handler.js`: the whole file — the wire-protocol
|
|
7
|
+
doc comment (~lines 9–37), `handleChannel` (onMessage string handling),
|
|
8
|
+
`handleRequest`, `sendChunk` (the response frame writer whose layout the
|
|
9
|
+
request frames mirror), `send`.
|
|
10
|
+
|
|
11
|
+
## Wire protocol (additions)
|
|
12
|
+
|
|
13
|
+
Existing messages are UNCHANGED. New:
|
|
14
|
+
|
|
15
|
+
Browser → Proxy, announcing a chunked request:
|
|
16
|
+
{ type: "request-start", requestId, method, path, query, headers,
|
|
17
|
+
bodyBytes } // bodyBytes = exact total body size in bytes
|
|
18
|
+
|
|
19
|
+
Browser → Proxy, body frames (BINARY messages — today the proxy only
|
|
20
|
+
ever receives strings, so binary is unambiguous):
|
|
21
|
+
byte 0 flags bit 0: done (last frame)
|
|
22
|
+
bit 1: aborted (drop this request, no reply)
|
|
23
|
+
byte 1 idLen requestId length in bytes
|
|
24
|
+
bytes 2..2+N requestId (ASCII)
|
|
25
|
+
bytes 2+N.. payload raw body bytes (UTF-8 of the body string;
|
|
26
|
+
may be empty on a done/abort frame)
|
|
27
|
+
|
|
28
|
+
Identical layout to the response frames (`sendChunk`) — one mental model,
|
|
29
|
+
and the browser already has a parser for it (its builder mirrors it).
|
|
30
|
+
|
|
31
|
+
No capability negotiation: POC, single-proxy pool, lockstep releases
|
|
32
|
+
(proxy first, then server). The 16 MB `maxMessageSize` advertisement in
|
|
33
|
+
webrtc-manager.js (pending 2.9.35) stays as a one-line transition cover
|
|
34
|
+
for tabs still running the single-send bundle.
|
|
35
|
+
|
|
36
|
+
## Constants
|
|
37
|
+
|
|
38
|
+
PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024
|
|
39
|
+
PARTIAL_REQUEST_TTL_MS = 60_000
|
|
40
|
+
|
|
41
|
+
## Assembly (all state per channel, inside `handleChannel`'s closure)
|
|
42
|
+
|
|
43
|
+
const partials = new Map(); // requestId → { meta, chunks: [], receivedBytes, timer }
|
|
44
|
+
|
|
45
|
+
- `request-start`: validate like a legacy request (same path allowlist —
|
|
46
|
+
run the SAME validation before accepting the body; reject with
|
|
47
|
+
`response-error` immediately on a bad path). Reject `bodyBytes` >
|
|
48
|
+
PROXY_MAX_REQUEST_BODY_BYTES with `response-error` "Request body too
|
|
49
|
+
large." and do NOT create state. Otherwise store `{ meta, chunks: [],
|
|
50
|
+
receivedBytes: 0 }` and arm the TTL timer.
|
|
51
|
+
- Binary frame: parse header; unknown requestId → ignore (stale/aborted).
|
|
52
|
+
bit 1 (aborted) → clear timer, delete entry, no reply. Append payload,
|
|
53
|
+
add to receivedBytes; receivedBytes > bodyBytes (or > the cap) →
|
|
54
|
+
`response-error` + drop. bit 0 (done): concat chunks → body string via
|
|
55
|
+
`Buffer.concat(...).toString("utf8")`; receivedBytes !== bodyBytes →
|
|
56
|
+
`response-error` "Request body size mismatch." and drop; else clear
|
|
57
|
+
timer, delete entry, and execute through the SAME code path a legacy
|
|
58
|
+
`request` message takes (factor `handleRequest` so both entry points
|
|
59
|
+
call one function with `{requestId, method, path, query, headers, body}`).
|
|
60
|
+
- TTL fire: delete entry, log
|
|
61
|
+
`[dc] Session …: dropped stale partial request <id8> (<receivedBytes>B)`.
|
|
62
|
+
- `channel.onClosed`: clear ALL timers and the map (extend the existing
|
|
63
|
+
handler — do not replace its logging).
|
|
64
|
+
|
|
65
|
+
## Logging
|
|
66
|
+
|
|
67
|
+
Chunked request execution logs the SAME `[dc] <method> <path>` line as
|
|
68
|
+
legacy, with `body=<bytes> bytes (chunked)`.
|
|
69
|
+
|
|
70
|
+
## Rules — do NOT
|
|
71
|
+
|
|
72
|
+
- Do NOT change the legacy `{type:"request"}` handling, the response
|
|
73
|
+
framing, ping/pong, or the path allowlist semantics.
|
|
74
|
+
- Do NOT add capability/version negotiation — POC decision, revisit only
|
|
75
|
+
when the pool has independently-updated proxies.
|
|
76
|
+
- Do NOT revert the 16 MB `maxMessageSize` advertisement (pending 2.9.35).
|
|
77
|
+
- Do NOT hold partial bodies beyond the TTL or channel lifetime; no global
|
|
78
|
+
(cross-channel) state.
|
|
79
|
+
- Do NOT create a new proxy version: fold into the pending 2.9.35
|
|
80
|
+
CHANGELOG entry (accumulate bullets, per the versioning rules) and the
|
|
81
|
+
pending addon 0.2.56 entry.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Proposal: Chunked request bodies over the data channel (proxy side)
|
|
2
|
+
|
|
3
|
+
## Why
|
|
4
|
+
|
|
5
|
+
The browser sends every request as ONE data-channel message, body included.
|
|
6
|
+
Registering a source carries the base64-encoded `.torrent` as that body — a
|
|
7
|
+
big multi-season pack (Poirot, 13 seasons: 420 KB `.torrent` → ~560 KB
|
|
8
|
+
base64) exceeded libdatachannel's default advertised `a=max-message-size`
|
|
9
|
+
of 256 KB, so the browser's `send()` threw "Trying to send message larger
|
|
10
|
+
than max-message-size" and playback dead-ended.
|
|
11
|
+
|
|
12
|
+
The committed-but-unpublished stopgap (advertise 16 MB, pending 2.9.35)
|
|
13
|
+
lifts the ceiling but keeps the flaw: any single-message body still has a
|
|
14
|
+
hard cap, and a large message is buffered whole on both ends. Responses
|
|
15
|
+
already solved this properly — they stream as small binary frames. Requests
|
|
16
|
+
should be symmetric.
|
|
17
|
+
|
|
18
|
+
## What Changes
|
|
19
|
+
|
|
20
|
+
- **Inbound binary body frames.** The proxy accepts request bodies as
|
|
21
|
+
binary frames with EXACTLY the response-frame layout
|
|
22
|
+
(`[flags][idLen][requestId][payload]`, bit 0 = done; new bit 1 = aborted),
|
|
23
|
+
announced by a new `{type:"request-start", …, bodyBytes}` control message.
|
|
24
|
+
On the done frame the assembled body runs through the SAME request
|
|
25
|
+
execution path as a legacy request. Bounded: per-body cap 32 MB, partial
|
|
26
|
+
bodies dropped after a 60 s TTL or an abort frame, all per-channel state
|
|
27
|
+
freed on channel close.
|
|
28
|
+
- **No capability negotiation.** POC: the pool is one proxy, released in
|
|
29
|
+
lockstep with the site (proxy first, then server). The browser just uses
|
|
30
|
+
chunked frames for large bodies; this proxy just understands them.
|
|
31
|
+
- **The 16 MB `max-message-size` advertisement (pending 2.9.35) stays** —
|
|
32
|
+
a single config value, no logic: it covers the transition window while
|
|
33
|
+
already-open tabs still run the single-send bundle.
|
|
34
|
+
- **Observability**: the `[dc]` request log line reports chunked bodies
|
|
35
|
+
(`body=<bytes> bytes (chunked)`).
|
|
36
|
+
|
|
37
|
+
Browser-side counterpart (chunk writer, threshold, backpressure, abort) is
|
|
38
|
+
the server repo's `chunked-request-bodies` change. Release order: proxy
|
|
39
|
+
(with addon bump) FIRST, then server.
|
|
40
|
+
|
|
41
|
+
## Capabilities
|
|
42
|
+
|
|
43
|
+
### New Capabilities
|
|
44
|
+
|
|
45
|
+
- `chunked-request-bodies`: request-body transport over the data channel.
|
|
46
|
+
|
|
47
|
+
## Impact
|
|
48
|
+
|
|
49
|
+
- `services/data-channel-handler.js` — binary inbound frame parsing;
|
|
50
|
+
per-channel partial-body assembly with caps/TTL; `request-start`
|
|
51
|
+
handling; shared execution path.
|
|
52
|
+
- Release: folds into the PENDING proxy 2.9.35 (extend its CHANGELOG entry;
|
|
53
|
+
do not create a new version) + ha-addon 0.2.56 (same rule).
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# chunked-request-bodies — delta spec (proxy)
|
|
2
|
+
|
|
3
|
+
## ADDED Requirements
|
|
4
|
+
|
|
5
|
+
### Requirement: Request bodies arrive in bounded binary chunks
|
|
6
|
+
|
|
7
|
+
The proxy SHALL accept a request whose body is delivered as binary frames
|
|
8
|
+
(mirroring the response-frame layout) announced by a `request-start`
|
|
9
|
+
control message, assemble it, and execute it through the same path as a
|
|
10
|
+
single-message request. Assembly SHALL be bounded: a per-body byte cap, a
|
|
11
|
+
TTL for incomplete bodies, an abort flag that drops the partial state, and
|
|
12
|
+
release of all partial state when the channel closes. Legacy single-message
|
|
13
|
+
requests SHALL keep working unchanged.
|
|
14
|
+
|
|
15
|
+
#### Scenario: Large .torrent registration
|
|
16
|
+
- **WHEN** the browser registers a multi-season torrent whose base64 body
|
|
17
|
+
exceeds any single-message limit
|
|
18
|
+
- **THEN** the body arrives in frames, the source registers, and the
|
|
19
|
+
response streams back exactly as for a small request
|
|
20
|
+
|
|
21
|
+
#### Scenario: Oversized or inconsistent body
|
|
22
|
+
- **WHEN** the announced or delivered size exceeds the cap, or the
|
|
23
|
+
delivered bytes do not match the announcement
|
|
24
|
+
- **THEN** the proxy replies with a response-error for that request and
|
|
25
|
+
drops the partial state; the channel and other requests are unaffected
|
|
26
|
+
|
|
27
|
+
#### Scenario: Sender vanishes mid-body
|
|
28
|
+
- **WHEN** frames stop arriving (tab closed, aborted without a frame)
|
|
29
|
+
- **THEN** the partial body is dropped after the TTL (or immediately on
|
|
30
|
+
channel close) and its memory is released
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Tasks: Chunked request bodies (proxy side)
|
|
2
|
+
|
|
3
|
+
Execute in order; design.md is normative. Read the code regions listed at
|
|
4
|
+
its top first.
|
|
5
|
+
|
|
6
|
+
## 1. Implementation
|
|
7
|
+
|
|
8
|
+
- [ ] 1.1 `data-channel-handler.js`: factor the execution tail of
|
|
9
|
+
`handleRequest` so a legacy `request` message and an assembled
|
|
10
|
+
chunked request run the SAME function. `node --check`.
|
|
11
|
+
- [ ] 1.2 `request-start` + binary inbound frames + per-channel assembly
|
|
12
|
+
with cap (32 MB), size-mismatch check, abort flag (bit 1), TTL
|
|
13
|
+
(60 s), cleanup on channel close. Unknown-requestId frames ignored.
|
|
14
|
+
- [ ] 1.3 Logging: `body=<bytes> bytes (chunked)` on execution; stale-drop
|
|
15
|
+
line on TTL.
|
|
16
|
+
|
|
17
|
+
## 2. Verification
|
|
18
|
+
|
|
19
|
+
- [ ] 2.1 Node loopback test (two node-datachannel PeerConnections in one
|
|
20
|
+
script, like the SDP test): drive a request-start + 64 KB frames of a
|
|
21
|
+
~600 KB body through a real channel into a handler instance wired to
|
|
22
|
+
a stub local server; assert the assembled body bytes match and a
|
|
23
|
+
response comes back. Also: abort frame → no reply, state dropped;
|
|
24
|
+
oversized announcement → response-error.
|
|
25
|
+
- [ ] 2.2 Legacy regression: single-message request path byte-identical
|
|
26
|
+
behaviour (run an existing small request through both entry points).
|
|
27
|
+
- [ ] 2.3 E2E (after the server-side change lands in preview): local stack
|
|
28
|
+
— preview server + local proxy (`node bin/cli.js --server-url
|
|
29
|
+
ws://localhost:8080`), register the real Poirot `.torrent`
|
|
30
|
+
(C:\Users\AntonNemtsev\Downloads\Пуаро_….torrent, ~560 KB base64)
|
|
31
|
+
via the UI; plan returns; `[dc] … body=… (chunked)` in the proxy log.
|
|
32
|
+
|
|
33
|
+
## 3. Release
|
|
34
|
+
|
|
35
|
+
- [ ] 3.1 EXTEND the pending 2.9.35 CHANGELOG entry (do not bump again) and
|
|
36
|
+
the pending addon 0.2.56 entry.
|
|
37
|
+
- [ ] 3.2 `npm run patch` in proxy (publishes 2.9.35), push addon bump,
|
|
38
|
+
update the addon in HA; verify `Starting @torrent-tv/proxy v2.9.35`
|
|
39
|
+
in the addon log. Proxy FIRST, then addon, then the server-side
|
|
40
|
+
change releases independently.
|
|
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
|
@@ -95,35 +95,149 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
95
95
|
* @returns {void}
|
|
96
96
|
*/
|
|
97
97
|
function handleChannel(sessionId, channel) {
|
|
98
|
-
|
|
98
|
+
const tag = sessionId.slice(0, 8);
|
|
99
|
+
log(`[dc] Session ${tag}: channel open`);
|
|
100
|
+
|
|
101
|
+
// Partial chunked-request bodies in flight on THIS channel, keyed by
|
|
102
|
+
// requestId. Each entry buffers frames until the done frame, then runs the
|
|
103
|
+
// assembled request through the same path as a single-message request.
|
|
104
|
+
/** @type {Map<string, { meta: object, chunks: Buffer[], receivedBytes: number, bodyBytes: number, timer: ReturnType<typeof setTimeout> }>} */
|
|
105
|
+
const partials = new Map();
|
|
106
|
+
|
|
107
|
+
const dropPartial = (requestId) => {
|
|
108
|
+
const entry = partials.get(requestId);
|
|
109
|
+
if (entry) {
|
|
110
|
+
clearTimeout(entry.timer);
|
|
111
|
+
partials.delete(requestId);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Begin assembling a chunked request. Validates the path and size up front
|
|
117
|
+
* so an invalid or oversized request never buffers a body.
|
|
118
|
+
*
|
|
119
|
+
* @param {any} message - The `request-start` control message.
|
|
120
|
+
*/
|
|
121
|
+
const startPartialRequest = (message) => {
|
|
122
|
+
const { requestId, method, path, query, headers, bodyBytes } = message ?? {};
|
|
123
|
+
if (typeof requestId !== "string" || requestId.length === 0) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (!isValidRequestPath(path)) {
|
|
127
|
+
send(channel, { type: "response-error", requestId, error: "Invalid request path." });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (!Number.isInteger(bodyBytes) || bodyBytes < 0 || bodyBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
|
|
131
|
+
send(channel, { type: "response-error", requestId, error: "Request body too large." });
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
dropPartial(requestId); // replace any stale entry with the same id
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
const entry = partials.get(requestId);
|
|
137
|
+
partials.delete(requestId);
|
|
138
|
+
log(`[dc] Session ${tag}: dropped stale partial request ${requestId.slice(0, 8)} (${entry?.receivedBytes ?? 0}B)`);
|
|
139
|
+
}, PARTIAL_REQUEST_TTL_MS);
|
|
140
|
+
partials.set(requestId, {
|
|
141
|
+
meta: { requestId, method, path, query, headers },
|
|
142
|
+
chunks: [],
|
|
143
|
+
receivedBytes: 0,
|
|
144
|
+
bodyBytes,
|
|
145
|
+
timer
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Handle a binary body frame for a chunked request.
|
|
151
|
+
* Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
|
|
152
|
+
*
|
|
153
|
+
* @param {Buffer} buf
|
|
154
|
+
*/
|
|
155
|
+
const handleBodyFrame = (buf) => {
|
|
156
|
+
if (buf.length < 2) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const flags = buf[0];
|
|
160
|
+
const idLen = buf[1];
|
|
161
|
+
if (buf.length < 2 + idLen) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const requestId = buf.toString("ascii", 2, 2 + idLen);
|
|
165
|
+
const entry = partials.get(requestId);
|
|
166
|
+
if (!entry) {
|
|
167
|
+
return; // stale / already-dropped / aborted
|
|
168
|
+
}
|
|
169
|
+
if (flags & 2) {
|
|
170
|
+
// Aborted by the browser — drop silently, no reply.
|
|
171
|
+
dropPartial(requestId);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (buf.length > 2 + idLen) {
|
|
175
|
+
const payload = buf.subarray(2 + idLen);
|
|
176
|
+
entry.chunks.push(Buffer.from(payload));
|
|
177
|
+
entry.receivedBytes += payload.length;
|
|
178
|
+
}
|
|
179
|
+
if (entry.receivedBytes > entry.bodyBytes || entry.receivedBytes > PROXY_MAX_REQUEST_BODY_BYTES) {
|
|
180
|
+
dropPartial(requestId);
|
|
181
|
+
send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (flags & 1) {
|
|
185
|
+
// Done frame — assemble and execute.
|
|
186
|
+
dropPartial(requestId);
|
|
187
|
+
if (entry.receivedBytes !== entry.bodyBytes) {
|
|
188
|
+
send(channel, { type: "response-error", requestId, error: "Request body size mismatch." });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const body = Buffer.concat(entry.chunks).toString("utf8");
|
|
192
|
+
void handleRequest(channel, { ...entry.meta, body }, true).catch((error) => {
|
|
193
|
+
log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
};
|
|
99
197
|
|
|
100
198
|
channel.onMessage((raw) => {
|
|
101
|
-
|
|
199
|
+
// Binary messages are chunked-request body frames; the proxy otherwise
|
|
200
|
+
// only ever receives JSON strings, so the type discriminates cleanly.
|
|
201
|
+
if (typeof raw !== "string") {
|
|
202
|
+
handleBodyFrame(Buffer.isBuffer(raw) ? raw : Buffer.from(raw));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** @type {DataChannelRequest | { type: string, id?: string }} */
|
|
102
207
|
let message;
|
|
103
208
|
try {
|
|
104
|
-
message = JSON.parse(
|
|
209
|
+
message = JSON.parse(raw);
|
|
105
210
|
} catch {
|
|
106
211
|
return;
|
|
107
212
|
}
|
|
108
213
|
|
|
109
214
|
if (message.type === "request") {
|
|
110
215
|
void handleRequest(channel, message).catch((error) => {
|
|
111
|
-
log(`[dc] Session ${
|
|
216
|
+
log(`[dc] Session ${tag}: request error: ${error?.message ?? error}`);
|
|
112
217
|
});
|
|
113
218
|
return;
|
|
114
219
|
}
|
|
115
220
|
|
|
221
|
+
if (message.type === "request-start") {
|
|
222
|
+
startPartialRequest(message);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
116
226
|
if (message.type === "ping") {
|
|
117
227
|
send(channel, { type: "pong", id: message.id });
|
|
118
228
|
}
|
|
119
229
|
});
|
|
120
230
|
|
|
121
231
|
channel.onClosed(() => {
|
|
122
|
-
|
|
232
|
+
for (const entry of partials.values()) {
|
|
233
|
+
clearTimeout(entry.timer);
|
|
234
|
+
}
|
|
235
|
+
partials.clear();
|
|
236
|
+
log(`[dc] Session ${tag}: channel closed`);
|
|
123
237
|
});
|
|
124
238
|
|
|
125
239
|
channel.onError((err) => {
|
|
126
|
-
log(`[dc] Session ${
|
|
240
|
+
log(`[dc] Session ${tag}: channel error: ${err}`);
|
|
127
241
|
});
|
|
128
242
|
}
|
|
129
243
|
|
|
@@ -138,24 +252,22 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
138
252
|
* @param {DataChannelRequest} req
|
|
139
253
|
* @returns {Promise<void>}
|
|
140
254
|
*/
|
|
141
|
-
async function handleRequest(channel, req) {
|
|
255
|
+
async function handleRequest(channel, req, viaChunks = false) {
|
|
142
256
|
const { requestId, method, path, query, headers: forwardedHeaders, body } = req;
|
|
143
257
|
|
|
144
258
|
// Reject paths that are not absolute, contain traversal sequences, or
|
|
145
259
|
// do not start with a known proxy route prefix. All valid browser-side
|
|
146
260
|
// requests use /api/*, /stream, /transcode/*, /health, or /healthz.
|
|
147
|
-
if (
|
|
148
|
-
typeof path !== "string" ||
|
|
149
|
-
!path.startsWith("/") ||
|
|
150
|
-
path.includes("..") ||
|
|
151
|
-
!PATH_ALLOWLIST_RE.test(path)
|
|
152
|
-
) {
|
|
261
|
+
if (!isValidRequestPath(path)) {
|
|
153
262
|
send(channel, { type: "response-error", requestId, error: "Invalid request path." });
|
|
154
263
|
return;
|
|
155
264
|
}
|
|
156
265
|
|
|
157
266
|
const queryInfo = query ? `?${query}` : "";
|
|
158
|
-
const bodyInfo =
|
|
267
|
+
const bodyInfo =
|
|
268
|
+
body != null && typeof body === "string" && body.length > 0
|
|
269
|
+
? ` body=${body.length} bytes${viaChunks ? " (chunked)" : ""}`
|
|
270
|
+
: "";
|
|
159
271
|
log(`[dc] ${method} ${path}${queryInfo}${bodyInfo}`);
|
|
160
272
|
|
|
161
273
|
const targetUrl = `http://127.0.0.1:${proxyPort}${path}${query ? `?${query}` : ""}`;
|
|
@@ -328,6 +440,27 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
328
440
|
*/
|
|
329
441
|
const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
|
|
330
442
|
|
|
443
|
+
/**
|
|
444
|
+
* True when `path` is an absolute, traversal-free path on a known proxy route.
|
|
445
|
+
* Shared by the single-message and chunked request entry points.
|
|
446
|
+
*
|
|
447
|
+
* @param {unknown} path
|
|
448
|
+
* @returns {boolean}
|
|
449
|
+
*/
|
|
450
|
+
function isValidRequestPath(path) {
|
|
451
|
+
return (
|
|
452
|
+
typeof path === "string" &&
|
|
453
|
+
path.startsWith("/") &&
|
|
454
|
+
!path.includes("..") &&
|
|
455
|
+
PATH_ALLOWLIST_RE.test(path)
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Max assembled size of a chunked request body (guards proxy memory). */
|
|
460
|
+
const PROXY_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
|
|
461
|
+
/** Drop an incomplete chunked body if no further frame arrives within this window. */
|
|
462
|
+
const PARTIAL_REQUEST_TTL_MS = 60_000;
|
|
463
|
+
|
|
331
464
|
/** Pause sending body chunks once the channel buffer exceeds this many bytes. */
|
|
332
465
|
const DC_BUFFER_HIGH_WATER = 8 * 1024 * 1024;
|
|
333
466
|
/** Resume sending once the channel buffer drains to this many bytes. */
|
|
@@ -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
|
-
|
|
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
|
-
//
|
|
1499
|
-
//
|
|
1500
|
-
//
|
|
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
|
-
|
|
1508
|
-
|
|
1509
|
-
);
|
|
1510
|
-
this.#startEncodeRun(session,
|
|
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);
|