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: cut still-image and title-card sections into composed music-video renders (#8985)

[._.]/ Adam Eivy351a60ebc49a
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index ad2955464f..31eaf2a1de 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -162,6 +162,15 @@ only audio. A cue's state at a time is a pure function of that time
The scratch directory is removed when the render ends, swept at boot, and
excluded from backups.
+A composed render also honors each scene's visual layer (#8985): its
+generated footage (the default), its selected still frame with a deterministic
+hold, push-in or pan, or a title card — a solid colour whose text is drawn by
+the same typography overlay for exactly that section. Still and card sections
+need an authored start/end instead of a clip, and every section is cut to a
+whole number of frames on the song's timebase, so the edit never drifts from
+the authored timeline. A plain concat render ignores the layer and plays
+footage, exactly as before.
+
## Launch-video admission (API foundation)
`POST /api/html-composition/render` accepts `launchVideo: { targetDurationSec: 20 }`.
diff --git a/server/lib/README.md b/server/lib/README.md
index 58266ec958..e2fc9bb025 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -521,6 +521,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `claimFlowTaskTypes.js` | `CLAIM_FLOW_TASK_TYPES` — the ONE list of task kinds whose prompts own their own `claim/<item>` worktree and push/PR/MR/review lifecycle (#6613). `services/cosTaskGenerator.js` stamps `metadata.claimFlow` from it (WRITE side); `services/agentPromptBuilder.js` reads it back through `isClaimFlowTask()` to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; `claimFlowTaskTypes.test.js` fails if a local copy reappears. Imports nothing. |
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
+| `musicVideoLayers.js` | Music Video per-scene visual layers (#8985): `MUSIC_VIDEO_VISUAL_LAYERS` (`footage`/`still`/`card`), `MUSIC_VIDEO_STILL_MOVES` (`hold`/`push`/`pan`), `sceneVisualLayer(scene, { layered })` (only a composed render honors a still/card), `sceneHasAuthoredSpan`, and `sceneRenderReady(scene, { layered })`. Pure leaf shared by `services/musicVideo/render.js` and the client board (`client/src/lib/musicVideoLayers.js`). |
| `pitchMath.js` | Dependency-free scientific-pitch math shared by the LLM-authored music formats on both runtimes: `pitchToMidi("C4")` → 60 (null when unparseable) and `midiToFreq(69)` → 440. |
| `wavAudioFile.js` | `writeWavAudioFile(wav, dir, basename)` — land a synthesized WAV Buffer as `<basename>.ogg` via the system ffmpeg, falling back to `<basename>.wav` (and dropping a stale `.ogg`) when ffmpeg is missing or the encode fails; resolves to the filename used. Shared by the chiptune and drawn-waveform renderers and the code-engine take upload. `wavDurationMs(buffer)` reads a PCM WAV's duration from its RIFF header (0 for anything that is not a parseable WAV). |
| `waveSketch.js` | Drawn-waveform music contract v1 (browser-safe; new paintings are v2 — see `paintedCanvas.js`): the LLM draws single-cycle `shapes` (point polylines in [-1, 1]) played by `voices` as timed strokes with optional glide, shape morph, and drawn envelope, plus a whole-piece `contour`. `normalizeWaveSketch(raw)` is the one lenient, idempotent validator (null when nothing playable survives); `synthesizeWaveSketch(sketch)` → deterministic mono PCM (seeded noise), so the client preview and server render match; `pcmPeaks(pcm, columns)` for drawing it; `WAVE_SKETCH_LIMITS`. `normalizeWaveSketch` dispatches a `version: 2` sketch to `normalizePaintedCanvas`; `synthesizeSketchChannels(sketch)` renders either version to its channel list; `isPaintedCanvas(sketch)`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index e0e2f228b8..c755489dd1 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -479,6 +479,7 @@ export * from './claimFlowTaskTypes.js';
export * from './chiptuneRender.js';
export * from './chiptuneScore.js';
export * from './pitchMath.js';
+export * from './musicVideoLayers.js';
export * from './wavAudioFile.js';
export * from './waveSketch.js';
export * from './paintedCanvas.js';
diff --git a/server/lib/musicVideoLayers.js b/server/lib/musicVideoLayers.js
new file mode 100644
index 0000000000..3ddfe90d71
--- /dev/null
+++ b/server/lib/musicVideoLayers.js
@@ -0,0 +1,36 @@
+/**
+ * Music Video — per-scene visual layers (#8985, part of #8966).
+ *
+ * In a composed render a scene can show its generated footage (the default,
+ * and every scene saved before the field existed), its selected still frame
+ * with a deterministic camera move, or a code-rendered title card (a solid
+ * colour whose text the typography layer draws). A plain concat render always
+ * uses footage. Pure and dependency-free: the server render and the client
+ * board read the same rules, so the Render button's readiness matches what the
+ * render preflight accepts.
+ */
+
+export const MUSIC_VIDEO_VISUAL_LAYERS = ['footage', 'still', 'card'];
+export const MUSIC_VIDEO_STILL_MOVES = ['hold', 'push', 'pan'];
+
+/** The layer a scene contributes; `layered` is true only for a composed render. */
+export function sceneVisualLayer(scene, { layered = false } = {}) {
+ const layer = scene?.visualLayer;
+ return layered && (layer === 'still' || layer === 'card') ? layer : 'footage';
+}
+
+/** A still/card section has no clip to measure, so it needs an authored span. */
+export function sceneHasAuthoredSpan(scene) {
+ return typeof scene?.startSec === 'number' && typeof scene?.endSec === 'number' && scene.endSec > scene.startSec;
+}
+
+/**
+ * Whether the render can include this scene as-is: footage needs its clip, a
+ * still needs its reference frame and a span, and a card needs only a span.
+ */
+export function sceneRenderReady(scene, { layered = false } = {}) {
+ const layer = sceneVisualLayer(scene, { layered });
+ if (layer === 'footage') return Boolean(scene?.videoHistoryId);
+ if (!sceneHasAuthoredSpan(scene)) return false;
+ return layer === 'card' || Boolean(scene.referenceImageId);
+}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 0f9aeb0c6a..7b44398967 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -9,6 +9,7 @@
*/
import { z } from 'zod';
+import { MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';
// A project is authored hands-on (director) or seeded by the AI planner
// (autonomous); both share the same record + scene board.
@@ -209,6 +210,15 @@ export const musicVideoCompositionSchema = z.object({
posterSec: timedSec,
}).strict();
+// Per-scene visual layer (#8985) — footage, a moved still, or a title card;
+// see musicVideoLayers.js. Only a composed render honors a non-footage layer.
+const sceneLayerFields = {
+ visualLayer: z.enum(MUSIC_VIDEO_VISUAL_LAYERS).optional(),
+ stillMove: z.enum(MUSIC_VIDEO_STILL_MOVES).optional(),
+ cardText: z.string().max(500).nullable().optional(),
+ cardColor: z.string().regex(/^#[0-9a-f]{6}$/i, 'card color is #rrggbb').nullable().optional(),
+};
+
export const musicVideoProjectCreateSchema = z.object({
name: z.string().min(1).max(200),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
@@ -264,6 +274,7 @@ export const musicVideoSceneCreateSchema = z.object({
sectionIndex: z.number().int().min(0).max(10000).nullable().optional(),
lyricText: z.string().max(2000).nullable().optional(),
visualIntent: z.string().max(2000).nullable().optional(),
+ ...sceneLayerFields,
}).strict().refine(
(s) => s.startSec == null || s.endSec == null || s.endSec >= s.startSec,
{ message: 'endSec must be >= startSec', path: ['endSec'] },
@@ -288,6 +299,7 @@ export const musicVideoSceneUpdateSchema = z.object({
sectionIndex: z.number().int().min(0).max(10000).nullable().optional(),
lyricText: z.string().max(2000).nullable().optional(),
visualIntent: z.string().max(2000).nullable().optional(),
+ ...sceneLayerFields,
referenceImageId: z.string().max(256).nullable().optional(),
videoHistoryId: z.string().max(64).nullable().optional(),
}).strict();
diff --git a/server/services/musicVideo/compositionRender.test.js b/server/services/musicVideo/compositionRender.test.js
index ac100c2448..c22649eb5f 100644
--- a/server/services/musicVideo/compositionRender.test.js
+++ b/server/services/musicVideo/compositionRender.test.js
@@ -1,6 +1,6 @@
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { existsSync } from 'node:fs';
-import { mkdir, readdir } from 'node:fs/promises';
+import { mkdir, readdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { execFileSync, spawn } from 'node:child_process';
import { chromium } from 'playwright-core';
@@ -8,7 +8,8 @@ import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../li
import { findFfmpeg, probeVideoDuration } from '../../lib/ffmpeg.js';
import { PATHS } from '../../lib/fileUtils.js';
import { _cleanupTestBrowser } from '../htmlComposition/testBrowserCleanup.js';
-import { buildMusicVideoFfmpegArgs } from './render.js';
+import { beatSnapClips, buildMusicVideoFfmpegArgs, resolveSceneClips, sectionCardCues } from './render.js';
+import { renderableCues } from './composition.js';
import { COMPOSITION_SCRATCH_DIR, removeCompositionScratch, renderTypographyOverlays } from './compositionRender.js';
let endpoint;
@@ -26,7 +27,7 @@ let proc;
let browser;
const FPS = 24;
-const run = (args) => execFileSync(ffmpeg, ['-v', 'error', ...args], { maxBuffer: 64 * 1024 * 1024 });
+const run = (args) => execFileSync(ffmpeg, ['-v', 'error', ...args], { maxBuffer: 256 * 1024 * 1024 });
// Decode a video to raw frames of `pix_fmt`.
const frames = (path, pixFmt) => run(['-i', path, '-f', 'rawvideo', '-pix_fmt', pixFmt, '-']);
@@ -125,6 +126,84 @@ describe.skipIf(!chrome || !ffmpeg)('music-video typography overlay with real Ch
expect(await readdir(join(PATHS.data, COMPOSITION_SCRATCH_DIR))).toEqual([]);
}, 60000);
+ // #8985 acceptance: footage, a still with a push-in, a code-rendered title
+ // card and animated text on one 30s timebase under one continuous song.
+ it('renders footage, a still, a title card and text on one timebase without gaps, repeats or audio resets', async () => {
+ const [w, h] = [320, 180];
+ await mkdir(PATHS.videos, { recursive: true });
+ await mkdir(PATHS.images, { recursive: true });
+ const dir = join(PATHS.data, 'fixture-layers');
+ await mkdir(dir, { recursive: true });
+ run(['-f', 'lavfi', '-i', `color=blue:s=${w}x${h}:r=${FPS}:d=8`, '-y', join(PATHS.videos, 'a.mp4')]);
+ run(['-f', 'lavfi', '-i', `color=magenta:s=${w}x${h}:r=${FPS}:d=11`, '-y', join(PATHS.videos, 'b.mp4')]);
+ run(['-f', 'lavfi', '-i', 'color=red:s=640x360', '-frames:v', '1', '-y', join(PATHS.images, 'still.png')]);
+ run(['-f', 'lavfi', '-i', 'sine=frequency=440:duration=30', '-y', join(dir, 'song.wav')]);
+ const entry = (id, filename, sec) => ({ id, filename, width: w, height: h, fps: FPS, numFrames: sec * FPS });
+ await writeFile(join(PATHS.data, 'video-history.json'), JSON.stringify([entry('h-a', 'a.mp4', 8), entry('h-b', 'b.mp4', 11)]));
+ const scenes = [
+ { sceneId: 's1', order: 0, videoHistoryId: 'h-a', startSec: 0, endSec: 8, beatAligned: true, loop: false },
+ // An off-grid boundary (15.37s is not a whole frame) and no footage.
+ { sceneId: 's2', order: 1, visualLayer: 'still', stillMove: 'push', referenceImageId: 'still.png', videoHistoryId: null, startSec: 8, endSec: 15.37 },
+ { sceneId: 's3', order: 2, visualLayer: 'card', cardText: 'CHAPTER TWO', cardColor: '#202020', videoHistoryId: null, startSec: 15.37, endSec: 19 },
+ { sceneId: 's4', order: 3, videoHistoryId: 'h-b', startSec: 19, endSec: 30, beatAligned: true, loop: false },
+ ];
+ const composition = { mode: 'composed', style: { color: '#ffffff', font: 'sans' },
+ textCues: [{ id: 'c1', text: 'OVER THE CUT', startSec: 7, endSec: 9, template: 'rise', placement: 'center', emphasis: 'hero' }] };
+ const clips = beatSnapClips(await resolveSceneClips({ scenes, composition }, { layered: true }), null, { scenes });
+ const song = join(dir, 'song.wav');
+ const output = join(dir, 'out.mp4');
+ const plan = buildMusicVideoFfmpegArgs(clips, song, output, { audioDurationSec: 30, frameGrid: true });
+ // Every section starts where the previous one ends, on the frame grid.
+ expect(plan.sections.map((s) => [s.layer, Math.round(s.startSec * FPS), Math.round(s.endSec * FPS)])).toEqual([
+ ['footage', 0, 192], ['still', 192, 369], ['card', 369, 456], ['footage', 456, 720],
+ ]);
+ const cues = [...renderableCues(composition, plan.totalDuration), ...sectionCardCues(clips, plan.sections, plan.totalDuration)];
+ const overlays = await renderTypographyOverlays({ jobId: 'job-layers', cues, style: composition.style, width: w, height: h, fps: FPS, durationSec: plan.totalDuration });
+ const { args } = buildMusicVideoFfmpegArgs(clips, song, output, { audioDurationSec: 30, overlays, frameGrid: true });
+ run(args.filter((arg, i) => !(arg === '-progress' || args[i - 1] === '-progress')));
+
+ expect(Math.abs(await probeVideoDuration(output) - 30)).toBeLessThanOrEqual(1 / FPS);
+ const pcm = run(['-i', output, '-map', '0:a', '-ac', '1', '-ar', '8000', '-f', 's16le', '-']);
+ const samples = new Int16Array(Uint8Array.from(pcm).buffer);
+ expect(Math.abs(samples.length / 8000 - 30)).toBeLessThanOrEqual(1 / FPS);
+ for (let start = 0; start + 80 <= samples.length - 800; start += 80) {
+ let peak = 0;
+ for (let i = start; i < start + 80; i++) peak = Math.max(peak, Math.abs(samples[i]));
+ expect(peak, `silent 10ms window at ${start / 8000}s`).toBeGreaterThan(1000);
+ }
+
+ const rgb = frames(output, 'rgb24');
+ const frameBytes = w * h * 3;
+ expect(rgb.length / frameBytes).toBe(30 * FPS);
+ const corner = (f) => [...rgb.subarray(f * frameBytes, f * frameBytes + 3)];
+ const whiteIn = (f) => {
+ let n = 0;
+ for (let p = 0; p < w * h; p++) {
+ const o = f * frameBytes + p * 3;
+ if (rgb[o] > 200 && rgb[o + 1] > 200 && rgb[o + 2] > 200) n += 1;
+ }
+ return n;
+ };
+ const isBlue = ([r, g, b]) => b > 200 && r < 60 && g < 60;
+ const isRed = ([r, g, b]) => r > 200 && g < 60 && b < 60;
+ const isCard = ([r, g, b]) => Math.max(r, g, b) < 60;
+ const isMagenta = ([r, g, b]) => r > 200 && b > 200 && g < 60;
+ // Each section holds its own picture right up to its boundary frame — no
+ // gap, no black filler, and no footage repeated into the still or card.
+ expect(isBlue(corner(0)) && isBlue(corner(191))).toBe(true);
+ expect(isRed(corner(192)) && isRed(corner(368))).toBe(true);
+ expect(isCard(corner(369)) && isCard(corner(455))).toBe(true);
+ expect(isMagenta(corner(456)) && isMagenta(corner(719))).toBe(true);
+ // The lyric cue is drawn across the footage→still cut; the card carries its own title.
+ expect(whiteIn(100)).toBe(0);
+ expect(whiteIn(186)).toBeGreaterThan(100);
+ expect(whiteIn(200)).toBeGreaterThan(100);
+ expect(whiteIn(280)).toBe(0);
+ expect(whiteIn(420)).toBeGreaterThan(100);
+ expect(whiteIn(600)).toBe(0);
+ await removeCompositionScratch('job-layers');
+ }, 120000);
+
it.each([['16:9', 480, 270], ['9:16', 270, 480], ['a small 16:9 frame', 160, 90]])('keeps every motion template inside the title-safe area at %s', async (_label, width, height) => {
const long = 'A deliberately long lyric line that has to wrap and shrink to stay inside the frame';
const cues = [
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 465a1fddd9..fbc0fd078a 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -310,6 +310,11 @@ function buildScene(input, { order }) {
sectionIndex: input.sectionIndex ?? null,
lyricText: input.lyricText ?? null,
visualIntent: input.visualIntent ?? null,
+ // #8985: what a composed render shows for this span (render.js#sceneLayer).
+ visualLayer: input.visualLayer ?? 'footage',
+ stillMove: input.stillMove ?? 'hold',
+ cardText: input.cardText ?? null,
+ cardColor: input.cardColor ?? null,
referenceImageId: null,
videoHistoryId: null,
// #8965 — immutable candidate takes; the two slot fields above are the
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index a6eb5561ba..c77155c896 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -432,6 +432,15 @@ describe('scene board operations', () => {
expect(next.scenes.map((s) => s.order)).toEqual([0, 1, 2]);
});
+ it('defaults a new scene to its footage and persists a chosen still or card layer (#8985)', () => {
+ const { project, scene } = addScene(baseProject(), { prompt: 'a' });
+ expect(scene).toMatchObject({ visualLayer: 'footage', stillMove: 'hold', cardText: null, cardColor: null });
+ const { updated } = applySceneUpdate(project, scene.sceneId, { visualLayer: 'card', cardText: 'Verse two', cardColor: '#112233' });
+ expect(updated).toMatchObject({ visualLayer: 'card', cardText: 'Verse two', cardColor: '#112233' });
+ expect(() => applySceneUpdate(project, scene.sceneId, { visualLayer: 'hologram' })).toThrow();
+ expect(() => applySceneUpdate(project, scene.sceneId, { cardColor: 'red' })).toThrow();
+ });
+
it('rejects a reorder that is not an exact permutation', () => {
let p = baseProject();
const r = addScene(p, { prompt: 'a' }); p = r.project;
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 1642a992c4..083b3412d0 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -35,6 +35,7 @@ import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';
import { getTrack } from '../tracks/index.js';
import { getProject, listProjects, updateProject } from './projects.js';
+import { sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';
import { renderableCues } from './composition.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';
@@ -68,6 +69,8 @@ export const attachRenderSseClient = (jobId, res) => attachSse(jobs, jobId, res)
// created since carries an explicit boolean, and only `loop: true` repeats.
const sceneLoops = (scene) => scene?.loop !== false;
+const round3 = (n) => Math.round(n * 1000) / 1000;
+
// A non-looping shot may run this much past its source clip; the gap holds the
// final frame (tpad) rather than repeating footage. Longer shortfalls block the
// render until the director resolves them.
@@ -82,7 +85,7 @@ const COVERAGE_RESOLUTIONS = Object.freeze(['trim', 'continue', 'replace', 'loop
function findCoverageShortfalls(clips, { toleranceSec = COVERAGE_TOLERANCE_SEC } = {}) {
const out = [];
for (const clip of Array.isArray(clips) ? clips : []) {
- if (clip.loop !== false) continue;
+ if (clip.layer || clip.loop !== false) continue;
const spanSec = clip.outSec - clip.inSec;
const clipSec = clip.sourceSec ?? clip.duration;
if (spanSec - clipSec > toleranceSec) {
@@ -135,25 +138,50 @@ export async function resolveMasterAudioPath(project) {
return safe;
}
+// A still/card section has no source clip to measure, so its authored span IS
+// its length. Null when the scene is not timed.
+const authoredSpan = (scene) => (sceneHasAuthoredSpan(scene) ? round3(scene.endSec - scene.startSec) : null);
+
// Resolve every scene that has a generated i2v clip (`videoHistoryId`) to a
// verified on-disk path + dims, in scene order. Scenes without a clip yet are
// skipped (not an error — they're just not rendered). A scene whose clip id
// references a missing history entry/file IS an error (404, listed).
-export async function resolveSceneClips(project) {
+//
+// `layered` (a composed render, #8985) also resolves still and card sections
+// in scene order. Neither needs footage: a still needs its selected reference
+// frame (404 MISSING_STILLS when it is gone), and both need an authored span
+// (422 UNTIMED_SECTIONS), since there is no clip to take a length from.
+export async function resolveSceneClips(project, { layered = false } = {}) {
const scenes = (Array.isArray(project.scenes) ? project.scenes : [])
.slice()
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
- .filter((s) => s && s.videoHistoryId);
+ .filter((s) => s && (s.videoHistoryId || sceneVisualLayer(s, { layered }) !== 'footage'));
if (scenes.length === 0) {
throw new ServerError('No scene videos to render — generate at least one scene clip first', {
status: 400, code: 'NO_SCENE_CLIPS',
});
}
- const history = await loadHistory();
+ const history = scenes.some((s) => sceneVisualLayer(s, { layered }) === 'footage') ? await loadHistory() : [];
const historyMap = new Map((Array.isArray(history) ? history : []).map((h) => [h.id, h]));
const missing = [];
+ const missingStills = [];
+ const untimed = [];
const clips = [];
for (const scene of scenes) {
+ const layer = sceneVisualLayer(scene, { layered });
+ if (layer !== 'footage') {
+ const spanSec = authoredSpan(scene);
+ if (spanSec == null) { untimed.push(scene.sceneId); continue; }
+ const section = { sceneId: scene.sceneId, layer, inSec: 0, outSec: spanSec, duration: spanSec, sourceSec: spanSec };
+ if (layer === 'card') {
+ clips.push({ ...section, cardText: typeof scene.cardText === 'string' ? scene.cardText.trim() : '', cardColor: /^#[0-9a-f]{6}$/i.test(scene.cardColor || '') ? scene.cardColor : '#000000' });
+ continue;
+ }
+ const imagePath = scene.referenceImageId ? safeUnder(PATHS.images, scene.referenceImageId) : null;
+ if (!imagePath || !existsSync(imagePath)) { missingStills.push(scene.sceneId); continue; }
+ clips.push({ ...section, imagePath, move: scene.stillMove || 'hold' });
+ continue;
+ }
const entry = historyMap.get(scene.videoHistoryId);
const videoPath = entry && entry.filename ? safeUnder(PATHS.videos, entry.filename) : null;
if (!entry || !videoPath || !existsSync(videoPath)) { missing.push(scene.videoHistoryId); continue; }
@@ -183,6 +211,16 @@ export async function resolveSceneClips(project) {
status: 404, code: 'MISSING_CLIPS', context: { missingClipIds: missing },
});
}
+ if (missingStills.length > 0) {
+ throw new ServerError(`${missingStills.length} still section(s) have no reference frame — generate or pick one first`, {
+ status: 404, code: 'MISSING_STILLS', context: { sceneIds: missingStills },
+ });
+ }
+ if (untimed.length > 0) {
+ throw new ServerError(`${untimed.length} still or card section(s) need a start and end time`, {
+ status: 422, code: 'UNTIMED_SECTIONS', context: { sceneIds: untimed },
+ });
+ }
return clips;
}
@@ -212,6 +250,11 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =
if (grid.length === 0 && !scenesById) return clips.map((c) => ({ ...c }));
let running = 0;
return clips.map((clip) => {
+ // A still/card section (#8985) is exactly its authored span.
+ if (clip.layer) {
+ running += clip.duration;
+ return { ...clip };
+ }
const scene = scenesById?.get(clip.sceneId);
if (scene?.beatAligned && typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec) {
// inSec stays 0 here deliberately: this only ever trims how much of the
@@ -249,6 +292,45 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =
});
}
+// The frame for a composed render with no footage to take dimensions from.
+const DEFAULT_CANVAS = Object.freeze({ width: 1280, height: 720, fps: 24 });
+// A still's push-in ends this much closer; a pan crosses this much extra width.
+const STILL_PUSH_ZOOM = 0.12;
+const STILL_PAN_TRAVEL = 0.15;
+const evenPx = (n) => Math.max(2, Math.round(n / 2) * 2);
+
+// One section's video chain (without its output label). A footage clip is
+// fitted, letterboxed and trimmed; a still (#8985) is cover-cropped and moved
+// deterministically (every frame is a pure function of its frame number); a
+// card is a solid colour the typography layer writes its text over. On the
+// frame grid every section is cut to an exact frame count.
+function sectionChain(c, input, { canonW, canonH, fps, frames, frameGrid }) {
+ const trim = frameGrid ? `trim=end_frame=${frames}` : `trim=start=${c.inSec}:end=${c.outSec}`;
+ if (c.layer === 'card') {
+ return `color=c=0x${c.cardColor.slice(1)}:s=${canonW}x${canonH}:r=${fps},setsar=1,format=yuv420p,${trim},setpts=PTS-STARTPTS`;
+ }
+ if (c.layer === 'still') {
+ const scale = c.move === 'push' ? 2 : c.move === 'pan' ? 1 + STILL_PAN_TRAVEL : 1;
+ const coverW = evenPx(canonW * scale);
+ const coverH = evenPx(canonH * scale);
+ const move = c.move === 'push'
+ // Rendered from a 2x cover so the slow zoom does not step pixel by pixel.
+ ? `zoompan=z='1+${STILL_PUSH_ZOOM}*on/${frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=1:s=${canonW}x${canonH}:fps=${fps},setsar=1,`
+ : c.move === 'pan' ? `crop=${canonW}:${canonH}:x='(iw-ow)*n/${Math.max(1, frames - 1)}':y='(ih-oh)/2',` : '';
+ return `[${input}:v]fps=${fps},scale=${coverW}:${coverH}:force_original_aspect_ratio=increase,crop=${coverW}:${coverH},setsar=1,`
+ + `${move}format=yuv420p,${trim},setpts=PTS-STARTPTS`;
+ }
+ // A non-looping shot a hair longer than its source holds the last frame for
+ // the remainder instead of ending early and drifting every later cut. On the
+ // frame grid it also pads the rounding frame, so it always fills its count.
+ const holdSec = c.loop === false ? (c.outSec - c.inSec) - (c.sourceSec ?? c.duration) : 0;
+ const padSec = c.loop === false && frameGrid ? Math.max(0, holdSec) + 2 / fps : holdSec;
+ const hold = padSec > 0 ? `tpad=stop_mode=clone:stop_duration=${round3(padSec)},` : '';
+ return `[${input}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,`
+ + `pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},`
+ + `${hold}${trim},setpts=PTS-STARTPTS`;
+}
+
// Pure: build the ffmpeg args for the master-bed render. Concats the clips
// video-only (each scaled/padded to the canonical dims + fps and trimmed to its
// snapped out-point) and maps ONE external audio input as the sole output audio.
@@ -256,51 +338,73 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =
// `overlays` (a composed render, #8984) are transparent typography clips, each
// offset to its song time and laid over the cut footage — the footage passes
// through untouched outside them, and the master audio is never re-cut.
-export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [] } = {}) {
+//
+// `frameGrid` (a composed render, #8985 — implied by any still/card section)
+// cuts every section to a whole number of frames derived from its cumulative
+// song-time boundary, so the edit never drifts more than half a frame from the
+// authored timeline however many sections it has. Returns `sections`, each
+// section's `[startSec, endSec)` on the output timebase.
+export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false } = {}) {
if (!Array.isArray(clips) || clips.length === 0) throw new Error('buildMusicVideoFfmpegArgs: empty clips');
- const canonW = clips[0].width;
- const canonH = clips[0].height;
- const fps = clips[0].fps || 24;
+ const frameGrid = gridOption || clips.some((c) => c.layer);
+ // Stills and cards have no dimensions of their own: the first footage clip
+ // sets the frame, or a default one when the render has no footage at all.
+ const lead = clips.find((c) => !c.layer) || DEFAULT_CANVAS;
+ const canonW = lead.width;
+ const canonH = lead.height;
+ const fps = lead.fps || 24;
+
+ let cursorSec = 0;
+ let cursorFrame = 0;
+ const plan = [];
+ for (const c of clips) {
+ const startSec = cursorSec;
+ cursorSec += c.outSec - c.inSec;
+ const endFrame = Math.round(cursorSec * fps);
+ const frames = endFrame - cursorFrame;
+ const section = frameGrid
+ ? { c, frames, startSec: cursorFrame / fps, endSec: endFrame / fps }
+ : { c, frames, startSec, endSec: cursorSec };
+ cursorFrame = endFrame;
+ // A section shorter than half a frame has no frame of its own on the grid.
+ if (!frameGrid || frames > 0) plan.push(section);
+ }
+ if (plan.length === 0) throw new Error('buildMusicVideoFfmpegArgs: no section spans a frame');
const inputs = [];
+ const inputOf = [];
// A generated scene clip is a reusable shot source, while the director's
// timeline owns how long that shot appears in the music video. A LOOPING
// clip input repeats so a 6–10s Grok/local result can fill a longer verse or
// chorus span; the per-input trim below still makes every loop finite. A
// non-looping clip (#8964, `loop: false`) is read once — the render preflight
- // guarantees its span fits, within COVERAGE_TOLERANCE_SEC.
- for (const c of clips) {
- if (c.loop !== false) inputs.push('-stream_loop', '-1');
- inputs.push('-i', c.videoPath);
+ // guarantees its span fits, within COVERAGE_TOLERANCE_SEC. A still loops its
+ // single image; a card needs no input (its colour is a filter source).
+ let nextInput = 0;
+ for (const { c } of plan) {
+ if (c.layer === 'card') { inputOf.push(null); continue; }
+ inputOf.push(nextInput++);
+ if (c.layer === 'still') inputs.push('-loop', '1', '-framerate', String(fps), '-i', c.imagePath);
+ else {
+ if (c.loop !== false) inputs.push('-stream_loop', '-1');
+ inputs.push('-i', c.videoPath);
+ }
}
- const audioIdx = clips.length; // master audio follows the clips
+ const audioIdx = nextInput; // master audio follows the section inputs
inputs.push('-i', audioPath);
for (const overlay of overlays) inputs.push('-itsoffset', String(overlay.startSec), '-i', overlay.path);
- const filters = [];
- const vStreams = [];
- for (let i = 0; i < clips.length; i++) {
- const c = clips[i];
- // A non-looping shot a hair longer than its source holds the last frame for
- // the remainder instead of ending early and drifting every later cut.
- const holdSec = c.loop === false ? (c.outSec - c.inSec) - (c.sourceSec ?? c.duration) : 0;
- const hold = holdSec > 0 ? `tpad=stop_mode=clone:stop_duration=${Math.round(holdSec * 1000) / 1000},` : '';
- filters.push(
- `[${i}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,`
- + `pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${fps},`
- + `${hold}trim=start=${c.inSec}:end=${c.outSec},setpts=PTS-STARTPTS[v${i}]`,
- );
- vStreams.push(`[v${i}]`);
- }
+ const filters = plan.map(({ c, frames }, i) => `${sectionChain(c, inputOf[i], { canonW, canonH, fps, frames, frameGrid })}[v${i}]`);
const cutLabel = overlays.length > 0 ? 'cut0' : 'outv';
- filters.push(`${vStreams.join('')}concat=n=${clips.length}:v=1:a=0[${cutLabel}]`);
+ filters.push(`${plan.map((_, i) => `[v${i}]`).join('')}concat=n=${plan.length}:v=1:a=0[${cutLabel}]`);
overlays.forEach((_, k) => {
const out = k === overlays.length - 1 ? 'outv' : `cut${k + 1}`;
filters.push(`[cut${k}][${audioIdx + 1 + k}:v]overlay=eof_action=pass:format=auto[${out}]`);
});
- const videoTotal = clips.reduce((s, c) => s + (c.outSec - c.inSec), 0);
+ const videoTotal = plan[plan.length - 1].endSec;
const totalDuration = audioDurationSec != null ? Math.min(videoTotal, audioDurationSec) : videoTotal;
+ const sections = plan.map(({ c, startSec, endSec }) => ({ sceneId: c.sceneId, layer: c.layer || 'footage', startSec, endSec }));
const args = [
...inputs,
@@ -319,7 +423,20 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
'-y',
outputPath,
];
- return { args, totalDuration, canonW, canonH, fps };
+ return { args, totalDuration, canonW, canonH, fps, sections };
+}
+
+// A title card's text (#8985) is drawn by the typography layer for exactly
+// its section on the output timebase, clipped to the rendered video.
+export function sectionCardCues(clips, sections, durationSec) {
+ const textBySceneId = new Map(clips.filter((c) => c.layer === 'card' && c.cardText).map((c) => [c.sceneId, c.cardText]));
+ return sections
+ .filter((section) => textBySceneId.has(section.sceneId) && section.startSec < durationSec)
+ .map((section) => ({
+ id: `card-${section.sceneId}`, text: textBySceneId.get(section.sceneId),
+ startSec: section.startSec, endSec: Math.min(section.endSec, durationSec),
+ template: 'fade', placement: 'center', emphasis: 'hero',
+ }));
}
export async function renderMusicVideo(projectId) {
@@ -343,7 +460,10 @@ export async function renderMusicVideo(projectId) {
if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
const audioPath = await resolveMasterAudioPath(project);
- const rawClips = await resolveSceneClips(project);
+ // #8985: a composed render cuts still and card sections into the same
+ // timebase as the footage; plain concat renders footage only, as before.
+ const composed = project.composition?.mode === 'composed';
+ const rawClips = await resolveSceneClips(project, { layered: composed });
const audioDurationSec = await probeVideoDuration(audioPath).catch(() => null);
const beats = project.audioAnalysis?.beats;
const clips = beatSnapClips(rawClips, beats, { scenes: project.scenes });
@@ -363,10 +483,12 @@ export async function renderMusicVideo(projectId) {
const jobId = randomUUID();
const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;
const outputPath = join(PATHS.videos, filename);
- const { args, totalDuration, canonW, canonH, fps } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec });
- // #8984: a composed project lays its timed text cues over the cut. No
- // renderable cue (plain mode, or nothing timed) renders exactly as before.
- const cues = renderableCues(project.composition, totalDuration);
+ const { args, totalDuration, canonW, canonH, fps, sections } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed });
+ // #8984: a composed project lays its timed text cues over the cut, and a
+ // title card's text (#8985) joins them over its own section. No renderable
+ // cue (plain mode, or nothing timed) skips the overlay capture entirely.
+ const cues = [...renderableCues(project.composition, totalDuration), ...sectionCardCues(clips, sections, totalDuration)]
+ .sort((a, b) => a.startSec - b.startSec);
const composition = cues.length > 0 ? project.composition : null;
const job = { id: jobId, projectId, status: 'running', clients: [], process: null, totalDuration };
@@ -540,8 +662,8 @@ export async function renderMusicVideo(projectId) {
signal.throwIfAborted();
// Capture is over: from here a cancel kills the encode (job.process).
job.overlayAbort = null;
- const composed = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays });
- startEncode(composed.args, 0.5);
+ const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true });
+ startEncode(layered.args, 0.5);
}).catch(async (err) => {
const canceled = signal.aborted;
job.status = canceled ? 'canceled' : 'error';
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index 05dbfaf8da..ff715b222d 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -45,7 +45,7 @@ vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));
vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));
vi.mock('../../lib/fileUtils.js', () => ({
ensureDir: vi.fn(async () => {}),
- PATHS: { videos: '/data/videos', videoThumbnails: '/data/thumbs', music: '/data/music', data: '/data' },
+ PATHS: { videos: '/data/videos', videoThumbnails: '/data/thumbs', music: '/data/music', images: '/data/images', data: '/data' },
}));
vi.mock('../../lib/sseUtils.js', () => ({
broadcastSse: vi.fn(),
@@ -392,3 +392,59 @@ describe('composed render lifecycle (#8984)', () => {
expect(cancelRender(jobId)).toBe(false);
});
});
+
+// #8985 — per-scene visual layers. A composed render cuts a still (its
+// reference frame, moved deterministically) and a code-rendered title card
+// into the footage timebase without needing footage for either; a plain
+// concat render ignores the layer choice entirely.
+describe('layered sections (#8985)', () => {
+ const layeredScenes = [
+ { sceneId: 's1', order: 0, videoHistoryId: 'h1' },
+ { sceneId: 's2', order: 1, visualLayer: 'still', stillMove: 'pan', referenceImageId: 'frame.png', videoHistoryId: 'h1', startSec: 2, endSec: 4 },
+ { sceneId: 's3', order: 2, visualLayer: 'card', cardText: 'Verse two', cardColor: '#112233', videoHistoryId: null, startSec: 4, endSec: 5.01 },
+ ];
+ const primeLayered = (projectId, mode, scenes = layeredScenes) => {
+ prime(projectId);
+ getProject.mockResolvedValue({
+ id: projectId, name: 'P', trackId: 't1', status: 'ready', scenes,
+ composition: { version: 1, mode, textCues: [], style: { color: '#ffffff', font: 'sans' }, posterSec: null },
+ });
+ };
+ const filterGraph = (args) => args[args.indexOf('-filter_complex') + 1];
+
+ it('keeps a concat render on footage only: the still scene plays its clip and the footage-less card is skipped', async () => {
+ primeLayered('plain-layers', 'concat');
+ await renderMusicVideo('plain-layers');
+ const { args } = lastProc();
+ expect(args).not.toContain('/data/images/frame.png');
+ expect(filterGraph(args)).not.toContain('color=');
+ expect(filterGraph(args)).toContain('concat=n=2:v=1:a=0[outv]');
+ expect(h.overlays.calls).toHaveLength(0);
+ });
+
+ it('cuts footage, a still and a titled card on one frame grid and draws the card text over its section', async () => {
+ primeLayered('layers-1', 'composed');
+ const { jobId } = await renderMusicVideo('layers-1');
+ // The card's title is captured for exactly its section: [2s clip][2s still][1.01s card → 24 frames].
+ expect(h.overlays.calls[0]).toMatchObject({ jobId, width: 768, height: 512,
+ cues: [{ id: 'card-s3', text: 'Verse two', startSec: 4, endSec: 5, placement: 'center', emphasis: 'hero' }] });
+ h.overlays.resolve([{ path: '/data/overlay-0.mov', startSec: 4, durationSec: 1 }]);
+ await tick();
+ const { args } = lastProc();
+ expect(args.slice(args.indexOf('-loop'), args.indexOf('-loop') + 6)).toEqual(['-loop', '1', '-framerate', '24', '-i', '/data/images/frame.png']);
+ const graph = filterGraph(args);
+ expect(graph).toContain('trim=end_frame=48,setpts=PTS-STARTPTS[v0]');
+ expect(graph).toMatch(/crop=768:512:x='\(iw-ow\)\*n\/47'.*trim=end_frame=48,setpts=PTS-STARTPTS\[v1\]/);
+ expect(graph).toContain('color=c=0x112233:s=768x512:r=24,setsar=1,format=yuv420p,trim=end_frame=24,setpts=PTS-STARTPTS[v2]');
+ // The song is still the one and only audio: two section inputs, then the master.
+ expect(args[args.lastIndexOf('-map') + 1]).toBe('2:a');
+ });
+
+ it('refuses a still with no reference frame and an untimed card, without spawning', async () => {
+ primeLayered('no-frame', 'composed', [{ sceneId: 's1', order: 0, visualLayer: 'still', referenceImageId: null, startSec: 0, endSec: 2 }]);
+ await expect(renderMusicVideo('no-frame')).rejects.toMatchObject({ status: 404, code: 'MISSING_STILLS', context: { sceneIds: ['s1'] } });
+ primeLayered('untimed', 'composed', [{ sceneId: 's1', order: 0, visualLayer: 'card', cardText: 'Hi', startSec: null, endSec: null }]);
+ await expect(renderMusicVideo('untimed')).rejects.toMatchObject({ status: 422, code: 'UNTIMED_SECTIONS', context: { sceneIds: ['s1'] } });
+ expect(h.procs).toHaveLength(0);
+ });
+});