Skip to content

Commit 2af3f4d

Browse files
vanceingallsclaude
andcommitted
fix(engine): stop the PNG walk at cICP, anchor IHDR, use native crc32
Three defects in the PNG metadata fallback, all introduced when the cICP early return became an accumulator. Corrupt trailing chunk nulls a good result. cICP must precede IDAT, so continuing past it only visits chunks this parser ignores — while making whole-file integrity a precondition for returning anything. A truncated or bad-CRC chunk after cICP in an otherwise-good HDR PNG returned null, and extractMediaMetadata then re-throws the ffprobe error it had swallowed instead of using the fallback it just computed: the render dies on a host without FFmpeg, or grades SDR on a build that does not decode cICP. Now stops once dimensions and colour are known. A second IHDR overwrote the dimensions. PNG permits exactly one, first, but nothing enforced that here — a trailing [IHDR 1x1] replaced a real 3840x2160 and the producer laid out a one-pixel image. Anchored to the first. The length guard was also `>= 8` against a spec length of 13, which accepted a truncated header and read height out of the CRC bytes. crc32 was hand-rolled bit-at-a-time and fed a Buffer.concat per chunk. Since the walk no longer stops early it CRC'd whole files: 210 ms on a 12 MiB PNG, 647 ms on a 35 MiB 4K one, synchronously on the event loop, plus ~11 MB of garbage per parse from concatenating a 4-byte type tag onto every chunk. node:zlib's crc32 is native and takes a running seed, so type and data hash in sequence with no copy. 210.28 ms -> 1.291 ms. Tests: 5 regressions — corrupt-after-cICP, truncation after cICP, second IHDR, short IHDR, and that a corrupt IHDR/cICP still rejects. Reverting the break or the anchor fails 3. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 3a6b7f0 commit 2af3f4d

2 files changed

Lines changed: 93 additions & 14 deletions

File tree

‎packages/engine/src/utils/ffprobe.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,3 +642,70 @@ describe("extractPngMetadataFromBuffer cICP ordering", () => {
642642
expect(extractPngMetadataFromBuffer(onlyCicp)).toBeNull();
643643
});
644644
});
645+
646+
describe("PNG chunk walk — integrity of the fallback itself", () => {
647+
const IHDR_4K = [0, 0, 0x0f, 0, 0, 0, 0x08, 0x70, 16, 2, 0, 0, 0];
648+
const CICP_PQ = [9, 16, 0, 1];
649+
650+
// Regression: the walk used to continue past cICP to IEND, which made
651+
// whole-file integrity a precondition for returning anything. A damaged
652+
// trailing chunk in an otherwise-good HDR PNG nulled the whole result, and
653+
// extractMediaMetadata then re-throws the ffprobe error it had swallowed
654+
// rather than using the fallback it just computed.
655+
it("returns metadata even when a chunk AFTER cICP is corrupt", () => {
656+
const bad = pngChunk("tEXt", [65, 66]);
657+
bad[bad.length - 1] ^= 0xff; // break the CRC
658+
const png = buildPngWithChunks([
659+
pngChunk("IHDR", IHDR_4K),
660+
pngChunk("cICP", CICP_PQ),
661+
pngChunk("IDAT", [0x78, 0x9c, 0x63, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01]),
662+
bad,
663+
pngChunk("IEND", []),
664+
]);
665+
expect(extractPngMetadataFromBuffer(png)).toEqual({
666+
width: 3840,
667+
height: 2160,
668+
colorSpace: { colorPrimaries: "bt2020", colorTransfer: "smpte2084", colorSpace: "gbr" },
669+
});
670+
});
671+
672+
it("survives outright truncation after cICP", () => {
673+
const png = buildPngWithChunks([pngChunk("IHDR", IHDR_4K), pngChunk("cICP", CICP_PQ)]);
674+
const truncated = Buffer.concat([png, Buffer.from([0, 0, 0x7f, 0xff, 73, 68, 65, 84])]);
675+
expect(extractPngMetadataFromBuffer(truncated)?.width).toBe(3840);
676+
});
677+
678+
// Regression: IHDR had no first-chunk anchor, so a later one overwrote the
679+
// real dimensions and the producer laid out a 1-pixel image.
680+
it("ignores a second IHDR", () => {
681+
const png = buildPngWithChunks([
682+
pngChunk("IHDR", IHDR_4K),
683+
pngChunk("cICP", CICP_PQ),
684+
pngChunk("IDAT", [0x78, 0x9c, 0x63, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01]),
685+
pngChunk("IHDR", [0, 0, 0, 1, 0, 0, 0, 1, 16, 2, 0, 0, 0]),
686+
pngChunk("IEND", []),
687+
]);
688+
const meta = extractPngMetadataFromBuffer(png);
689+
expect(meta?.width).toBe(3840);
690+
expect(meta?.height).toBe(2160);
691+
});
692+
693+
// A truncated 8-byte IHDR used to be accepted, reading height out of the
694+
// CRC bytes; the spec length is 13.
695+
it("rejects a short IHDR rather than reading garbage dimensions", () => {
696+
const png = buildPngWithChunks([
697+
pngChunk("IHDR", [0, 0, 0, 7, 0, 0, 0, 9]),
698+
pngChunk("cICP", CICP_PQ),
699+
pngChunk("IEND", []),
700+
]);
701+
expect(extractPngMetadataFromBuffer(png)).toBeNull();
702+
});
703+
704+
it("still rejects a PNG whose IHDR or cICP itself is corrupt", () => {
705+
const badIhdr = pngChunk("IHDR", IHDR_4K);
706+
badIhdr[badIhdr.length - 1] ^= 0xff;
707+
expect(
708+
extractPngMetadataFromBuffer(buildPngWithChunks([badIhdr, pngChunk("IEND", [])])),
709+
).toBeNull();
710+
});
711+
});

