The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Shorts Studio and Mixed Media: presets, segment planning, pipelines and API
Claudedf9cc2598ba1
diff --git a/src/app/api/mixed-media/estimate/route.ts b/src/app/api/mixed-media/estimate/route.tsnew file mode 100644index 00000000..3f2dc7f1--- /dev/null+++ b/src/app/api/mixed-media/estimate/route.ts@@ -0,0 +1,10 @@+import { estimateMixed } from "@/server/mixed-media";+import { MixedEstimateSchema, body, handle } from "@/server/shorts-schemas";++/** Frames, cost of the render and of a preview frame, and notes for the current settings. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, MixedEstimateSchema, "Pick a preset and the part of the clip to use");+ return Response.json(await estimateMixed(input));+ });+}diff --git a/src/app/api/mixed-media/preview/route.ts b/src/app/api/mixed-media/preview/route.tsnew file mode 100644index 00000000..8a887349--- /dev/null+++ b/src/app/api/mixed-media/preview/route.ts@@ -0,0 +1,10 @@+import { createMixedPreview } from "@/server/mixed-media";+import { MixedBodySchema, body, handle } from "@/server/shorts-schemas";++/** Generate one frame with the current settings before the full video. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, MixedBodySchema, "Pick a preset and upload a clip first");+ return Response.json(await createMixedPreview(input), { status: 201 });+ });+}diff --git a/src/app/api/mixed-media/route.ts b/src/app/api/mixed-media/route.tsnew file mode 100644index 00000000..02255477--- /dev/null+++ b/src/app/api/mixed-media/route.ts@@ -0,0 +1,11 @@+import { createMixed } from "@/server/mixed-media";+import { MixedBodySchema, body, handle } from "@/server/shorts-schemas";++/** Render a Mixed Media video (open: per frame; cloud: cut → restyle → original sound). */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, MixedBodySchema, "Pick a preset, upload a clip and choose up to 10 seconds");+ const { final, items } = await createMixed(input);+ return Response.json({ final, items }, { status: 201 });+ });+}diff --git a/src/app/api/shorts/estimate/route.ts b/src/app/api/shorts/estimate/route.tsnew file mode 100644index 00000000..e9937d52--- /dev/null+++ b/src/app/api/shorts/estimate/route.ts@@ -0,0 +1,10 @@+import { estimateShorts } from "@/server/shorts";+import { ShortsEstimateSchema, body, handle } from "@/server/shorts-schemas";++/** What a session would cost (or that it runs as a demo), how many segments it makes, and notes. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, ShortsEstimateSchema, "Pick a preset and the part of the clip to restyle");+ return Response.json(await estimateShorts(input));+ });+}diff --git a/src/app/api/shorts/presets/[id]/route.ts b/src/app/api/shorts/presets/[id]/route.tsnew file mode 100644index 00000000..374cde8b--- /dev/null+++ b/src/app/api/shorts/presets/[id]/route.ts@@ -0,0 +1,18 @@+import { deleteCustomPreset, ShortsError, updateCustomPreset } from "@/server/shorts";+import { PresetPatchSchema, body, handle } from "@/server/shorts-schemas";++export async function PATCH(request: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const patch = await body(request, PresetPatchSchema, "Those preset settings aren't valid");+ return Response.json(updateCustomPreset(id, patch));+ });+}++export async function DELETE(_req: Request, ctx: RouteContext<"/api/shorts/presets/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ if (!deleteCustomPreset(id)) throw new ShortsError("This preset no longer exists", 404);+ return new Response(null, { status: 204 });+ });+}diff --git a/src/app/api/shorts/presets/route.ts b/src/app/api/shorts/presets/route.tsnew file mode 100644index 00000000..1461326f--- /dev/null+++ b/src/app/api/shorts/presets/route.ts@@ -0,0 +1,17 @@+import { connection } from "next/server";+import { createCustomPreset, listCustomPresets } from "@/server/shorts";+import { PresetBodySchema, body, handle } from "@/server/shorts-schemas";++/** The user's own presets ("Created by you"). */+export async function GET() {+ await connection();+ return handle(() => Response.json({ items: listCustomPresets() }));+}++/** Create a preset from up to 10 reference images. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, PresetBodySchema, "Add 1–10 reference images");+ return Response.json(createCustomPreset(input), { status: 201 });+ });+}diff --git a/src/app/api/shorts/probe/route.ts b/src/app/api/shorts/probe/route.tsnew file mode 100644index 00000000..2c10ced2--- /dev/null+++ b/src/app/api/shorts/probe/route.ts@@ -0,0 +1,11 @@+import { z } from "zod";+import { probeSource } from "@/server/shorts";+import { body, handle } from "@/server/shorts-schemas";++/** An uploaded clip's length, size, frame rate and whether it has sound (from its MP4 / MOV header). */+export async function POST(request: Request) {+ return handle(async () => {+ const { url } = await body(request, z.object({ url: z.string().startsWith("/api/files/").max(500) }), "Upload the clip first");+ return Response.json(await probeSource(url));+ });+}diff --git a/src/app/api/shorts/sessions/[id]/route.ts b/src/app/api/shorts/sessions/[id]/route.tsnew file mode 100644index 00000000..1cda7a0d--- /dev/null+++ b/src/app/api/shorts/sessions/[id]/route.ts@@ -0,0 +1,31 @@+import { connection } from "next/server";+import { z } from "zod";+import { deleteSession, getSession, regenerateCost, renameSession } from "@/server/shorts";+import { body, handle } from "@/server/shorts-schemas";++/** The session with its generations (segments, takes, stitches) and what one more take costs. */+export async function GET(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {+ await connection();+ return handle(async () => {+ const { id } = await ctx.params;+ const s = getSession(id);+ return Response.json({ ...s, regenerateUsd: regenerateCost(s) });+ });+}++export async function PATCH(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const { title } = await body(request, z.object({ title: z.string().trim().min(1).max(120) }), "Give the short a name");+ return Response.json(renameSession(id, title));+ });+}++/** Delete the session; its videos move to the Trash unless ?keep=1. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]">) {+ return handle(async () => {+ const { id } = await ctx.params;+ const keep = new URL(request.url).searchParams.get("keep") === "1";+ return Response.json({ trashed: deleteSession(id, { keep }) });+ });+}diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.tsnew file mode 100644index 00000000..7515b42f--- /dev/null+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/primary/route.ts@@ -0,0 +1,14 @@+import { z } from "zod";+import { makePrimary, ShortsError } from "@/server/shorts";+import { body, handle } from "@/server/shorts-schemas";++/** Make a take the one the stitch uses. */+export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]/primary">) {+ return handle(async () => {+ const { id, index } = await ctx.params;+ const i = Number(index);+ if (!Number.isInteger(i) || i < 0) throw new ShortsError("No such segment", 404);+ const { generationId } = await body(request, z.object({ generationId: z.string().min(1).max(40) }), "Pick a take");+ return Response.json(makePrimary(id, i, generationId));+ });+}diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/route.tsnew file mode 100644index 00000000..301e9822--- /dev/null+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts@@ -0,0 +1,12 @@+import { regenerateSegment, ShortsError } from "@/server/shorts";+import { handle } from "@/server/shorts-schemas";++/** Regenerate: one more take of this segment. */+export async function POST(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) {+ return handle(async () => {+ const { id, index } = await ctx.params;+ const i = Number(index);+ if (!Number.isInteger(i) || i < 0) throw new ShortsError("No such segment", 404);+ return Response.json(regenerateSegment(id, i), { status: 201 });+ });+}diff --git a/src/app/api/shorts/sessions/[id]/stitch/route.ts b/src/app/api/shorts/sessions/[id]/stitch/route.tsnew file mode 100644index 00000000..c06b5507--- /dev/null+++ b/src/app/api/shorts/sessions/[id]/stitch/route.ts@@ -0,0 +1,10 @@+import { stitchSession } from "@/server/shorts";+import { handle } from "@/server/shorts-schemas";++/** Stitch again: join the chosen takes and put the original sound back. */+export async function POST(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) {+ return handle(async () => {+ const { id } = await ctx.params;+ return Response.json(stitchSession(id), { status: 201 });+ });+}diff --git a/src/app/api/shorts/sessions/route.ts b/src/app/api/shorts/sessions/route.tsnew file mode 100644index 00000000..6d9f41fe--- /dev/null+++ b/src/app/api/shorts/sessions/route.ts@@ -0,0 +1,17 @@+import { connection } from "next/server";+import { createSession, listSessions } from "@/server/shorts";+import { ShortsBodySchema, body, handle } from "@/server/shorts-schemas";++/** Shorts sessions, newest first (History). */+export async function GET() {+ await connection();+ return handle(() => Response.json({ items: listSessions() }));+}++/** Start a session: cut the clip into segments, restyle each, stitch them under the original sound. */+export async function POST(request: Request) {+ return handle(async () => {+ const input = await body(request, ShortsBodySchema, "Pick a preset, upload a clip and choose the part to restyle");+ return Response.json(await createSession(input), { status: 201 });+ });+}diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.tsnew file mode 100644index 00000000..9ee2fe2c--- /dev/null+++ b/src/lib/catalog/mixed-media.ts@@ -0,0 +1,590 @@+/**+ * Mixed Media (Higgsfield's /mixed-media): turn a 1–10 s clip into mixed-media art (sketch, comic,+ * paper, neon…) with per-preset settings. Higgsfield samples frames at 4–24 fps and stylises each+ * one, priced per output frame; the open engine does the same (Z-Image per frame, oss-mixed-media),+ * the cloud route runs a video-to-video restyle model on the trimmed clip, anchored on the preview+ * frame when the model takes one (LTX 2.3 reference restyle).+ *+ * Pure module, shared by the page, src/server/mixed-media.ts and the tests.+ * Research: docs/research/higgsfield-studios.md §3.+ */+import { scenePoster, type PresetPreview, type PreviewFx, type PreviewScene } from "../preset-cards";+import type { PlanStep } from "./shorts";+import type { Engine } from "./types";++export const MIXED = {+ minSeconds: 1,+ maxSeconds: 10,+ maxBytes: 50 * 1024 * 1024,+ minSourceFps: 4,+ fps: [4, 8, 10, 12, 24] as const,+ defaultFps: 8,+ manualFps: { min: 4, max: 24 },+ resolutions: ["1K", "2K", "4K"] as const,+ /** Higgsfield: 2 credits per output frame (×2 at 4K). */+ accept: "video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm",+} as const;++export type MixedResolution = (typeof MIXED.resolutions)[number];++export const MIXED_FEATURE = "mixed-media";+/** Helper steps (the cut, the render before the soundtrack) and preview frames stay out of History. */+export const MIXED_STEP_FEATURE = "mixed-media-step";+export const MIXED_PREVIEW_FEATURE = "mixed-media-preview";++/** Cloud restyle models (the first is the default) and the open per-frame model. */+export const MIXED_MODELS: Record<Engine, string[]> = {+ cloud: ["ltx-2-3-restyle", "lucy-edit-pro", "gemini-omni-flash", "kling-o3-4k-edit", "happy-horse-video-edit", "wan-2-7", "runway-aleph-2"],+ open: ["oss-mixed-media"],+};+export const MIXED_TOOLS = {+ cloud: { cut: "trim-video", mux: "merge-audio-video", preview: "nano-banana-2" },+ open: { preview: "oss-mixed-media" },+} as const;++// ---------------------------------------------------------------------------+// Settings (Higgsfield's per-preset param_configs: colour pickers, dropdowns with a custom option, text)++export type MixedSetting =+ | { key: string; label: string; type: "color"; default: string }+ | { key: string; label: string; type: "select"; options: { value: string; label: string; prompt: string }[]; default: string; custom?: boolean }+ | { key: string; label: string; type: "text"; default: string; placeholder: string; max: number };++/**+ * A setting's value: "#rrggbb" for a colour, an option value for a dropdown, the words for text.+ * "Write settings as prompt" (colours) and the custom dropdown option keep the user's words after "text:".+ */+export type MixedValues = Record<string, string>;++const color = (key: string, label: string, def: string): MixedSetting => ({ key, label, type: "color", default: def });+const select = (key: string, label: string, options: [label: string, prompt: string][], def = 0): MixedSetting => {+ const opts = options.map(([l, prompt]) => ({ value: l.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""), label: l, prompt }));+ return { key, label, type: "select", options: opts, default: opts[def].value, custom: true };+};+const text = (key: string, label: string, def: string, placeholder: string): MixedSetting => ({ key, label, type: "text", default: def, placeholder, max: 40 });++/** Every preset ends with how strongly the look takes over (also the open engine's denoise). */+export const INTENSITY = {+ key: "intensity",+ label: "Intensity",+ type: "select",+ options: [+ { value: "subtle", label: "Subtle", prompt: "applied lightly so the original footage still shows through" },+ { value: "balanced", label: "Balanced", prompt: "" },+ { value: "bold", label: "Bold", prompt: "pushed all the way, fully stylised" },+ ],+ default: "balanced",+} as const satisfies MixedSetting;+const DENOISE: Record<string, number> = { subtle: 0.55, balanced: 0.7, bold: 0.82 };++export interface MixedPreset {+ id: string;+ name: string;+ /** One line for the card. */+ description: string;+ /** The look, with {key} placeholders for the settings. */+ look: string;+ settings: MixedSetting[];+ hue: number;+ fx: PreviewFx;+ scene: PreviewScene;+}++type Row = [name: string, description: string, look: string, settings: MixedSetting[], hue: number, fx: PreviewFx, scene: PreviewScene];++const ROWS: Row[] = [+ [+ "Layer mixed media",+ "Stacked collage of paper, paint and photo layers",+ "a stacked mixed-media collage: {layers} layered over the footage, accents in {accent}",+ [select("layers", "Layers", [["Paper and paint", "torn paper and loose paint strokes"], ["Photo fragments", "cut-out photo fragments and film strips"], ["Tape and stickers", "masking tape, stickers and scribbled notes"]]), color("accent", "Accent colour", "#ff5a36")],+ 20,+ "halftone",+ "portrait",+ ],+ [+ "Sketch",+ "Hand-drawn textured linework",+ "hand-drawn textured linework in {ink} ink on {paper}, cross-hatching and loose construction lines",+ [color("ink", "Ink colour", "#1d1d1f"), select("paper", "Paper", [["White paper", "white sketchbook paper"], ["Toned paper", "warm toned paper"], ["Notebook grid", "a squared notebook page"]])],+ 260,+ "halftone",+ "portrait",+ ],+ [+ "Canvas",+ "Hand-drawn, canvas-style artwork",+ "a hand-painted canvas: visible canvas weave and thick {medium} strokes, the palette led by {color}",+ [select("medium", "Medium", [["Oil paint", "oil paint"], ["Acrylic", "acrylic"], ["Gouache", "gouache"]]), color("color", "Main colour", "#2a6f97")],+ 210,+ "halftone",+ "landscape",+ ],+ [+ "Flash comic",+ "High-energy comic visuals",+ "a high-energy comic: bold ink outlines, halftone shading, {burst} and flashes of {color}",+ [select("burst", "Accents", [["Action bursts", "starburst action bubbles"], ["Speed lines", "radiating speed lines"], ["Sound effects", "hand-lettered sound-effect words"]]), color("color", "Flash colour", "#ffd400")],+ 55,+ "explode",+ "city",+ ],+ [+ "Overexposed",+ "Extreme light, blown-out highlights",+ "an overexposed look: blown-out {tone} highlights, light leaks in {leak}, washed-out shadows and halation glow",+ [select("tone", "Highlights", [["White", "bright white"], ["Warm", "warm cream"], ["Cool", "cool blue-white"]]), color("leak", "Light leak", "#ff8a3d")],+ 60,+ "flare",+ "portrait",+ ],+ [+ "Paper",+ "Handcrafted paper textures",+ "a handcrafted paper world: everything made of {paper} with layered edges and soft shadows, colours led by {color}",+ [select("paper", "Paper", [["Cut paper", "cut paper"], ["Torn paper", "torn paper with rough fibres"], ["Cardboard", "corrugated cardboard"]]), color("color", "Paper colour", "#e9c46a")],+ 45,+ "halftone",+ "landscape",+ ],+ [+ "Noir",+ "Cinematic noir lighting",+ "cinematic film noir: high-contrast black and white, {light}, deep shadows, smoky haze and a single touch of {accent}",+ [select("light", "Light", [["Venetian blinds", "hard light through venetian blinds"], ["Street lamp", "a pool of hard street-lamp light"], ["Rim light", "a hard rim light"]]), color("accent", "Accent colour", "#c1121f")],+ 0,+ "grade",+ "city",+ ],+ [+ "Particles",+ "Luminous particles in motion",+ "luminous particles in motion: the subject formed from {density} glowing {color} particles drifting and swirling on a dark background",+ [color("color", "Particle colour", "#6ee7ff"), select("density", "Density", [["Sparse", "sparse"], ["Dense", "dense"], ["Storm", "a storm of"]])],+ 195,+ "sparkle",+ "portrait",+ ],+ [+ "Hand paint",+ "Freeform hand-painted brushwork",+ "freeform hand-painted brushwork: expressive {brush} strokes, drips and palette-knife texture, led by {color}",+ [select("brush", "Brush", [["Loose brush", "loose"], ["Thick impasto", "thick impasto"], ["Dry brush", "scratchy dry-brush"]]), color("color", "Main colour", "#e76f51")],+ 15,+ "halftone",+ "portrait",+ ],+ ["Toxic", "Radioactive neon colour blast", "a radioactive neon look: toxic {color} glow, slime-like glowing edges against a dark high-contrast background", [color("color", "Glow colour", "#7cff00")], 120, "glitch", "city"],+ [+ "Tracking",+ "Dynamic object tracking lines",+ "a dynamic tracking overlay: thin {color} tracking lines, boxes, points and labels following the movement, HUD text reading “{label}”",+ [color("color", "Line colour", "#00e5ff"), text("label", "Label", "SUBJECT 01", "e.g. SUBJECT 01")],+ 185,+ "scan",+ "city",+ ],+ ["Ultraviolet", "Neon ultraviolet glow", "a neon ultraviolet glow: blacklight {color} and violet light, fluorescent edges and deep purple shadows", [color("color", "Glow colour", "#b026ff")], 290, "glow", "portrait"],+ [+ "Windows",+ "Overlapping digital interface windows",+ "overlapping digital interface windows: the footage repeated inside retro computer windows with title bars reading “{title}”, cursors and pop-ups, accents in {color}",+ [text("title", "Window title", "untitled.mov", "e.g. untitled.mov"), color("color", "Accent colour", "#3a86ff")],+ 220,+ "frame",+ "city",+ ],+ [+ "Acid",+ "Psychedelic neon colour distortion",+ "psychedelic neon colour distortion: melting {palette} gradients, chromatic aberration and warped edges",+ [select("palette", "Palette", [["Rainbow", "rainbow"], ["Pink and green", "hot pink and acid green"], ["Orange and blue", "orange and electric blue"]])],+ 310,+ "glitch",+ "portrait",+ ],+ [+ "Palette",+ "Hand-painted colour composition",+ "a hand-painted colour composition: flat painted shapes in only {c1}, {c2} and {c3}",+ [color("c1", "Colour 1", "#264653"), color("c2", "Colour 2", "#e9c46a"), color("c3", "Colour 3", "#e76f51")],+ 30,+ "grade",+ "landscape",+ ],+ [+ "Comic",+ "Graphic illustrated comic look",+ "a graphic illustrated comic: clean ink lines, flat cel colours, halftone shading, {panel}",+ [select("panel", "Layout", [["Single panel", "framed as a single panel"], ["Comic panels", "split into comic panels"], ["Speech bubbles", "with empty speech bubbles"]])],+ 50,+ "halftone",+ "city",+ ],+ ["Akrill", "Layered acrylic colour blocks", "layered acrylic colour blocks: thick acrylic paint in blocky layers led by {color}, palette-knife edges", [color("color", "Main colour", "#ff006e")], 330, "halftone", "portrait"],+ ["Two color", "High-contrast two-tone style", "a high-contrast two-tone print using only {c1} and {c2}", [color("c1", "Ink", "#1d3557"), color("c2", "Paper", "#f1faee")], 225, "grade", "portrait"],+ [+ "Multiverse",+ "Layered reality collision",+ "a layered reality collision: several versions of the scene ({styles}) split and overlapping like portals",+ [select("styles", "Worlds", [["Cartoon, real and sketch", "cartoon, photoreal and pencil sketch"], ["Neon, film and print", "neon, vintage film and print"], ["Pixel, clay and paint", "pixel art, clay and oil paint"]])],+ 265,+ "wipe",+ "city",+ ],+ [+ "Fragments",+ "Layered abstract visual fragments",+ "layered abstract fragments: the picture broken into {shape} shards with offset copies and {color} accents",+ [select("shape", "Shards", [["Glass", "glass"], ["Paper", "paper"], ["Geometric", "geometric"]]), color("color", "Accent colour", "#ffbe0b")],+ 45,+ "crack",+ "portrait",+ ],+ ["Origami", "Crisp origami-style geometry", "crisp origami geometry: everything folded from {color} paper with sharp creases and faceted planes", [color("color", "Paper colour", "#f4a261")], 30, "morph", "product"],+ ["Random Glow", "Glows bloom on random spots", "random glow accents: soft {color} glows blooming on random parts of the frame with dreamy halation", [color("color", "Glow colour", "#ffd166")], 75, "glow", "portrait"],+ [+ "Vintage",+ "Hand-inked illustrated style",+ "a hand-inked vintage illustration: crosshatched ink, old engraving style on {paper} paper",+ [select("paper", "Paper", [["Aged", "aged sepia"], ["Cream", "cream"], ["Newsprint", "grey newsprint"]])],+ 40,+ "grade",+ "landscape",+ ],+ ["Cannabis", "Smoky psychedelic poster look", "a smoky psychedelic poster: swirling smoke, {color} haze, 70s poster style and soft grain", [color("color", "Haze colour", "#3ddc84")], 140, "wind", "portrait"],+ ["Bubbles", "Dreamy soap-bubble texture", "a dreamy soap-bubble texture: iridescent {color} bubbles floating and refracting the scene, soft focus", [color("color", "Bubble tint", "#a0c4ff")], 215, "water", "portrait"],+ [+ "Magazine",+ "Printed magazine look",+ "a printed magazine: halftone print, paper texture, a bold masthead reading “{headline}” and an editorial layout",+ [text("headline", "Masthead", "ISSUE 01", "e.g. ISSUE 01")],+ 0,+ "halftone",+ "portrait",+ ],+ ["Cold vision", "Cold neon shadow lighting", "cold neon shadow lighting: icy {color} light, deep blue shadows and a night-vision mood", [color("color", "Light colour", "#00b4ff")], 205, "relight", "city"],+ ["Modern", "Clean geometric minimalism", "clean geometric minimalism: flat shapes, thin lines and plenty of negative space in {c1} and {c2}", [color("c1", "Colour 1", "#111111"), color("c2", "Colour 2", "#f2f2f2")], 0, "grade", "product"],+ [+ "LSD",+ "Hallucinogenic colour waves",+ "hallucinogenic colour waves: rippling {palette} bands flowing over the frame with kaleidoscopic edges",+ [select("palette", "Palette", [["Rainbow", "rainbow"], ["Sunset", "magenta, orange and gold"], ["Ocean", "teal, violet and blue"]])],+ 300,+ "glitch",+ "landscape",+ ],+ [+ "Broken mirror",+ "Broken-glass reflections",+ "a broken mirror: the frame split into {pieces} with sharp reflections and offset copies",+ [select("pieces", "Shards", [["A few large shards", "a few large cracked shards"], ["Many small shards", "many small cracked shards"]])],+ 200,+ "crack",+ "portrait",+ ],+ ["Lava", "Liquid lava colour motion", "liquid lava colour motion: molten {color} flowing through the shapes, glowing cracks and heat shimmer", [color("color", "Lava colour", "#ff4d00")], 20, "fire", "landscape"],+ [+ "Marble",+ "Sculpted marble visual style",+ "a sculpted marble look: everything carved from {stone} marble with veins and soft museum light",+ [select("stone", "Stone", [["White Carrara", "white Carrara"], ["Black", "black veined"], ["Green", "green veined"]])],+ 40,+ "morph",+ "portrait",+ ],+ ["Ocean", "Liquid sea colour overlay", "a liquid sea colour overlay: rippling {color} water caustics and waves washing over the scene", [color("color", "Water colour", "#0077b6")], 210, "water", "landscape"],+];++const slug = (s: string) =>+ s+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "");++export const MIXED_PRESETS: MixedPreset[] = ROWS.map(([name, description, look, settings, hue, fx, scene]) => ({+ id: `mixed-${slug(name)}`,+ name,+ description,+ look,+ settings: [...settings, INTENSITY],+ hue,+ fx,+ scene,+}));++export function getMixedPreset(id: string): MixedPreset | undefined {+ return MIXED_PRESETS.find((p) => p.id === id);+}++export function mixedPreview(p: Pick<MixedPreset, "scene" | "fx">): PresetPreview {+ return { poster: scenePoster(p.scene), scene: p.scene, fx: p.fx };+}++export function defaultValues(p: Pick<MixedPreset, "settings">): MixedValues {+ return Object.fromEntries(p.settings.map((s) => [s.key, s.default]));+}++/** Saved values cleaned against the preset: unknown keys dropped, bad colours and options reset, text clipped. */+export function cleanValues(p: Pick<MixedPreset, "settings">, raw: Record<string, unknown> | undefined): MixedValues {+ const out = defaultValues(p);+ for (const s of p.settings) {+ const v = raw?.[s.key];+ if (typeof v !== "string") continue;+ if (v.startsWith("text:")) {+ const words = v.slice(5).trim().slice(0, 120);+ if (words && (s.type === "color" || (s.type === "select" && s.custom))) out[s.key] = `text:${words}`;+ continue;+ }+ if (s.type === "color" && /^#[0-9a-f]{6}$/i.test(v)) out[s.key] = v.toLowerCase();+ else if (s.type === "select" && s.options.some((o) => o.value === v)) out[s.key] = v;+ else if (s.type === "text") out[s.key] = v.trim().slice(0, s.max);+ }+ return out;+}++// ---------------------------------------------------------------------------+// Colours in words (models read "teal" better than "#2a9d8f")++function hsl(hex: string): [number, number, number] {+ const n = parseInt(hex.slice(1), 16);+ const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((c) => c / 255);+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ const d = max - min;+ if (!d) return [0, 0, l];+ const s = d / (1 - Math.abs(2 * l - 1));+ const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;+ return [(h * 60 + 360) % 360, s, l];+}++const HUES: [number, string][] = [+ [12, "red"],+ [35, "orange"],+ [50, "amber"],+ [65, "yellow"],+ [100, "lime"],+ [150, "green"],+ [175, "teal"],+ [195, "cyan"],+ [215, "sky blue"],+ [245, "blue"],+ [265, "indigo"],+ [290, "violet"],+ [315, "purple"],+ [335, "magenta"],+ [350, "pink"],+ [360, "red"],+];++/** "#ff5a36" → "orange-red"-ish words: hue name plus dark/light/pale/deep. */+export function colorName(hex: string): string {+ if (!/^#[0-9a-f]{6}$/i.test(hex)) return hex;+ const [h, s, l] = hsl(hex);+ if (s < 0.12 || l < 0.06 || l > 0.96) return l < 0.15 ? "black" : l > 0.88 ? "white" : l < 0.4 ? "dark grey" : l > 0.65 ? "light grey" : "grey";+ const name = HUES.find(([max]) => h < max)?.[1] ?? "red";+ if (name === "orange" && l < 0.35) return "brown";+ const tone = l < 0.25 ? "dark " : l < 0.42 ? "deep " : l > 0.8 ? "pale " : l > 0.65 ? "light " : s > 0.85 && l > 0.45 ? "bright " : "";+ return `${tone}${name}`;+}++/** A setting's value as words for the prompt. */+export function settingWords(s: MixedSetting, value: string | undefined): string {+ const v = value ?? s.default;+ if (v.startsWith("text:")) return v.slice(5).trim();+ if (s.type === "color") return /^#[0-9a-f]{6}$/i.test(v) ? `${colorName(v)} (${v.toUpperCase()})` : v;+ if (s.type === "select") return s.options.find((o) => o.value === v)?.prompt ?? s.options[0].prompt;+ return v.trim() || s.default;+}++/** The look with the user's settings filled in. */+export function mixedLook(p: Pick<MixedPreset, "look" | "settings">, values: MixedValues): string {+ let look = p.look;+ for (const s of p.settings) look = look.replaceAll(`{${s.key}}`, settingWords(s, values[s.key]));+ const intensity = INTENSITY.options.find((o) => o.value === values.intensity)?.prompt;+ return intensity ? `${look}, ${intensity}` : look;+}++const cap = (s: string) => s[0].toUpperCase() + s.slice(1);++/** Prompts per step: the video restyle (cloud), each frame (open, img2img), and the preview still (cloud edit). */+export function mixedPrompts(p: Pick<MixedPreset, "look" | "settings">, values: MixedValues) {+ const look = mixedLook(p, values);+ return {+ video: `Restyle this video as ${look}. Keep the people, poses, motion, timing and camera exactly as they are; change only the look.`,+ frame: `${cap(look)}. Same composition and subject as the source frame, highly detailed mixed-media artwork.`,+ still: `Redraw this image as ${look}. Keep the composition, framing, people and poses exactly.`,+ };+}++export const denoiseFor = (values: MixedValues) => DENOISE[values.intensity] ?? DENOISE.balanced;++// ---------------------------------------------------------------------------+// Frames, frame rates and cost++/** Output frames for a selection: floor(seconds × fps), as Higgsfield counts and charges them. */+export function mixedFrames(seconds: number, fps: number): number {+ return Math.max(0, Math.floor(seconds * fps + 1e-6));+}++/** Cost of a per-frame render: frames × the price of one frame (×2 at 4K). */+export function framesCost(frames: number, perFrameUsd: number, resolution: MixedResolution = "1K"): number {+ return Math.round(frames * perFrameUsd * (resolution === "4K" ? 2 : 1) * 10000) / 10000;+}++/** The frame-rate choices for a clip: those above its own frame rate are turned off ("Uploaded video has 6 FPS"). */+export function fpsChoices(sourceFps?: number): { fps: number; disabled: boolean }[] {+ return MIXED.fps.map((fps) => ({ fps, disabled: !!sourceFps && fps > Math.floor(sourceFps + 0.01) }));+}++/** The frame rate actually used: within 4–24, and never above the clip's own (drops to the highest allowed). */+export function clampFps(want: number, sourceFps?: number): number {+ const cap = sourceFps ? Math.max(MIXED.manualFps.min, Math.floor(sourceFps + 0.01)) : MIXED.manualFps.max;+ return Math.max(MIXED.manualFps.min, Math.min(Math.round(want), MIXED.manualFps.max, cap));+}++/** What's wrong with a selection, or null. */+export function mixedRangeProblem(range: { start: number; end: number }, duration?: number, sourceFps?: number): string | null {+ const len = range.end - range.start;+ if (!(len > 0) || range.start < 0) return "Pick a part of the clip";+ if (duration !== undefined && range.end > duration + 0.05) return "The selection runs past the end of the clip";+ if (len < MIXED.minSeconds - 0.02) return "Select at least 1 second";+ if (len > MIXED.maxSeconds + 0.05) return "Select up to 10 seconds";+ if (sourceFps !== undefined && sourceFps < MIXED.minSourceFps) return "Video must be at least 4 FPS";+ return null;+}++/** The cloud model's resolution setting closest to 1K / 2K / 4K. */+export function nearestResolution(choices: string[] | undefined, want: MixedResolution): string | undefined {+ if (!choices?.length) return undefined;+ const order = ["360p", "480p", "540p", "720p", "768p", "1080p", "1440p", "2k", "2K", "4k", "4K"];+ const target = want === "1K" ? "720p" : want === "2K" ? "1080p" : "4k";+ const rank = (r: string) => {+ const i = order.findIndex((o) => o.toLowerCase() === r.toLowerCase());+ return i < 0 ? 3 : i;+ };+ const t = rank(target);+ return [...choices].filter((c) => c !== "auto").sort((a, b) => Math.abs(rank(a) - t) - Math.abs(rank(b) - t) || rank(b) - rank(a))[0];+}++// ---------------------------------------------------------------------------+// Pipelines++export interface MixedPlanInput {+ engine: Engine;+ title: string;+ preset: Pick<MixedPreset, "id" | "name" | "look" | "settings">;+ values: MixedValues;+ source: { url: string; duration?: number; hasAudio?: boolean };+ range: { start: number; end: number };+ fps: number;+ resolution: MixedResolution;+ /** The restyle model (cloud) or oss-mixed-media (open). */+ modelId: string;+ /** Cloud: the approved preview still, sent when the model takes an image (LTX: the first frame; Kling, Happy Horse: a style reference). */+ anchor?: string;+ /** Cloud: what to ask the model for (its nearest resolution). */+ modelResolution?: string;+ /** Cloud: the model's extra settings (LTX: follow the outlines). */+ extra?: Record<string, unknown>;+ seed?: number;+}++/** The full render. Open: one per-frame job. Cloud: cut the selection, restyle it, put its own sound back. */+export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: string } {+ const prompts = mixedPrompts(input.preset, input.values);+ const base = { batchTitle: input.title };+ const seed = input.seed !== undefined ? { seed: input.seed } : {};+ if (input.engine === "open") {+ return {+ final: "render",+ steps: [+ {+ key: "render",+ request: {+ ...base,+ feature: MIXED_FEATURE,+ title: input.title,+ modelId: input.modelId,+ op: "v2v",+ prompt: prompts.frame,+ inputs: { video: input.source.url },+ params: { startTime: input.range.start, endTime: input.range.end, fps: input.fps, aspectRatio: "auto", resolution: input.resolution, ...seed, extra: { denoise: denoiseFor(input.values) } },+ },+ },+ ],+ };+ }+ const t = MIXED_TOOLS.cloud;+ const sound = !!input.source.hasAudio;+ const steps: PlanStep[] = [+ {+ key: "cut",+ request: { ...base, feature: MIXED_STEP_FEATURE, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Cut", index: 0, of: 3 } },+ },+ {+ key: "render",+ request: {+ ...base,+ feature: sound ? MIXED_STEP_FEATURE : MIXED_FEATURE,+ ...(sound ? {} : { title: input.title }),+ modelId: input.modelId,+ op: "v2v",+ prompt: prompts.video,+ inputs: input.anchor ? { images: [input.anchor] } : undefined,+ params: {+ duration: Math.max(1, Math.round(input.range.end - input.range.start)),+ generateAudio: false,+ ...(input.modelResolution ? { resolution: input.modelResolution } : {}),+ ...seed,+ ...(input.extra ? { extra: input.extra } : {}),+ },+ step: { label: "Restyle", index: 1, of: 3 },+ },+ after: ["cut"],+ chain: [{ slot: "video" }],+ },+ ];+ if (!sound) return { steps, final: "render" };+ steps.push({+ key: "final",+ request: { ...base, feature: MIXED_FEATURE, title: input.title, modelId: t.mux, op: "mux", step: { label: "Original sound", index: 2, of: 3 } },+ after: ["render", "cut"],+ // The cut is a clip: the mux takes its soundtrack.+ chain: [{ slot: "video" }, { slot: "audio" }],+ });+ return { steps, final: "final" };+}++/** One frame with the current settings. Open: the per-frame model on one frame; cloud: an image edit of the frame the browser grabbed. */+export function planMixedPreview(input: MixedPlanInput & { frameUrl?: string }): PlanStep {+ const prompts = mixedPrompts(input.preset, input.values);+ const title = `${input.preset.name} · preview`;+ if (input.engine === "open") {+ return {+ key: "preview",+ request: {+ feature: MIXED_PREVIEW_FEATURE,+ title,+ modelId: MIXED_TOOLS.open.preview,+ op: "v2v",+ prompt: prompts.frame,+ inputs: { video: input.source.url },+ params: { startTime: input.range.start, fps: input.fps, aspectRatio: "auto", resolution: input.resolution, ...(input.seed !== undefined ? { seed: input.seed } : {}), extra: { denoise: denoiseFor(input.values), frames: 1 } },+ },+ };+ }+ return {+ key: "preview",+ request: {+ feature: MIXED_PREVIEW_FEATURE,+ title,+ modelId: MIXED_TOOLS.cloud.preview,+ op: "edit",+ prompt: prompts.still,+ inputs: { images: input.frameUrl ? [input.frameUrl] : [] },+ ...(input.seed !== undefined ? { params: { seed: input.seed } } : {}),+ },+ };+}diff --git a/src/lib/catalog/shorts-models.ts b/src/lib/catalog/shorts-models.tsnew file mode 100644index 00000000..29654e54--- /dev/null+++ b/src/lib/catalog/shorts-models.ts@@ -0,0 +1,88 @@+/**+ * What the Shorts Studio and Mixed Media restyle models can take, read from their routes (field+ * maps), and slim rows for the pages. Uses the full catalog, so it runs on the server (pages and+ * src/server/shorts.ts, src/server/mixed-media.ts); the browser gets the rows.+ */+import { getModel } from "./index";+import { routesFor } from "./plan";+import { SHORTS } from "./shorts";+import type { Engine, ModelDef } from "./types";++/** How many reference images a restyle model takes on every route (0: it restyles from words only). */+export function maxRefsFor(modelId: string): number {+ const m = getModel(modelId);+ if (!m) return 0;+ if (m.engine === "open") return SHORTS.openReferences;+ const routes = routesFor(m, "v2v");+ if (!routes.length || !routes.every((r) => r.map?.images)) return 0;+ return Math.min(SHORTS.maxReferences, m.options.maxImages ?? 4);+}++/** Whether every v2v route of a cloud model reads an image (LTX: the first frame; Kling, Happy Horse: references). */+export function takesImage(modelId: string): boolean {+ const m = getModel(modelId);+ if (!m || m.engine !== "cloud") return false;+ const routes = routesFor(m, "v2v");+ return routes.length > 0 && routes.every((r) => r.map?.image || r.map?.images);+}++/** Whether every v2v route can be asked for an aspect ratio (else the output keeps the clip's shape). */+export function reframes(modelId: string): boolean {+ const m = getModel(modelId);+ if (!m) return false;+ if (m.engine === "open") return true;+ const routes = routesFor(m, "v2v");+ return routes.length > 0 && routes.every((r) => r.map?.aspectRatio);+}++/** The cloud model's 720p setting, when it has one (Higgsfield renders Shorts at 720p). */+export function resolutionFor(modelId: string): string | undefined {+ const m = getModel(modelId);+ return m?.engine === "cloud" && m.options.resolutions?.includes("720p") ? "720p" : undefined;+}++export interface RestyleModelInfo {+ id: string;+ name: string;+ vendor: string;+ tagline: string;+ engine: Engine;+ /** Reference images it takes (0: words only). */+ refs: number;+ /** Takes a still (first frame or style reference). */+ image: boolean;+ /** Can be asked for 9:16 / 16:9. */+ reframes: boolean;+ price: string | null;+ resolutions?: string[];+}++function priceLine(m: ModelDef): string | null {+ if (m.engine === "open") return "Free · your GPU";+ const p = m.pricing;+ if (!p) return null;+ const usd = p.usd < 0.1 ? p.usd.toFixed(3).replace(/0$/, "") : p.usd.toFixed(2);+ return `$${usd} / ${p.unit === "second" ? "s" : p.unit}`;+}++/** Slim model rows for a studio page (so the browser needs no catalog). */+export function modelInfos(ids: string[]): RestyleModelInfo[] {+ return ids.flatMap((id) => {+ const m = getModel(id);+ if (!m) return [];+ return [+ {+ id,+ name: m.name,+ vendor: m.vendor,+ tagline: m.tagline,+ engine: m.engine,+ refs: maxRefsFor(id),+ image: takesImage(id),+ reframes: reframes(id),+ price: priceLine(m),+ ...(m.options.resolutions ? { resolutions: m.options.resolutions } : {}),+ },+ ];+ });+}diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.tsnew file mode 100644index 00000000..7e0458b1--- /dev/null+++ b/src/lib/catalog/shorts.ts@@ -0,0 +1,696 @@+/**+ * Shorts Studio (Higgsfield's Shorts Studio / reels_studio): restyle your own footage into a new+ * look while the motion stays yours. Up to 2 minutes in; the clip is cut into segments (≤10 s on+ * cloud models, ≤5 s = 81 frames at 16 fps on the open engine), each segment is restyled, and the+ * segments are stitched back together under the original sound.+ *+ * Pure module (presets, limits, segment planning, prompts, the pipeline's steps), shared by the+ * page, the server (src/server/shorts.ts) and the tests. Research: docs/research/higgsfield-studios.md §2.+ */+import { scenePoster, type PresetPreview, type PreviewFx, type PreviewScene } from "../preset-cards";+import type { ChainSlot, Engine, Generation, GenerationRequest } from "./types";++// ---------------------------------------------------------------------------+// Limits (Higgsfield's, from the upload dialog) and engine shapes++export const SHORTS = {+ minSeconds: 4,+ maxSeconds: 120,+ maxBytes: 200 * 1024 * 1024,+ maxDimension: 4000,+ /** Longest segment a cloud restyle model gets (Gemini Omni Flash: ≤10 s per clip). */+ cloudSegmentSeconds: 10,+ /** Open engine: Wan 2.2 Fun VACE renders 81 frames (4n+1) at 16 fps, ≈5 s. */+ openFps: 16,+ openMaxFrames: 81,+ maxReferences: 10,+ /** Qwen-Image-Edit takes the frame plus two references. */+ openReferences: 2,+ accept: "video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm",+} as const;++export const SHORTS_RATIOS = [+ { value: "9:16", label: "9:16", hint: "Vertical" },+ { value: "16:9", label: "16:9", hint: "Horizontal" },+] as const;+export type ShortsRatio = (typeof SHORTS_RATIOS)[number]["value"];++/** Languages for on-screen words (type presets), as Higgsfield lists them. "auto" = the language spoken in the clip. */+export const SHORTS_LANGUAGES = [+ "English",+ "Spanish",+ "French",+ "Kazakh",+ "Arabic",+ "Bulgarian",+ "Chinese",+ "Croatian",+ "Czech",+ "Danish",+ "Dutch",+ "Filipino",+ "Finnish",+ "German",+ "Greek",+ "Hungarian",+ "Hindi",+ "Indonesian",+ "Italian",+ "Japanese",+ "Korean",+ "Malay",+ "Norwegian",+ "Polish",+ "Portuguese",+ "Romanian",+ "Russian",+ "Slovak",+ "Swedish",+ "Tamil",+ "Turkish",+ "Ukrainian",+ "Vietnamese",+] as const;++/** Restyle models per engine; the first is the default (Gemini Omni Flash is Higgsfield's Shorts engine). */+export const SHORTS_MODELS: Record<Engine, string[]> = {+ cloud: ["gemini-omni-flash", "kling-o3-4k-edit", "happy-horse-video-edit", "lucy-edit-pro", "runway-aleph-2", "ltx-2-3-restyle", "wan-2-7"],+ open: ["oss-wan22-vace-restyle"],+};++/** The helper models of the pipeline. */+export const SHORTS_TOOLS = {+ cloud: { cut: "trim-video", trim: "trim-video", join: "join-clips", mux: "merge-audio-video", joinMax: 24 },+ open: { cut: "oss-segment", trim: "oss-trim", frame: "oss-qwen-edit", join: "oss-join-clips", mux: "oss-mux", joinMax: 4 },+} as const;++// ---------------------------------------------------------------------------+// Presets: the 44 Higgsfield names, with Fuobe's own descriptions and prompts++export type ShortsCategory = "Colour" | "Drawn" | "Comic & pop" | "Type" | "Street & collage" | "Digital" | "Craft";++export interface ShortsPreset {+ id: string;+ name: string;+ category: ShortsCategory;+ /** One line for the card. */+ description: string;+ /** The look, as the end of "Restyle this video as …". */+ look: string;+ /** On-screen words are part of the look: the language setting applies. */+ type?: boolean;+ hue: number;+ fx: PreviewFx;+ scene: PreviewScene;+}++type Row = [name: string, category: ShortsCategory, description: string, look: string, hue: number, fx: PreviewFx, scene: PreviewScene, type?: true];++const ROWS: Row[] = [+ ["Bold Urban", "Colour", "Punchy city grade with deep blacks and teal-orange colour", "a bold urban music-video grade: crushed deep blacks, saturated teal and orange, crisp high contrast and sharp street detail", 30, "grade", "city"],+ ["Green Contrast", "Colour", "Moody high contrast with rich emerald greens", "a high-contrast green-tinted look: rich emerald greens in the midtones, inky shadows and bright clean highlights", 150, "grade", "landscape"],+ ["Urban Serenity", "Colour", "Calm, airy city tones in soft pastels", "a calm, airy urban look: soft pastel tones, gentle haze, lifted shadows and quiet muted colours", 220, "grade", "city"],+ ["Warm Glow", "Colour", "Golden-hour warmth with a soft bloom", "warm golden-hour light with a soft dreamy bloom around the highlights, honey tones and glowing skin", 70, "relight", "portrait"],+ ["Yellow Frame", "Comic & pop", "A bold yellow poster frame around the action", "a graphic poster with a thick bright yellow frame around the action, flat bold colours and clean cut-out edges", 95, "frame", "portrait"],+ ["Monochrome Vibes", "Colour", "Rich black and white with film grain", "rich black-and-white film photography: deep blacks, silver highlights, fine film grain and strong contrast", 260, "grade", "city"],+ ["Claymation", "Craft", "Stop-motion clay with a handmade, tactile feel", "stop-motion claymation: every person and object sculpted from plasticine with fingerprint textures, soft studio light and a slightly stepped, handmade motion", 40, "morph", "portrait"],+ ["Marker Scribble", "Drawn", "Loose marker doodles scribbled over the footage", "hand-drawn marker doodles: loose felt-tip outlines, scribbled highlights, arrows and squiggles drawn around the subject over the real footage", 15, "halftone", "portrait"],+ ["Sticker Type", "Type", "Die-cut sticker words that pop onto the frame", "a playful sticker collage: the subject cut out with a thick white die-cut border, bold sticker-style words and emoji stickers popping onto the frame", 330, "pop", "portrait", true],+ ["Blue Comic", "Comic & pop", "Blue-toned comic panels with heavy ink lines", "a comic book drawn in shades of blue: heavy black ink outlines, halftone dots and flat blue and cyan fills", 240, "halftone", "city"],+ ["Red Graffiti", "Street & collage", "Red spray-paint tags, outlines and drips", "street graffiti in bold red spray paint: drippy tags, outlines and splatters sprayed around the subject on a concrete-wall texture", 25, "halftone", "city"],+ ["Watercolor", "Drawn", "Soft watercolour washes on textured paper", "a watercolour painting: soft translucent washes that bleed at the edges, visible paper grain and a loose pencil underdrawing", 200, "halftone", "landscape"],+ ["Pencil Sketch", "Drawn", "A graphite pencil sketch that moves", "a graphite pencil sketch on white paper: hatched shading, smudged tones and confident hand-drawn contour lines", 280, "halftone", "portrait"],+ ["Desktop", "Digital", "Your clip inside a retro computer desktop", "a retro computer desktop: the footage playing inside pixel-perfect windows with title bars, cursors, icons and pop-up dialogs on a bright desktop background", 210, "frame", "city"],+ ["Acid Green", "Colour", "Toxic neon-green duotone", "an acid neon-green duotone: the picture mapped to toxic lime and black, glowing edges and a rave-poster intensity", 125, "glitch", "city"],+ ["Balloon Type", "Type", "Glossy balloon letters floating in", "inflated glossy balloon lettering: shiny 3D balloon words floating around the subject, bright party colours and soft reflections", 345, "pop", "portrait", true],+ ["Blueprint", "Drawn", "White technical lines on blueprint blue", "an architectural blueprint: white technical line drawing on deep blue paper with grid lines, measurements and construction notes", 245, "halftone", "city"],+ ["Bold Caption", "Type", "Big punchy captions stamped over the action", "a social-video look with huge bold captions: thick white words with black outlines stamped over the action and punchy high-contrast colour", 50, "pop", "portrait", true],+ ["Bounding Box", "Digital", "Tracking boxes and labels on everything", "a computer-vision overlay: thin tracking boxes, corner brackets, labels and confidence numbers following the people and objects", 180, "scan", "city"],+ ["Circuit", "Digital", "Glowing circuit-board traces", "a circuit-board world: glowing cyan and green circuit traces flowing across every surface and outlining the subject on a dark PCB texture", 165, "glitch", "product"],+ ["Comic Burst", "Comic & pop", "Action panels with POW-style bursts", "an action comic: bold ink lines, speed lines, halftone shading and starburst sound-effect bubbles bursting behind the subject", 10, "explode", "city"],+ ["Comic Pop", "Comic & pop", "Bright pop-art comic colours and dots", "pop-art comic style: thick black outlines, Ben-Day dots and flat primary colours like a vintage comic print", 55, "halftone", "portrait"],+ ["Pink Wash", "Colour", "A dreamy pink tint over everything", "a dreamy pink colour wash: soft rose and magenta over the whole frame, glowing highlights and pastel shadows", 350, "grade", "landscape"],+ ["Gold Stars", "Comic & pop", "Sparkling gold stars and glitter", "a glamorous sparkle look: twinkling gold stars, glitter and lens sparkles swirling around the subject in warm shimmering light", 80, "sparkle", "portrait"],+ ["Graffiti", "Street & collage", "A colourful wall-mural makeover", "a colourful graffiti mural: the scene repainted as spray-painted street art with bold outlines, gradients and wildstyle shapes on brick", 300, "halftone", "city"],+ ["Green Doodle", "Drawn", "Green hand-drawn doodles around you", "green hand-drawn doodles: playful green marker outlines, stars, hearts and squiggles traced around the subject over the footage", 140, "halftone", "portrait"],+ ["Green Pop", "Comic & pop", "Lime pop-art colour blocking", "pop-art colour blocking in lime and green: flat graphic shapes, bold outlines and a bright cut-out poster feel", 130, "pop", "portrait"],+ ["Heart Pop", "Comic & pop", "Pink hearts popping all around", "a cute pop look: pink and red cartoon hearts popping and floating around the subject, soft pastel tones and glossy highlights", 355, "sparkle", "portrait"],+ ["Kinetic Type", "Type", "Bold words moving with the action", "kinetic typography: big bold words sliding, scaling and stacking around the subject in time with the movement, graphic two-colour design", 270, "pop", "city", true],+ ["Liquid Chrome", "Digital", "Mirror-polished liquid metal", "liquid chrome: everything turned into flowing mirror-polished liquid metal with sharp reflections and iridescent highlights", 230, "shine", "product"],+ ["Mascot", "Craft", "You, as a cute 3D cartoon mascot", "a cute 3D cartoon mascot: the people turned into soft rounded toy-like characters with big eyes, smooth plastic shading and bright colours", 45, "morph", "portrait"],+ ["Neon Pop", "Comic & pop", "Electric neon outlines on dark", "electric neon pop: glowing pink and cyan neon outlines tracing the subject against a dark background, with vivid light trails", 320, "glow", "city"],+ ["Neon Type", "Type", "Glowing neon-sign lettering", "neon-sign lettering: glowing tube-light words and outlines in hot pink and blue buzzing around the subject at night", 300, "glow", "city", true],+ ["Patterned", "Street & collage", "Bold repeating patterns fill the scene", "a patterned collage: the background and clothes filled with bold repeating graphic patterns (checks, stripes and dots) in a flat print style", 20, "halftone", "portrait"],+ ["Pink Pop", "Comic & pop", "Hot-pink pop-art palette", "hot-pink pop art: flat bubblegum pinks, bold black outlines and glossy graphic shapes", 340, "pop", "portrait"],+ ["Pink Scribble", "Drawn", "Pink crayon scribbles and doodles", "pink crayon scribbles: loose hand-drawn pink outlines, hearts and zigzags scribbled over and around the subject", 335, "halftone", "portrait"],+ ["Polka Pop", "Comic & pop", "Polka dots and pop-art colour blocks", "playful pop art with polka dots: oversized dots, flat colour blocks and thick outlines like a retro print", 5, "pop", "portrait"],+ ["Retro Collage", "Street & collage", "Cut-paper textures and grainy print colours", "a vintage cut-paper collage: torn paper edges, magazine cut-outs, grainy risograph print colours and tape marks", 35, "halftone", "landscape"],+ ["Stacked Type", "Type", "Giant stacked words layered behind you", "bold stacked typography: giant repeated words stacked in layers behind the subject, the subject cut out in front, clean two-tone design", 0, "pop", "portrait", true],+ ["Star Comic", "Comic & pop", "Comic panels with exploding stars", "a comic-book look with star bursts: ink outlines, halftone dots and bright yellow stars exploding around the action", 60, "sparkle", "city"],+ ["Street Art", "Street & collage", "Stencils and paste-up posters", "stencil street art: high-contrast spray stencils, paste-up posters and paint drips on an urban wall", 15, "halftone", "city"],+ ["Vintage Paper", "Street & collage", "An old printed page with faded inks", "an old printed page: aged yellowed paper, faded inks, misregistered print colours and creases", 50, "grade", "landscape"],+ ["Yellow Burst", "Comic & pop", "Graphic bursts on a punchy yellow backdrop", "bold graphic bursts on a punchy yellow backdrop: the subject cut out over bright yellow with radiating rays and black outline shapes", 90, "explode", "portrait"],+ ["Yellow Doodle", "Drawn", "Bright yellow highlighter doodles", "yellow highlighter doodles: bright yellow hand-drawn outlines, sparkles and arrows scribbled around the subject over the footage", 95, "halftone", "portrait"],+];++const slug = (s: string) =>+ s+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "");++export const SHORTS_PRESETS: ShortsPreset[] = ROWS.map(([name, category, description, look, hue, fx, scene, type]) => ({+ id: `shorts-${slug(name)}`,+ name,+ category,+ description,+ look,+ hue,+ fx,+ scene,+ ...(type ? { type } : {}),+}));++export const SHORTS_CATEGORIES: ShortsCategory[] = ["Colour", "Drawn", "Comic & pop", "Type", "Street & collage", "Digital", "Craft"];++export function getShortsPreset(id: string): ShortsPreset | undefined {+ return SHORTS_PRESETS.find((p) => p.id === id);+}++export function shortsPreview(p: Pick<ShortsPreset, "scene" | "fx">): PresetPreview {+ return { poster: scenePoster(p.scene), scene: p.scene, fx: p.fx };+}++/** A preset the user made from reference images (stored in shorts_presets). */+export interface ShortsCustomPreset {+ id: string;+ name: string;+ /** What the look should feel like, in the user's words (optional). */+ description: string;+ references: string[];+ createdAt: number;+ updatedAt: number;+}++/** What a session restyles with: a built-in preset or a custom one, snapshotted when the session starts. */+export interface ShortsLook {+ presetId: string;+ name: string;+ look: string;+ type?: boolean;+ references?: string[];+ custom?: boolean;+}++export function lookFromPreset(p: ShortsPreset): ShortsLook {+ return { presetId: p.id, name: p.name, look: p.look, ...(p.type ? { type: true } : {}) };+}++export function lookFromCustom(p: ShortsCustomPreset): ShortsLook {+ const words = p.description.trim().replace(/[.\s]+$/, "");+ return {+ presetId: p.id,+ name: p.name,+ look: words ? `the look of the reference images: ${words}` : "the look of the reference images: their colours, textures, lighting and graphic style",+ references: p.references.slice(0, SHORTS.maxReferences),+ custom: true,+ };+}++/** A name for a custom preset when the user leaves it empty: the first words of the description, or "My look N". */+export function customPresetName(description: string, existing: number): string {+ const words = description+ .replace(/[^\p{L}\p{N}\s'-]/gu, " ")+ .split(/\s+/)+ .filter((w) => w.length > 2 && !/^(the|and|with|for|from|that|this|very|look|style)$/i.test(w))+ .slice(0, 3);+ if (!words.length) return `My look ${existing + 1}`;+ const name = words.join(" ");+ return name[0].toUpperCase() + name.slice(1).toLowerCase();+}++// ---------------------------------------------------------------------------+// Prompts++const tidy = (s: string) => s.trim().replace(/[.\s]+$/, "");++/** "on-screen words in Spanish" — only type presets put words on screen. */+function wordsLine(look: Pick<ShortsLook, "type">, language: string): string {+ if (!look.type) return "";+ const lang = !language || language === "auto" ? "the language spoken in the clip" : language;+ return ` Any on-screen words are written in ${lang}.`;+}++/** The video-to-video prompt: the look, and the promise that the motion stays the user's. */+export function restylePrompt(look: Pick<ShortsLook, "look" | "type" | "references">, language = "auto", refsSent = 0): string {+ const refs = refsSent ? ` Match the style of the reference image${refsSent > 1 ? "s" : ""}.` : "";+ return `Restyle this video as ${tidy(look.look)}. Keep everything that happens exactly as it is: the same people, faces, poses, motion, timing and camera moves; change only the look.${refs}${wordsLine(look, language)}`;+}++/** Open engine, step 1: restyle the segment's first frame (image 1) with Qwen-Image-Edit; references are images 2 and 3. */+export function firstFramePrompt(look: Pick<ShortsLook, "look" | "type">, language = "auto", refs = 0): string {+ const match = refs ? ` Match the style, colours and textures of ${refs > 1 ? "images 2 and 3" : "image 2"}.` : "";+ return `Redraw image 1 as ${tidy(look.look)}. Keep the composition, framing, people, faces, poses and expressions of image 1 exactly.${match}${wordsLine(look, language)}`;+}++/** Open engine, step 2: Wan 2.2 Fun VACE follows the restyled first frame and the clip's depth. */+export function segmentPrompt(look: Pick<ShortsLook, "look">): string {+ const l = tidy(look.look);+ return `${l[0].toUpperCase()}${l.slice(1)}. The same look on every frame, smooth natural motion.`;+}++// ---------------------------------------------------------------------------+// Segments++export interface ShortsRange {+ start: number;+ end: number;+}++export interface ShortsSegment {+ index: number;+ /** Seconds in the source clip. */+ start: number;+ end: number;+ /** Open engine: the segment's exact frame count at SHORTS.openFps (4n+1). */+ frames?: number;+}++const r3 = (n: number) => Math.round(n * 1000) / 1000;++/** What's wrong with a selection, or null. */+export function rangeProblem(range: ShortsRange, duration?: number): string | null {+ const len = range.end - range.start;+ if (!(len > 0) || range.start < 0) return "Pick a part of the clip";+ if (duration !== undefined && range.end > duration + 0.05) return "The selection runs past the end of the clip";+ if (len < SHORTS.minSeconds - 0.05) return `Select at least ${SHORTS.minSeconds} seconds`;+ if (len > SHORTS.maxSeconds + 0.05) return "Select up to 2 minutes";+ return null;+}++/**+ * Cloud: cut the selection into equal segments of at most `max` seconds, so no segment ends up a+ * sliver (47 s → five 9.4 s segments, not four 10 s and a 7 s one).+ */+export function planCloudSegments(range: ShortsRange, max: number = SHORTS.cloudSegmentSeconds): ShortsSegment[] {+ const len = range.end - range.start;+ const n = Math.max(1, Math.ceil(len / max - 1e-9));+ return Array.from({ length: n }, (_, i) => ({+ index: i,+ start: r3(range.start + (len * i) / n),+ end: i === n - 1 ? r3(range.end) : r3(range.start + (len * (i + 1)) / n),+ }));+}++/**+ * Open: Wan wants 4n+1 frames per segment (at most 81 at 16 fps). Segments are cut back to back+ * on whole frames, so the stitched video has exactly the selection's frames (less up to 3 at the+ * end) and stays in sync with the original sound all the way through.+ */+export function planOpenSegments(range: ShortsRange, fps: number = SHORTS.openFps, maxFrames: number = SHORTS.openMaxFrames): ShortsSegment[] {+ const total = Math.floor((range.end - range.start) * fps + 1e-6);+ const first = Math.round(range.start * fps);+ const k = Math.max(1, Math.ceil(total / maxFrames));+ const units = Math.max(k, Math.floor((total - k) / 4)); // each segment is 4·n + 1 frames+ const base = Math.floor(units / k);+ const extra = units % k;+ const out: ShortsSegment[] = [];+ let at = first;+ for (let i = 0; i < k; i++) {+ const frames = 4 * (base + (i < extra ? 1 : 0)) + 1;+ out.push({ index: i, start: r3(at / fps), end: r3((at + frames) / fps), frames });+ at += frames;+ }+ return out;+}++export function planSegments(range: ShortsRange, engine: Engine): ShortsSegment[] {+ return engine === "open" ? planOpenSegments(range) : planCloudSegments(range);+}++/** Groups of at most `max` consecutive items, as even as possible (5 by 4 → 3 + 2, never 4 + 1). */+export function joinGroups(n: number, max: number): number[][] {+ const g = Math.max(1, Math.ceil(n / max));+ const out: number[][] = [];+ let at = 0;+ for (let i = 0; i < g; i++) {+ const size = Math.floor(n / g) + (i < n % g ? 1 : 0);+ out.push(Array.from({ length: size }, (_, j) => at + j));+ at += size;+ }+ return out;+}++/** Whether the selection is the whole clip (then the upload itself carries the sound to put back). */+export function wholeClip(range: ShortsRange, duration?: number): boolean {+ return range.start <= 0.05 && duration !== undefined && range.end >= duration - 0.05;+}++// ---------------------------------------------------------------------------+// The pipeline: steps for createPipeline (src/server/chains.ts)++export interface PlanStep {+ key: string;+ request: GenerationRequest;+ after?: string[];+ chain?: ChainSlot[];+}++export interface ShortsPlanInput {+ engine: Engine;+ title: string;+ source: { url: string; duration?: number; hasAudio?: boolean };+ range: ShortsRange;+ look: ShortsLook;+ aspectRatio: ShortsRatio;+ language: string;+ /** The restyle model (cloud: SHORTS_MODELS.cloud; open: oss-wan22-vace-restyle). */+ modelId: string;+ /** How many reference images the restyle model takes (0: it restyles from words only). */+ maxRefs: number;+ /** Resolution to ask the cloud model for, when it has a setting. */+ resolution?: string;+ /** Extra params for the restyle model (e.g. a seed for a new take). */+ seed?: number;+}++export const SHORTS_FEATURE = "shorts";++/** Keys of one take's steps. */+export interface TakeKeys {+ cut: string;+ frame?: string;+ look: string;+}++const segLabel = (s: ShortsSegment, n: number, what: string) => ({ label: `Segment ${s.index + 1} of ${n} · ${what}`, index: s.index, of: n });++/** Which references go where: the cloud model's own reference slot, or images 2–3 of the open first-frame edit. */+export function refsFor(input: Pick<ShortsPlanInput, "engine" | "look" | "maxRefs">): string[] {+ const refs = input.look.references ?? [];+ if (input.engine === "open") return refs.slice(0, SHORTS.openReferences);+ return refs.slice(0, Math.max(0, input.maxRefs));+}++/** One take of one segment: cut it out, (open: restyle its first frame,) restyle it. */+export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: number, suffix = ""): { steps: PlanStep[]; keys: TakeKeys } {+ const t = SHORTS_TOOLS[input.engine];+ const base = { feature: SHORTS_FEATURE, batchTitle: input.title };+ const k = (what: string) => `${what}${seg.index}${suffix}`;+ const refs = refsFor(input);+ const seed = input.seed !== undefined ? { seed: input.seed } : {};+ if (input.engine === "open") {+ const keys: TakeKeys = { cut: k("cut"), frame: k("frame"), look: k("look") };+ return {+ keys,+ steps: [+ {+ key: keys.cut,+ request: {+ ...base,+ modelId: t.cut,+ op: "trim",+ inputs: { video: input.source.url },+ params: { startTime: seg.start, endTime: seg.end, fps: SHORTS.openFps, aspectRatio: input.aspectRatio, resolution: "480p" },+ step: segLabel(seg, total, "cut"),+ },+ },+ {+ key: keys.frame!,+ request: {+ ...base,+ modelId: SHORTS_TOOLS.open.frame,+ op: "edit",+ prompt: firstFramePrompt(input.look, input.language, refs.length),+ inputs: refs.length ? { images: refs } : undefined,+ params: { ...seed },+ step: segLabel(seg, total, "first frame"),+ },+ after: [keys.cut],+ chain: [{ slot: "images", position: "first" }],+ },+ {+ key: keys.look,+ request: {+ ...base,+ modelId: input.modelId,+ op: "v2v",+ prompt: segmentPrompt(input.look),+ params: { aspectRatio: input.aspectRatio, resolution: "480p", duration: (seg.frames ?? Math.round((seg.end - seg.start) * SHORTS.openFps)) / SHORTS.openFps, ...seed },+ step: segLabel(seg, total, "restyle"),+ },+ after: [keys.cut, keys.frame!],+ chain: [{ slot: "video" }, { slot: "images" }],+ },+ ],+ };+ }+ const keys: TakeKeys = { cut: k("cut"), look: k("look") };+ const seconds = seg.end - seg.start;+ return {+ keys,+ steps: [+ {+ key: keys.cut,+ request: { ...base, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: seg.start, endTime: seg.end }, step: segLabel(seg, total, "cut") },+ },+ {+ key: keys.look,+ request: {+ ...base,+ modelId: input.modelId,+ op: "v2v",+ prompt: restylePrompt(input.look, input.language, refs.length),+ inputs: refs.length ? { images: refs } : undefined,+ // Whole seconds (Wan's edit takes 2–10); the price is per second of video.+ params: { aspectRatio: input.aspectRatio, duration: Math.max(2, Math.round(seconds)), ...(input.resolution ? { resolution: input.resolution } : {}), ...seed },+ step: segLabel(seg, total, "restyle"),+ },+ after: [keys.cut],+ chain: [{ slot: "video" }],+ },+ ],+ };+}++/** Where a clip in a stitch comes from: an earlier step's output, or a finished file. */+export type ClipRef = { key: string } | { url: string };++/**+ * Join the restyled segments (in order, folding when the join model takes fewer clips than there+ * are) and put the original sound back. Returns the steps and the key of the finished video+ * (undefined when there is nothing to make: one segment and no sound to add).+ */+export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""): { steps: PlanStep[]; final?: string } {+ const t = SHORTS_TOOLS[input.engine];+ const base = { feature: SHORTS_FEATURE, batchTitle: input.title };+ const steps: PlanStep[] = [];+ const params = input.engine === "open" ? { aspectRatio: input.aspectRatio, resolution: "480p" } : { aspectRatio: input.aspectRatio };+ // Each join step takes its clips either chained (key) or as files (url).+ let level: ClipRef[] = clips;+ let depth = 0;+ while (level.length > 1) {+ const groups = joinGroups(level.length, t.joinMax);+ const last = groups.length === 1;+ level = groups.map((g, gi) => {+ const items = g.map((i) => level[i]);+ const after = items.flatMap((c) => ("key" in c ? [c.key] : []));+ const urls = items.flatMap((c) => ("url" in c ? [c.url] : []));+ const key = last ? `join${suffix}` : `join${suffix}-${depth}-${gi}`;+ // Files first, then chained clips: a level only ever mixes the two in that order (stitch-again fold).+ steps.push({+ key,+ request: {+ ...base,+ modelId: t.join,+ op: "concat",+ prompt: input.title,+ inputs: urls.length ? { videos: urls } : undefined,+ params,+ step: { label: last ? "Stitch" : "Stitching", index: 1000 + depth, of: 1000 },+ },+ ...(after.length ? { after, chain: after.map(() => ({ slot: "videos" as const })) } : {}),+ });+ return { key };+ });+ depth++;+ }+ const picture = level[0];+ if (!input.source.hasAudio) {+ // Nothing to put back: the joined clip (or the single segment) is the short.+ if ("key" in picture) {+ const last = steps.find((s) => s.key === picture.key);+ if (last) last.request = { ...last.request, title: input.title };+ return { steps, final: picture.key };+ }+ return { steps, final: undefined };+ }+ const whole = wholeClip(input.range, input.source.duration);+ const after: string[] = [];+ const chain: ChainSlot[] = [];+ const inputs: GenerationRequest["inputs"] = {};+ if ("key" in picture) {+ after.push(picture.key);+ chain.push({ slot: "video" });+ } else inputs.video = picture.url;+ if (whole) inputs.audio = input.source.url;+ else {+ // The sound of the selection: the source cut to the same window (the mux reads a clip's soundtrack).+ const key = `sound${suffix}`;+ steps.push({+ key,+ request: { ...base, modelId: t.trim, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Original sound", index: 1100, of: 1000 } },+ });+ after.push(key);+ chain.push({ slot: "audio" });+ }+ const key = `final${suffix}`;+ steps.push({+ key,+ request: { ...base, title: input.title, modelId: t.mux, op: "mux", inputs: Object.keys(inputs).length ? inputs : undefined, step: { label: "Final video", index: 1200, of: 1000 } },+ ...(after.length ? { after, chain } : {}),+ });+ return { steps, final: key };+}++/** The whole session: every segment's first take, the stitch and the soundtrack. */+export function planShorts(input: ShortsPlanInput): { segments: ShortsSegment[]; steps: PlanStep[]; takes: TakeKeys[]; final?: string } {+ const segments = planSegments(input.range, input.engine);+ const takes = segments.map((s) => planTake(input, s, segments.length));+ const stitch = planStitch(+ input,+ takes.map((t) => ({ key: t.keys.look })),+ );+ return { segments, steps: [...takes.flatMap((t) => t.steps), ...stitch.steps], takes: takes.map((t) => t.keys), final: stitch.final ?? takes[0].keys.look };+}++// ---------------------------------------------------------------------------+// Sessions (stored by src/server/shorts.ts, read by the page)++export interface ShortsTake {+ /** The generations of this take's steps, by role. */+ cut: string;+ frame?: string;+ look: string;+ createdAt: number;+}++export interface ShortsSessionSegment extends ShortsSegment {+ takes: ShortsTake[];+ /** The take (its look generation id) the stitch uses. */+ primary: string;+}++export interface ShortsStitch {+ /** Every generation of this stitch. */+ ids: string[];+ /** The finished video. */+ final: string;+ /** The primary takes it was made from, in order. */+ clips: string[];+ createdAt: number;+}++export interface ShortsSession {+ id: string;+ title: string;+ engine: Engine;+ batchId: string;+ look: ShortsLook;+ source: { url: string; name?: string; duration?: number; hasAudio?: boolean; width?: number; height?: number };+ range: ShortsRange;+ settings: { aspectRatio: ShortsRatio; language: string; modelId: string; resolution?: string; maxRefs: number };+ segments: ShortsSessionSegment[];+ stitches: ShortsStitch[];+ createdAt: number;+ updatedAt: number;+}++/** The plan input a stored session stands for (regenerate and stitch reuse it). */+export function sessionPlanInput(s: ShortsSession, seed?: number): ShortsPlanInput {+ return {+ engine: s.engine,+ title: s.title,+ source: s.source,+ range: s.range,+ look: s.look,+ aspectRatio: s.settings.aspectRatio,+ language: s.settings.language,+ modelId: s.settings.modelId,+ maxRefs: s.settings.maxRefs,+ resolution: s.settings.resolution,+ ...(seed !== undefined ? { seed } : {}),+ };+}++/** Whether the latest stitch was made from the current primary takes. */+export function stitchCurrent(s: Pick<ShortsSession, "segments" | "stitches">): boolean {+ const last = s.stitches[s.stitches.length - 1];+ if (!last) return false;+ const now = s.segments.map((g) => g.primary);+ return now.length === last.clips.length && now.every((id, i) => last.clips[i] === id);+}++export function formatSeconds(sec: number): string {+ const s = Math.max(0, sec);+ const m = Math.floor(s / 60);+ const rest = s - m * 60;+ const whole = Math.floor(rest);+ const tenth = Math.floor((rest - whole) * 10 + 1e-6);+ return `${m}:${String(whole).padStart(2, "0")}${tenth ? `.${tenth}` : ""}`;+}++// ---------------------------------------------------------------------------+// Progress of a chain of steps (a take: cut → first frame → restyle; a stitch: joins → sound → final)++export interface ChainState {+ status: "done" | "working" | "failed" | "gone";+ /** What's happening now ("Restyling", "Stitching"), or why it stopped. */+ label: string;+ /** 0–1 over the whole chain. */+ progress: number;+ error?: string;+ /** The generation that failed (Retry starts there). */+ failed?: Generation;+}++/**+ * One state for a few chained generations: done when the last one is, failed when any step failed+ * (with that step's own error, not "An earlier step didn't finish"), otherwise working on the+ * first step that isn't done. `gone` when the result was deleted.+ */+export function chainState(steps: { g?: Generation; label: string }[]): ChainState {+ const last = steps[steps.length - 1];+ if (!last?.g) return { status: "gone", label: "Deleted", progress: 0 };+ if (last.g.status === "succeeded") return { status: "done", label: "Ready", progress: 1 };+ const failed = steps.find((s) => s.g && (s.g.status === "failed" || s.g.status === "canceled"));+ if (failed?.g) {+ const why = failed.g.status === "canceled" ? "Canceled" : (failed.g.error ?? "Something went wrong");+ return { status: "failed", label: `${failed.label} failed`, progress: 0, error: why, failed: failed.g };+ }+ const missing = steps.find((s) => !s.g);+ if (missing) return { status: "gone", label: `${missing.label} was deleted`, progress: 0 };+ const i = steps.findIndex((s) => s.g!.status !== "succeeded");+ const cur = steps[i];+ const own = cur.g!.status === "running" ? (cur.g!.progress ?? 0) : 0;+ return { status: "working", label: cur.label, progress: (i + own) / steps.length };+}++/** A take's steps with their labels. */+export function takeSteps(t: Pick<ShortsTake, "cut" | "frame" | "look">, gens: Record<string, Generation>): { g?: Generation; label: string }[] {+ return [+ { g: gens[t.cut], label: "Cutting the segment" },+ ...(t.frame ? [{ g: gens[t.frame], label: "Restyling the first frame" }] : []),+ { g: gens[t.look], label: "Restyling" },+ ];+}++/** A stitch's steps with their labels (joins, the original sound, the final mux). */+export function stitchSteps(s: Pick<ShortsStitch, "ids" | "final">, gens: Record<string, Generation>): { g?: Generation; label: string }[] {+ const ids = s.ids.includes(s.final) ? s.ids : [...s.ids, s.final];+ return ids.map((id) => {+ const g = gens[id];+ const label = !g ? "A step" : g.op === "concat" ? "Stitching the segments" : g.op === "trim" ? "Cutting the original sound" : g.op === "mux" ? "Putting the sound back" : "Restyling";+ return { g, label };+ });+}diff --git a/src/lib/trim-range.ts b/src/lib/trim-range.tsnew file mode 100644index 00000000..e2204327--- /dev/null+++ b/src/lib/trim-range.ts@@ -0,0 +1,88 @@+/**+ * The arithmetic behind the video trimmer (src/components/studio/video-trimmer.tsx): keeping a+ * selection inside the clip and within a min/max length while one edge or the whole window moves.+ * Pure, so it is shared and tested.+ */++export interface TrimRange {+ startTime: number;+ endTime: number;+}++export interface TrimLimits {+ duration: number;+ /** Shortest selection, in seconds. */+ min?: number;+ /** Longest selection, in seconds. */+ max?: number;+}++const r2 = (n: number) => Math.round(n * 100) / 100;+const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));++/** The selection a fresh clip starts with: from the start, as long as allowed. */+export function initialRange(duration: number, max?: number): TrimRange {+ return { startTime: 0, endTime: r2(max ? Math.min(duration, max) : duration) };+}++/**+ * Keep a selection valid after an edit. `edge` says what the user moved: when an edge moves, the+ * other edge stays put and the moved one stops at the clip's ends and at the min/max length;+ * "move" keeps the length and slides the window within the clip.+ */+export function clampRange(r: TrimRange, limits: TrimLimits, edge: "start" | "end" | "move"): TrimRange {+ const d = Math.max(0, limits.duration);+ const min = Math.min(limits.min ?? 0, d);+ const max = Math.max(min, limits.max ?? d);+ let { startTime: s, endTime: e } = r;+ if (edge === "move") {+ const len = clamp(e - s, min, max);+ s = clamp(s, 0, Math.max(0, d - len));+ e = s + len;+ } else if (edge === "start") {+ e = clamp(e, Math.min(min, d), d);+ s = clamp(s, Math.max(0, e - max), Math.max(0, e - min));+ } else {+ s = clamp(s, 0, Math.max(0, d - min));+ e = clamp(e, s + min, Math.min(d, s + max));+ }+ return { startTime: r2(s), endTime: r2(e) };+}++/** Set one edge to a typed value (seconds), keeping the selection valid. */+export function setEdge(r: TrimRange, edge: "start" | "end", value: number, limits: TrimLimits): TrimRange {+ if (!Number.isFinite(value)) return r;+ return clampRange(edge === "start" ? { ...r, startTime: value } : { ...r, endTime: value }, limits, edge);+}++/** Slide the whole selection by `delta` seconds. */+export function moveRange(r: TrimRange, delta: number, limits: TrimLimits): TrimRange {+ return clampRange({ startTime: r.startTime + delta, endTime: r.endTime + delta }, limits, "move");+}++function spoken(sec: number): string {+ if (sec >= 60 && sec % 60 === 0) return `${sec / 60} minute${sec === 60 ? "" : "s"}`;+ return `${Number.isInteger(sec) ? sec : sec.toFixed(1)} second${sec === 1 ? "" : "s"}`;+}++/** What the trimmer asks for: "Select a 10-second segment", "Select up to 2 minutes", or nothing. */+export function trimHint(limits: TrimLimits): string | null {+ const { duration, min, max } = limits;+ if (min && duration < min - 0.05) return `This clip is ${duration.toFixed(1)} s — it needs at least ${spoken(min)}`;+ if (max && duration > max + 0.05) return max % 60 === 0 && max >= 60 ? `Select up to ${spoken(max)}` : `Select a ${Number.isInteger(max) ? max : max.toFixed(1)}-second segment`;+ return null;+}++/** When to grab the filmstrip's frames: the middle of `n` equal slices. */+export function thumbTimes(duration: number, n: number): number[] {+ if (!(duration > 0) || n < 1) return [];+ return Array.from({ length: n }, (_, i) => r2(((i + 0.5) * duration) / n));+}++/** "1:05.3" */+export function clock(sec: number): string {+ const s = Math.max(0, sec);+ const m = Math.floor(s / 60);+ const rest = s - m * 60;+ return `${m}:${rest.toFixed(1).padStart(4, "0")}`;+}diff --git a/src/server/db.ts b/src/server/db.tsindex 73575c8d..75383a4e 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -175,6 +175,30 @@ const MIGRATIONS: string[] = [edited_at INTEGER);CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,+ // Shorts Studio: sessions (a clip cut into segments, each with its takes and the chosen one, plus the stitches) and custom presets.+ `CREATE TABLE IF NOT EXISTS shorts_sessions (+ id TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ engine TEXT NOT NULL,+ batch_id TEXT NOT NULL,+ look_json TEXT NOT NULL,+ source_json TEXT NOT NULL,+ range_json TEXT NOT NULL,+ settings_json TEXT NOT NULL,+ segments_json TEXT NOT NULL DEFAULT '[]',+ stitches_json TEXT NOT NULL DEFAULT '[]',+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS shorts_sessions_updated ON shorts_sessions(updated_at DESC);+ CREATE TABLE IF NOT EXISTS shorts_presets (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ references_json TEXT NOT NULL DEFAULT '[]',+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );`,];declare global {diff --git a/src/server/generations.ts b/src/server/generations.tsindex e5034312..ff313d16 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -208,6 +208,8 @@ const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [{ table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"] },{ table: "cinema_items", cols: ["meta_json"], except: "generation_id" },{ table: "canvases", cols: ["graph_json"] },+ { table: "shorts_sessions", cols: ["source_json", "look_json"] },+ { table: "shorts_presets", cols: ["references_json"] },];/** Whether anything still refers to this stored file (see ASSET_REFS). */@@ -419,10 +421,17 @@ const STEM_ALIASES: Record<string, string[]> = {background: ["background", "accompaniment", "instrumental", "residual", "no_vocals"],};+/**+ * Soundtrack slots a video can fill: a step that made only a clip hands over the clip itself, and the+ * mux reads its sound (ComfyUI's LoadAudio and fal's FFmpeg take a video file as the audio input).+ * Shorts and Mixed Media put the trimmed source's own sound back under the restyled picture this way.+ */+const SOUNDTRACK_SLOTS = new Set<ChainSlot["slot"]>(["audio", "audio2"]);+/** The dependency output a slot takes: the first of the slot's kind, or the one with the slot's `stem`. */export function pickOutput(outputs: OutputFile[], s: ChainSlot): OutputFile | undefined {const ofKind = outputs.filter((o) => o.kind === SLOT_KIND[s.slot]);- if (!s.stem) return ofKind[0];+ if (!s.stem) return ofKind[0] ?? (SOUNDTRACK_SLOTS.has(s.slot) ? outputs.find((o) => o.kind === "video") : undefined);const want = STEM_ALIASES[s.stem.toLowerCase()] ?? [s.stem.toLowerCase()];return ofKind.find((o) => typeof o.meta?.stem === "string" && want.includes(o.meta.stem.toLowerCase()));}diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.tsnew file mode 100644index 00000000..1ab27f0e--- /dev/null+++ b/src/server/mixed-media.ts@@ -0,0 +1,143 @@+import "server-only";+import { getModel } from "@/lib/catalog";+import {+ clampFps,+ cleanValues,+ getMixedPreset,+ MIXED_MODELS,+ mixedFrames,+ mixedRangeProblem,+ nearestResolution,+ planMixed,+ planMixedPreview,+ type MixedPlanInput,+ type MixedResolution,+} from "@/lib/catalog/mixed-media";+import type { PlanStep } from "@/lib/catalog/shorts";+import { takesImage } from "@/lib/catalog/shorts-models";+import type { Engine, Generation } from "@/lib/catalog/types";+import { createPipeline } from "./chains";+import { previewChained } from "./generations";+import { engineMode } from "./settings";+import { probeSource, ShortsError } from "./shorts";++/**+ * Mixed Media renders and preview frames. No table of its own: every render is a pipeline of+ * ordinary generations (feature "mixed-media" for the finished video, "mixed-media-step" for the+ * cut and the soundtrack-less render, "mixed-media-preview" for preview frames), so History is a feed.+ */++export { ShortsError as MixedError };++export interface MixedBody {+ engine: Engine;+ presetId: string;+ values?: Record<string, unknown>;+ source: { url: string; name?: string; duration?: number; fps?: number };+ range: { start: number; end: number };+ fps: number;+ resolution: MixedResolution;+ modelId?: string;+ /** Cloud: the approved preview still (anchors the render when the model takes an image). */+ anchor?: string;+ /** Cloud preview: the frame the browser grabbed at the start of the selection. */+ frameUrl?: string;+ seed?: number;+}++async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ input: MixedPlanInput; frames: number; notes: string[] }> {+ const mode = engineMode();+ if (mode !== "both" && mode !== body.engine) {+ throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);+ }+ const preset = getMixedPreset(body.presetId);+ if (!preset) throw new ShortsError("Pick a preset");+ const info = opts.probe ? await probeSource(body.source.url) : {};+ const duration = info.duration ?? body.source.duration;+ const sourceFps = info.fps ?? body.source.fps;+ const problem = mixedRangeProblem(body.range, duration, sourceFps);+ if (problem) throw new ShortsError(problem);+ const fps = clampFps(body.fps, sourceFps);+ const modelId = body.modelId && MIXED_MODELS[body.engine].includes(body.modelId) ? body.modelId : MIXED_MODELS[body.engine][0];+ const model = getModel(modelId);+ const notes: string[] = [];+ const anchor = body.engine === "cloud" && body.anchor && takesImage(modelId) ? body.anchor : undefined;+ if (body.engine === "cloud") {+ if (body.anchor && !anchor) notes.push(`${model?.name} restyles from words only — the preview frame isn't sent`);+ notes.push(`${model?.name} renders smooth motion at its own frame rate; the frame rate sets the frame count shown here and the open engine's sampling`);+ } else if (body.resolution !== "1K") notes.push("The open engine renders up to 1536 px on the long side");+ const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);+ return {+ frames: mixedFrames(body.range.end - body.range.start, fps),+ notes,+ input: {+ engine: body.engine,+ title: name ? `${preset.name} · ${name}` : `${preset.name} mixed media`,+ preset,+ values: cleanValues(preset, body.values),+ source: { url: body.source.url, duration, hasAudio: info.hasAudio ?? true },+ range: body.range,+ fps,+ resolution: body.resolution,+ modelId,+ anchor,+ modelResolution: body.engine === "cloud" ? nearestResolution(model?.options.resolutions, body.resolution) : undefined,+ // LTX follows the clip's outlines, like the open engine's canny ControlNet.+ extra: modelId === "ltx-2-3-restyle" ? { preprocessor: "canny" } : undefined,+ ...(body.seed !== undefined ? { seed: body.seed } : {}),+ },+ };+}++const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });++function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {+ let cost: number | null = 0;+ let demo = false;+ for (const s of steps) {+ const p = previewChained(withChain(s), s.after?.length ?? 0);+ demo ||= p.demo;+ cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;+ }+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };+}++export interface MixedEstimate {+ costUsd: number | null;+ previewUsd: number | null;+ demo: boolean;+ frames: number;+ fps: number;+ notes: string[];+}++export async function estimateMixed(body: MixedBody): Promise<MixedEstimate> {+ const { input, frames, notes } = await planInput(body, { probe: false });+ const full = price(planMixed(input).steps);+ const preview = price([planMixedPreview({ ...input, frameUrl: body.frameUrl ?? "/api/files/placeholder.png" })]);+ return { ...full, previewUsd: preview.costUsd, frames, fps: input.fps, notes };+}++function run(steps: PlanStep[]): { batchId: string; items: Generation[]; byKey: Record<string, Generation> } {+ try {+ return createPipeline(steps);+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+}++/** Start the full render; returns the finished video's generation (the others wait for it). */+export async function createMixed(body: MixedBody): Promise<{ final: Generation; items: Generation[] }> {+ const { input } = await planInput(body, { probe: true });+ const plan = planMixed(input);+ const p = run(plan.steps);+ return { final: p.byKey[plan.final], items: p.items };+}++/** One frame with the current settings. */+export async function createMixedPreview(body: MixedBody): Promise<Generation> {+ const { input } = await planInput(body, { probe: true });+ if (input.engine === "cloud" && !body.frameUrl?.startsWith("/api/files/")) throw new ShortsError("Couldn't grab a frame from this clip in the browser — generate the full video instead");+ const step = planMixedPreview({ ...input, frameUrl: body.frameUrl });+ return run([step]).byKey.preview;+}diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.tsindex c73ecb74..81ad64d5 100644--- a/src/server/providers/mock.ts+++ b/src/server/providers/mock.ts@@ -246,7 +246,11 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,case "trim":case "captions":case "mux":- return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } }];+ return [+ { url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } },+ // The segment cutter also hands over the segment's first frame (Shorts restyles it, then the clip).+ ...(meta.firstFrame ? [{ url: svgUri(demoSvg("first frame", ar, 3)), kind: "image" as const, contentType: "image/svg+xml", meta: { role: "first-frame", demo: true } }] : []),+ ];}if (kind === "image") {return Array.from({ length: Number(meta.count) }, (_, i) => ({ url: svgUri(demoSvg(prompt, ar, i)), kind: "image" as const, contentType: "image/svg+xml" }));@@ -282,6 +286,8 @@ export const mockProvider: ProviderAdapter = {targetLanguage: input.targetLanguage,sourceLanguage: input.sourceLanguage,numLayers: input.numLayers,+ // Workflows whose second output is the cut's first frame (video-segment-resample).+ firstFrame: route.provider === "comfyui" && route.endpoint === "video-segment-resample",},payload: { demo: true, ...input },};diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.tsnew file mode 100644index 00000000..b140bde1--- /dev/null+++ b/src/server/shorts-schemas.ts@@ -0,0 +1,76 @@+import "server-only";+import { z } from "zod";+import { MIXED } from "@/lib/catalog/mixed-media";+import { SHORTS } from "@/lib/catalog/shorts";+import { ShortsError } from "./shorts";++/** Request bodies for /api/shorts/** and /api/mixed-media/** (zod), and the shared error answer. */++const fileUrl = z.string().startsWith("/api/files/").max(500);+const seconds = z.number().finite().min(0).max(3600);++const source = z.object({+ url: fileUrl,+ name: z.string().max(200).optional(),+ duration: z.number().finite().positive().max(3600).optional(),+ fps: z.number().finite().positive().max(240).optional(),+});++export const ShortsBodySchema = z.object({+ engine: z.enum(["cloud", "open"]),+ presetId: z.string().min(1).max(80),+ source,+ range: z.object({ start: seconds, end: seconds }),+ aspectRatio: z.enum(["9:16", "16:9"]).default("9:16"),+ language: z.string().max(40).default("auto"),+ modelId: z.string().max(80).optional(),+});++/** The estimate is asked for before the upload finishes: any URL stands in. */+export const ShortsEstimateSchema = ShortsBodySchema.extend({ source: source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }) });++export const PresetBodySchema = z.object({+ name: z.string().trim().max(60).optional(),+ description: z.string().trim().max(300).optional(),+ references: z.array(fileUrl).min(1).max(SHORTS.maxReferences),+});++export const PresetPatchSchema = PresetBodySchema.partial();++export const MixedBodySchema = z.object({+ engine: z.enum(["cloud", "open"]),+ presetId: z.string().min(1).max(80),+ values: z.record(z.string(), z.string().max(200)).optional(),+ source,+ range: z.object({ start: seconds, end: seconds }),+ fps: z.number().finite().min(MIXED.manualFps.min).max(MIXED.manualFps.max).default(MIXED.defaultFps),+ resolution: z.enum(MIXED.resolutions).default("1K"),+ modelId: z.string().max(80).optional(),+ anchor: fileUrl.optional(),+ frameUrl: fileUrl.optional(),+ seed: z.number().int().min(0).max(2 ** 48).optional(),+});++export const MixedEstimateSchema = MixedBodySchema.extend({ source: source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }) });++/** A user-facing error answer: ShortsError keeps its status; anything else from the planner is a 422. */+export function errorResponse(e: unknown): Response {+ if (e instanceof ShortsError) return Response.json({ error: e.message }, { status: e.status });+ return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 422 });+}++/** Parse a JSON body with a schema; a bad one is a 400 with `message`. */+export async function body<S extends z.ZodType>(request: Request, schema: S, message: string): Promise<z.infer<S>> {+ const parsed = schema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) throw new ShortsError(message, 400);+ return parsed.data;+}++/** Run a route body, answering errors as `{ error }`. */+export async function handle(fn: () => Promise<Response> | Response): Promise<Response> {+ try {+ return await fn();+ } catch (e) {+ return errorResponse(e);+ }+}diff --git a/src/server/shorts.ts b/src/server/shorts.tsnew file mode 100644index 00000000..0e757b1f--- /dev/null+++ b/src/server/shorts.ts@@ -0,0 +1,518 @@+import "server-only";+import { nanoid } from "nanoid";+import { getModel } from "@/lib/catalog";+import { maxRefsFor, reframes, resolutionFor } from "@/lib/catalog/shorts-models";+import {+ customPresetName,+ getShortsPreset,+ lookFromCustom,+ lookFromPreset,+ planShorts,+ planStitch,+ planTake,+ rangeProblem,+ sessionPlanInput,+ SHORTS,+ SHORTS_MODELS,+ type PlanStep,+ type ShortsCustomPreset,+ type ShortsLook,+ type ShortsPlanInput,+ type ShortsRange,+ type ShortsRatio,+ type ShortsSession,+ type ShortsSessionSegment,+ type ShortsStitch,+} from "@/lib/catalog/shorts";+import type { Engine, Generation } from "@/lib/catalog/types";+import { probeMedia, type MediaInfo } from "@/lib/media-probe";+import { createPipeline } from "./chains";+import { db } from "./db";+import { getGeneration, previewChained } from "./generations";+import { trashGenerations } from "./library";+import { engineMode } from "./settings";+import { readRef } from "./storage";++/**+ * Shorts Studio sessions: a clip cut into segments, each restyled (one or more takes, one of them+ * primary) and stitched back together under the original sound. Every step is an ordinary+ * generation made through createPipeline; a session only records which generation is which.+ */++export class ShortsError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++// ---------------------------------------------------------------------------+// Models (what each restyle model takes: src/lib/catalog/shorts-models.ts)++export { maxRefsFor, modelInfos, resolutionFor } from "@/lib/catalog/shorts-models";++// ---------------------------------------------------------------------------+// Source clips++export interface SourceInfo {+ duration?: number;+ width?: number;+ height?: number;+ fps?: number;+ hasAudio?: boolean;+}++/** What the clip's header says (MP4 / MOV; other containers come back empty and the browser's numbers are used). */+export async function probeSource(url: string): Promise<SourceInfo> {+ if (!url.startsWith("/api/files/")) throw new ShortsError("Upload the clip first");+ let info: MediaInfo | null = null;+ try {+ info = probeMedia((await readRef(url)).data);+ } catch {+ throw new ShortsError("That clip is gone — upload it again", 404);+ }+ if (!info) return {};+ return {+ duration: info.videoDuration ?? info.duration,+ width: info.width,+ height: info.height,+ fps: info.fps,+ hasAudio: info.hasAudio,+ };+}++// ---------------------------------------------------------------------------+// Rows++interface SessionRow {+ id: string;+ title: string;+ engine: string;+ batch_id: string;+ look_json: string;+ source_json: string;+ range_json: string;+ settings_json: string;+ segments_json: string;+ stitches_json: string;+ created_at: number;+ updated_at: number;+}++const toSession = (r: SessionRow): ShortsSession => ({+ id: r.id,+ title: r.title,+ engine: r.engine as Engine,+ batchId: r.batch_id,+ look: JSON.parse(r.look_json),+ source: JSON.parse(r.source_json),+ range: JSON.parse(r.range_json),+ settings: JSON.parse(r.settings_json),+ segments: JSON.parse(r.segments_json),+ stitches: JSON.parse(r.stitches_json),+ createdAt: r.created_at,+ updatedAt: r.updated_at,+});++function readSession(id: string): ShortsSession {+ const r = db().prepare("SELECT * FROM shorts_sessions WHERE id = ?").get(id) as SessionRow | undefined;+ if (!r) throw new ShortsError("This short no longer exists", 404);+ return toSession(r);+}++function saveSession(s: ShortsSession): ShortsSession {+ const now = Date.now();+ db()+ .prepare("UPDATE shorts_sessions SET segments_json = ?, stitches_json = ?, title = ?, updated_at = ? WHERE id = ?")+ .run(JSON.stringify(s.segments), JSON.stringify(s.stitches), s.title, now, s.id);+ return { ...s, updatedAt: now };+}++interface PresetRow {+ id: string;+ name: string;+ description: string;+ references_json: string;+ created_at: number;+ updated_at: number;+}++const toPreset = (r: PresetRow): ShortsCustomPreset => ({+ id: r.id,+ name: r.name,+ description: r.description,+ references: JSON.parse(r.references_json),+ createdAt: r.created_at,+ updatedAt: r.updated_at,+});++// ---------------------------------------------------------------------------+// Custom presets ("Create a preset from references")++export function listCustomPresets(): ShortsCustomPreset[] {+ return (db().prepare("SELECT * FROM shorts_presets ORDER BY created_at DESC").all() as PresetRow[]).map(toPreset);+}++export function getCustomPreset(id: string): ShortsCustomPreset | null {+ const r = db().prepare("SELECT * FROM shorts_presets WHERE id = ?").get(id) as PresetRow | undefined;+ return r ? toPreset(r) : null;+}++export function createCustomPreset(input: { name?: string; description?: string; references: string[] }): ShortsCustomPreset {+ const refs = [...new Set(input.references)].slice(0, SHORTS.maxReferences);+ if (!refs.length) throw new ShortsError("Add at least one reference image");+ const count = (db().prepare("SELECT COUNT(*) AS n FROM shorts_presets").get() as { n: number }).n;+ const description = (input.description ?? "").trim();+ const name = input.name?.trim() || customPresetName(description, count);+ const now = Date.now();+ const id = `custom-${nanoid(10)}`;+ db()+ .prepare("INSERT INTO shorts_presets (id, name, description, references_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)")+ .run(id, name, description, JSON.stringify(refs), now, now);+ return getCustomPreset(id)!;+}++export function updateCustomPreset(id: string, patch: { name?: string; description?: string; references?: string[] }): ShortsCustomPreset {+ const cur = getCustomPreset(id);+ if (!cur) throw new ShortsError("This preset no longer exists", 404);+ const refs = patch.references ? [...new Set(patch.references)].slice(0, SHORTS.maxReferences) : cur.references;+ if (!refs.length) throw new ShortsError("Keep at least one reference image");+ db()+ .prepare("UPDATE shorts_presets SET name = ?, description = ?, references_json = ?, updated_at = ? WHERE id = ?")+ .run(patch.name?.trim() || cur.name, patch.description?.trim() ?? cur.description, JSON.stringify(refs), Date.now(), id);+ return getCustomPreset(id)!;+}++export function deleteCustomPreset(id: string): boolean {+ return db().prepare("DELETE FROM shorts_presets WHERE id = ?").run(id).changes > 0;+}++// ---------------------------------------------------------------------------+// Planning++export interface ShortsBody {+ engine: Engine;+ presetId: string;+ source: { url: string; name?: string; duration?: number };+ range: ShortsRange;+ aspectRatio: ShortsRatio;+ language: string;+ modelId?: string;+}++function lookFor(presetId: string): ShortsLook {+ const built = getShortsPreset(presetId);+ if (built) return lookFromPreset(built);+ const custom = getCustomPreset(presetId);+ if (custom) return lookFromCustom(custom);+ throw new ShortsError("Pick a preset");+}++function checkEngine(engine: Engine) {+ const mode = engineMode();+ if (mode !== "both" && mode !== engine) {+ throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);+ }+}++const fileTitle = (name?: string) =>+ (name ?? "")+ .replace(/\.[a-z0-9]{2,4}$/i, "")+ .replace(/[_-]+/g, " ")+ .trim()+ .slice(0, 40);++/** The plan input for a request: model, look, clip facts (from its header when it has one). */+async function planInput(body: ShortsBody, opts: { probe: boolean }): Promise<{ input: ShortsPlanInput; info: SourceInfo }> {+ checkEngine(body.engine);+ const modelId = body.modelId && SHORTS_MODELS[body.engine].includes(body.modelId) ? body.modelId : SHORTS_MODELS[body.engine][0];+ const look = lookFor(body.presetId);+ const info = opts.probe ? await probeSource(body.source.url) : {};+ const duration = info.duration ?? body.source.duration;+ const problem = rangeProblem(body.range, duration);+ if (problem) throw new ShortsError(problem);+ const name = fileTitle(body.source.name);+ return {+ info,+ input: {+ engine: body.engine,+ title: name ? `${look.name} · ${name}` : `${look.name} short`,+ // Unknown sound (a container the header reader doesn't know) is treated as present.+ source: { url: body.source.url, duration, hasAudio: info.hasAudio ?? true },+ range: body.range,+ look,+ aspectRatio: body.aspectRatio,+ language: body.language || "auto",+ modelId,+ maxRefs: maxRefsFor(modelId),+ resolution: resolutionFor(modelId),+ },+ };+}++const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });++/** Price and run mode of some steps, as createPipeline would make them. */+function priceSteps(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {+ let cost: number | null = 0;+ let demo = false;+ for (const s of steps) {+ const p = previewChained(withChain(s), s.after?.length ?? 0);+ demo ||= p.demo;+ cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;+ }+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };+}++export interface ShortsEstimate {+ costUsd: number | null;+ /** One segment's restyle (what Regenerate costs). */+ perSegmentUsd: number | null;+ demo: boolean;+ segments: number;+ seconds: number;+ refsSent: number;+ notes: string[];+}++function notesFor(input: ShortsPlanInput): string[] {+ const notes: string[] = [];+ const refs = input.look.references?.length ?? 0;+ if (refs && input.engine === "cloud" && !input.maxRefs) notes.push(`${getModel(input.modelId)?.name ?? "This model"} restyles from words only — pick Kling O3 4K Edit or Happy Horse to use your reference images`);+ if (refs > SHORTS.openReferences && input.engine === "open") notes.push(`The open engine uses your first ${SHORTS.openReferences} reference images`);+ if (input.engine === "cloud") {+ if (!reframes(input.modelId)) notes.push(`${getModel(input.modelId)?.name} keeps your clip's shape; the open engine crops to ${input.aspectRatio}`);+ }+ return notes;+}++/** What a session would cost and how it would run, without creating anything. */+export async function estimateShorts(body: ShortsBody): Promise<ShortsEstimate> {+ const { input } = await planInput(body, { probe: false });+ const plan = planShorts(input);+ const all = priceSteps(plan.steps);+ const one = priceSteps(planTake(input, plan.segments[0], plan.segments.length).steps);+ return {+ ...all,+ perSegmentUsd: one.costUsd,+ segments: plan.segments.length,+ seconds: Math.round((input.range.end - input.range.start) * 10) / 10,+ refsSent: input.engine === "open" ? Math.min(SHORTS.openReferences, input.look.references?.length ?? 0) : Math.min(input.maxRefs, input.look.references?.length ?? 0),+ notes: notesFor(input),+ };+}++// ---------------------------------------------------------------------------+// Sessions++export async function createSession(body: ShortsBody): Promise<ShortsSession> {+ const { input, info } = await planInput(body, { probe: true });+ const plan = planShorts(input);+ const pipeline = (() => {+ try {+ return createPipeline(plan.steps);+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+ })();+ const id = (k: string) => pipeline.byKey[k].id;+ const now = Date.now();+ const segments: ShortsSessionSegment[] = plan.segments.map((s, i) => {+ const t = plan.takes[i];+ return { ...s, takes: [{ cut: id(t.cut), ...(t.frame ? { frame: id(t.frame) } : {}), look: id(t.look), createdAt: now }], primary: id(t.look) };+ });+ const takeKeys = new Set(plan.takes.flatMap((t) => [t.cut, t.look, ...(t.frame ? [t.frame] : [])]));+ const stitch: ShortsStitch = {+ ids: plan.steps.filter((s) => !takeKeys.has(s.key)).map((s) => id(s.key)),+ final: id(plan.final!),+ clips: segments.map((s) => s.primary),+ createdAt: now,+ };+ const session: ShortsSession = {+ id: nanoid(10),+ title: input.title,+ engine: input.engine,+ batchId: pipeline.batchId,+ look: input.look,+ source: { url: input.source.url, name: body.source.name, duration: input.source.duration, hasAudio: input.source.hasAudio, width: info.width, height: info.height },+ range: input.range,+ settings: { aspectRatio: input.aspectRatio, language: input.language, modelId: input.modelId, resolution: input.resolution, maxRefs: input.maxRefs },+ segments,+ stitches: [stitch],+ createdAt: now,+ updatedAt: now,+ };+ db()+ .prepare(+ `INSERT INTO shorts_sessions (id, title, engine, batch_id, look_json, source_json, range_json, settings_json, segments_json, stitches_json, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run(+ session.id,+ session.title,+ session.engine,+ session.batchId,+ JSON.stringify(session.look),+ JSON.stringify(session.source),+ JSON.stringify(session.range),+ JSON.stringify(session.settings),+ JSON.stringify(session.segments),+ JSON.stringify(session.stitches),+ now,+ now,+ );+ return session;+}++/** Every generation a session made. */+export function sessionIds(s: ShortsSession): string[] {+ const ids = [...s.segments.flatMap((g) => g.takes.flatMap((t) => [t.cut, t.look, ...(t.frame ? [t.frame] : [])])), ...s.stitches.flatMap((x) => [...x.ids, x.final])];+ return [...new Set(ids)];+}++export interface ShortsSessionView extends ShortsSession {+ /** The session's generations by id (trashed or deleted ones are missing). */+ generations: Record<string, Generation>;+}++export function getSession(id: string): ShortsSessionView {+ const s = readSession(id);+ const generations: Record<string, Generation> = {};+ for (const gid of sessionIds(s)) {+ const g = getGeneration(gid);+ if (g) generations[gid] = g;+ }+ return { ...s, generations };+}++export interface ShortsSessionCard {+ id: string;+ title: string;+ engine: Engine;+ lookName: string;+ segments: number;+ seconds: number;+ createdAt: number;+ updatedAt: number;+ /** The newest stitch's video, else the first segment's chosen take. */+ cover: Generation | null;+ status: "rendering" | "ready" | "failed";+}++export function listSessions(limit = 60): ShortsSessionCard[] {+ const rows = db().prepare("SELECT * FROM shorts_sessions ORDER BY created_at DESC LIMIT ?").all(limit) as SessionRow[];+ return rows.map((r) => {+ const s = toSession(r);+ const final = s.stitches.length ? getGeneration(s.stitches[s.stitches.length - 1].final) : null;+ const looks = s.segments.map((g) => getGeneration(g.primary));+ const active = [final, ...looks].some((g) => g && (g.status === "queued" || g.status === "running"));+ const failed = [final, ...looks].some((g) => !g || g.status === "failed" || g.status === "canceled");+ return {+ id: s.id,+ title: s.title,+ engine: s.engine,+ lookName: s.look.name,+ segments: s.segments.length,+ seconds: Math.round((s.range.end - s.range.start) * 10) / 10,+ createdAt: s.createdAt,+ updatedAt: s.updatedAt,+ cover: final?.status === "succeeded" ? final : (looks.find((g) => g?.status === "succeeded") ?? final ?? looks[0] ?? null),+ status: active ? "rendering" : failed ? "failed" : "ready",+ };+ });+}++export function renameSession(id: string, title: string): ShortsSession {+ const s = readSession(id);+ return saveSession({ ...s, title: title.trim().slice(0, 120) || s.title });+}++/** Delete a session; its generations move to the Trash (restorable for 30 days) unless `keep`. */+export function deleteSession(id: string, opts: { keep?: boolean } = {}): number {+ const s = readSession(id);+ const trashed = opts.keep ? 0 : trashGenerations(sessionIds(s));+ db().prepare("DELETE FROM shorts_sessions WHERE id = ?").run(id);+ return trashed;+}++const segmentAt = (s: ShortsSession, index: number) => {+ const seg = s.segments[index];+ if (!seg) throw new ShortsError("No such segment", 404);+ return seg;+};++const usable = (id: string) => {+ const g = getGeneration(id);+ return !!g && g.status !== "failed" && g.status !== "canceled";+};++/** A new take of one segment (a fresh seed). It becomes the chosen take when the current one failed or is gone. */+export function regenerateSegment(id: string, index: number): ShortsSessionView {+ const s = readSession(id);+ const seg = segmentAt(s, index);+ checkEngine(s.engine);+ const seed = Math.floor(Math.random() * 2 ** 31);+ const take = planTake(sessionPlanInput(s, seed), seg, s.segments.length, `r${seg.takes.length}`);+ let pipeline;+ try {+ pipeline = createPipeline(take.steps, { batchId: s.batchId });+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+ const id_ = (k: string) => pipeline.byKey[k].id;+ const next = { cut: id_(take.keys.cut), ...(take.keys.frame ? { frame: id_(take.keys.frame) } : {}), look: id_(take.keys.look), createdAt: Date.now() };+ const segments = s.segments.map((g, i) => (i === index ? { ...g, takes: [...g.takes, next], primary: usable(g.primary) ? g.primary : next.look } : g));+ saveSession({ ...s, segments });+ return getSession(id);+}++/** Use another take of a segment in the stitch. */+export function makePrimary(id: string, index: number, lookId: string): ShortsSessionView {+ const s = readSession(id);+ const seg = segmentAt(s, index);+ if (!seg.takes.some((t) => t.look === lookId)) throw new ShortsError("That take isn't part of this segment");+ saveSession({ ...s, segments: s.segments.map((g, i) => (i === index ? { ...g, primary: lookId } : g)) });+ return getSession(id);+}++/** Join the chosen takes again (after a regenerate or a new choice) and put the sound back. */+export function stitchSession(id: string): ShortsSessionView {+ const s = readSession(id);+ checkEngine(s.engine);+ const clips = s.segments.map((seg, i) => {+ const g = getGeneration(seg.primary);+ if (!g) throw new ShortsError(`Segment ${i + 1}'s take was deleted — regenerate it first`, 409);+ if (g.status === "queued" || g.status === "running") throw new ShortsError(`Segment ${i + 1} is still rendering`, 409);+ const url = g.outputs.find((o) => o.kind === "video")?.url;+ if (g.status !== "succeeded" || !url) throw new ShortsError(`Segment ${i + 1} didn't render — regenerate it first`, 409);+ return { url };+ });+ const plan = planStitch(sessionPlanInput(s), clips, `-s${s.stitches.length}`);+ const now = Date.now();+ let stitch: ShortsStitch;+ if (!plan.steps.length || !plan.final) {+ // One silent segment: its take is the short.+ stitch = { ids: [], final: s.segments[0].primary, clips: s.segments.map((g) => g.primary), createdAt: now };+ } else {+ let pipeline;+ try {+ pipeline = createPipeline(plan.steps, { batchId: s.batchId });+ } catch (e) {+ throw new ShortsError((e as Error).message, 422);+ }+ stitch = { ids: plan.steps.map((x) => pipeline.byKey[x.key].id), final: pipeline.byKey[plan.final].id, clips: s.segments.map((g) => g.primary), createdAt: now };+ }+ saveSession({ ...s, stitches: [...s.stitches, stitch] });+ return getSession(id);+}++/** What one more take of a segment costs. */+export function regenerateCost(s: ShortsSession): number | null {+ try {+ return priceSteps(planTake(sessionPlanInput(s, 1), s.segments[0], s.segments.length).steps).costUsd;+ } catch {+ return null;+ }+}diff --git a/tests/fixtures/shorts-12s.mp4 b/tests/fixtures/shorts-12s.mp4new file mode 100644index 00000000..0b53f71aBinary files /dev/null and b/tests/fixtures/shorts-12s.mp4 differdiff --git a/tests/mixed-media.test.ts b/tests/mixed-media.test.tsnew file mode 100644index 00000000..df6d4d25--- /dev/null+++ b/tests/mixed-media.test.ts@@ -0,0 +1,186 @@+import { describe, expect, it } from "vitest";+import { getModel } from "@/lib/catalog";+import {+ clampFps,+ cleanValues,+ colorName,+ defaultValues,+ denoiseFor,+ fpsChoices,+ framesCost,+ getMixedPreset,+ MIXED,+ MIXED_MODELS,+ MIXED_PRESETS,+ MIXED_TOOLS,+ mixedFrames,+ mixedLook,+ mixedPrompts,+ mixedRangeProblem,+ nearestResolution,+ planMixed,+ planMixedPreview,+ settingWords,+ type MixedPlanInput,+} from "@/lib/catalog/mixed-media";+import { FX } from "@/lib/preset-cards";++const sketch = getMixedPreset("mixed-sketch")!;+const windows = getMixedPreset("mixed-windows")!;++const input = (over: Partial<MixedPlanInput> = {}): MixedPlanInput => ({+ engine: "open",+ title: "Sketch · skate",+ preset: sketch,+ values: defaultValues(sketch),+ source: { url: "/api/files/uploads/skate.mp4", duration: 12, hasAudio: true },+ range: { start: 2, end: 7 },+ fps: 8,+ resolution: "1K",+ modelId: "oss-mixed-media",+ ...over,+});++describe("Mixed Media presets", () => {+ it("has Higgsfield's 33 presets, each with its own settings and an intensity", () => {+ expect(MIXED_PRESETS).toHaveLength(33);+ expect(new Set(MIXED_PRESETS.map((p) => p.id)).size).toBe(33);+ for (const p of MIXED_PRESETS) {+ expect(p.description.length).toBeGreaterThan(8);+ expect(FX).toContain(p.fx);+ expect(p.settings.at(-1)!.key).toBe("intensity");+ expect(new Set(p.settings.map((s) => s.key)).size).toBe(p.settings.length);+ // Every placeholder has a setting and every setting but intensity is used.+ const used = [...p.look.matchAll(/\{(\w+)\}/g)].map((m) => m[1]);+ expect(used.sort()).toEqual(p.settings.filter((s) => s.key !== "intensity").map((s) => s.key).sort());+ expect(mixedLook(p, defaultValues(p))).not.toMatch(/[{}]/);+ }+ });++ it("uses real models", () => {+ for (const id of [...MIXED_MODELS.cloud, ...MIXED_MODELS.open, ...Object.values(MIXED_TOOLS.cloud), ...Object.values(MIXED_TOOLS.open)]) expect(getModel(id), id).toBeDefined();+ });++ it("cleans saved settings: bad colours and unknown options go back to the default, words are kept", () => {+ const v = cleanValues(sketch, { ink: "#ABCDEF", paper: "nope", intensity: "bold", stray: "x" });+ expect(v).toEqual({ ink: "#abcdef", paper: "white-paper", intensity: "bold" });+ expect(cleanValues(sketch, { ink: "text:the blue of old ballpoint pens", paper: "text:a page torn from a diary" })).toMatchObject({+ ink: "text:the blue of old ballpoint pens",+ paper: "text:a page torn from a diary",+ });+ expect(cleanValues(sketch, { ink: "red" }).ink).toBe("#1d1d1f");+ expect(cleanValues(windows, { title: " a very long window title that goes on and on and on " }).title).toHaveLength(40);+ });++ it("names colours in words for the prompt", () => {+ expect(colorName("#ff0000")).toBe("bright red");+ expect(colorName("#1d1d1f")).toBe("black");+ expect(colorName("#ffffff")).toBe("white");+ expect(colorName("#2a6f97")).toBe("deep sky blue");+ expect(colorName("#7cff00")).toBe("bright lime");+ expect(colorName("#8b4513")).toBe("brown");+ expect(colorName("#ffc0cb")).toBe("pale pink");+ expect(settingWords(sketch.settings[0], "#00e5ff")).toBe("bright cyan (#00E5FF)");+ });++ it("fills the look with the settings", () => {+ expect(mixedLook(sketch, { ink: "#c1121f", paper: "notebook-grid", intensity: "balanced" })).toBe(+ "hand-drawn textured linework in deep red (#C1121F) ink on a squared notebook page, cross-hatching and loose construction lines",+ );+ expect(mixedLook(windows, { title: "dream.exe", color: "text:sunset orange", intensity: "bold" })).toMatch(/title bars reading “dream\.exe”.*accents in sunset orange, pushed all the way, fully stylised$/);+ const p = mixedPrompts(sketch, defaultValues(sketch));+ expect(p.video).toMatch(/^Restyle this video as hand-drawn textured linework.*change only the look\.$/);+ expect(p.frame).toMatch(/^Hand-drawn textured linework/);+ expect(p.still).toMatch(/^Redraw this image as/);+ expect(denoiseFor({ intensity: "subtle" })).toBe(0.55);+ expect(denoiseFor({})).toBe(0.7);+ });+});++describe("Mixed Media frames and cost", () => {+ it("counts output frames as floor(seconds × fps)", () => {+ expect(mixedFrames(10, 8)).toBe(80);+ expect(mixedFrames(10, 24)).toBe(240);+ expect(mixedFrames(3.33, 12)).toBe(39);+ expect(mixedFrames(0.3, 4)).toBe(1);+ });++ it("prices per frame, double at 4K", () => {+ expect(framesCost(160, 0.02)).toBe(3.2);+ expect(framesCost(160, 0.02, "4K")).toBe(6.4);+ expect(framesCost(80, 0)).toBe(0);+ });++ it("never samples faster than the clip", () => {+ expect(fpsChoices(10).map((c) => [c.fps, c.disabled])).toEqual([+ [4, false],+ [8, false],+ [10, false],+ [12, true],+ [24, true],+ ]);+ expect(fpsChoices(undefined).every((c) => !c.disabled)).toBe(true);+ expect(clampFps(24, 10)).toBe(10);+ expect(clampFps(24, 29.97)).toBe(24);+ expect(clampFps(30)).toBe(24);+ expect(clampFps(2)).toBe(4);+ expect(clampFps(15.4, 30)).toBe(15);+ expect(MIXED.defaultFps).toBe(8);+ });++ it("checks the selection", () => {+ expect(mixedRangeProblem({ start: 0, end: 0.5 })).toBe("Select at least 1 second");+ expect(mixedRangeProblem({ start: 0, end: 11 })).toBe("Select up to 10 seconds");+ expect(mixedRangeProblem({ start: 0, end: 5 }, 12, 3)).toBe("Video must be at least 4 FPS");+ expect(mixedRangeProblem({ start: 2, end: 12 }, 12, 30)).toBe(null);+ });++ it("asks cloud models for their closest resolution", () => {+ expect(nearestResolution(["720p", "1080p"], "4K")).toBe("1080p");+ expect(nearestResolution(["360p", "720p", "1080p", "4k"], "4K")).toBe("4k");+ expect(nearestResolution(["360p", "720p", "1080p", "4k"], "1K")).toBe("720p");+ expect(nearestResolution(["auto", "480p", "720p"], "2K")).toBe("720p");+ expect(nearestResolution(undefined, "2K")).toBeUndefined();+ });+});++describe("Mixed Media pipeline shape", () => {+ it("open: one per-frame job on the selection at the chosen frame rate", () => {+ const plan = planMixed(input({ values: { ...defaultValues(sketch), intensity: "bold" } }));+ expect(plan.final).toBe("render");+ expect(plan.steps).toHaveLength(1);+ expect(plan.steps[0].request).toMatchObject({+ feature: "mixed-media",+ title: "Sketch · skate",+ modelId: "oss-mixed-media",+ op: "v2v",+ inputs: { video: "/api/files/uploads/skate.mp4" },+ params: { startTime: 2, endTime: 7, fps: 8, aspectRatio: "auto", resolution: "1K", extra: { denoise: 0.82 } },+ });+ });++ it("cloud: cut → restyle (anchored on the preview) → the cut's own sound", () => {+ const plan = planMixed(input({ engine: "cloud", modelId: "ltx-2-3-restyle", anchor: "/api/files/outputs/still.png", extra: { preprocessor: "canny" } }));+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));+ expect(Object.keys(by)).toEqual(["cut", "render", "final"]);+ expect(by.cut.request).toMatchObject({ feature: "mixed-media-step", modelId: "trim-video", op: "trim", params: { startTime: 2, endTime: 7 } });+ expect(by.render).toMatchObject({+ after: ["cut"],+ chain: [{ slot: "video" }],+ request: { feature: "mixed-media-step", modelId: "ltx-2-3-restyle", inputs: { images: ["/api/files/outputs/still.png"] }, params: { generateAudio: false, extra: { preprocessor: "canny" } } },+ });+ expect(by.final).toMatchObject({ after: ["render", "cut"], chain: [{ slot: "video" }, { slot: "audio" }], request: { feature: "mixed-media", modelId: "merge-audio-video", op: "mux" } });+ const silent = planMixed(input({ engine: "cloud", modelId: "lucy-edit-pro", source: { url: "/api/files/x.mp4", hasAudio: false } }));+ expect(silent.final).toBe("render");+ expect(silent.steps[1].request).toMatchObject({ feature: "mixed-media", title: "Sketch · skate" });+ expect(silent.steps[1].request.inputs).toBeUndefined();+ });++ it("preview: one frame (open: the per-frame model; cloud: an edit of the grabbed frame)", () => {+ const open = planMixedPreview(input());+ expect(open.request).toMatchObject({ feature: "mixed-media-preview", modelId: "oss-mixed-media", params: { startTime: 2, fps: 8, extra: { frames: 1 } } });+ const cloud = planMixedPreview({ ...input({ engine: "cloud", modelId: "ltx-2-3-restyle" }), frameUrl: "/api/files/uploads/frame.png" });+ expect(cloud.request).toMatchObject({ modelId: "nano-banana-2", op: "edit", inputs: { images: ["/api/files/uploads/frame.png"] } });+ expect(cloud.request.prompt).toMatch(/^Redraw this image as hand-drawn/);+ });+});diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.tsnew file mode 100644index 00000000..9491aae2--- /dev/null+++ b/tests/shorts-api.test.ts@@ -0,0 +1,288 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { Generation } from "@/lib/catalog/types";++vi.setConfig({ testTimeout: 120_000 });++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-shorts-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const { saveFile } = await import("@/server/storage");+const { db } = await import("@/server/db");+const shorts = await import("@/server/shorts");+const mixed = await import("@/server/mixed-media");+const sessionsRoute = await import("@/app/api/shorts/sessions/route");+const sessionRoute = await import("@/app/api/shorts/sessions/[id]/route");+const regenRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/route");+const primaryRoute = await import("@/app/api/shorts/sessions/[id]/segments/[index]/primary/route");+const stitchRoute = await import("@/app/api/shorts/sessions/[id]/stitch/route");+const estimateRoute = await import("@/app/api/shorts/estimate/route");+const presetsRoute = await import("@/app/api/shorts/presets/route");+const mixedRoute = await import("@/app/api/mixed-media/route");+const mixedPreviewRoute = await import("@/app/api/mixed-media/preview/route");+const mixedEstimateRoute = await import("@/app/api/mixed-media/estimate/route");++const json = (method: string, body?: unknown) =>+ new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) }) as never;++let clip = "";+let png = "";++beforeAll(() => {+ setSetting("demoMode", "auto");+ // A 12 s, 16 fps clip with a sound track.+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "beach day.mp4" }).url;+ png = saveFile({ data: Buffer.from("89504e470d0a1a0a", "hex"), contentType: "image/png", source: "upload" }).url;+});+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++async function settle(id: string, ms = 90_000): Promise<Generation> {+ const end = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++const dependsOn = (id: string) => {+ const v = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;+ return !v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v];+};++const body = (over: Record<string, unknown> = {}) => ({+ engine: "cloud",+ presetId: "shorts-claymation",+ source: { url: clip, name: "beach day.mp4" },+ range: { start: 0, end: 12 },+ aspectRatio: "9:16",+ language: "auto",+ ...over,+});++describe("Shorts sessions", () => {+ it("reads the clip's length, frame rate and sound from its header", async () => {+ const info = await shorts.probeSource(clip);+ expect(info.duration).toBeCloseTo(12, 1);+ expect(info.fps).toBeCloseTo(16, 1);+ expect(info.hasAudio).toBe(true);+ await expect(shorts.probeSource("https://example.com/x.mp4")).rejects.toThrow(/Upload the clip first/);+ });++ it("estimates before anything is made: demo is free, a connected provider is priced per second", async () => {+ const demo = await (await estimateRoute.POST(json("POST", body({ source: { url: "/api/files/placeholder.mp4", duration: 12 } })))).json();+ expect(demo).toMatchObject({ demo: true, costUsd: 0, segments: 2, seconds: 12 });+ setSetting("falKey", "test-key");+ try {+ const est = await shorts.estimateShorts(body({ source: { url: clip, duration: 12 } }) as never);+ expect(est.demo).toBe(false);+ // Gemini Omni Flash at $0.03/s: two 6 s segments, plus the cuts, the join and the soundtrack (≈ free).+ expect(est.costUsd!).toBeGreaterThanOrEqual(0.36);+ expect(est.costUsd!).toBeLessThan(0.4);+ expect(est.perSegmentUsd!).toBeGreaterThanOrEqual(0.18);+ expect(est.perSegmentUsd!).toBeLessThan(0.2);+ expect(est.notes.join(" ")).toMatch(/keeps your clip's shape/);+ } finally {+ setSetting("falKey", "");+ }+ const bad = await estimateRoute.POST(json("POST", body({ range: { start: 0, end: 2 } })));+ expect(bad.status).toBe(400);+ expect((await bad.json()).error).toBe("Select at least 4 seconds");+ });++ let sessionId = "";++ it("creates a cloud session: segments cut and restyled, stitched under the original sound", async () => {+ const res = await sessionsRoute.POST(json("POST", body()));+ expect(res.status).toBe(201);+ const s = await res.json();+ sessionId = s.id;+ expect(s).toMatchObject({ title: "Claymation · beach day", engine: "cloud", range: { start: 0, end: 12 }, settings: { aspectRatio: "9:16", modelId: "gemini-omni-flash", maxRefs: 0, resolution: "720p" } });+ expect(s.source).toMatchObject({ hasAudio: true });+ expect(s.segments).toHaveLength(2);+ expect(s.segments.map((g: { start: number; end: number }) => [g.start, g.end])).toEqual([+ [0, 6],+ [6, 12],+ ]);+ const [a, b] = s.segments;+ expect(a.primary).toBe(a.takes[0].look);+ expect(dependsOn(a.takes[0].look)).toEqual([a.takes[0].cut]);+ const look = gens.getGeneration(a.takes[0].look)!;+ expect(look).toMatchObject({ modelId: "gemini-omni-flash", op: "v2v", feature: "shorts" });+ expect(look.request.step?.label).toBe("Segment 1 of 2 · restyle");+ const stitch = s.stitches[0];+ const final = gens.getGeneration(stitch.final)!;+ expect(final).toMatchObject({ modelId: "merge-audio-video", op: "mux" });+ // The whole clip: the upload carries the sound; the join waits for both restyles.+ expect(final.request.inputs?.audio).toBe(clip);+ const join = stitch.ids.find((id: string) => gens.getGeneration(id)!.op === "concat");+ expect(dependsOn(join)).toEqual([a.takes[0].look, b.takes[0].look]);+ expect(dependsOn(stitch.final)).toEqual([join]);+ expect(await settle(stitch.final)).toMatchObject({ status: "succeeded" });+ });++ it("returns the session with its generations, and lists it in History", async () => {+ // (GET handlers call connection(), which needs a request scope: read through the server module.)+ const s = shorts.getSession(sessionId);+ expect(Object.keys(s.generations).length).toBe(6);+ expect(shorts.regenerateCost(s)).toBe(0);+ const list = shorts.listSessions();+ expect(list[0]).toMatchObject({ id: sessionId, lookName: "Claymation", segments: 2, seconds: 12, status: "ready" });+ expect(list[0].cover!.op).toBe("mux");+ });++ it("regenerates a segment, picks the new take and stitches again", async () => {+ const res = await regenRoute.POST(json("POST"), params({ id: sessionId, index: "1" }));+ expect(res.status).toBe(201);+ const s = await res.json();+ const seg = s.segments[1];+ expect(seg.takes).toHaveLength(2);+ // The first take is fine, so it stays the chosen one until the user picks.+ expect(seg.primary).toBe(seg.takes[0].look);+ const fresh = seg.takes[1].look;+ expect(gens.getGeneration(fresh)!.request.params?.seed).toEqual(expect.any(Number));+ await settle(fresh);+ const picked = await (await primaryRoute.POST(json("POST", { generationId: fresh }), params({ id: sessionId, index: "1" }))).json();+ expect(picked.segments[1].primary).toBe(fresh);+ const wrong = await primaryRoute.POST(json("POST", { generationId: "nope" }), params({ id: sessionId, index: "1" }));+ expect(wrong.status).toBe(400);+ const st = await (await stitchRoute.POST(json("POST"), params({ id: sessionId }))).json();+ expect(st.stitches).toHaveLength(2);+ const last = st.stitches[1];+ expect(last.clips).toEqual([st.segments[0].primary, fresh]);+ const join = gens.getGeneration(last.ids[0])!;+ // Finished takes are joined by file: nothing to wait for.+ expect(join.request.inputs?.videos).toHaveLength(2);+ expect(dependsOn(join.id)).toEqual([]);+ expect(await settle(last.final)).toMatchObject({ status: "succeeded", op: "mux" });+ });++ it("won't stitch while a segment is still rendering", async () => {+ const s = shorts.regenerateSegment(sessionId, 0);+ const take = s.segments[0].takes.at(-1)!.look;+ shorts.makePrimary(sessionId, 0, take);+ const res = await stitchRoute.POST(json("POST"), params({ id: sessionId }));+ expect(res.status).toBe(409);+ expect((await res.json()).error).toBe("Segment 1 is still rendering");+ await settle(take);+ });++ it("trims: the segments start at the selection and the sound is the source cut to it", async () => {+ const s = await shorts.createSession(body({ range: { start: 1.5, end: 9.5 } }) as never);+ expect(s.segments).toHaveLength(1);+ expect(s.segments[0]).toMatchObject({ start: 1.5, end: 9.5 });+ const final = gens.getGeneration(s.stitches[0].final)!;+ const deps = dependsOn(final.id).map((id) => gens.getGeneration(id)!);+ expect(deps.map((g) => g.op)).toEqual(["v2v", "trim"]);+ expect(deps[1].request.params).toMatchObject({ startTime: 1.5, endTime: 9.5 });+ // The mux takes the cut clip's soundtrack (an audio slot fed by a video).+ expect(await settle(final.id)).toMatchObject({ status: "succeeded" });+ });++ it("runs the open engine: segment (+ first frame) → Qwen first-frame restyle → Wan VACE → join → soundtrack", async () => {+ const s = await shorts.createSession(body({ engine: "open" }) as never);+ expect(s.settings.modelId).toBe("oss-wan22-vace-restyle");+ expect(s.segments.map((g) => g.frames)).toEqual([65, 65, 61]);+ const take = s.segments[2].takes[0];+ expect(gens.getGeneration(take.cut)).toMatchObject({ modelId: "oss-segment", op: "trim" });+ expect(gens.getGeneration(take.frame!)).toMatchObject({ modelId: "oss-qwen-edit", op: "edit" });+ expect(dependsOn(take.look)).toEqual([take.cut, take.frame]);+ const final = await settle(s.stitches[0].final);+ expect(final).toMatchObject({ status: "succeeded", modelId: "oss-mux" });+ // The first-frame restyle got the segment's first frame.+ const frame = gens.getGeneration(take.frame!)!;+ expect(frame.status).toBe("succeeded");+ expect(frame.request.inputs?.images?.[0]).toMatch(/^\/api\/files\//);+ });++ it("custom presets: references go to models that take them", async () => {+ const res = await presetsRoute.POST(json("POST", { description: "dusty desert film", references: [png, png] }));+ expect(res.status).toBe(201);+ const p = await res.json();+ expect(p).toMatchObject({ name: "Dusty desert film", references: [png] });+ expect(shorts.listCustomPresets().map((x) => x.id)).toContain(p.id);+ const kling = await shorts.createSession(body({ presetId: p.id, modelId: "kling-o3-4k-edit", range: { start: 0, end: 8 } }) as never);+ expect(kling.settings.maxRefs).toBe(4);+ const look = gens.getGeneration(kling.segments[0].takes[0].look)!;+ expect(look.request.inputs?.images).toEqual([png]);+ expect(look.request.prompt).toMatch(/^Restyle this video as the look of the reference images: dusty desert film\./);+ const est = await shorts.estimateShorts(body({ presetId: p.id }) as never);+ expect(est.refsSent).toBe(0);+ expect(est.notes[0]).toMatch(/restyles from words only/);+ });++ it("respects the engine mode", async () => {+ setSetting("engineMode", "open");+ try {+ const res = await sessionsRoute.POST(json("POST", body()));+ expect(res.status).toBe(422);+ expect((await res.json()).error).toMatch(/open-source models only/);+ } finally {+ setSetting("engineMode", "both");+ }+ });++ it("deletes a session and moves its videos to the Trash", async () => {+ const ids = shorts.sessionIds(shorts.getSession(sessionId));+ const res = await sessionRoute.DELETE(json("DELETE"), params({ id: sessionId }));+ expect((await res.json()).trashed).toBe(ids.length);+ expect(gens.getGeneration(ids[0])).toBeNull();+ expect(() => shorts.getSession(sessionId)).toThrow(/no longer exists/);+ });+});++describe("Mixed Media renders", () => {+ const mm = (over: Record<string, unknown> = {}) => ({+ engine: "open",+ presetId: "mixed-sketch",+ values: { ink: "#c1121f", intensity: "bold" },+ source: { url: clip, name: "skate.mp4" },+ range: { start: 2, end: 7 },+ fps: 24,+ resolution: "1K",+ ...over,+ });++ it("estimates frames as floor(seconds × fps) and caps the frame rate at the clip's", async () => {+ const est = await (await mixedEstimateRoute.POST(json("POST", mm({ source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 16 } })))).json();+ expect(est).toMatchObject({ frames: 80, fps: 16, demo: true, costUsd: 0, previewUsd: 0 });+ });++ it("renders on the open engine in one per-frame job", async () => {+ const res = await mixedRoute.POST(json("POST", mm()));+ expect(res.status).toBe(201);+ const { final, items } = await res.json();+ expect(items).toHaveLength(1);+ expect(final).toMatchObject({ modelId: "oss-mixed-media", feature: "mixed-media", request: { title: "Sketch · skate" } });+ expect(final.request.params).toMatchObject({ startTime: 2, endTime: 7, fps: 16, extra: { denoise: 0.82 } });+ expect(final.request.prompt).toMatch(/deep red \(#C1121F\) ink/);+ expect(await settle(final.id)).toMatchObject({ status: "succeeded" });+ });++ it("renders on the cloud: cut → restyle anchored on the preview still → the cut's sound", async () => {+ const preview = await (await mixedPreviewRoute.POST(json("POST", mm({ engine: "cloud", frameUrl: png })))).json();+ expect(preview).toMatchObject({ modelId: "nano-banana-2", op: "edit", feature: "mixed-media-preview" });+ const still = await settle(preview.id);+ const anchor = still.outputs[0].url;+ const { final, items } = await mixed.createMixed(mm({ engine: "cloud", anchor }) as never);+ expect(items.map((g) => g.modelId)).toEqual(["trim-video", "ltx-2-3-restyle", "merge-audio-video"]);+ expect(items[1].request.inputs?.images).toEqual([anchor]);+ expect(items[1].request.params?.extra).toEqual({ preprocessor: "canny" });+ expect(dependsOn(final.id)).toEqual([items[1].id, items[0].id]);+ expect(await settle(final.id)).toMatchObject({ status: "succeeded", feature: "mixed-media" });+ });++ it("asks for a grabbed frame before a cloud preview", async () => {+ const res = await mixedPreviewRoute.POST(json("POST", mm({ engine: "cloud" })));+ expect(res.status).toBe(400);+ expect((await res.json()).error).toMatch(/Couldn't grab a frame/);+ });+});diff --git a/tests/shorts.test.ts b/tests/shorts.test.tsnew file mode 100644index 00000000..675ecdcc--- /dev/null+++ b/tests/shorts.test.ts@@ -0,0 +1,297 @@+import { describe, expect, it } from "vitest";+import { getModel } from "@/lib/catalog";+import {+ chainState,+ customPresetName,+ firstFramePrompt,+ formatSeconds,+ joinGroups,+ lookFromCustom,+ lookFromPreset,+ planCloudSegments,+ planOpenSegments,+ planShorts,+ planStitch,+ planTake,+ rangeProblem,+ restylePrompt,+ segmentPrompt,+ SHORTS,+ SHORTS_LANGUAGES,+ SHORTS_MODELS,+ SHORTS_PRESETS,+ SHORTS_TOOLS,+ stitchCurrent,+ stitchSteps,+ takeSteps,+ wholeClip,+ type ShortsPlanInput,+} from "@/lib/catalog/shorts";+import { FX } from "@/lib/preset-cards";++const claymation = SHORTS_PRESETS.find((p) => p.name === "Claymation")!;+const kinetic = SHORTS_PRESETS.find((p) => p.name === "Kinetic Type")!;++const input = (over: Partial<ShortsPlanInput> = {}): ShortsPlanInput => ({+ engine: "cloud",+ title: "Claymation · beach",+ source: { url: "/api/files/uploads/beach.mp4", duration: 30, hasAudio: true },+ range: { start: 0, end: 30 },+ look: lookFromPreset(claymation),+ aspectRatio: "9:16",+ language: "auto",+ modelId: "gemini-omni-flash",+ maxRefs: 0,+ ...over,+});++describe("Shorts presets and catalog", () => {+ it("has Higgsfield's 44 presets with Fuobe's own descriptions and looks", () => {+ expect(SHORTS_PRESETS).toHaveLength(44);+ expect(new Set(SHORTS_PRESETS.map((p) => p.id)).size).toBe(44);+ expect(new Set(SHORTS_PRESETS.map((p) => p.name)).size).toBe(44);+ for (const p of SHORTS_PRESETS) {+ expect(p.description.length).toBeGreaterThan(10);+ expect(p.description.length).toBeLessThanOrEqual(100);+ expect(p.look.length).toBeGreaterThan(30);+ expect(FX).toContain(p.fx);+ expect(p.hue).toBeGreaterThanOrEqual(0);+ expect(p.hue).toBeLessThan(360);+ }+ // The type presets put words on screen, so the language applies to them.+ expect(SHORTS_PRESETS.filter((p) => p.type).map((p) => p.name)).toEqual(["Sticker Type", "Balloon Type", "Bold Caption", "Kinetic Type", "Neon Type", "Stacked Type"]);+ });++ it("lists auto-detect plus 33 languages and only real models", () => {+ expect(SHORTS_LANGUAGES).toHaveLength(33);+ for (const id of [...SHORTS_MODELS.cloud, ...SHORTS_MODELS.open, ...Object.values(SHORTS_TOOLS.cloud), ...Object.values(SHORTS_TOOLS.open)]) {+ if (typeof id === "number") continue;+ expect(getModel(id), id).toBeDefined();+ }+ expect(SHORTS_MODELS.cloud[0]).toBe("gemini-omni-flash");+ for (const id of SHORTS_MODELS.cloud) expect(getModel(id)!.routes.some((r) => r.op === "v2v"), id).toBe(true);+ });++ it("names a custom preset from its description, or numbers it", () => {+ expect(customPresetName("warm slow film look with soft grain", 0)).toBe("Warm slow film");+ expect(customPresetName("", 2)).toBe("My look 3");+ const look = lookFromCustom({ id: "custom-1", name: "Mine", description: "dusty 70s film.", references: Array.from({ length: 12 }, (_, i) => `/api/files/r${i}.png`), createdAt: 0, updatedAt: 0 });+ expect(look.references).toHaveLength(10);+ expect(look.look).toBe("the look of the reference images: dusty 70s film");+ });+});++describe("Shorts prompts", () => {+ it("restyles the look and keeps the motion", () => {+ const p = restylePrompt(lookFromPreset(claymation));+ expect(p).toMatch(/^Restyle this video as stop-motion claymation/);+ expect(p).toMatch(/same people, faces, poses, motion, timing and camera moves; change only the look\.$/);+ expect(p).not.toMatch(/on-screen/);+ });++ it("writes on-screen words in the chosen language for type presets", () => {+ expect(restylePrompt(lookFromPreset(kinetic), "Spanish")).toMatch(/Any on-screen words are written in Spanish\.$/);+ expect(restylePrompt(lookFromPreset(kinetic), "auto")).toMatch(/written in the language spoken in the clip\.$/);+ expect(restylePrompt(lookFromPreset(kinetic), "auto", 2)).toMatch(/Match the style of the reference images\./);+ });++ it("restyles the first frame with references as images 2 and 3 (open engine)", () => {+ expect(firstFramePrompt(lookFromPreset(claymation), "auto", 0)).toMatch(/^Redraw image 1 as stop-motion claymation.*poses and expressions of image 1 exactly\.$/);+ expect(firstFramePrompt(lookFromPreset(claymation), "auto", 1)).toMatch(/Match the style, colours and textures of image 2\./);+ expect(firstFramePrompt(lookFromPreset(claymation), "auto", 2)).toMatch(/of images 2 and 3\./);+ expect(segmentPrompt(lookFromPreset(claymation))).toMatch(/^Stop-motion claymation: .*smooth natural motion\.$/);+ });+});++describe("Shorts segment planning", () => {+ it("cuts cloud selections into equal segments of at most 10 s", () => {+ expect(planCloudSegments({ start: 0, end: 10 })).toEqual([{ index: 0, start: 0, end: 10 }]);+ const five = planCloudSegments({ start: 0, end: 47 });+ expect(five).toHaveLength(5);+ for (const s of five) expect(s.end - s.start).toBeCloseTo(9.4, 3);+ const two = planCloudSegments({ start: 3, end: 13.5 });+ expect(two.map((s) => [s.start, s.end])).toEqual([+ [3, 8.25],+ [8.25, 13.5],+ ]);+ expect(planCloudSegments({ start: 0, end: 120 })).toHaveLength(12);+ });++ it("covers the selection back to back, never longer than the limit", () => {+ for (const [a, b] of [+ [0, 4],+ [1.3, 33.7],+ [5, 125],+ [0, 120],+ ]) {+ const segs = planCloudSegments({ start: a, end: b });+ expect(segs[0].start).toBe(a);+ expect(segs[segs.length - 1].end).toBe(b);+ segs.forEach((s, i) => {+ expect(s.end - s.start).toBeLessThanOrEqual(10.001);+ if (i) expect(s.start).toBe(segs[i - 1].end);+ });+ }+ });++ it("cuts open selections on whole frames: 4n+1 frames, at most 81, back to back", () => {+ const segs = planOpenSegments({ start: 0, end: 12 });+ // 192 frames at 16 fps → 3 segments of 65 + 65 + 61 frames (191: one frame dropped at the end).+ expect(segs.map((s) => s.frames)).toEqual([65, 65, 61]);+ expect(segs.map((s) => [s.start, s.end])).toEqual([+ [0, 4.063],+ [4.063, 8.125],+ [8.125, 11.938],+ ]);+ for (const [a, b] of [+ [0, 4],+ [2.3, 14.3],+ [0, 120],+ [7.77, 61.2],+ ]) {+ const s = planOpenSegments({ start: a, end: b });+ const total = Math.floor((b - a) * 16 + 1e-6);+ const used = s.reduce((n, x) => n + x.frames!, 0);+ expect(used).toBeLessThanOrEqual(total);+ expect(total - used).toBeLessThanOrEqual(3);+ for (const x of s) {+ expect((x.frames! - 1) % 4).toBe(0);+ expect(x.frames!).toBeLessThanOrEqual(81);+ // Frame-exact: start and end land on whole frames, and the span is the frame count.+ expect(Math.round((x.end - x.start) * 16)).toBe(x.frames);+ }+ s.forEach((x, i) => i && expect(x.start).toBe(s[i - 1].end));+ }+ expect(planOpenSegments({ start: 0, end: 120 })).toHaveLength(24);+ });++ it("groups joins evenly, never leaving a single clip", () => {+ expect(joinGroups(1, 4)).toEqual([[0]]);+ expect(joinGroups(2, 4)).toEqual([[0, 1]]);+ expect(joinGroups(5, 4)).toEqual([+ [0, 1, 2],+ [3, 4],+ ]);+ expect(joinGroups(24, 4)).toHaveLength(6);+ expect(joinGroups(12, 24)).toEqual([Array.from({ length: 12 }, (_, i) => i)]);+ for (let n = 2; n <= 30; n++) for (const g of joinGroups(n, 4)) expect(g.length).toBeGreaterThanOrEqual(2);+ });++ it("checks the selection", () => {+ expect(rangeProblem({ start: 0, end: 3 })).toBe("Select at least 4 seconds");+ expect(rangeProblem({ start: 0, end: 130 })).toBe("Select up to 2 minutes");+ expect(rangeProblem({ start: 5, end: 15 }, 12)).toBe("The selection runs past the end of the clip");+ expect(rangeProblem({ start: 2, end: 2 })).toBe("Pick a part of the clip");+ expect(rangeProblem({ start: 10, end: 130 }, 200)).toBe(null);+ expect(wholeClip({ start: 0, end: 30 }, 30.02)).toBe(true);+ expect(wholeClip({ start: 1, end: 30 }, 30)).toBe(false);+ expect(formatSeconds(75.25)).toBe("1:15.2");+ expect(formatSeconds(9)).toBe("0:09");+ });+});++describe("Shorts pipeline shape", () => {+ it("cloud: cut → restyle per segment, one join, then the original sound from the upload", () => {+ const plan = planShorts(input());+ expect(plan.segments).toHaveLength(3);+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));+ expect(Object.keys(by)).toEqual(["cut0", "look0", "cut1", "look1", "cut2", "look2", "join", "final"]);+ expect(by.cut1.request).toMatchObject({ modelId: "trim-video", op: "trim", inputs: { video: "/api/files/uploads/beach.mp4" }, params: { startTime: 10, endTime: 20 } });+ expect(by.look1).toMatchObject({ after: ["cut1"], chain: [{ slot: "video" }], request: { modelId: "gemini-omni-flash", op: "v2v", params: { aspectRatio: "9:16", duration: 10 } } });+ expect(by.look1.request.inputs).toBeUndefined();+ expect(by.join).toMatchObject({ after: ["look0", "look1", "look2"], request: { modelId: "join-clips", op: "concat" } });+ expect(by.join.chain).toHaveLength(3);+ // The whole clip was used: the upload itself carries the sound.+ expect(by.final).toMatchObject({ after: ["join"], chain: [{ slot: "video" }], request: { modelId: "merge-audio-video", op: "mux", inputs: { audio: "/api/files/uploads/beach.mp4" }, title: "Claymation · beach" } });+ expect(plan.final).toBe("final");+ for (const s of plan.steps) expect(s.request).toMatchObject({ feature: "shorts", batchTitle: "Claymation · beach" });+ expect(by.look2.request.step).toEqual({ label: "Segment 3 of 3 · restyle", index: 2, of: 3 });+ });++ it("cloud: a trimmed selection takes its sound from the source cut to the same window", () => {+ const plan = planShorts(input({ range: { start: 4, end: 12 } }));+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));+ expect(plan.segments).toHaveLength(1);+ expect(by.join).toBeUndefined();+ expect(by.sound.request).toMatchObject({ modelId: "trim-video", params: { startTime: 4, endTime: 12 } });+ expect(by.final).toMatchObject({ after: ["look0", "sound"], chain: [{ slot: "video" }, { slot: "audio" }] });+ expect(by.final.request.inputs).toBeUndefined();+ });++ it("silent clips skip the soundtrack; one silent segment is the short itself", () => {+ const silent = planShorts(input({ source: { url: "/api/files/x.mp4", duration: 30, hasAudio: false } }));+ expect(silent.steps.map((s) => s.key)).not.toContain("final");+ expect(silent.final).toBe("join");+ expect(silent.steps.find((s) => s.key === "join")!.request.title).toBe("Claymation · beach");+ const one = planShorts(input({ source: { url: "/api/files/x.mp4", duration: 8, hasAudio: false }, range: { start: 0, end: 8 } }));+ expect(one.steps.map((s) => s.key)).toEqual(["cut0", "look0"]);+ expect(one.final).toBe("look0");+ });++ it("sends references only to cloud models that take them, up to their limit", () => {+ const refs = Array.from({ length: 6 }, (_, i) => `/api/files/ref${i}.png`);+ const look = { ...lookFromPreset(claymation), references: refs };+ const words = planTake(input({ look }), { index: 0, start: 0, end: 5 }, 1);+ expect(words.steps[1].request.inputs).toBeUndefined();+ const kling = planTake(input({ look, modelId: "kling-o3-4k-edit", maxRefs: 4 }), { index: 0, start: 0, end: 5 }, 1);+ expect(kling.steps[1].request.inputs?.images).toEqual(refs.slice(0, 4));+ expect(kling.steps[1].request.prompt).toMatch(/Match the style of the reference images/);+ });++ it("open: segment (with its first frame) → restyled first frame → Wan VACE, joined 4 at a time", () => {+ const refs = ["/api/files/a.png", "/api/files/b.png", "/api/files/c.png"];+ const plan = planShorts(input({ engine: "open", modelId: "oss-wan22-vace-restyle", maxRefs: 2, range: { start: 0, end: 30 }, look: { ...lookFromPreset(claymation), references: refs } }));+ expect(plan.segments).toHaveLength(6);+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));+ expect(by.cut0.request).toMatchObject({ modelId: "oss-segment", op: "trim", params: { startTime: 0, fps: 16, aspectRatio: "9:16", resolution: "480p" } });+ expect(by.frame0).toMatchObject({ after: ["cut0"], chain: [{ slot: "images", position: "first" }], request: { modelId: "oss-qwen-edit", op: "edit", inputs: { images: refs.slice(0, 2) } } });+ expect(by.look0).toMatchObject({ after: ["cut0", "frame0"], chain: [{ slot: "video" }, { slot: "images" }], request: { modelId: "oss-wan22-vace-restyle", op: "v2v" } });+ // The restyle runs exactly as many frames as its segment.+ for (const s of plan.segments) expect(Math.round((by[`look${s.index}`].request.params!.duration as number) * 16)).toBe(s.frames);+ // 6 clips → two joins of 3, then one join of the two.+ const joins = plan.steps.filter((s) => s.request.op === "concat");+ expect(joins.map((j) => [j.key, j.after?.length])).toEqual([+ ["join-0-0", 3],+ ["join-0-1", 3],+ ["join", 2],+ ]);+ for (const j of joins) expect(j.request.modelId).toBe("oss-join-clips");+ expect(by.final).toMatchObject({ after: ["join"], request: { modelId: "oss-mux", op: "mux", inputs: { audio: "/api/files/uploads/beach.mp4" } } });+ });++ it("stitch again joins finished takes by file and keeps the sound step for a trimmed selection", () => {+ const st = planStitch(input({ range: { start: 2, end: 22 } }), [{ url: "/api/files/a.mp4" }, { url: "/api/files/b.mp4" }], "-s1");+ expect(st.steps.map((s) => s.key)).toEqual(["join-s1", "sound-s1", "final-s1"]);+ expect(st.steps[0].request.inputs).toEqual({ videos: ["/api/files/a.mp4", "/api/files/b.mp4"] });+ expect(st.steps[0].after).toBeUndefined();+ expect(st.final).toBe("final-s1");+ const single = planStitch(input({ source: { url: "/api/files/x.mp4", hasAudio: false } }), [{ url: "/api/files/a.mp4" }]);+ expect(single).toEqual({ steps: [], final: undefined });+ });++ it("knows when the stitch is out of date", () => {+ const s = { segments: [{ primary: "a" }, { primary: "b" }], stitches: [{ clips: ["a", "b"] }] } as never;+ expect(stitchCurrent(s)).toBe(true);+ expect(stitchCurrent({ segments: [{ primary: "a" }, { primary: "c" }], stitches: [{ clips: ["a", "b"] }] } as never)).toBe(false);+ expect(stitchCurrent({ segments: [{ primary: "a" }], stitches: [] } as never)).toBe(false);+ });++ it("sums a chain of steps into one state with the failing step's own error", () => {+ const g = (status: string, extra: Record<string, unknown> = {}) => ({ id: Math.random().toString(), status, ...extra }) as never;+ const gens: Record<string, never> = { c: g("succeeded"), f: g("running", { progress: 0.5 }), l: g("queued") };+ expect(chainState(takeSteps({ cut: "c", frame: "f", look: "l" }, gens))).toEqual({ status: "working", label: "Restyling the first frame", progress: 0.5 });+ const failed = { c: g("failed", { error: "The start time is past the end of the clip" }), l: g("failed", { error: "An earlier step didn't finish" }) };+ expect(chainState(takeSteps({ cut: "c", look: "l" }, failed))).toMatchObject({ status: "failed", label: "Cutting the segment failed", error: "The start time is past the end of the clip" });+ expect(chainState(takeSteps({ cut: "c", look: "gone" }, gens))).toMatchObject({ status: "gone" });+ expect(chainState(takeSteps({ cut: "c", look: "c" }, gens))).toMatchObject({ status: "done", progress: 1 });+ const st = stitchSteps({ ids: ["j", "s"], final: "m" }, { j: g("succeeded", { op: "concat" }), s: g("succeeded", { op: "trim" }), m: g("running", { op: "mux", progress: 0.2 }) });+ expect(st.map((x) => x.label)).toEqual(["Stitching the segments", "Cutting the original sound", "Putting the sound back"]);+ expect(chainState(st).progress).toBeCloseTo((2 + 0.2) / 3);+ });++ it("limits are Higgsfield's", () => {+ expect(SHORTS.minSeconds).toBe(4);+ expect(SHORTS.maxSeconds).toBe(120);+ expect(SHORTS.maxBytes).toBe(200 * 1024 * 1024);+ });+});diff --git a/tests/trim-range.test.ts b/tests/trim-range.test.tsnew file mode 100644index 00000000..d8e56af3--- /dev/null+++ b/tests/trim-range.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";+import { clampRange, clock, initialRange, moveRange, setEdge, thumbTimes, trimHint } from "@/lib/trim-range";++const L = { duration: 30, min: 4, max: 10 };++describe("video trimmer arithmetic", () => {+ it("starts with as much of the clip as allowed", () => {+ expect(initialRange(30, 10)).toEqual({ startTime: 0, endTime: 10 });+ expect(initialRange(7.25)).toEqual({ startTime: 0, endTime: 7.25 });+ expect(initialRange(3, 10)).toEqual({ startTime: 0, endTime: 3 });+ });++ it("moves one edge without moving the other, stopping at min and max length", () => {+ const r = { startTime: 5, endTime: 12 };+ expect(setEdge(r, "start", 1, L)).toEqual({ startTime: 2, endTime: 12 }); // max 10 s+ expect(setEdge(r, "start", 10, L)).toEqual({ startTime: 8, endTime: 12 }); // min 4 s+ expect(setEdge(r, "end", 40, L)).toEqual({ startTime: 5, endTime: 15 });+ expect(setEdge(r, "end", 6, L)).toEqual({ startTime: 5, endTime: 9 });+ expect(setEdge(r, "start", -3, { duration: 30 })).toEqual({ startTime: 0, endTime: 12 });+ expect(setEdge(r, "end", Number.NaN, L)).toBe(r);+ });++ it("slides the window inside the clip, keeping its length", () => {+ const r = { startTime: 5, endTime: 12 };+ expect(moveRange(r, 3, L)).toEqual({ startTime: 8, endTime: 15 });+ expect(moveRange(r, 100, L)).toEqual({ startTime: 23, endTime: 30 });+ expect(moveRange(r, -100, L)).toEqual({ startTime: 0, endTime: 7 });+ // A window longer than allowed is cut to the max when slid.+ expect(clampRange({ startTime: 0, endTime: 25 }, L, "move")).toEqual({ startTime: 0, endTime: 10 });+ });++ it("handles clips shorter than the minimum", () => {+ expect(clampRange({ startTime: 0, endTime: 3 }, { duration: 3, min: 4, max: 10 }, "end")).toEqual({ startTime: 0, endTime: 3 });+ });++ it("asks for the right selection", () => {+ expect(trimHint({ duration: 30, min: 1, max: 10 })).toBe("Select a 10-second segment");+ expect(trimHint({ duration: 30, max: 15 })).toBe("Select a 15-second segment");+ expect(trimHint({ duration: 200, min: 4, max: 120 })).toBe("Select up to 2 minutes");+ expect(trimHint({ duration: 2.5, min: 4, max: 120 })).toBe("This clip is 2.5 s — it needs at least 4 seconds");+ expect(trimHint({ duration: 8, min: 1, max: 10 })).toBe(null);+ });++ it("spreads filmstrip frames over the clip and prints times", () => {+ expect(thumbTimes(10, 4)).toEqual([1.25, 3.75, 6.25, 8.75]);+ expect(thumbTimes(0, 4)).toEqual([]);+ expect(clock(65.34)).toBe("1:05.3");+ expect(clock(4)).toBe("0:04.0");+ });+});