Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([vo-mux-preserve-clip-audio-under-ducked-vo]): preserve + duck stitched-clip audio under VO

[._.]/ Adam Eivy2320615eec13
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 46eb24a82c..a56d247e2c 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -141,6 +141,28 @@ export const findFfprobe = async () => {
return cachedFfprobePath;
};
+// Probe whether a media file carries at least one audio stream. Referencing
+// `[0:a]` in a filter_complex graph against a silent video (AI-gen clips are
+// silent today) aborts the whole ffmpeg run, so callers that want to preserve
+// a clip's own soundtrack (e.g. LTX-2 audio-to-video) must gate the `[0:a]`
+// input on this probe. Returns false when ffprobe is unavailable so callers
+// default to the safe "no clip audio" path rather than emitting a graph that
+// can't build.
+export const hasAudioStream = async (videoPath) => {
+ if (typeof videoPath !== 'string' || !videoPath) return false;
+ const ffprobe = await findFfprobe();
+ if (!ffprobe) return false;
+ const args = [
+ '-v', 'error',
+ '-select_streams', 'a',
+ '-show_entries', 'stream=index',
+ '-of', 'default=nokey=1:noprint_wrappers=1',
+ videoPath,
+ ];
+ const { stdout } = await execFileAsync(ffprobe, args, { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));
+ return (stdout || '').trim().length > 0;
+};
+
// Single-video thumbnail extraction. Seeks to mid-clip rather than frame 0
// because LTX-2 renders fade IN from black: the first ~0.5s is near-zero
// brightness, so a frame-0 thumbnail looks like a "broken black" tile
diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.js
index fadc192f4a..3c4845cfc4 100644
--- a/server/lib/ffmpeg.test.js
+++ b/server/lib/ffmpeg.test.js
@@ -3,7 +3,7 @@ import { writeFileSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { verifyVideoPlayable, safeUnder, runFfmpegProcess } from './ffmpeg.js';
+import { verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream } from './ffmpeg.js';
describe('verifyVideoPlayable', () => {
let tmpDir;
@@ -51,6 +51,25 @@ describe('verifyVideoPlayable', () => {
});
});
+describe('hasAudioStream', () => {
+ it('returns false for an empty/invalid path without shelling out', async () => {
+ expect(await hasAudioStream('')).toBe(false);
+ expect(await hasAudioStream(null)).toBe(false);
+ expect(await hasAudioStream(undefined)).toBe(false);
+ });
+
+ it('returns false for a non-media file (no audio stream, or ffprobe absent)', async () => {
+ // Garbage bytes: ffprobe reports no audio stream → false. When ffprobe is
+ // not installed the helper short-circuits to false (documented safe
+ // default), so false is the expected outcome either way.
+ const tmpDir = mkdtempSync(join(tmpdir(), 'portos-ffmpeg-audio-'));
+ const junk = join(tmpDir, 'junk.mp4');
+ writeFileSync(junk, Buffer.alloc(64, 0));
+ expect(await hasAudioStream(junk)).toBe(false);
+ rmSync(tmpDir, { recursive: true, force: true });
+ });
+});
+
describe('runFfmpegProcess', () => {
it('returns ok:false when bin is not a string', async () => {
const res = await runFfmpegProcess({ args: ['-version'] });
diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.js
index fa796de9ed..3c81533a52 100644
--- a/server/services/creativeDirector/stitchRunner.js
+++ b/server/services/creativeDirector/stitchRunner.js
@@ -157,7 +157,7 @@ async function maybeMuxPipelineAudio(project, finalEntry) {
console.log(`🎙️ CD stitch mux: overlaying ${voLines.length} VO line(s)${musicPath ? ' + ducked music bed' : ''} onto ${finalEntry.filename}`);
const result = await muxVoLines(videoPath, { voLines, musicPath });
if (result.ok) {
- console.log(`✅ CD stitch mux: VO mux applied to ${finalEntry.filename} (${result.lineCount} line(s)${result.ducked ? ', music ducked' : ''})`);
+ console.log(`✅ CD stitch mux: VO mux applied to ${finalEntry.filename} (${result.lineCount} line(s)${result.ducked ? ', music ducked' : ''}${result.clipAudio ? ', clip audio preserved' : ''})`);
return;
}
// VO mux failed — fall through to a plain music bed if we have one, so a
diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.js
index bd52520756..7c399683e5 100644
--- a/server/services/pipeline/audioMux.js
+++ b/server/services/pipeline/audioMux.js
@@ -13,16 +13,18 @@
* `muxMusicBed` whenever the issue has placed VO lines; music-only issues still
* take the simpler `muxMusicBed` path.
*
+ * Clip-audio preservation: `muxVoLines` also keeps the stitched video's *own*
+ * soundtrack (LTX-2 audio-to-video can carry one) — when the input video has an
+ * audio stream it's mixed in as another bed and ducked under VO via the same
+ * sidechain key as the music. Probed with `hasAudioStream` first, because
+ * referencing `[0:a]` against a silent AI-gen clip would abort the whole graph.
+ * (`muxMusicBed` still replaces the track — it's the no-VO music-only path.)
+ *
* Failure handling: this is a value-add overlay, not a correctness gate. If
* the mux pass throws (ffmpeg missing, malformed audio, etc.), callers
* should log and leave the silent video in place — graceful degradation
* beats blocking the whole stitch on an optional cosmetic step.
*
- * Known limitation: like `muxMusicBed`, the VO pass *replaces* the stitched
- * video's audio track rather than mixing under it. AI-gen clips are silent
- * today, but LTX-2 audio-to-video can carry a clip soundtrack — preserving +
- * ducking that under VO is tracked as a follow-up in PLAN.md.
- *
* ffmpeg floor: the VO graph uses `amix ... normalize=0` + `sidechaincompress`
* (ffmpeg 4.4+, 2021). On an older ffmpeg `muxVoLines` returns ok:false and the
* CD stitch falls back to `muxMusicBed`, which uses only `aresample`/`aformat`
@@ -34,7 +36,7 @@ import { rename, unlink } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { PATHS } from '../../lib/fileUtils.js';
-import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
+import { findFfmpeg, runFfmpegProcess, hasAudioStream } from '../../lib/ffmpeg.js';
import { statMusicTrack } from './musicLibrary.js';
// 0.5 ≈ -6 dB — quiet enough to sit under dialogue once VO mixing lands
@@ -141,14 +143,17 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAU
* - each VO line: delayed to its offset, resampled to the shared format
* - VO lines mixed into one track (`amix normalize=0` so speech stays at full
* level rather than being attenuated by 1/N)
- * - with music: the VO track is split — one copy keys a `sidechaincompress`
- * that ducks the (gained) music bed, the other is mixed back over the
- * ducked bed
+ * - beds to duck under VO: the (gained) music bed when `musicPath` is set, and
+ * the stitched video's own soundtrack (`[0:a]`) when `clipAudio` is set
+ * - with one or more beds: the padded VO track is split into a "mixed back"
+ * copy plus one sidechain key per bed (sidechaincompress consumes its key,
+ * so each bed needs its own copy). Each bed is `sidechaincompress`-ed
+ * against a VO key, then all ducked beds are mixed back over the VO
* - the final audio is `apad`-ed to infinity and paired with `-shortest` so
* the output always matches the VIDEO length (never truncates the episode
* to the last VO line, never trails silence past the video)
*/
-export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, outPath }) {
+export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, clipAudio = false, outPath }) {
const args = ['-i', inputVideoPath];
for (const line of voLines) args.push('-i', line.path);
if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);
@@ -170,22 +175,38 @@ export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain =
voMixLabel = '[vomix]';
}
+ // Beds ducked under VO. The music bed is the looped final input; the clip
+ // bed is the stitched video's own audio (`[0:a]`, gated on hasAudioStream
+ // upstream so we never reference a missing stream). Both get resampled to
+ // the shared format so amix/sidechaincompress inputs agree.
+ const beds = [];
if (musicPath) {
const musicIdx = voLines.length + 1;
const gain = Number(musicGain).toFixed(3);
- chains.push(`${voMixLabel}asplit=2[voscraw][vomain]`);
- // Pad the sidechain *key* to infinity (silence after the last VO line).
- // sidechaincompress ends with its shortest input, so a finite VO key would
- // cut the ducked bed off at the last line — the music would vanish for the
- // rest of the episode. With an infinite (silence-padded) key, the bed runs
- // the full video length: ducked under dialogue, full-level in the gaps.
- chains.push(`[voscraw]apad[vosc]`);
chains.push(`[${musicIdx}:a]volume=${gain},${AFMT}[bed]`);
- chains.push(`[bed][vosc]sidechaincompress=threshold=${duck.threshold}:ratio=${duck.ratio}:attack=${duck.attack}:release=${duck.release}[ducked]`);
- // `[vomain]` is the finite VO; `[ducked]` is bed-length (infinite via the
- // looped music). amix=longest keeps the bed past the VO; -shortest then
- // pins the whole output to the video length.
- chains.push(`[ducked][vomain]amix=inputs=2:normalize=0[aout]`);
+ beds.push('[bed]');
+ }
+ if (clipAudio) {
+ chains.push(`[0:a]${AFMT}[clip]`);
+ beds.push('[clip]');
+ }
+
+ if (beds.length) {
+ // Pad the VO to infinity (silence after the last line), then split it into
+ // one "mixed back" copy plus a sidechain key per bed. sidechaincompress
+ // ends with its shortest input, so a finite VO key would cut a ducked bed
+ // off at the last line; an infinite (silence-padded) key keeps every bed
+ // running the full video length — ducked under dialogue, full-level in the
+ // gaps. Padding the mixed-back copy too is harmless (it just adds silence).
+ const keys = beds.map((_, i) => `[vsck${i}]`);
+ chains.push(`${voMixLabel}apad,asplit=${beds.length + 1}[vomain]${keys.join('')}`);
+ const ducked = beds.map((bed, i) => {
+ chains.push(`${bed}${keys[i]}sidechaincompress=threshold=${duck.threshold}:ratio=${duck.ratio}:attack=${duck.attack}:release=${duck.release}[ducked${i}]`);
+ return `[ducked${i}]`;
+ });
+ // amix=longest keeps the (infinite) beds past the VO; -shortest then pins
+ // the whole output to the video length.
+ chains.push(`${ducked.join('')}[vomain]amix=inputs=${beds.length + 1}:normalize=0[aout]`);
} else {
chains.push(`${voMixLabel}apad[aout]`);
}
@@ -231,8 +252,15 @@ export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = nul
const ffmpeg = await findFfmpeg();
if (!ffmpeg) return { ok: false, reason: 'ffmpeg not on PATH' };
+ // Preserve the stitched clip's own soundtrack (LTX-2 audio-to-video) by
+ // mixing 0:a in, ducked under VO. Gate on hasAudioStream: referencing [0:a]
+ // in the filter graph against a silent AI-gen clip would abort the whole
+ // mux, and a probe failure (no ffprobe) safely defaults to the prior
+ // replace-the-track behavior.
+ const clipAudio = await hasAudioStream(inputVideoPath);
+
const tmpOut = `${inputVideoPath}.vomux.${randomUUID()}.mp4`;
- const args = buildVoMuxArgs({ inputVideoPath, voLines: placed, musicPath: usableMusic, musicGain, duck, outPath: tmpOut });
+ const args = buildVoMuxArgs({ inputVideoPath, voLines: placed, musicPath: usableMusic, musicGain, duck, clipAudio, outPath: tmpOut });
const result = await runFfmpegProcess({ bin: ffmpeg, args, signal });
if (!result.ok) {
@@ -240,7 +268,7 @@ export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = nul
return result;
}
await rename(tmpOut, inputVideoPath);
- return { ok: true, lineCount: placed.length, ducked: !!usableMusic };
+ return { ok: true, lineCount: placed.length, ducked: !!usableMusic, clipAudio };
}
export { DEFAULT_MUSIC_GAIN, DEFAULT_DUCK };
diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.js
index 004e0e99ce..f309668437 100644
--- a/server/services/pipeline/audioMux.test.js
+++ b/server/services/pipeline/audioMux.test.js
@@ -15,6 +15,10 @@ vi.mock('../../lib/fileUtils.js', async () => {
});
const findFfmpegMock = vi.fn();
+// hasAudioStream is mocked so muxVoLines tests deterministically control
+// whether the input video is treated as carrying a clip soundtrack — without
+// shelling out to a real ffprobe against the fake video fixtures.
+const hasAudioStreamMock = vi.fn();
// Pull the real runFfmpegProcess through — it's the helper audioMux now
// delegates to. The child_process mock below still intercepts spawn, so the
// real helper drives our fake ffmpeg.
@@ -23,6 +27,7 @@ vi.mock('../../lib/ffmpeg.js', async () => {
return {
...actual,
findFfmpeg: (...a) => findFfmpegMock(...a),
+ hasAudioStream: (...a) => hasAudioStreamMock(...a),
};
});
@@ -67,6 +72,10 @@ beforeEach(async () => {
mockExitCode = 0;
mockStderr = '';
findFfmpegMock.mockReset();
+ // Default: input video has no audio stream (matches today's silent AI-gen
+ // clips). Tests that exercise clip-audio preservation opt in explicitly.
+ hasAudioStreamMock.mockReset();
+ hasAudioStreamMock.mockResolvedValue(false);
await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
await mkdir(FAKE_MUSIC_DIR, { recursive: true });
});
@@ -236,14 +245,50 @@ describe('buildVoMuxArgs', () => {
// music is the looped last input (index 2 here: video=0, vo=1, music=2)
expect(args).toContain('-stream_loop');
const filter = args[args.indexOf('-filter_complex') + 1];
- expect(filter).toContain('asplit=2[voscraw][vomain]');
+ // One bed (music) → VO padded then split into the mixed-back copy + one
+ // sidechain key. The apad-before-split keeps the bed alive past the last
+ // VO line (sidechaincompress ends with its shortest input).
+ expect(filter).toContain('apad,asplit=2[vomain][vsck0]');
expect(filter).toContain('[2:a]volume=0.400');
expect(filter).toContain('sidechaincompress=threshold=');
- expect(filter).toContain('[bed][vosc]sidechaincompress');
- expect(filter).toContain('[ducked][vomain]amix=inputs=2:normalize=0[aout]');
- // The sidechain KEY must be padded to infinity so the music bed survives
- // past the last VO line (sidechaincompress ends with its shortest input).
- expect(filter).toContain('[voscraw]apad[vosc]');
+ expect(filter).toContain('[bed][vsck0]sidechaincompress');
+ expect(filter).toContain('[ducked0][vomain]amix=inputs=2:normalize=0[aout]');
+ });
+
+ it('mixes the clip soundtrack in as a second ducked bed alongside music', () => {
+ const args = buildVoMuxArgs({
+ inputVideoPath: '/v.mp4',
+ voLines: [{ path: '/a.wav', offsetSec: 0 }],
+ musicPath: '/m.mp3',
+ clipAudio: true,
+ outPath: '/out.mp4',
+ });
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ // The stitched video's own audio (0:a) is resampled and ducked under VO
+ // via its own sidechain key, the same way the music bed is.
+ expect(filter).toContain('[0:a]aresample=48000');
+ expect(filter).toMatch(/\[clip\]/);
+ // Two beds (music + clip) → VO split into mixed-back + two sidechain keys.
+ expect(filter).toContain('apad,asplit=3[vomain][vsck0][vsck1]');
+ expect(filter).toContain('[bed][vsck0]sidechaincompress');
+ expect(filter).toContain('[clip][vsck1]sidechaincompress');
+ expect(filter).toContain('[ducked0][ducked1][vomain]amix=inputs=3:normalize=0[aout]');
+ });
+
+ it('ducks the clip soundtrack under VO even with no music bed', () => {
+ const args = buildVoMuxArgs({
+ inputVideoPath: '/v.mp4',
+ voLines: [{ path: '/a.wav', offsetSec: 0 }],
+ clipAudio: true,
+ outPath: '/out.mp4',
+ });
+ // No music → no looped input, but the clip soundtrack is still preserved.
+ expect(args).not.toContain('-stream_loop');
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ expect(filter).toContain('[0:a]aresample=48000');
+ expect(filter).toContain('apad,asplit=2[vomain][vsck0]');
+ expect(filter).toContain('[clip][vsck0]sidechaincompress');
+ expect(filter).toContain('[ducked0][vomain]amix=inputs=2:normalize=0[aout]');
});
it('uses a single VO label without amix for one line', () => {
@@ -330,4 +375,39 @@ describe('muxVoLines', () => {
const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];
expect(filter).toContain('sidechaincompress');
});
+
+ it('preserves the clip soundtrack ducked under VO when the input has audio', async () => {
+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');
+ hasAudioStreamMock.mockResolvedValue(true);
+ const video = join(TEST_HOME, 'v.mp4');
+ const wav = join(TEST_HOME, 'a.wav');
+ await writeFile(video, Buffer.from('vid'));
+ await writeFile(wav, Buffer.from('wav'));
+
+ const result = await muxVoLines(video, { voLines: [{ path: wav, offsetSec: 1 }] });
+ expect(result.ok).toBe(true);
+ expect(result.clipAudio).toBe(true);
+ // VO-only request, but the clip's own audio is mixed in and ducked.
+ expect(result.ducked).toBe(false);
+ const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];
+ expect(filter).toContain('[0:a]aresample=48000');
+ expect(filter).toContain('[clip][vsck0]sidechaincompress');
+ });
+
+ it('skips the clip soundtrack when the input video is silent', async () => {
+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');
+ hasAudioStreamMock.mockResolvedValue(false);
+ const video = join(TEST_HOME, 'v.mp4');
+ const wav = join(TEST_HOME, 'a.wav');
+ await writeFile(video, Buffer.from('vid'));
+ await writeFile(wav, Buffer.from('wav'));
+
+ const result = await muxVoLines(video, { voLines: [{ path: wav, offsetSec: 1 }] });
+ expect(result.ok).toBe(true);
+ expect(result.clipAudio).toBe(false);
+ const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];
+ // A silent video must never have [0:a] referenced — that would abort ffmpeg.
+ expect(filter).not.toContain('[0:a]');
+ expect(filter).not.toContain('[clip]');
+ });
});