Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Character Swap Studio: the project document, shots, segments, prompts and engine steps (pure)

Claudefc953d6f2739
diff --git a/src/lib/av/scene-cuts.ts b/src/lib/av/scene-cuts.ts
new file mode 100644
index 00000000..22b1aa89
--- /dev/null
+++ b/src/lib/av/scene-cuts.ts
@@ -0,0 +1,120 @@
+/**
+ * Finding the edits in a clip the way FFmpeg's scene filter does (`select='gt(scene,0.32)'`, the threshold Akatz Labs'
+ * H3 Character Swap tool uses: docs/research/openjutsu-6.md §4.2). FFmpeg scores each frame against the one before:
+ * the mean absolute frame difference (MAFD, 0–255 a sample) and how much it jumped from the previous pair's MAFD; the
+ * score is the smaller of the two over 100, clipped to 0–1 (libavfilter/f_select.c, get_scene_score). A steady pan
+ * has a high MAFD but no jump; a cut has both. Re-implemented here from that description — no FFmpeg code.
+ *
+ * The browser can't afford to read all 3,592 frames of a 150 s clip, so the studio looks twice: a coarse pass a few
+ * frames a second finds the stretches where a cut can be (`coarseWindows`), and a fine pass reads every 24 fps frame
+ * of those stretches and keeps the frames whose score is over the threshold (`sceneCuts`). Pure: the sampling lives
+ * in src/components/swap-studio, the tests run these on synthetic frames.
+ */
+
+/** FFmpeg's scene-change threshold in Akatz Labs' tool. */
+export const SCENE_THRESHOLD = 0.32;
+/** The coarse pass keeps more than it needs: the fine pass decides at the real threshold. */
+export const COARSE_THRESHOLD = 0.18;
+/** The studio's frame rate: every clip is worked on at 24 fps (H3's rate). */
+export const STUDIO_FPS = 24;
+
+/** RGBA pixels (a canvas's ImageData.data) or any array of 8-bit samples in RGBA order. */
+export type Pixels = ArrayLike<number>;
+
+/** Mean absolute difference per colour sample (R, G and B; alpha ignored), 0–255. */
+export function mafd(a: Pixels, b: Pixels): number {
+ const n = Math.min(a.length, b.length) - (Math.min(a.length, b.length) % 4);
+ if (n <= 0) return 0;
+ let sad = 0;
+ for (let i = 0; i < n; i += 4) sad += Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]);
+ return sad / ((n / 4) * 3);
+}
+
+/**
+ * The scene score of each frame in order, as FFmpeg's select filter computes it: the first frame scores 0, and every
+ * other frame min(MAFD, |MAFD − previous MAFD|) / 100, clipped to 0–1 (the previous MAFD starts at 0).
+ */
+export function sceneScores(frames: Pixels[]): number[] {
+ const out: number[] = [];
+ let prev = 0;
+ frames.forEach((f, i) => {
+ if (!i) {
+ out.push(0);
+ return;
+ }
+ const m = mafd(frames[i - 1], f);
+ const diff = Math.abs(m - prev);
+ prev = m;
+ out.push(Math.max(0, Math.min(1, Math.min(m, diff) / 100)));
+ });
+ return out;
+}
+
+/**
+ * The cut frames among scored frames: each frame whose score is over the threshold starts a new shot. `frames` are the
+ * 24 fps frame numbers of the scored frames (FFmpeg's round(pts × 24)); cuts at frame 0 or at/after the clip's end
+ * aren't cuts. Sorted, without duplicates.
+ */
+export function sceneCuts(scores: number[], frames: number[], total: number, threshold = SCENE_THRESHOLD): number[] {
+ const out = new Set<number>();
+ scores.forEach((s, i) => {
+ const f = frames[i];
+ if (s > threshold && Number.isInteger(f) && f > 0 && f < total) out.add(f);
+ });
+ return [...out].sort((a, b) => a - b);
+}
+
+/** A clip's frame count at the studio's 24 fps (the normaliser keeps round(seconds × 24) frames). */
+export const studioFrames = (seconds: number) => Math.max(1, Math.round(seconds * STUDIO_FPS));
+
+/** The time of a 24 fps frame, in seconds (to the millisecond). */
+export const frameTime = (frame: number) => Math.round((frame / STUDIO_FPS) * 1000) / 1000;
+
+/** A time → its 24 fps frame (FFmpeg's round(pts × 24)). */
+export const timeFrame = (seconds: number) => Math.round(seconds * STUDIO_FPS);
+
+/** Coarse sample times: about `perSecond` a second, at most `max` over the clip, the first at 0. */
+export function coarseTimes(duration: number, perSecond = 6, max = 600): number[] {
+ if (!(duration > 0)) return [];
+ const rate = Math.min(perSecond, max / duration);
+ const n = Math.max(2, Math.floor(duration * rate) + 1);
+ return Array.from({ length: n }, (_, i) => Math.min(duration, Math.round(((i * duration) / (n - 1)) * 1000) / 1000));
+}
+
+/**
+ * The stretches the fine pass has to read: each pair of coarse samples whose score passes the coarse threshold, as
+ * 24 fps frame ranges [from, to] that include the frame before (FFmpeg compares each frame with the previous one, and
+ * the jump needs the pair before that). Overlapping stretches merge.
+ */
+export function coarseWindows(times: number[], scores: number[], total: number, threshold = COARSE_THRESHOLD): { from: number; to: number }[] {
+ const raw: { from: number; to: number }[] = [];
+ scores.forEach((s, i) => {
+ if (!i || s <= threshold) return;
+ const from = Math.max(0, timeFrame(times[i - 1]) - 2);
+ const to = Math.min(total - 1, timeFrame(times[i]) + 1);
+ if (to > from) raw.push({ from, to });
+ });
+ raw.sort((a, b) => a.from - b.from);
+ const out: { from: number; to: number }[] = [];
+ for (const w of raw) {
+ const last = out.at(-1);
+ if (last && w.from <= last.to + 1) last.to = Math.max(last.to, w.to);
+ else out.push({ ...w });
+ }
+ return out;
+}
+
+/** The 24 fps frames a stretch reads, in order. */
+export const windowFrames = (w: { from: number; to: number }) => Array.from({ length: w.to - w.from + 1 }, (_, i) => w.from + i);
+
+/**
+ * The cuts in one stretch read frame by frame. Its first two scores aren't FFmpeg's: the first frame has nothing
+ * before it, and the second has no previous MAFD to jump from (FFmpeg's would be the real pair before). So a stretch
+ * starts two frames early (coarseWindows) and only frames from its third on can be cuts — except at the clip's start,
+ * where FFmpeg's own history is just as empty.
+ */
+export function windowCuts(frames: number[], pixels: Pixels[], total: number, threshold = SCENE_THRESHOLD): number[] {
+ const scores = sceneScores(pixels);
+ const skip = frames[0] === 0 ? 0 : 2;
+ return sceneCuts(scores.slice(skip), frames.slice(skip), total, threshold);
+}
diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.ts
new file mode 100644
index 00000000..921289f6
--- /dev/null
+++ b/src/lib/catalog/swap-studio-plan.ts
@@ -0,0 +1,451 @@
+/**
+ * Character Swap Studio's jobs on each engine (src/lib/catalog/swap-studio.ts holds the project document). Every job
+ * is ordinary generations planned as PlanSteps for createPipeline: the 24 fps copy of a clip, its transcript, a mask,
+ * a scene anchor, one segment's take, and the assembled clip. Pure, shared by the server and the tests.
+ *
+ * Your GPU (ComfyUI): Fuobe's fit graph makes the 24 fps copy (VHS, constant memory), Qwen3-ASR transcribes, H3 Relay
+ * 2.0's SAM 3.1 chain makes masks (points on any frame, Update frame or Track shot spliced into the version they
+ * correct), Qwen-Image-Edit 2511 makes anchors, and each segment is one H3 Relay pass with the approved mask, its
+ * anchor and the previous take's lossless (FFV1) master as history; the assembly fits every piece to the clip's size
+ * at 24 fps, joins them packet by packet and puts the clip's sound back.
+ * The cloud (fal): the clip stays as filmed (H3 makes 24 fps, the join keeps the lowest rate), Scribe v2 transcribes,
+ * SAM 3.1 video marks the person from your words or clicks, GPT Image 2.5 Sunburst or Nano Banana Pro make anchors, and
+ * each segment is fal's MiniMax H3 reference-to-video with Akatz Labs' swap LoRA — no mask (who to swap is said in
+ * words) and no history (a continuing segment starts from the previous take's last frame).
+ */
+import { anchorAspect, anchorModel, anchorPrompt, swapLoraRef } from "./character-swap";
+import { MASK_TRACKER } from "./remove-object";
+import type { PlanStep } from "./shorts";
+import {
+ at,
+ enginePrompt,
+ frameWindow,
+ normalizedSize,
+ qualityFor,
+ SWAP_STUDIO,
+ type AssemblyPiece,
+ type MaskVersion,
+ type SwapClip,
+ type SwapProject,
+ type SwapSegment,
+ type SwapShot,
+ type WhoToSwap,
+} from "./swap-studio";
+import { silenceRef } from "./canvas";
+import { getModel } from "./index";
+import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";
+
+/** The models each job runs on. */
+export const STUDIO_MODELS = {
+ open: {
+ normalize: "oss-fit-clip",
+ transcribe: "oss-qwen3-asr",
+ mask: "oss-h3-person-mask",
+ frame: "oss-extract-frame",
+ swap: "oss-h3-swap-segment",
+ fit: "oss-fit-clip",
+ join: "oss-join-encoded",
+ mux: "oss-mux",
+ joinMax: 100,
+ },
+ cloud: {
+ transcribe: "scribe-v2",
+ mask: MASK_TRACKER,
+ cut: "trim-video",
+ frame: "extract-frame",
+ swap: "fuobe-character-swap",
+ join: "join-clips",
+ mux: "merge-audio-video",
+ joinMax: 24,
+ },
+} as const;
+
+/** The ComfyUI workflows the studio adds (H3 Relay 2.0 nodes). */
+export const STUDIO_WORKFLOWS = { mask: "video-mask-h3-relay", segment: "video-character-swap-h3-segment" } as const;
+
+const helper = (title: string) => ({ feature: SWAP_STUDIO.stepFeature, batchTitle: title });
+
+/** The clip a job reads: your GPU's 24 fps copy, else the upload. */
+export const workingClip = (clip: SwapClip, engine: Engine) => (engine === "open" ? (clip.normalized?.url ?? clip.source.url) : clip.source.url);
+
+// ---------------------------------------------------------------------------
+// Import: the 24 fps copy (your GPU)
+
+/** Your GPU: the clip at 24 fps, at its own size (even, at most 2048 px), its sound kept. The cloud keeps the clip as filmed. */
+export function planNormalize(clip: SwapClip): PlanStep[] {
+ const size = normalizedSize(clip.source.width, clip.source.height);
+ return [
+ {
+ key: "normalize",
+ request: {
+ ...helper(`Character Swap · ${clip.name}`),
+ title: `${clip.name} · 24 fps`,
+ modelId: STUDIO_MODELS.open.normalize,
+ op: "trim",
+ inputs: { video: clip.source.url },
+ params: { startTime: 0, fps: SWAP_STUDIO.fps, ...(size ? { extra: { ...size } } : { aspectRatio: "auto" }) },
+ step: { label: "The clip at 24 fps", index: 0, of: 1 },
+ },
+ },
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// Transcript
+
+export function planTranscribe(clip: SwapClip, engine: Engine): PlanStep[] {
+ const s = clip.source.duration;
+ return [
+ {
+ key: "transcribe",
+ request: {
+ ...helper(`Character Swap · ${clip.name}`),
+ title: `${clip.name} · words`,
+ modelId: STUDIO_MODELS[engine].transcribe,
+ op: "transcribe",
+ inputs: { video: workingClip(clip, engine) },
+ params: { duration: s, sourceDuration: s },
+ step: { label: "The clip's words", index: 0, of: 1 },
+ },
+ },
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// Masks
+
+export interface MaskPlanInput {
+ engine: Engine;
+ clip: SwapClip;
+ shot: SwapShot;
+ kind: MaskVersion["kind"];
+ /** The shot's frame the points are on (0 = its first). */
+ frame: number;
+ points: PixelPoint[];
+ who: WhoToSwap;
+ /** The version it corrects (your GPU splices into its mask). */
+ base: MaskVersion | null;
+}
+
+/**
+ * What a mask job sends SAM 3.1 to point at someone: your GPU's graph takes clicks as JSON pixel points on H3's
+ * prepared frame (the provider moves them into its canvas) and the selection; fal's SAM 3.1 takes `point_prompts`
+ * ({x, y, label 1 | 0}) on the first frame of the clip it gets, so its clip starts on the clicked frame.
+ */
+export function maskPointsPayload(engine: Engine, points: PixelPoint[], who: WhoToSwap): { points?: PixelPoint[]; prompt?: string; selection?: string; subjectIndex?: number } {
+ const clicked = points.slice(0, SWAP_STUDIO.maxPoints);
+ if (engine === "cloud") return clicked.length ? { points: clicked } : { prompt: who.words.trim() || "person" };
+ // SAM3_Detect puts the clicked person first among its detections: take that one.
+ return clicked.length ? { points: clicked, prompt: who.words.trim() || "person", selection: "index", subjectIndex: 0 } : { prompt: who.words.trim() || "person", selection: who.selection, subjectIndex: who.selection === "index" ? who.index : 0 };
+}
+
+export function planMask(m: MaskPlanInput): PlanStep[] {
+ const { clip, shot } = m;
+ const len = shot.end - shot.start;
+ const title = `Character Swap · ${clip.name} · shot mask`;
+ const payload = maskPointsPayload(m.engine, m.points, m.who);
+ const label = m.kind === "frame" ? `Mask · frame ${m.frame + 1}` : m.frame ? `Mask · from frame ${m.frame + 1}` : "Mask · the shot";
+ if (m.engine === "open") {
+ const span = m.kind === "frame" ? 1 : len - m.frame;
+ const prev = m.base?.pieces[0]?.url;
+ return [
+ {
+ key: "mask",
+ request: {
+ ...helper(title),
+ title: label,
+ modelId: STUDIO_MODELS.open.mask,
+ op: "bg-remove-video",
+ prompt: payload.prompt,
+ inputs: { video: workingClip(clip, "open") },
+ params: {
+ ...frameWindow(shot.start, shot.end),
+ resolution: qualityFor(shot.settings.renderMp),
+ matteOutput: "matte",
+ ...(payload.points ? { points: payload.points } : {}),
+ extra: {
+ selection: payload.selection,
+ subjectIndex: payload.subjectIndex,
+ maskPrompt: payload.prompt,
+ keyFrame: m.frame,
+ spanFrames: span,
+ shotFrames: len,
+ ...(prev && (m.frame > 0 || span < len) ? { prevMask: prev } : {}),
+ },
+ },
+ step: { label, index: 0, of: 1 },
+ },
+ },
+ ];
+ }
+ const from = shot.start + m.frame;
+ const to = m.kind === "frame" ? from + 1 : shot.end;
+ return [
+ { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: clip.source.url }, params: { startTime: at(from), endTime: at(to) }, step: { label: "Cut from the frame", index: 0, of: 2 } } },
+ {
+ key: "mask",
+ request: {
+ ...helper(title),
+ title: label,
+ modelId: STUDIO_MODELS.cloud.mask,
+ op: "bg-remove-video",
+ ...(payload.prompt ? { prompt: payload.prompt } : {}),
+ params: { matteOutput: "matte", duration: at(to - from), ...(payload.points ? { points: payload.points } : {}) },
+ step: { label, index: 1, of: 2 },
+ },
+ after: ["cut"],
+ chain: [{ slot: "video" }],
+ },
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// Anchors
+
+export interface AnchorPlanInput {
+ engine: Engine;
+ project: Pick<SwapProject, "character">;
+ clip: SwapClip;
+ shot: SwapShot;
+ /** The frame of the clip the anchor edits (the shot's or a segment's first). */
+ frame: number;
+ /** The image model (the engine's first by default). */
+ modelId?: string;
+ seed?: number;
+}
+
+/** The anchor edit's words: your own base prompt, else Akatz Labs' brief (or Openjutsu's without a description), plus your instructions. */
+export function anchorWords(project: Pick<SwapProject, "character">, shot: SwapShot): string {
+ const base = shot.anchorBasePrompt.trim() || anchorPrompt({ who: shot.who.selection, index: shot.who.index, subject: shot.who.words, description: project.character.description.slice(0, 500) });
+ const extra = shot.anchorInstructions.trim();
+ return (extra ? `${base}\n\n${extra}` : base).slice(0, SWAP_STUDIO.maxPromptChars);
+}
+
+export function planAnchor(a: AnchorPlanInput): PlanStep[] {
+ if (!a.project.character.image) throw new Error("Add a picture of your character first");
+ const am = anchorModel(a.engine, a.modelId);
+ const title = `Character Swap · ${a.clip.name} · anchor`;
+ const t = at(a.frame);
+ // The first frame keeps the clip's shape ("auto", or the nearest ratio the model lists): the models' default is square.
+ const aspect = anchorAspect(getModel(am.id)?.options.aspectRatios, a.clip.source);
+ const edit = (after: string): PlanStep => ({
+ key: "anchor",
+ request: {
+ ...helper(title),
+ title: `Anchor · ${am.label}`,
+ modelId: am.id,
+ op: "edit",
+ prompt: anchorWords(a.project, a.shot),
+ inputs: { images: [a.project.character.image!] },
+ params: { ...(aspect ? { aspectRatio: aspect } : {}), ...(am.extra ? { extra: { ...am.extra } } : {}), ...(a.seed !== undefined ? { seed: a.seed } : {}) },
+ step: { label: `Your character in the frame (${am.label})`, index: 1, of: 2 },
+ },
+ after: [after],
+ chain: [{ slot: "images", position: "first" }],
+ });
+ if (a.engine === "open") {
+ return [
+ { key: "frame", request: { ...helper(title), modelId: STUDIO_MODELS.open.frame, op: "frame", inputs: { video: workingClip(a.clip, "open") }, params: { ...frameWindow(a.frame, a.frame + 12), extra: { frameIndex: 0 } }, step: { label: "The frame", index: 0, of: 2 } } },
+ edit("frame"),
+ ];
+ }
+ return [
+ { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: a.clip.source.url }, params: { startTime: t, endTime: Math.min(a.clip.source.duration, t + 1) }, step: { label: "Cut at the frame", index: 0, of: 3 } } },
+ { key: "frame", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.frame, op: "frame", params: { extra: { frame_type: "first" } }, step: { label: "The frame", index: 1, of: 3 } }, after: ["cut"], chain: [{ slot: "video" }] },
+ edit("frame"),
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// A segment's take
+
+export interface SegmentPlanInput {
+ engine: Engine;
+ project: SwapProject;
+ clip: SwapClip;
+ shot: SwapShot;
+ seg: SwapSegment;
+ /** 1-based, for labels. */
+ shotNumber: number;
+ segNumber: number;
+ takeNumber: number;
+ /** segmentPrompt(...) in H3's tags; the plan puts it in the engine's words. */
+ prompt: string;
+ history: number;
+ anchor: string | null;
+ /** Your GPU: the approved mask (a whole-shot mask video) when masked generation is on. */
+ mask?: string | null;
+ /** Your GPU: the previous take's lossless master and its frame count; the cloud: its video (the last frame starts this one). */
+ previous?: { master?: string; video?: string; frames: number } | null;
+}
+
+/** H3's whole seconds for a cloud call (5–15). */
+export const cloudCallSeconds = (frames: number) => Math.min(15, Math.max(5, Math.ceil(frames / SWAP_STUDIO.fps - 1e-6)));
+
+/**
+ * One take of a segment. Your GPU: one H3 Relay pass over the segment's frames (and the `history` frames before it,
+ * which the previous take's master replaces), with the approved mask, the anchor as <Picture 2> (or <Picture 3> after
+ * the boundary) and a lossless master saved for the next segment. The cloud: the segment cut from the clip, then fal's
+ * H3 with the swap LoRA (the character, the anchor and the previous take's last frame as pictures).
+ */
+export function planSegmentTake(p: SegmentPlanInput): { steps: PlanStep[]; final: string } {
+ const { shot, seg, clip, project } = p;
+ if (!project.character.image) throw new Error("Add a picture of your character first");
+ const title = `Character Swap · ${clip.name}`;
+ const label = `Shot ${p.shotNumber} · segment ${p.segNumber} · take ${p.takeNumber}`;
+ const quality = qualityFor(shot.settings.renderMp);
+ const frames = seg.end - seg.start;
+ if (p.engine === "open") {
+ const h = p.history;
+ if (h && !p.previous?.master) throw new Error(`${label} continues from the segment before it, which has no lossless master`);
+ const first = shot.start + seg.start - h;
+ const mask = shot.settings.useMask ? (p.mask ?? null) : null;
+ return {
+ final: "swap",
+ steps: [
+ {
+ key: "swap",
+ request: {
+ ...helper(title),
+ title: label,
+ modelId: STUDIO_MODELS.open.swap,
+ op: "video-swap",
+ prompt: enginePrompt(p.prompt, "open", shot.who),
+ inputs: { video: workingClip(clip, "open"), images: [project.character.image, ...(p.anchor ? [p.anchor] : [])] },
+ params: {
+ ...frameWindow(first, shot.start + seg.end),
+ resolution: quality,
+ seed: seg.seed,
+ extra: {
+ selection: shot.who.selection,
+ subjectIndex: shot.who.selection === "index" ? shot.who.index : 0,
+ maskPrompt: shot.who.words.trim() || "person",
+ maskGrow: shot.settings.expansion,
+ ...(shot.settings.lora !== "v1.5" ? { lora: shot.settings.lora } : {}),
+ ...(shot.settings.useMask ? {} : { useMask: false }),
+ // The mask video covers the shot from its first frame: the same window, counted from the shot.
+ ...(mask ? { maskVideo: mask, maskStart: frameWindow(seg.start - h, seg.end).startTime } : {}),
+ ...(h ? { historyVideo: p.previous!.master, historyStart: p.previous!.frames - h, historyLength: h } : {}),
+ ...(h && p.anchor ? { anchorAfterHistory: true } : {}),
+ },
+ },
+ step: { label, index: 0, of: 1 },
+ },
+ },
+ ],
+ };
+ }
+ // The cloud: fal's H3 takes 2–15 s of reference video and makes whole seconds.
+ const from = shot.start + seg.start;
+ const boundary = p.history > 0 && !!p.previous?.video;
+ const steps: PlanStep[] = [
+ { key: "cut", request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video: clip.source.url }, params: { startTime: at(from), endTime: at(shot.start + seg.end) }, step: { label: `${label} · cut`, index: 0, of: 3 } } },
+ ];
+ const after = ["cut"];
+ const chain: ChainSlot[] = [{ slot: "video" }];
+ if (boundary) {
+ steps.push({
+ key: "boundary",
+ request: { ...helper(title), modelId: STUDIO_MODELS.cloud.frame, op: "frame", inputs: { video: p.previous!.video! }, params: { extra: { frame_type: "last" } }, step: { label: `${label} · the previous take's last frame`, index: 1, of: 3 } },
+ });
+ after.push("boundary");
+ chain.push({ slot: "images", position: "last" });
+ }
+ const text = enginePrompt(p.prompt, "cloud", shot.who, { swapPictures: boundary && !!p.anchor });
+ steps.push({
+ key: "swap",
+ request: {
+ ...helper(title),
+ title: label,
+ modelId: STUDIO_MODELS.cloud.swap,
+ op: "video-swap",
+ prompt: 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, index: 2, of: 3 },
+ },
+ after,
+ chain,
+ });
+ return { steps, final: "swap" };
+}
+
+// ---------------------------------------------------------------------------
+// Assembly
+
+export interface AssemblyPlanInput {
+ engine: Engine;
+ clip: SwapClip;
+ pieces: AssemblyPiece[];
+ /** Each take's finished video. */
+ videoOf: (piece: Extract<AssemblyPiece, { kind: "take" }>) => string;
+}
+
+/** Fold `keys` into joins of at most `max` (the last join is "join"). */
+function joins(steps: PlanStep[], keys: string[], max: number, request: (n: number, last: boolean) => GenerationRequest): string {
+ let level = keys;
+ let depth = 0;
+ while (level.length > 1) {
+ const groups: string[][] = [];
+ for (let i = 0; i < level.length; i += max) groups.push(level.slice(i, i + max));
+ const last = groups.length === 1;
+ level = groups.map((g, gi) => {
+ const key = last ? "join" : `join-${depth}-${gi}`;
+ steps.push({ key, request: request(g.length, last), after: g, chain: g.map(() => ({ slot: "videos" as const })) });
+ return key;
+ });
+ depth++;
+ }
+ return level[0];
+}
+
+/**
+ * The clip with every swapped shot's chosen takes over the original timeline and the clip's own sound; kept shots
+ * stay as filmed. Your GPU: each piece fitted to the clip's size at 24 fps (Fuobe's fit graph), joined packet by
+ * packet, the clip's sound put back. The cloud: each piece cut (a take to its segment's exact length), joined (fal
+ * keeps the lowest frame rate: 24 for H3), the clip's sound (or its silence) put back.
+ */
+export function planAssembly(a: AssemblyPlanInput): { steps: PlanStep[]; final: string } {
+ const { clip } = a;
+ const title = `${clip.name} · character swap`;
+ const base = { feature: SWAP_STUDIO.feature, batchTitle: title, title };
+ const total = a.pieces.length;
+ const steps: PlanStep[] = [];
+ const keys: string[] = [];
+ const size = normalizedSize(clip.source.width, clip.source.height);
+ a.pieces.forEach((piece, i) => {
+ const key = `piece${i}`;
+ const what = piece.kind === "source" ? "kept as filmed" : "your character";
+ const label = { label: `Part ${i + 1} of ${total} · ${what}`, index: i, of: total };
+ // Exact frame times: the fit graph counts round(seconds × 24) frames from them.
+ const len = at(piece.end - piece.start);
+ const video = piece.kind === "source" ? workingClip(clip, a.engine) : a.videoOf(piece);
+ const start = piece.kind === "source" ? at(piece.start) : 0;
+ if (a.engine === "open") {
+ steps.push({
+ key,
+ request: { ...helper(title), modelId: STUDIO_MODELS.open.fit, op: "trim", inputs: { video }, params: { startTime: start, endTime: start + len, fps: SWAP_STUDIO.fps, ...(size ? { extra: { ...size } } : { aspectRatio: "auto" }) }, step: label },
+ });
+ } else {
+ steps.push({ key, request: { ...helper(title), modelId: STUDIO_MODELS.cloud.cut, op: "trim", inputs: { video }, params: { startTime: start, endTime: start + len }, step: label } });
+ }
+ keys.push(key);
+ });
+ const m = STUDIO_MODELS[a.engine];
+ const picture = joins(steps, keys, m.joinMax, (_n, last) => ({ ...helper(title), modelId: m.join, op: "concat", prompt: title, step: { label: last ? "Join the parts" : "Joining", index: 1000, of: 1000 } }));
+ const sound: GenerationRequest["inputs"] = clip.source.hasAudio ? { audio: workingClip(clip, a.engine) } : a.engine === "cloud" ? { audio: silenceRef(clip.source.duration) } : undefined;
+ if (!sound) {
+ // Your GPU, a silent clip: the fit graph already gave every part silence; the join is the result.
+ const last = steps.find((s) => s.key === picture)!;
+ last.request = { ...last.request, ...base };
+ return { steps, final: picture };
+ }
+ steps.push({
+ key: "final",
+ request: { ...base, modelId: m.mux, op: "mux", inputs: sound, step: { label: clip.source.hasAudio ? "Put the clip's sound back" : "Keep it silent, like the clip", index: 1200, of: 1000 } },
+ after: [picture],
+ chain: [{ slot: "video" }],
+ });
+ return { steps, final: "final" };
+}
diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.ts
new file mode 100644
index 00000000..2fbe6ece
--- /dev/null
+++ b/src/lib/catalog/swap-studio.ts
@@ -0,0 +1,1106 @@
+/**
+ * Character Swap Studio (/character-swap): Akatz Labs' H3 Character Swap workbench for whole clips, on both engines
+ * (docs/research/openjutsu-6.md §4.2, the Akatz app's modes and options). A project holds clips and one character
+ * (a reference image and a written description). Each clip is cut into shots at its edits; a shot is either swapped
+ * ("Replace character") or kept as filmed ("Keep original"). A swapped shot runs as segments of one diffusion pass each
+ * (at most 362 frames with its continuation boundary), each with its own dialogue, speaker, prompt, seed, a fresh start
+ * or a continuation of the segment before it, and an anchor. Segments make takes; the chosen takes are laid over the
+ * original timeline with the original sound.
+ *
+ * This module is the pure part, shared by the page, the server (src/server/swap-studio.ts) and the tests: the project
+ * document and its defaults, shots from cuts, transcript words and speakers, the performance prompts, segment layouts
+ * and their continuation dependencies, take and review state, mask point payloads and the assembly order. The engine
+ * steps are in swap-studio-plan.ts. Behaviour follows Akatz Labs' app (MIT, Akatz Labs 2026); its prompts are reused
+ * with that notice. No code of theirs is copied.
+ */
+import { CHARACTER_SWAP, HISTORY_CHOICES, WINDOW_CHOICES, whoWords, type SwapLora, type SwapWho } from "./character-swap";
+import { STUDIO_FPS } from "@/lib/av/scene-cuts";
+import type { Engine, PixelPoint } from "./types";
+
+export const SWAP_STUDIO = {
+ feature: "swap-studio",
+ stepFeature: "swap-studio-step",
+ fps: STUDIO_FPS,
+ /** "Trim this clip to 149.66 seconds or less before import." (Akatz's normaliser: 3,592 frames at 24 fps). */
+ maxFrames: 3592,
+ maxSeconds: 3592 / STUDIO_FPS,
+ /** Fuobe's upload limit. */
+ maxBytes: 200 * 1024 * 1024,
+ maxClips: 20,
+ accept: "video/mp4,video/quicktime,video/x-matroska,video/webm,video/x-msvideo,.mp4,.mov,.mkv,.webm,.avi",
+ extensions: ["mp4", "mov", "mkv", "webm", "avi"],
+ maxNameChars: 80,
+ maxDescriptionChars: 2000,
+ /** Akatz: prompts, directions and the custom anchor base prompt are at most 20,000 characters. */
+ maxPromptChars: 20_000,
+ maxNotesChars: 2000,
+ /** One diffusion pass, the continuation boundary included (Akatz: "at most 362 frames"). */
+ maxPassFrames: 362,
+ /** The layouts the Segments panel offers (5, 10 and 15 s). */
+ segmentLengths: [5, 10, 15] as const,
+ /** fal's H3 reads 2–15 s of reference video a call. */
+ cloudMinFrames: 2 * STUDIO_FPS,
+ cloudMaxFrames: 15 * STUDIO_FPS,
+ /** Akatz's seed for new shots. */
+ seed: 194729,
+ maxSeed: 2 ** 32 - 1,
+ maxPoints: 24,
+ maxTakes: 30,
+ maxAnchors: 12,
+ maxMaskVersions: 20,
+ maxSegments: 1000,
+} as const;
+
+// ---------------------------------------------------------------------------
+// The document
+
+/** Who speaks (Akatz's speaker choice): the selected character, another person, an offscreen voice, nobody. */
+export type SwapRole = "target" | "other" | "offscreen" | "none";
+export type ShotMode = "generate" | "preserve";
+export type Connection = "start" | "continue";
+/** The segment's anchor: the shot's scene anchor, its own reference, or none. */
+export type AnchorMode = "shot" | "custom" | "none";
+export type Decision = "pending" | "keep" | "maybe" | "skip";
+/** Render size in megapixels: 0.5 is H3's "480", 1.0 its "768". */
+export type RenderMp = 0.5 | 1;
+
+export const ROLE_LABELS: Record<SwapRole, { label: string; hint: string }> = {
+ target: { label: "My character speaks", hint: "Their lips follow the clip's own voice" },
+ other: { label: "Someone else speaks", hint: "Your character keeps the filmed mouth movement" },
+ offscreen: { label: "Offscreen voice", hint: "Nobody on screen says it" },
+ none: { label: "No dialogue", hint: "Nobody speaks here" },
+};
+export const DECISION_LABELS: Record<Decision, string> = { pending: "Not reviewed", keep: "Keep", maybe: "Maybe", skip: "Skip" };
+export const MODE_LABELS: Record<ShotMode, { label: string; hint: string }> = {
+ generate: { label: "Replace character", hint: "Your character takes over this shot" },
+ preserve: { label: "Keep original", hint: "This shot stays as filmed" },
+};
+
+/** H3's quality for a render size. */
+export const qualityFor = (mp: RenderMp): "480p" | "768p" => (mp === 0.5 ? "480p" : "768p");
+
+/** A shot's generation settings (Akatz's shot fields; new shots take the project's defaults). */
+export interface SwapSettings {
+ lora: SwapLora;
+ useAnchor: boolean;
+ /** Masked generation (your GPU): only the person's mask is regenerated. */
+ useMask: boolean;
+ renderMp: RenderMp;
+ seed: number;
+ /** The diffusion window the default segment layout follows (17n + 5, 22–362). */
+ windowFrames: number;
+ /** Continuation history new segments take (0, 1 or 17n + 1). */
+ historyFrames: number;
+ /** Pixels the mask grows by (0–256). */
+ expansion: number;
+}
+
+export const DEFAULT_SETTINGS: SwapSettings = {
+ lora: "v1.5",
+ useAnchor: true,
+ useMask: true,
+ renderMp: 1,
+ seed: SWAP_STUDIO.seed,
+ windowFrames: CHARACTER_SWAP.window,
+ historyFrames: CHARACTER_SWAP.history,
+ expansion: CHARACTER_SWAP.maskGrow,
+};
+
+/** Who to swap: SAM 3.1's words and which of the people they find. */
+export interface WhoToSwap {
+ selection: SwapWho;
+ /** Person #n (from 0). */
+ index: number;
+ /** What SAM 3.1 looks for ("person"; "the woman in the red coat" narrows it). */
+ words: string;
+}
+
+export const DEFAULT_WHO: WhoToSwap = { selection: "largest", index: 0, words: "person" };
+
+/** A part of a mask video: frames [from, from + frames) of the shot. A later piece wins where they overlap. */
+export interface MaskPiece {
+ from: number;
+ frames: number;
+ /** The mask video once it is made. */
+ url?: string;
+ genId?: string;
+}
+
+/**
+ * A mask version: "track" follows the person from `frame` to the shot's end, "frame" redoes one frame. On your GPU
+ * every version is a whole-shot mask (the graph splices the new part into the version it corrects); on the cloud it
+ * is the version it corrects plus a new piece.
+ */
+export interface MaskVersion {
+ id: string;
+ createdAt: number;
+ kind: "track" | "frame";
+ engine: Engine;
+ frame: number;
+ points: PixelPoint[];
+ who: WhoToSwap;
+ /** The version it corrects. */
+ base?: string;
+ pieces: MaskPiece[];
+ /** The job that makes the newest piece. */
+ genId?: string;
+}
+
+export interface AnchorVariant {
+ id: string;
+ createdAt: number;
+ source: "generated" | "imported";
+ /** The image (an upload, or the job's output once it is done). */
+ url?: string;
+ genId?: string;
+ modelId?: string;
+ prompt?: string;
+}
+
+export interface TakeDependency {
+ segmentId: string;
+ takeId: string | null;
+ frames: number;
+}
+
+/**
+ * A take: one render of a segment. `state` is the studio's own: waiting for the segments it continues from, launched
+ * (the generations say how it goes), or stopped before it ran (with the reason).
+ */
+export interface SwapTake {
+ id: string;
+ createdAt: number;
+ engine: Engine;
+ state: "waiting" | "launched" | "stopped";
+ reason?: string;
+ /** The takes of this queue it waits for (the segments it continues from). */
+ waitsOn?: { segmentId: string; takeId: string }[];
+ /** The finished video's generation, and every step it took. */
+ genId?: string;
+ stepIds?: string[];
+ signature: string;
+ dependencies: TakeDependency[];
+ prompt: string;
+ seed: number;
+ /** The selected take when it was queued: it becomes the selection when it finishes, unless that changed. */
+ replaces?: string | null;
+ favourite: boolean;
+ decision: Decision;
+ notes: string;
+}
+
+export interface SwapSegment {
+ id: string;
+ /** Frames of the shot: [start, end). */
+ start: number;
+ end: number;
+ connection: Connection;
+ history: number;
+ seed: number;
+ /** Extra direction for this segment. */
+ prompt: string;
+ /** "Exact prompt for this segment" (null: built from the shot's). */
+ performancePrompt: string | null;
+ /** The segment's words (null: the transcript's for its frames). */
+ dialogue: string | null;
+ speaker: SwapRole | null;
+ anchorMode: AnchorMode;
+ /** The segment reference picked (anchorMode "custom"): one of `anchors`. */
+ anchor: string | null;
+ anchors: AnchorVariant[];
+ takes: SwapTake[];
+ selectedTake: string | null;
+ /** A layout change merged settings into it: worth a look before it runs. */
+ needsReview: boolean;
+}
+
+export interface SwapShot {
+ id: string;
+ /** Frames of the clip at 24 fps: [start, end). */
+ start: number;
+ end: number;
+ mode: ShotMode;
+ /** Who speaks (null: from the transcript's voices). */
+ speaker: SwapRole | null;
+ /** The shot's words (null: the transcript's). */
+ dialogue: string | null;
+ /** The performance prompt ("Build shot prompts" writes it; editable). Null: built when needed. */
+ prompt: string | null;
+ who: WhoToSwap;
+ masks: MaskVersion[];
+ approvedMask: string | null;
+ anchors: AnchorVariant[];
+ approvedAnchor: string | null;
+ /** Extra words for the anchor edit, and a base prompt of your own (replaces Akatz's brief). */
+ anchorInstructions: string;
+ anchorBasePrompt: string;
+ settings: SwapSettings;
+ /** The generation segments (null: the default layout, from the window plan). */
+ segments: SwapSegment[] | null;
+}
+
+export interface TranscriptCue {
+ start: number;
+ end: number;
+ text: string;
+ speaker?: string;
+}
+
+export interface SwapClip {
+ id: string;
+ name: string;
+ source: { url: string; name?: string; duration: number; fps?: number; width?: number; height?: number; hasAudio: boolean; bytes?: number };
+ /** Your GPU: the clip at 24 fps (H.264, its sound kept), made on import. */
+ normalized: { genId?: string; url?: string } | null;
+ /** Frames at 24 fps. */
+ frames: number;
+ cuts: number[];
+ /** Detected edits not yet confirmed. */
+ detected: number[] | null;
+ cutsReviewed: boolean;
+ shots: SwapShot[];
+ transcript: { genId?: string; modelId?: string; cues: TranscriptCue[] | null; voices: Record<string, SwapRole> } | null;
+ review: Decision;
+ reviewNotes: string;
+ assembly: { genId?: string; stepIds?: string[]; takes: string[]; createdAt: number } | null;
+}
+
+export interface SwapProject {
+ id: string;
+ name: string;
+ engine: Engine;
+ character: { image: string | null; description: string };
+ defaults: SwapSettings;
+ clips: SwapClip[];
+ createdAt: number;
+ updatedAt: number;
+ revision: number;
+}
+
+// ---------------------------------------------------------------------------
+// Small helpers
+
+const tidy = (s: string | null | undefined) => (s ?? "").replace(/\s+/g, " ").trim();
+const clampInt = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Math.round(Number.isFinite(v) ? v : lo)));
+
+/** A short random id (the server passes its own generator in tests). */
+export function uid(prefix: string, rand: () => number = Math.random): string {
+ let s = "";
+ for (let i = 0; i < 10; i++) s += "abcdefghijkmnpqrstuvwxyz23456789"[Math.floor(rand() * 32)];
+ return `${prefix}${s}`;
+}
+
+/** FNV-1a over a string, as 8 hex digits: a take's settings signature. */
+export function digest(value: unknown): string {
+ const text = typeof value === "string" ? value : stableJson(value);
+ let h = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h.toString(16).padStart(8, "0");
+}
+
+/** JSON with sorted keys (so a signature doesn't depend on the order fields were written). */
+export function stableJson(v: unknown): string {
+ if (Array.isArray(v)) return `[${v.map(stableJson).join(",")}]`;
+ if (v && typeof v === "object") {
+ return `{${Object.keys(v as object)
+ .filter((k) => (v as Record<string, unknown>)[k] !== undefined)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${stableJson((v as Record<string, unknown>)[k])}`)
+ .join(",")}}`;
+ }
+ return JSON.stringify(v ?? null);
+}
+
+export const seconds = (frames: number) => Math.round((frames / SWAP_STUDIO.fps) * 1000) / 1000;
+/** The exact time of a 24 fps frame (graphs and cuts count frames from it, so it isn't rounded). */
+export const at = (frame: number) => frame / SWAP_STUDIO.fps;
+
+/**
+ * Frames [from, to) as a ComfyUI Trim Video window. It starts half a frame early (Trim Video keeps the frames at or
+ * after its start, so float error can't drop the first one) and runs a quarter frame past the range (H3's
+ * PrepareVideo keeps floor(seconds × 24) frames, which a hair under the length would make one short). From frame 0
+ * the window takes one frame too many, and PrepareVideo's frame limit drops it.
+ */
+export function frameWindow(from: number, to: number): { startTime: number; endTime: number } {
+ const startTime = from > 0 ? (from - 0.5) / SWAP_STUDIO.fps : 0;
+ return { startTime, endTime: startTime + (to - from + 0.25) / SWAP_STUDIO.fps };
+}
+export const framesOf = (s: number) => Math.round(s * SWAP_STUDIO.fps);
+/** "12.5 s" */
+export const secondsLabel = (frames: number) => `${(Math.round((frames / SWAP_STUDIO.fps) * 10) / 10).toString()} s`;
+
+// ---------------------------------------------------------------------------
+// Clips
+
+/** The clip's file kind from its name, or null when the studio doesn't take it. */
+export function clipExtension(name: string): string | null {
+ const ext = name.split(".").pop()?.toLowerCase() ?? "";
+ return (SWAP_STUDIO.extensions as readonly string[]).includes(ext) ? ext : null;
+}
+
+/** What stops a clip from being imported, or null. */
+export function clipProblem(c: { name?: string; duration?: number; bytes?: number }): string | null {
+ if (c.name && !clipExtension(c.name)) return "Add an MP4, MOV, MKV, WebM or AVI clip";
+ if (c.bytes !== undefined && c.bytes > SWAP_STUDIO.maxBytes) return "Keep clips under 200 MB";
+ if (c.duration !== undefined && !(c.duration > 0)) return "Couldn't read this clip's length — save it as an MP4 and add it again";
+ if (c.duration !== undefined && c.duration > SWAP_STUDIO.maxSeconds + 0.01) return "Trim this clip to 149.66 seconds or less before you add it";
+ return null;
+}
+
+/**
+ * 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) };
+}
+
+// ---------------------------------------------------------------------------
+// Shots
+
+export function newShot(start: number, end: number, defaults: SwapSettings, hasAudio: boolean, rand?: () => number): SwapShot {
+ return {
+ id: uid("shot-", rand),
+ start,
+ end,
+ mode: "generate",
+ speaker: hasAudio ? null : "none",
+ dialogue: null,
+ prompt: null,
+ who: { ...DEFAULT_WHO },
+ masks: [],
+ approvedMask: null,
+ anchors: [],
+ approvedAnchor: null,
+ anchorInstructions: "",
+ anchorBasePrompt: "",
+ settings: { ...defaults },
+ segments: null,
+ };
+}
+
+/** What's wrong with a list of cuts for a clip of `frames` frames, or null (whole frames inside the clip). */
+export function cutsProblem(cuts: number[], frames: number): string | null {
+ if (cuts.some((n) => !Number.isInteger(n))) return "Cut positions must be whole frames";
+ if (cuts.some((n) => n <= 0 || n >= frames)) return "Cuts must fall inside the clip";
+ return null;
+}
+
+export const tidyCuts = (cuts: number[]) => [...new Set(cuts)].sort((a, b) => a - b);
+
+/**
+ * The shots of a clip for these cuts. A shot whose frames didn't change keeps everything; a changed one keeps the
+ * mode, who to swap, speaker and settings of the old shot it overlaps most, but not what depends on its exact frames
+ * (masks, anchors, segments and their takes). `modes` (one per shot) override.
+ */
+export function shotsFromCuts(clip: Pick<SwapClip, "frames" | "shots" | "source">, cuts: number[], defaults: SwapSettings, modes?: ShotMode[], rand?: () => number): SwapShot[] {
+ const bounds = [0, ...tidyCuts(cuts), clip.frames];
+ const out: SwapShot[] = [];
+ for (let i = 0; i < bounds.length - 1; i++) {
+ const [a, b] = [bounds[i], bounds[i + 1]];
+ const same = clip.shots.find((s) => s.start === a && s.end === b);
+ let shot: SwapShot;
+ if (same) shot = same;
+ else {
+ shot = newShot(a, b, defaults, clip.source.hasAudio, rand);
+ const overlap = (s: SwapShot) => Math.min(b, s.end) - Math.max(a, s.start);
+ const best = [...clip.shots].filter((s) => overlap(s) > 0).sort((x, y) => overlap(y) - overlap(x))[0];
+ if (best) Object.assign(shot, { mode: best.mode, who: { ...best.who }, speaker: best.speaker, settings: { ...best.settings }, anchorInstructions: best.anchorInstructions, anchorBasePrompt: best.anchorBasePrompt });
+ }
+ if (modes?.[i]) shot = { ...shot, mode: modes[i] };
+ out.push(shot);
+ }
+ return out;
+}
+
+/** Add a cut (no-op when it is already there or outside the clip). */
+export const addCut = (cuts: number[], frame: number, frames: number) => (frame > 0 && frame < frames && Number.isInteger(frame) ? tidyCuts([...cuts, frame]) : tidyCuts(cuts));
+export const removeCut = (cuts: number[], frame: number) => tidyCuts(cuts.filter((c) => c !== frame));
+
+/** Move cut `from` to `to`, keeping it between its neighbours (at least one frame from each). */
+export function moveCut(cuts: number[], from: number, to: number, frames: number): number[] {
+ const list = tidyCuts(cuts);
+ const i = list.indexOf(from);
+ if (i < 0) return list;
+ const lo = (list[i - 1] ?? 0) + 1;
+ const hi = (list[i + 1] ?? frames) - 1;
+ if (lo > hi) return list;
+ list[i] = clampInt(to, lo, hi);
+ return tidyCuts(list);
+}
+
+// ---------------------------------------------------------------------------
+// Words and speakers
+
+export interface TimedWord {
+ start: number;
+ end: number;
+ text: string;
+ speaker?: string;
+}
+
+/**
+ * A transcript's cues as words: a cue's words share its time evenly (the transcribers give caption-sized cues), so a
+ * word's middle says which segment it belongs to.
+ */
+export function cueWords(cues: TranscriptCue[] | null | undefined): TimedWord[] {
+ const out: TimedWord[] = [];
+ for (const c of cues ?? []) {
+ if (!Number.isFinite(c.start) || !Number.isFinite(c.end) || c.end < c.start) continue;
+ const words = tidy(c.text).split(" ").filter(Boolean);
+ const step = (c.end - c.start) / Math.max(1, words.length);
+ words.forEach((w, i) => out.push({ start: c.start + i * step, end: c.start + (i + 1) * step, text: w, ...(c.speaker ? { speaker: c.speaker } : {}) }));
+ }
+ return out.sort((a, b) => a.start - b.start);
+}
+
+/** The words whose middle falls in frames [start, end) of the clip (Akatz: (w.start + w.end) / 2 inside the range). */
+export function wordsIn(words: TimedWord[], start: number, end: number): TimedWord[] {
+ const a = start / SWAP_STUDIO.fps;
+ const b = end / SWAP_STUDIO.fps;
+ return words.filter((w) => {
+ const mid = (w.start + w.end) / 2;
+ return mid >= a && mid < b;
+ });
+}
+
+export const wordsText = (words: TimedWord[]) => words.map((w) => w.text).join(" ").trim();
+
+/** The voices a transcript names (diarized speakers), in order of first appearance; "voice" when it names none. */
+export function voicesOf(cues: TranscriptCue[] | null | undefined): string[] {
+ const out: string[] = [];
+ for (const c of cues ?? []) {
+ const v = c.speaker || "voice";
+ if (!out.includes(v)) out.push(v);
+ }
+ return out;
+}
+
+/** "Voice 1", "Voice 2"… for the transcriber's speaker ids. */
+export const voiceLabel = (voices: string[], v: string) => `Voice ${voices.indexOf(v) + 1}`;
+
+/**
+ * Who speaks in frames [start, end): the role of the voice with the most words there ("none" when nobody speaks).
+ * A voice not marked yet is the selected character (Akatz's default speaker).
+ */
+export function speakerIn(words: TimedWord[], roles: Record<string, SwapRole>, start: number, end: number): SwapRole {
+ const inside = wordsIn(words, start, end);
+ if (!inside.length) return "none";
+ const count = new Map<string, number>();
+ for (const w of inside) count.set(w.speaker || "voice", (count.get(w.speaker || "voice") ?? 0) + 1);
+ const top = [...count.entries()].sort((x, y) => y[1] - x[1])[0][0];
+ return roles[top] ?? "target";
+}
+
+/** A shot's words and speaker: what you set, else the transcript's (frames of the clip). */
+export function shotDialogue(clip: SwapClip, shot: SwapShot): string {
+ if (shot.dialogue !== null) return shot.dialogue;
+ return wordsText(wordsIn(cueWords(clip.transcript?.cues), shot.start, shot.end));
+}
+
+export function shotSpeaker(clip: SwapClip, shot: SwapShot): SwapRole {
+ if (shot.speaker) return shot.speaker;
+ if (!clip.source.hasAudio) return "none";
+ if (!clip.transcript?.cues) return "target";
+ return speakerIn(cueWords(clip.transcript.cues), clip.transcript.voices, shot.start, shot.end);
+}
+
+/** A segment's words and speaker (frames of the shot): its own, else the transcript's for its frames, else the shot's. */
+export function segmentDialogue(clip: SwapClip, shot: SwapShot, seg: SwapSegment): string {
+ if (seg.dialogue !== null) return seg.dialogue;
+ if (!clip.transcript?.cues && shot.dialogue !== null) return shot.dialogue;
+ return wordsText(wordsIn(cueWords(clip.transcript?.cues), shot.start + seg.start, shot.start + seg.end));
+}
+
+export function segmentSpeaker(clip: SwapClip, shot: SwapShot, seg: SwapSegment): SwapRole {
+ if (seg.speaker) return seg.speaker;
+ if (shot.speaker || !clip.transcript?.cues || !clip.source.hasAudio) return shotSpeaker(clip, shot);
+ const words = cueWords(clip.transcript.cues);
+ return wordsIn(words, shot.start + seg.start, shot.start + seg.end).length ? speakerIn(words, clip.transcript.voices, shot.start + seg.start, shot.start + seg.end) : shotSpeaker(clip, shot);
+}
+
+// ---------------------------------------------------------------------------
+// Prompts (Akatz Labs' performance prompt, MIT, Akatz Labs 2026)
+
+const SPEECH: Record<SwapRole, string> = {
+ target: "The selected character is speaking.",
+ offscreen: "Speech is offscreen; do not make the selected character speak.",
+ other: "Another person is speaking; preserve the selected character’s actual mouth performance.",
+ none: "No dialogue; preserve the visible source performance.",
+};
+
+const ANCHOR_SENTENCE = "<Picture 2> is the exact first-frame scene and pose anchor.";
+
+/**
+ * The shot's performance prompt in H3's reference tags (<Video 1> the clip, <Picture 1> the character, <Picture 2>
+ * the anchor, <Audio 1> the clip's sound): who becomes the character, what to keep, who speaks and the shot's words.
+ */
+export function shotPrompt(description: string, speaker: SwapRole, dialogue: string, anchor = true): string {
+ const who = tidy(description).replace(/[.\s]+$/, "") || "the reference character";
+ return [
+ `Replace only the selected person in <Video 1> with the single character in <Picture 1>: ${who}.`,
+ anchor ? ANCHOR_SENTENCE : "",
+ "Keep the reference identity and costume throughout. Match source posture, gaze, blinks, facial emotion, mouth movement, hand contacts and camera movement.",
+ SPEECH[speaker],
+ `Current shot dialogue: "${tidy(dialogue)}".`,
+ "<Audio 1> and source video determine exact timing. Do not repeat earlier dialogue or invent words, gestures, people or camera cuts. Retain the scene outside the person region. Output the raw decoded generation.",
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+/** "Build shot prompts": the shot's prompt from the character, its speaker and its words. */
+export function buildShotPrompt(project: Pick<SwapProject, "character">, clip: SwapClip, shot: SwapShot): string {
+ return shotPrompt(project.character.description, shotSpeaker(clip, shot), shotDialogue(clip, shot), shot.settings.useAnchor);
+}
+
+/** The continuation history a segment really uses: none when it starts fresh. */
+export const effectiveHistory = (seg: Pick<SwapSegment, "connection" | "history">) => (seg.connection === "continue" ? seg.history : 0);
+
+/** The anchor image a segment uses (the shot's approved scene anchor, its own reference, or none). */
+export function segmentAnchor(shot: SwapShot, seg: SwapSegment): string | null {
+ if (seg.anchorMode === "shot") return shot.settings.useAnchor ? (shot.anchors.find((a) => a.id === shot.approvedAnchor)?.url ?? null) : null;
+ if (seg.anchorMode === "custom") return seg.anchors.find((a) => a.id === seg.anchor)?.url ?? null;
+ return null;
+}
+
+/** What <Picture 2> (and <Picture 3>) are for a segment. */
+export function referenceContext(history: number, anchor: boolean): string {
+ if (history) {
+ return (
+ "<Picture 2> is the generated boundary from the preceding segment. Continue its motion and appearance." +
+ (anchor ? " <Picture 3> is an additional scene and performance reference for this segment; preserve continuity with the generated boundary." : "")
+ );
+ }
+ return anchor ? ANCHOR_SENTENCE : "";
+}
+
+/**
+ * The prompt a segment runs with: its exact prompt when you wrote one, else the shot's prompt without the shot-wide
+ * words and anchor sentence, what its pictures are, its own words, and its extra direction.
+ */
+export function segmentPrompt(project: Pick<SwapProject, "character">, clip: SwapClip, shot: SwapShot, seg: SwapSegment): string {
+ if (seg.performancePrompt !== null) return seg.performancePrompt;
+ const shared = (shot.prompt ?? buildShotPrompt(project, clip, shot))
+ .replace(/Current shot dialogue: "[^"]*"\.\s*/, "")
+ .replace(ANCHOR_SENTENCE, "")
+ .replace(/\s{2,}/g, " ")
+ .trim();
+ const context = referenceContext(effectiveHistory(seg), !!segmentAnchor(shot, seg));
+ const words = segmentDialogue(clip, shot, seg);
+ return [shared, context, `Current segment dialogue: "${tidy(words)}". Follow source audio timing. Earlier reference dialogue is context only; do not repeat it.`, seg.prompt.trim()].filter(Boolean).join("\n\n");
+}
+
+/** "Update prompt" for a segment: its full, editable prompt, with its speaker and words in the shot's text. */
+export function buildSegmentPrompt(project: Pick<SwapProject, "character">, clip: SwapClip, shot: SwapShot, seg: SwapSegment): string {
+ const base = shotPrompt(project.character.description, segmentSpeaker(clip, shot, seg), segmentDialogue(clip, shot, seg), true)
+ .replace(ANCHOR_SENTENCE, referenceContext(effectiveHistory(seg), !!segmentAnchor(shot, seg)))
+ .replace("Current shot dialogue:", "Current segment dialogue:")
+ .replace(/\s{2,}/g, " ")
+ .trim();
+ return [base, seg.prompt.trim()].filter(Boolean).join("\n\n");
+}
+
+/**
+ * The prompt in the engine's words. Your GPU's graph reads H3's tags; fal's H3 calls its inputs Video 1, Image 1,
+ * Image 2…, has no mask (so "the selected person" becomes who you picked, in words) and gets the clip's sound inside
+ * Video 1. `swapPictures`: on the cloud the anchor goes before the boundary frame (Image 2 / Image 3 trade places).
+ */
+export function enginePrompt(text: string, engine: Engine, who: WhoToSwap, o: { swapPictures?: boolean } = {}): string {
+ if (engine === "open") return text;
+ let out = text
+ .replace(/the selected person/g, whoWords({ who: who.selection, index: who.index, subject: who.words }))
+ .replace(/the selected character/g, "the character")
+ .replace(/<Audio 1> and source video determine/g, "Video 1's sound and motion determine")
+ .replace(/<Video (\d)>/g, "Video $1");
+ if (o.swapPictures) out = out.replace(/<Picture 2>/g, "\u0000").replace(/<Picture 3>/g, "<Picture 2>").replace(/\u0000/g, "<Picture 3>");
+ return out.replace(/<Picture (\d)>/g, "Image $1");
+}
+
+// ---------------------------------------------------------------------------
+// Segments
+
+/** The smallest diffusion window that takes a pass of `needed` frames with `history` frames before it, or null. */
+export function passWindow(needed: number, history: number): number | null {
+ return WINDOW_CHOICES.find((v) => v >= needed && v > history) ?? null;
+}
+
+/**
+ * The window plan's delivered ranges for `count` frames (H3's plan_windows: the first window has no history, each
+ * later one starts on the last frame made and delivers the rest of its window). Akatz's default segment layout.
+ */
+export function windowRanges(count: number, window: number, history: number): { start: number; end: number }[] {
+ const out: { start: number; end: number }[] = [];
+ let covered = 0;
+ while (covered < count) {
+ const eh = out.length ? history : 0;
+ const start = covered - (eh ? 1 : 0);
+ const needed = Math.min(count - start, window);
+ const size = WINDOW_CHOICES.find((v) => v >= needed && v > eh) ?? window;
+ const end = Math.min(count, start + size);
+ if (end <= covered) break;
+ out.push({ start: covered, end });
+ covered = end;
+ }
+ return out;
+}
+
+export function newSegment(shot: Pick<SwapShot, "settings">, start: number, end: number, index: number, rand?: () => number): SwapSegment {
+ return {
+ id: uid("seg-", rand),
+ start,
+ end,
+ connection: index ? "continue" : "start",
+ history: shot.settings.historyFrames,
+ seed: (shot.settings.seed + index) % (SWAP_STUDIO.maxSeed + 1),
+ prompt: "",
+ performancePrompt: null,
+ dialogue: null,
+ speaker: null,
+ anchorMode: !index && shot.settings.useAnchor ? "shot" : "none",
+ anchor: null,
+ anchors: [],
+ takes: [],
+ selectedTake: null,
+ needsReview: false,
+ };
+}
+
+/** A shot's segments: its own layout, or the default one from its window plan (ids stable per range). */
+export function currentSegments(shot: SwapShot): SwapSegment[] {
+ if (shot.segments) return shot.segments;
+ const len = shot.end - shot.start;
+ const w = WINDOW_CHOICES.includes(shot.settings.windowFrames) ? shot.settings.windowFrames : CHARACTER_SWAP.window;
+ const h = HISTORY_CHOICES.includes(shot.settings.historyFrames) && shot.settings.historyFrames < w ? shot.settings.historyFrames : CHARACTER_SWAP.history;
+ return windowRanges(len, w, h).map((r, i) => ({ ...newSegment(shot, r.start, r.end, i), id: `seg-${shot.id.replace(/^shot-/, "")}-${r.start}-${r.end}` }));
+}
+
+/** What's wrong with a segment layout for a shot, or null (Akatz's checks, in their words where they exist). */
+export function segmentsProblem(shot: Pick<SwapShot, "start" | "end">, items: SwapSegment[], engine?: Engine): string | null {
+ if (!items.length || items.length > SWAP_STUDIO.maxSegments) return "Choose between 1 and 1000 segments";
+ let covered = 0;
+ let chain = 0;
+ const ids = new Set<string>();
+ for (let i = 0; i < items.length; i++) {
+ const s = items[i];
+ const n = i + 1;
+ if (ids.has(s.id)) return "Segment identifiers must be unique";
+ ids.add(s.id);
+ if (!Number.isInteger(s.start) || !Number.isInteger(s.end) || s.start !== covered || s.end <= s.start) return "Segments must cover the shot in order, without gaps or overlaps";
+ if (!i && s.connection !== "start") return "The first segment starts fresh; later segments can continue or start fresh";
+ if (s.connection === "start") chain = s.start;
+ if (!HISTORY_CHOICES.includes(s.history)) return `Segment ${n}: choose a supported continuation history`;
+ const h = effectiveHistory(s);
+ if (h > s.start - chain) return `Segment ${n}: history extends before this continuous sequence; reduce history or move the boundary`;
+ if (passWindow(s.end - s.start + (h ? 1 : 0), h) === null) return `Segment ${n} must fit one diffusion pass (at most 362 frames, including its continuation boundary)`;
+ if (engine === "cloud") {
+ const len = s.end - s.start;
+ if (len < SWAP_STUDIO.cloudMinFrames || len > SWAP_STUDIO.cloudMaxFrames) return `Segment ${n} is ${secondsLabel(len)}: on the cloud a segment runs 2–15 s (fal's H3 reads 2–15 s of your clip a call)`;
+ }
+ if (!Number.isInteger(s.seed) || s.seed < 0 || s.seed > SWAP_STUDIO.maxSeed) return `Segment ${n}: use a whole-number seed`;
+ if (s.prompt.length > SWAP_STUDIO.maxPromptChars || (s.performancePrompt?.length ?? 0) > SWAP_STUDIO.maxPromptChars || (s.dialogue?.length ?? 0) > SWAP_STUDIO.maxPromptChars) return `Segment ${n}: keep its text under 20,000 characters`;
+ covered = s.end;
+ }
+ if (covered !== shot.end - shot.start) return "Segments must cover the entire shot";
+ return null;
+}
+
+/** The longest segment the layout offers for the engine (15 s; a cloud call takes 15 s of clip). */
+export const layoutFrames = (seconds: number) => Math.round(seconds * SWAP_STUDIO.fps);
+
+export type LayoutOp = { op: "partition"; frames: number } | { op: "split"; frame: number } | { op: "merge"; index: number } | { op: "boundary"; index: number; frame: number };
+
+/**
+ * A new layout from an operation (Akatz's layout): partition into equal lengths, split at the playhead, merge at a
+ * boundary or move a boundary. A segment whose frames didn't change is kept with its takes; a new one takes its seed,
+ * history and direction from the first segment it overlaps (and its connection and anchor when it starts with it),
+ * the directions of every overlapped segment, and is marked for review. A continuation can't reach before its
+ * sequence: its history shrinks to what is there.
+ */
+export function applyLayout(shot: SwapShot, op: LayoutOp, rand?: () => number): SwapSegment[] {
+ const old = currentSegments(shot);
+ const end = shot.end - shot.start;
+ let bounds = [0, ...old.map((s) => s.end)];
+ if (op.op === "partition") {
+ if (!Number.isInteger(op.frames) || op.frames < 1 || op.frames > 361) throw new Error("Choose a segment length of at most 15 seconds");
+ bounds = [];
+ for (let f = 0; f < end; f += op.frames) bounds.push(f);
+ bounds.push(end);
+ } else if (op.op === "split") {
+ if (!Number.isInteger(op.frame) || op.frame <= 0 || op.frame >= end || bounds.includes(op.frame)) throw new Error("Place the playhead inside a segment to split it");
+ bounds = [...bounds, op.frame].sort((a, b) => a - b);
+ } else {
+ if (!Number.isInteger(op.index) || op.index < 1 || op.index >= old.length) throw new Error("Choose a boundary between segments");
+ if (op.op === "merge") bounds.splice(op.index, 1);
+ else {
+ if (!Number.isInteger(op.frame) || !(bounds[op.index - 1] < op.frame && op.frame < bounds[op.index + 1])) throw new Error("The boundary must stay between its neighbouring boundaries");
+ bounds[op.index] = op.frame;
+ }
+ }
+ const out: SwapSegment[] = [];
+ for (let i = 0; i < bounds.length - 1; i++) {
+ const [a, b] = [bounds[i], bounds[i + 1]];
+ const exact = old.find((s) => s.start === a && s.end === b);
+ if (exact) {
+ out.push({ ...exact });
+ continue;
+ }
+ const overlaps = old.filter((s) => s.end > a && s.start < b);
+ const seg = newSegment(shot, a, b, i, rand);
+ if (overlaps.length) {
+ const first = overlaps[0];
+ Object.assign(seg, { seed: first.seed, history: first.history });
+ if (a === first.start) Object.assign(seg, { connection: first.connection, anchorMode: first.anchorMode, anchor: first.anchor, anchors: first.anchors });
+ seg.prompt = [...new Set(overlaps.map((s) => s.prompt).filter((p) => p.trim()))].join("\n\n");
+ for (const key of ["performancePrompt", "dialogue"] as const) {
+ const values = [...new Set(overlaps.map((s) => s[key]).filter((v): v is string => v !== null))];
+ if (values.length) seg[key] = values.join("\n\n");
+ }
+ seg.speaker = first.speaker;
+ seg.needsReview = !!seg.prompt || seg.performancePrompt !== null || seg.dialogue !== null || seg.speaker !== null;
+ }
+ out.push(seg);
+ }
+ let chain = 0;
+ out.forEach((seg, i) => {
+ if (!i) seg.connection = "start";
+ if (seg.connection === "start") chain = seg.start;
+ else if (seg.history > seg.start - chain) seg.history = Math.max(...HISTORY_CHOICES.filter((h) => h <= seg.start - chain));
+ });
+ const problem = segmentsProblem(shot, out);
+ if (problem) throw new Error(problem);
+ return out;
+}
+
+/**
+ * The segments a continuation draws its history from, oldest first, with how many frames each gives; never across a
+ * fresh start. Throws when the sequence before it is too short.
+ */
+export function predecessors(items: SwapSegment[], index: number): { segment: SwapSegment; frames: number }[] {
+ let needed = effectiveHistory(items[index]);
+ const out: { segment: SwapSegment; frames: number }[] = [];
+ for (let i = index - 1; i >= 0 && needed > 0; i--) {
+ const s = items[i];
+ const n = Math.min(needed, s.end - s.start);
+ out.push({ segment: s, frames: n });
+ needed -= n;
+ if (s.connection === "start") break;
+ }
+ if (needed > 0) throw new Error("Not enough preceding frames in this continuous sequence");
+ return out.reverse();
+}
+
+export const dependencies = (items: SwapSegment[], index: number): TakeDependency[] => predecessors(items, index).map(({ segment, frames }) => ({ segmentId: segment.id, takeId: segment.selectedTake, frames }));
+
+export const takeOf = (seg: SwapSegment, id?: string | null) => seg.takes.find((t) => t.id === (id ?? seg.selectedTake)) ?? null;
+
+/** The mask a shot's segments generate with (your GPU, masked generation on): the approved version's newest piece. */
+export function approvedMask(shot: SwapShot): MaskVersion | null {
+ return shot.masks.find((m) => m.id === shot.approvedMask) ?? null;
+}
+
+/** Everything a take's result depends on: a take whose signature differs from its segment's is stale. */
+export function settingSignature(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, engine: Engine = project.engine): string {
+ const mask = engine === "open" && shot.settings.useMask ? (approvedMask(shot)?.pieces.map((p) => p.url ?? p.genId) ?? null) : null;
+ return digest({
+ engine,
+ source: clip.normalized?.url ?? clip.source.url,
+ reference: project.character.image,
+ shotStart: shot.start,
+ segment: { id: seg.id, start: seg.start, end: seg.end, connection: seg.connection, history: effectiveHistory(seg), seed: seg.seed },
+ prompt: segmentPrompt(project, clip, shot, seg),
+ anchor: segmentAnchor(shot, seg),
+ settings: { lora: shot.settings.lora, useMask: engine === "open" ? shot.settings.useMask : false, renderMp: shot.settings.renderMp, expansion: engine === "open" ? shot.settings.expansion : 0 },
+ // Who to swap: the words and selection, unless an approved mask says it (your GPU).
+ who: mask ? null : shot.who,
+ mask,
+ });
+}
+
+export interface SegmentState {
+ id: string;
+ /** ready: the selected take matches the settings and what it continues from; stale: it doesn't; empty: no take. */
+ status: "ready" | "stale" | "empty";
+ /** A segment it continues from has no current take. */
+ blocked: boolean;
+ dialogue: string;
+ speaker: SwapRole;
+ prompt: string;
+ dependencies: TakeDependency[];
+ /** The pass's window (frames). */
+ windowFrames: number | null;
+}
+
+export function segmentStates(project: SwapProject, clip: SwapClip, shot: SwapShot, items: SwapSegment[] = currentSegments(shot)): SegmentState[] {
+ const out: SegmentState[] = [];
+ items.forEach((seg, i) => {
+ let deps: TakeDependency[] = [];
+ let broken = false;
+ try {
+ deps = dependencies(items, i);
+ } catch {
+ broken = true;
+ }
+ const chosen = takeOf(seg);
+ const staleParent = deps.some((d) => {
+ const j = items.findIndex((s) => s.id === d.segmentId);
+ return j >= 0 && out[j]?.status !== "ready";
+ });
+ const done = !!chosen && chosen.state === "launched";
+ const sameDeps = !!chosen && stableJson(chosen.dependencies) === stableJson(deps);
+ const ready = done && chosen!.signature === settingSignature(project, clip, shot, seg) && sameDeps && !staleParent && !broken;
+ const h = effectiveHistory(seg);
+ out.push({
+ id: seg.id,
+ status: ready ? "ready" : chosen ? "stale" : "empty",
+ blocked: broken || deps.some((d) => !d.takeId) || staleParent,
+ dialogue: segmentDialogue(clip, shot, seg),
+ speaker: segmentSpeaker(clip, shot, seg),
+ prompt: segmentPrompt(project, clip, shot, seg),
+ dependencies: deps,
+ windowFrames: passWindow(seg.end - seg.start + (h ? 1 : 0), h),
+ });
+ });
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Queueing segments
+
+export type QueueMode = "segment" | "from" | "all";
+
+export interface QueueEntry {
+ index: number;
+ segment: SwapSegment;
+ /** Earlier segments of this same queue it continues from (it waits for their takes). */
+ waitsOn: string[];
+ dependencies: TakeDependency[];
+}
+
+/**
+ * Which segments a "Queue segment / Queue from here / Queue all segments" makes takes for, and what each waits on
+ * (Akatz's freeze): a segment already being made is skipped (or refused when asked for alone), "from here" and "all"
+ * skip segments that are already current, and a continuation whose segment before it isn't in the queue needs that
+ * segment's current take (your GPU: its lossless master).
+ */
+export function planQueue(
+ project: SwapProject,
+ clip: SwapClip,
+ shot: SwapShot,
+ segmentId: string,
+ mode: QueueMode,
+ o: { active: (take: SwapTake) => boolean; hasMaster?: (take: SwapTake) => boolean },
+): { entries: QueueEntry[] } | { problem: string } {
+ const engine = project.engine;
+ if (shot.mode !== "generate") return { problem: "This shot keeps its original — switch it to Replace character first" };
+ if (!project.character.image) return { problem: "Add a picture of your character first" };
+ const items = currentSegments(shot);
+ const layout = segmentsProblem(shot, items, engine);
+ if (layout) return { problem: layout };
+ if (engine === "open" && !clip.normalized?.url) return { problem: "The clip is still being prepared at 24 fps — wait for it, then queue" };
+ const start = items.findIndex((s) => s.id === segmentId);
+ if (start < 0) return { problem: "That segment is no longer in this shot — reload" };
+ const states = segmentStates(project, clip, shot, items);
+ const busy = (s: SwapSegment) => s.takes.some((t) => t.state === "waiting" || (t.state === "launched" && o.active(t)));
+ let indices = mode === "segment" ? [start] : Array.from({ length: items.length - (mode === "all" ? 0 : start) }, (_, i) => i + (mode === "all" ? 0 : start));
+ if (mode === "segment" && busy(items[start])) return { problem: "This segment is already queued or generating" };
+ if (mode !== "segment") indices = indices.filter((i) => !busy(items[i]) && states[i].status !== "ready");
+ if (!indices.length) return { problem: "These segments are already current, queued or generating" };
+ const queued = new Set(indices);
+ const mask = approvedMask(shot);
+ const entries: QueueEntry[] = [];
+ for (const i of indices) {
+ const seg = items[i];
+ const n = i + 1;
+ if (seg.anchorMode !== "none" && !segmentAnchor(shot, seg)) {
+ return { problem: seg.anchorMode === "shot" ? `Segment ${n}: approve a scene anchor, or choose no anchor` : `Segment ${n}: pick its reference image, or choose no anchor` };
+ }
+ if (engine === "open" && shot.settings.useMask && mask && mask.pieces.some((p) => !p.url)) return { problem: "The approved mask is still being made — wait for it" };
+ const waitsOn: string[] = [];
+ let deps: TakeDependency[];
+ try {
+ deps = dependencies(items, i);
+ } catch (e) {
+ return { problem: `Segment ${n}: ${(e as Error).message.toLowerCase()}` };
+ }
+ for (const d of deps) {
+ const j = items.findIndex((s) => s.id === d.segmentId);
+ if (queued.has(j)) {
+ waitsOn.push(d.segmentId);
+ continue;
+ }
+ const chosen = takeOf(items[j]);
+ if (states[j].status !== "ready" || !chosen) return { problem: `Generate segment ${j + 1} first, or queue from an earlier segment` };
+ if (engine === "open" && o.hasMaster && !o.hasMaster(chosen)) return { problem: `Segment ${j + 1}'s take has no lossless master to continue from — make it again on your GPU` };
+ if (chosen.engine !== engine) return { problem: `Segment ${j + 1}'s take was made on the ${chosen.engine === "open" ? "open engine" : "cloud"} — make it again on this engine to continue from it` };
+ }
+ entries.push({ index: i, segment: seg, waitsOn, dependencies: deps });
+ }
+ return { entries };
+}
+
+// ---------------------------------------------------------------------------
+// Masks
+
+/** The mask piece covering a frame of the shot: the newest piece that holds it. */
+export function maskPieceAt(version: MaskVersion | null | undefined, frame: number): MaskPiece | null {
+ if (!version) return null;
+ for (let i = version.pieces.length - 1; i >= 0; i--) {
+ const p = version.pieces[i];
+ if (frame >= p.from && frame < p.from + p.frames) return p;
+ }
+ return null;
+}
+
+/** The pieces of a new version (the cloud keeps the corrected version's pieces under the new one). */
+export function maskPieces(engine: Engine, kind: MaskVersion["kind"], frame: number, shotFrames: number, base: MaskVersion | null): MaskPiece[] {
+ const piece: MaskPiece = kind === "frame" ? { from: frame, frames: 1 } : { from: frame, frames: shotFrames - frame };
+ // Your GPU splices the new part into the corrected version: one whole-shot mask.
+ if (engine === "open") return [{ from: 0, frames: shotFrames }];
+ return [...(base?.pieces ?? []).filter((p) => p.url || p.genId), piece];
+}
+
+/** What stops a mask job, or null. */
+export function maskProblem(engine: Engine, kind: MaskVersion["kind"], frame: number, shotFrames: number, points: PixelPoint[], who: WhoToSwap, base: MaskVersion | null): string | null {
+ if (!Number.isInteger(frame) || frame < 0 || frame >= shotFrames) return "Pick a frame inside the shot";
+ if (points.length > SWAP_STUDIO.maxPoints) return `Use at most ${SWAP_STUDIO.maxPoints} points`;
+ if (points.length && !points.some((p) => p.label !== "negative")) return "Add at least one include point (exclude points only narrow it)";
+ if (!points.length && !tidy(who.words)) return "Say who to look for (“person”), or click them";
+ if (kind === "frame" && !base) return "Track the shot first — Update frame corrects one frame of a mask";
+ if (kind === "frame" && engine === "open" && !points.length) return "Click the person on this frame to correct it";
+ if (base && base.engine !== engine) return "That mask was made on the other engine — track the shot again here";
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Takes and review
+
+export function selectTake(seg: SwapSegment, takeId: string): SwapSegment {
+ const t = takeOf(seg, takeId);
+ if (!t) throw new Error("That take is gone");
+ if (t.state !== "launched") throw new Error("That take didn't run");
+ return { ...seg, selectedTake: takeId };
+}
+
+export function updateTake(seg: SwapSegment, takeId: string, patch: Partial<Pick<SwapTake, "favourite" | "decision" | "notes">>): SwapSegment {
+ if (!takeOf(seg, takeId)) throw new Error("That take is gone");
+ if (patch.notes !== undefined && patch.notes.length > SWAP_STUDIO.maxNotesChars) throw new Error("Keep notes under 2,000 characters");
+ return { ...seg, takes: seg.takes.map((t) => (t.id === takeId ? { ...t, ...patch } : t)) };
+}
+
+/** Taking a take away: a selected one leaves the segment without a selection. */
+export function removeTake(seg: SwapSegment, takeId: string): SwapSegment {
+ return { ...seg, takes: seg.takes.filter((t) => t.id !== takeId), selectedTake: seg.selectedTake === takeId ? null : seg.selectedTake };
+}
+
+/** A finished take becomes the selection when nothing changed since it was queued (Akatz's attach_take). */
+export function autoSelect(project: SwapProject, clip: SwapClip, shot: SwapShot, seg: SwapSegment, take: SwapTake, items: SwapSegment[]): boolean {
+ if (seg.selectedTake !== (take.replaces ?? null)) return false;
+ const i = items.findIndex((s) => s.id === seg.id);
+ let deps: TakeDependency[] = [];
+ try {
+ deps = dependencies(items, i);
+ } catch {
+ return false;
+ }
+ return take.signature === settingSignature(project, clip, shot, seg, take.engine) && stableJson(take.dependencies) === stableJson(deps);
+}
+
+export interface DecisionExport {
+ project: string;
+ exportedAt: string;
+ clips: {
+ clip: string;
+ review: Decision;
+ notes: string;
+ assembled: boolean;
+ shots: {
+ shot: number;
+ frames: [number, number];
+ mode: ShotMode;
+ segments: { segment: number; frames: [number, number]; selectedTake: string | null; takes: { take: string; favourite: boolean; decision: Decision; notes: string; seed: number; video?: string }[] }[];
+ }[];
+ }[];
+}
+
+/** "Export decisions": every clip's review and every take's favourite, decision and notes, as JSON. */
+export function exportDecisions(project: SwapProject, videoOf: (take: SwapTake) => string | undefined, now = new Date()): DecisionExport {
+ return {
+ project: project.name,
+ exportedAt: now.toISOString(),
+ clips: project.clips.map((c) => ({
+ clip: c.name,
+ review: c.review,
+ notes: c.reviewNotes,
+ assembled: !!c.assembly?.genId,
+ shots: c.shots.map((s, si) => ({
+ shot: si + 1,
+ frames: [s.start, s.end] as [number, number],
+ mode: s.mode,
+ segments:
+ s.mode === "generate"
+ ? currentSegments(s).map((g, gi) => ({
+ segment: gi + 1,
+ frames: [s.start + g.start, s.start + g.end] as [number, number],
+ selectedTake: g.selectedTake,
+ takes: g.takes.map((t) => ({ take: t.id, favourite: t.favourite, decision: t.decision, notes: t.notes, seed: t.seed, ...(videoOf(t) ? { video: videoOf(t) } : {}) })),
+ }))
+ : [],
+ })),
+ })),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Assembly
+
+/** One part of the assembled clip: kept frames of the clip, or a segment's chosen take. */
+export type AssemblyPiece = { kind: "source"; start: number; end: number } | { kind: "take"; start: number; end: number; take: SwapTake; segmentId: string };
+
+/**
+ * The clip's timeline for the assembly: kept shots as they were filmed (neighbours merged into one piece), swapped
+ * shots as their segments' chosen takes, in order. Every swapped shot needs a current take for every segment.
+ */
+export function assemblyPieces(project: SwapProject, clip: SwapClip): { pieces: AssemblyPiece[] } | { problem: string } {
+ if (!clip.shots.length) return { problem: "Confirm the clip's shots first" };
+ if (!clip.shots.some((s) => s.mode === "generate")) return { problem: "No shot replaces the character — mark at least one shot Replace character" };
+ const pieces: AssemblyPiece[] = [];
+ for (const [si, shot] of clip.shots.entries()) {
+ if (shot.mode === "preserve") {
+ const last = pieces.at(-1);
+ if (last?.kind === "source" && last.end === shot.start) last.end = shot.end;
+ else pieces.push({ kind: "source", start: shot.start, end: shot.end });
+ continue;
+ }
+ const items = currentSegments(shot);
+ const states = segmentStates(project, clip, shot, items);
+ for (const [gi, seg] of items.entries()) {
+ const t = takeOf(seg);
+ if (!t || states[gi].status !== "ready") return { problem: `Shot ${si + 1}, segment ${gi + 1} has no current take — generate it, or use a take that matches its settings` };
+ pieces.push({ kind: "take", start: shot.start + seg.start, end: shot.start + seg.end, take: t, segmentId: seg.id });
+ }
+ }
+ return { pieces };
+}
+
+/** 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 Finish stage (Akatz's refinement) — not runnable from the public release
+
+export const FINISH_UNAVAILABLE = {
+ title: "Finish: clean backplate and alpha compositing",
+ reason:
+ "Not available yet. Akatz Labs' Finish stage rebuilds a clean background plate with H3 Relay's Person Remover and the removal-continuation LoRA (h3-removal-continuation/B-step2000), then composites alpha mattes of the source and the character. The public release can't run it: the removal-continuation LoRA isn't published, templates/alpha.json is missing from the repository, and Akatz's own app says “Raw assembly migration is pending”.",
+ source: "docs/research/openjutsu-6.md §4.2",
+} as const;
+
+/** Where Akatz's GPU workers went: Fuobe's ComfyUI connection (and its isolated worker); no SSH workers. */
+export const WORKERS_NOTE = "Runs on your ComfyUI (Settings → ComfyUI). Akatz Labs' local and SSH GPU workers map to that connection and the isolated worker; Fuobe doesn't open SSH sessions.";
diff --git a/tests/swap-studio.test.ts b/tests/swap-studio.test.ts
new file mode 100644
index 00000000..43c43380
--- /dev/null
+++ b/tests/swap-studio.test.ts
@@ -0,0 +1,694 @@
+import { describe, expect, it } from "vitest";
+import { coarseTimes, coarseWindows, mafd, sceneCuts, sceneScores, studioFrames, timeFrame, windowCuts, windowFrames } from "@/lib/av/scene-cuts";
+import {
+ addCut,
+ applyLayout,
+ assemblyPieces,
+ assemblyTakes,
+ autoSelect,
+ buildSegmentPrompt,
+ clipProblem,
+ cueWords,
+ currentSegments,
+ DEFAULT_SETTINGS,
+ dependencies,
+ digest,
+ enginePrompt,
+ exportDecisions,
+ maskPieceAt,
+ maskPieces,
+ maskProblem,
+ moveCut,
+ newSegment,
+ newShot,
+ normalizedSize,
+ planQueue,
+ predecessors,
+ referenceContext,
+ removeCut,
+ removeTake,
+ segmentDialogue,
+ segmentPrompt,
+ segmentSpeaker,
+ segmentStates,
+ segmentsProblem,
+ selectTake,
+ settingSignature,
+ shotPrompt,
+ shotsFromCuts,
+ shotSpeaker,
+ speakerIn,
+ stableJson,
+ updateTake,
+ voicesOf,
+ windowRanges,
+ wordsIn,
+ type MaskVersion,
+ type SwapClip,
+ type SwapProject,
+ type SwapSegment,
+ type SwapShot,
+ type SwapTake,
+} from "@/lib/catalog/swap-studio";
+import { cloudCallSeconds, maskPointsPayload, planAnchor, planAssembly, planMask, planNormalize, planSegmentTake, planTranscribe, STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";
+
+// ---------------------------------------------------------------------------
+// Fixtures
+
+// One sequence for the whole file: ids made in different calls never collide.
+let tick = 0;
+const golden = () => (((tick++ * 0.6180339887) % 1) + 1) % 1;
+const seq = () => golden;
+
+function frame(value: number, n = 16): Uint8ClampedArray {
+ const px = new Uint8ClampedArray(n * 4);
+ for (let i = 0; i < n; i++) px.set([value, value, value, 255], i * 4);
+ return px;
+}
+
+function clipOf(over: Partial<SwapClip> = {}): SwapClip {
+ return {
+ 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 projectOf(clips: SwapClip[], engine: SwapProject["engine"] = "open"): SwapProject {
+ return { id: "p1", name: "Demo", engine, character: { image: "/api/files/uploads/x/hero.png", description: "a woman in a yellow raincoat" }, defaults: { ...DEFAULT_SETTINGS }, clips, createdAt: 0, updatedAt: 0, revision: 1 };
+}
+
+function shotOf(start: number, end: number, over: Partial<SwapShot> = {}): SwapShot {
+ return { ...newShot(start, end, DEFAULT_SETTINGS, true, seq()), id: `shot-${start}`, ...over };
+}
+
+function take(id: string, over: Partial<SwapTake> = {}): SwapTake {
+ return { id, createdAt: 1, engine: "open", state: "launched", genId: `g-${id}`, signature: "", dependencies: [], prompt: "", seed: 1, favourite: false, decision: "pending", notes: "", ...over };
+}
+
+/** Segments whose selected takes match their current settings (and what they continue from). */
+function ready(project: SwapProject, clip: SwapClip, shot: SwapShot): SwapShot {
+ const items = currentSegments(shot).map((s) => ({ ...s }));
+ const out = { ...shot, segments: items };
+ items.forEach((seg, i) => {
+ const t = take(`t-${seg.id}`, { signature: settingSignature(project, clip, out, seg), dependencies: dependencies(items, i) });
+ items[i] = { ...seg, takes: [t], selectedTake: t.id };
+ // Later dependencies name the selected takes: recompute once the earlier one is set.
+ for (let j = i + 1; j < items.length; j++) items[j] = { ...items[j] };
+ });
+ items.forEach((seg, i) => {
+ const t = { ...seg.takes[0], dependencies: dependencies(items, i), signature: settingSignature(project, clip, out, seg) };
+ items[i] = { ...seg, takes: [t] };
+ });
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Shot detection maths (FFmpeg's scene score)
+
+describe("scene cuts", () => {
+ it("scores a still frame 0 and a hard cut over Akatz's 0.32", () => {
+ const frames = [frame(20), frame(20), frame(20), frame(200), frame(200)];
+ const scores = sceneScores(frames);
+ expect(scores[0]).toBe(0);
+ expect(scores[1]).toBe(0);
+ expect(scores[3]).toBeCloseTo(1, 5); // MAFD 180, jump 180: min / 100, clipped to 1
+ expect(scores[4]).toBe(0);
+ expect(sceneCuts(scores, [0, 1, 2, 3, 4], 5)).toEqual([3]);
+ });
+
+ it("doesn't cut on steady motion: a high MAFD without a jump scores low", () => {
+ // Every frame differs from the last by 40 levels: MAFD 40 each time, no jump after the first pair.
+ const frames = Array.from({ length: 8 }, (_, i) => frame((i * 40) % 256));
+ const scores = sceneScores(frames.slice(0, 6));
+ expect(mafd(frames[0], frames[1])).toBeCloseTo(40, 5);
+ expect(scores.slice(2).every((s) => s < 0.32)).toBe(true);
+ // The second frame has no MAFD before it (FFmpeg starts at 0): it scores MAFD / 100.
+ expect(scores[1]).toBeCloseTo(0.4, 5);
+ });
+
+ it("ignores a stretch's first two frames, except at the clip's start", () => {
+ const frames = [frame(10), frame(80), frame(150), frame(150), frame(150)];
+ // From frame 40: the jump at index 1 is an artefact of starting mid-clip.
+ expect(windowCuts([40, 41, 42, 43, 44], frames, 480)).toEqual([]);
+ // From frame 0 FFmpeg's history is just as empty: a jump at frame 1 counts.
+ expect(windowCuts([0, 1, 2, 3, 4], [frame(0), frame(200), frame(200), frame(200), frame(200)], 480)).toEqual([1]);
+ });
+
+ it("keeps cuts inside the clip and drops repeats", () => {
+ expect(sceneCuts([0, 0.9, 0.9, 0.5], [0, 0, 479, 480], 480)).toEqual([479]);
+ expect(sceneCuts([1, 1], [12, 12], 480)).toEqual([12]);
+ });
+
+ it("plans the coarse pass and the stretches the fine pass reads", () => {
+ const times = coarseTimes(10, 6);
+ expect(times[0]).toBe(0);
+ expect(times.at(-1)).toBe(10);
+ expect(times.length).toBe(61);
+ expect(coarseTimes(150, 6, 600).length).toBeLessThanOrEqual(601);
+ const scores = times.map((_, i) => (i === 30 || i === 31 ? 0.5 : 0));
+ const w = coarseWindows(times, scores, studioFrames(10));
+ // Samples 29–31 are one stretch: frames from two before sample 29 to one after sample 31.
+ expect(w).toEqual([{ from: timeFrame(times[29]) - 2, to: timeFrame(times[31]) + 1 }]);
+ expect(windowFrames(w[0]).length).toBe(w[0].to - w[0].from + 1);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Clips and shots
+
+describe("clips and shots", () => {
+ it("takes the researched formats and length", () => {
+ expect(clipProblem({ name: "a.avi", duration: 10 })).toBeNull();
+ expect(clipProblem({ name: "a.mkv", duration: 149.66 })).toBeNull();
+ expect(clipProblem({ name: "a.gif" })).toMatch(/MP4, MOV, MKV, WebM or AVI/);
+ expect(clipProblem({ name: "a.mp4", duration: 150 })).toMatch(/149\.66/);
+ expect(normalizedSize(3840, 2160)).toEqual({ width: 2048, height: 1152 });
+ expect(normalizedSize(1279, 721)).toEqual({ width: 1278, height: 720 });
+ });
+
+ it("makes shots from cuts and keeps an unchanged shot whole", () => {
+ const clip = clipOf();
+ const first = shotsFromCuts(clip, [120, 300], DEFAULT_SETTINGS, undefined, seq());
+ expect(first.map((s) => [s.start, s.end])).toEqual([
+ [0, 120],
+ [120, 300],
+ [300, 480],
+ ]);
+ const edited = { ...first[0], mode: "preserve" as const, approvedAnchor: "a1" };
+ const second = shotsFromCuts({ ...clip, shots: [edited, first[1], first[2]] }, [120, 200, 300], DEFAULT_SETTINGS, undefined, seq());
+ expect(second[0]).toBe(edited);
+ // A changed shot keeps the mode and who of the shot it overlaps most, but nothing frame-bound.
+ expect(second[1].start).toBe(120);
+ expect(second[1].approvedAnchor).toBeNull();
+ expect(second.length).toBe(4);
+ const modes = shotsFromCuts(clip, [240], DEFAULT_SETTINGS, ["preserve", "generate"], seq());
+ expect(modes.map((s) => s.mode)).toEqual(["preserve", "generate"]);
+ });
+
+ it("adds, moves and removes cuts within the clip", () => {
+ expect(addCut([120], 60, 480)).toEqual([60, 120]);
+ expect(addCut([120], 0, 480)).toEqual([120]);
+ expect(addCut([120], 480, 480)).toEqual([120]);
+ expect(moveCut([60, 120], 120, 10, 480)).toEqual([60, 61]);
+ expect(moveCut([60, 120], 60, 500, 480)).toEqual([119, 120]);
+ expect(removeCut([60, 120], 60)).toEqual([120]);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Transcript, speakers and prompts
+
+describe("words and prompts", () => {
+ const cues = [
+ { start: 0, end: 2, text: "Hello there my friend", speaker: "speaker_0" },
+ { start: 6, end: 7, text: "Who are you?", speaker: "speaker_1" },
+ ];
+
+ it("spreads a cue's words over its time and takes them by their middle", () => {
+ const words = cueWords(cues);
+ expect(words.map((w) => w.text)).toEqual(["Hello", "there", "my", "friend", "Who", "are", "you?"]);
+ // Frames 0–24 (0–1 s): "Hello" (mid 0.25) and "there" (mid 0.75).
+ expect(wordsIn(words, 0, 24).map((w) => w.text)).toEqual(["Hello", "there"]);
+ expect(voicesOf(cues)).toEqual(["speaker_0", "speaker_1"]);
+ });
+
+ it("marks who speaks from the voices' roles", () => {
+ const words = cueWords(cues);
+ expect(speakerIn(words, { speaker_0: "target", speaker_1: "offscreen" }, 0, 48)).toBe("target");
+ expect(speakerIn(words, { speaker_0: "target", speaker_1: "offscreen" }, 144, 168)).toBe("offscreen");
+ expect(speakerIn(words, {}, 72, 96)).toBe("none");
+ const clip = clipOf({ transcript: { cues, voices: { speaker_0: "other" } } });
+ expect(shotSpeaker(clip, shotOf(0, 48))).toBe("other");
+ expect(shotSpeaker(clip, shotOf(0, 48, { speaker: "none" }))).toBe("none");
+ expect(shotSpeaker(clipOf({ source: { ...clipOf().source, hasAudio: false } }), shotOf(0, 48))).toBe("none");
+ });
+
+ it("builds the shot prompt in H3's tags with the speaker line", () => {
+ const p = shotPrompt("a woman in a yellow raincoat.", "offscreen", "Hello there");
+ expect(p).toContain("Replace only the selected person in <Video 1> with the single character in <Picture 1>: a woman in a yellow raincoat.");
+ expect(p).toContain("<Picture 2> is the exact first-frame scene and pose anchor.");
+ expect(p).toContain("Speech is offscreen; do not make the selected character speak.");
+ expect(p).toContain('Current shot dialogue: "Hello there".');
+ expect(shotPrompt("", "none", "", false)).not.toContain("<Picture 2>");
+ expect(shotPrompt("", "none", "")).toContain("the reference character");
+ });
+
+ it("builds each segment's prompt from its own words and pictures", () => {
+ const clip = clipOf({ transcript: { cues, voices: { speaker_0: "target", speaker_1: "other" } } });
+ const project = projectOf([clip]);
+ const shot = shotOf(0, 240, { approvedAnchor: "a1", anchors: [{ id: "a1", createdAt: 0, source: "imported", url: "/api/files/a.png" }] });
+ const items = currentSegments(shot);
+ expect(items.map((s) => [s.start, s.end])).toEqual([
+ [0, 124],
+ [124, 240],
+ ]);
+ const p0 = segmentPrompt(project, clip, shot, items[0]);
+ expect(p0).toContain("<Picture 2> is the exact first-frame scene and pose anchor.");
+ expect(p0).toContain('Current segment dialogue: "Hello there my friend".');
+ expect(p0).not.toContain("Current shot dialogue");
+ const p1 = segmentPrompt(project, clip, shot, items[1]);
+ expect(p1).toContain("<Picture 2> is the generated boundary from the preceding segment.");
+ expect(p1).toContain('"Who are you?"');
+ expect(segmentDialogue(clip, shot, items[1])).toBe("Who are you?");
+ expect(segmentSpeaker(clip, shot, items[1])).toBe("other");
+ expect(segmentPrompt(project, clip, shot, { ...items[1], performancePrompt: "Exact words" })).toBe("Exact words");
+ const built = buildSegmentPrompt(project, clip, shot, { ...items[1], prompt: "Keep the umbrella" });
+ expect(built).toContain("Another person is speaking");
+ expect(built).toContain("Current segment dialogue:");
+ expect(built.endsWith("Keep the umbrella")).toBe(true);
+ expect(referenceContext(18, true)).toContain("<Picture 3> is an additional scene and performance reference");
+ expect(referenceContext(0, false)).toBe("");
+ });
+
+ it("puts the prompt in fal's words on the cloud", () => {
+ const text = "Replace only the selected person in <Video 1> with the single character in <Picture 1>. <Picture 2> is the generated boundary. <Picture 3> is a reference. <Audio 1> and source video determine exact timing.";
+ expect(enginePrompt(text, "open", { selection: "largest", index: 0, words: "person" })).toBe(text);
+ const cloud = enginePrompt(text, "cloud", { selection: "leftmost", index: 0, words: "person" }, { swapPictures: true });
+ expect(cloud).toContain("Replace only the person on the left in Video 1 with the single character in Image 1.");
+ expect(cloud).toContain("Image 3 is the generated boundary. Image 2 is a reference.");
+ expect(cloud).toContain("Video 1's sound and motion determine exact timing");
+ expect(cloud).not.toMatch(/<|>/);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Segment planning and continuation dependencies
+
+describe("segments", () => {
+ it("follows H3's window plan for the default layout", () => {
+ expect(windowRanges(120, 124, 18)).toEqual([{ start: 0, end: 120 }]);
+ expect(windowRanges(300, 124, 18)).toEqual([
+ { start: 0, end: 124 },
+ { start: 124, end: 247 },
+ { start: 247, end: 300 },
+ ]);
+ const shot = shotOf(0, 300);
+ const items = currentSegments(shot);
+ expect(items.map((s) => s.connection)).toEqual(["start", "continue", "continue"]);
+ expect(items.map((s) => s.anchorMode)).toEqual(["shot", "none", "none"]);
+ expect(items[1].seed).toBe(DEFAULT_SETTINGS.seed + 1);
+ // The default layout's ids are stable per range.
+ expect(currentSegments(shot).map((s) => s.id)).toEqual(items.map((s) => s.id));
+ });
+
+ it("checks a layout the way Akatz's app does", () => {
+ const shot = shotOf(0, 400);
+ const a = newSegment(shot, 0, 200, 0, seq());
+ const b = newSegment(shot, 200, 400, 1, seq());
+ expect(segmentsProblem(shot, [a, b])).toBeNull();
+ expect(segmentsProblem(shot, [a, { ...b, start: 201 }])).toMatch(/without gaps/);
+ expect(segmentsProblem(shot, [{ ...a, connection: "continue" }, b])).toMatch(/first segment starts fresh/);
+ expect(segmentsProblem(shot, [{ ...a, end: 10 }, { ...b, start: 10, history: 18 }])).toMatch(/history extends before/);
+ expect(segmentsProblem(shot, [{ ...a, end: 362 }, { ...b, start: 362, connection: "start" }])).toBeNull();
+ expect(segmentsProblem({ start: 0, end: 400 }, [{ ...a, end: 363 }, { ...b, start: 363, connection: "start" }])).toMatch(/one diffusion pass/);
+ // A continuing 361-frame segment needs 362 with its boundary: still one pass. 362 continuing frames don't fit.
+ expect(segmentsProblem({ start: 0, end: 723 }, [{ ...a, end: 362 }, { ...b, start: 362, end: 723 }])).toBeNull();
+ expect(segmentsProblem({ start: 0, end: 724 }, [{ ...a, end: 362 }, { ...b, start: 362, end: 724 }])).toMatch(/Segment 2 must fit one diffusion pass/);
+ expect(segmentsProblem(shot, [a, b], "cloud")).toBeNull();
+ expect(segmentsProblem({ start: 0, end: 230 }, [{ ...a, end: 200 }, { ...b, start: 200, end: 230 }], "cloud")).toMatch(/2–15 s/);
+ });
+
+ it("splits, merges, moves boundaries and partitions", () => {
+ const shot = shotOf(0, 600, { segments: null });
+ const parts = applyLayout(shot, { op: "partition", frames: 240 }, seq());
+ expect(parts.map((s) => [s.start, s.end, s.connection])).toEqual([
+ [0, 240, "start"],
+ [240, 480, "continue"],
+ [480, 600, "continue"],
+ ]);
+ const withDirection = { ...shot, segments: parts.map((s, i) => (i === 1 ? { ...s, prompt: "Smile" } : s)) };
+ const split = applyLayout(withDirection, { op: "split", frame: 300 }, seq());
+ expect(split.map((s) => [s.start, s.end])).toEqual([
+ [0, 240],
+ [240, 300],
+ [300, 480],
+ [480, 600],
+ ]);
+ expect(split[1].prompt).toBe("Smile");
+ expect(split[2].needsReview).toBe(true);
+ // The untouched first and last segments are the same segments.
+ expect(split[0].id).toBe(parts[0].id);
+ const merged = applyLayout({ ...shot, segments: split }, { op: "merge", index: 2 }, seq());
+ expect(merged.map((s) => [s.start, s.end])).toEqual([
+ [0, 240],
+ [240, 480],
+ [480, 600],
+ ]);
+ // Segment 2 starts fresh; moving its end to 245 leaves segment 3 five frames of sequence to continue from.
+ const fresh = merged.map((s, i) => (i === 1 ? { ...s, connection: "start" as const } : s));
+ const moved = applyLayout({ ...shot, segments: fresh }, { op: "boundary", index: 2, frame: 245 }, seq());
+ expect(moved.map((s) => [s.start, s.end])).toEqual([
+ [0, 240],
+ [240, 245],
+ [245, 600],
+ ]);
+ // A continuation can't reach before its sequence: 5 frames back holds a history of 1 at most.
+ expect(moved[2].history).toBe(1);
+ expect(() => applyLayout({ ...shot, segments: merged }, { op: "boundary", index: 1, frame: 10 })).toThrow(/one diffusion pass/);
+ expect(() => applyLayout(shot, { op: "split", frame: 0 })).toThrow(/playhead/);
+ expect(() => applyLayout(shot, { op: "partition", frames: 400 })).toThrow(/15 seconds/);
+ });
+
+ it("draws history from the segments before, never across a fresh start", () => {
+ const shot = shotOf(0, 400);
+ const a = newSegment(shot, 0, 10, 0, seq());
+ const b = { ...newSegment(shot, 10, 20, 1, seq()), history: 1 };
+ const c = { ...newSegment(shot, 20, 400, 2, seq()), history: 18 };
+ const items = [a, b, c];
+ // 18 frames: 10 from b, 8 from a.
+ expect(predecessors(items, 2).map((p) => [p.segment.id, p.frames])).toEqual([
+ [a.id, 8],
+ [b.id, 10],
+ ]);
+ expect(dependencies(items, 1)).toEqual([{ segmentId: a.id, takeId: null, frames: 1 }]);
+ expect(() => predecessors([a, { ...b, connection: "start" }, c], 2)).toThrow(/Not enough preceding frames/);
+ expect(predecessors([a, b, { ...c, connection: "start" }], 2)).toEqual([]);
+ });
+
+ it("knows which takes are current, stale or missing", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shot = ready(project, clip, shotOf(0, 300, { approvedAnchor: "a1", anchors: [{ id: "a1", createdAt: 0, source: "imported", url: "/api/files/a.png" }] }));
+ expect(segmentStates(project, clip, shot).map((s) => s.status)).toEqual(["ready", "ready", "ready"]);
+ // A new seed on the first segment: its take is stale, and the ones continuing from it are blocked.
+ const changed = { ...shot, segments: shot.segments!.map((s, i) => (i === 0 ? { ...s, seed: 7 } : s)) };
+ const states = segmentStates(project, clip, changed);
+ expect(states.map((s) => s.status)).toEqual(["stale", "stale", "stale"]);
+ expect(states[1].blocked).toBe(true);
+ // A new character picture makes every take stale.
+ const other = { ...project, character: { ...project.character, image: "/api/files/b.png" } };
+ expect(segmentStates(other, clip, shot)[0].status).toBe("stale");
+ // The cloud doesn't mask: a mask approved later doesn't make its takes stale.
+ const cloud = projectOf([clip], "cloud");
+ const cloudShot = ready(cloud, clip, shotOf(0, 120, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } }));
+ const masked = { ...cloudShot, approvedMask: "m1", masks: [{ id: "m1" } as MaskVersion] };
+ expect(segmentStates(cloud, clip, masked)[0].status).toBe("ready");
+ });
+
+ it("queues one segment, from here, or all, with continuations waiting on their segment", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const base = shotOf(0, 300, { approvedAnchor: "a1", anchors: [{ id: "a1", createdAt: 0, source: "imported", url: "/api/files/a.png" }] });
+ const items = currentSegments(base);
+ const shot = { ...base, segments: items };
+ const active = () => false;
+ const all = planQueue(project, clip, shot, items[0].id, "all", { active });
+ expect("entries" in all && all.entries.map((e) => [e.index, e.waitsOn])).toEqual([
+ [0, []],
+ [1, [items[0].id]],
+ [2, [items[1].id]],
+ ]);
+ // Segment 2 alone needs segment 1's take first.
+ const one = planQueue(project, clip, shot, items[1].id, "segment", { active });
+ expect("problem" in one && one.problem).toMatch(/Generate segment 1 first/);
+ // With segment 1 current, "from here" makes 2 and 3; 3 waits on 2.
+ const done = ready(project, clip, shot);
+ const fresh = { ...done, segments: done.segments!.map((s, i) => (i ? { ...s, takes: [], selectedTake: null } : s)) };
+ const from = planQueue(project, clip, fresh, items[1].id, "from", { active, hasMaster: () => true });
+ expect("entries" in from && from.entries.map((e) => [e.index, e.waitsOn])).toEqual([
+ [1, []],
+ [2, [items[1].id]],
+ ]);
+ // Without a master to continue from (your GPU), it can't start.
+ const noMaster = planQueue(project, clip, fresh, items[1].id, "segment", { active, hasMaster: () => false });
+ expect("problem" in noMaster && noMaster.problem).toMatch(/lossless master/);
+ // A segment already queued is refused when asked for alone, and skipped otherwise.
+ const busy = { ...fresh, segments: fresh.segments!.map((s, i) => (i === 1 ? { ...s, takes: [take("w", { state: "waiting" })] } : s)) };
+ expect("problem" in planQueue(project, clip, busy, items[1].id, "segment", { active })).toBe(true);
+ // Everything current: nothing to do.
+ expect(planQueue(project, clip, done, items[0].id, "all", { active })).toEqual({ problem: "These segments are already current, queued or generating" });
+ // The scene anchor must be approved.
+ const noAnchor = planQueue(project, clip, { ...shot, approvedAnchor: null }, items[0].id, "segment", { active });
+ expect("problem" in noAnchor && noAnchor.problem).toMatch(/approve a scene anchor/);
+ expect(planQueue(project, clip, { ...shot, mode: "preserve" }, items[0].id, "all", { active })).toEqual({ problem: expect.stringMatching(/keeps its original/) });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Masks
+
+describe("mask point payloads", () => {
+ const who = { selection: "rightmost" as const, index: 0, words: "the man in the hat" };
+ const pts = [
+ { x: 100, y: 200, label: "positive" as const },
+ { x: 300, y: 50, label: "negative" as const },
+ ];
+
+ it("sends clicks to SAM 3.1 as each engine takes them", () => {
+ expect(maskPointsPayload("open", pts, who)).toEqual({ points: pts, prompt: "the man in the hat", selection: "index", subjectIndex: 0 });
+ expect(maskPointsPayload("open", [], who)).toEqual({ prompt: "the man in the hat", selection: "rightmost", subjectIndex: 0 });
+ expect(maskPointsPayload("open", [], { selection: "index", index: 2, words: "" })).toEqual({ prompt: "person", selection: "index", subjectIndex: 2 });
+ expect(maskPointsPayload("cloud", pts, who)).toEqual({ points: pts });
+ expect(maskPointsPayload("cloud", [], who)).toEqual({ prompt: "the man in the hat" });
+ });
+
+ it("plans the open mask with the frame, its span and the version it corrects", () => {
+ const clip = clipOf();
+ const shot = shotOf(120, 360);
+ const base: MaskVersion = { id: "m1", createdAt: 0, kind: "track", engine: "open", frame: 0, points: [], who, pieces: [{ from: 0, frames: 240, url: "/api/files/m1.mp4" }] };
+ const [step] = planMask({ engine: "open", clip, shot, kind: "frame", frame: 30, points: pts, who, base });
+ expect(step.request.modelId).toBe(STUDIO_MODELS.open.mask);
+ // Frames 120–360 of the clip: Trim Video starts half a frame early and runs a quarter frame long.
+ expect(step.request.params).toMatchObject({ startTime: 119.5 / 24, endTime: expect.closeTo((119.5 + 240.25) / 24, 9), points: pts, extra: { keyFrame: 30, spanFrames: 1, shotFrames: 240, prevMask: "/api/files/m1.mp4", selection: "index", subjectIndex: 0 } });
+ // Tracking the whole shot from its first frame needs no earlier version.
+ const [whole] = planMask({ engine: "open", clip, shot, kind: "track", frame: 0, points: [], who, base });
+ expect((whole.request.params?.extra as Record<string, unknown>).prevMask).toBeUndefined();
+ expect(whole.request.inputs?.video).toBe(clip.normalized!.url);
+ });
+
+ it("plans the cloud mask on a cut that starts at the clicked frame", () => {
+ const clip = clipOf();
+ const shot = shotOf(120, 360);
+ const steps = planMask({ engine: "cloud", clip, shot, kind: "track", frame: 24, points: pts, who, base: null });
+ expect(steps[0].request).toMatchObject({ modelId: "trim-video", params: { startTime: 6, endTime: 15 }, inputs: { video: clip.source.url } });
+ expect(steps[1].request).toMatchObject({ modelId: "sam-3-1-video-mask", params: { points: pts, matteOutput: "matte" } });
+ expect(steps[1].request.prompt).toBeUndefined();
+ expect(steps[1].chain).toEqual([{ slot: "video" }]);
+ });
+
+ it("layers cloud pieces and finds the one covering a frame", () => {
+ const base: MaskVersion = { id: "m1", createdAt: 0, kind: "track", engine: "cloud", frame: 0, points: [], who, pieces: [{ from: 0, frames: 240, url: "a" }] };
+ const pieces = maskPieces("cloud", "track", 100, 240, base);
+ expect(pieces).toEqual([
+ { from: 0, frames: 240, url: "a" },
+ { from: 100, frames: 140 },
+ ]);
+ const v = { ...base, pieces: [pieces[0], { ...pieces[1], url: "b" }] };
+ expect(maskPieceAt(v, 50)?.url).toBe("a");
+ expect(maskPieceAt(v, 150)?.url).toBe("b");
+ expect(maskPieceAt(v, 240)).toBeNull();
+ expect(maskPieces("open", "frame", 100, 240, base)).toEqual([{ from: 0, frames: 240 }]);
+ expect(maskProblem("open", "frame", 10, 240, [], who, base)).toMatch(/Click the person/);
+ expect(maskProblem("open", "frame", 10, 240, pts, who, null)).toMatch(/Track the shot first/);
+ expect(maskProblem("cloud", "track", 10, 240, [{ x: 1, y: 1, label: "negative" }], who, null)).toMatch(/include point/);
+ expect(maskProblem("cloud", "track", 240, 240, [], who, null)).toMatch(/inside the shot/);
+ expect(maskProblem("cloud", "track", 0, 240, [], who, base)).toBeNull();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Takes and review
+
+describe("takes and review", () => {
+ const seg: SwapSegment = { ...newSegment(shotOf(0, 120), 0, 120, 0, seq()), takes: [take("a"), take("b"), take("c", { state: "stopped", reason: "x" })], selectedTake: "a" };
+
+ it("picks, favourites, decides and notes takes", () => {
+ expect(selectTake(seg, "b").selectedTake).toBe("b");
+ expect(() => selectTake(seg, "c")).toThrow(/didn't run/);
+ expect(() => selectTake(seg, "zz")).toThrow(/gone/);
+ const fav = updateTake(seg, "b", { favourite: true, decision: "keep", notes: "Best eyes" });
+ expect(fav.takes[1]).toMatchObject({ favourite: true, decision: "keep", notes: "Best eyes" });
+ expect(() => updateTake(seg, "b", { notes: "x".repeat(2001) })).toThrow(/2,000/);
+ expect(removeTake(seg, "a").selectedTake).toBeNull();
+ expect(removeTake(seg, "b").selectedTake).toBe("a");
+ });
+
+ it("selects a finished take only when nothing changed since it was queued", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shot = shotOf(0, 120, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } });
+ const items = currentSegments(shot);
+ const s = items[0];
+ const t = take("new", { signature: settingSignature(project, clip, shot, s), dependencies: [], replaces: null });
+ expect(autoSelect(project, clip, shot, s, t, items)).toBe(true);
+ expect(autoSelect(project, clip, shot, { ...s, selectedTake: "other" }, t, items)).toBe(false);
+ expect(autoSelect(project, clip, shot, { ...s, seed: 99 }, t, [{ ...s, seed: 99 }])).toBe(false);
+ });
+
+ it("exports every decision as JSON", () => {
+ const clip = clipOf({ review: "maybe", reviewNotes: "Check shot 2", shots: [shotOf(0, 120, { segments: [seg] }), shotOf(120, 480, { mode: "preserve" })] });
+ const out = exportDecisions(projectOf([clip]), (t) => (t.id === "a" ? "/api/files/a.mp4" : undefined), new Date("2026-10-27T10:00:00Z"));
+ expect(out.exportedAt).toBe("2026-10-27T10:00:00.000Z");
+ expect(out.clips[0]).toMatchObject({ clip: "walk", review: "maybe", notes: "Check shot 2", assembled: false });
+ expect(out.clips[0].shots[0].segments[0]).toMatchObject({ segment: 1, frames: [0, 120], selectedTake: "a" });
+ expect(out.clips[0].shots[0].segments[0].takes[0]).toMatchObject({ take: "a", video: "/api/files/a.mp4", decision: "pending" });
+ expect(out.clips[0].shots[1].segments).toEqual([]);
+ expect(JSON.parse(JSON.stringify(out))).toEqual(out);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Engine steps
+
+describe("engine steps", () => {
+ it("prepares the clip at 24 fps on your GPU and transcribes on both engines", () => {
+ const clip = clipOf();
+ const [n] = planNormalize(clip);
+ expect(n.request).toMatchObject({ modelId: "oss-fit-clip", op: "trim", inputs: { video: clip.source.url }, params: { startTime: 0, fps: 24, extra: { width: 1920, height: 1080 } } });
+ expect(n.request.feature).toBe("swap-studio-step");
+ expect(planTranscribe(clip, "cloud")[0].request).toMatchObject({ modelId: "scribe-v2", inputs: { video: clip.source.url } });
+ expect(planTranscribe(clip, "open")[0].request).toMatchObject({ modelId: "oss-qwen3-asr", inputs: { video: clip.normalized!.url } });
+ });
+
+ it("makes an anchor from the frame with the engine's image edit", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shot = shotOf(48, 300, { anchorInstructions: "Rain on her hood", who: { selection: "leftmost", index: 0, words: "person" } });
+ const open = planAnchor({ engine: "open", project, clip, shot, frame: 48 });
+ expect(open.map((s) => s.request.modelId)).toEqual(["oss-extract-frame", "oss-qwen-edit"]);
+ expect(open[0].request.params).toMatchObject({ startTime: 47.5 / 24, extra: { frameIndex: 0 } });
+ expect(open[1].request.prompt).toContain("Replace ONLY the person on the left");
+ expect(open[1].request.prompt).toContain("a woman in a yellow raincoat");
+ expect(open[1].request.prompt?.endsWith("Rain on her hood")).toBe(true);
+ expect(open[1].chain).toEqual([{ slot: "images", position: "first" }]);
+ const cloud = planAnchor({ engine: "cloud", project, clip, shot: { ...shot, anchorBasePrompt: "My own brief" }, frame: 48, modelId: "nano-banana-pro" });
+ expect(cloud.map((s) => s.request.modelId)).toEqual(["trim-video", "extract-frame", "nano-banana-pro"]);
+ expect(cloud[2].request.prompt).toBe("My own brief\n\nRain on her hood");
+ });
+
+ it("plans a take on your GPU with the mask, the history master and the anchor after the boundary", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shot = shotOf(120, 420, { settings: { ...DEFAULT_SETTINGS, lora: "v1", expansion: 32 } });
+ const items = currentSegments(shot);
+ const { steps, final } = planSegmentTake({
+ engine: "open",
+ project,
+ clip,
+ shot,
+ seg: items[1],
+ shotNumber: 2,
+ segNumber: 2,
+ takeNumber: 1,
+ prompt: "P <Picture 2>",
+ history: 18,
+ anchor: "/api/files/anchor.png",
+ mask: "/api/files/mask.mp4",
+ previous: { master: "/api/files/master.mkv", frames: 124 },
+ });
+ expect(final).toBe("swap");
+ const r = steps[0].request;
+ expect(r.modelId).toBe("oss-h3-swap-segment");
+ expect(r.inputs).toEqual({ video: clip.normalized!.url, images: [project.character.image, "/api/files/anchor.png"] });
+ // The source starts 18 frames before the segment (the history the master replaces).
+ const first = 120 + 124 - 18;
+ expect(r.params).toMatchObject({ startTime: (first - 0.5) / 24, endTime: expect.closeTo((first - 0.5 + (247 - 124 + 18) + 0.25) / 24, 9), resolution: "768p", seed: items[1].seed });
+ expect(r.params?.extra).toMatchObject({ lora: "v1", maskGrow: 32, maskVideo: "/api/files/mask.mp4", maskStart: (124 - 18 - 0.5) / 24, historyVideo: "/api/files/master.mkv", historyStart: 106, historyLength: 18, anchorAfterHistory: true });
+ expect(() => planSegmentTake({ engine: "open", project, clip, shot, seg: items[1], shotNumber: 1, segNumber: 2, takeNumber: 1, prompt: "", history: 18, anchor: null, previous: null })).toThrow(/lossless master/);
+ });
+
+ it("plans a cloud take: the cut, the previous take's last frame and fal's H3 with the LoRA", () => {
+ const clip = clipOf();
+ const project = projectOf([clip], "cloud");
+ const shot = shotOf(0, 300, { who: { selection: "rightmost", index: 0, words: "person" } });
+ const items = currentSegments(shot);
+ const { steps } = planSegmentTake({ engine: "cloud", project, clip, shot, seg: items[1], shotNumber: 1, segNumber: 2, takeNumber: 3, prompt: "Replace only the selected person in <Video 1>. <Picture 2> is the generated boundary. <Picture 3> is a reference.", history: 18, anchor: "/api/files/a.png", previous: { video: "/api/files/prev.mp4", frames: 124 } });
+ expect(steps.map((s) => s.key)).toEqual(["cut", "boundary", "swap"]);
+ expect(steps[0].request.params).toEqual({ startTime: 124 / 24, endTime: 247 / 24 });
+ expect(steps[1].request).toMatchObject({ modelId: "extract-frame", inputs: { video: "/api/files/prev.mp4" }, params: { extra: { frame_type: "last" } } });
+ const swap = steps[2];
+ expect(swap.request.modelId).toBe("fuobe-character-swap");
+ // Image 2 is the anchor (a fixed input), Image 3 the boundary (chained after it): the prompt says so.
+ expect(swap.request.inputs?.images).toEqual([project.character.image, "/api/files/a.png"]);
+ expect(swap.chain).toEqual([{ slot: "video" }, { slot: "images", position: "last" }]);
+ expect(swap.request.prompt).toBe("Replace only the person on the right in Video 1. Image 3 is the generated boundary. Image 2 is a reference.");
+ expect(swap.request.loras?.[0].file).toBe("h3_character_swap_v1.5.safetensors");
+ expect(swap.request.params).toMatchObject({ duration: 6, sourceDuration: 123 / 24, resolution: "768p" });
+ expect(cloudCallSeconds(48)).toBe(5);
+ expect(cloudCallSeconds(361)).toBe(15);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Assembly plan
+
+describe("assembly", () => {
+ const clip = clipOf();
+ const project = projectOf([clip]);
+ const shots = [shotOf(0, 100, { mode: "preserve" }), shotOf(100, 160, { mode: "preserve" }), ready(project, clip, shotOf(160, 400, { settings: { ...DEFAULT_SETTINGS, useAnchor: false } })), shotOf(400, 480, { mode: "preserve" })];
+ const assembled = { ...clip, shots };
+
+ it("lays the chosen takes over the original timeline, kept shots merged", () => {
+ const r = assemblyPieces(project, assembled);
+ expect("pieces" in r).toBe(true);
+ const pieces = "pieces" in r ? r.pieces : [];
+ expect(pieces.map((p) => [p.kind, p.start, p.end])).toEqual([
+ ["source", 0, 160],
+ ["take", 160, 284],
+ ["take", 284, 400],
+ ["source", 400, 480],
+ ]);
+ expect(assemblyTakes(pieces).length).toBe(2);
+ const missing = assemblyPieces(project, { ...assembled, shots: [shots[0], shotOf(100, 480)] });
+ expect("problem" in missing && missing.problem).toMatch(/Shot 2, segment 1 has no current take/);
+ expect(assemblyPieces(project, { ...assembled, shots: [shots[0]] })).toEqual({ problem: expect.stringMatching(/No shot replaces/) });
+ });
+
+ it("fits, joins and puts the sound back on your GPU", () => {
+ const r = assemblyPieces(project, assembled);
+ const pieces = "pieces" in r ? r.pieces : [];
+ const { steps, final } = planAssembly({ engine: "open", clip: assembled, pieces, videoOf: (p) => `/api/files/${p.take.id}.mp4` });
+ expect(final).toBe("final");
+ expect(steps.filter((s) => s.request.modelId === "oss-fit-clip").length).toBe(4);
+ expect(steps[0].request.params).toMatchObject({ startTime: 0, endTime: 160 / 24, fps: 24, extra: { width: 1920, height: 1080 } });
+ expect(steps[3].request.params).toMatchObject({ startTime: 400 / 24, endTime: 400 / 24 + 80 / 24 });
+ expect(steps[1].request).toMatchObject({ inputs: { video: `/api/files/${pieces[1].kind === "take" ? pieces[1].take.id : ""}.mp4` }, params: { startTime: 0, endTime: 124 / 24 } });
+ const join = steps.find((s) => s.key === "join")!;
+ expect(join.request.modelId).toBe("oss-join-encoded");
+ expect(join.after).toEqual(["piece0", "piece1", "piece2", "piece3"]);
+ const mux = steps.find((s) => s.key === "final")!;
+ expect(mux.request).toMatchObject({ modelId: "oss-mux", feature: "swap-studio", inputs: { audio: clip.normalized!.url } });
+ expect(steps.filter((s) => s.request.feature === "swap-studio").length).toBe(1);
+ });
+
+ it("cuts, joins in folds of 24 and mutes a silent clip on the cloud", () => {
+ const many = Array.from({ length: 30 }, (_, i) => ({ kind: "source" as const, start: i * 10, end: i * 10 + 10 }));
+ const silent = { ...clip, source: { ...clip.source, hasAudio: false } };
+ const { steps, final } = planAssembly({ engine: "cloud", clip: silent, pieces: many, videoOf: () => "" });
+ expect(final).toBe("final");
+ expect(steps.filter((s) => s.request.modelId === "join-clips").map((s) => s.after?.length)).toEqual([24, 6, 2]);
+ const mux = steps.find((s) => s.key === "final")!;
+ expect(mux.request.inputs?.audio).toMatch(/^silence:|20/);
+ // One piece with sound: no join, the cut goes straight to the mux.
+ const one = planAssembly({ engine: "cloud", clip, pieces: [{ kind: "source", start: 0, end: 480 }], videoOf: () => "" });
+ expect(one.steps.map((s) => s.key)).toEqual(["piece0", "final"]);
+ expect(one.steps[1].after).toEqual(["piece0"]);
+ });
+
+ it("ends on the join for a silent clip on your GPU", () => {
+ const silent = { ...clip, source: { ...clip.source, hasAudio: false } };
+ const { steps, final } = planAssembly({ engine: "open", clip: silent, pieces: [{ kind: "source", start: 0, end: 100 }, { kind: "source", start: 100, end: 200 }], videoOf: () => "" });
+ expect(final).toBe("join");
+ expect(steps.find((s) => s.key === "join")!.request.feature).toBe("swap-studio");
+ });
+});
+
+describe("signatures", () => {
+ it("are stable whatever the key order", () => {
+ expect(stableJson({ b: 1, a: [2, { d: 1, c: 2 }] })).toBe('{"a":[2,{"c":2,"d":1}],"b":1}');
+ expect(digest({ a: 1, b: 2 })).toBe(digest({ b: 2, a: 1 }));
+ expect(digest({ a: 1 })).not.toBe(digest({ a: 2 }));
+ });
+});