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: condition lip-sync performance shots on an optional vocal stem (#8977)
[._.]/ Adam Eivyd91cbfa6a2f8
diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsxindex f7314f2048..611dd0e4c5 100644--- a/client/src/components/musicVideo/TrackPanel.jsx+++ b/client/src/components/musicVideo/TrackPanel.jsx@@ -3,6 +3,7 @@ import toast from '../ui/Toast';import MidiVisualization from '../songs/MidiVisualization.jsx';import { trackAudioUrl } from '../../services/apiTracks.js';import YoutubeImportControls from './YoutubeImportControls.jsx';+import VocalStemControl from './VocalStemControl.jsx';import { trackSourceLabel } from '../../lib/trackProvenance.js';/**@@ -10,11 +11,12 @@ import { trackSourceLabel } from '../../lib/trackProvenance.js';* YouTube (re-selecting either PATCHes the project's trackId), then preview and* download the resolved master file. Relinking is blocked while a render or a* MIDI transcription is bound to this project — both already resolved the- * project's audio at kickoff.+ * project's audio at kickoff. An optional vocal stem (#8977) conditions+ * lip-sync performance shots in place of the mix.*/export default function TrackPanel({project, tracks, trackName, audioFilename, youtube,- renderBound, midiBound, onChangeTrack,+ renderBound, midiBound, onChangeTrack, onProjectUpdated,}) {const blockedMessage = renderBound? 'Wait for the current render to finish before changing the track'@@ -55,6 +57,11 @@ export default function TrackPanel({compact/></div>+ <VocalStemControl+ project={project}+ hasAudio={Boolean(project.trackId || project.uploadedAudioFilename)}+ onUpdated={onProjectUpdated}+ />{/* Preview + download the project's master audio track. Both act onthe resolved data/music/ file (linked track or uploaded audio). */}{audioUrl && (diff --git a/client/src/components/musicVideo/VocalStemControl.jsx b/client/src/components/musicVideo/VocalStemControl.jsxnew file mode 100644index 0000000000..86c173616e--- /dev/null+++ b/client/src/components/musicVideo/VocalStemControl.jsx@@ -0,0 +1,59 @@+import { useState } from 'react';+import { Mic, 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.';++/**+ * Attach, replace or remove the project's vocal stem (#8977). 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 }) {+ const [busy, setBusy] = useState(false);+ const inputId = `mv-vocal-stem-${project.id}`;+ const stem = project.vocalStemFilename || null;++ const run = (call, success, failure) => {+ setBusy(true);+ call()+ .then((updated) => {+ onUpdated(updated);+ toast.success(success);+ })+ .catch((err) => toast.error(err?.message || failure))+ .finally(() => setBusy(false));+ };++ const upload = (e) => {+ const file = e.target.files?.[0];+ e.target.value = '';+ if (!file) return;+ run(() => uploadMusicVideoVocalStem(project.id, file, { silent: true }), 'Vocal stem attached', 'Failed to attach the vocal stem');+ };+ const remove = () => run(() => removeMusicVideoVocalStem(project.id, { silent: true }), 'Vocal stem removed', 'Failed to remove the vocal stem');++ const disabled = busy || !hasAudio;+ 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} />+ <label htmlFor={inputId}+ 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>+ {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"+ 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>+ </>+ ) : (+ <span className="text-port-text-muted">Lip-sync uses the full mix</span>+ )}+ </div>+ );+}diff --git a/client/src/components/musicVideo/VocalStemControl.test.jsx b/client/src/components/musicVideo/VocalStemControl.test.jsxnew file mode 100644index 0000000000..e0e2eca03a--- /dev/null+++ b/client/src/components/musicVideo/VocalStemControl.test.jsx@@ -0,0 +1,54 @@+/**+ * Vocal stem control (#8977): choosing a file uploads it and applies the+ * project the server returns, a refused stem leaves the project as it was and+ * says why, and removal applies the cleared project.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++vi.mock('../../services/apiMusicVideo.js', () => ({+ uploadMusicVideoVocalStem: vi.fn(),+ removeMusicVideoVocalStem: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import * as api from '../../services/apiMusicVideo.js';+import toast from '../ui/Toast';+import VocalStemControl from './VocalStemControl.jsx';++const project = { id: 'mv-1', uploadedAudioFilename: 'song.wav' };+const file = () => new File(['x'], 'vocals.wav', { type: 'audio/wav' });++beforeEach(() => vi.clearAllMocks());++describe('VocalStemControl', () => {+ it('uploads a chosen stem, and on refusal keeps the project and shows the reason', async () => {+ const onUpdated = vi.fn();+ api.uploadMusicVideoVocalStem.mockResolvedValueOnce({ ...project, vocalStemFilename: 'vocals-1.wav' });+ render(<VocalStemControl project={project} hasAudio onUpdated={onUpdated} />);+ expect(screen.getByText('Lip-sync uses the full mix')).toBeTruthy();++ fireEvent.change(screen.getByLabelText(/Add vocal stem/), { target: { files: [file()] } });+ await waitFor(() => expect(onUpdated).toHaveBeenCalledWith({ ...project, vocalStemFilename: 'vocals-1.wav' }));+ expect(api.uploadMusicVideoVocalStem).toHaveBeenCalledWith('mv-1', expect.any(File), { silent: true });++ api.uploadMusicVideoVocalStem.mockRejectedValueOnce(new Error('The vocal stem is 5.000s but the song is 6.000s.'));+ fireEvent.change(screen.getByLabelText(/Add vocal stem/), { target: { files: [file()] } });+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('The vocal stem is 5.000s but the song is 6.000s.'));+ expect(onUpdated).toHaveBeenCalledTimes(1);+ });++ it('removes an attached stem', async () => {+ const onUpdated = vi.fn();+ api.removeMusicVideoVocalStem.mockResolvedValueOnce({ ...project, vocalStemFilename: null });+ render(<VocalStemControl project={{ ...project, vocalStemFilename: 'vocals-1.wav' }} hasAudio onUpdated={onUpdated} />);+ expect(screen.getByText('Lip-sync uses vocals-1.wav')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Remove vocal stem' }));+ await waitFor(() => expect(onUpdated).toHaveBeenCalledWith({ ...project, vocalStemFilename: null }));+ });++ it('is unavailable until the project has a song to match a stem against', () => {+ render(<VocalStemControl project={{ id: 'mv-2' }} hasAudio={false} onUpdated={vi.fn()} />);+ expect(screen.getByLabelText(/Add vocal stem/).disabled).toBe(true);+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex c4e591b829..721e9232e8 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -695,6 +695,7 @@ export default function MusicVideo() {renderBound={renderTargetsSelected}midiBound={midiTargetsSelected}onChangeTrack={handleChangeTrack}+ onProjectUpdated={replaceProject}/><RenderStatusPanelrendering={renderTargetsSelected}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex de28c088a4..1769a13020 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -70,6 +70,15 @@ export const splitMusicVideoScene = (id, sceneId, backend, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/split`, {method: 'POST', body: JSON.stringify(backend ? { backend } : {}), ...options,});+// Optional vocal stem (#8977): a full-length vocal bounce on the master's+// timebase that performance shots are conditioned on. Both → the project.+export const uploadMusicVideoVocalStem = (id, file, options = {}) => {+ const body = new FormData();+ body.append('stem', file, file.name || 'vocal-stem');+ return request(`/music-video/${encodeURIComponent(id)}/vocal-stem`, { method: 'POST', body, ...options });+};+export const removeMusicVideoVocalStem = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/vocal-stem`, { method: 'DELETE', ...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 76928b07b2..2d73379f3e 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) — Grok video is cutaway-only. | — |+| **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. | — || **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/conflictJournal.js b/server/lib/conflictJournal.jsindex 2b21048d88..20615fcb71 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -581,7 +581,7 @@ export const RESTORABLE_FIELDS = Object.freeze({// Music Video projects (#1770): the user-authored config + creative content the// merge can restore. `scenes[]` (the beat-aligned director board with prompts)// carries the bulk of the work, alongside name/status/mode/trackId/- // uploadedAudioFilename/concept. Server-owned / machine-managed fields are+ // uploadedAudioFilename/vocalStemFilename/concept. Server-owned / machine-managed fields are// excluded — `id`/`createdAt`/the LWW-tombstone trio are structural,// `renderHistoryId` is a derived output pointer, and `audioAnalysis` is the// machine-derived beat cache (regenerated from the audio, not hand-authored).@@ -589,7 +589,7 @@ export const RESTORABLE_FIELDS = Object.freeze({// narrowing); this set is what the Conflicts UI offers for restore.// `musicVideoProject` matches the record kind and updateProject (via// applyProjectPatch's wholesale spread) accepts every field here.- musicVideoProject: ['name', 'status', 'mode', 'trackId', 'uploadedAudioFilename', 'concept', 'scenes'],+ musicVideoProject: ['name', 'status', 'mode', 'trackId', 'uploadedAudioFilename', 'vocalStemFilename', 'concept', 'scenes'],});const present = (v) => v !== undefined;diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 24566b5d12..03c66b2405 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -42,6 +42,9 @@ import { recordRenderPinFields } from '../lib/sharedSchemas.js';import { PATHS } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';import { resolveGalleryImage } from '../lib/pathSafety.js';+import { uploadSingle } from '../lib/multipart.js';+import { isSupportedMusicUpload, MUSIC_UPLOAD_MAX_BYTES } from '../services/pipeline/musicLibrary.js';+import { attachVocalStem, detachVocalStem } from '../services/musicVideo/vocalStem.js';import {listProjects,getProject,@@ -139,6 +142,27 @@ router.delete('/:id', asyncHandler(async (req, res) => {res.json({ ok: true });}));+// Optional vocal stem (#8977): a full-length bounce of the vocal on the+// master's timebase. Performance shots are conditioned on it instead of the+// mix; the master stays the project's audio. Same audio formats and size cap+// as a track upload.+const vocalStemUpload = uploadSingle('stem', {+ limits: { fileSize: MUSIC_UPLOAD_MAX_BYTES },+ fileFilter: (_req, file, cb) => {+ if (isSupportedMusicUpload(file)) cb(null, true);+ else cb(new ServerError('Unsupported audio format — accepted: MP3, WAV, M4A, OGG, FLAC', { status: 400, code: 'VALIDATION_ERROR' }));+ },+});++router.post('/:id/vocal-stem', vocalStemUpload, asyncHandler(async (req, res) => {+ if (!req.file) throw new ServerError('No vocal stem file uploaded', { status: 400, code: 'VALIDATION_ERROR' });+ res.json(await attachVocalStem(req.params.id, { tempPath: req.file.path, originalName: req.file.originalname }));+}));++router.delete('/:id/vocal-stem', asyncHandler(async (req, res) => {+ res.json(await detachVocalStem(req.params.id));+}));+// 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.diff --git a/server/routes/musicVideoVocalStem.test.js b/server/routes/musicVideoVocalStem.test.jsnew file mode 100644index 0000000000..613e8f2c52--- /dev/null+++ b/server/routes/musicVideoVocalStem.test.js@@ -0,0 +1,104 @@+/**+ * Music Video vocal stem (#8977), through the real router, the real multipart+ * parser, the real file-backed project store and real ffprobe: a stem on the+ * 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.+ */++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++const 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 () => ({})) }));++const { default: musicVideoRoutes } = await import('./musicVideo.js');+const projects = await import('../services/musicVideo/projects.js');+const { findFfmpeg } = await import('../lib/ffmpeg.js');++const app = express();+app.use(express.json());+app.use('/api/music-video', musicVideoRoutes);+app.use(errorMiddleware);++const RATE = 8000;+// A silent mono 16-bit PCM WAV of an exact length.+const wav = (seconds) => {+ const bytes = Math.round(seconds * RATE) * 2;+ const buf = Buffer.alloc(44 + bytes);+ buf.write('RIFF', 0); buf.writeUInt32LE(36 + bytes, 4); buf.write('WAVE', 8);+ buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(1, 22);+ buf.writeUInt32LE(RATE, 24); buf.writeUInt32LE(RATE * 2, 28); buf.writeUInt16LE(2, 32); buf.writeUInt16LE(16, 34);+ buf.write('data', 36); buf.writeUInt32LE(bytes, 40);+ return buf;+};++const MUSIC = () => join(ROOT(), 'music');+const libraryFiles = () => readdirSync(MUSIC()).sort();++async function uploadStem(projectId, seconds) {+ const form = new FormData();+ form.append('stem', new Blob([wav(seconds)], { type: 'audio/wav' }), 'vocals.wav');+ const encoded = new Request('http://localhost/', { method: 'POST', body: form });+ return request(app).post(`/api/music-video/${projectId}/vocal-stem`)+ .set('content-type', encoded.headers.get('content-type'))+ .send(Buffer.from(await encoded.arrayBuffer()));+}++const ffmpeg = await findFfmpeg();++let project;+beforeEach(async () => {+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });+ rmSync(MUSIC(), { recursive: true, force: true });+ mkdirSync(MUSIC(), { recursive: true });+ writeFileSync(join(MUSIC(), 'song.wav'), wav(6));+ writeFileSync(join(MUSIC(), 'other-song.wav'), wav(6));+ project = await projects.createProject({ name: 'Example Video', uploadedAudioFilename: 'song.wav' });+});+afterAll(cleanupTempDataRoots);++describe.skipIf(!ffmpeg)('music-video vocal stem routes', () => {+ it('attaches a stem on the song timebase, keeps it through removal in the library, and drops it with the song', async () => {+ const res = await uploadStem(project.id, 6);+ expect(res.status).toBe(200);+ const stem = res.body.vocalStemFilename;+ expect(stem).toMatch(/\.wav$/);+ expect(existsSync(join(MUSIC(), stem))).toBe(true);+ expect((await projects.getProject(project.id)).vocalStemFilename).toBe(stem);++ const removed = await request(app).delete(`/api/music-video/${project.id}/vocal-stem`);+ expect(removed.status).toBe(200);+ expect(removed.body.vocalStemFilename).toBeNull();+ // The library is shared, so the file stays.+ expect(existsSync(join(MUSIC(), stem))).toBe(true);++ // A stem is a bounce of one song; relinking the project drops it.+ await uploadStem(project.id, 6);+ const relinked = await request(app).patch(`/api/music-video/${project.id}`).send({ uploadedAudioFilename: 'other-song.wav' });+ expect(relinked.status).toBe(200);+ expect(relinked.body.vocalStemFilename).toBeNull();+ });++ it('refuses a stem whose length does not match the song, before it reaches the library', async () => {+ const before = libraryFiles();+ const res = await uploadStem(project.id, 5);+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('MUSIC_VIDEO_VOCAL_STEM_TIMEBASE');+ expect(libraryFiles()).toEqual(before);+ expect((await projects.getProject(project.id)).vocalStemFilename).toBeUndefined();+ });++ it('refuses a stem for a project with no song to match it against', async () => {+ const empty = await projects.createProject({ name: 'No Song' });+ const res = await uploadStem(empty.id, 6);+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('NO_AUDIO');+ });+});diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.jsindex c3128a8988..6cf8a26501 100644--- a/server/services/musicVideo/performanceShot.js+++ b/server/services/musicVideo/performanceShot.js@@ -21,6 +21,11 @@* performance, capability snapshot, target edit duration and the coverage* the provider will generate.*+ * When the project carries a vocal stem (vocalStem.js) the window is cut from+ * the stem instead of the mix, at the same song times, after re-checking that+ * the stem still shares the master's timebase. The instruction records which+ * recording conditioned the take.+ ** The sliced WAV is staged under data/uploads so the media-job queue owns and* deletes it on every terminal path (completion, failure, cancel, restart).* The master stays untouched and remains the only audio in the final render.@@ -42,6 +47,7 @@ import {selectedPerformanceInstruction,} from '../../lib/musicVideoShotTiming.js';import { getProject } from './projects.js';+import { assertVocalStemTimebase, resolveVocalStemPath } from './vocalStem.js';export const SHOT_INSTRUCTION_VERSION = 1;@@ -145,10 +151,17 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImagePconst plan = planPerformanceWindow({ startSec: scene.startSec, endSec: scene.endSec, songDurationSec, capability });if (!plan.ok) throw refuse(plan.message, plan.code);+ // An optional vocal stem conditions the provider in place of the mix. It+ // is re-checked here because the file could have been replaced on disk or+ // arrived from a peer since it was attached.+ const stemPath = resolveVocalStemPath(project);+ if (stemPath) assertVocalStemTimebase(await probeVideoDuration(stemPath), songDurationSec);+const audioSha256 = await hashFile(masterPath);+ const conditioningSha256 = stemPath ? await hashFile(stemPath) : audioSha256;await ensureDir(PATHS.uploads);const audioFilePath = join(PATHS.uploads, `mv-performance-${randomUUID()}.wav`);- await sliceAudioWindow(masterPath, audioFilePath, { startSec: plan.windowStartSec, endSec: plan.windowEndSec });+ await sliceAudioWindow(stemPath || masterPath, audioFilePath, { startSec: plan.windowStartSec, endSec: plan.windowEndSec });// Verify the cut before anything is paid for: the provider rejects short// audio and silently clips long audio, and both would break the edit points.const slicedSec = await probeVideoDuration(audioFilePath);@@ -169,6 +182,10 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImagePsource: project.trackId ? 'track' : 'upload',sha256: audioSha256,songDurationSec,+ // What the provider heard: the master itself, or a vocal stem on the+ // master's timebase. `sha256` above stays the master's, so a take+ // is stale only when the song changes, not when a stem is swapped.+ conditioning: { source: stemPath ? 'vocal-stem' : 'master', sha256: conditioningSha256 },},songInterval: { startSec: scene.startSec, endSec: scene.endSec },audioWindow: { startSec: plan.windowStartSec, endSec: plan.windowEndSec, durationSec: plan.windowSec },diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.jsindex c5b342e4ce..2da1b9f8ad 100644--- a/server/services/musicVideo/performanceShot.test.js+++ b/server/services/musicVideo/performanceShot.test.js@@ -7,6 +7,7 @@*/import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';import { existsSync } from 'node:fs';import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';import { join } from 'node:path';@@ -41,14 +42,14 @@ const MARKER_SEC = 20;// A mono 16-bit PCM WAV built sample-by-sample, so the marker's position is// known exactly without trusting any encoder.-function songWav() {- const samples = SONG_SEC * RATE;+function songWav({ seconds = SONG_SEC, markerAmp = 30000 } = {}) {+ const samples = seconds * RATE;const buf = Buffer.alloc(44 + samples * 2);buf.write('RIFF', 0); buf.writeUInt32LE(36 + samples * 2, 4); buf.write('WAVE', 8);buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(1, 22);buf.writeUInt32LE(RATE, 24); buf.writeUInt32LE(RATE * 2, 28); buf.writeUInt16LE(2, 32); buf.writeUInt16LE(16, 34);buf.write('data', 36); buf.writeUInt32LE(samples * 2, 40);- buf.writeInt16LE(30000, 44 + MARKER_SEC * RATE * 2);+ buf.writeInt16LE(markerAmp, 44 + MARKER_SEC * RATE * 2);return buf;}@@ -113,6 +114,7 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncexpect(si.songInterval).toEqual({ startSec: 20, endSec: 21.5 });expect(si.cues).toEqual([{ text: 'hold on', startSec: 0.775, endSec: 2.275 }]);expect(si.audio.sha256).toMatch(/^[0-9a-f]{64}$/);+ expect(si.audio.conditioning).toEqual({ source: 'master', sha256: si.audio.sha256 });expect(si).toMatchObject({ referenceImageId: 'frame.png', performance: 'sings the held note', generatedCoverageSec: 5.05 });expect(si.capability).toMatchObject({ provider: 'fal', minAudioSec: 5, maxAudioSec: 14.8 });@@ -193,6 +195,34 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncexpect(asCutaway).toMatchObject({ inSec: 0 });}, 60_000);+ it('conditions on the vocal stem at the same song times and refuses a stem off the master timebase', async () => {+ const sha = (buf) => createHash('sha256').update(buf).digest('hex');+ const stem = songWav({ markerAmp: 12000 });+ await writeFile(join(PATHS.music, 'vocals.wav'), stem);+ getProject.mockResolvedValue({ ...project(), vocalStemFilename: 'vocals.wav' });+ const args = { musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: '/x/frame.png', mode: 'image' };+ const { audioFilePath, shotInstruction: si } = await preparePerformanceShot(args);++ // Same window and in-point as the master slice, but the stem's bytes.+ expect(si.audioWindow).toEqual({ startSec: 18.225, endSec: 23.275, durationSec: 5.05 });+ const samples = pcm(await readFile(audioFilePath));+ const markerAt = Math.round((MARKER_SEC - 18.225) * RATE);+ expect(samples.readInt16LE(markerAt * 2)).toBe(12000);+ // Staleness still keys on the master; the stem is recorded as what the+ // provider heard.+ expect(si.audio.sha256).toBe(sha(songWav()));+ expect(si.audio.conditioning).toEqual({ source: 'vocal-stem', sha256: sha(stem) });++ // A trimmed stem would put the syllables on the wrong frames.+ await writeFile(join(PATHS.music, 'vocals.wav'), songWav({ seconds: SONG_SEC - 1 }));+ await rm(PATHS.uploads, { recursive: true, force: true });+ await expect(preparePerformanceShot(args)).rejects.toMatchObject({ status: 400, code: 'MUSIC_VIDEO_VOCAL_STEM_TIMEBASE' });+ // A stem the record names but the disk lacks is not silently replaced by the mix.+ await rm(join(PATHS.music, 'vocals.wav'));+ await expect(preparePerformanceShot(args)).rejects.toMatchObject({ status: 404, code: 'MUSIC_VIDEO_VOCAL_STEM_MISSING' });+ expect(existsSync(PATHS.uploads) ? await readdir(PATHS.uploads) : []).toEqual([]);+ });+it('uses the full span of a long shot and stays under the provider maximum', async () => {getProject.mockResolvedValue(project({ startSec: 10, endSec: 24.7 }));const { shotInstruction: si } = await preparePerformanceShot({diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex ba0b9a9c02..acb679cd2d 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -296,6 +296,9 @@ export function applyProjectPatch(project, patch) {// Composition cue times and the poster frame were set against the old// song too: keep the text, clear the timings (#8984)....(project.composition ? { composition: invalidateCompositionTiming(project.composition) } : {}),+ // A vocal stem is a bounce of the OLD song; conditioning a performance on+ // it against the new master would sing the wrong words (#8977).+ ...(project.vocalStemFilename ? { vocalStemFilename: null } : {}),...mergedPatch,...statusPatch,audioAnalysis: null,diff --git a/server/services/musicVideo/vocalStem.js b/server/services/musicVideo/vocalStem.jsnew file mode 100644index 0000000000..4602c5fd59--- /dev/null+++ b/server/services/musicVideo/vocalStem.js@@ -0,0 +1,107 @@+/**+ * Music Video vocal-stem conditioning (#8977).+ *+ * A performance shot conditions the lip-sync provider on a slice of the song.+ * The full mix carries drums, bass and pads that can pull mouth motion off the+ * vocal, so the director may attach an isolated VOCAL STEM: a full-length+ * bounce of the vocal from the same session as the master. Performance slices+ * are then cut from the stem, at the same song times, instead of the mix.+ *+ * The stem conditions generation only. The master stays the project's audio:+ * the final render, the beat grid, the lyric cues and the staleness check on+ * a performance take all still read the master.+ *+ * A stem is only useful if it shares the master's timebase. Song time T in+ * the stem must be song time T in the master. The check that can be made+ * without guessing is duration: a stem bounced from the same session is the+ * master's length to within an encoder frame or two. A trimmed, offset or+ * different-edit stem is refused, both when attached and again at every+ * submission. A leading offset inside an equal-length file cannot be detected+ * this way, which is why the UI asks for a full-length bounce from zero.+ *+ * The stem file lives in the shared music library (like an uploaded master),+ * so it federates through the project's `music` asset manifest.+ */++import { existsSync } from 'fs';+import { unlink } from 'fs/promises';+import { join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/fileUtils.js';+import { probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';+import { importUploadedTrack } from '../pipeline/musicLibrary.js';+import { getProject, updateProject } from './projects.js';++// A same-session bounce differs from the master by encoder padding at most+// (an MP3 frame is ~26ms); a tenth of a second admits that and nothing that+// would move a syllable onto the wrong frame.+export const VOCAL_STEM_TIMEBASE_TOLERANCE_SEC = 0.1;++/**+ * Refuse a stem whose length does not match the master's.+ */+export function assertVocalStemTimebase(stemSec, songSec) {+ if (stemSec == null || songSec == null) {+ throw new ServerError('Could not read the vocal stem or song duration', { status: 400, code: 'MUSIC_VIDEO_VOCAL_STEM_UNREADABLE' });+ }+ if (Math.abs(stemSec - songSec) > VOCAL_STEM_TIMEBASE_TOLERANCE_SEC) {+ throw new ServerError(+ `The vocal stem is ${stemSec.toFixed(3)}s but the song is ${songSec.toFixed(3)}s. A stem must be a full-length bounce from the same session, starting at 0:00, so its timing matches the song.`,+ { status: 400, code: 'MUSIC_VIDEO_VOCAL_STEM_TIMEBASE' },+ );+ }+}++/**+ * Absolute path of the project's vocal stem, or null when none is attached.+ * Throws when the record names a stem whose file is gone or unsafe, rather+ * than quietly conditioning on the full mix.+ */+export function resolveVocalStemPath(project) {+ const filename = project?.vocalStemFilename;+ if (!filename) return null;+ const safe = safeUnder(PATHS.music, filename);+ if (!safe || !existsSync(safe)) {+ throw new ServerError('The project\'s vocal stem file is missing. Attach it again or remove it.', { status: 404, code: 'MUSIC_VIDEO_VOCAL_STEM_MISSING' });+ }+ return safe;+}++const audioSourceKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uploadedAudioFilename ?? ''}`;++/**+ * Attach an uploaded vocal stem to a project after checking its timebase+ * against the current master. The temp upload is always removed.+ */+export async function attachVocalStem(projectId, { tempPath, originalName }) {+ try {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ // Lazy: render.js pulls the whole render pipeline.+ const { resolveMasterAudioPath } = await import('./render.js');+ const masterPath = await resolveMasterAudioPath(project);+ const [songSec, stemSec] = await Promise.all([probeVideoDuration(masterPath), probeVideoDuration(tempPath)]);+ assertVocalStemTimebase(stemSec, songSec);+ const { filename } = await importUploadedTrack(tempPath, originalName);+ // The song may have been swapped while the files were probed; a stem+ // checked against the old master must not land on the new one.+ const current = await getProject(projectId);+ if (!current || audioSourceKey(current) !== audioSourceKey(project)) {+ await unlink(join(PATHS.music, filename)).catch(() => {});+ throw new ServerError('The project\'s song changed while the vocal stem was uploading. Upload it again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });+ }+ return updateProject(projectId, { vocalStemFilename: filename });+ } finally {+ await unlink(tempPath).catch(() => {});+ }+}++/**+ * Stop conditioning on a stem. The library file stays, as with a track's+ * audio, because the library is shared.+ */+export async function detachVocalStem(projectId) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ return updateProject(projectId, { vocalStemFilename: null });+}diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex de574741c3..aace9c815a 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -547,6 +547,9 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }// precisely so it rides this manifest; without it a subscribed peer receives// a `midiTranscription.filename` pointer whose bytes never arrive.if (isStr(project?.midiTranscription?.filename)) audioNames.push(project.midiTranscription.filename);+ // The optional vocal stem (#8977) conditions performance shots and lives+ // under PATHS.music beside the master, so it rides the same entries.+ if (isStr(project?.vocalStemFilename)) audioNames.push(project.vocalStemFilename);for (const name of [...new Set(audioNames)]) {const audio = assetReference(name, 'music');if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.jsindex 7602b69e8c..3ba025bd20 100644--- a/server/services/sharing/peerSyncAssets.test.js+++ b/server/services/sharing/peerSyncAssets.test.js@@ -135,17 +135,21 @@ describe('buildMusicVideoAssetManifest — master audio', () => {expect(manifest).toEqual([]);});- it('bundles the MuScriptor MIDI transcription alongside the master audio', async () => {+ it('bundles the MuScriptor MIDI transcription and the vocal stem alongside the master audio', async () => {const audioBytes = Buffer.from('uploaded-audio');const midiBytes = Buffer.from('MThd-midi-bytes');+ const stemBytes = Buffer.from('vocal-stem');writeMusic('upload.mp3', audioBytes);writeMusic('neon-midi.mid', midiBytes);+ writeMusic('vocals.wav', stemBytes);const manifest = await buildMusicVideoAssetManifest({trackId: null, uploadedAudioFilename: 'upload.mp3', scenes: [],midiTranscription: { filename: 'neon-midi.mid', model: 'medium' },+ vocalStemFilename: 'vocals.wav',});expect(manifest).toContainEqual({ filename: 'upload.mp3', kind: 'music', sha256: sha(audioBytes) });expect(manifest).toContainEqual({ filename: 'neon-midi.mid', kind: 'music', sha256: sha(midiBytes) });+ expect(manifest).toContainEqual({ filename: 'vocals.wav', kind: 'music', sha256: sha(stemBytes) });});it('dedups when the upload basename and the linked track point at the same file', async () => {