Skip to content

Commit 9ca1e17

Browse files
feat(studio-server): probe media codec facts for proxy decisions (#2587)
* feat(studio-server): probe media codec facts for proxy decisions Adds the codec manifest: one ffprobe-backed answer to what codec an asset uses, whether a browser can decode it, and whether it carries alpha. Migrates the existing prober to the shared ff-binaries resolver and to async execFile so a scan pool runs off the event loop. No consumer yet; the preview weld wires it up later in the stack. * fix(studio-server): honor injected ffprobe runners
1 parent d7b38da commit 9ca1e17

7 files changed

Lines changed: 757 additions & 29 deletions

File tree

Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
2+
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3+
import { join } from "node:path";
4+
import { tmpdir } from "node:os";
5+
import type { FfprobeRunner } from "./mediaMetadata.js";
6+
import {
7+
BROWSER_HOSTILE_CODECS,
8+
decideMediaProxyEligibility,
9+
createMediaCodecProbeCache,
10+
probeAssetCodec,
11+
scanProjectMediaCodecMap,
12+
} from "./mediaCodecMap.js";
13+
14+
// Any real, existing file works as a stand-in ffprobe path — the runner
15+
// passed to probeMediaMetadata is what's actually invoked, mirroring
16+
// packages/lint/src/project.test.ts's hevc_preview_codec pattern (keeps this
17+
// test independent of whether the host actually has ffprobe installed).
18+
const FAKE_FFPROBE_PATH = process.execPath;
19+
20+
function makeRunner(
21+
codecByPath: Record<string, string | { codecName: string; pixFmt?: string }>,
22+
): FfprobeRunner {
23+
return (_command, args) => {
24+
const filePath = args[args.length - 1] ?? "";
25+
const entry = codecByPath[filePath];
26+
const normalized = typeof entry === "string" ? { codecName: entry } : entry;
27+
const streams = normalized
28+
? [
29+
{
30+
codec_type: "video",
31+
codec_name: normalized.codecName,
32+
pix_fmt: normalized.pixFmt,
33+
},
34+
]
35+
: [];
36+
return { status: 0, stdout: JSON.stringify({ streams }), stderr: "" };
37+
};
38+
}
39+
40+
function countingRunner(runner: FfprobeRunner): {
41+
runner: FfprobeRunner;
42+
calls: () => number;
43+
} {
44+
let calls = 0;
45+
return {
46+
runner: (command, args, options) => {
47+
calls++;
48+
return runner(command, args, options);
49+
},
50+
calls: () => calls,
51+
};
52+
}
53+
54+
function videoHtml(...srcs: string[]): string {
55+
const tags = srcs
56+
.map(
57+
(src, i) =>
58+
`<video id="v${i}" class="clip" src="${src}" muted data-start="0" data-duration="5"></video>`,
59+
)
60+
.join("\n");
61+
return `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="10">${tags}</div></body></html>`;
62+
}
63+
64+
let dirs: string[] = [];
65+
66+
function tmpProject(): string {
67+
const dir = mkdtempSync(join(tmpdir(), "hf-media-codec-map-test-"));
68+
dirs.push(dir);
69+
return dir;
70+
}
71+
72+
beforeEach(() => {
73+
process.env.HYPERFRAMES_FFPROBE_PATH = FAKE_FFPROBE_PATH;
74+
});
75+
76+
afterEach(() => {
77+
delete process.env.HYPERFRAMES_FFPROBE_PATH;
78+
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
79+
dirs = [];
80+
});
81+
82+
describe("probeAssetCodec", () => {
83+
it("reports an HEVC asset as browser-hostile with the pinned representative mime", async () => {
84+
const project = tmpProject();
85+
const videoPath = join(project, "clip.mp4");
86+
writeFileSync(videoPath, "fake video bytes");
87+
88+
const facts = await probeAssetCodec(videoPath, makeRunner({ [videoPath]: "hevc" }));
89+
90+
expect(facts).toEqual({
91+
codecName: "hevc",
92+
browserHostile: true,
93+
representativeMime: BROWSER_HOSTILE_CODECS.hevc,
94+
hasAlpha: false,
95+
});
96+
});
97+
98+
it("reports an H.264 asset as not browser-hostile", async () => {
99+
const project = tmpProject();
100+
const videoPath = join(project, "clip.mp4");
101+
writeFileSync(videoPath, "fake video bytes");
102+
103+
const facts = await probeAssetCodec(videoPath, makeRunner({ [videoPath]: "h264" }));
104+
105+
expect(facts).toEqual({
106+
codecName: "h264",
107+
browserHostile: false,
108+
representativeMime: null,
109+
hasAlpha: false,
110+
});
111+
});
112+
113+
it("treats VP9 as conditionally hostile so unsupported browsers can request a proxy", async () => {
114+
const project = tmpProject();
115+
const videoPath = join(project, "clip.webm");
116+
writeFileSync(videoPath, "fake video bytes");
117+
118+
const facts = await probeAssetCodec(videoPath, makeRunner({ [videoPath]: "vp9" }));
119+
120+
expect(facts).toEqual({
121+
codecName: "vp9",
122+
browserHostile: true,
123+
representativeMime: BROWSER_HOSTILE_CODECS.vp9,
124+
hasAlpha: false,
125+
});
126+
});
127+
128+
it("reports ProRes as browser-hostile with no representative mime", async () => {
129+
const project = tmpProject();
130+
const videoPath = join(project, "clip.mov");
131+
writeFileSync(videoPath, "fake video bytes");
132+
133+
const facts = await probeAssetCodec(videoPath, makeRunner({ [videoPath]: "prores" }));
134+
135+
expect(facts).toEqual({
136+
codecName: "prores",
137+
browserHostile: true,
138+
representativeMime: null,
139+
hasAlpha: false,
140+
});
141+
});
142+
143+
it("flags an alpha-bearing pix_fmt (ProRes 4444) with hasAlpha", async () => {
144+
const project = tmpProject();
145+
const videoPath = join(project, "clip.mov");
146+
writeFileSync(videoPath, "fake video bytes");
147+
148+
const facts = await probeAssetCodec(
149+
videoPath,
150+
makeRunner({
151+
[videoPath]: { codecName: "prores", pixFmt: "yuva444p10le" },
152+
}),
153+
);
154+
155+
expect(facts).toEqual({
156+
codecName: "prores",
157+
browserHostile: true,
158+
representativeMime: null,
159+
hasAlpha: true,
160+
});
161+
});
162+
163+
it("returns null (never throws) when ffprobe is unresolvable", async () => {
164+
const project = tmpProject();
165+
const videoPath = join(project, "clip.mp4");
166+
writeFileSync(videoPath, "fake video bytes");
167+
process.env.HYPERFRAMES_FFPROBE_PATH = join(project, "missing-ffprobe");
168+
169+
await expect(probeAssetCodec(videoPath)).resolves.toBeNull();
170+
});
171+
});
172+
173+
describe("decideMediaProxyEligibility", () => {
174+
it("allows only hostile opaque video through the H.264 proxy path", () => {
175+
expect(
176+
decideMediaProxyEligibility({
177+
codecName: "hevc",
178+
browserHostile: true,
179+
representativeMime: null,
180+
hasAlpha: false,
181+
}),
182+
).toEqual({ eligible: true });
183+
});
184+
185+
it("rejects alpha and browser-safe sources before transcoding", () => {
186+
expect(
187+
decideMediaProxyEligibility({
188+
codecName: "prores",
189+
browserHostile: true,
190+
representativeMime: null,
191+
hasAlpha: true,
192+
}),
193+
).toEqual({ eligible: false, reason: "alpha_source" });
194+
expect(
195+
decideMediaProxyEligibility({
196+
codecName: "h264",
197+
browserHostile: false,
198+
representativeMime: null,
199+
hasAlpha: false,
200+
}),
201+
).toEqual({ eligible: false, reason: "browser_safe_codec" });
202+
expect(decideMediaProxyEligibility(null)).toEqual({
203+
eligible: false,
204+
reason: "unknown_codec",
205+
});
206+
});
207+
});
208+
209+
describe("scanProjectMediaCodecMap", () => {
210+
it("omits an asset from the map (no throw) when ffprobe is unresolvable", async () => {
211+
const project = tmpProject();
212+
writeFileSync(join(project, "clip.mp4"), "fake video bytes");
213+
process.env.HYPERFRAMES_FFPROBE_PATH = join(project, "missing-ffprobe");
214+
215+
const map = await scanProjectMediaCodecMap(project, [{ html: videoHtml("clip.mp4") }]);
216+
217+
expect(map).toEqual({});
218+
});
219+
220+
it("keys the map by project-root-relative URL pathnames: decoded, forward-slash, leading-slash", async () => {
221+
const project = tmpProject();
222+
mkdirSync(join(project, "assets", "sub"), { recursive: true });
223+
writeFileSync(join(project, "assets", "sub", "clip.mp4"), "fake video bytes");
224+
writeFileSync(join(project, "assets", "my clip.mp4"), "fake video bytes");
225+
226+
const html = videoHtml("assets/sub/clip.mp4", "assets/my%20clip.mp4");
227+
const map = await scanProjectMediaCodecMap(project, [{ html }], {
228+
runner: makeRunner({
229+
[join(project, "assets", "sub", "clip.mp4")]: "hevc",
230+
[join(project, "assets", "my clip.mp4")]: "h264",
231+
}),
232+
});
233+
234+
expect(Object.keys(map)).toEqual(["/assets/sub/clip.mp4"]);
235+
expect(map["/assets/sub/clip.mp4"]?.browserHostile).toBe(true);
236+
expect(map["/assets/my clip.mp4"]).toBeUndefined();
237+
});
238+
239+
it("rewrites a sub-composition's ../-traversing src via compSrcPath before resolving (rewriteAssetPath)", async () => {
240+
const project = tmpProject();
241+
mkdirSync(join(project, "assets"), { recursive: true });
242+
mkdirSync(join(project, "compositions"), { recursive: true });
243+
writeFileSync(join(project, "assets", "clip.mp4"), "fake video bytes");
244+
245+
const map = await scanProjectMediaCodecMap(
246+
project,
247+
[
248+
{
249+
html: videoHtml("../assets/clip.mp4"),
250+
compSrcPath: "compositions/scene.html",
251+
},
252+
],
253+
{ runner: makeRunner({ [join(project, "assets", "clip.mp4")]: "hevc" }) },
254+
);
255+
256+
// The key is root-relative (what the served DOM resolves to), not the
257+
// sub-composition-relative authored src.
258+
expect(Object.keys(map)).toEqual(["/assets/clip.mp4"]);
259+
expect(map["/assets/clip.mp4"]?.browserHostile).toBe(true);
260+
});
261+
262+
it("caches by path + mtime + size, invalidating same-mtime re-exports and touched files", async () => {
263+
const project = tmpProject();
264+
const videoPath = join(project, "clip.mp4");
265+
writeFileSync(videoPath, "fake video bytes");
266+
const pinnedMtime = new Date(Date.now() - 60_000);
267+
utimesSync(videoPath, pinnedMtime, pinnedMtime);
268+
const html = videoHtml("clip.mp4");
269+
const cache = createMediaCodecProbeCache();
270+
const probe = countingRunner(makeRunner({ [videoPath]: "hevc" }));
271+
272+
const first = await scanProjectMediaCodecMap(project, [{ html }], {
273+
cache,
274+
runner: probe.runner,
275+
});
276+
expect(first["/clip.mp4"]?.codecName).toBe("hevc");
277+
expect(probe.calls()).toBe(1);
278+
279+
const second = await scanProjectMediaCodecMap(project, [{ html }], {
280+
cache,
281+
runner: probe.runner,
282+
});
283+
expect(second["/clip.mp4"]?.codecName).toBe("hevc");
284+
expect(probe.calls()).toBe(1);
285+
286+
writeFileSync(videoPath, "larger fake video bytes");
287+
utimesSync(videoPath, pinnedMtime, pinnedMtime);
288+
const resized = await scanProjectMediaCodecMap(project, [{ html }], {
289+
cache,
290+
runner: probe.runner,
291+
});
292+
expect(resized["/clip.mp4"]?.codecName).toBe("hevc");
293+
expect(probe.calls()).toBe(2);
294+
295+
const future = new Date(Date.now() + 60_000);
296+
utimesSync(videoPath, future, future);
297+
298+
const third = await scanProjectMediaCodecMap(project, [{ html }], {
299+
cache,
300+
runner: probe.runner,
301+
});
302+
expect(third["/clip.mp4"]?.codecName).toBe("hevc");
303+
expect(probe.calls()).toBe(3);
304+
});
305+
306+
it("bounds the long-lived probe cache while retaining the newest assets", async () => {
307+
const project = tmpProject();
308+
const cache = createMediaCodecProbeCache();
309+
const paths = Array.from({ length: 513 }, (_, index) => `clip-${index}.mp4`);
310+
const codecByPath: Record<string, string> = {};
311+
for (const path of paths) {
312+
const absolutePath = join(project, path);
313+
writeFileSync(absolutePath, "fake video bytes");
314+
codecByPath[absolutePath] = "hevc";
315+
}
316+
317+
await scanProjectMediaCodecMap(project, [{ html: videoHtml(...paths) }], {
318+
cache,
319+
runner: makeRunner(codecByPath),
320+
});
321+
322+
expect(cache.size).toBe(512);
323+
expect(paths.slice(0, 8).some((path) => !cache.has(join(project, path)))).toBe(true);
324+
expect(cache.has(join(project, "clip-512.mp4"))).toBe(true);
325+
});
326+
});

0 commit comments

Comments
 (0)