fix(studio): a paused untagged video shows the colours the export renders (#8405)

* test(studio): a paused untagged video is drawn as the export reads it

* fix(studio): a paused untagged video shows the colours the export renders, not BT.709
This commit is contained in:
Miguel Ángel
2026-11-21 23:06:44 +00:00
committed by GitHub
parent 4a5a5eb27e
commit 71907274a7
5 changed files with 107 additions and 8 deletions
@@ -18,6 +18,7 @@ import { isPathInside } from "@hyperframes/parsers/asset-paths";
import { resolveProjectRelativeSrc } from "@hyperframes/parsers/asset-resolution";
import { assetRootsRefusal } from "../utils/assetRoots.js";
import { alphaDecoderFor } from "@hyperframes/parsers/media-alpha";
import { untaggedVideoMatrix } from "@hyperframes/parsers/media-streams";
import {
MEDIA_RENDER_ID_ATTR,
isAudibleVideoElement,
@@ -1032,14 +1033,10 @@ function readFirstFrameColour(videoPath: string, codec: string) {
return probe;
}
/** Chrome plays untagged VP9 and AV1 as BT.601, H.264 and VP8 as BT.709 from 720 coded 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"}`];
return [`setparams=colorspace=${untaggedVideoMatrix(metadata.videoCodec, metadata.height)}`];
}
export function sdrCanvasColourFilters(metadata: VideoMetadata, toneMappedToSdr = false): string[] {
+12 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { decodableAudioStream } from "./mediaStreams";
import { decodableAudioStream, untaggedVideoMatrix } from "./mediaStreams";
describe("decodableAudioStream", () => {
it("skips an audio track ffprobe names no codec for, counting only audio streams", () => {
@@ -21,3 +21,14 @@ describe("decodableAudioStream", () => {
expect(decodableAudioStream([{ codec_type: "audio" }])).toBeNull();
});
});
describe("untaggedVideoMatrix", () => {
it("reads an untagged video's colours as Chrome does: BT.601 below 720 lines and for VP9 and AV1", () => {
expect(untaggedVideoMatrix("avc", 360)).toBe("smpte170m");
expect(untaggedVideoMatrix("h264", 719)).toBe("smpte170m");
expect(untaggedVideoMatrix("avc", 720)).toBe("bt709");
expect(untaggedVideoMatrix("hevc", 1080)).toBe("bt709");
expect(untaggedVideoMatrix("vp9", 1080)).toBe("smpte170m");
expect(untaggedVideoMatrix("av1", 2160)).toBe("smpte170m");
});
});
+6
View File
@@ -28,3 +28,9 @@ export function decodableAudioStream(streams: readonly FfprobeStreamCodec[]): nu
.findIndex((stream) => stream.codec_name !== undefined);
return index < 0 ? null : index;
}
const BT601_UNTAGGED_CODECS = new Set(["vp9", "av1"]);
export function untaggedVideoMatrix(codec: string, codedHeight: number): "bt709" | "smpte170m" {
return codedHeight >= 720 && !BT601_UNTAGGED_CODECS.has(codec) ? "bt709" : "smpte170m";
}
@@ -3,6 +3,10 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { createPausedVideoDecoder } from "./pausedVideoDecoder";
const inputs: { source: string; dispose: ReturnType<typeof vi.fn> }[] = [];
const rebuilt: {
init: { colorSpace?: { matrix?: string } };
drawWithFit: ReturnType<typeof vi.fn>;
}[] = [];
const getTrack = vi.fn();
const getSample = vi.fn();
const cancelReads = vi.fn();
@@ -28,6 +32,16 @@ vi.mock("mediabunny", () => ({
return getTrack(this.options.source.url);
}
},
VideoSample: class {
close = vi.fn();
drawWithFit = vi.fn();
constructor(
readonly data: ArrayBuffer,
readonly init: { colorSpace?: { matrix?: string } },
) {
rebuilt.push(this);
}
},
VideoSampleSink: class {
constructor(readonly track: { source: string }) {}
getSample(time: number) {
@@ -78,6 +92,15 @@ const signal = () => new AbortController().signal;
const sample = (timestamp = 0) => ({
timestamp,
duration: 1 / 30,
format: "I420",
codedWidth: 100,
codedHeight: 100,
visibleRect: { left: 0, top: 0, width: 100, height: 100 },
rotation: 0,
flip: false,
colorSpace: { primaries: "bt709", transfer: "bt709", matrix: "bt709", fullRange: false },
allocationSize: () => 8,
copyTo: vi.fn(async () => []),
close: vi.fn(),
drawWithFit: vi.fn(),
});
@@ -97,10 +120,14 @@ const track = (source: string) => ({
getRotation: async () => 0,
getFlip: async () => false,
canBeTransparent: async () => false,
getCodec: async () => "avc",
getCodedHeight: async () => 100,
getColorSpace: async (): Promise<{ matrix?: string }> => ({ matrix: "bt709" }),
});
beforeEach(() => {
inputs.length = 0;
rebuilt.length = 0;
getTrack.mockReset().mockImplementation(async (source: string) => track(source));
getSample.mockReset().mockImplementation(async () => sample());
iterateSamples.mockReset();
@@ -715,3 +742,29 @@ it("closes the selected alpha sample when suspension cancels an in-flight read",
expect(selected.close).toHaveBeenCalledOnce();
expect(inputs[0]!.dispose).toHaveBeenCalledOnce();
});
it("draws an untagged video the way the export reads it, not as the BT.709 mediabunny assumes", async () => {
const frames = async (height: number, matrix?: string) => {
getTrack.mockImplementationOnce(async (source: string) => ({
...track(source),
getCodedHeight: async () => height,
getColorSpace: async () => (matrix ? { matrix } : {}),
}));
const decoded = sample();
getSample.mockImplementationOnce(async () => decoded);
const owner = provider();
(await owner.decode([request(`clip-${height}-${matrix ?? "none"}`)], signal()))[0]?.release();
return decoded;
};
const small = await frames(360);
expect(rebuilt.map((made) => made.init.colorSpace?.matrix)).toEqual(["smpte170m"]);
expect(rebuilt[0]!.drawWithFit).toHaveBeenCalledOnce();
expect(small.drawWithFit).not.toHaveBeenCalled();
expect(small.close).toHaveBeenCalled();
rebuilt.length = 0;
const hd = await frames(720);
const tagged = await frames(360, "bt709");
expect(rebuilt).toEqual([]);
expect(hd.drawWithFit).toHaveBeenCalledOnce();
expect(tagged.drawWithFit).toHaveBeenCalledOnce();
});
@@ -2,15 +2,16 @@ import {
ALL_FORMATS,
Input,
UrlSource,
VideoSample,
VideoSampleSink,
type Rotation,
type VideoSample,
} from "mediabunny";
import type {
PausedVideoFrame,
PausedVideoFrameProvider,
PausedVideoFrameRequest,
} from "@hyperframes/core";
import { untaggedVideoMatrix } from "@hyperframes/parsers/media-streams";
import { mediaUrlSourceOptions } from "./mediaFetch";
import type { IframeWindow } from "./playbackTypes";
import {
@@ -44,6 +45,7 @@ type Reader = {
lead: number;
ticks: number;
transparent: boolean;
untaggedBt601: boolean;
tail: Promise<void>;
iterator: AsyncGenerator<VideoSample, void, unknown> | null;
iteratorEnd: number;
@@ -69,6 +71,24 @@ async function readSingleSample(reader: Reader, query: number): Promise<VideoSam
}
}
async function asBt601(sample: VideoSample): Promise<VideoSample> {
if (!sample.format) return sample;
const data = new ArrayBuffer(sample.allocationSize());
const layout = await sample.copyTo(data);
const { primaries, transfer, fullRange } = sample.colorSpace;
return new VideoSample(data, {
format: sample.format,
codedWidth: sample.visibleRect.width,
codedHeight: sample.visibleRect.height,
timestamp: sample.timestamp,
duration: sample.duration,
rotation: sample.rotation,
flip: sample.flip,
layout,
colorSpace: { primaries, transfer, fullRange, matrix: "smpte170m" },
});
}
export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideoFrameProvider {
const readers = new Map<string, Promise<Reader>>();
const opened = new Map<string, Reader>();
@@ -162,6 +182,11 @@ export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideo
track.getFlip(),
track.canBeTransparent(),
]);
const [codec, codedHeight, colour] = await Promise.all([
track.getCodec(),
track.getCodedHeight(),
track.getColorSpace(),
]);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.ceil(width));
const aspect = rotation % 180 === 0 ? squareWidth / squareHeight : squareHeight / squareWidth;
@@ -179,6 +204,8 @@ export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideo
lead,
ticks,
transparent,
untaggedBt601:
!colour.matrix && untaggedVideoMatrix(codec ?? "", codedHeight) === "smpte170m",
tail: Promise.resolve(),
iterator: null,
iteratorEnd: 0,
@@ -280,7 +307,12 @@ export function createPausedVideoDecoder(iframe: HTMLIFrameElement): PausedVideo
if (!context) throw new Error("Preview canvas unavailable");
context.clearRect(0, 0, reader.canvas.width, reader.canvas.height);
context.imageSmoothingQuality = "high";
sample.drawWithFit(context, { fit: "fill", rotation: reader.rotation, flip: reader.flip });
const drawn = reader.untaggedBt601 ? await asBt601(sample) : sample;
try {
drawn.drawWithFit(context, { fit: "fill", rotation: reader.rotation, flip: reader.flip });
} finally {
if (drawn !== sample) drawn.close();
}
const image = await createImageBitmap(reader.canvas);
if (signal.aborted || disposed || reader.disposed) {
image.close();