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
Video tools: a Remove object tab — type it, click it or paint it on the first frame, price first, before and after
Claude91b6662f52ca
diff --git a/src/components/remove-object/frame-stage.tsx b/src/components/remove-object/frame-stage.tsxnew file mode 100644index 00000000..70d2af2f--- /dev/null+++ b/src/components/remove-object/frame-stage.tsx@@ -0,0 +1,142 @@+"use client";++import { Crosshair, X } from "lucide-react";+import { useRef, useState } from "react";+import type { PixelPoint } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";++export interface Frame {+ /** The first frame of the selection as the browser grabbed it (an object URL). */+ url: string;+ width: number;+ height: number;+}++const pct = (n: number) => `${Math.round(n * 1000) / 10}%`;++/**+ * The selection's first frame with what you marked on it: clicked points (green = remove, grey = keep) or the+ * painted area. In click mode it takes clicks, and the keyboard: arrows move a crosshair (Shift: further),+ * Enter adds a point where it is, Delete takes the last one away.+ */+export function FrameStage({+ frame,+ points,+ onPoints,+ pointLabel,+ overlay,+ clickable,+ maxPoints,+ children,+}: {+ frame: Frame;+ points: PixelPoint[];+ onPoints?: (p: PixelPoint[]) => void;+ /** What a new point marks. */+ pointLabel: "positive" | "negative";+ /** The painted area (the editor's red-tinted copy of the frame). */+ overlay?: string;+ clickable: boolean;+ maxPoints: number;+ children?: React.ReactNode;+}) {+ const box = useRef<HTMLDivElement>(null);+ const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);+ const add = (x: number, y: number) => {+ if (!onPoints || points.length >= maxPoints) return;+ onPoints([...points, { x: Math.round(x * frame.width), y: Math.round(y * frame.height), label: pointLabel }]);+ };+ const onKey = (e: React.KeyboardEvent) => {+ if (!clickable) return;+ const step = e.shiftKey ? 0.1 : 0.02;+ const c = cursor ?? { x: 0.5, y: 0.5 };+ const move = ({ ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] } as Record<string, [number, number]>)[e.key];+ if (move) {+ e.preventDefault();+ setCursor({ x: Math.min(1, Math.max(0, c.x + move[0])), y: Math.min(1, Math.max(0, c.y + move[1])) });+ } else if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ add(c.x, c.y);+ setCursor(c);+ } else if ((e.key === "Delete" || e.key === "Backspace") && points.length) {+ e.preventDefault();+ onPoints?.(points.slice(0, -1));+ }+ };+ return (+ <div className="space-y-2">+ <div className="grid place-items-center overflow-hidden rounded-xl bg-media">+ <div+ ref={box}+ tabIndex={clickable ? 0 : -1}+ role={clickable ? "application" : undefined}+ aria-label={+ clickable+ ? `First frame. Click what to remove${pointLabel === "negative" ? " — marking what to keep" : ""}. Arrow keys move a crosshair, Enter adds a point, Delete removes the last. ${points.length} point${points.length === 1 ? "" : "s"} so far.`+ : undefined+ }+ onKeyDown={onKey}+ onFocus={() => clickable && setCursor((c) => c ?? { x: 0.5, y: 0.5 })}+ onBlur={() => setCursor(null)}+ onClick={(e) => {+ if (!clickable) return;+ const r = box.current!.getBoundingClientRect();+ add((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height);+ }}+ className={cn("relative outline-none focus-visible:ring-2 focus-visible:ring-ring", clickable && "cursor-crosshair")}+ // The box has the frame's own shape (as wide as fits, at most 46vh tall), so points land where they're clicked.+ style={{ aspectRatio: `${frame.width} / ${frame.height}`, width: `min(100%, calc(min(46vh, 520px) * ${(frame.width / frame.height).toFixed(4)}))` }}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={overlay ?? frame.url} alt="The first frame of the selection" className="absolute inset-0 size-full object-contain select-none" draggable={false} />+ {points.map((p, i) => (+ <span+ key={i}+ aria-hidden+ className={cn(+ "absolute grid size-6 -translate-1/2 place-items-center rounded-full border-2 border-white text-[11px] font-semibold text-white shadow-normal",+ p.label === "negative" ? "bg-zinc-500" : "bg-success",+ )}+ style={{ left: pct(p.x / frame.width), top: pct(p.y / frame.height) }}+ >+ {i + 1}+ </span>+ ))}+ {clickable && cursor && (+ <span aria-hidden className="pointer-events-none absolute -translate-1/2 text-white mix-blend-difference" style={{ left: pct(cursor.x), top: pct(cursor.y) }}>+ <Crosshair className="size-7" />+ </span>+ )}+ {children}+ </div>+ </div>+ {points.length > 0 && onPoints && (+ <ul className="flex flex-wrap gap-1.5" aria-label="Points">+ {points.map((p, i) => (+ <li key={i}>+ <button+ type="button"+ onClick={() => onPoints(points.filter((_, j) => j !== i))}+ className="inline-flex h-7 items-center gap-1 rounded-full bg-muted px-2.5 text-[12px] font-medium hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ aria-label={`Take away point ${i + 1} (${p.label === "negative" ? "keep" : "remove"})`}+ >+ <span className={cn("size-2 rounded-full", p.label === "negative" ? "bg-zinc-500" : "bg-success")} />+ {i + 1} · {p.label === "negative" ? "keep" : "remove"}+ <X className="size-3 text-muted-foreground" />+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++/** A frame of a clip as a still: the browser's own decode, at most `maxSide` px. */+export async function frameFromBlob(blob: Blob): Promise<Frame> {+ const url = URL.createObjectURL(blob);+ const img = new Image();+ img.src = url;+ await img.decode();+ return { url, width: img.naturalWidth, height: img.naturalHeight };+}diff --git a/src/components/remove-object/hooks.ts b/src/components/remove-object/hooks.tsnew file mode 100644index 00000000..5ad739ef--- /dev/null+++ b/src/components/remove-object/hooks.ts@@ -0,0 +1,67 @@+"use client";++import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useDeferredValue } from "react";+import type { RemoveMode } from "@/lib/catalog/remove-object";+import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";+import { send } from "@/components/shorts/hooks";++/** React Query hooks for /api/remove-object/** (the Remove object tab of Video tools). */++export interface RemovalBody {+ engine: Engine;+ mode: RemoveMode;+ modelId?: string;+ effects?: boolean;+ prompt?: string;+ points?: PixelPoint[];+ frame?: { width: number; height: number };+ mask?: string;+ source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };+ range?: { start: number; end: number };+ /** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */+ requestId?: string;+}++export interface RemovalEstimate {+ costUsd: number | null;+ demo: boolean;+ modelId: string;+ modelName: string;+ pieces: number;+ seconds: number;+ steps: number;+ notes: string[];+ previewUsd: number | null;+}++/** The price and shape of a removal for the current settings (debounced by React's deferred value). */+export function useRemovalEstimate(body: RemovalBody | null) {+ const key = useDeferredValue(body ? JSON.stringify(body) : null);+ return useQuery({+ queryKey: ["remove-object", "estimate", key],+ queryFn: async () => send<RemovalEstimate>("/api/remove-object/estimate", "POST", JSON.parse(key!)),+ enabled: !!key,+ placeholderData: keepPreviousData,+ retry: false,+ staleTime: 30_000,+ });+}++export function useRemovalActions() {+ const qc = useQueryClient();+ const seed = (g: Generation) => qc.setQueryData(["generation", g.id], g);+ return {+ run: useMutation({+ mutationFn: (b: RemovalBody) => send<{ final: Generation; items: Generation[] }>("/api/remove-object", "POST", b),+ onSuccess: (r) => {+ r.items.forEach(seed);+ void qc.invalidateQueries({ queryKey: ["generations"] });+ },+ }),+ preview: useMutation({+ mutationFn: (b: RemovalBody) => send<Generation>("/api/remove-object/preview", "POST", b),+ onSuccess: seed,+ }),+ };+}diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsxnew file mode 100644index 00000000..1a480ae3--- /dev/null+++ b/src/components/remove-object/remove-object-tool.tsx@@ -0,0 +1,574 @@+"use client";++import { Brush, Cloud, Download, Eraser as EraserIcon, Eye, Loader2, RotateCcw, Sparkles, Type, Undo2 } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { StepList, type StepRow } from "@/components/av/step-list";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { useGeneration, useGenerationList } from "@/components/av/use-generation";+import { useSubmitGuard } from "@/components/shorts/hooks";+import { ClipBar, ClipDrop, costText, Field, Segmented } from "@/components/shorts/ui";+import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-source-clip";+import { Feed } from "@/components/studio/feed";+import { radioKeys, radioTab } from "@/components/studio/radio-keys";+import { SketchEditor, type Stroke } from "@/components/studio/sketch-editor";+import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";+import { useEngine, useGenerations } from "@/lib/api";+import {+ CLICK_OPEN_PROBLEM,+ chooseEraser,+ erasersFor,+ REMOVE,+ REMOVE_EXAMPLES,+ REMOVE_MODES,+ type Eraser,+ type RemoveMode,+} from "@/lib/catalog/remove-object";+import { chainState } from "@/lib/catalog/shorts";+import type { Generation, PixelPoint } from "@/lib/catalog/types";+import { downloadHref, downloadName } from "@/lib/library";+import { cn } from "@/lib/utils";+import { FrameStage, frameFromBlob, type Frame } from "./frame-stage";+import { useRemovalActions, useRemovalEstimate, type RemovalBody } from "./hooks";+import { VideoCompare } from "./video-compare";++const LIMITS = `MP4, MOV or WebM · up to ${REMOVE.maxSeconds} s at a time · ${REMOVE.maxBytes / 1024 / 1024} MB`;++interface Paint {+ mask: string;+ overlay: string;+ strokes: Stroke[];+}++interface Run {+ final: string;+ ids: string[];+ /** The original the result is compared with: the clip and where the selection starts. */+ before: string;+ start: number;+}++/**+ * Video tools → Remove object: say what goes by typing it, clicking it on the first frame or painting over it;+ * see the price (or "Free" on the open engine) and an optional mask preview before anything runs; get the+ * result with a before / after wipe. Long clips are cut into pieces or windows, erased and joined with their+ * own sound (src/lib/catalog/remove-object.ts).+ */+export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {+ const [engine, setEngine, engineMode] = useEngine();+ const source = useSourceClip(REMOVE.maxBytes);+ const clip = source.clip;+ const trimmer = useRef<VideoTrimmerHandle>(null);+ const [range, setRange] = useState<TrimRange | null>(null);+ const [mode, setMode] = useState<RemoveMode>("type");+ const [prompt, setPrompt] = useState("");+ const [effects, setEffects] = useState(false);+ const [picked, setPicked] = useState<Record<string, string>>({});+ const [points, setPoints] = useState<PixelPoint[]>([]);+ const [pointLabel, setPointLabel] = useState<"positive" | "negative">("positive");+ const [paint, setPaint] = useState<Paint | null>(null);+ const [painting, setPainting] = useState(false);+ const [frame, setFrame] = useState<Frame | null>(null);+ const [frameError, setFrameError] = useState(false);+ const [previewId, setPreviewId] = useState<string | null>(null);+ const [run, setRun] = useState<Run | null>(null);+ const actions = useRemovalActions();+ const runGuard = useSubmitGuard();+ const previewGuard = useSubmitGuard();+ const history = useGenerations({ features: [REMOVE.feature], limit: 24 });++ const duration = clipDuration(clip);+ const size = clipSize(clip);+ const choiceKey = `${engine}:${mode}`;+ const choice = chooseEraser({ engine, mode, effects: mode === "type" && effects, modelId: picked[choiceKey] });+ const eraser: Eraser | null = "eraser" in choice ? choice.eraser : null;+ const options = erasersFor(engine, mode).filter((e) => !e.effects);+ const everyone = !!eraser?.everyone;++ // The selection's first frame, grabbed by the browser: what points and paint are made on.+ const startAt = range ? Math.round(range.startTime * 100) / 100 : null;+ const previewSrc = clip?.preview;+ useEffect(() => {+ if (!previewSrc || startAt === null) return;+ let alive = true;+ const t = setTimeout(async () => {+ const blob = await trimmer.current?.grabFrame(startAt, 1280);+ if (!alive) return;+ if (!blob) return setFrameError(true);+ const f = await frameFromBlob(blob).catch(() => null);+ if (!alive || !f) return;+ setFrameError(false);+ setFrame((old) => {+ if (old) URL.revokeObjectURL(old.url);+ return f;+ });+ }, 350);+ return () => {+ alive = false;+ clearTimeout(t);+ };+ }, [previewSrc, startAt]);+ // A new first frame: points and paint made on the old one no longer line up.+ const [frameAt, setFrameAt] = useState<string | null>(null);+ const frameKey = `${previewSrc}|${startAt}`;+ if (frameKey !== frameAt) {+ setFrameAt(frameKey);+ if (points.length || paint) {+ setPoints([]);+ setPaint(null);+ }+ setPreviewId(null);+ }++ const reset = () => {+ source.clear();+ setRange(null);+ setFrame(null);+ setFrameError(false);+ setPoints([]);+ setPaint(null);+ setPreviewId(null);+ };++ const ready = !!clip?.url && !clip.uploading && !clip.error && !!duration && !!range;+ const marked =+ mode === "type" ? everyone || !!prompt.trim() : mode === "click" ? points.some((p) => p.label !== "negative") : !!paint;+ const body: RemovalBody | null =+ ready && eraser && marked+ ? {+ engine,+ mode,+ modelId: eraser.id,+ effects: mode === "type" && effects,+ ...(mode === "type" && !everyone ? { prompt: prompt.trim() } : {}),+ ...(mode === "click" ? { points } : {}),+ ...(mode === "paint" && paint ? { mask: paint.mask } : {}),+ ...(mode !== "type" && frame ? { frame: { width: frame.width, height: frame.height } } : {}),+ source: { url: clip.url!, name: clip.name, duration, fps: clip.info?.fps, width: size.width, height: size.height, hasAudio: clip.info?.hasAudio },+ range: { start: range.startTime, end: range.endTime },+ }+ : null;+ const estimate = useRemovalEstimate(body);+ const est = estimate.data && !estimate.isError ? estimate.data : undefined;++ const blocker = !clip+ ? "Add a clip"+ : clip.error+ ? clip.error+ : clip.uploading+ ? clip.progress < 1+ ? `Uploading… ${Math.round(clip.progress * 100)}%`+ : "Reading the clip…"+ : !range || !duration+ ? "Reading the clip…"+ : !eraser+ ? "problem" in choice+ ? choice.problem+ : "Pick how to point at it"+ : !marked+ ? mode === "type"+ ? "Say what to remove"+ : mode === "click"+ ? "Click what to remove on the first frame"+ : "Paint over what to remove"+ : estimate.isError+ ? (estimate.error as Error).message+ : null;++ const start = () => {+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "remove-blocker" });+ void runGuard(JSON.stringify(body), (requestId) => actions.run.mutateAsync({ ...body, requestId }))+ .then((r) => {+ if (!r) return;+ setRun({ final: r.final.id, ids: r.items.map((g) => g.id), before: clip!.preview, start: range!.startTime });+ toast("Removing it", { description: "Follow it below — it lands in your Library too." });+ })+ .catch((e: Error) => toast.error(e.message));+ };++ const canPreview = !!body && est?.previewUsd != null;+ const makePreview = () => {+ if (!body || !canPreview) return;+ void previewGuard(JSON.stringify(body), (requestId) => actions.preview.mutateAsync({ ...body, requestId }))+ .then((g) => g && setPreviewId(g.id))+ .catch((e: Error) => toast.error(e.message));+ };+ const preview = useGeneration(previewId).data;++ return (+ <ToolShell title="Video tools" tabs={tabs} wide>+ {!clip && (+ <ToolHero+ title="Remove anything from a video"+ subtitle="Type what goes, click it, or paint over it — the gap is filled frame by frame and the sound stays. Priced before it runs; free on your own ComfyUI."+ />+ )}+ <div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>+ {!clip ? (+ <ClipDrop+ accept={REMOVE.accept}+ limits={LIMITS}+ onFile={(f) => {+ const err = source.pick(f);+ if (err) toast.error(err);+ else setRange(null);+ }}+ onLibrary={(url, name) => {+ source.adopt(url, name);+ setRange(null);+ }}+ />+ ) : (+ <div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">+ <div className="min-w-0 space-y-4">+ <Panel>+ <div className="space-y-3">+ <ClipBar clip={clip} onRemove={reset} />+ <VideoTrimmer+ ref={trimmer}+ src={clip.preview}+ value={range}+ onChange={setRange}+ min={REMOVE.minSeconds}+ max={REMOVE.maxSeconds}+ duration={clip.info?.duration}+ label="Part of the clip to clean up"+ hint={duration && duration > REMOVE.maxSeconds ? `Pick up to ${REMOVE.maxSeconds} s — only that part comes out` : "The whole clip, or just the part you need"}+ onMeta={source.setBrowserMeta}+ />+ </div>+ </Panel>+ <Panel+ title="First frame"+ aside={+ mode === "click" && engine === "cloud" ? (+ <Segmented+ label="What a click marks"+ value={pointLabel}+ onChange={setPointLabel}+ className="w-auto"+ options={[+ { value: "positive", label: "Remove" },+ { value: "negative", label: "Keep" },+ ]}+ />+ ) : null+ }+ >+ {frame ? (+ <FrameStage+ frame={frame}+ points={mode === "click" ? points : []}+ onPoints={mode === "click" && engine === "cloud" ? setPoints : undefined}+ pointLabel={pointLabel}+ overlay={mode === "paint" ? paint?.overlay : undefined}+ clickable={mode === "click" && engine === "cloud"}+ maxPoints={REMOVE.maxPoints}+ />+ ) : (+ <div className="grid aspect-video place-items-center rounded-xl bg-muted text-[13px] text-muted-foreground">+ {frameError ? (+ <p className="max-w-xs px-4 text-center">This browser can't show the clip's frames (an H.265 or ProRes file?). Type it works without them.</p>+ ) : (+ <Loader2 className="size-5 animate-spin" aria-label="Reading the first frame" />+ )}+ </div>+ )}+ <p className="mt-2 text-[12px] text-muted-foreground">{frameHint(mode, engine, points.length, !!paint)}</p>+ {preview && <MaskPreview g={preview} engine={engine} />}+ </Panel>+ </div>++ <Panel className="space-y-4 lg:sticky lg:top-[112px]">+ <Field label="How do you point at it?">+ <Segmented+ label="How do you point at it?"+ value={mode}+ onChange={(m) => {+ setMode(m);+ setPreviewId(null);+ }}+ options={REMOVE_MODES.map((m) => ({ value: m.id, label: m.label }))}+ />+ </Field>++ {mode === "type" && (+ <Field label="What to remove" htmlFor="remove-what" hint={everyone ? "Not needed: every person goes" : undefined}>+ <Textarea+ id="remove-what"+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ disabled={everyone}+ maxLength={2500}+ rows={3}+ placeholder="e.g. “the coffee cup in her hand”"+ className="resize-none"+ />+ <div className="flex flex-wrap gap-1.5">+ {REMOVE_EXAMPLES.map((x) => (+ <button+ key={x.label}+ type="button"+ disabled={everyone}+ onClick={() => setPrompt(x.prompt)}+ className="inline-flex h-7 items-center rounded-full bg-muted px-2.5 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:opacity-50"+ >+ {x.label}+ </button>+ ))}+ </div>+ </Field>+ )}++ {mode === "click" && engine === "open" && (+ <div className="space-y-2 rounded-xl bg-muted/60 p-3 text-[13px]" role="status">+ <p>{CLICK_OPEN_PROBLEM}.</p>+ <div className="flex flex-wrap gap-1.5">+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => setMode("type")}>+ <Type className="size-3.5" /> Type it+ </Button>+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => setMode("paint")}>+ <Brush className="size-3.5" /> Paint it+ </Button>+ {engineMode === "both" && (+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => setEngine("cloud")}>+ <Cloud className="size-3.5" /> Use the cloud+ </Button>+ )}+ </div>+ </div>+ )}++ {mode === "click" && engine === "cloud" && (+ <div className="flex flex-wrap items-center gap-2 text-[13px]">+ <p className="min-w-0 flex-1 text-muted-foreground">+ {points.length ? `${points.length} point${points.length === 1 ? "" : "s"}` : "No points yet"} — click the object; switch to Keep for things next to it that stay.+ </p>+ <Button size="sm" variant="ghost" className="rounded-full" disabled={!points.length} onClick={() => setPoints(points.slice(0, -1))}>+ <Undo2 className="size-3.5" /> Undo+ </Button>+ </div>+ )}++ {mode === "paint" && (+ <div className="flex flex-wrap items-center gap-2">+ <Button className="rounded-full" variant={paint ? "outline" : "default"} disabled={!frame} onClick={() => setPainting(true)}>+ <Brush className="size-4" /> {paint ? "Touch up the paint" : "Paint over it"}+ </Button>+ {paint && (+ <Button variant="ghost" size="sm" className="rounded-full" onClick={() => setPaint(null)}>+ <RotateCcw className="size-3.5" /> Clear+ </Button>+ )}+ <p className="w-full text-[12px] text-muted-foreground">+ {engine === "open" ? "SAM 3.1 follows what you paint through the clip." : "SAM 3.1 follows what you paint through the clip, then Bria erases it."} Painting needs a mouse, pen or finger — Type it works from the keyboard.+ </p>+ </div>+ )}++ {mode === "type" && (+ <label className="flex items-center gap-3 rounded-xl border px-3 py-2.5">+ <span className="min-w-0 flex-1">+ <span className="block text-[13px] font-medium">Shadows and reflections too</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">VOID also removes what the object causes: its shadow, reflections, things it moves</span>+ </span>+ <Switch checked={effects} onCheckedChange={setEffects} disabled={everyone} aria-label="Shadows and reflections too" />+ </label>+ )}++ {eraser && options.length > 1 && !(mode === "type" && effects) && (+ <Field label="Eraser">+ <EraserList options={options} value={eraser.id} onChange={(id) => setPicked((p) => ({ ...p, [choiceKey]: id }))} />+ </Field>+ )}+ {eraser && (options.length <= 1 || (mode === "type" && effects)) && (+ <p className="text-[12px] text-muted-foreground">+ <span className="font-medium text-foreground">{eraser.label}</span> · {eraser.note}+ </p>+ )}++ <div className="space-y-3 border-t pt-3">+ {body && est?.previewUsd != null && (+ <div className="flex items-center gap-2">+ <Button variant="outline" size="sm" className="rounded-full" onClick={makePreview} disabled={actions.preview.isPending || (preview && (preview.status === "queued" || preview.status === "running"))}>+ {actions.preview.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Eye className="size-3.5" />} Preview the mask+ </Button>+ <span className="text-[12px] text-muted-foreground">+ first {REMOVE.previewSeconds} s · {est.demo ? "demo" : engine === "open" ? "free" : costText({ costUsd: est.previewUsd, demo: false }, "cloud")}+ </span>+ </div>+ )}+ <div className="flex items-center gap-2">+ <div className="min-w-0 flex-1" aria-live="polite">+ {blocker ? (+ <p className="text-[13px] text-muted-foreground">{blocker}</p>+ ) : (+ <>+ <p className="flex items-center gap-1.5 text-[15px] font-semibold tabular-nums">+ {costText(est, engine)}+ {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" aria-label="Updating the price" />}+ </p>+ {est && (+ <p className="truncate text-[12px] text-muted-foreground">+ {est.modelName} · {est.seconds} s{est.pieces > 1 ? ` in ${est.pieces} ${engine === "open" ? "windows" : "pieces"}` : ""}+ </p>+ )}+ </>+ )}+ </div>+ <Button className="rounded-full" onClick={start} disabled={!!blocker || actions.run.isPending}>+ {actions.run.isPending ? <Loader2 className="size-4 animate-spin" /> : <EraserIcon className="size-4" />} Remove it+ </Button>+ </div>+ {est && est.notes.length > 0 && !blocker && (+ <ul className="space-y-1 text-[12px] leading-snug text-muted-foreground">+ {est.notes.map((n) => (+ <li key={n} className="flex gap-1.5">+ <Sparkles className="mt-0.5 size-3 shrink-0 text-brand-text" />+ <span>{n}.</span>+ </li>+ ))}+ </ul>+ )}+ </div>+ </Panel>+ </div>+ )}+ </div>++ {run && <RunPanel run={run} onAgain={start} />}++ {(history.data?.length ?? 0) > 0 && (+ <section className="mt-10" aria-labelledby="removals">+ <h3 id="removals" className="mb-3 font-heading text-[22px]">+ Your removals+ </h3>+ <Feed items={history.data!} />+ </section>+ )}++ {frame && (+ <SketchEditor+ open={painting}+ onOpenChange={setPainting}+ image={frame.url}+ mode="mask"+ initialStrokes={paint?.strokes}+ onDone={(r) => r.mask && setPaint({ mask: r.mask, overlay: r.overlay, strokes: r.strokes })}+ />+ )}+ </ToolShell>+ );+}++function frameHint(mode: RemoveMode, engine: "cloud" | "open", points: number, painted: boolean): string {+ if (mode === "type") return "Name it in the panel — the first frame is here to check what you mean.";+ if (mode === "click") return engine === "open" ? "Clicking works on the cloud engine." : points ? "Add more points on the same object, or mark what stays with Keep." : "Click the object you want gone. Keyboard: arrows move the crosshair, Enter adds a point.";+ return painted ? "Red is what goes. Touch up the paint, or clear it to start over." : "Paint over what should go — the paint only needs to cover it on this frame.";+}++/** The erasers for this engine and way of pointing, one line each (what it's good at, its limits). */+function EraserList({ options, value, onChange }: { options: Eraser[]; value: string; onChange: (id: string) => void }) {+ return (+ <div role="radiogroup" aria-label="Eraser" onKeyDown={radioKeys} className="space-y-1.5">+ {options.map((e) => (+ <button+ key={e.id}+ type="button"+ role="radio"+ aria-checked={value === e.id}+ tabIndex={radioTab(value === e.id)}+ onClick={() => onChange(e.id)}+ className={cn(+ "flex w-full min-w-0 items-start gap-2.5 rounded-xl border px-3 py-2 text-left transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",+ value === e.id && "border-primary bg-brand-faint hover:bg-brand-faint-hover",+ )}+ >+ <span className={cn("mt-1 size-3 shrink-0 rounded-full border-2", value === e.id ? "border-primary bg-primary" : "border-border-strong")} />+ <span className="min-w-0">+ <span className="block text-[13px] font-medium">{e.label}</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{e.note}</span>+ </span>+ </button>+ ))}+ </div>+ );+}++/** The mask preview: SAM 3.1's mask video (cloud: white = what goes) or the SAM 3 cut-out of it (open). */+function MaskPreview({ g, engine }: { g: Generation; engine: "cloud" | "open" }) {+ const out = g.outputs.find((o) => o.kind === "video");+ return (+ <div className="mt-3 rounded-xl border p-2.5">+ <p className="mb-2 text-[12px] font-medium">+ Mask preview <span className="font-normal text-muted-foreground">· {engine === "open" ? "what goes, cut out" : "white is what goes"}</span>+ </p>+ {g.status === "succeeded" && out ? (+ <video+ src={out.url}+ autoPlay+ loop+ muted+ playsInline+ className={cn("max-h-48 w-full rounded-lg object-contain", engine === "open" ? "bg-[repeating-conic-gradient(var(--muted)_0_25%,transparent_0_50%)] bg-[length:16px_16px]" : "bg-media")}+ />+ ) : g.status === "failed" || g.status === "canceled" ? (+ <p className="text-[12px] text-destructive">{g.error ?? "The preview didn't finish"}</p>+ ) : (+ <p className="flex items-center gap-2 text-[12px] text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" /> {g.message ?? "Making the preview…"}+ </p>+ )}+ </div>+ );+}++/** What a removal's steps are doing, then the result with a before / after wipe. */+function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {+ const list = useGenerationList(run.ids).data;+ const byId = useMemo(() => new Map((list ?? []).map((g) => [g.id, g])), [list]);+ const final = byId.get(run.final);+ const rows: StepRow[] = run.ids.map((id) => {+ const g = byId.get(id);+ return { key: id, label: g?.request.step?.label ?? "A step", g };+ });+ const state = chainState(rows.map((r) => ({ g: r.g, label: r.label })).sort((a, b) => (a.g?.id === run.final ? 1 : b.g?.id === run.final ? -1 : 0)));+ const out = final?.status === "succeeded" ? final.outputs.find((o) => o.kind === "video") : undefined;+ return (+ <section className="mt-6" aria-labelledby="run-title">+ <Panel+ title={<span id="run-title">{final?.request.title ?? "Your removal"}</span>}+ aside={+ out && final ? (+ <Button asChild size="sm" variant="outline" className="rounded-full">+ <a href={downloadHref(out.url, downloadName(final, out, 0))}>+ <Download className="size-3.5" /> Download+ </a>+ </Button>+ ) : state.status === "failed" ? (+ <Button size="sm" variant="outline" className="rounded-full" onClick={onAgain}>+ <RotateCcw className="size-3.5" /> Try again+ </Button>+ ) : null+ }+ >+ {out ? (+ <VideoCompare before={run.before} after={out.url} start={run.start} />+ ) : (+ <div className="space-y-3">+ <div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">+ <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />+ </div>+ <p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">+ {state.status === "failed" ? `${state.label}: ${state.error}` : state.label}+ </p>+ {rows.length > 1 && <StepList steps={rows} />}+ </div>+ )}+ </Panel>+ </section>+ );+}diff --git a/src/components/remove-object/video-compare.tsx b/src/components/remove-object/video-compare.tsxnew file mode 100644index 00000000..ed876b73--- /dev/null+++ b/src/components/remove-object/video-compare.tsx@@ -0,0 +1,104 @@+"use client";++import { MoveHorizontal, Pause, Play } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { Button } from "@/components/ui/button";++/**+ * Before / after for a video: the result plays underneath and the original on top, cut at the handle; drag it+ * (or use ← → on the slider) to wipe between them. The original follows the result's clock from `start` (the+ * selection's start in the original clip), so both show the same moment.+ */+export function VideoCompare({ before, after, start = 0, label = "Compare the original and the result" }: { before: string; after: string; start?: number; label?: string }) {+ const box = useRef<HTMLDivElement>(null);+ const a = useRef<HTMLVideoElement>(null);+ const b = useRef<HTMLVideoElement>(null);+ const [pos, setPos] = useState(50);+ const [playing, setPlaying] = useState(false);+ const move = (clientX: number) => {+ const r = box.current?.getBoundingClientRect();+ if (r) setPos(Math.min(100, Math.max(0, ((clientX - r.left) / r.width) * 100)));+ };+ // Keep the original on the result's clock.+ useEffect(() => {+ const va = a.current;+ const vb = b.current;+ if (!va || !vb) return;+ const sync = () => {+ const want = start + va.currentTime;+ if (Math.abs(vb.currentTime - want) > 0.12) vb.currentTime = want;+ };+ const onPlay = () => {+ sync();+ void vb.play().catch(() => {});+ setPlaying(true);+ };+ const onPause = () => {+ vb.pause();+ setPlaying(false);+ };+ va.addEventListener("timeupdate", sync);+ va.addEventListener("seeked", sync);+ va.addEventListener("play", onPlay);+ va.addEventListener("pause", onPause);+ return () => {+ va.removeEventListener("timeupdate", sync);+ va.removeEventListener("seeked", sync);+ va.removeEventListener("play", onPlay);+ va.removeEventListener("pause", onPause);+ };+ }, [start, before, after]);+ const toggle = () => {+ const va = a.current;+ if (!va) return;+ if (va.paused) void va.play().catch(() => {});+ else va.pause();+ };+ return (+ <div className="space-y-2">+ <div+ ref={box}+ className="relative grid touch-none place-items-center overflow-hidden rounded-xl bg-media select-none"+ onPointerDown={(e) => {+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ move(e.clientX);+ }}+ onPointerMove={(e) => e.buttons && move(e.clientX)}+ >+ <video ref={a} src={after} playsInline loop className="block max-h-[56vh] w-full object-contain" onLoadedMetadata={() => b.current && (b.current.currentTime = start)} />+ <video+ ref={b}+ src={before}+ playsInline+ muted+ preload="auto"+ aria-hidden+ className="absolute inset-0 size-full object-contain"+ style={{ clipPath: `inset(0 ${100 - pos}% 0 0)` }}+ onLoadedMetadata={(e) => (e.currentTarget.currentTime = start)}+ />+ <div className="pointer-events-none absolute inset-y-0 w-0.5 bg-white shadow-[0_0_8px_rgba(0,0,0,.5)]" style={{ left: `${pos}%` }}>+ <span className="absolute top-1/2 left-1/2 grid size-9 -translate-1/2 place-items-center rounded-full bg-white text-black shadow-normal">+ <MoveHorizontal className="size-4" />+ </span>+ </div>+ <span className="pointer-events-none absolute top-3 left-3 rounded-full bg-black/50 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">Before</span>+ <span className="pointer-events-none absolute top-3 right-3 rounded-full bg-black/50 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">After</span>+ </div>+ <div className="flex items-center gap-3">+ <Button variant="outline" size="sm" className="rounded-full" onClick={toggle}>+ {playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />} {playing ? "Pause" : "Play both"}+ </Button>+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(pos)}+ onChange={(e) => setPos(Number(e.target.value))}+ aria-label={label}+ className="h-1.5 min-w-0 flex-1 cursor-pointer accent-primary"+ />+ </div>+ </div>+ );+}diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex a2e72a12..5dcf87a8 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -22,6 +22,7 @@ import { HUB_MODES, modeHref, type HubKind } from "@/lib/hubs";import { CaptionsStudio } from "@/components/captions/captions-studio";import { DubStudio } from "@/components/dub/dub-studio";import { TrimTool } from "@/components/av/trim-tool";+import { RemoveObjectTool } from "@/components/remove-object/remove-object-tool";import { ModeStudio, ModeTabs } from "./mode-studio";import type { StudioConfig } from "./studio-context";@@ -45,10 +46,14 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {},};-/** Modes that are their own tool rather than a composer studio (Translate & dub, Captions, Trim). */+/** Modes that are their own tool rather than a composer studio (Translate & dub, Remove object, Captions, Trim). */const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {audio: { translate: ({ tabs }) => <DubStudio tabs={tabs} /> },- "video-tools": { captions: ({ tabs }) => <CaptionsStudio tabs={tabs} />, trim: ({ tabs }) => <TrimTool tabs={tabs} /> },+ "video-tools": {+ "remove-object": ({ tabs }) => <RemoveObjectTool tabs={tabs} />,+ captions: ({ tabs }) => <CaptionsStudio tabs={tabs} />,+ trim: ({ tabs }) => <TrimTool tabs={tabs} />,+ },};const HUB_TITLE: Record<HubKind, string> = { upscale: "Upscale", audio: "Audio", "video-tools": "Video tools" };diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsindex d3da001a..1cca4ee1 100644--- a/src/lib/hubs.ts+++ b/src/lib/hubs.ts@@ -21,6 +21,7 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {],"video-tools": [{ id: "matte", label: "Remove background" },+ { id: "remove-object", label: "Remove object" },{ id: "relight", label: "Relight" },{ id: "depth", label: "Depth map" },{ id: "captions", label: "Captions" },