diff --git a/packages/engine/src/services/videoFrameExtractor.probeCancel.test.ts b/packages/engine/src/services/videoFrameExtractor.probeCancel.test.ts new file mode 100644 index 0000000000..7f489dacd3 --- /dev/null +++ b/packages/engine/src/services/videoFrameExtractor.probeCancel.test.ts @@ -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((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, +); diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.ts index 947113d83a..e832d22d2c 100644 --- a/packages/engine/src/services/videoFrameExtractor.ts +++ b/packages/engine/src/services/videoFrameExtractor.ts @@ -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( diff --git a/packages/engine/src/utils/ffprobe.test.ts b/packages/engine/src/utils/ffprobe.test.ts index 8defc883c0..2ebf442172 100644 --- a/packages/engine/src/utils/ffprobe.test.ts +++ b/packages/engine/src/utils/ffprobe.test.ts @@ -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(); diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.ts index 3f5c9ab109..6c80df9585 100644 --- a/packages/engine/src/utils/ffprobe.ts +++ b/packages/engine/src/utils/ffprobe.ts @@ -201,6 +201,10 @@ const finalVideoFrameTimestampSignalCaches = new WeakMap< AbortSignal, Map> >(); +const videoMetadataSignalCaches = new WeakMap< + AbortSignal, + Map> +>(); const audioMetadataCache = new Map>(); 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 { 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 { +export async function extractMediaMetadata( + filePath: string, + options?: { signal?: AbortSignal }, +): Promise { + 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 => { @@ -1001,8 +1017,10 @@ export async function extractMediaMetadata(filePath: string): Promise 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 { +async function scanPacketDuration( + filePath: string, + fps: number, + signal?: AbortSignal, +): Promise { try { const stdout = await runFfprobe( filePath, @@ -1173,7 +1197,7 @@ async function scanPacketDuration(filePath: string, fps: number): Promise ({ + 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()), + 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"), + `
<${tag} muted src="clip.mp4" data-start="0" data-track-index="0">
`, + ); + 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"); + }, +); diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index c30e0fce9a..c90a1d93e2 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -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 }; diff --git a/packages/producer/src/services/render/stages/extractVideosStage.ts b/packages/producer/src/services/render/stages/extractVideosStage.ts index fd2e0a16f1..7715c700be 100644 --- a/packages/producer/src/services/render/stages/extractVideosStage.ts +++ b/packages/producer/src/services/render/stages/extractVideosStage.ts @@ -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,