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: plan music-video shots from timed lyrics and musical phrases (#8964)

[._.]/ Adam Eivy624b40c64d5f
diff --git a/client/src/components/musicVideo/BeatTimeline.jsx b/client/src/components/musicVideo/BeatTimeline.jsx
index f2ac78cfdb..2b677e962d 100644
--- a/client/src/components/musicVideo/BeatTimeline.jsx
+++ b/client/src/components/musicVideo/BeatTimeline.jsx
@@ -18,7 +18,23 @@ import { formatTimecode } from '../../utils/formatters.js';
const PX_PER_SEC = 80;
const SNAP_TOLERANCE_SEC = 0.15;
-export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {
+// Timed lyric lines (#8964) render as a read-only strip under the scene
+// blocks, so the director can see which words each cut spans. A cue with no
+// explicit end runs to the next cue (capped) — the same reading the planner uses.
+const OPEN_CUE_MAX_SEC = 8;
+function lyricSpans(cues) {
+ const timed = (Array.isArray(cues) ? cues : [])
+ .filter((c) => typeof c?.startSec === 'number' && c.text)
+ .slice()
+ .sort((a, b) => a.startSec - b.startSec);
+ return timed.map((c, i) => {
+ const next = timed[i + 1];
+ const openEnd = Math.min(c.startSec + OPEN_CUE_MAX_SEC, next ? next.startSec : Infinity);
+ return { id: c.id || `cue-${i}`, text: c.text, startSec: c.startSec, endSec: typeof c.endSec === 'number' && c.endSec > c.startSec ? c.endSec : openEnd };
+ });
+}
+
+export default function BeatTimeline({ audioAnalysis, scenes, lyricCues, onCommit }) {
const gridPoints = useMemo(() => buildBeatGridPoints(audioAnalysis), [audioAnalysis]);
const baseSpans = useMemo(
() => computeSceneSpans(scenes, audioAnalysis?.durationSec),
@@ -39,6 +55,7 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {
const totalDurationSec = Math.max(audioAnalysis?.durationSec || 0, ...spans.map((s) => s.endSec), 1);
const widthPx = Math.ceil(totalDurationSec * PX_PER_SEC) + 40;
const waveform = Array.isArray(audioAnalysis?.waveform) ? audioAnalysis.waveform : [];
+ const cueSpans = useMemo(() => lyricSpans(lyricCues), [lyricCues]);
const timeMarks = useMemo(() => {
const interval = totalDurationSec > 180 ? 30 : totalDurationSec > 60 ? 15 : 5;
return Array.from({ length: Math.floor(totalDurationSec / interval) + 1 }, (_, i) => i * interval);
@@ -179,10 +196,11 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {
<span><i className="mr-1 inline-block h-3 w-px bg-port-border" />beat</span>
<span><i className="mr-1 inline-block h-3 w-0.5 bg-port-accent" />downbeat</span>
<span><i className="mr-1 inline-block h-2 w-3 bg-port-success/40" />scene start</span>
+ {cueSpans.length > 0 && <span><i className="mr-1 inline-block h-2 w-3 bg-port-warning/30" />lyric line</span>}
</div>
<div ref={scrollRef} className="overflow-x-auto border border-port-border rounded-lg bg-port-bg">
- <div className="relative h-36" style={{ width: `${widthPx}px`, touchAction: 'none' }}>
+ <div className={`relative ${cueSpans.length > 0 ? 'h-44' : 'h-36'}`} style={{ width: `${widthPx}px`, touchAction: 'none' }}>
{(audioAnalysis.sections || []).map((section, i) => (
<div key={`sec-${i}`}
className="absolute top-0 h-6 border-r border-port-border/60 overflow-hidden"
@@ -240,6 +258,14 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {
</div>
);
})}
+ {cueSpans.map((cue) => (
+ <div key={cue.id}
+ className="pointer-events-none absolute top-[142px] h-6 overflow-hidden rounded border border-port-warning/40 bg-port-warning/15 px-1 text-[10px] leading-6 text-port-text truncate"
+ style={{ left: cue.startSec * PX_PER_SEC, width: Math.max(4, (cue.endSec - cue.startSec) * PX_PER_SEC) }}
+ title={cue.text}>
+ {cue.text}
+ </div>
+ ))}
</div>
</div>
</div>
diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsx
new file mode 100644
index 0000000000..62d23d88d0
--- /dev/null
+++ b/client/src/components/musicVideo/LyricsPanel.jsx
@@ -0,0 +1,163 @@
+import { useState } from 'react';
+import { Plus, Trash2, Upload } from 'lucide-react';
+
+// Client-minted ids keep a freshly added row addressable across saves without
+// waiting for the server (crypto.randomUUID is unavailable on the plain-HTTP
+// tailnet origin PortOS is usually opened from).
+const mintId = (prefix) => `${prefix}-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
+const toSec = (value) => (value === '' ? null : Number(value));
+const PACING_FIELDS = [
+ ['minShotSec', 'Shortest shot (s)', 'Floor for a planned shot; a shorter section stays one shot.'],
+ ['maxShotSec', 'Longest shot (s)', 'Ceiling for a planned shot — defaults to one generated clip (5s local, 6/10s Grok).'],
+ ['hookSec', 'Opening hook (s)', 'Cap on the very first shot so the video opens on a cut.'],
+];
+
+const inputCls = 'bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs';
+
+/**
+ * Timed lyric cues, musical-phrase annotations and shot pacing for the AI
+ * shot planner (#8964). Every list is editable in place: edits apply to the
+ * board immediately (`onEditLocal`) and persist on blur (`onSave`, a project
+ * PATCH that replaces the list whole). Import parses pasted LRC, SRT/WebVTT or
+ * plain lines server-side; plain lines arrive untimed and are timed here.
+ * Changing the project's audio clears every timing (the text stays) — those
+ * rows show as untimed until they are re-timed against the new track.
+ */
+export default function LyricsPanel({ project, onEditLocal, onSave, onImport, importing }) {
+ const cues = project.lyricCues || [];
+ const phrases = project.phrases || [];
+ const pacing = project.pacing || {};
+ const [importText, setImportText] = useState('');
+ const [importFormat, setImportFormat] = useState('auto');
+ const [importMode, setImportMode] = useState('replace');
+ const timedCount = cues.filter((c) => typeof c.startSec === 'number').length;
+
+ const editCue = (id, patch) => onEditLocal({ lyricCues: cues.map((c) => (c.id === id ? { ...c, ...patch } : c)) });
+ const editPhrase = (id, patch) => onEditLocal({ phrases: phrases.map((p) => (p.id === id ? { ...p, ...patch } : p)) });
+ const saveCues = (next = cues) => onSave({ lyricCues: next });
+ const savePhrases = (next = phrases) => onSave({ phrases: next });
+ const replaceCues = (next) => { onEditLocal({ lyricCues: next }); saveCues(next); };
+ const replacePhrases = (next) => { onEditLocal({ phrases: next }); savePhrases(next); };
+
+ const commitPacing = (key, raw) => {
+ const next = { ...pacing };
+ if (raw === '') delete next[key];
+ else next[key] = Number(raw);
+ const value = Object.keys(next).length > 0 ? next : null;
+ onEditLocal({ pacing: value });
+ onSave({ pacing: value });
+ };
+
+ const submitImport = () => {
+ if (!importText.trim()) return;
+ onImport({ text: importText, format: importFormat, mode: importMode }, () => setImportText(''));
+ };
+
+ return (
+ <details className="mt-2 bg-port-bg border border-port-border rounded-lg p-2 text-xs">
+ <summary className="cursor-pointer select-none text-port-text-muted">
+ Lyrics, phrases &amp; pacing — {cues.length} line{cues.length === 1 ? '' : 's'} ({timedCount} timed)
+ · {phrases.length} phrase{phrases.length === 1 ? '' : 's'}
+ <span className="block sm:inline sm:ml-1">— AI Plan cuts on timed lines and phrase edges; no lyrics = an instrumental plan.</span>
+ </summary>
+
+ <div className="mt-2 grid grid-cols-1 gap-3 lg:grid-cols-2">
+ <section className="space-y-2 min-w-0">
+ <h4 className="font-medium text-port-text">Import lyrics</h4>
+ <label htmlFor="mv-lyrics-import" className="sr-only">Lyrics to import</label>
+ <textarea id="mv-lyrics-import" rows={3} value={importText} onChange={(e) => setImportText(e.target.value)}
+ placeholder={'Paste LRC ([00:12.50] line), SRT/WebVTT cues, or plain lines (imported untimed)'}
+ className="w-full bg-port-card border border-port-border rounded px-2 py-1.5 text-xs" />
+ <div className="flex flex-wrap items-end gap-2">
+ <div>
+ <label htmlFor="mv-lyrics-format" className="block text-port-text-muted mb-0.5">Format</label>
+ <select id="mv-lyrics-format" value={importFormat} onChange={(e) => setImportFormat(e.target.value)} className={inputCls}>
+ <option value="auto">Detect</option>
+ <option value="lrc">LRC</option>
+ <option value="srt">SRT / WebVTT</option>
+ <option value="text">Plain lines</option>
+ </select>
+ </div>
+ <div>
+ <label htmlFor="mv-lyrics-mode" className="block text-port-text-muted mb-0.5">Existing lines</label>
+ <select id="mv-lyrics-mode" value={importMode} onChange={(e) => setImportMode(e.target.value)} className={inputCls}>
+ <option value="replace">Replace</option>
+ <option value="append">Append after</option>
+ </select>
+ </div>
+ <button type="button" onClick={submitImport} disabled={importing || !importText.trim()}
+ className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 min-h-[44px] sm:min-h-0 disabled:opacity-50">
+ <Upload size={13} /> {importing ? 'Importing…' : 'Import lyrics'}
+ </button>
+ </div>
+
+ <h4 className="font-medium text-port-text pt-1">Shot pacing</h4>
+ <div className="flex flex-wrap gap-2">
+ {PACING_FIELDS.map(([key, label, help]) => (
+ <div key={key}>
+ <label htmlFor={`mv-pacing-${key}`} className="block text-port-text-muted mb-0.5" title={help}>{label}</label>
+ <input id={`mv-pacing-${key}`} type="number" min={0.5} max={120} step={0.5}
+ defaultValue={pacing[key] ?? ''} key={`${project.id}-${key}-${pacing[key] ?? ''}`}
+ placeholder="default" title={help}
+ onBlur={(e) => { if (e.target.value !== String(pacing[key] ?? '')) commitPacing(key, e.target.value); }}
+ className={`${inputCls} w-24`} />
+ </div>
+ ))}
+ </div>
+ </section>
+
+ <section className="space-y-1 min-w-0">
+ <div className="flex items-center justify-between">
+ <h4 className="font-medium text-port-text">Lyric lines</h4>
+ <button type="button" onClick={() => replaceCues([...cues, { id: mintId('lc'), text: 'New line', startSec: null, endSec: null }])}
+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0"><Plus size={13} /> Line</button>
+ </div>
+ {cues.length === 0 && <p className="text-port-text-muted">No lyrics — instrumental tracks plan from sections and beats alone.</p>}
+ <div className="max-h-64 overflow-y-auto space-y-1 pr-1">
+ {cues.map((cue, i) => (
+ <div key={cue.id} className="flex flex-wrap items-center gap-1">
+ <input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} start (s)`} placeholder="start"
+ value={cue.startSec ?? ''} onChange={(e) => editCue(cue.id, { startSec: toSec(e.target.value) })}
+ onBlur={() => saveCues()} className={`${inputCls} w-16`} />
+ <input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} end (s)`} placeholder="end"
+ value={cue.endSec ?? ''} onChange={(e) => editCue(cue.id, { endSec: toSec(e.target.value) })}
+ onBlur={() => saveCues()} className={`${inputCls} w-16`} />
+ <input type="text" maxLength={500} aria-label={`Line ${i + 1} text`}
+ value={cue.text} onChange={(e) => editCue(cue.id, { text: e.target.value })}
+ onBlur={() => saveCues()} className={`${inputCls} min-w-0 flex-1 basis-40`} />
+ <button type="button" onClick={() => replaceCues(cues.filter((c) => c.id !== cue.id))}
+ aria-label={`Delete line ${i + 1}`} className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 text-port-error"><Trash2 size={12} /></button>
+ </div>
+ ))}
+ </div>
+
+ <div className="flex items-center justify-between pt-1">
+ <h4 className="font-medium text-port-text">Phrases</h4>
+ <button type="button" onClick={() => replacePhrases([...phrases, { id: mintId('mp'), label: '', intent: '', startSec: null, endSec: null }])}
+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0"><Plus size={13} /> Phrase</button>
+ </div>
+ <div className="max-h-48 overflow-y-auto space-y-1 pr-1">
+ {phrases.map((phrase, i) => (
+ <div key={phrase.id} className="flex flex-wrap items-center gap-1">
+ <input type="number" min={0} step={0.01} aria-label={`Phrase ${i + 1} start (s)`} placeholder="start"
+ value={phrase.startSec ?? ''} onChange={(e) => editPhrase(phrase.id, { startSec: toSec(e.target.value) })}
+ onBlur={() => savePhrases()} className={`${inputCls} w-16`} />
+ <input type="number" min={0} step={0.01} aria-label={`Phrase ${i + 1} end (s)`} placeholder="end"
+ value={phrase.endSec ?? ''} onChange={(e) => editPhrase(phrase.id, { endSec: toSec(e.target.value) })}
+ onBlur={() => savePhrases()} className={`${inputCls} w-16`} />
+ <input type="text" maxLength={120} aria-label={`Phrase ${i + 1} label`} placeholder="label"
+ value={phrase.label || ''} onChange={(e) => editPhrase(phrase.id, { label: e.target.value })}
+ onBlur={() => savePhrases()} className={`${inputCls} w-24`} />
+ <input type="text" maxLength={2000} aria-label={`Phrase ${i + 1} visual intent`} placeholder="visual intent"
+ value={phrase.intent || ''} onChange={(e) => editPhrase(phrase.id, { intent: e.target.value })}
+ onBlur={() => savePhrases()} className={`${inputCls} min-w-0 flex-1 basis-40`} />
+ <button type="button" onClick={() => replacePhrases(phrases.filter((p) => p.id !== phrase.id))}
+ aria-label={`Delete phrase ${i + 1}`} className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 text-port-error"><Trash2 size={12} /></button>
+ </div>
+ ))}
+ </div>
+ </section>
+ </div>
+ </details>
+ );
+}
diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsx
index 2d8f4bc37b..a6c2c7bc86 100644
--- a/client/src/components/musicVideo/ProjectToolbar.jsx
+++ b/client/src/components/musicVideo/ProjectToolbar.jsx
@@ -64,7 +64,7 @@ export default function ProjectToolbar({
</>
)}
<button onClick={onPlan} disabled={busy.planning || !project.audioAnalysis}
- title={!project.audioAnalysis ? 'Analyze the track first' : 'AI-propose a scene per song section'}
+ title={!project.audioAnalysis ? 'Analyze the track first' : 'AI-plan bounded shots per song section, cut on timed lyrics, phrases and beats'}
className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">
<Wand2 size={15} /> {busy.planning ? 'Planning…' : 'AI Plan'}
</button>
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index acba3d6eab..fcb03d1127 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -1,9 +1,12 @@
-import { useRef } from 'react';
-import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2 } from 'lucide-react';
+import { useRef, useState } from 'react';
+import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle } from 'lucide-react';
import { formatDurationSec } from '../../utils/formatters.js';
// The two timeline-bound scene fields rendered as identical number inputs.
const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];
+// Mirrors render.js COVERAGE_TOLERANCE_SEC: a non-looping shot may run this far
+// past its clip (the last frame holds); beyond it the render refuses (#8964).
+const COVERAGE_TOLERANCE_SEC = 0.25;
/**
* One scene on the board: ordering/delete, the shot + reference-frame prompts
@@ -26,6 +29,18 @@ export default function SceneCard({
// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's
// native controls let the user unmute it first (muted is only initial).
const clipPlayerRef = useRef(null);
+ // Source-clip length, read from the inline player's metadata and keyed to
+ // the clip it was measured from so a regenerated clip is re-measured.
+ const [clipMeta, setClipMeta] = useState(null);
+ const clipSec = clipMeta?.id === scene.videoHistoryId ? clipMeta.sec : null;
+ // Pre-#8964 scenes have no `loop` key and keep the legacy loop-to-fill render.
+ const loops = scene.loop !== false;
+ const spanSec = scene.beatAligned && typeof scene.startSec === 'number' && typeof scene.endSec === 'number'
+ ? scene.endSec - scene.startSec
+ : null;
+ const shortBySec = !loops && spanSec != null && clipSec != null ? spanSec - clipSec : 0;
+ const underCovered = shortBySec > COVERAGE_TOLERANCE_SEC;
+ const applyPatch = (patch) => { onEditLocal(scene.sceneId, patch); onSave(scene.sceneId, patch); };
return (
<div className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">
<div className="flex items-center justify-between gap-2">
@@ -40,6 +55,7 @@ export default function SceneCard({
: ''}
{scene.referenceImageId ? ' · frame ready' : ''}
{scene.videoHistoryId ? ' · video ready' : ''}
+ {clipSec != null ? ` · clip ${clipSec.toFixed(1)}s` : ''}
</div>
</div>
<div className="flex items-center gap-2">
@@ -56,6 +72,12 @@ export default function SceneCard({
placeholder="Shot prompt — what this scene's video should show"
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"
/>
+ {(scene.lyricText || scene.visualIntent) && (
+ <div className="text-[11px] text-port-text-muted space-y-0.5">
+ {scene.lyricText && <p className="italic break-words">♪ {scene.lyricText}</p>}
+ {scene.visualIntent && <p className="break-words">Intent: {scene.visualIntent}</p>}
+ </div>
+ )}
<div className="flex flex-wrap gap-2 items-center text-xs">
{SCENE_TIME_FIELDS.map(([labelText, key]) => {
const toValue = (v) => (v === '' ? null : Number(v));
@@ -72,7 +94,24 @@ export default function SceneCard({
onChange={(e) => { onEditLocal(scene.sceneId, { beatAligned: e.target.checked }); onSave(scene.sceneId, { beatAligned: e.target.checked }); }} />
Beat-aligned
</label>
+ <label className="flex items-center gap-1" title="Repeat the generated clip to fill a span longer than the clip. Off: the shot must be covered by its clip (trim, continue, or replace it).">
+ <input type="checkbox" checked={loops} onChange={(e) => applyPatch({ loop: e.target.checked })} />
+ Loop clip
+ </label>
</div>
+ {underCovered && (
+ <div role="alert" className="flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">
+ <AlertTriangle size={13} className="shrink-0" />
+ <span className="min-w-0 flex-1 basis-48">
+ Shot runs {spanSec.toFixed(1)}s but its clip is {clipSec.toFixed(1)}s — the render won&apos;t repeat it.
+ Trim the shot, continue or regenerate a longer clip, or loop it on purpose.
+ </span>
+ <button type="button" onClick={() => applyPatch({ endSec: Math.round((scene.startSec + clipSec) * 1000) / 1000 })}
+ className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Trim to clip</button>
+ <button type="button" onClick={() => applyPatch({ loop: true })}
+ className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Loop clip</button>
+ </div>
+ )}
{/* Reference frame — the still image that seeds this shot (Phase 1b) */}
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<textarea
@@ -119,6 +158,10 @@ export default function SceneCard({
playsInline
preload="metadata"
controls
+ onLoadedMetadata={(e) => {
+ const sec = e.currentTarget.duration;
+ if (Number.isFinite(sec) && sec > 0) setClipMeta({ id: scene.videoHistoryId, sec });
+ }}
/>
{/* Corner expand — do not put the open handler on <video> itself;
that would fight native play/pause controls. Shape matches
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 4781dee240..c47673b718 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -16,6 +16,7 @@ import {
updateMusicVideoScene,
deleteMusicVideoScene,
reorderMusicVideoScenes,
+ importMusicVideoLyrics,
} from '../services/apiMusicVideo.js';
import useFieldDraft from '../hooks/useFieldDraft.js';
import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';
@@ -38,6 +39,7 @@ import TrackPanel from '../components/musicVideo/TrackPanel.jsx';
import RenderStatusPanel from '../components/musicVideo/RenderStatusPanel.jsx';
import AnalysisPanel from '../components/musicVideo/AnalysisPanel.jsx';
import SceneCard from '../components/musicVideo/SceneCard.jsx';
+import LyricsPanel from '../components/musicVideo/LyricsPanel.jsx';
import { autoArrangeScenes } from '../lib/beatGrid.js';
import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';
import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';
@@ -67,6 +69,7 @@ export default function MusicVideo() {
const [arranging, setArranging] = useState(false);
const [planning, setPlanning] = useState(false);
const [cloning, setCloning] = useState(false);
+ const [importingLyrics, setImportingLyrics] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });
const selected = projects.find((p) => p.id === selectedId) || null;
@@ -213,11 +216,11 @@ export default function MusicVideo() {
.finally(() => setAnalyzing(false));
};
- // Autonomous shot planner (#1855): propose one scene per analyzed audio
- // section (energy-aware durations fall out of the section boundaries
- // themselves) and seed them onto the board, optionally with a first-pass
- // framePrompt/prompt per scene. Director-first — seeded scenes are
- // ordinary, fully-editable board entries, same as a hand-added one.
+ // Autonomous shot planner (#1855, multi-shot #8964): tile each analyzed
+ // section with bounded shots — cut on timed lyric lines, phrase edges and
+ // the beat grid, capped at the renderer's clip length — and seed them onto
+ // the board, optionally with a first-pass framePrompt/prompt per shot.
+ // Director-first — seeded shots are ordinary, fully-editable board entries.
const handlePlan = () => {
if (!selected?.audioAnalysis) return;
setPlanning(true);
@@ -227,7 +230,7 @@ export default function MusicVideo() {
const suffix = promptsSeeded
? ' with first-pass prompts'
: (promptsSkippedReason && promptsSkippedReason !== 'not-requested' ? ` (prompts skipped: ${promptsSkippedReason})` : '');
- toast.success(`Planned ${scenesAdded} scene${scenesAdded === 1 ? '' : 's'}${suffix}`);
+ toast.success(`Planned ${scenesAdded} shot${scenesAdded === 1 ? '' : 's'}${suffix}`);
})
.catch((err) => toast.error(err?.message || 'Plan failed'))
.finally(() => setPlanning(false));
@@ -321,6 +324,25 @@ export default function MusicVideo() {
updateMusicVideoProject(selected.id, { concept: patch }, { silent: true })
.catch((err) => toast.error(err?.message || 'Failed to save concept'));
};
+ // Lyric cues / phrases / pacing (#8964) — optimistic-local + silent PATCH on
+ // blur, like the scene editors. Lists are replaced whole server-side.
+ const editProjectLocal = (patch) => patchProject(selected.id, patch);
+ const saveProjectFields = (patch) => {
+ updateMusicVideoProject(selected.id, patch, { silent: true })
+ .catch((err) => toast.error(err?.message || 'Failed to save lyrics'));
+ };
+ const handleImportLyrics = (body, onDone) => {
+ const projectId = selected.id;
+ setImportingLyrics(true);
+ importMusicVideoLyrics(projectId, body, { silent: true })
+ .then(({ project, imported, format }) => {
+ patchProject(projectId, { lyricCues: project.lyricCues, updatedAt: project.updatedAt });
+ onDone?.();
+ toast.success(`Imported ${imported} lyric line${imported === 1 ? '' : 's'} (${format})`);
+ })
+ .catch((err) => toast.error(err?.message || 'Lyric import failed'))
+ .finally(() => setImportingLyrics(false));
+ };
// Buffered so a concept/style keystroke doesn't fire a round-trip per character,
// and a focus-without-edit blur doesn't re-PATCH an unchanged value.
const conceptDraft = useFieldDraft(selected?.concept?.prompt, (v) => commitConcept({ prompt: v }));
@@ -552,6 +574,13 @@ export default function MusicVideo() {
finalVideo={finalVideo}
onOpenPreview={openPreview}
/>
+ <LyricsPanel
+ project={selected}
+ onEditLocal={editProjectLocal}
+ onSave={saveProjectFields}
+ onImport={handleImportLyrics}
+ importing={importingLyrics}
+ />
<AnalysisPanel
audioAnalysis={selected.audioAnalysis}
scenes={selected.scenes || []}
@@ -560,7 +589,7 @@ export default function MusicVideo() {
</div>
{selected.audioAnalysis && (selected.scenes || []).length > 0 && (
- <BeatTimeline audioAnalysis={selected.audioAnalysis} scenes={selected.scenes} onCommit={commitSceneTiming} />
+ <BeatTimeline audioAnalysis={selected.audioAnalysis} scenes={selected.scenes} lyricCues={selected.lyricCues} onCommit={commitSceneTiming} />
)}
<div className="flex items-center justify-between">
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 2161d6c359..ee40a76c61 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -51,6 +51,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({
updateMusicVideoScene: vi.fn(),
deleteMusicVideoScene: vi.fn(),
reorderMusicVideoScenes: vi.fn(),
+ importMusicVideoLyrics: vi.fn(),
renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),
musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,
cancelMusicVideoRender: vi.fn(async () => ({ ok: true })),
@@ -132,6 +133,7 @@ import MusicVideo from './MusicVideo.jsx';
import {
listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,
deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender,
+ importMusicVideoLyrics, updateMusicVideoScene,
} from '../services/apiMusicVideo.js';
import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
import { generateVideo, getVideoGenStatus } from '../services/apiImageVideo.js';
@@ -614,6 +616,63 @@ describe('MusicVideo autonomous shot planner (#1855)', () => {
});
});
+describe('MusicVideo lyrics and shot coverage (#8964)', () => {
+ it('imports pasted lyrics, shows the cues, and persists an edited line on blur', async () => {
+ const cues = [
+ { id: 'lc-1', text: 'first line', startSec: 1, endSec: 3 },
+ { id: 'lc-2', text: 'second line', startSec: 3, endSec: null },
+ ];
+ importMusicVideoLyrics.mockResolvedValue({ project: { ...PROJECT_ANALYZED, lyricCues: cues }, imported: 2, format: 'lrc' });
+ await openProject(PROJECT_ANALYZED);
+
+ fireEvent.change(screen.getByLabelText('Lyrics to import'), { target: { value: '[00:01.00]first line\n[00:03.00]second line' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Import lyrics$/ }));
+ await waitFor(() => expect(importMusicVideoLyrics).toHaveBeenCalledWith(
+ 'mv-3',
+ { text: '[00:01.00]first line\n[00:03.00]second line', format: 'auto', mode: 'replace' },
+ { silent: true },
+ ));
+ const line = await screen.findByLabelText('Line 2 text');
+ expect(line).toHaveValue('second line');
+ expect(screen.getByLabelText('Lyrics to import')).toHaveValue('');
+
+ fireEvent.change(line, { target: { value: 'second line, retold' } });
+ fireEvent.blur(line);
+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith(
+ 'mv-3',
+ { lyricCues: [cues[0], { ...cues[1], text: 'second line, retold' }] },
+ { silent: true },
+ ));
+ });
+
+ it('flags a non-looping shot longer than its clip and trims it; a legacy scene is left alone', async () => {
+ const project = {
+ ...PROJECT_WITH_CLIP,
+ scenes: [
+ { sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img1', videoHistoryId: 'h1', beatAligned: true, startSec: 2, endSec: 12, loop: false, lyricText: 'first line' },
+ { sceneId: 's2', order: 1, prompt: 'b', referenceImageId: 'img1', videoHistoryId: 'h2', beatAligned: true, startSec: 12, endSec: 30 },
+ ],
+ };
+ updateMusicVideoScene.mockResolvedValue({});
+ await openProject(project);
+ expect(screen.getByText(/first line/)).toBeTruthy();
+
+ const players = document.body.querySelectorAll('video[src^="/data/videos/h"]');
+ expect(players).toHaveLength(2);
+ for (const player of players) {
+ Object.defineProperty(player, 'duration', { configurable: true, value: 5 });
+ fireEvent.loadedMetadata(player);
+ }
+ const alerts = await screen.findAllByRole('alert');
+ expect(alerts).toHaveLength(1); // the legacy s2 keeps looping to fill its span
+ expect(alerts[0].textContent).toContain('Shot runs 10.0s but its clip is 5.0s');
+
+ fireEvent.click(within(alerts[0]).getByRole('button', { name: 'Trim to clip' }));
+ await waitFor(() => expect(updateMusicVideoScene).toHaveBeenCalledWith('mv-1', 's1', { endSec: 7 }, { silent: true }));
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ });
+});
+
describe('MusicVideo concept & style editor (#3168)', () => {
it('seeds the fields from the project and persists each on blur', async () => {
const withConcept = { ...PROJECT_NO_CLIP, concept: { prompt: 'A road trip through neon ruins', style: 'Cyberpunk anime' } };
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index ec217b265a..d9f2f8e8b9 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -32,14 +32,22 @@ export const setMusicVideoManualTempo = (id, body, options = {}) => request(`/mu
method: 'POST', body: JSON.stringify(body), ...options,
});
-// Autonomous shot planner (#1855): propose one scene per analyzed audio
-// section and seed them onto the board. `seedPrompts` (default true) also
+// Autonomous shot planner (#1855, multi-shot #8964): tile each analyzed
+// section with bounded shots (cut on lyric lines / phrases / beats) and seed
+// them onto the board. `seedPrompts` (default true) also
// best-effort asks the active provider for a first-pass framePrompt/prompt
-// per scene. Returns `{ project, scenesAdded, promptsSeeded, promptsSkippedReason }`.
+// per scene. Returns `{ project, scenesAdded, promptsSeeded, promptsSkippedReason, pacing }`.
export const planMusicVideoProject = (id, body = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/plan`, {
method: 'POST', body: JSON.stringify(body), ...options,
});
+// Import timed lyric cues (#8964) from pasted LRC / SRT / WebVTT / plain lines.
+// Body: { text, format?: 'auto'|'lrc'|'srt'|'text', mode?: 'replace'|'append' }.
+// Resolves to { project, imported, format }.
+export const importMusicVideoLyrics = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/lyrics/import`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+
// ---- Director scene board ----
export const addMusicVideoScene = (id, scene, options = {}) => request(`/music-video/${encodeURIComponent(id)}/scenes`, {
method: 'POST', body: JSON.stringify(scene), ...options,
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index dadcccac99..72c1e64da6 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -39,6 +39,49 @@ export const musicVideoVideoSettingsSchema = z.object({
audioReactiveScale: z.number().min(0).max(2).optional(),
}).strict();
+// Timed lyric cues (#8964). Editable, user-owned text: a cue carries its line
+// and optional timing against the project's CURRENT audio source. `startSec`
+// null means "not yet timed" (plain pasted lyrics, or timings invalidated by an
+// audio-source change — see projectsLogic.applyProjectPatch). The id is
+// optional on input; the server mints one so edits stay addressable.
+const timedSec = z.number().min(0).max(36000).nullable().optional();
+export const musicVideoLyricCueSchema = z.object({
+ id: z.string().min(1).max(64).optional(),
+ text: z.string().max(500),
+ startSec: timedSec,
+ endSec: timedSec,
+}).strict();
+
+// A musical-phrase annotation: a span of the song with an optional visual
+// intent (what the picture should do there). Phrase edges are preferred cut
+// points for the shot planner and the intent is handed to the prompt seeder.
+export const musicVideoPhraseSchema = z.object({
+ id: z.string().min(1).max(64).optional(),
+ label: z.string().max(120).optional(),
+ startSec: timedSec,
+ endSec: timedSec,
+ intent: z.string().max(2000).optional(),
+}).strict();
+
+// Shot pacing for the planner. `maxShotSec` defaults to the renderer's clip
+// capacity; `hookSec` bounds the opening shot so the video opens on a cut.
+export const musicVideoPacingSchema = z.object({
+ minShotSec: z.number().min(0.5).max(60).optional(),
+ maxShotSec: z.number().min(1).max(120).optional(),
+ hookSec: z.number().min(0.5).max(60).optional(),
+}).strict();
+
+const lyricCueList = z.array(musicVideoLyricCueSchema).max(2000);
+const phraseList = z.array(musicVideoPhraseSchema).max(500);
+
+// Import lyric cues from pasted text: LRC (`[mm:ss.xx] line`), SRT/WebVTT
+// cue blocks, or plain lines (untimed). `auto` sniffs the format.
+export const musicVideoLyricsImportSchema = z.object({
+ format: z.enum(['auto', 'lrc', 'srt', 'text']).optional(),
+ text: z.string().max(200000),
+ mode: z.enum(['replace', 'append']).optional(),
+}).strict();
+
export const musicVideoProjectCreateSchema = z.object({
name: z.string().min(1).max(200),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
@@ -60,6 +103,9 @@ export const musicVideoProjectUpdateSchema = z.object({
concept: musicVideoConceptSchema.nullable().optional(),
videoSettings: musicVideoVideoSettingsSchema.optional(),
renderHistoryId: z.string().max(64).nullable().optional(),
+ lyricCues: lyricCueList.optional(),
+ phrases: phraseList.optional(),
+ pacing: musicVideoPacingSchema.nullable().optional(),
}).strict();
// Fork a project into its next editable version. The server derives lineage and
@@ -81,6 +127,13 @@ export const musicVideoSceneCreateSchema = z.object({
startSec: z.number().min(0).max(36000).nullable().optional(),
endSec: z.number().min(0).max(36000).nullable().optional(),
beatAligned: z.boolean().optional(),
+ // #8964: shot-planning fields. `loop` is an explicit, deliberate choice to
+ // repeat the source clip across a longer authored span; a scene with no
+ // `loop` key is a pre-#8964 record and keeps the legacy loop-to-fill render.
+ loop: z.boolean().optional(),
+ sectionIndex: z.number().int().min(0).max(10000).nullable().optional(),
+ lyricText: z.string().max(2000).nullable().optional(),
+ visualIntent: z.string().max(2000).nullable().optional(),
}).strict().refine(
(s) => s.startSec == null || s.endSec == null || s.endSec >= s.startSec,
{ message: 'endSec must be >= startSec', path: ['endSec'] },
@@ -98,6 +151,13 @@ export const musicVideoSceneUpdateSchema = z.object({
startSec: z.number().min(0).max(36000).nullable().optional(),
endSec: z.number().min(0).max(36000).nullable().optional(),
beatAligned: z.boolean().optional(),
+ // #8964: shot-planning fields. `loop` is an explicit, deliberate choice to
+ // repeat the source clip across a longer authored span; a scene with no
+ // `loop` key is a pre-#8964 record and keeps the legacy loop-to-fill render.
+ loop: z.boolean().optional(),
+ sectionIndex: z.number().int().min(0).max(10000).nullable().optional(),
+ lyricText: z.string().max(2000).nullable().optional(),
+ visualIntent: z.string().max(2000).nullable().optional(),
referenceImageId: z.string().max(256).nullable().optional(),
videoHistoryId: z.string().max(64).nullable().optional(),
}).strict();
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index e6f0d2a746..a87e758c85 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -573,7 +573,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// (uploaded audio, scene images/rendered videos) is NOT bundled in this phase —
// it federates via its own channels / a follow-up. The FIRST incompatible
// project-shape change MUST bump this to 2.
- musicVideoProjects: 1,
+ // v2 = timed lyric cues, phrase annotations, pacing, and explicit per-shot
+ // `loop` semantics (#8964). The body is still stored verbatim by a v1
+ // receiver, but a v1 peer would mis-execute it and LWW the damage back: its
+ // renderer loops every clip (silently repeating footage in `loop: false`
+ // shots the newer peer refuses to render that way), and its audio-source
+ // change clears the analysis while leaving the lyric/phrase timings aligned
+ // to the OLD track — an edit that then wins LWW onto the upgraded peer.
+ // Gating makes a v1 receiver reject the ahead-version transfer until it
+ // upgrades; pre-#8964 records need no rewrite (absent `loop` = legacy loop).
+ musicVideoProjects: 2,
// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)
// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,
// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index e2a9a1e416..73e0f75c05 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -21,6 +21,7 @@ import {
musicVideoPlanRequestSchema,
musicVideoManualAnalysisSchema,
musicVideoTranscribeMidiRequestSchema,
+ musicVideoLyricsImportSchema,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
@@ -49,6 +50,7 @@ import {
import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';
import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';
import { planProject } from '../services/musicVideo/planner.js';
+import { parseLyricCues } from '../services/musicVideo/timedText.js';
import { getTrack } from '../services/tracks/index.js';
const router = Router();
@@ -175,6 +177,27 @@ router.post('/:id/plan', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Import timed lyric cues (#8964) from pasted LRC, SRT/WebVTT, or plain lines
+// (plain lines arrive untimed, ready to be timed by hand). `replace` swaps the
+// project's cue list; `append` adds after it. The cues persist through the
+// ordinary project PATCH path, so ids/normalization match hand edits.
+const MAX_LYRIC_CUES = 2000;
+router.post('/:id/lyrics/import', asyncHandler(async (req, res) => {
+ const { format = 'auto', text, mode = 'replace' } = validateRequest(musicVideoLyricsImportSchema, req.body);
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const { format: detected, cues } = parseLyricCues(text, format);
+ if (cues.length === 0) {
+ throw new ServerError(`No lyric lines found in the ${detected} text`, { status: 422, code: 'NO_LYRICS' });
+ }
+ const lyricCues = mode === 'append' ? [...(project.lyricCues || []), ...cues] : cues;
+ if (lyricCues.length > MAX_LYRIC_CUES) {
+ throw new ServerError(`A project holds at most ${MAX_LYRIC_CUES} lyric cues`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const updated = await updateProject(project.id, { lyricCues });
+ res.json({ project: updated, imported: cues.length, format: detected });
+}));
+
// --- Audio → MIDI transcription (MuScriptor) ---
// Transcribe the project's source audio into a .mid via the local MuScriptor
// sidecar. Kickoff returns 202 + a jobId (503 with the install hint when the
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index 76276493da..24aa3076fb 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -168,6 +168,49 @@ describe('musicVideo routes', () => {
expect(svc.updateProject).not.toHaveBeenCalled();
});
+ it('PATCH /:id rejects an out-of-range pacing ceiling or an oversized lyric line', async () => {
+ const pacing = await request(app).patch('/api/music-video/mv-1').send({ pacing: { maxShotSec: 0 } });
+ expect(pacing.status).toBe(400);
+ const cue = await request(app).patch('/api/music-video/mv-1')
+ .send({ lyricCues: [{ text: 'x'.repeat(501), startSec: 1 }] });
+ expect(cue.status).toBe(400);
+ expect(svc.updateProject).not.toHaveBeenCalled();
+ });
+
+ describe('POST /:id/lyrics/import (#8964)', () => {
+ it('replaces the cue list with the parsed LRC and reports the detected format', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [{ id: 'lc-old', text: 'old', startSec: 1, endSec: 2 }] });
+ const r = await request(app).post('/api/music-video/mv-1/lyrics/import')
+ .send({ text: '[00:01.00]one\n[00:03.00]two' });
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({ imported: 2, format: 'lrc' });
+ expect(svc.updateProject).toHaveBeenCalledWith('mv-1', {
+ lyricCues: [{ text: 'one', startSec: 1, endSec: 3 }, { text: 'two', startSec: 3, endSec: null }],
+ });
+ });
+
+ it('appends plain lines after the existing cues', async () => {
+ const existing = { id: 'lc-old', text: 'old', startSec: 1, endSec: 2 };
+ svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [existing] });
+ const r = await request(app).post('/api/music-video/mv-1/lyrics/import')
+ .send({ text: 'new line', mode: 'append' });
+ expect(r.status).toBe(200);
+ expect(svc.updateProject).toHaveBeenCalledWith('mv-1', {
+ lyricCues: [existing, { text: 'new line', startSec: null, endSec: null }],
+ });
+ });
+
+ it('422s when the text holds no lyric lines, and 404s for a missing project', async () => {
+ svc.getProject.mockResolvedValue({ id: 'mv-1', lyricCues: [] });
+ const empty = await request(app).post('/api/music-video/mv-1/lyrics/import').send({ text: '[Chorus]\n\n' });
+ expect(empty.status).toBe(422);
+ svc.getProject.mockResolvedValue(null);
+ const missing = await request(app).post('/api/music-video/mv-x/lyrics/import').send({ text: 'a' });
+ expect(missing.status).toBe(404);
+ expect(svc.updateProject).not.toHaveBeenCalled();
+ });
+ });
+
it('DELETE /:id soft-deletes', async () => {
const r = await request(app).delete('/api/music-video/mv-1');
expect(r.status).toBe(200);
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 1ce40b22c6..1665633dfa 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -1,5 +1,14 @@
/**
- * Music Video — autonomous shot planner (#1855).
+ * Music Video — autonomous shot planner (#1855; multi-shot + lyrics #8964).
+ *
+ * #8964: sections are no longer 1:1 with scenes. `shotPlan.js#planShots`
+ * tiles each analyzed section with several bounded shots (pacing ceiling =
+ * the renderer's clip capacity, an opening hook, cuts preferring lyric-line /
+ * phrase boundaries then downbeats then beats), and every shot carries its
+ * section identity plus the lyric lines and phrase intent it spans. The
+ * paragraphs below describe the original one-scene-per-section design; the
+ * energy segmentation and grid snapping they describe still decide the
+ * section edges each shot list is tiled inside.
*
* Part of #1760's secondary "autonomous mode" convenience path (the manual
* director path shipped through Phase 2). Given a project's cached
@@ -31,16 +40,19 @@
import { ServerError } from '../../lib/errorHandler.js';
import { extractJson } from '../../lib/jsonExtract.js';
import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';
-import { snapSectionsToGrid } from './audioAnalysis.js';
+import { planShots, resolveClipCapacitySec } from './shotPlan.js';
import { getProject, addProjectScenes } from './projects.js';
-const SECTION_LABEL_MAX = 120;
+const SCENE_LABEL_MAX = 120;
const SCENE_TEXT_MAX = 2000;
-// A music video plan with more sections than this would blow the LLM prompt
-// budget for marginal value (typical analyses produce single-digit-to-low-
-// dozens of sections) — scenes are still seeded deterministically above the
-// cap, just without the optional first-pass prompt text.
-const MAX_SECTIONS_FOR_PROMPTS = 80;
+// Lyric text per shot quoted into the LLM prompt (the full text persists on
+// the scene); keeps a lyric-dense plan inside the prompt budget.
+const PROMPT_LYRIC_MAX = 240;
+// A plan with more shots than this would blow the LLM prompt budget for
+// marginal value (a 4-minute song at ~5s shots is ~50) — scenes are still
+// seeded deterministically above the cap, just without the optional
+// first-pass prompt text.
+const MAX_SHOTS_FOR_PROMPTS = 120;
// Mirrors musicVideoSceneCreateSchema's startSec/endSec bounds (musicVideoValidation.js)
// so a section just outside the downstream scene schema's range is dropped
@@ -64,64 +76,72 @@ export function validSections(sections) {
}
/**
- * Pure: derive one scene-create input per analyzed section, in section
- * order. `sections` must already be filtered via `validSections` — the
- * caller owns that so this stays a straight 1:1 map (no index drift between
- * this and the LLM prompt's section list).
- *
- * Section edges come out of energy-novelty segmentation on half-second window
- * boundaries — they have never touched the beat grid. So before seeding, snap
- * the internal boundaries onto the analysis's downbeats/beats and take
- * `beatAligned` from whether each scene's own edges actually landed there
- * (#4664). Stamping `beatAligned: true` unconditionally, as this used to,
- * told `render.js#beatSnapClips` to honor an arbitrary window edge exactly
- * and suppressed the live snap that would otherwise have corrected it.
- *
- * An edge that cannot snap reports `beatAligned: false`, handing that span back
- * to the live snap. A track with NO grid at all keeps its planned spans honored
- * — there is no live snap to hand them to, and dropping them would render every
- * scene at its raw source-clip length; see `snapSectionsToGrid`.
- *
- * @param {Array<object>} sections
- * @param {{ downbeats?: number[], beats?: number[], toleranceSec?: number, minSceneSec?: number }} [grid]
+ * Pure: turn the shot plan into scene-create inputs, in timeline order. Each
+ * shot is a new, non-looping scene (`loop: false`) — the render refuses to
+ * silently repeat its clip, so a shot longer than its generated clip asks the
+ * director to trim, continue, replace, or explicitly loop it (render.js).
+ * The label keeps the section name and numbers the shots inside it.
*/
-export function planScenesFromSections(sections, grid = {}) {
- const { sections: snapped, beatAligned } = snapSectionsToGrid(sections, grid);
- return snapped.map((s, i) => {
- const label = typeof s.label === 'string' ? s.label.slice(0, SECTION_LABEL_MAX) : '';
+export function sceneInputsFromShots(shots) {
+ return shots.map((shot) => {
+ const base = shot.sectionLabel || `Section ${shot.sectionIndex + 1}`;
+ const label = (shot.shotCount > 1 ? `${base} · ${shot.shotIndex + 1}/${shot.shotCount}` : base).slice(0, SCENE_LABEL_MAX);
return {
label,
- sectionLabel: label || null,
- startSec: s.startSec,
- endSec: s.endSec,
- beatAligned: beatAligned[i],
+ sectionLabel: shot.sectionLabel,
+ sectionIndex: shot.sectionIndex,
+ startSec: shot.startSec,
+ endSec: shot.endSec,
+ beatAligned: shot.beatAligned,
+ loop: false,
+ lyricText: shot.lyricText,
+ visualIntent: shot.visualIntent,
};
});
}
-/** Build the LLM prompt asking for a first-pass framePrompt/prompt per section. */
-export function buildScenePlanPrompt(project, sections) {
+const quote = (text, max) => {
+ const flat = String(text).replace(/\s+/g, ' ').trim();
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
+};
+
+/**
+ * Build the LLM prompt asking for a first-pass framePrompt/prompt per SHOT.
+ * Each line carries the shot's musical section (label, energy, position inside
+ * the section), its duration, the lyric lines it spans (or that it is
+ * instrumental — no lyrics are invented), and any phrase-level visual intent.
+ */
+export function buildScenePlanPrompt(project, shots) {
const concept = project.concept || {};
const conceptLine = concept.prompt ? `Concept: ${concept.prompt}` : '';
const styleLine = concept.style ? `Visual style: ${concept.style}` : '';
- const sectionLines = sections.map((s, i) => {
+ const hasLyrics = shots.some((s) => s.lyricText);
+ const shotLines = shots.map((s, i) => {
const duration = (s.endSec - s.startSec).toFixed(1);
- const energy = typeof s.energy === 'number' ? s.energy.toFixed(2) : 'unknown';
- return `${i}. "${s.label || `Section ${i + 1}`}" — ${duration}s, normalized energy ${energy}`;
+ const energy = typeof s.sectionEnergy === 'number' ? s.sectionEnergy.toFixed(2) : 'unknown';
+ const section = `"${s.sectionLabel || `Section ${s.sectionIndex + 1}`}" shot ${s.shotIndex + 1}/${s.shotCount}`;
+ const parts = [`${i}. ${section} — ${duration}s, energy ${energy}`];
+ parts.push(s.lyricText ? `lyrics: "${quote(s.lyricText, PROMPT_LYRIC_MAX)}"` : 'instrumental');
+ if (s.visualIntent) parts.push(`intent: ${quote(s.visualIntent, PROMPT_LYRIC_MAX)}`);
+ if (s.hook) parts.push('OPENING HOOK');
+ return parts.join('; ');
}).join('\n');
return `You are directing a music video for "${project.name}".
${conceptLine}
${styleLine}
-The track has been split into these sections (index, label, duration, normalized 0..1 energy — higher energy means a louder/more intense part of the song):
-${sectionLines}
+The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent):
+${shotLines}
-For EACH section above, propose ONE shot for a generative video model:
+For EACH shot above, propose the shot for a generative video model:
- "framePrompt": the opening reference still — subject, setting, lighting, composition. Keep it concrete and visual.
-- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections should read more kinetic; calmer sections more static/lingering.
+- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections read more kinetic; calmer sections more static/lingering.
+- Shots in the same section are one edited sequence: keep subject and setting continuous, but vary framing (wide / medium / close), angle, or action from shot to shot so consecutive shots cut rather than repeat.
+- The OPENING HOOK shot must grab attention immediately.
+${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text.\n' : ''}- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.
-Respond with ONLY a JSON array, one object per section, in section-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:
+Respond with ONLY a JSON array, one object per shot, in shot-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:
[{ "index": 0, "framePrompt": "<the opening reference still, ready to render>", "prompt": "<the shot's motion, ready to render>" }]`;
}
@@ -170,9 +190,9 @@ function parseScenePlanResponse(text, count) {
* provider disabled, LLM call failed, response didn't parse) so the caller
* can fall back to plain scenes without the whole plan request failing.
*/
-async function tryProposeScenePrompts(project, sections, { providerId, model } = {}) {
- if (sections.length > MAX_SECTIONS_FOR_PROMPTS) {
- return { seeded: null, reason: 'too-many-sections' };
+async function tryProposeScenePrompts(project, shots, { providerId, model } = {}) {
+ if (shots.length > MAX_SHOTS_FOR_PROMPTS) {
+ return { seeded: null, reason: 'too-many-shots' };
}
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model }).catch((err) => {
@@ -187,7 +207,7 @@ async function tryProposeScenePrompts(project, sections, { providerId, model } =
({ text } = await runPromptThroughProvider({
provider,
model: selectedModel,
- prompt: buildScenePlanPrompt(project, sections),
+ prompt: buildScenePlanPrompt(project, shots),
source: 'music-video-plan',
}));
} catch (err) {
@@ -195,7 +215,7 @@ async function tryProposeScenePrompts(project, sections, { providerId, model } =
return { seeded: null, reason: 'llm-failed' };
}
- const seeded = parseScenePlanResponse(text, sections.length);
+ const seeded = parseScenePlanResponse(text, shots.length);
if (!seeded) {
console.warn(`⚠️ Music Video plan: unparsable scene-prompt response for ${project.id}`);
return { seeded: null, reason: 'unparsable-response' };
@@ -213,7 +233,7 @@ async function tryProposeScenePrompts(project, sections, { providerId, model } =
* @param {string} [options.providerId] — pin a specific provider instead of
* the active one.
* @param {string} [options.model] — model override for the prompt-seeding call.
- * @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null }>}
+ * @returns {Promise<{ project: object, scenesAdded: number, promptsSeeded: boolean, promptsSkippedReason: string|null, pacing: object }>}
*/
export async function planProject(id, { seedPrompts = true, providerId, model } = {}) {
const project = await getProject(id);
@@ -227,18 +247,22 @@ export async function planProject(id, { seedPrompts = true, providerId, model }
);
}
- // `buildScenePlanPrompt` below keeps listing the PRE-snap `sections`:
- // indices still agree 1:1 with `sceneInputs`, and a sub-beat difference in a
- // section's reported duration does not change the creative direction asked for.
- const sceneInputs = planScenesFromSections(sections, {
+ // One shot list drives both the seeded scenes and the prompt, so prompt
+ // indices agree 1:1 with `sceneInputs`.
+ const { shots, pacing } = planShots(sections, {
downbeats: project.audioAnalysis?.downbeats,
beats: project.audioAnalysis?.beats,
+ lyricCues: project.lyricCues,
+ phrases: project.phrases,
+ pacing: project.pacing,
+ clipCapacitySec: resolveClipCapacitySec(project.videoSettings),
});
+ const sceneInputs = sceneInputsFromShots(shots);
let promptsSeeded = false;
let promptsSkippedReason = seedPrompts ? null : 'not-requested';
if (seedPrompts) {
- const { seeded, reason } = await tryProposeScenePrompts(project, sections, { providerId, model });
+ const { seeded, reason } = await tryProposeScenePrompts(project, shots, { providerId, model });
if (seeded) {
promptsSeeded = true;
for (const [idx, fields] of seeded) {
@@ -260,5 +284,5 @@ export async function planProject(id, { seedPrompts = true, providerId, model }
// second getProject round trip.
const { project: updated, scenes } = await addProjectScenes(id, sceneInputs);
console.log(`🪄 Music Video plan: seeded ${scenes.length} scene${scenes.length === 1 ? '' : 's'} for ${id} (prompts ${promptsSeeded ? 'seeded' : `skipped: ${promptsSkippedReason || 'n/a'}`})`);
- return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason };
+ return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason, pacing };
}
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index 1df87421e2..0f0b92495c 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -14,10 +14,10 @@ import { resolveProviderAndModel, runPromptThroughProvider } from '../promptRunn
import { getProject, addProjectScenes } from './projects.js';
import {
validSections,
- planScenesFromSections,
buildScenePlanPrompt,
planProject,
} from './planner.js';
+import { planShots } from './shotPlan.js';
const SECTIONS = [
{ label: 'Intro', startSec: 0, endSec: 10, energy: 0.2 },
@@ -66,85 +66,154 @@ describe('validSections', () => {
});
});
-describe('planScenesFromSections', () => {
- const GRID = { beats: BEATS, downbeats: DOWNBEATS };
-
- it('builds one scene-create input per section, in order', () => {
- const inputs = planScenesFromSections(SECTIONS, GRID);
- expect(inputs).toHaveLength(3);
- expect(inputs[0]).toEqual({
- label: 'Intro', sectionLabel: 'Intro', startSec: 0, endSec: 10, beatAligned: true,
- });
- expect(inputs[1]).toMatchObject({ label: 'Drop', startSec: 10, endSec: 18 });
- expect(inputs[2]).toMatchObject({ label: 'Outro', startSec: 18, endSec: 30 });
- });
+// Contiguous, gap-free tiling of [from, to] — the "complete timeline coverage"
+// half of the plan contract.
+function expectTiles(shots, from, to) {
+ expect(shots[0].startSec).toBe(from);
+ expect(shots.at(-1).endSec).toBe(to);
+ for (let i = 1; i < shots.length; i++) expect(shots[i].startSec).toBe(shots[i - 1].endSec);
+}
- it('each scene duration is its (snapped) section span — energy-aware via segmentation', () => {
- const inputs = planScenesFromSections(SECTIONS, GRID);
- for (let i = 0; i < SECTIONS.length; i++) {
- expect(inputs[i].endSec - inputs[i].startSec).toBe(SECTIONS[i].endSec - SECTIONS[i].startSec);
+describe('planShots', () => {
+ const GRID = { beats: BEATS, downbeats: DOWNBEATS };
+ const VERSE = [{ label: 'Verse', startSec: 0, endSec: 24, energy: 0.5 }];
+
+ it('splits a verse longer than the clip capacity into bounded, beat-cut shots covering it exactly', () => {
+ const { shots, pacing } = planShots(VERSE, { ...GRID, clipCapacitySec: 5 });
+ expect(pacing).toEqual({ minShotSec: 2, maxShotSec: 5, hookSec: 3 });
+ expect(shots.length).toBeGreaterThanOrEqual(5);
+ expectTiles(shots, 0, 24);
+ for (const shot of shots) {
+ const len = shot.endSec - shot.startSec;
+ expect(len).toBeLessThanOrEqual(5);
+ expect(len).toBeGreaterThanOrEqual(2);
+ expect(shot.beatAligned).toBe(true);
+ expect(DOWNBEATS.concat(BEATS)).toContain(shot.startSec);
}
+ // The opening hook is capped separately from the section pacing.
+ expect(shots[0].hook).toBe(true);
+ expect(shots[0].endSec - shots[0].startSec).toBeLessThanOrEqual(3);
+ expect(shots.slice(1).every((s) => !s.hook)).toBe(true);
+ // Section identity survives the split.
+ expect(shots.every((s) => s.sectionIndex === 0 && s.sectionLabel === 'Verse' && s.shotCount === shots.length)).toBe(true);
+ expect(shots.map((s) => s.shotIndex)).toEqual(shots.map((_, i) => i));
+ // Deterministic: the same inputs plan the same shots.
+ expect(planShots(VERSE, { ...GRID, clipCapacitySec: 5 }).shots).toEqual(shots);
});
- it('snaps off-grid section boundaries onto the beat grid, keeping the timeline contiguous', () => {
- // Energy-novelty segmentation cuts on 0.5s window edges, so a real analysis
- // routinely lands a boundary off the beat — 10.3s here snaps to the 10.5s
- // beat (the 10.0s downbeat is outside the tempo-derived tolerance).
- const inputs = planScenesFromSections([
- { label: 'A', startSec: 0, endSec: 10.3 },
- { label: 'B', startSec: 10.3, endSec: 18.2 },
- { label: 'C', startSec: 18.2, endSec: 30 },
- ], GRID);
- expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.5], [10.5, 18], [18, 30]]);
- expect(inputs.every((i) => i.beatAligned)).toBe(true);
+ it('uses a Grok clip capacity and a project pacing ceiling when given', () => {
+ const grok = planShots(VERSE, { ...GRID, clipCapacitySec: 10 }).shots;
+ expect(grok.every((s) => s.endSec - s.startSec <= 10)).toBe(true);
+ expect(grok.length).toBeLessThan(planShots(VERSE, { ...GRID, clipCapacitySec: 5 }).shots.length);
+ const paced = planShots(VERSE, { ...GRID, clipCapacitySec: 10, pacing: { maxShotSec: 4 } }).shots;
+ expect(paced.every((s) => s.endSec - s.startSec <= 4)).toBe(true);
+ expectTiles(paced, 0, 24);
});
- it('reports beatAligned:false on a scene whose edge could not snap', () => {
- // Nothing snapped, so the flag must not claim otherwise — render.js's
- // beatSnapClips then does its own live snapping instead of freezing the span.
- const inputs = planScenesFromSections([
- { label: 'A', startSec: 0, endSec: 10.3 },
- { label: 'B', startSec: 10.3, endSec: 30 },
- ], { ...GRID, toleranceSec: 0.05 });
- expect(inputs.every((i) => i.beatAligned === false)).toBe(true);
- expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.3], [10.3, 30]]);
+ it('holds the pacing floor at half the ceiling so any span can still be tiled', () => {
+ const { shots, pacing } = planShots([{ label: 'Long', startSec: 0, endSec: 25 }], {
+ ...GRID, pacing: { minShotSec: 8, maxShotSec: 10 },
+ });
+ expect(pacing.minShotSec).toBe(5);
+ expectTiles(shots, 0, 25);
+ expect(shots.every((s) => s.endSec - s.startSec >= 5 && s.endSec - s.startSec <= 10)).toBe(true);
});
- it('keeps the planned spans honored when the track has no usable tempo', () => {
- // No grid means no live snap to hand the span back to, so dropping the flag
- // would leave the render at each clip's raw source duration instead of the
- // planned section span — the plan would be silently discarded.
- const inputs = planScenesFromSections(SECTIONS, { beats: [], downbeats: [] });
- expect(inputs.every((i) => i.beatAligned === true)).toBe(true);
- expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10], [10, 18], [18, 30]]);
+ it('cuts on timed lyric lines (snapped to the beat) and attaches the lines each shot spans', () => {
+ const lyricCues = [
+ { text: 'line one', startSec: 4.1, endSec: 7.8 },
+ { text: 'line two', startSec: 9.9, endSec: 13.5 },
+ { text: 'line three', startSec: 14.05, endSec: 17 },
+ { text: 'untimed line', startSec: null, endSec: null },
+ ];
+ const sections = [
+ { label: 'Verse', startSec: 0, endSec: 20, energy: 0.5 },
+ { label: 'Solo', startSec: 20, endSec: 30, energy: 0.8 },
+ ];
+ const { shots } = planShots(sections, { ...GRID, lyricCues, clipCapacitySec: 5 });
+ expectTiles(shots, 0, 30);
+ const cuts = shots.map((s) => s.startSec);
+ // 4.1 / 9.9 / 14.05 are sung slightly off the beat; the cuts land on it.
+ expect(cuts).toEqual(expect.arrayContaining([4, 10, 14]));
+ const at = (t) => shots.find((s) => s.startSec === t);
+ expect(at(4).lyricText).toBe('line one');
+ expect(at(10).lyricText).toBe('line two');
+ expect(at(14).lyricText).toBe('line three');
+ // An untimed line is never placed, and the instrumental section invents nothing.
+ expect(shots.some((s) => s.lyricText?.includes('untimed'))).toBe(false);
+ const solo = shots.filter((s) => s.sectionLabel === 'Solo');
+ expect(solo.length).toBeGreaterThan(1);
+ expect(solo.every((s) => s.lyricText === null && s.sectionIndex === 1)).toBe(true);
});
- it('refuses a snap that would push a scene below the minimum scene length', () => {
- const inputs = planScenesFromSections([
- { label: 'A', startSec: 0, endSec: 10.3 },
- { label: 'B', startSec: 10.3, endSec: 30 },
- ], { ...GRID, minSceneSec: 25 });
- expect(inputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.3], [10.3, 30]]);
- expect(inputs.every((i) => i.beatAligned === false)).toBe(true);
+ it('carries phrase-level visual intent onto the shots it covers', () => {
+ const phrases = [{ label: 'Lift', startSec: 20, endSec: 30, intent: 'slow push toward the sun' }];
+ const { shots } = planShots(SECTIONS, { ...GRID, phrases, clipCapacitySec: 5 });
+ const outro = shots.filter((s) => s.startSec >= 20);
+ expect(outro.length).toBeGreaterThan(0);
+ expect(outro.every((s) => s.visualIntent === 'slow push toward the sun' && s.phraseLabel === 'Lift')).toBe(true);
+ expect(shots.filter((s) => s.endSec <= 18).every((s) => s.visualIntent === null)).toBe(true);
});
- it('falls back to an empty/null label when a section has no label', () => {
- const [input] = planScenesFromSections([{ startSec: 0, endSec: 5 }], GRID);
- expect(input.label).toBe('');
- expect(input.sectionLabel).toBeNull();
+ // Section edges still come from snapSectionsToGrid (#4664). A ceiling wider
+ // than every section keeps one shot per section so the edges are observable.
+ describe('section edges', () => {
+ const WIDE = { pacing: { maxShotSec: 60, hookSec: 60 } };
+
+ it('snaps off-grid section boundaries onto the beat grid, keeping the timeline contiguous', () => {
+ const { shots } = planShots([
+ { label: 'A', startSec: 0, endSec: 10.3 },
+ { label: 'B', startSec: 10.3, endSec: 18.2 },
+ { label: 'C', startSec: 18.2, endSec: 30 },
+ ], { ...GRID, ...WIDE });
+ expect(shots.map((s) => [s.startSec, s.endSec])).toEqual([[0, 10.5], [10.5, 18], [18, 30]]);
+ expect(shots.every((s) => s.beatAligned)).toBe(true);
+ });
+
+ it('reports beatAligned:false on a shot whose section edge could not snap', () => {
+ const { shots } = planShots([
+ { label: 'A', startSec: 0, endSec: 10.3 },
+ { label: 'B', startSec: 10.3, endSec: 30 },
+ ], { ...GRID, ...WIDE, toleranceSec: 0.05 });
+ expect(shots.every((s) => s.beatAligned === false)).toBe(true);
+ expect(shots.map((s) => [s.startSec, s.endSec])).toEqual([[0, 10.3], [10.3, 30]]);
+ });
+
+ it('keeps planned spans honored when the track has no usable tempo', () => {
+ const { shots } = planShots(SECTIONS, { beats: [], downbeats: [], clipCapacitySec: 5 });
+ expectTiles(shots, 0, 30);
+ expect(shots.every((s) => s.beatAligned === true && s.endSec - s.startSec <= 5)).toBe(true);
+ });
});
});
describe('buildScenePlanPrompt', () => {
- it('includes the project concept, style, and per-section index/label/duration/energy', () => {
- const prompt = buildScenePlanPrompt(makeProject(), SECTIONS);
+ it('includes the concept, style, and per-shot section/duration/energy/lyrics/intent', () => {
+ const { shots } = planShots(SECTIONS, {
+ beats: BEATS,
+ downbeats: DOWNBEATS,
+ clipCapacitySec: 10,
+ lyricCues: [{ text: 'we run the night', startSec: 10, endSec: 14 }],
+ phrases: [{ label: 'Lift', startSec: 18, endSec: 30, intent: 'the city falls away' }],
+ });
+ const prompt = buildScenePlanPrompt(makeProject(), shots);
expect(prompt).toContain('Neon Nights');
expect(prompt).toContain('cyberpunk chase');
expect(prompt).toContain('neon, rain-slicked streets');
- expect(prompt).toContain('0. "Intro" — 10.0s, normalized energy 0.20');
- expect(prompt).toContain('1. "Drop" — 8.0s, normalized energy 0.95');
+ expect(prompt).toMatch(/0\. "Intro" shot 1\/\d+ — \d+\.\ds, energy 0\.20; instrumental; OPENING HOOK/);
+ expect(prompt).toContain('"Drop" shot 1/');
+ expect(prompt).toContain('lyrics: "we run the night"');
+ expect(prompt).toContain('intent: the city falls away');
+ expect(prompt).toContain('Never render the lyrics as on-screen text');
expect(prompt).toContain('JSON array');
});
+
+ it('omits the lyric guidance for a track with no lyrics', () => {
+ const { shots } = planShots(SECTIONS, { beats: BEATS, downbeats: DOWNBEATS });
+ const prompt = buildScenePlanPrompt(makeProject(), shots);
+ expect(prompt).not.toContain('lyrics:');
+ expect(prompt).not.toContain('on-screen text');
+ });
});
describe('planProject', () => {
@@ -176,7 +245,7 @@ describe('planProject', () => {
return { project: { ...makeProject(), renderHistoryId: 'rh-fresh', scenes: FRESH_SCENES, ...overrides }, scenes: FRESH_SCENES };
}
- it('seeds one scene per section, calls getProject exactly once, and returns the freshly-persisted project from addProjectScenes', async () => {
+ it('seeds several non-looping shots per section, calls getProject exactly once, and returns the freshly-persisted project from addProjectScenes', async () => {
const project = makeProject();
getProject.mockResolvedValue(project);
addProjectScenes.mockResolvedValue(freshProjectResult());
@@ -185,10 +254,14 @@ describe('planProject', () => {
const result = await planProject('mv-1');
expect(getProject).toHaveBeenCalledTimes(1);
- expect(addProjectScenes).toHaveBeenCalledWith('mv-1', expect.arrayContaining([
- expect.objectContaining({ label: 'Intro', startSec: 0, endSec: 10 }),
- ]));
- expect(addProjectScenes.mock.calls[0][1]).toHaveLength(3);
+ // Local renderer (5s clips): 30s of sections → more shots than sections,
+ // each labeled within its section and never looping by default.
+ const seeded = addProjectScenes.mock.calls[0][1];
+ expect(seeded.length).toBeGreaterThan(3);
+ expect(seeded[0]).toMatchObject({ label: expect.stringMatching(/^Intro · 1\/\d+$/), sectionLabel: 'Intro', sectionIndex: 0, startSec: 0, loop: false });
+ expect(seeded.every((scene) => scene.loop === false && scene.endSec - scene.startSec <= 5)).toBe(true);
+ expect(seeded.at(-1)).toMatchObject({ sectionLabel: 'Outro', sectionIndex: 2, endSec: 30 });
+ expect(result.pacing).toEqual({ minShotSec: 2, maxShotSec: 5, hookSec: 3 });
expect(runPromptThroughProvider).not.toHaveBeenCalled();
expect(result.project.renderHistoryId).toBe('rh-fresh');
expect(result.scenesAdded).toBe(3);
@@ -318,7 +391,7 @@ Here is my answer:
warnSpy.mockRestore();
});
- it('threads the cached beat grid into the snap, so seeded spans cut on the music', async () => {
+ it('threads the cached beat grid, lyrics, and pacing into the plan', async () => {
getProject.mockResolvedValue(makeProject({
audioAnalysis: {
bpm: 120,
@@ -330,14 +403,23 @@ Here is my answer:
{ label: 'B', startSec: 10.3, endSec: 30, energy: 0.9 },
],
},
+ videoSettings: { backend: 'grok', grokDuration: 10 },
+ pacing: { maxShotSec: 8 },
+ lyricCues: [{ id: 'lc-1', text: 'hold on', startSec: 12.1, endSec: 15 }],
}));
addProjectScenes.mockResolvedValue(freshProjectResult());
await planProject('mv-1', { seedPrompts: false });
const seededInputs = addProjectScenes.mock.calls[0][1];
- expect(seededInputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10.5], [10.5, 30]]);
- expect(seededInputs.every((i) => i.beatAligned)).toBe(true);
+ // Section B starts on the snapped 10.5s beat; the project ceiling (8s)
+ // wins over the Grok clip length (10s).
+ expect(seededInputs.find((i) => i.sectionIndex === 1).startSec).toBe(10.5);
+ expect(seededInputs.every((i) => i.beatAligned && i.endSec - i.startSec <= 8)).toBe(true);
+ const lyricShots = seededInputs.filter((i) => i.lyricText === 'hold on');
+ expect(lyricShots).toHaveLength(1);
+ expect(lyricShots[0].startSec).toBeLessThanOrEqual(12.1);
+ expect(lyricShots[0].endSec).toBeGreaterThanOrEqual(15);
});
it('still honors the planned spans when the cached analysis has no beat grid', async () => {
@@ -350,6 +432,8 @@ Here is my answer:
const seededInputs = addProjectScenes.mock.calls[0][1];
expect(seededInputs.every((i) => i.beatAligned === true)).toBe(true);
- expect(seededInputs.map((i) => [i.startSec, i.endSec])).toEqual([[0, 10], [10, 18], [18, 30]]);
+ expect(seededInputs[0].startSec).toBe(0);
+ expect(seededInputs.at(-1).endSec).toBe(30);
+ for (let i = 1; i < seededInputs.length; i++) expect(seededInputs[i].startSec).toBe(seededInputs[i - 1].endSec);
});
});
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
index f16e799532..7d14f6fe19 100644
--- a/server/services/musicVideo/projectsFile.test.js
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -108,6 +108,68 @@ describe('projectsFile federation (#1770)', () => {
expect((await file.listProjectIds({ includeDeleted: true })).sort()).toEqual([a.id, b.id].sort());
});
+ // #8964 — timed lyric cues, phrase annotations, pacing, and per-shot loop
+ // semantics are editable record state: they must survive reload, clone, and
+ // a peer round trip, and an audio-source change must invalidate the timings
+ // (derived from the old track) while keeping the director's text.
+ it('persists timed text + shot fields through reload, clone, and peer sync; an audio change clears the timings', async () => {
+ const p = await file.createProject({ name: 'Lyric MV', trackId: 't1' });
+ expect(p).toMatchObject({ lyricCues: [], phrases: [], pacing: null });
+
+ await file.updateProject(p.id, {
+ lyricCues: [
+ { text: ' first line ', startSec: 1.25, endSec: 3 },
+ { text: ' ', startSec: 4 }, // empty → dropped
+ { text: 'second line', startSec: 5, endSec: 4 }, // backwards end → open end
+ { text: 'untimed line' },
+ ],
+ phrases: [{ label: 'Lift', startSec: 8, endSec: 16, intent: 'rise above the city' }],
+ pacing: { minShotSec: 1.5, maxShotSec: 6, hookSec: 2 },
+ });
+ const saved = await file.getProject(p.id);
+ expect(saved.lyricCues).toEqual([
+ { id: expect.stringMatching(/^lc-/), text: 'first line', startSec: 1.25, endSec: 3 },
+ { id: expect.stringMatching(/^lc-/), text: 'second line', startSec: 5, endSec: null },
+ { id: expect.stringMatching(/^lc-/), text: 'untimed line', startSec: null, endSec: null },
+ ]);
+ expect(saved.phrases).toEqual([
+ { id: expect.stringMatching(/^mp-/), label: 'Lift', intent: 'rise above the city', startSec: 8, endSec: 16 },
+ ]);
+ // Editing a line keeps its id (the list is replaced whole, entries by id).
+ const retimed = saved.lyricCues.map((c, i) => (i === 2 ? { ...c, startSec: 9 } : c));
+ const edited = await file.updateProject(p.id, { lyricCues: retimed });
+ expect(edited.lyricCues.map((c) => c.id)).toEqual(saved.lyricCues.map((c) => c.id));
+ expect(edited.lyricCues[2].startSec).toBe(9);
+
+ // A new scene never loops by default; planned shot fields persist.
+ await file.addProjectScenes(p.id, [
+ { label: 'Verse · 1/2', sectionLabel: 'Verse', sectionIndex: 0, startSec: 0, endSec: 4, beatAligned: true, lyricText: 'first line' },
+ { label: 'Verse · 2/2', sectionLabel: 'Verse', sectionIndex: 0, startSec: 4, endSec: 8, beatAligned: true, loop: true, visualIntent: 'hold' },
+ ]);
+ const withScenes = await file.getProject(p.id);
+ expect(withScenes.scenes.map((s) => [s.loop, s.sectionIndex, s.lyricText, s.visualIntent]))
+ .toEqual([[false, 0, 'first line', null], [true, 0, null, 'hold']]);
+
+ const clone = await file.cloneProject(p.id);
+ expect(clone.lyricCues).toEqual(edited.lyricCues);
+ expect(clone.phrases).toEqual(saved.phrases);
+ expect(clone.pacing).toEqual({ minShotSec: 1.5, maxShotSec: 6, hookSec: 2 });
+ expect(clone.scenes.map((s) => s.loop)).toEqual([false, true]);
+
+ // Peer round trip: a record carrying these fields lands verbatim.
+ const peerCopy = { ...withScenes, id: 'mv-peer-lyrics', updatedAt: '2099-01-01T00:00:00Z' };
+ await file.mergeProjectsFromSync([peerCopy]);
+ const received = await file.getProject('mv-peer-lyrics');
+ expect(received.lyricCues).toEqual(withScenes.lyricCues);
+ expect(received.phrases).toEqual(withScenes.phrases);
+ expect(received.scenes).toEqual(withScenes.scenes);
+
+ const swapped = await file.updateProject(p.id, { trackId: 't2' });
+ expect(swapped.lyricCues.map((c) => [c.id, c.text, c.startSec, c.endSec]))
+ .toEqual(edited.lyricCues.map((c) => [c.id, c.text, null, null]));
+ expect(swapped.phrases).toEqual([{ ...saved.phrases[0], startSec: null, endSec: null }]);
+ });
+
it('mergeProjectsFromSync inserts a brand-new peer record', async () => {
const remote = { id: 'mv-peer-1', name: 'Peer', status: 'draft', updatedAt: '2026-02-01T00:00:00Z', createdAt: '2026-02-01T00:00:00Z', scenes: [] };
const res = await file.mergeProjectsFromSync([remote]);
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 22dbc5cb99..1de6d54a9c 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -28,6 +28,7 @@ import { stripMusicVideoLocalRenderPins } from '../../lib/syncWire.js';
import { persistedRenderPinFields } from '../../lib/renderTargets.js';
import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
import { isStr } from '../../lib/textUtils.js';
+import { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';
export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
@@ -92,6 +93,11 @@ export function buildProjectRecord(input, { id, now }) {
...persistedRenderPinFields(input),
audioAnalysis: null,
midiTranscription: null,
+ // #8964 — editable timed lyric cues + phrase annotations (timed against
+ // the current audio source) and the shot planner's pacing range.
+ lyricCues: [],
+ phrases: [],
+ pacing: null,
scenes: [],
renderHistoryId: null,
// Soft-delete tombstone trio — kept so peer-sync federation (a follow-up)
@@ -153,9 +159,16 @@ export function applyProjectPatch(project, patch) {
// below, so a caller sending only the sub-field it edited (e.g. { style: '…' })
// can't clobber a sibling sub-field (e.g. prompt) set concurrently by another
// sync peer (#3168). An explicit `concept: null` still clears it outright.
- const conceptMergedPatch = ('concept' in patch && patch.concept && project.concept)
- ? { ...patch, concept: { ...project.concept, ...patch.concept } }
- : patch;
+ // Edited cue/phrase lists replace the stored list whole, normalized so every
+ // entry persists a stable id and a forward time range (timedText.js).
+ const timedPatch = {
+ ...patch,
+ ...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues) } : {}),
+ ...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),
+ };
+ const conceptMergedPatch = ('concept' in timedPatch && timedPatch.concept && project.concept)
+ ? { ...timedPatch, concept: { ...project.concept, ...timedPatch.concept } }
+ : timedPatch;
// Renderer settings are edited independently in the UI. Merge a partial
// change so picking a model cannot discard the provider or Grok duration.
const mergedPatch = ('videoSettings' in conceptMergedPatch && conceptMergedPatch.videoSettings)
@@ -198,7 +211,17 @@ export function applyProjectPatch(project, patch) {
const statusPatch = regressStatus ? { status: 'draft' } : {};
// The MIDI transcription was produced from the OLD audio too — clear it with
// the analysis so a stale .mid can't masquerade as the new track's score.
- return touch(project, { ...mergedPatch, ...statusPatch, audioAnalysis: null, midiTranscription: null, scenes });
+ // Lyric-cue and phrase timings were aligned to the OLD audio as well: keep the
+ // director's text but clear the times (#8964), unless this same patch supplied
+ // fresh lists of its own.
+ return touch(project, {
+ ...invalidateTimedText(project),
+ ...mergedPatch,
+ ...statusPatch,
+ audioAnalysis: null,
+ midiTranscription: null,
+ scenes,
+ });
}
/**
@@ -236,6 +259,13 @@ function buildScene(input, { order }) {
beatAligned: input.beatAligned ?? false,
prompt: input.prompt ?? '',
framePrompt: input.framePrompt ?? null,
+ // #8964: a new shot never silently repeats its clip to fill a span — looping
+ // is an explicit choice. (Pre-#8964 scenes carry no `loop` key and keep the
+ // legacy loop-to-fill render; see render.js#sceneLoops.)
+ loop: input.loop ?? false,
+ sectionIndex: input.sectionIndex ?? null,
+ lyricText: input.lyricText ?? null,
+ visualIntent: input.visualIntent ?? null,
referenceImageId: null,
videoHistoryId: null,
};
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index a54fbcb2d0..baa78a255f 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -60,6 +60,37 @@ const appendToVideoHistory = (meta) =>
export const attachRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+// #8964 loop semantics. A scene saved before shot planning existed has no
+// `loop` key and keeps the legacy behavior — its clip repeats to fill the
+// authored span — so existing projects render exactly as they did. A scene
+// created since carries an explicit boolean, and only `loop: true` repeats.
+export const sceneLoops = (scene) => scene?.loop !== false;
+
+// A non-looping shot may run this much past its source clip; the gap holds the
+// final frame (tpad) rather than repeating footage. Longer shortfalls block the
+// render until the director resolves them.
+export const COVERAGE_TOLERANCE_SEC = 0.25;
+export const COVERAGE_RESOLUTIONS = Object.freeze(['trim', 'continue', 'replace', 'loop']);
+
+/**
+ * Pure: the snapped clips whose authored span needs more footage than their
+ * non-looping source clip provides. Returns
+ * `[{ sceneId, spanSec, clipSec, shortBySec }]` (empty when every shot is covered).
+ */
+export function findCoverageShortfalls(clips, { toleranceSec = COVERAGE_TOLERANCE_SEC } = {}) {
+ const out = [];
+ for (const clip of Array.isArray(clips) ? clips : []) {
+ if (clip.loop !== false) continue;
+ const spanSec = clip.outSec - clip.inSec;
+ const clipSec = clip.sourceSec ?? clip.duration;
+ if (spanSec - clipSec > toleranceSec) {
+ const round = (n) => Math.round(n * 100) / 100;
+ out.push({ sceneId: clip.sceneId, spanSec: round(spanSec), clipSec: round(clipSec), shortBySec: round(spanSec - clipSec) });
+ }
+ }
+ return out;
+}
+
export function getRenderJobStatus(jobId) {
const job = jobs.get(jobId);
if (!job) return null;
@@ -130,6 +161,10 @@ export async function resolveSceneClips(project) {
height: entry.height,
fps: entry.fps || 24,
duration,
+ // The native source length survives the snap below (which rewrites
+ // `duration` to the rendered span) so coverage can be judged against it.
+ sourceSec: duration,
+ loop: sceneLoops(scene),
inSec: 0,
outSec: duration,
});
@@ -146,7 +181,8 @@ export async function resolveSceneClips(project) {
// analyzed beat, when one is within `toleranceSec` and the trim keeps the clip
// at least `minClipSec` long. This derived, non-authored snap only SHORTENS a
// source clip. A director-authored beatAligned span is handled separately
-// below and may exceed the native clip because the ffmpeg builder loops it.
+// below and may exceed the native clip: a looping scene fills it by repeating
+// the clip, a non-looping one is caught by findCoverageShortfalls (#8964).
// Returns a NEW clips array with adjusted `outSec`/`duration`.
// With no beats (no analysis) and no persisted scene arrangement, clips are
// returned unchanged.
@@ -171,10 +207,11 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =
if (scene?.beatAligned && typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec) {
// inSec stays 0 here deliberately: this only ever trims how much of the
// clip plays, never which frames — there is no in-point/out-point
- // distinction. A planned music-video scene commonly spans much longer
- // than one generated 6–10s source clip; buildMusicVideoFfmpegArgs loops
- // that input, so the authored timeline duration is allowed to exceed the
- // source duration instead of silently truncating the final song.
+ // distinction. A legacy planned scene commonly spans much longer than
+ // one generated 6–10s source clip; buildMusicVideoFfmpegArgs loops a
+ // looping input, so the authored timeline duration is allowed to exceed
+ // the source duration instead of silently truncating the final song. A
+ // non-looping shot that does so is refused before render (#8964).
const outSec = Math.max(minClipSec, scene.endSec - scene.startSec);
running += outSec;
return { ...clip, inSec: 0, outSec, duration: outSec };
@@ -215,10 +252,15 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
const inputs = [];
// A generated scene clip is a reusable shot source, while the director's
- // timeline owns how long that shot appears in the music video. Loop each
- // finite clip input so a 6–10s Grok/local result can fill a longer verse or
- // chorus span; the per-input trim below still makes every loop finite.
- for (const c of clips) inputs.push('-stream_loop', '-1', '-i', c.videoPath);
+ // timeline owns how long that shot appears in the music video. A LOOPING
+ // clip input repeats so a 6–10s Grok/local result can fill a longer verse or
+ // chorus span; the per-input trim below still makes every loop finite. A
+ // non-looping clip (#8964, `loop: false`) is read once — the render preflight
+ // guarantees its span fits, within COVERAGE_TOLERANCE_SEC.
+ for (const c of clips) {
+ if (c.loop !== false) inputs.push('-stream_loop', '-1');
+ inputs.push('-i', c.videoPath);
+ }
const audioIdx = clips.length; // master audio is the last input
inputs.push('-i', audioPath);
@@ -226,10 +268,14 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
const vStreams = [];
for (let i = 0; i < clips.length; i++) {
const c = clips[i];
+ // A non-looping shot a hair longer than its source holds the last frame for
+ // the remainder instead of ending early and drifting every later cut.
+ const holdSec = c.loop === false ? (c.outSec - c.inSec) - (c.sourceSec ?? c.duration) : 0;
+ const hold = holdSec > 0 ? `tpad=stop_mode=clone:stop_duration=${Math.round(holdSec * 1000) / 1000},` : '';
filters.push(
`[${i}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,`
+ `pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},`
- + `trim=start=${c.inSec}:end=${c.outSec},setpts=PTS-STARTPTS[v${i}]`,
+ + `${hold}trim=start=${c.inSec}:end=${c.outSec},setpts=PTS-STARTPTS[v${i}]`,
);
vStreams.push(`[v${i}]`);
}
@@ -283,6 +329,16 @@ export async function renderMusicVideo(projectId) {
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 } },
+ );
+ }
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index 44f420c15e..e7c2e25bc2 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -21,8 +21,9 @@ const h = vi.hoisted(() => {
},
};
};
- const spawn = () => {
+ const spawn = (_cmd, args) => {
const p = makeEmitter();
+ p.args = args;
p.stderr = makeEmitter();
p.kill = () => {};
procs.push(p);
@@ -261,3 +262,59 @@ it('chooses the loudest section midpoint within the rendered duration', async ()
expect(generateThumbnail).toHaveBeenCalledWith(expect.any(String), jobId, { atSec: 1.5 });
expect(getRenderJobStatus(jobId).status).toBe('complete');
});
+
+// #8964 — loop semantics at the render boundary. A pre-#8964 scene (no `loop`
+// key) keeps filling its authored span by repeating the clip; a planned shot
+// (`loop: false`) may never silently repeat, so a span its clip cannot cover
+// blocks the render with the shots to fix, and never spawns ffmpeg.
+describe('renderMusicVideo clip coverage (#8964)', () => {
+ const primeScene = (projectId, scene) => {
+ prime(projectId);
+ getProject.mockResolvedValue({
+ id: projectId, name: 'P', trackId: 't1', status: 'ready',
+ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1', beatAligned: true, ...scene }],
+ });
+ };
+ const filterGraph = (args) => args[args.indexOf('-filter_complex') + 1];
+
+ it('keeps looping a legacy scene across a span longer than its clip', async () => {
+ primeScene('legacy-1', { startSec: 0, endSec: 20 });
+ await renderMusicVideo('legacy-1');
+ const { args } = lastProc();
+ expect(args.slice(0, 3)).toEqual(['-stream_loop', '-1', '-i']);
+ expect(filterGraph(args)).toContain('trim=start=0:end=20');
+ });
+
+ it('refuses a non-looping shot its clip cannot cover, naming the fix, without spawning', async () => {
+ primeScene('short-1', { startSec: 0, endSec: 20, loop: false });
+ const expected = {
+ status: 422,
+ code: 'INSUFFICIENT_CLIP_COVERAGE',
+ context: {
+ shortfalls: [{ sceneId: 's1', spanSec: 20, clipSec: 2, shortBySec: 18 }],
+ resolutions: ['trim', 'continue', 'replace', 'loop'],
+ },
+ };
+ await expect(renderMusicVideo('short-1')).rejects.toMatchObject(expected);
+ expect(h.procs).toHaveLength(0);
+ expect(updateProject).not.toHaveBeenCalled();
+ // The slot is released: a retry re-checks coverage instead of 409ing.
+ await expect(renderMusicVideo('short-1')).rejects.toMatchObject({ code: 'INSUFFICIENT_CLIP_COVERAGE' });
+ });
+
+ it('reads a covered non-looping shot once and holds its last frame over a sub-tolerance gap', async () => {
+ primeScene('fit-1', { startSec: 0, endSec: 2.2, loop: false });
+ await renderMusicVideo('fit-1');
+ const { args } = lastProc();
+ expect(args).not.toContain('-stream_loop');
+ expect(filterGraph(args)).toContain('tpad=stop_mode=clone:stop_duration=0.2,trim=start=0:end=2.2');
+ });
+
+ it('repeats a shot the director explicitly set to loop', async () => {
+ primeScene('loop-1', { startSec: 0, endSec: 20, loop: true });
+ await renderMusicVideo('loop-1');
+ const { args } = lastProc();
+ expect(args).toContain('-stream_loop');
+ expect(filterGraph(args)).not.toContain('tpad');
+ });
+});
diff --git a/server/services/musicVideo/shotPlan.js b/server/services/musicVideo/shotPlan.js
new file mode 100644
index 0000000000..4d2059cdd6
--- /dev/null
+++ b/server/services/musicVideo/shotPlan.js
@@ -0,0 +1,240 @@
+/**
+ * Music Video — deterministic shot plan (#8964).
+ *
+ * The planner used to seed ONE scene per analyzed section, so a 30s verse
+ * became one 30s scene that the renderer then filled by looping a 6–10s
+ * generated clip. This module instead tiles every section with several
+ * bounded shots:
+ *
+ * - no shot is longer than the pacing ceiling (by default the renderer's
+ * clip capacity), so each shot can be covered by ONE generated clip;
+ * - no shot is shorter than the pacing floor (a section shorter than the
+ * floor stays a single shot);
+ * - the very first shot is capped at the opening-hook length;
+ * - cuts prefer, in order: a timed lyric-line / phrase boundary (snapped to
+ * the beat grid when one is close), a downbeat, a beat — picking the
+ * candidate nearest an even split of what remains, so pacing stays even;
+ * - shots inside a section tile it exactly (no gap, no overlap), so the plan
+ * covers the same timeline the sections did.
+ *
+ * Every shot keeps its section identity (`sectionIndex` + `sectionLabel`) and
+ * carries the lyric lines and phrase intent it spans, which the prompt seeder
+ * reads. An instrumental stretch carries `lyricText: null` — nothing is
+ * invented. Pure and deterministic: same inputs → same plan.
+ */
+
+import { snapSectionsToGrid } from './audioAnalysis.js';
+
+const EPS = 1e-6;
+const SECTION_LABEL_MAX = 120;
+const LYRIC_TEXT_MAX = 2000;
+// A lyric/phrase boundary within this distance of a grid point cuts ON the grid
+// point: sung phrasing drifts a little off the beat, the picture should not.
+const BOUNDARY_SNAP_SEC = 0.2;
+// An untimed-end cue lasts until the next cue, capped here.
+const OPEN_CUE_MAX_SEC = 8;
+// Grok renders fixed 6s/10s clips; a local model's default render is ~5s
+// (121 frames at 24fps). A project pacing ceiling overrides either.
+export const DEFAULT_LOCAL_CLIP_CAPACITY_SEC = 5;
+const DEFAULT_MIN_SHOT_SEC = 2;
+const DEFAULT_HOOK_SEC = 3;
+
+const round3 = (n) => Math.round(n * 1000) / 1000;
+const sortedGrid = (list) => (Array.isArray(list) ? list : [])
+ .filter((t) => typeof t === 'number' && Number.isFinite(t) && t >= 0)
+ .sort((a, b) => a - b);
+
+/** Seconds of footage one generated clip provides for the project's renderer. */
+export function resolveClipCapacitySec(videoSettings) {
+ if (videoSettings?.backend === 'grok') return videoSettings.grokDuration === 6 ? 6 : 10;
+ return DEFAULT_LOCAL_CLIP_CAPACITY_SEC;
+}
+
+/**
+ * Resolve the effective pacing range. The floor is held at or below half the
+ * ceiling so any span longer than the ceiling can always be tiled within
+ * [floor, ceiling]; the hook is clamped into the same range.
+ */
+export function resolvePacing(pacing, clipCapacitySec) {
+ const maxShotSec = Math.max(1, pacing?.maxShotSec ?? clipCapacitySec);
+ const minShotSec = Math.min(pacing?.minShotSec ?? DEFAULT_MIN_SHOT_SEC, maxShotSec / 2);
+ const hookSec = Math.min(maxShotSec, Math.max(minShotSec, pacing?.hookSec ?? DEFAULT_HOOK_SEC));
+ return { minShotSec, maxShotSec, hookSec };
+}
+
+/** Timed cues sorted by start, each with a resolved end (explicit, next cue, or capped open end). */
+export function timedCues(cues) {
+ const timed = (Array.isArray(cues) ? cues : [])
+ .filter((c) => c && typeof c.text === 'string' && c.text.trim() && typeof c.startSec === 'number')
+ .slice()
+ .sort((a, b) => a.startSec - b.startSec);
+ return timed.map((c, i) => {
+ const next = timed[i + 1];
+ const openEnd = Math.min(c.startSec + OPEN_CUE_MAX_SEC, next ? next.startSec : Infinity);
+ const endSec = typeof c.endSec === 'number' && c.endSec > c.startSec ? c.endSec : openEnd;
+ return { text: c.text.trim(), startSec: c.startSec, endSec };
+ });
+}
+
+function timedPhrases(phrases) {
+ return (Array.isArray(phrases) ? phrases : [])
+ .filter((p) => p && typeof p.startSec === 'number' && typeof p.endSec === 'number' && p.endSec > p.startSec);
+}
+
+function nearestWithin(grid, t, tol) {
+ let best = null;
+ for (const g of grid) {
+ if (Math.abs(g - t) <= tol && (best == null || Math.abs(g - t) < Math.abs(best - t))) best = g;
+ }
+ return best;
+}
+
+/**
+ * Tier-ordered cut candidates: 0 = lyric/phrase boundary, 1 = downbeat, 2 = beat.
+ * A boundary near a grid point is moved onto it (and counts as on-grid).
+ */
+function buildCandidates({ cues, phrases, beats, downbeats }) {
+ const grid = [...downbeats, ...beats];
+ const out = [];
+ const boundaries = [
+ ...cues.map((c) => c.startSec),
+ ...phrases.flatMap((p) => [p.startSec, p.endSec]),
+ ];
+ for (const b of boundaries) {
+ const snapped = nearestWithin(grid, b, BOUNDARY_SNAP_SEC);
+ out.push({ t: snapped ?? b, tier: 0, onGrid: snapped != null });
+ }
+ for (const t of downbeats) out.push({ t, tier: 1, onGrid: true });
+ for (const t of beats) out.push({ t, tier: 2, onGrid: true });
+ return out;
+}
+
+/**
+ * Split one section span into contiguous shot spans. Returns
+ * `[{ startSec, endSec, cutOnGrid }]` where `cutOnGrid` says whether the
+ * shot's END is an interior cut that landed on the grid (the section's own
+ * edges are judged by the caller).
+ */
+function splitSpan(startSec, endSec, { minShotSec, maxShotSec, firstMaxSec, candidates, hasGrid }) {
+ const shots = [];
+ let cursor = startSec;
+ let localMax = firstMaxSec ?? maxShotSec;
+ while (endSec - cursor > localMax + EPS) {
+ const remaining = endSec - cursor;
+ const lo = cursor + minShotSec;
+ const hi = Math.min(cursor + localMax, endSec - minShotSec);
+ if (hi < lo - EPS) {
+ // Only the hook can make the window empty (a ceiling below 2× floor is
+ // excluded by resolvePacing): drop the hook cap rather than violate the floor.
+ if (localMax < maxShotSec) { localMax = maxShotSec; continue; }
+ break;
+ }
+ const pieces = Math.max(2, Math.ceil(remaining / maxShotSec));
+ const ideal = Math.min(hi, Math.max(lo, cursor + Math.min(localMax, remaining / pieces)));
+ let pick = null;
+ for (let tier = 0; tier <= 2 && !pick; tier++) {
+ for (const c of candidates) {
+ if (c.tier !== tier || c.t < lo - EPS || c.t > hi + EPS) continue;
+ if (!pick || Math.abs(c.t - ideal) < Math.abs(pick.t - ideal) - EPS) pick = c;
+ }
+ }
+ const cut = pick ? round3(pick.t) : round3(ideal);
+ shots.push({ startSec: cursor, endSec: cut, cutOnGrid: pick ? pick.onGrid : !hasGrid });
+ cursor = cut;
+ localMax = maxShotSec;
+ }
+ shots.push({ startSec: cursor, endSec: endSec, cutOnGrid: null });
+ return shots;
+}
+
+function overlapSec(aStart, aEnd, bStart, bEnd) {
+ return Math.max(0, Math.min(aEnd, bEnd) - Math.max(aStart, bStart));
+}
+
+// A line belongs to a shot when a meaningful part of it plays inside the shot:
+// at least half the line, or half a second of it.
+function lyricsFor(cues, startSec, endSec) {
+ const lines = cues.filter((c) => {
+ const overlap = overlapSec(startSec, endSec, c.startSec, c.endSec);
+ return overlap > EPS && (overlap >= 0.5 || overlap >= (c.endSec - c.startSec) / 2);
+ }).map((c) => c.text);
+ return lines.length > 0 ? lines.join(' / ').slice(0, LYRIC_TEXT_MAX) : null;
+}
+
+function phraseFor(phrases, startSec, endSec) {
+ let best = null;
+ let bestOverlap = 0;
+ for (const p of phrases) {
+ const overlap = overlapSec(startSec, endSec, p.startSec, p.endSec);
+ if (overlap > bestOverlap + EPS) { best = p; bestOverlap = overlap; }
+ }
+ return best;
+}
+
+/**
+ * Plan the shot list for a project.
+ *
+ * @param {Array<object>} sections — already filtered via planner.validSections
+ * @param {object} options
+ * @param {number[]} [options.beats]
+ * @param {number[]} [options.downbeats]
+ * @param {Array<object>} [options.lyricCues]
+ * @param {Array<object>} [options.phrases]
+ * @param {object} [options.pacing] — the project's `pacing` (nullable)
+ * @param {number} [options.clipCapacitySec]
+ * @param {number} [options.toleranceSec] / [options.minSceneSec] — section-snap overrides (tests)
+ * @returns {{ shots: Array<object>, pacing: object }}
+ * each shot: `{ sectionIndex, sectionLabel, sectionEnergy, shotIndex, shotCount,
+ * startSec, endSec, beatAligned, lyricText, phraseLabel, visualIntent, hook }`
+ */
+export function planShots(sections, {
+ beats = [], downbeats = [], lyricCues = [], phrases = [], pacing = null,
+ clipCapacitySec = DEFAULT_LOCAL_CLIP_CAPACITY_SEC, toleranceSec, minSceneSec,
+} = {}) {
+ const beatGrid = sortedGrid(beats);
+ const downbeatGrid = sortedGrid(downbeats);
+ const hasGrid = beatGrid.length > 0 || downbeatGrid.length > 0;
+ const resolved = resolvePacing(pacing, clipCapacitySec);
+ const cues = timedCues(lyricCues);
+ const marks = timedPhrases(phrases);
+ const candidates = buildCandidates({ cues, phrases: marks, beats: beatGrid, downbeats: downbeatGrid });
+
+ const { sections: snapped, beatAligned } = snapSectionsToGrid(sections, {
+ downbeats: downbeatGrid, beats: beatGrid,
+ ...(toleranceSec != null ? { toleranceSec } : {}),
+ ...(minSceneSec != null ? { minSceneSec } : {}),
+ });
+
+ const shots = [];
+ snapped.forEach((section, sectionIndex) => {
+ const label = typeof section.label === 'string' ? section.label.slice(0, SECTION_LABEL_MAX) : '';
+ const spans = splitSpan(section.startSec, section.endSec, {
+ ...resolved,
+ firstMaxSec: sectionIndex === 0 ? resolved.hookSec : null,
+ candidates,
+ hasGrid,
+ });
+ spans.forEach((span, shotIndex) => {
+ // The section's own edges carry snapSectionsToGrid's verdict; an interior
+ // edge carries whether its cut landed on the grid.
+ const startOk = shotIndex === 0 ? beatAligned[sectionIndex] : spans[shotIndex - 1].cutOnGrid;
+ const endOk = shotIndex === spans.length - 1 ? beatAligned[sectionIndex] : span.cutOnGrid;
+ const phrase = phraseFor(marks, span.startSec, span.endSec);
+ shots.push({
+ sectionIndex,
+ sectionLabel: label || null,
+ sectionEnergy: typeof section.energy === 'number' ? section.energy : null,
+ shotIndex,
+ shotCount: spans.length,
+ startSec: round3(span.startSec),
+ endSec: round3(span.endSec),
+ beatAligned: !!(startOk && endOk),
+ lyricText: lyricsFor(cues, span.startSec, span.endSec),
+ phraseLabel: phrase?.label || null,
+ visualIntent: phrase?.intent || null,
+ hook: sectionIndex === 0 && shotIndex === 0,
+ });
+ });
+ });
+ return { shots, pacing: resolved };
+}
diff --git a/server/services/musicVideo/timedText.js b/server/services/musicVideo/timedText.js
new file mode 100644
index 0000000000..c06024b48e
--- /dev/null
+++ b/server/services/musicVideo/timedText.js
@@ -0,0 +1,168 @@
+/**
+ * Music Video — timed lyric cues + musical-phrase annotations (#8964).
+ *
+ * Both lists live on the project record (`lyricCues`, `phrases`) and are
+ * whole-list replaced by a project PATCH, so the director can edit, retime, or
+ * delete any entry. This module owns the storage-agnostic pieces: importing
+ * cue text (LRC / SRT / WebVTT / plain lines), normalizing an edited list so it
+ * always persists a stable id and a sane time range, and invalidating the
+ * timings when the project's audio source changes.
+ *
+ * Timings are alignment DERIVED from one specific audio file; the text is the
+ * director's own. So an audio-source change keeps every line and label but
+ * clears their times (`startSec`/`endSec` → null) — the planner then ignores
+ * them until they are re-timed against the new track, instead of cutting the
+ * new song on the old song's lyric positions.
+ */
+
+import { randomUUID } from 'crypto';
+
+const MAX_CUE_TEXT = 500;
+const MAX_SEC = 36000;
+
+const round3 = (n) => Math.round(n * 1000) / 1000;
+
+function toTime(value) {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_SEC
+ ? round3(value)
+ : null;
+}
+
+// A range with an end before its start keeps the start and drops the end —
+// the start is what the planner cuts on; a missing end is derived from the next
+// cue at plan time.
+function normalizeRange(entry) {
+ const startSec = toTime(entry?.startSec);
+ const end = toTime(entry?.endSec);
+ return { startSec, endSec: startSec != null && end != null && end > startSec ? end : null };
+}
+
+// Keep each entry's id (minting one for a new or duplicated entry) so a
+// whole-list replace still addresses the same rows; `shape` returns the
+// entry's authored fields, or null to drop it.
+function normalizeList(list, prefix, shape) {
+ if (!Array.isArray(list)) return [];
+ const seen = new Set();
+ const out = [];
+ for (const entry of list) {
+ const fields = entry && typeof entry === 'object' ? shape(entry) : null;
+ if (!fields) continue;
+ const given = typeof entry.id === 'string' && entry.id && !seen.has(entry.id) ? entry.id : null;
+ const id = given || `${prefix}-${randomUUID()}`;
+ seen.add(id);
+ out.push({ id, ...fields, ...normalizeRange(entry) });
+ }
+ return out;
+}
+
+const trimmed = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+
+/** Normalize an edited cue list: keep ids, trim text, drop empty lines. Order is kept (lyric order). */
+export const normalizeLyricCues = (cues) => normalizeList(cues, 'lc', (cue) => {
+ const text = trimmed(cue.text, MAX_CUE_TEXT);
+ return text ? { text } : null;
+});
+
+/** Normalize an edited phrase list: keep ids, trim label/intent. */
+export const normalizePhrases = (phrases) => normalizeList(phrases, 'mp', (phrase) => ({
+ label: trimmed(phrase.label, 120),
+ intent: trimmed(phrase.intent, 2000),
+}));
+
+/** Clear the audio-derived timings on every cue/phrase, keeping the authored text. */
+export function invalidateTimedText(project) {
+ const clear = (list) => (Array.isArray(list) ? list.map((e) => ({ ...e, startSec: null, endSec: null })) : list);
+ return {
+ ...(Array.isArray(project.lyricCues) ? { lyricCues: clear(project.lyricCues) } : {}),
+ ...(Array.isArray(project.phrases) ? { phrases: clear(project.phrases) } : {}),
+ };
+}
+
+// `[mm:ss]`, `[mm:ss.xx]`, `[mm:ss:xx]` and `[h:mm:ss.xxx]` all appear in the wild.
+const LRC_STAMP = /\[(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?\]/g;
+const LRC_OFFSET = /^\s*\[offset:\s*([+-]?\d+)\s*\]\s*$/i;
+const SRT_TIMING = /(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})/;
+const VTT_SHORT_TIMING = /(\d{1,2}):(\d{2})[.](\d{1,3})\s*-->\s*(\d{1,2}):(\d{2})[.](\d{1,3})/;
+
+const fraction = (digits) => (digits ? Number(digits) / 10 ** digits.length : 0);
+
+function parseLrc(text) {
+ let offsetSec = 0;
+ const stamped = [];
+ for (const line of text.split(/\r?\n/)) {
+ const offset = line.match(LRC_OFFSET);
+ // LRC offset is milliseconds; a positive offset shows lyrics sooner.
+ if (offset) { offsetSec = -Number(offset[1]) / 1000; continue; }
+ // Metadata tags ([ar:…], [ti:…]) carry no mm:ss stamp, so they fall out here.
+ const stamps = [...line.matchAll(LRC_STAMP)];
+ if (stamps.length === 0) continue;
+ const lyric = line.replace(LRC_STAMP, '').replace(/<\d{1,3}:\d{1,2}(?:[.:]\d{1,3})?>/g, '').trim();
+ for (const m of stamps) {
+ stamped.push({ t: Number(m[1]) * 60 + Number(m[2]) + fraction(m[3]), text: lyric });
+ }
+ }
+ stamped.sort((a, b) => a.t - b.t);
+ // An empty-text stamp is a timed gap marker: it ends the previous line.
+ const cues = [];
+ for (let i = 0; i < stamped.length; i++) {
+ const { t, text: lyric } = stamped[i];
+ if (!lyric) continue;
+ const next = stamped[i + 1];
+ const startSec = Math.max(0, t + offsetSec);
+ cues.push({ text: lyric, startSec, endSec: next ? Math.max(0, next.t + offsetSec) : null });
+ }
+ return cues;
+}
+
+function parseSrt(text) {
+ const cues = [];
+ for (const block of text.replace(/\r\n?/g, '\n').split(/\n{2,}/)) {
+ const lines = block.split('\n').map((l) => l.trim()).filter(Boolean);
+ const timingIdx = lines.findIndex((l) => l.includes('-->'));
+ if (timingIdx < 0) continue;
+ const long = lines[timingIdx].match(SRT_TIMING);
+ const short = long ? null : lines[timingIdx].match(VTT_SHORT_TIMING);
+ let startSec;
+ let endSec;
+ if (long) {
+ startSec = Number(long[1]) * 3600 + Number(long[2]) * 60 + Number(long[3]) + fraction(long[4]);
+ endSec = Number(long[5]) * 3600 + Number(long[6]) * 60 + Number(long[7]) + fraction(long[8]);
+ } else if (short) {
+ startSec = Number(short[1]) * 60 + Number(short[2]) + fraction(short[3]);
+ endSec = Number(short[4]) * 60 + Number(short[5]) + fraction(short[6]);
+ } else {
+ continue;
+ }
+ // Strip inline markup (<i>, <v Speaker>, {\an8}) that subtitle files carry.
+ const lyric = lines.slice(timingIdx + 1).join(' ').replace(/<[^>]*>|\{[^}]*\}/g, '').trim();
+ if (lyric) cues.push({ text: lyric, startSec, endSec });
+ }
+ return cues;
+}
+
+function parsePlain(text) {
+ return text.split(/\r?\n/)
+ .map((line) => line.trim())
+ // Section headers like "[Chorus]" are structure, not sung text.
+ .filter((line) => line && !/^\[[^\]]*\]$/.test(line))
+ .map((line) => ({ text: line, startSec: null, endSec: null }));
+}
+
+export function detectLyricsFormat(text) {
+ if (/-->/.test(text)) return 'srt';
+ if (/^\s*\[\d{1,3}:\d{1,2}/m.test(text)) return 'lrc';
+ return 'text';
+}
+
+/**
+ * Parse pasted/imported lyric text into cue inputs (not yet id'd — run the
+ * result through `normalizeLyricCues`). Returns `{ format, cues }`.
+ */
+export function parseLyricCues(text, format = 'auto') {
+ const source = typeof text === 'string' ? text : '';
+ const resolved = format === 'auto' || !format ? detectLyricsFormat(source) : format;
+ const cues = resolved === 'lrc' ? parseLrc(source)
+ : resolved === 'srt' ? parseSrt(source)
+ : parsePlain(source);
+ return { format: resolved, cues };
+}
diff --git a/server/services/musicVideo/timedText.test.js b/server/services/musicVideo/timedText.test.js
new file mode 100644
index 0000000000..e7d5cdc543
--- /dev/null
+++ b/server/services/musicVideo/timedText.test.js
@@ -0,0 +1,62 @@
+import { describe, it, expect } from 'vitest';
+import { parseLyricCues } from './timedText.js';
+
+// The lyric importer is a parser with a real input matrix (LRC, SRT, WebVTT,
+// plain text) — each case pins a format rule the route test cannot see.
+describe('parseLyricCues', () => {
+ it('parses LRC: metadata skipped, repeated stamps expanded, gap markers end a line, offset applied', () => {
+ const lrc = [
+ '[ar:Example Artist]',
+ '[ti:Example Song]',
+ '[offset:+500]',
+ '[00:01.50]First line',
+ '[00:04.00][00:20.00]Chorus hook',
+ '[00:06.25]',
+ '[00:08.000]Word <00:08.50>timed <00:09.00>line',
+ ].join('\n');
+ const { format, cues } = parseLyricCues(lrc);
+ expect(format).toBe('lrc');
+ // +500ms offset shows lyrics half a second sooner.
+ expect(cues).toEqual([
+ { text: 'First line', startSec: 1, endSec: 3.5 },
+ { text: 'Chorus hook', startSec: 3.5, endSec: 5.75 },
+ { text: 'Word timed line', startSec: 7.5, endSec: 19.5 },
+ { text: 'Chorus hook', startSec: 19.5, endSec: null },
+ ]);
+ });
+
+ it('parses SRT blocks, joining multi-line text and stripping markup', () => {
+ const srt = '1\r\n00:00:01,000 --> 00:00:03,500\r\n<i>Hello</i>\r\nthere\r\n\r\n2\r\n00:01:02,250 --> 00:01:04,000\r\n{\\an8}Second\r\n';
+ expect(parseLyricCues(srt)).toEqual({
+ format: 'srt',
+ cues: [
+ { text: 'Hello there', startSec: 1, endSec: 3.5 },
+ { text: 'Second', startSec: 62.25, endSec: 64 },
+ ],
+ });
+ });
+
+ it('parses WebVTT short timings and speaker tags', () => {
+ const vtt = 'WEBVTT\n\n00:05.000 --> 00:07.500\n<v Singer>Line one\n\n00:08.000 --> 00:09.000\nLine two';
+ expect(parseLyricCues(vtt).cues).toEqual([
+ { text: 'Line one', startSec: 5, endSec: 7.5 },
+ { text: 'Line two', startSec: 8, endSec: 9 },
+ ]);
+ });
+
+ it('imports plain lyrics as untimed lines, dropping section headers and blanks', () => {
+ expect(parseLyricCues('[Verse 1]\nWalking home\n\n under neon \n[Chorus]\n')).toEqual({
+ format: 'text',
+ cues: [
+ { text: 'Walking home', startSec: null, endSec: null },
+ { text: 'under neon', startSec: null, endSec: null },
+ ],
+ });
+ });
+
+ it('honors an explicit format over detection', () => {
+ expect(parseLyricCues('[00:01.00]stamped', 'text').cues).toEqual([
+ { text: '[00:01.00]stamped', startSec: null, endSec: null },
+ ]);
+ });
+});