mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(studio-server): long preview copies keep only the picture in pieces and add the sound once
AAC pieces overlap at every seam (each piece's priming frame reaches back into the one before), so a strict join refuses them. Pieces now carry only the picture and join strictly, exactly like the render joins; the sound is encoded once from the source and put with the picture by a stream copy that keeps both on the source's timeline. This replaces the length checks of the earlier commits, and old pieces with sound get a new name tag so they are never joined as picture-only pieces.
This commit is contained in:
@@ -273,12 +273,9 @@ export function concatListText(
|
||||
* Concat input for a list HyperFrames wrote: entries open only as local mov, matroska or concat
|
||||
* files (an ffconcat entry is followed in safe mode), and `-xerror` fails at a refused entry.
|
||||
*/
|
||||
export function concatListInputArgs(
|
||||
concatListPath: string,
|
||||
{ exitOnError = true }: { exitOnError?: boolean } = {},
|
||||
): string[] {
|
||||
export function concatListInputArgs(concatListPath: string): string[] {
|
||||
return [
|
||||
...(exitOnError ? ["-xerror"] : []),
|
||||
"-xerror",
|
||||
"-protocol_whitelist",
|
||||
"file",
|
||||
"-f",
|
||||
|
||||
@@ -138,32 +138,6 @@ describe("probeMediaMetadata", () => {
|
||||
expect(audioFile).not.toHaveProperty("hasAudio");
|
||||
});
|
||||
|
||||
it("reads how long the picture and the sound it plays last, apart from longer tracks it leaves out", async () => {
|
||||
const probe = (streams: object[]) =>
|
||||
probeMediaMetadata("/tmp/clip.mkv", () => ({
|
||||
status: 0,
|
||||
stdout: JSON.stringify({ streams, format: { duration: "50.0" } }),
|
||||
stderr: "",
|
||||
}));
|
||||
const mp4 = await probe([
|
||||
{ codec_type: "video", codec_name: "h264", duration: "47.000000" },
|
||||
{ codec_type: "audio", codec_name: "aac", duration: "47.021333" },
|
||||
{ codec_type: "audio", codec_name: "aac", duration: "50.000000" },
|
||||
{ codec_type: "subtitle", codec_name: "mov_text", duration: "50.000000" },
|
||||
]);
|
||||
expect(mp4).toMatchObject({ durationSeconds: 50, keptStreamsSeconds: 47.021333 });
|
||||
const mkv = await probe([
|
||||
{ codec_type: "video", codec_name: "vp9", tags: { DURATION: "00:00:47.000000000" } },
|
||||
{ codec_type: "subtitle", codec_name: "ass", tags: { DURATION: "00:00:50.000000000" } },
|
||||
]);
|
||||
expect(mkv.keptStreamsSeconds).toBe(47);
|
||||
const unknown = await probe([
|
||||
{ codec_type: "video", codec_name: "h264" },
|
||||
{ codec_type: "audio", codec_name: "aac", duration: "47.0" },
|
||||
]);
|
||||
expect(unknown).not.toHaveProperty("keptStreamsSeconds");
|
||||
});
|
||||
|
||||
it("reads a flac file as audio", async () => {
|
||||
const flac = await probeMediaMetadata("/tmp/music.flac", () => ({
|
||||
status: 0,
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface FfprobeRunResult {
|
||||
export type FfprobeRunner = (
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: { timeout?: number; maxBuffer?: number; signal?: AbortSignal },
|
||||
options?: { timeout?: number; maxBuffer?: number },
|
||||
) => FfprobeRunResult | Promise<FfprobeRunResult>;
|
||||
|
||||
/** Default runner: genuinely async (`execFile`), unlike the previous
|
||||
@@ -41,12 +41,7 @@ const execFileRunner: FfprobeRunner = (command, args, options) =>
|
||||
execFile(
|
||||
command,
|
||||
args,
|
||||
{
|
||||
timeout: options?.timeout,
|
||||
maxBuffer: options?.maxBuffer,
|
||||
signal: options?.signal,
|
||||
windowsHide: true,
|
||||
},
|
||||
{ timeout: options?.timeout, maxBuffer: options?.maxBuffer, windowsHide: true },
|
||||
(error, stdout, stderr) => {
|
||||
if (error && error.code === "ENOENT") {
|
||||
resolvePromise({ status: null, stdout: "", stderr: "", error });
|
||||
@@ -90,7 +85,6 @@ export interface MediaMetadata {
|
||||
/** Video stream carries alpha (pix_fmt or the VP8/VP9 alpha_mode tag). */
|
||||
hasAlpha?: boolean;
|
||||
durationSeconds?: number;
|
||||
keptStreamsSeconds?: number;
|
||||
source?: PreviewSourceFacts;
|
||||
/** Every stream as `type:codec[flags]`, for a failure report. */
|
||||
streams?: string[];
|
||||
@@ -99,7 +93,6 @@ export interface MediaMetadata {
|
||||
|
||||
interface FfprobeStream {
|
||||
codec_type?: string;
|
||||
duration?: string;
|
||||
codec_name?: string;
|
||||
profile?: string;
|
||||
pix_fmt?: string;
|
||||
@@ -281,14 +274,6 @@ type ProbeOutput = {
|
||||
format?: { duration?: string; bit_rate?: string };
|
||||
};
|
||||
|
||||
function streamSeconds(stream: FfprobeStream): number | undefined {
|
||||
const tagged = /^(\d+):(\d+):([\d.]+)$/.exec(stream.tags?.DURATION ?? "");
|
||||
const seconds = tagged
|
||||
? Number(tagged[1]) * 3600 + Number(tagged[2]) * 60 + Number(tagged[3])
|
||||
: Number(stream.duration);
|
||||
return Number.isFinite(seconds) && seconds > 0 ? seconds : undefined;
|
||||
}
|
||||
|
||||
function audioOf(streams: FfprobeStream[]): Pick<MediaMetadata, "hasAudio" | "audioStream"> {
|
||||
const audioStream = decodableAudioStream(streams);
|
||||
return audioStream === null ? { hasAudio: false } : { hasAudio: true, audioStream };
|
||||
@@ -309,13 +294,6 @@ function metadataFromProbe(kind: MediaMetadata["kind"], parsed: ProbeOutput): Me
|
||||
metadata.hasAlpha = stream !== undefined && videoStreamHasAlpha(stream);
|
||||
const duration = Number(parsed.format?.duration);
|
||||
if (Number.isFinite(duration) && duration > 0) metadata.durationSeconds = duration;
|
||||
const keptAudio = (parsed.streams ?? []).filter((item) => item.codec_type === "audio")[
|
||||
metadata.audioStream ?? -1
|
||||
];
|
||||
const longestKept = Math.max(
|
||||
...[stream, keptAudio].flatMap((item) => (item ? [streamSeconds(item) ?? NaN] : [])),
|
||||
);
|
||||
if (Number.isFinite(longestKept)) metadata.keptStreamsSeconds = longestKept;
|
||||
metadata.source = sourceFactsOf(stream, parsed.format?.bit_rate);
|
||||
}
|
||||
return metadata;
|
||||
@@ -370,7 +348,6 @@ export async function probeAudioTrack(
|
||||
export async function probeMediaMetadata(
|
||||
filePath: string,
|
||||
runner: FfprobeRunner = execFileRunner,
|
||||
signal?: AbortSignal,
|
||||
): Promise<MediaMetadata> {
|
||||
const kind = inferKindFromPath(filePath);
|
||||
if (kind === "audio" || kind === "unknown") {
|
||||
@@ -395,14 +372,14 @@ export async function probeMediaMetadata(
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,bit_rate,r_frame_rate,avg_frame_rate,duration:stream_disposition:stream_tags=alpha_mode,DURATION:format=duration,bit_rate",
|
||||
"stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,bit_rate,r_frame_rate,avg_frame_rate:stream_disposition:stream_tags=alpha_mode:format=duration,bit_rate",
|
||||
"-of",
|
||||
"json",
|
||||
...mediaInputArgs(filePath),
|
||||
"--",
|
||||
filePath,
|
||||
],
|
||||
{ timeout: 15_000, maxBuffer: 1024 * 1024, signal },
|
||||
{ timeout: 15_000, maxBuffer: 1024 * 1024 },
|
||||
);
|
||||
|
||||
if (result.error?.code === "ENOENT") {
|
||||
|
||||
@@ -156,14 +156,6 @@ afterEach(() => {
|
||||
delete process.env.HYPERFRAMES_PROXY_MAX_QUEUE;
|
||||
});
|
||||
|
||||
/** A piece lasts its own stretch of the source, cut as the transcoder cuts it; any other file lasts the source. */
|
||||
function lengthOf(path: string, sourceSeconds: number | undefined): number | undefined {
|
||||
const index = /\.part-[^/\\]*-(\d+)\.\w+$/.exec(path)?.[1];
|
||||
if (index === undefined || sourceSeconds === undefined) return sourceSeconds;
|
||||
const count = Math.floor(sourceSeconds / PIECE_SECONDS);
|
||||
return Number(index) < count - 1 ? PIECE_SECONDS : sourceSeconds - (count - 1) * PIECE_SECONDS;
|
||||
}
|
||||
|
||||
async function loadModule(
|
||||
spawn: SpawnImpl,
|
||||
ffmpegPath: string | undefined,
|
||||
@@ -185,10 +177,10 @@ async function loadModule(
|
||||
findFfBinary: () => ffmpegPath,
|
||||
}));
|
||||
vi.doMock("./mediaMetadata.js", () => ({
|
||||
probeMediaMetadata: async (path: string) => ({
|
||||
probeMediaMetadata: async () => ({
|
||||
kind: "video",
|
||||
color: { isHdr, hdrTransfer, codecName },
|
||||
durationSeconds: lengthOf(path, durationSeconds),
|
||||
durationSeconds,
|
||||
streams,
|
||||
}),
|
||||
probeFirstFrameColour: async () => ({}),
|
||||
@@ -297,105 +289,6 @@ describe("resolveProxy on a long source", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
const isJoinedCopy = (path: string) => basename(path).startsWith(".tmp-");
|
||||
|
||||
/** A source with sound whose files last what `lengthFor` says when they are measured. */
|
||||
async function loadWithSound(
|
||||
lengthFor: (path: string) => number | undefined | Promise<number | undefined>,
|
||||
) {
|
||||
const { spawn, calls } = createSpawnSpy();
|
||||
vi.resetModules();
|
||||
vi.doMock("@hyperframes/core/preview-proof", () => ({ previewToken: () => "a".repeat(64) }));
|
||||
vi.doMock("node:child_process", () => ({ spawn, default: { spawn } }));
|
||||
vi.doMock("@hyperframes/parsers/ff-binaries", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hyperframes/parsers/ff-binaries")>()),
|
||||
findFfBinary: () => FFMPEG_PATH,
|
||||
}));
|
||||
vi.doMock("./mediaMetadata.js", () => ({
|
||||
probeMediaMetadata: async (path: string) => ({
|
||||
kind: "video",
|
||||
color: { isHdr: false, hdrTransfer: null },
|
||||
durationSeconds: await lengthFor(path),
|
||||
audioStream: 0,
|
||||
}),
|
||||
probeFirstFrameColour: async () => ({}),
|
||||
}));
|
||||
const projectDir = tmpProject();
|
||||
const sourcePath = join(projectDir, "talk.mov");
|
||||
writeFileSync(sourcePath, "source-bytes");
|
||||
return {
|
||||
...(await import("./proxyTranscoder.js")),
|
||||
calls,
|
||||
projectDir,
|
||||
sourcePath,
|
||||
cacheDirectory: join(projectDir, ".transcode-cache"),
|
||||
};
|
||||
}
|
||||
|
||||
it("refuses a join of pieces with sound that came out short, and makes its pieces again", async () => {
|
||||
let joinedSeconds = 2 * PIECE_SECONDS;
|
||||
const { resolveProxy, getProxyCachePath, clearFailedTranscodesForTest, ...made } =
|
||||
await loadWithSound((path) =>
|
||||
isJoinedCopy(path) ? joinedSeconds : lengthOf(path, LONG_SECONDS),
|
||||
);
|
||||
const { calls, projectDir, sourcePath, cacheDirectory } = made;
|
||||
|
||||
const short = resolveProxy(projectDir, sourcePath).catch((error: unknown) => error);
|
||||
await answerAll(calls);
|
||||
expect(calls.at(-1)!.args).not.toContain("-xerror");
|
||||
expect(String(await short)).toContain(
|
||||
`the joined copy lasts ${(2 * PIECE_SECONDS).toFixed(1)} s of`,
|
||||
);
|
||||
expect(copiesIn(cacheDirectory)).toEqual([]);
|
||||
|
||||
clearFailedTranscodesForTest();
|
||||
joinedSeconds = LONG_SECONDS;
|
||||
const piecesBefore = startsOf(calls).length;
|
||||
const whole = resolveProxy(projectDir, sourcePath);
|
||||
await answerAll(calls);
|
||||
expect(await whole).toBe(getProxyCachePath(projectDir, sourcePath));
|
||||
expect(startsOf(calls).length - piecesBefore).toBe(piecesBefore);
|
||||
});
|
||||
|
||||
it("refuses a join whose short piece shortens the copy it adds up to", async () => {
|
||||
const lastPiece = /\.part-[^/\\]*-2\.\w+$/;
|
||||
const shortBy = 14;
|
||||
const { resolveProxy, calls, projectDir, sourcePath, cacheDirectory } = await loadWithSound(
|
||||
(path) => {
|
||||
if (lastPiece.test(path)) return LONG_SECONDS - 2 * PIECE_SECONDS - shortBy;
|
||||
return isJoinedCopy(path) ? LONG_SECONDS - shortBy : lengthOf(path, LONG_SECONDS);
|
||||
},
|
||||
);
|
||||
|
||||
const short = resolveProxy(projectDir, sourcePath).catch((error: unknown) => error);
|
||||
await answerAll(calls);
|
||||
expect(String(await short)).toContain(
|
||||
`piece 3 lasts ${(LONG_SECONDS - 2 * PIECE_SECONDS - shortBy).toFixed(1)} s of`,
|
||||
);
|
||||
expect(copiesIn(cacheDirectory)).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps no copy when its last caller leaves while the copy is being measured", async () => {
|
||||
let measure: (seconds: number) => void = () => {};
|
||||
const measuring = new Promise<number>((resolve) => (measure = resolve));
|
||||
const { resolveProxy, getProxyCachePath, calls, projectDir, sourcePath, cacheDirectory } =
|
||||
await loadWithSound((path) =>
|
||||
isJoinedCopy(path) ? measuring : lengthOf(path, LONG_SECONDS),
|
||||
);
|
||||
const leave = new AbortController();
|
||||
|
||||
const left = resolveProxy(projectDir, sourcePath, "h264", undefined, {
|
||||
signal: leave.signal,
|
||||
}).catch((error: unknown) => error);
|
||||
await answerAll(calls);
|
||||
leave.abort();
|
||||
expect(await left).toBe(leave.signal.reason);
|
||||
measure(LONG_SECONDS);
|
||||
await flush(50);
|
||||
expect(existsSync(getProxyCachePath(projectDir, sourcePath))).toBe(false);
|
||||
expect(readdirSync(cacheDirectory).filter((name) => name.startsWith(".part-"))).toHaveLength(3);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"runs the join from the cache folder and names the list there by its bare name",
|
||||
async () => {
|
||||
@@ -472,33 +365,40 @@ describe("resolveProxy on a long source", () => {
|
||||
60_000,
|
||||
);
|
||||
|
||||
const realCopyOf = async (name: string, makeSource: (path: string) => void) => {
|
||||
vi.resetModules();
|
||||
vi.doUnmock("./mediaMetadata.js");
|
||||
vi.doMock("@hyperframes/core/preview-proof", () => ({ previewToken: () => "a".repeat(64) }));
|
||||
const { resolveProxy } = await import("./proxyTranscoder.js");
|
||||
const projectDir = realpathSync(tmpProject());
|
||||
const sourcePath = join(projectDir, name);
|
||||
makeSource(sourcePath);
|
||||
return { sourcePath, proxyPath: await resolveProxy(projectDir, sourcePath) };
|
||||
};
|
||||
const probeJson = (path: string, entries: string) =>
|
||||
JSON.parse(
|
||||
execFileSync(
|
||||
findFfBinary("ffprobe")!,
|
||||
["-v", "error", "-show_entries", entries, "-of", "json", "--", path],
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
|
||||
it.skipIf(!realFfmpeg || !findFfBinary("ffprobe"))(
|
||||
"joins the pieces of a source with sound into one copy that keeps its sound",
|
||||
async () => {
|
||||
vi.resetModules();
|
||||
vi.doUnmock("./mediaMetadata.js");
|
||||
vi.doMock("@hyperframes/core/preview-proof", () => ({ previewToken: () => "a".repeat(64) }));
|
||||
const { resolveProxy } = await import("./proxyTranscoder.js");
|
||||
const projectDir = realpathSync(tmpProject());
|
||||
const sourcePath = join(projectDir, "talk.mp4");
|
||||
execFileSync(realFfmpeg!, [
|
||||
...["-v", "error", "-f", "lavfi", "-i", `color=c=blue:s=32x32:r=2:d=${LONG_SECONDS}`],
|
||||
...["-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:d=${LONG_SECONDS}`],
|
||||
...["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", sourcePath],
|
||||
const { proxyPath } = await realCopyOf("talk.mp4", (path) =>
|
||||
execFileSync(realFfmpeg!, [
|
||||
...["-v", "error", "-f", "lavfi", "-i", `color=c=blue:s=32x32:r=2:d=${LONG_SECONDS}`],
|
||||
...["-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:d=${LONG_SECONDS}`],
|
||||
...["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", path],
|
||||
]),
|
||||
);
|
||||
const probed = probeJson(proxyPath, "stream=codec_type:format=duration");
|
||||
expect(probed.streams.map((s: { codec_type: string }) => s.codec_type).sort()).toEqual([
|
||||
"audio",
|
||||
"video",
|
||||
]);
|
||||
|
||||
const proxyPath = await resolveProxy(projectDir, sourcePath);
|
||||
const probed = JSON.parse(
|
||||
execFileSync(
|
||||
findFfBinary("ffprobe")!,
|
||||
[
|
||||
...["-v", "error", "-show_entries", "stream=codec_type:format=duration"],
|
||||
...["-of", "json", "--", proxyPath],
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
) as { streams: Array<{ codec_type: string }>; format: { duration: string } };
|
||||
expect(probed.streams.map((stream) => stream.codec_type).sort()).toEqual(["audio", "video"]);
|
||||
expect(Number(probed.format.duration)).toBeCloseTo(LONG_SECONDS, 0);
|
||||
},
|
||||
60_000,
|
||||
@@ -507,32 +407,86 @@ describe("resolveProxy on a long source", () => {
|
||||
it.skipIf(!realFfmpeg || !findFfBinary("ffprobe"))(
|
||||
"keeps a whole copy when a track it leaves out runs longer than the picture",
|
||||
async () => {
|
||||
vi.resetModules();
|
||||
vi.doUnmock("./mediaMetadata.js");
|
||||
vi.doMock("@hyperframes/core/preview-proof", () => ({ previewToken: () => "a".repeat(64) }));
|
||||
const { resolveProxy } = await import("./proxyTranscoder.js");
|
||||
const projectDir = realpathSync(tmpProject());
|
||||
const sourcePath = join(projectDir, "two-tracks.mp4");
|
||||
const shown = LONG_SECONDS - 3;
|
||||
execFileSync(realFfmpeg!, [
|
||||
...["-v", "error", "-f", "lavfi", "-i", `color=c=blue:s=32x32:r=2:d=${shown}`],
|
||||
...["-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:d=${shown}`],
|
||||
...["-f", "lavfi", "-i", `sine=frequency=660:sample_rate=48000:d=${LONG_SECONDS}`],
|
||||
...["-map", "0", "-map", "1", "-map", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p"],
|
||||
...["-c:a", "aac", sourcePath],
|
||||
]);
|
||||
|
||||
const proxyPath = await resolveProxy(projectDir, sourcePath);
|
||||
const seconds = execFileSync(
|
||||
findFfBinary("ffprobe")!,
|
||||
["-v", "error", "-show_entries", "format=duration", "-of", "json", "--", proxyPath],
|
||||
{ encoding: "utf8" },
|
||||
const { proxyPath } = await realCopyOf("two-tracks.mp4", (path) =>
|
||||
execFileSync(realFfmpeg!, [
|
||||
...["-v", "error", "-f", "lavfi", "-i", `color=c=blue:s=32x32:r=2:d=${shown}`],
|
||||
...["-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:d=${shown}`],
|
||||
...["-f", "lavfi", "-i", `sine=frequency=660:sample_rate=48000:d=${LONG_SECONDS}`],
|
||||
...["-map", "0", "-map", "1", "-map", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p"],
|
||||
...["-c:a", "aac", path],
|
||||
]),
|
||||
);
|
||||
expect(Number(JSON.parse(seconds).format.duration)).toBeCloseTo(shown, 0);
|
||||
const streams = probeJson(proxyPath, "stream=codec_type,duration").streams;
|
||||
expect(streams.map((s: { codec_type: string }) => s.codec_type).sort()).toEqual([
|
||||
"audio",
|
||||
"video",
|
||||
]);
|
||||
for (const stream of streams) expect(Number(stream.duration)).toBeCloseTo(shown, 0);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
const CLAPS = [2, 14.5, 15.2, 29.9, 30.4, 44.6, 47];
|
||||
const FPS = 30;
|
||||
const soundMinusFlashPerClap = (path: string): number[] => {
|
||||
let at = 0;
|
||||
let lit = false;
|
||||
const flashes: number[] = [];
|
||||
const frames = execFileSync(
|
||||
realFfmpeg!,
|
||||
["-v", "error", "-i", path, "-vf", "signalstats,metadata=print:file=-", "-f", "null", "-"],
|
||||
{ encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
for (const line of frames.split(/\r?\n/)) {
|
||||
const time = /pts_time:([\d.]+)/.exec(line);
|
||||
if (time) at = Number(time[1]);
|
||||
const luma = /YAVG=([\d.]+)/.exec(line);
|
||||
if (!luma) continue;
|
||||
if (Number(luma[1]) > 100 && !lit) flashes.push(at);
|
||||
lit = Number(luma[1]) > 100;
|
||||
}
|
||||
const { stderr } = spawnSync(
|
||||
realFfmpeg!,
|
||||
["-i", path, "-map", "0:a", "-af", "silencedetect=n=-30dB:d=0.1", "-f", "null", "-"],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
const quiet = [...stderr.matchAll(/silence_(start|end): ([\d.]+)/g)];
|
||||
const sounds = quiet.flatMap((match, index) =>
|
||||
match[1] === "end" && quiet[index + 1]?.[1] === "start" ? [Number(match[2])] : [],
|
||||
);
|
||||
expect(flashes).toHaveLength(CLAPS.length);
|
||||
expect(sounds).toHaveLength(CLAPS.length);
|
||||
return flashes.map((flash, index) => sounds[index]! - flash);
|
||||
};
|
||||
|
||||
it.skipIf(!realFfmpeg || !findFfBinary("ffprobe")).each([
|
||||
["picture and sound together", 0, 0],
|
||||
["picture starting late", 0.4, 0],
|
||||
["sound starting late", 0, 0.4],
|
||||
])(
|
||||
"keeps every clap within a frame of the source across the seams, %s",
|
||||
async (_case, pictureDelay, soundDelay) => {
|
||||
const during = (seconds: number) =>
|
||||
CLAPS.map((clap) => `between(t,${clap},${clap + seconds})`).join("+");
|
||||
const { sourcePath, proxyPath } = await realCopyOf("claps.mp4", (path) =>
|
||||
execFileSync(realFfmpeg!, [
|
||||
...["-v", "error", "-itsoffset", String(pictureDelay), "-f", "lavfi", "-i"],
|
||||
`color=black:s=32x32:r=${FPS}:d=${LONG_SECONDS},drawbox=c=white:t=fill:enable='${during(2 / FPS)}'`,
|
||||
...["-itsoffset", String(soundDelay), "-f", "lavfi", "-i"],
|
||||
`aevalsrc='(${during(0.03)})*sin(2*PI*1000*t)':s=48000:d=${LONG_SECONDS}`,
|
||||
...["-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p"],
|
||||
...["-c:a", "aac", path],
|
||||
]),
|
||||
);
|
||||
const source = soundMinusFlashPerClap(sourcePath);
|
||||
soundMinusFlashPerClap(proxyPath).forEach((offset, index) =>
|
||||
expect(Math.abs(offset - source[index]!)).toBeLessThanOrEqual(1 / FPS),
|
||||
);
|
||||
},
|
||||
120_000,
|
||||
);
|
||||
|
||||
it("encodes every piece again when the project shipped pieces at the names it can predict", async () => {
|
||||
const { spawn, calls } = createSpawnSpy();
|
||||
const { resolveProxy, getProxyCachePath } = await loadModule(
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
concatListText,
|
||||
findFfBinary,
|
||||
followFfmpegProgress,
|
||||
localContainerInputArgs,
|
||||
} from "@hyperframes/parsers/ff-binaries";
|
||||
import { alphaDecoderFor } from "@hyperframes/parsers/media-alpha";
|
||||
import { ffmpegHasHdrFilters } from "./hdrFilters.js";
|
||||
@@ -87,7 +88,7 @@ function pieceSecret(): string {
|
||||
|
||||
function unguessablePiecePrefix(cacheDir: string, stem: string): string {
|
||||
const tag = createHmac("sha256", pieceSecret())
|
||||
.update(`proxy-piece\n${stem}`)
|
||||
.update(`proxy-picture-piece\n${stem}`)
|
||||
.digest("hex")
|
||||
.slice(0, 32);
|
||||
return join(cacheDir, `${CHUNK_PREFIX}${stem}-${tag}-`);
|
||||
@@ -670,29 +671,9 @@ async function encodeInChunks(
|
||||
} finally {
|
||||
rmSync(listPath, { force: true });
|
||||
}
|
||||
const measured = [...pieces, tempPath];
|
||||
const lengths = ranges.map((range) => range.lengthSeconds);
|
||||
const wanted = [...lengths, lengths.reduce((sum, length) => sum + length, 0)];
|
||||
let short: string | undefined;
|
||||
for (const [index, path] of measured.entries()) {
|
||||
const seconds = (await probeMediaMetadata(path, undefined, signal)).durationSeconds;
|
||||
signal.throwIfAborted();
|
||||
if (
|
||||
short === undefined &&
|
||||
!((seconds ?? NaN) >= wanted[index]! - JOIN_SHORTFALL_ALLOWED_SECONDS)
|
||||
) {
|
||||
const what = path === tempPath ? "the joined copy" : `piece ${index + 1}`;
|
||||
short = `${what} lasts ${seconds?.toFixed(1) ?? "an unknown time"} s of ${wanted[index]!.toFixed(1)} s`;
|
||||
}
|
||||
}
|
||||
for (const piece of pieces) if (existsSync(piece)) unlinkSync(piece);
|
||||
if (short !== undefined) {
|
||||
throw new ProxyTranscodeError(`${short}; its pieces are made again next time`, null, "");
|
||||
}
|
||||
}
|
||||
|
||||
const JOIN_SHORTFALL_ALLOWED_SECONDS = 1;
|
||||
|
||||
const KEYFRAME_EVERY_SECOND_ARGS = ["-force_key_frames", "expr:gte(t,n_forced*1)"];
|
||||
// Fixed recipe; changing either array means bumping PROXY_PARAMS_VERSION.
|
||||
const H264_ARGS = [
|
||||
@@ -799,14 +780,9 @@ async function runFfmpeg(
|
||||
const videoFilter = await buildVideoFilter(ffmpegPath, sourcePath, metadata, keepsAlpha, box);
|
||||
const alphaDecoder = keepsAlpha ? alphaDecoderFor(metadata.color.codecName) : null;
|
||||
const decoderArgs = alphaDecoder ? ["-c:v", alphaDecoder] : [];
|
||||
const streamArgs = [
|
||||
...["-map", "0:V:0"],
|
||||
...(metadata.audioStream === undefined ? [] : ["-map", `0:a:${metadata.audioStream}`]),
|
||||
];
|
||||
const totalSeconds = copiedSeconds(
|
||||
metadata.keptStreamsSeconds ?? metadata.durationSeconds,
|
||||
limitSeconds,
|
||||
);
|
||||
const soundMap =
|
||||
metadata.audioStream === undefined ? [] : ["-map", `0:a:${metadata.audioStream}`];
|
||||
const totalSeconds = copiedSeconds(metadata.durationSeconds, limitSeconds);
|
||||
// libvpx scales poorly across threads, so alpha pieces run side by side with the cores shared out.
|
||||
const gate = keepsAlpha ? ALPHA_PIECE_GATE : UNGATED;
|
||||
const vp8Threads = (pieces: number) => [
|
||||
@@ -826,7 +802,8 @@ async function runFfmpeg(
|
||||
...mediaInputArgs(sourcePath),
|
||||
"-i",
|
||||
sourcePath,
|
||||
...streamArgs,
|
||||
...["-map", "0:V:0"],
|
||||
...(range ? [] : soundMap),
|
||||
...lengthArgs(range?.lengthSeconds ?? limitSeconds),
|
||||
"-vf",
|
||||
videoFilter,
|
||||
@@ -846,22 +823,18 @@ async function runFfmpeg(
|
||||
onProgress({ doneSeconds: encodedSeconds, totalSeconds }),
|
||||
);
|
||||
}
|
||||
const picturePath = soundMap.length ? besideAsTemp(outputPath) : outputPath;
|
||||
await encodeInChunks(
|
||||
ranges,
|
||||
chunks,
|
||||
outputPath,
|
||||
picturePath,
|
||||
encode,
|
||||
(listPath, target) => {
|
||||
// ffmpeg resolves relative list entries against the list path, which breaks on '#' or '?' in a folder name.
|
||||
const cwd = JOIN_FROM_CACHE_FOLDER ? dirname(listPath) : undefined;
|
||||
return spawnFfmpeg(
|
||||
ffmpegPath,
|
||||
concatArgs(
|
||||
cwd ? basename(listPath) : listPath,
|
||||
target,
|
||||
variant,
|
||||
metadata.audioStream !== undefined,
|
||||
),
|
||||
concatArgs(cwd ? basename(listPath) : listPath, target, variant),
|
||||
CONCAT_TIMEOUT_MS,
|
||||
signal,
|
||||
undefined,
|
||||
@@ -873,20 +846,78 @@ async function runFfmpeg(
|
||||
gate,
|
||||
(doneSeconds) => onProgress({ doneSeconds, totalSeconds }),
|
||||
);
|
||||
if (picturePath !== outputPath) {
|
||||
await addSoundFromSource(
|
||||
ffmpegPath,
|
||||
sourcePath,
|
||||
soundMap,
|
||||
picturePath,
|
||||
outputPath,
|
||||
variant,
|
||||
limitSeconds,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
throw withSource(err, () => describeSource(sourcePath, metadata));
|
||||
}
|
||||
}
|
||||
|
||||
function concatArgs(
|
||||
listPath: string,
|
||||
target: string,
|
||||
function besideAsTemp(path: string, extension = extname(path)): string {
|
||||
const copyName = basename(path, extname(path)).replace(/^\.tmp-[0-9a-f-]{36}-/, "");
|
||||
return join(dirname(path), `.tmp-${randomUUID()}-${copyName}${extension}`);
|
||||
}
|
||||
|
||||
async function addSoundFromSource(
|
||||
ffmpegPath: string,
|
||||
sourcePath: string,
|
||||
soundMap: string[],
|
||||
picturePath: string,
|
||||
outputPath: string,
|
||||
variant: ProxyVariant,
|
||||
piecesHaveSound: boolean,
|
||||
): string[] {
|
||||
limitSeconds: number | undefined,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
const keepsAlpha = variant === "vp8";
|
||||
const soundPath = besideAsTemp(outputPath, keepsAlpha ? ".webm" : ".m4a");
|
||||
const container = keepsAlpha ? "matroska" : "mov";
|
||||
try {
|
||||
await spawnFfmpeg(
|
||||
ffmpegPath,
|
||||
[
|
||||
...["-y", "-progress", "pipe:1", "-nostats"],
|
||||
...mediaInputArgs(sourcePath),
|
||||
...["-i", sourcePath, ...soundMap],
|
||||
...lengthArgs(limitSeconds),
|
||||
...(keepsAlpha ? ["-ac", "2", "-c:a", "libopus"] : ["-c:a", "aac"]),
|
||||
soundPath,
|
||||
],
|
||||
TRANSCODE_STALL_MS,
|
||||
signal,
|
||||
);
|
||||
await spawnFfmpeg(
|
||||
ffmpegPath,
|
||||
[
|
||||
...["-y", "-copyts"],
|
||||
...[...localContainerInputArgs(container), "-i", picturePath],
|
||||
...[...localContainerInputArgs(container), "-i", soundPath],
|
||||
...["-map", "0:v:0", "-map", "1:a:0", "-c", "copy"],
|
||||
...(keepsAlpha ? [] : ["-movflags", "+faststart"]),
|
||||
outputPath,
|
||||
],
|
||||
CONCAT_TIMEOUT_MS,
|
||||
signal,
|
||||
);
|
||||
} finally {
|
||||
rmSync(soundPath, { force: true });
|
||||
rmSync(picturePath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function concatArgs(listPath: string, target: string, variant: ProxyVariant): string[] {
|
||||
return [
|
||||
"-y",
|
||||
...concatListInputArgs(listPath, { exitOnError: !piecesHaveSound }),
|
||||
...concatListInputArgs(listPath),
|
||||
"-c",
|
||||
"copy",
|
||||
...(variant === "h264" ? ["-movflags", "+faststart"] : []),
|
||||
@@ -1042,7 +1073,6 @@ async function transcodeToCache(
|
||||
(progress) => reportProgress(job, progress),
|
||||
() => job.background && !job.priority,
|
||||
);
|
||||
job.abandoned.signal.throwIfAborted();
|
||||
renameSync(tempPath, cachePath);
|
||||
writeCopyIndex(contentIndex, cachePath);
|
||||
maintainProxyCache(cacheDir);
|
||||
|
||||
Reference in New Issue
Block a user