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: direct cover lettering controls, saved artist styles, uploadable fonts, outline/stencil titles (#10345)

Adam Eivyef19130bf73a
diff --git a/client/src/components/musicVideo/CoverArtPanel.jsx b/client/src/components/musicVideo/CoverArtPanel.jsx
index f3f83be555..16494f34e0 100644
--- a/client/src/components/musicVideo/CoverArtPanel.jsx
+++ b/client/src/components/musicVideo/CoverArtPanel.jsx
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react';
import { Download, Image as ImageIcon, Images, Sparkles } from 'lucide-react';
import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import useMusicVideoCoverLettering from '../../hooks/useMusicVideoCoverLettering.js';
+import CoverLetteringPanel from './CoverLetteringPanel.jsx';
const MAX_SOURCES = 24;
@@ -33,6 +35,8 @@ export function coverArtSources(project) {
* Any image the project has, or any in image history (or uploaded), can be
* the photo; the title and artist are set on it by code, so the lettering
* stays sharp. A cover finished elsewhere is used bare ("lettering" off).
+ * The Lettering section sets the song's design directly (no AI), with a live
+ * preview, uploaded fonts and a saved style per artist (#10345).
*/
export default function CoverArtPanel({ project, publishKit }) {
const art = project?.publishKit?.coverArt || {};
@@ -48,8 +52,12 @@ export default function CoverArtPanel({ project, publishKit }) {
// Follow the server: a restyle or a new photo turns lettering back on there.
useEffect(() => { setLettering(art.lettering !== false); }, [art.lettering]);
const [pickerOpen, setPickerOpen] = useState(false);
- const busy = publishKit.composing || publishKit.designing || publishKit.requestingImage;
+ // The Lettering section's open state lives here, not in the panel, which remounts whenever the saved design changes.
+ const [lettersOpen, setLettersOpen] = useState(Boolean(art.source));
+ const letterAssets = useMusicVideoCoverLettering({ enabled: lettering && lettersOpen });
+ const busy = publishKit.composing || publishKit.designing || publishKit.requestingImage || publishKit.savingLettering;
const chosen = art.source ? `${art.source.kind}:${art.source.filename}` : null;
+ const chosenSource = sources.find((s) => `${s.kind}:${s.filename}` === chosen) || null;
const look = () => ({ title: title.trim(), ...(tag !== null ? { tag: tag.trim() } : {}), focusX, lettering });
const needsTitle = lettering && !title.trim();
const compose = (source) => publishKit.composeCover({ ...(source ? { source: { kind: source.kind, filename: source.filename } } : {}), ...look() });
@@ -132,6 +140,12 @@ export default function CoverArtPanel({ project, publishKit }) {
<GalleryImagePicker open={pickerOpen} onClose={() => setPickerOpen(false)} allowUpload
onSelect={(item) => item?.filename && compose({ kind: 'image', filename: item.filename })} />
+ {lettering && (
+ <CoverLetteringPanel key={JSON.stringify(art.design ?? null)} project={project} art={art} source={chosenSource}
+ title={title} tag={tag ?? art.tag ?? ''} focusX={focusX} publishKit={publishKit} lettering={letterAssets} busy={busy}
+ open={lettersOpen} onToggle={setLettersOpen} />
+ )}
+
<div className="space-y-1 rounded border border-port-border p-2">
{art.rationale && <p className="text-port-text-muted">This song's look: {art.rationale}</p>}
<label htmlFor={idFor('notes')} className="block text-[11px] text-port-text-muted">
diff --git a/client/src/components/musicVideo/CoverArtPanel.test.jsx b/client/src/components/musicVideo/CoverArtPanel.test.jsx
index d64b74fc6e..8ca23cdbda 100644
--- a/client/src/components/musicVideo/CoverArtPanel.test.jsx
+++ b/client/src/components/musicVideo/CoverArtPanel.test.jsx
@@ -6,6 +6,8 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import CoverArtPanel, { coverArtSources } from './CoverArtPanel.jsx';
+// Lettering data (fonts, artist styles) loads from the server; this suite is about the cover's source and lettering switch.
+vi.mock('../../hooks/useMusicVideoCoverLettering.js', () => ({ default: () => ({ fonts: [], styles: [], uploading: false }) }));
vi.mock('../imageGen/GalleryImagePicker', () => ({
default: ({ open, onSelect, allowUpload }) => (open ? (
<button type="button" data-upload={String(allowUpload)} onClick={() => onSelect({ filename: 'history-example.png' })}>Pick history-example</button>
diff --git a/client/src/components/musicVideo/CoverLetteringPanel.jsx b/client/src/components/musicVideo/CoverLetteringPanel.jsx
new file mode 100644
index 0000000000..f6d959dadb
--- /dev/null
+++ b/client/src/components/musicVideo/CoverLetteringPanel.jsx
@@ -0,0 +1,189 @@
+import { useEffect, useMemo, useState } from 'react';
+import { RotateCcw, Save, Trash2, Type, Upload } from 'lucide-react';
+import {
+ COVER_ART_SIZE,
+ COVER_DESIGN_OPTIONS,
+ canvasCoverWidths,
+ coverOverlaySvg,
+ coverTypefaceChoices,
+ normalizeCoverDesign,
+} from '../../lib/musicVideoCoverOverlay.js';
+import { musicVideoCoverFontUrl } from '../../services/apiMusicVideo.js';
+
+const FIELDS = [
+ ['layout', 'Position'],
+ ['typeface', 'Typeface'],
+ ['weight', 'Weight'],
+ ['letterCase', 'Case'],
+ ['scale', 'Size'],
+ ['titleStyle', 'Title treatment'],
+ ['backdrop', 'Behind the title'],
+ ['tagStyle', 'Artist name style'],
+ ['tagLayout', 'Artist name placement'],
+];
+const humanize = (value) => {
+ const text = String(value).replace(/-/g, ' ');
+ return text.charAt(0).toUpperCase() + text.slice(1);
+};
+const control = 'w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';
+const button = 'flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 min-h-[44px] sm:min-h-0';
+
+// A face is registered with the page once per upload, so the preview sets the title in the file the server will.
+const loadedFaces = new Set();
+function usePreviewFonts(fonts) {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ if (typeof FontFace === 'undefined' || typeof document === 'undefined' || !document.fonts) return;
+ for (const font of fonts || []) {
+ const key = `${font.id}:${font.addedAt}`;
+ if (loadedFaces.has(key)) continue;
+ loadedFaces.add(key);
+ new FontFace(font.family, `url(${musicVideoCoverFontUrl(font.id)})`).load()
+ .then((face) => { document.fonts.add(face); setTick((t) => t + 1); })
+ .catch(() => loadedFaces.delete(key));
+ }
+ }, [fonts]);
+ return tick;
+}
+
+/**
+ * Lettering for the cover (#10345): a control for every field of the song's
+ * design, beside a live preview that lays the title and artist out with the
+ * same code the server renders with (lib/musicVideoCoverOverlay.js), so a tweak
+ * is seen at once with no AI call. "Set the lettering" saves the design and the
+ * server re-sets the cover in it. The design can be kept as the artist's style,
+ * and an uploaded typeface joins the Typeface choices.
+ *
+ * Remounted (keyed by the saved design) whenever the server's design changes,
+ * which drops any unsaved edits that the new design replaces.
+ */
+export default function CoverLetteringPanel({ project, art, source, title, tag, focusX, publishKit, lettering, busy, open, onToggle }) {
+ const idFor = (s) => `mv-lettering-${project?.id}-${s}`;
+ const fonts = lettering.fonts || [];
+ const styles = lettering.styles || [];
+ const fontTick = usePreviewFonts(lettering.fonts);
+ const saved = useMemo(() => normalizeCoverDesign(art.design, { fonts }), [art.design, lettering.fonts]); // eslint-disable-line react-hooks/exhaustive-deps
+ const [edits, setEdits] = useState({});
+ const design = normalizeCoverDesign({ ...saved, ...edits }, { fonts });
+ const dirty = JSON.stringify(design) !== JSON.stringify(saved);
+ const set = (key, value) => setEdits((prev) => ({ ...prev, [key]: value }));
+
+ const artist = (tag || '').trim();
+ const [pickedStyle, setPickedStyle] = useState('');
+ const chosenStyle = styles.find((s) => s.key === pickedStyle) || styles.find((s) => s.key === artist.toLowerCase().replace(/\s+/g, ' ')) || null;
+
+ const designKey = JSON.stringify(design);
+ const svg = useMemo(() => {
+ const widths = canvasCoverWidths(design, { title, tag, size: COVER_ART_SIZE }, fonts);
+ return coverOverlaySvg({ title, tag, design, widths, fonts });
+ }, [designKey, title, tag, lettering.fonts, fontTick]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const choices = (key) => (key === 'typeface' ? coverTypefaceChoices(fonts) : COVER_DESIGN_OPTIONS[key]);
+ const choiceLabel = (key, value) => (key === 'typeface' ? (fonts.find((f) => `font:${f.id}` === value)?.family || humanize(value)) : humanize(value));
+ const onFontFile = (e) => {
+ const file = e.target.files?.[0];
+ e.target.value = '';
+ if (file) lettering.uploadFont(file);
+ };
+
+ return (
+ <details open={open} onToggle={(e) => onToggle(e.currentTarget.open)} className="rounded border border-port-border p-2 text-xs">
+ <summary className="cursor-pointer text-sm font-medium flex items-center gap-1.5 min-h-[44px] sm:min-h-0"><Type size={14} /> Lettering</summary>
+ <div className="mt-2 flex flex-col sm:flex-row gap-3">
+ <div className="w-full sm:w-56 shrink-0 space-y-1">
+ <div className="relative w-full aspect-square overflow-hidden rounded border border-port-border bg-port-bg">
+ {source && <img src={source.src} alt="" className="absolute inset-0 w-full h-full object-cover" style={{ objectPosition: `${focusX * 100}% 50%` }} />}
+ <div role="img" aria-label={`Lettering preview for ${title || 'the cover'}`} className="absolute inset-0 [&>svg]:w-full [&>svg]:h-full" dangerouslySetInnerHTML={{ __html: svg }} />
+ </div>
+ <p className="text-port-text-muted">Preview. The cover is set in this when you save.</p>
+ </div>
+
+ <div className="flex-1 min-w-0 space-y-2">
+ <div className="grid grid-cols-2 gap-2">
+ {FIELDS.map(([key, label]) => (
+ <div key={key}>
+ <label htmlFor={idFor(key)} className="block text-[11px] text-port-text-muted">{label}</label>
+ <select id={idFor(key)} value={design[key]} onChange={(e) => set(key, e.target.value)} className={control}>
+ {choices(key).map((value) => <option key={value} value={value}>{choiceLabel(key, value)}</option>)}
+ </select>
+ </div>
+ ))}
+ <div>
+ <label htmlFor={idFor('titleColor')} className="block text-[11px] text-port-text-muted">Title color</label>
+ <input id={idFor('titleColor')} type="color" value={design.titleColor} onChange={(e) => set('titleColor', e.target.value)} className={`${control} p-0.5`} />
+ </div>
+ <div>
+ <label htmlFor={idFor('accentColor')} className="block text-[11px] text-port-text-muted">Accent color (artist, rule, band)</label>
+ <input id={idFor('accentColor')} type="color" value={design.accentColor} onChange={(e) => set('accentColor', e.target.value)} className={`${control} p-0.5`} />
+ </div>
+ <div>
+ <label htmlFor={idFor('tracking')} className="block text-[11px] text-port-text-muted">Letter spacing</label>
+ <input id={idFor('tracking')} type="range" min={-0.05} max={0.3} step={0.01} value={design.tracking} onChange={(e) => set('tracking', Number(e.target.value))} className="w-full min-h-[44px] sm:min-h-0" />
+ </div>
+ <label htmlFor={idFor('rule')} className="flex items-center gap-1.5 min-h-[44px] sm:min-h-0 self-end">
+ <input id={idFor('rule')} type="checkbox" checked={design.rule} onChange={(e) => set('rule', e.target.checked)} />
+ A thin line by the title
+ </label>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={() => publishKit.saveCoverDesign(design)} disabled={busy || !dirty} className={button}>
+ <Save size={13} /> {publishKit.savingLettering ? 'Setting the lettering…' : 'Set the lettering'}
+ </button>
+ {dirty && (
+ <button type="button" onClick={() => setEdits({})} disabled={busy} className={button}>
+ <RotateCcw size={13} /> Undo changes
+ </button>
+ )}
+ </div>
+
+ <div className="space-y-1 rounded border border-port-border p-2">
+ <span className="text-port-text-muted">Artist style: keep one look across a set of singles</span>
+ <div className="flex flex-wrap items-end gap-2">
+ <button type="button" onClick={() => lettering.saveStyle({ name: artist, design })} disabled={!artist}
+ className={button} title={artist ? `Save this lettering as ${artist}'s style` : 'Give the cover an artist name first'}>
+ <Save size={13} /> Save as artist style
+ </button>
+ {styles.length > 0 && (
+ <>
+ <div>
+ <label htmlFor={idFor('style')} className="block text-[11px] text-port-text-muted">Saved styles</label>
+ <select id={idFor('style')} value={chosenStyle?.key || ''} onChange={(e) => setPickedStyle(e.target.value)} className={control}>
+ <option value="" disabled>Choose an artist</option>
+ {styles.map((s) => <option key={s.key} value={s.key}>{s.name}</option>)}
+ </select>
+ </div>
+ <button type="button" onClick={() => publishKit.saveCoverDesign(chosenStyle.design)} disabled={busy || !chosenStyle} className={button}>
+ Apply artist style
+ </button>
+ <button type="button" onClick={() => lettering.removeStyle(chosenStyle.name)} disabled={!chosenStyle} aria-label={chosenStyle ? `Delete the style for ${chosenStyle.name}` : 'Delete the saved style'}
+ className="flex items-center text-port-text-muted hover:text-port-error disabled:opacity-50 rounded px-2 py-1.5 min-h-[44px] sm:min-h-0">
+ <Trash2 size={13} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+
+ <div className="space-y-1 rounded border border-port-border p-2">
+ <span className="text-port-text-muted">Your own typefaces (.ttf, .otf, .woff2)</span>
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor={idFor('font-file')} className={`${button} cursor-pointer ${lettering.uploading ? 'opacity-50' : ''}`}>
+ <Upload size={13} /> {lettering.uploading ? 'Adding the font…' : 'Upload a font'}
+ </label>
+ <input id={idFor('font-file')} type="file" accept=".ttf,.otf,.woff2" disabled={lettering.uploading} onChange={onFontFile} className="sr-only" />
+ {fonts.map((f) => (
+ <span key={f.id} className="flex items-center gap-1 rounded bg-port-bg border border-port-border px-1.5 py-1">
+ {f.family}
+ <button type="button" onClick={() => lettering.removeFont(f.id)} aria-label={`Remove the font ${f.family}`} className="text-port-text-muted hover:text-port-error min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 flex items-center justify-center">
+ <Trash2 size={12} />
+ </button>
+ </span>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ </details>
+ );
+}
diff --git a/client/src/components/musicVideo/CoverLetteringPanel.test.jsx b/client/src/components/musicVideo/CoverLetteringPanel.test.jsx
new file mode 100644
index 0000000000..dc419fb274
--- /dev/null
+++ b/client/src/components/musicVideo/CoverLetteringPanel.test.jsx
@@ -0,0 +1,83 @@
+/**
+ * The cover Lettering controls (#10345): a control changes the live preview
+ * with no request, "Set the lettering" sends the whole design to be saved,
+ * a saved artist style applies in one click, and an uploaded font joins the
+ * Typeface choices.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, within } from '@testing-library/react';
+
+const lettering = {
+ fonts: [{ id: 'example-font', family: 'Example Font', ext: 'ttf', width: 0.5, addedAt: '2026-01-01T00:00:00.000Z' }],
+ styles: [{ key: 'example artist', name: 'Example Artist', design: { layout: 'center', typeface: 'serif', titleStyle: 'outline' }, updatedAt: '2026-01-01T00:00:00.000Z' }],
+ uploading: false,
+ uploadFont: vi.fn(async () => null),
+ removeFont: vi.fn(async () => true),
+ saveStyle: vi.fn(async () => null),
+ removeStyle: vi.fn(async () => true),
+};
+vi.mock('../imageGen/GalleryImagePicker', () => ({ default: () => null }));
+vi.mock('../../hooks/useMusicVideoCoverLettering.js', () => ({ default: () => lettering }));
+
+import CoverArtPanel from './CoverArtPanel.jsx';
+
+const project = {
+ id: 'mv-example',
+ name: 'Example Song',
+ publishKit: {
+ thumbnails: ['frame-1.jpg'],
+ coverArt: {
+ title: 'Example Song', tag: 'Example Artist', focusX: 0.5, filename: 'cover-example.jpg',
+ source: { kind: 'thumbnail', filename: 'frame-1.jpg' },
+ design: { layout: 'bottom-left', typeface: 'sans', weight: 'bold', titleStyle: 'fill' },
+ },
+ },
+};
+const kit = (over = {}) => ({
+ composing: false, designing: false, requestingImage: false, savingLettering: false,
+ composeCover: vi.fn(async () => null), designCover: vi.fn(async () => null), generateCover: vi.fn(async () => null),
+ saveCoverDesign: vi.fn(async () => null), ...over,
+});
+const preview = () => screen.getByRole('img', { name: /Lettering preview/ });
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('CoverLetteringPanel (inside CoverArtPanel)', () => {
+ it('previews a control change at once, and saves the whole design only when asked', () => {
+ const k = kit();
+ render(<CoverArtPanel project={project} publishKit={k} />);
+ expect(preview().innerHTML).not.toContain('stroke=');
+ expect(screen.getByRole('button', { name: /Set the lettering/ })).toBeDisabled();
+
+ fireEvent.change(screen.getByLabelText('Title treatment'), { target: { value: 'outline' } });
+ fireEvent.change(screen.getByLabelText('Title color'), { target: { value: '#ff8800' } });
+ // The preview is laid out by the server's own code, so it shows the change with no request.
+ expect(preview().innerHTML).toContain('fill="none" stroke="#ff8800"');
+ expect(k.saveCoverDesign).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: /Set the lettering/ }));
+ expect(k.saveCoverDesign).toHaveBeenCalledWith(expect.objectContaining({ layout: 'bottom-left', typeface: 'sans', titleStyle: 'outline', titleColor: '#ff8800' }));
+
+ // Undo returns the controls (and the preview) to the saved design.
+ fireEvent.click(screen.getByRole('button', { name: /Undo changes/ }));
+ expect(screen.getByLabelText('Title treatment')).toHaveValue('fill');
+ expect(preview().innerHTML).not.toContain('stroke=');
+ });
+
+ it("offers the artist's uploaded font as a typeface and applies a saved artist style in one click", () => {
+ const k = kit();
+ render(<CoverArtPanel project={project} publishKit={k} />);
+ const typeface = screen.getByLabelText('Typeface');
+ expect(within(typeface).getByRole('option', { name: 'Example Font' })).toHaveValue('font:example-font');
+ fireEvent.change(typeface, { target: { value: 'font:example-font' } });
+ expect(preview().innerHTML).toContain("font-family=\"'Example Font',sans-serif\"");
+
+ // The saved style for the cover's artist is chosen already; one click puts it on this song.
+ expect(screen.getByLabelText('Saved styles')).toHaveValue('example artist');
+ fireEvent.click(screen.getByRole('button', { name: 'Apply artist style' }));
+ expect(k.saveCoverDesign).toHaveBeenCalledWith(expect.objectContaining({ layout: 'center', typeface: 'serif', titleStyle: 'outline' }));
+
+ fireEvent.click(screen.getByRole('button', { name: /Save as artist style/ }));
+ expect(lettering.saveStyle).toHaveBeenCalledWith({ name: 'Example Artist', design: expect.objectContaining({ typeface: 'font:example-font' }) });
+ });
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f681dfb117..7537c3c321 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -263,6 +263,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. A server refusal toasts as a failure; a throw in the hook's own follow-up AFTER the server succeeded reloads the saved record instead (#9940), so an opened repair whose resume failed stays recoverable from the "Needs attention" banner. Returns `{ busy, revise(excerptId, sceneIds?), repair(basis), repairPerformance(sceneId, input), resume(revisionId), cancel(revisionId) }`. | The Music Video excerpt panel. |
| `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and reports outcomes; the server generates a run's revised sections itself (#10014), so the board never submits them and a run completes with no tab open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. |
| `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |
+| `useMusicVideoCoverLettering` | Music Video cover Lettering controls (#10345): the install's uploaded typefaces and saved per-artist styles, loaded once. Loads on first `enabled` (the section is open). Returns `{ fonts, styles, uploading, uploadFont(file), removeFont(id), saveStyle({ name, design }), removeStyle(name) }` (`fonts`/`styles` null until loaded); each mutation applies the server's answer at once. | `CoverArtPanel` (Publish stage). |
| `useMusicVideoPublishKit` | Music Video publishing kit (#9281): a `useSseJobSlot` build job (encodes, thumbnails, captions, chapters) whose terminal frame reloads the project, plus the one-call copy draft, per-field copy edits and thumbnail choice, each applying the returned project. Returns `{ building, progress, build(), cancelBuild(), drafting, saving, draftCopy(body), saveCopy(patch), selectThumbnail(filename) }`. | The Music Video Publish stage. |
| `useMusicVideoPublishing` | Music Video posting (#9282): per-platform drafts filled in the PortOS Browser. `prepare` returns the filled draft's summary and screenshot (a sign-in-required refusal is kept as the platform's error with its login URL), `submit` posts that reviewed draft and applies the returned project, `discard` closes it. Platforms are opt-in (#9287): it loads the saved `platforms` (enabled + optional account each) and per-platform `history` (posts, reception tally, recent notes across projects); `setPlatform` toggles one optimistically and `recordPost` saves a hand-made post's link or a post's reception and notes. Returns `{ drafts, busy, errors, prepare(target, options), submit(target), discard(target), platforms, history, enabledTargets, setPlatform(target, change), recordPost(target, body) }`. | The Music Video Publish stage's posting panel. |
| `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 5ebfb210a5..0e9fc5a35d 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -65,6 +65,7 @@ export { default as useMusicVideoAutoReview } from './useMusicVideoAutoReview.js
export { default as useMusicVideoCastAndSets } from './useMusicVideoCastAndSets.js';
export { default as useMusicVideoDevArtifacts } from './useMusicVideoDevArtifacts.js';
export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';
+export { default as useMusicVideoCoverLettering } from './useMusicVideoCoverLettering.js';
export { default as useMusicVideoPublishKit } from './useMusicVideoPublishKit.js';
export { default as useMusicVideoPublishing } from './useMusicVideoPublishing.js';
export { default as useMusicVideoKickoff } from './useMusicVideoKickoff.js';
diff --git a/client/src/hooks/useMusicVideoCoverLettering.js b/client/src/hooks/useMusicVideoCoverLettering.js
new file mode 100644
index 0000000000..08ca35d9db
--- /dev/null
+++ b/client/src/hooks/useMusicVideoCoverLettering.js
@@ -0,0 +1,65 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import toast from '../components/ui/Toast';
+import {
+ deleteMusicVideoArtistStyle,
+ deleteMusicVideoCoverFont,
+ getMusicVideoArtistStyles,
+ getMusicVideoCoverFonts,
+ saveMusicVideoArtistStyle,
+ uploadMusicVideoCoverFont,
+} from '../services/apiMusicVideo.js';
+
+/**
+ * What the cover Lettering controls draw on besides the song itself (#10345):
+ * the typefaces the director uploaded and the saved style per artist. Both are
+ * install-wide server records, loaded once, the first time `enabled` (the
+ * Lettering section is open); each mutation applies the server's answer at
+ * once. `fonts` / `styles` are null until loaded. Failures toast through the
+ * shared request layer and leave the lists as they were.
+ */
+export default function useMusicVideoCoverLettering({ enabled = true } = {}) {
+ const [fonts, setFonts] = useState(null);
+ const [styles, setStyles] = useState(null);
+ const [uploading, setUploading] = useState(false);
+ const requested = useRef(false);
+
+ // One load per mount, the first time the section is open; closing it again never drops the answer.
+ useEffect(() => {
+ if (!enabled || requested.current) return;
+ requested.current = true;
+ getMusicVideoCoverFonts({ silent: true }).then((res) => setFonts(res?.fonts || [])).catch(() => setFonts((prev) => prev || []));
+ getMusicVideoArtistStyles({ silent: true }).then((res) => setStyles(res?.styles || [])).catch(() => setStyles((prev) => prev || []));
+ }, [enabled]);
+
+ const uploadFont = useCallback(async (file) => {
+ setUploading(true);
+ const res = await uploadMusicVideoCoverFont(file).catch(() => null);
+ setUploading(false);
+ if (!res) return null;
+ setFonts(res.fonts || []);
+ toast.success(`Added the font ${res.font?.family || ''}`.trim());
+ return res.font;
+ }, []);
+
+ const removeFont = useCallback(async (id) => {
+ const res = await deleteMusicVideoCoverFont(id).catch(() => null);
+ if (res) setFonts(res.fonts || []);
+ return Boolean(res);
+ }, []);
+
+ const saveStyle = useCallback(async ({ name, design }) => {
+ const res = await saveMusicVideoArtistStyle({ name, design }).catch(() => null);
+ if (!res?.style) return null;
+ setStyles((prev) => [...(prev || []).filter((s) => s.key !== res.style.key), res.style].sort((a, b) => a.name.localeCompare(b.name)));
+ toast.success(`Saved the style for ${res.style.name}`);
+ return res.style;
+ }, []);
+
+ const removeStyle = useCallback(async (name) => {
+ const res = await deleteMusicVideoArtistStyle(name).catch(() => null);
+ if (res) setStyles((prev) => (prev || []).filter((s) => s.name !== name));
+ return Boolean(res);
+ }, []);
+
+ return { fonts, styles, uploading, uploadFont, removeFont, saveStyle, removeStyle };
+}
diff --git a/client/src/hooks/useMusicVideoPublishKit.js b/client/src/hooks/useMusicVideoPublishKit.js
index 3e4ab6b0c5..541437c2f7 100644
--- a/client/src/hooks/useMusicVideoPublishKit.js
+++ b/client/src/hooks/useMusicVideoPublishKit.js
@@ -12,6 +12,7 @@ import {
composeMusicVideoCoverArt,
generateMusicVideoCoverArt,
designMusicVideoCoverArt,
+ saveMusicVideoCoverDesign,
} from '../services/apiMusicVideo.js';
import useSseJobSlot from './useSseJobSlot.js';
@@ -30,6 +31,7 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}
const [saving, setSaving] = useState(false);
const [composing, setComposing] = useState(false);
const [designing, setDesigning] = useState(false);
+ const [savingLettering, setSavingLettering] = useState(false);
const [requestingImage, setRequestingImage] = useState(false);
const reload = (id) => {
@@ -108,6 +110,14 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}
.catch(() => null)
.finally(() => setDesigning(false));
};
+ // The Lettering controls: the song's design set directly (no AI call), the cover re-set in it.
+ const saveCoverDesign = (design) => {
+ setSavingLettering(true);
+ return saveMusicVideoCoverDesign(projectId, design)
+ .then(apply)
+ .catch(() => null)
+ .finally(() => setSavingLettering(false));
+ };
// In flight from the click until the request is queued (a song with no design
// drafts one first); after that the record's `pending` reports progress.
const generateCover = (body) => {
@@ -132,6 +142,8 @@ export default function useMusicVideoPublishKit({ project, replaceProject } = {}
composeCover,
designing,
designCover,
+ savingLettering,
+ saveCoverDesign,
requestingImage,
generateCover,
};
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 72fbbbfd36..77f9464a06 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -65,6 +65,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectActionGroups.jsx` and `hooks/useMusicVideoSceneMedia.js`. |
| `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeClipUrl` (hover-preview clip), `sceneHasPendingDecision` (contact-sheet filter), `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. |
| `musicVideoSceneAttention.js` | Music Video per-scene attention model (#10152): `sceneAttention(scene, ctx)` returns the codes (`missing-frame`, `missing-clip`, `under-covered`, `contract-problem`, `perf-blocked`, `candidates-pending`, `plate-unverified`, `no-span`, `last-failure`) behind the collapsed scene-row chips, the Board `?scenes=attention\|missing\|all` filter (`parseSceneFilter`, `sceneMatchesFilter`) and the Produce per-shot strip; `SCENE_ATTENTION_LABELS`. Used by `components/musicVideo/SceneCard.jsx`, `stages/BoardStage.jsx` and `stages/ProduceStage.jsx`. |
+| `musicVideoCoverOverlay.js` | Cover-art lettering preview (#10345): re-export of `server/lib/musicVideoCoverOverlay.js` (the design vocabulary, `normalizeCoverDesign`, `coverOverlaySvg`) plus `canvasCoverWidths(design, texts, fonts)`, which measures text with a canvas so the live preview wraps and sizes the title the way the server's measured render does. |
| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceRepair` (measured accepted-prefix boundary, suffix interval and next spend), `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |
| `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (six steps: Song `setup` → Look `cast-sets` → Storyboard `board` → Make `produce` → Final render `review` → Publish; a retired `compose` link resolves to Make), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete step; a live production run pins Make), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, verify lyric timing, stop/resume production, render final, …), `describeProjectStatus` (the header line and the step that needs the director), `autopilotStatus` (the header Autopilot button), `projectSpend(project)` (paid generation used vs. cap), `projectShotSummary(project)` (document shots or scene counts), `stageChecklist(stageId, project, readiness)` (what one step still needs, with the open approval's reason and a scroll anchor), `stepNotes(project, readiness, publish)` (one fact per step for the step list), `listPreviewSources` (final, live composition, drafts, then the storyboard animatic), `projectServicesSummary(project)` (the saved image/video render services), `compareMusicVideoProjectsNewestFirst(a, b)` (sort projects newest created / updated first for project cards and pickers), and `currentProductionRun`; `productionReviewStopGuidance` separates current approval blockers from historical run stops. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. |
| `musicVideoAttention.js` | Music Video "Needs attention" model (#9940): `deriveAttentionItems(project, live)` returns the banner rows for server-held states a client-orchestrated workflow can strand — an open/rendering revision, an interrupted Cast & Sets stage, a running auto-review waiting on its revised sections, a final render nobody is watching — derived from the persisted record so they survive a reload (healthy work this tab can see progressing is not flagged); `openRevisionOf(project)`; `ATTENTION_ANCHOR_ID` + `revealAttention()` scroll a refusal toast to the banner. Used by `components/musicVideo/NeedsAttentionBanner.jsx` and `pages/MusicVideo.jsx`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index c45f46844a..ff5b49194e 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -75,6 +75,7 @@ export * from './musicVideoAspect.js';
export * from './musicVideoMotion.js';
export * from './musicVideoTakes.js';
export * from './musicVideoSceneAttention.js';
+export * from './musicVideoCoverOverlay.js';
export * from './musicVideoShotTiming.js';
export * from './musicVideoStages.js';
export * from './musicVideoAttention.js';
diff --git a/client/src/lib/musicVideoCoverOverlay.js b/client/src/lib/musicVideoCoverOverlay.js
new file mode 100644
index 0000000000..6d0f2b043d
--- /dev/null
+++ b/client/src/lib/musicVideoCoverOverlay.js
@@ -0,0 +1,42 @@
+/**
+ * Cover-art lettering preview (#10345).
+ *
+ * Re-export of `server/lib/musicVideoCoverOverlay.js` — the one layout the
+ * server renders the cover with, imported rather than copied so the live
+ * Lettering preview cannot drift from the saved JPEG — plus a canvas width
+ * measure standing in for the server's sharp probe.
+ */
+import { coverFontSpec, tagTextFor, titleLinesFor } from '../../../server/lib/musicVideoCoverOverlay.js';
+
+export {
+ COVER_ART_SIZE,
+ COVER_DESIGN_OPTIONS,
+ DEFAULT_COVER_DESIGN,
+ coverOverlaySvg,
+ coverTypefaceChoices,
+ customTypeface,
+ normalizeCoverDesign,
+} from '../../../server/lib/musicVideoCoverOverlay.js';
+
+const PROBE_PX = 100;
+
+/**
+ * `{ title(text), tag(text) }` for `coverOverlaySvg`: each text's width at a 1px
+ * font size, measured on a canvas in the design's font stack. Null where a
+ * canvas is unavailable, so the overlay falls back to the faces' average advance.
+ */
+export function canvasCoverWidths(design, { title, tag, size }, fonts = []) {
+ const ctx = typeof document === 'undefined' ? null : document.createElement('canvas').getContext?.('2d');
+ if (!ctx) return null;
+ const measure = (kind, texts) => {
+ const { family, weight, trackingEm } = coverFontSpec(design, kind, fonts);
+ ctx.font = `${weight} ${PROBE_PX}px ${family}`;
+ if ('letterSpacing' in ctx) ctx.letterSpacing = `${trackingEm * PROBE_PX}px`;
+ const out = new Map(texts.filter(Boolean).map((text) => [text, ctx.measureText(text).width / PROBE_PX]));
+ return (text) => out.get(text);
+ };
+ return {
+ title: measure('title', titleLinesFor(title, design, size, fonts)),
+ tag: measure('tag', [tagTextFor(tag, design)]),
+ };
+}
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 1d4376fa8d..f6db0f49bc 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -256,6 +256,24 @@ export const designMusicVideoCoverArt = (id, body, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art/design`, { method: 'POST', body: JSON.stringify(body || {}), ...options });
export const generateMusicVideoCoverArt = (id, body, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art/generate`, { method: 'POST', body: JSON.stringify(body || {}), ...options });
+// Lettering controls (#10345): `design` is any subset of the cover design, merged over the song's; recomposes at once.
+export const saveMusicVideoCoverDesign = (id, design, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/cover-art/design`, { method: 'PUT', body: JSON.stringify({ design }), ...options });
+// One saved cover design per artist, and the typefaces the director uploaded (#10345).
+export const getMusicVideoArtistStyles = (options = {}) => request('/music-video/publish/artist-styles', options);
+export const saveMusicVideoArtistStyle = (body, options = {}) =>
+ request('/music-video/publish/artist-styles', { method: 'PUT', body: JSON.stringify(body), ...options });
+export const deleteMusicVideoArtistStyle = (name, options = {}) =>
+ request(`/music-video/publish/artist-styles?name=${encodeURIComponent(name)}`, { method: 'DELETE', ...options });
+export const getMusicVideoCoverFonts = (options = {}) => request('/music-video/publish/cover-fonts', options);
+export const uploadMusicVideoCoverFont = (file, options = {}) => {
+ const body = new FormData();
+ body.append('font', file, file.name || 'font');
+ return request('/music-video/publish/cover-fonts', { method: 'POST', body, ...options });
+};
+export const deleteMusicVideoCoverFont = (id, options = {}) =>
+ request(`/music-video/publish/cover-fonts/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
+export const musicVideoCoverFontUrl = (id) => `/api/music-video/publish/cover-fonts/${encodeURIComponent(id)}/file`;
// ---- Posting (#9282) ----
// Prepare fills the platform's post in the PortOS Browser → { draftId, target,
// summary, screenshot }. Manual posting is handled outside this wrapper.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8c57fdaaf4..35db9dd9fe 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -464,6 +464,10 @@ Apply this checklist to **every new feature that persists data**, and require it
Optional SDK environments under `data/venvs/` are machine-local, regenerable runtime files, not application records. Reactor provisions its pinned SDK, private Python and checksum-verified uv manager on the first authorized render (or optionally through `npm run setup:reactor`); no seed, migration, database table, or peer synchronization is needed. Data Manager identifies these environments but does not purge them while render processes may use them.
+### Music Video cover lettering
+
+`data/cover-fonts/` is `file-primary`: the typefaces a director uploads for cover lettering (`<id>.ttf|otf|woff2`) plus a small `fonts.json` index (`{ id, family, ext, width, addedAt }`, width measured at upload). Machine-local and never federated: a font is a licensed binary the director chose for this install, and whether it renders depends on this machine's font system. It is included in normal data backups (no new exclude); it relates to no other record and needs no search, so it stays out of the DB. On macOS each font is also mirrored into `~/Library/Fonts/PortOS/`, because CoreText reads only Fonts folders; other platforms register the file with fontconfig through libvips. An upload is refused unless the renderer proves it can set text in it. The per-artist saved cover design is `settings.musicVideoPublishing.artistStyles` in the file-primary `data/settings.json` (keyed by lowercased artist name), beside the machine-local `platforms` choice; settings are not synced between machines. Neither needs a migration: a cover design stored before `titleStyle`/`tagLayout` existed normalizes to the previous look unchanged. Code: `server/services/musicVideo/coverFonts.js`, `publish/artistStyles.js`; layout: `server/lib/musicVideoCoverOverlay.js`.
+
### Private integration API keys
`data/private/api-keys.json` is machine-local `file-primary` configuration,
diff --git a/server/lib/README.md b/server/lib/README.md
index d02baa21c0..b0bd2c6d40 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -319,6 +319,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `filmStyleGrammars.js` | Curated film style grammar catalog (`FILM_STYLE_GRAMMARS`, eight code-rendered media with rendering, colour, type, motion, camera, sound and native-move guidance), `getFilmStyleGrammar`, `summarizeFilmStyleGrammar` (picker projection) and `knownFilmStyleIdSchema` (request-field id check) and `renderFilmStyleGrammarPrompt(id, { parts })` — one prompt section capped at `FILM_STYLE_PROMPT_MAX_CHARS`; unknown id or bad parts is a 400. |
| `falVideoModels.js` | Curated fal.ai VIDEO model catalog — `FAL_VIDEO_MODELS` (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on `FAL_VIDEO_PRICING_VERIFIED_AT`; `getFalVideoModel()`, `coerceFalVideoSeconds()` (round UP to a covering length), `resolveFalVideoResolution()`, `buildFalVideoRequest()` (the exact queue body per model; null for an uncurated id, which keeps the legacy body), `estimateFalVideoCostUsd()` (null = unknown), `describeFalVideoRate()`. Dependency-free; the client re-exports it. |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
+| `fontMetadata.js` | `fontContainer(buf)` (sfnt / woff2 / null) and `fontFamilyName(buf)` — a font file's family name read from its `name` table (TrueType, OpenType, and WOFF2's brotli stream) with no font library; null for anything unreadable (#10345). |
+| `musicVideoCoverOverlay.js` | Music Video cover lettering (#10345): `COVER_DESIGN_OPTIONS` / `DEFAULT_COVER_DESIGN`, `normalizeCoverDesign(design, { fonts })` (accepts every stored design; a `font:<id>` typeface only when that uploaded font is listed), `coverOverlaySvg({ title, tag, design, widths, fonts })` and the `coverFontSpec` / `fontAttrs` / `titleLinesFor` / `tagTextFor` helpers the width probe reads. Pure; the server render (`coverArtCompose.js`) and the client's live Lettering preview run this one layout. |
| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–30s per take, default 1080P), `falSceneTake()` (the fal model/length/resolution a scene take requests and its estimated cost — shared by the board, the submit path and the autopilot spend cap) + `falTakeRequestFields(take)` (that take as `/api/video-gen` fields), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `planPerformanceRepair()` (complete measured suffix evidence, safe word-gap boundary, source/clip timebases and next spend), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it. |
| `reactorStartingFrame.js` | Fits a reactor.inc `starting_frame` to the fast-h3 session canvas before it is uploaded. `readImageSize(path)` → `{width,height}` or `null` (never a guessed dimension), and `prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath)` → `{ aspect, canvas, framePath, fittedPath }`: an absent `requestedAspect` DERIVES the canvas from the frame's own shape (`nearestReactorAspect`), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. `fittedPath` is the temp file the caller deletes; `null` means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does. |
| `reactorVideoClip.js` | The reactor.inc `fast-h3` clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — `REACTOR_MAX_PROMPT_LENGTH` (800; the API rejects a longer prompt rather than truncating it), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS` (5.167–14.375, i.e. 124–345 frames at the `REACTOR_CLIP_FPS` 24 it delivers), `REACTOR_MAX_CLIP_ID_LENGTH`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()` (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Also the CANVAS contract `set_canvas` accepts: `REACTOR_CANVASES` (`16:9` 1344×768, `4:3` 1024×768, `1:1` 768×768, `9:16` 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), `REACTOR_ASPECTS`, `REACTOR_DEFAULT_ASPECT`, `reactorCanvas(aspect)` and `nearestReactorAspect(width, height)` (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). Mirrored to `client/src/lib/reactorVideoClip.js`, parity pinned by `reactorVideoClip.test.js`. |
diff --git a/server/lib/fontMetadata.js b/server/lib/fontMetadata.js
new file mode 100644
index 0000000000..fa1f4bc5d4
--- /dev/null
+++ b/server/lib/fontMetadata.js
@@ -0,0 +1,115 @@
+/**
+ * Read a font file's family name without a font library (#10345).
+ *
+ * The cover lettering names an uploaded typeface by the family the renderer
+ * registers it under, which is the family inside the file, not its filename.
+ * Handles TrueType/OpenType (`name` table, preferring the typographic family)
+ * and WOFF2 (the `name` table is stored untransformed inside the container's
+ * one brotli stream). Returns null for anything else, including collections.
+ */
+import { brotliDecompressSync } from 'zlib';
+
+const FAMILY_NAME_IDS = [16, 1];
+const SFNT_FLAVORS = new Set([0x00010000, 0x4f54544f, 0x74727565]); // 1.0 (TrueType), 'OTTO' (CFF), 'true'
+// WOFF2 table directory: the registered tags by index (63 means an explicit 4-byte tag follows).
+const WOFF2_KNOWN_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG', 'EBDT', 'EBLC', 'gasp', 'hdmx', 'kern', 'LTSH', 'PCLT', 'VDMX', 'vhea', 'vmtx', 'BASE', 'GDEF', 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH', 'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar', 'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill'];
+
+/** The container a buffer is, from its first four bytes: 'sfnt', 'woff2', or null. */
+export function fontContainer(buf) {
+ if (!Buffer.isBuffer(buf) || buf.length < 12) return null;
+ if (buf.toString('latin1', 0, 4) === 'wOF2') return 'woff2';
+ return SFNT_FLAVORS.has(buf.readUInt32BE(0)) ? 'sfnt' : null;
+}
+
+function familyFromNameTable(table) {
+ if (table.length < 6) return null;
+ const count = table.readUInt16BE(2);
+ const storage = table.readUInt16BE(4);
+ const names = new Map();
+ for (let i = 0; i < count; i += 1) {
+ const at = 6 + i * 12;
+ if (at + 12 > table.length) break;
+ const platform = table.readUInt16BE(at);
+ const nameId = table.readUInt16BE(at + 6);
+ const length = table.readUInt16BE(at + 8);
+ const start = storage + table.readUInt16BE(at + 10);
+ if (!FAMILY_NAME_IDS.includes(nameId) || start + length > table.length) continue;
+ const raw = table.subarray(start, start + length);
+ // Windows (3) and Unicode (0) names are UTF-16BE; Macintosh (1) names are single-byte.
+ const text = platform === 3 || platform === 0 ? Buffer.from(raw).swap16().toString('utf16le') : raw.toString('latin1');
+ // Windows names win over Mac ones for the same id: they carry the full Unicode name.
+ if (text.trim() && (!names.has(nameId) || platform === 3)) names.set(nameId, text.trim());
+ }
+ return FAMILY_NAME_IDS.map((id) => names.get(id)).find(Boolean) || null;
+}
+
+function sfntNameTable(buf) {
+ const tables = buf.readUInt16BE(4);
+ for (let i = 0; i < tables; i += 1) {
+ const at = 12 + i * 16;
+ if (at + 16 > buf.length) return null;
+ if (buf.toString('latin1', at, at + 4) !== 'name') continue;
+ const offset = buf.readUInt32BE(at + 8);
+ const length = buf.readUInt32BE(at + 12);
+ return offset + length <= buf.length ? buf.subarray(offset, offset + length) : null;
+ }
+ return null;
+}
+
+// WOFF2 "UIntBase128": 7 bits per byte, high bit set while more follow.
+function readBase128(buf, at) {
+ let value = 0;
+ for (let i = 0; i < 5; i += 1) {
+ const byte = buf[at + i];
+ if (byte === undefined) return null;
+ value = value * 128 + (byte & 0x7f);
+ if (!(byte & 0x80)) return { value, next: at + i + 1 };
+ }
+ return null;
+}
+
+function woff2NameTable(buf) {
+ if (buf.length < 48) return null;
+ const count = buf.readUInt16BE(12);
+ const compressedSize = buf.readUInt32BE(20);
+ let at = 48;
+ let offset = 0;
+ let name = null;
+ for (let i = 0; i < count; i += 1) {
+ const flags = buf[at];
+ if (flags === undefined) return null;
+ at += 1;
+ let tag = WOFF2_KNOWN_TAGS[flags & 0x3f];
+ if ((flags & 0x3f) === 63) { tag = buf.toString('latin1', at, at + 4); at += 4; }
+ const original = readBase128(buf, at);
+ if (!original) return null;
+ at = original.next;
+ // glyf/loca are transformed when the version is 0; every other table when it is not.
+ const transformed = tag === 'glyf' || tag === 'loca' ? (flags >> 6) === 0 : (flags >> 6) !== 0;
+ let stored = original.value;
+ if (transformed) {
+ const transform = readBase128(buf, at);
+ if (!transform) return null;
+ at = transform.next;
+ stored = transform.value;
+ }
+ if (tag === 'name') name = { offset, length: stored };
+ offset += stored;
+ }
+ if (!name) return null;
+ const inflated = brotliDecompressSync(buf.subarray(at, at + compressedSize));
+ return inflated.subarray(name.offset, name.offset + name.length);
+}
+
+/** The font's family name, or null when the file is not a font this can read or names none. */
+export function fontFamilyName(buf) {
+ const container = fontContainer(buf);
+ if (!container) return null;
+ // An uploaded file is untrusted: a truncated or corrupt one reads as "no family", never a throw.
+ try {
+ const table = container === 'woff2' ? woff2NameTable(buf) : sfntNameTable(buf);
+ return table ? familyFromNameTable(table) : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/server/lib/fontMetadata.test.js b/server/lib/fontMetadata.test.js
new file mode 100644
index 0000000000..32380f97c2
--- /dev/null
+++ b/server/lib/fontMetadata.test.js
@@ -0,0 +1,30 @@
+/**
+ * Reading a family name out of an uploaded font (#10345): TrueType/OpenType
+ * and WOFF2, preferring the typographic family, and null for anything that is
+ * not a single font, so an upload never throws on a bad file.
+ */
+import { describe, expect, it } from 'vitest';
+import { sfntWithNames, woff2WithNames } from '../services/musicVideo/__fontFixture.js';
+import { fontContainer, fontFamilyName } from './fontMetadata.js';
+
+describe('fontFamilyName', () => {
+ const names = [[1, 1, 'Example Mac Name'], [3, 1, 'Example Sans Light'], [3, 16, 'Example Sans']];
+
+ it('reads the typographic family, preferring it over the style-linked one', () => {
+ expect(fontFamilyName(sfntWithNames(names))).toBe('Example Sans');
+ expect(fontFamilyName(sfntWithNames([[1, 1, 'Plain Family']]))).toBe('Plain Family');
+ });
+
+ it('reads the name table out of a WOFF2 container', () => {
+ expect(fontContainer(woff2WithNames(names))).toBe('woff2');
+ expect(fontFamilyName(woff2WithNames(names))).toBe('Example Sans');
+ });
+
+ it('answers null for files that are not a readable single font', () => {
+ expect(fontFamilyName(Buffer.from('not a font at all, just text'))).toBeNull();
+ expect(fontFamilyName(Buffer.from('ttcf\0\0\0\0\0\0\0\0\0\0\0\0'))).toBeNull(); // a collection
+ expect(fontFamilyName(sfntWithNames(names).subarray(0, 30))).toBeNull(); // truncated
+ expect(fontFamilyName(woff2WithNames(names).subarray(0, 60))).toBeNull(); // corrupt brotli stream
+ expect(fontFamilyName(null)).toBeNull();
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index c83468a7f7..18a5eb9b53 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -199,6 +199,8 @@ export * from './grok.js';
export * from './falVideoModels.js';
export * from './filmStyleGrammars.js';
export * from './grokVideoClip.js';
+export * from './fontMetadata.js';
+export * from './musicVideoCoverOverlay.js';
export * from './musicVideoShotTiming.js';
export * from './reactorStartingFrame.js';
export * from './reactorVideoClip.js';
diff --git a/server/lib/musicVideoCoverOverlay.js b/server/lib/musicVideoCoverOverlay.js
new file mode 100644
index 0000000000..7c0c2e90e2
--- /dev/null
+++ b/server/lib/musicVideoCoverOverlay.js
@@ -0,0 +1,256 @@
+/**
+ * Music Video cover lettering, as a pure function of a song's cover design.
+ *
+ * The design vocabulary (`COVER_DESIGN_OPTIONS`), the normalizer that accepts
+ * any stored design, and `coverOverlaySvg`, which lays the song title and
+ * artist tag out as one SVG. Pure and dependency-free so the server render
+ * (coverArtCompose.js, through sharp/librsvg) and the client's live Lettering
+ * preview run the SAME layout code; they differ only in who measures the text.
+ */
+
+export const COVER_ART_SIZE = 3000;
+
+// The vocabulary a design is written in (the drafting prompt offers exactly these).
+export const COVER_DESIGN_OPTIONS = Object.freeze({
+ layout: ['bottom-left', 'bottom-center', 'top-left', 'top-center', 'center', 'vertical-left'],
+ typeface: ['sans', 'condensed', 'serif', 'mono'],
+ weight: ['light', 'regular', 'bold', 'black'],
+ letterCase: ['upper', 'lower', 'as-written'],
+ scale: ['small', 'medium', 'large'],
+ backdrop: ['none', 'fade', 'band', 'box'],
+ tagStyle: ['plain', 'boxed', 'none'],
+ titleStyle: ['fill', 'outline', 'stencil'],
+ tagLayout: ['opposite-corner', 'with-title'],
+});
+
+export const DEFAULT_COVER_DESIGN = Object.freeze({
+ layout: 'bottom-left', typeface: 'sans', weight: 'bold', letterCase: 'upper', scale: 'medium',
+ tracking: 0.02, titleColor: '#ffffff', accentColor: '#ffffff', backdrop: 'fade', tagStyle: 'plain', rule: false,
+ titleStyle: 'fill', tagLayout: 'opposite-corner',
+});
+
+// A typeface the director uploaded is written `font:<id>` in a design.
+export const CUSTOM_TYPEFACE_PREFIX = 'font:';
+export const customTypeface = (fontId) => `${CUSTOM_TYPEFACE_PREFIX}${fontId}`;
+
+// Font stacks: the first face a Mac has, then what a Linux install has. `width`
+// is the average advance per character as a fraction of the font size.
+const FACES = {
+ sans: { family: "'Helvetica Neue','Helvetica','Arial','DejaVu Sans',sans-serif", width: 0.6 },
+ condensed: { family: "'Futura Condensed ExtraBold','Avenir Next Condensed','Impact','Arial Narrow','DejaVu Sans Condensed',sans-serif", width: 0.46 },
+ serif: { family: "'Didot','Bodoni 72','Georgia','DejaVu Serif',serif", width: 0.58 },
+ mono: { family: "'Menlo','SF Mono','DejaVu Sans Mono',monospace", width: 0.62 },
+};
+const WEIGHTS = { light: 300, regular: 400, bold: 700, black: 900 };
+const SCALES = { small: 0.075, medium: 0.11, large: 0.16 };
+const HEX = /^#[0-9a-f]{6}$/i;
+const ASCENT = 0.78;
+const MARGIN = 0.065;
+const TAG_SCALE = 0.03;
+
+const escapeXml = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[c]);
+const pick = (value, list, fallback) => (list.includes(value) ? value : fallback);
+const n = (v) => v.toFixed(1);
+
+/** Every typeface a design may name: the built-in four, then each uploaded font. */
+export const coverTypefaceChoices = (fonts = []) => [...COVER_DESIGN_OPTIONS.typeface, ...fonts.map((f) => customTypeface(f.id))];
+
+/** The face a typeface names: its font stack (CSS) and average advance. An unknown one is the default's. */
+function faceFor(typeface, fonts = []) {
+ if (FACES[typeface]) return FACES[typeface];
+ const custom = typeof typeface === 'string' && typeface.startsWith(CUSTOM_TYPEFACE_PREFIX)
+ ? fonts.find((f) => customTypeface(f.id) === typeface) : null;
+ return custom ? { family: `'${custom.family}',sans-serif`, width: custom.width } : FACES[DEFAULT_COVER_DESIGN.typeface];
+}
+
+/**
+ * A design with every field valid: unknown or missing values take the default's.
+ * `fonts` (the uploaded typefaces, `{ id, family, width }`) is what lets a
+ * `font:<id>` typeface through; a design naming a font that is gone, or one
+ * normalized without the list, falls back to the default typeface.
+ */
+export function normalizeCoverDesign(design = {}, { fonts = [] } = {}) {
+ const d = design && typeof design === 'object' ? design : {};
+ const out = {};
+ for (const [key, list] of Object.entries(COVER_DESIGN_OPTIONS)) {
+ out[key] = pick(d[key], key === 'typeface' ? coverTypefaceChoices(fonts) : list, DEFAULT_COVER_DESIGN[key]);
+ }
+ const tracking = Number(d.tracking);
+ out.tracking = Number.isFinite(tracking) ? Math.min(0.3, Math.max(-0.05, tracking)) : DEFAULT_COVER_DESIGN.tracking;
+ out.titleColor = HEX.test(d.titleColor || '') ? d.titleColor : DEFAULT_COVER_DESIGN.titleColor;
+ out.accentColor = HEX.test(d.accentColor || '') ? d.accentColor : DEFAULT_COVER_DESIGN.accentColor;
+ out.rule = d.rule === true;
+ return out;
+}
+
+const caseOf = (text, letterCase) => (letterCase === 'upper' ? text.toUpperCase() : letterCase === 'lower' ? text.toLowerCase() : text);
+
+/** Break the title into at most 3 lines of about `perLine` characters, at word boundaries. */
+function titleLines(title, perLine) {
+ const words = String(title || '').replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
+ const lines = [];
+ for (const word of words) {
+ const last = lines[lines.length - 1];
+ if (last !== undefined && last.length + 1 + word.length <= perLine) lines[lines.length - 1] = `${last} ${word}`;
+ else lines.push(word);
+ }
+ return lines.length > 3 ? [...lines.slice(0, 2), lines.slice(2).join(' ')] : lines;
+}
+
+/**
+ * How a text is set: its font stack, weight and letter spacing (in em). The
+ * server's width probe and the client's canvas measure read this, and
+ * `fontAttrs` writes the same values as SVG attributes, so a measured width
+ * is the width the overlay draws.
+ */
+export function coverFontSpec(d, kind, fonts = []) {
+ const weight = WEIGHTS[d.weight];
+ return kind === 'tag'
+ ? { family: faceFor(d.typeface, fonts).family, weight: Math.max(400, weight - 200), trackingEm: 0.08 }
+ : { family: faceFor(d.typeface, fonts).family, weight, trackingEm: d.tracking };
+}
+
+export function fontAttrs(d, kind, fontSize, fonts = []) {
+ const { family, weight, trackingEm } = coverFontSpec(d, kind, fonts);
+ return `font-family="${escapeFamilyStack(family)}" font-weight="${weight}" letter-spacing="${n(trackingEm * fontSize)}"`;
+}
+
+// A stack's own quotes are SVG-safe inside a double-quoted attribute; only a custom family's name can carry markup.
+const escapeFamilyStack = (family) => family.replace(/[<>&"]/g, (c) => escapeXml(c));
+
+/** The title's lines as the design sets them (one line when it runs up the edge). */
+export function titleLinesFor(title, d, size, fonts = []) {
+ const text = caseOf(String(title || '').trim(), d.letterCase);
+ if (d.layout === 'vertical-left') return [text];
+ const room = size * (1 - 2 * MARGIN);
+ return titleLines(text, Math.max(6, Math.round(room / (size * SCALES[d.scale] * faceFor(d.typeface, fonts).width * (1 + d.tracking)))));
+}
+
+/** The artist tag as the design sets it: cased, trimmed, empty when the design has none. */
+export const tagTextFor = (tag, d) => (d.tagStyle === 'none' ? '' : caseOf(String(tag || '').trim().slice(0, 24), d.letterCase));
+
+// A stencil cuts each line with one thin gap at mid-height (never under 0.2% of the canvas, so a small title still shows it); `strips` are `[x, y, w, h]` in canvas space.
+const stencilGap = (fontSize, size) => Math.max(fontSize * 0.05, size * 0.002);
+const stencilMask = (size, strips) => `<mask id="stencil" maskUnits="userSpaceOnUse" x="0" y="0" width="${size}" height="${size}"><rect width="${size}" height="${size}" fill="#fff"/>${strips.map(([x, y, w, h]) => `<rect x="${n(x)}" y="${n(y)}" width="${n(w)}" height="${n(h)}" fill="#000"/>`).join('')}</mask>`;
+
+/** The fill/stroke that paints the title's glyphs for its `titleStyle`. */
+const inkFor = (d, fontSize) => (d.titleStyle === 'outline'
+ ? `fill="none" stroke="${d.titleColor}" stroke-width="${n(Math.max(2, fontSize * 0.035))}" stroke-linejoin="round"`
+ : `fill="${d.titleColor}"`);
+
+/**
+ * The title block: lines, size and where it sits, plus whatever the design
+ * puts behind it. `widthOf(text)` is the text's rendered width at a 1px font
+ * size (measured by the caller, since the face a stack resolves to varies by
+ * machine); without it the face's average advance stands in. A tag set
+ * `with-title` is part of the block, so the backdrop and the margins hold it;
+ * `tagSpot` says where it goes.
+ */
+function titleParts(title, d, size, widthOf, fonts, tagText) {
+ const face = faceFor(d.typeface, fonts);
+ const margin = size * MARGIN;
+ const room = size - 2 * margin;
+ const parts = [];
+ const defs = [];
+ const lines = titleLinesFor(title, d, size, fonts);
+ const unitW = (line) => widthOf?.(line) ?? line.length * face.width * (1 + d.tracking);
+ const unitWidest = Math.max(0.001, ...lines.map(unitW));
+ const stencil = d.titleStyle === 'stencil';
+ const text = (attrs, body, strips, cut) => {
+ parts.push(`<text ${attrs}>${escapeXml(body)}</text>`);
+ if (stencil) strips.push(cut);
+ };
+ const strips = [];
+
+ if (d.layout === 'vertical-left') {
+ // One line reading bottom to top along the left edge.
+ const fontSize = Math.min(size * SCALES[d.scale], room / unitWidest);
+ if (d.backdrop !== 'none') {
+ parts.push(`<rect x="0" y="0" width="${n(margin * 2 + fontSize)}" height="${size}" fill="${d.backdrop === 'band' ? d.accentColor : '#000'}" fill-opacity="${d.backdrop === 'band' ? 1 : 0.6}"/>`);
+ }
+ const attrs = `transform="translate(${n(margin + fontSize * ASCENT)} ${n(size - margin)}) rotate(-90)" ${fontAttrs(d, 'title', fontSize, fonts)} ${inkFor(d, fontSize)} font-size="${n(fontSize)}"`;
+ text(attrs, lines[0], strips, [margin + fontSize * ASCENT * 0.5, 0, stencilGap(fontSize, size), size]);
+ if (stencil) { defs.push(stencilMask(size, strips)); parts.splice(parts.length - 1, 1, `<g mask="url(#stencil)">${parts[parts.length - 1]}</g>`); }
+ return { parts, defs, tagSpot: null };
+ }
+
+ const center = d.layout.endsWith('center');
+ const atTop = d.layout.startsWith('top');
+ // As large as the design's scale allows; a long title shrinks to fit.
+ const fontSize = Math.min(size * SCALES[d.scale], room / unitWidest);
+ const lineH = fontSize * 1.08;
+ const textH = lineH * (lines.length - 1) + fontSize * ASCENT;
+ // The tag sits under the title (and under its rule, when the rule is below it).
+ const ruleBelow = d.rule && (atTop || d.layout === 'center');
+ const tagFs = size * TAG_SCALE;
+ const tagGap = fontSize * (ruleBelow ? 0.6 : 0.3);
+ const reserve = tagText ? tagGap + tagFs * 1.45 : 0;
+ const blockH = textH + reserve;
+ const widest = Math.min(room, unitWidest * fontSize);
+ const x = center ? size / 2 : margin;
+ const left = center ? (size - widest) / 2 : margin;
+ const top = atTop ? margin + size * 0.06 : d.layout === 'center' ? (size - blockH) / 2 : size - margin - blockH;
+
+ if (d.backdrop === 'fade' && d.layout !== 'center') {
+ defs.push(`<linearGradient id="fade" x1="0" y1="${atTop ? 1 : 0}" x2="0" y2="${atTop ? 0 : 1}"><stop offset="0" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity="0.7"/></linearGradient>`);
+ const h = blockH + margin * 3;
+ parts.push(`<rect x="0" y="${n(atTop ? 0 : size - h)}" width="${size}" height="${n(h)}" fill="url(#fade)"/>`);
+ } else if (d.backdrop === 'band') {
+ const pad = fontSize * 0.35;
+ parts.push(`<rect x="0" y="${n(top - pad)}" width="${size}" height="${n(blockH + pad * 2)}" fill="${d.accentColor}"/>`);
+ } else if (d.backdrop === 'box' || (d.backdrop === 'fade' && d.layout === 'center')) {
+ const pad = fontSize * 0.4;
+ parts.push(`<rect x="${n(left - pad)}" y="${n(top - pad)}" width="${n(widest + pad * 2)}" height="${n(blockH + pad * 2)}" fill="#000" fill-opacity="0.65"/>`);
+ }
+ if (d.rule) {
+ const ry = atTop ? top + textH + fontSize * 0.35 : top - fontSize * 0.35;
+ parts.push(`<rect x="${n(left)}" y="${n(ry)}" width="${n(widest)}" height="${n(size * 0.004)}" fill="${d.accentColor}"/>`);
+ }
+ const ink = `${fontAttrs(d, 'title', fontSize, fonts)} ${inkFor(d, fontSize)}`;
+ const titleStart = parts.length;
+ lines.forEach((line, i) => {
+ const baseline = top + fontSize * ASCENT + i * lineH;
+ text(`x="${n(x)}" y="${n(baseline)}" ${ink} font-size="${n(fontSize)}" text-anchor="${center ? 'middle' : 'start'}"`, line, strips, [0, baseline - fontSize * ASCENT * 0.5, size, stencilGap(fontSize, size)]);
+ });
+ if (stencil) {
+ defs.push(stencilMask(size, strips));
+ parts.splice(titleStart, parts.length - titleStart, `<g mask="url(#stencil)">${parts.slice(titleStart).join('')}</g>`);
+ }
+ const tagSpot = tagText ? { x, anchor: center ? 'middle' : 'start', baseline: top + textH + tagGap + tagFs * 1.05 } : null;
+ return { parts, defs, tagSpot };
+}
+
+/** The artist tag, small: under the title, or at the edge across from it. */
+function tagParts(tagText, d, size, widthOf, fonts, spot) {
+ if (!tagText) return [];
+ const margin = size * MARGIN;
+ const fs = size * TAG_SCALE;
+ const w = (widthOf?.(tagText) ?? tagText.length * faceFor(d.typeface, fonts).width * 1.08) * fs;
+ const center = d.layout.endsWith('center') && d.layout !== 'center';
+ const anchor = spot ? spot.anchor : center ? 'middle' : 'end';
+ const tx = spot ? spot.x : center ? size / 2 : size - margin;
+ const baseline = spot ? spot.baseline : d.layout.startsWith('top') ? size - margin : margin + fs * ASCENT;
+ const font = `${fontAttrs(d, 'tag', fs, fonts)} font-size="${n(fs)}" text-anchor="${anchor}"`;
+ if (d.tagStyle !== 'boxed') return [`<text x="${n(tx)}" y="${n(baseline)}" ${font} fill="${d.accentColor}">${escapeXml(tagText)}</text>`];
+ const pad = fs * 0.5;
+ const bx = anchor === 'end' ? tx - w - pad : anchor === 'start' ? tx - pad : tx - w / 2 - pad;
+ return [
+ `<rect x="${n(bx)}" y="${n(baseline - fs * 1.05)}" width="${n(w + pad * 2)}" height="${n(fs * 1.45)}" fill="${d.accentColor}"/>`,
+ `<text x="${n(tx)}" y="${n(baseline)}" ${font} fill="#111">${escapeXml(tagText)}</text>`,
+ ];
+}
+
+/**
+ * The overlay as SVG: the song's title and artist tag, laid out by its design.
+ * `widths` is `{ title(text), tag(text) }`, each a text's width at a 1px font
+ * size, or null to lay out by the faces' average advance; `fonts` is the
+ * uploaded typefaces.
+ */
+export function coverOverlaySvg({ title, tag = '', design, size = COVER_ART_SIZE, widths = null, fonts = [] }) {
+ const d = normalizeCoverDesign(design, { fonts });
+ const tagText = tagTextFor(tag, d);
+ const withTitle = d.tagLayout === 'with-title' && d.layout !== 'vertical-left';
+ const { parts, defs, tagSpot } = titleParts(title, d, size, widths?.title, fonts, withTitle ? tagText : '');
+ const tagSvg = tagParts(tagText, d, size, widths?.tag, fonts, withTitle ? tagSpot : null);
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${defs.length ? `<defs>${defs.join('')}</defs>` : ''}${[...parts, ...tagSvg].join('')}</svg>`;
+}
diff --git a/server/lib/musicVideoCoverOverlay.test.js b/server/lib/musicVideoCoverOverlay.test.js
new file mode 100644
index 0000000000..6fcbf6c6c0
--- /dev/null
+++ b/server/lib/musicVideoCoverOverlay.test.js
@@ -0,0 +1,56 @@
+/**
+ * Cover lettering layout (#10345): a design stored before the treatments
+ * existed lays out exactly as before, and each new treatment changes only what
+ * it names. Pure SVG-string assertions; the real render is in
+ * services/musicVideo/coverArt.test.js.
+ */
+import { describe, expect, it } from 'vitest';
+import { coverOverlaySvg, DEFAULT_COVER_DESIGN, normalizeCoverDesign } from './musicVideoCoverOverlay.js';
+
+const SONG = { title: 'Example Song', tag: 'Example Artist', size: 1000 };
+// The first y a <text> is drawn at, per text content.
+const textY = (svg, content) => Number(new RegExp(`<text[^>]* y="([\\d.]+)"[^>]*>${content}</text>`).exec(svg)?.[1]);
+
+describe('cover design normalization', () => {
+ it('reads a design stored before titleStyle and tagLayout existed as the default treatment', () => {
+ const legacy = { layout: 'top-left', typeface: 'serif', weight: 'light', letterCase: 'lower', scale: 'large', tracking: 0.1, titleColor: '#112233', accentColor: '#445566', backdrop: 'band', tagStyle: 'boxed', rule: true };
+ expect(normalizeCoverDesign(legacy)).toEqual({ ...legacy, titleStyle: 'fill', tagLayout: 'opposite-corner' });
+ expect(normalizeCoverDesign({})).toEqual(DEFAULT_COVER_DESIGN);
+ expect(coverOverlaySvg({ ...SONG, design: legacy })).toBe(coverOverlaySvg({ ...SONG, design: { ...legacy, titleStyle: 'fill', tagLayout: 'opposite-corner' } }));
+ });
+
+ it('accepts an uploaded typeface only while that font exists', () => {
+ const fonts = [{ id: 'example-font', family: 'Example Font', width: 0.5 }];
+ expect(normalizeCoverDesign({ typeface: 'font:example-font' }, { fonts }).typeface).toBe('font:example-font');
+ expect(normalizeCoverDesign({ typeface: 'font:example-font' }).typeface).toBe('sans');
+ expect(normalizeCoverDesign({ typeface: 'font:other' }, { fonts }).typeface).toBe('sans');
+ // The layout wraps by the font's measured width, and names its family.
+ const svg = coverOverlaySvg({ ...SONG, design: { typeface: 'font:example-font' }, fonts });
+ expect(svg).toContain(`font-family="'Example Font',sans-serif"`);
+ });
+});
+
+describe('cover lettering treatments', () => {
+ it('draws an outline title hollow, and a stencil title through a mask that cuts every line', () => {
+ const outline = coverOverlaySvg({ ...SONG, design: { titleStyle: 'outline', titleColor: '#ff0000' } });
+ expect(outline).toMatch(/<text[^>]*fill="none" stroke="#ff0000"/);
+ expect(outline).not.toContain('<mask');
+
+ const stencil = coverOverlaySvg({ ...SONG, title: 'Example Song With A Longer Name', design: { titleStyle: 'stencil', scale: 'large' } });
+ expect(stencil).toContain('<g mask="url(#stencil)">');
+ const cuts = stencil.match(/<mask[\s\S]*?<\/mask>/)[0].match(/fill="#000"/g);
+ expect(cuts.length).toBeGreaterThan(1); // one cut per title line
+ });
+
+ it('sets the artist tag under the title when asked, inside the margin, instead of across the cover', () => {
+ const apart = coverOverlaySvg({ ...SONG, design: { layout: 'bottom-left', tagLayout: 'opposite-corner' } });
+ const together = coverOverlaySvg({ ...SONG, design: { layout: 'bottom-left', tagLayout: 'with-title' } });
+ // Apart: the tag is up at the top edge, far from the title. Together: it sits just below the title, above the bottom margin.
+ expect(textY(apart, 'EXAMPLE ARTIST')).toBeLessThan(textY(apart, 'EXAMPLE SONG'));
+ expect(textY(together, 'EXAMPLE ARTIST')).toBeGreaterThan(textY(together, 'EXAMPLE SONG'));
+ expect(textY(together, 'EXAMPLE ARTIST')).toBeLessThan(1000 * (1 - 0.065));
+ // A cover with no artist tag has nothing to reserve room for: the title does not move.
+ const alone = coverOverlaySvg({ ...SONG, tag: '', design: { layout: 'bottom-left', tagLayout: 'with-title' } });
+ expect(textY(alone, 'EXAMPLE SONG')).toBe(textY(apart, 'EXAMPLE SONG'));
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 57058fcbc6..5c3873f827 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1,5 +1,6 @@
import { MUSIC_VIDEO_MEDIA_MODES } from './musicVideoMediaPolicy.js';
import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';
+import { COVER_DESIGN_OPTIONS } from './musicVideoCoverOverlay.js';
/**
* Music Video production mode — Zod schemas + shared enums (issue #1760, Phase 1).
*
@@ -702,6 +703,27 @@ export const musicVideoCoverArtDesignSchema = z.object({
providerId: z.string().min(1).max(200).optional(),
model: z.string().min(1).max(200).optional(),
}).strict();
+// #10345: the Lettering controls. A design is every COVER_DESIGN_OPTIONS field
+// plus tracking, colors and the rule; any subset is a patch over the song's
+// current design. `typeface` is a free string here (a built-in name or a
+// `font:<id>` for an uploaded font) and is resolved against the uploaded fonts
+// when the design is normalized.
+const coverHex = z.string().regex(/^#[0-9a-f]{6}$/i);
+const coverDesignFields = Object.fromEntries(Object.entries(COVER_DESIGN_OPTIONS)
+ .map(([key, list]) => [key, key === 'typeface' ? z.string().min(1).max(60) : z.enum(list)]));
+export const musicVideoCoverDesignSchema = z.object({
+ ...coverDesignFields,
+ tracking: z.number().min(-0.05).max(0.3),
+ titleColor: coverHex,
+ accentColor: coverHex,
+ rule: z.boolean(),
+}).partial().strict();
+export const musicVideoCoverDesignSaveSchema = z.object({ design: musicVideoCoverDesignSchema }).strict();
+export const musicVideoArtistStyleSaveSchema = z.object({
+ name: z.string().trim().min(1).max(60),
+ design: musicVideoCoverDesignSchema,
+}).strict();
+export const musicVideoArtistStyleDeleteSchema = z.object({ name: z.string().trim().min(1).max(60) }).strict();
export const musicVideoCoverArtGenerateSchema = z.object({
notes: z.string().max(1500).optional(),
reference: z.object({ kind: z.literal('image'), filename: z.string().min(1).max(300) }).strict().optional(),
diff --git a/server/lib/paths.js b/server/lib/paths.js
index fd685334cb..360c82ac51 100644
--- a/server/lib/paths.js
+++ b/server/lib/paths.js
@@ -102,6 +102,9 @@ export const PATHS = {
voiceProfiles: join(INSTALL_ROOT, 'data/voice-profiles'),
videos: join(INSTALL_ROOT, 'data/videos'),
videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),
+ // Music Video cover lettering (#10345): typefaces the director uploaded (.ttf/.otf/.woff2)
+ // plus their index. Machine-local; included in normal data backups.
+ coverFonts: join(INSTALL_ROOT, 'data/cover-fonts'),
imageThumbnails: join(INSTALL_ROOT, 'data/image-thumbnails'),
// Sprite Manager (issue #2895): per-record asset trees
// (sprites/<id>/{reference,walk,runs,runtime,atlas}/...). Records live in
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 3d629925d3..805d619a15 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -48,6 +48,9 @@ import {
musicVideoPublishThumbnailSchema,
musicVideoCoverArtComposeSchema,
musicVideoCoverArtGenerateSchema,
+ musicVideoCoverDesignSaveSchema,
+ musicVideoArtistStyleSaveSchema,
+ musicVideoArtistStyleDeleteSchema,
musicVideoCoverArtDesignSchema,
musicVideoPublishTargetSchema,
musicVideoPublishPrepareSchema,
@@ -129,6 +132,8 @@ import { suggestSocialCuts } from '../services/musicVideo/socialCuts.js';
import { getActivePublishKitBuild, startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';
import { preparePublishDraft, discardPublishDraft, listPublishDrafts, recordPublishPost } from '../services/musicVideo/publish/index.js';
import { getPublishPlatforms, updatePublishPlatforms, publishHistory } from '../services/musicVideo/publish/platforms.js';
+import { listArtistStyles, saveArtistStyle, removeArtistStyle } from '../services/musicVideo/publish/artistStyles.js';
+import { addCoverFont, coverFontPath, listCoverFonts, MAX_COVER_FONT_BYTES, removeCoverFont } from '../services/musicVideo/coverFonts.js';
import {
getDependencyImpact,
startDependencyRepair,
@@ -945,6 +950,14 @@ router.post('/:id/publish-kit/cover-art/design', asyncHandler(async (req, res) =
res.json({ project });
}));
+// #10345: the Lettering controls set the design directly, with no AI call.
+router.put('/:id/publish-kit/cover-art/design', asyncHandler(async (req, res) => {
+ const { design } = validateRequest(musicVideoCoverDesignSaveSchema, req.body ?? {});
+ const { saveCoverDesign } = await import('../services/musicVideo/coverArt.js');
+ const { project } = await saveCoverDesign(req.params.id, design);
+ res.json({ project });
+}));
+
router.post('/:id/publish-kit/cover-art/generate', asyncHandler(async (req, res) => {
const input = validateRequest(musicVideoCoverArtGenerateSchema, req.body || {});
const { generateCoverArtSource } = await import('../services/musicVideo/coverArt.js');
@@ -967,6 +980,46 @@ router.put('/publish/platforms', asyncHandler(async (req, res) => {
res.json({ platforms: await updatePublishPlatforms(patch) });
}));
+// #10345: one saved cover design per artist, and the typefaces the director uploaded.
+router.get('/publish/artist-styles', asyncHandler(async (req, res) => {
+ res.json({ styles: await listArtistStyles() });
+}));
+
+router.put('/publish/artist-styles', asyncHandler(async (req, res) => {
+ const input = validateRequest(musicVideoArtistStyleSaveSchema, req.body ?? {});
+ res.json({ style: await saveArtistStyle(input) });
+}));
+
+router.delete('/publish/artist-styles', asyncHandler(async (req, res) => {
+ const { name } = validateRequest(musicVideoArtistStyleDeleteSchema, req.query);
+ await removeArtistStyle(name);
+ res.json({ ok: true });
+}));
+
+const COVER_FONT_MIME = { ttf: 'font/ttf', otf: 'font/otf', woff2: 'font/woff2' };
+const coverFontUpload = uploadSingle('font', { limits: { fileSize: MAX_COVER_FONT_BYTES } });
+
+router.get('/publish/cover-fonts', asyncHandler(async (req, res) => {
+ res.json({ fonts: await listCoverFonts() });
+}));
+
+router.post('/publish/cover-fonts', coverFontUpload, asyncHandler(async (req, res) => {
+ if (!req.file) throw new ServerError('No font file uploaded (multipart field "font")', { status: 400, code: 'VALIDATION_ERROR' });
+ const font = await addCoverFont({ tempPath: req.file.path, originalName: req.file.originalname }).finally(() => unlink(req.file.path).catch(() => {}));
+ res.status(201).json({ font, fonts: await listCoverFonts() });
+}));
+
+router.get('/publish/cover-fonts/:fontId/file', asyncHandler(async (req, res) => {
+ const found = await coverFontPath(req.params.fontId);
+ if (!found) throw new ServerError('Font not found', { status: 404, code: 'NOT_FOUND' });
+ res.type(COVER_FONT_MIME[found.font.ext]).sendFile(found.path);
+}));
+
+router.delete('/publish/cover-fonts/:fontId', asyncHandler(async (req, res) => {
+ await removeCoverFont(req.params.fontId);
+ res.json({ fonts: await listCoverFonts() });
+}));
+
// Record a post made by hand, or rate one: its link, reception and notes.
router.put('/:id/publish/posts/:target', asyncHandler(async (req, res) => {
const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);
diff --git a/server/routes/musicVideoCoverLettering.test.js b/server/routes/musicVideoCoverLettering.test.js
new file mode 100644
index 0000000000..140538ef7d
--- /dev/null
+++ b/server/routes/musicVideoCoverLettering.test.js
@@ -0,0 +1,143 @@
+/**
+ * Cover lettering controls (#10345), through the real router, the real
+ * multipart parser and the real stores: uploading a typeface (accepted only
+ * once the renderer can set text in it), a song's lettering saved straight from
+ * the controls, and a saved style per artist. The renderer itself is faked
+ * here (its widths stand in for fontconfig/CoreText); the real render is
+ * exercised in services/musicVideo/coverArt.test.js.
+ */
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import express from 'express';
+import { rmSync } from 'fs';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+
+const ROOT = () => lazyTempDataRoot('mv-cover-lettering-route-test-');
+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));
+// Settings in memory: the artist styles live in `musicVideoPublishing`.
+let stored = {};
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => stored),
+ updateSettingsWith: vi.fn(async (mutate) => { stored = await mutate(stored); return stored; }),
+}));
+
+const { default: musicVideoRoutes } = await import('./musicVideo.js');
+const projects = await import('../services/musicVideo/projects.js');
+const fonts = await import('../services/musicVideo/coverFonts.js');
+const { sfntFont } = await import('../services/musicVideo/__fontFixture.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/music-video', musicVideoRoutes);
+app.use(errorMiddleware);
+
+// A renderer where a font "loads" when its family is one this fake knows: the
+// probe string then measures differently from a missing family's fallback.
+const RENDERABLE = ['Example Sans'];
+const fakeSharp = (input) => {
+ const chain = {
+ trim: () => chain,
+ png: () => chain,
+ toBuffer: async (opts) => {
+ if (!opts?.resolveWithObject) return Buffer.alloc(0);
+ const svg = Buffer.isBuffer(input) ? input.toString() : '';
+ return { info: { width: RENDERABLE.some((family) => svg.includes(`'${family}'`)) ? 1500 : 1000 } };
+ },
+ };
+ return chain;
+};
+
+async function upload(name, body) {
+ const form = new FormData();
+ form.append('font', new Blob([body], { type: 'application/octet-stream' }), name);
+ const encoded = new Request('http://localhost/', { method: 'POST', body: form });
+ return request(app).post('/api/music-video/publish/cover-fonts')
+ .set('content-type', encoded.headers.get('content-type'))
+ .send(Buffer.from(await encoded.arrayBuffer()));
+}
+
+beforeEach(() => {
+ stored = {};
+ rmSync(join(ROOT(), 'cover-fonts'), { recursive: true, force: true });
+ rmSync(join(ROOT(), 'music-video-projects.json'), { force: true });
+ fonts.__setCoverFontDepsForTests({ sharp: async () => fakeSharp, mirrorDir: null, waitMs: 0 });
+});
+afterAll(cleanupTempDataRoots);
+
+describe('uploaded cover typefaces', () => {
+ it('accepts a font the renderer can set, lists it with its measured width, serves the file, and removes it', async () => {
+ const res = await upload('ExampleSans-Regular.ttf', sfntFont('Example Sans'));
+ expect(res.status).toBe(201);
+ expect(res.body.font).toMatchObject({ id: 'example-sans', family: 'Example Sans', ext: 'ttf' });
+ // 1500 / 100px probe units over the 27-character probe string.
+ expect(res.body.font.width).toBeCloseTo(15 / 27, 2);
+ expect((await request(app).get('/api/music-video/publish/cover-fonts')).body.fonts.map((f) => f.id)).toEqual(['example-sans']);
+
+ const file = await request(app).get('/api/music-video/publish/cover-fonts/example-sans/file');
+ expect(file.status).toBe(200);
+ expect(file.headers['content-type']).toContain('font/ttf');
+
+ // The same family again replaces it under the same id, so designs naming it keep working.
+ const again = await upload('ExampleSans-Regular-v2.ttf', sfntFont('Example Sans'));
+ expect(again.body.fonts.map((f) => f.id)).toEqual(['example-sans']);
+
+ const removed = await request(app).delete('/api/music-video/publish/cover-fonts/example-sans');
+ expect(removed.body.fonts).toEqual([]);
+ expect((await request(app).get('/api/music-video/publish/cover-fonts/example-sans/file')).status).toBe(404);
+ });
+
+ it('refuses a file that is not a font, a font the renderer cannot set, and the wrong extension', async () => {
+ expect((await upload('notes.ttf', 'just some text, not a font')).status).toBe(422);
+ const unusable = await upload('Unrenderable.otf', sfntFont('Unrenderable Face'));
+ expect(unusable.status).toBe(422);
+ expect(unusable.body.code).toBe('COVER_FONT_UNUSABLE');
+ expect((await upload('Example.exe', sfntFont('Example Sans'))).status).toBe(400);
+ // Nothing was kept from the refused uploads.
+ expect((await request(app).get('/api/music-video/publish/cover-fonts')).body.fonts).toEqual([]);
+ });
+});
+
+describe('lettering saved from the controls', () => {
+ it('saves a partial design over the song, validates it, and lets an uploaded font through by id', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ const put = (body) => request(app).put(`/api/music-video/${id}/publish-kit/cover-art/design`).send(body);
+
+ const saved = await put({ design: { layout: 'center', titleStyle: 'stencil', tagLayout: 'with-title', titleColor: '#ff8800' } });
+ expect(saved.status).toBe(200);
+ expect(saved.body.project.publishKit.coverArt.design).toMatchObject({ layout: 'center', titleStyle: 'stencil', tagLayout: 'with-title', titleColor: '#ff8800', typeface: 'sans' });
+
+ expect((await put({ design: { titleStyle: 'confetti' } })).status).toBe(400);
+ expect((await put({ design: { titleColor: 'orange' } })).status).toBe(400);
+ expect((await put({ design: { unknown: true } })).status).toBe(400);
+
+ await upload('ExampleSans-Regular.ttf', sfntFont('Example Sans'));
+ const withFont = await put({ design: { typeface: 'font:example-sans' } });
+ expect(withFont.body.project.publishKit.coverArt.design).toMatchObject({ typeface: 'font:example-sans', titleStyle: 'stencil' });
+ });
+});
+
+describe('artist styles', () => {
+ it('saves one design per artist (name case aside), lists them, applies from the list, and removes one', async () => {
+ const put = (body) => request(app).put('/api/music-video/publish/artist-styles').send(body);
+ const first = await put({ name: 'Example Artist', design: { layout: 'top-left', typeface: 'serif', titleStyle: 'outline' } });
+ expect(first.status).toBe(200);
+ expect(first.body.style).toMatchObject({ key: 'example artist', name: 'Example Artist', design: { layout: 'top-left', typeface: 'serif', titleStyle: 'outline' } });
+
+ await put({ name: 'EXAMPLE artist', design: { layout: 'center' } }); // same artist: replaces
+ await put({ name: 'Another Example', design: { weight: 'light' } });
+ const listed = (await request(app).get('/api/music-video/publish/artist-styles')).body.styles;
+ expect(listed.map((s) => s.name)).toEqual(['Another Example', 'EXAMPLE artist']);
+ expect(listed[1].design).toMatchObject({ layout: 'center', typeface: 'sans' }); // a full design, not a patch
+
+ // Platform settings saved beside the styles are untouched by them.
+ stored = { ...stored, musicVideoPublishing: { ...stored.musicVideoPublishing, platforms: { x: { enabled: true, account: 'example' } } } };
+ await put({ name: 'Third Example', design: {} });
+ expect(stored.musicVideoPublishing.platforms.x).toEqual({ enabled: true, account: 'example' });
+
+ expect((await request(app).delete('/api/music-video/publish/artist-styles?name=another%20example')).status).toBe(200);
+ expect((await request(app).delete('/api/music-video/publish/artist-styles?name=another%20example')).status).toBe(404);
+ expect((await put({ name: '', design: {} })).status).toBe(400);
+ });
+});
diff --git a/server/services/musicVideo/__fontFixture.js b/server/services/musicVideo/__fontFixture.js
new file mode 100644
index 0000000000..831b91e24c
--- /dev/null
+++ b/server/services/musicVideo/__fontFixture.js
@@ -0,0 +1,51 @@
+/**
+ * Tiny font files for tests (#10345): a `name` table wrapped in a bare sfnt or
+ * WOFF2 container. Enough for the family-name reader and the upload path; they
+ * carry no glyphs, so nothing renders from them (the suites fake the renderer).
+ */
+import { brotliCompressSync } from 'zlib';
+
+// A `name` table with the given [platformID, nameID, text] records (UTF-16BE on platform 3, latin1 on 1).
+function nameTable(records) {
+ const strings = records.map(([platform, , text]) => (platform === 3 ? Buffer.from(text, 'utf16le').swap16() : Buffer.from(text, 'latin1')));
+ const header = Buffer.alloc(6 + records.length * 12);
+ header.writeUInt16BE(records.length, 2);
+ header.writeUInt16BE(header.length, 4);
+ let offset = 0;
+ records.forEach(([platform, nameId], i) => {
+ const at = 6 + i * 12;
+ header.writeUInt16BE(platform, at);
+ header.writeUInt16BE(nameId, at + 6);
+ header.writeUInt16BE(strings[i].length, at + 8);
+ header.writeUInt16BE(offset, at + 10);
+ offset += strings[i].length;
+ });
+ return Buffer.concat([header, ...strings]);
+}
+
+function sfnt(name) {
+ const dir = Buffer.alloc(12 + 16);
+ dir.writeUInt32BE(0x00010000, 0);
+ dir.writeUInt16BE(1, 4);
+ dir.write('name', 12, 'latin1');
+ dir.writeUInt32BE(28, 20);
+ dir.writeUInt32BE(name.length, 24);
+ return Buffer.concat([dir, name]);
+}
+
+function woff2(name, { flavor = 0x00010000 } = {}) {
+ const compressed = brotliCompressSync(name);
+ const header = Buffer.alloc(48);
+ header.write('wOF2', 0, 'latin1');
+ header.writeUInt32BE(flavor, 4);
+ header.writeUInt16BE(1, 12);
+ header.writeUInt32BE(compressed.length, 20);
+ // One table: registered tag index 5 ('name'), no transform, length as UIntBase128 (< 128 here).
+ return Buffer.concat([header, Buffer.from([5, name.length]), compressed]);
+}
+
+/** A minimal TrueType file whose family is `family`. */
+export const sfntFont = (family) => sfnt(nameTable([[3, 1, family]]));
+/** The same name records ([platformID, nameID, text]) as a bare sfnt, and inside a WOFF2 container. */
+export const sfntWithNames = (records) => sfnt(nameTable(records));
+export const woff2WithNames = (records) => woff2(nameTable(records));
diff --git a/server/services/musicVideo/coverArt.js b/server/services/musicVideo/coverArt.js
index b72351202a..8645937ced 100644
--- a/server/services/musicVideo/coverArt.js
+++ b/server/services/musicVideo/coverArt.js
@@ -28,6 +28,7 @@ import { safeUnder } from '../../lib/ffmpeg.js';
import { resolveGalleryImage } from '../../lib/pathSafety.js';
import { trimTo } from '../../lib/textUtils.js';
import { composeCoverArt, normalizeCoverDesign } from './coverArtCompose.js';
+import { listCoverFonts, registerCoverFonts } from './coverFonts.js';
import { buildCoverDesignPrompt, parseCoverDesign } from './coverArtDesign.js';
import { musicVideoEvents } from './events.js';
import { getProject, mutateProjectRecord } from './projects.js';
@@ -50,6 +51,9 @@ const defaults = {
withStyle: async (...args) => (await import('./styleReferences.js')).withMusicVideoStyle(...args),
jobStatus: async (jobId) => (await import('../mediaJobQueue/index.js')).getJob(jobId)?.status || null,
runner: async () => import('../promptRunner.js'),
+ fonts: listCoverFonts,
+ registerFonts: registerCoverFonts,
+ artistStyle: async (name) => (await import('./publish/artistStyles.js')).artistStyleFor(name),
};
let deps = { ...defaults };
export function __setCoverArtDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }
@@ -131,8 +135,10 @@ export async function composeProjectCoverArt(projectId, { source = null, title,
};
if (next.lettering && !next.title) throw coverError(422, 'VALIDATION_ERROR', 'Give the cover a title');
await ensureDir(PATHS.videoThumbnails);
+ const fonts = await deps.fonts();
+ await deps.registerFonts(fonts);
const filename = `cover-${String(projectId).slice(3, 11)}-${randomUUID().slice(0, 8)}.jpg`;
- await deps.compose({ ...next, design: art.design || null, source: path, out: safeUnder(PATHS.videoThumbnails, filename) });
+ await deps.compose({ ...next, design: art.design || null, fonts, source: path, out: safeUnder(PATHS.videoThumbnails, filename) });
// The JPEG is written in place; the row that first names it commits under a backup lease (#9982).
const out = await withBackupAssetPublication(() => writeCoverArt(projectId, () => ({
...next, filename, composedAt: new Date().toISOString(), lastError: null,
@@ -156,9 +162,12 @@ export async function designCoverArt(projectId, { direction = '', providerId = n
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
if (!provider) throw coverError(503, 'NO_PROVIDER', 'No AI provider is available to design the cover');
const previous = art.design ? { design: art.design, imagePrompt: art.imagePrompt || '' } : null;
- const prompt = buildCoverDesignPrompt(project, { direction: trimTo(direction, 1500), previous });
+ const fonts = await deps.fonts();
+ // A fresh design starts from the artist's saved style, when they have one.
+ const artistStyle = previous ? null : await deps.artistStyle(art.tag ?? await defaultTag()).catch(() => null);
+ const prompt = buildCoverDesignPrompt(project, { direction: trimTo(direction, 1500), previous, artistStyle: artistStyle?.design || null, fonts });
const { text } = await runPromptThroughProvider({ provider, model: selectedModel, prompt, source: 'music-video-cover-design' });
- const drafted = parseCoverDesign(text);
+ const drafted = parseCoverDesign(text, { fonts });
if (!drafted) throw coverError(502, 'COVER_DESIGN_UNPARSEABLE', 'The cover design came back without a usable design. Try again or another model');
const out = await writeCoverArt(projectId, () => ({
design: drafted.design,
@@ -175,6 +184,25 @@ export async function designCoverArt(projectId, { direction = '', providerId = n
return { project: out.project };
}
+/**
+ * Set the song's lettering from the Lettering controls (or an artist style):
+ * `patch` is any subset of the design, merged over the current one, with no AI
+ * call. A song with a cover is recomposed at once, so the saved JPEG matches
+ * what the preview showed.
+ */
+export async function saveCoverDesign(projectId, patch = {}) {
+ const project = await requireProject(projectId);
+ const art = projectCoverArt(project);
+ const fonts = await deps.fonts();
+ const design = normalizeCoverDesign({ ...normalizeCoverDesign(art.design, { fonts }), ...patch }, { fonts });
+ const out = await writeCoverArt(projectId, () => ({ design, lastError: null }));
+ console.log(`🖼️ Music Video cover art ${String(projectId).slice(3, 11)}: lettering set (${design.layout}, ${design.typeface}, ${design.titleStyle})`);
+ // Like a restyle, setting the lettering puts it back on a cover that was used bare.
+ if (art.source) return composeProjectCoverArt(projectId, { lettering: true });
+ publish(projectId, out.project);
+ return { project: out.project };
+}
+
// Where the photo should stay calm, so the title reads over it.
const QUIET_AREA = {
'bottom-left': 'the lower left', 'bottom-center': 'the bottom', 'top-left': 'the upper left',
diff --git a/server/services/musicVideo/coverArt.test.js b/server/services/musicVideo/coverArt.test.js
index abc181d4ba..fac50ea1e2 100644
--- a/server/services/musicVideo/coverArt.test.js
+++ b/server/services/musicVideo/coverArt.test.js
@@ -30,18 +30,23 @@ const DRAFT = { imagePrompt: 'Example image prompt: a grainy profile in blue lig
const runPrompt = vi.fn(async () => ({ text: JSON.stringify(DRAFT) }));
const defaultRoute = vi.fn(async () => ({ mode: 'grok', model: null }));
+const depsFor = () => ({
+ compose, enqueue, defaultRoute, jobStatus,
+ runner: async () => ({ resolveProviderAndModel: async () => ({ provider: { id: 'example-provider' }, selectedModel: null }), runPromptThroughProvider: runPrompt }),
+ getSettings: async () => ({}),
+ getPlatforms: async () => ({ distrokid: { enabled: true, account: 'Example Artist' } }),
+ imageParams: async (_settings, route, common) => ({ ...common, provider: route.mode }),
+ withStyle: async (_project, params) => params,
+ fonts: async () => [],
+ registerFonts: async () => {},
+ artistStyle: async () => null,
+});
+
beforeEach(() => {
compose.mockClear(); enqueue.mockReset(); enqueue.mockResolvedValue({ jobId: 'job-example' }); defaultRoute.mockClear();
jobStatus.mockReset(); jobStatus.mockResolvedValue('queued');
runPrompt.mockReset(); runPrompt.mockResolvedValue({ text: JSON.stringify(DRAFT) });
- cover.__setCoverArtDepsForTests({
- compose, enqueue, defaultRoute, jobStatus,
- runner: async () => ({ resolveProviderAndModel: async () => ({ provider: { id: 'example-provider' }, selectedModel: null }), runPromptThroughProvider: runPrompt }),
- getSettings: async () => ({}),
- getPlatforms: async () => ({ distrokid: { enabled: true, account: 'Example Artist' } }),
- imageParams: async (_settings, route, common) => ({ ...common, provider: route.mode }),
- withStyle: async (_project, params) => params,
- });
+ cover.__setCoverArtDepsForTests(depsFor());
});
async function projectWithThumbnail(name = 'Example Song') {
@@ -191,6 +196,47 @@ describe('release cover art', () => {
expect(compose.mock.calls.at(-1)[0].lettering).toBe(true);
});
+ it('sets the lettering from direct controls with no AI call, merging over the current design and re-setting the cover', async () => {
+ const { id, thumb } = await projectWithThumbnail();
+ await cover.composeProjectCoverArt(id, { source: { kind: 'thumbnail', filename: thumb } });
+ await cover.designCoverArt(id);
+ runPrompt.mockClear();
+ compose.mockClear();
+
+ const art = (await cover.saveCoverDesign(id, { scale: 'small', titleColor: '#ff8800', titleStyle: 'outline' })).project.publishKit.coverArt;
+ expect(runPrompt).not.toHaveBeenCalled();
+ // Only what the controls named changed; the rest of the drafted look stays.
+ expect(art.design).toMatchObject({ layout: 'top-center', typeface: 'serif', scale: 'small', titleColor: '#ff8800', titleStyle: 'outline', tagLayout: 'opposite-corner' });
+ expect(compose).toHaveBeenCalledTimes(1);
+ expect(compose.mock.calls[0][0].design).toMatchObject({ scale: 'small', titleStyle: 'outline' });
+
+ // An uploaded font is accepted by its id while it exists, and falls back to the default typeface once it is gone.
+ const example = { id: 'example-font', family: 'Example Font', ext: 'ttf', width: 0.5 };
+ cover.__setCoverArtDepsForTests({ ...depsFor(), fonts: async () => [example] });
+ expect((await cover.saveCoverDesign(id, { typeface: 'font:example-font' })).project.publishKit.coverArt.design.typeface).toBe('font:example-font');
+ expect(compose.mock.calls.at(-1)[0].fonts).toEqual([example]);
+ cover.__setCoverArtDepsForTests({ ...depsFor(), fonts: async () => [] });
+ expect((await cover.saveCoverDesign(id, { scale: 'large' })).project.publishKit.coverArt.design.typeface).toBe('sans');
+ });
+
+ it("starts a song's first design from the artist's saved style, offers uploaded fonts, and leaves an existing design's adjustment alone", async () => {
+ const { id } = await projectWithThumbnail();
+ const style = { key: 'example artist', name: 'Example Artist', design: { layout: 'bottom-center', typeface: 'mono', weight: 'black', titleColor: '#aabbcc' } };
+ const artistStyle = vi.fn(async () => style);
+ cover.__setCoverArtDepsForTests({ ...depsFor(), artistStyle, fonts: async () => [{ id: 'example-font', family: 'Example Font', ext: 'ttf', width: 0.5 }] });
+ await cover.designCoverArt(id);
+ expect(artistStyle).toHaveBeenCalledWith('Example Artist');
+ const first = runPrompt.mock.calls.at(-1)[0].prompt;
+ expect(first).toContain("The artist's saved style");
+ expect(first).toContain('"titleColor":"#aabbcc"');
+ expect(first).toContain('"font:example-font"');
+
+ artistStyle.mockClear();
+ await cover.designCoverArt(id, { direction: 'warmer' });
+ expect(artistStyle).not.toHaveBeenCalled();
+ expect(runPrompt.mock.calls.at(-1)[0].prompt).not.toContain("The artist's saved style");
+ });
+
it("queues on the install's own default image generator, never a fixed one", async () => {
const { id } = await projectWithThumbnail();
cover.__setCoverArtDepsForTests({
diff --git a/server/services/musicVideo/coverArtCompose.js b/server/services/musicVideo/coverArtCompose.js
index 8516c84278..68e6a3413a 100644
--- a/server/services/musicVideo/coverArtCompose.js
+++ b/server/services/musicVideo/coverArtCompose.js
@@ -4,181 +4,29 @@
* artist set by code from the song's own cover design: where the title sits,
* its typeface, weight, case, spacing and colors, and what sits behind it.
* Each song gets its own design (coverArt.js drafts it from the song); this
- * module only renders one. Lettering is set here rather than drawn by an image
- * model, so it stays crisp.
+ * module only renders one: the layout itself is lib/musicVideoCoverOverlay.js
+ * (shared with the client's live Lettering preview), and this adds the
+ * measuring and the sharp composite. Lettering is set here rather than drawn
+ * by an image model, so it stays crisp.
*
* Pure apart from the files it reads and writes; `sharp` is loaded lazily so
* the many suites that reach the publish services never pay for it.
*/
-export const COVER_ART_SIZE = 3000;
+import {
+ COVER_ART_SIZE, coverOverlaySvg, fontAttrs, normalizeCoverDesign, tagTextFor, titleLinesFor,
+} from '../../lib/musicVideoCoverOverlay.js';
-// The vocabulary a design is written in (the drafting prompt offers exactly these).
-export const COVER_DESIGN_OPTIONS = Object.freeze({
- layout: ['bottom-left', 'bottom-center', 'top-left', 'top-center', 'center', 'vertical-left'],
- typeface: ['sans', 'condensed', 'serif', 'mono'],
- weight: ['light', 'regular', 'bold', 'black'],
- letterCase: ['upper', 'lower', 'as-written'],
- scale: ['small', 'medium', 'large'],
- backdrop: ['none', 'fade', 'band', 'box'],
- tagStyle: ['plain', 'boxed', 'none'],
-});
-
-export const DEFAULT_COVER_DESIGN = Object.freeze({
- layout: 'bottom-left', typeface: 'sans', weight: 'bold', letterCase: 'upper', scale: 'medium',
- tracking: 0.02, titleColor: '#ffffff', accentColor: '#ffffff', backdrop: 'fade', tagStyle: 'plain', rule: false,
-});
-
-// Font stacks: the first face a Mac has, then what a Linux install has. `width`
-// is the average advance per character as a fraction of the font size.
-const FACES = {
- sans: { family: "'Helvetica Neue','Helvetica','Arial','DejaVu Sans',sans-serif", width: 0.6 },
- condensed: { family: "'Futura Condensed ExtraBold','Avenir Next Condensed','Impact','Arial Narrow','DejaVu Sans Condensed',sans-serif", width: 0.46 },
- serif: { family: "'Didot','Bodoni 72','Georgia','DejaVu Serif',serif", width: 0.58 },
- mono: { family: "'Menlo','SF Mono','DejaVu Sans Mono',monospace", width: 0.62 },
-};
-const WEIGHTS = { light: 300, regular: 400, bold: 700, black: 900 };
-const SCALES = { small: 0.075, medium: 0.11, large: 0.16 };
-const HEX = /^#[0-9a-f]{6}$/i;
-const ASCENT = 0.78;
-const MARGIN = 0.065;
+export {
+ COVER_ART_SIZE, COVER_DESIGN_OPTIONS, DEFAULT_COVER_DESIGN, coverOverlaySvg, normalizeCoverDesign,
+} from '../../lib/musicVideoCoverOverlay.js';
const escapeXml = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[c]);
-const pick = (value, list, fallback) => (list.includes(value) ? value : fallback);
-const n = (v) => v.toFixed(1);
-
-/** A design with every field valid: unknown or missing values take the default's. */
-export function normalizeCoverDesign(design = {}) {
- const d = design && typeof design === 'object' ? design : {};
- const out = {};
- for (const [key, list] of Object.entries(COVER_DESIGN_OPTIONS)) out[key] = pick(d[key], list, DEFAULT_COVER_DESIGN[key]);
- const tracking = Number(d.tracking);
- out.tracking = Number.isFinite(tracking) ? Math.min(0.3, Math.max(-0.05, tracking)) : DEFAULT_COVER_DESIGN.tracking;
- out.titleColor = HEX.test(d.titleColor || '') ? d.titleColor : DEFAULT_COVER_DESIGN.titleColor;
- out.accentColor = HEX.test(d.accentColor || '') ? d.accentColor : DEFAULT_COVER_DESIGN.accentColor;
- out.rule = d.rule === true;
- return out;
-}
-
-const caseOf = (text, letterCase) => (letterCase === 'upper' ? text.toUpperCase() : letterCase === 'lower' ? text.toLowerCase() : text);
-
-/** Break the title into at most 3 lines of about `perLine` characters, at word boundaries. */
-function titleLines(title, perLine) {
- const words = String(title || '').replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
- const lines = [];
- for (const word of words) {
- const last = lines[lines.length - 1];
- if (last !== undefined && last.length + 1 + word.length <= perLine) lines[lines.length - 1] = `${last} ${word}`;
- else lines.push(word);
- }
- return lines.length > 3 ? [...lines.slice(0, 2), lines.slice(2).join(' ')] : lines;
-}
-
-const titleFont = (d, fontSize) => `font-family="${FACES[d.typeface].family}" font-weight="${WEIGHTS[d.weight]}" letter-spacing="${n(d.tracking * fontSize)}"`;
-const tagFont = (d, fontSize) => `font-family="${FACES[d.typeface].family}" font-weight="${Math.max(400, WEIGHTS[d.weight] - 200)}" letter-spacing="${n(0.08 * fontSize)}"`;
-
-/** The title's lines as the design sets them (one line when it runs up the edge). */
-function titleLinesFor(title, d, size) {
- const text = caseOf(String(title || '').trim(), d.letterCase);
- if (d.layout === 'vertical-left') return [text];
- const room = size * (1 - 2 * MARGIN);
- return titleLines(text, Math.max(6, Math.round(room / (size * SCALES[d.scale] * FACES[d.typeface].width * (1 + d.tracking)))));
-}
-
-/**
- * The title block: lines, size and where it sits, plus whatever the design
- * puts behind it. `widthOf(text)` is the text's rendered width at a 1px font
- * size (measured by composeCoverArt, since the face a stack resolves to varies
- * by machine); without it the face's average advance stands in.
- */
-function titleParts(title, d, size, widthOf) {
- const face = FACES[d.typeface];
- const margin = size * MARGIN;
- const room = size - 2 * margin;
- const ink = (fontSize) => `${titleFont(d, fontSize)} fill="${d.titleColor}"`;
- const parts = [];
- const defs = [];
- const lines = titleLinesFor(title, d, size);
- const unitW = (line) => widthOf?.(line) ?? line.length * face.width * (1 + d.tracking);
- const unitWidest = Math.max(0.001, ...lines.map(unitW));
-
- if (d.layout === 'vertical-left') {
- // One line reading bottom to top along the left edge.
- const text = lines[0];
- const fontSize = Math.min(size * SCALES[d.scale], room / unitWidest);
- if (d.backdrop !== 'none') {
- parts.push(`<rect x="0" y="0" width="${n(margin * 2 + fontSize)}" height="${size}" fill="${d.backdrop === 'band' ? d.accentColor : '#000'}" fill-opacity="${d.backdrop === 'band' ? 1 : 0.6}"/>`);
- }
- parts.push(`<text transform="translate(${n(margin + fontSize * ASCENT)} ${n(size - margin)}) rotate(-90)" ${ink(fontSize)} font-size="${n(fontSize)}">${escapeXml(text)}</text>`);
- return { parts, defs };
- }
-
- const center = d.layout.endsWith('center');
- const atTop = d.layout.startsWith('top');
- // As large as the design's scale allows; a long title shrinks to fit.
- const fontSize = Math.min(size * SCALES[d.scale], room / unitWidest);
- const lineH = fontSize * 1.08;
- const blockH = lineH * (lines.length - 1) + fontSize * ASCENT;
- const widest = Math.min(room, unitWidest * fontSize);
- const x = center ? size / 2 : margin;
- const left = center ? (size - widest) / 2 : margin;
- const top = atTop ? margin + size * 0.06 : d.layout === 'center' ? (size - blockH) / 2 : size - margin - blockH;
-
- if (d.backdrop === 'fade' && d.layout !== 'center') {
- defs.push(`<linearGradient id="fade" x1="0" y1="${atTop ? 1 : 0}" x2="0" y2="${atTop ? 0 : 1}"><stop offset="0" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity="0.7"/></linearGradient>`);
- const h = blockH + margin * 3;
- parts.push(`<rect x="0" y="${n(atTop ? 0 : size - h)}" width="${size}" height="${n(h)}" fill="url(#fade)"/>`);
- } else if (d.backdrop === 'band') {
- const pad = fontSize * 0.35;
- parts.push(`<rect x="0" y="${n(top - pad)}" width="${size}" height="${n(blockH + pad * 2)}" fill="${d.accentColor}"/>`);
- } else if (d.backdrop === 'box' || (d.backdrop === 'fade' && d.layout === 'center')) {
- const pad = fontSize * 0.4;
- parts.push(`<rect x="${n(left - pad)}" y="${n(top - pad)}" width="${n(widest + pad * 2)}" height="${n(blockH + pad * 2)}" fill="#000" fill-opacity="0.65"/>`);
- }
- if (d.rule) {
- const ry = atTop ? top + blockH + fontSize * 0.35 : top - fontSize * 0.35;
- parts.push(`<rect x="${n(left)}" y="${n(ry)}" width="${n(widest)}" height="${n(size * 0.004)}" fill="${d.accentColor}"/>`);
- }
- lines.forEach((line, i) => {
- parts.push(`<text x="${n(x)}" y="${n(top + fontSize * ASCENT + i * lineH)}" ${ink(fontSize)} font-size="${n(fontSize)}" text-anchor="${center ? 'middle' : 'start'}">${escapeXml(line)}</text>`);
- });
- return { parts, defs };
-}
-
-/** The artist tag, small, at the edge across from the title. */
-const tagTextFor = (tag, d) => (d.tagStyle === 'none' ? '' : caseOf(String(tag || '').trim().slice(0, 24), d.letterCase));
-
-function tagParts(tag, d, size, widthOf) {
- const text = tagTextFor(tag, d);
- if (!text) return [];
- const margin = size * MARGIN;
- const fs = size * 0.03;
- const w = (widthOf?.(text) ?? text.length * FACES[d.typeface].width * 1.08) * fs;
- const center = d.layout.endsWith('center') && d.layout !== 'center';
- const anchor = center ? 'middle' : 'end';
- const tx = center ? size / 2 : size - margin;
- const baseline = d.layout.startsWith('top') ? size - margin : margin + fs * ASCENT;
- const font = `${tagFont(d, fs)} font-size="${n(fs)}" text-anchor="${anchor}"`;
- if (d.tagStyle !== 'boxed') return [`<text x="${n(tx)}" y="${n(baseline)}" ${font} fill="${d.accentColor}">${escapeXml(text)}</text>`];
- const pad = fs * 0.5;
- const bx = anchor === 'end' ? tx - w - pad : tx - w / 2 - pad;
- return [
- `<rect x="${n(bx)}" y="${n(baseline - fs * 1.05)}" width="${n(w + pad * 2)}" height="${n(fs * 1.45)}" fill="${d.accentColor}"/>`,
- `<text x="${n(tx)}" y="${n(baseline)}" ${font} fill="#111">${escapeXml(text)}</text>`,
- ];
-}
-
-/** The overlay as SVG: the song's title and artist tag, laid out by its design. */
-function coverOverlaySvg({ title, tag = '', design, size = COVER_ART_SIZE, widths = null }) {
- const d = normalizeCoverDesign(design);
- const { parts, defs } = titleParts(title, d, size, widths?.title);
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${defs.length ? `<defs>${defs.join('')}</defs>` : ''}${[...parts, ...tagParts(tag, d, size, widths?.tag)].join('')}</svg>`;
-}
-const PROBE_PX = 100;
+export const PROBE_PX = 100;
/** Each text's rendered width at a 1px font size, by drawing it at PROBE_PX and trimming the empty canvas around it. */
-async function measureWidths(sharp, texts, font) {
+export async function measureWidths(sharp, texts, font) {
const out = new Map();
for (const text of texts) {
if (!text || out.has(text)) continue;
@@ -194,8 +42,10 @@ async function measureWidths(sharp, texts, font) {
* Write `out` (a JPEG): `source` cropped to its largest square at `focusX`
* (0 = left edge, 1 = right edge), scaled to `size`, with the song's design on top.
* `lettering: false` leaves the image bare: a finished cover designed elsewhere.
+ * `fonts` are the uploaded typefaces the design may name (already registered
+ * with the renderer, see coverFonts.js).
*/
-export async function composeCoverArt({ source, out, title, tag = '', design = null, focusX = 0.5, size = COVER_ART_SIZE, lettering = true }, deps = {}) {
+export async function composeCoverArt({ source, out, title, tag = '', design = null, fonts = [], focusX = 0.5, size = COVER_ART_SIZE, lettering = true }, deps = {}) {
const sharp = deps.sharp || (await import('sharp')).default;
// Apply the EXIF orientation first, so the crop is measured on the upright image.
const { data, info } = await sharp(source).rotate().toBuffer({ resolveWithObject: true });
@@ -207,12 +57,12 @@ export async function composeCoverArt({ source, out, title, tag = '', design = n
.extract({ left, top, width: side, height: side })
.resize(size, size, { kernel: 'lanczos3' });
if (lettering) {
- const d = normalizeCoverDesign(design);
+ const d = normalizeCoverDesign(design, { fonts });
const widths = {
- title: await measureWidths(sharp, titleLinesFor(title, d, size), titleFont(d, PROBE_PX)),
- tag: await measureWidths(sharp, [tagTextFor(tag, d)], tagFont(d, PROBE_PX)),
+ title: await measureWidths(sharp, titleLinesFor(title, d, size, fonts), fontAttrs(d, 'title', PROBE_PX, fonts)),
+ tag: await measureWidths(sharp, [tagTextFor(tag, d)], fontAttrs(d, 'tag', PROBE_PX, fonts)),
};
- image = image.composite([{ input: Buffer.from(coverOverlaySvg({ title, tag, design: d, size, widths })), top: 0, left: 0 }]);
+ image = image.composite([{ input: Buffer.from(coverOverlaySvg({ title, tag, design: d, size, widths, fonts })), top: 0, left: 0 }]);
}
await image
.jpeg({ quality: 92, chromaSubsampling: '4:4:4' })
diff --git a/server/services/musicVideo/coverArtDesign.js b/server/services/musicVideo/coverArtDesign.js
index 0b7ba2703f..4bad1ff09a 100644
--- a/server/services/musicVideo/coverArtDesign.js
+++ b/server/services/musicVideo/coverArtDesign.js
@@ -10,16 +10,18 @@
import { extractJson } from '../../lib/jsonExtract.js';
import { fenceBlock } from '../../lib/promptFencing.js';
import { trimTo } from '../../lib/textUtils.js';
-import { COVER_DESIGN_OPTIONS, normalizeCoverDesign } from './coverArtCompose.js';
+import { COVER_DESIGN_OPTIONS, coverTypefaceChoices, customTypeface, normalizeCoverDesign } from '../../lib/musicVideoCoverOverlay.js';
const lyricsText = (project) => (project?.lyricCues || []).map((c) => (typeof c?.text === 'string' ? c.text.trim() : '')).filter(Boolean).join('\n');
/**
* The drafting prompt. With a `previous` design the direction is an
* adjustment to it; without one it is a fresh design (the direction, when
- * given, steering it).
+ * given, steering it). `artistStyle` (the artist's saved design) is where a
+ * fresh design starts, so a run of singles reads as a set; `fonts` are the
+ * typefaces the director uploaded, which the design may use.
*/
-export function buildCoverDesignPrompt(project, { direction = '', previous = null } = {}) {
+export function buildCoverDesignPrompt(project, { direction = '', previous = null, artistStyle = null, fonts = [] } = {}) {
const castDirection = project?.castAndSets?.direction || {};
const p = castDirection.protagonist || {};
const facts = [
@@ -28,14 +30,19 @@ export function buildCoverDesignPrompt(project, { direction = '', previous = nul
castDirection.look ? `The video's photographic look: ${trimTo(castDirection.look, 600)}` : null,
[p.face, p.hair, p.signature].some(Boolean) ? `The singer: ${trimTo([p.face, p.hair, p.signature].filter(Boolean).join('; '), 600)}` : null,
].filter(Boolean).join('\n');
- const options = Object.entries(COVER_DESIGN_OPTIONS).map(([k, list]) => ` "${k}": one of ${list.map((v) => `"${v}"`).join(', ')}`).join(',\n');
+ const options = Object.entries({ ...COVER_DESIGN_OPTIONS, typeface: coverTypefaceChoices(fonts) })
+ .map(([k, list]) => ` "${k}": one of ${list.map((v) => `"${v}"`).join(', ')}`).join(',\n');
+ const uploaded = fonts.map((f) => `"${customTypeface(f.id)}" is the artist's own typeface ${f.family}`);
return [
'You are the art director for a single\'s cover artwork (the square image Spotify shows). Design a look that is this song\'s own: grow it from the song\'s words and its video\'s world, not from a genre template or another artist\'s cover.',
'The cover is one photograph with the song title and artist name set over it in type. You choose the photo and the type treatment.',
facts,
fenceBlock('Lyrics', lyricsText(project) || '(no lyrics)', 3000),
previous ? fenceBlock('The current design (adjust it; keep what the direction does not change)', JSON.stringify(previous), 3000) : '',
+ !previous && artistStyle ? fenceBlock("The artist's saved style (start from it so their singles read as a set; change only what this song calls for)", JSON.stringify(artistStyle), 3000) : '',
direction ? fenceBlock(previous ? "The artist's adjustment" : "The artist's direction", direction, 1500) : '',
+ 'Title treatments: "outline" sets hollow letters, "stencil" cuts each line with a thin gap. Artist name: "with-title" sets it right under the title, "opposite-corner" puts it at the far edge.',
+ uploaded.length ? `Typefaces: ${uploaded.join('; ')}. Prefer one when it suits the song.` : '',
'Return ONLY a JSON object:',
`{
"imagePrompt": "the cover photograph to generate, in one paragraph: subject, framing, light, palette, texture. Square. No text or lettering in the image. Leave calm space where the title goes.",
@@ -52,11 +59,11 @@ ${options},
}
/** The model's answer as `{ design, imagePrompt, rationale }`, or null when it has no usable design. */
-export function parseCoverDesign(text) {
+export function parseCoverDesign(text, { fonts = [] } = {}) {
const { value } = extractJson(text, { blockType: 'object' });
if (!value || typeof value !== 'object' || !value.design || typeof value.design !== 'object') return null;
return {
- design: normalizeCoverDesign(value.design),
+ design: normalizeCoverDesign(value.design, { fonts }),
imagePrompt: trimTo(typeof value.imagePrompt === 'string' ? value.imagePrompt : '', 1500),
rationale: trimTo(typeof value.rationale === 'string' ? value.rationale : '', 300),
};
diff --git a/server/services/musicVideo/coverFonts.js b/server/services/musicVideo/coverFonts.js
new file mode 100644
index 0000000000..a77dcfe088
--- /dev/null
+++ b/server/services/musicVideo/coverFonts.js
@@ -0,0 +1,184 @@
+/**
+ * Music Video cover lettering: typefaces the director uploads (#10345).
+ *
+ * A font file (.ttf/.otf/.woff2) lives under `data/cover-fonts/` with an index
+ * of `{ id, family, ext, width }`. A design names one as `font:<id>`
+ * (musicVideoCoverOverlay.js). The title is drawn by librsvg through sharp, so
+ * the font has to be known to the renderer's font system, and that differs by
+ * platform: fontconfig platforms take the file through libvips' text-op
+ * `fontfile` hook (adds it to the process-wide config, live), while macOS
+ * renders through CoreText, which only sees fonts in a Fonts folder, so each
+ * font is mirrored into `~/Library/Fonts/PortOS` (picked up by the running
+ * process within a couple of seconds).
+ *
+ * An upload is accepted only after the renderer proves it can set text in the
+ * font: a probe string must measure differently from a missing family. That
+ * probe also yields the font's measured average advance (`width`), which the
+ * layout uses in place of a built-in face's hard-coded one.
+ */
+import { createHash } from 'crypto';
+import { copyFile, readFile, rm, stat, mkdir } from 'fs/promises';
+import { homedir } from 'os';
+import { join } from 'path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { fontContainer, fontFamilyName } from '../../lib/fontMetadata.js';
+import { atomicWrite } from '../../lib/fileCore.js';
+import { readJSONFile } from '../../lib/jsonIo.js';
+import { PATHS } from '../../lib/paths.js';
+import { measureWidths } from './coverArtCompose.js';
+
+export const MAX_COVER_FONT_BYTES = 8 * 1024 * 1024;
+export const MAX_COVER_FONTS = 24;
+const EXTENSIONS = new Set(['ttf', 'otf', 'woff2']);
+const PROBE_TEXT = 'Hamburgefonstiv 0123 Quartz';
+const MISSING_FAMILY = 'zz-portos-no-such-family';
+const POLL_MS = 400;
+
+const defaults = {
+ sharp: async () => (await import('sharp')).default,
+ // macOS only: CoreText reads fonts from a Fonts folder, not from a fontconfig directory.
+ mirrorDir: process.platform === 'darwin' && !process.env.VITEST ? join(homedir(), 'Library', 'Fonts', 'PortOS') : null,
+ waitMs: 6000,
+};
+let deps = { ...defaults };
+export function __setCoverFontDepsForTests(overrides) { deps = { ...defaults, ...overrides }; resetRegistered(); }
+
+const fontError = (status, code, message) => new ServerError(message, { status, code });
+const indexFile = () => join(PATHS.coverFonts, 'fonts.json');
+const fontFile = (font) => join(PATHS.coverFonts, `${font.id}.${font.ext}`);
+const registered = new Set();
+function resetRegistered() { registered.clear(); }
+
+// Every write reads the index fresh and goes through one tail, so two uploads never overwrite each other's row.
+let writeTail = Promise.resolve();
+const serialized = (task) => {
+ const run = writeTail.then(task);
+ writeTail = run.catch(() => {});
+ return run;
+};
+
+const isFont = (v) => v && typeof v === 'object' && typeof v.id === 'string' && typeof v.family === 'string'
+ && EXTENSIONS.has(v.ext) && Number.isFinite(v.width) && v.width > 0;
+
+/** The uploaded typefaces, oldest first: `{ id, family, ext, width, addedAt }`. */
+export async function listCoverFonts() {
+ const stored = await readJSONFile(indexFile(), { fonts: [] }, { allowArray: false });
+ return (Array.isArray(stored?.fonts) ? stored.fonts : []).filter(isFont);
+}
+
+/** A font file's absolute path, or null when `id` names none. */
+export async function coverFontPath(id) {
+ const font = (await listCoverFonts()).find((f) => f.id === id);
+ return font ? { font, path: fontFile(font) } : null;
+}
+
+const slugOf = (family) => family.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'font';
+// A family is written into CSS and XML attributes; keep it to plain name characters.
+const cleanFamily = (family) => family.replace(/[^\p{L}\p{N} ._+-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 60);
+
+/**
+ * Tell the renderer about `fonts`. Idempotent per process. fontconfig
+ * platforms register through libvips; macOS mirrors into the user's Fonts
+ * folder (a missing mirror is rewritten, so a wiped folder heals on the next compose).
+ */
+export async function registerCoverFonts(fonts) {
+ if (!fonts.length) return;
+ if (deps.mirrorDir) {
+ await mkdir(deps.mirrorDir, { recursive: true });
+ for (const font of fonts) {
+ const target = join(deps.mirrorDir, `${font.id}.${font.ext}`);
+ if (!(await stat(target).catch(() => null))) await copyFile(fontFile(font), target);
+ }
+ return;
+ }
+ const sharp = await deps.sharp();
+ for (const font of fonts) {
+ const file = fontFile(font);
+ if (registered.has(file)) continue;
+ await sharp({ text: { text: 'A', fontfile: file, rgba: true } }).png().toBuffer().catch((err) => {
+ console.warn(`⚠️ Cover font ${font.id}: renderer would not take the file (${err.message})`);
+ });
+ registered.add(file);
+ }
+}
+
+const familyAttr = (family) => `font-family="'${family}',sans-serif"`;
+
+/**
+ * The font's average advance per character (fraction of the font size) as the
+ * renderer sets it, once it can: polls until the probe differs from a missing
+ * family's fallback, or `waitMs` runs out (null).
+ */
+async function measureRegistered(sharp, family) {
+ const deadline = Date.now() + deps.waitMs;
+ for (;;) {
+ const [own, fallback] = await Promise.all([
+ measureWidths(sharp, [PROBE_TEXT], familyAttr(family)).then((w) => w(PROBE_TEXT)),
+ measureWidths(sharp, [PROBE_TEXT], familyAttr(MISSING_FAMILY)).then((w) => w(PROBE_TEXT)),
+ ]);
+ if (own && fallback && Math.abs(own - fallback) / fallback > 0.005) return Math.round((own / PROBE_TEXT.length) * 1000) / 1000;
+ if (Date.now() >= deadline) return null;
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
+ }
+}
+
+/**
+ * Accept an uploaded font file (already on disk at `tempPath`). The same
+ * family uploaded again replaces its file, so designs naming it keep working.
+ */
+export async function addCoverFont({ tempPath, originalName = '' }) {
+ const ext = String(originalName).toLowerCase().split('.').pop();
+ if (!EXTENSIONS.has(ext)) throw fontError(400, 'VALIDATION_ERROR', 'Cover fonts must be .ttf, .otf or .woff2 files');
+ const size = (await stat(tempPath)).size;
+ if (size > MAX_COVER_FONT_BYTES) throw fontError(413, 'VALIDATION_ERROR', `That font file is over ${MAX_COVER_FONT_BYTES / 1024 / 1024} MB`);
+ const buffer = await readFile(tempPath);
+ if (!fontContainer(buffer)) throw fontError(422, 'VALIDATION_ERROR', 'That file is not a single-font TrueType, OpenType or WOFF2 file');
+ const stem = String(originalName).replace(/\.[^.]+$/, '');
+ const family = cleanFamily(fontFamilyName(buffer) || stem);
+ if (!family) throw fontError(422, 'VALIDATION_ERROR', 'That font has no usable family name');
+
+ return serialized(async () => {
+ const fonts = await listCoverFonts();
+ const same = fonts.find((f) => f.family.toLowerCase() === family.toLowerCase());
+ if (!same && fonts.length >= MAX_COVER_FONTS) throw fontError(409, 'COVER_FONT_LIMIT', `Remove a font first: at most ${MAX_COVER_FONTS} can be uploaded`);
+ const slug = slugOf(family);
+ const taken = (id) => fonts.some((f) => f.id === id && f !== same);
+ const id = same?.id || (taken(slug) ? `${slug}-${createHash('sha1').update(family).digest('hex').slice(0, 6)}` : slug);
+ const font = { id, family, ext, width: 0, addedAt: new Date().toISOString() };
+ await mkdir(PATHS.coverFonts, { recursive: true });
+ await atomicWrite(fontFile(font), buffer);
+ // The probe runs against what is on disk; a replaced font under the same name keeps its old registration until a restart on fontconfig platforms.
+ registered.delete(fontFile(font));
+ await registerCoverFonts([font]);
+ const measured = await measureRegisteredFont(font);
+ if (!measured) {
+ await rm(fontFile(font), { force: true });
+ if (deps.mirrorDir) await rm(join(deps.mirrorDir, `${font.id}.${font.ext}`), { force: true });
+ throw fontError(422, 'COVER_FONT_UNUSABLE', `This machine's renderer could not set text in "${family}". Try the .ttf or .otf version of the font`);
+ }
+ font.width = measured;
+ // A same-family upload in another format leaves the old file behind otherwise.
+ if (same && same.ext !== ext) await rm(fontFile(same), { force: true });
+ await atomicWrite(indexFile(), { fonts: [...fonts.filter((f) => f !== same), font] });
+ console.log(`🔤 Cover font ${font.id} added (${family}, ${ext})`);
+ return font;
+ });
+}
+
+async function measureRegisteredFont(font) {
+ const sharp = await deps.sharp();
+ return measureRegistered(sharp, font.family);
+}
+
+/** Remove an uploaded font. Designs that name it fall back to the default typeface. */
+export async function removeCoverFont(id) {
+ return serialized(async () => {
+ const fonts = await listCoverFonts();
+ const font = fonts.find((f) => f.id === id);
+ if (!font) throw fontError(404, 'NOT_FOUND', 'Font not found');
+ await atomicWrite(indexFile(), { fonts: fonts.filter((f) => f !== font) });
+ await rm(fontFile(font), { force: true });
+ if (deps.mirrorDir) await rm(join(deps.mirrorDir, `${font.id}.${font.ext}`), { force: true });
+ console.log(`🔤 Cover font ${font.id} removed`);
+ });
+}
diff --git a/server/services/musicVideo/publish/artistStyles.js b/server/services/musicVideo/publish/artistStyles.js
new file mode 100644
index 0000000000..0ce0a33e9c
--- /dev/null
+++ b/server/services/musicVideo/publish/artistStyles.js
@@ -0,0 +1,80 @@
+/**
+ * Music Video artist styles (#10345): one saved cover design per artist.
+ *
+ * A single's lettering is drafted per song, so a run of singles drifts apart
+ * unless the artist's look is kept somewhere. "Save as artist style" stores
+ * the current design here under the artist's name; "Apply artist style" copies
+ * it onto another song, and the cover-design draft for a new song starts from
+ * it. Kept in the server-side publishing settings
+ * (`settings.musicVideoPublishing.artistStyles`, beside `platforms`), so every
+ * browser that opens this install sees the same styles. A song's own tweaks
+ * stay on the song; nothing here changes a cover until it is applied.
+ */
+import { normalizeCoverDesign } from '../../../lib/musicVideoCoverOverlay.js';
+import { ServerError } from '../../../lib/errorHandler.js';
+import { getSettings, updateSettingsWith } from '../../settings.js';
+import { listCoverFonts } from '../coverFonts.js';
+
+const SETTINGS_KEY = 'musicVideoPublishing';
+const MAX_STYLES = 100;
+export const MAX_ARTIST_NAME = 60;
+
+const cleanName = (v) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, MAX_ARTIST_NAME) : '');
+/** The key an artist's style is stored under: their name, case and spacing aside. */
+export const artistStyleKey = (name) => cleanName(name).toLowerCase();
+
+const styleRows = (section) => (section?.artistStyles && typeof section.artistStyles === 'object' && !Array.isArray(section.artistStyles) ? section.artistStyles : {});
+
+const present = (key, row, fonts) => ({
+ key,
+ name: cleanName(row?.name) || key,
+ design: normalizeCoverDesign(row?.design, { fonts }),
+ updatedAt: typeof row?.updatedAt === 'string' ? row.updatedAt : null,
+});
+
+/** Every saved artist style, by name. */
+export async function listArtistStyles() {
+ const [settings, fonts] = await Promise.all([getSettings().catch(() => ({})), listCoverFonts()]);
+ return Object.entries(styleRows(settings?.[SETTINGS_KEY]))
+ .map(([key, row]) => present(key, row, fonts))
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/** The saved style for an artist, or null. */
+export async function artistStyleFor(name) {
+ const key = artistStyleKey(name);
+ return key ? (await listArtistStyles()).find((s) => s.key === key) || null : null;
+}
+
+/** Save (or replace) the style for `name`; resolves the saved style. */
+export async function saveArtistStyle({ name, design }) {
+ const key = artistStyleKey(name);
+ if (!key) throw new ServerError('Name the artist to save a style for', { status: 422, code: 'VALIDATION_ERROR' });
+ const fonts = await listCoverFonts();
+ let saved = null;
+ await updateSettingsWith((current) => {
+ const section = current?.[SETTINGS_KEY] && typeof current[SETTINGS_KEY] === 'object' ? current[SETTINGS_KEY] : {};
+ const styles = { ...styleRows(section) };
+ if (!styles[key] && Object.keys(styles).length >= MAX_STYLES) {
+ throw new ServerError(`Remove an artist style first: at most ${MAX_STYLES} can be saved`, { status: 409, code: 'ARTIST_STYLE_LIMIT' });
+ }
+ styles[key] = { name: cleanName(name), design: normalizeCoverDesign(design, { fonts }), updatedAt: new Date().toISOString() };
+ saved = present(key, styles[key], fonts);
+ return { ...current, [SETTINGS_KEY]: { ...section, artistStyles: styles } };
+ });
+ console.log(`🎨 Music Video artist style saved (${key})`);
+ return saved;
+}
+
+/** Remove an artist's saved style. */
+export async function removeArtistStyle(name) {
+ const key = artistStyleKey(name);
+ let found = false;
+ await updateSettingsWith((current) => {
+ const section = current?.[SETTINGS_KEY] && typeof current[SETTINGS_KEY] === 'object' ? current[SETTINGS_KEY] : {};
+ const { [key]: gone, ...rest } = styleRows(section);
+ found = Boolean(gone);
+ return found ? { ...current, [SETTINGS_KEY]: { ...section, artistStyles: rest } } : current;
+ });
+ if (!found) throw new ServerError('No saved style for that artist', { status: 404, code: 'NOT_FOUND' });
+}