Open source CapCut alternative.
TypeScript
feat(site): keep a cloud project's opening frame on this machine
David Lef96607c06a39
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxindex 9bf9c1b6..949c9321 100644--- a/site/src/cut/components/Preview.tsx+++ b/site/src/cut/components/Preview.tsx@@ -1,10 +1,16 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useEffect, useRef, useState, type RefObject } from "react";import { usePlayback } from "@/cut/hooks/usePlayback";import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";import { startDrag } from "@/cut/lib/drag";import { getClipSpans, useEditor } from "@/cut/lib/store";+import {+ capturePoster,+ capturePosterWhenReady,+ paintPoster,+ readPoster,+} from "@/cut/lib/posterCache";import { setPreviewCanvas } from "@/cut/lib/previewCanvas";import { frameOf, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";import { cn } from "@/lib/utils";@@ -33,6 +39,35 @@ function pannableSpan(s: {return ox > 1 || oy > 1 ? span : null;}+/** Paint the picture this project's preview last showed, then hand the canvas+ * back to the engine. Cloud media is a network away, so without this the+ * preview holds black for about a second on every open while the first decoder+ * fetches and seeks — the engine leaves the canvas alone until it has a frame,+ * which is what lets a poster sit there in the meantime. Once a real frame+ * lands it is kept for the next open. */+function useCachedFirstFrame(canvasRef: RefObject<HTMLCanvasElement | null>) {+ // Re-runs per load, so reopening a project repaints and re-captures.+ const epoch = useEditor((s) => (s.loaded ? s.loadEpoch : 0));+ const projectId = useEditor((s) => s.projectId);+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || !epoch || !projectId) return;+ let alive = true;+ void readPoster("frame", projectId).then((data) => {+ // Only if the engine has not beaten us to it — a warm decoder paints+ // within the same frame, and the real picture outranks a stored one.+ if (alive && data && !capturePoster("frame", projectId, canvas)) {+ void paintPoster(canvas, data);+ }+ });+ const stop = capturePosterWhenReady("frame", projectId, () => canvasRef.current);+ return () => {+ alive = false;+ stop();+ };+ }, [canvasRef, epoch, projectId]);+}+export function Preview() {const canvasRef = useRef<HTMLCanvasElement>(null);const wrapRef = useRef<HTMLDivElement>(null);@@ -48,6 +83,8 @@ export function Preview() {return () => setPreviewCanvas(null);}, []);+ useCachedFirstFrame(canvasRef);+useEffect(() => {const wrap = wrapRef.current;if (!wrap) return;diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 4e60b479..a9850e51 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";import { useQueryClient } from "@tanstack/react-query";import { useRouter, useSearchParams } from "next/navigation";import {@@ -47,6 +47,7 @@ import {} from "@/components/ui/dropdown-menu";import { Input } from "@/components/ui/input";import { MEDIA_CORS } from "@/cut/lib/mediaCors";+import { capturePosterWhenReady, readPoster } from "@/cut/lib/posterCache";import { engineOrigin, servedFromEngine } from "@/cut/lib/api";import { quotaErrorMessage } from "@/cut/lib/backend/cloud";import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";@@ -944,6 +945,9 @@ export function ProjectsHome() {function CardPreview({ project: p, residency }: { project: ProjectSummary; residency: Residency }) {const videoRef = useRef<HTMLVideoElement>(null);const [tileRef, seen] = useInView<HTMLDivElement>();+ // The frame this card drew last time, so coming back from a project shows the+ // picture at once instead of a grey rectangle while the media loads.+ const poster = useCardPoster(p.id, residency, videoRef, seen);const backend = backendFor(residency);const fileUrl = (file: string) =>backend.url(`/api/cut/projects/${p.id}/media/${encodeURIComponent(file)}`);@@ -994,6 +998,7 @@ function CardPreview({ project: p, residency }: { project: ProjectSummary; residcrossOrigin={MEDIA_CORS}ref={videoRef}src={`${src}#t=${posterT}`}+ poster={poster ?? undefined}mutedloopplaysInline@@ -1005,6 +1010,32 @@ function CardPreview({ project: p, residency }: { project: ProjectSummary; resid);}+/** The cached opening frame for a project card, once it has been read off this+ * machine, and the standing job of keeping it fresh. Null until the read lands,+ * and for a project this browser has never drawn. */+function useCardPoster(+ projectId: string,+ residency: Residency,+ videoRef: RefObject<HTMLVideoElement | null>,+ seen: boolean+): string | null {+ const [poster, setPoster] = useState<string | null>(null);+ useEffect(() => {+ let alive = true;+ void readPoster("card", projectId, residency).then((data) => {+ if (alive) setPoster(data);+ });+ return () => {+ alive = false;+ };+ }, [projectId, residency]);+ useEffect(() => {+ if (!seen) return;+ return capturePosterWhenReady("card", projectId, () => videoRef.current, residency);+ }, [projectId, residency, seen, videoRef]);+ return poster;+}+function ProjectMenu({project: p,className,diff --git a/site/src/cut/lib/posterCache.ts b/site/src/cut/lib/posterCache.tsnew file mode 100644index 00000000..ea5446b7--- /dev/null+++ b/site/src/cut/lib/posterCache.ts@@ -0,0 +1,137 @@+"use client";++/**+ * A project's opening picture, kept on this machine.+ *+ * A local project's media is a file on this Mac, so a card tile and a freshly+ * opened editor draw their first frame in the same breath as the layout. A+ * cloud project's media is a network away: the card holds a grey rectangle and+ * the preview holds black for about a second while a decoder fetches metadata,+ * seeks and decodes — every single time, on a project you have opened a dozen+ * times already. The frame is small, it is the one thing you look at first, and+ * it barely changes. So the surfaces that show it keep the last one they drew+ * and paint that immediately; the real decoder replaces it when it arrives.+ *+ * Two pictures, because the two surfaces frame differently. A card crops a+ * source frame to its tile, while the preview shows the composited frame with+ * the project's letterboxing, so a card poster stretched across the preview+ * would be the wrong picture. Each surface caches what it actually draws.+ *+ * Never a source of truth: a miss, a tainted canvas or a browser with no+ * storage costs the wait it used to cost every time.+ */++import { getBackend, type CutMode } from "./backend";+import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";++/** `card` is the tile's cropped source frame; `frame` is the preview canvas's+ * composited picture. */+type PosterKind = "card" | "frame";++// Wide enough that neither surface shows the upscale in the moment before the+// decoder takes over, small enough that a few hundred projects stay cheap.+const WIDTH: Record<PosterKind, number> = { card: 480, frame: 640 };+const QUALITY = 0.72;++// How long to keep asking a surface for its picture, and how often. A card+// element renders its poster frame without ever firing a reliable event — a+// preload="metadata" video may never reach `loadeddata` — so the picture is+// taken by asking rather than by listening.+const POLL_MS = 400;+const POLL_LIMIT_MS = 20_000;++/** Where the project lives. The projects home lists both shelves at once while+ * the ambient backend is whichever the app is running against, so a caller that+ * knows a project's residency says so; anything editing an open project is+ * already pinned to it and can let this default. */+const keyFor = (kind: PosterKind, projectId: string, scope: CutMode = getBackend().kind) =>+ snapshotKey(scope, `poster-${kind}`, projectId);++export async function readPoster(+ kind: PosterKind,+ projectId: string,+ scope?: CutMode+): Promise<string | null> {+ const hit = await readSnapshot<string>(keyFor(kind, projectId, scope));+ return typeof hit?.value === "string" ? hit.value : null;+}++/** Whether `data` holds anything worth keeping. A decoder that is not ready+ * yet leaves the surface black, and caching that would make the next visit+ * paint a black rectangle with confidence — worse than the wait it saves. */+function hasPicture(data: Uint8ClampedArray): boolean {+ for (let i = 0; i < data.length; i += 4) {+ if (data[i] > 12 || data[i + 1] > 12 || data[i + 2] > 12) return true;+ }+ return false;+}++/** Keep `source`'s current picture as this project's opening frame, reporting+ * whether one was there to keep. Safe to call on any frame: a source with no+ * pixels yet, or one still showing black, is skipped, so the stored poster+ * stays the last good one and a caller can keep asking until it lands. */+export function capturePoster(+ kind: PosterKind,+ projectId: string,+ source: HTMLCanvasElement | HTMLVideoElement,+ scope?: CutMode+): boolean {+ const sw = source instanceof HTMLVideoElement ? source.videoWidth : source.width;+ const sh = source instanceof HTMLVideoElement ? source.videoHeight : source.height;+ if (!sw || !sh) return false;+ try {+ const scale = Math.min(1, WIDTH[kind] / sw);+ const scratch = document.createElement("canvas");+ scratch.width = Math.max(1, Math.round(sw * scale));+ scratch.height = Math.max(1, Math.round(sh * scale));+ const ctx = scratch.getContext("2d", { willReadFrequently: true });+ if (!ctx) return false;+ ctx.drawImage(source, 0, 0, scratch.width, scratch.height);+ if (!hasPicture(ctx.getImageData(0, 0, scratch.width, scratch.height).data)) return false;+ writeSnapshot(keyFor(kind, projectId, scope), scratch.toDataURL("image/jpeg", QUALITY));+ return true;+ } catch {+ // A tainted source cannot be read back; the surface keeps waiting on the+ // network the way it always did.+ return false;+ }+}++/** Keep asking `source` for its picture until one is there to keep, then stop.+ * Returns a canceller for the caller's cleanup. */+export function capturePosterWhenReady(+ kind: PosterKind,+ projectId: string,+ source: () => HTMLCanvasElement | HTMLVideoElement | null,+ scope?: CutMode+): () => void {+ const started = performance.now();+ const timer = setInterval(() => {+ const el = source();+ const done = !el || capturePoster(kind, projectId, el, scope);+ if (done || performance.now() - started > POLL_LIMIT_MS) clearInterval(timer);+ }, POLL_MS);+ return () => clearInterval(timer);+}++/** Draw a stored poster over a canvas, contained and centred so a project whose+ * aspect has changed since is letterboxed rather than stretched. */+export function paintPoster(canvas: HTMLCanvasElement, data: string): Promise<void> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => {+ const ctx = canvas.getContext("2d");+ if (ctx) {+ const scale = Math.min(canvas.width / img.width, canvas.height / img.height);+ const w = img.width * scale;+ const h = img.height * scale;+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.drawImage(img, (canvas.width - w) / 2, (canvas.height - h) / 2, w, h);+ }+ resolve();+ };+ img.onerror = () => resolve();+ img.src = data;+ });+}