@torrent-tv/proxy 2.9.0 → 2.9.3
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 +5 -0
- package/CLAUDE.md +62 -0
- package/package.json +1 -1
- package/services/data-channel-handler.js +108 -13
- package/services/hls-session-manager.js +1 -1
- package/services/hwaccel.js +108 -35
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
## 2.9.3
|
|
2
|
+
|
|
3
|
+
- **New**: WebRTC data-channel response bodies are now sent as **binary** frames (`sendMessageBinary`) instead of base64-encoded JSON `response-chunk` messages, removing the ~33% base64 overhead and the JSON encode cost. Frame layout: `[flags(1)][idLen(1)][requestId(ASCII)][payload]`. Control messages (`response-start`, `response-error`, `pong`) remain JSON strings. Requires the matching browser client (server ≥ 0.8.0); **deploy the server before the proxy**.
|
|
4
|
+
- **New**: Backpressure on the send loop — `data-channel-handler.js` pauses queuing body chunks once the channel's `bufferedAmount()` exceeds 8 MB and resumes when it drains below 1 MB (`setBufferedAmountLowThreshold` + `onBufferedAmountLow`), with a 5 s timeout fallback. Prevents the SCTP send buffer from ballooning and stalling throughput.
|
|
5
|
+
|
|
1
6
|
## 2.6.3
|
|
2
7
|
|
|
3
8
|
- **Fix**: Data channel handler now logs **all** requests regardless of body presence — `GET /transcode/…`, `GET /api/…/progress`, `GET /api/…/stats` etc. were previously invisible in logs. Non-2xx response statuses and fetch errors are also logged, enabling diagnosis of HLS manifest load failures.
|
package/CLAUDE.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# proxy — @torrent-tv/proxy (WebTorrent + ffmpeg)
|
|
2
|
+
|
|
3
|
+
Downloads a torrent and streams the chosen file to the browser, transcoding to
|
|
4
|
+
HLS only when needed. See the parent `../CLAUDE.md` for the overall architecture
|
|
5
|
+
and release process.
|
|
6
|
+
|
|
7
|
+
## Deployment-agnostic — important
|
|
8
|
+
|
|
9
|
+
The HA addon is only ONE way to run this; bare npm and Docker are planned. Keep
|
|
10
|
+
all code free of Home-Assistant assumptions. Anything host-specific (GPU
|
|
11
|
+
devices, ffmpeg build, CLI flags) belongs in the `ha-addon` layer. Hardware
|
|
12
|
+
detection must probe at runtime and fall back gracefully; do not assume a
|
|
13
|
+
Linux-only host (e.g. POSIX-only signals must degrade elsewhere).
|
|
14
|
+
|
|
15
|
+
## Layout
|
|
16
|
+
|
|
17
|
+
- `bin/cli.js` — CLI entry; resolves `ffmpegBin` (uses `--ffmpeg-bin` if given,
|
|
18
|
+
else bundled ffmpeg-static, else PATH `ffmpeg`).
|
|
19
|
+
- `server.js` — Fastify setup; detects the video encoder at startup
|
|
20
|
+
(`detectVideoEncoder`) and passes it to `HlsSessionManager`.
|
|
21
|
+
- `routes/<path>/<method>.js` — same convention as the server repo.
|
|
22
|
+
- `routes/stream/get.js` — byte-range torrent file streaming (HTTP 206).
|
|
23
|
+
- `routes/api/playback-plan/post.js` — codec/container/duration probe result.
|
|
24
|
+
- `routes/transcode/session-file/get.js` — serves HLS playlist/segments;
|
|
25
|
+
long-polls while a segment is being produced, returns retryable 503 (never
|
|
26
|
+
202 — hls.js can't consume it).
|
|
27
|
+
- `services/`:
|
|
28
|
+
- `playback-planner.js` — single ffmpeg probe returns audioCodec, videoCodec,
|
|
29
|
+
container, durationSeconds. `mode` is advisory; the browser decides.
|
|
30
|
+
- `hls-session-manager.js` — one ffmpeg per (source, file, settings). Serves a
|
|
31
|
+
synthetic full-duration VOD playlist; produces segments on demand; restarts
|
|
32
|
+
ffmpeg at the requested segment for server-side seeking. Short idle TTL.
|
|
33
|
+
Uses the detected `videoEncoder` for video re-encode (copy otherwise).
|
|
34
|
+
- `hwaccel.js` — detect best H.264 encoder (NVENC/QSV/VAAPI/V4L2M2M) with a
|
|
35
|
+
STRICT startup test: encode `testsrc2` through the real HLS pipeline, then
|
|
36
|
+
verify each segment decodes independently (catches non-IDR/corrupted hw
|
|
37
|
+
output). Falls back to software libx264. Runtime fallback to software if a
|
|
38
|
+
hw encode later fails. v4l2m2m is gated by this test (fails on HA Yellow).
|
|
39
|
+
- `data-channel-handler.js` — forwards WebRTC data-channel requests to the
|
|
40
|
+
local HTTP server (loopback), so the same routes serve both transports.
|
|
41
|
+
|
|
42
|
+
## Gotchas
|
|
43
|
+
|
|
44
|
+
- Do NOT use `-hls_playlist_type event` — it breaks duration/seek. VOD only.
|
|
45
|
+
- A transitive dep (`ip-set`, via webtorrent) ships a hostile
|
|
46
|
+
`preinstall: npx only-allow pnpm` that breaks `npm install`. The addon works
|
|
47
|
+
around it with `--ignore-scripts` + a targeted rebuild of `node-datachannel`;
|
|
48
|
+
if you ever change install flow, keep that in mind.
|
|
49
|
+
|
|
50
|
+
## Changelog
|
|
51
|
+
|
|
52
|
+
Every behavioural change must be recorded in `CHANGELOG.md` — add an entry under
|
|
53
|
+
a new `## <version>` heading at the top (the next patch version that
|
|
54
|
+
`npm run patch` will publish), following the existing
|
|
55
|
+
`- **New**/**Fix**/**Chore**:` format. See the parent `../CLAUDE.md`.
|
|
56
|
+
|
|
57
|
+
## Release
|
|
58
|
+
|
|
59
|
+
`npm run patch` (publishes to npm + pushes tags). The HA addon then needs its
|
|
60
|
+
own version bump to pull the new package. Publish proxy BEFORE bumping the addon.
|
|
61
|
+
|
|
62
|
+
**Any proxy change requires bumping the ha-addon version** (`ha-addon/torrent_tv_proxy/config.yaml`). The addon installs the proxy from npm at build time and the build is cached; without a version bump the plugin will NOT update and keeps running the old proxy. So after `npm run patch`, always bump the addon `config.yaml` version, push, and update the addon.
|
package/package.json
CHANGED
|
@@ -16,12 +16,23 @@
|
|
|
16
16
|
*
|
|
17
17
|
* Proxy → Browser
|
|
18
18
|
* ```
|
|
19
|
-
* { type: "response-start", requestId, status, headers }
|
|
20
|
-
* { type: "response-
|
|
21
|
-
* { type: "
|
|
22
|
-
* { type: "pong", id }
|
|
19
|
+
* { type: "response-start", requestId, status, headers } (JSON string)
|
|
20
|
+
* { type: "response-error", requestId, error: string } (JSON string)
|
|
21
|
+
* { type: "pong", id } (JSON string)
|
|
23
22
|
* ```
|
|
24
23
|
*
|
|
24
|
+
* Response bodies are sent as BINARY data-channel messages (not JSON), to
|
|
25
|
+
* avoid the ~33% base64 overhead and the JSON encode/decode cost. Each binary
|
|
26
|
+
* frame is laid out as:
|
|
27
|
+
* ```
|
|
28
|
+
* byte 0 flags (bit 0: done)
|
|
29
|
+
* byte 1 idLen (length of the requestId in bytes)
|
|
30
|
+
* bytes 2..2+N requestId (ASCII)
|
|
31
|
+
* bytes 2+N.. payload (raw body bytes; empty on the final done frame)
|
|
32
|
+
* ```
|
|
33
|
+
* Control messages stay JSON strings so the browser can distinguish them from
|
|
34
|
+
* body frames by message type (string vs ArrayBuffer).
|
|
35
|
+
*
|
|
25
36
|
* The protocol mirrors the tunnel relay protocol so both transports share
|
|
26
37
|
* the same mental model and the same browser-side `WebRtcProxy` implementation.
|
|
27
38
|
*/
|
|
@@ -177,30 +188,107 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
177
188
|
send(channel, { type: "response-start", requestId, status: response.status, headers: responseHeaders });
|
|
178
189
|
|
|
179
190
|
if (!response.body) {
|
|
180
|
-
|
|
191
|
+
sendChunk(channel, requestId, null, true);
|
|
181
192
|
return;
|
|
182
193
|
}
|
|
183
194
|
|
|
184
195
|
try {
|
|
185
196
|
const reader = response.body.getReader();
|
|
197
|
+
// [net-debug] TEMPORARY: measure transfer size/time and channel buffering.
|
|
198
|
+
const sendStartedAt = Date.now();
|
|
199
|
+
let totalBytes = 0;
|
|
200
|
+
let maxBuffered = 0;
|
|
186
201
|
while (true) {
|
|
187
202
|
const { done, value } = await reader.read();
|
|
188
203
|
if (done) {
|
|
189
|
-
|
|
204
|
+
sendChunk(channel, requestId, null, true);
|
|
205
|
+
const elapsedMs = Date.now() - sendStartedAt;
|
|
206
|
+
let bufferedNow = 0;
|
|
207
|
+
try { bufferedNow = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0; } catch { /* ignore */ }
|
|
208
|
+
log(
|
|
209
|
+
`[net-debug] sent ${path}${queryInfo} bytes=${totalBytes} ms=${elapsedMs} ` +
|
|
210
|
+
`maxBuffered=${maxBuffered} bufferedAtEnd=${bufferedNow}`
|
|
211
|
+
);
|
|
190
212
|
break;
|
|
191
213
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
214
|
+
totalBytes += value.length;
|
|
215
|
+
try {
|
|
216
|
+
const b = typeof channel.bufferedAmount === "function" ? channel.bufferedAmount() : 0;
|
|
217
|
+
if (b > maxBuffered) maxBuffered = b;
|
|
218
|
+
} catch { /* ignore */ }
|
|
219
|
+
sendChunk(channel, requestId, value, false);
|
|
220
|
+
// Backpressure: do not keep queuing chunks once the channel's outgoing
|
|
221
|
+
// buffer is large — wait for it to drain. Prevents the SCTP send buffer
|
|
222
|
+
// from ballooning, which stalls throughput.
|
|
223
|
+
await waitForBufferDrain(channel);
|
|
198
224
|
}
|
|
199
225
|
} catch {
|
|
200
|
-
|
|
226
|
+
sendChunk(channel, requestId, null, true);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Send a response body frame as a BINARY data-channel message.
|
|
232
|
+
* Layout: [flags(1)][idLen(1)][requestId(ASCII)][payload].
|
|
233
|
+
*
|
|
234
|
+
* @param {DataChannel} channel
|
|
235
|
+
* @param {string} requestId
|
|
236
|
+
* @param {Uint8Array | null} bytes - Body bytes, or null/empty for the done frame.
|
|
237
|
+
* @param {boolean} done
|
|
238
|
+
* @returns {void}
|
|
239
|
+
*/
|
|
240
|
+
function sendChunk(channel, requestId, bytes, done) {
|
|
241
|
+
try {
|
|
242
|
+
const idBuf = Buffer.from(requestId, "ascii");
|
|
243
|
+
const header = Buffer.allocUnsafe(2 + idBuf.length);
|
|
244
|
+
header[0] = done ? 1 : 0;
|
|
245
|
+
header[1] = idBuf.length;
|
|
246
|
+
idBuf.copy(header, 2);
|
|
247
|
+
const frame =
|
|
248
|
+
bytes && bytes.length > 0 ? Buffer.concat([header, Buffer.from(bytes)]) : header;
|
|
249
|
+
channel.sendMessageBinary(frame);
|
|
250
|
+
} catch {
|
|
251
|
+
// Channel closed between check and send — safe to ignore.
|
|
201
252
|
}
|
|
202
253
|
}
|
|
203
254
|
|
|
255
|
+
/**
|
|
256
|
+
* Resolve once the channel's outgoing buffer has drained below the low-water
|
|
257
|
+
* mark. No-op (resolves immediately) when the buffer is already small or the
|
|
258
|
+
* channel does not expose buffer APIs. A timeout fallback guards against a
|
|
259
|
+
* missed low-water event so the send loop can never deadlock.
|
|
260
|
+
*
|
|
261
|
+
* @param {DataChannel} channel
|
|
262
|
+
* @returns {Promise<void>}
|
|
263
|
+
*/
|
|
264
|
+
function waitForBufferDrain(channel) {
|
|
265
|
+
return new Promise((resolve) => {
|
|
266
|
+
try {
|
|
267
|
+
if (typeof channel.bufferedAmount !== "function" || channel.bufferedAmount() <= DC_BUFFER_HIGH_WATER) {
|
|
268
|
+
resolve();
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
let settled = false;
|
|
272
|
+
const done = () => {
|
|
273
|
+
if (settled) return;
|
|
274
|
+
settled = true;
|
|
275
|
+
resolve();
|
|
276
|
+
};
|
|
277
|
+
channel.setBufferedAmountLowThreshold(DC_BUFFER_LOW_WATER);
|
|
278
|
+
channel.onBufferedAmountLow(done);
|
|
279
|
+
// Guard against a race where the buffer drained between the check above
|
|
280
|
+
// and registering the callback (the low-water event would never fire).
|
|
281
|
+
if (channel.bufferedAmount() <= DC_BUFFER_LOW_WATER) {
|
|
282
|
+
done();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
setTimeout(done, DC_BUFFER_DRAIN_TIMEOUT_MS);
|
|
286
|
+
} catch {
|
|
287
|
+
resolve();
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
204
292
|
/**
|
|
205
293
|
* Serialise `message` to JSON and send it over the data channel.
|
|
206
294
|
* Errors are silently swallowed — the channel may have closed between
|
|
@@ -226,3 +314,10 @@ export function createDataChannelHandler({ proxyPort, onLog }) {
|
|
|
226
314
|
* Only the known proxy API and streaming routes are accepted.
|
|
227
315
|
*/
|
|
228
316
|
const PATH_ALLOWLIST_RE = /^(?:\/api\/|\/stream(?:$|\?)|\/?transcode\/|\/health(?:z)?(?:$|\?))/;
|
|
317
|
+
|
|
318
|
+
/** Pause sending body chunks once the channel buffer exceeds this many bytes. */
|
|
319
|
+
const DC_BUFFER_HIGH_WATER = 8 * 1024 * 1024;
|
|
320
|
+
/** Resume sending once the channel buffer drains to this many bytes. */
|
|
321
|
+
const DC_BUFFER_LOW_WATER = 1 * 1024 * 1024;
|
|
322
|
+
/** Safety fallback so the send loop cannot deadlock on a missed drain event. */
|
|
323
|
+
const DC_BUFFER_DRAIN_TIMEOUT_MS = 5000;
|
|
@@ -512,7 +512,7 @@ export class HlsSessionManager {
|
|
|
512
512
|
|
|
513
513
|
logger.info(
|
|
514
514
|
`transcode ${sessionId} start "${logName}" ` +
|
|
515
|
-
`video=${transcodeVideo ?
|
|
515
|
+
`video=${transcodeVideo ? this.videoEncoder.name : "copy"} audio=${transcodeAudio ? "aac" : "copy"} ` +
|
|
516
516
|
`duration=${hasDuration ? formatSeconds(durationSeconds) : "unknown"} segments=${segmentCount}`
|
|
517
517
|
);
|
|
518
518
|
|
package/services/hwaccel.js
CHANGED
|
@@ -21,7 +21,9 @@
|
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
23
|
import { spawn } from "node:child_process";
|
|
24
|
-
import { readdirSync } from "node:fs";
|
|
24
|
+
import { mkdtempSync, readdirSync, rmSync } from "node:fs";
|
|
25
|
+
import os from "node:os";
|
|
26
|
+
import path from "node:path";
|
|
25
27
|
|
|
26
28
|
const SOFTWARE_PRESET = "superfast";
|
|
27
29
|
const SOFTWARE_CRF = "24";
|
|
@@ -141,8 +143,11 @@ function nvencDescriptor() {
|
|
|
141
143
|
|
|
142
144
|
/** @returns {import("./hwaccel.js").VideoEncoderDescriptor} */
|
|
143
145
|
function v4l2m2mDescriptor() {
|
|
144
|
-
// ARM SoC (e.g. Raspberry Pi) stateful M2M encoder. No GPU
|
|
145
|
-
// software,
|
|
146
|
+
// ARM SoC (e.g. Raspberry Pi / HA Yellow) stateful M2M encoder. No GPU
|
|
147
|
+
// scaler — scale in software, hand YUV420 frames to the hardware encoder.
|
|
148
|
+
// `-g` aligns the GOP to the segment length so an IDR lands on every segment
|
|
149
|
+
// boundary; this is verified by the keyframe-alignment test before use,
|
|
150
|
+
// because v4l2m2m does not always honour these hints.
|
|
146
151
|
return {
|
|
147
152
|
name: "h264_v4l2m2m",
|
|
148
153
|
kind: "v4l2m2m",
|
|
@@ -155,12 +160,14 @@ function v4l2m2mDescriptor() {
|
|
|
155
160
|
`scale=${w}:${h}:force_original_aspect_ratio=decrease:force_divisible_by=2,fps=${TRANSCODE_FPS},format=yuv420p`,
|
|
156
161
|
"-c:v", "h264_v4l2m2m",
|
|
157
162
|
"-b:v", "3M",
|
|
163
|
+
"-g", String(TRANSCODE_FPS * segmentDurationSec),
|
|
158
164
|
...keyFrameArgs(segmentDurationSec)
|
|
159
165
|
];
|
|
160
166
|
}
|
|
161
167
|
};
|
|
162
168
|
}
|
|
163
169
|
|
|
170
|
+
|
|
164
171
|
/**
|
|
165
172
|
* @typedef {Object} VideoEncoderDescriptor
|
|
166
173
|
* @property {string} name
|
|
@@ -253,44 +260,89 @@ function hasV4l2Device() {
|
|
|
253
260
|
}
|
|
254
261
|
|
|
255
262
|
/**
|
|
256
|
-
*
|
|
257
|
-
*
|
|
263
|
+
* Build a full ffmpeg command that encodes a short, *moving* synthetic clip
|
|
264
|
+
* (testsrc2 — far more representative than a static black frame) through the
|
|
265
|
+
* candidate encoder into real HLS segments in `outDir`, with keyframes forced
|
|
266
|
+
* on segment boundaries. Verifying the resulting segments (see
|
|
267
|
+
* {@link verifySegmentsDecodeCleanly}) catches encoders that silently produce
|
|
268
|
+
* a corrupted or non-IDR-aligned stream (e.g. some V4L2 M2M builds).
|
|
258
269
|
*
|
|
259
270
|
* @param {VideoEncoderDescriptor} descriptor
|
|
271
|
+
* @param {number} segmentDurationSec
|
|
272
|
+
* @param {string} outDir
|
|
260
273
|
* @returns {string[]}
|
|
261
274
|
*/
|
|
262
|
-
function
|
|
263
|
-
const
|
|
275
|
+
function buildEncoderTestArgs(descriptor, segmentDurationSec, outDir) {
|
|
276
|
+
const durationSec = Math.max(8, segmentDurationSec * 3);
|
|
277
|
+
const source = ["-f", "lavfi", "-i", `testsrc2=s=640x360:r=${TRANSCODE_FPS}:d=${durationSec}`];
|
|
278
|
+
const kf = keyFrameArgs(segmentDurationSec);
|
|
279
|
+
|
|
280
|
+
/** @type {string[]} */
|
|
281
|
+
let pre = ["-hide_banner", "-loglevel", "error"];
|
|
282
|
+
/** @type {string[]} */
|
|
283
|
+
let encode;
|
|
264
284
|
switch (descriptor.kind) {
|
|
265
285
|
case "vaapi":
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
...src,
|
|
270
|
-
"-vf", "format=nv12,hwupload", "-c:v", "h264_vaapi",
|
|
271
|
-
"-f", "null", "-"
|
|
272
|
-
];
|
|
286
|
+
pre = [...pre, "-vaapi_device", String(descriptor.device)];
|
|
287
|
+
encode = ["-vf", "format=nv12,hwupload", "-c:v", "h264_vaapi", "-qp", "24", ...kf];
|
|
288
|
+
break;
|
|
273
289
|
case "qsv":
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
...src,
|
|
278
|
-
"-vf", "hwupload=extra_hw_frames=16,format=qsv", "-c:v", "h264_qsv",
|
|
279
|
-
"-f", "null", "-"
|
|
280
|
-
];
|
|
290
|
+
pre = [...pre, "-qsv_device", String(descriptor.device)];
|
|
291
|
+
encode = ["-vf", "hwupload=extra_hw_frames=16,format=qsv", "-c:v", "h264_qsv", "-global_quality", "24", ...kf];
|
|
292
|
+
break;
|
|
281
293
|
case "nvenc":
|
|
282
|
-
|
|
294
|
+
encode = ["-c:v", "h264_nvenc", "-preset", "p4", "-cq", "24", "-pix_fmt", "yuv420p", ...kf];
|
|
295
|
+
break;
|
|
283
296
|
case "v4l2m2m":
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
...src, "-pix_fmt", "yuv420p", "-c:v", "h264_v4l2m2m", "-f", "null", "-"
|
|
287
|
-
];
|
|
297
|
+
encode = ["-pix_fmt", "yuv420p", "-c:v", "h264_v4l2m2m", "-b:v", "3M", "-g", String(TRANSCODE_FPS * segmentDurationSec), ...kf];
|
|
298
|
+
break;
|
|
288
299
|
default:
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
...src, "-c:v", "libx264", "-preset", "ultrafast", "-f", "null", "-"
|
|
292
|
-
];
|
|
300
|
+
encode = ["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", ...kf];
|
|
301
|
+
break;
|
|
293
302
|
}
|
|
303
|
+
|
|
304
|
+
const hlsOut = [
|
|
305
|
+
"-f", "hls",
|
|
306
|
+
"-hls_time", String(segmentDurationSec),
|
|
307
|
+
"-hls_list_size", "0",
|
|
308
|
+
"-hls_flags", "independent_segments",
|
|
309
|
+
"-hls_segment_filename", path.join(outDir, "seg-%03d.ts"),
|
|
310
|
+
path.join(outDir, "index.m3u8")
|
|
311
|
+
];
|
|
312
|
+
return [...pre, ...source, ...encode, ...hlsOut];
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Verify the HLS segments produced by the test encode are valid: at least two
|
|
317
|
+
* segments exist, and each decodes standalone without errors. A segment that
|
|
318
|
+
* does not begin with a keyframe (broken/corrupted output) emits decode errors
|
|
319
|
+
* when read on its own, which fails this check.
|
|
320
|
+
*
|
|
321
|
+
* @param {string} ffmpegBin
|
|
322
|
+
* @param {string} outDir
|
|
323
|
+
* @returns {Promise<boolean>}
|
|
324
|
+
*/
|
|
325
|
+
async function verifySegmentsDecodeCleanly(ffmpegBin, outDir) {
|
|
326
|
+
let files;
|
|
327
|
+
try {
|
|
328
|
+
files = readdirSync(outDir).filter((n) => /^seg-\d+\.ts$/.test(n)).sort();
|
|
329
|
+
} catch {
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
if (files.length < 2) {
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
for (const file of files) {
|
|
336
|
+
const result = await runFfmpeg(
|
|
337
|
+
ffmpegBin,
|
|
338
|
+
["-hide_banner", "-loglevel", "error", "-i", path.join(outDir, file), "-f", "null", "-"],
|
|
339
|
+
8000
|
|
340
|
+
);
|
|
341
|
+
if (result.code !== 0 || result.stderr.trim().length > 0) {
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return true;
|
|
294
346
|
}
|
|
295
347
|
|
|
296
348
|
/**
|
|
@@ -298,10 +350,10 @@ function testEncodeArgs(descriptor) {
|
|
|
298
350
|
* software libx264). Each hardware candidate is verified with a real
|
|
299
351
|
* test-encode before being selected.
|
|
300
352
|
*
|
|
301
|
-
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void } }} options
|
|
353
|
+
* @param {{ ffmpegBin: string, logger?: { info: (m: string) => void, warn: (m: string) => void }, segmentDurationSec?: number }} options
|
|
302
354
|
* @returns {Promise<VideoEncoderDescriptor>}
|
|
303
355
|
*/
|
|
304
|
-
export async function detectVideoEncoder({ ffmpegBin, logger }) {
|
|
356
|
+
export async function detectVideoEncoder({ ffmpegBin, logger, segmentDurationSec = 4 }) {
|
|
305
357
|
const log = logger ?? { info: () => {}, warn: () => {} };
|
|
306
358
|
const software = softwareDescriptor();
|
|
307
359
|
|
|
@@ -324,20 +376,41 @@ export async function detectVideoEncoder({ ffmpegBin, logger }) {
|
|
|
324
376
|
if (has("h264_vaapi") && renderNodes.length > 0) {
|
|
325
377
|
candidates.push(vaapiDescriptor(renderNodes[0]));
|
|
326
378
|
}
|
|
379
|
+
// h264_v4l2m2m (ARM SoC / Raspberry Pi / HA Yellow). It is gated behind the
|
|
380
|
+
// strict keyframe-alignment test below, because some V4L2 M2M builds silently
|
|
381
|
+
// emit a corrupted / non-IDR-aligned stream; the test rejects those and the
|
|
382
|
+
// host falls back to software libx264.
|
|
327
383
|
if (has("h264_v4l2m2m") && hasV4l2Device()) {
|
|
328
384
|
candidates.push(v4l2m2mDescriptor());
|
|
329
385
|
}
|
|
330
386
|
|
|
331
387
|
for (const candidate of candidates) {
|
|
332
|
-
const
|
|
333
|
-
|
|
388
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), "tt-hwtest-"));
|
|
389
|
+
let ok = false;
|
|
390
|
+
try {
|
|
391
|
+
const encoded = await runFfmpeg(
|
|
392
|
+
ffmpegBin,
|
|
393
|
+
buildEncoderTestArgs(candidate, segmentDurationSec, dir),
|
|
394
|
+
25000
|
|
395
|
+
);
|
|
396
|
+
if (encoded.code === 0) {
|
|
397
|
+
ok = await verifySegmentsDecodeCleanly(ffmpegBin, dir);
|
|
398
|
+
}
|
|
399
|
+
} finally {
|
|
400
|
+
try {
|
|
401
|
+
rmSync(dir, { recursive: true, force: true });
|
|
402
|
+
} catch {
|
|
403
|
+
// best effort
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (ok) {
|
|
334
407
|
log.info(
|
|
335
408
|
`hwaccel: using hardware encoder ${candidate.name}` +
|
|
336
409
|
`${candidate.device ? ` (${candidate.device})` : ""}`
|
|
337
410
|
);
|
|
338
411
|
return candidate;
|
|
339
412
|
}
|
|
340
|
-
log.warn(`hwaccel: ${candidate.name}
|
|
413
|
+
log.warn(`hwaccel: ${candidate.name} failed the HLS keyframe-alignment test; skipping`);
|
|
341
414
|
}
|
|
342
415
|
|
|
343
416
|
log.info("hwaccel: no working hardware encoder; using software libx264");
|