Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(engine): renders show the video frame the preview shows at each output frame (#4596)
Miguel Ángele8313b2b3967
diff --git a/packages/engine/src/services/extractionCache.test.ts b/packages/engine/src/services/extractionCache.test.tsindex 96222f5741..d3bf36e665 100644--- a/packages/engine/src/services/extractionCache.test.ts+++ b/packages/engine/src/services/extractionCache.test.ts@@ -65,8 +65,8 @@ function seedPartialDir(entry: { dir: string; keyHash: string }, frameContent: s}describe("extractionCache constants", () => {- it("exposes the v5 schema prefix", () => {- expect(SCHEMA_PREFIX).toBe("hfcache-v5-");+ it("exposes the v6 schema prefix", () => {+ expect(SCHEMA_PREFIX).toBe("hfcache-v6-");});it("exposes the frame filename prefix shared with the extractor", () => {diff --git a/packages/engine/src/services/extractionCache.ts b/packages/engine/src/services/extractionCache.tsindex bf436d4aec..668d445beb 100644--- a/packages/engine/src/services/extractionCache.ts+++ b/packages/engine/src/services/extractionCache.ts@@ -58,16 +58,10 @@ export const COMPLETE_SENTINEL = ".hf-complete";export const GC_MARKER = ".hf-last-gc";/**- * Current schema version. Bump when the cache-contents invariant changes.- * v2 -> v3: one-pass VFR extraction (-fps_mode cfr) replaces the two-pass- * VFR-to-CFR re-encode, changing frame contents for VFR sources under- * identical key tuples. Without the bump, warm v2 entries (two-pass frames)- * would keep being served across the deploy boundary.- * v3 -> v4: the target fps identity is the exact FFmpeg argument instead of- * a JavaScript number. This invalidates entries created after rational NTSC- * rates had already been rounded to a decimal.+ * Current schema version. Bump it whenever extraction writes different frames for the same key,+ * or warm entries keep serving the old frames across a deploy. Each bump's commit says why.*/-export const SCHEMA_PREFIX = "hfcache-v5-";+export const SCHEMA_PREFIX = "hfcache-v6-";/** Truncated hex chars of SHA-256 used for the entry directory name. */const KEY_HEX_CHARS = 16;diff --git a/packages/engine/src/services/videoFrameExtractor.test.ts b/packages/engine/src/services/videoFrameExtractor.test.tsindex 1b856f3ba7..374f983a34 100644--- a/packages/engine/src/services/videoFrameExtractor.test.ts+++ b/packages/engine/src/services/videoFrameExtractor.test.ts@@ -1786,6 +1786,98 @@ describe.skipIf(!HAS_FFMPEG)("video frame extraction format", () => {}, 60_000);});+// Each output slot shows the frame on screen at its time, as the preview does.+describe.skipIf(!HAS_FFMPEG)("frame sampling at the output frame rate", () => {+ const FIXTURE_DIR = mkdtempSync(join(tmpdir(), "hf-video-frame-sampling-"));+ const WIDTH = 32;+ const HEIGHT = 16;+ // Matroska stores whole-millisecond timestamps (a 30 fps frame at 66.67 ms reads 67 ms);+ // a 1/30 timescale stores each frame exactly on a coarse tick.+ const SOURCES = {+ "mp4-60": { fps: 60, file: "index-60fps.mp4", muxer: [] },+ "mkv-30": { fps: 30, file: "index-30fps.mkv", muxer: [] },+ "mp4-30-timescale-30": {+ fps: 30,+ file: "index-30fps-ts30.mp4",+ muxer: ["-video_track_timescale", "30"],+ },+ } as const;+ type SourceName = keyof typeof SOURCES;+ const sourcePath = (name: SourceName) => join(FIXTURE_DIR, SOURCES[name].file);++ beforeAll(async () => {+ for (const name of Object.keys(SOURCES) as SourceName[]) {+ // Frame k carries luma 16 + 2k, so each extracted frame names its source index.+ const result = await runFfmpeg([+ "-y",+ "-hide_banner",+ "-loglevel",+ "error",+ "-f",+ "lavfi",+ "-i",+ `nullsrc=s=${WIDTH}x${HEIGHT}:r=${SOURCES[name].fps}:d=1.5,geq=lum='16+2*N':cb=128:cr=128`,+ "-c:v",+ "libx264",+ "-qp",+ "0",+ "-pix_fmt",+ "yuv420p",+ ...SOURCES[name].muxer,+ sourcePath(name),+ ]);+ if (!result.success) throw new Error(`index fixture synthesis failed: ${result.stderr}`);+ }+ }, 30_000);++ afterAll(() => {+ rmSync(FIXTURE_DIR, { recursive: true, force: true });+ });++ function sourceIndexes(extracted: ExtractedFrames): number[] {+ const decoded = spawnSync("ffmpeg", [+ "-v",+ "error",+ "-i",+ join(extracted.outputDir, extracted.framePattern),+ "-f",+ "rawvideo",+ "-pix_fmt",+ "gray",+ "pipe:1",+ ]);+ if (decoded.status !== 0) throw new Error(decoded.stderr.toString());+ const indexes: number[] = [];+ for (let offset = 0; offset < decoded.stdout.length; offset += WIDTH * HEIGHT) {+ indexes.push(Math.round(((decoded.stdout[offset] ?? 0) * 219) / 255 / 2));+ }+ return indexes;+ }++ it.each([+ { source: "mp4-60", fps: 24, startTime: 0, duration: 0.5 },+ { source: "mp4-60", fps: 10, startTime: 0.37, duration: 0.6 },+ { source: "mkv-30", fps: 30, startTime: 0, duration: 0.5 },+ { source: "mp4-30-timescale-30", fps: 60, startTime: 0, duration: 0.5 },+ ] as const)(+ "$source: samples the frame on screen at each $fps fps slot from $startTime s",+ async (c) => {+ const extracted = await extractVideoFramesRange(+ sourcePath(c.source),+ `${c.source}-${c.fps}`,+ c.startTime,+ c.duration,+ { fps: c.fps, outputDir: FIXTURE_DIR, format: "png" },+ );+ const onScreen = Array.from({ length: Math.round(c.duration * c.fps) }, (_, i) =>+ Math.floor((c.startTime + i / c.fps) * SOURCES[c.source].fps + 1e-9),+ );+ expect(sourceIndexes(extracted)).toEqual(onScreen);+ },+ 30_000,+ );+});+describe.skipIf(!HAS_FFMPEG)("held tails on sparse-timestamp sources", () => {const fixtureDir = mkdtempSync(join(tmpdir(), "hf-sparse-held-tail-"));const cfrFixture = join(fixtureDir, "sub-1fps-cfr.mp4");diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.tsindex a7b1103dac..30d84fab70 100644--- a/packages/engine/src/services/videoFrameExtractor.ts+++ b/packages/engine/src/services/videoFrameExtractor.ts@@ -827,12 +827,7 @@ export async function extractVideoFramesRange(options: ExtractionOptions,signal?: AbortSignal,config?: Partial<Pick<EngineConfig, "ffmpegProcessTimeout">>,- /**- * Override the output directory for this extraction. When provided, frames- * are written directly into `outputDirOverride` (no per-videoId subdir).- * Used by the cache layer to materialize frames straight into the keyed- * cache entry directory.- */+ /** Frames go straight here, with no per-videoId subdir (the cache layer's keyed entry). */outputDirOverride?: string,): Promise<ExtractedFrames> {const ffmpegProcessTimeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout;@@ -877,6 +872,8 @@ export async function extractVideoFramesRange(const isHdr = isHdrColorSpaceUtil(metadata.colorSpace);const isMacOS = process.platform === "darwin";+ const sampleCfrAtOutputFps = !options.finalFrameOnly && !metadata.isVFR;+const args: string[] = [];if (isHdr && isMacOS) {args.push("-hwaccel", "videotoolbox");@@ -900,6 +897,8 @@ export async function extractVideoFramesRange(// a negative timestamp base) can seek to EOF and emit zero frames.args.push("-i", videoPath, "-ss", String(startTime), "-frames:v", "1");} else {+ // An accurate seek drops the frame on screen at startTime; the fps sampling below needs it.+ if (sampleCfrAtOutputFps) args.push("-noaccurate_seek");args.push("-ss", String(startTime), "-i", videoPath, "-t", String(duration));}@@ -908,8 +907,14 @@ export async function extractVideoFramesRange(// VideoToolbox tone-maps during decode; force output to bt709 SDR formatvfFilters.push("format=nv12");}- if (!options.finalFrameOnly && !metadata.isVFR) {- vfFilters.push(`fps=${ffmpegFps}`);+ if (sampleCfrAtOutputFps) {+ // Each slot takes the last frame starting at or before its time. Ticks of 2 ms or finer+ // first shift half a tick, absorbing container rounding (WebM/MKV use whole ms).+ vfFilters.push(+ "settb=intb/2",+ "setpts=PTS-lte(TB\\,0.001)",+ `fps=${ffmpegFps}:start_time=0:round=up`,+ );}if (options.sdrToHdrTransfer) {// Ordering intent: fps sampling runs BEFORE the colorspace remap so onlydiff --git a/packages/producer/tests/style-12-prod/output/output.mp4 b/packages/producer/tests/style-12-prod/output/output.mp4index e51514cb20..a661369ae7 100644--- a/packages/producer/tests/style-12-prod/output/output.mp4+++ b/packages/producer/tests/style-12-prod/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:21fde191f0b1c2e89f4dace8419b3f2274e44652a35d1ecaddd8fac5774413e8-size 11095224+oid sha256:7978a2502f3c187419ef7fd404f5f48998cf6799f5b565a588ea189a4665812a+size 11712255diff --git a/packages/producer/tests/style-13-prod/output/output.mp4 b/packages/producer/tests/style-13-prod/output/output.mp4index 86495fde11..aba15db654 100644--- a/packages/producer/tests/style-13-prod/output/output.mp4+++ b/packages/producer/tests/style-13-prod/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:a0809b9b98e70674bef3da96055fd0c33f807bf26eac9e14c42acd13e270f2e4-size 14425452+oid sha256:af9dca1109886deef88b0400ed8d5cf0516e6e9b236fae166215ce7387d46877+size 15006441diff --git a/packages/producer/tests/style-15-prod/output/output.mp4 b/packages/producer/tests/style-15-prod/output/output.mp4index b45e170dd1..1a18fc175d 100644--- a/packages/producer/tests/style-15-prod/output/output.mp4+++ b/packages/producer/tests/style-15-prod/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:13e7dd6d0dbeca86db4b69ca00d985f331572166aeacfd1af7d0fb4abf6abe84-size 22376857+oid sha256:41e09a7519f56d573096ba01d2e5c9cf59956f5b54e9da5bb0a1467a49f48039+size 22661197diff --git a/packages/producer/tests/style-18-prod/output/output.mp4 b/packages/producer/tests/style-18-prod/output/output.mp4index f5f31caa23..b6948847f2 100644--- a/packages/producer/tests/style-18-prod/output/output.mp4+++ b/packages/producer/tests/style-18-prod/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:c722ec4fc2496581eaedb5d86662f2a4a2eb4903099d870caf2877d8548eafb1-size 15245778+oid sha256:f917e469fd0d80c2393e153239254ba2bc9faf68bffc57cde4cc8dbb4e4ab986+size 17512767