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.

Split soundtrack: read a WebM or AVI header through the same scoped reader

Claude0f71e8d12e40
diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.ts
index 791776bd..1d0d063f 100644
--- a/src/server/audio-tools.ts
+++ b/src/server/audio-tools.ts
@@ -93,10 +93,11 @@ function present(url: string, gone: string): void {
/**
* A clip's length, channel count and whether it has sound, from its header (read as {@link lengthOf} reads it, through
- * storedMedia: only the asker's own files), or null when no reader knows the file.
+ * storedMedia: only the asker's own files, header only, cached; a WebM or AVI header too: screen and browser recordings
+ * are WebM), or null when no reader knows the file.
*/
function factsOf(url: string): ClipFacts | null {
- const found = storedMedia(url);
+ const found = storedMedia(url, { allContainers: true });
if (!found) throw new AudioToolError("That audio file is gone — add it again");
const info = found.info;
if (!info) return null;
diff --git a/src/server/media-facts.ts b/src/server/media-facts.ts
index eeadc201..0945fa0b 100644
--- a/src/server/media-facts.ts
+++ b/src/server/media-facts.ts
@@ -1,6 +1,5 @@
import "server-only";
-import fs from "node:fs/promises";
-import { probeMedia, probeMediaRanges, type MediaInfo } from "@/lib/media-probe";
+import { probeMedia, type MediaInfo } from "@/lib/media-probe";
import { probeAvi } from "./avi-probe";
import { probeWebm } from "./webm-probe";
@@ -34,31 +33,14 @@ export function mediaFacts(data: Uint8Array): SourceInfo {
return { duration: info.videoDuration ?? info.duration, width: info.width, height: info.height, fps: info.fps, hasAudio: info.hasAudio };
}
-/** How much of the start of a WebM / Matroska or AVI file is read for its header (the tracks come before the media). */
-const HEADER_BYTES = 1024 * 1024;
-
/**
- * The header facts of a stored file, read in ranges and never whole (a 2 GB upscale is a few small reads): an MP4 /
- * MOV's moov box, a WAV / FLAC / MP3 header, else the first megabyte for a WebM / Matroska or AVI header. Null when no
- * reader knows the file; throws when it can't be opened.
+ * A WebM / Matroska or AVI header's facts, from a file's first bytes (their tracks come before the media), for the
+ * stored-file reader (storage.ts storedMedia, which reads MP4 / MOV, WAV, FLAC and MP3 itself) when Split soundtrack asks
+ * for every container. Null when neither reader knows the bytes.
*/
-export async function fileInfo(abs: string): Promise<MediaInfo | null> {
- const fh = await fs.open(abs, "r");
- try {
- const size = (await fh.stat()).size;
- const read = async (start: number, end: number) => {
- const buf = Buffer.alloc(Math.max(0, Math.min(end, size) - start));
- const { bytesRead } = await fh.read(buf, 0, buf.length, start);
- return new Uint8Array(buf.buffer, buf.byteOffset, bytesRead);
- };
- const info = await probeMediaRanges(read, size);
- if (info) return info;
- const head = Buffer.from(await read(0, Math.min(size, HEADER_BYTES)));
- const webm = probeWebm(head);
- if (webm) return { container: "webm", duration: webm.duration, width: webm.width, height: webm.height, fps: webm.fps, hasVideo: webm.hasVideo, hasAudio: webm.hasAudio, ...(webm.channels && { channels: webm.channels }) };
- const avi = probeAvi(head);
- return avi ? { container: "avi", duration: avi.duration, width: avi.width, height: avi.height, fps: avi.fps, hasVideo: avi.hasVideo, hasAudio: avi.hasAudio } : null;
- } finally {
- await fh.close();
- }
+export function otherHeaderInfo(head: Buffer): MediaInfo | null {
+ const webm = probeWebm(head);
+ if (webm) return { container: "webm", duration: webm.duration, width: webm.width, height: webm.height, fps: webm.fps, hasVideo: webm.hasVideo, hasAudio: webm.hasAudio, ...(webm.channels && { channels: webm.channels }) };
+ const avi = probeAvi(head);
+ return avi ? { container: "avi", duration: avi.duration, width: avi.width, height: avi.height, fps: avi.fps, hasVideo: avi.hasVideo, hasAudio: avi.hasAudio } : null;
}
diff --git a/src/server/storage.ts b/src/server/storage.ts
index d52945ee..0f9c933e 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -9,6 +9,7 @@ import { fetchRemote } from "./remote-fetch";
import { tenant, tenantAccount } from "./tenant";
import { accountInputLimit } from "./account-files";
import { assetAccount, fileAccount, generationAccount } from "./account-library";
+import { otherHeaderInfo } from "./media-facts";
export const FILES_DIR = path.join(DATA_DIR, "files");
@@ -392,8 +393,12 @@ const OWNER_MOOV_BYTES = 64 * 1024 * 1024;
* that is also another's file: it answers like one that is gone, before any cache is looked at.
* - { info: null }: a file the asker may use whose header says nothing Fuobe reads (WebM…), or, inside a tenant, one
* bigger than an upload of its kind may be (never read: the run itself says it is too big).
+ *
+ * `allContainers` (Split soundtrack): a WebM / Matroska or AVI header is read too, from the same first bytes
+ * (media-facts.ts otherHeaderInfo), when the header says nothing else Fuobe reads. Cached apart, so every other caller's
+ * answer for those files stays as it was.
*/
-export function storedMedia(ref: string): { info: MediaInfo | null } | null {
+export function storedMedia(ref: string, opts: { allContainers?: boolean } = {}): { info: MediaInfo | null } | null {
const rel = filesRel(ref);
if (rel === null) return null;
if (tenant() && !ownsRef(ref, rel)) return null;
@@ -408,7 +413,7 @@ export function storedMedia(ref: string): { info: MediaInfo | null } | null {
if (!st.isFile()) return null;
if (tenant() && st.size > accountInputLimit(contentTypeFor(rel)).bytes) return { info: null };
const cache = (globalThis.__fuobeStoredFacts ??= new Map());
- const key = `${rel}:${st.size}:${st.mtimeMs}`;
+ const key = `${rel}:${st.size}:${st.mtimeMs}${opts.allContainers ? ":all" : ""}`;
if (cache.has(key)) return { info: cache.get(key) ?? null };
let info: MediaInfo | null = null;
try {
@@ -419,6 +424,13 @@ export function storedMedia(ref: string): { info: MediaInfo | null } | null {
return buf.subarray(0, fs.readSync(fd, buf, 0, buf.length, start));
};
info = probeMediaRangesSync(read, st.size, { headBytes: STORED_HEAD_BYTES, maxMoov: tenant() ? TENANT_MOOV_BYTES : OWNER_MOOV_BYTES });
+ if (!info && opts.allContainers) {
+ try {
+ info = otherHeaderInfo(read(0, Math.min(st.size, STORED_HEAD_BYTES)));
+ } catch {
+ info = null;
+ }
+ }
} finally {
fs.closeSync(fd);
}
diff --git a/tests/price-check-reads.test.ts b/tests/price-check-reads.test.ts
index 05159add..af48404b 100644
--- a/tests/price-check-reads.test.ts
+++ b/tests/price-check-reads.test.ts
@@ -84,6 +84,25 @@ describe("H-3: price checks read only the header of the asker's own files", () =
expect((await previewAudioTool({ tool: "loop", engine: "open", audio: owners, duration: 60 })).summary).toMatch(/Loops it/);
});
+ it("Split soundtrack and its remux: never another's file, and it answers like a file that is gone", async () => {
+ const owners = saveFile({ data: wav(30), contentType: "audio/wav", source: "upload" }).url;
+ const others = saveFile({ data: wav(30), contentType: "audio/wav", source: "upload", accountId: b }).url;
+ const mine = saveFile({ data: wav(30), contentType: "audio/wav", source: "upload", accountId: a }).url;
+ const video = saveFile({ data: MP4, contentType: "video/mp4", source: "upload", accountId: a }).url;
+ for (const url of [owners, others]) {
+ await expect(asA(() => previewAudioTool({ tool: "split", engine: "open", media: url, kind: "audio" }))).rejects.toThrow(/gone/);
+ await expect(asGuest(() => previewAudioTool({ tool: "split", engine: "open", media: url, kind: "audio" }))).rejects.toThrow(/gone/);
+ await expect(asA(() => previewAudioTool({ tool: "remux", engine: "open", video, audio: url }))).rejects.toThrow("That mix is gone");
+ await expect(asA(() => previewAudioTool({ tool: "remux", engine: "open", video: url, audio: mine }))).rejects.toThrow("That video is gone");
+ }
+ // Its own file: the header's length and channels, never the whole file. The owner still prices with any file.
+ const spies = wholeReads();
+ expect(await asA(() => previewAudioTool({ tool: "split", engine: "open", media: mine, kind: "audio" }))).toMatchObject({ length: 30, channels: 1, demo: false });
+ expect(called(spies, mine)).toBe(false);
+ expect((await asA(() => previewAudioTool({ tool: "remux", engine: "open", video, audio: mine }))).steps).toBe(1);
+ expect((await previewAudioTool({ tool: "split", engine: "open", media: others, kind: "audio" })).channels).toBe(1);
+ });
+
it("audio Join: ten copies of its own file read its header, not the whole file", async () => {
const mine = saveFile({ data: wav(20), contentType: "audio/wav", source: "upload", accountId: a }).url;
const spies = wholeReads();
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index 61484dbb..51f5dfca 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -59,7 +59,7 @@ function call(url: string, body: unknown, cookie?: string) {
const png = (name: string) => saveFile({ data: encodePng({ width: 18, height: 32, data: Buffer.alloc(18 * 32 * 4, 128) }), contentType: "image/png", name, source: "upload" }).url;
/** A two-second 16-bit stereo WAV, saved as the owner's upload. */
-function wav(name = "film.wav"): string {
+function wav(name = "film.wav", accountId?: string): string {
const rate = 8000;
const n = rate * 2;
const buf = Buffer.alloc(44 + n * 4);
@@ -75,7 +75,7 @@ function wav(name = "film.wav"): string {
buf.writeUInt16LE(16, 34);
buf.write("data", 36);
buf.writeUInt32LE(n * 4, 40);
- return saveFile({ data: buf, contentType: "audio/wav", name, source: "upload" }).url;
+ return saveFile({ data: buf, contentType: "audio/wav", name, source: "upload", ...(accountId && { accountId }) }).url;
}
let n = 0;
@@ -204,17 +204,23 @@ describe("the routes: a visitor's price is its own GPU's, and the owner's charac
expect((await turnaroundEstimate.POST(call("/api/turnaround/estimate", { engine: "open", views, elementId: "no-such-id" }, owner))).status).toBe(404);
});
- it("prices a visitor's Split soundtrack on its own GPU, never a demo", async () => {
+ it("prices a visitor's Split soundtrack on its own GPU, never a demo, and only of its own file", async () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
- const media = wav();
- const body = { tool: "split", engine: "open", media, kind: "audio", name: "Film" };
- const guest = await audioTools.POST(call("/api/audio-tools?preview=1", body));
- expect(guest.status).toBe(200);
- expect(await guest.json()).toMatchObject({ steps: 1, costUsd: 0, demo: false });
- const account = await audioTools.POST(call("/api/audio-tools?preview=1", body, auth.createSession(newAccount().id).value));
- expect(await account.json()).toMatchObject({ steps: 1, demo: false });
- const owner = await audioTools.POST(call("/api/audio-tools?preview=1", body, auth.createSession().value));
- expect(await owner.json()).toMatchObject({ steps: 1, demo: true });
+ const who = newAccount();
+ const cookie = auth.createSession(who.id).value;
+ const owners = wav();
+ const body = (media: string) => ({ tool: "split", engine: "open", media, kind: "audio", name: "Film" });
+ // A price check reads only the asker's own files (storage.ts storedMedia): the owner's file answers a guest, who owns
+ // none, and an account as a file that is gone, saying nothing of what it holds.
+ for (const c of [undefined, cookie]) {
+ const r = await audioTools.POST(call("/api/audio-tools?preview=1", body(owners), c));
+ expect(r.status).toBe(422);
+ expect((await r.json()).error).toBe("That audio file is gone — add it again");
+ }
+ const account = await audioTools.POST(call("/api/audio-tools?preview=1", body(wav("mine.wav", who.id)), cookie));
+ expect(await account.json()).toMatchObject({ steps: 1, costUsd: 0, demo: false, channels: 2 });
+ const owner = await audioTools.POST(call("/api/audio-tools?preview=1", body(owners), auth.createSession().value));
+ expect(await owner.json()).toMatchObject({ steps: 1, demo: true, channels: 2 });
});
});
diff --git a/tests/split-soundtrack.test.ts b/tests/split-soundtrack.test.ts
index 20e8e0aa..db02a9d3 100644
--- a/tests/split-soundtrack.test.ts
+++ b/tests/split-soundtrack.test.ts
@@ -59,11 +59,10 @@ process.env.FUOBE_DATA_DIR = dir;
process.env.COMFYUI_URL = "http://127.0.0.1:9";
const { setSetting } = await import("@/server/settings");
-const { getAsset, saveFile, scratchDir } = await import("@/server/storage");
+const { getAsset, saveFile, scratchDir, storedMedia } = await import("@/server/storage");
const gens = await import("@/server/generations");
const route = await import("@/app/api/audio-tools/route");
const exportRoute = await import("@/app/api/audio-tools/export/route");
-const { fileInfo } = await import("@/server/media-facts");
beforeAll(() => setSetting("demoMode", "auto"));
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -489,8 +488,9 @@ describe("POST /api/audio-tools split and remux (demo mode)", () => {
expect(run.result.request.params.extra).toEqual({ channels: "mono", sourceChannels: 6 });
});
- it("reads a header without reading the file: a 2.2 GB file is a few small reads", async () => {
- const file = path.join(dir, "huge.wav");
+ it("reads a header without reading the file: a 2.2 GB file is a few small reads", () => {
+ fs.mkdirSync(path.join(dir, "files", "uploads"), { recursive: true });
+ const file = path.join(dir, "files", "uploads", "huge.wav");
const head = Buffer.alloc(44);
const data = 2.2e9 - 44;
head.write("RIFF", 0);
@@ -508,7 +508,7 @@ describe("POST /api/audio-tools split and remux (demo mode)", () => {
fs.writeFileSync(file, head);
fs.truncateSync(file, 2.2e9);
try {
- expect(await fileInfo(file)).toEqual({ container: "wav", duration: data / 192000, hasVideo: false, hasAudio: true, channels: 2 });
+ expect(storedMedia("/api/files/uploads/huge.wav", { allContainers: true })).toEqual({ info: { container: "wav", duration: data / 192000, hasVideo: false, hasAudio: true, channels: 2 } });
} finally {
fs.rmSync(file, { force: true });
}