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(music-video): automatic lyric import, whisper alignment and demucs vocal stems (#9233)
[._.]/3948abcc2cbf
diff --git a/.env.example b/.env.exampleindex 1b7e41336e..a7fee17bf3 100644--- a/.env.example+++ b/.env.example@@ -310,6 +310,10 @@ PGPASSWORD=portos# LM Studio model id auto-installed for voice tool calling (default: built-in fallback chain)# PORTOS_VOICE_DEFAULT_TOOL_MODEL=lmstudio-community/Qwen2.5-3B-Instruct-GGUF+# Music Video "Separate vocals" installs demucs into its own venv on first use+# (services/musicVideo/vocalSeparation.js; default: ~/.portos/venvs/demucs).+# PORTOS_DEMUCS_VENV_DIR=/path/to/venvs/demucs+# Signal Desktop install directory read by Signal sync (signalSync.js; default:# ~/Library/Application Support/Signal). SIGNAL_CONFIG_PATH and SIGNAL_DB_PATH are# derived from it, so relocating a Signal install usually only needs this one.diff --git a/client/src/components/musicVideo/AutomationPanel.jsx b/client/src/components/musicVideo/AutomationPanel.jsxindex ea14732ac2..2ab6b68c81 100644--- a/client/src/components/musicVideo/AutomationPanel.jsx+++ b/client/src/components/musicVideo/AutomationPanel.jsx@@ -10,10 +10,12 @@ const actionClass = 'text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1';/*** The project's automation brief — tools, guidance, budget — shown first on- * the board, with a one-click kickoff (analyze the song, then plan every shot- * against the brief). Edits PATCH through `onSave`, which owns the error toast.+ * the board, with a one-click kickoff (analyze the song, import the track's+ * lyrics, separate vocals, align words, then plan every shot against the+ * brief). `kickoffStep` names the step running now. Edits PATCH through+ * `onSave`, which owns the error toast.*/-export default function AutomationPanel({ project, onSave, onKickoff, kickoffBusy, kickoffBlockedReason }) {+export default function AutomationPanel({ project, onSave, onKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason }) {const [draft, setDraft] = useState(null);const [saving, setSaving] = useState(false);const automation = project.automation || null;@@ -55,7 +57,7 @@ export default function AutomationPanel({ project, onSave, onKickoff, kickoffBustype="button"onClick={onKickoff}disabled={kickoffBusy || !!kickoffBlockedReason}- title={kickoffBlockedReason || 'Analyze the song, then plan every shot against the brief'}+ title={kickoffBlockedReason || 'Analyze the song, import its lyrics, separate and align the vocal, then plan every shot against the brief'}className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"><Play size={14} /> {kickoffBusy ? 'Working…' : 'Analyze & plan'}@@ -73,6 +75,7 @@ export default function AutomationPanel({ project, onSave, onKickoff, kickoffBus<p className="text-xs text-port-text-muted break-words line-clamp-3">{automation.guidance || 'No guidance yet — the agent plans from the song, universe and board alone.'}</p>+ {kickoffStep && <p className="text-xs text-port-accent" role="status">{kickoffStep}</p>}{kickoffBlockedReason && <p className="text-xs text-port-warning">{kickoffBlockedReason}</p>}</>);diff --git a/client/src/components/musicVideo/AutomationPanel.test.jsx b/client/src/components/musicVideo/AutomationPanel.test.jsxnew file mode 100644index 0000000000..27a4af993b--- /dev/null+++ b/client/src/components/musicVideo/AutomationPanel.test.jsx@@ -0,0 +1,109 @@+/**+ * Autopilot kickoff ("Analyze & plan"): the steps run in order on the+ * freshest project, the panel names the step that is running, a step whose+ * result already exists is skipped, and a failed lyric step still plans while+ * a failed analysis stops the run.+ */+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import AutomationPanel from './AutomationPanel.jsx';+import useMusicVideoKickoff from '../../hooks/useMusicVideoKickoff.js';++const automation = { tools: ['local-image'], guidance: 'Moody neon', budgetUsd: null };++function deferred() {+ let resolve;+ const promise = new Promise((r) => { resolve = r; });+ return { promise, resolve };+}++function Harness({ project, steps }) {+ const kickoff = useMusicVideoKickoff(steps);+ return (+ <AutomationPanel+ project={project}+ onSave={vi.fn()}+ onKickoff={() => kickoff.run(project)}+ kickoffBusy={kickoff.running}+ kickoffStep={kickoff.stepLabel}+ />+ );+}++const cue = (id, text, words) => ({ id, text, startSec: null, endSec: null, ...(words ? { words } : {}) });++describe('AutomationPanel autopilot kickoff', () => {+ it('analyzes, imports track lyrics, separates vocals, aligns and plans — showing each step', async () => {+ const order = [];+ const base = { id: 'mv-1', trackId: 't1', automation, lyricCues: [] };+ const analyzed = { ...base, audioAnalysis: { sections: [] } };+ const withLyrics = { ...analyzed, lyricCues: [cue('lc-1', 'hold on')] };+ const withStem = { ...withLyrics, vocalStemFilename: 'stem.wav' };+ const aligned = { ...withStem, lyricCues: [cue('lc-1', 'hold on', [{ w: 'hold' }, { w: 'on' }])] };+ const separating = deferred();+ const steps = {+ analyze: vi.fn(async () => { order.push('analyze'); return analyzed; }),+ importLyrics: vi.fn(async (p) => { order.push(['lyrics', p]); return withLyrics; }),+ separateVocals: vi.fn((p) => { order.push(['vocals', p]); return separating.promise; }),+ alignLyrics: vi.fn(async (p) => { order.push(['align', p]); return aligned; }),+ plan: vi.fn(async (p) => { order.push(['plan', p]); }),+ };+ render(<Harness project={base} steps={steps} />);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));++ expect(await screen.findByRole('status')).toHaveTextContent('Separating vocals…');+ expect(screen.getByRole('button', { name: /Working/ }).disabled).toBe(true);+ separating.resolve(withStem);++ await waitFor(() => expect(steps.plan).toHaveBeenCalled());+ expect(order).toEqual([+ 'analyze',+ ['lyrics', analyzed],+ ['vocals', withLyrics],+ ['align', withStem],+ ['plan', aligned],+ ]);+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());+ });++ it('skips what already exists, and still plans when the lyric import fails', async () => {+ const project = {+ id: 'mv-2', trackId: 't1', automation, audioAnalysis: { sections: [] }, vocalStemFilename: 'stem.wav', lyricCues: [],+ };+ const steps = {+ analyze: vi.fn(),+ importLyrics: vi.fn(async () => null),+ separateVocals: vi.fn(),+ alignLyrics: vi.fn(),+ plan: vi.fn(async () => {}),+ };+ render(<Harness project={project} steps={steps} />);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(steps.plan).toHaveBeenCalledWith(project));+ expect(steps.analyze).not.toHaveBeenCalled();+ expect(steps.importLyrics).toHaveBeenCalledOnce();+ // No lyric lines means nothing to separate or align.+ expect(steps.separateVocals).not.toHaveBeenCalled();+ expect(steps.alignLyrics).not.toHaveBeenCalled();+ });++ it('stops when the analysis fails', async () => {+ const analyzing = deferred();+ const steps = {+ analyze: vi.fn(() => analyzing.promise),+ importLyrics: vi.fn(),+ separateVocals: vi.fn(),+ alignLyrics: vi.fn(),+ plan: vi.fn(),+ };+ render(<Harness project={{ id: 'mv-3', trackId: 't1', automation, lyricCues: [] }} steps={steps} />);+ const button = screen.getByRole('button', { name: /Analyze & plan/ });+ fireEvent.click(button);+ expect(await screen.findByRole('status')).toHaveTextContent('Analyzing the song…');+ analyzing.resolve(null);+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());+ expect(steps.analyze).toHaveBeenCalledOnce();+ expect(steps.importLyrics).not.toHaveBeenCalled();+ expect(steps.plan).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsxindex bacb65e9ef..5591828160 100644--- a/client/src/components/musicVideo/LyricsPanel.jsx+++ b/client/src/components/musicVideo/LyricsPanel.jsx@@ -1,5 +1,5 @@import { useRef, useState } from 'react';-import { Plus, Trash2, Upload } from 'lucide-react';+import { ListMusic, Plus, Trash2, Upload } from 'lucide-react';// Client-minted ids keep a freshly added row addressable across saves without// waiting for the server (crypto.randomUUID is unavailable on the plain-HTTP@@ -94,8 +94,28 @@ function WordTimingRow({ cue, onPreview, onCommit }) {* correct it. Changing a line's text drops its word timings. Changing the* project's audio clears every timing (the text stays).*/-export default function LyricsPanel({ project, onEditLocal, onSave, onImport, importing, onAlign, aligning = false }) {+// Marker chips read the sheet's structure back to the director: sections in+// the accent colour, delivery directions muted.+function MarkerChips({ markers }) {+ if (!markers?.length) return null;+ return (+ <div className="flex flex-wrap gap-1 pt-1">+ {markers.map((marker, index) => (+ <span key={`${marker.type}-${marker.label}-${index}`}+ title={marker.type === 'section' ? 'Section from the lyric sheet' : 'Delivery direction from the lyric sheet'}+ className={`rounded px-1.5 py-0.5 text-[10px] break-words ${marker.type === 'section' ? 'bg-port-accent/20 text-port-accent font-medium' : 'bg-port-border text-port-text-muted italic'}`}>+ {marker.type === 'section' ? marker.label : `[${marker.label}]`}+ </span>+ ))}+ </div>+ );+}++export default function LyricsPanel({ project, onEditLocal, onSave, onImport, importing, onImportTrack, onAlign, aligning = false }) {const cues = project.lyricCues || [];+ const markers = project.lyricMarkers || [];+ const markersAt = (line) => markers.filter((marker) => marker.line === line);+ const trailingMarkers = markers.filter((marker) => marker.line >= cues.length);const phrases = project.phrases || [];const pacing = project.pacing || {};const [importText, setImportText] = useState('');@@ -140,7 +160,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imif (!onAlign || aligning) return;setAlignError('');Promise.resolve(onAlign(cueId)).catch((err) => {- setAlignError(err?.message || 'Speech-to-text is not running. Enable the local whisper server in Settings → Voice, then try Align words again.');+ setAlignError(err?.message || 'Could not align the words to the vocal. Try Align words again.');});};const editWords = (id, words, save) => {@@ -159,7 +179,16 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im<div className="mt-2 grid grid-cols-1 gap-3 lg:grid-cols-2"><section className="space-y-2 min-w-0">- <h4 className="font-medium text-port-text">Import lyrics</h4>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h4 className="font-medium text-port-text">Import lyrics</h4>+ {onImportTrack && project.trackId && (+ <button type="button" onClick={onImportTrack} disabled={importing}+ title={cues.length ? 'Replace these lines with the linked track\'s lyric sheet' : 'Use the linked track\'s lyric sheet'}+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0 disabled:opacity-50">+ <ListMusic size={13} /> Use track lyrics+ </button>+ )}+ </div><label htmlFor="mv-lyrics-import" className="sr-only">Lyrics to import</label><textarea id="mv-lyrics-import" rows={3} value={importText} onChange={(e) => setImportText(e.target.value)}placeholder={'Paste LRC ([00:12.50] line), SRT/WebVTT cues, or plain lines (imported untimed)'}@@ -212,7 +241,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im<span className="flex items-center gap-2">{onAlign && (<button type="button" onClick={() => runAlign()} disabled={aligning || cues.length === 0 || !hasAudio}- title={hasAudio ? 'Align each word to the vocal' : 'Attach a song before aligning words'}+ title={hasAudio ? 'Align each word to the vocal with local whisper.cpp (the first run downloads a 1.6 GB model)' : 'Attach a song before aligning words'}className="min-h-[44px] sm:min-h-0 text-port-accent disabled:opacity-50">{aligning ? 'Aligning…' : 'Align words'}</button>@@ -226,6 +255,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im<div className="max-h-64 overflow-y-auto space-y-1 pr-1">{cues.map((cue, i) => (<div key={cue.id} className="space-y-1 border-b border-port-border/50 pb-1">+ <MarkerChips markers={markersAt(i)} /><div className="flex flex-wrap items-center gap-1"><input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} start (s)`} placeholder="start"value={cue.startSec ?? ''} onChange={(e) => editCue(cue.id, { startSec: toSec(e.target.value) })}@@ -254,6 +284,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imonCommit={(words) => editWords(cue.id, words, true)} /></div>))}+ {cues.length > 0 && <MarkerChips markers={trailingMarkers} />}</div><div className="flex items-center justify-between pt-1">diff --git a/client/src/components/musicVideo/LyricsPanel.test.jsx b/client/src/components/musicVideo/LyricsPanel.test.jsxindex f9a604e089..003c7786a6 100644--- a/client/src/components/musicVideo/LyricsPanel.test.jsx+++ b/client/src/components/musicVideo/LyricsPanel.test.jsx@@ -60,3 +60,28 @@ describe('LyricsPanel word alignment', () => {});});});++describe('LyricsPanel track lyrics', () => {+ it('offers the linked track\'s lyric sheet, and shows its sections and directions over the lines', () => {+ const onImportTrack = vi.fn();+ renderPanel({+ onImportTrack,+ project: {+ ...PROJECT,+ lyricMarkers: [+ { type: 'section', label: 'Chorus', kind: 'chorus', line: 0 },+ { type: 'direction', label: 'Whispered spoken', kind: 'whispered', line: 0 },+ ],+ },+ });+ expect(screen.getByText('Chorus')).toBeTruthy();+ expect(screen.getByText('[Whispered spoken]')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /Use track lyrics/ }));+ expect(onImportTrack).toHaveBeenCalledOnce();+ });++ it('has no track-lyrics button without a linked track', () => {+ renderPanel({ onImportTrack: vi.fn(), project: { ...PROJECT, trackId: null } });+ expect(screen.queryByRole('button', { name: /Use track lyrics/ })).toBeNull();+ });+});diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsxindex 5fa950e33c..1beec5d0b9 100644--- a/client/src/components/musicVideo/TrackPanel.jsx+++ b/client/src/components/musicVideo/TrackPanel.jsx@@ -18,7 +18,7 @@ import { trackSourceLabel } from '../../lib/trackProvenance.js';*/export default function TrackPanel({project, tracks, trackName, audioFilename, youtube,- renderBound, midiBound, onChangeTrack, onProjectUpdated,+ renderBound, midiBound, onChangeTrack, onProjectUpdated, separation = null,}) {const blockedMessage = renderBound? 'Wait for the current render to finish before changing the track'@@ -63,6 +63,7 @@ export default function TrackPanel({project={project}hasAudio={Boolean(project.trackId || project.uploadedAudioFilename)}onUpdated={onProjectUpdated}+ separation={separation}/>{/* #8988: an optional, explicitly chosen bed mixed under the song. */}<SoundBedControl key={project.id} project={project} tracks={tracks} disabled={renderBound} onUpdated={onProjectUpdated} />diff --git a/client/src/components/musicVideo/VocalStemControl.jsx b/client/src/components/musicVideo/VocalStemControl.jsxindex 86c173616e..67c9345756 100644--- a/client/src/components/musicVideo/VocalStemControl.jsx+++ b/client/src/components/musicVideo/VocalStemControl.jsx@@ -1,20 +1,28 @@import { useState } from 'react';-import { Mic, X } from 'lucide-react';+import { Mic, Wand2, X } from 'lucide-react';import toast from '../ui/Toast';import { uploadMusicVideoVocalStem, removeMusicVideoVocalStem } from '../../services/apiMusicVideo.js';const HELP = 'Optional. A full-length vocal bounce from the same session as the song, starting at 0:00. '+ 'Lip-sync performance shots are conditioned on it instead of the full mix. The final video keeps the song.';+const SEPARATE_HELP = 'Split the vocal out of the song with demucs and attach it as the stem. '+ + 'The first run installs demucs (a few minutes); after that a song takes seconds on Apple Silicon or an NVIDIA GPU.';+/**- * Attach, replace or remove the project's vocal stem (#8977). The server+ * Attach, replace or remove the project's vocal stem (#8977), or separate one+ * from the song (`separation`, a useMusicVideoVocalSeparation slot). The server* refuses a stem whose length does not match the song, since its timing would* not line up; the error toast says why.*/-export default function VocalStemControl({ project, hasAudio, onUpdated }) {+export default function VocalStemControl({ project, hasAudio, onUpdated, separation = null }) {const [busy, setBusy] = useState(false);const inputId = `mv-vocal-stem-${project.id}`;const stem = project.vocalStemFilename || null;+ const separating = Boolean(separation?.active && separation.context === project.id);+ const separationLabel = separating+ ? `${separation.stageLabel || 'Separating vocals…'}${separation.stage === 'separating' && separation.percent ? ` ${separation.percent}%` : ''}`+ : 'Separate vocals';const run = (call, success, failure) => {setBusy(true);@@ -35,7 +43,7 @@ export default function VocalStemControl({ project, hasAudio, onUpdated }) {};const remove = () => run(() => removeMusicVideoVocalStem(project.id, { silent: true }), 'Vocal stem removed', 'Failed to remove the vocal stem');- const disabled = busy || !hasAudio;+ const disabled = busy || !hasAudio || separating;return (<div className="mt-2 flex flex-wrap items-center gap-2 text-xs" title={hasAudio ? HELP : 'Link a track first'}><input id={inputId} type="file" accept="audio/*" className="sr-only" onChange={upload} disabled={disabled} />@@ -43,10 +51,23 @@ export default function VocalStemControl({ project, hasAudio, onUpdated }) {className={`flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0 ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-port-border/40'}`}><Mic size={13} /> {busy ? 'Working…' : stem ? 'Replace vocal stem' : 'Add vocal stem'}</label>+ {separation && (+ <button type="button" onClick={() => separation.start(project.id)} disabled={busy || !hasAudio || separation.active}+ title={hasAudio ? SEPARATE_HELP : 'Link a track first'} aria-live="polite"+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0 disabled:opacity-50">+ <Wand2 size={13} /> {separationLabel}+ </button>+ )}+ {separating && separation.jobId && (+ <button type="button" onClick={separation.cancel}+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0">+ Cancel+ </button>+ )}{stem ? (<><span className="text-port-text-muted break-all">Lip-sync uses {stem}</span>- <button type="button" onClick={remove} disabled={busy} aria-label="Remove vocal stem"+ <button type="button" onClick={remove} disabled={busy || separating} aria-label="Remove vocal stem"className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0 disabled:opacity-50"><X size={13} /> Remove</button>diff --git a/client/src/components/musicVideo/VocalStemControl.test.jsx b/client/src/components/musicVideo/VocalStemControl.test.jsxindex e0e2eca03a..90e0cfbbdf 100644--- a/client/src/components/musicVideo/VocalStemControl.test.jsx+++ b/client/src/components/musicVideo/VocalStemControl.test.jsx@@ -52,3 +52,24 @@ describe('VocalStemControl', () => {expect(screen.getByLabelText(/Add vocal stem/).disabled).toBe(true);});});++describe('VocalStemControl separation', () => {+ const slot = (overrides = {}) => ({+ active: false, context: null, jobId: null, stage: null, stageLabel: null, percent: 0,+ start: vi.fn(), cancel: vi.fn(), ...overrides,+ });++ it('starts a separation for this project, and shows its progress with a cancel while it runs', () => {+ const idle = slot();+ const { rerender } = render(<VocalStemControl project={project} hasAudio onUpdated={vi.fn()} separation={idle} />);+ fireEvent.click(screen.getByRole('button', { name: /Separate vocals/ }));+ expect(idle.start).toHaveBeenCalledWith('mv-1');++ const running = slot({ active: true, context: 'mv-1', jobId: 'job-1', stage: 'separating', stageLabel: 'Separating vocals…', percent: 40 });+ rerender(<VocalStemControl project={project} hasAudio onUpdated={vi.fn()} separation={running} />);+ expect(screen.getByRole('button', { name: /Separating vocals… 40%/ }).disabled).toBe(true);+ expect(screen.getByLabelText(/Add vocal stem/).disabled).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(running.cancel).toHaveBeenCalledOnce();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 343a0c434d..416ee50c57 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -248,6 +248,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. || `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |+| `useMusicVideoKickoff` | The Music Video autopilot kickoff sequence — analyze → import track lyrics → separate vocals → align words → plan — each step skipped when its result already exists and handed the freshest project. A failed analysis stops the run; a failed lyric/vocal/align step still plans. Returns `{ step, stepLabel, running, run(project) }`. | The Music Video "Analyze & plan" button. |+| `useMusicVideoVocalSeparation` | "Separate vocals" (demucs) as a `useSseJobSlot`: `start(projectId)` for the button, `run(projectId)` as a promise resolving with the project carrying its new stem (or null on failure/cancel), `stageLabel` for install/separation progress, `onSeparated(projectId, project)` on success. | The Music Video vocal-stem control and the autopilot kickoff. || `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. || `useMusicVideoProduction` | Server-owned production run (#9066): start a browserless plan → frames → clips → reviewed-draft run with an allowed provider/model pool and explicit limits, and Stop / Resume / Cancel it; applies the project pushed on `music-video:production` and toasts terminal outcomes. Returns `{ busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }`. | The Music Video production panel. || `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 0b74577ba2..5ba43290af 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -62,6 +62,7 @@ export * from './useMediaJobSse.js';export { default as useSceneRenderLifecycle } from './useSceneRenderLifecycle.js';export { default as useMusicVideoAutoReview } from './useMusicVideoAutoReview.js';export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';+export { default as useMusicVideoKickoff } from './useMusicVideoKickoff.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';@@ -71,6 +72,7 @@ export { default as useMusicVideoRevisions } from './useMusicVideoRevisions.js';export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';export { default as useMusicVideoTakes } from './useMusicVideoTakes.js';export { default as useMusicVideoTreatment } from './useMusicVideoTreatment.js';+export { default as useMusicVideoVocalSeparation } from './useMusicVideoVocalSeparation.js';export { default as useMusicVideoYoutubeImport } from './useMusicVideoYoutubeImport.js';export { default as useBeeperOutbox } from './useBeeperOutbox.js';export { default as useBeeperRealtime } from './useBeeperRealtime.js';diff --git a/client/src/hooks/useMusicVideoKickoff.js b/client/src/hooks/useMusicVideoKickoff.jsnew file mode 100644index 0000000000..21be198737--- /dev/null+++ b/client/src/hooks/useMusicVideoKickoff.js@@ -0,0 +1,68 @@+import { useRef, useState } from 'react';+import useMounted from './useMounted.js';++export const MUSIC_VIDEO_KICKOFF_STEPS = Object.freeze({+ analyze: 'Analyzing the song…',+ lyrics: 'Importing track lyrics…',+ vocals: 'Separating vocals…',+ align: 'Aligning words…',+ plan: 'Planning shots…',+});++const hasCues = (project) => (project?.lyricCues || []).length > 0;+// A step reports its own failure; one that throws or rejects anyway counts as+// failed rather than stranding the run half way.+const attempt = (step, project) => Promise.resolve().then(() => step(project)).catch(() => null);+const allAligned = (project) => hasCues(project) && project.lyricCues.every((cue) => (cue.words || []).length > 0);++/**+ * The Music Video autopilot kickoff ("Analyze & plan"): analyze → import the+ * track's lyrics → separate vocals → align words → plan. Each step is skipped+ * when its result already exists (a beat map, lyric lines, a vocal stem,+ * aligned words), so a re-run only does what is missing. Every step receives+ * the freshest project and resolves with the updated one, or null when it+ * failed (the step reports its own error). A failed analysis stops the run —+ * nothing can be planned without sections — while a failed lyric, vocal or+ * alignment step leaves the plan to work with what exists.+ *+ * Returns `{ step, stepLabel, running, run(project) }`; `step` names the+ * running step (a key of MUSIC_VIDEO_KICKOFF_STEPS).+ */+export default function useMusicVideoKickoff({ analyze, importLyrics, separateVocals, alignLyrics, plan }) {+ const [step, setStep] = useState(null);+ const busy = useRef(false);+ const mounted = useMounted();+ const enter = (id) => { if (mounted.current) setStep(id); };++ const run = async (start) => {+ if (!start || busy.current) return;+ busy.current = true;+ let project = start;+ try {+ if (!project.audioAnalysis) {+ enter('analyze');+ project = await attempt(analyze, project);+ if (!project?.audioAnalysis) return;+ }+ if (!hasCues(project) && project.trackId) {+ enter('lyrics');+ project = (await attempt(importLyrics, project)) || project;+ }+ if (hasCues(project) && !project.vocalStemFilename) {+ enter('vocals');+ project = (await attempt(separateVocals, project)) || project;+ }+ if (hasCues(project) && !allAligned(project)) {+ enter('align');+ project = (await attempt(alignLyrics, project)) || project;+ }+ enter('plan');+ await attempt(plan, project);+ } finally {+ busy.current = false;+ enter(null);+ }+ };++ return { step, stepLabel: step ? MUSIC_VIDEO_KICKOFF_STEPS[step] : null, running: step !== null, run };+}diff --git a/client/src/hooks/useMusicVideoVocalSeparation.js b/client/src/hooks/useMusicVideoVocalSeparation.jsnew file mode 100644index 0000000000..446cac0e9c--- /dev/null+++ b/client/src/hooks/useMusicVideoVocalSeparation.js@@ -0,0 +1,68 @@+import { useEffect, useRef } from 'react';+import useSseJobSlot from './useSseJobSlot.js';+import {+ separateMusicVideoVocals,+ musicVideoVocalSeparationEventsUrl,+ cancelMusicVideoVocalSeparation,+} from '../services/apiMusicVideo.js';++const STAGE_LABELS = {+ preparing: 'Preparing…',+ provision: 'Creating the demucs environment…',+ installing: 'Installing demucs (first run only)…',+ separating: 'Separating vocals…',+ attaching: 'Attaching the stem…',+};++/**+ * "Separate vocals" for a Music Video project: one demucs job over SSE whose+ * terminal frame carries the project with its new vocal stem. `start(projectId)`+ * is the button; `run(projectId)` is the same job as a promise for the+ * autopilot kickoff — it resolves with the updated project, or null when the+ * job failed, was cancelled or lost its stream (each already reported).+ * `onSeparated(projectId, project)` fires on success.+ */+export default function useMusicVideoVocalSeparation({ onSeparated } = {}) {+ const waiter = useRef(null);+ const settle = (value) => {+ const pending = waiter.current;+ waiter.current = null;+ pending?.resolve(value);+ };+ const slot = useSseJobSlot({+ startRequest: (projectId) => separateMusicVideoVocals(projectId, { silent: true }),+ eventsUrl: musicVideoVocalSeparationEventsUrl,+ cancelRequest: cancelMusicVideoVocalSeparation,+ onComplete: (frame, projectId) => {+ if (frame.project) onSeparated?.(projectId, frame.project);+ settle(frame.project || null);+ },+ successToast: () => 'Vocals separated and attached as the stem',+ errorFallback: 'Vocal separation failed',+ canceledMessage: 'Vocal separation cancelled',+ lostConnectionMessage: 'Lost connection to the vocal separation',+ startErrorFallback: 'Could not start vocal separation',+ onErrorFrame: () => { settle(null); return false; },+ onKickoffError: () => { settle(null); return false; },+ });++ // Cancel and a dropped stream clear the slot without a callback; release+ // the kickoff waiting on it.+ useEffect(() => {+ if (!slot.active && waiter.current?.started) settle(null);+ if (slot.active && waiter.current) waiter.current.started = true;+ }, [slot.active]);+ useEffect(() => () => settle(null), []);++ const run = (projectId) => new Promise((resolve) => {+ if (slot.active) { resolve(null); return; }+ waiter.current = { resolve, started: false };+ slot.start(projectId);+ });++ return {+ ...slot,+ stageLabel: STAGE_LABELS[slot.stage] || (slot.active ? 'Separating vocals…' : null),+ run,+ };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex de80bb7e05..0a54eb50da 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -19,11 +19,14 @@ import {splitMusicVideoScene,reorderMusicVideoScenes,importMusicVideoLyrics,+ importMusicVideoTrackLyrics,alignMusicVideoLyrics,} from '../services/apiMusicVideo.js';import useFieldDraft from '../hooks/useFieldDraft.js';import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';import useMusicVideoMidiJob from '../hooks/useMusicVideoMidiJob.js';+import useMusicVideoKickoff from '../hooks/useMusicVideoKickoff.js';+import useMusicVideoVocalSeparation from '../hooks/useMusicVideoVocalSeparation.js';import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';@@ -140,6 +143,11 @@ export default function MusicVideo() {})),onProjectUpdated: replaceProject,});+ // "Separate vocals" (demucs) — one slot shared by the stem control and the+ // autopilot kickoff; the terminal frame carries the project with its stem.+ const separation = useMusicVideoVocalSeparation({+ onSeparated: (projectId, project) => patchProject(projectId, { vocalStemFilename: project.vocalStemFilename, updatedAt: project.updatedAt }),+ });const midi = useMusicVideoMidiJob({onTranscribed: (projectId, midiTranscription) => patchProject(projectId, { midiTranscription }),});@@ -323,15 +331,35 @@ export default function MusicVideo() {.finally(() => setPlanning(false));};- // Autopilot kickoff: analyze the song when it has no beat map yet, then plan- // every shot against the brief (the planner reads automation.guidance).+ // Autopilot kickoff: analyze the song, import the track's lyric sheet,+ // separate the vocal, align the words, then plan every shot against the+ // brief (the planner reads automation.guidance). Each step only runs when+ // its result is missing; lyric/vocal/alignment failures still plan.const autopilotBlockedReason = creativeSetupPending? 'Save or cancel the creative setup before starting autopilot.': autopilotBlocker(selected);+ const kickoff = useMusicVideoKickoff({+ analyze: () => handleAnalyze(),+ importLyrics: (project) => importMusicVideoTrackLyrics(project.id, { mode: 'if-empty' }, { silent: true })+ .then(({ project: next, imported }) => {+ patchProject(next.id, { lyricCues: next.lyricCues, lyricMarkers: next.lyricMarkers, updatedAt: next.updatedAt });+ if (imported) toast.success(`Imported ${imported} lyric line${imported === 1 ? '' : 's'} from the track`);+ return next;+ })+ .catch((err) => { toast.error(err?.message || 'Could not import the track lyrics'); return null; }),+ separateVocals: (project) => separation.run(project.id),+ alignLyrics: (project) => alignMusicVideoLyrics(project.id, {}, { silent: true })+ .then((next) => {+ patchProject(next.id, { lyricCues: next.lyricCues, audioAnalysis: next.audioAnalysis, updatedAt: next.updatedAt });+ toast.success('Aligned words to the vocal');+ return next;+ })+ .catch((err) => { toast.error(err?.message || 'Could not align the words — planning without word timings'); return null; }),+ plan: (project) => handlePlan(project),+ });const handleKickoff = () => {- if (!selected || analyzing || planning || autopilotBlockedReason) return;- (selected.audioAnalysis ? Promise.resolve(selected) : handleAnalyze())- .then((proj) => (proj?.audioAnalysis ? handlePlan(proj) : null));+ if (!selected || analyzing || planning || kickoff.running || autopilotBlockedReason) return;+ kickoff.run(selected);};// Saving a brief hands the project to autopilot, so mode follows it.const saveAutomation = (automation) => updateMusicVideoProject(selected.id, { automation, mode: 'autonomous' }, { silent: true })@@ -458,6 +486,18 @@ export default function MusicVideo() {.catch((err) => toast.error(err?.message || 'Lyric import failed')).finally(() => setImportingLyrics(false));};+ // "Use track lyrics": replace the lines with the linked track's sheet.+ const handleImportTrackLyrics = () => {+ const projectId = selected.id;+ setImportingLyrics(true);+ importMusicVideoTrackLyrics(projectId, { mode: 'replace' }, { silent: true })+ .then(({ project, imported, markers }) => {+ patchProject(projectId, { lyricCues: project.lyricCues, lyricMarkers: project.lyricMarkers, updatedAt: project.updatedAt });+ toast.success(`Imported ${imported} lyric line${imported === 1 ? '' : 's'}${markers ? ` and ${markers} section/direction marker${markers === 1 ? '' : 's'}` : ''} from the track`);+ })+ .catch((err) => toast.error(err?.message || 'Could not import the track lyrics'))+ .finally(() => setImportingLyrics(false));+ };// Alignment is a click, never an import side effect. The panel shows the// whisper setup error itself, so this request stays silent.const handleAlignLyrics = (cueId) => {@@ -465,7 +505,7 @@ export default function MusicVideo() {setAligningLyrics(true);return alignMusicVideoLyrics(projectId, cueId ? { cueId } : {}, { silent: true }).then((project) => {- patchProject(projectId, { lyricCues: project.lyricCues, updatedAt: project.updatedAt });+ patchProject(projectId, { lyricCues: project.lyricCues, audioAnalysis: project.audioAnalysis, updatedAt: project.updatedAt });toast.success(cueId ? 'Re-aligned that line' : 'Aligned words to the vocal');}).finally(() => setAligningLyrics(false));@@ -722,7 +762,8 @@ export default function MusicVideo() {project={selected}onSave={saveAutomation}onKickoff={handleKickoff}- kickoffBusy={analyzing || planning}+ kickoffBusy={analyzing || planning || kickoff.running}+ kickoffStep={kickoff.stepLabel}kickoffBlockedReason={autopilotBlockedReason}/><CreativeSetupPanel key={`creative-${selected.id}`} project={selected} onPendingChange={setCreativeSetupPending}@@ -766,6 +807,7 @@ export default function MusicVideo() {midiBound={midiTargetsSelected}onChangeTrack={handleChangeTrack}onProjectUpdated={replaceProject}+ separation={separation}/><AnalysisPanelaudioAnalysis={selected.audioAnalysis}@@ -779,6 +821,7 @@ export default function MusicVideo() {onEditLocal={editProjectLocal}onSave={saveProjectFields}onImport={handleImportLyrics}+ onImportTrack={handleImportTrackLyrics}importing={importingLyrics}onAlign={handleAlignLyrics}aligning={aligningLyrics}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex f9d40e42fd..18571dfa5c 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -53,7 +53,11 @@ vi.mock('../services/apiMusicVideo.js', () => ({reorderMusicVideoScenes: vi.fn(),splitMusicVideoScene: vi.fn(),importMusicVideoLyrics: vi.fn(),+ importMusicVideoTrackLyrics: vi.fn(),alignMusicVideoLyrics: vi.fn(),+ separateMusicVideoVocals: vi.fn(async () => ({ jobId: 'sep-job-1' })),+ musicVideoVocalSeparationEventsUrl: (jobId) => `/api/music-video/vocal-stem/separate/${jobId}/events`,+ cancelMusicVideoVocalSeparation: vi.fn(async () => ({ ok: true })),renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,cancelMusicVideoRender: vi.fn(async () => ({ ok: true })),@@ -163,7 +167,7 @@ import MusicVideo from './MusicVideo.jsx';import {listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender, analyzeMusicVideoProject,- importMusicVideoLyrics, alignMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,+ importMusicVideoLyrics, importMusicVideoTrackLyrics, separateMusicVideoVocals, alignMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,addMusicVideoSceneTake, getMusicVideoHandoffBundle,renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,@@ -1486,14 +1490,20 @@ describe('MusicVideo YouTube audio import (#1945)', () => {));});- it('autopilot kickoff analyzes the song, then plans the shots against the brief', async () => {- const project = { ...PROJECT_NO_CLIP, scenes: [], automation: { tools: ['image:local'], guidance: 'noir', budgetUsd: null } };- analyzeMusicVideoProject.mockResolvedValue({ ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis, status: 'analyzed' });- planMusicVideoProject.mockResolvedValue({ project: { ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis }, scenesAdded: 3, promptsSeeded: true });+ it('autopilot kickoff analyzes the song, tries the track lyrics, then plans the shots against the brief', async () => {+ const project = { ...PROJECT_NO_CLIP, trackId: 'track-1', lyricCues: [], scenes: [], automation: { tools: ['image:local'], guidance: 'noir', budgetUsd: null } };+ const analyzed = { ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis, status: 'analyzed' };+ analyzeMusicVideoProject.mockResolvedValue(analyzed);+ // An instrumental track: nothing to import, so nothing to separate or align.+ importMusicVideoTrackLyrics.mockResolvedValue({ project: analyzed, imported: 0, markers: 0, skipped: 'no-track-lyrics' });+ planMusicVideoProject.mockResolvedValue({ project: analyzed, scenesAdded: 3, promptsSeeded: true });await openProject(project);fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));expect(analyzeMusicVideoProject).toHaveBeenCalledWith(project.id, { silent: true });+ expect(importMusicVideoTrackLyrics).toHaveBeenCalledWith(project.id, { mode: 'if-empty' }, { silent: true });+ expect(separateMusicVideoVocals).not.toHaveBeenCalled();+ expect(alignMusicVideoLyrics).not.toHaveBeenCalled();});it('blocks relinking the track while a render is in progress for the selected project', async () => {diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex ed2fff25d3..6057b6682f 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -48,6 +48,14 @@ export const importMusicVideoLyrics = (id, body, options = {}) => request(`/musimethod: 'POST', body: JSON.stringify(body), ...options,});+// Import the linked track's lyric sheet: its lines become the project's lyric+// cues and its `[Chorus]`/`[Spoken, close]` tags become lyric markers.+// Body `{ mode?: 'replace' | 'if-empty' }` — `if-empty` never replaces lines.+// Resolves to { project, imported, markers, skipped }.+export const importMusicVideoTrackLyrics = (id, body = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/lyrics/import-track`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// Align director lyric lines to the vocal (#9074). Body `{}` aligns every line;// `{ cueId }` re-aligns one line. Resolves to the updated project. Runs only// when the caller invokes it — there is no boot or import hook.@@ -86,6 +94,15 @@ export const uploadMusicVideoVocalStem = (id, file, options = {}) => {};export const removeMusicVideoVocalStem = (id, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/vocal-stem`, { method: 'DELETE', ...options });+// Separate the vocal out of the song with demucs and attach it as the stem.+// Kickoff resolves to { jobId }; the terminal `complete` frame carries the+// updated project. The first run installs demucs, so it can take minutes.+export const separateMusicVideoVocals = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/vocal-stem/separate`, { method: 'POST', body: '{}', ...options });+export const musicVideoVocalSeparationEventsUrl = (jobId) =>+ `/api/music-video/vocal-stem/separate/${encodeURIComponent(jobId)}/events`;+export const cancelMusicVideoVocalSeparation = (jobId, options = {}) =>+ request(`/music-video/vocal-stem/separate/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });// ---- Scene takes (#8965) ----// Every render/import for a scene slot is an immutable take; the scene'sdiff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 95fbf992c3..cf2cb206a4 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached) — Grok video is cutaway-only. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — |+| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), then plans. Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex d18cddd36a..41f66f0f59 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -121,7 +121,20 @@ export const musicVideoPacingSchema = z.object({hookSec: z.number().min(0.5).max(60).optional(),}).strict();+// Lyric-sheet structure: a section header (`[Chorus]`) or a stage direction+// (`[Spoken, close]`) anchored to the index of the lyric line it precedes.+// `kind` is the normalized section part or delivery (see+// services/musicVideo/lyricMarkers.js); a free string so a newer peer's+// vocabulary still validates here.+export const musicVideoLyricMarkerSchema = z.object({+ type: z.enum(['section', 'direction']),+ label: z.string().trim().min(1).max(120),+ kind: z.string().max(32).optional(),+ line: z.number().int().min(0).max(2000),+}).strict();+const lyricCueList = z.array(musicVideoLyricCueSchema).max(2000);+const lyricMarkerList = z.array(musicVideoLyricMarkerSchema).max(500);const phraseList = z.array(musicVideoPhraseSchema).max(500);// ---- Visual specification + scene takes (#8965) ----------------------------@@ -229,6 +242,13 @@ export const musicVideoLyricsImportSchema = z.object({mode: z.enum(['replace', 'append']).optional(),}).strict();+// Import the linked track's lyric sheet. `replace` swaps the project's lines+// for the sheet; `if-empty` (the autopilot kickoff) imports only when the+// project has no lines yet, so a re-run never overwrites the director's edits.+export const musicVideoLyricsImportTrackSchema = z.object({+ mode: z.enum(['replace', 'if-empty']).optional(),+}).strict();+// Word alignment (#9074) runs only when the director clicks. `cueId` re-aligns// that line; omitted, every line is aligned.export const musicVideoLyricsAlignSchema = z.object({@@ -545,6 +565,7 @@ export const musicVideoProjectCreateSchema = z.object({videoSettings: musicVideoVideoSettingsSchema.optional(),automation: musicVideoAutomationSchema.nullable().optional(),lyricCues: lyricCueList.optional(),+ lyricMarkers: lyricMarkerList.optional(),phrases: phraseList.optional(),pacing: musicVideoPacingSchema.nullable().optional(),composition: musicVideoCompositionSchema.nullable().optional(),@@ -563,6 +584,7 @@ export const musicVideoProjectUpdateSchema = z.object({automation: musicVideoAutomationSchema.nullable().optional(),renderHistoryId: z.string().max(64).nullable().optional(),lyricCues: lyricCueList.optional(),+ lyricMarkers: lyricMarkerList.optional(),phrases: phraseList.optional(),pacing: musicVideoPacingSchema.nullable().optional(),composition: musicVideoCompositionSchema.nullable().optional(),@@ -726,6 +748,11 @@ export const musicVideoAudioAnalysisSchema = z.object({// Normalized 0..1 section loudness used by the energy-weighted auto-arranger// (#1915). Additive + optional so older cached analyses still validate.energy: z.number().min(0).optional(),+ // Set when the label came from the aligned lyric sheet ("Chorus") rather+ // than the detector ("Section 3"); `analysisLabel` keeps the detector's+ // label so a later pass can restore it. Additive, so older analyses validate.+ labelSource: z.enum(['analysis', 'lyrics']).optional(),+ analysisLabel: z.string().max(120).optional(),})),durationSec: z.number(),// Explain whether the beat grid came from the full track, consensus amongdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 1979491b5b..86c38370f1 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -619,7 +619,14 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// loss back, so the gate rejects the ahead transfer. The older peer is// never handed `mode: "code"` (an enum value it cannot store). It keeps// the concat/composed project it already understands.- musicVideoProjects: 7,+ // v8 = lyric-sheet structure (`lyricMarkers`: section headers and stage+ // directions anchored to lyric-line indices) and lyric-derived analysis+ // section names (`audioAnalysis.sections[].labelSource`/`analysisLabel`).+ // A v7 receiver stores the body verbatim but mis-executes it: its lyric+ // import replaces the lines without replacing the markers, leaving them+ // anchored to the wrong lines, and that edit wins LWW onto the upgraded+ // peer. Records without either field need no rewrite.+ musicVideoProjects: 8,// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 2d5ae848d0..d7a0209f5b 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -23,6 +23,7 @@ import {musicVideoManualAnalysisSchema,musicVideoTranscribeMidiRequestSchema,musicVideoLyricsImportSchema,+ musicVideoLyricsImportTrackSchema,musicVideoLyricsAlignSchema,musicVideoTakeInputSchema,musicVideoTakeReviewSchema,@@ -95,6 +96,8 @@ import {import { planProject } from '../services/musicVideo/planner.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';+import { importTrackLyrics, MAX_LYRIC_CUES } from '../services/musicVideo/trackLyrics.js';+import { offsetLyricMarkers, relabelAnalysisSections } from '../services/musicVideo/lyricMarkers.js';import {updateTreatment,compileTreatment,@@ -178,6 +181,28 @@ router.delete('/:id/vocal-stem', asyncHandler(async (req, res) => {res.json(await detachVocalStem(req.params.id));}));+// Separate the vocal from the song with demucs and attach it as the stem.+// Kickoff returns 202 + a jobId (a running separation for the project is+// re-attached, not doubled); progress streams over SSE. The first run+// installs demucs into its own venv — only ever from this explicit request.+// Lazy import: the demucs runner pulls the spawn/venv helpers only this needs.+router.post('/:id/vocal-stem/separate', asyncHandler(async (req, res) => {+ const { startVocalSeparation } = await import('../services/musicVideo/vocalSeparation.js');+ res.status(202).json(await startVocalSeparation(req.params.id));+}));++router.get('/vocal-stem/separate/:jobId/events', asyncHandler(async (req, res) => {+ const { attachVocalSeparationSseClient } = await import('../services/musicVideo/vocalSeparation.js');+ if (!attachVocalSeparationSseClient(req.params.jobId, res)) {+ throw new ServerError('Vocal separation job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+}));++router.post('/vocal-stem/separate/:jobId/cancel', asyncHandler(async (req, res) => {+ const { cancelVocalSeparation } = await import('../services/musicVideo/vocalSeparation.js');+ res.json({ ok: cancelVocalSeparation(req.params.jobId) });+}));+// Resolve a project's source audio to an absolute path under data/music/. The// filename comes from the linked track or the uploaded-audio field; both are// validated as safe basenames so a tampered record can't escape the directory.@@ -209,7 +234,9 @@ router.post('/:id/analyze', asyncHandler(async (req, res) => {if (!analysis) {throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });}- const updated = await setProjectAnalysis(project.id, analysis);+ // Timed lyrics with sheet headers name the fresh sections too (a no-op+ // until the lines are aligned).+ const updated = await setProjectAnalysis(project.id, relabelAnalysisSections(analysis, project.lyricCues, project.lyricMarkers));res.json(updated);}));@@ -286,26 +313,40 @@ router.post('/:id/treatment/proofs/:proofId/review', asyncHandler(async (req, re// (plain lines arrive untimed, ready to be timed by hand). `replace` swaps the// project's cue list; `append` adds after it. The cues persist through the// ordinary project PATCH path, so ids/normalization match hand edits.-const MAX_LYRIC_CUES = 2000;+// Plain lines keep their section headers and stage directions as lyric+// markers anchored to the imported lines (lyricMarkers.js).router.post('/:id/lyrics/import', asyncHandler(async (req, res) => {const { format = 'auto', text, mode = 'replace' } = validateRequest(musicVideoLyricsImportSchema, req.body);const project = await getProject(req.params.id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const { format: detected, cues } = parseLyricCues(text, format);+ const { format: detected, cues, markers } = parseLyricCues(text, format);if (cues.length === 0) {throw new ServerError(`No lyric lines found in the ${detected} text`, { status: 422, code: 'NO_LYRICS' });}- const lyricCues = mode === 'append' ? [...(project.lyricCues || []), ...cues] : cues;+ const existing = project.lyricCues || [];+ const append = mode === 'append';+ const lyricCues = append ? [...existing, ...cues] : cues;if (lyricCues.length > MAX_LYRIC_CUES) {throw new ServerError(`A project holds at most ${MAX_LYRIC_CUES} lyric cues`, { status: 400, code: 'VALIDATION_ERROR' });}- const updated = await updateProject(project.id, { lyricCues });+ const lyricMarkers = append+ ? [...(project.lyricMarkers || []), ...offsetLyricMarkers(markers, existing.length)]+ : markers;+ const updated = await updateProject(project.id, { lyricCues, lyricMarkers });res.json({ project: updated, imported: cues.length, format: detected });}));+// Import the linked track's lyric sheet ("Use track lyrics", and the+// autopilot kickoff with `mode: 'if-empty'`, which never replaces lines).+router.post('/:id/lyrics/import-track', asyncHandler(async (req, res) => {+ const { mode = 'replace' } = validateRequest(musicVideoLyricsImportTrackSchema, req.body || {});+ res.json(await importTrackLyrics(req.params.id, { mode }));+}));+// Word-level alignment (#9074). Nothing here runs until the director clicks-// Align words or a line's Re-align. An unreachable whisper server is an error,-// not an empty timing list.+// Align words or a line's Re-align (or starts an autopilot run). The first+// alignment downloads the music-grade whisper model; no whisper.cpp at all is+// a 503 with install steps, not an empty timing list.router.post('/:id/lyrics/align', asyncHandler(async (req, res) => {const { cueId } = validateRequest(musicVideoLyricsAlignSchema, req.body || {});res.json(await alignProjectLyrics(req.params.id, { cueId }));diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex e866dafcdd..ef2b12f251 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -278,17 +278,24 @@ describe('musicVideo routes', () => {expect(r.body).toMatchObject({ imported: 2, format: 'lrc' });expect(svc.updateProject).toHaveBeenCalledWith('mv-1', {lyricCues: [{ text: 'one', startSec: 1, endSec: 3 }, { text: 'two', startSec: 3, endSec: null }],+ lyricMarkers: [],});});- it('appends plain lines after the existing cues', async () => {+ it('appends plain lines after the existing cues, anchoring the sheet\'s markers after them', async () => {const existing = { id: 'lc-old', text: 'old', startSec: 1, endSec: 2 };- svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [existing] });+ const marker = { type: 'section', label: 'Verse 1', kind: 'verse', line: 0 };+ svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [existing], lyricMarkers: [marker] });const r = await request(app).post('/api/music-video/mv-1/lyrics/import')- .send({ text: 'new line', mode: 'append' });+ .send({ text: '[Chorus]\nnew line\n[Shouts]', mode: 'append' });expect(r.status).toBe(200);expect(svc.updateProject).toHaveBeenCalledWith('mv-1', {lyricCues: [existing, { text: 'new line', startSec: null, endSec: null }],+ lyricMarkers: [+ marker,+ { type: 'section', label: 'Chorus', kind: 'chorus', line: 1 },+ { type: 'direction', label: 'Shouts', kind: 'shouted', line: 2 },+ ],});});@@ -303,6 +310,47 @@ describe('musicVideo routes', () => {});});+ describe('POST /:id/lyrics/import-track', () => {+ const SHEET = '[Verse 1]\nWalking home\n[Spoken, close]\nunder neon\n[Chorus]\nHold on';++ it('replaces the lines with the linked track\'s sheet, keeping its headers and directions as markers', async () => {+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1', lyricCues: [{ id: 'lc-old', text: 'old' }] });+ getTrack.mockResolvedValue({ id: 't1', lyrics: SHEET });+ const r = await request(app).post('/api/music-video/mv-1/lyrics/import-track').send({});+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ imported: 3, markers: 3, skipped: null });+ expect(svc.updateProject).toHaveBeenCalledWith('mv-1', {+ lyricCues: [+ { text: 'Walking home', startSec: null, endSec: null },+ { text: 'under neon', startSec: null, endSec: null },+ { text: 'Hold on', startSec: null, endSec: null },+ ],+ lyricMarkers: [+ { type: 'section', label: 'Verse 1', kind: 'verse', line: 0 },+ { type: 'direction', label: 'Spoken, close', kind: 'spoken', line: 1 },+ { type: 'section', label: 'Chorus', kind: 'chorus', line: 2 },+ ],+ });+ });++ it('if-empty never replaces lines the project already has, and skips a track with no lyrics', async () => {+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1', lyricCues: [{ id: 'lc-1', text: 'mine' }] });+ getTrack.mockResolvedValue({ id: 't1', lyrics: SHEET });+ const kept = await request(app).post('/api/music-video/mv-1/lyrics/import-track').send({ mode: 'if-empty' });+ expect(kept.status).toBe(200);+ expect(kept.body).toMatchObject({ imported: 0, skipped: 'has-lyrics' });++ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: 't1', lyricCues: [] });+ getTrack.mockResolvedValue({ id: 't1', lyrics: '' });+ const none = await request(app).post('/api/music-video/mv-1/lyrics/import-track').send({ mode: 'if-empty' });+ expect(none.body).toMatchObject({ imported: 0, skipped: 'no-track-lyrics' });+ const explicit = await request(app).post('/api/music-video/mv-1/lyrics/import-track').send({});+ expect(explicit.status).toBe(422);+ expect(explicit.body.code).toBe('NO_TRACK_LYRICS');+ expect(svc.updateProject).not.toHaveBeenCalled();+ });+ });+describe('POST /:id/lyrics/align (#9074)', () => {it('aligns only when the route is called, and accepts a single-line re-align', async () => {expect(alignProjectLyrics).not.toHaveBeenCalled();diff --git a/server/routes/musicVideoVocalStem.test.js b/server/routes/musicVideoVocalStem.test.jsindex 517396e23a..d926996948 100644--- a/server/routes/musicVideoVocalStem.test.js+++ b/server/routes/musicVideoVocalStem.test.js@@ -4,11 +4,16 @@* song's timebase is attached, a stem of a different length is refused before* it reaches the library, removing it keeps the library file, and changing the* song drops the stem that belonged to the old one.+ *+ * "Separate vocals" runs the same attach path from a demucs job. Only the+ * child processes are stubbed (venv creation, pip, the import probe and+ * demucs itself, which writes a vocals.wav the way demucs lays it out).*/import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';import express from 'express';import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'fs';+import { dirname } from 'path';import { join } from 'path';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';@@ -17,9 +22,19 @@ import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots, sweepStrayTempRconst ROOT = () => lazyTempDataRoot('mv-vocal-stem-route-test-');vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: vi.fn() }));+vi.mock('../lib/pythonSetup.js', async (importOriginal) => ({+ ...(await importOriginal()),+ classifyVenvBases: vi.fn(async () => ({ supported: ['/opt/python3.12/bin/python3'], rejected: [] })),+}));+vi.mock('../lib/cudaCapability.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getCudaCapability: vi.fn(async () => ({ status: 'available' })),+}));const { default: musicVideoRoutes } = await import('./musicVideo.js');const projects = await import('../services/musicVideo/projects.js');+const { runStreamingCommand } = await import('../lib/streamingSpawn.js');const { findFfmpeg } = await import('../lib/ffmpeg.js');const app = express();@@ -110,3 +125,95 @@ describe.skipIf(!ffmpeg)('music-video vocal stem routes', () => {expect(res.body.code).toBe('NO_AUDIO');});});++describe.skipIf(!ffmpeg)('music-video vocal separation', () => {+ const VENV = () => join(ROOT(), 'venvs', 'demucs');+ const PYTHON = () => join(VENV(), process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');++ // A demucs double: builds the venv, installs, answers the import probe, and+ // separates by writing `<out>/htdemucs_ft/<song>/vocals.wav` of the given length.+ function demucsDouble({ stemSeconds = 6, failDevices = [] } = {}) {+ const calls = [];+ runStreamingCommand.mockImplementation(async (bin, args, onLine) => {+ calls.push([bin, ...args]);+ if (args[0] === '-m' && args[1] === 'venv') {+ mkdirSync(dirname(PYTHON()), { recursive: true });+ writeFileSync(PYTHON(), '');+ return { success: true };+ }+ if (args[0] === '-m' && args[1] === 'pip') {+ onLine?.('Collecting demucs');+ onLine?.('Successfully installed demucs soundfile');+ return { success: true };+ }+ if (args[0] === '-c') return { success: true };+ if (args[0] === '-m' && args[1] === 'demucs') {+ const device = args[args.indexOf('-d') + 1];+ if (failDevices.includes(device)) return { success: false, error: `exit 1: ${device} backend failed` };+ const outDir = args[args.indexOf('-o') + 1];+ onLine?.(' 50%|█████ | 5.0/10.0 [00:01<00:01]');+ mkdirSync(join(outDir, 'htdemucs_ft', 'song'), { recursive: true });+ writeFileSync(join(outDir, 'htdemucs_ft', 'song', 'vocals.wav'), wav(stemSeconds));+ return { success: true };+ }+ return { success: false, error: 'unexpected command' };+ });+ return calls;+ }++ beforeEach(() => {+ process.env.PORTOS_DEMUCS_VENV_DIR = VENV();+ rmSync(VENV(), { recursive: true, force: true });+ runStreamingCommand.mockReset();+ });+ afterAll(() => { delete process.env.PORTOS_DEMUCS_VENV_DIR; });++ it('installs demucs on first use, separates on the accelerator, falls back to the CPU, and attaches the stem', async () => {+ const calls = demucsDouble({ failDevices: ['mps', 'cuda'] });+ const res = await request(app).post(`/api/music-video/${project.id}/vocal-stem/separate`).send({});+ expect(res.status).toBe(202);+ expect(res.body.jobId).toEqual(expect.any(String));++ await vi.waitFor(async () => {+ expect((await projects.getProject(project.id)).vocalStemFilename).toMatch(/\.wav$/);+ }, { timeout: 10000 });+ const stem = (await projects.getProject(project.id)).vocalStemFilename;+ expect(existsSync(join(MUSIC(), stem))).toBe(true);++ const kinds = calls.map((argv) => argv.slice(1, 3).join(' '));+ expect(kinds[0]).toBe('-m venv');+ expect(kinds[1]).toBe('-m pip');+ const demucsRuns = calls.filter((argv) => argv[2] === 'demucs');+ expect(demucsRuns[0]).toEqual(expect.arrayContaining(['--two-stems=vocals', '-n', 'htdemucs_ft']));+ expect(demucsRuns.at(-1)[demucsRuns.at(-1).indexOf('-d') + 1]).toBe('cpu');+ expect(demucsRuns.length).toBe(2);+ }, 20000);++ it('reuses a working venv, and refuses a separated stem that does not match the song', async () => {+ mkdirSync(dirname(PYTHON()), { recursive: true });+ writeFileSync(PYTHON(), '');+ const calls = demucsDouble({ stemSeconds: 5 });+ const before = libraryFiles();+ const res = await request(app).post(`/api/music-video/${project.id}/vocal-stem/separate`).send({});+ expect(res.status).toBe(202);+ // The stream ends once the job is cleaned up; its last frame is the verdict.+ const events = await request(app).get(`/api/music-video/vocal-stem/separate/${res.body.jobId}/events`);+ expect(events.status).toBe(200);+ expect(events.text).toContain('"type":"error"');+ expect(events.text).toContain('MUSIC_VIDEO_VOCAL_STEM_TIMEBASE');+ expect(calls.some((argv) => argv[2] === 'venv' || argv[2] === 'pip')).toBe(false);+ expect((await projects.getProject(project.id)).vocalStemFilename).toBeUndefined();+ expect(libraryFiles()).toEqual(before);+ }, 20000);++ it('404s for a missing project and 400s for a project with no song, before any job starts', async () => {+ demucsDouble();+ const missing = await request(app).post('/api/music-video/mv-missing/vocal-stem/separate').send({});+ expect(missing.status).toBe(404);+ const empty = await projects.createProject({ name: 'No Song' });+ const noSong = await request(app).post(`/api/music-video/${empty.id}/vocal-stem/separate`).send({});+ expect(noSong.status).toBe(400);+ expect(noSong.body.code).toBe('NO_AUDIO');+ expect(runStreamingCommand).not.toHaveBeenCalled();+ });+});diff --git a/server/services/musicVideo/codeTimeline.test.js b/server/services/musicVideo/codeTimeline.test.jsindex a198befb5b..dd061af4b9 100644--- a/server/services/musicVideo/codeTimeline.test.js+++ b/server/services/musicVideo/codeTimeline.test.js@@ -123,6 +123,6 @@ describe('code mode keeps the rest of the project (#9076)', () => {expect(code.codeVideo.sections).toEqual([{ id: 'Verse', source }]);expect(normalizeComposition({ ...code, mode: 'concat' }).textCues).toHaveLength(1);expect(normalizeComposition({ ...code, mode: 'composed' }).codeVideo.sections).toHaveLength(1);- expect(PORTOS_SCHEMA_VERSIONS.musicVideoProjects).toBe(7);+ expect(PORTOS_SCHEMA_VERSIONS.musicVideoProjects).toBeGreaterThanOrEqual(7);});});diff --git a/server/services/musicVideo/lyricAlign.js b/server/services/musicVideo/lyricAlign.jsindex d470d38868..c01e3baae4 100644--- a/server/services/musicVideo/lyricAlign.js+++ b/server/services/musicVideo/lyricAlign.js@@ -1,12 +1,17 @@/*** Music Video word-level lyric alignment (#9074).*- * Runs only when the director clicks Align words (or a line's Re-align).- * The vocal stem is the audio when one is attached; otherwise the master.- * ffmpeg decodes that file to 16 kHz mono PCM, the local whisper.cpp server+ * Runs when the director clicks Align words (or a line's Re-align), or as a+ * step of an autopilot run the director started. ffmpeg decodes the audio to+ * 16 kHz mono PCM; a whisper runner (lyricTranscriber.js — whisper-cli with a+ * music-grade model, the voice STT endpoint, or a temporary whisper-server)* returns word timings, and those timings are aligned to the director's- * spelling. A line the singer skipped stays inside its own window and does- * not move the lines around it. Times the director already set are kept.+ * spelling. With a vocal stem attached, both the stem and the mix are+ * transcribed and merged, so a recognizer that loops on the isolated vocal is+ * outvoted by the mix. A line the singer skipped stays inside its own window+ * and does not move the lines around it. Times the director already set are+ * kept. A whole-song alignment also names the analysis sections after the+ * lyric sheet's `[Verse]`/`[Chorus]` headers (lyricMarkers.js).*/import { mkdtemp, readFile, rm } from 'fs/promises';@@ -14,19 +19,15 @@ import { tmpdir } from 'os';import { join } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';-import { transcribe } from '../voice/stt.js';+import { musicVideoAudioAnalysisSchema } from '../../lib/musicVideoValidation.js';import { getProject, updateProject } from './projects.js';import {alignDirectorWords,- explainSttFailure,- lyricAlignChunkSec,lyricAlignFfmpegArgs,- mergeChunkWords,+ mergeTranscripts,pickAlignmentPath,- planAudioChunks,- sliceWav,- wavDurationSec,} from './lyricAlignCore.js';+import { relabelAnalysisSections } from './lyricMarkers.js';async function decodeSourceToWav(sourcePath) {const ffmpeg = await findFfmpeg();@@ -47,55 +48,27 @@ async function decodeSourceToWav(sourcePath) {}}-const audioKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uploadedAudioFilename ?? ''}`;+// Lazy: the runner pulls the download/spawn helpers only an alignment needs.+async function resolveTranscriber() {+ const { resolveAlignmentTranscriber } = await import('./lyricTranscriber.js');+ return resolveAlignmentTranscriber();+}++const audioKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uploadedAudioFilename ?? ''}\u0000${project?.vocalStemFilename ?? ''}`;const textKey = (cues) => (cues || []).map((cue) => `${cue.id ?? ''}\u0000${cue.text ?? ''}`).join('\n');function alignmentPrompt(cues) {return (cues || []).map((cue) => cue?.text || '').filter(Boolean).join('\n').slice(0, 800);}-async function recognizeRegion(wav, region, transcribeFn, prompt) {- const duration = wavDurationSec(wav);- if (!(duration > 0)) {- throw new ServerError('Could not read the decoded vocal.', { status: 422, code: 'LYRIC_ALIGN_DECODE_FAILED' });- }- const regionStart = Math.max(0, region.startSec || 0);- const regionEnd = Math.min(duration, region.endSec ?? duration);- if (!(regionEnd > regionStart)) {- throw new ServerError('That lyric line has no audio window to align.', { status: 422, code: 'LYRIC_ALIGN_NO_WINDOW' });- }- const span = regionEnd - regionStart;- const chunks = planAudioChunks(span, { chunkSec: lyricAlignChunkSec() }).map((chunk) => ({- startSec: regionStart + chunk.startSec,- endSec: regionStart + chunk.endSec,- }));- console.log(`🎤 Aligning lyric words (${chunks.length} whisper ${chunks.length === 1 ? 'chunk' : 'chunks'})`);- const results = [];- for (const chunk of chunks) {- const slice = sliceWav(wav, chunk.startSec, chunk.endSec);- let result;- try {- result = await transcribeFn(slice, {- verbose: true,- mimeType: 'audio/wav',- filename: 'lyric-align.wav',- prompt,- });- } catch (err) {- console.error(`❌ Lyric alignment speech-to-text failed: ${err.message}`);- throw new ServerError(explainSttFailure(err), { status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE' });- }- results.push({- startSec: chunk.startSec,- endSec: chunk.endSec,- words: (result?.words || []).map((word) => ({- text: word.text,- startSec: word.startSec,- endSec: word.endSec,- })),- });- }- return mergeChunkWords(results);+/** The analysis with its sections named after the lyric sheet, or null when nothing changes. */+function relabeledAnalysis(project, cues) {+ const analysis = project.audioAnalysis;+ if (!analysis || !Array.isArray(analysis.sections)) return null;+ const next = relabelAnalysisSections(analysis, cues, project.lyricMarkers || []);+ if (JSON.stringify(next.sections) === JSON.stringify(analysis.sections)) return null;+ const parsed = musicVideoAudioAnalysisSchema.safeParse(next);+ return parsed.success ? parsed.data : null;}/**@@ -109,7 +82,7 @@ export async function alignProjectLyrics(projectId, options = {}) {updateProject,resolveAudio: pickAlignmentPath,decodeAudio: decodeSourceToWav,- transcribe,+ resolveTranscriber,...options.deps,};const cueId = options.cueId || null;@@ -122,22 +95,32 @@ export async function alignProjectLyrics(projectId, options = {}) {const cue = cueId ? cues.find((entry) => entry.id === cueId) : null;if (cueId && !cue) throw new ServerError('That lyric line is no longer on the project.', { status: 404, code: 'NOT_FOUND' });- const { path: audioPath, source } = await deps.resolveAudio(project);+ const { path: audioPath, source, mixPath } = await deps.resolveAudio(project);const wav = await deps.decodeAudio(audioPath);- const duration = wavDurationSec(wav);+ const mixWav = mixPath ? await deps.decodeAudio(mixPath) : null;const windowed = cue&& typeof cue.startSec === 'number'&& typeof cue.endSec === 'number'&& cue.endSec > cue.startSec? { startSec: cue.startSec, endSec: cue.endSec }: null;- const region = windowed- ? { startSec: windowed.startSec, endSec: Math.min(windowed.endSec, duration || windowed.endSec) }- : { startSec: 0, endSec: duration };- const recognized = await recognizeRegion(wav, region, deps.transcribe, alignmentPrompt(windowed ? [cue] : cues));+ const region = windowed || { startSec: 0, endSec: null };+ const promptCues = windowed ? [cue] : cues;+ const prompt = alignmentPrompt(promptCues);+ const lyricText = promptCues.map((entry) => entry.text).join('\n');++ const transcriber = await deps.resolveTranscriber();+ let recognized;+ try {+ const primary = await transcriber.transcribe(wav, { ...region, prompt });+ const mix = mixWav ? await transcriber.transcribe(mixWav, { ...region, prompt }) : [];+ recognized = mergeTranscripts(primary, mix, lyricText);+ } finally {+ await Promise.resolve(transcriber.release?.()).catch((err) => console.error(`❌ Could not stop the alignment runner: ${err.message}`));+ }if (!windowed && recognized.length === 0) {throw new ServerError(- 'Speech-to-text returned no words for this audio. Enable the local whisper server in Settings → Voice and try Align words again.',+ 'Speech-to-text heard no words in this audio. Check the song has vocals, then try Align words again.',{ status: 422, code: 'LYRIC_ALIGN_EMPTY' },);}@@ -159,6 +142,12 @@ export async function alignProjectLyrics(projectId, options = {}) {const aligned = alignDirectorWords(freshCues, recognized);nextCues = cueId ? freshCues.map((entry, index) => (entry.id === cueId ? aligned[index] : entry)) : aligned;}- console.log(`🎤 Aligned lyric words from the ${source}`);- return deps.updateProject(projectId, { lyricCues: nextCues });+ const matched = nextCues.reduce((sum, entry) => sum + (entry.words || []).filter((word) => word.conf === 'matched').length, 0);+ console.log(`🎤 Aligned lyric words from the ${source}${mixWav ? ' + mix' : ''} via ${transcriber.kind} (${matched} words matched)`);+ const patch = { lyricCues: nextCues };+ if (!cueId) {+ const analysis = relabeledAnalysis(fresh, nextCues);+ if (analysis) patch.audioAnalysis = analysis;+ }+ return deps.updateProject(projectId, patch);}diff --git a/server/services/musicVideo/lyricAlign.test.js b/server/services/musicVideo/lyricAlign.test.jsindex b6c9b8e952..af567dee2e 100644--- a/server/services/musicVideo/lyricAlign.test.js+++ b/server/services/musicVideo/lyricAlign.test.js@@ -4,10 +4,10 @@ import { alignProjectLyrics } from './lyricAlign.js';import {alignDirectorWords,encodePcm16Wav,- explainSttFailure,lyricAlignChunkSec,lyricAlignFfmpegArgs,mergeChunkWords,+ mergeTranscripts,pickAlignmentPath,planAudioChunks,sliceWav,@@ -115,6 +115,60 @@ describe('alignDirectorWords', () => {expect(aligned.words[3].startSec).toBe(7);});+ it('does not let a word the recognizer missed latch onto the same word a verse later', () => {+ // "the" in line one was not heard. A next-equal-word matcher would take the+ // "the" of line three for it and strand line two between them.+ const aligned = alignDirectorWords([+ { id: 'a', text: 'into the night', startSec: null, endSec: null },+ { id: 'b', text: 'running far away', startSec: null, endSec: null },+ { id: 'c', text: 'under the moon', startSec: null, endSec: null },+ ], [+ { text: 'into', startSec: 1, endSec: 1.3 },+ { text: 'night', startSec: 1.6, endSec: 2 },+ { text: 'running', startSec: 3, endSec: 3.4 },+ { text: 'far', startSec: 3.4, endSec: 3.7 },+ { text: 'away', startSec: 3.7, endSec: 4.2 },+ { text: 'under', startSec: 6, endSec: 6.3 },+ { text: 'the', startSec: 6.3, endSec: 6.4 },+ { text: 'moon', startSec: 6.4, endSec: 7 },+ ]);+ expect(aligned[0].words.map((word) => word.conf)).toEqual(['matched', 'interpolated', 'matched']);+ expect(aligned[0].words[1].startSec).toBeGreaterThanOrEqual(1.3);+ expect(aligned[0].words[1].endSec).toBeLessThanOrEqual(1.6);+ expect(aligned[1]).toMatchObject({ startSec: 3, endSec: 4.2 });+ expect(aligned[1].words.every((word) => word.conf === 'matched')).toBe(true);+ expect(aligned[2].words[1]).toMatchObject({ w: 'the', startSec: 6.3, conf: 'matched' });+ });++ it('matches a curly-apostrophe sheet word to the recognizer\'s straight one', () => {+ const [aligned] = alignDirectorWords(+ [{ id: 'a', text: 'I’m gonna stay', startSec: null, endSec: null }],+ [+ { text: "I'm", startSec: 1, endSec: 1.2 },+ { text: 'gona', startSec: 1.2, endSec: 1.5 },+ { text: 'stay', startSec: 1.5, endSec: 2 },+ ],+ );+ expect(aligned.words.map((word) => [word.w, word.conf])).toEqual([+ ['I’m', 'matched'], ['gonna', 'matched'], ['stay', 'matched'],+ ]);+ });++ it('gives a one-word line the recognizer timed as an instant a playable span', () => {+ const aligned = alignDirectorWords([+ { id: 'a', text: 'Hush.', startSec: null, endSec: null },+ { id: 'b', text: 'can you feel', startSec: null, endSec: null },+ ], [+ { text: 'Hush.', startSec: 20.5, endSec: 20.5 },+ { text: 'can', startSec: 21, endSec: 21.2 },+ { text: 'you', startSec: 21.2, endSec: 21.4 },+ { text: 'feel', startSec: 21.4, endSec: 21.8 },+ ]);+ expect(aligned[0]).toMatchObject({ startSec: 20.5, endSec: 20.75 });+ expect(aligned[0].words[0]).toMatchObject({ w: 'Hush.', conf: 'matched' });+ expect(aligned[1]).toMatchObject({ startSec: 21, endSec: 21.8 });+ });+it('fills only the cue times the director left empty', () => {const [aligned] = alignDirectorWords([{ id: 'a', text: 'walking home', startSec: 1, endSec: null }],@@ -145,18 +199,17 @@ describe('lyric alignment audio', () => {expect(() => sliceWav(stereo, 0, 0.01)).toThrow(/16-bit mono/);});- it('uses the vocal stem when one is attached, and does not fall back when that file is missing', async () => {+ it('uses the vocal stem with the mix beside it, and does not fall back when the stem file is missing', async () => {const resolveMaster = vi.fn(async () => '/library/mix.wav');await expect(pickAlignmentPath({ vocalStemFilename: 'v.wav' }, {resolveStem: () => '/library/v.wav',resolveMaster,- })).resolves.toEqual({ path: '/library/v.wav', source: 'vocal-stem' });- expect(resolveMaster).not.toHaveBeenCalled();+ })).resolves.toEqual({ path: '/library/v.wav', source: 'vocal-stem', mixPath: '/library/mix.wav' });await expect(pickAlignmentPath({}, {resolveStem: () => null,resolveMaster,- })).resolves.toEqual({ path: '/library/mix.wav', source: 'master' });+ })).resolves.toEqual({ path: '/library/mix.wav', source: 'master', mixPath: null });const missing = new ServerError('missing', { status: 404, code: 'MUSIC_VIDEO_VOCAL_STEM_MISSING' });await expect(pickAlignmentPath({ vocalStemFilename: 'gone.wav' }, {@@ -166,6 +219,32 @@ describe('lyric alignment audio', () => {});});+describe('mergeTranscripts', () => {+ const words = (list) => list.map(([text, startSec]) => ({ text, startSec, endSec: startSec + 0.3 }));++ it('keeps the stem where it is clean and takes the mix only where the stem loops', () => {+ const stem = words([+ ['hold', 1], ['me', 1.4], ['close', 1.8],+ ['Na-na-na-na-na-na', 4],+ ['no', 9], ['no', 9.4], ['no', 9.8], ['no', 10.2], ['no', 10.6], ['no', 11],+ ]);+ // The mix mishears the clean stretch, and stretches words across the loop too.+ const mix = words([+ ['old', 1], ['me', 1.4], ['clothes', 1.8],+ ['tonight', 4.1],+ ['never', 9], ['let', 9.4], ['me', 9.8], ['go', 10.2],+ ]);+ const merged = mergeTranscripts(stem, mix, 'hold me close tonight\nnever let me go');+ expect(merged.map((word) => word.text)).toEqual(['hold', 'me', 'close', 'tonight', 'never', 'let', 'me', 'go']);+ });++ it('keeps a repeat the lyrics really sing, and drops a looped run with nothing to replace it', () => {+ const sung = words([['hey', 1], ['hey', 1.4], ['hey', 1.8], ['hey', 2.2]]);+ expect(mergeTranscripts(sung, [], 'hey hey hey hey')).toHaveLength(4);+ expect(mergeTranscripts(sung, [], 'hey there')).toHaveLength(0);+ });+});+describe('alignProjectLyrics', () => {const project = {id: 'mv-1',@@ -176,39 +255,37 @@ describe('alignProjectLyrics', () => {],};- function harness(transcribe, record = project) {+ function harness(transcribe, record = project, { resolveAudio } = {}) {const updateProject = vi.fn(async (id, patch) => ({ id, ...record, ...patch }));const decodeAudio = vi.fn(async () => encodePcm16Wav(16000 * 3));const getProject = vi.fn(async () => record);+ const release = vi.fn(async () => {});return {updateProject,decodeAudio,transcribe,+ release,run: (opts = {}) => alignProjectLyrics(record.id, {...opts,deps: {getProject,updateProject,- resolveAudio: async () => ({ path: 'song.wav', source: 'master' }),+ resolveAudio: resolveAudio || (async () => ({ path: 'song.wav', source: 'master', mixPath: null })),decodeAudio,- transcribe,+ resolveTranscriber: async () => ({ kind: 'test', transcribe, release }),},}),};}it('writes matched and interpolated words, and does not replace a time the director set', async () => {- const transcribe = vi.fn(async () => ({- text: 'walking home',- words: [- { text: 'walking', startSec: 0.5, endSec: 1 },- { text: 'home', startSec: 1, endSec: 1.5 },- ],- latencyMs: 4,- }));- const { run, updateProject } = harness(transcribe);+ const transcribe = vi.fn(async () => [+ { text: 'walking', startSec: 0.5, endSec: 1 },+ { text: 'home', startSec: 1, endSec: 1.5 },+ ]);+ const { run, updateProject, release } = harness(transcribe);const saved = await run();- expect(transcribe).toHaveBeenCalledWith(expect.any(Buffer), expect.objectContaining({ verbose: true }));+ expect(transcribe).toHaveBeenCalledWith(expect.any(Buffer), expect.objectContaining({ prompt: 'walking home\nnot sung here' }));expect(saved.lyricCues[0]).toMatchObject({startSec: 1,endSec: 1.5,@@ -220,6 +297,58 @@ describe('alignProjectLyrics', () => {expect(saved.lyricCues[1].words.every((word) => word.conf === 'interpolated')).toBe(true);expect(saved.lyricCues[1].words.every((word) => word.startSec >= 2 && word.endSec <= 2.8)).toBe(true);expect(updateProject).toHaveBeenCalledOnce();+ expect(release).toHaveBeenCalledOnce();+ });++ it('transcribes the stem and the mix, and aligns to their merge', async () => {+ const transcribe = vi.fn()+ .mockResolvedValueOnce([+ { text: 'walking', startSec: 0.5, endSec: 1 },+ { text: 'no', startSec: 1.2, endSec: 1.3 }, { text: 'no', startSec: 1.3, endSec: 1.4 },+ { text: 'no', startSec: 1.4, endSec: 1.5 }, { text: 'no', startSec: 1.5, endSec: 1.6 },+ ])+ .mockResolvedValueOnce([+ { text: 'walking', startSec: 0.5, endSec: 1 },+ { text: 'home', startSec: 1.1, endSec: 1.6 },+ ]);+ const { run, decodeAudio } = harness(transcribe, project, {+ resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem', mixPath: 'song.wav' }),+ });+ const saved = await run();+ expect(decodeAudio.mock.calls.map(([path]) => path)).toEqual(['stem.wav', 'song.wav']);+ expect(saved.lyricCues[0].words[1]).toMatchObject({ w: 'home', startSec: 1.1, conf: 'matched' });+ });++ it('names the analysis sections after the lyric sheet once the lines are timed', async () => {+ const record = {+ ...project,+ lyricCues: [+ { id: 'lc-1', text: 'walking home', startSec: null, endSec: null },+ { id: 'lc-2', text: 'under neon', startSec: null, endSec: null },+ ],+ lyricMarkers: [+ { type: 'section', label: 'Verse 1', kind: 'verse', line: 0 },+ { type: 'section', label: 'Chorus', kind: 'chorus', line: 1 },+ ],+ audioAnalysis: {+ bpm: 120, beats: [], downbeats: [], durationSec: 12,+ sections: [+ { label: 'Section 1', startSec: 0, endSec: 2, energy: 0.2 },+ { label: 'Section 2', startSec: 2, endSec: 5, energy: 0.5 },+ { label: 'Section 3', startSec: 5, endSec: 9, energy: 0.9 },+ { label: 'Section 4', startSec: 9, endSec: 12, energy: 0.3 },+ ],+ },+ };+ const transcribe = vi.fn(async () => [+ { text: 'walking', startSec: 2.2, endSec: 3 }, { text: 'home', startSec: 3, endSec: 4.5 },+ { text: 'under', startSec: 5.1, endSec: 6 }, { text: 'neon', startSec: 6, endSec: 8.8 },+ ]);+ const saved = await harness(transcribe, record).run();+ expect(saved.audioAnalysis.sections.map((section) => [section.label, section.labelSource ?? null])).toEqual([+ ['Intro', 'lyrics'], ['Verse 1', 'lyrics'], ['Chorus', 'lyrics'], ['Outro', 'lyrics'],+ ]);+ expect(saved.audioAnalysis.sections[2]).toMatchObject({ analysisLabel: 'Section 3', startSec: 5, endSec: 9, energy: 0.9 });});it('re-aligns one windowed line without moving the other line', async () => {@@ -236,23 +365,21 @@ describe('alignProjectLyrics', () => {{ id: 'lc-2', text: 'not sung here', startSec: 2, endSec: 2.8 },],};- const transcribe = vi.fn(async () => ({ text: '', words: [], latencyMs: 1 }));+ const transcribe = vi.fn(async () => []);const saved = await harness(transcribe, record).run({ cueId: 'lc-2' });+ expect(transcribe).toHaveBeenCalledWith(expect.any(Buffer), expect.objectContaining({ startSec: 2, endSec: 2.8 }));expect(saved.lyricCues[0].words).toEqual(record.lyricCues[0].words);expect(saved.lyricCues[1].words.every((word) => word.conf === 'interpolated')).toBe(true);expect(saved.lyricCues[1].words.every((word) => word.startSec >= 2 && word.endSec <= 2.8)).toBe(true);});- it('reports an unreachable speech-to-text server instead of saving empty timings', async () => {- const transcribe = vi.fn(async () => { throw new Error('fetch failed'); });- const { run, updateProject } = harness(transcribe);- await expect(run()).rejects.toMatchObject({- status: 503,- code: 'LYRIC_ALIGN_STT_UNAVAILABLE',- message: expect.stringMatching(/Settings → Voice/),- });+ it('stops the runner and saves nothing when transcription fails', async () => {+ const failure = new ServerError('no whisper', { status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE' });+ const transcribe = vi.fn(async () => { throw failure; });+ const { run, updateProject, release } = harness(transcribe);+ await expect(run()).rejects.toBe(failure);expect(updateProject).not.toHaveBeenCalled();- expect(explainSttFailure(new Error('fetch failed'))).toMatch(/not running/);+ expect(release).toHaveBeenCalledOnce();});it('does not transcribe when the project has no lyric lines', async () => {diff --git a/server/services/musicVideo/lyricAlignCore.js b/server/services/musicVideo/lyricAlignCore.jsindex caa8dde5d7..59fca3c940 100644--- a/server/services/musicVideo/lyricAlignCore.js+++ b/server/services/musicVideo/lyricAlignCore.js@@ -6,7 +6,7 @@import { ServerError } from '../../lib/errorHandler.js';import { STT_TIMEOUT_MS } from '../voice/stt.js';-import { lyricTokens } from './timedText.js';+import { lyricKey, lyricTokens } from './timedText.js';import { resolveVocalStemPath } from './vocalStem.js';const LYRIC_ALIGN_SAMPLE_RATE = 16000;@@ -32,12 +32,12 @@ function lyricAlignFfmpegArgs(sourcePath, outPath) {function explainSttFailure(err) {const msg = String(err?.message || '');if (/whisper inference failed:/i.test(msg)) {- return 'Speech-to-text rejected the audio. Enable the local whisper server in Settings → Voice and try Align words again.';+ return 'The whisper server rejected the audio. Try Align words again; if it keeps failing, check the whisper server log.';}if (/timed out|timeout|aborted/i.test(msg)) {- return 'Speech-to-text did not answer in time. Enable the local whisper server in Settings → Voice and try Align words again.';+ return 'The whisper server did not answer in time. Try Align words again.';}- return 'Speech-to-text is not running. Enable the local whisper server in Settings → Voice, then try Align words again.';+ return 'The whisper server stopped answering during alignment. Try Align words again.';}/** Chunk a song so each whisper call fits the timeout, overlapping the seams. */@@ -80,6 +80,158 @@ function mergeChunkWords(chunks) {return owned;}+const SPECIAL_TOKEN = /^(?:\[_[A-Z0-9_]*\]|<\|.*?\|>)$/;++/**+ * Word timings from a whisper.cpp CLI `-ojf` (full JSON) file. Offsets are+ * milliseconds. Run with `-ml 1 -sow`, each `transcription` entry is one word+ * (" I'm" = tokens " I" + "'m"); entries holding several words are split on+ * the leading space whisper puts on a word's first token. Special tokens+ * (`[_BEG_]`, `[_TT_150]`) and empty entries are dropped.+ * @returns {Array<{ text: string, startSec: number, endSec: number }>}+ */+function parseWhisperCliWords(data) {+ const segments = Array.isArray(data?.transcription) ? data.transcription : [];+ const out = [];+ for (const segment of segments) {+ const tokens = (Array.isArray(segment?.tokens) ? segment.tokens : []).filter((token) => {+ const text = typeof token?.text === 'string' ? token.text : '';+ return text.trim() && !SPECIAL_TOKEN.test(text.trim())+ && Number.isFinite(token?.offsets?.from) && Number.isFinite(token?.offsets?.to);+ });+ if (tokens.length === 0) {+ const text = String(segment?.text || '').trim();+ const from = segment?.offsets?.from;+ const to = segment?.offsets?.to;+ if (text && !SPECIAL_TOKEN.test(text) && Number.isFinite(from) && Number.isFinite(to) && to >= from) {+ out.push({ text, startSec: from / 1000, endSec: to / 1000 });+ }+ continue;+ }+ let current = null;+ for (const token of tokens) {+ const startSec = token.offsets.from / 1000;+ const endSec = Math.max(startSec, token.offsets.to / 1000);+ const text = token.text.trim();+ if (!current || /^\s/.test(token.text)) {+ current = { text, startSec, endSec };+ out.push(current);+ } else {+ current.text += text;+ current.endSec = Math.max(current.endSec, endSec);+ }+ }+ }+ return dropNonLyricWords(out);+}++const NON_LYRIC_PAREN = /music|applause|laugh|inaudible|instrumental|singing|vocaliz|humming|silence|no speech/i;+const CLOSERS = { '*': '*', '[': ']', '(': ')' };++/**+ * Remove the recognizer's sound captions ("*sad music*", "[Music]",+ * "(upbeat music)", "♪"). A caption may span several words; an opener with no+ * closer within a few words is treated as sung text.+ */+function dropNonLyricWords(words) {+ const list = Array.isArray(words) ? words : [];+ const out = [];+ for (let i = 0; i < list.length; i++) {+ const text = String(list[i]?.text || '').trim();+ if (!text || /^[♪♫]+$/.test(text)) continue;+ const opener = CLOSERS[text[0]];+ if (opener) {+ let end = -1;+ for (let k = i; k < Math.min(list.length, i + 6); k++) {+ const t = String(list[k]?.text || '').trim();+ if ((k > i || t.length > 1) && t.endsWith(opener)) { end = k; break; }+ }+ if (end >= 0) {+ const caption = list.slice(i, end + 1).map((w) => w.text).join(' ');+ if (text[0] !== '(' || NON_LYRIC_PAREN.test(caption)) { i = end; continue; }+ }+ }+ out.push(list[i]);+ }+ return out;+}++// A recognizer stuck on one word ("no, no, no, no, no…") emits a run far+// longer than the sheet ever sings. A run is suspect at this length unless the+// lyrics themselves repeat that word as many times.+const HALLUCINATED_RUN = 4;++function longestRuns(keys) {+ const runs = new Map();+ let prev = null;+ let run = 0;+ for (const key of keys) {+ run = key === prev ? run + 1 : 1;+ prev = key;+ if (run > (runs.get(key) || 0)) runs.set(key, run);+ }+ return runs;+}++// One "word" that is a syllable looped many times ("na-na-na-na-na…"), which a+// recognizer emits across a stretch it could not follow.+function isLoopedToken(text) {+ const parts = String(text || '').toLowerCase().split(/[-\s,.!?]+/).filter(Boolean);+ return parts.length >= HALLUCINATED_RUN && new Set(parts).size <= 2;+}++function flagHallucinations(words, allowedRuns, vocab) {+ const keys = words.map((word) => lyricKey(word.text));+ const flagged = words.map((word, index) => isLoopedToken(word.text) && !vocab.has(keys[index]));+ let start = 0;+ for (let i = 1; i <= keys.length; i++) {+ if (i < keys.length && keys[i] === keys[start] && keys[i]) continue;+ const length = i - start;+ const key = keys[start];+ if (key && length >= HALLUCINATED_RUN && length > (allowedRuns.get(key) || 0) + 1) {+ for (let k = start; k < i; k++) flagged[k] = true;+ }+ start = i;+ }+ return flagged;+}++/**+ * Merge a vocal-stem transcript with a full-mix transcript. The stem is the+ * cleaner signal and is kept wherever it holds up; a recognizer can still loop+ * on an isolated vocal and emit a run of one word ("no, no, no…") or one+ * syllable repeated across a whole phrase ("na-na-na…"). Those stretches are+ * dropped and filled with the mix's words for the same time span. With no+ * stem transcript the mix is used alone, minus its own loops.+ * Returns one time-ordered word list.+ */+function mergeTranscripts(primary, secondary, lyricText = '') {+ const a = Array.isArray(primary) ? primary : [];+ const b = Array.isArray(secondary) ? secondary : [];+ const lyricKeys = lyricTokens(lyricText).map((token) => token.key);+ const vocab = new Set(lyricKeys);+ const allowed = longestRuns(lyricKeys);+ const clean = (words) => {+ const flags = flagHallucinations(words, allowed, vocab);+ return { kept: words.filter((_, index) => !flags[index]), flagged: words.filter((_, index) => flags[index]) };+ };+ const main = clean(a);+ const other = clean(b);+ if (a.length === 0) return other.kept.slice().sort((x, y) => x.startSec - y.startSec);+ // Spans the stem got wrong, merged when they touch.+ const spans = [];+ for (const word of main.flagged) {+ const last = spans[spans.length - 1];+ if (last && word.startSec <= last.endSec + 0.5) last.endSec = Math.max(last.endSec, word.endSec);+ else spans.push({ startSec: word.startSec, endSec: word.endSec });+ }+ const inSpan = (word) => {+ const mid = (Number(word.startSec) + Number(word.endSec)) / 2;+ return spans.some((span) => mid >= span.startSec && mid <= span.endSec);+ };+ return [...main.kept, ...other.kept.filter(inSpan)].sort((x, y) => x.startSec - y.startSec);+}+/** Glue a contraction fragment ("'s") onto the previous recognized word. */function glueContractions(words) {const out = [];@@ -99,6 +251,17 @@ function glueContractions(words) {return out;}+// Give an instant (from == to) recognized word the time up to the next word,+// at most MIN_LINE_SEC, so it can anchor a line.+function widenInstants(tokens) {+ return tokens.map((token, index) => {+ if (token.endSec > token.startSec) return token;+ const next = tokens[index + 1];+ const ceiling = next && next.startSec > token.startSec ? next.startSec : token.startSec + MIN_LINE_SEC;+ return { ...token, endSec: Math.min(ceiling, token.startSec + MIN_LINE_SEC) };+ });+}+function recognizedTokens(words) {const out = [];for (const word of glueContractions(words)) {@@ -119,12 +282,40 @@ function recognizedTokens(words) {cursor = endSec;});}- return out;+ return widenInstants(out);}-// Earliest still-available equal token. Repeated choruses stay in order-// because a match consumes that recognizer word.-function alignTokenIndexes(director, recognized) {+// True when a and b differ by one insertion, deletion or substitution.+function withinOneEdit(a, b) {+ if (Math.abs(a.length - b.length) > 1) return false;+ let i = 0;+ let j = 0;+ let edits = 0;+ while (i < a.length && j < b.length) {+ if (a[i] === b[j]) { i += 1; j += 1; continue; }+ edits += 1;+ if (edits > 1) return false;+ if (a.length > b.length) i += 1;+ else if (b.length > a.length) j += 1;+ else { i += 1; j += 1; }+ }+ return edits + (a.length - i) + (b.length - j) <= 1;+}++// How strongly a sung word matches a recognized one: exact keys beat a+// one-letter slip ("gonna"/"gona"), which only counts on words long enough+// that a slip is not a different word.+function tokenScore(a, b) {+ if (a === b) return 3;+ if (a.length >= 4 && b.length >= 4 && a[0] === b[0] && withinOneEdit(a, b)) return 2;+ return 0;+}++// Past this many DP cells (~32 MB of Int32) the greedy matcher is used.+const MAX_ALIGN_DP_CELLS = 8_000_000;++// Earliest still-available equal token. Kept for inputs too large for the DP.+function greedyTokenIndexes(director, recognized) {const matchOf = new Array(director.length).fill(-1);let cursor = 0;for (let i = 0; i < director.length; i++) {@@ -138,6 +329,54 @@ function alignTokenIndexes(director, recognized) {return matchOf;}+/**+ * Order-preserving best match of the sung words to the recognized ones (a+ * weighted longest common subsequence). A greedy "next equal word" matcher+ * lets one word the recognizer missed ("the") latch onto the same word a+ * verse later, and every line in between loses its timing; the DP only takes+ * a match when it does not cost more matches elsewhere. Repeated choruses+ * stay in order because a recognized word is used once.+ */+function alignTokenIndexes(director, recognized) {+ const n = director.length;+ const m = recognized.length;+ if (n === 0 || m === 0) return new Array(n).fill(-1);+ if ((n + 1) * (m + 1) > MAX_ALIGN_DP_CELLS) return greedyTokenIndexes(director, recognized);+ const width = m + 1;+ const score = new Int32Array((n + 1) * width);+ for (let i = 1; i <= n; i++) {+ const a = director[i - 1].key;+ for (let j = 1; j <= m; j++) {+ const up = score[(i - 1) * width + j];+ const left = score[i * width + j - 1];+ let best = up > left ? up : left;+ const s = tokenScore(a, recognized[j - 1].key);+ if (s > 0) {+ const diag = score[(i - 1) * width + j - 1] + s;+ if (diag > best) best = diag;+ }+ score[i * width + j] = best;+ }+ }+ const matchOf = new Array(n).fill(-1);+ let i = n;+ let j = m;+ while (i > 0 && j > 0) {+ const here = score[i * width + j];+ const s = tokenScore(director[i - 1].key, recognized[j - 1].key);+ if (s > 0 && here === score[(i - 1) * width + j - 1] + s) {+ matchOf[i - 1] = j - 1;+ i -= 1;+ j -= 1;+ } else if (score[(i - 1) * width + j] >= score[i * width + j - 1]) {+ i -= 1;+ } else {+ j -= 1;+ }+ }+ return matchOf;+}+function distribute(tokens, left, right) {const span = Math.max(0, right - left);const weights = tokens.map((token) => Math.max(1, token.w.length));@@ -244,10 +483,17 @@ function placeAll(cues, byCue, recognized) {return placed;}+// A line the recognizer timed as an instant (a one-word "Hush." whose token+// has from == to) still gets a playable span.+const MIN_LINE_SEC = 0.25;+function applyWordTimes(cue, words) {const next = { ...cue, words };if (next.startSec == null && words.length) next.startSec = words[0].startSec;- if (next.endSec == null && words.length) next.endSec = words[words.length - 1].endSec;+ if (next.endSec == null && words.length) {+ const end = words[words.length - 1].endSec;+ next.endSec = typeof next.startSec === 'number' && end <= next.startSec ? round3(next.startSec + MIN_LINE_SEC) : end;+ }if (typeof next.startSec === 'number' && typeof next.endSec === 'number' && next.endSec <= next.startSec) {if (cue.endSec == null) next.endSec = null;if (cue.startSec == null) next.startSec = null;@@ -364,8 +610,10 @@ export async function pickAlignmentPath(project, io = {}) {return resolveMasterAudioPath(record);});const stem = resolveStem(project);- if (stem) return { path: stem, source: 'vocal-stem' };- return { path: await resolveMaster(project), source: 'master' };+ // With a stem, the mix is transcribed too: the two transcripts are merged so+ // a recognizer that loops on the isolated vocal is outvoted (mergeTranscripts).+ if (stem) return { path: stem, source: 'vocal-stem', mixPath: await resolveMaster(project) };+ return { path: await resolveMaster(project), source: 'master', mixPath: null };}export {@@ -374,6 +622,9 @@ export {explainSttFailure,planAudioChunks,mergeChunkWords,+ mergeTranscripts,+ parseWhisperCliWords,+ dropNonLyricWords,alignDirectorWords,encodePcm16Wav,wavDurationSec,diff --git a/server/services/musicVideo/lyricMarkers.js b/server/services/musicVideo/lyricMarkers.jsnew file mode 100644index 0000000000..fdbc18f401--- /dev/null+++ b/server/services/musicVideo/lyricMarkers.js@@ -0,0 +1,251 @@+/**+ * Music Video lyric-sheet structure: section headers and stage directions.+ *+ * A lyric sheet carries more than sung text. `[Verse 1]`, `[Chorus]` and+ * `[Bridge — stripped groove]` name the song's structure, and directions like+ * `[Spoken, close]`, `[Whispered spoken]`, `[Shouts]` or `[Stop — silence]`+ * say how a line is delivered. The cue importer drops those lines from the+ * sung text; this module keeps them as `lyricMarkers` on the project, each+ * anchored to the index of the lyric line it precedes, so the planner can+ * frame a whispered line close and cut hard on a shout, and the analysis can+ * name its sections after the sheet once the lines are timed.+ *+ * Marker shape: `{ type: 'section' | 'direction', label, kind, line }`.+ * A section's `kind` is its normalized part (`verse`, `chorus`, …); a+ * direction's `kind` is its delivery (`spoken`, `whispered`, `shouted`,+ * `silence`, `hits`, `rhythm`, `note`). `line` is the lyric-cue index the+ * marker applies to; a marker after the last line carries the line count.+ */++import { trimTo } from '../../lib/textUtils.js';++export const LYRIC_MARKER_LABEL_MAX = 120;+export const LYRIC_MARKER_KIND_MAX = 32;+export const LYRIC_MARKERS_MAX = 500;++// Ordered: `pre-chorus` must win over `chorus`.+const SECTION_KINDS = [+ ['pre-chorus', /^pre[\s-]?chorus\b/],+ ['post-chorus', /^post[\s-]?chorus\b/],+ ['chorus', /^(?:(?:final|last|double|big)\s+)?chorus\b/],+ ['verse', /^verse\b/],+ ['bridge', /^(?:middle\s+(?:8|eight)|bridge)\b/],+ ['intro', /^intro\b/],+ ['outro', /^(?:outro|ending)\b/],+ ['hook', /^hook\b/],+ ['refrain', /^refrain\b/],+ ['interlude', /^interlude\b/],+ ['breakdown', /^breakdown\b/],+ ['drop', /^(?:beat\s+)?drop\b/],+ ['instrumental', /^(?:instrumental|(?:guitar\s+|piano\s+)?solo)\b/],+ ['coda', /^coda\b/],+];++// Ordered: "Whispered spoken" is a whisper; "Stop-time" is a rhythmic device,+// not a silence.+const DELIVERY_KINDS = [+ ['whispered', /whisper/],+ ['shouted', /shout|yell|scream|chant/],+ ['hits', /stop[\s-]?time|\bstabs?\b|\bhits?\b/],+ ['silence', /silen|\bstop\b|\bpause\b|a[\s-]?cappella|\bbreak\b/],+ ['spoken', /spoken|\bspeak|\bsaid\b|talk|narrat|recit/],+ ['rhythm', /clap|groove|drum|half[\s-]?time|double[\s-]?time|restart|beat|stomp/],+];++/** Normalized section kind for a header's leading words, or null. */+function sectionKind(text) {+ const head = String(text || '').toLowerCase().trim();+ for (const [kind, pattern] of SECTION_KINDS) if (pattern.test(head)) return kind;+ return null;+}++/** Delivery kind for a stage direction. Unrecognized text is a plain `note`. */+function deliveryKind(text) {+ const lower = String(text || '').toLowerCase();+ for (const [kind, pattern] of DELIVERY_KINDS) if (pattern.test(lower)) return kind;+ return 'note';+}++const clean = (text) => trimTo(String(text || '').replace(/\s+/g, ' ').trim(), LYRIC_MARKER_LABEL_MAX);++/**+ * Markers for one bracketed tag's content. `Bridge — stripped groove` is a+ * section plus a direction note; `Spoken, close` is a direction alone.+ */+function markersForTag(content, line) {+ const text = clean(content);+ if (!text) return [];+ const [head, ...rest] = text.split(/\s+[—–-]\s+|\s*:\s+/);+ const kind = sectionKind(head);+ if (!kind) return [{ type: 'direction', label: text, kind: deliveryKind(text), line }];+ const out = [{ type: 'section', label: clean(head), kind, line }];+ const note = clean(rest.join(' — '));+ if (note) out.push({ type: 'direction', label: note, kind: deliveryKind(note), line });+ return out;+}++const WHOLE_BRACKET = /^\[([^\]]*)\]$/;+const WHOLE_PAREN = /^\(([^)]*)\)$/;+const WHOLE_STAR = /^\*([^*]+)\*$/;+// Only a tag with words in it: `[00:12.50]` is a timestamp, not a direction.+const INLINE_BRACKET = /\[([^\]]*\p{L}[^\]]*)\]/gu;++/**+ * Split plain lyric text into sung lines and structure markers. A whole-line+ * `[…]` or `*…*` is always structure. A whole-line `(…)` is structure only when+ * it reads as a delivery direction — `(oh-oh)` is a sung ad-lib. A `[…]` tag+ * inside a sung line is lifted off the text as a direction for that line.+ */+export function parseLyricSheet(text) {+ const cues = [];+ const markers = [];+ for (const raw of String(text || '').split(/\r?\n/)) {+ const line = raw.trim();+ if (!line) continue;+ const bracket = line.match(WHOLE_BRACKET) || line.match(WHOLE_STAR);+ if (bracket) {+ markers.push(...markersForTag(bracket[1], cues.length));+ continue;+ }+ const paren = line.match(WHOLE_PAREN);+ if (paren && deliveryKind(paren[1]) !== 'note' && !sectionKind(paren[1])) {+ markers.push(...markersForTag(paren[1], cues.length));+ continue;+ }+ const inline = [...line.matchAll(INLINE_BRACKET)].map((m) => m[1]);+ const sung = inline.length ? line.replace(INLINE_BRACKET, ' ').replace(/\s+/g, ' ').trim() : line;+ if (!sung) {+ for (const tag of inline) markers.push(...markersForTag(tag, cues.length));+ continue;+ }+ for (const tag of inline) {+ markers.push(...markersForTag(tag, cues.length).map((m) => (m.type === 'section' ? m : { ...m, type: 'direction' })));+ }+ cues.push({ text: sung, startSec: null, endSec: null });+ }+ return { cues, markers };+}++/** Normalize a stored/edited marker list: known types, bounded text, a line inside the cue list. */+export function normalizeLyricMarkers(markers, cueCount = Infinity) {+ if (!Array.isArray(markers)) return [];+ const maxLine = Number.isFinite(cueCount) ? Math.max(0, cueCount) : 2000;+ const out = [];+ for (const marker of markers) {+ if (!marker || typeof marker !== 'object') continue;+ if (marker.type !== 'section' && marker.type !== 'direction') continue;+ const label = clean(marker.label);+ if (!label) continue;+ const line = Number(marker.line);+ if (!Number.isInteger(line) || line < 0) continue;+ const kind = trimTo(String(marker.kind || ''), LYRIC_MARKER_KIND_MAX)+ || (marker.type === 'section' ? (sectionKind(label) || 'section') : deliveryKind(label));+ out.push({ type: marker.type, label, kind, line: Math.min(line, maxLine) });+ if (out.length >= LYRIC_MARKERS_MAX) break;+ }+ return out;+}++/** Shift every marker's line by `offset` (appending an imported sheet after existing lines). */+export const offsetLyricMarkers = (markers, offset) => (markers || []).map((m) => ({ ...m, line: m.line + offset }));++const isTime = (value) => typeof value === 'number' && Number.isFinite(value);++// First timed cue at or after `line` and before `stop`.+function firstTimed(cues, line, stop) {+ for (let i = line; i < Math.min(stop, cues.length); i++) if (isTime(cues[i]?.startSec)) return cues[i];+ return null;+}++function lastTimedEnd(cues, from, stop) {+ for (let i = Math.min(stop, cues.length) - 1; i >= from; i--) {+ const cue = cues[i];+ if (isTime(cue?.endSec)) return cue.endSec;+ if (isTime(cue?.startSec)) return cue.startSec;+ }+ return null;+}++/**+ * Time spans of the sheet's sections once its lines are timed. A section runs+ * from its first timed line to the next section's first timed line (the last+ * one to its last timed line). Sections with no timed line are left out.+ */+function lyricSectionSpans(cues, markers) {+ const list = Array.isArray(cues) ? cues : [];+ const sections = (markers || []).filter((m) => m?.type === 'section');+ const spans = [];+ sections.forEach((section, index) => {+ const stop = index + 1 < sections.length ? sections[index + 1].line : list.length;+ const first = firstTimed(list, section.line, stop);+ if (!first) return;+ spans.push({ label: section.label, kind: section.kind, startSec: first.startSec, stop, line: section.line });+ });+ return spans.map((span, index) => {+ const next = spans[index + 1];+ const endSec = next ? next.startSec : lastTimedEnd(list, span.line, span.stop);+ return { label: span.label, kind: span.kind, startSec: span.startSec, endSec: isTime(endSec) && endSec > span.startSec ? endSec : span.startSec };+ }).filter((span) => span.endSec > span.startSec);+}++// An analysis section takes the sheet's name when at least this share of it+// lies inside one lyric section.+const RELABEL_MIN_SHARE = 0.45;++const overlap = (a, b) => Math.max(0, Math.min(a.endSec, b.endSec) - Math.max(a.startSec, b.startSec));++function restore(section) {+ if (section.labelSource !== 'lyrics') return section;+ const { analysisLabel, labelSource, ...rest } = section;+ return { ...rest, label: analysisLabel || rest.label };+}++/**+ * Name the analysis sections after the lyric sheet. Each section keeps its+ * detector label in `analysisLabel` and is marked `labelSource: 'lyrics'`, so+ * a later pass can restore it. Stretches before the first sung section and+ * after the last become Intro/Outro. Boundaries, energy and every other+ * analysis field are untouched. Returns the analysis unchanged when nothing is+ * timed.+ */+export function relabelAnalysisSections(analysis, cues, markers) {+ if (!analysis || !Array.isArray(analysis.sections)) return analysis;+ const spans = lyricSectionSpans(cues, markers);+ const sections = analysis.sections.map((section) => {+ const base = restore(section);+ if (spans.length === 0) return base;+ const length = base.endSec - base.startSec;+ if (!(length > 0)) return base;+ let best = null;+ let bestShare = 0;+ for (const span of spans) {+ const share = overlap(base, span) / length;+ if (share > bestShare) { best = span; bestShare = share; }+ }+ const original = base.label;+ const named = (label) => ({ ...base, label, labelSource: 'lyrics', analysisLabel: original });+ if (best && bestShare >= RELABEL_MIN_SHARE) return named(best.label);+ if (base.endSec <= spans[0].startSec + 0.25) return named('Intro');+ if (base.startSec >= spans[spans.length - 1].endSec - 0.25) return named('Outro');+ return base;+ });+ return { ...analysis, sections };+}++/**+ * Delivery directions that fall inside [startSec, endSec): a direction is+ * placed at the start of the line it precedes, or at the end of the last+ * line when it trails the sheet. Returns the direction labels in order.+ */+export function deliveryNotesWithin(cues, markers, startSec, endSec) {+ const list = Array.isArray(cues) ? cues : [];+ const notes = [];+ for (const marker of markers || []) {+ if (marker?.type !== 'direction') continue;+ const cue = list[marker.line];+ const at = cue && isTime(cue.startSec) ? cue.startSec : (marker.line >= list.length ? lastTimedEnd(list, 0, list.length) : null);+ if (!isTime(at) || at < startSec || at >= endSec) continue;+ if (!notes.includes(marker.label)) notes.push(marker.label);+ }+ return notes;+}diff --git a/server/services/musicVideo/lyricTranscriber.js b/server/services/musicVideo/lyricTranscriber.jsnew file mode 100644index 0000000000..a8c2f57763--- /dev/null+++ b/server/services/musicVideo/lyricTranscriber.js@@ -0,0 +1,286 @@+/**+ * Speech-to-text for Music Video lyric alignment.+ *+ * Voice chat's STT is off by default (the browser does it) and its whisper+ * model is `base.en`, which is too weak for a sung vocal. Alignment therefore+ * brings its own runner and never asks the director to enable voice:+ *+ * 1. `whisper-cli` on PATH → one-shot run over the whole decoded song with a+ * music-grade model (large-v3-turbo), word timestamps from its `-ojf`+ * JSON. A 3–4 minute song takes seconds on Apple Silicon.+ * 2. The configured voice STT endpoint, when something answers there.+ * 3. `whisper-server` on PATH → a temporary loopback server on a free port+ * with the music-grade model, stopped when the alignment finishes.+ * 4. None of these → 503 with how to install whisper.cpp.+ *+ * The model downloads on the first alignment that needs it (a user click or+ * an autopilot run the user started — never at boot) into the same folder+ * voice uses, through a `.partial` file renamed into place when complete.+ *+ * A transcriber is `{ kind, transcribe(wav, { startSec, endSec, prompt }), release() }`+ * where `transcribe` returns words on the SONG clock.+ */++import { existsSync } from 'fs';+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { createServer } from 'net';+import { homedir, tmpdir } from 'os';+import { basename, join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { spawn } from '../../lib/childProcess.js';+import { whichFirst } from '../../lib/processEnv.js';+import { runStreamingCommand } from '../../lib/streamingSpawn.js';+import { streamResumableDownload } from '../../lib/downloadPreflight.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { killWithEscalation } from '../../lib/killWithEscalation.js';+import { getVoiceConfig, expandPath } from '../voice/config.js';+import { transcribe as sttTranscribe } from '../voice/stt.js';+import {+ explainSttFailure,+ lyricAlignChunkSec,+ mergeChunkWords,+ parseWhisperCliWords,+ planAudioChunks,+ sliceWav,+ wavDurationSec,+} from './lyricAlignCore.js';++export const ALIGN_MODEL_FILE = 'ggml-large-v3-turbo.bin';+export const ALIGN_MODEL_URL = `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${ALIGN_MODEL_FILE}`;+export const alignModelDir = () => join(homedir(), '.portos', 'voice', 'models');++// Homebrew's whisper-cpp ships `whisper-cli`; older builds named it `whisper-cpp`.+const WHISPER_CLI_NAMES = ['whisper-cli', 'whisper-cpp'];+const CLI_TIMEOUT_MS = 15 * 60 * 1000;+const SERVER_BOOT_MS = 90_000;+const ENDPOINT_PROBE_MS = 1500;++export const WHISPER_MISSING_MESSAGE = 'Aligning words needs whisper.cpp, and none was found on this machine. '+ + 'Install it (macOS: `brew install whisper-cpp`; Linux/Windows: build whisper.cpp so `whisper-cli` is on PATH, '+ + 'or run scripts/setup-voice.sh), then click Align words again.';++let modelDownload = null;++async function downloadAlignmentModel(target, { download = streamResumableDownload } = {}) {+ console.log(`⬇️ Downloading whisper alignment model ${ALIGN_MODEL_FILE} (about 1.6 GB, first alignment only)`);+ let lastDecile = -1;+ await download({+ url: ALIGN_MODEL_URL,+ destPath: target,+ onBytes: (received, total) => {+ if (!(total > 0)) return;+ const decile = Math.floor((received / total) * 10);+ if (decile === lastDecile) return;+ lastDecile = decile;+ console.log(`⬇️ Whisper alignment model ${decile * 10}% (${Math.round(received / 1e6)} of ${Math.round(total / 1e6)} MB)`);+ },+ });+ console.log(`✅ Whisper alignment model ready at ${target}`);+}++/**+ * Path of a music-grade whisper model, downloading large-v3-turbo on first+ * use. A `large` model the voice settings already point at is used as is.+ * Concurrent callers share one download.+ */+async function ensureAlignmentModel({ configuredModelPath = null, download } = {}) {+ const target = join(alignModelDir(), ALIGN_MODEL_FILE);+ if (existsSync(target)) return target;+ if (configuredModelPath && /large/i.test(basename(configuredModelPath)) && existsSync(configuredModelPath)) {+ return configuredModelPath;+ }+ if (!modelDownload) {+ modelDownload = downloadAlignmentModel(target, { download }).finally(() => { modelDownload = null; });+ }+ await modelDownload.catch((err) => {+ console.error(`❌ Whisper alignment model download failed: ${err.message}`);+ throw new ServerError(`Could not download the whisper alignment model: ${err.message}`, { status: 502, code: 'LYRIC_ALIGN_MODEL_DOWNLOAD_FAILED' });+ });+ return target;+}++/** whisper-cli argv for one WAV file; JSON lands at `${outBase}.json`. */+function whisperCliArgs({ modelPath, wavPath, outBase, language = 'en', prompt = '' }) {+ const args = ['-m', modelPath, '-f', wavPath, '-l', language, '-ml', '1', '-sow', '-ojf', '-of', outBase, '-np'];+ if (prompt) args.push('--prompt', prompt);+ return args;+}++function regionOf(wav, { startSec, endSec } = {}) {+ const duration = wavDurationSec(wav);+ if (!(duration > 0)) {+ throw new ServerError('Could not read the decoded vocal.', { status: 422, code: 'LYRIC_ALIGN_DECODE_FAILED' });+ }+ const start = Math.max(0, startSec || 0);+ const end = Math.min(duration, endSec ?? duration);+ if (!(end > start)) {+ throw new ServerError('That lyric line has no audio window to align.', { status: 422, code: 'LYRIC_ALIGN_NO_WINDOW' });+ }+ return { startSec: start, endSec: end, whole: start === 0 && end === duration };+}++/** One-shot whisper-cli transcriber. */+function createCliTranscriber({ bin, modelPath, language = 'en', run = runStreamingCommand }) {+ return {+ kind: 'whisper-cli',+ async transcribe(wav, { startSec, endSec, prompt = '' } = {}) {+ const region = regionOf(wav, { startSec, endSec });+ const dir = await mkdtemp(join(tmpdir(), 'lyric-align-cli-'));+ try {+ const wavPath = join(dir, 'audio.wav');+ const outBase = join(dir, 'words');+ await writeFile(wavPath, region.whole ? wav : sliceWav(wav, region.startSec, region.endSec));+ const result = await run(bin, whisperCliArgs({ modelPath, wavPath, outBase, language, prompt }), null, { timeoutMs: CLI_TIMEOUT_MS });+ if (!result?.success) {+ console.error(`❌ whisper-cli failed: ${result?.error || 'unknown error'}`);+ throw new ServerError(`whisper-cli could not transcribe the song: ${result?.error || 'unknown error'}`, { status: 502, code: 'LYRIC_ALIGN_WHISPER_FAILED' });+ }+ const raw = await readFile(`${outBase}.json`, 'utf8').catch(() => null);+ const parsed = raw ? (() => { try { return JSON.parse(raw); } catch { return null; } })() : null;+ if (!parsed) {+ throw new ServerError('whisper-cli wrote no readable word timings.', { status: 502, code: 'LYRIC_ALIGN_WHISPER_FAILED' });+ }+ return parseWhisperCliWords(parsed).map((word) => ({+ ...word,+ startSec: word.startSec + region.startSec,+ endSec: word.endSec + region.startSec,+ }));+ } finally {+ await rm(dir, { recursive: true, force: true }).catch(() => {});+ }+ },+ release: async () => {},+ };+}++/**+ * Transcriber over a whisper.cpp HTTP server (the voice endpoint or a+ * temporary one): the region is chunked so each request fits the STT timeout.+ */+function createEndpointTranscriber({ endpoint = null, kind = 'stt-endpoint', transcribe = sttTranscribe, release = async () => {} }) {+ return {+ kind,+ async transcribe(wav, { startSec, endSec, prompt = '' } = {}) {+ const region = regionOf(wav, { startSec, endSec });+ const chunks = planAudioChunks(region.endSec - region.startSec, { chunkSec: lyricAlignChunkSec() }).map((chunk) => ({+ startSec: region.startSec + chunk.startSec,+ endSec: region.startSec + chunk.endSec,+ }));+ console.log(`🎤 Aligning lyric words (${chunks.length} whisper ${chunks.length === 1 ? 'chunk' : 'chunks'} via ${kind})`);+ const results = [];+ for (const chunk of chunks) {+ let result;+ try {+ result = await transcribe(sliceWav(wav, chunk.startSec, chunk.endSec), {+ verbose: true,+ mimeType: 'audio/wav',+ filename: 'lyric-align.wav',+ prompt,+ ...(endpoint ? { endpoint } : {}),+ });+ } catch (err) {+ console.error(`❌ Lyric alignment speech-to-text failed: ${err.message}`);+ throw new ServerError(explainSttFailure(err), { status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE' });+ }+ results.push({+ startSec: chunk.startSec,+ endSec: chunk.endSec,+ words: (result?.words || []).map((word) => ({ text: word.text, startSec: word.startSec, endSec: word.endSec })),+ });+ }+ return mergeChunkWords(results);+ },+ release,+ };+}++/** True when anything answers HTTP at the endpoint (any status = bound). */+async function probeSttEndpoint(endpoint) {+ if (!endpoint) return false;+ return fetchWithTimeout(`${String(endpoint).replace(/\/+$/, '')}/`, { method: 'GET' }, ENDPOINT_PROBE_MS)+ .then(() => true)+ .catch(() => false);+}++function freeLoopbackPort() {+ return new Promise((resolve, reject) => {+ const server = createServer();+ server.unref();+ server.on('error', reject);+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address();+ server.close(() => resolve(port));+ });+ });+}++/** Start a private whisper-server for this alignment; resolves `{ endpoint, stop }`. */+async function startTemporaryWhisperServer({ bin, modelPath }) {+ const port = await freeLoopbackPort();+ const endpoint = `http://127.0.0.1:${port}`;+ const child = spawn(bin, ['--host', '127.0.0.1', '--port', String(port), '--model', modelPath], { stdio: 'ignore' });+ let exited = false;+ child.on('exit', () => { exited = true; });+ child.on('error', (err) => {+ exited = true;+ console.error(`❌ Temporary whisper-server failed: ${err.message}`);+ });+ const stop = async () => {+ if (exited) return;+ killWithEscalation(child, { label: 'temporary whisper-server', stillRunning: () => !exited });+ };+ const deadline = Date.now() + SERVER_BOOT_MS;+ while (Date.now() < deadline && !exited) {+ if (await probeSttEndpoint(endpoint)) {+ console.log(`🎙️ Temporary whisper-server up on ${endpoint} for lyric alignment`);+ return { endpoint, stop };+ }+ await new Promise((resolve) => setTimeout(resolve, 300));+ }+ await stop();+ throw new ServerError('The temporary whisper server did not start. Check that whisper-server runs from a terminal.', { status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE' });+}++async function firstOnPath(names, which) {+ for (const name of names) {+ const found = await which(name);+ if (found) return found;+ }+ return null;+}++/**+ * Pick the runner for this alignment (see the module header for the order).+ * Every dependency is injectable so selection is testable without binaries.+ */+export async function resolveAlignmentTranscriber(deps = {}) {+ const {+ which = whichFirst,+ voiceConfig = getVoiceConfig,+ probeEndpoint = probeSttEndpoint,+ ensureModel = ensureAlignmentModel,+ runCommand = runStreamingCommand,+ startServer = startTemporaryWhisperServer,+ transcribe = sttTranscribe,+ } = deps;+ const cfg = await voiceConfig().catch(() => null);+ const language = cfg?.stt?.language || 'en';+ const configuredModelPath = cfg?.stt?.modelPath ? expandPath(cfg.stt.modelPath) : null;++ const cli = await firstOnPath(WHISPER_CLI_NAMES, which);+ if (cli) {+ const modelPath = await ensureModel({ configuredModelPath });+ return createCliTranscriber({ bin: cli, modelPath, language, run: runCommand });+ }+ const endpoint = cfg?.stt?.endpoint || null;+ if (endpoint && await probeEndpoint(endpoint)) {+ return createEndpointTranscriber({ endpoint, kind: 'stt-endpoint', transcribe });+ }+ const serverBin = await which('whisper-server');+ if (serverBin) {+ const modelPath = await ensureModel({ configuredModelPath });+ const server = await startServer({ bin: serverBin, modelPath });+ return createEndpointTranscriber({ endpoint: server.endpoint, kind: 'whisper-server', transcribe, release: server.stop });+ }+ throw new ServerError(WHISPER_MISSING_MESSAGE, { status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE' });+}diff --git a/server/services/musicVideo/lyricTranscriber.test.js b/server/services/musicVideo/lyricTranscriber.test.jsnew file mode 100644index 0000000000..a7c26bcd57--- /dev/null+++ b/server/services/musicVideo/lyricTranscriber.test.js@@ -0,0 +1,104 @@+import { describe, it, expect, vi } from 'vitest';+import { writeFile } from 'fs/promises';+import { encodePcm16Wav, parseWhisperCliWords } from './lyricAlignCore.js';+import { resolveAlignmentTranscriber } from './lyricTranscriber.js';++// A whisper-cli `-ml 1 -sow -ojf` file: one entry per word, offsets in ms,+// special tokens and empty entries mixed in, a contraction split over two+// tokens, and a sound caption the recognizer invented.+const CLI_JSON = {+ systeminfo: 'test',+ model: { type: 'large' },+ result: { language: 'en' },+ transcription: [+ { offsets: { from: 0, to: 170 }, text: '', tokens: [{ text: '[_BEG_]', offsets: { from: 0, to: 0 } }] },+ {+ offsets: { from: 170, to: 900 },+ text: " I'm",+ tokens: [{ text: ' I', offsets: { from: 170, to: 400 } }, { text: "'m", offsets: { from: 400, to: 900 } }],+ },+ { offsets: { from: 900, to: 1400 }, text: ' walking', tokens: [{ text: ' walking', offsets: { from: 900, to: 1400 } }] },+ { offsets: { from: 1400, to: 2000 }, text: ' home', tokens: [{ text: ' home', offsets: { from: 1400, to: 2000 } }, { text: '[_TT_100]', offsets: { from: 2000, to: 2000 } }] },+ { offsets: { from: 2500, to: 2800 }, text: ' *soft', tokens: [{ text: ' *', offsets: { from: 2500, to: 2600 } }, { text: 'soft', offsets: { from: 2600, to: 2800 } }] },+ { offsets: { from: 2800, to: 3200 }, text: ' music*', tokens: [{ text: ' music', offsets: { from: 2800, to: 3100 } }, { text: '*', offsets: { from: 3100, to: 3200 } }] },+ { offsets: { from: 4000, to: 4600 }, text: ' tonight', tokens: [{ text: ' tonight', offsets: { from: 4000, to: 4600 } }] },+ ],+};++describe('parseWhisperCliWords', () => {+ it('reads word timings from the -ojf file, dropping special tokens and sound captions', () => {+ expect(parseWhisperCliWords(CLI_JSON)).toEqual([+ { text: "I'm", startSec: 0.17, endSec: 0.9 },+ { text: 'walking', startSec: 0.9, endSec: 1.4 },+ { text: 'home', startSec: 1.4, endSec: 2 },+ { text: 'tonight', startSec: 4, endSec: 4.6 },+ ]);+ });+});++describe('resolveAlignmentTranscriber', () => {+ const voiceConfig = async () => ({ stt: { endpoint: 'http://127.0.0.1:5562', language: 'en', modelPath: '/models/ggml-base.en.bin' } });+ const which = (present) => vi.fn(async (name) => (present.includes(name) ? `/bin/${name}` : null));++ it('prefers whisper-cli with the music model, and runs it once over the song', async () => {+ const ensureModel = vi.fn(async () => '/models/ggml-large-v3-turbo.bin');+ const probeEndpoint = vi.fn(async () => true);+ const runCommand = vi.fn(async (bin, args) => {+ const outBase = args[args.indexOf('-of') + 1];+ await writeFile(`${outBase}.json`, JSON.stringify(CLI_JSON));+ return { success: true };+ });+ const transcriber = await resolveAlignmentTranscriber({+ which: which(['whisper-cli', 'whisper-server']), voiceConfig, probeEndpoint, ensureModel, runCommand,+ });+ expect(transcriber.kind).toBe('whisper-cli');+ expect(probeEndpoint).not.toHaveBeenCalled();+ expect(ensureModel).toHaveBeenCalledWith({ configuredModelPath: '/models/ggml-base.en.bin' });++ // A windowed re-align slices the audio and shifts the words onto the song clock.+ const words = await transcriber.transcribe(encodePcm16Wav(16000 * 10), { startSec: 2, endSec: 8, prompt: 'walking home' });+ expect(runCommand).toHaveBeenCalledOnce();+ const [bin, args] = runCommand.mock.calls[0];+ expect(bin).toBe('/bin/whisper-cli');+ expect(args).toEqual(expect.arrayContaining(['-m', '/models/ggml-large-v3-turbo.bin', '-ml', '1', '-ojf', '-sow', '--prompt', 'walking home']));+ expect(words[0]).toEqual({ text: "I'm", startSec: 2.17, endSec: 2.9 });+ });++ it('uses the voice endpoint when whisper-cli is absent and something answers there', async () => {+ const ensureModel = vi.fn();+ const transcribe = vi.fn(async () => ({ words: [{ text: 'hello', startSec: 0.1, endSec: 0.4 }] }));+ const transcriber = await resolveAlignmentTranscriber({+ which: which(['whisper-server']), voiceConfig, probeEndpoint: async () => true, ensureModel, transcribe,+ });+ expect(transcriber.kind).toBe('stt-endpoint');+ expect(ensureModel).not.toHaveBeenCalled();+ const words = await transcriber.transcribe(encodePcm16Wav(16000 * 4), { prompt: 'hello' });+ expect(words).toEqual([{ text: 'hello', startSec: 0.1, endSec: 0.4 }]);+ expect(transcribe).toHaveBeenCalledWith(expect.any(Buffer), expect.objectContaining({ endpoint: 'http://127.0.0.1:5562', verbose: true, prompt: 'hello' }));+ });++ it('starts a temporary whisper-server when nothing answers and only the server binary exists', async () => {+ const stop = vi.fn(async () => {});+ const startServer = vi.fn(async () => ({ endpoint: 'http://127.0.0.1:40123', stop }));+ const transcriber = await resolveAlignmentTranscriber({+ which: which(['whisper-server']),+ voiceConfig,+ probeEndpoint: async () => false,+ ensureModel: async () => '/models/ggml-large-v3-turbo.bin',+ startServer,+ transcribe: vi.fn(async () => ({ words: [] })),+ });+ expect(transcriber.kind).toBe('whisper-server');+ expect(startServer).toHaveBeenCalledWith({ bin: '/bin/whisper-server', modelPath: '/models/ggml-large-v3-turbo.bin' });+ await transcriber.release();+ expect(stop).toHaveBeenCalledOnce();+ });++ it('refuses with install steps, and downloads nothing, when no whisper exists at all', async () => {+ const ensureModel = vi.fn();+ await expect(resolveAlignmentTranscriber({+ which: which([]), voiceConfig, probeEndpoint: async () => false, ensureModel,+ })).rejects.toMatchObject({ status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE', message: expect.stringMatching(/brew install whisper-cpp/) });+ expect(ensureModel).not.toHaveBeenCalled();+ });+});diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.jsindex 1f757f662a..07272a3ba8 100644--- a/server/services/musicVideo/planner.js+++ b/server/services/musicVideo/planner.js@@ -43,6 +43,7 @@ import { extractJson } from '../../lib/jsonExtract.js';import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';import { planShots, resolveClipCapacitySec, validSections } from './shotPlan.js';import { getProject, addProjectScenes } from './projects.js';+import { deliveryNotesWithin } from './lyricMarkers.js';const SCENE_LABEL_MAX = 120;const SCENE_TEXT_MAX = 2000;@@ -115,6 +116,7 @@ export function buildScenePlanPrompt(project, shots) {const guidance = project.automation?.guidance?.trim();const guidanceLine = guidance ? `Director guidance: ${quote(guidance, PROMPT_GUIDANCE_MAX)}` : '';const hasLyrics = shots.some((s) => s.lyricText);+ const hasDelivery = shots.some((s) => s.delivery?.length);const shotLines = shots.map((s, i) => {const duration = (s.endSec - s.startSec).toFixed(1);const energy = typeof s.sectionEnergy === 'number' ? s.sectionEnergy.toFixed(2) : 'unknown';@@ -122,6 +124,7 @@ export function buildScenePlanPrompt(project, shots) {const parts = [`${i}. ${section} — ${duration}s, energy ${energy}`];parts.push(s.lyricText ? `lyrics: "${quote(s.lyricText, PROMPT_LYRIC_MAX)}"` : 'instrumental');if (s.visualIntent) parts.push(`intent: ${quote(s.visualIntent, PROMPT_LYRIC_MAX)}`);+ if (s.delivery?.length) parts.push(`delivery: ${quote(s.delivery.join('; '), PROMPT_LYRIC_MAX)}`);if (s.hook) parts.push('OPENING HOOK');return parts.join('; ');}).join('\n');@@ -133,7 +136,7 @@ ${musicVideoCreativeContext(concept)}${briefLines}${guidanceLine}-The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent):+The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent${hasDelivery ? '; optional delivery directions from the lyric sheet' : ''}):${shotLines}For EACH shot above, propose the shot for a generative video model:@@ -141,7 +144,7 @@ For EACH shot above, propose the shot for a generative video model:- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections read more kinetic; calmer sections more static/lingering.- Shots in the same section are one edited sequence: keep subject and setting continuous, but vary framing (wide / medium / close), angle, or action from shot to shot so consecutive shots cut rather than repeat.- The OPENING HOOK shot must grab attention immediately.-${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text.\n' : ''}- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.+${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text.\n' : ''}${hasDelivery ? '- Follow the delivery directions: spoken or whispered lines play as intimate close-ups; shouts land as hard-hitting cuts or impacts; a silence or stop is a held, frozen or cut-to-black beat.\n' : ''}- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.Respond with ONLY a JSON array, one object per shot, in shot-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:[{ "index": 0, "framePrompt": "<the opening reference still, ready to render>", "prompt": "<the shot's motion, ready to render>" }]`;@@ -261,6 +264,15 @@ export async function planProject(id, { seedPrompts = true, providerId, model, dpacing: project.pacing,clipCapacitySec: resolveClipCapacitySec(project.videoSettings),});+ // Lyric-sheet stage directions ([Spoken, close], [Shouts], [Stop — silence])+ // placed by the timed lines, so the first-pass prompts can frame them.+ const markers = project.lyricMarkers || [];+ if (markers.length) {+ for (const shot of shots) {+ const delivery = deliveryNotesWithin(project.lyricCues, markers, shot.startSec, shot.endSec);+ if (delivery.length) shot.delivery = delivery;+ }+ }const sceneInputs = sceneInputsFromShots(shots);let promptsSeeded = false;diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.jsindex 8e34754815..e688ce2c3c 100644--- a/server/services/musicVideo/planner.test.js+++ b/server/services/musicVideo/planner.test.js@@ -471,6 +471,30 @@ Here is my answer:expect(lyricShots[0].endSec).toBeGreaterThanOrEqual(15);});+ it('hands the lyric sheet\'s delivery directions to the first-pass prompt for the shot they fall in', async () => {+ getProject.mockResolvedValue(makeProject({+ lyricCues: [+ { id: 'lc-1', text: 'come closer', startSec: 2, endSec: 4 },+ { id: 'lc-2', text: 'let it out', startSec: 12, endSec: 14 },+ ],+ lyricMarkers: [+ { type: 'direction', label: 'Whispered spoken', kind: 'whispered', line: 0 },+ { type: 'direction', label: 'Shouts', kind: 'shouted', line: 1 },+ ],+ }));+ addProjectScenes.mockResolvedValue(freshProjectResult());+ resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });+ runPromptThroughProvider.mockResolvedValue({ text: '[]' });++ await planProject('mv-1');++ const { prompt } = runPromptThroughProvider.mock.calls[0][0];+ const lines = prompt.split('\n');+ expect(lines.find((line) => line.includes('"come closer"'))).toMatch(/delivery: Whispered spoken/);+ expect(lines.find((line) => line.includes('"let it out"'))).toMatch(/delivery: Shouts/);+ expect(prompt).toMatch(/whispered lines play as intimate close-ups/);+ });+it('still honors the planned spans when the cached analysis has no beat grid', async () => {getProject.mockResolvedValue(makeProject({audioAnalysis: { bpm: null, beats: [], downbeats: [], sections: SECTIONS, durationSec: 30 },diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex 2fb06799e9..862f027ec1 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -95,10 +95,12 @@ async function seedTrackMetadata(input) {const track = await getTrack(input.trackId).catch(() => null);if (!track) return input;let lyricCues = input.lyricCues;+ let lyricMarkers = input.lyricMarkers;if ((!lyricCues || lyricCues.length === 0) && track.lyrics) {const parsed = parseLyricCues(track.lyrics);if (parsed.cues && parsed.cues.length > 0) {lyricCues = parsed.cues;+ lyricMarkers = parsed.markers;}}let name = input.name;@@ -117,6 +119,7 @@ async function seedTrackMetadata(input) {...input,...(name ? { name } : {}),...(lyricCues ? { lyricCues } : {}),+ ...(lyricMarkers ? { lyricMarkers } : {}),...(concept ? { concept } : {}),};}@@ -129,10 +132,12 @@ async function seedTrackMetadataOnUpdate(id, patch) {const track = await getTrack(patch.trackId).catch(() => null);if (!track) return patch;let lyricCues = patch.lyricCues;+ let lyricMarkers = patch.lyricMarkers;if (!lyricCues && track.lyrics) {const parsed = parseLyricCues(track.lyrics);if (parsed.cues && parsed.cues.length > 0) {lyricCues = parsed.cues;+ lyricMarkers = parsed.markers;}}let concept = patch.concept;@@ -147,6 +152,7 @@ async function seedTrackMetadataOnUpdate(id, patch) {return {...patch,...(lyricCues ? { lyricCues } : {}),+ ...(lyricMarkers ? { lyricMarkers } : {}),...(concept ? { concept } : {}),};}diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 34d7391428..c1ce19a25e 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -31,6 +31,7 @@ import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';import { isStr } from '../../lib/textUtils.js';import { isPerformanceScene, planShotSplit, shotSplitLimit } from '../../lib/musicVideoShotTiming.js';import { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';+import { normalizeLyricMarkers } from './lyricMarkers.js';import { ensureSceneTakes, TAKE_SLOT } from './takes.js';import { normalizeComposition, invalidateCompositionTiming } from './composition.js';import { normalizeSoundBed } from './soundBed.js';@@ -140,6 +141,12 @@ export function buildProjectRecord(input, { id, now }) {// #8964 — editable timed lyric cues + phrase annotations (timed against// the current audio source) and the shot planner's pacing range.lyricCues: Array.isArray(input.lyricCues) ? normalizeLyricCues(input.lyricCues) : [],+ // Section headers + stage directions read off the lyric sheet, anchored to+ // cue indices (lyricMarkers.js). Present only when the sheet had any, so a+ // record without them keeps its shape.+ ...(Array.isArray(input.lyricMarkers) && input.lyricMarkers.length+ ? { lyricMarkers: normalizeLyricMarkers(input.lyricMarkers) }+ : {}),phrases: Array.isArray(input.phrases) ? normalizePhrases(input.phrases) : [],pacing: input.pacing ?? null,// #8984 — composition manifest (null = plain concatenation render).@@ -259,6 +266,7 @@ export function applyProjectPatch(project, patch) {automation: patch.automation ? normalizeMusicVideoAutomation(patch.automation, project.automation) : null,} : {}),...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues) } : {}),+ ...(Array.isArray(patch.lyricMarkers) ? { lyricMarkers: normalizeLyricMarkers(patch.lyricMarkers) } : {}),...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),// #8984 — the composition manifest is replaced whole; null clears it....('composition' in patch ? { composition: normalizeComposition(patch.composition) } : {}),diff --git a/server/services/musicVideo/timedText.js b/server/services/musicVideo/timedText.jsindex 8e8ddb2ff0..cb79b906f3 100644--- a/server/services/musicVideo/timedText.js+++ b/server/services/musicVideo/timedText.js@@ -17,16 +17,24 @@import { randomUUID } from 'crypto';import { trimTo } from '../../lib/textUtils.js';+import { parseLyricSheet } from './lyricMarkers.js';const MAX_CUE_TEXT = 500;const MAX_SEC = 36000;const round3 = (n) => Math.round(n * 1000) / 1000;-/** One sung word: the director's spelling plus a key with punctuation stripped. */+/**+ * Comparison key for one sung word: lower case, letters and digits only.+ * Apostrophes drop out entirely, so a sheet's curly `I’m` and a recognizer's+ * straight `I'm` compare equal, and accented letters survive (`café`).+ */+export const lyricKey = (word) => String(word || '').toLowerCase().normalize('NFC').replace(/[^\p{L}\p{N}]+/gu, '');++/** One sung word: the director's spelling plus its comparison key. */export function lyricTokens(text) {return String(text || '').split(/\s+/).filter(Boolean).map((w) => {- const key = w.toLowerCase().replace(/[^a-z0-9']+/g, '');+ const key = lyricKey(w);return key ? { w, key } : null;}).filter(Boolean);}@@ -174,13 +182,6 @@ function parseSrt(text) {return cues;}-function parsePlain(text) {- return text.split(/\r?\n/)- .map((line) => line.trim())- // Section headers like "[Chorus]" are structure, not sung text.- .filter((line) => line && !/^\[[^\]]*\]$/.test(line))- .map((line) => ({ text: line, startSec: null, endSec: null }));-}function detectLyricsFormat(text) {if (/-->/.test(text)) return 'srt';@@ -190,13 +191,16 @@ function detectLyricsFormat(text) {/*** Parse pasted/imported lyric text into cue inputs (not yet id'd — run the- * result through `normalizeLyricCues`). Returns `{ format, cues }`.+ * result through `normalizeLyricCues`). Returns `{ format, cues, markers }`.+ * Plain text keeps its section headers and stage directions (`[Chorus]`,+ * `[Spoken, close]`) as `markers` anchored to line indices instead of sung+ * lines (lyricMarkers.js); timed formats carry none.*/export function parseLyricCues(text, format = 'auto') {const source = typeof text === 'string' ? text : '';const resolved = format === 'auto' || !format ? detectLyricsFormat(source) : format;- const cues = resolved === 'lrc' ? parseLrc(source)- : resolved === 'srt' ? parseSrt(source)- : parsePlain(source);- return { format: resolved, cues };+ if (resolved === 'lrc') return { format: resolved, cues: parseLrc(source), markers: [] };+ if (resolved === 'srt') return { format: resolved, cues: parseSrt(source), markers: [] };+ const { cues, markers } = parseLyricSheet(source);+ return { format: resolved, cues, markers };}diff --git a/server/services/musicVideo/timedText.test.js b/server/services/musicVideo/timedText.test.jsindex e7d5cdc543..86879b8299 100644--- a/server/services/musicVideo/timedText.test.js+++ b/server/services/musicVideo/timedText.test.js@@ -33,6 +33,7 @@ describe('parseLyricCues', () => {{ text: 'Hello there', startSec: 1, endSec: 3.5 },{ text: 'Second', startSec: 62.25, endSec: 64 },],+ markers: [],});});@@ -44,16 +45,60 @@ describe('parseLyricCues', () => {]);});- it('imports plain lyrics as untimed lines, dropping section headers and blanks', () => {+ it('imports plain lyrics as untimed lines, keeping section headers as markers', () => {expect(parseLyricCues('[Verse 1]\nWalking home\n\n under neon \n[Chorus]\n')).toEqual({format: 'text',cues: [{ text: 'Walking home', startSec: null, endSec: null },{ text: 'under neon', startSec: null, endSec: null },],+ markers: [+ { type: 'section', label: 'Verse 1', kind: 'verse', line: 0 },+ { type: 'section', label: 'Chorus', kind: 'chorus', line: 2 },+ ],});});+ // The lyric-sheet vocabulary is a real input matrix: each row pins how one+ // header or stage-direction shape becomes structure rather than sung text.+ it('reads section headers and stage directions off a lyric sheet', () => {+ const sheet = [+ '[Intro]',+ '(Spoken, close)',+ 'Hello there',+ '[Pre-Chorus]',+ 'Up we go [Shouts]',+ '(oh-oh)',+ '[Stop — silence]',+ '[Bridge — stripped groove]',+ '[Whispered spoken]',+ 'Quiet now',+ '[Stop-time]',+ '[Final Chorus — full return]',+ '*Handclaps*',+ 'Big finish',+ '[Outro — drums cut, spoken]',+ ].join('\n');+ const { cues, markers } = parseLyricCues(sheet);+ expect(cues.map((cue) => cue.text)).toEqual(['Hello there', 'Up we go', '(oh-oh)', 'Quiet now', 'Big finish']);+ expect(markers).toEqual([+ { type: 'section', label: 'Intro', kind: 'intro', line: 0 },+ { type: 'direction', label: 'Spoken, close', kind: 'spoken', line: 0 },+ { type: 'section', label: 'Pre-Chorus', kind: 'pre-chorus', line: 1 },+ { type: 'direction', label: 'Shouts', kind: 'shouted', line: 1 },+ { type: 'direction', label: 'Stop — silence', kind: 'silence', line: 3 },+ { type: 'section', label: 'Bridge', kind: 'bridge', line: 3 },+ { type: 'direction', label: 'stripped groove', kind: 'rhythm', line: 3 },+ { type: 'direction', label: 'Whispered spoken', kind: 'whispered', line: 3 },+ { type: 'direction', label: 'Stop-time', kind: 'hits', line: 4 },+ { type: 'section', label: 'Final Chorus', kind: 'chorus', line: 4 },+ { type: 'direction', label: 'full return', kind: 'note', line: 4 },+ { type: 'direction', label: 'Handclaps', kind: 'rhythm', line: 4 },+ { type: 'section', label: 'Outro', kind: 'outro', line: 5 },+ { type: 'direction', label: 'drums cut, spoken', kind: 'spoken', line: 5 },+ ]);+ });+it('honors an explicit format over detection', () => {expect(parseLyricCues('[00:01.00]stamped', 'text').cues).toEqual([{ text: '[00:01.00]stamped', startSec: null, endSec: null },diff --git a/server/services/musicVideo/trackLyrics.js b/server/services/musicVideo/trackLyrics.jsnew file mode 100644index 0000000000..2fd1b37255--- /dev/null+++ b/server/services/musicVideo/trackLyrics.js@@ -0,0 +1,48 @@+/**+ * Import the linked track's lyric sheet onto a Music Video project.+ *+ * A track in the music library carries the song's lyrics as a plain sheet+ * with `[Verse]`/`[Chorus]` headers and stage directions. The project needs+ * them as lyric cues (the sung lines) plus lyric markers (the structure), and+ * nothing else reads them off the track once the project exists. The+ * director's "Use track lyrics" button replaces the lines; the autopilot+ * kickoff imports only when the project has no lines, so a re-run never+ * overwrites lines the director edited.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { getTrack } from '../tracks/index.js';+import { getProject, updateProject } from './projects.js';+import { parseLyricCues } from './timedText.js';++export const MAX_LYRIC_CUES = 2000;++/**+ * @param {string} projectId+ * @param {{ mode?: 'replace' | 'if-empty' }} [options]+ * @returns {Promise<{ project: object, imported: number, markers: number, skipped: string|null }>}+ */+export async function importTrackLyrics(projectId, { mode = 'replace' } = {}) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const ifEmpty = mode === 'if-empty';+ const skip = (skipped) => ({ project, imported: 0, markers: 0, skipped });+ if (ifEmpty && (project.lyricCues || []).length > 0) return skip('has-lyrics');+ if (!project.trackId) {+ if (ifEmpty) return skip('no-track');+ throw new ServerError('Link a track from the music library first', { status: 400, code: 'NO_TRACK' });+ }+ const track = await getTrack(project.trackId);+ if (!track) throw new ServerError('Linked track not found', { status: 404, code: 'NOT_FOUND' });+ const { cues, markers } = parseLyricCues(typeof track.lyrics === 'string' ? track.lyrics : '');+ if (cues.length === 0) {+ if (ifEmpty) return skip('no-track-lyrics');+ throw new ServerError('The linked track has no lyrics', { status: 422, code: 'NO_TRACK_LYRICS' });+ }+ if (cues.length > MAX_LYRIC_CUES) {+ throw new ServerError(`A project holds at most ${MAX_LYRIC_CUES} lyric cues`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ const updated = await updateProject(project.id, { lyricCues: cues, lyricMarkers: markers });+ console.log(`🎼 Imported ${cues.length} track lyric lines (${markers.length} markers) into ${project.id}`);+ return { project: updated, imported: cues.length, markers: markers.length, skipped: null };+}diff --git a/server/services/musicVideo/vocalSeparation.js b/server/services/musicVideo/vocalSeparation.jsnew file mode 100644index 0000000000..e8e51916af--- /dev/null+++ b/server/services/musicVideo/vocalSeparation.js@@ -0,0 +1,250 @@+/**+ * Music Video vocal separation: split the project's song into an isolated+ * vocal with demucs (htdemucs_ft, two stems) and attach it as the project's+ * vocal stem.+ *+ * Runs only when the director clicks "Separate vocals" or starts an autopilot+ * run — never at boot. The first run provisions a private venv at+ * `~/.portos/venvs/demucs` (`python -m venv` + `pip install demucs soundfile`),+ * and demucs fetches its own weights on first use. Separation picks the best+ * device (Apple Silicon → mps, NVIDIA → cuda, otherwise cpu) and retries on the+ * CPU when the accelerator run fails. The result goes through the same+ * `attachVocalStem` as an uploaded stem, so the timebase check still applies+ * and the file lands in the shared music library like any other stem.+ *+ * Job shape mirrors audioMidiTranscription.js: kickoff returns `{ jobId }`,+ * the work runs detached and streams `{ type: 'progress' | 'complete' |+ * 'error' | 'canceled' }` frames. One job per project at a time — a second+ * kickoff re-attaches to the running one.+ */++import { randomUUID } from 'crypto';+import { existsSync } from 'fs';+import { mkdir, mkdtemp, readdir, rm } from 'fs/promises';+import { homedir, tmpdir } from 'os';+import { dirname, join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { shortId } from '../../lib/fileUtils.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';+import { runStreamingCommand } from '../../lib/streamingSpawn.js';+import { whichFirst } from '../../lib/processEnv.js';+import { getProject } from './projects.js';+import { attachVocalStem } from './vocalStem.js';++const IS_WIN = process.platform === 'win32';+const VENV_TIMEOUT_MS = 5 * 60 * 1000;+const PIP_TIMEOUT_MS = 45 * 60 * 1000;+const PROBE_TIMEOUT_MS = 2 * 60 * 1000;+const SEPARATE_TIMEOUT_MS = 60 * 60 * 1000;+// htdemucs_ft is a bag of four models; demucs draws one progress bar per model.+const DEMUCS_MODEL = 'htdemucs_ft';+const DEMUCS_PASSES = 4;++/** Where the demucs venv lives. `PORTOS_DEMUCS_VENV_DIR` overrides it. */+export const demucsVenvDir = () => process.env.PORTOS_DEMUCS_VENV_DIR || join(homedir(), '.portos', 'venvs', 'demucs');+export const venvPython = (dir) => (IS_WIN ? join(dir, 'Scripts', 'python.exe') : join(dir, 'bin', 'python'));++/** Best demucs device for this host. */+function pickDemucsDevice({ platform = process.platform, arch = process.arch, cudaAvailable = false } = {}) {+ if (platform === 'darwin' && arch === 'arm64') return 'mps';+ if (cudaAvailable) return 'cuda';+ return 'cpu';+}++function demucsArgs({ audioPath, outDir, device }) {+ return ['-m', 'demucs', '--two-stems=vocals', '-n', DEMUCS_MODEL, '-d', device, '-o', outDir, audioPath];+}++async function defaultBasePython() {+ const { classifyVenvBases } = await import('../../lib/pythonSetup.js');+ const { supported } = await classifyVenvBases().catch(() => ({ supported: [] }));+ return supported[0] || whichFirst(IS_WIN ? 'python' : 'python3');+}++async function defaultCudaAvailable() {+ if (process.platform === 'darwin') return false;+ const { getCudaCapability } = await import('../../lib/cudaCapability.js');+ return (await getCudaCapability().catch(() => null))?.status === 'available';+}++let provisioning = null;++async function provisionDemucs({ dir, python, onProgress, run, resolveBasePython }) {+ if (!existsSync(python)) {+ const base = await resolveBasePython();+ if (!base) {+ throw new ServerError('Separating vocals needs Python 3.10 or newer to install demucs. Install Python, then try again.', { status: 503, code: 'DEMUCS_PYTHON_MISSING' });+ }+ onProgress({ stage: 'provision', detail: 'Creating the demucs environment (first run only)' });+ console.log(`🐍 Creating demucs venv at ${dir}`);+ await mkdir(dirname(dir), { recursive: true });+ const made = await run(base, ['-m', 'venv', dir], null, { timeoutMs: VENV_TIMEOUT_MS });+ if (!made.success) {+ throw new ServerError(`Could not create the demucs environment: ${made.error}`, { status: 502, code: 'DEMUCS_INSTALL_FAILED' });+ }+ }+ onProgress({ stage: 'installing', detail: 'Installing demucs (first run only, a few minutes)' });+ console.log('📦 Installing demucs + soundfile into the demucs venv');+ let lines = 0;+ const installed = await run(python, ['-m', 'pip', 'install', 'demucs', 'soundfile'], (line) => {+ lines += 1;+ // One frame per new package line, not per progress redraw.+ if (/^(Collecting|Downloading|Installing|Successfully)/.test(line)) {+ onProgress({ stage: 'installing', detail: line.slice(0, 160) });+ if (lines % 10 === 0 || /^Successfully/.test(line)) console.log(`📦 demucs install: ${line.slice(0, 160)}`);+ }+ }, { timeoutMs: PIP_TIMEOUT_MS });+ if (!installed.success) {+ throw new ServerError(`Could not install demucs: ${installed.error}`, { status: 502, code: 'DEMUCS_INSTALL_FAILED' });+ }+}++/**+ * Interpreter of a working demucs venv, creating or repairing it when needed.+ * Concurrent callers share one install.+ */+async function ensureDemucsRuntime({ onProgress = () => {}, run = runStreamingCommand, resolveBasePython = defaultBasePython } = {}) {+ const dir = demucsVenvDir();+ const python = venvPython(dir);+ if (existsSync(python)) {+ const probe = await run(python, ['-c', 'import demucs, soundfile'], null, { timeoutMs: PROBE_TIMEOUT_MS });+ if (probe.success) return python;+ console.warn(`⚠️ demucs venv at ${dir} cannot import demucs — reinstalling its packages`);+ }+ if (!provisioning) {+ provisioning = provisionDemucs({ dir, python, onProgress, run, resolveBasePython }).finally(() => { provisioning = null; });+ }+ await provisioning;+ return python;+}++async function findVocals(dir) {+ const entries = await readdir(dir, { withFileTypes: true, recursive: true }).catch(() => []);+ const hit = entries.find((entry) => entry.isFile() && entry.name === 'vocals.wav');+ return hit ? join(hit.parentPath ?? hit.path, hit.name) : null;+}++/** Overall percent across demucs's per-model progress bars. */+function createDemucsProgress(passes = DEMUCS_PASSES) {+ let pass = 0;+ let last = -1;+ return (line) => {+ const match = String(line).match(/(\d{1,3})%\|/);+ if (!match) return null;+ const pct = Math.min(100, Number(match[1]));+ if (pct < last) pass = Math.min(passes - 1, pass + 1);+ last = pct;+ return Math.min(100, Math.round((pass * 100 + pct) / passes));+ };+}++const audioSourceKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uploadedAudioFilename ?? ''}`;+const stemName = (project) => `${String(project?.name || 'music-video').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'music-video'}-vocals.wav`;++// jobId -> job; projectId -> running jobId+const separationJobs = new Map();+const activeByProject = new Map();++export const attachVocalSeparationSseClient = (jobId, res) => attachSse(separationJobs, jobId, res);++export function cancelVocalSeparation(jobId) {+ const job = separationJobs.get(jobId);+ if (!job || job.settled) return false;+ job.cancelRequested = true;+ return true;+}++const canceledRun = () => Object.assign(new Error('cancelled'), { canceled: true });++/**+ * Start separating a project's song. Resolves `{ jobId }` (plus+ * `reused: true` when a separation for this project is already running).+ * Throws before a job exists when the project or its audio is missing.+ */+export async function startVocalSeparation(projectId, { deps = {} } = {}) {+ const d = {+ getProject,+ attachVocalStem,+ resolveMaster: async (project) => (await import('./render.js')).resolveMasterAudioPath(project),+ run: runStreamingCommand,+ resolveBasePython: defaultBasePython,+ cudaAvailable: defaultCudaAvailable,+ ...deps,+ };+ const project = await d.getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const running = activeByProject.get(projectId);+ if (running && separationJobs.get(running) && !separationJobs.get(running).settled) {+ return { jobId: running, reused: true };+ }+ const audioPath = await d.resolveMaster(project);+ const jobId = randomUUID();+ const job = { id: jobId, clients: [], settled: false, cancelRequested: false };+ separationJobs.set(jobId, job);+ activeByProject.set(projectId, jobId);+ console.log(`🎙️ Vocal separation ${shortId(jobId)} started for ${projectId}`);++ (async () => {+ let outDir = null;+ const progress = (frame) => broadcastSse(job, { type: 'progress', ...frame });+ const checkCancel = () => { if (job.cancelRequested) throw canceledRun(); };+ try {+ progress({ stage: 'preparing' });+ const python = await ensureDemucsRuntime({ onProgress: progress, run: d.run, resolveBasePython: d.resolveBasePython });+ checkCancel();+ outDir = await mkdtemp(join(tmpdir(), 'portos-demucs-'));+ const separate = (device) => {+ const toPercent = createDemucsProgress();+ let lastPercent = -1;+ progress({ stage: 'separating', detail: `Separating vocals on ${device}`, percent: 0 });+ return d.run(python, demucsArgs({ audioPath, outDir, device }), (line) => {+ const percent = toPercent(line);+ if (percent == null || percent === lastPercent) return;+ lastPercent = percent;+ progress({ stage: 'separating', detail: `Separating vocals on ${device}`, percent });+ }, {+ timeoutMs: SEPARATE_TIMEOUT_MS,+ splitRe: /[\r\n]+/,+ env: { ...process.env, PYTORCH_ENABLE_MPS_FALLBACK: '1' },+ isCancelled: () => job.cancelRequested,+ });+ };+ const device = pickDemucsDevice({ cudaAvailable: await d.cudaAvailable() });+ let result = await separate(device);+ checkCancel();+ if (!result.success && device !== 'cpu') {+ console.warn(`⚠️ demucs on ${device} failed (${result.error}) — retrying on cpu`);+ result = await separate('cpu');+ checkCancel();+ }+ if (!result.success) {+ throw new ServerError(`demucs could not separate the vocals: ${result.error}`, { status: 502, code: 'DEMUCS_FAILED' });+ }+ const vocals = await findVocals(outDir);+ if (!vocals) throw new ServerError('demucs finished but wrote no vocals.wav', { status: 502, code: 'DEMUCS_FAILED' });+ const current = await d.getProject(projectId);+ if (!current || audioSourceKey(current) !== audioSourceKey(project)) {+ throw new ServerError('The project\'s song changed while the vocals were separating. Run Separate vocals again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });+ }+ progress({ stage: 'attaching', percent: 100 });+ const updated = await d.attachVocalStem(projectId, { tempPath: vocals, originalName: stemName(project) });+ console.log(`✅ Vocal separation ${shortId(jobId)} attached ${updated?.vocalStemFilename} to ${projectId}`);+ broadcastSse(job, { type: 'complete', project: updated });+ } catch (err) {+ if (err?.canceled || job.cancelRequested) {+ console.log(`🛑 Vocal separation ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ } else {+ console.error(`❌ Vocal separation ${shortId(jobId)} failed: ${err?.message || err}`);+ broadcastSse(job, { type: 'error', error: err?.message || String(err), ...(err?.code ? { code: err.code } : {}) });+ }+ } finally {+ job.settled = true;+ if (activeByProject.get(projectId) === jobId) activeByProject.delete(projectId);+ if (outDir) await rm(outDir, { recursive: true, force: true }).catch(() => {});+ closeJobAfterDelay(separationJobs, jobId);+ }+ })();++ return { jobId };+}