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
DBS D1 fixes: no missing model on GPU hosts, 5.1 split in mono, mixes exported in parts, header-only probes
Claudebca202661625
diff --git a/docs/research/dbs-separation-7.md b/docs/research/dbs-separation-7.mdindex bf68caa8..a6593017 100644--- a/docs/research/dbs-separation-7.md+++ b/docs/research/dbs-separation-7.md@@ -230,7 +230,7 @@ All hand-built (`scripts/comfy/hand-built/`), with only `DBSLoader`, `DBSSeparat| 8 | `SaveAudioAdvanced` | [4,0], `fuobe/dbs/background` → stem `background` || 9 | `PreviewAny` | `source` [3,3] → text output, role `report` (speed and windows for the job's details) |-Why the background is "original minus speech" (node 4) and not "music plus effects": with `channels: mono` it keeps the original stereo image (§2.1); with `each channel` it equals music + effects in every channel anyway (the sum is exact). Output order puts `voice` first, so a chain without a `stem` takes the dialogue (`pickOutput`, `src/server/generations.ts` L777–789). Defaults: `DBS-BSRNN-DnR` and `mono` on CPU hosts; `DBS-TIGER-DnR` and `each channel` are worth it on CUDA hosts, where they still run well over 10x real time (§2.4). Fuobe can tell which host it has from `GET /system_stats` `devices[0].type` (ComfyUI `server.py` L783–796; Fuobe already reads `devices[0]` at `comfyui.ts` L1530). For more than 2 channels, use `each channel` or down-mix first, because node 4 would take the speech out of the LFE and surround channels too.+Why the background is "original minus speech" (node 4) and not "music plus effects": with `channels: mono` it keeps the original stereo image (§2.1); with `each channel` it equals music + effects in every channel anyway (the sum is exact). Output order puts `voice` first, so a chain without a `stem` takes the dialogue (`pickOutput`, `src/server/generations.ts` L777–789). Defaults: `DBS-BSRNN-DnR` and `mono` on CPU hosts; `DBS-TIGER-DnR` and `each channel` are worth it on CUDA hosts, where they still run well over 10x real time (§2.4). Fuobe can tell which host it has from `GET /system_stats` `devices[0].type` (ComfyUI `server.py` L783–796; Fuobe already reads `devices[0]` at `comfyui.ts` L1530). For more than 2 channels, use `each channel` or down-mix first, because node 4 would take the speech out of the LFE and surround channels too. *As built (D1 fixes):* `each channel` can't be used there: ComfyUI's audio save (`comfy_api/latest/_ui.py`, `AudioSaveHelper`) writes any waveform with more than one channel as "stereo", so a 4 s 5.1 stem came out on the worker as 12 s of scrambled stereo. A file with more than 2 channels is split in `mono`, and node 4 becomes music + effects (`AudioMerge` add): every stem is mono and valid.**B. `dub-prepare-dbs-transcribe`** (capability `separate-audio`). Same output contract as today's `dub-prepare-separate-transcribe` (`library.spec.mjs` L2239–2262: stems `voice` and `background`, text `cues`, `transcript`, `language`), so the open dub only changes its model id.@@ -262,7 +262,7 @@ Honest expectation: the separation half becomes CPU-friendly (23 MB instead of t### 4.5 Library tooling changes- **Install pin.** Add `[ComfyUI-DBS]="https://github.com/hiroki-abe-58/ComfyUI-DBS f656e53434b5485c148a2866fbd6ddc6b6152ed6"` to `NODES` in `scripts/comfy/install-comfyui.sh` (L15–34), with a comment that the Registry flags 0.1.0 and the code was read at this commit. No extra Python packages. The weights are small enough to fetch in the same script: an opt-out block (`DBS_WEIGHTS=0` skips it) that downloads the 4 files of §3.1 at the pinned revisions into `models/dbs/<name>/` and checks them with `sha256sum -c`.-- **Folder models.** `build-library.mjs` finds models only through `LOADER_FOLDERS[class][input]` or a file-name extension on a widget value (L31–48, L306–334). `DBSLoader.model` is a name with no extension, so the builder would neither list nor flag the DBS weights, and the Workflows page's missing-model help (`src/app/api/comfyui/route.ts`, `src/components/workflows-view.tsx` L43) would not know them. Fix: `KNOWN_MODELS` entries keyed by the path under the folder (`'DBS-BSRNN-DnR/model.safetensors': { folder: 'dbs', url }`, and the same for `config.json` and the TIGER pair) plus a new spec field, say `requiredModels: [...]`, handled next to the existing `optionalModels` loop (L335–346); TIGER goes in `optionalModels`. Presence then works as it is: with the pack loaded, ComfyUI registers the `dbs` folder with no extension filter (`folder_paths.py` L398, L445–446), so `GET /models/dbs` lists `DBS-BSRNN-DnR/config.json` and `DBS-BSRNN-DnR/model.safetensors`, which `/api/comfyui` matches by file string. (A Windows ComfyUI would list back-slashed paths; a minor gap.)+- **Folder models.** `build-library.mjs` finds models only through `LOADER_FOLDERS[class][input]` or a file-name extension on a widget value (L31–48, L306–334). `DBSLoader.model` is a name with no extension, so the builder would neither list nor flag the DBS weights, and the Workflows page's missing-model help (`src/app/api/comfyui/route.ts`, `src/components/workflows-view.tsx` L43) would not know them. Fix: `KNOWN_MODELS` entries keyed by the path under the folder (`'DBS-BSRNN-DnR/model.safetensors': { folder: 'dbs', url }`, and the same for `config.json` and the TIGER pair) plus a new spec field, say `requiredModels: [...]`, handled next to the existing `optionalModels` loop (L335–346); TIGER goes in `optionalModels`. Presence then works as it is: with the pack loaded, ComfyUI registers the `dbs` folder with no extension filter (`folder_paths.py` L398, L445–446), so `GET /models/dbs` lists `DBS-BSRNN-DnR/config.json` and `DBS-BSRNN-DnR/model.safetensors`, which `/api/comfyui` matches by file string. (A Windows ComfyUI would list back-slashed paths; a minor gap.) *As built (D1):* the TIGER pair is in `requiredModels` too, because a CUDA host runs DBS-TIGER by default and the Workflows page's install commands skip optional files; the provider also reads `GET /models/dbs` (back slashes included) and never queues a model that isn't on disk.- **Packs not on the validation server.** Use the existing `packs: ['ComfyUI-DBS']` field with a `PACK_CLASSES` entry `/^DBS(Loader|Separate)$/` (`library.spec.mjs` L140–143 and L2809; `build-library.mjs` L260–262), like the H3 entries. Add `CUSTOM_NODE_REPOS['ComfyUI-DBS']` (L110–136).- **Bindings.** Add `separationModel`, `channels`, `voiceDb`, `musicDb` and `effectsDb` to `BINDING_KEYS` (`build-library.mjs` L96ff) and to the spec header, and teach `src/server/providers/comfyui.ts` to fill them from `params`.- **Validation.** `validate-workflows.mjs` only POSTs `/prompt` and deletes the job (L9–20), and it creates zero-byte placeholders for missing models (L111–113, L190). DBS's combo is fixed, so placeholders are not needed to validate, and nothing checks that the real weights exist: only a run would catch a missing file, at `DBSLoader`.diff --git a/scripts/comfy/README.md b/scripts/comfy/README.mdindex 27f1b1d1..daf29811 100644--- a/scripts/comfy/README.md+++ b/scripts/comfy/README.md@@ -341,11 +341,15 @@ COMFYUI_URL=http://127.0.0.1:<port> COMFYUI_MODELS_DIR=<that ComfyUI>/models nodpublic reason; the code was read at this commit. It needs only einops and safetensors, already installed.- **Weights** (23 MB): `install-comfyui.sh` downloads `config.json` and `model.safetensors` of JusperLee/DBS-BSRNN-DnR andJusperLee/DBS-TIGER-DnR at pinned revisions into `models/dbs/<model>/` and checks them with `sha256sum -c` (`DBS_WEIGHTS=0`- skips it). The manifest lists them by their path under the folder (`requiredModels` / `optionalModels`), which is what- `GET /models/dbs` answers, so the Workflows page knows when they are there.+ skips it). The manifest lists all four by their path under the folder (`requiredModels`: a CUDA host runs DBS-TIGER, so+ the Workflows page's install commands fetch both models), which is what `GET /models/dbs` answers, so the Workflows page+ knows when they are there.- **Host pick**: the provider uses DBS-TIGER when `GET /system_stats` says the first device is `cuda` and DBS-BSRNN otherwise- (about 3x faster on a CPU: 0.27x real time against 0.09x on a 4-CPU host), unless the run picks one; `each channel` for- stereo stems and always for files with more than 2 channels.+ (about 3x faster on a CPU: 0.27x real time against 0.09x on a 4-CPU host), unless the run picks one; the other model when+ `GET /models/dbs` shows the pick isn't on disk, and a model asked for that isn't there is refused in words before the+ job is queued. `each channel` for stereo stems. ComfyUI saves audio as mono or stereo only (a 5.1 waveform is written as+ scrambled stereo three times as long), so a file with more than 2 channels is split in `mono` and its background is the+ music and effects stems added up (the provider rewires node 4 to `AudioMerge` add).## Adding a workflowdiff --git a/scripts/comfy/build-library.mjs b/scripts/comfy/build-library.mjsindex a8932c60..0a14dffa 100644--- a/scripts/comfy/build-library.mjs+++ b/scripts/comfy/build-library.mjs@@ -134,8 +134,8 @@ export const BINDING_KEYS = new Set(['separationModel', 'channels',]);-// Sizes in GB: two decimals, three under 0.1 GB (a 4 MB DBS model would otherwise read 0).-const gb = (bytes) => (bytes < 1e8 ? Math.round(bytes / 1e6) / 1000 : Math.round((bytes / 1e9) * 100) / 100);+// Sizes in GB: two decimals, and three where two would read 0 (a 4 MB DBS model), so no other entry's size changes.+export const gb = (bytes) => Math.round((bytes / 1e9) * 100) / 100 || Math.round(bytes / 1e6) / 1000;const readJson = (p, fallback) => (fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : fallback);const writeJson = (p, v) => fs.writeFileSync(p, JSON.stringify(v, null, 2) + '\n');export const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');@@ -341,7 +341,7 @@ async function main() {// Files a loader reads by a name with no extension (DBSLoader: models/dbs/<model>/config.json + model.safetensors), which the// loop above can't see: listed like any model, so install help and the presence check (GET /models/<folder>) know them.- // Then files a model control can pick instead (FILM for RIFE, DBS-TIGER): listed as optional, so missing-model help names them.+ // Then files a model control can pick instead (FILM for RIFE): listed as optional, so missing-model help names them.for (const [file, optional] of [...(spec.requiredModels || []).map((f) => [f, false]), ...(spec.optionalModels || []).map((f) => [f, true])]) {if (models.has(file)) continue;const known = KNOWN_MODELS[file];diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex befb95a8..41719e77 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -109,10 +109,11 @@// Keys added with DBS soundtrack separation (docs/research/dbs-separation-7.md §4). * = the provider fills it:// separationModel* (DBSLoader model: DBS-BSRNN-DnR (fast) | DBS-TIGER-DnR (best); params.extra.separationModel,// else the host's pick: TIGER when /system_stats says the device is cuda, BSRNN on a CPU)-// channels* (DBSSeparate channels: mono | each channel; params.extra.channels, forced to "each channel"-// for inputs with more than 2 channels)+// channels* (DBSSeparate channels: mono | each channel; params.extra.channels, "mono" for inputs with+// more than 2 channels, which ComfyUI can't save, with node 4 rewired to music + effects)// Entry field requiredModels: files a loader reads by a name with no extension (DBSLoader's model folder), listed in the-// manifest like any model (KNOWN_MODELS keys are the path under the folder, e.g. 'DBS-BSRNN-DnR/model.safetensors').+// manifest like any model (KNOWN_MODELS keys are the path under the folder, e.g. 'DBS-BSRNN-DnR/model.safetensors'), so the+// Workflows page's presence check and its install commands cover them.import fs from 'node:fs';@@ -2390,8 +2391,9 @@ export const SPEC = [capability: 'separate-audio',handBuilt: 'hand-built/separate-soundtrack-dbs.json',packs: ['ComfyUI-DBS'],- requiredModels: ['DBS-BSRNN-DnR/model.safetensors', 'DBS-BSRNN-DnR/config.json'],- optionalModels: ['DBS-TIGER-DnR/model.safetensors', 'DBS-TIGER-DnR/config.json'],+ // Both models are required (23 MB together): a CUDA host runs DBS-TIGER unless asked otherwise, so the Workflows page's+ // install commands fetch it and its presence check names it when it's missing.+ requiredModels: ['DBS-BSRNN-DnR/model.safetensors', 'DBS-BSRNN-DnR/config.json', 'DBS-TIGER-DnR/model.safetensors', 'DBS-TIGER-DnR/config.json'],bindings: { audio: [b('1', 'audio')], separationModel: [b('2', 'model')], channels: [b('3', 'channels')] },outputs: [{ node: '5', kind: 'audio', stem: 'voice' },@@ -2407,11 +2409,14 @@ export const SPEC = ['CPU OK, about 1.7 GiB on CUDA. audio = an audio file or a video (LoadAudio reads a video\'s soundtrack without decoding frames). ' +'DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 3x slower on a CPU, the CUDA default); device auto. ' +'Measured on a 4-CPU host (torch 2.14.1+cpu, 10-20 s clips): DBS-BSRNN 0.17-0.33x real time per channel, DBS-TIGER 0.08-0.09x. ' +- 'DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (every channel separated on its own: 2x the time for stereo, 6x for 5.1; ' +- 'the provider forces it for inputs with more than 2 channels, where the subtract below would also take speech out of the LFE and surrounds); output_sample_rate input. ' ++ 'DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (stereo stems: every channel separated on its own, 2x the time); output_sample_rate input. ' ++ 'ComfyUI saves audio as mono or stereo only (a 5.1 waveform comes out as scrambled stereo three times as long), so the provider splits a file with more than 2 channels in mono ' ++ 'and makes its background from music + effects (node 4 rewired to AudioMerge add) rather than the original minus the speech. ' +'Outputs in order: voice (speech), music, effects (sfx), background = original minus speech (AudioMerge subtract: with mono it keeps the original stereo image at mono cost; ' +'AudioMerge scales the whole result down when it peaks over 1.0), and the pack\'s JSON report (model, device, rates, windows, seconds, times real time). ' +- 'Stems are FLAC, so they still add up to the source. Voice is first, so a chain without a stem takes the dialogue. Trained on synthetic English mixes (DnR v2): dialogue separates well (15-16 dB), music against effects less so (5.7-7.8 dB).',+ 'Voice + background add up to the source, except on a loud master where AudioMerge had to lower the background to fit under full scale (FLAC holds no more). ' ++ 'Voice is first, so a chain without a stem takes the dialogue. Trained on synthetic English mixes (DnR v2): dialogue separates well (15-16 dB), music against effects less so (5.7-7.8 dB). ' ++ 'Some FSD50K and FMA clips inside DnR v2 carry their own CC licences, NC variants included; whether that reaches the weights or their outputs is unresolved (recorded as information).',},{id: 'captions-qwen3-asr',diff --git a/src/app/api/audio-tools/export/route.ts b/src/app/api/audio-tools/export/route.tsnew file mode 100644index 00000000..6ea5a9b3--- /dev/null+++ b/src/app/api/audio-tools/export/route.ts@@ -0,0 +1,21 @@+import { MixExportError, PART_MAX, receiveMixPart } from "@/server/mix-export";++/**+ * Split soundtrack's Export mix, in parts: POST the WAV's bytes as the body, `?offset=` where they start, `&id=` from+ * the first part's answer, `&last=1&name=` on the last part, which answers with the Library asset (201).+ */+export async function POST(request: Request) {+ const q = new URL(request.url).searchParams;+ const offset = Number(q.get("offset") ?? "0");+ if (!Number.isSafeInteger(offset) || offset < 0) return Response.json({ error: "Say where the part starts (offset)" }, { status: 400 });+ if (Number(request.headers.get("content-length")) > PART_MAX) return Response.json({ error: "That part is too large" }, { status: 413 });+ const data = Buffer.from(await request.arrayBuffer());+ try {+ const r = receiveMixPart({ id: q.get("id"), offset, data, last: q.get("last") === "1", name: q.get("name") });+ return Response.json(r, { status: "relPath" in r ? 201 : 200 });+ } catch (e) {+ if (e instanceof MixExportError) return Response.json({ error: e.message }, { status: e.status });+ console.error("[audio-tools/export]", e);+ return Response.json({ error: (e as Error).message || "Couldn't save the mix" }, { status: 500 });+ }+}diff --git a/src/lib/av/audio-tools.ts b/src/lib/av/audio-tools.tsindex 74620303..830be530 100644--- a/src/lib/av/audio-tools.ts+++ b/src/lib/av/audio-tools.ts@@ -62,6 +62,10 @@ export interface AudioToolPreview {hostPick?: "fast" | "best";/** The ComfyUI host's device type ("cpu", "cuda"…), when it said. */device?: string;+ /** The DBS models the host has on disk, when it said (the page marks one that isn't there). */+ installed?: ("fast" | "best")[];+ /** The file's channel count from its header, when the server could read it (the page then needn't decode the file). */+ channels?: number;}export interface LoopInput {diff --git a/src/lib/av/split.ts b/src/lib/av/split.tsindex 87399622..465d83cd 100644--- a/src/lib/av/split.ts+++ b/src/lib/av/split.ts@@ -42,34 +42,90 @@ export const QUALITY_LABELS: Record<SplitQuality, string> = {};export type DbsChannels = "mono" | "each channel";+/**+ * The DBS models a host has on disk, from GET /models/dbs (paths under the folder; a Windows ComfyUI lists them with+ * back slashes): both files of a model, or it isn't there. Undefined when the host can't say (no list).+ */+export function installedDbs(files: readonly string[] | null | undefined): DbsModel[] | undefined {+ if (!files) return undefined;+ const have = new Set(files.map((f) => f.replace(/\\/g, "/")));+ return Object.values(DBS_MODELS).filter((m) => have.has(`${m}/model.safetensors`) && have.has(`${m}/config.json`));+}++const qualityOf = (m: DbsModel): SplitQuality => (m === DBS_MODELS.best ? "best" : "fast");+/*** The model a host does best with: DBS-TIGER (10.13 dB) on a CUDA GPU, where both run well over 10x real time- * (ROCm reports "cuda" too); DBS-BSRNN (9.07 dB) on a CPU, where it runs about 4x faster than DBS-TIGER.+ * (ROCm reports "cuda" too); DBS-BSRNN (9.07 dB) on a CPU, where it runs about 3x faster than DBS-TIGER (§2.4). When+ * the host's list of DBS models is known and its pick isn't on disk, the other one if that is.*/-export function hostPick(deviceType?: string | null): SplitQuality {- return deviceType === "cuda" ? "best" : "fast";+export function hostPick(deviceType?: string | null, installed?: readonly DbsModel[]): SplitQuality {+ const want: SplitQuality = deviceType === "cuda" ? "best" : "fast";+ if (!installed || installed.includes(DBS_MODELS[want])) return want;+ const other: SplitQuality = want === "best" ? "fast" : "best";+ return installed.includes(DBS_MODELS[other]) ? other : want;}-/** The DBSLoader model a run gets: the one asked for ("fast" / "best" or the model's name), else the host's pick. */-export function dbsModelFor(asked: unknown, deviceType?: string | null): DbsModel {- if (asked === "DBS-BSRNN-DnR" || asked === "DBS-TIGER-DnR") return asked;- if (asked === "fast" || asked === "best") return DBS_MODELS[asked];- return DBS_MODELS[hostPick(deviceType)];+/** Why a DBS model can't run on this host: its files aren't in models/dbs. */+export function missingDbs(model: DbsModel, installed: readonly DbsModel[]): string {+ const q = qualityOf(model);+ const other = installed.find((m) => m !== model);+ return `${QUALITY_LABELS[q]} isn't installed on your ComfyUI (models/dbs/${model}). Copy the install commands from Workflows → "Split a soundtrack"${other ? `, or pick ${QUALITY_LABELS[qualityOf(other)]}` : ""}.`;+}++/**+ * The DBSLoader model a run gets: the one asked for ("fast" / "best" or the model's name), else the host's pick. With+ * the host's list of DBS models known, a model it doesn't have is refused here, in words, rather than failing inside+ * ComfyUI.+ */+export function dbsModelFor(asked: unknown, deviceType?: string | null, installed?: readonly DbsModel[]): DbsModel {+ const named: DbsModel | undefined = asked === "DBS-BSRNN-DnR" || asked === "DBS-TIGER-DnR" ? asked : asked === "fast" || asked === "best" ? DBS_MODELS[asked] : undefined;+ const model = named ?? DBS_MODELS[hostPick(deviceType, installed)];+ if (installed && !installed.includes(model)) throw new Error(missingDbs(model, installed));+ return model;}+/**+ * ComfyUI saves audio (SaveAudioAdvanced, comfy_api's AudioSaveHelper) as mono or stereo only: a waveform with more+ * channels is written as "stereo" with its samples interleaved as if it had two, so a 4 s 5.1 stem comes out as 12 s+ * of scrambled stereo (seen on the worker). A file with more channels is therefore split in mono.+ */+export const SAVE_MAX_CHANNELS = 2;++/** A source with more channels than ComfyUI can save (5.1, 7.1): split in mono, with a mono Music & effects. */+export const surroundSource = (channels?: number | null): boolean => typeof channels === "number" && channels > SAVE_MAX_CHANNELS;+/*** DBSSeparate's channel mode: "mono" (the mean of the channels, the official usage) unless stereo stems are asked- * for; always "each channel" for more than 2 channels, where the background (original minus the mono speech) would- * also take speech out of the LFE and surround channels.+ * for. A mono file is one pass either way, and a file with more than 2 channels is split in mono too: ComfyUI can't save+ * its channels (SAVE_MAX_CHANNELS), and its background is then made from the music and effects stems (dbsSurroundBed),+ * not the original minus the speech, which would keep all its channels.*/export function dbsChannelsFor(asked: unknown, channels?: number | null): DbsChannels {- if (typeof channels === "number" && channels > 2) return "each channel";+ if (channels === 1 || surroundSource(channels)) return "mono";return asked === "each channel" || asked === "stereo" || asked === true ? "each channel" : "mono";}-/** How many times the model runs over the clip: once in mono, once per channel otherwise. */+type GraphNode = { class_type: string; inputs: Record<string, unknown> };+const linkedTo = (v: unknown, node: string, slot: number) => Array.isArray(v) && v[0] === node && v[1] === slot;++/**+ * Graph A's background for a surround source: the music and effects stems added up (AudioMerge add, mono) in place of+ * the original minus the speech (which has the source's 6 or 8 channels, more than ComfyUI can save). The graph as it is+ * when it has no DBSSeparate or no such merge.+ */+export function dbsSurroundBed<T extends Record<string, GraphNode>>(wf: T): T {+ const dbs = Object.keys(wf).find((k) => wf[k].class_type === "DBSSeparate");+ if (!dbs) return wf;+ const merge = Object.keys(wf).find((k) => wf[k].class_type === "AudioMerge" && linkedTo(wf[k].inputs.audio2, dbs, 2) && wf[k].inputs.merge_method === "subtract");+ if (!merge) return wf;+ // DBSSeparate's outputs: 0 music, 1 sfx, 2 speech, 3 report.+ return { ...wf, [merge]: { ...wf[merge], inputs: { ...wf[merge].inputs, audio1: [dbs, 0], audio2: [dbs, 1], merge_method: "add" } } };+}++/** How many times the model runs over the clip: once in mono, once per channel otherwise (stereo when unknown). */export function separationPasses(mode: DbsChannels, channels?: number | null): number {- return mode === "mono" ? 1 : Math.max(2, Math.round(channels ?? 2));+ return mode === "mono" ? 1 : Math.max(1, Math.round(channels ?? 2));}// ---------------------------------------------------------------------------@@ -164,7 +220,7 @@ export function planSplit(i: SplitInput): SplitPlan {},step: { label: STEP_LABEL[mode], index: 0, of: 1 },};- const forced = mode === "each channel" && !i.stereo;+ const surround = surroundSource(i.channels);const passes = separationPasses(mode, i.channels);return {steps: [{ key: "split", request }],@@ -173,7 +229,7 @@ export function planSplit(i: SplitInput): SplitPlan {mode,summary: `Splits ${i.kind === "video" ? "the video's soundtrack" : "it"} into dialogue, music, effects and music & effects${mode === "each channel" ? `, every channel on its own (${passes} passes)` : ""}.`,notes: [- ...(forced ? [`This file has ${i.channels} channels, so each is split on its own: about ${passes}x the time.`] : []),+ ...(surround ? [`This file has ${i.channels} channels. ComfyUI saves audio in mono or stereo only, so the stems come out in mono (all channels mixed), and Music & effects is the music and effects stems added up.`] : []),"Dialogue comes out clean; music and effects can bleed into each other.",],};@@ -238,8 +294,11 @@ const on = (db = 0): StemMix => ({ db, mute: false, solo: false });const off = (db = 0): StemMix => ({ db, mute: true, solo: false });/**- * The original back: dialogue plus music & effects (they sum to the source exactly). The separate music and effects- * stems start muted, so nothing plays twice.+ * The original back: dialogue plus music & effects, which the graph makes as the source minus the dialogue, so the two+ * add up to the source. Except on a loud master: where the source minus the dialogue goes over full scale, ComfyUI's+ * AudioMerge lowers the whole background stem to fit (FLAC can't hold more), and this plays the background that much+ * quieter (backgroundLowered says when; the mixer says so). The separate music and effects stems start muted, so+ * nothing plays twice.*/export const ORIGINAL_MIX: Mix = {voice: on(),@@ -278,6 +337,15 @@ export function presetOf(mix: Mix): string | null {return PRESETS.find((p) => STEMS.every((s) => same(mix[s.id], p.mix[s.id])))?.id ?? null;}+/**+ * A background stem that peaks at full scale was lowered by AudioMerge (it divides the whole stem by its peak when the+ * source minus the dialogue goes over 1.0), so dialogue plus music & effects is a little quieter than the source in the+ * background. A stem that was left alone peaks under full scale, but for the rare one that lands on it exactly.+ */+export function backgroundLowered(peak: number): boolean {+ return peak >= 0.999;+}+export const clampDb = (db: number): number => Math.min(LEVEL_MAX, Math.max(LEVEL_MIN, Math.round(db * 2) / 2));/** A level in dB as a gain (0 dB = 1, −6 dB ≈ 0.5, +6 dB ≈ 2). */@@ -331,7 +399,11 @@ export function mixName(mix: Mix): string {}// ----------------------------------------------------------------------------// Export: the rendered mix as a WAV file+// Export: the mix as a WAV file, made and uploaded in parts++/** A WAV holds at most 4 GiB (32-bit sizes); the export route takes up to 2 GiB, in parts the sign-in proxy passes whole. */+export const MIX_MAX_BYTES = 2 * 1024 ** 3;+export const MIX_PART_BYTES = 16 * 1024 * 1024;/*** The gain that keeps a mix from clipping: 1 when its peak is at or under full scale, else just enough to bring the@@ -342,15 +414,17 @@ export function headroomGain(peak: number): number {return peak > ceiling ? ceiling / peak : 1;}-/** 16-bit PCM WAV from planar float channels (−1…1, clipped), as the export uploads it. */-export function encodeWav(channels: Float32Array[], sampleRate: number): Uint8Array {- const n = channels.length ? channels[0].length : 0;- const ch = Math.max(1, channels.length);- const bytes = new Uint8Array(44 + n * ch * 2);+/** The size of a 16-bit PCM WAV. */+export const wavBytes = (frames: number, channels: number): number => 44 + frames * Math.max(1, channels) * 2;++/** The 44-byte header of a 16-bit PCM WAV of `frames` frames. */+export function wavHeader(frames: number, channels: number, sampleRate: number): Uint8Array {+ const ch = Math.max(1, channels);+ const bytes = new Uint8Array(44);const d = new DataView(bytes.buffer);const text = (o: number, s: string) => [...s].forEach((c, k) => d.setUint8(o + k, c.charCodeAt(0)));text(0, "RIFF");- d.setUint32(4, 36 + n * ch * 2, true);+ d.setUint32(4, 36 + frames * ch * 2, true);text(8, "WAVE");text(12, "fmt ");d.setUint32(16, 16, true);@@ -361,13 +435,128 @@ export function encodeWav(channels: Float32Array[], sampleRate: number): Uint8Ard.setUint16(32, ch * 2, true);d.setUint16(34, 16, true);text(36, "data");- d.setUint32(40, n * ch * 2, true);- for (let i = 0, o = 44; i < n; i++)- for (let c = 0; c < ch; c++, o += 2) {- const v = Math.max(-1, Math.min(1, channels[c]?.[i] ?? 0));- d.setInt16(o, Math.round(v < 0 ? v * 0x8000 : v * 0x7fff), true);- }+ d.setUint32(40, frames * ch * 2, true);+ return bytes;+}++const int16 = (v: number) => {+ const c = Math.max(-1, Math.min(1, v));+ return Math.round(c < 0 ? c * 0x8000 : c * 0x7fff);+};++/** 16-bit PCM WAV from planar float channels (−1…1, clipped). */+export function encodeWav(channels: Float32Array[], sampleRate: number): Uint8Array {+ const n = channels.length ? channels[0].length : 0;+ const ch = Math.max(1, channels.length);+ const bytes = new Uint8Array(wavBytes(n, ch));+ bytes.set(wavHeader(n, ch, sampleRate));+ const d = new DataView(bytes.buffer);+ for (let i = 0, o = 44; i < n; i++) for (let c = 0; c < ch; c++, o += 2) d.setInt16(o, int16(channels[c]?.[i] ?? 0), true);return bytes;}+/** A decoded stem in a mix: its planar channels (one rate for all stems) and the gain it plays at. */+export interface MixStem {+ channels: Float32Array[];+ gain: number;+}++/**+ * Which channel of a stem with `n` channels feeds output channel `c` of `out` (−1: none), as WebAudio's "speakers"+ * up-mix plays it live: mono into stereo or quad on left and right, into 5.1 on the centre; otherwise channel for+ * channel. (A split's stems are either all one channel count, or mono beside a stereo background.)+ */+export function stemFeed(n: number, out: number, c: number): number {+ if (n === 1) return out === 6 ? (c === 2 ? 0 : -1) : out === 2 || out === 4 ? (c < 2 ? 0 : -1) : c === 0 ? 0 : -1;+ return c < n ? c : -1;+}++/** A mix ready to write: the audible stems, which of their channels feed each output channel, and the file's shape. */+export interface MixPlan {+ stems: MixStem[];+ feeds: number[][];+ frames: number;+ channels: number;+ sampleRate: number;+ /** The whole WAV's size. */+ bytes: number;+}++export function mixPlan(all: MixStem[], sampleRate: number): MixPlan {+ const stems = all.filter((s) => s.gain > 0 && s.channels.length > 0);+ const channels = Math.max(1, ...all.map((s) => s.channels.length));+ const frames = Math.max(0, ...all.flatMap((s) => s.channels.map((d) => d.length)));+ const feeds = stems.map((s) => Array.from({ length: channels }, (_, c) => stemFeed(s.channels.length, channels, c)));+ return { stems, feeds, frames, channels, sampleRate, bytes: wavBytes(frames, channels) };+}++/** One sample of the mix: every audible stem at its gain. */+function mixAt(p: MixPlan, c: number, i: number): number {+ let v = 0;+ for (let s = 0; s < p.stems.length; s++) {+ const k = p.feeds[s][c];+ if (k < 0) continue;+ const data = p.stems[s].channels[k];+ if (i < data.length) v += data[i] * p.stems[s].gain;+ }+ return v;+}++/** The loudest sample of the mix in frames [from, to) (the page looks at it a slice at a time, so it stays responsive). */+export function mixPeak(p: MixPlan, from = 0, to = p.frames): number {+ let peak = 0;+ for (let i = from, end = Math.min(to, p.frames); i < end; i++) for (let c = 0; c < p.channels; c++) peak = Math.max(peak, Math.abs(mixAt(p, c, i)));+ return peak;+}++/** Frames per part of about `partBytes`. */+export const partFrames = (p: MixPlan, partBytes = MIX_PART_BYTES): number => Math.max(1, Math.floor(partBytes / (p.channels * 2)));++/**+ * Frames [from, to) of the mix as 16-bit PCM at gain `k` (headroomGain of the whole mix's peak); the part that starts+ * at frame 0 carries the WAV header. Parts in order, joined, are the WAV file.+ */+export function mixPart(p: MixPlan, from: number, to: number, k = 1): Uint8Array {+ const n = Math.max(0, Math.min(to, p.frames) - from);+ const head = from === 0 ? 44 : 0;+ const out = new Uint8Array(head + n * p.channels * 2);+ if (head) out.set(wavHeader(p.frames, p.channels, p.sampleRate));+ const d = new DataView(out.buffer);+ for (let i = 0, o = head; i < n; i++) for (let c = 0; c < p.channels; c++, o += 2) d.setInt16(o, int16(mixAt(p, c, from + i) * k), true);+ return out;+}++// ---------------------------------------------------------------------------+// What the browser can hold++const GiB = 1024 ** 3;++/** Bytes the browser holds to mix a split: every stem decoded as 32-bit float at the audio context's rate. */+export function mixerBytes(stems: { seconds: number; channels: number }[], sampleRate: number): number {+ return stems.reduce((n, s) => n + Math.ceil(Math.max(0, s.seconds) * sampleRate) * Math.max(1, s.channels) * 4, 0);+}++/**+ * How much decoded audio this browser is trusted with: a quarter of the device's memory where the browser says it+ * (Chrome, at most 8 GB reported), from 512 MiB to 2 GiB; else 1 GiB on a phone or tablet and 2 GiB on a computer.+ */+export function mixerBudget(o: { deviceMemoryGb?: number; coarse?: boolean }): number {+ if (o.deviceMemoryGb && o.deviceMemoryGb > 0) return Math.min(2 * GiB, Math.max(GiB / 2, (o.deviceMemoryGb * GiB) / 4));+ return o.coarse ? GiB : 2 * GiB;+}++const sizeWords = (bytes: number) => (bytes >= GiB ? `${Math.round((bytes / GiB) * 10) / 10} GB` : `${Math.max(1, Math.round(bytes / 1024 ** 2))} MB`);++/** Why the browser shouldn't decode these stems (too long for this device), or null. */+export function mixerProblem(bytes: number, budget: number): string | null {+ if (bytes <= budget) return null;+ return `This split is too long to mix in your browser: its stems take about ${sizeWords(bytes)} of memory to play, and this device has room for about ${sizeWords(budget)}. Download the stems and mix them in an editor, or split a shorter clip.`;+}++/** Why a mix can't be exported as one WAV (over the export's limit), or null. */+export function exportProblem(frames: number, channels: number): string | null {+ const bytes = wavBytes(frames, channels);+ return bytes > MIX_MAX_BYTES ? `This mix would be a ${sizeWords(bytes)} WAV, over the ${sizeWords(MIX_MAX_BYTES)} an export can be. Download the stems and mix them in an editor.` : null;+}+export { clock };diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 041679b0..84feb777 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1138,7 +1138,7 @@ const open: ModelDef[] = [}),// DBS (docs/research/dbs-separation-7.md): dialogue, music and effects from any soundtrack, small enough for a CPU. The// provider picks the model by the host (DBS-TIGER on CUDA, DBS-BSRNN otherwise) unless one is asked for, and separates- // every channel on its own for inputs with more than 2 channels. Split soundtrack (src/lib/av/split.ts) runs on it.+ // a file with more than 2 channels in mono (ComfyUI saves mono or stereo only). Split soundtrack (src/lib/av/split.ts) runs on it.o({id: "oss-dbs-separate",name: "DBS (dialogue, music, effects)",diff --git a/src/lib/licences.ts b/src/lib/licences.tsindex 4ce9d933..a0b10eb5 100644--- a/src/lib/licences.ts+++ b/src/lib/licences.ts@@ -436,7 +436,7 @@ export const NODE_PACKS: NodePack[] = [name: "MIT",class: "commercial",url: SPDX("MIT"),- note: "Dialogue / music / effects separation; MIT code, vendored DBS code Apache-2.0 with MIT notices; the DBS weights are Apache-2.0, trained on DnR v2 (CC BY 4.0)",+ note: "Dialogue / music / effects separation; MIT code, vendored DBS code Apache-2.0 with MIT notices; the DBS weights are Apache-2.0, trained on DnR v2 (CC BY 4.0). Some FSD50K and FMA clips inside DnR v2 carry their own CC licences, NC variants included; whether that reaches the weights or their outputs is unresolved",}),];@@ -453,6 +453,8 @@ export interface Attribution {text: string;licence: string;url?: string;+ /** What the admin should also know (an open licence question), shown under the credit. */+ note?: string;}export const ATTRIBUTIONS: Attribution[] = [@@ -461,6 +463,7 @@ export const ATTRIBUTIONS: Attribution[] = [text: "Trained on the Divide and Remaster (DnR) v2 dataset by Darius Petermann, Gordon Wichern, Zhong-Qiu Wang and Jonathan Le Roux",licence: "CC BY 4.0",url: "https://zenodo.org/records/6949108",+ note: "Some FSD50K and FMA clips inside DnR v2 carry their own CC licences, NC variants included. Whether that reaches the DBS weights or what they make is unresolved: recorded here as information.",},{ for: "DBS (vendored code)", text: "BS-RoFormer, copyright (c) 2023 Phil Wang", licence: "MIT", url: "https://github.com/lucidrains/BS-RoFormer" },{ for: "DBS (vendored code)", text: "Music-Source-Separation-Training, copyright (c) 2024 Roman Solovyev (ZFTurbo)", licence: "MIT", url: "https://github.com/ZFTurbo/Music-Source-Separation-Training" },diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.tsindex d9ab6c1f..5307f319 100644--- a/src/lib/media-probe.ts+++ b/src/lib/media-probe.ts@@ -1,7 +1,8 @@/*** Just enough of the common media containers to know a file's shape before a job runs: duration, displayed- * size, frame rate / count and which tracks it has. 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.+ * 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.*/export interface MediaInfo {/**@@ -20,24 +21,35 @@ export interface MediaInfo {frames?: number;hasVideo: boolean;hasAudio: boolean;- /** Audio channels, where the header says (WAV, FLAC, MP3); unset for MP4 and the rest. */+ /**+ * Audio channels, where the header says: WAV, FLAC, MP3, 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;}const fourcc = (b: Uint8Array, o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);-export function probeMedia(data: Uint8Array): MediaInfo | null {+/**+ * The facts in `data`: a whole file, or (`size` = the whole file's length) the start of a WAV, FLAC or MP3, whose+ * header says all of it.+ */+export function probeMedia(data: Uint8Array, size = data.length): MediaInfo | null {try {if (data.length < 12) return null;- if (fourcc(data, 0) === "RIFF" && fourcc(data, 8) === "WAVE") return probeWav(data);+ if (fourcc(data, 0) === "RIFF" && fourcc(data, 8) === "WAVE") return probeWav(data, size);if (fourcc(data, 0) === "fLaC") return probeFlac(data);if (fourcc(data, 4) === "ftyp" || ["moov", "mdat", "free", "wide", "skip"].includes(fourcc(data, 4))) return probeIsoBmff(data);- return probeMp3(data);+ return probeMp3(data, size);} catch {return null;}}+/** A WAV, FLAC or MP3 (an ID3 tag or a frame at the very start): its header at the start says what the file is. */+const headerSays = (head: Uint8Array) =>+ (fourcc(head, 0) === "RIFF" && fourcc(head, 8) === "WAVE") || fourcc(head, 0) === "fLaC" || fourcc(head, 0).startsWith("ID3") || (head[0] === 0xff && (head[1] & 0xe0) === 0xe0);+// ---------------------------------------------------------------------------// Probing a file without reading all of it@@ -51,14 +63,14 @@ const ISO_TOP = ["ftyp", "moov", "mdat", "free", "wide", "skip"];/*** {@link probeMedia} without reading the whole file: an MP4 / MOV is walked box header by box header* to its moov box (at the start, or after the media data like a camera file) and only that is read,- * so a 200 MB clip costs a few small reads. Other containers are probed when the whole file fits in- * the first read, else unknown (null).+ * so a 200 MB clip costs a few small reads. A WAV, FLAC or MP3 is read from its header (the first read);+ * other containers are probed when the whole file fits in the first read, else unknown (null).*/export async function probeMediaRanges(read: ReadRange, size: number): Promise<MediaInfo | null> {try {const head = await read(0, Math.min(size, HEAD_BYTES));if (head.length < 12) return null;- if (!ISO_TOP.includes(fourcc(head, 4))) return size <= head.length ? probeMedia(head) : null;+ if (!ISO_TOP.includes(fourcc(head, 4))) return size <= head.length ? probeMedia(head) : headerSays(head) ? probeMedia(head, size) : null;for (let o = 0; o + 8 <= size; ) {const h = o + 16 <= head.length ? head.subarray(o, o + 16) : await read(o, Math.min(size, o + 16));if (h.length < 8) return null;@@ -146,6 +158,65 @@ function timing(d: DataView, b: Box): [number, number] {return [d.getUint32(b.start + 12), d.getUint32(b.start + 16)];}+/**+ * A sound track's channel count from its first sample entry (stsd): an AAC track's AudioSpecificConfig (esds) when it+ * names a layout, else the entry's channelcount (QuickTime version 2 entries keep the real count further on); 0 when+ * none says.+ */+function soundChannels(d: DataView, stsd: Box): number {+ const entry = boxes(d, stsd.start + 8, stsd.end).next().value;+ // SampleEntry (6 reserved, data reference index) then version, revision, vendor, channelcount.+ if (!entry || entry.start + 28 > entry.end) return 0;+ const version = d.getUint16(entry.start + 8);+ let channels = version === 2 && entry.start + 44 <= entry.end ? d.getUint32(entry.start + 40) : d.getUint16(entry.start + 16);+ if (entry.type === "mp4a") {+ const extra = version === 1 ? 16 : version === 2 ? 36 : 0;+ for (const b of boxes(d, entry.start + 28 + extra, entry.end)) if (b.type === "esds") channels = aacChannels(d, b) || channels;+ }+ return channels > 0 && channels <= 64 ? channels : 0;+}++/** An esds box's AudioSpecificConfig channelConfiguration as a count (1–6, 7 = 7.1 = 8 channels); 0 when it doesn't say. */+function aacChannels(d: DataView, esds: Box): number {+ let o = esds.start + 4; // version + flags+ // A descriptor: tag, then a size of 1–4 bytes (7 bits each).+ const descriptor = (tag: number): number | null => {+ if (o + 2 > esds.end || d.getUint8(o) !== tag) return null;+ o++;+ let size = 0;+ for (let i = 0; i < 4 && o < esds.end; i++) {+ const b = d.getUint8(o++);+ size = (size << 7) | (b & 0x7f);+ if (!(b & 0x80)) break;+ }+ return size;+ };+ if (descriptor(0x03) === null || o + 3 > esds.end) return 0; // ES_Descriptor+ const flags = d.getUint8(o + 2);+ o += 3;+ if (flags & 0x80) o += 2; // dependsOn_ES_ID+ if (flags & 0x40 && o < esds.end) o += 1 + d.getUint8(o); // URL+ if (flags & 0x20) o += 2; // OCR_ES_Id+ if (descriptor(0x04) === null) return 0; // DecoderConfigDescriptor+ o += 13;+ if (descriptor(0x05) === null || o + 2 > esds.end) return 0; // DecoderSpecificInfo = AudioSpecificConfig+ // audioObjectType (5 bits; 31 = escape, 6 more), samplingFrequencyIndex (4; 15 = 24 more), channelConfiguration (4).+ let pos = 0;+ const take = (n: number) => {+ let v = 0;+ for (let i = 0; i < n; i++, pos++) {+ const at = o + (pos >> 3);+ if (at >= esds.end) return -1;+ v = (v << 1) | ((d.getUint8(at) >> (7 - (pos & 7))) & 1);+ }+ return v;+ };+ if (take(5) === 31) take(6);+ if (take(4) === 15) take(24);+ const layout = take(4);+ return layout >= 1 && layout <= 6 ? layout : layout === 7 ? 8 : 0;+}+function probeIsoBmff(data: Uint8Array): MediaInfo | null {const d = new DataView(data.buffer, data.byteOffset, data.byteLength);let moov: Box | undefined;@@ -162,7 +233,13 @@ function probeIsoBmff(data: Uint8Array): MediaInfo | null {const mdia = child(d, trak, "mdia");const hdlr = mdia && child(d, mdia, "hdlr");const handler = hdlr ? fourcc(data, hdlr.start + 8) : "";- if (handler === "soun") info.hasAudio = true;+ if (handler === "soun" && !info.hasAudio) {+ info.hasAudio = true;+ const minf = mdia && child(d, mdia, "minf");+ const stsd = minf && child(d, minf, "stbl") && child(d, child(d, minf, "stbl")!, "stsd");+ const channels = stsd ? soundChannels(d, stsd) : 0;+ if (channels > 0) info.channels = channels;+ }if (handler !== "vide" || info.hasVideo) continue;info.hasVideo = true;const tkhd = child(d, trak, "tkhd");@@ -200,7 +277,7 @@ function probeIsoBmff(data: Uint8Array): MediaInfo | null {// ---------------------------------------------------------------------------// WAV, FLAC, MP3-function probeWav(data: Uint8Array): MediaInfo | null {+function probeWav(data: Uint8Array, total: number): MediaInfo | null {const d = new DataView(data.buffer, data.byteOffset, data.byteLength);let byteRate = 0;let channels = 0;@@ -212,7 +289,7 @@ function probeWav(data: Uint8Array): MediaInfo | null {byteRate = d.getUint32(o + 16, true);}if (id === "data") {- if (!size || size === 0xffffffff || o + 8 + size > data.length) size = data.length - o - 8; // streamed header+ if (!size || size === 0xffffffff || o + 8 + size > total) size = total - o - 8; // streamed headerreturn byteRate ? { container: "wav", duration: size / byteRate, hasVideo: false, hasAudio: true, ...(channels > 0 && { channels }) } : null;}o += 8 + size + (size % 2);@@ -236,7 +313,7 @@ const MP3_BITRATES: Record<string, number[]> = {};const MP3_RATES: Record<number, number[]> = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] };-function probeMp3(data: Uint8Array): MediaInfo | null {+function probeMp3(data: Uint8Array, total: number): MediaInfo | null {let o = 0;if (fourcc(data, 0).startsWith("ID3")) o = 10 + ((data[6] & 0x7f) << 21) + ((data[7] & 0x7f) << 14) + ((data[8] & 0x7f) << 7) + (data[9] & 0x7f);// The first frame header within a few KB of the tag.@@ -258,5 +335,5 @@ function probeMp3(data: Uint8Array): MediaInfo | null {return { container: "mp3", duration: (frames * samplesPerFrame) / rate, hasVideo: false, hasAudio: true, channels: mono ? 1 : 2 };}if (!bitrate) return null;- return { container: "mp3", duration: ((data.length - o) * 8) / bitrate, hasVideo: false, hasAudio: true, channels: mono ? 1 : 2 };+ return { container: "mp3", duration: ((total - o) * 8) / bitrate, hasVideo: false, hasAudio: true, channels: mono ? 1 : 2 };}diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.tsindex c5d44c63..11810a4a 100644--- a/src/server/audio-tools.ts+++ b/src/server/audio-tools.ts@@ -2,12 +2,12 @@ import "server-only";import fs from "node:fs/promises";import { z } from "zod";import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";-import { CLOUD_ONLY_PROBLEM, dbsChannelsFor, hostPick, planRemux, planSplit, splitTime } from "@/lib/av/split";+import { CLOUD_ONLY_PROBLEM, DBS_MODELS, dbsChannelsFor, hostPick, missingDbs, planRemux, planSplit, splitTime } from "@/lib/av/split";import type { Engine, Generation } from "@/lib/catalog/types";-import { probeMedia } from "@/lib/media-probe";import { createPipeline } from "./chains";import { previewChained } from "./generations";-import { comfyDevice } from "./providers/comfyui";+import { fileInfo } from "./media-facts";+import { comfyDbsModels, comfyDevice } from "./providers/comfyui";import { engineMode } from "./settings";import { absolutePath } from "./storage";@@ -72,6 +72,8 @@ export class AudioToolError extends Error {}interface ClipFacts {duration?: number;channels?: number;+ /** False when the header says the file has no sound track (a silent video). */+ hasAudio?: boolean;}declare global {@@ -98,7 +100,10 @@ async function present(url: string, gone: string): Promise<void> {}}-/** A clip's length and channel count from its header (cached by file version), or null when the header says neither. */+/**+ * A clip's length, channel count and whether it has sound, from its header (cached by file version; read in ranges, so a+ * file of any size costs a few small reads), or null when no reader knows the file.+ */async function factsOf(url: string): Promise<ClipFacts | null> {let file: string;let key: string;@@ -111,21 +116,20 @@ async function factsOf(url: string): Promise<ClipFacts | null> {throw new AudioToolError("That audio file is gone — add it again");}if (!lengths.has(key)) {- let data: Buffer;+ let info: Awaited<ReturnType<typeof fileInfo>>;try {- data = await fs.readFile(file);+ info = await fileInfo(file);} catch {throw new AudioToolError("That audio file is gone — add it again");}- const info = probeMedia(data);if (lengths.size >= LENGTHS_KEPT) lengths.delete(lengths.keys().next().value!);const duration = info?.duration && info.duration > 0 ? Math.round(info.duration * 1000) / 1000 : undefined;- lengths.set(key, duration || info?.channels ? { ...(duration && { duration }), ...(info?.channels && { channels: info.channels }) } : null);+ lengths.set(key, info ? { ...(duration && { duration }), ...(info.channels && { channels: info.channels }), hasAudio: info.hasAudio } : null);}return lengths.get(key) ?? null;}-async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine; split?: ClipFacts }> {+async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine; split?: ClipFacts; headerChannels?: number }> {const mode = engineMode();// Split soundtrack runs on the open engine only: an install set to paid APIs only says why, whichever engine was asked for.if (body.tool === "split" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_PROBLEM);@@ -133,9 +137,11 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Enginetry {if (body.tool === "split") {const facts = await factsOf(body.media);+ // A clip made without sound (a silent text-to-video take): nothing to split, said before anything is queued.+ if (facts?.hasAudio === false) throw new AudioToolError(body.kind === "video" ? "This video has no sound to split" : "This file has no sound to split");const seconds = facts?.duration ?? body.sourceDuration;const channels = facts?.channels ?? body.channels;- return { engine: body.engine, ...planSplit({ ...body, seconds, channels }), split: { duration: seconds, channels } };+ return { engine: body.engine, ...planSplit({ ...body, seconds, channels }), split: { duration: seconds, channels }, headerChannels: facts?.channels };}if (body.tool === "remux") {await present(body.audio, "That mix is gone — export it again");@@ -170,11 +176,14 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToo}const out: AudioToolPreview = { summary: p.summary, notes: p.notes, length: p.length, steps: p.steps.length, costUsd: cost === null ? null : Math.round(cost * 1000) / 1000, demo };if (body.tool === "split") {- // How long it takes on this host: its device (asked once a minute), the model it would use and how many passes.- const device = demo ? undefined : await comfyDevice().catch(() => undefined);- const quality = body.quality ?? hostPick(device);+ // How long it takes on this host: its device (asked once a minute), the model it would use (one it has on disk) and+ // how many passes. A model the host doesn't have is refused here, before the run, with how to install it.+ const [device, installed] = demo ? [undefined, undefined] : await Promise.all([comfyDevice().catch(() => undefined), comfyDbsModels().catch(() => undefined)]);+ if (body.quality && installed && !installed.includes(DBS_MODELS[body.quality])) throw new AudioToolError(missingDbs(DBS_MODELS[body.quality], installed));+ const pick = hostPick(device, installed);+ const quality = body.quality ?? pick;const { duration: seconds, channels } = p.split ?? {};- Object.assign(out, { hostPick: hostPick(device), ...(device && { device }) });+ Object.assign(out, { hostPick: pick, ...(device && { device }), ...(installed && { installed: installed.map((m) => (m === DBS_MODELS.best ? "best" : "fast")) }), ...(p.headerChannels && { channels: p.headerChannels }) });if (seconds) out.estimate = splitTime({ seconds, quality, mode: dbsChannelsFor(body.stereo ? "each channel" : "mono", channels), channels, device });}return out;diff --git a/src/server/media-facts.ts b/src/server/media-facts.tsindex c7745cfb..eeadc201 100644--- a/src/server/media-facts.ts+++ b/src/server/media-facts.ts@@ -1,5 +1,6 @@import "server-only";-import { probeMedia } from "@/lib/media-probe";+import fs from "node:fs/promises";+import { probeMedia, probeMediaRanges, type MediaInfo } from "@/lib/media-probe";import { probeAvi } from "./avi-probe";import { probeWebm } from "./webm-probe";@@ -32,3 +33,32 @@ 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.+ */+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();+ }+}diff --git a/src/server/mix-export.ts b/src/server/mix-export.tsnew file mode 100644index 00000000..0e8f58e4--- /dev/null+++ b/src/server/mix-export.ts@@ -0,0 +1,109 @@+import "server-only";+import fs from "node:fs";+import path from "node:path";+import { nanoid } from "nanoid";+import { MIX_MAX_BYTES, MIX_PART_BYTES } from "@/lib/av/split";+import { adoptFile, scratchDir, type Asset } from "./storage";++/**+ * Split soundtrack's Export mix (and "Put back on the video", which exports first): the browser writes the mix as a+ * 16-bit WAV and sends it here in parts of MIX_PART_BYTES, which the sign-in proxy passes whole (it buffers at most+ * 210 MB of a body) and the server appends to a scratch file without holding the mix in memory. The first part starts+ * with the WAV header, which says how big the file will be (at most MIX_MAX_BYTES); the last one turns the file into an+ * upload in the Library. A 5.1 film clip's mix outgrows the 200 MB upload cap after about six minutes; this doesn't.+ */++export class MixExportError extends Error {+ constructor(+ message: string,+ readonly status = 400,+ ) {+ super(message);+ }+}++/** A part may be a little over MIX_PART_BYTES (the first one carries the header). */+export const PART_MAX = MIX_PART_BYTES + 1024 * 1024;+const ID = /^[A-Za-z0-9_-]{16}$/;+const PART_FILE = /^mix-[A-Za-z0-9_-]{16}\.wav\.part$/;+/** Exports nobody finished are removed when the next one starts. */+const STALE_MS = 6 * 60 * 60 * 1000;++const partPath = (id: string) => path.join(scratchDir(), `mix-${id}.wav.part`);++/** The file size a 16-bit PCM WAV header declares, or null when it isn't one. */+export function declaredWavBytes(head: Buffer): number | null {+ if (head.length < 44) return null;+ const tag = (o: number) => head.toString("latin1", o, o + 4);+ if (tag(0) !== "RIFF" || tag(8) !== "WAVE" || tag(12) !== "fmt " || head.readUInt16LE(20) !== 1 || head.readUInt16LE(34) !== 16) return null;+ return head.readUInt32LE(4) + 8;+}++function headOf(file: string): Buffer {+ const fd = fs.openSync(file, "r");+ try {+ const buf = Buffer.alloc(44);+ fs.readSync(fd, buf, 0, 44, 0);+ return buf;+ } finally {+ fs.closeSync(fd);+ }+}++function sweep() {+ const dir = scratchDir();+ for (const f of fs.readdirSync(dir)) {+ if (!PART_FILE.test(f)) continue;+ const abs = path.join(dir, f);+ try {+ if (Date.now() - fs.statSync(abs).mtimeMs > STALE_MS) fs.rmSync(abs, { force: true });+ } catch {}+ }+}++const mb = (bytes: number) => `${Math.round(bytes / 1024 ** 2)} MB`;++/**+ * One part of an export: the first (no `id`, offset 0) starts it; the others carry its `id` and the offset they start+ * at (the bytes received so far). Gives the export's id and the bytes received, or, for the `last` part, the Library+ * asset of the finished WAV.+ */+export function receiveMixPart(o: { id?: string | null; offset: number; data: Buffer; last: boolean; name?: string | null }): { id: string; received: number } | Asset {+ if (o.data.length > PART_MAX) throw new MixExportError(`A part can be at most ${mb(PART_MAX)}`, 413);+ let id = o.id ?? "";+ let file: string;+ let total: number;+ if (!id) {+ if (o.offset !== 0) throw new MixExportError("Start the export from its first part", 409);+ const declared = declaredWavBytes(o.data);+ if (declared === null) throw new MixExportError("An export is a 16-bit PCM WAV file", 415);+ if (declared > MIX_MAX_BYTES) throw new MixExportError(`That mix is over the ${mb(MIX_MAX_BYTES)} an export can be`, 413);+ total = declared;+ sweep();+ id = nanoid(16);+ file = partPath(id);+ fs.writeFileSync(file, o.data, { flag: "wx" });+ } else {+ if (!ID.test(id)) throw new MixExportError("That export doesn't exist", 404);+ file = partPath(id);+ let size: number;+ try {+ size = fs.statSync(file).size;+ } catch {+ throw new MixExportError("That export expired — export the mix again", 404);+ }+ if (o.offset !== size) throw new MixExportError(`That part doesn't follow on (the export has ${size} bytes)`, 409);+ total = declaredWavBytes(headOf(file)) ?? 0;+ if (size + o.data.length > total) throw new MixExportError("That's more audio than the WAV header says", 413);+ fs.appendFileSync(file, o.data);+ }+ const received = fs.statSync(file).size;+ if (received > total) {+ fs.rmSync(file, { force: true });+ throw new MixExportError("That's more audio than the WAV header says", 413);+ }+ if (!o.last) return { id, received };+ if (received !== total) throw new MixExportError(`The export stopped short (${received} of ${total} bytes) — export the mix again`, 409);+ const name = (o.name?.trim() || "Mix").slice(0, 196);+ return adoptFile({ from: file, contentType: "audio/wav", name: /\.wav$/i.test(name) ? name : `${name}.wav`, source: "upload" });+}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex c095c887..27863064 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -36,7 +36,7 @@ import {} from "@/lib/comfy";import { fpsPlan } from "@/lib/av/fps";import { crossfadeProblem, fadeCurveWav } from "@/lib/av/crossfade";-import { dbsChannelsFor, dbsModelFor } from "@/lib/av/split";+import { dbsChannelsFor, dbsModelFor, dbsSurroundBed, installedDbs, surroundSource, type DbsModel } from "@/lib/av/split";import { expandAudioJoinWorkflow, expandVideoJoinWorkflow } from "@/lib/av/joins";import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";import { exportValues, exrWorkflow, framesPerPass, hdrColorSpace, upscaleShortSide, wholeClipProblem, wholeClipTool } from "@/lib/av/video-finish";@@ -471,6 +471,28 @@ export async function comfyDevice(worker: ComfyWorker = "main"): Promise<stringreturn type;}+declare global {+ /** The DBS models each ComfyUI address listed last (GET /models/dbs), and when. */+ var __fuobeComfyDbs: Map<string, { models?: DbsModel[]; at: number }> | undefined;+}++/**+ * The DBS models the connected ComfyUI has on disk (GET /models/dbs, which ComfyUI-DBS registers: both files of a+ * model, or it isn't there), at most `maxAgeMs` old; undefined when the server can't say (unreachable, or the pack+ * isn't loaded, so there is no dbs folder).+ */+export async function comfyDbsModels(worker: ComfyWorker = "main", maxAgeMs = 10_000): Promise<DbsModel[] | undefined> {+ const url = baseUrl(worker);+ if (!url) return undefined;+ const cache = (globalThis.__fuobeComfyDbs ??= new Map());+ const hit = cache.get(url);+ if (hit && Date.now() - hit.at < maxAgeMs) return hit.models;+ const files = await comfyJson<unknown>("/models/dbs", worker).catch(() => undefined);+ const models = Array.isArray(files) ? installedDbs(files.filter((f): f is string => typeof f === "string")) : undefined;+ cache.set(url, { models, at: Date.now() });+ return models;+}+/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */export function comfyRam(): number | undefined {const cur = globalThis.__fuobeComfyReach;@@ -514,7 +536,7 @@ function webmInfo(data: Buffer): MediaInfo | null {const w = probeWebm(data);if (!w) return null;const frames = w.duration && w.fps ? Math.round(w.duration * w.fps) : undefined;- return { container: "webm", duration: w.duration, videoDuration: w.hasVideo ? w.duration : undefined, width: w.width, height: w.height, fps: w.fps, frames, hasVideo: w.hasVideo, hasAudio: w.hasAudio };+ return { container: "webm", duration: w.duration, videoDuration: w.hasVideo ? w.duration : undefined, width: w.width, height: w.height, fps: w.fps, frames, hasVideo: w.hasVideo, hasAudio: w.hasAudio, ...(w.channels && { channels: w.channels }) };}/** An AVI clip's header facts in MediaInfo's shape (src/server/avi-probe.ts; Character Swap Studio takes AVI). */@@ -619,6 +641,8 @@ export interface PrepareContext {serverRam?: () => Promise<number | undefined>;/** The server's first torch device type ("cuda", "cpu", "mps"…; GET /system_stats devices[0].type): DBS picks its model by it. */device?: () => Promise<string | undefined>;+ /** The DBS models on the server's disk (GET /models/dbs), undefined when it can't say: a run never gets one that isn't there. */+ dbsModels?: () => Promise<DbsModel[] | undefined>;/*** The route puts the run's one LoRA in the graph's own LoRA slot (ModelRoute.loraSlot: Fuobe Speak's FusioniX on kijai's* InfiniteTalk graph, with the settings it goes with). Without it a graph with no model loader refuses a LoRA.@@ -1108,9 +1132,19 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,const muted = manifest.id === "video-fit-clip" && extra.mute === true;delete extra.mute;// DBS (separate-soundtrack-dbs): the model asked for, else the host's pick (DBS-TIGER on a CUDA GPU, DBS-BSRNN on a- // CPU); "each channel" for stereo stems, and always for more than 2 channels (the header's count, else the browser's).- if (b.separationModel) values.separationModel = dbsModelFor(extra.separationModel, extra.separationModel ? undefined : await ctx.device?.().catch(() => undefined));- if (b.channels) values.channels = dbsChannelsFor(extra.channels, ctx.media?.(String(values.audio ?? ""))?.channels ?? (Number(extra.sourceChannels) || undefined));+ // CPU, the other one when the pick isn't on disk; a model that isn't there is refused in words); "each channel" for+ // stereo stems. A source with more than 2 channels (the header's count, else the browser's) is split in mono with a+ // mono Music & effects (dbsSurroundBed below): ComfyUI can't save more than 2 channels.+ if (b.separationModel) {+ const [device, installed] = await Promise.all([extra.separationModel ? undefined : ctx.device?.().catch(() => undefined), ctx.dbsModels?.().catch(() => undefined)]);+ try {+ values.separationModel = dbsModelFor(extra.separationModel, device, installed);+ } catch (e) {+ throw new ProviderError((e as Error).message, 400);+ }+ }+ const sourceChannels = b.channels ? (ctx.media?.(String(values.audio ?? ""))?.channels ?? (Number(extra.sourceChannels) || undefined)) : undefined;+ if (b.channels) values.channels = dbsChannelsFor(extra.channels, sourceChannels);for (const k of ["separationModel", "channels", "sourceChannels"]) delete extra[k];for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;if (audio2 && ctx.op !== "dialogue" && ctx.op !== "voice-change") values.audio2 = audio2;@@ -1183,6 +1217,7 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,const id = Object.keys(wf).find((k) => wf[k].class_type === "FrameInterpolate");if (id) wf = bypassNode(wf, id, "images", outputIds);}+ if (surroundSource(sourceChannels)) wf = dbsSurroundBed(wf);// Slow motion: the sound would no longer match the picture.if (finish.dropSound) for (const n of Object.values(wf)) if (n.class_type === "CreateVideo") delete n.inputs.audio;// VHS meta-batch: a manager of its own per job (a stale one loses frames), and no sound link for a silent clip.@@ -1391,6 +1426,8 @@ export const comfyProvider: ProviderAdapter = {media: mediaInfoFor,serverRam: async () => (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats", worker).catch(() => undefined))?.system?.ram_total,device: () => comfyDevice(worker),+ // Fresh: a model installed a moment ago runs.+ dbsModels: () => comfyDbsModels(worker, 0),});const { clientId } = ensureSocket(worker);const res = await comfyFetch(diff --git a/src/server/webm-probe.ts b/src/server/webm-probe.tsindex 1f90938f..a018f8a4 100644--- a/src/server/webm-probe.ts+++ b/src/server/webm-probe.ts@@ -5,7 +5,7 @@* one (the soundtrack step would fail after every restyle was paid for).** Reads the EBML elements up to the first Cluster: Segment → Info (TimecodeScale, Duration) and- * Tracks → TrackEntry (TrackType, DefaultDuration, Video → PixelWidth / PixelHeight). Pure.+ * Tracks → TrackEntry (TrackType, DefaultDuration, Video → PixelWidth / PixelHeight, Audio → Channels). Pure.*/export interface WebmInfo {@@ -15,6 +15,8 @@ export interface WebmInfo {fps?: number;hasAudio: boolean;hasVideo: boolean;+ /** The first sound track's channel count (Matroska's default is 1 when the Audio element doesn't say). */+ channels?: number;}const ID = {@@ -30,6 +32,8 @@ const ID = {Video: 0xe0,PixelWidth: 0xb0,PixelHeight: 0xba,+ Audio: 0xe1,+ Channels: 0x9f,Cluster: 0x1f43b675,} as const;@@ -104,7 +108,12 @@ export function probeWebm(buf: Buffer): WebmInfo | null {const fields = children(buf, track.start, track.end);const type = fields.find((f) => f.id === ID.TrackType);const kind = type ? uint(buf, type.start, type.end - type.start) : 0;- if (kind === 2) info.hasAudio = true;+ if (kind === 2 && !info.hasAudio) {+ info.hasAudio = true;+ const audio = fields.find((f) => f.id === ID.Audio);+ const count = audio ? children(buf, audio.start, audio.end).find((a) => a.id === ID.Channels) : undefined;+ info.channels = count ? uint(buf, count.start, count.end - count.start) || 1 : 1;+ }if (kind !== 1) continue;info.hasVideo = true;const frame = fields.find((f) => f.id === ID.DefaultDuration);diff --git a/tests/comfy-dbs.test.ts b/tests/comfy-dbs.test.tsindex 5ebf875d..dde520c5 100644--- a/tests/comfy-dbs.test.ts+++ b/tests/comfy-dbs.test.ts@@ -1,11 +1,12 @@import fs from "node:fs";import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { afterAll, describe, expect, it, vi } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest, ManifestWorkflow } from "@/lib/comfy";import { installScript, nodeInstall } from "@/lib/comfy-install";import { ATTRIBUTIONS, licenceInfo, nodePack, workflowLicence } from "@/lib/licences";+import type { DbsModel } from "@/lib/av/split";import type { MediaInfo } from "@/lib/media-probe";// DBS D1's ground on the open engine: the pinned pack and weights, graph A (separate-soundtrack-dbs) in the manifest,@@ -13,7 +14,7 @@ import type { MediaInfo } from "@/lib/media-probe";const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-dbs-"));process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";-const { collectOutputs, prepareWorkflow } = await import("@/server/providers/comfyui");+const { collectOutputs, comfyDbsModels, prepareWorkflow } = await import("@/server/providers/comfyui");afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const root = path.resolve(__dirname, "..");@@ -68,12 +69,12 @@ describe("separate-soundtrack-dbs in the manifest", () => {expect(graph["9"].inputs.source).toEqual(["3", 3]);});- it("lists the BSRNN pair as required and the TIGER pair as optional, under models/dbs, at pinned revisions", () => {+ it("lists both models as required (a CUDA host runs DBS-TIGER), under models/dbs, at pinned revisions", () => {expect(entry.models).toEqual([- { file: "DBS-BSRNN-DnR/model.safetensors", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/model.safetensors`, sizeGb: 0.019 },+ { file: "DBS-BSRNN-DnR/model.safetensors", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/model.safetensors`, sizeGb: 0.02 },{ file: "DBS-BSRNN-DnR/config.json", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/config.json`, sizeGb: 0 },- { file: "DBS-TIGER-DnR/model.safetensors", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/model.safetensors`, sizeGb: 0.004, optional: true },- { file: "DBS-TIGER-DnR/config.json", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/config.json`, sizeGb: 0, optional: true },+ { file: "DBS-TIGER-DnR/model.safetensors", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/model.safetensors`, sizeGb: 0.004 },+ { file: "DBS-TIGER-DnR/config.json", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/config.json`, sizeGb: 0 },]);expect(entry.customNodes).toEqual([{ name: "ComfyUI-DBS", repo: `https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/${PACK}` }]);});@@ -84,8 +85,9 @@ describe("separate-soundtrack-dbs in the manifest", () => {expect(script).toContain(`git -C "$COMFYUI/custom_nodes/ComfyUI-DBS" checkout -q ${PACK}`);expect(script).toContain(`mkdir -p "$COMFYUI/models/dbs/DBS-BSRNN-DnR" && wget -c -O "$COMFYUI/models/dbs/DBS-BSRNN-DnR/model.safetensors" "https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/model.safetensors"`);expect(script).toContain('"$COMFYUI/models/dbs/DBS-BSRNN-DnR/config.json"');- // TIGER is optional: named on the card, not installed by default.- expect(script).not.toContain("DBS-TIGER-DnR");+ // TIGER too: a GPU host set up from the Workflows page runs it by default, so its install fetches it.+ expect(script).toContain(`mkdir -p "$COMFYUI/models/dbs/DBS-TIGER-DnR" && wget -c -O "$COMFYUI/models/dbs/DBS-TIGER-DnR/model.safetensors" "https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/model.safetensors"`);+ expect(script).toContain('"$COMFYUI/models/dbs/DBS-TIGER-DnR/config.json"');});});@@ -123,14 +125,24 @@ describe("the library spec", async () => {expect(spec.CUSTOM_NODE_REPOS["ComfyUI-DBS"]).toBe(`https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/${PACK}`);expect(spec.KNOWN_MODELS["DBS-TIGER-DnR/model.safetensors"]).toEqual({ folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/model.safetensors` });const e = spec.SPEC.find((s: { id: string }) => s.id === "separate-soundtrack-dbs");- expect(e).toMatchObject({ packs: ["ComfyUI-DBS"], requiredModels: ["DBS-BSRNN-DnR/model.safetensors", "DBS-BSRNN-DnR/config.json"], optionalModels: ["DBS-TIGER-DnR/model.safetensors", "DBS-TIGER-DnR/config.json"] });+ expect(e).toMatchObject({ packs: ["ComfyUI-DBS"], requiredModels: ["DBS-BSRNN-DnR/model.safetensors", "DBS-BSRNN-DnR/config.json", "DBS-TIGER-DnR/model.safetensors", "DBS-TIGER-DnR/config.json"] });+ expect(e).not.toHaveProperty("optionalModels");expect(build.BINDING_KEYS.has("separationModel")).toBe(true);expect(build.BINDING_KEYS.has("channels")).toBe(true);});++ it("rounds sizes to two decimals, three only where two would read 0, so no other entry's size moves", () => {+ // film_net_fp16 (68,882,302 bytes) stays 0.07, as tests/video-finish.test.ts expects after a full rebuild.+ expect(build.gb(68_882_302)).toBe(0.07);+ expect(build.gb(18_900_000)).toBe(0.02);+ expect(build.gb(4_100_000)).toBe(0.004);+ expect(build.gb(1_200)).toBe(0);+ expect(build.gb(9_660_000_000)).toBe(9.66);+ });});describe("the provider fills the DBS bindings", () => {- async function prepare(input: GenInput, opts: { device?: string; media?: Record<string, MediaInfo> } = {}) {+ async function prepare(input: GenInput, opts: { device?: string; media?: Record<string, MediaInfo>; installed?: DbsModel[] } = {}) {let asked = 0;const res = await prepareWorkflow("separate-soundtrack-dbs", { seed: 1, ...input }, {generationId: "gen1",@@ -141,6 +153,7 @@ describe("the provider fills the DBS bindings", () => {asked++;return opts.device;},+ dbsModels: async () => opts.installed,});return { wf: res.workflow, asked };}@@ -156,14 +169,31 @@ describe("the provider fills the DBS bindings", () => {expect((await prepare({ audio: "film.wav", extra: { separationModel: "best" } }, { device: "cpu" })).wf["2"].inputs.model).toBe("DBS-TIGER-DnR");});- it("separates the mono mix unless stereo stems are asked for, and each channel of a file with more than 2", async () => {- expect((await prepare({ audio: "film.wav" })).wf["3"].inputs.channels).toBe("mono");- expect((await prepare({ audio: "film.wav", extra: { channels: "each channel" } })).wf["3"].inputs.channels).toBe("each channel");+ it("never sends a model the host doesn't have: the other one for the host's pick, words for one asked for", async () => {+ // A GPU ComfyUI with only BSRNN on disk: the default run takes BSRNN instead of failing inside DBSLoader.+ expect((await prepare({ audio: "film.wav" }, { device: "cuda", installed: ["DBS-BSRNN-DnR"] })).wf["2"].inputs.model).toBe("DBS-BSRNN-DnR");+ expect((await prepare({ audio: "film.wav" }, { device: "cuda", installed: ["DBS-BSRNN-DnR", "DBS-TIGER-DnR"] })).wf["2"].inputs.model).toBe("DBS-TIGER-DnR");+ await expect(prepare({ audio: "film.wav", extra: { separationModel: "DBS-TIGER-DnR" } }, { device: "cuda", installed: ["DBS-BSRNN-DnR"] })).rejects.toThrow(+ /^Best \(DBS-TIGER\) isn't installed on your ComfyUI \(models\/dbs\/DBS-TIGER-DnR\)/,+ );+ });++ it("separates the mono mix unless stereo stems are asked for; a file with more than 2 channels in mono, its bed from music + effects", async () => {+ const plain = (await prepare({ audio: "film.wav" })).wf;+ expect(plain["3"].inputs.channels).toBe("mono");+ expect(plain["4"].inputs).toEqual({ audio1: ["1", 0], audio2: ["3", 2], merge_method: "subtract" });+ const stereo = (await prepare({ audio: "film.wav", extra: { channels: "each channel" } })).wf;+ expect(stereo["3"].inputs.channels).toBe("each channel");+ expect(stereo["4"].inputs.merge_method).toBe("subtract");+ // ComfyUI saves mono or stereo only: a 6-channel stem would come out as scrambled stereo three times as long.const surround: MediaInfo = { container: "wav", duration: 10, hasVideo: false, hasAudio: true, channels: 6 };- expect((await prepare({ audio: "film.wav", extra: { channels: "mono" } }, { media: { "film.wav": surround } })).wf["3"].inputs.channels).toBe("each channel");- // An MP4 the header doesn't count: the channels the browser decoded.- expect((await prepare({ video: "clip.mp4", extra: { sourceChannels: 6 } })).wf["3"].inputs.channels).toBe("each channel");- expect((await prepare({ video: "clip.mp4", extra: { sourceChannels: 2 } })).wf["3"].inputs.channels).toBe("mono");+ const five = (await prepare({ audio: "film.wav", extra: { channels: "each channel" } }, { media: { "film.wav": surround } })).wf;+ expect(five["3"].inputs.channels).toBe("mono");+ expect(five["4"].inputs).toEqual({ audio1: ["3", 0], audio2: ["3", 1], merge_method: "add" });+ // A file the header doesn't count: the channels the browser decoded.+ const decoded = (await prepare({ video: "clip.ogg", extra: { sourceChannels: 6 } })).wf;+ expect([decoded["3"].inputs.channels, decoded["4"].inputs.merge_method]).toEqual(["mono", "add"]);+ expect((await prepare({ video: "clip.mp4", extra: { sourceChannels: 2 } })).wf["4"].inputs.merge_method).toBe("subtract");});it("reads a video's soundtrack with LoadAudio and keeps the rest of the graph as built", async () => {@@ -176,6 +206,32 @@ describe("the provider fills the DBS bindings", () => {});});+describe("which DBS models the host has (GET /models/dbs)", () => {+ it("reads the dbs folder's list, keeps it a few seconds, and says nothing when the pack isn't loaded", async () => {+ globalThis.__fuobeComfyDbs = undefined;+ let answer: Response = Response.json(["DBS-BSRNN-DnR/config.json", "DBS-BSRNN-DnR/model.safetensors", "DBS-TIGER-DnR/model.safetensors"]);+ const fetch = vi.fn(async (url: string) => {+ expect(url).toBe("http://comfy.test:8188/models/dbs");+ return answer.clone();+ });+ vi.stubGlobal("fetch", fetch);+ try {+ expect(await comfyDbsModels()).toEqual(["DBS-BSRNN-DnR"]);+ expect(await comfyDbsModels()).toEqual(["DBS-BSRNN-DnR"]);+ expect(fetch).toHaveBeenCalledTimes(1);+ // A run asks afresh: a model installed a moment ago is there.+ answer = Response.json(["DBS-BSRNN-DnR/config.json", "DBS-BSRNN-DnR/model.safetensors", "DBS-TIGER-DnR/config.json", "DBS-TIGER-DnR/model.safetensors"]);+ expect(await comfyDbsModels("main", 0)).toEqual(["DBS-BSRNN-DnR", "DBS-TIGER-DnR"]);+ // No ComfyUI-DBS: no dbs folder (404), so the host can't say and nothing is refused for it.+ answer = new Response("Not found", { status: 404 });+ expect(await comfyDbsModels("main", 0)).toBeUndefined();+ } finally {+ vi.unstubAllGlobals();+ globalThis.__fuobeComfyDbs = undefined;+ }+ });+});+describe("a finished DBS job's outputs", () => {it("are the four FLAC stems, tagged and voice first, then the pack's report as text", () => {const flac = (n: string) => ({ audio: [{ filename: `gen1_${n}.flac`, subfolder: "fuobe", type: "output" }] });@@ -199,16 +255,20 @@ describe("licences, as information", () => {licence: {name: "MIT",class: "commercial",- note: "Dialogue / music / effects separation; MIT code, vendored DBS code Apache-2.0 with MIT notices; the DBS weights are Apache-2.0, trained on DnR v2 (CC BY 4.0)",+ note: "Dialogue / music / effects separation; MIT code, vendored DBS code Apache-2.0 with MIT notices; the DBS weights are Apache-2.0, trained on DnR v2 (CC BY 4.0). Some FSD50K and FMA clips inside DnR v2 carry their own CC licences, NC variants included; whether that reaches the weights or their outputs is unresolved",},});expect(licenceInfo(workflowLicence(entry))).toMatchObject({ name: "Apache-2.0", class: "commercial" });});it("credits DnR v2 (CC BY 4.0) and the three MIT notices of the vendored code", () => {- expect(ATTRIBUTIONS.find((a) => a.licence === "CC BY 4.0")?.text).toBe(- "Trained on the Divide and Remaster (DnR) v2 dataset by Darius Petermann, Gordon Wichern, Zhong-Qiu Wang and Jonathan Le Roux",- );+ const dnr = ATTRIBUTIONS.find((a) => a.licence === "CC BY 4.0");+ expect(dnr?.text).toBe("Trained on the Divide and Remaster (DnR) v2 dataset by Darius Petermann, Gordon Wichern, Zhong-Qiu Wang and Jonathan Le Roux");+ // The open question about DnR's own source clips, recorded as information (research §3.2).+ expect(dnr?.note).toMatch(/^Some FSD50K and FMA clips inside DnR v2 carry their own CC licences, NC variants included\./);+ expect(entry.notes).toMatch(/NC variants included; whether that reaches the weights or their outputs is unresolved/);+ // Still information: the workflow's licence row reads Apache-2.0, nothing is flagged or hidden for it.+ expect(licenceInfo(workflowLicence(entry)).class).toBe("commercial");expect(ATTRIBUTIONS.filter((a) => a.licence === "MIT").map((a) => a.text)).toEqual(["BS-RoFormer, copyright (c) 2023 Phil Wang","Music-Source-Separation-Training, copyright (c) 2024 Roman Solovyev (ZFTurbo)",diff --git a/tests/media-probe.test.ts b/tests/media-probe.test.tsindex 41686006..a3c6b0e9 100644--- a/tests/media-probe.test.ts+++ b/tests/media-probe.test.ts@@ -33,6 +33,33 @@ function mp4({ w = 1920, h = 1080, rotate = false, audio = true, frames = 300, freturn Buffer.concat([box("ftyp", Buffer.from("mp42"), u32(0)), box("mdat", Buffer.alloc(64)), box("moov", mvhd, video, ...(audio ? [sound] : []))]);}+/** An audio-only MP4 / M4A whose sound track's first sample entry is `entry`. */+function soundOnly(entry: Buffer): Buffer {+ const stsd = box("stsd", u32(0, 1), entry);+ const sound = box("trak", box("mdia", box("mdhd", u32(0, 0, 0, 48000, 48000 * 2), Buffer.alloc(4)), box("hdlr", u32(0, 0), Buffer.from("soun"), Buffer.alloc(12)), box("minf", box("stbl", stsd))));+ return Buffer.concat([box("ftyp", Buffer.from("M4A "), u32(0)), box("moov", box("mvhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(80)), sound)]);+}++/** An AudioSampleEntry: SampleEntry (6 reserved, data reference 1), version, revision, vendor, channelcount, sample size… */+function audioEntry(type: string, channels: number, children: Buffer[] = [], version = 0, extra = Buffer.alloc(0)): Buffer {+ const fields = Buffer.alloc(28);+ fields.writeUInt16BE(1, 6);+ fields.writeUInt16BE(version, 8);+ fields.writeUInt16BE(channels, 16);+ fields.writeUInt16BE(16, 18);+ fields.writeUInt32BE(48000 * 65536, 24);+ return box(type, fields, extra, ...children);+}++/** An esds box whose AudioSpecificConfig is AAC-LC, 48 kHz, with this channelConfiguration. */+function esds(layout: number): Buffer {+ const asc = Buffer.from([(2 << 3) | (3 >> 1), ((3 & 1) << 7) | (layout << 3)]);+ const dsi = Buffer.concat([Buffer.from([0x05, asc.length]), asc]);+ const dcd = Buffer.concat([Buffer.from([0x04, 13 + dsi.length, 0x40, 0x15]), Buffer.alloc(11), dsi]);+ const es = Buffer.concat([Buffer.from([0x03, 3 + dcd.length, 0, 1, 0]), dcd]);+ return box("esds", u32(0), es);+}+function wav(seconds: number, rate = 22050, channels = 1): Buffer {const data = Buffer.alloc(Math.round(seconds * rate) * 2 * channels);const h = Buffer.alloc(44);@@ -92,6 +119,26 @@ describe("media probe", () => {expect(probeMedia(cbr)?.duration).toBeCloseTo(1, 6);});+ it("reads an MP4 / MOV sound track's channel count: an AAC track's own config, else the sample entry", () => {+ // ffmpeg's 5.1 AAC: the entry says 6, and so does the AudioSpecificConfig.+ expect(probeMedia(soundOnly(audioEntry("mp4a", 6, [esds(6)])))).toEqual({ container: "mp4", hasVideo: false, hasAudio: true, duration: 2, channels: 6 });+ // An encoder that leaves the entry at its template value of 2: the AAC config is right (7 = 7.1, eight channels).+ expect(probeMedia(soundOnly(audioEntry("mp4a", 2, [esds(6)])))?.channels).toBe(6);+ expect(probeMedia(soundOnly(audioEntry("mp4a", 2, [esds(7)])))?.channels).toBe(8);+ expect(probeMedia(soundOnly(audioEntry("mp4a", 2, [esds(2)])))?.channels).toBe(2);+ // AC-3 and PCM entries: channelcount.+ expect(probeMedia(soundOnly(audioEntry("ac-3", 6)))?.channels).toBe(6);+ expect(probeMedia(soundOnly(audioEntry("sowt", 1)))?.channels).toBe(1);+ // A QuickTime version 2 entry keeps the real count after its fixed fields (the 16-bit one reads 3).+ const v2 = Buffer.alloc(36);+ v2.writeUInt32BE(72, 0);+ v2.writeDoubleBE(48000, 4);+ v2.writeUInt32BE(6, 12);+ expect(probeMedia(soundOnly(audioEntry("lpcm", 3, [], 2, v2)))?.channels).toBe(6);+ // A sound track with no sample table: no count.+ expect(probeMedia(mp4())?.channels).toBeUndefined();+ });+it("says nothing about containers it doesn't read", () => {expect(probeMedia(Buffer.from("\x1aE\xdf\xa3 webm header....."))).toBeNull();expect(probeMedia(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]))).toBeNull();@@ -156,6 +203,21 @@ describe("probing without reading the whole file (Trim, the Ad Multiplier)", ()expect(await probeUrl("/api/files/gone.mp4")).toBeNull();});+ it("reads a big WAV, FLAC or MP3 from its header alone (Split soundtrack's 2 GB films, the mixer's FLAC stems)", async () => {+ // A WAV header for 600 s of 48 kHz 5.1, the rest never read.+ const head = wav(0, 48000, 6);+ head.writeUInt32LE(600 * 48000 * 12, 40);+ head.writeUInt32LE(36 + 600 * 48000 * 12, 4);+ const size = 44 + 600 * 48000 * 12;+ const r = reader(Buffer.concat([head, Buffer.alloc(300 * 1024)]));+ expect(await probeMediaRanges(r.read, size)).toEqual({ container: "wav", duration: 600, hasVideo: false, hasAudio: true, channels: 6 });+ expect(r.reads).toEqual([[0, 256 * 1024]]);+ // A CBR MP3 without a Xing header: the length from the whole file's size, not the bytes read.+ const mp3 = Buffer.alloc(300 * 1024);+ mp3.set([0xff, 0xfb, 0x90, 0x00], 0);+ expect((await probeMediaRanges(reader(mp3).read, 16000 * 60))?.duration).toBeCloseTo(60, 6);+ });+it("probes other containers only when the whole file fits in the first read", async () => {const wav = Buffer.alloc(44);wav.write("RIFF", 0);diff --git a/tests/split-soundtrack.test.ts b/tests/split-soundtrack.test.tsindex a8ea34f2..20e8e0aa 100644--- a/tests/split-soundtrack.test.ts+++ b/tests/split-soundtrack.test.ts@@ -3,45 +3,67 @@ import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import {+ backgroundLowered,CLOUD_ONLY_PROBLEM,CLOUD_SPLIT_PROBLEM,clampDb,dbLabel,dbsChannelsFor,dbsModelFor,+ dbsSurroundBed,dbToGain,DBS_SPEED,durationWords,encodeWav,+ exportProblem,headroomGain,hostPick,+ installedDbs,+ missingDbs,+ MIX_MAX_BYTES,+ mixerBudget,+ mixerBytes,+ mixerProblem,mixName,+ mixPart,+ mixPeak,+ mixPlan,ORIGINAL_MIX,+ partFrames,planRemux,planSplit,presetOf,PRESETS,+ SAVE_MAX_CHANNELS,+ separationPasses,setLevel,setMute,setSolo,splitTime,+ stemFeed,STEMS,stemGains,+ surroundSource,+ wavBytes,type Mix,} from "@/lib/av/split";import { getModel } from "@/lib/catalog";import { HUB_MODES, modeHref } from "@/lib/hubs";// Audio → Split soundtrack (DBS D1): the planner, the mixer maths and the API in demo mode.+const SURROUND_NOTE =+ "This file has 6 channels. ComfyUI saves audio in mono or stereo only, so the stems come out in mono (all channels mixed), and Music & effects is the music and effects stems added up.";const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-split-"));process.env.FUOBE_DATA_DIR = dir;// Nothing listens: the open model runs on the demo provider.process.env.COMFYUI_URL = "http://127.0.0.1:9";const { setSetting } = await import("@/server/settings");-const { saveFile } = await import("@/server/storage");+const { getAsset, saveFile, scratchDir } = 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 }));@@ -66,6 +88,23 @@ function upload(seconds: number, channels = 2, name = "film.wav"): string {return saveFile({ data: buf, contentType: "audio/wav", name, source: "upload" }).url;}+/** A small MP4: a video track and, unless `channels` is null, an AAC sound track with that many channels (2 s each). */+function mp4Sound(channels: number | null): Buffer {+ const u32 = (...v: number[]) => Buffer.concat(v.map((n) => Buffer.from([n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255])));+ const box = (type: string, ...parts: Buffer[]) => {+ const body = Buffer.concat(parts);+ return Buffer.concat([u32(8 + body.length), Buffer.from(type), body]);+ };+ const trak = (handler: string, ...stbl: Buffer[]) =>+ box("trak", box("mdia", box("mdhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(4)), box("hdlr", u32(0, 0), Buffer.from(handler), Buffer.alloc(12)), box("minf", box("stbl", ...stbl))));+ const entry = Buffer.alloc(28);+ entry.writeUInt16BE(1, 6);+ entry.writeUInt16BE(channels ?? 2, 16);+ entry.writeUInt16BE(16, 18);+ const sound = channels === null ? [] : [trak("soun", box("stsd", u32(0, 1), box("mp4a", entry)))];+ return Buffer.concat([box("ftyp", Buffer.from("isom"), u32(0)), box("moov", box("mvhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(80)), trak("vide", box("stts", u32(0, 1, 50, 40))), ...sound)]);+}+const post = (body: unknown, preview = false) =>route.POST(new Request(`http://x/api/audio-tools${preview ? "?preview=1" : ""}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));@@ -93,14 +132,43 @@ describe("the DBS model and channels a run gets", () => {expect(dbsModelFor("something else", "cpu")).toBe("DBS-BSRNN-DnR");});- it("separates the mono mix unless stereo stems are asked for, and every channel of anything over two", () => {+ it("separates the mono mix unless stereo stems are asked for, and anything over two channels in mono", () => {expect(dbsChannelsFor(undefined, 2)).toBe("mono");expect(dbsChannelsFor("mono", 1)).toBe("mono");expect(dbsChannelsFor("each channel", 2)).toBe("each channel");expect(dbsChannelsFor("stereo")).toBe("each channel");- // 5.1: the background (original minus mono speech) would take speech out of the LFE and surrounds too.- expect(dbsChannelsFor("mono", 6)).toBe("each channel");- expect(dbsChannelsFor(undefined, 3)).toBe("each channel");+ // 5.1: ComfyUI saves mono or stereo only (a 6-channel stem comes out as scrambled stereo), so mono, stereo asked or not.+ expect(SAVE_MAX_CHANNELS).toBe(2);+ expect([surroundSource(6), surroundSource(3), surroundSource(2), surroundSource(undefined)]).toEqual([true, true, false, false]);+ expect(dbsChannelsFor("mono", 6)).toBe("mono");+ expect(dbsChannelsFor("each channel", 6)).toBe("mono");+ expect(dbsChannelsFor(undefined, 3)).toBe("mono");+ // A mono file is one pass whatever is asked: no stereo stems to make, and the estimate isn't doubled.+ expect(dbsChannelsFor("each channel", 1)).toBe("mono");+ expect(separationPasses("each channel", 1)).toBe(1);+ expect(separationPasses("each channel", 2)).toBe(2);+ expect(separationPasses("each channel")).toBe(2);+ expect(separationPasses("mono", 6)).toBe(1);+ });++ it("only picks a model the host has on disk, and refuses one asked for that isn't there", () => {+ // GET /models/dbs: both files of a model, or it isn't there (a Windows ComfyUI answers with back slashes).+ expect(installedDbs(["DBS-BSRNN-DnR/config.json", "DBS-BSRNN-DnR/model.safetensors", "DBS-TIGER-DnR/config.json"])).toEqual(["DBS-BSRNN-DnR"]);+ expect(installedDbs(["DBS-TIGER-DnR\\config.json", "DBS-TIGER-DnR\\model.safetensors"])).toEqual(["DBS-TIGER-DnR"]);+ expect(installedDbs([])).toEqual([]);+ expect(installedDbs(null)).toBeUndefined();+ // A GPU host set up without TIGER runs BSRNN rather than a model that isn't there; a CPU host without BSRNN, TIGER.+ expect(hostPick("cuda", ["DBS-BSRNN-DnR"])).toBe("fast");+ expect(hostPick("cuda", ["DBS-BSRNN-DnR", "DBS-TIGER-DnR"])).toBe("best");+ expect(hostPick("cpu", ["DBS-TIGER-DnR"])).toBe("best");+ expect(hostPick("cuda", [])).toBe("best");+ expect(dbsModelFor(undefined, "cuda", ["DBS-BSRNN-DnR"])).toBe("DBS-BSRNN-DnR");+ expect(() => dbsModelFor("best", "cuda", ["DBS-BSRNN-DnR"])).toThrow(missingDbs("DBS-TIGER-DnR", ["DBS-BSRNN-DnR"]));+ expect(missingDbs("DBS-TIGER-DnR", ["DBS-BSRNN-DnR"])).toBe(+ 'Best (DBS-TIGER) isn\'t installed on your ComfyUI (models/dbs/DBS-TIGER-DnR). Copy the install commands from Workflows → "Split a soundtrack", or pick Fast (DBS-BSRNN).',+ );+ // No weights at all: said in words, not a FileNotFoundError from inside ComfyUI.+ expect(() => dbsModelFor(undefined, "cpu", [])).toThrow(/Fast \(DBS-BSRNN\) isn't installed on your ComfyUI \(models\/dbs\/DBS-BSRNN-DnR\)\. Copy the install commands from Workflows → "Split a soundtrack"\.$/);});});@@ -138,11 +206,25 @@ describe("planSplit", () => {expect(p.length).toBeNull();});- it("splits every channel of a 5.1 file on its own, and says why it takes longer", () => {- const p = planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 6 });- expect(p.mode).toBe("each channel");- expect(p.steps[0].request.params?.extra).toEqual({ channels: "each channel", sourceChannels: 6 });- expect(p.notes[0]).toBe("This file has 6 channels, so each is split on its own: about 6x the time.");+ it("splits a 5.1 file in mono, and says why its stems are mono", () => {+ const p = planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 6, stereo: true });+ expect(p.mode).toBe("mono");+ expect(p.steps[0].request.params?.extra).toEqual({ channels: "mono", sourceChannels: 6 });+ expect(p.notes[0]).toBe(SURROUND_NOTE);+ expect(p.summary).toBe("Splits it into dialogue, music, effects and music & effects.");+ });++ it("makes a surround file's background from the music and effects stems (graph A's node 4 rewired)", () => {+ const graph = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "workflows/comfyui/separate-soundtrack-dbs.json"), "utf8"));+ const bed = dbsSurroundBed(graph);+ expect(bed["4"].inputs).toEqual({ audio1: ["3", 0], audio2: ["3", 1], merge_method: "add" });+ // Nothing else changes, and the graph it came from is left as it was.+ expect({ ...bed, "4": graph["4"] }).toEqual(graph);+ expect(graph["4"].inputs.merge_method).toBe("subtract");+ // A graph without DBS, or already rewired: as it is.+ const other = { "1": { class_type: "LoadAudio", inputs: {} } };+ expect(dbsSurroundBed(other)).toBe(other);+ expect(dbsSurroundBed(bed)).toBe(bed);});it("has no cloud route: DBS isn't hosted, and no other model stands in for it", () => {@@ -172,8 +254,11 @@ describe("time on the open engine", () => {const stereo = splitTime({ seconds: 60, quality: "fast", mode: "each channel", channels: 2, device: "cpu" });expect(stereo.high).toBe(Math.round(3 + ((60 * 2) / 0.27) * 1.6));expect(splitTime({ seconds: 60, quality: "best", mode: "mono" }).low).toBe(Math.round(3 + (60 / 0.09) * 0.8));- // A 5.1 file: six passes.+ // A mono file with stereo stems asked for: one pass (DBS runs once per channel).+ expect(splitTime({ seconds: 60, quality: "fast", mode: dbsChannelsFor("each channel", 1), channels: 1, device: "cpu" })).toEqual({ low: 181, high: 359 });+ // Each channel is one pass per channel (the measured 5.1 run: six passes); a 5.1 split is mono now, one pass.expect(splitTime({ seconds: 10, quality: "fast", mode: "each channel", channels: 6, device: "cpu" }).low).toBe(Math.round(3 + (60 / 0.27) * 0.8));+ expect(splitTime({ seconds: 10, quality: "fast", mode: dbsChannelsFor("each channel", 6), channels: 6, device: "cpu" }).low).toBe(Math.round(3 + (10 / 0.27) * 0.8));// CUDA: well over real time, a range up to 4x slower than the reference card.expect(splitTime({ seconds: 600, quality: "best", mode: "mono", device: "cuda" })).toEqual({ low: 41, high: 154 });});@@ -252,6 +337,12 @@ describe("the mixer", () => {expect(mixName({ ...ORIGINAL_MIX, voice: { db: 0, mute: true, solo: false }, background: { db: 0, mute: true, solo: false } })).toBe("Silence");});+ it("knows a background that AudioMerge lowered to fit under full scale (a loud master)", () => {+ expect(backgroundLowered(1)).toBe(true);+ expect(backgroundLowered(32767 / 32768)).toBe(true);+ expect(backgroundLowered(0.97)).toBe(false);+ });+it("exports a 16-bit WAV kept under full scale", () => {expect(headroomGain(0.5)).toBe(1);expect(headroomGain(2) * 2).toBeCloseTo(dbToGain(-0.1), 6);@@ -263,6 +354,59 @@ describe("the mixer", () => {// Interleaved L/R, clipped at full scale.expect(Array.from({ length: 8 }, (_, i) => d.getInt16(44 + i * 2, true))).toEqual([0, 32767, 16384, -16384, -32768, 0, 32767, 0]);});++ it("mixes the stems as WebAudio plays them: mono up-mixed to both sides of stereo, to the centre of 5.1", () => {+ expect([0, 1].map((c) => stemFeed(1, 2, c))).toEqual([0, 0]);+ expect([0, 1, 2, 3, 4, 5].map((c) => stemFeed(1, 6, c))).toEqual([-1, -1, 0, -1, -1, -1]);+ expect([0, 1, 2, 3, 4, 5].map((c) => stemFeed(6, 6, c))).toEqual([0, 1, 2, 3, 4, 5]);+ expect([0, 1, 2].map((c) => stemFeed(2, 3, c))).toEqual([0, 1, -1]);+ expect(stemFeed(1, 1, 0)).toBe(0);+ });++ it("writes the mix in parts that join into the WAV, lowering the whole mix when it would clip", () => {+ const voice = { channels: [Float32Array.from([0.5, 0.5, 0.5, 0.5, 0.5])], gain: 1 };+ const bed = { channels: [Float32Array.from([0.25, 0.5, 0.75, 0.25, 0]), Float32Array.from([-0.25, -0.5, -0.75, -0.25, 0])], gain: 1 };+ const muted = { channels: [Float32Array.from([1, 1, 1, 1, 1])], gain: 0 };+ const plan = mixPlan([voice, bed, muted], 8000);+ expect(plan).toMatchObject({ frames: 5, channels: 2, sampleRate: 8000, bytes: wavBytes(5, 2) });+ // Left 0.5 + 0.75 = 1.25 at its loudest: over full scale, so the whole mix comes down to −0.1 dBFS.+ expect(mixPeak(plan)).toBeCloseTo(1.25, 6);+ expect(mixPeak(plan, 3, 5)).toBeCloseTo(0.75, 6);+ const k = headroomGain(mixPeak(plan));+ const expected = encodeWav(+ [Float32Array.from([0.75, 1, 1.25, 0.75, 0.5].map((v) => v * k)), Float32Array.from([0.25, 0, -0.25, 0.25, 0.5].map((v) => v * k))],+ 8000,+ );+ // 2 frames (8 bytes) a part: the header rides on the first.+ const parts = [0, 2, 4].map((f) => mixPart(plan, f, f + 2, k));+ expect(partFrames(plan, 8)).toBe(2);+ expect(parts.map((p) => p.length)).toEqual([44 + 8, 8, 4]);+ expect(Buffer.concat(parts)).toEqual(Buffer.from(expected));+ // Frame 2's left sample, the loudest, lands at −0.1 dBFS.+ expect(new DataView(parts[1].buffer).getInt16(0, true)).toBe(Math.round(1.25 * k * 0x7fff));+ // A quiet mix is left as it is.+ expect(headroomGain(mixPeak(mixPlan([voice], 8000)))).toBe(1);+ });++ it("knows how much the browser can hold, and says so before decoding a split too long for it", () => {+ // Four stems of a 7-minute 5.1 clip, every channel split: 24 channels at 48 kHz as 32-bit floats.+ const surround = mixerBytes(Array(4).fill({ seconds: 420, channels: 6 }), 48000);+ expect(surround).toBe(420 * 48000 * 24 * 4);+ expect(mixerBudget({ deviceMemoryGb: 8 })).toBe(2 * 1024 ** 3);+ expect(mixerBudget({ deviceMemoryGb: 2 })).toBe(512 * 1024 ** 2);+ expect(mixerBudget({ coarse: true })).toBe(1024 ** 3);+ expect(mixerBudget({})).toBe(2 * 1024 ** 3);+ expect(mixerProblem(surround, mixerBudget({}))).toBeNull();+ // An hour of stereo on a phone: refused, in words, before anything is fetched.+ const hour = mixerBytes([{ seconds: 3600, channels: 1 }, { seconds: 3600, channels: 1 }, { seconds: 3600, channels: 1 }, { seconds: 3600, channels: 2 }], 48000);+ expect(mixerProblem(hour, mixerBudget({ coarse: true }))).toBe(+ "This split is too long to mix in your browser: its stems take about 3.2 GB of memory to play, and this device has room for about 1 GB. Download the stems and mix them in an editor, or split a shorter clip.",+ );+ // The export itself: a WAV up to MIX_MAX_BYTES, sent in parts, so a 7-minute 5.1 mix (242 MB) is fine.+ expect(wavBytes(420 * 48000, 6)).toBe(44 + 420 * 48000 * 12);+ expect(exportProblem(420 * 48000, 6)).toBeNull();+ expect(exportProblem(Math.ceil(MIX_MAX_BYTES / 12), 6)).toMatch(/^This mix would be a 2 GB WAV, over the 2 GB an export can be/);+ });});describe("Split soundtrack in the Audio hub", () => {@@ -300,12 +444,13 @@ describe("POST /api/audio-tools split and remux (demo mode)", () => {expect(g.outputs.every((o) => o.url.startsWith("/api/files/"))).toBe(true);});- it("reads a 5.1 file's channels from its header and splits each one", async () => {+ it("reads a 5.1 file's channels from its header and splits it in mono", async () => {const media = upload(4, 6, "surround.wav");- const preview = await (await post({ tool: "split", engine: "open", media, kind: "audio" }, true)).json();- expect(preview.notes[0]).toBe("This file has 6 channels, so each is split on its own: about 6x the time.");+ const preview = await (await post({ tool: "split", engine: "open", media, kind: "audio", stereo: true }, true)).json();+ expect(preview.notes[0]).toBe(SURROUND_NOTE);+ expect(preview.estimate).toEqual(splitTime({ seconds: 4, quality: "fast", mode: "mono", channels: 6 }));const run = await (await post({ tool: "split", engine: "open", media, kind: "audio" })).json();- expect(run.result.request.params.extra).toEqual({ channels: "each channel", sourceChannels: 6 });+ expect(run.result.request.params.extra).toEqual({ channels: "mono", sourceChannels: 6 });});it("says plainly that the cloud has no split, and refuses on an install set to paid APIs only", async () => {@@ -324,6 +469,51 @@ describe("POST /api/audio-tools split and remux (demo mode)", () => {expect((await (await post({ tool: "split", engine: "open", media: "/api/files/uploads/gone.wav", kind: "audio" }, true)).json()).error).toBe("That audio file is gone — add it again");});+ it("refuses a file with no sound before anything is queued", async () => {+ const silent = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures", "shorts-silent.webm")), contentType: "video/webm", name: "silent.webm", source: "upload" }).url;+ for (const preview of [true, false]) {+ const res = await post({ tool: "split", engine: "open", media: silent, kind: "video" }, preview);+ expect(res.status).toBe(422);+ expect((await res.json()).error).toBe("This video has no sound to split");+ }+ const silentMp4 = saveFile({ data: mp4Sound(null), contentType: "video/mp4", name: "t2v.mp4", source: "upload" }).url;+ expect((await (await post({ tool: "split", engine: "open", media: silentMp4, kind: "video" }, true)).json()).error).toBe("This video has no sound to split");+ });++ it("reads a 5.1 MP4's channels from its header, so an API call without the browser's count gets the surround rule", async () => {+ const media = saveFile({ data: mp4Sound(6), contentType: "video/mp4", name: "film.mp4", source: "upload" }).url;+ const preview = await (await post({ tool: "split", engine: "open", media, kind: "video" }, true)).json();+ expect(preview).toMatchObject({ channels: 6, length: 2 });+ expect(preview.notes[0]).toBe(SURROUND_NOTE);+ const run = await (await post({ tool: "split", engine: "open", media, kind: "video" })).json();+ 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");+ const head = Buffer.alloc(44);+ const data = 2.2e9 - 44;+ head.write("RIFF", 0);+ head.writeUInt32LE(36 + data, 4);+ head.write("WAVEfmt ", 8);+ head.writeUInt32LE(16, 16);+ head.writeUInt16LE(1, 20);+ head.writeUInt16LE(2, 22);+ head.writeUInt32LE(48000, 24);+ head.writeUInt32LE(192000, 28);+ head.writeUInt16LE(4, 32);+ head.writeUInt16LE(16, 34);+ head.write("data", 36);+ head.writeUInt32LE(data, 40);+ 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 });+ } finally {+ fs.rmSync(file, { force: true });+ }+ });+it("puts a mix back on the video: free on the open engine, priced on the cloud", async () => {const audio = upload(3, 2, "mix.wav");const video = saveFile({ data: Buffer.from("not really a video"), contentType: "video/mp4", name: "clip.mp4", source: "upload" }).url;@@ -338,3 +528,60 @@ describe("POST /api/audio-tools split and remux (demo mode)", () => {expect((await (await post({ tool: "remux", engine: "open", video })).json()).error).toBe("Export the mix first");});});++describe("POST /api/audio-tools/export (a mix sent in parts)", () => {+ const send = (q: string, body: Uint8Array) => exportRoute.POST(new Request(`http://x/api/audio-tools/export?${q}`, { method: "POST", body: Buffer.from(body) }));++ it("joins the parts into one WAV in the Library, whatever its size", async () => {+ const plan = mixPlan([{ channels: [Float32Array.from({ length: 1000 }, (_, i) => Math.sin(i / 10) / 2), Float32Array.from({ length: 1000 }, () => 0.25)], gain: 1 }], 8000);+ const per = partFrames(plan, 1000);+ const parts = Array.from({ length: Math.ceil(plan.frames / per) }, (_, i) => mixPart(plan, i * per, (i + 1) * per));+ expect(parts.length).toBe(4);+ let id = "";+ let offset = 0;+ let res: Response | undefined;+ for (const [i, part] of parts.entries()) {+ const last = i === parts.length - 1;+ res = await send(`offset=${offset}${id ? `&id=${id}` : ""}${last ? `&last=1&name=${encodeURIComponent("Film · No dialogue.wav")}` : ""}`, part);+ if (!last) {+ expect(res.status).toBe(200);+ const body = await res.json();+ id = body.id;+ offset = body.received;+ }+ }+ expect(res!.status).toBe(201);+ const asset = await res!.json();+ expect(asset).toMatchObject({ kind: "audio", contentType: "audio/wav", name: "Film · No dialogue.wav", source: "upload" });+ const stored = getAsset(asset.id)!;+ const bytes = fs.readFileSync(path.join(dir, "files", stored.relPath));+ expect(bytes).toEqual(Buffer.concat(parts));+ expect(bytes.length).toBe(plan.bytes);+ // Nothing is left behind in the scratch folder.+ expect(fs.readdirSync(scratchDir()).filter((f) => f.startsWith("mix-"))).toEqual([]);+ });++ it("refuses what isn't a 16-bit WAV, a part that doesn't follow on, too much audio and a short export", async () => {+ expect((await send("offset=0&last=1", new TextEncoder().encode("not a wav file at all, not even close to one"))).status).toBe(415);+ expect((await send("offset=10", mixPart(mixPlan([{ channels: [new Float32Array(10)], gain: 1 }], 8000), 0, 10))).status).toBe(409);+ const plan = mixPlan([{ channels: [new Float32Array(100)], gain: 1 }], 8000);+ const first = await (await send("offset=0", mixPart(plan, 0, 50))).json();+ expect(first.received).toBe(44 + 100);+ expect((await send(`offset=0&id=${first.id}`, mixPart(plan, 50, 100))).status).toBe(409);+ const short = await send(`offset=${first.received}&id=${first.id}&last=1`, mixPart(plan, 50, 60));+ expect(short.status).toBe(409);+ expect((await short.json()).error).toMatch(/^The export stopped short/);+ // The short part was kept (20 bytes): the next one must start after it, and the header caps what can follow.+ expect((await send(`offset=${first.received}&id=${first.id}`, mixPart(plan, 60, 70))).status).toBe(409);+ expect((await send(`offset=${first.received + 20}&id=${first.id}`, new Uint8Array(400))).status).toBe(413);+ const done = await send(`offset=${first.received + 20}&id=${first.id}&last=1&name=Mix`, mixPart(plan, 60, 100));+ expect(done.status).toBe(201);+ expect((await done.json()).name).toBe("Mix.wav");+ expect((await send("offset=4&id=../../etc", new Uint8Array(4))).status).toBe(404);+ expect((await send("offset=4&id=AAAAAAAAAAAAAAAA", new Uint8Array(4))).status).toBe(404);+ // A header that declares more than an export can be.+ const huge = mixPart(plan, 0, 10);+ new DataView(huge.buffer).setUint32(4, MIX_MAX_BYTES, true);+ expect((await send("offset=0", huge)).status).toBe(413);+ });+});diff --git a/tests/webm-probe.test.ts b/tests/webm-probe.test.tsindex a1067456..daaab008 100644--- a/tests/webm-probe.test.ts+++ b/tests/webm-probe.test.ts@@ -7,7 +7,7 @@ const fixture = (name: string) => fs.readFileSync(path.join(__dirname, "fixturesdescribe("probeWebm", () => {it("reads a WebM's length, size, frame rate and whether it has sound", () => {- expect(probeWebm(fixture("shorts-sound.webm"))).toMatchObject({ hasAudio: true, hasVideo: true, width: 96, height: 64 });+ expect(probeWebm(fixture("shorts-sound.webm"))).toMatchObject({ hasAudio: true, hasVideo: true, width: 96, height: 64, channels: 1 });const silent = probeWebm(fixture("shorts-silent.webm"))!;expect(silent).toMatchObject({ hasAudio: false, hasVideo: true, width: 96, height: 64 });expect(silent.duration).toBeCloseTo(6, 1);@@ -28,6 +28,17 @@ describe("probeWebm", () => {const header = el([0x1a, 0x45, 0xdf, 0xa3], el([0x42, 0x82], Buffer.from("webm")));// Segment with the "unknown size" marker (all ones), then an unknown-size Cluster.const segment = Buffer.concat([Buffer.from([0x18, 0x53, 0x80, 0x67, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), tracks, Buffer.from([0x1f, 0x43, 0xb6, 0x75, 0xff]), Buffer.alloc(32)]);- expect(probeWebm(Buffer.concat([header, segment]))).toEqual({ hasAudio: true, hasVideo: true, width: 640, height: 360 });+ // An audio track without an Audio element: Matroska's default of one channel.+ expect(probeWebm(Buffer.concat([header, segment]))).toEqual({ hasAudio: true, hasVideo: true, width: 640, height: 360, channels: 1 });+ });++ it("says how many channels the first sound track has (Split soundtrack splits each channel of a 5.1 file on its own)", () => {+ const el = (id: number[], body: Buffer) => Buffer.concat([Buffer.from(id), Buffer.from([0x80 | body.length]), body]);+ const u = (n: number) => Buffer.from([n]);+ const audio = (channels: number) => el([0xae], Buffer.concat([el([0x83], u(2)), el([0xe1], Buffer.concat([el([0xb5], Buffer.from([0x40, 0xe7, 0x70, 0, 0, 0, 0, 0])), el([0x9f], u(channels))]))]));+ const tracks = el([0x16, 0x54, 0xae, 0x6b], Buffer.concat([audio(6), audio(2)]));+ const header = el([0x1a, 0x45, 0xdf, 0xa3], el([0x42, 0x82], Buffer.from("webm")));+ const segment = Buffer.concat([Buffer.from([0x18, 0x53, 0x80, 0x67, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), tracks]);+ expect(probeWebm(Buffer.concat([header, segment]))).toEqual({ hasAudio: true, hasVideo: false, channels: 6 });});});diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex 6b7891af..49f037ae 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -1,6 +1,6 @@{"version": 1,- "generatedAt": "2026-10-29T18:20:35.522Z",+ "generatedAt": "2026-10-29T20:13:35.739Z","comfyuiCommit": "fc04da91b2ab12f99e4716371a7e4f98ac982597","comfyuiVersion": "0.41.0","workflowTemplatesVersion": "0.11.86",@@ -10943,7 +10943,7 @@"file": "DBS-BSRNN-DnR/model.safetensors","folder": "dbs","url": "https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/5af343f57f106fbb95efe8a60f1a3999eeb0aef8/model.safetensors",- "sizeGb": 0.019+ "sizeGb": 0.02},{"file": "DBS-BSRNN-DnR/config.json",@@ -10955,15 +10955,13 @@"file": "DBS-TIGER-DnR/model.safetensors","folder": "dbs","url": "https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/22da7d4cd3ea63f9365181008bff1c0d2ab6fb2b/model.safetensors",- "sizeGb": 0.004,- "optional": true+ "sizeGb": 0.004},{"file": "DBS-TIGER-DnR/config.json","folder": "dbs","url": "https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/22da7d4cd3ea63f9365181008bff1c0d2ab6fb2b/config.json",- "sizeGb": 0,- "optional": true+ "sizeGb": 0}],"customNodes": [@@ -10975,7 +10973,7 @@"vramGb": 0,"license": "DBS weights Apache-2.0 (JusperLee; trained on DnR v2, CC BY 4.0); ComfyUI-DBS code MIT; vendored DBS code Apache-2.0 with MIT notices (BS-RoFormer, MSST, TIGER)","validated": true,- "notes": "CPU OK, about 1.7 GiB on CUDA. audio = an audio file or a video (LoadAudio reads a video's soundtrack without decoding frames). DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 3x slower on a CPU, the CUDA default); device auto. Measured on a 4-CPU host (torch 2.14.1+cpu, 10-20 s clips): DBS-BSRNN 0.17-0.33x real time per channel, DBS-TIGER 0.08-0.09x. DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (every channel separated on its own: 2x the time for stereo, 6x for 5.1; the provider forces it for inputs with more than 2 channels, where the subtract below would also take speech out of the LFE and surrounds); output_sample_rate input. Outputs in order: voice (speech), music, effects (sfx), background = original minus speech (AudioMerge subtract: with mono it keeps the original stereo image at mono cost; AudioMerge scales the whole result down when it peaks over 1.0), and the pack's JSON report (model, device, rates, windows, seconds, times real time). Stems are FLAC, so they still add up to the source. Voice is first, so a chain without a stem takes the dialogue. Trained on synthetic English mixes (DnR v2): dialogue separates well (15-16 dB), music against effects less so (5.7-7.8 dB)."+ "notes": "CPU OK, about 1.7 GiB on CUDA. audio = an audio file or a video (LoadAudio reads a video's soundtrack without decoding frames). DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 3x slower on a CPU, the CUDA default); device auto. Measured on a 4-CPU host (torch 2.14.1+cpu, 10-20 s clips): DBS-BSRNN 0.17-0.33x real time per channel, DBS-TIGER 0.08-0.09x. DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (every channel separated on its own: 2x the time for stereo, 6x for 5.1; the provider forces it for inputs with more than 2 channels, where the subtract below would also take speech out of the LFE and surrounds); output_sample_rate input. Outputs in order: voice (speech), music, effects (sfx), background = original minus speech (AudioMerge subtract: with mono it keeps the original stereo image at mono cost; AudioMerge scales the whole result down when it peaks over 1.0), and the pack's JSON report (model, device, rates, windows, seconds, times real time). Voice + background add up to the source, except on a loud master where AudioMerge had to lower the background to fit under full scale (FLAC holds no more). Voice is first, so a chain without a stem takes the dialogue. Trained on synthetic English mixes (DnR v2): dialogue separates well (15-16 dB), music against effects less so (5.7-7.8 dB). Some FSD50K and FMA clips inside DnR v2 carry their own CC licences, NC variants included; whether that reaches the weights or their outputs is unresolved (recorded as information)."},{"id": "captions-qwen3-asr",