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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-863]): derive per-arc audio cues + multi-cue episode muxer
[._.]/ Adam Eivy46a3b0e7d885
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 7f0f62857d..d0e6589e70 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -263,6 +263,13 @@"returnsJson": true,"variables": []},+ "pipeline-audio-cues": {+ "name": "Pipeline — Audio Cue Planner",+ "description": "Break an episode's narrative beats into a small ordered list of per-arc-beat musical cues (one cue per emotional movement, not per scene), each with a self-contained text-to-music prompt + human label. Drives the whole-episode 'generated' audio mode; timing is placed at stitch time from rendered clip durations.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"story-builder-idea-expand": {"name": "Story Builder — Idea Expand","description": "Expand a one-line seed idea into a working title, logline, and a world-and-arc-ready premise for the Unified Story Builder's first step (seed intake mode). Seeds the universe starter prompt and the series premise.",diff --git a/data.reference/prompts/stages/pipeline-audio-cues.md b/data.reference/prompts/stages/pipeline-audio-cues.mdnew file mode 100644index 0000000000..98e14b2710--- /dev/null+++ b/data.reference/prompts/stages/pipeline-audio-cues.md@@ -0,0 +1,49 @@+# Pipeline — Audio Cue Planner++You are a film score supervisor planning the soundtrack for one episode. You read the episode's narrative beats and break them into a small ordered list of **musical cues** — one cue per *arc beat* (act / sequence / emotional movement), not one per scene. Each cue is a stretch of underscore with its own tone, written as a text-to-music generation prompt.++## Series++- **Title:** {{series.name}}+- **Tone / style:** {{series.styleNotes}}++## Episode++- **Number:** {{issue.number}}+- **Title:** {{issue.title}}++## Episode beats (the narrative arc — drive the cues from THIS)++```+{{episodeBeats}}+```++## Scene order ({{sceneCount}} storyboard scene(s))++```+{{scenesList}}+```++## How to plan the cues — read carefully++- **One cue per ARC BEAT, not per scene.** Most episodes have a handful of emotional movements (setup, rising tension, turn, climax, resolution). Group the scenes above under those movements and give each movement ONE cue. A typical episode is **3–6 cues**. Never exceed {{maxCues}}.+- **Follow the emotional shape, not the mechanical one.** Cue boundaries should fall at act/sequence turns — natural musical transition points — so a fade between cues reads as intentional, not choppy. Do not emit a cue per scene cut.+- **Each cue's prompt is a self-contained text-to-music prompt** (~15–40 words): instrumentation, mood, tempo/energy, genre cues. Bake in the series' tone/style. Describe the *music*, not the plot — an audio model has no story context. Examples: "slow warm ambient pads, sparse piano, contemplative, low energy"; "driving percussion, tense strings, rising synth, high urgency"; "resolving major-key strings, gentle, hopeful, mid tempo, fading out".+- **`label`** — a short human name for the beat the cue covers (e.g. "Act I — setup", "The chase", "Aftermath"). This is what the editor sees in the cue list.+- **Do NOT assign timing.** You do not know how long each scene's rendered clip is — leave placement to the stitch step. Emit cues in story order only.+- **Do NOT name an engine** unless the style clearly calls for one; the system picks a default generator.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "cues": [+ {+ "label": "Act I — setup",+ "prompt": "slow warm ambient pads, sparse piano, contemplative, low energy"+ }+ ]+}+```diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex 13ec2e3899..ea26b7d83e 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -187,6 +187,11 @@ export const hasAudioStream = async (videoPath) => {// Returns the basename on success, null when ffmpeg is missing or fails —// callers should treat null as "no thumbnail" rather than aborting the// parent operation.+// Probe a video's duration in seconds via ffprobe. Returns null when ffprobe is+// unavailable or the file has no parseable duration — callers must treat null as+// "unknown" rather than 0. Exported as `probeVideoDuration` for the cue-placement+// path (issue #863), which needs the episode length to lay arc cues onto the+// timeline.const probeDurationSeconds = async (videoPath) => {const stdout = await runFfprobe(['-v', 'error',@@ -197,6 +202,7 @@ const probeDurationSeconds = async (videoPath) => {const n = parseFloat(stdout);return Number.isFinite(n) && n > 0 ? n : null;};+export const probeVideoDuration = probeDurationSeconds;export const generateThumbnail = async (videoPath, jobId) => {await ensureDir(PATHS.videoThumbnails);diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex c0c759227b..02c43e6553 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -91,6 +91,7 @@ import {DEFAULT_ENGINE_ID,isEngineReady,} from '../services/pipeline/musicGen.js';+import { deriveAudioCues, preserveRenderedCues } from '../services/pipeline/audioCues.js';import { uploadSingle } from '../lib/multipart.js';import { parseComicScript } from '../lib/comicScriptParser.js';import {@@ -1072,6 +1073,143 @@ router.delete('/issues/:id/stages/audio/music', asyncHandler(async (req, res) =>res.json({ issue: updatedIssue, stage });}));+// Whole-episode audio cues (issue #863, step 3). The 'generated' audioMode lays+// an ordered cues[] array — one cue per narrative arc beat — onto the episode+// timeline at stitch time. These two routes derive the cue list from the+// episode's own beats and render each cue's audio.++// Derive the per-arc cue list from the episode's OWN beat prose (stages.idea) ++// storyboard scene order. Replaces the existing cues[] unless force is false and+// cues already exist (mirrors the extract-lines / extract-scenes overwrite+// guard). Already-rendered cue audio is carried forward by label so re-deriving+// doesn't silently invalidate every rendered WAV.+const cuesGenerateSchema = z.object({+ engine: z.enum(Object.keys(ENGINES)).optional(),+ providerOverride: z.string().trim().max(80).optional(),+ modelOverride: z.string().trim().max(128).optional(),+ force: z.boolean().optional(),+});+router.post('/issues/:id/stages/audio/cues/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(cuesGenerateSchema, req.body ?? {});+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'audio');+ const existing = Array.isArray(issue.stages?.audio?.cues) ? issue.stages.audio.cues : [];+ if (existing.length > 0 && !body.force) {+ throw new ServerError(+ `Audio stage already has ${existing.length} cue${existing.length === 1 ? '' : 's'} — pass { force: true } to replace`,+ { status: 409, code: 'PIPELINE_AUDIO_CUES_EXIST' },+ );+ }+ const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });+ // Inherit the series LLM unless the client overrides — same provider/model+ // resolution as the other Pipeline LLM actions (extract-scenes / extract-canon).+ const { provider, model } = resolveSeriesLlmOverride(series, {+ overrideProvider: body.providerOverride,+ overrideModel: body.modelOverride,+ });+ const result = await deriveAudioCues(issue, {+ defaultEngine: body.engine ?? DEFAULT_ENGINE_ID,+ providerOverride: provider,+ modelOverride: model,+ series: { name: series.name, styleNotes: series.styleNotes },+ }).catch((err) => { throw mapServiceError(err); });+ // Carry forward already-rendered cue audio (matched by label) so a re-derive+ // doesn't drop WAVs the user already generated.+ const cues = preserveRenderedCues(result.cues, existing);+ // Deriving cues implies the user wants the episode-level generated soundtrack —+ // flip audioMode to 'generated' so the muxer picks up the cues at stitch time.+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ req.params.id,+ 'audio',+ () => ({ audioMode: 'generated', cues, lastRunId: result.runId, errorMessage: '' }),+ ).catch((err) => { throw mapServiceError(err); });+ res.json({+ issue: updatedIssue, stage,+ cues: stage.cues,+ cueCount: stage.cues.length,+ runId: result.runId,+ providerId: result.providerId,+ model: result.model,+ });+}));++// Render one cue's audio via the generator-agnostic generateMusic contract,+// stamping trackFilename + durationSec back into that cue. Mirrors the per-line+// render route. The duration is the cue's placed timeline span (endSec-startSec)+// when placed, else the requested durationSec, else the engine default —+// per-engine clampDuration in generateMusic guards the final value.+const cueRenderSchema = z.object({+ engine: z.enum(Object.keys(ENGINES)).optional(),+ durationSec: z.number().min(1).max(MAX_ENGINE_DURATION).optional(),+ modelId: z.enum(ALL_MODEL_IDS).optional(),+});+router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler(async (req, res) => {+ const cueIdx = Number(req.params.cueIdx);+ if (!Number.isInteger(cueIdx) || cueIdx < 0) {+ throw new ServerError('cueIdx must be a non-negative integer', {+ status: 400, code: 'PIPELINE_AUDIO_BAD_INDEX',+ });+ }+ const body = validateRequest(cueRenderSchema, req.body ?? {});+ // Guard the expensive generation behind a 404 + range check first so we don't+ // burn GPU time only to discover the issue/cue is gone (orphaning the WAV).+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'audio');+ const cues = Array.isArray(issue.stages?.audio?.cues) ? issue.stages.audio.cues : [];+ const cue = cues[cueIdx];+ if (!cue) {+ throw new ServerError(`cueIdx ${cueIdx} out of range (have ${cues.length})`, {+ status: 404, code: 'PIPELINE_AUDIO_CUE_NOT_FOUND',+ });+ }+ if (!cue.prompt) {+ throw new ServerError('Cue has no prompt to render — derive cues first', {+ status: 400, code: 'PIPELINE_AUDIO_CUE_NO_PROMPT',+ });+ }+ // Duration priority: an explicit body override → the placed timeline span+ // (endSec-startSec when both are placed) → the engine default (generateMusic+ // resolves undefined to the engine's defaultDurationSec). Engine resolution+ // priority: body → the cue's own engine hint → the global default.+ const span = (typeof cue.startSec === 'number' && typeof cue.endSec === 'number' && cue.endSec > cue.startSec)+ ? cue.endSec - cue.startSec+ : undefined;+ const engine = body.engine ?? cue.engine ?? DEFAULT_ENGINE_ID;+ const gen = await generateMusic({+ prompt: cue.prompt,+ engine,+ durationSec: body.durationSec ?? span,+ modelId: body.modelId,+ }).catch((err) => { throw mapServiceError(err); });+ // Merge against the freshest persisted cue inside the write queue so a+ // concurrent re-derive can't clobber the render (the cue list is re-read here).+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ req.params.id,+ 'audio',+ (current) => {+ const curCues = Array.isArray(current?.cues) ? current.cues : [];+ const target = curCues[cueIdx];+ if (!target) return {};+ const nextCues = [...curCues];+ nextCues[cueIdx] = {+ ...target,+ engine: gen.engine,+ trackFilename: gen.filename,+ durationSec: gen.durationSec,+ };+ return { cues: nextCues, errorMessage: '' };+ },+ ).catch((err) => { throw mapServiceError(err); });+ res.json({+ issue: updatedIssue, stage, cueIdx,+ cue: stage.cues[cueIdx],+ trackFilename: gen.filename,+ durationSec: gen.durationSec,+ engine: gen.engine,+ modelId: gen.modelId,+ });+}));+// Deleting from the library leaves stale `music.trackFilename` pointers on// issues so the user sees the broken playback and re-picks. Auto-purging// would scan every issue on every delete; deferred until needed.diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 5480a34713..c4b8601f81 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -270,6 +270,29 @@ vi.mock('../services/pipeline/musicLibrary.js', () => ({}),}));+// Music generation (musicGen.js) — keep the real ENGINES registry + helpers+// (the route builds Zod enums from them at module load) but stub generateMusic+// so cue-render tests never spawn the Python sidecar.+const generateMusicMock = vi.fn(async ({ engine }) => ({+ filename: `music-gen-mock-${++uuidCounter}.wav`,+ durationSec: 18,+ modelId: 'musicgen-medium',+ model: 'MusicGen Medium',+ engine: engine || 'musicgen',+}));+vi.mock('../services/pipeline/musicGen.js', async () => {+ const actual = await vi.importActual('../services/pipeline/musicGen.js');+ return { ...actual, generateMusic: (...a) => generateMusicMock(...a) };+});++// Audio cue derivation (audioCues.js) — stub the LLM-backed derivation but keep+// the real preserveRenderedCues helper so the carry-forward path is exercised.+let deriveAudioCuesSpy;+vi.mock('../services/pipeline/audioCues.js', async () => {+ const actual = await vi.importActual('../services/pipeline/audioCues.js');+ return { ...actual, deriveAudioCues: (...a) => deriveAudioCuesSpy(...a) };+});+vi.mock('../lib/multipart.js', () => ({uploadSingle: () => (req, _res, next) => {req.file = req.body?._mockFile || null;@@ -2326,6 +2349,149 @@ describe('pipeline routes', () => {});});+ // ---- whole-episode audio cues (issue #863, steps 3+4) ----+ describe('audio cue routes', () => {+ beforeEach(() => {+ // Default derivation stub: two arc cues with prompts, no timing/render yet.+ deriveAudioCuesSpy = vi.fn(async () => ({+ cues: [+ { id: 'cue-001', label: 'Act I — setup', prompt: 'warm ambient pads', engine: 'musicgen', startSec: null, endSec: null, trackFilename: null, durationSec: null, gain: null },+ { id: 'cue-002', label: 'Climax', prompt: 'driving percussion, tense', engine: 'musicgen', startSec: null, endSec: null, trackFilename: null, durationSec: null, gain: null },+ ],+ runId: 'cue-run-1', providerId: 'p', model: 'm',+ }));+ generateMusicMock.mockClear();+ });++ async function seedIssueWithBeats(app) {+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { idea: { status: 'ready', output: 'Act 1: setup. Act 2: rising. Act 3: climax then resolution.' } },+ });+ return iss.body;+ }++ it('POST /audio/cues/generate derives cues and flips audioMode to generated', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`)+ .send({});+ expect(r.status).toBe(200);+ expect(r.body.cueCount).toBe(2);+ expect(r.body.stage.audioMode).toBe('generated');+ expect(r.body.stage.cues[0]).toMatchObject({ label: 'Act I — setup', prompt: 'warm ambient pads' });+ // Persisted on the issue.+ const after = await request(app).get(`/api/pipeline/issues/${iss.id}`);+ expect(after.body.stages.audio.cues).toHaveLength(2);+ expect(after.body.stages.audio.audioMode).toBe('generated');+ });++ it('POST /audio/cues/generate 409s when cues already exist without force', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`).send({});+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`)+ .send({});+ expect(r.status).toBe(409);+ });++ it('POST /audio/cues/generate with force:true replaces existing cues', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`).send({});+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`)+ .send({ force: true });+ expect(r.status).toBe(200);+ expect(r.body.cueCount).toBe(2);+ });++ it('POST /audio/cues/generate carries forward a previously-rendered cue by label', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ // First derive + render cue 0 so it has a trackFilename.+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`).send({});+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/0/render`).send({});+ // Re-derive (force) — the same label should keep the rendered track.+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`)+ .send({ force: true });+ expect(r.status).toBe(200);+ const carried = r.body.stage.cues.find((c) => c.label === 'Act I — setup');+ expect(carried.trackFilename).toMatch(/^music-gen-mock-/);+ });++ it('POST /audio/cues/generate 400s when the issue has no idea beats', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });+ // Real derivation throws PIPELINE_AUDIO_CUES_NO_SOURCE for an empty idea —+ // route the spy through the real implementation for this case.+ const real = await vi.importActual('../services/pipeline/audioCues.js');+ deriveAudioCuesSpy = (...a) => real.deriveAudioCues(...a);+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/audio/cues/generate`)+ .send({});+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('PIPELINE_AUDIO_CUES_NO_SOURCE');+ });++ it('POST /audio/cues/:idx/render renders one cue and stamps trackFilename + durationSec', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`).send({});+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/1/render`)+ .send({});+ expect(r.status).toBe(200);+ expect(r.body.cueIdx).toBe(1);+ expect(r.body.trackFilename).toMatch(/^music-gen-mock-/);+ expect(r.body.durationSec).toBe(18);+ // Engine resolves from the cue's own hint when no body override.+ expect(generateMusicMock).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'driving percussion, tense', engine: 'musicgen' }));+ const after = await request(app).get(`/api/pipeline/issues/${iss.id}`);+ expect(after.body.stages.audio.cues[1].trackFilename).toMatch(/^music-gen-mock-/);+ expect(after.body.stages.audio.cues[1].durationSec).toBe(18);+ });++ it('POST /audio/cues/:idx/render passes the placed span as durationSec', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`).send({});+ // Place cue 0 with a 12s span via the issue PATCH (audio arm).+ await request(app).patch(`/api/pipeline/issues/${iss.id}`).send({+ stages: { audio: { audioMode: 'generated', cues: [+ { id: 'cue-001', label: 'Act I — setup', prompt: 'warm ambient pads', engine: 'musicgen', startSec: 4, endSec: 16 },+ { id: 'cue-002', label: 'Climax', prompt: 'driving percussion, tense', engine: 'musicgen' },+ ] } },+ });+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/0/render`).send({});+ expect(generateMusicMock).toHaveBeenCalledWith(expect.objectContaining({ durationSec: 12 }));+ });++ it('POST /audio/cues/:idx/render 404s for an out-of-range index', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/generate`).send({});+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/9/render`)+ .send({});+ expect(r.status).toBe(404);+ });++ it('POST /audio/cues/:idx/render 400s for a non-integer index', async () => {+ const app = makeApp();+ const iss = await seedIssueWithBeats(app);+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/cues/nope/render`)+ .send({});+ expect(r.status).toBe(400);+ });+ });+describe('music library routes', () => {beforeEach(() => {musicLibraryStore.clear();diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.jsindex 3c81533a52..92946e6bc9 100644--- a/server/services/creativeDirector/stitchRunner.js+++ b/server/services/creativeDirector/stitchRunner.js@@ -24,8 +24,10 @@ import { addItem as addCollectionItem } from '../mediaCollections.js';import { buildTimelineClips } from './orchestrator.js';import { getProject, updateProject } from './local.js';import { getIssue } from '../pipeline/issues.js';-import { muxMusicBed, muxVoLines, resolveMusicTrackPath, selectPlacedVoLines } from '../pipeline/audioMux.js';+import { muxMusicBed, muxVoLines, muxCueBed, muxStripAudio, resolveMusicTrackPath, selectPlacedVoLines, selectPlacedCues } from '../pipeline/audioMux.js';+import { placeCuesOnTimeline } from '../pipeline/audioCuePlacement.js';import { PATHS } from '../../lib/fileUtils.js';+import { probeVideoDuration } from '../../lib/ffmpeg.js';const FINAL_RENDER_POLL_MS = 3000;const FINAL_RENDER_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes — concat is fast but be generous on big projects.@@ -140,19 +142,76 @@ async function maybeMuxPipelineAudio(project, finalEntry) {console.log(`⚠️ CD stitch mux: source issue ${project.sourceIssueId.slice(0, 8)} not found — skipping`);return;}- const musicFilename = issue.stages?.audio?.music?.trackFilename;- const musicPath = await resolveMusicTrackPath(musicFilename);- // Placed VO lines — rendered AND positioned (see selectPlacedVoLines). When- // any exist, the VO pass (which also ducks the music bed under dialogue)- // supersedes the music-only bed.+ const videoPath = join(PATHS.videos, finalEntry.filename);+ // Whole-episode audio strategy (issue #863). Absent / unknown audioMode reads+ // as 'per-clip' (the sanitizer already defaults it), so existing issues keep+ // today's behavior. Placed VO lines are muxable in every non-silent mode.+ const audioMode = issue.stages?.audio?.audioMode || 'per-clip';const voLines = selectPlacedVoLines(issue.stages?.audio?.lines);+ // 'generated' — assemble the arc-driven cues[] onto the timeline. Cue timing+ // is derived HERE from the rendered episode's duration (the design defers+ // placement to stitch time). Falls back to the music-bed path only if there+ // are no placed+rendered cues.+ if (audioMode === 'generated') {+ const cues = Array.isArray(issue.stages?.audio?.cues) ? issue.stages.audio.cues : [];+ const rendered = cues.filter((c) => c?.trackFilename);+ if (rendered.length) {+ const totalSec = await probeVideoDuration(videoPath);+ const placed = selectPlacedCues(placeCuesOnTimeline(rendered, totalSec));+ if (placed.length) {+ console.log(`🎼 CD stitch mux: laying ${placed.length} generated cue(s)${voLines.length ? ` + ${voLines.length} VO line(s)` : ''} onto ${finalEntry.filename}`);+ const result = await muxCueBed(videoPath, { cues: placed, voLines });+ if (result.ok) {+ console.log(`✅ CD stitch mux: cue bed applied to ${finalEntry.filename} (${result.cueCount} cue(s)${result.ducked ? ', VO ducked' : ''}${result.clipAudio ? ', clip audio preserved' : ''})`);+ return;+ }+ console.log(`⚠️ CD stitch mux: cue bed skipped (${result.reason}) — keeping clip audio`);+ } else {+ console.log(`⚠️ CD stitch mux: generated mode but no placeable cues (episode duration unknown?) — keeping clip audio`);+ }+ } else {+ console.log(`⚠️ CD stitch mux: generated mode but no rendered cues — keeping clip audio`);+ }+ // No cue bed landed. If VO lines are placed, still overlay them (no music+ // bed) so dialogue isn't lost; otherwise leave the clip audio as-is.+ if (voLines.length) {+ const result = await muxVoLines(videoPath, { voLines, musicPath: null });+ if (result.ok) console.log(`✅ CD stitch mux: VO-only overlay applied to ${finalEntry.filename}`);+ }+ return;+ }++ // 'silent' — strip the clip's own soundtrack (the design mutes the bed AND the+ // clip audio). Strip first, then overlay any placed VO over the now-silent+ // video: the VO mux re-probes and finds no audio stream, so dialogue plays+ // with no clip bed underneath — "ducked over silence" per the design table.+ if (audioMode === 'silent') {+ console.log(`🔇 CD stitch mux: silent mode — stripping clip audio${voLines.length ? ` + overlaying ${voLines.length} VO line(s)` : ''} on ${finalEntry.filename}`);+ const stripped = await muxStripAudio(videoPath);+ if (!stripped.ok) {+ console.log(`⚠️ CD stitch mux: silent strip skipped (${stripped.reason}) — keeping output`);+ return;+ }+ if (voLines.length) {+ const result = await muxVoLines(videoPath, { voLines, musicPath: null });+ if (result.ok) console.log(`✅ CD stitch mux: VO applied over silence to ${finalEntry.filename}`);+ else console.log(`⚠️ CD stitch mux: VO skipped (${result.reason}) — silent video kept`);+ } else {+ console.log(`✅ CD stitch mux: silent episode (clip audio stripped) for ${finalEntry.filename}`);+ }+ return;+ }++ // 'uploaded-track' (and 'per-clip') — today's single-music-pointer path.+ // 'per-clip' has no music pointer so it preserves each clip's own soundtrack.+ const musicFilename = issue.stages?.audio?.music?.trackFilename;+ const musicPath = await resolveMusicTrackPath(musicFilename);+// Nothing to overlay — no placed VO and no music. Leave the stitch as-is.if (!voLines.length && !musicPath) return;- const videoPath = join(PATHS.videos, finalEntry.filename);-if (voLines.length) {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 });diff --git a/server/services/pipeline/audioCuePlacement.js b/server/services/pipeline/audioCuePlacement.jsnew file mode 100644index 0000000000..351104dbb6--- /dev/null+++ b/server/services/pipeline/audioCuePlacement.js@@ -0,0 +1,73 @@+/**+ * Pure cue → timeline placement for whole-episode audio (issue #863, step 4).+ *+ * Cues are derived per-arc-beat in story order (audioCues.js) but carry no+ * timeline position — the design defers `startSec`/`endSec` to episode-stitch+ * time, because the only real source of timing is the rendered episode's+ * duration (storyboard scenes carry no per-scene duration, and the VO+ * `offsetSec` is a manually-placed audio offset, not a scene-timing source).+ *+ * This module owns that placement: given the ordered cues and the total episode+ * duration (ffprobed at stitch time), it lays each story-order cue onto the+ * absolute timeline so the cues tile the episode end-to-end. A cue's own+ * rendered `durationSec` is honored when present (so a 30s sting stays 30s);+ * unrendered cues split the remaining time evenly. The result is the+ * `startSec`/`endSec` the cue muxer (`buildCueMuxArgs`) places each cue at.+ *+ * Pure + unit-tested — no ffprobe, no filesystem. The caller probes the+ * duration and passes it in.+ */++/**+ * Place an ordered cue list onto a timeline of `totalDurationSec`. Returns a NEW+ * cue array (cues unchanged in identity) with `startSec`/`endSec` filled.+ *+ * Strategy: walk cues in order, advancing a cursor. Each cue spans from the+ * cursor to cursor + its length, where length is the cue's rendered+ * `durationSec` when it's a finite positive number, otherwise an even share of+ * the time still unclaimed by the remaining cues. The final cue is pinned to+ * end exactly at `totalDurationSec` so the bed covers the whole episode (no+ * trailing gap from rounding). Cues that would start past the episode end are+ * clamped to a zero-length tail at the end (the muxer drops zero/negative-span+ * cues via its placed-cue filter).+ *+ * @param {Array} cues ordered cue objects (need at least `id`)+ * @param {number} totalDurationSec episode length in seconds (> 0)+ * @returns {Array} cues with startSec/endSec set+ */+export function placeCuesOnTimeline(cues, totalDurationSec) {+ if (!Array.isArray(cues) || cues.length === 0) return [];+ const total = Number(totalDurationSec);+ if (!Number.isFinite(total) || total <= 0) {+ // No usable duration — leave timing null (un-placed); the muxer skips them.+ return cues.map((c) => ({ ...c, startSec: null, endSec: null }));+ }++ const out = [];+ let cursor = 0;+ for (let i = 0; i < cues.length; i += 1) {+ const cue = cues[i];+ const remainingCues = cues.length - i;+ const remainingTime = Math.max(0, total - cursor);+ const rendered = Number(cue?.durationSec);+ const hasRendered = Number.isFinite(rendered) && rendered > 0;++ let length;+ if (i === cues.length - 1) {+ // Last cue: fill to the end so the bed covers the whole episode.+ length = remainingTime;+ } else if (hasRendered) {+ // Honor the cue's actual rendered length, but never overrun the timeline.+ length = Math.min(rendered, remainingTime);+ } else {+ // Even share of the time still unclaimed by the cues that remain.+ length = remainingTime / remainingCues;+ }++ const startSec = Math.min(cursor, total);+ const endSec = Math.min(cursor + length, total);+ out.push({ ...cue, startSec, endSec });+ cursor = endSec;+ }+ return out;+}diff --git a/server/services/pipeline/audioCuePlacement.test.js b/server/services/pipeline/audioCuePlacement.test.jsnew file mode 100644index 0000000000..ebcc9098d2--- /dev/null+++ b/server/services/pipeline/audioCuePlacement.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';+import { placeCuesOnTimeline } from './audioCuePlacement.js';++describe('placeCuesOnTimeline', () => {+ it('returns [] for empty / non-array input', () => {+ expect(placeCuesOnTimeline([], 100)).toEqual([]);+ expect(placeCuesOnTimeline(null, 100)).toEqual([]);+ });++ it('leaves timing null when the duration is unknown', () => {+ const cues = [{ id: 'cue-001' }, { id: 'cue-002' }];+ const placed = placeCuesOnTimeline(cues, null);+ expect(placed).toHaveLength(2);+ expect(placed.every((c) => c.startSec === null && c.endSec === null)).toBe(true);+ });++ it('leaves timing null for a non-positive duration', () => {+ const placed = placeCuesOnTimeline([{ id: 'cue-001' }], 0);+ expect(placed[0].startSec).toBeNull();+ });++ it('tiles cues end-to-end across the episode, last cue pinned to the end', () => {+ const cues = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];+ const placed = placeCuesOnTimeline(cues, 90);+ // Even split (no rendered durations): 30s each.+ expect(placed[0].startSec).toBe(0);+ expect(placed[0].endSec).toBeCloseTo(30, 5);+ expect(placed[1].startSec).toBeCloseTo(30, 5);+ expect(placed[2].endSec).toBe(90); // pinned to the episode end+ // Contiguous: each cue starts where the previous ended.+ expect(placed[1].startSec).toBeCloseTo(placed[0].endSec, 5);+ expect(placed[2].startSec).toBeCloseTo(placed[1].endSec, 5);+ });++ it('honors a cue rendered durationSec, splitting the rest evenly', () => {+ const cues = [+ { id: 'a', durationSec: 20 }, // honored+ { id: 'b' },+ { id: 'c' },+ ];+ const placed = placeCuesOnTimeline(cues, 100);+ expect(placed[0].endSec).toBeCloseTo(20, 5); // honored rendered length+ // remaining 80s split across the 2 remaining cues → 40 each, last pinned to 100+ expect(placed[1].startSec).toBeCloseTo(20, 5);+ expect(placed[1].endSec).toBeCloseTo(60, 5);+ expect(placed[2].endSec).toBe(100);+ });++ it('clamps a rendered duration that would overrun the timeline', () => {+ const cues = [{ id: 'a', durationSec: 500 }, { id: 'b' }];+ const placed = placeCuesOnTimeline(cues, 60);+ // First cue can't run past the episode; last cue pinned to the end.+ expect(placed[0].endSec).toBeLessThanOrEqual(60);+ expect(placed[1].endSec).toBe(60);+ // A clamped first cue can leave the last cue a zero-length tail — that's fine,+ // the muxer's placed-cue filter drops zero/negative spans.+ expect(placed[1].startSec).toBeLessThanOrEqual(60);+ });++ it('preserves cue identity fields (id/label/prompt) while adding timing', () => {+ const cues = [{ id: 'cue-001', label: 'Act I', prompt: 'pads' }];+ const placed = placeCuesOnTimeline(cues, 30);+ expect(placed[0]).toMatchObject({ id: 'cue-001', label: 'Act I', prompt: 'pads', startSec: 0, endSec: 30 });+ });+});diff --git a/server/services/pipeline/audioCues.js b/server/services/pipeline/audioCues.jsnew file mode 100644index 0000000000..46861c7c1a--- /dev/null+++ b/server/services/pipeline/audioCues.js@@ -0,0 +1,203 @@+/**+ * Pipeline audio cues — arc-driven cue derivation for whole-episode audio+ * (issue #863 / design doc 2026-06-03-whole-episode-audio-strategy.md, step 3).+ *+ * `audioMode: 'generated'` lays an ordered `cues[]` array — one cue per+ * *narrative arc beat* — onto the episode timeline at stitch time. This module+ * owns the LLM pass that DERIVES that cue list from the episode's own beat+ * prose (`stages.idea` — `.output` beats, `.input` synopsis seed) plus the+ * storyboard scene ordering. Following the design's timing discussion and the+ * #736 reviewers' correction:+ *+ * - the beats come from the ISSUE's own `stages.idea`, NOT from series-level+ * arcPlanner output (arcPlanner operates at the season/series level and+ * emits no per-episode act/sequence structure);+ * - storyboard `scenes[]` give the scene ORDER but carry no sanitized+ * per-scene duration, so a cue's `startSec`/`endSec` stay `null` at+ * derivation time — they are placed at episode-stitch time from the+ * rendered clips' real durations (the cue muxer in audioMux.js / the+ * stitch runner owns that placement). This module synthesizes only the+ * per-cue PROMPT + human label + ordering.+ *+ * Extraction-only, mirroring sceneExtractor.js / arcPlanner.js: the LLM call ++ * sanitization live here, the route owns persistence. Returns+ * `{ cues, runId, providerId, model }`; the route stamps the cues into+ * `stages.audio.cues` (preserving any already-rendered cue's trackFilename+ * where the label still matches, like the per-line render-preserve on+ * re-extract).+ */++import { runStagedLLM } from '../../lib/stageRunner.js';+import { ServerError } from '../../lib/errorHandler.js';+import { trimTo } from '../../lib/storyBible.js';+import {+ AUDIO_CUES_MAX,+ AUDIO_CUE_LABEL_MAX,+ AUDIO_CUE_PROMPT_MAX,+} from './issues.js';++export const ERR_NO_SOURCE = 'PIPELINE_AUDIO_CUES_NO_SOURCE';+export const ERR_EMPTY_RESULT = 'PIPELINE_AUDIO_CUES_EMPTY';++const AUDIO_CUES_STAGE = 'pipeline-audio-cues';++// Compact scene-order summary fed to the prompt so the LLM can size the number+// of arc cues against how much screen time the episode actually has. We pass+// scene headings/summaries (no per-scene timing — there is none) so the cue+// boundaries follow the emotional arc, not a mechanical per-scene split.+const SCENE_SUMMARY_MAX = 240;+const SCENES_FOR_PROMPT_MAX = 120;++function renderScenesForPrompt(scenes) {+ if (!Array.isArray(scenes) || scenes.length === 0) {+ return '(no storyboard scenes yet — derive cues from the episode beats alone)';+ }+ return scenes+ .slice(0, SCENES_FOR_PROMPT_MAX)+ .map((s, i) => {+ const heading = trimTo(s?.heading, 120) || `Scene ${i + 1}`;+ const summary = trimTo(s?.summary, SCENE_SUMMARY_MAX)+ || trimTo(s?.description, SCENE_SUMMARY_MAX)+ || trimTo(s?.visualPrompt, SCENE_SUMMARY_MAX);+ return summary ? `${i + 1}. ${heading} — ${summary}` : `${i + 1}. ${heading}`;+ })+ .join('\n');+}++// The richest episode-beat text available: the LLM-expanded beats+// (`idea.output`) preferred over the synopsis seed (`idea.input`). Trimmed so a+// runaway draft can't blow the prompt budget.+const IDEA_TEXT_MAX = 24_000;+function episodeBeatText(issue) {+ const out = (issue?.stages?.idea?.output || '').trim();+ const input = (issue?.stages?.idea?.input || '').trim();+ return (out || input).slice(0, IDEA_TEXT_MAX);+}++/**+ * Sanitize one LLM-emitted cue into the un-rendered/un-placed cue shape the+ * issue sanitizer (sanitizeAudioCue) will re-validate on persist. We set only+ * the fields derivation OWNS — id/label/prompt/engine — and leave the timeline+ * (startSec/endSec) + render (trackFilename/durationSec) fields null so the+ * design's null-vs-0 sentinel discipline holds: a freshly-derived cue is "not+ * placed, not rendered" until the muxer places it and the render route fills+ * trackFilename.+ */+function sanitizeDerivedCue(raw, i, defaultEngine) {+ if (!raw || typeof raw !== 'object') return null;+ const prompt = trimTo(raw.prompt, AUDIO_CUE_PROMPT_MAX);+ // A cue with no prompt can never render — drop it rather than persist a dead+ // entry the render route would 400 on.+ if (!prompt) return null;+ return {+ id: `cue-${String(i + 1).padStart(3, '0')}`,+ label: trimTo(raw.label, AUDIO_CUE_LABEL_MAX) || `Cue ${i + 1}`,+ prompt,+ // Honor a per-cue engine hint when the LLM names one; else fall back to the+ // stage/global default engine so the render route has a concrete target.+ engine: trimTo(raw.engine, 80) || defaultEngine || null,+ startSec: null,+ endSec: null,+ trackFilename: null,+ durationSec: null,+ gain: null,+ };+}++/**+ * Carry forward an already-rendered cue's audio when a re-derivation produces a+ * cue with the same (case-insensitive) label — otherwise re-deriving cues would+ * silently invalidate every previously-rendered cue WAV (mirrors the per-line+ * render-preserve on audio extract-lines). Match on label because ids are+ * positional and re-derivation reshuffles them. Only the render artifacts+ * (trackFilename/durationSec) carry over; prompt/engine come from the fresh+ * derivation so a re-derive can re-tone an existing cue.+ */+export function preserveRenderedCues(freshCues, priorCues) {+ if (!Array.isArray(priorCues) || priorCues.length === 0) return freshCues;+ const renderedByLabel = new Map();+ for (const c of priorCues) {+ const key = (c?.label || '').trim().toLowerCase();+ if (key && c?.trackFilename) renderedByLabel.set(key, c);+ }+ if (renderedByLabel.size === 0) return freshCues;+ return freshCues.map((cue) => {+ const prior = renderedByLabel.get((cue.label || '').trim().toLowerCase());+ if (!prior) return cue;+ return { ...cue, trackFilename: prior.trackFilename, durationSec: prior.durationSec ?? null };+ });+}++/**+ * Derive the arc-beat cue list for one episode. Reads the issue's OWN beat prose+ * (stages.idea) + storyboard scene order, runs the cue-planning LLM pass, and+ * returns sanitized un-rendered cues. Throws a ServerError(400) when the episode+ * has no beat text to derive from.+ *+ * @param {object} issue the pipeline issue record+ * @param {object} [opts]+ * @param {string} [opts.defaultEngine] engine id to stamp when a cue omits one+ * @param {string} [opts.providerOverride]+ * @param {string} [opts.modelOverride]+ * @param {object} [opts.series] `{ name, styleNotes }` for prompt grounding+ */+export async function deriveAudioCues(issue, {+ defaultEngine,+ providerOverride,+ modelOverride,+ series,+} = {}) {+ const beats = episodeBeatText(issue);+ if (!beats) {+ throw new ServerError(+ "Cannot derive audio cues — the episode's Idea stage has no beats or synopsis to drive the arc",+ { status: 400, code: ERR_NO_SOURCE },+ );+ }+ const scenes = Array.isArray(issue?.stages?.storyboards?.scenes)+ ? issue.stages.storyboards.scenes+ : [];++ const { content, runId, providerId, model } = await runStagedLLM(+ AUDIO_CUES_STAGE,+ {+ returnsJson: true,+ series: { name: series?.name || '', styleNotes: series?.styleNotes || '' },+ issue: { number: issue?.number ?? '', title: issue?.title || '' },+ episodeBeats: beats,+ scenesList: renderScenesForPrompt(scenes),+ sceneCount: scenes.length,+ maxCues: AUDIO_CUES_MAX,+ },+ {+ providerOverride,+ modelOverride,+ returnsJson: true,+ source: 'pipeline-audio-cues',+ },+ );++ const rawCues = Array.isArray(content?.cues) ? content.cues : [];+ const cues = rawCues+ .slice(0, AUDIO_CUES_MAX)+ .map((c, i) => sanitizeDerivedCue(c, i, defaultEngine))+ .filter(Boolean)+ // Re-index ids after the filter so they stay sequential cue-001..N.+ .map((cue, i) => ({ ...cue, id: `cue-${String(i + 1).padStart(3, '0')}` }));++ if (cues.length === 0) {+ throw new ServerError(+ 'The cue planner returned no usable cues — try regenerating',+ { status: 502, code: ERR_EMPTY_RESULT },+ );+ }++ return { cues, runId, providerId, model };+}++// Export internals for unit tests (the sanitizer is the load-bearing pure part).+export const __testing = {+ sanitizeDerivedCue,+ renderScenesForPrompt,+ episodeBeatText,+};diff --git a/server/services/pipeline/audioCues.test.js b/server/services/pipeline/audioCues.test.jsnew file mode 100644index 0000000000..3f784a52b8--- /dev/null+++ b/server/services/pipeline/audioCues.test.js@@ -0,0 +1,139 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Stub the LLM driver so deriveAudioCues never hits a provider.+const runStagedLLMMock = vi.fn();+vi.mock('../../lib/stageRunner.js', () => ({+ runStagedLLM: (...a) => runStagedLLMMock(...a),+}));++const {+ deriveAudioCues,+ preserveRenderedCues,+ ERR_NO_SOURCE,+ ERR_EMPTY_RESULT,+ __testing,+} = await import('./audioCues.js');++describe('audioCues — pure internals', () => {+ describe('episodeBeatText', () => {+ it('prefers idea.output (beats) over idea.input (synopsis)', () => {+ const issue = { stages: { idea: { output: 'BEATS', input: 'SYNOPSIS' } } };+ expect(__testing.episodeBeatText(issue)).toBe('BEATS');+ });+ it('falls back to idea.input when output is empty', () => {+ const issue = { stages: { idea: { output: ' ', input: 'SYNOPSIS' } } };+ expect(__testing.episodeBeatText(issue)).toBe('SYNOPSIS');+ });+ it('returns empty string when neither is present', () => {+ expect(__testing.episodeBeatText({ stages: { idea: {} } })).toBe('');+ expect(__testing.episodeBeatText({})).toBe('');+ });+ });++ describe('renderScenesForPrompt', () => {+ it('returns the no-scenes placeholder for an empty list', () => {+ expect(__testing.renderScenesForPrompt([])).toMatch(/no storyboard scenes/i);+ expect(__testing.renderScenesForPrompt(null)).toMatch(/no storyboard scenes/i);+ });+ it('numbers scenes and prefers heading + summary', () => {+ const out = __testing.renderScenesForPrompt([+ { heading: 'The kitchen', summary: 'Jean waits.' },+ { heading: 'The roof' },+ ]);+ expect(out).toContain('1. The kitchen — Jean waits.');+ expect(out).toContain('2. The roof');+ });+ });++ describe('sanitizeDerivedCue', () => {+ it('drops a cue with no prompt', () => {+ expect(__testing.sanitizeDerivedCue({ label: 'x' }, 0, 'musicgen')).toBeNull();+ });+ it('builds an un-rendered, un-placed cue with sequential id + default engine', () => {+ const cue = __testing.sanitizeDerivedCue({ label: 'Act I', prompt: 'pads' }, 0, 'audioldm2');+ expect(cue).toMatchObject({+ id: 'cue-001', label: 'Act I', prompt: 'pads', engine: 'audioldm2',+ startSec: null, endSec: null, trackFilename: null, durationSec: null, gain: null,+ });+ });+ it('honors a per-cue engine hint over the default', () => {+ const cue = __testing.sanitizeDerivedCue({ prompt: 'p', engine: 'suno' }, 3, 'musicgen');+ expect(cue.engine).toBe('suno');+ expect(cue.id).toBe('cue-004');+ });+ it('defaults the label when absent', () => {+ const cue = __testing.sanitizeDerivedCue({ prompt: 'p' }, 1, 'musicgen');+ expect(cue.label).toBe('Cue 2');+ });+ });+});++describe('preserveRenderedCues', () => {+ it('returns fresh cues unchanged when there is no prior rendered audio', () => {+ const fresh = [{ id: 'cue-001', label: 'A', trackFilename: null }];+ expect(preserveRenderedCues(fresh, [])).toEqual(fresh);+ expect(preserveRenderedCues(fresh, [{ label: 'A', trackFilename: null }])).toEqual(fresh);+ });+ it('carries a rendered track forward onto the matching fresh label (case-insensitive)', () => {+ const fresh = [+ { id: 'cue-001', label: 'Act I', prompt: 'new prompt', trackFilename: null, durationSec: null },+ { id: 'cue-002', label: 'Climax', trackFilename: null, durationSec: null },+ ];+ const prior = [{ label: 'act i', trackFilename: 'music-gen-x.wav', durationSec: 42 }];+ const merged = preserveRenderedCues(fresh, prior);+ expect(merged[0].trackFilename).toBe('music-gen-x.wav');+ expect(merged[0].durationSec).toBe(42);+ // The fresh prompt is kept — only the render artifacts carry over.+ expect(merged[0].prompt).toBe('new prompt');+ // A label with no prior match stays un-rendered.+ expect(merged[1].trackFilename).toBeNull();+ });+});++describe('deriveAudioCues', () => {+ beforeEach(() => runStagedLLMMock.mockReset());++ const issueWithBeats = {+ number: 3, title: 'Ep',+ stages: { idea: { output: 'Act 1 setup. Act 2 climax.' }, storyboards: { scenes: [{ heading: 'A' }] } },+ };++ it('throws PIPELINE_AUDIO_CUES_NO_SOURCE when the episode has no beats', async () => {+ await expect(deriveAudioCues({ stages: { idea: {} } })).rejects.toMatchObject({ code: ERR_NO_SOURCE, status: 400 });+ expect(runStagedLLMMock).not.toHaveBeenCalled();+ });++ it('runs the cue-planner stage and returns sanitized cues with the default engine', async () => {+ runStagedLLMMock.mockResolvedValue({+ content: { cues: [+ { label: 'Act I', prompt: 'warm pads' },+ { label: 'Climax', prompt: 'tense strings' },+ ] },+ runId: 'r1', providerId: 'p', model: 'm',+ });+ const { cues, runId } = await deriveAudioCues(issueWithBeats, { defaultEngine: 'audioldm2' });+ expect(runStagedLLMMock).toHaveBeenCalledWith('pipeline-audio-cues', expect.any(Object), expect.objectContaining({ returnsJson: true }));+ expect(cues).toHaveLength(2);+ expect(cues[0]).toMatchObject({ id: 'cue-001', label: 'Act I', prompt: 'warm pads', engine: 'audioldm2', startSec: null, trackFilename: null });+ expect(cues[1].id).toBe('cue-002');+ expect(runId).toBe('r1');+ });++ it('drops prompt-less cues and re-indexes ids sequentially', async () => {+ runStagedLLMMock.mockResolvedValue({+ content: { cues: [+ { label: 'A', prompt: 'p1' },+ { label: 'B' }, // dropped — no prompt+ { label: 'C', prompt: 'p3' },+ ] },+ });+ const { cues } = await deriveAudioCues(issueWithBeats, { defaultEngine: 'musicgen' });+ expect(cues.map((c) => c.id)).toEqual(['cue-001', 'cue-002']);+ expect(cues.map((c) => c.label)).toEqual(['A', 'C']);+ });++ it('throws PIPELINE_AUDIO_CUES_EMPTY when no usable cues come back', async () => {+ runStagedLLMMock.mockResolvedValue({ content: { cues: [{ label: 'no prompt' }] } });+ await expect(deriveAudioCues(issueWithBeats)).rejects.toMatchObject({ code: ERR_EMPTY_RESULT });+ });+});diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.jsindex 7c399683e5..153b139b3b 100644--- a/server/services/pipeline/audioMux.js+++ b/server/services/pipeline/audioMux.js@@ -131,6 +131,43 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAUreturn { ok: true };}+// Build the VO-mix sub-graph: delay each VO line to its offset, resample, and+// (for 2+ lines) amix at full level. `firstInputIdx` is the ffmpeg input index+// of the FIRST VO line (1 when VO follows the video directly, cues.length+1 when+// cues precede it). Appends to `chains` and returns the label of the mixed VO+// track. Shared by buildVoMuxArgs (VO are inputs 1..N) and buildCueMuxArgs (VO+// follow the cues) so the delay/amix contract can't drift between them.+function appendVoMixChain(chains, voLines, firstInputIdx) {+ voLines.forEach((line, i) => {+ const ms = Math.round(Number(line.offsetSec) * 1000);+ // adelay `:all=1` delays every channel by `ms` regardless of layout, so a+ // mono VO WAV doesn't need an explicit per-channel delay list.+ chains.push(`[${firstInputIdx + i}:a]adelay=${ms}:all=1,${AFMT}[vo${i}]`);+ });+ if (voLines.length === 1) return '[vo0]';+ const ins = voLines.map((_, i) => `[vo${i}]`).join('');+ chains.push(`${ins}amix=inputs=${voLines.length}:normalize=0[vomix]`);+ return '[vomix]';+}++// Build the sidechain-duck sub-graph: pad the VO mix to infinity, split it into+// a "mixed back" copy + one sidechain key per bed, sidechaincompress each bed+// against its key, then amix the ducked beds back over the VO. The apad-before-+// split keeps each bed alive past the last VO line (sidechaincompress ends with+// its shortest input). Appends to `chains` and returns the final `[aout]` label.+// Shared by both mux builders so the (tricky, load-bearing) pad/split/duck graph+// stays identical. `keyPrefix` namespaces the intermediate labels.+function appendDuckChain(chains, voMixLabel, beds, duck, keyPrefix) {+ const keys = beds.map((_, i) => `[${keyPrefix}sck${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}[${keyPrefix}ducked${i}]`);+ return `[${keyPrefix}ducked${i}]`;+ });+ chains.push(`${ducked.join('')}[vomain]amix=inputs=${beds.length + 1}:normalize=0[aout]`);+ return '[aout]';+}+/*** Build the ffmpeg argv for a VO-line mux. Pure — unit-tested without spawning.*@@ -159,21 +196,8 @@ export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain =if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);const chains = [];- voLines.forEach((line, i) => {- const ms = Math.round(Number(line.offsetSec) * 1000);- // adelay `:all=1` delays every channel by `ms` regardless of layout, so a- // mono VO WAV doesn't need an explicit per-channel delay list.- chains.push(`[${i + 1}:a]adelay=${ms}:all=1,${AFMT}[vo${i}]`);- });-- let voMixLabel;- if (voLines.length === 1) {- voMixLabel = '[vo0]';- } else {- const ins = voLines.map((_, i) => `[vo${i}]`).join('');- chains.push(`${ins}amix=inputs=${voLines.length}:normalize=0[vomix]`);- voMixLabel = '[vomix]';- }+ // VO are inputs 1..N (directly after the video).+ const voMixLabel = appendVoMixChain(chains, voLines, 1);// 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@@ -192,21 +216,7 @@ export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain =}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]`);+ appendDuckChain(chains, voMixLabel, beds, duck, 'vo');} else {chains.push(`${voMixLabel}apad[aout]`);}@@ -271,4 +281,201 @@ export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = nulreturn { ok: true, lineCount: placed.length, ducked: !!usableMusic, clipAudio };}+// ── Multi-cue bed (audioMode: 'generated') ────────────────────────────────+// Whole-episode audio (issue #863, step 4): the 'generated' mode assembles an+// ordered cues[] onto an ABSOLUTE timeline — each rendered cue laid at its+// startSec with a fade in/out, then amix-ed into one bed. This is NOT+// acrossfade: acrossfade is sequential concatenation (splices two streams+// back-to-back, ignoring absolute offsets), so it can't place cues at arbitrary+// timeline positions. The delayed + faded cues are combined with+// `amix=normalize=0` (so cues keep their level rather than being attenuated by+// 1/N), and the resulting bed is ducked under VO via the same machinery as the+// music bed when placed VO lines exist.++// Fade length at each cue boundary. A short fade in/out blends adjacent cues at+// act turns without an audible click; kept well under the shortest plausible+// cue so it never swallows a whole cue.+const CUE_FADE_SEC = 1.5;++/**+ * Pure: map an issue's raw `stages.audio.cues` to the cues that are actually+ * muxable — *rendered* (have a `trackFilename`) AND *placed* (have a finite,+ * >= 0 `startSec`). Returns `[{ path, startSec, endSec, gain }]` with each+ * filename resolved under PATHS.music. Single source of truth for "what counts+ * as a placed+rendered cue", shared by the stitch runner and the arg builder so+ * the predicate can't drift.+ */+export function selectPlacedCues(cues) {+ if (!Array.isArray(cues)) return [];+ return cues+ .filter((c) => c?.trackFilename && isPlacedOffset(c.startSec))+ .map((c) => ({+ path: join(PATHS.music, c.trackFilename),+ startSec: c.startSec,+ // endSec is advisory for fade timing; null when un-placed.+ endSec: isPlacedOffset(c.endSec) && c.endSec > c.startSec ? c.endSec : null,+ // null gain → fall back to the stage default; 0 is a real "muted" value.+ gain: typeof c.gain === 'number' && Number.isFinite(c.gain) && c.gain >= 0 ? c.gain : null,+ }));+}++/**+ * Build the ffmpeg argv for the multi-cue 'generated' bed. Pure — unit-tested+ * without spawning.+ *+ * Input order: video is input 0, each cue is inputs 1..N (in the order given),+ * and — when present — the placed VO lines are inputs N+1..N+M. `cues` MUST+ * already be filtered to placed+rendered entries (selectPlacedCues does this).+ *+ * Graph:+ * - each cue: delayed to its startSec (`adelay`), faded in at its start and+ * out at its end (`afade`), resampled to the shared format, gained+ * - all cues `amix=normalize=0` into one absolute-timeline bed+ * - when VO lines are present: the bed is ducked under VO via+ * `sidechaincompress` (same key machinery as buildVoMuxArgs), and the VO is+ * mixed back over the ducked bed; the clip's own audio (`[0:a]`) is also+ * ducked when `clipAudio` is set+ * - `-shortest` pins the output to the video length+ */+export function buildCueMuxArgs({ inputVideoPath, cues, voLines = [], musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, clipAudio = false, outPath }) {+ const args = ['-i', inputVideoPath];+ for (const cue of cues) args.push('-i', cue.path);+ for (const line of voLines) args.push('-i', line.path);++ const chains = [];+ // Each cue: delay to its absolute start, fade in/out, resample, gain.+ cues.forEach((cue, i) => {+ const inputIdx = i + 1; // 0 is the video+ const delayMs = Math.round(Number(cue.startSec) * 1000);+ const gain = Number(cue.gain ?? musicGain).toFixed(3);+ const filters = [`adelay=${delayMs}:all=1`];+ // Fade IN at the cue's absolute start (st is in seconds on the post-delay+ // timeline). Fade OUT just before endSec when we know the span — otherwise+ // skip the out-fade (the amix tail + -shortest still bounds it).+ filters.push(`afade=t=in:st=${(cue.startSec).toFixed(3)}:d=${CUE_FADE_SEC}`);+ if (cue.endSec && cue.endSec - cue.startSec > CUE_FADE_SEC) {+ const fadeOutStart = (cue.endSec - CUE_FADE_SEC).toFixed(3);+ filters.push(`afade=t=out:st=${fadeOutStart}:d=${CUE_FADE_SEC}`);+ }+ filters.push(`volume=${gain}`, AFMT);+ chains.push(`[${inputIdx}:a]${filters.join(',')}[cue${i}]`);+ });++ // Mix the cues into one bed. A single cue needs no amix.+ let bedLabel;+ if (cues.length === 1) {+ bedLabel = '[cue0]';+ } else {+ const ins = cues.map((_, i) => `[cue${i}]`).join('');+ chains.push(`${ins}amix=inputs=${cues.length}:normalize=0[cuebed]`);+ bedLabel = '[cuebed]';+ }++ if (voLines.length) {+ // VO are inputs (cues.length+1)..(cues.length+voLines.length) — after the+ // cues. Mix them, then duck the cue bed (and clip audio, when present) under+ // VO via the shared duck graph. `cue` prefix namespaces the duck labels so+ // they can't collide with a VO-only mux's labels.+ const voMixLabel = appendVoMixChain(chains, voLines, cues.length + 1);+ const beds = [bedLabel];+ if (clipAudio) {+ chains.push(`[0:a]${AFMT}[clip]`);+ beds.push('[clip]');+ }+ appendDuckChain(chains, voMixLabel, beds, duck, 'cue');+ } else {+ // No VO — the cue bed is the whole soundtrack. apad so -shortest pins it to+ // the video length rather than the last cue.+ chains.push(`${bedLabel}apad[aout]`);+ }++ args.push(+ '-filter_complex', chains.join(';'),+ '-map', '0:v',+ '-map', '[aout]',+ '-c:v', 'copy',+ '-c:a', 'aac',+ '-b:a', '192k',+ '-shortest',+ '-movflags', '+faststart',+ '-y',+ outPath,+ );+ return args;+}++/**+ * Mix the placed+rendered cues (and, when present, ducked VO + clip audio) onto+ * `inputVideoPath`, replacing the file in place. Returns `{ ok: true, cueCount }`+ * on success or `{ ok: false, reason }` on any failure (graceful degradation —+ * the caller keeps the prior video).+ *+ * `cues` is `[{ path, startSec, endSec, gain }]`; entries without an on-disk file+ * or a finite, >= 0 startSec are dropped. With no usable cues this returns+ * ok:false so the caller can leave the (clip-audio) video as-is.+ */+export async function muxCueBed(inputVideoPath, { cues = [], voLines = [], musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, signal } = {}) {+ if (!inputVideoPath || !existsSync(inputVideoPath)) {+ return { ok: false, reason: 'input video missing' };+ }+ const placedCues = (Array.isArray(cues) ? cues : []).filter((c) => (+ c?.path && existsSync(c.path) && isPlacedOffset(c.startSec)+ ));+ if (!placedCues.length) return { ok: false, reason: 'no placed+rendered cues' };+ const placedVo = (Array.isArray(voLines) ? voLines : []).filter((l) => (+ l?.path && existsSync(l.path) && isPlacedOffset(l.offsetSec)+ ));++ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not on PATH' };++ // Preserve the clip's own soundtrack only when ducking under VO (same gate as+ // muxVoLines); referencing [0:a] against a silent clip aborts the graph.+ const clipAudio = placedVo.length ? await hasAudioStream(inputVideoPath) : false;++ const tmpOut = `${inputVideoPath}.cuemux.${randomUUID()}.mp4`;+ const args = buildCueMuxArgs({ inputVideoPath, cues: placedCues, voLines: placedVo, musicGain, duck, clipAudio, outPath: tmpOut });++ const result = await runFfmpegProcess({ bin: ffmpeg, args, signal });+ if (!result.ok) {+ await unlink(tmpOut).catch(() => {});+ return result;+ }+ await rename(tmpOut, inputVideoPath);+ return { ok: true, cueCount: placedCues.length, ducked: placedVo.length > 0, clipAudio };+}++/**+ * Strip ALL audio from the episode, replacing the file in place. This is the+ * `audioMode: 'silent'` path with no placed VO — the design specifies a silent+ * episode strips the clip's own soundtrack (LTX-2 audio-to-video) rather than+ * preserving it. `-an` drops the audio stream; the video is stream-copied so+ * there's no re-encode. Graceful degradation: returns `{ ok: false, reason }`+ * on any failure so the caller keeps the prior output.+ */+export async function muxStripAudio(inputVideoPath, { signal } = {}) {+ if (!inputVideoPath || !existsSync(inputVideoPath)) {+ return { ok: false, reason: 'input video missing' };+ }+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not on PATH' };+ const tmpOut = `${inputVideoPath}.silent.${randomUUID()}.mp4`;+ const args = [+ '-i', inputVideoPath,+ '-map', '0:v',+ '-an',+ '-c:v', 'copy',+ '-movflags', '+faststart',+ '-y',+ tmpOut,+ ];+ const result = await runFfmpegProcess({ bin: ffmpeg, args, signal });+ if (!result.ok) {+ await unlink(tmpOut).catch(() => {});+ return result;+ }+ await rename(tmpOut, inputVideoPath);+ return { ok: true };+}+export { DEFAULT_MUSIC_GAIN, DEFAULT_DUCK };diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsindex f309668437..34cccc9100 100644--- a/server/services/pipeline/audioMux.test.js+++ b/server/services/pipeline/audioMux.test.js@@ -65,7 +65,7 @@ vi.mock('child_process', async () => {};});-const { muxMusicBed, muxVoLines, buildVoMuxArgs, selectPlacedVoLines, resolveMusicTrackPath, DEFAULT_MUSIC_GAIN } = await import('./audioMux.js');+const { muxMusicBed, muxVoLines, buildVoMuxArgs, buildCueMuxArgs, muxCueBed, muxStripAudio, selectPlacedVoLines, selectPlacedCues, resolveMusicTrackPath, DEFAULT_MUSIC_GAIN } = await import('./audioMux.js');beforeEach(async () => {spawnCalls.length = 0;@@ -248,11 +248,11 @@ describe('buildVoMuxArgs', () => {// 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('apad,asplit=2[vomain][vosck0]');expect(filter).toContain('[2:a]volume=0.400');expect(filter).toContain('sidechaincompress=threshold=');- expect(filter).toContain('[bed][vsck0]sidechaincompress');- expect(filter).toContain('[ducked0][vomain]amix=inputs=2:normalize=0[aout]');+ expect(filter).toContain('[bed][vosck0]sidechaincompress');+ expect(filter).toContain('[voducked0][vomain]amix=inputs=2:normalize=0[aout]');});it('mixes the clip soundtrack in as a second ducked bed alongside music', () => {@@ -269,10 +269,10 @@ describe('buildVoMuxArgs', () => {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]');+ expect(filter).toContain('apad,asplit=3[vomain][vosck0][vosck1]');+ expect(filter).toContain('[bed][vosck0]sidechaincompress');+ expect(filter).toContain('[clip][vosck1]sidechaincompress');+ expect(filter).toContain('[voducked0][voducked1][vomain]amix=inputs=3:normalize=0[aout]');});it('ducks the clip soundtrack under VO even with no music bed', () => {@@ -286,9 +286,9 @@ describe('buildVoMuxArgs', () => {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]');+ expect(filter).toContain('apad,asplit=2[vomain][vosck0]');+ expect(filter).toContain('[clip][vosck0]sidechaincompress');+ expect(filter).toContain('[voducked0][vomain]amix=inputs=2:normalize=0[aout]');});it('uses a single VO label without amix for one line', () => {@@ -391,7 +391,7 @@ describe('muxVoLines', () => {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');+ expect(filter).toContain('[clip][vosck0]sidechaincompress');});it('skips the clip soundtrack when the input video is silent', async () => {@@ -411,3 +411,169 @@ describe('muxVoLines', () => {expect(filter).not.toContain('[clip]');});});++describe('selectPlacedCues', () => {+ it('keeps only rendered (trackFilename) AND placed (finite startSec >= 0) cues', () => {+ const out = selectPlacedCues([+ { trackFilename: 'a.wav', startSec: 0, endSec: 30, gain: 0.7 }, // kept+ { trackFilename: 'b.wav', startSec: null }, // dropped — not placed+ { trackFilename: null, startSec: 10 }, // dropped — not rendered+ { trackFilename: 'c.wav', startSec: 30, endSec: 60 }, // kept+ ]);+ expect(out).toHaveLength(2);+ expect(out[0].path).toMatch(/a\.wav$/);+ expect(out[0].startSec).toBe(0);+ expect(out[0].gain).toBe(0.7);+ expect(out[1].path).toMatch(/c\.wav$/);+ });++ it('nulls a non-positive-span endSec and a negative/invalid gain', () => {+ const out = selectPlacedCues([+ { trackFilename: 'a.wav', startSec: 10, endSec: 5, gain: -1 }, // endSec <= startSec+ ]);+ expect(out[0].endSec).toBeNull();+ expect(out[0].gain).toBeNull();+ });++ it('returns [] for non-array input', () => {+ expect(selectPlacedCues(null)).toEqual([]);+ expect(selectPlacedCues(undefined)).toEqual([]);+ });+});++describe('buildCueMuxArgs', () => {+ it('lays each cue at its absolute startSec with delay + fade, then amixes (no VO)', () => {+ const args = buildCueMuxArgs({+ inputVideoPath: '/v.mp4',+ cues: [+ { path: '/c0.wav', startSec: 0, endSec: 30, gain: 0.5 },+ { path: '/c1.wav', startSec: 30, endSec: 60, gain: 0.5 },+ ],+ outPath: '/out.mp4',+ });+ // video=0, cue0=1, cue1=2 (no VO inputs)+ expect(args.slice(0, 6)).toEqual(['-i', '/v.mp4', '-i', '/c0.wav', '-i', '/c1.wav']);+ const filter = args[args.indexOf('-filter_complex') + 1];+ // Absolute placement via adelay (NOT acrossfade) + per-cue fade in/out.+ expect(filter).toContain('[1:a]adelay=0:all=1');+ expect(filter).toContain('[2:a]adelay=30000:all=1');+ expect(filter).toContain('afade=t=in:st=0.000');+ expect(filter).toContain('afade=t=in:st=30.000');+ expect(filter).toContain('afade=t=out');+ expect(filter).not.toContain('acrossfade'); // design correction: never acrossfade+ // Two cues amix into one bed, then padded so -shortest pins to video length.+ expect(filter).toContain('amix=inputs=2:normalize=0[cuebed]');+ expect(filter).toContain('[cuebed]apad[aout]');+ expect(filter).not.toContain('sidechaincompress'); // no VO → no duck+ expect(args).toContain('-shortest');+ expect(args[args.indexOf('-map') + 1]).toBe('0:v');+ });++ it('uses a single cue label without amix for one cue', () => {+ const args = buildCueMuxArgs({+ inputVideoPath: '/v.mp4',+ cues: [{ path: '/c0.wav', startSec: 5, endSec: 35, gain: 0.5 }],+ outPath: '/out.mp4',+ });+ const filter = args[args.indexOf('-filter_complex') + 1];+ expect(filter).toContain('[cue0]apad[aout]');+ expect(filter).not.toContain('[cuebed]');+ });++ it('ducks the cue bed under VO when VO lines are present', () => {+ const args = buildCueMuxArgs({+ inputVideoPath: '/v.mp4',+ cues: [{ path: '/c0.wav', startSec: 0, endSec: 30, gain: 0.5 }],+ voLines: [{ path: '/a.wav', offsetSec: 2 }],+ outPath: '/out.mp4',+ });+ // video=0, cue=1, VO=2+ expect(args.slice(0, 6)).toEqual(['-i', '/v.mp4', '-i', '/c0.wav', '-i', '/a.wav']);+ const filter = args[args.indexOf('-filter_complex') + 1];+ expect(filter).toContain('[2:a]adelay=2000:all=1');+ // Cue bed ducked under VO via sidechaincompress (one bed, one VO key copy).+ expect(filter).toContain('apad,asplit=2[vomain][cuesck0]');+ expect(filter).toContain('sidechaincompress=threshold=');+ expect(filter).toContain('[cueducked0][vomain]amix=inputs=2:normalize=0[aout]');+ });++ it('adds the clip soundtrack as a second ducked bed under VO when clipAudio is set', () => {+ const args = buildCueMuxArgs({+ inputVideoPath: '/v.mp4',+ cues: [{ path: '/c0.wav', startSec: 0, endSec: 30, gain: 0.5 }],+ voLines: [{ path: '/a.wav', offsetSec: 0 }],+ clipAudio: true,+ outPath: '/out.mp4',+ });+ const filter = args[args.indexOf('-filter_complex') + 1];+ expect(filter).toContain('[0:a]aresample=48000');+ expect(filter).toContain('apad,asplit=3[vomain][cuesck0][cuesck1]');+ expect(filter).toContain('[cueducked0][cueducked1][vomain]amix=inputs=3:normalize=0[aout]');+ });+});++describe('muxCueBed', () => {+ beforeEach(() => {+ findFfmpegMock.mockReset();+ hasAudioStreamMock.mockReset();+ spawnCalls.length = 0;+ });++ it('returns ok:false when no cue is placed+rendered (caller keeps clip audio)', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'cv.mp4');+ await writeFile(video, Buffer.from('vid'));+ const result = await muxCueBed(video, { cues: [{ path: '/missing.wav', startSec: 0 }] });+ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/no placed/i);+ });++ it('mixes placed+rendered cues onto the video and reports the cue count', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ hasAudioStreamMock.mockResolvedValue(false);+ const video = join(TEST_HOME, 'cv2.mp4');+ const cue = join(TEST_HOME, 'cue.wav');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(cue, Buffer.from('wav'));+ const result = await muxCueBed(video, { cues: [{ path: cue, startSec: 0, endSec: 30, gain: 0.5 }] });+ expect(result.ok).toBe(true);+ expect(result.cueCount).toBe(1);+ expect(result.ducked).toBe(false); // no VO+ });++ it('does not probe / reference clip audio when there is no VO', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ hasAudioStreamMock.mockResolvedValue(true);+ const video = join(TEST_HOME, 'cv3.mp4');+ const cue = join(TEST_HOME, 'cue3.wav');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(cue, Buffer.from('wav'));+ await muxCueBed(video, { cues: [{ path: cue, startSec: 0, endSec: 30, gain: 0.5 }] });+ const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];+ expect(filter).not.toContain('[0:a]');+ });+});++describe('muxStripAudio', () => {+ beforeEach(() => { findFfmpegMock.mockReset(); spawnCalls.length = 0; });++ it('returns ok:false when the input video is missing', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const result = await muxStripAudio(join(TEST_HOME, 'nope.mp4'));+ expect(result.ok).toBe(false);+ expect(result.reason).toBe('input video missing');+ });++ it('strips the audio stream with -an and stream-copies the video', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'sv.mp4');+ await writeFile(video, Buffer.from('vid'));+ const result = await muxStripAudio(video);+ expect(result).toEqual({ ok: true });+ const { args } = spawnCalls[0];+ expect(args).toContain('-an');+ expect(args[args.indexOf('-map') + 1]).toBe('0:v');+ expect(args[args.indexOf('-c:v') + 1]).toBe('copy');+ expect(args).not.toContain('-filter_complex');+ });+});