Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(music-video): project composition documents rendered with the song (#9240)

[._.]/37d64d121e8a
diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.jsx
new file mode 100644
index 0000000000..084c7b5be6
--- /dev/null
+++ b/client/src/components/musicVideo/DocumentCompositionPanel.jsx
@@ -0,0 +1,320 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import FilePickerButton from '../ui/FilePickerButton.jsx';
+import { Download, FileArchive, FolderInput, LayoutTemplate, Pause, Play, Unlink } from 'lucide-react';
+import toast from '../ui/Toast';
+import { downloadBlob } from '../../lib/downloadBlob';
+import { formatBytes, timeAgo } from '../../utils/formatters.js';
+import { compositionDraft } from './compositionDraft.js';
+import {
+ detachMusicVideoCompositionDocument, fetchMusicVideoPreviewAsset, getMusicVideoCompositionDocument, getMusicVideoCompositionExport,
+ getMusicVideoCompositionPreview, importMusicVideoCompositionDirectory, importMusicVideoCompositionZip,
+ startMusicVideoCompositionTemplate,
+} 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';
+const inputCls = 'bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs';
+const SOURCE_LABELS = { template: 'template', zip: 'zip', directory: 'folder' };
+
+const linesOf = (value) => String(value || '').split('\n').map((line) => line.trim()).filter(Boolean);
+// "12.5 = 80" per line → [[12.5, 80], …]; unparseable lines are dropped.
+const keyframesOf = (value) => linesOf(value)
+ .map((line) => line.split(/[=:,\s]+/).map(Number))
+ .filter(([t, v]) => Number.isFinite(t) && t >= 0 && Number.isFinite(v) && v >= 0 && v <= 100)
+ .map(([t, v]) => [t, v]);
+
+/**
+ * HUD block the layered template draws (`composition.overlay`). Text fields
+ * edit locally and persist on blur, replacing the whole manifest.
+ */
+function OverlayEditor({ project, onSave }) {
+ const composition = compositionDraft(project);
+ const overlay = composition.overlay || null;
+ const [draft, setDraft] = useState(() => ({
+ titleLines: (overlay?.titleLines || []).join('\n'),
+ ticker: (overlay?.ticker || []).join('\n'),
+ meterLabel: overlay?.meter?.label || '',
+ keyframes: (overlay?.meter?.keyframes || []).map(([t, v]) => `${t} = ${v}`).join('\n'),
+ }));
+ const save = (patch = {}) => {
+ const next = {
+ enabled: overlay?.enabled ?? true,
+ timecode: overlay?.timecode ?? true,
+ timecodeStartSec: overlay?.timecodeStartSec ?? 0,
+ titleLines: linesOf(draft.titleLines).slice(0, 4),
+ ticker: linesOf(draft.ticker).slice(0, 40),
+ meter: draft.meterLabel || draft.keyframes ? { label: draft.meterLabel.trim().slice(0, 40), keyframes: keyframesOf(draft.keyframes) } : null,
+ ...patch,
+ };
+ onSave({ composition: { ...composition, overlay: next } });
+ };
+ const field = (key) => ({ value: draft[key], onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })), onBlur: () => save() });
+ return (
+ <details className="rounded border border-port-border p-2 text-xs">
+ <summary className="cursor-pointer select-none text-port-text-muted">HUD overlay — {overlay?.enabled === false || !overlay ? 'off' : 'on'} (drawn by the layered template)</summary>
+ <div className="mt-2 flex flex-wrap items-center gap-3">
+ <label htmlFor="mv-doc-hud-on" className="flex items-center gap-1">
+ <input id="mv-doc-hud-on" type="checkbox" checked={Boolean(overlay) && overlay.enabled !== false} onChange={(e) => save({ enabled: e.target.checked })} /> Show HUD
+ </label>
+ <label htmlFor="mv-doc-hud-tc" className="flex items-center gap-1">
+ <input id="mv-doc-hud-tc" type="checkbox" checked={overlay?.timecode ?? true} onChange={(e) => save({ timecode: e.target.checked })} /> Timecode
+ </label>
+ <label htmlFor="mv-doc-hud-tc-start" className="flex items-center gap-1">
+ Timecode starts at (s)
+ <input id="mv-doc-hud-tc-start" type="number" min={0} step={1} className={`${inputCls} w-24`} defaultValue={overlay?.timecodeStartSec ?? 0}
+ onBlur={(e) => save({ timecodeStartSec: Math.max(0, Number(e.target.value) || 0) })} />
+ </label>
+ </div>
+ <div className="mt-2 grid grid-cols-1 gap-2 md:grid-cols-2">
+ <div>
+ <label htmlFor="mv-doc-hud-title" className="block text-port-text-muted mb-0.5">Title lines (up to 4)</label>
+ <textarea id="mv-doc-hud-title" rows={3} className={`${inputCls} w-full`} {...field('titleLines')} />
+ </div>
+ <div>
+ <label htmlFor="mv-doc-hud-ticker" className="block text-port-text-muted mb-0.5">Ticker (one item per line)</label>
+ <textarea id="mv-doc-hud-ticker" rows={3} className={`${inputCls} w-full`} {...field('ticker')} />
+ </div>
+ <div>
+ <label htmlFor="mv-doc-hud-meter" className="block text-port-text-muted mb-0.5">Meter label</label>
+ <input id="mv-doc-hud-meter" type="text" maxLength={40} className={`${inputCls} w-full`} {...field('meterLabel')} />
+ </div>
+ <div>
+ <label htmlFor="mv-doc-hud-keys" className="block text-port-text-muted mb-0.5">Meter keyframes (seconds = percent, one per line)</label>
+ <textarea id="mv-doc-hud-keys" rows={3} placeholder={'0 = 100\n60 = 40'} className={`${inputCls} w-full`} {...field('keyframes')} />
+ </div>
+ </div>
+ </details>
+ );
+}
+
+/** The document's files, read when opened (the manifest route). */
+function DocumentFiles({ projectId, directory }) {
+ const [manifest, setManifest] = useState(null);
+ const [error, setError] = useState('');
+ const load = (open) => {
+ if (!open || manifest) return;
+ getMusicVideoCompositionDocument(projectId, { silent: true })
+ .then(setManifest)
+ .catch((err) => setError(err?.message || 'Could not list the document files'));
+ };
+ return (
+ <details key={directory} className="rounded border border-port-border p-2 text-xs" onToggle={(e) => load(e.currentTarget.open)}>
+ <summary className="cursor-pointer select-none text-port-text-muted">Files</summary>
+ {error && <p role="status" className="mt-1 text-port-error">{error}</p>}
+ {manifest && !manifest.available && <p className="mt-1 text-port-warning">The document folder is missing on this machine — import it again.</p>}
+ {manifest?.available && (
+ <ul className="mt-1 max-h-48 overflow-y-auto font-mono">
+ {manifest.files.map((file) => <li key={file.path} className="flex justify-between gap-2"><span className="min-w-0 break-all">{file.path}</span><span className="shrink-0 text-port-text-muted">{formatBytes(file.bytes)}</span></li>)}
+ </ul>
+ )}
+ </details>
+ );
+}
+
+/**
+ * The project's composition document (render style `document`): what is
+ * attached, import (template / zip / data folder), export, and a live preview.
+ * The preview runs in an opaque-origin sandbox that cannot fetch; this panel
+ * fetches the scene takes and document media and posts them in as Blobs.
+ */
+export default function DocumentCompositionPanel({ project, audioUrl, onProject, onSave }) {
+ const doc = project.composition?.document || null;
+ const [busy, setBusy] = useState(null);
+ // Replacing or detaching drops the current version folder once nothing
+ // points at it, so both ask for a second click (no window.confirm).
+ const [confirming, setConfirming] = useState(null);
+ const [folder, setFolder] = useState('');
+ const [preview, setPreview] = useState(null);
+ const [previewError, setPreviewError] = useState('');
+ const [status, setStatus] = useState('');
+ const [t, setT] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const iframeRef = useRef(null);
+ const audioRef = useRef(null);
+ const blobCache = useRef(new Map());
+ const seekState = useRef({ inFlight: false, pending: null, ready: false });
+
+ const refresh = doc ? `${doc.directory}|${project.updatedAt}` : null;
+ useEffect(() => {
+ let active = true;
+ setPreview(null);
+ setPreviewError('');
+ seekState.current = { inFlight: false, pending: null, ready: false };
+ if (!refresh) return () => { active = false; };
+ getMusicVideoCompositionPreview(project.id, { silent: true })
+ .then((next) => { if (active) setPreview(next); })
+ .catch((err) => { if (active) setPreviewError(err?.message || 'Could not build the preview'); });
+ return () => { active = false; };
+ }, [project.id, refresh]);
+
+ const postSeek = useCallback((time) => {
+ const frame = iframeRef.current?.contentWindow;
+ const state = seekState.current;
+ if (!frame || !state.ready) return;
+ if (state.inFlight) { state.pending = time; return; }
+ state.inFlight = true;
+ frame.postMessage({ type: 'portos-mv:seek', t: time }, '*');
+ }, []);
+
+ useEffect(() => {
+ if (!preview) return undefined;
+ let active = true;
+ const onMessage = async (event) => {
+ if (event.source !== iframeRef.current?.contentWindow) return;
+ const message = event.data || {};
+ const state = seekState.current;
+ if (message.type === 'portos-mv:loaded') {
+ const files = {};
+ let loaded = 0;
+ for (const asset of preview.assets || []) {
+ if (!active) return;
+ setStatus(`Loading preview media ${loaded + 1}/${preview.assets.length}…`);
+ const blob = blobCache.current.get(asset.url) || await fetchMusicVideoPreviewAsset(asset.url).catch(() => null);
+ if (blob) { blobCache.current.set(asset.url, blob); files[asset.key] = blob; }
+ loaded += 1;
+ }
+ if (!active) return;
+ setStatus(loaded === (preview.assets || []).length ? '' : 'Some preview media could not be loaded');
+ iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:assets', files }, '*');
+ state.ready = true;
+ postSeek(t);
+ } else if (message.type === 'portos-mv:seeked') {
+ state.inFlight = false;
+ if (state.pending != null) { const next = state.pending; state.pending = null; postSeek(next); }
+ } else if (message.type === 'portos-mv:error') {
+ state.inFlight = false;
+ setPreviewError(String(message.message || 'The composition document failed in the preview'));
+ }
+ };
+ window.addEventListener('message', onMessage);
+ return () => { active = false; window.removeEventListener('message', onMessage); };
+ // `t` is read once when the page loads; later seeks go through postSeek.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [preview, postSeek]);
+
+ const duration = preview?.durationSec || 0;
+ const fps = preview?.fps || 24;
+ const seek = useCallback((time) => {
+ const next = Math.min(Math.max(0, time), Math.max(0, duration - 1 / fps));
+ setT(next);
+ postSeek(next);
+ if (audioRef.current && Math.abs((audioRef.current.currentTime || 0) - next) > 0.05) audioRef.current.currentTime = next;
+ }, [duration, fps, postSeek]);
+
+ useEffect(() => {
+ if (!playing) return undefined;
+ let handle = 0;
+ let posted = -1;
+ const tick = () => {
+ const time = audioRef.current?.currentTime || 0;
+ const frameIndex = Math.floor(time * fps + 1e-9);
+ if (frameIndex !== posted) { posted = frameIndex; setT(time); postSeek(time); }
+ handle = requestAnimationFrame(tick);
+ };
+ handle = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(handle);
+ }, [playing, fps, postSeek]);
+
+ const togglePlay = () => {
+ const audio = audioRef.current;
+ if (!audio) return;
+ if (playing) { audio.pause(); setPlaying(false); return; }
+ audio.play?.()?.catch?.(() => {});
+ setPlaying(true);
+ };
+
+ const run = async (label, task, success) => {
+ setBusy(label);
+ const result = await Promise.resolve().then(task).catch((err) => { toast.error(err?.message || 'Composition document action failed'); return null; });
+ setBusy(null);
+ if (result?.project) onProject(result.project);
+ if (result && success) toast.success(success);
+ return result;
+ };
+ const confirmFirst = (key, action) => () => {
+ if (doc && confirming !== key) { setConfirming(key); return; }
+ setConfirming(null);
+ action();
+ };
+ const startTemplate = confirmFirst('template', () => run('template', () => startMusicVideoCompositionTemplate(project.id, 'layered', { silent: true }), 'Layered template copied into this project'));
+ const importZip = (file) => file && run('zip', () => importMusicVideoCompositionZip(project.id, file, { silent: true }), 'Composition document imported');
+ const importFolder = () => folder.trim() && run('folder', () => importMusicVideoCompositionDirectory(project.id, folder.trim(), { silent: true }), 'Composition document imported');
+ const exportZip = () => run('export', async () => {
+ const buffer = await getMusicVideoCompositionExport(project.id, { silent: true });
+ downloadBlob(buffer, `${(project.name || 'music-video').replace(/[^\w.-]+/g, '-')}-composition.zip`, 'application/zip');
+ return {};
+ });
+ const detach = confirmFirst('detach', () => run('detach', () => detachMusicVideoCompositionDocument(project.id, { silent: true }), 'Composition document detached'));
+
+ const aspect = preview?.width && preview?.height ? `${preview.width} / ${preview.height}` : '16 / 9';
+ return (
+ <section className="mt-3 space-y-2 rounded-lg border border-port-border bg-port-bg p-2" aria-label="Composition document">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-port-text-muted">
+ <span className="text-sm text-port-text">Composition document</span>
+ {doc ? (
+ <span>
+ {SOURCE_LABELS[doc.source?.kind] || 'imported'}{doc.source?.name ? ` · ${doc.source.name}` : ''}
+ {doc.files != null ? ` · ${doc.files} files` : ''}{doc.bytes != null ? ` · ${formatBytes(doc.bytes)}` : ''}
+ {doc.updatedAt ? ` · updated ${timeAgo(doc.updatedAt)}` : ''}
+ </span>
+ ) : <span>None yet — start from the layered template or import your own.</span>}
+ </div>
+ <div className="flex flex-wrap items-end gap-2">
+ <button type="button" className={buttonCls} disabled={!!busy} onClick={startTemplate}
+ title="Copy PortOS's layered template (scene media, camera moves, grain, HUD, kinetic lyrics) into this project">
+ <LayoutTemplate size={14} /> {busy === 'template' ? 'Copying…' : confirming === 'template' ? 'Click again to replace' : doc ? 'Replace with template' : 'Start from template'}
+ </button>
+ <FilePickerButton accept=".zip,application/zip" onChange={(e) => importZip(e.target.files?.[0])} disabled={!!busy}
+ ariaLabel="Import zip composition document" className={`${buttonCls} cursor-pointer`}
+ title="A .zip whose root (or single top folder) holds index.html">
+ <FileArchive size={14} aria-hidden="true" /> {busy === 'zip' ? 'Importing…' : 'Import zip'}
+ </FilePickerButton>
+ <div className="flex items-end gap-1">
+ <div>
+ <label htmlFor="mv-doc-folder" className="block text-xs text-port-text-muted mb-0.5">Folder inside data/</label>
+ <input id="mv-doc-folder" type="text" value={folder} onChange={(e) => setFolder(e.target.value)} placeholder="compositions/my-video"
+ className={`${inputCls} w-48`} />
+ </div>
+ <button type="button" className={buttonCls} disabled={!!busy || !folder.trim()} onClick={importFolder}>
+ <FolderInput size={14} /> {busy === 'folder' ? 'Importing…' : 'Import folder'}
+ </button>
+ </div>
+ <button type="button" className={buttonCls} disabled={!!busy || !doc} onClick={exportZip}>
+ <Download size={14} /> Export zip
+ </button>
+ <button type="button" className={buttonCls} disabled={!!busy || !doc} onClick={detach} title="Stop using this document (the render refuses until another is attached)">
+ <Unlink size={14} /> {confirming === 'detach' ? 'Click again to detach' : 'Detach'}
+ </button>
+ </div>
+ <OverlayEditor key={`${project.id}-${project.composition?.overlay ? 'hud' : 'none'}`} project={project} onSave={onSave} />
+ {doc && (
+ <>
+ <DocumentFiles key={doc.directory} projectId={project.id} directory={doc.directory} />
+ {previewError && <p className="text-xs text-port-error" role="alert">{previewError}</p>}
+ {status && <p className="text-xs text-port-text-muted">{status}</p>}
+ <div className="overflow-hidden rounded border border-port-border bg-black mx-auto" style={{ aspectRatio: aspect, maxHeight: '70vh', maxWidth: '100%' }}>
+ {preview?.html ? (
+ <iframe ref={iframeRef} title="Composition document preview" sandbox="allow-scripts" srcDoc={preview.html} className="h-full w-full" />
+ ) : (
+ <p className="p-3 text-xs text-port-text-muted">{previewError ? '' : 'Building the preview…'}</p>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" className={buttonCls} onClick={togglePlay} disabled={!preview || !audioUrl}>
+ {playing ? <Pause size={14} /> : <Play size={14} />} {playing ? 'Pause' : 'Play'}
+ </button>
+ <label htmlFor="mv-doc-scrub" className="sr-only">Scrub the composition preview</label>
+ <input id="mv-doc-scrub" type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}
+ onChange={(e) => { audioRef.current?.pause(); setPlaying(false); seek(Number(e.target.value)); }}
+ className="min-w-0 flex-1" />
+ <span className="text-xs text-port-text-muted tabular-nums">{t.toFixed(2)}s / {duration.toFixed(1)}s</span>
+ </div>
+ <p className="text-[11px] text-port-text-muted">
+ Renders, draft excerpts, proofs and auto-review all seek this document on song time with the song as the only audio (plus the sound bed, when set).
+ It reads <code>window.PORTOS_MV</code> from <code>portos-mv.js</code>; each scene&apos;s selected take is copied into <code>media/</code>.
+ </p>
+ {audioUrl && <audio ref={audioRef} src={audioUrl} preload="none" className="hidden" onEnded={() => setPlaying(false)} />}
+ </>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
new file mode 100644
index 0000000000..1c5dc941e8
--- /dev/null
+++ b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
@@ -0,0 +1,57 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const api = vi.hoisted(() => ({
+ getMusicVideoCompositionPreview: vi.fn(),
+ getMusicVideoCompositionDocument: vi.fn(),
+ startMusicVideoCompositionTemplate: vi.fn(),
+ importMusicVideoCompositionZip: vi.fn(),
+ importMusicVideoCompositionDirectory: vi.fn(),
+ getMusicVideoCompositionExport: vi.fn(),
+ detachMusicVideoCompositionDocument: vi.fn(),
+ fetchMusicVideoPreviewAsset: vi.fn(),
+}));
+vi.mock('../../services/apiMusicVideo.js', () => api);
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+import DocumentCompositionPanel from './DocumentCompositionPanel.jsx';
+
+const DOCUMENT = { directory: 'music-video/mv-1/composition/doc-a', entry: 'index.html', updatedAt: '2026-01-01T00:00:00.000Z', source: { kind: 'template', name: 'layered' }, files: 9, bytes: 90000 };
+const bare = { id: 'mv-1', name: 'Example', updatedAt: '2026-01-01T00:00:00.000Z', composition: { mode: 'document' } };
+const attached = { ...bare, composition: { mode: 'document', document: DOCUMENT } };
+
+beforeEach(() => {
+ for (const fn of Object.values(api)) fn.mockReset();
+ api.getMusicVideoCompositionPreview.mockResolvedValue({ html: '<!doctype html><p>preview</p>', assets: [], width: 1920, height: 1080, fps: 24, durationSec: 10 });
+ api.startMusicVideoCompositionTemplate.mockResolvedValue({ project: attached, document: DOCUMENT });
+ api.detachMusicVideoCompositionDocument.mockResolvedValue({ project: bare });
+});
+
+describe('DocumentCompositionPanel', () => {
+ it('starts from the template in one click when nothing is attached, and builds no preview', async () => {
+ const onProject = vi.fn();
+ render(<DocumentCompositionPanel project={bare} audioUrl={null} onProject={onProject} onSave={vi.fn()} />);
+ fireEvent.click(screen.getByRole('button', { name: /Start from template/ }));
+ await waitFor(() => expect(onProject).toHaveBeenCalledWith(attached));
+ expect(api.startMusicVideoCompositionTemplate).toHaveBeenCalledWith('mv-1', 'layered', { silent: true });
+ expect(api.getMusicVideoCompositionPreview).not.toHaveBeenCalled();
+ });
+
+ it('shows the attached document in a sandboxed preview and asks twice before replacing or detaching it', async () => {
+ const onProject = vi.fn();
+ render(<DocumentCompositionPanel project={attached} audioUrl={null} onProject={onProject} onSave={vi.fn()} />);
+ expect(screen.getByText(/template · layered · 9 files/)).toBeTruthy();
+ const frame = await screen.findByTitle('Composition document preview');
+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts');
+
+ fireEvent.click(screen.getByRole('button', { name: /Replace with template/ }));
+ expect(api.startMusicVideoCompositionTemplate).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: /Click again to replace/ }));
+ await waitFor(() => expect(api.startMusicVideoCompositionTemplate).toHaveBeenCalledTimes(1));
+
+ fireEvent.click(screen.getByRole('button', { name: /^Detach/ }));
+ expect(api.detachMusicVideoCompositionDocument).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: /Click again to detach/ }));
+ await waitFor(() => expect(onProject).toHaveBeenLastCalledWith(bare));
+ });
+});
diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsx
index e968a309f9..3187f5bf9b 100644
--- a/client/src/components/musicVideo/ProjectToolbar.jsx
+++ b/client/src/components/musicVideo/ProjectToolbar.jsx
@@ -46,6 +46,12 @@ export default function ProjectToolbar({
...(project.lyricCues || []).map((cue) => cue.endSec || cue.startSec || 0),
);
const codeReady = codeMode && !noAudio && codeDuration > 0;
+ // A composition document seeks the song: it needs the analysis's duration
+ // and an attached document; scene media is optional (the document decides).
+ const documentMode = mode === 'document';
+ const documentBlocked = !documentMode ? '' : noAudio ? 'Link a track first'
+ : !(project.audioAnalysis?.durationSec > 0) ? 'Analyze the track first — the document is timed against the song'
+ : !project.composition?.document ? 'Start from the template or import a composition document first' : '';
const footageBlocked = codeMode ? 'Code-rendered style draws the picture in code and does not generate footage' : '';
const nextVersion = (project.version || 1) + 1;
return (
@@ -156,10 +162,12 @@ 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 || (codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}
+ <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || (documentMode ? !!documentBlocked : codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}
title={renderJob.active
? 'Wait for the other project render to finish, or return to it to cancel'
- : codeMode
+ : documentMode
+ ? (documentBlocked || 'Render the composition document over the song')
+ : 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'
diff --git a/client/src/components/musicVideo/TypographyPanel.jsx b/client/src/components/musicVideo/TypographyPanel.jsx
index 3d43cdef8b..d655224ddf 100644
--- a/client/src/components/musicVideo/TypographyPanel.jsx
+++ b/client/src/components/musicVideo/TypographyPanel.jsx
@@ -82,6 +82,7 @@ export default function TypographyPanel({ project, onEditLocal, onSave }) {
{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>}
+ {composition.mode === 'document' && <p className="mt-2 text-port-text-muted">The composition document reads these cues from <code>PORTOS_MV.textCues</code>: the layered template draws Hero cues as kinetic words on their sung times and uses Subtitle cues (or, with none, the timed lyrics) as subtitles.</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.js
index 209ddad126..30ca6a3b3b 100644
--- a/client/src/components/musicVideo/compositionDraft.js
+++ b/client/src/components/musicVideo/compositionDraft.js
@@ -9,6 +9,7 @@ export const RENDER_STYLES = [
['concat', 'Footage'],
['composed', 'Composed'],
['code', 'Code-rendered'],
+ ['document', 'Composition document'],
];
export function compositionDraft(project, patch = {}) {
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 1769ffb52f..5cf35c206f 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -61,6 +61,7 @@ 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 DocumentCompositionPanel from '../components/musicVideo/DocumentCompositionPanel.jsx';
import { compositionDraft } from '../components/musicVideo/compositionDraft.js';
import VisualSpecPanel from '../components/musicVideo/VisualSpecPanel.jsx';
import TreatmentPanel from '../components/musicVideo/TreatmentPanel.jsx';
@@ -940,6 +941,15 @@ export default function MusicVideo() {
onProject={replaceProject}
/>
)}
+ {selected.composition?.mode === 'document' && (
+ <DocumentCompositionPanel
+ key={`document-${selected.id}`}
+ project={selected}
+ audioUrl={projectAudioFilename(selected) ? trackAudioUrl(projectAudioFilename(selected)) : null}
+ onProject={replaceProject}
+ onSave={saveProjectFields}
+ />
+ )}
<RenderStatusPanel
rendering={renderTargetsSelected}
progress={renderJob.progress}
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 0fd64bb779..0b37589c1b 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -317,3 +317,31 @@ export const approveMusicVideoCastAndSets = (id, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/approve`, { method: 'POST', ...options });
export const skipMusicVideoCastAndSets = (id, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/cast-and-sets/skip`, { method: 'POST', ...options });
+
+// ---- Composition document (render style `document`) ----
+// A project-owned HTML composition document rendered over the song. Imports
+// resolve to `{ project, document }`; the manifest to `{ document, available,
+// files, totalBytes }`; the preview to `{ html, assets, width, height, fps, durationSec }`.
+const compositionDocumentPath = (id) => `/music-video/${encodeURIComponent(id)}/composition/document`;
+export const getMusicVideoCompositionDocument = (id, options = {}) => request(compositionDocumentPath(id), options);
+export const importMusicVideoCompositionZip = (id, file, options = {}) => {
+ const body = new FormData();
+ body.append('file', file, file.name || 'composition.zip');
+ return request(`${compositionDocumentPath(id)}/zip`, { method: 'POST', body, ...options });
+};
+export const importMusicVideoCompositionDirectory = (id, directory, options = {}) =>
+ request(`${compositionDocumentPath(id)}/directory`, { method: 'POST', body: JSON.stringify({ directory }), ...options });
+export const startMusicVideoCompositionTemplate = (id, template = 'layered', options = {}) =>
+ request(`${compositionDocumentPath(id)}/template`, { method: 'POST', body: JSON.stringify({ template }), ...options });
+export const getMusicVideoCompositionExport = (id, options = {}) =>
+ request(`${compositionDocumentPath(id)}/export`, { responseType: 'arraybuffer', ...options });
+export const getMusicVideoCompositionPreview = (id, options = {}) => request(`${compositionDocumentPath(id)}/preview`, options);
+export const detachMusicVideoCompositionDocument = (id, options = {}) =>
+ request(compositionDocumentPath(id), { method: 'DELETE', ...options });
+// One preview asset (a scene take under /data, or a document file) as a Blob the
+// page posts into the sandboxed preview, which cannot fetch anything itself.
+export async function fetchMusicVideoPreviewAsset(url) {
+ const response = await fetch(url, { credentials: 'same-origin' });
+ if (!response.ok) throw new Error(`Could not load preview media (${response.status})`);
+ return response.blob();
+}
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index 4d5eb51497..09050c6968 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -228,6 +228,66 @@ project's video backend has a source-audio lip-sync lane (fal.ai today).
The treatment's proof checklist treats readable text and audio alignment as
judgeable only in the final render.
+## Music-video composition documents
+
+A Music Video project can own its whole edit as a composition document: set
+the render style to **Composition document** (`composition.mode: "document"`)
+and start from the shipped `layered` template, import a `.zip`, or copy a
+folder that already sits inside `data/`. Each import is an immutable version
+folder under `data/music-video/<projectId>/composition/`; imports refuse
+symlinks, special files, traversal names and the reserved names below
+(`server/services/musicVideo/compositionDocument.js`). Routes, all under
+`/api/music-video/:id/composition/document`: `GET` (manifest), `POST /zip`
+(multipart `file`), `POST /directory` (`{ directory }`), `POST /template`
+(`{ template: "layered" }`), `GET /export` (zip), `GET /preview`,
+`GET /file?path=` (one document file, served inert), `DELETE` (detach).
+
+Every render of the project — the final render, a draft excerpt, its contact
+sheet and the auto-review excerpt — copies the document into a job-private
+folder under `data/music-video-song-renders/<jobId>/` and adds, before the
+snapshot freezes (`server/services/musicVideo/documentRender.js`):
+
+- `portos-mv.js` — `window.PORTOS_MV = { project: { id, name, aspect }, render:
+ { width, height, fps, frames, durationSec }, song: { durationSec, bpm, beats,
+ downbeats, sections, words }, lyrics, lyricMarkers, scenes: [{ sceneId,
+ label, startSec, endSec, shotMode, visualLayer, stillMove, cardText,
+ cardColor, lyricText, direction, media: { kind, src, inSec, outSec, fps,
+ width, height } | null }], textCues, composition: { mode, style, posterSec,
+ overlay } }`. Load it with `<script src="portos-mv.js">`; the sandbox
+ refuses `fetch`.
+- `song.json` — the same song block the code-rendered mode reads.
+- `media/scene-<sceneId>.<ext>` — each scene's selected take (its clip when
+ it has one, else its still), named by `scenes[].media.src`.
+
+Staged audio/video is streamed from disk by byte range rather than held in
+memory, so a song's worth of footage fits. The document stays on song time:
+an excerpt seeks the same song times as the full render (`startSec + n / fps`,
+snapped to the frame grid). The picture is captured silent and the master song
+(plus the optional sound-design bed) is muxed under it. The project's aspect
+ratio picks the frame; a page authored at another aspect must list that size
+in `portosComposition.formats` (its `layout({ width, height })` hook
+reframes). A `seek(t)` that rejects — for example a `<video>` that failed to
+seek — fails the render and names the frame. A page that draws `<video>`
+frames must await `seeked` before painting; the template seeks to the middle
+of the source frame so a frame boundary can never round to the previous one.
+
+The shipped `layered` template (`server/services/musicVideo/documentTemplates/layered/`)
+draws each scene's take with a gentle camera move and beat punch-ins, film
+grain and a vignette, a title card for card scenes, subtitles (the subtitle
+text cues, else the timed lyrics), kinetic hero words for cues flagged
+`hero`, and an optional HUD from `composition.overlay` (title lines, a meter
+with keyframes, a ticker, timecode). It declares all three frame sizes. Its
+fonts (IBM Plex Mono, IBM Plex Sans Condensed, Big Shoulders Stencil
+Display) are SIL Open Font License; the licenses ship beside them. Once
+copied into a project the files are the project's to edit — project-specific
+cards belong there, not in the template.
+
+The in-app preview is a self-contained `srcdoc` in an opaque-origin sandbox
+with no network: the server inlines the document's scripts, stylesheets and
+small assets, the PortOS page fetches the larger media on the user's behalf
+and posts it in as Blobs (`window.PORTOS_MV_ASSETS` resolves to
+`{ src: blobUrl }`), and the scrubber posts `portos-mv:seek` messages.
+
## Launch-video admission (API foundation)
`POST /api/html-composition/render` accepts `launchVideo: { targetDurationSec: 20 }`.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index d1938dffdc..a74175c653 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -189,6 +189,7 @@ goal data together; interrupted intents remain retryable after restore.
- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes, tracked in `data/video-history.json`; indexed into `media_assets` keyed `video:<jobId>`. History file remains authoritative.
- Game asset manifests — immutable `data/games/{id}/manifests/game-assets-v{N}.json` artifacts reference sprite atlas and music-library bytes by stable path + SHA-256; the `games` DB record owns the current pointer and history. Both halves are backed up: PostgreSQL by the required dump, manifests and referenced media by the rsync snapshot.
- Music Video development artifacts ("ingredients": a Cast & Sets check-in sheet, animatic, treatment, storyboard) — each version is an immutable file under `data/music-video/{projectId}/dev/{artifactId}/v{N}.{html,md,mp4,png,jpg}`; the `musicVideoProject` record owns the metadata (`devArtifacts[]`: kind, title, review status, notes, version history with each version's data-relative path). Versions are never overwritten and deletes are soft, so a clone that carried the metadata keeps valid pointers. The metadata is **wire-local** (stripped by `stripMusicVideoLocalRenderPins`, restored over a newer remote by `mergeProjectRecord`) because the bytes are not in the project's peer-sync asset manifest; both halves are backed up (PostgreSQL dump + rsync snapshot). Adapter: `server/services/musicVideo/devArtifactStore.js`.
+- Music Video composition documents (render style `document`) — each import (zip, a folder inside `data/`, or the shipped `layered` template) is one immutable version folder `data/music-video/{projectId}/composition/{versionId}/` (index.html + scripts, fonts, media); the `musicVideoProject` record's `composition.document` holds the data-relative pointer plus source/size metadata. A clone shares the pointer; a version no project (live or tombstoned) points at is pruned on the next import or detach. The pointer is **wire-local** like the development artifacts (stripped by `stripMusicVideoLocalRenderPins`, restored by `mergeProjectRecord`) — a peer keeps its own and refuses to render without one. Renders stage a job-private copy under `data/music-video-song-renders/{jobId}/` (swept at boot, excluded from backups). Adapter: `server/services/musicVideo/compositionDocument.js`.
- Beeper attachment mirror (#37) — message media stays on disk under `data/beeper/attachments/<sha256 prefix>/<sha256>.<ext>` (content-addressed, so one forwarded photo is one file); `beeper_attachments` in PostgreSQL holds the metadata plus `local_path` / `sha256` / `byte_length` / `keep`. Machine-local and **never federated** (message content is PII — see the message-bodies ADR); a lazy CACHE rather than an archive, so it is excluded from backup by default (overridable) while the rows that describe it ride the Postgres dump. The bytes are re-fetchable from Beeper Desktop for as long as the source network still holds the media, and the surface renders a labelled reference when it does not.
- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes. **Still `data/media-collections/*` JSON today** — a follow-up slice of #1000.
diff --git a/server/lib/README.md b/server/lib/README.md
index 3f0e1eb910..370bef94d2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -381,6 +381,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. `classifyLoraKeyLayoutFromHeader(header)` / `classifyLoraKeyLayout(path)` classify the key layout as `LORA_KEY_LAYOUTS` (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`, `null` = unreadable), `isKnownLoraKeyLayout(layout)` validates a layout read back out of persisted state, and `videoLoraLayoutIssue(layout)` returns the user-facing reason a layout can't fuse into the LTX-2 video transformer (or `null` when it can). |
| `loraEffect.js` | LoRA adapter-effect report rules — the JS half of the `scripts/lora_effect_probe.py` diagnostic (#4872). `client/src/lib/loraEffect.js` re-exports `LORA_EFFECT_STATUSES` from here; `loraEffect.test.js` holds `LORA_EFFECT_PROBE_VERSION` in lockstep with the probe`s `PROBE_VERSION` — drift silently disables the cache. `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`) + `isKnownLoraEffectStatus`; `normalizeLoraEffectReport(raw,{sizeBytes,mtimeMs,measuredAt})` coerces every non-finite number to `null`, drops statistics when nothing was measured so "no data" can never read as "measured 0.0", and downgrades a `zero` status that no measurement backs; `readCachedLoraEffectReport(raw,{sizeBytes,mtimeMs})` returns a stored report only while its probe version, file size AND mtime all still match, which is what lets `listLoras()` surface one without ever spawning a probe; `loraEffectIssue(report)` is the user-facing refusal phrase for a measured entirely-zero adapter and `null` for EVERY other status; `formatLoraEffect(report)` is the one-line log/UI summary. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
+| `zipArchive.js` | Buffer-backed ZIP reader over the central directory — `readZipArchive(buffer, { maxEntries })` lists members with their raw names, `isDirectory`/`isSymlink` (Unix mode bits) and a lazy CRC-checked `read()`; `unsafeZipEntryName(name)` names why a member path is not a plain relative path (absolute, `..`, backslash, NUL). For imports that must refuse traversal and symlink members rather than rewrite them. |
| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `collectZipEntry(entry, maxBytes?)` buffers one `parseZip` entry into a Buffer (size-capped); `collectZipEntries(path, { match, onMatch, maxBytes? })` owns the multi-entry import lifecycle (teardown, autodrain, per-entry await) leaving callers only match/parse; `isZipUpload(file)` predicate for an uploaded ZIP; `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |
| `zipWriter.js` | Minimal ZIP writer — `createZip(entries)` builds a stored (uncompressed) archive Buffer that round-trips through `parseZip`; `crc32(buf)` is the dependency-free checksum it uses. |
| `assetHash.js` | Cross-transport SHA-256 cache for `data/images/*` — persists hashes in the asset's `.metadata.json` sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. `sidecarGenParamsHash` canonically hashes a sidecar's gen-params (excludes the machine-local `sha256` cache block) for cross-machine sidecar-convergence comparisons. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 4cf56c1f39..09826e0828 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -329,6 +329,7 @@ export * from './safetensors.js';
export * from './loraEffect.js';
export * from './assetHash.js';
export * from './pdfImageEmbed.js';
+export * from './zipArchive.js';
export * from './zipStream.js';
export * from './zipWriter.js';
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 8d32899eac..bc11677485 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -263,7 +263,15 @@ export const musicVideoLyricsAlignSchema = z.object({
// 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'];
+// `document` renders a project-owned HTML composition document (its own
+// folder under data/music-video/<projectId>/composition/) seeked over the
+// song; see services/musicVideo/compositionDocument.js and documentRender.js.
+export const MUSIC_VIDEO_COMPOSITION_MODES = ['concat', 'composed', 'code', 'document'];
+// Shipped starting points a project can copy into its document folder.
+export const MUSIC_VIDEO_DOCUMENT_TEMPLATES = ['layered'];
+export const MUSIC_VIDEO_DOCUMENT_SOURCES = ['zip', 'directory', 'template'];
+// One immutable document version: data/music-video/<projectId>/composition/<versionId>.
+export const MUSIC_VIDEO_DOCUMENT_DIRECTORY = /^music-video\/[A-Za-z0-9_-]{1,100}\/composition\/[A-Za-z0-9_-]{1,100}$/;
// 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;
@@ -305,6 +313,35 @@ export const musicVideoCodeGenerateSchema = z.object({
model: z.string().max(200).optional(),
}).strict();
+// Where the project's composition document lives. Set only by the import
+// routes; a PATCH that carries it back is ignored (the stored pointer wins).
+export const musicVideoCompositionDocumentSchema = z.object({
+ directory: z.string().max(300).regex(MUSIC_VIDEO_DOCUMENT_DIRECTORY, 'directory is a composition document version folder'),
+ entry: z.literal('index.html').optional(),
+ updatedAt: z.string().max(40).nullable().optional(),
+ source: z.object({
+ kind: z.enum(MUSIC_VIDEO_DOCUMENT_SOURCES),
+ name: z.string().max(200).nullable().optional(),
+ }).strict().nullable().optional(),
+ files: z.number().int().min(0).max(4096).optional(),
+ bytes: z.number().int().min(0).optional(),
+}).strict();
+
+// The optional HUD block a composition document may draw (the shipped
+// layered template reads it from PORTOS_MV.composition.overlay).
+export const musicVideoCompositionOverlaySchema = z.object({
+ enabled: z.boolean().optional(),
+ titleLines: z.array(z.string().max(120)).max(4).optional(),
+ meter: z.object({
+ label: z.string().max(40).optional(),
+ // [songSec, percent] pairs, eased between.
+ keyframes: z.array(z.tuple([z.number().min(0).max(36000), z.number().min(0).max(100)])).max(200).optional(),
+ }).strict().nullable().optional(),
+ ticker: z.array(z.string().max(200)).max(40).optional(),
+ timecode: z.boolean().optional(),
+ timecodeStartSec: z.number().min(0).max(86400).optional(),
+}).strict();
+
// Replaced whole by a project PATCH (the editor sends the full manifest).
export const musicVideoCompositionSchema = z.object({
version: z.literal(1).optional(),
@@ -316,6 +353,22 @@ export const musicVideoCompositionSchema = z.object({
}).strict().optional(),
posterSec: timedSec,
codeVideo: musicVideoCodeVideoSchema.nullable().optional(),
+ document: musicVideoCompositionDocumentSchema.nullable().optional(),
+ overlay: musicVideoCompositionOverlaySchema.nullable().optional(),
+}).strict();
+
+// A relative folder inside data/ to copy a composition document from.
+export const musicVideoDocumentDirectoryImportSchema = z.object({
+ directory: z.string().min(1).max(1024).refine((value) => !value.startsWith('/') && !value.includes('\\') && !value.includes(':')
+ && !value.includes('\0') && !value.split('/').some((part) => part === '..' || part === '.' || !part), 'directory must be a relative path inside data'),
+}).strict();
+
+export const musicVideoDocumentFileQuerySchema = z.object({
+ path: z.string().min(1).max(512),
+}).strict();
+
+export const musicVideoDocumentTemplateSchema = z.object({
+ template: z.enum(MUSIC_VIDEO_DOCUMENT_TEMPLATES).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.js
index 451784021f..ffa68ec536 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -638,7 +638,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// live under this install's data/music-video/ and are not in the project's
// asset manifest, so they are never sent. What an approved check-in writes
// into ordinary fields (visual-spec references, concept subjects) syncs.
- musicVideoProjects: 9,
+ // v10 = composition mode `document` (a project-owned HTML composition
+ // document) and `composition.overlay` (its HUD settings). A v9 peer's
+ // normalizeComposition collapses the unknown mode to `concat` and drops the
+ // overlay, and its next composition edit would last-writer-wins both losses
+ // back, so the gate rejects the ahead transfer. The document pointer itself
+ // (`composition.document`) is wire-local like `devArtifacts`: its files live
+ // under this install's data/music-video/<projectId>/composition/ and are not
+ // in the asset manifest, so a peer keeps its own pointer (or none, and then
+ // refuses to render with COMPOSITION_DOCUMENT_MISSING).
+ musicVideoProjects: 10,
// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)
// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,
// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 3296aee1ba..970b8862d5 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -57,6 +57,14 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = tru
devArtifacts: _devArtifacts, castAndSets: _castAndSets,
...shared
} = record;
+ // A composition document names a folder on this install only
+ // (services/musicVideo/compositionDocument.js); the render mode and HUD
+ // settings still sync, and a peer without the files refuses to render.
+ if (shared.composition && typeof shared.composition === 'object' && !Array.isArray(shared.composition)
+ && Object.hasOwn(shared.composition, 'document')) {
+ const { document: _document, ...composition } = shared.composition;
+ shared.composition = composition;
+ }
if (stripVideoBackend && shared.videoSettings
&& typeof shared.videoSettings === 'object' && !Array.isArray(shared.videoSettings)) {
const { backend: _backend, ...sharedVideoSettings } = shared.videoSettings;
diff --git a/server/lib/zipArchive.js b/server/lib/zipArchive.js
new file mode 100644
index 0000000000..904ab86dcd
--- /dev/null
+++ b/server/lib/zipArchive.js
@@ -0,0 +1,111 @@
+/**
+ * Buffer-backed ZIP reader driven by the central directory.
+ *
+ * `zipStream.js` streams local headers and silently strips `..` segments, which
+ * suits imports that match members by name. An import that unpacks a whole
+ * tree needs the opposite: the authoritative names and the Unix mode bits the
+ * central directory carries, so it can REFUSE a traversal name or a symlink
+ * member instead of quietly rewriting it. Stored (0) and deflate (8) members;
+ * ZIP64 and encrypted archives are refused.
+ *
+ * const entries = readZipArchive(buffer); // [{ name, isDirectory, isSymlink, size, read() }]
+ * const problem = unsafeZipEntryName(entries[0].name); // null when the name is a plain relative path
+ */
+
+import { inflateRawSync } from 'zlib';
+import { crc32 } from './zipWriter.js';
+
+const EOCD_SIG = 0x06054b50;
+const CENTRAL_SIG = 0x02014b50;
+const LOCAL_SIG = 0x04034b50;
+const ZIP64_MARK = 0xffffffff;
+const S_IFMT = 0o170000;
+const S_IFLNK = 0o120000;
+const S_IFDIR = 0o040000;
+const UNIX_HOST = 3;
+
+function findEndOfCentralDirectory(buffer) {
+ // The EOCD record is 22 bytes plus a comment of up to 65535 bytes.
+ const floor = Math.max(0, buffer.length - 22 - 0xffff);
+ for (let i = buffer.length - 22; i >= floor; i--) {
+ if (buffer.readUInt32LE(i) === EOCD_SIG) return i;
+ }
+ return -1;
+}
+
+/**
+ * Why `name` is not a plain relative member path, or null when it is.
+ * Refuses absolute paths, drive letters, backslashes, NUL, and any empty,
+ * `.` or `..` segment (a trailing `/` marks a directory and is allowed).
+ */
+export function unsafeZipEntryName(name) {
+ if (typeof name !== 'string' || !name) return 'empty name';
+ if (name.includes('\0')) return 'NUL in name';
+ if (name.includes('\\')) return 'backslash in name';
+ if (name.startsWith('/') || /^[A-Za-z]:/.test(name)) return 'absolute path';
+ const parts = name.replace(/\/$/, '').split('/');
+ if (parts.some((part) => part === '..')) return 'parent-directory segment';
+ if (parts.some((part) => part === '.' || part === '')) return 'empty or dot segment';
+ return null;
+}
+
+/**
+ * Parse `buffer`'s central directory. Each entry exposes the raw member name,
+ * `isDirectory`, `isSymlink` (Unix mode S_IFLNK), sizes, and a lazy `read()`
+ * that inflates and CRC-checks the member. Throws on a malformed archive, a
+ * ZIP64/encrypted member, or more than `maxEntries` members.
+ */
+export function readZipArchive(buffer, { maxEntries = 4096 } = {}) {
+ if (!Buffer.isBuffer(buffer) || buffer.length < 22) throw new Error('Not a ZIP archive');
+ const eocd = findEndOfCentralDirectory(buffer);
+ if (eocd < 0) throw new Error('Not a ZIP archive (no end of central directory)');
+ const count = buffer.readUInt16LE(eocd + 10);
+ const cdSize = buffer.readUInt32LE(eocd + 12);
+ const cdOffset = buffer.readUInt32LE(eocd + 16);
+ if (count === 0xffff || cdOffset === ZIP64_MARK || cdSize === ZIP64_MARK) throw new Error('ZIP64 archives are not supported');
+ if (count > maxEntries) throw new Error(`ZIP has more than ${maxEntries} members`);
+ if (cdOffset + cdSize > eocd) throw new Error('Malformed ZIP central directory');
+ const entries = [];
+ let at = cdOffset;
+ for (let i = 0; i < count; i++) {
+ if (at + 46 > buffer.length || buffer.readUInt32LE(at) !== CENTRAL_SIG) throw new Error('Malformed ZIP central directory');
+ const madeBy = buffer.readUInt16LE(at + 4) >> 8;
+ const flags = buffer.readUInt16LE(at + 8);
+ const method = buffer.readUInt16LE(at + 10);
+ const crc = buffer.readUInt32LE(at + 16);
+ const compressedSize = buffer.readUInt32LE(at + 20);
+ const size = buffer.readUInt32LE(at + 24);
+ const nameLen = buffer.readUInt16LE(at + 28);
+ const extraLen = buffer.readUInt16LE(at + 30);
+ const commentLen = buffer.readUInt16LE(at + 32);
+ const externalAttrs = buffer.readUInt32LE(at + 38);
+ const localOffset = buffer.readUInt32LE(at + 42);
+ const name = buffer.subarray(at + 46, at + 46 + nameLen).toString('utf8');
+ at += 46 + nameLen + extraLen + commentLen;
+ if (compressedSize === ZIP64_MARK || size === ZIP64_MARK || localOffset === ZIP64_MARK) throw new Error('ZIP64 archives are not supported');
+ if (flags & 0x1) throw new Error('Encrypted ZIP members are not supported');
+ const mode = madeBy === UNIX_HOST ? (externalAttrs >>> 16) & S_IFMT : 0;
+ const isDirectory = name.endsWith('/') || mode === S_IFDIR || (externalAttrs & 0x10) === 0x10;
+ entries.push({
+ name,
+ isDirectory,
+ isSymlink: mode === S_IFLNK,
+ size,
+ compressedSize,
+ method,
+ read() {
+ if (localOffset + 30 > buffer.length || buffer.readUInt32LE(localOffset) !== LOCAL_SIG) throw new Error(`Malformed ZIP member ${name}`);
+ const start = localOffset + 30 + buffer.readUInt16LE(localOffset + 26) + buffer.readUInt16LE(localOffset + 28);
+ const raw = buffer.subarray(start, start + compressedSize);
+ if (raw.length !== compressedSize) throw new Error(`Truncated ZIP member ${name}`);
+ let data;
+ if (method === 0) data = raw;
+ else if (method === 8) data = inflateRawSync(raw, { maxOutputLength: Math.max(1, size) });
+ else throw new Error(`Unsupported ZIP compression method ${method} for ${name}`);
+ if (data.length !== size || crc32(data) !== crc) throw new Error(`ZIP member ${name} failed its checksum`);
+ return data;
+ },
+ });
+ }
+ return entries;
+}
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 0bc2b7d02b..254bb35b72 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -51,6 +51,9 @@ import {
musicVideoDevArtifactFileQuerySchema,
musicVideoCastAndSetsStartSchema,
musicVideoCastAndSetsRegenerateSchema,
+ musicVideoDocumentDirectoryImportSchema,
+ musicVideoDocumentFileQuerySchema,
+ musicVideoDocumentTemplateSchema,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
@@ -103,6 +106,19 @@ import {
startProduction, resumeProduction, stopProduction, cancelProduction, getProduction,
} from '../services/musicVideo/productionService.js';
import { planProject } from '../services/musicVideo/planner.js';
+import {
+ DOCUMENT_ZIP_MAX_BYTES,
+ detachDocument,
+ documentMimeType,
+ exportDocumentZip,
+ importDocumentDirectory,
+ importDocumentTemplate,
+ importDocumentZip,
+ readDocumentManifest,
+ resolveDocumentFile,
+} from '../services/musicVideo/compositionDocument.js';
+import { buildDocumentPreview } from '../services/musicVideo/documentPreview.js';
+import { isZipUpload } from '../lib/zipStream.js';
import { parseLyricCues } from '../services/musicVideo/timedText.js';
import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';
import { importTrackLyrics, MAX_LYRIC_CUES } from '../services/musicVideo/trackLyrics.js';
@@ -476,6 +492,78 @@ router.post('/:id/code/sections/:sectionId/regenerate', asyncHandler(async (req,
res.json(await regenerateMusicVideoCodeSection(req.params.id, req.params.sectionId, body));
}));
+// --- Composition document (render style `document`) ---
+// A project-owned HTML composition document (services/musicVideo/
+// compositionDocument.js): import a zip, a folder inside data/, or the shipped
+// template; export it; read its manifest; preview it. Files stay on this
+// install; the record keeps a pointer to the current immutable version.
+const requireProject = async (id) => {
+ const project = await getProject(id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ return project;
+};
+
+const documentZipUpload = uploadSingle('file', {
+ limits: { fileSize: DOCUMENT_ZIP_MAX_BYTES },
+ fileFilter: (_req, file, cb) => {
+ if (isZipUpload(file)) cb(null, true);
+ else cb(new ServerError('Upload a .zip of the composition document', { status: 400, code: 'VALIDATION_ERROR' }));
+ },
+});
+
+router.get('/:id/composition/document', asyncHandler(async (req, res) => {
+ res.json(await readDocumentManifest(await requireProject(req.params.id)));
+}));
+
+router.post('/:id/composition/document/zip', documentZipUpload, asyncHandler(async (req, res) => {
+ if (!req.file) throw new ServerError('No file uploaded (multipart field "file")', { status: 400, code: 'VALIDATION_ERROR' });
+ try {
+ res.status(201).json(await importDocumentZip(req.params.id, req.file.path, req.file.originalname));
+ } finally {
+ await unlink(req.file.path).catch(() => {});
+ }
+}));
+
+router.post('/:id/composition/document/directory', asyncHandler(async (req, res) => {
+ const { directory } = validateRequest(musicVideoDocumentDirectoryImportSchema, req.body || {});
+ res.status(201).json(await importDocumentDirectory(req.params.id, directory));
+}));
+
+router.post('/:id/composition/document/template', asyncHandler(async (req, res) => {
+ const { template } = validateRequest(musicVideoDocumentTemplateSchema, req.body || {});
+ res.status(201).json(await importDocumentTemplate(req.params.id, template));
+}));
+
+router.get('/:id/composition/document/export', asyncHandler(async (req, res) => {
+ const { zip, filename } = await exportDocumentZip(await requireProject(req.params.id));
+ res.set('Content-Type', 'application/zip');
+ res.set('Content-Disposition', `attachment; filename="${filename}"`);
+ res.send(zip);
+}));
+
+router.get('/:id/composition/document/preview', asyncHandler(async (req, res) => {
+ res.json(await buildDocumentPreview(await requireProject(req.params.id)));
+}));
+
+// One document file, for the preview's asset bridge (fetched by the PortOS
+// page, never loaded by the sandboxed preview itself). Served inert: a
+// sandbox CSP, no sniffing, same-origin only.
+router.get('/:id/composition/document/file', asyncHandler(async (req, res) => {
+ const { path } = validateRequest(musicVideoDocumentFileQuerySchema, req.query || {});
+ const abs = await resolveDocumentFile(await requireProject(req.params.id), path);
+ res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
+ res.setHeader('Cache-Control', 'private, no-cache');
+ res.type(documentMimeType(path));
+ res.sendFile(abs, { dotfiles: 'allow' });
+}));
+
+router.delete('/:id/composition/document', asyncHandler(async (req, res) => {
+ await requireProject(req.params.id);
+ res.json(await detachDocument(req.params.id));
+}));
+
// --- 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/routes/musicVideoCompositionDocument.test.js b/server/routes/musicVideoCompositionDocument.test.js
new file mode 100644
index 0000000000..1acab659eb
--- /dev/null
+++ b/server/routes/musicVideoCompositionDocument.test.js
@@ -0,0 +1,189 @@
+/**
+ * Music Video composition documents, through the real router, the real
+ * multipart parser, compositionDocument.js and the real file-backed project
+ * store: zip / data-folder / template import, manifest, export, preview, the
+ * file bridge, and the refusals (traversal, symlinks, reserved names).
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import express from 'express';
+import { existsSync, readdirSync, rmSync } from 'fs';
+import { mkdir, symlink, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { createZip } from '../lib/zipWriter.js';
+import { readZipArchive } from '../lib/zipArchive.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+const ROOT = () => lazyTempDataRoot('mv-composition-document-route-test-');
+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));
+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+
+const { default: musicVideoRoutes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+
+const PAGE = '<!doctype html><html><head><link rel="stylesheet" href="style.css"></head><body><script src="portos-mv.js"></script><script src="app.js"></script></body></html>';
+const FILES = { 'index.html': PAGE, 'app.js': 'globalThis.portosComposition = { durationSec: 1, fps: 12, width: 1280, height: 720, seek() {} };', 'style.css': 'body { background: url(bg.png); }', 'bg.png': Buffer.from([137, 80, 78, 71]) };
+
+// A symlink member: the central directory carries a Unix S_IFLNK mode.
+function withSymlinkMember(zip, name) {
+ const buf = Buffer.from(zip);
+ for (let at = 0; at < buf.length - 46; at++) {
+ if (buf.readUInt32LE(at) !== 0x02014b50) continue;
+ const nameLen = buf.readUInt16LE(at + 28);
+ if (buf.subarray(at + 46, at + 46 + nameLen).toString() !== name) continue;
+ buf.writeUInt16LE((3 << 8) | 20, at + 4);
+ buf.writeUInt32LE((0o120777 << 16) >>> 0, at + 38);
+ }
+ return buf;
+}
+
+async function uploadZip(projectId, zip, name = 'doc.zip') {
+ const form = new FormData();
+ form.append('file', new Blob([zip], { type: 'application/zip' }), name);
+ const encoded = new Request('http://localhost/', { method: 'POST', body: form });
+ return request(app).post(`/api/music-video/${projectId}/composition/document/zip`)
+ .set('content-type', encoded.headers.get('content-type'))
+ .send(Buffer.from(await encoded.arrayBuffer()));
+}
+
+async function fetchBytes(path) {
+ const server = await new Promise((resolve) => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ try {
+ const res = await fetch(`http://127.0.0.1:${server.address().port}${path}`);
+ return { status: res.status, headers: Object.fromEntries(res.headers.entries()), bytes: Buffer.from(await res.arrayBuffer()) };
+ } finally { await new Promise((resolve) => server.close(resolve)); }
+}
+
+const versionsOf = (projectId) => {
+ const dir = join(ROOT(), 'music-video', projectId, 'composition');
+ return existsSync(dir) ? readdirSync(dir).sort() : [];
+};
+
+let project;
+beforeEach(async () => {
+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });
+ rmSync(join(ROOT(), 'music-video'), { recursive: true, force: true });
+ rmSync(join(ROOT(), 'compositions'), { recursive: true, force: true });
+ project = await projects.createProject({ name: 'Example Video' });
+});
+afterAll(cleanupTempDataRoots);
+
+describe('music-video composition documents', () => {
+ it('imports a zip (one top folder), switches the render style, lists, exports, previews and serves its files inert', async () => {
+ const zip = createZip(Object.entries(FILES).map(([name, data]) => ({ name: `my-video/${name}`, data })), { compress: true });
+ const created = await uploadZip(project.id, zip, 'my-video.zip');
+ expect(created.status).toBe(201);
+ const { document } = created.body;
+ expect(document).toMatchObject({ entry: 'index.html', source: { kind: 'zip', name: 'my-video.zip' }, files: 4 });
+ expect(document.directory).toMatch(new RegExp(`^music-video/${project.id}/composition/doc-`));
+ expect(created.body.project.composition).toMatchObject({ mode: 'document', document });
+ // Persisted, not just echoed.
+ expect((await projects.getProject(project.id)).composition.document).toEqual(document);
+
+ const manifest = await request(app).get(`/api/music-video/${project.id}/composition/document`);
+ expect(manifest.body).toMatchObject({ available: true, totalBytes: expect.any(Number) });
+ expect(manifest.body.files.map((f) => f.path)).toEqual(['app.js', 'bg.png', 'index.html', 'style.css']);
+
+ const exported = await fetchBytes(`/api/music-video/${project.id}/composition/document/export`);
+ expect(exported.status).toBe(200);
+ expect(exported.headers['content-type']).toBe('application/zip');
+ const round = Object.fromEntries(readZipArchive(exported.bytes).map((entry) => [entry.name, entry.read()]));
+ expect(Object.keys(round).sort()).toEqual(Object.keys(FILES).sort());
+ expect(round['app.js'].toString()).toBe(FILES['app.js']);
+
+ const preview = await request(app).get(`/api/music-video/${project.id}/composition/document/preview`);
+ expect(preview.status).toBe(200);
+ // Self-contained: no network, the stylesheet/script/asset inlined, PORTOS_MV injected, portos-mv.js dropped.
+ expect(preview.body.html).toContain("default-src 'none'");
+ expect(preview.body.html).toContain('window.PORTOS_MV = ');
+ expect(preview.body.html).toContain(FILES['app.js']);
+ expect(preview.body.html).toContain('url("data:image/png;base64,');
+ expect(preview.body.html).not.toContain('src="portos-mv.js"');
+ expect(preview.body).toMatchObject({ width: 1920, height: 1080, fps: 24 });
+
+ const file = await request(app).get(`/api/music-video/${project.id}/composition/document/file?path=app.js`);
+ expect(file.status).toBe(200);
+ expect(file.text).toBe(FILES['app.js']);
+ expect(file.headers['content-security-policy']).toMatch(/^sandbox;/);
+ expect(file.headers['x-content-type-options']).toBe('nosniff');
+ const escape = await request(app).get(`/api/music-video/${project.id}/composition/document/file?path=${encodeURIComponent('../../../music-video-projects.json')}`);
+ expect(escape.status).toBe(400);
+ });
+
+ it('refuses a zip member that climbs out of the document and writes nothing', async () => {
+ const zip = createZip([{ name: 'index.html', data: PAGE }, { name: '../../escape.js', data: 'x' }]);
+ const res = await uploadZip(project.id, zip);
+ expect(res.status).toBe(422);
+ expect(res.body.code).toBe('COMPOSITION_DOCUMENT_TRAVERSAL');
+ expect(versionsOf(project.id)).toEqual([]);
+ expect(existsSync(join(ROOT(), 'escape.js'))).toBe(false);
+ expect((await projects.getProject(project.id)).composition).toBeNull();
+ });
+
+ it('refuses a zip symlink member', async () => {
+ const zip = withSymlinkMember(createZip([{ name: 'index.html', data: PAGE }, { name: 'secrets.json', data: '../../music-video-projects.json' }]), 'secrets.json');
+ const res = await uploadZip(project.id, zip);
+ expect(res.status).toBe(422);
+ expect(res.body.code).toBe('COMPOSITION_DOCUMENT_SYMLINK');
+ expect(versionsOf(project.id)).toEqual([]);
+ });
+
+ it('copies a folder inside data, refusing symlinks, reserved names and paths outside data', async () => {
+ const src = join(ROOT(), 'compositions', 'hand-built');
+ await mkdir(join(src, 'assets'), { recursive: true });
+ for (const [name, data] of Object.entries(FILES)) await writeFile(join(src, name), data);
+ const ok = await request(app).post(`/api/music-video/${project.id}/composition/document/directory`).send({ directory: 'compositions/hand-built' });
+ expect(ok.status).toBe(201);
+ expect(ok.body.document.source).toEqual({ kind: 'directory', name: 'compositions/hand-built' });
+
+ await symlink(join(ROOT(), 'music-video-projects.json'), join(src, 'assets', 'leak.json'));
+ const linked = await request(app).post(`/api/music-video/${project.id}/composition/document/directory`).send({ directory: 'compositions/hand-built' });
+ expect(linked.status).toBe(422);
+ expect(linked.body.code).toBe('COMPOSITION_DOCUMENT_SYMLINK');
+ rmSync(join(src, 'assets', 'leak.json'));
+
+ await writeFile(join(src, 'portos-mv.js'), 'window.PORTOS_MV = {};');
+ const reserved = await request(app).post(`/api/music-video/${project.id}/composition/document/directory`).send({ directory: 'compositions/hand-built' });
+ expect(reserved.status).toBe(422);
+ rmSync(join(src, 'portos-mv.js'));
+
+ const outside = await request(app).post(`/api/music-video/${project.id}/composition/document/directory`).send({ directory: '../elsewhere' });
+ expect(outside.status).toBe(400);
+ // Only the first import produced a version.
+ expect(versionsOf(project.id)).toHaveLength(1);
+ });
+
+ it('starts from the shipped layered template, and a re-import prunes the version nothing points at', async () => {
+ const first = await request(app).post(`/api/music-video/${project.id}/composition/document/template`).send({});
+ expect(first.status).toBe(201);
+ const dir = join(ROOT(), first.body.document.directory);
+ for (const name of ['index.html', 'engine.js', 'fonts/LICENSE-IBM-Plex.txt', 'fonts/LICENSE-Big-Shoulders.txt', 'fonts/big-shoulders-stencil-display-900.woff2']) {
+ expect(existsSync(join(dir, name)), name).toBe(true);
+ }
+ const second = await uploadZip(project.id, createZip(Object.entries(FILES).map(([name, data]) => ({ name, data }))));
+ expect(second.status).toBe(201);
+ expect(versionsOf(project.id)).toEqual([second.body.document.directory.split('/').pop()]);
+
+ // A PATCH that forges the pointer keeps the stored one.
+ const patched = await request(app).patch(`/api/music-video/${project.id}`).send({
+ composition: { ...second.body.project.composition, document: { ...second.body.document, directory: first.body.document.directory } },
+ });
+ expect(patched.status).toBe(200);
+ expect(patched.body.composition.document).toEqual(second.body.document);
+
+ const detached = await request(app).delete(`/api/music-video/${project.id}/composition/document`);
+ expect(detached.status).toBe(200);
+ expect(detached.body.project.composition).not.toHaveProperty('document');
+ expect(versionsOf(project.id)).toEqual([]);
+ const missing = await request(app).get(`/api/music-video/${project.id}/composition/document/export`);
+ expect(missing.status).toBe(409);
+ expect(missing.body.code).toBe('COMPOSITION_DOCUMENT_MISSING');
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index 439187303b..bab2fb303d 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -173,6 +173,7 @@ export const DEFAULT_EXCLUDES = [
{ path: '/composition-proofs/', reason: 'HTML-composition contact-sheet proofs — review stills, re-rendered from the composition source', overridable: true },
{ path: '/code-animation-exports/', reason: 'Code Animation frame-exact export staging — the stored HTML plus render shim, staged once per export', overridable: true },
{ path: '/music-video-compositions/', reason: 'In-flight music-video typography overlay scratch — removed when its render ends and swept at boot', overridable: false },
+ { path: '/music-video-song-renders/', reason: 'In-flight music-video composition renders (a staged copy of the document plus scene media) — removed when the render ends and swept at boot', overridable: false },
{ path: '/launch-videos/*/*/proofs/', reason: 'Launch-video critique-loop contact sheets — re-rendered from the run composition', overridable: true },
{ path: '/cache/', reason: 'Remote-API metadata and licensed reading caches — regenerable on demand, and stale on restore anyway', overridable: false },
// Anchored with a leading `/`, like every entry here. The manifest describes
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index b22a940149..09ba0e25c3 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -83,8 +83,9 @@ export const CATEGORIES = {
// version of a Cast & Sets sheet, animatic, treatment or storyboard, one
// immutable file each, referenced by the project record. Not deletable from
// here: a purge would strand those references (delete the artifact instead).
- 'music-video': { label: 'Music Video Development Files', description: 'Versioned development artifacts (check-in sheets, animatics, treatments) referenced by Music Video projects', archivable: true, deletable: false },
+ 'music-video': { label: 'Music Video Development Files', description: 'Versioned development artifacts (check-in sheets, animatics, treatments) and composition documents referenced by Music Video projects', archivable: true, deletable: false },
'music-video-compositions': { label: 'Music Video Overlay Scratch', description: 'Typography overlay frames for an in-flight composed music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
+ 'music-video-song-renders': { label: 'Music Video Composition Render Scratch', description: 'A staged copy of a composition document plus its scene media for an in-flight music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
'code-animations': { label: 'Code Animations', description: 'Generated animation HTML retained with its job history — the only copy of provider-generated work', archivable: true, deletable: false },
'code-animation-exports': { label: 'Code Animation Export Staging', description: 'Animation HTML plus the frame-exact render shim, staged once per MP4 export — safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
'commission-feedback': { label: 'Commission Feedback', description: 'Reactions on creative commissions (file mirror of the Postgres store)', archivable: true, deletable: false },
diff --git a/server/services/htmlComposition/browser.js b/server/services/htmlComposition/browser.js
index 9187bfeae5..ca5c8b7687 100644
--- a/server/services/htmlComposition/browser.js
+++ b/server/services/htmlComposition/browser.js
@@ -1,11 +1,11 @@
import WebSocket from 'ws';
-import { readFile, readdir, realpath, stat } from 'node:fs/promises';
+import { open, readFile, readdir, realpath, stat } from 'node:fs/promises';
import { resolve, relative, isAbsolute, join, extname } from 'node:path';
import { PATHS } from '../../lib/fileUtils.js';
import { cdpRequest } from '../browserService.js';
const ORIGIN = 'https://composition.invalid';
-const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav' };
+const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav' };
// Sandboxing removes alternate realms, popups, forms and workers. HTTP assets
// are fulfilled below, never continued to the browser's network stack.
const CSP = "sandbox allow-scripts; default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src http: https:; font-src 'self'; media-src 'self'; connect-src http: https:; frame-src 'none'; worker-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
@@ -15,14 +15,26 @@ function inside(root, path) {
return rel && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\') && !isAbsolute(rel);
}
+// Media a staged render reads from disk on request instead of holding in
+// memory (a song's worth of takes and stills would not fit the 256 MiB cap).
+const STREAMABLE = new Set(['.mp4', '.mov', '.webm', '.mp3', '.wav', '.png', '.jpg', '.jpeg', '.webp']);
+const STREAMED_MAX_BYTES = 8 * 1024 * 1024 * 1024;
+// One fulfilled range never exceeds this; the media loader asks for the rest.
+const RANGE_CHUNK_BYTES = 8 * 1024 * 1024;
+
// Freeze the input before any script runs. Symlinks are refused, including
// symlinked assets, so the virtual origin cannot export another data store.
-export async function snapshotAssets(directory) {
+// `streamMedia` (a job-private staged copy only, e.g. a music-video document
+// render with every scene's take) leaves video, audio and images on disk and
+// serves them (by byte range when asked) on request; everything else is read
+// into memory here.
+export async function snapshotAssets(directory, { streamMedia = false } = {}) {
const root = await realpath(PATHS.data);
const dir = await realpath(resolve(root, directory));
if (!inside(root, dir)) throw new Error('directory must be inside data');
const assets = new Map();
let bytes = 0;
+ let streamed = 0;
async function walk(path, prefix = '') {
for (const entry of await readdir(path, { withFileTypes: true })) {
const name = `${prefix}${entry.name}`;
@@ -30,6 +42,12 @@ export async function snapshotAssets(directory) {
if (entry.isDirectory()) await walk(join(path, entry.name), `${name}/`);
else if (entry.isFile()) {
const size = (await stat(join(path, entry.name))).size;
+ if (streamMedia && STREAMABLE.has(extname(entry.name).toLowerCase())) {
+ streamed += size;
+ if (streamed > STREAMED_MAX_BYTES || assets.size >= 4096) throw new Error('Composition media exceed 8 GiB or 4096 files');
+ assets.set(`/${name}`, { path: join(path, entry.name), size });
+ continue;
+ }
if (bytes + size > 256 * 1024 * 1024 || assets.size >= 4096) throw new Error('Composition assets exceed 256 MiB or 4096 files');
const body = await readFile(join(path, entry.name));
bytes += body.length;
@@ -45,8 +63,35 @@ export async function snapshotAssets(directory) {
// One browser-level socket owns a disposable context and its hidden target.
// Disconnect/abort rejects pending commands; disposeOnDetach covers crashes.
-export async function openComposition(directory, { signal, validateAssets } = {}) {
- const assets = await snapshotAssets(directory);
+// `bytes=a-b` / `bytes=a-` / `bytes=-n` against `size`; null when absent or unsatisfiable.
+function parseByteRange(header, size) {
+ const match = /^bytes=(\d*)-(\d*)$/.exec(String(header || '').trim());
+ if (!match || (!match[1] && !match[2])) return null;
+ let start;
+ let end;
+ if (!match[1]) {
+ start = Math.max(0, size - Number(match[2]));
+ end = size - 1;
+ } else {
+ start = Number(match[1]);
+ end = match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
+ }
+ if (!(start <= end) || start >= size) return null;
+ return { start, end: Math.min(end, start + RANGE_CHUNK_BYTES - 1) };
+}
+
+async function readSlice(asset, start, end) {
+ if (Buffer.isBuffer(asset)) return asset.subarray(start, end + 1);
+ const handle = await open(asset.path, 'r');
+ try {
+ const out = Buffer.alloc(end - start + 1);
+ const { bytesRead } = await handle.read(out, 0, out.length, start);
+ return out.subarray(0, bytesRead);
+ } finally { await handle.close(); }
+}
+
+export async function openComposition(directory, { signal, validateAssets, streamMedia = false } = {}) {
+ const assets = await snapshotAssets(directory, { streamMedia });
validateAssets?.(assets);
signal?.throwIfAborted();
const response = await cdpRequest('/json/version');
@@ -82,18 +127,35 @@ export async function openComposition(directory, { signal, validateAssets } = {}
async function request(params) {
const url = new URL(params.request.url);
const key = decodeURIComponent(url.pathname);
- const body = url.origin === ORIGIN && !url.username && !url.password && params.request.method === 'GET' && assets.get(key);
- if (!body) {
+ const asset = url.origin === ORIGIN && !url.username && !url.password && params.request.method === 'GET' && assets.get(key);
+ if (!asset) {
// Do not continue even a failed request. Disconnect destroys the context.
throw new Error(`Refused composition request: ${params.request.url}`);
}
+ const size = Buffer.isBuffer(asset) ? asset.length : asset.size;
+ const headers = params.request.headers || {};
+ const rangeHeader = Object.entries(headers).find(([name]) => name.toLowerCase() === 'range')?.[1];
+ // Media elements ask for byte ranges; answer them (206) so a seek never
+ // needs the whole file, and a streamed asset is read only as far as asked.
+ const range = rangeHeader ? parseByteRange(rangeHeader, size) : null;
+ if (rangeHeader && !range && size > 0) {
+ await send('Fetch.fulfillRequest', { requestId: params.requestId, responseCode: 416,
+ responseHeaders: [{ name: 'Content-Range', value: `bytes */${size}` }, { name: 'Content-Security-Policy', value: CSP }], body: '' });
+ return;
+ }
+ const start = range ? range.start : 0;
+ const end = range ? range.end : size - 1;
+ const body = size === 0 ? Buffer.alloc(0) : await readSlice(asset, start, end);
await send('Fetch.fulfillRequest', {
- requestId: params.requestId, responseCode: 200,
+ requestId: params.requestId, responseCode: range ? 206 : 200,
responseHeaders: [
{ name: 'Content-Type', value: MIME[extname(key).toLowerCase()] ?? 'application/octet-stream' },
{ name: 'Content-Security-Policy', value: CSP },
{ name: 'Access-Control-Allow-Origin', value: '*' },
{ name: 'X-DNS-Prefetch-Control', value: 'off' },
+ { name: 'Accept-Ranges', value: 'bytes' },
+ { name: 'Content-Length', value: String(body.length) },
+ ...(range ? [{ name: 'Content-Range', value: `bytes ${start}-${start + body.length - 1}/${size}` }] : []),
], body: body.toString('base64'),
});
}
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 8726680ea1..e9d26533ce 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -18,9 +18,26 @@ async function frameFormat(page, { width, height, layout }) {
page.check();
}
+// A composition's seek(t) owns its frame: a rejection (a <video> that failed
+// to seek, a missing asset) or a hung seek must fail the render loudly and say
+// which frame, never capture whatever the page last painted.
+async function seekComposition(page, t, frame) {
+ try {
+ await page.evaluate(`globalThis.portosComposition.seek(${t})`);
+ } catch (error) {
+ throw new Error(`Composition seek(${t}) failed${frame == null ? '' : ` at frame ${frame}`}: ${error.message}`);
+ }
+}
+
+// PNG stays lossless; optimizeForSpeed only trades file size for encode time
+// (about 3x faster on photographic 1080p frames).
+const SCREENSHOT = Object.freeze({ format: 'png', optimizeForSpeed: true, fromSurface: true, captureBeyondViewport: false });
+
// Stream one frame at a time. The write callback supplies back-pressure and
// the terminal race releases a pending write on exit, disconnect or cancel.
-export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {
+// `offsetSec` seeks a window of a longer timeline: frame n is drawn at
+// `offsetSec + n / fps` (a music-video excerpt stays on song time).
+export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, offsetSec = 0, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {
const ffmpeg = await locateFfmpeg();
if (!ffmpeg) throw new Error('ffmpeg not found on PATH');
const tag = await tagFilter();
@@ -77,12 +94,14 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
}
};
signal?.addEventListener('abort', stop, { once: true });
+ if (!Number.isFinite(offsetSec) || offsetSec < 0) throw new Error('offsetSec must be a non-negative number');
const capture = async t => {
page.check();
// awaitPromise in evaluate is essential: each seek owns its paint.
- await page.evaluate(`globalThis.portosComposition.seek(${t})`);
+ const at = offsetSec ? Math.round((offsetSec + t) * 1e6) / 1e6 : t;
+ await seekComposition(page, at, Math.round(t * fps));
page.check();
- const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });
+ const { data } = await page.send('Page.captureScreenshot', SCREENSHOT);
page.check();
return Buffer.from(data, 'base64');
};
@@ -173,10 +192,10 @@ export async function encodeContactSheet(page, contract, outputPath, { times, si
try {
for (const t of times) {
page.check();
- await page.evaluate(`globalThis.portosComposition.seek(${t})`);
+ await seekComposition(page, t);
page.check();
// Chrome downscales to tile size, so full-resolution PNGs never cross CDP.
- const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false,
+ const { data } = await page.send('Page.captureScreenshot', { ...SCREENSHOT,
clip: { x: 0, y: 0, width, height, scale: tileWidth / width } });
signal?.throwIfAborted();
await Promise.race([
diff --git a/server/services/htmlComposition/encode.musicVideo.test.js b/server/services/htmlComposition/encode.musicVideo.test.js
index f2a64e6c25..b89e174687 100644
--- a/server/services/htmlComposition/encode.musicVideo.test.js
+++ b/server/services/htmlComposition/encode.musicVideo.test.js
@@ -19,7 +19,7 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => {
proc.stdin.write = (buf, cb) => { bytes += buf.length; cb?.(); return true; };
proc.stdin.end = () => { proc.emit('close', 0); };
proc.kill = () => {};
- spawned.push({ args, bytes: () => bytes });
+ spawned.push({ args, bytes: () => bytes, proc });
return proc;
},
};
@@ -80,3 +80,42 @@ describe('encodeComposition music-video audio', () => {
expect(result.status, `${result.stderr || ''}\n${result.stdout || ''}`).toBe(0);
}, 150000);
});
+
+describe('encodeComposition song-time windows', () => {
+ const recording = (fail = null) => {
+ const seeks = [];
+ return {
+ seeks,
+ page: {
+ check() {},
+ async evaluate(expression) {
+ const t = Number(/seek\(([^)]+)\)/.exec(expression)?.[1]);
+ if (Number.isFinite(t)) {
+ seeks.push(t);
+ if (fail && fail(t)) {
+ // The real encoder exits once its stdin is abandoned; this fake one closes on the failure.
+ spawned.at(-1).proc.emit('close', 1);
+ throw new Error('Composition script failed: video seek failed: media/scene-a.mp4');
+ }
+ }
+ },
+ async send(method) { return method === 'Page.captureScreenshot' ? { data: FRAME } : {}; },
+ },
+ };
+ };
+
+ it('seeks the window on the timeline it came from: frame n is drawn at offsetSec + n / fps', async () => {
+ spawned.length = 0;
+ const { page: windowPage, seeks } = recording();
+ await encodeComposition(windowPage, contract(0.5), '/tmp/window.mp4', { offsetSec: 61.25 });
+ expect(seeks).toEqual([61.25, 61.333333, 61.416667, 61.5, 61.583333, 61.666667]);
+ expect(spawned[0].args.join(' ')).toContain('-frames:v 6');
+ });
+
+ it('fails loudly, naming the frame, when a seek rejects', async () => {
+ spawned.length = 0;
+ const { page: failing } = recording((t) => t >= 10.25);
+ await expect(encodeComposition(failing, contract(1), '/tmp/fail.mp4', { offsetSec: 10 }))
+ .rejects.toThrow(/seek\(10\.25\) failed at frame 3: .*video seek failed/);
+ });
+});
diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.js
index 1ceb528ff7..84b08ec59d 100644
--- a/server/services/htmlComposition/index.js
+++ b/server/services/htmlComposition/index.js
@@ -59,22 +59,27 @@ async function resolveMusicVideoOwner({ owner, audio, maxDurationSec }) {
};
}
+export const MUSIC_VIDEO_SCRATCH_DIR = 'music-video-song-renders';
+
// Copy the composition into this job's scratch directory and write song.json
// before openComposition freezes the snapshot. The page fetches it by relative
-// URL, so the network-refusing sandbox stays unchanged.
-async function stageMusicVideoComposition(sourceDirectory, jobId, song) {
+// URL, so the network-refusing sandbox stays unchanged. `prepare(dir)` lets a
+// caller add job files (a music-video document's portos-mv.js and scene media)
+// to the private copy before the snapshot; the caller removes `scratchRoot`.
+export async function stageMusicVideoComposition(sourceDirectory, jobId, song, { prepare } = {}) {
if (typeof jobId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(jobId)) throw new Error('Invalid composition job id');
const root = await realpath(PATHS.data);
const source = await realpath(resolve(root, sourceDirectory));
if (!insideData(root, source)) throw new Error('directory must be inside data');
- const scratchRoot = join(root, 'music-video-song-renders', jobId);
+ const scratchRoot = join(root, MUSIC_VIDEO_SCRATCH_DIR, jobId);
try {
await rm(scratchRoot, { recursive: true, force: true });
const compositionDir = join(scratchRoot, 'composition');
await ensureDir(scratchRoot);
await cp(source, compositionDir, { recursive: true, verbatimSymlinks: true });
await writeFile(join(compositionDir, 'song.json'), `${JSON.stringify(normalizeSongDocument(song))}\n`);
- return { directory: `music-video-song-renders/${jobId}/composition`, scratchRoot };
+ if (prepare) await prepare(compositionDir);
+ return { directory: `${MUSIC_VIDEO_SCRATCH_DIR}/${jobId}/composition`, scratchRoot };
} catch (error) {
await rm(scratchRoot, { recursive: true, force: true });
throw error;
@@ -150,7 +155,9 @@ export async function renderComposition({ jobId, owner, audio, maxDurationSec, s
let { directory } = parsedInput;
const sourceDirectory = directory;
const { musicTrack, launchVideo, synthesizeMusic, proof, formats, motionBlur: blurChoice } = parsedInput;
- if (musicVideo && (launchVideo || synthesizeMusic || musicTrack || proof || formats)) {
+ // A music-video render may still ask for the extra frames its contract
+ // declares in portosComposition.formats (renderTargets enforces that).
+ if (musicVideo && (launchVideo || synthesizeMusic || musicTrack || proof)) {
throw new Error('A music-video composition render cannot use launch-video, proof, or library-music options');
}
let musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;
diff --git a/server/services/htmlComposition/musicVideoOwner.test.js b/server/services/htmlComposition/musicVideoOwner.test.js
index 1a8389e520..dc6fec7a8d 100644
--- a/server/services/htmlComposition/musicVideoOwner.test.js
+++ b/server/services/htmlComposition/musicVideoOwner.test.js
@@ -99,6 +99,21 @@ describe('music-video composition owner', () => {
expect(encodeComposition).not.toHaveBeenCalled();
});
+ it('renders the extra frames the page declares in formats, and refuses one it does not', async () => {
+ encodeComposition.mockClear();
+ const master = join(PATHS.data, 'master-formats.wav');
+ await writeFile(master, Buffer.alloc(8));
+ const owner = { owner: 'music-video', audio: { path: master, startSec: 0 }, maxDurationSec: 30, song: {} };
+ seen.contract = { fps: 12, width: 1920, height: 1080, durationSec: 10, formats: ['1080x1920'], layout: true };
+ await expect(renderComposition({ jobId: randomUUID(), directory: await sourceDir(), formats: ['landscape', 'vertical'], ...owner }))
+ .rejects.toThrow('thumbnail skipped');
+ expect(encodeComposition.mock.calls.map(([, contract]) => `${contract.width}x${contract.height}`)).toEqual(['1920x1080', '1080x1920']);
+ encodeComposition.mockClear();
+ await expect(renderComposition({ jobId: randomUUID(), directory: await sourceDir(), formats: ['square'], ...owner }))
+ .rejects.toThrow('portosComposition.formats must include 1080x1080');
+ expect(encodeComposition).not.toHaveBeenCalled();
+ });
+
it('does not let the owner option carry launch-video delivery', async () => {
const directory = await sourceDir();
const master = join(PATHS.data, 'master-launch.wav');
diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.js
index 113bced431..25a17fc215 100644
--- a/server/services/musicVideo/composition.js
+++ b/server/services/musicVideo/composition.js
@@ -20,6 +20,8 @@ import { randomUUID } from 'crypto';
import { trimTo } from '../../lib/textUtils.js';
import {
MUSIC_VIDEO_COMPOSITION_MODES as COMPOSITION_MODES,
+ MUSIC_VIDEO_DOCUMENT_DIRECTORY,
+ MUSIC_VIDEO_DOCUMENT_SOURCES,
MUSIC_VIDEO_TYPOGRAPHY_EMPHASES as TYPOGRAPHY_EMPHASES,
MUSIC_VIDEO_TYPOGRAPHY_FONTS as TYPOGRAPHY_FONTS,
MUSIC_VIDEO_TYPOGRAPHY_PLACEMENTS as TYPOGRAPHY_PLACEMENTS,
@@ -55,6 +57,49 @@ function normalizeCodeVideo(input) {
};
}
+/**
+ * The stored pointer to the project's composition document, or null when the
+ * value is not a document version folder. Only the import routes set it.
+ */
+function normalizeCompositionDocument(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
+ if (typeof input.directory !== 'string' || !MUSIC_VIDEO_DOCUMENT_DIRECTORY.test(input.directory)) return null;
+ const source = input.source && typeof input.source === 'object' && MUSIC_VIDEO_DOCUMENT_SOURCES.includes(input.source.kind)
+ ? { kind: input.source.kind, name: typeof input.source.name === 'string' && input.source.name ? input.source.name.slice(0, 200) : null }
+ : null;
+ const count = (value, max) => (Number.isInteger(value) && value >= 0 && value <= max ? value : null);
+ return {
+ directory: input.directory,
+ entry: 'index.html',
+ updatedAt: typeof input.updatedAt === 'string' && input.updatedAt ? input.updatedAt.slice(0, 40) : null,
+ source,
+ ...(count(input.files, 4096) != null ? { files: input.files } : {}),
+ ...(count(input.bytes, Number.MAX_SAFE_INTEGER) != null ? { bytes: input.bytes } : {}),
+ };
+}
+
+/** The HUD block a composition document may draw; null when absent. */
+function normalizeCompositionOverlay(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
+ const lines = (list, maxItems, maxLen) => (Array.isArray(list) ? list : [])
+ .map((line) => trimTo(line, maxLen)).filter(Boolean).slice(0, maxItems);
+ const meterIn = input.meter && typeof input.meter === 'object' && !Array.isArray(input.meter) ? input.meter : null;
+ const keyframes = (Array.isArray(meterIn?.keyframes) ? meterIn.keyframes : [])
+ .filter((pair) => Array.isArray(pair) && toTime(pair[0]) != null && typeof pair[1] === 'number' && pair[1] >= 0 && pair[1] <= 100)
+ .map(([t, v]) => [toTime(t), Math.round(v * 100) / 100])
+ .sort((a, b) => a[0] - b[0])
+ .slice(0, 200);
+ const start = input.timecodeStartSec;
+ return {
+ enabled: input.enabled !== false,
+ titleLines: lines(input.titleLines, 4, 120),
+ meter: meterIn ? { label: trimTo(meterIn.label, 40), keyframes } : null,
+ ticker: lines(input.ticker, 40, 200),
+ timecode: input.timecode !== false,
+ timecodeStartSec: typeof start === 'number' && Number.isFinite(start) && start >= 0 && start <= 86400 ? start : 0,
+ };
+}
+
/**
* 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
@@ -84,6 +129,8 @@ export function normalizeComposition(input) {
}
const style = input.style && typeof input.style === 'object' ? input.style : {};
const codeVideo = normalizeCodeVideo(input.codeVideo);
+ const documentRef = normalizeCompositionDocument(input.document);
+ const overlay = normalizeCompositionOverlay(input.overlay);
return {
version: COMPOSITION_VERSION,
mode: pick(input.mode, COMPOSITION_MODES, 'concat'),
@@ -96,9 +143,22 @@ export function normalizeComposition(input) {
// Absent unless a code video was actually stored, so a composed manifest
// stays the shape peers and clones already compare.
...(codeVideo ? { codeVideo } : {}),
+ // Same posture: present only once a document was imported / a HUD set.
+ ...(documentRef ? { document: documentRef } : {}),
+ ...(overlay ? { overlay } : {}),
};
}
+/**
+ * `next` (a normalized manifest, or null) carrying `stored`'s document pointer
+ * instead of whatever `next` holds: only the import routes set the pointer.
+ */
+export function withStoredCompositionDocument(next, stored) {
+ if (!next) return next;
+ const { document: _ignored, ...rest } = next;
+ return stored?.document ? { ...rest, document: stored.document } : rest;
+}
+
/** Clear the audio-derived timings (cue times, poster) when the song changes, keeping the text. */
export function invalidateCompositionTiming(composition) {
if (!composition || typeof composition !== 'object') return composition;
diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.js
new file mode 100644
index 0000000000..b75b3f7abd
--- /dev/null
+++ b/server/services/musicVideo/compositionDocument.js
@@ -0,0 +1,356 @@
+/**
+ * Music Video — project composition documents (files on disk).
+ *
+ * A project in `composition.mode === 'document'` renders its own deterministic
+ * HTML composition (a page exposing `globalThis.portosComposition`, see
+ * services/htmlComposition). Every import writes one immutable version folder:
+ *
+ * data/music-video/<projectId>/composition/<versionId>/index.html (+ scripts, fonts, media)
+ *
+ * and the record's `composition.document` points at it (data-relative path).
+ * A clone carries the pointer and keeps reading the same bytes; a version no
+ * live or tombstoned project points at is pruned after the next import. The
+ * pointer is wire-local (lib/syncWire.js) because the files are not in the
+ * project's peer-sync asset manifest; the folder is covered by the rsync
+ * snapshot backup like the rest of data/music-video/.
+ *
+ * Imports refuse symlinks, special files, traversal names and oversized trees
+ * rather than rewriting them, so a document can never reach outside its folder.
+ */
+
+import { cp, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, writeFile } from 'fs/promises';
+import { dirname, extname, join, relative, resolve, sep } from 'path';
+import { fileURLToPath } from 'url';
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/fileUtils.js';
+import { isPathInsideDir } from '../../lib/pathSafety.js';
+import { readZipArchive, unsafeZipEntryName } from '../../lib/zipArchive.js';
+import { createZip } from '../../lib/zipWriter.js';
+import { MUSIC_VIDEO_DOCUMENT_DIRECTORY, MUSIC_VIDEO_DOCUMENT_TEMPLATES } from '../../lib/musicVideoValidation.js';
+import { getProject, listProjects, mutateProjectRecord } from './projects.js';
+import { normalizeComposition } from './composition.js';
+
+// The composition browser snapshots at most 256 MiB / 4096 files per render,
+// and a render adds the staged scene media beside the document.
+export const DOCUMENT_MAX_BYTES = 128 * 1024 * 1024;
+export const DOCUMENT_MAX_FILES = 1024;
+export const DOCUMENT_ZIP_MAX_BYTES = DOCUMENT_MAX_BYTES + 16 * 1024 * 1024;
+// Names the render writes next to the entry; a document may not ship them.
+export const DOCUMENT_RESERVED_FILES = Object.freeze(['portos-mv.js', 'song.json']);
+
+const SEGMENT = /^[A-Za-z0-9_-]{1,100}$/;
+const TEMPLATE_ROOT = join(dirname(fileURLToPath(import.meta.url)), 'documentTemplates');
+
+const MIME_TYPES = Object.freeze({
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
+ '.txt': 'text/plain', '.md': 'text/plain', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
+ '.gif': 'image/gif', '.svg': 'image/svg+xml', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
+ '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav',
+});
+
+/** The served media type for a document file (octet-stream when unknown). */
+export const documentMimeType = (path) => MIME_TYPES[extname(String(path)).toLowerCase()] || 'application/octet-stream';
+
+const refuse = (message, code = 'COMPOSITION_DOCUMENT_INVALID', status = 422) => new ServerError(message, { status, code });
+
+function assertProjectId(projectId) {
+ if (typeof projectId !== 'string' || !SEGMENT.test(projectId)) throw refuse('Invalid project id', 'VALIDATION_ERROR', 400);
+}
+
+const documentsRoot = () => join(PATHS.data, 'music-video');
+const projectDocumentRoot = (projectId) => join(documentsRoot(), projectId, 'composition');
+
+/**
+ * Absolute folder for a stored document pointer, or null when the pointer is
+ * not a version folder inside data/music-video/ (a hand-edited or peer record).
+ */
+function resolveDocumentDirectory(document) {
+ const directory = document?.directory;
+ if (typeof directory !== 'string' || !MUSIC_VIDEO_DOCUMENT_DIRECTORY.test(directory)) return null;
+ const abs = resolve(PATHS.data, directory);
+ return isPathInsideDir(documentsRoot(), abs) ? abs : null;
+}
+
+/** Whether the project has a document pointer whose folder holds an index.html on this install. */
+async function documentAvailable(project) {
+ const dir = resolveDocumentDirectory(project?.composition?.document);
+ if (!dir) return false;
+ const info = await lstat(join(dir, 'index.html')).catch(() => null);
+ return Boolean(info?.isFile());
+}
+
+// Reserved names are compared case-insensitively (macOS / Windows file systems).
+const isReserved = (rel) => DOCUMENT_RESERVED_FILES.includes(rel.toLowerCase());
+
+/**
+ * Every regular file under `root` as `[{ rel, abs, size }]`, refusing symlinks,
+ * special files and a tree over the file / byte caps. `rel` uses `/`.
+ */
+async function collectTree(root) {
+ const files = [];
+ let bytes = 0;
+ async function walk(dir, prefix) {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const rel = `${prefix}${entry.name}`;
+ const abs = join(dir, entry.name);
+ // lstat, not the dirent alone: a symlink is refused even when it points inside.
+ const info = await lstat(abs);
+ if (info.isSymbolicLink()) throw refuse(`Composition documents cannot contain symlinks (${rel})`, 'COMPOSITION_DOCUMENT_SYMLINK');
+ if (info.isDirectory()) { await walk(abs, `${rel}/`); continue; }
+ if (!info.isFile()) throw refuse(`Composition documents can only contain regular files (${rel})`);
+ if (unsafeZipEntryName(rel)) throw refuse(`Unsupported file name in the composition document (${rel})`);
+ files.push({ rel, abs, size: info.size });
+ bytes += info.size;
+ if (files.length > DOCUMENT_MAX_FILES || bytes > DOCUMENT_MAX_BYTES) {
+ throw refuse(`A composition document is limited to ${DOCUMENT_MAX_FILES} files and ${DOCUMENT_MAX_BYTES / (1024 * 1024)} MiB`, 'COMPOSITION_DOCUMENT_TOO_LARGE', 413);
+ }
+ }
+ }
+ await walk(root, '');
+ return { files, bytes };
+}
+
+function assertDocumentShape(rels) {
+ if (!rels.includes('index.html')) throw refuse('A composition document needs an index.html at its root', 'COMPOSITION_DOCUMENT_NO_ENTRY');
+ const reserved = rels.find(isReserved);
+ if (reserved) throw refuse(`${reserved} is written by PortOS at render time — remove it from the document`);
+}
+
+// Imports and detaches of one project run one at a time: a prune must never
+// see a freshly renamed version folder whose record write is still pending.
+const projectTails = new Map();
+function serializeProject(projectId, task) {
+ const previous = projectTails.get(projectId) || Promise.resolve();
+ const run = previous.catch(() => {}).then(task);
+ const tail = run.catch(() => {});
+ projectTails.set(projectId, tail);
+ tail.then(() => { if (projectTails.get(projectId) === tail) projectTails.delete(projectId); });
+ return run;
+}
+
+/**
+ * Write one immutable version folder from `files` ([{ rel, data } | { rel, abs }])
+ * and point the project at it. The folder is assembled under a hidden name and
+ * renamed into place, so a failed import never leaves a half-written version.
+ */
+function storeVersion(projectId, files, source) {
+ assertProjectId(projectId);
+ return serializeProject(projectId, () => storeVersionNow(projectId, files, source));
+}
+
+async function storeVersionNow(projectId, files, source) {
+ assertDocumentShape(files.map((file) => file.rel));
+ if (!(await getProject(projectId))) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const versionId = `doc-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
+ const root = projectDocumentRoot(projectId);
+ const staging = join(root, `.${versionId}.partial`);
+ const finalDir = join(root, versionId);
+ let bytes = 0;
+ try {
+ for (const file of files) {
+ const target = resolve(staging, file.rel);
+ if (!isPathInsideDir(staging, target)) throw refuse(`Unsupported file name in the composition document (${file.rel})`);
+ await mkdir(dirname(target), { recursive: true });
+ if (file.data) await writeFile(target, file.data, { flag: 'wx' });
+ else await cp(file.abs, target, { errorOnExist: true, force: false });
+ bytes += file.data ? file.data.length : file.size;
+ }
+ await rename(staging, finalDir);
+ } catch (error) {
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
+ throw error;
+ }
+ const document = {
+ directory: `music-video/${projectId}/composition/${versionId}`,
+ entry: 'index.html',
+ updatedAt: new Date().toISOString(),
+ source,
+ files: files.length,
+ bytes,
+ };
+ let outcome;
+ try {
+ outcome = await mutateProjectRecord(projectId, (current) => {
+ const composition = normalizeComposition({ ...(current.composition || {}), mode: 'document' });
+ const project = { ...current, composition: { ...composition, document }, updatedAt: document.updatedAt };
+ return { project };
+ });
+ } catch (error) {
+ await rm(finalDir, { recursive: true, force: true }).catch(() => {});
+ throw error;
+ }
+ console.log(`🧩 Music Video composition document ${versionId} stored for ${projectId.slice(0, 11)} (${files.length} files, ${source.kind})`);
+ await pruneDocumentVersions(projectId).catch((err) => {
+ console.warn(`⚠️ Music Video composition document prune failed for ${projectId.slice(0, 11)}: ${err.message}`);
+ });
+ return { project: outcome.project, document };
+}
+
+/**
+ * Remove this project's version folders that no project (live or tombstoned —
+ * a clone may share one) points at. Hidden `.partial` leftovers go too.
+ */
+async function pruneDocumentVersions(projectId) {
+ assertProjectId(projectId);
+ const root = projectDocumentRoot(projectId);
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
+ if (!entries.length) return 0;
+ const referenced = new Set((await listProjects({ includeDeleted: true }))
+ .map((project) => project?.composition?.document?.directory).filter(Boolean));
+ let removed = 0;
+ const staleBefore = Date.now() - 60 * 60 * 1000;
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ // A hidden `.…partial` folder is an import in progress unless it is old.
+ if (entry.name.startsWith('.')) {
+ const info = await lstat(join(root, entry.name)).catch(() => null);
+ if (!info || info.mtimeMs > staleBefore) continue;
+ }
+ if (referenced.has(`music-video/${projectId}/composition/${entry.name}`)) continue;
+ await rm(join(root, entry.name), { recursive: true, force: true });
+ removed += 1;
+ }
+ return removed;
+}
+
+// A zip of a folder usually holds everything under one top-level directory.
+function stripCommonRoot(names) {
+ const first = names[0]?.split('/')[0];
+ if (!first || names.includes('index.html')) return '';
+ const prefix = `${first}/`;
+ return names.every((name) => name.startsWith(prefix)) ? prefix : '';
+}
+
+/** Import an uploaded zip (the caller removes the temp file). */
+export async function importDocumentZip(projectId, zipPath, originalName = null) {
+ const info = await stat(zipPath);
+ if (info.size > DOCUMENT_ZIP_MAX_BYTES) throw refuse('The zip is too large for a composition document', 'COMPOSITION_DOCUMENT_TOO_LARGE', 413);
+ let entries;
+ try {
+ entries = readZipArchive(await readFile(zipPath), { maxEntries: DOCUMENT_MAX_FILES * 2 });
+ } catch (error) {
+ throw refuse(`Could not read the zip: ${error.message}`);
+ }
+ for (const entry of entries) {
+ const problem = unsafeZipEntryName(entry.name);
+ if (problem) throw refuse(`The zip has an unsafe member (${problem}): ${entry.name.slice(0, 120)}`, 'COMPOSITION_DOCUMENT_TRAVERSAL');
+ if (entry.isSymlink) throw refuse(`Composition documents cannot contain symlinks (${entry.name.slice(0, 120)})`, 'COMPOSITION_DOCUMENT_SYMLINK');
+ }
+ const members = entries.filter((entry) => !entry.isDirectory && !entry.name.startsWith('__MACOSX/') && !entry.name.split('/').pop().startsWith('._'));
+ const prefix = stripCommonRoot(members.map((entry) => entry.name));
+ let bytes = 0;
+ const files = members.map((entry) => {
+ bytes += entry.size;
+ if (members.length > DOCUMENT_MAX_FILES || bytes > DOCUMENT_MAX_BYTES) {
+ throw refuse(`A composition document is limited to ${DOCUMENT_MAX_FILES} files and ${DOCUMENT_MAX_BYTES / (1024 * 1024)} MiB`, 'COMPOSITION_DOCUMENT_TOO_LARGE', 413);
+ }
+ return { rel: entry.name.slice(prefix.length), entry };
+ }).filter((file) => file.rel && !file.rel.split('/').pop().startsWith('.DS_Store'));
+ // Read (inflate + CRC) only after every name passed.
+ const loaded = files.map(({ rel, entry }) => {
+ try { return { rel, data: entry.read() }; } catch (error) { throw refuse(`Could not read the zip: ${error.message}`); }
+ });
+ const name = typeof originalName === 'string' && originalName ? originalName.split(/[\\/]/).pop().slice(0, 200) : null;
+ return storeVersion(projectId, loaded, { kind: 'zip', name });
+}
+
+/** Copy a document from a folder inside data/ given by its data-relative path. */
+export async function importDocumentDirectory(projectId, directory) {
+ const root = await realpath(PATHS.data);
+ const requested = resolve(root, directory);
+ const info = await lstat(requested).catch(() => null);
+ if (!info) throw refuse('That folder does not exist inside data', 'COMPOSITION_DOCUMENT_NOT_FOUND', 404);
+ if (info.isSymbolicLink()) throw refuse('The document folder must not be a symlink', 'COMPOSITION_DOCUMENT_SYMLINK');
+ if (!info.isDirectory()) throw refuse('The document path must be a folder');
+ // Every ancestor must resolve inside data too (a symlinked parent is refused).
+ const real = await realpath(requested);
+ const rel = relative(root, real);
+ if (!rel || rel.startsWith('..') || rel.startsWith(`..${sep}`) || real !== requested) {
+ throw refuse('directory must be inside data and not reached through a symlink', 'COMPOSITION_DOCUMENT_SYMLINK');
+ }
+ const { files } = await collectTree(real);
+ return storeVersion(projectId, files, { kind: 'directory', name: rel.split(sep).join('/').slice(0, 200) });
+}
+
+/** Copy a shipped template (documentTemplates/<id>) into the project. */
+export async function importDocumentTemplate(projectId, templateId = 'layered') {
+ if (!MUSIC_VIDEO_DOCUMENT_TEMPLATES.includes(templateId)) throw refuse('Unknown composition template', 'VALIDATION_ERROR', 400);
+ const { files } = await collectTree(join(TEMPLATE_ROOT, templateId));
+ return storeVersion(projectId, files, { kind: 'template', name: templateId });
+}
+
+async function requireDocument(project) {
+ const dir = resolveDocumentDirectory(project?.composition?.document);
+ if (!dir || !(await documentAvailable(project))) {
+ throw refuse('This project has no composition document on this machine — import one or start from the template', 'COMPOSITION_DOCUMENT_MISSING', 409);
+ }
+ return dir;
+}
+
+/** The document's file list: `{ document, files: [{ path, bytes }], totalBytes }`. */
+export async function readDocumentManifest(project) {
+ const document = project?.composition?.document || null;
+ if (!document) return { document: null, available: false, files: [], totalBytes: 0 };
+ if (!(await documentAvailable(project))) return { document, available: false, files: [], totalBytes: 0 };
+ const { files, bytes } = await collectTree(resolveDocumentDirectory(document));
+ return {
+ document,
+ available: true,
+ files: files.map((file) => ({ path: file.rel, bytes: file.size })).sort((a, b) => a.path.localeCompare(b.path)),
+ totalBytes: bytes,
+ };
+}
+
+/** A zip of the current document: `{ zip, filename }`. */
+export async function exportDocumentZip(project) {
+ const dir = await requireDocument(project);
+ const { files } = await collectTree(dir);
+ const entries = [];
+ for (const file of files.sort((a, b) => a.rel.localeCompare(b.rel))) {
+ entries.push({ name: file.rel, data: await readFile(file.abs) });
+ }
+ return { zip: createZip(entries, { compress: true }), filename: `music-video-${project.id}-composition.zip` };
+}
+
+/** Absolute path of one document file for the preview bridge, refusing traversal and symlinks. */
+export async function resolveDocumentFile(project, relPath) {
+ const dir = await requireDocument(project);
+ if (unsafeZipEntryName(relPath)) throw refuse('Invalid document file path', 'VALIDATION_ERROR', 400);
+ const abs = resolve(dir, relPath);
+ if (!isPathInsideDir(dir, abs)) throw refuse('Invalid document file path', 'VALIDATION_ERROR', 400);
+ const info = await lstat(abs).catch(() => null);
+ if (!info?.isFile()) throw new ServerError('Document file not found', { status: 404, code: 'NOT_FOUND' });
+ return abs;
+}
+
+/** Point the project back at no document (the folders are pruned). */
+export function detachDocument(projectId) {
+ assertProjectId(projectId);
+ return serializeProject(projectId, async () => {
+ const outcome = await mutateProjectRecord(projectId, (current) => {
+ if (!current.composition?.document) return { project: current };
+ const { document: _removed, ...composition } = current.composition;
+ return { project: { ...current, composition, updatedAt: new Date().toISOString() } };
+ });
+ await pruneDocumentVersions(projectId).catch((err) => {
+ console.warn(`⚠️ Music Video composition document prune failed for ${projectId.slice(0, 11)}: ${err.message}`);
+ });
+ return { project: outcome.project };
+ });
+}
+
+/** The document folder a render stages; throws COMPOSITION_DOCUMENT_MISSING. */
+export async function documentDirectoryForRender(project) {
+ const dir = await requireDocument(project);
+ return relative(PATHS.data, dir).split(sep).join('/');
+}
+
+/** Every file a document ships, read into memory (the preview builder). */
+export async function readDocumentFiles(project) {
+ const dir = await requireDocument(project);
+ const { files } = await collectTree(dir);
+ const out = new Map();
+ for (const file of files) out.set(file.rel, { abs: file.abs, size: file.size });
+ return out;
+}
diff --git a/server/services/musicVideo/compositionRender.js b/server/services/musicVideo/compositionRender.js
index cbb294a3a4..5a96802593 100644
--- a/server/services/musicVideo/compositionRender.js
+++ b/server/services/musicVideo/compositionRender.js
@@ -53,7 +53,7 @@ async function captureWindow(page, ffmpeg, { startSec, frames, fps, outputPath,
page.check();
await page.evaluate(`globalThis.portosComposition.seek(${startSec + n / fps})`);
page.check();
- const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', optimizeForSpeed: true, fromSurface: true, captureBeyondViewport: false });
signal?.throwIfAborted();
await Promise.race([
new Promise((resolve, reject) => proc.stdin.write(Buffer.from(data, 'base64'), (error) => (error ? reject(error) : resolve()))),
@@ -76,7 +76,7 @@ async function captureWindow(page, ffmpeg, { startSec, frames, fps, outputPath,
* `width`×`height`, `fps` frame. Resolves `[{ path, startSec, durationSec }]` in
* time order. `onProgress(0..1)` reports captured frames; `signal` cancels.
*/
-function musicVideoSongDocument(project) {
+export function musicVideoSongDocument(project) {
const analysis = project?.audioAnalysis && typeof project.audioAnalysis === 'object' && !Array.isArray(project.audioAnalysis)
? project.audioAnalysis : {};
let words = null;
diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.js
new file mode 100644
index 0000000000..512807360b
--- /dev/null
+++ b/server/services/musicVideo/documentPreview.js
@@ -0,0 +1,189 @@
+/**
+ * Music Video — the in-app live preview of a composition document.
+ *
+ * The preview runs in an opaque-origin `<iframe sandbox="allow-scripts"
+ * srcdoc>` that can reach nothing on the network (its CSP allows only inline
+ * code and data:/blob: assets), so it can never call PortOS with the user's
+ * session. The server therefore hands the client ONE self-contained page:
+ *
+ * - the document's own scripts and stylesheets inlined, and every file its
+ * CSS or `<img>` tags name inlined as a data: URL;
+ * - `window.PORTOS_MV` built exactly as a render builds it (portos-mv.js);
+ * - a bootstrap that receives the large media (scene takes, shipped video
+ * and images) as Blobs the PortOS page fetched on the user's behalf and
+ * posted in (`portos-mv:assets`), exposes them as `window.PORTOS_MV_ASSETS`
+ * (a promise of `{ 'media/…': 'blob:…' }`), maps any relative media `src`
+ * a script sets onto them, and answers `portos-mv:seek` messages.
+ *
+ * `assets` lists what the client should fetch and post: `{ key, url }` with
+ * `url` a same-origin PortOS path.
+ */
+
+import { readFile } from 'fs/promises';
+import { extname } from 'path';
+import { loadHistory } from '../videoGen/history.js';
+import { readDocumentFiles, documentMimeType } from './compositionDocument.js';
+import {
+ buildDocumentData, documentRenderClock, documentSongDuration, resolveSceneMedia,
+ DOCUMENT_FRAME_SIZES, documentAspect,
+} from './documentRender.js';
+
+// Inline (data: URL) budget for files referenced from HTML/CSS: fonts, small images.
+const INLINE_FILE_MAX = 4 * 1024 * 1024;
+const INLINE_TOTAL_MAX = 24 * 1024 * 1024;
+const BRIDGED = new Set(['.mp4', '.mov', '.webm', '.mp3', '.wav', '.png', '.jpg', '.jpeg', '.webp', '.gif']);
+
+export const PREVIEW_CSP = [
+ "default-src 'none'", "script-src 'unsafe-inline'", "style-src 'unsafe-inline'",
+ 'img-src data: blob:', 'media-src data: blob:', 'font-src data: blob:',
+ "connect-src 'none'", "form-action 'none'", "base-uri 'none'", "object-src 'none'",
+ "frame-src 'none'", "worker-src 'none'", "manifest-src 'none'",
+].join('; ');
+
+const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
+// A script body can hold anything except its own closing tag.
+const inlineScript = (source) => source.replace(/<\/(script)/gi, '<\\/$1');
+const cleanRef = (ref) => {
+ const value = String(ref || '').trim().replace(/^['"]|['"]$/g, '').replace(/^\.\//, '').split(/[?#]/)[0];
+ if (!value || /^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('/') || value.startsWith('//')) return null;
+ try { return decodeURIComponent(value); } catch { return value; }
+};
+
+// Runs before any document script: asset bridge, relative-src mapping, seek/layout messages.
+const BOOTSTRAP = `(() => {
+ const map = new Map();
+ let resolved = false;
+ let resolveAssets;
+ window.PORTOS_MV_PREVIEW = true;
+ window.PORTOS_MV_ASSETS = new Promise((resolve) => { resolveAssets = resolve; });
+ const keyOf = (value) => String(value).replace(/^\\.\\//, '').split(/[?#]/)[0];
+ const relative = (value) => typeof value === 'string' && value && !/^[a-z][a-z0-9+.-]*:/i.test(value) && !value.startsWith('/');
+ const pending = [];
+ for (const Ctor of [HTMLMediaElement, HTMLImageElement, HTMLSourceElement]) {
+ const desc = Object.getOwnPropertyDescriptor(Ctor.prototype, 'src');
+ if (!desc || !desc.set) continue;
+ Object.defineProperty(Ctor.prototype, 'src', { configurable: true, enumerable: desc.enumerable,
+ get() { return desc.get.call(this); },
+ set(value) {
+ if (relative(value)) {
+ const url = map.get(keyOf(value));
+ if (url) return desc.set.call(this, url);
+ if (!resolved) { pending.push([this, desc, value]); return; }
+ }
+ desc.set.call(this, value);
+ } });
+ }
+ const post = (message) => parent.postMessage(message, '*');
+ const contract = () => {
+ const c = globalThis.portosComposition;
+ return c ? { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, formats: c.formats || null, layout: typeof c.layout === 'function' } : null;
+ };
+ let seeking = Promise.resolve();
+ addEventListener('message', (event) => {
+ const message = event.data;
+ if (!message || typeof message !== 'object') return;
+ if (message.type === 'portos-mv:assets' && !resolved) {
+ for (const [key, blob] of Object.entries(message.files || {})) {
+ if (blob instanceof Blob) map.set(keyOf(key), URL.createObjectURL(blob));
+ }
+ resolved = true;
+ for (const [el, desc, value] of pending.splice(0)) desc.set.call(el, map.get(keyOf(value)) || value);
+ resolveAssets(Object.fromEntries(map));
+ } else if (message.type === 'portos-mv:seek') {
+ const t = Number(message.t) || 0;
+ seeking = seeking.then(() => globalThis.portosComposition?.seek(t)).then(
+ () => post({ type: 'portos-mv:seeked', t }),
+ (error) => post({ type: 'portos-mv:error', message: String(error && error.message || error) }),
+ );
+ }
+ });
+ addEventListener('error', (event) => post({ type: 'portos-mv:error', message: String(event.message || 'Script error') }));
+ addEventListener('load', () => {
+ const c = contract();
+ const want = window.PORTOS_MV && window.PORTOS_MV.render;
+ if (c && want && c.layout && (c.width !== want.width || c.height !== want.height)) {
+ try { globalThis.portosComposition.layout({ width: want.width, height: want.height }); } catch (error) { post({ type: 'portos-mv:error', message: String(error.message || error) }); }
+ }
+ post({ type: 'portos-mv:loaded', contract: c });
+ });
+})();`;
+
+/**
+ * The preview page and the assets to post into it:
+ * `{ html, assets: [{ key, url, bytes }], width, height, fps, durationSec }`.
+ */
+export async function buildDocumentPreview(project) {
+ const files = await readDocumentFiles(project);
+ const songDurationSec = documentSongDuration(project) || 0;
+ const clock = documentRenderClock(songDurationSec);
+ const frame = DOCUMENT_FRAME_SIZES[documentAspect(project)];
+ const history = (project.scenes || []).some((s) => s?.videoHistoryId) ? await loadHistory() : [];
+ const media = await resolveSceneMedia(project, { history });
+ const data = buildDocumentData(project, { media, frame, clock, songDurationSec });
+
+ let inlined = 0;
+ const inlinedKeys = new Set();
+ const dataUrl = async (rel) => {
+ const file = files.get(rel);
+ if (!file || file.size > INLINE_FILE_MAX || inlined + file.size > INLINE_TOTAL_MAX) return null;
+ inlined += file.size;
+ inlinedKeys.add(rel);
+ return `data:${documentMimeType(rel)};base64,${(await readFile(file.abs)).toString('base64')}`;
+ };
+ const rewriteCss = async (css) => {
+ const refs = [...css.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi)];
+ let out = css;
+ for (const match of refs) {
+ const rel = cleanRef(match[2]);
+ const url = rel ? await dataUrl(rel) : null;
+ if (url) out = out.split(match[0]).join(`url("${url}")`);
+ }
+ return out;
+ };
+
+ let html = await readFile(files.get('index.html').abs, 'utf8');
+ // <link rel=stylesheet href=…> → <style>
+ for (const match of [...html.matchAll(/<link\b[^>]*>/gi)]) {
+ const tag = match[0];
+ if (!/rel\s*=\s*["']?stylesheet/i.test(tag)) continue;
+ const rel = cleanRef(/href\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i.exec(tag)?.[1]);
+ const file = rel && files.get(rel);
+ if (!file) continue;
+ html = html.split(tag).join(`<style>${await rewriteCss(await readFile(file.abs, 'utf8'))}</style>`);
+ }
+ // <script src=…></script> → inline; portos-mv.js becomes the preview data.
+ for (const match of [...html.matchAll(/<script\b([^>]*)\bsrc\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)([^>]*)>\s*<\/script>/gi)]) {
+ const rel = cleanRef(match[2]);
+ if (!rel) continue;
+ if (rel === 'portos-mv.js') { html = html.split(match[0]).join(''); continue; }
+ const file = files.get(rel);
+ if (!file) continue;
+ html = html.split(match[0]).join(`<script${match[1]}${match[3]}>${inlineScript(await readFile(file.abs, 'utf8'))}</script>`);
+ }
+ // Inline <style> blocks and style="" attributes, then <img src>.
+ for (const match of [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)]) {
+ const next = await rewriteCss(match[1]);
+ if (next !== match[1]) html = html.split(match[0]).join(match[0].replace(match[1], () => next));
+ }
+ for (const match of [...html.matchAll(/<img\b[^>]*\bsrc\s*=\s*("[^"]*"|'[^']*')/gi)]) {
+ const rel = cleanRef(match[1]);
+ const url = rel ? await dataUrl(rel) : null;
+ if (url) html = html.split(match[0]).join(match[0].replace(match[1], () => `"${url}"`));
+ }
+ const head = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}"><script>${BOOTSTRAP}</script><script>window.PORTOS_MV = ${scriptJson(data)};</script>`;
+ const at = html.match(/<head[^>]*>/i);
+ html = at ? `${html.slice(0, at.index + at[0].length)}${head}${html.slice(at.index + at[0].length)}` : `${head}${html}`;
+
+ const assets = [];
+ for (const scene of data.scenes) {
+ const m = scene.media && media.get(scene.sceneId);
+ if (!m) continue;
+ const name = m.path.split(/[\\/]/).pop();
+ assets.push({ key: scene.media.src, url: `/data/${m.kind === 'video' ? 'videos' : 'images'}/${encodeURIComponent(name)}`, bytes: null });
+ }
+ for (const [rel, file] of files) {
+ if (inlinedKeys.has(rel) || !BRIDGED.has(extname(rel).toLowerCase())) continue;
+ assets.push({ key: rel, url: `/api/music-video/${encodeURIComponent(project.id)}/composition/document/file?path=${encodeURIComponent(rel)}`, bytes: file.size });
+ }
+ return { html, assets, width: frame.width, height: frame.height, fps: clock.fps, durationSec: clock.durationSec };
+}
diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.js
new file mode 100644
index 0000000000..de118b7d19
--- /dev/null
+++ b/server/services/musicVideo/documentRender.browser.test.js
@@ -0,0 +1,106 @@
+/**
+ * The shipped layered template with real Chrome and ffmpeg: an excerpt of a
+ * composition-document project seeks the selected take's <video> on SONG time
+ * (streamed to the page by byte range), renders frame-for-frame identically
+ * every time, and carries the master song. Skips without Chrome or ffmpeg.
+ */
+
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { mkdir, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { execFileSync, spawn } from 'node:child_process';
+import { chromium } from 'playwright-core';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+let endpoint;
+vi.mock('../browserService.js', () => ({ cdpRequest: (path) => fetch(`${endpoint}${path}`) }));
+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-document-browser-'),
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const { findFfmpeg } = await import('../../lib/ffmpeg.js');
+const { encodeDocumentComposition, prepareDocumentRender } = await import('./documentRender.js');
+const { importDocumentTemplate } = await import('./compositionDocument.js');
+const projects = await import('./projects.js');
+const { _cleanupTestBrowser } = await import('../htmlComposition/testBrowserCleanup.js');
+
+afterAll(() => cleanupTempDataRoots());
+
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+].find((path) => path && existsSync(path));
+const ffmpeg = await findFfmpeg();
+
+describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpeg', () => {
+ let proc;
+ let browser;
+ beforeAll(async () => {
+ const profile = join(PATHS.data, 'chrome-test-profile');
+ proc = spawn(chrome, ['--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });
+ const ws = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Test Chrome did not start')), 20000);
+ proc.once('error', reject);
+ proc.stderr.on('data', (bytes) => {
+ const match = bytes.toString().match(/DevTools listening on (ws:\/\/\S+)/);
+ if (match) { clearTimeout(timer); resolve(match[1]); }
+ });
+ });
+ endpoint = new URL(ws).origin.replace('ws:', 'http:');
+ browser = await chromium.connectOverCDP(endpoint);
+ }, 30000);
+ afterAll(() => _cleanupTestBrowser({ browser, proc, cleanup: () => {} }));
+
+ it('draws the selected take at SONG time in an excerpt, identically on every render, with the master muxed', async () => {
+ // A 3s clip: red, then green, then blue — each second a solid colour.
+ await mkdir(PATHS.videos, { recursive: true });
+ await mkdir(PATHS.music, { recursive: true });
+ const clip = join(PATHS.videos, 'rgb.webm');
+ execFileSync(ffmpeg, ['-v', 'error', '-y',
+ '-f', 'lavfi', '-i', 'color=c=red:s=640x360:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=lime:s=640x360:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=blue:s=640x360:r=24:d=1',
+ '-filter_complex', '[0:v][1:v][2:v]concat=n=3:v=1:a=0', '-c:v', 'libvpx', '-b:v', '1M', '-g', '24', clip]);
+ const master = join(PATHS.music, 'master.wav');
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=6', master]);
+ const created = await projects.createProject({ name: 'Excerpt' });
+ await projects.mutateProjectRecord(created.id, (current) => ({ project: {
+ ...current,
+ audioAnalysis: { durationSec: 6, beats: [], downbeats: [], sections: [] },
+ scenes: [{ sceneId: 'rgb', order: 0, startSec: 0, endSec: 3, videoHistoryId: 'vh-rgb' }],
+ } }));
+ await writeFile(join(PATHS.data, 'video-history.json'), JSON.stringify([{ id: 'vh-rgb', filename: 'rgb.webm', numFrames: 72, fps: 24, width: 640, height: 360 }]));
+ await importDocumentTemplate(created.id);
+ const project = await projects.getProject(created.id);
+ const plan = await prepareDocumentRender(project);
+
+ const render = async (name) => {
+ const outputPath = join(PATHS.videos, name);
+ const result = await encodeDocumentComposition({ project, plan, jobId: `job-${name.replace(/\W/g, '')}`, audioPath: master, outputPath, windowStart: 1.02, windowEnd: 1.75 });
+ return { result, outputPath };
+ };
+ const first = await render('first.mp4');
+ // Snapped down to the frame grid: song 1.0s → 1.75s is 18 frames.
+ expect(first.result).toMatchObject({ startSec: 1, durationSec: 0.75, width: 1920, height: 1080, fps: 24 });
+ const pixels = execFileSync(ffmpeg, ['-v', 'error', '-i', first.outputPath, '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 1 << 26 });
+ const frameBytes = 64 * 36 * 3;
+ expect(pixels.length / frameBytes).toBe(18);
+ for (let n = 0; n < 18; n++) {
+ const at = n * frameBytes + (18 * 64 + 32) * 3; // centre pixel
+ const [r, g, b] = pixels.subarray(at, at + 3);
+ // Song second 1 is the clip's green second — not the red of clip time 0.
+ expect(g, `frame ${n}`).toBeGreaterThan(r + 60);
+ expect(g, `frame ${n}`).toBeGreaterThan(b + 60);
+ }
+ const streams = execFileSync(ffmpeg.replace(/ffmpeg$/, 'ffprobe'), ['-v', 'error', '-show_entries', 'stream=codec_type', '-of', 'csv=p=0', first.outputPath]).toString();
+ expect(streams.split('\n').filter(Boolean).sort()).toEqual(['audio', 'video']);
+
+ const second = await render('second.mp4');
+ const hashes = (path) => execFileSync(ffmpeg, ['-v', 'error', '-i', path, '-map', '0:v', '-f', 'framemd5', '-']).toString().split('\n').filter((l) => l && !l.startsWith('#')).map((l) => l.split(',').pop().trim());
+ expect(hashes(second.outputPath)).toEqual(hashes(first.outputPath));
+ // The staged job folder is gone once the render ends.
+ expect(existsSync(join(PATHS.data, 'music-video-song-renders', 'job-firstmp4'))).toBe(false);
+ await rm(first.outputPath, { force: true });
+ await rm(second.outputPath, { force: true });
+ }, 120000);
+});
diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.js
new file mode 100644
index 0000000000..1cb102c949
--- /dev/null
+++ b/server/services/musicVideo/documentRender.js
@@ -0,0 +1,385 @@
+/**
+ * Music Video — render a project's composition document over the song.
+ *
+ * `composition.mode === 'document'` renders the project-owned HTML composition
+ * (compositionDocument.js) through the music-video owner of the sandboxed
+ * composition browser. Per job the document folder is copied into a private
+ * scratch directory (htmlComposition `stageMusicVideoComposition`), and PortOS
+ * adds the data the document draws from, before the snapshot freezes:
+ *
+ * portos-mv.js `window.PORTOS_MV = { project, render, song, lyrics, lyricMarkers,
+ * scenes, textCues, composition }` — read with a plain <script>,
+ * no fetch (the sandbox refuses network).
+ * song.json the same song block the code-rendered mode reads.
+ * media/ each scene's SELECTED take (video preferred, else its still)
+ * as `media/scene-<sceneId>.<ext>`, named by `scenes[].media.src`.
+ *
+ * The document stays song-timed: a full render seeks 0…durationSec, an excerpt
+ * seeks the SAME song times (`startSec + n / fps`), so a draft frame matches the
+ * full render at that song time. The picture is captured silent; the master
+ * song (plus the optional sound-design bed) is muxed after, trimmed to the
+ * window. The page declares its own size; the project's aspect ratio picks the
+ * frame, and a different aspect must be listed in `portosComposition.formats`
+ * (the page's optional `layout({ width, height })` hook reframes it).
+ */
+
+import { constants as fsConstants } from 'fs';
+import { copyFile, mkdir, rm, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/fileUtils.js';
+import { htmlCompositionContractSchemaFor } from '../../lib/validation.js';
+import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
+import { sceneVisualLayer } from '../../lib/musicVideoLayers.js';
+import { documentDirectoryForRender } from './compositionDocument.js';
+import { musicVideoSongDocument } from './compositionRender.js';
+import { buildSongDocument } from './codeTimeline.js';
+
+export const DOCUMENT_RENDER_FPS = 24;
+// The frame each project aspect renders at (the composition browser's sizes).
+export const DOCUMENT_FRAME_SIZES = Object.freeze({
+ '16:9': Object.freeze({ width: 1920, height: 1080 }),
+ '9:16': Object.freeze({ width: 1080, height: 1920 }),
+ '1:1': Object.freeze({ width: 1080, height: 1080 }),
+});
+const SONG_CAP_SEC = 900;
+
+const round3 = (n) => Math.round(n * 1000) / 1000;
+const finite = (n) => (typeof n === 'number' && Number.isFinite(n) ? n : null);
+const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
+const safeSegment = (id) => String(id || 'scene').replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 80) || 'scene';
+
+/** The project's aspect ratio (brief), defaulting to 16:9. */
+export function documentAspect(project) {
+ const aspect = project?.treatment?.brief?.aspectRatio;
+ return DOCUMENT_FRAME_SIZES[aspect] ? aspect : '16:9';
+}
+
+const aspectOf = (width, height) => {
+ const r = width / height;
+ if (Math.abs(r - 16 / 9) < 0.01) return '16:9';
+ if (Math.abs(r - 9 / 16) < 0.01) return '9:16';
+ if (Math.abs(r - 1) < 0.01) return '1:1';
+ return `${width}x${height}`;
+};
+
+/**
+ * The frame to render a validated page contract at for this project: the
+ * page's own size when its aspect matches, else a size it declares in
+ * `formats`. Throws COMPOSITION_DOCUMENT_FORMAT otherwise.
+ */
+function documentTargetFrame(contract, project) {
+ const aspect = documentAspect(project);
+ if (aspectOf(contract.width, contract.height) === aspect) return { ...contract };
+ const { width, height } = DOCUMENT_FRAME_SIZES[aspect];
+ const size = `${width}x${height}`;
+ if (!contract.formats?.includes(size)) {
+ throw new ServerError(`The composition document is ${contract.width}x${contract.height} and does not declare ${size} in portosComposition.formats (this project is ${aspect})`, {
+ status: 422, code: 'COMPOSITION_DOCUMENT_FORMAT',
+ });
+ }
+ return { ...contract, width, height };
+}
+
+/** The song length the document is timed against (analysis first). */
+export function documentSongDuration(project) {
+ const duration = finite(project?.audioAnalysis?.durationSec);
+ return duration && duration > 0 ? Math.min(duration, SONG_CAP_SEC) : null;
+}
+
+/** Whole frames that fit inside the song at `fps` (the contract ceiling). */
+export function documentRenderClock(songDurationSec, fps = DOCUMENT_RENDER_FPS) {
+ const frames = Math.max(0, Math.floor(songDurationSec * fps + 1e-6));
+ return { fps, frames, durationSec: frames / fps };
+}
+
+/**
+ * Each scene's selected take as a file to stage: `Map<sceneId, { kind, path,
+ * ext, inSec, outSec, fps, width, height }>`. Video is preferred over the still;
+ * a scene whose selection is missing on disk gets no entry (media: null).
+ * `history` is the video history list; `probe(path)` measures a clip the
+ * history did not (hosted renders record no geometry).
+ */
+export async function resolveSceneMedia(project, { history = [], probe = async () => null } = {}) {
+ const byId = new Map((Array.isArray(history) ? history : []).map((entry) => [entry.id, entry]));
+ const out = new Map();
+ const { safeUnder } = await import('../../lib/ffmpeg.js');
+ for (const scene of Array.isArray(project?.scenes) ? project.scenes : []) {
+ if (!scene?.sceneId) continue;
+ const entry = scene.videoHistoryId ? byId.get(scene.videoHistoryId) : null;
+ const videoPath = entry?.filename ? safeUnder(PATHS.videos, entry.filename) : null;
+ if (videoPath && existsSync(videoPath)) {
+ const measured = entry.numFrames && entry.fps && entry.width && entry.height ? entry : { ...entry, ...((await probe(videoPath)) || {}) };
+ const duration = measured.numFrames && measured.fps ? measured.numFrames / measured.fps : null;
+ const edit = selectedPerformanceInstruction(scene)?.edit ?? null;
+ const ext = (/\.([a-z0-9]{2,5})$/i.exec(entry.filename)?.[1] || 'mp4').toLowerCase();
+ out.set(scene.sceneId, {
+ kind: 'video',
+ path: videoPath,
+ ext,
+ inSec: edit ? round3(Math.min(edit.inSec, duration ?? edit.inSec)) : 0,
+ outSec: edit ? round3(Math.min(edit.outSec, duration ?? edit.outSec)) : (duration ? round3(duration) : null),
+ fps: finite(measured.fps),
+ width: finite(measured.width),
+ height: finite(measured.height),
+ });
+ continue;
+ }
+ const imagePath = scene.referenceImageId ? safeUnder(PATHS.images, scene.referenceImageId) : null;
+ if (imagePath && existsSync(imagePath)) {
+ const ext = (/\.([a-z0-9]{2,5})$/i.exec(scene.referenceImageId)?.[1] || 'png').toLowerCase();
+ out.set(scene.sceneId, { kind: 'image', path: imagePath, ext: ext === 'jpeg' ? 'jpg' : ext, inSec: null, outSec: null, fps: null, width: null, height: null });
+ }
+ }
+ return out;
+}
+
+const mediaSrc = (sceneId, media) => `media/scene-${safeSegment(sceneId)}.${media.ext}`;
+
+function sceneDirection(project, sceneId) {
+ const direction = (project?.treatment?.shotDirections || []).find((d) => d?.sceneId === sceneId);
+ if (!direction) return null;
+ const { mode, route, focalSubject, framing, typographyRole, emphasis, transitionIn, transitionOut } = direction;
+ return { mode, route, focalSubject, framing, typographyRole, emphasis, transitionIn, transitionOut };
+}
+
+/**
+ * The `window.PORTOS_MV` payload (pure). `media` is resolveSceneMedia's map;
+ * `frame` is `{ width, height }`; `clock` is documentRenderClock's result.
+ */
+export function buildDocumentData(project, { media = new Map(), frame, clock, songDurationSec }) {
+ const song = musicVideoSongDocument(project);
+ const analysis = project?.audioAnalysis || {};
+ const scenes = (Array.isArray(project?.scenes) ? project.scenes : [])
+ .filter((scene) => scene?.sceneId)
+ .slice()
+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
+ .map((scene) => {
+ const m = media.get(scene.sceneId) || null;
+ const start = finite(scene.startSec);
+ const end = finite(scene.endSec);
+ return {
+ sceneId: scene.sceneId,
+ label: typeof scene.label === 'string' ? scene.label : '',
+ sectionLabel: typeof scene.sectionLabel === 'string' ? scene.sectionLabel : null,
+ startSec: start,
+ endSec: start != null && end != null && end > start ? end : null,
+ shotMode: scene.shotMode === 'performance' ? 'performance' : 'cutaway',
+ visualLayer: sceneVisualLayer(scene, { layered: true }),
+ stillMove: typeof scene.stillMove === 'string' ? scene.stillMove : null,
+ cardText: typeof scene.cardText === 'string' ? scene.cardText : null,
+ cardColor: typeof scene.cardColor === 'string' ? scene.cardColor : null,
+ lyricText: typeof scene.lyricText === 'string' ? scene.lyricText : null,
+ visualIntent: typeof scene.visualIntent === 'string' ? scene.visualIntent : null,
+ direction: sceneDirection(project, scene.sceneId),
+ media: m ? {
+ kind: m.kind, src: mediaSrc(scene.sceneId, m),
+ inSec: m.inSec, outSec: m.outSec, fps: m.fps, width: m.width, height: m.height,
+ } : null,
+ };
+ });
+ const lyrics = buildSongDocument(project).lyrics;
+ const composition = project?.composition || {};
+ return {
+ version: 1,
+ project: { id: project?.id ?? null, name: project?.name ?? '', aspect: documentAspect(project) },
+ render: { width: frame.width, height: frame.height, fps: clock.fps, frames: clock.frames, durationSec: clock.durationSec },
+ song: {
+ durationSec: songDurationSec,
+ bpm: finite(analysis.bpm) ?? finite(analysis.tempo),
+ beats: song.beats,
+ downbeats: song.downbeats,
+ sections: song.sections,
+ words: song.words || [],
+ },
+ lyrics,
+ lyricMarkers: Array.isArray(project?.lyricMarkers) ? project.lyricMarkers : [],
+ scenes,
+ textCues: (composition.textCues || []).filter((cue) => cue?.text && cue.startSec != null && cue.endSec != null),
+ composition: {
+ mode: composition.mode || 'concat',
+ style: composition.style || null,
+ posterSec: composition.posterSec ?? null,
+ overlay: composition.overlay || null,
+ },
+ };
+}
+
+/**
+ * Everything a document render needs before the page opens. Throws
+ * COMPOSITION_DOCUMENT_MISSING (409) or NO_TIMELINE (422).
+ */
+export async function prepareDocumentRender(project) {
+ const directory = await documentDirectoryForRender(project);
+ const songDurationSec = documentSongDuration(project);
+ if (!songDurationSec) {
+ throw new ServerError('A composition document is timed against the song — analyze the track first', { status: 422, code: 'NO_TIMELINE' });
+ }
+ const clock = documentRenderClock(songDurationSec);
+ if (clock.frames < 1) throw new ServerError('The song is shorter than one frame', { status: 422, code: 'NO_TIMELINE' });
+ const frame = DOCUMENT_FRAME_SIZES[documentAspect(project)];
+ return { directory, songDurationSec, clock, frame, width: frame.width, height: frame.height, fps: clock.fps, durationSec: clock.durationSec };
+}
+
+/** Write portos-mv.js and copy the selected takes into a staged document folder. */
+async function stageDocumentData(compositionDir, data, media) {
+ await mkdir(join(compositionDir, 'media'), { recursive: true });
+ for (const scene of data.scenes) {
+ const m = scene.media && media.get(scene.sceneId);
+ if (!m) continue;
+ const target = join(compositionDir, scene.media.src);
+ // Clone where the file system can (APFS), refuse to overwrite a file the
+ // document shipped under PortOS's reserved name.
+ await copyFile(m.path, target, fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE).catch((error) => {
+ if (error.code === 'EEXIST') throw new ServerError(`The composition document ships ${scene.media.src}, a name PortOS writes at render time`, { status: 422, code: 'COMPOSITION_DOCUMENT_INVALID' });
+ throw error;
+ });
+ }
+ await writeFile(join(compositionDir, 'portos-mv.js'), `window.PORTOS_MV = ${scriptJson(data)};\n`);
+}
+
+/**
+ * The window a render seeks, on the document's own frame grid: the full
+ * contract, or `[startSec, endSec)` snapped down to a frame boundary.
+ */
+function documentRenderWindow(contract, { windowStart = null, windowEnd = null } = {}) {
+ if (windowStart == null && windowEnd == null) return { startSec: 0, durationSec: contract.durationSec, frames: Math.round(contract.durationSec * contract.fps) };
+ const fps = contract.fps;
+ if (!(windowStart >= 0) || !(windowEnd > windowStart) || windowStart >= contract.durationSec - 1e-6) {
+ throw new ServerError('The excerpt range must fall within the composition document', {
+ status: 422, code: 'INVALID_EXCERPT_RANGE', context: { totalDuration: contract.durationSec },
+ });
+ }
+ const firstFrame = Math.floor(windowStart * fps + 1e-6);
+ const lastFrame = Math.min(Math.round(contract.durationSec * fps), Math.ceil(Math.min(windowEnd, contract.durationSec) * fps - 1e-6));
+ const frames = Math.max(1, lastFrame - firstFrame);
+ return { startSec: firstFrame / fps, durationSec: frames / fps, frames };
+}
+
+/** Scene boundaries inside the window, relative to it (contact-sheet sample times). */
+function documentBoundaryTimes(data, window) {
+ const end = window.startSec + window.durationSec;
+ const times = new Set([0]);
+ for (const scene of data.scenes) {
+ for (const t of [scene.startSec, scene.endSec]) {
+ if (t == null || t < window.startSec - 1e-6 || t >= end - 1e-3) continue;
+ times.add(round3(Math.max(0, t - window.startSec)));
+ }
+ }
+ return [...times].sort((a, b) => a - b);
+}
+
+// Mux the silent picture with the master song (and the optional bed), both
+// cut to the window on SONG time.
+function documentMuxArgs(videoPath, audioPath, outputPath, { startSec, durationSec, songDurationSec, soundBed = null, buildBed, audioNorm }) {
+ if (!soundBed?.path) {
+ const args = ['-hide_banner', '-loglevel', 'error', '-i', videoPath];
+ if (startSec > 0) args.push('-ss', String(startSec));
+ 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`,
+ '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-y', outputPath);
+ return args;
+ }
+ const bed = buildBed({
+ beds: [{ assetPath: soundBed.path, offsetSec: 0, durationSec: songDurationSec, volume: soundBed.volume }],
+ firstInputIdx: 2, mainLabel: '[master]', outLabel: '[mixa]',
+ });
+ const filters = [`[1:a]${audioNorm}[master]`, ...bed.filters,
+ `[mixa]atrim=start=${startSec}:end=${startSec + durationSec},asetpts=PTS-STARTPTS,apad=whole_dur=${durationSec}[outa]`];
+ return ['-hide_banner', '-loglevel', 'error', '-i', videoPath, '-i', audioPath, ...bed.inputs,
+ '-filter_complex', filters.join(';'), '-map', '0:v:0', '-map', '[outa]', '-t', String(durationSec), '-c:v', 'copy',
+ '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-y', outputPath];
+}
+
+/**
+ * Stage, open, capture and mux one document render (full song or a window).
+ * Resolves `{ width, height, fps, durationSec, startSec, boundaryTimes }`.
+ */
+export async function encodeDocumentComposition({
+ project, plan, jobId, audioPath, soundBed = null, outputPath, signal, onProgress, windowStart = null, windowEnd = null,
+}) {
+ const { findFfmpeg, runFfmpegProcess, probeVideoGeometry } = await import('../../lib/ffmpeg.js');
+ const { stageMusicVideoComposition } = await import('../htmlComposition/index.js');
+ const { openComposition } = await import('../htmlComposition/browser.js');
+ const { encodeComposition } = await import('../htmlComposition/encode.js');
+ const { loadHistory } = await import('../videoGen/history.js');
+ const { AUDIO_NORM, buildAudioBedMix } = await import('../videoTimeline/audioBedMix.js');
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
+ const history = (project.scenes || []).some((s) => s?.videoHistoryId) ? await loadHistory() : [];
+ const media = await resolveSceneMedia(project, { history, probe: probeVideoGeometry });
+ const data = buildDocumentData(project, { media, frame: plan.frame, clock: plan.clock, songDurationSec: plan.songDurationSec });
+ const silent = `${outputPath}.silent.mp4`;
+ let staged;
+ let page;
+ try {
+ staged = await stageMusicVideoComposition(plan.directory, jobId, musicVideoSongDocument(project), {
+ prepare: (dir) => stageDocumentData(dir, data, media),
+ });
+ signal?.throwIfAborted();
+ page = await openComposition(staged.directory, { signal, streamMedia: true });
+ const metadata = await page.evaluate(`(() => {
+ const c = globalThis.portosComposition;
+ if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');
+ return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, formats: c.formats, layout: typeof c.layout === 'function' };
+ })()`);
+ // The managed browser is Google Chrome by default; a Chromium build without
+ // proprietary codecs cannot decode the H.264 takes. Say so up front instead
+ // of failing on the first scene's <video> error.
+ if ([...media.values()].some((m) => m.ext === 'mp4' || m.ext === 'mov')) {
+ const h264 = await page.evaluate(`document.createElement('video').canPlayType('video/mp4; codecs="avc1.640028"')`);
+ if (!h264) {
+ throw new ServerError('The managed browser cannot decode H.264 video (a Chromium build without proprietary codecs) — point Settings › Browser at Google Chrome', {
+ status: 422, code: 'COMPOSITION_BROWSER_CODEC',
+ });
+ }
+ }
+ const parsed = htmlCompositionContractSchemaFor(Math.max(1, plan.songDurationSec)).safeParse(metadata);
+ if (!parsed.success) {
+ throw new ServerError(`The composition document's contract is invalid — ${parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`, {
+ status: 422, code: 'COMPOSITION_DOCUMENT_CONTRACT',
+ });
+ }
+ const target = documentTargetFrame({ ...parsed.data, motionBlur: 1 }, project);
+ const window = documentRenderWindow(target, { windowStart, windowEnd });
+ await encodeComposition(page, { ...target, durationSec: window.durationSec }, silent, {
+ signal, offsetSec: window.startSec, onProgress: (fraction) => onProgress?.(fraction * 0.95),
+ });
+ page.check();
+ await page.close({ verify: true });
+ page = null;
+ signal?.throwIfAborted();
+ const mux = await runFfmpegProcess({
+ bin: ffmpeg, signal,
+ args: documentMuxArgs(silent, audioPath, outputPath, {
+ startSec: window.startSec, durationSec: window.durationSec, songDurationSec: plan.songDurationSec,
+ soundBed, buildBed: buildAudioBedMix, audioNorm: AUDIO_NORM,
+ }),
+ });
+ 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);
+ return {
+ width: target.width, height: target.height, fps: target.fps,
+ durationSec: window.durationSec, startSec: window.startSec,
+ boundaryTimes: documentBoundaryTimes(data, window),
+ };
+ } finally {
+ if (page) await page.close().catch(() => {});
+ if (staged?.scratchRoot) await rm(staged.scratchRoot, { recursive: true, force: true }).catch(() => {});
+ await rm(silent, { force: true }).catch(() => {});
+ }
+}
+
+/** Boot sweep: no document render survives a restart, so its scratch is stale. */
+export async function sweepDocumentScratch() {
+ const { MUSIC_VIDEO_SCRATCH_DIR } = await import('../htmlComposition/index.js');
+ await rm(join(PATHS.data, MUSIC_VIDEO_SCRATCH_DIR), { recursive: true, force: true });
+}
diff --git a/server/services/musicVideo/documentRender.test.js b/server/services/musicVideo/documentRender.test.js
new file mode 100644
index 0000000000..a7c5eb1f6b
--- /dev/null
+++ b/server/services/musicVideo/documentRender.test.js
@@ -0,0 +1,130 @@
+/**
+ * Composition-document render staging, through encodeDocumentComposition with
+ * the composition browser stubbed at its boundary: the job folder holds
+ * portos-mv.js with each scene's selected take and the take files beside the
+ * page, a reserved media name is refused, the page must be (or declare) the
+ * project's aspect, and the job folder is removed however the render ends.
+ */
+
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+const { browser } = vi.hoisted(() => ({ browser: { seen: null, contract: null } }));
+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-document-stage-'),
+}));
+// The staging assertions stop before ffmpeg ever runs; CI images have no
+// ffmpeg on PATH, so resolve the lookup instead of depending on the host.
+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ findFfmpeg: async () => 'ffmpeg',
+}));
+// Capture the frozen job folder the page would open, then stop the render.
+vi.mock('../htmlComposition/browser.js', () => ({
+ openComposition: async (directory) => {
+ const { readFile: read, readdir: list } = await import('node:fs/promises');
+ const { join: joinPath } = await import('node:path');
+ const { PATHS: paths } = await import('../../lib/paths.js');
+ const dir = joinPath(paths.data, directory);
+ const media = {};
+ for (const name of await list(joinPath(dir, 'media'))) media[name] = await read(joinPath(dir, 'media', name), 'utf8');
+ const window = {};
+ new Function('window', await read(joinPath(dir, 'portos-mv.js'), 'utf8'))(window);
+ browser.seen = { directory, data: window.PORTOS_MV, media, song: JSON.parse(await read(joinPath(dir, 'song.json'), 'utf8')) };
+ return {
+ async evaluate(expression) {
+ if (expression.includes('canPlayType')) return 'probably';
+ if (browser.contract) return browser.contract;
+ throw new Error('stop after staging');
+ },
+ check() {},
+ async close() {},
+ async send() { return {}; },
+ };
+ },
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const { encodeDocumentComposition, documentRenderClock } = await import('./documentRender.js');
+
+afterAll(() => cleanupTempDataRoots());
+beforeEach(() => { browser.seen = null; browser.contract = null; });
+
+const performanceTake = (assetId) => ({ takeId: 'mvt-p', kind: 'video', assetId, status: 'candidate', shotInstruction: { shotMode: 'performance', edit: { inSec: 0.5, outSec: 3.5 } } });
+
+async function fixture({ shipped = {} } = {}) {
+ await mkdir(PATHS.videos, { recursive: true });
+ await mkdir(PATHS.images, { recursive: true });
+ await writeFile(join(PATHS.videos, 'clip-a.mp4'), 'video-a');
+ await writeFile(join(PATHS.images, 'still-b.png'), 'image-b');
+ await writeFile(join(PATHS.data, 'video-history.json'), JSON.stringify([{ id: 'vh-a', filename: 'clip-a.mp4', numFrames: 96, fps: 24, width: 1280, height: 720 }]));
+ const directory = 'music-video/mv-stage/composition/doc-test';
+ await rm(join(PATHS.data, directory), { recursive: true, force: true });
+ await mkdir(join(PATHS.data, directory), { recursive: true });
+ await writeFile(join(PATHS.data, directory, 'index.html'), '<!doctype html><script src="portos-mv.js"></script>');
+ for (const [name, body] of Object.entries(shipped)) {
+ await mkdir(join(PATHS.data, directory, name, '..'), { recursive: true });
+ await writeFile(join(PATHS.data, directory, name), body);
+ }
+ const project = {
+ id: 'mv-stage', name: 'Stage', audioAnalysis: { durationSec: 30, beats: [0, 0.5], downbeats: [0], sections: [] },
+ lyricCues: [{ id: 'l1', text: 'first line', startSec: 1, endSec: 2 }],
+ composition: { mode: 'document', textCues: [{ id: 'c1', text: 'hero', startSec: 1, endSec: 2, emphasis: 'hero' }], overlay: { enabled: true, ticker: ['a'] } },
+ scenes: [
+ { sceneId: 'a', order: 0, startSec: 0, endSec: 4, videoHistoryId: 'vh-a', referenceImageId: 'still-b.png' },
+ { sceneId: 'b', order: 1, startSec: 4, endSec: 8, videoHistoryId: 'vh-gone', referenceImageId: 'still-b.png', visualLayer: 'still', stillMove: 'push' },
+ { sceneId: 'c', order: 2, startSec: 8, endSec: 9, visualLayer: 'card', cardText: 'Title' },
+ { sceneId: 'd', order: 3, startSec: 9, endSec: 12, shotMode: 'performance', videoHistoryId: 'vh-a', takes: [performanceTake('vh-a')] },
+ ],
+ };
+ const plan = { directory, songDurationSec: 30, clock: documentRenderClock(30), frame: { width: 1920, height: 1080 } };
+ return { project, plan };
+}
+
+const encode = (project, plan, jobId) => encodeDocumentComposition({ project, plan, jobId, audioPath: join(PATHS.data, 'none.wav'), outputPath: join(PATHS.videos, `${jobId}.mp4`) });
+const scratchEntries = async () => (await readdir(join(PATHS.data, 'music-video-song-renders')).catch(() => []));
+
+describe('composition document staging', () => {
+ it('writes portos-mv.js with each scene\'s selected take (video first) and copies the files beside the page', async () => {
+ const { project, plan } = await fixture();
+ await expect(encode(project, plan, 'job-stage')).rejects.toThrow('stop after staging');
+ const { data, media, song } = browser.seen;
+ const byId = Object.fromEntries(data.scenes.map((s) => [s.sceneId, s]));
+ expect(byId.a.media).toMatchObject({ kind: 'video', src: 'media/scene-a.mp4', inSec: 0, outSec: 4, fps: 24 });
+ expect(byId.b.media).toMatchObject({ kind: 'image', src: 'media/scene-b.png' });
+ expect(byId.b).toMatchObject({ visualLayer: 'still', stillMove: 'push' });
+ expect(byId.c).toMatchObject({ media: null, visualLayer: 'card', cardText: 'Title' });
+ expect(byId.d.media).toMatchObject({ kind: 'video', src: 'media/scene-d.mp4', inSec: 0.5, outSec: 3.5 });
+ expect(data.render).toEqual({ width: 1920, height: 1080, fps: 24, frames: 720, durationSec: 30 });
+ expect(data.song).toMatchObject({ durationSec: 30, beats: [0, 0.5], downbeats: [0] });
+ expect(data.lyrics.map((l) => l.text)).toEqual(['first line']);
+ expect(data.textCues.map((c) => c.emphasis)).toEqual(['hero']);
+ expect(data.composition).toMatchObject({ mode: 'document', overlay: { enabled: true, ticker: ['a'] } });
+ expect(media).toEqual({ 'scene-a.mp4': 'video-a', 'scene-b.png': 'image-b', 'scene-d.mp4': 'video-a' });
+ expect(song).toMatchObject({ beats: [0, 0.5], downbeats: [0] });
+ // The source document is untouched and the job folder is gone.
+ expect(existsSync(join(PATHS.data, plan.directory, 'portos-mv.js'))).toBe(false);
+ expect(await scratchEntries()).toEqual([]);
+ });
+
+ it('refuses a document that ships a file under a name PortOS writes at render time', async () => {
+ const { project, plan } = await fixture({ shipped: { 'media/scene-a.mp4': 'mine' } });
+ await expect(encode(project, plan, 'job-clash')).rejects.toMatchObject({ code: 'COMPOSITION_DOCUMENT_INVALID' });
+ expect(browser.seen).toBeNull();
+ expect(await readFile(join(PATHS.data, plan.directory, 'media/scene-a.mp4'), 'utf8')).toBe('mine');
+ expect(await scratchEntries()).toEqual([]);
+ });
+
+ it('renders the project aspect only when the page is that aspect or declares it', async () => {
+ const { project, plan } = await fixture();
+ browser.contract = { durationSec: 10, fps: 24, width: 1280, height: 720, layout: false };
+ const vertical = { ...project, treatment: { brief: { aspectRatio: '9:16' } } };
+ await expect(encode(vertical, plan, 'job-aspect')).rejects.toMatchObject({ code: 'COMPOSITION_DOCUMENT_FORMAT' });
+ browser.contract = { ...browser.contract, durationSec: 31 };
+ await expect(encode(project, plan, 'job-long')).rejects.toMatchObject({ code: 'COMPOSITION_DOCUMENT_CONTRACT' });
+ expect(await scratchEntries()).toEqual([]);
+ });
+});
diff --git a/server/services/musicVideo/documentTemplates/layered/engine.js b/server/services/musicVideo/documentTemplates/layered/engine.js
new file mode 100644
index 0000000000..4737c8b3df
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/layered/engine.js
@@ -0,0 +1,433 @@
+/* Layered music-video composition — the PortOS starting template.
+ *
+ * Every frame is a pure function of song time t: portosComposition.seek(t)
+ * draws the scene under t (its selected take, with a gentle camera move and a
+ * beat punch-in), film grain and a vignette, an optional HUD, and the words
+ * (subtitle lyrics, or kinetic hero words for text cues flagged "hero").
+ *
+ * Data: window.PORTOS_MV, written by PortOS as portos-mv.js at render time —
+ * { project, render, song, lyrics, lyricMarkers, scenes, textCues, composition }.
+ * scenes[].media.src names a file PortOS copied into media/ (the selected take).
+ * In the in-app preview window.PORTOS_MV_ASSETS resolves to { src: blob URL }.
+ *
+ * This file is yours once copied into a project: add project-specific cards
+ * (title cards, diagrams, outros) in CARDS below and key them from scene labels.
+ */
+(() => {
+ 'use strict';
+ const MV = window.PORTOS_MV;
+ if (!MV || !MV.render) throw new Error('PORTOS_MV is missing — PortOS writes portos-mv.js next to index.html when it renders');
+
+ // ---------- frame ----------
+ let W = MV.render.width;
+ let H = MV.render.height;
+ const FPS = MV.render.fps || 24;
+ const DURATION = MV.render.durationSec;
+ const canvas = document.getElementById('stage');
+ const ctx = canvas.getContext('2d');
+ let U = 1; // type/HUD unit: 1 at 1080px on the short side
+ function resize(width, height) {
+ W = width; H = height;
+ canvas.width = W; canvas.height = H;
+ U = Math.min(W, H) / 1080;
+ }
+ resize(W, H);
+
+ // ---------- palette & type (edit freely) ----------
+ const style = MV.composition?.style || {};
+ const C = {
+ ink: '#07090a', paper: style.color || '#eef1ea', dim: 'rgba(238,241,234,.62)', faint: 'rgba(238,241,234,.28)',
+ accent: '#ff5a1f', ok: '#b8d63a', alert: '#ff2a2a',
+ };
+ const F = {
+ stencil: (px) => `900 ${px}px "MV Stencil", Impact, sans-serif`,
+ cond: (px, w = 500) => `${w} ${px}px "MV Cond", "Arial Narrow", sans-serif`,
+ mono: (px, w = 400) => `${w} ${px}px "MV Mono", Menlo, monospace`,
+ };
+
+ // ---------- math ----------
+ const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+ const lerp = (a, b, k) => a + (b - a) * k;
+ const seg = (t, a, b) => (b > a ? clamp((t - a) / (b - a)) : (t >= b ? 1 : 0));
+ const easeOut = (k) => 1 - Math.pow(1 - k, 3);
+ const easeInOut = (k) => (k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2);
+ const hash = (n) => { const x = Math.sin(n * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };
+ const frameOf = (t) => Math.floor(t * FPS + 1e-6);
+
+ // ---------- song ----------
+ const beats = (MV.song?.beats || []).filter(Number.isFinite);
+ const downs = (MV.song?.downbeats || []).filter(Number.isFinite);
+ const sections = (MV.song?.sections || []).filter((s) => Number.isFinite(s?.startSec));
+ function lastIndex(list, t) {
+ let lo = 0; let hi = list.length - 1; let r = -1;
+ while (lo <= hi) { const m = (lo + hi) >> 1; if (list[m] <= t) { r = m; lo = m + 1; } else hi = m - 1; }
+ return r;
+ }
+ const sinceBeat = (t, list = beats) => { const i = lastIndex(list, t); return i < 0 ? 99 : t - list[i]; };
+ const pulse = (t, list = beats, k = 7) => Math.exp(-k * sinceBeat(t, list));
+ const sectionAt = (t) => sections.filter((s) => s.startSec <= t).pop() || null;
+ const isHighEnergy = (t) => /chorus|hook|drop|final|climax/i.test(sectionAt(t)?.label || '');
+
+ // ---------- scenes ----------
+ const SCENES = (MV.scenes || [])
+ .filter((s) => Number.isFinite(s.startSec) && Number.isFinite(s.endSec) && s.endSec > s.startSec)
+ .sort((a, b) => a.startSec - b.startSec)
+ .map((s, i) => ({ ...s, index: i }));
+ function sceneAt(t) {
+ let lo = 0; let hi = SCENES.length - 1; let r = -1;
+ while (lo <= hi) { const m = (lo + hi) >> 1; if (SCENES[m].startSec <= t) { r = m; lo = m + 1; } else hi = m - 1; }
+ const scene = r >= 0 ? SCENES[r] : null;
+ return scene && t < scene.endSec ? scene : null;
+ }
+ // Gentle camera moves (scale, offsets in frame fractions), picked per scene.
+ const MOVES = [
+ { s0: 1.04, s1: 1.12, x0: 0, x1: 0, y0: 0, y1: 0 },
+ { s0: 1.13, s1: 1.05, x0: 0, x1: 0, y0: 0, y1: 0 },
+ { s0: 1.09, s1: 1.09, x0: 0.022, x1: -0.022, y0: 0, y1: 0 },
+ { s0: 1.09, s1: 1.09, x0: -0.022, x1: 0.022, y0: 0, y1: 0 },
+ { s0: 1.05, s1: 1.11, x0: 0, x1: 0, y0: 0.018, y1: -0.01 },
+ ];
+ function moveFor(scene) {
+ if (scene.media?.kind === 'video') return { s0: 1.02, s1: 1.06, x0: 0, x1: 0, y0: 0, y1: 0 };
+ if (scene.stillMove === 'hold') return { s0: 1.03, s1: 1.04, x0: 0, x1: 0, y0: 0, y1: 0 };
+ if (scene.stillMove === 'push') return MOVES[0];
+ if (scene.stillMove === 'pan') return MOVES[2 + (scene.index % 2)];
+ return MOVES[scene.index % MOVES.length];
+ }
+
+ // ---------- media (lazy, a few decoders at a time) ----------
+ let assetUrls = null;
+ const urlOf = (src) => (assetUrls && assetUrls[src]) || src;
+ const images = new Map();
+ const videos = new Map();
+ const MAX_VIDEOS = 4;
+ const MAX_IMAGES = 16;
+ function touch(map, key) { const v = map.get(key); map.delete(key); map.set(key, v); return v; }
+ function evict(map, max, release) {
+ while (map.size > max) { const [key, value] = map.entries().next().value; map.delete(key); release(value); }
+ }
+ function loadImage(src) {
+ if (images.has(src)) return touch(images, src).ready;
+ const im = new Image();
+ const entry = { el: im, ready: new Promise((resolve, reject) => {
+ im.onload = () => resolve(im);
+ im.onerror = () => reject(new Error(`image failed to load: ${src}`));
+ }) };
+ im.src = urlOf(src);
+ images.set(src, entry);
+ evict(images, MAX_IMAGES, () => {});
+ return entry.ready;
+ }
+ function loadVideo(src) {
+ if (videos.has(src)) return touch(videos, src).ready;
+ const v = document.createElement('video');
+ v.muted = true; v.playsInline = true; v.preload = 'auto';
+ const entry = { el: v, ready: new Promise((resolve, reject) => {
+ v.addEventListener('loadeddata', () => resolve(v), { once: true });
+ v.addEventListener('error', () => reject(new Error(`video failed to load: ${src} (${v.error?.code ?? '?'})`)), { once: true });
+ }) };
+ v.src = urlOf(src);
+ videos.set(src, entry);
+ evict(videos, MAX_VIDEOS, (old) => { old.el.pause(); old.el.removeAttribute('src'); old.el.load(); });
+ return entry.ready;
+ }
+ // Seek to the middle of the source frame under `local` so a frame boundary
+ // can never round to the previous frame; resolve only on 'seeked'.
+ function seekVideo(v, media, local) {
+ const fps = media.fps || FPS;
+ const last = Math.max(0, (Number.isFinite(media.outSec) ? media.outSec : v.duration) - 0.5 / fps);
+ const clamped = Math.min(Math.max(local, media.inSec || 0), last);
+ const target = Math.min((Math.floor(clamped * fps + 1e-6) + 0.5) / fps, Math.max(0, v.duration - 1e-3));
+ if (Math.abs(v.currentTime - target) < 1e-6 && v.readyState >= 2 && !v.seeking) return Promise.resolve(v);
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { cleanup(); reject(new Error(`video seek timed out: ${media.src} @ ${target.toFixed(3)}s`)); }, 15000);
+ const done = () => { cleanup(); resolve(v); };
+ const fail = () => { cleanup(); reject(new Error(`video seek failed: ${media.src} (${v.error?.code ?? '?'})`)); };
+ function cleanup() { clearTimeout(timer); v.removeEventListener('seeked', done); v.removeEventListener('error', fail); }
+ v.addEventListener('seeked', done);
+ v.addEventListener('error', fail);
+ v.currentTime = target;
+ });
+ }
+ // Resolve the drawable for a scene at song time t (and warm the next scene).
+ async function sourceFor(scene, t) {
+ const media = scene?.media;
+ if (!media?.src) return null;
+ const next = SCENES[scene.index + 1];
+ if (next?.media?.src) (next.media.kind === 'video' ? loadVideo(next.media.src) : loadImage(next.media.src)).catch(() => {});
+ if (media.kind === 'video') {
+ const v = await loadVideo(media.src);
+ return seekVideo(v, media, (media.inSec || 0) + (t - scene.startSec));
+ }
+ return loadImage(media.src);
+ }
+
+ // ---------- drawing helpers ----------
+ function drawCover(src, k, move, extraScale = 1) {
+ const sw = src.videoWidth || src.naturalWidth || src.width;
+ const sh = src.videoHeight || src.naturalHeight || src.height;
+ if (!sw || !sh) return;
+ const s = lerp(move.s0, move.s1, easeInOut(k)) * extraScale;
+ const base = Math.max(W / sw, H / sh) * s;
+ const dw = sw * base; const dh = sh * base;
+ const ox = lerp(move.x0, move.x1, easeInOut(k)) * W;
+ const oy = lerp(move.y0, move.y1, easeInOut(k)) * H;
+ ctx.drawImage(src, (W - dw) / 2 + ox, (H - dh) / 2 + oy, dw, dh);
+ }
+ const grainTiles = [];
+ function buildGrain() {
+ for (let n = 0; n < 6; n++) {
+ const c = document.createElement('canvas'); c.width = 256; c.height = 256;
+ const g = c.getContext('2d'); const d = g.createImageData(256, 256);
+ for (let i = 0; i < d.data.length; i += 4) {
+ const v = 128 + (hash(i * 0.37 + n * 1013.3) - 0.5) * 255;
+ d.data[i] = v; d.data[i + 1] = v; d.data[i + 2] = v; d.data[i + 3] = 255;
+ }
+ g.putImageData(d, 0, 0); grainTiles.push(c);
+ }
+ }
+ function grain(t, amount = 0.09) {
+ const f = frameOf(t);
+ ctx.save(); ctx.globalAlpha = amount; ctx.globalCompositeOperation = 'overlay';
+ ctx.fillStyle = ctx.createPattern(grainTiles[f % grainTiles.length], 'repeat');
+ const off = hash(f) * 256;
+ ctx.translate(-off, -off * 0.7); ctx.fillRect(0, 0, W + 512, H + 512);
+ ctx.restore();
+ }
+ function vignette(strength = 0.5) {
+ const g = ctx.createRadialGradient(W / 2, H / 2, Math.min(W, H) * 0.35, W / 2, H / 2, Math.max(W, H) * 0.62);
+ g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(1, `rgba(0,0,0,${strength})`);
+ ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
+ }
+ function flash(k, color = '#fff') { if (k <= 0.001) return; ctx.save(); ctx.globalAlpha = clamp(k); ctx.fillStyle = color; ctx.fillRect(0, 0, W, H); ctx.restore(); }
+ function glitch(t, strength) {
+ if (strength <= 0.02) return;
+ const f = frameOf(t);
+ const n = 3 + Math.floor(hash(f) * 5);
+ for (let i = 0; i < n; i++) {
+ const y = Math.floor(hash(f * 3 + i) * H); const h = 6 + Math.floor(hash(f * 7 + i) * 80 * U * strength);
+ const dx = (hash(f * 11 + i) - 0.5) * 200 * U * strength;
+ ctx.drawImage(canvas, 0, y, W, h, dx, y, W, h);
+ }
+ }
+ function text(str, x, y, font, color, align = 'left') {
+ ctx.font = font; ctx.fillStyle = color; ctx.textAlign = align; ctx.textBaseline = 'alphabetic'; ctx.fillText(str, x, y);
+ }
+ function wrap(words, maxW, measure) {
+ const lines = [[]]; let width = 0;
+ for (const w of words) {
+ const ww = measure(w);
+ if (width + ww > maxW && lines[lines.length - 1].length) { lines.push([]); width = 0; }
+ lines[lines.length - 1].push(w); width += ww;
+ }
+ return lines;
+ }
+
+ // ---------- words ----------
+ const norm = (s) => String(s).toLowerCase().replace(/[’]/g, "'").replace(/[^a-z0-9']/g, '');
+ const songWords = (MV.song?.words || []).filter((w) => Number.isFinite(w?.startSec));
+ // Kinetic hero words for a text cue: each word lands on its sung time when
+ // the aligned lyric words match, else spread across the cue.
+ function heroWordsFor(cue) {
+ const tokens = String(cue.text).split(/\s+/).filter(Boolean);
+ const pool = songWords.filter((w) => w.startSec >= cue.startSec - 0.35 && w.startSec <= cue.endSec + 0.2);
+ const out = []; let j = 0;
+ for (const token of tokens) {
+ const key = norm(token);
+ let hit = null;
+ for (let k = j; k < pool.length; k++) {
+ const p = norm(pool[k].w);
+ if (p === key || (key.length > 3 && p.startsWith(key.slice(0, 4)))) { hit = pool[k]; j = k + 1; break; }
+ }
+ out.push({ w: token.toUpperCase(), t0: hit ? hit.startSec : null });
+ }
+ if (out.some((w) => w.t0 == null)) {
+ const span = Math.max(0.2, (cue.endSec - cue.startSec) * 0.8);
+ out.forEach((w, i) => { w.t0 = cue.startSec + (i * span) / Math.max(1, out.length); });
+ }
+ return out;
+ }
+ const CUES = (MV.textCues || []).filter((c) => Number.isFinite(c.startSec) && Number.isFinite(c.endSec) && c.endSec > c.startSec);
+ const HERO = CUES.filter((c) => c.emphasis === 'hero').map((c) => ({ ...c, words: heroWordsFor(c) }));
+ const SUBTITLE_CUES = CUES.filter((c) => c.emphasis !== 'hero');
+ // Subtitles: the director's subtitle cues when there are any, else the lyrics.
+ const SUBTITLES = (SUBTITLE_CUES.length ? SUBTITLE_CUES : (MV.lyrics || []))
+ .filter((l) => l?.text && Number.isFinite(l.startSec))
+ .map((l) => ({ text: l.text, startSec: l.startSec, endSec: Number.isFinite(l.endSec) ? l.endSec : l.startSec + 2.5 }));
+
+ function heroWords(t, cue) {
+ const shown = cue.words.filter((w) => t >= w.t0 - 0.02);
+ if (!shown.length) return;
+ const maxW = W - 180 * U;
+ let px = Math.round((W > H ? 150 : 120) * U);
+ ctx.font = F.stencil(px);
+ const measure = (w) => ctx.measureText(`${w.w} `).width;
+ let lines = wrap(cue.words, maxW, measure);
+ while (lines.length > 3 && px > 40) { px = Math.round(px * 0.88); ctx.font = F.stencil(px); lines = wrap(cue.words, maxW, measure); }
+ const lineH = px * 0.92;
+ const baseY = cue.placement === 'upper' ? 220 * U + lineH : cue.placement === 'center' ? H / 2 + lineH / 2 : H - 150 * U;
+ const topY = baseY - (lines.length - 1) * lineH;
+ const out = seg(t, cue.endSec - 0.12, cue.endSec);
+ lines.forEach((line, li) => {
+ let x = W > H ? 96 * U : (W - line.reduce((s, w) => s + measure(w), 0)) / 2;
+ for (const w of line) {
+ const ww = measure(w);
+ if (t >= w.t0 - 0.02) {
+ const k = seg(t, w.t0 - 0.02, w.t0 + 0.09);
+ const sc = lerp(1.35, 1, easeOut(k));
+ ctx.save(); ctx.globalAlpha = 1 - out;
+ ctx.translate(x, topY + li * lineH); ctx.scale(sc, sc);
+ ctx.font = F.stencil(px); ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+ if (k < 1) { ctx.fillStyle = C.accent; ctx.fillText(w.w, 6 * U, 0); }
+ ctx.fillStyle = C.paper; ctx.fillText(w.w, 0, 0);
+ ctx.restore();
+ }
+ x += ww;
+ }
+ });
+ }
+ function subtitle(t, line) {
+ const a = Math.min(seg(t, line.startSec, line.startSec + 0.08), 1 - seg(t, line.endSec - 0.08, line.endSec));
+ if (a <= 0) return;
+ const px = Math.round(44 * U);
+ ctx.save(); ctx.globalAlpha = a; ctx.font = F.cond(px, 500);
+ const lines = wrap(line.text.split(/\s+/), W - 240 * U, (w) => ctx.measureText(`${w} `).width).map((l) => l.join(' '));
+ const lineH = px * 1.3;
+ const bottom = H - (W > H ? 150 : 260) * U;
+ lines.forEach((str, i) => {
+ const y = bottom - (lines.length - 1 - i) * lineH;
+ const w = ctx.measureText(str).width;
+ ctx.fillStyle = 'rgba(7,9,10,.55)'; ctx.fillRect(W / 2 - w / 2 - 18 * U, y - px, w + 36 * U, px * 1.35);
+ text(str, W / 2, y, F.cond(px, 500), C.paper, 'center');
+ });
+ ctx.restore();
+ }
+
+ // ---------- HUD (composition.overlay) ----------
+ const HUD = MV.composition?.overlay && MV.composition.overlay.enabled !== false ? MV.composition.overlay : null;
+ function interp(keys, t) {
+ if (!keys?.length) return null;
+ if (t <= keys[0][0]) return keys[0][1];
+ for (let i = 1; i < keys.length; i++) {
+ if (t < keys[i][0]) { const [a, va] = keys[i - 1]; const [b, vb] = keys[i]; return lerp(va, vb, easeInOut(seg(t, a, b))); }
+ }
+ return keys[keys.length - 1][1];
+ }
+ function drawHud(t) {
+ if (!HUD) return;
+ const f = frameOf(t);
+ const m = 40 * U; const L = 34 * U; const pad = 64 * U;
+ ctx.save();
+ ctx.globalAlpha = 0.92 * seg(t, 0.2, 1.2);
+ ctx.strokeStyle = C.dim; ctx.lineWidth = Math.max(1, 2 * U);
+ [[m, m, 1, 1], [W - m, m, -1, 1], [m, H - m, 1, -1], [W - m, H - m, -1, -1]].forEach(([x, y, sx, sy]) => {
+ ctx.beginPath(); ctx.moveTo(x, y + sy * L); ctx.lineTo(x, y); ctx.lineTo(x + sx * L, y); ctx.stroke();
+ });
+ (HUD.titleLines || []).forEach((line, i) => text(line, pad, pad + 22 * U + i * 26 * U, F.mono(Math.round(19 * U), i === 0 ? 600 : 400), i === 0 ? C.paper : C.dim));
+ const recY = pad + 22 * U + (HUD.titleLines?.length || 0) * 26 * U + 8 * U;
+ if (f % 24 < 14) { ctx.fillStyle = C.alert; ctx.beginPath(); ctx.arc(pad + 8 * U, recY, 7 * U, 0, Math.PI * 2); ctx.fill(); }
+ text('REC', pad + 24 * U, recY + 7 * U, F.mono(Math.round(18 * U), 600), C.paper);
+ const pct = interp(HUD.meter?.keyframes, t);
+ if (pct != null) {
+ const bw = Math.min(360 * U, W * 0.36); const bx = W - pad - bw; const by = pad + 8 * U;
+ const color = pct < 25 ? C.alert : pct < 60 ? C.accent : C.ok;
+ text(HUD.meter.label || 'LEVEL', bx, by + 14 * U, F.mono(Math.round(18 * U), 600), C.paper);
+ text(`${pct.toFixed(0)}%`, W - pad, by + 14 * U, F.mono(Math.round(26 * U), 600), color, 'right');
+ ctx.strokeStyle = C.dim; ctx.strokeRect(bx, by + 28 * U, bw, 14 * U);
+ ctx.fillStyle = color;
+ const segs = 30; const sw = (bw - 6 * U) / segs;
+ for (let i = 0; i < segs; i++) if (i / segs < pct / 100) ctx.fillRect(bx + 3 * U + i * sw, by + 31 * U, sw * 0.75, 8 * U);
+ }
+ if (HUD.timecode !== false) {
+ const sec = (HUD.timecodeStartSec || 0) + t;
+ const pad2 = (n) => String(n).padStart(2, '0');
+ const tc = `${pad2(Math.floor(sec / 3600))}:${pad2(Math.floor(sec / 60) % 60)}:${pad2(Math.floor(sec) % 60)}:${pad2(f % FPS)}`;
+ text(tc, W - pad, H - pad, F.mono(Math.round(19 * U)), C.dim, 'right');
+ }
+ ctx.fillStyle = C.faint;
+ for (let i = 0; i < 18; i++) ctx.fillRect(m, H * 0.2 + i * 36 * U, i % 4 === 0 ? 22 * U : 11 * U, Math.max(1, 2 * U));
+ const ticker = HUD.ticker || [];
+ if (ticker.length) {
+ const sep = ' ◆ ';
+ const str = ticker.join(sep);
+ ctx.font = F.mono(Math.round(17 * U));
+ const full = ctx.measureText(str + sep).width;
+ const off = (t * 120 * U) % full;
+ const width = W - 2 * pad - (HUD.timecode !== false ? 340 * U : 0);
+ ctx.save(); ctx.beginPath(); ctx.rect(pad, H - pad - 32 * U, width, 30 * U); ctx.clip();
+ ctx.fillStyle = C.dim; ctx.textAlign = 'left'; ctx.fillText(str + sep + str, pad - off, H - pad - 8 * U);
+ ctx.restore();
+ ctx.fillStyle = C.faint; ctx.fillRect(pad, H - pad - 36 * U, W - 2 * pad, 1);
+ }
+ ctx.restore();
+ }
+
+ // ---------- cards (add project-specific ones here) ----------
+ // A card draws the whole scene layer: (t, localT, durationSec, scene, source).
+ const CARDS = {
+ // A title card from the scene's card text on its card colour.
+ title(t, lt, d, scene) {
+ ctx.fillStyle = scene.cardColor || C.ink; ctx.fillRect(0, 0, W, H);
+ const str = (scene.cardText || scene.label || '').toUpperCase();
+ if (!str) return;
+ let px = Math.round(220 * U);
+ ctx.font = F.stencil(px);
+ while (ctx.measureText(str).width > W - 160 * U && px > 40) { px = Math.round(px * 0.9); ctx.font = F.stencil(px); }
+ const k = easeOut(seg(lt, 0, 0.25));
+ ctx.save(); ctx.globalAlpha = k * (1 - seg(lt, d - 0.2, d));
+ ctx.translate(W / 2, H / 2 + px * 0.36); ctx.scale(lerp(1.2, 1, k), lerp(1.2, 1, k));
+ text(str, 0, 0, F.stencil(px), C.paper, 'center');
+ ctx.restore();
+ glitch(t, pulse(t, downs, 9) * 0.6);
+ },
+ };
+ const cardFor = (scene) => (scene?.visualLayer === 'card' ? CARDS.title : null);
+
+ // ---------- frame ----------
+ function render(t, scene, source) {
+ ctx.fillStyle = C.ink; ctx.fillRect(0, 0, W, H);
+ if (scene) {
+ const lt = t - scene.startSec; const d = scene.endSec - scene.startSec;
+ const card = cardFor(scene);
+ if (card) card(t, lt, d, scene, source);
+ else if (source) {
+ const energetic = isHighEnergy(t) || scene.shotMode === 'performance';
+ const punch = 1 + 0.018 * pulse(t, energetic ? beats : downs, 8);
+ drawCover(source, seg(t, scene.startSec, scene.endSec), moveFor(scene), punch);
+ }
+ if (isHighEnergy(t)) glitch(t, pulse(t, downs, 8) * 0.5);
+ }
+ vignette(0.5);
+ grain(t, 0.09);
+ drawHud(t);
+ const hero = HERO.find((c) => t >= c.startSec && t < c.endSec);
+ if (hero) heroWords(t, hero);
+ else {
+ const line = SUBTITLES.find((l) => t >= l.startSec && t < l.endSec);
+ if (line) subtitle(t, line);
+ }
+ }
+
+ // ---------- contract ----------
+ const ready = (async () => {
+ if (window.PORTOS_MV_ASSETS) assetUrls = await window.PORTOS_MV_ASSETS;
+ await Promise.all([F.stencil(40), F.mono(20), F.mono(20, 600), F.cond(20), F.cond(20, 700)].map((font) => document.fonts.load(font)));
+ buildGrain();
+ })();
+ globalThis.portosComposition = {
+ durationSec: DURATION,
+ fps: FPS,
+ width: W,
+ height: H,
+ // One timeline, every aspect: the layout hook reframes before capture.
+ formats: ['1920x1080', '1080x1920', '1080x1080'],
+ layout({ width, height }) { resize(width, height); },
+ async seek(t) {
+ await ready;
+ const scene = sceneAt(t);
+ const source = scene && !cardFor(scene) ? await sourceFor(scene, t) : null;
+ render(t, scene, source);
+ return true;
+ },
+ };
+})();
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/LICENSE-Big-Shoulders.txt b/server/services/musicVideo/documentTemplates/layered/fonts/LICENSE-Big-Shoulders.txt
new file mode 100644
index 0000000000..b5a4e0dff0
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/layered/fonts/LICENSE-Big-Shoulders.txt
@@ -0,0 +1,93 @@
+Copyright 2019 The Big Shoulders Project Authors (https://github.com/xotypeco/big_shoulders)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/LICENSE-IBM-Plex.txt b/server/services/musicVideo/documentTemplates/layered/fonts/LICENSE-IBM-Plex.txt
new file mode 100644
index 0000000000..01497cc60d
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/layered/fonts/LICENSE-IBM-Plex.txt
@@ -0,0 +1,93 @@
+Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/big-shoulders-stencil-display-900.woff2 b/server/services/musicVideo/documentTemplates/layered/fonts/big-shoulders-stencil-display-900.woff2
new file mode 100644
index 0000000000..48757942d6
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/layered/fonts/big-shoulders-stencil-display-900.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-mono-400.woff2 b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-mono-400.woff2
new file mode 100644
index 0000000000..0804aaff92
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-mono-400.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-mono-600.woff2 b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-mono-600.woff2
new file mode 100644
index 0000000000..67aeeb0104
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-mono-600.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-sans-condensed-500.woff2 b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-sans-condensed-500.woff2
new file mode 100644
index 0000000000..cae454121b
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-sans-condensed-500.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-sans-condensed-700.woff2 b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-sans-condensed-700.woff2
new file mode 100644
index 0000000000..149ab39e83
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/layered/fonts/ibm-plex-sans-condensed-700.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/layered/index.html b/server/services/musicVideo/documentTemplates/layered/index.html
new file mode 100644
index 0000000000..02206437ac
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/layered/index.html
@@ -0,0 +1,25 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Layered music-video composition</title>
+<style>
+@font-face { font-family: "MV Stencil"; src: url(fonts/big-shoulders-stencil-display-900.woff2) format("woff2"); font-weight: 900; }
+@font-face { font-family: "MV Mono"; src: url(fonts/ibm-plex-mono-400.woff2) format("woff2"); font-weight: 400; }
+@font-face { font-family: "MV Mono"; src: url(fonts/ibm-plex-mono-600.woff2) format("woff2"); font-weight: 600; }
+@font-face { font-family: "MV Cond"; src: url(fonts/ibm-plex-sans-condensed-500.woff2) format("woff2"); font-weight: 500; }
+@font-face { font-family: "MV Cond"; src: url(fonts/ibm-plex-sans-condensed-700.woff2) format("woff2"); font-weight: 700; }
+html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
+/* The canvas keeps the render frame's pixels; CSS only fits it to the viewport
+ (the render's viewport IS the frame, the in-app preview is smaller). */
+#stage { display: block; width: 100vw; height: 100vh; object-fit: contain; }
+</style>
+</head>
+<body>
+<canvas id="stage"></canvas>
+<!-- PortOS writes portos-mv.js (window.PORTOS_MV) and media/ next to this page at render time. -->
+<script src="portos-mv.js"></script><!-- portos-allow-hidden-content: the render-time data file -->
+<script src="engine.js"></script><!-- portos-allow-hidden-content: the reviewed template engine beside this page -->
+</body>
+</html>
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index 85b39486a0..175827de4f 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -29,8 +29,9 @@ 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, resolveMasterAudioPath } from './render.js';
+import { planMusicVideoRender, buildMusicVideoFfmpegArgs, excerptBoundaryTimes, isLocalRenderMark, resolveMasterAudioPath, resolveSoundBedPath } from './render.js';
import { encodeCodeComposition, prepareCodeRender, writeCodeProofSheet } from './codeRender.js';
+import { encodeDocumentComposition, prepareDocumentRender } from './documentRender.js';
import { renderableCues, sectionCardCues } from './composition.js';
import { renderTypographyOverlays, removeCompositionScratch } from './compositionRender.js';
import { startExcerptOnProject, applyExcerptPatch } from './excerpt.js';
@@ -76,29 +77,60 @@ 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);
- // Same order as a full code render: a missing master throws before the
+// A code-rendered or composition-document project excerpts the same seekable
+// composition, windowed on song time, instead of the footage concat.
+const SEEKED_EXCERPTS = Object.freeze({
+ code: {
+ label: 'code',
+ prepare: async (project) => {
+ const full = prepareCodeRender(project);
+ return { full, totalSec: full.durationSec, songSections: full.song.sections.map((s) => ({ sceneId: s.sceneId || s.id, startSec: s.startSec, endSec: s.endSec })) };
+ },
+ encode: async ({ project, projectId, jobId, audioPath, outputPath, signal, onProgress, startSec, endSec }) => {
+ const plan = prepareCodeRender(project, { windowStart: startSec, windowEnd: endSec });
+ await encodeCodeComposition({
+ ...plan, audioPath, audioStartSec: startSec, outputPath, directory: `compositions/music-video/${projectId}/${jobId}`, signal, onProgress,
+ });
+ return { width: plan.width, height: plan.height, fps: plan.fps, boundaryTimes: plan.sectionTimes };
+ },
+ },
+ document: {
+ label: 'composition document',
+ soundBed: true,
+ prepare: async (project) => {
+ const plan = await prepareDocumentRender(project);
+ const songSections = (project.scenes || [])
+ .filter((s) => s?.sceneId && typeof s.startSec === 'number' && typeof s.endSec === 'number' && s.endSec > s.startSec)
+ .map((s) => ({ sceneId: s.sceneId, startSec: s.startSec, endSec: s.endSec }));
+ return { plan, totalSec: plan.durationSec, songSections };
+ },
+ encode: ({ prepared, project, jobId, audioPath, soundBed, outputPath, signal, onProgress, startSec, endSec }) => encodeDocumentComposition({
+ project, plan: prepared.plan, jobId, audioPath, soundBed, outputPath, signal, onProgress, windowStart: startSec, windowEnd: endSec,
+ }),
+ },
+});
+
+async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revisionId, handOff, renderer }) {
+ const prepared = await renderer.prepare(project);
+ // Same order as a full render: a missing master throws before the
// excerpt is marked rendering.
const audioPath = await resolveMasterAudioPath(project);
- if (!(startSec >= 0) || !(endSec > startSec) || endSec > full.durationSec + 1e-6) {
+ const soundBed = renderer.soundBed ? await resolveSoundBedPath(project) : null;
+ if (!(startSec >= 0) || !(endSec > startSec) || endSec > prepared.totalSec + 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 } },
+ `The excerpt range must fall within the project's ${prepared.totalSec.toFixed(2)}s song`,
+ { status: 422, code: 'INVALID_EXCERPT_RANGE', context: { totalDuration: prepared.totalSec } },
);
}
- const endClamped = Math.min(endSec, full.durationSec);
- const plan = prepareCodeRender(project, { windowStart: startSec, windowEnd: endClamped });
+ const endClamped = Math.min(endSec, prepared.totalSec);
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
+ const sections = prepared.songSections
.filter((section) => section.startSec < endClamped && section.endSec > startSec)
.map((section) => ({
- sceneId: section.sceneId || section.id,
+ sceneId: section.sceneId,
startSec: round3(Math.max(section.startSec, startSec)),
endSec: round3(Math.min(section.endSec, endClamped)),
}));
@@ -109,44 +141,40 @@ async function launchCodeExcerpt({ projectId, project, startSec, endSec, revisio
});
const excerptId = excerpt.id;
const jobId = excerptId;
- const totalDuration = plan.durationSec;
+ const totalDuration = endClamped - startSec;
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 Label = `${renderer.label[0].toUpperCase()}${renderer.label.slice(1)}`;
+ console.log(`🎬 Rendering ${renderer.label} 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}`);
+ console.error(`❌ Music-video ${renderer.label} 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,
+ Promise.resolve().then(() => renderer.encode({
+ prepared, project, projectId, jobId, audioPath, soundBed, outputPath, signal, startSec, endSec: endClamped,
onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),
- }).then(async () => {
+ })).then(async (encoded) => {
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,
+ await writeCodeProofSheet(outputPath, join(PATHS.videoThumbnails, contactSheetFilename), encoded.boundaryTimes, {
+ width: encoded.width, height: encoded.height, fps: encoded.fps,
});
} catch (err) {
- console.warn(`⚠️ Music-video code excerpt contact sheet failed [${jobId.slice(4, 12)}]: ${err.message}`);
+ console.warn(`⚠️ Music-video ${renderer.label} excerpt contact sheet failed [${jobId.slice(4, 12)}]: ${err.message}`);
contactSheetFilename = null;
}
const persisted = await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null });
@@ -155,15 +183,15 @@ async function launchCodeExcerpt({ projectId, project, startSec, endSec, revisio
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}`);
+ console.log(`✅ ${Label} 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}`;
+ const reason = canceled ? 'Render cancelled' : `${Label} 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}`);
+ log(`${canceled ? '🛑' : '❌'} Music-video ${renderer.label} 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 });
@@ -185,9 +213,10 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { revi
let handedOff = false;
try {
- if (project.composition?.mode === 'code') {
- return await launchCodeExcerpt({
- projectId, project, startSec, endSec, revisionId, handOff: () => { handedOff = true; },
+ const seeked = SEEKED_EXCERPTS[project.composition?.mode];
+ if (seeked) {
+ return await launchSeekedExcerpt({
+ projectId, project, startSec, endSec, revisionId, handOff: () => { handedOff = true; }, renderer: seeked,
});
}
const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 6f62e31082..04e06e12e4 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -33,7 +33,7 @@ import { isPerformanceScene, planShotSplit, shotSplitLimit } from '../../lib/mus
import { normalizeLyricCues, normalizePhrases, invalidateTimedText } from './timedText.js';
import { normalizeLyricMarkers } from './lyricMarkers.js';
import { ensureSceneTakes, TAKE_SLOT } from './takes.js';
-import { normalizeComposition, invalidateCompositionTiming } from './composition.js';
+import { normalizeComposition, invalidateCompositionTiming, withStoredCompositionDocument } from './composition.js';
import { normalizeSoundBed } from './soundBed.js';
import { remapTreatmentForClone, scenesFingerprint } from './treatment.js';
import { normalizeMusicVideoAutomation } from '../../lib/musicVideoAutomation.js';
@@ -150,7 +150,8 @@ export function buildProjectRecord(input, { id, now }) {
phrases: Array.isArray(input.phrases) ? normalizePhrases(input.phrases) : [],
pacing: input.pacing ?? null,
// #8984 — composition manifest (null = plain concatenation render).
- composition: input.composition ? normalizeComposition(input.composition) : null,
+ // The document pointer is set only by the import routes, never on create.
+ composition: input.composition ? withStoredCompositionDocument(normalizeComposition(input.composition), null) : null,
// #8988 — optional sound-design bed mixed under the song.
soundBed: input.soundBed ? normalizeSoundBed(input.soundBed) : null,
// #8980 — optional pre-production treatment (brief, arc, shot direction,
@@ -275,7 +276,9 @@ export function applyProjectPatch(project, patch) {
...(Array.isArray(patch.lyricMarkers) ? { lyricMarkers: normalizeLyricMarkers(patch.lyricMarkers) } : {}),
...(Array.isArray(patch.phrases) ? { phrases: normalizePhrases(patch.phrases) } : {}),
// #8984 — the composition manifest is replaced whole; null clears it.
- ...('composition' in patch ? { composition: normalizeComposition(patch.composition) } : {}),
+ // The composition document pointer is owned by the import routes: a PATCH
+ // that echoes (or omits, or forges) it keeps the stored one.
+ ...('composition' in patch ? { composition: withStoredCompositionDocument(normalizeComposition(patch.composition), project.composition) } : {}),
// #8988 — an explicitly chosen sound-design bed; null clears it.
...('soundBed' in patch ? { soundBed: normalizeSoundBed(patch.soundBed) } : {}),
};
@@ -647,6 +650,11 @@ export function mergeProjectRecord(local, remoteRaw) {
// their files and jobs exist only on this install.
if (Object.hasOwn(local, 'devArtifacts')) remote.devArtifacts = local.devArtifacts;
if (Object.hasOwn(local, 'castAndSets')) remote.castAndSets = local.castAndSets;
+ // The composition document's files live only on this install as well
+ // (compositionDocument.js), so its pointer survives a newer remote body.
+ if (local.composition?.document && remote.composition && typeof remote.composition === 'object' && !Array.isArray(remote.composition)) {
+ remote.composition = { ...remote.composition, document: local.composition.document };
+ }
if (local.videoSettings && typeof local.videoSettings === 'object'
&& !Array.isArray(local.videoSettings) && Object.hasOwn(local.videoSettings, 'backend')) {
const remoteVideoSettings = remote.videoSettings && typeof remote.videoSettings === 'object'
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 1dc2adc3c3..666b38ca91 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -697,3 +697,48 @@ describe('mergeProjectRecord (#1770 LWW)', () => {
expect(r.changed).toBe(false);
});
});
+
+describe('composition document (render style `document`)', () => {
+ const pointer = { directory: 'music-video/mv-1/composition/doc-a1', entry: 'index.html', updatedAt: '2026-01-02T00:00:00.000Z', source: { kind: 'template', name: 'layered' }, files: 3, bytes: 42 };
+ const overlay = { enabled: true, titleLines: ['EXAMPLE'], meter: { label: 'LEVEL', keyframes: [[10, 40], [0, 100]] }, ticker: ['alpha'], timecode: false, timecodeStartSec: 0 };
+ const withDocument = () => ({ ...baseProject(), composition: { version: 1, mode: 'document', textCues: [], style: { color: '#ffffff', font: 'sans' }, posterSec: null, document: pointer, overlay } });
+
+ it('never takes the pointer from a create body, and keeps the HUD settings normalized', () => {
+ const created = buildProjectRecord({ name: 'Doc', composition: { mode: 'document', document: pointer, overlay } }, { id: 'mv-9', now: '2026-01-01T00:00:00.000Z' });
+ expect(created.composition.mode).toBe('document');
+ expect(created.composition).not.toHaveProperty('document');
+ expect(created.composition.overlay.meter.keyframes).toEqual([[0, 100], [10, 40]]);
+ });
+
+ it('keeps the stored pointer across a PATCH that echoes, forges or omits it', () => {
+ const project = withDocument();
+ const forged = { ...project.composition, document: { ...pointer, directory: 'music-video/mv-other/composition/doc-z9' } };
+ expect(applyProjectPatch(project, { composition: forged }).composition.document).toEqual(pointer);
+ const { document: _omit, ...omitted } = project.composition;
+ const next = applyProjectPatch(project, { composition: { ...omitted, overlay: { ...overlay, timecode: true } } });
+ expect(next.composition.document).toEqual(pointer);
+ expect(next.composition.overlay.timecode).toBe(true);
+ expect(applyProjectPatch(project, { composition: null }).composition).toBeNull();
+ });
+
+ it('carries the pointer to a clone (versions are immutable folders)', () => {
+ const clone = cloneProjectRecord(withDocument(), { id: 'mv-2', now: '2026-01-03T00:00:00.000Z' });
+ expect(clone.composition.document).toEqual(pointer);
+ });
+
+ it('keeps the pointer install-local: stripped from the wire, never taken from a peer, kept over a newer remote', async () => {
+ const { sanitizeRecordForWire } = await import('../../lib/syncWire.js');
+ const local = { ...withDocument(), updatedAt: '2026-01-01T00:00:00Z' };
+ const wire = sanitizeRecordForWire('musicVideoProject', local);
+ expect(wire.composition.mode).toBe('document');
+ expect(wire.composition.overlay).toEqual(overlay);
+ expect(wire.composition).not.toHaveProperty('document');
+
+ const foreign = { ...pointer, directory: 'music-video/mv-1/composition/doc-peer' };
+ const inserted = mergeProjectRecord(null, { ...local, id: 'mv-3', updatedAt: '2026-01-02T00:00:00Z', composition: { ...local.composition, document: foreign } }).next;
+ expect(inserted.composition).not.toHaveProperty('document');
+ const { next } = mergeProjectRecord(local, { ...local, updatedAt: '2026-01-05T00:00:00Z', name: 'remote edit', composition: { ...local.composition, mode: 'document', document: foreign } });
+ expect(next.name).toBe('remote edit');
+ expect(next.composition.document).toEqual(pointer);
+ });
+});
diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.js
new file mode 100644
index 0000000000..f309fca75d
--- /dev/null
+++ b/server/services/musicVideo/render.document.test.js
@@ -0,0 +1,68 @@
+/**
+ * Render planning for the composition-document render style: a `document`
+ * project takes the seeked path with its document folder, a full render and a
+ * draft excerpt both refuse (and release their slot) while no document is
+ * attached, and the finished render is filed like any other.
+ */
+
+import { describe, expect, it, vi, afterAll } from 'vitest';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-document-plan-'),
+}));
+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({ ...(await importOriginal()), generateThumbnail: vi.fn(async () => 'thumb.jpg') }));
+vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'instance-test') }));
+vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(async () => []), mutateVideoHistory: vi.fn(async () => {}) }));
+vi.mock('./codeRender.js', async (importOriginal) => ({ ...(await importOriginal()), writeCodeProofSheet: vi.fn(async () => null) }));
+vi.mock('./documentRender.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ encodeDocumentComposition: vi.fn(async ({ plan }) => ({ width: 1920, height: 1080, fps: 24, durationSec: plan.durationSec, startSec: 0, boundaryTimes: [0] })),
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const projects = await import('./projects.js');
+const { renderMusicVideo } = await import('./render.js');
+const { startExcerptRender } = await import('./excerptRender.js');
+const { importDocumentTemplate } = await import('./compositionDocument.js');
+const { encodeDocumentComposition } = await import('./documentRender.js');
+const { mutateVideoHistory } = await import('../videoGen/local.js');
+
+afterAll(() => cleanupTempDataRoots());
+
+async function documentProject() {
+ await mkdir(PATHS.music, { recursive: true });
+ await writeFile(join(PATHS.music, 'song.wav'), Buffer.alloc(64));
+ const created = await projects.createProject({ name: 'Doc', uploadedAudioFilename: 'song.wav', composition: { mode: 'document' } });
+ await projects.mutateProjectRecord(created.id, (current) => ({ project: { ...current, audioAnalysis: { durationSec: 12.5, beats: [], downbeats: [], sections: [] } } }));
+ return created.id;
+}
+
+describe('composition-document render plan', () => {
+ it('refuses a full render and an excerpt while no document is attached, and releases both slots', async () => {
+ const id = await documentProject();
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await expect(renderMusicVideo(id)).rejects.toMatchObject({ status: 409, code: 'COMPOSITION_DOCUMENT_MISSING' });
+ await expect(startExcerptRender(id, { startSec: 1, endSec: 3 })).rejects.toMatchObject({ status: 409, code: 'COMPOSITION_DOCUMENT_MISSING' });
+ }
+ expect(encodeDocumentComposition).not.toHaveBeenCalled();
+ });
+
+ it('renders the attached document over the song and files the result', async () => {
+ const id = await documentProject();
+ const { document } = await importDocumentTemplate(id);
+ const { jobId } = await renderMusicVideo(id);
+ await vi.waitFor(() => expect(mutateVideoHistory).toHaveBeenCalled());
+ const call = encodeDocumentComposition.mock.calls.at(-1)[0];
+ expect(call).toMatchObject({
+ jobId,
+ audioPath: join(PATHS.music, 'song.wav'),
+ soundBed: null,
+ plan: { directory: document.directory, songDurationSec: 12.5, durationSec: 12.5, fps: 24, width: 1920, height: 1080 },
+ });
+ expect(call).not.toHaveProperty('windowStart');
+ await vi.waitFor(async () => expect((await projects.getProject(id)).renderHistoryId).toBe(jobId));
+ });
+});
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 3014c3e61a..90b32a8c85 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -39,6 +39,7 @@ 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 { encodeDocumentComposition, prepareDocumentRender, sweepDocumentScratch } from './documentRender.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch, renderSongComposition } from './compositionRender.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
import { findStalePerformanceTakes } from './performanceShot.js';
@@ -165,7 +166,7 @@ export async function resolveMasterAudioPath(project) {
// #8988: resolve the project's explicitly chosen sound-design bed (a
// music-library track) to a verified path under data/music/, or null when the
// song is the sole audio master (the default).
-async function resolveSoundBed(project) {
+export async function resolveSoundBedPath(project) {
const bed = projectSoundBed(project);
// A (synced) record naming the song itself as its bed mixes nothing.
if (!bed || bed.trackId === project.trackId) return null;
@@ -593,7 +594,7 @@ export async function planMusicVideoRender(project) {
{ status: 422, code: 'INSUFFICIENT_CLIP_COVERAGE', context: { shortfalls, resolutions: COVERAGE_RESOLUTIONS } },
);
}
- const soundBed = await resolveSoundBed(project);
+ const soundBed = await resolveSoundBedPath(project);
return { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed };
}
@@ -619,14 +620,42 @@ 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);
+// Code-rendered mode (#9076) and the composition-document mode seek a
+// composition instead of concatenating footage. They share this module's job
+// map so the existing SSE and cancel routes apply. Code mode never asks a
+// footage model for pixels; a document draws the scenes' selected takes.
+const SEEKED_RENDERERS = Object.freeze({
+ code: {
+ label: 'code',
+ modelId: 'music-video-code',
+ prepare: async (project) => prepareCodeRender(project),
+ encode: async ({ plan, projectId, jobId, audioPath, outputPath, signal, onProgress }) => {
+ await encodeCodeComposition({
+ ...plan, audioPath, outputPath, directory: `compositions/music-video/${projectId}/${jobId}`, signal, onProgress,
+ });
+ return { width: plan.width, height: plan.height, fps: plan.fps, durationSec: plan.durationSec, boundaryTimes: plan.sectionTimes };
+ },
+ },
+ document: {
+ label: 'composition document',
+ modelId: 'music-video-document',
+ soundBed: true,
+ prepare: (project) => prepareDocumentRender(project),
+ encode: ({ plan, project, jobId, audioPath, soundBed, outputPath, signal, onProgress }) => encodeDocumentComposition({
+ project, plan, jobId, audioPath, soundBed, outputPath, signal, onProgress,
+ }),
+ },
+});
+
+/** The seeked renderer for a project's render mode, or null for footage modes. */
+export const seekedRendererFor = (project) => SEEKED_RENDERERS[project?.composition?.mode] || null;
+
+async function renderSeekedMode(projectId, project, handOff, renderer) {
+ const plan = await renderer.prepare(project);
// Resolve the master before any rendering mark. A missing track throws here
// and the caller releases the pending slot without leaving a job running.
const audioPath = await resolveMasterAudioPath(project);
+ const soundBed = renderer.soundBed ? await resolveSoundBedPath(project) : null;
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);
const renderingOn = await ensureInstanceId();
@@ -643,62 +672,58 @@ async function renderCodeMode(projectId, project, handOff) {
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.error(`❌ Music-video ${renderer.label} 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`);
+ console.log(`🎬 Rendering ${renderer.label} 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}`);
+ console.error(`❌ Music-video ${renderer.label} 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,
+ Promise.resolve().then(() => renderer.encode({
+ plan, project, projectId, jobId, audioPath, soundBed, outputPath, signal,
onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),
- }).then(async () => {
+ })).then(async (encoded) => {
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,
+ await writeCodeProofSheet(outputPath, join(PATHS.videoThumbnails, sheetName), encoded.boundaryTimes, {
+ width: encoded.width, height: encoded.height, fps: encoded.fps,
});
proof = sheetName;
} catch (err) {
- console.warn(`⚠️ Music-video code proof sheet failed [${jobId.slice(0, 8)}]: ${err.message}`);
+ console.warn(`⚠️ Music-video ${renderer.label} proof sheet failed [${jobId.slice(0, 8)}]: ${err.message}`);
}
- const atSec = typeof project.composition?.posterSec === 'number' ? project.composition.posterSec : (plan.sectionTimes[0] || 0);
+ const atSec = typeof project.composition?.posterSec === 'number' ? project.composition.posterSec : (encoded.boundaryTimes[0] || 0);
const thumb = await generateThumbnail(outputPath, jobId, { atSec });
await appendToVideoHistory({
id: jobId,
prompt: `Music Video: ${project.name}`,
- modelId: 'music-video-code',
+ modelId: renderer.modelId,
seed: 0,
- width: plan.width,
- height: plan.height,
- numFrames: Math.round(plan.durationSec * plan.fps),
- fps: plan.fps,
+ width: encoded.width,
+ height: encoded.height,
+ numFrames: Math.round(encoded.durationSec * encoded.fps),
+ fps: encoded.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}`);
+ console.log(`✅ ${renderer.label[0].toUpperCase()}${renderer.label.slice(1)} 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}`;
+ const reason = canceled ? 'Render cancelled' : `${renderer.label[0].toUpperCase()}${renderer.label.slice(1)} 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}`);
+ log(`${canceled ? '🛑' : '❌'} Music-video ${renderer.label} 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' });
@@ -726,8 +751,9 @@ export async function renderMusicVideo(projectId, options = {}) {
let handedOff = false;
try {
- if (project.composition?.mode === 'code') {
- return await renderCodeMode(projectId, project, () => { handedOff = true; });
+ const seeked = seekedRendererFor(project);
+ if (seeked) {
+ return await renderSeekedMode(projectId, project, () => { handedOff = true; }, seeked);
}
const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);
await ensureDir(PATHS.videos);
@@ -959,6 +985,10 @@ export async function recoverStuckMusicVideoRenders() {
await sweepCompositionScratch().catch((err) => {
console.warn(`⚠️ Music Video recovery: could not remove stale overlay scratch: ${err.message}`);
});
+ // Nor a composition-document render's staged copy (document + scene media).
+ await sweepDocumentScratch().catch((err) => {
+ console.warn(`⚠️ Music Video recovery: could not remove stale composition-document scratch: ${err.message}`);
+ });
const instanceId = await ensureInstanceId();
const stuck = (await listProjects()).filter((p) => p?.status === 'rendering'
&& !projectRenders.has(p.id) && isLocalRenderMark(p.renderingOn, instanceId));