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: fit a file in the browser instead of refusing it, across the tools

Adarsh96e7b0dfbcf1
diff --git a/src/components/audio-tools/audio-tools.tsx b/src/components/audio-tools/audio-tools.tsx
index 07251143..53b11a61 100644
--- a/src/components/audio-tools/audio-tools.tsx
+++ b/src/components/audio-tools/audio-tools.tsx
@@ -9,6 +9,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { Slider } from "@/components/ui/slider";
import { Feed } from "@/components/studio/feed";
import { ACCEPT, fileToList, fileToSlot, kindOfFile, LibraryGrid, wrongKindMessage, type SlotValue } from "@/components/studio/media-slot";
+import { SoundAloneButton } from "@/components/av/sound-alone";
import { Segmented } from "@/components/faceless/controls";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
import { useDraft } from "@/components/av/use-draft";
@@ -360,6 +361,10 @@ export function AudioLoopTool() {
}
>
<AudioPlayer clip={clip} onDuration={(duration) => setClip((c) => (c ? { ...c, duration } : c))} />
+ {/* A clip whose length can't be read: an MP3 of it (made here) can be. */}
+ {ready && preview.error && /length can't be read/.test((preview.error as Error).message) && (
+ <SoundAloneButton src={ready.ref} name={ready.name} label="Convert to MP3" className="pt-2" onDone={(f) => setClip({ ref: f.url, preview: f.url, kind: "audio", name: f.name })} />
+ )}
</Panel>
)}
{clip && (
diff --git a/src/components/audio-tools/clean-dialogue-panel.tsx b/src/components/audio-tools/clean-dialogue-panel.tsx
index d172f1fc..1366721b 100644
--- a/src/components/audio-tools/clean-dialogue-panel.tsx
+++ b/src/components/audio-tools/clean-dialogue-panel.tsx
@@ -9,6 +9,7 @@ import { Switch } from "@/components/ui/switch";
import { Segmented } from "@/components/faceless/controls";
import { Panel } from "@/components/av/tool-shell";
import { useGeneration } from "@/components/av/use-generation";
+import { SoundAloneButton } from "@/components/av/sound-alone";
import {
BED_LEVELS,
CLEANERS,
@@ -18,6 +19,7 @@ import {
DEFAULT_CLEANER,
OPEN_NOTE,
RELATION_NOTE,
+ soundAloneHelps,
type BedLevel,
type Cleaner,
} from "@/lib/av/clean-dialogue";
@@ -52,6 +54,7 @@ export function CleanDialoguePanel({
engine,
blocker,
onMixer,
+ onSoundAlone,
}: {
/** The soundtrack, once it's uploaded. */
source: CleanSource | null;
@@ -61,6 +64,8 @@ export function CleanDialoguePanel({
blocker: string | null;
/** Switch to Split into stems (the mixer opens on the Clean dialogue preset). */
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;
}) {
const [bed, setBed] = useState<BedLevel>(DEFAULT_BED);
const [quality, setQuality] = useState<SplitQuality | null>(null);
@@ -197,6 +202,9 @@ export function CleanDialoguePanel({
{busy ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Clean it
</Button>
</div>
+ {source?.kind === "video" && engine === "cloud" && !blocker && soundAloneHelps(error) && onSoundAlone && (
+ <SoundAloneButton src={source.ref} name={source.name} label="Clean the sound alone (MP3)" onDone={onSoundAlone} />
+ )}
</div>
{g && (g.status === "queued" || g.status === "running") && (
diff --git a/src/components/audio-tools/remove-dialogue-tool.tsx b/src/components/audio-tools/remove-dialogue-tool.tsx
index 2c03118c..a7d896be 100644
--- a/src/components/audio-tools/remove-dialogue-tool.tsx
+++ b/src/components/audio-tools/remove-dialogue-tool.tsx
@@ -38,6 +38,7 @@ import { Segmented } from "@/components/faceless/controls";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
import { useGeneration } from "@/components/av/use-generation";
import { useAskBeforeUpload, useEngine, useGenerations } from "@/lib/api";
+import { SourceFit } from "@/components/av/fit-source";
import {
CLOUD_ONLY_REMOVE_PROBLEM,
CLOUD_REMOVE_PROBLEM,
@@ -46,6 +47,7 @@ import {
LOWER_MIN_DB,
OUTCOMES,
REMOVE_DIALOGUE_FEATURE,
+ REMOVE_DIALOGUE_MAX_SECONDS,
REMOVED_STEM,
requestedOutcome,
type DialogueOutcome,
@@ -521,6 +523,7 @@ export function RemoveDialogueTool() {
)}
</Panel>
)}
+ <SourceFit source={source} kind="video" tool="Remove dialogue" maxSeconds={REMOVE_DIALOGUE_MAX_SECONDS} setSource={setSource} />
{source && engine === "cloud" && (
<Panel>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
diff --git a/src/components/audio-tools/speech-edit-tool.tsx b/src/components/audio-tools/speech-edit-tool.tsx
index 1845f4a0..c6f2b0df 100644
--- a/src/components/audio-tools/speech-edit-tool.tsx
+++ b/src/components/audio-tools/speech-edit-tool.tsx
@@ -37,6 +37,7 @@ import {
PROMPT_HELPER_NOTE,
QUALITY_HINTS,
SPEECH_EDIT_FEATURE,
+ SPEECH_EDIT_MAX_SECONDS,
VOLUME_STEPS,
type AukQuality,
type EffectKind,
@@ -46,6 +47,7 @@ import { cn } from "@/lib/utils";
import { BeforeAfterAudio } from "./before-after-audio";
import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";
import { uploadSource } from "./split-tool";
+import { SourceFit } from "@/components/av/fit-source";
/**
* Audio → Edit speech (nm10-speech-edit): add a recording or a video, transcribe it, then change its words (AuK re-speaks
@@ -411,6 +413,7 @@ export function SpeechEditTool({ setup }: { setup?: OwnSetup | null } = {}) {
) : (
<SourcePanel source={source} onDuration={(duration) => setSource((s) => (s ? { ...s, duration } : s))} onRemove={clear} />
)}
+ <SourceFit source={source} kind={source?.kind ?? "audio"} tool="Edit speech" maxSeconds={SPEECH_EDIT_MAX_SECONDS} setSource={setSource} />
{source && engine === "cloud" && (
<Panel>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsx
index 3dc32633..d9740f27 100644
--- a/src/components/audio-tools/split-tool.tsx
+++ b/src/components/audio-tools/split-tool.tsx
@@ -820,6 +820,7 @@ export function SplitSoundtrackTool() {
setGoal("split");
setMixPreset(mixPresetFor("split", true));
}}
+ onSoundAlone={(f) => setSource({ ref: f.url, preview: f.url, kind: "audio", id: nanoid(8), name: f.name })}
/>
)}
{goal === "split" && source && engine === "cloud" && (
diff --git a/src/components/av/fit-clip.tsx b/src/components/av/fit-clip.tsx
new file mode 100644
index 00000000..95d8fdb2
--- /dev/null
+++ b/src/components/av/fit-clip.tsx
@@ -0,0 +1,241 @@
+"use client";
+
+import { Loader2 } from "lucide-react";
+import { nanoid } from "nanoid";
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { useAskBeforeUpload, useIsGuest } from "@/lib/api";
+import { clock } from "@/lib/av/fit-upload";
+import { cutMp4, readMp4Index, type CutPart, type Mp4Index } from "@/lib/av/mp4-cut";
+import { postFile } from "@/lib/upload";
+import { cn } from "@/lib/utils";
+import { readSeconds } from "./fit-audio";
+import { TrimPicker } from "./trim-picker";
+import { useUploadSwitches } from "./use-upload-switches";
+
+/**
+ * The fitting step on a clip slot: a clip longer than the tool takes gets a part offered (src/components/av/trim-picker.tsx)
+ * instead of only a refusal. The part is cut without encoding again (src/lib/av/mp4-cut.ts), from a key frame, so it
+ * keeps its quality and takes a moment. An MP4 or MOV only: another kind of clip, or the owner's "Offer a part" switch off,
+ * leaves the clip as it is, and the tool's own check says why it can't take it.
+ * - A clip picked, dropped or pasted (`take`): offered before it is uploaded.
+ * - A clip already stored (a library pick, a Reuse, one uploaded elsewhere): offered once it is in the slot.
+ * Cancel keeps the clip as it is. While the part is cut and uploaded, the slot shows as uploading.
+ */
+
+export interface ClipFitRule {
+ /** Who the part is for, in the line after it is cut ("for H3 Max"). */
+ for: string;
+ /** The tool's name in the line ("Kandinsky VSR takes up to 0:05"). */
+ tool: string;
+ minSeconds?: number;
+ maxSeconds: number;
+}
+
+type Offer = { source: Blob | string; name?: string; seconds: number; index: Mp4Index; stored?: SlotValue };
+
+/** A part a hair shorter than the tool's limit, so its header never reads a frame over it. */
+const MARGIN = 0.05;
+const SLACK = 0.05;
+
+/** A stored file's bytes by range (its header boxes only). */
+const rangeReader = (url: string) => async (a: number, b: number) => {
+ const res = await fetch(url, { headers: { Range: `bytes=${a}-${b - 1}` } });
+ if (!res.ok) throw new Error(String(res.status));
+ const buf = new Uint8Array(await res.arrayBuffer());
+ // A server that ignores Range sends the whole file: the part asked for is in it.
+ return res.status === 206 ? buf : buf.subarray(a, b);
+};
+const blobReader = (b: Blob) => async (a: number, c: number) => new Uint8Array(await b.slice(a, c).arrayBuffer());
+
+async function storedSize(url: string): Promise<number | undefined> {
+ const r = await fetch(url, { headers: { Range: "bytes=0-0" } }).catch(() => null);
+ void r?.body?.cancel();
+ return Number(/\/(\d+)$/.exec(r?.headers.get("content-range") ?? "")?.[1] ?? r?.headers.get("content-length")) || undefined;
+}
+
+/** "Beach.mov" -> "Beach (part).mov". */
+const partName = (name: string | undefined, type: string) => {
+ const base = (name ?? "").split(/[\\/]/).pop()?.replace(/\.[a-z0-9]{1,5}$/i, "").trim() || "Clip";
+ return `${base} (part).${type === "video/quicktime" ? "mov" : "mp4"}`;
+};
+
+function partFile(src: Blob, parts: CutPart[], name: string | undefined): File {
+ const type = src.type === "video/quicktime" ? "video/quicktime" : "video/mp4";
+ const blobs: BlobPart[] = parts.map((p) => (p instanceof Uint8Array ? (p as Uint8Array<ArrayBuffer>) : src.slice(p.start, p.end)));
+ return new File(blobs, partName(name, type), { type });
+}
+
+export function useClipFit({
+ rule,
+ value,
+ seconds,
+ setValue,
+ upload,
+}: {
+ /** The tool's rule; null turns the step off. Keep it stable between renders (useMemo). */
+ rule: ClipFitRule | null;
+ value: SlotValue | null | undefined;
+ /** The stored clip's length, when the page has read it already. */
+ seconds?: number;
+ setValue: (v: SlotValue | null) => void;
+ /** The slot's own upload (it places the tile and swaps in the stored file, or keeps it for a guest). */
+ upload: (f: File) => void;
+}) {
+ const sw = useUploadSwitches();
+ const on = !!rule && sw.videoTrim;
+ const guest = useIsGuest();
+ const askFirst = useAskBeforeUpload();
+ 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 latest = useRef(value);
+ const cb = useRef({ rule, setValue, upload });
+ useEffect(() => {
+ latest.current = value;
+ cb.current = { rule, setValue, upload };
+ });
+ // 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 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 });
+ expect.current = null;
+ }, [value, landed]);
+
+ const lineFor = (s: number, max: number, r: ClipFitRule) => `This clip is ${clock(s)}. ${r.tool} takes up to ${max < 60 ? `${Math.floor(max * 10) / 10} s` : clock(max)}: pick the part to use`;
+
+ /** True when this step takes the file: a clip, while a rule and the switch are on. */
+ const wants = useCallback((f: File) => on && (f.type.startsWith("video/") || /\.(mp4|mov|m4v)$/i.test(f.name)), [on]);
+
+ /** A clip picked, dropped or pasted: its length from its header, then a part offered, or the clip uploaded as it is. */
+ const take = useCallback(
+ (f: File) => {
+ const r = cb.current.rule;
+ setOffer(null);
+ setError(null);
+ if (!r || !on) return cb.current.upload(f);
+ void (async () => {
+ const s = await readSeconds(f, true);
+ if (!s || s <= r.maxSeconds + SLACK) return cb.current.upload(f);
+ const index = await readMp4Index(blobReader(f), f.size);
+ // Not an MP4 or MOV this can cut: as it is, and the tool's check says why.
+ if (!index) return cb.current.upload(f);
+ setOffer({ source: f, name: f.name, seconds: index.seconds || s, index });
+ })();
+ },
+ [on],
+ );
+
+ // A stored clip longer than the tool takes: offered once.
+ 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;
+ 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;
+ 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]);
+
+ // An offer belongs to the clip it was made for.
+ const offerGone = !!offer && (offer.stored ? value?.ref !== offer.stored.ref : !!value && !value.uploading);
+ const [seen, setSeen] = useState(value);
+ if (seen !== value) {
+ setSeen(value);
+ if (offerGone) setOffer(null);
+ }
+
+ const use = useCallback(
+ async (from: number, to: number) => {
+ const r = cb.current.rule;
+ if (!offer || !r || askFirst()) return;
+ const o = offer;
+ setOffer(null);
+ setError(null);
+ const cut = cutMp4(o.index, from, Math.min(to - from, r.maxSeconds - MARGIN));
+ if (!cut) return setError("We couldn't cut this clip here. Trim it in another app and add it again");
+ 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 };
+ return cb.current.upload(file);
+ }
+ const token = nanoid(8);
+ const stored = o.stored;
+ cb.current.setValue({ ...stored, id: token, uploading: true });
+ latest.current = { ...stored, id: token, uploading: true };
+ setBusy(true);
+ try {
+ const res = await fetch(stored.ref);
+ if (!res.ok) throw new Error("We couldn't open the clip to cut it. Add it again");
+ const file = partFile(await res.blob(), cut.parts, o.name);
+ 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 });
+ } catch (e) {
+ if (latest.current?.id !== token) return;
+ cb.current.setValue({ ...stored, uploading: false });
+ setError((e as Error).message || "We couldn't cut this clip here. Trim it in another app and add it again");
+ } finally {
+ setBusy(false);
+ }
+ },
+ [offer, askFirst],
+ );
+
+ const shownOffer = offer && !offerGone && rule ? offer : null;
+ const line = busy ? "Cutting the part…" : (error ?? (made && landed === made.ref ? made.line : null));
+ return {
+ on,
+ wants,
+ take,
+ busy,
+ line,
+ failedNow: !!error && !busy,
+ offer: shownOffer
+ ? {
+ ...shownOffer,
+ max: rule!.maxSeconds,
+ min: rule!.minSeconds,
+ line: lineFor(shownOffer.seconds, rule!.maxSeconds, rule!),
+ use: (a: number, b: number) => void use(a, b),
+ cancel: () => {
+ const o = shownOffer;
+ setOffer(null);
+ // 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);
+ },
+ }
+ : null,
+ };
+}
+
+/** The slot's line (cutting, the part used, why not) and the part to pick when the clip is longer than the tool takes. */
+export function FitClipNote({ fit, className }: { fit: ReturnType<typeof useClipFit>; className?: string }) {
+ const o = fit.offer;
+ if (!fit.line && !o) return null;
+ return (
+ <div className={cn("space-y-1.5 pb-2 text-xs text-muted-foreground", className)}>
+ {fit.line && (
+ <p role="status" className={cn("flex items-center gap-1.5", fit.failedNow && "text-destructive")}>
+ {fit.busy && <Loader2 className="size-3 shrink-0 animate-spin" />}
+ {fit.line}
+ </p>
+ )}
+ {o && <TrimPicker source={o.source} kind="video" seconds={o.seconds} max={o.max} min={o.min} line={o.line} keyframes={o.index.keyframes} onUse={o.use} onCancel={o.cancel} />}
+ </div>
+ );
+}
diff --git a/src/components/av/fit-crop.tsx b/src/components/av/fit-crop.tsx
new file mode 100644
index 00000000..ebced2c9
--- /dev/null
+++ b/src/components/av/fit-crop.tsx
@@ -0,0 +1,189 @@
+"use client";
+
+import { Crop, Loader2, X } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { useAskBeforeUpload, useIsGuest } from "@/lib/api";
+import { postFile } from "@/lib/upload";
+import { cn } from "@/lib/utils";
+import { cropFor } from "@/lib/av/crop-fit";
+import { fitImage } from "./fit-image";
+import { useUploadSwitches } from "./use-upload-switches";
+
+/**
+ * The fitting step on a picture slot whose tool takes only some shapes (H3 Max lip sync: 0.4:1 tall to 2.5:1 wide): a
+ * picture outside them gets a crop offered, the nearest shape the tool takes, which the person slides into place. The
+ * crop is made in this browser and uploaded as a new file. Cancel (or the owner's "Offer a crop" switch off) keeps the
+ * picture, and the tool's own check says why it can't take it.
+ */
+
+export interface CropRule {
+ /** The tool's name in the line. */
+ tool: string;
+ /** The shapes it takes, width ÷ height. */
+ ratio: [min: number, max: number];
+}
+
+type Offer = { ref: string; name?: string; width: number; height: number; stored: SlotValue };
+
+function pictureSize(src: string): Promise<{ width: number; height: number } | null> {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve(img.naturalWidth ? { width: img.naturalWidth, height: img.naturalHeight } : null);
+ img.onerror = () => resolve(null);
+ img.src = src;
+ });
+}
+
+export function useCropFit({ rule, value, setValue }: { rule: CropRule | null; value: SlotValue | null | undefined; setValue: (v: SlotValue | null) => void }) {
+ const sw = useUploadSwitches();
+ const on = !!rule && sw.photoCrop;
+ const guest = useIsGuest();
+ const askFirst = useAskBeforeUpload();
+ const [offer, setOffer] = useState<Offer | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [made, setMade] = useState<string | null>(null);
+ const offered = useRef(new Set<string>());
+ const latest = useRef(value);
+ useEffect(() => {
+ latest.current = value;
+ });
+
+ const ref = on && value && !value.uploading && !value.held && value.ref.startsWith("/api/files/") ? value.ref : undefined;
+ useEffect(() => {
+ if (!rule || !ref || guest || offered.current.has(ref) || made === ref) return;
+ let gone = false;
+ void pictureSize(ref).then((size) => {
+ if (gone || !size || latest.current?.ref !== ref || !cropFor(size.width, size.height, rule.ratio)) return;
+ offered.current.add(ref);
+ setOffer({ ref, name: latest.current.name, ...size, stored: latest.current });
+ });
+ return () => {
+ gone = true;
+ };
+ }, [rule, ref, guest, made]);
+
+ const offerGone = !!offer && value?.ref !== offer.ref;
+ const [seen, setSeen] = useState(value);
+ if (seen !== value) {
+ setSeen(value);
+ if (offerGone) setOffer(null);
+ }
+
+ const use = useCallback(
+ async (crop: { x: number; y: number; width: number; height: number }) => {
+ if (!offer || askFirst()) return;
+ const o = offer;
+ setOffer(null);
+ setError(null);
+ setBusy(true);
+ setValue({ ...o.stored, uploading: true });
+ try {
+ const res = await fetch(o.ref);
+ if (!res.ok) throw new Error("We couldn't open the picture to crop it. Add it again");
+ const out = await fitImage(await res.blob(), { name: o.name, crop, keepAlpha: false, maxPixels: 40_000_000, maxBytes: 25 * 1024 * 1024 });
+ const asset = await postFile(out.file);
+ if (latest.current?.ref !== o.ref) return;
+ setValue({ ref: asset.url, preview: asset.url, kind: asset.kind ?? "image", name: out.file.name, source: "upload" });
+ setMade(asset.url);
+ } catch (e) {
+ setValue({ ...o.stored, uploading: false });
+ setError((e as Error).message || "We couldn't crop the picture here. Crop it in another app and add it again");
+ } finally {
+ setBusy(false);
+ }
+ },
+ [offer, askFirst, setValue],
+ );
+
+ const shown = offer && !offerGone && on ? offer : null;
+ const line = busy ? "Cropping the picture…" : (error ?? (made && value?.ref === made && rule ? `Cropped for ${rule.tool}` : null));
+ return { on, busy, line, failedNow: !!error && !busy, offer: shown && rule ? { ...shown, rule, use: (c: Parameters<typeof use>[0]) => void use(c), cancel: () => setOffer(null) } : null };
+}
+
+/** The picture with the crop to slide into place, and Use this crop / Cancel. */
+function CropPicker({ o }: { o: NonNullable<ReturnType<typeof useCropFit>["offer"]> }) {
+ const base = cropFor(o.width, o.height, o.rule.ratio)!;
+ const tall = base.height < o.height;
+ const room = tall ? o.height - base.height : o.width - base.width;
+ const [at, setAt] = useState(tall ? base.y : base.x);
+ const box = useRef<HTMLDivElement>(null);
+ const drag = useRef<{ y: number; at: number } | null>(null);
+ const crop = tall ? { ...base, y: at } : { ...base, x: at };
+ const pos = (n: number, of: number) => `${(n / of) * 100}%`;
+ const scale = () => {
+ const r = box.current?.getBoundingClientRect();
+ return r ? (tall ? o.height / r.height : o.width / r.width) : 1;
+ };
+ const clamp = (n: number) => Math.round(Math.min(room, Math.max(0, n)));
+ const line = `This picture is ${o.width}×${o.height}. ${o.rule.tool} takes ${o.rule.ratio[0]}:1 (tall) to ${o.rule.ratio[1]}:1 (wide): slide the crop to the part to use`;
+ return (
+ <div className="space-y-3 rounded-2xl border bg-card p-3 text-foreground shadow-sm sm:p-4" data-crop-picker>
+ <p className="text-[13px] leading-snug">{line}</p>
+ <div
+ ref={box}
+ className="relative mx-auto max-h-[46vh] touch-none overflow-hidden rounded-xl bg-muted select-none"
+ style={{ aspectRatio: `${o.width} / ${o.height}`, maxWidth: `min(100%, calc(46vh * ${o.width / o.height}))` }}
+ onPointerDown={(e) => {
+ drag.current = { y: tall ? e.clientY : e.clientX, at };
+ e.currentTarget.setPointerCapture(e.pointerId);
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (d) setAt(clamp(d.at + ((tall ? e.clientY : e.clientX) - d.y) * scale()));
+ }}
+ onPointerUp={() => (drag.current = null)}
+ onPointerCancel={() => (drag.current = null)}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={o.ref} alt="" draggable={false} className="absolute inset-0 size-full object-cover" />
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label="Where the crop sits"
+ aria-valuemin={0}
+ aria-valuemax={room}
+ aria-valuenow={at}
+ onKeyDown={(e) => {
+ const step = (e.shiftKey ? 0.1 : 0.02) * room * (e.key === "ArrowUp" || e.key === "ArrowLeft" ? -1 : e.key === "ArrowDown" || e.key === "ArrowRight" ? 1 : 0);
+ if (!step) return;
+ e.preventDefault();
+ setAt(clamp(at + step));
+ }}
+ className="absolute cursor-grab rounded-lg border-[3px] border-primary shadow-[0_0_0_9999px_rgb(0_0_0/0.55)] outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
+ style={{ left: pos(crop.x, o.width), top: pos(crop.y, o.height), width: pos(crop.width, o.width), height: pos(crop.height, o.height) }}
+ />
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => o.use(crop)}
+ className="inline-flex min-h-11 flex-1 items-center justify-center gap-1.5 rounded-full bg-foreground px-4 text-[14px] font-medium text-background sm:flex-none"
+ >
+ <Crop className="size-4" />
+ Use this crop
+ </button>
+ <button type="button" onClick={o.cancel} className="inline-flex min-h-11 items-center justify-center gap-1.5 rounded-full border px-4 text-[14px] font-medium hover:bg-accent">
+ <X className="size-4" />
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function FitCropNote({ fit, className }: { fit: ReturnType<typeof useCropFit>; className?: string }) {
+ if (!fit.line && !fit.offer) return null;
+ return (
+ <div className={cn("space-y-1.5 pb-2 text-xs text-muted-foreground", className)}>
+ {fit.line && (
+ <p role="status" className={cn("flex items-center gap-1.5", fit.failedNow && "text-destructive")}>
+ {fit.busy && <Loader2 className="size-3 shrink-0 animate-spin" />}
+ {fit.line}
+ </p>
+ )}
+ {fit.offer && <CropPicker key={fit.offer.ref} o={fit.offer} />}
+ </div>
+ );
+}
diff --git a/src/components/av/fit-file.ts b/src/components/av/fit-file.ts
new file mode 100644
index 00000000..71229547
--- /dev/null
+++ b/src/components/av/fit-file.ts
@@ -0,0 +1,32 @@
+"use client";
+
+import { toast } from "sonner";
+import { FIT_READ_MAX_SECONDS, mp3Kbps } from "@/lib/av/fit-upload";
+import { ACCOUNT_PHOTO_BYTES, ACCOUNT_PHOTO_PIXELS, ACCOUNT_SOUND_BYTES, mayHaveAlpha, type FileFit } from "@/lib/av/fit-file";
+import { readSeconds, toMp3 } from "./fit-audio";
+import { fitImage } from "./fit-image";
+import { uploadSwitchesNow } from "./use-upload-switches";
+
+/**
+ * The browser half of fitting an upload (src/lib/av/fit-file.ts): a photo becomes a JPEG (or a WebP) within an account's
+ * caps, a sound an MP3 within an account's cap, said in a toast. Null when the owner switched that step off: the file goes
+ * as it is, and the route says why it can't take it.
+ */
+export async function fitFile(file: File, fit: FileFit): Promise<File | null> {
+ const sw = await uploadSwitchesNow();
+ if (fit.kind === "photo") {
+ if (!sw.photoConvert) return null;
+ const out = await fitImage(file, { name: file.name, maxPixels: ACCOUNT_PHOTO_PIXELS, maxBytes: ACCOUNT_PHOTO_BYTES, keepAlpha: mayHaveAlpha(file) });
+ toast.success(`Converted to ${out.file.type === "image/webp" ? "WebP" : "JPEG"} to upload it`);
+ return out.file;
+ }
+ if (fit.kind === "sound") {
+ if (!sw.soundConvert) return null;
+ const seconds = await readSeconds(file);
+ if (seconds && seconds > FIT_READ_MAX_SECONDS) throw new Error("This sound is too long to convert here (15 minutes at most). Save it as an MP3 and add it again");
+ const out = await toMp3(file, { kbps: (seconds && mp3Kbps(seconds, ACCOUNT_SOUND_BYTES)) || 192, name: file.name });
+ toast.success("Converted to MP3 to upload it");
+ return out;
+ }
+ return null;
+}
diff --git a/src/components/av/fit-image.ts b/src/components/av/fit-image.ts
new file mode 100644
index 00000000..8aff4235
--- /dev/null
+++ b/src/components/av/fit-image.ts
@@ -0,0 +1,130 @@
+"use client";
+
+/**
+ * The browser half of fitting a photo (src/lib/av/fit-image.ts says when): decoded here and saved again as a JPEG, or a
+ * WebP when it may have see-through parts, at most `maxPixels` and `maxBytes`. Nothing is sent anywhere while it runs.
+ */
+
+export interface ImageFitOut {
+ file: File;
+ width: number;
+ height: number;
+}
+
+const cantOpen = (name?: string) => {
+ const ext = /\.([a-z0-9]{2,5})$/i.exec(name ?? "")?.[1]?.toUpperCase();
+ return new Error(`This browser can't open ${ext ? `${ext} photos` : "this photo"}. Save it as a JPEG and add it again`);
+};
+
+async function decode(file: Blob, name?: string): Promise<{ draw: CanvasImageSource; width: number; height: number; close: () => void }> {
+ if (typeof createImageBitmap === "function") {
+ try {
+ const b = await createImageBitmap(file, { imageOrientation: "from-image" });
+ return { draw: b, width: b.width, height: b.height, close: () => b.close() };
+ } catch {
+ // An <img> below (some browsers open more types there).
+ }
+ }
+ const url = URL.createObjectURL(file);
+ try {
+ const img = new Image();
+ img.decoding = "async";
+ img.src = url;
+ await img.decode();
+ if (!img.naturalWidth) throw cantOpen(name);
+ return { draw: img, width: img.naturalWidth, height: img.naturalHeight, close: () => URL.revokeObjectURL(url) };
+ } catch {
+ URL.revokeObjectURL(url);
+ throw cantOpen(name);
+ }
+}
+
+const toBlob = (c: HTMLCanvasElement, type: string, quality: number) => new Promise<Blob | null>((r) => c.toBlob(r, type, quality));
+
+/** "IMG_2041.HEIC" -> "IMG_2041.jpg". */
+export function renamed(name: string | undefined, ext: string): string {
+ const base = (name ?? "").split(/[\\/]/).pop()?.replace(/\.[a-z0-9]{1,5}$/i, "").trim();
+ return `${base || "Photo"}.${ext}`;
+}
+
+/**
+ * The photo (its first frame, for a GIF) as a JPEG, or a WebP when `keepAlpha` and the browser saves one, no bigger than
+ * `maxPixels` and `maxBytes`, and cropped to `crop` (in the photo's pixels) when given. Throws in plain words when the
+ * browser can't open it or can't get it under `maxBytes`.
+ */
+export async function fitImage(
+ file: Blob,
+ opts: {
+ name?: string;
+ maxPixels?: number;
+ maxBytes?: number;
+ keepAlpha?: boolean;
+ crop?: { x: number; y: number; width: number; height: number };
+ /** Exactly this size (an endpoint's own limits, src/lib/catalog/still-limits.ts). */
+ size?: { width: number; height: number };
+ /** Saved as a PNG (an endpoint that reads PNG only), else JPEG or WebP. */
+ png?: boolean;
+ },
+): Promise<ImageFitOut> {
+ const src = await decode(file, opts.name);
+ try {
+ const crop = opts.crop ?? { x: 0, y: 0, width: src.width, height: src.height };
+ let scale = opts.size ? opts.size.width / crop.width : 1;
+ if (opts.maxPixels && crop.width * crop.height > opts.maxPixels) scale = Math.sqrt(opts.maxPixels / (crop.width * crop.height));
+ for (let attempt = 0; attempt < 6; attempt++) {
+ const w = attempt === 0 && opts.size ? opts.size.width : Math.max(1, Math.floor(crop.width * scale));
+ const h = attempt === 0 && opts.size ? opts.size.height : Math.max(1, Math.floor(crop.height * scale));
+ const canvas = document.createElement("canvas");
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) throw cantOpen(opts.name);
+ if (!opts.keepAlpha) {
+ ctx.fillStyle = "#fff";
+ ctx.fillRect(0, 0, w, h);
+ }
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(src.draw, crop.x, crop.y, crop.width, crop.height, 0, 0, w, h);
+ if (opts.png) {
+ const blob = await toBlob(canvas, "image/png", 1);
+ if (!blob) throw cantOpen(opts.name);
+ if (!opts.maxBytes || blob.size <= opts.maxBytes) return { file: new File([blob], renamed(opts.name, "png"), { type: "image/png" }), width: w, height: h };
+ scale *= 0.8;
+ continue;
+ }
+ for (const q of [0.92, 0.86, 0.8]) {
+ let blob = opts.keepAlpha ? await toBlob(canvas, "image/webp", q) : null;
+ // A browser that doesn't save WebP answers with a PNG: a JPEG then (on white).
+ if (!blob || blob.type !== "image/webp") {
+ if (opts.keepAlpha) {
+ ctx.globalCompositeOperation = "destination-over";
+ ctx.fillStyle = "#fff";
+ ctx.fillRect(0, 0, w, h);
+ ctx.globalCompositeOperation = "source-over";
+ }
+ blob = await toBlob(canvas, "image/jpeg", q);
+ }
+ if (!blob) throw cantOpen(opts.name);
+ if (!opts.maxBytes || blob.size <= opts.maxBytes) {
+ const ext = blob.type === "image/webp" ? "webp" : "jpg";
+ return { file: new File([blob], renamed(opts.name, ext), { type: blob.type }), width: w, height: h };
+ }
+ }
+ scale *= 0.8;
+ }
+ throw new Error("We couldn't make this photo small enough here. Save it smaller and add it again");
+ } finally {
+ src.close();
+ }
+}
+
+/** A photo's size in pixels, read by the browser (null when it can't open it). */
+export async function imageSize(file: Blob): Promise<{ width: number; height: number } | null> {
+ try {
+ const src = await decode(file);
+ src.close();
+ return { width: src.width, height: src.height };
+ } catch {
+ return null;
+ }
+}
diff --git a/src/components/av/fit-source.tsx b/src/components/av/fit-source.tsx
new file mode 100644
index 00000000..9ede9e94
--- /dev/null
+++ b/src/components/av/fit-source.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import { useMemo } from "react";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { FitClipNote, useClipFit } from "./fit-clip";
+import { FitUploadNote, useFitUpload } from "./fit-upload";
+
+/**
+ * A tool's own source (a sound or a video, once stored) longer than the tool takes: a part of it offered, with the shared
+ * picker (src/components/av/trim-picker.tsx). A sound's part is an MP3, a clip's part is cut from a key frame. The tool
+ * keeps its own check: Cancel, or the owner's switch off, leaves the file as it is and the tool says why.
+ */
+
+type Source = { ref: string; preview: string; kind?: string; name?: string; uploading?: boolean; held?: string; duration?: number };
+
+const SOUND_CAP = 50 * 1024 * 1024;
+
+export function SourceFit<S extends Source>({
+ source,
+ kind,
+ tool,
+ maxSeconds,
+ minSeconds,
+ setSource,
+ className,
+}: {
+ source: S | null;
+ kind: "audio" | "video";
+ tool: string;
+ /** The longest the tool takes; undefined: nothing to fit. */
+ maxSeconds: number | undefined;
+ minSeconds?: number;
+ setSource: (s: S | null) => void;
+ 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);
+ 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),
+ [kind, tool, maxSeconds, minSeconds],
+ );
+ const clip = useClipFit({
+ rule: clipRule,
+ value,
+ seconds: source?.duration,
+ setValue: set,
+ upload: () => {},
+ });
+ const sound = useFitUpload({
+ rule: soundRule,
+ value,
+ seconds: source?.duration,
+ setValue: set,
+ upload: () => {},
+ });
+ return kind === "video" ? <FitClipNote fit={clip} className={className} /> : <FitUploadNote fit={sound} className={className} />;
+}
diff --git a/src/components/av/fit-still.ts b/src/components/av/fit-still.ts
new file mode 100644
index 00000000..2c5d6e9d
--- /dev/null
+++ b/src/components/av/fit-still.ts
@@ -0,0 +1,46 @@
+"use client";
+
+import { toast } from "sonner";
+import { STILL_LIMITS, stillPlan, type StillFormat } from "@/lib/catalog/still-limits";
+import type { ModelDef, Operation } from "@/lib/catalog/types";
+import { fitImage, imageSize } from "./fit-image";
+import { uploadSwitchesNow } from "./use-upload-switches";
+
+/**
+ * A picture for a cloud endpoint with limits of its own (src/lib/catalog/still-limits.ts: Qwen Image 3 edit 384-2048 px and
+ * 10 MB, Recraft Crisp PNG only, …) fitted in this browser before it is uploaded, so a smaller file goes up. The server
+ * still fits what arrives (src/server/fit-still.ts), so this is never the only check. Off with the owner's "Convert or make
+ * smaller" switch.
+ */
+
+/** The endpoint with limits a model's op runs on in the cloud, or undefined. */
+export function stillEndpoint(model: Pick<ModelDef, "engine" | "routes"> | undefined, op: Operation | undefined): string | undefined {
+ if (!model || model.engine === "open") return undefined;
+ return model.routes.find((r) => (!op || r.op === op) && STILL_LIMITS[r.endpoint])?.endpoint;
+}
+
+const formatOf = (type: string): StillFormat =>
+ /png/i.test(type) ? "png" : /jpe?g/i.test(type) ? "jpeg" : /webp/i.test(type) ? "webp" : /gif/i.test(type) ? "gif" : /svg/i.test(type) ? "svg" : "other";
+
+/** The picture fitted to `endpoint`, or the same file when it fits (or can't be read here: the server fits it). */
+export async function fitStill(file: File, endpoint: string, forName: string): Promise<File> {
+ if (!(await uploadSwitchesNow()).photoConvert) return file;
+ const size = await imageSize(file);
+ if (!size) return file;
+ const plan = stillPlan(endpoint, { ...size, bytes: file.size, format: formatOf(file.type) });
+ if (!plan) return file;
+ const lim = STILL_LIMITS[endpoint];
+ try {
+ const out = await fitImage(file, {
+ name: file.name,
+ size: plan.resize,
+ png: plan.toFormat === "png" || (!plan.toFormat && formatOf(file.type) === "png" && !plan.flatten && !lim.maxBytes),
+ keepAlpha: !plan.flatten && plan.toFormat !== "jpeg",
+ maxBytes: lim.maxBytes,
+ });
+ toast.success(`Fitted for ${forName}`);
+ return out.file;
+ } catch {
+ return file;
+ }
+}
diff --git a/src/components/av/sound-alone.tsx b/src/components/av/sound-alone.tsx
new file mode 100644
index 00000000..645d43f4
--- /dev/null
+++ b/src/components/av/sound-alone.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { AudioLines, Loader2 } from "lucide-react";
+import { useState } from "react";
+import { FIT_READ_MAX_SECONDS, mp3Kbps } from "@/lib/av/fit-upload";
+import { postFile } from "@/lib/upload";
+import { cn } from "@/lib/utils";
+import { readSeconds, toMp3 } from "./fit-audio";
+import { useUploadSwitches } from "./use-upload-switches";
+
+/** An account's sound cap: the MP3 stays under it. */
+const SOUND_CAP = 50 * 1024 * 1024;
+
+/**
+ * A stored file's sound as an MP3, made in this browser and uploaded as a new file: for a tool that can't take the file as
+ * it is (a video too big to have its sound taken in the cloud, a sound whose length can't be read). Hidden while the owner's
+ * "Convert to MP3" switch is off: the tool's own words then stand.
+ */
+export function SoundAloneButton({
+ src,
+ name,
+ label = "Send the sound alone (MP3)",
+ onDone,
+ className,
+}: {
+ src: string;
+ name?: string;
+ label?: string;
+ onDone: (file: { url: string; name: string }) => void;
+ className?: string;
+}) {
+ const sw = useUploadSwitches();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ if (!sw.soundConvert) return null;
+ const go = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const res = await fetch(src);
+ if (!res.ok) throw new Error("We couldn't open the file. Add it again");
+ const blob = await res.blob();
+ const seconds = await readSeconds(blob, blob.type.startsWith("video/"));
+ if (seconds && seconds > FIT_READ_MAX_SECONDS) throw new Error("Its sound is too long to convert here (15 minutes at most). Save the sound as an MP3 and add it");
+ const mp3 = await toMp3(blob, { kbps: (seconds && mp3Kbps(seconds, SOUND_CAP)) || 192, name });
+ const asset = await postFile(mp3);
+ onDone({ url: asset.url, name: mp3.name });
+ } catch (e) {
+ setError((e as Error).message || "We couldn't convert the sound here. Save it as an MP3 and add it");
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <div className={cn("space-y-1.5", className)}>
+ <button
+ type="button"
+ onClick={() => void go()}
+ disabled={busy}
+ className="inline-flex min-h-10 items-center gap-1.5 rounded-full border bg-background px-3.5 text-[13px] font-medium text-foreground hover:bg-accent disabled:opacity-60"
+ >
+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <AudioLines className="size-3.5" />}
+ {busy ? "Converting to MP3…" : label}
+ </button>
+ {error && <p className="text-[12px] text-destructive">{error}</p>}
+ </div>
+ );
+}
diff --git a/src/components/av/trim-picker.tsx b/src/components/av/trim-picker.tsx
index 7641e05c..8d804c7f 100644
--- a/src/components/av/trim-picker.tsx
+++ b/src/components/av/trim-picker.tsx
@@ -58,7 +58,8 @@ export function stamp(t: number, tenths = false): string {
function lengthWords(t: number, tenths: boolean): string {
if (t < 60) return `${tenths ? t.toFixed(1) : Math.round(t)} s`;
const m = Math.floor(t / 60);
- return `${m} min ${String(Math.round(t - m * 60)).padStart(2, "0")} s`;
+ const s = Math.round(t - m * 60);
+ return s ? `${m} min ${String(s).padStart(2, "0")} s` : `${m} min`;
}
type Drag = { mode: "start" | "end" | "move"; grab: number } | null;
diff --git a/src/components/av/use-upload-switches.ts b/src/components/av/use-upload-switches.ts
index eb8b9151..75674ae2 100644
--- a/src/components/av/use-upload-switches.ts
+++ b/src/components/av/use-upload-switches.ts
@@ -6,20 +6,29 @@ import { readUploadSwitches, UPLOAD_SWITCH_DEFAULTS, type UploadSwitches } from
/** The query that holds the upload switches (Settings changes them and refreshes it). */
export const UPLOAD_SWITCHES_KEY = ["upload-switches"] as const;
+/** Read again after a minute. */
+const FRESH_MS = 60_000;
+let last: { at: number; value: UploadSwitches } | null = null;
+
+async function fetchSwitches(): Promise<UploadSwitches> {
+ const res = await fetch("/api/site/uploads", { cache: "no-store" });
+ if (!res.ok) throw new Error(String(res.status));
+ const value = readUploadSwitches(((await res.json()) as { switches?: unknown }).switches);
+ last = { at: Date.now(), value };
+ return value;
+}
+
/**
* The owner's upload switches (src/lib/av/upload-switches.ts), read once a page loads and again when it comes back into
* view, so a change applies without a deploy. All on while they load or when they can't be read.
*/
export function useUploadSwitches(): UploadSwitches {
- const q = useQuery({
- queryKey: UPLOAD_SWITCHES_KEY,
- queryFn: async () => {
- const res = await fetch("/api/site/uploads", { cache: "no-store" });
- if (!res.ok) throw new Error(String(res.status));
- return readUploadSwitches(((await res.json()) as { switches?: unknown }).switches);
- },
- staleTime: 60_000,
- retry: 1,
- });
+ const q = useQuery({ queryKey: UPLOAD_SWITCHES_KEY, queryFn: fetchSwitches, staleTime: FRESH_MS, retry: 1 });
return q.data ?? UPLOAD_SWITCH_DEFAULTS;
}
+
+/** The same, outside React (an upload on its way): the last read when it is fresh, else read now; all on if it can't be. */
+export async function uploadSwitchesNow(): Promise<UploadSwitches> {
+ if (last && Date.now() - last.at < FRESH_MS) return last.value;
+ return fetchSwitches().catch(() => last?.value ?? UPLOAD_SWITCH_DEFAULTS);
+}
diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsx
index 3c717430..f4e372bc 100644
--- a/src/components/dub/dub-studio.tsx
+++ b/src/components/dub/dub-studio.tsx
@@ -9,7 +9,10 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
-import type { SlotValue } from "@/components/studio/media-slot";
+import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";
+import { FitClipNote, useClipFit } from "@/components/av/fit-clip";
+import { getModel } from "@/lib/catalog";
+import { clipWindowProblem, sourceSeconds } from "@/lib/catalog/clip-windows";
import { CueEditor, useCueEditor } from "@/components/av/cue-editor";
import { PlaceholderChip } from "@/components/demo-mode";
import { SourceLanguageSelect, TargetLanguages } from "@/components/av/language-picker";
@@ -159,7 +162,13 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
setMode("oneshot");
};
const connectGpu = () => window.dispatchEvent(new CustomEvent<ConnectGpuDetail>(CONNECT_GPU_EVENT, { detail: { gpuOnly: true, needs: "gpu" } }));
- const blocker = !video ? "Add the video to translate" : video.uploading ? "Uploading…" : !usable.length ? "Pick a language to dub into" : null;
+ // One shot's own limit (HeyGen Translate: up to 480 s), said before the run, with a part of a longer video offered.
+ const modelName = getModel(model)?.name ?? "HeyGen Translate";
+ const longest = oneShot ? sourceSeconds(model).max : undefined;
+ const tooLong = longest && duration ? clipWindowProblem({ id: model, name: modelName }, duration) : null;
+ const clipRule = longest ? { for: modelName, tool: modelName, maxSeconds: longest } : null;
+ const clipFit = useClipFit({ rule: clipRule, value: video, seconds: duration, setValue: setVideo, upload: (f) => void fileToSlot(f, setVideo, "video") });
+ const blocker = !video ? "Add the video to translate" : video.uploading ? "Uploading…" : !usable.length ? "Pick a language to dub into" : tooLong;
const body =
video && !video.uploading && usable.length && !needsGpu
? { engine, mode: oneShot ? ("oneshot" as const) : ("steps" as const), model: oneShot ? model : undefined, video: video.ref, source, targets: usable, duration, ...(engine === "open" && { voiceSplit: split }) }
@@ -201,6 +210,7 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {
hint="MP4, MOV or WebM up to 200 MB · one clear speaker works best"
compact
/>
+ <FitClipNote fit={clipFit} className="pt-2" />
</div>
<Panel title="How">
<div role="radiogroup" aria-label="How to dub" className="grid gap-2 sm:grid-cols-2">
diff --git a/src/components/model3d/retexture-dialog.tsx b/src/components/model3d/retexture-dialog.tsx
index 7b8af945..e7885d31 100644
--- a/src/components/model3d/retexture-dialog.tsx
+++ b/src/components/model3d/retexture-dialog.tsx
@@ -22,6 +22,8 @@ import {
type RetextureModel,
} from "@/lib/av/model3d";
import { toastError } from "@/lib/refusals";
+import { fitImage } from "@/components/av/fit-image";
+import { uploadSwitchesNow } from "@/components/av/use-upload-switches";
import { priceLine, useCreate3d, useRunPreview } from "./hooks";
const SIZE_LABEL: Record<(typeof RETEXTURE_SIZES)[number], string> = { "2k": "2K textures", "4k": "4K textures", "8k": "8K textures" };
@@ -66,14 +68,21 @@ export function RetextureDialog({
const req = ready ? retextureRequest({ glb, prompt, style: style?.url, model, size, keepUv }) : null;
const preview = useRunPreview(open ? req : null);
const price = priceLine(preview.data);
- const pickStyle = async (f: File | undefined) => {
- if (!f) return;
- if (f.size > RETEXTURE_STYLE_MAX_BYTES) {
- toast.error("The style picture must be 20 MB or less");
- return;
- }
+ const pickStyle = async (picked: File | undefined) => {
+ if (!picked) return;
setUploading(true);
try {
+ // Over 20 MB, or not a PNG, JPEG or WebP (a HEIC photo): made into one here when the owner's switch allows, else said.
+ let f = picked;
+ const fits = picked.size <= RETEXTURE_STYLE_MAX_BYTES && RETEXTURE_STYLE_TYPES.split(",").includes(picked.type);
+ if (!fits) {
+ if (!(await uploadSwitchesNow()).photoConvert) {
+ toast.error("The style picture must be a PNG, JPEG or WebP of 20 MB or less");
+ return;
+ }
+ f = (await fitImage(picked, { name: picked.name, maxBytes: RETEXTURE_STYLE_MAX_BYTES, maxPixels: 40_000_000, keepAlpha: /png|webp|heic|heif|avif/i.test(picked.type || picked.name) })).file;
+ toast.success("Made the style picture fit (20 MB at most)");
+ }
const asset = await uploadFile(f);
setStyle({ url: asset.url, preview: URL.createObjectURL(f) });
} catch (e) {
@@ -141,7 +150,7 @@ export function RetextureDialog({
{uploading ? <Loader2 className="size-3.5 animate-spin" /> : <ImagePlus className="size-3.5" />} Style picture
</Button>
)}
- <input ref={file} type="file" accept={RETEXTURE_STYLE_TYPES} className="hidden" onChange={(e) => void pickStyle(e.target.files?.[0])} />
+ <input ref={file} type="file" accept={`${RETEXTURE_STYLE_TYPES},image/heic,image/heif,image/avif,.heic,.heif,.avif`} className="hidden" onChange={(e) => void pickStyle(e.target.files?.[0])} />
<Select value={model} onValueChange={(v) => setModel(v as RetextureModel)}>
<SelectTrigger size="sm" className="rounded-full" aria-label="Model">
<SelectValue />
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index c7ae7c26..abdaab1c 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -17,6 +17,11 @@ import type { Engine, InputSlot, MediaKind, ModelDef, Operation, Preset, PresetR
import { LYRICS_PARAM, SONG_ID_PARAM, songFormat, songToolProblem, withSongId } from "@/lib/lyrics";
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 { FitCropNote, useCropFit } from "@/components/av/fit-crop";
+import { fitStill, stillEndpoint } from "@/components/av/fit-still";
+import { portraitRatio } from "@/lib/catalog/clip-windows";
+import { sampleFitRule, shortName, voiceFitRule } from "@/lib/av/voice-fit";
import { dualEngine, onEngine } from "@/lib/catalog/engines";
import { locksByDefault } from "@/lib/catalog/palettes";
import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";
@@ -65,6 +70,7 @@ import {
blockerFor,
blockerLine,
clipBlocker,
+ clipFitWindow,
clipOutcome,
costLabel,
engineSwitchModel,
@@ -811,7 +817,13 @@ export function Composer({ docked }: { docked: boolean }) {
// browser instead: converted to an MP3, or a part of it offered (src/components/av/fit-upload.tsx); what's left is said
// as before. One of Mureka's own songs goes by its id and is left alone.
const fitOp = op ?? studioOp ?? model?.routes.find((r) => SONG_FIT_OPS.has(r.op))?.op;
- const songRule = useMemo(() => (config.voiceFacts && model?.family === "mureka" ? murekaSongRule(fitOp) : null), [config.voiceFacts, model?.family, fitOp]);
+ // A talking avatar's voice outside its model's length (H3 Max lip sync 5 s to 15 min, OmniHuman 2 4 s to 5 min, P-Video up to
+ // 3 min), or a file its model doesn't take (OmniHuman 2: an MP3 or WAV up to 15 MB): the same step, with that model's rule.
+ const songRule = useMemo(() => {
+ if (!config.voiceFacts || !model) return null;
+ if (model.family === "mureka") return murekaSongRule(fitOp);
+ return (op ?? studioOp) === "avatar" ? voiceFitRule({ id: model.id, name: shortName(model.name) }) : null;
+ }, [config.voiceFacts, model, fitOp, op, studioOp]);
const songFit = useFitUpload({
rule: songRule,
value: draft.slots.audio,
@@ -820,8 +832,37 @@ export function Composer({ docked }: { docked: boolean }) {
setValue: (v) => attach.setSlotValue("audio", v),
upload: (f) => attach.uploadToSlot("audio", f, "audio"),
});
+ // A clip longer than the model's window (or a tool's longest source: Kandinsky VSR 5 s): a part of it offered, cut from a
+ // key frame without encoding it again (src/components/av/fit-clip.tsx).
+ const clipRule = useMemo(() => {
+ const w = config.clipFacts ? clipFitWindow(op ?? studioOp, model, facts?.fps) : undefined;
+ return w && model ? { for: shortName(model.name), tool: shortName(model.name), minSeconds: w.min, maxSeconds: w.max } : null;
+ }, [config.clipFacts, op, studioOp, model, facts?.fps]);
+ const clipFit = useClipFit({
+ rule: clipRule,
+ value: draft.slots.video,
+ seconds: facts?.duration,
+ setValue: (v) => attach.setSlotValue("video", v),
+ upload: (f) => attach.uploadToSlot("video", f, "video"),
+ });
+ // A portrait outside the shapes its model takes (H3 Max lip sync: 0.4:1 to 2.5:1): a crop offered.
+ const cropRule = useMemo(() => {
+ const ratio = model && (op ?? studioOp) === "avatar" ? portraitRatio(model.id) : undefined;
+ return ratio && model ? { tool: shortName(model.name), ratio } : null;
+ }, [model, op, studioOp]);
+ const cropFit = useCropFit({ rule: cropRule, value: draft.slots.image, setValue: (v) => attach.setSlotValue("image", v) });
+ // A picture for a cloud endpoint with limits of its own (Qwen Image 3 edit, Recraft Crisp…): fitted here before it goes up.
+ const stillEp = stillEndpoint(model, op ?? studioOp);
+ // AuK's voice sample (under 20 s): a part of a longer one offered.
+ const sampleRule = useMemo(() => (model?.id === "oss-auk" ? sampleFitRule() : null), [model?.id]);
+ const sampleFit = useFitUpload({
+ rule: sampleRule,
+ value: draft.slots.voiceAudio,
+ setValue: (v) => setSlot("voiceAudio", v),
+ upload: (f) => attach.uploadToSlot("voiceAudio", f, "audio"),
+ });
useEffect(() => {
- songRoute.current = (f) => songFit.wants(f) && (songFit.take(f), true);
+ songRoute.current = (f) => (songFit.wants(f) && (songFit.take(f), true)) || (clipFit.wants(f) && (clipFit.take(f), true));
});
const songProblem = songRef ? songToolProblem(op!, { format: songFormat(undefined, songRef), seconds: voice?.duration }, songById) : null;
if (songProblem && !planError) planError = songProblem;
@@ -1688,7 +1729,15 @@ export function Composer({ docked }: { docked: boolean }) {
caption
value={draft.slots[s.key] ?? null}
onChange={(v) => attach.setSlotValue(s.key, v)}
- onFile={(f) => (s.key === "audio" && songFit.wants(f) ? songFit.take(f) : attach.uploadToSlot(s.key, f, s.accept))}
+ onFile={(f) =>
+ s.key === "audio" && songFit.wants(f)
+ ? songFit.take(f)
+ : s.key === "video" && clipFit.wants(f)
+ ? clipFit.take(f)
+ : s.key === "image" && stillEp && model
+ ? void fitStill(f, stillEp, model.name).then((g) => attach.uploadToSlot(s.key, g, s.accept))
+ : attach.uploadToSlot(s.key, f, s.accept)
+ }
{...(s.key === "audio" && songFit.on && { accept: songFit.accept, takes: songFit.wants })}
/>
),
@@ -1742,6 +1791,9 @@ export function Composer({ docked }: { docked: boolean }) {
<ReferenceOrder images={refImages} clips={refClips.length} audios={refAudios.length} problem={refProblem} />
)}
{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" />}
+ {showAttachments && !collapsed && !framesOn && <FitCropNote fit={cropFit} className="px-3" />}
{/* On a phone the slot row scrolls sideways, so the switch gets its own line under it. */}
{showAttachments && !collapsed && !framesOn && hasCleanVoice && <CleanVoiceSwitch status className="px-3 pb-2 sm:hidden" hint="first, free on your GPU" />}
{showAttachments && !collapsed && !framesOn && voiceFirstShown && voiceFirstKind && (
diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsx
index 6cd13813..2bfcbe10 100644
--- a/src/components/studio/media-slot.tsx
+++ b/src/components/studio/media-slot.tsx
@@ -38,10 +38,11 @@ export interface SlotValue {
sketch?: { mode: SketchMode; strokes: Stroke[] };
}
+// HEIC, AVIF, AAC, Opus and the like are converted in this browser before they are uploaded (src/lib/av/fit-file.ts).
export const ACCEPT: Record<MediaKind, string> = {
- image: "image/png,image/jpeg,image/webp,image/gif",
+ image: "image/png,image/jpeg,image/webp,image/gif,image/heic,image/heif,image/avif,.heic,.heif,.avif",
video: "video/mp4,video/webm,video/quicktime",
- audio: "audio/mpeg,audio/wav,audio/x-wav,audio/ogg,audio/flac,audio/mp4,audio/webm",
+ audio: "audio/mpeg,audio/wav,audio/x-wav,audio/ogg,audio/flac,audio/mp4,audio/webm,audio/x-m4a,audio/aac,audio/opus,audio/aiff,.m4a,.aac,.opus,.aif,.aiff,.caf",
text: "text/plain,.txt,.srt,.vtt",
model3d: ".glb,.gltf,model/gltf-binary",
};
@@ -51,7 +52,7 @@ export const MAX_MB = 200;
const EXT_KIND: [RegExp, MediaKind][] = [
[/\.(mp4|webm|mov|m4v)$/i, "video"],
- [/\.(mp3|wav|ogg|flac|m4a|aac|opus)$/i, "audio"],
+ [/\.(mp3|wav|ogg|flac|m4a|aac|opus|aif|aiff|caf|wma|amr)$/i, "audio"],
[/\.(txt|srt|vtt)$/i, "text"],
[/\.(glb|gltf)$/i, "model3d"],
];
diff --git a/src/lib/av/clean-dialogue.ts b/src/lib/av/clean-dialogue.ts
index 17c1c1f2..ba184986 100644
--- a/src/lib/av/clean-dialogue.ts
+++ b/src/lib/av/clean-dialogue.ts
@@ -118,6 +118,9 @@ export interface CleanDialoguePlan extends ToolPlan {
const nameOf = (i: Pick<CleanDialogueInput, "name" | "kind">) => i.name?.trim() || (i.kind === "video" ? "video soundtrack" : "recording");
+/** A video too big for the cloud to take its sound from: its sound alone (an MP3 made in the browser) fits. */
+export const soundAloneHelps = (problem: string | null | undefined): boolean => !!problem && /files up to (100|512) MB/.test(problem);
+
/** What's in the way of a run (in words the page shows), or null. */
export function cleanDialogueProblem(i: Pick<CleanDialogueInput, "engine" | "media" | "kind" | "silent" | "seconds" | "cleaner" | "bytes">): string | null {
if (!i.media) return `Add the ${i.kind === "video" ? "video" : "audio"} to clean`;
diff --git a/src/lib/av/crop-fit.ts b/src/lib/av/crop-fit.ts
new file mode 100644
index 00000000..4d2dd93a
--- /dev/null
+++ b/src/lib/av/crop-fit.ts
@@ -0,0 +1,15 @@
+/** A picture's shape outside what a tool takes (src/components/av/fit-crop.tsx): the crop offered. */
+
+const SLACK = 0.005;
+
+/** The crop of a `width`×`height` picture at the nearest shape `ratio` allows (centred), or null when it fits. */
+export function cropFor(width: number, height: number, ratio: [number, number]): { x: number; y: number; width: number; height: number } | null {
+ const shape = width / height;
+ if (shape >= ratio[0] - SLACK && shape <= ratio[1] + SLACK) return null;
+ if (shape < ratio[0]) {
+ const h = Math.floor(width / ratio[0]);
+ return { x: 0, y: Math.floor((height - h) / 2), width, height: h };
+ }
+ const w = Math.floor(height * ratio[1]);
+ return { x: Math.floor((width - w) / 2), y: 0, width: w, height };
+}
diff --git a/src/lib/av/fit-file.ts b/src/lib/av/fit-file.ts
new file mode 100644
index 00000000..fc892ff5
--- /dev/null
+++ b/src/lib/av/fit-file.ts
@@ -0,0 +1,93 @@
+/**
+ * What an upload needs before it goes (src/lib/upload.ts), decided from the file's type and name only: the browser half
+ * (src/components/av/fit-file.ts) then converts it. The upload route takes PNG, JPEG, WebP or GIF pictures, MP4, MOV,
+ * WebM, MKV or AVI clips and MP3, WAV, OGG, FLAC, M4A or WebM sound (an account: a picture of up to 25 MB and
+ * 40 megapixels, a sound of up to 50 MB).
+ *
+ * - A type the route knows under another name (Chrome's audio/x-m4a): sent under the route's name, as it is.
+ * - A photo the route can't take (HEIC, AVIF, TIFF, BMP): converted to a JPEG (a WebP when it may have see-through parts).
+ * - A sound the route can't take (AAC, Opus, AIFF, CAF, WMA, AMR): converted to an MP3.
+ * - Refused for its size or type all the same (an account's caps, an account's GIF): made to fit once, and sent again.
+ * Each conversion follows the owner's switches (src/lib/av/upload-switches.ts).
+ */
+
+/** The route's own names for types browsers name otherwise. */
+const ALIASES: Record<string, string> = {
+ "audio/x-m4a": "audio/mp4",
+ "audio/m4a": "audio/mp4",
+ "audio/aacp": "audio/aac",
+ "audio/x-flac": "audio/flac",
+ "audio/wave": "audio/wav",
+ "audio/vnd.wave": "audio/wav",
+ "audio/mp3": "audio/mpeg",
+ "audio/x-mp3": "audio/mpeg",
+ "audio/x-mpeg": "audio/mpeg",
+ "image/jpg": "image/jpeg",
+ "image/pjpeg": "image/jpeg",
+ "image/x-png": "image/png",
+};
+
+const TAKEN = /^(image\/(png|jpeg|webp|gif)|video\/.+|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;
+
+/** By extension, for a file the browser gives no type. */
+const EXT_TYPE: Record<string, string> = {
+ heic: "image/heic",
+ heif: "image/heif",
+ avif: "image/avif",
+ tif: "image/tiff",
+ tiff: "image/tiff",
+ bmp: "image/bmp",
+ aac: "audio/aac",
+ opus: "audio/opus",
+ aif: "audio/aiff",
+ aiff: "audio/aiff",
+ caf: "audio/x-caf",
+ wma: "audio/x-ms-wma",
+ amr: "audio/amr",
+ m4a: "audio/mp4",
+};
+
+const ext = (name: string) => /\.([a-z0-9]{2,5})$/i.exec(name)?.[1]?.toLowerCase() ?? "";
+
+/** The file's type as the upload route reads it ("" when only its name could say, and it doesn't). */
+export function uploadType(file: { type?: string; name?: string }): string {
+ const t = (file.type ?? "").split(";")[0].trim().toLowerCase();
+ const given = t && t !== "application/octet-stream" ? t : (EXT_TYPE[ext(file.name ?? "")] ?? "");
+ return ALIASES[given] ?? given;
+}
+
+export type FileFit =
+ /** Send it as it is (under `type` when that differs from the file's own). */
+ | { kind: "send"; type?: string }
+ /** Convert a photo, or a sound. */
+ | { kind: "photo" }
+ | { kind: "sound" };
+
+/** What a file needs before it is sent: from its type and name only. */
+export function fitBeforeSend(file: { type?: string; name?: string }): FileFit {
+ const type = uploadType(file);
+ if (!type || TAKEN.test(type)) return { kind: "send", ...(type && type !== (file.type ?? "").toLowerCase() && { type }) };
+ if (type.startsWith("image/")) return { kind: "photo" };
+ if (type.startsWith("audio/")) return { kind: "sound" };
+ return { kind: "send" };
+}
+
+/** An account's caps (src/server/account-files.ts ACCOUNT_LIMITS: a test keeps them the same). */
+export const ACCOUNT_PHOTO_BYTES = 25 * 1024 * 1024;
+export const ACCOUNT_PHOTO_PIXELS = 40_000_000;
+export const ACCOUNT_SOUND_BYTES = 50 * 1024 * 1024;
+
+/**
+ * After the route refused a file (413: too big; 415: a type it doesn't take): what to make of it, or null when there's
+ * nothing to fit (a clip, a full allowance, anything else).
+ */
+export function fitAfterRefusal(file: { type?: string; name?: string; size: number }, status: number): FileFit | null {
+ if (status !== 413 && status !== 415) return null;
+ const type = uploadType(file);
+ if (type.startsWith("image/")) return { kind: "photo" };
+ if (type.startsWith("audio/")) return { kind: "sound" };
+ return null;
+}
+
+/** Whether a photo may have see-through parts (kept as a WebP where the browser saves one). */
+export const mayHaveAlpha = (file: { type?: string; name?: string }) => /^image\/(png|webp|gif|avif|heic|heif|tiff)$/.test(uploadType(file));
diff --git a/src/lib/av/voice-fit.ts b/src/lib/av/voice-fit.ts
new file mode 100644
index 00000000..51180283
--- /dev/null
+++ b/src/lib/av/voice-fit.ts
@@ -0,0 +1,39 @@
+import { voiceFile, voiceWindow } from "@/lib/catalog/clip-windows";
+import { AUK_TTS_MAX_SAMPLE } from "@/lib/speech-edit";
+import type { AudioFitRule } from "./fit-upload";
+
+/**
+ * The fitting step's rules (src/lib/av/fit-upload.ts) for a voice: a talking avatar's (its model's length window and the
+ * files it documents, src/lib/catalog/clip-windows.ts) and AuK's voice sample (under 20 s, src/lib/speech-edit.ts). A
+ * voice slot takes sound only: a clip dropped beside it is the studio's video.
+ */
+
+/** A model's name without what its picker adds after a dot ("MiniMax H3 Max Lip Sync · up to 15 min"). */
+export const shortName = (name: string) => name.split(" · ")[0].trim();
+
+/** What a model takes when it documents no file types: any sound the app stores. */
+const ANY = ["*"];
+/** The most a converted voice weighs when its model names no size: an account's sound cap. */
+const SOUND_CAP = 50 * 1024 * 1024;
+
+/** A talking avatar's voice, or null when its model has no window or file rule. */
+export function voiceFitRule(model: { id: string; name: string }): AudioFitRule | null {
+ const w = voiceWindow(model.id);
+ const file = voiceFile(model.id);
+ if (!w && !file) return null;
+ return {
+ for: model.name,
+ tool: model.name,
+ formats: file?.formats ?? ANY,
+ maxBytes: file?.bytes,
+ minSeconds: w?.min,
+ maxSeconds: w?.max,
+ outMaxBytes: file?.bytes ?? SOUND_CAP,
+ fromVideo: false,
+ };
+}
+
+/** AuK's voice sample: a part of a longer one. */
+export function sampleFitRule(): AudioFitRule {
+ return { for: "AuK", tool: "AuK", formats: ANY, maxSeconds: AUK_TTS_MAX_SAMPLE, outMaxBytes: SOUND_CAP, fromVideo: false };
+}
diff --git a/src/lib/catalog/clip-windows.ts b/src/lib/catalog/clip-windows.ts
index c00cade8..245a377d 100644
--- a/src/lib/catalog/clip-windows.ts
+++ b/src/lib/catalog/clip-windows.ts
@@ -341,3 +341,40 @@ export function clipWindowProblem(model: { id: string; name: string; engine?: st
const takes = min !== undefined && max !== undefined ? `${min}–${max} s` : max !== undefined ? `up to ${max} s` : `${min} s or longer`;
return `${model.name} takes ${takes} clips, and this one is ${secs(seconds)}: ${long ? "trim it first" : "use a longer one"}`;
}
+
+// ---------------------------------------------------------------------------
+// The same windows, for the browser's fitting step (src/components/av): what a sound, clip or picture is fitted to.
+
+/** The voice length a model takes (the longest any size takes), or undefined. */
+export function voiceWindow(modelId: string): { min: number; max: number } | undefined {
+ const w = VOICE_SECONDS[modelId];
+ return w && { min: w.min, max: Math.max(w.max, ...Object.values(w.byResolution ?? {})) };
+}
+
+/** The voice files a model documents ("mp3", "wav" and a size), or undefined when it takes any. */
+export function voiceFile(modelId: string): { formats: string[]; bytes: number } | undefined {
+ const a = CLIP_FILE[modelId]?.audio;
+ if (!a) return undefined;
+ const formats = [...new Set(a.types.map((t) => (t === "audio/mpeg" ? "mp3" : t.includes("wav") ? "wav" : t.split("/")[1])))];
+ return { formats, bytes: a.bytes };
+}
+
+/** The picture shape a model takes (width ÷ height), or undefined. */
+export const portraitRatio = (modelId: string): [number, number] | undefined => PORTRAIT_RATIO[modelId];
+
+/** The voice-clip length a model's references take, or undefined. */
+export const referenceVoiceWindow = (modelId: string): { min: number; max: number } | undefined => REFERENCE_VOICE_SECONDS[modelId];
+
+/**
+ * The clip length a model takes for an edit (its window, or its frames at `fps`, 30 when not known, for a frame-billed
+ * route), or undefined.
+ */
+export function clipWindow(model: { id: string; engine?: string }, fps?: number): { min?: number; max?: number } | undefined {
+ const f = sourceFrames(model.id, model.engine);
+ if (f) {
+ const rate = fps && fps > 0 ? fps : f.assumeFps;
+ return { min: f.minFrames / rate, max: f.maxFrames / rate };
+ }
+ const w = sourceSeconds(model.id);
+ return w.min !== undefined || w.max !== undefined ? w : undefined;
+}
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 733c1d50..00c78731 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 { sideMultipleProblem, targetShortEdge, upscaledSize, upscaleFactorFor, upscaleTier } from "./av/upscale";
import { wholeClipProblem, wholeClipTool } from "./av/video-finish";
-import { clipFpsProblem, clipSizeProblem, clipWindowProblem } from "./catalog/clip-windows";
+import { clipFpsProblem, clipSizeProblem, clipWindow, clipWindowProblem } from "./catalog/clip-windows";
import { clipBilling, sourceLengthProblem } from "./catalog/plan";
import { addFrameAt, frameTimes, framesInputs, removeFrameAt, spread, type FrameSupport } from "./catalog/keyframes";
import { keyTimes, totalSeconds, type InbetweenTiming } from "./inbetween";
@@ -1337,3 +1337,20 @@ export function relatedHref(related: { href: string; models?: Partial<Record<Eng
if (!model) return related.href;
return `${related.href}${related.href.includes("?") ? "&" : "?"}model=${encodeURIComponent(model)}`;
}
+
+/**
+ * The clip length the attached clip is fitted to before Generate (a part offered: src/components/av/fit-clip.tsx): a clip
+ * edit's window, or a tool's longest source (Kandinsky VSR 5 s, FLUX video upscale 20 s). Undefined when nothing limits it.
+ */
+export function clipFitWindow(
+ op: Operation | undefined,
+ model: (Pick<ModelDef, "options"> & Partial<Pick<ModelDef, "id" | "engine">>) | undefined,
+ fps?: number,
+): { min?: number; max: number } | undefined {
+ if (!model) return undefined;
+ const windowed = op === "v2v" || op === "relight-video" || op === "insert-moment" || op === "extend" || op === "reframe" || op === "remove-object" || op === "motion-transfer";
+ const w = windowed && model.id ? clipWindow({ id: model.id, engine: model.engine }, fps) : undefined;
+ if (w?.max) return { min: w.min, max: w.max };
+ const max = model.options.maxSourceSeconds;
+ return max ? { max } : undefined;
+}
diff --git a/src/lib/upload.ts b/src/lib/upload.ts
index 3b889b87..003df82f 100644
--- a/src/lib/upload.ts
+++ b/src/lib/upload.ts
@@ -1,6 +1,31 @@
import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, refusalCard, type Asset, type ConnectGpuDetail } from "@/lib/api";
import { KINETIC_UPLOAD_HEADER } from "@/lib/guest-access";
import { responseError } from "@/lib/refusals";
+import { fitAfterRefusal, fitBeforeSend, type FileFit } from "@/lib/av/fit-file";
+
+/**
+ * The file as the upload route takes it (src/lib/av/fit-file.ts): under the route's name for its type, or converted in this
+ * browser (a HEIC photo, an AAC sound) when the owner's switches allow. A Kinetic Motion result goes as it is. A file
+ * that needs nothing is returned at once (not a promise), so its upload starts in the same tick as before.
+ */
+function prepared(file: File, kinetic?: boolean): File | Promise<File> {
+ if (kinetic) return file;
+ const fit = fitBeforeSend(file);
+ if (fit.kind === "send") return fit.type ? new File([file], file.name, { type: fit.type, lastModified: file.lastModified }) : file;
+ return converted(file, fit).then((f) => f ?? file);
+}
+
+/** The converter is loaded only when a file needs it. */
+async function converted(file: File, fit: FileFit): Promise<File | null> {
+ const { fitFile } = await import("@/components/av/fit-file");
+ return fitFile(file, fit);
+}
+
+/** Refused for its size or type (an account's caps, an account's GIF): fitted once, or null when nothing fits it. */
+async function refitted(file: File, status: number, kinetic?: boolean): Promise<File | null> {
+ const fit = kinetic ? null : fitAfterRefusal(file, status);
+ return fit ? converted(file, fit).catch(() => null) : null;
+}
/**
* Upload a file as it is (the body is the file; its type and its name in headers), so the server streams it to disk
@@ -8,13 +33,21 @@ import { responseError } from "@/lib/refusals";
* marked when the refusal shows its own card (src/lib/refusals.ts).
*/
export async function postFile(file: File, signal?: AbortSignal, opts: { kinetic?: boolean } = {}): Promise<Asset> {
- const res = await fetch("/api/uploads", {
- method: "POST",
- body: file,
- signal,
- // A Kinetic Motion clip or poster rendered in the page: any account may save one (KINETIC_UPLOAD_HEADER).
- headers: { "Content-Type": file.type || "application/octet-stream", "X-File-Name": encodeURIComponent(file.name), ...(opts.kinetic && { [KINETIC_UPLOAD_HEADER]: "1" }) },
- });
+ const send = (f: File) =>
+ fetch("/api/uploads", {
+ method: "POST",
+ body: f,
+ signal,
+ // A Kinetic Motion clip or poster rendered in the page: any account may save one (KINETIC_UPLOAD_HEADER).
+ headers: { "Content-Type": f.type || "application/octet-stream", "X-File-Name": encodeURIComponent(f.name), ...(opts.kinetic && { [KINETIC_UPLOAD_HEADER]: "1" }) },
+ });
+ const ready = prepared(file, opts.kinetic);
+ const first = ready instanceof File ? ready : await ready;
+ let res = await send(first);
+ if (res.status === 413 || res.status === 415) {
+ const again = await refitted(first, res.status, opts.kinetic);
+ if (again && !signal?.aborted) res = await send(again);
+ }
const body = (await res.json().catch(() => ({}))) as Asset & { error?: string };
if (!res.ok) throw responseError(res, body.error ?? "That upload didn't go through. Please try again.");
return body;
@@ -25,7 +58,20 @@ export async function postFile(file: File, signal?: AbortSignal, opts: { kinetic
* clip up to the viewer's limit is streamed to disk (a form is only taken from an account while small). Aborts with
* `signal` (an AbortError).
*/
-export function postFileWithProgress(file: File, onProgress: (p: number) => void, signal?: AbortSignal): Promise<{ url: string; name?: string }> {
+export async function postFileWithProgress(file: File, onProgress: (p: number) => void, signal?: AbortSignal): Promise<{ url: string; name?: string }> {
+ const ready = prepared(file);
+ const first = ready instanceof File ? ready : await ready;
+ try {
+ return await sendWithProgress(first, onProgress, signal);
+ } catch (e) {
+ const status = (e as { status?: number }).status;
+ const again = status === 413 || status === 415 ? await refitted(first, status) : null;
+ if (!again || signal?.aborted) throw e;
+ return sendWithProgress(again, onProgress, signal);
+ }
+}
+
+function sendWithProgress(file: File, onProgress: (p: number) => void, signal?: AbortSignal): Promise<{ url: string; name?: string }> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/uploads");
@@ -36,7 +82,7 @@ export function postFileWithProgress(file: File, onProgress: (p: number) => void
xhr.onload = () => {
const body = xhr.response as { url?: string; name?: string; error?: string } | null;
if (xhr.status >= 200 && xhr.status < 300 && body?.url) return resolve({ url: body.url, name: body.name });
- const err = new Error(body?.error ?? "That upload didn't go through. Please try again.");
+ const err = Object.assign(new Error(body?.error ?? "That upload didn't go through. Please try again."), { status: xhr.status });
// A guest's upload (401 x-fuobe-guest) or an account's with no GPU or key of its own (403 x-fuobe-connect-gpu):
// the card that sets it up opens, as for a fetch (watchGuestRefusals), and the error says it's shown.
const guest = xhr.status === 401 && xhr.getResponseHeader("x-fuobe-guest") === "1";
diff --git a/src/server/dub.ts b/src/server/dub.ts
index 77234274..12899c4a 100644
--- a/src/server/dub.ts
+++ b/src/server/dub.ts
@@ -20,6 +20,7 @@ import {
} from "@/lib/av/dub";
import { normalizeCues } from "@/lib/av/cue-edit";
import { getModel } from "@/lib/catalog";
+import { clipWindowProblem } from "@/lib/catalog/clip-windows";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { ACCOUNT_PROJECT_LIMITS, createAccountProject, deleteAccountProject, getAccountProject, listAccountProjects, updateAccountProject } from "./account-projects";
import type { ToolStep } from "./account-tool-run";
@@ -171,6 +172,16 @@ export function dubVoiceSplit(input: Pick<CreateDubInput, "engine" | "mode" | "v
return input.engine === "open" && input.mode === "steps" ? pickVoiceSplit(input.voiceSplit, (id) => isOffered(id, "open")) : undefined;
}
+/**
+ * Why a one-shot dub's video is longer than its model takes (HeyGen Translate: up to 480 s), in Generate's words, or null.
+ * Checked before anything is sent or priced, so a clip the service would refuse is never billed. A length that can't be
+ * read (no header, nothing measured) is left to the service.
+ */
+export function oneShotLengthProblem(model: OneShotModel, seconds: number | undefined): string | null {
+ if (!seconds) return null;
+ return clipWindowProblem({ id: model, name: getModel(model)?.name ?? model }, seconds);
+}
+
/** A dub planned, not started: the session it will be, and its one-shot jobs or its prepare pipeline. */
export interface DubPlan {
base: DubSession;
@@ -204,6 +215,8 @@ export function planDub(input: CreateDubInput): DubPlan {
};
if (input.mode === "oneshot") {
const model = input.model ?? "heygen-translate";
+ const long = oneShotLengthProblem(model, duration);
+ if (long) throw new Error(long);
return { base, oneshot: { model, jobs: oneShotRequests({ model, video: input.video, source: input.source, targets: base.targets, title }) } };
}
const gpu = tenantAccount() ? ({ translator: "gpu", seconds: duration } as const) : {};
@@ -339,6 +352,8 @@ export function previewDub(input: CreateDubInput): DubPrice {
const seconds = videoLength(input.video, input.duration);
const targets = [...new Set(input.targets)];
if (input.mode === "oneshot") {
+ const long = oneShotLengthProblem(input.model ?? "heygen-translate", seconds);
+ if (long) throw new Error(long);
const jobs = oneShotRequests({ model: input.model ?? "heygen-translate", video: input.video, source: input.source, targets });
return priceSteps(input.engine, jobs.map((j, i) => ({ key: `dub:${i}`, request: j.request })), seconds);
}
diff --git a/tests/upload-fit-tools.test.ts b/tests/upload-fit-tools.test.ts
new file mode 100644
index 00000000..6ecdd14c
--- /dev/null
+++ b/tests/upload-fit-tools.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+import { cropFor } from "@/lib/av/crop-fit";
+import { ACCOUNT_PHOTO_BYTES, ACCOUNT_PHOTO_PIXELS, ACCOUNT_SOUND_BYTES, fitAfterRefusal, fitBeforeSend, uploadType } from "@/lib/av/fit-file";
+import { planAudioFit } from "@/lib/av/fit-upload";
+import { sampleFitRule, voiceFitRule } from "@/lib/av/voice-fit";
+import { soundAloneHelps } from "@/lib/av/clean-dialogue";
+import { clipWindow, portraitRatio, voiceFile, voiceWindow } from "@/lib/catalog/clip-windows";
+import { clipFitWindow } from "@/lib/composer";
+import { getModel } from "@/lib/catalog";
+
+const dir = tempDir("fuobe-upload-fit-tools-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+const { ACCOUNT_LIMITS } = await import("@/server/account-files");
+const dub = await import("@/server/dub");
+const { saveFile } = await import("@/server/storage");
+
+describe("uploads: what a file needs before it goes", () => {
+ it("sends what the route takes as it is, under the route's own name for its type", () => {
+ expect(fitBeforeSend({ type: "image/png", name: "a.png" })).toEqual({ kind: "send" });
+ expect(fitBeforeSend({ type: "video/quicktime", name: "a.mov" })).toEqual({ kind: "send" });
+ expect(fitBeforeSend({ type: "audio/x-m4a", name: "a.m4a" })).toEqual({ kind: "send", type: "audio/mp4" });
+ expect(fitBeforeSend({ type: "image/jpg", name: "a.jpg" })).toEqual({ kind: "send", type: "image/jpeg" });
+ expect(fitBeforeSend({ type: "", name: "notes.glb" })).toEqual({ kind: "send" });
+ });
+
+ it("converts the photos and sounds the route can't take, by type or by name", () => {
+ expect(fitBeforeSend({ type: "image/heic", name: "IMG_1.HEIC" })).toEqual({ kind: "photo" });
+ expect(fitBeforeSend({ type: "", name: "IMG_1.HEIC" })).toEqual({ kind: "photo" });
+ expect(fitBeforeSend({ type: "image/avif", name: "a.avif" })).toEqual({ kind: "photo" });
+ expect(fitBeforeSend({ type: "audio/aac", name: "a.aac" })).toEqual({ kind: "sound" });
+ expect(fitBeforeSend({ type: "", name: "voice.opus" })).toEqual({ kind: "sound" });
+ expect(fitBeforeSend({ type: "audio/x-caf", name: "a.caf" })).toEqual({ kind: "sound" });
+ expect(uploadType({ type: "audio/wave" })).toBe("audio/wav");
+ });
+
+ it("fits a refused photo or sound once (size or type), never a clip or another refusal", () => {
+ expect(fitAfterRefusal({ type: "image/jpeg", name: "big.jpg", size: 30e6 }, 413)).toEqual({ kind: "photo" });
+ expect(fitAfterRefusal({ type: "image/gif", name: "a.gif", size: 1e6 }, 415)).toEqual({ kind: "photo" });
+ expect(fitAfterRefusal({ type: "audio/wav", name: "long.wav", size: 60e6 }, 413)).toEqual({ kind: "sound" });
+ expect(fitAfterRefusal({ type: "video/mp4", name: "a.mp4", size: 99e6 }, 413)).toBeNull();
+ expect(fitAfterRefusal({ type: "image/png", name: "a.png", size: 1e6 }, 403)).toBeNull();
+ });
+
+ it("keeps an account's caps the same as the server's", () => {
+ expect(ACCOUNT_PHOTO_BYTES).toBe(ACCOUNT_LIMITS.imageBytes);
+ expect(ACCOUNT_PHOTO_PIXELS).toBe(ACCOUNT_LIMITS.imagePixels);
+ expect(ACCOUNT_SOUND_BYTES).toBe(ACCOUNT_LIMITS.audioBytes);
+ });
+});
+
+describe("uploads: the windows a tool's file is fitted to", () => {
+ it("reads a voice's window and files from the model's own rules", () => {
+ expect(voiceWindow("minimax-h3-max-lipsync")).toEqual({ min: 5, max: 900 });
+ expect(voiceWindow("omnihuman")?.max).toBe(60);
+ expect(voiceFile("omnihuman-2")).toEqual({ formats: ["mp3", "wav"], bytes: 15 * 1024 * 1024 });
+ expect(voiceFile("minimax-h3-max-lipsync")).toBeUndefined();
+ expect(portraitRatio("minimax-h3-max-lipsync")).toEqual([0.4, 2.5]);
+ });
+
+ it("offers a part of a long voice, and converts one OmniHuman 2 can't take", () => {
+ const h3 = voiceFitRule({ id: "minimax-h3-max-lipsync", name: "H3 Max lip sync" })!;
+ expect(planAudioFit(h3, { format: "m4a", bytes: 9e6, seconds: 1000 })).toMatchObject({ kind: "refuse" });
+ expect(planAudioFit(h3, { format: "m4a", bytes: 9e6, seconds: 600 })).toEqual({ kind: "keep" });
+ const omni = voiceFitRule({ id: "omnihuman-2", name: "OmniHuman 2" })!;
+ expect(planAudioFit(omni, { format: "m4a", bytes: 3e6, seconds: 60 })).toMatchObject({ kind: "convert" });
+ expect(planAudioFit(omni, { format: "mp3", bytes: 3e6, seconds: 400 })).toMatchObject({ kind: "trim", max: 300 });
+ expect(voiceFitRule({ id: "flux-2", name: "FLUX" })).toBeNull();
+ expect(planAudioFit(sampleFitRule(), { format: "wav", bytes: 3e6, seconds: 45 })).toMatchObject({ kind: "trim", max: 20 });
+ });
+
+ it("finds a clip edit's window, or a tool's longest source", () => {
+ const vsr = getModel("kandinsky-vsr");
+ expect(vsr && clipFitWindow("upscale-video", vsr)).toEqual({ max: 5 });
+ expect(clipWindow({ id: "heygen-translate" })).toEqual({ max: 480 });
+ expect(clipFitWindow("v2v", { id: "heygen-translate", options: {} })).toEqual({ max: 480 });
+ expect(clipFitWindow("t2v", { id: "heygen-translate", options: {} })).toBeUndefined();
+ });
+
+ it("crops a picture to the nearest shape the tool takes, centred", () => {
+ expect(cropFor(1000, 3000, [0.4, 2.5])).toEqual({ x: 0, y: 250, width: 1000, height: 2500 });
+ expect(cropFor(3000, 1000, [0.4, 2.5])).toEqual({ x: 250, y: 0, width: 2500, height: 1000 });
+ expect(cropFor(1000, 1000, [0.4, 2.5])).toBeNull();
+ });
+
+ it("offers the sound alone for a video too big for the cloud, not for other refusals", () => {
+ expect(soundAloneHelps("The cloud takes a video's soundtrack from files up to 100 MB — trim or compress it")).toBe(true);
+ expect(soundAloneHelps("VEED cleans up to 30 minutes — trim it first, or pick another cleaner")).toBe(false);
+ expect(soundAloneHelps(null)).toBe(false);
+ });
+});
+
+describe("Dub: one shot's own length, before anything is sent", () => {
+ // A clip whose header can't be read here: the browser's measure stands.
+ const clip = () => saveFile({ data: Buffer.from("not a real clip"), contentType: "video/webm", source: "upload" }).url;
+
+ it("refuses HeyGen Translate past 480 s in the price check and the plan, in Generate's words", () => {
+ const body = { engine: "cloud" as const, mode: "oneshot" as const, model: "heygen-translate" as const, video: clip(), targets: ["es"], duration: 600 };
+ expect(() => dub.previewDub(body)).toThrow(/takes up to 480 s clips, and this one is 600 s: trim it first/);
+ expect(() => dub.planDub(body)).toThrow(/up to 480 s/);
+ expect(dub.oneShotLengthProblem("heygen-translate-fast", 481)).toMatch(/480 s/);
+ expect(dub.oneShotLengthProblem("heygen-translate", 479)).toBeNull();
+ expect(dub.oneShotLengthProblem("heygen-translate", undefined)).toBeNull();
+ // Within it, the plan goes on as before.
+ expect(dub.planDub({ ...body, duration: 300 }).oneshot?.jobs.length).toBe(1);
+ });
+});