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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Song tools: fit an uploaded song in the browser instead of refusing it
Adarsh5a1220daf787
diff --git a/package.json b/package.jsonindex 0d2db85a..cd48b08b 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@},"dependencies": {"@anthropic-ai/sdk": "^0.135.0",+ "@breezystack/lamejs": "1.2.7","@fal-ai/client": "^1.10.1","@gltf-transform/core": "4.5.1","@gltf-transform/extensions": "4.5.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 006eb68b..dcc877a2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -11,6 +11,9 @@ importers:'@anthropic-ai/sdk':specifier: ^0.135.0version: 0.135.0([email protected])+ '@breezystack/lamejs':+ specifier: 1.2.7+ version: 1.2.7'@fal-ai/client':specifier: ^1.10.1version: 1.10.1@@ -290,6 +293,9 @@ packages:resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}engines: {node: '>=6.9.0'}+ '@breezystack/[email protected]':+ resolution: {integrity: sha512-6wc7ck65ctA75Hq7FYHTtTvGnYs6msgdxiSUICQ+A01nVOWg6rqouZB8IdyteRlfpYYiFovkf67dIeOgWIUzTA==}+'@dimforge/[email protected]':resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==}@@ -4838,6 +4844,8 @@ snapshots:'@babel/helper-string-parser': 7.29.7'@babel/helper-validator-identifier': 7.29.7+ '@breezystack/[email protected]': {}+'@dimforge/[email protected]': {}'@dotenvx/[email protected]':diff --git a/src/components/av/fit-audio.ts b/src/components/av/fit-audio.tsnew file mode 100644index 00000000..c3db4ee5--- /dev/null+++ b/src/components/av/fit-audio.ts@@ -0,0 +1,173 @@+"use client";++import { FIT_READ_MAX_SECONDS, FIT_SOURCE_MAX_BYTES, mp3Name } from "@/lib/av/fit-upload";+import { MP3_BLOCK, Mp3Stream } from "@/lib/av/mp3-encode";+import { probeBlob, probeUrl } from "@/lib/media-probe";+import type { Mp3In, Mp3Out } from "./mp3.worker";++/**+ * The browser half of the fitting step (src/lib/av/fit-upload.ts): a file's length from its header, and a sound (any file+ * the browser plays, or a video's sound) as an MP3, all of it or a part. Decoded with Web Audio at 44.1 kHz and encoded+ * with LAME in a Web Worker a block at a time (on the main thread where a worker can't start), so a phone holds the decoded+ * sound once and a block. Nothing is sent anywhere while it runs.+ */++const RATE = 44100;+/** Blocks of about 10 s go to the worker one at a time. */+const SEND = MP3_BLOCK * 12;++const unreadable = () => new Error("We couldn't read the sound in this file here. Save it as an MP3 and add it again");++function stopIfAsked(signal?: AbortSignal) {+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");+}++/** The length a media element reads from the file's header (anything the browser plays), or undefined. */+function elementSeconds(src: string, video: boolean): Promise<number | undefined> {+ return new Promise((resolve) => {+ const el = document.createElement(video ? "video" : "audio");+ const done = (s?: number) => {+ clearTimeout(timer);+ el.removeAttribute("src");+ el.load();+ resolve(s && Number.isFinite(s) && s > 0 ? s : undefined);+ };+ const timer = setTimeout(() => done(), 15_000);+ el.preload = "metadata";+ el.muted = true;+ el.onloadedmetadata = () => done(el.duration);+ el.onerror = () => done();+ el.src = src;+ });+}++/** A file's length in seconds from its header only (never the whole file): our own reader first, then the browser's. */+export async function readSeconds(src: Blob | string, video = false): Promise<number | undefined> {+ const info = await (typeof src === "string" ? probeUrl(src) : probeBlob(src)).catch(() => null);+ if (info?.duration && info.duration > 0) return info.duration;+ if (typeof document === "undefined") return undefined;+ if (typeof src === "string") return elementSeconds(src, video);+ const url = URL.createObjectURL(src);+ try {+ return await elementSeconds(url, video || src.type.startsWith("video/"));+ } finally {+ URL.revokeObjectURL(url);+ }+}++async function decode(data: ArrayBuffer): Promise<AudioBuffer> {+ const Ctx: typeof OfflineAudioContext | undefined =+ typeof OfflineAudioContext !== "undefined" ? OfflineAudioContext : (globalThis as { webkitOfflineAudioContext?: typeof OfflineAudioContext }).webkitOfflineAudioContext;+ if (!Ctx) throw unreadable();+ const ctx = new Ctx(2, 1, RATE);+ try {+ // The callback form too: older Safari returns no promise.+ return await new Promise<AudioBuffer>((resolve, reject) => {+ const p = ctx.decodeAudioData(data, resolve, reject) as Promise<AudioBuffer> | undefined;+ p?.then(resolve, reject);+ });+ } catch {+ throw unreadable();+ }+}++/** The encoder: a worker when one starts, else the main thread (yielding between blocks). */+interface Encoder {+ push(block: Float32Array[]): Promise<void>;+ end(): Promise<Uint8Array[]>;+ close(): void;+}++async function workerEncoder(channels: number, kbps: number): Promise<Encoder | null> {+ if (typeof Worker === "undefined") return null;+ let w: Worker;+ try {+ w = new Worker(new URL("./mp3.worker.ts", import.meta.url), { type: "module" });+ } catch {+ return null;+ }+ let waiting: { resolve: (m: Mp3Out) => void; reject: (e: Error) => void } | null = null;+ let broken: Error | null = null;+ const next = () =>+ new Promise<Mp3Out>((resolve, reject) => {+ if (broken) return reject(broken);+ waiting = { resolve, reject };+ });+ w.onmessage = (e: MessageEvent<Mp3Out>) => {+ const m = e.data;+ const at = waiting;+ waiting = null;+ if (m.type === "error") at?.reject(new Error("We couldn't convert the sound here. Save it as an MP3 and add it again"));+ else at?.resolve(m);+ };+ w.onerror = () => {+ broken = new Error("We couldn't convert the sound here. Save it as an MP3 and add it again");+ waiting?.reject(broken);+ waiting = null;+ };+ try {+ // Loaded (in 10 s at most): else the main thread does it.+ const ready = await Promise.race([next(), new Promise<null>((r) => setTimeout(() => r(null), 10_000))]);+ if (ready?.type !== "ready") throw new Error("worker");+ } catch {+ w.terminate();+ return null;+ }+ const send = (m: Mp3In, transfer: Transferable[] = []) => w.postMessage(m, transfer);+ send({ type: "start", channels, sampleRate: RATE, kbps });+ return {+ async push(block) {+ const answer = next();+ send({ type: "block", block }, block.map((b) => b.buffer as ArrayBuffer));+ await answer;+ },+ async end() {+ const answer = next();+ send({ type: "end" });+ const m = await answer;+ if (m.type !== "done") throw unreadable();+ return m.parts;+ },+ close: () => w.terminate(),+ };+}++function mainEncoder(channels: number, kbps: number): Encoder {+ const s = new Mp3Stream(channels, RATE, kbps);+ return {+ async push(block) {+ s.push(block);+ await new Promise((r) => setTimeout(r, 0));+ },+ end: async () => s.end(),+ close: () => {},+ };+}++/**+ * The sound as an MP3 at `kbps`, named after the original: all of it, or `from` to `to` seconds. Throws in plain words+ * when the browser can't read the file. The caller has checked the caps (planAudioFit), checked again here.+ */+export async function toMp3(src: Blob, opts: { kbps: number; name?: string; from?: number; to?: number; signal?: AbortSignal }): Promise<File> {+ if (src.size > FIT_SOURCE_MAX_BYTES) throw new Error(`The largest file this takes is ${Math.round(FIT_SOURCE_MAX_BYTES / 1024 / 1024)} MB. Use a shorter clip`);+ const audio = await decode(await src.arrayBuffer());+ stopIfAsked(opts.signal);+ if (audio.duration > FIT_READ_MAX_SECONDS + 1) throw new Error("This file is too long to cut here: use a shorter clip");+ const a = Math.max(0, Math.round((opts.from ?? 0) * audio.sampleRate));+ const b = Math.min(audio.length, opts.to ? Math.round(opts.to * audio.sampleRate) : audio.length);+ if (b <= a) throw unreadable();+ const n = Math.min(2, audio.numberOfChannels);+ const enc = (await workerEncoder(n, opts.kbps)) ?? mainEncoder(n, opts.kbps);+ try {+ for (let at = a; at < b; at += SEND) {+ stopIfAsked(opts.signal);+ const end = Math.min(b, at + SEND);+ // A copy of this block only: the worker takes it over.+ await enc.push(Array.from({ length: n }, (_, c) => audio.getChannelData(c).slice(at, end)));+ }+ const parts = await enc.end();+ return new File(parts as BlobPart[], mp3Name(opts.name), { type: "audio/mpeg" });+ } finally {+ enc.close();+ }+}diff --git a/src/components/av/fit-upload.tsx b/src/components/av/fit-upload.tsxnew file mode 100644index 00000000..c0a92e99--- /dev/null+++ b/src/components/av/fit-upload.tsx@@ -0,0 +1,302 @@+"use client";++import { Loader2, Scissors, X } 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, convertedLine, fitSourceKind, FIT_SOURCE_MAX_BYTES, mp3Kbps, planAudioFit, type AudioFitRule, type FitPlan } from "@/lib/av/fit-upload";+import { songFormat } from "@/lib/lyrics";+import { postFile } from "@/lib/upload";+import { cn } from "@/lib/utils";+import { readSeconds, toMp3 } from "./fit-audio";++/**+ * The fitting step on a sound slot (src/lib/av/fit-upload.ts): a file the tool can't take as it is becomes one it takes, in+ * this browser, instead of being refused.+ * - A file picked, dropped or pasted: its length read from its header, then kept, converted to an MP3 before it is+ * uploaded, offered as a part (the person picks it), or refused in one line (too big or too long to read here; nothing+ * is uploaded).+ * - A file already stored (a library pick, a Reuse): the same, fetched from here and uploaded again once fitted.+ * While it converts, the slot shows as uploading, so Generate waits. `skip` leaves a file alone (Mureka's own song, sent by+ * its id).+ */++type Offer = { source: Blob | string; name?: string; seconds: number; max: number; line: string; stored?: SlotValue };++/** A part a hair shorter than the tool's limit, so the file's own header never reads a frame over it. */+const MARGIN = 0.5;++export function useFitUpload({+ rule,+ value,+ skip = false,+ seconds,+ setValue,+ upload,+}: {+ /** The tool's rule; null turns the step off. Keep it stable between renders (useMemo). */+ rule: AudioFitRule | null;+ value: SlotValue | null | undefined;+ skip?: boolean;+ /** The stored file'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 guest = useIsGuest();+ const askFirst = useAskBeforeUpload();+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<{ line: string; at: string | null } | null>(null);+ const [offer, setOffer] = useState<Offer | null>(null);+ const [start, setStart] = useState(0);+ const [made, setMade] = useState<Set<string>>(() => new Set());+ const failed = useRef(new Set<string>());+ const latest = useRef(value);+ const cb = useRef({ setValue, upload, rule });+ useEffect(() => {+ latest.current = value;+ cb.current = { setValue, upload, rule };+ });+ const ctl = useRef<AbortController | null>(null);+ useEffect(() => () => ctl.current?.abort(), []);+ // A file this step handed to the slot's upload, by name: once it lands (stored, or kept for a guest) it is marked.+ const expect = useRef<string | null>(null);+ const landed = value && !value.uploading ? (value.held ?? value.ref) || undefined : undefined;+ useEffect(() => {+ if (!expect.current || value?.uploading) return;+ if (value?.name === expect.current && landed) setMade((m) => new Set(m).add(landed));+ expect.current = null;+ }, [value, landed]);++ /** Put a stand-in in the slot (uploading, so Generate waits) and know it at once. */+ const hold = useCallback((v: SlotValue) => {+ cb.current.setValue(v);+ latest.current = v;+ }, []);+ // Stored files offered a part already: not offered again (a Cancel stands).+ const offered = useRef(new Set<string>());++ /** Convert while the slot holds `token` (the person may remove or replace the file meanwhile), then hand the MP3 on. */+ const convert = useCallback(+ async (token: string, source: () => Promise<Blob>, opts: { kbps: number; name?: string; from?: number; to?: number }, done: (f: File) => Promise<void> | void, onFail: (why: string) => void) => {+ ctl.current?.abort();+ const c = new AbortController();+ ctl.current = c;+ setBusy(true);+ setError(null);+ const still = () => !c.signal.aborted && latest.current?.id === token;+ try {+ const mp3 = await toMp3(await source(), { ...opts, signal: c.signal });+ if (still()) await done(mp3);+ } catch (e) {+ if (!still() || (e as Error).name === "AbortError") return;+ onFail((e as Error).message || "We couldn't convert the sound here. Save it as an MP3 and add it again");+ } finally {+ if (ctl.current === c) {+ ctl.current = null;+ setBusy(false);+ }+ }+ },+ [],+ );++ /** A new file: converted (all of it, or `from`-`to`) and handed to the slot's upload. */+ const convertFile = useCallback(+ (f: Blob, name: string | undefined, opts: { kbps: number; from?: number; to?: number }) => {+ const token = nanoid(8);+ hold({ id: token, ref: "", preview: "", kind: "audio", name, uploading: true });+ void convert(+ token,+ async () => f,+ { ...opts, name },+ (mp3) => {+ expect.current = mp3.name;+ cb.current.upload(mp3);+ },+ (why) => {+ cb.current.setValue(null);+ setError({ line: why, at: null });+ },+ );+ },+ [convert, hold],+ );++ /** A stored file: fetched, converted, uploaded as a new file and put in the slot. */+ const convertStored = useCallback(+ (v: SlotValue, opts: { kbps: number; from?: number; to?: number }) => {+ const token = nanoid(8);+ hold({ ...v, id: token, uploading: true });+ void convert(+ token,+ async () => {+ const res = await fetch(v.ref);+ if (!res.ok) throw new Error("We couldn't open the file to convert it. Add it again");+ return res.blob();+ },+ { ...opts, name: v.name ?? v.ref.split("/").pop() },+ async (mp3) => {+ const asset = await postFile(mp3);+ if (latest.current?.id !== token) return;+ cb.current.setValue({ ref: asset.url, preview: asset.url, kind: asset.kind ?? "audio", name: mp3.name, source: "upload" });+ setMade((m) => new Set(m).add(asset.url));+ },+ (why) => {+ failed.current.add(v.ref);+ cb.current.setValue({ ...v, uploading: false });+ setError({ line: why, at: v.ref });+ },+ );+ },+ [convert, hold],+ );++ /** Act on a plan: keep (the caller's own path), convert, offer a part, or say why not. */+ const follow = useCallback(+ (plan: FitPlan, source: Blob | string, name: string | undefined, keep: () => void, stored?: SlotValue) => {+ const r = cb.current.rule;+ if (!r || plan.kind === "keep") return keep();+ if (plan.kind === "refuse") {+ if (stored) failed.current.add(stored.ref);+ else cb.current.setValue(null);+ return setError({ line: plan.line, at: stored?.ref ?? null });+ }+ if (plan.kind === "trim") {+ if (stored) offered.current.add(stored.ref);+ else cb.current.setValue(null);+ setStart(0);+ return setOffer({ source, name, seconds: plan.seconds, max: plan.max, line: plan.line, stored });+ }+ if (stored) convertStored(stored, { kbps: plan.kbps });+ else convertFile(source as Blob, name, { kbps: plan.kbps });+ },+ [convertFile, convertStored],+ );++ /** True when this step takes the file (any sound or video file while a rule is on). */+ const wants = useCallback((f: File) => !!rule && !!fitSourceKind(f), [rule]);++ /** A file picked, dropped or pasted: its length read from its header first (nothing else is read), then fitted. */+ const take = useCallback(+ (f: File) => {+ const r = cb.current.rule;+ if (!r) return cb.current.upload(f);+ setOffer(null);+ setError(null);+ const facts = { format: songFormat(f.type, f.name), bytes: f.size, video: fitSourceKind(f) === "video" };+ const first = planAudioFit(r, facts);+ // Taken as it is, by a tool with no length rule; or too big to read at all: no need for its length.+ if (first.kind === "keep" && !r.maxSeconds) return cb.current.upload(f);+ if (first.kind === "refuse" && f.size > FIT_SOURCE_MAX_BYTES) return follow(first, f, f.name, () => {});+ const token = nanoid(8);+ hold({ id: token, ref: "", preview: "", kind: "audio", name: f.name, uploading: true });+ void readSeconds(f, facts.video).then((seconds) => {+ if (latest.current?.id !== token) return;+ follow(planAudioFit(r, { ...facts, seconds }), f, f.name, () => cb.current.upload(f));+ });+ },+ [follow, hold],+ );++ // A file already stored that the tool can't take as it is (a library pick, a Reuse): fitted once, at once.+ const ref = rule && value && !value.uploading && !value.held && value.ref.startsWith("/api/files/") ? value.ref : undefined;+ useEffect(() => {+ if (!rule || !ref || skip || guest || failed.current.has(ref) || offered.current.has(ref) || made.has(ref)) return;+ const v = latest.current;+ if (!v) return;+ let gone = false;+ void (async () => {+ const format = songFormat(undefined, ref) ?? songFormat(undefined, v.name);+ // Its size from the answer for its first byte, when the tool has a size rule.+ let bytes: number | undefined;+ if (rule.maxBytes) {+ const r = await fetch(ref, { headers: { Range: "bytes=0-0" } }).catch(() => null);+ void r?.body?.cancel();+ bytes = Number(/\/(\d+)$/.exec(r?.headers.get("content-range") ?? "")?.[1] ?? r?.headers.get("content-length")) || undefined;+ }+ const facts = { format, bytes };+ let plan = planAudioFit(rule, facts);+ if (plan.kind !== "keep" || rule.maxSeconds) plan = planAudioFit(rule, { ...facts, seconds: seconds ?? (await readSeconds(ref)) });+ if (gone || latest.current?.ref !== ref || latest.current.uploading) return;+ follow(plan, ref, v.name, () => {}, latest.current);+ })();+ return () => {+ gone = true;+ };+ }, [rule, ref, skip, guest, made, seconds, follow]);++ // An offer belongs to the file it was made for: another file in the slot (or a stored one taken out) ends it.+ const offerGone = !!offer && (offer.stored ? value?.ref !== offer.stored.ref : !!value && !value.uploading);+ const [seen, setSeen] = useState(value);+ if (seen !== value) {+ setSeen(value);+ if (offerGone) setOffer(null);+ }++ const usePart = useCallback(() => {+ const r = cb.current.rule;+ if (!offer || !r || askFirst()) return;+ const from = Math.min(start, Math.max(0, offer.seconds - offer.max));+ const opts = { kbps: mp3Kbps(offer.max, r.outMaxBytes) ?? 96, from, to: from + offer.max - MARGIN };+ setOffer(null);+ if (offer.stored) convertStored(offer.stored, opts);+ else convertFile(offer.source as Blob, offer.name, opts);+ }, [offer, start, askFirst, convertFile, convertStored]);++ // A file refused before it landed is said while the slot stays empty; a stored one's while it is in the slot.+ const shownError = error && (error.at === null ? !value : error.at === landed) ? error.line : null;+ const converted = !!landed && made.has(landed);+ const line = !rule ? null : busy ? `Converting to MP3 for ${rule.for}…` : (shownError ?? (converted ? convertedLine(rule) : null));+ return {+ on: !!rule,+ wants,+ take,+ busy,+ line,+ failedNow: !!shownError && !busy,+ offer: offer && !offerGone ? { ...offer, start, setStart, use: usePart, cancel: () => setOffer(null) } : null,+ };+}++/** The slot's line: converting, converted, why it couldn't; and the part to use when the file is longer than the tool takes. */+export function FitUploadNote({ fit, className }: { fit: ReturnType<typeof useFitUpload>; className?: string }) {+ const o = fit.offer;+ if (!fit.line && !o) return null;+ const last = o ? Math.max(0, Math.floor(o.seconds - o.max)) : 0;+ 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 && (+ <div className="space-y-1.5 rounded-xl border bg-muted/40 p-2.5">+ <p className="text-foreground">{o.line}</p>+ {last > 0 && (+ <label className="flex items-center gap-2">+ <span className="w-24 shrink-0 tabular-nums">+ {clock(Math.min(o.start, last))}–{clock(Math.min(o.start, last) + o.max)}+ </span>+ <input type="range" min={0} max={last} step={1} value={Math.min(o.start, last)} onChange={(e) => o.setStart(Number(e.target.value))} aria-label="Where the part starts" className="h-9 min-w-0 flex-1 accent-primary" />+ </label>+ )}+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={o.use} className="inline-flex min-h-9 items-center gap-1.5 rounded-full bg-foreground px-3.5 font-medium text-background">+ <Scissors className="size-3.5" />+ Use this part+ </button>+ <button type="button" onClick={o.cancel} className="inline-flex min-h-9 items-center gap-1.5 rounded-full border px-3.5 font-medium text-foreground hover:bg-accent">+ <X className="size-3.5" />+ Cancel+ </button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/src/components/av/mp3.worker.ts b/src/components/av/mp3.worker.tsnew file mode 100644index 00000000..0ec5a251--- /dev/null+++ b/src/components/av/mp3.worker.ts@@ -0,0 +1,31 @@+/**+ * MP3 encoding off the main thread (src/components/av/fit-audio.ts). The page sends "start", then one block of channels at a+ * time (each answered with "next", so only a block is in flight), then "end" for the file. Nothing leaves the browser.+ */+import { Mp3Stream } from "@/lib/av/mp3-encode";++export type Mp3In = { type: "start"; channels: number; sampleRate: number; kbps: number } | { type: "block"; block: Float32Array[] } | { type: "end" };+export type Mp3Out = { type: "ready" } | { type: "next" } | { type: "done"; parts: Uint8Array[] } | { type: "error"; message: string };++const post = (m: Mp3Out, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(m, transfer);+let stream: Mp3Stream | null = null;++self.onmessage = (e: MessageEvent<Mp3In>) => {+ try {+ const m = e.data;+ if (m.type === "start") stream = new Mp3Stream(m.channels, m.sampleRate, m.kbps);+ else if (m.type === "block") {+ stream!.push(m.block);+ post({ type: "next" });+ } else {+ const parts = stream!.end();+ stream = null;+ post({ type: "done", parts }, parts.map((p) => p.buffer as ArrayBuffer));+ }+ } catch (err) {+ post({ type: "error", message: (err as Error)?.message ?? String(err) });+ }+};++// Loaded and listening: the page starts sending.+post({ type: "ready" });diff --git a/src/components/studio/attachments.ts b/src/components/studio/attachments.tsindex d5364cb6..e8cd173b 100644--- a/src/components/studio/attachments.ts+++ b/src/components/studio/attachments.ts@@ -62,9 +62,10 @@ const MAX_AT_ONCE = 8;* model that takes none) is never uploaded: the person is told why instead. Someone whose upload* would be refused (a guest, an account with neither its own GPU nor its own key) gets that card* at once, before any preview is placed. With `hold` (a guest, hosted runs on), a file is kept in this browser- * instead of uploaded, until the guest signs up (src/lib/held-files.ts).+ * instead of uploaded, until the guest signs up (src/lib/held-files.ts). With `route`, a paste or drop the caller takes itself+ * (a song tool's song, fitted first: src/components/av/fit-upload.tsx) goes there instead.*/-export function useAttach(slots: InputSlot[], refMax: number, { hold = false }: { hold?: boolean } = {}) {+export function useAttach(slots: InputSlot[], refMax: number, { hold = false, route }: { hold?: boolean; route?: (f: File) => boolean } = {}) {const { config, draft, setDraft } = useStudio();// The latest draft, to check for room before an upload starts (callbacks outlive renders).const latest = useRef(draft);@@ -143,6 +144,8 @@ export function useAttach(slots: InputSlot[], refMax: number, { hold = false }:(files: File[]) => {// A paste, a drop on the page or the "+" menu: one card for the lot, and no toast about kinds or room on top.if (!hold && askFirst()) return;+ if (route) files = files.filter((f) => !route(f));+ if (!files.length) return;const frames = latest.current.frames;// Frames mode: each still becomes the next frame, up to ten.const usable = files.filter((f) => (frames ? kindOfFile(f) === "image" : kinds.has(kindOfFile(f))));@@ -160,7 +163,7 @@ export function useAttach(slots: InputSlot[], refMax: number, { hold = false }:if (rejected.length) noRoom();for (const i of placed) start(batch[i], place);},- [askFirst, hold, kinds, start, place, noRoom, slots, config.multiRef, refMax],+ [askFirst, hold, route, kinds, start, place, noRoom, slots, config.multiRef, refMax],);/** A slot tile: replace its value (an upload it held is cancelled by the reaper). A drawing belongs to the image it was made on. */diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 9db6a8cc..12438098 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -15,6 +15,9 @@ import { useToday } from "@/hooks/use-today";import { estimateCost, imageLimit, layoutCanvas, planGeneration, routesFor, type Plan } from "@/lib/catalog/plan";import type { Engine, InputSlot, MediaKind, ModelDef, Operation, Preset, PresetRoute, VideoFormat } from "@/lib/catalog/types";import { LYRICS_PARAM, SONG_ID_PARAM, songFormat, songToolProblem, withSongId } from "@/lib/lyrics";+import { murekaSongRule, SONG_ACCEPT, SONG_FIT_OPS } from "@/lib/av/song-fit";+import { fitSourceKind } from "@/lib/av/fit-upload";+import { FitUploadNote, useFitUpload } from "@/components/av/fit-upload";import { dualEngine, onEngine } from "@/lib/catalog/engines";import { locksByDefault } from "@/lib/catalog/palettes";import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";@@ -625,7 +628,10 @@ export function Composer({ docked }: { docked: boolean }) {// Hosted runs on, a guest's files are kept in this browser until sign-up (HoldFilesForGuests), and its whole draft and// the run it pressed come back after it (useGuestDraft).const guestHold = useContext(HoldFilesCtx);- const attach = useAttach(slots, refMax, { hold: guestHold });+ // A song tool's song dropped or pasted on the page goes to its slot's converter first (useSongFit, below).+ const songRoute = useRef<((f: File) => boolean) | null>(null);+ const routeSong = useCallback((f: File) => songRoute.current?.(f) ?? false, []);+ const attach = useAttach(slots, refMax, { hold: guestHold, route: routeSong });const guestDraft = useGuestDraft({ hold: guestHold, viewer: status?.viewer?.kind, draft: typed, setDraft });// The price changed since its guest pressed Run: said once, and Run waits for a click.const [priceNote, setPriceNote] = useState<string | null>(null);@@ -801,6 +807,22 @@ export function Composer({ docked }: { docked: boolean }) {// or M4A), from its name and header, as the server does. One of Mureka's own goes by its id (withSongId), never as a file.const songRef = config.voiceFacts && (op === "song-stems" || op === "song-remix" || op === "song-extend") ? draft.slots.audio?.ref : undefined;const songById = model?.family === "mureka" && !!draft.song && !!songRef && draft.song.url === songRef;+ // One Mureka can't take as it is (another format, over 10 MB, a video's sound, longer than Remix takes) is fitted in this+ // 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]);+ const songFit = useFitUpload({+ rule: songRule,+ value: draft.slots.audio,+ skip: songById,+ seconds: voice?.duration,+ setValue: (v) => attach.setSlotValue("audio", v),+ upload: (f) => attach.uploadToSlot("audio", f, "audio"),+ });+ useEffect(() => {+ songRoute.current = (f) => songFit.wants(f) && (songFit.take(f), true);+ });const songProblem = songRef ? songToolProblem(op!, { format: songFormat(undefined, songRef), seconds: voice?.duration }, songById) : null;if (songProblem && !planError) planError = songProblem;if (signed.blocker) planError = signed.blocker;@@ -1666,7 +1688,8 @@ export function Composer({ docked }: { docked: boolean }) {captionvalue={draft.slots[s.key] ?? null}onChange={(v) => attach.setSlotValue(s.key, v)}- onFile={(f) => attach.uploadToSlot(s.key, f, s.accept)}+ onFile={(f) => (s.key === "audio" && songFit.wants(f) ? songFit.take(f) : attach.uploadToSlot(s.key, f, s.accept))}+ {...(s.key === "audio" && songFit.on && { accept: SONG_ACCEPT, takes: (f: File) => !!fitSourceKind(f) })}/>),)}@@ -1718,6 +1741,7 @@ export function Composer({ docked }: { docked: boolean }) {{showAttachments && !collapsed && !framesOn && refMode && (refsOpen || refClips.length > 0 || refAudios.length > 0) && (<ReferenceOrder images={refImages} clips={refClips.length} audios={refAudios.length} problem={refProblem} />)}+ {showAttachments && !collapsed && !framesOn && <FitUploadNote fit={songFit} 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.tsxindex 8e14fe5d..6cd13813 100644--- a/src/components/studio/media-slot.tsx+++ b/src/components/studio/media-slot.tsx@@ -287,6 +287,8 @@ export function MediaSlot({local,slotKey,caption,+ accept,+ takes,}: {label: string;kind: MediaKind;@@ -302,10 +304,14 @@ export function MediaSlot({slotKey?: string;/** Filled, keep the slot's role on the thumbnail ("Target", "Face"), so two photos can be told apart. */caption?: boolean;+ /** The file picker's types, when the tile takes more than its kind (a song tool's slot takes a video's sound). */+ accept?: string;+ /** The files the tile takes, when more than its kind (with `onFile`, which turns them into its kind). */+ takes?: (f: File) => boolean;}) {const handleFile = (f: File) => {// A tile takes its own kind only (a clip dropped on the Image tile would land as a video there).- if (kindOfFile(f) !== kind) return void toast(wrongKindMessage(kind));+ if (!(takes ? takes(f) : kindOfFile(f) === kind)) return void toast(wrongKindMessage(kind));if (onFile) onFile(f);else void fileToSlot(f, onChange, kind);};@@ -375,7 +381,7 @@ export function MediaSlot({<inputref={input}type="file"- accept={ACCEPT[kind]}+ accept={accept ?? ACCEPT[kind]}hiddenonChange={(e) => {const f = e.target.files?.[0];diff --git a/src/lib/av/fit-upload.ts b/src/lib/av/fit-upload.tsnew file mode 100644index 00000000..564595e6--- /dev/null+++ b/src/lib/av/fit-upload.ts@@ -0,0 +1,117 @@+/**+ * Fit an upload to a tool instead of refusing it: one shared step for any tool whose provider takes only some sound files+ * (a format, a size, a length). It decides here, from what a file's header says (its length) before anything is read+ * into memory; the browser then converts or cuts it (src/components/av/fit-audio.ts) and the slot shows one short line+ * (src/components/av/fit-upload.tsx). Nothing is converted on the server, and an original too big to read is never+ * uploaded to be converted there.+ *+ * - A file the tool takes as it is: kept.+ * - Another format, too big, or a video's sound: converted to an MP3, at the best bit rate that keeps it under the+ * tool's size (never under 96 kbit/s; 128 and up when the length allows).+ * - Longer than the tool takes, or than fits its size at 96 kbit/s: a part of it is offered (the first allowed stretch+ * by default, or the part the person picks). Never a silent cut, never a quality crush.+ * - Past the caps a phone can read safely (200 MB, 15 minutes): said in one line, and the file isn't uploaded.+ *+ * Mureka's Extend, Remix and Stems are its first users (src/lib/av/song-fit.ts).+ */++/** What a tool takes, for the fitting step. */+export interface AudioFitRule {+ /** Who the file is for, in the line said after a conversion: "Converted to MP3 for Mureka". */+ for: string;+ /** The tool's name in the lines: "Extend". */+ tool: string;+ /** The formats it takes as they are ("mp3", "m4a"), as songFormat (src/lib/lyrics.ts) names them. */+ formats: readonly string[];+ /** The largest file it takes as it is, in bytes (none: any size). */+ maxBytes?: number;+ /** The length it takes, in seconds (a shorter file is left to the tool's own check: it can't be made longer). */+ minSeconds?: number;+ maxSeconds?: number;+ /** The largest file a conversion may make. */+ outMaxBytes: number;+}++/** The largest file read in the browser to fit it: the app's own upload limit (MAX_MB in media-slot.tsx, /api/uploads). */+export const FIT_SOURCE_MAX_BYTES = 200 * 1024 * 1024;+/** The longest file read to fit it: 15 minutes decodes to about 320 MB of sound, as much as a phone should hold. */+export const FIT_READ_MAX_SECONDS = 15 * 60;+/** MP3 bit rates (kbit/s), best first, down to the floor: under 96 a song sounds worse than the tool deserves. */+export const FIT_KBPS = [320, 256, 192, 160, 128, 112, 96] as const;+export const FIT_MIN_KBPS = 96;++/** Bytes kept free in a converted file for frame padding and tags: 2 % and 16 KB. */+const room = (maxBytes: number) => maxBytes * 0.98 - 16_000;++/** The best bit rate that keeps `seconds` under `maxBytes`, or null when even 96 kbit/s is too big. */+export function mp3Kbps(seconds: number, maxBytes: number): number | null {+ if (!(seconds > 0)) return FIT_KBPS[0];+ return FIT_KBPS.find((k) => (seconds * k * 1000) / 8 <= room(maxBytes)) ?? null;+}++/** The longest sound that fits `maxBytes` at `kbps`, in whole seconds. */+export function secondsAt(kbps: number, maxBytes: number): number {+ return Math.floor(room(maxBytes) / ((kbps * 1000) / 8));+}++/** A file a sound can be taken from: any sound file, or a video file (its sound is used). */+export function fitSourceKind(file: { type?: string; name?: string }): "audio" | "video" | null {+ const type = (file.type ?? "").toLowerCase();+ if (type.startsWith("audio/")) return "audio";+ if (type.startsWith("video/")) return "video";+ const ext = /\.([a-z0-9]{2,5})$/i.exec(file.name ?? "")?.[1]?.toLowerCase();+ if (ext && ["mp3", "m4a", "aac", "wav", "wave", "flac", "ogg", "oga", "opus", "weba", "aif", "aiff", "caf", "wma", "amr"].includes(ext)) return "audio";+ if (ext && ["mp4", "m4v", "mov", "webm", "mkv", "avi", "3gp"].includes(ext)) return "video";+ return null;+}++/** "75" -> "1:15". */+export function clock(seconds: number): string {+ const s = Math.max(0, Math.round(seconds));+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;+}++/** "Take 2.wav" -> "Take 2.mp3". */+export function mp3Name(name: string | undefined): string {+ const base = (name ?? "").split(/[\\/]/).pop()?.replace(/\.[a-z0-9]{1,5}$/i, "").trim();+ return `${base || "Sound"}.mp3`;+}++export type FitPlan =+ | { kind: "keep" }+ /** Convert all of it at `kbps`. */+ | { kind: "convert"; kbps: number }+ /** Offer a part of at most `max` seconds of its `seconds` (the person picks where it starts; 0 by default). */+ | { kind: "trim"; seconds: number; max: number; line: string }+ | { kind: "refuse"; line: string };++/** The line said after a conversion. */+export const convertedLine = (rule: AudioFitRule) => `Converted to MP3 for ${rule.for}`;++/** The longest part a conversion can keep for this tool: its own length rule, and its size at 96 kbit/s. */+export function fitMaxSeconds(rule: AudioFitRule): number {+ return Math.min(rule.maxSeconds ?? Infinity, secondsAt(FIT_MIN_KBPS, rule.outMaxBytes));+}++/**+ * What to do with a file for this tool, from what is known before it is read: its format, size and length, and whether+ * it is a video. A length not known yet (`seconds` undefined) is read before a conversion: a file that needs one and whose+ * length can't be read is refused in words.+ */+export function planAudioFit(rule: AudioFitRule, file: { format?: string; bytes?: number; seconds?: number; video?: boolean }): FitPlan {+ const tooLong = !!rule.maxSeconds && !!file.seconds && file.seconds > rule.maxSeconds;+ const needs = !!file.video || (!!file.format && !rule.formats.includes(file.format)) || (!!rule.maxBytes && !!file.bytes && file.bytes > rule.maxBytes);+ if (!needs && !tooLong) return { kind: "keep" };+ if (file.bytes && file.bytes > FIT_SOURCE_MAX_BYTES) {+ return { kind: "refuse", line: `The largest file this takes is ${Math.round(FIT_SOURCE_MAX_BYTES / 1024 / 1024)} MB. Use a shorter clip` };+ }+ if (!file.seconds) return { kind: "refuse", line: `We couldn't read this file's length here. Save it as an MP3 and add it again` };+ const max = fitMaxSeconds(rule);+ if (file.seconds > max) {+ if (file.seconds > FIT_READ_MAX_SECONDS) {+ return { kind: "refuse", line: `This file is ${clock(file.seconds)}. A part can be cut here from a file of up to ${clock(FIT_READ_MAX_SECONDS)}: use a shorter clip` };+ }+ return { kind: "trim", seconds: file.seconds, max, line: `This one is ${clock(file.seconds)}. ${rule.tool} takes up to ${clock(max)}: pick the part to use` };+ }+ return { kind: "convert", kbps: mp3Kbps(file.seconds, rule.outMaxBytes) ?? FIT_MIN_KBPS };+}diff --git a/src/lib/av/mp3-encode.ts b/src/lib/av/mp3-encode.tsnew file mode 100644index 00000000..a0d40900--- /dev/null+++ b/src/lib/av/mp3-encode.ts@@ -0,0 +1,53 @@+import { Mp3Encoder } from "@breezystack/lamejs";++/**+ * PCM to MP3 with LAME (lamejs, pure JavaScript), a block at a time: runs in a browser Web Worker+ * (src/components/av/mp3.worker.ts), on the main thread where a worker can't start, and in tests. One or two channels of+ * float samples (-1 to 1), constant bit rate.+ */++function toInt16(src: Float32Array): Int16Array {+ const out = new Int16Array(src.length);+ for (let i = 0; i < src.length; i++) {+ const s = Math.max(-1, Math.min(1, src[i]));+ out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;+ }+ return out;+}++/** An MP3 made a block at a time: `push` each block of channels (the same length), then `end` for the file's parts. */+export class Mp3Stream {+ private enc: Mp3Encoder;+ private parts: Uint8Array[] = [];+ constructor(+ private channels: number,+ sampleRate: number,+ kbps: number,+ ) {+ if (channels < 1 || channels > 2) throw new Error("No sound to convert");+ this.enc = new Mp3Encoder(channels, sampleRate, kbps);+ }+ push(block: Float32Array[]) {+ const left = toInt16(block[0]);+ const out = this.channels === 2 ? this.enc.encodeBuffer(left, toInt16(block[1])) : this.enc.encodeBuffer(left);+ if (out.length) this.parts.push(new Uint8Array(out));+ }+ end(): Uint8Array[] {+ const out = this.enc.flush();+ if (out.length) this.parts.push(new Uint8Array(out));+ return this.parts;+ }+}++/** Samples per block: 32 MP3 frames (MPEG-1 Layer III frames hold 1152). */+export const MP3_BLOCK = 1152 * 32;++/** The whole MP3 of `channels` at once (tests; the browser streams blocks instead). */+export async function encodeMp3(channels: Float32Array[], sampleRate: number, kbps: number, breathe?: () => void | Promise<void>): Promise<Uint8Array[]> {+ const s = new Mp3Stream(Math.min(2, channels.length), sampleRate, kbps);+ for (let at = 0; at < channels[0].length; at += MP3_BLOCK) {+ s.push(channels.slice(0, 2).map((c) => c.subarray(at, at + MP3_BLOCK)));+ if (breathe) await breathe();+ }+ return s.end();+}diff --git a/src/lib/av/song-fit.ts b/src/lib/av/song-fit.tsnew file mode 100644index 00000000..3ed6c958--- /dev/null+++ b/src/lib/av/song-fit.ts@@ -0,0 +1,28 @@+import { EXTEND_UPLOAD_MAX_BYTES, REMIX_SECONDS, STEMS_FORMATS, STEMS_MAX_BYTES, UPLOAD_FORMATS } from "@/lib/lyrics";+import type { AudioFitRule } from "./fit-upload";++/**+ * Mureka's song tools as the fitting step's rules (src/lib/av/fit-upload.ts): Extend takes an MP3 or M4A of up to 10 MB,+ * Remix an MP3 or M4A of 10 s to 5:50, Stems an MP3 or M4A of up to 10 MB (src/lib/lyrics.ts, as the server checks them).+ * A converted song stays under 10 MB, so the same MP3 serves all three. One of Mureka's own songs goes by its id and is+ * never fitted (the caller leaves it out).+ */++/** The ops whose song is fitted. */+export const SONG_FIT_OPS = new Set(["song-extend", "song-remix", "song-stems"]);++/** What a converted song may weigh: Extend's and Stems' 10 MB. */+export const SONG_FIT_MAX_BYTES = Math.min(EXTEND_UPLOAD_MAX_BYTES, STEMS_MAX_BYTES);++/** The song slot's file picker: any sound or video file (a phone offers its videos too). */+export const SONG_ACCEPT = "audio/*,video/*";++/** The rule for a song tool's song, or null for any other op. */+export function murekaSongRule(op: string | undefined): AudioFitRule | null {+ if (op === "song-extend") return { for: "Mureka", tool: "Extend", formats: UPLOAD_FORMATS, maxBytes: EXTEND_UPLOAD_MAX_BYTES, outMaxBytes: SONG_FIT_MAX_BYTES };+ if (op === "song-stems") return { for: "Mureka", tool: "Stems", formats: STEMS_FORMATS, maxBytes: STEMS_MAX_BYTES, outMaxBytes: SONG_FIT_MAX_BYTES };+ if (op === "song-remix") {+ return { for: "Mureka", tool: "Remix", formats: UPLOAD_FORMATS, minSeconds: REMIX_SECONDS.min, maxSeconds: REMIX_SECONDS.max, outMaxBytes: SONG_FIT_MAX_BYTES };+ }+ return null;+}diff --git a/tests/fit-upload.test.ts b/tests/fit-upload.test.tsnew file mode 100644index 00000000..13af05ce--- /dev/null+++ b/tests/fit-upload.test.ts@@ -0,0 +1,127 @@+/**+ * The fitting step (src/lib/av/fit-upload.ts) with Mureka's song tools as its rules (src/lib/av/song-fit.ts): a file a+ * tool can't take as it is gets converted to an MP3 in the browser, or a part of it offered, decided from its length; past+ * the caps a phone can read (200 MB, 15 minutes) it is refused in one line and never uploaded. The MP3 encoder+ * (src/lib/av/mp3-encode.ts) runs here for real: its file reads back at the right length and size, and the server's own+ * check (songToolProblem) takes it.+ */+import { describe, expect, it } from "vitest";+import { clock, convertedLine, fitMaxSeconds, fitSourceKind, FIT_SOURCE_MAX_BYTES, mp3Kbps, mp3Name, planAudioFit, secondsAt } from "@/lib/av/fit-upload";+import { encodeMp3 } from "@/lib/av/mp3-encode";+import { murekaSongRule, SONG_FIT_MAX_BYTES } from "@/lib/av/song-fit";+import { songFormat, songToolProblem } from "@/lib/lyrics";+import { probeMedia } from "@/lib/media-probe";++const MB = 1_000_000;+const extend = murekaSongRule("song-extend")!;+const remix = murekaSongRule("song-remix")!;+const stems = murekaSongRule("song-stems")!;++describe("Mureka's rules", () => {+ it("covers Extend, Remix and Stems only", () => {+ expect(murekaSongRule("music")).toBeNull();+ expect(murekaSongRule(undefined)).toBeNull();+ expect(convertedLine(extend)).toBe("Converted to MP3 for Mureka");+ });++ it("keeps an MP3 or M4A the tool takes as it is", () => {+ expect(planAudioFit(extend, { format: "mp3", bytes: 9 * MB, seconds: 400 })).toEqual({ kind: "keep" });+ expect(planAudioFit(extend, { format: "m4a", bytes: 9 * MB })).toEqual({ kind: "keep" });+ // Extend has no length rule: a long MP3 under 10 MB goes as it is.+ expect(planAudioFit(extend, { format: "mp3", bytes: 9 * MB, seconds: 20 * 60 })).toEqual({ kind: "keep" });+ // Remix has no size rule.+ expect(planAudioFit(remix, { format: "mp3", bytes: 14 * MB, seconds: 300 })).toEqual({ kind: "keep" });+ });+});++describe("converting, decided by length", () => {+ it("converts a WAV, a FLAC, a video's sound and an MP3 over 10 MB, at 128 kbit/s or better when it fits", () => {+ expect(planAudioFit(extend, { format: "wav", bytes: 40 * MB, seconds: 4 * 60 })).toEqual({ kind: "convert", kbps: 320 });+ expect(planAudioFit(stems, { format: "flac", bytes: 30 * MB, seconds: 6 * 60 })).toEqual({ kind: "convert", kbps: 192 });+ expect(planAudioFit(remix, { format: "mp4", video: true, bytes: 150 * MB, seconds: 5 * 60 })).toEqual({ kind: "convert", kbps: 256 });+ expect(planAudioFit(extend, { format: "mp3", bytes: 14 * MB, seconds: 10 * 60 })).toEqual({ kind: "convert", kbps: 128 });+ });++ it("goes down to 96 kbit/s, never lower: past that it offers a part", () => {+ expect(planAudioFit(extend, { format: "wav", bytes: 140 * MB, seconds: 12 * 60 })).toEqual({ kind: "convert", kbps: 96 });+ const p = planAudioFit(extend, { format: "wav", bytes: 160 * MB, seconds: 14 * 60 });+ expect(p).toEqual({ kind: "trim", seconds: 14 * 60, max: fitMaxSeconds(extend), line: `This one is 14:00. Extend takes up to ${clock(fitMaxSeconds(extend))}: pick the part to use` });+ expect(mp3Kbps(fitMaxSeconds(extend), SONG_FIT_MAX_BYTES)).toBe(96);+ });++ it("offers Remix the part it takes of a longer song, even an MP3", () => {+ expect(planAudioFit(remix, { format: "mp3", bytes: 9 * MB, seconds: 7 * 60 })).toMatchObject({ kind: "trim", max: 350, line: "This one is 7:00. Remix takes up to 5:50: pick the part to use" });+ // Too short can't be fixed: the tool's own check says so.+ expect(planAudioFit(remix, { format: "mp3", bytes: 1 * MB, seconds: 5 })).toEqual({ kind: "keep" });+ });++ it("never reads a file past the caps, and says the largest it takes", () => {+ expect(planAudioFit(extend, { format: "wav", bytes: 10_000 * MB })).toEqual({ kind: "refuse", line: "The largest file this takes is 200 MB. Use a shorter clip" });+ expect(planAudioFit(remix, { format: "mp4", video: true, bytes: FIT_SOURCE_MAX_BYTES + 1, seconds: 60 })).toMatchObject({ kind: "refuse" });+ expect(planAudioFit(extend, { format: "wav", bytes: 100 * MB, seconds: 40 * 60 })).toEqual({+ kind: "refuse",+ line: "This file is 40:00. A part can be cut here from a file of up to 15:00: use a shorter clip",+ });+ expect(planAudioFit(extend, { format: "wav", bytes: 10 * MB })).toMatchObject({ kind: "refuse", line: expect.stringContaining("couldn't read this file's length") });+ });+});++describe("numbers", () => {+ it("fits about 10 minutes at 128 kbit/s and 13:35 at 96 under 10 MB", () => {+ expect(clock(secondsAt(128, SONG_FIT_MAX_BYTES))).toBe("10:11");+ expect(clock(secondsAt(96, SONG_FIT_MAX_BYTES))).toBe("13:35");+ for (const s of [30, 180, 350, 600, 815]) expect((s * mp3Kbps(s, SONG_FIT_MAX_BYTES)! * 1000) / 8).toBeLessThan(SONG_FIT_MAX_BYTES);+ expect(mp3Kbps(14 * 60, SONG_FIT_MAX_BYTES)).toBeNull();+ });++ it("knows a sound or video file by its type or name", () => {+ expect(fitSourceKind({ type: "audio/flac", name: "a.flac" })).toBe("audio");+ expect(fitSourceKind({ type: "", name: "VID_0001.MOV" })).toBe("video");+ expect(fitSourceKind({ type: "image/png", name: "a.png" })).toBeNull();+ expect(mp3Name("Take 2.wav")).toBe("Take 2.mp3");+ expect(mp3Name("/api/files/up/abc.flac")).toBe("abc.mp3");+ });+});++describe("the MP3 encoder", () => {+ const tone = (seconds: number, rate = 44100) => {+ const n = Math.round(seconds * rate);+ const l = new Float32Array(n);+ const r = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ l[i] = 0.4 * Math.sin((2 * Math.PI * 440 * i) / rate);+ r[i] = 0.4 * Math.sin((2 * Math.PI * 660 * i) / rate);+ }+ return [l, r];+ };+ const join = (parts: Uint8Array[]) => {+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.length;+ }+ return out;+ };++ it("makes an MP3 of the right length and size that Mureka's check takes", async () => {+ const seconds = 6;+ let calls = 0;+ const mp3 = join(await encodeMp3(tone(seconds), 44100, 128, () => void calls++));+ expect(calls).toBeGreaterThan(1);+ // An MPEG-1 Layer III frame sync, and the length the server reads from the file.+ expect(mp3[0]).toBe(0xff);+ expect(mp3[1] & 0xfe).toBe(0xfa);+ const info = probeMedia(mp3);+ expect(info?.duration).toBeGreaterThan(seconds - 0.2);+ expect(info?.duration).toBeLessThan(seconds + 0.2);+ expect(mp3.length).toBeGreaterThan(0.9 * ((seconds * 128_000) / 8));+ expect(mp3.length).toBeLessThan(1.1 * ((seconds * 128_000) / 8));+ expect(songToolProblem("song-extend", { format: songFormat("audio/mpeg", "a.mp3"), bytes: mp3.length, seconds: info?.duration }, false)).toBeNull();+ });++ it("encodes one channel too", async () => {+ const mp3 = join(await encodeMp3([tone(2)[0]], 44100, 96));+ expect(probeMedia(mp3)?.duration).toBeGreaterThan(1.8);+ });+});