Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Add an MTV-style opening title card to music videos (#11044)
[._.]/291a6ac79e3a
diff --git a/client/src/components/musicVideo/CompositionPanel.jsx b/client/src/components/musicVideo/CompositionPanel.jsxindex 9acf231f6f..872adec55e 100644--- a/client/src/components/musicVideo/CompositionPanel.jsx+++ b/client/src/components/musicVideo/CompositionPanel.jsx@@ -1,6 +1,7 @@import { RenderFailure } from './RenderStatusPanel.jsx';import GradePanel from './GradePanel.jsx';import FilmLookPanel from './FilmLookPanel.jsx';+import TitleCardPanel from './TitleCardPanel.jsx';import TypographyPanel from './TypographyPanel.jsx';import EidoverseVideoPanel from './EidoverseVideoPanel.jsx';import CodeVideoPanel from './CodeVideoPanel.jsx';@@ -36,6 +37,8 @@ export default function CompositionPanel({ board }) {)}<GradePanel project={project} onSave={board.saveCompositionGrade} /><FilmLookPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields} />+ <TitleCardPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields}+ onPreview={board.seekToScene ? (startSec) => board.seekToScene({ startSec }, { play: true }) : null} />{mode !== 'eidoverse' && <TypographyPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields} />}{mode === 'eidoverse' && <EidoverseVideoPanel key={project.id} project={project} onProject={board.replaceProject} productionReadiness={board.productionReadiness} />}{mode === 'code' && (diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsxindex bb8111b67b..92e7ae9912 100644--- a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx@@ -1,5 +1,6 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Pause, Play } from 'lucide-react';+import { normalizeTitleCard } from '../../../../server/lib/musicVideoTitleCard.js';import { fetchMusicVideoPreviewAsset, getMusicVideoCompositionPreview, getMusicVideoLyricPlaythroughPreview } 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';@@ -91,6 +92,14 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesfilmLookRef.current = filmLook;if (seekState.current.ready) iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:film-look', look: filmLook }, '*');}, [filmLook]);+ // The opening title card is posted the same way, so its panel's edits redraw the paused frame at once;+ // unlike the look it also shows over the lyric playthrough, to check it against the timed lyrics.+ const titleCard = useMemo(() => normalizeTitleCard(project.titleCard), [project.titleCard]);+ const titleCardRef = useRef(titleCard);+ useEffect(() => {+ titleCardRef.current = titleCard;+ if (seekState.current.ready) iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:title-card', card: titleCard }, '*');+ }, [titleCard]);// The document's own version (its folder + save time), not the project's// `updatedAt`: an unrelated save must not reload a playing preview.@@ -153,6 +162,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekRequesevent.source.postMessage({ type: 'portos-mv:manifest', keys: [...byKey.keys()] }, '*');// The page starts from the look saved when it was built; the board may have moved the sliders since.event.source.postMessage({ type: 'portos-mv:film-look', look: filmLookRef.current }, '*');+ event.source.postMessage({ type: 'portos-mv:title-card', card: titleCardRef.current }, '*');showStatus();state.ready = true;postSeek(t);diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsxindex 438ceee7df..5288fa9160 100644--- a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx@@ -116,6 +116,23 @@ describe('CompositionPreviewPlayer', () => {expect(api.getMusicVideoCompositionPreview).toHaveBeenCalledTimes(1);});+ it('hands the opening title card to the loaded document and again on each edit, without rebuilding the preview', async () => {+ const card = { enabled: true, title: 'Example Song', startSec: 2, endSec: 8 };+ const { rerender } = render(<CompositionPreviewPlayer project={{ ...project, titleCard: card }} audioUrl={null} />);+ const frame = await screen.findByTitle('Composition document preview');+ const post = vi.spyOn(frame.contentWindow, 'postMessage');+ const send = (data) => act(async () => { window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data })); });+ await waitFor(async () => {+ await send({ type: 'portos-mv:loaded' });+ expect(post).toHaveBeenCalledWith({ type: 'portos-mv:title-card', card: expect.objectContaining({ title: 'Example Song', position: 'lower-left' }) }, '*');+ });+ rerender(<CompositionPreviewPlayer project={{ ...project, titleCard: { ...card, position: 'upper-right' } }} audioUrl={null} />);+ await waitFor(() => expect(post).toHaveBeenCalledWith({ type: 'portos-mv:title-card', card: expect.objectContaining({ position: 'upper-right' }) }, '*'));+ rerender(<CompositionPreviewPlayer project={{ ...project, titleCard: null }} audioUrl={null} />);+ await waitFor(() => expect(post).toHaveBeenCalledWith({ type: 'portos-mv:title-card', card: null }, '*'));+ expect(api.getMusicVideoCompositionPreview).toHaveBeenCalledTimes(1);+ });+it('keeps the loaded preview through an unrelated project save and rebuilds when the document version changes', async () => {const { rerender } = render(<CompositionPreviewPlayer project={project} audioUrl={null} />);const frame = await screen.findByTitle('Composition document preview');diff --git a/client/src/components/musicVideo/StoryboardAnimatic.jsx b/client/src/components/musicVideo/StoryboardAnimatic.jsxindex 971fbb8315..5211a09547 100644--- a/client/src/components/musicVideo/StoryboardAnimatic.jsx+++ b/client/src/components/musicVideo/StoryboardAnimatic.jsx@@ -1,8 +1,9 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Captions } from 'lucide-react';import { formatDurationSec } from '../../utils/formatters.js';import { getMusicVideoLyricOverlayPreview } from '../../services/apiMusicVideo.js';import { playthroughVersion } from './CompositionPreviewPlayer.jsx';+import { normalizeTitleCard } from '../../../../server/lib/musicVideoTitleCard.js';const timedShots = (scenes) => scenes.filter((scene) => Number.isFinite(scene?.startSec)).sort((a, b) => a.startSec - b.startSec);@@ -39,6 +40,13 @@ function useLyricOverlay({ project, enabled, audioRef, time }) {const iframeRef = useRef(null);const seekState = useRef({ inFlight: false, pending: null, ready: false, sentAt: 0 });const version = enabled ? playthroughVersion(project) : null;+ // The opening title card rides on the lyric layer, posted live so its panel's edits show at once.+ const titleCard = useMemo(() => normalizeTitleCard(project.titleCard), [project.titleCard]);+ const titleCardRef = useRef(titleCard);+ useEffect(() => {+ titleCardRef.current = titleCard;+ if (seekState.current.ready) iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:title-card', card: titleCard }, '*');+ }, [titleCard]);useEffect(() => {let active = true;@@ -71,6 +79,7 @@ function useLyricOverlay({ project, enabled, audioRef, time }) {const state = seekState.current;if (message.type === 'portos-mv:loaded') {event.source.postMessage({ type: 'portos-mv:manifest', keys: [] }, '*');+ event.source.postMessage({ type: 'portos-mv:title-card', card: titleCardRef.current }, '*');state.ready = true;postSeek(audioRef.current?.currentTime || 0);} else if (message.type === 'portos-mv:request') {diff --git a/client/src/components/musicVideo/StoryboardAnimatic.test.jsx b/client/src/components/musicVideo/StoryboardAnimatic.test.jsxindex 114b41740e..8dbe23556e 100644--- a/client/src/components/musicVideo/StoryboardAnimatic.test.jsx+++ b/client/src/components/musicVideo/StoryboardAnimatic.test.jsx@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import StoryboardAnimatic, { shotAt } from './StoryboardAnimatic.jsx';const scenes = [@@ -52,6 +52,18 @@ describe('StoryboardAnimatic lyrics', () => {expect(screen.getByText('Opening').closest('figure')).toBeTruthy();});+ // Uniquely catches the animatic's lyric layer dropping the opening title card or its live edits.+ it('hands the opening title card to the lyric layer and again when it is edited', async () => {+ const card = { enabled: true, title: 'Example Song', startSec: 2, endSec: 8 };+ const { rerender } = render(<StoryboardAnimatic project={{ ...lyricProject, titleCard: card }} audioUrl="/song.mp3" />);+ const overlay = await screen.findByTestId('animatic-lyrics');+ const post = vi.spyOn(overlay.contentWindow, 'postMessage');+ await act(async () => { window.dispatchEvent(new MessageEvent('message', { source: overlay.contentWindow, data: { type: 'portos-mv:loaded' } })); });+ expect(post).toHaveBeenCalledWith({ type: 'portos-mv:title-card', card: expect.objectContaining({ title: 'Example Song', position: 'lower-left' }) }, '*');+ rerender(<StoryboardAnimatic project={{ ...lyricProject, titleCard: { ...card, position: 'upper-right' } }} audioUrl="/song.mp3" />);+ await waitFor(() => expect(post).toHaveBeenCalledWith({ type: 'portos-mv:title-card', card: expect.objectContaining({ position: 'upper-right' }) }, '*'));+ });+it('offers no lyrics until the words are timed', () => {render(<StoryboardAnimatic project={{ ...lyricProject, lyricCues: [{ id: 'c1', text: 'hello', startSec: null }] }} audioUrl="/song.mp3" />);expect(screen.queryByRole('button', { name: 'Lyrics' })).toBeNull();diff --git a/client/src/components/musicVideo/TitleCardPanel.jsx b/client/src/components/musicVideo/TitleCardPanel.jsxnew file mode 100644index 0000000000..23753b807c--- /dev/null+++ b/client/src/components/musicVideo/TitleCardPanel.jsx@@ -0,0 +1,174 @@+import { useState } from 'react';+import { Clapperboard, Play } from 'lucide-react';+import { getMusicVideoPublishPlatforms } from '../../services/apiMusicVideo.js';+import {+ TITLE_CARD_LIMITS, normalizeTitleCard, titleCardPrefill,+} from '../../../../server/lib/musicVideoTitleCard.js';++const POSITIONS = [['lower-left', 'Bottom left'], ['lower-right', 'Bottom right'], ['upper-left', 'Top left'], ['upper-right', 'Top right'], ['lower-center', 'Bottom centre'], ['center', 'Centre']];+const FONTS = [['display', 'Lyric type'], ['sans', 'Helvetica'], ['serif', 'Serif'], ['mono', 'Mono']];+const inputCls = 'w-full rounded border border-port-border bg-port-bg px-2 py-1 text-sm min-h-[44px] sm:min-h-0';+const labelCls = 'mb-0.5 block text-xs text-port-text-muted';+const clock = (sec) => {+ const rest = sec % 60;+ return `${Math.floor(sec / 60)}:${Number.isInteger(Math.round(rest * 10) / 10) ? String(Math.round(rest)).padStart(2, '0') : rest.toFixed(1).padStart(4, '0')}`;+};+const toNumber = (value) => (value === '' || !Number.isFinite(Number(value)) ? undefined : Number(value));++/** The first timed lyric line that shares the screen with the card's window, if any. */+function lyricDuringCard(project, card) {+ return (project.lyricCues || [])+ .filter((cue) => typeof cue?.startSec === 'number' && cue.startSec < card.endSec && (typeof cue.endSec === 'number' ? cue.endSec : cue.startSec + 1) > card.startSec)+ .sort((a, b) => a.startSec - b.startSec)[0] || null;+}++/**+ * The MTV-style opening title card (lib/musicVideoTitleCard.js): song title,+ * artist and year in a corner, fading in and out over the opener. Drawn over+ * the composition document in the docked live preview and the final render.+ * Turning it on fills the song title, the artist named for DistroKid under+ * Where you post, this year and a window that ends before the first sung line.+ * Edits reach the preview at once (`onEditLocal`); leaving a field saves.+ */+export default function TitleCardPanel({ project, onEditLocal, onSave, onPreview }) {+ const [starting, setStarting] = useState(false);+ const documentMode = project.composition?.mode === 'document';+ const raw = project.titleCard || null;+ const card = normalizeTitleCard(raw);+ const on = !!card?.enabled;++ const edit = (patch) => onEditLocal({ titleCard: { ...(raw || {}), ...patch } });+ const commit = (patch = {}) => {+ const next = normalizeTitleCard({ ...(raw || {}), ...patch });+ onEditLocal({ titleCard: next });+ return onSave({ titleCard: next });+ };++ const turnOn = () => {+ if (card) return commit({ enabled: true });+ setStarting(true);+ const firstLyricSec = (project.lyricCues || []).map((cue) => cue?.startSec).filter((s) => typeof s === 'number').sort((a, b) => a - b)[0] ?? null;+ return getMusicVideoPublishPlatforms({ silent: true }).catch(() => null)+ .then((platforms) => {+ const distrokid = platforms?.distrokid;+ const next = titleCardPrefill(project, { artist: distrokid?.account || distrokid?.defaults?.artistName || '', firstLyricSec });+ onEditLocal({ titleCard: next });+ return onSave({ titleCard: next });+ })+ // The board's save already reports a failure; it must not leave the switch disabled.+ .catch(() => null)+ .finally(() => setStarting(false));+ };++ const overlap = on ? lyricDuringCard(project, card) : null;+ const endBefore = overlap ? Math.round((overlap.startSec - 0.5) * 10) / 10 : null;+ const field = (key) => (raw?.[key] ?? card?.[key] ?? '');++ return (+ <section aria-label="Opening title card" className="space-y-2 border-t border-port-border pt-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="inline-flex items-center gap-1.5 text-sm font-medium"><Clapperboard size={14} className="text-port-accent" aria-hidden="true" /> Opening title card</h3>+ <label htmlFor="mv-title-card-on" className="inline-flex min-h-[44px] items-center gap-2 text-xs text-port-text-muted sm:min-h-0">+ {on ? `Live in the preview · ${clock(card.startSec)}–${clock(card.endSec)}` : 'Off'}+ <input id="mv-title-card-on" type="checkbox" checked={on} disabled={starting}+ onChange={(e) => (e.target.checked ? turnOn() : commit({ enabled: false }))} className="h-4 w-4" />+ </label>+ </div>+ {!documentMode && on && (+ <p className="text-xs text-port-text-muted" role="status">The title card is drawn by the composition-document render style; this project's render style ignores it.</p>+ )}+ {on && (+ <>+ <div className="grid grid-cols-2 gap-2">+ <div>+ <label htmlFor="mv-title-card-title" className={labelCls}>Song title</label>+ <input id="mv-title-card-title" value={field('title')} maxLength={TITLE_CARD_LIMITS.textMax}+ onChange={(e) => edit({ title: e.target.value })} onBlur={() => commit()} className={inputCls} />+ </div>+ <div>+ <label htmlFor="mv-title-card-artist" className={labelCls}>Artist</label>+ <input id="mv-title-card-artist" value={field('artist')} maxLength={TITLE_CARD_LIMITS.textMax}+ onChange={(e) => edit({ artist: e.target.value })} onBlur={() => commit()} className={inputCls} />+ </div>+ <div>+ <label htmlFor="mv-title-card-year" className={labelCls}>Year</label>+ <input id="mv-title-card-year" value={field('year')} maxLength={TITLE_CARD_LIMITS.yearMax} inputMode="numeric"+ onChange={(e) => edit({ year: e.target.value })} onBlur={() => commit()} className={inputCls} />+ </div>+ <div>+ <label htmlFor="mv-title-card-extra" className={labelCls}>Extra line</label>+ <input id="mv-title-card-extra" value={field('extra')} maxLength={TITLE_CARD_LIMITS.textMax} placeholder="Album or director"+ onChange={(e) => edit({ extra: e.target.value })} onBlur={() => commit()} className={inputCls} />+ </div>+ </div>+ <div className="grid grid-cols-3 gap-2">+ <div>+ <label htmlFor="mv-title-card-start" className={labelCls}>In (s)</label>+ <input id="mv-title-card-start" type="number" min={0} max={TITLE_CARD_LIMITS.startMax} step={0.1} value={field('startSec')}+ onChange={(e) => edit({ startSec: toNumber(e.target.value) })} onBlur={() => commit()} className={inputCls} />+ </div>+ <div>+ <label htmlFor="mv-title-card-end" className={labelCls}>Out (s)</label>+ <input id="mv-title-card-end" type="number" min={0} step={0.1} value={field('endSec')}+ onChange={(e) => edit({ endSec: toNumber(e.target.value) })} onBlur={() => commit()} className={inputCls} />+ </div>+ <div>+ <label htmlFor="mv-title-card-fade" className={labelCls}>Fade (s)</label>+ <input id="mv-title-card-fade" type="number" min={0} max={TITLE_CARD_LIMITS.fadeMax} step={0.1} value={field('fadeSec')}+ onChange={(e) => edit({ fadeSec: toNumber(e.target.value) })} onBlur={() => commit()} className={inputCls} />+ </div>+ </div>+ <div className="grid grid-cols-2 gap-2">+ <div>+ <label htmlFor="mv-title-card-position" className={labelCls}>Position</label>+ <select id="mv-title-card-position" value={card.position} onChange={(e) => commit({ position: e.target.value })} className={inputCls}>+ {POSITIONS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="mv-title-card-font" className={labelCls}>Font</label>+ <select id="mv-title-card-font" value={card.font} onChange={(e) => commit({ font: e.target.value })} className={inputCls}>+ {FONTS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </div>+ </div>+ <div className="flex flex-wrap items-end gap-x-4 gap-y-2">+ <div className="min-w-[10rem] flex-1">+ <label htmlFor="mv-title-card-size" className={labelCls}>Size {field('size')}%</label>+ <input id="mv-title-card-size" type="range" min={TITLE_CARD_LIMITS.sizeMin} max={TITLE_CARD_LIMITS.sizeMax} step={5} value={field('size')}+ onChange={(e) => edit({ size: Number(e.target.value) })} onPointerUp={() => commit()} onKeyUp={() => commit()} onBlur={() => commit()}+ className="h-11 w-full sm:h-auto" />+ </div>+ <div>+ <label htmlFor="mv-title-card-color" className={labelCls}>Color</label>+ <input id="mv-title-card-color" type="color" value={card.color}+ onChange={(e) => edit({ color: e.target.value })} onBlur={() => commit()} className="h-11 w-14 rounded border border-port-border bg-port-bg sm:h-8" />+ </div>+ <label htmlFor="mv-title-card-quote" className="inline-flex min-h-[44px] items-center gap-2 text-xs text-port-text-muted sm:min-h-0">+ <input id="mv-title-card-quote" type="checkbox" checked={card.quoteTitle} onChange={(e) => commit({ quoteTitle: e.target.checked })} className="h-4 w-4" />+ Quote the title+ </label>+ {onPreview && (+ <button type="button" onClick={() => onPreview(Math.max(0, card.startSec - 0.5))}+ className="inline-flex min-h-[44px] items-center gap-1 text-xs text-port-accent sm:min-h-0">+ <Play size={13} aria-hidden="true" /> Play from {clock(Math.max(0, card.startSec - 0.5))}+ </button>+ )}+ </div>+ {overlap && (+ <p className="text-xs text-port-warning" role="status">+ A sung line starts at {clock(overlap.startSec)} while the card is up. Check the corner in the preview+ {endBefore > card.startSec + TITLE_CARD_LIMITS.windowMin && (+ <>, or{' '}+ <button type="button" onClick={() => commit({ endSec: endBefore })} className="min-h-[44px] px-1 text-port-accent sm:min-h-0">+ end it at {clock(endBefore)}+ </button>+ </>+ )}.+ </p>+ )}+ </>+ )}+ </section>+ );+}diff --git a/client/src/components/musicVideo/TitleCardPanel.test.jsx b/client/src/components/musicVideo/TitleCardPanel.test.jsxnew file mode 100644index 0000000000..9a626ec662--- /dev/null+++ b/client/src/components/musicVideo/TitleCardPanel.test.jsx@@ -0,0 +1,67 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { useState } from 'react';++const api = vi.hoisted(() => ({ getMusicVideoPublishPlatforms: vi.fn() }));+vi.mock('../../services/apiMusicVideo.js', () => api);++import TitleCardPanel from './TitleCardPanel.jsx';++const base = {+ id: 'mv-1', name: 'Example Song v2', composition: { mode: 'document' },+ lyricCues: [{ id: 'l1', text: 'first line', startSec: 7, endSec: 9 }],+};++// The board's local edit + save, as MusicVideo.jsx wires them.+function Harness({ initial, onSave }) {+ const [project, setProject] = useState(initial);+ return <TitleCardPanel project={project} onEditLocal={(patch) => setProject((p) => ({ ...p, ...patch }))} onSave={onSave} onPreview={() => {}} />;+}++beforeEach(() => {+ api.getMusicVideoPublishPlatforms.mockReset();+ api.getMusicVideoPublishPlatforms.mockResolvedValue({ distrokid: { enabled: true, account: 'Example Artist' } });+});++describe('TitleCardPanel', () => {+ it('turns on prefilled with the song title, the DistroKid artist, this year and a window ending before the first sung line', async () => {+ const onSave = vi.fn().mockResolvedValue({});+ render(<Harness initial={base} onSave={onSave} />);+ fireEvent.click(screen.getByLabelText(/Off/));+ await waitFor(() => expect(onSave).toHaveBeenCalled());+ expect(onSave.mock.calls[0][0].titleCard).toMatchObject({+ enabled: true, title: 'Example Song', artist: 'Example Artist', year: String(new Date().getFullYear()), startSec: 1.5, endSec: 6.5, position: 'lower-left',+ });+ expect(await screen.findByLabelText('Song title')).toHaveValue('Example Song');+ expect(screen.queryByText(/A sung line starts/)).toBeNull();+ });++ it('re-enables the switch when the first save fails', async () => {+ const onSave = vi.fn().mockRejectedValue(new Error('offline'));+ render(<Harness initial={base} onSave={onSave} />);+ const toggle = screen.getByLabelText(/Off/);+ fireEvent.click(toggle);+ await waitFor(() => expect(onSave).toHaveBeenCalled());+ await waitFor(() => expect(screen.getByRole('checkbox', { name: /Live in the preview/ })).not.toBeDisabled());+ });++ it('flags a sung line under the card and ends the card before it in one tap', async () => {+ const onSave = vi.fn().mockResolvedValue({});+ render(<Harness initial={{ ...base, titleCard: { enabled: true, title: 'Example Song', startSec: 2, endSec: 10 } }} onSave={onSave} />);+ expect(screen.getByText(/A sung line starts at 0:07 /)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'end it at 0:06.5' }));+ expect(onSave).toHaveBeenLastCalledWith({ titleCard: expect.objectContaining({ startSec: 2, endSec: 6.5 }) });+ expect(screen.queryByText(/A sung line starts/)).toBeNull();+ });++ it('keeps the text when switched off and saves typed edits on blur', async () => {+ const onSave = vi.fn().mockResolvedValue({});+ render(<Harness initial={{ ...base, titleCard: { enabled: true, title: 'Example Song', startSec: 1, endSec: 5 } }} onSave={onSave} />);+ fireEvent.change(screen.getByLabelText('Year'), { target: { value: '1984' } });+ fireEvent.blur(screen.getByLabelText('Year'));+ expect(onSave).toHaveBeenLastCalledWith({ titleCard: expect.objectContaining({ year: '1984' }) });+ fireEvent.click(screen.getByLabelText(/Live in the preview/));+ expect(onSave).toHaveBeenLastCalledWith({ titleCard: expect.objectContaining({ enabled: false, title: 'Example Song', year: '1984' }) });+ expect(screen.queryByLabelText('Song title')).toBeNull();+ });+});diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex eb9cb6c16a..013f187e44 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -320,6 +320,34 @@ qualities (`describeFilmLook`), so tuning a look also teaches the vocabularyfor the next generation prompt. The look works on composition-documentprojects; the composed render style keeps its own render grade above.+## Music-video opening title card++The MTV-style credit block a video opens with: song title, artist, year and an+optional extra line (album, director), fading in over the opener and out again.+**Compose → Opening title card** stores it on the project (`project.titleCard`,+validated by `musicVideoTitleCardSchema`, normalized by `normalizeTitleCard` in+`server/lib/musicVideoTitleCard.js`; `null` = none, `enabled: false` keeps the+text). Turning it on fills the song title (the project name without its version+suffix), the artist named for DistroKid under Where you post, this year, and a+window that ends half a second before the first sung line. Timing (in, out,+fade), position (four corners, bottom centre, centre), font (the lyric type's+Archivo, Helvetica, serif, Plex Mono), size and color are all editable; the+panel flags a sung line that starts while the card is up and offers to end the+card before it.++The card is not part of the composition document. `titleCardRuntimeSource()`+is a page script installed beside it, in the live preview's head (live edits+arrive as `portos-mv:title-card` messages) and in every render browser+(`documentRenderInitScripts`). It draws on its own canvas fixed over the page,+fitted to the render's aspect, and wraps `portosComposition.seek()` (chaining+the film look's wrapper) so the card is drawn for each frame after its faces+load. It follows the lyric type: cream fill, ink outline, no plate, inside the+same title-safe insets, and a block wider than its zone shrinks rather than+running off frame. Like the lyrics it sits under the film look. It also rides+on the lyric pages (the lyric-timing playthrough and the lyrics laid over the+storyboard animatic, which carry no film look), so it can be checked against+the timed words before the composition exists.+## Music-video composition documentsA Music Video project can own its whole edit as a composition document: setdiff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 921f0a11cd..83f21ce76c 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -38,6 +38,7 @@ const MAX_TARGETED_TEST_FILES = 125;// registry test (browser-suite-registry.test.js) fails when a suite importing// the gate is left out.export const BROWSER_SUITES = [+ 'server/lib/musicVideoTitleCard.browser.test.js','server/routes/musicVideoProductionReview.browser.test.js','server/routes/musicVideoRichAuthoring.browser.test.js','server/routes/musicVideoSongRevision.browser.test.js',diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex f00a0b4148..cad5a4c16f 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -1463,8 +1463,12 @@ describe('cross-workspace browser suites (#10312)', () => {!/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(path) || BROWSER_SUITES.includes(path));const plan = buildCiTestPlan(inputs.changedFiles, { ...inputs, trackedFiles });+ // The title card suite drives only the server-side runtime script, so a+ // client component change has nothing to select it for.+ const runtimeOnly = 'server/lib/musicVideoTitleCard.browser.test.js';expect(plan.full).toBe(false);- expect(plan.browserFiles).toEqual(expect.arrayContaining(BROWSER_SUITES));+ expect(plan.browserFiles).toEqual(expect.arrayContaining(BROWSER_SUITES.filter((suite) => suite !== runtimeOnly)));+ expect(plan.browserFiles).not.toContain(runtimeOnly);expect(plan.suiteReasons.browser).toMatch(/browser suite/);});diff --git a/server/lib/README.md b/server/lib/README.mdindex 201088aaea..8bd5b19ba5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -857,6 +857,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoGrade.js` | Opt-in Music Video grade presets, bounded normalization, and shared song-timed RGB curves with deterministic grain for composed and document encodes. || `filmLook.js` | The film look: `FILM_LOOK_CONTROLS` (sliders, colors, toggles with their photography terms and prompt words), `FILM_LOOK_PRESETS`, `normalizeFilmLook`, `isFilmLookNeutral`, `describeFilmLook` (the look as prompt vocabulary), `filmLookFilterMarkup` (the one SVG filter the live preview, the document render and gallery bakes apply, frame-seeded) and `filmLookRuntimeSource` (the page script that applies and re-seeds it per seek). Browser-safe. || `filmLookValidation.js` | `filmLookSchema` / `filmLookBakeSchema`: the Zod shape of a film look, derived from `FILM_LOOK_CONTROLS`. |+| `musicVideoTitleCard.js` | The MTV-style opening title card (song, artist, year over the opener): `normalizeTitleCard`, `titleCardVisible`, `titleCardPrefill` (a new card's text and a window ending before the first sung line), and `titleCardRuntimeSource` (the page script the live preview and the document render install to draw it per seek, with its fade and title-safe layout). Browser-safe. || `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. || `musicVideoCrossLinks.js` | Cross-links between a release's posts: each post's public link, the `Label: url` lines a new draft adds, which links a posted record carries (`links`, or what its draft always linked), and `crossLinkBackfill(kit)` listing the links each editable post (YouTube, Suno, X, Stacker News) still lacks. Shared by the publish payloads and the Publish stage. || `musicVideoExcerptRange.js` | `excerptRangeFits(startSec, endSec, totalSec, fps)`: whether a code/document excerpt window fits a frame-quantized render, allowing the end up to one frame past it (scene ends follow the analysed song length; the caller clamps). The start must fall inside the render; an unknown fps allows no slack. |diff --git a/server/lib/index.js b/server/lib/index.jsindex c7daf7ac01..9c3be7bfe0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -835,6 +835,7 @@ export * from './musicVideoActionContract.js';export * from './musicVideoGrade.js';export * from './filmLook.js';export * from './filmLookValidation.js';+export * from './musicVideoTitleCard.js';export * from './musicVideoDependencies.js';export * from './musicVideoCrossLinks.js';export * from './musicVideoExcerptRange.js';diff --git a/server/lib/musicVideoTitleCard.browser.test.js b/server/lib/musicVideoTitleCard.browser.test.jsnew file mode 100644index 0000000000..cca0e99440--- /dev/null+++ b/server/lib/musicVideoTitleCard.browser.test.js@@ -0,0 +1,101 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { existsSync } from 'node:fs';+import { chromium } from 'playwright-core';+import sharp from 'sharp';+import { browserSuiteCanRun } from './browserSuiteGate.js';+import { filmLookRuntimeSource } from './filmLook.js';+import { titleCardRuntimeSource } from './musicVideoTitleCard.js';++/**+ * The title card runtime in real Chrome, installed the way the preview and the+ * render install it (after the film look, before the document): a seek draws+ * the card over the document's own frame inside its window and nothing outside+ * it, chaining the film look's seek wrapper rather than replacing it.+ */+const chrome = [process.env.CHROME_PATH, chromium.executablePath(),+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium',+].find((p) => p && existsSync(p));+const canRun = browserSuiteCanRun('title card browser', { Chrome: chrome });++const W = 640;+const H = 360;+// A stand-in composition document: a full-frame canvas painted flat grey on every seek.+const DOCUMENT = `<canvas id="doc" width="${W}" height="${H}" style="position:fixed;inset:0;width:100vw;height:100vh"></canvas>+<script>+ window.PORTOS_MV = { render: { width: ${W}, height: ${H}, fps: 24 } };+ window.seeks = [];+ window.portosComposition = { durationSec: 20, fps: 24, width: ${W}, height: ${H},+ seek(t) { window.seeks.push(t); const ctx = document.getElementById('doc').getContext('2d'); ctx.fillStyle = '#404040'; ctx.fillRect(0, 0, ${W}, ${H}); } };+</script>`;++// Count bright (cream) pixels in a region of a PNG screenshot.+async function brightIn(png, { left, top, width, height }) {+ const { data, info } = await sharp(png).extract({ left, top, width, height }).raw().toBuffer({ resolveWithObject: true });+ let bright = 0;+ for (let i = 0; i < data.length; i += info.channels) if (data[i] > 200 && data[i + 1] > 200 && data[i + 2] > 180) bright += 1;+ return bright;+}++describe.skipIf(!canRun)('title card runtime in Chrome', () => {+ let browser;+ let page;+ const errors = [];+ const lowerLeft = { left: 0, top: H / 2, width: W / 2, height: H / 2 };+ const upperRight = { left: W / 2, top: 0, width: W / 2, height: H / 2 };+ const shotAt = async (t) => { await page.evaluate((at) => globalThis.portosComposition.seek(at), t); return page.screenshot(); };++ beforeAll(async () => {+ browser = await chromium.launch({ executablePath: chrome, headless: true });+ page = await browser.newPage({ viewport: { width: W, height: H } });+ page.on('pageerror', (error) => errors.push(error.message));+ const card = { title: 'Example Song', artist: 'Example Artist', year: '2026', startSec: 2, endSec: 8, fadeSec: 0.5 };+ await page.setContent(`<!doctype html><html><head><style>html,body{margin:0;background:#000}</style>+<script>${filmLookRuntimeSource({ preset: 'none' })}</script><script>${titleCardRuntimeSource(card)}</script></head><body>${DOCUMENT}</body></html>`);+ }, 30000);+ afterAll(async () => { await browser?.close(); });++ it('draws the card in the lower-left inside its window, nothing outside it, and the same pixels on a repeat seek', async () => {+ const before = await shotAt(1);+ const during = await shotAt(5);+ await shotAt(12);+ const again = await shotAt(5);+ const after = await shotAt(12);+ expect(await brightIn(before, lowerLeft)).toBe(0);+ expect(await brightIn(during, lowerLeft)).toBeGreaterThan(200);+ expect(await brightIn(during, upperRight)).toBe(0);+ expect(await brightIn(after, lowerLeft)).toBe(0);+ expect(Buffer.compare(during, again)).toBe(0);+ // The document still ran every seek, through both wrappers.+ expect(await page.evaluate(() => window.seeks)).toEqual([1, 5, 12, 5, 12]);+ expect(await page.evaluate(() => [globalThis.portosComposition.__portosFilmLookWrapped, globalThis.portosComposition.__portosTitleCardWrapped])).toEqual([true, true]);+ expect(errors).toEqual([]);+ }, 30000);++ it('lays the block out inside the title-safe corner and shrinks a long one to fit, with the real faces', async () => {+ const lines = await page.evaluate(() => globalThis.__portosTitleCard.layout());+ expect(lines.map((l) => l.text)).toEqual(['“Example Song”', 'Example Artist', '2026']);+ expect(lines.every((l) => l.align === 'left' && Math.abs(l.x - W * 0.06) < 1e-6)).toBe(true);+ expect(lines[0].px).toBeGreaterThan(lines[1].px);+ expect(lines.at(-1).y).toBeLessThan(H - H * 0.07);+ const long = await page.evaluate(() => {+ const card = globalThis.__portosTitleCard.card;+ globalThis.__portosTitleCard.apply({ ...card, title: 'An Extremely Long Song Title That Would Run Straight Off The Frame', size: 200 });+ const ctx = document.createElement('canvas').getContext('2d');+ const widths = globalThis.__portosTitleCard.layout().map((l) => { ctx.font = l.font; return ctx.measureText(l.text).width; });+ globalThis.__portosTitleCard.apply(card);+ return Math.max(...widths);+ });+ expect(long).toBeLessThanOrEqual(W * 0.62 + 0.5);+ }, 30000);++ it('takes a live change from the panel and redraws the paused frame, and clears on null', async () => {+ await shotAt(5);+ await page.evaluate(() => globalThis.__portosTitleCard.apply({ ...globalThis.__portosTitleCard.card, position: 'upper-right' }));+ const moved = await page.screenshot();+ expect(await brightIn(moved, upperRight)).toBeGreaterThan(200);+ expect(await brightIn(moved, lowerLeft)).toBe(0);+ await page.evaluate(() => globalThis.__portosTitleCard.apply(null));+ expect(await brightIn(await page.screenshot(), upperRight)).toBe(0);+ expect(errors).toEqual([]);+ }, 30000);+});diff --git a/server/lib/musicVideoTitleCard.js b/server/lib/musicVideoTitleCard.jsnew file mode 100644index 0000000000..43af96c09d--- /dev/null+++ b/server/lib/musicVideoTitleCard.js@@ -0,0 +1,279 @@+/**+ * Music Video — the opening title card: the small credit block an MTV video+ * opens with (song title, artist, year), fading in over the opener and out+ * again. One record on the project (`project.titleCard`, null = none) drives+ * the composition live preview and the final render alike.+ *+ * The card is not part of the composition document (documents are immutable+ * versions the director may have authored); `titleCardRuntimeSource()` is a+ * page script installed beside the document — in the preview's head and in+ * every render browser (`documentRenderInitScripts`) — that draws the card on+ * its own canvas above the page, re-drawn for every seek. It follows the+ * shared lyric type (lyricType.js): cream fill with an ink outline, no plate,+ * inside the same title-safe insets, so it reads like the lyrics.+ *+ * Every frame is a pure function of song time. Browser-safe, no imports.+ */++export const TITLE_CARD_POSITIONS = Object.freeze(['lower-left', 'lower-right', 'upper-left', 'upper-right', 'lower-center', 'center']);+export const TITLE_CARD_FONTS = Object.freeze(['display', 'sans', 'serif', 'mono']);+export const TITLE_CARD_LIMITS = Object.freeze({+ textMax: 120, yearMax: 20, startMax: 600, windowMin: 0.5, fadeMax: 3, sizeMin: 50, sizeMax: 200,+});+export const TITLE_CARD_DEFAULTS = Object.freeze({+ enabled: true, title: '', artist: '', year: '', extra: '', quoteTitle: true,+ startSec: 2, endSec: 8, fadeSec: 0.8, position: 'lower-left', font: 'display', size: 100, color: '#f3ead7',+});++const clampNum = (value, min, max, fallback) => {+ const n = typeof value === 'number' && Number.isFinite(value) ? value : fallback;+ return Math.min(max, Math.max(min, n));+};+const cleanText = (value, max) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '');+const round3 = (n) => Math.round(n * 1000) / 1000;++/**+ * A stored title card from any input (null for none). Missing fields take+ * TITLE_CARD_DEFAULTS; the window keeps at least TITLE_CARD_LIMITS.windowMin.+ */+export function normalizeTitleCard(input) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const D = TITLE_CARD_DEFAULTS;+ const L = TITLE_CARD_LIMITS;+ const startSec = round3(clampNum(input.startSec, 0, L.startMax, D.startSec));+ const endSec = round3(Math.max(startSec + L.windowMin, clampNum(input.endSec, 0, L.startMax + 60, Math.max(D.endSec, startSec + 6))));+ return {+ enabled: typeof input.enabled === 'boolean' ? input.enabled : D.enabled,+ title: cleanText(input.title, L.textMax),+ artist: cleanText(input.artist, L.textMax),+ year: cleanText(input.year, L.yearMax),+ extra: cleanText(input.extra, L.textMax),+ quoteTitle: typeof input.quoteTitle === 'boolean' ? input.quoteTitle : D.quoteTitle,+ startSec,+ endSec,+ fadeSec: round3(clampNum(input.fadeSec, 0, L.fadeMax, D.fadeSec)),+ position: TITLE_CARD_POSITIONS.includes(input.position) ? input.position : D.position,+ font: TITLE_CARD_FONTS.includes(input.font) ? input.font : D.font,+ size: Math.round(clampNum(input.size, L.sizeMin, L.sizeMax, D.size)),+ color: typeof input.color === 'string' && /^#[0-9a-f]{6}$/i.test(input.color) ? input.color.toLowerCase() : D.color,+ };+}++/** True when the card would draw something (enabled, with at least one line). */+export function titleCardVisible(card) {+ return !!(card && card.enabled && [card.title, card.artist, card.year, card.extra].some((line) => String(line || '').trim()));+}++/**+ * The default window for a new card: in a couple of seconds after the song+ * starts, out half a second before the first sung line (so it never shares the+ * screen with a lyric), held 3–6 seconds. With vocals that start almost at+ * once it still holds 3 seconds from 0.5s; the panel then flags the overlap.+ */+function defaultTitleCardTiming(firstLyricSec = null) {+ const first = typeof firstLyricSec === 'number' && Number.isFinite(firstLyricSec) && firstLyricSec > 0 ? firstLyricSec : null;+ if (first == null || first >= 9) return { startSec: 2, endSec: 8 };+ const startSec = first >= 5 ? 1.5 : 0.5;+ return { startSec, endSec: round3(Math.max(startSec + 3, first - 0.5)) };+}++/** The defaults a freshly enabled card is filled from: song title (version suffix dropped), artist, year. */+export function titleCardPrefill(project, { artist = '', year = new Date().getFullYear(), firstLyricSec = null } = {}) {+ const name = typeof project?.name === 'string' ? project.name.replace(/\s+v\d+$/i, '').trim() : '';+ return normalizeTitleCard({ ...defaultTitleCardTiming(firstLyricSec), title: name, artist, year: year ? String(year) : '' });+}++/* The three functions below are inlined into sandboxed pages by toString()+ * (titleCardRuntimeSource), so each must stay self-contained: no references+ * to module scope, only to each other by name. */++/** The card's opacity at song time t: a linear fade in and out inside its window (0 outside). */+function titleCardAlpha(card, t) {+ if (!card || !card.enabled || !(t >= card.startSec) || !(t < card.endSec)) return 0;+ const fade = Math.min(Math.max(0, card.fadeSec || 0), (card.endSec - card.startSec) / 2);+ if (fade <= 0) return 1;+ return Math.max(0, Math.min(1, (t - card.startSec) / fade, (card.endSec - t) / fade));+}++/**+ * The card's lines placed on a width × height frame: `[{ text, font, px, x, y,+ * align, outline }]` (y is the alphabetic baseline). The title is the first,+ * larger line; artist, year and the extra line follow. A block wider than its+ * zone shrinks as a whole, so the card never runs off frame. `measure(text,+ * font)` returns a width in pixels. Pure.+ */+function titleCardLayout(card, { width, height, measure }) {+ const stacks = {+ display: ['"MV Archivo", "Arial Black", Impact, sans-serif', 800, 600],+ sans: ['"Helvetica Neue", Helvetica, Arial, sans-serif', 700, 400],+ serif: ['Georgia, "Times New Roman", serif', 700, 400],+ mono: ['"MV Mono", Menlo, Consolas, monospace', 500, 500],+ };+ const [family, titleWeight, metaWeight] = stacks[card.font] || stacks.display;+ const clean = (s) => String(s || '').replace(/\s+/g, ' ').trim();+ const title = clean(card.title);+ const rows = [];+ if (title) rows.push({ text: card.quoteTitle ? `“${title}”` : title, title: true });+ for (const key of ['artist', 'year', 'extra']) if (clean(card[key])) rows.push({ text: clean(card[key]), title: false });+ if (!rows.length) return [];+ const unit = Math.min(width, height) / 1080;+ const scale = (Number(card.size) || 100) / 100;+ const insetX = Math.max(72 * unit, width * 0.06);+ const insetY = Math.max(72 * unit, height * 0.07);+ const position = card.position || 'lower-left';+ const centered = position === 'center' || position === 'lower-center';+ const portrait = height > width;+ const maxW = centered || portrait ? width - 2 * insetX : width * 0.62;+ const fontOf = (row, px) => `${row.title ? titleWeight : metaWeight} ${Math.floor(px * 100) / 100}px ${family}`;+ const baseOf = (row) => (row.title ? 50 : 36) * unit * scale;+ const widest = Math.max(...rows.map((row) => measure(row.text, fontOf(row, baseOf(row)))));+ const fit = widest > maxW && widest > 0 ? maxW / widest : 1;+ const sized = rows.map((row) => ({ ...row, px: baseOf(row) * fit }));+ const lineH = (row) => row.px * (row.title ? 1.18 : 1.3);+ const blockH = sized.reduce((sum, row) => sum + lineH(row), 0);+ let top;+ if (position === 'center') top = (height - blockH) / 2;+ else if (position.startsWith('upper')) top = insetY;+ else top = height - insetY - blockH;+ const align = centered ? 'center' : position.endsWith('right') ? 'right' : 'left';+ const x = align === 'left' ? insetX : align === 'right' ? width - insetX : width / 2;+ const out = [];+ let y = top;+ for (const row of sized) {+ y += lineH(row);+ // The baseline sits a little above the line box's foot, leaving room for descenders.+ out.push({ text: row.text, font: fontOf(row, row.px), px: row.px, x, y: y - row.px * (row.title ? 0.24 : 0.3), align, outline: Math.max(2, row.px * (row.title ? 0.15 : 0.12)) });+ }+ return out;+}++/** Draw the card at song time t onto a 2D context (nothing outside its window). */+function drawTitleCard(ctx, card, t, { width, height }) {+ const alpha = titleCardAlpha(card, t);+ if (!(alpha > 0)) return false;+ const measure = (text, font) => { ctx.font = font; return ctx.measureText(text).width; };+ const lines = titleCardLayout(card, { width, height, measure });+ if (!lines.length) return false;+ ctx.save();+ ctx.globalAlpha = alpha;+ ctx.textBaseline = 'alphabetic';+ ctx.lineJoin = 'round';+ ctx.miterLimit = 2;+ for (const line of lines) {+ ctx.font = line.font;+ ctx.textAlign = line.align;+ ctx.lineWidth = line.outline;+ ctx.strokeStyle = '#141217';+ ctx.strokeText(line.text, line.x, line.y);+ ctx.fillStyle = card.color || '#f3ead7';+ ctx.fillText(line.text, line.x, line.y);+ }+ ctx.restore();+ return true;+}++/**+ * A browser script that draws a card over the page it runs in: installed in+ * the composition live preview and in the final render's browsers before the+ * document's own scripts. It exposes `window.__portosTitleCard`:+ *+ * apply(card) put a (normalized) card on the page, or null to clear it+ * draw(t) redraw for song time t+ * layout() the lines as placed on the render frame (for checks)+ * card the card currently applied+ *+ * It wraps `globalThis.portosComposition.seek(t)` (chaining any accessor an+ * earlier init script installed, such as the film look's) so the card is drawn+ * for the frame before the document paints, after its faces have loaded. The+ * canvas is fixed over the viewport, fitted to the render's aspect, and sits+ * under the film look's root filter like the lyrics do.+ */+export function titleCardRuntimeSource(card = null) {+ return `(() => {+ ${titleCardAlpha.toString()}+ ${titleCardLayout.toString()}+ ${drawTitleCard.toString()}+ let card = ${JSON.stringify(normalizeTitleCard(card)).replace(/</g, '\\u003c')};+ let t = 0;+ let canvas = null;+ const fonts = new Map();+ const frame = () => {+ const r = globalThis.PORTOS_MV && globalThis.PORTOS_MV.render;+ return { width: (r && r.width) || innerWidth || 1920, height: (r && r.height) || innerHeight || 1080 };+ };+ // Resolves once the card's faces are loaded; null when they already are (the seek stays synchronous).+ const ready = () => {+ if (!card || !card.enabled || !document.fonts || !document.fonts.load) return null;+ const { width, height } = frame();+ const wanted = titleCardLayout(card, { width, height, measure: () => 0 }).map((line) => line.font);+ const pending = [];+ for (const font of wanted) {+ if (!fonts.has(font)) {+ const entry = { done: false };+ entry.promise = document.fonts.load(font).catch(() => null).then(() => { entry.done = true; });+ fonts.set(font, entry);+ }+ const entry = fonts.get(font);+ if (!entry.done) pending.push(entry.promise);+ }+ return pending.length ? Promise.all(pending) : null;+ };+ const draw = () => {+ if (!document.body) return;+ const on = card && titleCardAlpha(card, t) > 0;+ if (!on) { if (canvas) canvas.style.display = 'none'; return; }+ const { width, height } = frame();+ if (!canvas) {+ canvas = document.createElement('canvas');+ canvas.dataset.portosTitleCard = '1';+ canvas.setAttribute('aria-hidden', 'true');+ }+ if (!canvas.isConnected) document.body.appendChild(canvas);+ if (canvas.width !== width) canvas.width = width;+ if (canvas.height !== height) canvas.height = height;+ const vw = innerWidth || width;+ const vh = innerHeight || height;+ const s = Math.min(vw / width, vh / height);+ canvas.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483647;margin:0;padding:0;border:0;'+ + 'left:' + (vw - width * s) / 2 + 'px;top:' + (vh - height * s) / 2 + 'px;width:' + width * s + 'px;height:' + height * s + 'px';+ const ctx = canvas.getContext('2d');+ ctx.clearRect(0, 0, width, height);+ drawTitleCard(ctx, card, t, { width, height });+ };+ const api = {+ apply(next) {+ card = next && typeof next === 'object' ? next : null;+ const wait = ready();+ return wait ? wait.then(draw) : (draw(), Promise.resolve());+ },+ draw(at) { t = Number(at) || 0; draw(); },+ /** The current card's lines as drawn on the render frame (positions, fonts, sizes). */+ layout() {+ if (!card) return [];+ const { width, height } = frame();+ const ctx = (canvas || document.createElement('canvas')).getContext('2d');+ return titleCardLayout(card, { width, height, measure: (text, font) => { ctx.font = font; return ctx.measureText(text).width; } });+ },+ get card() { return card; },+ };+ Object.defineProperty(window, '__portosTitleCard', { value: api, configurable: false, writable: false });+ const wrap = (c) => {+ if (!c || typeof c !== 'object' || typeof c.seek !== 'function' || c.__portosTitleCardWrapped) return c;+ const seek = c.seek;+ const wrapped = function(at, ...rest) {+ t = Number(at) || 0;+ const go = () => { draw(); return seek.call(this, at, ...rest); };+ const wait = ready();+ return wait ? wait.then(go) : go();+ };+ try { Object.defineProperty(c, 'seek', { value: wrapped, configurable: true, writable: true }); Object.defineProperty(c, '__portosTitleCardWrapped', { value: true }); }+ catch { return Object.assign(Object.create(c), { seek: wrapped, __portosTitleCardWrapped: true }); }+ return c;+ };+ const prior = Object.getOwnPropertyDescriptor(globalThis, 'portosComposition');+ let own = prior && 'value' in prior ? wrap(prior.value) : undefined;+ Object.defineProperty(globalThis, 'portosComposition', { configurable: true, enumerable: true,+ get() { return prior && prior.get ? prior.get.call(globalThis) : own; },+ set(value) { const next = wrap(value); if (prior && prior.set) prior.set.call(globalThis, next); else own = next; } });+})();`;+}diff --git a/server/lib/musicVideoTitleCard.test.js b/server/lib/musicVideoTitleCard.test.jsnew file mode 100644index 0000000000..0338399469--- /dev/null+++ b/server/lib/musicVideoTitleCard.test.js@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';+import { TITLE_CARD_DEFAULTS, normalizeTitleCard, titleCardPrefill, titleCardVisible } from './musicVideoTitleCard.js';++describe('normalizeTitleCard', () => {+ it('fills defaults, clamps ranges and keeps the window open', () => {+ expect(normalizeTitleCard(null)).toBeNull();+ expect(normalizeTitleCard({})).toEqual({ ...TITLE_CARD_DEFAULTS });+ const card = normalizeTitleCard({ title: ' Example Song Title ', startSec: 5, endSec: 4, fadeSec: 9, size: 999, position: 'nowhere', font: 'comic', color: '#ABCDEF' });+ expect(card).toMatchObject({ title: 'Example Song Title', startSec: 5, endSec: 5.5, fadeSec: 3, size: 200, position: 'lower-left', font: 'display', color: '#abcdef' });+ });++ it('counts a card as visible only when enabled with some text', () => {+ expect(titleCardVisible(normalizeTitleCard({ title: 'Song' }))).toBe(true);+ expect(titleCardVisible(normalizeTitleCard({ title: 'Song', enabled: false }))).toBe(false);+ expect(titleCardVisible(normalizeTitleCard({ title: ' ' }))).toBe(false);+ });+});++describe('titleCardPrefill', () => {+ it('fills the song title without its version suffix, the artist and the year', () => {+ expect(titleCardPrefill({ name: 'Example Song Title v3' }, { artist: 'Example Artist', year: 2026 }))+ .toMatchObject({ enabled: true, title: 'Example Song Title', artist: 'Example Artist', year: '2026' });+ });++ it('times a new card to leave the screen before the first sung line', () => {+ const window = (firstLyricSec) => {+ const { startSec, endSec } = titleCardPrefill({ name: 'Song' }, { firstLyricSec });+ return [startSec, endSec];+ };+ expect(window(null)).toEqual([2, 8]);+ expect(window(30)).toEqual([2, 8]);+ expect(window(7)).toEqual([1.5, 6.5]);+ // Vocals almost at once: still a readable 3s hold (the panel then flags the overlap).+ expect(window(2)).toEqual([0.5, 3.5]);+ });+});diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 7e8bd5471f..4c51ecedfc 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -1,6 +1,7 @@import { MUSIC_VIDEO_MEDIA_MODES } from './musicVideoMediaPolicy.js';import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';import { filmLookSchema } from './filmLookValidation.js';+import { TITLE_CARD_FONTS, TITLE_CARD_LIMITS, TITLE_CARD_POSITIONS } from './musicVideoTitleCard.js';import { COVER_DESIGN_OPTIONS } from './musicVideoCoverOverlay.js';import { DISTROKID_REMEMBERED_OPTIONS } from './distrokidGenres.js';import { CROSS_LINK_EDIT_TARGETS } from './musicVideoCrossLinks.js';@@ -1200,6 +1201,25 @@ export const musicVideoCastAndSetsDirectionEditSchema = z.object({}).strict()).max(8).optional(),}).strict();+// The opening title card (lib/musicVideoTitleCard.js): song title, artist, year+// in a corner over the opener. Every field is optional (the normalizer fills+// defaults); null on the project = none.+export const musicVideoTitleCardSchema = z.object({+ enabled: z.boolean().optional(),+ title: z.string().max(TITLE_CARD_LIMITS.textMax).optional(),+ artist: z.string().max(TITLE_CARD_LIMITS.textMax).optional(),+ year: z.string().max(TITLE_CARD_LIMITS.yearMax).optional(),+ extra: z.string().max(TITLE_CARD_LIMITS.textMax).optional(),+ quoteTitle: z.boolean().optional(),+ startSec: z.number().min(0).max(TITLE_CARD_LIMITS.startMax).optional(),+ endSec: z.number().min(0).max(TITLE_CARD_LIMITS.startMax + 60).optional(),+ fadeSec: z.number().min(0).max(TITLE_CARD_LIMITS.fadeMax).optional(),+ position: z.enum(TITLE_CARD_POSITIONS).optional(),+ font: z.enum(TITLE_CARD_FONTS).optional(),+ size: z.number().min(TITLE_CARD_LIMITS.sizeMin).max(TITLE_CARD_LIMITS.sizeMax).optional(),+ color: z.string().regex(/^#[0-9a-f]{6}$/i, 'color is #rrggbb').optional(),+}).strict();+export const musicVideoProjectCreateSchema = z.object({mediaMode: z.enum(MUSIC_VIDEO_MEDIA_MODES).optional(),productionPolicy: musicVideoProductionPolicySchema.optional(),@@ -1224,6 +1244,8 @@ export const musicVideoProjectCreateSchema = z.object({soundBed: musicVideoSoundBedSchema.nullable().optional(),// The finishing film look (lib/filmLook.js); null = none.filmLook: filmLookSchema.nullable().optional(),+ // The opening title card (lib/musicVideoTitleCard.js); null = none.+ titleCard: musicVideoTitleCardSchema.nullable().optional(),}).strict();export const musicVideoProjectUpdateSchema = z.object({@@ -1250,6 +1272,8 @@ export const musicVideoProjectUpdateSchema = z.object({soundBed: musicVideoSoundBedSchema.nullable().optional(),// The finishing film look (lib/filmLook.js); null = none.filmLook: filmLookSchema.nullable().optional(),+ // The opening title card (lib/musicVideoTitleCard.js); null = none.+ titleCard: musicVideoTitleCardSchema.nullable().optional(),}).strict();// Mark a project finished outside PortOS (or clear the marker). The serverdiff --git a/server/routes/musicVideoCompositionDocument.test.js b/server/routes/musicVideoCompositionDocument.test.jsindex 54b3b404b0..fd794ecd45 100644--- a/server/routes/musicVideoCompositionDocument.test.js+++ b/server/routes/musicVideoCompositionDocument.test.js@@ -174,6 +174,18 @@ describe('music-video composition documents', () => {expect((await projects.getProject(project.id)).filmLook).toBeNull();});+ it('persists a normalized opening title card through the project route, refuses an unknown field, and clears it with null', async () => {+ const saved = await request(app).patch(`/api/music-video/${project.id}`).send({ titleCard: { title: ' Example Song ', artist: 'Example Artist', year: '2026', startSec: 3, endSec: 2 } });+ expect(saved.status).toBe(200);+ expect(saved.body.titleCard).toMatchObject({ enabled: true, title: 'Example Song', startSec: 3, endSec: 3.5, position: 'lower-left', font: 'display' });+ expect((await projects.getProject(project.id)).titleCard).toEqual(saved.body.titleCard);+ expect((await request(app).patch(`/api/music-video/${project.id}`).send({ titleCard: { title: 'x', label: 'y' } })).status).toBe(400);+ expect((await request(app).patch(`/api/music-video/${project.id}`).send({ titleCard: { position: 'sideways' } })).status).toBe(400);+ const cleared = await request(app).patch(`/api/music-video/${project.id}`).send({ titleCard: null });+ expect(cleared.status).toBe(200);+ expect(cleared.body.titleCard).toBeNull();+ });+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');diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.jsindex 6dd7493bc8..77fc016081 100644--- a/server/services/musicVideo/documentPreview.js+++ b/server/services/musicVideo/documentPreview.js@@ -1,6 +1,7 @@import { PREVIEW_DOCUMENT_BASE, inlineDocumentModule, previewDocumentPath } from './documentModules.js';import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';import { filmLookRuntimeSource } from '../../lib/filmLook.js';+import { titleCardRuntimeSource } from '../../lib/musicVideoTitleCard.js';/*** Music Video — the in-app live preview of a composition document.*@@ -190,6 +191,9 @@ const BOOTSTRAP = `(() => {} else if (message.type === 'portos-mv:film-look') {// The finishing look, live from the panel's sliders: applied to the page root, re-seeded per seek.if (globalThis.__portosFilmLook) globalThis.__portosFilmLook.apply(message.look && typeof message.look === 'object' ? message.look : null);+ } else if (message.type === 'portos-mv:title-card') {+ // The opening title card, live from its panel: redrawn at once over the paused frame.+ if (globalThis.__portosTitleCard) globalThis.__portosTitleCard.apply(message.card && typeof message.card === 'object' ? message.card : null);} else if (message.type === 'portos-mv:seek') {const t = Number(message.t) || 0;seeking = seeking.then(() => globalThis.portosComposition?.seek(t)).then(@@ -284,8 +288,8 @@ export async function buildDocumentPreview(project, { draft = false, files: give}const mode = musicVideoMediaMode(project);const csp = PREVIEW_CSP.replace('img-src data: blob:', mode === 'code-only' ? "img-src 'none'" : 'img-src data: blob:').replace('media-src data: blob:', mode !== 'code-images-video' ? "media-src 'none'" : 'media-src data: blob:');- // The film look runtime always ships (the panel posts live changes); the project's saved look is its start.- const head = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script>${BOOTSTRAP}</script><script>${filmLookRuntimeSource(project.filmLook)}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</script>`;+ // The film look and title card runtimes always ship (their panels post live changes); the saved records are their start.+ const head = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script>${BOOTSTRAP}</script><script>${filmLookRuntimeSource(project.filmLook)}</script><script>${inlineScript(titleCardRuntimeSource(project.titleCard))}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</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}`;diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.jsindex 6ab3932745..745d354573 100644--- a/server/services/musicVideo/documentRender.js+++ b/server/services/musicVideo/documentRender.js@@ -1,6 +1,7 @@import { assertMusicVideoMediaSelections, musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';import { filmLookRuntimeSource, isFilmLookNeutral } from '../../lib/filmLook.js';+import { titleCardRuntimeSource, titleCardVisible } from '../../lib/musicVideoTitleCard.js';/*** Music Video — render a project's composition document over the song.*@@ -61,12 +62,16 @@ export const documentAspect = musicVideoAspect;/*** The browser init scripts a document render opens its page with: the film- * look runtime (lib/filmLook.js) when the project has a non-neutral look, so- * every captured frame, probe sample and worker browser draws the same- * finishing filter the live preview shows. Pure.+ * look runtime (lib/filmLook.js) when the project has a non-neutral look, and+ * the opening title card (lib/musicVideoTitleCard.js) when it has one to show,+ * so every captured frame, probe sample and worker browser draws what the live+ * preview shows. Pure.*/export function documentRenderInitScripts(project) {- return isFilmLookNeutral(project?.filmLook) ? [] : [filmLookRuntimeSource(project.filmLook)];+ return [+ ...(isFilmLookNeutral(project?.filmLook) ? [] : [filmLookRuntimeSource(project.filmLook)]),+ ...(titleCardVisible(project?.titleCard) ? [titleCardRuntimeSource(project.titleCard)] : []),+ ];}const aspectOf = (width, height) => {diff --git a/server/services/musicVideo/documentRender.test.js b/server/services/musicVideo/documentRender.test.jsindex 57a7fd2c6f..d210209536 100644--- a/server/services/musicVideo/documentRender.test.js+++ b/server/services/musicVideo/documentRender.test.js@@ -182,3 +182,16 @@ it('installs the project film look in the render page before the document runs,expect(browser.seen.initScripts[0]).toContain('"grain":0.6');expect(await scratchEntries()).toEqual([]);});++// Uniquely catches the final render dropping the opening title card the live preview shows.+it('installs the opening title card in the render page only while it is on and has text', async () => {+ const { project, plan } = await fixture();+ const titled = { ...project, titleCard: { enabled: true, title: 'Example Song', artist: 'Example Artist', year: '2026', startSec: 2, endSec: 8, fadeSec: 0.8, position: 'lower-left', font: 'display', size: 100, color: '#f3ead7', extra: '', quoteTitle: true } };+ await expect(encode(titled, plan, 'job-title')).rejects.toThrow('stop after staging');+ expect(browser.seen.initScripts).toHaveLength(1);+ expect(browser.seen.initScripts[0]).toContain('__portosTitleCard');+ expect(browser.seen.initScripts[0]).toContain('"title":"Example Song"');+ await expect(encode({ ...titled, titleCard: { ...titled.titleCard, enabled: false } }, plan, 'job-title-off')).rejects.toThrow('stop after staging');+ expect(browser.seen.initScripts).toEqual([]);+ expect(await scratchEntries()).toEqual([]);+});diff --git a/server/services/musicVideo/lyricPlaythrough.js b/server/services/musicVideo/lyricPlaythrough.jsindex f35b77a663..183478c5dd 100644--- a/server/services/musicVideo/lyricPlaythrough.js+++ b/server/services/musicVideo/lyricPlaythrough.js@@ -80,7 +80,7 @@ export async function buildLyricPlaythroughPreview(project, { overlay = false }}const shots = timedShots(project.scenes);const scenes = shots.length ? shots : lyricScenes(cues, project.lyricMarkers, durationSec);- // Only the song and the words: no composition, overlay text, narrative events or film look of the+ // Only the song, the words and the opening title card: no composition, overlay text, narrative events or film look of the// project's own. The look would filter the whole page, and on the transparent overlay that dims the// storyboard frames under the words.const playthrough = { ...project, scenes, composition: { mode: 'document', textCues: [] }, filmLook: null };diff --git a/server/services/musicVideo/lyricPlaythrough.test.js b/server/services/musicVideo/lyricPlaythrough.test.jsindex 7ea4bce2c5..9bf01a7d23 100644--- a/server/services/musicVideo/lyricPlaythrough.test.js+++ b/server/services/musicVideo/lyricPlaythrough.test.js@@ -82,7 +82,8 @@ describe('lyric timing playthrough', () => {it('draws the same words alone on a transparent page for the storyboard animatic', async () => {const scenes = [{ sceneId: 's1', order: 0, label: 'Wide', startSec: 0, endSec: 30, textZone: 'upper-right', referenceImageId: 'frame.png' }];const filmLook = { preset: 'vhs', enabled: true };- const preview = await buildLyricPlaythroughPreview({ ...project, scenes, filmLook }, { overlay: true });+ const titleCard = { enabled: true, title: 'Example Song' };+ const preview = await buildLyricPlaythroughPreview({ ...project, scenes, filmLook, titleCard }, { overlay: true });const data = portosData(preview.html);expect(data.lyrics.map((line) => line.text)).toEqual(['hello there', 'second line']);expect(data.scenes.map(({ sceneId, textZone, media }) => [sceneId, textZone, media])).toEqual([['s1', 'upper-right', null]]);@@ -92,5 +93,7 @@ describe('lyric timing playthrough', () => {expect(preview.assets).toEqual([]);// The project's film look would filter (and dim) the whole transparent page.expect(preview.html).toContain('let look = null;');+ // The opening title card does ride along, so it can be checked against the lyrics and the animatic.+ expect(preview.html).toContain('"title":"Example Song"');});});diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 5f0ed0ef95..ba526b8eb2 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -38,6 +38,7 @@ import { ensureSceneTakes, TAKE_SLOT } from './takes.js';import { normalizeComposition, invalidateCompositionTiming, withStoredCompositionDocument } from './composition.js';import { normalizeSoundBed } from './soundBed.js';import { normalizeFilmLook } from '../../lib/filmLook.js';+import { normalizeTitleCard } from '../../lib/musicVideoTitleCard.js';import { remapTreatmentForClone, scenesFingerprint } from './treatment.js';import { normalizeMusicVideoAutomation } from '../../lib/musicVideoAutomation.js';@@ -162,6 +163,8 @@ export function buildProjectRecord(input, { id, now }) {soundBed: input.soundBed ? normalizeSoundBed(input.soundBed) : null,// The finishing film look every preview, render and baked still is viewed through; null = none.filmLook: input.filmLook ? normalizeFilmLook(input.filmLook) : null,+ // The opening title card (song, artist, year over the opener); null = none.+ titleCard: normalizeTitleCard(input.titleCard),// #8980 — optional pre-production treatment (brief, arc, shot direction,// proof checklist); null until the director starts one. See treatment.js.treatment: null,@@ -361,6 +364,8 @@ export function applyProjectPatch(project, patch) {...('soundBed' in patch ? { soundBed: normalizeSoundBed(patch.soundBed) } : {}),// The film look is replaced whole (one bounded record); null clears it....('filmLook' in patch ? { filmLook: normalizeFilmLook(patch.filmLook) } : {}),+ // The title card is replaced whole (one bounded record); null clears it.+ ...('titleCard' in patch ? { titleCard: normalizeTitleCard(patch.titleCard) } : {}),};// #8988: a bed is mixed UNDER the song — the song itself can't be its bed.const masterTrackId = 'trackId' in patch ? patch.trackId : project.trackId;