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.

Uploads: offer a part of reference clips, sound and clip elements that run too long

Adarshb7e2c202740d
diff --git a/src/components/audio-tools/clean-dialogue-panel.tsx b/src/components/audio-tools/clean-dialogue-panel.tsx
index 1366721b..919d6a6c 100644
--- a/src/components/audio-tools/clean-dialogue-panel.tsx
+++ b/src/components/audio-tools/clean-dialogue-panel.tsx
@@ -20,6 +20,7 @@ import {
OPEN_NOTE,
RELATION_NOTE,
soundAloneHelps,
+ VEED_MAX_SECONDS,
type BedLevel,
type Cleaner,
} from "@/lib/av/clean-dialogue";
@@ -55,6 +56,7 @@ export function CleanDialoguePanel({
blocker,
onMixer,
onSoundAlone,
+ trim,
}: {
/** The soundtrack, once it's uploaded. */
source: CleanSource | null;
@@ -66,6 +68,8 @@ export function CleanDialoguePanel({
onMixer: () => void;
/** Clean the video's sound alone instead (an MP3 made in the browser), when the video is too big for the cloud. */
onSoundAlone?: (file: { url: string; name: string }) => void;
+ /** The part of a longer source to clean, offered with the picker: the longest the cleaner takes (none: nothing to fit). */
+ trim?: (maxSeconds: number | undefined) => React.ReactNode;
}) {
const [bed, setBed] = useState<BedLevel>(DEFAULT_BED);
const [quality, setQuality] = useState<SplitQuality | null>(null);
@@ -175,6 +179,8 @@ export function CleanDialoguePanel({
</div>
</Panel>
+ {/* VEED cleans up to 30 minutes: a longer source gets the part to clean offered (kept while the part uploads). */}
+ {engine === "cloud" && trim?.(cleaner === "veed" ? VEED_MAX_SECONDS : undefined)}
<div className="space-y-2">
{!blocker && !error && p && (
<div className="space-y-1 text-[13px] text-muted-foreground" aria-live="polite">
diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsx
index d9740f27..8e58f947 100644
--- a/src/components/audio-tools/split-tool.tsx
+++ b/src/components/audio-tools/split-tool.tsx
@@ -62,6 +62,7 @@ import { usePoolRun } from "@/components/studio/pool-price";
import { toolPoolPrice } from "@/lib/run-place";
import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";
import { CleanDialoguePanel } from "./clean-dialogue-panel";
+import { SourceFit } from "@/components/av/fit-source";
import { CLEAN_DIALOGUE_PRESET, mixPresetFor } from "@/lib/av/clean-dialogue";
/**
@@ -821,6 +822,7 @@ export function SplitSoundtrackTool() {
setMixPreset(mixPresetFor("split", true));
}}
onSoundAlone={(f) => setSource({ ref: f.url, preview: f.url, kind: "audio", id: nanoid(8), name: f.name })}
+ trim={(max) => <SourceFit source={source} kind={source?.kind ?? "audio"} tool="VEED" maxSeconds={max} setSource={(s) => setSource(s && { ...s, channels: undefined })} className="px-1" />}
/>
)}
{goal === "split" && source && engine === "cloud" && (
diff --git a/src/components/av/element-clip-fit.tsx b/src/components/av/element-clip-fit.tsx
new file mode 100644
index 00000000..9fe0f0e8
--- /dev/null
+++ b/src/components/av/element-clip-fit.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import { Loader2, Scissors } from "lucide-react";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { useMediaSeconds } from "@/components/studio/reference-tray";
+import { useSaveElement } from "@/lib/api";
+import { elementClipCheck, elementClips } from "@/lib/av/reference-fit";
+import type { StudioElement } from "@/lib/catalog/elements";
+import type { GenerationRequest, ModelDef } from "@/lib/catalog/types";
+import { toastError } from "@/lib/refusals";
+import { cn } from "@/lib/utils";
+import { ListFit, type ListItem } from "./fit-list";
+import { useUploadSwitches } from "./use-upload-switches";
+
+/** Operations that edit a clip: the clip edited counts in the model's clips in all. */
+const EDITS = new Set(["v2v", "video-swap", "video-insert"]);
+
+/**
+ * Clip elements (Kling 4.0: a character or prop given as a 3–8 s clip, with every clip of the run 30 s in all), mentioned by
+ * name: their lengths read here before the run, and what is wrong said as the run's blocker. The fix ("Trim Maya's clip")
+ * opens the picker on that element's clip, and the part is saved on the element in place of the clip.
+ * `request` is the run as applyMentions resolved it (its elements and clips).
+ */
+export function useElementClipCheck(model: Pick<ModelDef, "id" | "name"> | undefined, request: Pick<GenerationRequest, "op" | "params" | "inputs"> | undefined, mentioned: readonly StudioElement[]) {
+ const clips = useMemo(() => (model && request && mentioned.length ? elementClips(request, mentioned) : []), [model, request, mentioned]);
+ // The run's other clips (reference clips, and the clip an edit edits) count in its clips in all, but aren't cut here.
+ const others = useMemo(() => {
+ if (!clips.length || !request) return [];
+ const own = new Set(clips.map((c) => c.ref));
+ const refs = (request.inputs?.videos ?? []).filter((r) => !own.has(r));
+ const edited = request.op && EDITS.has(request.op) && request.inputs?.video ? [request.inputs.video] : [];
+ return [...refs, ...edited];
+ }, [clips, request]);
+ const seconds = useMediaSeconds([...clips.map((c) => c.ref), ...others].map((r): SlotValue => ({ ref: r, preview: r, kind: "video" })));
+ const own = seconds.slice(0, clips.length);
+ const rest = seconds.slice(clips.length).reduce<number>((a, s) => a + (s ?? 0), 0);
+ const check = model && clips.length ? elementClipCheck(model, clips.map((c, i) => ({ name: c.element.name, seconds: own[i] })), rest) : null;
+ const target = check?.target ? { ...check.target, clip: clips[check.target.index], seconds: own[check.target.index] } : null;
+ return { problem: check?.problem ?? null, target, model };
+}
+
+/** The fix under the run's line: "Trim Maya's clip", then the picker on that clip; the part goes on the element. */
+export function ElementClipFix({ check, className }: { check: ReturnType<typeof useElementClipCheck>; className?: string }) {
+ const sw = useUploadSwitches();
+ const t = check.target;
+ if (!t || !check.model || !sw.videoTrim) return null;
+ return <ElementTrim key={`${t.clip.element.id}:${t.clip.ref}`} target={t} problem={check.problem} model={check.model} className={className} />;
+}
+
+function ElementTrim({ target, problem, model, className }: { target: NonNullable<ReturnType<typeof useElementClipCheck>["target"]>; problem: string | null; model: Pick<ModelDef, "name">; className?: string }) {
+ const save = useSaveElement();
+ const el = target.clip.element;
+ const [open, setOpen] = useState(false);
+ // The clip as the picker sees it: swapped for a stand-in while the part is cut, then for the part.
+ const [item, setItem] = useState<ListItem>(() => ({ ref: target.clip.ref, preview: target.clip.ref, kind: "video", name: `${el.name}.mp4` }));
+ const replace = (_from: ListItem, to: SlotValue) => {
+ setItem({ ...to, id: to.id ?? item.id });
+ if (to.uploading || !to.ref || to.ref === target.clip.ref) return;
+ save.mutate({ id: el.id, name: el.name, references: el.references.map((r) => (r === target.clip.ref ? to.ref : r)) }, {
+ onSuccess: () => toast.success(`${el.name} now uses the part you picked`),
+ onError: (e) => toastError(e, `We couldn't save the part on ${el.name}. Try again`),
+ });
+ };
+ return (
+ <div className={cn("space-y-1.5 pb-2", className)}>
+ {!open && problem && <p className="text-xs text-destructive">{problem}</p>}
+ {!open && (
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ className="inline-flex min-h-9 items-center gap-1.5 rounded-full border bg-background px-3.5 text-[13px] font-medium text-foreground hover:bg-accent"
+ >
+ <Scissors className="size-3.5" /> Trim {el.name}&apos;s clip
+ </button>
+ )}
+ {open && <ListFit item={item} seconds={item.ref === target.clip.ref ? target.seconds : undefined} kind="video" max={target.max} min={target.min} tool={model.name} line={target.line} label={`${el.name}'s clip`} replace={replace} />}
+ {save.isPending && (
+ <p role="status" className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" /> Saving the part on {el.name}…
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/av/fit-clip.tsx b/src/components/av/fit-clip.tsx
index 95d8fdb2..4dca7cf9 100644
--- a/src/components/av/fit-clip.tsx
+++ b/src/components/av/fit-clip.tsx
@@ -30,6 +30,8 @@ export interface ClipFitRule {
tool: string;
minSeconds?: number;
maxSeconds: number;
+ /** The picker's line, when the page says it its own way (a part to cut so clips fit together). */
+ line?: string;
}
type Offer = { source: Blob | string; name?: string; seconds: number; index: Mp4Index; stored?: SlotValue };
@@ -89,7 +91,11 @@ export function useClipFit({
const [offer, setOffer] = useState<Offer | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [made, setMade] = useState<{ ref: string; line: string } | null>(null);
+ const [made, setMade] = useState<{ ref: string; line: string; max: number } | null>(null);
+ // A stored clip whose offer was cancelled (Again offers it once more), and one this can't cut (not an MP4 or MOV).
+ const [declined, setDeclined] = useState<string | null>(null);
+ const [uncut, setUncut] = useState<string | null>(null);
+ const [tick, setTick] = useState(0);
const latest = useRef(value);
const cb = useRef({ rule, setValue, upload });
useEffect(() => {
@@ -99,11 +105,11 @@ export function useClipFit({
// Stored clips offered a part already: not offered again (a Cancel stands).
const offered = useRef(new Set<string>());
// A part handed to the slot's upload, by name: its stored address is marked once it lands.
- const expect = useRef<{ name: string; line: string } | null>(null);
+ const expect = useRef<{ name: string; line: string; max: number } | null>(null);
const landed = value && !value.uploading ? value.held ?? value.ref : undefined;
useEffect(() => {
if (!expect.current || value?.uploading) return;
- if (value?.name === expect.current.name && landed) setMade({ ref: landed, line: expect.current.line });
+ if (value?.name === expect.current.name && landed) setMade({ ref: landed, line: expect.current.line, max: expect.current.max });
expect.current = null;
}, [value, landed]);
@@ -135,19 +141,20 @@ export function useClipFit({
const ref = on && value && !value.uploading && !value.held && value.ref.startsWith("/api/files/") ? value.ref : undefined;
useEffect(() => {
const r = cb.current.rule;
- if (!r || !ref || guest || offered.current.has(ref) || made?.ref === ref || !seconds || seconds <= r.maxSeconds + SLACK) return;
+ if (!r || !ref || guest || offered.current.has(ref) || (made?.ref === ref && made.max <= r.maxSeconds + SLACK) || !seconds || seconds <= r.maxSeconds + SLACK) return;
let gone = false;
void (async () => {
const size = await storedSize(ref);
const index = size ? await readMp4Index(rangeReader(ref), size).catch(() => null) : null;
- if (gone || !index || latest.current?.ref !== ref) return;
+ if (gone || latest.current?.ref !== ref) return;
+ if (!index) return setUncut(ref);
offered.current.add(ref);
setOffer({ source: ref, name: latest.current.name, seconds: index.seconds || seconds, index, stored: latest.current });
})();
return () => {
gone = true;
};
- }, [ref, seconds, guest, made]);
+ }, [ref, seconds, guest, made, tick]);
// An offer belongs to the clip it was made for.
const offerGone = !!offer && (offer.stored ? value?.ref !== offer.stored.ref : !!value && !value.uploading);
@@ -169,7 +176,7 @@ export function useClipFit({
const line = `Using ${clock(cut.from)}–${clock(cut.from + cut.seconds)} for ${r.for}`;
if (!o.stored) {
const file = partFile(o.source as Blob, cut.parts, o.name);
- expect.current = { name: file.name, line };
+ expect.current = { name: file.name, line, max: r.maxSeconds };
return cb.current.upload(file);
}
const token = nanoid(8);
@@ -184,7 +191,7 @@ export function useClipFit({
const asset = await postFile(file);
if (latest.current?.id !== token) return;
cb.current.setValue({ ref: asset.url, preview: asset.url, kind: asset.kind ?? "video", name: file.name, source: "upload" });
- setMade({ ref: asset.url, line });
+ setMade({ ref: asset.url, line, max: r.maxSeconds });
} catch (e) {
if (latest.current?.id !== token) return;
cb.current.setValue({ ...stored, uploading: false });
@@ -197,26 +204,37 @@ export function useClipFit({
);
const shownOffer = offer && !offerGone && rule ? offer : null;
- const line = busy ? "Cutting the part…" : (error ?? (made && landed === made.ref ? made.line : null));
+ const line = busy
+ ? "Cutting the part…"
+ : (error ?? (made && landed === made.ref ? made.line : uncut && uncut === ref ? "This clip can't be cut here (MP4 and MOV only): trim it in another app and add it again" : null));
return {
on,
wants,
take,
busy,
line,
- failedNow: !!error && !busy,
+ failedNow: (!!error || (!!uncut && uncut === ref)) && !busy,
+ /** The stored clip in the slot had its part offered and the offer was cancelled. */
+ declined: !!ref && declined === ref && !offer,
+ /** Offer the stored clip's part again (after a Cancel). */
+ again: () => {
+ offered.current.clear();
+ setDeclined(null);
+ setTick((t) => t + 1);
+ },
offer: shownOffer
? {
...shownOffer,
max: rule!.maxSeconds,
min: rule!.minSeconds,
- line: lineFor(shownOffer.seconds, rule!.maxSeconds, rule!),
+ line: rule!.line ?? lineFor(shownOffer.seconds, rule!.maxSeconds, rule!),
use: (a: number, b: number) => void use(a, b),
cancel: () => {
const o = shownOffer;
setOffer(null);
+ if (o.stored) setDeclined(o.stored.ref);
// A clip picked here and not cut goes in as it is: the tool's own check says why it can't take it.
- if (!o.stored) cb.current.upload(o.source as File);
+ else cb.current.upload(o.source as File);
},
}
: null,
diff --git a/src/components/av/fit-list.tsx b/src/components/av/fit-list.tsx
new file mode 100644
index 00000000..0cab2ab5
--- /dev/null
+++ b/src/components/av/fit-list.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import { Scissors } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { FitClipNote, useClipFit } from "./fit-clip";
+import { FitUploadNote, useFitUpload } from "./fit-upload";
+
+/** An account's sound cap: a part made here stays under it. */
+const SOUND_CAP = 50 * 1024 * 1024;
+
+/** A stored clip or sound in a list (a reference, an element's clip). */
+export type ListItem = { id?: string; ref: string; preview: string; kind?: string; name?: string; uploading?: boolean; held?: string };
+
+/**
+ * One stored clip or sound of a list (references, an element's clip) that is longer than the run takes: a part of it
+ * offered with the shared picker (src/components/av/trim-picker.tsx), cut here and uploaded as a new file in its place
+ * (`replace`). A clip's part is cut from a key frame (MP4 and MOV); a sound's part is an MP3. The owner's switches
+ * apply: with "Offer a part" off, nothing is offered and the page's own line says why the run can't take it. After a
+ * Cancel, a button offers the part again.
+ */
+export function ListFit({
+ item,
+ seconds,
+ kind: askedKind,
+ max: askedMax,
+ min,
+ tool,
+ line: askedLine,
+ label,
+ replace,
+ className,
+}: {
+ /** The one to offer a part of; null: nothing to fit. */
+ item: ListItem | null;
+ /** Its length, as the page read it. */
+ seconds: number | undefined;
+ kind: "audio" | "video";
+ /** The longest part to keep, and the shortest. */
+ max: number | undefined;
+ min?: number;
+ /** Who the part is for: "MiniMax H3". */
+ tool: string;
+ /** The picker's line (why a part is asked). */
+ line?: string;
+ /** Its name on the button after a Cancel: "Clip 2", "Maya's clip". */
+ label: string;
+ /** Put `to` where `from` is in the list. */
+ replace: (from: ListItem, to: SlotValue) => void;
+ className?: string;
+}) {
+ // The fitting step swaps the item for a stand-in while it cuts, then for the part: each swap finds the last one. While
+ // it cuts, the stand-in stays this step's own, even when the page no longer asks for a part of it (an uploading file
+ // isn't counted).
+ const [cutting, setCutting] = useState<{ item: ListItem; max?: number; line?: string; kind: "audio" | "video" } | null>(null);
+ const cur = useRef(item);
+ useEffect(() => {
+ if (item) cur.current = item;
+ });
+ const set = (v: SlotValue | null) => {
+ const from = cur.current;
+ if (!v || !from) return;
+ replace(from, v);
+ const next = { ...v, id: v.id ?? from.id };
+ cur.current = next;
+ setCutting(v.uploading ? { item: next, max: cutting?.max ?? askedMax, line: cutting?.line ?? askedLine, kind: cutting?.kind ?? askedKind } : null);
+ };
+ const shown = cutting?.item ?? item;
+ const { max, line, kind } = cutting ?? { max: askedMax, line: askedLine, kind: askedKind };
+ const value = shown as SlotValue | null;
+ const has = !!shown;
+ const clipRule = useMemo(() => (kind === "video" && has && max ? { for: tool, tool, maxSeconds: max, minSeconds: min, line } : null), [kind, has, tool, max, min, line]);
+ const soundRule = useMemo(
+ () => (kind === "audio" && has && max ? { for: tool, tool, formats: ["*"], maxSeconds: max, minSeconds: min, outMaxBytes: SOUND_CAP, fromVideo: false, line } : null),
+ [kind, has, tool, max, min, line],
+ );
+ const clip = useClipFit({ rule: clipRule, value, seconds, setValue: set, upload: () => {} });
+ const sound = useFitUpload({ rule: soundRule, value, seconds, setValue: set, upload: () => {} });
+ const fit = kind === "video" ? clip : sound;
+ return (
+ <div className={className}>
+ {kind === "video" ? <FitClipNote fit={clip} /> : <FitUploadNote fit={sound} />}
+ {fit.declined && !fit.busy && (
+ <button
+ type="button"
+ onClick={fit.again}
+ className="mb-2 inline-flex min-h-9 items-center gap-1.5 rounded-full border bg-background px-3.5 text-[13px] font-medium text-foreground hover:bg-accent"
+ >
+ <Scissors className="size-3.5" /> Pick the part of {label}
+ </button>
+ )}
+ </div>
+ );
+}
+
+/**
+ * A list's "add" tile for a guest whose files are kept in this browser (they can't be cut once kept): a clip or sound
+ * longer than `max` gets its part offered before it is added (`add`), with the same picker. Cancel adds it as it is.
+ */
+export function useAddFit({ kind, max, min, tool, add }: { kind: "audio" | "video"; max: number | undefined; min?: number; tool: string; add: (f: File) => void }) {
+ const [value, setValue] = useState<SlotValue | null>(null);
+ const clipRule = useMemo(() => (kind === "video" && max ? { for: tool, tool, maxSeconds: max, minSeconds: min } : null), [kind, tool, max, min]);
+ const soundRule = useMemo(
+ () => (kind === "audio" && max ? { for: tool, tool, formats: ["*"], maxSeconds: max, minSeconds: min, outMaxBytes: SOUND_CAP, fromVideo: false } : null),
+ [kind, tool, max, min],
+ );
+ const cb = useRef(add);
+ useEffect(() => {
+ cb.current = add;
+ });
+ const clip = useClipFit({ rule: clipRule, value: null, setValue: () => {}, upload: (f) => cb.current(f) });
+ const sound = useFitUpload({
+ rule: soundRule,
+ value,
+ setValue,
+ upload: (f) => {
+ setValue(null);
+ cb.current(f);
+ },
+ });
+ const take = (f: File) => {
+ if (kind === "video" && clip.wants(f)) return clip.take(f);
+ if (kind === "audio" && sound.wants(f)) return sound.take(f);
+ cb.current(f);
+ };
+ return { take, note: kind === "video" ? <FitClipNote fit={clip} /> : <FitUploadNote fit={sound} /> };
+}
diff --git a/src/components/av/fit-source.tsx b/src/components/av/fit-source.tsx
index 9ede9e94..38088b99 100644
--- a/src/components/av/fit-source.tsx
+++ b/src/components/av/fit-source.tsx
@@ -34,7 +34,8 @@ export function SourceFit<S extends Source>({
className?: string;
}) {
const value = source as unknown as SlotValue | null;
- const set = (v: SlotValue | null) => setSource(v ? ({ ...(source ?? {}), ...v, kind, duration: undefined } as unknown as S) : null);
+ // The stand-in while a part is cut, then the part: a field the stand-in had (uploading) never outlives it.
+ const set = (v: SlotValue | null) => setSource(v ? ({ ...(source ?? {}), uploading: undefined, held: undefined, ...v, kind, duration: undefined } as unknown as S) : null);
const clipRule = useMemo(() => (kind === "video" && maxSeconds ? { for: tool, tool, maxSeconds, minSeconds } : null), [kind, tool, maxSeconds, minSeconds]);
const soundRule = useMemo(
() => (kind === "audio" && maxSeconds ? { for: tool, tool, formats: ["*"], maxSeconds, minSeconds, outMaxBytes: SOUND_CAP, fromVideo: false } : null),
diff --git a/src/components/av/fit-upload.tsx b/src/components/av/fit-upload.tsx
index db271c46..c8ec0e38 100644
--- a/src/components/av/fit-upload.tsx
+++ b/src/components/av/fit-upload.tsx
@@ -60,7 +60,12 @@ export function useFitUpload({
const [busy, setBusy] = useState(false);
const [error, setError] = useState<{ line: string; at: string | null } | null>(null);
const [offer, setOffer] = useState<Offer | null>(null);
- const [made, setMade] = useState<Set<string>>(() => new Set());
+ // Files this step made, with the longest the rule took then (a stricter rule since may fit one again).
+ const [made, setMade] = useState<Map<string, number>>(() => new Map());
+ const madeFor = (m: Map<string, number>, ref: string, max = Infinity) => new Map(m).set(ref, max);
+ // A stored file whose offer was cancelled (again() offers it once more).
+ const [declined, setDeclined] = useState<string | null>(null);
+ const [tick, setTick] = useState(0);
const failed = useRef(new Set<string>());
const latest = useRef(value);
const cb = useRef({ setValue, upload, rule });
@@ -75,7 +80,7 @@ export function useFitUpload({
const landed = value && !value.uploading ? (value.held ?? value.ref) || undefined : undefined;
useEffect(() => {
if (!expect.current || value?.uploading) return;
- if (value?.name === expect.current && landed) setMade((m) => new Set(m).add(landed));
+ if (value?.name === expect.current && landed) setMade((m) => madeFor(m, landed, cb.current.rule?.maxSeconds));
expect.current = null;
}, [value, landed]);
@@ -151,7 +156,7 @@ export function useFitUpload({
const asset = await postFile(mp3);
if (latest.current?.id !== token) return;
cb.current.setValue({ ref: asset.url, preview: asset.url, kind: asset.kind ?? "audio", name: mp3.name, source: "upload" });
- setMade((m) => new Set(m).add(asset.url));
+ setMade((m) => madeFor(m, asset.url, cb.current.rule?.maxSeconds));
},
(why) => {
failed.current.add(v.ref);
@@ -176,7 +181,7 @@ export function useFitUpload({
if (plan.kind === "trim") {
if (stored) offered.current.add(stored.ref);
else cb.current.setValue(null);
- return setOffer({ source, name, seconds: plan.seconds, max: plan.max, min: r.minSeconds, line: plan.line, stored });
+ return setOffer({ source, name, seconds: plan.seconds, max: plan.max, min: r.minSeconds, line: r.line ?? plan.line, stored });
}
if (stored) convertStored(stored, { kbps: plan.kbps });
else convertFile(source as Blob, name, { kbps: plan.kbps });
@@ -215,7 +220,7 @@ export function useFitUpload({
// A file already stored that the tool can't take as it is (a library pick, a Reuse): fitted once, at once.
const ref = rule && value && !value.uploading && !value.held && value.ref.startsWith("/api/files/") ? value.ref : undefined;
useEffect(() => {
- if (!rule || !ref || skip || guest || failed.current.has(ref) || offered.current.has(ref) || made.has(ref)) return;
+ if (!rule || !ref || skip || guest || failed.current.has(ref) || offered.current.has(ref) || (made.has(ref) && (!rule.maxSeconds || rule.maxSeconds + 0.05 >= made.get(ref)!))) return;
const v = latest.current;
if (!v) return;
let gone = false;
@@ -237,7 +242,7 @@ export function useFitUpload({
return () => {
gone = true;
};
- }, [rule, ref, skip, guest, made, seconds, follow]);
+ }, [rule, ref, skip, guest, made, seconds, follow, tick]);
// An offer belongs to the file it was made for: another file in the slot (or a stored one taken out) ends it.
const offerGone = !!offer && (offer.stored ? value?.ref !== offer.stored.ref : !!value && !value.uploading);
@@ -262,6 +267,7 @@ export function useFitUpload({
const cancelOffer = useCallback((o: Offer) => {
if (o.source instanceof Blob) forgetDecoded(o.source);
+ if (o.stored) setDeclined(o.stored.ref);
setOffer(null);
}, []);
@@ -278,6 +284,15 @@ export function useFitUpload({
busy,
line,
failedNow: !!shownError && !busy,
+ /** The stored file in the slot had its part offered and the offer was cancelled. */
+ declined: !!ref && declined === ref && !offer,
+ /** Offer the stored file's part again (after a Cancel). */
+ again: () => {
+ offered.current.clear();
+ failed.current.clear();
+ setDeclined(null);
+ setTick((t) => t + 1);
+ },
offer: offer && !offerGone ? { ...offer, use: usePart, cancel: () => cancelOffer(offer) } : null,
};
}
diff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsx
index 6ac80584..4546e99e 100644
--- a/src/components/cinema/prompt-bar.tsx
+++ b/src/components/cinema/prompt-bar.tsx
@@ -29,6 +29,7 @@ import {
IMAGE_ASPECTS,
IMAGE_RESOLUTIONS,
ORIGINAL_LINES,
+ REFERENCE_LIMITS,
VIDEO_ASPECTS,
checkReferences,
videoResolutionsFor,
@@ -36,7 +37,12 @@ import {
planCinema,
type DirectorSettings,
} from "@/lib/catalog/cinema";
-import { findMentions, type StudioElement } from "@/lib/catalog/elements";
+import { applyMentions, findMentions, type StudioElement } from "@/lib/catalog/elements";
+import { referenceWindow, trimLine, trimTarget, windowProblem, type ClipWindow } from "@/lib/av/reference-fit";
+import { ListFit } from "@/components/av/fit-list";
+import { ElementClipFix, useElementClipCheck } from "@/components/av/element-clip-fit";
+import { useMediaSeconds } from "@/components/studio/reference-tray";
+import type { SlotValue } from "@/components/studio/media-slot";
import type { Engine, MediaKind } from "@/lib/catalog/types";
import { formatCost } from "@/lib/format";
import { modKey } from "@/lib/keys";
@@ -344,12 +350,47 @@ export function PromptBar(props: PromptBarProps) {
const model = plan.model;
const mentions = useMemo(() => findMentions(draft.prompt, elements), [draft.prompt, elements]);
const characters = mentions.filter((e) => e.kind === "character");
- const refCheck = checkReferences({
+ // How many references (the studio's limits). Their lengths are checked below, against the model the take runs on.
+ const refCount = checkReferences({
images: draft.refs.filter((r) => r.kind === "image").length,
- videos: draft.refs.filter((r) => r.kind === "video").map((r) => r.duration ?? NaN),
- audios: draft.refs.filter((r) => r.kind === "audio").map((r) => r.duration ?? NaN),
+ videos: draft.refs.filter((r) => r.kind === "video").map(() => NaN),
+ audios: draft.refs.filter((r) => r.kind === "audio").map(() => NaN),
elements: mentions.length,
});
+ // Reference clips and sound held to the window of the model the take runs on (MiniMax H3 and H3 Max Turbo: 2–15 s each,
+ // 15 s together; Vidu Q4's voices: 3–12 s), else the studio's own (2–30 s, 30 s together): what is wrong is said
+ // before the run, and a part of the clip or sound to cut is offered with the picker.
+ const mainRequest = plan.steps.find((s) => s.key === "main")?.request;
+ const runModel = mainRequest ? getModel(mainRequest.modelId) : undefined;
+ const clipRefs = draft.refs.filter((r) => r.kind === "video" || r.kind === "audio");
+ const clipSeconds = useMediaSeconds(clipRefs as unknown as SlotValue[]);
+ const refLists = (["video", "audio"] as const).map((kind) => {
+ const key = kind === "video" ? "videos" : "audios";
+ const items = clipRefs.filter((r) => r.kind === kind);
+ const seconds = items.map((r) => {
+ const s = clipSeconds[clipRefs.indexOf(r)] ?? r.duration;
+ return s !== undefined && Number.isFinite(s) ? s : undefined;
+ });
+ const own: ClipWindow = { min: REFERENCE_LIMITS.clipMin, max: REFERENCE_LIMITS.clipMax, total: kind === "video" ? REFERENCE_LIMITS.totalVideo : REFERENCE_LIMITS.totalAudio };
+ const sent = !!mainRequest?.inputs?.[key]?.length;
+ const window = (sent ? referenceWindow(runModel, key, own) : own) ?? own;
+ const words = { model: sent && runModel ? runModel.name : "Cinema Studio", label: (i: number) => `${kind === "video" ? "Video" : "Audio"} ${i + 1}`, all: kind === "video" ? "The reference videos" : "The reference audio files" };
+ const target = trimTarget(seconds, window);
+ return { kind, items, seconds, window, words, problem: windowProblem(seconds, window, words), target };
+ });
+ const refCheck = refCount ?? refLists.find((l) => l.problem)?.problem ?? null;
+ const fitList = refLists.find((l) => l.target);
+ const fitItem = fitList?.target ? fitList.items[fitList.target.index] : null;
+ /** A reference swapped for its part (a stand-in while it is cut): its length is read again once it lands. */
+ const replaceRef = (from: { id?: string }, to: SlotValue) =>
+ setDraft((d) => ({
+ refs: d.refs.map((r) => (r.id === from.id ? { ...r, id: to.id ?? r.id, ref: to.ref, preview: to.preview, name: to.name ?? r.name, uploading: to.uploading, duration: to.uploading ? r.duration : undefined } : r)),
+ }));
+ const elementCheck = useElementClipCheck(
+ runModel,
+ runModel && mainRequest && mentions.length ? applyMentions(mainRequest, runModel, elements).request : undefined,
+ mentions,
+ );
const demo = placeholdersOn(status?.demoMode);
const cost = demo ? 0 : plan.costUsd;
const overCap = costCapUsd != null && cost != null && cost > 0 && spentUsd + cost > costCapUsd + 1e-9;
@@ -364,6 +405,7 @@ export function PromptBar(props: PromptBarProps) {
const blocker = uploading
? "Uploading…"
: (refCheck ??
+ elementCheck.problem ??
plan.blocker ??
(overCap ? `Over the project's ${formatUsd(costCapUsd)} limit (≈ ${formatUsd(spentUsd)} spent) — raise it in project settings` : undefined) ??
(poolRun.off ? pool?.text : undefined));
@@ -704,12 +746,25 @@ export function PromptBar(props: PromptBarProps) {
const n: Record<string, number> = {};
return draft.refs.map((r) => {
const i = (n[r.kind] = (n[r.kind] ?? -1) + 1);
- return <RefThumb key={r.id} r={r} index={i} startFrame={r.kind === "image" && i === 0 && video && action === "generate" && !refMode} onRemove={() => setDraft((d) => ({ refs: d.refs.filter((x) => x.id !== r.id) }))} />;
+ return <RefThumb key={r.id} r={r.duration === undefined && clipRefs.includes(r) ? { ...r, duration: clipSeconds[clipRefs.indexOf(r)] } : r} index={i} startFrame={r.kind === "image" && i === 0 && video && action === "generate" && !refMode} onRemove={() => setDraft((d) => ({ refs: d.refs.filter((x) => x.id !== r.id) }))} />;
});
})()}
<AddRef onFiles={addRefs} onPick={(r) => setDraft((d) => ({ refs: [...d.refs, r] }))} />
{!draft.refs.length && <span className="hidden text-[12px] text-muted-foreground sm:inline">Start frame, references, clips or audio — or @ a character</span>}
</div>
+ {/* A reference clip or sound longer than the take's model takes: the part to use, picked here. */}
+ <ListFit
+ className="px-2"
+ item={fitItem}
+ seconds={fitList?.target ? fitList.seconds[fitList.target.index] : undefined}
+ kind={fitList?.kind ?? "video"}
+ max={fitList?.target?.max}
+ min={fitList?.window.min}
+ tool={fitList?.words.model ?? ""}
+ line={fitList?.target ? trimLine(fitList.seconds, fitList.target, fitList.window, fitList.words) : undefined}
+ label={fitList?.target ? fitList.words.label(fitList.target.index) : ""}
+ replace={replaceRef}
+ />
{video && <MoveChips moves={draft.moves} onChange={(moves) => setDraft(withMoves(draft, moves))} />}
{video && action === "generate" && takesExact(draft.moves[0]) && (
@@ -752,6 +807,7 @@ export function PromptBar(props: PromptBarProps) {
})}
</div>
)}
+ <ElementClipFix check={elementCheck} className="px-2" />
{/* Director's Panel */}
{/* Narrow bars scroll this row (with faded edges where more chips hide); wide ones wrap it. Phones fold it into the Director chip below. */}
@@ -942,7 +998,7 @@ export function PromptBar(props: PromptBarProps) {
)}
{/* Why Generate can't run, in words (touch screens never see the tooltip). */}
{blocker && (
- <p id={blockerId} className={cn("px-2 pt-1 text-[11.5px] leading-snug", quietBlocker ? "sr-only" : refCheck || overCap ? "text-destructive" : "text-muted-foreground")}>
+ <p id={blockerId} className={cn("px-2 pt-1 text-[11.5px] leading-snug", quietBlocker ? "sr-only" : refCheck || elementCheck.problem || overCap ? "text-destructive" : "text-muted-foreground")}>
{blocker}
</p>
)}
diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsx
index 63083f82..ecd6e546 100644
--- a/src/components/elements-view.tsx
+++ b/src/components/elements-view.tsx
@@ -25,6 +25,9 @@ import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Skeleton } from "@/components/ui/skeleton";
import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { useMediaSeconds } from "@/components/studio/reference-tray";
+import { ListFit } from "@/components/av/fit-list";
+import { ELEMENT_CLIP_MODEL, elementClipWindow, trimTarget } from "@/lib/av/reference-fit";
import { ELEMENT_ICONS } from "@/components/studio/prompt-input";
import { VoiceRecorder } from "@/components/studio/voice-recorder";
import { useMaybeClean } from "@/components/audio-tools/clean-voice-switch";
@@ -77,44 +80,69 @@ function PhotoGrid({ photos, setPhotos }: { photos: SlotValue[]; setPhotos: Reac
);
}
};
+ // A clip attached as the element (Kling 4.0 takes one of 3–8 s): a part of a longer one is offered here, before any run.
+ const clips = photos.filter((p) => p.kind === "video");
+ const clipSeconds = useMediaSeconds(clips);
+ const w = elementClipWindow();
+ const t = w ? trimTarget(clipSeconds, w) : null;
+ const fit = t ? { item: clips[t.index], seconds: clipSeconds[t.index]! } : null;
return (
- <div
- className="flex flex-wrap gap-2"
- onDragOver={(e) => e.preventDefault()}
- onDrop={(e) => {
- e.preventDefault();
- addFiles(e.dataTransfer.files);
- }}
- >
- {photos.map((p) => (
- <div key={p.id} className="relative size-20 overflow-hidden rounded-xl border bg-muted">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={p.preview} alt="" className="size-full object-cover" />
- {p.uploading && (
- <div className="absolute inset-0 grid place-items-center bg-background/60">
- <Loader2 className="size-4 animate-spin" />
- </div>
- )}
- <button
- onClick={() => setPhotos((ps) => ps.filter((x) => x.id !== p.id))}
- className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"
- aria-label="Remove photo"
- >
- <X className="size-3" />
- </button>
- </div>
- ))}
- {photos.length < MAX_PHOTOS && (
- <MediaSlot
- label="Add photos"
- kind="image"
- value={null}
- onChange={(v) => v && setPhotos((ps) => [...ps, { ...v, id: nanoid(6) }])}
- onFile={(f) => addFiles([f])}
- size="lg"
+ <>
+ <div
+ className="flex flex-wrap gap-2"
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ addFiles(e.dataTransfer.files);
+ }}
+ >
+ {photos.map((p) => (
+ <div key={p.id} className="relative size-20 overflow-hidden rounded-xl border bg-muted">
+ {p.kind === "video" ? (
+ <video src={`${p.preview}#t=0.1`} muted playsInline preload="metadata" className="size-full object-cover" />
+ ) : (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={p.preview} alt="" className="size-full object-cover" />
+ )}
+ {p.uploading && (
+ <div className="absolute inset-0 grid place-items-center bg-background/60">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ )}
+ <button
+ onClick={() => setPhotos((ps) => ps.filter((x) => x.id !== p.id))}
+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-foreground/80 text-background"
+ aria-label="Remove photo"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {photos.length < MAX_PHOTOS && (
+ <MediaSlot
+ label="Add photos"
+ kind="image"
+ value={null}
+ onChange={(v) => v && setPhotos((ps) => [...ps, { ...v, id: nanoid(6) }])}
+ onFile={(f) => addFiles([f])}
+ size="lg"
+ />
+ )}
+ </div>
+ {w && (
+ <ListFit
+ item={fit?.item ?? null}
+ seconds={fit?.seconds}
+ kind="video"
+ max={w.max}
+ min={w.min}
+ tool={ELEMENT_CLIP_MODEL.name}
+ line={fit ? `This clip is ${Math.round(fit.seconds * 10) / 10} s. ${ELEMENT_CLIP_MODEL.name} takes ${w.min}–${w.max} s clips as elements: pick the part to use` : undefined}
+ label="the clip"
+ replace={(from, to) => setPhotos((ps) => ps.map((p) => ((from.id ? p.id === from.id : p.ref === from.ref) ? { ...to, id: to.id ?? p.id } : p)))}
/>
)}
- </div>
+ </>
);
}
@@ -140,7 +168,7 @@ function ElementForm({ onOpenChange, element, defaultKind = "character", onSaved
const [kind, setKind] = useState<ElementKind>(element?.kind ?? defaultKind);
const [name, setName] = useState(element?.name ?? "");
const [description, setDescription] = useState(element?.description ?? "");
- const [photos, setPhotos] = useState<SlotValue[]>(() => (element?.references ?? []).map((r) => ({ id: nanoid(6), ref: r, preview: r, kind: "image" })));
+ const [photos, setPhotos] = useState<SlotValue[]>(() => (element?.references ?? []).map((r) => ({ id: nanoid(6), ref: r, preview: r, kind: /\.(mp4|mov|m4v|webm)(\?|#|$)/i.test(r) ? "video" : "image" })));
const uploading = photos.some((p) => p.uploading);
const refs = photos.filter((p) => p.ref).map((p) => p.ref);
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 75853291..fa71de62 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -18,6 +18,9 @@ import { LYRICS_PARAM, SONG_ID_PARAM, songFormat, songToolProblem, withSongId }
import { murekaSongRule, SONG_FIT_OPS } from "@/lib/av/song-fit";
import { FitUploadNote, useFitUpload } from "@/components/av/fit-upload";
import { FitClipNote, useClipFit } from "@/components/av/fit-clip";
+import { ListFit, useAddFit, type ListItem } from "@/components/av/fit-list";
+import { ElementClipFix, useElementClipCheck } from "@/components/av/element-clip-fit";
+import { trimLine, trimTarget } from "@/lib/av/reference-fit";
import { FitCropNote, useCropFit } from "@/components/av/fit-crop";
import { fitStill, stillEndpoint } from "@/components/av/fit-still";
import { portraitRatio } from "@/lib/catalog/clip-windows";
@@ -45,7 +48,7 @@ import { ExactOrbitControls } from "@/components/exact-orbit-controls";
import { useFlyAround } from "@/components/fly-around-run";
import { exactDefaults, takesExact, type ExactOrbit } from "@/lib/exact-orbit";
import { placeOf } from "@/lib/place-name";
-import { askToSignUp, CONNECT_GPU_EVENT, engineForNextPage, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useIsOwner, useLikelyVisitor, useNewestRun, useStatus } from "@/lib/api";
+import { askToSignUp, CONNECT_GPU_EVENT, engineForNextPage, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useIsGuest, useIsOwner, useLikelyVisitor, useNewestRun, useStatus } from "@/lib/api";
import { keyTurnedDown, keyTurnedDownWords, siteRunOf, siteRunRequest } from "@/lib/site-run";
import { usePagePlace } from "@/components/gpu/use-page-place";
import { applyMentions, elementsNote, type StudioElement } from "@/lib/catalog/elements";
@@ -121,7 +124,7 @@ import { openModelPicker } from "@/lib/open-model-picker";
import { GpuReadinessLine } from "@/components/gpu/file-steps";
import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
import { cn } from "@/lib/utils";
-import { h3ReferenceProblem, openReferenceMode } from "@/lib/h3-references";
+import { H3_REFERENCE_LIMITS, h3ReferenceProblem, openReferenceMode } from "@/lib/h3-references";
import { badgeFor, badgeText, dropGpuRetry, openGpuSetup, setGpuRetry, useGpuBadges } from "@/hooks/use-gpu";
import { AttachMenu } from "./attach-menu";
import { useAttach, useComposerBridge, useUploadReaper } from "./attachments";
@@ -875,6 +878,35 @@ export function Composer({ docked }: { docked: boolean }) {
? h3ReferenceProblem({ images: refImages, videos: refSeconds.slice(0, refClips.length), audios: refSeconds.slice(refClips.length) })
: null;
if (refProblem && !planError) planError = refProblem;
+ // A reference clip or voice longer than H3 takes (15 s each, 15 s of each kind together): the part to use is offered.
+ const refWindow = { min: H3_REFERENCE_LIMITS.minSec, max: H3_REFERENCE_LIMITS.maxSec, total: H3_REFERENCE_LIMITS.groupSec };
+ const refFit = (() => {
+ if (!refMode || framesOn) return null;
+ const lists = [
+ { kind: "video" as const, items: refClips, seconds: refSeconds.slice(0, refClips.length), one: "Clip", all: "The clips" },
+ { kind: "audio" as const, items: refAudios, seconds: refSeconds.slice(refClips.length), one: "Voice", all: "The voice and music clips" },
+ ];
+ for (const l of lists) {
+ const t = trimTarget(l.seconds, refWindow);
+ if (!t) continue;
+ const words = { model: "H3", label: (i: number) => `${l.one} ${i + 1}`, all: l.all };
+ return { ...l, target: t, item: l.items[t.index], line: trimLine(l.seconds, t, refWindow, words), label: words.label(t.index) };
+ }
+ return null;
+ })();
+ // A clip or voice swapped for its part (a stand-in while it is cut), in whichever list holds it.
+ const replaceRef = (from: ListItem, to: SlotValue) =>
+ setDraft((d) => {
+ const swap = (l?: SlotValue[]) => l?.map((r) => ((from.id ? r.id === from.id : r.ref === from.ref) ? { ...to, id: to.id ?? r.id } : r));
+ return { refClips: swap(d.refClips), refAudios: swap(d.refAudios) };
+ });
+ // A guest's clips and voices are kept in this browser: a long one gets its part offered before it is added.
+ const guest = useIsGuest();
+ const clipAdd = useAddFit({ kind: "video", max: refMode && guest ? H3_REFERENCE_LIMITS.maxSec : undefined, min: H3_REFERENCE_LIMITS.minSec, tool: "H3", add: (f) => attach.addListFile("refClips", f, refMode?.videos ?? 0) });
+ const voiceAdd = useAddFit({ kind: "audio", max: refMode && guest ? H3_REFERENCE_LIMITS.maxSec : undefined, min: H3_REFERENCE_LIMITS.minSec, tool: "H3", add: (f) => attach.addListFile("refAudios", f, refMode?.audios ?? 0) });
+ // Clip elements mentioned by name (Kling 4.0: 3–8 s each, 30 s of clips in all): said before the run, with the fix.
+ const elementCheck = useElementClipCheck(catalog.getModel(mentions.request.modelId) ?? model, mentions.request, mentions.mentioned);
+ if (elementCheck.problem && !planError) planError = elementCheck.problem;
// An end frame runs first and last frames only: References mode's extra images, clips and sound would be left out.
// It goes before "Write a prompt first": words won't fix it.
if (refMode && !framesOn && draft.slots.endImage?.ref && (draft.refs.length || refClips.length || refAudios.length) && (!planError || planError === WRITE_PROMPT)) {
@@ -1793,7 +1825,7 @@ export function Composer({ docked }: { docked: boolean }) {
audios={refAudios}
images={refImages}
limits={refMode}
- onFile={attach.addListFile}
+ onFile={(list, f, max) => (!guest ? attach.addListFile(list, f, max) : list === "refClips" ? clipAdd.take(f) : voiceAdd.take(f))}
onPick={attach.addToList}
onRemove={attach.removeFromList}
/>
@@ -1803,6 +1835,23 @@ export function Composer({ docked }: { docked: boolean }) {
{showAttachments && !collapsed && !framesOn && refMode && (refsOpen || refClips.length > 0 || refAudios.length > 0) && (
<ReferenceOrder images={refImages} clips={refClips.length} audios={refAudios.length} problem={refProblem} />
)}
+ {showAttachments && !collapsed && !framesOn && refMode && (
+ <div className="px-3">
+ {clipAdd.note}
+ {voiceAdd.note}
+ <ListFit
+ item={refFit?.item ?? null}
+ seconds={refFit ? refFit.seconds[refFit.target.index] : undefined}
+ kind={refFit?.kind ?? "video"}
+ max={refFit?.target.max}
+ min={H3_REFERENCE_LIMITS.minSec}
+ tool="H3"
+ line={refFit?.line}
+ label={refFit?.label ?? ""}
+ replace={replaceRef}
+ />
+ </div>
+ )}
{showAttachments && !collapsed && !framesOn && <FitUploadNote fit={songFit} className="px-3" />}
{showAttachments && !collapsed && !framesOn && <FitClipNote fit={clipFit} className="px-3" />}
{showAttachments && !collapsed && !framesOn && <FitUploadNote fit={sampleFit} className="px-3" />}
@@ -1863,7 +1912,9 @@ export function Composer({ docked }: { docked: boolean }) {
<TooltipTrigger asChild>
<span className={cn("inline-flex h-7 items-center gap-1.5 rounded-full border bg-background pr-2.5 pl-0.5 text-[12px] font-medium", words && "border-dashed text-muted-foreground")}>
<span className="grid size-6 place-items-center overflow-hidden rounded-full bg-muted">
- {el.references[0] ? (
+ {el.references[0] && /\.(mp4|mov|m4v|webm)(\?|#|$)/i.test(el.references[0]) ? (
+ <video src={`${el.references[0]}#t=0.1`} muted playsInline preload="metadata" className="size-full object-cover" />
+ ) : el.references[0] ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={el.references[0]} alt="" className="size-full object-cover" />
) : (
@@ -1881,6 +1932,7 @@ export function Composer({ docked }: { docked: boolean }) {
})}
</div>
)}
+ <ElementClipFix check={elementCheck} className="px-2" />
{/* Upscale → Video: Restore · faithful, Quick · RTX and (while it is offered) Regenerate · creative side by side (on your GPU). */}
{config.finishChoices && !preset && (
diff --git a/src/lib/av/fit-upload.ts b/src/lib/av/fit-upload.ts
index 631867b9..766f0d60 100644
--- a/src/lib/av/fit-upload.ts
+++ b/src/lib/av/fit-upload.ts
@@ -38,6 +38,8 @@ export interface AudioFitRule {
trim?: boolean;
/** False: a video file is not this slot's (its sound isn't taken from it). */
fromVideo?: boolean;
+ /** The picker's line, when the page says it its own way (a part to cut so sounds fit together). */
+ line?: string;
}
/** The largest file read in the browser to fit it: the app's own upload limit (MAX_MB in media-slot.tsx, /api/uploads). */
diff --git a/src/lib/av/reference-fit.ts b/src/lib/av/reference-fit.ts
new file mode 100644
index 00000000..420854e6
--- /dev/null
+++ b/src/lib/av/reference-fit.ts
@@ -0,0 +1,167 @@
+import { clipTotalSeconds, elementClipSeconds, referenceSeconds, referenceVoiceSeconds } from "@/lib/catalog/clip-windows";
+import type { StudioElement } from "@/lib/catalog/elements";
+import type { GenerationRequest, ModelDef } from "@/lib/catalog/types";
+import { H3_REFERENCE_LIMITS, openReferenceMode } from "@/lib/h3-references";
+
+/**
+ * Reference clips and sound held to a length: each one between `min` and `max` seconds, and (where the model says) at most
+ * `total` seconds of them together. Which one to offer a part of (src/components/av/trim-picker.tsx), and what to say.
+ * Pure, so Cinema Studio's references, the H3 reference tray, Kling 4.0's clip elements and the tests share it.
+ * - A clip or sound over `max`: a part of it is offered.
+ * - All of them together over `total`: how much to cut is said, and a part of the longest one is offered.
+ * - One under `min` can't be made longer: it is said, with what to do.
+ */
+
+export interface ClipWindow {
+ min: number;
+ max: number;
+ /** The most seconds of them together. */
+ total?: number;
+}
+
+/** A header's length can run a frame or so past the cut that made it: a few hundredths over are let through. */
+const SLACK = 0.05;
+
+const sec = (n: number) => `${Math.round(n * 10) / 10} s`;
+
+/**
+ * The window a model holds its reference clips ("videos") or sound ("audios") to, or `fallback` (the studio's own):
+ * MiniMax H3 and H3 Max Turbo in the cloud (2–15 s each, 15 s together), Vidu Q4's voices (3–12 s each), H3 on your GPU
+ * (Pika's limits, the same).
+ */
+export function referenceWindow(model: Pick<ModelDef, "id" | "engine" | "routes" | "options"> | undefined, kind: "videos" | "audios", fallback?: ClipWindow): ClipWindow | undefined {
+ if (!model) return fallback;
+ if (model.engine !== "open") {
+ const hosted = referenceSeconds(model.id);
+ if (hosted?.kinds.includes(kind)) return { min: hosted.min, max: hosted.max, total: hosted.total };
+ const voice = kind === "audios" ? referenceVoiceSeconds(model.id) : undefined;
+ if (voice) return { ...voice };
+ } else if (openReferenceMode(model as ModelDef)) {
+ const L = H3_REFERENCE_LIMITS;
+ return { min: L.minSec, max: L.maxSec, total: L.groupSec };
+ }
+ return fallback;
+}
+
+export interface TrimTarget {
+ /** Which one (its place in the list). */
+ index: number;
+ /** The longest part of it to keep. */
+ max: number;
+ /** Seconds to cut from them together (when they are over `total`). */
+ over?: number;
+}
+
+/**
+ * The one to offer a part of: the first over `max` (the part is up to `max`); else, when they are over `total` together,
+ * the longest that can still be cut (the part keeps what fits, never under `min`). Null when they fit, or nothing can
+ * be cut. A length not known yet counts as nothing.
+ */
+export function trimTarget(seconds: readonly (number | undefined)[], w: ClipWindow): TrimTarget | null {
+ for (const [index, s] of seconds.entries()) if (s !== undefined && s > w.max + SLACK) return { index, max: w.max };
+ if (w.total === undefined) return null;
+ const sum = seconds.reduce<number>((a, s) => a + (s ?? 0), 0);
+ const over = sum - w.total;
+ if (over <= SLACK) return null;
+ let index = -1;
+ for (const [i, s] of seconds.entries()) if (s !== undefined && s > w.min + SLACK && (index < 0 || s > seconds[index]!)) index = i;
+ if (index < 0) return null;
+ const keep = Math.floor((seconds[index]! - over) * 10) / 10;
+ return { index, max: Math.max(w.min, keep), over: Math.ceil(over * 10) / 10 };
+}
+
+export interface WindowWords {
+ /** The model's name: "MiniMax H3". */
+ model: string;
+ /** One of them by its place: "Clip 2", "Voice 1". */
+ label: (index: number) => string;
+ /** All of them: "The reference clips". */
+ all: string;
+}
+
+/** What is wrong with their lengths, in a line with what to do, or null. */
+export function windowProblem(seconds: readonly (number | undefined)[], w: ClipWindow, words: WindowWords): string | null {
+ for (const [i, s] of seconds.entries()) {
+ if (s === undefined || !(s > 0)) continue;
+ if (s < w.min - SLACK) return `${words.label(i)} is ${sec(s)}, and ${words.model} needs at least ${w.min} s: use a longer one`;
+ if (s > w.max + SLACK) return `${words.label(i)} is ${sec(s)}, and ${words.model} takes up to ${w.max} s: trim it first`;
+ }
+ if (w.total === undefined) return null;
+ const sum = seconds.reduce<number>((a, s) => a + (s ?? 0), 0);
+ if (sum <= w.total + SLACK) return null;
+ return `${words.all} add up to ${sec(sum)}, and ${words.model} takes ${w.total} s of them together: cut ${sec(Math.ceil((sum - w.total) * 10) / 10)}`;
+}
+
+/** The picker's line for a target: why a part is asked, and of which one. */
+export function trimLine(seconds: readonly (number | undefined)[], t: TrimTarget, w: ClipWindow, words: WindowWords): string {
+ const s = seconds[t.index] ?? 0;
+ if (!t.over) return `${words.label(t.index)} is ${sec(s)}. ${words.model} takes up to ${w.max} s: pick the part to use`;
+ const sum = seconds.reduce<number>((a, x) => a + (x ?? 0), 0);
+ return `${words.all} add up to ${sec(sum)}, and ${words.model} takes ${w.total} s together. Cut ${sec(t.over)}: pick the part of ${words.label(t.index)} to keep`;
+}
+
+// ---------------------------------------------------------------------------
+// Clip elements (Kling 4.0: a character or prop given as a 3–8 s clip, with every clip of the run 30 s in all)
+
+/** A clip that goes to the run as one of the model's elements, and the element it belongs to. */
+export interface ElementClip {
+ element: StudioElement;
+ /** The clip (/api/files/…). */
+ ref: string;
+}
+
+/** The mentioned elements whose clip goes to the run as the model's element (the request as applyMentions resolved it). */
+export function elementClips(request: Pick<GenerationRequest, "params" | "inputs">, mentioned: readonly StudioElement[]): ElementClip[] {
+ const videos = request.inputs?.videos ?? [];
+ const out: ElementClip[] = [];
+ for (const g of request.params?.elements ?? []) {
+ const ref = g.video !== undefined ? videos[g.video] : undefined;
+ const element = ref ? mentioned.find((e) => e.references.includes(ref)) : undefined;
+ if (ref && element) out.push({ element, ref });
+ }
+ return out;
+}
+
+/**
+ * Clip elements outside the model's window, in a line with what to do, and the clip to offer a part of: one over its
+ * length, or the longest when the run's clips together (`others`: the clip edited and the reference clips, which aren't
+ * cut here) are over what the model takes in all. Null when they fit, or the model holds clip elements to nothing.
+ */
+export function elementClipCheck(
+ model: Pick<ModelDef, "id" | "name">,
+ clips: readonly { name: string; seconds?: number }[],
+ others = 0,
+): { problem: string; target: (TrimTarget & { min: number; line: string }) | null } | null {
+ const each = elementClipSeconds(model.id);
+ const all = clipTotalSeconds(model.id);
+ if (!each || !clips.length) return null;
+ const seconds = clips.map((c) => c.seconds);
+ for (const [i, s] of seconds.entries()) {
+ if (s === undefined || !(s > 0) || s >= each.min - SLACK) continue;
+ return { problem: `${model.name} takes ${each.min}–${each.max} s clips as elements, and ${clips[i].name}'s is ${sec(s)}: give ${clips[i].name} a longer clip, or photos instead`, target: null };
+ }
+ const w: ClipWindow = { ...each, ...(all !== undefined && { total: Math.max(0, all - others) }) };
+ const t = trimTarget(seconds, w);
+ const name = (i: number) => clips[i].name;
+ if (t && !t.over) {
+ const s = seconds[t.index]!;
+ return {
+ problem: `${model.name} takes ${each.min}–${each.max} s clips as elements, and ${name(t.index)}'s is ${sec(s)}: trim it`,
+ target: { ...t, min: each.min, line: `${name(t.index)}'s clip is ${sec(s)}. ${model.name} takes ${each.min}–${each.max} s clips as elements: pick the part to use` },
+ };
+ }
+ const sum = others + seconds.reduce<number>((a, s) => a + (s ?? 0), 0);
+ if (all === undefined || sum <= all + SLACK) return null;
+ const cut = sec(Math.ceil((sum - all) * 10) / 10);
+ const problem = `The clips add up to ${sec(sum)} (the clip you edit, reference clips and clip elements together), and ${model.name} takes ${all} s in all: cut ${cut}`;
+ return {
+ problem,
+ target: t ? { ...t, min: each.min, line: `The clips add up to ${sec(sum)}, and ${model.name} takes ${all} s in all. Cut ${cut}: pick the part of ${name(t.index)}'s clip to keep` } : null,
+ };
+}
+
+/** The model that takes clips as elements (Kling 4.0, 3–8 s): an element's clip is fitted to it where it is attached. */
+export const ELEMENT_CLIP_MODEL = { id: "kling-4", name: "Kling 4.0" } as const;
+
+/** The window an element's clip is fitted to where it is attached, or undefined. */
+export const elementClipWindow = (): ClipWindow | undefined => elementClipSeconds(ELEMENT_CLIP_MODEL.id);
diff --git a/src/lib/catalog/clip-windows.ts b/src/lib/catalog/clip-windows.ts
index 245a377d..957f00db 100644
--- a/src/lib/catalog/clip-windows.ts
+++ b/src/lib/catalog/clip-windows.ts
@@ -111,6 +111,9 @@ const REFERENCE_VOICE_SECONDS: Record<string, { min: number; max: number }> = {
/** Whether the model holds each reference voice to a length (REFERENCE_VOICE_SECONDS): its headers are read before the run. */
export const hasReferenceVoiceWindow = (model: { id: string }): boolean => model.id in REFERENCE_VOICE_SECONDS;
+/** The length each reference voice may be on the model (REFERENCE_VOICE_SECONDS), or undefined. */
+export const referenceVoiceSeconds = (modelId: string): { min: number; max: number } | undefined => REFERENCE_VOICE_SECONDS[modelId];
+
/** Why reference voice `n` (1-based), `seconds` long, is outside what the model takes, in Generate's words, or null. */
export function referenceVoiceProblem(model: { id: string; name: string }, seconds: number, n = 1): string | null {
const w = REFERENCE_VOICE_SECONDS[model.id];
@@ -259,6 +262,9 @@ export function referenceClipsProblem(model: { id: string; name: string }, kind:
/** 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 } };
+/** The length a clip element may be on the model (ELEMENT_CLIP_SECONDS), or undefined. */
+export const elementClipSeconds = (modelId: string): { min: number; max: number } | undefined => ELEMENT_CLIP_SECONDS[modelId];
+
/** 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];
@@ -282,6 +288,9 @@ export function editClipsProblem(model: { id: string; name: string }, count: num
*/
const CLIP_TOTAL_SECONDS: Record<string, number> = { "kling-4": 30 };
+/** The most seconds of clips a run takes in all on the model (CLIP_TOTAL_SECONDS), or undefined. */
+export const clipTotalSeconds = (modelId: string): number | undefined => CLIP_TOTAL_SECONDS[modelId];
+
/** Why clips `seconds` long in all are too long for the model ("Kling 4.0 takes 30 s of clips in all…"), or null. */
export function clipTotalProblem(model: { id: string; name: string }, seconds: number): string | null {
const max = CLIP_TOTAL_SECONDS[model.id];
diff --git a/src/lib/h3-references.ts b/src/lib/h3-references.ts
index 5bf8e2d8..0f81b3a1 100644
--- a/src/lib/h3-references.ts
+++ b/src/lib/h3-references.ts
@@ -62,7 +62,7 @@ export function h3ReferenceProblem(r: H3References): string | null {
if (s > L.maxSec + 0.05) return `${g.one} ${i + 1} is ${fmt(s)}: trim it to ${L.maxSec} s or less`;
}
const sum = g.list.reduce<number>((a, s) => a + (s ?? 0), 0);
- if (sum > L.groupSec + 0.05) return `${g.all} add up to ${fmt(sum)}: keep them to ${L.groupSec} s together`;
+ if (sum > L.groupSec + 0.05) return `${g.all} add up to ${fmt(sum)}, and H3 takes ${L.groupSec} s of them together: cut ${fmt(Math.ceil((sum - L.groupSec) * 10) / 10)}`;
}
return null;
}
diff --git a/tests/reference-fit.test.ts b/tests/reference-fit.test.ts
new file mode 100644
index 00000000..735381bb
--- /dev/null
+++ b/tests/reference-fit.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from "vitest";
+import { getModel } from "@/lib/catalog";
+import type { StudioElement } from "@/lib/catalog/elements";
+import { elementClipCheck, elementClips, elementClipWindow, referenceWindow, trimLine, trimTarget, windowProblem } from "@/lib/av/reference-fit";
+import { h3ReferenceProblem } from "@/lib/h3-references";
+
+const H3 = { min: 2, max: 15, total: 15 };
+const words = { model: "MiniMax H3", label: (i: number) => `Video ${i + 1}`, all: "The reference videos" };
+
+describe("reference windows", () => {
+ it("takes the window of the model the take runs on", () => {
+ expect(referenceWindow(getModel("minimax-h3"), "videos")).toEqual(H3);
+ expect(referenceWindow(getModel("minimax-h3-max-turbo-refs"), "audios")).toEqual(H3);
+ expect(referenceWindow(getModel("vidu-q4"), "audios")).toEqual({ min: 3, max: 12 });
+ // The extend takes reference sound only: its clips keep the studio's own window.
+ expect(referenceWindow(getModel("minimax-h3-max-turbo-extend"), "videos", { min: 2, max: 30, total: 30 })).toEqual({ min: 2, max: 30, total: 30 });
+ expect(referenceWindow(getModel("oss-minimax-h3"), "videos")).toEqual(H3);
+ expect(referenceWindow(undefined, "videos")).toBeUndefined();
+ });
+});
+
+describe("trimTarget", () => {
+ it("offers a part of the first one over the window", () => {
+ expect(trimTarget([4, 20.3, 30], H3)).toEqual({ index: 1, max: 15 });
+ expect(trimTarget([15.03], H3)).toBeNull();
+ expect(trimTarget([undefined, 9], H3)).toBeNull();
+ });
+
+ it("over the total, says how much to cut and offers the longest", () => {
+ expect(trimTarget([6, 10.4], H3)).toEqual({ index: 1, max: 9, over: 1.4 });
+ // The longest can't give it all (never under 2 s): it keeps 2 s, and the next offer takes the rest.
+ expect(trimTarget([9, 9, 9], H3)).toEqual({ index: 0, max: 2, over: 12 });
+ expect(trimTarget([2, 2, 12], { min: 2, max: 15, total: 15 })).toEqual({ index: 2, max: 11, over: 1 });
+ // Nothing can be cut: none of them is over the shortest allowed.
+ expect(trimTarget([2, 2], { min: 2, max: 15, total: 3 })).toBeNull();
+ });
+
+ it("says what is wrong, and the picker's line", () => {
+ expect(windowProblem([20.3], H3, words)).toBe("Video 1 is 20.3 s, and MiniMax H3 takes up to 15 s: trim it first");
+ expect(windowProblem([1.2], H3, words)).toBe("Video 1 is 1.2 s, and MiniMax H3 needs at least 2 s: use a longer one");
+ expect(windowProblem([6, 10.4], H3, words)).toBe("The reference videos add up to 16.4 s, and MiniMax H3 takes 15 s of them together: cut 1.4 s");
+ expect(windowProblem([6, 9], H3, words)).toBeNull();
+ expect(trimLine([20.3], { index: 0, max: 15 }, H3, words)).toBe("Video 1 is 20.3 s. MiniMax H3 takes up to 15 s: pick the part to use");
+ expect(trimLine([6, 10.4], { index: 1, max: 9, over: 1.4 }, H3, words)).toBe(
+ "The reference videos add up to 16.4 s, and MiniMax H3 takes 15 s together. Cut 1.4 s: pick the part of Video 2 to keep",
+ );
+ });
+
+ it("words the H3 tray's total with how much to cut", () => {
+ expect(h3ReferenceProblem({ images: 1, videos: [8, 9.2], audios: [] })).toBe("The clips add up to 17.2 s, and H3 takes 15 s of them together: cut 2.2 s");
+ });
+});
+
+const el = (id: string, name: string, references: string[]): StudioElement => ({ id, name, handle: name.toLowerCase(), kind: "character", references, loras: [] }) as unknown as StudioElement;
+
+describe("clip elements", () => {
+ const maya = el("e1", "Maya", ["/api/files/maya.mp4", "/api/files/maya.jpg"]);
+ const leo = el("e2", "Leo", ["/api/files/leo.mov"]);
+ const kling = { id: "kling-4", name: "Kling 4.0" };
+
+ it("finds the clips that go as the model's elements", () => {
+ const request = { inputs: { videos: ["/api/files/ref.mp4", "/api/files/maya.mp4", "/api/files/leo.mov"] }, params: { elements: [{ video: 1 }, { images: [0] }, { video: 2 }] } };
+ expect(elementClips(request, [maya, leo]).map((c) => [c.element.name, c.ref])).toEqual([
+ ["Maya", "/api/files/maya.mp4"],
+ ["Leo", "/api/files/leo.mov"],
+ ]);
+ });
+
+ it("offers a part of a clip over 8 s, and says a short one can't be made longer", () => {
+ const long = elementClipCheck(kling, [{ name: "Maya", seconds: 12.4 }]);
+ expect(long?.problem).toBe("Kling 4.0 takes 3–8 s clips as elements, and Maya's is 12.4 s: trim it");
+ expect(long?.target).toMatchObject({ index: 0, max: 8, min: 3 });
+ expect(long?.target?.line).toBe("Maya's clip is 12.4 s. Kling 4.0 takes 3–8 s clips as elements: pick the part to use");
+ const short = elementClipCheck(kling, [{ name: "Maya", seconds: 2 }]);
+ expect(short?.problem).toMatch(/Maya's is 2 s: give Maya a longer clip, or photos instead/);
+ expect(short?.target).toBeNull();
+ expect(elementClipCheck(kling, [{ name: "Maya", seconds: 6 }])).toBeNull();
+ expect(elementClipCheck({ id: "veo-3-1", name: "Veo" }, [{ name: "Maya", seconds: 20 }])).toBeNull();
+ });
+
+ it("over 30 s of clips in all, says how much to cut and offers the longest element's clip", () => {
+ const r = elementClipCheck(kling, [{ name: "Maya", seconds: 8 }, { name: "Leo", seconds: 7 }], 20);
+ expect(r?.problem).toBe("The clips add up to 35 s (the clip you edit, reference clips and clip elements together), and Kling 4.0 takes 30 s in all: cut 5 s");
+ expect(r?.target).toMatchObject({ index: 0, max: 3, over: 5 });
+ expect(r?.target?.line).toMatch(/Cut 5 s: pick the part of Maya's clip to keep$/);
+ });
+
+ it("fits an attached clip to Kling 4.0's window", () => {
+ expect(elementClipWindow()).toEqual({ min: 3, max: 8 });
+ });
+});