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: add a code-rendered music video style (#9076)
[._.]/ Adam Eivy86e7b7fee868
diff --git a/client/src/components/musicVideo/CodeVideoPanel.jsx b/client/src/components/musicVideo/CodeVideoPanel.jsxnew file mode 100644index 0000000000..9e78007b46--- /dev/null+++ b/client/src/components/musicVideo/CodeVideoPanel.jsx@@ -0,0 +1,203 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { useSearchParams } from 'react-router';+import { Film, RotateCcw } from 'lucide-react';+import toast from '../ui/Toast';+import useProviderModels from '../../hooks/useProviderModels.js';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import { shouldIgnoreGlobalKey } from '../../lib/a11yKeyboard.js';+import { prepareAnimationHtml } from '../codeAnimation/CodeAnimationPreview.jsx';+import { generateMusicVideoCode, getMusicVideoCodeDocument, regenerateMusicVideoCodeSection } from '../../services/apiMusicVideo.js';++const buttonCls = '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';++/**+ * Preview and generation for a code-rendered music video (#9076).+ * The selected section is `?section=`. Generation runs only from a click,+ * after the provider and model are shown.+ */+export default function CodeVideoPanel({ project, audioUrl, onProject }) {+ const [searchParams, setSearchParams] = useSearchParams();+ const [doc, setDoc] = useState(null);+ const [error, setError] = useState('');+ const [busy, setBusy] = useState(null);+ const [t, setT] = useState(0);+ const [playing, setPlaying] = useState(false);+ const [looping, setLooping] = useState(false);+ const iframeRef = useRef(null);+ const audioRef = useRef(null);+ const tRef = useRef(0);+ const {+ providers, selectedProviderId, selectedModel, availableModels, selectedProvider,+ setSelectedProviderId, setSelectedModel,+ } = useProviderModels({ allowDefault: true, silent: true });++ useEffect(() => {+ let active = true;+ setError('');+ getMusicVideoCodeDocument(project.id, { silent: true })+ .then((next) => { if (active) setDoc(next); })+ .catch((err) => { if (active) setError(err?.message || 'Could not build the code preview'); });+ return () => { active = false; };+ }, [project.id, project.updatedAt, project.composition?.codeVideo?.generatedAt]);++ const sections = doc?.song?.sections || doc?.timeline?.sections || [];+ const fps = doc?.fps || 24;+ const duration = doc?.durationSec || 0;+ const requested = searchParams.get('section');+ const section = sections.find((item) => item.id === requested) || sections[0] || null;++ useEffect(() => {+ if (!section || requested === section.id) return undefined;+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.set('section', section.id);+ return next;+ }, { replace: true });+ return undefined;+ }, [section, requested, setSearchParams]);++ const srcDoc = useMemo(() => (doc?.html ? prepareAnimationHtml(doc.html, 'MV_CODE_AUDIO', null) : null), [doc]);++ const seek = (time) => {+ const next = Math.min(Math.max(0, time), duration || time);+ tRef.current = next;+ setT(next);+ iframeRef.current?.contentWindow?.postMessage({ type: 'mv-code:seek', t: next }, '*');+ if (audioRef.current && Math.abs((audioRef.current.currentTime || 0) - next) > 0.05) {+ audioRef.current.currentTime = next;+ }+ };++ useEffect(() => {+ const step = (dir) => seek(tRef.current + dir / fps);+ const jump = (dir) => {+ if (!sections.length) return;+ const index = Math.max(0, sections.findIndex((item) => item.id === (section?.id)));+ const next = sections[(index + dir + sections.length) % sections.length];+ setSearchParams((prev) => {+ const params = new URLSearchParams(prev);+ params.set('section', next.id);+ return params;+ }, { replace: true });+ seek(next.startSec || 0);+ };+ const onKey = (event) => {+ if (shouldIgnoreGlobalKey(event)) return;+ if (event.key === ',' || event.key === '.') {+ event.preventDefault();+ if (audioRef.current) audioRef.current.pause();+ setPlaying(false);+ step(event.key === '.' ? 1 : -1);+ } else if (event.key === '[' || event.key === ']') {+ event.preventDefault();+ jump(event.key === ']' ? 1 : -1);+ } else if (event.key === 'l' || event.key === 'L') {+ event.preventDefault();+ setLooping((value) => !value);+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ });++ useEffect(() => {+ if (!playing) return undefined;+ let frame = 0;+ const tick = () => {+ const audio = audioRef.current;+ if (!audio) return;+ let time = audio.currentTime || 0;+ if (looping && section && time >= section.endSec) {+ time = section.startSec || 0;+ audio.currentTime = time;+ }+ tRef.current = time;+ setT(time);+ iframeRef.current?.contentWindow?.postMessage({ type: 'mv-code:seek', t: time }, '*');+ frame = requestAnimationFrame(tick);+ };+ frame = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(frame);+ }, [playing, looping, section]);++ const providerLabel = selectedProvider?.name || selectedProviderId || 'the active provider';+ const modelLabel = selectedModel ? ` / ${selectedModel}` : '';++ const run = async (sectionId) => {+ setBusy(sectionId || 'all');+ const body = { providerId: selectedProviderId || undefined, model: selectedModel || undefined };+ const task = sectionId+ ? regenerateMusicVideoCodeSection(project.id, sectionId, body, { silent: true })+ : generateMusicVideoCode(project.id, body, { silent: true });+ const result = await Promise.resolve(task).catch((err) => {+ toast.error(err?.message || 'Code video generation failed');+ return null;+ });+ setBusy(null);+ if (result?.project) onProject(result.project);+ };++ const togglePlay = () => {+ const audio = audioRef.current;+ if (!audio) { setPlaying((value) => !value); return; }+ if (playing) { audio.pause(); setPlaying(false); return; }+ audio.play?.()?.catch?.(() => {});+ setPlaying(true);+ };++ return (+ <section className="mt-3 space-y-2 rounded-lg border border-port-border bg-port-bg p-2" aria-label="Code-rendered preview">+ <div className="flex flex-wrap items-end gap-2">+ {providers.length > 0 && (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ label="Code video provider"+ disabled={!!busy}+ modelDisabled={availableModels.length === 0}+ compact+ alwaysShowModel+ emptyProviderOption="Active provider (default)"+ emptyModelOption="Default model"+ />+ )}+ <p className="text-xs text-port-text-muted">+ Generate code video uses {providerLabel}{modelLabel}. Nothing is sent until you click.+ </p>+ <button type="button" className={`${buttonCls} bg-port-accent text-white`} disabled={!!busy || !doc}+ onClick={() => run(null)}>+ <Film size={14} /> {busy === 'all' ? 'Generating…' : 'Generate code video'}+ </button>+ <button type="button" className={buttonCls} disabled={!!busy || !section}+ onClick={() => run(section.id)}>+ <RotateCcw size={14} /> {busy && busy !== 'all' ? 'Regenerating…' : 'Regenerate section'}+ </button>+ </div>+ {error && <p className="text-xs text-port-error" role="alert">{error}</p>}+ <div className="overflow-hidden rounded border border-port-border bg-black" style={{ aspectRatio: doc?.width && doc?.height ? `${doc.width} / ${doc.height}` : '16 / 9', maxHeight: '70vh' }}>+ {srcDoc ? (+ <iframe ref={iframeRef} title="Code-rendered preview" sandbox="allow-scripts" srcDoc={srcDoc} className="h-full w-full" />+ ) : (+ <p className="p-3 text-xs text-port-text-muted">{error ? '' : 'Building the preview…'}</p>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" className={buttonCls} onClick={togglePlay} disabled={!doc}>{playing ? 'Pause' : 'Play'}</button>+ <button type="button" className={buttonCls} aria-pressed={looping} onClick={() => setLooping((value) => !value)}>+ {looping ? 'Looping section' : 'Loop section'}+ </button>+ <label htmlFor="mv-code-scrub" className="sr-only">Scrub preview</label>+ <input id="mv-code-scrub" type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}+ onChange={(e) => { if (audioRef.current) audioRef.current.pause(); setPlaying(false); seek(Number(e.target.value)); }}+ className="min-w-0 flex-1" />+ <span className="text-xs text-port-text-muted">{section ? section.label || section.id : 'No section'} · {t.toFixed(2)}s</span>+ </div>+ <p className="text-[11px] text-port-text-muted">, and . step one frame. [ and ] change section. l loops the section.</p>+ {audioUrl && <audio ref={audioRef} src={audioUrl} preload="none" className="hidden" />}+ </section>+ );+}diff --git a/client/src/components/musicVideo/CodeVideoPanel.test.jsx b/client/src/components/musicVideo/CodeVideoPanel.test.jsxnew file mode 100644index 0000000000..2ec70db5e4--- /dev/null+++ b/client/src/components/musicVideo/CodeVideoPanel.test.jsx@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({+ getMusicVideoCodeDocument: vi.fn(),+ generateMusicVideoCode: vi.fn(),+ regenerateMusicVideoCodeSection: vi.fn(),+}));++vi.mock('../../services/apiMusicVideo.js', () => api);+vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({+ providers: [{ id: 'stub-provider', name: 'Stub Provider', models: ['fixture-model'] }],+ selectedProviderId: 'stub-provider',+ selectedModel: 'fixture-model',+ availableModels: ['fixture-model'],+ selectedProvider: { id: 'stub-provider', name: 'Stub Provider' },+ setSelectedProviderId: vi.fn(),+ setSelectedModel: vi.fn(),+ }),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import CodeVideoPanel from './CodeVideoPanel.jsx';++const DOC = {+ html: '<!doctype html><html><body><canvas id="c"></canvas></body></html>',+ durationSec: 2,+ fps: 24,+ width: 320,+ height: 180,+ song: { sections: [+ { id: 'a', label: 'Verse', startSec: 0, endSec: 1 },+ { id: 'b', label: 'Chorus', startSec: 1, endSec: 2 },+ ] },+};++const project = { id: 'mv-1', updatedAt: '2026-01-01T00:00:00.000Z', composition: { mode: 'code' } };++beforeEach(() => {+ api.getMusicVideoCodeDocument.mockReset();+ api.generateMusicVideoCode.mockReset();+ api.regenerateMusicVideoCodeSection.mockReset();+ api.getMusicVideoCodeDocument.mockResolvedValue(DOC);+ api.generateMusicVideoCode.mockResolvedValue({ project });+ api.regenerateMusicVideoCodeSection.mockResolvedValue({ project });+});++function renderPanel() {+ return render(+ <MemoryRouter initialEntries={['/music-video/mv-1']}>+ <CodeVideoPanel project={project} audioUrl={null} onProject={vi.fn()} />+ </MemoryRouter>,+ );+}++describe('CodeVideoPanel (#9076)', () => {+ it('shows the provider before a click and does not generate on mount', async () => {+ renderPanel();+ expect(await screen.findByText(/Stub Provider \/ fixture-model/)).toBeTruthy();+ const generate = await screen.findByRole('button', { name: 'Generate code video' });+ await waitFor(() => expect(generate).toBeEnabled());+ expect(api.generateMusicVideoCode).not.toHaveBeenCalled();+ fireEvent.click(generate);+ await waitFor(() => expect(api.generateMusicVideoCode).toHaveBeenCalledWith(+ 'mv-1',+ { providerId: 'stub-provider', model: 'fixture-model' },+ { silent: true },+ ));+ });++ it('steps a frame and selects the next section from the keyboard', async () => {+ renderPanel();+ await screen.findByLabelText('Scrub preview');+ fireEvent.keyDown(window, { key: '.' });+ expect(Number(screen.getByLabelText('Scrub preview').value)).toBeCloseTo(1 / 24, 5);+ fireEvent.keyDown(window, { key: ']' });+ await waitFor(() => expect(screen.getByText(/Chorus/)).toBeTruthy());+ });+});diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsxindex 7311b81e28..e968a309f9 100644--- a/client/src/components/musicVideo/ProjectToolbar.jsx+++ b/client/src/components/musicVideo/ProjectToolbar.jsx@@ -3,6 +3,7 @@ import RecordRenderPinRow from '../imageGen/RecordRenderPinRow.jsx';import { MUSCRIPTOR_MODELS } from '../../lib/muscriptorModels.js';import VideoRenderSettings from './VideoRenderSettings.jsx';import { sceneRenderReady, sceneVisualLayer } from '../../lib/musicVideoLayers.js';+import { compositionDraft, RENDER_STYLES } from './compositionDraft.js';const uniqueCount = (scenes, key) => new Set(scenes.map((scene) => scene[key]).filter(Boolean)).size;@@ -17,13 +18,15 @@ const uniqueCount = (scenes, key) => new Set(scenes.map((scene) => scene[key]).f*/export default function ProjectToolbar({project, midi, midiBound, videoSettings, sceneMedia, renderJob, busy,- onAnalyze, onPlan, onAutoArrange, onClone, onDelete,+ onAnalyze, onPlan, onAutoArrange, onClone, onDelete, onRenderStyle,}) {const scenes = project.scenes || [];const sceneCount = scenes.length;// #8985: in a composed render a still needs only its frame and a title card// needs neither frame nor clip, so the counts cover the scenes that use them.- const layered = project.composition?.mode === 'composed';+ const mode = project.composition?.mode || 'concat';+ const layered = mode === 'composed';+ const codeMode = mode === 'code';const frameScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) !== 'card');const footageScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) === 'footage');const referenceFrameCount = frameScenes.filter((scene) => scene.referenceImageId).length;@@ -37,11 +40,26 @@ export default function ProjectToolbar({const generatingFrames = Object.keys(sceneMedia.genScenes).length > 0;const generatingVideos = Object.keys(sceneMedia.genVideoScenes).length > 0;const noAudio = !project.trackId && !project.uploadedAudioFilename;+ const codeDuration = Math.max(+ project.audioAnalysis?.durationSec || 0,+ ...(project.scenes || []).map((scene) => scene.endSec || 0),+ ...(project.lyricCues || []).map((cue) => cue.endSec || cue.startSec || 0),+ );+ const codeReady = codeMode && !noAudio && codeDuration > 0;+ const footageBlocked = codeMode ? 'Code-rendered style draws the picture in code and does not generate footage' : '';const nextVersion = (project.version || 1) + 1;return (<div className="flex min-w-0 flex-wrap items-start gap-2"><h2 className="w-full text-lg font-semibold sm:w-auto sm:shrink-0">{project.name}</h2><div className="flex min-w-0 w-full flex-1 flex-wrap items-center justify-start gap-2 sm:w-auto sm:justify-end">+ <div>+ <label htmlFor="mv-toolbar-render-style" className="sr-only">Render style</label>+ <select id="mv-toolbar-render-style" value={compositionDraft(project).mode}+ onChange={(e) => onRenderStyle?.(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm min-h-[44px] sm:min-h-0">+ {RENDER_STYLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </div><button onClick={onAnalyze} disabled={busy.analyzing || noAudio}title={noAudio ? 'Link a track first' : 'Analyze beat grid'}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">@@ -96,18 +114,18 @@ export default function ProjectToolbar({<VideoRenderSettings videoSettings={videoSettings} generating={generatingVideos} /><buttononClick={sceneMedia.generateMissingFrames}- disabled={videoSettings.framePinSaving || sceneCount === 0 || missingFrameCount === 0 || generatingFrames}- title={videoSettings.framePinSaving+ disabled={codeMode || videoSettings.framePinSaving || sceneCount === 0 || missingFrameCount === 0 || generatingFrames}+ title={footageBlocked || (videoSettings.framePinSaving? 'Saving the frame renderer…'- : (missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame')}+ : (missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame'))}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"><ImageIcon size={15} /> Frames {referenceFrameCount}/{frameScenes.length}</button><buttononClick={sceneMedia.generateMissingVideos}- disabled={videoSettings.saving || footageScenes.length === 0 || missingVideoCount === 0 || !footageFramesReady || generatingVideos || !!videoSettings.videoBlockedReason}- title={videoSettings.videoBlockedReason+ disabled={codeMode || videoSettings.saving || footageScenes.length === 0 || missingVideoCount === 0 || !footageFramesReady || generatingVideos || !!videoSettings.videoBlockedReason}+ title={footageBlocked || videoSettings.videoBlockedReason|| (!footageFramesReady? 'Generate every reference frame first': (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video'))}@@ -138,16 +156,18 @@ export default function ProjectToolbar({<Activity size={15} className="animate-spin" /> {renderJob.pending ? 'Preparing render…' : `${renderJob.progress}% · Cancel`}</button>) : (- <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || sceneCount === 0 || readySceneCount !== sceneCount}+ <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || (codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}title={renderJob.active? 'Wait for the other project render to finish, or return to it to cancel'- : sceneCount === 0- ? 'Add scenes first'- : readySceneCount !== sceneCount- ? (layered- ? `${sceneCount - readySceneCount} scene${sceneCount - readySceneCount === 1 ? ' is' : 's are'} not ready — footage needs a video, a still needs a frame and a span, a card needs a span`- : `Generate videos for all ${sceneCount} scenes first`)- : 'Render the complete music video over the track'}+ : codeMode+ ? (codeReady ? 'Render the code-rendered video over the song. This does not generate footage.' : 'Analyze the song or time a scene before rendering code')+ : sceneCount === 0+ ? 'Add scenes first'+ : readySceneCount !== sceneCount+ ? (layered+ ? `${sceneCount - readySceneCount} scene${sceneCount - readySceneCount === 1 ? ' is' : 's are'} not ready — footage needs a video, a still needs a frame and a span, a card needs a span`+ : `Generate videos for all ${sceneCount} scenes first`)+ : 'Render the complete music video over the track'}className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"><Film size={15} /> {renderJob.active ? 'Rendering another project…' : 'Render final'}</button>diff --git a/client/src/components/musicVideo/TypographyPanel.jsx b/client/src/components/musicVideo/TypographyPanel.jsxindex 716b185961..3d43cdef8b 100644--- a/client/src/components/musicVideo/TypographyPanel.jsx+++ b/client/src/components/musicVideo/TypographyPanel.jsx@@ -1,4 +1,5 @@import { Copy, Plus, Trash2 } from 'lucide-react';+import { compositionDraft, RENDER_STYLES, renderStyleLabel } from './compositionDraft.js';// 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)}`;@@ -11,8 +12,6 @@ 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@@ -22,9 +21,10 @@ const EMPTY = { version: 1, mode: 'concat', textCues: [], style: { color: '#ffff* 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 composition = compositionDraft(project);const cues = composition.textCues || [];const composed = composition.mode === 'composed';+ const codeMode = composition.mode === 'code';const timedLyrics = (project.lyricCues || []).filter((c) => typeof c.startSec === 'number' && typeof c.endSec === 'number');const edit = (patch) => onEditLocal({ composition: { ...composition, ...patch } });@@ -41,16 +41,15 @@ export default function TypographyPanel({ project, onEditLocal, onSave }) {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'}+ Typography — {renderStyleLabel(composition.mode)} · {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>+ <label htmlFor="mv-typo-mode" className="block text-port-text-muted mb-0.5">Render style</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>+ {RENDER_STYLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></div><div>@@ -82,6 +81,7 @@ export default function TypographyPanel({ project, onEditLocal, onSave }) {</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>}+ {codeMode && <p className="mt-2 text-port-text-muted">Code-rendered draws the song in code. Text cues stay stored and come back if you switch to Composed.</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">diff --git a/client/src/components/musicVideo/compositionDraft.js b/client/src/components/musicVideo/compositionDraft.jsnew file mode 100644index 0000000000..209ddad126--- /dev/null+++ b/client/src/components/musicVideo/compositionDraft.js@@ -0,0 +1,22 @@+// The composition manifest the editor round-trips. Mode switches spread the+// stored manifest so scenes, takes, text cues, and generated section functions+// stay put.+export const EMPTY_COMPOSITION = {+ version: 1, mode: 'concat', textCues: [], style: { color: '#ffffff', font: 'sans' }, posterSec: null,+};++export const RENDER_STYLES = [+ ['concat', 'Footage'],+ ['composed', 'Composed'],+ ['code', 'Code-rendered'],+];++export function compositionDraft(project, patch = {}) {+ const current = project?.composition || {};+ const style = { ...EMPTY_COMPOSITION.style, ...(current.style || {}), ...(patch.style || {}) };+ return { ...EMPTY_COMPOSITION, ...current, ...patch, style };+}++export function renderStyleLabel(mode) {+ return RENDER_STYLES.find(([value]) => value === mode)?.[1] || 'Footage';+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 0713c41cf5..b97e387eb7 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -39,7 +39,7 @@ import { useVideoFileSrc } from '../hooks/useVideoFileSrc.js';import MediaPreview from '../components/media/MediaPreview.jsx';import MidiInstallModal from '../components/install/MidiInstallModal.jsx';import MidiGatedModal from '../components/install/MidiGatedModal.jsx';-import { listTracks } from '../services/apiTracks.js';+import { listTracks, trackAudioUrl } from '../services/apiTracks.js';import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';import CreateProjectDrawer from '../components/musicVideo/CreateProjectDrawer.jsx';import AutomationPanel from '../components/musicVideo/AutomationPanel.jsx';@@ -55,6 +55,8 @@ 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 CodeVideoPanel from '../components/musicVideo/CodeVideoPanel.jsx';+import { compositionDraft } from '../components/musicVideo/compositionDraft.js';import VisualSpecPanel from '../components/musicVideo/VisualSpecPanel.jsx';import TreatmentPanel from '../components/musicVideo/TreatmentPanel.jsx';import HandoffControls from '../components/musicVideo/HandoffControls.jsx';@@ -727,6 +729,11 @@ export default function MusicVideo() {<div className="bg-port-card border border-port-border rounded-lg p-3"><ProjectToolbarproject={selected}+ onRenderStyle={(mode) => {+ const composition = compositionDraft(selected, { mode });+ editProjectLocal({ composition });+ saveProjectFields({ composition });+ }}midi={midi}midiBound={midiTargetsSelected}videoSettings={videoSettings}@@ -837,6 +844,13 @@ export default function MusicVideo() {onEditLocal={editProjectLocal}onSave={saveProjectFields}/>+ {selected.composition?.mode === 'code' && (+ <CodeVideoPanel+ project={selected}+ audioUrl={projectAudioFilename(selected) ? trackAudioUrl(projectAudioFilename(selected)) : null}+ onProject={replaceProject}+ />+ )}<AnalysisPanelaudioAnalysis={selected.audioAnalysis}scenes={selected.scenes || []}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 9a983e7162..2a0c9aef11 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -82,6 +82,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({startMusicVideoRevision: vi.fn(),resumeMusicVideoRevision: vi.fn(),cancelMusicVideoRevision: vi.fn(),+ getMusicVideoCodeDocument: vi.fn(async () => ({ html: '<!doctype html><html><body></body></html>', durationSec: 2, fps: 24, width: 1280, height: 720, song: { sections: [] }, timeline: { sections: [] } })),+ generateMusicVideoCode: vi.fn(),+ regenerateMusicVideoCodeSection: vi.fn(),}));vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn(), listUniverseNames: vi.fn(() => Promise.resolve([])) }));vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));@@ -1053,7 +1056,7 @@ describe('MusicVideo typography composition (#8984)', () => {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(document.getElementById('mv-typo-mode'), { 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);diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 0ded93f1e5..5c07472169 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -141,6 +141,14 @@ export const cancelMusicVideoMidiTranscription = (jobId, options = {}) =>// the SSE URL below (subscribe with useSseProgress). cancel stops an in-flight job.export const renderMusicVideoProject = (id, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/render`, { method: 'POST', ...options });+export const getMusicVideoCodeDocument = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/code/document`, options);+export const generateMusicVideoCode = (id, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/code/generate`, { method: 'POST', body: JSON.stringify(body), ...options });+export const regenerateMusicVideoCodeSection = (id, sectionId, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/code/sections/${encodeURIComponent(sectionId)}/regenerate`, {+ method: 'POST', body: JSON.stringify(body), ...options,+ });// EventSource URL for a render job's progress stream (consumed by useSseProgress).export const musicVideoRenderEventsUrl = (jobId) =>diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 3854dad0ec..c4cdd5c2fe 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -225,10 +225,19 @@ export const musicVideoLyricsAlignSchema = z.object({// ---- 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'];+// project with no manifest) is the plain clip concatenation. `code` draws the+// whole song as a seekable composition instead of generated footage. 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', 'code'];+// One section function. Reject the calls that would make a frame depend on+// the clock, entropy, or the network — the preview and the render both seek.+export const MUSIC_VIDEO_CODE_SOURCE_MAX = 20000;+export const MUSIC_VIDEO_CODE_NONDETERMINISTIC = /\bMath\s*\.\s*random\b|\bDate\s*\.\s*now\b|\bperformance\s*\.\s*now\b|\bgetRandomValues\b|\bfetch\s*\(|\bXMLHttpRequest\b|\bWebSocket\b|\bimport\s*\(|\brequire\s*\(/;+export const isDeterministicCodeSource = (source) => typeof source === 'string'+ && source.length > 0+ && source.length <= MUSIC_VIDEO_CODE_SOURCE_MAX+ && !MUSIC_VIDEO_CODE_NONDETERMINISTIC.test(source);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'];@@ -244,6 +253,24 @@ export const musicVideoTextCueSchema = z.object({emphasis: z.enum(MUSIC_VIDEO_TYPOGRAPHY_EMPHASES).optional(),}).strict();+const codeSectionSource = z.string().min(1).max(MUSIC_VIDEO_CODE_SOURCE_MAX)+ .refine(isDeterministicCodeSource, 'section source must be deterministic and offline');++export const musicVideoCodeVideoSchema = z.object({+ providerId: z.string().max(120).nullable().optional(),+ model: z.string().max(200).nullable().optional(),+ generatedAt: z.string().max(40).nullable().optional(),+ sections: z.array(z.object({+ id: z.string().min(1).max(64),+ source: codeSectionSource,+ }).strict()).max(40),+}).strict();++export const musicVideoCodeGenerateSchema = z.object({+ providerId: z.string().max(120).optional(),+ model: z.string().max(200).optional(),+}).strict();+// Replaced whole by a project PATCH (the editor sends the full manifest).export const musicVideoCompositionSchema = z.object({version: z.literal(1).optional(),@@ -254,6 +281,7 @@ export const musicVideoCompositionSchema = z.object({font: z.enum(MUSIC_VIDEO_TYPOGRAPHY_FONTS).optional(),}).strict().optional(),posterSec: timedSec,+ codeVideo: musicVideoCodeVideoSchema.nullable().optional(),}).strict();// Per-scene visual layer (#8985) — footage, a moved still, or a title card;diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 232726e08d..7216d55752 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -610,7 +610,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// wins LWW onto the upgraded peer. Gating makes a v5 receiver reject the// ahead-version transfer until it upgrades. Records without `words` need no// rewrite.- musicVideoProjects: 6,+ // v7 = composition mode `code` (#9076). A v6 peer's normalizeComposition+ // collapses an unknown mode to `concat` and would last-writer-wins that+ // loss back, so the gate rejects the ahead transfer. The older peer is+ // never handed `mode: "code"` (an enum value it cannot store). It keeps+ // the concat/composed project it already understands.+ musicVideoProjects: 7,// 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.jsindex 8d10c8c9bf..54d08a9667 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -32,6 +32,7 @@ import {musicVideoTreatmentApplySchema,musicVideoTreatmentProofReviewSchema,musicVideoExcerptRequestSchema,+ musicVideoCodeGenerateSchema,musicVideoExcerptNoteSchema,musicVideoExcerptNoteUpdateSchema,musicVideoRevisionStartSchema,@@ -76,6 +77,8 @@ import {} from '../services/audioMidiTranscription.js';import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';+import { prepareCodeRender } from '../services/musicVideo/codeRender.js';+import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../services/musicVideo/codeGeneration.js';import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';import {@@ -377,6 +380,28 @@ router.post('/render/:jobId/cancel', (req, res) => {res.json({ ok: cancelRender(req.params.jobId) });});+// Code-rendered style (#9076). Document reads build the page from stored+// section functions and never call a provider. Generate / regenerate are the+// only provider calls, and both require this click.+router.get('/:id/code/document', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ if (project.composition?.mode !== 'code') {+ throw new ServerError('Switch the render style to Code-rendered first', { status: 409, code: 'NOT_CODE_MODE' });+ }+ res.json(prepareCodeRender(project));+}));++router.post('/:id/code/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(musicVideoCodeGenerateSchema, req.body || {});+ res.json(await generateMusicVideoCode(req.params.id, body));+}));++router.post('/:id/code/sections/:sectionId/regenerate', asyncHandler(async (req, res) => {+ const body = validateRequest(musicVideoCodeGenerateSchema, req.body || {});+ res.json(await regenerateMusicVideoCodeSection(req.params.id, req.params.sectionId, body));+}));+// --- Draft excerpt render (#8986) ---// A director-chosen [startSec, endSec) window re-rendered through the same// composed pipeline, plus a cut/cue contact sheet and timecoded review notes.diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.jsindex 3bdc945b7a..76526f7227 100644--- a/server/services/codeAnimation/prompt.js+++ b/server/services/codeAnimation/prompt.js@@ -301,3 +301,63 @@ export function extractAnimationHtml(text) {const end = endMatch ? start + endMatch.index + endMatch[0].length : text.length;return text.slice(start, end).trim();}++const CODE_VIDEO_RULES = `RUNTIME CONTRACT (the host already supplies this — write only the section functions):+- globalThis.portosComposition.seek(t) covers the whole song. The page reads the inlined song.json document (the same JSON written beside index.html). You do not fetch it.+- One function per section id: \`function render(ctx, env) { ... }\`. env is { t, localT, frame, width, height, song, palette, section, safe, karaoke }.+- Use the shared palette (env.palette) and the safe rect (env.safe, 10% inset). Do not draw lyric text — the host paints karaoke after your function, inside the title-safe area, so every active line stays readable.+- Karaoke, enforced by the host: a word may brighten at most 0.4s before its startSec, and the highlight never begins before startSec.+- Determinism: no Math.random, Date.now, performance.now, getRandomValues, fetch, WebSocket, XMLHttpRequest, import, or require. Per-frame jitter must use env.frame (the integer frame index), never continuous env.t, so motion-blur sub-frames stay coherent.+- Canvas 2D only. No external assets, fonts, or network.`;++function promptSong(song) {+ return {+ durationSec: song.durationSec,+ fps: song.fps,+ sections: song.sections,+ lyrics: (song.lyrics || []).slice(0, 400),+ beats: (song.beats || []).slice(0, 400),+ downbeats: (song.downbeats || []).slice(0, 200),+ };+}++/**+ * Music-video variant of the code-animation contract (#9076). Asks for one+ * render function per section (or just `onlySectionId` when regenerating).+ * The host assembles the page; the model does not return a full HTML document.+ */+export function buildMusicVideoCodePrompt({ title = '', palette, song, styleLines = [], onlySectionId = null }) {+ const wanted = (song.sections || []).filter((section) => !onlySectionId || section.id === onlySectionId);+ const brief = wanted.map((section) => `- ${section.id} [${section.startSec}s, ${section.endSec}s) ${section.label || ''}${section.lyric ? ` — lyric: ${section.lyric}` : ' — instrumental'}`).join('\n');+ const scope = onlySectionId+ ? `Return a function for section "${onlySectionId}" only. The host keeps every other section.`+ : 'Return one function for every section id listed.';+ return [+ `You write Canvas 2D section functions for a code-rendered music video${title ? ` titled "${trimTo(title, 200)}"` : ''}. The host seeks them against the song. No footage generation.`,+ CODE_VIDEO_RULES,+ `PALETTE:\n${JSON.stringify(palette)}`,+ styleLines.length ? `STYLE SOURCE:\n${styleLines.join('\n')}` : '',+ `SONG (song.json):\n${JSON.stringify(promptSong(song))}`,+ `SECTIONS:\n${brief}`,+ scope,+ 'OUTPUT: Return ONLY a ```json fence of the form {"sections":[{"id":"...","source":"function render(ctx, env) { ... }"}]}. No HTML document, no explanation.',+ ].filter(Boolean).join('\n\n');+}++/** Pull `{ sections: [{ id, source }] }` out of a model response. `[]` when absent. */+export function extractCodeSections(text) {+ if (!isNonBlankStr(text)) return [];+ const fences = [...text.matchAll(/```(?:json)?[^\n]*\n([\s\S]*?)```/gi)].map((match) => match[1]);+ const candidates = fences.length ? fences : [text];+ for (const candidate of candidates) {+ const start = candidate.indexOf('{');+ const end = candidate.lastIndexOf('}');+ if (start < 0 || end <= start) continue;+ try {+ const parsed = JSON.parse(candidate.slice(start, end + 1));+ if (!Array.isArray(parsed?.sections)) continue;+ return parsed.sections.filter((section) => section && typeof section.id === 'string' && typeof section.source === 'string');+ } catch { /* the next fence may be the document */ }+ }+ return [];+}diff --git a/server/services/musicVideo/codeComposition.js b/server/services/musicVideo/codeComposition.jsnew file mode 100644index 0000000000..4916ab246c--- /dev/null+++ b/server/services/musicVideo/codeComposition.js@@ -0,0 +1,73 @@+/**+ * The HTML page a code-rendered music video seeks (#9076).+ *+ * song.json is written beside index.html for the composition renderer and for+ * a later full-song mux (#9075). The same document is inlined: seek() has to+ * be ready at load, and the preview sandbox cannot fetch. Section code runs+ * after fetch/WebSocket are disabled.+ */++import { codeRuntimeSource } from './codeFrame.js';++const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');++/**+ * @param {object} input+ * @param {object} input.song song.json document+ * @param {object} input.palette+ * @param {Record<string, string>} input.sources section id → render function source+ * @param {number} [input.windowStart] song time the page's t=0 corresponds to+ * @param {number} [input.windowDuration] page duration; defaults to the song+ */+export function buildCodeDocument({ song, palette, sources, width, height, fps, windowStart = 0, windowDuration = null }) {+ const durationSec = windowDuration == null ? song.durationSec : windowDuration;+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>+html, body { margin: 0; background: #000; overflow: hidden; }+canvas { display: block; width: 100vw; height: 100vh; object-fit: contain; background: #000; }+</style></head><body><canvas id="portos-code" width="${width}" height="${height}"></canvas><script>+${codeRuntimeSource()}+const SONG = ${scriptJson(song)};+const PALETTE = ${scriptJson(palette)};+const SOURCES = ${scriptJson(sources || {})};+const WINDOW_START = ${Number(windowStart) || 0};+function disableNetwork() {+ const block = (name) => function blocked() { throw new Error(name + ' is disabled in a code-rendered video'); };+ for (const key of ['fetch', 'WebSocket', 'XMLHttpRequest', 'EventSource']) {+ try { Object.defineProperty(globalThis, key, { configurable: true, value: block(key) }); } catch { /* already sealed */ }+ }+}+disableNetwork();+const canvas = document.getElementById('portos-code');+const ctx = canvas.getContext('2d');+globalThis.portosComposition = {+ durationSec: ${durationSec},+ fps: ${fps},+ width: ${width},+ height: ${height},+ song: SONG,+ seek(t) {+ const time = WINDOW_START + (Number(t) || 0);+ drawCodeFrame({ ctx, song: SONG, palette: PALETTE, sources: SOURCES, t: time, width: ${width}, height: ${height}, fps: ${fps} });+ }+};+addEventListener('message', (event) => {+ const data = event.data;+ if (!data || data.type !== 'mv-code:seek' || !Number.isFinite(data.t)) return;+ globalThis.portosComposition.seek(data.t);+});+globalThis.portosComposition.seek(0);+try { parent.postMessage({ type: 'mv-code:ready', durationSec: ${durationSec} }, '*'); } catch { /* opened as a file */ }+</script></body></html>`;+ return { html, song, durationSec, fps, width, height, windowStart: Number(windowStart) || 0 };+}++/** The inlined song.json document, for tests that the page and the file match. */+export function embeddedSong(html) {+ const marker = 'const SONG = ';+ const start = html.indexOf(marker);+ if (start < 0) return null;+ const jsonStart = start + marker.length;+ const end = html.indexOf(';\n', jsonStart);+ if (end < 0) return null;+ return JSON.parse(html.slice(jsonStart, end));+}diff --git a/server/services/musicVideo/codeFrame.js b/server/services/musicVideo/codeFrame.jsnew file mode 100644index 0000000000..afd445a73c--- /dev/null+++ b/server/services/musicVideo/codeFrame.js@@ -0,0 +1,233 @@+/**+ * Seekable frame contract for a code-rendered music video (#9076).+ *+ * `drawCodeFrame` is the host painter: one section function, then karaoke.+ * Its source is embedded in the preview and render page, so it must not close+ * over module state — every input arrives on the argument, and the helpers it+ * calls are emitted beside it. Seeking the same `t` twice paints the same+ * pixels. Jitter, when a section uses it, is keyed to `env.frame`.+ */++export const CODE_FPS = 24;+export const CODE_SAFE_INSET = 0.1;+export const CODE_EARLY_DIM_SEC = 0.4;++const FONT_STACKS = { sans: 'sans-serif', serif: 'serif', mono: 'monospace' };++/** How one lyric word looks at time `t`. The highlight never starts early. */+export function wordAppearance(word, t) {+ const start = word.startSec;+ const end = typeof word.endSec === 'number' && word.endSec > start ? word.endSec : start + 0.35;+ const dimAt = Math.max(0, start - CODE_EARLY_DIM_SEC);+ if (!(t >= dimAt)) return { opacity: 0, highlight: false };+ if (t < start) return { opacity: 0.45, highlight: false };+ if (t < end) return { opacity: 1, highlight: true };+ return { opacity: 0.72, highlight: false };+}++function lineEnd(line) {+ const words = line.words || [];+ const last = words[words.length - 1];+ if (last && typeof last.endSec === 'number' && last.endSec > (last.startSec ?? 0)) return last.endSec;+ if (typeof line.endSec === 'number' && line.endSec > (line.startSec ?? 0)) return line.endSec;+ return (line.startSec ?? 0) + 0.5;+}++/** A line is on screen from 0.4s before its first word through its end. */+export function lineActive(line, t) {+ const start = line.words?.[0]?.startSec ?? line.startSec ?? 0;+ return t >= start - CODE_EARLY_DIM_SEC && t < lineEnd(line);+}++/**+ * Paint one frame. `sources` maps a section id to `function render(ctx, env)`.+ * A missing or throwing section still leaves the palette and the lyric line.+ */+export function drawCodeFrame({ ctx, song, palette, sources, t, width, height, fps }) {+ const duration = song.durationSec;+ const time = Math.min(Math.max(0, t), Math.max(0, duration));+ const frame = Math.max(0, Math.floor(time * fps + 1e-9));+ const sections = song.sections || [];+ let section = sections[sections.length - 1] || { id: 'song', startSec: 0, endSec: duration, label: 'Song' };+ for (const candidate of sections) {+ if (time >= candidate.startSec && time < candidate.endSec) { section = candidate; break; }+ }+ const inset = CODE_SAFE_INSET;+ const safe = { x: width * inset, y: height * inset, w: width * (1 - 2 * inset), h: height * (1 - 2 * inset) };+ ctx.globalAlpha = 1;+ ctx.fillStyle = palette.background;+ ctx.fillRect(0, 0, width, height);+ const localT = time - (section.startSec || 0);+ const karaoke = (song.lyrics || []).filter((line) => lineActive(line, time)).map((line) => ({+ ...line,+ words: (line.words || []).map((word) => {+ const appearance = wordAppearance(word, time);+ // The line is already on screen, so every word stays readable. Only the+ // highlight is withheld until startSec, and the brighter anticipation+ // is the 0.4s wordAppearance window.+ return { ...word, ...appearance, opacity: appearance.opacity > 0 ? appearance.opacity : 0.4 };+ }),+ }));+ const env = { t: time, localT, frame, width, height, song, palette, section, safe, karaoke };+ const source = sources && sources[section.id];+ if (typeof source === 'string' && source) {+ const body = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;+ const restore = lockClock();+ try {+ if (!drawCodeFrame.compiled) drawCodeFrame.compiled = new Map();+ let fn = drawCodeFrame.compiled.get(body);+ if (!fn) {+ fn = new Function('ctx', 'env', `${body}\nreturn typeof render === 'function' ? render(ctx, env) : undefined;`);+ drawCodeFrame.compiled.set(body, fn);+ }+ fn(ctx, env);+ } catch { /* the host lyric pass below still runs */ } finally { restore(); }+ } else {+ ctx.fillStyle = palette.accent;+ const band = 8 + (frame % 4);+ ctx.fillRect(safe.x, safe.y, band, band);+ }+ paintKaraoke(ctx, { palette, safe, karaoke });+ return { frame, sectionId: section.id };+}++function lockClock() {+ const math = Math.random;+ const now = Date.now;+ const perfObj = globalThis.performance;+ const perfNow = perfObj ? perfObj.now : undefined;+ Math.random = () => { throw new Error('Math.random is disabled'); };+ Date.now = () => { throw new Error('Date.now is disabled'); };+ if (perfObj) perfObj.now = () => { throw new Error('performance.now is disabled'); };+ return () => {+ Math.random = math;+ Date.now = now;+ if (perfObj) perfObj.now = perfNow;+ };+}++function paintKaraoke(ctx, { palette, safe, karaoke }) {+ if (!karaoke.length) return;+ const stack = FONT_STACKS[palette.font] || FONT_STACKS.sans;+ const lines = karaoke.slice(-3);+ let cursor = safe.y + safe.h;+ for (let i = lines.length - 1; i >= 0; i -= 1) {+ const line = lines[i];+ const text = (line.words || []).map((word) => word.text).join(' ');+ if (!text) continue;+ let size = Math.max(12, Math.min(64, Math.floor(safe.h * 0.09)));+ ctx.textAlign = 'left';+ ctx.textBaseline = 'alphabetic';+ while (size > 8) {+ ctx.font = `${size}px ${stack}`;+ if (ctx.measureText(text).width <= safe.w) break;+ size -= 1;+ }+ cursor -= size + 4;+ if (cursor < safe.y) break;+ let x = safe.x;+ for (const word of line.words || []) {+ if (!(word.opacity > 0)) continue;+ const token = `${word.text} `;+ const advance = ctx.measureText(token).width;+ if (x + advance > safe.x + safe.w + 0.5) break;+ ctx.globalAlpha = word.opacity;+ ctx.fillStyle = word.highlight ? palette.accent : palette.ink;+ ctx.fillText(word.text, x, cursor + size);+ x += advance;+ }+ ctx.globalAlpha = 1;+ }+}++/** A section body the tests and the fallback provider share. Color is literal. */+export function fixtureSectionSource(color) {+ const ink = JSON.stringify(color);+ return `function render(ctx, env) {\n ctx.fillStyle = ${ink};\n ctx.fillRect(env.safe.x, env.safe.y, 12 + (env.frame % 3), 12);\n}`;+}++function parseHex(style) {+ const match = /^#([0-9a-f]{6})$/i.exec(String(style || ''));+ if (!match) return [0, 0, 0];+ const n = parseInt(match[1], 16);+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];+}++/** Canvas stand-in so a seek can be compared without a browser. */+export function createSoftwareCanvas(width, height) {+ const data = new Uint8ClampedArray(width * height * 4);+ const stack = [];+ const state = { fillStyle: '#000000', globalAlpha: 1, font: '16px sans-serif', textAlign: 'left', textBaseline: 'alphabetic' };+ const textOps = [];+ const paint = (x0, y0, w, h) => {+ const [r, g, b] = parseHex(state.fillStyle);+ const alpha = state.globalAlpha;+ const x1 = Math.max(0, Math.floor(x0));+ const y1 = Math.max(0, Math.floor(y0));+ const x2 = Math.min(width, Math.ceil(x0 + w));+ const y2 = Math.min(height, Math.ceil(y0 + h));+ for (let y = y1; y < y2; y += 1) {+ for (let x = x1; x < x2; x += 1) {+ const i = (y * width + x) * 4;+ data[i] = Math.round(data[i] * (1 - alpha) + r * alpha);+ data[i + 1] = Math.round(data[i + 1] * (1 - alpha) + g * alpha);+ data[i + 2] = Math.round(data[i + 2] * (1 - alpha) + b * alpha);+ data[i + 3] = 255;+ }+ }+ };+ return {+ data,+ textOps,+ get fillStyle() { return state.fillStyle; },+ set fillStyle(value) { state.fillStyle = value; },+ get globalAlpha() { return state.globalAlpha; },+ set globalAlpha(value) { state.globalAlpha = value; },+ get font() { return state.font; },+ set font(value) { state.font = value; },+ get textAlign() { return state.textAlign; },+ set textAlign(value) { state.textAlign = value; },+ get textBaseline() { return state.textBaseline; },+ set textBaseline(value) { state.textBaseline = value; },+ save() { stack.push({ ...state }); },+ restore() { Object.assign(state, stack.pop() || {}); },+ measureText(text) {+ const size = Number(/(\d+(?:\.\d+)?)px/.exec(state.font)?.[1] || 16);+ return { width: String(text).length * size * 0.55 };+ },+ fillRect: paint,+ fillText(text, x, y) {+ textOps.push({ text: String(text), x, y, font: state.font });+ const size = Number(/(\d+(?:\.\d+)?)px/.exec(state.font)?.[1] || 16);+ paint(x, y - size, Math.max(1, String(text).length * 2), Math.max(1, size * 0.7));+ },+ };+}++/** Paint `t` and return the pixel buffer plus the lyric placements. */+export function sampleFrame({ song, palette, sources, t, width, height, fps = CODE_FPS }) {+ const ctx = createSoftwareCanvas(width, height);+ const meta = drawCodeFrame({ ctx, song, palette, sources, t, width, height, fps });+ return { data: ctx.data, textOps: ctx.textOps, ...meta, width, height };+}++/** Source emitted into the preview and render page. Same functions as this module. */+export function codeRuntimeSource() {+ return [+ `const CODE_SAFE_INSET = ${CODE_SAFE_INSET};`,+ `const CODE_EARLY_DIM_SEC = ${CODE_EARLY_DIM_SEC};`,+ `const FONT_STACKS = ${JSON.stringify(FONT_STACKS)};`,+ wordAppearance,+ lineEnd,+ lineActive,+ lockClock,+ paintKaraoke,+ drawCodeFrame,+ ].map((part) => (typeof part === 'function' ? part.toString() : part)).join('\n');+}++export function samePixels(a, b) {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;+ return true;+}diff --git a/server/services/musicVideo/codeFrame.test.js b/server/services/musicVideo/codeFrame.test.jsnew file mode 100644index 0000000000..b7d395305b--- /dev/null+++ b/server/services/musicVideo/codeFrame.test.js@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest';+import { buildCodeDocument, embeddedSong } from './codeComposition.js';+import { CODE_EARLY_DIM_SEC, fixtureSectionSource, lineActive, sampleFrame, samePixels, wordAppearance } from './codeFrame.js';+import { buildSongDocument, paletteFromProject } from './codeTimeline.js';++const project = {+ audioAnalysis: {+ durationSec: 2,+ beats: [0, 0.5, 1, 1.5],+ downbeats: [0, 1],+ sections: [+ { id: 'a', label: 'A', startSec: 0, endSec: 1 },+ { id: 'b', label: 'B', startSec: 1, endSec: 2 },+ ],+ },+ lyricCues: [{ id: 'line', text: 'hello </script>', startSec: 0.2, endSec: 1.6, words: [+ { text: 'hello', startSec: 0.2, endSec: 0.6 },+ { text: 'there', startSec: 0.8, endSec: 1.4 },+ ] }],+ visualSpec: { palette: ['#101010', '#f0f0f0', '#ff8800'] },+ composition: { style: { font: 'sans' } },+};++function frameAt(sources, t) {+ const song = buildSongDocument(project);+ return sampleFrame({+ song, palette: paletteFromProject(project), sources, t, width: 320, height: 180, fps: song.fps,+ });+}++describe('code frame contract (#9076)', () => {+ it('seeks the same t twice to identical pixels, including inside one frame', () => {+ const sources = { a: fixtureSectionSource('#2244aa'), b: fixtureSectionSource('#aa4422') };+ const first = frameAt(sources, 0.5);+ const second = frameAt(sources, 0.5);+ expect(samePixels(first.data, second.data)).toBe(true);+ const later = frameAt(sources, 0.5 + 0.01);+ expect(later.frame).toBe(first.frame);+ expect(samePixels(first.data, later.data)).toBe(true);+ });++ it('regenerating one section leaves the other section pixels unchanged', () => {+ const before = { a: fixtureSectionSource('#2244aa'), b: fixtureSectionSource('#aa4422') };+ const after = { ...before, a: fixtureSectionSource('#00ff00') };+ expect(samePixels(frameAt(before, 1.25).data, frameAt(after, 1.25).data)).toBe(true);+ expect(samePixels(frameAt(before, 0.3).data, frameAt(after, 0.3).data)).toBe(false);+ });++ it('highlights a word only at its start and keeps the line inside the safe area', () => {+ const word = { text: 'hello', startSec: 0.2, endSec: 0.6 };+ expect(wordAppearance(word, 0.2 - CODE_EARLY_DIM_SEC - 0.05).opacity).toBe(0);+ expect(wordAppearance(word, 0.2 - 0.01).highlight).toBe(false);+ expect(wordAppearance(word, 0.2).highlight).toBe(true);+ const song = buildSongDocument(project);+ const line = song.lyrics[0];+ expect(lineActive(line, 0.5)).toBe(true);+ const painted = frameAt({ a: fixtureSectionSource('#2244aa'), b: fixtureSectionSource('#aa4422') }, 0.5);+ expect(painted.textOps.map((op) => op.text)).toEqual(expect.arrayContaining(['hello', 'there']));+ const safe = { x: 320 * 0.1, y: 180 * 0.1, w: 320 * 0.8, h: 180 * 0.8 };+ for (const op of painted.textOps) {+ expect(op.x).toBeGreaterThanOrEqual(safe.x - 0.5);+ expect(op.x).toBeLessThanOrEqual(safe.x + safe.w + 0.5);+ expect(op.y).toBeLessThanOrEqual(safe.y + safe.h + 0.5);+ }+ const there = painted.textOps.find((op) => op.text === 'there');+ expect(there).toBeTruthy();+ });++ it('inlines song.json and escapes a lyric that could close the script', () => {+ const song = buildSongDocument(project);+ const doc = buildCodeDocument({+ song, palette: paletteFromProject(project), sources: {}, width: 320, height: 180, fps: 24,+ });+ expect(embeddedSong(doc.html)).toEqual(song);+ expect(doc.html).toContain('\\u003c/script>');+ expect(doc.html.split('</script>')).toHaveLength(2);+ expect(doc.html).toContain('portosComposition');+ expect(doc.html).toContain('mv-code:seek');+ });+});diff --git a/server/services/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.jsnew file mode 100644index 0000000000..eb92b88477--- /dev/null+++ b/server/services/musicVideo/codeGeneration.js@@ -0,0 +1,139 @@+/**+ * User-triggered code-video generation (#9076).+ *+ * Nothing here runs from boot or from a project read. Both entry points are+ * the Generate / Regenerate clicks: they resolve a provider, show it in the+ * log line, and store section functions. The render path never calls them+ * and never asks a footage model for pixels.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/paths.js';+import { isDeterministicCodeSource } from '../../lib/musicVideoValidation.js';+import { universeStyleLines } from '../../lib/styleSourcePrompt.js';+import { buildMusicVideoCodePrompt, extractCodeSections } from '../codeAnimation/prompt.js';+import { normalizeComposition } from './composition.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { buildCodeTimeline, buildSongDocument, paletteFromProject } from './codeTimeline.js';++async function styleLinesFor(project) {+ const universeId = project.concept?.universeId;+ if (!universeId) return [];+ try {+ const { resolveUniverseStyleSource } = await import('../creativeStyleSources.js');+ const universe = await resolveUniverseStyleSource(universeId, { imageSlots: 0 });+ return universe ? universeStyleLines(universe) : [];+ } catch (err) {+ console.warn(`⚠️ Music-video code style source skipped: ${err.message}`);+ return [];+ }+}++function acceptSources(parsed, ids) {+ const wanted = new Set(ids);+ const accepted = [];+ for (const section of parsed) {+ if (!wanted.has(section.id)) continue;+ if (!isDeterministicCodeSource(section.source)) {+ throw new ServerError(`Section ${section.id} used a non-deterministic or networked call`, { status: 422, code: 'NONDETERMINISTIC_SECTION' });+ }+ accepted.push({ id: section.id, source: section.source });+ }+ return accepted;+}++async function runModel({ providerId, model, prompt }) {+ const { assertProvider, resolveProviderAndModel, runPromptThroughProvider } = await import('../promptRunner.js');+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, { message: 'No AI provider available to write the code video', code: 'PROVIDER_UNAVAILABLE', status: 400 });+ console.log(`🎬 Music-video code generation on ${provider.id}/${selectedModel || 'default'}`);+ const { text } = await runPromptThroughProvider({+ provider,+ model: selectedModel || undefined,+ prompt,+ source: 'music-video-code',+ cwd: PATHS.data,+ });+ return { text, providerId: provider.id, model: selectedModel || null };+}++function storeCodeVideo(project, { providerId, model, sections, timelineIds }) {+ const allowed = new Set(timelineIds);+ const previous = (project.composition?.codeVideo?.sections || []).filter((section) => allowed.has(section.id));+ const merged = new Map(previous.map((section) => [section.id, section.source]));+ for (const section of sections) merged.set(section.id, section.source);+ const codeVideo = {+ providerId,+ model,+ generatedAt: new Date().toISOString(),+ sections: [...merged.entries()].map(([id, source]) => ({ id, source })),+ };+ return normalizeComposition({ ...(project.composition || {}), mode: 'code', codeVideo });+}++async function writeComposition(projectId, run, sections, timelineIds) {+ const { project } = await mutateProjectRecord(projectId, (current) => ({+ project: {+ ...current,+ composition: storeCodeVideo(current, { providerId: run.providerId, model: run.model, sections, timelineIds }),+ updatedAt: new Date().toISOString(),+ },+ }));+ return project;+}++/**+ * Generate every section. Replaces stored functions for the sections the+ * model returned; a section it omitted keeps its previous function.+ */+export async function generateMusicVideoCode(projectId, { providerId, model } = {}) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const timeline = buildCodeTimeline(project);+ if (!timeline.sections.length) {+ throw new ServerError('Code-rendered video needs a song duration — analyze the track or time a scene or lyric line', { status: 422, code: 'NO_TIMELINE' });+ }+ const song = buildSongDocument(project, timeline);+ const palette = paletteFromProject(project);+ const prompt = buildMusicVideoCodePrompt({+ title: project.name,+ palette,+ song,+ styleLines: await styleLinesFor(project),+ });+ const run = await runModel({ providerId, model, prompt });+ const parsed = extractCodeSections(run.text);+ const sections = acceptSources(parsed, timeline.sections.map((section) => section.id));+ if (!sections.length) {+ throw new ServerError('The model did not return a section function', { status: 422, code: 'NO_SECTION_SOURCE' });+ }+ const updated = await writeComposition(projectId, run, sections, timeline.sections.map((section) => section.id));+ console.log(`✅ Music-video code stored sections=${sections.length}`);+ return { project: updated, providerId: run.providerId, model: run.model };+}++/** Replace one section function. Every other stored function stays. */+export async function regenerateMusicVideoCodeSection(projectId, sectionId, { providerId, model } = {}) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const timeline = buildCodeTimeline(project);+ if (!timeline.sections.some((section) => section.id === sectionId)) {+ throw new ServerError('That section is not on the code timeline', { status: 404, code: 'SECTION_NOT_FOUND' });+ }+ const song = buildSongDocument(project, timeline);+ const prompt = buildMusicVideoCodePrompt({+ title: project.name,+ palette: paletteFromProject(project),+ song,+ styleLines: await styleLinesFor(project),+ onlySectionId: sectionId,+ });+ const run = await runModel({ providerId, model, prompt });+ const sections = acceptSources(extractCodeSections(run.text), [sectionId]);+ if (!sections.length) {+ throw new ServerError('The model did not return that section', { status: 422, code: 'NO_SECTION_SOURCE' });+ }+ const updated = await writeComposition(projectId, run, sections, timeline.sections.map((section) => section.id));+ console.log(`✅ Music-video code replaced section=${sectionId}`);+ return { project: updated, providerId: run.providerId, model: run.model, sectionId };+}diff --git a/server/services/musicVideo/codeGeneration.test.js b/server/services/musicVideo/codeGeneration.test.jsnew file mode 100644index 0000000000..052bb9f78b--- /dev/null+++ b/server/services/musicVideo/codeGeneration.test.js@@ -0,0 +1,95 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fixtureSectionSource } from './codeFrame.js';++const h = vi.hoisted(() => ({ project: null, calls: 0, response: '' }));++vi.mock('../promptRunner.js', () => ({+ assertProvider: () => {},+ resolveProviderAndModel: vi.fn(async ({ providerId, model }) => ({+ provider: { id: providerId || 'stub-provider' },+ selectedModel: model || 'fixture-model',+ })),+ runPromptThroughProvider: vi.fn(async () => {+ h.calls += 1;+ return { text: h.response };+ }),+}));++vi.mock('./projects.js', () => ({+ getProject: vi.fn(async () => h.project),+ mutateProjectRecord: vi.fn(async (_id, transform) => transform(h.project)),+}));++const { generateMusicVideoCode, regenerateMusicVideoCodeSection } = await import('./codeGeneration.js');+const { buildMusicVideoCodePrompt } = await import('../codeAnimation/prompt.js');++const base = () => ({+ id: 'mv-code',+ name: 'Click track',+ concept: { universeId: null },+ audioAnalysis: {+ durationSec: 2,+ beats: [0, 0.5, 1, 1.5],+ downbeats: [0, 1],+ sections: [+ { id: 'a', label: 'Verse', startSec: 0, endSec: 1 },+ { id: 'b', label: 'Chorus', startSec: 1, endSec: 2 },+ ],+ },+ lyricCues: [{ id: 'l1', text: 'hello', startSec: 0.2, endSec: 0.8 }],+ scenes: [{ sceneId: 's1', startSec: 0, endSec: 2 }],+ composition: {+ mode: 'code',+ textCues: [{ id: 'c1', text: 'kept', startSec: 0, endSec: 1 }],+ codeVideo: { sections: [+ { id: 'a', source: fixtureSectionSource('#111111') },+ { id: 'b', source: fixtureSectionSource('#222222') },+ ] },+ },+});++beforeEach(() => {+ h.project = base();+ h.calls = 0;+ h.response = '';+});++describe('music video code generation (#9076)', () => {+ it('does not call a provider until generate runs, and names the model it used', async () => {+ expect(h.calls).toBe(0);+ const prompt = buildMusicVideoCodePrompt({+ title: 'Click',+ palette: { background: '#111111', ink: '#ffffff', accent: '#ffaa00', font: 'sans' },+ song: { durationSec: 2, fps: 24, sections: [{ id: 'a', label: 'Verse', startSec: 0, endSec: 2, lyric: 'hello' }], lyrics: [], beats: [0], downbeats: [0] },+ });+ expect(prompt).toContain('song.json');+ expect(prompt).toContain('0.4');+ expect(prompt).toContain('env.frame');+ expect(prompt).toContain('startSec');+ expect(h.calls).toBe(0);++ h.response = JSON.stringify({ sections: [+ { id: 'a', source: fixtureSectionSource('#333333') },+ { id: 'b', source: fixtureSectionSource('#444444') },+ ] });+ const result = await generateMusicVideoCode('mv-code', { providerId: 'stub-provider', model: 'fixture-model' });+ expect(h.calls).toBe(1);+ expect(result.providerId).toBe('stub-provider');+ expect(result.model).toBe('fixture-model');+ expect(result.project.composition.textCues.map((cue) => cue.text)).toEqual(['kept']);+ expect(result.project.scenes).toEqual(base().scenes);+ });++ it('regenerating one section keeps the other section source', async () => {+ const next = fixtureSectionSource('#00ff00');+ h.response = JSON.stringify({ sections: [+ { id: 'a', source: next },+ { id: 'b', source: fixtureSectionSource('#ffffff') },+ ] });+ const result = await regenerateMusicVideoCodeSection('mv-code', 'a', { providerId: 'stub-provider', model: 'fixture-model' });+ const stored = Object.fromEntries(result.project.composition.codeVideo.sections.map((section) => [section.id, section.source]));+ expect(stored.a).toBe(next);+ expect(stored.b).toBe(fixtureSectionSource('#222222'));+ expect(h.calls).toBe(1);+ });+});diff --git a/server/services/musicVideo/codeRender.js b/server/services/musicVideo/codeRender.jsnew file mode 100644index 0000000000..deadc7212e--- /dev/null+++ b/server/services/musicVideo/codeRender.js@@ -0,0 +1,120 @@+/**+ * Frame-accurate encode of a code-rendered music video (#9076).+ *+ * The page seeks in the composition browser — the same path as an HTML+ * composition — then the master song is muxed for the exact frame count with+ * no tail fade and no footage model. song.json is written next to index.html+ * and inlined into the page (the preview sandbox cannot fetch).+ */++import { rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, PATHS } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { buildCodeDocument } from './codeComposition.js';+import { buildCodeTimeline, buildSongDocument, codeFrameSize, paletteFromProject, quantizeSongDuration } from './codeTimeline.js';++// The composition browser and ffmpeg mux are loaded only when a render runs,+// so unit tests of the footage renderer can keep a partial ffmpeg mock.+const AAC_MUX_ARGS = Object.freeze(['-c:a', 'aac', '-b:a', '192k']);++export function muxExactArgs(videoPath, audioPath, outputPath, durationSec, audioStartSec = 0) {+ const args = ['-hide_banner', '-loglevel', 'error', '-i', videoPath];+ if (audioStartSec > 0) args.push('-ss', String(audioStartSec));+ args.push(+ '-i', audioPath,+ '-map', '0:v:0', '-map', '1:a:0',+ '-t', String(durationSec),+ '-c:v', 'copy',+ '-af', `atrim=duration=${durationSec},apad=whole_dur=${durationSec},asetpts=PTS-STARTPTS`,+ ...AAC_MUX_ARGS,+ '-movflags', '+faststart',+ '-y', outputPath,+ );+ return args;+}++/**+ * The document, song, and frame size for a full song or an excerpt window.+ * No provider call and no footage. Throws NO_TIMELINE / INVALID_EXCERPT_RANGE.+ */+export function prepareCodeRender(project, { windowStart = null, windowEnd = null } = {}) {+ const timeline = buildCodeTimeline(project);+ if (!(timeline.durationSec > 0) || timeline.sections.length === 0) {+ throw new ServerError('Code-rendered video needs a song duration — analyze the track or time a scene or lyric line', { status: 422, code: 'NO_TIMELINE' });+ }+ const song = buildSongDocument(project, timeline);+ const palette = paletteFromProject(project);+ const sources = Object.fromEntries((project.composition?.codeVideo?.sections || [])+ .filter((section) => section && typeof section.id === 'string' && typeof section.source === 'string')+ .map((section) => [section.id, section.source]));+ const size = codeFrameSize(project.treatment?.brief?.aspectRatio);+ let start = 0;+ let durationSec = song.durationSec;+ if (windowStart != null || windowEnd != null) {+ if (!(windowStart >= 0) || !(windowEnd > windowStart) || windowStart >= song.durationSec - 1e-6) {+ throw new ServerError('The excerpt range must fall within the song', {+ status: 422, code: 'INVALID_EXCERPT_RANGE', context: { totalDuration: song.durationSec },+ });+ }+ const span = Math.min(windowEnd, song.durationSec) - windowStart;+ start = windowStart;+ durationSec = quantizeSongDuration(span, song.fps).durationSec;+ }+ const doc = buildCodeDocument({+ song, palette, sources, ...size, fps: song.fps, windowStart: start, windowDuration: durationSec,+ });+ const sectionTimes = song.sections+ .map((section) => section.startSec - start)+ .filter((time) => time >= -1e-6 && time < durationSec - 1e-3)+ .map((time) => Math.max(0, Math.round(time * 1000) / 1000));+ return { ...doc, timeline, palette, sectionTimes, footageGeneration: false };+}++export async function encodeCodeComposition({+ html, song, width, height, fps, durationSec, audioPath, outputPath, directory, signal, onProgress, audioStartSec = 0,+}) {+ const { findFfmpeg, runFfmpegProcess } = await import('../../lib/ffmpeg.js');+ const { openComposition } = await import('../htmlComposition/browser.js');+ const { encodeComposition } = await import('../htmlComposition/encode.js');+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });+ const root = join(PATHS.data, directory);+ await ensureDir(root);+ await writeFile(join(root, 'index.html'), html);+ await writeFile(join(root, 'song.json'), JSON.stringify(song));+ const silent = `${outputPath}.silent.mp4`;+ let page;+ try {+ page = await openComposition(directory, { signal });+ await encodeComposition(page, { durationSec, fps, width, height }, silent, {+ signal, onProgress: (fraction) => onProgress?.(fraction * 0.9),+ });+ signal?.throwIfAborted();+ const mux = await runFfmpegProcess({+ bin: ffmpeg, signal, args: muxExactArgs(silent, audioPath, outputPath, durationSec, audioStartSec),+ });+ if (!mux.ok) {+ if (signal?.aborted || /cancelled/.test(mux.reason || '')) {+ const canceled = new Error('Render cancelled');+ canceled.code = 'CANCELED';+ throw canceled;+ }+ throw new Error(mux.reason || 'audio mux failed');+ }+ onProgress?.(1);+ } finally {+ if (page) await page.close().catch(() => {});+ await rm(root, { recursive: true, force: true }).catch(() => {});+ await rm(silent, { force: true }).catch(() => {});+ }+}++/** Contact sheet at section boundaries. A failure is the caller's to soften. */+export async function writeCodeProofSheet(videoPath, sheetPath, times, geometry) {+ const usable = (Array.isArray(times) ? times : []).filter((time) => time >= 0);+ if (!usable.length) return null;+ const { encodeFileContactSheetAtTimes } = await import('../htmlComposition/encode.js');+ await encodeFileContactSheetAtTimes(videoPath, sheetPath, usable, geometry);+ return sheetPath;+}diff --git a/server/services/musicVideo/codeRender.test.js b/server/services/musicVideo/codeRender.test.jsnew file mode 100644index 0000000000..da8ee97ae3--- /dev/null+++ b/server/services/musicVideo/codeRender.test.js@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';+import { prepareCodeRender, muxExactArgs } from './codeRender.js';++const ffmpeg = await findFfmpeg();++const project = {+ composition: { mode: 'code', textCues: [{ id: 'c', text: 'kept', startSec: 0, endSec: 1 }] },+ scenes: [{ sceneId: 's1', startSec: 0, endSec: 2, takes: [{ id: 't1' }] }],+ audioAnalysis: {+ durationSec: 2,+ beats: [0, 0.5, 1, 1.5],+ downbeats: [0, 1],+ sections: [{ id: 'a', label: 'All', startSec: 0, endSec: 2 }],+ },+ lyricCues: [{ id: 'l', text: 'la', startSec: 0.5, endSec: 1 }],+};++describe('code render plan (#9076)', () => {+ it('plans a code render without footage generation', () => {+ const plan = prepareCodeRender(project);+ expect(plan.footageGeneration).toBe(false);+ expect(plan.durationSec).toBeGreaterThanOrEqual(2 - 1e-9);+ expect(plan.durationSec - 2).toBeLessThan(1 / 24 + 1e-9);+ expect(plan.html).toContain('portosComposition');+ expect(plan.song.lyrics[0].text).toBe('la');+ });+});++describe.skipIf(!ffmpeg)('code render mux (#9076)', () => {+ it('muxes the song so the file covers it within one frame and does not fade', async () => {+ const plan = prepareCodeRender({ ...project, audioAnalysis: { ...project.audioAnalysis, durationSec: 2.01, sections: [{ id: 'a', label: 'All', startSec: 0, endSec: 2.01 }] } });+ const dir = await mkdtemp(join(tmpdir(), 'portos-code-mux-'));+ try {+ const silent = join(dir, 'silent.mp4');+ const wav = join(dir, 'click.wav');+ const out = join(dir, 'out.mp4');+ const made = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', `color=c=black:s=32x18:r=24:d=${plan.durationSec}`, '-frames:v', String(plan.song.frames), '-y', silent],+ });+ expect(made.ok).toBe(true);+ const rate = 24000;+ const samples = new Float32Array(Math.ceil(rate * 2.01));+ for (let i = 0; i < samples.length; i += rate / 2) samples[i] = 0.8;+ await writeFile(wav, pcmToWavBuffer(samples, { sampleRate: rate }));+ const muxed = await runFfmpegProcess({+ bin: ffmpeg,+ args: muxExactArgs(silent, wav, out, plan.durationSec, 0),+ });+ expect(muxed.ok).toBe(true);+ const duration = await probeVideoDuration(out);+ expect(Math.abs(duration - plan.durationSec)).toBeLessThan(1 / 24 + 0.02);+ expect(duration).toBeGreaterThanOrEqual(2.01 - 1 / 24);+ const args = muxExactArgs(silent, wav, out, plan.durationSec, 0).join(' ');+ expect(args).not.toContain('afade');+ expect(await readFile(out)).toBeInstanceOf(Buffer);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });+});diff --git a/server/services/musicVideo/codeTimeline.js b/server/services/musicVideo/codeTimeline.jsnew file mode 100644index 0000000000..c4d49b0141--- /dev/null+++ b/server/services/musicVideo/codeTimeline.js@@ -0,0 +1,242 @@+/**+ * Section windows for a code-rendered music video (#9076).+ *+ * The windows come from the treatment arc, otherwise the analyzed sections,+ * otherwise the scenes, otherwise one window for the whole song. The picture+ * starts at song time 0 — the same timebase as a footage render. Each later+ * boundary snaps to the beat at or before the first word of that section's+ * first lyric line, or to the nearest downbeat when the section has no lyric.+ * Word timings are used when a line carries them; otherwise the line start is+ * the only cue (#9074 may add words later).+ */++import { CODE_FPS } from './codeFrame.js';++const round3 = (n) => Math.round(n * 1000) / 1000;++function finite(value) {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;+}++function beatGrid(values) {+ return (Array.isArray(values) ? values : []).filter((value) => typeof value === 'number' && Number.isFinite(value) && value >= 0).sort((a, b) => a - b);+}++function beatAtOrBefore(beats, t) {+ let best = null;+ for (const beat of beats) {+ if (beat > t + 1e-6) break;+ best = beat;+ }+ return best;+}++function nearest(points, t) {+ let best = null;+ let bestDist = Infinity;+ for (const point of points) {+ const dist = Math.abs(point - t);+ if (dist < bestDist - 1e-9) { best = point; bestDist = dist; }+ }+ return best;+}++function songDuration(project) {+ const analysis = project.audioAnalysis || {};+ const ends = [finite(analysis.durationSec)];+ for (const section of analysis.sections || []) ends.push(finite(section?.endSec));+ for (const beat of project.treatment?.arc?.beats || []) ends.push(finite(beat?.endSec));+ for (const scene of project.scenes || []) ends.push(finite(scene?.endSec));+ for (const cue of project.lyricCues || []) ends.push(finite(cue?.endSec), finite(cue?.startSec));+ for (const beat of beatGrid(analysis.beats)) ends.push(beat);+ const duration = ends.reduce((max, value) => (value != null ? Math.max(max, value) : max), 0);+ return duration > 0 ? duration : 0;+}++function windowsFrom(items, idOf, labelOf) {+ return (Array.isArray(items) ? items : [])+ .map((item, index) => {+ const startSec = finite(item?.startSec);+ const endSec = finite(item?.endSec);+ if (startSec == null || endSec == null || endSec <= startSec) return null;+ return {+ id: idOf(item, index),+ label: labelOf(item, index),+ sceneId: item.sceneId || null,+ startSec,+ endSec,+ };+ })+ .filter(Boolean)+ .sort((a, b) => a.startSec - b.startSec);+}++function nominalWindows(project, duration) {+ const treatment = windowsFrom(+ project.treatment?.arc?.beats,+ (beat, index) => (typeof beat.id === 'string' && beat.id ? beat.id : `beat-${index}`),+ (beat, index) => beat.label || beat.role || `Section ${index + 1}`,+ );+ if (treatment.length) return treatment;+ const analyzed = windowsFrom(+ project.audioAnalysis?.sections,+ (section, index) => (typeof section.id === 'string' && section.id ? section.id : `analysis-${index}`),+ (section, index) => section.label || `Section ${index + 1}`,+ );+ if (analyzed.length) return analyzed;+ const scenes = windowsFrom(+ project.scenes,+ (scene, index) => scene.sceneId || `scene-${index}`,+ (scene, index) => scene.label || scene.sectionLabel || `Scene ${index + 1}`,+ );+ if (scenes.length) return scenes.map((scene) => ({ ...scene, sceneId: scene.id }));+ if (duration > 0) return [{ id: 'song', label: 'Song', sceneId: null, startSec: 0, endSec: duration }];+ return [];+}++function lyricLines(project) {+ return (project.lyricCues || [])+ .filter((cue) => cue && typeof cue.text === 'string' && cue.text.trim() && finite(cue.startSec) != null)+ .map((cue) => ({ ...cue, text: cue.text.trim() }))+ .sort((a, b) => a.startSec - b.startSec);+}++function wordsOf(line) {+ const words = Array.isArray(line.words) ? line.words.filter((word) => word && typeof word.text === 'string' && word.text.trim() && finite(word.startSec) != null) : [];+ if (words.length) {+ return words.map((word) => ({+ text: word.text.trim(),+ startSec: word.startSec,+ endSec: finite(word.endSec) != null && word.endSec > word.startSec ? word.endSec : null,+ }));+ }+ const startSec = line.startSec;+ const endSec = finite(line.endSec) != null && line.endSec > startSec ? line.endSec : null;+ return [{ text: line.text, startSec, endSec }];+}++function firstLyric(lines, window) {+ return lines.find((line) => line.startSec >= window.startSec - 1e-6 && line.startSec < window.endSec - 1e-6) || null;+}++function anchorOf(line) {+ const words = wordsOf(line);+ return words[0]?.startSec ?? line.startSec;+}++/**+ * Quantize a span up to a whole frame so the encoded file covers it and+ * `duration × fps` is a whole number of frames (the composition encoder's+ * contract). The extra time is strictly under one frame.+ */+export function quantizeSongDuration(durationSec, fps = CODE_FPS) {+ if (!(durationSec > 0) || !Number.isFinite(durationSec)) return { frames: 0, durationSec: 0, fps };+ const frames = Math.max(1, Math.ceil(durationSec * fps - 1e-9));+ let seconds = frames / fps;+ if (Math.round(seconds * fps) !== frames) seconds = (frames - 0.5) / fps + 1 / fps;+ return { frames, durationSec: frames / fps, fps };+}++export function paletteFromProject(project) {+ const colors = (project.visualSpec?.palette || [])+ .filter((color) => typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color))+ .map((color) => color.toLowerCase());+ return {+ background: colors[0] || '#12141c',+ ink: colors[1] || '#f4f1ea',+ accent: colors[2] || '#e0a458',+ mute: colors[3] || '#8a8f98',+ font: project.composition?.style?.font || 'sans',+ colors,+ };+}++export const CODE_FRAME_SIZES = Object.freeze({+ '16:9': Object.freeze({ width: 1280, height: 720 }),+ '9:16': Object.freeze({ width: 1080, height: 1920 }),+ '1:1': Object.freeze({ width: 1080, height: 1080 }),+});++export function codeFrameSize(aspectRatio) {+ return CODE_FRAME_SIZES[aspectRatio] || CODE_FRAME_SIZES['16:9'];+}++/**+ * Section windows on the song timebase. Interior boundaries are beat times.+ * The first section starts at 0 and the last ends at the song duration.+ */+export function buildCodeTimeline(project, { fps = CODE_FPS } = {}) {+ const duration = songDuration(project);+ const beats = beatGrid(project.audioAnalysis?.beats);+ const downbeats = beatGrid(project.audioAnalysis?.downbeats);+ const lines = lyricLines(project);+ const windows = nominalWindows(project, duration);+ const snapped = windows.map((window) => {+ const lyric = firstLyric(lines, window);+ if (lyric) {+ const anchor = anchorOf(lyric);+ const beat = beatAtOrBefore(beats, anchor);+ return { ...window, snap: beat ?? anchor, snapKind: beat == null ? 'lyric' : 'beat', lyricId: lyric.id || null };+ }+ const down = nearest(downbeats, window.startSec);+ if (down != null) return { ...window, snap: down, snapKind: 'downbeat', lyricId: null };+ const beat = nearest(beats, window.startSec);+ return { ...window, snap: beat ?? window.startSec, snapKind: beat == null ? 'nominal' : 'beat', lyricId: null };+ }).sort((a, b) => a.snap - b.snap || a.startSec - b.startSec);++ const minSpan = 1 / fps;+ const sections = [];+ for (const window of snapped) {+ const startSec = sections.length === 0 ? 0 : window.snap;+ if (!(startSec < duration - 1e-6)) continue;+ if (sections.length && startSec < sections[sections.length - 1].startSec + minSpan - 1e-9) continue;+ sections.push({+ id: window.id,+ label: window.label,+ sceneId: window.sceneId,+ startSec: round3(startSec),+ endSec: round3(duration),+ snapKind: sections.length === 0 ? 'start' : window.snapKind,+ lyricId: window.lyricId,+ });+ if (sections.length > 1) sections[sections.length - 2].endSec = round3(startSec);+ }+ if (!sections.length && duration > 0) {+ sections.push({ id: 'song', label: 'Song', sceneId: null, startSec: 0, endSec: round3(duration), snapKind: 'start', lyricId: null });+ }+ return { durationSec: round3(duration), fps, sections, beats, downbeats };+}++/** The song.json document the composition seeks. Words fall back to the line. */+export function buildSongDocument(project, timeline = buildCodeTimeline(project)) {+ const quantized = quantizeSongDuration(timeline.durationSec, timeline.fps);+ const lines = lyricLines(project).map((line) => ({+ id: typeof line.id === 'string' ? line.id : null,+ text: line.text,+ startSec: line.startSec,+ endSec: finite(line.endSec),+ words: wordsOf(line),+ }));+ const sections = timeline.sections.map((section, index) => {+ const endSec = index === timeline.sections.length - 1 ? quantized.durationSec : section.endSec;+ const lyric = lines.find((line) => line.startSec >= section.startSec - 1e-6 && line.startSec < endSec - 1e-6) || null;+ return {+ id: section.id,+ label: section.label,+ sceneId: section.sceneId,+ startSec: section.startSec,+ endSec,+ snapKind: section.snapKind,+ lyric: lyric ? lyric.text : null,+ };+ });+ return {+ durationSec: quantized.durationSec,+ frames: quantized.frames,+ fps: timeline.fps,+ beats: timeline.beats,+ downbeats: timeline.downbeats,+ sections,+ lyrics: lines,+ };+}diff --git a/server/services/musicVideo/codeTimeline.test.js b/server/services/musicVideo/codeTimeline.test.jsnew file mode 100644index 0000000000..9d4386bb74--- /dev/null+++ b/server/services/musicVideo/codeTimeline.test.js@@ -0,0 +1,101 @@+import { describe, expect, it } from 'vitest';+import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';+import { normalizeComposition } from './composition.js';+import { buildCodeTimeline, buildSongDocument, quantizeSongDuration } from './codeTimeline.js';+import { fixtureSectionSource } from './codeFrame.js';++const project = {+ name: 'Click',+ audioAnalysis: {+ durationSec: 4,+ beats: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5],+ downbeats: [0, 2],+ sections: [+ { label: 'Verse', startSec: 0, endSec: 2 },+ { label: 'Chorus', startSec: 2, endSec: 4 },+ ],+ },+ lyricCues: [+ { id: 'l1', text: 'hello world', startSec: 0.55, endSec: 1.4 },+ { id: 'l2', text: 'second line', startSec: 2.2, endSec: 3.2, words: [+ { text: 'second', startSec: 2.25, endSec: 2.6 },+ { text: 'line', startSec: 2.7, endSec: 3.1 },+ ] },+ ],+ scenes: [{ sceneId: 's1', label: 'Shot', startSec: 0, endSec: 4, takes: [{ id: 'take-1' }] }],+ composition: { mode: 'concat', textCues: [{ id: 'c1', text: 'kept', startSec: 1, endSec: 2 }], style: { color: '#ffffff', font: 'sans' } },+};++describe('buildCodeTimeline (#9076)', () => {+ it('snaps later section boundaries to the beat at or before the first word', () => {+ const timeline = buildCodeTimeline(project);+ expect(timeline.sections.map((section) => [section.label, section.startSec, section.endSec])).toEqual([+ ['Verse', 0, 2],+ ['Chorus', 2, 4],+ ]);+ for (const section of timeline.sections.slice(1)) {+ expect(timeline.beats).toContain(section.startSec);+ }+ const song = buildSongDocument(project, timeline);+ const chorus = song.lyrics.find((line) => line.id === 'l2');+ expect(chorus.words.map((word) => word.text)).toEqual(['second', 'line']);+ // No word timings: the line itself is the only cue, not invented word times.+ expect(song.lyrics.find((line) => line.id === 'l1').words).toEqual([+ { text: 'hello world', startSec: 0.55, endSec: 1.4 },+ ]);+ });++ it('uses the nearest downbeat when a section has no lyric', () => {+ const instrumental = {+ ...project,+ lyricCues: [],+ audioAnalysis: { ...project.audioAnalysis, sections: [+ { label: 'Intro', startSec: 0, endSec: 2.2 },+ { label: 'Drop', startSec: 2.2, endSec: 4 },+ ] },+ };+ const timeline = buildCodeTimeline(instrumental);+ expect(timeline.sections.map((section) => section.startSec)).toEqual([0, 2]);+ expect(timeline.sections[1].snapKind).toBe('downbeat');+ });++ it('prefers treatment windows over analyzed sections', () => {+ const directed = {+ ...project,+ treatment: { arc: { beats: [+ { id: 'b1', label: 'Open', startSec: 0, endSec: 1.2 },+ { id: 'b2', label: 'Payoff', startSec: 1.2, endSec: 4 },+ ] } },+ };+ const timeline = buildCodeTimeline(directed);+ expect(timeline.sections.map((section) => section.id)).toEqual(['b1', 'b2']);+ expect(timeline.beats).toContain(timeline.sections[1].startSec);+ });++ it('covers the song within one frame', () => {+ for (const duration of [1 / 24, 2, 2.01, 3.333, 10]) {+ const quantized = quantizeSongDuration(duration, 24);+ expect(quantized.durationSec).toBeGreaterThanOrEqual(duration - 1e-9);+ expect(quantized.durationSec - duration).toBeLessThan(1 / 24 + 1e-9);+ expect(Math.round(quantized.durationSec * 24)).toBe(quantized.frames);+ }+ });+});++describe('code mode keeps the rest of the project (#9076)', () => {+ it('defaults unknown modes to concat and round-trips code without dropping cues', () => {+ expect(normalizeComposition({ mode: 'not-a-mode', textCues: [{ text: 'Hi', startSec: 1, endSec: 2 }] }).mode).toBe('concat');+ const source = fixtureSectionSource('#112233');+ const code = normalizeComposition({+ mode: 'code',+ textCues: project.composition.textCues,+ codeVideo: { providerId: 'stub', model: 'fixture', sections: [{ id: 'Verse', source }, { id: 'bad', source: 'Math.random()' }] },+ });+ expect(code.mode).toBe('code');+ expect(code.textCues.map((cue) => cue.text)).toEqual(['kept']);+ expect(code.codeVideo.sections).toEqual([{ id: 'Verse', source }]);+ expect(normalizeComposition({ ...code, mode: 'concat' }).textCues).toHaveLength(1);+ expect(normalizeComposition({ ...code, mode: 'composed' }).codeVideo.sections).toHaveLength(1);+ expect(PORTOS_SCHEMA_VERSIONS.musicVideoProjects).toBe(7);+ });+});diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.jsindex 7b4d08fb57..36e3ba2d02 100644--- a/server/services/musicVideo/composition.js+++ b/server/services/musicVideo/composition.js@@ -24,6 +24,7 @@ import {MUSIC_VIDEO_TYPOGRAPHY_FONTS as TYPOGRAPHY_FONTS,MUSIC_VIDEO_TYPOGRAPHY_PLACEMENTS as TYPOGRAPHY_PLACEMENTS,MUSIC_VIDEO_TYPOGRAPHY_TEMPLATES as TYPOGRAPHY_TEMPLATES,+ isDeterministicCodeSource,} from '../../lib/musicVideoValidation.js';export const COMPOSITION_VERSION = 1;@@ -33,6 +34,27 @@ 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);+// Keep generated section functions across a mode switch. A source that would+// not seek cleanly is dropped rather than stored.+function normalizeCodeVideo(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const seen = new Set();+ const sections = [];+ for (const section of Array.isArray(input.sections) ? input.sections : []) {+ if (!section || typeof section.id !== 'string' || !section.id || seen.has(section.id)) continue;+ if (!isDeterministicCodeSource(section.source)) continue;+ seen.add(section.id);+ sections.push({ id: section.id, source: section.source });+ }+ if (!sections.length && !input.providerId && !input.model && !input.generatedAt) return null;+ return {+ providerId: typeof input.providerId === 'string' && input.providerId ? input.providerId.slice(0, 120) : null,+ model: typeof input.model === 'string' && input.model ? input.model.slice(0, 200) : null,+ generatedAt: typeof input.generatedAt === 'string' && input.generatedAt ? input.generatedAt.slice(0, 40) : null,+ sections,+ };+}+/*** 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@@ -70,6 +92,7 @@ export function normalizeComposition(input) {font: pick(style.font, TYPOGRAPHY_FONTS, 'sans'),},posterSec: toTime(input.posterSec),+ codeVideo: normalizeCodeVideo(input.codeVideo),};}diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.jsindex 3fa7077fda..6bbb3add39 100644--- a/server/services/musicVideo/excerptRender.js+++ b/server/services/musicVideo/excerptRender.js@@ -29,7 +29,8 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';import { safeUnder } from '../../lib/ffmpeg.js';import { encodeFileContactSheetAtTimes } from '../htmlComposition/encode.js';import { getProject, listProjects, mutateProjectRecord } from './projects.js';-import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark } from './render.js';+import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark, resolveMasterAudioPath } from './render.js';+import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';import { renderableCues, sectionCardCues } from './composition.js';import { renderTypographyOverlays, removeCompositionScratch } from './compositionRender.js';import { startExcerptOnProject, applyExcerptPatch } from './excerpt.js';@@ -75,6 +76,99 @@ const unlinkUnder = (root, filename) => {* `revisionId` (#8987) links the render to an open selective revision in the* same write that creates the excerpt, so its finish settles that revision.*/+// A code-rendered project excerpts the same seekable composition, windowed,+// instead of the footage concat. Footage generation is not involved.+async function launchCodeExcerpt({ projectId, project, startSec, endSec, revisionId, handOff }) {+ const full = prepareCodeRender(project);+ const audioPath = await resolveMasterAudioPath(project);+ if (!(startSec >= 0) || !(endSec > startSec) || endSec > full.durationSec + 1e-6) {+ throw new ServerError(+ `The excerpt range must fall within the project's ${full.durationSec.toFixed(2)}s song`,+ { status: 422, code: 'INVALID_EXCERPT_RANGE', context: { totalDuration: full.durationSec } },+ );+ }+ const endClamped = Math.min(endSec, full.durationSec);+ const plan = prepareCodeRender(project, { windowStart: startSec, windowEnd: endClamped });+ await ensureDir(PATHS.videos);+ await ensureDir(PATHS.videoThumbnails);+ const filename = `music-video-excerpt-${projectId.slice(0, 8)}-${Date.now()}.mp4`;+ const outputPath = join(PATHS.videos, filename);+ const sections = full.song.sections+ .filter((section) => section.startSec < endClamped && section.endSec > startSec)+ .map((section) => ({+ sceneId: section.sceneId || section.id,+ startSec: round3(Math.max(section.startSec, startSec)),+ endSec: round3(Math.min(section.endSec, endClamped)),+ }));+ const renderingOn = await ensureInstanceId();+ const { excerpt } = await mutateProjectRecord(projectId, (current) => {+ const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, partialFilename: filename, renderingOn });+ return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;+ });+ const excerptId = excerpt.id;+ const jobId = excerptId;+ const totalDuration = plan.durationSec;+ const job = { id: jobId, projectId, excerptId, status: 'running', clients: [], process: null, totalDuration, overlayAbort: new AbortController() };+ jobs.set(jobId, job);+ projectExcerptRenders.set(projectId, jobId);+ handOff();+ console.log(`🎬 Rendering code music-video excerpt [${jobId.slice(4, 12)}]: project=${projectId.slice(0, 8)} range=[${startSec.toFixed(2)},${endClamped.toFixed(2)}]s footage=off`);+ const { signal } = job.overlayAbort;+ const finalize = async (patch) => {+ projectExcerptRenders.delete(projectId);+ const persisted = await mutateProjectRecord(projectId, (current) => ({+ project: settleRevisionRender(applyExcerptPatch(current, excerptId, { ...patch, partialFilename: null, renderingOn: null }), excerptId, patch),+ })).then(() => true, (err) => {+ console.error(`❌ Music-video code excerpt [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);+ return false;+ });+ closeJobAfterDelay(jobs, jobId);+ if (persisted) musicVideoEvents.emit('excerpt-render', { projectId, excerptId, status: patch.status });+ return persisted;+ };+ encodeCodeComposition({+ ...plan,+ audioPath,+ audioStartSec: startSec,+ outputPath,+ directory: `compositions/music-video/${projectId}/${jobId}`,+ signal,+ onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),+ }).then(async () => {+ job.overlayAbort = null;+ job.status = 'complete';+ let contactSheetFilename = null;+ try {+ contactSheetFilename = sheetFilenameFor(filename);+ await writeCodeProofSheet(outputPath, join(PATHS.videoThumbnails, contactSheetFilename), plan.sectionTimes, {+ width: plan.width, height: plan.height, fps: plan.fps,+ });+ } catch (err) {+ console.warn(`⚠️ Music-video code excerpt contact sheet failed [${jobId.slice(4, 12)}]: ${err.message}`);+ contactSheetFilename = null;+ }+ const persisted = await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null });+ if (!persisted) {+ await unlink(outputPath).catch(() => {});+ broadcastSse(job, { type: 'error', error: 'The excerpt rendered, but saving the result failed — reload the project and try again' });+ return;+ }+ console.log(`✅ Code music-video excerpt rendered [${jobId.slice(4, 12)}]: ${filename}`);+ broadcastSse(job, { type: 'complete', result: { excerptId, filename, path: `/data/videos/${filename}`, contactSheetFilename, contactSheetPath: contactSheetFilename ? `/data/video-thumbnails/${contactSheetFilename}` : null } });+ }).catch(async (err) => {+ const canceled = signal.aborted || err?.code === 'CANCELED';+ job.status = canceled ? 'canceled' : 'error';+ const reason = canceled ? 'Render cancelled' : `Code excerpt failed: ${err.message}`;+ job.lastError = reason;+ const log = canceled ? console.log : console.error;+ log(`${canceled ? '🛑' : '❌'} Music-video code excerpt ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(4, 12)}]: ${reason}`);+ await unlink(outputPath).catch(() => {});+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });+ await finalize({ status: canceled ? 'canceled' : 'error', error: canceled ? null : reason, filename: null, jobId: null });+ });+ return { jobId, excerptId };+}+export async function startExcerptRender(projectId, { startSec, endSec }, { revisionId = null } = {}) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });@@ -89,6 +183,11 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { revilet handedOff = false;try {+ if (project.composition?.mode === 'code') {+ return await launchCodeExcerpt({+ projectId, project, startSec, endSec, revisionId, handOff: () => { handedOff = true; },+ });+ }const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 145eed056d..b40b5b320c 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -38,6 +38,7 @@ import { getProject, listProjects, updateProject, mutateProjectRecord } from './import { applyProjectPatch } from './projectsLogic.js';import { sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';import { renderableCues, sectionCardCues } from './composition.js';+import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch, renderSongComposition } from './compositionRender.js';import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';import { findStalePerformanceTakes } from './performanceShot.js';@@ -596,8 +597,9 @@ export async function planMusicVideoRender(project) {return { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed };}-// Code compositions are not the footage concat below. The caller names the-// composition directory; excerpts pass the master's in-point as startSec.+// An existing HTML composition directory is rendered through the music-video+// owner (#9075). The caller names the directory; excerpts pass the master's+// in-point as startSec. This is not the code-rendered project mode below.async function renderMusicVideoCode(projectId, { codeDirectory, startSec = 0 }) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });@@ -617,6 +619,91 @@ async function renderMusicVideoCode(projectId, { codeDirectory, startSec = 0 })}}+// Code-rendered mode (#9076) seeks a composition instead of concatenating+// footage. It shares this module's job map so the existing SSE and cancel+// routes apply, and it never asks a footage model for pixels.+async function renderCodeMode(projectId, project, handOff) {+ const plan = prepareCodeRender(project);+ const audioPath = await resolveMasterAudioPath(project);+ await ensureDir(PATHS.videos);+ await ensureDir(PATHS.videoThumbnails);+ const renderingOn = await ensureInstanceId();+ const jobId = randomUUID();+ const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;+ const outputPath = join(PATHS.videos, filename);+ const sheetName = filename.replace(/\.mp4$/, '-proof.png');+ const job = {+ id: jobId, projectId, status: 'running', clients: [], process: null,+ totalDuration: plan.durationSec, overlayAbort: new AbortController(),+ };+ jobs.set(jobId, job);+ projectRenders.set(projectId, jobId);+ handOff();+ const priorStatus = project.status && project.status !== 'rendering' ? project.status : 'ready';+ await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename }).catch((err) => {+ console.error(`❌ Music-video code render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→rendering write failed: ${err.message}`);+ });+ console.log(`🎬 Rendering code music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} frames=${Math.round(plan.durationSec * plan.fps)} footage=off`);+ const { signal } = job.overlayAbort;+ const finish = async (patch) => {+ projectRenders.delete(projectId);+ await updateProject(projectId, settledRender(patch.status, patch.extra || {})).catch((err) => {+ console.error(`❌ Music-video code render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);+ });+ closeJobAfterDelay(jobs, jobId);+ };+ encodeCodeComposition({+ ...plan,+ audioPath,+ outputPath,+ directory: `compositions/music-video/${projectId}/${jobId}`,+ signal,+ onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),+ }).then(async () => {+ job.overlayAbort = null;+ job.status = 'complete';+ let proof = null;+ try {+ await writeCodeProofSheet(outputPath, join(PATHS.videoThumbnails, sheetName), plan.sectionTimes, {+ width: plan.width, height: plan.height, fps: plan.fps,+ });+ proof = sheetName;+ } catch (err) {+ console.warn(`⚠️ Music-video code proof sheet failed [${jobId.slice(0, 8)}]: ${err.message}`);+ }+ const atSec = typeof project.composition?.posterSec === 'number' ? project.composition.posterSec : (plan.sectionTimes[0] || 0);+ const thumb = await generateThumbnail(outputPath, jobId, { atSec });+ await appendToVideoHistory({+ id: jobId,+ prompt: `Music Video: ${project.name}`,+ modelId: 'music-video-code',+ seed: 0,+ width: plan.width,+ height: plan.height,+ numFrames: Math.round(plan.durationSec * plan.fps),+ fps: plan.fps,+ filename,+ thumbnail: thumb,+ createdAt: new Date().toISOString(),+ musicVideoProjectId: projectId,+ });+ await finish({ status: 'complete', extra: { renderHistoryId: jobId } });+ console.log(`✅ Code music video rendered [${jobId.slice(0, 8)}]: ${filename}`);+ broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}`, proof: proof ? `/data/video-thumbnails/${proof}` : null } });+ }).catch(async (err) => {+ const canceled = signal.aborted || err?.code === 'CANCELED';+ job.status = canceled ? 'canceled' : 'error';+ const reason = canceled ? 'Render cancelled' : `Code render failed: ${err.message}`;+ job.lastError = reason;+ const log = canceled ? console.log : console.error;+ log(`${canceled ? '🛑' : '❌'} Music-video code render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);+ await unlink(outputPath).catch(() => {});+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });+ await finish({ status: canceled ? priorStatus : 'failed' });+ });+ return { jobId };+}+export async function renderMusicVideo(projectId, options = {}) {if (typeof options?.codeDirectory === 'string' && options.codeDirectory) {return renderMusicVideoCode(projectId, options);@@ -637,6 +724,9 @@ export async function renderMusicVideo(projectId, options = {}) {let handedOff = false;try {+ if (project.composition?.mode === 'code') {+ return await renderCodeMode(projectId, project, () => { handedOff = true; });+ }const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);