mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(cli): read every media path a command is given as that one file (#8650)
* fix(cli): read every media path a command is given as that one file * test(cli): the hanging ffmpeg stand-in answers the demuxer listing
This commit is contained in:
@@ -329,7 +329,11 @@ describe("transcribe", () => {
|
||||
vi.spyOn(manager, "ensureModel").mockResolvedValue(join(dir, "ggml-small.en.bin"));
|
||||
const ffmpeg = join(dir, "ffmpeg");
|
||||
const pidFile = join(dir, "ffmpeg.pid");
|
||||
hangingTool(ffmpeg, pidFile, 'for out; do :; done\nprintf partial > "$out"\n');
|
||||
hangingTool(
|
||||
ffmpeg,
|
||||
pidFile,
|
||||
'case "$*" in *-demuxers*) exit 0;; esac\nfor out; do :; done\nprintf partial > "$out"\n',
|
||||
);
|
||||
vi.stubEnv("HYPERFRAMES_FFMPEG_PATH", ffmpeg);
|
||||
vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", join(dir, "no-ffprobe"));
|
||||
const input = join(dir, "narration.mp3");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
|
||||
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { assertLiteralMediaInput } from "@hyperframes/parsers/literal-media-input";
|
||||
import {
|
||||
decodableAudioStream,
|
||||
misstatesPcmByteRate,
|
||||
@@ -24,13 +25,20 @@ function requiredBinary(name: "ffmpeg" | "ffprobe"): string {
|
||||
return path;
|
||||
}
|
||||
|
||||
function literalInputArgs(binary: string, file: string, inputArgs: readonly string[]) {
|
||||
if (inputArgs.length === 0) return mediaInputFormatArgs(binary, file);
|
||||
assertLiteralMediaInput(file);
|
||||
return inputArgs;
|
||||
}
|
||||
|
||||
/** The format of the audio track ffmpeg can decode, or `null` when the file has none. */
|
||||
export async function probeAudio(
|
||||
file: string,
|
||||
inputArgs: readonly string[] = [],
|
||||
): Promise<AudioStreamInfo | null> {
|
||||
const ffprobe = requiredBinary("ffprobe");
|
||||
const { stdout } = await run(
|
||||
requiredBinary("ffprobe"),
|
||||
ffprobe,
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
@@ -40,7 +48,7 @@ export async function probeAudio(
|
||||
"-show_format",
|
||||
"-of",
|
||||
"json",
|
||||
...inputArgs,
|
||||
...literalInputArgs(ffprobe, file, inputArgs),
|
||||
"--",
|
||||
file,
|
||||
],
|
||||
@@ -96,12 +104,14 @@ export async function decodeAudio(
|
||||
const seek = window.from ? ["-ss", String(window.from)] : [];
|
||||
const [inputSeek, decodedSeek] = probedInfo.misstatedByteRate ? [[], seek] : [seek, []];
|
||||
const length = window.seconds === undefined ? [] : ["-t", String(window.seconds)];
|
||||
const ffmpeg = requiredBinary("ffmpeg");
|
||||
const { stdout } = await run(
|
||||
requiredBinary("ffmpeg"),
|
||||
ffmpeg,
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
...inputSeek,
|
||||
...mediaInputFormatArgs(ffmpeg, file),
|
||||
"-i",
|
||||
file,
|
||||
...decodedSeek,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { Span } from "@hyperframes/core/audio-analysis";
|
||||
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
|
||||
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
|
||||
import { readPlainFile } from "../../utils/projectRecords.js";
|
||||
import { isPlainFile, makeRealFolder } from "../cacheFolder.js";
|
||||
@@ -99,7 +99,10 @@ async function mp3Of(path: string, scratch: string): Promise<Buffer> {
|
||||
const out = join(scratch, `${createHash("sha256").update(path).digest("hex").slice(0, 12)}.mp3`);
|
||||
await runFile(
|
||||
ffmpeg,
|
||||
["-v", "error", "-y", "-i", path, "-vn", "-ac", "2", "-ar", "44100", "-b:a", "160k", out],
|
||||
[
|
||||
...["-v", "error", "-y", ...mediaInputFormatArgs(ffmpeg, path), "-i", path],
|
||||
...["-vn", "-ac", "2", "-ar", "44100", "-b:a", "160k", out],
|
||||
],
|
||||
{ windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
|
||||
);
|
||||
return readFileSync(out);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { statSync } from "node:fs";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
|
||||
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
import { downloadToFile } from "../../cloud/download.js";
|
||||
@@ -112,7 +112,8 @@ async function encoded(path: string, dir: string, signal: AbortSignal): Promise<
|
||||
await runFile(
|
||||
ffmpeg,
|
||||
[
|
||||
...["-v", "error", "-y", "-i", path, "-map", `0:a:${audio.audioStream}`],
|
||||
...["-v", "error", "-y", ...mediaInputFormatArgs(ffmpeg, path), "-i", path],
|
||||
...["-map", `0:a:${audio.audioStream}`],
|
||||
...["-vn", "-ac", "2", "-ar", "44100", "-b:a", "192k", out],
|
||||
],
|
||||
{ windowsHide: true, maxBuffer: 8 * 1024 * 1024, signal },
|
||||
|
||||
@@ -17,6 +17,7 @@ import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { renameSync, rmSync } from "node:fs";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
|
||||
import { runCancellableProcess } from "../utils/cancellableProcess.js";
|
||||
import { readFrames } from "./frameReader.js";
|
||||
@@ -131,6 +132,7 @@ async function decoderTransposesDimensions(inputPath: string): Promise<boolean>
|
||||
"-show_streams",
|
||||
"-print_format",
|
||||
"json",
|
||||
...mediaInputFormatArgs(ffprobePath, inputPath),
|
||||
"--",
|
||||
inputPath,
|
||||
],
|
||||
@@ -435,7 +437,10 @@ async function runPipeline(
|
||||
|
||||
const decoder = spawnFfmpeg(
|
||||
ffmpegPath,
|
||||
["-loglevel", "error", "-i", inputPath, "-f", "rawvideo", "-pix_fmt", "rgb24", "-an", "-"],
|
||||
[
|
||||
...["-loglevel", "error", ...mediaInputFormatArgs(ffmpegPath, inputPath), "-i", inputPath],
|
||||
...["-f", "rawvideo", "-pix_fmt", "rgb24", "-an", "-"],
|
||||
],
|
||||
"ffmpeg decoder",
|
||||
["ignore", "pipe", "pipe"],
|
||||
);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
|
||||
import { defineCommand } from "../utils/defineCommand.js";
|
||||
import type { Example } from "./_examples.js";
|
||||
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { openSettledCompositionPage, runFfmpegOnce } from "../capture/captureCompositionFrame.js";
|
||||
import { findFFmpeg } from "../browser/ffmpeg.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
@@ -500,6 +501,7 @@ async function extractVideoFrameToBuffer(videoPath: string): Promise<Buffer | nu
|
||||
"error",
|
||||
"-ss",
|
||||
"0",
|
||||
...mediaInputFormatArgs(ffmpegPath, videoPath),
|
||||
"-i",
|
||||
videoPath,
|
||||
"-frames:v",
|
||||
|
||||
@@ -994,7 +994,8 @@ describe("transcodeToMp4", () => {
|
||||
const ffmpeg = join(dir, "ffmpeg");
|
||||
const output = join(dir, "out.mp4");
|
||||
// Blocking writes, like ffmpeg's own log: 1 MB stalls on a pipe nobody reads.
|
||||
const script = `const fs = require("node:fs");
|
||||
const script = `if (process.argv.includes("-demuxers")) process.exit(0);
|
||||
const fs = require("node:fs");
|
||||
const line = Buffer.alloc(1024, "x");
|
||||
for (let i = 0; i < 1024; i++) fs.writeSync(2, line);
|
||||
fs.writeFileSync(process.argv.at(-1), "");`;
|
||||
|
||||
@@ -50,6 +50,7 @@ import { trackInitTemplate } from "../telemetry/events.js";
|
||||
import { DEFAULT_MODEL, hasFFmpeg } from "../whisper/manager.js";
|
||||
import { TRANSCRIPT_FILE } from "../whisper/transcriptFile.js";
|
||||
import { initialModelForLanguage } from "../whisper/transcribe.js";
|
||||
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import {
|
||||
@@ -130,7 +131,17 @@ function probeVideo(filePath: string): VideoMeta | undefined {
|
||||
if (!ffprobePath) return undefined;
|
||||
const raw = execFileSync(
|
||||
ffprobePath,
|
||||
["-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", "--", filePath],
|
||||
[
|
||||
"-v",
|
||||
"quiet",
|
||||
...mediaInputFormatArgs(ffprobePath, filePath),
|
||||
"-print_format",
|
||||
"json",
|
||||
"-show_format",
|
||||
"-show_streams",
|
||||
"--",
|
||||
filePath,
|
||||
],
|
||||
{ encoding: "utf-8", timeout: 15_000 },
|
||||
);
|
||||
|
||||
@@ -232,6 +243,7 @@ export function transcodeToMp4(inputPath: string, outputPath: string): Promise<b
|
||||
const child = spawn(
|
||||
ffmpegPath,
|
||||
[
|
||||
...mediaInputFormatArgs(ffmpegPath, inputPath),
|
||||
"-i",
|
||||
inputPath,
|
||||
"-c:v",
|
||||
|
||||
@@ -10,6 +10,7 @@ import { defineCommand } from "../../utils/defineCommand.js";
|
||||
import type { Example } from "../_examples.js";
|
||||
import { jsonArg, num, roiArg, runMeasure, videoAndRoi, videoArg } from "../../measure/command.js";
|
||||
import {
|
||||
ffmpegInput,
|
||||
Fix,
|
||||
frameAt,
|
||||
projectOf,
|
||||
@@ -116,7 +117,7 @@ export function cutClip(
|
||||
// seek time, which at some rates is the one before k0.
|
||||
encodeOnto(out, (staged) =>
|
||||
runFfmpeg([
|
||||
...["-y", "-i", info.path],
|
||||
...["-y", ...ffmpegInput(info.path)],
|
||||
...[
|
||||
"-vf",
|
||||
`trim=start_frame=${k0}:end_frame=${k1},setpts=PTS-STARTPTS,${crop(roi)},format=yuv420p`,
|
||||
@@ -168,8 +169,7 @@ export function cutSound(info: VideoInfo, from: number, to: number, out: string)
|
||||
"-y",
|
||||
"-ss",
|
||||
String(a),
|
||||
"-i",
|
||||
info.path,
|
||||
...ffmpegInput(info.path),
|
||||
"-t",
|
||||
String(b - a),
|
||||
"-vn",
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Example } from "../_examples.js";
|
||||
import { jsonArg, runMeasure, videoArg } from "../../measure/command.js";
|
||||
import {
|
||||
ffmpegBin,
|
||||
ffmpegInput,
|
||||
Fix,
|
||||
probeVideo,
|
||||
round,
|
||||
@@ -60,7 +61,7 @@ function normalize(info: VideoInfo, out: string): { path: string; fps: string }
|
||||
}
|
||||
makeOutputFolder(dirname(out));
|
||||
runFfmpeg([
|
||||
...["-y", "-i", info.path, "-vf", [...filters, "format=yuv420p"].join(",")],
|
||||
...["-y", ...ffmpegInput(info.path), "-vf", [...filters, "format=yuv420p"].join(",")],
|
||||
...["-c:v", "libx264", "-crf", "12", "-preset", "medium", "-c:a", "aac", "-b:a", "192k", out],
|
||||
]);
|
||||
return { path: out, fps };
|
||||
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
import { findCuts, signatures } from "../measure/cuts.js";
|
||||
import {
|
||||
Fix,
|
||||
ffmpegInput,
|
||||
ffmpegToFile,
|
||||
probeVideo,
|
||||
projectOf,
|
||||
@@ -417,7 +418,7 @@ async function shrunk(paths: string[], work: string): Promise<Map<string, string
|
||||
needFile(path);
|
||||
const to = join(work, `picture-${out.size}.jpg`);
|
||||
const viaFfmpeg = () =>
|
||||
runFfmpeg(["-y", "-i", path, "-vf", FIT_2048, "-q:v", "3", "-frames:v", "1", to]);
|
||||
runFfmpeg(["-y", ...ffmpegInput(path), "-vf", FIT_2048, "-q:v", "3", "-frames:v", "1", to]);
|
||||
if (!sharp) viaFfmpeg();
|
||||
else
|
||||
await sharp(path)
|
||||
@@ -443,13 +444,16 @@ function inline(work: string, pictures: Map<string, string>, masks: Mask[] = [])
|
||||
`in-${Math.random().toString(36).slice(2)}.${{ audio: "mp3", video: "mp4" }[kind]}`,
|
||||
);
|
||||
if (kind === "audio")
|
||||
runFfmpeg(["-y", "-i", path, "-vn", "-ac", "1", "-c:a", "libmp3lame", "-b:a", "128k", out]);
|
||||
runFfmpeg([
|
||||
...["-y", ...ffmpegInput(path), "-vn", "-ac", "1"],
|
||||
...["-c:a", "libmp3lame", "-b:a", "128k", out],
|
||||
]);
|
||||
// A guide clip only needs its motion: 720 px on the long side, no sound, at most 15 s.
|
||||
else if (kind === "video") {
|
||||
const guide = masks.length ? fillMasks(path, masks, work) : path;
|
||||
const guide = masks.length ? ["-i", fillMasks(path, masks, work)] : ffmpegInput(path);
|
||||
const scale = "scale='if(gt(iw,ih),min(720,iw),-2)':'if(gt(iw,ih),-2,min(720,ih))'";
|
||||
runFfmpeg([
|
||||
...["-y", "-i", guide, "-t", "15", "-an", "-vf", scale],
|
||||
...["-y", ...guide, "-t", "15", "-an", "-vf", scale],
|
||||
...["-c:v", "libx264", "-crf", "28", "-preset", "veryfast", "-pix_fmt", "yuv420p", out],
|
||||
]);
|
||||
}
|
||||
@@ -525,7 +529,7 @@ function structured(clip: string, guide: { width: number; height: number }, mask
|
||||
/** The masks whose surroundings change, where the camera moves: a median over time would freeze old frames in them. */
|
||||
function staleMasks(path: string, { width, height }: Size, masks: Mask[]): Mask[] {
|
||||
const gray = runFfmpeg([
|
||||
...["-t", String(GUIDE_MAX_S), "-i", path],
|
||||
...["-t", String(GUIDE_MAX_S), ...ffmpegInput(path)],
|
||||
...["-vf", "fps=2", "-pix_fmt", "gray", "-f", "rawvideo", "-"],
|
||||
]);
|
||||
const frame = (i: number) => gray.subarray(i * width * height, (i + 1) * width * height);
|
||||
@@ -542,22 +546,22 @@ function staleMasks(path: string, { width, height }: Size, masks: Mask[]): Mask[
|
||||
function fillMasks(path: string, masks: Mask[], work: string): string {
|
||||
const info = probeVideo(path);
|
||||
const stale = staleMasks(path, info, masks);
|
||||
const encode = (from: string, name: string, filter: string[]) => {
|
||||
const encode = (input: string[], name: string, filter: string[]) => {
|
||||
const out = join(work, name);
|
||||
runFfmpeg([
|
||||
...["-y", "-i", from, "-an"],
|
||||
...["-y", ...input, "-an"],
|
||||
...filter,
|
||||
...["-crf", "14", "-pix_fmt", "yuv420p", out],
|
||||
]);
|
||||
return out;
|
||||
};
|
||||
const median = encode(path, "median.mp4", [
|
||||
const median = encode(ffmpegInput(path), "median.mp4", [
|
||||
...["-t", "15", "-filter_complex", maskFilters(masks, info.fps, stale)],
|
||||
...["-map", `[v${masks.length}]`],
|
||||
]);
|
||||
const left = structured(median, info, masks).map((s) => s.mask);
|
||||
if (!left.length) return median;
|
||||
return encode(median, "filled.mp4", [
|
||||
return encode(["-i", median], "filled.mp4", [
|
||||
...["-filter_complex", maskFilters(left, info.fps, left)],
|
||||
...["-map", `[v${left.length}]`],
|
||||
]);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { TranscriptionCreateRequest } from "../cloud/_gen/types.js";
|
||||
import { projectOf, runFfmpeg } from "../measure/media.js";
|
||||
import { ffmpegInput, projectOf, runFfmpeg } from "../measure/media.js";
|
||||
import { idempotencyKey, runJob, type JobRoute } from "./v3.js";
|
||||
|
||||
const ROUTE: JobRoute = {
|
||||
@@ -62,8 +62,7 @@ export async function transcribeWithHeygen(
|
||||
const mp3 = join(work, "audio.mp3");
|
||||
runFfmpeg([
|
||||
"-y",
|
||||
"-i",
|
||||
inputPath,
|
||||
...ffmpegInput(inputPath),
|
||||
"-vn",
|
||||
"-ac",
|
||||
"1",
|
||||
|
||||
@@ -30,6 +30,7 @@ import { hiddenCopy, layerVerdict, scoreLayerFrame, type LayerVerdict } from "./
|
||||
import { compareLook, look, sameLook, type LookComparison } from "./look.js";
|
||||
import {
|
||||
decode,
|
||||
ffmpegInput,
|
||||
ffmpegToFile,
|
||||
Fix,
|
||||
frameAt,
|
||||
@@ -1174,7 +1175,7 @@ function onsetCurve(path: string): number[] {
|
||||
// On the sound's own timestamps (first_pts=0 pads up to its first decoded sample), not the probe's start_time:
|
||||
// ffmpeg 5.1 drops an HE-AAC edit list's skip twice, keeps the rest timestamped right, and still probes 0.
|
||||
const raw = runFfmpeg([
|
||||
...["-i", path, "-vn", "-af", "aresample=async=1:first_pts=0"],
|
||||
...[...ffmpegInput(path), "-vn", "-af", "aresample=async=1:first_pts=0"],
|
||||
...["-t", "20", "-ac", "1", "-ar", "8000", "-f", "f32le", "-"],
|
||||
]);
|
||||
const samples = new Float32Array(raw.buffer, raw.byteOffset, Math.floor(raw.byteLength / 4));
|
||||
@@ -1222,7 +1223,14 @@ function sideBySide(
|
||||
const skip = (seconds: number) => (seconds > 0 ? ["-ss", String(seconds)] : []);
|
||||
return ffmpegToFile(
|
||||
[
|
||||
...["-y", ...skip(-offset), "-i", reference, ...skip(offset), "-i", yours, "-filter_complex"],
|
||||
...[
|
||||
"-y",
|
||||
...skip(-offset),
|
||||
...ffmpegInput(reference),
|
||||
...skip(offset),
|
||||
...ffmpegInput(yours),
|
||||
],
|
||||
"-filter_complex",
|
||||
`[0:v]setsar=1[a];[1:v]scale=${ref.width}:${ref.height},setsar=1[b];[a][b]hstack=inputs=2,pad=ceil(iw/2)*2:ceil(ih/2)*2[v]`,
|
||||
...["-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p"],
|
||||
...["-c:a", "aac", "-shortest"],
|
||||
|
||||
@@ -153,8 +153,8 @@ describe.skipIf(!media)("readSamples", () => {
|
||||
it("refuses text that a text-art demuxer would show as a picture", () => {
|
||||
const art = join(dir, "notes.ans");
|
||||
writeFileSync(art, "SECRET=abc\n");
|
||||
const info = probeVideo(art);
|
||||
expect(readSamples(info, [0], 80, 48)).toHaveLength(1);
|
||||
const info = { ...probeVideo(video), path: art };
|
||||
expect(() => readSamples(info, [0], 80, 48)).toThrow(/not on whitelist/);
|
||||
expect(() => readSamples({ ...info, guarded: true }, [0], 80, 48)).toThrow(/not on whitelist/);
|
||||
});
|
||||
|
||||
|
||||
@@ -56,8 +56,8 @@ export function minWindow(h: number, share: number): number {
|
||||
}
|
||||
|
||||
function decode(info: VideoInfo, args: string[]): Buffer {
|
||||
if (!info.guarded) return runFfmpeg(args);
|
||||
const formats = mediaInputFormatArgs(ffmpegBin(), info.path);
|
||||
if (!info.guarded) return runFfmpeg([...formats, ...args]);
|
||||
try {
|
||||
return runFfmpeg([...formats, ...args], undefined, undefined, GUARDED_RUN_MS);
|
||||
} catch (err) {
|
||||
|
||||
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { HTTPRequest, Page } from "puppeteer-core";
|
||||
import { trustedCacheRoot } from "@hyperframes/core/cache-dir";
|
||||
import { Fix, round, runFfmpeg, type VideoInfo } from "./media.js";
|
||||
import { ffmpegInput, Fix, round, runFfmpeg, type VideoInfo } from "./media.js";
|
||||
import { ensurePinnedFiles, type PinnedFile } from "./pinnedFiles.js";
|
||||
|
||||
const VERSION = "1.0.0";
|
||||
@@ -154,8 +154,7 @@ export function handFrames(
|
||||
"-y",
|
||||
"-ss",
|
||||
start.toFixed(3),
|
||||
"-i",
|
||||
info.path,
|
||||
...ffmpegInput(info.path),
|
||||
"-t",
|
||||
(end - start).toFixed(3),
|
||||
"-vf",
|
||||
|
||||
@@ -114,7 +114,7 @@ describe.skipIf(!ffmpeg)("a guarded probe", () => {
|
||||
});
|
||||
|
||||
it("refuses text that a text-art demuxer would show as a picture", () => {
|
||||
expect(probeVideo(art).codec).toBe("ansi");
|
||||
expect(() => probeVideo(art)).toThrow(Fix);
|
||||
expect(() => probeVideo(art, { guarded: true })).toThrow(Fix);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,6 +66,10 @@ export function runFfmpeg(args: string[], input?: Buffer, cwd?: string, timeout?
|
||||
});
|
||||
}
|
||||
|
||||
export function ffmpegInput(path: string): string[] {
|
||||
return [...mediaInputFormatArgs(ffmpegBin(), path), "-i", path];
|
||||
}
|
||||
|
||||
export function ffmpegToFile(args: string[], out: string, input?: Buffer): string {
|
||||
const work = createStagingDir(dirname(out), ".ffmpeg-");
|
||||
try {
|
||||
@@ -99,7 +103,7 @@ export interface VideoInfo {
|
||||
hdr: boolean;
|
||||
transfer?: string;
|
||||
codec: string;
|
||||
/** A file a composition names: each run reads it with render's demuxer list and stops after {@link GUARDED_RUN_MS}. */
|
||||
/** A file a composition names: each run stops after {@link GUARDED_RUN_MS}. */
|
||||
guarded?: boolean;
|
||||
}
|
||||
|
||||
@@ -128,9 +132,20 @@ const rate = (text: string | undefined): number => {
|
||||
/** A sound's length in seconds. */
|
||||
export function probeSeconds(path: string): number {
|
||||
if (!existsSync(path)) throw new Fix(`no file at ${path}`, "pass a sound from the project");
|
||||
const bin = ffprobeBin();
|
||||
const text = execFileSync(
|
||||
ffprobeBin(),
|
||||
["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", "--", path],
|
||||
bin,
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
...mediaInputFormatArgs(bin, path),
|
||||
"-show_entries",
|
||||
"format=duration",
|
||||
"-of",
|
||||
"csv=p=0",
|
||||
"--",
|
||||
path,
|
||||
],
|
||||
{ maxBuffer: MAX_BUFFER, windowsHide: true },
|
||||
).toString();
|
||||
return Number(text) || 0;
|
||||
@@ -201,23 +216,14 @@ function startsWithMp4Header(path: string): boolean {
|
||||
// fallow-ignore-next-line complexity
|
||||
export function probeVideo(path: string, { guarded = false } = {}): VideoInfo {
|
||||
if (!existsSync(path)) throw new Fix(`no file at ${path}`, missingFileFix(path));
|
||||
const bin = ffprobeBin();
|
||||
const formats = mediaInputFormatArgs(bin, path);
|
||||
let json: { streams?: ProbeStream[]; format?: { duration?: string } };
|
||||
try {
|
||||
const bin = ffprobeBin();
|
||||
json = JSON.parse(
|
||||
execFileSync(
|
||||
bin,
|
||||
[
|
||||
"-v",
|
||||
"error",
|
||||
...(guarded ? mediaInputFormatArgs(bin, path) : []),
|
||||
"-show_streams",
|
||||
"-show_format",
|
||||
"-of",
|
||||
"json",
|
||||
"--",
|
||||
path,
|
||||
],
|
||||
["-v", "error", ...formats, "-show_streams", "-show_format", "-of", "json", "--", path],
|
||||
{
|
||||
maxBuffer: MAX_BUFFER,
|
||||
windowsHide: true,
|
||||
@@ -312,8 +318,7 @@ export function videoClip(
|
||||
return {
|
||||
input: [
|
||||
...(start > 0 ? ["-ss", String(start)] : []),
|
||||
"-i",
|
||||
path,
|
||||
...ffmpegInput(path),
|
||||
...(seconds !== undefined ? ["-t", String(seconds)] : []),
|
||||
],
|
||||
filters: [],
|
||||
|
||||
@@ -7,7 +7,16 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { contrast } from "./drawn.js";
|
||||
import { faceBoxes } from "./face.js";
|
||||
import { pearson, probeVideo, round, runFfmpeg, sumOf, type Roi, type VideoInfo } from "./media.js";
|
||||
import {
|
||||
ffmpegInput,
|
||||
pearson,
|
||||
probeVideo,
|
||||
round,
|
||||
runFfmpeg,
|
||||
sumOf,
|
||||
type Roi,
|
||||
type VideoInfo,
|
||||
} from "./media.js";
|
||||
import { avSync, type SyncResult } from "./sync.js";
|
||||
|
||||
/** A shot's framing is clearly wrong when, by the shot's medians, the face centre sits over FRAMING_SHIFT face heights
|
||||
@@ -121,7 +130,10 @@ export function generatedClips(ledger: string): GeneratedClip[] {
|
||||
|
||||
/** Loudness every 10 ms of a file's sound. */
|
||||
function envelope(path: string): number[] {
|
||||
const raw = runFfmpeg([...["-i", path, "-vn", "-ac", "1", "-ar", "8000", "-f", "f32le", "-"]]);
|
||||
const raw = runFfmpeg([
|
||||
...ffmpegInput(path),
|
||||
...["-vn", "-ac", "1", "-ar", "8000", "-f", "f32le", "-"],
|
||||
]);
|
||||
const s = new Float32Array(
|
||||
raw.buffer.slice(raw.byteOffset, raw.byteOffset + (raw.byteLength & ~3)),
|
||||
);
|
||||
@@ -262,7 +274,7 @@ function boxAt(
|
||||
].join(",");
|
||||
runFfmpeg(
|
||||
[
|
||||
...["-i", info.path, "-an", "-vf", filters, "-fps_mode", "passthrough"],
|
||||
...[...ffmpegInput(info.path), "-an", "-vf", filters, "-fps_mode", "passthrough"],
|
||||
...["-f", "rawvideo", "out.rgb"],
|
||||
],
|
||||
undefined,
|
||||
@@ -330,7 +342,7 @@ export function carriedFrame(
|
||||
function stillBox(path: string, box: Roi, w: number, h: number): Uint8Array | undefined {
|
||||
try {
|
||||
const raw = runFfmpeg([
|
||||
...["-i", path, "-frames:v", "1", "-vf"],
|
||||
...[...ffmpegInput(path), "-frames:v", "1", "-vf"],
|
||||
`scale=${w}:${h}:force_original_aspect_ratio=increase:flags=bicubic,format=rgb24,crop=${w}:${h},crop=${box[2]}:${box[3]}:${box[0]}:${box[1]}`,
|
||||
...["-f", "rawvideo", "-"],
|
||||
]);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// region's mean luma change, per frame the change of the sound's loudness, and the lag where the two correlate best.
|
||||
// A motion and energy proxy, not phoneme sync: head motion, gestures, cuts and music in the ROI or mix move it.
|
||||
import {
|
||||
ffmpegInput,
|
||||
Fix,
|
||||
pearson,
|
||||
readClip,
|
||||
@@ -17,7 +18,7 @@ const RATE = 16000;
|
||||
/** Mono samples of the window at RATE Hz. */
|
||||
function samples(info: VideoInfo, start: number, seconds: number): Float32Array {
|
||||
const raw = runFfmpeg([
|
||||
...["-ss", String(start), "-i", info.path, "-t", String(seconds), "-vn"],
|
||||
...["-ss", String(start), ...ffmpegInput(info.path), "-t", String(seconds), "-vn"],
|
||||
...["-af", "aresample=async=1:first_pts=0"],
|
||||
...["-ac", "1", "-ar", String(RATE), "-f", "f32le", "-"],
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { decodeAudio, probeAudio } from "../audio/analysis/decode.js";
|
||||
import { probeSeconds, probeVideo, readFrames } from "../measure/media.js";
|
||||
import { sampledAlphaIsFullyOpaque } from "./webmAlphaCheck.js";
|
||||
|
||||
const ffmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;
|
||||
const vp9 =
|
||||
ffmpeg && spawnSync("ffmpeg", ["-hide_banner", "-encoders"]).stdout.includes("libvpx-vp9");
|
||||
const PATTERN = /read it as a pattern/;
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-literal-inputs-"));
|
||||
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
function make(out: string, args: string[]): void {
|
||||
execFileSync("ffmpeg", ["-v", "error", "-y", ...args, out]);
|
||||
}
|
||||
|
||||
describe.skipIf(!ffmpeg)("a sound whose path ffmpeg would read as a pattern", () => {
|
||||
const tone = join(dir, "tone.wav");
|
||||
const inPatternFolder = join(dir, "d%03d", "tone.wav");
|
||||
beforeAll(() => {
|
||||
make(tone, ["-f", "lavfi", "-i", "sine=d=0.5"]);
|
||||
mkdirSync(join(dir, "d%03d"));
|
||||
copyFileSync(tone, inPatternFolder);
|
||||
});
|
||||
|
||||
it("is probed and decoded under a plain name", async () => {
|
||||
expect((await probeAudio(tone))?.sampleRate).toBe(44100);
|
||||
expect((await decodeAudio(tone))?.signal.channels[0]?.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("is refused by the probe, with or without the caller's input arguments", async () => {
|
||||
await expect(probeAudio(inPatternFolder)).rejects.toThrow(PATTERN);
|
||||
await expect(probeAudio(inPatternFolder, ["-format_whitelist", "wav"])).rejects.toThrow(
|
||||
PATTERN,
|
||||
);
|
||||
});
|
||||
|
||||
it("is refused by the decoder even when the caller passes a probe", async () => {
|
||||
const probed = await probeAudio(tone);
|
||||
await expect(decodeAudio(inPatternFolder, {}, probed ?? undefined)).rejects.toThrow(PATTERN);
|
||||
});
|
||||
|
||||
it("is refused by measure's sound probe", () => {
|
||||
expect(probeSeconds(tone)).toBeGreaterThan(0);
|
||||
expect(() => probeSeconds(inPatternFolder)).toThrow(PATTERN);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!ffmpeg)("a picture named like a numbered sequence", () => {
|
||||
const plain = join(dir, "frame.png");
|
||||
const pattern = join(dir, "a%d.png");
|
||||
beforeAll(() => {
|
||||
make(plain, ["-f", "lavfi", "-i", "color=c=red:s=16x16", "-frames:v", "1"]);
|
||||
copyFileSync(plain, join(dir, "a1.png"));
|
||||
copyFileSync(plain, pattern);
|
||||
});
|
||||
|
||||
it("is measured under a plain name", () => {
|
||||
expect(probeVideo(plain).width).toBe(16);
|
||||
expect(readFrames(plain, { limit: 1 }).frames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("is refused by measure's probe and decode instead of opening a1.png", () => {
|
||||
expect(() => probeVideo(pattern)).toThrow(PATTERN);
|
||||
expect(() => readFrames(pattern, { limit: 1 })).toThrow(PATTERN);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!vp9)("a transparent WebM named like a pattern", () => {
|
||||
const plain = join(dir, "alpha.webm");
|
||||
const pattern = join(dir, "alpha%d.webm");
|
||||
beforeAll(() => {
|
||||
make(plain, [
|
||||
...["-f", "lavfi", "-i", "color=c=red@0.5:s=16x16:d=0.2,format=yuva420p"],
|
||||
...["-c:v", "libvpx-vp9", "-auto-alt-ref", "0"],
|
||||
]);
|
||||
copyFileSync(plain, pattern);
|
||||
});
|
||||
|
||||
it("is sampled under a plain name and left unsampled under the pattern name", () => {
|
||||
expect(sampledAlphaIsFullyOpaque(plain)).toBe(false);
|
||||
expect(sampledAlphaIsFullyOpaque(pattern)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
|
||||
@@ -86,6 +87,7 @@ function probeWebmAlpha(filePath: string): WebmAlphaProbe {
|
||||
"stream=codec_name:stream_tags=alpha_mode",
|
||||
"-of",
|
||||
"json",
|
||||
...mediaInputFormatArgs(ffprobePath, filePath),
|
||||
"--",
|
||||
filePath,
|
||||
],
|
||||
@@ -147,6 +149,7 @@ export function sampledAlphaIsFullyOpaque(filePath: string): boolean | undefined
|
||||
"error",
|
||||
"-c:v",
|
||||
"libvpx-vp9",
|
||||
...mediaInputFormatArgs(ffmpegPath, filePath),
|
||||
"-i",
|
||||
filePath,
|
||||
"-frames:v",
|
||||
|
||||
@@ -294,7 +294,7 @@ describe.skipIf(process.platform === "win32")("prepareWav", () => {
|
||||
const ffmpeg = join(dir, "ffmpeg");
|
||||
writeFileSync(
|
||||
ffmpeg,
|
||||
`#!${process.execPath}\nrequire("fs").writeFileSync(process.argv.at(-1), "partial");\nprocess.exit(255);\n`,
|
||||
`#!${process.execPath}\nif (process.argv.includes("-demuxers")) process.exit(0);\nrequire("fs").writeFileSync(process.argv.at(-1), "partial");\nprocess.exit(255);\n`,
|
||||
);
|
||||
chmodSync(ffmpeg, 0o755);
|
||||
const leftovers = () =>
|
||||
|
||||
@@ -36,6 +36,7 @@ import { parseWhisperJson, type Word } from "./normalize.js";
|
||||
import { emitWords } from "./progress.js";
|
||||
import { probeAudio } from "../audio/analysis/decode.js";
|
||||
import { decodableAudioStream } from "@hyperframes/parsers/media-streams";
|
||||
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
|
||||
export { initialModelForLanguage };
|
||||
|
||||
@@ -184,6 +185,7 @@ export function getMediaDurationSeconds(filePath: string): number | null {
|
||||
"format=duration",
|
||||
"-of",
|
||||
"default=noprint_wrappers=1:nokey=1",
|
||||
...mediaInputFormatArgs(ffprobePath, filePath),
|
||||
"--",
|
||||
filePath,
|
||||
]);
|
||||
@@ -379,6 +381,7 @@ async function extractAudio(videoPath: string, signal?: AbortSignal): Promise<st
|
||||
await runFfmpeg(
|
||||
ffmpegPath,
|
||||
[
|
||||
...mediaInputFormatArgs(ffmpegPath, videoPath),
|
||||
"-i",
|
||||
videoPath,
|
||||
"-map",
|
||||
@@ -425,6 +428,7 @@ function isWav16kMono(filePath: string): boolean {
|
||||
"-print_format",
|
||||
"json",
|
||||
"-show_streams",
|
||||
...mediaInputFormatArgs(ffprobePath, filePath),
|
||||
"--",
|
||||
filePath,
|
||||
]);
|
||||
@@ -453,7 +457,17 @@ async function prepareAudio(audioPath: string, signal?: AbortSignal): Promise<st
|
||||
const wavPath = tempWavPath();
|
||||
await runFfmpeg(
|
||||
ffmpegPath,
|
||||
["-i", audioPath, "-ar", "16000", "-ac", "1", "-f", "wav"],
|
||||
[
|
||||
...mediaInputFormatArgs(ffmpegPath, audioPath),
|
||||
"-i",
|
||||
audioPath,
|
||||
"-ar",
|
||||
"16000",
|
||||
"-ac",
|
||||
"1",
|
||||
"-f",
|
||||
"wav",
|
||||
],
|
||||
wavPath,
|
||||
resolveAudioPreparationTimeoutMs(getMediaDurationSeconds(audioPath)),
|
||||
signal,
|
||||
|
||||
Reference in New Issue
Block a user