diff --git a/packages/engine/src/services/videoFrameExtractor.seekIndex.test.ts b/packages/engine/src/services/videoFrameExtractor.seekIndex.test.ts index 88452f6724..9ab78c7dd4 100644 --- a/packages/engine/src/services/videoFrameExtractor.seekIndex.test.ts +++ b/packages/engine/src/services/videoFrameExtractor.seekIndex.test.ts @@ -1,11 +1,34 @@ -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { spawnSync } from "node:child_process"; import { runFfmpeg } from "../utils/runFfmpeg.js"; import { extractVideoFramesRange, type ExtractedFrames } from "./videoFrameExtractor.js"; +const rebuildCopies = vi.hoisted(() => [] as number[]); +const failingCopy = vi.hoisted(() => ({ throws: false, dirs: [] as string[] })); + +// Pass-through that records how many bytes each seek-index copy wrote before it is removed. +vi.mock("../utils/runFfmpeg.js", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + runFfmpeg: async (...call: Parameters) => { + const output = call[0].at(-1) ?? ""; + if (failingCopy.throws && output.endsWith("source.mov")) { + failingCopy.dirs.push(dirname(output)); + throw new Error("ffmpeg could not start"); + } + const result = await real.runFfmpeg(...call); + if (output.endsWith("source.mov")) { + rebuildCopies.push(existsSync(output) ? statSync(output).size : 0); + } + return result; + }, + }; +}); + const HAS_FFMPEG = spawnSync("ffmpeg", ["-version"]).status === 0; const WIDTH = 32; const HEIGHT = 16; @@ -29,6 +52,36 @@ function dropFirstSyncSample(source: string, target: string): void { writeFileSync(target, bytes); } +/** Box offset of `type` in an MP4 whose boxes up to it are each found once. */ +function boxAt(bytes: Buffer, type: string): number { + const at = bytes.indexOf(type); + if (at < 4) throw new Error(`fixture has no ${type} box`); + return at - 4; +} + +/** + * Repeats the first edit-list entry so the demuxer plays the same samples `repeats` times. The + * file stays a few kilobytes while a stream copy of it writes every repeat. Needs `moov` after + * `mdat`, so growing it moves no chunk offsets. + */ +function repeatEditList(source: string, target: string, repeats: number): void { + const bytes = readFileSync(source); + const elst = boxAt(bytes, "elst"); + if (bytes[elst + 8] !== 0 || bytes.readUInt32BE(elst + 12) !== 1) { + throw new Error("fixture needs a single version-0 edit-list entry"); + } + if (boxAt(bytes, "moov") < boxAt(bytes, "mdat")) throw new Error("fixture needs moov last"); + const entry = bytes.subarray(elst + 16, elst + 28); + const extra = Buffer.concat(Array.from({ length: repeats - 1 }, () => entry)); + const grown = Buffer.concat([bytes.subarray(0, elst + 28), extra, bytes.subarray(elst + 28)]); + grown.writeUInt32BE(repeats, elst + 12); + for (const type of ["elst", "edts", "trak", "moov"]) { + const at = boxAt(grown, type); + grown.writeUInt32BE(grown.readUInt32BE(at) + extra.length, at); + } + writeFileSync(target, grown); +} + describe.skipIf(!HAS_FFMPEG)("an MP4 whose sync-sample index leaves out the first keyframe", () => { const fixtureDir = mkdtempSync(join(tmpdir(), "hf-seek-index-fixture-")); const indexed = join(fixtureDir, "indexed.mp4"); @@ -64,6 +117,11 @@ describe.skipIf(!HAS_FFMPEG)("an MP4 whose sync-sample index leaves out the firs rmSync(fixtureDir, { recursive: true, force: true }); }); + beforeEach(() => { + rebuildCopies.length = 0; + failingCopy.throws = false; + }); + /** Every frame the extraction wrote, decoded to gray pixels, in frame order. */ function decodedFrames(extracted: ExtractedFrames): Buffer[] { return [...extracted.framePaths.entries()] @@ -110,4 +168,48 @@ describe.skipIf(!HAS_FFMPEG)("an MP4 whose sync-sample index leaves out the firs expect([...extracted.framePaths.keys()].sort((a, b) => a - b)).toEqual([3, 4, 5, 6]); expect(decodedFrames(extracted)).toEqual(decodedFrames(reference)); }, 30_000); + + it("never copies a playlist that names the clip many times", async () => { + // ffmpeg prints the input's name, so this name alone matches the seek-failure message. + const playlist = join(fixtureDir, "could not seek to position 0.ffconcat"); + writeFileSync( + playlist, + `ffconcat version 1.0\n${"file indexed.mp4\nduration 4\n".repeat(200)}`, + ); + const extracted = await extractVideoFramesRange(playlist, "broll", 0.5, 1, { + fps: 10, + format: "png", + outputDir: mkdtempSync(join(fixtureDir, "playlist-")), + }); + expect(rebuildCopies).toEqual([]); + expect(extracted.totalFrames).toBe(10); + }, 30_000); + + it("stops a copy that outgrows its source at a ceiling and extracts without it", async () => { + const looped = join(fixtureDir, "looped.mp4"); + repeatEditList(source, looped, 3000); + const ceiling = 2 * statSync(looped).size + 1024 * 1024; + const extracted = await extractVideoFramesRange(looped, "broll", 0.5, 1, { + fps: 10, + format: "png", + outputDir: mkdtempSync(join(fixtureDir, "looped-")), + }); + expect(rebuildCopies).toHaveLength(1); + // ffmpeg stops past the limit and still writes the sample index, so the copy ends above it. + expect(rebuildCopies[0]).toBeGreaterThanOrEqual(ceiling); + expect(rebuildCopies[0]).toBeLessThan(2 * ceiling); + expect(extracted.totalFrames).toBe(10); + }, 60_000); + + it("removes the copy's folder when the copy throws", async () => { + failingCopy.throws = true; + const extraction = extractVideoFramesRange(source, "broll", 0.5, 1, { + fps: 10, + format: "png", + outputDir: mkdtempSync(join(fixtureDir, "throws-")), + }); + await expect(extraction).rejects.toThrow("ffmpeg could not start"); + expect(failingCopy.dirs).toHaveLength(1); + expect(existsSync(failingCopy.dirs[0]!)).toBe(false); + }, 30_000); }); diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.ts index ec2ea4f3cd..947113d83a 100644 --- a/packages/engine/src/services/videoFrameExtractor.ts +++ b/packages/engine/src/services/videoFrameExtractor.ts @@ -8,7 +8,7 @@ import { usableCpuCount } from "./systemMemory.js"; import { audioGroupsById, isMemberGroupHidden, isSelfOrAncestorHidden } from "./mediaHidden.js"; -import { copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, rmSync } from "fs"; +import { copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, rmSync, statSync } from "fs"; import { basename, isAbsolute, join, normalize, relative, win32 } from "path"; import { tmpdir } from "os"; import { createConcurrencyLimit } from "../utils/concurrencyLimit.js"; @@ -1342,23 +1342,56 @@ export async function buildVideoLayerInput( // VLC-muxed MP4s can leave the first IDR out of `stss`; ffmpeg then cannot input-seek before the next one. const SEEK_INDEX_MISSING = /Cannot find an index entry before timestamp|could not seek to position/; +/** The probed size of a source the mov/mp4 demuxer reads; undefined for a playlist, a list or any other format. */ +async function movSourceBytes( + videoPath: string, + signal?: AbortSignal, +): Promise { + try { + const probed = JSON.parse( + await runFfprobe( + videoPath, + ["-show_entries", "format=format_name,size", "-of", "json"], + signal, + ), + ) as { format?: { format_name?: string; size?: string } }; + const bytes = Number(probed.format?.size); + return probed.format?.format_name === "mov,mp4,m4a,3gp,3g2,mj2" && bytes > 0 + ? bytes + : undefined; + } catch { + return undefined; + } +} + +/** A mov/mp4 copy past this replays data, so it fails. `-fs` caps the media; the index written after grows in step. */ +const seekIndexCopyLimit = (sourceBytes: number) => 2 * sourceBytes + 1024 * 1024; + async function streamCopyWithRebuiltSeekIndex( videoPath: string, signal: AbortSignal | undefined, timeout: number, ): Promise<{ dir: string; path: string } | undefined> { + const sourceBytes = await movSourceBytes(videoPath, signal); + if (sourceBytes === undefined) return undefined; + const limit = seekIndexCopyLimit(sourceBytes); const dir = mkdtempSync(join(tmpdir(), "hf-seek-index-")); const path = join(dir, "source.mov"); - const result = await runFfmpeg( - [ - ...urlInputArgs(videoPath), - ...["-i", videoPath, "-map", "0:v:0", "-map", "0:a?", "-c", "copy", "-y", path], - ], - { signal, timeout }, - ); - if (result.success && existsSync(path)) return { dir, path }; - rmSync(dir, { recursive: true, force: true }); - return undefined; + let kept = false; + try { + const result = await runFfmpeg( + [ + ...urlInputArgs(videoPath), + ...["-f", "mov", "-i", videoPath, "-map", "0:v:0", "-map", "0:a?", "-c", "copy"], + ...["-fs", String(limit), "-y", path], + ], + { signal, timeout }, + ); + kept = result.success && existsSync(path) && statSync(path).size < limit; + return kept ? { dir, path } : undefined; + } finally { + if (!kept) rmSync(dir, { recursive: true, force: true }); + } } async function extractVideoFramesRangeUnredacted( @@ -1556,7 +1589,10 @@ async function extractVideoFramesRangeUnredacted( !seekIndexRebuilt && SEEK_INDEX_MISSING.test(processResult.stderr) ) { - const rebuilt = await streamCopyWithRebuiltSeekIndex(videoPath, signal, ffmpegProcessTimeout); + const rebuilt = await inExtractionSlot( + () => streamCopyWithRebuiltSeekIndex(videoPath, signal, ffmpegProcessTimeout), + signal, + ); if (rebuilt) { for (const stale of framePathsFromDirectory(videoOutputDir, format, true).values()) rmSync(stale, { force: true });