Open source CapCut alternative.
TypeScript
feat(site): play library copies of undecodable video
David Leb19743369b9d
diff --git a/site/src/cut/components/ImportVideoPoster.tsx b/site/src/cut/components/ImportVideoPoster.tsxindex fa9da36c..072de88e 100644--- a/site/src/cut/components/ImportVideoPoster.tsx+++ b/site/src/cut/components/ImportVideoPoster.tsx@@ -7,20 +7,27 @@ import { importPoster, type ImportPosterFrame } from "@/cut/lib/importPoster";import { holdMemory } from "@/cut/lib/memoryBudget";type Props = {- file: File;+ /** The video: a dropped file, or a stored file's URL. */+ source: Blob | string;+ name: string;size: number;onShape?: (shape: { width: number; height: number }) => void;/** The decoded frame while the tile holds it, and undefined once it lets go. */onFrame?: (frame: ImportPosterFrame | undefined) => void;+ /** No frame could be decoded from the video. */+ onUnreadable?: () => void;};-/** A local frame while the original file is being imported to any shelf. */-export function ImportVideoPoster({ file, size, onShape, onFrame }: Props) {+/** A frame decoded from the video itself, through the WASM decoder where the+ * browser has none: what stands in for a clip still arriving on a shelf, or+ * one whose media element cannot show its picture. */+export function ImportVideoPoster({ source, name, size, onShape, onFrame, onUnreadable }: Props) {const [visible, setVisible] = useState(false);const [poster, setPoster] = useState<string>();const [unreadable, setUnreadable] = useState(false);const measured = useEffectEvent((shape: { width: number; height: number }) => onShape?.(shape));const framed = useEffectEvent((frame: ImportPosterFrame | undefined) => onFrame?.(frame));+ const failed = useEffectEvent(() => onUnreadable?.());const ref = useCallback((node: HTMLDivElement | null) => {if (!node) return;const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));@@ -33,7 +40,7 @@ export function ImportVideoPoster({ file, size, onShape, onFrame }: Props) {const abort = new AbortController();let url: string | undefined;let release: (() => void) | undefined;- void importPoster(file, size, abort.signal).then((frame) => {+ void importPoster(source, size, abort.signal).then((frame) => {if (abort.signal.aborted) return;const { blob, width, height } = frame;if (width && height) measured({ width, height });@@ -43,7 +50,9 @@ export function ImportVideoPoster({ file, size, onShape, onFrame }: Props) {setPoster(url);}).catch(() => {// A missing local decoder leaves the import running on its chosen shelf.- if (!abort.signal.aborted) setUnreadable(true);+ if (abort.signal.aborted) return;+ setUnreadable(true);+ failed();});return () => {abort.abort();@@ -52,13 +61,13 @@ export function ImportVideoPoster({ file, size, onShape, onFrame }: Props) {setPoster(undefined);framed(undefined);};- }, [file, size, visible]);+ }, [source, size, visible]);return (<div ref={ref} className="size-full">{poster ? (// eslint-disable-next-line @next/next/no-img-element -- local decoded frame- <img src={poster} alt={file.name} className="size-full object-cover" />+ <img src={poster} alt={name} className="size-full object-cover" />) : unreadable ? (<div className="flex size-full items-center justify-center bg-muted text-muted-foreground"><Film className="size-8" aria-label="Video" />diff --git a/site/src/cut/components/LibraryCard.tsx b/site/src/cut/components/LibraryCard.tsxindex b9a79ac4..4687ee8c 100644--- a/site/src/cut/components/LibraryCard.tsx+++ b/site/src/cut/components/LibraryCard.tsx@@ -1,8 +1,9 @@"use client";-import { useState, type ReactNode } from "react";+import { useCallback, useState, type ReactNode } from "react";+import { useQueryClient } from "@tanstack/react-query";import { isLinkedAssetType, type AssetType } from "@/cut/lib/types";-import { Film, Image as ImageIcon, Music, Type } from "lucide-react";+import { Film, Image as ImageIcon, Loader2, Music, Type } from "lucide-react";import { Skeleton } from "@/components/ui/skeleton";import { CardActionsMenu } from "@/cut/components/CardActionsMenu";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";@@ -11,6 +12,7 @@ import { RenameInput } from "@/cut/components/RenameInput";import { ShelfBadge } from "@/cut/components/ShelfBadge";import { AudioCardFace } from "@/cut/components/AudioPanel";import { CopyNameLabel } from "@/cut/components/AssetRefs";+import { ImportVideoPoster } from "@/cut/components/ImportVideoPoster";import { FontSpecimen } from "@/cut/components/FontSpecimen";import { useInView } from "@/cut/hooks/useInView";import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";@@ -19,7 +21,10 @@ import { setLibraryDragData } from "@/cut/lib/assetDrag";import { refFromLibrary } from "@/cut/lib/assetRef";import { openExternal } from "@/cut/lib/hostBridge";import { fileKind } from "@/cut/lib/media";-import { libraryAssetName, libraryMediaUrl, libraryPosterUrl, downloadLibraryAsset, type LibraryAsset } from "@/cut/lib/library";+import { libraryAssetName, libraryMediaUrl, libraryPlaybackUrl, libraryPosterUrl, downloadLibraryAsset, type LibraryAsset, type LibraryData } from "@/cut/lib/library";+import { ensureLibraryProxy, libraryProxyKey, useLibraryProxies } from "@/cut/lib/libraryProxy";+import { patchLibrary } from "@/cut/lib/queries";+import { showsNoPicture } from "@/cut/lib/videoPicture";import { LUT_FILE_ICON, LUT_MARK_ICON } from "@/cut/lib/linkedLibrary";import { lightboxItemFromLibrary, type LightboxItem } from "@/cut/lib/lightbox";import { availableResidencies } from "@/cut/lib/residency";@@ -35,7 +40,9 @@ export const LIBRARY_AUDIO_TILE_AREA = LIBRARY_TILE_AREA * 0.7 ** 2;* sounds, LUTs, fonts, notes and templates. */export const LIBRARY_SQUARE = Math.round(Math.sqrt(LIBRARY_AUDIO_TILE_AREA));-type SharedMedia = { src: string; poster?: string; downloadHref: string };+/** A share viewer's media URLs: the file, what plays when a copy stands in+ * for an undecodable master, its cover, and the download. */+type SharedMedia = { src: string; play?: string; poster?: string; downloadHref: string };/** A Library tile's box. Pictures take their own aspect at the shared area;* every other file is the square the sound tile is. Without an area the tile@@ -193,9 +200,12 @@ export function LibraryCard({// metadata across the network the moment the page opened.const [tileRef, seen] = useInView<HTMLDivElement>();const src = sharedMedia?.src ?? libraryMediaUrl(a.fileName, a.residency);+ // What the card and the viewer play: a master the browser cannot decode+ // plays from its copy. The size pill and the download stay the master's.+ const playSrc = sharedMedia ? (sharedMedia.play ?? sharedMedia.src) : libraryPlaybackUrl(a);const poster = sharedMedia ? sharedMedia.poster : libraryPosterUrl(a);const view = (): LightboxItem => sharedMedia ? {- kind: a.type, src, name: libraryAssetName(a), prompt: "", assetId: null, bare: true,+ kind: a.type, src: playSrc, name: libraryAssetName(a), prompt: "", assetId: null, bare: true,duration: a.duration, poster, ...(a.width && a.height ? { ratio: a.width / a.height } : {}),} : lightboxItemFromLibrary(a, !onUse);@@ -207,6 +217,23 @@ export function LibraryCard({// shimmering slab, so a clip that lands while the page is open takes its// place in the grid at once and resolves into itself a moment later.const [painted, setPainted] = useState(false);+ // The source whose element loaded with no picture: a ProRes master, which+ // no browser's media element decodes. The card shows a frame decoded from+ // the file and asks its shelf for a playable copy, which becomes `playSrc`.+ const [blankSrc, setBlankSrc] = useState<string>();+ const blank = blankSrc === playSrc;+ const client = useQueryClient();+ const patch = useCallback(+ (fn: (d: LibraryData) => LibraryData) => patchLibrary(client, fn),+ [client],+ );+ const proxyState = useLibraryProxies((s) => s.jobs[libraryProxyKey(a)]);+ const noPicture = (el: HTMLVideoElement) => {+ if (!showsNoPicture(el)) return;+ setBlankSrc(playSrc);+ // A share viewer can't build anything on the owner's shelf.+ if (!sharedMedia) void ensureLibraryProxy(a, patch);+ };// The size pill only shows on hover, so the lookup waits for the first one.// A font wears its size in the footer at rest, so that one asks as it scrolls// into view.@@ -322,7 +349,7 @@ export function LibraryCard({<videocrossOrigin={MEDIA_CORS}ref={videoRef}- src={`${src}#t=${posterT}`}+ src={`${playSrc}#t=${posterT}`}poster={poster}mutedloop@@ -331,9 +358,15 @@ export function LibraryCard({className="size-full object-cover"// Whichever lands first: a clip with a stored poster paints// from that, one without paints its own first frame.- onLoadedMetadata={() => setPainted(true)}+ onLoadedMetadata={(e) => {+ setPainted(true);+ noPicture(e.currentTarget);+ }}onLoadedData={() => setPainted(true)}- onError={() => setPainted(true)}+ onError={(e) => {+ setPainted(true);+ noPicture(e.currentTarget);+ }}/>{/* The source's own cover — a video's thumbnail where it camefrom — is the face at rest: the element's poster gives way as@@ -352,6 +385,39 @@ export function LibraryCard({onError={() => setPainted(true)}/>)}+ {blank && !poster && (+ <div data-drag-omit className="pointer-events-none absolute inset-0">+ <ImportVideoPoster+ source={playSrc}+ name={a.name}+ size={Math.ceil(Math.sqrt(area ?? LIBRARY_TILE_AREA))}+ />+ </div>+ )}+ {blank && proxyState && (+ // Where the playable copy stands: built while the card+ // shows a frame, or the reason none could be made.+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger+ render={+ <span+ data-drag-omit+ className="absolute bottom-1.5 left-1.5 flex items-center gap-1 rounded-md bg-black/65 px-1.5 py-0.5 text-[10px] text-white"+ />+ }+ >+ {proxyState.kind === "making" && <Loader2 className="size-3 animate-spin" />}+ {proxyState.kind === "making" ? "Preparing" : "Can't play"}+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ {proxyState.kind === "making"+ ? "Making a copy this browser can play"+ : proxyState.error}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}</>)) : a.type === "image" ? (diff --git a/site/src/cut/components/LibraryImportCard.tsx b/site/src/cut/components/LibraryImportCard.tsxindex d3ccb44b..bf20e46e 100644--- a/site/src/cut/components/LibraryImportCard.tsx+++ b/site/src/cut/components/LibraryImportCard.tsx@@ -166,7 +166,8 @@ export function LibraryImportCard({/>) : file && mediaType === "video" ? (<ImportVideoPoster- file={file}+ source={file}+ name={file.name}size={Math.ceil(Math.sqrt(area ?? LIBRARY_TILE_AREA))}onShape={measured}onFrame={setFrame}diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsxindex 7ea36e99..6f2caedb 100644--- a/site/src/cut/components/Lightbox.tsx+++ b/site/src/cut/components/Lightbox.tsx@@ -18,7 +18,9 @@ import {SPECIMEN_INK,} from "@/cut/lib/fontSpecimen";import { PeakStrip } from "./AudioPanel";+import { ImportVideoPoster } from "./ImportVideoPoster";import { MediaTransport } from "./MediaTransport";+import { showsNoPicture } from "@/cut/lib/videoPicture";import { cn } from "@/lib/utils";// The asset lightbox: the big version of a stock, generated, or chat asset@@ -33,6 +35,9 @@ import { cn } from "@/lib/utils";// decodable picture, or media that fails to load.const FALLBACK_RATIO = 16 / 9;+// The side of the square whose area a frame decoded for the viewer covers.+const VIEWER_FRAME_SIZE = 720;+export function Lightbox() {const item = useLightbox((s) => s.item);// The shape the media reported on load, for an item opened without one.@@ -227,7 +232,9 @@ function LightboxMedia({const mediaStyle = ratio ? { aspectRatio: ratio } : undefined;if (item.kind === "video") {- return <VideoBody item={item} ratio={ratio} style={mediaStyle} onRatio={onRatio} />;+ // Keyed to the source: a copy swapped in for an undecodable master starts+ // the element, and what it found, over.+ return <VideoBody key={item.src} item={item} ratio={ratio} style={mediaStyle} onRatio={onRatio} />;}return (// eslint-disable-next-line @next/next/no-img-element -- static/project image, client-only page@@ -265,6 +272,10 @@ function VideoBody({const [time, setTime] = useState(0);const [duration, setDuration] = useState(item.duration ?? 0);const [muted, setMuted] = useState(false);+ // The element loaded with no picture — a ProRes master, which no browser's+ // media element decodes. The sound still plays; the viewer shows a frame+ // decoded from the file while the shelf makes a copy it can play.+ const [blank, setBlank] = useState(false);const toggle = () => {const el = videoRef.current;@@ -305,10 +316,35 @@ function VideoBody({onLoadedMetadata={(e) => {const el = e.currentTarget;setDuration(loadedDuration(el, item));+ // A blank picture takes its shape from the decoded frame below.+ if (showsNoPicture(el)) {+ setBlank(true);+ return;+ }onRatio(ratioOf(el.videoWidth, el.videoHeight));}}- onError={() => onRatio(FALLBACK_RATIO)}+ onError={(e) => {+ if (showsNoPicture(e.currentTarget)) setBlank(true);+ else onRatio(FALLBACK_RATIO);+ }}/>+ {blank && !item.poster && (+ <div className="pointer-events-none absolute inset-0">+ <ImportVideoPoster+ source={item.src}+ name={item.name}+ size={VIEWER_FRAME_SIZE}+ onShape={(s) => onRatio(ratioOf(s.width, s.height))}+ onUnreadable={() => onRatio(FALLBACK_RATIO)}+ />+ </div>+ )}+ {blank && (+ <span className="pointer-events-none absolute top-3 left-3 flex items-center gap-1.5 rounded-full bg-black/55 px-2.5 py-1 text-[11px] text-white backdrop-blur-sm">+ <Loader2 className="size-3 animate-spin" />+ Preparing playback+ </span>+ )}<MediaTransportplaying={playing}time={time}diff --git a/site/src/cut/components/SharedLibraryView.tsx b/site/src/cut/components/SharedLibraryView.tsxindex 0b86b687..3a28b985 100644--- a/site/src/cut/components/SharedLibraryView.tsx+++ b/site/src/cut/components/SharedLibraryView.tsx@@ -15,10 +15,12 @@ import { useCutBase } from "@/cut/lib/nav";function Asset({ asset, token }: { asset: SharedLibraryAsset; token: string }) {const src = `/api/cut-shared/library/${encodeURIComponent(token)}/media/${encodeURIComponent(asset.id)}`;const poster = asset.hasPoster ? `${src}?poster=1` : undefined;+ // A master the browser cannot decode plays from its copy; the download is the master.+ const play = asset.hasProxy ? `${src}?proxy=1` : undefined;return <LibraryCardasset={{ ...asset, addedAt: 0, residency: "cloud" }}area={asset.type === "video" || asset.type === "image" ? LIBRARY_TILE_AREA : LIBRARY_AUDIO_TILE_AREA}- sharedMedia={{ src, poster, downloadHref: `${src}?download=1` }}+ sharedMedia={{ src, play, poster, downloadHref: `${src}?download=1` }}/>;}diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.tsindex a3762c8e..a1d76031 100644--- a/site/src/cut/lib/assetRef.ts+++ b/site/src/cut/lib/assetRef.ts@@ -183,7 +183,8 @@ export const refFromLibrary = (a: LibraryAsset): AssetRef => ({// A ref outlives the session it was made in — it is saved with the chat// thread — so it carries the shelf route rather than a minted URL that// expires inside the hour.- url: libraryRouteUrl(a.fileName, a.residency),+ // A master the browser cannot decode is shown and read through its copy.+ url: libraryRouteUrl(a.proxyFile ?? a.fileName, a.residency),...(isLinkedAssetType(a.type) ? {} : { duration: a.duration }),...(a.width !== undefined ? { width: a.width } : {}),...(a.height !== undefined ? { height: a.height } : {}),diff --git a/site/src/cut/lib/importPoster.ts b/site/src/cut/lib/importPoster.tsindex f83559dc..e7201de4 100644--- a/site/src/cut/lib/importPoster.ts+++ b/site/src/cut/lib/importPoster.ts@@ -9,7 +9,7 @@ export type ImportPosterFrame = { blob: Blob; width: number; height: number; dur/** A frame from the file, with the clip's display size so its tile can take the finished asset's shape. */export function importPoster(- file: Blob,+ file: Blob | string,size: number,signal: AbortSignal,): Promise<ImportPosterFrame> {diff --git a/site/src/cut/lib/libraryProxy.ts b/site/src/cut/lib/libraryProxy.tsnew file mode 100644index 00000000..f5db9706--- /dev/null+++ b/site/src/cut/lib/libraryProxy.ts@@ -0,0 +1,106 @@+"use client";++// The playable copy of a library video the browser cannot decode.+//+// A ProRes master — a phone's or a camera's — has no decoder in any browser's+// media element, so a card of one shows nothing and its viewer plays only the+// sound. The shelf that holds the master builds a copy beside it with the+// project preview's proxy code (the Mac's engine, the cloud worker, or this+// page for the browser shelf) and names it on the asset; every surface then+// plays the copy, and a project still takes the master.+//+// A card asks the moment its own video element reports no picture, so the+// files already on a shelf heal the first time anyone looks at them, and+// whatever format a browser cannot show takes the same path.++import { create } from "zustand";+import { engineFeatures } from "./api";+import { apiJson } from "./backend";+import { pollCloudJob } from "./cloudJob";+import { cutColor } from "./colorSettings";+import type { LibraryAsset, LibraryData } from "./library";+import { useLightbox, lightboxItemFromLibrary } from "./lightbox";+import { backendFor } from "./residency";++/** Where an asset's copy stands this session. */+export type LibraryProxyState =+ | { kind: "making"; progress: number }+ | { kind: "failed"; error: string };++interface LibraryProxies {+ jobs: Record<string, LibraryProxyState>;+}++/** The copies being made, or found unmakeable, this session, by shelf and id. */+export const useLibraryProxies = create<LibraryProxies>(() => ({ jobs: {} }));++/** An asset's key in the store: ids are unique per shelf only. */+export const libraryProxyKey = (a: Pick<LibraryAsset, "id" | "residency">) => `${a.residency}:${a.id}`;++const setJob = (key: string, state: LibraryProxyState | null) =>+ useLibraryProxies.setState((s) => {+ const jobs = { ...s.jobs };+ if (state) jobs[key] = state;+ else delete jobs[key];+ return { jobs };+ });++const FAILED = "Could not make a playable copy of this video.";+/** A cloud build still queued when the poll gives up: the worker keeps going,+ * and the shelf's next listing carries the copy. */+const STILL_QUEUED = "The playable copy is still being made.";++/**+ * Have the asset's shelf build its playable copy, then write the copy onto+ * the cached listing and onto the viewer if it is showing this asset. Runs+ * once per asset per session: a second ask while one is on its way, or after+ * one failed, does nothing, so a file nothing can convert never loops.+ */+export async function ensureLibraryProxy(+ a: LibraryAsset,+ patch: (fn: (d: LibraryData) => LibraryData) => void+): Promise<void> {+ const key = libraryProxyKey(a);+ if (a.type !== "video" || a.proxyFile || useLibraryProxies.getState().jobs[key]) return;+ setJob(key, { kind: "making", progress: 0 });+ try {+ // A Mac app older than the route has nothing to build the copy with.+ if (a.residency === "local" && !(await engineFeatures()).has("library.proxy")) {+ throw new Error("Update the Donkey app to play this video here.");+ }+ const backend = backendFor(a.residency);+ const { proxyMaxHeight, proxyCrf } = cutColor();+ const res = await backend.fetch(`/api/cut/library/${encodeURIComponent(a.id)}/proxy`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ maxHeight: proxyMaxHeight, crf: proxyCrf }),+ });+ const body = await apiJson<LibraryAsset | { jobId: string }>(res);+ if (!res.ok) throw new Error(body.error ?? FAILED);++ // The cloud queues the build on its worker; the Mac and the page answer+ // with the asset once the copy is there.+ const landed = "jobId" in body+ ? await pollCloudJob<LibraryAsset>(body.jobId, backend, FAILED, {+ timedOut: STILL_QUEUED,+ onProgress: (progress) => setJob(key, { kind: "making", progress }),+ })+ : body;+ const proxyFile = landed.proxyFile;+ if (!proxyFile) throw new Error(FAILED);+ const updated: LibraryAsset = { ...a, proxyFile };+ patch((d) => ({+ ...d,+ assets: d.assets.map((x) => (x.id === a.id && x.residency === a.residency ? { ...x, proxyFile } : x)),+ }));++ // A viewer open on this asset swaps to the copy.+ const open = useLightbox.getState().item;+ if (open?.libraryId === a.id) useLightbox.getState().open(lightboxItemFromLibrary(updated, open.bare));+ setJob(key, null);+ } catch (e) {+ const error = e instanceof Error ? e.message : FAILED;+ if (error === STILL_QUEUED) return;+ setJob(key, { kind: "failed", error });+ }+}diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsindex 8e406ecd..7d40cda7 100644--- a/site/src/cut/lib/lightbox.ts+++ b/site/src/cut/lib/lightbox.ts@@ -2,7 +2,7 @@import { create } from "zustand";import type { AssetRef } from "./assetRef";-import { libraryAssetName, libraryMediaUrl, libraryPosterUrl, type LibraryAsset } from "./library";+import { libraryAssetName, libraryPlaybackUrl, libraryPosterUrl, type LibraryAsset } from "./library";import type { MediaAsset } from "./types";// The asset lightbox: a full-screen viewer opened from stock tiles, generated@@ -72,7 +72,7 @@ export const lightboxItemFromLibrary = (bare = false,): LightboxItem => ({kind: a.type,- src: libraryMediaUrl(a.fileName, a.residency),+ src: libraryPlaybackUrl(a),// The title read off the clip is what it is called wherever it is shown, so// the viewer captions it that way and an import from here lands under it.name: libraryAssetName(a),diff --git a/site/src/cut/lib/videoPicture.ts b/site/src/cut/lib/videoPicture.tsnew file mode 100644index 00000000..a2e00e78--- /dev/null+++ b/site/src/cut/lib/videoPicture.ts@@ -0,0 +1,8 @@+/** Whether a video element has found it cannot show the file's picture: its+ * metadata loaded with no picture size (Chrome plays a ProRes file's sound+ * and drops the picture), or it refused the source outright (a ProRes file+ * with no sound). A network failure is neither. */+export function showsNoPicture(el: HTMLVideoElement): boolean {+ if (el.error) return el.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED;+ return el.readyState >= HTMLMediaElement.HAVE_METADATA && !el.videoWidth;+}