Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/cli/src/commands/measure/probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
runFfmpeg,
type VideoInfo,
} from "../../measure/media.js";
import { toneMapReferenceNits } from "@hyperframes/core";
import { execFileSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { makeOutputFolder } from "../../utils/outputFolder.js";
Expand Down Expand Up @@ -54,7 +55,7 @@ function normalize(info: VideoInfo, out: string): { path: string; fps: string }
"install an ffmpeg built with libzimg, e.g. brew install ffmpeg",
);
filters.push(
"zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv",
`zscale=t=linear:npl=${toneMapReferenceNits(info.transfer ? [info.transfer] : [])},format=gbrpf32le,zscale=p=bt709,tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv`,
);
}
makeOutputFolder(dirname(out));
Expand Down
28 changes: 19 additions & 9 deletions packages/cli/src/commands/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,14 @@ import {
import {
firstFrameColourArgs,
hdrToSdrToneMapFilter,
keyframeTransferArgs,
parseKeyframeTransfers,
type ToneMapFrameColour,
isClipVisibleAt,
isInClipWindow,
MEDIA_RENDER_ID_ATTR,
parseFirstFrameColour,
readsKeyframeTransfers,
readElementRateSpec,
sourceTimeAt,
timeAtSourceTime,
Expand Down Expand Up @@ -620,20 +624,26 @@ async function videoColour(ffmpegPath: string, videoPath: string) {
metadata && isHdrColorSpace(metadata.colorSpace)
? hdrToSdrToneMapFilter(
metadata.colorSpace ?? {},
parseFirstFrameColour(
(
await runFfmpegOnce(
ffmpegPath,
firstFrameColourArgs(videoPath),
FFMPEG_EXTRACT_TIMEOUT_MS,
)
).stderr,
),
await frameColour(ffmpegPath, videoPath, metadata.videoCodec),
)
: null;
return { metadata, toneMap };
}

async function frameColour(
ffmpegPath: string,
videoPath: string,
codec: string,
): Promise<ToneMapFrameColour> {
const read = (args: string[]) => runFfmpegOnce(ffmpegPath, args, FFMPEG_EXTRACT_TIMEOUT_MS);
const probe = await read(firstFrameColourArgs(videoPath));
const first = parseFirstFrameColour(probe.stderr);
if (probe.code !== 0 || !readsKeyframeTransfers(first)) return first;
const keyframes = await read(keyframeTransferArgs(videoPath, codec));
const keyframeTransfers = keyframes.code === 0 ? parseKeyframeTransfers(keyframes.stderr) : [];
return { ...first, keyframeTransfers };
}

function frameFilters(
select: number | undefined,
displayedPixels: number,
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/measure/media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export interface VideoInfo {
/** The container's frame rate and the stream's average differ: frames are not evenly spaced. */
vfr: boolean;
hdr: boolean;
transfer?: string;
codec: string;
}

Expand Down Expand Up @@ -160,6 +161,7 @@ export function probeVideo(path: string): VideoInfo {
avgFps: avg || fps,
vfr: avg > 0 && Math.abs(avg - fps) / fps > 0.01,
hdr: /smpte2084|arib-std-b67/.test(video.color_transfer ?? ""),
transfer: video.color_transfer,
codec: video.codec_name ?? "",
};
}
Expand Down
95 changes: 87 additions & 8 deletions packages/core/src/hdrToneMap.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { spawnSync } from "node:child_process";
import { describe, expect, it } from "vitest";
import { hdrToSdrToneMapFilter } from "./hdrToneMap";
import {
hdrToSdrToneMapFilter,
keyframeTransferArgs,
parseKeyframeTransfers,
toneMapReferenceNits,
} from "./hdrToneMap";

const PQ = { colorSpace: "bt2020nc", colorPrimaries: "bt2020", colorTransfer: "smpte2084" };
const TONE_MAP =
"zscale=t=linear:npl=100,tonemap=hable:desat=0,zscale=p=bt709:t=bt709:m=bt709:r=tv";
const toneMap = (npl: number) =>
`zscale=t=linear:npl=${npl},tonemap=hable:desat=0,zscale=p=bt709:t=bt709:m=bt709:r=tv`;

describe("hdrToSdrToneMapFilter", () => {
it("leaves every frame its own tags when the first frame carries them all", () => {
expect(hdrToSdrToneMapFilter(PQ, PQ)).toBe(TONE_MAP);
expect(hdrToSdrToneMapFilter(PQ, PQ)).toBe(toneMap(100));
});

it("resizes in the first zscale, before the tone map, when it is given a size", () => {
Expand All @@ -18,10 +24,10 @@ describe("hdrToSdrToneMapFilter", () => {

it("sets the probed tags the first frame lacks", () => {
expect(hdrToSdrToneMapFilter(PQ, {})).toBe(
`setparams=colorspace=bt2020nc:color_primaries=bt2020:color_trc=smpte2084,${TONE_MAP}`,
`setparams=colorspace=bt2020nc:color_primaries=bt2020:color_trc=smpte2084,${toneMap(100)}`,
);
expect(hdrToSdrToneMapFilter(PQ, { colorTransfer: "arib-std-b67" })).toBe(
`setparams=colorspace=bt2020nc:color_primaries=bt2020,${TONE_MAP}`,
`setparams=colorspace=bt2020nc:color_primaries=bt2020,${toneMap(100)}`,
);
});

Expand All @@ -31,9 +37,82 @@ describe("hdrToSdrToneMapFilter", () => {
{ colorSpace: "unknown", colorTransfer: "arib-std-b67" },
{ colorSpace: "unknown", colorPrimaries: "unknown", colorTransfer: "arib-std-b67" },
),
).toBe(`setparams=colorspace=bt2020nc:color_primaries=bt2020,${TONE_MAP}`);
).toBe(`setparams=colorspace=bt2020nc:color_primaries=bt2020,${toneMap(100)}`);
expect(hdrToSdrToneMapFilter({ colorPrimaries: "reserved" }, {})).toBe(
`setparams=colorspace=bt2020nc:color_primaries=bt2020,${TONE_MAP}`,
`setparams=colorspace=bt2020nc:color_primaries=bt2020,${toneMap(100)}`,
);
});

it("maps a stream at BT.2408's 203-nit HLG reference white only when every keyframe is HLG", () => {
const hlg = { ...PQ, colorTransfer: "arib-std-b67" };
const keyframes = (...keyframeTransfers: string[]) => ({ ...hlg, keyframeTransfers });
expect(hdrToSdrToneMapFilter(hlg, keyframes("arib-std-b67", "arib-std-b67"))).toBe(
toneMap(203),
);
expect(hdrToSdrToneMapFilter(hlg, keyframes("arib-std-b67", "smpte2084"))).toBe(toneMap(100));
expect(hdrToSdrToneMapFilter(hlg, keyframes("arib-std-b67", "bt709"))).toBe(toneMap(100));
expect(hdrToSdrToneMapFilter(hlg, keyframes())).toBe(toneMap(100));
const untagged = (keyframeTransfers: string[]) => ({
colorTransfer: "unknown",
keyframeTransfers,
});
expect(hdrToSdrToneMapFilter(hlg, untagged(["unspecified", "arib-std-b67"]))).toContain(
"npl=203",
);
expect(hdrToSdrToneMapFilter(PQ, untagged(["unspecified"]))).toContain("npl=100");
expect(hdrToSdrToneMapFilter(PQ, { ...PQ, keyframeTransfers: ["smpte2084"] })).toBe(
toneMap(100),
);
expect(toneMapReferenceNits(undefined)).toBe(100);
});

it("names each SPS transfer trace_headers prints, and reads only keyframes' headers", () => {
const line = (code: number) =>
`[trace_headers @ 0x1] 287 transfer_characteristics 00010010 = ${code}`;
expect(parseKeyframeTransfers([18, 16, 1, 2, 4].map(line).join("\n"))).toEqual([
"arib-std-b67",
"smpte2084",
"bt709",
"unspecified",
"code 4",
]);
expect(keyframeTransferArgs("clip.mov", "hevc")).toContain(
"filter_units=pass_types=33,trace_headers",
);
expect(keyframeTransferArgs("clip.mov")).toEqual(expect.arrayContaining(["-discard", "nokey"]));
});
});

const FFMPEG_MAJOR = Number(
/ffmpeg version n?(\d+)/.exec(spawnSync("ffmpeg", ["-version"]).stdout?.toString() ?? "")?.[1] ??
0,
);
const HAS_ZSCALE = /\szscale\s/.test(
spawnSync("ffmpeg", ["-hide_banner", "-filters"]).stdout?.toString() ?? "",
);

/** The 8-bit full-range grey the chain makes of one 10-bit HLG code value. */
function toneMappedGrey(code: number): number {
const hlg = { colorSpace: "bt2020nc", colorPrimaries: "bt2020", colorTransfer: "arib-std-b67" };
const tags =
"setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc:range=tv";
const run = spawnSync("ffmpeg", [
...["-v", "error", "-f", "lavfi", "-i", "color=c=black:s=16x16:d=0.04"],
...[
"-vf",
`format=yuv420p10le,geq=lum=${code}:cb=512:cr=512,${tags},${hdrToSdrToneMapFilter(hlg, { ...hlg, keyframeTransfers: ["arib-std-b67"] })}`,
],
...["-frames:v", "1", "-pix_fmt", "gray", "-f", "rawvideo", "pipe:1"],
]);
const luma = run.stdout[0] ?? Number.NaN;
return Math.round(((luma - 16) * 255) / 219);
}

// ffmpeg before 8 bundles an older zimg that maps HLG white near 174, outside the tolerance.
describe.skipIf(!HAS_ZSCALE || FFMPEG_MAJOR < 8)("hdrToSdrToneMapFilter on HLG grey", () => {
// Apple's own SDR conversion (avconvert) of these 10-bit steps gives 105 and 161; at 100 nits ours gave 142 and 216.
it("puts mid grey and reference white where Apple's SDR conversion does", () => {
expect(Math.abs(toneMappedGrey(551) - 105)).toBeLessThanOrEqual(8);
expect(Math.abs(toneMappedGrey(745) - 161)).toBeLessThanOrEqual(8);
});
});
49 changes: 47 additions & 2 deletions packages/core/src/hdrToneMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@ export interface ToneMapSourceColour {
colorTransfer?: string;
}

export interface ToneMapFrameColour extends ToneMapSourceColour {
keyframeTransfers?: readonly string[];
}

const BT2408_HLG_REFERENCE_WHITE_NITS = 203;
const SDR_NOMINAL_PEAK_NITS = 100;

/** One zscale serves a stream: only an all-HLG one takes HLG's white, so a mixed one's PQ stays as is. */
export const toneMapReferenceNits = (keyframeTransfers: readonly string[] | undefined): number =>
keyframeTransfers?.length && keyframeTransfers.every((transfer) => transfer === "arib-std-b67")
? BT2408_HLG_REFERENCE_WHITE_NITS
: SDR_NOMINAL_PEAK_NITS;

export const readsKeyframeTransfers = ({ colorTransfer }: ToneMapSourceColour): boolean =>
colorTransfer === "arib-std-b67" || !known(colorTransfer);

function known(value: string | undefined): string | undefined {
return value && value !== "unknown" && value !== "reserved" ? value : undefined;
}
Expand All @@ -14,7 +30,7 @@ function known(value: string | undefined): string | undefined {
*/
export function hdrToSdrToneMapFilter(
probed: ToneMapSourceColour,
firstFrame: ToneMapSourceColour,
firstFrame: ToneMapFrameColour,
size?: { width: string; height: string },
): string {
const fill = (key: keyof ToneMapSourceColour, fallback?: string) =>
Expand All @@ -26,7 +42,13 @@ export function hdrToSdrToneMapFilter(
].filter(([, value]) => value);
const setTags = tags.length ? `setparams=${tags.map((tag) => tag.join("=")).join(":")},` : "";
const resizeBeforeToneMap = size ? `w=${size.width}:h=${size.height}:` : "";
return `${setTags}zscale=${resizeBeforeToneMap}t=linear:npl=100,tonemap=hable:desat=0,zscale=p=bt709:t=bt709:m=bt709:r=tv`;
const stream = known(firstFrame.colorTransfer) ?? known(probed.colorTransfer);
const npl = toneMapReferenceNits(
firstFrame.keyframeTransfers?.map((transfer) =>
transfer === "unspecified" ? (stream ?? transfer) : transfer,
),
);
return `${setTags}zscale=${resizeBeforeToneMap}t=linear:npl=${npl},tonemap=hable:desat=0,zscale=p=bt709:t=bt709:m=bt709:r=tv`;
}

/** ffmpeg args printing the first shown frame's tags; ffprobe's packet-bounded reads miss edit-list pre-roll. */
Expand All @@ -37,6 +59,29 @@ export function firstFrameColourArgs(videoPath: string): string[] {
];
}

const SPS_UNIT_TYPES: Record<string, string> = { h264: "7", hevc: "33" };
const TRANSFER_NAMES: Record<string, string> = {
"1": "bt709",
"2": "unspecified",
"16": "smpte2084",
"18": "arib-std-b67",
};

/** ffmpeg args tracing the transfer of each SPS, in the header and in keyframes, without decoding a picture. */
export function keyframeTransferArgs(videoPath: string, codec?: string): string[] {
const sps = codec ? SPS_UNIT_TYPES[codec] : undefined;
const trace = sps ? `filter_units=pass_types=${sps},trace_headers` : "trace_headers";
return [
...["-hide_banner", "-nostats", "-discard", "nokey", "-i", videoPath, "-map", "0:v:0"],
...["-c", "copy", "-bsf:v", trace, "-f", "null", "-"],
];
}

export const parseKeyframeTransfers = (stderr: string): string[] =>
[...stderr.matchAll(/transfer_characteristics +[01]+ = (\d+)/g)].map(
([, code = ""]) => TRANSFER_NAMES[code] ?? `code ${code}`,
);

export function parseFirstFrameColour(stderr: string): ToneMapSourceColour {
const tags = / color_space:(\S+) color_primaries:(\S+) color_trc:(\S+)/.exec(stderr);
return tags ? { colorSpace: tags[1], colorPrimaries: tags[2], colorTransfer: tags[3] } : {};
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,12 @@ export { bakeHfColorGradingCube, type BakeHfColorGradingCubeOptions } from "./co
export {
firstFrameColourArgs,
hdrToSdrToneMapFilter,
keyframeTransferArgs,
parseKeyframeTransfers,
readsKeyframeTransfers,
toneMapReferenceNits,
parseFirstFrameColour,
type ToneMapFrameColour,
type ToneMapSourceColour,
} from "./hdrToneMap";
export {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ describe.skipIf(process.platform === "win32")("extractAllVideoFrames ffmpeg conc
delete process.env.HF_TEST_SHIM_DIR;
}
const alive = readFileSync(join(run, "alive"), "utf8").trim().split(/\s+/).map(Number);
expect(alive).toHaveLength(8 + 2);
expect(alive).toHaveLength(8 + 2 * 2);
expect(Math.max(...alive)).toBe(1);
},
60_000,
Expand Down
Loading
Loading