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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Shorts, Mixed Media: 9:16 on cloud, real step errors and retry, WebM sound, UI fixes
Claude78ca9c3ae9d6
diff --git a/src/app/api/mixed-media/retry/route.ts b/src/app/api/mixed-media/retry/route.tsnew file mode 100644index 00000000..329d66e5--- /dev/null+++ b/src/app/api/mixed-media/retry/route.ts@@ -0,0 +1,11 @@+import { z } from "zod";+import { retryMixed } from "@/server/mixed-media";+import { body, handle, once } from "@/server/shorts-schemas";++/** Run a render again with the same settings ("Try again" in History); a repeated requestId gets the first answer. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, z.object({ id: z.string().min(1).max(64), requestId: z.string().trim().min(8).max(64).optional() }), "Pick a render to try again");+ return Response.json(await once("mixed-retry", input.requestId, () => retryMixed(input.id)), { status: 201 });+ });+}diff --git a/src/components/mixed-media/history.tsx b/src/components/mixed-media/history.tsxindex 24fcd7eb..efc5fe54 100644--- a/src/components/mixed-media/history.tsx+++ b/src/components/mixed-media/history.tsx@@ -1,23 +1,49 @@"use client";-import { Download, Shapes } from "lucide-react";-import { useState } from "react";+import { Download, Loader2, RotateCcw, Shapes } from "lucide-react";+import { useMemo, useState } from "react";+import { toast } from "sonner";import { Skeleton } from "@/components/ui/skeleton";+import { useSubmitGuard } from "@/components/shorts/hooks";import { PendingTile } from "@/components/studio/feed";import { MediaThumb } from "@/components/studio/result-media";import { Viewer } from "@/components/studio/viewer";import { useGenerations } from "@/lib/api";-import { MIXED_FEATURE } from "@/lib/catalog/mixed-media";+import { MIXED_FEATURE, MIXED_STEP_FEATURE } from "@/lib/catalog/mixed-media";+import { chainState } from "@/lib/catalog/shorts";import type { Generation } from "@/lib/catalog/types";import { timeAgo } from "@/lib/format";import { downloadHref, downloadName, userTitle } from "@/lib/library";+import { renderSteps, useMixedActions } from "./hooks";-const FILTER = { features: [MIXED_FEATURE], limit: 60 };+/** The finished videos and their helper steps (a failed render shows the failing step's own error). */+const FILTER = { features: [MIXED_FEATURE, MIXED_STEP_FEATURE], limit: 150 };++/** Each finished (or rendering, or failed) video with the steps of its render, in order. */+function renders(list: Generation[]): { final: Generation; chain: Generation[] }[] {+ const steps = new Map<string, Generation[]>();+ for (const g of list) if (g.feature === MIXED_STEP_FEATURE && g.batchId) steps.set(g.batchId, [...(steps.get(g.batchId) ?? []), g]);+ return list+ .filter((g) => g.feature === MIXED_FEATURE)+ .map((final) => {+ const own = (final.batchId ? (steps.get(final.batchId) ?? []) : []).slice().sort((a, b) => (a.request.step?.index ?? 0) - (b.request.step?.index ?? 0));+ return { final, chain: [...own, final] };+ });+}/** History: the finished (and rendering) Mixed Media videos, newest first. */export function MixedHistory({ onStart }: { onStart: () => void }) {const list = useGenerations(FILTER);+ const items = useMemo(() => renders(list.data ?? []), [list.data]);const [open, setOpen] = useState<Generation | null>(null);+ const actions = useMixedActions();+ const guard = useSubmitGuard();+ const retry = (id: string) => {+ if (actions.retry.isPending) return;+ void guard(`retry:${id}`, (requestId) => actions.retry.mutateAsync({ id, requestId }))+ .then((r) => r && toast("Rendering it again"))+ .catch((e: Error) => toast.error(e.message));+ };if (list.isLoading)return (<div className="grid grid-cols-2 gap-3 pt-8 sm:grid-cols-3 lg:grid-cols-4">@@ -26,7 +52,7 @@ export function MixedHistory({ onStart }: { onStart: () => void }) {))}</div>);- if (!list.data?.length)+ if (!items.length)return (<div className="mx-auto flex max-w-md flex-col items-center py-20 text-center"><span className="grid size-12 place-items-center rounded-full bg-brand-faint text-brand-text">@@ -42,8 +68,10 @@ export function MixedHistory({ onStart }: { onStart: () => void }) {return (<><div className="grid grid-cols-2 gap-3 pt-8 sm:grid-cols-3 lg:grid-cols-4">- {list.data.map((g) => {+ {items.map(({ final: g, chain }) => {const out = g.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined;+ const state = chainState(renderSteps(chain));+ const retrying = actions.retry.isPending && actions.retry.variables?.id === g.id;return (<div key={g.id} className="min-w-0"><div className="relative aspect-square overflow-hidden rounded-xl bg-muted">@@ -52,11 +80,19 @@ export function MixedHistory({ onStart }: { onStart: () => void }) {<MediaThumb output={out} /></button>) : g.status === "queued" || g.status === "running" ? (- <PendingTile g={g} ratio={1} />+ <PendingTile g={state.status === "working" ? (chain.find((x) => x.status !== "succeeded") ?? g) : g} ratio={1} />) : (<div className="flex size-full flex-col justify-center gap-1 border border-dashed p-3">- <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't render this one"}</p>- {g.error && <p className="line-clamp-4 text-[12px] text-muted-foreground">{g.error}</p>}+ <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : state.status === "failed" ? state.label : "Couldn't render this one"}</p>+ {(state.error ?? g.error) && <p className="line-clamp-4 text-[12px] break-words text-muted-foreground">{state.error ?? g.error}</p>}+ <button+ type="button"+ onClick={() => retry(g.id)}+ disabled={actions.retry.isPending}+ className="mt-1 inline-flex h-7 w-fit items-center gap-1 rounded-full border bg-background px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-60"+ >+ {retrying ? <Loader2 className="size-3 animate-spin" /> : <RotateCcw className="size-3" />} Try again+ </button></div>)}</div>diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.tsindex 30c0b3c4..bfa590f1 100644--- a/src/components/mixed-media/hooks.ts+++ b/src/components/mixed-media/hooks.ts@@ -1,6 +1,6 @@"use client";-import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";import { useDeferredValue } from "react";import type { MixedResolution, MixedValues } from "@/lib/catalog/mixed-media";import type { Engine, Generation } from "@/lib/catalog/types";@@ -62,6 +62,29 @@ export function useWatchedGeneration(id: string | null) {});}+/** Follow every step of a render (cut → restyle → sound), so a failed step shows its own error. */+export function useWatchedChain(ids: string[]): (Generation | undefined)[] {+ const qc = useQueryClient();+ const connected = useGenerationEvents((ev) => {+ if (ev.type === "generation" && ids.includes(ev.generation.id)) qc.setQueryData(["mixed-media", "generation", ev.generation.id], ev.generation);+ });+ return useQueries({+ queries: ids.map((id) => ({+ queryKey: ["mixed-media", "generation", id],+ queryFn: async () => send<Generation>(`/api/generations/${id}`, "GET"),+ refetchInterval: (q: { state: { data?: Generation } }) => (active(q.state.data) ? (connected ? 5000 : 1200) : false),+ })),+ }).map((q) => q.data);+}++/** What each step of a render is doing, for chainState(). */+export function renderSteps(chain: (Generation | undefined)[]): { g?: Generation; label: string }[] {+ return chain.map((g) => ({+ g,+ label: !g ? "A step" : g.op === "trim" ? "Cutting the clip" : g.op === "mux" ? "Putting the sound back" : "Restyling",+ }));+}+export function useMixedActions() {const qc = useQueryClient();const seed = (g: Generation) => qc.setQueryData(["mixed-media", "generation", g.id], g);@@ -69,7 +92,7 @@ export function useMixedActions() {render: useMutation({mutationFn: (b: MixedBody) => send<{ final: Generation; items: Generation[] }>("/api/mixed-media", "POST", b),onSuccess: (r) => {- seed(r.final);+ r.items.forEach(seed);void qc.invalidateQueries({ queryKey: ["generations"] });},}),@@ -77,5 +100,13 @@ export function useMixedActions() {mutationFn: (b: MixedBody) => send<Generation>("/api/mixed-media/preview", "POST", b),onSuccess: seed,}),+ /** Run a finished-or-failed render again with the same settings (History's "Try again"). */+ retry: useMutation({+ mutationFn: (v: { id: string; requestId?: string }) => send<{ final: Generation; items: Generation[] }>("/api/mixed-media/retry", "POST", v),+ onSuccess: (r) => {+ r.items.forEach(seed);+ void qc.invalidateQueries({ queryKey: ["generations"] });+ },+ }),};}diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex 8c72cc3e..cf8d352a 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -1,48 +1,17 @@"use client";-import {- ArrowDown,- Cloud,- Cpu,- Download,- ImageIcon,- Info,- Loader2,- Search,- Sparkles,- Wand2,- X,-} from "lucide-react";+import { ArrowDown, Cloud, Cpu, Download, ImageIcon, Info, Loader2, Search, Sparkles, Wand2, X } from "lucide-react";import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { SidebarTrigger } from "@/components/ui/sidebar";import { EngineSwitch } from "@/components/studio/engine-switch";import { MediaThumb } from "@/components/studio/result-media";-import {- VideoTrimmer,- type VideoTrimmerHandle,-} from "@/components/studio/video-trimmer";+import { VideoTrimmer, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";import { LookCard } from "@/components/shorts/preset-card";import { useSubmitGuard } from "@/components/shorts/hooks";-import {- ClipBar,- ClipDrop,- costText,- Field,- Segmented,- tabKeys,-} from "@/components/shorts/ui";-import {- clipDuration,- useSourceClip,-} from "@/components/shorts/use-source-clip";+import { ClipBar, ClipDrop, costText, Field, Segmented, tabKeys } from "@/components/shorts/ui";+import { clipDuration, useSourceClip } from "@/components/shorts/use-source-clip";import { uploadFile, useEngine } from "@/lib/api";import {clampFps,@@ -58,19 +27,14 @@ import {type MixedResolution,type MixedValues,} from "@/lib/catalog/mixed-media";-import { clipLengthProblem } from "@/lib/catalog/shorts";+import { chainState, clipLengthProblem } from "@/lib/catalog/shorts";import type { RestyleModelInfo } from "@/lib/catalog/shorts-models";import type { Engine, Generation } from "@/lib/catalog/types";import { downloadHref, downloadName } from "@/lib/library";import type { TrimRange } from "@/lib/trim-range";import { cn } from "@/lib/utils";import { MixedHistory } from "./history";-import {- useMixedActions,- useMixedEstimate,- useWatchedGeneration,- type MixedBody,-} from "./hooks";+import { renderSteps, useMixedActions, useMixedEstimate, useWatchedChain, useWatchedGeneration, type MixedBody } from "./hooks";import { AdvancedSettings, loadSaved } from "./settings";type Tab = "presets" | "history" | "how";@@ -81,30 +45,14 @@ const TABS: { id: Tab; label: string }[] = [];const HOW = [- {- step: "Choose a preset",- text: "Browse 33 mixed-media looks — sketch, comic, paper, neon, marble — and pick the one that fits your clip.",- },- {- step: "Upload your video",- text: "Add a clip and trim it to up to 10 seconds. It needs at least 4 frames per second.",- },- {- step: "Customize settings",- text: "Each preset has its own colours, materials and intensity. Save them per preset; they stay in this browser.",- },- {- step: "Generate & preview",- text: "Make one preview frame first to check the look, then render the whole video. The open engine restyles it frame by frame at the rate you pick; cloud models restyle it as smooth video.",- },+ { step: "Choose a preset", text: "Browse 33 mixed-media looks — sketch, comic, paper, neon, marble — and pick the one that fits your clip." },+ { step: "Upload your video", text: "Add a clip and trim it to up to 10 seconds. It needs at least 4 frames per second." },+ { step: "Customize settings", text: "Each preset has its own colours, materials and intensity. Save them per preset; they stay in this browser." },+ { step: "Generate & preview", text: "Make one preview frame first to check the look, then render the whole video. The open engine restyles it frame by frame at the rate you pick; cloud models restyle it as smooth video." },];/** Mixed Media: pick a look, add a ≤10 s clip, tune the settings, preview one frame, render. */-export function MixedStudio({- models,-}: {- models: Record<Engine, RestyleModelInfo[]>;-}) {+export function MixedStudio({ models }: { models: Record<Engine, RestyleModelInfo[]> }) {const [tab, setTab] = useState<Tab>("presets");const [engine, setEngine] = useEngine();useEffect(() => {@@ -123,15 +71,8 @@ export function MixedStudio({<div className="flex min-h-svh min-w-0 flex-col"><header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><SidebarTrigger className="md:hidden" />- <h1 className="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">- Mixed Media- </h1>- <div- role="tablist"- aria-label="Mixed Media"- onKeyDown={tabKeys}- className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4"- >+ <h1 className="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">Mixed Media</h1>+ <div role="tablist" aria-label="Mixed Media" onKeyDown={tabKeys} className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4">{TABS.map((t) => (<buttonkey={t.id}@@ -140,10 +81,7 @@ export function MixedStudio({aria-selected={tab === t.id}tabIndex={tab === t.id ? 0 : -1}onClick={() => pick(t.id)}- className={cn(- "h-7 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground",- tab === t.id && "bg-background text-foreground shadow-soft",- )}+ className={cn("h-7 shrink-0 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground", tab === t.id && "bg-background text-foreground shadow-soft")}>{t.label}</button>@@ -161,16 +99,10 @@ export function MixedStudio({) : (<><div className="mx-auto max-w-[720px] pt-8 pb-6 text-center sm:pt-12">- <p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">- No prompts, just vibe- </p>- <h2 className="mt-2 font-heading text-display text-balance">- Turn any video into mixed-media art- </h2>+ <p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">No prompts, just vibe</p>+ <h2 className="mt-2 font-heading text-display text-balance">Turn any video into mixed-media art</h2><p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">- 33 looks, each with its own colours and materials. Preview one- frame first, then render the clip — frame by frame at the rate- you choose on the open engine.+ 33 looks, each with its own colours and materials. Preview one frame first, then render the clip — frame by frame at the rate you choose on the open engine.</p></div><Workspace engine={engine} models={models[engine]} />@@ -184,15 +116,11 @@ export function MixedStudio({function How({ onStart }: { onStart: () => void }) {return (<div className="mx-auto max-w-[920px] pt-10">- <h2 className="text-center font-heading text-[34px] leading-tight">- How it works- </h2>+ <h2 className="text-center font-heading text-[34px] leading-tight">How it works</h2><ol className="mt-8 grid gap-3 sm:grid-cols-2">{HOW.map((h, i) => (<li key={h.step} className="rounded-2xl border bg-background p-5">- <span className="grid size-7 place-items-center rounded-full bg-primary text-[13px] font-semibold text-primary-foreground">- {i + 1}- </span>+ <span className="grid size-7 place-items-center rounded-full bg-primary text-[13px] font-semibold text-primary-foreground">{i + 1}</span><p className="mt-3 text-[15px] font-semibold">{h.step}</p><p className="mt-1 text-[14px] text-muted-foreground">{h.text}</p></li>@@ -201,19 +129,12 @@ function How({ onStart }: { onStart: () => void }) {<div className="mt-6 rounded-2xl bg-muted/60 p-5 text-[13px] text-muted-foreground"><p className="font-medium text-foreground">Cost</p><p className="mt-1">- On the open engine a render is counted in frames: seconds × frame- rate, rounded down (10 s at 8 FPS = 80 frames), and every frame runs- on your GPU for free. Cloud models restyle the clip as video and are- priced by the model (per second or per video); the estimate shows- before you generate.+ On the open engine a render is counted in frames: seconds × frame rate, rounded down (10 s at 8 FPS = 80 frames), and every frame runs on your GPU for free.+ Cloud models restyle the clip as video and are priced by the model (per second or per video); the estimate shows before you generate.</p></div><div className="mt-6 text-center">- <button- type="button"- onClick={onStart}- className="h-10 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground hover:bg-primary/90"- >+ <button type="button" onClick={onStart} className="h-10 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground hover:bg-primary/90">Choose a preset</button></div>@@ -221,35 +142,19 @@ function How({ onStart }: { onStart: () => void }) {);}-function Workspace({- engine,- models,-}: {- engine: Engine;- models: RestyleModelInfo[];-}) {+function Workspace({ engine, models }: { engine: Engine; models: RestyleModelInfo[] }) {const [presetId, setPresetId] = useState<string | null>(null);const preset = MIXED_PRESETS.find((p) => p.id === presetId) ?? null;const [values, setValues] = useState<MixedValues>({});const [q, setQ] = useState("");const query = useDeferredValue(q.trim().toLowerCase());- const list = useMemo(- () =>- MIXED_PRESETS.filter(- (p) =>- !query || `${p.name} ${p.description}`.toLowerCase().includes(query),- ),- [query],- );+ const list = useMemo(() => MIXED_PRESETS.filter((p) => !query || `${p.name} ${p.description}`.toLowerCase().includes(query)), [query]);const panel = useRef<HTMLElement>(null);const [panelVisible, setPanelVisible] = useState(false);useEffect(() => {const el = panel.current;if (!el) return;- const io = new IntersectionObserver(- ([e]) => setPanelVisible(e.isIntersecting),- { rootMargin: "0px 0px -30% 0px" },- );+ const io = new IntersectionObserver(([e]) => setPanelVisible(e.isIntersecting), { rootMargin: "0px 0px -30% 0px" });io.observe(el);return () => io.disconnect();}, []);@@ -276,13 +181,8 @@ function Workspace({<div className="grid min-w-0 gap-6 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-start"><section aria-labelledby="mm-presets" className="min-w-0 space-y-4"><div className="flex flex-col gap-3 sm:flex-row sm:items-center">- <h3- id="mm-presets"- className="flex items-center gap-2 text-[15px] font-semibold"- >- <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">- 1- </span>+ <h3 id="mm-presets" className="flex items-center gap-2 text-[15px] font-semibold">+ <span className="grid size-6 place-items-center rounded-full bg-primary text-[12px] text-primary-foreground">1</span>Choose a preset</h3><div className="relative w-full sm:ml-auto sm:w-64">@@ -296,12 +196,7 @@ function Workspace({className="h-9 w-full rounded-full border bg-background pr-9 pl-9 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint [&::-webkit-search-cancel-button]:hidden"/>{q && (- <button- type="button"- onClick={() => setQ("")}- aria-label="Clear search"- className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent"- >+ <button type="button" onClick={() => setQ("")} aria-label="Clear search" className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-accent"><X className="size-3.5" /></button>)}@@ -310,62 +205,30 @@ function Workspace({{list.length ? (<div className="grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-4">{list.map((p) => (- <LookCard- key={p.id}- id={p.id}- name={p.name}- description={p.description}- preview={mixedPreview(p)}- hue={p.hue}- selected={presetId === p.id}- onSelect={select}- />+ <LookCard key={p.id} id={p.id} name={p.name} description={p.description} preview={mixedPreview(p)} hue={p.hue} selected={presetId === p.id} onSelect={select} />))}</div>) : (<div className="py-12 text-center">- <p className="font-heading text-[22px]">- No presets match “{q.trim()}”- </p>- <button- type="button"- onClick={() => setQ("")}- className="mt-3 h-8 rounded-full border px-3 text-[13px] font-medium hover:bg-accent"- >+ <p className="font-heading text-[22px]">No presets match “{q.trim()}”</p>+ <button type="button" onClick={() => setQ("")} className="mt-3 h-8 rounded-full border px-3 text-[13px] font-medium hover:bg-accent">Clear search</button></div>)}</section>- <aside- ref={panel}- id="mm-editor"- className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl"- >- <Editor- engine={engine}- models={models}- preset={preset}- values={values}- setValues={setValues}- />+ <aside ref={panel} id="mm-editor" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">+ <Editor engine={engine} models={models} preset={preset} values={values} setValues={setValues} /></aside>{preset && !panelVisible && (<div className="fixed inset-x-3 bottom-[max(0.75rem,env(safe-area-inset-bottom))] z-30 lg:hidden"><buttontype="button"- onClick={() =>- panel.current?.scrollIntoView({- behavior: "smooth",- block: "start",- })- }+ onClick={() => panel.current?.scrollIntoView({ behavior: "smooth", block: "start" })}className="flex h-12 w-full items-center gap-2 rounded-full bg-foreground px-4 text-[14px] font-medium text-background shadow-strong"><Sparkles className="size-4 shrink-0" />- <span className="min-w-0 flex-1 truncate text-left">- {preset.name}- </span>+ <span className="min-w-0 flex-1 truncate text-left">{preset.name}</span><span className="flex shrink-0 items-center gap-1">Add a clip <ArrowDown className="size-4" /></span>@@ -397,86 +260,52 @@ function Editor({// Hand-off: /mixed-media?video=/api/files/… (a result or a Library clip).useEffect(() => {const video = new URLSearchParams(window.location.search).get("video");- if (video?.startsWith("/api/files/"))- source.adopt(video, video.split("/").pop());+ if (video?.startsWith("/api/files/")) source.adopt(video, video.split("/").pop());// Once, on arrival.// eslint-disable-next-line react-hooks/exhaustive-deps}, []);const trimmer = useRef<VideoTrimmerHandle>(null);const [range, setRange] = useState<TrimRange | null>(null);- const [fpsChoice, setFpsChoice] = useState<FpsChoice>(- MIXED.defaultFps as number,- );+ const [fpsChoice, setFpsChoice] = useState<FpsChoice>(MIXED.defaultFps as number);const [manual, setManual] = useState<number>(MIXED.defaultFps);const [resolution, setResolution] = useState<MixedResolution>("1K");- const [pickedModel, setModel] = useState<Record<Engine, string>>({- cloud: "",- open: "",- });+ const [pickedModel, setModel] = useState<Record<Engine, string>>({ cloud: "", open: "" });const modelId = pickedModel[engine] || models[0]?.id;const model = models.find((m) => m.id === modelId);const [previewId, setPreviewId] = useState<string | null>(null);- const [renderId, setRenderId] = useState<string | null>(null);+ // Every step of the latest render (cut → restyle → sound), so a failed step shows its own error.+ const [renderIds, setRenderIds] = useState<string[]>([]);const [anchorOff, setAnchorOff] = useState(false);const [grabbing, setGrabbing] = useState(false);const actions = useMixedActions();const preview = useWatchedGeneration(previewId).data;- const render = useWatchedGeneration(renderId).data;+ const render = useWatchedChain(renderIds);const duration = clipDuration(clip);const sourceFps = clip?.info?.fps;// A choice above the clip's own frame rate drops to the highest one allowed ("Uploaded video has 6 FPS" → 4).const choices = fpsChoices(sourceFps);const allowedFps = choices.filter((c) => !c.disabled);- const fpsShown: FpsChoice =- typeof fpsChoice === "number" &&- choices.find((c) => c.fps === fpsChoice)?.disabled- ? (allowedFps.at(-1)?.fps ?? "manual")- : fpsChoice;+ const fpsShown: FpsChoice = typeof fpsChoice === "number" && choices.find((c) => c.fps === fpsChoice)?.disabled ? (allowedFps.at(-1)?.fps ?? "manual") : fpsChoice;const fps = clampFps(fpsShown === "manual" ? manual : fpsShown, sourceFps);const mmRange = range ? { start: range.startTime, end: range.endTime } : null;const seconds = mmRange ? mmRange.end - mmRange.start : 0;- const problem = mmRange- ? mixedRangeProblem(mmRange, duration, sourceFps)- : null;+ const problem = mmRange ? mixedRangeProblem(mmRange, duration, sourceFps) : null;const frames = mmRange ? mixedFrames(seconds, fps) : 0;// Cloud models restyle the cut as video: the frame rate is the open engine's, and the resolution// is the model's own setting nearest to 1K / 2K / 4K (choices that land on the same one are off).const cloud = engine === "cloud";- const lengthIssue = (m: RestyleModelInfo) =>- cloud && seconds ? clipLengthProblem(m, seconds) : null;+ const lengthIssue = (m: RestyleModelInfo) => (cloud && seconds ? clipLengthProblem(m, seconds) : null);const resOptions = MIXED.resolutions.map((r, i) => {const at = cloud ? nearestResolution(model?.resolutions, r) : undefined;- const prev =- i > 0 && cloud- ? nearestResolution(model?.resolutions, MIXED.resolutions[i - 1])- : undefined;- return {- value: r,- label: r,- hint: at,- disabled: cloud && !!at && at === prev,- title: cloud && at === prev ? `${model?.name} renders up to ${at}` : at,- };+ const prev = i > 0 && cloud ? nearestResolution(model?.resolutions, MIXED.resolutions[i - 1]) : undefined;+ return { value: r, label: r, hint: at, disabled: cloud && !!at && at === prev, title: cloud && at === prev ? `${model?.name} renders up to ${at}` : at };});- const showResolution =- !cloud || resOptions.some((o) => o.hint && !o.disabled && o.value !== "1K");- const resShown: MixedResolution = resOptions.find(- (o) => o.value === resolution,- )?.disabled- ? ([...resOptions].reverse().find((o) => !o.disabled)?.value ?? "1K")- : resolution;- const modelRes = cloud- ? nearestResolution(model?.resolutions, resShown)- : undefined;- const previewImage =- preview?.status === "succeeded"- ? preview.outputs.find((o) => o.kind === "image")- : undefined;- const anchor =- engine === "cloud" && model?.image && previewImage && !anchorOff- ? previewImage.url- : undefined;+ const showResolution = !cloud || resOptions.some((o) => o.hint && !o.disabled && o.value !== "1K");+ const resShown: MixedResolution = resOptions.find((o) => o.value === resolution)?.disabled ? ([...resOptions].reverse().find((o) => !o.disabled)?.value ?? "1K") : resolution;+ const modelRes = cloud ? nearestResolution(model?.resolutions, resShown) : undefined;+ const previewImage = preview?.status === "succeeded" ? preview.outputs.find((o) => o.kind === "image") : undefined;+ const anchor = engine === "cloud" && model?.image && previewImage && !anchorOff ? previewImage.url : undefined;const body: MixedBody | null =preset && mmRange && !problem@@ -484,12 +313,7 @@ function Editor({engine,presetId: preset.id,values,- source: {- url: clip?.url ?? "/api/files/placeholder.mp4",- name: clip?.name,- duration,- fps: sourceFps,- },+ source: { url: clip?.url ?? "/api/files/placeholder.mp4", name: clip?.name, duration, fps: sourceFps },range: mmRange,fps,resolution: resShown,@@ -535,8 +359,7 @@ function Editor({const renderGuard = useSubmitGuard();const previewBusy = actions.preview.isPending || grabbing;const makePreview = () => {- if (blocker || !body)- return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });if (previewBusy) return;void previewGuard(JSON.stringify(body), async (requestId) => {let frameUrl: string | undefined;@@ -544,41 +367,25 @@ function Editor({setGrabbing(true);try {const blob = await trimmer.current?.grabFrame(range!.startTime);- if (!blob)- throw new Error(- "This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video",- );- frameUrl = (- await uploadFile(- new File([blob], "frame.jpg", { type: "image/jpeg" }),- )- ).url;+ if (!blob) throw new Error("This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video");+ frameUrl = (await uploadFile(new File([blob], "frame.jpg", { type: "image/jpeg" }))).url;} finally {setGrabbing(false);}}- const g = await actions.preview.mutateAsync({- ...body,- frameUrl,- requestId,- });+ const g = await actions.preview.mutateAsync({ ...body, frameUrl, requestId });setPreviewId(g.id);}).catch((e: Error) => toast.error(e.message));};const generate = () => {- if (blocker || !body)- return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });if (actions.render.isPending) return;- void renderGuard(JSON.stringify(body), (requestId) =>- actions.render.mutateAsync({ ...body, requestId }),- )+ void renderGuard(JSON.stringify(body), (requestId) => actions.render.mutateAsync({ ...body, requestId })).then((r) => {if (!r) return;- setRenderId(r.final.id);- toast("Rendering your video", {- description: "It shows up in History too.",- });+ setRenderIds(r.items.map((g) => g.id));+ toast("Rendering your video", { description: "It shows up in History too." });}).catch((e: Error) => toast.error(e.message));};@@ -589,10 +396,7 @@ function Editor({<Sparkles className="mt-0.5 size-4 shrink-0 text-brand-text" />{preset ? (<span className="min-w-0">- <span className="font-medium">{preset.name}</span>{" "}- <span className="text-muted-foreground">- · {preset.description}- </span>+ <span className="font-medium">{preset.name}</span> <span className="text-muted-foreground">· {preset.description}</span></span>) : (<span className="text-muted-foreground">Pick a preset to start</span>@@ -632,34 +436,20 @@ function Editor({max={MIXED.maxSeconds}duration={clip.info?.duration}label="Part of the clip to transform"- onMeta={(m) => source.setBrowserDuration(m.duration)}+ onMeta={source.setBrowserMeta}/></div>)}</Field>{!cloud && (- <Field- label="Frame rate"- hint={- sourceFps- ? `Uploaded video has ${Math.round(sourceFps)} FPS`- : "8 FPS is the classic stop-motion look"- }- >+ <Field label="Frame rate" hint={sourceFps ? `Uploaded video has ${Math.round(sourceFps)} FPS` : "8 FPS is the classic stop-motion look"}><Segmented<FpsChoice>label="Frame rate"value={fpsShown}onChange={setFpsChoice}options={[- ...choices.map((c) => ({- value: c.fps as FpsChoice,- label: String(c.fps),- disabled: c.disabled,- title: c.disabled- ? "Above the clip's own frame rate"- : `${c.fps} FPS`,- })),+ ...choices.map((c) => ({ value: c.fps as FpsChoice, label: String(c.fps), disabled: c.disabled, title: c.disabled ? "Above the clip's own frame rate" : `${c.fps} FPS` })),{ value: "manual" as FpsChoice, label: "Manual" },]}/>@@ -669,59 +459,27 @@ function Editor({<inputtype="number"min={MIXED.manualFps.min}- max={Math.min(- MIXED.manualFps.max,- sourceFps ? Math.floor(sourceFps) : MIXED.manualFps.max,- )}+ max={Math.min(MIXED.manualFps.max, sourceFps ? Math.floor(sourceFps) : MIXED.manualFps.max)}value={manual}- onChange={(e) =>- setManual(Number(e.target.value) || MIXED.manualFps.min)- }+ onChange={(e) => setManual(Number(e.target.value) || MIXED.manualFps.min)}aria-label="Frames per second"className="h-7 w-16 rounded-md border bg-background px-2 font-mono text-[12px] text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"/>FPS</label>)}- {fps !== (fpsShown === "manual" ? manual : fpsShown) && (- <p className="text-[12px] text-warning">- Using {fps} FPS — the clip itself has no more frames than that.- </p>- )}- {fpsShown !== fpsChoice && (- <p className="text-[12px] text-muted-foreground">- Using {fps} FPS — {fpsChoice} is above the clip's own frame- rate.- </p>- )}+ {fps !== (fpsShown === "manual" ? manual : fpsShown) && <p className="text-[12px] text-warning">Using {fps} FPS — the clip itself has no more frames than that.</p>}+ {fpsShown !== fpsChoice && <p className="text-[12px] text-muted-foreground">Using {fps} FPS — {fpsChoice} is above the clip's own frame rate.</p>}</Field>)}{showResolution && (- <Field- label="Resolution"- hint={- cloud && modelRes- ? `${model?.name} renders at ${modelRes}`- : undefined- }- >- <Segmented<MixedResolution>- label="Resolution"- value={resShown}- onChange={setResolution}- options={resOptions}- />+ <Field label="Resolution" hint={cloud && modelRes ? `${model?.name} renders at ${modelRes}` : undefined}>+ <Segmented<MixedResolution> label="Resolution" value={resShown} onChange={setResolution} options={resOptions} /></Field>)}- {preset && (- <AdvancedSettings- preset={preset}- values={values}- onChange={setValues}- />- )}+ {preset && <AdvancedSettings preset={preset} values={values} onChange={setValues} />}<Fieldlabel="Model"@@ -738,17 +496,12 @@ function Editor({}>{models.length > 1 ? (- <Select- value={modelId}- onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}- >+ <Select value={modelId} onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}><SelectTrigger className="w-full" aria-label="Model"><SelectValue><span className="flex min-w-0 items-center gap-2"><span className="truncate">{model?.name}</span>- <span className="shrink-0 font-mono text-[11px] text-muted-foreground">- {model?.price}- </span>+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{model?.price}</span></span></SelectValue></SelectTrigger>@@ -756,23 +509,13 @@ function Editor({{models.map((m) => {const issue = lengthIssue(m);return (- <SelectItem- key={m.id}- value={m.id}- disabled={!!issue && m.id !== modelId}- >+ <SelectItem key={m.id} value={m.id} disabled={!!issue && m.id !== modelId}><span className="flex min-w-0 flex-col"><span className="flex min-w-0 items-center gap-2"><span className="truncate">{m.name}</span>- <span className="shrink-0 font-mono text-[11px] text-muted-foreground">- {m.price}- </span>+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">{m.price}</span></span>- {issue && (- <span className="text-[11px] text-muted-foreground">- {issue}- </span>- )}+ {issue && <span className="text-[11px] text-muted-foreground">{issue}</span>}</span></SelectItem>);@@ -781,57 +524,35 @@ function Editor({</Select>) : (<div className="rounded-lg border px-3 py-2 text-[13px]">- <span className="font-medium">{model?.name ?? "—"}</span>{" "}- <span className="text-muted-foreground">· {model?.price}</span>+ <span className="font-medium">{model?.name ?? "—"}</span> <span className="text-muted-foreground">· {model?.price}</span></div>)}- {model && (- <p className="text-[12px] leading-snug text-muted-foreground">- {model.tagline}- </p>- )}+ {model && <p className="text-[12px] leading-snug text-muted-foreground">{model.tagline}</p>}</Field><div className="space-y-2 rounded-xl border p-3"><div className="flex items-center justify-between gap-2"><span className="text-[13px] font-medium">Preview frame</span>- <span className="font-mono text-[12px] text-muted-foreground tabular-nums">- Preview costs:{" "}- {est- ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine)- : "—"}- </span>+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">Preview costs: {est ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine) : "—"}</span></div>- <p className="text-[12px] text-muted-foreground">- Generate one frame with your current settings before creating the full- video.- </p>+ <p className="text-[12px] text-muted-foreground">Generate one frame with your current settings before creating the full video.</p>{preview && (<div className="relative mx-auto aspect-video w-full max-w-[320px] overflow-hidden rounded-lg bg-muted">{preview.status === "succeeded" && preview.outputs[0] ? (<MediaThumb output={preview.outputs[0]} fit />) : preview.status === "failed" || preview.status === "canceled" ? (- <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">- {preview.error ?? "Canceled"}- </div>+ <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">{preview.error ?? "Canceled"}</div>) : (<div className="skeleton-sweep grid size-full animate-skeleton place-items-center">- <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">- Restyling one frame…- </span>+ <span className="shimmer-text animate-shimmer-text text-[12px] font-medium">Restyling one frame…</span></div>)}</div>)}{anchor && (<p className="flex items-center gap-1.5 text-[12px] text-brand-text">- <Wand2 className="size-3.5 shrink-0" /> {model?.name} follows this- frame for the whole video- <button- type="button"- onClick={() => setAnchorOff(true)}- className="ml-auto text-muted-foreground underline-offset-2 hover:underline"- >+ <Wand2 className="size-3.5 shrink-0" /> {model?.name} follows this frame for the whole video+ <button type="button" onClick={() => setAnchorOff(true)} className="ml-auto text-muted-foreground underline-offset-2 hover:underline">Don't use it</button></p>@@ -843,46 +564,32 @@ function Editor({aria-disabled={!!blocker || previewBusy}className={cn("flex h-9 w-full items-center justify-center gap-2 rounded-full border text-[13px] font-medium",- blocker- ? "text-subtle-foreground"- : "bg-background hover:bg-accent",+ blocker ? "text-subtle-foreground" : "bg-background hover:bg-accent",)}>- {previewBusy ? (- <Loader2 className="size-4 animate-spin" />- ) : (- <ImageIcon className="size-4" />- )}- {preview- ? "Generate another preview frame"- : "Generate preview frame"}+ {previewBusy ? <Loader2 className="size-4 animate-spin" /> : <ImageIcon className="size-4" />}+ {preview ? "Generate another preview frame" : "Generate preview frame"}</button></div><div className="space-y-3 border-t pt-4"><div className="flex items-baseline justify-between gap-2"><span className="text-[13px] text-muted-foreground">- {!mmRange- ? "Estimate"- : cloud- ? `${seconds.toFixed(1)} s${modelRes ? ` · ${modelRes}` : ""}`- : `${frames} frames · ${fps} FPS`}+ {!mmRange ? "Estimate" : cloud ? `${seconds.toFixed(1)} s${modelRes ? ` · ${modelRes}` : ""}` : `${frames} frames · ${fps} FPS`}</span>- <span- className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums"- aria-live="polite"- >- {estimate.isFetching && (- <Loader2 className="size-3 animate-spin text-muted-foreground" />- )}+ <span className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums" aria-live="polite">+ {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" />}{body ? costText(est, engine) : "—"}</span></div>+ {clip?.url && !clip.uploading && !clip.error && clip.info && clip.info.hasAudio === undefined && (+ <p className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground">+ <Info className="mt-0.5 size-3.5 shrink-0" />+ Couldn't read this clip's sound track — it's made without sound.+ </p>+ )}{est?.notes.map((n) => (- <p- key={n}- className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground"- >+ <p key={n} className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground"><Info className="mt-0.5 size-3.5 shrink-0" />{n}</p>@@ -895,67 +602,50 @@ function Editor({aria-describedby={blocker ? "mm-blocker" : undefined}className={cn("flex h-11 w-full items-center justify-center gap-2 rounded-full text-[14px] font-medium transition-colors",- blocker- ? "bg-muted text-subtle-foreground"- : "bg-primary text-primary-foreground hover:bg-primary/90",+ blocker ? "bg-muted text-subtle-foreground" : "bg-primary text-primary-foreground hover:bg-primary/90",)}>- {actions.render.isPending ? (- <Loader2 className="size-4 animate-spin" />- ) : (- <Sparkles className="size-4" />- )}+ {actions.render.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}Generate video</button>{blocker && (- <p- id="mm-blocker"- className="text-center text-[12px] text-muted-foreground"- >+ <p id="mm-blocker" className="text-center text-[12px] text-muted-foreground">{blocker}</p>)}- {render && <LatestRender g={render} />}+ {render.length > 0 && <LatestRender chain={render} />}</div></div>);}-function LatestRender({ g }: { g: Generation }) {- const out =- g.status === "succeeded"- ? g.outputs.find((o) => o.kind === "video")- : undefined;+/** The latest render: its steps' progress, the failing step's own error, or the video. */+function LatestRender({ chain }: { chain: (Generation | undefined)[] }) {+ const g = chain[chain.length - 1];+ // Steps still loading read as working, not as deleted.+ const state = chain.some((x) => !x) ? ({ status: "working", label: "Rendering", progress: 0 } as const) : chainState(renderSteps(chain));+ const out = g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined;return (<div className="space-y-2 rounded-xl bg-muted/50 p-3" aria-live="polite"><p className="text-[13px] font-medium">Your video</p><div className="relative mx-auto aspect-video w-full overflow-hidden rounded-lg bg-muted">{out ? (- <video- src={out.url}- controls- playsInline- preload="metadata"- className="size-full bg-black object-contain"- />- ) : g.status === "failed" || g.status === "canceled" ? (- <div className="grid size-full place-items-center p-3 text-center text-[12px] text-muted-foreground">- {g.error ?? "Canceled"}+ <video src={out.url} controls playsInline preload="metadata" className="size-full bg-black object-contain" />+ ) : state.status === "failed" || state.status === "gone" ? (+ <div className="flex size-full flex-col justify-center gap-1 p-3 text-center">+ <p className="text-[13px] font-medium">{state.label}</p>+ {state.error && <p className="line-clamp-4 text-[12px] break-words text-muted-foreground">{state.error}</p>}</div>) : (<div className="skeleton-sweep grid size-full animate-skeleton place-items-center"><span className="shimmer-text animate-shimmer-text text-[12px] font-medium">- {g.message ?? "Rendering…"}+ {g ? `${state.label}… ${Math.round(state.progress * 100)}%` : "Rendering…"}</span></div>)}</div>- {out && (- <a- href={downloadHref(out.url, downloadName(g, out, 0))}- download={downloadName(g, out, 0)}- className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent"- >+ {out && g && (+ <a href={downloadHref(out.url, downloadName(g, out, 0))} download={downloadName(g, out, 0)} className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent"><Download className="size-3.5" /> Download</a>)}diff --git a/src/components/mixed-media/settings.tsx b/src/components/mixed-media/settings.tsxindex 4dd7c48c..0e3bb1b6 100644--- a/src/components/mixed-media/settings.tsx+++ b/src/components/mixed-media/settings.tsx@@ -4,7 +4,7 @@ import { RotateCcw, Save } from "lucide-react";import { useCallback, useId, useState, useSyncExternalStore } from "react";import { toast } from "sonner";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";-import { cleanValues, defaultValues, type MixedPreset, type MixedSetting, type MixedValues } from "@/lib/catalog/mixed-media";+import { cleanValues, defaultValues, parseHex, type MixedPreset, type MixedSetting, type MixedValues } from "@/lib/catalog/mixed-media";/*** Per-preset advanced settings (Higgsfield's param_configs): colours (or "describe the colour"),@@ -93,22 +93,50 @@ function ColorSetting({ s, value, onChange }: { s: Extract<MixedSetting, { type:) : (<div className="flex items-center gap-2"><input id={id} type="color" value={value} onChange={(e) => onChange(e.target.value.toLowerCase())} className="h-8 w-10 cursor-pointer rounded-md border bg-background p-0.5" />- <input- aria-label={`${s.label} (hex)`}- value={value.toUpperCase()}- onChange={(e) => {- const v = e.target.value.trim();- if (/^#[0-9a-f]{6}$/i.test(v)) onChange(v.toLowerCase());- }}- maxLength={7}- className="h-8 w-24 rounded-lg border bg-background px-2 font-mono text-[12px] uppercase outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"- />+ <HexField label={`${s.label} (hex)`} value={value} onChange={onChange} /></div>)}</div>);}+/**+ * A hex code field you can type into: the draft is shown while editing, a complete code is applied+ * as soon as it's typed ("#" optional), and leaving (or Escape) with an incomplete one puts the+ * current colour back.+ */+function HexField({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {+ const [draft, setDraft] = useState<string | null>(null);+ const shown = draft ?? value.toUpperCase();+ const invalid = draft !== null && draft.trim() !== "" && !parseHex(draft) && draft.replace(/^#/, "").length >= 6;+ return (+ <input+ aria-label={label}+ aria-invalid={invalid || undefined}+ value={shown}+ spellCheck={false}+ autoComplete="off"+ onChange={(e) => {+ const v = e.target.value.slice(0, 7);+ setDraft(v);+ const hex = /^#?[0-9a-f]{6}$/i.test(v.trim()) ? parseHex(v) : null;+ if (hex && hex !== value) onChange(hex);+ }}+ onBlur={() => {+ const hex = draft !== null ? parseHex(draft) : null;+ if (hex && hex !== value) onChange(hex);+ setDraft(null);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ else if (e.key === "Escape") setDraft(null);+ }}+ maxLength={7}+ className="h-8 w-24 rounded-lg border bg-background px-2 font-mono text-[12px] uppercase outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint aria-invalid:border-destructive"+ />+ );+}+function SelectSetting({ s, value, onChange }: { s: Extract<MixedSetting, { type: "select" }>; value: string; onChange: (v: string) => void }) {const id = useId();const custom = value.startsWith("text:");diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.tsindex 0a554615..0614a91d 100644--- a/src/components/shorts/hooks.ts+++ b/src/components/shorts/hooks.ts@@ -22,7 +22,7 @@ export const send = async <T>(url: string, method: string, body?: unknown) =>export interface ShortsBody {engine: Engine;presetId: string;- source: { url: string; name?: string; duration?: number };+ source: { url: string; name?: string; duration?: number; width?: number; height?: number };range: ShortsRange;aspectRatio: ShortsRatio;language: string;@@ -103,7 +103,7 @@ export function useShortsEstimate(body: ShortsBody | null) {export function useShortsSessions() {const qc = useQueryClient();const connected = useGenerationEvents((ev) => {- if (ev.type === "generation" && ev.generation.feature === "shorts") void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] });+ if (ev.type === "generation" && ev.generation.feature.startsWith("shorts")) void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] });});return useQuery({queryKey: ["shorts", "sessions"],diff --git a/src/components/shorts/look-motif.tsx b/src/components/shorts/look-motif.tsxnew file mode 100644index 00000000..06fe7ea0--- /dev/null+++ b/src/components/shorts/look-motif.tsx@@ -0,0 +1,576 @@+/**+ * A small motif drawn over a look card's procedural preview, so presets that share a treatment+ * (halftone, pop, grade) still read apart at a glance: lettering on the type presets, scribbles on+ * the doodle ones, paper grain, a blueprint grid, comic panels, a desktop window, a film look…+ * Static SVG and CSS filters (no images, no animation), aria-hidden. Shared by Shorts Studio and+ * Mixed Media (keyed by preset id).+ */+import { useId } from "react";++type Motif =+ | { kind: "type"; style: "sticker" | "balloon" | "caption" | "kinetic" | "neon" | "stacked"; text: string }+ | { kind: "scribble" | "highlight" | "graffiti" | "polka" | "hearts" | "stars" | "pattern" | "collage" | "desktop" | "bbox" | "circuit" | "chrome" | "mascot" | "clay" | "comic" | "burst" | "frame" | "blueprint" | "pop" | "fragments" | "particles" | "bubbles" | "origami" | "magazine" | "mirror" | "marble" | "tracking"; text?: string }+ | { kind: "paper" | "watercolor" | "pencil" | "film" | "noir" }+ | { kind: "grade"; filter: string };++const MOTIFS: Record<string, Motif> = {+ // Shorts Studio+ "shorts-bold-urban": { kind: "grade", filter: "contrast(1.35) saturate(1.5)" },+ "shorts-green-contrast": { kind: "grade", filter: "contrast(1.45) hue-rotate(-25deg) saturate(1.2)" },+ "shorts-urban-serenity": { kind: "grade", filter: "saturate(0.55) brightness(1.12) contrast(0.9)" },+ "shorts-warm-glow": { kind: "grade", filter: "sepia(0.35) saturate(1.35) brightness(1.08)" },+ "shorts-yellow-frame": { kind: "frame" },+ "shorts-monochrome-vibes": { kind: "film" },+ "shorts-claymation": { kind: "clay" },+ "shorts-marker-scribble": { kind: "scribble" },+ "shorts-sticker-type": { kind: "type", style: "sticker", text: "WOW!" },+ "shorts-blue-comic": { kind: "comic", text: "ZAP!" },+ "shorts-red-graffiti": { kind: "graffiti" },+ "shorts-watercolor": { kind: "watercolor" },+ "shorts-pencil-sketch": { kind: "pencil" },+ "shorts-desktop": { kind: "desktop" },+ "shorts-acid-green": { kind: "grade", filter: "hue-rotate(70deg) saturate(1.9) contrast(1.15)" },+ "shorts-balloon-type": { kind: "type", style: "balloon", text: "YAY" },+ "shorts-blueprint": { kind: "blueprint" },+ "shorts-bold-caption": { kind: "type", style: "caption", text: "AND THEN…" },+ "shorts-bounding-box": { kind: "bbox" },+ "shorts-circuit": { kind: "circuit" },+ "shorts-comic-burst": { kind: "burst", text: "BAM!" },+ "shorts-comic-pop": { kind: "comic", text: "POW!" },+ "shorts-pink-wash": { kind: "grade", filter: "sepia(0.25) hue-rotate(-45deg) saturate(1.5) brightness(1.05)" },+ "shorts-gold-stars": { kind: "stars" },+ "shorts-graffiti": { kind: "graffiti", text: "tag" },+ "shorts-green-doodle": { kind: "scribble" },+ "shorts-green-pop": { kind: "pop" },+ "shorts-heart-pop": { kind: "hearts" },+ "shorts-kinetic-type": { kind: "type", style: "kinetic", text: "GO BIG NOW" },+ "shorts-liquid-chrome": { kind: "chrome" },+ "shorts-mascot": { kind: "mascot" },+ "shorts-neon-pop": { kind: "pop" },+ "shorts-neon-type": { kind: "type", style: "neon", text: "LIVE" },+ "shorts-patterned": { kind: "pattern" },+ "shorts-pink-pop": { kind: "pop" },+ "shorts-pink-scribble": { kind: "scribble" },+ "shorts-polka-pop": { kind: "polka" },+ "shorts-retro-collage": { kind: "collage" },+ "shorts-stacked-type": { kind: "type", style: "stacked", text: "BIG BOLD LOUD" },+ "shorts-star-comic": { kind: "stars", text: "comic" },+ "shorts-street-art": { kind: "graffiti" },+ "shorts-vintage-paper": { kind: "paper" },+ "shorts-yellow-burst": { kind: "burst", text: "YES!" },+ "shorts-yellow-doodle": { kind: "highlight" },+ // Mixed Media+ "mixed-layer-mixed-media": { kind: "collage" },+ "mixed-sketch": { kind: "pencil" },+ "mixed-canvas": { kind: "watercolor" },+ "mixed-flash-comic": { kind: "burst", text: "FLASH" },+ "mixed-overexposed": { kind: "grade", filter: "brightness(1.45) contrast(1.25) saturate(0.8)" },+ "mixed-paper": { kind: "paper" },+ "mixed-noir": { kind: "noir" },+ "mixed-particles": { kind: "particles" },+ "mixed-hand-paint": { kind: "watercolor" },+ "mixed-tracking": { kind: "tracking" },+ "mixed-windows": { kind: "desktop" },+ "mixed-acid": { kind: "grade", filter: "hue-rotate(110deg) saturate(2.2) contrast(1.2)" },+ "mixed-palette": { kind: "collage" },+ "mixed-comic": { kind: "comic", text: "POW!" },+ "mixed-multiverse": { kind: "fragments" },+ "mixed-fragments": { kind: "fragments" },+ "mixed-vintage": { kind: "paper" },+ "mixed-magazine": { kind: "magazine" },+ "mixed-lsd": { kind: "grade", filter: "hue-rotate(200deg) saturate(2.4)" },+ "mixed-broken-mirror": { kind: "mirror" },+ "mixed-marble": { kind: "marble" },+ "mixed-toxic": { kind: "grade", filter: "hue-rotate(80deg) saturate(2.4) contrast(1.3)" },+ "mixed-ultraviolet": { kind: "grade", filter: "hue-rotate(250deg) saturate(1.8) contrast(1.2) brightness(0.9)" },+ "mixed-akrill": { kind: "collage" },+ "mixed-two-color": { kind: "grade", filter: "grayscale(1) contrast(2.2)" },+ "mixed-origami": { kind: "origami" },+ "mixed-random-glow": { kind: "particles" },+ "mixed-cannabis": { kind: "magazine" },+ "mixed-bubbles": { kind: "bubbles" },+ "mixed-cold-vision": { kind: "grade", filter: "hue-rotate(190deg) saturate(1.3) contrast(1.25) brightness(0.92)" },+ "mixed-modern": { kind: "origami" },+ "mixed-lava": { kind: "grade", filter: "sepia(0.6) hue-rotate(-30deg) saturate(2.2) contrast(1.2)" },+ "mixed-ocean": { kind: "grade", filter: "sepia(0.3) hue-rotate(160deg) saturate(1.6)" },+};++const BOX = "absolute inset-0 size-full pointer-events-none";+const ink = (hue: number, l = 0.7, c = 0.19) => `oklch(${l} ${c} ${hue})`;++/** A backdrop filter over the preview (a grade, black and white). */+function Filter({ filter, children }: { filter: string; children?: React.ReactNode }) {+ return (+ <div className={BOX} style={{ backdropFilter: filter, WebkitBackdropFilter: filter }}>+ {children}+ </div>+ );+}++function Svg({ children }: { children: React.ReactNode }) {+ return (+ <svg className={BOX} viewBox="0 0 80 100" preserveAspectRatio="xMidYMid slice" aria-hidden>+ {children}+ </svg>+ );+}++const grain = (u: string) => (+ <pattern id={`${u}-grain`} width="3" height="3" patternUnits="userSpaceOnUse">+ <circle cx="0.6" cy="0.8" r="0.35" fill="#000" opacity="0.18" />+ <circle cx="2.1" cy="2.2" r="0.3" fill="#fff" opacity="0.25" />+ </pattern>+);++function TypeMotif({ style, text, hue, u }: { style: Extract<Motif, { kind: "type" }>["style"]; text: string; hue: number; u: string }) {+ const font = { fontFamily: "var(--font-heading, system-ui), system-ui, sans-serif", fontWeight: 900 } as const;+ if (style === "sticker")+ return (+ <Svg>+ <g transform="rotate(-8 40 32)">+ <rect x="13" y="20" width="54" height="22" rx="6" fill="#fff" stroke="#111" strokeWidth="1.2" />+ <text x="40" y="36.5" textAnchor="middle" fontSize="15" fill={ink(hue, 0.6, 0.24)} style={font}>+ {text}+ </text>+ </g>+ <circle cx="66" cy="76" r="7" fill="#ffd43b" stroke="#fff" strokeWidth="2" />+ <circle cx="64" cy="74.5" r="0.9" fill="#111" />+ <circle cx="68" cy="74.5" r="0.9" fill="#111" />+ <path d="M63 78 q3 2.5 6 0" stroke="#111" strokeWidth="0.9" fill="none" strokeLinecap="round" />+ </Svg>+ );+ if (style === "balloon")+ return (+ <Svg>+ <text x="40" y="40" textAnchor="middle" fontSize="24" fill={ink(hue, 0.78, 0.17)} stroke="#fff" strokeWidth="3.2" strokeLinejoin="round" paintOrder="stroke" style={{ ...font, letterSpacing: -1 }}>+ {text}+ </text>+ <ellipse cx="33" cy="30" rx="3" ry="1.4" fill="#fff" opacity="0.7" />+ </Svg>+ );+ if (style === "caption")+ return (+ <Svg>+ <text x="40" y="82" textAnchor="middle" fontSize="9" fill="#fff" stroke="#000" strokeWidth="1.6" strokeLinejoin="round" paintOrder="stroke" style={font}>+ {text}+ </text>+ <rect x="22" y="85.5" width="36" height="2.2" rx="1.1" fill={ink(hue, 0.82, 0.18)} />+ </Svg>+ );+ if (style === "neon")+ return (+ <Svg>+ <defs>+ <filter id={`${u}-neon`} x="-30%" y="-30%" width="160%" height="160%">+ <feGaussianBlur stdDeviation="1.6" result="b" />+ <feMerge>+ <feMergeNode in="b" />+ <feMergeNode in="b" />+ <feMergeNode in="SourceGraphic" />+ </feMerge>+ </filter>+ </defs>+ <text x="40" y="34" textAnchor="middle" fontSize="18" fill="none" stroke={ink(hue, 0.85, 0.2)} strokeWidth="1.3" filter={`url(#${u}-neon)`} style={{ ...font, fontWeight: 700, letterSpacing: 2 }}>+ {text}+ </text>+ </Svg>+ );+ const words = text.split(" ");+ if (style === "kinetic")+ return (+ <Svg>+ {words.map((w, i) => (+ <text key={w} x={16 + i * 14} y={28 + i * 13} fontSize={12 - i * 1.5} fill={i === 1 ? ink(hue, 0.85, 0.2) : "#fff"} stroke="#000" strokeWidth="1" paintOrder="stroke" transform={`rotate(${-10 + i * 7} ${16 + i * 14} ${28 + i * 13})`} style={font}>+ {w}+ </text>+ ))}+ </Svg>+ );+ return (+ <Svg>+ {words.map((w, i) => (+ <text key={w} x="40" y={30 + i * 16} textAnchor="middle" fontSize="17" textLength="66" lengthAdjust="spacingAndGlyphs" fill={i === 1 ? ink(hue, 0.85, 0.2) : "#fff"} opacity="0.95" style={{ ...font, letterSpacing: -0.5 }}>+ {w}+ </text>+ ))}+ </Svg>+ );+}++function Draw({ m, hue, u }: { m: Motif; hue: number; u: string }) {+ const c = ink(hue);+ switch (m.kind) {+ case "type":+ return <TypeMotif style={m.style} text={m.text} hue={hue} u={u} />;+ case "grade":+ return <Filter filter={m.filter} />;+ case "film":+ case "noir":+ return (+ <Filter filter={m.kind === "noir" ? "grayscale(1) contrast(1.6) brightness(0.8)" : "grayscale(1) contrast(1.25)"}>+ <Svg>+ {grain(u)}+ <rect width="80" height="100" fill={`url(#${u}-grain)`} />+ {m.kind === "noir" ? (+ <g fill="#000" opacity="0.35">+ {Array.from({ length: 6 }, (_, i) => (+ <rect key={i} x="-10" y={i * 18} width="100" height="7" transform="rotate(-18 40 50)" />+ ))}+ </g>+ ) : (+ <path d="M18 0 L19 100 M61 0 L60.5 100" stroke="#fff" strokeWidth="0.3" opacity="0.5" />+ )}+ </Svg>+ </Filter>+ );+ case "pencil":+ return (+ <Filter filter="grayscale(1) contrast(1.4) brightness(1.15)">+ <Svg>+ <g stroke="#333" strokeWidth="0.35" opacity="0.45">+ {Array.from({ length: 22 }, (_, i) => (+ <path key={i} d={`M${i * 5 - 20} 100 L${i * 5 + 10} 0`} />+ ))}+ </g>+ <path d="M8 90 q20 -6 34 -2 t30 -3" stroke="#222" strokeWidth="0.8" fill="none" strokeLinecap="round" />+ </Svg>+ </Filter>+ );+ case "paper":+ return (+ <Filter filter="sepia(0.55) contrast(0.95) brightness(1.05)">+ <Svg>+ {grain(u)}+ <rect width="80" height="100" fill={`url(#${u}-grain)`} />+ <path d="M0 37 L80 41 M44 0 L41 100" stroke="#5b4630" strokeWidth="0.5" opacity="0.35" />+ <rect x="1.5" y="1.5" width="77" height="97" fill="none" stroke="#5b4630" strokeWidth="1.2" opacity="0.25" />+ </Svg>+ </Filter>+ );+ case "watercolor":+ return (+ <Filter filter="saturate(1.2) contrast(0.92) brightness(1.06)">+ <Svg>+ {grain(u)}+ <g opacity="0.35" style={{ mixBlendMode: "multiply" }}>+ <ellipse cx="18" cy="22" rx="20" ry="14" fill={ink(hue, 0.78, 0.14)} />+ <ellipse cx="62" cy="70" rx="24" ry="17" fill={ink(hue + 120, 0.8, 0.13)} />+ <ellipse cx="28" cy="86" rx="16" ry="9" fill={ink(hue + 220, 0.82, 0.12)} />+ </g>+ <rect width="80" height="100" fill={`url(#${u}-grain)`} />+ </Svg>+ </Filter>+ );+ case "scribble":+ return (+ <Svg>+ <g fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">+ <path d="M14 18 c6 -8 14 -2 10 4 s-12 4 -6 10" />+ <path d="M58 14 l3 6 l6 1 l-5 4 l1 6 l-5 -3 l-5 3 l1 -6 l-4 -4 l6 -1z" />+ <path d="M10 70 q10 -10 18 -2 M24 64 l4 6 l-7 1" />+ <path d="M54 84 c4 -6 10 -6 14 0 c-4 6 -10 6 -14 0z" />+ <path d="M60 46 q4 -4 8 0 q4 4 8 0" />+ </g>+ </Svg>+ );+ case "highlight":+ return (+ <Svg>+ <g fill="none" stroke="oklch(0.92 0.2 100)" strokeLinecap="round" opacity="0.75">+ <path d="M10 22 q20 -4 34 2" strokeWidth="5" />+ <path d="M40 86 q14 -3 30 0" strokeWidth="5" />+ </g>+ <g fill="none" stroke="oklch(0.86 0.19 95)" strokeWidth="1.6" strokeLinecap="round">+ <path d="M64 14 v8 M60 18 h8 M14 54 v6 M11 57 h6 M66 56 l4 -4 M62 64 c6 2 10 -2 8 -6" />+ </g>+ </Svg>+ );+ case "graffiti":+ return (+ <Svg>+ <g fill={ink(hue, 0.6, 0.23)}>+ {[14, 30, 52, 66].map((x, i) => (+ <g key={x}>+ <rect x={x} y="0" width="3" height={14 + ((i * 7) % 12)} rx="1.5" />+ <circle cx={x + 1.5} cy={15 + ((i * 7) % 12)} r="2" />+ </g>+ ))}+ </g>+ <path d="M10 80 c8 -12 14 6 20 -6 s10 10 18 -4 s8 8 20 -2" fill="none" stroke={ink(hue, 0.6, 0.23)} strokeWidth="3" strokeLinecap="round" />+ {m.text && (+ <text x="58" y="94" fontSize="9" fill="#fff" stroke="#111" strokeWidth="0.8" paintOrder="stroke" fontStyle="italic" style={{ fontWeight: 900 }}>+ {m.text}+ </text>+ )}+ </Svg>+ );+ case "polka":+ return (+ <Svg>+ <pattern id={`${u}-polka`} width="10" height="10" patternUnits="userSpaceOnUse">+ <circle cx="5" cy="5" r="2.2" fill={c} />+ </pattern>+ <rect width="80" height="100" fill={`url(#${u}-polka)`} opacity="0.55" />+ </Svg>+ );+ case "hearts":+ case "stars":+ return (+ <Svg>+ {[+ [12, 16, 1.1],+ [64, 22, 0.8],+ [56, 74, 1.3],+ [18, 82, 0.7],+ [40, 10, 0.6],+ ].map(([x, y, s], i) =>+ m.kind === "hearts" ? (+ <path key={i} transform={`translate(${x} ${y}) scale(${s})`} d="M0 3 C0 -1 -6 -1 -6 3 C-6 6 0 9 0 11 C0 9 6 6 6 3 C6 -1 0 -1 0 3z" fill={ink(hue, 0.68, 0.24)} stroke="#fff" strokeWidth="0.8" />+ ) : (+ <path key={i} transform={`translate(${x} ${y}) scale(${s})`} d="M0 -6 L1.8 -1.8 L6 -1.6 L2.7 1.2 L3.8 5.6 L0 3.2 L-3.8 5.6 L-2.7 1.2 L-6 -1.6 L-1.8 -1.8Z" fill="oklch(0.86 0.17 88)" stroke="oklch(0.6 0.13 70)" strokeWidth="0.5" />+ ),+ )}+ {m.text && <rect x="3" y="3" width="74" height="94" fill="none" stroke="#111" strokeWidth="2" />}+ </Svg>+ );+ case "pattern":+ return (+ <Svg>+ <pattern id={`${u}-zig`} width="12" height="8" patternUnits="userSpaceOnUse">+ <path d="M0 6 L3 2 L6 6 L9 2 L12 6" fill="none" stroke={c} strokeWidth="1.4" />+ </pattern>+ <rect width="80" height="22" fill={`url(#${u}-zig)`} opacity="0.85" />+ <rect y="78" width="80" height="22" fill={`url(#${u}-zig)`} opacity="0.85" />+ </Svg>+ );+ case "collage":+ return (+ <Svg>+ <path d="M4 8 L34 5 L36 30 L6 33z" fill="oklch(0.95 0.03 90)" opacity="0.88" />+ <path d="M48 64 L76 60 L78 92 L50 95z" fill={ink(hue, 0.82, 0.12)} opacity="0.85" />+ <rect x="22" y="2" width="16" height="5" fill="oklch(0.9 0.06 85)" opacity="0.9" transform="rotate(12 30 4)" />+ <rect x="54" y="57" width="14" height="5" fill="oklch(0.9 0.06 85)" opacity="0.9" transform="rotate(-10 61 59)" />+ </Svg>+ );+ case "desktop":+ return (+ <Svg>+ <g>+ <rect x="8" y="12" width="64" height="44" rx="2.5" fill="none" stroke="#fff" strokeWidth="1.2" />+ <rect x="8" y="12" width="64" height="7" rx="2.5" fill="#fff" opacity="0.92" />+ {[13, 17.5, 22].map((x, i) => (+ <circle key={x} cx={x} cy="15.5" r="1.3" fill={["#ff5f57", "#febc2e", "#28c840"][i]} />+ ))}+ <rect x="26" y="50" width="46" height="34" rx="2.5" fill="none" stroke="#fff" strokeWidth="1" opacity="0.9" />+ <rect x="26" y="50" width="46" height="6" rx="2.5" fill={ink(hue, 0.8, 0.12)} opacity="0.9" />+ </g>+ <path d="M58 70 l0 11 l3 -3 l2.5 5 l2 -1 l-2.5 -5 l4 0z" fill="#fff" stroke="#111" strokeWidth="0.6" />+ </Svg>+ );+ case "bbox":+ case "tracking":+ return (+ <Svg>+ <g fill="none" stroke="oklch(0.85 0.2 145)" strokeWidth="1">+ <rect x="22" y="24" width="36" height="54" />+ <rect x="6" y="70" width="18" height="16" />+ {m.kind === "tracking" && <path d="M40 51 C30 40 20 50 15 78" strokeDasharray="2 2" />}+ </g>+ <rect x="22" y="19" width="26" height="5" fill="oklch(0.85 0.2 145)" />+ <text x="23.5" y="22.8" fontSize="3.6" fill="#05260f" style={{ fontFamily: "ui-monospace, monospace", fontWeight: 700 }}>+ person 0.98+ </text>+ </Svg>+ );+ case "circuit":+ return (+ <Svg>+ <g fill="none" stroke={ink(hue, 0.8, 0.17)} strokeWidth="0.9" opacity="0.9">+ <path d="M0 20 H20 L28 28 H44 M80 34 H58 L50 42 V60 M0 76 H16 L24 68 H40 M80 84 H62 L54 92" />+ </g>+ <g fill={ink(hue, 0.85, 0.18)}>+ {[+ [44, 28],+ [50, 60],+ [40, 68],+ [54, 92],+ ].map(([x, y]) => (+ <circle key={`${x}-${y}`} cx={x} cy={y} r="1.6" />+ ))}+ </g>+ </Svg>+ );+ case "chrome":+ return (+ <Svg>+ <defs>+ <linearGradient id={`${u}-chrome`} x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stopColor="#fff" stopOpacity="0.7" />+ <stop offset="0.35" stopColor="#9aa4b1" stopOpacity="0.15" />+ <stop offset="0.5" stopColor="#fff" stopOpacity="0.65" />+ <stop offset="0.7" stopColor="#58606b" stopOpacity="0.2" />+ <stop offset="1" stopColor="#fff" stopOpacity="0.5" />+ </linearGradient>+ </defs>+ <rect width="80" height="100" fill={`url(#${u}-chrome)`} style={{ mixBlendMode: "overlay" }} />+ <path d="M20 30 c10 -8 30 -8 40 0 c-6 10 -34 10 -40 0z" fill="#fff" opacity="0.35" />+ </Svg>+ );+ case "mascot":+ case "clay":+ return (+ <Svg>+ {m.kind === "mascot" ? (+ <g transform="translate(58 18)">+ <circle r="11" fill={ink(hue, 0.82, 0.16)} stroke="#fff" strokeWidth="1.5" />+ <circle cx="-3.5" cy="-2" r="2.6" fill="#fff" />+ <circle cx="3.5" cy="-2" r="2.6" fill="#fff" />+ <circle cx="-3" cy="-1.6" r="1.2" fill="#111" />+ <circle cx="4" cy="-1.6" r="1.2" fill="#111" />+ <path d="M-4 4 q4 4 8 0" stroke="#111" strokeWidth="1" fill="none" strokeLinecap="round" />+ </g>+ ) : (+ <g opacity="0.55" fill="none" stroke="#fff" strokeWidth="0.6">+ {[3, 5, 7, 9].map((r) => (+ <ellipse key={r} cx="62" cy="80" rx={r} ry={r * 0.8} />+ ))}+ </g>+ )}+ </Svg>+ );+ case "comic":+ return (+ <Svg>+ <g fill="none" stroke="#111" strokeWidth="2.2">+ <rect x="1.5" y="1.5" width="77" height="97" />+ <path d="M1.5 62 L78.5 54 M44 54.5 L40 98.5" />+ </g>+ <path d="M8 6 h30 a4 4 0 0 1 4 4 v9 a4 4 0 0 1 -4 4 h-18 l-6 6 l1 -6 h-7 a4 4 0 0 1 -4 -4 v-9 a4 4 0 0 1 4 -4z" fill="#fff" stroke="#111" strokeWidth="1" />+ <text x="23" y="18.5" textAnchor="middle" fontSize="9" fill={ink(hue, 0.55, 0.22)} style={{ fontWeight: 900 }}>+ {m.text}+ </text>+ </Svg>+ );+ case "burst":+ return (+ <Svg>+ <path+ transform="translate(56 24)"+ d={Array.from({ length: 24 }, (_, i) => {+ const a = (i / 24) * Math.PI * 2;+ const r = i % 2 ? 9 : 19;+ return `${i ? "L" : "M"}${(Math.cos(a) * r).toFixed(1)} ${(Math.sin(a) * r * 0.85).toFixed(1)}`;+ }).join(" ") + "Z"}+ fill="oklch(0.9 0.19 95)"+ stroke="#111"+ strokeWidth="1"+ />+ <text x="56" y="27.5" textAnchor="middle" fontSize="8" fill="#d6262c" transform="rotate(-8 56 24)" style={{ fontWeight: 900 }}>+ {m.text}+ </text>+ </Svg>+ );+ case "frame":+ return (+ <Svg>+ <rect x="3" y="3" width="74" height="94" fill="none" stroke="oklch(0.88 0.18 95)" strokeWidth="6" />+ </Svg>+ );+ case "blueprint":+ return (+ <Filter filter="grayscale(1) contrast(1.3)">+ <Svg>+ <rect width="80" height="100" fill="oklch(0.42 0.14 255)" opacity="0.55" style={{ mixBlendMode: "multiply" }} />+ <pattern id={`${u}-grid`} width="8" height="8" patternUnits="userSpaceOnUse">+ <path d="M8 0 H0 V8" fill="none" stroke="#fff" strokeWidth="0.3" opacity="0.55" />+ </pattern>+ <rect width="80" height="100" fill={`url(#${u}-grid)`} />+ <path d="M10 90 H70 M10 87 V93 M70 87 V93" stroke="#fff" strokeWidth="0.6" />+ </Svg>+ </Filter>+ );+ case "pop":+ return (+ <Svg>+ <rect x="0" y="0" width="80" height="26" fill={ink(hue, 0.82, 0.2)} opacity="0.75" style={{ mixBlendMode: "multiply" }} />+ <pattern id={`${u}-dots`} width="4" height="4" patternUnits="userSpaceOnUse">+ <circle cx="2" cy="2" r="0.9" fill="#111" opacity="0.5" />+ </pattern>+ <rect x="44" y="70" width="36" height="30" fill={`url(#${u}-dots)`} />+ </Svg>+ );+ case "fragments":+ case "mirror":+ return (+ <Svg>+ <g fill="none" stroke="#fff" strokeWidth={m.kind === "mirror" ? 0.7 : 1.4} opacity="0.85">+ <path d="M40 46 L8 0 M40 46 L80 18 M40 46 L70 100 M40 46 L0 70 M40 46 L36 100 M40 46 L52 0" />+ </g>+ {m.kind === "fragments" && <rect x="44" y="52" width="22" height="18" fill={ink(hue, 0.8, 0.15)} opacity="0.5" transform="rotate(8 55 61)" />}+ </Svg>+ );+ case "particles":+ case "bubbles":+ return (+ <Svg>+ {[+ [12, 20, 2],+ [26, 70, 3],+ [62, 30, 4],+ [70, 76, 2.5],+ [44, 12, 1.5],+ [52, 88, 2],+ [8, 52, 1.2],+ ].map(([x, y, r], i) =>+ m.kind === "bubbles" ? (+ <circle key={i} cx={x} cy={y} r={r * 2} fill="none" stroke="#fff" strokeWidth="0.6" opacity="0.8" />+ ) : (+ <circle key={i} cx={x} cy={y} r={r} fill={ink(hue + i * 30, 0.9, 0.16)} opacity="0.85" />+ ),+ )}+ </Svg>+ );+ case "origami":+ return (+ <Svg>+ <path d="M0 100 L40 56 L80 100z" fill="#fff" opacity="0.28" />+ <path d="M40 56 L80 100 L80 40z" fill={ink(hue, 0.7, 0.12)} opacity="0.35" />+ <path d="M0 0 L36 0 L0 34z" fill="#fff" opacity="0.22" />+ </Svg>+ );+ case "magazine":+ return (+ <Svg>+ <text x="6" y="16" fontSize="13" fill="#fff" style={{ fontFamily: "Georgia, serif", fontWeight: 900, letterSpacing: -0.5 }}>+ ISSUE 07+ </text>+ <rect x="6" y="84" width="28" height="2" fill="#fff" />+ <rect x="6" y="88" width="20" height="2" fill="#fff" opacity="0.7" />+ </Svg>+ );+ case "marble":+ return (+ <Filter filter="grayscale(0.85) brightness(1.15) contrast(1.1)">+ <Svg>+ <path d="M0 30 C20 24 30 44 50 36 S70 50 80 44 M0 72 C14 66 30 80 46 72 S70 84 80 78" fill="none" stroke="#9aa0a6" strokeWidth="0.6" opacity="0.7" />+ </Svg>+ </Filter>+ );+ }+}++/** The preset's motif over its preview card, if it has one. */+export function LookMotif({ id, hue }: { id: string; hue: number }) {+ // Pattern and filter ids are per card: 44 cards on a page, each with its own colours.+ const u = `lm${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;+ const m = MOTIFS[id];+ if (!m) return null;+ return (+ <div className="pointer-events-none absolute inset-0 z-[6] overflow-hidden" aria-hidden>+ <Draw m={m} hue={hue} u={u} />+ </div>+ );+}++/** Presets with a motif (for tests). */+export const MOTIF_IDS = Object.keys(MOTIFS);diff --git a/src/components/shorts/preset-card.tsx b/src/components/shorts/preset-card.tsxindex 11b9f806..56d1fb24 100644--- a/src/components/shorts/preset-card.tsx+++ b/src/components/shorts/preset-card.tsx@@ -5,6 +5,7 @@ import { memo } from "react";import { PresetPreview, usePreviewPlayback } from "@/components/preset-preview";import type { PresetPreview as Preview } from "@/lib/preset-cards";import { cn } from "@/lib/utils";+import { LookMotif } from "./look-motif";/*** A selectable look card (Shorts Studio and Mixed Media): the procedural preview from the@@ -45,10 +46,12 @@ export const LookCard = memo(function LookCard({><div className={cn("relative aspect-[4/5] w-full overflow-hidden rounded-lg bg-muted ring-offset-2 ring-offset-background transition-shadow", selected && "ring-2 ring-primary")}><PresetPreview preview={preview} hue={hue} playing={playing} />- <span className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-black/40 to-transparent" />- {badge && <span className="absolute top-1.5 left-1.5 rounded-[4px] bg-black/45 px-1.5 text-[10px] font-medium text-white backdrop-blur">{badge}</span>}+ {/* The preset's own motif (lettering, scribbles, paper, a grid…), so similar treatments read apart. */}+ <LookMotif id={id} hue={hue} />+ <span className="pointer-events-none absolute inset-x-0 bottom-0 z-[7] h-12 bg-gradient-to-t from-black/40 to-transparent" />+ {badge && <span className="absolute top-1.5 left-1.5 z-[8] rounded-[4px] bg-black/45 px-1.5 text-[10px] font-medium text-white backdrop-blur">{badge}</span>}{selected && (- <span className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft">+ <span className="absolute top-1.5 right-1.5 z-[8] grid size-6 place-items-center rounded-full bg-primary text-primary-foreground shadow-soft"><Check className="size-3.5" /></span>)}diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex adde8515..d9624b15 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -20,6 +20,7 @@ import { SidebarTrigger } from "@/components/ui/sidebar";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { MediaThumb } from "@/components/studio/result-media";+import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { Viewer } from "@/components/studio/viewer";import { chainState, formatSeconds, stitchCurrent, stitchSteps, takeSteps, type ChainState, type ShortsSessionSegment } from "@/lib/catalog/shorts";import type { Generation } from "@/lib/catalog/types";@@ -348,21 +349,25 @@ function SegmentCard({)}{state.status === "done" && <p className="text-[13px] text-muted-foreground">Take {seg.takes.findIndex((t) => t.look === seg.primary) + 1} is in the full video.</p>}{seg.takes.length > 1 && (- <div role="radiogroup" aria-label={`Takes of segment ${index + 1}`} className="flex flex-wrap gap-1.5">+ // Arrow keys move between the takes and pick them (radio pattern); the chosen take is the Tab stop.+ // Only takes that can't be picked (still rendering, failed) are turned off, with the reason in their name.+ <div role="radiogroup" aria-label={`Takes of segment ${index + 1}`} onKeyDown={radioKeys} className="flex flex-wrap gap-1.5">{seg.takes.map((t, ti) => {const g = gens[t.look];const v = videoOf(g);const st = chainState(takeSteps(t, gens));const chosen = seg.primary === t.look;+ const why = st.status === "done" ? "" : st.status === "working" ? "still rendering" : st.status === "gone" ? "deleted" : "failed";return (<buttonkey={t.look}type="button"role="radio"aria-checked={chosen}- aria-label={`Take ${ti + 1}${st.status === "done" ? "" : ` (${st.status === "working" ? "rendering" : st.status})`}`}- disabled={st.status !== "done" || chosen}- onClick={() => onPrimary(t.look)}+ aria-label={`Take ${ti + 1}${why ? ` (${why})` : chosen ? " (in the full video)" : ""}`}+ tabIndex={radioTab(chosen)}+ disabled={st.status !== "done" && !chosen}+ onClick={() => !chosen && st.status === "done" && onPrimary(t.look)}title={st.status === "done" ? (chosen ? "In the full video" : "Use this take") : st.status === "working" ? "Still rendering" : st.error}className={cn("relative size-12 overflow-hidden rounded-lg bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default",diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex f48e1751..86a226b9 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -10,6 +10,7 @@ import { EngineSwitch } from "@/components/studio/engine-switch";import { VideoTrimmer } from "@/components/studio/video-trimmer";import { useEngine } from "@/lib/api";import {+ clipShapeProblem,rangeProblem,SHORTS,SHORTS_CATEGORIES,@@ -29,7 +30,7 @@ import { useShortsActions, useShortsEstimate, useShortsPresets, useSubmitGuard,import { CreateCard, CustomCard, LookCard } from "./preset-card";import { ShortsHistory } from "./history";import { ClipBar, ClipDrop, costText, Field, Segmented, Steps, tabKeys } from "./ui";-import { clipDuration, useSourceClip } from "./use-source-clip";+import { clipDuration, clipSize, useSourceClip } from "./use-source-clip";export type ModelChoice = RestyleModelInfo;@@ -172,6 +173,7 @@ function Workspace({presetId={presetId}presetName={selectedName}customRefs={selectedCustom?.references.length ?? 0}+ customDescribed={!!selectedCustom?.description.trim()}source={source}range={range}setRange={setRange}@@ -287,6 +289,7 @@ function SetupPanel({presetId,presetName,customRefs,+ customDescribed,source,range,setRange,@@ -296,6 +299,8 @@ function SetupPanel({presetId: string | null;presetName?: string;customRefs: number;+ /** The custom preset has words of its own (a words-only model has something to go on). */+ customDescribed: boolean;source: ReturnType<typeof useSourceClip>;range: TrimRange | null;setRange: (r: TrimRange | null) => void;@@ -305,17 +310,29 @@ function SetupPanel({const [ratio, setRatio] = useState<ShortsRatio>("9:16");const [language, setLanguage] = useState("auto");const [pickedModel, setModel] = useState<Record<Engine, string>>({ cloud: "", open: "" });- const modelId = pickedModel[engine] || models[0]?.id;+ // A custom preset is its reference images: on cloud, start on the first model that reads them+ // (Kling O3 4K Edit, then Happy Horse) unless a model was picked.+ const refModel = models.find((m) => m.refs > 0)?.id;+ const modelId = pickedModel[engine] || (customRefs > 0 && engine === "cloud" && refModel ? refModel : models[0]?.id);const model = models.find((m) => m.id === modelId);const duration = clipDuration(clip);const actions = useShortsActions();const presetType = SHORTS_PRESETS.find((p) => p.id === presetId)?.type;+ const size = clipSize(clip);const shortsRange = range ? { start: range.startTime, end: range.endTime } : null;- const problem = shortsRange ? rangeProblem(shortsRange, duration) : null;+ const problem = clipShapeProblem(size.width, size.height) ?? (shortsRange ? rangeProblem(shortsRange, duration) : null);const estimateBody: ShortsBody | null =presetId && shortsRange && !problem- ? { engine, presetId, source: { url: clip?.url ?? "/api/files/placeholder.mp4", name: clip?.name, duration }, range: shortsRange, aspectRatio: ratio, language, modelId }+ ? {+ engine,+ presetId,+ source: { url: clip?.url ?? "/api/files/placeholder.mp4", name: clip?.name, duration, ...(size.width && size.height ? { width: size.width, height: size.height } : {}) },+ range: shortsRange,+ aspectRatio: ratio,+ language,+ modelId,+ }: null;const estimate = useShortsEstimate(estimateBody);const est = estimate.data;@@ -330,13 +347,15 @@ function SetupPanel({? "Reading the clip…": problem? problem- : clip.uploading- ? clip.progress < 1- ? `Uploading… ${Math.round(clip.progress * 100)}%`- : "Reading the clip…"- : estimate.error- ? (estimate.error as Error).message- : null;+ : customRefs > 0 && engine === "cloud" && model && !model.refs && !customDescribed+ ? "Describe the look in your preset, or pick a model that reads reference images"+ : clip.uploading+ ? clip.progress < 1+ ? `Uploading… ${Math.round(clip.progress * 100)}%`+ : "Reading the clip…"+ : estimate.error+ ? (estimate.error as Error).message+ : null;const guard = useSubmitGuard();const [leaving, setLeaving] = useState(false);@@ -403,7 +422,7 @@ function SetupPanel({max={SHORTS.maxSeconds}duration={clip.info?.duration}label="Part of the clip to restyle"- onMeta={(m) => source.setBrowserDuration(m.duration)}+ onMeta={source.setBrowserMeta}/></div>)}@@ -479,6 +498,12 @@ function SetupPanel({</span></div>{est && !est.demo && engine === "cloud" && <p className="text-[12px] text-muted-foreground">You're only charged for the actual length.</p>}+ {clip?.url && !clip.uploading && !clip.error && clip.info && clip.info.hasAudio === undefined && (+ <p className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground">+ <Info className="mt-0.5 size-3.5 shrink-0" />+ Couldn't read this clip's sound track — it's made without sound.+ </p>+ )}{est?.notes.map((n) => (<p key={n} className="flex gap-1.5 text-[12px] leading-snug text-muted-foreground"><Info className="mt-0.5 size-3.5 shrink-0" />diff --git a/src/components/shorts/use-source-clip.ts b/src/components/shorts/use-source-clip.tsindex 92abb55f..2f933ae7 100644--- a/src/components/shorts/use-source-clip.ts+++ b/src/components/shorts/use-source-clip.ts@@ -28,8 +28,10 @@ export interface SourceClip {uploading: boolean;error?: string;info?: SourceInfo;- /** Length as the browser read it (formats the server can't read). */+ /** Length and size as the browser read them (formats the server can't read). */browserDuration?: number;+ browserWidth?: number;+ browserHeight?: number;}const VIDEO_TYPE = /^video\/(mp4|quicktime|webm|x-m4v)$/;@@ -120,10 +122,19 @@ export function useSourceClip(maxBytes: number) {setClip(null);}, []);- const setBrowserDuration = useCallback((d: number) => setClip((c) => (c && d > 0 ? { ...c, browserDuration: d } : c)), []);+ /** What the browser's player read (the trimmer's onMeta). */+ const setBrowserMeta = useCallback(+ (m: { duration: number; width?: number; height?: number }) =>+ setClip((c) => (c && m.duration > 0 ? { ...c, browserDuration: m.duration, ...(m.width && m.height ? { browserWidth: m.width, browserHeight: m.height } : {}) } : c)),+ [],+ );- return { clip, pick, adopt, clear, setBrowserDuration };+ return { clip, pick, adopt, clear, setBrowserMeta };}/** The clip's length: its header's, else what the browser read. */export const clipDuration = (c: SourceClip | null) => c?.info?.duration ?? c?.browserDuration;++/** The clip's picture size: its header's, else what the browser read. */+export const clipSize = (c: SourceClip | null): { width?: number; height?: number } =>+ c?.info?.width && c.info.height ? { width: c.info.width, height: c.info.height } : { width: c?.browserWidth, height: c?.browserHeight };diff --git a/src/components/studio/video-trimmer.tsx b/src/components/studio/video-trimmer.tsxindex 5580eba6..78e39285 100644--- a/src/components/studio/video-trimmer.tsx+++ b/src/components/studio/video-trimmer.tsx@@ -2,7 +2,7 @@import { Pause, Play, Volume2, VolumeX } from "lucide-react";import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";-import { clampRange, clock, initialRange, moveRange, setEdge, thumbTimes, trimHint, type TrimLimits, type TrimRange } from "@/lib/trim-range";+import { clampRange, clock, initialRange, moveRange, parseTime, setEdge, thumbTimes, trimHint, trimKey, type TrimLimits, type TrimRange } from "@/lib/trim-range";import { cn } from "@/lib/utils";export type { TrimRange } from "@/lib/trim-range";@@ -306,29 +306,15 @@ export const VideoTrimmer = forwardRef<VideoTrimmerHandle, VideoTrimmerProps>(fuconst onKey = (e: React.KeyboardEvent<HTMLElement>) => {const kind = e.currentTarget.dataset.trim as "start" | "end" | "move" | undefined;if (!range || !d || !kind) return;- const big = e.shiftKey ? 10 : 1;- let delta: number | null = null;- let to: number | null = null;- if (e.key === "ArrowLeft" || e.key === "ArrowDown") delta = -STEP * big;- else if (e.key === "ArrowRight" || e.key === "ArrowUp") delta = STEP * big;- else if (e.key === "PageDown") delta = -5;- else if (e.key === "PageUp") delta = 5;- else if (e.key === "Home") to = 0;- else if (e.key === "End") to = d;- else if (e.key === " " || e.key === "Enter") {+ if (e.key === " " || e.key === "Enter") {e.preventDefault();togglePlay();return;- } else return;- e.preventDefault();- if (kind === "move") {- const next = moveRange(range, to !== null ? (to === 0 ? -range.startTime : d - range.endTime) : delta!, limits);- commit(next, next.startTime);- } else {- const cur = kind === "start" ? range.startTime : range.endTime;- const next = setEdge(range, kind, to ?? cur + delta!, limits);- commit(next, kind === "start" ? next.startTime : next.endTime);}+ const next = trimKey(range, kind, e.key, e.shiftKey, limits, STEP);+ if (!next) return;+ e.preventDefault();+ commit(next, kind === "end" ? next.endTime : next.startTime);};const pct = (t: number) => (d ? `${(t / d) * 100}%` : "0%");@@ -462,13 +448,9 @@ export const VideoTrimmer = forwardRef<VideoTrimmerHandle, VideoTrimmerProps>(fufunction TimeField({ label, value, disabled, onCommit }: { label: string; value?: number; disabled?: boolean; onCommit: (t: number) => void }) {const [draft, setDraft] = useState<string | null>(null);const shown = draft ?? (value !== undefined ? value.toFixed(1) : "");- const parse = (s: string) => {- const m = /^\s*(?:(\d+):)?(\d+(?:\.\d+)?)\s*s?\s*$/.exec(s);- return m ? Number(m[1] ?? 0) * 60 + Number(m[2]) : NaN;- };const done = () => {if (draft !== null) {- const t = parse(draft);+ const t = parseTime(draft);if (Number.isFinite(t)) onCommit(t);}setDraft(null);diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.tsindex 2e1e12a3..f974a354 100644--- a/src/lib/catalog/mixed-media.ts+++ b/src/lib/catalog/mixed-media.ts@@ -420,6 +420,14 @@ export function mixedPrompts(p: Pick<MixedPreset, "look" | "settings">, values:export const denoiseFor = (values: MixedValues) => DENOISE[values.intensity] ?? DENOISE.balanced;+/** "#c1121f" from a typed "#C1121F", "c1121f" or "#c12" (shorthand), else null. */+export function parseHex(raw: string): string | null {+ const v = raw.trim().replace(/^#/, "").toLowerCase();+ if (/^[0-9a-f]{6}$/.test(v)) return `#${v}`;+ if (/^[0-9a-f]{3}$/.test(v)) return `#${[...v].map((c) => c + c).join("")}`;+ return null;+}+// ---------------------------------------------------------------------------// Frames, frame rates and costdiff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex aec13b0f..68caa88d 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1070,6 +1070,21 @@ const cloudTools: ModelDef[] = [pricing: { unit: "request", usd: 0.001 },hidden: true,},+ {+ // Shorts Studio: a clip cropped to 9:16 or 16:9 before a restyle model that keeps its input's shape.+ id: "scale-video",+ name: "Crop to size",+ vendor: "fal",+ family: "utility",+ engine: "cloud",+ kind: "video",+ tagline: "Centre-crop (or pad) a clip to an exact size, no AI",+ // Size in params.extra {width, height} (even numbers); "crop" scales to cover, then centre-crops.+ routes: [{ op: "reframe", provider: "fal", endpoint: "fal-ai/workflow-utilities/scale-video", map: { prompt: false, video: "video_url", defaults: { mode: "crop" } } }],+ options: {},+ pricing: { unit: "request", usd: 0.001, note: "billed per compute second" },+ hidden: true,+ },];/**diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.tsindex 6b9285fb..c545ccf0 100644--- a/src/lib/catalog/shorts.ts+++ b/src/lib/catalog/shorts.ts@@ -80,7 +80,7 @@ export const SHORTS_MODELS: Record<Engine, string[]> = {/** The helper models of the pipeline. */export const SHORTS_TOOLS = {- cloud: { cut: "trim-video", trim: "trim-video", join: "join-clips", mux: "merge-audio-video", joinMax: 24 },+ cloud: { cut: "trim-video", trim: "trim-video", fit: "scale-video", join: "join-clips", mux: "merge-audio-video", joinMax: 24 },open: { cut: "oss-segment", trim: "oss-trim", frame: "oss-qwen-edit", join: "oss-join-clips", mux: "oss-mux", joinMax: 4 },} as const;@@ -200,6 +200,8 @@ export interface ShortsLook {type?: boolean;references?: string[];custom?: boolean;+ /** A custom preset with words of its own (else the look is only its reference images). */+ described?: boolean;}export function lookFromPreset(p: ShortsPreset): ShortsLook {@@ -214,6 +216,7 @@ export function lookFromCustom(p: ShortsCustomPreset): ShortsLook {look: words ? `the look of the reference images: ${words}` : "the look of the reference images: their colours, textures, lighting and graphic style",references: p.references.slice(0, SHORTS.maxReferences),custom: true,+ described: !!words,};}@@ -285,6 +288,15 @@ export function clipLengthProblem(m: { name: string; minSeconds?: number; maxSecreturn null;}+/** Higgsfield's upload rules for the picture: up to 4000 px on the long side, between 1:3 and 3:1. */+export function clipShapeProblem(width?: number, height?: number): string | null {+ if (!width || !height) return null;+ if (Math.max(width, height) > SHORTS.maxDimension) return `This clip is ${width}×${height} — use one up to ${SHORTS.maxDimension} px on its long side`;+ const r = width / height;+ if (r > 3.01 || r < 1 / 3.01) return "Use a clip between 1:3 and 3:1";+ return null;+}+/** What's wrong with a selection, or null. */export function rangeProblem(range: ShortsRange, duration?: number): string | null {const len = range.end - range.start;@@ -366,10 +378,12 @@ export interface PlanStep {export interface ShortsPlanInput {engine: Engine;title: string;- source: { url: string; duration?: number; hasAudio?: boolean };+ source: { url: string; duration?: number; hasAudio?: boolean; width?: number; height?: number };range: ShortsRange;look: ShortsLook;aspectRatio: ShortsRatio;+ /** Cloud: the restyle model can be asked for the ratio itself; otherwise each cut is cropped to it first (it keeps its input's shape). */+ reframes?: boolean;language: string;/** The restyle model (cloud: SHORTS_MODELS.cloud; open: oss-wan22-vace-restyle). */modelId: string;@@ -382,10 +396,14 @@ export interface ShortsPlanInput {}export const SHORTS_FEATURE = "shorts";+/** The steps in between (cuts, crops, first frames, joins, the sound): kept apart from the takes and the finished short. */+export const SHORTS_STEP_FEATURE = "shorts-step";/** Keys of one take's steps. */export interface TakeKeys {cut: string;+ /** Cloud: the cut cropped to the output ratio. */+ fit?: string;frame?: string;look: string;}@@ -403,6 +421,7 @@ export function refsFor(input: Pick<ShortsPlanInput, "engine" | "look" | "maxRefexport function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: number, suffix = ""): { steps: PlanStep[]; keys: TakeKeys } {const t = SHORTS_TOOLS[input.engine];const base = { feature: SHORTS_FEATURE, batchTitle: input.title };+ const helper = { feature: SHORTS_STEP_FEATURE, batchTitle: input.title };const k = (what: string) => `${what}${seg.index}${suffix}`;const refs = refsFor(input);const seed = input.seed !== undefined ? { seed: input.seed } : {};@@ -414,7 +433,7 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb{key: keys.cut,request: {- ...base,+ ...helper,modelId: t.cut,op: "trim",inputs: { video: input.source.url },@@ -425,7 +444,7 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb{key: keys.frame!,request: {- ...base,+ ...helper,modelId: SHORTS_TOOLS.open.frame,op: "edit",prompt: firstFramePrompt(input.look, input.language, refs.length),@@ -452,15 +471,33 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb],};}- const keys: TakeKeys = { cut: k("cut"), look: k("look") };+ const fit = !input.reframes && needsFit(input.source, input.aspectRatio);+ const keys: TakeKeys = { cut: k("cut"), ...(fit ? { fit: k("fit") } : {}), look: k("look") };const seconds = seg.end - seg.start;return {keys,steps: [{key: keys.cut,- request: { ...base, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: seg.start, endTime: seg.end }, step: segLabel(seg, total, "cut") },+ request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: seg.start, endTime: seg.end }, step: segLabel(seg, total, "cut") },},+ // The restyle keeps its input's shape: crop the cut to the output ratio first (centre crop, no AI, ≈ free).+ ...(keys.fit+ ? [+ {+ key: keys.fit,+ request: {+ ...helper,+ modelId: SHORTS_TOOLS.cloud.fit,+ op: "reframe" as const,+ params: { aspectRatio: input.aspectRatio, extra: { ...fitSize(input.aspectRatio) } },+ step: segLabel(seg, total, `crop to ${input.aspectRatio}`),+ },+ after: [keys.cut],+ chain: [{ slot: "video" as const }],+ },+ ]+ : []),{key: keys.look,request: {@@ -474,13 +511,25 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numbparams: { aspectRatio: input.aspectRatio, duration: r3(seconds), ...(input.resolution ? { resolution: input.resolution } : {}), ...seed },step: segLabel(seg, total, "restyle"),},- after: [keys.cut],+ after: [keys.fit ?? keys.cut],chain: [{ slot: "video" }],},],};}+/** The size a cut is cropped to before a restyle that keeps its input's shape (1080 on the short side). */+export function fitSize(ratio: ShortsRatio): { width: number; height: number } {+ return ratio === "9:16" ? { width: 1080, height: 1920 } : { width: 1920, height: 1080 };+}++/** Whether a clip needs cropping to come out at `ratio` (an unknown shape is cropped: it's ≈ free). */+export function needsFit(source: { width?: number; height?: number }, ratio: ShortsRatio): boolean {+ if (!source.width || !source.height) return true;+ const want = ratio === "9:16" ? 9 / 16 : 16 / 9;+ return Math.abs(source.width / source.height - want) / want > 0.02;+}+/** Where a clip in a stitch comes from: an earlier step's output, or a finished file. */export type ClipRef = { key: string } | { url: string };@@ -492,6 +541,7 @@ export type ClipRef = { key: string } | { url: string };export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""): { steps: PlanStep[]; final?: string } {const t = SHORTS_TOOLS[input.engine];const base = { feature: SHORTS_FEATURE, batchTitle: input.title };+ const helper = { feature: SHORTS_STEP_FEATURE, batchTitle: input.title };const steps: PlanStep[] = [];const params = input.engine === "open" ? { aspectRatio: input.aspectRatio, resolution: "480p" } : { aspectRatio: input.aspectRatio };// Each join step takes its clips either chained (key) or as files (url).@@ -509,7 +559,7 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""steps.push({key,request: {- ...base,+ ...helper,modelId: t.join,op: "concat",prompt: input.title,@@ -528,7 +578,7 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""// Nothing to put back: the joined clip (or the single segment) is the short.if ("key" in picture) {const last = steps.find((s) => s.key === picture.key);- if (last) last.request = { ...last.request, title: input.title };+ if (last) last.request = { ...last.request, feature: SHORTS_FEATURE, title: input.title };return { steps, final: picture.key };}return { steps, final: undefined };@@ -547,7 +597,7 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""const key = `sound${suffix}`;steps.push({key,- request: { ...base, modelId: t.trim, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Original sound", index: 1100, of: 1000 } },+ request: { ...helper, modelId: t.trim, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Original sound", index: 1100, of: 1000 } },});after.push(key);chain.push({ slot: "audio" });@@ -578,6 +628,8 @@ export function planShorts(input: ShortsPlanInput): { segments: ShortsSegment[];export interface ShortsTake {/** The generations of this take's steps, by role. */cut: string;+ /** Cloud: the cut cropped to the output ratio. */+ fit?: string;frame?: string;look: string;createdAt: number;@@ -607,7 +659,7 @@ export interface ShortsSession {look: ShortsLook;source: { url: string; name?: string; duration?: number; hasAudio?: boolean; width?: number; height?: number };range: ShortsRange;- settings: { aspectRatio: ShortsRatio; language: string; modelId: string; resolution?: string; maxRefs: number };+ settings: { aspectRatio: ShortsRatio; language: string; modelId: string; resolution?: string; maxRefs: number; reframes?: boolean };segments: ShortsSessionSegment[];stitches: ShortsStitch[];createdAt: number;@@ -627,6 +679,7 @@ export function sessionPlanInput(s: ShortsSession, seed?: number): ShortsPlanInpmodelId: s.settings.modelId,maxRefs: s.settings.maxRefs,resolution: s.settings.resolution,+ reframes: s.settings.reframes,...(seed !== undefined ? { seed } : {}),};}@@ -685,9 +738,10 @@ export function chainState(steps: { g?: Generation; label: string }[]): ChainSta}/** A take's steps with their labels. */-export function takeSteps(t: Pick<ShortsTake, "cut" | "frame" | "look">, gens: Record<string, Generation>): { g?: Generation; label: string }[] {+export function takeSteps(t: Pick<ShortsTake, "cut" | "fit" | "frame" | "look">, gens: Record<string, Generation>): { g?: Generation; label: string }[] {return [{ g: gens[t.cut], label: "Cutting the segment" },+ ...(t.fit ? [{ g: gens[t.fit], label: "Cropping the segment" }] : []),...(t.frame ? [{ g: gens[t.frame], label: "Restyling the first frame" }] : []),{ g: gens[t.look], label: "Restyling" },];diff --git a/src/lib/trim-range.ts b/src/lib/trim-range.tsindex e2204327..262ff6ef 100644--- a/src/lib/trim-range.ts+++ b/src/lib/trim-range.ts@@ -60,6 +60,36 @@ export function moveRange(r: TrimRange, delta: number, limits: TrimLimits): Trimreturn clampRange({ startTime: r.startTime + delta, endTime: r.endTime + delta }, limits, "move");}+export type TrimHandle = "start" | "end" | "move";++/**+ * The selection after a key on one of the trimmer's sliders (the start handle, the end handle or the+ * whole window), or null when the key isn't a slider key: arrows move 0.1 s (Shift ×10), Page Up /+ * Page Down 5 s, Home / End go to the clip's ends. The min/max length and the clip's ends hold.+ */+export function trimKey(r: TrimRange, handle: TrimHandle, key: string, shift: boolean, limits: TrimLimits, step = 0.1): TrimRange | null {+ const d = limits.duration;+ const big = shift ? 10 : 1;+ let delta: number | null = null;+ let to: number | null = null;+ if (key === "ArrowLeft" || key === "ArrowDown") delta = -step * big;+ else if (key === "ArrowRight" || key === "ArrowUp") delta = step * big;+ else if (key === "PageDown") delta = -5;+ else if (key === "PageUp") delta = 5;+ else if (key === "Home") to = 0;+ else if (key === "End") to = d;+ else return null;+ if (handle === "move") return moveRange(r, to !== null ? (to === 0 ? -r.startTime : d - r.endTime) : delta!, limits);+ const cur = handle === "start" ? r.startTime : r.endTime;+ return setEdge(r, handle, to ?? cur + delta!, limits);+}++/** A typed time in seconds: "12.5", "12.5 s" or "0:12.5" (NaN when it isn't one). */+export function parseTime(s: string): number {+ const m = /^\s*(?:(\d+):)?(\d+(?:\.\d+)?)\s*s?\s*$/.exec(s);+ return m ? Number(m[1] ?? 0) * 60 + Number(m[2]) : NaN;+}+function spoken(sec: number): string {if (sec >= 60 && sec % 60 === 0) return `${sec / 60} minute${sec === 60 ? "" : "s"}`;return `${Number.isInteger(sec) ? sec : sec.toFixed(1)} second${sec === 1 ? "" : "s"}`;diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.tsindex 44603bc6..3d115eb1 100644--- a/src/server/mixed-media.ts+++ b/src/server/mixed-media.ts@@ -4,7 +4,9 @@ import {clampFps,cleanValues,getMixedPreset,+ MIXED_FEATURE,MIXED_MODELS,+ MIXED_STEP_FEATURE,mixedFrames,mixedRangeProblem,nearestResolution,@@ -17,7 +19,8 @@ import { clipLengthProblem, type PlanStep } from "@/lib/catalog/shorts";import { sourceSeconds, takesImage } from "@/lib/catalog/shorts-models";import type { Engine, Generation } from "@/lib/catalog/types";import { createPipeline } from "./chains";-import { previewChained } from "./generations";+import { db } from "./db";+import { getGeneration, previewChained } from "./generations";import { engineMode } from "./settings";import { probeSource, ShortsError } from "./shorts";@@ -84,7 +87,8 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ ititle: name ? `${preset.name} · ${name}` : `${preset.name} mixed media`,preset,values: cleanValues(preset, body.values),- source: { url: body.source.url, duration, hasAudio: info.hasAudio ?? true },+ // Sound we couldn't read counts as none (the soundtrack step would fail after the restyle was paid for).+ source: { url: body.source.url, duration, hasAudio: info.hasAudio ?? false },range: body.range,fps,resolution: body.resolution,@@ -143,6 +147,35 @@ export async function createMixed(body: MixedBody): Promise<{ final: Generation;return { final: p.byKey[plan.final], items: p.items };}+/**+ * Run a render again with the same settings (History's "Try again" after a failed step): its steps+ * are made anew from their stored requests, waiting on each other as before.+ */+export function retryMixed(id: string): { final: Generation; items: Generation[] } {+ const final = getGeneration(id);+ if (!final || final.feature !== MIXED_FEATURE || !final.batchId) throw new ShortsError("This render no longer exists", 404);+ const mode = engineMode();+ if (mode !== "both" && mode !== final.engine) {+ throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);+ }+ const rows = db()+ .prepare("SELECT id, depends_on FROM generations WHERE batch_id = ? AND feature IN (?, ?) ORDER BY created_at ASC, id ASC")+ .all(final.batchId, MIXED_FEATURE, MIXED_STEP_FEATURE) as { id: string; depends_on: string | null }[];+ const deps = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);+ const steps: PlanStep[] = rows.map((r) => {+ const g = getGeneration(r.id);+ if (!g) throw new ShortsError("Part of this render was deleted — make it again from the editor", 409);+ const { chain, ...request } = g.request;+ const after = deps(r.depends_on);+ // Chained inputs were filled in when the step ran: the new run fills them from the new steps.+ const inputs = { ...request.inputs };+ for (const c of chain ?? []) if (c.slot !== "images" && c.slot !== "videos" && c.slot !== "prompt") delete inputs[c.slot];+ return { key: r.id, request: { ...request, inputs: Object.keys(inputs).length ? inputs : undefined }, ...(after.length ? { after, chain } : {}) };+ });+ const p = run(steps);+ return { final: p.byKey[id], items: p.items };+}+/** One frame with the current settings. */export async function createMixedPreview(body: MixedBody): Promise<Generation> {const { input } = await planInput(body, { probe: true });diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.tsindex 5356b747..e270f2af 100644--- a/src/server/shorts-schemas.ts+++ b/src/server/shorts-schemas.ts@@ -16,6 +16,8 @@ const source = z.object({name: z.string().max(200).optional(),duration: z.number().finite().positive().max(3600).optional(),fps: z.number().finite().positive().max(240).optional(),+ width: z.number().int().positive().max(20000).optional(),+ height: z.number().int().positive().max(20000).optional(),});export const ShortsBodySchema = z.object({diff --git a/src/server/shorts.ts b/src/server/shorts.tsindex 4d420029..8a5b586a 100644--- a/src/server/shorts.ts+++ b/src/server/shorts.ts@@ -4,10 +4,12 @@ import { getModel } from "@/lib/catalog";import { maxRefsFor, reframes, resolutionFor, sourceSeconds } from "@/lib/catalog/shorts-models";import {clipLengthProblem,+ clipShapeProblem,customPresetName,getShortsPreset,lookFromCustom,lookFromPreset,+ needsFit,planSegments,planShorts,planStitch,@@ -35,6 +37,7 @@ import { getGeneration, previewChained } from "./generations";import { trashGenerations } from "./library";import { engineMode } from "./settings";import { readRef } from "./storage";+import { probeWebm } from "./webm-probe";/*** Shorts Studio sessions: a clip cut into segments, each restyled (one or more takes, one of them@@ -67,16 +70,28 @@ export interface SourceInfo {hasAudio?: boolean;}-/** What the clip's header says (MP4 / MOV; other containers come back empty and the browser's numbers are used). */+/**+ * What the clip's header says (MP4 / MOV, and WebM / Matroska). A file neither reader knows comes+ * back empty: the browser's numbers are used, and its sound counts as unknown (made without it).+ */export async function probeSource(url: string): Promise<SourceInfo> {if (!url.startsWith("/api/files/")) throw new ShortsError("Upload the clip first");let info: MediaInfo | null = null;+ let data: Buffer;try {- info = probeMedia((await readRef(url)).data);+ data = (await readRef(url)).data;} catch {throw new ShortsError("That clip is gone — upload it again", 404);}- if (!info) return {};+ try {+ info = probeMedia(data);+ } catch {+ info = null;+ }+ if (!info) {+ const webm = probeWebm(data);+ return webm ? { duration: webm.duration, width: webm.width, height: webm.height, fps: webm.fps, hasAudio: webm.hasAudio } : {};+ }return {duration: info.videoDuration ?? info.duration,width: info.width,@@ -198,7 +213,8 @@ export function deleteCustomPreset(id: string): boolean {export interface ShortsBody {engine: Engine;presetId: string;- source: { url: string; name?: string; duration?: number };+ /** width / height: what the browser read, for estimates made before the server has the file. */+ source: { url: string; name?: string; duration?: number; width?: number; height?: number };range: ShortsRange;aspectRatio: ShortsRatio;language: string;@@ -234,7 +250,7 @@ async function planInput(body: ShortsBody, opts: { probe: boolean }): Promise<{const look = lookFor(body.presetId);const info = opts.probe ? await probeSource(body.source.url) : {};const duration = info.duration ?? body.source.duration;- const problem = rangeProblem(body.range, duration);+ const problem = rangeProblem(body.range, duration) ?? clipShapeProblem(info.width ?? body.source.width, info.height ?? body.source.height);if (problem) throw new ShortsError(problem);// Every segment has to be a clip the restyle model takes (a cut outside its window is paid for, then refused).const limits = sourceSeconds(modelId);@@ -242,6 +258,11 @@ async function planInput(body: ShortsBody, opts: { probe: boolean }): Promise<{.map((s) => clipLengthProblem({ name: getModel(modelId)?.name ?? modelId, minSeconds: limits.min, maxSeconds: limits.max }, s.end - s.start)).find(Boolean);if (odd) throw new ShortsError(`${odd} per segment — pick another model`);+ // A custom preset without words on a words-only model would restyle from nothing but "the look of the reference images".+ if (look.custom && !look.described && body.engine === "cloud" && !maxRefsFor(modelId)) {+ const readers = SHORTS_MODELS.cloud.filter((id) => maxRefsFor(id) > 0).map((id) => getModel(id)?.name ?? id);+ throw new ShortsError(`${getModel(modelId)?.name ?? "This model"} restyles from words only — describe the look in your preset, or pick ${readers.join(" or ")}`, 422);+ }const name = fileTitle(body.source.name);return {info,@@ -249,7 +270,14 @@ async function planInput(body: ShortsBody, opts: { probe: boolean }): Promise<{engine: body.engine,title: name ? `${look.name} · ${name}` : `${look.name} short`,// Unknown sound (a container the header reader doesn't know) is treated as present.- source: { url: body.source.url, duration, hasAudio: info.hasAudio ?? true },+ source: {+ url: body.source.url,+ duration,+ // Sound we couldn't read counts as none: a soundtrack step fed a silent file fails after every restyle was paid for.+ hasAudio: info.hasAudio ?? false,+ width: info.width ?? body.source.width,+ height: info.height ?? body.source.height,+ },range: body.range,look,aspectRatio: body.aspectRatio,@@ -257,6 +285,7 @@ async function planInput(body: ShortsBody, opts: { probe: boolean }): Promise<{modelId,maxRefs: maxRefsFor(modelId),resolution: resolutionFor(modelId),+ reframes: body.engine === "open" || reframes(modelId),},};}@@ -292,7 +321,8 @@ function notesFor(input: ShortsPlanInput): string[] {if (refs && input.engine === "cloud" && !input.maxRefs) notes.push(`${getModel(input.modelId)?.name ?? "This model"} restyles from words only — pick Kling O3 4K Edit or Happy Horse to use your reference images`);if (refs > SHORTS.openReferences && input.engine === "open") notes.push(`The open engine uses your first ${SHORTS.openReferences} reference images`);if (input.engine === "cloud") {- if (!reframes(input.modelId)) notes.push(`${getModel(input.modelId)?.name} keeps your clip's shape; the open engine crops to ${input.aspectRatio}`);+ const { width: w, height: h } = input.source;+ if (!input.reframes && w && h && needsFit(input.source, input.aspectRatio)) notes.push(`Your ${w}×${h} clip is centre-cropped to ${input.aspectRatio} before the restyle`);}return notes;}@@ -330,9 +360,9 @@ export async function createSession(body: ShortsBody): Promise<ShortsSession> {const now = Date.now();const segments: ShortsSessionSegment[] = plan.segments.map((s, i) => {const t = plan.takes[i];- return { ...s, takes: [{ cut: id(t.cut), ...(t.frame ? { frame: id(t.frame) } : {}), look: id(t.look), createdAt: now }], primary: id(t.look) };+ return { ...s, takes: [{ cut: id(t.cut), ...(t.fit ? { fit: id(t.fit) } : {}), ...(t.frame ? { frame: id(t.frame) } : {}), look: id(t.look), createdAt: now }], primary: id(t.look) };});- const takeKeys = new Set(plan.takes.flatMap((t) => [t.cut, t.look, ...(t.frame ? [t.frame] : [])]));+ const takeKeys = new Set(plan.takes.flatMap((t) => [t.cut, t.look, ...(t.fit ? [t.fit] : []), ...(t.frame ? [t.frame] : [])]));const stitch: ShortsStitch = {ids: plan.steps.filter((s) => !takeKeys.has(s.key)).map((s) => id(s.key)),final: id(plan.final!),@@ -347,7 +377,7 @@ export async function createSession(body: ShortsBody): Promise<ShortsSession> {look: input.look,source: { url: input.source.url, name: body.source.name, duration: input.source.duration, hasAudio: input.source.hasAudio, width: info.width, height: info.height },range: input.range,- settings: { aspectRatio: input.aspectRatio, language: input.language, modelId: input.modelId, resolution: input.resolution, maxRefs: input.maxRefs },+ settings: { aspectRatio: input.aspectRatio, language: input.language, modelId: input.modelId, resolution: input.resolution, maxRefs: input.maxRefs, reframes: input.reframes },segments,stitches: [stitch],createdAt: now,@@ -377,7 +407,7 @@ export async function createSession(body: ShortsBody): Promise<ShortsSession> {/** Every generation a session made. */export function sessionIds(s: ShortsSession): string[] {- const ids = [...s.segments.flatMap((g) => g.takes.flatMap((t) => [t.cut, t.look, ...(t.frame ? [t.frame] : [])])), ...s.stitches.flatMap((x) => [...x.ids, x.final])];+ const ids = [...s.segments.flatMap((g) => g.takes.flatMap((t) => [t.cut, ...(t.fit ? [t.fit] : []), ...(t.frame ? [t.frame] : []), t.look])), ...s.stitches.flatMap((x) => [...x.ids, x.final])];return [...new Set(ids)];}@@ -471,7 +501,13 @@ export function regenerateSegment(id: string, index: number): ShortsSessionViewthrow new ShortsError((e as Error).message, 422);}const id_ = (k: string) => pipeline.byKey[k].id;- const next = { cut: id_(take.keys.cut), ...(take.keys.frame ? { frame: id_(take.keys.frame) } : {}), look: id_(take.keys.look), createdAt: Date.now() };+ const next = {+ cut: id_(take.keys.cut),+ ...(take.keys.fit ? { fit: id_(take.keys.fit) } : {}),+ ...(take.keys.frame ? { frame: id_(take.keys.frame) } : {}),+ look: id_(take.keys.look),+ createdAt: Date.now(),+ };const segments = s.segments.map((g, i) => (i === index ? { ...g, takes: [...g.takes, next], primary: usable(g.primary) ? g.primary : next.look } : g));saveSession({ ...s, segments });return getSession(id);diff --git a/src/server/webm-probe.ts b/src/server/webm-probe.tsnew file mode 100644index 00000000..1f90938f--- /dev/null+++ b/src/server/webm-probe.ts@@ -0,0 +1,125 @@+/**+ * What a WebM / Matroska file's header says: length, picture size, frame rate and whether it has a+ * sound track. src/lib/media-probe.ts reads MP4 / MOV only; Shorts Studio and Mixed Media also take+ * WebM (screen and browser recordings), and a clip whose sound is unknown can't be assumed to have+ * one (the soundtrack step would fail after every restyle was paid for).+ *+ * Reads the EBML elements up to the first Cluster: Segment → Info (TimecodeScale, Duration) and+ * Tracks → TrackEntry (TrackType, DefaultDuration, Video → PixelWidth / PixelHeight). Pure.+ */++export interface WebmInfo {+ duration?: number;+ width?: number;+ height?: number;+ fps?: number;+ hasAudio: boolean;+ hasVideo: boolean;+}++const ID = {+ EBML: 0x1a45dfa3,+ Segment: 0x18538067,+ Info: 0x1549a966,+ TimecodeScale: 0x2ad7b1,+ Duration: 0x4489,+ Tracks: 0x1654ae6b,+ TrackEntry: 0xae,+ TrackType: 0x83,+ DefaultDuration: 0x23e383,+ Video: 0xe0,+ PixelWidth: 0xb0,+ PixelHeight: 0xba,+ Cluster: 0x1f43b675,+} as const;++/** A variable-length integer at `at`: its value (with the length marker kept for IDs) and byte length. */+function vint(buf: Buffer, at: number, keepMarker: boolean): { value: number; len: number; unknown: boolean } | null {+ if (at >= buf.length) return null;+ const first = buf[at];+ let len = 1;+ while (len <= 8 && !(first & (0x80 >> (len - 1)))) len++;+ if (len > 8 || at + len > buf.length) return null;+ let value = keepMarker ? first : first & (0xff >> len);+ let allOnes = value === (0xff >> len);+ for (let i = 1; i < len; i++) {+ value = value * 256 + buf[at + i];+ if (buf[at + i] !== 0xff) allOnes = false;+ }+ return { value, len, unknown: !keepMarker && allOnes };+}++const uint = (buf: Buffer, at: number, size: number) => {+ let v = 0;+ for (let i = 0; i < size; i++) v = v * 256 + buf[at + i];+ return v;+};++const float = (buf: Buffer, at: number, size: number) => (size === 4 ? buf.readFloatBE(at) : size === 8 ? buf.readDoubleBE(at) : NaN);++interface El {+ id: number;+ start: number;+ end: number;+ unknown: boolean;+}++/** The elements directly inside [from, to). Stops at a Cluster (the media data) or anything unreadable. */+function children(buf: Buffer, from: number, to: number): El[] {+ const out: El[] = [];+ let at = from;+ while (at < to && out.length < 4096) {+ const id = vint(buf, at, true);+ if (!id) break;+ const size = vint(buf, at + id.len, false);+ if (!size) break;+ const start = at + id.len + size.len;+ const end = size.unknown ? to : Math.min(to, start + size.value);+ out.push({ id: id.value, start, end, unknown: size.unknown });+ if (id.value === ID.Cluster || size.unknown) break;+ at = end;+ }+ return out;+}++/** The header of a WebM / Matroska file, or null when it isn't one. */+export function probeWebm(buf: Buffer): WebmInfo | null {+ const top = children(buf, 0, buf.length);+ if (top[0]?.id !== ID.EBML) return null;+ const segment = top.find((e) => e.id === ID.Segment);+ if (!segment) return null;+ const info: WebmInfo = { hasAudio: false, hasVideo: false };+ let scale = 1_000_000;+ let rawDuration: number | undefined;+ for (const el of children(buf, segment.start, segment.end)) {+ if (el.id === ID.Cluster) break;+ if (el.id === ID.Info) {+ for (const f of children(buf, el.start, el.end)) {+ if (f.id === ID.TimecodeScale) scale = uint(buf, f.start, f.end - f.start) || scale;+ if (f.id === ID.Duration) rawDuration = float(buf, f.start, f.end - f.start);+ }+ }+ if (el.id === ID.Tracks) {+ for (const track of children(buf, el.start, el.end).filter((t) => t.id === ID.TrackEntry)) {+ const fields = children(buf, track.start, track.end);+ const type = fields.find((f) => f.id === ID.TrackType);+ const kind = type ? uint(buf, type.start, type.end - type.start) : 0;+ if (kind === 2) info.hasAudio = true;+ if (kind !== 1) continue;+ info.hasVideo = true;+ const frame = fields.find((f) => f.id === ID.DefaultDuration);+ const ns = frame ? uint(buf, frame.start, frame.end - frame.start) : 0;+ if (ns > 0 && info.fps === undefined) info.fps = Math.round((1e9 / ns) * 1000) / 1000;+ const video = fields.find((f) => f.id === ID.Video);+ if (video && info.width === undefined) {+ for (const v of children(buf, video.start, video.end)) {+ if (v.id === ID.PixelWidth) info.width = uint(buf, v.start, v.end - v.start);+ if (v.id === ID.PixelHeight) info.height = uint(buf, v.start, v.end - v.start);+ }+ }+ }+ }+ }+ if (rawDuration !== undefined && Number.isFinite(rawDuration) && rawDuration > 0) info.duration = Math.round(((rawDuration * scale) / 1e9) * 1000) / 1000;+ return info.hasVideo || info.hasAudio ? info : null;+}diff --git a/tests/chain-soundtrack.test.ts b/tests/chain-soundtrack.test.tsnew file mode 100644index 00000000..5a2d0872--- /dev/null+++ b/tests/chain-soundtrack.test.ts@@ -0,0 +1,38 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { OutputFile } from "@/lib/catalog/types";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soundtrack-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+const { pickOutput } = await import("@/server/generations");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const clip: OutputFile = { url: "/api/files/cut.mp4", kind: "video", contentType: "video/mp4" };+const still: OutputFile = { url: "/api/files/frame.png", kind: "image", contentType: "image/png" };+const voice: OutputFile = { url: "/api/files/voice.wav", kind: "audio", contentType: "audio/wav", meta: { stem: "vocals" } };+const bed: OutputFile = { url: "/api/files/bed.wav", kind: "audio", contentType: "audio/wav", meta: { stem: "accompaniment" } };++describe("pickOutput: which output of an earlier step a chained slot takes", () => {+ it("an audio slot fed by a step that made only a clip takes the clip (its soundtrack, for the mux)", () => {+ expect(pickOutput([clip], { slot: "audio" })).toBe(clip);+ expect(pickOutput([still, clip], { slot: "audio2" })).toBe(clip);+ });++ it("an audio slot prefers real audio, and a stem only ever matches audio with that stem", () => {+ expect(pickOutput([clip, voice], { slot: "audio" })).toBe(voice);+ expect(pickOutput([clip], { slot: "audio", stem: "voice" })).toBeUndefined();+ expect(pickOutput([voice, bed], { slot: "audio", stem: "background" })).toBe(bed);+ expect(pickOutput([voice, bed], { slot: "audio2", stem: "voice" })).toBe(voice);+ });++ it("other slots are unchanged: a video slot takes a video, an image slot an image, never a stand-in", () => {+ expect(pickOutput([still, clip], { slot: "video" })).toBe(clip);+ expect(pickOutput([voice], { slot: "video" })).toBeUndefined();+ expect(pickOutput([clip, still], { slot: "images" })).toBe(still);+ expect(pickOutput([clip], { slot: "images" })).toBeUndefined();+ expect(pickOutput([clip], { slot: "voiceAudio" })).toBeUndefined();+ });+});diff --git a/tests/fixtures/shorts-silent.webm b/tests/fixtures/shorts-silent.webmnew file mode 100644index 00000000..86edc075Binary files /dev/null and b/tests/fixtures/shorts-silent.webm differdiff --git a/tests/fixtures/shorts-sound.webm b/tests/fixtures/shorts-sound.webmnew file mode 100644index 00000000..017f8017Binary files /dev/null and b/tests/fixtures/shorts-sound.webm differdiff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.tsindex d6007892..74da97df 100644--- a/tests/shorts-api.test.ts+++ b/tests/shorts-api.test.ts@@ -27,6 +27,7 @@ const presetsRoute = await import("@/app/api/shorts/presets/route");const mixedRoute = await import("@/app/api/mixed-media/route");const mixedPreviewRoute = await import("@/app/api/mixed-media/preview/route");const mixedEstimateRoute = await import("@/app/api/mixed-media/estimate/route");+const mixedRetryRoute = await import("@/app/api/mixed-media/retry/route");const json = (method: string, body?: unknown) =>new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });@@ -89,7 +90,10 @@ describe("Shorts sessions", () => {expect(est.costUsd!).toBeLessThan(1.25);expect(est.perSegmentUsd!).toBeGreaterThanOrEqual(0.6);expect(est.perSegmentUsd!).toBeLessThan(0.62);- expect(est.notes.join(" ")).toMatch(/keeps your clip's shape/);+ // A 9:16 clip for a 9:16 short: nothing to crop. The same clip as a 16:9 short is centre-cropped first.+ expect(est.notes.join(" ")).not.toMatch(/cropped/);+ const wide = await shorts.estimateShorts(body({ aspectRatio: "16:9", source: { url: clip, duration: 12, width: 72, height: 128 } }) as never);+ expect(wide.notes).toContain("Your 72×128 clip is centre-cropped to 16:9 before the restyle");} finally {setSetting("falKey", "");}@@ -199,6 +203,23 @@ describe("Shorts sessions", () => {shorts.deleteSession(c.id);});+ it("crops each cut to the output ratio before a restyle model that keeps its input's shape", async () => {+ const s = await shorts.createSession(body({ aspectRatio: "16:9", range: { start: 0, end: 8 } }) as never);+ expect(s.source).toMatchObject({ width: 72, height: 128 });+ const take = s.segments[0].takes[0];+ expect(take.fit).toEqual(expect.any(String));+ expect(gens.getGeneration(take.fit!)).toMatchObject({ modelId: "scale-video", op: "reframe", request: { params: { aspectRatio: "16:9", extra: { width: 1920, height: 1080 } } } });+ expect(dependsOn(take.fit!)).toEqual([take.cut]);+ expect(dependsOn(take.look)).toEqual([take.fit]);+ expect(shorts.sessionIds(s)).toContain(take.fit);+ // A new take crops its cut too.+ const again = shorts.regenerateSegment(s.id, 0).segments[0].takes[1];+ expect(dependsOn(again.look)).toEqual([again.fit]);+ expect(await settle(s.stitches[0].final)).toMatchObject({ status: "succeeded" });+ await settle(again.look);+ shorts.deleteSession(s.id);+ });+it("won't stitch while a segment is still rendering", async () => {const s = shorts.regenerateSegment(sessionId, 0);const take = s.segments[0].takes.at(-1)!.look;@@ -253,6 +274,38 @@ describe("Shorts sessions", () => {expect(est.notes[0]).toMatch(/restyles from words only/);});+ it("reads WebM headers: a silent recording gets no soundtrack step (it would fail after the restyles were paid for)", async () => {+ const webm = (name: string) => saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures", name)), contentType: "video/webm", source: "upload", name }).url;+ const silent = webm("shorts-silent.webm");+ expect(await shorts.probeSource(silent)).toMatchObject({ hasAudio: false, width: 96, height: 64 });+ expect((await shorts.probeSource(webm("shorts-sound.webm"))).hasAudio).toBe(true);+ const s = await shorts.createSession(body({ source: { url: silent, name: "screen.webm" }, range: { start: 0, end: 6 } }) as never);+ expect(s.source.hasAudio).toBe(false);+ const final = gens.getGeneration(s.stitches[0].final)!;+ expect(final.op).toBe("v2v");+ expect(Object.values(shorts.getSession(s.id).generations).some((g) => g.op === "mux")).toBe(false);+ await settle(final.id);+ // A file nobody can read counts as silent too.+ const junk = saveFile({ data: Buffer.from("not a video"), contentType: "video/mp4", source: "upload", name: "x.mp4" }).url;+ expect(await shorts.probeSource(junk)).toEqual({});+ shorts.deleteSession(s.id);+ });++ it("checks the picture's size and shape, and custom presets on words-only models", async () => {+ const big = await estimateRoute.POST(json("POST", body({ source: { url: "/api/files/placeholder.mp4", duration: 12, width: 7680, height: 4320 } })));+ expect(big.status).toBe(400);+ expect((await big.json()).error).toBe("This clip is 7680×4320 — use one up to 4000 px on its long side");+ const tall = await estimateRoute.POST(json("POST", body({ source: { url: "/api/files/placeholder.mp4", duration: 12, width: 400, height: 1600 } })));+ expect((await tall.json()).error).toBe("Use a clip between 1:3 and 3:1");+ const bare = shorts.createCustomPreset({ references: [png] });+ const words = await estimateRoute.POST(json("POST", body({ presetId: bare.id })));+ expect(words.status).toBe(422);+ expect((await words.json()).error).toBe("Gemini Omni Flash 1.1 restyles from words only — describe the look in your preset, or pick Kling O3 4K Edit or Happy Horse Video Edit");+ const kling = await (await estimateRoute.POST(json("POST", body({ presetId: bare.id, modelId: "kling-o3-4k-edit" })))).json();+ expect(kling.refsSent).toBe(1);+ shorts.deleteCustomPreset(bare.id);+ });+it("respects the engine mode", async () => {setSetting("engineMode", "open");try {@@ -314,6 +367,26 @@ describe("Mixed Media renders", () => {expect(await settle(final.id)).toMatchObject({ status: "succeeded", feature: "mixed-media" });});+ it("tries a failed render again with the same settings, from its first step", async () => {+ const { final, items } = await mixed.createMixed(mm({ engine: "cloud", range: { start: 1, end: 4 } }) as never);+ // The restyle stops: the soundtrack step then fails with the generic "An earlier step didn't finish".+ await gens.cancelGeneration(items[1].id);+ expect(await settle(final.id)).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });+ const res = await mixedRetryRoute.POST(json("POST", { id: final.id, requestId: "mm-retry-0001" }));+ expect(res.status).toBe(201);+ const again = await res.json();+ expect(again.items.map((g: Generation) => g.modelId)).toEqual(["trim-video", "ltx-2-3-restyle", "merge-audio-video"]);+ expect(again.final.id).not.toBe(final.id);+ expect(again.final.batchId).not.toBe(final.batchId);+ // Same settings; the chained inputs are filled again by the new steps.+ expect(again.items[1].request).toMatchObject({ prompt: items[1].request.prompt, params: items[1].request.params });+ expect(again.items[1].request.inputs?.video).toBeUndefined();+ expect(dependsOn(again.final.id)).toEqual([again.items[1].id, again.items[0].id]);+ expect(await settle(again.final.id)).toMatchObject({ status: "succeeded" });+ const gone = await mixedRetryRoute.POST(json("POST", { id: "nope" }));+ expect(gone.status).toBe(404);+ });+it("starts one render per request id", async () => {const req = () => mixedRoute.POST(json("POST", mm({ requestId: "mm-render-0001" })));const [a, b] = await Promise.all([req(), req()]);diff --git a/tests/shorts.test.ts b/tests/shorts.test.tsindex 675ecdcc..e7bfa865 100644--- a/tests/shorts.test.ts+++ b/tests/shorts.test.ts@@ -3,6 +3,8 @@ import { getModel } from "@/lib/catalog";import {chainState,customPresetName,+ fitSize,+ needsFit,firstFramePrompt,formatSeconds,joinGroups,@@ -28,6 +30,8 @@ import {type ShortsPlanInput,} from "@/lib/catalog/shorts";import { FX } from "@/lib/preset-cards";+import { MOTIF_IDS } from "@/components/shorts/look-motif";+import { MIXED_PRESETS } from "@/lib/catalog/mixed-media";const claymation = SHORTS_PRESETS.find((p) => p.name === "Claymation")!;const kinetic = SHORTS_PRESETS.find((p) => p.name === "Kinetic Type")!;@@ -46,6 +50,12 @@ const input = (over: Partial<ShortsPlanInput> = {}): ShortsPlanInput => ({});describe("Shorts presets and catalog", () => {+ it("gives every Shorts and Mixed Media preset its own motif on the card (lettering, scribbles, paper, grids…)", () => {+ const ids = [...SHORTS_PRESETS, ...MIXED_PRESETS].map((p) => p.id);+ expect(ids.filter((id) => !MOTIF_IDS.includes(id))).toEqual([]);+ expect(MOTIF_IDS.filter((id) => !ids.includes(id))).toEqual([]);+ });+it("has Higgsfield's 44 presets with Fuobe's own descriptions and looks", () => {expect(SHORTS_PRESETS).toHaveLength(44);expect(new Set(SHORTS_PRESETS.map((p) => p.id)).size).toBe(44);@@ -191,20 +201,23 @@ describe("Shorts segment planning", () => {});describe("Shorts pipeline shape", () => {- it("cloud: cut → restyle per segment, one join, then the original sound from the upload", () => {+ it("cloud: cut → crop to the ratio → restyle per segment, one join, then the original sound from the upload", () => {const plan = planShorts(input());expect(plan.segments).toHaveLength(3);const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));- expect(Object.keys(by)).toEqual(["cut0", "look0", "cut1", "look1", "cut2", "look2", "join", "final"]);+ expect(Object.keys(by)).toEqual(["cut0", "fit0", "look0", "cut1", "fit1", "look1", "cut2", "fit2", "look2", "join", "final"]);expect(by.cut1.request).toMatchObject({ modelId: "trim-video", op: "trim", inputs: { video: "/api/files/uploads/beach.mp4" }, params: { startTime: 10, endTime: 20 } });- expect(by.look1).toMatchObject({ after: ["cut1"], chain: [{ slot: "video" }], request: { modelId: "gemini-omni-flash", op: "v2v", params: { aspectRatio: "9:16", duration: 10 } } });+ // The restyle model keeps its input's shape: the cut is centre-cropped to 9:16 first.+ expect(by.fit1).toMatchObject({ after: ["cut1"], chain: [{ slot: "video" }], request: { modelId: "scale-video", op: "reframe", params: { aspectRatio: "9:16", extra: { width: 1080, height: 1920 } } } });+ expect(by.look1).toMatchObject({ after: ["fit1"], chain: [{ slot: "video" }], request: { modelId: "gemini-omni-flash", op: "v2v", params: { aspectRatio: "9:16", duration: 10 } } });expect(by.look1.request.inputs).toBeUndefined();expect(by.join).toMatchObject({ after: ["look0", "look1", "look2"], request: { modelId: "join-clips", op: "concat" } });expect(by.join.chain).toHaveLength(3);// The whole clip was used: the upload itself carries the sound.expect(by.final).toMatchObject({ after: ["join"], chain: [{ slot: "video" }], request: { modelId: "merge-audio-video", op: "mux", inputs: { audio: "/api/files/uploads/beach.mp4" }, title: "Claymation · beach" } });expect(plan.final).toBe("final");- for (const s of plan.steps) expect(s.request).toMatchObject({ feature: "shorts", batchTitle: "Claymation · beach" });+ // The takes and the finished short are "shorts"; the cuts, crops and joins in between are "shorts-step".+ for (const s of plan.steps) expect(s.request).toMatchObject({ feature: /^(look|final)/.test(s.key) ? "shorts" : "shorts-step", batchTitle: "Claymation · beach" });expect(by.look2.request.step).toEqual({ label: "Segment 3 of 3 · restyle", index: 2, of: 3 });});@@ -222,20 +235,37 @@ describe("Shorts pipeline shape", () => {const silent = planShorts(input({ source: { url: "/api/files/x.mp4", duration: 30, hasAudio: false } }));expect(silent.steps.map((s) => s.key)).not.toContain("final");expect(silent.final).toBe("join");- expect(silent.steps.find((s) => s.key === "join")!.request.title).toBe("Claymation · beach");- const one = planShorts(input({ source: { url: "/api/files/x.mp4", duration: 8, hasAudio: false }, range: { start: 0, end: 8 } }));+ expect(silent.steps.find((s) => s.key === "join")!.request).toMatchObject({ title: "Claymation · beach", feature: "shorts" });+ const one = planShorts(input({ source: { url: "/api/files/x.mp4", duration: 8, hasAudio: false, width: 1080, height: 1920 }, range: { start: 0, end: 8 } }));expect(one.steps.map((s) => s.key)).toEqual(["cut0", "look0"]);expect(one.final).toBe("look0");});+ it("crops only clips of another shape (or of an unknown one), and only for models that can't be asked for the ratio", () => {+ const at = (width: number, height: number, aspectRatio: "9:16" | "16:9" = "9:16") =>+ planTake(input({ aspectRatio, source: { url: "/api/files/x.mp4", duration: 30, hasAudio: true, width, height } }), { index: 0, start: 0, end: 5 }, 1).keys;+ expect(at(1920, 1080).fit).toBe("fit0");+ expect(at(1080, 1920).fit).toBeUndefined();+ expect(at(720, 1280).fit).toBeUndefined();+ expect(at(1920, 1080, "16:9").fit).toBeUndefined();+ expect(at(1080, 1920, "16:9").fit).toBe("fit0");+ expect(needsFit({}, "9:16")).toBe(true);+ expect(fitSize("16:9")).toEqual({ width: 1920, height: 1080 });+ const asked = planTake(input({ reframes: true }), { index: 0, start: 0, end: 5 }, 1);+ expect(asked.keys.fit).toBeUndefined();+ expect(asked.steps[1]).toMatchObject({ after: ["cut0"], request: { params: { aspectRatio: "9:16" } } });+ expect(takeSteps({ cut: "c", fit: "f", look: "l" }, {}).map((s) => s.label)).toEqual(["Cutting the segment", "Cropping the segment", "Restyling"]);+ });+it("sends references only to cloud models that take them, up to their limit", () => {const refs = Array.from({ length: 6 }, (_, i) => `/api/files/ref${i}.png`);const look = { ...lookFromPreset(claymation), references: refs };const words = planTake(input({ look }), { index: 0, start: 0, end: 5 }, 1);- expect(words.steps[1].request.inputs).toBeUndefined();+ expect(words.steps.find((s) => s.key === words.keys.look)!.request.inputs).toBeUndefined();const kling = planTake(input({ look, modelId: "kling-o3-4k-edit", maxRefs: 4 }), { index: 0, start: 0, end: 5 }, 1);- expect(kling.steps[1].request.inputs?.images).toEqual(refs.slice(0, 4));- expect(kling.steps[1].request.prompt).toMatch(/Match the style of the reference images/);+ const klingLook = kling.steps.find((s) => s.key === kling.keys.look)!;+ expect(klingLook.request.inputs?.images).toEqual(refs.slice(0, 4));+ expect(klingLook.request.prompt).toMatch(/Match the style of the reference images/);});it("open: segment (with its first frame) → restyled first frame → Wan VACE, joined 4 at a time", () => {diff --git a/tests/trim-range.test.ts b/tests/trim-range.test.tsindex d8e56af3..f2c62089 100644--- a/tests/trim-range.test.ts+++ b/tests/trim-range.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { clampRange, clock, initialRange, moveRange, setEdge, thumbTimes, trimHint } from "@/lib/trim-range";+import { clampRange, clock, initialRange, moveRange, parseTime, setEdge, thumbTimes, trimHint, trimKey } from "@/lib/trim-range";const L = { duration: 30, min: 4, max: 10 };@@ -48,3 +48,37 @@ describe("video trimmer arithmetic", () => {expect(clock(4)).toBe("0:04.0");});});++describe("video trimmer keyboard (the sliders' contract, shared by every studio that uses it)", () => {+ const r = { startTime: 5, endTime: 12 };+ it("moves the start, end and window by 0.1 s, ×10 with Shift, 5 s with Page Up / Down", () => {+ expect(trimKey(r, "start", "ArrowRight", false, L)).toEqual({ startTime: 5.1, endTime: 12 });+ expect(trimKey(r, "start", "ArrowLeft", true, L)).toEqual({ startTime: 4, endTime: 12 });+ expect(trimKey(r, "end", "ArrowUp", false, L)).toEqual({ startTime: 5, endTime: 12.1 });+ expect(trimKey(r, "end", "PageDown", false, L)).toEqual({ startTime: 5, endTime: 9 });+ expect(trimKey(r, "move", "PageUp", false, L)).toEqual({ startTime: 10, endTime: 17 });+ expect(trimKey(r, "move", "ArrowLeft", true, L)).toEqual({ startTime: 4, endTime: 11 });+ });+ it("Home / End go to the clip's ends within the min and max length", () => {+ // The start can't go further back than 10 s (max) before the end.+ expect(trimKey(r, "start", "Home", false, L)).toEqual({ startTime: 2, endTime: 12 });+ expect(trimKey(r, "end", "End", false, L)).toEqual({ startTime: 5, endTime: 15 });+ expect(trimKey(r, "move", "Home", false, L)).toEqual({ startTime: 0, endTime: 7 });+ expect(trimKey(r, "move", "End", false, L)).toEqual({ startTime: 23, endTime: 30 });+ // Never shorter than the min (4 s).+ expect(trimKey({ startTime: 5, endTime: 9 }, "end", "PageDown", false, L)).toEqual({ startTime: 5, endTime: 9 });+ expect(trimKey({ startTime: 5, endTime: 9 }, "start", "ArrowRight", true, L)).toEqual({ startTime: 5, endTime: 9 });+ });+ it("ignores other keys", () => {+ expect(trimKey(r, "start", "a", false, L)).toBeNull();+ expect(trimKey(r, "move", "Tab", false, L)).toBeNull();+ });+ it("reads typed times", () => {+ expect(parseTime("12.5")).toBe(12.5);+ expect(parseTime("0:12.5")).toBe(12.5);+ expect(parseTime("1:05")).toBe(65);+ expect(parseTime(" 7 s ")).toBe(7);+ expect(parseTime("abc")).toBeNaN();+ expect(setEdge(r, "end", parseTime("0:12.5"), L)).toEqual({ startTime: 5, endTime: 12.5 });+ });+});diff --git a/tests/webm-probe.test.ts b/tests/webm-probe.test.tsnew file mode 100644index 00000000..a1067456--- /dev/null+++ b/tests/webm-probe.test.ts@@ -0,0 +1,33 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { probeWebm } from "@/server/webm-probe";++const fixture = (name: string) => fs.readFileSync(path.join(__dirname, "fixtures", name));++describe("probeWebm", () => {+ it("reads a WebM's length, size, frame rate and whether it has sound", () => {+ expect(probeWebm(fixture("shorts-sound.webm"))).toMatchObject({ hasAudio: true, hasVideo: true, width: 96, height: 64 });+ const silent = probeWebm(fixture("shorts-silent.webm"))!;+ expect(silent).toMatchObject({ hasAudio: false, hasVideo: true, width: 96, height: 64 });+ expect(silent.duration).toBeCloseTo(6, 1);+ });++ it("isn't fooled by other files", () => {+ expect(probeWebm(fixture("shorts-12s.mp4"))).toBeNull();+ expect(probeWebm(Buffer.from("not a video at all"))).toBeNull();+ expect(probeWebm(Buffer.alloc(0))).toBeNull();+ });++ it("reads a recording whose Segment has an unknown size and no Duration (MediaRecorder)", () => {+ const el = (id: number[], body: Buffer) => Buffer.concat([Buffer.from(id), Buffer.from([0x80 | body.length]), body]);+ const u = (n: number) => Buffer.from([n]);+ const track = (type: number, extra: Buffer = Buffer.alloc(0)) => el([0xae], Buffer.concat([el([0x83], u(type)), extra]));+ const video = el([0xe0], Buffer.concat([el([0xb0], Buffer.from([0x02, 0x80])), el([0xba], Buffer.from([0x01, 0x68]))]));+ const tracks = el([0x16, 0x54, 0xae, 0x6b], Buffer.concat([track(1, video), track(2)]));+ const header = el([0x1a, 0x45, 0xdf, 0xa3], el([0x42, 0x82], Buffer.from("webm")));+ // Segment with the "unknown size" marker (all ones), then an unknown-size Cluster.+ const segment = Buffer.concat([Buffer.from([0x18, 0x53, 0x80, 0x67, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), tracks, Buffer.from([0x1f, 0x43, 0xb6, 0x75, 0xff]), Buffer.alloc(32)]);+ expect(probeWebm(Buffer.concat([header, segment]))).toEqual({ hasAudio: true, hasVideo: true, width: 640, height: 360 });+ });+});