Skip to content

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

feat: preview piecewise audio timing revisions before applying (#9350)

[._.]/ Adam Eivy425bde65a2f8
diff --git a/client/src/components/musicVideo/AudioTimingPanel.jsx b/client/src/components/musicVideo/AudioTimingPanel.jsx
new file mode 100644
index 0000000000..b9fc2d6e08
--- /dev/null
+++ b/client/src/components/musicVideo/AudioTimingPanel.jsx
@@ -0,0 +1,74 @@
+import { useRef, useState } from 'react';
+import { previewMusicVideoAudioTiming, applyMusicVideoAudioTiming } from '../../services/apiMusicVideo.js';
+import { formatCount } from '../../utils/formatters.js';
+
+const seconds = (value) => value == null ? '—' : `${Number(value).toFixed(2)}s`;
+
+/** Draft lives only in this keyed panel. Cancel never mutates the project. */
+export default function AudioTimingPanel({ project, tracks, onApplied, disabled }) {
+ const [open, setOpen] = useState(false);
+ const [targetTrackId, setTargetTrackId] = useState('');
+ const [intervals, setIntervals] = useState([{ oldStartSec: 0, oldEndSec: project.audioAnalysis?.durationSec || 1, newStartSec: 0 }]);
+ const [preview, setPreview] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState('');
+ const generation = useRef(0);
+ const change = (fn) => { generation.current++; setPreview(null); setError(''); fn(); };
+ const cancel = () => change(() => { setOpen(false); });
+ const inspect = () => {
+ const token = ++generation.current;
+ setBusy(true); setError('');
+ previewMusicVideoAudioTiming(project.id, { targetTrackId, intervals }, { silent: true })
+ .then((result) => { if (generation.current === token) setPreview(result); })
+ .catch((err) => { if (generation.current === token) setError(err.message); })
+ .finally(() => setBusy(false));
+ };
+ const apply = () => {
+ setBusy(true); setError('');
+ applyMusicVideoAudioTiming(project.id, { targetTrackId, intervals, basis: preview.basis }, { silent: true })
+ .then(({ project: updated }) => { onApplied(updated); setPreview(null); setOpen(false); })
+ .catch((err) => setError(err.message))
+ .finally(() => setBusy(false));
+ };
+ if (!open) return <button disabled={disabled} onClick={() => setOpen(true)} className="min-h-[44px] text-sm text-port-accent">Preview audio timing revision</button>;
+ return (
+ <section aria-label="Audio timing revision" className="min-w-0 space-y-3 rounded-lg border border-port-border bg-port-card p-3">
+ <h3 className="font-medium">Preview audio timing revision</h3>
+ <p className="text-xs text-port-text-muted">Choose a separate edited track and list preserved intervals in seconds. Gaps describe inserted or deleted audio. Each interval keeps its duration. Cancel leaves timing unchanged.</p>
+ <fieldset disabled={busy || disabled} className="space-y-3">
+ <label htmlFor="audio-timing-track" className="block text-sm">Edited track</label>
+ <select id="audio-timing-track" value={targetTrackId} onChange={(event) => change(() => setTargetTrackId(event.target.value))} className="w-full rounded border border-port-border bg-port-bg p-2">
+ <option value="">Choose a library track</option>
+ {(tracks || []).filter((track) => track.audioFilename && track.id !== project.trackId).map((track) => <option key={track.id} value={track.id}>{track.title || track.id}</option>)}
+ </select>
+ {intervals.map((row, index) => (
+ <div key={index} className="flex flex-wrap items-end gap-2">
+ {[['oldStartSec', 'Old start'], ['oldEndSec', 'Old end'], ['newStartSec', 'New start']].map(([key, label]) => (
+ <div key={key} className="min-w-0 flex-1">
+ <label htmlFor={`timing-${index}-${key}`} className="block text-xs">{label} {formatCount(index + 1)}</label>
+ <input id={`timing-${index}-${key}`} type="number" min="0" step="0.01" value={row[key]} onChange={(event) => change(() => setIntervals((current) => current.map((entry, i) => i === index ? { ...entry, [key]: Number(event.target.value) } : entry)))} className="w-full rounded border border-port-border bg-port-bg p-2" />
+ </div>
+ ))}
+ <button disabled={intervals.length === 1} onClick={() => change(() => setIntervals((current) => current.filter((_, i) => i !== index)))} className="min-h-[44px] text-sm">Remove interval {formatCount(index + 1)}</button>
+ </div>
+ ))}
+ <div className="flex flex-wrap gap-3">
+ <button disabled={intervals.length >= 200} onClick={() => change(() => setIntervals((current) => [...current, { oldStartSec: current.at(-1).oldEndSec, oldEndSec: current.at(-1).oldEndSec + 1, newStartSec: current.at(-1).newStartSec + current.at(-1).oldEndSec - current.at(-1).oldStartSec }]))} className="min-h-[44px] text-sm">Add preserved interval</button>
+ <button disabled={!targetTrackId} onClick={inspect} className="min-h-[44px] text-sm text-port-accent">Preview mapping</button>
+ </div>
+ </fieldset>
+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}
+ {preview && <div aria-label="Timing map preview" className="space-y-2 text-sm">
+ {[...preview.intervals, ...preview.gaps].map((row, index) => <p key={index}>{row.status}: {seconds(row.oldStartSec)}–{seconds(row.oldEndSec)} → {seconds(row.newStartSec)}–{seconds(row.newEndSec)}</p>)}
+ {preview.affectedShots.map((shot) => <div key={shot.sceneId} className="rounded border border-port-border p-2">
+ <p>{shot.label || shot.sceneId}: {shot.status} · {seconds(shot.oldStartSec)}–{seconds(shot.oldEndSec)} → {seconds(shot.newStartSec)}–{seconds(shot.newEndSec)}</p>
+ <p className="text-xs text-port-text-muted">{formatCount(shot.takeIds.length)} historical takes retained{shot.repairRequired ? ' · performance repair required' : ''}{shot.reason ? ` · ${shot.reason}` : ''}</p>
+ </div>)}
+ <p>Rebuild estimate: {formatCount(preview.estimate.minGenerations)}–{formatCount(preview.estimate.maxGenerations)} shot repairs, up to {seconds(preview.estimate.maxSeconds)}. Price depends on the selected repair backend. Apply starts no generation.</p>
+ {preview.blockers.map((blocker, index) => <p key={index} role="alert">{blocker}</p>)}
+ <button disabled={!preview.canApply || busy || disabled} onClick={apply} className="min-h-[44px] rounded bg-port-accent px-3 text-white">Apply timing revision</button>
+ </div>}
+ <button disabled={busy} onClick={cancel} className="min-h-[44px] text-sm">Cancel timing revision</button>
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/AudioTimingPanel.test.jsx b/client/src/components/musicVideo/AudioTimingPanel.test.jsx
new file mode 100644
index 0000000000..d387b010c8
--- /dev/null
+++ b/client/src/components/musicVideo/AudioTimingPanel.test.jsx
@@ -0,0 +1,45 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import AudioTimingPanel from './AudioTimingPanel.jsx';
+import { previewMusicVideoAudioTiming, applyMusicVideoAudioTiming } from '../../services/apiMusicVideo.js';
+vi.mock('../../services/apiMusicVideo.js', () => ({ previewMusicVideoAudioTiming: vi.fn(), applyMusicVideoAudioTiming: vi.fn() }));
+const project = { id: 'example', audioAnalysis: { durationSec: 10 } };
+const preview = { basis: 'basis', canApply: true, intervals: [{ oldStartSec: 0, oldEndSec: 4, newStartSec: 0, newEndSec: 4, status: 'unchanged' }], gaps: [{ newStartSec: 4, newEndSec: 8, status: 'inserted' }],
+ affectedShots: [{ sceneId: 'shot', label: 'Chorus', status: 'moved', oldStartSec: 6, oldEndSec: 8, newStartSec: 10, newEndSec: 12, takeIds: ['take'], repairRequired: true }],
+ blockers: [], estimate: { minGenerations: 0, maxGenerations: 1, maxSeconds: 2 } };
+beforeEach(() => { vi.clearAllMocks(); previewMusicVideoAudioTiming.mockResolvedValue(preview); });
+async function open(onApplied = vi.fn()) {
+ render(<AudioTimingPanel project={project} tracks={[{ id: 'edited', title: 'Edited song', audioFilename: 'edited.wav' }]} onApplied={onApplied} />);
+ fireEvent.click(screen.getByText('Preview audio timing revision'));
+ fireEvent.change(screen.getByLabelText('Edited track'), { target: { value: 'edited' } });
+ fireEvent.click(screen.getByText('Preview mapping'));
+ await screen.findByLabelText('Timing map preview');
+}
+describe('audio timing timeline preview', () => {
+ it('renders intervals, affected take and bounded repair estimate, then cancels without applying', async () => {
+ await open();
+ expect(screen.getByText(/inserted:.*4.00s.*8.00s/)).toBeTruthy();
+ expect(screen.getByText(/Chorus: moved.*6.00s.*10.00s/)).toBeTruthy();
+ expect(screen.getByText(/1 historical takes retained.*performance repair required/)).toBeTruthy();
+ fireEvent.click(screen.getByText('Cancel timing revision'));
+ expect(screen.queryByLabelText('Timing map preview')).toBeNull();
+ expect(applyMusicVideoAudioTiming).not.toHaveBeenCalled();
+ });
+ it('applies the reviewed basis and immediately updates the board, invalidating a preview on input changes', async () => {
+ const onApplied = vi.fn();
+ applyMusicVideoAudioTiming.mockResolvedValue({ project: { ...project, trackId: 'edited' } });
+ await open(onApplied);
+ fireEvent.change(screen.getByLabelText('Old end 1'), { target: { value: '8' } });
+ expect(screen.queryByText('Apply timing revision')).toBeNull();
+ fireEvent.click(screen.getByText('Preview mapping'));
+ fireEvent.click(await screen.findByText('Apply timing revision'));
+ await waitFor(() => expect(onApplied).toHaveBeenCalledWith({ ...project, trackId: 'edited' }));
+ expect(applyMusicVideoAudioTiming).toHaveBeenCalledWith('example', { targetTrackId: 'edited', intervals: [{ oldStartSec: 0, oldEndSec: 8, newStartSec: 0 }], basis: 'basis' }, { silent: true });
+ });
+ it('shows ambiguous window refusals with Apply disabled', async () => {
+ previewMusicVideoAudioTiming.mockResolvedValue({ ...preview, canApply: false, blockers: ['Split the shot crossing this edit.'] });
+ await open();
+ expect(screen.getByRole('alert').textContent).toContain('Split the shot');
+ expect(screen.getByText('Apply timing revision').disabled).toBe(true);
+ });
+});
diff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsx
index 4840113b9c..f14cc06020 100644
--- a/client/src/components/musicVideo/stages/BoardStage.jsx
+++ b/client/src/components/musicVideo/stages/BoardStage.jsx
@@ -1,4 +1,5 @@
import { Plus } from 'lucide-react';
+import AudioTimingPanel from '../AudioTimingPanel.jsx';
import BeatTimeline from '../BeatTimeline.jsx';
import SceneCard from '../SceneCard.jsx';
import { PlanActions } from '../ProjectActionGroups.jsx';
@@ -32,6 +33,8 @@ export default function BoardStage({ board }) {
<PlanActions project={project} busy={busy} onPlan={board.onPlan} onAutoArrange={board.onAutoArrange} />
</div>
+ <AudioTimingPanel key={project.id} project={project} tracks={board.tracks} onApplied={board.replaceProject} disabled={locked || board.renderBound} />
+
{project.audioAnalysis && scenes.length > 0 && (
<BeatTimeline audioAnalysis={project.audioAnalysis} scenes={scenes} lyricCues={project.lyricCues} onCommit={board.commitSceneTiming} />
)}
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 7069fdff9f..ee108b5fe6 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -406,3 +406,10 @@ export const repairMusicVideoPerformance = (id, sceneId, input, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/scenes/${encodeURIComponent(sceneId)}/performance-repair`, {
method: 'POST', body: JSON.stringify(input), ...options,
});
+
+export const previewMusicVideoAudioTiming = (id, data, options = {}) => request(`/music-video/${encodeURIComponent(id)}/audio-timing/preview`, {
+ method: 'POST', body: JSON.stringify(data), ...options,
+});
+export const applyMusicVideoAudioTiming = (id, data, options = {}) => request(`/music-video/${encodeURIComponent(id)}/audio-timing/apply`, {
+ method: 'POST', body: JSON.stringify(data), ...options,
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index efcb047d8c..16ca0da2aa 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1013,3 +1013,17 @@ export const musicVideoPerformanceRepairSchema = z.object({
sourceAssetId: z.string().min(1).max(200),
boundarySec: z.number().finite().min(0).max(36000),
}).strict();
+
+
+// Preserved intervals have equal duration: insertions/deletions are gaps, never stretch.
+export const musicVideoAudioTimingPreviewSchema = z.object({
+ targetTrackId: z.string().min(1).max(128),
+ intervals: z.array(z.object({
+ oldStartSec: z.number().finite().min(0).max(36000),
+ oldEndSec: z.number().finite().min(0).max(36000),
+ newStartSec: z.number().finite().min(0).max(36000),
+ }).strict()).min(1).max(200),
+}).strict();
+export const musicVideoAudioTimingApplySchema = musicVideoAudioTimingPreviewSchema.extend({
+ basis: z.string().regex(/^[a-f0-9]{32}$/),
+});
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index ecac9cc1af..2f26864db8 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -664,7 +664,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v16 = accepted-prefix continuation edit points and one-generation repair
// reservations. Older peers could regenerate accepted footage or duplicate
// a submitted suffix after restart. Absent repair metadata stays legacy.
- musicVideoProjects: 16,
+ // v17 = piecewise audio timing receipts and historical source/timing snapshots.
+ // Optional on legacy records; no backfill. Older peers cannot apply receipts safely.
+ musicVideoProjects: 17,
// 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/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 4a1d46f7af..61711eee4c 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -66,10 +66,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
describe('buildPortosMeta', () => {
it('rejects repair reservations and edit points on older music-video peers', async () => {
const meta = await buildPortosMeta();
- expect(meta.schemaVersions.musicVideoProjects).toBe(16);
- for (const receiverV of [13, 14, 15]) {
+ expect(meta.schemaVersions.musicVideoProjects).toBe(17);
+ for (const receiverV of [13, 14, 15, 16]) {
expect(compareSchemaVersions(meta.schemaVersions, { ...meta.schemaVersions, musicVideoProjects: receiverV }).ahead)
- .toContainEqual({ category: 'musicVideoProjects', senderV: 16, receiverV });
+ .toContainEqual({ category: 'musicVideoProjects', senderV: 17, receiverV });
}
});
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 0278d70dfe..b72e2fb89b 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -14,6 +14,8 @@ import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
+ musicVideoAudioTimingPreviewSchema,
+ musicVideoAudioTimingApplySchema,
musicVideoProjectCreateSchema,
musicVideoProjectCloneSchema,
musicVideoProjectUpdateSchema,
@@ -220,6 +222,18 @@ router.patch('/:id', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// Preview is read-only; Apply rechecks audio and the serialized project basis.
+router.post('/:id/audio-timing/preview', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoAudioTimingPreviewSchema, req.body);
+ const { previewAudioTiming } = await import('../services/musicVideo/audioTiming.js');
+ res.json(await previewAudioTiming(req.params.id, input));
+}));
+router.post('/:id/audio-timing/apply', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoAudioTimingApplySchema, req.body);
+ const { applyAudioTiming } = await import('../services/musicVideo/audioTiming.js');
+ res.json(await applyAudioTiming(req.params.id, input));
+}));
+
router.delete('/:id', asyncHandler(async (req, res) => {
await deleteProject(req.params.id);
res.json({ ok: true });
diff --git a/server/routes/musicVideoAudioTiming.test.js b/server/routes/musicVideoAudioTiming.test.js
new file mode 100644
index 0000000000..971b456b4e
--- /dev/null
+++ b/server/routes/musicVideoAudioTiming.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, afterAll } from 'vitest';
+import express from 'express';
+import { mkdirSync, writeFileSync } from 'fs';
+import { join, basename } from 'path';
+import { createHash } from 'crypto';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+const ROOT = () => lazyTempDataRoot('mv-audio-timing-');
+vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), { dataRoot: ROOT }));
+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+vi.mock('../services/tracks/index.js', () => ({ getTrack: vi.fn(async (id) => ({ id, audioFilename: `${id}.wav` })) }));
+// Deterministic offline decoder double; route/store/mapping and performance
+// fingerprint checks stay real. Different durations model inserted/deleted audio.
+vi.mock('../services/musicVideo/audioAnalysis.js', () => ({
+ analyzeAudioFile: vi.fn(async (path) => ({ durationSec: basename(path) === 'insert.wav' ? 14 : basename(path) === 'delete.wav' ? 8 : 10, bpm: 120, beats: [], downbeats: [], sections: [] })),
+}));
+vi.mock('../lib/audioFingerprint.js', async (original) => ({
+ ...await original(), computeRmsEnvelope: vi.fn(async () => new Int8Array(1400).fill(-20)),
+}));
+const { default: routes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+const { windowFingerprint } = await import('../lib/audioFingerprint.js');
+const { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
+const app = express(); app.use(express.json()); app.use('/api/music-video', routes); app.use(errorMiddleware);
+const post = (id, action, body) => request(app).post(`/api/music-video/${id}/audio-timing/${action}`).send(body);
+
+async function fixture({ legacy = false } = {}) {
+ mkdirSync(join(ROOT(), 'music'), { recursive: true });
+ for (const name of ['old', 'insert', 'delete']) writeFileSync(join(ROOT(), 'music', `${name}.wav`), `${name}-synthetic-audio`);
+ const project = await projects.createProject({ name: 'Example timing project', trackId: 'old' });
+ await projects.mutateProjectRecord(project.id, (p) => ({ project: { ...p,
+ lyricCues: [{ id: 'cue', text: 'Example lyric', startSec: 6, endSec: 8, words: [{ w: 'Example', startSec: 6, endSec: 7, conf: 'matched' }, { w: 'lyric', startSec: 7, endSec: 8, conf: 'matched' }] }],
+ composition: { mode: 'composed', textCues: [{ id: 'title', text: 'Example', startSec: 6, endSec: 8 }], posterSec: 7 },
+ scenes: [
+ { sceneId: 'first', label: 'Opening', startSec: 0, endSec: 2, shotMode: 'performance', videoHistoryId: 'clip-a' },
+ { sceneId: 'second', label: 'Chorus', startSec: 6, endSec: 8, shotMode: 'performance', videoHistoryId: 'clip-b' },
+ ].map((scene) => legacy ? scene : { ...scene, takes: [{ takeId: `take-${scene.sceneId}`, kind: 'video', assetId: scene.videoHistoryId,
+ shotInstruction: { shotMode: 'performance', edit: { inSec: 0, outSec: 2 }, songInterval: { startSec: scene.startSec, endSec: scene.endSec },
+ audio: { sha256: createHash('sha256').update('old-synthetic-audio').digest('hex'), windowFingerprint: windowFingerprint(new Int8Array(1000).fill(-20), { startSec: scene.startSec, endSec: scene.endSec }) } } }] }),
+ } }));
+ return projects.getProject(project.id);
+}
+const insertion = { targetTrackId: 'insert', intervals: [{ oldStartSec: 0, oldEndSec: 4, newStartSec: 0 }, { oldStartSec: 4, oldEndSec: 10, newStartSec: 8 }] };
+afterAll(cleanupTempDataRoots);
+
+describe('audio timing preview and Apply', () => {
+ it('previews insertion without mutation, preserves unchanged takes and applies once across restart/retry', async () => {
+ const before = await fixture();
+ const response = await post(before.id, 'preview', insertion);
+ expect(response.status).toBe(200);
+ expect(response.body.gaps).toEqual([{ status: 'inserted', newStartSec: 4, newEndSec: 8 }]);
+ expect(response.body.affectedShots).toMatchObject([
+ { sceneId: 'first', status: 'unchanged', repairRequired: false },
+ { sceneId: 'second', status: 'moved', newStartSec: 10, newEndSec: 12, repairRequired: true },
+ ]);
+ expect(await projects.getProject(before.id)).toEqual(before); // dismiss/cancel has no write
+ const body = { ...insertion, basis: response.body.basis };
+ const [applied, concurrent] = await Promise.all([post(before.id, 'apply', body), post(before.id, 'apply', body)]);
+ expect(applied.status).toBe(200);
+ expect(concurrent.status).toBe(200);
+ expect(applied.body.project.scenes[1]).toMatchObject({ startSec: 10, endSec: 12, takes: before.scenes[1].takes });
+ expect(applied.body.project.lyricCues[0]).toMatchObject({ startSec: 10, endSec: 12, words: [{ startSec: 10, endSec: 11 }, { startSec: 11, endSec: 12 }] });
+ expect(applied.body.project.composition.textCues[0]).toMatchObject({ startSec: 10, endSec: 12 });
+ expect(applied.body.project.composition.posterSec).toBeNull();
+ expect(applied.body.revision.before.scenes[1]).toMatchObject({ startSec: 6, endSec: 8 });
+ // A fresh public call reads the persisted receipt, with no in-memory token.
+ const replay = await post(before.id, 'apply', body);
+ expect(replay.body.alreadyApplied).toBe(true);
+ expect(replay.body.project.audioTimingRevisions).toHaveLength(1);
+ expect(replay.body.project.scenes[1].startSec).toBe(10);
+ expect((await post(before.id, 'apply', { ...body, targetTrackId: 'delete' })).status).toBe(409);
+ const clone = await projects.cloneProject(before.id, {});
+ expect(clone.audioTimingRevisions).toEqual([]);
+ expect(clone.scenes[1].startSec).toBe(10);
+ });
+
+ it('maps deletions and marks legacy performance evidence for repair', async () => {
+ const before = await fixture({ legacy: true });
+ const input = { targetTrackId: 'delete', intervals: [{ oldStartSec: 0, oldEndSec: 2, newStartSec: 0 }, { oldStartSec: 4, oldEndSec: 10, newStartSec: 2 }] };
+ const preview = await post(before.id, 'preview', input);
+ expect(preview.body.gaps).toEqual([{ status: 'deleted', oldStartSec: 2, oldEndSec: 4 }]);
+ expect(preview.body.affectedShots[0].repairRequired).toBe(true);
+ const applied = await post(before.id, 'apply', { ...input, basis: preview.body.basis });
+ expect(applied.status).toBe(200);
+ expect(applied.body.project.scenes[1]).toMatchObject({ startSec: 4, endSec: 6, videoHistoryId: 'clip-b' });
+ });
+
+ it('refuses overlapping/out-of-bounds maps, ambiguous shots and stale previews without writes', async () => {
+ const before = await fixture();
+ for (const intervals of [
+ [{ oldStartSec: 0, oldEndSec: 11, newStartSec: 0 }],
+ [{ oldStartSec: 0, oldEndSec: 4, newStartSec: 0 }, { oldStartSec: 3, oldEndSec: 10, newStartSec: 4 }],
+ [{ oldStartSec: 0, oldEndSec: 10, newStartSec: 9 }],
+ ]) expect((await post(before.id, 'preview', { targetTrackId: 'insert', intervals })).status).toBe(400);
+ const ambiguous = { targetTrackId: 'insert', intervals: [{ oldStartSec: 0, oldEndSec: 7, newStartSec: 0 }, { oldStartSec: 7, oldEndSec: 10, newStartSec: 11 }] };
+ const preview = await post(before.id, 'preview', ambiguous);
+ expect(preview.body.canApply).toBe(false);
+ expect(preview.body.affectedShots[1].status).toBe('ambiguous');
+ expect((await post(before.id, 'apply', { ...ambiguous, basis: preview.body.basis })).status).toBe(409);
+ const valid = await post(before.id, 'preview', insertion);
+ await projects.updateProject(before.id, { name: 'Changed after preview' });
+ expect((await post(before.id, 'apply', { ...insertion, basis: valid.body.basis })).status).toBe(409);
+ expect((await projects.getProject(before.id)).scenes).toEqual(before.scenes);
+ const fresh = await post(before.id, 'preview', insertion);
+ writeFileSync(join(ROOT(), 'music', 'insert.wav'), 'changed-after-preview');
+ expect((await post(before.id, 'apply', { ...insertion, basis: fresh.body.basis })).status).toBe(409);
+ });
+
+ it('keeps receipt-bearing records off older peers', () => {
+ expect(compareSchemaVersions(PORTOS_SCHEMA_VERSIONS, { ...PORTOS_SCHEMA_VERSIONS, musicVideoProjects: 16 }).ahead)
+ .toContainEqual({ category: 'musicVideoProjects', senderV: 17, receiverV: 16 });
+ });
+});
diff --git a/server/services/musicVideo/audioTiming.js b/server/services/musicVideo/audioTiming.js
new file mode 100644
index 0000000000..a4ca6a3f46
--- /dev/null
+++ b/server/services/musicVideo/audioTiming.js
@@ -0,0 +1,143 @@
+/** Explicit piecewise audio revision. Preview never persists or calls a provider.
+ * Receipts live on the existing db-primary project, under its write lock.
+ */
+import { sha256File as sourceHash } from '../../lib/fileCore.js';
+import { basename } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { canonicalSnapshotChecksum as checksum } from '../../lib/snapshotChecksum.js';
+import { presentMusicVideoDependencies } from '../../lib/musicVideoDependencies.js';
+import { isPerformanceScene } from '../../lib/musicVideoShotTiming.js';
+import { getProject, mutateProjectRecord } from './projects.js';
+import { applyProjectPatch } from './projectsLogic.js';
+
+const refuse = (message, status = 409) => new ServerError(message, { status, code: 'AUDIO_TIMING_INVALID' });
+const projectBasis = (project) => checksum(presentMusicVideoDependencies(project));
+const time = (value) => Math.round(value * 1000) / 1000;
+
+function mapWindow(intervals, start, end) {
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return null;
+ const pieces = intervals.filter((row) => row.oldStartSec < end && row.oldEndSec > start);
+ if (!pieces.length || pieces[0].oldStartSec > start || pieces.at(-1).oldEndSec < end) return null;
+ const offset = pieces[0].newStartSec - pieces[0].oldStartSec;
+ for (let i = 0; i < pieces.length; i++) {
+ if (Math.abs(pieces[i].newStartSec - pieces[i].oldStartSec - offset) > 0.0001
+ || (i && pieces[i].oldStartSec !== pieces[i - 1].oldEndSec)) return null;
+ }
+ return { startSec: time(start + offset), endSec: time(end + offset) };
+}
+
+function mapTimed(items, intervals) {
+ return (items || []).map((item) => {
+ const mapped = mapWindow(intervals, item.startSec, item.endSec);
+ return { ...item, ...(mapped || { startSec: null, endSec: null }),
+ ...(item.words ? { words: mapped ? mapTimed(item.words, intervals).filter((word) => word.startSec != null) : [] } : {}),
+ ...(!mapped && 'matched' in item ? { matched: 0 } : {}) };
+ });
+}
+
+async function prepare(project, input) {
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const { resolveMasterAudioPath } = await import('./render.js');
+ const { analyzeAudioFile } = await import('./audioAnalysis.js');
+ const oldPath = await resolveMasterAudioPath(project);
+ const newPath = await resolveMasterAudioPath({ trackId: input.targetTrackId });
+ if (oldPath === newPath) throw refuse('Choose a separate edited track so the original audio remains available.');
+ const [oldHash, newHash, oldAnalysis, analysis] = await Promise.all([
+ sourceHash(oldPath), sourceHash(newPath),
+ analyzeAudioFile(oldPath), analyzeAudioFile(newPath),
+ ]);
+ const [oldAfter, newAfter] = await Promise.all([sourceHash(oldPath), sourceHash(newPath)]);
+ if (oldHash !== oldAfter || newHash !== newAfter) throw refuse('Audio changed during analysis. Preview again.');
+ if (!oldAnalysis?.durationSec || !analysis?.durationSec) throw refuse('Both source audio files must decode before timing can be mapped.');
+ if (oldAnalysis.truncatedAtSec || analysis.truncatedAtSec) throw refuse('Full audio analysis is required; these files exceed the analyzer duration limit.');
+ const intervals = input.intervals.map((row) => ({ ...row,
+ newEndSec: time(row.newStartSec + row.oldEndSec - row.oldStartSec),
+ status: row.newStartSec === row.oldStartSec ? 'unchanged' : 'moved',
+ }));
+ let oldEnd = 0;
+ let newEnd = 0;
+ const gaps = [];
+ for (const row of intervals) {
+ if (row.oldEndSec <= row.oldStartSec || row.oldStartSec < oldEnd || row.newStartSec < newEnd
+ || row.oldEndSec > oldAnalysis.durationSec || row.newEndSec > analysis.durationSec) {
+ throw refuse('Intervals must be ordered, non-overlapping, positive, and inside both audio files.', 400);
+ }
+ if (row.oldStartSec > oldEnd) gaps.push({ status: 'deleted', oldStartSec: oldEnd, oldEndSec: row.oldStartSec });
+ if (row.newStartSec > newEnd) gaps.push({ status: 'inserted', newStartSec: newEnd, newEndSec: row.newStartSec });
+ oldEnd = row.oldEndSec;
+ newEnd = row.newEndSec;
+ }
+ if (oldEnd < oldAnalysis.durationSec) gaps.push({ status: 'deleted', oldStartSec: oldEnd, oldEndSec: oldAnalysis.durationSec });
+ if (newEnd < analysis.durationSec) gaps.push({ status: 'inserted', newStartSec: newEnd, newEndSec: analysis.durationSec });
+ const scenes = (project.scenes || []).map((scene) => {
+ const mapped = mapWindow(intervals, scene.startSec, scene.endSec);
+ return { ...scene, ...(mapped || {}) };
+ });
+ const { findStalePerformanceTakes } = await import('./performanceShot.js');
+ const stale = await findStalePerformanceTakes({ ...project, scenes }, newPath);
+ const affectedShots = (project.scenes || []).map((scene) => {
+ const mapped = mapWindow(intervals, scene.startSec, scene.endSec);
+ const performance = isPerformanceScene(scene);
+ const moved = mapped && (mapped.startSec !== scene.startSec || mapped.endSec !== scene.endSec);
+ const repair = stale.find((entry) => entry.sceneId === scene.sceneId);
+ return { sceneId: scene.sceneId, label: scene.label, oldStartSec: scene.startSec, oldEndSec: scene.endSec,
+ newStartSec: mapped?.startSec ?? null, newEndSec: mapped?.endSec ?? null,
+ status: !mapped ? 'ambiguous' : moved ? 'moved' : 'unchanged',
+ takeIds: (scene.takes || []).map((take) => take.takeId),
+ selectedAssetId: scene.videoHistoryId || scene.referenceImageId || null,
+ repairRequired: Boolean(performance && (moved || repair)),
+ reason: !mapped ? 'Split or retime this shot before applying: its source window crosses an edit or has no timing.'
+ : performance && moved ? 'Moved performance requires a supported source-audio repair; no footage will be stretched.'
+ : repair?.reason || null };
+ });
+ const blockers = affectedShots.filter((shot) => shot.status === 'ambiguous').map((shot) => `${shot.label || shot.sceneId}: ${shot.reason}`);
+ if (['code', 'document'].includes(project.composition?.mode)) blockers.push('Authored code/document compositions need manual timing revision.');
+ if ((project.revisions || []).some((revision) => !['complete', 'completed', 'canceled', 'failed'].includes(revision.status))) blockers.push('Finish or cancel the active repair before changing audio timing.');
+ if (project.status === 'rendering' || (project.productionRuns || []).some((run) => ['running', 'queued'].includes(run.status))) blockers.push('Wait for active production to finish.');
+ if ((project.audioTimingRevisions || []).length >= 100) blockers.push('This project has reached 100 timing revisions; clone it to continue.');
+ const basis = checksum({ project: projectBasis(project), input, oldHash, newHash });
+ const repairs = affectedShots.filter((shot) => shot.repairRequired);
+ return { basis, intervals, gaps, affectedShots, blockers, canApply: blockers.length === 0,
+ estimate: { minGenerations: 0, maxGenerations: repairs.length, maxSeconds: time(repairs.reduce((sum, shot) => sum + (shot.newEndSec - shot.newStartSec || 0), 0)), costUsd: null },
+ oldDurationSec: oldAnalysis.durationSec, newDurationSec: analysis.durationSec,
+ analysis, scenes, oldAudioFilename: basename(oldPath) };
+}
+
+export async function previewAudioTiming(id, input) {
+ const preview = await prepare(await getProject(id), input);
+ const { analysis, scenes, oldAudioFilename, ...publicPreview } = preview;
+ return publicPreview;
+}
+
+export async function applyAudioTiming(id, { basis, ...input }) {
+ const before = await getProject(id);
+ if (!before) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const receipt = (before.audioTimingRevisions || []).find((revision) => revision.basis === basis);
+ if (receipt) {
+ if (checksum(receipt.input) !== checksum(input)) throw refuse('The applied preview belongs to another mapping.');
+ return { project: before, revision: receipt, alreadyApplied: true };
+ }
+ const preview = await prepare(before, input);
+ if (preview.basis !== basis) throw refuse('Project or source audio changed. Preview this mapping again.');
+ if (!preview.canApply) throw refuse(preview.blockers.join(' '));
+ return mutateProjectRecord(id, (current) => {
+ const existing = (current.audioTimingRevisions || []).find((revision) => revision.basis === basis);
+ if (existing) return { project: current, revision: existing, alreadyApplied: true };
+ if (projectBasis(current) !== projectBasis(before)) throw refuse('Project changed while preparing Apply. Preview again.');
+ const revision = { version: 1, basis, input, appliedAt: new Date().toISOString(),
+ before: { trackId: current.trackId, uploadedAudioFilename: current.uploadedAudioFilename,
+ audioFilename: preview.oldAudioFilename, vocalStemFilename: current.vocalStemFilename,
+ audioAnalysis: current.audioAnalysis, lyricCues: current.lyricCues, phrases: current.phrases,
+ composition: current.composition ? { textCues: current.composition.textCues, posterSec: current.composition.posterSec } : null,
+ renderHistoryId: current.renderHistoryId, midiTranscription: current.midiTranscription,
+ scenes: (current.scenes || []).map(({ sceneId, startSec, endSec }) => ({ sceneId, startSec, endSec })) },
+ affectedShots: preview.affectedShots };
+ const next = applyProjectPatch(current, { trackId: input.targetTrackId, uploadedAudioFilename: null });
+ return { project: { ...next, scenes: preview.scenes.map((scene) => ({ ...scene, beatAligned: false, sectionIndex: null })),
+ audioAnalysis: preview.analysis, status: 'analyzed', renderHistoryId: null,
+ midiTranscription: null, vocalStemFilename: null, performanceConditioningSource: 'master',
+ lyricCues: mapTimed(current.lyricCues, preview.intervals), phrases: mapTimed(current.phrases, preview.intervals),
+ ...(current.composition ? { composition: { ...next.composition, posterSec: null, textCues: mapTimed(current.composition.textCues, preview.intervals) } } : {}),
+ audioTimingRevisions: [...(current.audioTimingRevisions || []), revision] }, revision, alreadyApplied: false };
+ });
+}
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index a096af624c..0b27f00bf9 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -246,6 +246,7 @@ export function cloneProjectRecord(source, {
// A revision is in-progress work against the SOURCE's takes; the clone
// starts with none (its carried-over notes can open a fresh one).
revisions: [],
+ audioTimingRevisions: [],
// #9102: an auto-review run is tied to the SOURCE's revisions/excerpts, so a
// clone starts with none (terminal runs too — their links are source-scoped).
...(Array.isArray(source.autoReviews) ? { autoReviews: [] } : {}),
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 9d13bde299..998870f55c 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -550,6 +550,11 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }
// 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 revision of project?.audioTimingRevisions || []) {
+ if (isStr(revision.before?.audioFilename)) audioNames.push(revision.before.audioFilename);
+ if (isStr(revision.before?.vocalStemFilename)) audioNames.push(revision.before.vocalStemFilename);
+ if (isStr(revision.before?.midiTranscription?.filename)) audioNames.push(revision.before.midiTranscription.filename);
+ }
for (const name of [...new Set(audioNames)]) {
const audio = assetReference(name, 'music');
if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);
@@ -564,6 +569,7 @@ export async function referenceMusicVideoAssetManifest(project, { linkedTrack }
const videoIds = [...new Set([
...scenes.map((s) => (isStr(s?.videoHistoryId) ? s.videoHistoryId : null)).filter(Boolean),
...takeIds('video'),
+ ...(project?.audioTimingRevisions || []).map((revision) => revision.before?.renderHistoryId).filter(isStr),
])];
if (videoIds.length) {
const byId = await videoHistoryFilenamesById();
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index df6e1f87b4..c9baad3fe4 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -120,6 +120,13 @@ describe('buildMusicVideoAssetManifest — master audio', () => {
expect(manifest).toContainEqual({ filename: 'track-1.wav', kind: 'music', sha256: sha(bytes) });
});
+ it('retains the historical source audio after a timing revision', async () => {
+ const bytes = Buffer.from('historical-audio');
+ writeMusic('previous.wav', bytes);
+ const manifest = await buildMusicVideoAssetManifest({ scenes: [], audioTimingRevisions: [{ before: { audioFilename: 'previous.wav' } }] });
+ expect(manifest).toContainEqual({ filename: 'previous.wav', kind: 'music', sha256: sha(bytes) });
+ });
+
it('skips a missing/deleted track without throwing', async () => {
vi.mocked(getTrack).mockResolvedValue(null);
const manifest = await buildMusicVideoAssetManifest({