mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(render): keep segment checkpoints in the local cache (#8137)
* fix(render): keep segment checkpoints in the local cache * fix(producer): read checkpoints through a validated descriptor * fix(render): enforce cache and audio sidecar input policies * fix(render): recapture unreadable segment checkpoints * chore(parsers): remove redundant concat comment
This commit is contained in:
@@ -203,6 +203,7 @@ export {
|
||||
buildEncoderArgs,
|
||||
encodeFramesFromDir,
|
||||
buildConcatArgs,
|
||||
writeVideoConcatList,
|
||||
concatVideoFiles,
|
||||
encodeFramesChunkedConcat,
|
||||
muxVideoWithAudio,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* so long audio is encoded as frame-aligned segments in parallel and their frames joined.
|
||||
*/
|
||||
|
||||
import { localContainerInputArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { removeScratch } from "@hyperframes/core/remove-scratch";
|
||||
@@ -84,10 +85,11 @@ function supportsSettsDuration(binary = getFfmpegBinary()): Promise<boolean> {
|
||||
function encodeInOnePass(
|
||||
input: string,
|
||||
outputPath: string,
|
||||
inputArgs: string[],
|
||||
{ signal, timeout, filter }: { signal?: AbortSignal; timeout: number; filter?: string },
|
||||
): Promise<RunFfmpegResult> {
|
||||
const filters = [filter, `aresample=${SAMPLE_RATE}`].filter(Boolean).join(",");
|
||||
return runFfmpeg(["-i", input, "-af", filters, ...AAC_ARGS, "-y", outputPath], {
|
||||
return runFfmpeg([...inputArgs, "-i", input, "-af", filters, ...AAC_ARGS, "-y", outputPath], {
|
||||
signal,
|
||||
timeout,
|
||||
});
|
||||
@@ -102,11 +104,19 @@ export async function encodeAac(
|
||||
signal,
|
||||
timeout,
|
||||
filter,
|
||||
inputContainer,
|
||||
segments: count = aacSegmentCount(totalDuration),
|
||||
}: { signal?: AbortSignal; timeout: number; filter?: string; segments?: number },
|
||||
}: {
|
||||
signal?: AbortSignal;
|
||||
timeout: number;
|
||||
filter?: string;
|
||||
segments?: number;
|
||||
inputContainer?: "mov";
|
||||
},
|
||||
): Promise<RunFfmpegResult> {
|
||||
const inputArgs = localContainerInputArgs(inputContainer);
|
||||
if (!(await supportsSettsDuration())) {
|
||||
return encodeInOnePass(input, outputPath, { signal, timeout, filter });
|
||||
return encodeInOnePass(input, outputPath, inputArgs, { signal, timeout, filter });
|
||||
}
|
||||
const dir = createStagingDir(dirname(outputPath), ".aac-segments-");
|
||||
try {
|
||||
@@ -120,6 +130,7 @@ export async function encodeAac(
|
||||
[
|
||||
"-cpuflags",
|
||||
"0",
|
||||
...inputArgs,
|
||||
"-i",
|
||||
input,
|
||||
"-af",
|
||||
|
||||
@@ -4,7 +4,12 @@ import { tmpdir } from "node:os";
|
||||
import { join, relative } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { getFfmpegBinary, getFfprobeBinary } from "../utils/ffmpegBinaries.js";
|
||||
import { concatVideoFiles, encodeFramesChunkedConcat } from "./chunkEncoder.js";
|
||||
import {
|
||||
buildConcatArgs,
|
||||
writeVideoConcatList,
|
||||
concatVideoFiles,
|
||||
encodeFramesChunkedConcat,
|
||||
} from "./chunkEncoder.js";
|
||||
import { validJpeg } from "./__fixtures__/jpeg.js";
|
||||
|
||||
const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"]).status === 0;
|
||||
@@ -58,6 +63,34 @@ describe.skipIf(!HAS_FFMPEG)("concat input paths", () => {
|
||||
expect(probe.stdout.trim()).toBe("64,64,30/1,40");
|
||||
}, 30_000);
|
||||
|
||||
it("rejects a non-video demuxer even after a valid first segment", async () => {
|
||||
const clip = join(root, "clip.mp4");
|
||||
const made = spawnSync(getFfmpegBinary(), [
|
||||
"-v",
|
||||
"error",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"color=size=32x32",
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
clip,
|
||||
]);
|
||||
expect(made.status, made.stderr.toString()).toBe(0);
|
||||
const other = join(root, "second.mp4");
|
||||
writeFileSync(other, "ffconcat version 1.0\n");
|
||||
const list = writeVideoConcatList(root, [other]);
|
||||
const rejected = spawnSync(getFfmpegBinary(), buildConcatArgs(list, join(root, "unused.mp4")), {
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(rejected.status).not.toBe(0);
|
||||
expect(rejected.stderr).toContain("not on whitelist");
|
||||
const result = await concatVideoFiles([clip, other], join(root, "joined.mp4"));
|
||||
expect(result).toMatchObject({ success: false, externalInterruption: false });
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"preserves frames and order with mixed input paths, relative first: %s",
|
||||
async (relativeFirst) => {
|
||||
@@ -201,9 +234,7 @@ describe.skipIf(!HAS_FFMPEG)("concat input formats", () => {
|
||||
expect(result.success).toBe(false);
|
||||
}, 30_000);
|
||||
|
||||
it("follows a listed file that is itself an ffconcat list, but only to relative names", async () => {
|
||||
// `concat` stays in the format whitelist because the list itself opens through it, so a nested
|
||||
// list is followed. It opens with the default `-safe 1`, which refuses absolute paths.
|
||||
it("refuses nested lists with relative or absolute names", async () => {
|
||||
const sub = join(root, "sub");
|
||||
mkdirSync(sub);
|
||||
makeClip(join(root, "a.mp4"), 2);
|
||||
@@ -212,10 +243,8 @@ describe.skipIf(!HAS_FFMPEG)("concat input formats", () => {
|
||||
const joined = join(root, "joined.mp4");
|
||||
|
||||
writeFileSync(nested, "ffconcat version 1.0\nfile 'beside.mp4'\n");
|
||||
expect(await concatVideoFiles([join(root, "a.mp4"), nested], joined)).toEqual({
|
||||
success: true,
|
||||
});
|
||||
expect(frameCount(joined)).toBe("5");
|
||||
const relative = await concatVideoFiles([join(root, "a.mp4"), nested], joined);
|
||||
expect(relative.success).toBe(false);
|
||||
|
||||
writeFileSync(nested, `ffconcat version 1.0\nfile '${join(sub, "beside.mp4")}'\n`);
|
||||
const absolute = await concatVideoFiles([join(root, "a.mp4"), nested], joined);
|
||||
|
||||
@@ -314,7 +314,9 @@ describe("encodeFramesChunkedConcat ffmpegEncodeTimeout", () => {
|
||||
expect(dirname(chunkPath)).not.toBe(legacyDir);
|
||||
expect(dirname(list)).toBe(dirname(chunkPath));
|
||||
expect(dirname(dirname(list))).toBe(root);
|
||||
expect(readFileSync(list, "utf8")).toBe(`file '${chunkPath.replace(/'/g, "'\\''")}'\n`);
|
||||
expect(readFileSync(list, "utf8")).toBe(
|
||||
`file '${chunkPath.replace(/'/g, "'\\''")}'\noption format_whitelist mov,matroska\n`,
|
||||
);
|
||||
}
|
||||
expect(readFileSync(legacyList, "utf8")).toBe("another render's concat list");
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* Supports CPU (libx264) and GPU encoding.
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { frameSequencePath } from "./extractedFrameIndex.js";
|
||||
import {
|
||||
closeSync,
|
||||
@@ -50,7 +51,11 @@ import { appendVp9CpuUsedArg } from "./vp9Options.js";
|
||||
import { appendSoftwareEncoderThreadsArg } from "./softwareEncoderThreads.js";
|
||||
import { appendRenderProvenanceArgs } from "../utils/renderProvenance.js";
|
||||
import { createStagingDir } from "@hyperframes/core/atomic-file";
|
||||
import { concatListInputArgs, concatListText } from "@hyperframes/parsers/ff-binaries";
|
||||
import {
|
||||
concatListInputArgs,
|
||||
concatListText,
|
||||
localContainerInputArgs,
|
||||
} from "@hyperframes/parsers/ff-binaries";
|
||||
|
||||
export type { EncoderOptions, EncodeResult, MuxResult } from "./chunkEncoder.types.js";
|
||||
|
||||
@@ -102,6 +107,7 @@ export interface MuxVideoWithAudioOptions extends Partial<
|
||||
* depend on the file extension alone.
|
||||
*/
|
||||
audioCodec?: "aac";
|
||||
audioContainer?: "mov";
|
||||
/** Replaces `-i <videoPath>` (which is then unused), e.g. with a concat-demuxer input. */
|
||||
videoInputArgs?: readonly string[];
|
||||
/**
|
||||
@@ -124,7 +130,9 @@ async function shouldCopyAacSidecar(
|
||||
if (KNOWN_NON_AAC_AUDIO_EXTENSIONS.has(audioExtension)) return false;
|
||||
|
||||
try {
|
||||
const metadata = await extractAudioMetadata(audioPath);
|
||||
const metadata = options?.audioContainer
|
||||
? await extractAudioMetadata(audioPath, { inputContainer: options.audioContainer })
|
||||
: await extractAudioMetadata(audioPath);
|
||||
return metadata.audioCodec === "aac";
|
||||
} catch {
|
||||
// Preserve the pre-existing fallback for invalid or unprobeable sidecars:
|
||||
@@ -683,18 +691,13 @@ export function buildConcatArgs(concatListPath: string, outputPath: string): str
|
||||
return args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sequence rather than a timestamp: two lists written in the same millisecond
|
||||
* into one directory would otherwise collide, and a concat that reads another
|
||||
* render's list produces a silently wrong video rather than an error.
|
||||
*/
|
||||
let concatListSeq = 0;
|
||||
|
||||
function writeConcatList(dir: string, inputPaths: readonly string[]): string {
|
||||
concatListSeq += 1;
|
||||
const listPath = join(dir, `concat-list-${process.pid}-${concatListSeq}.txt`);
|
||||
const body = concatListText(inputPaths.map((p) => resolve(p)));
|
||||
writeFileSync(listPath, body, "utf-8");
|
||||
export function writeVideoConcatList(dir: string, inputPaths: readonly string[]): string {
|
||||
const listPath = join(dir, `concat-list-${randomUUID()}.txt`);
|
||||
const body = concatListText(
|
||||
inputPaths.map((path) => resolve(path)),
|
||||
{ videoContainersOnly: true },
|
||||
);
|
||||
writeFileSync(listPath, body, { flag: "wx", mode: 0o600 });
|
||||
return listPath;
|
||||
}
|
||||
|
||||
@@ -723,7 +726,7 @@ export async function concatVideoFiles(
|
||||
// and `--debug` keeps both so a bad concat can be reproduced from its list.
|
||||
let listPath: string;
|
||||
try {
|
||||
listPath = writeConcatList(dirname(firstInput), inputPaths);
|
||||
listPath = writeVideoConcatList(dirname(firstInput), inputPaths);
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message, externalInterruption: false };
|
||||
}
|
||||
@@ -891,7 +894,14 @@ export async function muxVideoWithAudio(
|
||||
const isWebm = outputExtension === ".webm";
|
||||
const isMov = outputExtension === ".mov";
|
||||
const shouldCopyAudio = isWebm ? false : await shouldCopyAacSidecar(audioPath, config);
|
||||
const args = [...(config?.videoInputArgs ?? ["-i", videoPath]), "-i", audioPath, "-c:v", "copy"];
|
||||
const args = [
|
||||
...(config?.videoInputArgs ?? ["-i", videoPath]),
|
||||
...localContainerInputArgs(config?.audioContainer),
|
||||
"-i",
|
||||
audioPath,
|
||||
"-c:v",
|
||||
"copy",
|
||||
];
|
||||
|
||||
if (isWebm) {
|
||||
args.push("-c:a", "libopus", "-b:a", "128k");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// fallow-ignore-file code-duplication complexity
|
||||
import { localContainerInputArgs } from "@hyperframes/parsers/ff-binaries";
|
||||
import { spawn } from "child_process";
|
||||
import { createReadStream, mkdtempSync, readFileSync, rmSync, statSync } from "fs";
|
||||
import { chunkCrc32 } from "./crc32.js";
|
||||
@@ -1333,10 +1334,12 @@ export const extractVideoMetadata = extractMediaMetadata;
|
||||
|
||||
export async function extractAudioMetadata(
|
||||
filePath: string,
|
||||
options?: { signal?: AbortSignal },
|
||||
options?: { signal?: AbortSignal; inputContainer?: "mov" },
|
||||
): Promise<AudioMetadata> {
|
||||
// A probe bound to a caller's abort signal is shared only among callers of that same signal,
|
||||
// and only when the file has an identity to key it by.
|
||||
if (options?.inputContainer)
|
||||
return probeAudioMetadata(filePath, options.signal, options.inputContainer);
|
||||
const identity = mediaFileIdentity(filePath);
|
||||
const signal = options?.signal;
|
||||
if (signal && identity === null) return probeAudioMetadata(filePath, signal);
|
||||
@@ -1352,8 +1355,17 @@ export async function extractAudioMetadata(
|
||||
return probePromise;
|
||||
}
|
||||
|
||||
async function probeAudioMetadata(filePath: string, signal?: AbortSignal): Promise<AudioMetadata> {
|
||||
const output = await probeMediaOutput(filePath, signal);
|
||||
async function probeAudioMetadata(
|
||||
filePath: string,
|
||||
signal?: AbortSignal,
|
||||
inputContainer?: "mov",
|
||||
): Promise<AudioMetadata> {
|
||||
const inputArgs = localContainerInputArgs(inputContainer);
|
||||
const output = inputContainer
|
||||
? refuseTextArt(
|
||||
parseProbeJson(await runFfprobe(filePath, [...PROBE_JSON_ARGS, ...inputArgs], signal)),
|
||||
)
|
||||
: await probeMediaOutput(filePath, signal);
|
||||
const audioStreams = output.streams.filter((s) => s.codec_type === "audio");
|
||||
const audioStreamIndex = decodableAudioStream(output.streams);
|
||||
const audioStream = audioStreamIndex === null ? undefined : audioStreams[audioStreamIndex];
|
||||
@@ -1373,6 +1385,7 @@ async function probeAudioMetadata(filePath: string, signal?: AbortSignal): Promi
|
||||
audioStartSeconds(audioStream, output.format),
|
||||
durationSeconds,
|
||||
signal,
|
||||
inputArgs,
|
||||
);
|
||||
if (decoded !== null) {
|
||||
durationSeconds = reconcileAudioDuration(durationSeconds, decoded, output.format);
|
||||
@@ -1455,6 +1468,7 @@ async function probeDecodedAudioDuration(
|
||||
startSeconds: number,
|
||||
containerDurationSeconds: number,
|
||||
signal?: AbortSignal,
|
||||
inputArgs: string[] = [],
|
||||
): Promise<number | null> {
|
||||
const probe = async (
|
||||
readInterval?: string,
|
||||
@@ -1471,7 +1485,7 @@ async function probeDecodedAudioDuration(
|
||||
try {
|
||||
const stdout = await runFfprobe(
|
||||
filePath,
|
||||
args,
|
||||
[...args, ...inputArgs],
|
||||
signal,
|
||||
// CSV, not JSON: a tail truncated under the size cap still parses.
|
||||
{ retainTail: true, maxChars: 64 * 1024 },
|
||||
|
||||
Reference in New Issue
Block a user