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
[issue-1760] Music Video render: scene clips over a master audio bed (Phase 2)
Adam Eivy5d5fea594f71
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bc430c1b99..0ce8fee6ab 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -27,6 +27,7 @@## Music Video production mode+- **[issue-1760] Render the finished music video — scene clips over the track as one master audio bed (Phase 2).** The director board can now turn its per-scene clips into a single MP4: a new **Render** button assembles every scene that has a generated video, in order, and lays the project's track underneath as the **master audio bed** (the per-clip generated audio is dropped — a music video plays one continuous song, not each shot's audio). Render progress streams live as a percentage with a Cancel option, and when it finishes a "View rendered music video" link drops you into Media History. When the project has a cached beat analysis, each cut is **lightly snapped to the nearest beat** (trimming a clip slightly so the edit lands on the music — never stretching it), so the result feels cut-to-the-beat even before the full beat-quantized arranger lands. The render reuses the existing ffmpeg pipeline and ends on the shorter of video/track, so it never runs past the song. (`server/services/musicVideo/render.js`, `server/routes/musicVideo.js`, `client/src/pages/MusicVideo.jsx`, `client/src/services/apiMusicVideo.js`)- **[issue-1760] Groundwork: offline beat/tempo/section analysis of an audio track (Phase 0 spike).** The first slice of the planned Music Video production mode proves the riskiest unknown — that a music track's BPM, beat grid, 4/4 downbeats, and a coarse section map can be extracted **fully offline with no new dependency**, using only ffmpeg (already required) plus a pure-JS DSP core (onset-strength envelope → tempo-weighted autocorrelation → beat-phase fit → energy-novelty sections). No Python, no ML model download, no network — so it runs the same in CI and on every install. There's no user-facing surface yet; this is the analyzer the upcoming director scene board and beat-snapped render build on. (`server/services/musicVideo/audioAnalysis.js`)- **[issue-1760] Director scene board: create a Music Video project, analyze its track, and storyboard beat-aligned scenes (Phase 1).** Builds the first user-facing surface on top of the Phase 0 analyzer: a new **Create → Music Video** page (also reachable via `⌘K` and voice) where you pick an existing track (or name an uploaded audio file), create a project, and run the offline analyzer with one click — the detected BPM, beat/downbeat counts, and section map render inline. From there you storyboard the video as an ordered list of **scenes**, each with a label, a start/end time, a beat-aligned flag, and image/frame prompts; scenes can be added, edited (blur-to-save), reordered, and removed. Projects persist through a db-primary store (PostgreSQL `music_video_projects` with a file-backend fallback for dev/test), mirroring the creative-director pattern with soft-delete tombstones and LWW timestamps. Cross-machine federation of projects, per-scene reference-frame/image generation + image-to-video, and the beat-snapped render with a master audio bed are filed as follow-ups on #1760. (`server/services/musicVideo/`, `server/routes/musicVideo.js`, `server/lib/musicVideoValidation.js`, `client/src/pages/MusicVideo.jsx`, `client/src/services/apiMusicVideo.js`)- **[issue-1770] Music Video projects now sync across your federated machines.** Phase 1 shipped the project store as local-only; it now federates over the same peer-sync pipeline your other creative records use. A new **Music Video** toggle on the Instances page enables it per peer — when on, creating, editing, reordering scenes on, or deleting a project on one machine propagates to the others, with newest-edit-wins conflict resolution and deletions that an out-of-date peer can't resurrect. Conflicting edits are surfaced in the Conflicts UI for restore. Referenced media (the uploaded audio track and rendered scene clips) is not bundled in this phase and is tracked as a follow-up. (Closes #1770)diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 0de5d61488..ec737fe9d1 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -11,11 +11,15 @@ import {updateMusicVideoScene,deleteMusicVideoScene,reorderMusicVideoScenes,+ renderMusicVideoProject,+ musicVideoRenderEventsUrl,+ cancelMusicVideoRender,} from '../services/apiMusicVideo.js';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import { listTracks } from '../services/apiTracks.js';import useSceneRenderLifecycle from '../hooks/useSceneRenderLifecycle.js';+import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress.js';import { formatDurationSec } from '../utils/formatters.js';const MODES = ['director', 'autonomous'];@@ -122,6 +126,67 @@ export default function MusicVideo() {.finally(() => setAnalyzing(false));};+ // --- Render (#1760, Phase 2): assemble scene clips over the master audio bed.+ // The kickoff returns a jobId; progress streams over SSE via useSseProgress.+ const [render, setRender] = useState(null); // { jobId, projectId } while in flight+ const renderSse = useSseProgress(render ? musicVideoRenderEventsUrl(render.jobId) : null);+ const renderProgress = render ? Math.round((renderSse.latest?.progress ?? 0) * 100) : 0;+ // The number of scenes that already have a generated clip — the render's inputs.+ const renderableSceneCount = (selected?.scenes || []).filter((s) => s.videoHistoryId).length;++ // React to terminal SSE frames: record the render on the project, surface the+ // outcome, and clear the in-flight job. Functional update keys on the captured+ // projectId so a project switch mid-render can't misattribute the result.+ useEffect(() => {+ const frame = renderSse.latest;+ if (!render || !frame) return;+ if (frame.type === 'complete') {+ const result = frame.result || {};+ setProjects((prev) => prev.map((p) => (p.id === render.projectId+ ? { ...p, renderHistoryId: result.id || p.renderHistoryId, status: 'complete' } : p)));+ toast.success('Music video rendered');+ setRender(null);+ } else if (frame.type === 'error') {+ toast.error(frame.error || 'Render failed');+ setProjects((prev) => prev.map((p) => (p.id === render.projectId ? { ...p, status: 'failed' } : p)));+ setRender(null);+ } else if (frame.type === 'canceled' || frame.type === 'cancelled') {+ toast.info('Render cancelled');+ setRender(null);+ }+ }, [renderSse.latest]);+ // Stream closed on a NON-terminal frame (server restart mid-render, or the job+ // was pruned before/after attach so the 404 closes the stream) — recover so the+ // spinner can't hang. Gating on `!latest` is wrong: `latest` holds the last+ // *progress* frame once any progress streamed, so it would never fire. Mirror+ // VideoTimelineEditor: recover whenever the final frame isn't terminal.+ useEffect(() => {+ if (render && renderSse.closed && !isTerminalSseFrame(renderSse.latest)) {+ setRender(null);+ toast.info('Lost connection to the render — check Media History for the result');+ }+ }, [renderSse.closed]);++ const handleRender = () => {+ if (!selected) return;+ const projectId = selected.id;+ renderMusicVideoProject(projectId, { silent: true })+ .then(({ jobId }) => setRender({ jobId, projectId }))+ .catch((err) => {+ // 409 → a render is already in flight for this project; attach to it.+ if (err?.status === 409 && err?.context?.jobId) {+ setRender({ jobId: err.context.jobId, projectId });+ return;+ }+ toast.error(err?.message || 'Failed to start render');+ });+ };++ const handleCancelRender = () => {+ if (!render) return;+ cancelMusicVideoRender(render.jobId, { silent: true }).catch(() => {});+ };+const handleAddScene = () => {addMusicVideoScene(selected.id, { prompt: '' }).then((scene) => replaceProject({ ...selected, scenes: [...(selected.scenes || []), scene] }))@@ -297,12 +362,39 @@ export default function MusicVideo() {className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50"><Activity size={15} /> {analyzing ? 'Analyzing…' : 'Analyze'}</button>+ {render ? (+ <button onClick={handleCancelRender} title="Cancel render"+ className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">+ <Activity size={15} className="animate-spin" /> {renderProgress}% · Cancel+ </button>+ ) : (+ <button onClick={handleRender} disabled={renderableSceneCount === 0}+ title={renderableSceneCount === 0 ? 'Generate at least one scene video first' : 'Render the music video over the track'}+ className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">+ <Film size={15} /> Render+ </button>+ )}<button onClick={() => handleDelete(selected.id)} title="Delete project"className="flex items-center gap-1 text-port-error border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0"><Trash2 size={15} /></button></div></div>+ {render && (+ <div className="mt-2">+ <div className="h-1.5 bg-port-bg rounded overflow-hidden">+ <div className="h-full bg-port-accent transition-all" style={{ width: `${renderProgress}%` }} />+ </div>+ <p className="text-xs text-port-text-muted mt-1">Rendering music video — {renderProgress}%</p>+ </div>+ )}+ {!render && selected.renderHistoryId && (+ <div className="mt-2 text-xs flex items-center gap-2">+ <Film size={14} className="text-port-success" />+ <a href={`/media/history?preview=${encodeURIComponent(`video:${selected.renderHistoryId}`)}`}+ className="text-port-accent">View rendered music video →</a>+ </div>+ )}{selected.audioAnalysis && (<div className="text-xs text-port-text-muted mt-2 flex flex-wrap gap-x-4 gap-y-1"><span>Tempo: {selected.audioAnalysis.bpm ? `${selected.audioAnalysis.bpm} BPM` : '—'}</span>diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxnew file mode 100644index 0000000000..f67984c05c--- /dev/null+++ b/client/src/pages/MusicVideo.test.jsx@@ -0,0 +1,82 @@+/**+ * Focused tests for the music-video Render control (#1760 Phase 2): the button+ * gates on a scene having a generated clip, and clicking it kicks off the render.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';++const PROJECT_WITH_CLIP = {+ id: 'mv-1', name: 'Neon Run', mode: 'director', status: 'ready',+ trackId: 't1', uploadedAudioFilename: null, audioAnalysis: null, renderHistoryId: null,+ scenes: [{ sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img1', videoHistoryId: 'h1' }],+};+const PROJECT_NO_CLIP = {+ ...PROJECT_WITH_CLIP, id: 'mv-2', name: 'No Clips',+ scenes: [{ sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img1', videoHistoryId: null }],+};++const { sseState } = vi.hoisted(() => ({ sseState: { latest: null, closed: false, frames: [], isOpen: false } }));++vi.mock('../services/apiMusicVideo.js', () => ({+ listMusicVideoProjects: vi.fn(async () => []),+ createMusicVideoProject: vi.fn(),+ deleteMusicVideoProject: vi.fn(),+ analyzeMusicVideoProject: vi.fn(),+ addMusicVideoScene: vi.fn(),+ updateMusicVideoScene: vi.fn(),+ deleteMusicVideoScene: vi.fn(),+ reorderMusicVideoScenes: vi.fn(),+ renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),+ musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,+ cancelMusicVideoRender: vi.fn(async () => ({ ok: true })),+}));+vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));+vi.mock('../services/apiImageVideo.js', () => ({ generateVideo: vi.fn() }));+vi.mock('../services/apiTracks.js', () => ({ listTracks: vi.fn(async () => []) }));+vi.mock('../hooks/useSceneRenderLifecycle.js', () => ({+ default: () => ({ genScenes: {}, startScene: vi.fn(), clearScene: vi.fn(), trackJob: vi.fn() }),+}));+vi.mock('../hooks/useSseProgress.js', () => ({ useSseProgress: () => sseState }));+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));+vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{title}</div> }));++import MusicVideo from './MusicVideo.jsx';+import { listMusicVideoProjects, renderMusicVideoProject } from '../services/apiMusicVideo.js';++const openProject = async (project) => {+ listMusicVideoProjects.mockResolvedValue([project]);+ render(<MusicVideo />);+ // Project list button appears, then select it to open the board.+ const btn = await screen.findByRole('button', { name: new RegExp(project.name) });+ fireEvent.click(btn);+};++beforeEach(() => {+ vi.clearAllMocks();+ sseState.latest = null;+ sseState.closed = false;+});++describe('MusicVideo render control (#1760)', () => {+ it('enables Render and kicks off the job when a scene has a clip', async () => {+ await openProject(PROJECT_WITH_CLIP);+ const renderBtn = await screen.findByRole('button', { name: /^Render$/ });+ expect(renderBtn).toHaveProperty('disabled', false);++ fireEvent.click(renderBtn);+ await waitFor(() => expect(renderMusicVideoProject).toHaveBeenCalledWith('mv-1', { silent: true }));+ });++ it('disables Render when no scene has a generated clip', async () => {+ await openProject(PROJECT_NO_CLIP);+ const renderBtn = await screen.findByRole('button', { name: /^Render$/ });+ expect(renderBtn).toHaveProperty('disabled', true);+ });++ it('shows the rendered-video link once a project carries a renderHistoryId', async () => {+ await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' });+ const link = await screen.findByText(/View rendered music video/i);+ // Media History matches video items by their `video:<id>` key via ?preview=.+ expect(link.closest('a').getAttribute('href')).toContain('preview=video%3Arh-9');+ });+});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 30c947da01..a7fe33ae3d 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -38,3 +38,16 @@ export const reorderMusicVideoScenes = (id, sceneIds, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/scenes/reorder`, {method: 'POST', body: JSON.stringify({ sceneIds }), ...options,});++// ---- Render (#1760, Phase 2) ----+// Kick off the master-bed render; resolves to { jobId }. Progress streams over+// the SSE URL below (subscribe with useSseProgress). cancel stops an in-flight job.+export const renderMusicVideoProject = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/render`, { method: 'POST', ...options });++// EventSource URL for a render job's progress stream (consumed by useSseProgress).+export const musicVideoRenderEventsUrl = (jobId) =>+ `/api/music-video/render/${encodeURIComponent(jobId)}/events`;++export const cancelMusicVideoRender = (jobId, options = {}) =>+ request(`/music-video/render/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 2597cefe9b..bcca1a1a2b 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -33,6 +33,7 @@ import {reorderProjectScenes,} from '../services/musicVideo/projects.js';import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';+import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';import { getTrack } from '../services/tracks/index.js';const router = Router();@@ -99,6 +100,25 @@ router.post('/:id/analyze', asyncHandler(async (req, res) => {res.json(updated);}));+// --- Render (#1760, Phase 2) ---+// Assemble the scenes' i2v clips into one MP4 over the track as the master audio+// bed. Kickoff returns { jobId }; progress streams over SSE (mirrors+// videoTimeline). Per-project mutex returns 409 with the live jobId for re-attach.+router.post('/:id/render', asyncHandler(async (req, res) => {+ res.json(await renderMusicVideo(req.params.id));+}));++// SSE progress stream for a render job. Two-segment path — distinct from the+// one-segment GET /:id project read, so it can't shadow it.+router.get('/render/:jobId/events', (req, res) => {+ const ok = attachRenderSseClient(req.params.jobId, res);+ if (!ok) throw new ServerError('Render job not found or expired', { status: 404, code: 'NOT_FOUND' });+});++router.post('/render/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelRender(req.params.jobId) });+});+// --- Director scene board ---router.post('/:id/scenes', asyncHandler(async (req, res) => {diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 85d599ffa4..e3378689ef 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -23,9 +23,18 @@ vi.mock('../services/tracks/index.js', () => ({getTrack: vi.fn(),}));+// Mock the render service so the route test doesn't pull the real ffmpeg/+// video-history/spawn graph; the route's job is to dispatch + stream.+vi.mock('../services/musicVideo/render.js', () => ({+ renderMusicVideo: vi.fn(async () => ({ jobId: 'job-1' })),+ attachRenderSseClient: vi.fn(() => true),+ cancelRender: vi.fn(() => true),+}));+import * as svc from '../services/musicVideo/projects.js';import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';import { getTrack } from '../services/tracks/index.js';+import * as renderSvc from '../services/musicVideo/render.js';import musicVideoRoutes from './musicVideo.js';describe('musicVideo routes', () => {@@ -158,4 +167,32 @@ describe('musicVideo routes', () => {expect(r.status).toBe(400);});});++ describe('render (#1760 Phase 2)', () => {+ it('POST /:id/render kicks off the render and returns the jobId', async () => {+ const r = await request(app).post('/api/music-video/mv-1/render').send({});+ expect(r.status).toBe(200);+ expect(renderSvc.renderMusicVideo).toHaveBeenCalledWith('mv-1');+ expect(r.body).toEqual({ jobId: 'job-1' });+ });++ it('POST /:id/render does not collide with /:id/scenes', async () => {+ await request(app).post('/api/music-video/mv-1/render').send({});+ // The render handler ran, not the scene handler.+ expect(svc.addProjectScene).not.toHaveBeenCalled();+ });++ it('POST /render/:jobId/cancel cancels the job', async () => {+ const r = await request(app).post('/api/music-video/render/job-1/cancel').send({});+ expect(r.status).toBe(200);+ expect(renderSvc.cancelRender).toHaveBeenCalledWith('job-1');+ expect(r.body).toEqual({ ok: true });+ });++ it('GET /render/:jobId/events 404s for an unknown job', async () => {+ renderSvc.attachRenderSseClient.mockReturnValueOnce(false);+ const r = await request(app).get('/api/music-video/render/nope/events');+ expect(r.status).toBe(404);+ });+ });});diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsnew file mode 100644index 0000000000..7c88853e4a--- /dev/null+++ b/server/services/musicVideo/render.js@@ -0,0 +1,374 @@+/**+ * Music Video — render pipeline (#1760, Phase 2).+ *+ * Assembles a project's per-scene i2v clips (each a `videoHistoryId` entry the+ * scene-video hook filed) into a single MP4 laid under the project's source+ * track as the **master audio bed** — the music video's defining shape: one+ * music track under all clips, the per-clip generated audio dropped. Mirrors+ * videoTimeline's SSE render runner (job map, ffmpeg `-progress` parsing, the+ * shared sseUtils broadcast), but its ffmpeg graph concats video-only and maps+ * one external audio input as the sole output audio, ended on `-shortest` so the+ * render runs only as long as the shorter of (video, track).+ *+ * Lightweight beat-snap: when the project carries a cached beat analysis, each+ * cut is trimmed back to the nearest beat (never extended — a clip can't grow),+ * so cuts land on the music. With no analysis the clips render at their natural+ * length. The full beat-quantized arranger is a follow-up.+ */++import { spawn } from 'child_process';+import { existsSync } from 'fs';+import { unlink } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { ensureDir, PATHS } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';+import { findFfmpeg, safeUnder, generateThumbnail, probeVideoDuration } from '../../lib/ffmpeg.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';+import { loadHistory, saveHistory } from '../videoGen/local.js';+import { getTrack } from '../tracks/index.js';+import { getProject, updateProject } from './projects.js';++// Per-project render mutex (keyed by projectId so two projects can render in+// parallel; same-project re-entry returns 409 with the live jobId for re-attach).+const jobs = new Map();+const projectRenders = new Map();+// Reserved synchronously the instant a render is accepted, BEFORE the async+// prep (ffmpeg/audio/clip resolution) — so a double-click or second client+// can't pass the 409 check during that await window and spawn a duplicate.+const PENDING = Symbol('mv-render-pending');++// Serialize the read-modify-write of the shared video-history file across renders.+// The per-project mutex above deliberately lets two DIFFERENT projects render (and+// finalize) in parallel, but each finalizer does loadHistory→unshift→saveHistory and+// saveHistory is a bare atomicWrite (the normal video-gen pipeline only avoids this+// race because mediaJobQueue serializes it to one GPU lane — this renderer bypasses+// that queue). Two overlapping finalize windows would otherwise drop one project's+// entry, leaving its "View rendered music video" deep link pointing at a 404. One+// module-level tail collapses every history append onto a single lane.+let historyWriteTail = Promise.resolve();+function appendToVideoHistory(meta) {+ const run = historyWriteTail.then(async () => {+ const loaded = await loadHistory();+ const history = Array.isArray(loaded) ? loaded : [];+ history.unshift(meta);+ await saveHistory(history);+ });+ historyWriteTail = run.catch(() => {}); // keep the lane alive even if one append throws+ return run;+}++export const attachRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res);++export function getRenderJobStatus(jobId) {+ const job = jobs.get(jobId);+ if (!job) return null;+ return { status: job.status, error: job.lastError };+}++export function cancelRender(jobId) {+ const job = jobs.get(jobId);+ if (!job || !job.process) return false;+ const proc = job.process;+ proc.kill('SIGTERM');+ setTimeout(() => {+ if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {+ console.log(`⚠️ music-video render didn't exit on SIGTERM — escalating to SIGKILL`);+ proc.kill('SIGKILL');+ }+ }, 8000);+ return true;+}++// Resolve the project's source audio to a verified path under data/music/.+// Mirrors the route's resolveAudioPath (track or uploaded file, safe basename).+export async function resolveMasterAudioPath(project) {+ let filename = null;+ if (project.trackId) {+ const track = await getTrack(project.trackId);+ if (!track) throw new ServerError('Linked track not found', { status: 404, code: 'NOT_FOUND' });+ filename = track.audioFilename;+ } else if (project.uploadedAudioFilename) {+ filename = project.uploadedAudioFilename;+ }+ if (!filename) {+ throw new ServerError('Project has no audio — set a track or upload audio first', { status: 400, code: 'NO_AUDIO' });+ }+ const safe = safeUnder(PATHS.music, filename);+ if (!safe || !existsSync(safe)) {+ throw new ServerError('Project audio file is missing', { status: 404, code: 'AUDIO_MISSING' });+ }+ return safe;+}++// Resolve every scene that has a generated i2v clip (`videoHistoryId`) to a+// verified on-disk path + dims, in scene order. Scenes without a clip yet are+// skipped (not an error — they're just not rendered). A scene whose clip id+// references a missing history entry/file IS an error (404, listed).+export async function resolveSceneClips(project) {+ const scenes = (Array.isArray(project.scenes) ? project.scenes : [])+ .slice()+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))+ .filter((s) => s && s.videoHistoryId);+ if (scenes.length === 0) {+ throw new ServerError('No scene videos to render — generate at least one scene clip first', {+ status: 400, code: 'NO_SCENE_CLIPS',+ });+ }+ const history = await loadHistory();+ const historyMap = new Map((Array.isArray(history) ? history : []).map((h) => [h.id, h]));+ const missing = [];+ const clips = [];+ for (const scene of scenes) {+ const entry = historyMap.get(scene.videoHistoryId);+ const videoPath = entry && entry.filename ? safeUnder(PATHS.videos, entry.filename) : null;+ if (!entry || !videoPath || !existsSync(videoPath)) { missing.push(scene.videoHistoryId); continue; }+ const duration = entry.numFrames && entry.fps ? entry.numFrames / entry.fps : null;+ if (!duration || duration <= 0) { missing.push(scene.videoHistoryId); continue; }+ clips.push({+ sceneId: scene.sceneId,+ videoPath,+ width: entry.width,+ height: entry.height,+ fps: entry.fps || 24,+ duration,+ inSec: 0,+ outSec: duration,+ });+ }+ if (missing.length > 0) {+ throw new ServerError(`Missing source clips for ${missing.length} scene(s)`, {+ status: 404, code: 'MISSING_CLIPS', context: { missingClipIds: missing },+ });+ }+ return clips;+}++// Pure: trim each clip's out-point so its cumulative cut lands on the nearest+// analyzed beat, when one is within `toleranceSec` and the trim keeps the clip+// at least `minClipSec` long. Snapping only ever SHORTENS a clip (a clip can't+// be extended past its rendered length), so a cut can move earlier onto a beat+// but never later. Returns a NEW clips array with adjusted `outSec`/`duration`.+// With no beats (no analysis) the clips are returned unchanged.+export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec = 0.4 } = {}) {+ const grid = Array.isArray(beats) ? beats.filter((b) => typeof b === 'number' && b >= 0).sort((a, b) => a - b) : [];+ if (grid.length === 0) return clips.map((c) => ({ ...c }));+ let running = 0;+ return clips.map((clip) => {+ const naturalEnd = running + clip.duration;+ // Nearest beat at or before the natural end (snap trims, never extends).+ let best = null;+ for (const beat of grid) {+ if (beat > naturalEnd) break;+ best = beat;+ }+ let outSec = clip.outSec;+ if (best != null+ && (naturalEnd - best) <= toleranceSec+ && (best - running) >= minClipSec) {+ outSec = best - running; // trim relative to the clip's own start (inSec=0)+ running = best;+ } else {+ running = naturalEnd;+ }+ return { ...clip, inSec: 0, outSec, duration: outSec };+ });+}++// Pure: build the ffmpeg args for the master-bed render. Concats the clips+// video-only (each scaled/padded to the canonical dims + fps and trimmed to its+// snapped out-point) and maps ONE external audio input as the sole output audio.+// `-shortest` ends the output at the shorter of (concatenated video, track).+export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null } = {}) {+ if (!Array.isArray(clips) || clips.length === 0) throw new Error('buildMusicVideoFfmpegArgs: empty clips');+ const canonW = clips[0].width;+ const canonH = clips[0].height;+ const fps = clips[0].fps || 24;++ const inputs = [];+ for (const c of clips) inputs.push('-i', c.videoPath);+ const audioIdx = clips.length; // master audio is the last input+ inputs.push('-i', audioPath);++ const filters = [];+ const vStreams = [];+ for (let i = 0; i < clips.length; i++) {+ const c = clips[i];+ filters.push(+ `[${i}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,`+ + `pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},`+ + `trim=start=${c.inSec}:end=${c.outSec},setpts=PTS-STARTPTS[v${i}]`,+ );+ vStreams.push(`[v${i}]`);+ }+ filters.push(`${vStreams.join('')}concat=n=${clips.length}:v=1:a=0[outv]`);++ const videoTotal = clips.reduce((s, c) => s + (c.outSec - c.inSec), 0);+ const totalDuration = audioDurationSec != null ? Math.min(videoTotal, audioDurationSec) : videoTotal;++ const args = [+ ...inputs,+ '-filter_complex', filters.join(';'),+ '-map', '[outv]',+ '-map', `${audioIdx}:a`,+ '-c:v', 'libx264',+ '-preset', 'veryfast',+ '-crf', '18',+ '-pix_fmt', 'yuv420p',+ '-c:a', 'aac',+ '-b:a', '192k',+ '-shortest',+ '-movflags', '+faststart',+ '-progress', 'pipe:2',+ '-y',+ outputPath,+ ];+ return { args, totalDuration, canonW, canonH, fps };+}++export async function renderMusicVideo(projectId) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });++ const existingJob = projectRenders.get(projectId);+ if (existingJob && (existingJob === PENDING || jobs.has(existingJob))) {+ throw new ServerError('Render already in progress for this project', {+ status: 409, code: 'RENDER_IN_PROGRESS', context: { jobId: existingJob === PENDING ? null : existingJob },+ });+ }+ // Reserve the slot SYNCHRONOUSLY (no await between the check above and here)+ // so a concurrent same-project start can't slip through during prep. Released+ // in the `finally` below if prep throws or we never reach the spawn handoff.+ projectRenders.set(projectId, PENDING);++ let handedOff = false;+ try {+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });++ const audioPath = await resolveMasterAudioPath(project);+ const rawClips = await resolveSceneClips(project);+ const audioDurationSec = await probeVideoDuration(audioPath).catch(() => null);+ const beats = project.audioAnalysis?.beats;+ const clips = beatSnapClips(rawClips, beats);+ await ensureDir(PATHS.videos);+ await ensureDir(PATHS.videoThumbnails);++ const jobId = randomUUID();+ const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;+ const outputPath = join(PATHS.videos, filename);+ const { args, totalDuration, canonW, canonH, fps } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec });++ const job = { id: jobId, projectId, status: 'running', clients: [], process: null, totalDuration };+ jobs.set(jobId, job);+ projectRenders.set(projectId, jobId);+ handedOff = true; // the job lifecycle now owns the projectRenders entry++ // Capture the pre-render status so a cancel restores it rather than blindly+ // downgrading a previously-'complete' project to 'ready'. Fall back to 'ready'+ // if it was somehow already 'rendering'.+ const priorStatus = project.status && project.status !== 'rendering' ? project.status : 'ready';+ // Mark the project rendering so the board reflects an in-flight render even+ // on a client that didn't initiate it (federates via emitRecordUpdated).+ await updateProject(projectId, { status: 'rendering' }).catch(() => {});++ console.log(`🎬 Rendering music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} duration=${totalDuration.toFixed(2)}s`);++ const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'ignore', 'pipe'] });+ job.process = proc;++ let stderrBuf = '';+ proc.stderr.on('data', (chunk) => {+ stderrBuf += chunk.toString();+ const lines = stderrBuf.split('\n');+ stderrBuf = lines.pop();+ for (const raw of lines) {+ const line = raw.trim();+ const eq = line.indexOf('=');+ if (eq <= 0) continue;+ const key = line.slice(0, eq);+ const val = line.slice(eq + 1);+ if (key === 'out_time_us') {+ const us = parseInt(val, 10);+ if (Number.isFinite(us) && totalDuration > 0) {+ broadcastSse(job, { type: 'progress', progress: Math.min(1, (us / 1_000_000) / totalDuration) });+ }+ } else if (key === 'progress' && val === 'end') {+ broadcastSse(job, { type: 'progress', progress: 1 });+ }+ }+ });++ proc.on('error', async (err) => {+ job.status = 'error';+ const reason = `Failed to spawn ffmpeg: ${err.message}`;+ job.lastError = reason;+ console.log(`❌ Music-video render spawn error [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: reason });+ projectRenders.delete(projectId);+ await updateProject(projectId, { status: 'failed' }).catch(() => {});+ closeJobAfterDelay(jobs, jobId);+ });++ proc.on('close', async (code, signal) => {+ job.process = null;+ if (code !== 0) {+ const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';+ job.status = canceled ? 'canceled' : 'error';+ const reason = canceled ? 'Render cancelled' : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;+ job.lastError = reason;+ console.log(`${canceled ? '🛑' : '❌'} Music-video render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);+ await unlink(outputPath).catch(() => {});+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });+ projectRenders.delete(projectId);+ // A cancel restores the pre-render status (so a cancelled re-render of a+ // 'complete' project stays 'complete'); a real failure marks it 'failed'.+ await updateProject(projectId, { status: canceled ? priorStatus : 'failed' }).catch(() => {});+ closeJobAfterDelay(jobs, jobId);+ return;+ }+ // Success finalization runs in an event callback (no request to bubble to)+ // — a throw in thumbnailing/history I/O would otherwise leave the project+ // stuck 'rendering' and projectRenders un-cleared (every later render 409s).+ // Wrap it so any failure still emits a terminal frame and releases the slot.+ try {+ job.status = 'complete';+ const thumb = await generateThumbnail(outputPath, jobId);+ const meta = {+ id: jobId,+ prompt: `Music Video: ${project.name}`,+ modelId: 'music-video',+ seed: 0,+ width: canonW,+ height: canonH,+ numFrames: Math.round(totalDuration * (fps || 24)),+ fps: fps || 24,+ filename,+ thumbnail: thumb,+ createdAt: new Date().toISOString(),+ musicVideoProjectId: projectId,+ };+ await appendToVideoHistory(meta);+ await updateProject(projectId, { renderHistoryId: jobId, status: 'complete' }).catch(() => {});+ console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);+ broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });+ } catch (err) {+ job.status = 'error';+ job.lastError = `Finalize failed: ${err.message}`;+ console.error(`❌ Music-video render finalize failed [${jobId.slice(0, 8)}]: ${err.message}`);+ broadcastSse(job, { type: 'error', error: 'Render finalize failed' });+ await updateProject(projectId, { status: 'failed' }).catch(() => {});+ } finally {+ projectRenders.delete(projectId);+ closeJobAfterDelay(jobs, jobId);+ }+ });++ return { jobId };+ } finally {+ // Prep threw (or we never handed off to the job lifecycle) — release the+ // reserved slot so a stale PENDING can't 409 every future render.+ if (!handedOff) projectRenders.delete(projectId);+ }+}diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsnew file mode 100644index 0000000000..126be07a61--- /dev/null+++ b/server/services/musicVideo/render.test.js@@ -0,0 +1,197 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Isolate the module's I/O boundaries so the pure builders + resolvers can be+// unit-tested without ffmpeg, the DB, or the filesystem.+vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));+vi.mock('../../lib/ffmpeg.js', () => ({+ findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),+ safeUnder: (root, name) => (name ? `${root}/${name}` : null),+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),+ probeVideoDuration: vi.fn(async () => 30),+}));+vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(), saveHistory: vi.fn(async () => {}) }));+vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));+vi.mock('./projects.js', () => ({ getProject: vi.fn(), updateProject: vi.fn(async () => ({})) }));++import { existsSync } from 'fs';+import {+ beatSnapClips,+ buildMusicVideoFfmpegArgs,+ resolveSceneClips,+ resolveMasterAudioPath,+ renderMusicVideo,+} from './render.js';+import { findFfmpeg } from '../../lib/ffmpeg.js';+import { loadHistory } from '../videoGen/local.js';+import { getTrack } from '../tracks/index.js';+import { getProject } from './projects.js';++const clip = (over = {}) => ({ videoPath: '/v/a.mp4', width: 768, height: 512, fps: 24, duration: 2, inSec: 0, outSec: 2, ...over });++beforeEach(() => {+ vi.clearAllMocks();+ existsSync.mockReturnValue(true);+});++describe('buildMusicVideoFfmpegArgs', () => {+ it('concats video-only and maps one external audio bed', () => {+ const { args } = buildMusicVideoFfmpegArgs([clip({ videoPath: '/v/a.mp4' }), clip({ videoPath: '/v/b.mp4' })], '/music/track.wav', '/out.mp4', { audioDurationSec: 30 });+ const fc = args[args.indexOf('-filter_complex') + 1];+ // Video-only concat (a=0), no per-clip audio stubs.+ expect(fc).toContain('concat=n=2:v=1:a=0[outv]');+ expect(fc).not.toContain('anullsrc');+ expect(fc).not.toContain('atrim');+ expect(fc).not.toMatch(/\[a\d+\]/);+ // The track is the last input, mapped as the sole output audio (index 2).+ expect(args.slice(-3, -1)).not.toContain('anullsrc');+ expect(args).toContain('/music/track.wav');+ const maps = args.reduce((acc, a, i) => (a === '-map' ? [...acc, args[i + 1]] : acc), []);+ expect(maps).toEqual(['[outv]', '2:a']);+ expect(args).toContain('-shortest');+ });++ it('totalDuration is the min of video and audio length', () => {+ const r1 = buildMusicVideoFfmpegArgs([clip({ duration: 2, outSec: 2 }), clip({ duration: 2, outSec: 2 })], '/a.wav', '/o.mp4', { audioDurationSec: 30 });+ expect(r1.totalDuration).toBe(4); // video (4) < audio (30)+ const r2 = buildMusicVideoFfmpegArgs([clip({ duration: 20, outSec: 20 })], '/a.wav', '/o.mp4', { audioDurationSec: 10 });+ expect(r2.totalDuration).toBe(10); // audio (10) < video (20)+ });++ it('throws on empty clips', () => {+ expect(() => buildMusicVideoFfmpegArgs([], '/a.wav', '/o.mp4')).toThrow(/empty clips/);+ });+});++describe('beatSnapClips', () => {+ it('returns clips unchanged when there is no beat grid', () => {+ const out = beatSnapClips([clip({ duration: 2, outSec: 2 })], null);+ expect(out[0].outSec).toBe(2);+ });++ it('trims a cut back to a nearby beat (snap earlier, never extend)', () => {+ // clip natural end = 2.0; a beat at 1.95 is within tolerance → trim to 1.95.+ const out = beatSnapClips([clip({ duration: 2, outSec: 2 })], [0, 1.95, 4], { toleranceSec: 0.12 });+ expect(out[0].outSec).toBeCloseTo(1.95, 5);+ expect(out[0].duration).toBeCloseTo(1.95, 5);+ });++ it('does not extend a clip to a beat past its natural end', () => {+ // nearest beat (2.1) is AFTER the 2.0 natural end → no snap (can't grow a clip).+ const out = beatSnapClips([clip({ duration: 2, outSec: 2 })], [0, 2.1], { toleranceSec: 0.2 });+ expect(out[0].outSec).toBe(2);+ });++ it('ignores a beat outside the tolerance window', () => {+ const out = beatSnapClips([clip({ duration: 2, outSec: 2 })], [0, 1.5], { toleranceSec: 0.12 });+ expect(out[0].outSec).toBe(2);+ });++ it('never trims below the minimum clip length', () => {+ const out = beatSnapClips([clip({ duration: 0.5, outSec: 0.5 })], [0.45], { toleranceSec: 0.12, minClipSec: 0.4 });+ // snapping to 0.45 would leave 0.45 ≥ min, so it IS allowed here:+ expect(out[0].outSec).toBeCloseTo(0.45, 5);+ // but a beat that would shorten below min is rejected:+ const out2 = beatSnapClips([clip({ duration: 0.5, outSec: 0.5 })], [0.3], { toleranceSec: 0.3, minClipSec: 0.4 });+ expect(out2[0].outSec).toBe(0.5);+ });++ it('advances the running cursor by the snapped (not natural) duration', () => {+ // clip0 trims 2.0→1.95; clip1 natural end is then 1.95+2=3.95, beat at 3.9 → 1.95.+ const out = beatSnapClips([clip({ duration: 2, outSec: 2 }), clip({ duration: 2, outSec: 2 })], [1.95, 3.9], { toleranceSec: 0.12 });+ expect(out[0].outSec).toBeCloseTo(1.95, 5);+ expect(out[1].outSec).toBeCloseTo(1.95, 5); // 3.9 - 1.95+ });+});++describe('resolveSceneClips', () => {+ it('resolves scenes with a clip, in order, skipping those without one', async () => {+ loadHistory.mockResolvedValue([+ { id: 'h1', filename: 'a.mp4', width: 768, height: 512, fps: 24, numFrames: 48 },+ { id: 'h2', filename: 'b.mp4', width: 768, height: 512, fps: 24, numFrames: 24 },+ ]);+ const project = { scenes: [+ { sceneId: 's2', order: 1, videoHistoryId: 'h2' },+ { sceneId: 's1', order: 0, videoHistoryId: 'h1' },+ { sceneId: 's3', order: 2, videoHistoryId: null }, // no clip yet → skipped+ ] };+ const clips = await resolveSceneClips(project);+ expect(clips.map((c) => c.sceneId)).toEqual(['s1', 's2']); // sorted by order+ expect(clips[0].duration).toBe(2); // 48/24+ });++ it('throws NO_SCENE_CLIPS when no scene has a clip', async () => {+ loadHistory.mockResolvedValue([]);+ await expect(resolveSceneClips({ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: null }] }))+ .rejects.toMatchObject({ status: 400, code: 'NO_SCENE_CLIPS' });+ });++ it('throws MISSING_CLIPS when a clip id is not in history', async () => {+ loadHistory.mockResolvedValue([]); // h1 absent+ await expect(resolveSceneClips({ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }] }))+ .rejects.toMatchObject({ status: 404, code: 'MISSING_CLIPS' });+ });++ it('throws MISSING_CLIPS when the clip file is gone', async () => {+ loadHistory.mockResolvedValue([{ id: 'h1', filename: 'a.mp4', width: 768, height: 512, fps: 24, numFrames: 48 }]);+ existsSync.mockReturnValue(false);+ await expect(resolveSceneClips({ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }] }))+ .rejects.toMatchObject({ status: 404, code: 'MISSING_CLIPS' });+ });+});++describe('renderMusicVideo mutex (#1760 re-entrancy guard)', () => {+ it('409s a second concurrent render for the same project', async () => {+ getProject.mockResolvedValue({ id: 'p1', name: 'P', trackId: 't1', status: 'ready', scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }] });+ loadHistory.mockResolvedValue([{ id: 'h1', filename: 'a.mp4', width: 768, height: 512, fps: 24, numFrames: 48 }]);+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });+ // The first call hangs in prep (findFfmpeg never resolves) so its synchronously+ // reserved PENDING slot stays claimed across the await window.+ findFfmpeg.mockReturnValue(new Promise(() => {}));+ const first = renderMusicVideo('p1'); // do NOT await — hangs after claiming PENDING+ first.catch(() => {}); // it never settles; suppress any rejection noise+ await new Promise((r) => setTimeout(r, 0)); // let the first call claim PENDING++ await expect(renderMusicVideo('p1')).rejects.toMatchObject({ status: 409, code: 'RENDER_IN_PROGRESS' });+ findFfmpeg.mockResolvedValue('/usr/bin/ffmpeg'); // restore for any later test+ });++ it('releases the slot when prep throws (no stale 409 on retry)', async () => {+ // Audio resolves (track present) so prep reaches the clip check and throws there.+ getProject.mockResolvedValue({ id: 'p2', name: 'P', status: 'ready', trackId: 't1', scenes: [] });+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });+ findFfmpeg.mockResolvedValue('/usr/bin/ffmpeg');+ loadHistory.mockResolvedValue([]);+ await expect(renderMusicVideo('p2')).rejects.toMatchObject({ code: 'NO_SCENE_CLIPS' });+ // The slot was released on the prep failure, so a retry reaches resolution+ // again (same throw, NOT a 409 from a stuck slot).+ await expect(renderMusicVideo('p2')).rejects.toMatchObject({ code: 'NO_SCENE_CLIPS' });+ });+});++describe('resolveMasterAudioPath', () => {+ it('resolves a linked track to its audio file', async () => {+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });+ const p = await resolveMasterAudioPath({ trackId: 't1' });+ expect(p).toMatch(/song\.wav$/);+ });++ it('resolves an uploaded audio filename', async () => {+ const p = await resolveMasterAudioPath({ uploadedAudioFilename: 'upload.mp3' });+ expect(p).toMatch(/upload\.mp3$/);+ });++ it('400s when the project has no audio', async () => {+ await expect(resolveMasterAudioPath({})).rejects.toMatchObject({ status: 400, code: 'NO_AUDIO' });+ });++ it('404s when the linked track is missing', async () => {+ getTrack.mockResolvedValue(null);+ await expect(resolveMasterAudioPath({ trackId: 't1' })).rejects.toMatchObject({ status: 404 });+ });++ it('404s when the audio file is gone', async () => {+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });+ existsSync.mockReturnValue(false);+ await expect(resolveMasterAudioPath({ trackId: 't1' })).rejects.toMatchObject({ status: 404, code: 'AUDIO_MISSING' });+ });+});