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
Runs: a run's facts carry the length of the clip it follows
Adarsh8278750f05ae
diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 75be1f4c..7137cb7c 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -478,16 +478,25 @@ type Size = { width: number; height: number };const megapixelsOf = (s: Size) => Math.round((s.width * s.height) / 10_000) / 100;const positive = (v: unknown): number | null => ((typeof v === "number" || typeof v === "string") && Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : null);+/** The header of a request's input clip (inputs.video, else its first clip); null when there is none or it can't be read. */+function clipInfo(req: GenerationRequest) {+ const clip = req.inputs?.video ?? req.inputs?.videos?.[0];+ return clip ? (storedMedia(clip)?.info ?? null) : null;+}++/** The size of a request's input clip, from its file's header; null when it can't be read. */+function clipSize(req: GenerationRequest): Size | null {+ const info = clipInfo(req);+ return info?.width && info.height ? { width: info.width, height: info.height } : null;+}+/** The size of a request's first input picture (else clip), from its file's header; null when it can't be read. */function inputSize(req: GenerationRequest): Size | null {const i = req.inputs ?? {};const picture = i.images?.[0] ?? i.endImage;const head = picture ? localHead(picture) : null;const still = head ? imageSize(head) : null;- if (still) return still;- const clip = i.video ?? i.videos?.[0];- const info = clip ? storedMedia(clip)?.info : null;- return info?.width && info.height ? { width: info.width, height: info.height } : null;+ return still ?? clipSize(req);}/** An upscale model's own factor, from its file's name (RealESRGAN_x4plus, 4x-UltraSharp: 4). */@@ -523,7 +532,9 @@ function workflowSize(req: GenerationRequest, endpoint: string, modelId: string)};const maxW = Number(manifest.limits?.maxWidth ?? Infinity);const maxH = Number(manifest.limits?.maxHeight ?? Infinity);- const src = inputSize(req);+ // Motion transfer crops its driving clip to the canvas, so the canvas takes the clip's shape (comfy-compose.ts followDriver).+ const driver = req.op === "motion-transfer" && b.video ? clipSize(req) : null;+ const src = driver ?? inputSize(req);if (b.width && b.height) {const [w, h] = [positive(extra.width), positive(extra.height)];if (w && h) return fitCanvas(w, h, manifest.limits);@@ -531,7 +542,7 @@ function workflowSize(req: GenerationRequest, endpoint: string, modelId: string)const asked = req.params?.aspectRatio ?? model?.defaults?.aspectRatio;const h3 = isH3Graph(manifest.id);// "auto" (or H3 from a still) keeps the input's shape when its header says it.- const follows = !asked || asked === "auto" || (h3 && !!b.image);+ const follows = !asked || asked === "auto" || (h3 && !!b.image) || !!driver;const shape = follows && src ? `${src.width}:${src.height}` : asked === "auto" ? undefined : asked;if (h3) return h3Canvas(shape);// The canvas the composer binds (its trained size, comfy.ts workflowCanvas); a crop after it makes the saved picture smaller.@@ -601,6 +612,97 @@ export function genjutsuSize(req: GenerationRequest): { seconds: number | null;return { seconds: positive(o.seconds), megapixels: canvas ? megapixelsOf({ width: canvas[0], height: canvas[1] }) : null };}+/**+ * Operations whose result is as long as the clip they follow (or the part of it a range keeps): the edits, swaps and+ * transfers of a clip, and the tools that copy, convert or enlarge one. A talking avatar is as long as its voice.+ */+const CLIP_LENGTH_OPS: ReadonlySet<string> = new Set([+ "v2v",+ "motion-transfer",+ "video-swap",+ "video-insert",+ "remove-object",+ "group-swap",+ "scene-edit",+ "face-fix-video",+ "picture-video",+ "tone-video",+ "lipsync",+ "dub",+ "relight-video",+ "restore-video",+ "reframe",+ "color-match",+ "captions",+ "mux",+ "composite",+ "bg-remove-video",+ "depth-video",+ "body-capture-video",+ "upscale-video",+ "interpolate",+ "sdr-to-hdr",+ "export-video",+ "trim",+]);++const r3 = (n: number) => Math.round(n * 1000) / 1000;++/**+ * The seconds a run makes whose result follows its input clip (CLIP_LENGTH_OPS) or, for a talking avatar or lip re-sync+ * that follows its voice, the voice, as the run reads it: the length the request states for its clip (params.sourceDuration: a studio's part, the composer's+ * read of the upload), else the header of the uploaded file, as the GPUs' own job size reads it; within the range the+ * request keeps where the run cuts one (params.startTime / endTime); slow motion stretched by its factor. A length the+ * request asks for wins where the run makes that length. Undefined for any other run, null when the clip's length can't be+ * read.+ */+export function clipRunSeconds(+ req: GenerationRequest,+ op: string,+ run: { modelId: string; providerId: string; workflow?: string | null },+): number | null | undefined {+ if (op !== "avatar" && !CLIP_LENGTH_OPS.has(op)) return undefined;+ const params: NonNullable<GenerationRequest["params"]> = req.params ?? {};+ // Does the run make the length or range its request names? On ComfyUI, a graph that binds them; on a hosted route, a+ // model with lengths to pick, or a route that sends them.+ const model = getModel(run.modelId);+ let binds: (key: string) => boolean;+ if (run.providerId === "comfyui") {+ let bindings: Record<string, unknown> = {};+ try {+ bindings = run.workflow && !run.workflow.includes("{") ? ((getWorkflow(run.workflow).manifest.bindings ?? {}) as Record<string, unknown>) : {};+ } catch {+ bindings = {};+ }+ binds = (key) => !!bindings[key];+ } else {+ const maps = (model?.routes ?? []).filter((r) => r.op === op).map((r) => (r.map ?? {}) as Record<string, unknown>);+ binds = (key) => maps.some((m) => !!m[key]);+ }+ const asked = positive(params.duration);+ const lengths = run.providerId !== "comfyui" && !!model?.options.durations?.length;+ if (asked && (lengths || binds("duration") || binds("numFrames") || binds("frames"))) return asked;+ // A talking avatar, and lip re-sync with no clip or on a graph that counts its frames, run as long as the voice+ // (comfy-compose.ts voiceLength); the length the request states is the voice's only for an avatar or with no clip.+ const voice = op === "avatar" || (op === "lipsync" && (!req.inputs?.video || (run.providerId === "comfyui" && binds("frames"))));+ let length = voice && req.inputs?.video ? null : positive(params.sourceDuration);+ if (!length) {+ const file = voice ? (req.inputs?.audio ?? req.inputs?.voiceAudio) : (req.inputs?.video ?? req.inputs?.videos?.[0]);+ const info = file ? storedMedia(file)?.info : null;+ length = positive(voice ? info?.duration : (info?.videoDuration ?? info?.duration));+ }+ if (!length) return asked ?? null;+ if (voice) return r3(length);+ // The part a range keeps: a trim's, or a graph or route that cuts the clip there.+ if (op === "trim" || binds("startTime") || binds("startFrame")) {+ const start = Math.min(length, Math.max(0, Number(params.startTime) || 0));+ const end = positive(params.endTime);+ length = Math.max(0, Math.min(length, end ?? length) - start);+ }+ if (op === "interpolate") length *= Math.max(1, Number(params.slowdown) || 1);+ return length > 0 ? r3(length) : null;+}+/*** A run's own step, then the other steps it makes beside it (a 2K take's finish), each model and operation once with its* count: the shape of RunFacts.steps.@@ -640,8 +742,10 @@ export function runFacts(// The graph an open-engine run resolves to, its options' variant picked as the pre-flight and the provider pick it.const graphs = p.model.engine === "open" && p.providerId === "comfyui" && endpoint ? loadIndex().workflows : null;const workflow = graphs && endpoint ? requestWorkflowId(endpoint, req, { op: p.op, gpu: p.gpu ?? undefined, h3: p.h3 ?? undefined, has: (id) => !!graphs[id] }).id : null;- // A Genjutsu run states its own length and canvas (genjutsuSize); every other run, as its request and workflow say.+ // A Genjutsu run states its own length and canvas (genjutsuSize); a run that follows a clip (or a voice) is as long as+ // it (clipRunSeconds); every other run, as its request and workflow say.const genjutsu = genjutsuSize(req);+ const clip = genjutsu?.seconds ? undefined : clipRunSeconds(req, p.op || req.op || "", { modelId: p.model.id, providerId: p.providerId, workflow: workflow ?? endpoint });return {place: "pool",model: p.model.id,@@ -655,7 +759,7 @@ export function runFacts(jobs: p.jobs,outputsPerJob: p.jobs > 0 ? Math.max(1, Math.round(p.outputs / p.jobs)) : 1,megapixels: genjutsu?.megapixels ?? requestMegapixels(req, kind, p.model.id, p.providerId === "comfyui" ? endpoint : undefined),- seconds: genjutsu?.seconds ?? req.params?.duration ?? (kind === "video" ? (model?.defaults?.duration ?? null) : null),+ seconds: genjutsu?.seconds ?? (clip !== undefined ? clip : (req.params?.duration ?? (kind === "video" ? (model?.defaults?.duration ?? null) : null))),fps: req.params?.fps ?? null,loras: p.loras.applied.length,inputs: inputCounts(req),diff --git a/tests/clip-run-facts.test.ts b/tests/clip-run-facts.test.tsnew file mode 100644index 00000000..57509a6f--- /dev/null+++ b/tests/clip-run-facts.test.ts@@ -0,0 +1,173 @@+import http from "node:http";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import type { GenerationRequest } from "@/lib/catalog/types";+import { listenOnFreePort, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++// A run whose result follows its input clip (motion transfer, a clip edit, a swap) is as long as that clip: the facts a+// run's price check and its hold send say the clip's seconds, read from the uploaded file's header, not a model's+// default or nothing.+const dir = tempDir("fuobe-clip-facts-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_MODERATION_URL;+globalThis.__fuobeTestDiskFree = 1e13;++const probe = http.createServer();+const comfyPort = await listenOnFreePort(probe);+await new Promise<void>((r) => probe.close(() => r()));+const comfy: FakeComfy = await startFakeComfy({ output: "video", delayMs: 0 }, comfyPort);+process.env.COMFYUI_URL = comfy.url;++const auth = await import("@/server/auth");+const uploadsRoute = await import("@/app/api/uploads/route");+const { resetRates } = await import("@/server/rate");+const billing = await import("@/server/billing");+const { clipRunSeconds, runFacts, runOnPool } = await import("@/server/hosted");+const { poolQuote, reservePool } = await import("@/server/hosted-run");+const { previewGeneration } = await import("@/server/generations");++/** A tiny MP4 header `seconds` long (ftyp + moov with one 1280×720 video trak), enough for the server's header read. */+function mp4(seconds: number): Buffer {+ const box = (type: string, ...body: Buffer[]) => {+ const data = Buffer.concat(body);+ const head = Buffer.alloc(8);+ head.writeUInt32BE(8 + data.length);+ head.write(type, 4, "latin1");+ return Buffer.concat([head, data]);+ };+ const mvhd = Buffer.alloc(100);+ mvhd.writeUInt32BE(1000, 12);+ mvhd.writeUInt32BE(seconds * 1000, 16);+ const tkhd = Buffer.alloc(84);+ tkhd.writeUInt32BE(0x10000, 40);+ tkhd.writeUInt32BE(0x10000, 56);+ tkhd.writeUInt32BE(1280 << 16, 76);+ tkhd.writeUInt32BE(720 << 16, 80);+ const mdhd = Buffer.alloc(24);+ mdhd.writeUInt32BE(1000, 12);+ mdhd.writeUInt32BE(seconds * 1000, 16);+ const hdlr = Buffer.alloc(24);+ hdlr.write("vide", 8, "latin1");+ const trak = box("trak", box("tkhd", tkhd), box("mdia", box("mdhd", mdhd), box("hdlr", hdlr)));+ return Buffer.concat([box("ftyp", Buffer.from("isom\0\0\0\0isomiso2mp41", "latin1")), box("moov", box("mvhd", mvhd), trak)]);+}++let fake: FakeBilling;+let a = "";+let cookie = "";+let clip30 = "";+let picture = "";++const headers = (extra: Record<string, string> = {}) => ({ cookie, host: "localhost:3000", ...extra });+const upload = async (bytes: Buffer, type: string, name: string) => {+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": type, "x-file-name": name, "content-length": String(bytes.length) }), body: new Uint8Array(bytes) }));+ expect(r.status).toBe(201);+ return ((await r.json()) as { url: string }).url;+};++const POLICY = { hosted: true, pool: {}, uploads: { image: true, video: true, audio: true }, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 70, maxSeconds: 700, keepDays: 7, spaceBytes: 7_000_000_000 }, ttlS: 0 };++beforeAll(async () => {+ fake = await startFakeBilling();+ fake.policy = POLICY;+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+ clip30 = await upload(mp4(30), "video/mp4", "dance.mp4");+ picture = await upload(TINY_PNG, "image/png", "me.png");+});+afterAll(async () => {+ globalThis.__fuobeTestDiskFree = undefined;+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ await fake.close();+ await comfy.close();+});+beforeEach(() => {+ resetRates();+ billing.resetBillingCache();+ fake.policy = POLICY;+});++/** The facts of a request as the price check plans it, read as the account. */+function factsOf(req: GenerationRequest) {+ const planned = runOnPool(a, () => previewGeneration(req));+ return runOnPool(a, () => runFacts(req, planned, "video"));+}++const motionLite = (): GenerationRequest => ({+ feature: "video",+ modelId: "fuobe-genjutsu-motion-lite",+ op: "motion-transfer",+ prompt: "",+ inputs: { images: [picture], video: clip30 },+ params: { resolution: "480p", extra: { steps: 4 } },+});++describe("a run that follows a clip carries the clip's length", () => {+ it("motion transfer Lite with a 30 s clip: 30 s, at the price check and at the hold", async () => {+ const account = auth.accountById(a)!;+ const req = motionLite();+ const before = fake.calls.length;+ const quoted = await poolQuote(account, req, undefined);+ expect(quoted?.planned?.model.id).toBe("fuobe-genjutsu-motion-lite");+ const quoteCall = fake.calls.slice(before).find((c) => c.path.split("?")[0] === "/v1/quote");+ expect(quoteCall, "the price check asked the service").toBeTruthy();+ expect((quoteCall!.body as { run: { seconds: number | null; op: string } }).run).toMatchObject({ seconds: 30, op: "motion-transfer" });++ const at = fake.calls.length;+ const held = await reservePool(account, req, quoted!.planned!, { amount: 7, priceVersion: "v7" }, false);+ expect(held.ok).toBe(true);+ const reserveCall = fake.calls.slice(at).find((c) => c.path.split("?")[0] === "/v1/reserve");+ expect((reserveCall!.body as { run: { seconds: number | null } }).run.seconds).toBe(30);+ });++ it("a length the composer read for the clip (params.sourceDuration) is the clip's length too", () => {+ const req = { ...motionLite(), inputs: { images: [picture], video: "https://example.com/elsewhere.mp4" }, params: { resolution: "480p", sourceDuration: 12.5 } };+ expect(clipRunSeconds(req, "motion-transfer", { modelId: req.modelId, providerId: "comfyui", workflow: "wan-animate2" })).toBe(12.5);+ });++ it("a length the graph doesn't make (a default left in the request) doesn't stand for the clip's", () => {+ expect(factsOf({ ...motionLite(), params: { resolution: "480p", duration: 5 } }).seconds).toBe(30);+ });++ it("the canvas follows the driving clip's shape", () => {+ // 1280 × 720 at 480p: Wan Animate's landscape canvas, not the picture's.+ expect(factsOf(motionLite()).megapixels).toBe(0.41);+ });++ it("a clip edit (v2v) and a character swap get the clip's length", () => {+ const v2v = factsOf({ feature: "video", modelId: "fuobe-genjutsu-restyle", op: "v2v", prompt: "oil paint", inputs: { video: clip30 }, params: { resolution: "480p" } });+ expect(v2v).toMatchObject({ op: "v2v", seconds: 30 });+ const swap = factsOf({ feature: "video", modelId: "fuobe-genjutsu-swap", op: "video-swap", prompt: "the dancer", inputs: { images: [picture], video: clip30 }, params: { resolution: "480p" } });+ expect(swap).toMatchObject({ op: "video-swap", seconds: 30 });+ // From a start time, the part from there to the clip's end (the swap's graph cuts the clip there).+ const later = factsOf({ feature: "video", modelId: "fuobe-genjutsu-swap", op: "video-swap", prompt: "the dancer", inputs: { images: [picture], video: clip30 }, params: { resolution: "480p", startTime: 10 } });+ expect(later.seconds).toBe(20);+ });++ it("a length the request asks for, where the run makes it, is kept", () => {+ const swap = factsOf({ feature: "video", modelId: "fuobe-genjutsu-swap", op: "video-swap", prompt: "the dancer", inputs: { images: [picture], video: clip30 }, params: { resolution: "480p", duration: 4 } });+ expect(swap.seconds).toBe(4);+ const t2v = factsOf({ feature: "video", modelId: "oss-wan22-14b-fast", op: "t2v", prompt: "a fox", params: { duration: 3 } });+ expect(t2v.seconds).toBe(3);+ });++ it("a picture run stays without seconds", () => {+ const req: GenerationRequest = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" };+ const planned = runOnPool(a, () => previewGeneration(req));+ expect(runOnPool(a, () => runFacts(req, planned, "image")).seconds).toBeNull();+ });++ it("another account's clip reads as unknown, never as its length", () => {+ const other = auth.createAccount("[email protected]", "long enough").id;+ const req = motionLite();+ const seconds = runOnPool(other, () => clipRunSeconds(req, "motion-transfer", { modelId: req.modelId, providerId: "comfyui", workflow: "wan-animate2" }));+ expect(seconds).toBeNull();+ });+});