fix(studio-server): a preview copy that joins short is refused and made again

Only a join of pieces with sound runs without -xerror, and every join is measured before it is kept: a copy shorter than its pieces is refused and its pieces are removed, so the next attempt makes them again. The sound test reads ffprobe's JSON so CRLF output parses too.
This commit is contained in:
Miguel Angel Simon Sierra
2026-11-19 15:55:50 -05:00
parent 65342bf045
commit f03753812b
2 changed files with 79 additions and 16 deletions
@@ -272,7 +272,8 @@ describe("resolveProxy on a long source", () => {
await answerAll(calls);
await result;
const joinArgs = calls.at(-1)!.args;
expect(joinArgs.slice(1, 13)).toEqual([
expect(joinArgs.slice(1, 14)).toEqual([
"-xerror",
"-protocol_whitelist",
"file",
"-f",
@@ -288,6 +289,47 @@ describe("resolveProxy on a long source", () => {
]);
});
it("refuses a join of pieces with sound that came out short, and makes its pieces again", async () => {
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,
}));
let joinedSeconds = 2 * PIECE_SECONDS;
vi.doMock("./mediaMetadata.js", () => ({
probeMediaMetadata: async (path: string) => ({
kind: "video",
color: { isHdr: false, hdrTransfer: null },
durationSeconds: path.includes(".transcode-cache") ? joinedSeconds : LONG_SECONDS,
audioStream: 0,
}),
probeFirstFrameColour: async () => ({}),
}));
const { resolveProxy, getProxyCachePath, clearFailedTranscodesForTest } =
await import("./proxyTranscoder.js");
const projectDir = tmpProject();
const sourcePath = join(projectDir, "talk.mov");
writeFileSync(sourcePath, "source-bytes");
const cacheDirectory = join(projectDir, ".transcode-cache");
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(`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.skipIf(process.platform === "win32")(
"runs the join from the cache folder and names the list there by its bare name",
async () => {
@@ -380,16 +422,18 @@ describe("resolveProxy on a long source", () => {
]);
const proxyPath = await resolveProxy(projectDir, sourcePath);
const streams = execFileSync(
findFfBinary("ffprobe")!,
[
...["-v", "error", "-show_entries", "stream=codec_type:format=duration"],
...["-of", "csv=p=0", "--", proxyPath],
],
{ encoding: "utf8" },
).split("\n");
expect(streams).toEqual(expect.arrayContaining(["video", "audio"]));
expect(Number(streams.find((line) => /^[\d.]+$/.test(line)))).toBeCloseTo(LONG_SECONDS, 0);
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,
);
@@ -670,9 +670,20 @@ async function encodeInChunks(
} finally {
rmSync(listPath, { force: true });
}
const wanted = ranges.reduce((sum, range) => sum + range.lengthSeconds, 0);
const { durationSeconds: joined } = await probeMediaMetadata(tempPath);
for (const piece of pieces) if (existsSync(piece)) unlinkSync(piece);
if (joined === undefined || joined < wanted - JOIN_SHORTFALL_ALLOWED_SECONDS) {
throw new ProxyTranscodeError(
`the joined copy lasts ${joined?.toFixed(1) ?? "an unknown time"} s of ${wanted.toFixed(1)} s; 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 = [
@@ -833,7 +844,12 @@ async function runFfmpeg(
const cwd = JOIN_FROM_CACHE_FOLDER ? dirname(listPath) : undefined;
return spawnFfmpeg(
ffmpegPath,
concatArgs(cwd ? basename(listPath) : listPath, target, variant),
concatArgs(
cwd ? basename(listPath) : listPath,
target,
variant,
metadata.audioStream !== undefined,
),
CONCAT_TIMEOUT_MS,
signal,
undefined,
@@ -850,12 +866,15 @@ async function runFfmpeg(
}
}
const LET_FFMPEG_MOVE_SOUND_TIMESTAMPS_AT_SEAMS = { exitOnError: false };
function concatArgs(listPath: string, target: string, variant: ProxyVariant): string[] {
function concatArgs(
listPath: string,
target: string,
variant: ProxyVariant,
piecesHaveSound: boolean,
): string[] {
return [
"-y",
...concatListInputArgs(listPath, LET_FFMPEG_MOVE_SOUND_TIMESTAMPS_AT_SEAMS),
...concatListInputArgs(listPath, { exitOnError: !piecesHaveSound }),
"-c",
"copy",
...(variant === "h264" ? ["-movflags", "+faststart"] : []),