Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(engine): SDR renders keep footage and page colours as in the source (#4564)
Miguel Ángelc9b3d9c9628d
diff --git a/packages/engine/src/services/chunkEncoder.test.ts b/packages/engine/src/services/chunkEncoder.test.tsindex 24f53556a8..d664ff2758 100644--- a/packages/engine/src/services/chunkEncoder.test.ts+++ b/packages/engine/src/services/chunkEncoder.test.ts@@ -1,3 +1,4 @@+import { spawnSync } from "node:child_process";import { EventEmitter } from "node:events";import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";@@ -13,6 +14,10 @@ import {resolveLockedGopSize,} from "./chunkEncoder.js";import { renderProvenanceArgs } from "../utils/renderProvenance.js";+import { SDR_CAPTURE_TO_BT709_FILTER } from "../utils/sdrCaptureColor.js";+import { getFfmpegBinary } from "../utils/ffmpegBinaries.js";++const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"]).status === 0;const TINY_PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAACXBIWXMAAAABAAAAAQBPJcTWAAAAEElEQVR4nGP8wwACLGCSAQANBAECv1AVswAAAABJRU5ErkJggg==",@@ -1071,7 +1076,7 @@ describe("buildEncoderArgs color space", () => {);const vfIdx = args.indexOf("-vf");expect(vfIdx).toBeGreaterThan(-1);- expect(args[vfIdx + 1]).toBe("scale=in_range=pc:out_range=tv");+ expect(args[vfIdx + 1]).toBe(SDR_CAPTURE_TO_BT709_FILTER);});it("adds the pad after range conversion for odd CPU output dimensions", () => {@@ -1081,7 +1086,7 @@ describe("buildEncoderArgs color space", () => {"out.mp4",);const vfIdx = args.indexOf("-vf");- expect(args[vfIdx + 1]).toBe("scale=in_range=pc:out_range=tv,pad=ceil(iw/2)*2:ceil(ih/2)*2");+ expect(args[vfIdx + 1]).toBe(`${SDR_CAPTURE_TO_BT709_FILTER},pad=ceil(iw/2)*2:ceil(ih/2)*2`);});it("prepends range conversion to VAAPI filter chain", () => {@@ -1093,10 +1098,10 @@ describe("buildEncoderArgs color space", () => {);const vfIdx = args.indexOf("-vf");expect(vfIdx).toBeGreaterThan(-1);- expect(args[vfIdx + 1]).toBe("scale=in_range=pc:out_range=tv,format=nv12,hwupload");+ expect(args[vfIdx + 1]).toBe(`${SDR_CAPTURE_TO_BT709_FILTER},format=nv12,hwupload`);});- it("pads odd dimensions (no range scale) for non-VAAPI GPU encoding", () => {+ it("converts to BT.709 and pads odd dimensions for non-VAAPI GPU encoding", () => {for (const gpu of ["nvenc", "videotoolbox", "qsv", "amf"] as const) {const args = buildEncoderArgs({@@ -1112,10 +1117,7 @@ describe("buildEncoderArgs color space", () => {gpu,);const vfIdx = args.indexOf("-vf");- // 4:2:0 HW encode still aborts on odd dims, so the pad must be present —- // but the range scale belongs to the SW path only.- expect(args[vfIdx + 1]).toBe("pad=ceil(iw/2)*2:ceil(ih/2)*2");- expect(args[vfIdx + 1]).not.toContain("scale=in_range");+ expect(args[vfIdx + 1]).toBe(`${SDR_CAPTURE_TO_BT709_FILTER},pad=ceil(iw/2)*2:ceil(ih/2)*2`);// but still has color metadataexpect(args).toContain("-colorspace:v");}@@ -1128,7 +1130,7 @@ describe("buildEncoderArgs color space", () => {"out.mp4","videotoolbox",);- expect(args).not.toContain("-vf");+ expect(args[args.indexOf("-vf") + 1]).toBe(SDR_CAPTURE_TO_BT709_FILTER);});it("pads odd dimensions for 10-bit (yuv420p10le) GPU HDR encoding", () => {@@ -1141,6 +1143,7 @@ describe("buildEncoderArgs color space", () => {quality: 23,useGpu: true,pixelFormat: "yuv420p10le",+ hdr: { transfer: "pq" },},inputArgs,"out.mp4",@@ -1684,14 +1687,14 @@ describe("buildEncoderArgs HDR color space", () => {expect(args[vfIdx + 1]).toContain("scale=in_range=pc:out_range=tv");});- it("uses same range conversion for SDR CPU encoding", () => {+ it("converts SDR CPU captures to the BT.709 matrix", () => {const args = buildEncoderArgs({ ...baseOptions, codec: "h264", preset: "medium", quality: 23 },inputArgs,"out.mp4",);const vfIdx = args.indexOf("-vf");- expect(args[vfIdx + 1]).toContain("scale=in_range=pc:out_range=tv");+ expect(args[vfIdx + 1]).toBe(SDR_CAPTURE_TO_BT709_FILTER);});it("tags BT.2020 + transfer for HDR GPU H.265 (no mastering metadata via -x265-params)", () => {@@ -1741,3 +1744,78 @@ describe("buildConcatArgs", () => {expect(args.at(-1)).toBe("/w/video-only.mp4");});});++describe.skipIf(!HAS_FFMPEG)("buildEncoderArgs SDR colour", () => {+ // Chrome captures are BT.601 JPEGs. A direct YUV-to-YUV scale keeps that matrix under the BT.709+ // tag (ffmpeg 7 and older) or tints greys (8 and newer), so the encode goes through RGB.+ it("delivers Chrome's JPEG colours in the BT.709 the mp4 is tagged with", () => {+ const ffmpeg = getFfmpegBinary();+ const dir = mkdtempSync(join(tmpdir(), "hf-sdr-colour-"));+ const rgbAt = (file: string, decode: string, x: number): number[] => [+ ...spawnSync(ffmpeg, [+ "-v",+ "error",+ "-i",+ file,+ "-vf",+ `${decode}format=rgb24,crop=1:1:${x}:8`,+ "-frames:v",+ "1",+ "-f",+ "rawvideo",+ "-",+ ]).stdout,+ ];+ try {+ for (const color of ["0xC83C28", "0xFE0000", "0x101010", "0x2050E0"]) {+ const jpg = join(dir, "frame.jpg");+ const out = join(dir, "out.mp4");+ const synth = spawnSync(ffmpeg, [+ "-v",+ "error",+ "-y",+ "-f",+ "lavfi",+ "-i",+ `color=c=${color}:s=64x16,format=rgb24,drawbox=x=31:y=0:w=33:h=16:c=0x0000FE:t=fill`,+ "-frames:v",+ "1",+ "-pix_fmt",+ "yuvj420p",+ jpg,+ ]);+ expect(synth.status).toBe(0);+ const args = buildEncoderArgs(+ {+ fps: { num: 30, den: 1 },+ width: 64,+ height: 16,+ codec: "h264",+ preset: "ultrafast",+ quality: 0,+ },+ ["-i", jpg],+ out,+ );+ expect(spawnSync(ffmpeg, args).status).toBe(0);++ // x=8 is flat colour; x=32 sits one pixel inside the blue edge, where a smoothing+ // chroma resample bleeds the colour across.+ for (const [x, limit] of [+ [8, 2],+ [32, 2],+ ] as const) {+ const captured = rgbAt(jpg, "", x);+ const delivered = rgbAt(out, "scale=in_color_matrix=bt709:in_range=tv,", x);+ const worst = Math.max(...delivered.map((v, i) => Math.abs(v - captured[i]!)));+ expect(+ worst,+ `${color} x=${x}: capture ${captured} delivered ${delivered}`,+ ).toBeLessThanOrEqual(limit);+ }+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/packages/engine/src/services/chunkEncoder.ts b/packages/engine/src/services/chunkEncoder.tsindex 6cb1c4adc9..9bef8f6575 100644--- a/packages/engine/src/services/chunkEncoder.ts+++ b/packages/engine/src/services/chunkEncoder.ts@@ -31,6 +31,7 @@ import {} from "../utils/gpuEncoder.js";import { type HdrTransfer, getHdrEncoderColorParams } from "../utils/hdr.js";import { withEvenDimensionPad } from "../utils/evenDimensions.js";+import { SDR_CAPTURE_TO_BT709_FILTER } from "../utils/sdrCaptureColor.js";import { formatFfmpegError, isExternalFfmpegInterruption, runFfmpeg } from "../utils/runFfmpeg.js";import { extractAudioMetadata } from "../utils/ffprobe.js";import { type Fps, fpsToFfmpegArg, fpsToNumber } from "@hyperframes/core";@@ -446,34 +447,31 @@ export function buildEncoderArgs();}- // Range conversion: Chrome's full-range RGB → limited/TV range.+ // Range conversion: Chrome's full-range capture → limited/TV range; SDR also+ // converts to the BT.709 matrix it is tagged with.+ const sdrFilter = options.hdr ? undefined : SDR_CAPTURE_TO_BT709_FILTER;+ const captureFilter = sdrFilter ?? "scale=in_range=pc:out_range=tv";if (gpuEncoder === "vaapi") {// vaapi already runs `format=nv12,hwupload`; the nv12 conversion aligns- // odd dimensions before upload, so only prepend the range conversion.+ // odd dimensions before upload, so only prepend the colour conversion.const vfIdx = args.indexOf("-vf");if (vfIdx !== -1) {- args[vfIdx + 1] = `scale=in_range=pc:out_range=tv,${args[vfIdx + 1]}`;+ args[vfIdx + 1] = `${captureFilter},${args[vfIdx + 1]}`;}} else if (shouldUseGpu) {// nvenc/videotoolbox/qsv/amf feed software frames straight to the HW- // encoder with no `-vf`. They hit the same "height not divisible by 2"- // abort as libx264 on an odd-sized 4:2:0 canvas, so pad odd dimensions- // up to even on the software side before the encode.- const vf = withEvenDimensionPad("", pixelFormat, options.width, options.height);+ // encoder. They hit the same "height not divisible by 2" abort as+ // libx264 on an odd-sized 4:2:0 canvas, so pad odd dimensions up to even+ // on the software side before the encode.+ const vf = withEvenDimensionPad(sdrFilter ?? "", pixelFormat, options.width, options.height);if (vf) args.push("-vf", vf);} else {- // Range conversion: Chrome screenshots are full-range RGB.// The scale filter handles both 8-bit and 10-bit correctly. Pad odd// dimensions up to even so libx264/libx265 (4:2:0) don't abort with// "height not divisible by 2" on an odd-sized composition canvas.args.push("-vf",- withEvenDimensionPad(- "scale=in_range=pc:out_range=tv",- pixelFormat,- options.width,- options.height,- ),+ withEvenDimensionPad(captureFilter, pixelFormat, options.width, options.height),);}diff --git a/packages/engine/src/services/extractionCache.test.ts b/packages/engine/src/services/extractionCache.test.tsindex 997e5852f8..96222f5741 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 v4 schema prefix", () => {- expect(SCHEMA_PREFIX).toBe("hfcache-v4-");+ it("exposes the v5 schema prefix", () => {+ expect(SCHEMA_PREFIX).toBe("hfcache-v5-");});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 46a3528e8c..bf436d4aec 100644--- a/packages/engine/src/services/extractionCache.ts+++ b/packages/engine/src/services/extractionCache.ts@@ -67,7 +67,7 @@ export const GC_MARKER = ".hf-last-gc";* a JavaScript number. This invalidates entries created after rational NTSC* rates had already been rounded to a decimal.*/-export const SCHEMA_PREFIX = "hfcache-v4-";+export const SCHEMA_PREFIX = "hfcache-v5-";/** Truncated hex chars of SHA-256 used for the entry directory name. */const KEY_HEX_CHARS = 16;diff --git a/packages/engine/src/services/streamingEncoder.test.ts b/packages/engine/src/services/streamingEncoder.test.tsindex 7b73f88e00..af54d2b52a 100644--- a/packages/engine/src/services/streamingEncoder.test.ts+++ b/packages/engine/src/services/streamingEncoder.test.ts@@ -12,8 +12,9 @@import { validJpeg } from "./__fixtures__/jpeg.js";+import { spawnSync } from "child_process";import { EventEmitter } from "events";-import { mkdtempSync } from "fs";+import { mkdtempSync, rmSync } from "fs";import { tmpdir } from "os";import { basename, join } from "path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -24,6 +25,7 @@ import {type StreamingEncoderOptions,} from "./streamingEncoder.js";import { DEFAULT_HDR10_MASTERING } from "../utils/hdr.js";+import { SDR_CAPTURE_TO_BT709_FILTER } from "../utils/sdrCaptureColor.js";const baseHdrPq: StreamingEncoderOptions = {fps: { num: 30, den: 1 },@@ -167,13 +169,13 @@ describe("buildStreamingArgs", () => {expect(args[args.indexOf("-color_primaries:v") + 1]).toBe("bt709");expect(args[args.indexOf("-colorspace:v") + 1]).toBe("bt709");expect(args[args.indexOf("-color_range") + 1]).toBe("tv");- expect(args[args.indexOf("-vf") + 1]).toBe("scale=in_range=pc:out_range=tv");+ expect(args[args.indexOf("-vf") + 1]).toBe(SDR_CAPTURE_TO_BT709_FILTER);});it("adds the pad after range conversion for odd SDR output dimensions", () => {const args = buildStreamingArgs({ ...baseSdr, height: 1081 }, "/tmp/out.mp4");expect(args[args.indexOf("-vf") + 1]).toBe(- "scale=in_range=pc:out_range=tv,pad=ceil(iw/2)*2:ceil(ih/2)*2",+ `${SDR_CAPTURE_TO_BT709_FILTER},pad=ceil(iw/2)*2:ceil(ih/2)*2`,);});});@@ -340,27 +342,26 @@ describe("buildStreamingArgs", () => {expect(h265Args[h265Args.indexOf("-qp_i") + 1]).toBe("23");});- // 4:2:0 HW encode aborts on odd dims just like libx264, and these paths- // feed software frames straight to the encoder with no `-vf`, so the- // even-dim pad (and only the pad, not the SW range scale) must be added.- it("pads odd dimensions (no range scale) for non-VAAPI GPU encoding", () => {+ // 4:2:0 HW encode aborts on odd dims just like libx264, so the pad follows the colour conversion.+ it("converts to BT.709 and pads odd dimensions for non-VAAPI GPU encoding", () => {for (const gpu of ["nvenc", "videotoolbox", "qsv", "amf"] as const) {const args = buildStreamingArgs({ ...baseGpu, height: 1081 }, "/tmp/out.mp4", gpu);const vfIdx = args.indexOf("-vf");- expect(args[vfIdx + 1]).toBe("pad=ceil(iw/2)*2:ceil(ih/2)*2");- expect(args[vfIdx + 1]).not.toContain("scale=in_range");+ expect(args[vfIdx + 1]).toBe(+ `${SDR_CAPTURE_TO_BT709_FILTER},pad=ceil(iw/2)*2:ceil(ih/2)*2`,+ );}});it("does not require the pad filter for even GPU output dimensions", () => {const args = buildStreamingArgs(baseGpu, "/tmp/out.mp4", "videotoolbox");- expect(args).not.toContain("-vf");+ expect(args[args.indexOf("-vf") + 1]).toBe(SDR_CAPTURE_TO_BT709_FILTER);});it("prepends range conversion to VAAPI chain (nv12 covers even-dim)", () => {const args = buildStreamingArgs(baseGpu, "/tmp/out.mp4", "vaapi");const vfIdx = args.indexOf("-vf");- expect(args[vfIdx + 1]).toBe("scale=in_range=pc:out_range=tv,format=nv12,hwupload");+ expect(args[vfIdx + 1]).toBe(`${SDR_CAPTURE_TO_BT709_FILTER},format=nv12,hwupload`);});});@@ -1130,3 +1131,81 @@ describe("createFrameReorderBuffer abort (interleaved parallel drain)", () => {await expect(buf.waitForFrame(1)).resolves.toBeUndefined();});});++describe.skipIf(spawnSync("ffmpeg", ["-version"]).status !== 0)(+ "buildStreamingArgs raw SDR colour",+ () => {+ // ffmpeg 7 and older convert raw RGB with the BT.601 matrix unless told otherwise.+ it("delivers raw sRGB frames in the BT.709 the mp4 is tagged with", () => {+ const dir = mkdtempSync(join(tmpdir(), "se-raw-sdr-"));+ const rgbAt = (+ inputFormat: string[],+ source: string,+ decode: string,+ x: number,+ stdin?: Buffer,+ ): number[] => [+ ...spawnSync(+ "ffmpeg",+ [+ "-v",+ "error",+ ...inputFormat,+ "-i",+ source,+ "-vf",+ `${decode}format=rgb24,crop=1:1:${x}:8`,+ "-frames:v",+ "1",+ "-f",+ "rawvideo",+ "-",+ ],+ { input: stdin },+ ).stdout,+ ];+ try {+ const frame = spawnSync("ffmpeg", [+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "color=c=0xC83C28:s=64x16,format=rgb24,drawbox=x=31:y=0:w=33:h=16:c=0x0000FE:t=fill",+ "-frames:v",+ "1",+ "-pix_fmt",+ "rgb48le",+ "-f",+ "rawvideo",+ "-",+ ]).stdout;+ const out = join(dir, "out.mp4");+ const args = buildStreamingArgs(+ {+ ...baseSdr,+ width: 64,+ height: 16,+ preset: "ultrafast",+ quality: 0,+ rawInputFormat: "rgb48le",+ },+ out,+ );+ expect(spawnSync("ffmpeg", args, { input: frame }).status).toBe(0);++ const rawInput = ["-f", "rawvideo", "-pix_fmt", "rgb48le", "-s", "64x16"];+ // x=8 is flat colour; x=32 sits one pixel inside the blue edge.+ for (const x of [8, 32]) {+ const source = rgbAt(rawInput, "-", "", x, frame);+ const delivered = rgbAt([], out, "scale=in_color_matrix=bt709:in_range=tv,", x);+ expect([source.length, delivered.length]).toEqual([3, 3]);+ const worst = Math.max(...delivered.map((v, i) => Math.abs(v - source[i]!)));+ expect(worst, `x=${x}: source ${source} delivered ${delivered}`).toBeLessThanOrEqual(2);+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }, 30_000);+ },+);diff --git a/packages/engine/src/services/streamingEncoder.ts b/packages/engine/src/services/streamingEncoder.tsindex 9bb7b4aaeb..97949ab624 100644--- a/packages/engine/src/services/streamingEncoder.ts+++ b/packages/engine/src/services/streamingEncoder.ts@@ -35,6 +35,7 @@ import { formatFfmpegError, isExternalFfmpegInterruption } from "../utils/runFfmimport { getFfmpegBinary } from "../utils/ffmpegBinaries.js";import { getHdrEncoderColorParams } from "../utils/hdr.js";import { withEvenDimensionPad } from "../utils/evenDimensions.js";+import { SDR_CAPTURE_TO_BT709_FILTER, SDR_RGB_TO_BT709_FILTER } from "../utils/sdrCaptureColor.js";import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";import { fpsToFfmpegArg, fpsToNumber, type Fps } from "@hyperframes/core";import { appendVp9CpuUsedArg } from "./vp9Options.js";@@ -413,38 +414,24 @@ export function buildStreamingArgs();}- // Video filter for range/color conversion.- // Raw HDR input (from WebGPU pipeline) is already PQ-encoded — no conversion needed.- // Chrome screenshots need full→TV range conversion.- if (options.rawInputFormat) {+ // Raw HDR input (from WebGPU pipeline) is already PQ-encoded, so only SDR gets a+ // conversion: raw sRGB or Chrome's BT.601 JPEG screenshots to BT.709 limited range.+ const sdrFilter = options.rawInputFormat+ ? SDR_RGB_TO_BT709_FILTER+ : SDR_CAPTURE_TO_BT709_FILTER;+ if (options.rawInputFormat && options.hdr) {// No filter needed — PQ data goes straight to encoder} else if (gpuEncoder === "vaapi") {// vaapi already runs `format=nv12,hwupload`; the nv12 conversion aligns- // odd dimensions before upload, so only prepend the range conversion.+ // odd dimensions before upload, so only prepend the colour conversion.const vfIdx = args.indexOf("-vf");if (vfIdx !== -1) {- args[vfIdx + 1] = `scale=in_range=pc:out_range=tv,${args[vfIdx + 1]}`;+ args[vfIdx + 1] = `${sdrFilter},${args[vfIdx + 1]}`;}- } else if (shouldUseGpu) {- // nvenc/videotoolbox/qsv/amf feed software frames straight to the HW- // encoder with no `-vf`. They hit the same "height not divisible by 2"- // abort as libx264 on an odd-sized 4:2:0 canvas, so pad odd dimensions- // up to even on the software side before the encode.- const vf = withEvenDimensionPad("", pixelFormat, options.width, options.height);- if (vf) args.push("-vf", vf);} else {- // Range conversion: Chrome screenshots are full-range RGB. Pad odd- // dimensions up to even so libx264/libx265 (4:2:0) don't abort with- // "height not divisible by 2" on an odd-sized composition canvas.- args.push(- "-vf",- withEvenDimensionPad(- "scale=in_range=pc:out_range=tv",- pixelFormat,- options.width,- options.height,- ),- );+ // Pad odd dimensions up to even so 4:2:0 encoders (software and+ // nvenc/videotoolbox/qsv/amf) don't abort with "height not divisible by 2".+ args.push("-vf", withEvenDimensionPad(sdrFilter, pixelFormat, options.width, options.height));}// Fixed timescale for consistent A/V timing across platforms.diff --git a/packages/engine/src/services/videoFrameExtractor.test.ts b/packages/engine/src/services/videoFrameExtractor.test.tsindex ebd5d4feab..1b856f3ba7 100644--- a/packages/engine/src/services/videoFrameExtractor.test.ts+++ b/packages/engine/src/services/videoFrameExtractor.test.ts@@ -11,7 +11,7 @@ import {utimesSync,writeFileSync,} from "node:fs";-import { join } from "node:path";+import { basename, join } from "node:path";import { tmpdir } from "node:os";import { spawnSync } from "node:child_process";import {@@ -1280,6 +1280,15 @@ const RED_SAMPLE_PIXELS = [[178, 92],] as const;+function pngChunkTypes(path: string): string[] {+ const bytes = readFileSync(path);+ const types: string[] = [];+ for (let offset = 8; offset + 8 <= bytes.length; offset += 12 + bytes.readUInt32BE(offset)) {+ types.push(bytes.toString("latin1", offset + 4, offset + 8));+ }+ return types;+}+function readFirstFramePixel(mediaPath: string, x: number, y: number): Rgb {const result = spawnSync("ffmpeg",@@ -1411,6 +1420,291 @@ describe.skipIf(!HAS_FFMPEG)("video frame extraction format", () => {expect(worstPngDelta).toBeLessThanOrEqual(worstDefaultDelta);}, 60_000);+ // Chrome runs with --force-color-profile=srgb and colour-manages any frame not tagged sRGB;+ // the SDR encoder writes the canvas code values as they are, so frames must reach it unconverted.+ it.each([+ ["BT.709", "bt709"],+ ["BT.601", "smpte170m"],+ ])(+ "declares png frames of a %s source as sRGB so Chrome shows their code values",+ async (name, tag) => {+ const fixture = join(FIXTURE_DIR, `${tag}-shadow.mp4`);+ const synth = await runFfmpeg([+ "-y",+ "-hide_banner",+ "-loglevel",+ "error",+ "-f",+ "lavfi",+ "-i",+ `color=c=0x101010:s=${UI_FIXTURE_WIDTH}x${UI_FIXTURE_HEIGHT}:d=1:r=1`,+ "-vf",+ `setparams=color_primaries=${tag}:color_trc=${tag}:colorspace=${tag}:range=tv`,+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-crf",+ "0",+ "-pix_fmt",+ "yuv420p",+ fixture,+ ]);+ if (!synth.success) {+ throw new Error(`${name} fixture synthesis failed: ${synth.stderr.slice(-400)}`);+ }+ expect((await extractVideoMetadata(fixture)).colorSpace?.colorTransfer).toBe(tag);+ const outputDir = join(FIXTURE_DIR, `out-png-transfer-${tag}`);+ mkdirSync(outputDir, { recursive: true });++ const result = await extractAllVideoFrames(+ [{ ...fixtureVideo(), id: tag, src: fixture }],+ FIXTURE_DIR,+ { fps: 1, outputDir, format: "png" },+ );++ expect(result.errors).toEqual([]);+ const frame = result.extracted[0]!.framePaths.get(0)!;+ // Chrome reads cICP before sRGB, and ffmpeg < 6.0 writes no cICP, so only an sRGB chunk+ // without cICP means "these are sRGB code values" on every ffmpeg.+ const chunks = pngChunkTypes(frame);+ expect(chunks).toContain("sRGB");+ expect(chunks).not.toContain("cICP");+ expect(readFirstFramePixel(frame, 10, 10)).toEqual(readFirstFramePixel(fixture, 10, 10));+ },+ 60_000,+ );++ it("extracts jpg frames of a BT.709 source as the BT.601 full range JPEG readers assume", async () => {+ const fixture = join(FIXTURE_DIR, "bt709-patch.mp4");+ const synth = await runFfmpeg([+ "-y",+ "-hide_banner",+ "-loglevel",+ "error",+ "-f",+ "lavfi",+ "-i",+ `color=c=0xC83C28:s=${UI_FIXTURE_WIDTH}x${UI_FIXTURE_HEIGHT}:d=1:r=1,format=rgb24,drawbox=x=31:y=0:w=64:h=${UI_FIXTURE_HEIGHT}:c=0x0000FE:t=fill`,+ "-vf",+ "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p,setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv",+ "-c:v",+ "libx264",+ "-preset",+ "ultrafast",+ "-crf",+ "0",+ fixture,+ ]);+ if (!synth.success) throw new Error(`fixture synthesis failed: ${synth.stderr.slice(-400)}`);+ const outputDir = join(FIXTURE_DIR, "out-jpg-matrix");+ mkdirSync(outputDir, { recursive: true });++ const result = await extractAllVideoFrames(+ [{ ...fixtureVideo(), id: "bt709-jpg", src: fixture }],+ FIXTURE_DIR,+ { fps: 1, outputDir, format: "jpg" },+ );++ expect(result.errors).toEqual([]);+ const frame = result.extracted[0]!.framePaths.get(0)!;+ // x=10 is flat colour; x=32 sits one pixel inside the blue edge.+ for (const x of [10, 32]) {+ const source = readFirstFramePixel(fixture, x, 10);+ const shown = readFirstFramePixel(frame, x, 10);+ const worst = Math.max(...shown.map((v, i) => Math.abs(v - source[i]!)));+ expect(worst, `x=${x}: source ${source} jpg ${shown}`).toBeLessThanOrEqual(3);+ }+ }, 60_000);++ // Measured in Chrome 152: untagged H.264 plays as BT.601 at 1280x718 and BT.709 at 1280x720 or 406x720;+ // untagged VP9 and AV1 play as BT.601 at every size.+ it.each([+ { codec: "libx264", height: 718, matrix: "bt601", format: "png" },+ { codec: "libx264", height: 718, matrix: "bt601", format: "jpg" },+ { codec: "libx264", height: 720, matrix: "bt709", format: "png" },+ { codec: "libx264", height: 720, matrix: "bt709", format: "jpg" },+ { codec: "libvpx-vp9", height: 720, matrix: "bt601", format: "png" },+ { codec: "libaom-av1", height: 720, matrix: "bt601", format: "png" },+ ] as const)(+ "reads an untagged $height-line $codec source as $matrix like Chrome's own playback ($format)",+ async ({ codec, height, matrix, format }) => {+ const extension = codec === "libvpx-vp9" ? "webm" : "mp4";+ const fixture = join(FIXTURE_DIR, `untagged-${codec}-${height}.${extension}`);+ const synth = await runFfmpeg([+ "-y",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ `color=c=0xC83C28:s=64x${height}:d=1:r=1`,+ "-vf",+ "scale=out_color_matrix=bt601:out_range=tv,format=yuv420p,setparams=colorspace=unknown:color_primaries=unknown:color_trc=unknown:range=tv",+ "-c:v",+ codec,+ ...(codec === "libx264" ? ["-qp", "0"] : ["-crf", "0", "-b:v", "0"]),+ ...(codec === "libaom-av1" ? ["-cpu-used", "8"] : []),+ fixture,+ ]);+ if (!synth.success) throw new Error(`fixture synthesis failed: ${synth.stderr.slice(-400)}`);+ expect((await extractVideoMetadata(fixture)).colorSpace?.colorSpace ?? "unknown").toBe(+ "unknown",+ );++ const result = await extractVideoFramesRange(+ fixture,+ `${basename(fixture)}-${format}`,+ 0,+ 1,+ {+ fps: 1,+ outputDir: join(FIXTURE_DIR, "out-untagged"),+ format,+ },+ );++ const pixelAt = (file: string, decode: string): number[] => [+ ...spawnSync("ffmpeg", [+ "-v",+ "error",+ "-i",+ file,+ "-vf",+ `${decode}format=rgb24,crop=1:1:10:10`,+ "-frames:v",+ "1",+ "-f",+ "rawvideo",+ "-",+ ]).stdout,+ ];+ const expected = pixelAt(fixture, `scale=in_color_matrix=${matrix}:in_range=tv,`);+ const shown = pixelAt(result.framePaths.get(0)!, "");+ expect([expected.length, shown.length]).toEqual([3, 3]);+ const worst = Math.max(...shown.map((v, i) => Math.abs(v - expected[i]!)));+ expect(worst, `${matrix} decode ${expected}, ${format} ${shown}`).toBeLessThanOrEqual(+ format === "png" ? 1 : 3,+ );+ },+ 60_000,+ );++ // ffmpeg < 6.1 drops frame durations from CFR resampling once any -vf is set, so the colour+ // filters would cut the still that ends this window short.+ it.each([+ {+ name: "full range BT.709",+ format: "png",+ codec: "libx264",+ pixFmt: "yuvj420p",+ probed: { colorTransfer: "bt709" },+ tags: "range=pc:color_primaries=bt709:color_trc=bt709:colorspace=bt709",+ },+ {+ name: "full range BT.709",+ format: "jpg",+ codec: "libx264",+ pixFmt: "yuvj420p",+ probed: { colorTransfer: "bt709" },+ tags: "range=pc:color_primaries=bt709:color_trc=bt709:colorspace=bt709",+ },+ {+ name: "BT.470BG gamma 2.8",+ format: "png",+ codec: "libx264",+ pixFmt: "yuv420p",+ probed: { colorTransfer: "bt470bg" },+ tags: "color_primaries=bt470bg:color_trc=bt470bg:colorspace=bt470bg",+ },+ {+ name: "RGB",+ format: "png",+ codec: "libx264rgb",+ pixFmt: "rgb24",+ probed: { colorSpace: "gbr" },+ tags: "",+ },+ ] as const)(+ "keeps every frame and the colours of a $name VFR window that ends on a still ($format)",+ async ({ name, format, codec, pixFmt, probed, tags }) => {+ const fixture = join(FIXTURE_DIR, `vfr-still-${name.replace(/\W+/g, "-")}-${format}.mp4`);+ const synth = await runFfmpeg([+ "-y",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ `color=c=0xC83C28:s=${UI_FIXTURE_WIDTH}x${UI_FIXTURE_HEIGHT}:d=2:r=60`,+ "-vf",+ `select='not(between(n\\,30\\,89))'${tags ? `,setparams=${tags}` : ""}`,+ "-fps_mode",+ "vfr",+ "-c:v",+ codec,+ "-preset",+ "ultrafast",+ "-pix_fmt",+ pixFmt,+ fixture,+ ]);+ if (!synth.success) throw new Error(`fixture synthesis failed: ${synth.stderr.slice(-400)}`);+ const window = 0.616666;+ const unfilteredDir = join(FIXTURE_DIR, `out-${basename(fixture)}-unfiltered`);+ mkdirSync(unfilteredDir, { recursive: true });+ const unfiltered = await runFfmpeg([+ "-v",+ "error",+ "-ss",+ "0",+ "-i",+ fixture,+ "-t",+ String(window),+ "-fps_mode",+ "cfr",+ "-r",+ "30",+ join(unfilteredDir, "f_%05d.png"),+ ]);+ expect(unfiltered.success).toBe(true);++ const result = await extractVideoFramesRange(fixture, basename(fixture), 0, window, {+ fps: 30,+ outputDir: join(FIXTURE_DIR, "out-vfr-still"),+ format,+ });++ expect(result.metadata.isVFR).toBe(true);+ expect(result.metadata.colorSpace).toMatchObject(probed);+ expect(result.totalFrames).toBe(readdirSync(unfilteredDir).length);+ const last = result.framePaths.get(result.totalFrames - 1)!;+ const source = readFirstFramePixel(fixture, 10, 10);+ const shown = readFirstFramePixel(last, 10, 10);+ const worst = Math.max(...shown.map((v, i) => Math.abs(v - source[i]!)));+ expect(worst, `source ${source} ${format} ${shown}`).toBeLessThanOrEqual(+ format === "png" ? 0 : 3,+ );+ if (format === "png") expect(pngChunkTypes(last)).toContain("sRGB");+ },+ 60_000,+ );++ it("leaves SDR-to-HDR frames in the HDR colours they were converted to", async () => {+ const outputDir = join(FIXTURE_DIR, "out-sdr-to-hdr-gate");+ mkdirSync(outputDir, { recursive: true });++ const result = await extractVideoFramesRange(UI_FIXTURE, "sdr-to-hdr-gate", 0, 1, {+ fps: 1,+ outputDir,+ format: "png",+ sdrToHdrTransfer: "pq",+ });++ expect(pngChunkTypes(result.framePaths.get(0)!)).not.toContain("sRGB");+ }, 60_000);+it("keeps jpg and png extraction caches separate", async () => {const cacheDir = mkdtempSync(join(tmpdir(), "hf-extract-format-cache-"));try {@@ -2861,6 +3155,69 @@ describe.skipIf(!HAS_FFMPEG || process.platform === "darwin")("forced-SDR HDR exexpect(frame(plain)).not.toEqual(frame(toneMapped));expect(frame(toneMappedAgain)).toEqual(frame(toneMapped));}, 60_000);++ // A second process would read the frames back without the HDR10 light-level metadata the tone map uses.+ it("tone-maps a VFR HDR10 window in one process, exactly as the unfiltered resample would", async () => {+ const source = join(fixtureDir, "pq-vfr-4000nit.mp4");+ const synthesized = await runFfmpeg([+ "-y",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ "color=c=0xf0e0c0:s=64x64:r=60:d=2",+ "-vf",+ "select='not(between(n\\,30\\,89))',zscale=pin=bt709:tin=bt709:min=bt709:p=bt2020:t=smpte2084:m=bt2020nc:r=tv:npl=1000,format=yuv420p10le",+ "-fps_mode",+ "vfr",+ "-c:v",+ "libx265",+ "-x265-params",+ "log-level=error:hdr10=1:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:max-cll=4000,400:master-display=G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(40000000,50)",+ source,+ ]);+ if (!synthesized.success)+ throw new Error(`PQ fixture synthesis failed: ${synthesized.stderr.slice(-400)}`);+ const referenceDir = join(fixtureDir, "pq-vfr-reference");+ mkdirSync(referenceDir, { recursive: true });+ const reference = await runFfmpeg([+ "-v",+ "error",+ "-ss",+ "0",+ "-i",+ source,+ "-t",+ "0.616666",+ "-vf",+ "zscale=t=linear:npl=100,tonemap=hable:desat=0,zscale=p=bt709:t=bt709:m=bt709:r=tv",+ "-fps_mode",+ "cfr",+ "-r",+ "30",+ "-q:v",+ "0",+ "-compression_level",+ "1",+ join(referenceDir, "frame_%05d.png"),+ ]);+ expect(reference.success, reference.stderr).toBe(true);++ const result = await extractVideoFramesRange(source, "pq-vfr", 0, 0.616666, {+ fps: 30,+ outputDir: join(fixtureDir, "pq-vfr-out"),+ format: "png",+ toneMapHdrToSdr: true,+ });++ expect(result.metadata.isVFR).toBe(true);+ const referenceFrames = readdirSync(referenceDir).sort();+ expect(result.totalFrames).toBe(referenceFrames.length);+ expect(readFileSync(result.framePaths.get(0)!)).toEqual(+ readFileSync(join(referenceDir, referenceFrames[0]!)),+ );+ }, 60_000);});describe("getFrameAtTime — IEEE 754 boundary precision", () => {diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.tsindex 1c181e6883..a7b1103dac 100644--- a/packages/engine/src/services/videoFrameExtractor.ts+++ b/packages/engine/src/services/videoFrameExtractor.ts@@ -48,7 +48,7 @@ import {UrlDownloadError,writeUrlDownloadTelemetry,} from "../utils/urlDownloader.js";-import { runFfmpeg } from "../utils/runFfmpeg.js";+import { runFfmpeg, runFfmpegPipeline, type RunFfmpegResult } from "../utils/runFfmpeg.js";import { DEFAULT_CONFIG, type EngineConfig } from "../config.js";import { unwrapTemplate } from "../utils/htmlTemplate.js";import {@@ -221,6 +221,9 @@ const SDR_TO_HDR_COLORSPACE_FILTER = "colorspace=all=bt2020:iall=bt709:range=tv"const HDR_TO_SDR_TONEMAP_FILTER ="zscale=t=linear:npl=100,tonemap=hable:desat=0,zscale=p=bt709:t=bt709:m=bt709:r=tv";const HDR_TO_SDR_TRANSFORM_KEY = "hdr2sdr-hable-bt709";+const SDR_CANVAS_PASSTHROUGH_FILTER = "setparams=color_primaries=bt709:color_trc=iec61966-2-1";+const SDR_JPEG_AS_BT601_FULL_RANGE_FILTER =+ "scale=flags=neighbor,format=gbrp,scale=out_color_matrix=bt601:out_range=pc:flags=neighbor,format=yuv420p";function sdrToHdrTransformKey(transfer: HdrTransfer): string {return `sdr2hdr-${transfer}`;@@ -751,6 +754,71 @@ export function parseImageElements(html: string): ImageElement[] {return images;}+/** Chrome plays untagged VP9 and AV1 as BT.601, H.264 and VP8 as BT.709 from 720 lines (assumed for the rest). */+const CHROME_BT601_UNTAGGED_CODECS = new Set(["vp9", "av1"]);++function chromeGuessForUntaggedMatrix(metadata: VideoMetadata): string[] {+ const matrix = metadata.colorSpace?.colorSpace;+ if (matrix && matrix !== "unknown") return [];+ const hd = metadata.height >= 720 && !CHROME_BT601_UNTAGGED_CODECS.has(metadata.videoCodec);+ return [`setparams=colorspace=${hd ? "bt709" : "smpte170m"}`];+}++/** Pixel formats nut carries as raw video unchanged on ffmpeg 5.1 to 8.1 (yuvj only loses its range). */+const NUT_RAW_PIXEL_FORMATS = new Set([+ "yuv420p",+ "yuvj420p",+ "yuv422p",+ "yuvj422p",+ "yuv444p",+ "yuvj444p",+ "yuva420p",+ "yuva444p",+ "yuv440p",+ "yuv411p",+ "yuv410p",+ "yuva422p",+ "yuv420p10le",+ "yuv422p10le",+ "yuv444p10le",+ "yuva420p10le",+ "yuva444p10le",+ "yuv420p12le",+ "nv12",+ "nv21",+ "yuyv422",+ "uyvy422",+ "gray",+ "gray10le",+ "ya8",+ "gbrp",+ "gbrap",+ "gbrp10le",+ "gbrp12le",+ "gbrap10le",+ "rgb24",+ "bgr24",+ "rgba",+ "bgra",+ "argb",+ "abgr",+ "rgb48le",+ "rgba64le",+]);++/** nut drops colour tags, so raw frames get the source's back before any other filter reads them. */+function restoreSourceColourFilter(metadata: VideoMetadata): string[] {+ const tags = [+ ["range", metadata.colorRange],+ ["colorspace", metadata.colorSpace?.colorSpace],+ ["color_primaries", metadata.colorSpace?.colorPrimaries],+ ["color_trc", metadata.colorSpace?.colorTransfer],+ ].filter(([, value]) => value && value !== "unknown" && value !== "reserved");+ return tags.length > 0+ ? [`setparams=${tags.map(([key, value]) => `${key}=${value}`).join(":")}`]+ : [];+}+export async function extractVideoFramesRange(videoPath: string,videoId: string,@@ -856,17 +924,46 @@ export async function extractVideoFramesRange(if (options.toneMapHdrToSdr && isHdr && !isMacOS) {vfFilters.push(HDR_TO_SDR_TONEMAP_FILTER);}- if (vfFilters.length > 0) args.push("-vf", vfFilters.join(","));- if (!options.finalFrameOnly && metadata.isVFR) {- args.push("-fps_mode", "cfr", "-r", ffmpegFps);+ if (!isHdr && !options.sdrToHdrTransfer) {+ vfFilters.push(...chromeGuessForUntaggedMatrix(metadata), SDR_CANVAS_PASSTHROUGH_FILTER);+ if (format === "jpg") vfFilters.push(SDR_JPEG_AS_BT601_FULL_RANGE_FILTER);}-- args.push("-q:v", format === "jpg" ? String(Math.ceil((100 - quality) / 3)) : "0");+ const encodeArgs = ["-q:v", format === "jpg" ? String(Math.ceil((100 - quality) / 3)) : "0"];// Render-scoped temp frames are read once; level 1 measured 3-5x faster for ~14% larger files.- if (format === "png") args.push("-compression_level", "1");- args.push("-y", outputPattern);+ if (format === "png") encodeArgs.push("-compression_level", "1");+ encodeArgs.push("-y", outputPattern);- const processResult = await runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout });+ const runOptions = { signal, timeout: ffmpegProcessTimeout };+ const resampleVfrToCfr = !options.finalFrameOnly && metadata.isVFR;+ if (resampleVfrToCfr) args.push("-fps_mode", "cfr", "-r", ffmpegFps);+ let processResult: RunFfmpegResult;+ if (+ resampleVfrToCfr &&+ vfFilters.length > 0 &&+ !isHdr &&+ NUT_RAW_PIXEL_FORMATS.has(metadata.pixelFormat ?? "")+ ) {+ // ffmpeg <6.1 ignores frame durations in CFR resampling once any -vf is set,+ // cutting a trailing still short, so the SDR filters run in a second process.+ processResult = await runFfmpegPipeline(+ [...args, "-an", "-sn", "-dn", "-c:v", "rawvideo", "-f", "nut", "pipe:1"],+ [+ "-f",+ "nut",+ "-i",+ "pipe:0",+ "-vf",+ [...restoreSourceColourFilter(metadata), ...vfFilters].join(","),+ "-fps_mode",+ "passthrough",+ ...encodeArgs,+ ],+ runOptions,+ );+ } else {+ if (vfFilters.length > 0) args.push("-vf", vfFilters.join(","));+ processResult = await runFfmpeg([...args, ...encodeArgs], runOptions);+ }if (processResult.failureReason === "external_interruption") {throw new VideoSourceExtractionError("external_interruption",diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.tsindex 1ac3f4e8ae..67c39d32dd 100644--- a/packages/engine/src/utils/ffprobe.ts+++ b/packages/engine/src/utils/ffprobe.ts@@ -188,6 +188,8 @@ export interface VideoMetadata {hasAlpha: boolean;/** Color space info from the video stream. Null if ffprobe didn't report it. */colorSpace: VideoColorSpace | null;+ colorRange?: string;+ pixelFormat?: string;/** Decoded frame count from the video stream's `nb_frames`. Omitted when the* container does not surface a reliable count (still images, malformed* streams, or muxes that require `-count_packets` to populate). Callers@@ -224,6 +226,7 @@ interface FFProbeStream {avg_frame_rate?: string;sample_rate?: string;channels?: number;+ color_range?: string;color_transfer?: string;color_primaries?: string;color_space?: string;@@ -788,6 +791,8 @@ export async function extractMediaMetadata(filePath: string): Promise<VideoMetadisVFR,hasAlpha,colorSpace,+ colorRange: videoStream.color_range,+ pixelFormat,frames,};})();diff --git a/packages/engine/src/utils/runFfmpeg.test.ts b/packages/engine/src/utils/runFfmpeg.test.tsindex 5e70cca864..adcffb41b3 100644--- a/packages/engine/src/utils/runFfmpeg.test.ts+++ b/packages/engine/src/utils/runFfmpeg.test.ts@@ -1,8 +1,13 @@+import { spawnSync } from "node:child_process";import { EventEmitter } from "node:events";-import { resolve } from "node:path";+import { mkdtempSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";-import { formatFfmpegError, isExternalFfmpegInterruption } from "./runFfmpeg.js";+import { formatFfmpegError, isExternalFfmpegInterruption, runFfmpegPipeline } from "./runFfmpeg.js";++const HAS_FFMPEG = spawnSync("ffmpeg", ["-version"]).status === 0;describe("isExternalFfmpegInterruption", () => {const base = {@@ -175,3 +180,111 @@ describe("runFfmpeg binary resolution", () => {expect(calls[0]).toEqual({ command: resolve("/tools/ffmpeg.exe"), args: ["-version"] });});});++describe.skipIf(!HAS_FFMPEG)("runFfmpegPipeline", () => {+ const rawFrames = (source: string) => [+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ source,+ "-c:v",+ "rawvideo",+ "-f",+ "nut",+ "pipe:1",+ ];++ it("hands every producer frame to the consumer", async () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-pipeline-"));+ try {+ const result = await runFfmpegPipeline(rawFrames("testsrc2=s=64x16:d=0.2:r=30"), [+ "-v",+ "error",+ "-f",+ "nut",+ "-i",+ "pipe:0",+ "-fps_mode",+ "passthrough",+ join(dir, "f_%03d.png"),+ ]);+ expect(result.success, result.stderr).toBe(true);+ expect(readdirSync(dir)).toHaveLength(6);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }, 30_000);++ it("fails with the producer's error when the producer cannot start its input", async () => {+ const result = await runFfmpegPipeline(+ [+ "-v",+ "error",+ "-i",+ join(tmpdir(), "hf-missing-input.mp4"),+ "-c:v",+ "rawvideo",+ "-f",+ "nut",+ "pipe:1",+ ],+ ["-v", "error", "-f", "nut", "-i", "pipe:0", "-f", "null", "-"],+ );+ expect(result.success).toBe(false);+ expect(result.stderr).toMatch(/hf-missing-input\.mp4/);+ }, 30_000);++ it("stops an endless producer when the consumer fails", async () => {+ const startedAt = Date.now();+ const result = await runFfmpegPipeline(+ rawFrames("testsrc2=s=320x240:r=30"),+ ["-v", "error", "-f", "nut", "-i", "pipe:0", "-vf", "hf_missing_filter", "-f", "null", "-"],+ { timeout: 20_000 },+ );+ expect(result.success).toBe(false);+ expect(result.terminationReason).toBe("exit");+ expect(result.stderr).toMatch(/hf_missing_filter/);+ expect(Date.now() - startedAt).toBeLessThan(10_000);+ }, 30_000);+});++describe("runFfmpegPipeline start failure", () => {+ afterEach(() => {+ vi.resetModules();+ vi.doUnmock("child_process");+ });++ it("releases a waiting consumer when the producer cannot start", async () => {+ const { PassThrough, Writable } = await import("node:stream");+ const producer = Object.assign(new EventEmitter(), {+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ kill: vi.fn(),+ pid: 4242,+ });+ const consumer = Object.assign(new EventEmitter(), {+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ stdin: new Writable({ write: (_chunk, _encoding, done) => done() }),+ kill: vi.fn(),+ pid: 4243,+ });+ consumer.stdin.on("finish", () => consumer.emit("close", 1, null));+ const spawn = vi.fn().mockReturnValueOnce(producer).mockReturnValueOnce(consumer);+ vi.resetModules();+ vi.doMock("child_process", () => ({ spawn }));+ const { runFfmpegPipeline: pipeline } = await import("./runFfmpeg.js");++ const startedAt = Date.now();+ const pending = pipeline(["-i", "in"], ["-i", "pipe:0"], { timeout: 5_000 });+ consumer.emit("spawn");+ producer.emit("error", Object.assign(new Error("spawn EMFILE"), { code: "EMFILE" }));+ const result = await pending;++ expect(result.success).toBe(false);+ expect(result.terminationReason).toBe("spawn_error");+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ });+});diff --git a/packages/engine/src/utils/runFfmpeg.ts b/packages/engine/src/utils/runFfmpeg.tsindex d82772e1ae..fa2ddbcc48 100644--- a/packages/engine/src/utils/runFfmpeg.ts+++ b/packages/engine/src/utils/runFfmpeg.ts@@ -6,11 +6,12 @@* that appears across audioMixer and chunkEncoder into a single helper.*/-import { spawn } from "child_process";+import { spawn, type ChildProcess } from "child_process";import { getFfmpegBinary } from "./ffmpegBinaries.js";import { trackChildProcess } from "./processTracker.js";import {ManagedChildProcess,+ type ManagedChildProcessOutcome,type ManagedProcessTerminationReason,} from "./managedChildProcess.js";@@ -110,25 +111,26 @@ export function formatFfmpegError(: `FFmpeg exited with code ${exitCode}`;}-export async function runFfmpeg(args: string[], opts?: RunFfmpegOptions): Promise<RunFfmpegResult> {- const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;+function spawnFfmpeg(args: string[]): ChildProcess {// windowsHide: ffmpeg/ffprobe are console-subsystem binaries, so without// this Node opens a visible console window per spawn on Windows. A render// shells out dozens of times across parallel workers, which flashes a burst// of windows across the user's desktop. No-op on macOS and Linux.const ffmpeg = spawn(getFfmpegBinary(), args, { windowsHide: true });trackChildProcess(ffmpeg);- const managed = new ManagedChildProcess(ffmpeg, {- signal: opts?.signal,- deadlineAtMs: Date.now() + timeout,- onStderr: opts?.onStderr,- });- const outcome = await managed.wait();+ return ffmpeg;+}++function succeeded(outcome: ManagedChildProcessOutcome): boolean {+ return outcome.reason === "exit" && outcome.exitCode === 0;+}++function toResult(outcome: ManagedChildProcessOutcome, stderr = outcome.stderr): RunFfmpegResult {const result: RunFfmpegResult = {- success: outcome.reason === "exit" && outcome.exitCode === 0,+ success: succeeded(outcome),exitCode: outcome.exitCode,signal: outcome.signal,- stderr: outcome.stderr,+ stderr,durationMs: outcome.durationMs,terminationReason: outcome.reason,error: outcome.error,@@ -138,3 +140,54 @@ export async function runFfmpeg(args: string[], opts?: RunFfmpegOptions): Promis}return result;}++export async function runFfmpeg(args: string[], opts?: RunFfmpegOptions): Promise<RunFfmpegResult> {+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;+ const managed = new ManagedChildProcess(spawnFfmpeg(args), {+ signal: opts?.signal,+ deadlineAtMs: Date.now() + timeout,+ onStderr: opts?.onStderr,+ });+ return toResult(await managed.wait());+}++/**+ * Runs `ffmpeg <producerArgs> | ffmpeg <consumerArgs>`. Fails when either side+ * fails and reports the first failure, its stderr last so error tails show it.+ */+export async function runFfmpegPipeline(+ producerArgs: string[],+ consumerArgs: string[],+ opts?: RunFfmpegOptions,+): Promise<RunFfmpegResult> {+ const deadlineAtMs = Date.now() + (opts?.timeout ?? DEFAULT_TIMEOUT);+ const producer = spawnFfmpeg(producerArgs);+ const consumer = spawnFfmpeg(consumerArgs);+ // Either side ending early, or failing to start, must release the other from the pipe.+ consumer.stdin?.on("error", () => {});+ for (const event of ["close", "error"] as const) {+ consumer.once(event, () => producer.stdout?.destroy());+ producer.once(event, () => consumer.stdin?.end());+ }+ if (consumer.stdin) producer.stdout?.pipe(consumer.stdin);+ const settleOrder: ManagedChildProcessOutcome[] = [];+ const outcomes = await Promise.all(+ [producer, consumer].map((child) =>+ new ManagedChildProcess(child, {+ signal: opts?.signal,+ deadlineAtMs,+ onStderr: opts?.onStderr,+ })+ .wait()+ .then((outcome) => {+ settleOrder.push(outcome);+ return outcome;+ }),+ ),+ );+ const reported = settleOrder.find((outcome) => !succeeded(outcome)) ?? outcomes[1]!;+ const stderr = [...outcomes.filter((outcome) => outcome !== reported), reported]+ .map((outcome) => outcome.stderr)+ .join("");+ return toResult(reported, stderr);+}diff --git a/packages/engine/src/utils/sdrCaptureColor.ts b/packages/engine/src/utils/sdrCaptureColor.tsnew file mode 100644index 0000000000..3a8e240144--- /dev/null+++ b/packages/engine/src/utils/sdrCaptureColor.ts@@ -0,0 +1,3 @@+export const SDR_RGB_TO_BT709_FILTER = "scale=out_color_matrix=bt709:out_range=tv:flags=neighbor";++export const SDR_CAPTURE_TO_BT709_FILTER = `scale=in_color_matrix=bt601:in_range=pc:flags=neighbor,format=gbrp,${SDR_RGB_TO_BT709_FILTER}`;diff --git a/packages/producer/tests/distributed/static-volume-future-set/output/output.mp4 b/packages/producer/tests/distributed/static-volume-future-set/output/output.mp4index 5c19b68cbb..cf82b1e1be 100644--- a/packages/producer/tests/distributed/static-volume-future-set/output/output.mp4+++ b/packages/producer/tests/distributed/static-volume-future-set/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:84699f00ac13eca17781789e1f114bd549ce631d43502aa8ce279ca77a63886b-size 60235+oid sha256:be14baf2cc15850ae357f217cb8f75ae5a2ce5a5a02509170fa27bbfc333de51+size 65309diff --git a/packages/producer/tests/hf2550-video-subcomposition-ghost/output/output.mp4 b/packages/producer/tests/hf2550-video-subcomposition-ghost/output/output.mp4index a8286e46e5..c787935534 100644--- a/packages/producer/tests/hf2550-video-subcomposition-ghost/output/output.mp4+++ b/packages/producer/tests/hf2550-video-subcomposition-ghost/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:697405f1eaa0f52dbe265d4c2a7674d70d18a05072a14921ded5c3237d377d1c-size 67061526+oid sha256:e091aee82c20da5e340e9f2a9c85c29474c4ed6be8220df1494c7f128f1749ce+size 65763536diff --git a/packages/producer/tests/nested-sequential-video-local-start/output/output.mp4 b/packages/producer/tests/nested-sequential-video-local-start/output/output.mp4index ccca6a533f..88ffab3829 100644--- a/packages/producer/tests/nested-sequential-video-local-start/output/output.mp4+++ b/packages/producer/tests/nested-sequential-video-local-start/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:7e56506833244506267cbe6c8bdd971eb2f92fbf96a83ce18c7565c74ecbfcae-size 2829+oid sha256:a20970478bdda73a8d1b2610d5046ea1ec05db25340251dd712230b3db57d975+size 3109diff --git a/packages/producer/tests/page-side-shader-compositor-render-compat/output/output.mp4 b/packages/producer/tests/page-side-shader-compositor-render-compat/output/output.mp4index 623bfc8f84..c6d11c7ace 100644--- a/packages/producer/tests/page-side-shader-compositor-render-compat/output/output.mp4+++ b/packages/producer/tests/page-side-shader-compositor-render-compat/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:adf207334fd405162b2989f861819f176116661de4aa3432344a123d42bdd23a-size 1029195+oid sha256:597949c9308c0436609f731291b9050d3d25efcd730c1d5db8f1a1cff76a0184+size 1019952diff --git a/packages/producer/tests/render-symlinked-assets/output/output.mp4 b/packages/producer/tests/render-symlinked-assets/output/output.mp4index e4db6f4a3a..906138e236 100644--- a/packages/producer/tests/render-symlinked-assets/output/output.mp4+++ b/packages/producer/tests/render-symlinked-assets/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:d73f03b86c6c60f8900627df3a71771b47386add8bcbb50ed7b162b81abea976-size 10433+oid sha256:a2244360ee769eb20661c7a36321783bc657a4c87de7bf11860dcd2095e3386e+size 10480diff --git a/packages/producer/tests/speed-ramp/output/output.mp4 b/packages/producer/tests/speed-ramp/output/output.mp4index 9372ed20ae..d6d2eaf41e 100644--- a/packages/producer/tests/speed-ramp/output/output.mp4+++ b/packages/producer/tests/speed-ramp/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:ffc894beb65de635d6e19a083af3937bab55864ddfb6746edabe4272ae12f68b-size 283643+oid sha256:a0aa5f4a6c032286630b386ea53feea7739a8deef5792a4c770bff54ebf171ae+size 277335diff --git a/packages/producer/tests/subcomp-bare-fragment/output/output.mp4 b/packages/producer/tests/subcomp-bare-fragment/output/output.mp4index a240793c37..c0a0a56d55 100644--- a/packages/producer/tests/subcomp-bare-fragment/output/output.mp4+++ b/packages/producer/tests/subcomp-bare-fragment/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:21635cf3545ee9c36568cf2b68c31c23ae1c5d03b9b645b926b73ee9e4999eb2-size 7693+oid sha256:e7b4f73d97c019701a8a40cfd3f3b34c649ab6030a3aa42af31a9dd81e820bd6+size 8010diff --git a/packages/producer/tests/timed-descendant-visibility/output/output.mp4 b/packages/producer/tests/timed-descendant-visibility/output/output.mp4index 75e3823d65..59f49e223e 100644--- a/packages/producer/tests/timed-descendant-visibility/output/output.mp4+++ b/packages/producer/tests/timed-descendant-visibility/output/output.mp4@@ -1,3 +1,3 @@version https://git-lfs.github.com/spec/v1-oid sha256:c5aac54303c4422aed7b0264c007dcfb314fca3dc74a16905eafff3914fb95e7-size 21971+oid sha256:8394303d13bead5195ad75144d0c6b82b5bd5bb931d6bee0775e20a142cd1eff+size 20401