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([issue-10583]): shared kinetic lyric type for composition documents

atomanticagent4c20802b4b8e
diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsx
index e2d9fa47ba..e32dfb4fb9 100644
--- a/client/src/components/musicVideo/SceneCard.jsx
+++ b/client/src/components/musicVideo/SceneCard.jsx
@@ -8,11 +8,14 @@ import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import PerformanceEvidence from './PerformanceEvidence.jsx';
import { planPerformanceRepair } from '../../lib/musicVideoShotTiming.js';
import SceneTakeStrip from './SceneTakeStrip.jsx';
-import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicVideoLayers.js';
+import { MUSIC_VIDEO_LYRIC_ROLES, MUSIC_VIDEO_TEXT_ZONES, MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicVideoLayers.js';
// #8985: what a composed render shows for this scene's span.
const LAYER_LABELS = { footage: 'Footage', still: 'Still image', card: 'Title card', code: 'Code-drawn' };
const STILL_MOVE_LABELS = [['hold', 'Hold'], ['push', 'Push in'], ['pan', 'Pan']];
+// #10583: the shared lyric type's zone and style for this shot (composition documents).
+const TEXT_ZONE_LABELS = { 'lower-left': 'Lower left', 'upper-right': 'Upper right', center: 'Centre', none: 'No lyrics' };
+const LYRIC_ROLE_LABELS = { line: 'Sung line', hook: 'Hook slam', stamp: 'Stamp', data: 'Data caption' };
import {
falSceneTake, grokCoverage, isPerformanceScene, performanceBlockedReason, performanceCapability, planPerformanceWindow, shotSplitLimit,
} from '../../lib/musicVideoShotTiming.js';
@@ -307,6 +310,24 @@ export default function SceneCard({
className="h-8 w-10 min-h-[44px] sm:min-h-0 bg-port-bg border border-port-border rounded" />
</>
)}
+ {documentComposition && (
+ <>
+ <label htmlFor={fieldId('text-zone')}>Lyrics</label>
+ <select id={fieldId('text-zone')} value={scene.textZone || ''} onChange={(e) => applyPatch({ textZone: e.target.value || null })}
+ title="Where the lyric type may sit in this shot, so it stays off the subject"
+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">
+ <option value="">Default zone</option>
+ {MUSIC_VIDEO_TEXT_ZONES.map((value) => <option key={value} value={value}>{TEXT_ZONE_LABELS[value]}</option>)}
+ </select>
+ <label htmlFor={fieldId('lyric-role')} className="sr-only">Lyric style</label>
+ <select id={fieldId('lyric-role')} value={scene.lyricRole || ''} onChange={(e) => applyPatch({ lyricRole: e.target.value || null })}
+ title="The lyric style of the lines sung over this shot"
+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">
+ <option value="">Style from the lyric sheet</option>
+ {MUSIC_VIDEO_LYRIC_ROLES.map((value) => <option key={value} value={value}>{LYRIC_ROLE_LABELS[value]}</option>)}
+ </select>
+ </>
+ )}
</div>
{layer !== 'footage' && !layered && (
<p className="text-[11px] text-port-text-muted">
diff --git a/client/src/components/musicVideo/SceneCard.test.jsx b/client/src/components/musicVideo/SceneCard.test.jsx
index b1bc2acd08..7288284392 100644
--- a/client/src/components/musicVideo/SceneCard.test.jsx
+++ b/client/src/components/musicVideo/SceneCard.test.jsx
@@ -71,3 +71,19 @@ describe('persisted render failure chip (#10154)', () => {
expect(onGenerateVideo).toHaveBeenCalledTimes(1);
});
});
+
+describe('lyric type per shot (#10583)', () => {
+ it('lets a composition-document shot pick its lyric zone and style, and clears back to the defaults', () => {
+ const onSave = vi.fn();
+ const scene = { sceneId: 's1', startSec: 0, endSec: 5, takes: [], textZone: 'upper-right' };
+ const { rerender } = render(<SceneCard scene={scene} index={0} layered onEditLocal={() => {}} onSave={onSave} />);
+ // Only a composition document draws the shared lyric type.
+ expect(screen.queryByLabelText('Lyrics')).toBeNull();
+ rerender(<SceneCard scene={scene} index={0} layered documentComposition onEditLocal={() => {}} onSave={onSave} />);
+ expect(screen.getByLabelText('Lyrics').value).toBe('upper-right');
+ fireEvent.change(screen.getByLabelText('Lyrics'), { target: { value: 'none' } });
+ fireEvent.change(screen.getByLabelText('Lyric style'), { target: { value: 'stamp' } });
+ fireEvent.change(screen.getByLabelText('Lyrics'), { target: { value: '' } });
+ expect(onSave.mock.calls).toEqual([['s1', { textZone: 'none' }], ['s1', { lyricRole: 'stamp' }], ['s1', { textZone: null }]]);
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f30256f103..5366fda69a 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -62,7 +62,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `musicVideoAspect.js` | Re-export of `server/lib/musicVideoAspect.js`: `musicVideoAspect`, `musicVideoFrameGenSize`. Used by `hooks/useMusicVideoSceneMedia.js` so board frames match the project aspect. |
| `musicVideoMotion.js` | Re-export of `server/lib/musicVideoMotion.js` (`MOTION_CONTINUITY_CLAUSE`) for board motion prompts. |
| `musicVideoBatchPlan.js` | Pure helpers for the Music Video missing-frame / missing-clip batches (#10153): `videoBatchPreview` (count + fal estimate summed from `falSceneTake`, unpriced count), `scenesWaitingForFrame`, `videosButtonLabel`, `batchSummary`, `batchActive`, `batchSceneName`. Used by `components/musicVideo/ProjectActionGroups.jsx`. |
-| `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`. |
+| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `MUSIC_VIDEO_TEXT_ZONES` / `MUSIC_VIDEO_LYRIC_ROLES` (#10583 lyric type per shot), `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. |
diff --git a/client/src/lib/musicVideoLayers.js b/client/src/lib/musicVideoLayers.js
index 049fe5347c..5bd0b5d936 100644
--- a/client/src/lib/musicVideoLayers.js
+++ b/client/src/lib/musicVideoLayers.js
@@ -6,6 +6,8 @@
export {
MUSIC_VIDEO_VISUAL_LAYERS,
MUSIC_VIDEO_STILL_MOVES,
+ MUSIC_VIDEO_TEXT_ZONES,
+ MUSIC_VIDEO_LYRIC_ROLES,
isSelfDrawnLayer,
sceneVisualLayer,
sceneHasAuthoredSpan,
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index 32ea57a673..e2ce1ed8e3 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -297,7 +297,7 @@ snapshot freezes (`server/services/musicVideo/documentRender.js`):
{ width, height, fps, frames, durationSec }, song: { durationSec, bpm, beats,
downbeats, sections, words }, lyrics, lyricMarkers, scenes: [{ sceneId,
label, startSec, endSec, shotMode, visualLayer, stillMove, cardText,
- cardColor, lyricText, direction, media: { kind, src, inSec, outSec, fps,
+ cardColor, textZone, lyricRole, lyricText, direction, media: { kind, src, inSec, outSec, fps,
width, height } | null }], textCues, composition: { mode, style, posterSec,
overlay } }`. Load it with `<script src="portos-mv.js">`; the sandbox
refuses `fetch`.
@@ -336,14 +336,52 @@ of the source frame so a frame boundary can never round to the previous one.
The shipped `layered` template (`server/services/musicVideo/documentTemplates/layered/`)
draws each scene's take with a gentle camera move and beat punch-ins, film
-grain and a vignette, a title card for card scenes, subtitles (the subtitle
-text cues, else the timed lyrics), kinetic hero words for cues flagged
-`hero`, and an optional HUD from `composition.overlay` (title lines, a meter
-with keyframes, a ticker, timecode). It declares all three frame sizes. Its
-fonts (IBM Plex Mono, IBM Plex Sans Condensed, Big Shoulders Stencil
-Display) are SIL Open Font License; the licenses ship beside them. Once
-copied into a project the files are the project's to edit — project-specific
-cards belong there, not in the template.
+grain and a vignette, a title card for card scenes, kinetic lyric type (the
+subtitle text cues, else the timed lyrics, plus hook slams for cues flagged
+`hero`) through the shared lyric-type module below, and an optional HUD from
+`composition.overlay` (title lines, a meter with keyframes, a ticker,
+timecode). It declares all three frame sizes. Its fonts (IBM Plex Mono, IBM
+Plex Sans Condensed, Big Shoulders Stencil Display, Archivo) are SIL Open Font
+License; the licenses ship beside them. Once copied into a project the files
+are the project's to edit — project-specific cards belong there, not in the
+template.
+
+### Shared kinetic lyric type (`lyricType.js`)
+
+Any composition document can draw its sung words with one consistent look
+instead of writing its own type engine
+(`server/services/musicVideo/documentTemplates/shared/`):
+
+```js
+import { createLyricType } from './lyricType.js';
+const lyricType = createLyricType(window.PORTOS_MV);
+await lyricType.ready;
+// each frame, after the picture:
+lyricType.draw(ctx, t, { width, height });
+```
+
+Link `lyricType.css` from the page for the bundled faces (Archivo variable
+widths and IBM Plex Mono, OFL licences in `fonts/`). When a stored document
+references `lyricType.js` or `lyricType.css` without shipping them, PortOS adds
+its copies and the faces at the document root; a document's own copy is kept.
+
+Lines come from `PORTOS_MV.lyrics` with their aligned word times (or
+`options.lines`), and every timing is read from the song data. Each line gets
+one of four roles: `line` (default sung line: words rise and fade in on their
+onsets, the line drifts up and fades 0.3s after its last word), `hook` (wide
+caps centred in the zone, each word slams in on its onset, one outline-only
+accent word, cut on the next beat), `stamp` (a three-frame stamp with a small
+tilt, optional strike-through) and `data` (mono HUD caption whose numbers roll;
+at most one per shot). A per-line override or the line's own `role` wins,
+then the shot's `lyricRole`, then the lyric sheet: the line's `lyricMarkers`
+delivery direction (spoken/shouted lines stamp), else its section header
+(choruses, hooks, refrains and drops are hooks), else `line`. Each shot's `textZone` (`lower-left`, `upper-right`,
+`center`, or `none` to keep the shot clear) places the words so they never
+cover the subject. A line never shows before its first word onset, stays at
+least 0.8s, and sung type stays at least 56px at 1080p. Palette tokens
+(`fill`, `ink`, `accent`, `strike`), fonts and an optional ink-boil jitter are
+options. Upgrading a pre-module layered engine adds the module's two tags in
+front of the template's engine tag.
The in-app preview is a self-contained `srcdoc` in an opaque-origin sandbox
with no network: the server inlines the document's scripts, stylesheets and
diff --git a/server/lib/musicVideoLayers.js b/server/lib/musicVideoLayers.js
index 4eade4b96e..c91fa0aca2 100644
--- a/server/lib/musicVideoLayers.js
+++ b/server/lib/musicVideoLayers.js
@@ -21,6 +21,16 @@ export const MUSIC_VIDEO_VISUAL_LAYERS = ['footage', 'still', 'card', 'code'];
export const isSelfDrawnLayer = (layer) => layer === 'card' || layer === 'code';
export const MUSIC_VIDEO_STILL_MOVES = ['hold', 'push', 'pan'];
+/**
+ * Kinetic lyric type per shot (#10583), read by the shared lyricType.js document
+ * module: `textZone` is where the shot's words may sit so they never cover the
+ * subject (`none` keeps the shot clear), and `lyricRole` overrides the role of the
+ * lines sung over it. Both are optional; a shot without them takes the sheet's roles
+ * and the module's default zone.
+ */
+export const MUSIC_VIDEO_TEXT_ZONES = ['lower-left', 'upper-right', 'center', 'none'];
+export const MUSIC_VIDEO_LYRIC_ROLES = ['line', 'hook', 'stamp', 'data'];
+
/**
* Whether a composition honours per-scene layers: a composed render cuts
* stills and cards itself, and a composition document (mode `document`) is
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index a9e4a2dec4..7cc42696c8 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -44,7 +44,7 @@ import { EFFORT_LEVELS } from './providerModels.js';
import { shotActionContractProblem } from './musicVideoActionContract.js';
import { NARRATIVE_EVENT_KINDS } from './musicVideoNarrativeEvents.js';
import { MUSIC_VIDEO_MEDIA } from './musicVideoMediumPlan.js';
-import { MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';
+import { MUSIC_VIDEO_LYRIC_ROLES, MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_TEXT_ZONES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';
import { MUSIC_VIDEO_SHOT_MODES, SOURCE_AUDIO_LIPSYNC } from './musicVideoShotTiming.js';
import {
MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD,
@@ -513,6 +513,9 @@ const sceneLayerFields = {
// #10302: footage that the composition also draws code over; still counts as footage.
codeOverlay: z.boolean().optional(),
cardColor: z.string().regex(/^#[0-9a-f]{6}$/i, 'card color is #rrggbb').nullable().optional(),
+ // #10583: where a composition document's lyric type may sit in this shot, and the role of its lines.
+ textZone: z.enum(MUSIC_VIDEO_TEXT_ZONES).nullable().optional(),
+ lyricRole: z.enum(MUSIC_VIDEO_LYRIC_ROLES).nullable().optional(),
};
// ---- Pre-production treatment (#8980) --------------------------------------
diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.js
index b0aa3367fc..2b1e2768cb 100644
--- a/server/services/musicVideo/compositionDocument.js
+++ b/server/services/musicVideo/compositionDocument.js
@@ -45,6 +45,13 @@ export const DOCUMENT_RESERVED_FILES = Object.freeze(['portos-mv.js', 'song.json
const SEGMENT = /^[A-Za-z0-9_-]{1,100}$/;
const TEMPLATE_ROOT = join(dirname(fileURLToPath(import.meta.url)), 'documentTemplates');
+// The shared kinetic lyric-type module (#10583): lyricType.js, lyricType.css and their OFL faces.
+const SHARED_ROOT = join(TEMPLATE_ROOT, 'shared');
+const LYRIC_TYPE_REF = /\blyricType\.(?:js|css)\b/;
+const LYRIC_TYPE_SCAN_MAX = 2 * 1024 * 1024;
+const LAYERED_ENGINE_TAG = '<script src="engine.js"></script>';
+const LYRIC_TYPE_TAGS = '<link rel="stylesheet" href="lyricType.css">\n'
+ + '<script type="module" src="lyricType.js"></script><!-- portos-allow-hidden-content: the shared PortOS lyric-type module -->\n';
const MIME_TYPES = Object.freeze({
'.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
@@ -143,8 +150,39 @@ function storeVersion(projectId, files, source, options = {}) {
return serializeProject(projectId, () => storeVersionNow(projectId, files, source, options));
}
-async function storeVersionNow(projectId, files, source, { draft = false, verifyCurrent = () => {} } = {}) {
- assertDocumentShape(files.map((file) => file.rel));
+/**
+ * A layered page from before #10583 loads the engine through the template's own
+ * tag; it gains the lyric-type stylesheet and module in front of that tag. A page
+ * that already names lyricType, or loads its engine some other way, is unchanged.
+ */
+function withLyricTypeTags(page) {
+ if (!page.includes(LAYERED_ENGINE_TAG) || LYRIC_TYPE_REF.test(page)) return page;
+ return page.replace(LAYERED_ENGINE_TAG, () => LYRIC_TYPE_TAGS + LAYERED_ENGINE_TAG);
+}
+
+/**
+ * A document that references the shared lyric-type module (lyricType.js / .css)
+ * without shipping it gets PortOS's copy and its faces added at its root, so an
+ * uploaded document never renders without its type. Files the document ships
+ * itself (its own lyricType.js, its own fonts) are kept as they are.
+ */
+async function withSharedLyricType(files) {
+ const rels = new Set(files.map((file) => file.rel));
+ let referenced = false;
+ for (const file of files) {
+ if (!/\.(?:html?|m?js|css)$/i.test(file.rel) || (file.size ?? file.data?.length ?? 0) > LYRIC_TYPE_SCAN_MAX) continue;
+ const text = file.data ? file.data.toString('utf8') : await readFile(file.abs, 'utf8');
+ if (LYRIC_TYPE_REF.test(text)) { referenced = true; break; }
+ }
+ if (!referenced) return files;
+ const { files: shared } = await collectTree(SHARED_ROOT);
+ const missing = shared.filter((file) => !rels.has(file.rel));
+ return missing.length ? [...files, ...missing] : files;
+}
+
+async function storeVersionNow(projectId, inputFiles, source, { draft = false, verifyCurrent = () => {} } = {}) {
+ assertDocumentShape(inputFiles.map((file) => file.rel));
+ const files = await withSharedLyricType(inputFiles);
const initial = await getProject(projectId);
await assertDocumentMediaPolicy(initial, files);
if (!initial) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -323,6 +361,7 @@ export async function stageGeneratedDocument(projectId, generatedFiles, { verify
// Known compatible shipped layered engines. Recognition only;
// customized engines belong to the author and are never silently replaced.
const UPGRADABLE_LAYERED_ENGINES = new Set([
+ 'dc27611ebaa429c28bd467b003495d2a1c7dc0ede73be0cfc28db4b97c964dcf',
'2556a0905a85958b9107cfa75ab0c5bfde167a708e29b511d577065bb530ea58',
'e2267a068c92a3c7dee49db5f3e57caff1ac11aee1312c0d82e28352850aad3b',
'23842766a818fd9820d79ff229eab538cc0edf391992756cbfd14434d525c019',
@@ -332,7 +371,9 @@ const engineDigest = bytes => createHash('sha256').update(bytes.toString('utf8')
/**
* Explicitly adopt the shipped layered engine in a new immutable document.
- * All authored scripts, HTML, fonts and assets retain their exact bytes. The
+ * All authored scripts, HTML, fonts and assets retain their exact bytes, except
+ * that a template-shaped index.html gains the shared lyric-type tags the shipped
+ * engine needs (see below). The
* new pointer invalidates revision-bound render/review evidence naturally.
*/
export function upgradeDocumentEngine(projectId, directory) {
@@ -359,6 +400,12 @@ export function upgradeDocumentEngine(projectId, directory) {
const loaded = await Promise.all(files.map(async file => ({
rel: file.rel, data: file.rel === 'engine.js' ? shipped : await readFile(file.abs),
})));
+ // The shipped engine draws its words with the shared lyricType.js (#10583). A page that
+ // loads the engine through the template's own tag gets the module's two tags in front
+ // of it (storeVersionNow adds the module and its faces); a page that doesn't is the
+ // author's and is left alone.
+ const index = loaded.find(file => file.rel === 'index.html');
+ if (index) index.data = Buffer.from(withLyricTypeTags(index.data.toString('utf8')));
const result = await storeVersionNow(projectId, loaded, project.composition.document.source || { kind: 'directory', name: null }, { verifyCurrent });
return { ...result, changed: true };
});
diff --git a/server/services/musicVideo/compositionDocument.lyricType.test.js b/server/services/musicVideo/compositionDocument.lyricType.test.js
new file mode 100644
index 0000000000..8b033f8f30
--- /dev/null
+++ b/server/services/musicVideo/compositionDocument.lyricType.test.js
@@ -0,0 +1,69 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-lyric-type-'),
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const projects = await import('./projects.js');
+const { importDocumentTemplate, importDocumentDirectory } = await import('./compositionDocument.js');
+
+afterAll(() => cleanupTempDataRoots());
+
+async function listed(document) {
+ const root = join(PATHS.data, document.directory);
+ const out = [];
+ const walk = async (dir, prefix) => {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) await walk(join(dir, entry.name), `${prefix}${entry.name}/`);
+ else out.push(`${prefix}${entry.name}`);
+ }
+ };
+ await walk(root, '');
+ return { root, files: out.sort() };
+}
+
+async function uploaded(name, files) {
+ const dir = join(PATHS.data, 'uploads', name);
+ for (const [rel, body] of Object.entries(files)) {
+ await mkdir(join(dir, rel, '..'), { recursive: true });
+ await writeFile(join(dir, rel), body);
+ }
+ return `uploads/${name}`;
+}
+
+describe('shared lyric-type assets in composition documents', () => {
+ it('ships lyricType.js, its stylesheet and OFL faces with the layered template', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ const { files } = await listed((await importDocumentTemplate(id)).document);
+ expect(files).toEqual(expect.arrayContaining([
+ 'lyricType.js', 'lyricType.css', 'fonts/archivo-variable.woff2', 'fonts/ibm-plex-mono-500.woff2',
+ 'fonts/LICENSE-Archivo.txt', 'fonts/LICENSE-IBM-Plex.txt', 'engine.js', 'index.html',
+ ]));
+ });
+
+ it('adds the module and faces to an uploaded document that imports it, and keeps a document\'s own copy', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ const importing = await importDocumentDirectory(id, await uploaded('imports-it', {
+ 'index.html': '<link rel="stylesheet" href="lyricType.css"><script type="module" src="app/main.js"></script>',
+ 'app/main.js': "import { createLyricType } from '../lyricType.js';\ncreateLyricType(window.PORTOS_MV);\n",
+ }));
+ const { root, files } = await listed(importing.document);
+ expect(files).toEqual(expect.arrayContaining(['lyricType.js', 'lyricType.css', 'fonts/archivo-variable.woff2', 'fonts/LICENSE-Archivo.txt']));
+ expect(await readFile(join(root, 'lyricType.js'), 'utf8')).toContain('export function createLyricType');
+
+ const own = await importDocumentDirectory(id, await uploaded('own-copy', {
+ 'index.html': '<script type="module" src="lyricType.js"></script>',
+ 'lyricType.js': 'export const createLyricType = () => null;\n',
+ }));
+ const kept = await listed(own.document);
+ expect(await readFile(join(kept.root, 'lyricType.js'), 'utf8')).toBe('export const createLyricType = () => null;\n');
+ expect(kept.files).toContain('fonts/archivo-variable.woff2');
+
+ const plain = await importDocumentDirectory(id, await uploaded('no-type', { 'index.html': '<canvas></canvas>' }));
+ expect((await listed(plain.document)).files).toEqual(['index.html']);
+ });
+});
diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.js
index d90966aff4..5869b0ddff 100644
--- a/server/services/musicVideo/documentRender.js
+++ b/server/services/musicVideo/documentRender.js
@@ -11,6 +11,7 @@ import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';
*
* portos-mv.js `window.PORTOS_MV = { project, render, song, lyrics, lyricMarkers,
* scenes, textCues, composition }` — read with a plain <script>,
+ * (scenes carry textZone/lyricRole for the shared lyricType.js),
* no fetch (the sandbox refuses network).
* song.json the same song block the code-rendered mode reads.
* media/ each scene's SELECTED take (video preferred, else its still)
@@ -33,7 +34,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { PATHS } from '../../lib/fileUtils.js';
import { htmlCompositionContractSchemaFor } from '../../lib/validation.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
-import { documentSceneVisualLayer } from '../../lib/musicVideoLayers.js';
+import { documentSceneVisualLayer, MUSIC_VIDEO_LYRIC_ROLES, MUSIC_VIDEO_TEXT_ZONES } from '../../lib/musicVideoLayers.js';
import { musicVideoAspect } from '../../lib/musicVideoAspect.js';
import { documentDirectoryForRender } from './compositionDocument.js';
import { musicVideoSongDocument } from './compositionRender.js';
@@ -175,6 +176,8 @@ export function buildDocumentData(project, { media = new Map(), frame, clock, so
stillMove: typeof scene.stillMove === 'string' ? scene.stillMove : null,
cardText: typeof scene.cardText === 'string' ? scene.cardText : null,
cardColor: typeof scene.cardColor === 'string' ? scene.cardColor : null,
+ textZone: MUSIC_VIDEO_TEXT_ZONES.includes(scene.textZone) ? scene.textZone : null,
+ lyricRole: MUSIC_VIDEO_LYRIC_ROLES.includes(scene.lyricRole) ? scene.lyricRole : null,
lyricText: typeof scene.lyricText === 'string' ? scene.lyricText : null,
visualIntent: typeof scene.visualIntent === 'string' ? scene.visualIntent : null,
direction: sceneDirection(project, scene.sceneId),
diff --git a/server/services/musicVideo/documentTemplates/layered/engine.js b/server/services/musicVideo/documentTemplates/layered/engine.js
index 85050e2798..6c4af81cd1 100644
--- a/server/services/musicVideo/documentTemplates/layered/engine.js
+++ b/server/services/musicVideo/documentTemplates/layered/engine.js
@@ -3,7 +3,8 @@
* Every frame is a pure function of song time t: portosComposition.seek(t)
* draws the scene under t (its selected take, with a gentle camera move and a
* beat punch-in), film grain and a vignette, an optional HUD, and the words
- * (subtitle lyrics, or kinetic hero words for text cues flagged "hero").
+ * (kinetic lyric type from the shared lyricType.js: sung lines, and hook
+ * slams for text cues flagged "hero").
*
* Data: window.PORTOS_MV, written by PortOS as portos-mv.js at render time —
* { project, render, song, lyrics, lyricMarkers, scenes, textCues, composition }.
@@ -247,94 +248,46 @@
function text(str, x, y, font, color, align = 'left') {
ctx.font = font; ctx.fillStyle = color; ctx.textAlign = align; ctx.textBaseline = 'alphabetic'; ctx.fillText(str, x, y);
}
- function wrap(words, maxW, measure) {
- const lines = [[]]; let width = 0;
- for (const w of words) {
- const ww = measure(w);
- if (width + ww > maxW && lines[lines.length - 1].length) { lines.push([]); width = 0; }
- lines[lines.length - 1].push(w); width += ww;
- }
- return lines;
- }
// ---------- words ----------
- const norm = (s) => String(s).toLowerCase().replace(/[’]/g, "'").replace(/[^a-z0-9']/g, '');
- const songWords = (MV.song?.words || []).filter((w) => Number.isFinite(w?.startSec));
- // Kinetic hero words for a text cue: each word lands on its sung time when
- // the aligned lyric words match, else spread across the cue.
- function heroWordsFor(cue) {
- const tokens = String(cue.text).split(/\s+/).filter(Boolean);
- const pool = songWords.filter((w) => w.startSec >= cue.startSec - 0.35 && w.startSec <= cue.endSec + 0.2);
- const out = []; let j = 0;
- for (const token of tokens) {
- const key = norm(token);
- let hit = null;
- for (let k = j; k < pool.length; k++) {
- const p = norm(pool[k].w);
- if (p === key || (key.length > 3 && p.startsWith(key.slice(0, 4)))) { hit = pool[k]; j = k + 1; break; }
- }
- out.push({ w: token.toUpperCase(), t0: hit ? hit.startSec : null });
- }
- if (out.some((w) => w.t0 == null)) {
- const span = Math.max(0.2, (cue.endSec - cue.startSec) * 0.8);
- out.forEach((w, i) => { w.t0 = cue.startSec + (i * span) / Math.max(1, out.length); });
- }
- return out;
- }
+ // The words are drawn by the shared PortOS lyric-type module (lyricType.js, loaded
+ // beside this page): hero text cues are `hook` lines, the director's subtitle cues
+ // (else the lyrics, with their sheet's roles) are sung `line`s. Each shot's
+ // textZone keeps the type off the subject.
const CUES = (MV.textCues || []).filter((c) => Number.isFinite(c.startSec) && Number.isFinite(c.endSec) && c.endSec > c.startSec);
- const HERO = CUES.filter((c) => c.emphasis === 'hero').map((c) => ({ ...c, words: heroWordsFor(c) }));
- const SUBTITLE_CUES = CUES.filter((c) => c.emphasis !== 'hero');
- // Subtitles: the director's subtitle cues when there are any, else the lyrics.
- const SUBTITLES = (SUBTITLE_CUES.length ? SUBTITLE_CUES : (MV.lyrics || []))
- .filter((l) => l?.text && Number.isFinite(l.startSec))
- .map((l) => ({ text: l.text, startSec: l.startSec, endSec: Number.isFinite(l.endSec) ? l.endSec : l.startSec + 2.5 }));
-
- function heroWords(t, cue) {
- const shown = cue.words.filter((w) => t >= w.t0 - 0.02);
- if (!shown.length) return;
- const maxW = W - 180 * U;
- let px = Math.round((W > H ? 150 : 120) * U);
- ctx.font = F.stencil(px);
- const measure = (w) => ctx.measureText(`${w.w} `).width;
- let lines = wrap(cue.words, maxW, measure);
- while (lines.length > 3 && px > 40) { px = Math.round(px * 0.88); ctx.font = F.stencil(px); lines = wrap(cue.words, maxW, measure); }
- const lineH = px * 0.92;
- const baseY = cue.placement === 'upper' ? 220 * U + lineH : cue.placement === 'center' ? H / 2 + lineH / 2 : H - 150 * U;
- const topY = baseY - (lines.length - 1) * lineH;
- const out = seg(t, cue.endSec - 0.12, cue.endSec);
- lines.forEach((line, li) => {
- let x = W > H ? 96 * U : (W - line.reduce((s, w) => s + measure(w), 0)) / 2;
- for (const w of line) {
- const ww = measure(w);
- if (t >= w.t0 - 0.02) {
- const k = seg(t, w.t0 - 0.02, w.t0 + 0.09);
- const sc = lerp(1.35, 1, easeOut(k));
- ctx.save(); ctx.globalAlpha = 1 - out;
- ctx.translate(x, topY + li * lineH); ctx.scale(sc, sc);
- ctx.font = F.stencil(px); ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
- if (k < 1) { ctx.fillStyle = C.accent; ctx.fillText(w.w, 6 * U, 0); }
- ctx.fillStyle = C.paper; ctx.fillText(w.w, 0, 0);
- ctx.restore();
- }
- x += ww;
- }
- });
+ const ZONE_OF_PLACEMENT = { upper: 'upper-right', center: 'center', lower: 'lower-left' };
+ const HERO_LINES = CUES.filter((c) => c.emphasis === 'hero')
+ .map((c) => ({ text: c.text, startSec: c.startSec, endSec: c.endSec, role: 'hook', zone: ZONE_OF_PLACEMENT[c.placement] || null }));
+ const SUBTITLE_CUES = CUES.filter((c) => c.emphasis !== 'hero')
+ .map((c) => ({ text: c.text, startSec: c.startSec, endSec: c.endSec, role: 'line' }));
+ let lyricType = null;
+ // lyricType.js is a module, so it runs after this classic script; it publishes
+ // itself on globalThis before DOMContentLoaded.
+ const lyricTypeModule = () => new Promise((resolve, reject) => {
+ const check = () => (globalThis.PORTOS_LYRIC_TYPE ? resolve(globalThis.PORTOS_LYRIC_TYPE)
+ : reject(new Error('lyricType.js did not load — the layered template needs it beside index.html')));
+ if (globalThis.PORTOS_LYRIC_TYPE || document.readyState !== 'loading') check();
+ else document.addEventListener('DOMContentLoaded', check, { once: true });
+ });
+ async function buildLyricType() {
+ const { createLyricType } = await lyricTypeModule();
+ const words = { palette: { fill: C.paper, ink: C.ink, accent: C.accent, strike: C.alert } };
+ // Subtitles: the director's subtitle cues when there are any, else the lyrics.
+ const lines = SUBTITLE_CUES.length ? [...HERO_LINES, ...SUBTITLE_CUES] : null;
+ lyricType = lines ? createLyricType(MV, { ...words, lines })
+ : HERO_LINES.length ? mergeLyricTypes(createLyricType(MV, { ...words, lines: HERO_LINES }), createLyricType(MV, words))
+ : createLyricType(MV, words);
+ await lyricType.ready;
}
- function subtitle(t, line) {
- const a = Math.min(seg(t, line.startSec, line.startSec + 0.08), 1 - seg(t, line.endSec - 0.08, line.endSec));
- if (a <= 0) return;
- const px = Math.round(44 * U);
- ctx.save(); ctx.globalAlpha = a; ctx.font = F.cond(px, 500);
- const lines = wrap(line.text.split(/\s+/), W - 240 * U, (w) => ctx.measureText(`${w} `).width).map((l) => l.join(' '));
- const lineH = px * 1.3;
- const bottom = H - (W > H ? 150 : 260) * U;
- lines.forEach((str, i) => {
- const y = bottom - (lines.length - 1 - i) * lineH;
- const w = ctx.measureText(str).width;
- ctx.fillStyle = 'rgba(7,9,10,.55)'; ctx.fillRect(W / 2 - w / 2 - 18 * U, y - px, w + 36 * U, px * 1.35);
- text(str, W / 2, y, F.cond(px, 500), C.paper, 'center');
- });
- ctx.restore();
+ // Hero cues over the sung lyrics: a visible hook takes the frame.
+ function mergeLyricTypes(hooks, sung) {
+ return {
+ ready: Promise.all([hooks.ready, sung.ready]),
+ draw(target, t, size) {
+ if (hooks.linesAt(t).length) hooks.draw(target, t, size);
+ else sung.draw(target, t, size);
+ },
+ };
}
// ---------- HUD (composition.overlay) ----------
@@ -550,12 +503,7 @@
grain(t, 0.09);
drawHud(t);
drawNarrativeEvents(state);
- const hero = HERO.find((c) => t >= c.startSec && t < c.endSec);
- if (hero) heroWords(t, hero);
- else {
- const line = SUBTITLES.find((l) => t >= l.startSec && t < l.endSec);
- if (line) subtitle(t, line);
- }
+ if (lyricType) lyricType.draw(ctx, t, { width: W, height: H });
footageVisibility = before ? { sceneId: scene.sceneId, ...compareFootagePixels(before, footagePixels(), 160, 96) } : null;
}
@@ -563,6 +511,7 @@
const ready = (async () => {
if (window.PORTOS_MV_ASSETS) assetUrls = await window.PORTOS_MV_ASSETS;
await Promise.all([F.stencil(40), F.mono(20), F.mono(20, 600), F.cond(20), F.cond(20, 700)].map((font) => document.fonts.load(font)));
+ await buildLyricType();
buildGrain();
})();
globalThis.portosComposition = {
diff --git a/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js b/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js
index 51238eb11d..ebdfc5a284 100644
--- a/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js
+++ b/server/services/musicVideo/documentTemplates/layered/engine.overlay.test.js
@@ -7,6 +7,7 @@ import { gateAutoReview } from '../../autoReviewJudge.js';
// The layered engine is a browser template copied into each document, so the overlay
// guard is exercised by evaluating just that helper against a recording fake context.
const engine = readFileSync(new URL('./engine.js', import.meta.url), 'utf8');
+const lyricType = readFileSync(new URL('../shared/lyricType.js', import.meta.url), 'utf8');
const helper = engine.slice(engine.indexOf(' const FOOTAGE_WASH_ALPHA'), engine.indexOf(' // Compare the same camera-transformed footage'));
const W = 1920; const H = 1080;
const footageOverlayContext = new Function('W', 'H', `${helper}\nreturn footageOverlayContext;`)(W, H);
@@ -82,6 +83,8 @@ describe.skipIf(!chrome)('layered footage review through rendered browser pixels
window.PORTOS_MV_GENERATED = { song: { sections: [{ id: 'opening', startSec: 0, endSec: 8 }] },
sections: { opening: new Function('ctx', 'env', source) } };
}, { source, flat });
+ await page.addScriptTag({ content: lyricType, type: 'module' });
+ await page.waitForFunction(() => globalThis.PORTOS_LYRIC_TYPE);
await page.addScriptTag({ content: engine });
return await page.evaluate(async () => {
await globalThis.portosComposition.seek(3, { reviewFootage: true });
diff --git a/server/services/musicVideo/documentTemplates/layered/index.html b/server/services/musicVideo/documentTemplates/layered/index.html
index 02206437ac..4801805187 100644
--- a/server/services/musicVideo/documentTemplates/layered/index.html
+++ b/server/services/musicVideo/documentTemplates/layered/index.html
@@ -15,11 +15,13 @@ html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
(the render's viewport IS the frame, the in-app preview is smaller). */
#stage { display: block; width: 100vw; height: 100vh; object-fit: contain; }
</style>
+<link rel="stylesheet" href="lyricType.css">
</head>
<body>
<canvas id="stage"></canvas>
<!-- PortOS writes portos-mv.js (window.PORTOS_MV) and media/ next to this page at render time. -->
<script src="portos-mv.js"></script><!-- portos-allow-hidden-content: the render-time data file -->
+<script type="module" src="lyricType.js"></script><!-- portos-allow-hidden-content: the shared PortOS lyric-type module -->
<script src="engine.js"></script><!-- portos-allow-hidden-content: the reviewed template engine beside this page -->
</body>
</html>
diff --git a/server/services/musicVideo/documentTemplates/shared/fonts/LICENSE-Archivo.txt b/server/services/musicVideo/documentTemplates/shared/fonts/LICENSE-Archivo.txt
new file mode 100644
index 0000000000..78b74533d0
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/shared/fonts/LICENSE-Archivo.txt
@@ -0,0 +1,93 @@
+Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo) Archivo-Italic[wdth,wght].ttf: Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/server/services/musicVideo/documentTemplates/shared/fonts/LICENSE-IBM-Plex.txt b/server/services/musicVideo/documentTemplates/shared/fonts/LICENSE-IBM-Plex.txt
new file mode 100644
index 0000000000..01497cc60d
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/shared/fonts/LICENSE-IBM-Plex.txt
@@ -0,0 +1,93 @@
+Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/server/services/musicVideo/documentTemplates/shared/fonts/archivo-variable.woff2 b/server/services/musicVideo/documentTemplates/shared/fonts/archivo-variable.woff2
new file mode 100644
index 0000000000..e2448d0561
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/shared/fonts/archivo-variable.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/shared/fonts/ibm-plex-mono-500.woff2 b/server/services/musicVideo/documentTemplates/shared/fonts/ibm-plex-mono-500.woff2
new file mode 100644
index 0000000000..090f82f7ec
Binary files /dev/null and b/server/services/musicVideo/documentTemplates/shared/fonts/ibm-plex-mono-500.woff2 differ
diff --git a/server/services/musicVideo/documentTemplates/shared/lyricType.css b/server/services/musicVideo/documentTemplates/shared/lyricType.css
new file mode 100644
index 0000000000..39acb7c469
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/shared/lyricType.css
@@ -0,0 +1,4 @@
+/* Faces for lyricType.js (OFL licences in fonts/). Link from the page:
+ <link rel="stylesheet" href="lyricType.css"> */
+@font-face { font-family: "MV Archivo"; src: url(fonts/archivo-variable.woff2) format("woff2"); font-weight: 100 900; font-stretch: 62% 125%; }
+@font-face { font-family: "MV Mono"; src: url(fonts/ibm-plex-mono-500.woff2) format("woff2"); font-weight: 500; }
diff --git a/server/services/musicVideo/documentTemplates/shared/lyricType.js b/server/services/musicVideo/documentTemplates/shared/lyricType.js
new file mode 100644
index 0000000000..039c02678e
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/shared/lyricType.js
@@ -0,0 +1,426 @@
+/* Kinetic lyric type — the shared PortOS lyric-motion module.
+ *
+ * Any composition document can draw its sung words with one consistent look:
+ *
+ * import { createLyricType } from './lyricType.js';
+ * const lyricType = createLyricType(window.PORTOS_MV);
+ * await lyricType.ready; // the bundled faces are loaded
+ * lyricType.draw(ctx, t, { width, height }); // every frame, after the picture
+ *
+ * Link lyricType.css from the page so the bundled faces (Archivo variable widths,
+ * IBM Plex Mono, OFL licences in fonts/) are declared; PortOS adds lyricType.js,
+ * lyricType.css and those fonts to any document that references this module.
+ *
+ * Everything is driven by the song data PortOS writes (no hard-coded seconds):
+ * lines come from PORTOS_MV.lyrics with their aligned word times, the role of each
+ * line from PORTOS_MV.lyricMarkers (section headers and delivery directions), and
+ * the text zone from the shot under the line (scenes[].textZone / lyricRole).
+ *
+ * Roles:
+ * line default sung line: words rise and fade in on their onsets, the line
+ * drifts up and fades out 0.3s after its last word.
+ * hook chorus / title phrases: wide caps, centred in the zone, each word slams
+ * in on its onset, one outline-only accent word, cut on the next beat.
+ * stamp short punches, negations, spoken lines: a three-frame stamp with a
+ * small tilt, optional strike-through.
+ * data HUD captions, counters and tags in mono; numbers roll. At most one
+ * per shot.
+ *
+ * Every frame is a pure function of song time, so a draft frame matches the full
+ * render at that time. The file is plain ES2020 with no imports.
+ */
+
+export const LYRIC_ROLES = Object.freeze(['line', 'hook', 'stamp', 'data']);
+export const TEXT_ZONES = Object.freeze(['lower-left', 'upper-right', 'center', 'none']);
+
+export const DEFAULT_PALETTE = Object.freeze({ fill: '#f3ead7', ink: '#141217', accent: '#ff5a1f', strike: '#ff2a2a' });
+export const DEFAULT_FONTS = Object.freeze({ display: '"MV Archivo", "Arial Black", Impact, sans-serif', mono: '"MV Mono", Menlo, monospace' });
+
+// Section kinds (lyricMarkers.js) and delivery directions that pick a role.
+const HOOK_SECTIONS = new Set(['chorus', 'hook', 'refrain', 'post-chorus', 'drop']);
+const STAMP_DIRECTIONS = new Set(['spoken', 'shouted', 'hits']);
+const SECTION_LABEL_KINDS = [
+ [/^pre[\s-]?chorus\b/i, 'pre-chorus'], [/^post[\s-]?chorus\b/i, 'post-chorus'],
+ [/\b(chorus|hook|refrain|drop)\b/i, null], [/\bspoken\b/i, 'spoken'],
+];
+
+// Motion constants (seconds unless noted), at 1080px on the short side.
+export const LYRIC_TIMING = Object.freeze({
+ lineRiseSec: 0.2, lineRisePx: 16, lineExitDelaySec: 0.3, lineExitFrames: 8,
+ hookSlamSec: 0.22, hookSlamFrom: 1.35, stampFrames: 3, stampFrom: 1.25, stampTiltDeg: 2,
+ strikeSec: 0.2, dataRollSec: 0.4, minOnScreenSec: 0.8, minPx: 56,
+});
+
+const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+const finite = (n) => typeof n === 'number' && Number.isFinite(n);
+const easeOutCubic = (k) => 1 - Math.pow(1 - clamp(k), 3);
+// A light spring that overshoots once and settles by k = 1.
+const spring = (k) => { k = clamp(k); return 1 - Math.cos(k * Math.PI * 1.5) * Math.exp(-5 * k); };
+const hash = (n) => { const x = Math.sin(n * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };
+const norm = (s) => String(s).toLowerCase().replace(/[’]/g, "'").replace(/[^a-z0-9']/g, '');
+
+function lastAtOrBefore(sorted, t) {
+ let lo = 0; let hi = sorted.length - 1; let r = -1;
+ while (lo <= hi) { const m = (lo + hi) >> 1; if (sorted[m] <= t) { r = m; lo = m + 1; } else hi = m - 1; }
+ return r;
+}
+
+/** The role a section kind or label implies (`hook` for choruses, else null). */
+export function roleForSection(kindOrLabel) {
+ if (!kindOrLabel) return null;
+ const value = String(kindOrLabel).trim().toLowerCase();
+ if (HOOK_SECTIONS.has(value)) return 'hook';
+ if (STAMP_DIRECTIONS.has(value)) return 'stamp';
+ for (const [pattern, kind] of SECTION_LABEL_KINDS) {
+ if (!pattern.test(value)) continue;
+ if (kind === 'pre-chorus') return null;
+ if (kind === 'spoken') return 'stamp';
+ return 'hook';
+ }
+ return null;
+}
+
+/**
+ * The role for each lyric line (by index), resolved in order: an explicit
+ * per-line override (`overrides[lineId]` or `overrides[index]`), the line's own
+ * `role`, the delivery direction marked on that line, the section the line sits
+ * in (lyricMarkers section headers, else the timed song section's label), else
+ * `line`. A role that is not one of LYRIC_ROLES is ignored.
+ */
+export function resolveLineRoles(lines, { lyricMarkers = [], sections = [], overrides = {} } = {}) {
+ const valid = (role) => (LYRIC_ROLES.includes(role) ? role : null);
+ const markers = (Array.isArray(lyricMarkers) ? lyricMarkers : []).filter((m) => m && Number.isInteger(m.line));
+ const sectionMarkers = markers.filter((m) => m.type === 'section').sort((a, b) => a.line - b.line);
+ const timedSections = (Array.isArray(sections) ? sections : []).filter((s) => finite(s?.startSec)).sort((a, b) => a.startSec - b.startSec);
+ return lines.map((line, index) => {
+ const override = valid(overrides?.[line?.id]) || valid(overrides?.[index]);
+ if (override) return override;
+ if (valid(line?.role)) return line.role;
+ const direction = markers.find((m) => m.type === 'direction' && m.line === index);
+ const fromDirection = direction ? roleForSection(direction.kind) : null;
+ if (fromDirection) return fromDirection;
+ const header = sectionMarkers.filter((m) => m.line <= index).pop();
+ if (header) return roleForSection(header.kind || header.label) || 'line';
+ const onset = finite(line?.startSec) ? line.startSec : null;
+ const timed = onset == null ? null : timedSections.filter((s) => s.startSec <= onset + 1e-6).pop();
+ return roleForSection(timed?.label) || 'line';
+ });
+}
+
+/**
+ * Per-word onsets for a line. Aligned words (`words[].startSec`) are used as they
+ * are; a line with one timing for several tokens is matched against the song's
+ * aligned words in its window, else spread across the line's first 80%.
+ */
+export function wordsForLine(line, songWords = []) {
+ const text = String(line?.text || '').trim();
+ const tokens = text.split(/\s+/).filter(Boolean);
+ const timed = (Array.isArray(line?.words) ? line.words : [])
+ .map((w) => ({ text: String(w?.text ?? w?.w ?? '').trim(), startSec: w?.startSec, endSec: w?.endSec }))
+ .filter((w) => w.text && finite(w.startSec));
+ if (timed.length > 1 || (timed.length === 1 && tokens.length <= 1)) {
+ return timed.map((w) => ({ text: w.text, startSec: w.startSec, endSec: finite(w.endSec) && w.endSec > w.startSec ? w.endSec : null }));
+ }
+ const start = finite(line?.startSec) ? line.startSec : timed[0]?.startSec;
+ if (!finite(start) || !tokens.length) return [];
+ const end = finite(line?.endSec) && line.endSec > start ? line.endSec : start + Math.max(1, tokens.length * 0.35);
+ const pool = (Array.isArray(songWords) ? songWords : [])
+ .filter((w) => finite(w?.startSec) && w.startSec >= start - 0.35 && w.startSec <= end + 0.2)
+ .sort((a, b) => a.startSec - b.startSec);
+ const out = []; let j = 0;
+ for (const token of tokens) {
+ const key = norm(token);
+ let hit = null;
+ for (let k = j; k < pool.length; k++) {
+ const p = norm(pool[k].w ?? pool[k].text ?? '');
+ if (p && (p === key || (key.length > 3 && p.startsWith(key.slice(0, 4))))) { hit = pool[k]; j = k + 1; break; }
+ }
+ out.push({ text: token, startSec: hit ? hit.startSec : null, endSec: hit && finite(hit.endSec) ? hit.endSec : null });
+ }
+ if (out.some((w) => w.startSec == null)) {
+ const span = Math.max(0.2, (end - start) * 0.8);
+ out.forEach((w, i) => { w.startSec = start + (i * span) / Math.max(1, out.length); w.endSec = null; });
+ out[out.length - 1].endSec = end;
+ }
+ return out;
+}
+
+/**
+ * When a line leaves the screen. A line never shows before its first onset and
+ * stays at least LYRIC_TIMING.minOnScreenSec. `line`/`stamp`/`data` start exiting
+ * 0.3s after the last word ends (capped at the next line's onset); a `hook`
+ * exits on the first beat at or after its last word, with no fade.
+ */
+export function lineWindow(words, role, { beats = [], nextOnset = null, fps = 24, endSec = null } = {}) {
+ const T = LYRIC_TIMING;
+ const onset = words[0].startSec;
+ const last = words[words.length - 1];
+ const lastEnd = Math.max(...words.map((w) => (finite(w.endSec) ? w.endSec : w.startSec)), finite(endSec) ? endSec : -Infinity);
+ const minExit = onset + T.minOnScreenSec;
+ if (role === 'hook') {
+ const sorted = beats.filter(finite);
+ const from = Math.max(lastEnd, last.startSec, minExit);
+ const index = lastAtOrBefore(sorted, from - 1e-6) + 1;
+ const exitSec = index < sorted.length ? sorted[index] : from + T.lineExitDelaySec;
+ return { startSec: onset, exitSec, endSec: exitSec };
+ }
+ let exitSec = lastEnd + T.lineExitDelaySec;
+ if (finite(nextOnset) && nextOnset < exitSec) exitSec = nextOnset;
+ exitSec = Math.max(exitSec, minExit);
+ const fade = role === 'stamp' ? 0 : T.lineExitFrames / fps;
+ return { startSec: onset, exitSec, endSec: exitSec + fade };
+}
+
+/** The pixel box a text zone allows on a width × height frame (null for `none`). */
+export function zoneRect(zone, width, height) {
+ const unit = Math.min(width, height) / 1080;
+ const insetX = Math.max(72 * unit, width * 0.06);
+ const insetY = Math.max(72 * unit, height * 0.07);
+ const portrait = height > width;
+ switch (zone) {
+ case 'none': return null;
+ case 'center':
+ return { zone, x: insetX, y: height * 0.22, w: width - 2 * insetX, h: height * 0.56, align: 'center', anchor: 'middle' };
+ case 'upper-right': {
+ const w = portrait ? width - 2 * insetX : width * 0.58;
+ return { zone, x: width - insetX - w, y: insetY, w, h: height * 0.38, align: 'right', anchor: 'top' };
+ }
+ case 'lower-left':
+ default: {
+ const w = portrait ? width - 2 * insetX : width * 0.62;
+ const h = height * 0.38;
+ return { zone: 'lower-left', x: insetX, y: height - insetY - h, w, h, align: 'left', anchor: 'bottom' };
+ }
+ }
+}
+
+/** Word-wrap `items` into rows no wider than `maxW` (measure returns a width). */
+function wrap(items, maxW, measure) {
+ const rows = []; let row = []; let width = 0;
+ for (const item of items) {
+ const w = measure(item);
+ if (row.length && width + w > maxW) { rows.push(row); row = []; width = 0; }
+ row.push(item); width += w;
+ }
+ if (row.length) rows.push(row);
+ return rows;
+}
+
+// The hook's outline-only accent word: the longest word (first on a tie).
+function accentIndexOf(words) {
+ let best = 0;
+ words.forEach((w, i) => { if (norm(w.text).length > norm(words[best].text).length) best = i; });
+ return words.length > 1 ? best : -1;
+}
+
+function rollNumbers(text, k) {
+ if (k >= 1) return text;
+ return text.replace(/\d+(?:\.\d+)?/g, (match) => {
+ const decimals = match.includes('.') ? match.split('.')[1].length : 0;
+ return (Number(match) * easeOutCubic(k)).toFixed(decimals);
+ });
+}
+
+/**
+ * Build the lyric plan and its renderer.
+ *
+ * `mv` is window.PORTOS_MV (lyrics, lyricMarkers, song, scenes, render). Options:
+ * lines explicit lines `[{ text, startSec, endSec?, words?, role?, zone?, strike? }]`
+ * instead of mv.lyrics (the layered template passes its text cues)
+ * overrides `{ [lineId | index]: role }`
+ * sectionRoles `{ [sectionKind]: role }` — e.g. `{ verse: 'stamp' }`
+ * palette `{ fill, ink, accent, strike }`; fonts `{ display, mono }`
+ * defaultZone zone for a shot without textZone (hooks default to `center`)
+ * boil `{ px, fps }` ink-boil jitter (off by default; share the scene's line boil)
+ * exclusive a visible hook hides the other roles (default true)
+ */
+export function createLyricType(mv = globalThis.PORTOS_MV, options = {}) {
+ const T = LYRIC_TIMING;
+ const fps = mv?.render?.fps || 24;
+ const palette = { ...DEFAULT_PALETTE, ...(options.palette || {}) };
+ const fonts = { ...DEFAULT_FONTS, ...(options.fonts || {}) };
+ const beats = (mv?.song?.beats || []).filter(finite).slice().sort((a, b) => a - b);
+ const songWords = mv?.song?.words || [];
+ const scenes = (mv?.scenes || [])
+ .filter((s) => finite(s?.startSec) && finite(s?.endSec) && s.endSec > s.startSec)
+ .slice().sort((a, b) => a.startSec - b.startSec);
+ const sceneAt = (t) => scenes.filter((s) => s.startSec <= t + 1e-6 && t < s.endSec).pop() || null;
+ const source = (Array.isArray(options.lines) ? options.lines : (mv?.lyrics || []))
+ .filter((l) => l && String(l.text || '').trim());
+ const roles = resolveLineRoles(source, {
+ lyricMarkers: options.lines ? [] : mv?.lyricMarkers,
+ sections: mv?.song?.sections,
+ overrides: options.overrides,
+ });
+ const sectionRoles = options.sectionRoles || {};
+ const timed = source.map((line, index) => {
+ const words = wordsForLine(line, songWords);
+ if (!words.length) return null;
+ let role = roles[index];
+ const section = (mv?.song?.sections || []).filter((s) => finite(s?.startSec) && s.startSec <= words[0].startSec + 1e-6).pop();
+ const kind = section?.label ? String(section.label).trim().toLowerCase().replace(/\s+\d+$/, '') : null;
+ if (!line.role && !options.overrides?.[line.id] && !options.overrides?.[index] && LYRIC_ROLES.includes(sectionRoles[kind])) role = sectionRoles[kind];
+ const shot = sceneAt(words[0].startSec);
+ if (!line.role && !options.overrides?.[line.id] && !options.overrides?.[index] && LYRIC_ROLES.includes(shot?.lyricRole)) role = shot.lyricRole;
+ return { index, id: line.id ?? null, text: String(line.text).trim(), role, words, zone: line.zone || null, strike: !!line.strike, endSec: line.endSec, shot };
+ }).filter(Boolean).sort((a, b) => a.words[0].startSec - b.words[0].startSec);
+
+ // At most one data caption per shot: later ones in the same shot fall back to `line`.
+ const dataShots = new Set();
+ for (const line of timed) {
+ if (line.role !== 'data') continue;
+ const key = line.shot?.sceneId ?? `t${Math.floor(line.words[0].startSec)}`;
+ if (dataShots.has(key)) line.role = 'line'; else dataShots.add(key);
+ }
+ const lines = timed.map((line, i) => {
+ const next = timed.slice(i + 1).find((other) => other.role === line.role);
+ const window = lineWindow(line.words, line.role, { beats, nextOnset: next?.words[0].startSec ?? null, fps, endSec: line.role === 'hook' ? line.endSec : null });
+ const zone = line.zone || line.shot?.textZone || (line.role === 'hook' ? 'center' : options.defaultZone || 'lower-left');
+ return { ...line, ...window, zone: TEXT_ZONES.includes(zone) ? zone : 'lower-left', accent: line.role === 'hook' ? accentIndexOf(line.words) : -1 };
+ });
+
+ const exclusive = options.exclusive !== false;
+ /** Lines on screen at t (none before a line's first onset). */
+ function linesAt(t) {
+ const on = lines.filter((l) => t >= l.startSec - 1e-6 && t < l.endSec && l.zone !== 'none');
+ if (exclusive && on.some((l) => l.role === 'hook')) return on.filter((l) => l.role === 'hook');
+ return on;
+ }
+
+ /** Per-word visual state for a line at t (pure; drawing reads it). */
+ function wordStates(line, t) {
+ return line.words.map((w, i) => {
+ const since = t - w.startSec;
+ if (since < -1e-6) return { ...w, index: i, shown: false };
+ switch (line.role) {
+ case 'hook': {
+ const k = clamp(since / T.hookSlamSec);
+ return { ...w, index: i, shown: true, alpha: 1, scale: T.hookSlamFrom + (1 - T.hookSlamFrom) * spring(k), dy: 0, tilt: 0 };
+ }
+ case 'stamp': {
+ const k = clamp(since / (T.stampFrames / fps));
+ const tilt = (hash(line.index * 31 + i) < 0.5 ? -1 : 1) * T.stampTiltDeg * (1 - k);
+ return { ...w, index: i, shown: true, alpha: 1, scale: T.stampFrom + (1 - T.stampFrom) * k, dy: 0, tilt };
+ }
+ default: {
+ const k = easeOutCubic(since / T.lineRiseSec);
+ return { ...w, index: i, shown: true, alpha: k, scale: 1, dy: (1 - k) * T.lineRisePx, tilt: 0 };
+ }
+ }
+ });
+ }
+
+ function lineExit(line, t) {
+ if (t < line.exitSec || line.role === 'hook' || line.role === 'stamp') return { alpha: 1, dy: 0 };
+ const k = clamp((t - line.exitSec) / Math.max(1e-6, line.endSec - line.exitSec));
+ return { alpha: 1 - k, dy: -T.lineRisePx * 1.5 * easeOutCubic(k) };
+ }
+
+ const fontFor = (role, px) => {
+ if (role === 'hook') return `900 extra-expanded ${Math.round(px)}px ${fonts.display}`;
+ if (role === 'stamp') return `900 ${Math.round(px)}px ${fonts.display}`;
+ if (role === 'data') return `500 ${Math.round(px)}px ${fonts.mono}`;
+ return `700 ${Math.round(px)}px ${fonts.display}`;
+ };
+ const basePx = (role, unit, portrait) => {
+ if (role === 'hook') return (portrait ? 140 : 160) * unit;
+ if (role === 'stamp') return 110 * unit;
+ if (role === 'data') return 34 * unit;
+ return 68 * unit;
+ };
+
+ /** Layout of a line in its zone: rows of words with x/y, font size (pure given measure). */
+ function layout(line, width, height, measure) {
+ const rect = zoneRect(line.zone, width, height);
+ if (!rect) return null;
+ const unit = Math.min(width, height) / 1080;
+ const floor = (line.role === 'data' ? 28 : T.minPx) * unit;
+ let px = basePx(line.role, unit, height > width);
+ const items = line.words.map((w) => (line.role === 'hook' ? String(w.text).toUpperCase() : w.text));
+ const rowsAt = (size) => wrap(items.map((text, index) => ({ text, index })), rect.w, (item) => measure(`${item.text} `, fontFor(line.role, size)));
+ let rows = rowsAt(px);
+ const maxRows = line.role === 'hook' ? 3 : 2;
+ while ((rows.length > maxRows || rows.length * px * 1.05 > rect.h) && px * 0.9 >= floor) { px *= 0.9; rows = rowsAt(px); }
+ const lineH = px * (line.role === 'data' ? 1.3 : 1.02);
+ const blockH = rows.length * lineH;
+ const top = rect.anchor === 'top' ? rect.y + px : rect.anchor === 'middle' ? rect.y + (rect.h - blockH) / 2 + px * 0.85 : rect.y + rect.h - blockH + px * 0.85;
+ const placed = [];
+ rows.forEach((row, r) => {
+ const widths = row.map((item) => measure(`${item.text} `, fontFor(line.role, px)));
+ const rowW = widths.reduce((a, b) => a + b, 0) - measure(' ', fontFor(line.role, px));
+ let x = rect.align === 'left' ? rect.x : rect.align === 'right' ? rect.x + rect.w - rowW : rect.x + (rect.w - rowW) / 2;
+ row.forEach((item, k) => {
+ placed.push({ index: item.index, text: item.text, x, y: top + r * lineH, w: widths[k] });
+ x += widths[k];
+ });
+ });
+ return { rect, px, rows: rows.length, words: placed };
+ }
+
+ function boilOffset(seed, t, unit) {
+ const boil = options.boil;
+ if (!boil || !(boil.px > 0)) return [0, 0];
+ const step = Math.floor(t * (boil.fps || 12));
+ return [(hash(seed * 7.1 + step) - 0.5) * 2 * boil.px * unit, (hash(seed * 3.3 + step + 91) - 0.5) * 2 * boil.px * unit];
+ }
+
+ /** Draw every visible line at song time t onto a 2D context. */
+ function draw(ctx, t, { width = ctx.canvas?.width, height = ctx.canvas?.height } = {}) {
+ const unit = Math.min(width, height) / 1080;
+ const measure = (str, font) => { ctx.font = font; return ctx.measureText(str).width; };
+ for (const line of linesAt(t)) {
+ const placed = layout(line, width, height, measure);
+ if (!placed) continue;
+ const states = wordStates(line, t);
+ const exit = lineExit(line, t);
+ const font = fontFor(line.role, placed.px);
+ const outline = Math.max(2, (line.role === 'data' ? 4 : 11) * unit * (placed.px / basePx(line.role, unit, height > width)));
+ ctx.save();
+ ctx.font = font; ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+ ctx.lineJoin = 'round'; ctx.miterLimit = 2; ctx.lineWidth = outline;
+ for (const word of placed.words) {
+ const s = states[word.index];
+ if (!s.shown) continue;
+ const [bx, by] = boilOffset(line.index * 17 + word.index, t, unit);
+ const cx = word.x + (word.w - measure(' ', font)) / 2;
+ ctx.save();
+ ctx.font = font;
+ ctx.globalAlpha = clamp(s.alpha * exit.alpha);
+ ctx.translate(cx + bx, word.y + (s.dy + exit.dy) * unit + by);
+ if (s.tilt) ctx.rotate((s.tilt * Math.PI) / 180);
+ if (s.scale !== 1) ctx.scale(s.scale, s.scale);
+ const text = line.role === 'data' ? rollNumbers(word.text, (t - s.startSec) / T.dataRollSec) : word.text;
+ const x0 = -(word.w - measure(' ', font)) / 2;
+ if (line.role === 'data') {
+ ctx.fillStyle = palette.accent; ctx.fillText(text, x0, 0);
+ } else if (line.role === 'hook' && word.index === line.accent) {
+ ctx.strokeStyle = palette.fill; ctx.strokeText(text, x0, 0);
+ } else {
+ ctx.strokeStyle = palette.ink; ctx.strokeText(text, x0, 0);
+ ctx.fillStyle = palette.fill; ctx.fillText(text, x0, 0);
+ }
+ ctx.restore();
+ }
+ if (line.role === 'stamp' && line.strike) {
+ const k = clamp((t - line.words[line.words.length - 1].startSec) / T.strikeSec);
+ const first = placed.words[0]; const last = placed.words[placed.words.length - 1];
+ const y = first.y - placed.px * 0.32;
+ const x0 = first.x; const x1 = last.x + last.w - measure(' ', font);
+ ctx.globalAlpha = exit.alpha; ctx.strokeStyle = palette.strike; ctx.lineCap = 'round';
+ ctx.lineWidth = Math.max(3, placed.px * 0.09);
+ ctx.beginPath(); ctx.moveTo(x0, y); ctx.lineTo(x0 + (x1 - x0) * k, y); ctx.stroke();
+ }
+ ctx.restore();
+ }
+ }
+
+ const faces = [fontFor('line', 40), fontFor('hook', 40), fontFor('stamp', 40), fontFor('data', 20)];
+ const ready = typeof document !== 'undefined' && document.fonts?.load
+ ? Promise.all(faces.map((face) => document.fonts.load(face))).then(() => true)
+ : Promise.resolve(true);
+
+ return { lines, linesAt, wordStates, layout, draw, ready, palette, fonts };
+}
+
+// Classic-script templates (the layered engine) reach the module through this global.
+if (typeof globalThis !== 'undefined') globalThis.PORTOS_LYRIC_TYPE = { createLyricType, zoneRect, LYRIC_ROLES, TEXT_ZONES };
diff --git a/server/services/musicVideo/documentTemplates/shared/lyricType.test.js b/server/services/musicVideo/documentTemplates/shared/lyricType.test.js
new file mode 100644
index 0000000000..ba0ab3edfc
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/shared/lyricType.test.js
@@ -0,0 +1,141 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { chromium } from 'playwright-core';
+import { createLyricType, resolveLineRoles, zoneRect } from './lyricType.js';
+
+// A synthetic song: a verse line, a chorus line, a spoken direction, all word-timed.
+const words = (text, start, step = 0.3) => text.split(' ').map((w, i) => ({ text: w, startSec: start + i * step, endSec: start + i * step + 0.25 }));
+const MV = {
+ render: { width: 1920, height: 1080, fps: 24, durationSec: 20 },
+ song: { beats: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10], sections: [], words: [] },
+ lyrics: [
+ { id: 'l0', text: 'walking through the static', startSec: 1, endSec: 2.2, words: words('walking through the static', 1) },
+ { id: 'l1', text: 'we light the signal', startSec: 4.1, endSec: 5.2, words: words('we light the signal', 4.1) },
+ { id: 'l2', text: 'not anymore', startSec: 8, endSec: 8.6, words: words('not anymore', 8) },
+ ],
+ lyricMarkers: [
+ { type: 'section', label: 'Verse 1', kind: 'verse', line: 0 },
+ { type: 'section', label: 'Chorus', kind: 'chorus', line: 1 },
+ { type: 'section', label: 'Verse 2', kind: 'verse', line: 2 },
+ { type: 'direction', label: 'Spoken', kind: 'spoken', line: 2 },
+ ],
+ scenes: [
+ { sceneId: 'a', startSec: 0, endSec: 3.5, textZone: 'upper-right' },
+ { sceneId: 'b', startSec: 3.5, endSec: 7.5 },
+ { sceneId: 'c', startSec: 7.5, endSec: 20, textZone: 'none' },
+ ],
+};
+
+// A deterministic measure: 0.5em per character.
+const measure = (str, font) => str.length * Number(/(\d+)px/.exec(font)[1]) * 0.5;
+
+describe('lyricType roles', () => {
+ it('takes roles from the lyric sheet: section headers, then a line\'s delivery direction, overrides first', () => {
+ expect(resolveLineRoles(MV.lyrics, { lyricMarkers: MV.lyricMarkers })).toEqual(['line', 'hook', 'stamp']);
+ expect(resolveLineRoles(MV.lyrics, { lyricMarkers: MV.lyricMarkers, overrides: { l1: 'data', 0: 'stamp' } })).toEqual(['stamp', 'data', 'stamp']);
+ // No sheet markers: the timed section label decides.
+ expect(resolveLineRoles(MV.lyrics, { sections: [{ label: 'Verse', startSec: 0 }, { label: 'Final Chorus', startSec: 4 }] })).toEqual(['line', 'hook', 'hook']);
+ });
+
+ it('lets a shot override the role of the lines sung over it', () => {
+ const type = createLyricType({ ...MV, scenes: MV.scenes.map((s) => (s.sceneId === 'a' ? { ...s, lyricRole: 'stamp' } : s)) });
+ expect(type.lines.map((l) => l.role)).toEqual(['stamp', 'hook', 'stamp']);
+ });
+});
+
+describe('lyricType timing', () => {
+ const type = createLyricType(MV);
+ const [verse, hook] = type.lines;
+
+ it('never shows a line before its first word onset, and reveals each word on its own onset', () => {
+ expect(type.linesAt(0.99)).toEqual([]);
+ expect(type.linesAt(1)).toEqual([verse]);
+ const states = type.wordStates(verse, 1.35);
+ expect(states.map((s) => s.shown)).toEqual([true, true, false, false]);
+ expect(states[1].alpha).toBeLessThan(1);
+ expect(type.wordStates(verse, 1.6)[0]).toMatchObject({ alpha: 1, dy: 0 });
+ });
+
+ it('exits a sung line 0.3s after its last word and cuts a hook on the next beat', () => {
+ expect(verse.exitSec).toBeCloseTo(1.9 + 0.25 + 0.3, 6);
+ expect(verse.endSec - verse.exitSec).toBeCloseTo(8 / 24, 6);
+ expect(type.linesAt(verse.endSec)).toEqual([]);
+ // Last hook word ends at 5.15 (cue end 5.2): the next beat is 5.5, no fade.
+ expect(hook.exitSec).toBe(5.5);
+ expect(hook.endSec).toBe(5.5);
+ expect(hook.accent).toBe(3); // the longest word ("signal") is the outline-only accent
+ });
+
+ it('keeps a short line on screen for at least 0.8s', () => {
+ const quick = createLyricType({ ...MV, lyricMarkers: [], lyrics: [{ text: 'no', startSec: 2, endSec: 2.1, words: [{ text: 'no', startSec: 2, endSec: 2.1 }] }] });
+ expect(quick.lines[0].exitSec).toBeCloseTo(2.8, 6);
+ });
+});
+
+describe('lyricType text zones', () => {
+ const type = createLyricType(MV);
+ const [verse, hook, spoken] = type.lines;
+
+ it('places each line inside its shot\'s text zone, and keeps a `none` shot clear', () => {
+ expect(verse.zone).toBe('upper-right');
+ expect(hook.zone).toBe('center');
+ expect(spoken.zone).toBe('none');
+ expect(type.linesAt(8.2)).toEqual([]);
+ for (const line of [verse, hook]) {
+ const placed = type.layout(line, 1920, 1080, measure);
+ const rect = zoneRect(line.zone, 1920, 1080);
+ for (const word of placed.words) {
+ expect(word.x).toBeGreaterThanOrEqual(rect.x - 1e-6);
+ expect(word.x + word.w - measure(' ', `${placed.px}px`)).toBeLessThanOrEqual(rect.x + rect.w + 1e-6);
+ expect(word.y).toBeGreaterThan(rect.y);
+ expect(word.y).toBeLessThanOrEqual(rect.y + rect.h);
+ }
+ expect(placed.px).toBeGreaterThanOrEqual(56);
+ }
+ });
+
+ it('reframes zones for a portrait frame', () => {
+ const rect = zoneRect('lower-left', 1080, 1920);
+ expect(rect.x + rect.w).toBeCloseTo(1080 - rect.x, 6);
+ expect(rect.y + rect.h).toBeLessThan(1920);
+ });
+});
+
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(), '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find((path) => path && existsSync(path));
+
+describe.skipIf(!chrome)('lyricType in the layered template (browser pixels)', () => {
+ let browser;
+ beforeAll(async () => { browser = await chromium.launch({ executablePath: chrome, headless: true }); }, 30000);
+ afterAll(async () => { await browser?.close(); });
+
+ it('draws nothing before the onset and draws the line inside the shot\'s zone after it', async () => {
+ const page = await browser.newPage();
+ try {
+ await page.setContent('<canvas id="stage"></canvas>');
+ await page.evaluate((mv) => { window.PORTOS_MV = mv; }, { ...MV, render: { ...MV.render, width: 640, height: 360 } });
+ await page.addScriptTag({ content: readFileSync(new URL('./lyricType.js', import.meta.url), 'utf8'), type: 'module' });
+ await page.waitForFunction(() => globalThis.PORTOS_LYRIC_TYPE);
+ await page.addScriptTag({ content: readFileSync(new URL('../layered/engine.js', import.meta.url), 'utf8') });
+ const lit = (t) => page.evaluate(async (time) => {
+ await globalThis.portosComposition.seek(time);
+ const c = document.getElementById('stage');
+ const data = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;
+ // Bright cream pixels per half of the frame (the ground is black, grain is faint).
+ let upperRight = 0; let lowerLeft = 0;
+ for (let y = 0; y < c.height; y++) for (let x = 0; x < c.width; x++) {
+ const o = (y * c.width + x) * 4;
+ if (data[o] > 200 && data[o + 1] > 200 && data[o + 2] > 180) {
+ if (x >= c.width / 2 && y < c.height / 2) upperRight++;
+ if (x < c.width / 2 && y >= c.height / 2) lowerLeft++;
+ }
+ }
+ return { upperRight, lowerLeft };
+ }, t);
+ expect((await lit(0.9)).upperRight).toBe(0);
+ const after = await lit(2);
+ expect(after.upperRight).toBeGreaterThan(50);
+ expect(after.lowerLeft).toBe(0);
+ } finally { await page.close(); }
+ }, 30000);
+});
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 9d00b0b7eb..a583581308 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -559,6 +559,15 @@ describe('scene board operations', () => {
expect(() => applySceneUpdate(project, scene.sceneId, { cardColor: 'red' })).toThrow();
});
+ it('persists a shot\'s lyric-type zone and role and refuses unknown ones (#10583)', () => {
+ const { project, scene } = addScene(baseProject(), { prompt: 'a' });
+ const { updated } = applySceneUpdate(project, scene.sceneId, { textZone: 'none', lyricRole: 'hook' });
+ expect(updated).toMatchObject({ textZone: 'none', lyricRole: 'hook' });
+ expect(applySceneUpdate(project, scene.sceneId, { textZone: null }).updated.textZone).toBeNull();
+ expect(() => applySceneUpdate(project, scene.sceneId, { textZone: 'middle' })).toThrow();
+ expect(() => applySceneUpdate(project, scene.sceneId, { lyricRole: 'karaoke' })).toThrow();
+ });
+
it('rejects a reorder that is not an exact permutation', () => {
let p = baseProject();
const r = addScene(p, { prompt: 'a' }); p = r.project;