Skip to content

Write HTML. Render video. Built for agents.

fix(engine): classify a single-keyframe video as problematic, not healthy (#3998)

miga-heygen29378b6c7f08
diff --git a/packages/engine/src/utils/ffprobe.test.ts b/packages/engine/src/utils/ffprobe.test.ts
index 20186127dc..0ef165a049 100644
--- a/packages/engine/src/utils/ffprobe.test.ts
+++ b/packages/engine/src/utils/ffprobe.test.ts
@@ -834,6 +834,139 @@ describe("ffprobe missing-binary fallback", () => {
expect(basename(calls[0]?.command ?? "")).toMatch(/^ffprobe(?:\.exe)?$/);
});
+ it("analyzeKeyframeIntervals flags a single-keyframe video as problematic, not healthy", async () => {
+ // A single-GOP file (one keyframe at t=0) is the worst case this check exists to catch.
+ // Regression for #3460, where fewer than 2 keyframes short-circuited to isProblematic:false.
+ // Real `csv=p=0` output has a trailing comma per row; parseFloat must tolerate it.
+ const { spawn } = createSpawnSpy([{ kind: "exit", code: 0, stdout: "0.000000,\n" }]);
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
+
+ await expect(
+ analyzeKeyframeIntervals("/tmp/single-gop.mp4", {
+ videoStreamDurationSeconds: 6.5,
+ videoStreamStartSeconds: 0,
+ }),
+ ).resolves.toEqual({
+ avgIntervalSeconds: 6.5,
+ maxIntervalSeconds: 6.5,
+ keyframeCount: 1,
+ isProblematic: true,
+ });
+ });
+
+ it("analyzeKeyframeIntervals leaves a single keyframe exactly at the 2s threshold healthy", async () => {
+ // isProblematic compares with a strict `>`, so exactly 2s must stay healthy.
+ const { spawn } = createSpawnSpy([{ kind: "exit", code: 0, stdout: "0.000000\n" }]);
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
+
+ await expect(
+ analyzeKeyframeIntervals("/tmp/exactly-two-seconds.mp4", {
+ videoStreamDurationSeconds: 2,
+ videoStreamStartSeconds: 0,
+ }),
+ ).resolves.toEqual({
+ avgIntervalSeconds: 2,
+ maxIntervalSeconds: 2,
+ keyframeCount: 1,
+ isProblematic: false,
+ });
+ });
+
+ it("analyzeKeyframeIntervals normalizes an absolute keyframe pts against a nonzero stream start", async () => {
+ // ffprobe's pts_time is absolute, not relative to stream start. A clip with
+ // start_time=5 and a keyframe at absolute pts 5.0 is still single-GOP end-to-end,
+ // so it must stay flagged, not cleared by subtracting duration from the raw pts.
+ const { spawn } = createSpawnSpy([{ kind: "exit", code: 0, stdout: "5.000000\n" }]);
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
+
+ await expect(
+ analyzeKeyframeIntervals("/tmp/nonzero-start-single-gop.mp4", {
+ videoStreamDurationSeconds: 3,
+ videoStreamStartSeconds: 5,
+ }),
+ ).resolves.toEqual({
+ avgIntervalSeconds: 3,
+ maxIntervalSeconds: 3,
+ keyframeCount: 1,
+ isProblematic: true,
+ });
+ });
+
+ it("analyzeKeyframeIntervals leaves a short single-keyframe video healthy", async () => {
+ // The single-GOP span is measured off the duration the caller passes in, so
+ // a 1s video muxed with 10s of audio has to be probed with its video
+ // stream's duration; the container's would overstate the span and warn.
+ const { spawn } = createSpawnSpy([{ kind: "exit", code: 0, stdout: "0.000000\n" }]);
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
+
+ await expect(
+ analyzeKeyframeIntervals("/tmp/short-video-long-audio.mp4", {
+ videoStreamDurationSeconds: 1,
+ videoStreamStartSeconds: 0,
+ }),
+ ).resolves.toEqual({
+ avgIntervalSeconds: 1,
+ maxIntervalSeconds: 1,
+ keyframeCount: 1,
+ isProblematic: false,
+ });
+ });
+
+ it("analyzeKeyframeIntervals treats a single keyframe with an unknown (NaN) duration as healthy, not NaN", async () => {
+ // ffprobe reports "N/A" for duration on some containers, which parses to
+ // NaN upstream in extractMediaMetadata. Without a finite-duration guard,
+ // NaN propagates through Math.max unchanged into the returned interval.
+ const { spawn } = createSpawnSpy([{ kind: "exit", code: 0, stdout: "0.000000\n" }]);
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
+
+ await expect(
+ analyzeKeyframeIntervals("/tmp/unknown-duration.mp4", {
+ videoStreamDurationSeconds: NaN,
+ videoStreamStartSeconds: 0,
+ }),
+ ).resolves.toEqual({
+ avgIntervalSeconds: 0,
+ maxIntervalSeconds: 0,
+ keyframeCount: 1,
+ isProblematic: false,
+ });
+ });
+
+ it("analyzeKeyframeIntervals reports a zero-keyframe video as healthy, ignoring the duration", async () => {
+ const { spawn } = createSpawnSpy([{ kind: "exit", code: 0, stdout: "" }]);
+ vi.resetModules();
+ vi.doMock("child_process", () => ({ spawn }));
+
+ const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
+
+ await expect(
+ analyzeKeyframeIntervals("/tmp/no-keyframes.mp4", {
+ videoStreamDurationSeconds: 6.5,
+ videoStreamStartSeconds: 0,
+ }),
+ ).resolves.toEqual({
+ avgIntervalSeconds: 0,
+ maxIntervalSeconds: 0,
+ keyframeCount: 0,
+ isProblematic: false,
+ });
+ });
+
it("analyzeKeyframeIntervals surfaces a ffprobe-missing error verbatim", async () => {
const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]);
hidePathBinaries();
@@ -842,9 +975,12 @@ describe("ffprobe missing-binary fallback", () => {
const { analyzeKeyframeIntervals } = await import("./ffprobe.js");
- await expect(analyzeKeyframeIntervals("/tmp/no-such-video.mp4")).rejects.toThrow(
- /ffprobe not found/,
- );
+ await expect(
+ analyzeKeyframeIntervals("/tmp/no-such-video.mp4", {
+ videoStreamDurationSeconds: 10,
+ videoStreamStartSeconds: 0,
+ }),
+ ).rejects.toThrow(/ffprobe not found/);
expect(calls.length).toBe(1);
expect(basename(calls[0]?.command ?? "")).toMatch(/^ffprobe(?:\.exe)?$/);
});
@@ -935,7 +1071,10 @@ describe("ffprobe option separator", () => {
const { extractAudioMetadata, analyzeKeyframeIntervals } = await import("./ffprobe.js");
await extractAudioMetadata("/tmp/-audio.wav");
- await analyzeKeyframeIntervals("/tmp/-video.mp4");
+ await analyzeKeyframeIntervals("/tmp/-video.mp4", {
+ videoStreamDurationSeconds: 10,
+ videoStreamStartSeconds: 0,
+ });
// Per call, not a flattened count. A total of 3 is satisfied by one call
// emitting three `--` and two emitting none — i.e. it cannot fail for
diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.ts
index 54b5f004cd..af2bab36b9 100644
--- a/packages/engine/src/utils/ffprobe.ts
+++ b/packages/engine/src/utils/ffprobe.ts
@@ -783,6 +783,21 @@ export async function extractMediaMetadata(filePath: string): Promise<VideoMetad
return probePromise;
}
+/**
+ * Normalized span of a video stream (not its container), plus its cache key.
+ * Computed here so callers cannot normalize or key differently.
+ */
+function resolveStreamWindow(
+ filePath: string,
+ metadata: Pick<VideoMetadata, "videoStreamDurationSeconds" | "videoStreamStartSeconds">,
+): { videoStreamStartSeconds: number; videoStreamDurationSeconds: number; cacheKey: string } {
+ const videoStreamDurationSeconds = metadata.videoStreamDurationSeconds;
+ const candidateStart = metadata.videoStreamStartSeconds ?? 0;
+ const videoStreamStartSeconds = Number.isFinite(candidateStart) ? candidateStart : 0;
+ const cacheKey = `${filePath}\0${String(videoStreamStartSeconds)}\0${String(videoStreamDurationSeconds)}`;
+ return { videoStreamStartSeconds, videoStreamDurationSeconds, cacheKey };
+}
+
/**
* Return the FFmpeg input-seek position of the final decoded video frame.
*
@@ -802,10 +817,11 @@ export async function extractFinalVideoFrameTimestamp(
metadata: Pick<VideoMetadata, "videoStreamDurationSeconds" | "videoStreamStartSeconds">,
signal?: AbortSignal,
): Promise<number> {
- const videoDurationSeconds = metadata.videoStreamDurationSeconds;
- const candidateStreamStart = metadata.videoStreamStartSeconds ?? 0;
- const videoStreamStartSeconds = Number.isFinite(candidateStreamStart) ? candidateStreamStart : 0;
- const cacheKey = `${filePath}\0${String(videoStreamStartSeconds)}\0${String(videoDurationSeconds)}`;
+ const {
+ videoStreamStartSeconds,
+ videoStreamDurationSeconds: videoDurationSeconds,
+ cacheKey,
+ } = resolveStreamWindow(filePath, metadata);
// A caller-owned abort signal cannot safely own a globally shared process
// promise: aborting one render would fail unrelated consumers. Calls in the
// SAME cancellation scope should still share the expensive interval +
@@ -982,26 +998,44 @@ export interface KeyframeAnalysis {
const keyframeCache = new Map<string, Promise<KeyframeAnalysis>>();
+/** Intervals beyond this cause seeking issues in the headless renderer and
+ * audio/video desync — the sole threshold for `isProblematic` below. */
+const PROBLEMATIC_KEYFRAME_INTERVAL_SECONDS = 2;
+
/**
- * Check keyframe intervals in a video file. Intervals > 2s cause seeking
- * issues in the headless renderer and audio/video desync. Videos from
- * yt-dlp --download-sections or screen recordings often have sparse keyframes.
+ * Checks keyframe intervals in a video stream; intervals over the threshold below flag `isProblematic`.
+ * Pass the stream's own duration/start (not the container's), which can overstate a single-keyframe GOP.
*/
-export async function analyzeKeyframeIntervals(filePath: string): Promise<KeyframeAnalysis> {
- const cached = keyframeCache.get(filePath);
+export async function analyzeKeyframeIntervals(
+ filePath: string,
+ metadata: Pick<VideoMetadata, "videoStreamDurationSeconds" | "videoStreamStartSeconds">,
+): Promise<KeyframeAnalysis> {
+ const { videoStreamStartSeconds, videoStreamDurationSeconds, cacheKey } = resolveStreamWindow(
+ filePath,
+ metadata,
+ );
+ const cached = keyframeCache.get(cacheKey);
if (cached) return cached;
- const promise = analyzeKeyframeIntervalsUncached(filePath);
- keyframeCache.set(filePath, promise);
+ const promise = analyzeKeyframeIntervalsUncached(
+ filePath,
+ videoStreamStartSeconds,
+ videoStreamDurationSeconds,
+ );
+ keyframeCache.set(cacheKey, promise);
promise.catch(() => {
- if (keyframeCache.get(filePath) === promise) {
- keyframeCache.delete(filePath);
+ if (keyframeCache.get(cacheKey) === promise) {
+ keyframeCache.delete(cacheKey);
}
});
return promise;
}
-async function analyzeKeyframeIntervalsUncached(filePath: string): Promise<KeyframeAnalysis> {
+async function analyzeKeyframeIntervalsUncached(
+ filePath: string,
+ videoStreamStartSeconds: number,
+ videoStreamDurationSeconds: number,
+): Promise<KeyframeAnalysis> {
const stdout = await runFfprobe(filePath, [
"-select_streams",
"v:0",
@@ -1018,15 +1052,33 @@ async function analyzeKeyframeIntervalsUncached(filePath: string): Promise<Keyfr
.map((line) => parseFloat(line.trim()))
.filter((t) => Number.isFinite(t));
- if (timestamps.length < 2) {
+ if (timestamps.length === 0) {
return {
avgIntervalSeconds: 0,
maxIntervalSeconds: 0,
- keyframeCount: timestamps.length,
+ keyframeCount: 0,
isProblematic: false,
};
}
+ if (timestamps.length === 1) {
+ // A single keyframe means the whole stream is one GOP — the worst case, not the healthy one.
+ // `timestamps[0]` is an absolute pts, so compare it against the absolute stream end
+ // (start + duration), not against duration alone.
+ const streamEnd = videoStreamStartSeconds + videoStreamDurationSeconds;
+ // The fallback is unreachable (length === 1); it only satisfies
+ // noUncheckedIndexedAccess.
+ const rawInterval = streamEnd - (timestamps[0] ?? videoStreamStartSeconds);
+ const singleGopInterval = Number.isFinite(rawInterval) ? Math.max(rawInterval, 0) : 0;
+ const roundedInterval = Math.round(singleGopInterval * 100) / 100;
+ return {
+ avgIntervalSeconds: roundedInterval,
+ maxIntervalSeconds: roundedInterval,
+ keyframeCount: 1,
+ isProblematic: singleGopInterval > PROBLEMATIC_KEYFRAME_INTERVAL_SECONDS,
+ };
+ }
+
let maxInterval = 0;
let totalInterval = 0;
for (let i = 1; i < timestamps.length; i++) {
@@ -1040,6 +1092,6 @@ async function analyzeKeyframeIntervalsUncached(filePath: string): Promise<Keyfr
avgIntervalSeconds: Math.round(avgInterval * 100) / 100,
maxIntervalSeconds: Math.round(maxInterval * 100) / 100,
keyframeCount: timestamps.length,
- isProblematic: maxInterval > 2,
+ isProblematic: maxInterval > PROBLEMATIC_KEYFRAME_INTERVAL_SECONDS,
};
}
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index 5d5e7ee424..e308eaf975 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -2097,32 +2097,33 @@ export async function compileForRender(
// Advisory video checks (sparse keyframes, VFR). Fire-and-forget — these spawn
// ffprobe subprocesses and should not block compilation since they only produce warnings.
+ // The two probes run in sequence rather than in parallel: the keyframe analysis needs
+ // the video stream's own duration to classify a single-keyframe (single-GOP) file.
for (const video of videos) {
if (isHttpUrl(video.src)) continue;
const videoPath = resolve(projectDir, video.src);
const reencode = `ffmpeg -i "${video.src}" -c:v libx264 -r 30 -g 30 -keyint_min 30 -movflags +faststart -c:a copy output.mp4`;
- Promise.all([
- withMediaProbeSlot(() => analyzeKeyframeIntervals(videoPath)),
- withMediaProbeSlot(() => extractMediaMetadata(videoPath)),
- ])
- .then(([analysis, metadata]) => {
- if (analysis.isProblematic) {
- defaultLogger.warn(
- `[Compiler] WARNING: Video "${video.id}" has sparse keyframes (max interval: ${analysis.maxIntervalSeconds}s). ` +
- `This causes seek failures and frame freezing. Re-encode with: ${reencode}`,
- );
- }
- if (metadata.isVFR) {
- // defaultLogger (stderr), not console.info (stdout) — matches the sibling
- // warning above; a stdout line here corrupts `check --json` / `validate --json`.
- defaultLogger.warn(
- `[Compiler] Video "${video.id}" is variable frame rate (VFR); ` +
- `the engine will normalize it to CFR before frame extraction. ` +
- `If rendering feels slow on this video, pre-encode once with: ${reencode}`,
- );
- }
- })
- .catch(() => {});
+ (async () => {
+ const metadata = await withMediaProbeSlot(() => extractMediaMetadata(videoPath));
+ const analysis = await withMediaProbeSlot(() =>
+ analyzeKeyframeIntervals(videoPath, metadata),
+ );
+ if (analysis.isProblematic) {
+ defaultLogger.warn(
+ `[Compiler] WARNING: Video "${video.id}" has sparse keyframes (max interval: ${analysis.maxIntervalSeconds}s). ` +
+ `This causes seek failures and frame freezing. Re-encode with: ${reencode}`,
+ );
+ }
+ if (metadata.isVFR) {
+ // defaultLogger (stderr), not console.info (stdout) — matches the sibling
+ // warning above; a stdout line here corrupts `check --json` / `validate --json`.
+ defaultLogger.warn(
+ `[Compiler] Video "${video.id}" is variable frame rate (VFR); ` +
+ `the engine will normalize it to CFR before frame extraction. ` +
+ `If rendering feels slow on this video, pre-encode once with: ${reencode}`,
+ );
+ }
+ })().catch(() => {});
}
// Read dimensions from root composition element using DOM parser