Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/cli/src/commands/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,24 @@ describe("extractVideoFrameToBuffer", () => {
},
);

it.skipIf(noProbe)(
"prints a video's name in its warning with control characters shown as escapes",
async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-escape-"));
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
try {
const named = join(dir, "clip\u001b]0;x\u0007.mp4");
expect(await extractVideoFrameOrWarn([], named, 1)).toBeNull();
const out = warn.mock.calls.map((call) => String(call[0])).join("\n");
expect(out).toContain("clip\\x1b]0;x\\x07.mp4");
expect(out).not.toContain("\u0007");
} finally {
warn.mockRestore();
rmSync(dir, { recursive: true, force: true });
}
},
);

it.skipIf(noProbe)(
"selects exact frame times in a fragmented MP4 whose start rounds down",
async () => {
Expand Down
25 changes: 14 additions & 11 deletions packages/cli/src/commands/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ import { normalizeErrorMessage, atStep } from "../utils/errorMessage.js";
import { describeSharpLoadFailure } from "../utils/sharpLoadFailure.js";
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
import { c } from "../ui/colors.js";
import { terminalText } from "../utils/terminalText.js";
import { writeCaptureFileSync } from "../capture/captureFile.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
Expand Down Expand Up @@ -829,7 +830,7 @@ export async function frameOrWarn(
} catch (error) {
if (!(error instanceof FrameExtractError)) throw error;
warnings.push(error.message);
console.warn(` ${c.warn("⚠")} ${error.message}`);
console.warn(` ${c.warn("⚠")} ${terminalText(error.message)}`);
return null;
}
}
Expand Down Expand Up @@ -1010,7 +1011,7 @@ export async function captureSnapshots(
: null;
if (swallowed) {
warnings.push(swallowed);
console.warn(` ${c.warn("⚠")} ${swallowed}`);
console.warn(` ${c.warn("⚠")} ${terminalText(swallowed)}`);
}
const server = await serveCapturePage(projectDir, html, opts.autoProxy);
const fps = compositionFps(html);
Expand Down Expand Up @@ -1074,7 +1075,7 @@ export async function captureSnapshots(
if (fontReport.unused.length > 0) parts.push(`${fontReport.unused.length} unused`);
log(`\n ${c.dim("Fonts:")} ${parts.join(", ")}`);
if (fontReport.errored.length > 0) {
log(` ${c.error("Fonts FAILED:")} ${fontReport.errored.join(", ")}`);
log(` ${c.error("Fonts FAILED:")} ${terminalText(fontReport.errored.join(", "))}`);
}
}

Expand Down Expand Up @@ -1226,7 +1227,7 @@ export async function captureSnapshots(
if (project?.refused) {
const message = `${relative(projectDir, project.file)} is not media: a document, a pipe or device, or a playlist naming files outside its folder`;
warnings.push(message);
console.warn(` ${c.warn("⚠")} ${message}`);
console.warn(` ${c.warn("⚠")} ${terminalText(message)}`);
}
return project;
});
Expand Down Expand Up @@ -1630,7 +1631,7 @@ function warnUnsettledImages(images: UnsettledImages, time: number, warnings: st
if (sources.length === 0) continue;
const message = `${sources.length} image(s) ${what} at ${time}s, so the frame may be missing them: ${sources.join(", ")}`;
warnings.push(message);
console.warn(` ${c.warn("⚠")} ${message}`);
console.warn(` ${c.warn("⚠")} ${terminalText(message)}`);
}
}

Expand Down Expand Up @@ -1747,19 +1748,19 @@ function printReview(
log: (message: string) => void,
): void {
const beats = review.plan.beats.map(
(beat) => `${formatSnapshotTimestamp(beat.time)} ${beat.label}`,
(beat) => `${formatSnapshotTimestamp(beat.time)} ${terminalText(beat.label)}`,
);
log(` Beat sheet (settled frame per scene): ${sheets.beats.join(", ") || "none"}`);
log(` ${c.dim(beats.join(" · "))}`);
review.plan.seams.forEach((seam, index) => {
const sides = `${seam.from ?? "start"} -> ${seam.to ?? "end"}`;
const sides = terminalText(`${seam.from ?? "start"} -> ${seam.to ?? "end"}`);
const strip = sheets.seams[index] ?? "not written";
log(` Seam ${index + 1} at ${formatSnapshotTimestamp(seam.time)} (${sides}): ${strip}`);
});
log(
` Phone sheet (beats at ${REVIEW_PHONE_WIDTH} px wide): ${sheets.phone.join(", ") || "none"}`,
);
for (const note of review.plan.notes) log(` ${c.dim(note)}`);
for (const note of review.plan.notes) log(` ${c.dim(terminalText(note))}`);
}

