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.

Media probe: Ogg Vorbis and Opus sound and length

Adarsh5c917601c346
diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.ts
index 613ef902..a0822c30 100644
--- a/src/lib/media-probe.ts
+++ b/src/lib/media-probe.ts
@@ -1,15 +1,15 @@
/**
* Just enough of the common media containers to know a file's shape before a job runs: duration, displayed
* size, frame rate / count, which tracks it has and how many audio channels. Reads MP4 / MOV / M4A (ISO-BMFF),
- * WAV, FLAC and MP3 from the bytes in memory; anything else (WebM, MKV, Ogg…) is "unknown" (null) and callers fall
- * back to safe defaults.
+ * WAV, FLAC, MP3 and Ogg (Vorbis or Opus sound) from the bytes in memory; anything else (WebM, MKV…) is "unknown" (null)
+ * and callers fall back to safe defaults.
*/
export interface MediaInfo {
/**
* "webm": read by the server's WebM / Matroska reader (src/server/webm-probe.ts), for the ComfyUI uploads;
* "image": a still's size (src/lib/image-size.ts), so "auto" can follow a start frame's shape.
*/
- container: "mp4" | "wav" | "flac" | "mp3" | "webm" | "avi" | "image";
+ container: "mp4" | "wav" | "flac" | "mp3" | "ogg" | "webm" | "avi" | "image";
/** Seconds (the longest track). */
duration?: number;
/** Seconds of picture (the video track alone). */
@@ -22,7 +22,7 @@ export interface MediaInfo {
hasVideo: boolean;
hasAudio: boolean;
/**
- * Audio channels, where the header says: WAV, FLAC, MP3, and an MP4 / MOV / M4A's first sound track (its sample
+ * Audio channels, where the header says: WAV, FLAC, MP3, Ogg, and an MP4 / MOV / M4A's first sound track (its sample
* entry, or an AAC track's own config); the server's WebM / Matroska reader adds them for those.
*/
channels?: number;
@@ -40,6 +40,8 @@ export function probeMedia(data: Uint8Array, size = data.length): MediaInfo | nu
const total = Math.max(size, data.length);
if (fourcc(data, 0) === "RIFF" && fourcc(data, 8) === "WAVE") return probeWav(data, total);
if (fourcc(data, 0) === "fLaC") return probeFlac(data);
+ // An Ogg's length is in its last page: known when `data` is the whole file.
+ if (fourcc(data, 0) === "OggS") return probeOgg(data, size <= data.length ? data : undefined);
if (fourcc(data, 4) === "ftyp" || ["moov", "mdat", "free", "wide", "skip"].includes(fourcc(data, 4))) return probeIsoBmff(data);
return probeMp3(data, total);
} catch {
@@ -76,6 +78,7 @@ export async function probeMediaRanges(read: ReadRange, size: number): Promise<M
try {
const head = await read(0, Math.min(size, HEAD_BYTES));
if (head.length < 12) return null;
+ if (fourcc(head, 0) === "OggS") return probeOgg(head, size <= head.length ? head : await read(Math.max(0, size - OGG_TAIL_BYTES), size));
if (!ISO_TOP.includes(fourcc(head, 4))) return size <= head.length ? probeMedia(head) : headerSays(head) ? probeMedia(head, size) : null;
for (let o = 0, n = 0; o + 8 <= size; n++) {
if (n >= MAX_TOP_BOXES) return null;
@@ -114,6 +117,7 @@ export function probeMediaRangesSync(read: ReadRangeSync, size: number, opts: {
try {
const head = read(0, Math.min(size, opts.headBytes ?? HEAD_BYTES));
if (head.length < 12) return null;
+ if (fourcc(head, 0) === "OggS") return probeOgg(head, size <= head.length ? head : read(Math.max(0, size - OGG_TAIL_BYTES), size));
if (!ISO_TOP.includes(fourcc(head, 4))) return probeMedia(head, size);
for (let o = 0, n = 0; o + 8 <= size; n++) {
if (n >= MAX_TOP_BOXES) return null;
@@ -382,3 +386,51 @@ function probeMp3(data: Uint8Array, total = data.length): MediaInfo | null {
if (!bitrate) return null;
return { container: "mp3", duration: ((total - o) * 8) / bitrate, hasVideo: false, hasAudio: true, channels: mono ? 1 : 2 };
}
+
+// ---------------------------------------------------------------------------
+// Ogg (Vorbis, Opus)
+
+/** The end of an Ogg read for its last page: a page is at most 65,307 bytes, so its header is always in here. */
+const OGG_TAIL_BYTES = 72 * 1024;
+
+/**
+ * An Ogg file's sound (RFC 3533 pages): the first page's identification header says the codec, channels and rate, and the
+ * last page's granule position is the samples played to its end (Vorbis I spec §A.2; Opus, RFC 7845 §4: at 48 kHz, less
+ * the pre-skip). `tail`: the file's last bytes (or the whole file), for the length; without it the length is unknown.
+ * Null for an Ogg of anything else (Theora video, FLAC in Ogg).
+ */
+function probeOgg(head: Uint8Array, tail?: Uint8Array): MediaInfo | null {
+ if (head.length < 28 || head[4] !== 0) return null;
+ const d = new DataView(head.buffer, head.byteOffset, head.byteLength);
+ const serial = d.getUint32(14, true);
+ const p = 27 + head[26];
+ const text = (o: number, n: number) => String.fromCharCode(...head.subarray(o, o + n));
+ let rate: number;
+ let channels: number;
+ let preSkip = 0;
+ if (p + 30 <= head.length && head[p] === 1 && text(p + 1, 6) === "vorbis") {
+ channels = head[p + 11];
+ rate = d.getUint32(p + 12, true);
+ } else if (p + 19 <= head.length && text(p, 8) === "OpusHead") {
+ channels = head[p + 9];
+ preSkip = d.getUint16(p + 10, true);
+ rate = 48_000; // Opus granule positions always count 48 kHz samples.
+ } else return null;
+ if (!rate || !channels) return null;
+ const info: MediaInfo = { container: "ogg", hasVideo: false, hasAudio: true, channels };
+ if (!tail) return info;
+ // The last page of the same stream with a granule position (-1 = no packet ends on that page).
+ const t = new DataView(tail.buffer, tail.byteOffset, tail.byteLength);
+ for (let o = tail.length - 27; o >= 0; o--) {
+ if (tail[o] !== 0x4f || tail[o + 1] !== 0x67 || tail[o + 2] !== 0x67 || tail[o + 3] !== 0x53 || tail[o + 4] !== 0) continue;
+ if (t.getUint32(o + 14, true) !== serial) continue;
+ const lo = t.getUint32(o + 6, true);
+ const hi = t.getUint32(o + 10, true);
+ if (lo === 0xffffffff && hi === 0xffffffff) continue;
+ const samples = hi * 2 ** 32 + lo - preSkip;
+ if (samples > 0) info.duration = samples / rate;
+ break;
+ }
+ return info;
+}
+
diff --git a/tests/media-probe-ogg.test.ts b/tests/media-probe-ogg.test.ts
new file mode 100644
index 00000000..91e84fde
--- /dev/null
+++ b/tests/media-probe-ogg.test.ts
@@ -0,0 +1,112 @@
+/**
+ * Ogg sound (Vorbis and Opus) read from its pages (RFC 3533): the first page's identification header gives the channels and
+ * rate, the last page's granule position the samples to its end (Opus: at 48 kHz, less the pre-skip, RFC 7845). Before, an
+ * Ogg voice had no length, so fal's H3 Max lip sync window (5 s to 15 minutes) and its per-second price were skipped for it.
+ */
+import { describe, expect, it } from "vitest";
+import { getModel } from "@/lib/catalog";
+import { voiceWindowProblem } from "@/lib/catalog/clip-windows";
+import { probeMedia, probeMediaRanges, probeMediaRangesSync } from "@/lib/media-probe";
+import { mediaFacts } from "@/server/media-facts";
+
+/** One Ogg page (the CRC is not checked by the reader, so it is left 0). */
+function page(granule: bigint, serial: number, seq: number, body: Uint8Array, type = 0): Uint8Array {
+ const segs: number[] = [];
+ for (let n = body.length; ; n -= 255) {
+ segs.push(Math.min(255, n));
+ if (n < 255) break;
+ }
+ const out = new Uint8Array(27 + segs.length + body.length);
+ const d = new DataView(out.buffer);
+ out.set([0x4f, 0x67, 0x67, 0x53], 0);
+ out[5] = type;
+ d.setBigUint64(6, granule, true);
+ d.setUint32(14, serial, true);
+ d.setUint32(18, seq, true);
+ out[26] = segs.length;
+ out.set(segs, 27);
+ out.set(body, 27 + segs.length);
+ return out;
+}
+
+const join = (...parts: Uint8Array[]) => {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let o = 0;
+ for (const p of parts) {
+ out.set(p, o);
+ o += p.length;
+ }
+ return out;
+};
+
+function vorbisId(channels: number, rate: number): Uint8Array {
+ const b = new Uint8Array(30);
+ const d = new DataView(b.buffer);
+ b[0] = 1;
+ b.set(new TextEncoder().encode("vorbis"), 1);
+ b[11] = channels;
+ d.setUint32(12, rate, true);
+ b[29] = 1;
+ return b;
+}
+
+function opusHead(channels: number, preSkip: number): Uint8Array {
+ const b = new Uint8Array(19);
+ const d = new DataView(b.buffer);
+ b.set(new TextEncoder().encode("OpusHead"), 0);
+ b[8] = 1;
+ b[9] = channels;
+ d.setUint16(10, preSkip, true);
+ d.setUint32(12, 44100, true);
+ return b;
+}
+
+/** An Ogg file: its id page, `filler` bytes of audio pages, and a last page ending at `granule`. */
+function ogg(id: Uint8Array, granule: bigint, filler = 1000, serial = 7): Uint8Array {
+ const audio: Uint8Array[] = [];
+ for (let left = filler, seq = 2; left > 0; left -= 4000, seq++) audio.push(page(-1n & 0xffffffffffffffffn, serial, seq, new Uint8Array(Math.min(4000, left))));
+ return join(page(0n, serial, 0, id, 2), page(0n, serial, 1, new Uint8Array(40)), ...audio, page(granule, serial, 99, new Uint8Array(200), 4));
+}
+
+describe("Ogg sound from its pages", () => {
+ it("Vorbis: channels and rate from the id header, the length from the last granule position", () => {
+ expect(probeMedia(ogg(vorbisId(2, 44100), 143_325n))).toEqual({ container: "ogg", hasVideo: false, hasAudio: true, channels: 2, duration: 3.25 });
+ });
+
+ it("Opus: 48 kHz granule positions less the pre-skip", () => {
+ expect(probeMedia(ogg(opusHead(1, 312), 360_312n))).toMatchObject({ container: "ogg", channels: 1, duration: 7.5 });
+ });
+
+ it("a last page without a granule position (-1) is passed over for the one before it", () => {
+ const file = join(ogg(vorbisId(1, 48000), 240_000n), page(0xffffffffffffffffn, 7, 100, new Uint8Array(50)));
+ expect(probeMedia(file)?.duration).toBe(5);
+ });
+
+ it("only the first bytes: the sound is known, its length is not; with the file's size, its end is read", async () => {
+ const file = ogg(vorbisId(2, 48000), 48000n * 600n, 400_000);
+ expect(probeMedia(file.subarray(0, 4096), file.length)).toEqual({ container: "ogg", hasVideo: false, hasAudio: true, channels: 2 });
+ const reads: [number, number][] = [];
+ const read = (s: number, e: number) => (reads.push([s, e]), file.subarray(s, e));
+ expect(probeMediaRangesSync(read, file.length)?.duration).toBe(600);
+ expect(await probeMediaRanges(async (s, e) => file.subarray(s, e), file.length)).toMatchObject({ container: "ogg", duration: 600 });
+ // The head and the last 72 KB, never the whole file.
+ expect(reads.every(([s, e]) => e - s <= 256 * 1024)).toBe(true);
+ });
+
+ it("an Ogg of anything else (Theora video) is not read as sound", () => {
+ const theora = new Uint8Array(42);
+ theora[0] = 0x80;
+ theora.set(new TextEncoder().encode("theora"), 1);
+ expect(probeMedia(ogg(theora, 1000n))).toBeNull();
+ });
+});
+
+describe("an Ogg voice on H3 Max lip sync", () => {
+ it("is held to fal's 5 s minimum like any other voice", () => {
+ const lipsync = getModel("minimax-h3-max-lipsync")!;
+ const short = mediaFacts(ogg(opusHead(1, 312), 48000n * 3n + 312n));
+ expect(short).toMatchObject({ duration: 3, hasAudio: true });
+ expect(voiceWindowProblem(lipsync, short.duration!)).toMatch(/needs at least 5 s of audio, and this is 3 s/);
+ expect(voiceWindowProblem(lipsync, mediaFacts(ogg(vorbisId(1, 44100), 44100n * 12n)).duration!)).toBeNull();
+ });
+});