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.

Home reel: hold One Take's last frame, warm first paint, steadier playback

Adarshecffeca63a19
diff --git a/scripts/gen-home-bento.mjs b/scripts/gen-home-bento.mjs
index 1432f63e..e17cfad5 100644
--- a/scripts/gen-home-bento.mjs
+++ b/scripts/gen-home-bento.mjs
@@ -17,7 +17,7 @@
* ba-{before,after}-tall-{432,691}.avif the same pair, a 3:5 crop for the tall tile
* board-{photo,film}.webp the Canvas board's photo and a frame of its film, 168 px squares
* and src/lib/home-bento.generated.ts: each file's content version, the reel (its clips in order, each one's length and
- * framing), and the waveform.
+ * framing, and where set how long it holds its last frame and fades out), each poster's mean colour, and the waveform.
*
* The reel: the video tile plays these clips one after another, each once, and crossfades into the next (after the
* last, back to the first). Each is a stretch of its preset's full-size render: `from` (its first frame in the render)
@@ -84,11 +84,12 @@ const BA_TALL = { left: 422, top: 0, width: 691, height: 1152 };
* (chosen on close crops of faces and fine detail against the render; a busy picture, such as One Take's leaves, costs
* more bits). The stretches are the ones that hold up frame by frame at the tile's size: One Take from the arch to its
* look back (the render's last frame) and Sand Storm from the first gust until the sand has wrapped round her (the render's last second relights the shot). The first clip's first frame is the
- * tile's poster.
+ * tile's poster. `hold` and `fade` (ms, src/lib/home-reel.ts ReelClip): One Take ends on her face, so it holds that
+ * last frame a moment before the next clip comes in, and crossfades out quicker, so the two faces barely overlap.
*/
export const REEL = [
{ id: "effect-sand-storm", name: "reel-sand-storm", from: 0, frames: 96, position: "50% 0%", crf: { 640: 22, 1024: 22, 1536: 26, 2048: 27 } },
- { id: "motion-one-take", name: "reel-one-take", from: 28, frames: 96, position: "50% 15%", crf: { 640: 22, 1024: 23, 1536: 27, 2048: 28 } },
+ { id: "motion-one-take", name: "reel-one-take", from: 28, frames: 96, position: "50% 15%", hold: 450, fade: 350, crf: { 640: 22, 1024: 23, 1536: 27, 2048: 28 } },
];
/**
* The 3D tile's clip: its published preset, the name of its copies here, and the CRF each width is encoded at (the
@@ -198,6 +199,12 @@ function readWave() {
return { wave: waveform(Array.from(samples, (s) => s / 32768)), seconds: samples.length / 8000 };
}
+/**
+ * A reel clip as the generated list holds it (and src/lib/home-reel.ts ReelClip reads it): `hold` and `fade` only where set.
+ * @param {{ id: string; name: string; frames: number; position: string; hold?: number; fade?: number }} c
+ */
+export const reelEntry = ({ id, name, frames, position, hold, fade }) => ({ id, name, frames, fps: CLIP_FPS, position, ...(hold ? { hold } : {}), ...(fade ? { fade } : {}) });
+
async function main() {
if (!DRY) fs.mkdirSync(OUT_DIR, { recursive: true });
if (MASTERS && !fs.existsSync(MASTERS)) throw new Error(`no masters folder at ${MASTERS}`);
@@ -285,6 +292,12 @@ async function main() {
if (!fs.existsSync(out) || !fs.readFileSync(out).equals(buf)) fs.writeFileSync(out, buf);
versions[`/previews/home/${s.name}`] = contentVersion([out]);
}
+ // Each poster's mean colour: its tile's background until the picture is in, so the first paint is never an empty box.
+ const tints = {};
+ for (const c of posterSets) {
+ const { channels } = await sharp(path.join(OUT_DIR, `${c.name}-${FALLBACK_WIDTH}.jpg`)).stats();
+ tints[c.name] = `#${channels.slice(0, 3).map((ch) => Math.round(ch.mean).toString(16).padStart(2, "0")).join("")}`;
+ }
const { wave, seconds } = readWave();
console.log(`stills ${(total / 1024).toFixed(1)} KB (clips aside) · waveform ${wave.length} bars over ${seconds.toFixed(2)} s`);
if (DRY) return;
@@ -298,11 +311,14 @@ export const HOME_BENTO_MEDIA: Record<string, string> = ${JSON.stringify(version
/** The video tile's reel, in the order it plays: each clip's preset, its copies' name, its length and its framing. */
export const HOME_BENTO_REEL = ${JSON.stringify(
- REEL.map(({ id, name, frames, position }) => ({ id, name, frames, fps: CLIP_FPS, position })),
+ REEL.map(reelEntry),
null,
2,
)};
+/** Each poster's mean colour (by its clip's name): the tile shows it until the poster is in. */
+export const HOME_BENTO_TINT: Record<string, string> = ${JSON.stringify(tints, null, 2)};
+
export const HOME_BENTO_WAVE = {
src: ${JSON.stringify(WAVE_SOURCE)},
source: ${JSON.stringify(source)},
diff --git a/src/components/home/bento-islands.tsx b/src/components/home/bento-islands.tsx
index 4a60dfc8..94d2f787 100644
--- a/src/components/home/bento-islands.tsx
+++ b/src/components/home/bento-islands.tsx
@@ -5,7 +5,7 @@ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useNavUi } from "@/components/nav/nav-ui";
import { usePreviewPlayback, usePreviewsPaused } from "@/components/preset-preview";
import type { BentoPicture } from "@/lib/home-bento";
-import { REEL_FADE_MS, fadeDue, nextInReel, reelProgress, reelSources, type ReelClip } from "@/lib/home-reel";
+import { REEL_STALL_MS, fadeDue, fadeOf, holdOf, nextInReel, reelProgress, reelSources, type ReelClip } from "@/lib/home-reel";
import { coverWidth, pickWidth, type Sized } from "@/lib/media-pick";
import { releaseVideo } from "@/lib/media-release";
import { browserPlaybackEnv } from "@/lib/preview-playback";
@@ -247,50 +247,67 @@ const holdsStill = () => window.matchMedia("(prefers-reduced-motion: reduce)").m
/**
* One clip of the reel, in its own element (keyed by `k`, its place in the order the reel has played): it lets go of
- * its source when it leaves, so a clip that has played stops costing memory. `shown`: on screen; `incoming`: it fades
- * in over the clip ending, at the reel's pace.
+ * its source when it leaves, so a clip that has played stops costing memory. Its source is set here rather than as a
+ * prop: in development React mounts it twice, and the source let go of on the first unmount must come back. `run`:
+ * whether it plays (it plays and pauses itself, so a second mount plays it too; played once it has ended, it starts
+ * from its first frame). `shown`: on screen; `incoming`: it fades in over the clip ending, for `fadeMs`.
*/
function ReelVideo({
k,
clip,
src,
loop,
+ run,
shown,
incoming,
+ fadeMs,
register,
onLoaded,
onPlaying,
onEnded,
+ onFailed,
+ onFaded,
}: {
k: number;
clip: ReelClip;
src: string;
loop: boolean;
+ run: boolean;
shown: boolean;
incoming: boolean;
+ fadeMs: number;
register: (k: number, v: HTMLVideoElement | null) => void;
onLoaded: (k: number) => void;
onPlaying: (k: number) => void;
onEnded: (k: number) => void;
+ onFailed: (k: number) => void;
+ onFaded: (k: number) => void;
}) {
const ref = useRef<HTMLVideoElement>(null);
useEffect(() => {
const v = ref.current;
+ if (!v) return;
+ v.src = src;
register(k, v);
return () => {
register(k, null);
releaseVideo(v);
};
- }, [k, register]);
+ }, [k, src, register]);
+ useEffect(() => {
+ const v = ref.current;
+ if (!v) return;
+ if (run) void v.play().catch(() => {});
+ else v.pause();
+ }, [run]);
return (
<video
ref={ref}
- src={src}
muted
loop={loop}
playsInline
preload="auto"
- style={{ objectPosition: clip.position }}
+ style={{ objectPosition: clip.position, transitionDuration: incoming ? `${fadeMs}ms` : undefined }}
data-clip={clip.id}
data-max={Math.max(...clip.clips.map((c) => c.w))}
data-ready={shown || undefined}
@@ -298,22 +315,28 @@ function ReelVideo({
onLoadedData={() => onLoaded(k)}
onPlaying={() => onPlaying(k)}
onEnded={() => onEnded(k)}
+ onError={() => onFailed(k)}
+ onTransitionEnd={(e) => e.propertyName === "opacity" && onFaded(k)}
/>
);
}
-/** The latest of two places in the reel's order (each "this one has loaded / played / ended" only moves forward). */
+/** The latest of two places in the reel's order (each "this one has loaded / played" only moves forward). */
const later = (k: number) => (prev: number) => Math.max(prev, k);
/**
* The video tile's reel (src/lib/home-reel.ts): its clips one after another, each played once, each crossfading into
- * the next for REEL_FADE_MS as it ends, and after the last the first again. It plays by the same rules as a tile's clip
- * (BentoClip): it joins the site's playback rules once its still is painted, plays only on screen and in a visible tab,
- * pauses where it is, and each clip is the narrowest copy at least as wide as the tile needs on this screen (and as the
- * copy of the still the browser chose). The still is the first clip's first frame, and that clip shows only once it has
- * that frame: no sign, no flash, nothing moves. Only the clip playing and the one after it are loaded, the next one
- * only once the current one plays. Under reduced motion or Save-Data nothing plays by itself; a hover or keyboard focus
- * plays the first clip alone, on a loop. `progress`: a line along the bottom follows the whole reel.
+ * the next as it ends (or once it has held its last frame), and after the last the first again. It plays by the same
+ * rules as a tile's clip (BentoClip): it joins the site's playback rules once its still is painted, plays only on
+ * screen and in a visible tab, pauses where it is, and each clip is the narrowest copy at least as wide as the tile
+ * needs on this screen (and as the copy of the still the browser chose). The still is the first clip's first frame,
+ * and that clip shows only once it has that frame: no sign, no flash, nothing moves. Only the clip playing and the one
+ * after it are loaded, the next one only once the current one plays. The next clip is started when its fade is due (a
+ * phone may not fetch a paused clip's frames) and shows once it plays. A next clip that fails stops the reel turning:
+ * the clip on screen loops instead. One that is slow lets the clip on screen play again rather than stop on its last
+ * frame. Under reduced motion or Save-Data nothing plays by itself; a hover or keyboard focus plays the first clip
+ * alone, on a loop (under Save-Data, the copy as wide as the still). `progress`: a line along the bottom follows the
+ * whole reel.
*/
export function BentoReel({ id, reel, progress }: { id: string; reel: ReelClip[]; progress?: boolean }) {
const [armed, setArmed] = useState(false);
@@ -337,8 +360,25 @@ export function BentoReel({ id, reel, progress }: { id: string; reel: ReelClip[]
}, [ref]);
// Chosen when it first plays, and kept: each clip's copy, and whether the reel turns or its first clip loops alone.
const [plan, setPlan] = useState<{ srcs: string[]; turns: boolean } | null>(null);
- if (playing && !plan) setPlan({ srcs: reelSources(reel, Math.max(need, stillW)), turns: reel.length > 1 && !holdsStill() });
+ // The clip resting on its last frame: it has ended, and stays there until the reel plays it again.
+ const [rest, setRest] = useState(-1);
+ if (playing && !plan) {
+ const width = browserPlaybackEnv.saveData() ? Math.max(stillW, 1) : Math.max(need, stillW);
+ setPlan({ srcs: reelSources(reel, width), turns: reel.length > 1 && !holdsStill() });
+ }
const turns = !!plan?.turns;
+ // Asked for less motion once it has started: it stops turning, and the clip on screen loops alone when played.
+ useEffect(() => {
+ if (!turns) return;
+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const stop = () => {
+ if (!reduced.matches) return;
+ setPlan((p) => p && { ...p, turns: false });
+ setRest(-1);
+ };
+ reduced.addEventListener("change", stop);
+ return () => reduced.removeEventListener("change", stop);
+ }, [turns]);
// `seq`: how many clips have played before the one on screen (it is clip seq % n). Each element is keyed by its seq,
// so a clip that comes round again is a new element.
@@ -346,13 +386,22 @@ export function BentoReel({ id, reel, progress }: { id: string; reel: ReelClip[]
const [seq, setSeq] = useState(0);
const [loaded, setLoaded] = useState(-1);
const [started, setStarted] = useState(-1);
+ // `due`: the latest clip whose fade into the next has come (set back when the next one is late, so it comes again).
const [due, setDue] = useState(-1);
- // The next clip loads once this one plays; it fades in once this one is near its end (or has ended) and it has its
- // first frame.
+ // Each time a clip ends: which one, and a count, so the same clip ending again is seen.
+ const [ends, setEnds] = useState({ k: -1, n: 0 });
+ const cur = reel[seq % n];
+ // The next clip loads once this one plays; it starts once this one is near its end (or has ended and held its last
+ // frame), and fades in once it plays.
const nextOn = turns && started >= seq;
- const fading = nextOn && due >= seq && loaded > seq;
+ const fading = nextOn && due >= seq;
+ const incomingShown = fading && started > seq;
const els = useRef(new Map<number, HTMLVideoElement>());
const [register] = useState(() => (k: number, v: HTMLVideoElement | null) => void (v ? els.current.set(k, v) : els.current.delete(k)));
+ const startedNow = useRef(started);
+ useEffect(() => {
+ startedNow.current = started;
+ });
const bar = useRef<HTMLElement>(null);
const on = useRef(handlers);
useEffect(() => {
@@ -373,37 +422,51 @@ export function BentoReel({ id, reel, progress }: { id: string; reel: ReelClip[]
};
}, [ref]);
- // Play or pause the clip on screen, and the one fading in over it; the next one waits on its first frame.
- useEffect(() => {
- const cur = els.current.get(seq);
- const next = els.current.get(seq + 1);
- if (cur) {
- if (playing) void cur.play().catch(() => {});
- else cur.pause();
- }
- if (next) {
- if (playing && fading) void next.play().catch(() => {});
- else next.pause();
- }
- }, [playing, seq, fading, plan, nextOn]);
-
- // Once the next clip has faded in, it takes this one's place (and this one's element goes).
+ // Whether each clip plays: the clip on screen while the reel plays, unless it has ended and rests on its last frame
+ // (played again, it starts from its first: it loops alone, or the next one is late); the next one only once its fade
+ // is due (until then it loads).
+ const runs = (k: number) => playing && (k === seq ? rest !== seq : fading);
+
+ // Once the next clip has faded in (its opacity's transition has ended), it takes this one's place and this one's
+ // element goes; a little after the fade's length at the latest.
+ const advance = (k: number) => {
+ if (k === seq + 1 && incomingShown) setSeq((x) => Math.max(x, k));
+ };
useEffect(() => {
- if (!fading) return;
- const t = window.setTimeout(() => setSeq((x) => Math.max(x, seq + 1)), REEL_FADE_MS);
+ if (!incomingShown) return;
+ const t = window.setTimeout(() => setSeq((x) => Math.max(x, seq + 1)), fadeOf(cur) + 150);
return () => clearTimeout(t);
- }, [fading, seq]);
+ }, [incomingShown, seq, cur]);
+
+ // When the clip on screen ends: its fade is due now, or once its last frame has held. If the next clip hasn't
+ // started REEL_STALL_MS after that, the fade is set back: the clip on screen plays again from its start, and the
+ // fade comes round again at its end.
+ useEffect(() => {
+ if (!turns || ends.k !== seq) return;
+ const hold = holdOf(cur);
+ const a = window.setTimeout(() => setDue(later(seq)), hold);
+ const b = window.setTimeout(() => {
+ if (startedNow.current > seq) return;
+ setDue((d) => Math.min(d, seq - 1));
+ setRest(-1);
+ }, hold + REEL_STALL_MS);
+ return () => {
+ clearTimeout(a);
+ clearTimeout(b);
+ };
+ }, [ends, seq, turns, cur]);
- // A frame at a time while it plays: the line follows the reel, and the fade is due REEL_FADE_MS before a clip's end.
+ // A frame at a time while it plays: the line follows the reel, and the fade is due its length before a clip's end
+ // (fadeDue; for a clip that holds its last frame, only once it has ended).
useEffect(() => {
const v = els.current.get(seq);
const b = bar.current;
- if (!v || !playing || loaded < seq) return;
+ if (!v || !playing || Math.max(loaded, started) < seq) return;
let raf = 0;
- let marked = false;
+ let marked = due >= seq;
const tick = () => {
if (b) b.style.transform = `scaleX(${turns ? reelProgress(seq % n, n, v.currentTime, v.duration) : v.duration > 0 ? v.currentTime / v.duration : 0})`;
- if (turns && !marked && fadeDue(v.currentTime, v.duration)) {
+ if (turns && !marked && !v.ended && fadeDue(v.currentTime, v.duration, cur)) {
marked = true;
setDue(later(seq));
}
@@ -411,7 +474,14 @@ export function BentoReel({ id, reel, progress }: { id: string; reel: ReelClip[]
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
- }, [playing, loaded, seq, turns, n]);
+ }, [playing, loaded, started, seq, turns, n, due, cur]);
+
+ // A next clip that can't play (missing, cut off, not decodable): the reel stops turning and the clip on screen loops.
+ const failed = (k: number) => {
+ if (k <= seq) return;
+ setPlan((p) => p && { ...p, turns: false });
+ setRest(-1);
+ };
const playingNow = plan ? [{ k: seq, i: seq % n }, ...(nextOn ? [{ k: seq + 1, i: nextInReel(seq % n, n) }] : [])] : [];
return (
@@ -424,12 +494,19 @@ export function BentoReel({ id, reel, progress }: { id: string; reel: ReelClip[]
clip={reel[i]}
src={plan.srcs[i]}
loop={!turns}
- shown={loaded >= k && (k === seq || fading)}
+ run={runs(k)}
+ shown={k === seq ? Math.max(loaded, started) >= k : incomingShown}
incoming={k > seq}
+ fadeMs={fadeOf(cur)}
register={register}
onLoaded={(x) => setLoaded(later(x))}
onPlaying={(x) => setStarted(later(x))}
- onEnded={(x) => setDue(later(x))}
+ onEnded={(x) => {
+ setRest(x);
+ setEnds((e) => ({ k: x, n: e.n + 1 }));
+ }}
+ onFailed={failed}
+ onFaded={advance}
/>
))}
{progress && (
diff --git a/src/components/home/home-bento.css b/src/components/home/home-bento.css
index 762c6ea9..6c3e76e6 100644
--- a/src/components/home/home-bento.css
+++ b/src/components/home/home-bento.css
@@ -545,9 +545,12 @@
.hb-clip video:not([data-ready]) {
opacity: 0;
}
-/* The video tile's reel: the next clip fades in over the one ending (REEL_FADE_MS, src/lib/home-reel.ts). */
+/* The video tile's reel: the next clip fades in over the one ending, for the ending clip's fade (REEL_FADE_MS unless
+ it sets its own, src/lib/home-reel.ts; set inline). Slow at both ends and quick through the middle: two faces are
+ never half over each other for long. */
.hb-clip video[data-in] {
transition-duration: 0.5s;
+ transition-timing-function: cubic-bezier(0.6, 0, 0.4, 1);
}
/* ---------------------------------------------------------------- image: a slow push in */
diff --git a/src/components/home/home-bento.tsx b/src/components/home/home-bento.tsx
index 5772e410..656e8f67 100644
--- a/src/components/home/home-bento.tsx
+++ b/src/components/home/home-bento.tsx
@@ -1,4 +1,5 @@
import { ArrowRight, ArrowUpRight, ChevronsLeftRight, Play, Sparkles, Video } from "lucide-react";
+import { preload } from "react-dom";
import { BentoClip, BentoMotion, BentoReel, LiveTyping, NumbersLink } from "@/components/home/bento-islands";
import { PausePreviews } from "@/components/home/home-islands";
import { IntentLink } from "@/components/intent-link";
@@ -25,8 +26,9 @@ const TALL_MEDIA = "(min-width: 1024px)";
/**
* A picture in AVIF where the browser takes it, its published JPEG or WebP where not; a picture with a `tall` crop
- * takes it from lg. `position`: its object-position, where it differs from its tile's. Decorative: the tile's link
- * names it.
+ * takes it from lg. `position`: its object-position, where it differs from its tile's. Its tint (a clip's poster) is
+ * its box's colour until it is in. `decoding`: "sync" for the picture that must land with the first screen.
+ * Decorative: the tile's link names it.
*/
function Pic({
pic,
@@ -35,6 +37,7 @@ function Pic({
loading = "eager",
fetchPriority,
position,
+ decoding = "async",
}: {
pic: BentoPicture;
sizes: string;
@@ -42,6 +45,7 @@ function Pic({
loading?: "eager" | "lazy";
fetchPriority?: "high" | "low";
position?: string;
+ decoding?: "async" | "sync";
}) {
return (
<picture className={s.pic}>
@@ -54,10 +58,10 @@ function Pic({
height={Math.round((pic.avif.at(-1)!.w * 3) / 4)}
loading={loading}
fetchPriority={fetchPriority}
- decoding="async"
+ decoding={decoding}
draggable={false}
className={cn(s.fill, className)}
- style={position ? { objectPosition: position } : undefined}
+ style={position || pic.tint ? { objectPosition: position, backgroundColor: pic.tint } : undefined}
/>
</picture>
);
@@ -156,6 +160,15 @@ function CanvasBoard({ board }: { board: Bento["canvas"] }) {
*/
export function HomeBento({ bento }: { bento: Bento }) {
const { tiles } = bento;
+ // The video tile's still is the first screen's biggest picture: asked for from the head, before the body's HTML.
+ const still = bento.video.poster;
+ preload(still.avif.at(-1)!.src, {
+ as: "image",
+ type: "image/avif",
+ fetchPriority: "high",
+ imageSrcSet: still.avif.map((a) => `${a.src} ${a.w}w`).join(", "),
+ imageSizes: SIZES.video,
+ });
return (
<section id="home-bento" aria-labelledby="home-bento-title" className={s.bento}>
<div className={s.head}>
@@ -181,7 +194,7 @@ export function HomeBento({ bento }: { bento: Bento }) {
<div className={s.grid}>
<Tile tile={tiles.video} area={s.video} bigMeta>
- <Pic pic={bento.video.poster} sizes={SIZES.video} fetchPriority="high" position={bento.video.reel[0].position} />
+ <Pic pic={still} sizes={SIZES.video} fetchPriority="high" decoding="sync" position={bento.video.reel[0].position} />
<BentoReel id={bento.video.id} reel={bento.video.reel} progress />
<span aria-hidden className={s.badge}>
<Video className="size-3.5" /> Video
diff --git a/src/lib/home-bento.generated.ts b/src/lib/home-bento.generated.ts
index a21b6fcf..ea4be0ab 100644
--- a/src/lib/home-bento.generated.ts
+++ b/src/lib/home-bento.generated.ts
@@ -50,10 +50,18 @@ export const HOME_BENTO_REEL = [
"name": "reel-one-take",
"frames": 96,
"fps": 24,
- "position": "50% 15%"
+ "position": "50% 15%",
+ "hold": 450,
+ "fade": 350
}
];
+/** Each poster's mean colour (by its clip's name): the tile shows it until the poster is in. */
+export const HOME_BENTO_TINT: Record<string, string> = {
+ "reel-sand-storm": "#b06c4c",
+ "rotation": "#bfbeb6"
+};
+
export const HOME_BENTO_WAVE = {
src: "/samples/clean-voice/clean.m4a",
source: "8a1e9cfc",
diff --git a/src/lib/home-bento.ts b/src/lib/home-bento.ts
index abe00b63..c46020e6 100644
--- a/src/lib/home-bento.ts
+++ b/src/lib/home-bento.ts
@@ -11,7 +11,7 @@ import { getTemplate } from "@/lib/catalog/canvas";
import { runsOn } from "@/lib/catalog/engines";
import type { ModelDef } from "@/lib/catalog/types";
import { EXAMPLE_MEDIA } from "@/lib/examples/media.generated";
-import { HOME_BENTO_MEDIA, HOME_BENTO_REEL, HOME_BENTO_WAVE } from "@/lib/home-bento.generated";
+import { HOME_BENTO_MEDIA, HOME_BENTO_REEL, HOME_BENTO_TINT, HOME_BENTO_WAVE } from "@/lib/home-bento.generated";
import type { ReelClip } from "@/lib/home-reel";
import type { Demo } from "@/lib/live/demo";
import { presetCover } from "@/lib/preset-covers";
@@ -58,11 +58,13 @@ export type BentoKey = keyof typeof BENTO_HREFS;
/**
* A picture in two or three widths: AVIF for the browsers that take it, the published JPEG for the rest. `tall`: a portrait
* crop of it for a tile that is tall from lg (home-bento.tsx), so the picture is never stretched past its own pixels.
+ * `tint`: its mean colour, shown until it is in (a clip's poster).
*/
export interface BentoPicture {
avif: { src: string; w: number }[];
fallback: string;
tall?: { src: string; w: number }[];
+ tint?: string;
}
/** A tile's clip: its id in the playback store, its poster, and the clip in each width (the tile picks one). */
@@ -195,11 +197,12 @@ export async function homeBento(f: BentoFacts) {
poster: {
avif: widthsOf(first.name, "avif").map((w) => ({ src: made(`/previews/home/${first.name}-${w}.avif`), w })),
fallback: made(`/previews/home/${first.name}-${BENTO_CLIP_FALLBACK}.jpg`),
+ tint: HOME_BENTO_TINT[first.name],
},
reel: HOME_BENTO_REEL.map((c) => {
const widths = widthsOf(c.name, "mp4");
if (!widths.length) throw new Error(`Home's video tile names ${c.name}, which scripts/gen-home-bento.mjs didn't make`);
- return { id: c.id, position: c.position, clips: widths.map((w) => ({ src: made(`/previews/home/${c.name}-${w}.mp4`), w })) };
+ return { id: c.id, position: c.position, hold: c.hold, fade: c.fade, clips: widths.map((w) => ({ src: made(`/previews/home/${c.name}-${w}.mp4`), w })) };
}),
};
};
@@ -212,6 +215,7 @@ export async function homeBento(f: BentoFacts) {
poster: {
avif: BENTO_CLIP_WIDTHS.map((w) => ({ src: made(`/previews/home/${name}-${w}.avif`), w })),
fallback: made(`/previews/home/${name}-${BENTO_CLIP_FALLBACK}.jpg`),
+ tint: HOME_BENTO_TINT[name],
},
clips: BENTO_CLIP_WIDTHS.map((w) => ({ src: made(`/previews/home/${name}-${w}.mp4`), w })),
};
diff --git a/src/lib/home-reel.ts b/src/lib/home-reel.ts
index c4a1c6d1..1723bb6f 100644
--- a/src/lib/home-reel.ts
+++ b/src/lib/home-reel.ts
@@ -5,16 +5,36 @@
*/
import { pickWidth, type Sized } from "@/lib/media-pick";
-/** One clip of the reel: its preset, where the tile anchors it (object-position), and its copies in each width. */
+/**
+ * One clip of the reel: its preset, where the tile anchors it (object-position), and its copies in each width.
+ * `hold`: how long its last frame stays once it ends, before the next clip fades in over it (ms). Without one, the fade
+ * starts a fade's length before its end. `fade`: how long its crossfade into the next clip takes (ms; REEL_FADE_MS
+ * unless set).
+ */
export interface ReelClip {
id: string;
position: string;
clips: Sized[];
+ hold?: number;
+ fade?: number;
}
-/** How long the crossfade from one clip into the next takes, in ms. */
+/** How long the crossfade from one clip into the next takes, in ms, unless the clip sets its own. */
export const REEL_FADE_MS = 500;
+/**
+ * How long the reel waits for the next clip to start once the clip on screen has ended (and held its last frame), in
+ * ms. Past that, the clip on screen plays again from its start while the next one goes on loading: the tile never
+ * stops on one frame.
+ */
+export const REEL_STALL_MS = 1500;
+
+/** How long clip `c` takes to crossfade into the next one, in ms. */
+export const fadeOf = (c: Pick<ReelClip, "fade">): number => c.fade ?? REEL_FADE_MS;
+
+/** How long clip `c` holds its last frame once it ends, before the next one fades in, in ms. */
+export const holdOf = (c: Pick<ReelClip, "hold">): number => c.hold ?? 0;
+
/** The clip that plays after clip `i` of `n`: the next one, and after the last the first. */
export const nextInReel = (i: number, n: number): number => (i + 1) % n;
@@ -24,8 +44,11 @@ export const nextInReel = (i: number, n: number): number => (i + 1) % n;
*/
export const reelSources = (reel: readonly ReelClip[], need: number): string[] => reel.map((c) => pickWidth(c.clips, need).src);
-/** Whether the crossfade into the next clip is due: the clip at `t` of its `d` seconds is within the fade of its end. */
-export const fadeDue = (t: number, d: number, fadeMs = REEL_FADE_MS): boolean => d > 0 && t >= d - fadeMs / 1000;
+/**
+ * Whether the crossfade into the next clip is due while clip `c` plays: at `t` of its `d` seconds, within its fade of
+ * its end. A clip that holds its last frame is never due while it plays: its fade starts once it has ended and held.
+ */
+export const fadeDue = (t: number, d: number, c: Pick<ReelClip, "fade" | "hold"> = {}): boolean => holdOf(c) === 0 && d > 0 && t >= d - fadeOf(c) / 1000;
/** How far through the whole reel it is (0 to 1), playing clip `i` of `n` at `t` of its `d` seconds. */
export const reelProgress = (i: number, n: number, t: number, d: number): number => (i + (d > 0 ? Math.min(1, Math.max(0, t / d)) : 0)) / n;
diff --git a/tests/e2e/home-bento.mjs b/tests/e2e/home-bento.mjs
index 4bfac8db..74a99077 100644
--- a/tests/e2e/home-bento.mjs
+++ b/tests/e2e/home-bento.mjs
@@ -7,6 +7,8 @@
// studio is the owner's, and the guest's pass is skipped.
// --weight-only: only measure what the first screen downloads (to compare another build, such as main's).
// --only <ids>: run only these numbered parts (the weight, 6, always runs unless --weight-only is all that's asked).
+// Under WebKit, the checks its Playwright build for Windows can't make (ENGINE_LIMITS) are reported as skipped, with
+// the reason, when they fail.
//
// 1. Every width (390, 768, 1024, 1280, 1440, 1920), light and dark, as a guest and as the owner: no sideways scroll,
// one h1, the headline in its own words ("Make anything:" on one line; the second line whole from 768, and on a
@@ -24,6 +26,9 @@
// clip framed as listed (its object-position); never more than the clip playing and the next one loaded, the next
// asked for only once the current one plays; off screen it pauses, back on screen it goes on. A picture of each
// clip in the tile (--shots). Under reduced motion a hover plays Sand Storm alone, on a loop.
+// 1e. The reel when its second clip can't be had, at 1440@2x (Chromium): when that clip fails, the first loops and never
+// stops on a frame; when it comes 6 s late, the first plays again rather than stop on its last frame (never stuck
+// on one frame longer than REEL_STALL_MS and a little), and the second still comes in, at the end of a pass.
// 2. Layout shift under 0.01 at 390 and 1440, through a load and a scroll to the bottom and back.
// 2b. The headline holds still when its parts come late, at 390@3x, 768 and 1440@2x (Chromium): with every font file
// 2.5 s late, and with the HTML in two parts (cut after the second line's first words, 1.5 s apart, by a proxy) and
@@ -56,9 +61,25 @@ if (shotsDir) fs.mkdirSync(shotsDir, { recursive: true });
const browser = await launch();
const failures = [];
const notes = [];
+/**
+ * The checks the Playwright WebKit build for Windows can't make, whatever the page does: under WebKit, one of these
+ * that fails is reported as skipped, with its reason.
+ */
+const ENGINE_LIMITS =
+ ENGINE === "webkit"
+ ? [
+ [/^sharp at /, "this WebKit build takes no AVIF (the narrower fallbacks) and reads a video's width as its box's"],
+ [/^the swap at /, "this WebKit build has no frame-accurate video timing (requestVideoFrameCallback)"],
+ [/each clip loads only once the one before it plays$/, "this WebKit build doesn't show media requests to the page"],
+ [/^reduced motion: no reel clip until asked/, "a looping video stops after one pass in this WebKit build"],
+ [/^Tab reaches the tiles|^a focused tile shows its ring/, "WebKit's Tab moves between form controls only, not links, unless the viewer turns that on"],
+ ]
+ : [];
const check = (name, ok, detail = "") => {
- console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? ` (${detail})` : ""}`);
- if (!ok) failures.push(`${name} ${detail}`);
+ const limit = !ok && ENGINE_LIMITS.find(([re]) => re.test(name));
+ console.log(`${ok ? "ok " : limit ? "skip" : "FAIL"} ${name}${detail ? ` (${detail})` : ""}`);
+ if (limit) notes.push(`skipped under ${ENGINE}: ${name} (${limit[1]})`);
+ else if (!ok) failures.push(`${name} ${detail}`);
};
const WIDTHS = [
@@ -72,11 +93,16 @@ const WIDTHS = [
const TILES = ["video", "image", "audio", "threeD", "restore", "numbers", "live", "canvas"];
/** The widest copy of a clip (scripts/gen-home-bento.mjs), where its element doesn't say (a reel clip's data-max). */
const CLIP_MAX = 2048;
-/** The video tile's reel, in order, and how each clip is framed (HOME_BENTO_REEL). */
-const REEL = ["effect-sand-storm", "motion-one-take"];
-const REEL_POSITION = { "effect-sand-storm": "50% 0%", "motion-one-take": "50% 15%" };
-/** Each reel clip's copies' name (HOME_BENTO_REEL's name). */
-const REEL_NAME = { "effect-sand-storm": "reel-sand-storm", "motion-one-take": "reel-one-take" };
+/**
+ * The video tile's reel, in order (HOME_BENTO_REEL, read from src/lib/home-bento.generated.ts): each clip's preset, how
+ * it is framed, and its copies' name.
+ */
+const HOME_REEL = JSON.parse(/export const HOME_BENTO_REEL = (\[[\s\S]*?\n\]);/.exec(fs.readFileSync(path.join(root, "src/lib/home-bento.generated.ts"), "utf8"))[1]);
+const REEL = HOME_REEL.map((c) => c.id);
+const REEL_POSITION = Object.fromEntries(HOME_REEL.map((c) => [c.id, c.position]));
+const REEL_NAME = Object.fromEntries(HOME_REEL.map((c) => [c.id, c.name]));
+/** How long the reel waits for a late next clip before the clip on screen plays again (src/lib/home-reel.ts). */
+const REEL_STALL_MS = Number(/export const REEL_STALL_MS = (\d+);/.exec(fs.readFileSync(path.join(root, "src/lib/home-reel.ts"), "utf8"))[1]);
const HEADLINE = "Make anything: From an idea to a finished film, in one place.";
/** A context as `who`; null when that viewer can't be had here (a guest needs a studio with a password). */
@@ -346,7 +372,7 @@ if (run("1c"))
* logged on the test's side (the same clock: Date.now()).
*/
const watchReel = () => {
- window.__reel = { turns: [], most: 0, both: [], playing: {}, fades: 0 };
+ window.__reel = { turns: [], most: 0, both: [], playing: {}, fades: 0, back: [], outT: new WeakMap() };
const look = () => {
const span = document.querySelector("#home-bento [data-tile=video] .hb-clip");
if (span) {
@@ -360,6 +386,13 @@ const watchReel = () => {
if (shown.length > 1) {
const o = Number(getComputedStyle(shown.at(-1)).opacity);
if (o > 0.05 && o < 0.95) window.__reel.fades++;
+ // The clip going out plays on to its end, or holds its last frame: it never jumps back while it shows through the
+ // fade (the clip coming in under 90 %), until it is let go of, its source gone, once the next one is in.
+ const out = shown[0];
+ const prev = window.__reel.outT.get(out);
+ if (prev !== undefined && o < 0.9 && out.hasAttribute("src") && out.currentTime < prev - 0.05 && out.currentTime < out.duration - 0.1)
+ window.__reel.back.push({ clip: out.dataset.clip, from: prev, to: out.currentTime, over: o, ended: out.ended, paused: out.paused });
+ window.__reel.outT.set(out, out.currentTime);
}
if (vids.length > 1 && window.__reel.both.length < 400) window.__reel.both.push({ t: Date.now(), clips: vids.map((v) => v.dataset.clip) });
}
@@ -414,6 +447,7 @@ if (run("1d")) {
const r = await page.evaluate(() => window.__reel);
check(`reel ${tag}: plays the clips in order and back to the first`, seen.join() === [...REEL.keys(), 0].join(), seen.join());
check(`reel ${tag}: each clip crossfades into the next`, r.fades >= REEL.length, `${r.fades} frames mid-fade`);
+ check(`reel ${tag}: the clip going out never jumps back under the fade`, r.back.length === 0, JSON.stringify(r.back.slice(0, 3)));
check(`reel ${tag}: never more than the clip playing and the next one`, r.most <= 2, String(r.most));
// Each clip asked for only once the one before it plays; at most one ahead of the clip on screen.
const order = asked.map((a) => a.name);
@@ -457,6 +491,72 @@ if (run("1d")) {
await ctx.close();
}
+// ------------------------------------------------------------------------------------------- 1e. a late or failed clip
+/**
+ * Logs the reel's picture a frame at a time from the first paint: the clip on top (the last one shown), its time, and
+ * how long the picture has stayed the same; every time the clip on screen changes, where the clip going out was.
+ */
+const watchStill = () => {
+ window.__still = { longest: 0, since: 0, sig: "", samples: [], turns: [] };
+ const look = () => {
+ const span = document.querySelector("#home-bento [data-tile=video] .hb-clip");
+ const vids = span ? [...span.querySelectorAll("video[data-ready]")] : [];
+ const top = vids.at(-1);
+ const now = performance.now();
+ const w = window.__still;
+ if (top) {
+ const sig = `${top.dataset.clip}@${top.currentTime.toFixed(3)}`;
+ if (sig !== w.sig) {
+ w.sig = sig;
+ w.since = now;
+ } else w.longest = Math.max(w.longest, now - w.since);
+ if (vids.length > 1 && w.turns.at(-1)?.to !== top.dataset.clip)
+ w.turns.push({ from: vids[0].dataset.clip, to: top.dataset.clip, at: vids[0].currentTime, of: vids[0].duration });
+ if (w.samples.length < 2000) w.samples.push({ t: Math.round(now), clip: top.dataset.clip, ct: top.currentTime, n: span.querySelectorAll("video").length, loop: top.loop });
+ }
+ requestAnimationFrame(look);
+ };
+ requestAnimationFrame(look);
+};
+if (run("1e") && ENGINE === "chromium") {
+ const second = REEL_NAME[REEL[1]];
+ for (const mode of ["fails", "late"]) {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 2 });
+ const page = await ctx.newPage();
+ await page.route(new RegExp(`/previews/home/${second}-\\d+\\.mp4`), async (route) => {
+ if (mode === "fails") return route.abort("failed");
+ await new Promise((r) => setTimeout(r, 6000));
+ return route.continue().catch(() => {});
+ });
+ await page.addInitScript(watchStill);
+ await open(page);
+ await page.waitForTimeout(mode === "fails" ? 14_000 : 22_000);
+ const w = await page.evaluate(() => window.__still);
+ const last = w.samples.slice(-40);
+ const moving = last.length > 1 && last.at(-1).ct !== last[0].ct;
+ if (mode === "fails") {
+ check(
+ `reel when ${REEL[1]} fails: ${REEL[0]} loops alone and never stops on a frame`,
+ moving && last.every((x) => x.clip === REEL[0] && x.n === 1 && x.loop) && w.longest < 700,
+ `longest still ${Math.round(w.longest)} ms; last ${JSON.stringify(last.at(-1))}`,
+ );
+ } else {
+ const into = w.turns.find((x) => x.to === REEL[1]);
+ check(
+ `reel when ${REEL[1]} is 6 s late: never stuck on one frame past ${REEL_STALL_MS} ms and a little`,
+ moving && w.longest < REEL_STALL_MS + 800,
+ `longest still ${Math.round(w.longest)} ms`,
+ );
+ check(
+ `reel when ${REEL[1]} is 6 s late: it still comes in, and every clip comes in at the end of a pass of the one before`,
+ !!into && into.from === REEL[0] && w.turns.every((x) => x.at >= x.of - 0.8),
+ JSON.stringify(w.turns),
+ );
+ }
+ await ctx.close();
+ }
+}
+
// ------------------------------------------------------------------------------------------- 2. layout shift
async function cls(v) {
const ctx = await browser.newContext(viewportOpts(v));
@@ -697,12 +797,15 @@ if (run("4")) {
check("reduced motion: the live words stay", a === b, `${JSON.stringify(a)} / ${JSON.stringify(b)}`);
await ctx.close();
- const sd = await browser.newContext(DESKTOP);
+ // The Save-Data header: through DevTools in Chromium, as the context's own header elsewhere (no DevTools session).
+ const sd = await browser.newContext(ENGINE === "chromium" ? DESKTOP : { ...DESKTOP, extraHTTPHeaders: { "Save-Data": "on" } });
await sd.addInitScript(() => Object.defineProperty(navigator, "connection", { value: { saveData: true, effectiveType: "4g", addEventListener() {} }, configurable: true }));
const sp = await sd.newPage();
- const cdp = await sd.newCDPSession(sp);
- await cdp.send("Network.enable");
- await cdp.send("Network.setExtraHTTPHeaders", { headers: { "Save-Data": "on" } });
+ if (ENGINE === "chromium") {
+ const cdp = await sd.newCDPSession(sp);
+ await cdp.send("Network.enable");
+ await cdp.send("Network.setExtraHTTPHeaders", { headers: { "Save-Data": "on" } });
+ }
const sdClips = [];
sp.on("request", (r) => r.url().includes(".mp4") && sdClips.push(r.url()));
await open(sp);
@@ -813,7 +916,8 @@ async function weight(v) {
media,
};
}
-if (weightOnly || run("6"))
+// The weight is read through DevTools: Chromium only.
+if ((weightOnly || run("6")) && ENGINE === "chromium")
for (const v of [WIDTHS[0], WIDTHS[3], WIDTHS[4], WIDTHS[5]]) {
const r = await weight(v);
// The whole page's total is reported (main's own script and fonts are most of it: compare with --weight-only on
diff --git a/tests/home-reel.test.ts b/tests/home-reel.test.ts
index c5bd8420..47dd5ad1 100644
--- a/tests/home-reel.test.ts
+++ b/tests/home-reel.test.ts
@@ -1,8 +1,8 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { HOME_BENTO_MEDIA, HOME_BENTO_REEL } from "@/lib/home-bento.generated";
-import { REEL_FADE_MS, fadeDue, nextInReel, reelProgress, reelSources, type ReelClip } from "@/lib/home-reel";
-import { REEL } from "../scripts/gen-home-bento.mjs";
+import { REEL_FADE_MS, REEL_STALL_MS, fadeDue, fadeOf, holdOf, nextInReel, reelProgress, reelSources, type ReelClip } from "@/lib/home-reel";
+import { REEL, reelEntry } from "../scripts/gen-home-bento.mjs";
import { mp4Seconds, mp4Size } from "./helpers/mp4-length";
/*
@@ -21,7 +21,7 @@ describe("Home's video reel", () => {
for (let i = 0; i < 6; i++) order.push(nextInReel(order.at(-1)!, n));
expect(order).toEqual([0, 1, 0, 1, 0, 1, 0]);
// The generated list is the script's, in the same order (run node scripts/gen-home-bento.mjs after changing REEL).
- expect(HOME_BENTO_REEL).toEqual(REEL.map(({ id, name, frames, position }) => ({ id, name, frames, fps: 24, position })));
+ expect(HOME_BENTO_REEL).toEqual(REEL.map(reelEntry));
});
it("cuts each clip to its stretch of the render: that many frames at 24 fps, played once", () => {
@@ -72,4 +72,24 @@ describe("Home's video reel", () => {
expect(reelProgress(2, 3, 4, 4)).toBe(1);
expect(reelProgress(1, 3, 1, NaN)).toBeCloseTo(1 / 3, 5);
});
+
+ it("lets a clip set its own fade, and hold its last frame before the next comes in", () => {
+ // A quicker fade starts later.
+ expect(fadeDue(3.6, 4, { fade: 350 })).toBe(false);
+ expect(fadeDue(3.7, 4, { fade: 350 })).toBe(true);
+ // A clip that holds is never due while it plays: its fade starts once it has ended and held.
+ expect(fadeDue(4, 4, { hold: 450 })).toBe(false);
+ expect([fadeOf({}), holdOf({})]).toEqual([REEL_FADE_MS, 0]);
+ expect([fadeOf({ fade: 350 }), holdOf({ hold: 450 })]).toEqual([350, 450]);
+ // One Take ends on her face: it holds a moment and fades out quicker than the reel's default; Sand Storm doesn't hold.
+ const [sand, take] = HOME_BENTO_REEL;
+ expect(holdOf(sand)).toBe(0);
+ expect(holdOf(take)).toBeGreaterThanOrEqual(300);
+ expect(holdOf(take)).toBeLessThanOrEqual(800);
+ expect(fadeOf(take)).toBeLessThan(REEL_FADE_MS);
+ expect(fadeOf(take)).toBeGreaterThanOrEqual(250);
+ // A late next clip: the clip on screen plays again rather than stop, but not before a phone has had time to start it.
+ expect(REEL_STALL_MS).toBeGreaterThanOrEqual(1000);
+ expect(REEL_STALL_MS).toBeLessThanOrEqual(3000);
+ });
});