Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Character swap in 2K: sizes offered by the part your character is redrawn in, a running sharper version kept safe and stopped before it is replaced, and why a size can't be picked said on the page

Claude0acac3b2c84f
diff --git a/src/app/api/swap-studio/projects/[id]/sharpen/route.ts b/src/app/api/swap-studio/projects/[id]/sharpen/route.ts
index 7a8c8f4b..bd1a7814 100644
--- a/src/app/api/swap-studio/projects/[id]/sharpen/route.ts
+++ b/src/app/api/swap-studio/projects/[id]/sharpen/route.ts
@@ -5,6 +5,6 @@ import { SharpenSchema, sharpenClip } from "@/server/swap-studio";
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 });
+ return Response.json(await 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.tsx
index aae337cb..7e55ad56 100644
--- a/src/components/genjutsu/character-panel.tsx
+++ b/src/components/genjutsu/character-panel.tsx
@@ -30,7 +30,7 @@ import {
type SwapWho,
} from "@/lib/catalog/character-swap";
import type { GenjutsuTarget, Maker } from "@/lib/catalog/genjutsu";
-import { cloudSharpenUsd, SHARPEN_COPY } from "@/lib/catalog/sharpen";
+import { cloudSharpenUsd, OPEN_TIER_OFF, SHARPEN_COPY, type SharpenTier } from "@/lib/catalog/sharpen";
import type { Engine } from "@/lib/catalog/types";
/** The Quality field's short hint: H3's own sizes in words, a finishing size's price (cloud) or "Free · your GPU". */
@@ -44,11 +44,14 @@ export function qualityShort(engine: Engine, q: CharacterChoice): string {
export function qualityHint(engine: Engine, q: CharacterChoice): string {
const finish = characterFinish(q);
if (!finish) return qualityShort(engine, q);
- 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.`;
+ if (engine === "open") return `${SHARPEN_COPY.hintOpen} Free on your GPU, about 3 min more per 5 s on a 72 GB GPU. ${SHARPEN_COPY.joinOpen}`;
const usd = (s: number) => `$${(cloudSharpenUsd(finish, s) ?? 0).toFixed(2)}`;
return `${SHARPEN_COPY.hint} ${usd(5)} for 5 s, ${usd(15)} for 15 s.`;
}
+/** Why a quality can't be picked on this engine (your GPU's 4K: it joins the clip at up to 2048 px a side), or null. */
+export const qualityOff = (engine: Engine, q: CharacterChoice): string | null => (engine === "open" ? (OPEN_TIER_OFF[q as SharpenTier] ?? null) : null);
+
/** 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;
@@ -96,7 +99,9 @@ export function CharacterControls({
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);
+ // A size this engine can't make worth it (your GPU's 4K) shows as the largest below it that it can.
+ const shown: CharacterChoice = !offered.includes(quality) ? characterQuality(quality) : qualityOff(engine, quality) ? ([...offered].reverse().find((q) => q !== quality && !qualityOff(engine, q) && characterFinish(q)) ?? "768p") : quality;
+ const offReasons = offered.flatMap((q) => (qualityOff(engine, q) ? [{ q, reason: qualityOff(engine, q)! }] : []));
const open = engine === "open";
const anchors = ANCHOR_MODELS[engine];
const who: SwapWho = value.who ?? "largest";
@@ -153,8 +158,19 @@ export function CharacterControls({
{h3 && (
<Field label="Quality" hint={qualityShort(engine, shown)}>
- <Segmented label="Quality" value={shown} onChange={onQuality} options={offered.map((q) => ({ value: q, label: q }))} />
+ <Segmented
+ label="Quality"
+ value={shown}
+ onChange={onQuality}
+ describedBy={offReasons.length ? "character-quality-off" : undefined}
+ options={offered.map((q) => ({ value: q, label: q, disabled: !!qualityOff(engine, q), title: qualityOff(engine, q) ?? undefined }))}
+ />
{characterFinish(shown) && <p className="text-[12px] leading-snug text-pretty text-muted-foreground">{qualityHint(engine, shown)}</p>}
+ {offReasons.length > 0 && (
+ <p id="character-quality-off" className="text-[12px] leading-snug text-pretty text-muted-foreground">
+ {offReasons.map((o) => `${o.q}: ${o.reason}.`).join(" ")}
+ </p>
+ )}
</Field>
)}
diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsx
index 3c9a22c5..9f12724b 100644
--- a/src/components/genjutsu/genjutsu-studio.tsx
+++ b/src/components/genjutsu/genjutsu-studio.tsx
@@ -59,7 +59,7 @@ import { downloadHref, downloadName } from "@/lib/library";
import { keepOffered, offered } from "@/lib/model-access";
import { cn } from "@/lib/utils";
import { refusalShown, toastError } from "@/lib/refusals";
-import { CharacterControls, CharacterFacts } from "./character-panel";
+import { CharacterControls, CharacterFacts, qualityOff } from "./character-panel";
import { useDescribeCharacter, useGenjutsuEstimate, useGenjutsuRun, useTranscribeClip, waitForGeneration, type GenjutsuBody } from "./hooks";
import { LookPicker, type LookSource } from "./look-picker";
import { SetupCode } from "./setup-code";
@@ -188,7 +188,8 @@ export function GenjutsuStudio() {
const cut = cutWarning(partCuts);
const seedNumber = seedOf(seed);
// Character swap's H3 makers take H3's two qualities; the other makers (Recast, P-Video…) Genjutsu's own.
- const askedQuality = isCharacter && maker?.h3 ? charQuality : quality;
+ // A size this engine can't make worth it (your GPU's 4K) is asked as 2K, as the picker shows it.
+ const askedQuality = isCharacter && maker?.h3 ? (qualityOff(engine, charQuality) ? "2K" : charQuality) : quality;
// "Describe my character" (the engine's text model) and "Use the clip's words" (one transcription of the clip; any
// part takes its own lines from it, so it is kept per clip).
diff --git a/src/components/shorts/ui.tsx b/src/components/shorts/ui.tsx
index 36b9af51..0577eeb8 100644
--- a/src/components/shorts/ui.tsx
+++ b/src/components/shorts/ui.tsx
@@ -16,18 +16,21 @@ export function Segmented<T extends string | number>({
options,
onChange,
className,
+ describedBy,
}: {
label: string;
value: T;
options: { value: T; label: string; hint?: string; disabled?: boolean; title?: string }[];
onChange: (v: T) => void;
className?: string;
+ /** The id of text that says more (why some options are turned off). */
+ describedBy?: string;
}) {
// The Tab stop is the checked option, or the first one that can be picked when it's turned off
// (a disabled button can't take focus, and the whole group would be skipped).
const stop = options.some((o) => o.value === value && !o.disabled) ? value : options.find((o) => !o.disabled)?.value;
return (
- <div role="radiogroup" aria-label={label} onKeyDown={radioKeys} className={cn("flex w-full rounded-full bg-muted p-0.5", className)}>
+ <div role="radiogroup" aria-label={label} aria-describedby={describedBy} onKeyDown={radioKeys} className={cn("flex w-full rounded-full bg-muted p-0.5", className)}>
{options.map((o) => (
<button
key={String(o.value)}
diff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsx
index 86ce466d..b7d08584 100644
--- a/src/components/swap-studio/stage-review.tsx
+++ b/src/components/swap-studio/stage-review.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Ban, Download, Film, Library, Loader2, Play, Sparkles, Star } from "lucide-react";
+import { Download, Film, Library, Loader2, Play, Sparkles, Star } from "lucide-react";
import Link from "next/link";
import { useRef, useState } from "react";
import { toast } from "sonner";
@@ -9,8 +9,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
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 { characterLicenceLine, h3Canvas } from "@/lib/catalog/character-swap";
import { defaultSharpenTier, filmSize, gpuMinutes, joinNote, SHARPEN_COPY, sharpenOptions, type SharpenTier } from "@/lib/catalog/sharpen";
import {
assemblyPieces,
@@ -18,7 +17,6 @@ import {
chosenTakes,
currentSegments,
DECISION_LABELS,
- FINISH_UNAVAILABLE,
jobState,
secondsLabel,
SWAP_STUDIO,
@@ -146,25 +144,23 @@ function FinishVersion({ take, gens, onUse }: { take: SwapTake; gens: Record<str
);
}
-/**
- * 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).
- */
+/** Assemble → Finish: "Sharpen to 1080p / 2K / 4K" (runnable: the size, its price or GPU time, Run). */
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);
+ // Your GPU redraws the character inside the part of H3's canvas the regenerate keeps.
+ const canvas = film ? h3Canvas(film.width, film.height, "768p") : undefined;
+ const options = sharpenOptions(engine, film, canvas);
+ const fallback = defaultSharpenTier(engine, film, canvas);
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 busy = chosen.some((p) => p.take.finish && ["queued", "running"].includes(jobState(p.take.finish.genId, p.take.finish.stepIds, gens).status));
// Every chosen take has a version at this size made or on its way: nothing for Sharpen to do.
const allMade = chosen.length > 0 && finishes.length === chosen.length && states.every((x) => x !== "failed" && x !== "canceled" && x !== "missing");
const ready = states.filter((x) => x === "succeeded").length;
@@ -174,64 +170,63 @@ function FinishPanel({ id, project, clip, gens, estimate }: Pick<StageProps, "id
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);
+ const shownTier = tier ?? (engine === "cloud" ? "2K" : "1080p");
+ // Why a size can't be picked, said under the picker (a turned-off button can't take focus or show a tooltip on touch).
+ const off = problem ? [] : options.filter((o) => !o.available && o.reason);
+ const offId = `sharpen-off-${clip.id}`;
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>
+ <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(shownTier) : SHARPEN_COPY.cardCloud(shownTier)}</p>
+ <SizePicker
+ label="Sharpen to"
+ value={shownTier}
+ onChange={setPicked}
+ describedBy={off.length ? offId : undefined}
+ options={options.map((o) => ({ value: o.tier, label: o.tier, disabled: !o.available, title: o.reason }))}
+ />
+ {off.length > 0 && (
+ <ul id={offId} className="space-y-0.5 text-[12px] leading-snug text-pretty text-muted-foreground">
+ {off.map((o) => (
+ <li key={o.tier}>
+ <span className="font-medium text-foreground">{o.tier}:</span> {o.reason}
+ </li>
+ ))}
+ </ul>
+ )}
+ {chosen.length > 0 && (
+ <p className="text-[12px] text-muted-foreground">
+ {chosen.length} chosen take{chosen.length === 1 ? "" : "s"} · {Math.round(seconds * 10) / 10} s{tier ? ` · ${SHARPEN_COPY.model(engine, tier)}` : ""}
+ </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 || allMade}
+ 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>
)}
- {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 || allMade}
- 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}` : ""}
+ {busy && (
+ <Button size="sm" variant="ghost" className="h-8 rounded-full" onClick={() => stop.mutate({ kind: "finish", clipId: clip.id })}>
+ Stop
</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>
+ )}
+ </div>
+ </section>
</Panel>
);
}
@@ -318,7 +313,7 @@ export function ReviewStage(props: StageProps) {
);
}
-/** Assemble: the chosen takes over the original timeline with the clip's own sound, and Finish (Sharpen; the backplate not available). */
+/** Assemble: the chosen takes over the original timeline with the clip's own sound, and Finish (Sharpen). */
export function AssembleStage({ id, project, clip, gens, estimate }: StageProps) {
const assemble = useAssemble(id);
const stop = useStopJob(id);
diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.ts
index 75848e25..9ed479ba 100644
--- a/src/lib/catalog/genjutsu.ts
+++ b/src/lib/catalog/genjutsu.ts
@@ -1221,8 +1221,10 @@ export function h3Extra(c: CharacterOptions | undefined): Record<string, unknown
*/
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);
+ // H3's canvas the swap is made at: your character is redrawn inside the part of it the regenerate keeps.
+ const canvas = h3Canvas(input.source.width!, input.source.height!, quality);
+ const tier = sharpenTierFor("open", asked, film, canvas);
if (!tier) throw new Error(SHARPEN_COPY.small);
const c = input.character ?? {};
const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };
@@ -1236,7 +1238,7 @@ function openFinish(input: GenjutsuPlanInput, asked: SharpenTier, quality: strin
key: "mask",
request: {
...helper,
- modelId: FINISH_TOOLS.mask,
+ modelId: SHARPEN_TOOLS.mask,
op: "bg-remove-video",
prompt: (typeof h3.maskPrompt === "string" && h3.maskPrompt) || "person",
inputs: { video: input.source.url },
@@ -1260,7 +1262,7 @@ function openFinish(input: GenjutsuPlanInput, asked: SharpenTier, quality: strin
});
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 } },
+ request: { ...helper, modelId: SHARPEN_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({
@@ -1277,14 +1279,14 @@ function openFinish(input: GenjutsuPlanInput, asked: SharpenTier, quality: strin
source: { after: "fit", start: 0 },
mask: { after: "mask", start: 0 },
film,
- canvas: h3Canvas(input.source.width!, input.source.height!, quality),
+ canvas,
});
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 } },
+ request: { ...base, modelId: SHARPEN_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" }],
});
@@ -1293,7 +1295,7 @@ function openFinish(input: GenjutsuPlanInput, asked: SharpenTier, quality: strin
}
/** 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;
+export const SHARPEN_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,
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 12468b34..7977f7fe 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -791,8 +791,8 @@ const NEEDS: Partial<
"extract-frames": { video: true, msg: "Add the video to take frames from" },
"images-to-video": { images: 1, msg: "Add the images, in order" },
overlay: { images: 2, msg: "Add the picture and the overlay to put on it" },
- // Character swap in 2K: the footage, the redrawn swap and the swap (the person's mask goes in inputs.mask).
- composite: { videos: 2, msg: "Add the footage and the redrawn clip to put the character back over it" },
+ // Character swap in 2K: the footage, the redrawn swap and the swap, and the person's mask (video-composite-mask).
+ composite: { videos: 3, mask: true, msg: "Add the footage, the redrawn clip, the swap and the person's mask to put the character back over it" },
// N7-5 (the open engine also needs the browser's render along the path: its model's options.requires.video)
"camera-path": { images: 1, msg: "Add the still to film along the path" },
};
diff --git a/src/lib/catalog/sharpen.ts b/src/lib/catalog/sharpen.ts
index fe5fd0e0..b734ac3c 100644
--- a/src/lib/catalog/sharpen.ts
+++ b/src/lib/catalog/sharpen.ts
@@ -52,14 +52,21 @@ 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.",
+ /** Your GPU: only the character is redrawn, at the size picked. */
+ card: (tier: string) =>
+ `Redraws each chosen take at ${tier} with Open-H3 Regenerate, 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.",
+ cardCloud: (tier: string) =>
+ `Makes each chosen take again at ${tier} 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.`,
+ /** The model each engine sharpens with, for the takes line. */
+ model: (engine: Engine, tier: string) => (engine === "open" ? `Open-H3 Regenerate at ${tier}` : `MiniMax H3 at ${tier}`),
/** 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.",
+ hintOpen: "1080p and 2K redraw the 768p swap at the higher size.",
+ /** Your GPU's limit, in Genjutsu's Quality hint. */
+ joinOpen: `Your GPU joins the clip at up to ${FILM_MAX} px a side, so 2K needs a clip larger than 1080p.`,
+ /** fal's 4K made in pieces: merge-videos joins them at up to 2048 px a side. */
+ joinCloud4k: `A part over 15 s is made in pieces, and the pieces are joined at up to ${FILM_MAX} px a side`,
/** The version beside a take, and its switch. */
version: (tier: string) => `${tier} version`,
pick: (tier: string) => `Use the ${tier} version`,
@@ -95,36 +102,92 @@ export interface SharpenOption {
}
const sizeWords = (f: { width: number; height: number }) => `${f.width}×${f.height}`;
+const below = (tier: SharpenTier): SharpenTier | null => SHARPEN_TIERS[SHARPEN_TIERS.indexOf(tier) - 1] ?? null;
/**
- * 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.
+ * The part of the film your GPU redraws the character in: the centre the regenerate's 16:9 / 9:16 draft keeps of H3's
+ * canvas (compositeGeometry's region). Without the canvas, the film's own shape stands in for it (H3's canvas is the
+ * clip's shape on a 32 px grid).
*/
-export function sharpenOptions(engine: Engine, film: { width: number; height: number } | null): SharpenOption[] {
+export function redrawnRegion(film: { width: number; height: number }, canvas?: { width: number; height: number }): { width: number; height: number } {
+ const { region } = compositeGeometry(film, canvas ?? film);
+ return { width: region.width, height: region.height };
+}
+
+/** The longest shorter side that part can have: the draft's 1.75 shape inside a film of at most 2048 px a side. */
+const REGION_MAX_SHORT = Math.floor((FILM_MAX * 768) / 1344);
+
+/**
+ * The tiers your GPU can never make worth it, whatever the clip: the part redrawn is at most 2048 × 1170, so 4K adds
+ * nothing over 2K. With the reason, in words.
+ */
+export const OPEN_TIER_OFF: Partial<Record<SharpenTier, string>> = Object.fromEntries(
+ SHARPEN_TIERS.filter((t) => below(t) && REGION_MAX_SHORT <= SHARPEN_SHORT_EDGE[below(t)!]).map((t) => [
+ t,
+ `Your GPU joins the clip at up to ${FILM_MAX} px a side, so ${t} adds nothing over ${below(t)}`,
+ ]),
+);
+
+/**
+ * What each tier does for a film of this size on an engine. The cloud redraws the whole frame and offers what fal makes
+ * (2K, 4K) where the join keeps it. Your GPU redraws only the character, inside the part of the frame the regenerate
+ * keeps (`canvas`: H3's canvas the swap was made at): 1080p is its base size, and a larger size is offered when that
+ * part is taller than the size below it (so it adds detail the smaller one can't).
+ */
+export function sharpenOptions(engine: Engine, film: { width: number; height: number } | null, canvas?: { width: number; height: number }): SharpenOption[] {
const short = film ? Math.min(film.width, film.height) : 0;
+ const region = film ? redrawnRegion(film, canvas) : null;
+ const regionShort = region ? Math.min(region.width, region.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 (engine === "open" && OPEN_TIER_OFF[tier]) return { tier, available: false, reason: OPEN_TIER_OFF[tier] };
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` };
+ if (engine === "cloud") {
+ // The cloud's 2K is the smallest it makes: always worth it over 768p, joined at the film's size.
+ if (tier === "2K" || 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` };
+ }
+ const lower = below(tier);
+ if (!lower || regionShort > SHARPEN_SHORT_EDGE[lower]) return { tier, available: true };
+ return {
+ tier,
+ available: false,
+ reason: `Your character is redrawn in a ${sizeWords(region!)} part of the frame (the clip is joined at up to ${FILM_MAX} px a side), so ${tier} adds nothing over ${lower}`,
+ };
});
}
/** 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);
+export function sharpenTierFor(engine: Engine, asked: SharpenTier, film: { width: number; height: number } | null, canvas?: { width: number; height: number }): SharpenTier | null {
+ const ok = sharpenOptions(engine, film, canvas).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 tier picked first. The cloud: 2K where it is available, else the largest that is. Your GPU: the largest the
+ * redrawn part holds in full (a larger one costs GPU time for little more), else the smallest available.
+ */
+export function defaultSharpenTier(engine: Engine, film: { width: number; height: number } | null, canvas?: { width: number; height: number }): SharpenTier | null {
+ const ok = sharpenOptions(engine, film, canvas).filter((o) => o.available);
+ if (engine === "cloud" || !film) return ok.find((o) => o.tier === "2K")?.tier ?? ok.at(-1)?.tier ?? null;
+ const r = redrawnRegion(film, canvas);
+ const short = Math.min(r.width, r.height);
+ return [...ok].reverse().find((o) => SHARPEN_SHORT_EDGE[o.tier] <= short)?.tier ?? ok[0]?.tier ?? null;
+}
+
+/**
+ * Why your GPU sharpens a clip at a smaller size than asked: the clip's own size, the 2048 px join, and the part the
+ * character is redrawn in. Null when it makes what was asked.
+ */
+export function openCapNote(source: { width?: number; height?: number }, asked: SharpenTier, canvas?: { width: number; height: number }): string | null {
+ const film = filmSize(source.width, source.height);
+ const made = sharpenTierFor("open", asked, film, canvas);
+ if (!film || !made || made === asked) return null;
+ const r = redrawnRegion(film, canvas);
+ const joined = film.width !== source.width || film.height !== source.height ? `, joined at ${sizeWords(film)} (up to ${FILM_MAX} px a side)` : ` (clips are joined at up to ${FILM_MAX} px a side)`;
+ return `Your clip is ${source.width}×${source.height}${joined}, and your character is redrawn in a ${sizeWords(r)} part of it, so it is sharpened at ${made}`;
}
/** The join's note: what a sharper take is joined at. */
@@ -164,18 +227,35 @@ function centre(frame: { width: number; height: number }, aspect: number): { wid
/** The draft shape Open-H3 Regenerate keeps of an H3 clip: 1344 × 768 (turned for a tall one). */
const DRAFT = { width: 1344, height: 768 };
+/**
+ * The rows (columns, for a tall clip) each tier keeps of the grid it is drawn on: the draft is stretched to 1920 × 1088,
+ * 2560 × 1440 or 3840 × 2176, and the regenerate's finish keeps the centre 1080 of 1088 (2160 of 2176) rows.
+ */
+const REGEN_TRIM: Record<SharpenTier, { kept: number; drawn: number }> = { "1080p": { kept: 1080, drawn: 1088 }, "2K": { kept: 1440, drawn: 1440 }, "4K": { kept: 2160, drawn: 2176 } };
+
/**
* 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.
+ * clip to its canvas), the regenerate the centre of that its 16:9 or 9:16 draft kept (`region`: it stretches the draft
+ * to its grid and keeps the centre rows of it, so at 1080p and 4K it covers the centre 1080 / 1088 of the region's
+ * height, or width for a tall clip: `regen`, at `trim` inside the region). All centred.
*/
-export function compositeGeometry(film: { width: number; height: number }, canvas: { width: number; height: number }): { take: Box; region: Box } {
+export function compositeGeometry(
+ film: { width: number; height: number },
+ canvas: { width: number; height: number },
+ tier: SharpenTier = "2K",
+): { take: Box; region: Box; regen: Box; trim: { x: number; y: number } } {
const t = centre(film, canvas.width / canvas.height);
- const draft = canvas.height > canvas.width ? DRAFT.height / DRAFT.width : DRAFT.width / DRAFT.height;
+ const tall = canvas.height > canvas.width;
+ const draft = tall ? 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) } };
+ const region = { ...r, x: tx + Math.floor((t.width - r.width) / 2), y: ty + Math.floor((t.height - r.height) / 2) };
+ const k = REGEN_TRIM[tier].kept / REGEN_TRIM[tier].drawn;
+ const width = tall ? Math.round(r.width * k) : r.width;
+ const height = tall ? r.height : Math.round(r.height * k);
+ const trim = { x: Math.floor((r.width - width) / 2), y: Math.floor((r.height - height) / 2) };
+ return { take: { ...t, x: tx, y: ty }, region, regen: { width, height, x: region.x + trim.x, y: region.y + trim.y }, trim };
}
/** The mask's grown and feathered edge, in the region's pixels (about 0.8 % and 1.2 % of its shorter side). */
@@ -257,7 +337,7 @@ const fill = (input: StepInput, slot: ChainSlot): { after?: string; chain?: Chai
*/
export function sharpenSteps(s: SharpenStepsInput): { steps: PlanStep[]; final: string } {
const steps: PlanStep[] = [];
- const geo = compositeGeometry(s.film, s.canvas);
+ const geo = compositeGeometry(s.film, s.canvas, s.tier);
const edge = maskEdge(geo.region);
const regen = frameWindows(s.frames, REGEN_WINDOW_SECONDS * FPS);
const parts: string[] = [];
@@ -320,10 +400,15 @@ export function sharpenSteps(s: SharpenStepsInput): { steps: PlanStep[]; final:
canvasHeight: geo.take.height,
takeX: geo.take.x,
takeY: geo.take.y,
+ // The mask is cut to the region the draft kept, then to the rows the regenerate kept of it.
regionWidth: geo.region.width,
regionHeight: geo.region.height,
- regionX: geo.region.x,
- regionY: geo.region.y,
+ regenWidth: geo.regen.width,
+ regenHeight: geo.regen.height,
+ regenX: geo.regen.x,
+ regenY: geo.regen.y,
+ trimX: geo.trim.x,
+ trimY: geo.trim.y,
maskGrow: edge.grow,
feather: edge.feather,
},
diff --git a/src/lib/catalog/sketch.ts b/src/lib/catalog/sketch.ts
index e6767594..e3738fe2 100644
--- a/src/lib/catalog/sketch.ts
+++ b/src/lib/catalog/sketch.ts
@@ -16,8 +16,9 @@ export function applySketch(req: GenerationRequest, model: ModelDef): { request:
const images = [...(i.images ?? [])];
const { mask, sketch, ...rest } = i;
- // Video erasers, swaps and inserts read the mask themselves (a first-frame PNG or a mask video): it stays as it is.
- if (mask && model.kind === "video" && (["remove-object", "video-swap", "video-insert"] as const).some(has)) return { request: req };
+ // Video erasers, swaps and inserts read the mask themselves (a first-frame PNG or a mask video), as does the Character
+ // swap's composite (the person's mask video): it stays as it is.
+ if (mask && model.kind === "video" && (["remove-object", "video-swap", "video-insert", "composite"] as const).some(has)) return { request: req };
// Inpaint: a mask (white = change) and, for models without a mask input, a red-tinted copy.
if (mask) {
if (model.kind === "image" && has("inpaint")) {
diff --git a/src/lib/catalog/swap-studio-edit.ts b/src/lib/catalog/swap-studio-edit.ts
index 949a522d..5070983e 100644
--- a/src/lib/catalog/swap-studio-edit.ts
+++ b/src/lib/catalog/swap-studio-edit.ts
@@ -33,6 +33,7 @@ import {
type SwapSegment,
type SwapSettings,
type SwapShot,
+ type SwapTake,
type WhoToSwap,
} from "./swap-studio";
import type { Engine } from "./types";
@@ -144,9 +145,12 @@ function mustShot(c: SwapClip, id: string): SwapShot {
return s;
}
-/** Whether a shot has a take still being made (or waiting to be). */
+/** Whether a take's sharper version (Assemble → Finish → Sharpen) is still being made. */
+export const finishBusy = (t: SwapTake, active: (genId: string) => boolean): boolean => !!t.finish && [...(t.finish.stepIds ?? []), t.finish.genId].some((id) => !!id && active(id));
+
+/** Whether a shot has a take still being made (or waiting to be), or a take's sharper version still being made. */
export function shotBusy(shot: SwapShot, active: (genId: string) => boolean): boolean {
- return (shot.segments ?? []).some((g) => g.takes.some((t) => t.state === "waiting" || (t.state === "launched" && !!t.genId && active(t.genId))));
+ return (shot.segments ?? []).some((g) => g.takes.some((t) => t.state === "waiting" || (t.state === "launched" && !!t.genId && active(t.genId)) || finishBusy(t, active)));
}
const mapClip = (p: SwapProject, id: string, f: (c: SwapClip) => SwapClip): SwapProject => ({ ...p, clips: p.clips.map((c) => (c.id === id ? f(c) : c)) });
@@ -315,6 +319,7 @@ export function applyEdit(project: SwapProject, edit: SwapEdit, o: { active: (ge
if (edit.remove) {
const t = next.takes.find((k) => k.id === edit.takeId);
if (t && (t.state === "waiting" || (t.genId && o.active(t.genId)))) throw new Error("Stop the take before removing it");
+ if (t && finishBusy(t, o.active)) throw new Error("Its sharper version is still being made — stop it in Assemble first");
return removeTake(next, edit.takeId);
}
if (edit.select) next = selectTake(next, edit.takeId);
diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.ts
index 869cb0c6..6583c01d 100644
--- a/src/lib/catalog/swap-studio.ts
+++ b/src/lib/catalog/swap-studio.ts
@@ -15,7 +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 { filmSize, type SharpenTier } from "./sharpen";
import { wholeClipBudget } from "@/lib/av/video-finish";
import type { Engine, PixelPoint } from "./types";
@@ -412,24 +412,13 @@ export function clipProblem(c: { name?: string; duration?: number; bytes?: numbe
* The size the normaliser keeps: the clip's own, on even numbers, at most 2048 px a side (the fit graph's limit;
* H3 works at 1 MP at most anyway).
*/
-export function normalizedSize(width?: number, height?: number): { width: number; height: number } | null {
- if (!width || !height) return null;
- const k = Math.min(1, 2048 / width, 2048 / height);
- const even = (n: number) => Math.max(2, Math.floor((n * k) / 2) * 2);
- return { width: even(width), height: even(height) };
-}
+export const normalizedSize = (width?: number, height?: number) => filmSize(width, height, "open");
/**
* The cloud assembly's frame: the clip's own shape on even numbers within fal merge-videos' 512–2048 px (every piece,
* the clip's own and H3's 480p / 768p takes, is scaled to it before the join). Null when the clip's size is unknown.
*/
-export function cloudFilmSize(width?: number, height?: number): { width: number; height: number } | null {
- if (!width || !height) return null;
- // Down to 2048 on the long side; up towards 512 on the short side (as far as the long side allows).
- const scale = Math.min(2048 / Math.max(width, height), Math.max(1, 512 / Math.min(width, height)));
- const even = (n: number) => Math.max(2, Math.round((n * scale) / 2) * 2);
- return { width: even(width), height: even(height) };
-}
+export const cloudFilmSize = (width?: number, height?: number) => filmSize(width, height, "cloud");
/** Whether the page needs a copy of a clip to play it (the cloud keeps the upload as filmed; your GPU makes its 24 fps copy anyway). */
export const clipNeedsPreview = (engine: Engine, clip: Pick<SwapClip, "source">) => engine === "cloud" && (clip.source.playable === false || clipExtension(clip.source.name ?? clip.source.url) === "avi");
@@ -1340,18 +1329,6 @@ export const assemblyTakes = (pieces: AssemblyPiece[]) => pieces.flatMap((p) =>
/** 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 Genjutsu
diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.ts
index 6291697f..01860897 100644
--- a/src/server/genjutsu.ts
+++ b/src/server/genjutsu.ts
@@ -9,6 +9,7 @@ import {
CHARACTER_LIMITS,
CHARACTER_SWAP,
characterFinish,
+ h3Canvas,
characterLicenceLine,
cutWarning,
h3Windows,
@@ -19,7 +20,7 @@ import {
type CharacterOptions,
} from "@/lib/catalog/character-swap";
import { ACCESS_PLACE } from "@/lib/model-access";
-import { filmSize, SHARPEN_SIGMA_RANGE, sharpenTierFor } from "@/lib/catalog/sharpen";
+import { openCapNote, SHARPEN_COPY, SHARPEN_SIGMA_RANGE } from "@/lib/catalog/sharpen";
import {
chooseMaker,
cutsInPart,
@@ -300,12 +301,16 @@ function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: Rem
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 === "cloud") {
+ notes.push(`fal's H3 makes ${finish} from a 768P base: the whole frame is drawn at the higher size`);
+ // Pieces are joined by fal's merge-videos, at up to 2048 px a side: only a single piece keeps its 4K.
+ if (finish === "4K" && n > 1) notes.push(SHARPEN_COPY.joinCloud4k);
+ }
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)`);
+ const canvas = source.width && source.height ? h3Canvas(source.width, source.height, CHARACTER_SWAP.defaultQuality) : undefined;
+ const capped = openCapNote(source, finish, canvas);
+ if (capped) notes.push(capped);
}
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`);
diff --git a/src/server/gpu/tools.ts b/src/server/gpu/tools.ts
index bdc1de81..4fda7a2d 100644
--- a/src/server/gpu/tools.ts
+++ b/src/server/gpu/tools.ts
@@ -12,6 +12,7 @@ import { REMOVE_TOOLS } from "@/lib/catalog/remove-object";
import { RESTORE, RESTORE_OPEN_JOIN } from "@/lib/catalog/restore";
import { REGEN_DEFAULT_TIER, REGEN_JOIN, REGEN_MODEL, regenerateGraphLoras } from "@/lib/catalog/regenerate";
import { COMPOSITE_MODEL } from "@/lib/catalog/sharpen";
+import { ORIGINALS, SHARPEN_TOOLS } from "@/lib/catalog/genjutsu";
import { libraryEntry, loraEntry, loraRef, needsToken } from "@/lib/catalog/loras";
import { ANGLES_2511_LORA } from "@/lib/catalog/open-tools";
import { presetRoutes, recipeRoute } from "@/lib/catalog/preset-recipes";
@@ -253,16 +254,21 @@ export const STUDIO_ROWS: StudioRowDef[] = [
{ modelId: REGEN_JOIN, op: "concat" },
],
},
- // n7-4: the Character swap at 1080p / 2K / 4K (Genjutsu, and Sharpen in Character Swap Studio's Finish): the swap
- // regenerated, only the character composited over the footage, the windows joined.
+ // n7-4: the Character swap at 1080p / 2K / 4K (Genjutsu, and Sharpen in Character Swap Studio's Finish): the 768p swap,
+ // the person's mask (SAM 3.1 on H3 Relay's graph), the part at 24 fps, the swap regenerated, only the character
+ // composited over the footage, the windows joined and the part's sound put back.
{
href: "/genjutsu?mode=character",
label: "Character swap in 2K",
group: "Video tools",
steps: [
+ { modelId: ORIGINALS.character, op: "video-swap" },
+ { modelId: SHARPEN_TOOLS.mask, op: "bg-remove-video" },
+ { modelId: SHARPEN_TOOLS.fit, op: "trim" },
{ modelId: REGEN_MODEL, op: "upscale-video" },
{ modelId: COMPOSITE_MODEL, op: "composite" },
{ modelId: REGEN_JOIN, op: "concat" },
+ { modelId: SHARPEN_TOOLS.mux, op: "mux" },
],
},
{ href: "/upscale/fps", label: "FPS boost", group: "Video tools", config: S.FPS_BOOST_STUDIO },
diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.ts
index 9e515e64..6ea0a918 100644
--- a/src/server/swap-studio.ts
+++ b/src/server/swap-studio.ts
@@ -1,7 +1,7 @@
import "server-only";
import { z } from "zod";
import { getModel } from "@/lib/catalog";
-import { ANCHOR_MODELS, anchorModel, characterLicenceLine, SWAP_LORAS, swapLoraRef, TURBO_LORA } from "@/lib/catalog/character-swap";
+import { ANCHOR_MODELS, anchorModel, CHARACTER_SWAP, characterLicenceLine, h3Canvas, SWAP_LORAS, swapLoraRef, TURBO_LORA } from "@/lib/catalog/character-swap";
import { scalePoints } from "@/lib/catalog/remove-object";
import type { PlanStep } from "@/lib/catalog/shorts";
import {
@@ -1036,6 +1036,12 @@ export function assemble(projectId: string, clipId: string): SwapProject {
export const SharpenSchema = z.object({ clipId: id, tier: z.enum(SHARPEN_TIERS) });
+/** The generations of a take's sharper version (its steps and its result). */
+const finishIds = (f: TakeFinish | null | undefined): string[] => (f ? [...(f.stepIds ?? []), ...(f.genId ? [f.genId] : [])] : []);
+
+/** H3's canvas a film's takes are made at: your GPU redraws the character inside the part of it the regenerate keeps. */
+const sharpenCanvas = (film: { width: number; height: number } | null) => (film ? h3Canvas(film.width, film.height, CHARACTER_SWAP.defaultQuality) : undefined);
+
/** 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;
@@ -1068,14 +1074,15 @@ function finishPlans(p: SwapProject, clip: SwapClip, tier: SharpenTier, look: Lo
* 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 {
+export async function sharpenClip(projectId: string, body: z.infer<typeof SharpenSchema>): Promise<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);
+ const canvas = sharpenCanvas(film);
+ const tier = sharpenTierFor(p.engine, body.tier, film, canvas);
+ if (!tier) throw new ShortsError(sharpenOptions(p.engine, film, canvas).find((o) => o.tier === body.tier)?.reason ?? SHARPEN_COPY.small, 422);
if (p.engine === "open") {
mustOffer(REGEN_MODEL, "open");
mustOffer(COMPOSITE_MODEL, "open");
@@ -1097,6 +1104,8 @@ export function sharpenClip(projectId: string, body: z.infer<typeof SharpenSchem
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;
}
+ // A version still being made at another size is replaced: it is stopped first (nothing would show it or stop it after).
+ for (const x of todo) for (const gid of finishIds(x.take.finish)) if (ACTIVE.has(look(gid)?.status ?? "")) await cancelGeneration(gid).catch(() => undefined);
const made = new Map<string, TakeFinish>();
for (const x of todo) {
const pipe = run(x.plan.steps);
@@ -1120,7 +1129,7 @@ function sharpenEstimate(p: SwapProject, clip: SwapClip, look: Look): { estimate
const costUsd: Partial<Record<SharpenTier, number | null>> = {};
let demo = false;
let problem: string | undefined;
- for (const o of sharpenOptions(p.engine, film)) {
+ for (const o of sharpenOptions(p.engine, film, sharpenCanvas(film))) {
if (!o.available) continue;
try {
let cost: number | null = 0;
@@ -1152,7 +1161,7 @@ export async function stopJob(projectId: string, body: z.infer<typeof StopSchema
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 === "finish") ids = clip.shots.flatMap((s) => currentSegments(s).flatMap((g) => g.takes.flatMap((t) => finishIds(t.finish))));
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;
diff --git a/tests/character-swap-2k.test.ts b/tests/character-swap-2k.test.ts
index 5bd000e9..74936164 100644
--- a/tests/character-swap-2k.test.ts
+++ b/tests/character-swap-2k.test.ts
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import type { PlanStep } from "@/lib/catalog/shorts";
-import type { GenInput } from "@/lib/catalog/types";
+import type { GenerationRequest, 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
@@ -16,7 +16,8 @@ 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");
+const { DEFAULT_SETTINGS, newShot, assemblyTakes, chosenTakes, usedFinish, normalizedSize, cloudFilmSize } = await import("@/lib/catalog/swap-studio");
+const { applyEdit, shotBusy } = await import("@/lib/catalog/swap-studio-edit");
type SwapClip = import("@/lib/catalog/swap-studio").SwapClip;
type SwapProject = import("@/lib/catalog/swap-studio").SwapProject;
type SwapTake = import("@/lib/catalog/swap-studio").SwapTake;
@@ -101,30 +102,86 @@ describe("prices", () => {
expect(qualityShort("cloud", "768p")).toBe("H3's native top");
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", "2K")).toBe(
+ "1080p and 2K redraw the 768p swap at the higher size. Free on your GPU, about 3 min more per 5 s on a 72 GB GPU. Your GPU joins the clip at up to 2048 px a side, so 2K needs a clip larger than 1080p.",
+ );
expect(qualityHint("open", "480p")).toBe("Faster and cheaper");
});
+
+ it("your GPU's 4K is turned off with the reason (it joins at up to 2048 px a side); the cloud's isn't", async () => {
+ const { qualityOff } = await import("@/components/genjutsu/character-panel");
+ expect(S.OPEN_TIER_OFF).toEqual({ "4K": "Your GPU joins the clip at up to 2048 px a side, so 4K adds nothing over 2K" });
+ expect(qualityOff("open", "4K")).toBe(S.OPEN_TIER_OFF["4K"]);
+ expect(["480p", "768p", "1080p", "2K"].map((q) => qualityOff("open", q as never))).toEqual([null, null, null, null]);
+ expect(qualityOff("cloud", "4K")).toBeNull();
+ // The picker says why as text the page shows (and links it to the group), not only in a tooltip.
+ const panel = fs.readFileSync(path.join(ROOT, "src/components/genjutsu/character-panel.tsx"), "utf8");
+ expect(panel).toMatch(/describedBy=\{offReasons\.length \? "character-quality-off"/);
+ expect(panel).toMatch(/id="character-quality-off"/);
+ });
});
describe("what each engine makes of a size", () => {
- it("your GPU: never above the footage (joined at most 2048 px a side)", () => {
+ it("your GPU: tiers gated and defaulted by the part the character is redrawn in (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([
+ const canvas = C.h3Canvas(1920, 1080, "768p");
+ expect(S.redrawnRegion(film, canvas)).toEqual({ width: 1842, height: 1052 });
+ expect(S.sharpenOptions("open", film, canvas).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");
+ expect(S.sharpenOptions("open", film, canvas)[1].reason).toBe("Your character is redrawn in a 1842×1052 part of the frame (the clip is joined at up to 2048 px a side), so 2K adds nothing over 1080p");
+ expect(S.sharpenOptions("open", film, canvas)[2].reason).toBe(S.OPEN_TIER_OFF["4K"]);
+ expect(S.sharpenTierFor("open", "4K", film, canvas)).toBe("1080p");
+ expect(S.defaultSharpenTier("open", film, canvas)).toBe("1080p");
+ // A 1440 square: the regenerate's 16:9 draft keeps a 1440 × 822 band of it, so 2K adds nothing there.
+ const sq1440 = S.filmSize(1440, 1440)!;
+ expect(S.redrawnRegion(sq1440, C.h3Canvas(1440, 1440, "768p"))).toEqual({ width: 1440, height: 822 });
+ expect(S.sharpenTierFor("open", "2K", sq1440, C.h3Canvas(1440, 1440, "768p"))).toBe("1080p");
+ // 4:3 at 2048 × 1536 (2048 × 1170 redrawn) and a 4K square (kept at 2048 × 2048): 2K adds a little and can be
+ // picked, but 1080p is the default, since neither part is 1440 tall.
+ for (const [w, h] of [
+ [2048, 1536],
+ [4096, 4096],
+ ]) {
+ const f = S.filmSize(w, h)!;
+ const c = C.h3Canvas(w, h, "768p");
+ expect(Math.min(S.redrawnRegion(f, c).width, S.redrawnRegion(f, c).height)).toBe(1170);
+ expect(S.sharpenTierFor("open", "4K", f, c)).toBe("2K");
+ expect(S.defaultSharpenTier("open", f, c)).toBe("1080p");
+ }
+ // Without the canvas, the film's own shape stands in for it.
+ expect(S.redrawnRegion(film)).toEqual({ width: 1890, height: 1080 });
// 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("Genjutsu's note names the clip's own size, the 2048 px join and the part redrawn when a size is capped", () => {
+ expect(S.openCapNote({ width: 3840, height: 2160 }, "4K", C.h3Canvas(3840, 2160, "768p"))).toBe(
+ "Your clip is 3840×2160, joined at 2048×1152 (up to 2048 px a side), and your character is redrawn in a 1964×1122 part of it, so it is sharpened at 2K",
+ );
+ expect(S.openCapNote({ width: 1920, height: 1080 }, "2K", C.h3Canvas(1920, 1080, "768p"))).toBe(
+ "Your clip is 1920×1080 (clips are joined at up to 2048 px a side), and your character is redrawn in a 1842×1052 part of it, so it is sharpened at 1080p",
+ );
+ expect(S.openCapNote({ width: 1920, height: 1080 }, "1080p", C.h3Canvas(1920, 1080, "768p"))).toBeNull();
+ });
+
+ it("the studio's film sizes are sharpen.ts's (one copy of the rule)", () => {
+ for (const [w, h] of [
+ [3840, 2160],
+ [72, 128],
+ [1080, 1920],
+ ]) {
+ expect(normalizedSize(w, h)).toEqual(S.filmSize(w, h, "open"));
+ expect(cloudFilmSize(w, h)).toEqual(S.filmSize(w, h, "cloud"));
+ }
+ expect(normalizedSize(3840, 2160)).toEqual({ width: 2048, height: 1152 });
+ expect(cloudFilmSize(72, 128)).toEqual({ width: 512, height: 910 });
+ });
+
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 });
@@ -168,6 +225,27 @@ describe("the composite's geometry and windows", () => {
expect(S.maskEdge({ width: 1888, height: 1080 })).toEqual({ grow: 9, feather: 13 });
});
+ it("at 1080p and 4K the regenerate covers the centre 1080 / 1088 (2160 / 2176) of the region: its finish trims the grid's rows", () => {
+ const film = { width: 1920, height: 1080 };
+ const canvas = C.h3Canvas(1920, 1080, "768p");
+ const hd = S.compositeGeometry(film, canvas, "1080p");
+ expect(hd.region).toEqual({ width: 1842, height: 1052, x: 39, y: 14 });
+ // 1052 × 1080 / 1088 = 1044.3 rows, 4 above and 4 below.
+ expect(hd.regen).toEqual({ width: 1842, height: 1044, x: 39, y: 18 });
+ expect(hd.trim).toEqual({ x: 0, y: 4 });
+ // 2K is drawn on 1440 rows and keeps them all.
+ const k2 = S.compositeGeometry(film, canvas, "2K");
+ expect(k2.regen).toEqual({ ...k2.region });
+ expect(k2.trim).toEqual({ x: 0, y: 0 });
+ // 4K keeps 2160 of 2176 rows.
+ expect(S.compositeGeometry(film, canvas, "4K").regen.height).toBe(Math.round((1052 * 2160) / 2176));
+ // A tall clip: the columns are trimmed.
+ const tall = S.compositeGeometry({ width: 1080, height: 1920 }, C.h3Canvas(1080, 1920, "768p"), "1080p");
+ expect(tall.regen.height).toBe(tall.region.height);
+ expect(tall.regen.width).toBe(Math.round((tall.region.width * 1080) / 1088));
+ expect(tall.regen.x - tall.region.x).toBe(tall.trim.x);
+ });
+
it("windows: equal, never a sliver, every frame once", () => {
expect(S.frameWindows(362, 360)).toEqual([
{ from: 0, frames: 181 },
@@ -347,15 +425,33 @@ describe("Character Swap Studio: Sharpen", () => {
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");
+ it("Finish is Sharpen alone: its card names the size picked and the model, and says why a size can't be picked", () => {
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.",
+ expect(page).not.toMatch(/backplate|Not available/i);
+ expect(page).toMatch(/describedBy=\{off\.length \? offId : undefined\}/);
+ expect(S.SHARPEN_COPY.card("1080p")).toBe(
+ "Redraws each chosen take at 1080p with Open-H3 Regenerate, 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.",
);
+ expect(S.SHARPEN_COPY.cardCloud("2K")).toMatch(/^Makes each chosen take again at 2K on MiniMax H3/);
+ expect(S.SHARPEN_COPY.model("open", "1080p")).toBe("Open-H3 Regenerate at 1080p");
+ expect(S.SHARPEN_COPY.model("cloud", "2K")).toBe("MiniMax H3 at 2K");
+ });
+
+ it("a take's sharper version still being made keeps its take and its shot's layout from changing", () => {
+ const x = studio("open");
+ const finish = { id: "finish-1", createdAt: 2, engine: "open" as const, asked: "1080p" as const, tier: "1080p" as const, genId: "g-fin", stepIds: ["g-regen", "g-fin"], use: false };
+ const shot = { ...x.shot, segments: [{ ...x.seg, takes: [{ ...x.take, finish }] }] };
+ const project = { ...x.project, clips: [{ ...x.clip, shots: [shot] }] };
+ const running = (id: string) => id === "g-regen";
+ expect(shotBusy(shot, running)).toBe(true);
+ expect(shotBusy(shot, () => false)).toBe(false);
+ const ref = { clipId: x.clip.id, shotId: shot.id, segmentId: x.seg.id, takeId: x.take.id };
+ expect(() => applyEdit(project, { type: "take", ...ref, remove: true }, { active: running })).toThrow(/sharper version is still being made/);
+ expect(() => applyEdit(project, { type: "remove-clip", clipId: x.clip.id } as never, { active: running })).toThrow(/Wait for this clip's takes/);
+ // Done: the take can go (with its version).
+ const out = applyEdit(project, { type: "take", ...ref, remove: true }, { active: () => false });
+ expect(out.clips[0].shots[0].segments![0].takes).toHaveLength(0);
});
});
@@ -363,12 +459,17 @@ describe("Character Swap Studio: Sharpen", () => {
// The graph
describe("the GPU pre-flight", () => {
- it("has a Character swap in 2K row on the regenerate, the composite and the join", async () => {
+ it("has a Character swap in 2K row on every graph Genjutsu's GPU run takes: the swap, the mask, the fit, the regenerate, the composite, the join and the mux", async () => {
const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");
const row = STUDIO_ROWS.find((r) => r.label === "Character swap in 2K")!;
expect(row).toMatchObject({ href: "/genjutsu?mode=character", group: "Video tools" });
+ // Every model the open 2K plan runs has its step on the row.
+ // (The optional anchor frame has its own models and rows.)
+ const planned = character("open", "2K").steps.filter((s) => s.key !== "frame" && s.key !== "anchor");
+ const listed = row.steps!.map((s) => `${s.modelId}#${s.op}`);
+ expect([...new Set(planned.map((s) => `${s.request.modelId}#${s.request.op}`))].sort()).toEqual([...listed].sort());
const t = studioTool(row)!;
- expect(t.workflows).toEqual(expect.arrayContaining(["video-regenerate-h3", "video-composite-mask", "video-concat-encoded"]));
+ expect(t.workflows).toEqual(expect.arrayContaining(["video-regenerate-h3", "video-composite-mask", "video-concat-encoded", "video-mask-h3-relay"]));
expect(t.loras.map((l) => l.file)).toContain("open_h3_regenerate_2k_lora.safetensors");
});
});
@@ -379,15 +480,32 @@ describe("video-composite-mask", () => {
it("is core nodes only, validated, with the bindings the plan fills", () => {
expect(manifest).toMatchObject({ capability: "composite", 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(),
+ [
+ ...["video", "video2", "video3", "mask", "startTime", "windowStart", "takeStart", "maskStart", "duration", "canvasWidth", "canvasHeight", "takeX", "takeY"],
+ ...["regionWidth", "regionHeight", "regenWidth", "regenHeight", "regenX", "regenY", "trimX", "trimY", "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"]),
+ new Set(["LoadVideo", "Video Slice", "GetVideoComponents", "ImageScale", "ImageToMask", "CropMask", "GrowMask", "FeatherMask", "ImageCompositeMasked", "CreateVideo", "SaveVideo"]),
);
expect(getModel(S.COMPOSITE_MODEL)).toMatchObject({ engine: "open", hidden: true });
});
+ it("a run keeps the person's mask (it isn't taken for a painted one) and needs the three clips and the mask", async () => {
+ const { applySketch } = await import("@/lib/catalog/sketch");
+ const { missingInputs } = await import("@/lib/catalog/plan");
+ const m = getModel(S.COMPOSITE_MODEL)!;
+ const req = { feature: "genjutsu-step", modelId: m.id, op: "composite" as const, inputs: { videos: ["/s.mp4", "/r.mp4", "/t.mp4"], mask: "/m.mp4" } } as GenerationRequest;
+ const kept = applySketch(req, m);
+ expect(kept.request.inputs).toEqual(req.inputs);
+ expect(kept.note).toBeUndefined();
+ expect(missingInputs("composite", req)).toBeNull();
+ const msg = "Add the footage, the redrawn clip, the swap and the person's mask to put the character back over it";
+ expect(missingInputs("composite", { inputs: { videos: ["/s.mp4", "/r.mp4"], mask: "/m.mp4" } })).toBe(msg);
+ expect(missingInputs("composite", { inputs: { videos: ["/s.mp4", "/r.mp4", "/t.mp4"] } })).toBe(msg);
+ });
+
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" });
@@ -404,8 +522,12 @@ describe("video-composite-mask", () => {
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", "width"), at("regen_mask_img", "height")]).toEqual([extra.regionWidth, extra.regionHeight]);
expect(at("regen_mask_img", "crop")).toBe("center");
+ // The regenerate and its mask: the rows its finish kept (1044 of the region's 1052 at 1080p), 4 rows down.
+ expect([at("regen_scaled", "width"), at("regen_scaled", "height"), at("composite", "x"), at("composite", "y")]).toEqual([extra.regenWidth, extra.regenHeight, extra.regenX, extra.regenY]);
+ expect([at("regen_trim", "x"), at("regen_trim", "y"), at("regen_trim", "width"), at("regen_trim", "height")]).toEqual([extra.trimX, extra.trimY, extra.regenWidth, extra.regenHeight]);
+ expect(extra).toMatchObject({ regionWidth: 1842, regionHeight: 1052, regenWidth: 1842, regenHeight: 1044, regenX: 39, regenY: 18, trimX: 0, trimY: 4 });
expect([at("take_grow", "expand"), at("regen_feather", "bottom")]).toEqual([extra.maskGrow, extra.feather]);
});
});
diff --git a/tests/swap-studio-sharpen.test.ts b/tests/swap-studio-sharpen.test.ts
index 3cfb7f80..a3dc6c11 100644
--- a/tests/swap-studio-sharpen.test.ts
+++ b/tests/swap-studio-sharpen.test.ts
@@ -31,6 +31,8 @@ const sharpen = await import("@/app/api/swap-studio/projects/[id]/sharpen/route"
const assemble = await import("@/app/api/swap-studio/projects/[id]/assemble/route");
const estimate = await import("@/app/api/swap-studio/projects/[id]/estimate/route");
const stop = await import("@/app/api/swap-studio/projects/[id]/stop/route");
+const masks = await import("@/app/api/swap-studio/projects/[id]/masks/route");
+const genjutsuEstimate = await import("@/app/api/genjutsu/estimate/route");
const req = (method: string, body?: unknown) => new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
@@ -63,10 +65,12 @@ function mp4(seconds: number, width: number, height: number): Buffer {
}
let clip = "";
+let square = "";
let hero = "";
beforeAll(() => {
setSetting("demoMode", "auto");
clip = saveFile({ data: mp4(6, 1920, 1080), contentType: "video/mp4", source: "upload", name: "street.mp4" }).url;
+ square = saveFile({ data: mp4(6, 2048, 2048), contentType: "video/mp4", source: "upload", name: "square.mp4" }).url;
hero = saveFile({ data: encodePng({ width: 64, height: 64, data: Buffer.alloc(64 * 64 * 4, 200) }), contentType: "image/png", source: "upload", name: "hero.png" }).url;
});
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -166,6 +170,92 @@ describe("Sharpen on the cloud (demo mode)", () => {
});
});
+describe("Sharpen on your GPU (demo mode)", () => {
+ it("a version still being made keeps its take; Sharpen at another size stops it before replacing it", async () => {
+ const id = (await post(projects, "", { name: "Square", engine: "open", character: { image: hero, description: "a knight" } })).id;
+ let p: SwapProject = await post(clips, id, { url: square, name: "square.mp4" });
+ const c = p.clips[0];
+ const shot = c.shots[0];
+ await until(id, (x) => !!x.project.clips[0].normalized?.url);
+ p = await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { settings: { useAnchor: false } } });
+ p = await patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 144 } });
+ const seg = p.clips[0].shots[0].segments![0];
+ p = await patch(id, { type: "segment", clipId: c.id, shotId: shot.id, segmentId: seg.id, patch: { anchorMode: "none" } });
+ // Who to swap: a tracked mask, approved.
+ p = await post(masks, id, { clipId: c.id, shotId: shot.id, kind: "track", frame: 0, points: [{ x: 1024, y: 1024, label: "positive" }] });
+ const m = p.clips[0].shots[0].masks[0];
+ await until(id, (x) => !!x.project.clips[0].shots[0].masks[0].pieces[0]?.url);
+ await patch(id, { type: "shot", clipId: c.id, shotId: shot.id, patch: { approvedMask: m.id } });
+ await post(queue, id, { clipId: c.id, shotId: shot.id, segmentId: seg.id, mode: "all" });
+ let v = await until(id, (x) => x.project.clips[0].shots[0].segments!.every((g) => !!g.selectedTake && x.gens[g.takes[0].genId!]?.status === "succeeded"));
+ const take = v.project.clips[0].shots[0].segments![0].takes[0];
+ const ref = { clipId: c.id, shotId: shot.id, segmentId: seg.id, takeId: take.id };
+
+ // A 2048 square: 2K adds a little over 1080p (a 2048 × 1170 part is redrawn), and 1080p is the default; 4K adds nothing.
+ const est = await (await estimate.GET(req("GET"), ctx(id) as never)).json();
+ expect(Object.keys(est.sharpen[c.id].costUsd)).toEqual(["1080p", "2K"]);
+ p = await post(sharpen, id, { clipId: c.id, tier: "1080p" });
+ const first = p.clips[0].shots[0].segments![0].takes[0].finish!;
+ expect(first).toMatchObject({ engine: "open", tier: "1080p" });
+ const firstIds = [...first.stepIds!, first.genId!];
+ expect(firstIds.map((g) => gens.getGeneration(g)!.modelId)).toEqual(expect.arrayContaining(["oss-h3-regenerate", "oss-composite-mask"]));
+
+ // While it is being made, its take stays, and so does the shot's layout.
+ await expect(patch(id, { type: "take", ...ref, remove: true })).rejects.toThrow(/sharper version is still being made/);
+ await expect(patch(id, { type: "layout", clipId: c.id, shotId: shot.id, op: { op: "partition", frames: 72 } })).rejects.toThrow(/409/);
+
+ // Sharpen again at 2K: the 1080p version still being made is stopped first, then replaced.
+ p = await post(sharpen, id, { clipId: c.id, tier: "2K" });
+ const second = p.clips[0].shots[0].segments![0].takes[0].finish!;
+ expect(second).toMatchObject({ tier: "2K", asked: "2K" });
+ expect(second.id).not.toBe(first.id);
+ expect(firstIds.map((g) => gens.getGeneration(g)!.status).filter((st) => st === "queued" || st === "running")).toEqual([]);
+ expect(gens.getGeneration(first.genId!)!.status).toBe("canceled");
+ // The 2K version's regenerate is drawn at 1440p.
+ expect(second.stepIds!.map((g) => gens.getGeneration(g)!).find((g) => g.modelId === "oss-h3-regenerate")!.request.params).toMatchObject({ resolution: "1440p" });
+
+ // Stop reaches it; then the take can go.
+ await post(stop, id, { kind: "finish", clipId: c.id }, 200);
+ v = await until(id, (x) => !["queued", "running"].includes(x.gens[x.project.clips[0].shots[0].segments![0].takes[0].finish!.genId!]?.status ?? ""), 20_000);
+ expect(v.gens[second.genId!].status).toBe("canceled");
+ const after = await patch(id, { type: "take", ...ref, remove: true });
+ expect(after.clips[0].shots[0].segments![0].takes.find((t) => t.id === take.id)).toBeUndefined();
+ });
+});
+
+describe("Genjutsu's notes for a finishing size", () => {
+ const est = async (body: unknown) => {
+ const res = await genjutsuEstimate.POST(req("POST", body) as never);
+ const out = await res.json();
+ if (res.status !== 200) throw new Error(`${res.status}: ${out.error}`);
+ return out as { notes: string[]; quality?: string };
+ };
+ const base = (engine: string, quality: string, over: Record<string, unknown> = {}) => ({
+ engine,
+ mode: "character",
+ references: [hero],
+ quality,
+ source: { url: clip, name: "street.mp4", duration: 30, fps: 30, width: 3840, height: 2160, hasAudio: true },
+ range: { start: 0, end: 10 },
+ ...over,
+ });
+
+ it("your GPU names the clip's own size and the 2048 px join when it sharpens at a smaller size", async () => {
+ const e = await est(base("open", "4K"));
+ expect(e.notes).toContain("Your clip is 3840×2160, joined at 2048×1152 (up to 2048 px a side), and your character is redrawn in a 1964×1122 part of it, so it is sharpened at 2K");
+ expect(e.notes.join(" ")).not.toMatch(/never above the clip's own size/);
+ });
+
+ it("the cloud's 4K over 15 s says its pieces are joined at up to 2048 px a side; a single piece doesn't", async () => {
+ const long = await est(base("cloud", "4K", { range: { start: 0, end: 20 } }));
+ expect(long.notes).toContain("A part over 15 s is made in pieces, and the pieces are joined at up to 2048 px a side");
+ const short = await est(base("cloud", "4K"));
+ expect(short.notes.join(" ")).not.toMatch(/joined at up to 2048/);
+ const k2 = await est(base("cloud", "2K", { range: { start: 0, end: 20 } }));
+ expect(k2.notes.join(" ")).not.toMatch(/joined at up to 2048/);
+ });
+});
+
describe("the route under the owner's public sign-up", () => {
it("gives guests and accounts own-gpu-tool (a studio job, like Assemble), and the owner the route", async () => {
process.env.FUOBE_PASSWORD = "install password";