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.

Kling 4.0: shots keep their own words, whole seconds, and the API's limits in Fuobe's words

Claude7693ffb67fdf
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index 5d76eee7..205f6f83 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -415,7 +415,9 @@ model("kling-4", "Kling 4.0", "Kuaishou", "kling", "video",
("video-swap", _K4_EDIT, "fal", {"drop": ["duration"]}), ("video-insert", _K4_EDIT, "fal", {"drop": ["duration"]}),
("t2v", "kwaivgi/kling-v4.0", "replicate", {"drop": ["image", "endImage", "images", "video"]}),
("i2v", "kwaivgi/kling-v4.0", "replicate", {"drop": ["images", "video", "aspectRatio"], "flf2v": True})],
- badges=["top", "30s", "new"], ranged_durations=True,
+ # Only reference-to-video takes "auto": each route lists the shapes it takes (fit_values), so a text or Replicate
+ # run leaves "auto" out (the API's own 16:9) rather than sending a value it refuses.
+ badges=["top", "30s", "new"], ranged_durations=True, fit_values=True,
pricing=("second", 0.235, "1080p; 720p $0.157. An edit, reference clips or video elements bill $0.141/s at 1080p ($0.094 at 720p) on the seconds in plus the seconds out, at least twice the output",
{"byResolution": {"720p": 0.157, "1080p": 0.235}, "clipInput": {"usd": 0.141, "byResolution": {"720p": 0.094, "1080p": 0.141}}}),
defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "1080p"})
diff --git a/src/lib/catalog/clip-windows.ts b/src/lib/catalog/clip-windows.ts
index afa4b71e..0c570e4c 100644
--- a/src/lib/catalog/clip-windows.ts
+++ b/src/lib/catalog/clip-windows.ts
@@ -20,18 +20,55 @@ export function sourceSeconds(modelId: string): { min?: number; max?: number } {
return SOURCE_SECONDS[modelId] ?? {};
}
-/** The sides a clip edit takes, in pixels (Kling 4.0's edit: 700–4553 px on each side). */
-const SOURCE_SIDES: Record<string, { min: number; max: number }> = { "kling-4": { min: 700, max: 4553 } };
+/**
+ * The frame a clip edit takes (Kling 4.0's edit, research part 4: 700–4553 px on each side, width ÷ height 0.40–2.50,
+ * 23.9–60.05 fps).
+ */
+const SOURCE_FRAME: Record<string, { min: number; max: number; ratio: [number, number]; fps: [number, number] }> = {
+ "kling-4": { min: 700, max: 4553, ratio: [0.4, 2.5], fps: [23.9, 60.05] },
+};
-/** Why a clip `width`×`height` is outside the sides the model takes, in Generate's words, or null. */
+/** Why a clip `width`×`height` is outside the sides or shape the model takes, in Generate's words, or null. */
export function clipSizeProblem(model: { id: string; name: string }, width: number, height: number): string | null {
- const s = SOURCE_SIDES[model.id];
+ const s = SOURCE_FRAME[model.id];
if (!s || !(width > 0) || !(height > 0)) return null;
if (Math.min(width, height) < s.min) return `${model.name} needs a clip at least ${s.min} px on each side, and this one is ${width}×${height}: upscale it first or pick another model`;
if (Math.max(width, height) > s.max) return `${model.name} takes clips up to ${s.max} px on a side, and this one is ${width}×${height}: scale it down first`;
+ const r = width / height;
+ if (r < s.ratio[0] - 0.005 || r > s.ratio[1] + 0.005) {
+ return `${model.name} takes clips from ${s.ratio[0].toFixed(1)}:1 (tall) to ${s.ratio[1].toFixed(1)}:1 (wide), and this one is ${width}×${height}: crop it first`;
+ }
return null;
}
+/** Why a clip at `fps` frames a second is outside the frame rates the model takes (Kling 4.0: 24–60 fps), or null. */
+export function clipFpsProblem(model: { id: string; name: string }, fps: number): string | null {
+ const s = SOURCE_FRAME[model.id];
+ if (!s || !(fps > 0) || (fps >= s.fps[0] && fps <= s.fps[1])) return null;
+ const range = `${Math.round(s.fps[0])}–${Math.round(s.fps[1])} fps`;
+ return `${model.name} takes clips at ${range}, and this one is ${Math.round(fps * 100) / 100} fps: save it at ${fps < s.fps[0] ? Math.round(s.fps[0]) : Math.round(s.fps[1])} fps first`;
+}
+
+/** How long a clip given as one of the model's elements may be (Kling 4.0's video elements: 3–8 s). */
+const ELEMENT_CLIP_SECONDS: Record<string, { min: number; max: number }> = { "kling-4": { min: 3, max: 8 } };
+
+/** Why a clip element `seconds` long is outside what the model takes ("Kling 4.0 takes 3–8 s clips as elements…"), or null. */
+export function elementClipProblem(model: { id: string; name: string }, seconds: number, name?: string): string | null {
+ const w = ELEMENT_CLIP_SECONDS[model.id];
+ if (!w || !(seconds > 0) || (seconds >= w.min - 0.05 && seconds <= w.max + 0.05)) return null;
+ return `${model.name} takes ${w.min}–${w.max} s clips as elements, and ${name ? `${name}'s` : "this one"} is ${secs(seconds)}: trim it, or use its photos instead`;
+}
+
+/** The most reference clips an edit takes beside the clip it edits (Kling 4.0's edit: 4 video_urls, @Video2..). */
+const EDIT_REFERENCE_CLIPS: Record<string, number> = { "kling-4": 4 };
+
+/** Why `count` reference clips are more than the model's edit takes, or null. */
+export function editClipsProblem(model: { id: string; name: string }, count: number): string | null {
+ const max = EDIT_REFERENCE_CLIPS[model.id];
+ if (max === undefined || count <= max) return null;
+ return `${model.name}'s edit takes up to ${max} reference clips beside the clip you edit, and this run has ${count}: remove ${count - max}`;
+}
+
/**
* The most seconds of clips a run takes in all, where the model says (Kling 4.0: "the source, reference and element
* videos must total at most 30s").
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index 33fee1c3..3099958f 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -4126,8 +4126,22 @@ export const CLOUD_MODELS: ModelDef[] = [
"maxPrompt": 512,
"integer": true
},
- "aspectRatio": "aspect_ratio",
- "resolution": "resolution",
+ "aspectRatio": {
+ "key": "aspect_ratio",
+ "accepts": [
+ "16:9",
+ "9:16",
+ "1:1",
+ "21:9"
+ ]
+ },
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
@@ -4147,7 +4161,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"maxPrompt": 512,
"integer": true
},
- "resolution": "resolution",
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
@@ -4167,7 +4187,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"maxPrompt": 512,
"integer": true
},
- "resolution": "resolution",
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
@@ -4196,8 +4222,23 @@ export const CLOUD_MODELS: ModelDef[] = [
"video": "video_url",
"maxVideos": 3
},
- "aspectRatio": "aspect_ratio",
- "resolution": "resolution",
+ "aspectRatio": {
+ "key": "aspect_ratio",
+ "accepts": [
+ "auto",
+ "16:9",
+ "9:16",
+ "1:1",
+ "21:9"
+ ]
+ },
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
@@ -4221,7 +4262,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"video": "video_url",
"maxVideos": 3
},
- "resolution": "resolution"
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ }
}
},
{
@@ -4241,7 +4288,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"video": "video_url",
"maxVideos": 3
},
- "resolution": "resolution"
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ }
}
},
{
@@ -4261,7 +4314,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"video": "video_url",
"maxVideos": 3
},
- "resolution": "resolution"
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ }
}
},
{
@@ -4269,8 +4328,22 @@ export const CLOUD_MODELS: ModelDef[] = [
"provider": "replicate",
"endpoint": "kwaivgi/kling-v4.0",
"map": {
- "aspectRatio": "aspect_ratio",
- "resolution": "resolution",
+ "aspectRatio": {
+ "key": "aspect_ratio",
+ "accepts": [
+ "16:9",
+ "9:16",
+ "1:1",
+ "21:9"
+ ]
+ },
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
@@ -4284,7 +4357,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"map": {
"image": "start_image",
"endImage": "end_image",
- "resolution": "resolution",
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
@@ -4298,7 +4377,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"map": {
"image": "start_image",
"endImage": "end_image",
- "resolution": "resolution",
+ "resolution": {
+ "key": "resolution",
+ "accepts": [
+ "720p",
+ "1080p"
+ ]
+ },
"duration": {
"key": "duration",
"type": "number"
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 9b56819d..8c257f86 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -316,7 +316,7 @@ function zoomValue(z: NonNullable<FieldMap["zoom"]>, input: GenInput): Record<st
}
/** `text` cut to `max` characters, at a word where one is near the end (a shot's prompt: Kling 4.0 takes 512). */
-function clipWords(text: string, max: number): string {
+export function clipWords(text: string, max: number): string {
if (text.length <= max) return text;
const cut = text.slice(0, max);
const space = cut.lastIndexOf(" ");
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 0f879748..b284c0e7 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -10,11 +10,11 @@ import type {
Preset,
PresetRoute,
} from "./types";
-import { sourceSeconds } from "./clip-windows";
+import { editClipsProblem, sourceSeconds } from "./clip-windows";
import { chainGapProblem, chainTiming, FIRST_AT_ZERO, frameTimes, keyframeChain, MAX_KEYFRAMES, spread } from "./keyframes";
import { cloudPath, fitLoras, gated, localOnly, loraCapacity, needsToken, routeLoraField, triggerOf } from "./loras";
import { anglesPrompt, anglesWords, ANGLES_ORIGINAL } from "./open-tools";
-import { askedSize, numFramesValue, sizeValue } from "./payload";
+import { askedSize, clipWords, numFramesValue, sizeValue } from "./payload";
import { characterScale, CINEMA_CROP, soulKind, soulMegapixels, soulRecipe, soulSize, type SoulOverlay } from "./soul";
import { pricingOn, type PriceClock } from "./promo";
import { presetRoutes } from "./preset-recipe-routes";
@@ -67,6 +67,35 @@ export function routesFor(model: ModelDef, op: Operation): ModelRoute[] {
return model.routes.filter((r) => r.op === op);
}
+/** Fewer characters than this of the overall prompt in front of a capped shot prompt say too little: it is left out. */
+const MIN_SHOT_LEAD = 40;
+
+/**
+ * Shots in whole seconds (each at least 1) that keep the take's rounded total: each is floored, and the seconds left go
+ * to the shots with the largest remainders, so 2.4 + 2.4 becomes 3 + 2 (5 s), not 2 + 2.
+ */
+export function wholeShots<S extends { duration: number }>(shots: S[]): S[] {
+ const total = Math.max(shots.length, Math.round(shots.reduce((n, s) => n + s.duration, 0)));
+ const secs = shots.map((s) => Math.max(1, Math.floor(s.duration)));
+ let left = total - secs.reduce((n, v) => n + v, 0);
+ const rem = (i: number) => shots[i].duration - Math.floor(shots[i].duration);
+ const byRem = shots.map((_, i) => i).sort((a, b) => rem(b) - rem(a) || a - b);
+ // Seconds to add go to the largest remainders (at most one each: they add up to less than one per shot); seconds to
+ // take back (shots raised to 1 s) come off the longest shots.
+ for (const i of byRem) {
+ if (left <= 0) break;
+ secs[i]++;
+ left--;
+ }
+ while (left < 0) {
+ const i = byRem.reduce((best, j) => (secs[j] > 1 && (best < 0 || secs[j] > secs[best]) ? j : best), -1);
+ if (i < 0) break;
+ secs[i]--;
+ left++;
+ }
+ return shots.map((s, i) => (secs[i] === s.duration ? s : { ...s, duration: secs[i] }));
+}
+
/**
* The most images a run of `op` sends this model: its routes' own limit when they all have one (ModelRoute.maxImages:
* Qwen-Image 2.1 inpaints and expands the picture alone), else the model's options.maxImages.
@@ -368,20 +397,37 @@ export function planGeneration(
loras = kept;
// Multi-shot: the clip is as long as its shots, and models without per-shot prompts get them written out.
- const shots = params.shots?.filter((s) => s.prompt.trim());
+ let shots = params.shots?.filter((s) => s.prompt.trim());
if (shots?.length) {
if (!model.options.multiShot) throw new Error(`${model.name} can't do multi-shot — try Kling 3.0, Seedance 2.5 or Wan 2.6`);
if (shots.length > model.options.multiShot.maxShots) throw new Error(`${model.name} takes up to ${model.options.multiShot.maxShots} shots`);
+ // A model whose shots are whole seconds (Kling 4.0) gets them rounded here, keeping the total, so the price, the
+ // per-shot lengths and every route's duration (Replicate's too) are the same whole seconds.
+ const shotMaps = model.routes.flatMap((r) => (r.map?.multiShot ? [r.map.multiShot] : []));
+ const whole = shotMaps.some((m) => m.integer);
+ if (whole) shots = wholeShots(shots);
const total = shots.reduce((n, s) => n + s.duration, 0);
const max = Math.max(...(model.options.durations ?? [total]));
+ const min = Math.min(...(model.options.durations ?? [total]));
// Joined films (open models) render each shot as its own clip: only each shot has to fit.
const concat = model.options.multiShot.mode === "concat";
if (concat && shots.some((s) => s.duration > max)) throw new Error(`${model.name} makes clips up to ${max}s per shot`);
if (!concat && total > max) throw new Error(`The shots add up to ${total}s — ${model.name} makes up to ${max}s`);
- // Per-shot prompts carry the overall description (and @element legend) with them.
+ if (whole && total < min) throw new Error(`The shots add up to ${total}s — ${model.name} makes ${min}s or more`);
+ // Per-shot prompts carry the overall description (and @element legend) with them. Where a shot's prompt has a
+ // length cap (Kling 4.0: 512 characters), the shot's own words come first: the overall part is cut to the room left,
+ // and left out when hardly any is left.
const overall = prompt.trim().replace(/[.\s]+$/, "");
const native = model.options.multiShot.mode === "native";
- params = { ...params, shots: native && overall ? shots.map((s) => ({ ...s, prompt: `${overall}. ${s.prompt.trim()}` })) : shots, duration: total };
+ const caps = shotMaps.flatMap((m) => (m.maxPrompt ? [m.maxPrompt] : []));
+ const cap = caps.length ? Math.min(...caps) : undefined;
+ const lead = (own: string) => {
+ if (cap === undefined || overall.length + own.length + 2 <= cap) return `${overall}. ${own}`;
+ const room = cap - own.length - 2;
+ const cut = room >= MIN_SHOT_LEAD ? clipWords(overall, room) : "";
+ return cut ? `${cut}. ${own}` : own;
+ };
+ params = { ...params, shots: native && overall ? shots.map((s) => ({ ...s, prompt: lead(s.prompt.trim()) })) : shots, duration: total };
prompt = composeShots(prompt, shots);
} else if (params.multiShot === "auto" && model.options.multiShot?.mode === "prompt") {
prompt = `${prompt.replace(/[.\s]+$/, "")}. Multi-shot sequence: tell it in several distinct shots with clean cuts between them.`;
@@ -390,6 +436,12 @@ export function planGeneration(
// Reference clips and video elements on a model that bills them with the output (Kling 4.0, Pricing.clipInput): priced
// at the least they bill (twice the output) until the server reads their length (params.clipSeconds).
if (model.pricing?.clipInput && req.inputs?.videos?.length && params.clipSeconds === undefined) params = { ...params, clipSeconds: 0 };
+ // An edit's reference clips (beside the clip it edits; clip elements are counted on their own): Kling 4.0 takes 4.
+ if (op === "v2v" || op === "video-swap" || op === "video-insert") {
+ const asElements = params.elements?.filter((g) => g.video !== undefined).length ?? 0;
+ const problem = editClipsProblem(model, (req.inputs?.videos?.length ?? 0) - asElements);
+ if (problem) throw new Error(problem);
+ }
if (!routesFor(model, op).length) {
throw new Error(`${model.name} can't do ${op} — try another model`);
}
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index fbd280dd..8394df9a 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -7,7 +7,7 @@ import { FORMAT_INFO } from "./av/formats";
import { fpsPlan, fpsSummary } from "./av/fps";
import { targetShortEdge, upscaledSize, upscaleFactorFor, upscaleTier } from "./av/upscale";
import { wholeClipProblem, wholeClipTool } from "./av/video-finish";
-import { clipSizeProblem, clipWindowProblem } from "./catalog/clip-windows";
+import { clipFpsProblem, clipSizeProblem, clipWindowProblem } from "./catalog/clip-windows";
import { clipBilling } from "./catalog/plan";
import { addFrameAt, frameTimes, framesInputs, removeFrameAt, spread, type FrameSupport } from "./catalog/keyframes";
import { FACE_MOSAIC_MODELS } from "./catalog/open-tools";
@@ -295,7 +295,11 @@ export function clipBlocker(
): string | null {
if (op === "v2v" && model?.id && (facts?.duration || facts?.width)) {
const named = { id: model.id, name: model.name ?? model.id };
- return (facts.duration ? clipWindowProblem(named, facts.duration) : null) ?? (facts.width && facts.height ? clipSizeProblem(named, facts.width, facts.height) : null);
+ return (
+ (facts.duration ? clipWindowProblem(named, facts.duration) : null) ??
+ (facts.width && facts.height ? clipSizeProblem(named, facts.width, facts.height) : null) ??
+ (facts.fps ? clipFpsProblem(named, facts.fps) : null)
+ );
}
if (!facts?.width || !facts.height || !model) return null;
if (op === "upscale-video") {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 0980bee4..506824e6 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -12,7 +12,7 @@ import { cueText, type Cue } from "@/lib/cues";
import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";
import { upscaleTier } from "@/lib/av/upscale";
import { chainedWaitMessage, framesWait, keyframeChain } from "@/lib/catalog/keyframes";
-import { clipSizeProblem, clipTotalProblem, clipWindowProblem } from "@/lib/catalog/clip-windows";
+import { clipFpsProblem, clipSizeProblem, clipTotalProblem, clipWindowProblem, elementClipProblem } from "@/lib/catalog/clip-windows";
import { avatarSeconds, clipEditSeconds, estimateCost, inferOperation, movedAppRequest, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";
import { framedLength, keepMatte } from "@/lib/catalog/payload";
import { fitLoras, loraName, lorasFit } from "@/lib/catalog/loras";
@@ -1500,14 +1500,15 @@ async function submitNow(
});
};
// Reference clips and clip elements a model bills with the output (Kling 4.0, Pricing.clipInput): their headers' lengths.
- const clipLengths: number[] = [];
+ // By the clip's place in inputs.videos, so a clip element (params.elements' video) finds its own length.
+ const clipLengths: (number | undefined)[] = [];
const billsClips = !!plan.model.pricing?.clipInput;
- const prepClip = async (ref?: string) => {
+ const prepClip = async (ref: string | undefined, i: number) => {
if (!ref || !billsClips) return prep(ref);
return gate(async () => {
const f = await readRef(ref);
const facts = mediaFacts(f.data);
- if (facts.duration) clipLengths.push(facts.duration);
+ if (facts.duration) clipLengths[i] = facts.duration;
return adapter.prepareFile(f.data, f.contentType, f.name, route);
});
};
@@ -1565,7 +1566,7 @@ async function submitNow(
audio2: await prep(req.inputs?.audio2),
voiceAudio: await prep(req.inputs?.voiceAudio),
voiceAudio2: await prep(req.inputs?.voiceAudio2),
- videos: (await Promise.all((req.inputs?.videos ?? []).map(prepClip))).filter(Boolean) as string[],
+ videos: (await Promise.all((req.inputs?.videos ?? []).map((ref, i) => prepClip(ref, i)))).filter(Boolean) as string[],
audios: (await Promise.all((req.inputs?.audios ?? []).map(prep))).filter(Boolean) as string[],
model3d: await prep(req.inputs?.model3d),
loras: plan.loras,
@@ -1588,17 +1589,33 @@ async function submitNow(
update(id, { cost_usd: estimateCost(plan.model, { ...plan.params, sourceDuration: input.sourceDuration }, 1, plan.op, plan.loras.length > 0 && !!route.loraEndpoint) });
}
}
- // Reference clips (and clip elements) billed with the output: refused past the most the model takes in all (with the
- // clip edited), before it's paid for, and priced on their seconds once read (the plan priced the least they bill).
- // An edit of a clip whose length the caller didn't say is priced on it (in and out) once its header is read.
const edits = plan.op === "v2v" || plan.op === "video-swap" || plan.op === "video-insert";
+ // An edit whose route sends no length keeps the clip's own (Kling 4.0's edit, swap and insert), whatever the request
+ // said: the clip is held to the model's window, sides, shape and frame rate before it's paid for.
+ if (edits && !route.map?.duration && !req.chain?.length && providerId !== "mock" && plan.model.engine !== "open") {
+ const problem =
+ (input.sourceDuration ? clipWindowProblem(plan.model, input.sourceDuration) : null) ??
+ (input.sourceSize ? clipSizeProblem(plan.model, input.sourceSize.width, input.sourceSize.height) : null) ??
+ (input.sourceFps ? clipFpsProblem(plan.model, input.sourceFps) : null);
+ if (problem) throw new Error(problem);
+ }
+ // Reference clips (and clip elements) billed with the output: refused past the most the model takes in all (with the
+ // clip edited), or a clip element outside its own window, before it's paid for, and priced on their seconds once read
+ // (the plan priced the least they bill). An edit of a clip whose length the caller didn't say is priced on it (in and
+ // out) once its header is read.
+ const read = clipLengths.filter((n): n is number => n !== undefined);
const unpricedEdit = edits && !!input.sourceDuration && plan.params.sourceDuration === undefined;
- if (billsClips && (clipLengths.length || unpricedEdit) && providerId !== "mock" && plan.model.engine !== "open") {
- const seconds = clipLengths.reduce((a, b) => a + b, 0);
+ if (billsClips && (read.length || unpricedEdit) && providerId !== "mock" && plan.model.engine !== "open") {
+ for (const g of plan.params.elements ?? []) {
+ const seconds = g.video !== undefined ? clipLengths[g.video] : undefined;
+ const problem = seconds !== undefined ? elementClipProblem(plan.model, seconds) : null;
+ if (problem) throw new Error(problem);
+ }
+ const seconds = read.reduce((a, b) => a + b, 0);
const problem = clipTotalProblem(plan.model, (edits ? (input.sourceDuration ?? 0) : 0) + seconds);
if (problem) throw new Error(problem);
- if (clipLengths.length) input.clipSeconds = seconds;
- const priced = { ...plan.params, ...(input.sourceDuration !== undefined && { sourceDuration: input.sourceDuration }), ...(clipLengths.length && { clipSeconds: seconds }) };
+ if (read.length) input.clipSeconds = seconds;
+ const priced = { ...plan.params, ...(input.sourceDuration !== undefined && { sourceDuration: input.sourceDuration }), ...(read.length && { clipSeconds: seconds }) };
update(id, { cost_usd: estimateCost(plan.model, priced, 1, plan.op) });
}
// An upscale that wouldn't enlarge the clip (a 1080p clip at a default 1080p; a 4K clip would even shrink):
diff --git a/tests/kling-4-server.test.ts b/tests/kling-4-server.test.ts
new file mode 100644
index 00000000..cef2bcd2
--- /dev/null
+++ b/tests/kling-4-server.test.ts
@@ -0,0 +1,104 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * Kling 4.0's clip limits on the server (nm10-kling-4): an edit keeps the clip's own length, so the clip is held to the
+ * edit's sides and shape even when the request named a length, and a clip element outside 3–8 s is refused, both
+ * before anything goes to fal. No paid call is made: fetch is stubbed and nothing reaches fal.
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kling-4-server-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { createGenerations, getGeneration } = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** A tiny MP4 header `seconds` long (ftyp + moov with one `width`×`height` video trak), enough for the server's header read. */
+function mp4(seconds: number, width = 1280, height = 720): 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(width << 16, 76);
+ tkhd.writeUInt32BE(height << 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)]);
+}
+const clip = (seconds: number, width?: number, height?: number) =>
+ saveFile({ data: mp4(seconds, width, height), contentType: "video/mp4", name: `clip-${seconds}-${width ?? 1280}.mp4`, source: "upload" }).url;
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+afterAll(() => {
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+describe("Kling 4.0's clip limits before fal is asked", () => {
+ it("refuses an edit's too-wide clip although the request named a length, and a clip element over 8 s", async () => {
+ setSetting("falKey", "fal_test_key_123456");
+ const real = globalThis.fetch;
+ const asked: string[] = [];
+ globalThis.fetch = (async (url: string) => {
+ asked.push(String(url));
+ return new Response(JSON.stringify({ request_id: "r1", status_url: "https://queue.fal.test/s", response_url: "https://queue.fal.test/r", cancel_url: "https://queue.fal.test/c" }), { status: 200 });
+ }) as typeof fetch;
+ const { falProvider: fal } = await import("@/server/providers/fal");
+ const upload = fal.prepareFile;
+ fal.prepareFile = async (_d, _t, name) => `https://v3.fal.media/files/${name}`;
+ const failed = async (id: string) => {
+ for (let i = 0; i < 200 && getGeneration(id)!.status !== "failed"; i++) await sleep(25);
+ return getGeneration(id)!;
+ };
+ try {
+ // 3000×700 is 4.3:1, past the edit's 2.5:1; the duration the composer sends doesn't skip the check.
+ const [wide] = createGenerations({
+ feature: "video-edit",
+ modelId: "kling-4",
+ engine: "cloud",
+ op: "v2v",
+ prompt: "make it snow",
+ inputs: { video: clip(8, 3000, 700) },
+ params: { duration: 5, resolution: "720p" },
+ });
+ expect(await failed(wide.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/2\.5:1 \(wide\), and this one is 3000×700: crop it first/) });
+ // A 10 s clip as an element: Kling takes 3–8 s ones.
+ const [element] = createGenerations({
+ feature: "video",
+ modelId: "kling-4",
+ engine: "cloud",
+ op: "ref2v",
+ prompt: "@Element1 walks in",
+ inputs: { videos: [clip(10)] },
+ params: { duration: 5, resolution: "720p", elements: [{ video: 0 }] },
+ });
+ expect(await failed(element.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/3–8 s clips as elements, and this one is 10 s/) });
+ expect(asked.filter((u) => u.includes("kling/v4"))).toEqual([]);
+ } finally {
+ globalThis.fetch = real;
+ fal.prepareFile = upload;
+ setSetting("falKey", "");
+ }
+ });
+});
diff --git a/tests/kling-4.test.ts b/tests/kling-4.test.ts
index 8b1d8676..960ceb9b 100644
--- a/tests/kling-4.test.ts
+++ b/tests/kling-4.test.ts
@@ -17,12 +17,18 @@ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
const { getModel, getPreset, MODELS, modelsFor } =
await import("@/lib/catalog");
const { buildPayload } = await import("@/lib/catalog/payload");
-const { clipBilling, estimateCost, planGeneration, routesFor } =
+const { clipBilling, estimateCost, planGeneration, routesFor, wholeShots } =
await import("@/lib/catalog/plan");
const { applyMentions, elementsNote } = await import("@/lib/catalog/elements");
const { planCinema } = await import("@/lib/catalog/cinema");
-const { clipSizeProblem, clipTotalProblem, clipWindowProblem } =
- await import("@/lib/catalog/clip-windows");
+const {
+ clipFpsProblem,
+ clipSizeProblem,
+ clipTotalProblem,
+ clipWindowProblem,
+ editClipsProblem,
+ elementClipProblem,
+} = await import("@/lib/catalog/clip-windows");
const { frameSupport } = await import("@/lib/catalog/keyframes");
const { genjutsuProblem, getMaker, makerPrompt } =
await import("@/lib/catalog/genjutsu");
@@ -262,6 +268,116 @@ describe("payloads against the stored schemas", () => {
checkAgainstSchema(r, payload);
});
+ it("a long overall prompt never pushes a shot's own words out of its 512 characters", () => {
+ const overall = `${"A slow, rain-soaked harbour at night with sodium lights. ".repeat(11)}End.`;
+ expect(overall.length).toBeGreaterThan(600);
+ const shots = [
+ { prompt: "SHOT-ONE: wide on the pier", duration: 4 },
+ { prompt: "SHOT-TWO: her hands on the rail", duration: 3 },
+ { prompt: "SHOT-THREE: the ship's horn", duration: 3 },
+ ];
+ const { route: r, payload } = payloadFor({ prompt: overall, params: { shots } });
+ const sent = payload.multi_prompt as { prompt: string }[];
+ sent.forEach((s, i) => {
+ expect(s.prompt.length).toBeLessThanOrEqual(512);
+ // The shot's words whole, after as much of the overall description as fits.
+ expect(s.prompt.endsWith(shots[i].prompt)).toBe(true);
+ expect(s.prompt.startsWith("A slow, rain-soaked harbour")).toBe(true);
+ });
+ expect(new Set(sent.map((s) => s.prompt)).size).toBe(3);
+ checkAgainstSchema(r, payload);
+ // A shot that fills the 512 characters itself goes alone (cut at a word), with no overall part in front.
+ const long = payloadFor({
+ prompt: overall,
+ params: {
+ shots: [
+ { prompt: `SHOT-LONG ${"word ".repeat(110)}`, duration: 5 },
+ { prompt: "SHOT-SHORT", duration: 5 },
+ ],
+ },
+ }).payload.multi_prompt as { prompt: string }[];
+ expect(long[0].prompt.startsWith("SHOT-LONG")).toBe(true);
+ expect(long[0].prompt.length).toBeLessThanOrEqual(512);
+ expect(long[1].prompt.endsWith("SHOT-SHORT")).toBe(true);
+ // A short overall prompt still leads each shot whole.
+ const short = payloadFor({ prompt: "Night harbour", params: { shots } })
+ .payload.multi_prompt as { prompt: string }[];
+ expect(short[0].prompt).toBe("Night harbour. SHOT-ONE: wide on the pier");
+ });
+
+ it("shots in whole seconds, the total kept: priced as sent, on fal and Replicate", () => {
+ expect(wholeShots([{ duration: 2.4 }, { duration: 2.4 }])).toEqual([
+ { duration: 3 },
+ { duration: 2 },
+ ]);
+ expect(
+ wholeShots([{ duration: 0.2 }, { duration: 0.2 }, { duration: 5 }]),
+ ).toEqual([{ duration: 1 }, { duration: 1 }, { duration: 3 }]);
+ const shots = [
+ { prompt: "Wide", duration: 2.4 },
+ { prompt: "Close", duration: 2.4 },
+ ];
+ const fal = payloadFor({ params: { shots, resolution: "720p" } });
+ expect(fal.plan.params.duration).toBe(5);
+ expect(
+ estimateCost(fal.plan.model, fal.plan.params, 1, fal.plan.op),
+ ).toBeCloseTo(5 * 0.157, 5);
+ const sent = fal.payload.multi_prompt as { duration: number }[];
+ expect(sent.map((s) => s.duration)).toEqual([3, 2]);
+ expect(fal.payload.duration).toBe(5);
+ checkAgainstSchema(fal.route, fal.payload);
+ // Replicate has no shots: they're written out, and the length is the same whole seconds.
+ const rep = payloadFor({ params: { shots, resolution: "720p" } }, "replicate");
+ expect(rep.payload.duration).toBe(5);
+ expect(rep.payload.multi_prompt).toBeUndefined();
+ checkAgainstSchema(rep.route, rep.payload);
+ // Under 3 s in all is refused before the call (fal answers 422).
+ expect(() =>
+ payloadFor({
+ params: {
+ shots: [
+ { prompt: "One", duration: 1 },
+ { prompt: "Two", duration: 1 },
+ ],
+ },
+ }),
+ ).toThrow(/add up to 2s — Kling 4.0 makes 3s or more/);
+ // Rounding up past 30 s is refused, not sent.
+ expect(() =>
+ payloadFor({
+ params: {
+ shots: [
+ { prompt: "One", duration: 15.4 },
+ { prompt: "Two", duration: 15.3 },
+ ],
+ },
+ }),
+ ).toThrow(/add up to 31s/);
+ });
+
+ it("'auto' shape goes only to reference-to-video; text runs leave it to the API's own 16:9", () => {
+ const t2v = payloadFor({ params: { aspectRatio: "auto" } });
+ expect(t2v.route.endpoint).toBe("kling/v4/text-to-video");
+ expect(t2v.payload.aspect_ratio).toBeUndefined();
+ checkAgainstSchema(t2v.route, t2v.payload);
+ const rep = payloadFor({ params: { aspectRatio: "auto" } }, "replicate");
+ expect(rep.payload.aspect_ratio).toBeUndefined();
+ checkAgainstSchema(rep.route, rep.payload);
+ // Shapes each route takes still go as they are.
+ expect(
+ payloadFor({ params: { aspectRatio: "9:16" } }, "replicate").payload
+ .aspect_ratio,
+ ).toBe("9:16");
+ const ref = payloadFor({
+ op: "ref2v",
+ params: { aspectRatio: "auto" },
+ inputs: { images: ["https://x/a.png"] },
+ });
+ expect(ref.route.endpoint).toBe("kling/v4/reference-to-video");
+ expect(ref.payload.aspect_ratio).toBe("auto");
+ checkAgainstSchema(ref.route, ref.payload);
+ });
+
it("start and end frames", () => {
const { route: r, payload } = payloadFor({
op: "flf2v",
@@ -553,6 +669,56 @@ describe("limits checked before a paid call", () => {
});
});
+describe("the hosted API's other limits, in Fuobe's words before the call", () => {
+ it("an edit's clip: shape 0.40–2.50 and 24–60 fps", () => {
+ expect(clipSizeProblem(kling, 3000, 700)).toMatch(/crop it first/);
+ expect(clipSizeProblem(kling, 720, 1920)).toMatch(/crop it first/);
+ expect(clipSizeProblem(kling, 1080, 1920)).toBeNull();
+ expect(clipSizeProblem(kling, 2500, 1000)).toBeNull();
+ expect(clipFpsProblem(kling, 15)).toMatch(/24–60 fps.*save it at 24 fps/);
+ expect(clipFpsProblem(kling, 120)).toMatch(/save it at 60 fps/);
+ expect(clipFpsProblem(kling, 23.976)).toBeNull();
+ expect(clipFpsProblem(kling, 60)).toBeNull();
+ expect(
+ clipBlocker(
+ "v2v",
+ { duration: 12, width: 1920, height: 1080, fps: 120 },
+ {},
+ kling,
+ undefined,
+ ),
+ ).toMatch(/fps/);
+ // Other models aren't held to Kling's limits.
+ const o3 = getModel("kling-o3-4k-edit") ?? { id: "x", name: "X" };
+ expect(clipFpsProblem(o3, 120)).toBeNull();
+ });
+
+ it("a clip element is 3–8 s", () => {
+ expect(elementClipProblem(kling, 10, "Maya")).toMatch(
+ /3–8 s clips as elements, and Maya's is 10 s/,
+ );
+ expect(elementClipProblem(kling, 2)).toMatch(/3–8 s/);
+ expect(elementClipProblem(kling, 5)).toBeNull();
+ });
+
+ it("an edit takes up to 4 reference clips beside the clip it edits (clip elements apart)", () => {
+ expect(editClipsProblem(kling, 5)).toMatch(/up to 4 reference clips/);
+ expect(editClipsProblem(kling, 4)).toBeNull();
+ const five = Array.from({ length: 5 }, (_, i) => `https://x/r${i}.mp4`);
+ const edit = (params?: Req["params"]) =>
+ payloadFor({
+ feature: "video-edit",
+ op: "v2v",
+ prompt: "Make it snow",
+ inputs: { video: "https://x/src.mp4", videos: five },
+ params,
+ });
+ expect(() => edit()).toThrow(/up to 4 reference clips.*has 5: remove 1/);
+ // One of the five is a clip element: four references left.
+ expect(() => edit({ elements: [{ video: 4 }] })).not.toThrow();
+ });
+});
+
describe("Cinema Studio", () => {
const SETTINGS = {} as Parameters<typeof planCinema>[0]["settings"];
it("a 30 s multi-shot take is one Kling 4.0 call, with no extend", () => {
diff --git a/tests/open-minimax-h3.test.ts b/tests/open-minimax-h3.test.ts
index 2c62b5b1..7b540cef 100644
--- a/tests/open-minimax-h3.test.ts
+++ b/tests/open-minimax-h3.test.ts
@@ -289,7 +289,8 @@ describe("the Video studio and the other studio defaults", () => {
it("opens on MiniMax H3 on both engines, with LTX-2.5, Lightning and Seedance next in Best", () => {
expect(VIDEO_STUDIO.defaultModels).toEqual({ cloud: "minimax-h3", open: "oss-minimax-h3" });
expect(best("open")).toEqual(["oss-minimax-h3", "oss-ltx25", "oss-wan22-14b-fast", "fuobe-cinema"]);
- expect(best("cloud")).toEqual(["minimax-h3", "seedance-2-5", "kling-3", "veo-3-1"]);
+ // Kling 4.0 (nm10-kling-4) sits after Seedance 2.5, so Veo 3.1 leaves the four Best picks (the owner's choice).
+ expect(best("cloud")).toEqual(["minimax-h3", "seedance-2-5", "kling-4", "kling-3"]);
expect(studioCatalog(VIDEO_STUDIO).models.map((m) => m.id)).toEqual(expect.arrayContaining(["oss-minimax-h3", "minimax-h3", "oss-wan22-14b"]));
});