export default defineCommand({
Expand Down Expand Up @@ -1941,7 +1942,9 @@ export default defineCommand({
camera && (camera.yaw !== 0 || camera.pitch !== 0)
? ` ${c.dim(`(angle yaw ${camera.yaw}° pitch ${camera.pitch}°)`)}`
: "";
log(`${c.accent("◆")} Capturing ${label} from ${c.accent(project.name)}${angleLabel}`);
log(
`${c.accent("◆")} Capturing ${label} from ${c.accent(terminalText(project.name))}${angleLabel}`,
);

let managedSnapshotDir: string | undefined;
let exitCode = 0;
Expand Down Expand Up @@ -2133,7 +2136,7 @@ export default defineCommand({
}
} catch (descErr) {
const msg = normalizeErrorMessage(descErr);
log(` ${c.dim(`--describe failed: ${msg}`)}`);
log(` ${c.dim(`--describe failed: ${terminalText(msg)}`)}`);
}
}
if (asJson) {
Expand All @@ -2151,7 +2154,7 @@ export default defineCommand({
if (err instanceof CliRuntimeError && err.result.presented) throw err;
const msg = failureMessage(err);
if (asJson) console.log(JSON.stringify(withMeta(jsonFailure("runtime_error", msg)), null, 2));
else console.error(`\n${c.error("✗")} Snapshot failed: ${msg}`);
else console.error(`\n${c.error("✗")} Snapshot failed: ${terminalText(msg)}`);
failCommand();
} finally {
if (managedSnapshotDir)
Expand Down
27 changes: 27 additions & 0 deletions packages/studio-server/src/helpers/proxyTranscoder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2034,6 +2034,33 @@ describe("resolveStill", () => {
60_000,
);

it.skipIf(!canStill)(
"sweeps the cache when it makes a still, so stills alone cannot grow it without bound",
async () => {
vi.resetModules();
vi.doUnmock("./mediaMetadata.js");
const { resolveStill, CACHE_DIR_NAME } = await import("./proxyTranscoder.js");
const projectDir = tmpProject();
const clip = join(projectDir, "clip.mp4");
execFileSync(realFfmpeg!, [
...["-v", "error", "-f", "lavfi", "-i", "testsrc2=s=320x180:r=25:d=2"],
...["-c:v", "libx264", "-pix_fmt", "yuv420p", clip],
]);
const cacheDir = join(projectDir, CACHE_DIR_NAME);
mkdirSync(cacheDir, { recursive: true });
const idle = join(cacheDir, `${"a".repeat(64)}.jpg`);
writeFileSync(idle, "old still");
const longAgo = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000);
utimesSync(idle, longAgo, longAgo);

const made = await resolveStill(projectDir, clip, 1);

expect(existsSync(made)).toBe(true);
expect(existsSync(idle)).toBe(false);
},
60_000,
);

async function stillSetup() {
const spy = createSpawnSpy();
const { resolveStill } = await loadModule(spy.spawn, FFMPEG_PATH);
Expand Down
13 changes: 10 additions & 3 deletions packages/studio-server/src/helpers/proxyTranscoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,11 @@ function forget(job: ProxyJob): void {
if (inFlight.get(job.cachePath)?.job === job) inFlight.delete(job.cachePath);
}

function maintainProxyCache(cacheDir: string, staleTempMs?: number): void {
function maintainProxyCache(cacheDir: string, staleTempMs?: number, justServed?: string): void {
const protectedPaths = new Set([...inFlight.keys(), ...stillsInFlight.keys()]);
if (justServed) protectedPaths.add(justServed);
try {
cleanupProxyCache(cacheDir, { protectedPaths: new Set(inFlight.keys()), staleTempMs });
cleanupProxyCache(cacheDir, { protectedPaths, staleTempMs });
} catch (error) {
// Cache maintenance must never turn a playable preview into an error.
console.warn(
Expand Down Expand Up @@ -1169,7 +1171,11 @@ export function resolveStill(
const at = Math.max(0, Math.round(atSeconds * 10) / 10);
const key = fastCopyKey(source.sourcePath, PROXY_PARAMS_VERSION, `still@${at}`, box);
const cachePath = join(source.projectDir, CACHE_DIR_NAME, `${key}${PROXY_STILL_EXTENSION}`);
if (existsSync(cachePath)) return Promise.resolve(cachePath);
if (existsSync(cachePath)) {
markCacheEntryUsed(cachePath);
maintainProxyCache(dirname(cachePath), undefined, cachePath);
return Promise.resolve(cachePath);
}
let job = stillsInFlight.get(cachePath);
if (!job) {
const abandoned = new AbortController();
Expand Down Expand Up @@ -1235,6 +1241,7 @@ async function makeStill(
} finally {
rmSync(tempPath, { force: true });
}
maintainProxyCache(dirname(cachePath), undefined, cachePath);
return cachePath;
}

Expand Down
4 changes: 2 additions & 2 deletions scripts/package-size-budgets.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
"unpacked": 26703858
},
"@hyperframes/studio-server": {
"packed": 172000,
"unpacked": 672000
"packed": 173500,
"unpacked": 676000
}
}
Loading