Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

ComfyUI provider: FPS Boost's m and n from the clip's frame rate, export formats, HDR curves, EXR as a zip, upscaling in passes

Claude9960a7b08fc0
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 789d35d5..d937ded5 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,5 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
+import { FORMAT_INFO } from "@/lib/av/formats";
+import type { VideoFormat } from "@/lib/catalog/types";
import { createGenerations, listGenerations } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
import { SignatureSchema } from "@/server/palettes";
@@ -58,7 +60,7 @@ const RequestSchema = z.object({
// Round 4: clicked points, keyframe times, output formats, Ken Burns moves, crossfades, retiming, overlays, rigging.
points: z.array(z.object({ x: z.number(), y: z.number(), label: z.enum(["positive", "negative"]).optional() })).max(64).optional(),
keyframeTimes: z.array(z.number().min(0).max(600)).max(10).optional(),
- format: z.enum(["h264", "h265_10bit", "prores_422_hq", "prores_4444", "ffv1", "exr"]).optional(),
+ format: z.enum(Object.keys(FORMAT_INFO) as [VideoFormat, ...VideoFormat[]]).optional(),
zoomFrom: z.number().min(0.1).max(10).optional(),
zoomTo: z.number().min(0.1).max(10).optional(),
panFrom: Focus.optional(),
diff --git a/src/app/api/media/probe/route.ts b/src/app/api/media/probe/route.ts
new file mode 100644
index 00000000..7899918b
--- /dev/null
+++ b/src/app/api/media/probe/route.ts
@@ -0,0 +1,14 @@
+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 header (MP4 / MOV, WebM).
+ * The composer prices clip-length tools with it and says what comes out (Upscale hub: "24 → 60 fps").
+ */
+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/lib/av/video-finish.ts b/src/lib/av/video-finish.ts
new file mode 100644
index 00000000..3a42609c
--- /dev/null
+++ b/src/lib/av/video-finish.ts
@@ -0,0 +1,92 @@
+/**
+ * The open engine's video finishing tools (Upscale hub: FPS Boost, SDR to HDR, Export, chunked upscaling)
+ * as plain data and math, shared by the ComfyUI provider and its tests. See scripts/comfy/library.spec.mjs
+ * for the workflows (interpolate-rife-fps, video-export-pro-chunked, video-sdr-to-hdr(-exr),
+ * video-export-exr, upscale-video-*-chunked).
+ */
+import type { VideoFormat } from "@/lib/catalog/types";
+import { FORMAT_INFO, formatList } from "./formats";
+import { targetShortEdge } from "./upscale";
+
+/** VideoHelperSuite's format (and ProRes profile) for each export format (video-export-pro(-chunked)). */
+export const VHS_FORMAT: Partial<Record<VideoFormat, { format: string; profile?: string }>> = {
+ prores_422_hq: { format: "video/ProRes", profile: "hq" },
+ prores_4444: { format: "video/ProRes", profile: "4444" },
+ h265_10bit: { format: "video/h265-mp4" },
+ ffv1: { format: "video/ffv1-mkv" },
+ h264: { format: "video/h264-mp4" },
+};
+
+/** The formats the export graph writes (EXR has a graph of its own). */
+export const OPEN_EXPORT_FORMATS: VideoFormat[] = ["prores_422_hq", "prores_4444", "h265_10bit", "ffv1", "h264", "exr"];
+/** The open SDR to HDR: CreateVideo's colour space per format (EXR has a graph of its own). */
+export const HDR_COLOR_SPACE: Partial<Record<VideoFormat, string>> = { hlg_10bit: "HDR", pq_10bit: "HDR PQ" };
+export const OPEN_HDR_FORMATS: VideoFormat[] = ["hlg_10bit", "pq_10bit", "exr"];
+
+/** The workflow a format runs on, when it isn't the route's own (EXR frames). */
+export function exrWorkflow(op: "export-video" | "sdr-to-hdr"): string {
+ return op === "export-video" ? "video-export-exr" : "video-sdr-to-hdr-exr";
+}
+
+/** VHS values for an export, or the reason it can't be written on the open engine. */
+export function exportValues(format: VideoFormat | undefined): { format: string; profile?: string } {
+ const v = VHS_FORMAT[format ?? "prores_422_hq"];
+ if (!v) throw new Error(`Export on the open engine writes ${formatList(OPEN_EXPORT_FORMATS)}${format ? `, not ${FORMAT_INFO[format]?.short ?? format}` : ""}`);
+ return v;
+}
+
+/** CreateVideo's colour space for an HDR format, or the reason the open engine can't write it. */
+export function hdrColorSpace(format: VideoFormat | undefined): string {
+ const v = HDR_COLOR_SPACE[format ?? "hlg_10bit"];
+ if (!v) {
+ throw new Error(
+ `The open engine writes HDR as ${formatList(OPEN_HDR_FORMATS)}${format ? `, not ${FORMAT_INFO[format]?.short ?? format}` : ""} — ` +
+ "H.265 and ProRes HDR come from Topaz SDR to HDR on the cloud",
+ );
+ }
+ return v;
+}
+
+/** A clip's facts as the provider knows them from its header. */
+export interface ClipFacts {
+ width?: number;
+ height?: number;
+ fps?: number;
+ frames?: number;
+ duration?: number;
+}
+
+const FLOAT_RGB = 12; // bytes per pixel of a ComfyUI IMAGE (float32 RGB)
+/** What one meta-batch pass may hold in frames (decoded + worked + written). */
+export const PASS_BUDGET = 1.5 * 2 ** 30;
+
+/** The shorter edge a chunked upscale writes: params.resolution ("1080p" = 1080), else the graph's default. */
+export function upscaleShortSide(resolution: string | undefined, fallback = 1080): number {
+ return targetShortEdge(resolution) ?? fallback;
+}
+
+/**
+ * Frames per meta-batch pass so one pass holds about PASS_BUDGET of frames: the decoded frame, the model's
+ * output (`modelScale` × each side, ESRGAN 4) and the frame scaled to `shortSide`. SeedVR2 restores
+ * 4n+1 frames at a time, so its passes are 4n+1 long (`fourNPlusOne`). The graph's default when the size is unknown.
+ */
+export function framesPerPass(clip: ClipFacts, o: { shortSide?: number; modelScale?: number; fourNPlusOne?: boolean; min?: number; max?: number; fallback: number }): number {
+ if (!clip.width || !clip.height) return o.fallback;
+ const px = clip.width * clip.height;
+ const k = o.shortSide ? o.shortSide / Math.min(clip.width, clip.height) : 1;
+ const perFrame = FLOAT_RGB * px * (1 + (o.modelScale ?? 0) ** 2 + k * k);
+ let n = Math.floor(PASS_BUDGET / perFrame);
+ n = Math.max(o.min ?? 4, Math.min(o.max ?? 64, n));
+ if (o.fourNPlusOne) n = Math.max(5, Math.floor((n - 1) / 4) * 4 + 1);
+ return n;
+}
+
+/**
+ * Bytes a whole-clip graph holds (FPS Boost, HDR, EXR export decode the whole clip as float32 frames):
+ * `copies` frame-sized copies of every source frame. Undefined when the clip's size or length is unknown.
+ */
+export function wholeClipBytes(clip: ClipFacts, copies: number): number | undefined {
+ const frames = clip.frames ?? (clip.duration && clip.fps ? Math.round(clip.duration * clip.fps) : undefined);
+ if (!clip.width || !clip.height || !frames) return undefined;
+ return clip.width * clip.height * FLOAT_RGB * frames * copies;
+}
diff --git a/src/lib/comfy.ts b/src/lib/comfy.ts
index 0c4f585b..b581c043 100644
--- a/src/lib/comfy.ts
+++ b/src/lib/comfy.ts
@@ -59,7 +59,7 @@ export interface ManifestOutput {
/**
* What a text, image or 3D output is: timed caption cues, a plain transcript, the detected language, layers, a grid's sheet or tiles…
* Round 4: OCR "lines" (JSON, boxes 0–1000) and the "frame" the model saw, an EXR sequence's "frames", a whole-"scene" GLB and its
- * "depth" map, a Gaussian "splat", a reference video's style "brief".
+ * "depth" map, a Gaussian "splat", a reference video's style "brief". A "preview" is the clip shown for an EXR export (the frames ride along zipped).
*/
role?:
| "cues"
@@ -76,7 +76,8 @@ export interface ManifestOutput {
| "scene"
| "depth"
| "splat"
- | "brief";
+ | "brief"
+ | "preview";
}
export interface ManifestWorkflow {
@@ -520,6 +521,59 @@ export function bypassReference(wf: ComfyWorkflow, loaderId: string): ComfyWorkf
return out;
}
+/**
+ * Take a node out of the graph: whatever read its first output reads `input`'s link instead (FPS Boost
+ * without interpolation: Select Every Nth takes the frames straight). Nodes nothing reads any more (its
+ * model loader, its constants) go too, except output nodes (`keep`). Unchanged when `input` isn't a link.
+ */
+export function bypassNode(wf: ComfyWorkflow, nodeId: string, input: string, keep: string[] = []): ComfyWorkflow {
+ const src = wf[nodeId]?.inputs[input];
+ if (!isLinkValue(src)) return wf;
+ const out = cloneWorkflow(wf);
+ for (const n of Object.values(out)) for (const [k, v] of Object.entries(n.inputs)) if (isLinkValue(v) && v[0] === nodeId) n.inputs[k] = [...src];
+ delete out[nodeId];
+ return dropUnused(out, keep);
+}
+
+/** Remove nodes whose outputs nothing reads, over and over, keeping the output nodes `keep`. */
+export function dropUnused(wf: ComfyWorkflow, keep: string[]): ComfyWorkflow {
+ const out = cloneWorkflow(wf);
+ for (;;) {
+ const read = new Set(Object.values(out).flatMap((n) => Object.values(n.inputs).filter(isLinkValue).map((v) => v[0])));
+ const gone = Object.keys(out).filter((id) => !read.has(id) && !keep.includes(id));
+ if (!gone.length) return out;
+ for (const id of gone) delete out[id];
+ }
+}
+
+/**
+ * VHS meta-batch graphs: tag each job's VHS_BatchManager with an input of its own. ComfyUI caches a node
+ * whose inputs didn't change, so without it a job right after a failed or canceled meta-batch reuses the
+ * stale manager and silently loses frames (checked on the CPU server: 32 of 48 frames). VHS keeps inputs
+ * it doesn't declare (it adds its own "requeue" the same way).
+ */
+export function tagMetaBatch(wf: ComfyWorkflow, job: string): ComfyWorkflow {
+ if (!Object.values(wf).some((n) => n.class_type === "VHS_BatchManager")) return wf;
+ const out = cloneWorkflow(wf);
+ for (const n of Object.values(out)) if (n.class_type === "VHS_BatchManager") n.inputs.job = job;
+ return out;
+}
+
+/**
+ * A clip with no sound: VHS_LoadVideo fails ("failed to extract audio") once its audio output is read, so
+ * the links from that output (VHS_VideoCombine.audio) are dropped. Only for clips whose header says so.
+ */
+export function dropVhsAudio(wf: ComfyWorkflow): ComfyWorkflow {
+ const loaders = new Set(Object.entries(wf).filter(([, n]) => n.class_type === "VHS_LoadVideo").map(([id]) => id));
+ if (!loaders.size) return wf;
+ const out = cloneWorkflow(wf);
+ for (const n of Object.values(out)) {
+ const a = n.inputs.audio;
+ if (isLinkValue(a) && loaders.has(a[0]) && a[1] === 2) delete n.inputs.audio;
+ }
+ return out;
+}
+
/** Languages ComfyUI-QwenASR's subtitle node accepts (besides "auto"), by ISO 639 code. */
const ASR_LANGUAGES: Record<string, string> = {
zh: "Chinese", en: "English", yue: "Cantonese", ar: "Arabic", de: "German", fr: "French", es: "Spanish", pt: "Portuguese",
diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.ts
index 3f8df1fa..ec4b6985 100644
--- a/src/lib/media-probe.ts
+++ b/src/lib/media-probe.ts
@@ -4,7 +4,8 @@
* the bytes in memory; anything else (WebM, MKV, Ogg…) is "unknown" (null) and callers fall back to safe defaults.
*/
export interface MediaInfo {
- container: "mp4" | "wav" | "flac" | "mp3";
+ /** "webm": read by the server's WebM / Matroska reader (src/server/webm-probe.ts), for the ComfyUI uploads. */
+ container: "mp4" | "wav" | "flac" | "mp3" | "webm";
/** Seconds (the longest track). */
duration?: number;
/** Seconds of picture (the video track alone). */
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 39c7cc60..a3f52d20 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -30,6 +30,7 @@ import { provider } from "./providers";
import { probeComfy } from "./providers/comfyui";
import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";
import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
+import { mediaFacts } from "./media-facts";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
import { contentTypeFor, deleteAsset, readRef, saveFile } from "./storage";
@@ -335,7 +336,7 @@ function prepare(original: GenerationRequest) {
const providerId: ProviderId = demo ? "mock" : route.provider;
// A text step that runs on Ollama is free; only Claude costs money.
const free = demo || (route.provider === "llm" && !llmUsesClaude(route));
- return { req, plan, route, demo, providerId, cost: free ? 0 : estimateCost(plan.model, plan.params, 1) };
+ return { req, plan, route, demo, providerId, cost: free ? 0 : estimateCost(plan.model, plan.params, 1, plan.op) };
}
@@ -622,6 +623,19 @@ async function submit(
const f = await readRef(ref);
return adapter.prepareFile(f.data, f.contentType, f.name);
};
+ // The input clip's header (size, frame rate, length): upscalers that take a factor and frame-count routes read it.
+ let source: Pick<GenInput, "sourceSize" | "sourceFps" | "sourceDuration"> = {};
+ const prepVideo = async (ref?: string) => {
+ if (!ref) return undefined;
+ const f = await readRef(ref);
+ const facts = mediaFacts(f.data);
+ source = {
+ ...(facts.width && facts.height ? { sourceSize: { width: facts.width, height: facts.height } } : {}),
+ ...(facts.fps ? { sourceFps: facts.fps } : {}),
+ ...(facts.duration ? { sourceDuration: facts.duration } : {}),
+ };
+ return adapter.prepareFile(f.data, f.contentType, f.name);
+ };
const prepMask = async (ref?: string) => {
if (!ref) return undefined;
const f = await readRef(ref);
@@ -642,7 +656,7 @@ async function submit(
images: (await Promise.all((req.inputs?.images ?? []).map(prep))).filter(Boolean) as string[],
endImage: await prep(req.inputs?.endImage),
mask: await prepMask(req.inputs?.mask),
- video: await prep(req.inputs?.video),
+ video: await prepVideo(req.inputs?.video),
audio: await prep(req.inputs?.audio),
audio2: await prep(req.inputs?.audio2),
voiceAudio: await prep(req.inputs?.voiceAudio),
@@ -654,6 +668,8 @@ async function submit(
// Vary seeds across a batch so N jobs don't return N identical results.
seed: plan.params.seed !== undefined && plan.params.seed >= 0 ? plan.params.seed + index : undefined,
};
+ // What the caller said about the clip's length wins; the header fills the rest.
+ Object.assign(input, { ...source, ...(plan.params.sourceDuration !== undefined && { sourceDuration: plan.params.sourceDuration }) });
const res = await adapter.submit({ generationId: id, model: plan.model, route, input });
const now = Date.now();
const status = statusOf(id);
@@ -899,7 +915,31 @@ function inlineText(text: string | undefined, meta: Record<string, unknown> | un
return { text: text.slice(0, MAX_INLINE_TEXT), meta: { ...meta, truncated: true } };
}
+/**
+ * Extra files a result carries as links (meta.artifacts: LTX HDR's EXR zip, Higgsfield's fbx / zip) are kept
+ * too, so the Library never depends on a provider's expiring URL. A link that can't be fetched stays as it was.
+ */
+async function persistArtifacts(meta: Record<string, unknown> | undefined, generationId: string): Promise<Record<string, unknown> | undefined> {
+ const links = meta?.artifacts;
+ if (!links || typeof links !== "object" || Array.isArray(links)) return meta;
+ const kept: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(links as Record<string, unknown>)) {
+ kept[k] = v;
+ if (typeof v !== "string" || !/^(https?:|data:)/.test(v)) continue;
+ try {
+ const f = await readRef(v);
+ const name = /^https?:/.test(v) ? new URL(v).pathname.split("/").pop() || undefined : undefined;
+ const type = f.contentType === "application/octet-stream" ? contentTypeFor(name ?? "", f.contentType) : f.contentType;
+ kept[k] = saveFile({ data: f.data, contentType: type, name, source: "generation", generationId }).url;
+ } catch (e) {
+ console.warn(`[fuobe] could not keep the ${k} file of ${generationId}: ${(e as Error).message}`);
+ }
+ }
+ return { ...meta, artifacts: kept };
+}
+
async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {
+ const meta = await persistArtifacts(o.meta, generationId);
let data: Buffer;
let contentType = o.contentType;
if (!o.url && o.text !== undefined) {
@@ -928,7 +968,7 @@ async function persistOutput(o: RichOutput, generationId: string): Promise<Outpu
kind: asset.kind,
contentType: asset.contentType,
assetId: asset.id,
- ...inlineText(text, o.meta),
+ ...inlineText(text, meta),
...(o.draftId ? { draftId: o.draftId } : {}),
};
}
diff --git a/src/server/media-facts.ts b/src/server/media-facts.ts
new file mode 100644
index 00000000..acef1b06
--- /dev/null
+++ b/src/server/media-facts.ts
@@ -0,0 +1,30 @@
+import "server-only";
+import { probeMedia } from "@/lib/media-probe";
+import { probeWebm } from "./webm-probe";
+
+/** What a clip's header says: length, displayed size, frame rate and whether it has sound. */
+export interface SourceInfo {
+ duration?: number;
+ width?: number;
+ height?: number;
+ fps?: number;
+ hasAudio?: boolean;
+}
+
+/**
+ * The header facts of a clip in memory: MP4 / MOV first, then WebM / Matroska. A file neither reader
+ * knows comes back empty (callers fall back to the browser's numbers or safe defaults).
+ */
+export function mediaFacts(data: Uint8Array): SourceInfo {
+ let info: ReturnType<typeof probeMedia> = null;
+ try {
+ info = probeMedia(data);
+ } catch {
+ info = null;
+ }
+ if (!info) {
+ const webm = probeWebm(Buffer.from(data.buffer, data.byteOffset, data.byteLength));
+ return webm ? { duration: webm.duration, width: webm.width, height: webm.height, fps: webm.fps, hasAudio: webm.hasAudio } : {};
+ }
+ return { duration: info.videoDuration ?? info.duration, width: info.width, height: info.height, fps: info.fps, hasAudio: info.hasAudio };
+}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 5d58d128..e7e0dd58 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -8,9 +8,11 @@ import {
alphaBBox,
applyBindings,
asrLanguage,
+ bypassNode,
bypassReference,
computeDimensions,
computeFrames,
+ dropVhsAudio,
expandCaptionWorkflow,
explainComfyError,
injectLoras,
@@ -20,6 +22,7 @@ import {
randomSeed,
splitCueWords,
swatchPixels,
+ tagMetaBatch,
whisperLanguage,
type BindingKey,
type CaptionCue,
@@ -28,13 +31,17 @@ import {
type ManifestOutput,
type ManifestWorkflow,
} from "@/lib/comfy";
+import { fpsPlan } from "@/lib/av/fps";
import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";
+import { exportValues, exrWorkflow, framesPerPass, hdrColorSpace, upscaleShortSide, wholeClipBytes } from "@/lib/av/video-finish";
import { guessKind } from "@/lib/catalog/payload";
import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";
import { probeMedia, type MediaInfo } from "@/lib/media-probe";
import { getSetting } from "../settings";
import { decodePng, encodePng } from "../png";
-import { readRef } from "../storage";
+import { probeWebm } from "../webm-probe";
+import { adoptFile, readRef, scratchDir } from "../storage";
+import { zipToFile } from "../zip";
import { ProviderError, type ProviderAdapter, type RemoteOutput } from "./types";
export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");
@@ -275,6 +282,30 @@ async function withLayerBoxes(outputs: ComfyOutput[]): Promise<ComfyOutput[]> {
);
}
+/**
+ * An EXR export's frames (role "frames", one file per frame) are zipped into one stored file, one frame
+ * in memory at a time, and ride along on the preview clip as meta.artifacts.exr (as LTX HDR's EXR zip
+ * does on the cloud). Other outputs pass through.
+ */
+async function bundleFrames(outputs: ComfyOutput[], generationId: string): Promise<ComfyOutput[]> {
+ const frames = outputs.filter((o) => o.meta?.role === "frames");
+ if (!frames.length) return outputs;
+ const rest = outputs.filter((o) => o.meta?.role !== "frames");
+ const preview = rest.find((o) => o.kind === "video");
+ if (!preview) throw new ProviderError("The EXR export finished without its preview clip");
+ const dest = path.join(scratchDir(), `${generationId || nanoid(8)}-${nanoid(6)}.zip`);
+ async function* files() {
+ for (const [i, f] of frames.entries()) {
+ const res = await fetch(f.url, { headers: f.headers });
+ if (!res.ok) throw new ProviderError(`ComfyUI answered HTTP ${res.status} for EXR frame ${i + 1}`);
+ yield { name: `frame_${String(i + 1).padStart(5, "0")}.exr`, data: Buffer.from(await res.arrayBuffer()) };
+ }
+ }
+ await zipToFile(files(), dest);
+ const zip = adoptFile({ from: dest, contentType: "application/zip", name: "exr-frames.zip", source: "generation", generationId: generationId || undefined });
+ return rest.map((o) => (o === preview ? { ...o, meta: { ...o.meta, artifacts: { exr: zip.url }, frames: frames.length } } : o));
+}
+
// ---------------------------------------------------------------------------
// Reachability. Routing (chooseRoute) is synchronous, so the first check for a server URL is a blocking probe
// (a worker thread does the fetch); after that the cached result is refreshed in the background every 10 s.
@@ -336,6 +367,14 @@ function rememberMedia(name: string, info: MediaInfo) {
if (seen.size > 256) seen.delete(seen.keys().next().value!);
}
+/** A WebM / Matroska clip's header facts in MediaInfo's shape (src/server/webm-probe.ts). */
+function webmInfo(data: Buffer): MediaInfo | null {
+ const w = probeWebm(data);
+ if (!w) return null;
+ const frames = w.duration && w.fps ? Math.round(w.duration * w.fps) : undefined;
+ return { container: "webm", duration: w.duration, videoDuration: w.hasVideo ? w.duration : undefined, width: w.width, height: w.height, fps: w.fps, frames, hasVideo: w.hasVideo, hasAudio: w.hasAudio };
+}
+
/** The header facts of a file this server uploaded to ComfyUI (undefined for images and unreadable containers). */
export function mediaInfoFor(name: unknown): MediaInfo | undefined {
return typeof name === "string" ? globalThis.__fuobeComfyMedia?.get(name) : undefined;
@@ -406,6 +445,77 @@ function captionCues(input: GenInput, extra: Record<string, unknown>): CaptionCu
const seconds = (n: number) => (n >= 10 ? String(Math.round(n)) : String(Math.round(n * 10) / 10));
const GB = 2 ** 30;
+const clipFacts = (clip: MediaInfo | undefined) => ({ width: clip?.width, height: clip?.height, fps: clip?.fps, frames: clip?.frames, duration: clip?.videoDuration ?? clip?.duration });
+
+/** Frame rate assumed for FPS Boost's m / n when the clip's header can't be read (the graph still plays at the right speed). */
+const ASSUMED_FPS = 30;
+
+/**
+ * Values and graph edits for the Upscale hub's open tools, from the request and the clip's header:
+ * VHS format / profile (export), CreateVideo's colour space (HDR10 PQ or HLG), FPS Boost's multiplier m,
+ * selection n and slow motion (src/lib/av/fps.ts), the chunked upscalers' short side and pass size.
+ * `holds` = frame-sized copies of the whole clip the graph keeps in memory (for the RAM check).
+ */
+function videoFinishValues(manifest: ManifestWorkflow, input: GenInput, clip: MediaInfo | undefined, extra: Record<string, unknown>) {
+ const b = manifest.bindings;
+ const d = manifest.defaults;
+ const facts = clipFacts(clip);
+ const values: Partial<Record<BindingKey, unknown>> = {};
+ const out = { values, holds: 0, what: manifest.title, bypassInterpolation: false, dropSound: false };
+ try {
+ // Export: VideoHelperSuite's format and ProRes profile.
+ if (manifest.capability === "export-video" && b.format) {
+ const v = exportValues(input.format);
+ values.format = v.format;
+ if (v.profile) values.profile = v.profile;
+ }
+ // SDR to HDR: HLG or PQ (HDR10's curve).
+ if (manifest.capability === "sdr-to-hdr" && b.colorSpace) values.colorSpace = hdrColorSpace(input.format);
+ } catch (e) {
+ throw new ProviderError((e as Error).message);
+ }
+ if (manifest.capability === "sdr-to-hdr" || manifest.id === "video-export-exr") {
+ out.holds = 3;
+ out.what = manifest.capability === "sdr-to-hdr" ? "SDR to HDR on the open engine" : "EXR export on the open engine";
+ }
+ // FPS Boost: interpolate by m, keep every n-th frame (the graph computes the output frame rate itself).
+ if (b.every && b.multiplier) {
+ const target = input.targetFps;
+ const slowdown = Math.max(1, Math.round(input.slowdown ?? 1));
+ let m = Number(extra.multiplier ?? d.multiplier ?? 2);
+ let n = 1;
+ // m, n and the slow-motion factor go together: a stray params.extra value can't break the ratio.
+ for (const k of ["multiplier", "every", "slowdown"]) delete extra[k];
+ if (target) {
+ const plan = fpsPlan(clip?.fps && clip.fps > 0 ? clip.fps : ASSUMED_FPS, target, slowdown, Number(manifest.limits?.maxMultiplier ?? 16));
+ m = plan.multiplier;
+ n = plan.every;
+ } else m = Math.max(2, Math.min(Number(manifest.limits?.maxMultiplier ?? 16), Math.round(m * slowdown)));
+ // m 1 (a lower target, or one the clip's rate divides into): FrameInterpolate is linked out below, and the
+ // graph's frame-rate expression still reads m, so it gets the real 1.
+ values.multiplier = m;
+ values.every = n;
+ values.slowdown = slowdown;
+ out.bypassInterpolation = m < 2;
+ out.dropSound = slowdown > 1;
+ // The source frames, their copy with the last frame held, the interpolated ones (m per frame) and the kept ones.
+ out.holds = 2 + m + m / n;
+ out.what = "FPS Boost on the open engine";
+ }
+ // Chunked upscaling: the shorter edge asked for, and passes that hold about 1.5 GB of frames.
+ if (b.shortSide) {
+ const shortSide = upscaleShortSide(input.resolution, Number(d.shortSide ?? 1080));
+ values.shortSide = shortSide;
+ if (b.framesPerBatch && extra.framesPerBatch === undefined) {
+ const seedvr = /seedvr/i.test(manifest.id);
+ values.framesPerBatch = framesPerPass(facts, { shortSide, modelScale: seedvr ? 0 : 4, fourNPlusOne: seedvr, max: seedvr ? 33 : 64, fallback: Number(d.framesPerBatch ?? 16) });
+ }
+ } else if (b.framesPerBatch && manifest.capability === "export-video" && extra.framesPerBatch === undefined) {
+ values.framesPerBatch = framesPerPass(facts, { min: 8, max: 256, fallback: Number(d.framesPerBatch ?? 64) });
+ }
+ return out;
+}
+
/**
* Turn a canonical request into the exact ComfyUI prompt: picks the workflow variant, maps Fuobe's inputs
* onto the workflow's bindings (sizes, frames, trim times, languages, palettes, layers…), uploads files the
@@ -433,6 +543,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
}
// Soundtrack without a background stem: the single-track graph.
if (ctx.op === "mux" && !audio2 && !extra.audio2 && loadManifest().workflows.some((w) => w.id === `${endpoint}-replace`)) endpoint = `${endpoint}-replace`;
+ // EXR frames have graphs of their own (export, SDR to HDR).
+ if (input.format === "exr" && (ctx.op === "export-video" || ctx.op === "sdr-to-hdr") && loadManifest().workflows.some((w) => w.id === exrWorkflow(ctx.op as "export-video"))) {
+ endpoint = exrWorkflow(ctx.op);
+ }
const { manifest, workflow } = getWorkflow(endpoint);
const d = manifest.defaults;
@@ -533,6 +647,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
}
values.frames = frames;
}
+ // Video finishing (Upscale hub): export formats, HDR curves, FPS Boost's m / n, chunked upscaling.
+ const finish = videoFinishValues(manifest, input, clip, extra);
+ Object.assign(values, finish.values);
+
// Drawn motion paths (normalised to the start frame) → one pixel point per output frame (Wan-Move).
const paths = extra.motionPaths as MotionPaths | undefined;
delete extra.motionPaths;
@@ -616,9 +734,32 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
}
}
+ // Graphs that hold the whole clip in memory (FPS Boost, HDR, EXR): refuse what the server can't hold.
+ if (finish.holds) {
+ const need = wholeClipBytes(clipFacts(clip), finish.holds);
+ const budget = ((await ctx.serverRam?.()) ?? 16 * GB) / 2;
+ if (need && need > budget) {
+ throw new ProviderError(
+ `${finish.what} holds the whole clip in memory: this one needs about ${Math.ceil(need / GB)} GB of RAM and this ComfyUI can spare ${Math.floor(budget / GB)} GB. ` +
+ "Trim it first (Video tools → Trim)" + (ctx.op === "interpolate" ? ", or pick a lower frame rate" : ""),
+ );
+ }
+ }
+
const bound = applyBindings(graph, b, Object.fromEntries(Object.entries(values).filter(([k]) => !left.includes(k))));
if (bound.missing.length) throw new ProviderError(`Workflow ${manifest.id} bindings point at missing nodes: ${bound.missing.join(", ")}`);
let wf = bound.workflow;
+ const outputIds = manifest.outputs.map((o) => o.node);
+ // FPS Boost to a lower rate, or one the clip divides into: no interpolation, only every n-th frame.
+ if (finish.bypassInterpolation) {
+ const id = Object.keys(wf).find((k) => wf[k].class_type === "FrameInterpolate");
+ if (id) wf = bypassNode(wf, id, "images", outputIds);
+ }
+ // Slow motion: the sound would no longer match the picture.
+ if (finish.dropSound) for (const n of Object.values(wf)) if (n.class_type === "CreateVideo") delete n.inputs.audio;
+ // VHS meta-batch: a manager of its own per job (a stale one loses frames), and no sound link for a silent clip.
+ wf = tagMetaBatch(wf, ctx.generationId);
+ if (clip && !clip.hasAudio && clip.hasVideo) wf = dropVhsAudio(wf);
if (manifest.expand === "captions") {
if (!cues.length) throw new ProviderError("No timed captions to burn in. Transcribe the clip first, or write lines like “0.00-2.40: Hello there”");
try {
@@ -702,8 +843,8 @@ export const comfyProvider: ProviderAdapter = {
const j = (await res.json()) as { name: string; subfolder?: string };
const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;
// Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.
- if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name)) {
- const info = probeMedia(data);
+ if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name) || /\.(webm|mkv)$/i.test(name)) {
+ const info = probeMedia(data) ?? webmInfo(data);
if (info) rememberMedia(uploaded, info);
}
return uploaded;
@@ -732,7 +873,7 @@ export const comfyProvider: ProviderAdapter = {
const detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...(input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: l.url }))] }) : (missingPack ?? body.error?.message);
throw new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status);
}
- return { externalId: body.prompt_id, meta, payload: wf };
+ return { externalId: body.prompt_id, meta: { ...meta, generationId }, payload: wf };
},
async poll({ externalId, meta }) {
@@ -757,6 +898,11 @@ export const comfyProvider: ProviderAdapter = {
}
forget(externalId);
if (!outputs.length) return { state: "failed" as const, error: "Workflow finished without saving any output" };
+ try {
+ outputs = await bundleFrames(outputs, String(meta.generationId ?? String(meta.prefix ?? "").replace(/^fuobe\//, "")));
+ } catch (e) {
+ return { state: "failed" as const, error: (e as Error).message };
+ }
return { state: "succeeded" as const, outputs: await withLayerBoxes(outputs) };
};
const isDone = (e: HistoryEntry | undefined): e is HistoryEntry => !!e && (!!e.status?.completed || e.status?.status_str === "success" || e.status?.status_str === "error");
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index 2f547810..7c24652e 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -5,6 +5,7 @@ import { OPERATION_OUTPUT, type MediaKind, type Operation } from "@/lib/catalog/
import type { ProviderAdapter, RemoteOutput } from "./types";
import { textOutput } from "./llm";
import { toDataUri } from "../storage";
+import { zip } from "../zip";
/**
* Demo provider: lets anyone click through the whole product with no API keys or GPU.
@@ -290,8 +291,11 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
case "images-to-video":
return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } }];
case "sdr-to-hdr":
- case "export-video":
- return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true, ...(meta.format ? { format: meta.format } : {}) } }];
+ case "export-video": {
+ // EXR frames ride along on the preview clip as a zip (meta.artifacts.exr), as the real routes do.
+ const exr = meta.format === "exr" ? { artifacts: { exr: toDataUri(zip([{ name: "README.txt", data: Buffer.from("Demo mode: a real run puts one 16-bit EXR file per frame here.\n") }]), "application/zip") } } : {};
+ return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true, ...(meta.format ? { format: meta.format } : {}), ...exr } }];
+ }
case "trim":
case "captions":
case "mux":
diff --git a/src/server/shorts.ts b/src/server/shorts.ts
index 8a5b586a..fa4d9ed1 100644
--- a/src/server/shorts.ts
+++ b/src/server/shorts.ts
@@ -30,14 +30,13 @@ import {
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";
-import { probeWebm } from "./webm-probe";
+import { mediaFacts, type SourceInfo } from "./media-facts";
/**
* Shorts Studio sessions: a clip cut into segments, each restyled (one or more takes, one of them
@@ -62,13 +61,7 @@ export { maxRefsFor, modelInfos, resolutionFor } from "@/lib/catalog/shorts-mode
// ---------------------------------------------------------------------------
// Source clips
-export interface SourceInfo {
- duration?: number;
- width?: number;
- height?: number;
- fps?: number;
- hasAudio?: boolean;
-}
+export type { SourceInfo } from "./media-facts";
/**
* What the clip's header says (MP4 / MOV, and WebM / Matroska). A file neither reader knows comes
@@ -76,29 +69,13 @@ export interface SourceInfo {
*/
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;
let data: Buffer;
try {
data = (await readRef(url)).data;
} catch {
throw new ShortsError("That clip is gone — upload it again", 404);
}
- try {
- info = probeMedia(data);
- } catch {
- info = null;
- }
- if (!info) {
- const webm = probeWebm(data);
- return webm ? { duration: webm.duration, width: webm.width, height: webm.height, fps: webm.fps, hasAudio: webm.hasAudio } : {};
- }
- return {
- duration: info.videoDuration ?? info.duration,
- width: info.width,
- height: info.height,
- fps: info.fps,
- hasAudio: info.hasAudio,
- };
+ return mediaFacts(data);
}
// ---------------------------------------------------------------------------
diff --git a/src/server/storage.ts b/src/server/storage.ts
index 6ea1c9db..b0f4fd8b 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -34,6 +34,11 @@ const EXT_BY_TYPE: Record<string, string> = {
// Gaussian splats (TripoSplat on fal writes .ply; the open TripoSplat graph writes .spz).
"model/ply": "ply",
"model/x-spz": "spz",
+ // Pro exports: FFV1 in Matroska, EXR frames (ComfyUI's /view says image/aces) and their zip.
+ "video/x-matroska": "mkv",
+ "image/x-exr": "exr",
+ "image/aces": "exr",
+ "application/zip": "zip",
};
const TYPE_BY_EXT: Record<string, string> = {
@@ -60,6 +65,9 @@ const TYPE_BY_EXT: Record<string, string> = {
gltf: "model/gltf+json",
ply: "model/ply",
spz: "model/x-spz",
+ mkv: "video/x-matroska",
+ exr: "image/x-exr",
+ zip: "application/zip",
};
export function contentTypeFor(fileName: string, fallback = "application/octet-stream"): string {
@@ -122,27 +130,24 @@ function toAsset(r: AssetRow): Asset {
};
}
-export function saveFile(opts: {
- data: Buffer;
- contentType: string;
- name?: string;
- source: Asset["source"];
- generationId?: string;
-}): Asset {
+type NewAsset = { contentType: string; name?: string; source: Asset["source"]; generationId?: string };
+
+/** Store a file under files/<outputs|uploads>/<day>/<id>.<ext>: `put` writes it there, then its row is added. */
+function addAsset(opts: NewAsset, put: (abs: string) => void): Asset {
const id = nanoid(12);
const ext = EXT_BY_TYPE[opts.contentType.split(";")[0].trim()] ?? opts.name?.split(".").pop()?.toLowerCase() ?? "bin";
const day = new Date().toISOString().slice(0, 10);
const relPath = path.join(/*turbopackIgnore: true*/ opts.source === "generation" ? "outputs" : "uploads", day, `${id}.${ext}`);
const abs = path.join(FILES_DIR, relPath);
fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, opts.data);
+ put(abs);
const row: AssetRow = {
id,
kind: kindFor(opts.contentType),
name: opts.name ?? null,
rel_path: relPath,
content_type: opts.contentType,
- size: opts.data.length,
+ size: fs.statSync(abs).size,
source: opts.source,
generation_id: opts.generationId ?? null,
created_at: Date.now(),
@@ -156,6 +161,25 @@ export function saveFile(opts: {
return toAsset(row);
}
+export function saveFile(opts: NewAsset & { data: Buffer }): Asset {
+ return addAsset(opts, (abs) => fs.writeFileSync(abs, opts.data));
+}
+
+/**
+ * A file that is already ready on disk (a zip a provider wrote while finishing a job) becomes an asset:
+ * moved into the files folder, not copied. `from` must be on the same file system (scratchDir()).
+ */
+export function adoptFile(opts: NewAsset & { from: string }): Asset {
+ return addAsset(opts, (abs) => fs.renameSync(opts.from, abs));
+}
+
+/** A scratch folder next to the files folder (same file system, so adoptFile can move from it; never served). */
+export function scratchDir(): string {
+ const dir = path.join(DATA_DIR, "tmp");
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
export function getAsset(id: string): Asset | null {
const row = db().prepare("SELECT * FROM assets WHERE id = ?").get(id) as AssetRow | undefined;
return row ? toAsset(row) : null;
diff --git a/src/server/zip.ts b/src/server/zip.ts
index 3c5f3fc0..8e0aea3e 100644
--- a/src/server/zip.ts
+++ b/src/server/zip.ts
@@ -132,3 +132,44 @@ export function zipStream(entries: ZipEntry[]): ReadableStream<Uint8Array> {
},
});
}
+
+/** The largest stored zip these writers make (no ZIP64). */
+export const ZIP_MAX = 0xffffffff;
+
+/**
+ * Write a stored zip to `dest` from files that arrive one at a time (frames downloaded from a provider):
+ * one file in memory at once, the central directory at the end. Throws (and removes `dest`) past 4 GB.
+ * Returns the zip's size in bytes.
+ */
+export async function zipToFile(files: AsyncIterable<{ name: string; data: Buffer }>, dest: string): Promise<number> {
+ const out = fs.openSync(dest, "w");
+ const central: Buffer[] = [];
+ let offset = 0;
+ let count = 0;
+ let size = 0;
+ try {
+ const when = dosTime(Date.now());
+ for await (const f of files) {
+ const name = Buffer.from(f.name, "utf8");
+ const crc = zlib.crc32(f.data);
+ const head = localHeader(name, crc, f.data.length, when);
+ if (offset + head.length + name.length + f.data.length > ZIP_MAX) throw new Error("The frames add up to more than 4 GB — export a shorter part of the clip");
+ fs.writeSync(out, head);
+ fs.writeSync(out, name);
+ fs.writeSync(out, f.data);
+ central.push(centralHeader(name, crc, f.data.length, offset, when), name);
+ offset += head.length + name.length + f.data.length;
+ count++;
+ }
+ const cd = Buffer.concat(central);
+ fs.writeSync(out, cd);
+ fs.writeSync(out, endRecord(count, cd.length, offset));
+ size = offset + cd.length + 22;
+ } catch (e) {
+ fs.closeSync(out);
+ fs.rmSync(dest, { force: true });
+ throw e;
+ }
+ fs.closeSync(out);
+ return size;
+}