‎packages/engine/src/utils/ffprobe.ts‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// fallow-ignore-file code-duplication complexity
22
import { spawn } from "child_process";
33
import { readFileSync } from "fs";
4+
import { crc32 } from "node:zlib";
45
import { basename, extname } from "path";
56
import { redactTelemetryString } from "@hyperframes/core";
67
import { FFPROBE_PATH_ENV, getFfprobeBinary } from "./ffmpegBinaries.js";
@@ -167,16 +168,13 @@ interface StillImageMetadata {
167168
colorSpace: VideoColorSpace | null;
168169
}
169170

170-
function crc32(buf: Buffer): number {
171-
let crc = 0xffffffff;
172-
for (let i = 0; i < buf.length; i++) {
173-
crc ^= buf[i] ?? 0;
174-
for (let bit = 0; bit < 8; bit++) {
175-
const mask = -(crc & 1);
176-
crc = (crc >>> 1) ^ (0xedb88320 & mask);
177-
}
178-
}
179-
return (crc ^ 0xffffffff) >>> 0;
171+
// node:zlib's crc32 is native and takes a running seed, so the chunk type and
172+
// the chunk data can be CRC'd in sequence without concatenating them into a
173+
// throwaway buffer. The hand-rolled bit-at-a-time loop this replaces cost
174+
// ~210 ms on a 12 MiB PNG; this is ~1.3 ms. Available on this repo's
175+
// "node": ">=22".
176+
function chunkCrc32(chunkType: string, chunkData: Buffer): number {
177+
return crc32(chunkData, crc32(Buffer.from(chunkType, "ascii")));
180178
}
181179

182180
export function extractPngMetadataFromBuffer(buf: Buffer): StillImageMetadata | null {
@@ -205,10 +203,14 @@ export function extractPngMetadataFromBuffer(buf: Buffer): StillImageMetadata |
205203
if (pos + 12 + chunkLen > buf.length) return null;
206204
const chunkData = buf.subarray(pos + 8, pos + 8 + chunkLen);
207205
const chunkCrc = buf.readUInt32BE(pos + 8 + chunkLen);
208-
const chunkBytes = Buffer.concat([Buffer.from(chunkType, "ascii"), chunkData]);
209-
if (crc32(chunkBytes) !== chunkCrc) return null;
210-
211-
if (chunkType === "IHDR" && chunkLen >= 8) {
206+
if (chunkCrc32(chunkType, chunkData) !== chunkCrc) return null;
207+
208+
// First IHDR only. PNG permits exactly one and it must come first, but a
209+
// malformed file can carry more — without this anchor a trailing
210+
// [IHDR 1x1] silently replaced the real 4K dimensions, and the producer
211+
// laid out a one-pixel image. `>= 13` is the spec length; the old `>= 8`
212+
// accepted a truncated header and read height out of the CRC bytes.
213+
if (chunkType === "IHDR" && chunkLen >= 13 && width === 0 && height === 0) {
212214
width = buf.readUInt32BE(pos + 8);
213215
height = buf.readUInt32BE(pos + 12);
214216
}
@@ -242,6 +244,16 @@ export function extractPngMetadataFromBuffer(buf: Buffer): StillImageMetadata |
242244
};
243245
}
244246

247+
// Everything this parser extracts has been found, so stop walking.
248+
//
249+
// Not just an optimisation: cICP must precede IDAT (enforced above), so
250+
// continuing only ever visits chunks we ignore — while making whole-file
251+
// integrity a precondition for returning anything. A truncated or
252+
// bad-CRC trailing chunk in an otherwise-good HDR PNG used to null the
253+
// entire result, and the caller then re-throws the swallowed ffprobe
254+
// error instead of using the fallback it just computed.
255+
if (width > 0 && height > 0 && colorSpaceFromCicp !== null) break;
256+
245257
if (chunkType === "IEND") break;
246258
pos += 12 + chunkLen;
247259
}

0 commit comments

Comments
 (0)