The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Character swap: 1080p, 2K and 4K in Genjutsu, and Sharpen in Character Swap Studio's Finish
Claude14dc740252fe
diff --git a/src/app/api/swap-studio/projects/[id]/sharpen/route.ts b/src/app/api/swap-studio/projects/[id]/sharpen/route.tsnew file mode 100644index 00000000..7a8c8f4b--- /dev/null+++ b/src/app/api/swap-studio/projects/[id]/sharpen/route.ts@@ -0,0 +1,10 @@+import { body, handle } from "@/server/shorts-schemas";+import { SharpenSchema, sharpenClip } from "@/server/swap-studio";++/** Sharpen: every chosen take of a clip made sharper at 1080p, 2K or 4K, each a version beside its take to compare. */+export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/sharpen">) {+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json(sharpenClip(id, await body(request, SharpenSchema, "Pick a clip and a size")), { status: 201 });+ }, request);+}diff --git a/src/components/genjutsu/character-panel.tsx b/src/components/genjutsu/character-panel.tsxindex 0363e214..ac120baa 100644--- a/src/components/genjutsu/character-panel.tsx+++ b/src/components/genjutsu/character-panel.tsx@@ -20,15 +20,28 @@ import {WHO_INDEX_LABEL,WHO_LABELS,WINDOW_CHOICES,+ CHARACTER_QUALITIES,+ characterFinish,+ characterQuality,+ type CharacterChoice,type CharacterOptions,- type CharacterQuality,type SwapLora,type SwapSpeech,type SwapWho,} from "@/lib/catalog/character-swap";import type { GenjutsuTarget, Maker } from "@/lib/catalog/genjutsu";+import { cloudSharpenUsd, SHARPEN_COPY } from "@/lib/catalog/sharpen";import type { Engine } from "@/lib/catalog/types";+/** What a quality does, in a line: H3's own sizes, or a finishing size with its price (cloud) or GPU time (open). */+export function qualityHint(engine: Engine, q: CharacterChoice): string {+ const finish = characterFinish(q);+ if (!finish) return q === "480p" ? "Faster and cheaper" : "H3's native top";+ if (engine === "open") return `${SHARPEN_COPY.hintOpen} Free on your GPU, about 3 min more per 5 s on a 72 GB GPU, never above your clip's own size.`;+ const usd = (s: number) => `$${(cloudSharpenUsd(finish, s) ?? 0).toFixed(2)}`;+ return `${SHARPEN_COPY.hint} ${usd(5)} for 5 s, ${usd(15)} for 15 s.`;+}+/** A helper the panel offers (Describe my character, the clip's words): its action, whether it's running or can run. */export interface PanelHelper {run: () => void;@@ -62,8 +75,8 @@ export function CharacterControls({target?: GenjutsuTarget;value: CharacterOptions;onChange: (v: CharacterOptions) => void;- quality: CharacterQuality;- onQuality: (q: CharacterQuality) => void;+ quality: CharacterChoice;+ onQuality: (q: CharacterChoice) => void;seed: string;onSeed: (s: string) => void;seedProblem?: string | null;@@ -74,6 +87,9 @@ export function CharacterControls({}) {const set = (patch: Partial<CharacterOptions>) => onChange({ ...value, ...patch });const h3 = !!maker?.h3;+ // Each engine's sizes (the cloud has no 1080p); a size the other engine offered shows as the swap's own.+ const offered = (maker?.qualities as CharacterChoice[] | undefined) ?? CHARACTER_QUALITIES[engine];+ const shown: CharacterChoice = offered.includes(quality) ? quality : characterQuality(quality);const open = engine === "open";const anchors = ANCHOR_MODELS[engine];const who: SwapWho = value.who ?? "largest";@@ -129,8 +145,8 @@ export function CharacterControls({)}{h3 && (- <Field label="Quality" hint={quality === "480p" ? "Faster and cheaper" : "H3's native top"}>- <Segmented label="Quality" value={quality} onChange={onQuality} options={CHARACTER_SWAP.qualities.map((q) => ({ value: q, label: q }))} />+ <Field label="Quality" hint={qualityHint(engine, shown)}>+ <Segmented label="Quality" value={shown} onChange={onQuality} options={offered.map((q) => ({ value: q, label: q }))} /></Field>)}diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 7ef2bfbf..3c9a22c5 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -27,7 +27,7 @@ import { openInStudio } from "@/components/swap-studio/hooks";import { SelfHostNote } from "@/components/self-host-note";import { useEdgeFade } from "@/components/studio/use-edge-fade";import { useEngine, useGenerations, useLikelyVisitor, useModelAccess } from "@/lib/api";-import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterOptions, type CharacterQuality } from "@/lib/catalog/character-swap";+import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterChoice, type CharacterOptions } from "@/lib/catalog/character-swap";import {chooseMaker,decodeSetup,@@ -124,8 +124,8 @@ export function GenjutsuStudio() {const [points, setPoints] = useState<PixelPoint[]>([]);const [pointLabel, setPointLabel] = useState<"positive" | "negative">("positive");const [paint, setPaint] = useState<Paint | null>(null);- // Character swap: its quality (H3's 480p / 768p), its settings, the seed, and a part longer than 15 s.- const [charQuality, setCharQuality] = useState<CharacterQuality>(CHARACTER_SWAP.defaultQuality);+ // Character swap: its quality (H3's 480p / 768p, or 1080p / 2K / 4K from the 768p swap), its settings, the seed.+ const [charQuality, setCharQuality] = useState<CharacterChoice>(CHARACTER_SWAP.defaultQuality);const [character, setCharacter] = useState<CharacterOptions>({});const [seed, setSeed] = useState("");const [longPart, setLongPart] = useState(false);@@ -293,7 +293,7 @@ export function GenjutsuStudio() {if (s.engine && engineMode === "both") setEngine(s.engine);if (s.tier) setTier(s.tier);if (s.mode === "character") {- if (s.quality === "480p" || s.quality === "768p") setCharQuality(s.quality);+ if (s.quality && ([...CHARACTER_SWAP.qualities, ...CHARACTER_SWAP.finishes] as string[]).includes(s.quality)) setCharQuality(s.quality as CharacterChoice);if (s.quality && (GENJUTSU.qualities as string[]).includes(s.quality)) setQuality(s.quality);setCharacter(s.character ?? {});} else if (s.quality) setQuality(s.quality);diff --git a/src/components/swap-studio/hooks.ts b/src/components/swap-studio/hooks.tsindex 4e65c4fa..5626910e 100644--- a/src/components/swap-studio/hooks.ts+++ b/src/components/swap-studio/hooks.ts@@ -3,6 +3,7 @@import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";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 { SharpenTier } from "@/lib/catalog/sharpen";import type { Engine, PixelPoint } from "@/lib/catalog/types";import { responseError } from "@/lib/refusals";@@ -124,8 +125,9 @@ export const useMakeAnchor = (id: string) => useAction<{ clipId: string; shotId:export const useQueue = (id: string) => useAction<{ clipId: string; shotId: string; segmentId: string; mode: QueueMode }, QueueAnswer>(id, "queue");export const useStopTake = (id: string) => useAction<{ clipId: string; shotId: string; segmentId: string; takeId: string }>(id, "takes/stop");export const useStopJob = (id: string) =>- useAction<{ kind: "mask" | "anchor" | "assembly" | "normalize" | "transcribe"; clipId: string; shotId?: string; segmentId?: string; jobId?: string }>(id, "stop");+ useAction<{ kind: "mask" | "anchor" | "assembly" | "normalize" | "transcribe" | "finish"; clipId: string; shotId?: string; segmentId?: string; jobId?: string }>(id, "stop");export const useAssemble = (id: string) => useAction<{ clipId: string }>(id, "assemble");+export const useSharpen = (id: string) => useAction<{ clipId: string; tier: SharpenTier }>(id, "sharpen");/*** Genjutsu's "Open in Character Swap Studio": a new project with the character, and the clip added (the clip'sdiff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsxindex 3d99ed3e..4a13c0ea 100644--- a/src/components/swap-studio/stage-review.tsx+++ b/src/components/swap-studio/stage-review.tsx@@ -1,6 +1,6 @@"use client";-import { Download, Film, Library, Loader2, Play, Star } from "lucide-react";+import { Ban, Download, Film, Library, Loader2, Play, Sparkles, Star } from "lucide-react";import Link from "next/link";import { useRef, useState } from "react";import { toast } from "sonner";@@ -8,13 +8,31 @@ import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Panel } from "@/components/av/tool-shell";import { Segmented } from "@/components/faceless/controls";+import { Segmented as SizePicker } from "@/components/shorts/ui";+import { useIsOwner } from "@/lib/api";import { characterLicenceLine } from "@/lib/catalog/character-swap";-import { assemblyPieces, assemblyTakes, currentSegments, DECISION_LABELS, jobState, secondsLabel, SWAP_STUDIO, WORKERS_NOTE, type Decision, type SwapTake } from "@/lib/catalog/swap-studio";+import { defaultSharpenTier, filmSize, gpuMinutes, joinNote, SHARPEN_COPY, sharpenOptions, type SharpenTier } from "@/lib/catalog/sharpen";+import {+ assemblyPieces,+ assemblyTakes,+ chosenTakes,+ currentSegments,+ DECISION_LABELS,+ FINISH_UNAVAILABLE,+ jobState,+ secondsLabel,+ SWAP_STUDIO,+ usedFinish,+ WORKERS_NOTE,+ type Decision,+ type GenSummary,+ type SwapTake,+} from "@/lib/catalog/swap-studio";import { STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";import { downloadHref } from "@/lib/library";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";-import { decisionsHref, useAssemble, useStopJob } from "./hooks";+import { decisionsHref, useAssemble, useSharpen, useStopJob } from "./hooks";import { GenChip, JobError, Note, priceText, SavedText } from "./parts";import type { StageProps } from "./workbench";@@ -36,7 +54,12 @@ function finishedTakes({ clip, gens }: Pick<StageProps, "clip" | "gens">): TakeRcurrentSegments(s).forEach((g, gi) =>g.takes.forEach((t, ti) => {const url = t.genId && gens[t.genId]?.status === "succeeded" ? gens[t.genId].url : undefined;- if (url) out.push({ key: t.id, label: `Shot ${si + 1} · segment ${gi + 1} · take ${ti + 1}${g.selectedTake === t.id ? " (chosen)" : ""}`, url, shotId: s.id, segmentId: g.id, take: t });+ const name = `Shot ${si + 1} · segment ${gi + 1} · take ${ti + 1}`;+ if (url) out.push({ key: t.id, label: `${name}${g.selectedTake === t.id ? " (chosen)" : ""}`, url, shotId: s.id, segmentId: g.id, take: t });+ // Its sharper version, to compare with it before keeping it.+ const f = t.finish;+ const sharp = f?.genId && gens[f.genId]?.status === "succeeded" ? gens[f.genId].url : undefined;+ if (f && sharp) out.push({ key: `${t.id}@${f.id}`, label: `${name} · ${SHARPEN_COPY.version(f.tier)}`, url: sharp, shotId: s.id, segmentId: g.id, take: t });}),),);@@ -91,6 +114,126 @@ function Compare({ takes }: { takes: TakeRef[] }) {);}+/** A take's sharper version (Assemble → Finish → Sharpen): how it goes, the video, and whether the assembly uses it. */+function FinishVersion({ take, gens, onUse }: { take: SwapTake; gens: Record<string, GenSummary>; onUse: (use: boolean) => void }) {+ const f = take.finish!;+ const s = jobState(f.genId, f.stepIds, gens);+ const url = s.status === "succeeded" && f.genId ? gens[f.genId]?.url : undefined;+ return (+ <div className={cn("space-y-2 rounded-lg border border-dashed p-2", f.use && "border-success")}>+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <span className="inline-flex items-center gap-1 text-[12px] font-medium">+ <Sparkles className="size-3.5" /> {SHARPEN_COPY.version(f.tier)}+ </span>+ <GenChip genId={f.genId} stepIds={f.stepIds} gens={gens} />+ </div>+ {url ? <video src={url} controls muted playsInline preload="metadata" className="aspect-video w-full rounded-lg bg-media object-contain" /> : null}+ <JobError genId={f.genId} stepIds={f.stepIds} gens={gens} />+ {url &&+ (f.use ? (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[12px] text-success">{SHARPEN_COPY.usingIt(f.tier)}</span>+ <Button size="sm" variant="ghost" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => onUse(false)}>+ Use the take instead+ </Button>+ </div>+ ) : (+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" onClick={() => onUse(true)}>+ {SHARPEN_COPY.pick(f.tier)}+ </Button>+ ))}+ </div>+ );+}++/**+ * Assemble → Finish: "Sharpen to 1080p / 2K / 4K" (runnable: the size, its price or GPU time, Run) beside Akatz Labs'+ * "Clean backplate + alpha", which stays not available (shown to the owner).+ */+function FinishPanel({ id, project, clip, gens, estimate }: Pick<StageProps, "id" | "project" | "clip" | "gens" | "estimate">) {+ const owner = useIsOwner();+ const sharpen = useSharpen(id);+ const stop = useStopJob(id);+ const engine = project.engine;+ const film = filmSize(clip.source.width, clip.source.height, engine);+ const options = sharpenOptions(engine, film);+ const fallback = defaultSharpenTier(engine, film);+ const [picked, setPicked] = useState<SharpenTier | null>(null);+ const tier = picked && options.some((o) => o.tier === picked && o.available) ? picked : fallback;+ const found = assemblyPieces(project, clip);+ const chosen = "pieces" in found ? chosenTakes(found.pieces) : [];+ const finishes = chosen.map((p) => p.take.finish).filter((f) => !!f && (!tier || f.tier === tier));+ const states = finishes.map((f) => jobState(f!.genId, f!.stepIds, gens).status);+ const busy = states.some((x) => x === "queued" || x === "running");+ const ready = states.filter((x) => x === "succeeded").length;+ const est = estimate?.sharpen[clip.id];+ const seconds = est?.seconds ?? chosen.reduce((n, p) => n + (p.end - p.start) / SWAP_STUDIO.fps, 0);+ const cost = tier ? est?.costUsd[tier] : undefined;+ const problem = "problem" in found ? SHARPEN_COPY.none : !tier ? (options.find((o) => o.reason)?.reason ?? SHARPEN_COPY.small) : null;+ const priceLine = engine === "open" ? (estimate?.demo ? priceText(0, { demo: true, engine }) : `Free on your GPU · ${gpuMinutes(seconds)}`) : priceText(cost, { demo: estimate?.demo, engine });+ const join = joinNote(film);+ return (+ <Panel title="Finish">+ <div className="grid gap-3 lg:grid-cols-2">+ <section aria-labelledby="sharpen-title" className="min-w-0 space-y-3 rounded-xl border p-3">+ <div className="flex min-w-0 flex-wrap items-baseline justify-between gap-x-3 gap-y-1">+ <h3 id="sharpen-title" className="text-[13px] font-semibold">+ {SHARPEN_COPY.title}+ </h3>+ <span className="font-mono text-[11px] text-muted-foreground">{priceLine}</span>+ </div>+ <p className="text-[12px] leading-snug text-pretty text-muted-foreground">{engine === "open" ? SHARPEN_COPY.card : SHARPEN_COPY.cardCloud}</p>+ <SizePicker+ label="Sharpen to"+ value={tier ?? "2K"}+ onChange={setPicked}+ options={options.map((o) => ({ value: o.tier, label: o.tier, disabled: !o.available, title: o.reason }))}+ />+ {chosen.length > 0 && (+ <p className="text-[12px] text-muted-foreground">+ {chosen.length} chosen take{chosen.length === 1 ? "" : "s"} · {Math.round(seconds * 10) / 10} s{engine === "cloud" && tier ? ` · MiniMax H3 at ${tier}` : engine === "open" ? " · MiniMax H3 regenerate" : ""}+ </p>+ )}+ {problem ? <Note tone="warn">{problem}</Note> : join ? <p className="text-[12px] leading-snug text-pretty text-muted-foreground">{join}</p> : null}+ {est?.problem && !problem && <Note tone="warn">{est.problem}</Note>}+ <div className="flex flex-wrap items-center gap-2">+ <Button+ className="h-9 rounded-full"+ disabled={!!problem || !tier || sharpen.isPending || busy}+ onClick={() => tier && sharpen.mutate({ clipId: clip.id, tier }, { onSuccess: () => toast(`Sharpening the chosen takes to ${tier}`), onError: (e) => toastError(e) })}+ >+ {sharpen.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Sharpen{tier ? ` to ${tier}` : ""}+ </Button>+ {finishes.length > 0 && (+ <span className="text-[12px] text-muted-foreground">+ {ready} of {chosen.length} ready{ready ? " · compare and pick them in Takes & review" : ""}+ </span>+ )}+ {busy && (+ <Button size="sm" variant="ghost" className="h-8 rounded-full" onClick={() => stop.mutate({ kind: "finish", clipId: clip.id })}>+ Stop+ </Button>+ )}+ </div>+ </section>+ {owner && (+ <section aria-labelledby="backplate-title" className="min-w-0 space-y-2 rounded-xl border border-dashed p-3">+ <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">+ <h3 id="backplate-title" className="text-[13px] font-semibold">+ {FINISH_UNAVAILABLE.title}+ </h3>+ <span className="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground">+ <Ban className="size-3" /> Not available+ </span>+ </div>+ <p className="text-[12px] leading-snug text-pretty text-muted-foreground">{FINISH_UNAVAILABLE.reason}</p>+ </section>+ )}+ </div>+ </Panel>+ );+}+/** Takes & review: compare takes, favourite, keep / maybe / skip with notes, the clip's review, Export decisions. */export function ReviewStage(props: StageProps) {const { id, clip, shot, gens, edit } = props;@@ -150,6 +293,7 @@ export function ReviewStage(props: StageProps) {Use this take</Button>)}+ {t.finish && <FinishVersion take={t} gens={gens} onUse={(finishUse) => void edit({ type: "take", ...ref, finishUse })} />}</li>);})}@@ -172,7 +316,7 @@ export function ReviewStage(props: StageProps) {);}-/** Assemble: the chosen takes over the original timeline with the clip's own sound; the Finish stage said as not available. */+/** Assemble: the chosen takes over the original timeline with the clip's own sound, and Finish (Sharpen; the backplate not available). */export function AssembleStage({ id, project, clip, gens, estimate }: StageProps) {const assemble = useAssemble(id);const stop = useStopJob(id);@@ -197,7 +341,7 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)<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")}>- {p.kind === "take" ? "Your character" : "As filmed"} · {secondsLabel(p.end - p.start)}+ {p.kind === "take" ? `Your character${usedFinish(p.take) ? ` · ${usedFinish(p.take)!.tier}` : ""}` : "As filmed"} · {secondsLabel(p.end - p.start)}</li>))}</ol>@@ -245,6 +389,8 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)</div></Panel>+ <FinishPanel id={id} project={project} clip={clip} gens={gens} estimate={estimate} />+<Panel title="Where it runs"><ul className="space-y-1.5 text-[12px] leading-snug text-pretty text-muted-foreground">{project.engine === "open" && <li>{WORKERS_NOTE}</li>}diff --git a/src/lib/catalog/character-swap.ts b/src/lib/catalog/character-swap.tsindex 223eb124..19748b92 100644--- a/src/lib/catalog/character-swap.ts+++ b/src/lib/catalog/character-swap.ts@@ -10,6 +10,7 @@* Pure module: limits, prompts, the H3 window plan, who to swap, the anchor's prompt and models, licences as data.* The prompts follow Openjutsu's (MIT, Comfy Org 2026) and Akatz Labs' anchor brief (MIT, Akatz Labs 2026).*/+import { isSharpenTier, type SharpenTier } from "./sharpen";import type { Engine, LoraRef, PixelPoint } from "./types";export const CHARACTER_SWAP = {@@ -24,8 +25,11 @@ export const CHARACTER_SWAP = {maxDescriptionChars: 500,/** Seeds Openjutsu takes (uint32); blank is random. */maxSeed: 2 ** 32 - 1,+ /** H3's two sizes: every swap is made at one of them. */qualities: ["480p", "768p"] as const,defaultQuality: "768p" as const,+ /** The sizes a 768p swap is finished at (sharpen.ts): regenerated on your GPU, made at 2K / 4K by fal in the cloud. */+ finishes: ["1080p", "2K", "4K"] as const,/** H3's frame rate: every part is normalised to 24 fps before it is swapped. */fps: 24,window: 124,@@ -38,6 +42,8 @@ export const CHARACTER_SWAP = {} as const;export type CharacterQuality = (typeof CHARACTER_SWAP.qualities)[number];+/** A quality the page offers: H3's own two, or a finishing size of the 768p swap. */+export type CharacterChoice = CharacterQuality | (typeof CHARACTER_SWAP.finishes)[number];/** Who to swap when several people are on screen (the pack's SelectSubject). */export type SwapWho = "largest" | "leftmost" | "rightmost" | "index";@@ -157,19 +163,33 @@ export interface CharacterOptions {// ---------------------------------------------------------------------------// Quality, sizes and windows-/** Genjutsu's qualities to H3's two: 480p stays, anything higher is 768p (H3's native top). */+/** Genjutsu's qualities to H3's two: 480p stays, anything higher is swapped at 768p (H3's native top). */export function characterQuality(q: string | undefined): CharacterQuality {return q === "480p" ? "480p" : "768p";}+/** The finishing size a quality asks for (1080p, 2K, 4K), or null for H3's own 480p / 768p. */+export function characterFinish(q: string | undefined): SharpenTier | null {+ return isSharpenTier(q) ? q : null;+}++/** The qualities each engine offers: your GPU regenerates 1080p, 2K and 4K; fal's H3 makes 2K and 4K (no 1080P). */+export const CHARACTER_QUALITIES: Record<Engine, CharacterChoice[]> = {+ open: ["480p", "768p", "1080p", "2K", "4K"],+ cloud: ["480p", "768p", "2K", "4K"],+};+/** What the unpatched h3_character_swap pack's PrepareVideo takes: the strings "480" / "768" (the patched one: integers). */export const packResolution = (q: string | undefined, patched = false): string | number => {const v = characterQuality(q) === "480p" ? "480" : "768";return patched ? Number(v) : v;};-/** fal's H3 resolution enum for a quality. */-export const falResolution = (q: string | undefined) => (characterQuality(q) === "480p" ? "480P" : "768P");+/**+ * fal's H3 resolution enum for a quality: 480P and 768P are made natively, 2K and 4K from a 768P base. fal has no 1080P:+ * 1080p goes to the largest it makes below it (768P), as Genjutsu's other models do (qualityFor).+ */+export const falResolution = (q: string | undefined): "480P" | "768P" | "2K" | "4K" => (q === "2K" || q === "4K" ? q : characterQuality(q) === "480p" ? "480P" : "768P");/** H3's frame grid: the first count of the form 17n + 5 at or above n (ComfyUI's align_frame_count). */export function alignFrames(n: number): number {diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.tsindex 00ce0dae..95889063 100644--- a/src/lib/catalog/genjutsu.ts+++ b/src/lib/catalog/genjutsu.ts@@ -23,10 +23,14 @@ import {anchorModel,anchorPrompt,ANCHOR_FALLBACK,+ CHARACTER_QUALITIES,CHARACTER_SWAP,CLOUD_NO_LORA,+ characterFinish,characterLicenceLine,characterQuality,+ h3Canvas,+ partFrames,cutsInPart,partProblem,seedProblem,@@ -59,12 +63,14 @@ import { firstFramePrompt, getShortsPreset, lookFromPreset, planShorts, segmentPimport { getModel } from "./index";import { REPLACED_BY } from "./replaced";import { soulLook } from "./soul";+import { filmSize, SHARPEN_COPY, sharpenPrompt, sharpenSteps, sharpenTierFor, type SharpenTier } from "./sharpen";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";export type GenjutsuMode = "motion" | "character" | "swap" | "restyle" | "insert";/** How you say what changes (Object swap and Insert) or who (Character swap): words, clicks on the first frame, or paint on it. */export type GenjutsuTarget = RemoveMode;-export type GenjutsuQuality = "480p" | "720p" | "768p" | "1080p";+/** Genjutsu's qualities; 2K and 4K are the Character swap's finishing sizes (sharpen.ts). */+export type GenjutsuQuality = "480p" | "720p" | "768p" | "1080p" | "2K" | "4K";/** Lite ("standard", the cheaper, faster tier of the same Original) or the full Original ("high"). */export type GenjutsuTier = "standard" | "high";@@ -317,7 +323,7 @@ export const MAKERS: Maker[] = [maxSeconds: CHARACTER_SWAP.maxSeconds,minSeconds: CHARACTER_SWAP.minSeconds,keepsSound: false,- qualities: ["480p", "768p"],+ qualities: CHARACTER_QUALITIES.cloud,h3: { anchor: true },promptOptional: true,},@@ -363,7 +369,7 @@ export const MAKERS: Maker[] = [source: "original",refs: { min: 1, max: 1 },keepsSound: true,- qualities: ["480p", "768p"],+ qualities: CHARACTER_QUALITIES.open,h3: { anchor: true, maskSwitch: true },promptOptional: true,},@@ -377,7 +383,7 @@ export const MAKERS: Maker[] = [source: "open",refs: { min: 1, max: 1 },keepsSound: true,- qualities: ["480p", "768p"],+ qualities: CHARACTER_QUALITIES.open,h3: { anchor: false },promptOptional: true,},@@ -765,7 +771,8 @@ const px = (q: string) => parseInt(q, 10) || 0;/** The resolution a model is asked for: the quality picked, or the nearest it renders (the largest not above, else its smallest). */export function qualityFor(m: Maker, quality: string): string | undefined {if (!m.qualities?.length) return undefined;- if (m.h3) return characterQuality(quality);+ // H3: its own 480p / 768p, or a finishing size of the 768p swap the engine makes (else the swap's own size).+ if (m.h3) return m.qualities.includes(quality) ? quality : characterQuality(quality);if (m.qualities.includes(quality)) return quality;const below = m.qualities.filter((q) => px(q) <= px(quality)).sort((a, b) => px(b) - px(a));return below[0] ?? [...m.qualities].sort((a, b) => px(a) - px(b))[0];@@ -1207,6 +1214,86 @@ export function h3Extra(c: CharacterOptions | undefined): Record<string, unknown};}+/**+ * Your GPU's 1080p / 2K / 4K (sharpen.ts): after the 768p swap, the person's mask over the part (SAM 3.1, as the swap+ * found them), the part at 24 fps and the film's size, then the swap regenerated (start sigma 0.8, never above the+ * footage's size) and only the character composited over the footage, and the part's own sound put back.+ */+function openFinish(input: GenjutsuPlanInput, asked: SharpenTier, quality: string) {+ const film = filmSize(input.source.width, input.source.height);+ const tier = sharpenTierFor("open", asked, film);+ if (!film) throw new Error(SHARPEN_COPY.noSize);+ if (!tier) throw new Error(SHARPEN_COPY.small);+ const c = input.character ?? {};+ const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };+ const base = { feature: GENJUTSU.feature, batchTitle: input.title, title: input.title };+ const start = r3(input.range.start);+ const end = r3(input.range.end);+ const frames = partFrames(end - start);+ const h3 = h3Extra(c);+ return (steps: PlanStep[], prompt: string): { final: string; sound: boolean } => {+ steps.push({+ key: "mask",+ request: {+ ...helper,+ modelId: FINISH_TOOLS.mask,+ op: "bg-remove-video",+ prompt: (typeof h3.maskPrompt === "string" && h3.maskPrompt) || "person",+ inputs: { video: input.source.url },+ params: {+ startTime: start,+ endTime: end,+ resolution: quality,+ matteOutput: "matte",+ ...(input.points?.length ? { points: input.points } : {}),+ extra: {+ selection: input.points?.length ? "index" : h3.selection,+ subjectIndex: input.points?.length ? 0 : h3.subjectIndex,+ maskPrompt: (typeof h3.maskPrompt === "string" && h3.maskPrompt) || "person",+ keyFrame: 0,+ spanFrames: frames,+ shotFrames: frames,+ },+ },+ step: { label: "Find your character's outline (SAM 3.1)", index: 0, of: 1 },+ },+ });+ steps.push({+ key: "fit",+ request: { ...helper, modelId: FINISH_TOOLS.fit, op: "trim", inputs: { video: input.source.url }, params: { startTime: start, endTime: end, fps: 24, extra: { ...film } }, step: { label: "The part at 24 fps", index: 0, of: 1 } },+ });+ const sound = !!input.source.hasAudio;+ const made = sharpenSteps({+ key: "sharpen-",+ label: "Your character",+ helper,+ result: sound ? helper : base,+ tier,+ prompt: sharpenPrompt(prompt, c.description),+ ...(input.seed !== undefined ? { seed: input.seed } : {}),+ frames,+ take: { after: "swap" },+ source: { after: "fit", start: 0 },+ mask: { after: "mask", start: 0 },+ film,+ canvas: h3Canvas(input.source.width!, input.source.height!, quality),+ });+ steps.push(...made.steps);+ if (!sound) return { final: made.final, sound: false };+ // The part's own sound over the whole of it (the composites' slices of it would meet at every window).+ steps.push({+ key: "sound",+ request: { ...base, modelId: FINISH_TOOLS.mux, op: "mux", step: { label: "Put the clip's sound back", index: 1200, of: 1000 } },+ after: [made.final, "fit"],+ chain: [{ slot: "video" }, { slot: "audio" }],+ });+ return { final: "sound", sound: true };+ };+}++/** Your GPU's finishing helpers: SAM 3.1's mask of a shot (H3 Relay), the 24 fps fit, the soundtrack. */+const FINISH_TOOLS = { mask: "oss-h3-person-mask", fit: "oss-fit-clip", mux: "oss-mux" } as const;+/*** Character swap on MiniMax H3. Open: one job on the upload (the graph trims the part, finds the person with SAM 3.1,* continues window after window up to 30 s and keeps the clip's sound). Cloud: 15 s pieces (5–15 s each), each with@@ -1221,6 +1308,8 @@ function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {const character = input.references.slice(0, 1);if (!character.length) throw new Error(REFS_MISSING.character);const quality = characterQuality(input.quality);+ // 1080p / 2K / 4K: the swap is made at 768p, then finished (your GPU: regenerated and composited; fal: made at that size).+ const finish = characterFinish(qualityFor(m, input.quality));const seed = input.seed !== undefined ? { seed: input.seed } : {};const anchorOn = !!m.h3?.anchor && c.anchor !== false;const am = anchorModel(m.engine, c.anchorModel);@@ -1254,11 +1343,11 @@ function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {});steps.push(anchorStep("anchor", "frame", { label: `Put your character in it (${am.label})`, index: 0, of: 1 }));}+ const sharpen = finish ? openFinish(input, finish, quality) : null;steps.push({key: "swap",request: {- ...base,- title: input.title,+ ...(sharpen ? helper : { ...base, title: input.title }),modelId: m.id,op: "video-swap",prompt: promptWith(anchorOn),@@ -1276,7 +1365,9 @@ function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {},...(anchorOn ? { after: ["anchor"], chain: [anchorSlot()] } : {}),});- return { steps, final: "swap", pieces: 1, sound: false, tracked: false, anchors: anchorOn ? 1 : 0 };+ if (!sharpen) return { steps, final: "swap", pieces: 1, sound: false, tracked: false, anchors: anchorOn ? 1 : 0 };+ const done = sharpen(steps, promptWith(anchorOn));+ return { steps, final: done.final, pieces: 1, sound: done.sound, tracked: false, anchors: anchorOn ? 1 : 0 };}// Cloud: fal's H3 takes 5–15 s of reference video and whole seconds of output, and needs a swap LoRA.@@ -1310,8 +1401,9 @@ function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {prompt: promptWith(anchorOn),inputs: { images: character },loras: [lora],- params: { duration: callSecs, sourceDuration: secs, resolution: quality, ...seed },- step: label("swap the character"),+ // fal makes 2K and 4K from a 768P base itself: the same call at that size.+ params: { duration: callSecs, sourceDuration: secs, resolution: finish ?? quality, ...seed },+ step: label(finish ? `swap the character at ${finish}` : "swap the character"),},after,chain,@@ -1458,7 +1550,7 @@ export interface GenjutsuSetup {}const MODES = new Set<string>(GENJUTSU_MODES.map((m) => m.id));-const QUALITIES = new Set<string>(["480p", "720p", "768p", "1080p"]);+const QUALITIES = new Set<string>(["480p", "720p", "768p", "1080p", "2K", "4K"]);const FILE = /^\/api\/files\/[\w./-]{1,200}$/;const str = (v: unknown, max: number) => (typeof v === "string" && v.trim() ? v.slice(0, max) : undefined);const files = (v: unknown, max: number) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && FILE.test(x)).slice(0, max) : []);diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 8c4c7fe6..817383e2 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -7,6 +7,7 @@ import { ANGLES_LORA, MOSAIC_SCALE, MOSAIC_TARGET, SPEAK_GRAPH, SPEAK_LORA, SPEAimport { CINEMA_CROP, SOUL_ASPECTS, SOUL_TIERS } from "./soul";import { RESTORE, offlineRestorePrompt } from "./restore";import { REGEN_COPY, REGEN_DEFAULT_TIER, REGEN_MODEL, REGEN_TIERS, REGEN_WORKFLOW } from "./regenerate";+import { COMPOSITE_MODEL, COMPOSITE_WORKFLOW } from "./sharpen";import { denoiseFor, EVOLUTION, EVOLUTION_DEFAULT_RESOLUTION, EVOLUTION_RESOLUTIONS, INTENSITIES, type Intensity } from "./evolution";import { LAST_FRAME_CHAIN, type ModelDef, type ModelOptions, type ModelRoute, type Operation } from "./types";@@ -1126,6 +1127,19 @@ const open: ModelDef[] = [options: { keepsNamed: true, matteOutputs: ["matte"] },hidden: true,}),+ // Character swap in 2K (n7-4): only the swapped character goes back over the footage, from the 768p swap and its+ // regenerate, through the person's mask (src/lib/catalog/sharpen.ts). Run by Character Swap Studio and Genjutsu.+ o({+ id: COMPOSITE_MODEL,+ name: "Character over the footage",+ vendor: "ComfyUI",+ family: "utility",+ kind: "video",+ tagline: "Puts only the swapped character back over the original footage, with its own sound · CPU",+ routes: [comfy("overlay", COMPOSITE_WORKFLOW, "the swap, then its regenerate, each through the person's mask (grown, feathered); a few seconds a pass")],+ options: {},+ hidden: true,+ }),o({id: "oss-qwen-relight",name: "Qwen-Image-Edit Relight",diff --git a/src/lib/catalog/sharpen.ts b/src/lib/catalog/sharpen.tsnew file mode 100644index 00000000..33694b11--- /dev/null+++ b/src/lib/catalog/sharpen.ts@@ -0,0 +1,347 @@+/**+ * Character swap in 2K (docs/research/new-models-7.md §2.10 rows 4-5, §2.11): a swap comes back at H3's 768p, and+ * "Sharpen" (Character Swap Studio's Finish) or a 1080p / 2K / 4K quality (Genjutsu's Character swap) makes it sharper+ * without touching the background or the sound.+ *+ * Your GPU: the 768p swap is redrawn by Open-H3 Regenerate (video-regenerate-h3, start sigma 0.8: it stays closer to the+ * draft), at most the size the footage is kept at, in 15 s windows; then video-composite-mask puts only the character+ * back over the original footage (the swap first, then the regenerate, each through the person's mask, grown and+ * feathered), with the footage's own sound, in short composite windows joined packet by packet.+ * The cloud: nobody hosts a regenerate after the fact, so the swap is made again on fal's MiniMax H3 at 2K or 4K (the+ * same hosted model asked for a size it offers, with the same words, LoRA, references and seed): a new version beside+ * the first one, for approval. The whole frame is redrawn there.+ *+ * Pure: the tiers and what each engine makes of them, the cap at the size the film is joined at, the composite's+ * geometry, the windows, the copy, and the steps on your GPU.+ */+import { REGEN_MODEL, REGEN_WINDOW_SECONDS, RERENDER } from "./regenerate";+import type { PlanStep } from "./shorts";+import type { ChainSlot, Engine, GenerationRequest } from "./types";++export const SHARPEN_TIERS = ["1080p", "2K", "4K"] as const;+export type SharpenTier = (typeof SHARPEN_TIERS)[number];+export const isSharpenTier = (v: unknown): v is SharpenTier => typeof v === "string" && (SHARPEN_TIERS as readonly string[]).includes(v);++/** Open-H3 Regenerate's tier for each (Upscale → Video names them by the shorter edge). */+export const SHARPEN_REGEN_TIER: Record<SharpenTier, "1080p" | "1440p" | "2160p"> = { "1080p": "1080p", "2K": "1440p", "4K": "2160p" };+/** The shorter edge each tier is made at. */+export const SHARPEN_SHORT_EDGE: Record<SharpenTier, number> = { "1080p": 1080, "2K": 1440, "4K": 2160 };+/** fal's MiniMax H3 resolutions: 480P and 768P are made natively, 2K and 4K from a 768P base (no 1080P). */+export const CLOUD_TIERS: readonly SharpenTier[] = ["2K", "4K"];++/** The regenerate's start noise for a swap (rdh: 0.8 "stays closer to the draft"; the release's 0.909 can drift a face). */+export const SHARPEN_SIGMA = 0.8;++/** fal's price per second of the LoRA route (the Character swap's), by resolution. */+export const SWAP_PER_SECOND: Record<"480P" | "768P" | "2K" | "4K", number> = { "480P": 0.0625, "768P": 0.075, ...RERENDER["fuobe-character-swap"].perSecond };++/** The mask composite (core nodes): the hidden model and its graph. */+export const COMPOSITE_MODEL = "oss-composite-mask";+export const COMPOSITE_WORKFLOW = "video-composite-mask";+/** One composite pass decodes four streams as float32 (about 25 MB a frame each at 1080p): 3 s keeps it near 12 GB. */+export const COMPOSITE_WINDOW_SECONDS = 3;+/** Both engines join the film at most this many pixels a side (the fit graph's limit; fal merge-videos' 2048). */+export const FILM_MAX = 2048;+const FPS = 24;++/** The pace the open engine's regenerate was measured at (about 3 minutes per 5 s at 2K on a 72 GB GPU). */+export const REGEN_MINUTES_PER_5S = 3;++export const SHARPEN_COPY = {+ title: "Sharpen to 1080p / 2K / 4K",+ /** Your GPU: only the character is redrawn. */+ card: "Redraws each chosen take at 2K, then puts only your character back over the original footage. The background and the sound stay as filmed. Faces can change slightly; compare before you keep it.",+ /** The cloud: a new render of the take (no regenerate is hosted). */+ cardCloud:+ "Makes each chosen take again at 2K on MiniMax H3, with the same words, references and seed, as a new version beside the first. The whole frame is redrawn, so compare before you keep it.",+ /** Genjutsu's Quality hint for a finishing size. */+ hint: "2K and 4K redraw the 768p swap at the higher size.",+ hintOpen: "1080p, 2K and 4K redraw the 768p swap at the higher size.",+ /** The version beside a take, and its switch. */+ version: (tier: string) => `${tier} version`,+ pick: (tier: string) => `Use the ${tier} version`,+ usingIt: (tier: string) => `The assembly uses the ${tier} version`,+ noMask: "Sharpen puts your character back through the shot's mask: approve a mask in Who to swap and make the take with it",+ small: "This clip is filmed below 1080p, so the 768p takes already match it",+ noSize: "Couldn't read the clip's size: open the clip once in Shots so it is measured",+ none: "Choose a take for every swapped segment first",+} as const;++/**+ * The film's frame: the size every piece is joined at, on even numbers. Your GPU: the clip's own, at most 2048 px a side+ * (the studio's 24 fps copy, swap-studio.ts normalizedSize). The cloud: the same, and a small clip scaled up towards+ * 512 px on its short side (fal merge-videos, swap-studio.ts cloudFilmSize).+ */+export function filmSize(width?: number, height?: number, engine: Engine = "open"): { width: number; height: number } | null {+ if (!width || !height) return null;+ if (engine === "cloud") {+ const scale = Math.min(FILM_MAX / 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) };+ }+ const k = Math.min(1, FILM_MAX / width, FILM_MAX / height);+ const even = (n: number) => Math.max(2, Math.floor((n * k) / 2) * 2);+ return { width: even(width), height: even(height) };+}++export interface SharpenOption {+ tier: SharpenTier;+ available: boolean;+ /** Why it can't be picked, in words. */+ reason?: string;+}++const sizeWords = (f: { width: number; height: number }) => `${f.width}×${f.height}`;++/**+ * What each tier does for a film of this size on an engine. The film is joined at most 2048 px a side, so a tier larger+ * than the film's shorter edge adds nothing: your GPU offers the tiers that fit (never above the footage), the cloud+ * offers what fal makes (2K, 4K) where the join keeps it.+ */+export function sharpenOptions(engine: Engine, film: { width: number; height: number } | null): SharpenOption[] {+ const short = film ? Math.min(film.width, film.height) : 0;+ return SHARPEN_TIERS.map((tier) => {+ if (engine === "cloud" && !CLOUD_TIERS.includes(tier)) return { tier, available: false, reason: "The cloud makes 2K or 4K" };+ if (!film) return { tier, available: engine === "cloud" && tier === "2K", ...(engine === "cloud" && tier === "2K" ? {} : { reason: SHARPEN_COPY.noSize }) };+ if (short < SHARPEN_SHORT_EDGE["1080p"]) return { tier, available: false, reason: SHARPEN_COPY.small };+ // The cloud's 2K is the smallest it makes: always worth it over 768p, joined at the film's size.+ if (engine === "cloud" && tier === "2K") return { tier, available: true };+ if (SHARPEN_SHORT_EDGE[tier] <= short) return { tier, available: true };+ return { tier, available: false, reason: `Joined at ${sizeWords(film)}, so ${tier} adds nothing to the film` };+ });+}++/** The tier made when `asked` is picked: the largest available one not above it (null: none is). */+export function sharpenTierFor(engine: Engine, asked: SharpenTier, film: { width: number; height: number } | null): SharpenTier | null {+ const ok = sharpenOptions(engine, film).filter((o) => o.available).map((o) => o.tier);+ const at = SHARPEN_TIERS.indexOf(asked);+ return [...ok].reverse().find((t) => SHARPEN_TIERS.indexOf(t) <= at) ?? null;+}++/** The tier picked first: 2K where it is available, else the largest that is. */+export function defaultSharpenTier(engine: Engine, film: { width: number; height: number } | null): SharpenTier | null {+ const ok = sharpenOptions(engine, film).filter((o) => o.available);+ return ok.find((o) => o.tier === "2K")?.tier ?? ok.at(-1)?.tier ?? null;+}++/** The join's note: what a sharper take is joined at. */+export function joinNote(film: { width: number; height: number } | null): string | null {+ return film ? `The clip is joined at ${sizeWords(film)} (up to ${FILM_MAX} px a side). Each sharper take keeps its own size in Takes & review` : null;+}++/** The cloud's price of one take made again at a size: whole seconds, 5–15 s a call (fal's H3). */+export function cloudSharpenUsd(tier: SharpenTier, seconds: number): number | null {+ if (!CLOUD_TIERS.includes(tier)) return null;+ const secs = Math.min(15, Math.max(5, Math.ceil(seconds - 1e-6)));+ return Math.round(SWAP_PER_SECOND[tier as "2K" | "4K"] * secs * 100) / 100;+}++/** Your GPU's time for seconds of swaps, in words ("about 3 min" per 5 s at 2K on a 72 GB GPU). */+export function gpuMinutes(seconds: number): string {+ const m = Math.max(1, Math.round((seconds / 5) * REGEN_MINUTES_PER_5S));+ return `about ${m} min on a 72 GB GPU`;+}++// ---------------------------------------------------------------------------+// The composite's geometry++export interface Box {+ width: number;+ height: number;+ x: number;+ y: number;+}++/** The centre part of a frame with a given shape (what a cover-and-crop to that shape keeps), on even numbers. */+function centre(frame: { width: number; height: number }, aspect: number): { width: number; height: number } {+ const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);+ return aspect < frame.width / frame.height ? { width: Math.min(frame.width, even(frame.height * aspect)), height: frame.height } : { width: frame.width, height: Math.min(frame.height, even(frame.width / aspect)) };+}++/** The draft shape Open-H3 Regenerate keeps of an H3 clip: 1344 × 768 (turned for a tall one). */+const DRAFT = { width: 1344, height: 768 };++/**+ * Where each layer goes in the film: the swap covers the part of the footage its canvas was cut from (H3 cover-crops the+ * clip to its canvas), the regenerate the centre of that its 16:9 or 9:16 draft kept (it stretches the draft to its+ * 16:9 grid and crops a few rows, so it is laid back over the draft's own part). Both are centred.+ */+export function compositeGeometry(film: { width: number; height: number }, canvas: { width: number; height: number }): { take: Box; region: Box } {+ const t = centre(film, canvas.width / canvas.height);+ const draft = canvas.height > canvas.width ? DRAFT.height / DRAFT.width : DRAFT.width / DRAFT.height;+ const r = centre(t, draft);+ const tx = Math.floor((film.width - t.width) / 2);+ const ty = Math.floor((film.height - t.height) / 2);+ return { take: { ...t, x: tx, y: ty }, region: { ...r, x: tx + Math.floor((t.width - r.width) / 2), y: ty + Math.floor((t.height - r.height) / 2) } };+}++/** The mask's grown and feathered edge, in the region's pixels (about 0.8 % and 1.2 % of its shorter side). */+export function maskEdge(region: { width: number; height: number }): { grow: number; feather: number } {+ const short = Math.min(region.width, region.height);+ return { grow: Math.max(2, Math.round(short * 0.008)), feather: Math.max(4, Math.round(short * 0.012)) };+}++// ---------------------------------------------------------------------------+// Windows++/** Frames split into equal windows of at most `max` frames (no sliver at the end). */+export function frameWindows(frames: number, max: number): { from: number; frames: number }[] {+ const total = Math.max(1, Math.round(frames));+ const n = Math.ceil(total / max);+ const out: { from: number; frames: number }[] = [];+ let from = 0;+ for (let i = 0; i < n; i++) {+ const to = Math.round(((i + 1) * total) / n);+ out.push({ from, frames: to - from });+ from = to;+ }+ return out;+}++const sec = (frames: number) => Math.round((frames / FPS) * 1e6) / 1e6;++// ---------------------------------------------------------------------------+// The steps on your GPU++/** A file the step reads: a stored file, or the output of an earlier step. */+export type StepInput = { url: string } | { after: string };++export interface SharpenStepsInput {+ /** Prefix of the step keys (unique within the pipeline). */+ key: string;+ /** Words for step labels ("Shot 1 · segment 2 · take 1"). */+ label: string;+ helper: Pick<GenerationRequest, "feature" | "batchTitle">;+ /** The finished step's identity (a result of its own): feature, title. */+ result: Pick<GenerationRequest, "feature" | "batchTitle" | "title">;+ /** The tier the regenerate makes (already capped: sharpenTierFor). */+ tier: SharpenTier;+ /** What the regenerate redraws from. */+ prompt: string;+ seed?: number;+ /** The swap's length in frames (24 fps). */+ frames: number;+ /** The 768p swap. */+ take: StepInput;+ /** The footage at 24 fps and the film's size, and where the swap starts in it (seconds). */+ source: StepInput & { start: number };+ /** The person's mask (H3's canvas, 24 fps), and where the swap starts in it (seconds). */+ mask: StepInput & { start: number };+ film: { width: number; height: number };+ /** H3's canvas the swap and the mask were made at. */+ canvas: { width: number; height: number };+}++/** The words a regenerate redraws a swap from: the take's own, without H3's reference tags. */+export function sharpenPrompt(takePrompt: string, description?: string): string {+ const words = takePrompt+ .replace(/<Video \d+>/g, "the clip")+ .replace(/<Picture \d+>/g, "the reference")+ .replace(/\s+/g, " ")+ .trim();+ const who = (description ?? "").replace(/\s+/g, " ").trim().replace(/[.\s]+$/, "");+ return [who ? `The character: ${who}.` : "", words].filter(Boolean).join(" ").slice(0, 1500);+}++const fill = (input: StepInput, slot: ChainSlot): { after?: string; chain?: ChainSlot; url?: string } => ("after" in input ? { after: input.after, chain: slot } : { url: input.url });++/**+ * One swap sharpened on your GPU: Open-H3 Regenerate in windows of up to 15 s, each composited over the footage in+ * windows of up to 3 s (the swap, then the regenerate, through the mask), joined packet by packet. The last step (the+ * join, or the only composite) is the result.+ */+export function sharpenSteps(s: SharpenStepsInput): { steps: PlanStep[]; final: string } {+ const steps: PlanStep[] = [];+ const geo = compositeGeometry(s.film, s.canvas);+ const edge = maskEdge(geo.region);+ const regen = frameWindows(s.frames, REGEN_WINDOW_SECONDS * FPS);+ const parts: string[] = [];+ const total = regen.reduce((n, w) => n + frameWindows(w.frames, COMPOSITE_WINDOW_SECONDS * FPS).length, 0);+ const take = fill(s.take, { slot: "video" });+ regen.forEach((w, wi) => {+ const rk = `${s.key}regen${wi}`;+ const many = regen.length > 1;+ steps.push({+ key: rk,+ request: {+ ...s.helper,+ modelId: REGEN_MODEL,+ op: "upscale-video",+ prompt: s.prompt,+ ...(take.url ? { inputs: { video: take.url } } : {}),+ params: {+ resolution: SHARPEN_REGEN_TIER[s.tier],+ ...(many ? { startTime: sec(w.from), endTime: sec(w.from + w.frames) } : {}),+ sourceDuration: sec(w.frames),+ ...(s.seed !== undefined ? { seed: s.seed } : {}),+ // An H3 draft (the 768p preset), and the start noise that keeps the swapped identity closer.+ extra: { startSigma: SHARPEN_SIGMA, draftFrom: "h3" },+ },+ step: { label: `${s.label} · redraw at ${s.tier}${many ? ` (${wi + 1} of ${regen.length})` : ""}`, index: wi, of: regen.length },+ },+ ...(take.after ? { after: [take.after], chain: [take.chain!] } : {}),+ });+ for (const c of frameWindows(w.frames, COMPOSITE_WINDOW_SECONDS * FPS)) {+ const ck = `${s.key}comp${parts.length}`;+ const from = w.from + c.from;+ const after: string[] = [rk];+ const chain: ChainSlot[] = [{ slot: "videos", at: 1 }];+ // The footage is the first clip, the regenerate the second, the swap the third; the mask is the mask.+ const src = fill(s.source, { slot: "videos", at: 0 });+ const tk = fill(s.take, { slot: "videos", at: 2 });+ const mk = fill(s.mask, { slot: "mask" });+ for (const x of [src, tk, mk]) {+ if (x.after) {+ after.push(x.after);+ chain.push(x.chain!);+ }+ }+ const own = [src.url, tk.url].filter((u): u is string => !!u);+ steps.push({+ key: ck,+ request: {+ ...s.helper,+ modelId: COMPOSITE_MODEL,+ op: "overlay",+ inputs: { ...(own.length ? { videos: own } : {}), ...(mk.url ? { mask: mk.url } : {}) },+ params: {+ startTime: Math.round((s.source.start + sec(from)) * 1e6) / 1e6,+ endTime: Math.round((s.source.start + sec(from + c.frames)) * 1e6) / 1e6,+ extra: {+ windowStart: sec(c.from),+ takeStart: sec(from),+ maskStart: Math.round((s.mask.start + sec(from)) * 1e6) / 1e6,+ canvasWidth: geo.take.width,+ canvasHeight: geo.take.height,+ takeX: geo.take.x,+ takeY: geo.take.y,+ regionWidth: geo.region.width,+ regionHeight: geo.region.height,+ regionX: geo.region.x,+ regionY: geo.region.y,+ maskGrow: edge.grow,+ feather: edge.feather,+ },+ },+ step: { label: `${s.label} · your character over the footage${total > 1 ? ` (${parts.length + 1} of ${total})` : ""}`, index: parts.length, of: total },+ },+ after,+ chain,+ });+ parts.push(ck);+ }+ });+ if (parts.length === 1) {+ const last = steps.find((x) => x.key === parts[0])!;+ last.request = { ...last.request, ...s.result };+ return { steps, final: parts[0] };+ }+ const jk = `${s.key}join`;+ steps.push({+ key: jk,+ request: { ...s.helper, ...s.result, modelId: "oss-join-encoded", op: "concat", step: { label: `${s.label} · join`, index: total, of: total } },+ after: parts,+ chain: parts.map(() => ({ slot: "videos" as const })),+ });+ return { steps, final: jk };+}diff --git a/src/lib/catalog/swap-studio-edit.ts b/src/lib/catalog/swap-studio-edit.tsindex 717372fa..949a522d 100644--- a/src/lib/catalog/swap-studio-edit.ts+++ b/src/lib/catalog/swap-studio-edit.ts@@ -77,7 +77,7 @@ export type SwapEdit =| { type: "layout"; clipId: string; shotId: string; op: LayoutOp }| { type: "segment"; clipId: string; shotId: string; segmentId: string; patch: SegmentPatch }| { type: "update-prompt"; clipId: string; shotId: string; segmentId: string }- | { type: "take"; clipId: string; shotId: string; segmentId: string; takeId: string; select?: boolean; favourite?: boolean; decision?: Decision; notes?: string; remove?: boolean }+ | { type: "take"; clipId: string; shotId: string; segmentId: string; takeId: string; select?: boolean; favourite?: boolean; decision?: Decision; notes?: string; remove?: boolean; finishUse?: boolean }| { type: "anchor-import"; clipId: string; shotId: string; segmentId?: string; url: string; id: string; at: number }| { type: "remove-anchor"; clipId: string; shotId: string; segmentId?: string; anchorId: string }| { type: "remove-mask"; clipId: string; shotId: string; maskId: string };@@ -318,6 +318,12 @@ export function applyEdit(project: SwapProject, edit: SwapEdit, o: { active: (gereturn removeTake(next, edit.takeId);}if (edit.select) next = selectTake(next, edit.takeId);+ // Its sharper version in the assembly (picked after comparing), or the take itself again.+ if (edit.finishUse !== undefined) {+ const t = next.takes.find((k) => k.id === edit.takeId);+ if (!t?.finish) throw new Error("This take has no sharper version — use Sharpen in Assemble");+ next = { ...next, takes: next.takes.map((k) => (k.id === edit.takeId ? { ...k, finish: { ...t.finish!, use: edit.finishUse! } } : k)) };+ }const patch = { ...(edit.favourite !== undefined ? { favourite: edit.favourite } : {}), ...(edit.decision ? { decision: edit.decision } : {}), ...(edit.notes !== undefined ? { notes: edit.notes } : {}) };return Object.keys(patch).length ? updateTake(next, edit.takeId, patch) : next;} catch (e) {diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.tsindex 4ed714c4..1018b4d1 100644--- a/src/lib/catalog/swap-studio-plan.ts+++ b/src/lib/catalog/swap-studio-plan.ts@@ -14,10 +14,12 @@* 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 { anchorAspect, anchorModel, anchorPrompt, h3Canvas, swapLoraRef } from "./character-swap";+import { CLOUD_TIERS, SHARPEN_COPY, sharpenPrompt, sharpenSteps, type SharpenTier } from "./sharpen";import { MASK_TRACKER } from "./remove-object";import type { PlanStep } from "./shorts";import {+ approvedMask,at,cloudFilmSize,enginePrompt,@@ -321,6 +323,8 @@ export interface SegmentPlanInput {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;+ /** The cloud: a size fal makes from a 768P base (2K, 4K) instead of the shot's own (Sharpen's new version). */+ resolution?: "2K" | "4K";}/** H3's whole seconds for a cloud call (5–15). */@@ -402,6 +406,7 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; finalchain.push({ slot: "images", position: "last" });}const text = enginePrompt(p.prompt, "cloud", shot.who, { swapPictures: boundary && !!p.anchor });+ const size = p.resolution ? ` at ${p.resolution}` : "";steps.push({key: "swap",request: {@@ -412,8 +417,8 @@ export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; finalprompt: text,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: `${label} · swap`, index: of - 2, of },+ params: { duration: cloudCallSeconds(frames), sourceDuration: at(frames), resolution: p.resolution ?? quality, seed: seg.seed },+ step: { label: `${label} · swap${size}`, index: of - 2, of },},after,chain,@@ -439,6 +444,7 @@ export function frozenTakePlan(take: SwapTake,numbers: { shot: number; segment: number; take: number },previous: SegmentPlanInput["previous"],+ resolution?: SegmentPlanInput["resolution"],): { steps: PlanStep[]; final: string } {const f = take.frozen;if (!f) throw new Error("This take wasn't queued from the studio — queue the segment again");@@ -457,6 +463,64 @@ export function frozenTakePlan(mask: f.mask,previous,...(f.keep !== undefined ? { keep: f.keep } : {}),+ ...(resolution ? { resolution } : {}),+ });+}++// ---------------------------------------------------------------------------+// Assemble → Finish → Sharpen (sharpen.ts)++export interface FinishPlanInput {+ project: SwapProject;+ clip: SwapClip;+ shot: SwapShot;+ seg: SwapSegment;+ take: SwapTake;+ numbers: { shot: number; segment: number; take: number };+ /** The size made (sharpenTierFor: never above the film on your GPU; 2K or 4K on the cloud). */+ tier: SharpenTier;+ /** Your GPU: the take's video. */+ video?: string;+ /** The cloud: what the take continued from (as when it was made). */+ previous?: SegmentPlanInput["previous"];+}++/**+ * A chosen take made sharper, on the engine it was made on. Your GPU: its video regenerated at the tier (start sigma 0.8,+ * the take's words and seed) and only the character put back over the clip's 24 fps copy through the mask it was made+ * with (the shot's approved one). The cloud: the same segment made again on fal's H3 at 2K or 4K, with the words, LoRA,+ * references and seed it was queued with.+ */+export function planTakeFinish(p: FinishPlanInput): { steps: PlanStep[]; final: string } {+ const { project, clip, shot, seg, take } = p;+ const f = take.frozen;+ if (!f) throw new Error("This take wasn't queued from the studio — queue the segment again");+ const label = `Shot ${p.numbers.shot} · segment ${p.numbers.segment} · take ${p.numbers.take}`;+ if (take.engine === "cloud") {+ if (!CLOUD_TIERS.includes(p.tier)) throw new Error("The cloud makes 2K or 4K");+ return frozenTakePlan(project, clip, shot, seg, take, p.numbers, p.previous ?? null, p.tier as "2K" | "4K");+ }+ const mask = f.mask ?? approvedMask(shot, "open")?.pieces[0]?.url ?? null;+ if (!mask) throw new Error(SHARPEN_COPY.noMask);+ if (!p.video) throw new Error(`${label} has no video yet`);+ const film = normalizedSize(clip.source.width, clip.source.height);+ if (!film) throw new Error(SHARPEN_COPY.noSize);+ const title = `Character Swap · ${clip.name}`;+ return sharpenSteps({+ key: "",+ label,+ helper: helper(title),+ result: { ...helper(title), title: `${label} · ${p.tier}` },+ tier: p.tier,+ prompt: sharpenPrompt(take.prompt, project.character.description),+ seed: take.seed,+ frames: f.end - f.start,+ take: { url: p.video },+ source: { url: workingClip(clip, "open"), start: at(f.shotStart + f.start) },+ // The mask covers the shot from its first frame.+ mask: { url: mask, start: at(f.start) },+ film,+ canvas: h3Canvas(film.width, film.height, qualityFor(f.settings.renderMp)),});}diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.tsindex afb11653..869cb0c6 100644--- a/src/lib/catalog/swap-studio.ts+++ b/src/lib/catalog/swap-studio.ts@@ -15,6 +15,7 @@*/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 type { SharpenTier } from "./sharpen";import { wholeClipBudget } from "@/lib/av/video-finish";import type { Engine, PixelPoint } from "./types";@@ -219,6 +220,25 @@ export interface SwapTake {frozen?: FrozenTake;/** The studio has looked at its finished result (selected it, or left the selection alone). */settled?: boolean;+ /** Its sharper version (Assemble → Finish → Sharpen), shown beside it until it is picked. */+ finish?: TakeFinish | null;+}++/**+ * A take made sharper (sharpen.ts). Your GPU: the take regenerated and only the character composited over the footage.+ * The cloud: the same segment made again on fal's H3 at 2K or 4K. The assembly uses it once it is picked (`use`).+ */+export interface TakeFinish {+ id: string;+ createdAt: number;+ engine: Engine;+ /** The size asked for, and the size made (your GPU: never above the footage's). */+ asked: SharpenTier;+ tier: SharpenTier;+ genId?: string;+ stepIds?: string[];+ /** Picked after comparing: the assembly uses it instead of the take. */+ use: boolean;}export interface SwapSegment {@@ -1130,6 +1150,11 @@ export interface StudioEstimate {transcribe: Record<string, number | null>;/** Tracking a whole shot's mask. */mask: Record<string, number | null>;+ /**+ * Sharpen for each clip: its chosen takes, their seconds, and what each size costs for all of them (null: unknown or+ * not offered; your GPU: 0).+ */+ sharpen: Record<string, { takes: number; seconds: number; costUsd: Partial<Record<SharpenTier, number | null>>; problem?: string }>;/** One anchor with each model on this engine. */anchors: { id: string; label: string; note: string; costUsd: number | null; offered: boolean }[];notes: string[];@@ -1306,8 +1331,26 @@ export function assemblyPieces(project: SwapProject, clip: SwapClip): { 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] : []));+/** The sharper version a take is assembled with, when one is picked. */+export const usedFinish = (take: Pick<SwapTake, "finish">) => (take.finish?.use ? take.finish : null);++/** The takes an assembly is made of (its identity: the same takes, and the same sharper versions, need no new assembly). */+export const assemblyTakes = (pieces: AssemblyPiece[]) => pieces.flatMap((p) => (p.kind === "take" ? [usedFinish(p.take) ? `${p.take.id}@${usedFinish(p.take)!.id}` : p.take.id] : []));++/** The chosen takes Sharpen works on: every swapped segment's, in the assembly's order. */+export const chosenTakes = (pieces: AssemblyPiece[]) => pieces.flatMap((p) => (p.kind === "take" ? [p] : []));++// ---------------------------------------------------------------------------+// Assemble → Finish++/**+ * Akatz Labs' other Finish (a clean background plate and alpha mattes of the source and the character): their public+ * release can't run it (docs/research/openjutsu-6.md §4.2), so it stays on the page as not available.+ */+export const FINISH_UNAVAILABLE = {+ title: "Clean backplate + alpha",+ reason: "Rebuilds the background without the person and gives your character as a layer of its own, for compositing in an editor. Not available yet.",+} as const;// ---------------------------------------------------------------------------// From Genjutsudiff --git a/src/server/genjutsu.ts b/src/server/genjutsu.tsindex 5653d00a..b689af70 100644--- a/src/server/genjutsu.ts+++ b/src/server/genjutsu.ts@@ -8,6 +8,7 @@ import {CHARACTER_GPU,CHARACTER_LIMITS,CHARACTER_SWAP,+ characterFinish,characterLicenceLine,cutWarning,h3Windows,@@ -18,6 +19,7 @@ import {type CharacterOptions,} from "@/lib/catalog/character-swap";import { ACCESS_PLACE } from "@/lib/model-access";+import { filmSize, sharpenTierFor } from "@/lib/catalog/sharpen";import {chooseMaker,cutsInPart,@@ -124,7 +126,7 @@ export const GenjutsuBodySchema = z.object({mode: z.enum(["motion", "character", "swap", "restyle", "insert"]),modelId: z.string().max(80).optional(),tier: z.enum(["standard", "high"]).optional(),- quality: z.enum(["480p", "720p", "768p", "1080p"]).optional(),+ quality: z.enum(["480p", "720p", "768p", "1080p", "2K", "4K"]).optional(),target: z.enum(["type", "click", "paint"]).optional(),subject: z.string().max(300).optional(),prompt: z.string().max(GENJUTSU.maxPromptChars).optional(),@@ -294,6 +296,15 @@ function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: Remnotes.push(`${am.label} first puts your character into the part's first frame${m.engine === "cloud" && n > 1 ? " (one per piece)" : ""}; if that fails the swap runs without it`);} else if (!m.h3.anchor) notes.push(`${name} runs without an anchor frame`);if (m.engine === "cloud") notes.push("On fal, H3 has no mask: who to swap is said in words, and the whole frame is regenerated around them");+ // 1080p / 2K / 4K (sharpen.ts): what each engine does with the 768p swap.+ const finish = characterFinish(qualityFor(m, body.quality ?? CHARACTER_SWAP.defaultQuality));+ if (finish && m.engine === "cloud") notes.push(`fal's H3 makes ${finish} from a 768P base: the whole frame is drawn at the higher size`);+ if (finish && m.engine === "open") {+ const film = filmSize(source.width, source.height);+ const made = sharpenTierFor("open", finish, film);+ notes.push("The 768p swap is redrawn by Open-H3 Regenerate and only your character is put back over your clip: the background and the sound stay as filmed. Faces can change slightly");+ if (made && made !== finish && film) notes.push(`Your clip is ${film.width}×${film.height}, so it is sharpened at ${made} (never above the clip's own size)`);+ }if (m.engine === "open" && c.who === "index" && !body.points?.length) notes.push("Person numbers follow SAM 3.1's detections, the one it is surest of first — not left to right");if (m.engine === "open" && !m.h3.maskSwitch && c.useMask === false) notes.push(`${name} always regenerates only the person: its graph has no switch for the whole frame`);const warn = cutWarning(cutsInPart(body.cuts, range));diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.tsindex 3601cc11..69d52066 100644--- a/src/server/swap-studio.ts+++ b/src/server/swap-studio.ts@@ -7,6 +7,7 @@ import type { PlanStep } from "@/lib/catalog/shorts";import {assemblyPieces,assemblyTakes,+ chosenTakes,clipNeedsPreview,clipProblem,currentSegments,@@ -39,10 +40,14 @@ import {type SwapSegment,type SwapShot,type SwapTake,+ type TakeFinish,type TranscriptCue,+ usedFinish,} from "@/lib/catalog/swap-studio";import { applyEdit, EditError, type SwapEdit } from "@/lib/catalog/swap-studio-edit";-import { cloudMaskCut, frozenTakePlan, planAnchor, planAssembly, planMask, planNormalize, planPreview, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";+import { cloudMaskCut, frozenTakePlan, planAnchor, planAssembly, planMask, planNormalize, planPreview, planTakeFinish, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";+import { REGEN_MODEL } from "@/lib/catalog/regenerate";+import { COMPOSITE_MODEL, filmSize, SHARPEN_COPY, SHARPEN_TIERS, sharpenOptions, sharpenTierFor, type SharpenTier } from "@/lib/catalog/sharpen";import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";import { ACCESS_PLACE } from "@/lib/model-access";import { createPipeline } from "./chains";@@ -165,7 +170,7 @@ function projectGenIds(p: SwapProject): string[] {for (const a of s.anchors) ids.push(a.genId, ...(a.stepIds ?? []));for (const g of s.segments ?? []) {for (const a of g.anchors) ids.push(a.genId, ...(a.stepIds ?? []));- for (const t of g.takes) ids.push(t.genId, ...(t.stepIds ?? []));+ for (const t of g.takes) ids.push(t.genId, ...(t.stepIds ?? []), t.finish?.genId, ...(t.finish?.stepIds ?? []));}}}@@ -287,20 +292,22 @@ function launchWaiting(project: SwapProject, clip: SwapClip, shot: SwapShot, looreturn out === items ? shot : { ...shot, segments: out };}+/** What a take continues from: the segment right before it (your GPU continues from it alone; the cloud from its last frame). */+function previousOf(shot: SwapShot, take: SwapTake, look: Look): { master?: string; video?: string; frames: number } | null {+ if (!take.frozen || take.frozen.history <= 0) return null;+ const items = shot.segments ?? [];+ const dep = take.dependencies[take.dependencies.length - 1];+ const before = items.find((g) => g.id === dep?.segmentId);+ 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");+ // Your GPU's master holds the take's last `keep` frames (masterKeep); the cloud's take is the segment's length.+ return { master: masterOutput(g)?.url, video: mainOutput(g)?.url, frames: prev.frozen?.keep ?? before.end - before.start };+}+/** Start one take's generations (its segments-before are made). */function launchTake(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, take: SwapTake, shotIndex: number, segIndex: number, look: Look): SwapTake {- const items = shot.segments ?? [];- let previous: { master?: string; video?: string; frames: number } | null = null;- if (take.frozen && take.frozen.history > 0) {- // The segment right before it (your GPU continues from it alone; the cloud from its last frame).- const dep = take.dependencies[take.dependencies.length - 1];- const before = items.find((g) => g.id === dep?.segmentId);- 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");- // 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 previous = previousOf(shot, take, look);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);return { ...take, state: "launched", waitsOn: undefined, genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id) };@@ -529,6 +536,8 @@ export const EditSchema = z.discriminatedUnion("type", [decision: decision.optional(),notes: text(SWAP_STUDIO.maxNotesChars).optional(),remove: z.boolean().optional(),+ /** Use its sharper version in the assembly (or the take itself again). */+ finishUse: z.boolean().optional(),}),z.object({ type: z.literal("anchor-import"), clipId: id, shotId: id, segmentId: id.optional(), url: fileUrl }),z.object({ type: z.literal("remove-anchor"), clipId: id, shotId: id, segmentId: id.optional(), anchorId: id }),@@ -553,6 +562,14 @@ export async function editProject(projectId: string, body: EditBody): Promise<SwmustMatchMode(edit.engine);after.engine = edit.engine;}+ // Only a sharper version that came out can be picked for the assembly.+ if (edit.type === "take" && edit.finishUse) {+ const clip = mustClip(p, edit.clipId);+ const t = currentSegments(mustShot(clip, edit.shotId))+ .find((g) => g.id === edit.segmentId)+ ?.takes.find((k) => k.id === edit.takeId);+ if (!t?.finish || look(t.finish.genId)?.status !== "succeeded") throw new ShortsError("Only a finished sharper version can be used", 422);+ }// Only a take that came out can be chosen.if (edit.type === "take" && edit.select) {const clip = mustClip(p, edit.clipId);@@ -993,9 +1010,11 @@ export function assemble(projectId: string, clipId: string): SwapProject {if (p.engine === "open" && !clip.normalized?.url) throw new ShortsError("The clip is still being prepared at 24 fps — wait for it", 409);const existing: Record<string, string> = {};const videoOf = (piece: Extract<(typeof found.pieces)[number], { kind: "take" }>) => {- const g = look(piece.take.genId);+ // A sharper version picked after comparing goes in instead of the take.+ const finish = usedFinish(piece.take);+ const g = look(finish?.genId ?? piece.take.genId);const url = g?.status === "succeeded" ? mainOutput(g)?.url : undefined;- if (!url) throw new ShortsError("A chosen take's video is missing — make it again", 422);+ if (!url) throw new ShortsError(finish ? "A chosen take's sharper version is missing — use the take, or sharpen it again" : "A chosen take's video is missing — make it again", 422);existing[`take-${piece.take.id}`] = g!.id;return url;};@@ -1006,10 +1025,118 @@ export function assemble(projectId: string, clipId: string): SwapProject {return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, assembly })));}+// ---------------------------------------------------------------------------+// Assemble → Finish → Sharpen (src/lib/catalog/sharpen.ts)++export const SharpenSchema = z.object({ clipId: id, tier: z.enum(SHARPEN_TIERS) });++/** A take's sharper version being made, or made: a new Sharpen at the same size doesn't make it again. */+const finishLive = (t: SwapTake, tier: SharpenTier, look: Look) => {+ const st = look(t.finish?.genId)?.status;+ return !!t.finish && t.finish.tier === tier && !!st && st !== "failed" && st !== "canceled";+};++/** Each chosen take's Sharpen steps at a size (your GPU: from the take's video; the cloud: from what it continued from). */+function finishPlans(p: SwapProject, clip: SwapClip, tier: SharpenTier, look: Look, stand = false) {+ const found = assemblyPieces(p, clip);+ if ("problem" in found) throw new ShortsError(found.problem === "Confirm the clip's shots first" ? found.problem : SHARPEN_COPY.none, 422);+ return chosenTakes(found.pieces).map((piece) => {+ const si = clip.shots.findIndex((s) => currentSegments(s).some((g) => g.id === piece.segmentId));+ const shot = clip.shots[si];+ const items = currentSegments(shot);+ const gi = items.findIndex((g) => g.id === piece.segmentId);+ const seg = items[gi];+ const take = piece.take;+ if (take.engine !== p.engine) throw new ShortsError(`Shot ${si + 1}, segment ${gi + 1}'s take was made on the ${take.engine === "open" ? "open engine" : "cloud"} — make it again on this engine to sharpen it`, 422);+ const g = look(take.genId);+ const video = stand ? "/api/files/placeholder-take.mp4" : g?.status === "succeeded" ? mainOutput(g)?.url : undefined;+ let previous: ReturnType<typeof previousOf> = null;+ if (take.engine === "cloud") previous = stand && take.frozen?.history ? { video: "/api/files/placeholder-take.mp4", frames: take.frozen.history } : previousOf(shot, take, look);+ const plan = planTakeFinish({ project: p, clip, shot, seg, take, numbers: { shot: si + 1, segment: gi + 1, take: seg.takes.findIndex((t) => t.id === take.id) + 1 }, tier, video, previous });+ return { shot, seg, take, plan, seconds: (seg.end - seg.start) / SWAP_STUDIO.fps };+ });+}++/**+ * Sharpen: every chosen take of the clip made sharper at a size (sharpen.ts), each a version beside its take until it is+ * picked in Takes & review. Your GPU: regenerated and composited, never above the size the clip is joined at; the cloud:+ * made again at 2K or 4K on fal's H3. Everything is checked (and priced) before the first one starts.+ */+export function sharpenClip(projectId: string, body: z.infer<typeof SharpenSchema>): SwapProject {+ const p = advanceProject(projectId);+ mustMatchMode(p.engine);+ const clip = mustClip(p, body.clipId);+ const look = lookup();+ const film = filmSize(clip.source.width, clip.source.height, p.engine);+ const tier = sharpenTierFor(p.engine, body.tier, film);+ if (!tier) throw new ShortsError(sharpenOptions(p.engine, film).find((o) => o.tier === body.tier)?.reason ?? SHARPEN_COPY.small, 422);+ if (p.engine === "open") {+ mustOffer(REGEN_MODEL, "open");+ mustOffer(COMPOSITE_MODEL, "open");+ } else mustOffer(STUDIO_MODELS.cloud.swap, "cloud");+ if (p.engine === "open" && !clip.normalized?.url) throw new ShortsError("The clip is still being prepared at 24 fps — wait for it", 409);+ let plans: ReturnType<typeof finishPlans>;+ try {+ plans = finishPlans(p, clip, tier, look);+ } catch (e) {+ if (e instanceof ShortsError) throw e;+ throw new ShortsError((e as Error).message, 422);+ }+ const todo = plans.filter((x) => !finishLive(x.take, tier, look));+ if (!todo.length) throw new ShortsError(`Every chosen take already has a ${tier} version — compare them in Takes & review`, 409);+ let demo: boolean | null = null;+ for (const x of todo) {+ const priced = price(x.plan.steps);+ if (priced.problem) throw new ShortsError(priced.problem, 422);+ if (demo !== null && demo !== priced.demo) throw new ShortsError("Some takes would run as a demo and others for real — connect the missing provider in Settings", 422);+ demo = priced.demo;+ }+ const made = new Map<string, TakeFinish>();+ for (const x of todo) {+ const pipe = run(x.plan.steps);+ made.set(x.take.id, { id: uid("finish-"), createdAt: Date.now(), engine: p.engine, asked: body.tier, tier, genId: pipe.byKey[x.plan.final].id, stepIds: pipe.items.map((g) => g.id), use: false });+ }+ return mutate(projectId, (cur) =>+ mapClip(cur, clip.id, (c) => ({+ ...c,+ shots: c.shots.map((s) => (s.segments ? { ...s, segments: s.segments.map((g) => ({ ...g, takes: g.takes.map((t) => (made.has(t.id) ? { ...t, finish: made.get(t.id)! } : t)) })) } : s)),+ })),+ );+}++/** Sharpen's price for a clip: every chosen take at each size the engine offers (stand-ins where a take isn't made). */+function sharpenEstimate(p: SwapProject, clip: SwapClip, look: Look): { estimate: StudioEstimate["sharpen"][string]; demo: boolean } | null {+ const found = assemblyPieces(p, clip);+ if ("problem" in found) return null;+ const takes = chosenTakes(found.pieces);+ const seconds = Math.round(takes.reduce((n, t) => n + (t.end - t.start) / SWAP_STUDIO.fps, 0) * 100) / 100;+ const film = filmSize(clip.source.width, clip.source.height, p.engine);+ const costUsd: Partial<Record<SharpenTier, number | null>> = {};+ let demo = false;+ let problem: string | undefined;+ for (const o of sharpenOptions(p.engine, film)) {+ if (!o.available) continue;+ try {+ let cost: number | null = 0;+ for (const x of finishPlans(p, clip, o.tier, look, true)) {+ const r = price(x.plan.steps);+ if (r.problem) throw new Error(r.problem);+ if (r.demo) demo = true;+ cost = add(cost, r.costUsd);+ }+ costUsd[o.tier] = cost;+ } catch (e) {+ costUsd[o.tier] = null;+ problem ??= (e as Error).message;+ }+ }+ return { estimate: { takes: takes.length, seconds, costUsd, ...(problem ? { problem } : {}) }, demo };+}+// ---------------------------------------------------------------------------// Stopping other jobs-export const StopSchema = z.object({ kind: z.enum(["mask", "anchor", "assembly", "normalize", "transcribe"]), clipId: id, shotId: id.optional(), segmentId: id.optional(), jobId: id.optional() });+export const StopSchema = z.object({ kind: z.enum(["mask", "anchor", "assembly", "normalize", "transcribe", "finish"]), clipId: id, shotId: id.optional(), segmentId: id.optional(), jobId: id.optional() });export async function stopJob(projectId: string, body: z.infer<typeof StopSchema>): Promise<SwapProject> {const p = mustProject(projectId);@@ -1018,6 +1145,8 @@ export async function stopJob(projectId: string, body: z.infer<typeof StopSchemaif (body.kind === "assembly") ids = [...(clip.assembly?.stepIds ?? []), clip.assembly?.genId];if (body.kind === "normalize") ids = [clip.normalized?.genId];if (body.kind === "transcribe") ids = [clip.transcript?.genId];+ // Sharpen: every sharper version of the clip still being made.+ if (body.kind === "finish") ids = clip.shots.flatMap((s) => currentSegments(s).flatMap((g) => g.takes.flatMap((t) => [...(t.finish?.stepIds ?? []), t.finish?.genId])));if (body.kind === "mask" || body.kind === "anchor") {const shot = mustShot(clip, body.shotId ?? "");const seg = body.segmentId ? currentSegments(shot).find((g) => g.id === body.segmentId) : undefined;@@ -1075,7 +1204,7 @@ export function estimateProject(projectId: string): StudioEstimate {const p = advanceProject(projectId);const look = lookup();const engine = p.engine;- const out: StudioEstimate = { engine, demo: false, free: engine === "open", segments: {}, problems: {}, shots: {}, project: { costUsd: 0, segments: 0 }, assembly: {}, transcribe: {}, mask: {}, anchors: [], notes: [] };+ const out: StudioEstimate = { engine, demo: false, free: engine === "open", segments: {}, problems: {}, shots: {}, project: { costUsd: 0, segments: 0 }, assembly: {}, transcribe: {}, mask: {}, sharpen: {}, anchors: [], notes: [] };const track = (r: { demo: boolean }) => {if (r.demo) out.demo = true;};@@ -1136,6 +1265,11 @@ export function estimateProject(projectId: string): StudioEstimate {track(a);out.assembly[clip.id] = a.costUsd;}+ const sharp = sharpenEstimate(p, working, look);+ if (sharp) {+ if (sharp.demo) out.demo = true;+ out.sharpen[clip.id] = sharp.estimate;+ }}const sample = p.clips[0];if (sample) {diff --git a/tests/character-swap-2k.test.ts b/tests/character-swap-2k.test.tsnew file mode 100644index 00000000..3c61d74d--- /dev/null+++ b/tests/character-swap-2k.test.ts@@ -0,0 +1,385 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { GenInput } from "@/lib/catalog/types";++// Character swap in 2K (package n7-4-character-swap-2k): Genjutsu's 1080p / 2K / 4K and Character Swap Studio's Sharpen,+// on both engines. Your GPU: the 768p swap regenerated (sigma 0.8, never above the footage's size), then only the+// character composited over the footage (video-composite-mask); the cloud: fal's H3 at 2K / 4K, a new version.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-2k-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++const S = await import("@/lib/catalog/sharpen");+const C = await import("@/lib/catalog/character-swap");+const G = await import("@/lib/catalog/genjutsu");+const { DEFAULT_SETTINGS, newShot, assemblyTakes, chosenTakes, usedFinish, FINISH_UNAVAILABLE } = await import("@/lib/catalog/swap-studio");+type SwapClip = import("@/lib/catalog/swap-studio").SwapClip;+type SwapProject = import("@/lib/catalog/swap-studio").SwapProject;+type SwapTake = import("@/lib/catalog/swap-studio").SwapTake;+const { planTakeFinish, planAssembly } = await import("@/lib/catalog/swap-studio-plan");+const { getModel } = await import("@/lib/catalog");+const { estimateCost } = await import("@/lib/catalog/plan");+const { buildPayload } = await import("@/lib/catalog/payload");+const { prepareWorkflow, getWorkflow } = await import("@/server/providers/comfyui");++const ROOT = path.resolve(__dirname, "..");+const hd = { url: "/api/files/uploads/x/clip.mp4", duration: 20, fps: 30, width: 1920, height: 1080, hasAudio: true };+const ref = "/api/files/uploads/x/hero.png";+const maker = (id: string, engine: "open" | "cloud") => G.getMaker(id, engine)!;+const character = (engine: "open" | "cloud", quality: string, o: Partial<Parameters<typeof G.planGenjutsu>[0]> = {}) =>+ G.planGenjutsu({ engine, mode: "character", maker: maker(G.ORIGINALS.character, engine), title: "Swap", source: hd, range: { start: 2, end: 12 }, quality, references: [ref], seed: 42, ...o });+const keys = (p: { steps: { key: string }[] }) => p.steps.map((s) => s.key);+const step = (p: { steps: { key: string; request: GenInput & Record<string, unknown>; after?: string[]; chain?: unknown[] }[] }, key: string) => {+ const s = p.steps.find((x) => x.key === key);+ if (!s) throw new Error(`no step ${key}: ${keys(p).join(", ")}`);+ return s;+};++describe("qualities", () => {+ it("480p and 768p stay H3's own; 1080p, 2K and 4K are finishing sizes of the 768p swap", () => {+ expect(C.CHARACTER_SWAP.qualities).toEqual(["480p", "768p"]);+ expect(C.characterQuality("480p")).toBe("480p");+ for (const q of ["768p", "1080p", "2K", "4K", undefined]) expect(C.characterQuality(q)).toBe("768p");+ expect(["480p", "768p", "720p", undefined].map(C.characterFinish)).toEqual([null, null, null, null]);+ expect(["1080p", "2K", "4K"].map(C.characterFinish)).toEqual(["1080p", "2K", "4K"]);+ // fal has no 1080P: the cloud offers 2K and 4K; your GPU all three.+ expect(C.CHARACTER_QUALITIES).toEqual({ open: ["480p", "768p", "1080p", "2K", "4K"], cloud: ["480p", "768p", "2K", "4K"] });+ expect(maker(G.ORIGINALS.character, "cloud").qualities).toEqual(C.CHARACTER_QUALITIES.cloud);+ expect(maker(G.ORIGINALS.character, "open").qualities).toEqual(C.CHARACTER_QUALITIES.open);+ expect(maker("oss-h3-character-swap-relay", "open").qualities).toEqual(C.CHARACTER_QUALITIES.open);+ // H3 Max Recast keeps its own 768P / 1080P.+ expect(maker("h3-max-recast", "cloud").qualities).toEqual(["768p", "1080p"]);+ });++ it("falResolution for every quality", () => {+ expect(Object.fromEntries(["480p", "720p", "768p", "1080p", "2K", "4K", undefined].map((q) => [String(q), C.falResolution(q)]))).toEqual({+ "480p": "480P",+ "720p": "768P",+ "768p": "768P",+ "1080p": "768P",+ "2K": "2K",+ "4K": "4K",+ undefined: "768P",+ });+ });++ it("Genjutsu asks each maker for what it offers, and the setup code keeps 2K and 4K", () => {+ expect(G.qualityFor(maker(G.ORIGINALS.character, "cloud"), "2K")).toBe("2K");+ expect(G.qualityFor(maker(G.ORIGINALS.character, "cloud"), "1080p")).toBe("768p");+ expect(G.qualityFor(maker(G.ORIGINALS.character, "open"), "1080p")).toBe("1080p");+ expect(G.resolutionWords(maker(G.ORIGINALS.character, "cloud"), "1080p")).toBe("renders up to 768p");+ expect(G.decodeSetup(G.encodeSetup({ mode: "character", quality: "4K" }))?.quality).toBe("4K");+ });+});++describe("prices", () => {+ it("fal's H3 LoRA route per second: 480P $0.0625, 768P $0.075, 2K $0.1625, 4K $0.20; 5 s at 2K = $0.81, 15 s = $2.44", () => {+ expect(S.SWAP_PER_SECOND).toEqual({ "480P": 0.0625, "768P": 0.075, "2K": 0.1625, "4K": 0.2 });+ expect(S.cloudSharpenUsd("2K", 5)).toBe(0.81);+ expect(S.cloudSharpenUsd("2K", 15)).toBe(2.44);+ expect(S.cloudSharpenUsd("4K", 5)).toBe(1);+ // Whole seconds, at least 5 a call.+ expect(S.cloudSharpenUsd("2K", 2)).toBe(0.81);+ expect(S.cloudSharpenUsd("1080p", 5)).toBeNull();+ // The catalog prices the plan's step the same way.+ const m = getModel("fuobe-character-swap")!;+ const cloud = { ...m, engine: "cloud" as const };+ expect(estimateCost(cloud, { resolution: "2K", duration: 5 }, 1, "video-swap")).toBeCloseTo(0.8125, 2);+ expect(estimateCost(cloud, { resolution: "4K", duration: 15 }, 1, "video-swap")).toBeCloseTo(3, 2);+ expect(estimateCost(cloud, { resolution: "768p", duration: 5 }, 1, "video-swap")).toBeCloseTo(0.375, 2);+ });++ it("the cloud's Quality hint carries the price; your GPU's the time", async () => {+ const { qualityHint } = await import("@/components/genjutsu/character-panel");+ expect(qualityHint("cloud", "2K")).toBe("2K and 4K redraw the 768p swap at the higher size. $0.81 for 5 s, $2.44 for 15 s.");+ expect(qualityHint("cloud", "4K")).toBe("2K and 4K redraw the 768p swap at the higher size. $1.00 for 5 s, $3.00 for 15 s.");+ expect(qualityHint("open", "2K")).toMatch(/^1080p, 2K and 4K redraw the 768p swap at the higher size\. Free on your GPU, about 3 min more per 5 s on a 72 GB GPU/);+ expect(qualityHint("open", "480p")).toBe("Faster and cheaper");+ });+});++describe("what each engine makes of a size", () => {+ it("your GPU: never above the footage (joined at most 2048 px a side)", () => {+ const film = S.filmSize(1920, 1080)!;+ expect(film).toEqual({ width: 1920, height: 1080 });+ expect(S.sharpenOptions("open", film).map((o) => [o.tier, o.available])).toEqual([+ ["1080p", true],+ ["2K", false],+ ["4K", false],+ ]);+ expect(S.sharpenOptions("open", film)[1].reason).toBe("Joined at 1920×1080, so 2K adds nothing to the film");+ expect(S.sharpenTierFor("open", "4K", film)).toBe("1080p");+ expect(S.defaultSharpenTier("open", film)).toBe("1080p");+ // A 4K square is kept at 2048 × 2048: 2K fits, 4K doesn't.+ expect(S.sharpenTierFor("open", "4K", S.filmSize(4096, 4096))).toBe("2K");+ // Below 1080p the 768p takes already match it.+ expect(S.sharpenTierFor("open", "2K", S.filmSize(1280, 720))).toBeNull();+ expect(S.sharpenOptions("open", S.filmSize(1280, 720))[0].reason).toBe(S.SHARPEN_COPY.small);+ });++ it("the cloud: 2K and 4K only (no 1080P on fal); 4K adds nothing to a film joined at 2048 px", () => {+ const film = S.filmSize(3840, 2160, "cloud")!;+ expect(film).toEqual({ width: 2048, height: 1152 });+ const o = S.sharpenOptions("cloud", film);+ expect(o.map((x) => [x.tier, x.available])).toEqual([+ ["1080p", false],+ ["2K", true],+ ["4K", false],+ ]);+ expect(o[0].reason).toBe("The cloud makes 2K or 4K");+ expect(o[2].reason).toBe("Joined at 2048×1152, so 4K adds nothing to the film");+ expect(S.sharpenTierFor("cloud", "1080p", film)).toBeNull();+ expect(S.sharpenTierFor("cloud", "4K", film)).toBe("2K");+ // The join note says the size.+ expect(S.joinNote(film)).toBe("The clip is joined at 2048×1152 (up to 2048 px a side). Each sharper take keeps its own size in Takes & review");+ // A small clip is scaled up for merge-videos, but stays below 1080p.+ expect(S.sharpenTierFor("cloud", "2K", S.filmSize(72, 128, "cloud"))).toBeNull();+ });+});++describe("the composite's geometry and windows", () => {+ it("the swap covers its canvas's part of the footage; the regenerate the centre its 16:9 draft kept", () => {+ const film = { width: 1920, height: 1080 };+ const canvas = C.h3Canvas(1920, 1080, "768p");+ const g = S.compositeGeometry(film, canvas);+ expect(g.take.width / g.take.height).toBeCloseTo(canvas.width / canvas.height, 2);+ // H3's canvas for a 1080p clip (1344 × 736) is a little wider than 16:9: the swap covers the full width.+ expect(canvas).toEqual({ width: 1344, height: 736 });+ expect(g.take).toEqual({ width: 1920, height: 1052, x: 0, y: 14 });+ expect(g.region.width / g.region.height).toBeCloseTo(1344 / 768, 2);+ expect(g.region.height).toBeLessThanOrEqual(g.take.height);+ expect(g.region.x).toBe(Math.floor((1920 - g.region.width) / 2));+ // A tall clip: the draft turns.+ const tall = S.compositeGeometry({ width: 1080, height: 1920 }, C.h3Canvas(1080, 1920, "768p"));+ expect(tall.region.height / tall.region.width).toBeCloseTo(1344 / 768, 2);+ // A square clip: the swap fills it, the regenerate is its centre 16:9 band.+ const sq = S.compositeGeometry({ width: 2048, height: 2048 }, { width: 992, height: 992 });+ expect(sq.take).toEqual({ width: 2048, height: 2048, x: 0, y: 0 });+ expect(sq.region).toMatchObject({ width: 2048, x: 0 });+ expect(sq.region.y).toBe(Math.floor((2048 - sq.region.height) / 2));+ expect(S.maskEdge({ width: 1888, height: 1080 })).toEqual({ grow: 9, feather: 13 });+ });++ it("windows: equal, never a sliver, every frame once", () => {+ expect(S.frameWindows(362, 360)).toEqual([+ { from: 0, frames: 181 },+ { from: 181, frames: 181 },+ ]);+ expect(S.frameWindows(240, 72).map((w) => w.frames)).toEqual([60, 60, 60, 60]);+ expect(S.frameWindows(50, 72)).toEqual([{ from: 0, frames: 50 }]);+ });++ it("the regenerate's words are the take's own, without H3's tags", () => {+ expect(S.sharpenPrompt("Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the timing.", "a chrome robot")).toBe(+ "The character: a chrome robot. Replace the selected person in the clip with the character in the reference. Preserve the timing.",+ );+ });+});++describe("Genjutsu's Character swap", () => {+ it("480p and 768p are the swap alone, as before", () => {+ for (const engine of ["open", "cloud"] as const) {+ for (const q of ["480p", "768p"]) {+ const p = character(engine, q);+ expect(keys(p).some((k) => /regen|comp|mask|fit/.test(k))).toBe(false);+ }+ }+ expect(keys(character("open", "768p"))).toEqual(["frame", "anchor", "swap"]);+ });++ it("your GPU at 2K: swap at 768p → mask → the part at 24 fps → regenerate (sigma 0.8, capped at 1080p for a 1080p clip) → composites → join → the sound", () => {+ const p = character("open", "2K");+ expect(keys(p)).toEqual(["frame", "anchor", "swap", "mask", "fit", "sharpen-regen0", "sharpen-comp0", "sharpen-comp1", "sharpen-comp2", "sharpen-comp3", "sharpen-join", "sound"]);+ expect(p.final).toBe("sound");+ expect(p.sound).toBe(true);+ // The swap itself stays 768p and is a step now.+ expect(step(p, "swap").request).toMatchObject({ feature: "genjutsu-step", params: { resolution: "768p" } });+ expect(step(p, "mask").request).toMatchObject({+ modelId: "oss-h3-person-mask",+ inputs: { video: hd.url },+ params: { startTime: 2, endTime: 12, resolution: "768p", matteOutput: "matte", extra: { keyFrame: 0, spanFrames: 240, shotFrames: 240, selection: "largest" } },+ });+ expect(step(p, "fit").request).toMatchObject({ modelId: "oss-fit-clip", params: { startTime: 2, endTime: 12, fps: 24, extra: { width: 1920, height: 1080 } } });+ const regen = step(p, "sharpen-regen0");+ expect(regen.request).toMatchObject({ modelId: "oss-h3-regenerate", op: "upscale-video", params: { resolution: "1080p", seed: 42, extra: { startSigma: 0.8, draftFrom: "h3" } } });+ expect(regen.request.prompt).toMatch(/^Replace the selected person in the clip with the character in the reference/);+ expect(regen.after).toEqual(["swap"]);+ const c1 = step(p, "sharpen-comp1");+ expect(c1.request).toMatchObject({ modelId: "oss-composite-mask", op: "overlay", params: { startTime: 2.5, endTime: 5, extra: { windowStart: 2.5, takeStart: 2.5, maskStart: 2.5 } } });+ expect(c1.after).toEqual(["sharpen-regen0", "fit", "swap", "mask"]);+ expect(c1.chain).toEqual([{ slot: "videos", at: 1 }, { slot: "videos", at: 0 }, { slot: "videos", at: 2 }, { slot: "mask" }]);+ expect(step(p, "sharpen-join").request).toMatchObject({ modelId: "oss-join-encoded", feature: "genjutsu-step" });+ expect(step(p, "sound").request).toMatchObject({ modelId: "oss-mux", feature: "genjutsu", title: "Swap" });+ expect(step(p, "sound").chain).toEqual([{ slot: "video" }, { slot: "audio" }]);+ });++ it("your GPU: a 4K square clip regenerates at 2K; a part over 15 s runs in two regenerate windows; a silent clip ends on the join", () => {+ const sq = character("open", "4K", { source: { ...hd, width: 4096, height: 4096 } });+ expect(step(sq, "sharpen-regen0").request.params).toMatchObject({ resolution: "1440p" });+ const long = character("open", "2K", { range: { start: 0, end: 20 } });+ expect(step(long, "sharpen-regen0").request.params).toMatchObject({ startTime: 0, endTime: 10, sourceDuration: 10 });+ expect(step(long, "sharpen-regen1").request.params).toMatchObject({ startTime: 10, endTime: 20 });+ const quiet = character("open", "1080p", { source: { ...hd, hasAudio: false } });+ expect(quiet.final).toBe("sharpen-join");+ expect(step(quiet, "sharpen-join").request).toMatchObject({ feature: "genjutsu", title: "Swap" });+ expect(() => character("open", "2K", { source: { ...hd, width: 1280, height: 720 } })).toThrow(S.SHARPEN_COPY.small);+ });++ it("the cloud at 2K: the same pieces, fal's H3 asked for 2K (no regenerate, no composite)", () => {+ const p = character("cloud", "2K");+ expect(keys(p).some((k) => /regen|comp/.test(k))).toBe(false);+ const swap = p.steps.find((s) => s.request.modelId === "fuobe-character-swap")!;+ expect(swap.request.params).toMatchObject({ resolution: "2K", duration: 10, seed: 42 });+ // 1080p on the cloud is the 768P swap.+ expect(character("cloud", "1080p").steps.find((s) => s.request.modelId === "fuobe-character-swap")!.request.params).toMatchObject({ resolution: "768p" });+ // The payload fal gets.+ const m = getModel("fuobe-character-swap")!;+ const route = (m.engines?.cloud?.routes ?? m.routes).find((r) => r.provider === "fal")!;+ const payload = buildPayload(route.map!, { ...swap.request.params, prompt: swap.request.prompt, images: [ref] } as never) as Record<string, unknown>;+ expect(payload).toMatchObject({ resolution: "2K", seed: 42, duration: 10 });+ });+});++// ---------------------------------------------------------------------------+// Character Swap Studio: Sharpen per chosen take++const clipOf = (over: Partial<SwapClip> = {}): SwapClip => ({+ id: "clip-1",+ name: "walk",+ source: { url: "/api/files/uploads/x/walk.mp4", name: "walk.mp4", duration: 20, fps: 30, width: 1920, height: 1080, hasAudio: true },+ normalized: { url: "/api/files/outputs/x/walk24.mp4", genId: "g-norm" },+ frames: 480,+ cuts: [],+ detected: null,+ cutsReviewed: true,+ shots: [],+ transcript: null,+ review: "pending",+ reviewNotes: "",+ assembly: null,+ ...over,+});++function studio(engine: "open" | "cloud", frames = 120) {+ const shot = { ...newShot(48, 48 + frames, DEFAULT_SETTINGS, true, () => 0.5), id: "shot-1" };+ const t: SwapTake = {+ id: "take-1",+ createdAt: 1,+ engine,+ state: "launched",+ genId: "g-take",+ signature: "",+ dependencies: [],+ prompt: "Replace the selected person in <Video 1> with the character in <Picture 1>.",+ seed: 7,+ favourite: false,+ decision: "pending",+ notes: "",+ frozen: { reference: ref, shotStart: 48, start: 0, end: frames, history: 0, anchor: null, mask: engine === "open" ? "/api/files/outputs/x/mask.mp4" : null, settings: { ...DEFAULT_SETTINGS }, who: shot.who },+ };+ const seg = { id: "seg-1", start: 0, end: frames, connection: "start" as const, history: 0, seed: 7, prompt: "", performancePrompt: null, dialogue: null, speaker: null, anchorMode: "none" as const, anchor: null, anchors: [], takes: [t], selectedTake: t.id, needsReview: false };+ const s = { ...shot, segments: [seg] };+ const clip = clipOf({ shots: [s] });+ const project: SwapProject = { id: "p1", name: "Demo", engine, character: { image: ref, description: "a chrome robot" }, defaults: { ...DEFAULT_SETTINGS }, clips: [clip], createdAt: 0, updatedAt: 0, revision: 1 };+ return { project, clip, shot: s, seg, take: t };+}++describe("Character Swap Studio: Sharpen", () => {+ it("your GPU: per take, regenerate → composites over the 24 fps copy through the mask it was made with → join", () => {+ const x = studio("open");+ const plan = planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p", video: "/api/files/outputs/x/take.mp4" });+ expect(keys(plan)).toEqual(["regen0", "comp0", "comp1", "join"]);+ expect(plan.final).toBe("join");+ expect(step(plan, "regen0").request).toMatchObject({ modelId: "oss-h3-regenerate", inputs: { video: "/api/files/outputs/x/take.mp4" }, params: { resolution: "1080p", seed: 7, extra: { startSigma: 0.8 } } });+ expect(step(plan, "regen0").request.prompt).toBe("The character: a chrome robot. Replace the selected person in the clip with the character in the reference.");+ const c1 = step(plan, "comp1");+ // The take starts at frame 48 of the clip (2 s) and at frame 0 of the shot's mask.+ expect(c1.request).toMatchObject({+ inputs: { videos: ["/api/files/outputs/x/walk24.mp4", "/api/files/outputs/x/take.mp4"], mask: "/api/files/outputs/x/mask.mp4" },+ params: { startTime: 4.5, endTime: 7, extra: { windowStart: 2.5, takeStart: 2.5, maskStart: 2.5 } },+ });+ expect(c1.chain).toEqual([{ slot: "videos", at: 1 }]);+ expect(step(plan, "join").request).toMatchObject({ feature: "swap-studio-step", title: "Shot 1 · segment 1 · take 1 · 1080p" });+ // No mask, no composite.+ expect(() => planTakeFinish({ ...x, shot: { ...x.shot, approvedMask: null }, take: { ...x.take, frozen: { ...x.take.frozen!, mask: null } }, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p", video: "/v.mp4" })).toThrow(+ S.SHARPEN_COPY.noMask,+ );+ });++ it("the cloud: the segment made again on fal's H3 at 2K, with its words, LoRA, references and seed", () => {+ const x = studio("cloud");+ const plan = planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "2K" });+ expect(keys(plan)).toEqual(["cut", "swap", "fit"]);+ expect(step(plan, "swap").request).toMatchObject({ modelId: "fuobe-character-swap", inputs: { images: [ref] }, params: { resolution: "2K", seed: 7, duration: 5, sourceDuration: 5 } });+ expect(step(plan, "swap").request.loras?.[0]?.file).toMatch(/swap/);+ expect((step(plan, "swap").request.step as { label: string }).label).toMatch(/swap at 2K$/);+ expect(() => planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p" })).toThrow(/2K or 4K/);+ });++ it("the assembly uses a sharper version only once it is picked, and knows when that changed", () => {+ const x = studio("open");+ const pieces = [{ kind: "take" as const, start: 48, end: 168, take: x.take, segmentId: "seg-1" }];+ expect(chosenTakes(pieces)).toHaveLength(1);+ expect(assemblyTakes(pieces)).toEqual(["take-1"]);+ const finish = { id: "finish-1", createdAt: 2, engine: "open" as const, asked: "2K" as const, tier: "1080p" as const, genId: "g-fin", use: false };+ expect(usedFinish({ finish })).toBeNull();+ const used = [{ ...pieces[0], take: { ...x.take, finish: { ...finish, use: true } } }];+ expect(assemblyTakes(used)).toEqual(["take-1@finish-1"]);+ const plan = planAssembly({ engine: "open", clip: x.clip, pieces: used, videoOf: (p) => (usedFinish(p.take) ? "/api/files/outputs/x/sharp.mp4" : "/v.mp4") });+ expect(plan.steps.find((s) => s.request.inputs?.video === "/api/files/outputs/x/sharp.mp4")).toBeTruthy();+ });++ it("Finish keeps Clean backplate + alpha on the page, not available", () => {+ expect(FINISH_UNAVAILABLE.title).toBe("Clean backplate + alpha");+ const page = fs.readFileSync(path.join(ROOT, "src/components/swap-studio/stage-review.tsx"), "utf8");+ expect(page).toMatch(/FINISH_UNAVAILABLE\.title/);+ expect(page).toMatch(/Not available/);+ expect(page).toMatch(/SHARPEN_COPY\.title/);+ expect(S.SHARPEN_COPY.card).toBe(+ "Redraws each chosen take at 2K, then puts only your character back over the original footage. The background and the sound stay as filmed. Faces can change slightly; compare before you keep it.",+ );+ });+});++// ---------------------------------------------------------------------------+// The graph++describe("video-composite-mask", () => {+ const { manifest } = getWorkflow(S.COMPOSITE_WORKFLOW);++ it("is core nodes only, validated, with the bindings the plan fills", () => {+ expect(manifest).toMatchObject({ capability: "overlay", vramGb: 0, validated: true });+ expect(Object.keys(manifest.bindings).sort()).toEqual(+ ["video", "video2", "video3", "mask", "startTime", "windowStart", "takeStart", "maskStart", "duration", "canvasWidth", "canvasHeight", "takeX", "takeY", "regionWidth", "regionHeight", "regionX", "regionY", "maskGrow", "feather", "filenamePrefix"].sort(),+ );+ const graph = JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/video-composite-mask.json"), "utf8")) as Record<string, { class_type: string }>;+ expect(new Set(Object.values(graph).map((n) => n.class_type))).toEqual(+ new Set(["LoadVideo", "Video Slice", "GetVideoComponents", "ImageScale", "ImageToMask", "GrowMask", "FeatherMask", "ImageCompositeMasked", "CreateVideo", "SaveVideo"]),+ );+ expect(getModel(S.COMPOSITE_MODEL)).toMatchObject({ engine: "open", hidden: true });+ });++ it("the provider puts the footage, the regenerate, the swap, the mask and the composite's places on their nodes", async () => {+ const x = studio("open");+ const plan = planTakeFinish({ ...x, numbers: { shot: 1, segment: 1, take: 1 }, tier: "1080p", video: "/take.mp4" });+ const c = step(plan, "comp0").request;+ const extra = c.params!.extra as Record<string, number>;+ const { workflow: wf } = await prepareWorkflow(+ S.COMPOSITE_WORKFLOW,+ { video: undefined, videos: ["src.mp4", "regen.mp4", "take.mp4"], mask: "mask.mp4", startTime: c.params!.startTime, endTime: c.params!.endTime, extra: { ...extra } } as GenInput,+ { generationId: "g1", op: "overlay", upload: async (_d, _t, name) => `up_${name}`, media: () => undefined },+ );+ const at = (node: string, input: string) => (wf as Record<string, { inputs: Record<string, unknown> }>)[node].inputs[input];+ expect([at("source", "file"), at("regen", "file"), at("take", "file"), at("mask", "file")]).toEqual(["src.mp4", "regen.mp4", "take.mp4", "mask.mp4"]);+ expect(at("source_slice", "start_time")).toBe(2);+ expect([at("source_slice", "duration"), at("regen_slice", "duration"), at("take_slice", "duration"), at("mask_slice", "duration")]).toEqual([2.5, 2.5, 2.5, 2.5]);+ expect([at("regen_slice", "start_time"), at("take_slice", "start_time"), at("mask_slice", "start_time")]).toEqual([0, 0, 0]);+ expect([at("take_scaled", "width"), at("take_scaled", "height"), at("base", "x"), at("base", "y")]).toEqual([extra.canvasWidth, extra.canvasHeight, extra.takeX, extra.takeY]);+ expect([at("regen_scaled", "width"), at("regen_mask_img", "height"), at("composite", "x"), at("composite", "y")]).toEqual([extra.regionWidth, extra.regionHeight, extra.regionX, extra.regionY]);+ expect(at("regen_mask_img", "crop")).toBe("center");+ expect([at("take_grow", "expand"), at("regen_feather", "bottom")]).toEqual([extra.maskGrow, extra.feather]);+ });+});