Skip to content

Commit 9fd5e4a

Browse files
fix(cli): a render no FFmpeg encoder can finish stops before capture, not after it (#5831)
1 parent 9566f96 commit 9fd5e4a

4 files changed

Lines changed: 114 additions & 64 deletions

File tree

‎packages/cli/src/browser/ffmpeg.test.ts‎

Lines changed: 56 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import { execFileSync } from "node:child_process";
21
import { tmpdir } from "node:os";
32
import { join } from "node:path";
43
import { afterEach, describe, expect, it, vi } from "vitest";
54
import { findFFmpeg, findFFprobe, H264EncoderUnavailableError } from "./ffmpeg.js";
5+
import { runCancellableProcess } from "../utils/cancellableProcess.js";
66

7-
// Only child_process is mocked: the H264 encoder probe shells out, while the
8-
// wrapper tests below resolve via env overrides and need the real `existsSync`.
7+
// Only child_process is mocked, so no lookup shells out, while the wrapper
8+
// tests below resolve via env overrides and need the real `existsSync`.
99
vi.mock("node:child_process", () => ({ execFileSync: vi.fn(), execSync: vi.fn() }));
1010

1111
// Only the distro probe is faked; `ffmpegInstallCommand` stays real so the
@@ -16,7 +16,8 @@ vi.mock("./linuxDeps.js", async (importOriginal) => ({
1616
detectLinuxDistro: () => ({ family: linuxFamily, isWsl: false, prettyName: null }),
1717
}));
1818

19-
const mockExecFile = vi.mocked(execFileSync);
19+
vi.mock("../utils/cancellableProcess.js", () => ({ runCancellableProcess: vi.fn() }));
20+
const mockRun = vi.mocked(runCancellableProcess);
2021

2122
afterEach(() => {
2223
vi.clearAllMocks();
@@ -45,56 +46,76 @@ describe("findFFmpeg / findFFprobe", () => {
4546
});
4647

4748
describe("resolveH264EncoderMode", () => {
48-
it("falls back to VideoToolbox when libx264 is absent", async () => {
49-
const { resolveH264EncoderMode } = await import("./ffmpeg.js");
50-
const encoders = `
51-
V....D h264_videotoolbox VideoToolbox H.264 Encoder
52-
`;
49+
// The shape of an LGPL FFmpeg build: OpenH264 and VideoToolbox, no libx264.
50+
const noX264 = " V....D libopenh264 OpenH264\n V....D h264_videotoolbox VideoToolbox H.264\n";
5351

54-
expect(resolveH264EncoderMode(encoders, false)).toBe("gpu");
52+
it("falls back to a GPU encoder that works when libx264 is absent", async () => {
53+
const { resolveH264EncoderMode } = await import("./ffmpeg.js");
54+
expect(resolveH264EncoderMode(noX264, false, true)).toBe("gpu");
5555
});
5656

57-
it("does not treat a compiled Linux hardware encoder as usable", async () => {
57+
it("refuses a compiled GPU encoder whose probe failed, with or without --gpu", async () => {
5858
const { resolveH264EncoderMode } = await import("./ffmpeg.js");
59-
const encoders = `
60-
V....D h264_vaapi H.264/AVC (VAAPI)
61-
`;
59+
expect(() => resolveH264EncoderMode(noX264, false, false)).toThrow(H264EncoderUnavailableError);
60+
expect(() => resolveH264EncoderMode(noX264, true, false)).toThrow(H264EncoderUnavailableError);
61+
});
6262

63-
expect(() => resolveH264EncoderMode(encoders, false)).toThrow(H264EncoderUnavailableError);
63+
it("encodes --gpu renders with libx264 when no GPU encoder works", async () => {
64+
const { resolveH264EncoderMode } = await import("./ffmpeg.js");
65+
expect(resolveH264EncoderMode(" V....D libx264 H.264\n", true, false)).toBe("software");
66+
expect(resolveH264EncoderMode(" V....D libx264 H.264\n", true, true)).toBe("gpu");
6467
});
6568

6669
it("prefers libx264 when both encoders are available", async () => {
6770
const { resolveH264EncoderMode } = await import("./ffmpeg.js");
6871
expect(
69-
resolveH264EncoderMode(" V....D libx264 H.264\n V....D h264_videotoolbox H.264\n", false),
72+
resolveH264EncoderMode(
73+
" V....D libx264 H.264\n V....D h264_videotoolbox H.264\n",
74+
false,
75+
true,
76+
),
7077
).toBe("software");
7178
});
7279

73-
it("distinguishes a successful unsupported probe from an unavailable probe", async () => {
74-
const { detectH264EncoderMode } = await import("./ffmpeg.js");
75-
mockExecFile.mockReturnValue(" V....D libvpx-vp9 VP9\n");
76-
expect(() => detectH264EncoderMode("/custom/ffmpeg", false)).toThrow(
77-
H264EncoderUnavailableError,
78-
);
79-
const timeout = new Error("ETIMEDOUT");
80-
mockExecFile.mockImplementationOnce(() => {
81-
throw timeout;
82-
});
83-
expect(() => detectH264EncoderMode("/custom/ffmpeg", false)).toThrow(timeout);
80+
it("says whether HEVC could still encode when H.264 cannot", async () => {
81+
const { resolveH264EncoderMode } = await import("./ffmpeg.js");
82+
const refusal = (encoders: string) => {
83+
try {
84+
resolveH264EncoderMode(encoders, false, false);
85+
} catch (error) {
86+
return error as InstanceType<typeof H264EncoderUnavailableError>;
87+
}
88+
};
89+
expect(refusal(" V....D libx265 HEVC\n")?.hevcEncoderAvailable).toBe(true);
90+
expect(refusal(noX264)?.hevcEncoderAvailable).toBe(false);
8491
});
8592

86-
it("inspects the configured FFmpeg binary", async () => {
87-
mockExecFile.mockReturnValue(
88-
" V....D h264_videotoolbox VideoToolbox H.264 Encoder\n" as never,
93+
it("asks the configured FFmpeg, and probes the GPU only when libx264 is missing or --gpu is set", async () => {
94+
const { detectH264EncoderModeForRender } = await import("./ffmpeg.js");
95+
const signal = new AbortController().signal;
96+
const probeGpu = vi.fn(async () => null);
97+
mockRun.mockResolvedValue({ stdout: " V....D libx264 H.264\n" } as never);
98+
expect(await detectH264EncoderModeForRender("/custom/ffmpeg", false, signal, probeGpu)).toBe(
99+
"software",
89100
);
90-
const { detectH264EncoderMode } = await import("./ffmpeg.js");
91-
92-
expect(detectH264EncoderMode("/custom/ffmpeg", false)).toBe("gpu");
93-
expect(mockExecFile).toHaveBeenCalledWith(
101+
expect(probeGpu).not.toHaveBeenCalled();
102+
expect(mockRun).toHaveBeenCalledWith(
94103
"/custom/ffmpeg",
95104
["-hide_banner", "-encoders"],
96-
expect.objectContaining({ encoding: "utf-8", windowsHide: true }),
105+
expect.objectContaining({ signal }),
97106
);
107+
108+
mockRun.mockResolvedValue({ stdout: " V....D h264_videotoolbox H.264\n" } as never);
109+
await expect(
110+
detectH264EncoderModeForRender("/custom/ffmpeg", true, signal, probeGpu),
111+
).rejects.toThrow(H264EncoderUnavailableError);
112+
expect(probeGpu).toHaveBeenCalledOnce();
113+
114+
const timeout = new Error("ETIMEDOUT");
115+
mockRun.mockRejectedValueOnce(timeout);
116+
await expect(
117+
detectH264EncoderModeForRender("/custom/ffmpeg", false, signal, probeGpu),
118+
).rejects.toThrow(timeout);
98119
});
99120
});
100121

‎packages/cli/src/browser/ffmpeg.ts‎

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { execFileSync } from "node:child_process";
1+
import { detectGpuEncoder } from "@hyperframes/engine";
22
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
33
import { detectLinuxDistro, ffmpegInstallCommand } from "./linuxDeps.js";
44
import { runCancellableProcess } from "../utils/cancellableProcess.js";
@@ -8,49 +8,47 @@ export { FFMPEG_PATH_ENV, FFPROBE_PATH_ENV } from "@hyperframes/parsers/ff-binar
88
export type H264EncoderMode = "software" | "gpu";
99

1010
export class H264EncoderUnavailableError extends Error {
11-
constructor() {
12-
super("This FFmpeg build has neither libx264 nor VideoToolbox H.264 encoding.");
11+
constructor(readonly hevcEncoderAvailable = false) {
12+
super("This FFmpeg build has no libx264 and no GPU H.264 encoder that works on this machine.");
1313
this.name = "H264EncoderUnavailableError";
1414
}
1515
}
1616

1717
/**
1818
* Select the H.264 encoder class supported by an FFmpeg build.
1919
*
20-
* Some macOS FFmpeg distributions expose VideoToolbox but omit libx264. The
21-
* default CPU render path must not pass libx264-only options such as `-preset`
22-
* to those builds.
20+
* Some FFmpeg distributions omit libx264. Without a GPU encoder that passes
21+
* the engine's probe, the encoder falls back to libx264-only options such as
22+
* `-preset`, so those builds must be refused before capture.
2323
*/
2424
export function resolveH264EncoderMode(
2525
ffmpegEncodersOutput: string,
2626
gpuRequested: boolean,
27+
usableGpu: boolean,
2728
): H264EncoderMode {
28-
if (gpuRequested) return "gpu";
29-
if (/\blibx264\b/.test(ffmpegEncodersOutput)) return "software";
30-
if (/\bh264_videotoolbox\b/.test(ffmpegEncodersOutput)) return "gpu";
31-
throw new H264EncoderUnavailableError();
29+
if (gpuRequested && usableGpu) return "gpu";
30+
if (hasLibx264(ffmpegEncodersOutput)) return "software";
31+
if (usableGpu) return "gpu";
32+
throw new H264EncoderUnavailableError(/\blibx265\b/.test(ffmpegEncodersOutput));
3233
}
3334

34-
export function detectH264EncoderMode(ffmpegPath: string, gpuRequested: boolean): H264EncoderMode {
35-
const encoders = execFileSync(ffmpegPath, ["-hide_banner", "-encoders"], {
36-
encoding: "utf-8",
37-
stdio: ["ignore", "pipe", "pipe"],
38-
timeout: FIRST_LAUNCH_TIMEOUT_MS,
39-
windowsHide: true,
40-
});
41-
return resolveH264EncoderMode(encoders, gpuRequested);
35+
function hasLibx264(ffmpegEncodersOutput: string): boolean {
36+
return /\blibx264\b/.test(ffmpegEncodersOutput);
4237
}
4338

4439
export async function detectH264EncoderModeForRender(
4540
ffmpegPath: string,
4641
gpuRequested: boolean,
4742
signal: AbortSignal,
43+
probeGpu: () => Promise<unknown> = detectGpuEncoder,
4844
): Promise<H264EncoderMode> {
4945
const result = await runCancellableProcess(ffmpegPath, ["-hide_banner", "-encoders"], {
5046
signal,
5147
timeoutMs: FIRST_LAUNCH_TIMEOUT_MS,
5248
});
53-
return resolveH264EncoderMode(result.stdout, gpuRequested);
49+
const needsGpu = gpuRequested || !hasLibx264(result.stdout);
50+
const usableGpu = needsGpu && (await probeGpu()) !== null;
51+
return resolveH264EncoderMode(result.stdout, gpuRequested, usableGpu);
5452
}
5553

5654
// `configuredMustExist`: the CLI surfaces an install hint when a binary is

‎packages/cli/src/commands/render.test.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ const ffmpegEncoderState = vi.hoisted(() => ({
8686
mode: "software" as "software" | "gpu",
8787
error: null as Error | null,
8888
encoders: null as string | null,
89+
usableGpu: false,
8990
}));
9091
const orphanCleanupState = vi.hoisted(() => ({
9192
calls: 0,
@@ -210,10 +211,14 @@ vi.mock("../browser/ffmpeg.js", async (importOriginal) => {
210211
const actual = await importOriginal<typeof import("../browser/ffmpeg.js")>();
211212
return {
212213
...actual,
213-
detectH264EncoderModeForRender: vi.fn(async () => {
214+
detectH264EncoderModeForRender: vi.fn(async (_path: string, gpuRequested: boolean) => {
214215
if (ffmpegEncoderState.error) throw ffmpegEncoderState.error;
215216
if (ffmpegEncoderState.encoders !== null)
216-
return actual.resolveH264EncoderMode(ffmpegEncoderState.encoders, false);
217+
return actual.resolveH264EncoderMode(
218+
ffmpegEncoderState.encoders,
219+
gpuRequested,
220+
ffmpegEncoderState.usableGpu,
221+
);
217222
return ffmpegEncoderState.mode;
218223
}),
219224
findFFmpeg: vi.fn(() => "/usr/bin/ffmpeg"),
@@ -474,6 +479,7 @@ describe("renderLocal browser GPU config", () => {
474479
ffmpegEncoderState.mode = "software";
475480
ffmpegEncoderState.error = null;
476481
ffmpegEncoderState.encoders = null;
482+
ffmpegEncoderState.usableGpu = false;
477483
orphanCleanupState.calls = 0;
478484
orphanCleanupState.killed = 0;
479485
orphanCleanupState.parentPid = () => null;
@@ -950,6 +956,26 @@ describe("renderLocal browser GPU config", () => {
950956
expect(stderr.mock.calls.flat().join(" ")).toContain("libx264");
951957
});
952958

959+
it("refuses a --gpu MP4 before capture when no GPU encoder works and FFmpeg lacks libx264", async () => {
960+
ffmpegEncoderState.encoders = " V....D libopenh264 OpenH264\n V....D h264_videotoolbox H.264\n";
961+
const stderr = vi.spyOn(console, "error").mockImplementation(() => undefined);
962+
963+
await expect(
964+
renderLocal(PROJECT_DIR, "/tmp/out.mp4", {
965+
fps: { num: 30, den: 1 },
966+
quality: "high",
967+
format: "mp4",
968+
gpu: true,
969+
browserGpuMode: "software",
970+
hdrMode: "auto",
971+
quiet: true,
972+
}),
973+
).rejects.toMatchObject({ name: "CliRuntimeError" });
974+
975+
expect(producerState.createdJobs).toHaveLength(0);
976+
expect(stderr.mock.calls.flat().join(" ")).toContain("libx264");
977+
});
978+
953979
it.each(["webm", "mov", "png-sequence"] as const)(
954980
"does not require H.264 for %s",
955981
async (format) => {
@@ -1084,6 +1110,7 @@ describe("renderLocal browser GPU config", () => {
10841110
// the software encoder's forced-keyframe lock.
10851111
it("fails an HLS render instead of falling back to GPU H.264", async () => {
10861112
ffmpegEncoderState.encoders = " V....D h264_videotoolbox H.264 (VideoToolbox)\n";
1113+
ffmpegEncoderState.usableGpu = true;
10871114
const stderr = vi.spyOn(console, "error").mockImplementation(() => undefined);
10881115

10891116
await expect(

‎packages/cli/src/commands/render.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,21 +1008,22 @@ async function executeLocalRender(
10081008
// HLS shares the H.264 encode path but cannot take the GPU fallback below:
10091009
// its fixed-length segments need the software encoder's forced-keyframe lock.
10101010
const isHls = options.format === "hls";
1011-
if (!options.gpu && (options.format === "mp4" || isHls) && preflight.ffmpegPath) {
1012-
let encoderMode: H264EncoderMode = "software";
1011+
if ((options.format === "mp4" || isHls) && preflight.ffmpegPath) {
1012+
const gpuRequested = options.gpu && !isHls;
1013+
let encoderMode: H264EncoderMode = gpuRequested ? "gpu" : "software";
10131014
try {
10141015
encoderMode = await detectH264EncoderModeForRender(
10151016
preflight.ffmpegPath,
1016-
false,
1017+
gpuRequested,
10171018
cancellation.signal,
10181019
);
10191020
} catch (error) {
10201021
if (cancellation.signal.aborted) cancellation.signal.throwIfAborted();
1021-
// HDR MP4 uses HEVC; auto mode cannot resolve the codec until sources
1022-
// have been inspected. Forced SDR and HLS are definitely H.264 here.
1022+
// HDR MP4 uses HEVC; auto mode cannot resolve the codec until sources are
1023+
// inspected. Forced SDR, HLS, or no libx265 either: nothing here can encode.
10231024
if (
10241025
error instanceof H264EncoderUnavailableError &&
1025-
(options.hdrMode === "force-sdr" || isHls)
1026+
(options.hdrMode === "force-sdr" || isHls || !error.hevcEncoderAvailable)
10261027
) {
10271028
errorBox(
10281029
`${isHls ? "HLS" : "MP4"} H.264 encoder unavailable`,
@@ -1049,12 +1050,15 @@ async function executeLocalRender(
10491050
);
10501051
failCommand();
10511052
}
1052-
if (encoderMode === "gpu") {
1053+
if (encoderMode === "gpu" && !gpuRequested) {
10531054
console.warn(
1054-
c.warn(" FFmpeg does not include libx264; falling back to VideoToolbox H.264 encoding."),
1055+
c.warn(" FFmpeg does not include libx264; falling back to GPU H.264 encoding."),
10551056
);
10561057
options = { ...options, gpu: true };
10571058
}
1059+
if (encoderMode === "software" && gpuRequested && !options.quiet) {
1060+
console.warn(c.warn(" No GPU encoder works on this machine; encoding with libx264."));
1061+
}
10581062
}
10591063

10601064
cancellation.checkAncestors();

0 commit comments

Comments
 (0)