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: draft excerpt render with cut/cue contact sheet and review notes (#8986)

[._.]/ Adam Eivy9a2021776fe4
diff --git a/client/src/components/musicVideo/ExcerptPanel.jsx b/client/src/components/musicVideo/ExcerptPanel.jsx
new file mode 100644
index 0000000000..3636fbcccd
--- /dev/null
+++ b/client/src/components/musicVideo/ExcerptPanel.jsx
@@ -0,0 +1,173 @@
+import { useRef, useState } from 'react';
+import { Film, Flag, CheckCircle2, Trash2, X, Clapperboard } from 'lucide-react';
+
+const VERDICT_STYLES = {
+ flagged: 'bg-port-error/20 text-port-error',
+ approved: 'bg-port-success/20 text-port-success',
+};
+const STATUS_LABELS = { rendering: 'Rendering…', complete: 'Ready', error: 'Failed', canceled: 'Cancelled' };
+
+const fmt = (sec) => {
+ const s = Math.max(0, Math.round(sec * 10) / 10);
+ const m = Math.floor(s / 60);
+ const r = (s % 60).toFixed(1).padStart(4, '0');
+ return `${m}:${r}`;
+};
+
+function NoteRow({ excerptId, note, busy, onEdit, onDelete, onSeek }) {
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(note.note);
+ if (editing) {
+ return (
+ <li className="flex flex-wrap items-center gap-1.5 text-xs">
+ <input value={draft} maxLength={2000} onChange={(e) => setDraft(e.target.value)}
+ aria-label="Edit review note"
+ className="min-w-0 flex-1 bg-port-bg border border-port-border rounded px-1.5 py-1" />
+ <button type="button" disabled={busy || !draft.trim()}
+ onClick={() => { onEdit(excerptId, note.id, { note: draft.trim() }); setEditing(false); }}
+ className="text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0 px-1">Save</button>
+ <button type="button" onClick={() => setEditing(false)} className="text-port-text-muted min-h-[44px] sm:min-h-0 px-1">Cancel</button>
+ </li>
+ );
+ }
+ return (
+ <li className="flex flex-wrap items-start gap-1.5 text-xs">
+ <button type="button" onClick={() => onSeek(note.atSec)} className="text-port-accent font-mono shrink-0 min-h-[44px] sm:min-h-0" title="Jump to this moment">
+ {fmt(note.atSec)}
+ </button>
+ <span className="min-w-0 flex-1 break-words">{note.note}</span>
+ {note.verdict && <span className={`px-1.5 py-0.5 rounded text-[10px] uppercase shrink-0 ${VERDICT_STYLES[note.verdict] || ''}`}>{note.verdict}</span>}
+ <div className="flex items-center gap-1 shrink-0">
+ <button type="button" title="Flag an issue" aria-label="Flag an issue"
+ onClick={() => onEdit(excerptId, note.id, { verdict: note.verdict === 'flagged' ? null : 'flagged' })}
+ disabled={busy} className={`p-1 rounded min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 ${note.verdict === 'flagged' ? 'text-port-error' : 'text-port-text-muted'}`}>
+ <Flag size={12} />
+ </button>
+ <button type="button" title="Approve" aria-label="Approve"
+ onClick={() => onEdit(excerptId, note.id, { verdict: note.verdict === 'approved' ? null : 'approved' })}
+ disabled={busy} className={`p-1 rounded min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 ${note.verdict === 'approved' ? 'text-port-success' : 'text-port-text-muted'}`}>
+ <CheckCircle2 size={12} />
+ </button>
+ <button type="button" title="Edit" aria-label="Edit note" onClick={() => setEditing(true)} disabled={busy}
+ className="p-1 rounded min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 text-port-text-muted">Edit</button>
+ <button type="button" title="Delete note" aria-label="Delete note" onClick={() => onDelete(excerptId, note.id)} disabled={busy}
+ className="p-1 rounded min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 text-port-error">
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </li>
+ );
+}
+
+function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNote, onEditNote, onDeleteNote }) {
+ const videoRef = useRef(null);
+ const [draft, setDraft] = useState('');
+ const seek = (t) => { if (videoRef.current) { videoRef.current.currentTime = t; videoRef.current.play?.().catch(() => {}); } };
+ const addNoteHere = () => {
+ if (!draft.trim()) return;
+ onAddNote(excerpt.id, { atSec: videoRef.current?.currentTime ?? 0, note: draft.trim() });
+ setDraft('');
+ };
+ return (
+ <li className="rounded border border-port-border p-2 space-y-2">
+ <div className="flex flex-wrap items-center justify-between gap-2 text-xs">
+ <span className="font-medium">{fmt(excerpt.startSec)} – {fmt(excerpt.endSec)} <span className="text-port-text-muted">({STATUS_LABELS[excerpt.status] || excerpt.status})</span></span>
+ <div className="flex items-center gap-2">
+ {excerpt.status === 'rendering'
+ ? <button type="button" onClick={() => onCancel(excerpt.id)} className="text-port-error flex items-center gap-1 min-h-[44px] sm:min-h-0"><X size={12} /> Cancel</button>
+ : <button type="button" disabled={deleting} onClick={() => onDelete(excerpt.id)} className="text-port-error flex items-center gap-1 disabled:opacity-50 min-h-[44px] sm:min-h-0"><Trash2 size={12} /> Delete</button>}
+ </div>
+ </div>
+ {excerpt.status === 'error' && excerpt.error && <p role="alert" className="text-xs text-port-error">{excerpt.error}</p>}
+ {excerpt.status === 'complete' && excerpt.filename && (
+ <div className="space-y-2">
+ <video ref={videoRef} src={`/data/videos/${excerpt.filename}`} controls playsInline preload="metadata"
+ className="w-full aspect-video max-h-[45vh] object-contain rounded bg-black border border-port-border"
+ aria-label={`Play excerpt ${fmt(excerpt.startSec)} to ${fmt(excerpt.endSec)}`} />
+ {excerpt.contactSheetFilename && (
+ <details className="text-xs">
+ <summary className="cursor-pointer text-port-text-muted flex items-center gap-1"><Clapperboard size={12} /> Contact sheet (cut/cue frames)</summary>
+ <img src={`/data/video-thumbnails/${excerpt.contactSheetFilename}`} alt="Excerpt contact sheet — one frame per cut and cue boundary" className="mt-1 w-full rounded border border-port-border" />
+ </details>
+ )}
+ <div className="space-y-1">
+ <span className="text-[11px] text-port-text-muted">Review notes — frame checks alone can't prove motion/audio sync; watch alongside the sheet</span>
+ {excerpt.notes?.length > 0 && (
+ <ul className="space-y-1">
+ {excerpt.notes.map((note) => (
+ <NoteRow key={note.id} excerptId={excerpt.id} note={note} busy={noteBusy === excerpt.id}
+ onEdit={onEditNote} onDelete={onDeleteNote} onSeek={seek} />
+ ))}
+ </ul>
+ )}
+ <div className="flex items-center gap-1.5">
+ <input value={draft} maxLength={2000} onChange={(e) => setDraft(e.target.value)}
+ placeholder="Note at the current playhead…" aria-label="New review note"
+ className="min-w-0 flex-1 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs" />
+ <button type="button" onClick={addNoteHere} disabled={noteBusy === excerpt.id || !draft.trim()}
+ className="text-port-accent disabled:opacity-50 text-xs min-h-[44px] sm:min-h-0 px-2">Add</button>
+ </div>
+ </div>
+ </div>
+ )}
+ </li>
+ );
+}
+
+/**
+ * Draft excerpt render (#8986): pick a `[startSec, endSec)` window and render
+ * it through the same composed pipeline as a full render, at a size a fast
+ * iteration loop can afford. Each excerpt keeps its own cut/cue contact sheet
+ * and timecoded review notes against its OWN timeline (0 = the excerpt's
+ * start) — a frame check alone can't prove motion/audio sync, so the video
+ * plays alongside the sheet rather than replacing it.
+ */
+export default function ExcerptPanel({ project, rendering, progress, excerpts, ...actions }) {
+ const durationSec = project?.audioAnalysis?.durationSec ?? null;
+ const [startSec, setStartSec] = useState(0);
+ const [endSec, setEndSec] = useState(durationSec ? Math.min(15, durationSec) : 15);
+ const idFor = (s) => `mv-excerpt-${project?.id}-${s}`;
+ const valid = Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec;
+
+ return (
+ <div className="space-y-2">
+ <span className="text-xs text-port-text-muted flex items-center gap-1"><Film size={12} /> Draft excerpt</span>
+ <div className="flex flex-wrap items-end gap-2">
+ <div>
+ <label htmlFor={idFor('start')} className="block text-[10px] text-port-text-muted">Start (sec)</label>
+ <input id={idFor('start')} type="number" min={0} step={0.5} value={startSec}
+ onChange={(e) => setStartSec(Number(e.target.value))}
+ className="w-24 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs" />
+ </div>
+ <div>
+ <label htmlFor={idFor('end')} className="block text-[10px] text-port-text-muted">End (sec)</label>
+ <input id={idFor('end')} type="number" min={0} step={0.5} value={endSec}
+ onChange={(e) => setEndSec(Number(e.target.value))}
+ className="w-24 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs" />
+ </div>
+ <button type="button" disabled={rendering || !valid}
+ onClick={() => actions.startExcerpt(startSec, endSec)}
+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
+ <Film size={13} /> Render excerpt
+ </button>
+ </div>
+ {rendering && (
+ <div>
+ <div className="h-1.5 bg-port-bg rounded overflow-hidden">
+ <div className="h-full bg-port-accent transition-all" style={{ width: `${progress}%` }} />
+ </div>
+ <p className="text-xs text-port-text-muted mt-1">Rendering excerpt — {Math.round(progress)}%</p>
+ </div>
+ )}
+ {excerpts.length > 0 && (
+ <ul className="space-y-2">
+ {[...excerpts].reverse().map((excerpt) => (
+ <ExcerptCard key={excerpt.id} excerpt={excerpt} deleting={actions.deletingId === excerpt.id} noteBusy={actions.noteBusyId}
+ onDelete={actions.deleteExcerpt} onCancel={actions.cancelExcerpt}
+ onAddNote={actions.addNote} onEditNote={actions.editNote} onDeleteNote={actions.deleteNote} />
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index ef4ec32c96..b14291b1c3 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -248,6 +248,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |
| `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. |
| `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. |
+| `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt, deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |
| `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. |
| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |
| `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index f1b3a45997..fc3a4329af 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -59,6 +59,7 @@ export * from './useKeyboardShortcuts.js';
export { default as useMediaJobProgress } from './useMediaJobProgress.js';
export * from './useMediaJobSse.js';
export { default as useSceneRenderLifecycle } from './useSceneRenderLifecycle.js';
+export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';
export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';
export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';
export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';
diff --git a/client/src/hooks/useMusicVideoExcerpts.js b/client/src/hooks/useMusicVideoExcerpts.js
new file mode 100644
index 0000000000..434d150535
--- /dev/null
+++ b/client/src/hooks/useMusicVideoExcerpts.js
@@ -0,0 +1,106 @@
+import { useState } from 'react';
+import toast from '../components/ui/Toast';
+import {
+ getMusicVideoProject,
+ renderMusicVideoExcerpt,
+ musicVideoExcerptRenderEventsUrl,
+ cancelMusicVideoExcerptRender,
+ deleteMusicVideoExcerpt,
+ addMusicVideoExcerptNote,
+ updateMusicVideoExcerptNote,
+ deleteMusicVideoExcerptNote,
+} from '../services/apiMusicVideo.js';
+import useSseJobSlot from './useSseJobSlot.js';
+
+const readPercent = (frame) => (Number.isFinite(frame.progress) ? frame.progress * 100 : undefined);
+
+/**
+ * Music Video draft excerpt render + timecoded review notes (#8986).
+ *
+ * The render itself reuses the shared SSE job slot (one excerpt render at a
+ * time per project, enforced server-side); every terminal frame — complete,
+ * error, or cancelled — reloads the project instead of hand-merging the
+ * result, since the persisted shape (status/filename/contactSheetFilename/
+ * error) already lives on the server record and a refetch can't drift from it.
+ *
+ * Notes/delete calls return the fresh whole project in their response body,
+ * so those apply it directly with `replaceProject` — no separate reload.
+ *
+ * `replaceProject(project)` swaps the local record whole; the caller supplies
+ * it (mirrors `useMusicVideoTreatment`).
+ */
+export default function useMusicVideoExcerpts({ project, replaceProject } = {}) {
+ const projectId = project?.id || null;
+ const [noteBusyId, setNoteBusyId] = useState(null);
+ const [deletingId, setDeletingId] = useState(null);
+
+ const reload = () => {
+ if (!projectId) return;
+ getMusicVideoProject(projectId, { silent: true }).then(replaceProject).catch(() => {});
+ };
+
+ const job = useSseJobSlot({
+ startRequest: ({ startSec, endSec }) => renderMusicVideoExcerpt(projectId, { startSec, endSec }, { silent: true }),
+ eventsUrl: musicVideoExcerptRenderEventsUrl,
+ cancelRequest: cancelMusicVideoExcerptRender,
+ readPercent,
+ onComplete: reload,
+ onErrorFrame: () => { reload(); return true; }, // reload already surfaces the persisted `error` field; skip the generic toast
+ onKickoffError: (err) => {
+ if (err?.status === 409) { toast.error(err.message || 'An excerpt render is already in progress'); return true; }
+ return false;
+ },
+ successToast: () => 'Excerpt rendered',
+ errorFallback: 'Excerpt render failed',
+ canceledMessage: 'Excerpt render cancelled',
+ lostConnectionMessage: 'Lost connection to the excerpt render',
+ startErrorFallback: 'Failed to start the excerpt render',
+ });
+
+ const startExcerpt = (startSec, endSec) => job.start({ startSec, endSec }, projectId);
+
+ const deleteExcerpt = (excerptId) => {
+ setDeletingId(excerptId);
+ return deleteMusicVideoExcerpt(projectId, excerptId, { silent: true })
+ .then(replaceProject)
+ .catch((err) => toast.error(err?.message || 'Failed to delete the excerpt'))
+ .finally(() => setDeletingId(null));
+ };
+
+ const addNote = (excerptId, { atSec, note, verdict }) => {
+ setNoteBusyId(excerptId);
+ return addMusicVideoExcerptNote(projectId, excerptId, { atSec, note, ...(verdict ? { verdict } : {}) }, { silent: true })
+ .then(({ project: next }) => { replaceProject(next); return next; })
+ .catch((err) => { toast.error(err?.message || 'Failed to add the note'); return null; })
+ .finally(() => setNoteBusyId(null));
+ };
+
+ const editNote = (excerptId, noteId, patch) => {
+ setNoteBusyId(excerptId);
+ return updateMusicVideoExcerptNote(projectId, excerptId, noteId, patch, { silent: true })
+ .then(({ project: next }) => { replaceProject(next); return next; })
+ .catch((err) => { toast.error(err?.message || 'Failed to update the note'); return null; })
+ .finally(() => setNoteBusyId(null));
+ };
+
+ const deleteNote = (excerptId, noteId) => {
+ setNoteBusyId(excerptId);
+ return deleteMusicVideoExcerptNote(projectId, excerptId, noteId, { silent: true })
+ .then(replaceProject)
+ .catch((err) => toast.error(err?.message || 'Failed to delete the note'))
+ .finally(() => setNoteBusyId(null));
+ };
+
+ return {
+ rendering: job.active,
+ progress: job.active ? job.percent : 0,
+ deletingId,
+ noteBusyId,
+ startExcerpt,
+ cancelExcerpt: job.cancel,
+ deleteExcerpt,
+ addNote,
+ editNote,
+ deleteNote,
+ };
+}
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index f97120c0c0..990ce749ce 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -22,6 +22,7 @@ import useFieldDraft from '../hooks/useFieldDraft.js';
import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';
import useMusicVideoMidiJob from '../hooks/useMusicVideoMidiJob.js';
import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';
+import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';
import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';
import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';
import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';
@@ -39,6 +40,7 @@ import CreateProjectDrawer from '../components/musicVideo/CreateProjectDrawer.js
import ProjectToolbar from '../components/musicVideo/ProjectToolbar.jsx';
import TrackPanel from '../components/musicVideo/TrackPanel.jsx';
import RenderStatusPanel from '../components/musicVideo/RenderStatusPanel.jsx';
+import ExcerptPanel from '../components/musicVideo/ExcerptPanel.jsx';
import AnalysisPanel from '../components/musicVideo/AnalysisPanel.jsx';
import SceneCard from '../components/musicVideo/SceneCard.jsx';
import LyricsPanel from '../components/musicVideo/LyricsPanel.jsx';
@@ -115,6 +117,10 @@ export default function MusicVideo() {
})),
onFailed: (projectId) => patchProject(projectId, { status: 'failed' }),
});
+ // Draft excerpt render (#8986): a fast cue/cut preview of a chosen window,
+ // separate from the full-render job/mutex above so a director can preview a
+ // change without waiting on (or blocking) a full render.
+ const excerpts = useMusicVideoExcerpts({ project: selected, replaceProject });
const videoSettings = useMusicVideoModelSettings({ project: selected, onProjectPatch: patchProject });
const tempo = useMusicVideoManualTempo({ project: selected, onUpdated: replaceProject });
const sceneMedia = useMusicVideoSceneMedia({
@@ -681,6 +687,20 @@ export default function MusicVideo() {
finalVideo={finalVideo}
onOpenPreview={openPreview}
/>
+ <ExcerptPanel
+ project={selected}
+ rendering={excerpts.rendering}
+ progress={excerpts.progress}
+ excerpts={selected.excerpts || []}
+ deletingId={excerpts.deletingId}
+ noteBusyId={excerpts.noteBusyId}
+ startExcerpt={excerpts.startExcerpt}
+ cancelExcerpt={excerpts.cancelExcerpt}
+ deleteExcerpt={excerpts.deleteExcerpt}
+ addNote={excerpts.addNote}
+ editNote={excerpts.editNote}
+ deleteNote={excerpts.deleteNote}
+ />
<LyricsPanel
project={selected}
onEditLocal={editProjectLocal}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 322098eeb0..6a12f46330 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -70,6 +70,13 @@ vi.mock('../services/apiMusicVideo.js', () => ({
previewMusicVideoTreatmentApply: vi.fn(),
applyMusicVideoTreatment: vi.fn(),
reviewMusicVideoTreatmentProof: vi.fn(),
+ renderMusicVideoExcerpt: vi.fn(async () => ({ jobId: 'mve-job-1', excerptId: 'mve-job-1' })),
+ musicVideoExcerptRenderEventsUrl: (jobId) => `/api/music-video/excerpt/${jobId}/events`,
+ cancelMusicVideoExcerptRender: vi.fn(async () => ({ ok: true })),
+ deleteMusicVideoExcerpt: vi.fn(),
+ addMusicVideoExcerptNote: vi.fn(),
+ updateMusicVideoExcerptNote: vi.fn(),
+ deleteMusicVideoExcerptNote: vi.fn(),
}));
vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn() }));
vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));
@@ -151,6 +158,8 @@ import {
importMusicVideoLyrics, updateMusicVideoScene,
selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,
addMusicVideoSceneTake, getMusicVideoHandoffBundle,
+ renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,
+ updateMusicVideoExcerptNote, deleteMusicVideoExcerptNote, getMusicVideoProject,
} from '../services/apiMusicVideo.js';
import { generateImage, uploadGalleryImage } from '../services/apiSystem.js';
import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
@@ -363,6 +372,91 @@ describe('MusicVideo render control (#1760)', () => {
});
});
+describe('MusicVideo draft excerpt render (#8986)', () => {
+ it('kicks off an excerpt render with the typed range and shows progress', async () => {
+ await openProject(PROJECT_WITH_CLIP);
+ fireEvent.change(screen.getByLabelText('Start (sec)'), { target: { value: '10' } });
+ fireEvent.change(screen.getByLabelText('End (sec)'), { target: { value: '20' } });
+ fireEvent.click(screen.getByRole('button', { name: /Render excerpt/i }));
+ await waitFor(() => expect(renderMusicVideoExcerpt).toHaveBeenCalledWith('mv-1', { startSec: 10, endSec: 20 }, { silent: true }));
+ await settle(); // let the resolved kickoff's jobId land before feeding the SSE frame
+
+ sseState.latest = { type: 'progress', progress: 0.5 };
+ // The mocked useSseProgress hook returns the shared, directly-mutated
+ // `sseState` object rather than its own React state, so nothing re-renders
+ // the component until something else does — force one (mirrors the
+ // existing render-job tests' use of this same mock).
+ fireEvent.click(screen.getByRole('button', { name: /New project/i }));
+ await screen.findByText(/Rendering excerpt — 50%/);
+ });
+
+ it('reloads the project on a completed excerpt render and shows the player + contact sheet + notes', async () => {
+ getMusicVideoProject.mockResolvedValue({
+ ...PROJECT_WITH_CLIP,
+ excerpts: [{
+ id: 'mve-1', startSec: 10, endSec: 20, status: 'complete',
+ filename: 'excerpt-1.mp4', contactSheetFilename: 'excerpt-1-sheet.png', error: null,
+ notes: [{ id: 'mvn-1', atSec: 3, note: 'lip-sync drifts here', verdict: null }],
+ }],
+ });
+ await openProject(PROJECT_WITH_CLIP);
+ fireEvent.click(screen.getByRole('button', { name: /Render excerpt/i }));
+ await waitFor(() => expect(renderMusicVideoExcerpt).toHaveBeenCalled());
+ await settle();
+ sseState.latest = { type: 'complete', result: { excerptId: 'mve-1', filename: 'excerpt-1.mp4' } };
+ fireEvent.click(screen.getByRole('button', { name: /New project/i }));
+
+ await screen.findByLabelText(/Play excerpt/i);
+ expect(screen.getByText('lip-sync drifts here')).toBeInTheDocument();
+ const contactSheet = await screen.findByAltText(/contact sheet/i);
+ expect(contactSheet.getAttribute('src')).toBe('/data/video-thumbnails/excerpt-1-sheet.png');
+ });
+
+ it('adds, edits and removes a review note against the excerpt', async () => {
+ const project = {
+ ...PROJECT_WITH_CLIP,
+ excerpts: [{
+ id: 'mve-1', startSec: 10, endSec: 20, status: 'complete',
+ filename: 'excerpt-1.mp4', contactSheetFilename: null, error: null, notes: [],
+ }],
+ };
+ addMusicVideoExcerptNote.mockResolvedValue({
+ project: { ...project, excerpts: [{ ...project.excerpts[0], notes: [{ id: 'mvn-1', atSec: 0, note: 'looks great', verdict: null }] }] },
+ note: { id: 'mvn-1', atSec: 0, note: 'looks great', verdict: null },
+ });
+ await openProject(project);
+
+ fireEvent.change(screen.getByLabelText('New review note'), { target: { value: 'looks great' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));
+ await waitFor(() => expect(addMusicVideoExcerptNote).toHaveBeenCalledWith('mv-1', 'mve-1', { atSec: 0, note: 'looks great' }, { silent: true }));
+ await screen.findByText('looks great');
+
+ updateMusicVideoExcerptNote.mockResolvedValue({
+ project: { ...project, excerpts: [{ ...project.excerpts[0], notes: [{ id: 'mvn-1', atSec: 0, note: 'looks great', verdict: 'approved' }] }] },
+ note: { id: 'mvn-1', atSec: 0, note: 'looks great', verdict: 'approved' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Approve' }));
+ await waitFor(() => expect(updateMusicVideoExcerptNote).toHaveBeenCalledWith('mv-1', 'mve-1', 'mvn-1', { verdict: 'approved' }, { silent: true }));
+
+ deleteMusicVideoExcerptNote.mockResolvedValue({ ...project, excerpts: [{ ...project.excerpts[0], notes: [] }] });
+ fireEvent.click(screen.getByRole('button', { name: 'Delete note' }));
+ await waitFor(() => expect(deleteMusicVideoExcerptNote).toHaveBeenCalledWith('mv-1', 'mve-1', 'mvn-1', { silent: true }));
+ await waitFor(() => expect(screen.queryByText('looks great')).not.toBeInTheDocument());
+ });
+
+ it('deletes a completed excerpt', async () => {
+ const project = {
+ ...PROJECT_WITH_CLIP,
+ excerpts: [{ id: 'mve-1', startSec: 10, endSec: 20, status: 'complete', filename: 'excerpt-1.mp4', contactSheetFilename: null, error: null, notes: [] }],
+ };
+ deleteMusicVideoExcerpt.mockResolvedValue({ ...project, excerpts: [] });
+ await openProject(project);
+ fireEvent.click(screen.getByRole('button', { name: /^Delete$/ }));
+ await waitFor(() => expect(deleteMusicVideoExcerpt).toHaveBeenCalledWith('mv-1', 'mve-1', { silent: true }));
+ await waitFor(() => expect(screen.queryByLabelText(/Play excerpt/i)).not.toBeInTheDocument());
+ });
+});
+
describe('MusicVideo project video renderer', () => {
it('lets the server resolve this install default when a synced project has no backend pin', async () => {
generateVideo.mockResolvedValue({ jobId: 'video-job-default' });
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 2b5f446c1b..cfb639fe4d 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -127,6 +127,35 @@ export const musicVideoRenderEventsUrl = (jobId) =>
export const cancelMusicVideoRender = (jobId, options = {}) =>
request(`/music-video/render/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });
+// ---- Draft excerpt render (#8986) ----
+// A director-chosen [startSec, endSec) window re-rendered through the same
+// composed pipeline, plus a cut/cue contact sheet and timecoded review notes.
+// Kickoff resolves to { jobId, excerptId }; progress streams over its OWN SSE
+// URL (subscribe with useSseProgress / useSseJobSlot).
+export const renderMusicVideoExcerpt = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/excerpt`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+export const musicVideoExcerptRenderEventsUrl = (jobId) =>
+ `/api/music-video/excerpt/${encodeURIComponent(jobId)}/events`;
+export const cancelMusicVideoExcerptRender = (jobId, options = {}) =>
+ request(`/music-video/excerpt/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });
+export const deleteMusicVideoExcerpt = (id, excerptId, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/excerpt/${encodeURIComponent(excerptId)}`, { method: 'DELETE', ...options });
+// Body: { atSec, note, verdict? } → { project, note }.
+export const addMusicVideoExcerptNote = (id, excerptId, body, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/excerpt/${encodeURIComponent(excerptId)}/notes`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+// Body: any of { atSec, note, verdict } → { project, note }.
+export const updateMusicVideoExcerptNote = (id, excerptId, noteId, body, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/excerpt/${encodeURIComponent(excerptId)}/notes/${encodeURIComponent(noteId)}`, {
+ method: 'PATCH', body: JSON.stringify(body), ...options,
+ });
+export const deleteMusicVideoExcerptNote = (id, excerptId, noteId, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/excerpt/${encodeURIComponent(excerptId)}/notes/${encodeURIComponent(noteId)}`, {
+ method: 'DELETE', ...options,
+ });
+
// ---- Pre-production treatment (#8980) ----
// A structured brief, a compiled whole-song arc, per-shot direction keyed to the
// board's scene ids and a proof checklist. Every write names the treatment
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index c34b6983a3..853f04c94c 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -350,6 +350,30 @@ export const musicVideoTreatmentProofReviewSchema = z.object({
}).strict().optional(),
}).strict();
+// ---- Draft excerpt render (#8986) -------------------------------------------
+// A director-chosen `[startSec, endSec)` window re-rendered through the same
+// composed pipeline as a full render, plus a cut/cue contact sheet and
+// timecoded review notes against the excerpt's OWN timeline (0 = its start).
+// See services/musicVideo/excerpt.js / excerptRender.js.
+export const MUSIC_VIDEO_EXCERPT_NOTE_VERDICTS = ['flagged', 'approved'];
+
+export const musicVideoExcerptRequestSchema = z.object({
+ startSec: z.number().min(0).max(36000),
+ endSec: z.number().min(0).max(36000),
+}).strict().refine((r) => r.endSec > r.startSec, { message: 'endSec must be greater than startSec' });
+
+export const musicVideoExcerptNoteSchema = z.object({
+ atSec: z.number().min(0).max(36000),
+ note: z.string().min(1).max(2000),
+ verdict: z.enum(MUSIC_VIDEO_EXCERPT_NOTE_VERDICTS).nullable().optional(),
+}).strict();
+
+export const musicVideoExcerptNoteUpdateSchema = z.object({
+ atSec: z.number().min(0).max(36000).optional(),
+ note: z.string().min(1).max(2000).optional(),
+ verdict: z.enum(MUSIC_VIDEO_EXCERPT_NOTE_VERDICTS).nullable().optional(),
+}).strict().refine((r) => r.atSec !== undefined || r.note !== undefined || r.verdict !== undefined, { message: 'atSec, note or verdict is required' });
+
export const musicVideoProjectCreateSchema = z.object({
name: z.string().min(1).max(200),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 942c05606d..dec3ffeab4 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -29,6 +29,9 @@ import {
musicVideoTreatmentCompileSchema,
musicVideoTreatmentApplySchema,
musicVideoTreatmentProofReviewSchema,
+ musicVideoExcerptRequestSchema,
+ musicVideoExcerptNoteSchema,
+ musicVideoExcerptNoteUpdateSchema,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
@@ -63,6 +66,8 @@ import {
} from '../services/audioMidiTranscription.js';
import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';
import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';
+import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';
+import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';
import { planProject } from '../services/musicVideo/planner.js';
import { parseLyricCues } from '../services/musicVideo/timedText.js';
import {
@@ -326,6 +331,46 @@ router.post('/render/:jobId/cancel', (req, res) => {
res.json({ ok: cancelRender(req.params.jobId) });
});
+// --- Draft excerpt render (#8986) ---
+// A director-chosen [startSec, endSec) window re-rendered through the same
+// composed pipeline, plus a cut/cue contact sheet and timecoded review notes.
+// Kickoff returns { jobId, excerptId }; progress streams over SSE (mirrors the
+// full render above) on its OWN job map, so an excerpt draft and a full render
+// can run at once without contending for the same mutex.
+router.post('/:id/excerpt', asyncHandler(async (req, res) => {
+ const { startSec, endSec } = validateRequest(musicVideoExcerptRequestSchema, req.body);
+ res.json(await startExcerptRender(req.params.id, { startSec, endSec }));
+}));
+
+router.get('/excerpt/:jobId/events', (req, res) => {
+ const ok = attachExcerptRenderSseClient(req.params.jobId, res);
+ if (!ok) throw new ServerError('Excerpt render job not found or expired', { status: 404, code: 'NOT_FOUND' });
+});
+
+router.post('/excerpt/:jobId/cancel', (req, res) => {
+ res.json({ ok: cancelExcerptRender(req.params.jobId) });
+});
+
+router.delete('/:id/excerpt/:excerptId', asyncHandler(async (req, res) => {
+ res.json(await deleteExcerpt(req.params.id, req.params.excerptId));
+}));
+
+router.post('/:id/excerpt/:excerptId/notes', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoExcerptNoteSchema, req.body);
+ const { project, note } = await addReviewNote(req.params.id, req.params.excerptId, input);
+ res.status(201).json({ project, note });
+}));
+
+router.patch('/:id/excerpt/:excerptId/notes/:noteId', asyncHandler(async (req, res) => {
+ const patch = validateRequest(musicVideoExcerptNoteUpdateSchema, req.body);
+ const { project, note } = await editReviewNote(req.params.id, req.params.excerptId, req.params.noteId, patch);
+ res.json({ project, note });
+}));
+
+router.delete('/:id/excerpt/:excerptId/notes/:noteId', asyncHandler(async (req, res) => {
+ res.json(await deleteReviewNote(req.params.id, req.params.excerptId, req.params.noteId));
+}));
+
// --- Director scene board ---
router.post('/:id/scenes', asyncHandler(async (req, res) => {
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index 5ed607660b..e31a5e7424 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -45,6 +45,22 @@ vi.mock('../services/musicVideo/render.js', () => ({
cancelRender: vi.fn(() => true),
}));
+// Same posture for the draft excerpt render (#8986) — the route's job is to
+// validate + dispatch + stream; the ffmpeg/overlay pipeline is covered in
+// excerptRender.js's own tests, and note/delete persistence in
+// musicVideoExcerpt.test.js against the real file-backed store.
+vi.mock('../services/musicVideo/excerptRender.js', () => ({
+ startExcerptRender: vi.fn(async () => ({ jobId: 'mve-job-1', excerptId: 'mve-job-1' })),
+ attachExcerptRenderSseClient: vi.fn(() => true),
+ cancelExcerptRender: vi.fn(() => true),
+}));
+vi.mock('../services/musicVideo/excerptService.js', () => ({
+ deleteExcerpt: vi.fn(async (id) => ({ id })),
+ addReviewNote: vi.fn(async (id, excerptId, input) => ({ project: { id }, note: { id: 'mvn-1', ...input } })),
+ editReviewNote: vi.fn(async (id, excerptId, noteId, patch) => ({ project: { id }, note: { id: noteId, ...patch } })),
+ deleteReviewNote: vi.fn(async (id) => ({ id })),
+}));
+
// Mock the MuScriptor transcription service so the route test doesn't depend
// on a provisioned venv; the route's job is to validate + resolve + dispatch.
vi.mock('../services/audioMidiTranscription.js', () => ({
@@ -66,6 +82,8 @@ import * as svc from '../services/musicVideo/projects.js';
import { analyzeAudioFile, analyzeAudioFileManual } from '../services/musicVideo/audioAnalysis.js';
import { getTrack } from '../services/tracks/index.js';
import * as renderSvc from '../services/musicVideo/render.js';
+import * as excerptRenderSvc from '../services/musicVideo/excerptRender.js';
+import * as excerptSvc from '../services/musicVideo/excerptService.js';
import * as midiSvc from '../services/audioMidiTranscription.js';
import { planProject } from '../services/musicVideo/planner.js';
import musicVideoRoutes from './musicVideo.js';
@@ -523,4 +541,69 @@ describe('musicVideo routes', () => {
expect(r.status).toBe(404);
});
});
+
+ describe('draft excerpt render (#8986)', () => {
+ it('POST /:id/excerpt validates the range and dispatches to the excerpt render service', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/excerpt').send({ startSec: 10, endSec: 20 });
+ expect(r.status).toBe(200);
+ expect(excerptRenderSvc.startExcerptRender).toHaveBeenCalledWith('mv-1', { startSec: 10, endSec: 20 });
+ expect(r.body).toEqual({ jobId: 'mve-job-1', excerptId: 'mve-job-1' });
+ });
+
+ it('POST /:id/excerpt rejects a non-forward range before dispatching', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/excerpt').send({ startSec: 20, endSec: 10 });
+ expect(r.status).toBe(400);
+ expect(excerptRenderSvc.startExcerptRender).not.toHaveBeenCalled();
+ });
+
+ it('POST /excerpt/:jobId/cancel cancels the job', async () => {
+ const r = await request(app).post('/api/music-video/excerpt/mve-1/cancel').send({});
+ expect(r.status).toBe(200);
+ expect(excerptRenderSvc.cancelExcerptRender).toHaveBeenCalledWith('mve-1');
+ expect(r.body).toEqual({ ok: true });
+ });
+
+ it('GET /excerpt/:jobId/events 404s for an unknown job', async () => {
+ excerptRenderSvc.attachExcerptRenderSseClient.mockReturnValueOnce(false);
+ const r = await request(app).get('/api/music-video/excerpt/nope/events');
+ expect(r.status).toBe(404);
+ });
+
+ it('DELETE /:id/excerpt/:excerptId dispatches to the excerpt service', async () => {
+ const r = await request(app).delete('/api/music-video/mv-1/excerpt/mve-1');
+ expect(r.status).toBe(200);
+ expect(excerptSvc.deleteExcerpt).toHaveBeenCalledWith('mv-1', 'mve-1');
+ });
+
+ it('POST /:id/excerpt/:excerptId/notes validates and adds a review note', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/excerpt/mve-1/notes').send({ atSec: 3, note: 'lip-sync drifts here' });
+ expect(r.status).toBe(201);
+ expect(excerptSvc.addReviewNote).toHaveBeenCalledWith('mv-1', 'mve-1', { atSec: 3, note: 'lip-sync drifts here' });
+ expect(r.body.note).toMatchObject({ atSec: 3, note: 'lip-sync drifts here' });
+ });
+
+ it('POST /:id/excerpt/:excerptId/notes rejects a blank note', async () => {
+ const r = await request(app).post('/api/music-video/mv-1/excerpt/mve-1/notes').send({ atSec: 3, note: '' });
+ expect(r.status).toBe(400);
+ expect(excerptSvc.addReviewNote).not.toHaveBeenCalled();
+ });
+
+ it('PATCH /:id/excerpt/:excerptId/notes/:noteId edits a note', async () => {
+ const r = await request(app).patch('/api/music-video/mv-1/excerpt/mve-1/notes/mvn-1').send({ verdict: 'approved' });
+ expect(r.status).toBe(200);
+ expect(excerptSvc.editReviewNote).toHaveBeenCalledWith('mv-1', 'mve-1', 'mvn-1', { verdict: 'approved' });
+ });
+
+ it('PATCH /:id/excerpt/:excerptId/notes/:noteId rejects an empty patch', async () => {
+ const r = await request(app).patch('/api/music-video/mv-1/excerpt/mve-1/notes/mvn-1').send({});
+ expect(r.status).toBe(400);
+ expect(excerptSvc.editReviewNote).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /:id/excerpt/:excerptId/notes/:noteId dispatches to the excerpt service', async () => {
+ const r = await request(app).delete('/api/music-video/mv-1/excerpt/mve-1/notes/mvn-1');
+ expect(r.status).toBe(200);
+ expect(excerptSvc.deleteReviewNote).toHaveBeenCalledWith('mv-1', 'mve-1', 'mvn-1');
+ });
+ });
});
diff --git a/server/routes/musicVideoExcerpt.test.js b/server/routes/musicVideoExcerpt.test.js
new file mode 100644
index 0000000000..e7f3f7ac08
--- /dev/null
+++ b/server/routes/musicVideoExcerpt.test.js
@@ -0,0 +1,119 @@
+/**
+ * Music Video draft excerpt (#8986): review-note CRUD, deletion, and clone
+ * carry-over, exercised through the real router + excerptService.js +
+ * excerpt.js + the real file-backed project store. The ffmpeg render itself
+ * is out of scope here (mocked) — this covers what the acceptance criteria
+ * actually gate on: review notes surviving a reload and a clone, and a render
+ * in flight blocking deletion until it's cancelled.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import express from 'express';
+import { rmSync } 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-excerpt-route-test-');
+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));
+
+// The route's job here is CRUD dispatch against the persisted excerpt list;
+// the ffmpeg/overlay pipeline is unit-tested in render.test.js
+// (buildMusicVideoFfmpegArgs' `excerpt` option, excerptBoundaryTimes).
+vi.mock('../services/musicVideo/excerptRender.js', () => ({
+ startExcerptRender: vi.fn(),
+ attachExcerptRenderSseClient: vi.fn(() => true),
+ cancelExcerptRender: vi.fn(() => true),
+}));
+
+const { default: musicVideoRoutes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+
+const base = (id) => `/api/music-video/${id}`;
+
+beforeEach(() => {
+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });
+ vi.clearAllMocks();
+});
+afterAll(cleanupTempDataRoots);
+
+// Seed a project with one excerpt directly on the record — the render
+// pipeline that produces this shape is exercised elsewhere.
+async function projectWithExcerpt(excerptOverrides = {}) {
+ const project = await projects.createProject({ name: 'Example Video' });
+ const excerpt = {
+ id: 'mve-1', startSec: 10, endSec: 20, status: 'complete',
+ filename: 'music-video-excerpt-1.mp4', contactSheetFilename: 'music-video-excerpt-1-sheet.png',
+ error: null, notes: [], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ ...excerptOverrides,
+ };
+ const updated = await projects.updateProject(project.id, { excerpts: [excerpt] });
+ return { project: updated, excerptId: excerpt.id };
+}
+
+describe('draft excerpt review notes (#8986)', () => {
+ it('adds, edits and removes a timecoded note, surviving a reload', async () => {
+ const { project } = await projectWithExcerpt();
+
+ const added = await request(app).post(`${base(project.id)}/excerpt/mve-1/notes`).send({ atSec: 3.5, note: 'lip-sync drifts here', verdict: 'flagged' });
+ expect(added.status).toBe(201);
+ const noteId = added.body.note.id;
+ expect(added.body.note).toMatchObject({ atSec: 3.5, note: 'lip-sync drifts here', verdict: 'flagged' });
+
+ // Reload from the store — not the response body — proves persistence.
+ const reloaded = await projects.getProject(project.id);
+ expect(reloaded.excerpts[0].notes).toEqual([added.body.note]);
+
+ const edited = await request(app).patch(`${base(project.id)}/excerpt/mve-1/notes/${noteId}`).send({ verdict: 'approved' });
+ expect(edited.status).toBe(200);
+ expect(edited.body.note.verdict).toBe('approved');
+ expect(edited.body.note.note).toBe('lip-sync drifts here'); // untouched fields survive a partial edit
+
+ const removed = await request(app).delete(`${base(project.id)}/excerpt/mve-1/notes/${noteId}`);
+ expect(removed.status).toBe(200);
+ expect(removed.body.excerpts[0].notes).toEqual([]);
+ });
+
+ it('404s adding a note to an unknown excerpt', async () => {
+ const project = await projects.createProject({ name: 'Example Video' });
+ const r = await request(app).post(`${base(project.id)}/excerpt/nope/notes`).send({ atSec: 1, note: 'x' });
+ expect(r.status).toBe(404);
+ });
+
+ it('422s a timecode well past the excerpt\'s own duration', async () => {
+ const { project } = await projectWithExcerpt(); // 10s excerpt (startSec 10, endSec 20)
+ const r = await request(app).post(`${base(project.id)}/excerpt/mve-1/notes`).send({ atSec: 30, note: 'way past the end' });
+ expect(r.status).toBe(422);
+ });
+});
+
+describe('draft excerpt deletion (#8986)', () => {
+ it('removes a completed excerpt and its files', async () => {
+ const { project } = await projectWithExcerpt();
+ const r = await request(app).delete(`${base(project.id)}/excerpt/mve-1`);
+ expect(r.status).toBe(200);
+ expect(r.body.excerpts).toEqual([]);
+ });
+
+ it('refuses to delete an excerpt whose render is still in flight', async () => {
+ const { project } = await projectWithExcerpt({ status: 'rendering', filename: null, contactSheetFilename: null });
+ const r = await request(app).delete(`${base(project.id)}/excerpt/mve-1`);
+ expect(r.status).toBe(409);
+ const reloaded = await projects.getProject(project.id);
+ expect(reloaded.excerpts).toHaveLength(1); // untouched
+ });
+});
+
+describe('excerpts survive a clone (#8986 acceptance)', () => {
+ it('carries excerpts and their review notes onto the cloned project', async () => {
+ const { project } = await projectWithExcerpt({ notes: [{ id: 'mvn-1', atSec: 2, note: 'kept across clone', verdict: null, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' }] });
+ const cloned = await projects.cloneProject(project.id, {});
+ expect(cloned.excerpts).toEqual(project.excerpts);
+ });
+});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index fb72834e25..b60d7b8ef9 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -127,6 +127,7 @@ import { recoverStuckAutoRuns } from './pipeline/autoRunner.js';
import { recoverStuckAutopilots } from './pipeline/seriesAutopilot.js';
import { recoverInFlightProjects } from './creativeDirector/recovery.js';
import { recoverStuckMusicVideoRenders } from './musicVideo/render.js';
+import { recoverStuckMusicVideoExcerpts } from './musicVideo/excerptRender.js';
import { recoverInterruptedModels as recoverInterruptedThreejsModels } from './threejsModels/index.js';
import { recoverInterruptedModels as recoverInterruptedImageTo3dModels } from './imageTo3d/models.js';
import { startPolling } from './instances.js';
@@ -428,6 +429,7 @@ const startBackgroundServices = ({ spawnerReady, io }) => {
recoverStuckAutoRuns().catch(err => logBootstrapFailure('❌ Pipeline auto-run recovery failed', err));
recoverStuckAutopilots().catch(err => logBootstrapFailure('❌ Pipeline autopilot recovery failed', err));
recoverStuckMusicVideoRenders().catch(err => logBootstrapFailure('❌ Music Video recovery failed', err));
+ recoverStuckMusicVideoExcerpts().catch(err => logBootstrapFailure('❌ Music Video excerpt recovery failed', err));
// A provider child cannot survive a server restart. Make interrupted
// Three.js generations retryable; this is state recovery only, never a
// cold-bootstrap provider call.
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 4098f25a1b..5032e49475 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -176,6 +176,32 @@ export async function encodeReferenceContactSheet(videoPath, outputPath, { every
return { columns, rows, times };
}
+// Same phone-sized, six-across contact sheet as `encodeContactSheet`, but
+// sampling a REAL rendered video file at explicit `times` (seconds, relative
+// to the file's own start) rather than a browser composition or a uniform
+// step (#8986 — the excerpt render's cut/cue contact sheet from
+// `excerptBoundaryTimes` in services/musicVideo/render.js). `between(t,…)`
+// selects a small window around each target time rather than an exact frame
+// timestamp match, which floating-point frame times almost never hit exactly.
+export async function encodeFileContactSheetAtTimes(videoPath, outputPath, times, { width, height } = {}) {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new Error('ffmpeg not found on PATH');
+ if (!Array.isArray(times) || times.length === 0) throw new Error('encodeFileContactSheetAtTimes: no sample times');
+ const tileWidth = width && height && width < height ? 240 : 360;
+ const columns = Math.min(PROOF_COLUMNS, times.length);
+ const rows = Math.ceil(times.length / columns);
+ const eps = 0.05;
+ const selectExpr = times.map((t) => `between(t,${Math.max(0, t).toFixed(3)},${(t + eps).toFixed(3)})`).join('+');
+ const result = await runFfmpegProcess({
+ bin: ffmpeg,
+ args: ['-hide_banner', '-loglevel', 'error', '-i', videoPath, '-vf',
+ `select='${selectExpr}',scale=${tileWidth}:-2,tile=${columns}x${rows}:padding=4:color=black`,
+ '-vsync', 'vfr', '-frames:v', '1', '-y', outputPath],
+ });
+ if (!result.ok) throw new Error(`Excerpt contact sheet failed: ${result.reason}`);
+ return { columns, rows };
+}
+
// Source remains subject to the composition sandbox and launch privacy gate;
// only bounded PCM leaves the browser, never arbitrary paths or encoded files.
export async function synthesizeCompositionMusic(page, durationSec) {
diff --git a/server/services/musicVideo/excerpt.js b/server/services/musicVideo/excerpt.js
new file mode 100644
index 0000000000..4f04119e46
--- /dev/null
+++ b/server/services/musicVideo/excerpt.js
@@ -0,0 +1,146 @@
+/**
+ * Music Video — draft excerpt record transforms (#8986, part of #8966).
+ *
+ * A project may carry a list of `excerpts`: a director-chosen `[startSec, endSec)`
+ * window re-rendered at full quality through the same composed pipeline as a
+ * full render (see `render.js` `buildMusicVideoFfmpegArgs`'s `excerpt` option),
+ * plus a contact sheet sampled at the range's cut and cue boundaries and a set
+ * of timecoded review notes. Frame checks alone can't validate motion/audio
+ * sync, so the note timeline is the excerpt's OWN (0 = the excerpt's start) —
+ * the UI plays the excerpt alongside the sheet and lets the director drop a
+ * note at whatever moment they're watching.
+ *
+ * Peer sync: `excerpts` is an additive field on the whole-record LWW project
+ * body (same posture as `treatment`/`scene.direction`, #8980). An older peer
+ * stores it verbatim, carries it through its own edits (every mutator spreads
+ * the record), and never executes it (it has no excerpt render route to run
+ * against a project it receives), so no `musicVideoProjects` schema bump is
+ * needed.
+ *
+ * Every transform here is pure (project in, project out) so the I/O layer
+ * (`excerptService.js`, `excerptRender.js`) can run it under
+ * `mutateProjectRecord`'s write serialization without duplicating validation.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
+
+const MAX_NOTE_LEN = 2000;
+const MAX_EXCERPT_SEC = 3600;
+
+function excerptError(status, code, message, context) {
+ return new ServerError(message, { status, code, ...(context ? { context } : {}) });
+}
+
+/** The excerpt array on a project, tolerating a legacy record with none. */
+export const projectExcerpts = (project) => (Array.isArray(project?.excerpts) ? project.excerpts : []);
+
+/** Find one excerpt by id, or throw 404. */
+function findExcerpt(project, excerptId) {
+ const excerpt = projectExcerpts(project).find((e) => e.id === excerptId);
+ if (!excerpt) throw excerptError(404, 'NOT_FOUND', 'Excerpt not found');
+ return excerpt;
+}
+
+/**
+ * Add a new `status: 'rendering'` excerpt record to the project. Its `id`
+ * doubles as the render job id (one render at a time per excerpt) — the
+ * caller kicks off the ffmpeg job under that same id. Returns the updated
+ * project; the render job fills in `filename`/`contactSheetFilename` (or
+ * `error`) once the encode finishes.
+ */
+export function startExcerptOnProject(project, { startSec, endSec }, now = new Date().toISOString()) {
+ if (!(startSec >= 0) || !(endSec > startSec) || endSec > MAX_EXCERPT_SEC) {
+ throw excerptError(422, 'INVALID_EXCERPT_RANGE', 'endSec must be greater than startSec, and both within range');
+ }
+ const id = `mve-${randomUUID()}`;
+ const excerpt = {
+ id,
+ startSec,
+ endSec,
+ status: 'rendering',
+ jobId: id,
+ filename: null,
+ contactSheetFilename: null,
+ error: null,
+ notes: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+ return { project: { ...project, excerpts: [...projectExcerpts(project), excerpt] }, excerpt };
+}
+
+/** Merge a patch (status/filename/contactSheetFilename/error/jobId) onto one excerpt. */
+export function applyExcerptPatch(project, excerptId, patch, now = new Date().toISOString()) {
+ findExcerpt(project, excerptId); // 404 if missing
+ return {
+ ...project,
+ excerpts: projectExcerpts(project).map((e) => (e.id === excerptId ? { ...e, ...patch, updatedAt: now } : e)),
+ };
+}
+
+/**
+ * Drop one excerpt record. Throws 404 if it doesn't exist, or 409 while its
+ * render is still in flight (the caller cancels that job first). Returns
+ * `{ project, excerpt }` — the removed excerpt, so the caller can clean up its
+ * on-disk video/contact-sheet files.
+ */
+export function removeExcerptFromProject(project, excerptId) {
+ const excerpt = findExcerpt(project, excerptId); // 404 if missing
+ if (excerpt.status === 'rendering') {
+ throw excerptError(409, 'EXCERPT_RENDERING', 'Cancel the in-progress render before deleting this excerpt');
+ }
+ return { project: { ...project, excerpts: projectExcerpts(project).filter((e) => e.id !== excerptId) }, excerpt };
+}
+
+const clampAtSec = (atSec, excerpt) => {
+ if (typeof atSec !== 'number' || !Number.isFinite(atSec) || atSec < 0) {
+ throw excerptError(422, 'VALIDATION_ERROR', 'atSec must be a non-negative number');
+ }
+ const span = excerpt.endSec - excerpt.startSec;
+ // A small tolerance past the last frame — the player's own duration and the
+ // encoded file's can differ by a fraction of a frame.
+ if (atSec > span + 0.25) {
+ throw excerptError(422, 'VALIDATION_ERROR', `atSec must fall within the excerpt's own ${span.toFixed(2)}s duration`);
+ }
+ return Math.min(atSec, span);
+};
+
+/** Append a timecoded review note (0 = the excerpt's own start). */
+export function addExcerptNote(project, excerptId, { atSec, note, verdict = null }, now = new Date().toISOString()) {
+ const excerpt = findExcerpt(project, excerptId);
+ if (!isNonBlankStr(note)) throw excerptError(422, 'VALIDATION_ERROR', 'A review note needs text');
+ const record = { id: `mvn-${randomUUID()}`, atSec: clampAtSec(atSec, excerpt), note: trimTo(note, MAX_NOTE_LEN), verdict: verdict ?? null, createdAt: now, updatedAt: now };
+ const next = { ...excerpt, notes: [...excerpt.notes, record], updatedAt: now };
+ return { project: { ...project, excerpts: projectExcerpts(project).map((e) => (e.id === excerptId ? next : e)) }, note: record };
+}
+
+function findNote(excerpt, noteId) {
+ const note = (excerpt.notes || []).find((n) => n.id === noteId);
+ if (!note) throw excerptError(404, 'NOT_FOUND', 'Review note not found');
+ return note;
+}
+
+/** Edit a review note's text, timecode, and/or verdict. */
+export function updateExcerptNote(project, excerptId, noteId, patch, now = new Date().toISOString()) {
+ const excerpt = findExcerpt(project, excerptId);
+ const existing = findNote(excerpt, noteId);
+ const next = { ...existing, updatedAt: now };
+ if (patch.atSec !== undefined) next.atSec = clampAtSec(patch.atSec, excerpt);
+ if (patch.note !== undefined) {
+ if (!isNonBlankStr(patch.note)) throw excerptError(422, 'VALIDATION_ERROR', 'A review note needs text');
+ next.note = trimTo(patch.note, MAX_NOTE_LEN);
+ }
+ if (patch.verdict !== undefined) next.verdict = patch.verdict;
+ const nextExcerpt = { ...excerpt, notes: excerpt.notes.map((n) => (n.id === noteId ? next : n)), updatedAt: now };
+ return { project: { ...project, excerpts: projectExcerpts(project).map((e) => (e.id === excerptId ? nextExcerpt : e)) }, note: next };
+}
+
+/** Remove a review note. */
+export function removeExcerptNote(project, excerptId, noteId) {
+ const excerpt = findExcerpt(project, excerptId);
+ findNote(excerpt, noteId); // 404 if missing
+ const nextExcerpt = { ...excerpt, notes: excerpt.notes.filter((n) => n.id !== noteId) };
+ return { ...project, excerpts: projectExcerpts(project).map((e) => (e.id === excerptId ? nextExcerpt : e)) };
+}
diff --git a/server/services/musicVideo/excerpt.test.js b/server/services/musicVideo/excerpt.test.js
new file mode 100644
index 0000000000..51fd3f9c43
--- /dev/null
+++ b/server/services/musicVideo/excerpt.test.js
@@ -0,0 +1,120 @@
+import { describe, it, expect } from 'vitest';
+import {
+ startExcerptOnProject,
+ applyExcerptPatch,
+ removeExcerptFromProject,
+ addExcerptNote,
+ updateExcerptNote,
+ removeExcerptNote,
+ projectExcerpts,
+} from './excerpt.js';
+
+const project = (over = {}) => ({ id: 'mv-1', name: 'Example Video', ...over });
+const findExcerpt = (proj, excerptId) => projectExcerpts(proj).find((e) => e.id === excerptId);
+
+describe('startExcerptOnProject (#8986)', () => {
+ it('appends a status: rendering excerpt whose id doubles as the job id', () => {
+ const { project: next, excerpt } = startExcerptOnProject(project(), { startSec: 10, endSec: 15 });
+ expect(excerpt.status).toBe('rendering');
+ expect(excerpt.jobId).toBe(excerpt.id);
+ expect(excerpt.startSec).toBe(10);
+ expect(excerpt.endSec).toBe(15);
+ expect(excerpt.notes).toEqual([]);
+ expect(projectExcerpts(next)).toEqual([excerpt]);
+ });
+
+ it('rejects a non-forward range', () => {
+ expect(() => startExcerptOnProject(project(), { startSec: 10, endSec: 10 })).toThrow(/endSec/);
+ expect(() => startExcerptOnProject(project(), { startSec: 10, endSec: 5 })).toThrow(/endSec/);
+ });
+
+ it('preserves any existing excerpts', () => {
+ const { project: withOne, excerpt: first } = startExcerptOnProject(project(), { startSec: 0, endSec: 5 });
+ const { project: withTwo } = startExcerptOnProject(withOne, { startSec: 5, endSec: 10 });
+ expect(projectExcerpts(withTwo)).toHaveLength(2);
+ expect(projectExcerpts(withTwo)[0]).toEqual(first);
+ });
+});
+
+describe('applyExcerptPatch', () => {
+ it('merges a patch onto the named excerpt only, bumping updatedAt', () => {
+ const { project: seeded, excerpt } = startExcerptOnProject(project(), { startSec: 0, endSec: 5 });
+ const patched = applyExcerptPatch(seeded, excerpt.id, { status: 'complete', filename: 'out.mp4' });
+ const found = findExcerpt(patched, excerpt.id);
+ expect(found.status).toBe('complete');
+ expect(found.filename).toBe('out.mp4');
+ });
+
+ it('404s on an unknown excerpt id', () => {
+ expect(() => applyExcerptPatch(project({ excerpts: [] }), 'nope', { status: 'error' })).toThrow(/not found/i);
+ });
+});
+
+describe('removeExcerptFromProject', () => {
+ it('drops the excerpt and returns it for on-disk cleanup', () => {
+ const { project: seeded, excerpt } = startExcerptOnProject(project(), { startSec: 0, endSec: 5 });
+ const complete = applyExcerptPatch(seeded, excerpt.id, { status: 'complete', filename: 'out.mp4' });
+ const { project: next, excerpt: removed } = removeExcerptFromProject(complete, excerpt.id);
+ expect(projectExcerpts(next)).toEqual([]);
+ expect(removed.filename).toBe('out.mp4');
+ });
+
+ it('refuses to remove an excerpt whose render is still in flight', () => {
+ const { project: seeded, excerpt } = startExcerptOnProject(project(), { startSec: 0, endSec: 5 });
+ expect(() => removeExcerptFromProject(seeded, excerpt.id)).toThrow(/cancel/i);
+ });
+});
+
+describe('review notes', () => {
+ function seededExcerpt() {
+ const { project: seeded, excerpt } = startExcerptOnProject(project(), { startSec: 10, endSec: 20 }); // 10s excerpt
+ return { project: applyExcerptPatch(seeded, excerpt.id, { status: 'complete', filename: 'out.mp4' }), excerptId: excerpt.id };
+ }
+
+ it('adds a timecoded note against the excerpt\'s own timeline', () => {
+ const { project, excerptId } = seededExcerpt();
+ const { project: next, note } = addExcerptNote(project, excerptId, { atSec: 3.5, note: 'lip-sync drifts here', verdict: 'flagged' });
+ expect(note.atSec).toBe(3.5);
+ expect(note.verdict).toBe('flagged');
+ expect(findExcerpt(next, excerptId).notes).toEqual([note]);
+ });
+
+ it('rejects a blank note', () => {
+ const { project, excerptId } = seededExcerpt();
+ expect(() => addExcerptNote(project, excerptId, { atSec: 1, note: ' ' })).toThrow(/text/i);
+ });
+
+ it('rejects a timecode well past the excerpt\'s own duration', () => {
+ const { project, excerptId } = seededExcerpt();
+ expect(() => addExcerptNote(project, excerptId, { atSec: 11, note: 'past the end' })).toThrow(/duration/i);
+ });
+
+ it('tolerates a timecode a fraction of a second past the end (encoder/player rounding)', () => {
+ const { project, excerptId } = seededExcerpt();
+ const { note } = addExcerptNote(project, excerptId, { atSec: 10.1, note: 'right at the last frame' });
+ expect(note.atSec).toBe(10); // clamped to the excerpt's own span
+ });
+
+ it('edits a note\'s text/verdict and can clear the verdict back to null', () => {
+ const { project, excerptId } = seededExcerpt();
+ const { project: withNote, note } = addExcerptNote(project, excerptId, { atSec: 2, note: 'first pass' });
+ const { note: edited } = updateExcerptNote(withNote, excerptId, note.id, { note: 'resolved on re-render', verdict: 'approved' });
+ expect(edited.note).toBe('resolved on re-render');
+ expect(edited.verdict).toBe('approved');
+ const { note: cleared } = updateExcerptNote(withNote, excerptId, note.id, { verdict: null });
+ expect(cleared.verdict).toBeNull();
+ });
+
+ it('removes a note', () => {
+ const { project, excerptId } = seededExcerpt();
+ const { project: withNote, note } = addExcerptNote(project, excerptId, { atSec: 2, note: 'first pass' });
+ const next = removeExcerptNote(withNote, excerptId, note.id);
+ expect(findExcerpt(next, excerptId).notes).toEqual([]);
+ });
+
+ it('404s editing/removing an unknown note', () => {
+ const { project, excerptId } = seededExcerpt();
+ expect(() => updateExcerptNote(project, excerptId, 'nope', { note: 'x' })).toThrow(/not found/i);
+ expect(() => removeExcerptNote(project, excerptId, 'nope')).toThrow(/not found/i);
+ });
+});
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
new file mode 100644
index 0000000000..d1352c7730
--- /dev/null
+++ b/server/services/musicVideo/excerptRender.js
@@ -0,0 +1,272 @@
+/**
+ * Music Video — draft excerpt render (#8986, part of #8966).
+ *
+ * Renders a director-chosen `[startSec, endSec)` window through the SAME
+ * composed pipeline as a full render (`planMusicVideoRender` +
+ * `buildMusicVideoFfmpegArgs` in `render.js`), then samples a contact sheet at
+ * every cut and typography-cue boundary the window contains
+ * (`excerptBoundaryTimes` + `encodeFileContactSheetAtTimes`). A frame check
+ * alone can't validate motion/audio sync, so the excerpt file itself is the
+ * primary artifact — the contact sheet is a quick-scan companion, and its
+ * failure doesn't fail the excerpt.
+ *
+ * Mirrors render.js's job/SSE/cancel machinery on a SEPARATE job map and
+ * per-project mutex: an excerpt draft and a full render are different
+ * artifacts writing different output files, so nothing stops a director
+ * running both — the mutex here only rejects a duplicate excerpt render on
+ * the SAME project while one is already in flight.
+ */
+
+import { unlink } from 'fs/promises';
+import { join } from 'path';
+import { ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { spawn } from '../../lib/childProcess.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { encodeFileContactSheetAtTimes } from '../htmlComposition/encode.js';
+import { getProject, listProjects, mutateProjectRecord } from './projects.js';
+import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes } from './render.js';
+import { renderableCues, sectionCardCues } from './composition.js';
+import { renderTypographyOverlays, removeCompositionScratch } from './compositionRender.js';
+import { startExcerptOnProject, applyExcerptPatch } from './excerpt.js';
+
+const jobs = new Map();
+const projectExcerptRenders = new Map();
+const PENDING = Symbol('mv-excerpt-render-pending');
+
+export const attachExcerptRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+export function cancelExcerptRender(jobId) {
+ const job = jobs.get(jobId);
+ if (!job) return false;
+ if (!job.process) {
+ if (job.status !== 'running' || !job.overlayAbort || job.overlayAbort.signal.aborted) return false;
+ job.overlayAbort.abort(new Error('Excerpt render cancelled'));
+ return true;
+ }
+ const proc = job.process;
+ killWithEscalation(proc, { label: 'music-video excerpt render', stillRunning: () => job.process === proc });
+ return true;
+}
+
+/** Kick off a draft excerpt render. Returns `{ jobId, excerptId }`. */
+export async function startExcerptRender(projectId, { startSec, endSec }) {
+ const project = await getProject(projectId);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+
+ const existingJob = projectExcerptRenders.get(projectId);
+ if (existingJob && (existingJob === PENDING || jobs.has(existingJob))) {
+ throw new ServerError('An excerpt render is already in progress for this project', {
+ status: 409, code: 'EXCERPT_RENDER_IN_PROGRESS', context: { jobId: existingJob === PENDING ? null : existingJob },
+ });
+ }
+ projectExcerptRenders.set(projectId, PENDING);
+
+ let handedOff = false;
+ try {
+ const { ffmpeg, audioPath, composed, clips, audioDurationSec } = await planMusicVideoRender(project);
+ await ensureDir(PATHS.videos);
+ await ensureDir(PATHS.videoThumbnails);
+
+ // A probe pass (no `excerpt` option) gets the full-song plan's canonical
+ // dims/fps/sections/cues in ABSOLUTE song time — the coordinate space
+ // `startSec`/`endSec` and `excerptBoundaryTimes` are given in.
+ const probe = buildMusicVideoFfmpegArgs(clips, audioPath, join(PATHS.videos, 'probe.mp4'), { audioDurationSec, frameGrid: composed });
+ if (!(startSec >= 0) || !(endSec > startSec) || endSec > probe.totalDuration + 1e-6) {
+ throw new ServerError(
+ `The excerpt range must fall within the project's ${probe.totalDuration.toFixed(2)}s render`,
+ { status: 422, code: 'INVALID_EXCERPT_RANGE', context: { totalDuration: probe.totalDuration } },
+ );
+ }
+ const endClamped = Math.min(endSec, probe.totalDuration);
+
+ // Persist the new `status: 'rendering'` excerpt against the FRESHEST
+ // record (not the `project` snapshot planning read above), so a
+ // concurrent note/edit on another excerpt can't be clobbered.
+ const { excerpt } = await mutateProjectRecord(projectId, (current) => startExcerptOnProject(current, { startSec, endSec: endClamped }));
+ const excerptId = excerpt.id;
+ const jobId = excerptId;
+ const filename = `music-video-excerpt-${projectId.slice(0, 8)}-${Date.now()}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+
+ // Only the cue/card windows overlapping the window are worth capturing —
+ // typography outside it never survives the final trim.
+ const allCues = composed
+ ? [...renderableCues(project.composition, probe.totalDuration), ...sectionCardCues(clips, probe.sections, probe.totalDuration)]
+ .sort((a, b) => a.startSec - b.startSec)
+ : [];
+ const cues = allCues.filter((c) => c.startSec < endClamped && c.endSec > startSec);
+ const composition = cues.length > 0 ? project.composition : null;
+
+ const totalDuration = endClamped - startSec;
+ const job = { id: jobId, projectId, excerptId, status: 'running', clients: [], process: null, totalDuration };
+ jobs.set(jobId, job);
+ projectExcerptRenders.set(projectId, jobId);
+ handedOff = true;
+
+ console.log(`🎬 Rendering music-video excerpt [${jobId.slice(4, 12)}]: project=${projectId.slice(0, 8)} range=[${startSec.toFixed(2)},${endClamped.toFixed(2)}]s clips=${clips.length} cues=${cues.length}`);
+
+ const finalize = async (patch) => {
+ projectExcerptRenders.delete(projectId);
+ await mutateProjectRecord(projectId, (current) => ({ project: applyExcerptPatch(current, excerptId, patch) })).catch((err) => {
+ console.error(`❌ Music-video excerpt render [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);
+ });
+ if (composition) await removeCompositionScratch(jobId).catch((err) => {
+ console.warn(`⚠️ Music-video excerpt render [${jobId.slice(4, 12)}] could not remove its overlay scratch: ${err.message}`);
+ });
+ closeJobAfterDelay(jobs, jobId);
+ };
+
+ // A cut/cue contact sheet is a best-effort companion artifact — its
+ // failure never fails an excerpt whose video encoded successfully.
+ const buildContactSheet = async () => {
+ try {
+ const times = excerptBoundaryTimes(probe.sections, cues, startSec, endClamped);
+ const sheetFilename = `${filename.replace(/\.mp4$/, '')}-sheet.png`;
+ await encodeFileContactSheetAtTimes(outputPath, join(PATHS.videoThumbnails, sheetFilename), times, { width: probe.canonW, height: probe.canonH });
+ return sheetFilename;
+ } catch (err) {
+ console.warn(`⚠️ Music-video excerpt render [${jobId.slice(4, 12)}] contact sheet failed: ${err.message}`);
+ return null;
+ }
+ };
+
+ const startEncode = (encodeArgs, progressBase = 0) => {
+ const encodeProgress = (fraction) => progressBase + (1 - progressBase) * fraction;
+ const proc = spawn(ffmpeg, encodeArgs, safeChildProcessOptions({ 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: encodeProgress(Math.min(1, (us / 1_000_000) / totalDuration)) });
+ }
+ } else if (key === 'progress' && val === 'end') {
+ broadcastSse(job, { type: 'progress', progress: 1 });
+ }
+ }
+ });
+
+ attachFfmpegRenderGuard(proc, {
+ label: `Music-video excerpt render [${jobId.slice(4, 12)}]`,
+ onProcessError: (err) => {
+ job.lastError = `ffmpeg process error: ${err.message}`;
+ console.log(`⚠️ Music-video excerpt render post-spawn error [${jobId.slice(4, 12)}]: ${err.message}`);
+ },
+ onSpawnError: async (err) => {
+ job.process = null;
+ job.status = 'error';
+ const reason = `Failed to spawn ffmpeg: ${err.message}`;
+ job.lastError = reason;
+ console.error(`❌ Music-video excerpt render spawn error [${jobId.slice(4, 12)}]: ${reason}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ await finalize({ status: 'error', error: reason, filename: null, jobId: null });
+ },
+ onClose: 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;
+ const logClose = canceled ? console.log : console.error;
+ logClose(`${canceled ? '🛑' : '❌'} Music-video excerpt render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(4, 12)}]: ${reason}`);
+ // #8986 acceptance: cancelling an excerpt removes its partial output.
+ await unlink(outputPath).catch(() => {});
+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
+ await finalize({ status: canceled ? 'canceled' : 'error', error: canceled ? null : reason, filename: null, jobId: null });
+ return;
+ }
+ try {
+ job.status = 'complete';
+ const contactSheetFilename = await buildContactSheet();
+ await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null });
+ console.log(`✅ Music-video excerpt rendered [${jobId.slice(4, 12)}]: ${filename}`);
+ broadcastSse(job, { type: 'complete', result: { excerptId, filename, path: `/data/videos/${filename}`, contactSheetFilename, contactSheetPath: contactSheetFilename ? `/data/video-thumbnails/${contactSheetFilename}` : null } });
+ } catch (err) {
+ job.status = 'error';
+ job.lastError = `Finalize failed: ${err.message}`;
+ console.error(`❌ Music-video excerpt render finalize failed [${jobId.slice(4, 12)}]: ${err.message}`);
+ broadcastSse(job, { type: 'error', error: 'Excerpt render finalize failed' });
+ await finalize({ status: 'error', error: 'Finalize failed', filename: null, jobId: null });
+ }
+ },
+ });
+ };
+
+ if (!composition) {
+ const { args } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, excerpt: { startSec, endSec: endClamped } });
+ startEncode(args);
+ return { jobId, excerptId };
+ }
+
+ job.overlayAbort = new AbortController();
+ const { signal } = job.overlayAbort;
+ // Clamp each cue's capture start to the excerpt window: a title-card cue
+ // (#8985) can span a whole song section, and capturing it from its TRUE
+ // start would re-render everything before the window too, defeating the
+ // point of a fast draft preview. The final `[outv]` trim below discards
+ // anything before `startSec` anyway, so nothing visible is lost.
+ const captureCues = cues.map((c) => ({ ...c, startSec: Math.max(c.startSec, startSec) }));
+ renderTypographyOverlays({
+ jobId, cues: captureCues, style: composition.style, width: probe.canonW, height: probe.canonH, fps: probe.fps, durationSec: endClamped, signal,
+ onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: 0.5 * fraction }),
+ }).then((overlays) => {
+ signal.throwIfAborted();
+ job.overlayAbort = null;
+ const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, excerpt: { startSec, endSec: endClamped } });
+ startEncode(layered.args, 0.5);
+ }).catch(async (err) => {
+ const canceled = signal.aborted;
+ job.status = canceled ? 'canceled' : 'error';
+ const reason = canceled ? 'Render cancelled' : `Typography overlay failed: ${err.message}`;
+ job.lastError = reason;
+ const log = canceled ? console.log : console.error;
+ log(`${canceled ? '🛑' : '❌'} Music-video excerpt render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(4, 12)}]: ${reason}`);
+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
+ await finalize({ status: canceled ? 'canceled' : 'error', error: canceled ? null : reason, filename: null, jobId: null });
+ });
+
+ return { jobId, excerptId };
+ } finally {
+ if (!handedOff) projectExcerptRenders.delete(projectId);
+ }
+}
+
+// Boot recovery: like recoverStuckMusicVideoRenders in render.js, no excerpt
+// render survives a restart — the job map is memory-only. Demote any excerpt
+// left `status: 'rendering'` with no live job to `error` so it isn't shown as
+// perpetually in-flight (and its slot doesn't 409 every later excerpt render
+// on that project).
+export async function recoverStuckMusicVideoExcerpts() {
+ const projects = await listProjects();
+ let recovered = 0;
+ for (const project of projects) {
+ const stuck = (project.excerpts || []).filter((e) => e.status === 'rendering' && !projectExcerptRenders.has(project.id));
+ if (stuck.length === 0) continue;
+ await mutateProjectRecord(project.id, (current) => {
+ let next = current;
+ for (const excerpt of stuck) {
+ next = { ...next, excerpts: (next.excerpts || []).map((e) => (e.id === excerpt.id ? { ...e, status: 'error', error: 'Interrupted by a server restart', jobId: null } : e)) };
+ }
+ return { project: next };
+ }).then(() => { recovered += stuck.length; }, (err) => {
+ console.error(`❌ Music Video excerpt recovery: project ${project.id.slice(0, 8)} write failed: ${err.message}`);
+ });
+ }
+ if (recovered > 0) console.log(`🎬 Music Video excerpt boot recovery: demoted ${recovered} stuck excerpt render(s)`);
+}
diff --git a/server/services/musicVideo/excerptService.js b/server/services/musicVideo/excerptService.js
new file mode 100644
index 0000000000..c99169ede4
--- /dev/null
+++ b/server/services/musicVideo/excerptService.js
@@ -0,0 +1,49 @@
+/**
+ * Music Video — draft excerpt CRUD (#8986): review-note edits and excerpt
+ * deletion over the pure transforms in `excerpt.js`. Kickoff/cancel of the
+ * ffmpeg render itself lives in `excerptRender.js` — this file only touches
+ * the persisted record plus the render's output files.
+ *
+ * Every write goes through `mutateProjectRecord`, so it runs against the
+ * freshest record under the backend's write serialization (mirrors
+ * treatmentService.js).
+ */
+
+import { unlink } from 'fs/promises';
+import { PATHS } from '../../lib/fileUtils.js';
+import { safeUnder } from '../../lib/ffmpeg.js';
+import { mutateProjectRecord } from './projects.js';
+import {
+ addExcerptNote,
+ removeExcerptFromProject,
+ removeExcerptNote,
+ updateExcerptNote,
+} from './excerpt.js';
+
+/** Remove an excerpt and its rendered files. Refuses while its render is in flight. */
+export async function deleteExcerpt(id, excerptId) {
+ const { project, excerpt } = await mutateProjectRecord(id, (current) => removeExcerptFromProject(current, excerptId));
+ await Promise.all([
+ excerpt.filename ? unlink(safeUnder(PATHS.videos, excerpt.filename) || '').catch(() => {}) : null,
+ excerpt.contactSheetFilename ? unlink(safeUnder(PATHS.videoThumbnails, excerpt.contactSheetFilename) || '').catch(() => {}) : null,
+ ]);
+ return project;
+}
+
+/** Add a timecoded review note to an excerpt. */
+export async function addReviewNote(id, excerptId, input) {
+ const { project, note } = await mutateProjectRecord(id, (current) => addExcerptNote(current, excerptId, input));
+ return { project, note };
+}
+
+/** Edit a review note's text, timecode, and/or verdict. */
+export async function editReviewNote(id, excerptId, noteId, patch) {
+ const { project, note } = await mutateProjectRecord(id, (current) => updateExcerptNote(current, excerptId, noteId, patch));
+ return { project, note };
+}
+
+/** Remove a review note. */
+export async function deleteReviewNote(id, excerptId, noteId) {
+ const { project } = await mutateProjectRecord(id, (current) => ({ project: removeExcerptNote(current, excerptId, noteId) }));
+ return project;
+}
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 5bf128a23f..a4e6982b06 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -364,7 +364,17 @@ function sectionChain(c, input, { canonW, canonH, fps, frames, frameGrid }) {
// song-time boundary, so the edit never drifts more than half a frame from the
// authored timeline however many sections it has. Returns `sections`, each
// section's `[startSec, endSec)` on the output timebase.
-export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false } = {}) {
+//
+// `excerpt` (#8986 — a draft excerpt render) windows the SAME full-song plan
+// down to `[startSec, endSec)` with one extra filter stage after the cut/overlay
+// chain is built: `trim`/`atrim` the finished `[outv]`/audio down to the window
+// and re-zero their timestamps, so a footage cut and every overlay keep the
+// exact absolute song-time alignment they'd have in a full render — only the
+// output's first/last frame move. `sections` reports only the spans that
+// overlap the window, clipped to it and re-based to the excerpt's own timeline
+// (0 = `startSec`) so a contact sheet built from the excerpt file can sample
+// cut boundaries directly. `totalDuration` becomes the excerpt's own length.
+export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false, excerpt = null } = {}) {
if (!Array.isArray(clips) || clips.length === 0) throw new Error('buildMusicVideoFfmpegArgs: empty clips');
const frameGrid = gridOption || clips.some((c) => c.layer);
// Stills and cards have no dimensions of their own: the first footage clip
@@ -423,14 +433,31 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
});
const videoTotal = plan[plan.length - 1].endSec;
- const totalDuration = audioDurationSec != null ? Math.min(videoTotal, audioDurationSec) : videoTotal;
- const sections = plan.map(({ c, startSec, endSec }) => ({ sceneId: c.sceneId, layer: c.layer || 'footage', startSec, endSec }));
+ const fullDuration = audioDurationSec != null ? Math.min(videoTotal, audioDurationSec) : videoTotal;
+
+ let videoMap = '[outv]';
+ let audioMap = `${audioIdx}:a`;
+ let totalDuration = fullDuration;
+ let sections = plan.map(({ c, startSec, endSec }) => ({ sceneId: c.sceneId, layer: c.layer || 'footage', startSec, endSec }));
+
+ if (excerpt) {
+ const excerptStart = Math.max(0, Math.min(excerpt.startSec, fullDuration));
+ const excerptEnd = Math.max(excerptStart, Math.min(excerpt.endSec, fullDuration));
+ filters.push(`[outv]trim=start=${excerptStart}:end=${excerptEnd},setpts=PTS-STARTPTS[outvx]`);
+ filters.push(`[${audioIdx}:a]atrim=start=${excerptStart}:end=${excerptEnd},asetpts=PTS-STARTPTS[outax]`);
+ videoMap = '[outvx]';
+ audioMap = '[outax]';
+ totalDuration = excerptEnd - excerptStart;
+ sections = sections
+ .filter((s) => s.startSec < excerptEnd && s.endSec > excerptStart)
+ .map((s) => ({ ...s, startSec: Math.max(0, s.startSec - excerptStart), endSec: Math.min(totalDuration, s.endSec - excerptStart) }));
+ }
const args = [
...inputs,
'-filter_complex', filters.join(';'),
- '-map', '[outv]',
- '-map', `${audioIdx}:a`,
+ '-map', videoMap,
+ '-map', audioMap,
'-c:v', 'libx264',
'-preset', 'veryfast',
'-crf', '18',
@@ -446,6 +473,65 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
return { args, totalDuration, canonW, canonH, fps, sections };
}
+// Pure: every cut and typography-cue boundary that falls inside
+// `[startSec, endSec)`, re-based to the excerpt's own timeline (0 = `startSec`)
+// and deduplicated — the sample times for the excerpt's contact sheet (#8986).
+// `sections`/`cues` are given in ABSOLUTE song time (as `buildMusicVideoFfmpegArgs`
+// returns them pre-excerpt, or as `renderableCues`/`sectionCardCues` compute
+// them). Always includes both ends of the window so the sheet covers the first
+// and last frame even when no cut/cue lands exactly on them.
+export function excerptBoundaryTimes(sections, cues, startSec, endSec) {
+ const span = endSec - startSec;
+ const times = new Set([0, span]);
+ const add = (t) => {
+ if (typeof t !== 'number' || !Number.isFinite(t)) return;
+ if (t >= startSec - 1e-9 && t <= endSec + 1e-9) times.add(round3(Math.min(span, Math.max(0, t - startSec))));
+ };
+ for (const s of Array.isArray(sections) ? sections : []) { add(s.startSec); add(s.endSec); }
+ for (const c of Array.isArray(cues) ? cues : []) { add(c.startSec); add(c.endSec); }
+ return Array.from(times).sort((a, b) => a - b);
+}
+
+// Shared prep for both the full render and the draft excerpt render (#8986):
+// resolve the master audio, refuse a stale performance take, resolve + snap
+// every scene's clip, and refuse a render whose shots don't cover their
+// authored span. Both callers build on the exact same resolved clip list, so
+// an excerpt frame matches what a full render would produce at that song time.
+export async function planMusicVideoRender(project) {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
+
+ const audioPath = await resolveMasterAudioPath(project);
+ // #8977: a performance take sings one stretch of one recording. If the
+ // scene was re-timed or the song replaced since, its mouth motion no longer
+ // matches the audio under it — refuse rather than render it out of sync.
+ const stale = await findStalePerformanceTakes(project, audioPath);
+ if (stale.length > 0) {
+ throw new ServerError(
+ `${stale.length} performance shot${stale.length === 1 ? ' has' : 's have'} no lip-synced take of the current song interval and recording — regenerate ${stale.length === 1 ? 'it' : 'them'}, or switch to Cutaway, before rendering`,
+ { status: 422, code: 'STALE_PERFORMANCE_TAKES', context: { stale } },
+ );
+ }
+ // #8985: a composed render cuts still and card sections into the same
+ // timebase as the footage; plain concat renders footage only, as before.
+ const composed = project.composition?.mode === 'composed';
+ const rawClips = await resolveSceneClips(project, { layered: composed });
+ const audioDurationSec = await probeVideoDuration(audioPath).catch(() => null);
+ const beats = project.audioAnalysis?.beats;
+ const clips = beatSnapClips(rawClips, beats, { scenes: project.scenes });
+ // #8964: a new (non-looping) shot must never silently repeat footage to
+ // fill its span. Refuse the render and name the shots that need a trim,
+ // a continuation, a replacement clip, or an explicit loop.
+ const shortfalls = findCoverageShortfalls(clips);
+ if (shortfalls.length > 0) {
+ throw new ServerError(
+ `${shortfalls.length} shot${shortfalls.length === 1 ? ' is' : 's are'} longer than ${shortfalls.length === 1 ? 'its' : 'their'} source clip — trim, continue, replace, or loop ${shortfalls.length === 1 ? 'it' : 'them'} before rendering`,
+ { status: 422, code: 'INSUFFICIENT_CLIP_COVERAGE', context: { shortfalls, resolutions: COVERAGE_RESOLUTIONS } },
+ );
+ }
+ return { ffmpeg, audioPath, composed, clips, audioDurationSec };
+}
+
export async function renderMusicVideo(projectId) {
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -463,37 +549,7 @@ export async function renderMusicVideo(projectId) {
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);
- // #8977: a performance take sings one stretch of one recording. If the
- // scene was re-timed or the song replaced since, its mouth motion no longer
- // matches the audio under it — refuse rather than render it out of sync.
- const stale = await findStalePerformanceTakes(project, audioPath);
- if (stale.length > 0) {
- throw new ServerError(
- `${stale.length} performance shot${stale.length === 1 ? ' has' : 's have'} no lip-synced take of the current song interval and recording — regenerate ${stale.length === 1 ? 'it' : 'them'}, or switch to Cutaway, before rendering`,
- { status: 422, code: 'STALE_PERFORMANCE_TAKES', context: { stale } },
- );
- }
- // #8985: a composed render cuts still and card sections into the same
- // timebase as the footage; plain concat renders footage only, as before.
- const composed = project.composition?.mode === 'composed';
- const rawClips = await resolveSceneClips(project, { layered: composed });
- const audioDurationSec = await probeVideoDuration(audioPath).catch(() => null);
- const beats = project.audioAnalysis?.beats;
- const clips = beatSnapClips(rawClips, beats, { scenes: project.scenes });
- // #8964: a new (non-looping) shot must never silently repeat footage to
- // fill its span. Refuse the render and name the shots that need a trim,
- // a continuation, a replacement clip, or an explicit loop.
- const shortfalls = findCoverageShortfalls(clips);
- if (shortfalls.length > 0) {
- throw new ServerError(
- `${shortfalls.length} shot${shortfalls.length === 1 ? ' is' : 's are'} longer than ${shortfalls.length === 1 ? 'its' : 'their'} source clip — trim, continue, replace, or loop ${shortfalls.length === 1 ? 'it' : 'them'} before rendering`,
- { status: 422, code: 'INSUFFICIENT_CLIP_COVERAGE', context: { shortfalls, resolutions: COVERAGE_RESOLUTIONS } },
- );
- }
+ const { ffmpeg, audioPath, composed, clips, audioDurationSec } = await planMusicVideoRender(project);
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);
diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.js
index 20d9db7f14..6688acb54f 100644
--- a/server/services/musicVideo/render.test.js
+++ b/server/services/musicVideo/render.test.js
@@ -18,6 +18,7 @@ import { existsSync } from 'fs';
import {
beatSnapClips,
buildMusicVideoFfmpegArgs,
+ excerptBoundaryTimes,
resolveSceneClips,
resolveMasterAudioPath,
renderMusicVideo,
@@ -62,6 +63,57 @@ describe('buildMusicVideoFfmpegArgs', () => {
it('throws on empty clips', () => {
expect(() => buildMusicVideoFfmpegArgs([], '/a.wav', '/o.mp4')).toThrow(/empty clips/);
});
+
+ // #8986 — a draft excerpt render windows the full-song plan down to
+ // [startSec, endSec) with one extra trim/atrim stage, instead of building a
+ // separate concat graph over just the overlapping clips.
+ describe('excerpt option (#8986)', () => {
+ it('trims the finished video+audio to the window and re-zeros totalDuration/sections', () => {
+ // Three 2s clips: [0,2) [2,4) [4,6). Window [1,5) crosses all three.
+ const clips = [clip({ videoPath: '/v/a.mp4', sceneId: 'a' }), clip({ videoPath: '/v/b.mp4', sceneId: 'b' }), clip({ videoPath: '/v/c.mp4', sceneId: 'c' })];
+ const { args, totalDuration, sections } = buildMusicVideoFfmpegArgs(clips, '/music/track.wav', '/out.mp4', { audioDurationSec: 30, excerpt: { startSec: 1, endSec: 5 } });
+ const fc = args[args.indexOf('-filter_complex') + 1];
+ expect(fc).toContain('[outv]trim=start=1:end=5,setpts=PTS-STARTPTS[outvx]');
+ expect(fc).toMatch(/:a\]atrim=start=1:end=5,asetpts=PTS-STARTPTS\[outax\]/);
+ const maps = args.reduce((acc, a, i) => (a === '-map' ? [...acc, args[i + 1]] : acc), []);
+ expect(maps).toEqual(['[outvx]', '[outax]']);
+ expect(totalDuration).toBe(4); // 5 - 1
+ // Re-based to the excerpt's own timeline (0 = startSec=1), clipped to it.
+ expect(sections).toEqual([
+ { sceneId: 'a', layer: 'footage', startSec: 0, endSec: 1 },
+ { sceneId: 'b', layer: 'footage', startSec: 1, endSec: 3 },
+ { sceneId: 'c', layer: 'footage', startSec: 3, endSec: 4 },
+ ]);
+ });
+
+ it('clamps a window past the full render to the actual video/audio length', () => {
+ const clips = [clip({ duration: 2, outSec: 2 }), clip({ duration: 2, outSec: 2 })]; // 4s video
+ const { totalDuration } = buildMusicVideoFfmpegArgs(clips, '/a.wav', '/o.mp4', { audioDurationSec: 30, excerpt: { startSec: 1, endSec: 10 } });
+ expect(totalDuration).toBe(3); // clamped to the 4s video, minus the 1s start
+ });
+ });
+});
+
+describe('excerptBoundaryTimes (#8986)', () => {
+ it('re-bases cut and cue boundaries inside the window to the excerpt timeline and dedupes', () => {
+ const sections = [
+ { sceneId: 'a', startSec: 0, endSec: 2 },
+ { sceneId: 'b', startSec: 2, endSec: 4 },
+ { sceneId: 'c', startSec: 4, endSec: 6 },
+ ];
+ const cues = [{ startSec: 2, endSec: 3 }]; // lands exactly on a cut — deduped
+ expect(excerptBoundaryTimes(sections, cues, 1, 5)).toEqual([0, 1, 2, 3, 4]);
+ });
+
+ it('always includes both ends of the window even with no cut/cue on them', () => {
+ const sections = [{ sceneId: 'a', startSec: 0, endSec: 10 }];
+ expect(excerptBoundaryTimes(sections, [], 2, 7)).toEqual([0, 5]);
+ });
+
+ it('drops boundaries outside the window', () => {
+ const sections = [{ sceneId: 'a', startSec: 0, endSec: 1 }, { sceneId: 'b', startSec: 1, endSec: 20 }];
+ expect(excerptBoundaryTimes(sections, [], 5, 8)).toEqual([0, 3]);
+ });
});
describe('beatSnapClips', () => {