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.

Audio: a lyrics editor with section tags and Write the lyrics, songs up to 5:00, and Extend & remix (Mureka extend, remix and stems) from any song

Claudec31103ebe99c
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index 5441bddc..352c4b2c 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -1035,6 +1035,16 @@ model("minimax-music-3", "MiniMax Music 3 · both engines", "MiniMax", "minimax-
model("elevenlabs-music-2-5", "ElevenLabs Music v2.5", "ElevenLabs", "elevenlabs", "audio", "Studio-quality songs and scores up to 10 minutes",
[("music", "elevenlabs/music/v2.5", "fal", {"drop": ["seed"]})], badges=["new"], pricing=("minute", 0.6, "billed per started minute", {"roundUp": True}),
defaults={"duration": 60}, options={"durations": [15, 30, 60, 120, 180, 300, 600]})
+# Mureka's song tools (Audio → Extend & remix, and a music result's Extend, Remix and Stems): the song is one of Mureka's own
+# (params.extra.songId, kept on its results) or a file sent first through Mureka's files/upload ($0.01, Pricing.uploadUsd).
+model("mureka-extend", "Mureka Extend", "Mureka", "mureka", "audio", "Makes a song longer with new lyrics, after its end or before its start",
+ [("song-extend", "mureka/v8/song/extend")], badges=["new"], pricing=("request", 0.004, "plus $0.01 to send a song Mureka didn't make", {"uploadUsd": 0.01}),
+ controls=[("extend_type", "Where", {"tail": "After the end", "head": "Before the start"})])
+model("mureka-remix", "Mureka Remix", "Mureka", "mureka", "audio", "A new arrangement of a song in the style you describe, with its lyrics",
+ [("song-remix", "mureka/v8/song/remix")], badges=["new"], pricing=("request", 0.20, "plus $0.01 to send a song Mureka didn't make", {"uploadUsd": 0.01}))
+# Its stems come back as a zip (zip_url): the fal provider opens it and keeps each track as a result of its own.
+model("mureka-stems", "Mureka Stems", "Mureka", "mureka", "audio", "A song split into its vocal and instrument tracks",
+ [("song-stems", "mureka/api/song/stem")], badges=["new"], pricing=("request", 0.20, "audio-separation-3, the default"))
# "Negative prompting is not supported by Lyria 3.5" (its schema): no negative prompt.
model("lyria-3-5", "Lyria 3.5", "Google", "lyria", "audio", "Google DeepMind's newest music model: full songs from words or a picture",
[("music", "google/lyria-3.5", "fal", {"drop": ["negativePrompt"]})], badges=["new"])
@@ -2130,10 +2140,22 @@ def build_route(op, ep, provider, m, opts, ropts=None):
fmap["duration"]["multiplier"] = 1000
# Song lyrics (params.extra.lyrics, nm10-music3): the API's lyrics field and the most characters it takes, or after the
# prompt for an API that reads them there (Lyria 3.5); the composer's lyrics editor follows ModelOptions.lyrics.
- if op == "music" and "lyrics" in kf and (inputs.get(kf["lyrics"]) or {}).get("type") == "string":
- most = num((inputs.get(kf["lyrics"]) or {}).get("maxLength"))
+ if op in ("music", "song-extend", "song-remix") and "lyrics" in kf and (inputs.get(kf["lyrics"]) or {}).get("type") == "string":
+ spec = inputs.get(kf["lyrics"]) or {}
+ most = num(spec.get("maxLength"))
fmap["lyrics"] = {"key": kf["lyrics"], **({"max": most} if most else {})}
- opts["lyrics"] = {**({"max": most} if most else {})}
+ opts["lyrics"] = {**({"max": most} if most else {}), **({"required": True} if spec.get("required") else {})}
+ # A song tool's source (Mureka): its own song by id, else the file sent first through the provider's files/upload with
+ # the purpose the id field names ("Audio ID returned by /files/upload with purpose='audio'").
+ if op in ("song-extend", "song-remix") and "songId" in kf and "uploadId" in kf:
+ purpose = re.search(r"purpose='([\w-]+)'", (inputs.get(kf["uploadId"]) or {}).get("desc") or "")
+ upload = next((ep2 for (p2, ep2) in EPS if p2 == provider and ep2.startswith(ep.split("/")[0] + "/") and ep2.endswith("/files/upload")), None)
+ if purpose and upload:
+ fmap["songSource"] = {"songId": kf["songId"], "uploadId": kf["uploadId"], "upload": {"endpoint": upload, "purpose": purpose.group(1)}}
+ else:
+ warn(f"{m['id']}: {ep} has no upload route or purpose for its song")
+ if "extendAt" in kf:
+ fmap["startTime"] = {"key": kf["extendAt"], "type": "number", "multiplier": 1000}
elif op == "music" and "lyricsInPrompt" in kf:
most = num((inputs.get(kf["lyricsInPrompt"]) or {}).get("maxLength"))
fmap["lyrics"] = {"inPrompt": True, **({"max": most} if most else {})}
diff --git a/src/app/api/enhance/route.ts b/src/app/api/enhance/route.ts
index 0e350cab..6980e577 100644
--- a/src/app/api/enhance/route.ts
+++ b/src/app/api/enhance/route.ts
@@ -1,10 +1,23 @@
-import { enhancePrompt } from "@/server/enhance";
+import { enhancePrompt, writeLyrics } from "@/server/enhance";
import type { MediaKind, Operation } from "@/lib/catalog/types";
export async function POST(request: Request) {
- const { prompt, kind, op } = (await request.json().catch(() => ({}))) as { prompt?: string; kind?: MediaKind; op?: Operation };
+ const { prompt, kind, op, target, seconds, max } = (await request.json().catch(() => ({}))) as {
+ prompt?: string;
+ kind?: MediaKind;
+ op?: Operation;
+ /** "lyrics": Audio → Music's "Write the lyrics" (words to sing for the song `prompt` describes). */
+ target?: "lyrics";
+ seconds?: number;
+ max?: number;
+ };
if (!prompt?.trim()) return Response.json({ error: "Empty prompt" }, { status: 400 });
try {
+ if (target === "lyrics") {
+ const lyrics = await writeLyrics(prompt.slice(0, 4000), { seconds: Number(seconds) || undefined, max: Number(max) || undefined });
+ if (!lyrics) return Response.json({ error: "Writing lyrics needs the AI helper: pick Claude or a local model in Settings → AI helper", code: "no-llm" }, { status: 503 });
+ return Response.json({ lyrics });
+ }
return Response.json({ prompt: await enhancePrompt(prompt, kind ?? "image", op ?? "t2i") });
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 502 });
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 1aa80581..73c08670 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -12,7 +12,9 @@ import { Kbd } from "@/components/ui/kbd";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useToday } from "@/hooks/use-today";
import { estimateCost, imageLimit, layoutCanvas, planGeneration, routesFor, type Plan } from "@/lib/catalog/plan";
-import type { Engine, GenerationRequest, MediaKind, ModelDef, Operation, Preset, PresetRoute, VideoFormat } from "@/lib/catalog/types";
+import type { Engine, GenerationRequest, InputSlot, MediaKind, ModelDef, Operation, Preset, PresetRoute, VideoFormat } from "@/lib/catalog/types";
+import { LYRICS_PARAM } from "@/lib/lyrics";
+import { SONG_ID_PARAM } from "@/lib/catalog/payload";
import { dualEngine } from "@/lib/catalog/engines";
import { locksByDefault } from "@/lib/catalog/palettes";
import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";
@@ -103,6 +105,7 @@ import { ELEMENT_ICONS, PromptInput, type PromptInputHandle } from "./prompt-inp
import { radioKeys, radioTab } from "./radio-keys";
import { SettingsChip } from "./settings-panel";
import { ShotsEditor } from "./shots-editor";
+import { LyricsEditor } from "./lyrics-editor";
import { SketchTools } from "./sketch-tools";
import { RECENT_MODELS, useStoredList } from "./stored-list";
import { usePresetUrl, useStartRequest, useStudio, type Draft } from "./studio-context";
@@ -226,6 +229,23 @@ function useRecipeMade(preset: Preset | undefined, engine: Engine, recipeModel:
return !!key && !!made[key];
}
+/** Operations whose models sing lyrics (the lyrics editor): a song, and a song extended or remixed. */
+const SUNG_OPS = new Set<Operation>(["music", "song-extend", "song-remix"]);
+
+/**
+ * Audio → Music: the lyrics go to a model that sings them (params.extra.lyrics), and a song to cover only to a model that
+ * covers one (the slot is hidden for the others, so a song left there from YuE2 is never sent to them).
+ */
+function songDraft<D extends Pick<Draft, "lyrics" | "params" | "slots" | "song">>(d: D, model: ModelDef | undefined, slots: InputSlot[]): D {
+ let out = d;
+ if (d.lyrics?.trim() && model?.options.lyrics) out = { ...out, params: { ...out.params, extra: { ...out.params.extra, [LYRICS_PARAM]: d.lyrics } } };
+ // One of Mureka's own songs, still the one attached: its tools take it by id (no upload).
+ if (d.song && d.slots.audio?.ref === d.song.url && model?.family === "mureka") out = { ...out, params: { ...out.params, extra: { ...out.params.extra, [SONG_ID_PARAM]: d.song.id } } };
+ const hidden = slots.filter((s) => s.cover && !model?.options.cover && out.slots[s.key]).map((s) => s.key);
+ if (hidden.length) out = { ...out, slots: Object.fromEntries(Object.entries(out.slots).filter(([k]) => !hidden.includes(k as InputSlot["key"]))) };
+ return out;
+}
+
/** Leaving a model that takes looks (Fuobe Soul) for one that doesn't: the look (its presetId) doesn't come along. */
function lookCleared(from: ModelDef | undefined, to: ModelDef): Partial<Draft> {
return from?.options.looks && !to.options.looks ? { presetId: undefined, presetStrength: undefined } : {};
@@ -538,7 +558,8 @@ export function Composer({ docked }: { docked: boolean }) {
() => namedImageSlots(baseSlots, model?.options.imageLabels, config.multiRef?.label, draft.refs.length),
[baseSlots, model?.options.imageLabels, config.multiRef?.label, draft.refs.length],
);
- const slots = named.slots;
+ // A song to cover (Audio → Music) shows only for a model that covers one (YuE2).
+ const slots = useMemo(() => named.slots.filter((s) => !s.cover || !!model?.options.cover), [named.slots, model?.options.cover]);
const hasCleanVoice = slots.some((s) => s.cleanVoice && s.accept === "audio");
// Clips: ComfyUI joins 4 at a time. Images: what the model takes beyond the fixed image slots, for the operation the run
// will be (a painted mask makes it an inpaint, which Qwen-Image 2.1 runs on the picture alone).
@@ -572,7 +593,8 @@ export function Composer({ docked }: { docked: boolean }) {
// A picked palette / moodboard routes the request (and can move it to another model) before anything else.
const signature = useSignature(!!config.signature, draft.signature);
- const prepare = (d: typeof draft) => {
+ const prepare = (draftIn: typeof draft) => {
+ const d = songDraft(draftIn, catalog.getModel(draftIn.modelId), config.slots);
const signed = signature.apply(buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(d.modelId)));
// Planned with the signature's sentences in the prompt (as the server runs it); sent with them apart.
const raw = signed.worded;
@@ -727,7 +749,9 @@ export function Composer({ docked }: { docked: boolean }) {
setRecent((r) => pushRecent(r, draft.modelId));
// The server resolves @mentions and drawings itself; only pin the operation when there are none.
// No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.
- const sent = signature.apply(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)));
+ const sent = signature.apply(
+ buildRequest(config.feature, songDraft(draft, model, config.slots), resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)),
+ );
// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).
if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors }, { onError: (e) => toastError(e) });
// If the server's pre-flight stops it (409 gpu-setup), the guided fix that opens can try again, or run it anyway.
@@ -1266,6 +1290,10 @@ export function Composer({ docked }: { docked: boolean }) {
/>
)}
+ {model?.options.lyrics && effectiveOp && SUNG_OPS.has(effectiveOp) && !collapsed && (
+ <LyricsEditor model={model} value={draft.lyrics ?? ""} onChange={(lyrics) => setDraft({ lyrics })} idea={draft.prompt} seconds={p.duration ?? model.defaults?.duration} />
+ )}
+
{model && effectiveOp === "dialogue" && <DialogueEditor model={model} lines={p.dialogue ?? defaultLines(model)} onChange={(dialogue) => setP({ dialogue })} />}
{model?.options.multiShot && p.shots && <ShotsEditor model={model} shots={p.shots} onChange={(shots) => setP({ shots })} />}
diff --git a/src/components/studio/lyrics-editor.tsx b/src/components/studio/lyrics-editor.tsx
new file mode 100644
index 00000000..728fb9ea
--- /dev/null
+++ b/src/components/studio/lyrics-editor.tsx
@@ -0,0 +1,138 @@
+"use client";
+
+import { Loader2, Music2, PenLine, Sparkles, X } from "lucide-react";
+import { useId, useRef, useState } from "react";
+import { toast } from "sonner";
+import { writeLyrics } from "@/lib/api";
+import type { ModelDef } from "@/lib/catalog/types";
+import { INSTRUMENTAL, insertTag, isInstrumental, normalizeLyrics, SECTION_TAGS, songLength, structureOf } from "@/lib/lyrics";
+import { toastError } from "@/lib/refusals";
+import { cn } from "@/lib/utils";
+
+/** The section tags offered as chips, most used first (the rest are one tap away in the same row). */
+const CHIPS = ["Verse", "Chorus", "Pre-Chorus", "Bridge", "Intro", "Outro", "Instrumental", "Solo"] as const satisfies readonly (typeof SECTION_TAGS)[number][];
+
+/**
+ * Audio → Music's lyrics, for a model that sings them (ModelOptions.lyrics): the words with their section tags, chips that
+ * put a tag on a line of its own at the cursor, "Write the lyrics" (the install's AI helper, from the song's description),
+ * and how many characters the model takes. The draft keeps the words while you switch models; only one that sings gets them.
+ */
+export function LyricsEditor({
+ model,
+ value,
+ onChange,
+ idea,
+ seconds,
+}: {
+ model: ModelDef;
+ value: string;
+ onChange: (v: string) => void;
+ /** The song's description (the prompt): what "Write the lyrics" writes for. */
+ idea: string;
+ /** The length picked, so written lyrics fit it. */
+ seconds?: number;
+}) {
+ const id = useId();
+ const area = useRef<HTMLTextAreaElement>(null);
+ const [writing, setWriting] = useState(false);
+ const spec = model.options.lyrics ?? {};
+ const length = normalizeLyrics(value).length;
+ const over = !!spec.max && length > spec.max;
+ const structure = structureOf(value);
+ const instrumental = !!value.trim() && isInstrumental(value);
+
+ const tag = (name: string) => {
+ const el = area.current;
+ const at = el ? el.selectionStart : value.length;
+ const next = insertTag(value, at, name);
+ onChange(next.text);
+ requestAnimationFrame(() => {
+ if (!area.current) return;
+ area.current.focus();
+ area.current.setSelectionRange(next.cursor, next.cursor);
+ });
+ };
+
+ const write = async () => {
+ if (!idea.trim()) return toast("Describe the song first: its subject, mood and style. The lyrics are written from it");
+ setWriting(true);
+ try {
+ onChange(await writeLyrics(idea, { seconds, max: spec.max }));
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setWriting(false);
+ }
+ };
+
+ return (
+ <div className="mx-2 mb-2 rounded-xl border bg-background" data-testid="lyrics-editor">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-3 pt-2">
+ <label htmlFor={id} className="inline-flex items-center gap-1.5 text-[13px] font-medium">
+ <PenLine className="size-3.5 text-muted-foreground" /> Lyrics
+ {!spec.required && <span className="font-normal text-muted-foreground">optional</span>}
+ </label>
+ <span className="ml-auto flex items-center gap-1">
+ <button
+ type="button"
+ onClick={write}
+ disabled={writing}
+ className="inline-flex h-7 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium text-brand-text hover:bg-brand-faint disabled:opacity-60"
+ >
+ {writing ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}
+ {writing ? "Writing…" : "Write the lyrics"}
+ </button>
+ {!spec.required && (
+ <button
+ type="button"
+ onClick={() => onChange(instrumental ? "" : INSTRUMENTAL)}
+ aria-pressed={instrumental}
+ className={cn("inline-flex h-7 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium hover:bg-accent", instrumental ? "bg-brand-faint text-brand-text" : "text-muted-foreground")}
+ >
+ <Music2 className="size-3.5" /> Instrumental
+ </button>
+ )}
+ {value && (
+ <button type="button" onClick={() => onChange("")} className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Clear the lyrics">
+ <X className="size-3.5" />
+ </button>
+ )}
+ </span>
+ </div>
+ <div className="flex flex-wrap gap-1 px-2.5 pt-1.5" role="group" aria-label="Add a section">
+ {CHIPS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ onClick={() => tag(c)}
+ className="h-6 rounded-full border bg-secondary px-2 font-mono text-[11px] text-secondary-foreground hover:bg-accent"
+ >
+ [{c}]
+ </button>
+ ))}
+ </div>
+ <textarea
+ id={id}
+ ref={area}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ rows={6}
+ spellCheck
+ placeholder={"[Verse]\nThe words of the first verse…\n\n[Chorus]\nThe hook everyone sings…"}
+ aria-describedby={`${id}-hint`}
+ className="mt-1.5 block max-h-72 min-h-28 w-full resize-y bg-transparent px-3 py-1.5 text-[14px] leading-relaxed outline-none placeholder:text-muted-foreground/70"
+ />
+ <p id={`${id}-hint`} className={cn("flex flex-wrap items-center gap-x-2 border-t px-3 py-1.5 text-[11px] text-muted-foreground", over && "text-destructive")}>
+ <span className="min-w-0 flex-1">
+ {structure.length ? structure.join(" · ") : spec.inPrompt ? `${model.name} reads the lyrics with your description` : "Each tag on its own line, the words under it"}
+ {seconds ? ` · up to ${songLength(seconds)}` : ""}
+ </span>
+ {spec.max ? (
+ <span className="tabular-nums">
+ {length.toLocaleString("en-US")} / {spec.max.toLocaleString("en-US")}
+ </span>
+ ) : null}
+ </p>
+ </div>
+ );
+}
diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsx
index b3cbf548..bdf2b7f2 100644
--- a/src/components/studio/mode-switch-studio.tsx
+++ b/src/components/studio/mode-switch-studio.tsx
@@ -10,6 +10,7 @@ import {
MUSIC_STUDIO,
SDR_TO_HDR_STUDIO,
SFX_STUDIO,
+ SONG_TOOLS_STUDIO,
TRANSCRIBE_STUDIO,
TRANSLATE_STUDIO,
UPSCALE_STUDIO,
@@ -46,6 +47,7 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {
transcribe: TRANSCRIBE_STUDIO,
sfx: SFX_STUDIO,
music: MUSIC_STUDIO,
+ song: SONG_TOOLS_STUDIO,
video: FOLEY_STUDIO,
},
"video-tools": {
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 758ed278..7c762486 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -2,6 +2,9 @@
import {
ArchiveRestore,
+ Disc3,
+ Layers3,
+ ListMusic,
AudioLines,
BookmarkPlus,
Box,
@@ -122,6 +125,9 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
"delete-upload": Trash2,
restore: ArchiveRestore,
"restore-video": Palette,
+ "extend-song": ListMusic,
+ "remix-song": Disc3,
+ "song-stems": Layers3,
"delete-forever": Trash2,
};
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 7a5378fb..70159b47 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -119,6 +119,10 @@ export interface Draft {
frames?: FrameAttachment<SlotValue>[];
/** Layout mode is on (studios with `layout`): the boxes, as fractions of the picture (the prompt is its caption). */
layout?: LayoutDraft;
+ /** Song lyrics with section tags (Audio → Music): sent as params.extra.lyrics to a model that sings them (ModelOptions.lyrics). */
+ lyrics?: string;
+ /** The attached song is one of Mureka's own (a music result's meta.songId): its song tools take it by id, not as a file. */
+ song?: { id: string; url: string };
}
interface Actions {
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index ba89cf3f..1172f65e 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -1,5 +1,6 @@
"use client";
+import { LYRICS_PARAM } from "@/lib/lyrics";
import { ArrowRight, ArrowUp, Loader2, Upload, Zap } from "lucide-react";
import Link from "next/link";
import dynamic from "next/dynamic";
@@ -135,6 +136,8 @@ function initialDraft(
}
if (sp.get("video")) slots.video = slot(sp.get("video"));
if (sp.get("audio")) slots.audio = slot(sp.get("audio"));
+ // A Mureka song handed over (a music result's Extend, Remix or Stems): its id goes with it.
+ const song = sp.get("audio") && sp.get("song") ? { id: sp.get("song")!, url: sp.get("audio")! } : undefined;
// A voice sample handed over (Clean up voice → "Use as a voice sample"): the voice a cloning model speaks with.
if (sp.get("voice")) slots.voiceAudio = slot(sp.get("voice"));
// An output format handed over in the link (Export → "ProRes in the cloud"), when the model writes it.
@@ -150,6 +153,7 @@ function initialDraft(
refs,
presetId: sp.get("preset") ?? config.preset?.id,
presetOptions: {},
+ ...(song && { song }),
};
}
@@ -182,6 +186,13 @@ function draftFromGeneration(g: Generation, config: StudioConfig, getModel: (id:
// A spoken language stored as a name (Assist's "Spanish") or a locale comes back as the model's own code.
const languages = getModel(r.modelId)?.options.sourceLanguages;
if (languages?.length && params.sourceLanguage) params.sourceLanguage = matchSpokenLanguage(params.sourceLanguage, languages) ?? params.sourceLanguage;
+ // A song's lyrics come back in the lyrics editor.
+ const lyrics = typeof params.extra?.[LYRICS_PARAM] === "string" ? (params.extra[LYRICS_PARAM] as string) : undefined;
+ if (lyrics !== undefined) {
+ const rest = { ...params.extra };
+ delete rest[LYRICS_PARAM];
+ params.extra = Object.keys(rest).length ? rest : undefined;
+ }
// A layout run comes back in Layout mode (studios that have it): its boxes in the editor, the prompt as their caption.
const laid = config.layout ? withoutLayout(params) : { params, layout: undefined };
return {
@@ -198,6 +209,7 @@ function draftFromGeneration(g: Generation, config: StudioConfig, getModel: (id:
presetStrength: r.presetStrength,
mix: r.mix,
signature: signed?.signature,
+ lyrics,
};
}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 51c75b28..d2e95598 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -934,6 +934,19 @@ export async function enhance(prompt: string, kind: MediaKind, op: string): Prom
).prompt;
}
+/** Audio → Music's "Write the lyrics": tagged lyrics for the song `idea` describes (the install's AI helper writes them). */
+export async function writeLyrics(idea: string, o: { seconds?: number; max?: number } = {}): Promise<string> {
+ return (
+ await json<{ lyrics: string }>(
+ await fetch("/api/enhance", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ prompt: idea, target: "lyrics", ...o }),
+ }),
+ )
+ ).lyrics;
+}
+
// ---------------------------------------------------------------------------
// Engine preference (Cloud vs Open source), shared across tabs via localStorage.
// Settings → Engine mode can lock the install to one engine; then the toggle is disabled.
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index 4ea8f4e4..f0521aba 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -12796,7 +12796,9 @@ export const CLOUD_MODELS: ModelDef[] = [
],
"options": {
"seed": true,
- "lyrics": {},
+ "lyrics": {
+ "required": true
+ },
"durations": [
30,
60,
@@ -12870,6 +12872,149 @@ export const CLOUD_MODELS: ModelDef[] = [
"roundUp": true
}
},
+ {
+ "id": "mureka-extend",
+ "name": "Mureka Extend",
+ "vendor": "Mureka",
+ "family": "mureka",
+ "engine": "cloud",
+ "kind": "audio",
+ "tagline": "Makes a song longer with new lyrics, after its end or before its start",
+ "routes": [
+ {
+ "op": "song-extend",
+ "provider": "fal",
+ "endpoint": "mureka/v8/song/extend",
+ "map": {
+ "prompt": false,
+ "lyrics": {
+ "key": "lyrics",
+ "max": 3000
+ },
+ "songSource": {
+ "songId": "song_id",
+ "uploadId": "upload_audio_id",
+ "upload": {
+ "endpoint": "mureka/api/files/upload",
+ "purpose": "audio"
+ }
+ },
+ "startTime": {
+ "key": "extend_at",
+ "type": "number",
+ "multiplier": 1000
+ }
+ }
+ }
+ ],
+ "options": {
+ "controls": [
+ {
+ "param": "extend_type",
+ "label": "Where",
+ "values": [
+ "tail",
+ "head"
+ ],
+ "default": "tail",
+ "labels": {
+ "tail": "After the end",
+ "head": "Before the start"
+ }
+ }
+ ],
+ "lyrics": {
+ "max": 3000,
+ "required": true
+ },
+ "promptless": true
+ },
+ "badges": [
+ "new"
+ ],
+ "pricing": {
+ "unit": "request",
+ "usd": 0.004,
+ "note": "plus $0.01 to send a song Mureka didn't make",
+ "uploadUsd": 0.01
+ }
+ },
+ {
+ "id": "mureka-remix",
+ "name": "Mureka Remix",
+ "vendor": "Mureka",
+ "family": "mureka",
+ "engine": "cloud",
+ "kind": "audio",
+ "tagline": "A new arrangement of a song in the style you describe, with its lyrics",
+ "routes": [
+ {
+ "op": "song-remix",
+ "provider": "fal",
+ "endpoint": "mureka/v8/song/remix",
+ "map": {
+ "lyrics": {
+ "key": "lyrics",
+ "max": 5000
+ },
+ "songSource": {
+ "songId": "song_id",
+ "uploadId": "upload_audio_id",
+ "upload": {
+ "endpoint": "mureka/api/files/upload",
+ "purpose": "remix"
+ }
+ }
+ }
+ }
+ ],
+ "options": {
+ "lyrics": {
+ "max": 5000,
+ "required": true
+ }
+ },
+ "badges": [
+ "new"
+ ],
+ "pricing": {
+ "unit": "request",
+ "usd": 0.2,
+ "note": "plus $0.01 to send a song Mureka didn't make",
+ "uploadUsd": 0.01
+ }
+ },
+ {
+ "id": "mureka-stems",
+ "name": "Mureka Stems",
+ "vendor": "Mureka",
+ "family": "mureka",
+ "engine": "cloud",
+ "kind": "audio",
+ "tagline": "A song split into its vocal and instrument tracks",
+ "routes": [
+ {
+ "op": "song-stems",
+ "provider": "fal",
+ "endpoint": "mureka/api/song/stem",
+ "map": {
+ "prompt": false,
+ "audio": "audio_url"
+ }
+ }
+ ],
+ "options": {
+ "promptless": true
+ },
+ "badges": [
+ "new"
+ ],
+ "pricing": {
+ "unit": "request",
+ "usd": 0.2,
+ "note": "audio-separation-3, the default"
+ }
+ },
{
"id": "lyria-3-5",
"name": "Lyria 3.5",
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 49b8d3ef..238600b5 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -190,7 +190,8 @@ function setPath(out: Record<string, unknown>, key: string, value: unknown) {
/** A number of seconds in the API's encoding (seconds or ms, number or "5s"). */
function timeValue(d: DurationField, seconds: number): number | string {
- const v = seconds * (d.multiplier ?? 1);
+ // Milliseconds are whole (Mureka's extend_at).
+ const v = (d.multiplier ?? 1) >= 1000 ? Math.round(seconds * d.multiplier!) : seconds * (d.multiplier ?? 1);
return d.type === "number" ? v : `${v}${d.suffix ?? ""}`;
}
@@ -351,6 +352,9 @@ function elementList(e: NonNullable<FieldMap["elements"]>, images: string[], vid
return { list, usedImages, usedVideos };
}
+/** params.extra key of a song tool's source when it is one of the provider's own songs (a result's meta.songId). */
+export const SONG_ID_PARAM = "songId";
+
/** Build a provider payload from canonical input using a route's {@link FieldMap}. Pure + unit-tested. */
export function buildPayload(map: FieldMap, input: GenInput): Record<string, unknown> {
const out: Record<string, unknown> = {};
@@ -527,8 +531,11 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk
// A layout draft rides in params.extra for Reuse and Edit layout; the prompt already carries it, in the model's own form.
// Options → Prompt helper (params.extra.promptHelper) is Fuobe's own: it goes out as the API's prompt expansion, below.
// Song lyrics (params.extra.lyrics) go out only where the route says (FieldMap.lyrics), in the models' own form.
- const ignore = new Set([...(map.ignore ?? []), LAYOUT_PARAM, PROMPT_HELPER_PARAM, LYRICS_PARAM, ...(asked ? [map.size!.key!] : [])]);
+ const ignore = new Set([...(map.ignore ?? []), LAYOUT_PARAM, PROMPT_HELPER_PARAM, LYRICS_PARAM, SONG_ID_PARAM, ...(asked ? [map.size!.key!] : [])]);
for (const [k, v] of Object.entries({ ...map.fixed, ...input.extra })) if (!(map.timeline && k === "timeline") && !ignore.has(k)) setPath(out, k, v);
+ // A song tool's song: one of the provider's own by its id (the fal provider sends any other song first, FieldMap.songSource).
+ const songId = input.extra?.[SONG_ID_PARAM];
+ if (map.songSource && typeof songId === "string" && songId.trim()) out[map.songSource.songId] = songId.trim();
const lyrics = map.lyrics ? lyricsOf(input.extra) : "";
if (lyrics && map.lyrics?.key) out[map.lyrics.key] = lyrics;
else if (lyrics && map.lyrics?.inPrompt && map.prompt !== false) {
@@ -1059,6 +1066,9 @@ export function extractOutputs(response: unknown, op?: Operation): ExtractedOutp
// Recraft makes a style from reference images on the fly and returns its id: keep it to reuse the style.
const styleId = str(r.style_id);
if (styleId) out = out.map((o) => ({ ...o, meta: { ...o.meta, styleId } }));
+ // Mureka's songs come back with an id its song tools take (extend, remix): kept on the song (meta.songId).
+ const songId = str(r.song_id);
+ if (songId) out = out.map((o) => (o.kind === "audio" ? { ...o, meta: { ...o.meta, songId } } : o));
// Cut-out endpoints (Bria extract-object) return the matte next to the image: it rides along on the
// cut-out (meta.mask) instead of landing in the feed as a second result.
const mask = fileOf(r.mask)?.url;
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 4356a04c..9c814d51 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -244,6 +244,8 @@ const PROMPTLESS = new Set<Operation>([
"face-mosaic",
// archive-restore: the scene's words help (period, place, light) but a run without them gets a neutral one
"restore-video",
+ // nm10-music3: extending a song takes its lyrics, its stems nothing
+ "song-extend", "song-stems",
]);
/**
@@ -501,9 +503,18 @@ export function planGeneration(
params = { ...params, extra: Object.keys(rest).length ? rest : undefined };
}
}
- if (op === "music" && model.options.lyrics?.required && isInstrumental(lyricsOf(params.extra))) {
- throw new Error(`${model.name} sings your lyrics: write them first, with [Verse] and [Chorus] on lines of their own`);
+ // A model that needs words to sing: a song from lyrics (YuE2), the lyrics of a song's new part or of its remix (Mureka).
+ const sung = lyricsOf(params.extra);
+ if (model.options.lyrics?.required && (!sung || (op === "music" && isInstrumental(sung)))) {
+ throw new Error(
+ op === "song-extend"
+ ? "Write the lyrics of the new part"
+ : op === "song-remix"
+ ? "Write the remix's lyrics: the whole song, with [Verse] and [Chorus] on lines of their own"
+ : `${model.name} sings your lyrics: write them first, with [Verse] and [Chorus] on lines of their own`,
+ );
}
+ if (op === "song-remix" && !prompt) throw new Error("Describe the remix: its genre, mood and instruments");
if (op === "music" && req.inputs?.audio && !model.options.cover) throw new Error(`${model.name} makes a new song: remove the song you added, or pick YuE2 to cover it`);
if (op === "finalize" && !params.draftId) throw new Error("Pick a draft to finish");
if (op === "dialogue" && !params.dialogue?.some((l) => l.text.trim())) throw new Error("Write at least one line");
@@ -800,6 +811,9 @@ const NEEDS: Partial<
"sdr-to-hdr": { video: true, msg: "Add the video to convert" },
"face-mosaic": { images: 1, msg: "Add the picture whose faces to pixelate" },
"restore-video": { video: true, msg: "Add the archive clip to restore" },
+ "song-extend": { audio: true, msg: "Add the song to extend" },
+ "song-remix": { audio: true, msg: "Add the song to remix" },
+ "song-stems": { audio: true, msg: "Add the song to split into stems" },
"export-video": { video: true, msg: "Add the video to export" },
ocr: { images: 1, msg: "Add the image to read" },
"still-motion": { images: 1, msg: "Add the still to move over" },
@@ -1093,6 +1107,8 @@ export function estimateCost(model: ModelDef, params: GenParams, jobs = 1, op?:
if (params.generateAudio === false && model.options.audio === true && p.note?.includes("audio-off-half")) per /= 2;
if (p.animationUsd && params.animation !== undefined && params.animation !== "") per += p.animationUsd;
if (p.perRequest) per += p.perRequest;
+ // A song tool's song goes up first unless it is one of the provider's own (Mureka's files/upload).
+ if (p.uploadUsd && typeof params.extra?.songId !== "string") per += p.uploadUsd;
if (p.generatedRefs && params.drawnRefs) per += p.generatedRefs.usd * Math.min(params.drawnRefs, p.generatedRefs.count);
return Math.round(per * jobs * 1000) / 1000;
}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 7b8b9e0f..53deb1b9 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -87,7 +87,11 @@ export type Operation =
// N7-5
| "camera-path" // image + params.cameraPath (+ inputs.video: the open engine's render along the path) → the camera following the path
// archive-restore
- | "restore-video"; // archive video (+ prompt: period, place, light; negative: what not to invent) → the same shot clean, in colour, larger
+ | "restore-video" // archive video (+ prompt: period, place, light; negative: what not to invent) → the same shot clean, in colour, larger
+ // nm10-music3: a song's cloud tools (Mureka). The song is inputs.audio, or one of Mureka's own (params.extra.songId)
+ | "song-extend" // song + lyrics for the new part (+ params.startTime: where it begins; params.extra.extend_type tail | head) → the song, longer
+ | "song-remix" // song + a style (prompt) + the whole song's lyrics → a new arrangement of it
+ | "song-stems"; // song → its vocal and instrument tracks (meta.stem), one file each
export const OPERATION_LABELS: Record<Operation, string> = {
t2i: "Text to image",
@@ -158,6 +162,9 @@ export const OPERATION_LABELS: Record<Operation, string> = {
"face-mosaic": "Pixelate faces",
"camera-path": "Fly path",
"restore-video": "Restore & colourise",
+ "song-extend": "Extend a song",
+ "song-remix": "Remix a song",
+ "song-stems": "Song stems",
};
export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
@@ -230,6 +237,9 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
"face-mosaic": "image",
"camera-path": "video",
"restore-video": "video",
+ "song-extend": "audio",
+ "song-remix": "audio",
+ "song-stems": "audio",
};
/**
@@ -511,6 +521,12 @@ export interface FieldMap {
* (Lyria 3.5). A route without it never sends params.extra.lyrics.
*/
lyrics?: { key?: string; inPrompt?: true; max?: number };
+ /**
+ * A song tool's source song (Mureka extend / remix): one of the provider's own songs by id (params.extra.songId, kept on a
+ * result as meta.songId) in `songId`, else the song file (inputs.audio) sent first to `upload` (Mureka's files/upload with
+ * its `purpose`), whose id goes in `uploadId`.
+ */
+ songSource?: { songId: string; uploadId: string; upload: { endpoint: string; purpose: string } };
/**
* An upscaler that takes a factor, not a size (Topaz, FLUX Upscale): params.resolution ("1080p", "4K",
* "Original" = 1) becomes target ÷ the clip's shorter edge (GenInput.sourceSize), kept within min–max.
@@ -739,6 +755,8 @@ export interface Pricing {
roundUp?: true;
/** The price per request when the run brings its own lyrics (params.extra.lyrics): Mureka bills a song from lyrics less than one it writes. */
withLyrics?: number;
+ /** What sending the song first costs when it isn't one of the provider's own (params.extra.songId): Mureka's files/upload, $0.01. */
+ uploadUsd?: number;
/** What an animation preset adds to a run (params.animation: Meshy rigging +$0.12). */
animationUsd?: number;
/**
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 7d1da00c..efdf19f0 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -28,7 +28,9 @@ export const SINGLE_TAKE = new Set<Operation>([
"bg-remove", "bg-remove-video", "depth-video", "concat", "color-match", "frame", "sdr-to-hdr", "export-video",
]);
-export const durationLabel = (v: number) => (v >= 1000 ? `${Math.round(v / 1000)}s` : `${v}s`);
+/** A length as it reads on a chip: seconds up to a minute ("10s"), minutes and seconds after it ("2:00", "4:30": a song). */
+export const durationLabel = (v: number) =>
+ v >= 1000 ? `${Math.round(v / 1000)}s` : v >= 60 ? `${Math.floor(v / 60)}:${String(Math.round(v % 60)).padStart(2, "0")}` : `${v}s`;
export interface SettingsShape {
/** Show the aspect-ratio control (the model offers several and the operation isn't framed by an input). */
diff --git a/src/lib/hubs.ts b/src/lib/hubs.ts
index 1b3161c3..f8c55bc0 100644
--- a/src/lib/hubs.ts
+++ b/src/lib/hubs.ts
@@ -23,6 +23,7 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {
{ id: "split", label: "Split soundtrack" },
{ id: "sfx", label: "Sound effects" },
{ id: "music", label: "Music" },
+ { id: "song", label: "Extend & remix" },
{ id: "loop", label: "Loop / extend" },
{ id: "join", label: "Join" },
{ id: "video", label: "Sound for video" },
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index eece3a23..6bc28eee 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -32,6 +32,9 @@ export type OutputActionId =
| "genjutsu"
| "voice-change"
| "loop-audio"
+ | "extend-song"
+ | "remix-song"
+ | "song-stems"
| "split-soundtrack"
| "remove-dialogue"
| "clean-voice"
@@ -156,6 +159,14 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
link("voice-change", "Change voice", `/audio/voice-change?audio=${q(o.url)}`);
link("loop-audio", "Loop / extend", `/audio/loop?audio=${q(o.url)}`);
+ // A song's cloud tools (Mureka, Audio → Extend & remix): any song, one of Mureka's own by its id. Not on an install
+ // that runs open models only.
+ if (g.op && SONG_OPS.has(g.op) && ctx.engineMode !== "open") {
+ const song = typeof o.meta?.songId === "string" ? `&song=${q(o.meta.songId)}` : "";
+ link("extend-song", "Extend song", `/audio/song?model=mureka-extend&audio=${q(o.url)}${song}`);
+ link("remix-song", "Remix", `/audio/song?model=mureka-remix&audio=${q(o.url)}${song}`);
+ link("song-stems", "Stems", `/audio/song?model=mureka-stems&audio=${q(o.url)}`);
+ }
link("split-soundtrack", "Split soundtrack", `/audio/split?audio=${q(o.url)}`);
// Not on music or sound effects (it keeps only a voice), nor on a voice it already cleaned.
if (g.op !== "music" && g.op !== "sfx" && g.feature !== CLEAN_FEATURE) link("clean-voice", "Clean up voice", `/audio/clean?audio=${q(o.url)}`);
@@ -202,6 +213,9 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
return out;
}
+/** Results that are songs: made, extended or remixed. */
+const SONG_OPS = new Set<Generation["op"]>(["music", "song-extend", "song-remix"]);
+
/** The hand-offs offered as next steps under a fresh result, best first (UX-18). */
const NEXT_STEPS: Partial<Record<OutputFile["kind"], OutputActionId[]>> = {
image: ["animate", "upscale", "edit"],
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index ba89cdee..d3d4189f 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -326,6 +326,27 @@ export const MUSIC_STUDIO: StudioConfig = {
suggestions: ["Lo-fi hip hop beat with soft piano, 80 bpm", "Epic orchestral trailer music building to a drop", "Upbeat indie pop with handclaps and a whistled hook"],
};
+/**
+ * Audio → Extend & remix (nm10-music3): a song's cloud tools on Mureka. Extend it with new lyrics, remix it in another style
+ * with its lyrics, or split it into its stems. Any song works: Mureka's own by its id, any other sent to it first. The
+ * song's length is read so an extension starts at its end (voiceFacts).
+ */
+export const SONG_TOOLS_STUDIO: StudioConfig = {
+ feature: "song-tools",
+ title: "Audio",
+ hero: "Take a song further",
+ subtitle: "Extend it with new lyrics, remix it in another style, or split it into its tracks. Runs in the cloud on Mureka.",
+ placeholder: "The remix's style: genre, mood, voice, instruments",
+ kind: "audio",
+ ops: ["song-extend", "song-remix", "song-stems"],
+ feed: { kind: "audio", features: ["song-tools"] },
+ slots: [{ key: "audio", label: "Song", accept: "audio", required: true }],
+ defaultModels: { cloud: "mureka-extend", open: "" },
+ promptOptional: true,
+ voiceFacts: true,
+ controlsTitle: "Options",
+};
+
export const FOLEY_STUDIO: StudioConfig = {
feature: "audio",
title: "Audio",
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index e2e03ec3..9545649d 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -2,6 +2,7 @@ import "server-only";
import Anthropic from "@anthropic-ai/sdk";
import type { MediaKind, Operation } from "@/lib/catalog/types";
import { writeCaption } from "@/lib/ideogram-caption";
+import { normalizeLyrics } from "@/lib/lyrics";
import { activeLocal, aiHelper, chatLocal, type JsonSpec } from "./llm";
import { engineMode, getSetting } from "./settings";
import { tenant } from "./tenant";
@@ -182,6 +183,29 @@ export async function enhanceSoulWords(words: string): Promise<string> {
return out && out.length > w.length ? out : words;
}
+/** Audio → Music's "Write the lyrics" (nm10-music3): words to sing, tagged by section as every Fuobe music model reads them. */
+const LYRICS_SYSTEM = `You write lyrics for a song generation model. Answer with the lyrics only: no title, no notes, no quotes, no code fence.
+Rules:
+- Put each section tag on a line of its own, in square brackets: [Intro], [Verse], [Pre-Chorus], [Chorus], [Bridge], [Outro]; [Instrumental] or [Solo] for a part with no singing. The words of a section go on the lines under its tag.
+- A common shape is Verse, Chorus, Verse, Chorus, Bridge, Chorus; repeat the chorus word for word.
+- Short, singable lines of 5 to 10 words that rhyme or half-rhyme. Concrete images over abstractions.
+- Only the words to be sung: no stage directions, no instruments, no chord names.
+- Keep the description's language, subject, mood and any words it quotes.`;
+
+/**
+ * Lyrics for a song described in `idea`, about as long as `seconds` of music and at most `max` characters, from whichever
+ * LLM the install allows (Claude or a local model); null when none answers. Tags are normalized (src/lib/lyrics.ts).
+ */
+export async function writeLyrics(idea: string, o: { seconds?: number; max?: number } = {}): Promise<string | null> {
+ const seconds = o.seconds && o.seconds > 0 ? Math.min(600, o.seconds) : 120;
+ const sections = seconds <= 45 ? "one verse and one chorus" : seconds <= 100 ? "a verse, a chorus, a second verse and the chorus again" : "a full song (two or three verses, the chorus after each, a bridge)";
+ const room = o.max ? ` Stay under ${Math.floor(o.max * 0.9)} characters.` : "";
+ const text = await llmText(LYRICS_SYSTEM, `Write lyrics for this song, about ${Math.round(seconds / 60 * 10) / 10} minutes long: ${sections}.${room}\n\n${idea.trim()}`);
+ const words = normalizeLyrics(text?.replace(/^```\w*\n?|```$/g, ""));
+ if (!words) return null;
+ return o.max && words.length > o.max ? normalizeLyrics(words.slice(0, words.lastIndexOf("\n", o.max))) : words;
+}
+
export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation): Promise<string> {
return (await llmText(SYSTEM, instruction(prompt, kind, op))) ?? heuristicEnhance(prompt, kind, op);
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index f8c0ffc4..d73264ef 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -1708,7 +1708,7 @@ async function submitNow(
endImage: await prep(req.inputs?.endImage),
mask: await prepMask(req.inputs?.mask),
video: await prepVideo(req.inputs?.video),
- audio: await (plan.op === "avatar" ? prepVoice : prep)(req.inputs?.audio),
+ audio: await (plan.op === "avatar" || plan.op === "song-extend" ? prepVoice : prep)(req.inputs?.audio),
audio2: await prep(req.inputs?.audio2),
voiceAudio: await prep(req.inputs?.voiceAudio),
voiceAudio2: await prep(req.inputs?.voiceAudio2),
@@ -1721,6 +1721,12 @@ async function submitNow(
};
// What the caller said about the clip's length wins; the header fills the rest.
Object.assign(input, { ...source, ...(plan.params.sourceDuration !== undefined && { sourceDuration: plan.params.sourceDuration }) });
+ // Extending a song (Mureka): the new part starts at its end (or, before its start, at 0) unless the run says where.
+ if (plan.op === "song-extend" && input.startTime === undefined) {
+ const head = input.extra?.extend_type === "head";
+ if (!head && !(input.sourceDuration && input.sourceDuration > 0)) throw new Error("The song's length couldn't be read: add it again as an MP3, WAV or M4A file");
+ input.startTime = head ? 0 : input.sourceDuration;
+ }
// A talking avatar renders as long as its voice: priced for it once its header is read (an API call that didn't say).
if (plan.op === "avatar" && plan.params.sourceDuration === undefined && input.sourceDuration && providerId !== "mock" && plan.model.engine !== "open") {
update(id, { cost_usd: estimateCost(plan.model, { ...plan.params, sourceDuration: input.sourceDuration }, 1, plan.op, plan.loras.length > 0 && !!route.loraEndpoint) });
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index 3bbca721..a640d149 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -4,6 +4,7 @@ import { loraEndpointFor, routeLoraField } from "@/lib/catalog/loras";
import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payload";
import { accountKeyError, balanceRefusal, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
import { tenant } from "../tenant";
+import { unzip } from "../unzip";
import { ProviderError, type ProviderAdapter } from "./types";
/**
@@ -20,6 +21,8 @@ import { ProviderError, type ProviderAdapter } from "./types";
*/
const QUEUE = "https://queue.fal.run";
const REST = "https://rest.fal.ai";
+/** fal.ai's synchronous runs: a song tool's song sent first through the provider's files/upload (Mureka's), which answers at once. */
+const RUN = "https://fal.run";
/** fal.ai's queue: the real one, or a stand-in on this machine in tests and `next dev` (provider-keys.ts standIn). */
export const falQueue = () => standIn("fal") ?? QUEUE;
@@ -27,9 +30,39 @@ export const falQueue = () => standIn("fal") ?? QUEUE;
/** Where a fal.ai key may go: the queue and the REST API (storage uploads), or the stand-in. */
function keyOrigin(url: string): boolean {
const o = originOf(url);
- return o === QUEUE || o === REST || (!!o && o === standIn("fal"));
+ return o === QUEUE || o === REST || o === RUN || (!!o && o === standIn("fal"));
}
+/** A synchronous fal.ai run: the real one, or the stand-in in tests and `next dev`. */
+const falRun = () => standIn("fal") ?? RUN;
+
+/**
+ * A song tool's song that isn't one of the provider's own, sent first through its files/upload (FieldMap.songSource: Mureka's,
+ * $0.01, priced as Pricing.uploadUsd): the id the tool then takes.
+ */
+async function uploadSong(upload: { endpoint: string; purpose: string }, fileUrl: string): Promise<string> {
+ const res = (await falFetch(`${falRun()}/${upload.endpoint}`, { method: "POST", body: JSON.stringify({ file_url: fileUrl, purpose: upload.purpose }) })) as { id?: unknown };
+ if (typeof res?.id !== "string" || !res.id) throw new ProviderError("The song couldn't be sent to Mureka: try again");
+ return res.id;
+}
+
+/** The stems a song tool answers with in one zip (Mureka's zip_url), one result each, named by their file (meta.stem). */
+async function stemsFromZip(zipUrl: string): Promise<{ url: string; kind: "audio"; contentType: string; meta: { stem: string } }[]> {
+ const res = await fetch(zipUrl);
+ if (!res.ok) throw new Error(`The stems couldn't be downloaded (${res.status})`);
+ const files = unzip(Buffer.from(await res.arrayBuffer())).filter((f) => AUDIO_FILE.test(f.name));
+ if (!files.length) throw new Error("The stems archive held no audio");
+ return files.map((f) => {
+ const ext = AUDIO_FILE.exec(f.name)![1].toLowerCase();
+ const contentType = AUDIO_TYPES[ext] ?? "audio/mpeg";
+ const stem = f.name.split("/").pop()!.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").trim().toLowerCase();
+ return { url: `data:${contentType};base64,${f.data.toString("base64")}`, kind: "audio" as const, contentType, meta: { stem } };
+ });
+}
+
+const AUDIO_FILE = /\.(mp3|wav|flac|m4a|ogg)$/i;
+const AUDIO_TYPES: Record<string, string> = { mp3: "audio/mpeg", wav: "audio/wav", flac: "audio/flac", m4a: "audio/mp4", ogg: "audio/ogg" };
+
function key(): string {
return cloudKey("fal");
}
@@ -115,6 +148,12 @@ export const falProvider: ProviderAdapter = {
// `transformer` per file on Wan 2.2, `weight_name`, at most the API's maximum) and switch to its LoRA endpoint.
const map = { ...route.map, loras: routeLoraField(route) };
const payload = buildPayload(map, input);
+ // A song tool's song that isn't one of the provider's own goes up first (Mureka's files/upload).
+ const song = map.songSource;
+ if (song && payload[song.songId] === undefined) {
+ if (!input.audio) throw new ProviderError("Add the song");
+ payload[song.uploadId] = await uploadSong(song.upload, input.audio);
+ }
let endpoint: string;
try {
endpoint = loraEndpointFor({ ...route, map }, input.loras);
@@ -151,6 +190,9 @@ export const falProvider: ProviderAdapter = {
if (status.error) return { state: "failed", error: status.error };
try {
const result = await falFetch(meta.responseUrl as string);
+ // A song's stems come back as one zip (Mureka): each track becomes a result of its own.
+ const zipUrl = route?.op === "song-stems" ? (result as { zip_url?: unknown })?.zip_url : undefined;
+ if (typeof zipUrl === "string" && zipUrl) return { state: "succeeded", outputs: await stemsFromZip(zipUrl) };
// Layers, text blocks, transcripts, 3D models and stems keep their structure (OutputFile.meta / text).
const outputs = extractOutputs(result, route?.op);
if (!outputs.length) return { state: "failed", error: noOutputsError(result) };
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index 1f8bfff4..2b759cef 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -332,6 +332,16 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
// The face mosaic (O11): a demo picture; no masks, so the browser has nothing to pixelate.
case "face-mosaic":
return [{ url: svgUri(demoSvg(brief || "pixelated faces", ar, 6)), kind: "image", contentType: "image/svg+xml", meta: { demo: true } }];
+ // A song's stems (Mureka): its vocals and instruments, one track each.
+ case "song-stems":
+ return (
+ [
+ ["vocals", [330, 495]],
+ ["drums", [90, 140]],
+ ["bass", [55, 82]],
+ ["other", [262, 392]],
+ ] as const
+ ).map(([stem, tones]) => ({ url: toDataUri(demoWav(3, [tones[0], tones[1]]), "audio/wav"), kind: "audio" as const, contentType: "audio/wav", meta: { stem, demo: true } }));
// The same tone, as long as the loop was asked to be (or the clips joined end to end).
case "audio-loop":
return [{ url: toDataUri(demoWav(clamp(Math.round(Number(meta.duration ?? 12)), 4, 30)), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { demo: true } }];
diff --git a/src/server/unzip.ts b/src/server/unzip.ts
new file mode 100644
index 00000000..7e09c4e4
--- /dev/null
+++ b/src/server/unzip.ts
@@ -0,0 +1,48 @@
+import "server-only";
+import { inflateRawSync } from "node:zlib";
+
+/**
+ * The files of a zip archive (stored or deflated entries), read from its central directory: what a provider answers with
+ * when its result is several files in one download (Mureka's stems). Directories and macOS resource forks are left out.
+ * Bounded: at most `maxFiles` entries and `maxBytes` of unpacked data, else it throws.
+ */
+export function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: number } = {}): { name: string; data: Buffer }[] {
+ const maxFiles = o.maxFiles ?? 64;
+ const maxBytes = o.maxBytes ?? 512 * 1024 * 1024;
+ // The end of central directory record: its signature within the last 64 KiB + 22 bytes.
+ let eocd = -1;
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
+ if (buf.readUInt32LE(i) === 0x06054b50) {
+ eocd = i;
+ break;
+ }
+ }
+ if (eocd < 0) throw new Error("Not a zip archive");
+ const count = buf.readUInt16LE(eocd + 10);
+ let at = buf.readUInt32LE(eocd + 16);
+ if (count > maxFiles) throw new Error(`The archive holds ${count} files, more than ${maxFiles}`);
+ const out: { name: string; data: Buffer }[] = [];
+ let total = 0;
+ for (let n = 0; n < count; n++) {
+ if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) throw new Error("The archive's directory is damaged");
+ const method = buf.readUInt16LE(at + 10);
+ const packed = buf.readUInt32LE(at + 20);
+ const size = buf.readUInt32LE(at + 24);
+ const nameLen = buf.readUInt16LE(at + 28);
+ const extraLen = buf.readUInt16LE(at + 30);
+ const commentLen = buf.readUInt16LE(at + 32);
+ const local = buf.readUInt32LE(at + 42);
+ const name = buf.subarray(at + 46, at + 46 + nameLen).toString("utf8");
+ at += 46 + nameLen + extraLen + commentLen;
+ if (name.endsWith("/") || name.startsWith("__MACOSX/") || name.split("/").pop()!.startsWith("._")) continue;
+ if (local + 30 > buf.length || buf.readUInt32LE(local) !== 0x04034b50) throw new Error("The archive's entries are damaged");
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
+ const raw = buf.subarray(start, start + packed);
+ total += size;
+ if (total > maxBytes) throw new Error("The archive unpacks to more than Fuobe keeps from one result");
+ const data = method === 0 ? Buffer.from(raw) : method === 8 ? inflateRawSync(raw, { maxOutputLength: maxBytes }) : null;
+ if (!data) throw new Error(`The archive uses a compression Fuobe can't read (method ${method})`);
+ out.push({ name, data });
+ }
+ return out;
+}