mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(producer): pass the render's cancel to probes of a source read at its URL (#8312)
* test(producer): a cancel stops a media source probed in place at its URL * fix(producer): pass the render's cancel to probes of a source read at its URL * test(engine): a cancelled metadata probe rejects with ffprobe's own error * test(engine): a cancel stops frame extraction while it probes a source at its URL * fix(producer): pass the render's cancel to every render-time probe of a source * fix(engine): a cancelled metadata probe rejects with the cancel's reason * test(engine): probe a local path in the metadata cancel test, so no TLS check runs first
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { createServer, type Server, type ServerResponse } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, beforeAll, expect, it, vi } from "vitest";
|
||||
import { getFfmpegBinary } from "../utils/ffmpegBinaries.js";
|
||||
import { extractAllVideoFrames } from "./videoFrameExtractor.js";
|
||||
|
||||
const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"], { encoding: "utf-8" }).status === 0;
|
||||
|
||||
let dir: string;
|
||||
let server: Server;
|
||||
let url = "";
|
||||
const held: ServerResponse[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "hf-probe-cancel-"));
|
||||
// A source that never answers: each request is held open, unanswered.
|
||||
server = createServer((_req, res) => void held.push(res));
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/clip.mp4`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const res of held.splice(0)) res.destroy();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// fails without the fix: the source's metadata probe took no signal, so a cancel waited out ffprobe's deadline.
|
||||
it.skipIf(!HAS_FFMPEG)(
|
||||
"a cancel during the probe of a source read at its URL stops frame extraction",
|
||||
async () => {
|
||||
const cancel = new AbortController();
|
||||
const video = { id: "v", src: "clip.mp4", start: 0, end: 1, mediaStart: 0, loop: false };
|
||||
const extraction = extractAllVideoFrames(
|
||||
[{ ...video, hasAudio: false }],
|
||||
dir,
|
||||
{
|
||||
fps: 30,
|
||||
outputDir: join(dir, "frames"),
|
||||
urlByAbsentLocalPath: new Map([[join(dir, "clip.mp4"), url]]),
|
||||
},
|
||||
cancel.signal,
|
||||
);
|
||||
extraction.catch(() => {});
|
||||
await vi.waitFor(() => expect(held.length).toBeGreaterThan(0), { timeout: 5_000 });
|
||||
cancel.abort(new Error("render cancelled"));
|
||||
|
||||
await expect(extraction).rejects.toThrow();
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
@@ -1417,7 +1417,7 @@ async function extractVideoFramesRangeUnredacted(
|
||||
|
||||
let metadata: VideoMetadata;
|
||||
try {
|
||||
metadata = await extractMediaMetadata(videoPath);
|
||||
metadata = await extractMediaMetadata(videoPath, { signal });
|
||||
} catch (error) {
|
||||
throw classifyVideoExtractionError(error);
|
||||
}
|
||||
@@ -2460,8 +2460,8 @@ export async function extractAllVideoFrames(
|
||||
const attempted =
|
||||
!options.collectProbeFailures &&
|
||||
boundedTransientRetryBudget(options.maxTransientRetries) === 0
|
||||
? { result: await extractMediaMetadata(videoPath), retries: 0 }
|
||||
: await runVideoExtractionWithRetry(() => extractMediaMetadata(videoPath), {
|
||||
? { result: await extractMediaMetadata(videoPath, { signal }), retries: 0 }
|
||||
: await runVideoExtractionWithRetry(() => extractMediaMetadata(videoPath, { signal }), {
|
||||
signal,
|
||||
maxTransientRetries: options.maxTransientRetries,
|
||||
onRetry: () => recordTransientRetries(1),
|
||||
@@ -2965,7 +2965,8 @@ export async function extractAllVideoFrames(
|
||||
throw new Error("Video frame extraction cancelled");
|
||||
}
|
||||
try {
|
||||
const metadata = videoMetadata[index] ?? (await extractMediaMetadata(videoPath));
|
||||
const metadata =
|
||||
videoMetadata[index] ?? (await extractMediaMetadata(videoPath, { signal }));
|
||||
alignClipStartToFirstOutputFrame(video, fps);
|
||||
const initialWindow = resolveVideoExtractionWindow(video, metadata, options.timelineEnd);
|
||||
const window = await resolveFinalFrameExtractionWindow(
|
||||
|
||||
@@ -1183,6 +1183,33 @@ describe("ffprobe missing-binary fallback", () => {
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
// fails without the fix: extractMediaMetadata took no signal, so its probe ran to the end after a cancel.
|
||||
it("extractMediaMetadata stops on a cancel raised while it probes", async () => {
|
||||
const controller = new AbortController();
|
||||
const { spawn: baseSpawn, calls } = createSpawnSpy([
|
||||
{
|
||||
kind: "exit",
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
streams: [{ codec_type: "video", codec_name: "h264", width: 16, height: 16 }],
|
||||
format: { duration: "1" },
|
||||
}),
|
||||
},
|
||||
]);
|
||||
const spawn = (command: string, args: readonly string[]) => {
|
||||
controller.abort(new Error("render cancelled"));
|
||||
return baseSpawn(command, args);
|
||||
};
|
||||
vi.resetModules();
|
||||
vi.doMock("child_process", () => ({ spawn }));
|
||||
|
||||
const { extractMediaMetadata } = await import("./ffprobe.js");
|
||||
await expect(
|
||||
extractMediaMetadata("/tmp/aborted.video", { signal: controller.signal }),
|
||||
).rejects.toThrow("render cancelled");
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("extractMediaMetadata falls back to PNG cICP metadata when ffprobe is missing", async () => {
|
||||
const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]);
|
||||
hidePathBinaries();
|
||||
|
||||
@@ -201,6 +201,10 @@ const finalVideoFrameTimestampSignalCaches = new WeakMap<
|
||||
AbortSignal,
|
||||
Map<string, MediaProbeCacheEntry<number>>
|
||||
>();
|
||||
const videoMetadataSignalCaches = new WeakMap<
|
||||
AbortSignal,
|
||||
Map<string, MediaProbeCacheEntry<VideoMetadata>>
|
||||
>();
|
||||
const audioMetadataCache = new Map<string, MediaProbeCacheEntry<AudioMetadata>>();
|
||||
const audioMetadataSignalCaches = new WeakMap<
|
||||
AbortSignal,
|
||||
@@ -533,7 +537,7 @@ export async function buildProbeFactsText(filePath: string, signal?: AbortSignal
|
||||
ffprobeMajor: await ffprobeMajor(),
|
||||
};
|
||||
try {
|
||||
const metadata = await extractMediaMetadata(filePath);
|
||||
const metadata = await extractMediaMetadata(filePath, { signal });
|
||||
const window = resolveStreamWindow(filePath, {
|
||||
videoStreamStartSeconds: metadata.videoStreamStartSeconds,
|
||||
videoStreamDurationSeconds:
|
||||
@@ -929,6 +933,7 @@ export { parseSampleAspectRatio };
|
||||
export async function probeDecodedAlphaPlane(
|
||||
filePath: string,
|
||||
decoder: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<boolean | undefined> {
|
||||
let probeDir: string | undefined;
|
||||
try {
|
||||
@@ -953,7 +958,7 @@ export async function probeDecodedAlphaPlane(
|
||||
"nut",
|
||||
framePath,
|
||||
],
|
||||
{ timeout: 30_000 },
|
||||
{ timeout: 30_000, signal },
|
||||
);
|
||||
if (!decoded.success) return undefined;
|
||||
const stdout = await runFfprobe(framePath, [
|
||||
@@ -980,9 +985,20 @@ export async function probeDecodedAlphaPlane(
|
||||
* deprecated alias below), this also handles still images such as PNG so it
|
||||
* can be used uniformly for any visual asset the HDR pipeline encounters.
|
||||
*/
|
||||
export async function extractMediaMetadata(filePath: string): Promise<VideoMetadata> {
|
||||
export async function extractMediaMetadata(
|
||||
filePath: string,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<VideoMetadata> {
|
||||
const signal = options?.signal;
|
||||
signal?.throwIfAborted();
|
||||
const identity = mediaFileIdentity(filePath);
|
||||
const cached = readMetadataCache(videoMetadataCache, filePath, identity);
|
||||
// As for audio: a probe bound to a caller's signal is shared only among callers of that signal.
|
||||
let cache = videoMetadataCache;
|
||||
if (signal) {
|
||||
cache = videoMetadataSignalCaches.get(signal) ?? new Map();
|
||||
videoMetadataSignalCaches.set(signal, cache);
|
||||
}
|
||||
const cached = readMetadataCache(cache, filePath, identity);
|
||||
if (cached) return cached;
|
||||
|
||||
const probePromise = (async (): Promise<VideoMetadata> => {
|
||||
@@ -1001,8 +1017,10 @@ export async function extractMediaMetadata(filePath: string): Promise<VideoMetad
|
||||
|
||||
let output: FFProbeOutput | null = null;
|
||||
try {
|
||||
output = await probeMediaOutput(filePath);
|
||||
output = await probeMediaOutput(filePath, signal);
|
||||
} catch (error) {
|
||||
// As probeMediaProfile does: a cancel rejects with its own reason, so callers read it as a cancel.
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
if (!stillImage()) throw error;
|
||||
}
|
||||
|
||||
@@ -1060,15 +1078,17 @@ export async function extractMediaMetadata(filePath: string): Promise<VideoMetad
|
||||
const hasAlpha = videoStreamHasAlpha(videoStream);
|
||||
const alphaDecoder = hasAlpha ? null : alphaDecoderFor(videoStream.codec_name);
|
||||
const alphaPlaneDecoded = alphaDecoder
|
||||
? await probeDecodedAlphaPlane(filePath, alphaDecoder)
|
||||
? await probeDecodedAlphaPlane(filePath, alphaDecoder, signal)
|
||||
: undefined;
|
||||
|
||||
let containerDuration = output?.format.duration ? parseFloat(output.format.duration) : 0;
|
||||
const streamDuration = videoStream.duration ? parseFloat(videoStream.duration) : 0;
|
||||
// Recorder output (WebM/Matroska written to a pipe) carries no duration header: read it off the packets.
|
||||
if (!(containerDuration > 0) && !(streamDuration > 0) && !isPng) {
|
||||
containerDuration = (await scanPacketDuration(filePath, fps)) ?? 0;
|
||||
containerDuration = (await scanPacketDuration(filePath, fps, signal)) ?? 0;
|
||||
}
|
||||
// The alpha and packet probes answer undefined on any failure, a cancel included.
|
||||
signal?.throwIfAborted();
|
||||
const parsedStreamStart = videoStream.start_time ? parseFloat(videoStream.start_time) : 0;
|
||||
const streamStart = Number.isFinite(parsedStreamStart) ? parsedStreamStart : 0;
|
||||
// `nb_frames` is populated by the container demuxer; a muxer that requires
|
||||
@@ -1121,7 +1141,7 @@ export async function extractMediaMetadata(filePath: string): Promise<VideoMetad
|
||||
};
|
||||
})();
|
||||
|
||||
writeMetadataCache(videoMetadataCache, filePath, identity, probePromise);
|
||||
if (!signal || identity !== null) writeMetadataCache(cache, filePath, identity, probePromise);
|
||||
return probePromise;
|
||||
}
|
||||
|
||||
@@ -1165,7 +1185,11 @@ export function readStoredFinalFrame(
|
||||
const PACKET_TAIL_CHARS = 64 * 1024;
|
||||
|
||||
/** The video stream's length from its packets (last end time), for a file whose headers state none. */
|
||||
async function scanPacketDuration(filePath: string, fps: number): Promise<number | undefined> {
|
||||
async function scanPacketDuration(
|
||||
filePath: string,
|
||||
fps: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<number | undefined> {
|
||||
try {
|
||||
const stdout = await runFfprobe(
|
||||
filePath,
|
||||
@@ -1173,7 +1197,7 @@ async function scanPacketDuration(filePath: string, fps: number): Promise<number
|
||||
...["-select_streams", "v:0", "-show_entries", "packet=pts_time,duration_time"],
|
||||
...["-of", "csv=p=0"],
|
||||
],
|
||||
undefined,
|
||||
signal,
|
||||
{ retainTail: true, maxChars: PACKET_TAIL_CHARS },
|
||||
);
|
||||
const lines = stdout.split("\n");
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { compileForRender } from "./htmlCompiler.js";
|
||||
|
||||
type Probe = "probeMediaProfile" | "extractMediaMetadata" | "extractAudioMetadata";
|
||||
const probes = vi.hoisted(() => ({
|
||||
hang: "probeMediaProfile" as string,
|
||||
calls: [] as { name: string; signal?: AbortSignal }[],
|
||||
}));
|
||||
const answer = (name: string, signal: AbortSignal | undefined, value: unknown) => {
|
||||
probes.calls.push({ name, signal });
|
||||
if (name !== probes.hang) return Promise.resolve(value);
|
||||
// A source that never answers: only an abort settles the probe.
|
||||
return new Promise((_resolve, reject) => {
|
||||
signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
|
||||
});
|
||||
};
|
||||
vi.mock("@hyperframes/engine", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hyperframes/engine")>()),
|
||||
assertMediaPayload: async () => {},
|
||||
probeMediaProfile: (_path: string, options?: { signal?: AbortSignal }) =>
|
||||
answer("probeMediaProfile", options?.signal, {
|
||||
hasVideoStream: true,
|
||||
hasAudioStream: true,
|
||||
visualKind: "moving",
|
||||
}),
|
||||
extractMediaMetadata: (_path: string, options?: { signal?: AbortSignal }) =>
|
||||
answer("extractMediaMetadata", options?.signal, { durationSeconds: 1 }),
|
||||
extractAudioMetadata: (_path: string, options?: { signal?: AbortSignal }) =>
|
||||
answer("extractAudioMetadata", options?.signal, { durationSeconds: 1 }),
|
||||
}));
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterEach(() => {
|
||||
probes.calls.length = 0;
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const cases: [Probe, string][] = [
|
||||
["probeMediaProfile", "video"],
|
||||
["extractMediaMetadata", "video"],
|
||||
["extractAudioMetadata", "audio"],
|
||||
];
|
||||
|
||||
// fails without the fix: a source probed in place at its URL was probed with no signal, so a cancel waited on it.
|
||||
it.each(cases)(
|
||||
"a cancel during %s of a %s probed in place stops the compile",
|
||||
async (probe, tag) => {
|
||||
probes.hang = probe;
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-probe-cancel-"));
|
||||
dirs.push(dir);
|
||||
writeFileSync(
|
||||
join(dir, "index.html"),
|
||||
`<!doctype html><html><head></head><body><main data-composition-id="root" data-start="0" data-duration="1" data-width="16" data-height="16"><${tag} muted src="clip.mp4" data-start="0" data-track-index="0"></${tag}></main></body></html>`,
|
||||
);
|
||||
const cancel = new AbortController();
|
||||
const compile = compileForRender(dir, join(dir, "index.html"), join(dir, "out"), {
|
||||
allowSystemFontCapture: false,
|
||||
abortSignal: cancel.signal,
|
||||
urlByAbsentLocalPath: new Map([
|
||||
[join(dir, "clip.mp4"), "https://media.example.com/clip.mp4"],
|
||||
]),
|
||||
});
|
||||
compile.catch(() => {});
|
||||
await vi.waitFor(() => expect(probes.calls.some((call) => call.name === probe)).toBe(true));
|
||||
expect(probes.calls.every((call) => call.signal === cancel.signal)).toBe(true);
|
||||
cancel.abort(new Error("render cancelled"));
|
||||
|
||||
await expect(compile).rejects.toThrow("render cancelled");
|
||||
},
|
||||
);
|
||||
@@ -773,13 +773,17 @@ async function resolveMediaDuration(
|
||||
// a typed NotMediaPayloadError instead of letting ffprobe emit an opaque
|
||||
// `[mov,mp4,...] moov atom not found` that routes as a codec bug.
|
||||
await assertMediaPayload(filePath, elementIdentity);
|
||||
const profile = await probeMediaProfile(filePath);
|
||||
const signal = run?.assets.signal;
|
||||
const profile = await probeMediaProfile(filePath, { signal });
|
||||
if (tagName === "video") {
|
||||
return { profile, fileDuration: (await extractMediaMetadata(filePath)).durationSeconds };
|
||||
const { durationSeconds } = await extractMediaMetadata(filePath, { signal });
|
||||
return { profile, fileDuration: durationSeconds };
|
||||
}
|
||||
try {
|
||||
return { profile, fileDuration: (await extractAudioMetadata(filePath)).durationSeconds };
|
||||
const { durationSeconds } = await extractAudioMetadata(filePath, { signal });
|
||||
return { profile, fileDuration: durationSeconds };
|
||||
} catch {
|
||||
if (signal?.aborted) throw signal.reason;
|
||||
// Source file has no audio stream (e.g. a silent video used as an audio src).
|
||||
// Duration 0 excludes the element from the composition, as missing files do.
|
||||
return { profile, fileDuration: null };
|
||||
|
||||
@@ -481,14 +481,20 @@ export async function runExtractVideosStage(
|
||||
// default zero budget this remains the exact legacy single probe.
|
||||
const attempted =
|
||||
extractionPolicy.maxTransientRetries === 0
|
||||
? { result: await extractMediaMetadata(videoPath), retries: 0 }
|
||||
: await runVideoExtractionWithRetry(() => extractMediaMetadata(videoPath), {
|
||||
signal: abortSignal,
|
||||
maxTransientRetries: extractionPolicy.maxTransientRetries,
|
||||
onRetry: () => {
|
||||
hdrProbeTransientRetries += 1;
|
||||
? {
|
||||
result: await extractMediaMetadata(videoPath, { signal: abortSignal }),
|
||||
retries: 0,
|
||||
}
|
||||
: await runVideoExtractionWithRetry(
|
||||
() => extractMediaMetadata(videoPath, { signal: abortSignal }),
|
||||
{
|
||||
signal: abortSignal,
|
||||
maxTransientRetries: extractionPolicy.maxTransientRetries,
|
||||
onRetry: () => {
|
||||
hdrProbeTransientRetries += 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
const meta = attempted.result;
|
||||
if (isHdrColorSpace(meta.colorSpace)) {
|
||||
nativeHdrVideoIds.add(v.id);
|
||||
@@ -736,7 +742,7 @@ export async function appendVideoAudioFromProbe(input: VideoAudioProbeInput): Pr
|
||||
? await remoteProbeSource(video, input)
|
||||
: localProbeSource(video.src, input);
|
||||
if (readFrom === null) return null;
|
||||
const metadata = await extractMediaMetadata(readFrom);
|
||||
const metadata = await extractMediaMetadata(readFrom, { signal: input.signal });
|
||||
const window = await resolveFinalFrameExtractionWindow(
|
||||
readFrom,
|
||||
video,
|
||||
|
||||
Reference in New Issue
Block a user