Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: render full-length music videos with the master song (#9075)
[._.]/ Adam Eivy2afa47870520
diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 62f257656b..77913870c0 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2536,32 +2536,40 @@ export const htmlCompositionBeatsQuerySchema = z.object({musicTrack: z.string().min(1).max(255).regex(/^[^/\\]+$/, 'musicTrack must be a Music-library filename'),}).strict();-export const htmlCompositionContractSchema = z.object({- durationSec: z.number().min(1).max(120),- fps: z.number().int().min(12).max(60),- width: z.number().int(),- height: z.number().int(),- // Subframes averaged per output frame to fake motion blur on fast moves.- // The integer form (1 default) keeps the existing tmix path byte for byte;- // the object form (#9077) samples a centred shutter in linear light, with a- // fixed count or 'auto' refinement that stops once the average converges.- motionBlur: z.union([- z.number().int().min(1).max(4),- z.object({- shutter: z.number().min(0.05).max(1).default(0.5),- samples: z.union([z.literal('auto'), z.number().int().min(4).max(64)]).default('auto'),- tolerance: z.number().min(1).max(8).default(2),- }).strict(),- ]).default(1),- // Extra sizes this one timeline can render (#8960), reframed by the optional- // layout({ width, height }) hook before each format's first seek.- formats: z.array(z.enum(Object.values(LAUNCH_VIDEO_FORMAT_SIZES))).min(1).max(LAUNCH_VIDEO_FORMATS.length).optional(),- layout: z.boolean().default(false),-}).superRefine((value, ctx) => {- if (!['1920x1080', '1080x1920', '1080x1080', '1280x720'].includes(`${value.width}x${value.height}`)) {- ctx.addIssue({ code: 'custom', path: ['width'], message: 'width/height must be 1920x1080, 1080x1920, 1080x1080 or 1280x720' });- }- if (Math.abs(value.durationSec * value.fps - Math.round(value.durationSec * value.fps)) > 1e-8) {- ctx.addIssue({ code: 'custom', path: ['durationSec'], message: 'durationSec × fps must be a whole number of frames' });- }-});+// Public renders stay capped at 120s. A music-video owner passes a higher+// ceiling (the song length, hard-capped by the caller at 900s) and gets the+// same frame rules. superRefine lives on this factory because the exported+// schema is a ZodEffects and cannot be extended in place.+export function htmlCompositionContractSchemaFor(maxDurationSec = 120) {+ return z.object({+ durationSec: z.number().min(1).max(maxDurationSec),+ fps: z.number().int().min(12).max(60),+ width: z.number().int(),+ height: z.number().int(),+ // Subframes averaged per output frame to fake motion blur on fast moves.+ // The integer form (1 default) keeps the existing tmix path byte for byte;+ // the object form (#9077) samples a centred shutter in linear light, with a+ // fixed count or 'auto' refinement that stops once the average converges.+ motionBlur: z.union([+ z.number().int().min(1).max(4),+ z.object({+ shutter: z.number().min(0.05).max(1).default(0.5),+ samples: z.union([z.literal('auto'), z.number().int().min(4).max(64)]).default('auto'),+ tolerance: z.number().min(1).max(8).default(2),+ }).strict(),+ ]).default(1),+ // Extra sizes this one timeline can render (#8960), reframed by the optional+ // layout({ width, height }) hook before each format's first seek.+ formats: z.array(z.enum(Object.values(LAUNCH_VIDEO_FORMAT_SIZES))).min(1).max(LAUNCH_VIDEO_FORMATS.length).optional(),+ layout: z.boolean().default(false),+ }).superRefine((value, ctx) => {+ if (!['1920x1080', '1080x1920', '1080x1080', '1280x720'].includes(`${value.width}x${value.height}`)) {+ ctx.addIssue({ code: 'custom', path: ['width'], message: 'width/height must be 1920x1080, 1080x1920, 1080x1080 or 1280x720' });+ }+ if (Math.abs(value.durationSec * value.fps - Math.round(value.durationSec * value.fps)) > 1e-8) {+ ctx.addIssue({ code: 'custom', path: ['durationSec'], message: 'durationSec × fps must be a whole number of frames' });+ }+ });+}++export const htmlCompositionContractSchema = htmlCompositionContractSchemaFor(120);diff --git a/server/routes/htmlComposition.test.js b/server/routes/htmlComposition.test.jsindex 70385b484c..31cea23a8e 100644--- a/server/routes/htmlComposition.test.js+++ b/server/routes/htmlComposition.test.js@@ -20,6 +20,20 @@ app.use('/api/html-composition', router);app.use(errorMiddleware);describe('HTML composition admission', () => {+ it('drops the music-video owner option from the public render body', async () => {+ enqueueJob.mockClear();+ const response = await request(app).post('/api/html-composition/render').send({+ directory: 'compositions/example',+ owner: 'music-video',+ audio: { path: '/tmp/master.wav', startSec: 60 },+ maxDurationSec: 900,+ durationSec: 180,+ song: { features: [] },+ });+ expect(response.status).toBe(202);+ expect(enqueueJob).toHaveBeenCalledWith({ kind: 'html-composition', params: { directory: 'compositions/example' } });+ });+it('accepts local composition assets and optional library music as a local-only media job', async () => {const params = { directory: 'compositions/example', musicTrack: 'example.wav' };const response = await request(app).post('/api/html-composition/render').send(params);diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.jsindex 98c308bca6..41a5619f3f 100644--- a/server/services/htmlComposition/encode.js+++ b/server/services/htmlComposition/encode.js@@ -20,13 +20,17 @@ async function frameFormat(page, { width, height, layout }) {// Stream one frame at a time. The write callback supplies back-pressure and// the terminal race releases a pending write on exit, disconnect or cancel.-export async function encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress } = {}) {+export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress } = {}) {const ffmpeg = await findFfmpeg();if (!ffmpeg) throw new Error('ffmpeg not found on PATH');const tag = await bt709TagFilter();signal?.throwIfAborted();const { fps, durationSec, width, height, motionBlur } = contract;const numFrames = Math.round(durationSec * fps);+ // Music-video masters are cut once (`-ss` / `-t`) and muxed whole. Library+ // beds keep the launch-video loop and half-second tail fade.+ const exactAudio = audio?.path ? audio : null;+ if (exactAudio && musicPath) throw new Error('Music-video audio replaces library music');// Integer motionBlur (1-4) captures that many subframes per output frame and// lets ffmpeg's tmix filter blend them; 1 (default) captures/encodes exactly// as before, byte for byte. The object form (#9077) blends in Node instead@@ -39,9 +43,11 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,await frameFormat(page, contract);const input = shutter ? ['-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', `${width}x${height}`] : ['-f', 'image2pipe', '-vcodec', 'png'];const args = ['-hide_banner', '-loglevel', 'error', ...input, '-framerate', String(fps * sub), '-i', 'pipe:0'];- if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);+ if (exactAudio) args.push('-ss', String(exactAudio.startSec ?? 0), '-t', String(durationSec), '-i', exactAudio.path);+ else if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);args.push('-map', '0:v', '-vf', [motionBlurFilter, 'scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','), ...H264_ENCODE_ARGS, ...BT709_CONTAINER_ARGS);- if (musicPath) args.push('-map', '1:a', '-af', `atrim=duration=${durationSec},asetpts=PTS-STARTPTS,afade=t=out:st=${durationSec - 0.5}:d=0.5`, ...AAC_ENCODE_ARGS);+ if (exactAudio) args.push('-map', '1:a', ...AAC_ENCODE_ARGS);+ else if (musicPath) args.push('-map', '1:a', '-af', `atrim=duration=${durationSec},asetpts=PTS-STARTPTS,afade=t=out:st=${durationSec - 0.5}:d=0.5`, ...AAC_ENCODE_ARGS);args.push('-frames:v', String(numFrames), '-t', String(durationSec), '-movflags', '+faststart', '-y', outputPath);const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));let stderr = '';@@ -55,6 +61,15 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,});// Attach a rejection handler before the first browser round trip.finished.catch(() => {});+ // One watcher for the whole job. A per-frame `.then` on `finished` piles up+ // handlers for a song-length capture (600s at 12fps is 7200 of them).+ let failEncoder;+ const encoderStopped = new Promise((_, reject) => { failEncoder = reject; });+ encoderStopped.catch(() => {});+ finished.then(+ () => failEncoder(new Error('ffmpeg exited before capture completed')),+ (error) => failEncoder(error),+ );const stop = () => {if (!exited && !stopping) {stopping = true;@@ -73,7 +88,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,};const write = bytes => Promise.race([new Promise((resolve, reject) => proc.stdin.write(bytes, error => error ? reject(error) : resolve())),- finished.then(() => { throw new Error('ffmpeg exited before capture completed'); }),+ encoderStopped,]);const toRgb = png => sharp(png).removeAlpha().raw().toBuffer();// Output frames per sub-frame count: where a shutter render spent its time.@@ -102,7 +117,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,} else {for (let k = 0; k < sub; k++) await write(await capture(n / fps + k / (fps * sub)));}- onProgress?.((n + 1) / numFrames);+ onProgress?.((n + 1) / numFrames, { frame: n + 1, frames: numFrames });}proc.stdin.end();await finished;diff --git a/server/services/htmlComposition/encode.musicVideo.test.js b/server/services/htmlComposition/encode.musicVideo.test.jsnew file mode 100644index 0000000000..ca1367317b--- /dev/null+++ b/server/services/htmlComposition/encode.musicVideo.test.js@@ -0,0 +1,93 @@+import { EventEmitter } from 'node:events';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { describe, expect, it, vi } from 'vitest';++const { spawned } = vi.hoisted(() => ({ spawned: [] }));+vi.mock('../../lib/childProcess.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ spawn: (_bin, args) => {+ const proc = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.stdin = new EventEmitter();+ let bytes = 0;+ proc.stdin.write = (buf, cb) => { bytes += buf.length; cb?.(); return true; };+ proc.stdin.end = () => { proc.emit('close', 0); };+ proc.kill = () => {};+ spawned.push({ args, bytes: () => bytes });+ return proc;+ },+ };+});+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, findFfmpeg: async () => '/usr/bin/ffmpeg', bt709TagFilter: async () => 'format=yuv420p' };+});+vi.mock('../../lib/killWithEscalation.js', () => ({ killWithEscalation: () => {} }));++const { encodeComposition } = await import('./encode.js');++const FRAME = Buffer.alloc(4 * 1024, 7).toString('base64');+const page = {+ check() {},+ async evaluate() {},+ async send(method) {+ if (method === 'Emulation.setDeviceMetricsOverride') return {};+ return { data: FRAME };+ },+};+const contract = (durationSec) => ({ fps: 12, durationSec, width: 1280, height: 720, motionBlur: 1 });++describe('encodeComposition music-video audio', () => {+ it('keeps the launch-video loop and tail fade when given a library bed', async () => {+ spawned.length = 0;+ await encodeComposition(page, contract(1), '/tmp/launch.mp4', { musicPath: '/library/bed.wav' });+ const args = spawned[0].args;+ expect(args).toContain('-stream_loop');+ expect(args.join(' ')).toContain('afade=t=out:st=0.5:d=0.5');+ expect(args).not.toContain('-ss');+ });++ it('cuts the master at the in-point with no loop and no fade', async () => {+ spawned.length = 0;+ await encodeComposition(page, contract(15), '/tmp/excerpt.mp4', { audio: { path: '/masters/song.wav', startSec: 60 } });+ const args = spawned[0].args;+ const audioAt = args.indexOf('/masters/song.wav');+ expect(args.slice(audioAt - 5, audioAt + 1)).toEqual(['-ss', '60', '-t', '15', '-i', '/masters/song.wav']);+ expect(args).not.toContain('-stream_loop');+ expect(args.join(' ')).not.toContain('afade');+ expect(args).toContain('-frames:v');+ });++ it('does not retain per-frame buffers across a long synthetic job', async () => {+ // Forced GC is what makes "not retained" observable. Re-exec once under+ // --expose-gc so a normal vitest run still executes the measurement.+ if (typeof global.gc !== 'function') {+ if (process.env.PORTOS_GC_CHILD === '1') throw new Error('forced GC was not available in the vitest worker');+ const serverRoot = fileURLToPath(new URL('../..', import.meta.url));+ const vitestBin = fileURLToPath(new URL('../../node_modules/vitest/vitest.mjs', import.meta.url));+ const result = spawnSync(process.execPath, [vitestBin, 'run', 'services/htmlComposition/encode.musicVideo.test.js', '-t', 'per-frame buffers'], {+ cwd: serverRoot, encoding: 'utf8', timeout: 180000,+ env: { ...process.env, PORTOS_GC_CHILD: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS || ''} --expose-gc`.trim() },+ });+ expect(result.status, result.stderr || result.stdout).toBe(0);+ return;+ }+ spawned.length = 0;+ const samples = [];+ await encodeComposition(page, contract(600), '/tmp/long.mp4', {+ onProgress: (_fraction, detail) => {+ if (detail.frame === 400 || detail.frame === 7200) {+ global.gc();+ samples.push(process.memoryUsage().heapUsed);+ }+ },+ });+ expect(spawned[0].bytes()).toBeGreaterThan(0);+ expect(samples).toHaveLength(2);+ // Frames 401–7200 of retained 4 KiB screenshots stay well over 12 MiB after GC.+ expect(samples[1] - samples[0]).toBeLessThan(12 * 1024 * 1024);+ }, 200000);+});diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.jsindex 733e8fa7c7..d00f876b7b 100644--- a/server/services/htmlComposition/index.js+++ b/server/services/htmlComposition/index.js@@ -1,10 +1,10 @@-import { dirname, join, resolve } from 'node:path';-import { lstat, mkdtemp, open, realpath, rm, writeFile } from 'node:fs/promises';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import { cp, lstat, mkdtemp, open, realpath, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { createReadStream } from 'node:fs';import { pipeline } from 'node:stream/promises';import { PATHS, ensureDir, unlinkGuarded } from '../../lib/fileUtils.js';-import { LAUNCH_VIDEO_FORMATS, LAUNCH_VIDEO_FORMAT_SIZES, htmlCompositionContractSchema, htmlCompositionRenderSchema, validateRequest } from '../../lib/validation.js';+import { LAUNCH_VIDEO_FORMATS, LAUNCH_VIDEO_FORMAT_SIZES, htmlCompositionContractSchema, htmlCompositionContractSchemaFor, htmlCompositionRenderSchema, validateRequest } from '../../lib/validation.js';import { generateThumbnail } from '../../lib/ffmpeg.js';import { videoGenEvents } from '../videoGen/events.js';import { mutateVideoHistory } from '../videoGen/history.js';@@ -14,6 +14,72 @@ import { encodeComposition, encodeContactSheet, proofTimes, synthesizeCompositioimport { validateLaunchVideoAssets } from '../../lib/launchVideoValidation.js';const active = new Map();+// A music-video owner may run as long as its song, and no longer than this.+const MUSIC_VIDEO_DURATION_CAP_SEC = 900;+const MUSIC_VIDEO_OWNER = 'music-video';++function insideData(root, path) {+ const rel = relative(root, path);+ return Boolean(rel) && rel !== '..' && !rel.startsWith(`..${sep}`) && !rel.startsWith('../') && !isAbsolute(rel);+}++// A missing feature block is null. An array (including []) is not a feature+// track — #9073's block is an object, and "not analyzed" must not look like+// a measured empty track.+function normalizeSongDocument(song) {+ const source = song && typeof song === 'object' && !Array.isArray(song) ? song : {};+ const features = source.features;+ return {+ beats: Array.isArray(source.beats) ? source.beats : [],+ downbeats: Array.isArray(source.downbeats) ? source.downbeats : [],+ sections: Array.isArray(source.sections) ? source.sections : [],+ features: features !== null && typeof features === 'object' && !Array.isArray(features) ? features : null,+ words: Array.isArray(source.words) ? source.words : null,+ };+}++async function resolveMusicVideoOwner({ owner, audio, maxDurationSec }) {+ if (owner == null) return null;+ if (owner !== MUSIC_VIDEO_OWNER) throw new Error('Unknown composition owner');+ if (!audio || typeof audio.path !== 'string' || !audio.path || audio.path.includes('\0')) {+ throw new Error('Music-video renders require an audio master path');+ }+ const startSec = audio.startSec ?? 0;+ if (!Number.isFinite(startSec) || startSec < 0) throw new Error('audio.startSec must be a non-negative number');+ if (!Number.isFinite(maxDurationSec) || maxDurationSec < 1) throw new Error('maxDurationSec must be the song duration');+ let info;+ try { info = await stat(audio.path); } catch (error) {+ if (error.code === 'ENOENT') throw new Error('Music-video audio master is missing');+ throw error;+ }+ if (!info.isFile()) throw new Error('Music-video audio master must be a regular file');+ return {+ audio: { path: audio.path, startSec },+ maxDurationSec: Math.min(MUSIC_VIDEO_DURATION_CAP_SEC, maxDurationSec),+ };+}++// Copy the composition into this job's scratch directory and write song.json+// before openComposition freezes the snapshot. The page fetches it by relative+// URL, so the network-refusing sandbox stays unchanged.+async function stageMusicVideoComposition(sourceDirectory, jobId, song) {+ if (typeof jobId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(jobId)) throw new Error('Invalid composition job id');+ const root = await realpath(PATHS.data);+ const source = await realpath(resolve(root, sourceDirectory));+ if (!insideData(root, source)) throw new Error('directory must be inside data');+ const scratchRoot = join(root, 'music-video-song-renders', jobId);+ try {+ await rm(scratchRoot, { recursive: true, force: true });+ const compositionDir = join(scratchRoot, 'composition');+ await ensureDir(scratchRoot);+ await cp(source, compositionDir, { recursive: true, verbatimSymlinks: true });+ await writeFile(join(compositionDir, 'song.json'), `${JSON.stringify(normalizeSongDocument(song))}\n`);+ return { directory: `music-video-song-renders/${jobId}/composition`, scratchRoot };+ } catch (error) {+ await rm(scratchRoot, { recursive: true, force: true });+ throw error;+ }+}export function cancel(jobId) {const job = active.get(jobId);@@ -56,12 +122,13 @@ function deliveryNames(targets) {return names;}-export async function renderComposition({ jobId, ...input }) {+export async function renderComposition({ jobId, owner, audio, maxDurationSec, song, ...input }) {const job = { controller: new AbortController(), committing: false };active.set(jobId, job);const { signal } = job.controller;let page;let audioDirectory;+ let scratchRoot;let success = false;let result;let failure;@@ -75,7 +142,14 @@ export async function renderComposition({ jobId, ...input }) {try { await write(handle); } finally { await handle.close(); }};try {- const { directory, musicTrack, launchVideo, synthesizeMusic, proof, formats } = validateRequest(htmlCompositionRenderSchema, input);+ const musicVideo = await resolveMusicVideoOwner({ owner, audio, maxDurationSec });+ const parsedInput = validateRequest(htmlCompositionRenderSchema, input);+ let { directory } = parsedInput;+ const sourceDirectory = directory;+ const { musicTrack, launchVideo, synthesizeMusic, proof, formats } = parsedInput;+ if (musicVideo && (launchVideo || synthesizeMusic || musicTrack || proof || formats)) {+ throw new Error('A music-video composition render cannot use launch-video, proof, or library-music options');+ }let musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;if (musicTrack && !musicPath) throw new Error('musicTrack is missing from the Music library');signal.throwIfAborted();@@ -92,6 +166,12 @@ export async function renderComposition({ jobId, ...input }) {const needsLaunchGate = launchVideo || directory.split('/')[0] === 'launch-videos';// One page and one frozen snapshot per job: the privacy and storyboard// gates run once however many formats render from it.+ if (musicVideo) {+ const staged = await stageMusicVideoComposition(directory, jobId, song);+ directory = staged.directory;+ scratchRoot = staged.scratchRoot;+ signal.throwIfAborted();+ }page = await openComposition(directory, { signal, validateAssets: needsLaunchGate? assets => { launchPlan = validateLaunchVideoAssets(assets, launchVideo); launchAssets = assets; }: undefined });@@ -101,7 +181,10 @@ export async function renderComposition({ jobId, ...input }) {return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, motionBlur: c.motionBlur,formats: c.formats, layout: typeof c.layout === 'function' };})()`);- const parsed = htmlCompositionContractSchema.safeParse(metadata);+ const contractSchema = musicVideo+ ? htmlCompositionContractSchemaFor(musicVideo.maxDurationSec)+ : htmlCompositionContractSchema;+ const parsed = contractSchema.safeParse(metadata);if (!parsed.success) throw new Error(parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '));const contract = parsed.data;if (launchPlan && Math.abs(contract.durationSec - launchPlan.durationSec) > 1e-8) {@@ -154,14 +237,37 @@ export async function renderComposition({ jobId, ...input }) {await writeFile(musicPath, wav, { flag: 'wx' });}await ensureDir(PATHS.videos);+ const frameCount = (item) => Math.round(item.durationSec * item.fps);+ const framesTotal = targets.reduce((sum, target) => sum + frameCount(target.contract), 0);+ let framesDone = 0;+ const startedAt = Date.now();const rendered = [];- for (const [index, target] of targets.entries()) {+ for (const target of targets) {const filename = `composition-${target.id}.mp4`;const outputPath = join(PATHS.videos, filename);+ const targetFrames = frameCount(target.contract);ownedPaths.push(outputPath, join(PATHS.videoThumbnails, `${target.id}.jpg`));- const { sampleHistogram } = await encodeComposition(page, target.contract, outputPath, { musicPath, signal, onProgress: progress => {- videoGenEvents.emit('progress', { generationId: jobId, progress: (index + progress) / targets.length * 0.95 });- } });+ const { sampleHistogram } = await encodeComposition(page, target.contract, outputPath, {+ musicPath: musicVideo ? null : musicPath,+ audio: musicVideo?.audio,+ signal,+ onProgress: (fraction, detail) => {+ const done = framesDone + (detail?.frame ?? Math.round(fraction * targetFrames));+ const elapsed = Date.now() - startedAt;+ const etaMs = done > 0 && done < framesTotal && elapsed > 0+ ? Math.max(1, Math.round(elapsed * (framesTotal - done) / done))+ : undefined;+ videoGenEvents.emit('progress', {+ generationId: jobId,+ progress: framesTotal ? (done / framesTotal) * 0.95 : 0,+ step: done,+ totalSteps: framesTotal,+ ...(etaMs != null ? { etaMs } : {}),+ message: `Rendering frame ${done}/${framesTotal}`,+ });+ },+ });+ framesDone += targetFrames;page.check();rendered.push({ ...target, filename, outputPath, sampleHistogram });}@@ -201,7 +307,7 @@ export async function renderComposition({ jobId, ...input }) {// One Media History entry per format, linked by launchVideo.runId and// written in a single mutation so a run registers all formats or none.const metas = rendered.map(video => ({- id: video.id, prompt: `HTML composition: ${directory}`, modelId: 'html-composition', seed: 0,+ id: video.id, prompt: `HTML composition: ${sourceDirectory}`, modelId: 'html-composition', seed: 0,...frameOf(video.contract), numFrames: Math.round(contract.durationSec * contract.fps),...(launchMetadata ? { launchVideo: launchMetadata, appId: launchMetadata.appId, posterSec: launchPlan.posterSec } : {}),filename: video.filename, thumbnail: video.thumbnail, createdAt,@@ -225,6 +331,9 @@ export async function renderComposition({ jobId, ...input }) {if (audioDirectory) await rm(audioDirectory, { recursive: true, force: true }).catch(() => {console.warn('⚠️ Could not remove temporary composition audio');});+ if (scratchRoot) await rm(scratchRoot, { recursive: true, force: true }).catch(() => {+ console.warn('⚠️ Could not remove temporary music-video composition');+ });if (!success) {for (const path of ownedPaths) await unlinkGuarded(path).catch(() => {});}diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.jsindex d2dddce142..3794206397 100644--- a/server/services/htmlComposition/index.test.js+++ b/server/services/htmlComposition/index.test.js@@ -6,7 +6,7 @@ import { randomUUID } from 'node:crypto';import { execFileSync, spawn } from 'node:child_process';import { chromium } from 'playwright-core';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';-import { findFfmpeg, probeVideoStreamInfo } from '../../lib/ffmpeg.js';+import { findFfmpeg, probeVideoDuration, probeVideoStreamInfo } from '../../lib/ffmpeg.js';import { PATHS } from '../../lib/fileUtils.js';import { loadHistory } from '../videoGen/history.js';import { videoGenEvents } from '../videoGen/events.js';@@ -368,4 +368,99 @@ globalThis.portosComposition = { durationSec:1, fps:12, width:1280, height:720,finally { videoGenEvents.off('progress', onProgress); await closed; }expect((await readdir(PATHS.videos)).some(name => name.includes(input.jobId))).toBe(false);});++ const pcmOf = (path, extra = []) => execFileSync(ffmpeg, ['-v', 'error', ...extra, '-i', path, '-vn', '-f', 'f32le', '-ac', '1', '-ar', '48000', '-'], { maxBuffer: 64 * 1024 * 1024 });+ const rms = (pcm, startSec, endSec) => {+ const from = Math.floor(startSec * 48000);+ const to = Math.min(pcm.length / 4, Math.floor(endSec * 48000));+ let sum = 0;+ for (let n = from; n < to; n++) sum += pcm.readFloatLE(n * 4) ** 2;+ return Math.sqrt(sum / Math.max(1, to - from));+ };++ it('reads song.json inside the sandbox and treats a missing feature block as null', async () => {+ const html = `<!doctype html><html><body style="margin:0"><script>+ globalThis.portosComposition = { durationSec: 1, fps: 12, width: 1280, height: 720,+ async seek() {+ const song = await (await fetch('song.json')).json();+ const ok = song.features === null && !Array.isArray(song.features) && song.beats[0] === 0 && song.words[0].w === 'go';+ document.body.style.background = ok ? 'rgb(0,255,0)' : 'rgb(255,0,0)';+ } };+ </script></body></html>`;+ const input = await composition(html);+ await mkdir(PATHS.music, { recursive: true });+ const master = join(PATHS.music, 'song-null-features.wav');+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1', '-y', master]);+ const result = await renderComposition({+ ...input, owner: 'music-video', audio: { path: master, startSec: 0 }, maxDurationSec: 180,+ song: { beats: [0], downbeats: [0], sections: [], features: [], words: [{ w: 'go', startSec: 0, endSec: 0.4, conf: 'matched' }] },+ });+ const pixel = execFileSync(ffmpeg, ['-v', 'error', '-i', join(PATHS.videos, result.filename), '-frames:v', '1', '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);+ expect(pixel[1]).toBeGreaterThan(200);+ expect(pixel[0]).toBeLessThan(40);+ expect(existsSync(join(PATHS.data, input.directory, 'song.json'))).toBe(false);+ }, 30000);++ it('renders a 180s song without looping or fading the master', async () => {+ const html = `<!doctype html><html><body style="margin:0"><script>+ globalThis.portosComposition = { durationSec: 180, fps: 12, width: 1280, height: 720, async seek() {} };+ </script></body></html>`;+ const input = await composition(html);+ await mkdir(PATHS.music, { recursive: true });+ const master = join(PATHS.music, 'song-180.wav');+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=180', '-y', master]);+ const frames = [];+ const onProgress = (event) => { if (event.generationId === input.jobId) frames.push(event); };+ videoGenEvents.on('progress', onProgress);+ let result;+ try { result = await renderComposition({ ...input, owner: 'music-video', audio: { path: master, startSec: 0 }, maxDurationSec: 180, song: { beats: [], features: null, words: null } }); }+ finally { videoGenEvents.off('progress', onProgress); }+ const output = join(PATHS.videos, result.filename);+ expect(await probeVideoStreamInfo(output)).toMatchObject({ frameCount: 180 * 12 });+ expect(Math.abs(await probeVideoDuration(output) - 180)).toBeLessThanOrEqual(1 / 12);+ const audio = pcmOf(output);+ expect(Math.abs(audio.length / 4 / 48000 - 180)).toBeLessThanOrEqual(1 / 12);+ expect(rms(audio, 179.85, 179.98)).toBeGreaterThan(rms(audio, 20, 20.5) * 0.5);+ expect(frames.some((event) => event.step > 0 && event.totalSteps === 2160 && event.etaMs > 0 && /Rendering frame \d+\/2160/.test(event.message))).toBe(true);+ }, 300000);++ it('muxes a 60–75s excerpt aligned to that range of the master', async () => {+ const html = `<!doctype html><html><body style="margin:0"><script>+ globalThis.portosComposition = { durationSec: 15, fps: 12, width: 1280, height: 720, async seek() {} };+ </script></body></html>`;+ const input = await composition(html);+ await mkdir(PATHS.music, { recursive: true });+ const master = join(PATHS.music, 'song-excerpt.wav');+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=60', '-f', 'lavfi', '-i', 'sine=frequency=880:duration=15', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=105', '-filter_complex', '[0][1][2]concat=n=3:v=0:a=1', '-y', master]);+ const result = await renderComposition({+ ...input, owner: 'music-video', audio: { path: master, startSec: 60 }, maxDurationSec: 180, song: { features: null },+ });+ const output = pcmOf(join(PATHS.videos, result.filename));+ const reference = pcmOf(master, ['-ss', '60', '-t', '15']);+ const opening = pcmOf(master, ['-ss', '0', '-t', '15']);+ const frameSamples = Math.round(48000 / 12);+ const samples = (buf) => buf.length / 4;+ const scoreAgainst = (other, lag) => {+ let sum = 0;+ let count = 0;+ const nOut = samples(output);+ const nOther = samples(other);+ for (let n = 0; n < nOut; n += 8) {+ const m = n + lag;+ if (m < 0 || m >= nOther) continue;+ sum += output.readFloatLE(n * 4) * other.readFloatLE(m * 4);+ count += 1;+ }+ return count ? sum / count : 0;+ };+ let bestLag = 0;+ let best = -Infinity;+ for (let lag = -frameSamples; lag <= frameSamples; lag += 40) {+ const value = scoreAgainst(reference, lag);+ if (value > best) { best = value; bestLag = lag; }+ }+ expect(Math.abs(bestLag)).toBeLessThanOrEqual(frameSamples);+ expect(best).toBeGreaterThan(Math.abs(scoreAgainst(opening, 0)) * 4);+ expect(await probeVideoStreamInfo(join(PATHS.videos, result.filename))).toMatchObject({ frameCount: 15 * 12 });+ }, 60000);});diff --git a/server/services/htmlComposition/musicVideoOwner.test.js b/server/services/htmlComposition/musicVideoOwner.test.jsnew file mode 100644index 0000000000..1a8389e520--- /dev/null+++ b/server/services/htmlComposition/musicVideoOwner.test.js@@ -0,0 +1,111 @@+import { afterAll, describe, expect, it, vi } from 'vitest';+import { mkdir, writeFile, access } from 'node:fs/promises';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';+import { htmlCompositionContractSchema, htmlCompositionContractSchemaFor } from '../../lib/validation.js';++const { seen } = vi.hoisted(() => ({ seen: [] }));+vi.mock('../../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-song-render-'),+}));+vi.mock('./browser.js', () => ({+ openComposition: async (directory) => {+ const { readFile } = await import('node:fs/promises');+ const { join: joinPath } = await import('node:path');+ const { PATHS } = await import('../../lib/fileUtils.js');+ try { seen.push(JSON.parse(await readFile(joinPath(PATHS.data, directory, 'song.json'), 'utf8'))); } catch { seen.push(null); }+ return { evaluate: async () => seen.contract, check() {}, close: async () => {} };+ },+}));+vi.mock('./encode.js', () => ({+ encodeComposition: vi.fn(async () => ({})),+ encodeContactSheet: vi.fn(),+ proofTimes: vi.fn(),+ synthesizeCompositionMusic: vi.fn(),+}));+vi.mock('../../lib/ffmpeg.js', () => ({ generateThumbnail: vi.fn(async () => { throw new Error('thumbnail skipped'); }) }));+vi.mock('../videoGen/history.js', () => ({ mutateVideoHistory: vi.fn() }));+vi.mock('../videoGen/events.js', () => ({ videoGenEvents: { emit: vi.fn(), on: vi.fn(), off: vi.fn() } }));+vi.mock('../pipeline/audioMux.js', () => ({ resolveMusicTrackPath: vi.fn(async () => null) }));++const { PATHS } = await import('../../lib/fileUtils.js');+const { renderComposition } = await import('./index.js');+const { encodeComposition } = await import('./encode.js');++const frame = { fps: 12, width: 1280, height: 720 };++async function sourceDir() {+ const directory = `compositions/${randomUUID()}`;+ await mkdir(join(PATHS.data, directory), { recursive: true });+ await writeFile(join(PATHS.data, directory, 'index.html'), '<html></html>');+ return directory;+}++describe('music-video composition owner', () => {+ afterAll(() => cleanupTempDataRoots());++ it('keeps the public contract at 120s and the owner ceiling at the song, hard-capped at 900s', () => {+ expect(htmlCompositionContractSchema.safeParse({ ...frame, durationSec: 120 }).success).toBe(true);+ expect(htmlCompositionContractSchema.safeParse({ ...frame, durationSec: 121 }).success).toBe(false);+ expect(htmlCompositionContractSchemaFor(180).safeParse({ ...frame, durationSec: 180 }).success).toBe(true);+ expect(htmlCompositionContractSchemaFor(180).safeParse({ ...frame, durationSec: 181 }).success).toBe(false);+ expect(htmlCompositionContractSchemaFor(900).safeParse({ ...frame, durationSec: 900 }).success).toBe(true);+ expect(htmlCompositionContractSchemaFor(900).safeParse({ ...frame, durationSec: 901 }).success).toBe(false);+ });++ it('writes song.json before the snapshot and removes the scratch copy afterwards', async () => {+ seen.length = 0;+ encodeComposition.mockClear();+ seen.contract = { ...frame, durationSec: 180 };+ const directory = await sourceDir();+ const jobId = randomUUID();+ const master = join(PATHS.data, 'master.wav');+ await writeFile(master, Buffer.alloc(16));+ await expect(renderComposition({+ jobId, directory, owner: 'music-video', audio: { path: master, startSec: 60 }, maxDurationSec: 180,+ song: { beats: [0, 1], downbeats: [0], sections: [{ label: 'verse', startSec: 0, endSec: 8 }], features: [], words: [{ w: 'go', startSec: 1, endSec: 1.2, conf: 'matched' }] },+ })).rejects.toThrow('thumbnail skipped');+ expect(seen[0]).toEqual({+ beats: [0, 1], downbeats: [0], sections: [{ label: 'verse', startSec: 0, endSec: 8 }],+ features: null, words: [{ w: 'go', startSec: 1, endSec: 1.2, conf: 'matched' }],+ });+ expect(encodeComposition).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ durationSec: 180 }), expect.any(String), expect.objectContaining({+ audio: { path: master, startSec: 60 }, musicPath: null,+ }));+ await expect(access(join(PATHS.data, directory, 'song.json'))).rejects.toThrow();+ await expect(access(join(PATHS.data, 'music-video-song-renders', jobId))).rejects.toThrow();+ });++ it('rejects a song-length page on the public path before capture', async () => {+ seen.length = 0;+ encodeComposition.mockClear();+ seen.contract = { ...frame, durationSec: 180 };+ const directory = await sourceDir();+ await expect(renderComposition({ jobId: randomUUID(), directory })).rejects.toThrow('durationSec');+ expect(seen[0]).toBeNull();+ expect(encodeComposition).not.toHaveBeenCalled();+ });++ it('rejects a composition longer than the 900s ceiling', async () => {+ encodeComposition.mockClear();+ seen.contract = { ...frame, durationSec: 901 };+ const directory = await sourceDir();+ const master = join(PATHS.data, 'master-long.wav');+ await writeFile(master, Buffer.alloc(8));+ await expect(renderComposition({+ jobId: randomUUID(), directory, owner: 'music-video', audio: { path: master, startSec: 0 }, maxDurationSec: 2000, song: {},+ })).rejects.toThrow('durationSec');+ expect(encodeComposition).not.toHaveBeenCalled();+ });++ it('does not let the owner option carry launch-video delivery', async () => {+ const directory = await sourceDir();+ const master = join(PATHS.data, 'master-launch.wav');+ await writeFile(master, Buffer.alloc(8));+ await expect(renderComposition({+ jobId: randomUUID(), directory, owner: 'music-video', audio: { path: master }, maxDurationSec: 30,+ launchVideo: { targetDurationSec: 15, appId: 'example', runId: 'run' },+ })).rejects.toThrow(/launch-video/);+ });+});diff --git a/server/services/musicVideo/compositionRender.js b/server/services/musicVideo/compositionRender.jsindex 3761d843bb..cbb294a3a4 100644--- a/server/services/musicVideo/compositionRender.js+++ b/server/services/musicVideo/compositionRender.js@@ -76,6 +76,54 @@ async function captureWindow(page, ffmpeg, { startSec, frames, fps, outputPath,* `width`×`height`, `fps` frame. Resolves `[{ path, startSec, durationSec }]` in* time order. `onProgress(0..1)` reports captured frames; `signal` cancels.*/+function musicVideoSongDocument(project) {+ const analysis = project?.audioAnalysis && typeof project.audioAnalysis === 'object' && !Array.isArray(project.audioAnalysis)+ ? project.audioAnalysis : {};+ let words = null;+ if (Array.isArray(project?.lyricCues)) {+ const collected = [];+ for (const cue of project.lyricCues) {+ if (!Array.isArray(cue?.words)) continue;+ words = collected;+ for (const word of cue.words) {+ if (!word || typeof word !== 'object') continue;+ collected.push({+ w: typeof word.w === 'string' ? word.w : '',+ startSec: Number.isFinite(word.startSec) ? word.startSec : null,+ endSec: Number.isFinite(word.endSec) ? word.endSec : null,+ conf: word.conf === 'matched' || word.conf === 'interpolated' ? word.conf : null,+ });+ }+ }+ }+ const features = analysis.features;+ return {+ beats: Array.isArray(analysis.beats) ? analysis.beats : [],+ downbeats: Array.isArray(analysis.downbeats) ? analysis.downbeats : [],+ sections: Array.isArray(analysis.sections) ? analysis.sections : [],+ features: features !== null && typeof features === 'object' && !Array.isArray(features) ? features : null,+ words,+ };+}++/**+ * Render one code-composition music video (or an excerpt of it) through the+ * HTML composition owner. `startSec` is the master's in-point (#8986); the+ * page's own duration is the rendered length. Song data is staged as song.json+ * before the composition snapshot freezes.+ */+export async function renderSongComposition({ project, directory, jobId, audioPath, startSec = 0 }) {+ const { renderComposition } = await import('../htmlComposition/index.js');+ return renderComposition({+ jobId,+ directory,+ owner: 'music-video',+ audio: { path: audioPath, startSec },+ maxDurationSec: Number(project?.audioAnalysis?.durationSec),+ song: musicVideoSongDocument(project),+ });+}+export async function renderTypographyOverlays({ jobId, cues, style, width, height, fps, durationSec, signal, onProgress }) {// Snap each window outward to the output frame grid so every overlay frame// lands exactly on a footage frame, and never past the video's last frame.diff --git a/server/services/musicVideo/compositionRender.song.test.js b/server/services/musicVideo/compositionRender.song.test.jsnew file mode 100644index 0000000000..75b5e2378e--- /dev/null+++ b/server/services/musicVideo/compositionRender.song.test.js@@ -0,0 +1,46 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('../htmlComposition/index.js', () => ({ renderComposition: vi.fn(async () => ({ generationId: 'job-1' })) }));++const { renderSongComposition } = await import('./compositionRender.js');+const { renderComposition } = await import('../htmlComposition/index.js');++describe('renderSongComposition', () => {+ it('calls the music-video owner with the master in-point and a null feature block', async () => {+ const project = {+ audioAnalysis: {+ durationSec: 180, beats: [0, 0.5], downbeats: [0],+ sections: [{ label: 'verse', startSec: 0, endSec: 8 }],+ features: [],+ },+ lyricCues: [{ text: 'go on', words: [{ w: 'go', startSec: 1, endSec: 1.2, conf: 'matched' }] }],+ };+ await renderSongComposition({+ project, directory: 'compositions/example', jobId: 'job-1', audioPath: '/data/music/song.wav', startSec: 60,+ });+ expect(renderComposition).toHaveBeenCalledWith({+ jobId: 'job-1',+ directory: 'compositions/example',+ owner: 'music-video',+ audio: { path: '/data/music/song.wav', startSec: 60 },+ maxDurationSec: 180,+ song: {+ beats: [0, 0.5],+ downbeats: [0],+ sections: [{ label: 'verse', startSec: 0, endSec: 8 }],+ features: null,+ words: [{ w: 'go', startSec: 1, endSec: 1.2, conf: 'matched' }],+ },+ });+ });++ it('leaves word timings null when no cue has been aligned', async () => {+ renderComposition.mockClear();+ await renderSongComposition({+ project: { audioAnalysis: { durationSec: 30, beats: [], downbeats: [], sections: [] }, lyricCues: [{ text: 'go' }] },+ directory: 'compositions/example', jobId: 'job-2', audioPath: '/data/music/song.wav',+ });+ expect(renderComposition.mock.calls[0][0].song.words).toBeNull();+ expect(renderComposition.mock.calls[0][0].audio.startSec).toBe(0);+ });+});diff --git a/server/services/musicVideo/render.code.test.js b/server/services/musicVideo/render.code.test.jsnew file mode 100644index 0000000000..64824ce66e--- /dev/null+++ b/server/services/musicVideo/render.code.test.js@@ -0,0 +1,50 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));+vi.mock('../../lib/ffmpeg.js', () => ({+ findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),+ safeUnder: (root, name) => (name ? `${root}/${name}` : null),+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),+ probeVideoDuration: vi.fn(async () => 30),+ probeVideoGeometry: vi.fn(async () => null),+}));+vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(), saveHistory: vi.fn(async () => {}), mutateVideoHistory: vi.fn() }));+vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));+vi.mock('./projects.js', () => ({ getProject: vi.fn(), updateProject: vi.fn(async () => ({})), listProjects: vi.fn(async () => []), mutateProjectRecord: vi.fn() }));+vi.mock('./compositionRender.js', () => ({+ renderTypographyOverlays: vi.fn(),+ removeCompositionScratch: vi.fn(),+ sweepCompositionScratch: vi.fn(),+ renderSongComposition: vi.fn(async () => ({ generationId: 'song-job' })),+}));++import { getProject } from './projects.js';+import { getTrack } from '../tracks/index.js';+import { renderSongComposition } from './compositionRender.js';+import { renderMusicVideo } from './render.js';++describe('renderMusicVideo code composition', () => {+ it('passes the composition directory and excerpt in-point to the song renderer', async () => {+ getProject.mockResolvedValue({ id: 'p1', trackId: 't1', audioAnalysis: { durationSec: 180 } });+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });+ const result = await renderMusicVideo('p1', { codeDirectory: 'compositions/song', startSec: 60 });+ expect(result).toEqual({ generationId: 'song-job' });+ expect(renderSongComposition).toHaveBeenCalledWith(expect.objectContaining({+ directory: 'compositions/song',+ audioPath: expect.stringContaining('song.wav'),+ startSec: 60,+ project: expect.objectContaining({ id: 'p1' }),+ }));+ });++ it('keeps a second code render off the project while the first is in flight', async () => {+ getProject.mockResolvedValue({ id: 'p2', uploadedAudioFilename: 'take.wav', audioAnalysis: { durationSec: 90 } });+ let release;+ renderSongComposition.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }));+ const first = renderMusicVideo('p2', { codeDirectory: 'compositions/song' });+ await vi.waitFor(() => expect(renderSongComposition).toHaveBeenCalled());+ await expect(renderMusicVideo('p2', { codeDirectory: 'compositions/song' })).rejects.toMatchObject({ status: 409, code: 'RENDER_IN_PROGRESS' });+ release({ generationId: 'done' });+ await first;+ });+});diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex d732639bc7..145eed056d 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -38,7 +38,7 @@ import { getProject, listProjects, updateProject, mutateProjectRecord } from './import { applyProjectPatch } from './projectsLogic.js';import { sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';import { renderableCues, sectionCardCues } from './composition.js';-import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';+import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch, renderSongComposition } from './compositionRender.js';import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';import { findStalePerformanceTakes } from './performanceShot.js';import { ensureInstanceId } from '../instanceIdentity.js';@@ -596,7 +596,31 @@ export async function planMusicVideoRender(project) {return { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed };}-export async function renderMusicVideo(projectId) {+// Code compositions are not the footage concat below. The caller names the+// composition directory; excerpts pass the master's in-point as startSec.+async function renderMusicVideoCode(projectId, { codeDirectory, startSec = 0 }) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const existingJob = projectRenders.get(projectId);+ if (existingJob && (existingJob === PENDING || jobs.has(existingJob))) {+ throw new ServerError('Render already in progress for this project', {+ status: 409, code: 'RENDER_IN_PROGRESS', context: { jobId: existingJob === PENDING ? null : existingJob },+ });+ }+ projectRenders.set(projectId, PENDING);+ const jobId = randomUUID();+ try {+ const audioPath = await resolveMasterAudioPath(project);+ return await renderSongComposition({ project, directory: codeDirectory, jobId, audioPath, startSec });+ } finally {+ if (projectRenders.get(projectId) === PENDING) projectRenders.delete(projectId);+ }+}++export async function renderMusicVideo(projectId, options = {}) {+ if (typeof options?.codeDirectory === 'string' && options.codeDirectory) {+ return renderMusicVideoCode(projectId, options);+ }const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });