Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Character Swap Studio: continuations that line up, smaller masters, assembly with older takes

Claudeb9f566dabe85
diff --git a/src/app/api/swap-studio/projects/[id]/prepare/route.ts b/src/app/api/swap-studio/projects/[id]/prepare/route.ts
index 6fcf02c2..edc21ba2 100644
--- a/src/app/api/swap-studio/projects/[id]/prepare/route.ts
+++ b/src/app/api/swap-studio/projects/[id]/prepare/route.ts
@@ -4,7 +4,7 @@ import { prepareClip } from "@/server/swap-studio";
const Prepare = z.object({ clipId: z.string().min(1).max(80) });
-/** Your GPU: make the clip's 24 fps copy (again). */
+/** Your GPU: make the clip's 24 fps copy (again). The cloud: its browser copy, when the page can't play the clip. */
export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/prepare">) {
return handle(async () => {
const { id } = await ctx.params;
diff --git a/src/app/api/swap-studio/projects/[id]/route.ts b/src/app/api/swap-studio/projects/[id]/route.ts
index f099cdf7..c3c39f5f 100644
--- a/src/app/api/swap-studio/projects/[id]/route.ts
+++ b/src/app/api/swap-studio/projects/[id]/route.ts
@@ -12,7 +12,7 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/swap-studio/pro
export async function PATCH(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]">) {
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(editProject(id, await body(request, EditSchema, "That change isn't valid")));
+ return Response.json(await editProject(id, await body(request, EditSchema, "That change isn't valid")));
});
}
diff --git a/src/components/genjutsu/character-panel.tsx b/src/components/genjutsu/character-panel.tsx
index 9281f9b0..d45e4f8a 100644
--- a/src/components/genjutsu/character-panel.tsx
+++ b/src/components/genjutsu/character-panel.tsx
@@ -291,8 +291,26 @@ function FrameSelect({ id, label, value, choices, onChange }: { id: string; labe
);
}
-/** The limits, the cut warning, the GPU it was tested on (open) and the licence, as information under the settings. */
-export function CharacterFacts({ engine, maker, cut }: { engine: Engine; maker: Maker | null; cut: string | null }) {
+/**
+ * The limits, the cut warning, the GPU it was tested on (open) and the licence, as information under the settings; and
+ * the way to Character Swap Studio for the whole clip (`onOpenStudio` takes the clip and character along).
+ */
+export function CharacterFacts({
+ engine,
+ maker,
+ cut,
+ onOpenStudio,
+ opening,
+ waiting,
+}: {
+ engine: Engine;
+ maker: Maker | null;
+ cut: string | null;
+ onOpenStudio?: () => void;
+ opening?: boolean;
+ /** Why the studio can't be opened with the clip yet (it is still uploading). */
+ waiting?: string | null;
+}) {
return (
<div className="space-y-2 text-[12px] leading-snug text-muted-foreground">
{cut && (
@@ -320,10 +338,17 @@ export function CharacterFacts({ engine, maker, cut }: { engine: Engine; maker:
<span>Licences are information: each model&apos;s is under its name above, and your admin decides what runs (Settings → Models &amp; licences).</span>
</p>
{/* Whole clips, shot by shot, with masks, anchors, segments and takes: the studio built on the same H3 recipe. */}
- <Link href="/character-swap" className="inline-flex items-center gap-1 font-medium text-brand-text hover:underline">
- <Drama className="size-3.5" /> Open in Character Swap Studio
- <span className="font-normal text-muted-foreground">— whole clips, shot by shot</span>
- </Link>
+ {onOpenStudio ? (
+ <button type="button" onClick={onOpenStudio} disabled={opening || !!waiting} className="inline-flex items-center gap-1 rounded-sm text-left font-medium text-brand-text outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60">
+ {opening ? <Loader2 className="size-3.5 animate-spin" /> : <Drama className="size-3.5" />} Open in Character Swap Studio
+ <span className="font-normal text-muted-foreground">— {waiting ?? "this whole clip and character, shot by shot"}</span>
+ </button>
+ ) : (
+ <Link href="/character-swap" className="inline-flex items-center gap-1 font-medium text-brand-text hover:underline">
+ <Drama className="size-3.5" /> Open in Character Swap Studio
+ <span className="font-normal text-muted-foreground">— whole clips, shot by shot</span>
+ </Link>
+ )}
</div>
);
}
diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsx
index 31210062..c1aa2e2b 100644
--- a/src/components/genjutsu/genjutsu-studio.tsx
+++ b/src/components/genjutsu/genjutsu-studio.tsx
@@ -2,7 +2,7 @@
import { Brush, Download, Info, Loader2, RotateCcw, Sparkles, Undo2, Wand2 } from "lucide-react";
import Link from "next/link";
-import { useSearchParams } from "next/navigation";
+import { useRouter, useSearchParams } from "next/navigation";
import { nanoid } from "nanoid";
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
@@ -23,6 +23,7 @@ import { fileToList, MediaSlot, type SlotValue } from "@/components/studio/media
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 { openInStudio } from "@/components/swap-studio/hooks";
import { useEngine, useGenerations, useModelAccess } from "@/lib/api";
import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterOptions, type CharacterQuality } from "@/lib/catalog/character-swap";
import {
@@ -182,6 +183,25 @@ export function GenjutsuStudio() {
// "Describe my character" (the engine's text model) and "Use the clip's words" (one transcription of the clip; any
// part takes its own lines from it, so it is kept per clip).
+ const router = useRouter();
+ const [opening, setOpening] = useState(false);
+ // "Open in Character Swap Studio": the whole clip and the character go to a new studio project on this engine.
+ const openStudio = async () => {
+ setOpening(true);
+ try {
+ const r = await openInStudio({
+ engine,
+ clip: clip && !clip.uploading && clip.url ? { url: clip.url, name: clip.name, ...(clip.size ? { size: clip.size } : {}), duration: clip.info?.duration ?? clip.browserDuration, width: clip.info?.width ?? clip.browserWidth, height: clip.info?.height ?? clip.browserHeight } : null,
+ image: refs.find((x) => !x.uploading)?.ref ?? null,
+ description: character.description,
+ });
+ if (r.problem) toast.error(r.problem, { description: "The project is open: add the clip there." });
+ router.push(`/character-swap/${encodeURIComponent(r.id)}`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ setOpening(false);
+ }
+ };
const describeMutation = useDescribeCharacter();
const transcribeMutation = useTranscribeClip();
const [clipWords, setClipWords] = useState<{ url: string; g: Generation } | null>(null);
@@ -736,7 +756,14 @@ export function GenjutsuStudio() {
))}
</ul>
)}
- {isCharacter && <CharacterFacts engine={engine} maker={maker} cut={cut} />}
+ {isCharacter && <CharacterFacts
+ engine={engine}
+ maker={maker}
+ cut={cut}
+ onOpenStudio={() => void openStudio()}
+ opening={opening}
+ waiting={clip?.uploading || refs.some((x) => x.uploading) ? "waiting for the upload" : null}
+ />}
</div>
</Panel>
</div>
diff --git a/src/components/swap-studio/hooks.ts b/src/components/swap-studio/hooks.ts
index fc160b2b..1858ea9a 100644
--- a/src/components/swap-studio/hooks.ts
+++ b/src/components/swap-studio/hooks.ts
@@ -1,7 +1,7 @@
"use client";
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import type { QueueMode, StudioEstimate, SwapProject, SwapProjectCard, SwapProjectView } from "@/lib/catalog/swap-studio";
+import { studioHandOff, type HandOffInput, type QueueMode, type StudioEstimate, type SwapProject, type SwapProjectCard, type SwapProjectView } from "@/lib/catalog/swap-studio";
import type { SwapEdit } from "@/lib/catalog/swap-studio-edit";
import type { Engine, PixelPoint } from "@/lib/catalog/types";
@@ -97,6 +97,8 @@ export interface ClipInput {
fps?: number;
hasAudio?: boolean;
bytes?: number;
+ /** Whether this browser could play it (the cloud makes a copy the page can play when it couldn't). */
+ playable?: boolean;
}
/** What "Queue …" answers: the project, the takes it made and any notes (a LoRA switched off). */
@@ -124,5 +126,21 @@ export const useStopJob = (id: string) =>
useAction<{ kind: "mask" | "anchor" | "assembly" | "normalize" | "transcribe"; clipId: string; shotId?: string; segmentId?: string; jobId?: string }>(id, "stop");
export const useAssemble = (id: string) => useAction<{ clipId: string }>(id, "assemble");
+/**
+ * Genjutsu's "Open in Character Swap Studio": a new project with the character, and the clip added (the clip's
+ * problem, if it can't be added, comes back to say on the way in). Answers the project's id.
+ */
+export async function openInStudio(input: HandOffInput): Promise<{ id: string; problem: string | null }> {
+ const h = studioHandOff(input);
+ const p = await send<SwapProject>("/api/swap-studio/projects", "POST", h.project);
+ if (!h.clip) return { id: p.id, problem: null };
+ try {
+ await send<SwapProject>(`${base(p.id)}/clips`, "POST", h.clip);
+ return { id: p.id, problem: null };
+ } catch (e) {
+ return { id: p.id, problem: (e as Error).message };
+ }
+}
+
/** The Export decisions download link. */
export const decisionsHref = (id: string) => `${base(id)}/decisions`;
diff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsx
index cbe7944e..9b306db0 100644
--- a/src/components/swap-studio/stage-review.tsx
+++ b/src/components/swap-studio/stage-review.tsx
@@ -187,6 +187,12 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)
{"problem" in found ? (
<Note tone="warn">{found.problem}</Note>
) : (
+ <>
+ {found.stale.length > 0 && (
+ <Note tone="warn">
+ {found.stale.join("; ")} {found.stale.length === 1 ? "uses a take" : "use takes"} made before later changes (settings, words, the character or the take before). The assembly uses {found.stale.length === 1 ? "it" : "them"} as {found.stale.length === 1 ? "it is" : "they are"} — queue {found.stale.length === 1 ? "it" : "them"} again in Segments for current ones.
+ </Note>
+ )}
<ol className="flex min-w-0 flex-wrap gap-1.5" aria-label="Pieces">
{found.pieces.map((p, i) => (
<li key={i} className={cn("rounded-full px-2.5 py-1 text-[11px] font-medium", p.kind === "take" ? "bg-brand-faint text-brand-text" : "bg-muted text-muted-foreground")}>
@@ -194,11 +200,12 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)
</li>
))}
</ol>
+ </>
)}
<p className="text-[12px] text-muted-foreground">
{project.engine === "open"
? "Each piece is fitted to the clip's size at 24 fps, joined packet by packet, and the clip's own sound goes back on."
- : "Each piece is cut to its frames, joined (fal keeps 24 fps, H3's rate), and the clip's own sound — or its silence — goes back on."}
+ : "The clip's pieces are cut to their frames, every piece is scaled to one frame size, they're joined at 24 fps (H3's rate), and the clip's own sound — or its silence — goes back on."}
</p>
<div className="flex flex-wrap items-center gap-2">
<Button
diff --git a/src/components/swap-studio/stage-segments.tsx b/src/components/swap-studio/stage-segments.tsx
index d90a9942..f29bb6f5 100644
--- a/src/components/swap-studio/stage-segments.tsx
+++ b/src/components/swap-studio/stage-segments.tsx
@@ -254,7 +254,8 @@ function SegmentCard(props: StageProps & { shot: SwapShot; seg: SwapSegment; ind
]}
onChange={(anchorMode) => set({ anchorMode })}
/>
- {seg.anchorMode === "shot" && !shot.approvedAnchor && <p className="text-[12px] text-muted-foreground">Approve a scene anchor (Scene anchors), or pick None.</p>}
+ {seg.anchorMode === "shot" && !shot.settings.useAnchor && <p className="text-[12px] text-muted-foreground">Scene anchors are off in Generation settings: this segment runs without one.</p>}
+ {seg.anchorMode === "shot" && shot.settings.useAnchor && !shot.approvedAnchor && <p className="text-[12px] text-muted-foreground">Approve a scene anchor (Scene anchors), or pick None.</p>}
</div>
</div>
diff --git a/src/components/swap-studio/stage-shots.tsx b/src/components/swap-studio/stage-shots.tsx
index f986e53a..1dbae6fc 100644
--- a/src/components/swap-studio/stage-shots.tsx
+++ b/src/components/swap-studio/stage-shots.tsx
@@ -24,6 +24,7 @@ export function ShotsStage({ project, clip, edit, src }: StageProps) {
const [modes, setModes] = useState<Record<string, ShotMode>>({});
const [frame, setFrame] = useState(0);
const [saving, setSaving] = useState(false);
+ const [unplayable, setUnplayable] = useState<string | null>(null);
const cuts = draft ?? clip.cuts;
const total = clip.frames;
const shots = useMemo(() => shotsFromCuts(clip, cuts, project.defaults), [clip, cuts, project.defaults]);
@@ -31,8 +32,9 @@ export function ShotsStage({ project, clip, edit, src }: StageProps) {
const changed = draft !== null || Object.keys(modes).length > 0;
const seek = (f: number) => {
- if (video.current) video.current.currentTime = at(f) + 0.5 / 24;
- setFrame(f);
+ const n = Math.min(total - 1, Math.max(0, Math.round(f)));
+ if (video.current) video.current.currentTime = at(n) + 0.5 / 24;
+ setFrame(n);
};
const detect = async () => {
const found = await scene.detect(src, total);
@@ -60,8 +62,17 @@ export function ShotsStage({ project, clip, edit, src }: StageProps) {
playsInline
preload="metadata"
onTimeUpdate={(e) => setFrame(Math.min(total - 1, Math.floor(e.currentTarget.currentTime * 24)))}
+ onLoadedData={() => setUnplayable(null)}
+ onError={() => setUnplayable(src)}
className="max-h-[46vh] w-full rounded-xl bg-media"
/>
+ {unplayable === src && (
+ <Note tone="warn" className="mt-2">
+ {project.engine === "cloud"
+ ? "Your browser can't play this clip, so Detect edits and frames to click on can't work here yet. Make a browser copy (above the stages), or add the clip as an MP4 (H.264). You can still type cuts by frame number."
+ : "Your browser can't play this clip yet — wait for the 24 fps copy (above the stages). You can still type cuts by frame number."}
+ </Note>
+ )}
{/* The timeline: shots by colour, cuts as lines, detected edits dashed, the playhead. */}
<div
className="relative mt-3 h-10 cursor-pointer overflow-hidden rounded-lg bg-muted"
@@ -83,9 +94,25 @@ export function ShotsStage({ project, clip, edit, src }: StageProps) {
<div className="absolute inset-y-0 w-0.5 bg-primary" style={{ left: pct(frame, total) }} />
</div>
<div className="mt-2 flex flex-wrap items-center gap-2">
- <span className="font-mono text-[12px] tabular-nums text-muted-foreground">
- Frame {frame} · {secondsLabel(frame)}
- </span>
+ {/* The playhead by number: the timeline above is for the mouse. */}
+ <label className="flex items-center gap-1.5 font-mono text-[12px] text-muted-foreground tabular-nums">
+ Frame
+ <input
+ key={frame}
+ type="number"
+ aria-label="Playhead frame"
+ defaultValue={frame}
+ min={0}
+ max={total - 1}
+ onBlur={(e) => {
+ const n = Number(e.currentTarget.value);
+ if (Number.isFinite(n) && Math.round(n) !== frame) seek(n);
+ }}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ className="h-7 w-20 rounded-md border bg-background px-2 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ · {secondsLabel(frame)}
+ </label>
<Button size="sm" variant="outline" className="h-8 rounded-full" onClick={() => setDraft(addCut(cuts, frame, total))} disabled={frame <= 0 || cuts.includes(frame)}>
<Plus className="size-3.5" /> Cut at the playhead
</Button>
@@ -132,7 +159,7 @@ export function ShotsStage({ project, clip, edit, src }: StageProps) {
const cutAt = i > 0 ? s.start : null;
return (
<li key={s.id} className="flex min-w-0 flex-wrap items-center gap-2 rounded-lg border px-2.5 py-2">
- <button type="button" onClick={() => seek(s.start)} className="min-w-0 text-left text-[13px] font-medium hover:underline">
+ <button type="button" onClick={() => seek(s.start)} className="min-w-0 rounded-sm text-left text-[13px] font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring">
Shot {i + 1}
<span className="ml-2 font-mono text-[12px] font-normal text-muted-foreground tabular-nums">
{s.start}–{s.end} · {secondsLabel(s.end - s.start)}
@@ -163,7 +190,12 @@ export function ShotsStage({ project, clip, edit, src }: StageProps) {
className="h-7 w-20 rounded-md border bg-background px-2 font-mono tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
</label>
- <button type="button" onClick={() => setDraft(removeCut(cuts, cutAt))} className="inline-flex items-center gap-1 rounded-full px-2 py-1 hover:bg-muted hover:text-foreground" aria-label={`Remove the cut at frame ${cutAt}`}>
+ <button
+ type="button"
+ onClick={() => setDraft(removeCut(cuts, cutAt))}
+ className="inline-flex items-center gap-1 rounded-full px-2 py-1 outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={`Remove the cut at frame ${cutAt}`}
+ >
<Trash2 className="size-3.5" /> Remove cut
</button>
</div>
diff --git a/src/components/swap-studio/stage-who.tsx b/src/components/swap-studio/stage-who.tsx
index c87a770e..0a7dd1a0 100644
--- a/src/components/swap-studio/stage-who.tsx
+++ b/src/components/swap-studio/stage-who.tsx
@@ -9,7 +9,7 @@ import { Panel } from "@/components/av/tool-shell";
import { Segmented, ToggleRow } from "@/components/faceless/controls";
import { FrameStage, type Frame } from "@/components/remove-object/frame-stage";
import { WHO_INDEX_LABEL, WHO_LABELS, type SwapWho } from "@/lib/catalog/character-swap";
-import { at, jobState, maskPieceAt, secondsLabel, SWAP_STUDIO, type MaskVersion } from "@/lib/catalog/swap-studio";
+import { approvedMask, at, jobState, maskPieceAt, secondsLabel, SWAP_STUDIO, type MaskVersion } from "@/lib/catalog/swap-studio";
import type { PixelPoint } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
import { useMakeMask, useStopJob } from "./hooks";
@@ -32,10 +32,14 @@ export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }:
if (!shot) return <Note>Pick a shot.</Note>;
const len = shot.end - shot.start;
const engine = project.engine;
+ const approvedMaskHere = !!approvedMask(shot, engine);
const who = shot.who;
const shown = frame && frame.shot === shot.id ? frame : null;
const finished = (m: MaskVersion) => m.pieces.every((p) => p.url);
- const baseVersion = shot.masks.find((m) => m.id === (base ?? shot.approvedMask)) ?? [...shot.masks].reverse().find(finished) ?? null;
+ // Corrections go into a version made on this engine (the other engine's can't be spliced into).
+ const here = (m: MaskVersion) => m.engine === engine && finished(m);
+ const named = shot.masks.find((m) => m.id === (base ?? shot.approvedMask));
+ const baseVersion = (named && here(named) ? named : null) ?? [...shot.masks].reverse().find(here) ?? null;
const show = async (f: number) => {
setLoading(true);
@@ -192,6 +196,7 @@ export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }:
const state = jobState(m.genId, m.stepIds, gens);
const piece = maskPieceAt(m, shown?.f ?? at24);
const approved = shot.approvedMask === m.id;
+ const elsewhere = m.engine !== engine;
return (
<li key={m.id} className={cn("min-w-0 space-y-2 rounded-xl border p-2.5", approved && "border-success")}>
<div className="flex min-w-0 flex-wrap items-center gap-2">
@@ -199,22 +204,35 @@ export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }:
<span className="min-w-0 truncate text-[12px] text-muted-foreground">
{m.kind === "track" ? `Track from frame ${m.frame + 1}` : `Frame ${m.frame + 1}`} · {m.points.length ? `${m.points.length} point${m.points.length === 1 ? "" : "s"}` : `“${m.who.words}”`}
{m.base ? ` · corrects v${shot.masks.findIndex((x) => x.id === m.base) + 1}` : ""}
+ {elsewhere ? ` · made ${m.engine === "open" ? "on your GPU" : "on the cloud"}` : ""}
</span>
<GenChip genId={m.genId} stepIds={m.stepIds} gens={gens} className="ml-auto" />
</div>
{piece?.url ? <video src={piece.url} muted loop playsInline controls preload="metadata" className="aspect-video w-full rounded-lg bg-media object-contain" /> : null}
<JobError genId={m.genId} stepIds={m.stepIds} gens={gens} />
<div className="flex flex-wrap gap-1.5">
- <Button
- size="sm"
- variant={approved ? "secondary" : "outline"}
- className="h-7 rounded-full px-2.5 text-[12px]"
- disabled={!finished(m) || approved}
- onClick={() => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { approvedMask: m.id } })}
- >
- <Check className="size-3.5" /> {approved ? "Approved" : "Approve"}
- </Button>
- {finished(m) && (
+ {approved ? (
+ <>
+ <span className="inline-flex h-7 items-center gap-1 rounded-full bg-success/12 px-2.5 text-[12px] font-medium text-success">
+ <Check className="size-3.5" /> Approved
+ </span>
+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { approvedMask: null } })}>
+ Unapprove
+ </Button>
+ </>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7 rounded-full px-2.5 text-[12px]"
+ disabled={!finished(m) || elsewhere}
+ title={elsewhere ? "Made on the other engine — track the shot again here" : undefined}
+ onClick={() => void edit({ type: "shot", clipId: clip.id, shotId: shot.id, patch: { approvedMask: m.id } })}
+ >
+ <Check className="size-3.5" /> Approve
+ </Button>
+ )}
+ {here(m) && (
<Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" aria-pressed={baseVersion?.id === m.id} onClick={() => setBase(m.id)}>
{baseVersion?.id === m.id ? "Updates go here" : "Update this one"}
</Button>
@@ -234,7 +252,7 @@ export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }:
})}
</ol>
)}
- {engine === "open" && shot.settings.useMask && !shot.approvedMask && <Note className="mt-3">No approved mask: each segment finds the person itself with SAM 3.1 from the pick and words above.</Note>}
+ {engine === "open" && shot.settings.useMask && !approvedMaskHere && <Note className="mt-3">No approved mask{shot.approvedMask ? " made on your GPU (the approved one is the cloud's)" : ""}: each segment finds the person itself with SAM 3.1 from the pick and words above.</Note>}
</Panel>
</div>
);
diff --git a/src/components/swap-studio/use-scene-cuts.ts b/src/components/swap-studio/use-scene-cuts.ts
index 703d00f9..95acf24d 100644
--- a/src/components/swap-studio/use-scene-cuts.ts
+++ b/src/components/swap-studio/use-scene-cuts.ts
@@ -2,12 +2,12 @@
import { useCallback, useRef, useState } from "react";
import { openVideo, releaseVideo, sampleFrames } from "@/components/av/frame-sampler";
-import { coarseTimes, coarseWindows, sceneScores, STUDIO_FPS, windowCuts, windowFrames } from "@/lib/av/scene-cuts";
+import { COARSE_WIDTH, coarseTimes, coarseWindows, fineWidth, sceneScores, STUDIO_FPS, windowChunks, windowCuts, windowFrames } from "@/lib/av/scene-cuts";
/**
* "Detect edits": FFmpeg's scene score at Akatz Labs' 0.32, read in the browser (src/lib/av/scene-cuts.ts). A coarse
- * pass a few frames a second finds where a cut can be; a fine pass reads every 24 fps frame there. The frames are
- * small (64 px wide) — the score is a mean over the picture, so it barely depends on the size.
+ * pass a few frames a second (small frames, a lower threshold) finds where a cut can be; a fine pass reads every
+ * 24 fps frame there at the clip's own size (up to 1280 px wide: a smaller picture scores cuts lower than FFmpeg).
*/
export function useSceneCuts() {
const [state, setState] = useState<{ busy: boolean; progress: number; error: string | null }>({ busy: false, progress: 0, error: null });
@@ -23,7 +23,7 @@ export function useSceneCuts() {
v = await openVideo(src);
const duration = v.duration;
const times = coarseTimes(duration);
- const coarse = await sampleFrames(v, times, { width: 64, signal: ctrl.signal, onProgress: (p) => setState((s) => ({ ...s, progress: p * 0.6 })) });
+ const coarse = await sampleFrames(v, times, { width: COARSE_WIDTH, signal: ctrl.signal, onProgress: (p) => setState((s) => ({ ...s, progress: p * 0.6 })) });
if (ctrl.signal.aborted) return null;
const windows = coarseWindows(
coarse.map((f) => f.t),
@@ -31,16 +31,19 @@ export function useSceneCuts() {
total,
);
const cuts = new Set<number>();
+ const width = fineWidth(v.videoWidth);
for (const [i, w] of windows.entries()) {
- const frames = windowFrames(w);
- // The middle of each 24 fps frame: whichever frame of the clip shows then.
- const fine = await sampleFrames(
- v,
- frames.map((f) => Math.min(duration - 0.01, (f + 0.5) / STUDIO_FPS)),
- { width: 64, signal: ctrl.signal },
- );
- if (ctrl.signal.aborted) return null;
- for (const c of windowCuts(frames, fine.map((f) => f.data.data), total)) cuts.add(c);
+ for (const piece of windowChunks(w)) {
+ const frames = windowFrames(piece);
+ // The middle of each 24 fps frame: whichever frame of the clip shows then.
+ const fine = await sampleFrames(
+ v,
+ frames.map((f) => Math.min(duration - 0.01, (f + 0.5) / STUDIO_FPS)),
+ { width, signal: ctrl.signal },
+ );
+ if (ctrl.signal.aborted) return null;
+ for (const c of windowCuts(frames, fine.map((f) => f.data.data), total)) cuts.add(c);
+ }
setState((s) => ({ ...s, progress: 0.6 + (0.4 * (i + 1)) / windows.length }));
}
setState({ busy: false, progress: 1, error: null });
diff --git a/src/components/swap-studio/workbench.tsx b/src/components/swap-studio/workbench.tsx
index 180ae6c8..49a78d54 100644
--- a/src/components/swap-studio/workbench.tsx
+++ b/src/components/swap-studio/workbench.tsx
@@ -11,7 +11,7 @@ import { Panel, ToolShell } from "@/components/av/tool-shell";
import { tabKeys } from "@/components/shorts/ui";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { uploadFile } from "@/lib/api";
-import { clipExtension, clipProblem, jobState, MODE_LABELS, secondsLabel, SWAP_STUDIO, type GenSummary, type StudioEstimate, type SwapClip, type SwapProject, type SwapShot } from "@/lib/catalog/swap-studio";
+import { clipExtension, clipNeedsPreview, clipProblem, jobState, MODE_LABELS, pageClip, secondsLabel, SWAP_STUDIO, type GenSummary, type StudioEstimate, type SwapClip, type SwapProject, type SwapShot } from "@/lib/catalog/swap-studio";
import { cn } from "@/lib/utils";
import { decisionsHref, useAddClip, usePrepareClip, useSwapEdit, useSwapEstimate, useSwapProject, type EditInput } from "./hooks";
import { GenChip, JobError, Note, priceText, SavedText } from "./parts";
@@ -32,7 +32,7 @@ export interface StageProps {
shot: SwapShot | null;
setShot: (id: string) => void;
edit: (e: EditInput) => Promise<SwapProject | undefined>;
- /** The clip as the page plays it (your GPU's 24 fps copy once it's made). */
+ /** The clip as the page plays it (your GPU's 24 fps copy, or the cloud's browser copy, once it's made). */
src: string;
}
@@ -130,7 +130,7 @@ export function SwapWorkbench({ id }: { id: string }) {
);
}
- const src = clip ? (project.engine === "open" ? (clip.normalized?.url ?? clip.source.url) : clip.source.url) : "";
+ const src = clip ? pageClip(project.engine, clip) : "";
const props: StageProps | null = clip ? { id, project, clip, gens: v.gens, estimate, shot, setShot: setShotId, edit, src } : null;
return (
@@ -328,10 +328,12 @@ function ClipsPanel({
const facts = await browserFacts(file);
const long = clipProblem({ duration: facts.duration });
if (long) return toast.error(long);
+ // A clip this browser can't play (AVI, or a codec it lacks): the cloud makes a copy the page can play.
+ const playable = facts.duration !== undefined && facts.width !== undefined;
setUpload({ name: file.name, progress: 0 });
try {
const up = await uploadClip(file, (p) => setUpload({ name: file.name, progress: p }));
- const p = await add.mutateAsync({ url: up.url, name: file.name, bytes: file.size, ...facts });
+ const p = await add.mutateAsync({ url: up.url, name: file.name, bytes: file.size, playable, ...facts });
onSelect(p.clips.at(-1)!.id);
} catch (e) {
toast.error((e as Error).message);
@@ -364,6 +366,7 @@ function ClipsPanel({
<ul className="space-y-1.5">
{project.clips.map((c) => {
const norm = project.engine === "open" && !c.normalized?.url ? jobState(c.normalized?.genId, undefined, gens) : null;
+ const copy = project.engine === "cloud" && clipNeedsPreview("cloud", c) && !c.preview?.url ? jobState(c.preview?.genId, undefined, gens) : null;
return (
<li key={c.id} className="flex min-w-0 items-center gap-1">
<button
@@ -380,6 +383,7 @@ function ClipsPanel({
{secondsLabel(c.frames)} · {c.shots.length} shot{c.shots.length === 1 ? "" : "s"} · {c.shots.filter((s) => s.mode === "generate").length} swapped
{c.assembly?.genId ? " · assembled" : ""}
{norm ? ` · 24 fps copy: ${norm.status === "succeeded" ? "ready" : norm.status}` : ""}
+ {copy ? ` · browser copy: ${copy.status === "succeeded" ? "ready" : copy.status}` : ""}
</span>
</button>
<button
@@ -414,6 +418,9 @@ function ClipsPanel({
function ClipHeader({ id, project, clip, gens }: StageProps) {
const prepare = usePrepareClip(id);
const norm = jobState(clip.normalized?.genId, undefined, gens);
+ const copy = jobState(clip.preview?.genId, undefined, gens);
+ const copied = project.engine === "cloud" && clipNeedsPreview("cloud", clip);
+ const needsCopy = copied && !clip.preview?.url;
const s = clip.source;
return (
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
@@ -433,9 +440,26 @@ function ClipHeader({ id, project, clip, gens }: StageProps) {
)}
</span>
)}
+ {needsCopy && (
+ <span className="flex items-center gap-2">
+ <span className="text-[12px] text-muted-foreground">Browser copy</span>
+ <GenChip genId={clip.preview?.genId} gens={gens} />
+ {(!clip.preview?.genId || copy.status === "failed" || copy.status === "canceled" || copy.status === "missing") && (
+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" disabled={prepare.isPending} onClick={() => prepare.mutate({ clipId: clip.id }, { onError: (e) => toast.error((e as Error).message) })}>
+ <RotateCcw className="size-3.5" /> Make a browser copy
+ </Button>
+ )}
+ </span>
+ )}
<div className="w-full">
<JobError genId={clip.normalized?.genId} gens={gens} />
+ {project.engine === "cloud" && <JobError genId={clip.preview?.genId} gens={gens} />}
</div>
+ {copied && (
+ <Note className="w-full">
+ Your browser can&apos;t play this clip ({clipExtension(s.name ?? s.url)?.toUpperCase() ?? "its format"}), so the page shows a copy fal makes as an H.264 MP4 — for finding the edits and clicking who to swap. The jobs read the clip as filmed.
+ </Note>
+ )}
</div>
);
}
@@ -443,8 +467,19 @@ function ClipHeader({ id, project, clip, gens }: StageProps) {
/** The clip's shots as a strip (widths by length): pick the shot a stage works on. */
export function ShotStrip({ clip, shot, onPick, gens }: { clip: SwapClip; shot: SwapShot | null; onPick: (id: string) => void; gens: Record<string, GenSummary> }) {
const busy = useMemo(() => new Set(Object.entries(gens).filter(([, g]) => g.status === "queued" || g.status === "running").map(([k]) => k)), [gens]);
+ const current = Math.max(0, clip.shots.findIndex((s) => s.id === shot?.id));
+ // A radio group is one tab stop: the arrow keys (and Home / End) move between shots and pick them.
+ const keys = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ const step = e.key === "ArrowRight" || e.key === "ArrowDown" ? 1 : e.key === "ArrowLeft" || e.key === "ArrowUp" ? -1 : 0;
+ const n = clip.shots.length;
+ const to = e.key === "Home" ? 0 : e.key === "End" ? n - 1 : step ? (current + step + n) % n : -1;
+ if (to < 0) return;
+ e.preventDefault();
+ onPick(clip.shots[to].id);
+ (e.currentTarget.querySelectorAll<HTMLButtonElement>("[role=radio]")[to])?.focus();
+ };
return (
- <div className="flex min-w-0 gap-1 overflow-x-auto pb-1" role="radiogroup" aria-label="Shot">
+ <div className="flex min-w-0 gap-1 overflow-x-auto pb-1" role="radiogroup" aria-label="Shot" onKeyDown={keys}>
{clip.shots.map((s, i) => {
const working = (s.segments ?? []).some((g) => g.takes.some((t) => t.state === "waiting" || (t.genId && busy.has(t.genId))));
return (
@@ -453,6 +488,7 @@ export function ShotStrip({ clip, shot, onPick, gens }: { clip: SwapClip; shot:
type="button"
role="radio"
aria-checked={shot?.id === s.id}
+ tabIndex={i === current ? 0 : -1}
onClick={() => onPick(s.id)}
title={`${MODE_LABELS[s.mode].label} · ${secondsLabel(s.end - s.start)}`}
style={{ flexGrow: Math.max(1, s.end - s.start) }}
diff --git a/src/lib/av/scene-cuts.ts b/src/lib/av/scene-cuts.ts
index 22b1aa89..dc0183ac 100644
--- a/src/lib/av/scene-cuts.ts
+++ b/src/lib/av/scene-cuts.ts
@@ -9,12 +9,27 @@
* frames a second finds the stretches where a cut can be (`coarseWindows`), and a fine pass reads every 24 fps frame
* of those stretches and keeps the frames whose score is over the threshold (`sceneCuts`). Pure: the sampling lives
* in src/components/swap-studio, the tests run these on synthetic frames.
+ *
+ * The score depends on the picture's size: shrinking a frame averages its pixels, and the mean difference of averages
+ * is never more than the mean of the differences (|avg a − avg b| ≤ avg |a − b|), so a small picture scores a cut
+ * lower than FFmpeg does on the whole frame (on a sample pair, 0.035 at 64×36 against 0.046 at 640×360). The coarse
+ * pass reads small frames with a threshold well under 0.32 to make up for it; the fine pass, which decides, reads the
+ * frames at the clip's own size up to FINE_MAX_WIDTH, in stretches of at most FINE_CHUNK frames to bound memory.
*/
/** FFmpeg's scene-change threshold in Akatz Labs' tool. */
export const SCENE_THRESHOLD = 0.32;
/** The coarse pass keeps more than it needs: the fine pass decides at the real threshold. */
export const COARSE_THRESHOLD = 0.18;
+/** The coarse pass's frame width (pixels). */
+export const COARSE_WIDTH = 64;
+/** The widest frame the fine pass reads (the clip's own width when it is narrower). */
+export const FINE_MAX_WIDTH = 1280;
+/** Frames the fine pass holds at once. */
+export const FINE_CHUNK = 24;
+
+/** The fine pass's frame width for a clip `videoWidth` pixels wide (640 when the browser doesn't say). */
+export const fineWidth = (videoWidth: number | undefined) => Math.max(COARSE_WIDTH, Math.min(FINE_MAX_WIDTH, Math.round(videoWidth || 640)));
/** The studio's frame rate: every clip is worked on at 24 fps (H3's rate). */
export const STUDIO_FPS = 24;
@@ -107,6 +122,23 @@ export function coarseWindows(times: number[], scores: number[], total: number,
/** The 24 fps frames a stretch reads, in order. */
export const windowFrames = (w: { from: number; to: number }) => Array.from({ length: w.to - w.from + 1 }, (_, i) => w.from + i);
+/**
+ * A stretch read in pieces of at most `max` frames (at least 3). Each piece after the first starts two frames before
+ * the next frame it decides on (windowCuts ignores a piece's first two frames), so together they decide on the same
+ * frames as the whole stretch.
+ */
+export function windowChunks(w: { from: number; to: number }, max = FINE_CHUNK): { from: number; to: number }[] {
+ const size = Math.max(3, Math.floor(max));
+ const out: { from: number; to: number }[] = [];
+ let from = w.from;
+ for (;;) {
+ const to = Math.min(w.to, from + size - 1);
+ out.push({ from, to });
+ if (to >= w.to) return out;
+ from = to - 1;
+ }
+}
+
/**
* The cuts in one stretch read frame by frame. Its first two scores aren't FFmpeg's: the first frame has nothing
* before it, and the second has no previous MAFD to jump from (FFmpeg's would be the real pair before). So a stretch
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index c157e386..24b1d893 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -210,7 +210,8 @@ export function pointsValue(format: NonNullable<FieldMap["points"]>["format"], p
const x = Math.round(p.x);
const y = Math.round(p.y);
const positive = p.label !== "negative";
- return format === "bria" ? `{'x':${x}, 'y':${y}, 'type':'${positive ? "positive" : "negative"}'}` : { x, y, label: positive ? 1 : 0 };
+ if (format === "bria") return `{'x':${x}, 'y':${y}, 'type':'${positive ? "positive" : "negative"}'}`;
+ return { x, y, label: positive ? 1 : 0, ...(Number.isInteger(p.frame) && p.frame! > 0 ? { frame_index: p.frame } : {}) };
});
}
diff --git a/src/lib/catalog/swap-studio-edit.ts b/src/lib/catalog/swap-studio-edit.ts
index d6bc7b22..717372fa 100644
--- a/src/lib/catalog/swap-studio-edit.ts
+++ b/src/lib/catalog/swap-studio-edit.ts
@@ -2,8 +2,9 @@
* Character Swap Studio's edits: every change the page makes to a project, as pure functions (the server checks the
* shape, applies them and saves; the tests run them here). Jobs that make something (the 24 fps copy, a transcript,
* a mask, an anchor, a take, an assembly) are in src/server/swap-studio.ts. Akatz Labs' rules carried over: a new
- * character picture un-approves the anchors made with the old one; editing a segment's words or speaker keeps its
- * prompt as it was (Update prompt rebuilds it, explicitly); a shot layout can't change under a running job.
+ * character picture un-approves the anchors made with the old one (the shots' scene anchors and the segments' picked
+ * references); editing a segment's words or speaker keeps its prompt as it was (Update prompt rebuilds it,
+ * explicitly); a shot layout can't change under a running job.
*/
import { HISTORY_CHOICES, WINDOW_CHOICES, type SwapLora, type SwapWho } from "./character-swap";
import {
@@ -177,12 +178,13 @@ export function applyEdit(project: SwapProject, edit: SwapEdit, o: { active: (ge
case "character": {
const image = edit.image === undefined ? p.character.image : edit.image;
const description = text(edit.description, SWAP_STUDIO.maxDescriptionChars, "description") ?? p.character.description;
- // Anchors were made with the old picture: they need approving again.
+ // Anchors and segment references were made with the old picture: they need approving (picking) again.
const changed = image !== p.character.image;
+ const unpick = (s: SwapShot): SwapShot => ({ ...s, approvedAnchor: null, segments: s.segments?.map((g) => (g.anchor ? { ...g, anchor: null } : g)) ?? null });
return {
...p,
character: { image, description },
- clips: changed ? p.clips.map((c) => ({ ...c, shots: c.shots.map((s) => ({ ...s, approvedAnchor: null })) })) : p.clips,
+ clips: changed ? p.clips.map((c) => ({ ...c, shots: c.shots.map(unpick) })) : p.clips,
};
}
case "defaults":
@@ -236,6 +238,7 @@ export function applyEdit(project: SwapProject, edit: SwapEdit, o: { active: (ge
who.words = who.words.slice(0, 120);
if (x.approvedAnchor && !s.anchors.some((a) => a.id === x.approvedAnchor && a.url)) throw new EditError("That anchor isn't ready yet");
if (x.approvedMask && !s.masks.some((m) => m.id === x.approvedMask && m.pieces.every((pc) => pc.url))) throw new EditError("That mask isn't ready yet");
+ if (x.approvedMask && s.masks.find((m) => m.id === x.approvedMask)!.engine !== p.engine) throw new EditError("That mask was made on the other engine — track the shot again here");
return {
...s,
...(x.mode ? { mode: x.mode } : {}),
diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.ts
index 2006a86d..4ed714c4 100644
--- a/src/lib/catalog/swap-studio-plan.ts
+++ b/src/lib/catalog/swap-studio-plan.ts
@@ -8,16 +8,18 @@
* correct), Qwen-Image-Edit 2511 makes anchors, and each segment is one H3 Relay pass with the approved mask, its
* anchor and the previous take's lossless (FFV1) master as history; the assembly fits every piece to the clip's size
* at 24 fps, joins them packet by packet and puts the clip's sound back.
- * The cloud (fal): the clip stays as filmed (H3 makes 24 fps, the join keeps the lowest rate), Scribe v2 transcribes,
+ * The cloud (fal): the clip stays as filmed (a browser copy is made when the page can't play it), Scribe v2 transcribes,
* SAM 3.1 video marks the person from your words or clicks, GPT Image 2.5 Sunburst or Nano Banana Pro make anchors, and
- * each segment is fal's MiniMax H3 reference-to-video with Akatz Labs' swap LoRA — no mask (who to swap is said in
- * words) and no history (a continuing segment starts from the previous take's last frame).
+ * each segment is fal's MiniMax H3 reference-to-video with Akatz Labs' swap LoRA, trimmed to the segment — no mask (who
+ * to swap is said in words) and no history (a continuing segment starts from the previous take's last frame); the
+ * assembly scales every piece to one frame and joins them at 24 fps.
*/
import { anchorAspect, anchorModel, anchorPrompt, swapLoraRef } from "./character-swap";
import { MASK_TRACKER } from "./remove-object";
import type { PlanStep } from "./shorts";
import {
at,
+ cloudFilmSize,
enginePrompt,
frameWindow,
normalizedSize,
@@ -55,6 +57,7 @@ export const STUDIO_MODELS = {
cut: "trim-video",
frame: "extract-frame",
swap: "fuobe-character-swap",
+ scale: "scale-video",
join: "join-clips",
mux: "merge-audio-video",
joinMax: 24,
@@ -91,6 +94,29 @@ export function planNormalize(clip: SwapClip): PlanStep[] {
];
}
+/**
+ * The cloud: a copy of the clip the browser can play (fal's scale-video re-encodes it as an H.264 MP4 at its own
+ * size), for the page alone — the cloud's jobs read the upload as filmed. Null when the clip's size is unknown.
+ */
+export function planPreview(clip: SwapClip): PlanStep[] | null {
+ const size = normalizedSize(clip.source.width, clip.source.height);
+ if (!size) return null;
+ return [
+ {
+ key: "preview",
+ request: {
+ ...helper(`Character Swap · ${clip.name}`),
+ title: `${clip.name} · browser copy`,
+ modelId: STUDIO_MODELS.cloud.scale,
+ op: "reframe",
+ inputs: { video: clip.source.url },
+ params: { extra: { ...size } },
+ step: { label: "A copy your browser can play", index: 0, of: 1 },
+ },
+ },
+ ];
+}
+
// ---------------------------------------------------------------------------
// Transcript
@@ -140,6 +166,20 @@ export function maskPointsPayload(engine: Engine, points: PixelPoint[], who: Who
return clicked.length ? { points: clicked, prompt: who.words.trim() || "person", selection: "index", subjectIndex: 0 } : { prompt: who.words.trim() || "person", selection: who.selection, subjectIndex: who.selection === "index" ? who.index : 0 };
}
+/**
+ * The clip's frames [from, to) a cloud mask job reads, and where the shot's frame is in them (`offset`). Track shot:
+ * from the frame to the shot's end. Update frame: half a second (a one-frame cut is too short to trim and track) from
+ * the frame — past the shot's end if need be, it is the clicked frame that counts — or, in the clip's last half
+ * second, its last 12 frames with the clicks on the frame inside them.
+ */
+export function cloudMaskCut(clip: Pick<SwapClip, "frames">, shot: Pick<SwapShot, "start" | "end">, kind: MaskVersion["kind"], frame: number): { from: number; to: number; offset: number } {
+ const at0 = shot.start + frame;
+ if (kind === "track") return { from: at0, to: shot.end, offset: 0 };
+ const span = Math.min(12, clip.frames);
+ const from = Math.max(0, Math.min(at0, clip.frames - span));
+ return { from, to: from + span, offset: at0 - from };
+}
+
export function planMask(m: MaskPlanInput): PlanStep[] {
const { clip, shot } = m;
const len = shot.end - shot.start;
@@ -179,12 +219,11 @@ export function planMask(m: MaskPlanInput): PlanStep[] {
},
];
}
- const from = shot.start + m.frame;
- // Update frame reads half a second from the frame (a one-frame cut is too short to trim and track); its piece is the
- // first frame of that mask.
- const to = m.kind === "frame" ? Math.min(shot.end, from + 12) : shot.end;
+ const cut = cloudMaskCut(clip, shot, m.kind, m.frame);
+ // The clicks go on the clicked frame of the cut (fal's frame_index when it isn't the first).
+ const points = payload.points?.map((p) => (cut.offset ? { ...p, frame: cut.offset } : p));
return [
- { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: clip.source.url }, params: { startTime: at(from), endTime: at(to) }, step: { label: "Cut from the frame", index: 0, of: 2 } } },
+ { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: clip.source.url }, params: { startTime: at(cut.from), endTime: at(cut.to) }, step: { label: "Cut from the frame", index: 0, of: 2 } } },
{
key: "mask",
request: {
@@ -193,7 +232,7 @@ export function planMask(m: MaskPlanInput): PlanStep[] {
modelId: STUDIO_MODELS.cloud.mask,
op: "bg-remove-video",
...(payload.prompt ? { prompt: payload.prompt } : {}),
- params: { matteOutput: "matte", duration: at(to - from), ...(payload.points ? { points: payload.points } : {}) },
+ params: { matteOutput: "matte", duration: at(cut.to - cut.from), ...(points ? { points } : {}) },
step: { label, index: 1, of: 2 },
},
after: ["cut"],
@@ -280,6 +319,8 @@ export interface SegmentPlanInput {
mask?: string | null;
/** Your GPU: the previous take's lossless master and its frame count; the cloud: its video (the last frame starts this one). */
previous?: { master?: string; video?: string; frames: number } | null;
+ /** Your GPU: how many of this take's last frames its master keeps (masterKeep; all of them when unset). */
+ keep?: number;
}
/** H3's whole seconds for a cloud call (5–15). */
@@ -303,6 +344,7 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; final
if (h && !p.previous?.master) throw new Error(`${label} continues from the segment before it, which has no lossless master`);
const first = shot.start + seg.start - h;
const mask = shot.settings.useMask ? (p.mask ?? null) : null;
+ const keep = Math.max(1, Math.min(frames, p.keep ?? frames));
return {
final: "swap",
steps: [
@@ -330,6 +372,9 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; final
...(mask ? { maskVideo: mask, maskStart: frameWindow(seg.start - h, seg.end).startTime } : {}),
...(h ? { historyVideo: p.previous!.master, historyStart: p.previous!.frames - h, historyLength: h } : {}),
...(h && p.anchor ? { anchorAfterHistory: true } : {}),
+ // The master keeps the segment's last `keep` frames (what the next segment reads as history).
+ masterKeep: keep,
+ segmentFrames: frames,
},
},
step: { label, index: 0, of: 1 },
@@ -338,18 +383,20 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; final
],
};
}
- // The cloud: fal's H3 takes 2–15 s of reference video and makes whole seconds.
+ // The cloud: fal's H3 takes 2–15 s of reference video and makes whole seconds (at least 5), so its video is cut back
+ // to the segment: the next segment's boundary is this one's last frame, and the assembly lines it up with the sound.
const from = shot.start + seg.start;
const boundary = p.history > 0 && !!p.previous?.video;
+ const of = boundary ? 4 : 3;
const steps: PlanStep[] = [
- { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: clip.source.url }, params: { startTime: at(from), endTime: at(shot.start + seg.end) }, step: { label: `${label} · cut`, index: 0, of: 3 } } },
+ { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: clip.source.url }, params: { startTime: at(from), endTime: at(shot.start + seg.end) }, step: { label: `${label} · cut`, index: 0, of } } },
];
const after = ["cut"];
const chain: ChainSlot[] = [{ slot: "video" }];
if (boundary) {
steps.push({
key: "boundary",
- request: { ...helper(title), modelId: STUDIO_MODELS.cloud.frame, op: "frame", inputs: { video: p.previous!.video! }, params: { extra: { frame_type: "last" } }, step: { label: `${label} · the previous take's last frame`, index: 1, of: 3 } },
+ request: { ...helper(title), modelId: STUDIO_MODELS.cloud.frame, op: "frame", inputs: { video: p.previous!.video! }, params: { extra: { frame_type: "last" } }, step: { label: `${label} · the previous take's last frame`, index: 1, of } },
});
after.push("boundary");
chain.push({ slot: "images", position: "last" });
@@ -366,12 +413,18 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; final
inputs: { images: [project.character.image, ...(p.anchor ? [p.anchor] : [])] },
loras: [swapLoraRef(shot.settings.lora === "v1" ? "v1" : "v1.5")],
params: { duration: cloudCallSeconds(frames), sourceDuration: at(frames), resolution: quality, seed: seg.seed },
- step: { label, index: 2, of: 3 },
+ step: { label: `${label} · swap`, index: of - 2, of },
},
after,
chain,
});
- return { steps, final: "swap" };
+ steps.push({
+ key: "fit",
+ request: { ...helper(title), title: label, modelId: STUDIO_MODELS.cloud.cut, op: "trim", params: { startTime: 0, endTime: at(frames) }, step: { label, index: of - 1, of } },
+ after: ["swap"],
+ chain: [{ slot: "video" }],
+ });
+ return { steps, final: "fit" };
}
/**
@@ -403,6 +456,7 @@ export function frozenTakePlan(
anchor: f.anchor,
mask: f.mask,
previous,
+ ...(f.keep !== undefined ? { keep: f.keep } : {}),
});
}
@@ -438,8 +492,9 @@ function joins(steps: PlanStep[], keys: string[], max: number, request: (n: numb
/**
* The clip with every swapped shot's chosen takes over the original timeline and the clip's own sound; kept shots
* stay as filmed. Your GPU: each piece fitted to the clip's size at 24 fps (Fuobe's fit graph), joined packet by
- * packet, the clip's sound put back. The cloud: each piece cut (a take to its segment's exact length), joined (fal
- * keeps the lowest frame rate: 24 for H3), the clip's sound (or its silence) put back.
+ * packet, the clip's sound put back. The cloud: the clip's pieces cut (a take is already its segment's length), every
+ * piece scaled to one frame (cloudFilmSize: H3 makes 480p / 768p, the clip is as filmed), joined at 24 fps, the clip's
+ * sound (or its silence) put back.
*/
export function planAssembly(a: AssemblyPlanInput): { steps: PlanStep[]; final: string } {
const { clip } = a;
@@ -449,6 +504,7 @@ export function planAssembly(a: AssemblyPlanInput): { steps: PlanStep[]; final:
const steps: PlanStep[] = [];
const keys: string[] = [];
const size = normalizedSize(clip.source.width, clip.source.height);
+ const film = cloudFilmSize(clip.source.width, clip.source.height);
a.pieces.forEach((piece, i) => {
const key = `piece${i}`;
const what = piece.kind === "source" ? "kept as filmed" : "your character";
@@ -463,12 +519,24 @@ export function planAssembly(a: AssemblyPlanInput): { steps: PlanStep[]; final:
request: { ...helper(title), modelId: STUDIO_MODELS.open.fit, op: "trim", inputs: { video }, params: { startTime: start, endTime: start + len, fps: SWAP_STUDIO.fps, ...(size ? { extra: { ...size } } : { aspectRatio: "auto" }) }, step: label },
});
} else {
- steps.push({ key, request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video }, params: { startTime: start, endTime: start + len }, step: label } });
+ const cut = piece.kind === "source";
+ if (cut) steps.push({ key: film ? `${key}-cut` : key, request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video }, params: { startTime: start, endTime: start + len }, step: label } });
+ if (film) {
+ steps.push({
+ key,
+ request: { ...helper(title), modelId: STUDIO_MODELS.cloud.scale, op: "reframe", ...(cut ? {} : { inputs: { video } }), params: { extra: { ...film } }, step: { ...label, label: `${label.label} · to ${film.width}×${film.height}` } },
+ ...(cut ? { after: [`${key}-cut`], chain: [{ slot: "video" as const }] } : {}),
+ });
+ } else if (!cut) {
+ // The clip's size unknown: the take as it came out.
+ steps.push({ key, request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video }, params: { startTime: 0, endTime: len }, step: label } });
+ }
}
keys.push(key);
});
const m = STUDIO_MODELS[a.engine];
- const picture = joins(steps, keys, m.joinMax, (_n, last) => ({ ...helper(title), modelId: m.join, op: "concat", prompt: title, step: { label: last ? "Join the parts" : "Joining", index: 1000, of: 1000 } }));
+ const rate = a.engine === "cloud" ? { params: { extra: { target_fps: SWAP_STUDIO.fps } } } : {};
+ const picture = joins(steps, keys, m.joinMax, (_n, last) => ({ ...helper(title), modelId: m.join, op: "concat", prompt: title, ...rate, step: { label: last ? "Join the parts" : "Joining", index: 1000, of: 1000 } }));
const sound: GenerationRequest["inputs"] = clip.source.hasAudio ? { audio: workingClip(clip, a.engine) } : a.engine === "cloud" ? { audio: silenceRef(clip.source.duration) } : undefined;
if (!sound) {
// Your GPU, a silent clip: the fit graph already gave every part silence; the join is the result.
diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.ts
index fca5a132..57dea649 100644
--- a/src/lib/catalog/swap-studio.ts
+++ b/src/lib/catalog/swap-studio.ts
@@ -13,8 +13,9 @@
* steps are in swap-studio-plan.ts. Behaviour follows Akatz Labs' app (MIT, Akatz Labs 2026); its prompts are reused
* with that notice. No code of theirs is copied.
*/
-import { CHARACTER_SWAP, HISTORY_CHOICES, WINDOW_CHOICES, whoWords, type SwapLora, type SwapWho } from "./character-swap";
+import { CHARACTER_SWAP, h3Canvas, HISTORY_CHOICES, WINDOW_CHOICES, whoWords, type SwapLora, type SwapWho } from "./character-swap";
import { STUDIO_FPS } from "@/lib/av/scene-cuts";
+import { wholeClipBudget } from "@/lib/av/video-finish";
import type { Engine, PixelPoint } from "./types";
export const SWAP_STUDIO = {
@@ -121,6 +122,8 @@ export const DEFAULT_WHO: WhoToSwap = { selection: "largest", index: 0, words: "
export interface MaskPiece {
from: number;
frames: number;
+ /** Frames into its video where `from` is (a cloud Update frame near the clip's end reads frames before it). */
+ offset?: number;
/** The mask video once it is made. */
url?: string;
genId?: string;
@@ -174,6 +177,11 @@ export interface FrozenTake {
anchor: string | null;
/** Your GPU: the approved mask video (masked generation on). */
mask: string | null;
+ /**
+ * Your GPU: how many of the take's last frames its lossless master keeps (what the next segment reads as history;
+ * unset: all of them).
+ */
+ keep?: number;
settings: SwapSettings;
who: WhoToSwap;
}
@@ -273,9 +281,15 @@ export interface TranscriptCue {
export interface SwapClip {
id: string;
name: string;
- source: { url: string; name?: string; duration: number; fps?: number; width?: number; height?: number; hasAudio: boolean; bytes?: number };
+ /** The upload; `playable` false when the browser that added it couldn't play it (AVI, or a codec it lacks). */
+ source: { url: string; name?: string; duration: number; fps?: number; width?: number; height?: number; hasAudio: boolean; bytes?: number; playable?: boolean };
/** Your GPU: the clip at 24 fps (H.264, its sound kept), made on import. */
normalized: { genId?: string; url?: string } | null;
+ /**
+ * The cloud: an H.264 copy at the clip's size for the page to play, show frames from and detect edits in, made when
+ * the browser can't play the upload (clipNeedsPreview). The cloud's jobs read the upload as filmed.
+ */
+ preview?: { genId?: string; url?: string } | null;
/** Frames at 24 fps. */
frames: number;
cuts: number[];
@@ -385,6 +399,24 @@ export function normalizedSize(width?: number, height?: number): { width: number
return { width: even(width), height: even(height) };
}
+/**
+ * The cloud assembly's frame: the clip's own shape on even numbers within fal merge-videos' 512–2048 px (every piece,
+ * the clip's own and H3's 480p / 768p takes, is scaled to it before the join). Null when the clip's size is unknown.
+ */
+export function cloudFilmSize(width?: number, height?: number): { width: number; height: number } | null {
+ if (!width || !height) return null;
+ // Down to 2048 on the long side; up towards 512 on the short side (as far as the long side allows).
+ const scale = Math.min(2048 / Math.max(width, height), Math.max(1, 512 / Math.min(width, height)));
+ const even = (n: number) => Math.max(2, Math.round((n * scale) / 2) * 2);
+ return { width: even(width), height: even(height) };
+}
+
+/** Whether the page needs a copy of a clip to play it (the cloud keeps the upload as filmed; your GPU makes its 24 fps copy anyway). */
+export const clipNeedsPreview = (engine: Engine, clip: Pick<SwapClip, "source">) => engine === "cloud" && (clip.source.playable === false || clipExtension(clip.source.name ?? clip.source.url) === "avi");
+
+/** The clip as the page plays it: your GPU's 24 fps copy, the cloud's browser copy, else the upload. */
+export const pageClip = (engine: Engine, clip: Pick<SwapClip, "source" | "normalized" | "preview">) => (engine === "open" ? clip.normalized?.url : clip.preview?.url) ?? clip.source.url;
+
// ---------------------------------------------------------------------------
// Shots
@@ -824,14 +856,28 @@ export const dependencies = (items: SwapSegment[], index: number): TakeDependenc
export const takeOf = (seg: SwapSegment, id?: string | null) => seg.takes.find((t) => t.id === (id ?? seg.selectedTake)) ?? null;
-/** The mask a shot's segments generate with (your GPU, masked generation on): the approved version's newest piece. */
-export function approvedMask(shot: SwapShot): MaskVersion | null {
- return shot.masks.find((m) => m.id === shot.approvedMask) ?? null;
+/**
+ * The shot's approved mask version, on `engine` when one is named: a version made on the other engine doesn't count
+ * there (a cloud mask is pieces of the clip as filmed, your GPU's one whole-shot mask at 24 fps).
+ */
+export function approvedMask(shot: SwapShot, engine?: Engine): MaskVersion | null {
+ const m = shot.masks.find((x) => x.id === shot.approvedMask) ?? null;
+ return m && (!engine || m.engine === engine) ? m : null;
+}
+
+/**
+ * The version a new mask job corrects when none is named: the approved one, else the newest finished one — made on
+ * this engine (a version from the other engine can't be spliced into).
+ */
+export function defaultMaskBase(shot: SwapShot, engine: Engine): MaskVersion | null {
+ const finished = (m: MaskVersion) => m.engine === engine && m.pieces.every((x) => x.url);
+ const approved = approvedMask(shot, engine);
+ return approved && finished(approved) ? approved : ([...shot.masks].reverse().find(finished) ?? null);
}
/** Everything a take's result depends on: a take whose signature differs from its segment's is stale. */
export function settingSignature(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, engine: Engine = project.engine): string {
- const mask = engine === "open" && shot.settings.useMask ? (approvedMask(shot)?.pieces.map((p) => p.url ?? p.genId) ?? null) : null;
+ const mask = engine === "open" && shot.settings.useMask ? (approvedMask(shot, engine)?.pieces.map((p) => p.url ?? p.genId) ?? null) : null;
return digest({
engine,
source: clip.normalized?.url ?? clip.source.url,
@@ -937,12 +983,14 @@ export function planQueue(
if (mode !== "segment") indices = indices.filter((i) => !busy(items[i]) && states[i].status !== "ready");
if (!indices.length) return { problem: "These segments are already current, queued or generating" };
const queued = new Set(indices);
- const mask = approvedMask(shot);
+ const mask = approvedMask(shot, engine);
const entries: QueueEntry[] = [];
for (const i of indices) {
const seg = items[i];
const n = i + 1;
- if (seg.anchorMode !== "none" && !segmentAnchor(shot, seg)) {
+ // "Scene anchor" off in the shot's settings: a segment set to the scene anchor runs without one.
+ const wantsAnchor = seg.anchorMode === "custom" || (seg.anchorMode === "shot" && shot.settings.useAnchor);
+ if (wantsAnchor && !segmentAnchor(shot, seg)) {
return { problem: seg.anchorMode === "shot" ? `Segment ${n}: approve a scene anchor, or choose no anchor` : `Segment ${n}: pick its reference image, or choose no anchor` };
}
if (engine === "open" && shot.settings.useMask && mask && mask.pieces.some((p) => !p.url)) return { problem: "The approved mask is still being made — wait for it" };
@@ -966,6 +1014,8 @@ export function planQueue(
const chosen = takeOf(items[j]);
if (states[j].status !== "ready" || !chosen) return { problem: `Generate segment ${j + 1} first, or queue from an earlier segment` };
if (engine === "open" && o.hasMaster && !o.hasMaster(chosen)) return { problem: `Segment ${j + 1}'s take has no lossless master to continue from — make it again on your GPU` };
+ const kept = chosen.frozen?.keep ?? items[j].end - items[j].start;
+ if (engine === "open" && kept < d.frames) return { problem: `Segment ${j + 1}'s take kept its last ${kept} frame${kept === 1 ? "" : "s"} to continue from — use at most ${kept} frames of history, or make segment ${j + 1} again` };
if (chosen.engine !== engine) return { problem: `Segment ${j + 1}'s take was made on the ${chosen.engine === "open" ? "open engine" : "cloud"} — make it again on this engine to continue from it` };
}
entries.push({ index: i, segment: seg, waitsOn, dependencies: deps });
@@ -973,9 +1023,21 @@ export function planQueue(
return { entries };
}
+/**
+ * How many of a take's last frames its lossless master keeps (your GPU): the most the segment after it can read as
+ * history — its own history when it continues, the shot's history for a layout made later — and at most the segment.
+ * A 16-bit master of a whole segment runs to hundreds of MB, more than ComfyUI takes as an upload by default (100 MB);
+ * the next segment reads only these frames.
+ */
+export function masterKeep(items: SwapSegment[], index: number, settings: Pick<SwapSettings, "historyFrames">): number {
+ const seg = items[index];
+ const next = items[index + 1];
+ return Math.min(seg.end - seg.start, Math.max(1, settings.historyFrames, next ? effectiveHistory(next) : 0));
+}
+
/** A segment's take as queued now: what it will run with (see FrozenTake). */
export function freezeTake(project: SwapProject, shot: SwapShot, seg: SwapSegment): FrozenTake {
- const mask = project.engine === "open" && shot.settings.useMask ? (approvedMask(shot)?.pieces[0]?.url ?? null) : null;
+ const mask = project.engine === "open" && shot.settings.useMask ? (approvedMask(shot, "open")?.pieces[0]?.url ?? null) : null;
return {
reference: project.character.image ?? "",
shotStart: shot.start,
@@ -1086,9 +1148,12 @@ export function maskPieceAt(version: MaskVersion | null | undefined, frame: numb
return null;
}
-/** The pieces of a new version (the cloud keeps the corrected version's pieces under the new one). */
-export function maskPieces(engine: Engine, kind: MaskVersion["kind"], frame: number, shotFrames: number, base: MaskVersion | null): MaskPiece[] {
- const piece: MaskPiece = kind === "frame" ? { from: frame, frames: 1 } : { from: frame, frames: shotFrames - frame };
+/**
+ * The pieces of a new version (the cloud keeps the corrected version's pieces under the new one). `offset`: where the
+ * new piece's first frame is in its video (a cloud Update frame near the clip's end reads frames before it).
+ */
+export function maskPieces(engine: Engine, kind: MaskVersion["kind"], frame: number, shotFrames: number, base: MaskVersion | null, offset = 0): MaskPiece[] {
+ const piece: MaskPiece = { ...(kind === "frame" ? { from: frame, frames: 1 } : { from: frame, frames: shotFrames - frame }), ...(offset > 0 ? { offset } : {}) };
// Your GPU splices the new part into the corrected version: one whole-shot mask.
if (engine === "open") return [{ from: 0, frames: shotFrames }];
return [...(base?.pieces ?? []).filter((p) => p.url || p.genId), piece];
@@ -1106,6 +1171,26 @@ export function maskProblem(engine: Engine, kind: MaskVersion["kind"], frame: nu
return null;
}
+const GB = 2 ** 30;
+
+/**
+ * Your GPU's mask graph holds the whole shot as float frames at H3's canvas size: the prepared shot, SAM's masks as
+ * pictures and the joined result — and, correcting a version, that version decoded, fitted and cut around the new part
+ * as well. Why a ComfyUI with `ramBytes` of RAM can't take this shot (half of it may go to frames, as for the other
+ * whole-clip graphs); null when it fits or the clip's size is unknown.
+ */
+export function maskMemoryProblem(m: { width?: number; height?: number; quality: string | undefined; shotFrames: number; correcting: boolean }, ramBytes: number | undefined): string | null {
+ if (!m.width || !m.height || !(m.shotFrames > 0)) return null;
+ const canvas = h3Canvas(m.width, m.height, m.quality);
+ const need = canvas.width * canvas.height * 12 * m.shotFrames * (m.correcting ? 6 : 3);
+ const budget = wholeClipBudget(ramBytes);
+ if (need <= budget) return null;
+ return (
+ `A mask on your GPU holds the whole shot in memory: this ${secondsLabel(m.shotFrames)} shot needs about ${Math.ceil(need / GB)} GB of RAM and this ComfyUI can spare ${Math.floor(budget / GB)} GB. ` +
+ `Cut the shot shorter (Shots → Cut at the playhead)${m.quality === "768p" ? ", or track it at 0.5 MP" : ""}`
+ );
+}
+
// ---------------------------------------------------------------------------
// Takes and review
@@ -1193,12 +1278,15 @@ export type AssemblyPiece = { kind: "source"; start: number; end: number } | { k
/**
* The clip's timeline for the assembly: kept shots as they were filmed (neighbours merged into one piece), swapped
- * shots as their segments' chosen takes, in order. Every swapped shot needs a current take for every segment.
+ * shots as their segments' chosen takes, in order. Every swapped segment needs a chosen take that came out (Akatz's
+ * assemble: a selected take for every generated shot); one made with settings that changed since is used as it is and
+ * named in `stale`, for the page to say.
*/
-export function assemblyPieces(project: SwapProject, clip: SwapClip): { pieces: AssemblyPiece[] } | { problem: string } {
+export function assemblyPieces(project: SwapProject, clip: SwapClip): { pieces: AssemblyPiece[]; stale: string[] } | { problem: string } {
if (!clip.shots.length) return { problem: "Confirm the clip's shots first" };
if (!clip.shots.some((s) => s.mode === "generate")) return { problem: "No shot replaces the character — mark at least one shot Replace character" };
const pieces: AssemblyPiece[] = [];
+ const stale: string[] = [];
for (const [si, shot] of clip.shots.entries()) {
if (shot.mode === "preserve") {
const last = pieces.at(-1);
@@ -1210,16 +1298,58 @@ export function assemblyPieces(project: SwapProject, clip: SwapClip): { pieces:
const states = segmentStates(project, clip, shot, items);
for (const [gi, seg] of items.entries()) {
const t = takeOf(seg);
- if (!t || states[gi].status !== "ready") return { problem: `Shot ${si + 1}, segment ${gi + 1} has no current take — generate it, or use a take that matches its settings` };
+ if (!t || t.state !== "launched") return { problem: `Shot ${si + 1}, segment ${gi + 1} has no chosen take — generate it, or choose one in Takes & review` };
+ if (states[gi].status !== "ready") stale.push(`Shot ${si + 1}, segment ${gi + 1}`);
pieces.push({ kind: "take", start: shot.start + seg.start, end: shot.start + seg.end, take: t, segmentId: seg.id });
}
}
- return { pieces };
+ return { pieces, stale };
}
/** The takes an assembly is made of (its identity: the same takes need no new assembly). */
export const assemblyTakes = (pieces: AssemblyPiece[]) => pieces.flatMap((p) => (p.kind === "take" ? [p.take.id] : []));
+// ---------------------------------------------------------------------------
+// From Genjutsu
+
+export interface HandOffInput {
+ engine: Engine;
+ /** The clip Genjutsu has (its upload once it is done). */
+ clip?: { url?: string; name: string; size?: number; duration?: number; width?: number; height?: number } | null;
+ /** The character's picture (an upload) and description. */
+ image?: string | null;
+ description?: string;
+}
+
+/**
+ * "Open in Character Swap Studio" from Genjutsu's Character swap: a project on the same engine with the character
+ * already in it, and the whole clip (the studio cuts it into shots), when Genjutsu has them uploaded.
+ */
+export function studioHandOff(o: HandOffInput): {
+ project: { name: string; engine: Engine; character: { image: string | null; description: string } };
+ clip: { url: string; name: string; bytes?: number; duration?: number; width?: number; height?: number } | null;
+} {
+ const file = o.clip?.url?.startsWith("/api/files/") ? o.clip : null;
+ const name = file ? file.name.replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, SWAP_STUDIO.maxNameChars) : "";
+ return {
+ project: {
+ name: name || "Character swap",
+ engine: o.engine,
+ character: { image: o.image?.startsWith("/api/files/") ? o.image : null, description: tidy(o.description).slice(0, SWAP_STUDIO.maxDescriptionChars) },
+ },
+ clip: file
+ ? {
+ url: file.url!,
+ name: file.name,
+ ...(file.size !== undefined ? { bytes: file.size } : {}),
+ ...(file.duration !== undefined ? { duration: file.duration } : {}),
+ ...(file.width !== undefined ? { width: file.width } : {}),
+ ...(file.height !== undefined ? { height: file.height } : {}),
+ }
+ : null,
+ };
+}
+
// ---------------------------------------------------------------------------
// The Finish stage (Akatz's refinement) — not runnable from the public release
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 5e575b65..da27b268 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -235,6 +235,8 @@ export interface PixelPoint {
x: number;
y: number;
label?: "positive" | "negative";
+ /** A video's frame the point is on (0, the first, when unset): SAM 3.1 video's `frame_index` on fal. */
+ frame?: number;
}
/** A position on a picture as fractions of its width and height (0–1 from the top left). */
diff --git a/src/lib/swap-studio-graphs.ts b/src/lib/swap-studio-graphs.ts
index d5af28bf..0c1b7b25 100644
--- a/src/lib/swap-studio-graphs.ts
+++ b/src/lib/swap-studio-graphs.ts
@@ -20,6 +20,11 @@ export interface SegmentGraphOptions {
mask?: { file: string; start: number; duration: number } | null;
/** Masked generation off: the whole frame is regenerated (the edit mask is bypassed). */
useMask: boolean;
+ /**
+ * The lossless master keeps the take's last `frames` frames from `from` on (what the next segment reads as history):
+ * a 16-bit master of the whole segment is hundreds of MB, more than ComfyUI takes as an upload by default.
+ */
+ masterTail?: { from: number; frames: number } | null;
/** Output nodes (never dropped). */
outputs: string[];
}
@@ -29,7 +34,7 @@ export interface SegmentGraphOptions {
* loader goes); without an anchor and without history Picture 2 and the first-frame guide go too (the window's anchor
* would otherwise be the clip's own first frame). With both, the anchor moves to Picture 3 at the canvas size and the
* window's anchor output is the boundary. An approved mask replaces SAM's chain; masked generation off bypasses the
- * edit mask and SAM altogether.
+ * edit mask and SAM altogether. The master saves only the frames the next segment can read (masterTail).
*/
export function segmentGraph(wf: ComfyWorkflow, o: SegmentGraphOptions): ComfyWorkflow {
const out = cloneWorkflow(wf);
@@ -62,6 +67,11 @@ export function segmentGraph(wf: ComfyWorkflow, o: SegmentGraphOptions): ComfyWo
out.mask_channel = { class_type: "ImageToMask", inputs: { image: ["mask_fit", 0], channel: "red" } };
out.expand_mask.inputs.masks = ["mask_channel", 0];
}
+ const save = out.save_master?.inputs;
+ if (o.masterTail && save && isLink(save.images)) {
+ out.master_tail = { class_type: "ImageFromBatch", inputs: { image: [...save.images], batch_index: o.masterTail.from, length: o.masterTail.frames }, _meta: { title: "The take's last frames (the next segment's history)" } };
+ save.images = ["master_tail", 0];
+ }
return dropUnused(out, o.outputs);
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 121ddab5..529e4ec8 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -43,6 +43,7 @@ import { exportValues, exrWorkflow, framesPerPass, hdrColorSpace, upscaleShortSi
import { guessKind } from "@/lib/catalog/payload";
import { loraByFile, needsToken } from "@/lib/catalog/loras";
import { CHARACTER_SWAP, packResolution, samCoords, swapPrompt, SWAP_LORAS, windowPlan } from "@/lib/catalog/character-swap";
+import { maskMemoryProblem } from "@/lib/catalog/swap-studio";
import { STUDIO_WORKFLOWS } from "@/lib/catalog/swap-studio-plan";
import { maskGraph, segmentGraph, type MaskGraphOptions, type SegmentGraphOptions } from "@/lib/swap-studio-graphs";
import { getMaker, makerPrompt, OPEN_TARGET_PROBLEM, ORIGINALS, swapTarget } from "@/lib/catalog/genjutsu";
@@ -967,14 +968,18 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
}
const maskFile = typeof extra.maskVideo === "string" && extra.maskVideo ? extra.maskVideo : null;
const span = input.endTime !== undefined ? Math.max(0, input.endTime - start) : Number(values.duration ?? 0);
+ // The master keeps the segment's last frames (the next segment's history), not the whole 16-bit segment.
+ const frames = Math.round(Number(extra.segmentFrames ?? 0));
+ const keep = Math.round(Number(extra.masterKeep ?? frames));
studioSegment = {
anchor: !dropAnchor,
history,
anchorAfterHistory: extra.anchorAfterHistory === true,
mask: maskFile ? { file: maskFile, start: Math.max(0, Number(extra.maskStart ?? 0)), duration: span } : null,
useMask: extra.useMask !== false,
+ masterTail: frames > 0 && keep > 0 && keep < frames ? { from: frames - keep, frames: keep } : null,
};
- for (const k of ["maskVideo", "maskStart", "anchorAfterHistory", "useMask"]) delete extra[k];
+ for (const k of ["maskVideo", "maskStart", "anchorAfterHistory", "useMask", "masterKeep", "segmentFrames"]) delete extra[k];
}
// Character Swap Studio's mask: who to swap on one frame of a shot (words, a selection or clicks moved into H3's
// canvas), followed for spanFrames, spliced into the version it corrects (prevMask).
@@ -1004,6 +1009,9 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
Object.assign(extra, { keyFrame, spanFrames, tailStart: keyFrame + spanFrames, tailFrames: Math.max(1, shotFrames - keyFrame - spanFrames) });
delete extra.shotFrames;
studioMask = { head: keyFrame, tail: shotFrames - keyFrame - spanFrames, prev };
+ // The graph holds the whole shot as float frames: refuse what the server can't hold (before it runs out of memory).
+ const tooBig = maskMemoryProblem({ width: clip?.width, height: clip?.height, quality: input.resolution, shotFrames, correcting: prev }, await ctx.serverRam?.());
+ if (tooBig) throw new ProviderError(tooBig);
}
// Genjutsu's Object swap: SAM 3.1 follows what goes (params.extra.maskPrompt, or the "replace … with" part of the prompt,
// as Genjutsu sends it), the reference comes in, the prompt describes the result. Insert: the painted spot and the
@@ -1239,6 +1247,11 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
form.append("type", "input");
form.append("overwrite", "true");
const res = await comfyFetch("/upload/image", { method: "POST", body: form }, worker);
+ if (res.status === 413) {
+ // ComfyUI's own limit (--max-upload-size, 100 MB unless it was started with more).
+ const mb = Math.ceil(data.length / 2 ** 20);
+ throw new ProviderError(`ComfyUI refused a ${mb} MB upload as too large (its --max-upload-size, 100 MB unless set) — start ComfyUI with a higher --max-upload-size, or send a smaller file`);
+ }
if (!res.ok) {
const text = await res.text().catch(() => "");
throw worker === "isolated" ? isolatedAnswer("an upload", res.status, reasonOf(text)) : new ProviderError(`ComfyUI upload failed: ${res.status} ${text}`);
diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.ts
index b6154780..3601cc11 100644
--- a/src/server/swap-studio.ts
+++ b/src/server/swap-studio.ts
@@ -5,16 +5,18 @@ import { ANCHOR_MODELS, anchorModel, characterLicenceLine, SWAP_LORAS, swapLoraR
import { scalePoints } from "@/lib/catalog/remove-object";
import type { PlanStep } from "@/lib/catalog/shorts";
import {
- approvedMask,
assemblyPieces,
assemblyTakes,
+ clipNeedsPreview,
clipProblem,
currentSegments,
DEFAULT_SETTINGS,
+ defaultMaskBase,
exportDecisions,
freezeTake,
maskPieces,
maskProblem,
+ masterKeep,
newShot,
normalizedSize,
planQueue,
@@ -40,7 +42,7 @@ import {
type TranscriptCue,
} from "@/lib/catalog/swap-studio";
import { applyEdit, EditError, type SwapEdit } from "@/lib/catalog/swap-studio-edit";
-import { frozenTakePlan, planAnchor, planAssembly, planMask, planNormalize, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
+import { cloudMaskCut, frozenTakePlan, planAnchor, planAssembly, planMask, planNormalize, planPreview, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
import { ACCESS_PLACE } from "@/lib/model-access";
import { createPipeline } from "./chains";
@@ -157,7 +159,7 @@ const ACTIVE = new Set(["queued", "running"]);
function projectGenIds(p: SwapProject): string[] {
const ids: (string | undefined)[] = [];
for (const c of p.clips) {
- ids.push(c.normalized?.genId, c.transcript?.genId, c.assembly?.genId, ...(c.assembly?.stepIds ?? []));
+ ids.push(c.normalized?.genId, c.preview?.genId, c.transcript?.genId, c.assembly?.genId, ...(c.assembly?.stepIds ?? []));
for (const s of c.shots) {
for (const m of s.masks) ids.push(m.genId, ...(m.stepIds ?? []), ...m.pieces.map((x) => x.genId));
for (const a of s.anchors) ids.push(a.genId, ...(a.stepIds ?? []));
@@ -205,8 +207,9 @@ function settleShot(project: SwapProject, clip: SwapClip, shot: SwapShot, look:
if (items.some((g) => g.anchors.some((a) => a.genId && !a.url && done(a.genId)))) {
items = items.map((g) => {
const anchors = fill(g.anchors);
- // A segment's first reference that is ready becomes its pick.
- return { ...g, anchors, anchor: g.anchor ?? anchors.find((a) => a.url)?.id ?? null };
+ // A reference that just came out becomes the segment's pick when it has none (the newest of them).
+ const fresh = anchors.filter((a, i) => a.url && !g.anchors[i].url);
+ return { ...g, anchors, anchor: g.anchor ?? fresh.at(-1)?.id ?? null };
});
}
// Finished takes: selected when nothing changed since they were queued (Akatz's attach_take).
@@ -295,7 +298,8 @@ function launchTake(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: S
const prev = before?.takes.find((t) => t.id === dep?.takeId);
const g = look(prev?.genId);
if (!before || !prev || !g) throw new Error("the take it continues from is gone");
- previous = { master: masterOutput(g)?.url, video: mainOutput(g)?.url, frames: before.end - before.start };
+ // Your GPU's master holds the take's last `keep` frames (masterKeep); the cloud's take is the segment's length.
+ previous = { master: masterOutput(g)?.url, video: mainOutput(g)?.url, frames: prev.frozen?.keep ?? before.end - before.start };
}
const plan = frozenTakePlan(project, clip, shot, seg, take, { shot: shotIndex + 1, segment: segIndex + 1, take: seg.takes.findIndex((t) => t.id === take.id) + 1 }, previous);
const pipe = run(plan.steps);
@@ -309,6 +313,7 @@ function settleClip(project: SwapProject, clip: SwapClip, look: Look): SwapClip
return g?.status === "succeeded" ? g : null;
};
if (c.normalized?.genId && !c.normalized.url && ok(c.normalized.genId)) c = { ...c, normalized: { ...c.normalized, url: mainOutput(ok(c.normalized.genId)!)?.url } };
+ if (c.preview?.genId && !c.preview.url && ok(c.preview.genId)) c = { ...c, preview: { ...c.preview, url: mainOutput(ok(c.preview.genId)!)?.url } };
if (c.transcript?.genId && c.transcript.cues === null && ok(c.transcript.genId)) c = { ...c, transcript: { ...c.transcript, cues: cuesOf(ok(c.transcript.genId)!) } };
const shots = c.shots.map((s, i) => settleShot(project, c, s, look, i));
return shots.some((s, i) => s !== c.shots[i]) ? { ...c, shots } : c;
@@ -532,11 +537,15 @@ export const EditSchema = z.discriminatedUnion("type", [
export type EditBody = z.infer<typeof EditSchema>;
-/** Apply one edit from the page (src/lib/catalog/swap-studio-edit.ts), on the project as it is now. */
-export function editProject(projectId: string, body: EditBody): SwapProject {
+/**
+ * Apply one edit from the page (src/lib/catalog/swap-studio-edit.ts), on the project as it is now. Jobs the edit leaves
+ * nothing to point at (a removed clip's or a re-cut shot's masks, anchors, copies and words) are stopped: their
+ * generations are hidden helpers, so nobody could find, stop or use them afterwards.
+ */
+export async function editProject(projectId: string, body: EditBody): Promise<SwapProject> {
const look = lookup();
const active = (gid: string) => ACTIVE.has(look(gid)?.status ?? "");
- const after: { engine: Engine | null } = { engine: null };
+ const after: { engine: Engine | null; orphans: string[] } = { engine: null, orphans: [] };
const next = mutate(projectId, (cur) => {
const p = settle(cur, look);
const edit: SwapEdit = body.type === "anchor-import" ? { ...body, id: uid("anchor-"), at: Date.now() } : (body as SwapEdit);
@@ -551,16 +560,24 @@ export function editProject(projectId: string, body: EditBody): SwapProject {
const t = seg?.takes.find((k) => k.id === edit.takeId);
if (t && look(t.genId)?.status !== "succeeded") throw new ShortsError("Only a finished take can be chosen", 422);
}
+ let out: SwapProject;
try {
- return applyEdit(p, edit, { active });
+ out = applyEdit(p, edit, { active });
} catch (e) {
if (e instanceof EditError) throw new ShortsError(e.message, e.status);
throw e;
}
+ const kept = new Set(projectGenIds(out));
+ after.orphans = projectGenIds(p).filter((g) => !kept.has(g) && active(g));
+ return out;
});
- // Switched to your GPU: the clips need their 24 fps copies.
- if (after.engine !== "open") return next;
- for (const c of next.clips) if (!c.normalized) prepareClipQuietly(next.id, c.id);
+ for (const g of after.orphans) await cancelGeneration(g).catch(() => undefined);
+ if (!after.engine) return next;
+ // Switched engines: on your GPU the clips need their 24 fps copies, on the cloud the page may need browser copies.
+ for (const c of next.clips) {
+ if (after.engine === "open" && !c.normalized) prepareClipQuietly(next.id, c.id);
+ if (after.engine === "cloud" && !c.preview && clipNeedsPreview("cloud", c)) prepareClipQuietly(next.id, c.id);
+ }
return mustProject(projectId);
}
@@ -591,6 +608,8 @@ export const ClipSchema = z.object({
height: z.number().int().positive().max(20_000).optional(),
hasAudio: z.boolean().optional(),
bytes: z.number().int().nonnegative().optional(),
+ /** Whether the browser that added it could play it (it couldn't: the cloud makes a copy for the page). */
+ playable: z.boolean().optional(),
});
/**
@@ -612,8 +631,19 @@ export async function addClip(projectId: string, body: z.infer<typeof ClipSchema
const clip: SwapClip = {
id: uid("clip-"),
name: name.replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, SWAP_STUDIO.maxNameChars) || "Clip",
- source: { url: body.url, name, duration, fps: info.fps ?? body.fps, width: info.width ?? body.width, height: info.height ?? body.height, hasAudio, ...(body.bytes !== undefined ? { bytes: body.bytes } : {}) },
+ source: {
+ url: body.url,
+ name,
+ duration,
+ fps: info.fps ?? body.fps,
+ width: info.width ?? body.width,
+ height: info.height ?? body.height,
+ hasAudio,
+ ...(body.bytes !== undefined ? { bytes: body.bytes } : {}),
+ ...(body.playable !== undefined ? { playable: body.playable } : {}),
+ },
normalized: null,
+ preview: null,
frames,
cuts: [],
detected: null,
@@ -627,22 +657,42 @@ export async function addClip(projectId: string, body: z.infer<typeof ClipSchema
if (before.engine === "open") {
mustMatchMode("open");
clip.normalized = { genId: normalizeJob(clip) };
+ } else if (clipNeedsPreview("cloud", clip)) {
+ // The page can't play it: a browser copy (if it can't be made, the page says so and offers to try again).
+ try {
+ clip.preview = { genId: previewJob(clip) };
+ } catch {
+ clip.preview = null;
+ }
}
return mutate(projectId, (p) => ({ ...p, clips: [...p.clips, clip] }));
}
+function previewJob(clip: SwapClip): string {
+ mustOffer(STUDIO_MODELS.cloud.scale, "cloud");
+ const steps = planPreview(clip);
+ if (!steps) throw new ShortsError("Couldn't read this clip's size to make a copy your browser can play — save it as an MP4 (H.264) and add it again", 422);
+ return run(steps).byKey.preview.id;
+}
+
function normalizeJob(clip: SwapClip): string {
mustOffer(STUDIO_MODELS.open.normalize, "open");
const pipe = run(planNormalize(clip));
return pipe.byKey.normalize.id;
}
-/** Your GPU: make (or make again) a clip's 24 fps copy. */
+/** Your GPU: make (or make again) a clip's 24 fps copy. The cloud: its browser copy, when the page can't play the clip. */
export function prepareClip(projectId: string, clipId: string): SwapProject {
const p = advanceProject(projectId);
- if (p.engine !== "open") throw new ShortsError("The cloud reads the clip as filmed — no 24 fps copy needed", 422);
- mustMatchMode("open");
+ mustMatchMode(p.engine);
const clip = mustClip(p, clipId);
+ if (p.engine === "cloud") {
+ if (!clipNeedsPreview("cloud", clip)) throw new ShortsError("The cloud reads the clip as filmed — no copy needed", 422);
+ const g = getGeneration(clip.preview?.genId ?? "");
+ if (clip.preview?.url || (g && ACTIVE.has(g.status))) throw new ShortsError("The browser copy is ready or on its way", 409);
+ const genId = previewJob(clip);
+ return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, preview: { genId } })));
+ }
const g = getGeneration(clip.normalized?.genId ?? "");
if (clip.normalized?.url || (g && ACTIVE.has(g.status))) throw new ShortsError("The 24 fps copy is ready or on its way", 409);
const genId = normalizeJob(clip);
@@ -708,7 +758,8 @@ export function makeMask(projectId: string, body: z.infer<typeof MaskSchema>): S
const len = shot.end - shot.start;
if (shot.masks.length >= SWAP_STUDIO.maxMaskVersions) throw new ShortsError(`A shot keeps ${SWAP_STUDIO.maxMaskVersions} mask versions — remove one first`, 422);
const finished = (m: MaskVersion) => m.pieces.every((x) => x.url);
- const base = body.base ? (shot.masks.find((m) => m.id === body.base) ?? null) : (approvedMask(shot) ?? [...shot.masks].reverse().find(finished) ?? null);
+ // The version it corrects: the one named, else this engine's approved or newest (never the other engine's).
+ const base = body.base ? (shot.masks.find((m) => m.id === body.base) ?? null) : defaultMaskBase(shot, p.engine);
if (base && !finished(base)) throw new ShortsError("That mask version is still being made — wait for it", 409);
const size = workingSize(p, clip);
const points: PixelPoint[] = body.points.length && body.size && size ? scalePoints(body.points, body.size, size) : body.points;
@@ -718,7 +769,7 @@ export function makeMask(projectId: string, body: z.infer<typeof MaskSchema>): S
mustOffer(STUDIO_MODELS[p.engine].mask, p.engine);
const pipe = run(planMask({ engine: p.engine, clip, shot, kind: body.kind, frame: body.frame, points, who: shot.who, base }));
const genId = pipe.byKey.mask.id;
- const pieces = maskPieces(p.engine, body.kind, body.frame, len, base);
+ const pieces = maskPieces(p.engine, body.kind, body.frame, len, base, p.engine === "cloud" ? cloudMaskCut(clip, shot, body.kind, body.frame).offset : 0);
pieces[pieces.length - 1] = { ...pieces[pieces.length - 1], genId };
const version: MaskVersion = {
id: uid("mask-"),
@@ -810,10 +861,14 @@ function takeSteps(p: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegm
return frozenTakePlan(p, clip, shot, seg, take, numbers, previous);
}
-/** A new take of a segment as it reads now (waiting until the takes it continues from are made). */
-function newTake(p: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, deps: SwapTake["dependencies"], lora: SwapShot["settings"]["lora"]): SwapTake {
+/**
+ * A new take of a segment as it reads now (waiting until the takes it continues from are made). `keep`: your GPU's
+ * master keeps the take's last frames for the segment after it (masterKeep).
+ */
+function newTake(p: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, deps: SwapTake["dependencies"], lora: SwapShot["settings"]["lora"], keep?: number): SwapTake {
const frozen = freezeTake(p, shot, seg);
frozen.settings = { ...frozen.settings, lora };
+ if (p.engine === "open" && keep !== undefined) frozen.keep = keep;
return {
id: uid("take-"),
createdAt: Date.now(),
@@ -865,7 +920,7 @@ export function queueTakes(projectId: string, body: z.infer<typeof QueueSchema>)
if (seg.takes.length >= SWAP_STUDIO.maxTakes) throw new ShortsError(`Segment ${e.index + 1} keeps ${SWAP_STUDIO.maxTakes} takes — remove one first`, 422);
// Takes it continues from in this queue are named by their new ids (they become the selection when made).
const deps = e.dependencies.map((d) => ({ ...d, takeId: made.get(d.segmentId)?.id ?? d.takeId }));
- const take = newTake(cur, clip, shot, seg, deps, lora);
+ const take = newTake(cur, clip, shot, seg, deps, lora, masterKeep(items, e.index, shot.settings));
made.set(seg.id, take);
}
// Every take's steps checked now (models switched off, demo and real mixed, a request a route refuses).
@@ -1052,9 +1107,10 @@ export function estimateProject(projectId: string): StudioEstimate {
let shotCost: number | null = 0;
let count = 0;
for (const [gi, seg] of items.entries()) {
- const take = newTake(stand, working, shot, seg, [], lora);
+ const take = newTake(stand, working, shot, seg, [], lora, masterKeep(items, gi, shot.settings));
// A stand-in anchor where one is still to be made: the price doesn't depend on which picture it is.
- if (seg.anchorMode !== "none" && !take.frozen!.anchor) take.frozen!.anchor = "/api/files/placeholder-anchor.png";
+ const wantsAnchor = seg.anchorMode === "custom" || (seg.anchorMode === "shot" && shot.settings.useAnchor);
+ if (wantsAnchor && !take.frozen!.anchor) take.frozen!.anchor = "/api/files/placeholder-anchor.png";
let r: ReturnType<typeof price>;
try {
r = price(takeSteps(stand, working, shot, seg, take, { shot: si + 1, segment: gi + 1, take: seg.takes.length + 1 }).steps);
@@ -1124,14 +1180,14 @@ export function studioNotes(engine: Engine): string[] {
return [
WORKERS_NOTE,
"Needs H3 Relay 2.0's nodes on your ComfyUI (scripts/comfy/install-comfyui.sh with H3_RELAY=1) and a 24 GB GPU with offloading; the masks need SAM 3.1",
- "Each segment is one H3 Relay pass with the approved mask, its anchor and the previous take's lossless (FFV1) master as continuation history",
+ "Each segment is one H3 Relay pass with the approved mask, its anchor and the previous take's last frames as continuation history (a lossless 16-bit FFV1 master, about 3 MB a frame at 1 MP: ComfyUI takes uploads up to 100 MB unless started with a higher --max-upload-size, so keep history to about 30 frames or raise it)",
characterLicenceLine("open", STUDIO_MODELS.open.swap),
];
}
return [
"On fal, H3 has no mask: who to swap is said in words, and the whole frame is regenerated around them",
"fal's H3 reads 2–15 s of the clip a call and bills whole seconds (5–15 s): a segment runs 2–15 s",
- "A continuing segment starts from the previous take's last frame — fal's H3 takes no continuation history",
+ "A continuing segment starts from the previous take's last frame — fal's H3 takes no continuation history. H3 makes whole seconds (at least 5), so each take is trimmed back to its segment",
"SAM 3.1 on fal marks the person from your clicks or words, for review; the swap itself doesn't read the mask",
characterLicenceLine("cloud", STUDIO_MODELS.cloud.swap),
];
diff --git a/tests/comfy-swap-studio.test.ts b/tests/comfy-swap-studio.test.ts
index f6b673e0..496a47e0 100644
--- a/tests/comfy-swap-studio.test.ts
+++ b/tests/comfy-swap-studio.test.ts
@@ -23,8 +23,9 @@ const entry = (id: string) => manifest.workflows.find((w) => w.id === id)!;
const file = (id: string) => JSON.parse(fs.readFileSync(path.join(dir, `${id}.json`), "utf8")) as ComfyWorkflow;
const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 20, videoDuration: 20, width: 1920, height: 1080, fps: 24, frames: 480 };
-const prepare = (id: string, input: Partial<GenInput>, op: Operation) =>
- prepareWorkflow(id, { video: "clip.mp4", ...input } as GenInput, { generationId: "g1", op, upload: async (_d, _t, name) => `up_${name}`, media: (n) => (n === "clip.mp4" ? clip : undefined) });
+const GB = 2 ** 30;
+const prepare = (id: string, input: Partial<GenInput>, op: Operation, ram = 64 * GB) =>
+ prepareWorkflow(id, { video: "clip.mp4", ...input } as GenInput, { generationId: "g1", op, upload: async (_d, _t, name) => `up_${name}`, media: (n) => (n === "clip.mp4" ? clip : undefined), serverRam: async () => ram });
const at = (wf: ComfyWorkflow, node: string, input: string) => wf[node]?.inputs[input];
const SEG = STUDIO_WORKFLOWS.segment;
const MASK = STUDIO_WORKFLOWS.mask;
@@ -110,6 +111,20 @@ describe("a segment through the provider", () => {
await expect(prepare(SEG, { ...base, extra: { historyVideo: "up_master.mkv", historyStart: -1, historyLength: 18 } }, "video-swap")).rejects.toThrow(/frame count/);
});
+ it("saves only the take's last frames as its lossless master (what the next segment reads)", async () => {
+ const { workflow: wf } = await prepare(SEG, { ...base, extra: { masterKeep: 18, segmentFrames: 120 } }, "video-swap");
+ expect(wf.master_tail).toMatchObject({ class_type: "ImageFromBatch", inputs: { image: ["finish", 0], batch_index: 102, length: 18 } });
+ expect(at(wf, "save_master", "images")).toEqual(["master_tail", 0]);
+ expect(at(wf, "save_master", "format")).toBe("video/ffv1-mkv");
+ // The take itself is the whole segment.
+ expect(at(wf, "video", "images")).toEqual(["finish", 0]);
+ for (const k of ["masterKeep", "segmentFrames"]) expect(JSON.stringify(wf)).not.toContain(k);
+ // Keeping every frame (or not saying): the master is the whole segment, as before.
+ const all = await prepare(SEG, { ...base, extra: { masterKeep: 120, segmentFrames: 120 } }, "video-swap");
+ expect(all.workflow.master_tail).toBeUndefined();
+ expect(at(all.workflow, "save_master", "images")).toEqual(["finish", 0]);
+ });
+
it("the approved mask replaces SAM's chain, trimmed like the segment", async () => {
const { workflow: wf } = await prepare(SEG, { ...base, startTime: 105.5 / 24, endTime: (105.5 + 141.25) / 24, extra: { maskVideo: "up_mask.mp4", maskStart: 105.5 / 24 } }, "video-swap");
expect(at(wf, "mask_source", "file")).toBe("up_mask.mp4");
@@ -184,4 +199,12 @@ describe("a mask through the provider", () => {
expect(blank.workflow.prev_source).toBeUndefined();
await expect(prepare(MASK, { ...base, extra: { keyFrame: 200, spanFrames: 100, shotFrames: 240 } }, "bg-remove-video")).rejects.toThrow(/don't fit in the shot/);
});
+
+ it("refuses a shot the server can't hold in memory, before it runs", async () => {
+ // Correcting a 10 s 1080p shot at 768p holds about 18 GB of frames: a 16 GB server spares 8.
+ await expect(prepare(MASK, { ...base, points: [{ x: 9, y: 9 }], extra: { keyFrame: 30, spanFrames: 1, shotFrames: 240, prevMask: "up_prev.mp4" } }, "bg-remove-video", 16 * GB)).rejects.toThrow(/holds the whole shot in memory.*can spare 8 GB/);
+ // At 0.5 MP it fits.
+ const small = await prepare(MASK, { ...base, resolution: "480p", points: [{ x: 9, y: 9 }], extra: { keyFrame: 30, spanFrames: 1, shotFrames: 240, prevMask: "up_prev.mp4" } }, "bg-remove-video", 16 * GB);
+ expect(at(small.workflow, "prepare", "resolution")).toBe("480");
+ });
});
diff --git a/tests/e2e/character-swap-studio.mjs b/tests/e2e/character-swap-studio.mjs
index 877cec5c..ad1a5d07 100644
--- a/tests/e2e/character-swap-studio.mjs
+++ b/tests/e2e/character-swap-studio.mjs
@@ -3,8 +3,8 @@
// click on a frame and Track shot, a mask and a scene anchor approved, two segments (the second continuing from the
// first, waiting for it), takes made, compared and reviewed, Export decisions, the assembly with a download, and the
// Finish stage shown as not available. Then every stage at 1440 and 390 px, light and dark, without sideways scroll;
-// a project on your GPU shows its 24 fps copy; the sidebar and Genjutsu's Character swap link here; an unknown project
-// is a 404.
+// a project on your GPU shows its 24 fps copy; an AVI on the cloud gets a copy the browser can play; the sidebar links
+// here and Genjutsu's Character swap opens its clip and character in a new project; an unknown project is a 404.
// Usage: node tests/e2e/character-swap-studio.mjs [appUrl] [--shots <dir>] (app in demo mode, ComfyUI unreachable).
// Exits 1 on a failed check.
import { execFileSync } from "node:child_process";
@@ -37,7 +37,7 @@ const STAGES = ["Shots", "Words", "Who to swap", "Scene anchors", "Segments", "T
// A rerun starts clean: earlier runs' projects go.
for (const p of (await (await fetch(`${app}/api/swap-studio/projects`)).json()).items ?? []) {
- if (p.name === "Rain scene" || p.name === "GPU check") await fetch(`${app}/api/swap-studio/projects/${p.id}`, { method: "DELETE" });
+ if (["Rain scene", "GPU check", "AVI check", "walk-handoff"].includes(p.name)) await fetch(`${app}/api/swap-studio/projects/${p.id}`, { method: "DELETE" });
}
const browser = await launch();
@@ -85,14 +85,16 @@ try {
check("Detect edits finds the cut at 4 s (frame 96)", /Detected 1 edit at frames 96 /.test(found), found.match(/Detected[^\n]*|No edits[^\n]*/)?.[0] ?? "");
if (/Detected 1 edit at frames 96 /.test(found)) await page.getByRole("button", { name: "Use them" }).click();
else {
- // Placed by hand at the playhead instead.
- await page.evaluate(() => {
- const v = document.querySelector("video");
- v.currentTime = 4.02;
- });
- await page.waitForFunction(() => /Frame 96 /.test(document.body.innerText), null, { timeout: 15_000 });
+ // Placed by hand at the playhead instead (typed: the timeline is for the mouse).
+ await page.getByLabel("Playhead frame").fill("96");
+ await page.getByLabel("Playhead frame").press("Enter");
await page.getByRole("button", { name: "Cut at the playhead" }).click();
}
+ // The playhead by keyboard: typed frame number.
+ await page.getByLabel("Playhead frame").fill("30");
+ await page.getByLabel("Playhead frame").press("Enter");
+ await page.waitForFunction(() => Math.abs(document.querySelector("video").currentTime - 30.5 / 24) < 0.01, null, { timeout: 10_000 });
+ check("the playhead moves to a typed frame", true);
await page.getByRole("radiogroup", { name: "Shot 2" }).getByRole("radio", { name: /Keep original/ }).click();
await page.getByRole("button", { name: "Save shots" }).click();
await page.getByRole("button", { name: "Saved" }).waitFor();
@@ -121,8 +123,16 @@ try {
await approveMask.waitFor();
await page.waitForFunction(() => [...document.querySelectorAll("button")].some((b) => b.textContent?.trim() === "Approve" && !b.disabled), null, { timeout: 60_000 });
await approveMask.click();
- await page.getByRole("button", { name: "Approved" }).waitFor();
- check("mask version made and approved", true);
+ await page.getByRole("button", { name: "Unapprove" }).waitFor();
+ check("mask version made and approved (and can be unapproved)", true);
+ // The shot strip is one tab stop; the arrow keys pick shots.
+ const radios = page.getByRole("radiogroup", { name: "Shot", exact: true }).getByRole("radio");
+ check("shot strip: one tab stop", (await radios.evaluateAll((els) => els.filter((e) => e.tabIndex === 0).length)) === 1);
+ await radios.first().focus();
+ await page.keyboard.press("ArrowRight");
+ check("shot strip: ArrowRight picks shot 2", (await radios.nth(1).getAttribute("aria-checked")) === "true" && (await page.evaluate(() => document.activeElement?.textContent ?? "")).startsWith("Shot 2"));
+ await page.keyboard.press("ArrowLeft");
+ await page.getByRole("button", { name: "Unapprove" }).waitFor();
await shot("03-who");
// Scene anchor: make, approve.
@@ -154,8 +164,21 @@ try {
await page.getByRole("radiogroup", { name: "Take 1 decision" }).first().getByRole("radio", { name: "Keep" }).click();
await page.getByRole("radiogroup", { name: "Clip decision" }).getByRole("radio", { name: "Keep" }).click();
await page.getByRole("button", { name: "Unfavourite" }).first().waitFor();
- const exported = await page.evaluate(async (u) => (await fetch(u)).json(), `${new URL(projectUrl).pathname.replace("/character-swap/", "/api/swap-studio/projects/")}/decisions`);
- check("Export decisions: the clip's review and the take's", exported.clips?.[0]?.review === "keep" && exported.clips[0].shots[0].segments[0].takes[0].favourite === true);
+ // The edits save as they're made: read the export once they have.
+ const decisionsUrl = `${new URL(projectUrl).pathname.replace("/character-swap/", "/api/swap-studio/projects/")}/decisions`;
+ const exported = await page
+ .waitForFunction(
+ async (u) => {
+ const d = await (await fetch(u)).json();
+ return d.clips?.[0]?.review === "keep" && d.clips[0].shots[0].segments[0].takes[0].favourite === true && d.clips[0].shots[0].segments[0].takes[0].decision === "keep" ? d : false;
+ },
+ decisionsUrl,
+ { timeout: 15_000, polling: 500 },
+ )
+ .then((h) => h.jsonValue())
+ .catch(() => null);
+ const last = exported ?? (await page.evaluate(async (u) => (await fetch(u)).json(), decisionsUrl));
+ check("Export decisions: the clip's review and the take's", !!exported, exported ? "" : JSON.stringify(last.clips?.[0]?.shots?.[0]?.segments?.map((g) => g.takes.map((t) => [t.favourite, t.decision]))) + ` review=${last.clips?.[0]?.review}`);
await shot("06-review");
// Assemble; the Finish stage is not available.
@@ -216,6 +239,42 @@ try {
await page.goto(`${app}/genjutsu?mode=character`, { waitUntil: "load" });
await page.getByRole("link", { name: /Open in Character Swap Studio/ }).waitFor({ timeout: 90_000 });
check("Genjutsu's Character swap links the studio", true);
+
+ // From Genjutsu with a clip and a character: a new project with both.
+ const upload = async (file, type, name) => {
+ const f = new FormData();
+ f.append("file", new Blob([fs.readFileSync(file)], { type }), name);
+ return (await (await fetch(`${app}/api/uploads`, { method: "POST", body: f })).json()).url;
+ };
+ const gClip = await upload(clipFile, "video/webm", "walk-handoff.webm");
+ const gHero = await upload(heroFile, "image/png", "hero.png");
+ await page.goto(`${app}/genjutsu?mode=character&video=${encodeURIComponent(gClip)}&image=${encodeURIComponent(gHero)}`, { waitUntil: "load" });
+ const open = page.getByRole("button", { name: /Open in Character Swap Studio/ });
+ await open.waitFor({ timeout: 90_000 });
+ await page.waitForFunction(() => ![...document.querySelectorAll("button")].find((b) => /Open in Character Swap Studio/.test(b.textContent ?? ""))?.disabled, null, { timeout: 30_000 });
+ await open.click();
+ await page.waitForURL(/\/character-swap\/swap-/, { timeout: 60_000 });
+ await page.getByText("Clips · 1").waitFor({ timeout: 60_000 });
+ const handedId = page.url().split("/").pop();
+ const handed = await (await fetch(`${app}/api/swap-studio/projects/${handedId}`)).json();
+ // Named after the clip (Genjutsu's name for an adopted upload is its stored file name).
+ check(
+ "Genjutsu hands the clip and character to a new studio project",
+ handed.project.clips.length === 1 && handed.project.clips[0].source.url === gClip && handed.project.character.image === gHero && handed.project.name === handed.project.clips[0].name,
+ `${handed.project.name} · ${handed.project.clips.length} clip`,
+ );
+ await fetch(`${app}/api/swap-studio/projects/${handedId}`, { method: "DELETE" });
+
+ // An AVI on the cloud: the browser can't play it, so the page gets an H.264 copy (a sample clip in demo mode).
+ const avi = path.join(path.dirname(clipFile), "walk.avi");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", walk, "-c:v", "mjpeg", "-q:v", "5", "-c:a", "pcm_s16le", avi]);
+ const aviProject = await (await fetch(`${app}/api/swap-studio/projects`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "AVI check", engine: "cloud" }) })).json();
+ await page.goto(`${app}/character-swap/${aviProject.id}`, { waitUntil: "load" });
+ await page.locator('input[type="file"][accept^="video/"]').setInputFiles(avi);
+ await page.getByRole("button", { name: /^walk/ }).waitFor({ timeout: 90_000 });
+ await page.getByText(/Your browser can.t play this clip \(AVI\)/).waitFor({ timeout: 30_000 });
+ const aviView = await (await fetch(`${app}/api/swap-studio/projects/${aviProject.id}`)).json();
+ check("an AVI on the cloud gets a browser copy (fal scale-video)", !!aviView.project.clips[0].preview?.genId && aviView.project.clips[0].source.playable === false);
const missing = await fetch(`${app}/character-swap/swap-nothing-here`);
check("an unknown project is a 404", missing.status === 404, String(missing.status));
await context.close();
diff --git a/tests/swap-studio-api.test.ts b/tests/swap-studio-api.test.ts
index 79bc0f54..8d2e7e91 100644
--- a/tests/swap-studio-api.test.ts
+++ b/tests/swap-studio-api.test.ts
@@ -188,17 +188,23 @@ describe("Character Swap Studio: the cloud, as a demo", () => {
});
const after = v.project.clips[0].shots[0].segments!;
expect(after.map((g) => g.selectedTake)).toEqual([t1.id, t2.id]);
- // The second take: cut, the first take's last frame, then H3 with the swap LoRA and both pictures.
+ // The second take: cut, the first take's last frame, H3 with the swap LoRA and both pictures, cut back to 2 s.
const take2 = after[1].takes[0];
const steps = take2.stepIds!.map((s) => gens.getGeneration(s)!);
- expect(steps.map((g) => g.modelId)).toEqual(["trim-video", "extract-frame", "fuobe-character-swap"]);
- expect(steps[1].request.inputs?.video).toBe(v.gens[after[0].takes[0].genId!].url);
+ expect(steps.map((g) => g.modelId)).toEqual(["trim-video", "extract-frame", "fuobe-character-swap", "trim-video"]);
+ // The boundary is the last frame of the first take as trimmed to its segment (H3 made 5 s for 2 s).
+ const take1 = gens.getGeneration(after[0].takes[0].genId!)!;
+ expect(take1).toMatchObject({ modelId: "trim-video", request: { params: { startTime: 0, endTime: 2 } } });
+ expect(steps[1].request.inputs?.video).toBe(v.gens[take1.id].url);
expect(steps[1].request.params?.extra).toEqual({ frame_type: "last" });
const swap = steps[2].request;
expect(swap.loras?.[0]?.file).toMatch(/swap/i);
expect(swap.params).toMatchObject({ duration: 5, sourceDuration: 2 });
+ expect(steps[3].request.params).toMatchObject({ startTime: 0, endTime: 2 });
+ expect(take2.genId).toBe(steps[3].id);
// The anchor is Image 2 on the first segment; after the boundary the boundary frame is Image 2, the anchor Image 3.
- expect(gens.getGeneration(after[0].takes[0].genId!)!.request.prompt).toMatch(/Image 2 is the exact first-frame scene/);
+ const swap1 = after[0].takes[0].stepIds!.map((s) => gens.getGeneration(s)!).find((g) => g.modelId === "fuobe-character-swap")!;
+ expect(swap1.request.prompt).toMatch(/Image 2 is the exact first-frame scene/);
expect(swap.prompt).toMatch(/Image 2 is the generated boundary/);
});
@@ -221,16 +227,37 @@ describe("Character Swap Studio: the cloud, as a demo", () => {
await expect(post(assemble, id, { clipId: c.id })).rejects.toThrow(/being assembled/);
const v = await until(id, (x) => statusOf(x, x.project.clips[0].assembly?.genId) === "succeeded");
const steps = asm.stepIds.map((s: string) => gens.getGeneration(s)!);
- // Two takes and the kept shot cut to their frames, joined, the clip's sound put back.
- expect(steps.map((g: { modelId: string }) => g.modelId)).toEqual(["trim-video", "trim-video", "trim-video", "join-clips", "merge-audio-video"]);
+ // The two takes (already their segments' length) and the kept shot cut to its frames, all scaled to one frame
+ // (the 72×128 clip's shape, 512 px on its short side for merge-videos), joined at 24 fps, the clip's sound put back.
+ expect(steps.map((g: { modelId: string }) => g.modelId)).toEqual(["scale-video", "scale-video", "trim-video", "scale-video", "join-clips", "merge-audio-video"]);
const final = gens.getGeneration(asm.genId)!;
expect(final).toMatchObject({ feature: "swap-studio", op: "mux" });
expect(final.request.inputs?.audio).toBe(clip);
expect(steps[2].request.params).toMatchObject({ startTime: 4, endTime: 12 });
+ expect(steps[0].request.params).toMatchObject({ extra: { width: 512, height: 910 } });
+ expect(steps[4].request.params).toMatchObject({ extra: { target_fps: 24 } });
expect(v.gens[asm.genId].url).toBeTruthy();
// The step generations stay out of the Library; the assembled clip is in it.
expect(gens.listGenerations({ feature: "swap-studio" }).map((g) => g.id)).toContain(asm.genId);
});
+
+ it("a clip the browser can't play gets a copy for the page; removing a clip stops the jobs it started", async () => {
+ let p: SwapProject = await post(clips, id, { url: clip, name: "night.mp4", playable: false });
+ const c = p.clips[1];
+ const copy = gens.getGeneration(c.preview!.genId!)!;
+ expect(copy).toMatchObject({ modelId: "scale-video", op: "reframe", feature: "swap-studio-step", request: { inputs: { video: clip }, params: { extra: { width: 72, height: 128 } } } });
+ const v = await until(id, (x) => !!x.project.clips[1].preview?.url);
+ expect(v.project.clips[1].preview!.url).toBe(v.gens[copy.id].url);
+ // The jobs still read the clip as filmed.
+ p = await post(masks, id, { clipId: c.id, shotId: c.shots[0].id, kind: "track", frame: 0, points: [] });
+ const m = p.clips[1].shots[0].masks[0];
+ expect(gens.getGeneration(m.stepIds![0])!.request.inputs?.video).toBe(clip);
+ // Removed while its mask is still being made: the mask's generations are stopped (nothing would show them).
+ expect([...m.stepIds!, m.genId].map((g) => gens.getGeneration(g!)!.status)).not.toContain("succeeded");
+ await patch(id, { type: "remove-clip", clipId: c.id });
+ for (const g of [...m.stepIds!, m.genId!]) expect(gens.getGeneration(g)!.status).toBe("canceled");
+ expect((await view(id)).project.clips).toHaveLength(1);
+ });
});
describe("Character Swap Studio: your GPU, as a demo", () => {
@@ -265,8 +292,10 @@ describe("Character Swap Studio: your GPU, as a demo", () => {
expect(first).toMatchObject({ modelId: "oss-h3-swap-segment", op: "video-swap", feature: "swap-studio-step" });
expect(first.request.inputs?.video).toBe(v.project.clips[0].normalized!.url);
expect(first.request.params?.extra).not.toHaveProperty("historyVideo");
- // Segment 2 reads 18 frames of history from take 1's master (144 frames long).
- expect(second.request.params?.extra).toMatchObject({ historyVideo: v.gens[first.id].master, historyStart: 126, historyLength: 18 });
+ // Take 1's master keeps its last 18 frames of 144 (what segment 2 reads), and segment 2 reads all of them.
+ expect(first.request.params?.extra).toMatchObject({ masterKeep: 18, segmentFrames: 144 });
+ expect(after[0].takes[0].frozen?.keep).toBe(18);
+ expect(second.request.params?.extra).toMatchObject({ historyVideo: v.gens[first.id].master, historyStart: 0, historyLength: 18 });
expect(v.gens[first.id].master).toBeTruthy();
expect(after.map((g) => g.selectedTake)).toEqual([t1.id, t2.id]);
diff --git a/tests/swap-studio-edit.test.ts b/tests/swap-studio-edit.test.ts
index 7c53e7b6..3cc38194 100644
--- a/tests/swap-studio-edit.test.ts
+++ b/tests/swap-studio-edit.test.ts
@@ -81,6 +81,18 @@ describe("project edits", () => {
expect(shotOf(after).anchors).toHaveLength(1);
});
+ it("a new character picture also un-picks the segments' own references (made or imported with the old one)", () => {
+ const base = shotOf(projectOf());
+ const segs = currentSegments(base).map((g, i) => (i ? g : { ...g, anchorMode: "custom" as const, anchors: [{ id: "r1", createdAt: 1, source: "generated" as const, url: "/api/files/r1.png" }], anchor: "r1" }));
+ const p = projectOf([clipOf({ shots: [{ ...base, segments: segs }] })]);
+ expect(shotOf(edit(p, { type: "character", description: "someone else" })).segments![0].anchor).toBe("r1");
+ const after = shotOf(edit(p, { type: "character", image: "/api/files/uploads/x/other.png" }));
+ expect(after.segments![0]).toMatchObject({ anchor: null, anchors: [{ id: "r1" }] });
+ // Queueing it now asks for a reference made with the new picture.
+ const q = planQueue({ ...p, character: { ...p.character, image: "/api/files/uploads/x/other.png" } }, p.clips[0], after, after.segments![0].id, "segment", { active: () => false });
+ expect("problem" in q && q.problem).toMatch(/pick its reference image/);
+ });
+
it("detected edits are kept apart until confirmed; confirmed cuts make shots, with Replace or Keep for each", () => {
let p = edit(projectOf(), { type: "detected", clipId: "clip-1", cuts: [120, 0, 600, 120, 300] });
expect(p.clips[0].detected).toEqual([120, 300]);
@@ -131,6 +143,10 @@ describe("project edits", () => {
expect(shotOf(edit(approved, { type: "remove-anchor", clipId: "clip-1", shotId: s.id, anchorId: "a1" })).approvedAnchor).toBeNull();
// A mask still being made can't be removed.
expect(refused(() => edit(p, { type: "remove-mask", clipId: "clip-1", shotId: s.id, maskId: "m1" }, (id) => id === "g-m1")).message).toMatch(/still being made/);
+ // A mask made on the other engine can't be approved here; an approval can be taken back.
+ const cloud = { ...made, engine: "cloud" as const };
+ expect(refused(() => edit(cloud, { type: "shot", clipId: "clip-1", shotId: s.id, patch: { approvedMask: "m1" } })).message).toMatch(/other engine/);
+ expect(shotOf(edit(approved, { type: "shot", clipId: "clip-1", shotId: s.id, patch: { approvedMask: null } })).approvedMask).toBeNull();
});
it("Build shot prompts writes each swapped shot's prompt from its speaker and words", () => {
@@ -255,12 +271,13 @@ describe("queued takes", () => {
});
describe("cloud mask updates", () => {
- it("Update frame cuts half a second from the frame (within the shot); its piece is that one frame", () => {
+ it("Update frame cuts half a second from the frame (past the shot's end if need be); its piece is that one frame", () => {
const p = projectOf([clipOf()], "cloud");
const shot = { ...shotOf(p), start: 24, end: 120 };
const [cut, mask] = planMask({ engine: "cloud", clip: p.clips[0], shot, kind: "frame", frame: 90, points: [{ x: 5, y: 5 }], who: shot.who, base: null });
- expect(cut.request.params).toEqual({ startTime: 114 / 24, endTime: 120 / 24 });
- expect(mask.request.params).toMatchObject({ duration: 6 / 24, points: [{ x: 5, y: 5 }] });
+ // Frame 114 of the clip, six frames before the shot ends: still half a second of clip to trim and track.
+ expect(cut.request.params).toEqual({ startTime: 114 / 24, endTime: 126 / 24 });
+ expect(mask.request.params).toMatchObject({ duration: 12 / 24, points: [{ x: 5, y: 5 }] });
const [mid] = planMask({ engine: "cloud", clip: p.clips[0], shot, kind: "frame", frame: 10, points: [{ x: 5, y: 5 }], who: shot.who, base: null });
expect(mid.request.params).toEqual({ startTime: 34 / 24, endTime: 46 / 24 });
});
diff --git a/tests/swap-studio.test.ts b/tests/swap-studio.test.ts
index 43c43380..756045b8 100644
--- a/tests/swap-studio.test.ts
+++ b/tests/swap-studio.test.ts
@@ -1,27 +1,36 @@
import { describe, expect, it } from "vitest";
-import { coarseTimes, coarseWindows, mafd, sceneCuts, sceneScores, studioFrames, timeFrame, windowCuts, windowFrames } from "@/lib/av/scene-cuts";
+import { coarseTimes, coarseWindows, fineWidth, FINE_MAX_WIDTH, mafd, sceneCuts, sceneScores, studioFrames, timeFrame, windowChunks, windowCuts, windowFrames } from "@/lib/av/scene-cuts";
+import { pointsValue } from "@/lib/catalog/payload";
import {
addCut,
applyLayout,
+ approvedMask,
assemblyPieces,
assemblyTakes,
autoSelect,
buildSegmentPrompt,
+ clipNeedsPreview,
clipProblem,
+ cloudFilmSize,
cueWords,
currentSegments,
DEFAULT_SETTINGS,
+ defaultMaskBase,
dependencies,
digest,
enginePrompt,
exportDecisions,
+ freezeTake,
+ maskMemoryProblem,
maskPieceAt,
maskPieces,
maskProblem,
+ masterKeep,
moveCut,
newSegment,
newShot,
normalizedSize,
+ pageClip,
planQueue,
predecessors,
referenceContext,
@@ -39,6 +48,7 @@ import {
shotSpeaker,
speakerIn,
stableJson,
+ studioHandOff,
updateTake,
voicesOf,
windowRanges,
@@ -50,7 +60,7 @@ import {
type SwapShot,
type SwapTake,
} from "@/lib/catalog/swap-studio";
-import { cloudCallSeconds, maskPointsPayload, planAnchor, planAssembly, planMask, planNormalize, planSegmentTake, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
+import { cloudCallSeconds, cloudMaskCut, frozenTakePlan, maskPointsPayload, planAnchor, planAssembly, planMask, planNormalize, planPreview, planSegmentTake, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
// ---------------------------------------------------------------------------
// Fixtures
@@ -604,8 +614,12 @@ describe("engine steps", () => {
const project = projectOf([clip], "cloud");
const shot = shotOf(0, 300, { who: { selection: "rightmost", index: 0, words: "person" } });
const items = currentSegments(shot);
- const { steps } = planSegmentTake({ engine: "cloud", project, clip, shot, seg: items[1], shotNumber: 1, segNumber: 2, takeNumber: 3, prompt: "Replace only the selected person in <Video 1>. <Picture 2> is the generated boundary. <Picture 3> is a reference.", history: 18, anchor: "/api/files/a.png", previous: { video: "/api/files/prev.mp4", frames: 124 } });
- expect(steps.map((s) => s.key)).toEqual(["cut", "boundary", "swap"]);
+ const { steps, final } = planSegmentTake({ engine: "cloud", project, clip, shot, seg: items[1], shotNumber: 1, segNumber: 2, takeNumber: 3, prompt: "Replace only the selected person in <Video 1>. <Picture 2> is the generated boundary. <Picture 3> is a reference.", history: 18, anchor: "/api/files/a.png", previous: { video: "/api/files/prev.mp4", frames: 124 } });
+ expect(steps.map((s) => s.key)).toEqual(["cut", "boundary", "swap", "fit"]);
+ // H3 makes whole seconds (6 s for these 123 frames): the take is cut back to the segment, so the next segment's
+ // boundary is this one's real last frame and the take lines up with the clip's sound.
+ expect(final).toBe("fit");
+ expect(steps[3]).toMatchObject({ request: { modelId: "trim-video", params: { startTime: 0, endTime: 123 / 24 } }, after: ["swap"], chain: [{ slot: "video" }] });
expect(steps[0].request.params).toEqual({ startTime: 124 / 24, endTime: 247 / 24 });
expect(steps[1].request).toMatchObject({ modelId: "extract-frame", inputs: { video: "/api/files/prev.mp4" }, params: { extra: { frame_type: "last" } } });
const swap = steps[2];
@@ -641,8 +655,9 @@ describe("assembly", () => {
["source", 400, 480],
]);
expect(assemblyTakes(pieces).length).toBe(2);
+ expect("stale" in r && r.stale).toEqual([]);
const missing = assemblyPieces(project, { ...assembled, shots: [shots[0], shotOf(100, 480)] });
- expect("problem" in missing && missing.problem).toMatch(/Shot 2, segment 1 has no current take/);
+ expect("problem" in missing && missing.problem).toMatch(/Shot 2, segment 1 has no chosen take/);
expect(assemblyPieces(project, { ...assembled, shots: [shots[0]] })).toEqual({ problem: expect.stringMatching(/No shot replaces/) });
});
@@ -671,10 +686,11 @@ describe("assembly", () => {
expect(steps.filter((s) => s.request.modelId === "join-clips").map((s) => s.after?.length)).toEqual([24, 6, 2]);
const mux = steps.find((s) => s.key === "final")!;
expect(mux.request.inputs?.audio).toMatch(/^silence:|20/);
- // One piece with sound: no join, the cut goes straight to the mux.
+ expect(steps.find((s) => s.key === "join")!.request.params?.extra).toEqual({ target_fps: 24 });
+ // One piece with sound: no join, the cut (scaled to the film's frame) goes straight to the mux.
const one = planAssembly({ engine: "cloud", clip, pieces: [{ kind: "source", start: 0, end: 480 }], videoOf: () => "" });
- expect(one.steps.map((s) => s.key)).toEqual(["piece0", "final"]);
- expect(one.steps[1].after).toEqual(["piece0"]);
+ expect(one.steps.map((s) => s.key)).toEqual(["piece0-cut", "piece0", "final"]);
+ expect(one.steps[2].after).toEqual(["piece0"]);
});
it("ends on the join for a silent clip on your GPU", () => {
@@ -692,3 +708,237 @@ describe("signatures", () => {
expect(digest({ a: 1 })).not.toBe(digest({ a: 2 }));
});
});
+
+// ---------------------------------------------------------------------------
+// Review fixes: continuation on both engines, stale takes, engine-bound masks, anchors off, the cloud's browser copy
+
+describe("continuing a segment", () => {
+ it("your GPU's master keeps only the frames the next segment reads", () => {
+ const shot = shotOf(0, 480, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } });
+ const items = currentSegments(shot);
+ // The default layout continues with 18 frames of history: each master keeps 18 frames, not the whole segment.
+ expect(items.map((_, i) => masterKeep(items, i, shot.settings))).toEqual([18, 18, 18, 18]);
+ const longer = items.map((g, i) => (i === 2 ? { ...g, history: 52 } : g));
+ expect(masterKeep(longer, 1, shot.settings)).toBe(52);
+ // Never more than the segment, at least one frame.
+ expect(masterKeep([{ ...items[0], end: 10 }], 0, { historyFrames: 18 })).toBe(10);
+ expect(masterKeep(items, 3, { historyFrames: 0 })).toBe(1);
+
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const plan = planSegmentTake({ engine: "open", project, clip, shot, seg: items[1], shotNumber: 1, segNumber: 2, takeNumber: 1, prompt: "P", history: 18, anchor: null, previous: { master: "/api/files/master.mkv", frames: 18 }, keep: 18 });
+ // The previous master holds 18 frames: the history is all of them.
+ expect(plan.steps[0].request.params?.extra).toMatchObject({ historyStart: 0, historyLength: 18, masterKeep: 18, segmentFrames: items[1].end - items[1].start });
+ });
+
+ it("refuses to continue from a take whose master kept fewer frames than the history asks for", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const base = shotOf(0, 300, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } });
+ const done = ready(project, clip, { ...base, segments: currentSegments(base) });
+ const kept = (n: number) => ({ ...done, segments: done.segments!.map((g, i) => (i === 0 ? { ...g, takes: g.takes.map((t) => ({ ...t, frozen: { ...freezeTake(project, done, g), keep: n } })) } : i ? { ...g, takes: [], selectedTake: null } : g)) });
+ const short = planQueue(project, clip, kept(1), done.segments![1].id, "segment", { active: () => false, hasMaster: () => true });
+ expect("problem" in short && short.problem).toMatch(/kept its last 1 frame to continue from — use at most 1 frames of history/);
+ expect("entries" in planQueue(project, clip, kept(18), done.segments![1].id, "segment", { active: () => false, hasMaster: () => true })).toBe(true);
+ });
+
+ it("a frozen take on your GPU saves the frames it was queued to keep", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shot = shotOf(0, 300, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } });
+ const items = currentSegments(shot);
+ const t = take("k", { prompt: "P", frozen: { ...freezeTake(project, shot, items[0]), keep: 35 } });
+ const plan = frozenTakePlan(project, clip, shot, items[0], t, { shot: 1, segment: 1, take: 1 }, null);
+ expect(plan.steps[0].request.params?.extra).toMatchObject({ masterKeep: 35, segmentFrames: items[0].end - items[0].start });
+ });
+});
+
+describe("assembling with takes made before later changes", () => {
+ it("uses the chosen takes as they are and names the out-of-date ones", () => {
+ const clip = clipOf();
+ const project = projectOf([clip], "cloud");
+ const shot = ready(project, clip, shotOf(0, 120, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } }));
+ const c = { ...clip, shots: [shot, shotOf(120, 480, { mode: "preserve" })] };
+ expect(assemblyPieces(project, c)).toMatchObject({ stale: [] });
+ // A new description changes every prompt: the takes are out of date, the assembly still runs with them.
+ const edited = { ...project, character: { ...project.character, description: "a woman in a red coat" } };
+ expect(segmentStates(edited, c, shot)[0].status).toBe("stale");
+ const r = assemblyPieces(edited, c);
+ expect("pieces" in r && r.pieces.map((p) => p.kind)).toEqual(["take", "source"]);
+ expect("stale" in r && r.stale).toEqual(["Shot 1, segment 1"]);
+ // A take that never ran can't be assembled.
+ const stopped = { ...shot, segments: shot.segments!.map((g) => ({ ...g, takes: g.takes.map((t) => ({ ...t, state: "stopped" as const })) })) };
+ expect(assemblyPieces(project, { ...c, shots: [stopped, c.shots[1]] })).toEqual({ problem: expect.stringMatching(/no chosen take/) });
+ });
+});
+
+describe("masks belong to the engine that made them", () => {
+ const who = { selection: "largest" as const, index: 0, words: "person" };
+ const cloudMask: MaskVersion = { id: "mc", createdAt: 0, kind: "track", engine: "cloud", frame: 30, points: [], who, pieces: [{ from: 30, frames: 210, url: "/api/files/cloudmask.mp4" }] };
+ const gpuMask: MaskVersion = { id: "mg", createdAt: 0, kind: "track", engine: "open", frame: 0, points: [], who, pieces: [{ from: 0, frames: 240, url: "/api/files/gpumask.mp4" }] };
+
+ it("a cloud-approved mask isn't sent to your GPU's segment graph, nor counted in its signature", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shot = shotOf(0, 240, { masks: [cloudMask], approvedMask: "mc", settings: { ...DEFAULT_SETTINGS, useAnchor: false } });
+ expect(approvedMask(shot)).toBe(cloudMask);
+ expect(approvedMask(shot, "open")).toBeNull();
+ expect(freezeTake(project, shot, currentSegments(shot)[0]).mask).toBeNull();
+ const plain = shotOf(0, 240, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } });
+ expect(settingSignature(project, clip, { ...shot, id: plain.id }, currentSegments(shot)[0])).toBe(settingSignature(project, clip, plain, currentSegments(shot)[0]));
+ // Your GPU's own approved mask is.
+ const own = { ...shot, masks: [cloudMask, gpuMask], approvedMask: "mg" };
+ expect(freezeTake(project, own, currentSegments(own)[0]).mask).toBe("/api/files/gpumask.mp4");
+ });
+
+ it("Track shot corrects this engine's versions only", () => {
+ const shot = shotOf(0, 240, { masks: [gpuMask, cloudMask], approvedMask: "mc" });
+ expect(defaultMaskBase(shot, "open")).toBe(gpuMask);
+ expect(defaultMaskBase(shot, "cloud")).toBe(cloudMask);
+ expect(defaultMaskBase({ ...shot, masks: [cloudMask] }, "open")).toBeNull();
+ expect(maskProblem("open", "track", 0, 240, [], who, defaultMaskBase({ ...shot, masks: [cloudMask] }, "open"))).toBeNull();
+ expect(maskProblem("open", "track", 0, 240, [], who, cloudMask)).toMatch(/other engine/);
+ });
+});
+
+describe("scene anchor off", () => {
+ it("a segment set to the scene anchor runs without one once anchors are off", () => {
+ const clip = clipOf();
+ const project = projectOf([clip], "cloud");
+ const base = shotOf(0, 240);
+ const items = currentSegments(base);
+ expect(items[0].anchorMode).toBe("shot");
+ const on = planQueue(project, clip, { ...base, segments: items }, items[0].id, "segment", { active: () => false });
+ expect("problem" in on && on.problem).toMatch(/approve a scene anchor/);
+ const off = { ...base, segments: items, settings: { ...base.settings, useAnchor: false } };
+ expect("entries" in planQueue(project, clip, off, items[0].id, "segment", { active: () => false })).toBe(true);
+ // A segment reference of its own is still needed when picked.
+ const custom = { ...off, segments: items.map((g, i) => (i ? g : { ...g, anchorMode: "custom" as const })) };
+ const r = planQueue(project, clip, custom, items[0].id, "segment", { active: () => false });
+ expect("problem" in r && r.problem).toMatch(/pick its reference image/);
+ });
+});
+
+describe("the cloud's pieces", () => {
+ it("scales every piece to one frame inside merge-videos' 512–2048 px and joins at 24 fps", () => {
+ expect(cloudFilmSize(1920, 1080)).toEqual({ width: 1920, height: 1080 });
+ expect(cloudFilmSize(3840, 2160)).toEqual({ width: 2048, height: 1152 });
+ expect(cloudFilmSize(72, 128)).toEqual({ width: 512, height: 910 });
+ expect(cloudFilmSize(undefined, 1080)).toBeNull();
+ const clip = clipOf();
+ const t = take("t1");
+ const { steps } = planAssembly({ engine: "cloud", clip, pieces: [{ kind: "source", start: 0, end: 100 }, { kind: "take", start: 100, end: 224, take: t, segmentId: "s" }], videoOf: () => "/api/files/take.mp4" });
+ expect(steps.map((s) => [s.key, s.request.modelId])).toEqual([
+ ["piece0-cut", "trim-video"],
+ ["piece0", "scale-video"],
+ ["piece1", "scale-video"],
+ ["join", "join-clips"],
+ ["final", "merge-audio-video"],
+ ]);
+ expect(steps[1]).toMatchObject({ request: { op: "reframe", params: { extra: { width: 1920, height: 1080 } } }, after: ["piece0-cut"], chain: [{ slot: "video" }] });
+ // A take is already its segment's length (planSegmentTake trims it): it is only scaled.
+ expect(steps[2].request.inputs).toEqual({ video: "/api/files/take.mp4" });
+ });
+
+ it("Update frame near the clip's end reads its last half second, the clicks on the frame inside it", () => {
+ const clip = clipOf();
+ const shot = shotOf(400, 480);
+ expect(cloudMaskCut(clip, shot, "frame", 10)).toEqual({ from: 410, to: 422, offset: 0 });
+ // Past the shot's end is fine (the clicked frame is what counts); the clip's end isn't.
+ expect(cloudMaskCut(clip, shotOf(0, 100), "frame", 99)).toEqual({ from: 99, to: 111, offset: 0 });
+ expect(cloudMaskCut(clip, shot, "frame", 79)).toEqual({ from: 468, to: 480, offset: 11 });
+ expect(cloudMaskCut(clip, shot, "track", 20)).toEqual({ from: 420, to: 480, offset: 0 });
+ const steps = planMask({ engine: "cloud", clip, shot, kind: "frame", frame: 79, points: [{ x: 5, y: 6, label: "positive" }], who: shot.who, base: null });
+ expect(steps[0].request.params).toEqual({ startTime: 468 / 24, endTime: 20 });
+ expect(steps[1].request.params?.points).toEqual([{ x: 5, y: 6, label: "positive", frame: 11 }]);
+ // fal's SAM 3.1 video takes the frame as frame_index (left out on the first frame).
+ expect(pointsValue("sam", [{ x: 5, y: 6, frame: 11 }, { x: 1, y: 2, label: "negative" }])).toEqual([
+ { x: 5, y: 6, label: 1, frame_index: 11 },
+ { x: 1, y: 2, label: 0 },
+ ]);
+ expect(maskPieces("cloud", "frame", 79, 80, null, 11)).toEqual([{ from: 79, frames: 1, offset: 11 }]);
+ });
+
+ it("makes a copy the browser can play when it can't play the clip (AVI, or a codec it lacks)", () => {
+ const avi = clipOf({ source: { ...clipOf().source, url: "/api/files/uploads/x/old.avi", name: "old.avi" }, normalized: null });
+ const mkv = clipOf({ source: { ...clipOf().source, name: "a.mkv", playable: false }, normalized: null });
+ const mp4 = clipOf({ normalized: null });
+ expect([avi, mkv, mp4].map((c) => clipNeedsPreview("cloud", c))).toEqual([true, true, false]);
+ expect(clipNeedsPreview("open", avi)).toBe(false);
+ const [step] = planPreview(avi)!;
+ expect(step.request).toMatchObject({ modelId: "scale-video", op: "reframe", inputs: { video: avi.source.url }, params: { extra: { width: 1920, height: 1080 } }, feature: "swap-studio-step" });
+ expect(planPreview({ ...avi, source: { ...avi.source, width: undefined } })).toBeNull();
+ // The page plays the copy once it's made; the cloud's jobs still read the upload as filmed.
+ expect(pageClip("cloud", avi)).toBe(avi.source.url);
+ expect(pageClip("cloud", { ...avi, preview: { url: "/api/files/copy.mp4" } })).toBe("/api/files/copy.mp4");
+ expect(pageClip("open", clipOf())).toBe(clipOf().normalized!.url);
+ });
+});
+
+describe("your GPU's mask memory", () => {
+ it("refuses a shot the server can't hold, in words", () => {
+ const GB = 2 ** 30;
+ const shot = { width: 1920, height: 1080, quality: "768p", shotFrames: 240, correcting: true };
+ expect(maskMemoryProblem(shot, 64 * GB)).toBeNull();
+ expect(maskMemoryProblem(shot, 16 * GB)).toMatch(/needs about \d+ GB of RAM and this ComfyUI can spare 8 GB.*or track it at 0\.5 MP/);
+ // Tracking holds fewer copies than correcting; 0.5 MP holds half.
+ expect(maskMemoryProblem({ ...shot, correcting: false }, 32 * GB)).toBeNull();
+ expect(maskMemoryProblem({ ...shot, quality: "480p" }, 32 * GB)).toBeNull();
+ expect(maskMemoryProblem({ ...shot, shotFrames: 3592 }, 64 * GB)).toMatch(/149\.7 s shot/);
+ expect(maskMemoryProblem({ ...shot, width: undefined }, 1)).toBeNull();
+ });
+});
+
+describe("the fine pass of Detect edits", () => {
+ it("reads frames at the clip's size (a small picture scores a cut lower), in bounded pieces", () => {
+ // Shrinking averages pixels: a cut between two textures scores lower when downscaled.
+ const a = new Uint8ClampedArray(4 * 4 * 4);
+ const b = new Uint8ClampedArray(4 * 4 * 4);
+ for (let i = 0; i < 16; i++) {
+ const v = (i + Math.floor(i / 4)) % 2 ? 255 : 0;
+ a.set([v, v, v, 255], i * 4);
+ b.set([255 - v, 255 - v, 255 - v, 255], i * 4);
+ }
+ const avg = (px: Uint8ClampedArray) => {
+ let t = 0;
+ for (let i = 0; i < 16; i++) t += px[i * 4];
+ const m = t / 16;
+ return new Uint8ClampedArray([m, m, m, 255]);
+ };
+ expect(mafd(a, b)).toBe(255);
+ expect(mafd(avg(a), avg(b))).toBeLessThan(1);
+ expect(fineWidth(1920)).toBe(FINE_MAX_WIDTH);
+ expect(fineWidth(480)).toBe(480);
+ expect(fineWidth(undefined)).toBe(640);
+ // Pieces decide on the same frames as the whole stretch: each starts two frames before its first decision.
+ const w = { from: 100, to: 160 };
+ const pieces = windowChunks(w, 24);
+ expect(pieces).toEqual([
+ { from: 100, to: 123 },
+ { from: 122, to: 145 },
+ { from: 144, to: 160 },
+ ]);
+ const frames = windowFrames(w);
+ const pixels = frames.map((f) => frame(f < 150 ? 10 : 240));
+ const whole = windowCuts(frames, pixels, 480);
+ const parts = pieces.flatMap((p) => {
+ const fs = windowFrames(p);
+ return windowCuts(fs, fs.map((f) => pixels[f - w.from]), 480);
+ });
+ expect(whole).toEqual([150]);
+ expect(parts).toEqual(whole);
+ expect(windowChunks({ from: 0, to: 5 }, 24)).toEqual([{ from: 0, to: 5 }]);
+ });
+});
+
+describe("from Genjutsu", () => {
+ it("opens the whole clip and the character in a new project on the same engine", () => {
+ const h = studioHandOff({ engine: "cloud", clip: { url: "/api/files/uploads/x/street.mov", name: "street.mov", size: 1234, duration: 42, width: 1920, height: 1080 }, image: "/api/files/uploads/x/hero.png", description: " a knight\n in armour " });
+ expect(h).toEqual({
+ project: { name: "street", engine: "cloud", character: { image: "/api/files/uploads/x/hero.png", description: "a knight in armour" } },
+ clip: { url: "/api/files/uploads/x/street.mov", name: "street.mov", bytes: 1234, duration: 42, width: 1920, height: 1080 },
+ });
+ // Still uploading (no file yet), or nothing: an empty project with the character.
+ expect(studioHandOff({ engine: "open", clip: { name: "a.mp4" }, image: "blob:x" })).toEqual({ project: { name: "Character swap", engine: "open", character: { image: null, description: "" } }, clip: null });
+ });
+});