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([pipeline-audio-phase-4c-2-4c-3-4d-2-local-oss]): local MusicGen + VO muxing with ducking
[._.]/ Adam Eivy5b1880d330f3
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsxindex f368534874..b79acb8ff4 100644--- a/client/src/components/pipeline/stages/AudioStage.jsx+++ b/client/src/components/pipeline/stages/AudioStage.jsx@@ -24,6 +24,8 @@ import {attachPipelineMusicTrack,detachPipelineMusicTrack,deletePipelineMusicTrack,+ listPipelineMusicGenerators,+ generatePipelineMusic,PIPELINE_STAGE_LABELS,PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,@@ -72,6 +74,55 @@ export default function AudioStage({ issue, onStageUpdate }) {const [pendingLibraryDelete, setPendingLibraryDelete] = useState(null);const fileInputRef = useRef(null);+ // Local-OSS music generation (Phase 4c.2). The generators list is fetched+ // lazily when the user opens the Generate panel; `ready` gates the prompt box+ // behind an install hint so a 503 never surprises them mid-prompt.+ const [genPanelOpen, setGenPanelOpen] = useState(false);+ const [generators, setGenerators] = useState(null);+ const [generating, setGenerating] = useState(false);+ const [genPrompt, setGenPrompt] = useState('');+ const [genDuration, setGenDuration] = useState(12);+ const [genModelId, setGenModelId] = useState('');++ // Per-line VO start-offset drafts (seconds into the stitched episode). Kept+ // separate from text drafts; committed on blur via the same patch queue.+ const [offsetDrafts, setOffsetDrafts] = useState({});++ const openGenPanel = async () => {+ setGenPanelOpen(true);+ if (generators === null) {+ const result = await listPipelineMusicGenerators().catch((err) => {+ toast.error(err.message || 'Failed to load generators');+ return null;+ });+ if (result) {+ setGenerators(result);+ setGenModelId((prev) => prev || result.defaultModelId || result.models?.[0]?.id || '');+ if (Number.isFinite(result.defaultDurationSec)) setGenDuration(result.defaultDurationSec);+ }+ }+ };++ const handleGenerateMusic = async () => {+ const prompt = genPrompt.trim();+ if (!prompt) { toast.error('Describe the music you want first'); return; }+ setGenerating(true);+ // Owns its own error toast → silent so the helper doesn't double-toast.+ const result = await generatePipelineMusic(+ issue.id,+ { prompt, durationSec: genDuration, modelId: genModelId || undefined },+ { silent: true },+ ).catch((err) => {+ toast.error(err.message || 'Music generation failed');+ return null;+ });+ setGenerating(false);+ if (!result) return;+ onStageUpdate?.('audio', result.stage, result.issue);+ setGenPanelOpen(false);+ toast.success(`Generated ${result.durationSec ?? genDuration}s track (${result.modelId})`);+ };+const loadMusicLibrary = async () => {setMusicLibraryLoading(true);const result = await listPipelineMusicLibrary().catch((err) => {@@ -168,6 +219,7 @@ export default function AudioStage({ issue, onStageUpdate }) {if (!result) return;onStageUpdate?.('audio', result.stage, result.issue);setDrafts({});+ setOffsetDrafts({});const preserved = result.preservedCount || 0;if (preserved > 0) {toast.success(`Extracted ${result.lineCount} line${result.lineCount === 1 ? '' : 's'} · preserved ${preserved} rendered`);@@ -216,6 +268,22 @@ export default function AudioStage({ issue, onStageUpdate }) {void saveLinePatch(lineIdx, { voiceIdOverride: voiceId });};+ // Commit a per-line start-offset edit. Empty input clears the placement+ // (null → muxer skips the line); a valid non-negative number positions it.+ // Invalid input is dropped silently so the field reverts to server state.+ const handleOffsetBlur = (lineIdx) => {+ const draft = offsetDrafts[lineIdx];+ if (draft === undefined) return;+ const dropDraft = () => setOffsetDrafts((prev) => { const next = { ...prev }; delete next[lineIdx]; return next; });+ const current = Number.isFinite(lines[lineIdx]?.offsetSec) ? lines[lineIdx].offsetSec : null;+ const trimmed = String(draft).trim();+ const parsed = trimmed === '' ? null : Number(trimmed);+ if (parsed !== null && (!Number.isFinite(parsed) || parsed < 0)) { dropDraft(); return; }+ if (parsed === current) { dropDraft(); return; }+ void saveLinePatch(lineIdx, { offsetSec: parsed });+ dropDraft();+ };+const handleRender = async (lineIdx) => {// Snapshot + await every outstanding PATCH for this line — both text// and voice-override saves can be in flight at once (e.g. textarea@@ -357,6 +425,24 @@ export default function AudioStage({ issue, onStageUpdate }) {{isRendering ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}{line.audioFilename ? 'Re-render' : 'Render'}</button>+ {/* Per-line start offset (seconds into the episode). Drives+ VO muxing in the final cut; blank = not placed yet. */}+ <label htmlFor={`vo-offset-${i}`} className="text-[10px] text-gray-500 mt-0.5">Start (s)</label>+ <input+ id={`vo-offset-${i}`}+ type="number"+ min="0"+ step="0.1"+ inputMode="decimal"+ value={offsetDrafts[i] !== undefined+ ? offsetDrafts[i]+ : (Number.isFinite(line.offsetSec) ? line.offsetSec : '')}+ onChange={(e) => setOffsetDrafts((prev) => ({ ...prev, [i]: e.target.value }))}+ onBlur={() => handleOffsetBlur(i)}+ placeholder="—"+ title="When this line plays in the stitched episode (seconds). Blank = not placed."+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ /></div></div></li>@@ -372,12 +458,12 @@ export default function AudioStage({ issue, onStageUpdate }) {<div><h3 className="text-base font-semibold text-white">Background Music</h3><p className="text-xs text-gray-500 mt-0.5">- Optional track played under the rendered episode. Upload from disk now;- {' '}<span className="text-gray-600">local OSS generation (MusicGen) coming next.</span>+ Optional track played under the rendered episode — ducked beneath dialogue in the final cut.+ {' '}<span className="text-gray-600">Upload, pick from the library, or generate locally with MusicGen.</span></p></div></div>- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-wrap"><inputref={fileInputRef}type="file"@@ -406,9 +492,88 @@ export default function AudioStage({ issue, onStageUpdate }) {<Music size={14} />{musicPickerOpen ? 'Close library' : 'Pick from library'}</button>+ <button+ type="button"+ onClick={() => (genPanelOpen ? setGenPanelOpen(false) : openGenPanel())}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"+ >+ <Wand2 size={14} />+ {genPanelOpen ? 'Close generator' : 'Generate (MusicGen)'}+ </button></div></div>+ {genPanelOpen ? (+ <div className="mb-3 p-3 bg-port-bg border border-port-border rounded-lg">+ {generators === null ? (+ <p className="text-xs text-gray-500">Loading generators…</p>+ ) : !generators.ready ? (+ <p className="text-xs text-gray-400">+ Local music generation isn't installed yet. Run{' '}+ <code className="text-gray-300">INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh</code>{' '}+ to bootstrap the MusicGen (MLX) runtime, then reopen this panel.+ </p>+ ) : (+ <div className="space-y-3">+ <div>+ <label htmlFor="musicgen-prompt" className="block text-xs text-gray-400 mb-1">Describe the music</label>+ <textarea+ id="musicgen-prompt"+ value={genPrompt}+ onChange={(e) => setGenPrompt(e.target.value)}+ rows={2}+ maxLength={800}+ placeholder="e.g. tense cinematic synth pad, slow build, minor key"+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"+ />+ </div>+ <div className="flex items-end gap-3 flex-wrap">+ <div>+ <label htmlFor="musicgen-model" className="block text-xs text-gray-400 mb-1">Model</label>+ <select+ id="musicgen-model"+ value={genModelId}+ onChange={(e) => setGenModelId(e.target.value)}+ className="px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"+ >+ {(generators.models || []).map((m) => (+ <option key={m.id} value={m.id}>{m.name}</option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="musicgen-duration" className="block text-xs text-gray-400 mb-1">+ Length (s)+ </label>+ <input+ id="musicgen-duration"+ type="number"+ min={generators.minDurationSec ?? 1}+ max={generators.maxDurationSec ?? 30}+ step="1"+ value={genDuration}+ onChange={(e) => setGenDuration(Number(e.target.value))}+ className="w-24 px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"+ />+ </div>+ <button+ type="button"+ onClick={handleGenerateMusic}+ disabled={generating || !genPrompt.trim()}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50"+ >+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}+ {generating ? 'Generating…' : 'Generate'}+ </button>+ </div>+ <p className="text-[11px] text-gray-600">+ Runs on-device via MLX — a {generators.maxDurationSec ?? 30}s clip takes ~tens of seconds. The track lands in your music library and is attached to this issue.+ </p>+ </div>+ )}+ </div>+ ) : null}+{music ? (<div className="p-3 bg-port-card border border-port-border rounded-lg"><div className="flex items-start justify-between gap-3 flex-wrap">diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex a41ac0e729..2848de40a4 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -613,3 +613,22 @@ export const deletePipelineMusicTrack = (filename) =>request(`/pipeline/audio/music-library/${encodeURIComponent(filename)}`, {method: 'DELETE',});++// ---- Local-OSS music generation (Phase 4c.2) ----++// Available MusicGen generators + whether the opt-in MLX runtime is installed.+// Returns { models, defaultModelId, defaultDurationSec, minDurationSec,+// maxDurationSec, ready }. `ready=false` → show the install hint instead of+// the prompt box.+export const listPipelineMusicGenerators = () =>+ request('/pipeline/audio/music/generators');++// Generate a background-music track with MusicGen (MLX) and attach it to the+// issue (source: 'gen'). Long-running (~tens of seconds); callers own a busy+// state. Returns { issue, stage, music, durationSec, modelId }.+export const generatePipelineMusic = (issueId, { prompt, durationSec, modelId } = {}, options = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/generate`, {+ method: 'POST',+ body: JSON.stringify({ prompt, durationSec, modelId }),+ ...options,+ });diff --git a/scripts/generate_musicgen.py b/scripts/generate_musicgen.pynew file mode 100644index 0000000000..874d524b36--- /dev/null+++ b/scripts/generate_musicgen.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""+PortOS MusicGen runner — local OSS background-music generation on Apple+Silicon via MLX. Spawned by `server/services/pipeline/musicGen.js`.++Pipeline Audio Phase 4c.2: the first local music generator behind the audio+stage's `source: 'gen'` library entry. Meta's MusicGen (MLX port) generates+bounded text-conditioned clips (~up to 30s) entirely on-device — no network,+no API key — matching PortOS's "local OSS first" media strategy.++Runtime: the MLX MusicGen implementation lives in ml-explore/mlx-examples+(`musicgen/`), which isn't a pip package. `INSTALL_MUSICGEN=1 bash+scripts/setup-image-video.sh` clones it to ~/.portos/mlx-examples and builds a+sibling venv at ~/.portos/venv-musicgen. The JS caller passes the clone's+`musicgen/` dir via --runtime-dir so this script can import `MusicGen` from it;+we also fall back to a plain `import musicgen` for installs that vendored it+onto the path some other way.++Progress protocol (mirrors the image/video sidecars): STAGE:<name>[:detail]+lines on stderr drive the JS-side phase tracker; a final `RESULT:<json>` line+on stdout reports the saved path + duration.++Output: a 32 kHz mono 16-bit PCM WAV at --output. We write the WAV with the+stdlib `wave` module (+ numpy for the float→int16 conversion) rather than+depending on scipy/soundfile, so the runtime's dependency surface stays small.+"""++import argparse+import json+import os+import sys+import wave+++# MusicGen decodes audio at 32 kHz; the EnCodec frame rate is 50 Hz, so one+# second of audio is 50 decoder steps. Both are fixed by the model.+SAMPLE_RATE = 32000+STEPS_PER_SECOND = 50+++def log_stage(name, detail=""):+ """Emit a STAGE: line the JS sidecar tails for phase/progress display."""+ line = f"STAGE:{name}" + (f":{detail}" if detail else "")+ print(line, file=sys.stderr, flush=True)+++def _import_musicgen(runtime_dir):+ """Resolve the MLX MusicGen class.++ Prefer the clone dir the JS caller points us at (the mlx-examples+ `musicgen/` package directory); fall back to an importable `musicgen`+ module for installs that placed it on PYTHONPATH another way. Raising a+ clear ImportError here lets the JS side surface "run the installer" rather+ than a bare traceback.+ """+ if runtime_dir and os.path.isdir(runtime_dir) and runtime_dir not in sys.path:+ sys.path.insert(0, runtime_dir)+ try:+ from musicgen import MusicGen # type: ignore+ return MusicGen+ except ImportError as exc:+ raise ImportError(+ "Could not import MusicGen from the MLX runtime. Run "+ "`INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh` to clone "+ f"ml-explore/mlx-examples and build the venv (looked in: {runtime_dir})."+ ) from exc+++def _to_int16_pcm(audio):+ """Flatten an mlx/numpy audio array to a 1-D int16 numpy buffer.++ MusicGen returns a float array (typically shape [samples, 1] or+ [1, samples]); we flatten to mono, clip to [-1, 1] so a hot sample can't+ wrap on the int16 cast, and scale to full-scale PCM.+ """+ import numpy as np++ arr = np.array(audio, dtype=np.float32).reshape(-1)+ np.clip(arr, -1.0, 1.0, out=arr)+ return (arr * 32767.0).astype(np.int16)+++def _write_wav(path, pcm_int16):+ with wave.open(path, "wb") as wav:+ wav.setnchannels(1)+ wav.setsampwidth(2) # 16-bit+ wav.setframerate(SAMPLE_RATE)+ wav.writeframes(pcm_int16.tobytes())+++def main():+ parser = argparse.ArgumentParser(description="PortOS MusicGen runner (MLX)")+ parser.add_argument("--model", default="facebook/musicgen-medium",+ help="HF repo id of the MusicGen weights")+ parser.add_argument("--text", required=True, help="Text prompt")+ parser.add_argument("--output", required=True, help="Output WAV path")+ parser.add_argument("--duration", type=float, default=12.0,+ help="Target clip length in seconds")+ parser.add_argument("--runtime-dir", default=os.environ.get("PORTOS_MUSICGEN_RUNTIME_DIR", ""),+ help="Path to the mlx-examples musicgen/ package dir")+ args = parser.parse_args()++ text = (args.text or "").strip()+ if not text:+ print("ERROR: --text is required", file=sys.stderr, flush=True)+ return 2++ # Clamp duration into the model's practical window. MusicGen degrades past+ # ~30s (it was trained on 30s windows); a 0.5s floor keeps max_steps >= 1.+ duration = max(0.5, min(float(args.duration or 12.0), 30.0))+ max_steps = max(1, round(duration * STEPS_PER_SECOND))++ log_stage("import-runtime")+ MusicGen = _import_musicgen(args.runtime_dir)++ log_stage("load-model", args.model)+ model = MusicGen.from_pretrained(args.model)++ log_stage("generate", f"{duration:.1f}s/{max_steps}steps")+ audio = model.generate(text, max_steps=max_steps)++ log_stage("encode-wav")+ pcm = _to_int16_pcm(audio)+ out_dir = os.path.dirname(os.path.abspath(args.output))+ if out_dir:+ os.makedirs(out_dir, exist_ok=True)+ _write_wav(args.output, pcm)++ # The actual rendered length can differ slightly from the request (integer+ # step count). Report what we actually wrote so the JS side persists truth.+ actual_seconds = len(pcm) / float(SAMPLE_RATE)+ result = {+ "output": args.output,+ "model": args.model,+ "durationSec": round(actual_seconds, 3),+ "sampleRate": SAMPLE_RATE,+ }+ print("RESULT:" + json.dumps(result), flush=True)+ log_stage("done")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 8a4c44f757..aa8fe6c43c 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -11,6 +11,8 @@# INSTALL_VIDEO '1' to also install mlx_video for LTX video generation (default: 1 on macOS, 0 on Windows)# INSTALL_LTX2 '1' to also clone + uv-sync dgrauet/ltx-2-mlx at ~/.portos/ltx-2-mlx for the second-gen LTX-2.3 pipeline (proper keyframe interpolation, true video extend, audio-to-video). Default: 0; opt in with INSTALL_LTX2=1.# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)+# INSTALL_MUSICGEN '1' to bootstrap a venv at ~/.portos/venv-musicgen + clone ml-explore/mlx-examples to ~/.portos/mlx-examples for local MusicGen (MLX) background-music generation (pipeline audio stage). Default: 0; opt in with INSTALL_MUSICGEN=1 (macOS / Apple Silicon only).+# MLX_EXAMPLES_PIN commit SHA of ml-explore/mlx-examples to check out for MusicGen (default: main).set -euo pipefail@@ -273,6 +275,63 @@ if [[ "$INSTALL_HUNYUAN" == "1" ]]; thenecho "✅ HunyuanVideo_MLX venv ready: ${HUNYUAN_PY}"fi+INSTALL_MUSICGEN="${INSTALL_MUSICGEN:-0}"+if [[ "$INSTALL_MUSICGEN" == "1" ]]; then+ # Local background-music generation for the pipeline audio stage (Phase+ # 4c.2). Meta's MusicGen runs on Apple Silicon via MLX, but the MLX+ # implementation lives in ml-explore/mlx-examples (`musicgen/`), which isn't+ # a pip package — so we clone the repo and build a sibling venv. The sidecar+ # `scripts/generate_musicgen.py` imports `MusicGen` from the clone;+ # server/lib/pythonSetup.js (resolveMusicgenPython) looks for python3 here.+ if ! is_macos; then+ echo "⚠️ INSTALL_MUSICGEN=1 is macOS / Apple-Silicon only (MLX). Skipping." >&2+ else+ if ! have git; then+ echo "❌ INSTALL_MUSICGEN=1 requires git." >&2+ exit 1+ fi+ MUSICGEN_VENV="${HOME}/.portos/venv-musicgen"+ MUSICGEN_PY="$MUSICGEN_VENV/bin/python3"+ MLX_EXAMPLES_DIR="${HOME}/.portos/mlx-examples"+ MLX_EXAMPLES_PIN="${MLX_EXAMPLES_PIN:-main}"+ mkdir -p "${HOME}/.portos"++ if [[ ! -d "${MLX_EXAMPLES_DIR}/.git" ]]; then+ echo "📦 Cloning ml-explore/mlx-examples → ${MLX_EXAMPLES_DIR}..."+ git clone https://github.com/ml-explore/mlx-examples.git "${MLX_EXAMPLES_DIR}"+ fi+ # Pin to a known commit when MLX_EXAMPLES_PIN is set to a SHA; default+ # 'main' tracks HEAD (the musicgen example is stable, but a pin keeps new+ # installs reproducible — mirror of the LTX2_PIN pattern above).+ (cd "${MLX_EXAMPLES_DIR}" && git fetch --quiet origin && git checkout --quiet "${MLX_EXAMPLES_PIN}")++ if [[ ! -x "$MUSICGEN_PY" ]]; then+ echo "📦 Creating MusicGen venv at ${MUSICGEN_VENV}..."+ "$PYTHON_BIN" -m venv "$MUSICGEN_VENV"+ fi+ echo "📦 Installing MusicGen (MLX) packages into ${MUSICGEN_VENV}..."+ "$MUSICGEN_PY" -m pip install --upgrade pip wheel setuptools >/dev/null+ # mlx + numpy run the model; transformers (<5 for MLX compat) + sentencepiece+ # provide the T5 text conditioner's tokenizer; scipy is imported by the+ # mlx-examples musicgen utils. We write WAV via the stdlib `wave` module in+ # the sidecar, so no soundfile dependency.+ "$MUSICGEN_PY" -m pip install --upgrade \+ mlx \+ numpy \+ "transformers<5" \+ sentencepiece \+ "huggingface_hub[hf_xet]" \+ scipy+ if ! PORTOS_MUSICGEN_RUNTIME_DIR="${MLX_EXAMPLES_DIR}/musicgen" \+ "$MUSICGEN_PY" -c "import sys, os; sys.path.insert(0, os.environ['PORTOS_MUSICGEN_RUNTIME_DIR']); from musicgen import MusicGen" 2>/dev/null; then+ echo "❌ MusicGen venv built but 'from musicgen import MusicGen' failed." >&2+ echo " Check that ${MLX_EXAMPLES_DIR}/musicgen exists and the clone is intact." >&2+ exit 1+ fi+ echo "✅ MusicGen venv ready: $MUSICGEN_PY (runtime: ${MLX_EXAMPLES_DIR}/musicgen @ ${MLX_EXAMPLES_PIN:0:12})"+ fi+fi+INSTALL_FLUX2="${INSTALL_FLUX2:-$DEFAULT_INSTALL_FLUX2}"if [[ "$INSTALL_FLUX2" == "1" ]]; then@@ -343,6 +402,9 @@ echo " Videos: ${PORTOS_DATA}/videos"if [[ "$INSTALL_LTX2" == "1" ]]; thenecho " LTX-2.3: ${HOME}/.portos/ltx-2-mlx/.venv/bin/python3 (separate venv, dgrauet pipeline @ ${LTX2_PIN:0:12})"fi+if [[ "$INSTALL_MUSICGEN" == "1" ]] && is_macos; then+ echo " MusicGen: ${HOME}/.portos/venv-musicgen/bin/python3 (separate venv, MLX runtime @ ${HOME}/.portos/mlx-examples/musicgen)"+fiif [[ "$INSTALL_FLUX2" == "1" ]]; thenecho " FLUX.2: ${HOME}/.portos/venv-flux2/bin/python3 (separate venv)"echo " Z-Image: reuses the FLUX.2 venv (Apache 2.0, no HF login needed)"diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex c7cefbc7cf..491bff349d 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -174,6 +174,42 @@ export function invalidateFlux2Health() {cachedFlux2Healthy = null;}+// MusicGen (Pipeline Audio Phase 4c.2) runs in its own venv at+// ~/.portos/venv-musicgen — mlx + numpy + transformers, kept apart from the+// FLUX.2 torch pile. The MLX MusicGen implementation isn't a pip package, so+// `INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh` also clones+// ml-explore/mlx-examples to ~/.portos/mlx-examples; the sidecar imports+// `MusicGen` from its `musicgen/` directory (see MUSICGEN_RUNTIME_DIR).+const MUSICGEN_VENV_CANDIDATES = IS_WIN+ ? [+ join(HOME, '.portos', 'venv-musicgen', 'Scripts', 'python.exe'),+ join(PATHS.data, 'python', 'venv-musicgen', 'Scripts', 'python.exe'),+ ]+ : [+ join(HOME, '.portos', 'venv-musicgen', 'bin', 'python3'),+ join(PATHS.data, 'python', 'venv-musicgen', 'bin', 'python3'),+ ];++export const MUSICGEN_VENV_DEFAULT = MUSICGEN_VENV_CANDIDATES[0];++// The mlx-examples clone's musicgen package directory — passed to the sidecar+// as --runtime-dir so it can `from musicgen import MusicGen`. The default+// mirrors the setup script's clone target.+export const MUSICGEN_RUNTIME_DIR = join(HOME, '.portos', 'mlx-examples', 'musicgen');++let cachedMusicgenPython = null;+export function resolveMusicgenPython() {+ if (cachedMusicgenPython && existsSync(cachedMusicgenPython)) return cachedMusicgenPython;+ for (const p of MUSICGEN_VENV_CANDIDATES) {+ if (existsSync(p)) { cachedMusicgenPython = p; return p; }+ }+ return null;+}++export function invalidateMusicgenPython() {+ cachedMusicgenPython = null;+}+// Used by /api/image-gen/setup/* routes to validate user-supplied pythonPath// before exec. Single-user / Tailnet model means we trust the operator, but// "you can shell out to anything" is still too sharp — restrict to actualdiff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex ec7ae40832..150d78d394 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -84,6 +84,15 @@ import {MUSIC_SOURCE,MUSIC_UPLOAD_MAX_BYTES,} from '../services/pipeline/musicLibrary.js';+import {+ generateMusic,+ MUSICGEN_MODELS,+ DEFAULT_MUSICGEN_MODEL_ID,+ DEFAULT_DURATION_SEC,+ MIN_DURATION_SEC,+ MAX_DURATION_SEC,+ isMusicGenReady,+} from '../services/pipeline/musicGen.js';import { uploadSingle } from '../lib/multipart.js';import { parseComicScript } from '../lib/comicScriptParser.js';import {@@ -762,6 +771,9 @@ router.post('/issues/:id/stages/audio/extract-lines', asyncHandler(async (req, rconst lineEditSchema = z.object({text: z.string().max(4000).optional(),voiceIdOverride: z.string().trim().max(200).nullable().optional(),+ // Per-line VO start offset (seconds into the stitched episode). null clears+ // the placement so the muxer skips the line. The sanitizer clamps the range.+ offsetSec: z.number().min(0).max(7200).nullable().optional(),});router.patch('/issues/:id/stages/audio/lines/:lineIdx', asyncHandler(async (req, res) => {const lineIdx = Number(req.params.lineIdx);@@ -786,6 +798,7 @@ router.patch('/issues/:id/stages/audio/lines/:lineIdx', asyncHandler(async (req,const next = { ...line };if ('text' in body) next.text = body.text;if ('voiceIdOverride' in body) next.voiceIdOverride = body.voiceIdOverride;+ if ('offsetSec' in body) next.offsetSec = body.offsetSec;const nextLines = [...lines];nextLines[lineIdx] = next;return { status: 'edited', lines: nextLines };@@ -878,6 +891,54 @@ router.get('/audio/music-library', asyncHandler(async (_req, res) => {res.json({ tracks: await listMusicLibrary() });}));+// Local-OSS music generators available to the audio stage (Phase 4c.2).+// `ready` reflects whether the opt-in MusicGen venv is provisioned, so the UI+// can show an install hint instead of letting the user type a prompt that 503s.+router.get('/audio/music/generators', asyncHandler(async (_req, res) => {+ res.json({+ models: MUSICGEN_MODELS.map(({ id, name }) => ({ id, name })),+ defaultModelId: DEFAULT_MUSICGEN_MODEL_ID,+ defaultDurationSec: DEFAULT_DURATION_SEC,+ minDurationSec: MIN_DURATION_SEC,+ maxDurationSec: MAX_DURATION_SEC,+ ready: isMusicGenReady(),+ });+}));++// Generate a background-music track with MusicGen (MLX) and attach it to the+// issue as a `source: 'gen'` track. The generated WAV lands in the shared+// music library, so it's reusable across issues exactly like an upload.+const musicGenerateSchema = z.object({+ prompt: z.string().trim().min(1).max(800),+ durationSec: z.number().min(MIN_DURATION_SEC).max(MAX_DURATION_SEC).optional(),+ modelId: z.enum(MUSICGEN_MODELS.map((m) => m.id)).optional(),+ label: z.string().trim().max(200).nullable().optional(),+});+router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(musicGenerateSchema, req.body ?? {});+ // Guard the (expensive) generation behind a 404 check first — generating a+ // multi-second clip only to discover the issue is gone wastes GPU time and+ // would orphan the WAV in the library.+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ issuesSvc.assertStageUnlocked(issue, 'audio');+ const gen = await generateMusic({+ prompt: body.prompt,+ durationSec: body.durationSec ?? DEFAULT_DURATION_SEC,+ modelId: body.modelId ?? DEFAULT_MUSICGEN_MODEL_ID,+ }).catch((err) => { throw mapServiceError(err); });+ const label = body.label?.trim() || gen.model;+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ req.params.id,+ 'audio',+ (current) => ({+ status: audioStatusAfterMusicChange(current),+ music: { source: MUSIC_SOURCE.GEN, trackFilename: gen.filename, label },+ errorMessage: '',+ }),+ ).catch((err) => { throw mapServiceError(err); });+ res.json({ issue: updatedIssue, stage, music: stage.music, durationSec: gen.durationSec, modelId: gen.modelId });+}));+router.post('/issues/:id/stages/audio/music/upload', musicUpload, asyncHandler(async (req, res) => {if (!req.file) {throw new ServerError('No audio file uploaded', {diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.jsindex a8d58959cc..3c7fe476b5 100644--- a/server/services/creativeDirector/stitchRunner.js+++ b/server/services/creativeDirector/stitchRunner.js@@ -24,7 +24,7 @@ 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, resolveMusicTrackPath } from '../pipeline/audioMux.js';+import { muxMusicBed, muxVoLines, resolveMusicTrackPath } from '../pipeline/audioMux.js';import { PATHS } from '../../lib/fileUtils.js';const FINAL_RENDER_POLL_MS = 3000;@@ -142,9 +142,34 @@ async function maybeMuxPipelineAudio(project, finalEntry) {}const musicFilename = issue.stages?.audio?.music?.trackFilename;const musicPath = await resolveMusicTrackPath(musicFilename);- if (!musicPath) return;++ // Collect placed VO lines — rendered (have an audioFilename) AND positioned+ // (have a numeric offsetSec). Un-placed lines stay silent rather than+ // stacking at t=0. When any exist, the VO pass (which also ducks the music+ // bed under dialogue) supersedes the music-only bed.+ const lines = Array.isArray(issue.stages?.audio?.lines) ? issue.stages.audio.lines : [];+ const voLines = lines+ .filter((l) => l?.audioFilename && Number.isFinite(Number(l?.offsetSec)) && Number(l.offsetSec) >= 0)+ .map((l) => ({ path: join(PATHS.audio, l.audioFilename), offsetSec: Number(l.offsetSec) }));++ // 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 });+ if (result.ok) {+ console.log(`✅ CD stitch mux: VO mux applied to ${finalEntry.filename} (${result.lineCount} line(s)${result.ducked ? ', music ducked' : ''})`);+ return;+ }+ // VO mux failed — fall through to a plain music bed if we have one, so a+ // graph error doesn't strip the music too.+ console.log(`⚠️ CD stitch mux: VO mux skipped (${result.reason})${musicPath ? ' — falling back to music bed' : ''}`);+ }++ if (!musicPath) return;console.log(`🎵 CD stitch mux: overlaying ${musicFilename} onto ${finalEntry.filename}`);const result = await muxMusicBed(videoPath, { musicPath });if (result.ok) {diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.jsindex ed290672bb..9814f46b62 100644--- a/server/services/pipeline/audioMux.js+++ b/server/services/pipeline/audioMux.js@@ -2,16 +2,26 @@* Pipeline audio mux — second-pass overlay of pipeline-stage audio onto the* already-stitched episode video.*- * Phase 4d v1 covers **background-music bedding**: stripping the timeline's- * silent track and laying the user-picked music file underneath the video at- * a configurable gain. The music loops to fill the video length and is cut- * to match the video duration. VO line muxing (4d.2) lands on top of this- * same module — the helper signature already accepts `voLines` for that.+ * Phase 4d v1 (`muxMusicBed`) covers **background-music bedding**: stripping+ * the timeline's silent track and laying the user-picked music file underneath+ * the video at a configurable gain, looped to fill + cut to the video length.+ *+ * Phase 4d.2 (`muxVoLines`) adds **voice-over muxing**: each rendered VO line+ * is delayed to its per-line offset and mixed onto the episode, and — when a+ * music bed is present — the music is **ducked** under the dialogue via+ * sidechain compression so speech stays intelligible. `muxVoLines` supersedes+ * `muxMusicBed` whenever the issue has placed VO lines; music-only issues still+ * take the simpler `muxMusicBed` 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.*/import { join } from 'path';@@ -26,6 +36,16 @@ import { statMusicTrack } from './musicLibrary.js';// (4d.2), but not so quiet the user wonders if it's there.const DEFAULT_MUSIC_GAIN = 0.5;+// Sidechain-ducking defaults — the music bed (sidechain input) is compressed+// whenever the VO track (sidechain key) exceeds the threshold. ratio=8 ++// a low threshold pulls the bed well down under speech; release=300ms lets the+// music swell back smoothly in the gaps between lines.+const DEFAULT_DUCK = Object.freeze({ threshold: 0.05, ratio: 8, attack: 20, release: 300 });++// Shared aformat target so every chain mixes at one sample rate / layout —+// sidechaincompress + amix both require their inputs to agree.+const AFMT = 'aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo';+/*** Resolve a library music filename to its absolute path on disk, or null* when the file is missing / the filename fails validation. Graceful@@ -82,4 +102,110 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAUreturn { ok: true };}-export { DEFAULT_MUSIC_GAIN };+/**+ * Build the ffmpeg argv for a VO-line mux. Pure — unit-tested without spawning.+ *+ * Input order is fixed: video is input 0, each VO line is inputs 1..N (in the+ * order given), and the optional looped music bed is input N+1. `voLines` MUST+ * already be filtered to entries with an on-disk `path` and a finite, >= 0+ * `offsetSec` (muxVoLines does this) — this builder trusts its input.+ *+ * Filter graph:+ * - 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+ * - 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 }) {+ const args = ['-i', inputVideoPath];+ for (const line of voLines) args.push('-i', line.path);+ 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]';+ }++ if (musicPath) {+ const musicIdx = voLines.length + 1;+ const gain = Number(musicGain).toFixed(3);+ chains.push(`${voMixLabel}asplit=2[vosc][vomain]`);+ 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]`);+ chains.push(`[ducked][vomain]amix=inputs=2:normalize=0,apad[aout]`);+ } else {+ chains.push(`${voMixLabel}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 VO lines (and, when present, a ducked music bed) onto+ * `inputVideoPath`, replacing the file in place. Returns `{ ok: true }` on+ * success or `{ ok: false, reason }` on any failure (graceful degradation —+ * the caller keeps the prior video).+ *+ * `voLines` is `[{ path, offsetSec }]`; entries without an on-disk file or a+ * finite, >= 0 offset are dropped (un-placed lines stay silent rather than+ * stacking at t=0). With no usable lines this returns ok:false so the caller+ * can fall back to the music-only `muxMusicBed` path.+ */+export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = null, musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, signal } = {}) {+ if (!inputVideoPath || !existsSync(inputVideoPath)) {+ return { ok: false, reason: 'input video missing' };+ }+ const placed = (Array.isArray(voLines) ? voLines : []).filter((l) => {+ const off = Number(l?.offsetSec);+ return l?.path && existsSync(l.path) && Number.isFinite(off) && off >= 0;+ });+ if (!placed.length) return { ok: false, reason: 'no placed VO lines' };+ // A missing music file is not fatal — drop to a VO-only mux rather than+ // failing, so a stale `music.trackFilename` pointer can't suppress dialogue.+ const usableMusic = musicPath && existsSync(musicPath) ? musicPath : null;++ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not on PATH' };++ const tmpOut = `${inputVideoPath}.vomux.${randomUUID()}.mp4`;+ const args = buildVoMuxArgs({ inputVideoPath, voLines: placed, musicPath: usableMusic, musicGain, duck, 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, lineCount: placed.length, ducked: !!usableMusic };+}++export { DEFAULT_MUSIC_GAIN, DEFAULT_DUCK };diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsindex 59a955e964..1ea6c3da6b 100644--- a/server/services/pipeline/audioMux.test.js+++ b/server/services/pipeline/audioMux.test.js@@ -60,7 +60,7 @@ vi.mock('child_process', async () => {};});-const { muxMusicBed, resolveMusicTrackPath, DEFAULT_MUSIC_GAIN } = await import('./audioMux.js');+const { muxMusicBed, muxVoLines, buildVoMuxArgs, resolveMusicTrackPath, DEFAULT_MUSIC_GAIN } = await import('./audioMux.js');beforeEach(async () => {spawnCalls.length = 0;@@ -179,3 +179,131 @@ describe('muxMusicBed', () => {expect(result.reason).toContain('last line of stderr');});});++describe('buildVoMuxArgs', () => {+ it('delays each VO line to its offset and pads to video length (no music)', () => {+ const args = buildVoMuxArgs({+ inputVideoPath: '/v.mp4',+ voLines: [{ path: '/a.wav', offsetSec: 1.5 }, { path: '/b.wav', offsetSec: 4 }],+ outPath: '/out.mp4',+ });+ // video is input 0, the two VO wavs are inputs 1 and 2 (no music input)+ expect(args.slice(0, 6)).toEqual(['-i', '/v.mp4', '-i', '/a.wav', '-i', '/b.wav']);+ expect(args).not.toContain('-stream_loop');+ const filter = args[args.indexOf('-filter_complex') + 1];+ // offsets become adelay milliseconds, all channels+ expect(filter).toContain('[1:a]adelay=1500:all=1');+ expect(filter).toContain('[2:a]adelay=4000:all=1');+ // two lines → amix at full level, then padded so -shortest matches video+ expect(filter).toContain('amix=inputs=2:normalize=0');+ expect(filter).toContain('apad[aout]');+ // no music → no sidechain ducking+ expect(filter).not.toContain('sidechaincompress');+ expect(args).toContain('-shortest');+ expect(args[args.indexOf('-map') + 1]).toBe('0:v');+ expect(args[args.length - 1]).toBe('/out.mp4');+ });++ it('ducks the music bed under VO via sidechain compression when music is present', () => {+ const args = buildVoMuxArgs({+ inputVideoPath: '/v.mp4',+ voLines: [{ path: '/a.wav', offsetSec: 0 }],+ musicPath: '/m.mp3',+ musicGain: 0.4,+ outPath: '/out.mp4',+ });+ // 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[vosc][vomain]');+ 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,apad[aout]');+ });++ it('uses a single VO label without amix for one line', () => {+ const args = buildVoMuxArgs({+ inputVideoPath: '/v.mp4',+ voLines: [{ path: '/a.wav', offsetSec: 2 }],+ outPath: '/out.mp4',+ });+ const filter = args[args.indexOf('-filter_complex') + 1];+ expect(filter).toContain('[vo0]apad[aout]');+ expect(filter).not.toContain('amix');+ });+});++describe('muxVoLines', () => {+ it('returns ok:false when no VO line is placed (lets caller fall back to music bed)', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'v.mp4');+ await writeFile(video, Buffer.from('vid'));+ // line missing offsetSec → not placed; non-existent path → dropped+ const result = await muxVoLines(video, { voLines: [+ { path: join(TEST_HOME, 'a.wav'), offsetSec: null },+ { path: join(TEST_HOME, 'ghost.wav'), offsetSec: 2 },+ ] });+ expect(result).toEqual({ ok: false, reason: 'no placed VO lines' });+ expect(spawnCalls).toHaveLength(0);+ });++ it('returns ok:false when the input video is missing', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const result = await muxVoLines(join(TEST_HOME, 'nope.mp4'), { voLines: [{ path: 'x', offsetSec: 0 }] });+ expect(result.ok).toBe(false);+ expect(result.reason).toBe('input video missing');+ expect(spawnCalls).toHaveLength(0);+ });++ it('builds the VO mux and swaps the file in on success', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ 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: 3 }] });+ expect(result.ok).toBe(true);+ expect(result.lineCount).toBe(1);+ expect(result.ducked).toBe(false);+ expect(spawnCalls).toHaveLength(1);+ const { args } = spawnCalls[0];+ expect(args[args.indexOf('-filter_complex') + 1]).toContain('adelay=3000:all=1');+ // output is a uniquely-suffixed temp that gets renamed over the input+ expect(args[args.length - 1]).toMatch(/\.vomux\.[0-9a-f-]+\.mp4$/);+ });++ it('drops a missing music file to a VO-only mux rather than failing', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ 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: 0 }],+ musicPath: join(TEST_HOME, 'gone.mp3'),+ });+ expect(result.ok).toBe(true);+ expect(result.ducked).toBe(false);+ const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];+ expect(filter).not.toContain('sidechaincompress');+ });++ it('ducks the music bed when both VO and a real music file are present', async () => {+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');+ const video = join(TEST_HOME, 'v.mp4');+ const wav = join(TEST_HOME, 'a.wav');+ const music = join(FAKE_MUSIC_DIR, 'm.mp3');+ await writeFile(video, Buffer.from('vid'));+ await writeFile(wav, Buffer.from('wav'));+ await writeFile(music, Buffer.from('mus'));++ const result = await muxVoLines(video, { voLines: [{ path: wav, offsetSec: 1 }], musicPath: music });+ expect(result.ok).toBe(true);+ expect(result.ducked).toBe(true);+ const filter = spawnCalls[0].args[spawnCalls[0].args.indexOf('-filter_complex') + 1];+ expect(filter).toContain('sidechaincompress');+ });+});diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex c0721459a5..aefce3de01 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -382,6 +382,20 @@ const AUDIO_LINE_TEXT_MAX = 4000;const AUDIO_LINES_MAX = 1000;const AUDIO_FILENAME_MAX = 500;const AUDIO_LINE_ID_MAX = 80;+// Cap a per-line VO offset at a generous episode length so a corrupted record+// can't push an `adelay` filter into absurd territory. Two hours is far beyond+// any single issue's runtime.+const AUDIO_LINE_OFFSET_MAX_SEC = 7200;+// Normalize a per-line start offset (seconds into the stitched episode where+// this VO line plays). `null` = "not placed yet" — kept distinct from `0`+// ("plays at the very start") so the muxer can skip un-placed lines instead of+// stacking them all at t=0. Negative / non-finite input collapses to null.+export const sanitizeLineOffset = (raw) => {+ if (raw === null || raw === undefined) return null;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) return null;+ return Math.min(n, AUDIO_LINE_OFFSET_MAX_SEC);+};const sanitizeAudioLine = (raw, i) => {if (!raw || typeof raw !== 'object') return null;const text = trimTo(raw.text, AUDIO_LINE_TEXT_MAX);@@ -397,6 +411,9 @@ const sanitizeAudioLine = (raw, i) => {audioFilename: isStr(raw.audioFilename) && raw.audioFilename? raw.audioFilename.slice(0, AUDIO_FILENAME_MAX): null,+ // Per-line start offset for muxing VO into the stitched episode (Phase+ // 4d.2). null until the user (or a future auto-spacer) places it.+ offsetSec: sanitizeLineOffset(raw.offsetSec),};};diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex beb25ba0ae..dd22ba6f47 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -1262,4 +1262,36 @@ describe('pipeline issues service', () => {expect(after.number).toBe(3); // renumber also applied});});++ describe('sanitizeLineOffset (VO per-line offset)', () => {+ it('keeps a valid non-negative number, distinguishing 0 from null', () => {+ expect(svc.sanitizeLineOffset(0)).toBe(0);+ expect(svc.sanitizeLineOffset(3.5)).toBe(3.5);+ });+ it('treats absent / cleared as null (un-placed), not 0', () => {+ expect(svc.sanitizeLineOffset(null)).toBeNull();+ expect(svc.sanitizeLineOffset(undefined)).toBeNull();+ });+ it('collapses negative / non-finite input to null', () => {+ expect(svc.sanitizeLineOffset(-1)).toBeNull();+ expect(svc.sanitizeLineOffset(NaN)).toBeNull();+ expect(svc.sanitizeLineOffset('abc')).toBeNull();+ });+ it('clamps an absurd offset to the 2-hour ceiling', () => {+ expect(svc.sanitizeLineOffset(999999)).toBe(7200);+ });+ it('round-trips through the audio stage sanitizer', async () => {+ const issue = await svc.createIssue({ seriesId: 'ser-1', title: 'E1' });+ const { stage } = await svc.updateStage(issue.id, 'audio', {+ lines: [+ { id: 'line-001', text: 'Hello', offsetSec: 4.2 },+ { id: 'line-002', text: 'World', offsetSec: -5 }, // invalid → null+ { id: 'line-003', text: 'Quiet' }, // absent → null+ ],+ });+ expect(stage.lines[0].offsetSec).toBe(4.2);+ expect(stage.lines[1].offsetSec).toBeNull();+ expect(stage.lines[2].offsetSec).toBeNull();+ });+ });});diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsnew file mode 100644index 0000000000..b34b972522--- /dev/null+++ b/server/services/pipeline/musicGen.js@@ -0,0 +1,199 @@+/**+ * Local OSS music generation — MusicGen via MLX (Pipeline Audio Phase 4c.2).+ *+ * The first generator behind the audio stage's `source: 'gen'` library entry.+ * Meta's MusicGen (MLX port) renders bounded text-conditioned clips on-device:+ * no network, no API key — the same "local OSS first" posture as the Kokoro /+ * Piper voice path in `audio.js`. A future 3rd-party engine (Suno, etc.) would+ * plug in here as a sibling generator behind the same `generateMusic` contract;+ * we ship local-only for now per the product decision.+ *+ * Runtime: the MLX MusicGen code lives in ml-explore/mlx-examples (not a pip+ * package), so generation needs the opt-in venv + clone from+ * `INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh`. When that isn't set+ * up, `generateMusic` throws a 503 with the install hint rather than a bare+ * spawn error — exactly like the FLUX.2 venv gate.+ *+ * Output: a 32 kHz mono WAV written into the shared music library (PATHS.music)+ * under a `music-gen-<uuid>.wav` basename, so the picker treats a generated+ * track identically to an uploaded one.+ */++import { spawn } from 'child_process';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { randomUUID } from 'crypto';+import { PATHS, ensureDir } from '../../lib/fileUtils.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';+import { hfTokenEnv } from '../../lib/hfToken.js';+import { resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT } from '../../lib/pythonSetup.js';+import { ServerError } from '../../lib/errorHandler.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+// scripts/generate_musicgen.py lives at the repo root — resolve module-relative+// so the path is correct regardless of the server process's cwd.+const SIDECAR_SCRIPT = join(__dirname, '../../../scripts/generate_musicgen.py');++// Practical clip-length window. MusicGen was trained on 30s windows and+// degrades past that; the floor keeps at least one decoder step.+export const MIN_DURATION_SEC = 1;+export const MAX_DURATION_SEC = 30;+export const DEFAULT_DURATION_SEC = 12;++// Registry of selectable generators. "Pick generator first" (the PLAN's+// gating decision) resolves to MusicGen across three size tiers; medium is the+// default — a quality/speed balance that fits comfortably in unified memory.+// Kept as a small in-module constant rather than threaded through the+// image/video `media-models.json` registry, whose seed/merge/migration+// machinery doesn't apply to a one-shot audio generator.+export const MUSICGEN_MODELS = Object.freeze([+ { id: 'musicgen-small', repo: 'facebook/musicgen-small', name: 'MusicGen Small (~2 GB, fastest)' },+ { id: 'musicgen-medium', repo: 'facebook/musicgen-medium', name: 'MusicGen Medium (~6 GB, balanced)' },+ { id: 'musicgen-large', repo: 'facebook/musicgen-large', name: 'MusicGen Large (~13 GB, best quality)' },+]);+export const DEFAULT_MUSICGEN_MODEL_ID = 'musicgen-medium';++export function getMusicgenModel(modelId) {+ return MUSICGEN_MODELS.find((m) => m.id === modelId) || null;+}++// Whether the opt-in MusicGen venv is provisioned. The UI gates its "Generate"+// affordance on this so users see an install hint instead of a 503 after+// typing a prompt. Cheap (an existsSync probe behind resolveMusicgenPython's+// cache) — safe to call per request.+export function isMusicGenReady() {+ return resolveMusicgenPython() !== null;+}++// Clamp a requested duration into the model's usable window. Non-finite input+// falls back to the default rather than throwing — the route validates shape,+// this guards the math.+export function clampDuration(durationSec) {+ const n = Number(durationSec);+ if (!Number.isFinite(n)) return DEFAULT_DURATION_SEC;+ return Math.max(MIN_DURATION_SEC, Math.min(MAX_DURATION_SEC, n));+}++/**+ * Build the `{ bin, args }` for the MusicGen sidecar. Pure — unit-tested+ * without spawning Python. `runtimeDir` is the mlx-examples musicgen/ package+ * dir the sidecar adds to sys.path.+ */+export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, runtimeDir = MUSICGEN_RUNTIME_DIR, repo, prompt, durationSec, outputPath }) {+ return {+ bin: pythonPath,+ args: [+ scriptPath,+ '--model', repo,+ '--text', prompt,+ '--duration', String(clampDuration(durationSec)),+ '--output', outputPath,+ '--runtime-dir', runtimeDir,+ ],+ };+}++// Pull the saved path + actual duration out of the sidecar's `RESULT:<json>`+// line. Returns null when no parseable result line is present so the caller+// can fail with a useful message instead of a malformed success.+function parseResultLine(stdout) {+ const line = (stdout || '').split(/\r?\n/).reverse().find((l) => l.startsWith('RESULT:'));+ if (!line) return null;+ try {+ return JSON.parse(line.slice('RESULT:'.length));+ } catch {+ return null;+ }+}++/**+ * Generate a background-music track and land it in the shared music library.+ * Returns `{ filename, durationSec, modelId, model }`. Throws a ServerError+ * (503) when the MusicGen venv isn't provisioned, or (500) when the sidecar+ * exits non-zero / produces no result.+ *+ * `signal` (optional AbortSignal) SIGTERMs the child — wired through so a+ * future cancel button can abort a long render.+ */+export async function generateMusic({ prompt, durationSec = DEFAULT_DURATION_SEC, modelId = DEFAULT_MUSICGEN_MODEL_ID, signal } = {}) {+ const text = (prompt || '').trim();+ if (!text) {+ throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });+ }+ const model = getMusicgenModel(modelId) || getMusicgenModel(DEFAULT_MUSICGEN_MODEL_ID);+ const pythonPath = resolveMusicgenPython();+ if (!pythonPath) {+ throw new ServerError(+ `MusicGen runtime not found. Run \`INSTALL_MUSICGEN=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected venv at ${MUSICGEN_VENV_DEFAULT}).`,+ { status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' },+ );+ }++ await ensureDir(PATHS.music);+ const filename = `music-gen-${randomUUID()}.wav`;+ const outputPath = join(PATHS.music, filename);+ const { bin, args } = buildMusicGenArgs({ pythonPath, repo: model.repo, prompt: text, durationSec, outputPath });++ console.log(`🎼 Generating music [${model.id}] ${clampDuration(durationSec)}s: "${text.slice(0, 60)}"`);+ // MusicGen's facebook/* weights are ungated, so a token isn't required — but+ // pass it through when the user has one set so the first download doesn't hit+ // anonymous HF rate limits.+ const env = safeChildProcessEnv(await hfTokenEnv());+ const result = await runMusicGenProcess({ bin, args, env, signal });+ if (!result.ok) {+ throw new ServerError(`Music generation failed: ${result.reason}`, {+ status: 500, code: 'PIPELINE_MUSIC_GEN_FAILED',+ });+ }+ const parsed = parseResultLine(result.stdout);+ return {+ filename,+ durationSec: Number.isFinite(parsed?.durationSec) ? parsed.durationSec : clampDuration(durationSec),+ modelId: model.id,+ model: model.name,+ };+}++// Spawn the sidecar and resolve `{ ok, stdout, reason? }`. STAGE: lines on+// stderr are echoed to pm2 logs so a stuck first-run model download is visible+// (mirrors the image/video sidecars). Captures stdout for the RESULT line and+// a bounded stderr tail for the failure reason. Not a route handler — the+// spawn-error / close branches must not throw (they run outside the Express+// lifecycle), so they resolve a structured result instead.+function runMusicGenProcess({ bin, args, env, signal }) {+ return new Promise((resolve) => {+ const proc = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });+ let stdout = '';+ let stderrTail = '';+ const STDERR_TAIL = 4000;+ let settled = false;+ const finish = (val) => { if (!settled) { settled = true; cleanup(); resolve(val); } };++ let onAbort = null;+ const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };+ if (signal) {+ onAbort = () => proc.kill('SIGTERM');+ signal.addEventListener('abort', onAbort, { once: true });+ }++ proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });+ proc.stderr.on('data', (chunk) => {+ const s = chunk.toString();+ stderrTail = (stderrTail + s).slice(-STDERR_TAIL);+ for (const line of s.split(/\r?\n/)) {+ const t = line.trim();+ if (t.startsWith('STAGE:')) console.log(`🎼 musicgen ${t.slice('STAGE:'.length)}`);+ }+ });+ proc.on('error', (err) => finish({ ok: false, reason: `spawn failed: ${err.message}`, stdout }));+ proc.on('close', (code, sig) => {+ if (sig === 'SIGTERM' || sig === 'SIGKILL') { finish({ ok: false, reason: `cancelled (${sig})`, stdout }); return; }+ if (code !== 0) {+ const tail = stderrTail.split(/\r?\n/).filter(Boolean).slice(-3).join(' | ');+ finish({ ok: false, reason: tail || `exit ${code}`, stdout });+ return;+ }+ finish({ ok: true, stdout });+ });+ });+}diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.jsnew file mode 100644index 0000000000..9f03cee17f--- /dev/null+++ b/server/services/pipeline/musicGen.test.js@@ -0,0 +1,82 @@+import { describe, it, expect } from 'vitest';+import {+ buildMusicGenArgs,+ clampDuration,+ getMusicgenModel,+ MUSICGEN_MODELS,+ DEFAULT_MUSICGEN_MODEL_ID,+ MIN_DURATION_SEC,+ MAX_DURATION_SEC,+ DEFAULT_DURATION_SEC,+} from './musicGen.js';++describe('MUSICGEN_MODELS registry', () => {+ it('has a stable, unique id + repo for each model', () => {+ const ids = MUSICGEN_MODELS.map((m) => m.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const m of MUSICGEN_MODELS) {+ expect(typeof m.id).toBe('string');+ expect(m.repo).toMatch(/^facebook\/musicgen-/);+ expect(typeof m.name).toBe('string');+ }+ });++ it('default model id resolves to a real entry', () => {+ expect(getMusicgenModel(DEFAULT_MUSICGEN_MODEL_ID)).toBeTruthy();+ });++ it('getMusicgenModel returns null for unknown ids', () => {+ expect(getMusicgenModel('nope')).toBeNull();+ expect(getMusicgenModel(undefined)).toBeNull();+ });+});++describe('clampDuration', () => {+ it('passes through an in-range value', () => {+ expect(clampDuration(12)).toBe(12);+ });+ it('floors at MIN and caps at MAX', () => {+ expect(clampDuration(0)).toBe(MIN_DURATION_SEC);+ expect(clampDuration(-5)).toBe(MIN_DURATION_SEC);+ expect(clampDuration(9999)).toBe(MAX_DURATION_SEC);+ });+ it('falls back to the default on non-finite input', () => {+ expect(clampDuration(NaN)).toBe(DEFAULT_DURATION_SEC);+ expect(clampDuration('abc')).toBe(DEFAULT_DURATION_SEC);+ expect(clampDuration(undefined)).toBe(DEFAULT_DURATION_SEC);+ });+});++describe('buildMusicGenArgs', () => {+ const base = {+ pythonPath: '/venv/bin/python3',+ repo: 'facebook/musicgen-medium',+ prompt: 'tense cinematic synth',+ durationSec: 10,+ outputPath: '/data/music/music-gen-abc.wav',+ runtimeDir: '/home/u/.portos/mlx-examples/musicgen',+ };++ it('builds the sidecar argv with every flag the script expects', () => {+ const { bin, args } = buildMusicGenArgs(base);+ expect(bin).toBe('/venv/bin/python3');+ expect(args[0]).toMatch(/generate_musicgen\.py$/);+ const flag = (name) => args[args.indexOf(name) + 1];+ expect(flag('--model')).toBe('facebook/musicgen-medium');+ expect(flag('--text')).toBe('tense cinematic synth');+ expect(flag('--output')).toBe('/data/music/music-gen-abc.wav');+ expect(flag('--runtime-dir')).toBe('/home/u/.portos/mlx-examples/musicgen');+ });++ it('passes the clamped duration as a string', () => {+ const { args } = buildMusicGenArgs({ ...base, durationSec: 9999 });+ const dur = args[args.indexOf('--duration') + 1];+ expect(dur).toBe(String(MAX_DURATION_SEC));+ expect(typeof dur).toBe('string');+ });++ it('clamps a sub-minimum duration', () => {+ const { args } = buildMusicGenArgs({ ...base, durationSec: 0 });+ expect(args[args.indexOf('--duration') + 1]).toBe(String(MIN_DURATION_SEC));+ });+});