fix(studio-server): a preview copy never keeps a short or broken piece from a stopped copy

A piece left by an earlier run is made again when it runs short of its stretch; when the join refuses one, every piece is dropped and made again once in the same run. A refused join no longer leaves its pieces or a picture temp behind; a stopped one keeps its pieces.
This commit is contained in:
Miguel Angel Simon Sierra
2026-11-19 21:11:42 -05:00
parent 21e951668d
commit a6d62ae2d6
2 changed files with 160 additions and 26 deletions
@@ -290,6 +290,78 @@ describe("resolveProxy on a long source", () => {
]); ]);
}); });
async function loadWithSound() {
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 () => ({
kind: "video",
color: { isHdr: false, hdrTransfer: null },
durationSeconds: LONG_SECONDS,
audioStream: 0,
}),
probeFirstFrameColour: async () => ({}),
}));
const projectDir = tmpProject();
const sourcePath = join(projectDir, "talk.mov");
writeFileSync(sourcePath, "source-bytes");
const leftIn = () =>
readdirSync(join(projectDir, ".transcode-cache")).filter((name) =>
/^\.(part|tmp)-/.test(name),
);
return { ...(await import("./proxyTranscoder.js")), calls, projectDir, sourcePath, leftIn };
}
const isJoin = (call: SpawnCall) => call.args.includes("concat");
it("makes every piece again after a join ffmpeg refuses, and leaves no picture behind", async () => {
const { resolveProxy, getProxyCachePath, clearFailedTranscodesForTest, ...made } =
await loadWithSound();
const { calls, projectDir, sourcePath, leftIn } = made;
const refused = resolveProxy(projectDir, sourcePath).catch((error: unknown) => error);
await answerUntilIdle(calls, (call) => {
if (!isJoin(call)) return succeed(call);
writeFileSync(call.args.at(-1)!, "partial picture");
fail(call, 1, "Impossible to open piece");
});
expect(await refused).toBeInstanceOf(Error);
expect(leftIn()).toEqual([]);
clearFailedTranscodesForTest();
const piecesBefore = startsOf(calls).length;
const answered = new Set(calls);
const whole = resolveProxy(projectDir, sourcePath);
await answerUntilIdle(calls, (call) => answered.has(call) || succeed(call));
expect(await whole).toBe(getProxyCachePath(projectDir, sourcePath));
expect(startsOf(calls).length - piecesBefore).toBe(piecesBefore);
expect(leftIn()).toEqual([]);
});
it("keeps its finished pieces and no picture when its last caller leaves during the join", async () => {
const { resolveProxy, calls, projectDir, sourcePath, leftIn } = await loadWithSound();
const leave = new AbortController();
const left = resolveProxy(projectDir, sourcePath, "h264", undefined, {
signal: leave.signal,
}).catch((error: unknown) => error);
await answerUntilIdle(calls, (call) => {
if (!isJoin(call)) return succeed(call);
writeFileSync(call.args.at(-1)!, "partial picture");
leave.abort();
call.proc.emit("close", null, "SIGKILL");
});
expect(await left).toBe(leave.signal.reason);
await flush(50);
expect(leftIn().every((name) => name.startsWith(".part-"))).toBe(true);
expect(leftIn()).toHaveLength(3);
});
it.skipIf(process.platform === "win32")( it.skipIf(process.platform === "win32")(
"runs the join from the cache folder and names the list there by its bare name", "runs the join from the cache folder and names the list there by its bare name",
async () => { async () => {
@@ -366,6 +438,12 @@ describe("resolveProxy on a long source", () => {
60_000, 60_000,
); );
const clip = (path: string, seconds: number) =>
execFileSync(realFfmpeg!, [
...["-y", "-v", "error", "-f", "lavfi", "-i", `color=c=blue:s=32x32:r=2:d=${seconds}`],
...["-f", "lavfi", "-i", `sine=frequency=440:sample_rate=48000:d=${seconds}`],
...["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", path],
]);
const realCopyOf = async (name: string, makeSource: (path: string) => void) => { const realCopyOf = async (name: string, makeSource: (path: string) => void) => {
vi.resetModules(); vi.resetModules();
vi.doUnmock("./mediaMetadata.js"); vi.doUnmock("./mediaMetadata.js");
@@ -405,6 +483,38 @@ describe("resolveProxy on a long source", () => {
60_000, 60_000,
); );
it.skipIf(!realFfmpeg || !findFfBinary("ffprobe")).each([
["ends early", (piece: string) => clip(piece, 5)],
["was cut off", (piece: string) => writeFileSync(piece, readFileSync(piece).subarray(0, 2000))],
])(
"makes a piece left from a stopped copy again when it %s",
async (_name, spoil) => {
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");
clip(sourcePath, LONG_SECONDS);
const stop = new AbortController();
const stopped = resolveProxy(projectDir, sourcePath, "h264", undefined, {
signal: stop.signal,
onProgress: ({ doneSeconds }) => doneSeconds >= LONG_SECONDS && stop.abort(),
}).catch((error: unknown) => error);
expect(await stopped).toBe(stop.signal.reason);
const cache = join(projectDir, ".transcode-cache");
const last = readdirSync(cache).find((name) => /^\.part-.*-2\.mp4$/.test(name))!;
spoil(join(cache, last));
const proxyPath = await resolveProxy(projectDir, sourcePath);
const picture = probeJson(proxyPath, "stream=codec_type,duration").streams.find(
(s: { codec_type: string }) => s.codec_type === "video",
);
expect(Number(picture.duration)).toBeCloseTo(LONG_SECONDS, 0);
},
60_000,
);
it.skipIf(!realFfmpeg || !findFfBinary("ffprobe"))( it.skipIf(!realFfmpeg || !findFfBinary("ffprobe"))(
"keeps a whole copy when a track it leaves out runs longer than the picture", "keeps a whole copy when a track it leaves out runs longer than the picture",
async () => { async () => {
@@ -611,7 +611,13 @@ async function encodeInChunks(
const extension = extname(tempPath); const extension = extname(tempPath);
const pieces = ranges.map((_, index) => `${chunks.prefix}${index}${extension}`); const pieces = ranges.map((_, index) => `${chunks.prefix}${index}${extension}`);
const madeAsPlainFile = (piece: string) => isProjectCacheFile(chunks.projectDir, piece); const madeAsPlainFile = (piece: string) => isProjectCacheFile(chunks.projectDir, piece);
const pending = ranges.flatMap((_, index) => (madeAsPlainFile(pieces[index]!) ? [] : [index])); const kept = await Promise.all(
ranges.map(async (range, index) => {
const piece = pieces[index]!;
return madeAsPlainFile(piece) && (await stillWhole(piece, range));
}),
);
const pending = ranges.flatMap((_, index) => (kept[index] ? [] : [index]));
let doneSeconds = 0; let doneSeconds = 0;
for (const [index, range] of ranges.entries()) { for (const [index, range] of ranges.entries()) {
if (!pending.includes(index)) doneSeconds += range.lengthSeconds; if (!pending.includes(index)) doneSeconds += range.lengthSeconds;
@@ -669,12 +675,27 @@ async function encodeInChunks(
), ),
); );
await concat(listPath, tempPath); await concat(listPath, tempPath);
} catch (error) {
if (signal.aborted) throw error;
removeAll(pieces);
if (pending.length === ranges.length) throw error;
return await encodeInChunks(ranges, chunks, tempPath, encode, concat, signal, gate, onDone);
} finally { } finally {
rmSync(listPath, { force: true }); rmSync(listPath, { force: true });
} }
for (const piece of pieces) if (existsSync(piece)) unlinkSync(piece); removeAll(pieces);
} }
// A piece left by an earlier run is made again if it runs short; if the join refuses one, all are.
async function stillWhole(piece: string, range: ChunkRange): Promise<boolean> {
const seconds = (await probeMediaMetadata(piece)).durationSeconds;
return seconds !== undefined && seconds >= range.lengthSeconds - 1;
}
const removeAll = (paths: string[]) => {
for (const path of paths) if (existsSync(path)) unlinkSync(path);
};
const KEYFRAME_EVERY_SECOND_ARGS = ["-force_key_frames", "expr:gte(t,n_forced*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. // Fixed recipe; changing either array means bumping PROXY_PARAMS_VERSION.
const H264_ARGS = [ const H264_ARGS = [
@@ -862,6 +883,7 @@ type PieceCopy = {
async function copyInPieces(ranges: ChunkRange[], outputPath: string, copy: PieceCopy) { async function copyInPieces(ranges: ChunkRange[], outputPath: string, copy: PieceCopy) {
const withSound = copy.soundMap.length > 0; const withSound = copy.soundMap.length > 0;
const picturePath = withSound ? besideAsTemp(outputPath) : outputPath; const picturePath = withSound ? besideAsTemp(outputPath) : outputPath;
try {
await encodeInChunks( await encodeInChunks(
ranges, ranges,
copy.chunks, copy.chunks,
@@ -885,6 +907,9 @@ async function copyInPieces(ranges: ChunkRange[], outputPath: string, copy: Piec
copy.onDone, copy.onDone,
); );
if (withSound) await addSoundFromSource(copy, picturePath, outputPath); if (withSound) await addSoundFromSource(copy, picturePath, outputPath);
} finally {
if (withSound) rmSync(picturePath, { force: true });
}
} }
async function addSoundFromSource( async function addSoundFromSource(
@@ -924,7 +949,6 @@ async function addSoundFromSource(
); );
} finally { } finally {
rmSync(soundPath, { force: true }); rmSync(soundPath, { force: true });
rmSync(picturePath, { force: true });
} }
} }