Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: lay timed typography over music-video renders (#8984)
[._.]/ Adam Eivy1bc232f1de7c
diff --git a/client/src/components/musicVideo/TypographyPanel.jsx b/client/src/components/musicVideo/TypographyPanel.jsxnew file mode 100644index 0000000000..716b185961--- /dev/null+++ b/client/src/components/musicVideo/TypographyPanel.jsx@@ -0,0 +1,110 @@+import { Copy, Plus, Trash2 } from 'lucide-react';++// Client-minted ids keep a freshly added row addressable across saves (see LyricsPanel).+const mintId = () => `mtc-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;+const toSec = (value) => (value === '' ? null : Number(value));+const inputCls = 'bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs';++// Mirrors the server's composition enums (server/lib/musicVideoValidation.js).+const TEMPLATES = [['fade', 'Fade'], ['rise', 'Rise'], ['typewriter', 'Typewriter'], ['pop', 'Pop']];+const PLACEMENTS = [['lower', 'Lower'], ['center', 'Center'], ['upper', 'Upper']];+const EMPHASES = [['subtitle', 'Subtitle'], ['hero', 'Hero']];+const FONTS = [['sans', 'Sans'], ['serif', 'Serif'], ['mono', 'Mono']];++const EMPTY = { version: 1, mode: 'concat', textCues: [], style: { color: '#ffffff', font: 'sans' }, posterSec: null };++/**+ * Composition manifest editor (#8984): switch the final render between plain+ * cuts and a composed render that lays these timed text cues over the footage+ * (the song stays the only audio). Cues are the director's own lines — "Copy+ * timed lyrics" seeds them from the lyric cues, after which they are edited+ * independently. Edits apply locally at once and persist on blur, replacing+ * the whole manifest (like the lyric lists).+ */+export default function TypographyPanel({ project, onEditLocal, onSave }) {+ const composition = { ...EMPTY, ...(project.composition || {}), style: { ...EMPTY.style, ...(project.composition?.style || {}) } };+ const cues = composition.textCues || [];+ const composed = composition.mode === 'composed';+ const timedLyrics = (project.lyricCues || []).filter((c) => typeof c.startSec === 'number' && typeof c.endSec === 'number');++ const edit = (patch) => onEditLocal({ composition: { ...composition, ...patch } });+ const save = (patch = {}) => onSave({ composition: { ...composition, ...patch } });+ const replace = (patch) => { edit(patch); save(patch); };+ const editCue = (id, patch) => edit({ textCues: cues.map((c) => (c.id === id ? { ...c, ...patch } : c)) });+ const replaceCue = (id, patch) => replace({ textCues: cues.map((c) => (c.id === id ? { ...c, ...patch } : c)) });+ const lastEnd = cues.reduce((max, c) => Math.max(max, c.endSec ?? 0), 0);++ const copyLyrics = () => replace({+ textCues: timedLyrics.map((c) => ({ id: mintId(), text: c.text, startSec: c.startSec, endSec: c.endSec, template: 'fade', placement: 'lower', emphasis: 'subtitle' })),+ });++ 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">+ Typography — {composed ? 'composed render' : 'plain cuts'} · {cues.length} text cue{cues.length === 1 ? '' : 's'}+ <span className="block sm:inline sm:ml-1">— timed text laid over the footage, kept inside the title-safe area.</span>+ </summary>++ <div className="mt-2 flex flex-wrap items-end gap-2">+ <div>+ <label htmlFor="mv-typo-mode" className="block text-port-text-muted mb-0.5">Final render</label>+ <select id="mv-typo-mode" value={composition.mode} onChange={(e) => replace({ mode: e.target.value })} className={inputCls}>+ <option value="concat">Plain cuts</option>+ <option value="composed">Composed with typography</option>+ </select>+ </div>+ <div>+ <label htmlFor="mv-typo-font" className="block text-port-text-muted mb-0.5">Font</label>+ <select id="mv-typo-font" value={composition.style.font} onChange={(e) => replace({ style: { ...composition.style, font: e.target.value } })} className={inputCls}>+ {FONTS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="mv-typo-color" className="block text-port-text-muted mb-0.5">Text color</label>+ <input id="mv-typo-color" type="color" value={composition.style.color}+ onChange={(e) => edit({ style: { ...composition.style, color: e.target.value } })}+ onBlur={() => save()} className="h-8 w-12 bg-port-bg border border-port-border rounded" />+ </div>+ <div>+ <label htmlFor="mv-typo-poster" className="block text-port-text-muted mb-0.5" title="Frame used as the rendered video's poster. Empty picks the loudest section.">Poster frame (s)</label>+ <input id="mv-typo-poster" type="number" min={0} step={0.1} placeholder="auto"+ value={composition.posterSec ?? ''} onChange={(e) => edit({ posterSec: toSec(e.target.value) })}+ onBlur={() => save()} className={`${inputCls} w-20`} />+ </div>+ <button type="button" onClick={copyLyrics} disabled={timedLyrics.length === 0}+ title={timedLyrics.length === 0 ? 'Time some lyric lines first' : 'Replace the text cues with the timed lyric lines'}+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0 disabled:opacity-50">+ <Copy size={13} /> Copy timed lyrics ({timedLyrics.length})+ </button>+ <button type="button"+ onClick={() => replace({ textCues: [...cues, { id: mintId(), text: 'New text', startSec: lastEnd, endSec: lastEnd + 2, template: 'fade', placement: 'lower', emphasis: 'subtitle' }] })}+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0"><Plus size={13} /> Text cue</button>+ </div>++ {composed && cues.length === 0 && <p className="mt-2 text-port-text-muted">No text cues yet — a composed render with none renders as plain cuts.</p>}+ <div className="mt-2 max-h-72 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={`Text cue ${i + 1} start (s)`} placeholder="start"+ value={cue.startSec ?? ''} onChange={(e) => editCue(cue.id, { startSec: toSec(e.target.value) })}+ onBlur={() => save()} className={`${inputCls} w-16`} />+ <input type="number" min={0} step={0.01} aria-label={`Text cue ${i + 1} end (s)`} placeholder="end"+ value={cue.endSec ?? ''} onChange={(e) => editCue(cue.id, { endSec: toSec(e.target.value) })}+ onBlur={() => save()} className={`${inputCls} w-16`} />+ <input type="text" maxLength={500} aria-label={`Text cue ${i + 1} text`}+ value={cue.text} onChange={(e) => editCue(cue.id, { text: e.target.value })}+ onBlur={() => save()} className={`${inputCls} min-w-0 flex-1 basis-40`} />+ {[['template', TEMPLATES, 'motion'], ['placement', PLACEMENTS, 'placement'], ['emphasis', EMPHASES, 'size']].map(([field, options, name]) => (+ <select key={field} aria-label={`Text cue ${i + 1} ${name}`} value={cue[field] || options[0][0]}+ onChange={(e) => replaceCue(cue.id, { [field]: e.target.value })} className={inputCls}>+ {options.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ ))}+ <button type="button" onClick={() => replace({ textCues: cues.filter((c) => c.id !== cue.id) })}+ aria-label={`Delete text cue ${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>+ </details>+ );+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex acb15f0179..6939d26ecc 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -41,6 +41,7 @@ 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 TypographyPanel from '../components/musicVideo/TypographyPanel.jsx';import VisualSpecPanel from '../components/musicVideo/VisualSpecPanel.jsx';import HandoffControls from '../components/musicVideo/HandoffControls.jsx';import ContactSheetDrawer from '../components/musicVideo/ContactSheetDrawer.jsx';@@ -346,8 +347,8 @@ 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. Each PATCH replaces a whole list, so the+ // Lyric cues / phrases / pacing (#8964) and the typography manifest (#8984)+ // — optimistic-local + silent PATCH on blur, like the scene editors. Each PATCH replaces a whole list, so the// saves are chained: two quick blurs can never land out of order and let an// older snapshot of the list overwrite a newer one.const timedTextSaveChain = useRef(Promise.resolve());@@ -356,7 +357,7 @@ export default function MusicVideo() {const projectId = selected.id;timedTextSaveChain.current = timedTextSaveChain.current.then(() => updateMusicVideoProject(projectId, patch, { silent: true }))- .catch((err) => toast.error(err?.message || 'Failed to save lyrics'));+ .catch((err) => toast.error(err?.message || 'Failed to save changes'));};const handleImportLyrics = (body, onDone) => {const projectId = selected.id;@@ -681,6 +682,11 @@ export default function MusicVideo() {onImport={handleImportLyrics}importing={importingLyrics}/>+ <TypographyPanel+ project={selected}+ onEditLocal={editProjectLocal}+ onSave={saveProjectFields}+ /><AnalysisPanelaudioAnalysis={selected.audioAnalysis}scenes={selected.scenes || []}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 51a5549668..41a8186930 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -753,6 +753,36 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {});});+describe('MusicVideo typography composition (#8984)', () => {+ it('seeds text cues from the timed lyrics, switches to a composed render, and saves an edited cue whole', async () => {+ const lyricCues = [+ { id: 'lc-1', text: 'first line', startSec: 1, endSec: 3 },+ { id: 'lc-2', text: 'untimed line', startSec: null, endSec: null },+ ];+ updateMusicVideoProject.mockResolvedValue({});+ await openProject({ ...PROJECT_ANALYZED, lyricCues });++ fireEvent.click(screen.getByRole('button', { name: /Copy timed lyrics \(1\)/ }));+ const text = await screen.findByLabelText('Text cue 1 text');+ expect(text).toHaveValue('first line');+ expect(screen.queryByLabelText('Text cue 2 text')).toBeNull();+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenLastCalledWith('mv-3', {+ composition: expect.objectContaining({ mode: 'concat', textCues: [expect.objectContaining({ text: 'first line', startSec: 1, endSec: 3, template: 'fade' })] }),+ }, { silent: true }));++ fireEvent.change(screen.getByLabelText('Final render'), { target: { value: 'composed' } });+ fireEvent.change(screen.getByLabelText('Text cue 1 motion'), { target: { value: 'typewriter' } });+ fireEvent.change(text, { target: { value: 'first line, typed' } });+ fireEvent.blur(text);+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenLastCalledWith('mv-3', {+ composition: expect.objectContaining({+ mode: 'composed',+ textCues: [expect.objectContaining({ text: 'first line, typed', template: 'typewriter' })],+ }),+ }, { silent: true }));+ });+});+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/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 0380fee326..0f9aeb0c6a 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -175,6 +175,40 @@ export const musicVideoLyricsImportSchema = z.object({mode: z.enum(['replace', 'append']).optional(),}).strict();+// ---- Composition manifest (#8984, part of #8966) ---------------------------++// A composed render lays timed text cues over the cut footage; `concat` (and a+// project with no manifest) is the plain clip concatenation. Cue text is the+// director's own, rendered as an independent typography layer — never baked+// into generated pixels. See services/musicVideo/composition.js.+export const MUSIC_VIDEO_COMPOSITION_MODES = ['concat', 'composed'];+export const MUSIC_VIDEO_TYPOGRAPHY_TEMPLATES = ['fade', 'rise', 'typewriter', 'pop'];+export const MUSIC_VIDEO_TYPOGRAPHY_PLACEMENTS = ['upper', 'center', 'lower'];+export const MUSIC_VIDEO_TYPOGRAPHY_EMPHASES = ['subtitle', 'hero'];+export const MUSIC_VIDEO_TYPOGRAPHY_FONTS = ['sans', 'serif', 'mono'];++export const musicVideoTextCueSchema = z.object({+ id: z.string().min(1).max(64).optional(),+ text: z.string().max(500),+ startSec: timedSec,+ endSec: timedSec,+ template: z.enum(MUSIC_VIDEO_TYPOGRAPHY_TEMPLATES).optional(),+ placement: z.enum(MUSIC_VIDEO_TYPOGRAPHY_PLACEMENTS).optional(),+ emphasis: z.enum(MUSIC_VIDEO_TYPOGRAPHY_EMPHASES).optional(),+}).strict();++// Replaced whole by a project PATCH (the editor sends the full manifest).+export const musicVideoCompositionSchema = z.object({+ version: z.literal(1).optional(),+ mode: z.enum(MUSIC_VIDEO_COMPOSITION_MODES).optional(),+ textCues: z.array(musicVideoTextCueSchema).max(1000).optional(),+ style: z.object({+ color: z.string().regex(/^#[0-9a-f]{6}$/i, 'color is #rrggbb').optional(),+ font: z.enum(MUSIC_VIDEO_TYPOGRAPHY_FONTS).optional(),+ }).strict().optional(),+ posterSec: timedSec,+}).strict();+export const musicVideoProjectCreateSchema = z.object({name: z.string().min(1).max(200),mode: z.enum(MUSIC_VIDEO_MODES).optional(),@@ -201,6 +235,7 @@ export const musicVideoProjectUpdateSchema = z.object({lyricCues: lyricCueList.optional(),phrases: phraseList.optional(),pacing: musicVideoPacingSchema.nullable().optional(),+ composition: musicVideoCompositionSchema.nullable().optional(),}).strict();// Fork a project into its next editable version. The server derives lineage anddiff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 95ed181677..1442dbcfbb 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -196,6 +196,17 @@ describe('musicVideo routes', () => {expect(svc.updateProject).not.toHaveBeenCalled();});+ it('PATCH /:id accepts a composition manifest and refuses an unknown motion template (#8984)', async () => {+ const bad = await request(app).patch('/api/music-video/mv-1')+ .send({ composition: { mode: 'composed', textCues: [{ text: 'hi', startSec: 1, endSec: 2, template: 'explode' }] } });+ expect(bad.status).toBe(400);+ expect(svc.updateProject).not.toHaveBeenCalled();+ const composition = { mode: 'composed', textCues: [{ text: 'hi', startSec: 1, endSec: 2, template: 'pop', placement: 'upper' }], posterSec: 1.5 };+ const ok = await request(app).patch('/api/music-video/mv-1').send({ composition });+ expect(ok.status).toBe(200);+ expect(svc.updateProject).toHaveBeenCalledWith('mv-1', { composition });+ });+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 }] });diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.jsnew file mode 100644index 0000000000..1f458078c9--- /dev/null+++ b/server/services/musicVideo/composition.js@@ -0,0 +1,242 @@+/**+ * Music Video — composition manifest + deterministic typography (#8984, part of #8966).+ *+ * A project may carry a versioned `composition` manifest that switches its+ * final render from plain clip concatenation (`mode: 'concat'`, the default and+ * the behavior of every project that has no manifest) to a **composed** render:+ * the same footage cut over the same master song, with editable timed text cues+ * laid over it. The cues are explicit, user-owned text — independent of the+ * lyric cues the shot planner reads, though the UI can copy them across.+ *+ * Everything here is storage- and browser-agnostic. `cueStateAt` is the single+ * source of truth for how a cue looks at a time; the overlay document embeds its+ * source verbatim, so seeking the page to a time and calling the function in+ * Node yield the same state. `buildTypographyDocument` produces the sandboxed+ * HTML composition (see services/htmlComposition/browser.js) that+ * compositionRender.js captures into transparent overlay clips.+ */++import { randomUUID } from 'crypto';+import { trimTo } from '../../lib/textUtils.js';+import {+ MUSIC_VIDEO_COMPOSITION_MODES as COMPOSITION_MODES,+ MUSIC_VIDEO_TYPOGRAPHY_EMPHASES as TYPOGRAPHY_EMPHASES,+ MUSIC_VIDEO_TYPOGRAPHY_FONTS as TYPOGRAPHY_FONTS,+ MUSIC_VIDEO_TYPOGRAPHY_PLACEMENTS as TYPOGRAPHY_PLACEMENTS,+ MUSIC_VIDEO_TYPOGRAPHY_TEMPLATES as TYPOGRAPHY_TEMPLATES,+} from '../../lib/musicVideoValidation.js';++export const COMPOSITION_VERSION = 1;++const MAX_SEC = 36000;+const round3 = (n) => Math.round(n * 1000) / 1000;+const toTime = (value) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_SEC ? round3(value) : null);+const pick = (value, allowed, fallback) => (allowed.includes(value) ? value : fallback);++/**+ * Normalize a validated (or legacy/peer-supplied) manifest. Every cue persists+ * a stable id and explicit defaults; a cue whose end is not after its start+ * keeps its text but loses its end (it does not render until re-timed). Returns+ * null for a non-object so a cleared manifest stays cleared.+ */+export function normalizeComposition(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const seen = new Set();+ const textCues = [];+ for (const cue of Array.isArray(input.textCues) ? input.textCues : []) {+ const text = cue && typeof cue === 'object' ? trimTo(cue.text, 500) : '';+ if (!text) continue;+ const id = typeof cue.id === 'string' && cue.id && !seen.has(cue.id) ? cue.id : `mtc-${randomUUID()}`;+ seen.add(id);+ const startSec = toTime(cue.startSec);+ const end = toTime(cue.endSec);+ textCues.push({+ id,+ text,+ startSec,+ endSec: startSec != null && end != null && end > startSec ? end : null,+ template: pick(cue.template, TYPOGRAPHY_TEMPLATES, 'fade'),+ placement: pick(cue.placement, TYPOGRAPHY_PLACEMENTS, 'lower'),+ emphasis: pick(cue.emphasis, TYPOGRAPHY_EMPHASES, 'subtitle'),+ });+ }+ const style = input.style && typeof input.style === 'object' ? input.style : {};+ return {+ version: COMPOSITION_VERSION,+ mode: pick(input.mode, COMPOSITION_MODES, 'concat'),+ textCues,+ style: {+ color: typeof style.color === 'string' && /^#[0-9a-f]{6}$/i.test(style.color) ? style.color.toLowerCase() : '#ffffff',+ font: pick(style.font, TYPOGRAPHY_FONTS, 'sans'),+ },+ posterSec: toTime(input.posterSec),+ };+}++/** Clear the audio-derived timings (cue times, poster) when the song changes, keeping the text. */+export function invalidateCompositionTiming(composition) {+ if (!composition || typeof composition !== 'object') return composition;+ return {+ ...composition,+ textCues: (composition.textCues || []).map((cue) => ({ ...cue, startSec: null, endSec: null })),+ posterSec: null,+ };+}++/** The cues a composed render draws: timed, non-empty, clipped to the video. */+export function renderableCues(composition, durationSec) {+ if (composition?.mode !== 'composed') return [];+ return (composition.textCues || [])+ .filter((cue) => cue.text && cue.startSec != null && cue.endSec != null && cue.startSec < durationSec)+ .map((cue) => ({ ...cue, endSec: Math.min(cue.endSec, durationSec) }))+ .filter((cue) => cue.endSec > cue.startSec)+ .sort((a, b) => a.startSec - b.startSec);+}++/**+ * Pure and self-contained (its source is embedded in the overlay page, so it+ * must not reference anything outside its own body): the visual state of `cue`+ * at time `t`, or null when the cue is not on screen. `offsetY` is a fraction+ * of the frame height; `visibleChars` is how much of the text the typewriter+ * template has revealed.+ */+export function cueStateAt(cue, t) {+ const start = cue.startSec;+ const end = cue.endSec;+ if (!(t >= start && t < end)) return null;+ const span = end - start;+ const ramp = Math.min(0.35, span / 4);+ const clamp = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);+ const inP = ramp > 0 ? clamp((t - start) / ramp) : 1;+ const outP = ramp > 0 ? clamp((end - t) / ramp) : 1;+ const easeOut = (p) => 1 - (1 - p) * (1 - p) * (1 - p);+ const length = String(cue.text).length;+ let opacity = Math.min(easeOut(inP), easeOut(outP));+ let offsetY = 0;+ let scale = 1;+ let visibleChars = length;+ if (cue.template === 'rise') {+ // Starts this far below its resting place (the overlay page's RISE reserve).+ offsetY = 0.04 * (1 - easeOut(inP));+ } else if (cue.template === 'pop') {+ // Grows into place and never past full size, so it cannot leave the safe area.+ scale = 0.85 + 0.15 * easeOut(inP);+ } else if (cue.template === 'typewriter') {+ const typeSec = Math.min(span * 0.6, length * 0.05);+ visibleChars = typeSec > 0 ? Math.min(length, Math.ceil(length * clamp((t - start) / typeSec))) : length;+ opacity = easeOut(outP);+ }+ return { opacity: Math.round(opacity * 10000) / 10000, offsetY: Math.round(offsetY * 10000) / 10000, scale: Math.round(scale * 10000) / 10000, visibleChars };+}++/**+ * The contiguous time ranges that need an overlay clip: the union of cue spans,+ * with near-adjacent spans joined so a lyric run renders as one clip. Frames+ * outside every window are never captured (the footage passes through as-is).+ */+export function overlayWindows(cues, { joinGapSec = 1 } = {}) {+ const windows = [];+ for (const cue of [...cues].sort((a, b) => a.startSec - b.startSec)) {+ const last = windows[windows.length - 1];+ if (last && cue.startSec - last.endSec <= joinGapSec) last.endSec = Math.max(last.endSec, cue.endSec);+ else windows.push({ startSec: cue.startSec, endSec: cue.endSec });+ }+ return windows;+}++// Title-safe area: 10% in from every edge of the frame, at any aspect.+export const SAFE_INSET = 0.1;+const FONT_STACKS = {+ sans: "'Helvetica Neue', Helvetica, Arial, sans-serif",+ serif: "Georgia, 'Times New Roman', serif",+ mono: "Menlo, 'Courier New', monospace",+};++// A `<script>`-safe JSON literal: `<` escaped so text can never close the tag. (U+2028/9+// are legal inside JS string literals since ES2019, so they need no escape.)+const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');++/**+ * The overlay page: a transparent document whose `portosComposition.seek(t)`+ * draws every cue's `cueStateAt` state. `layout()` sizes each cue once per frame+ * size — shrinking its font until it fits inside the safe area — so the text+ * box never changes between frames and cannot leave the safe area.+ */+export function buildTypographyDocument({ cues, style = {}, width, height, durationSec, fps }) {+ const payload = cues.map(({ id, text, startSec, endSec, template, placement, emphasis }) => ({ id, text, startSec, endSec, template, placement, emphasis }));+ const color = /^#[0-9a-f]{6}$/i.test(style.color || '') ? style.color : '#ffffff';+ const fontStack = FONT_STACKS[style.font] || FONT_STACKS.sans;+ return `<!doctype html><html><head><meta charset="utf-8"><style>+html, body { margin: 0; padding: 0; background: transparent; overflow: hidden; }+#safe { position: absolute; }+.cue { position: absolute; left: 0; right: 0; box-sizing: border-box; padding: 0.25em; text-align: center; color: ${color}; font-family: ${fontStack};+ font-weight: 700; line-height: 1.15; overflow-wrap: break-word; visibility: hidden; will-change: transform, opacity;+ /* The padding keeps this legibility shadow inside the cue box, and so inside the safe area. */+ text-shadow: 0 0 0.12em rgba(0,0,0,0.85), 0 0.04em 0.18em rgba(0,0,0,0.7); }+.cue .rest { visibility: hidden; }+</style></head><body><div id="safe"></div><script>+const CUES = ${scriptJson(payload)};+const SAFE_INSET = ${SAFE_INSET};+const cueStateAt = ${cueStateAt.toString()};+const safe = document.getElementById('safe');+const nodes = CUES.map((cue) => {+ const el = document.createElement('div');+ el.className = 'cue';+ const shown = document.createElement('span');+ const rest = document.createElement('span');+ rest.className = 'rest';+ el.append(shown, rest);+ safe.append(el);+ return { cue, el, shown, rest, chars: Array.from(cue.text) };+});+let frame = { width: ${Number(width)}, height: ${Number(height)} };+function layout({ width, height }) {+ frame = { width, height };+ const insetX = Math.round(width * SAFE_INSET);+ const insetY = Math.round(height * SAFE_INSET);+ const safeW = width - insetX * 2;+ const safeH = height - insetY * 2;+ Object.assign(safe.style, { left: insetX + 'px', top: insetY + 'px', width: safeW + 'px', height: safeH + 'px' });+ const base = Math.min(width, height);+ for (const node of nodes) {+ const hero = node.cue.emphasis === 'hero';+ const maxH = safeH * (hero ? 0.6 : 0.3);+ node.shown.textContent = node.cue.text;+ node.rest.textContent = '';+ let size = Math.round(base * (hero ? 0.09 : 0.05));+ const floor = Math.max(8, Math.round(base * 0.02));+ node.el.style.fontSize = size + 'px';+ while (size > floor && (node.el.scrollHeight > maxH || node.el.scrollWidth > safeW)) {+ size = Math.max(floor, Math.floor(size * 0.92));+ node.el.style.fontSize = size + 'px';+ }+ const boxH = Math.min(node.el.scrollHeight, safeH);+ // A lower cue that rises in starts below its resting place: rest it high+ // enough that its first frame is still inside the safe area.+ const reserve = node.cue.template === 'rise' ? Math.ceil(0.04 * height) : 0;+ const top = node.cue.placement === 'upper' ? 0 : node.cue.placement === 'center' ? (safeH - boxH) / 2 : safeH - boxH - reserve;+ node.el.style.top = Math.round(top) + 'px';+ node.el.style.maxHeight = safeH + 'px';+ }+}+function draw(t) {+ for (const node of nodes) {+ const state = cueStateAt(node.cue, t);+ if (!state) { node.el.style.visibility = 'hidden'; continue; }+ node.shown.textContent = node.chars.slice(0, state.visibleChars).join('');+ node.rest.textContent = node.chars.slice(state.visibleChars).join('');+ node.el.style.visibility = 'visible';+ node.el.style.opacity = String(state.opacity);+ node.el.style.transformOrigin = '50% 50%';+ node.el.style.transform = 'translateY(' + Math.round(state.offsetY * frame.height) + 'px) scale(' + state.scale + ')';+ }+}+layout(frame);+globalThis.portosComposition = {+ durationSec: ${Number(durationSec)}, fps: ${Number(fps)}, width: ${Number(width)}, height: ${Number(height)},+ layout,+ state: (t) => nodes.map((node) => ({ id: node.cue.id, state: cueStateAt(node.cue, t) })),+ async seek(t) { draw(t); await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); },+};+</script></body></html>`;+}diff --git a/server/services/musicVideo/composition.test.js b/server/services/musicVideo/composition.test.jsnew file mode 100644index 0000000000..f373451f83--- /dev/null+++ b/server/services/musicVideo/composition.test.js@@ -0,0 +1,92 @@+import { describe, expect, it } from 'vitest';+import { buildTypographyDocument, cueStateAt, normalizeComposition, overlayWindows, renderableCues } from './composition.js';++const cue = (over = {}) => ({ id: 'c', text: 'Hello world', startSec: 10, endSec: 12, template: 'fade', placement: 'lower', emphasis: 'subtitle', ...over });++describe('normalizeComposition (#8984)', () => {+ it('fills defaults for a legacy/peer manifest and drops malformed cues without losing text', () => {+ const out = normalizeComposition({+ mode: 'bogus',+ textCues: [+ { text: ' Line one ', startSec: 1, endSec: 0.5, template: 'spin' },+ { id: 'dup', text: 'Two', startSec: 2, endSec: 3 },+ { id: 'dup', text: 'Three', startSec: -1, endSec: 4 },+ { text: ' ' },+ null,+ ],+ style: { color: '#ABCDEF', font: 'comic' },+ posterSec: 'soon',+ });+ expect(out).toMatchObject({ version: 1, mode: 'concat', style: { color: '#abcdef', font: 'sans' }, posterSec: null });+ expect(out.textCues.map(({ text, startSec, endSec, template }) => ({ text, startSec, endSec, template }))).toEqual([+ { text: 'Line one', startSec: 1, endSec: null, template: 'fade' },+ { text: 'Two', startSec: 2, endSec: 3, template: 'fade' },+ { text: 'Three', startSec: null, endSec: null, template: 'fade' },+ ]);+ // A duplicated id is re-minted so every cue stays addressable.+ expect(out.textCues[1].id).toBe('dup');+ expect(out.textCues[2].id).not.toBe('dup');+ expect(normalizeComposition(null)).toBeNull();+ });++ it('draws only timed cues, and only in composed mode, clipped to the video', () => {+ const composition = normalizeComposition({ mode: 'composed', textCues: [+ cue({ id: 'late', startSec: 40, endSec: 50 }),+ cue({ id: 'tail', startSec: 25, endSec: 35 }),+ cue({ id: 'untimed', startSec: null, endSec: null }),+ cue({ id: 'early', startSec: 1, endSec: 2 }),+ ] });+ expect(renderableCues(composition, 30).map(({ id, endSec }) => [id, endSec])).toEqual([['early', 2], ['tail', 30]]);+ expect(renderableCues({ ...composition, mode: 'concat' }, 30)).toEqual([]);+ });+});++describe('cueStateAt (#8984)', () => {+ it('is invisible outside its span and fully shown mid-span for every template', () => {+ for (const template of ['fade', 'rise', 'typewriter', 'pop']) {+ const c = cue({ template });+ expect(cueStateAt(c, 9.99)).toBeNull();+ expect(cueStateAt(c, 12)).toBeNull();+ expect(cueStateAt(c, 11)).toEqual({ opacity: 1, offsetY: 0, scale: 1, visibleChars: c.text.length });+ }+ });++ it('animates each template in on its own terms', () => {+ expect(cueStateAt(cue(), 10).opacity).toBe(0);+ expect(cueStateAt(cue({ template: 'rise' }), 10)).toMatchObject({ offsetY: 0.04, opacity: 0 });+ expect(cueStateAt(cue({ template: 'pop' }), 10).scale).toBe(0.85);+ const typed = cue({ template: 'typewriter' });+ // 11 characters typed over 0.55s: 0.2s in reveals ceil(11 × 0.2 / 0.55) = 4.+ expect(cueStateAt(typed, 10.2)).toMatchObject({ opacity: 1, visibleChars: 4 });+ });++ it('never scales past full size or rises above its rest, so motion stays inside the safe area', () => {+ for (let t = 10; t < 12; t += 0.01) {+ const pop = cueStateAt(cue({ template: 'pop' }), t);+ const rise = cueStateAt(cue({ template: 'rise' }), t);+ expect(pop.scale).toBeLessThanOrEqual(1);+ expect(rise.offsetY).toBeGreaterThanOrEqual(0);+ expect(rise.offsetY).toBeLessThanOrEqual(0.04);+ }+ });+});++describe('overlayWindows (#8984)', () => {+ it('joins near-adjacent cues into one capture window and keeps distant ones apart', () => {+ expect(overlayWindows([+ { startSec: 20, endSec: 22 },+ { startSec: 1, endSec: 3 },+ { startSec: 3.5, endSec: 4 },+ { startSec: 2, endSec: 2.5 },+ ])).toEqual([{ startSec: 1, endSec: 4 }, { startSec: 20, endSec: 22 }]);+ });+});++describe('buildTypographyDocument (#8984)', () => {+ it('embeds cue text as inert data that cannot close the script element', () => {+ const html = buildTypographyDocument({ cues: [cue({ text: '</script><img src=x onerror=alert(1)>' })], width: 1920, height: 1080, durationSec: 30, fps: 24 });+ expect(html.match(/<\/script>/g)).toHaveLength(1);+ expect(html).toContain('\\u003c/script>');+ expect(html).not.toContain('innerHTML');+ });+});diff --git a/server/services/musicVideo/compositionRender.js b/server/services/musicVideo/compositionRender.jsnew file mode 100644index 0000000000..3761d843bb--- /dev/null+++ b/server/services/musicVideo/compositionRender.js@@ -0,0 +1,119 @@+/**+ * Music Video — typography overlay capture (#8984, part of #8966).+ *+ * Renders a composed project's timed text cues into transparent overlay clips+ * that render.js lays over the concatenated footage. The page is the sandboxed+ * HTML composition from composition.js, opened through the shared composition+ * browser boundary (htmlComposition/browser.js: frozen assets, no network, CSP+ * sandbox). Only the time ranges that carry text are captured — one clip per+ * `overlayWindows` range, each encoded with an alpha channel (QuickTime RLE) —+ * so a mostly-instrumental song costs a handful of frames, not the whole song.+ *+ * All output lives in one per-job scratch directory under data/ (the+ * composition browser only opens directories inside data); the caller removes+ * it once the final render finishes, and boot recovery sweeps any a crash left.+ */++import { join } from 'path';+import { mkdir, rm, writeFile } from 'fs/promises';+import { spawn } from '../../lib/childProcess.js';+import { PATHS } from '../../lib/fileUtils.js';+import { findFfmpeg } from '../../lib/ffmpeg.js';+import { safeChildProcessOptions } from '../../lib/processEnv.js';+import { killWithEscalation } from '../../lib/killWithEscalation.js';+import { buildTypographyDocument, overlayWindows } from './composition.js';++export const COMPOSITION_SCRATCH_DIR = 'music-video-compositions';++const scratchPath = (jobId) => join(PATHS.data, COMPOSITION_SCRATCH_DIR, jobId);++/** Remove one job's scratch directory (best-effort). */+export const removeCompositionScratch = async (jobId) => rm(scratchPath(jobId), { recursive: true, force: true });++/** Boot sweep: no render survives a restart, so every scratch directory is stale. */+export const sweepCompositionScratch = async () => rm(join(PATHS.data, COMPOSITION_SCRATCH_DIR), { recursive: true, force: true });++// Capture frames [0, frames) of one window, seeking the page to the window's+// absolute song time for each, into an alpha-preserving QuickTime RLE clip.+async function captureWindow(page, ffmpeg, { startSec, frames, fps, outputPath, signal, onFrame }) {+ const proc = spawn(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps),+ '-vcodec', 'png', '-i', 'pipe:0', '-c:v', 'qtrle', '-pix_fmt', 'argb', '-frames:v', String(frames), '-y', outputPath],+ safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));+ let stderr = '';+ let exited = false;+ proc.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-2000); });+ const finished = new Promise((resolve, reject) => {+ proc.on('error', reject);+ proc.stdin.on('error', reject);+ proc.once('close', (code) => { exited = true; code === 0 ? resolve() : reject(new Error(`overlay encode failed (${code}): ${stderr}`)); });+ });+ finished.catch(() => {});+ try {+ for (let n = 0; n < frames; n++) {+ page.check();+ await page.evaluate(`globalThis.portosComposition.seek(${startSec + n / fps})`);+ page.check();+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });+ signal?.throwIfAborted();+ await Promise.race([+ new Promise((resolve, reject) => proc.stdin.write(Buffer.from(data, 'base64'), (error) => (error ? reject(error) : resolve()))),+ finished.then(() => { throw new Error('ffmpeg exited before the overlay was complete'); }),+ ]);+ onFrame?.();+ }+ proc.stdin.end();+ await finished;+ } finally {+ if (!exited) {+ killWithEscalation(proc, { label: 'music-video overlay', stillRunning: () => !exited, delayMs: 1000 });+ await new Promise((resolve) => proc.once('close', resolve));+ }+ }+}++/**+ * Render the overlay clips for `cues` (already filtered by renderableCues) on a+ * `width`×`height`, `fps` frame. Resolves `[{ path, startSec, durationSec }]` in+ * time order. `onProgress(0..1)` reports captured frames; `signal` cancels.+ */+export async function renderTypographyOverlays({ jobId, cues, style, width, height, fps, durationSec, signal, onProgress }) {+ // Snap each window outward to the output frame grid so every overlay frame+ // lands exactly on a footage frame, and never past the video's last frame.+ const lastFrame = Math.round(durationSec * fps);+ const windows = overlayWindows(cues)+ .map((w) => {+ const first = Math.floor(w.startSec * fps + 1e-6);+ return { startSec: first / fps, frames: Math.min(lastFrame, Math.ceil(w.endSec * fps - 1e-6)) - first };+ })+ .filter((w) => w.frames > 0);+ if (windows.length === 0) return [];+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new Error('ffmpeg not found on PATH');+ const root = scratchPath(jobId);+ await mkdir(join(root, 'doc'), { recursive: true });+ await writeFile(join(root, 'doc', 'index.html'), buildTypographyDocument({ cues, style, width, height, durationSec, fps }));+ signal?.throwIfAborted();+ // Lazy: the composition browser drags in browserService, which only a+ // composed render needs — not every suite that reaches render.js.+ const { openComposition } = await import('../htmlComposition/browser.js');+ const page = await openComposition(`${COMPOSITION_SCRATCH_DIR}/${jobId}/doc`, { signal });+ try {+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ // A transparent default background is what gives the PNG captures alpha.+ await page.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });+ await page.evaluate(`globalThis.portosComposition.layout({ width: ${width}, height: ${height} })`);+ const total = windows.reduce((sum, w) => sum + w.frames, 0);+ let done = 0;+ const overlays = [];+ for (const [index, w] of windows.entries()) {+ const outputPath = join(root, `overlay-${index}.mov`);+ await captureWindow(page, ffmpeg, { startSec: w.startSec, frames: w.frames, fps, outputPath, signal,+ onFrame: () => { done += 1; onProgress?.(done / total); } });+ overlays.push({ path: outputPath, startSec: w.startSec, durationSec: w.frames / fps });+ }+ await page.close({ verify: true });+ return overlays;+ } finally {+ await page.close();+ }+}diff --git a/server/services/musicVideo/compositionRender.test.js b/server/services/musicVideo/compositionRender.test.jsnew file mode 100644index 0000000000..933c2eeb1b--- /dev/null+++ b/server/services/musicVideo/compositionRender.test.js@@ -0,0 +1,150 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { existsSync } from 'node:fs';+import { mkdir, readdir } from 'node:fs/promises';+import { join } from 'node:path';+import { execFileSync, spawn } from 'node:child_process';+import { chromium } from 'playwright-core';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';+import { findFfmpeg, probeVideoDuration } from '../../lib/ffmpeg.js';+import { PATHS } from '../../lib/fileUtils.js';+import { _cleanupTestBrowser } from '../htmlComposition/testBrowserCleanup.js';+import { buildMusicVideoFfmpegArgs } from './render.js';+import { COMPOSITION_SCRATCH_DIR, removeCompositionScratch, renderTypographyOverlays } from './compositionRender.js';++let endpoint;+vi.mock('../browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));+vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-composition-'),+}));++const chrome = [process.env.CHROME_PATH, chromium.executablePath(),+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+].find(path => path && existsSync(path));+const ffmpeg = await findFfmpeg();+let proc;+let browser;++const FPS = 24;+const run = (args) => execFileSync(ffmpeg, ['-v', 'error', ...args], { maxBuffer: 64 * 1024 * 1024 });+// Decode a video to raw frames of `pix_fmt`.+const frames = (path, pixFmt) => run(['-i', path, '-f', 'rawvideo', '-pix_fmt', pixFmt, '-']);++// Every overlay pixel with visible alpha lies inside the 10% title-safe area.+function assertInsideSafeArea(path, width, height) {+ const raw = frames(path, 'rgba');+ const frameBytes = width * height * 4;+ const x0 = width * 0.1; const x1 = width * 0.9; const y0 = height * 0.1; const y1 = height * 0.9;+ let drawn = 0;+ for (let f = 0; f < raw.length / frameBytes; f++) {+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ if (raw[f * frameBytes + (y * width + x) * 4 + 3] <= 8) continue;+ drawn += 1;+ if (x < x0 || x >= x1 || y < y0 || y >= y1) throw new Error(`frame ${f}: text pixel at (${x},${y}) outside the safe area`);+ }+ }+ }+ return drawn;+}++describe.skipIf(!chrome || !ffmpeg)('music-video typography overlay with real Chrome and ffmpeg (#8984)', () => {+ beforeAll(async () => {+ const profile = join(PATHS.data, 'chrome-test-profile');+ proc = spawn(chrome, ['--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });+ const ws = await new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('Test Chrome did not start')), 20000);+ proc.once('error', reject);+ proc.stderr.on('data', bytes => {+ const match = bytes.toString().match(/DevTools listening on (ws:\/\/\S+)/);+ if (match) { clearTimeout(timer); resolve(match[1]); }+ });+ });+ endpoint = new URL(ws).origin.replace('ws:', 'http:');+ browser = await chromium.connectOverCDP(endpoint);+ }, 30000);++ afterAll(() => _cleanupTestBrowser({ browser, proc, cleanup: cleanupTempDataRoots }));++ it('lays timed text over the cut on one continuous audio master, covering the edit within a frame', async () => {+ const dir = join(PATHS.data, 'fixture');+ await mkdir(dir, { recursive: true });+ const [w, h] = [320, 180];+ // Two 1.5s "scenes" (blue, green) cut over a 3s tone.+ run(['-f', 'lavfi', '-i', `color=blue:s=${w}x${h}:r=${FPS}:d=1.5`, '-y', join(dir, 'a.mp4')]);+ run(['-f', 'lavfi', '-i', `color=green:s=${w}x${h}:r=${FPS}:d=1.5`, '-y', join(dir, 'b.mp4')]);+ run(['-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-y', join(dir, 'song.wav')]);+ const clip = (name) => ({ videoPath: join(dir, name), width: w, height: h, fps: FPS, duration: 1.5, sourceSec: 1.5, loop: false, inSec: 0, outSec: 1.5 });+ const clips = [clip('a.mp4'), clip('b.mp4')];+ // A hero line spanning the cut at 1.5s.+ const cues = [{ id: 'c1', text: 'ACROSS THE CUT', startSec: 1, endSec: 2, template: 'fade', placement: 'center', emphasis: 'hero' }];+ const overlays = await renderTypographyOverlays({ jobId: 'job-a', cues, style: { color: '#ffffff', font: 'sans' }, width: w, height: h, fps: FPS, durationSec: 3 });+ expect(overlays).toEqual([{ path: expect.stringContaining('overlay-0.mov'), startSec: 1, durationSec: 1 }]);++ const output = join(dir, 'out.mp4');+ const { args } = buildMusicVideoFfmpegArgs(clips, join(dir, 'song.wav'), output, { audioDurationSec: 3, overlays });+ run(args.filter((arg, i) => !(arg === '-progress' || args[i - 1] === '-progress')));++ expect(Math.abs(await probeVideoDuration(output) - 3)).toBeLessThanOrEqual(1 / FPS);+ // One continuous master: the tone never drops out across the cut or the text.+ const pcm = run(['-i', output, '-map', '0:a', '-ac', '1', '-ar', '8000', '-f', 's16le', '-']);+ const samples = new Int16Array(Uint8Array.from(pcm).buffer);+ expect(Math.abs(samples.length / 8000 - 3)).toBeLessThanOrEqual(1 / FPS);+ for (let start = 0; start + 80 <= samples.length - 800; start += 80) {+ let peak = 0;+ for (let i = start; i < start + 80; i++) peak = Math.max(peak, Math.abs(samples[i]));+ expect(peak, `silent 10ms window at ${start / 8000}s`).toBeGreaterThan(1000);+ }++ const rgb = frames(output, 'rgb24');+ const frameBytes = w * h * 3;+ expect(rgb.length / frameBytes).toBe(3 * FPS);+ const whiteIn = (f) => {+ let n = 0;+ for (let p = 0; p < w * h; p++) {+ const o = f * frameBytes + p * 3;+ if (rgb[o] > 200 && rgb[o + 1] > 200 && rgb[o + 2] > 200) n += 1;+ }+ return n;+ };+ // No text before the cue; text drawn over BOTH scenes on either side of the cut; gone after.+ expect(whiteIn(12)).toBe(0);+ expect(whiteIn(33)).toBeGreaterThan(100);+ expect(whiteIn(39)).toBeGreaterThan(100);+ expect(whiteIn(60)).toBe(0);+ // Footage passes through untouched outside the text: the corner keeps its scene colour.+ const corner = (f) => [...rgb.subarray(f * frameBytes, f * frameBytes + 3)];+ expect(corner(33)[2]).toBeGreaterThan(200); // blue scene+ expect(corner(39)[1]).toBeGreaterThan(100); // green scene++ // Same time, same frame: a second capture of the same cues decodes identically.+ const again = await renderTypographyOverlays({ jobId: 'job-b', cues, style: {}, width: w, height: h, fps: FPS, durationSec: 3 });+ expect(frames(again[0].path, 'rgba').equals(frames(overlays[0].path, 'rgba'))).toBe(true);+ await removeCompositionScratch('job-a');+ await removeCompositionScratch('job-b');+ expect(await readdir(join(PATHS.data, COMPOSITION_SCRATCH_DIR))).toEqual([]);+ }, 60000);++ it.each([['16:9', 480, 270], ['9:16', 270, 480]])('keeps every motion template inside the title-safe area at %s', async (_label, width, height) => {+ const long = 'A deliberately long lyric line that has to wrap and shrink to stay inside the frame';+ const cues = [+ { id: 'hero', text: long, startSec: 0, endSec: 0.75, template: 'pop', placement: 'center', emphasis: 'hero' },+ { id: 'low', text: long, startSec: 1, endSec: 1.75, template: 'rise', placement: 'lower', emphasis: 'subtitle' },+ { id: 'up', text: long, startSec: 2, endSec: 2.75, template: 'typewriter', placement: 'upper', emphasis: 'subtitle' },+ ];+ const overlays = await renderTypographyOverlays({ jobId: `safe-${width}`, cues, style: { font: 'serif' }, width, height, fps: 12, durationSec: 3 });+ let drawn = 0;+ for (const overlay of overlays) drawn += assertInsideSafeArea(overlay.path, width, height);+ expect(drawn).toBeGreaterThan(1000);+ }, 60000);++ it('cancels a capture in progress and leaves no overlay behind', async () => {+ const controller = new AbortController();+ const cues = [{ id: 'c', text: 'Cancel me', startSec: 0, endSec: 20, template: 'fade', placement: 'lower', emphasis: 'subtitle' }];+ const capture = renderTypographyOverlays({ jobId: 'job-cancel', cues, style: {}, width: 320, height: 180, fps: 24, durationSec: 20, signal: controller.signal,+ onProgress: (fraction) => { if (fraction > 0.05) controller.abort(new Error('Render cancelled')); } });+ await expect(capture).rejects.toThrow();+ await removeCompositionScratch('job-cancel');+ expect(existsSync(join(PATHS.data, COMPOSITION_SCRATCH_DIR, 'job-cancel'))).toBe(false);+ }, 60000);+});diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.jsindex 7d14f6fe19..fae7c5ce84 100644--- a/server/services/musicVideo/projectsFile.test.js+++ b/server/services/musicVideo/projectsFile.test.js@@ -170,6 +170,46 @@ describe('projectsFile federation (#1770)', () => {expect(swapped.phrases).toEqual([{ ...saved.phrases[0], startSec: null, endSec: null }]);});+ // #8984 — the composition manifest is editable record state like the lyric+ // cues: normalized on save, carried by clone and peer sync, and its timings+ // (cue times, poster frame) cleared with the audio source, text kept.+ it('persists the composition manifest through reload, clone, and peer sync; an audio change clears its timings', async () => {+ const p = await file.createProject({ name: 'Composed MV', trackId: 't1' });+ expect(p.composition).toBeNull();++ await file.updateProject(p.id, { composition: {+ mode: 'composed',+ textCues: [+ { text: ' Hook line ', startSec: 1, endSec: 3, template: 'rise', placement: 'center', emphasis: 'hero' },+ { text: 'Tail', startSec: 4, endSec: 2 },+ ],+ style: { color: '#FFCC00' },+ posterSec: 2,+ } });+ const saved = await file.getProject(p.id);+ expect(saved.composition).toEqual({+ version: 1,+ mode: 'composed',+ textCues: [+ { id: expect.stringMatching(/^mtc-/), text: 'Hook line', startSec: 1, endSec: 3, template: 'rise', placement: 'center', emphasis: 'hero' },+ { id: expect.stringMatching(/^mtc-/), text: 'Tail', startSec: 4, endSec: null, template: 'fade', placement: 'lower', emphasis: 'subtitle' },+ ],+ style: { color: '#ffcc00', font: 'sans' },+ posterSec: 2,+ });++ expect((await file.cloneProject(p.id)).composition).toEqual(saved.composition);+ await file.mergeProjectsFromSync([{ ...saved, id: 'mv-peer-composed', updatedAt: '2099-01-01T00:00:00Z' }]);+ expect((await file.getProject('mv-peer-composed')).composition).toEqual(saved.composition);++ const swapped = await file.updateProject(p.id, { uploadedAudioFilename: 'other.wav' });+ expect(swapped.composition.posterSec).toBeNull();+ expect(swapped.composition.textCues.map((c) => [c.id, c.text, c.startSec, c.endSec]))+ .toEqual(saved.composition.textCues.map((c) => [c.id, c.text, null, null]));++ expect((await file.updateProject(p.id, { composition: null })).composition).toBeNull();+ });+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.jsindex 5381bc35d6..465a1fddd9 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -30,6 +30,7 @@ import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';import { isStr } from '../../lib/textUtils.js';import { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';import { ensureSceneTakes, TAKE_SLOT } from './takes.js';+import { normalizeComposition, invalidateCompositionTiming } from './composition.js';export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';@@ -128,6 +129,8 @@ export function buildProjectRecord(input, { id, now }) {lyricCues: [],phrases: [],pacing: null,+ // #8984 — composition manifest (null = plain concatenation render).+ composition: null,scenes: [],renderHistoryId: null,// Soft-delete tombstone trio — kept so peer-sync federation (a follow-up)@@ -200,6 +203,8 @@ export function applyProjectPatch(project, patch) {...(patch.visualSpec ? { visualSpec: normalizeVisualSpec(patch.visualSpec, project.visualSpec) } : {}),...(Array.isArray(patch.lyricCues) ? { lyricCues: normalizeLyricCues(patch.lyricCues) } : {}),...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),+ // #8984 — the composition manifest is replaced whole; null clears it.+ ...('composition' in patch ? { composition: normalizeComposition(patch.composition) } : {}),};const conceptMergedPatch = ('concept' in timedPatch && timedPatch.concept && project.concept)? { ...timedPatch, concept: { ...project.concept, ...timedPatch.concept } }@@ -252,6 +257,9 @@ export function applyProjectPatch(project, patch) {// fresh lists of its own.return touch(project, {...invalidateTimedText(project),+ // Composition cue times and the poster frame were set against the old+ // song too: keep the text, clear the timings (#8984).+ ...(project.composition ? { composition: invalidateCompositionTiming(project.composition) } : {}),...mergedPatch,...statusPatch,audioAnalysis: null,diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 0c0cd4fe18..4ec4c319b2 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -35,6 +35,8 @@ import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';import { getTrack } from '../tracks/index.js';import { getProject, listProjects, updateProject } from './projects.js';+import { renderableCues } from './composition.js';+import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';// Per-project render mutex (keyed by projectId so two projects can render in// parallel; same-project re-entry returns 409 with the live jobId for re-attach).@@ -99,7 +101,14 @@ export function getRenderJobStatus(jobId) {export function cancelRender(jobId) {const job = jobs.get(jobId);- if (!job || !job.process) return false;+ if (!job) return false;+ // A composed render spends its first phase capturing the typography overlay+ // (no ffmpeg yet); abort that capture instead.+ if (!job.process) {+ if (!job.overlayAbort || job.overlayAbort.signal.aborted) return false;+ job.overlayAbort.abort(new Error('Render cancelled'));+ return true;+ }const proc = job.process;killWithEscalation(proc, { label: 'music-video render', stillRunning: () => job.process === proc });return true;@@ -244,7 +253,10 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =// video-only (each scaled/padded to the canonical dims + fps and trimmed to its// snapped out-point) and maps ONE external audio input as the sole output audio.// `-shortest` ends the output at the shorter of (concatenated video, track).-export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null } = {}) {+// `overlays` (a composed render, #8984) are transparent typography clips, each+// offset to its song time and laid over the cut footage — the footage passes+// through untouched outside them, and the master audio is never re-cut.+export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [] } = {}) {if (!Array.isArray(clips) || clips.length === 0) throw new Error('buildMusicVideoFfmpegArgs: empty clips');const canonW = clips[0].width;const canonH = clips[0].height;@@ -261,8 +273,9 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDif (c.loop !== false) inputs.push('-stream_loop', '-1');inputs.push('-i', c.videoPath);}- const audioIdx = clips.length; // master audio is the last input+ const audioIdx = clips.length; // master audio follows the clipsinputs.push('-i', audioPath);+ for (const overlay of overlays) inputs.push('-itsoffset', String(overlay.startSec), '-i', overlay.path);const filters = [];const vStreams = [];@@ -279,7 +292,12 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD);vStreams.push(`[v${i}]`);}- filters.push(`${vStreams.join('')}concat=n=${clips.length}:v=1:a=0[outv]`);+ const cutLabel = overlays.length > 0 ? 'cut0' : 'outv';+ filters.push(`${vStreams.join('')}concat=n=${clips.length}:v=1:a=0[${cutLabel}]`);+ overlays.forEach((_, k) => {+ const out = k === overlays.length - 1 ? 'outv' : `cut${k + 1}`;+ filters.push(`[cut${k}][${audioIdx + 1 + k}:v]overlay=eof_action=pass:format=auto[${out}]`);+ });const videoTotal = clips.reduce((s, c) => s + (c.outSec - c.inSec), 0);const totalDuration = audioDurationSec != null ? Math.min(videoTotal, audioDurationSec) : videoTotal;@@ -346,6 +364,10 @@ export async function renderMusicVideo(projectId) {const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;const outputPath = join(PATHS.videos, filename);const { args, totalDuration, canonW, canonH, fps } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec });+ // #8984: a composed project lays its timed text cues over the cut. No+ // renderable cue (plain mode, or nothing timed) renders exactly as before.+ const cues = renderableCues(project.composition, totalDuration);+ const composition = cues.length > 0 ? project.composition : null;const job = { id: jobId, projectId, status: 'running', clients: [], process: null, totalDuration };jobs.set(jobId, job);@@ -362,127 +384,177 @@ export async function renderMusicVideo(projectId) {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→rendering write failed: ${err.message}`);});- console.log(`🎬 Rendering music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} duration=${totalDuration.toFixed(2)}s`);-- const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));- job.process = proc;-- let stderrBuf = '';- proc.stderr.on('data', (chunk) => {- stderrBuf += chunk.toString();- const lines = stderrBuf.split('\n');- stderrBuf = lines.pop();- for (const raw of lines) {- const line = raw.trim();- const eq = line.indexOf('=');- if (eq <= 0) continue;- const key = line.slice(0, eq);- const val = line.slice(eq + 1);- if (key === 'out_time_us') {- const us = parseInt(val, 10);- if (Number.isFinite(us) && totalDuration > 0) {- broadcastSse(job, { type: 'progress', progress: Math.min(1, (us / 1_000_000) / totalDuration) });+ console.log(`🎬 Rendering music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} cues=${cues.length} duration=${totalDuration.toFixed(2)}s`);++ const releaseScratch = () => (composition ? removeCompositionScratch(jobId).catch((err) => {+ console.warn(`⚠️ Music-video render [${jobId.slice(0, 8)}] could not remove its overlay scratch: ${err.message}`);+ }) : null);++ // A composed render first captures its overlay (progress 0–50%), then+ // encodes (50–100%); a plain render encodes across the whole bar.+ const startEncode = (encodeArgs, progressBase = 0) => {+ const encodeProgress = (fraction) => progressBase + (1 - progressBase) * fraction;+ const proc = spawn(ffmpeg, encodeArgs, safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));+ job.process = proc;++ let stderrBuf = '';+ proc.stderr.on('data', (chunk) => {+ stderrBuf += chunk.toString();+ const lines = stderrBuf.split('\n');+ stderrBuf = lines.pop();+ for (const raw of lines) {+ const line = raw.trim();+ const eq = line.indexOf('=');+ if (eq <= 0) continue;+ const key = line.slice(0, eq);+ const val = line.slice(eq + 1);+ if (key === 'out_time_us') {+ const us = parseInt(val, 10);+ if (Number.isFinite(us) && totalDuration > 0) {+ broadcastSse(job, { type: 'progress', progress: encodeProgress(Math.min(1, (us / 1_000_000) / totalDuration)) });+ }+ } else if (key === 'progress' && val === 'end') {+ broadcastSse(job, { type: 'progress', progress: 1 });}- } else if (key === 'progress' && val === 'end') {- broadcastSse(job, { type: 'progress', progress: 1 });}- }- });+ });- // Spawn-state tracking + exactly-once terminal guard + pre-vs-post-spawn- // dispatch live in the shared helper; only the finalize bodies below are- // service-specific (music-video mutates the project's render status).- attachFfmpegRenderGuard(proc, {- label: `Music-video render [${jobId.slice(0, 8)}]`,- onProcessError: (err) => {- // Post-spawn error (e.g. a failed kill during cancel). The ffmpeg is- // still live — do NOT release the project mutex or null job.process- // here, or a replacement render could spawn and overlap it. Record- // the reason; the pending 'close' runs the sole terminal finalization.- job.lastError = `ffmpeg process error: ${err.message}`;- console.log(`⚠️ Music-video render post-spawn error [${jobId.slice(0, 8)}]: ${err.message}`);- },- onSpawnError: async (err) => {- // Pre-spawn failure: the child never started, so 'close' won't follow.- job.process = null;- job.status = 'error';- const reason = `Failed to spawn ffmpeg: ${err.message}`;- job.lastError = reason;- console.error(`❌ Music-video render spawn error [${jobId.slice(0, 8)}]: ${reason}`);- broadcastSse(job, { type: 'error', error: reason });- projectRenders.delete(projectId);- await updateProject(projectId, { status: 'failed' }).catch((updateErr) => {- console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);- });- closeJobAfterDelay(jobs, jobId);- },- onClose: async (code, signal) => {- job.process = null;- if (code !== 0) {- const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';- job.status = canceled ? 'canceled' : 'error';- const reason = canceled ? 'Render cancelled' : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;+ // Spawn-state tracking + exactly-once terminal guard + pre-vs-post-spawn+ // dispatch live in the shared helper; only the finalize bodies below are+ // service-specific (music-video mutates the project's render status).+ attachFfmpegRenderGuard(proc, {+ label: `Music-video render [${jobId.slice(0, 8)}]`,+ onProcessError: (err) => {+ // Post-spawn error (e.g. a failed kill during cancel). The ffmpeg is+ // still live — do NOT release the project mutex or null job.process+ // here, or a replacement render could spawn and overlap it. Record+ // the reason; the pending 'close' runs the sole terminal finalization.+ job.lastError = `ffmpeg process error: ${err.message}`;+ console.log(`⚠️ Music-video render post-spawn error [${jobId.slice(0, 8)}]: ${err.message}`);+ },+ onSpawnError: async (err) => {+ // Pre-spawn failure: the child never started, so 'close' won't follow.+ job.process = null;+ job.status = 'error';+ const reason = `Failed to spawn ffmpeg: ${err.message}`;job.lastError = reason;- // A cancel is a user action (stdout); a non-zero exit is a failure (#7945).- const logClose = canceled ? console.log : console.error;- logClose(`${canceled ? '🛑' : '❌'} Music-video render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);- await unlink(outputPath).catch(() => {});- broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });+ console.error(`❌ Music-video render spawn error [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: reason });projectRenders.delete(projectId);- // A cancel restores the pre-render status (so a cancelled re-render of a- // 'complete' project stays 'complete'); a real failure marks it 'failed'.- const targetStatus = canceled ? priorStatus : 'failed';- await updateProject(projectId, { status: targetStatus }).catch((updateErr) => {- console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);- });- closeJobAfterDelay(jobs, jobId);- return;- }- // Success finalization runs in an event callback (no request to bubble- // to) — a throw in thumbnailing/history I/O would otherwise leave the- // project stuck 'rendering' and projectRenders un-cleared (every later- // render 409s). Wrap it so any failure still emits a terminal frame and- // releases the slot.- try {- job.status = 'complete';- const section = (project.audioAnalysis?.sections || [])- .filter(section => Number.isFinite(section.energy) && section.startSec >= 0 && section.endSec > section.startSec && section.startSec < totalDuration)- .sort((a, b) => b.energy - a.energy || a.startSec - b.startSec)[0];- const atSec = section ? (section.startSec + Math.min(section.endSec, totalDuration)) / 2 : undefined;- const thumb = await generateThumbnail(outputPath, jobId, { atSec });- const meta = {- id: jobId,- prompt: `Music Video: ${project.name}`,- modelId: 'music-video',- seed: 0,- width: canonW,- height: canonH,- numFrames: Math.round(totalDuration * (fps || 24)),- fps: fps || 24,- filename,- thumbnail: thumb,- createdAt: new Date().toISOString(),- musicVideoProjectId: projectId,- };- await appendToVideoHistory(meta);- await updateProject(projectId, { renderHistoryId: jobId, status: 'complete' }).catch((updateErr) => {- console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);- });- console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);- broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });- } catch (err) {- job.status = 'error';- job.lastError = `Finalize failed: ${err.message}`;- console.error(`❌ Music-video render finalize failed [${jobId.slice(0, 8)}]: ${err.message}`);- broadcastSse(job, { type: 'error', error: 'Render finalize failed' });await updateProject(projectId, { status: 'failed' }).catch((updateErr) => {console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);});- } finally {- projectRenders.delete(projectId);+ await releaseScratch();closeJobAfterDelay(jobs, jobId);- }- },+ },+ onClose: async (code, signal) => {+ job.process = null;+ if (code !== 0) {+ const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';+ job.status = canceled ? 'canceled' : 'error';+ const reason = canceled ? 'Render cancelled' : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;+ job.lastError = reason;+ // A cancel is a user action (stdout); a non-zero exit is a failure (#7945).+ const logClose = canceled ? console.log : console.error;+ logClose(`${canceled ? '🛑' : '❌'} Music-video render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);+ await unlink(outputPath).catch(() => {});+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });+ projectRenders.delete(projectId);+ // A cancel restores the pre-render status (so a cancelled re-render of a+ // 'complete' project stays 'complete'); a real failure marks it 'failed'.+ const targetStatus = canceled ? priorStatus : 'failed';+ await updateProject(projectId, { status: targetStatus }).catch((updateErr) => {+ console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);+ });+ await releaseScratch();+ closeJobAfterDelay(jobs, jobId);+ return;+ }+ // Success finalization runs in an event callback (no request to bubble+ // to) — a throw in thumbnailing/history I/O would otherwise leave the+ // project stuck 'rendering' and projectRenders un-cleared (every later+ // render 409s). Wrap it so any failure still emits a terminal frame and+ // releases the slot.+ try {+ job.status = 'complete';+ const section = (project.audioAnalysis?.sections || [])+ .filter(section => Number.isFinite(section.energy) && section.startSec >= 0 && section.endSec > section.startSec && section.startSec < totalDuration)+ .sort((a, b) => b.energy - a.energy || a.startSec - b.startSec)[0];+ // An explicitly chosen poster frame (#8984) wins over the loudest-section guess.+ const posterSec = project.composition?.posterSec;+ const atSec = typeof posterSec === 'number' && posterSec < totalDuration ? posterSec+ : section ? (section.startSec + Math.min(section.endSec, totalDuration)) / 2 : undefined;+ const thumb = await generateThumbnail(outputPath, jobId, { atSec });+ const meta = {+ id: jobId,+ prompt: `Music Video: ${project.name}`,+ modelId: 'music-video',+ seed: 0,+ width: canonW,+ height: canonH,+ numFrames: Math.round(totalDuration * (fps || 24)),+ fps: fps || 24,+ filename,+ thumbnail: thumb,+ createdAt: new Date().toISOString(),+ musicVideoProjectId: projectId,+ };+ await appendToVideoHistory(meta);+ await updateProject(projectId, { renderHistoryId: jobId, status: 'complete' }).catch((updateErr) => {+ console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);+ });+ console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);+ broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });+ } catch (err) {+ job.status = 'error';+ job.lastError = `Finalize failed: ${err.message}`;+ console.error(`❌ Music-video render finalize failed [${jobId.slice(0, 8)}]: ${err.message}`);+ broadcastSse(job, { type: 'error', error: 'Render finalize failed' });+ await updateProject(projectId, { status: 'failed' }).catch((updateErr) => {+ console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);+ });+ } finally {+ projectRenders.delete(projectId);+ await releaseScratch();+ closeJobAfterDelay(jobs, jobId);+ }+ },+ });+ };++ if (!composition) {+ startEncode(args);+ return { jobId };+ }++ // Composed: capture the overlay in the background (the route returns the+ // jobId at once; progress/cancel flow through the job like the encode's).+ // A capture failure or cancel is terminal here, since no ffmpeg exists yet+ // for the render guard to finalize.+ job.overlayAbort = new AbortController();+ const { signal } = job.overlayAbort;+ renderTypographyOverlays({+ jobId, cues, style: composition.style, width: canonW, height: canonH, fps, durationSec: totalDuration, signal,+ onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: 0.5 * fraction }),+ }).then((overlays) => {+ signal.throwIfAborted();+ const composed = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays });+ startEncode(composed.args, 0.5);+ }).catch(async (err) => {+ const canceled = signal.aborted;+ job.status = canceled ? 'canceled' : 'error';+ const reason = canceled ? 'Render cancelled' : `Typography overlay failed: ${err.message}`;+ job.lastError = reason;+ const log = canceled ? console.log : console.error;+ log(`${canceled ? '🛑' : '❌'} Music-video render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });+ projectRenders.delete(projectId);+ const targetStatus = canceled ? priorStatus : 'failed';+ await updateProject(projectId, { status: targetStatus }).catch((updateErr) => {+ console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);+ });+ await releaseScratch();+ closeJobAfterDelay(jobs, jobId);});return { jobId };@@ -499,6 +571,10 @@ export async function renderMusicVideo(projectId) {// propagates to the bootstrap caller's logBootstrapFailure rather than// reporting zero recovered.export async function recoverStuckMusicVideoRenders() {+ // No overlay capture survives a restart either; drop any scratch it left.+ await sweepCompositionScratch().catch((err) => {+ console.warn(`⚠️ Music Video recovery: could not remove stale overlay scratch: ${err.message}`);+ });const stuck = (await listProjects()).filter((p) => p?.status === 'rendering' && !projectRenders.has(p.id));let recovered = 0;for (const project of stuck) {diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.jsindex e7c2e25bc2..8475948032 100644--- a/server/services/musicVideo/render.terminal.test.js+++ b/server/services/musicVideo/render.terminal.test.js@@ -29,7 +29,15 @@ const h = vi.hoisted(() => {procs.push(p);return p;};- return { procs, spawn };+ // #8984 — the overlay capture, held open until a test settles it (or the+ // render's abort signal rejects it, as the real capture does).+ const overlays = { calls: [], resolve: null };+ const renderTypographyOverlays = (options) => new Promise((resolve, reject) => {+ overlays.calls.push(options);+ overlays.resolve = resolve;+ options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });+ });+ return { procs, spawn, overlays, renderTypographyOverlays };});vi.mock('../../lib/childProcess.js', () => ({ spawn: h.spawn }));@@ -59,9 +67,15 @@ vi.mock('../videoGen/local.js', () => ({mutateVideoHistory: vi.fn(async (fn) => fn([])),}));vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));+vi.mock('./compositionRender.js', () => ({+ renderTypographyOverlays: h.renderTypographyOverlays,+ removeCompositionScratch: vi.fn(async () => {}),+ sweepCompositionScratch: vi.fn(async () => {}),+}));vi.mock('./projects.js', () => ({ getProject: vi.fn(), listProjects: vi.fn(async () => []), updateProject: vi.fn(async () => ({})) }));-import { renderMusicVideo, getRenderJobStatus } from './render.js';+import { renderMusicVideo, getRenderJobStatus, cancelRender } from './render.js';+import { removeCompositionScratch } from './compositionRender.js';import { findFfmpeg, generateThumbnail } from '../../lib/ffmpeg.js';import { loadHistory } from '../videoGen/local.js';import { getTrack } from '../tracks/index.js';@@ -83,6 +97,7 @@ const prime = (projectId) => {beforeEach(() => {vi.clearAllMocks();h.procs.length = 0;+ h.overlays.calls.length = 0;});describe('renderMusicVideo terminal handling (#2386)', () => {@@ -318,3 +333,60 @@ describe('renderMusicVideo clip coverage (#8964)', () => {expect(filterGraph(args)).not.toContain('tpad');});});++// #8984 — a composed render captures its typography overlay before ffmpeg+// exists. The capture phase must be cancelable and terminal on its own, and a+// project whose manifest has nothing to draw must render exactly as before.+describe('composed render lifecycle (#8984)', () => {+ const cue = { id: 'c1', text: 'Hello', startSec: 0.5, endSec: 1.5, template: 'fade', placement: 'lower', emphasis: 'subtitle' };+ const primeComposed = (projectId, composition) => {+ prime(projectId);+ getProject.mockResolvedValue({+ id: projectId, name: 'P', trackId: 't1', status: 'complete',+ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }],+ composition: { version: 1, style: { color: '#ffffff', font: 'sans' }, posterSec: null, ...composition },+ });+ };++ it('renders a concat-mode manifest through the plain path', async () => {+ primeComposed('plain-1', { mode: 'concat', textCues: [cue] });+ await renderMusicVideo('plain-1');+ expect(h.overlays.calls).toHaveLength(0);+ expect(lastProc().args).not.toContain('-itsoffset');+ });++ it('cancels during overlay capture: no ffmpeg, prior status restored, scratch removed, slot released', async () => {+ primeComposed('cancel-1', { mode: 'composed', textCues: [cue] });+ const { jobId } = await renderMusicVideo('cancel-1');+ expect(h.overlays.calls).toHaveLength(1);+ expect(h.procs).toHaveLength(0);+ expect(cancelRender(jobId)).toBe(true);+ await tick();+ await tick();+ expect(getRenderJobStatus(jobId).status).toBe('canceled');+ expect(h.procs).toHaveLength(0);+ expect(updateProject).toHaveBeenLastCalledWith('cancel-1', { status: 'complete' });+ expect(removeCompositionScratch).toHaveBeenCalledWith(jobId);+ expect(cancelRender(jobId)).toBe(false);+ const again = await renderMusicVideo('cancel-1');+ expect(again.jobId).not.toBe(jobId);+ });++ it('lays the captured overlays over the cut and honors the chosen poster frame', async () => {+ primeComposed('composed-1', { mode: 'composed', textCues: [cue], posterSec: 1 });+ const { jobId } = await renderMusicVideo('composed-1');+ expect(h.overlays.calls[0]).toMatchObject({ jobId, width: 768, height: 512, fps: 24, cues: [expect.objectContaining({ id: 'c1' })] });+ h.overlays.resolve([{ path: '/data/overlay-0.mov', startSec: 0.5, durationSec: 1 }]);+ await tick();+ const { args } = lastProc();+ expect(args.slice(args.indexOf('-itsoffset'), args.indexOf('-itsoffset') + 4)).toEqual(['-itsoffset', '0.5', '-i', '/data/overlay-0.mov']);+ expect(args[args.indexOf('-filter_complex') + 1]).toContain('[cut0][2:v]overlay=eof_action=pass:format=auto[outv]');+ expect(args[args.indexOf('-map') + 1]).toBe('[outv]');+ lastProc().emit('spawn');+ lastProc().emit('close', 0, null);+ await tick();+ expect(generateThumbnail).toHaveBeenCalledWith(expect.any(String), jobId, { atSec: 1 });+ expect(getRenderJobStatus(jobId).status).toBe('complete');+ expect(removeCompositionScratch).toHaveBeenCalledWith(jobId);+ });+});