Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Preset covers: larger copies for wide cards and high-density screens

Adarsh01ac79bfe950
diff --git a/public/previews/presets/hd/1024/app-packshot.avif b/public/previews/presets/hd/1024/app-packshot.avif
new file mode 100644
index 00000000..5867c344
Binary files /dev/null and b/public/previews/presets/hd/1024/app-packshot.avif differ
diff --git a/public/previews/presets/hd/1024/app-packshot.jpg b/public/previews/presets/hd/1024/app-packshot.jpg
new file mode 100644
index 00000000..722583cd
Binary files /dev/null and b/public/previews/presets/hd/1024/app-packshot.jpg differ
diff --git a/public/previews/presets/hd/1024/app-packshot.mp4 b/public/previews/presets/hd/1024/app-packshot.mp4
new file mode 100644
index 00000000..6219c5c8
Binary files /dev/null and b/public/previews/presets/hd/1024/app-packshot.mp4 differ
diff --git a/public/previews/presets/hd/1024/app-product-shot.avif b/public/previews/presets/hd/1024/app-product-shot.avif
new file mode 100644
index 00000000..8da83fd6
Binary files /dev/null and b/public/previews/presets/hd/1024/app-product-shot.avif differ
diff --git a/public/previews/presets/hd/1024/app-product-shot.jpg b/public/previews/presets/hd/1024/app-product-shot.jpg
new file mode 100644
index 00000000..9927182c
Binary files /dev/null and b/public/previews/presets/hd/1024/app-product-shot.jpg differ
diff --git a/public/previews/presets/hd/1024/app-product-shot.mp4 b/public/previews/presets/hd/1024/app-product-shot.mp4
new file mode 100644
index 00000000..642f82b3
Binary files /dev/null and b/public/previews/presets/hd/1024/app-product-shot.mp4 differ
diff --git a/public/previews/presets/hd/1024/peak/app-packshot.avif b/public/previews/presets/hd/1024/peak/app-packshot.avif
new file mode 100644
index 00000000..8187e293
Binary files /dev/null and b/public/previews/presets/hd/1024/peak/app-packshot.avif differ
diff --git a/public/previews/presets/hd/1024/peak/app-packshot.jpg b/public/previews/presets/hd/1024/peak/app-packshot.jpg
new file mode 100644
index 00000000..ee7b0724
Binary files /dev/null and b/public/previews/presets/hd/1024/peak/app-packshot.jpg differ
diff --git a/public/previews/presets/hd/1024/peak/app-product-shot.avif b/public/previews/presets/hd/1024/peak/app-product-shot.avif
new file mode 100644
index 00000000..18098182
Binary files /dev/null and b/public/previews/presets/hd/1024/peak/app-product-shot.avif differ
diff --git a/public/previews/presets/hd/1024/peak/app-product-shot.jpg b/public/previews/presets/hd/1024/peak/app-product-shot.jpg
new file mode 100644
index 00000000..eb048054
Binary files /dev/null and b/public/previews/presets/hd/1024/peak/app-product-shot.jpg differ
diff --git a/public/previews/presets/hd/320/app-packshot.avif b/public/previews/presets/hd/320/app-packshot.avif
new file mode 100644
index 00000000..fde65204
Binary files /dev/null and b/public/previews/presets/hd/320/app-packshot.avif differ
diff --git a/public/previews/presets/hd/320/app-product-shot.avif b/public/previews/presets/hd/320/app-product-shot.avif
new file mode 100644
index 00000000..fa826053
Binary files /dev/null and b/public/previews/presets/hd/320/app-product-shot.avif differ
diff --git a/public/previews/presets/hd/320/peak/app-packshot.avif b/public/previews/presets/hd/320/peak/app-packshot.avif
new file mode 100644
index 00000000..e519eaa8
Binary files /dev/null and b/public/previews/presets/hd/320/peak/app-packshot.avif differ
diff --git a/public/previews/presets/hd/320/peak/app-product-shot.avif b/public/previews/presets/hd/320/peak/app-product-shot.avif
new file mode 100644
index 00000000..71fa276d
Binary files /dev/null and b/public/previews/presets/hd/320/peak/app-product-shot.avif differ
diff --git a/public/previews/presets/hd/640/app-packshot.avif b/public/previews/presets/hd/640/app-packshot.avif
new file mode 100644
index 00000000..5d5029ab
Binary files /dev/null and b/public/previews/presets/hd/640/app-packshot.avif differ
diff --git a/public/previews/presets/hd/640/app-packshot.jpg b/public/previews/presets/hd/640/app-packshot.jpg
new file mode 100644
index 00000000..e7de58a1
Binary files /dev/null and b/public/previews/presets/hd/640/app-packshot.jpg differ
diff --git a/public/previews/presets/hd/640/app-packshot.mp4 b/public/previews/presets/hd/640/app-packshot.mp4
new file mode 100644
index 00000000..c09298d4
Binary files /dev/null and b/public/previews/presets/hd/640/app-packshot.mp4 differ
diff --git a/public/previews/presets/hd/640/app-product-shot.avif b/public/previews/presets/hd/640/app-product-shot.avif
new file mode 100644
index 00000000..cbb2518d
Binary files /dev/null and b/public/previews/presets/hd/640/app-product-shot.avif differ
diff --git a/public/previews/presets/hd/640/app-product-shot.jpg b/public/previews/presets/hd/640/app-product-shot.jpg
new file mode 100644
index 00000000..2d0e1938
Binary files /dev/null and b/public/previews/presets/hd/640/app-product-shot.jpg differ
diff --git a/public/previews/presets/hd/640/app-product-shot.mp4 b/public/previews/presets/hd/640/app-product-shot.mp4
new file mode 100644
index 00000000..b316fc53
Binary files /dev/null and b/public/previews/presets/hd/640/app-product-shot.mp4 differ
diff --git a/public/previews/presets/hd/640/peak/app-packshot.avif b/public/previews/presets/hd/640/peak/app-packshot.avif
new file mode 100644
index 00000000..d24a0dd2
Binary files /dev/null and b/public/previews/presets/hd/640/peak/app-packshot.avif differ
diff --git a/public/previews/presets/hd/640/peak/app-packshot.jpg b/public/previews/presets/hd/640/peak/app-packshot.jpg
new file mode 100644
index 00000000..e8bef5ae
Binary files /dev/null and b/public/previews/presets/hd/640/peak/app-packshot.jpg differ
diff --git a/public/previews/presets/hd/640/peak/app-product-shot.avif b/public/previews/presets/hd/640/peak/app-product-shot.avif
new file mode 100644
index 00000000..2aee2117
Binary files /dev/null and b/public/previews/presets/hd/640/peak/app-product-shot.avif differ
diff --git a/public/previews/presets/hd/640/peak/app-product-shot.jpg b/public/previews/presets/hd/640/peak/app-product-shot.jpg
new file mode 100644
index 00000000..2772a4b7
Binary files /dev/null and b/public/previews/presets/hd/640/peak/app-product-shot.jpg differ
diff --git a/scripts/eval/lib/covers.mjs b/scripts/eval/lib/covers.mjs
index 514486c0..d94ef628 100644
--- a/scripts/eval/lib/covers.mjs
+++ b/scripts/eval/lib/covers.mjs
@@ -324,6 +324,40 @@ export function dissolveBack(frames, fade) {
return out;
}
+/** An ffmpeg scale filter that fits a picture within `px` on its longest side, never enlarging it. */
+const fit = (px) => `scale='if(gt(iw,ih),min(${px},iw),-2)':'if(gt(iw,ih),-2,min(${px},ih))'`;
+
+/**
+ * A cover clip's frames, cut and looped as encode() cuts them (its `opts`), decoded through `scale` (an ffmpeg filter:
+ * the published clip's fit(CLIP_PX), or a larger copy's width), so a copy of any size has the same frames at the same
+ * times. `rest` is the index of the frame a card rests on (a reveal's last, or the frame at `rest` seconds), or null
+ * when its poster is its first frame; `stream` turns frames back into a y4m stream.
+ * @param {string} src
+ * @param {{ rest?: "start" | "end" | number, length?: "full" }} opts
+ * @param {string} scale
+ */
+export function coverLoop(src, opts, scale) {
+ const atEnd = opts.rest === "end";
+ // A clip that rests on a moment of its own (seconds): kept whole, like a reveal, with that frame its poster.
+ const atTime = typeof opts.rest === "number" && opts.rest >= 0 ? opts.rest : null;
+ const whole = atEnd || atTime !== null;
+ // How much of the clip its loop keeps: the first CLIP_SECONDS, or all of it (up to REST_CLIP_SECONDS).
+ const full = opts.length === "full";
+ const keep = full ? REST_CLIP_SECONDS : CLIP_SECONDS;
+ // Decoded at CLIP_FPS: what it keeps, plus the frames the crossfade takes back from the start (a reveal or a full
+ // clip: all of it, as a full clip's dissolve is added after its end).
+ const seconds = whole || full ? REST_CLIP_SECONDS : keep + LOOP_FADE / CLIP_FPS;
+ const y4m = run(["-i", src, "-t", String(seconds), "-an", "-sn", "-dn", "-vf", `${scale},fps=${CLIP_FPS},format=yuv420p`, "-f", "yuv4mpegpipe", "-"]);
+ const { header, frames, luma } = readY4m(y4m);
+ if (frames.length < 2) throw new Error(`${src} has no frames to make a clip of`);
+ const cut = frames.slice(0, keep * CLIP_FPS);
+ const fade = Math.min(LOOP_FADE, Math.floor(frames.length / 4));
+ const looped = whole ? frames : loopsAlready(cut, luma) ? cut : full ? dissolveBack(cut, fade) : seamless(frames, fade);
+ const stream = (list) => Buffer.concat([Buffer.from(`${header}\n`, "latin1"), ...list.flatMap((fr) => [Buffer.from("FRAME\n"), fr])]);
+ const rest = !whole ? null : atEnd ? looped.length - 1 : Math.min(looped.length - 1, Math.round(atTime * CLIP_FPS));
+ return { looped, rest, stream };
+}
+
/**
* A still at most STILL_PX wide/tall (a 4:2:0 JPEG), or a clip's first seconds at most CLIP_PX that loops
* without a jump (crossfaded, unless it loops already), with its first frame as the poster.
@@ -343,30 +377,12 @@ export function dissolveBack(frames, fade) {
* @returns {{ poster: string, video?: string, at?: number }}
*/
export function encode(src, kind, destBase, opts = {}) {
- const fit = (px) => `scale='if(gt(iw,ih),min(${px},iw),-2)':'if(gt(iw,ih),-2,min(${px},ih))'`;
if (kind === "video") {
- const atEnd = opts.rest === "end";
- // A clip that rests on a moment of its own (seconds): kept whole, like a reveal, with that frame its poster.
- const atTime = typeof opts.rest === "number" && opts.rest >= 0 ? opts.rest : null;
- const whole = atEnd || atTime !== null;
- // How much of the clip its loop keeps: the first CLIP_SECONDS, or all of it (up to REST_CLIP_SECONDS).
- const full = opts.length === "full";
- const keep = full ? REST_CLIP_SECONDS : CLIP_SECONDS;
- // Decoded at CLIP_FPS: what it keeps, plus the frames the crossfade takes back from the start (a reveal or a full
- // clip: all of it, as a full clip's dissolve is added after its end).
- const seconds = whole || full ? REST_CLIP_SECONDS : keep + LOOP_FADE / CLIP_FPS;
- const y4m = run(["-i", src, "-t", String(seconds), "-an", "-sn", "-dn", "-vf", `${fit(CLIP_PX)},fps=${CLIP_FPS},format=yuv420p`, "-f", "yuv4mpegpipe", "-"]);
- const { header, frames, luma } = readY4m(y4m);
- if (frames.length < 2) throw new Error(`${src} has no frames to make a clip of`);
- const cut = frames.slice(0, keep * CLIP_FPS);
- const fade = Math.min(LOOP_FADE, Math.floor(frames.length / 4));
- const looped = whole ? frames : loopsAlready(cut, luma) ? cut : full ? dissolveBack(cut, fade) : seamless(frames, fade);
- const stream = (list) => Buffer.concat([Buffer.from(`${header}\n`, "latin1"), ...list.flatMap((fr) => [Buffer.from("FRAME\n"), fr])]);
+ const { looped, rest, stream } = coverLoop(src, opts, fit(CLIP_PX));
run(["-f", "yuv4mpegpipe", "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-map_metadata", "-1", "-movflags", "+faststart", `${destBase}.mp4`], stream(looped));
- if (whole) {
- const i = atEnd ? looped.length - 1 : Math.min(looped.length - 1, Math.round(atTime * CLIP_FPS));
- run(["-f", "yuv4mpegpipe", "-i", "-", "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`], stream([looped[i]]));
- return { poster: `${destBase}.jpg`, video: `${destBase}.mp4`, at: Math.round((i / CLIP_FPS) * 1000) / 1000 };
+ if (rest !== null) {
+ run(["-f", "yuv4mpegpipe", "-i", "-", "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`], stream([looped[rest]]));
+ return { poster: `${destBase}.jpg`, video: `${destBase}.mp4`, at: Math.round((rest / CLIP_FPS) * 1000) / 1000 };
}
run(["-i", `${destBase}.mp4`, "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`]);
return { poster: `${destBase}.jpg`, video: `${destBase}.mp4` };
diff --git a/scripts/gen-preset-hd.mjs b/scripts/gen-preset-hd.mjs
new file mode 100644
index 00000000..a853d743
--- /dev/null
+++ b/scripts/gen-preset-hd.mjs
@@ -0,0 +1,198 @@
+#!/usr/bin/env node
+/**
+ * Larger copies of preset covers, for boxes wider than the 512 px clip and still (a starter card, a preset header, a
+ * 2x or 3x screen): the clip, its poster and its peak frame at more widths, made from the render the published cover
+ * was cut from rather than enlarged from the 512 px copy.
+ *
+ * Input: a masters folder with a folder per preset id holding clip.mp4 (the render) and, as pnpm eval:covers reads
+ * it, an optional meta.json (`{"length": "full"}`). The clip is cut and looped as the published one (coverLoop in
+ * scripts/eval/lib/covers.mjs), so every copy has the same frames at the same times.
+ *
+ * Output, for each width W in CLIP_WIDTHS up to the render's own width:
+ * public/previews/presets/hd/<W>/<id>.mp4 H.264 High, BT.709 tags, its index at the front
+ * public/previews/presets/hd/<W>/<id>.avif, .jpg the poster: the clip's first frame (or the frame it rests on)
+ * public/previews/presets/hd/<W>/peak/<id>.avif, .jpg the peak frame (preset-peaks.generated.ts), when it has one
+ * and AVIF copies of both stills at SMALL_PX (hd/320/), so a small tile on a browser that takes AVIF stays small.
+ * src/lib/preset-hd.generated.ts { "<id>": { w: [<widths>], v: "<version>" } }
+ * The stills are decoded from the encoded clip the way a browser shows it, so the swap from still to clip can't be seen.
+ *
+ * Check: before anything is written, each poster and peak is compared with the published 512 px one (the mean
+ * difference of 128x96 grey copies, at most MATCH): a copy that doesn't show what the card shows fails the run.
+ *
+ * A render no wider than 512 px has nothing to add: the run lists it as needing a new render and goes on.
+ *
+ * Run: node scripts/gen-preset-hd.mjs --masters <dir> <id> … make these
+ * node scripts/gen-preset-hd.mjs -<id> … take these out, with their files
+ * node scripts/gen-preset-hd.mjs --versions hash only
+ * --dry-run makes and checks, and writes nothing.
+ * Needs ffmpeg on PATH (or FUOBE_FFMPEG).
+ */
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import sharp from "sharp";
+import { CLIP_FPS, contentVersion, coverLoop } from "./eval/lib/covers.mjs";
+
+const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
+const PRESETS = path.join(ROOT, "public", "previews", "presets");
+const OUT_DIR = path.join(PRESETS, "hd");
+const OUT_TS = path.join(ROOT, "src", "lib", "preset-hd.generated.ts");
+const PEAKS_TS = path.join(ROOT, "src", "lib", "preset-peaks.generated.ts");
+/** The copies' widths (4:3): a 440 px card on a 2x screen takes 1024, a phone's half-width tile 640. */
+const CLIP_WIDTHS = [640, 1024];
+/** The small AVIF stills' width, as the JPEG thumbs' (thumbOf). */
+const SMALL_PX = 320;
+/** The published copies' width: a render no wider has nothing to add. */
+const PUBLISHED_PX = 512;
+/** CRF per width: the larger copy is seen larger, so it keeps more. */
+const CRF = { 640: 24, 1024: 23 };
+const AVIF_QUALITY = 62;
+const JPEG_QUALITY = 82;
+/** How far (of 255) a copy may differ from the published still, on average: another frame is 10 and more. */
+const MATCH = 6;
+/** The colours every clip is tagged with (libx264 takes them as its own options): its stills are decoded the same way. */
+const BT709 = ["-x264-params", "colorprim=bt709:transfer=bt709:colormatrix=bt709", "-color_range", "tv"];
+
+const argv = process.argv.slice(2);
+const DRY = argv.includes("--dry-run");
+const mastersAt = argv.indexOf("--masters");
+const MASTERS = mastersAt >= 0 ? argv[mastersAt + 1] : undefined;
+const named = argv.filter((a, i) => !a.startsWith("--") && (mastersAt < 0 || i !== mastersAt + 1));
+
+const tool = (name, args, input) => {
+ const r = spawnSync(process.env[name === "ffmpeg" ? "FUOBE_FFMPEG" : "FUOBE_FFPROBE"] ?? name, args, { input, maxBuffer: 1 << 30 });
+ if (r.error?.code === "ENOENT") throw new Error(`gen-preset-hd needs ${name} on PATH`);
+ if (r.status !== 0) throw new Error(`${name} failed: ${String(r.stderr).trim().split("\n").at(-1)}`);
+ return r.stdout;
+};
+
+const readTs = (file) => {
+ if (!fs.existsSync(file)) return {};
+ const text = fs.readFileSync(file, "utf8");
+ return JSON.parse(text.slice(text.indexOf("= {") + 2, text.lastIndexOf("}") + 1));
+};
+
+const rel = (w, id, ext, peak = false) => path.join(OUT_DIR, String(w), ...(peak ? ["peak"] : []), `${id}.${ext}`);
+
+/** Every file an entry has, in a fixed order (its version is theirs). */
+function filesOf(id, entry, hasPeak) {
+ const out = [];
+ for (const w of entry.w) out.push(rel(w, id, "mp4"), rel(w, id, "avif"), rel(w, id, "jpg"), ...(hasPeak ? [rel(w, id, "avif", true), rel(w, id, "jpg", true)] : []));
+ out.push(rel(SMALL_PX, id, "avif"), ...(hasPeak ? [rel(SMALL_PX, id, "avif", true)] : []));
+ return out;
+}
+
+/** The render's width. */
+const widthOf = (file) => Number(String(tool("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width", "-of", "csv=p=0", file])).trim());
+
+/** Frame `n` of an encoded clip as a PNG, decoded as a browser shows it (BT.709, limited range). */
+const frameOf = (file, n) =>
+ tool("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${n}),scale=in_color_matrix=bt709:in_range=tv:flags=accurate_rnd+full_chroma_int+lanczos,format=rgb24`, "-frames:v", "1", "-c:v", "png", "-f", "image2pipe", "-"]);
+
+/** Mean difference (of 255) between two pictures' 128x96 grey copies. */
+async function gap(a, b) {
+ const grey = (x) => sharp(x).resize(128, 96, { fit: "fill" }).greyscale().raw().toBuffer();
+ const [p, q] = await Promise.all([grey(a), grey(b)]);
+ let sum = 0;
+ for (let i = 0; i < p.length; i++) sum += Math.abs(p[i] - q[i]);
+ return sum / p.length;
+}
+
+function readMeta(folder) {
+ try {
+ return JSON.parse(fs.readFileSync(path.join(folder, "meta.json"), "utf8")) ?? {};
+ } catch {
+ return {};
+ }
+}
+
+const hd = readTs(OUT_TS);
+const peaks = readTs(PEAKS_TS);
+const reRender = [];
+
+async function make(id) {
+ if (!MASTERS) throw new Error(`${id}: copies are made from the renders: run with --masters <dir>`);
+ const folder = path.join(MASTERS, id);
+ const src = path.join(folder, "clip.mp4");
+ if (!fs.existsSync(src)) throw new Error(`${id}: no ${src}`);
+ const own = widthOf(src);
+ if (own <= PUBLISHED_PX) {
+ reRender.push(`${id} (its render is ${own} px wide)`);
+ return;
+ }
+ const widths = [...new Set(CLIP_WIDTHS.map((w) => Math.min(w, own)))].filter((w) => w > PUBLISHED_PX);
+ const meta = readMeta(folder);
+ const opts = meta.length === "full" ? { length: "full" } : {};
+ const peak = peaks[id];
+ const published = { poster: path.join(PRESETS, `${id}.jpg`), peak: path.join(PRESETS, "peak", `${id}.jpg`) };
+ const made = new Map();
+ let largest;
+ for (const w of widths) {
+ const { looped, rest, stream } = coverLoop(src, opts, `scale=${w}:-2:flags=lanczos`);
+ const tmp = path.join(os.tmpdir(), `gen-preset-hd-${process.pid}-${w}.mp4`);
+ try {
+ tool("ffmpeg", ["-v", "error", "-y", "-f", "yuv4mpegpipe", "-i", "-", "-an", "-c:v", "libx264", "-profile:v", "high", "-preset", "slow", "-tune", "film", "-crf", String(CRF[w] ?? 23), "-g", String(2 * CLIP_FPS), "-pix_fmt", "yuv420p", ...BT709, "-map_metadata", "-1", "-movflags", "+faststart", tmp], stream(looped));
+ made.set(rel(w, id, "mp4"), fs.readFileSync(tmp));
+ const stills = [{ kind: "poster", n: rest ?? 0 }, ...(peak ? [{ kind: "peak", n: Math.round(peak.at * CLIP_FPS - 0.5) }] : [])];
+ for (const s of stills) {
+ const png = frameOf(tmp, s.n);
+ const d = await gap(png, published[s.kind]);
+ console.log(`${id} ${w} ${s.kind} (frame ${s.n}): differs ${d.toFixed(2)} from the published one`);
+ if (d > MATCH) throw new Error(`${id}: its ${w} px ${s.kind} differs ${d.toFixed(2)} (> ${MATCH}) from the published one: check the render`);
+ const peakSide = s.kind === "peak";
+ made.set(rel(w, id, "avif", peakSide), await sharp(png).avif({ quality: AVIF_QUALITY, effort: 6 }).toBuffer());
+ made.set(rel(w, id, "jpg", peakSide), await sharp(png).jpeg({ quality: JPEG_QUALITY, mozjpeg: true }).toBuffer());
+ if (w === widths.at(-1)) largest = { ...(largest ?? {}), [s.kind]: png };
+ }
+ } finally {
+ fs.rmSync(tmp, { force: true });
+ }
+ }
+ for (const [kind, png] of Object.entries(largest)) made.set(rel(SMALL_PX, id, "avif", kind === "peak"), await sharp(png).resize(SMALL_PX).avif({ quality: AVIF_QUALITY, effort: 6 }).toBuffer());
+ for (const [file, buf] of made) {
+ console.log(` ${path.relative(PRESETS, file).split(path.sep).join("/")} ${(buf.length / 1024).toFixed(1)} KB`);
+ if (DRY) continue;
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, buf);
+ }
+ if (!DRY) hd[id] = { w: widths };
+}
+
+for (const arg of named) {
+ if (arg.startsWith("-")) {
+ const id = arg.slice(1);
+ if (hd[id] && !DRY) for (const f of filesOf(id, hd[id], true)) fs.rmSync(f, { force: true });
+ delete hd[id];
+ console.log(`${id}: taken out`);
+ continue;
+ }
+ await make(arg);
+}
+if (reRender.length) console.log(`needs a new render (nothing larger than ${PUBLISHED_PX} px): ${reRender.join(", ")}`);
+
+if (!DRY) {
+ const sorted = Object.entries(hd)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([id, e]) => {
+ const files = filesOf(id, e, Boolean(peaks[id]));
+ const missing = files.filter((f) => !fs.existsSync(f));
+ if (missing.length) throw new Error(`${id}: ${missing.length} of its copies are missing (${path.relative(ROOT, missing[0])}): make it again, or take it out with -${id}`);
+ return [id, { w: e.w, v: contentVersion(files) }];
+ });
+ fs.writeFileSync(
+ OUT_TS,
+ `/**
+ * Larger copies of preset covers (public/previews/presets/hd/<w>/): the clip, its poster and its peak frame at each
+ * width in \`w\` (H.264; AVIF and JPEG stills), and AVIF stills at 320 px. \`v\` is the content version every copy's URL
+ * ends in (?v=), so copies made again get new URLs. Read through src/lib/preset-hd.ts. Generated by
+ * scripts/gen-preset-hd.mjs: run it again rather than editing.
+ */
+export const PRESET_HD: Record<string, { w: number[]; v: string }> = {
+${sorted.map(([id, e]) => ` ${JSON.stringify(id)}: { "w": ${JSON.stringify(e.w)}, "v": ${JSON.stringify(e.v)} }`).join(",\n")}
+};
+`,
+ );
+ console.log(`wrote ${sorted.length} entries`);
+}
diff --git a/src/components/preset-preview.tsx b/src/components/preset-preview.tsx
index 9506530e..fd575ece 100644
--- a/src/components/preset-preview.tsx
+++ b/src/components/preset-preview.tsx
@@ -17,8 +17,10 @@ import {
type PreviewScene,
} from "@/lib/preset-cards";
import { coverFraming } from "@/lib/cover-framing";
+import { coverWidth, pickWidth } from "@/lib/media-pick";
import { releaseVideo } from "@/lib/media-release";
import { glyphFor } from "@/lib/move-glyphs";
+import { presetClipCopies, presetStillSources } from "@/lib/preset-hd";
import { autoplays, browserPlaybackEnv, createPlaybackStore, playsWhenAsked, previewKind, untilPlace, type AutoPlay } from "@/lib/preview-playback";
import { cn } from "@/lib/utils";
@@ -280,6 +282,9 @@ function Fx({ fx, scene }: { fx: NonNullable<Preview["fx"]>; scene: PreviewScene
}
}
+/** The cover clips' shape (width / height): every one is 4:3. */
+const CLIP_ASPECT = 4 / 3;
+
/** When the clips' shared cycle began (performance.now()), set by the first clip ready to play by itself (Clip). */
let cycleStart: number | undefined;
@@ -311,7 +316,8 @@ function Clip({ src, rest, asked, place, focus }: { src: string; rest?: Preview[
useLayoutEffect(() => {
const v = ref.current;
if (!v) return;
- v.src = src;
+ // The narrowest copy at least as wide as the box shows it on this screen (preset-hd.ts; most clips have one).
+ v.src = pickWidth(presetClipCopies(src), coverWidth(v.clientWidth, v.clientHeight, CLIP_ASPECT, window.devicePixelRatio || 1)).src;
void v.play().catch(() => {});
return () => {
releaseVideo(v);
@@ -400,24 +406,36 @@ export const PresetPreview = memo(function PresetPreview({
// How the cover sits in a frame of another shape (cover-framing.ts): a focus point, or the whole picture.
const framing = coverFraming(still);
const focus = framing?.focus;
+ // Larger copies (preset-hd.ts), where the cover has them: the box takes one at least as wide as it shows.
+ const hd = sizes ? presetStillSources(still, thumbOf(still)) : undefined;
+ const img = (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={still}
+ srcSet={hd ? hd.jpeg : sizes ? `${thumbOf(still)} 320w, ${still} 512w` : undefined}
+ sizes={sizes}
+ alt=""
+ width={512}
+ height={384}
+ draggable={false}
+ loading={loading}
+ fetchPriority={fetchPriority}
+ decoding={fetchPriority ? undefined : "async"}
+ className="absolute inset-0 size-full object-cover"
+ style={focus ? { objectPosition: focus } : undefined}
+ aria-hidden
+ />
+ );
const cover = (
<>
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={still}
- srcSet={sizes ? `${thumbOf(still)} 320w, ${still} 512w` : undefined}
- sizes={sizes}
- alt=""
- width={512}
- height={384}
- draggable={false}
- loading={loading}
- fetchPriority={fetchPriority}
- decoding={fetchPriority ? undefined : "async"}
- className="absolute inset-0 size-full object-cover"
- style={focus ? { objectPosition: focus } : undefined}
- aria-hidden
- />
+ {hd ? (
+ <picture>
+ <source type="image/avif" srcSet={hd.avif} sizes={sizes} />
+ {img}
+ </picture>
+ ) : (
+ img
+ )}
{preview.video && playing && <Clip src={preview.video} rest={preview.rest} asked={asked} place={place} focus={focus} />}
</>
);
diff --git a/src/lib/preset-hd.generated.ts b/src/lib/preset-hd.generated.ts
new file mode 100644
index 00000000..587e3212
--- /dev/null
+++ b/src/lib/preset-hd.generated.ts
@@ -0,0 +1,10 @@
+/**
+ * Larger copies of preset covers (public/previews/presets/hd/<w>/): the clip, its poster and its peak frame at each
+ * width in `w` (H.264; AVIF and JPEG stills), and AVIF stills at 320 px. `v` is the content version every copy's URL
+ * ends in (?v=), so copies made again get new URLs. Read through src/lib/preset-hd.ts. Generated by
+ * scripts/gen-preset-hd.mjs: run it again rather than editing.
+ */
+export const PRESET_HD: Record<string, { w: number[]; v: string }> = {
+ "app-packshot": { "w": [640,1024], "v": "93ff2132" },
+ "app-product-shot": { "w": [640,1024], "v": "01a3efb0" }
+};
diff --git a/src/lib/preset-hd.ts b/src/lib/preset-hd.ts
new file mode 100644
index 00000000..c764b302
--- /dev/null
+++ b/src/lib/preset-hd.ts
@@ -0,0 +1,53 @@
+/**
+ * The larger copies of a preset cover (preset-hd.generated.ts, made by scripts/gen-preset-hd.mjs): a cover's still or
+ * clip URL as the cards hold it (/previews/presets/<id>.jpg, /previews/presets/peak/<id>.jpg, /previews/presets/<id>.mp4)
+ * and the copies a box can choose from by its size and the screen's pixel ratio. A cover without copies has none, and
+ * its card keeps its 320 and 512 px files.
+ */
+import type { Sized } from "@/lib/media-pick";
+import { PRESET_HD } from "@/lib/preset-hd.generated";
+
+/** The published copies' width (scripts/eval/lib/covers.mjs CLIP_PX), and the small stills' (thumbOf). */
+export const PUBLISHED_PX = 512;
+export const SMALL_PX = 320;
+
+const STILL = /^\/previews\/presets\/(peak\/)?([a-z0-9-]+)\.jpg(?:\?|$)/;
+const CLIP = /^\/previews\/presets\/([a-z0-9-]+)\.mp4(?:\?|$)/;
+
+/** A still's choices for a `<picture>`: its AVIF copies, and its JPEG ones (the 320 and 512 px files first). */
+export interface StillSources {
+ avif: string;
+ jpeg: string;
+}
+
+/** The srcsets of a cover's still with larger copies, or undefined. `thumb` is its 320 px JPEG (thumbOf). */
+export function presetStillSources(still: string, thumb: string): StillSources | undefined {
+ const m = STILL.exec(still);
+ const hd = m && PRESET_HD[m[2]];
+ if (!m || !hd) return undefined;
+ const at = (w: number, ext: string) => `/previews/presets/hd/${w}/${m[1] ?? ""}${m[2]}.${ext}?v=${hd.v}`;
+ return {
+ avif: [SMALL_PX, ...hd.w].map((w) => `${at(w, "avif")} ${w}w`).join(", "),
+ jpeg: [`${thumb} ${SMALL_PX}w`, `${still} ${PUBLISHED_PX}w`, ...hd.w.map((w) => `${at(w, "jpg")} ${w}w`)].join(", "),
+ };
+}
+
+/** A cover clip's copies by width (its own 512 px file first), or just itself when it has none. */
+export function presetClipCopies(video: string): Sized[] {
+ const m = CLIP.exec(video);
+ const hd = m && PRESET_HD[m[1]];
+ if (!m || !hd) return [{ src: video, w: PUBLISHED_PX }];
+ return [{ src: video, w: PUBLISHED_PX }, ...hd.w.map((w) => ({ src: `/previews/presets/hd/${w}/${m[1]}.mp4?v=${hd.v}`, w }))];
+}
+
+/** Every copy a cover has (bare URLs): its clip and stills at each width, its peak's when it has one, and its 320 px AVIFs. */
+export function presetHdFiles(id: string, hasPeak: boolean): string[] {
+ const hd = PRESET_HD[id];
+ if (!hd) return [];
+ const at = (w: number, ext: string, peak = false) => `/previews/presets/hd/${w}/${peak ? "peak/" : ""}${id}.${ext}`;
+ return [
+ ...hd.w.flatMap((w) => [at(w, "mp4"), at(w, "avif"), at(w, "jpg"), ...(hasPeak ? [at(w, "avif", true), at(w, "jpg", true)] : [])]),
+ at(SMALL_PX, "avif"),
+ ...(hasPeak ? [at(SMALL_PX, "avif", true)] : []),
+ ];
+}
diff --git a/tests/preset-covers.test.ts b/tests/preset-covers.test.ts
index 5715ccc9..4f68ae53 100644
--- a/tests/preset-covers.test.ts
+++ b/tests/preset-covers.test.ts
@@ -11,6 +11,8 @@ import { coverPreview, presetCover, thumbOf } from "@/lib/preset-covers";
import { HOME_BENTO_MEDIA } from "@/lib/home-bento.generated";
import { PRESET_BEFORE_AFTER } from "@/lib/preset-before-after.generated";
import { PRESET_COVERS } from "@/lib/preset-covers.generated";
+import { PRESET_HD } from "@/lib/preset-hd.generated";
+import { presetHdFiles } from "@/lib/preset-hd";
import { PRESET_PEAKS } from "@/lib/preset-peaks.generated";
import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";
import { mp4Seconds } from "./helpers/mp4-length";
@@ -86,6 +88,8 @@ describe("the preset covers manifest", () => {
const named = new Set(entries.flatMap(([, e]) => [e.poster, thumbOf(e.poster), e.video].filter((u): u is string => !!u).map((u) => u.split("?")[0])));
for (const id of Object.keys(PRESET_PEAKS)) for (const f of [`/previews/presets/peak/${id}.jpg`, thumbOf(`/previews/presets/peak/${id}.jpg`)]) named.add(f);
for (const id of Object.keys(PRESET_BEFORE_AFTER)) for (const f of beforeAfterFiles(id)) named.add(f);
+ // The larger copies (scripts/gen-preset-hd.mjs, tests/preset-hd.test.ts).
+ for (const id of Object.keys(PRESET_HD)) for (const f of presetHdFiles(id, !!PRESET_PEAKS[id])) named.add(f);
// Home's first screen makes its own clips and stills (scripts/gen-home-bento.mjs, tests/home-bento.test.ts).
for (const f of Object.keys(HOME_BENTO_MEDIA)) named.add(f);
const dir = path.join(root, "public", "previews");
diff --git a/tests/preset-hd.test.ts b/tests/preset-hd.test.ts
new file mode 100644
index 00000000..9682a375
--- /dev/null
+++ b/tests/preset-hd.test.ts
@@ -0,0 +1,101 @@
+import fs from "node:fs";
+import path from "node:path";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import sharp from "sharp";
+import { describe, expect, it } from "vitest";
+import { PresetPreview } from "@/components/preset-preview";
+import { coverWidth, pickWidth } from "@/lib/media-pick";
+import { PRESET_HD } from "@/lib/preset-hd.generated";
+import { presetClipCopies, presetHdFiles, presetStillSources } from "@/lib/preset-hd";
+import { PRESET_PEAKS } from "@/lib/preset-peaks.generated";
+import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";
+import { STARTERS, starterCover } from "@/lib/starters/catalog";
+
+/*
+ * Larger copies of preset covers (scripts/gen-preset-hd.mjs, src/lib/preset-hd.ts): every listed copy is there at its
+ * width, each still shows what the published 512 px one shows (so nothing jumps when a card swaps to it or its clip
+ * starts), and a card offers them in its srcset, so a box takes one at least as wide as it shows.
+ */
+
+const root = process.cwd();
+const local = (url: string) => path.join(root, "public", ...url.split("?")[0].split(" ")[0].split("/").filter(Boolean));
+const grey = (file: string) => sharp(file).resize(128, 96, { fit: "fill" }).greyscale().raw().toBuffer();
+const gap = (a: Buffer, b: Buffer) => a.reduce((sum, v, i) => sum + Math.abs(v - b[i]), 0) / a.length;
+/** As gen-preset-hd.mjs's MATCH. */
+const MATCH = 6;
+/** The most a copy may weigh, by width: a 1024 px clip of a 3 s loop is about 350 to 450 KB. */
+const MAX_CLIP = { 640: 260_000, 1024: 560_000 } as Record<number, number>;
+const MAX_STILL = { 320: 24_000, 640: 70_000, 1024: 150_000 } as Record<number, number>;
+
+const urls = (srcset: string) => srcset.split(", ").map((s) => ({ url: s.split(" ")[0], w: Number(s.split(" ")[1].slice(0, -1)) }));
+
+describe("preset covers' larger copies", () => {
+ const ids = Object.keys(PRESET_HD);
+
+ it("lists covers that are published, at widths past 512 px", () => {
+ expect(ids.length).toBeGreaterThan(0);
+ for (const id of ids) {
+ expect(PRESET_PREVIEWS[id]?.video, id).toBeTruthy();
+ expect(PRESET_HD[id].w.every((w) => w > 512), id).toBe(true);
+ }
+ });
+
+ it.each(ids)("%s: every copy is there, at its width and weight, showing the published frame", async (id) => {
+ const poster = PRESET_PREVIEWS[id].poster;
+ const stills = [poster, ...(PRESET_PEAKS[id] ? [`/previews/presets/peak/${id}.jpg?v=${PRESET_PEAKS[id].v}`] : [])];
+ for (const still of stills) {
+ const src = presetStillSources(still, "/thumb.jpg")!;
+ expect(src, still).toBeDefined();
+ const published = await grey(local(still));
+ for (const { url, w } of [...urls(src.avif), ...urls(src.jpeg).filter((c) => c.w > 512)]) {
+ expect(url).toMatch(/\?v=[0-9a-f]{8}$/);
+ const file = local(url);
+ const meta = await sharp(file).metadata();
+ expect(meta.width, url).toBe(w);
+ expect(meta.height, url).toBe((w * 3) / 4);
+ expect(fs.statSync(file).size, url).toBeLessThan(MAX_STILL[w]);
+ expect(gap(await grey(file), published), url).toBeLessThan(MATCH);
+ }
+ }
+ const clips = presetClipCopies(PRESET_PREVIEWS[id].video!);
+ expect(clips.map((c) => c.w)).toEqual([512, ...PRESET_HD[id].w]);
+ for (const c of clips.slice(1)) {
+ expect(c.src).toMatch(new RegExp(`^/previews/presets/hd/${c.w}/${id}\\.mp4\\?v=${PRESET_HD[id].v}$`));
+ expect(fs.statSync(local(c.src)).size, c.src).toBeLessThan(MAX_CLIP[c.w]);
+ }
+ });
+
+ it("leaves no file in public/previews/presets/hd that no entry names", () => {
+ const named = new Set(ids.flatMap((id) => presetHdFiles(id, !!PRESET_PEAKS[id])));
+ const dir = path.join(root, "public", "previews", "presets", "hd");
+ const files = fs.readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((f) => /.(jpg|avif|mp4)$/.test(f));
+ expect(files.map((f) => `/previews/presets/hd/${f.replaceAll("\\", "/")}`).filter((u) => !named.has(u))).toEqual([]);
+ });
+
+ it("a cover without copies keeps its own files", () => {
+ expect(presetStillSources("/previews/presets/no-such-cover.jpg?v=1", "/t.jpg")).toBeUndefined();
+ expect(presetClipCopies("/previews/presets/no-such-cover.mp4?v=1")).toEqual([{ src: "/previews/presets/no-such-cover.mp4?v=1", w: 512 }]);
+ });
+
+ it("a clip box takes the narrowest copy at least as wide as it shows", () => {
+ const [id] = ids;
+ const clips = presetClipCopies(PRESET_PREVIEWS[id].video!);
+ // A 440 x 248 starter card on a 2x screen, a 358 px phone card at 3x, a 136 px picker tile at 2x.
+ expect(pickWidth(clips, coverWidth(440, 248, 4 / 3, 2)).w).toBe(1024);
+ expect(pickWidth(clips, coverWidth(358, 201, 4 / 3, 3)).w).toBe(1024);
+ expect(pickWidth(clips, coverWidth(300, 225, 4 / 3, 2)).w).toBe(640);
+ expect(pickWidth(clips, coverWidth(136, 102, 4 / 3, 2)).w).toBe(512);
+ });
+
+ it("the Marketing starters' cards offer their cover at 1024 px, AVIF first", () => {
+ for (const s of STARTERS.filter((x) => x.coverFrom && PRESET_HD[x.coverFrom])) {
+ const cover = starterCover(s)!;
+ const html = renderToStaticMarkup(createElement(PresetPreview, { preview: { poster: cover.poster, scene: "product" }, hue: 0, playing: false, sizes: "440px" }));
+ expect(html, s.id).toMatch(/<picture><source type="image\/avif" srcSet="[^"]*\/hd\/1024\/peak\/[^"]+\.avif\?v=[0-9a-f]{8} 1024w"/);
+ expect(html, s.id).toMatch(/<img[^>]*srcSet="[^"]*\/hd\/1024\/peak\/[^"]+\.jpg\?v=[0-9a-f]{8} 1024w"/);
+ }
+ expect(STARTERS.some((s) => s.id === "mk.perfume-moss" && s.coverFrom && PRESET_HD[s.coverFrom])).toBe(true);
+ expect(STARTERS.some((s) => s.id === "mk.bag-packshot" && s.coverFrom && PRESET_HD[s.coverFrom])).toBe(true);
+ });
+});