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
Render long music videos across several browsers at once (#10365)
[._.]/8f3c9990f070
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.jsindex bbec579f6f..2a9c67bba4 100644--- a/server/services/htmlComposition/encode.js+++ b/server/services/htmlComposition/encode.js@@ -2,6 +2,8 @@ import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';import { spawn } from '../../lib/childProcess.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';+import { availableParallelism, totalmem } from 'node:os';+import { rm, writeFile } from 'node:fs/promises';import sharp from 'sharp';import { blurFrame } from './shutterBlur.js';import { findFfmpeg, runFfmpegProcess, probeVideoDuration, H264_ENCODE_ARGS, AAC_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter, planLoudnessMaster, reportMasteredLoudness } from '../../lib/ffmpeg.js';@@ -37,7 +39,11 @@ const SCREENSHOT = Object.freeze({ format: 'png', optimizeForSpeed: true, fromSu// the terminal race releases a pending write on exit, disconnect or cancel.// `offsetSec` seeks a window of a longer timeline: frame n is drawn at// `offsetSec + n / fps` (a music-video excerpt stays on song time).-export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, offsetSec = 0, videoFilter = null, master = false, runFfmpeg = runFfmpegProcess, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {+// `continuous` marks a window that continues an earlier one and `followed` one+// that a later window continues (parallel segments): the auto-shutter+// comparison at each seam sees the real neighbouring frame instead of treating+// the window edge as an edge of the song.+export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, offsetSec = 0, continuous = false, followed = false, videoFilter = null, master = false, runFfmpeg = runFfmpegProcess, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {const ffmpeg = await locateFfmpeg();if (!ffmpeg) throw new Error('ffmpeg not found on PATH');const tag = await tagFilter();@@ -133,7 +139,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,// Output frames per sub-frame count: where a shutter render spent its time.const histogram = {};try {- let previous = null;+ let previous = shutter?.samples === 'auto' && continuous && offsetSec > 0 && numFrames > 0 ? await capture(-1 / fps) : null;let centre = shutter?.samples === 'auto' && numFrames > 0 ? await capture(0) : null;for (let n = 0; n < numFrames; n++) {if (shutter) {@@ -142,14 +148,14 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,// Each frame's centre is captured one frame ahead. A frame whose// centre matches both neighbours' did not move this interval, so it// costs one capture, same as an unblurred render.- const next = n + 1 < numFrames ? await capture((n + 1) / fps) : null;+ const next = n + 1 < numFrames || followed ? await capture((n + 1) / fps) : null;const still = (previous || next) && (!previous || previous.equals(centre)) && (!next || next.equals(centre));frame = still ? { rgb: await toRgb(centre), count: 1 }- : await blurFrame(shutter, width, height, async offset => toRgb(await capture(Math.max(0, (n + offset * shutter.shutter) / fps))), await toRgb(centre));+ : await blurFrame(shutter, width, height, async offset => toRgb(await capture(Math.max(-offsetSec, (n + offset * shutter.shutter) / fps))), await toRgb(centre));previous = centre;centre = next;} else {- frame = await blurFrame(shutter, width, height, async offset => toRgb(await capture(Math.max(0, (n + offset * shutter.shutter) / fps))));+ frame = await blurFrame(shutter, width, height, async offset => toRgb(await capture(Math.max(-offsetSec, (n + offset * shutter.shutter) / fps))));}histogram[frame.count] = (histogram[frame.count] ?? 0) + 1;await write(frame.rgb);@@ -180,6 +186,94 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,}}+// Capture is serial per page: seek, screenshot, pipe, one frame at a time, so a+// song-length render leaves most cores idle. A long render splits into frame+// ranges, each captured by its own browser into its own segment, then the+// segments join losslessly (stream copy). Seeks are deterministic by contract,+// so each frame is the same whichever browser draws it. Each browser holds a+// full-size page and its own encoder, so the count is capped by cores and RAM.+const SEGMENT_MIN_FRAMES = 240;+const SEGMENT_MAX_WORKERS = 4;+const SEGMENT_BYTES_PER_WORKER = 3 * 1024 ** 3;++function compositionRenderWorkers({ cores = availableParallelism(), memoryBytes = totalmem() } = {}) {+ return Math.max(1, Math.min(SEGMENT_MAX_WORKERS, Math.floor(cores / 2), Math.floor(memoryBytes / SEGMENT_BYTES_PER_WORKER)));+}++/** Contiguous frame ranges `[{ start, frames }]`, each at least SEGMENT_MIN_FRAMES long. */+function planSegments(numFrames, workers) {+ const count = Math.max(1, Math.min(workers, Math.floor(numFrames / SEGMENT_MIN_FRAMES)));+ const base = Math.floor(numFrames / count);+ const extra = numFrames % count;+ const segments = [];+ for (let i = 0, start = 0; i < count; i++) {+ const frames = base + (i < extra ? 1 : 0);+ segments.push({ start, frames });+ start += frames;+ }+ return segments;+}++// A video-only (silent) capture of `contract`, split across `workers` pages.+// `page` draws the first segment; `openPage(signal)` opens each further one+// and the segment closes it. `videoFilterAt(offsetSec)` builds a segment's+// filter on song time. One segment is exactly `encodeComposition`.+export async function encodeCompositionSegments(page, contract, outputPath, { openPage, workers = compositionRenderWorkers(), offsetSec = 0, videoFilterAt = () => null, signal, onProgress, encode = encodeComposition, runFfmpeg = runFfmpegProcess, locateFfmpeg = findFfmpeg } = {}) {+ const { fps, durationSec } = contract;+ const numFrames = Math.round(durationSec * fps);+ const segments = planSegments(numFrames, workers);+ if (segments.length === 1) {+ return encode(page, contract, outputPath, { signal, onProgress, offsetSec, videoFilter: videoFilterAt(offsetSec) });+ }+ const ffmpeg = await locateFfmpeg();+ if (!ffmpeg) throw new Error('ffmpeg not found on PATH');+ // One failed segment stops the rest instead of letting them run to the end.+ const controller = new AbortController();+ const relay = () => controller.abort(signal.reason);+ signal?.addEventListener('abort', relay, { once: true });+ const parts = segments.map((_, i) => `${outputPath}.part${i}.mp4`);+ const listPath = `${outputPath}.parts.txt`;+ const done = segments.map(() => 0);+ const histogram = {};+ try {+ signal?.throwIfAborted();+ const results = await Promise.allSettled(segments.map(async ({ start, frames }, i) => {+ let segmentPage = i === 0 ? page : null;+ try {+ segmentPage ??= await openPage(controller.signal);+ const at = Math.round((offsetSec + start / fps) * 1e6) / 1e6;+ const result = await encode(segmentPage, { ...contract, durationSec: frames / fps }, parts[i], {+ signal: controller.signal, offsetSec: at, continuous: start > 0, followed: i < segments.length - 1, videoFilter: videoFilterAt(at),+ onProgress: (_fraction, detail) => {+ done[i] = detail?.frame ?? 0;+ const frame = done.reduce((sum, value) => sum + value, 0);+ onProgress?.(frame / numFrames, { frame, frames: numFrames });+ },+ });+ for (const [count, total] of Object.entries(result?.sampleHistogram ?? {})) histogram[count] = (histogram[count] ?? 0) + total;+ } catch (error) {+ controller.abort(error);+ throw error;+ } finally {+ if (i > 0 && segmentPage) await segmentPage.close().catch(() => {});+ }+ }));+ signal?.throwIfAborted();+ // Report the segment that failed first, not the ones it stopped.+ const failed = results.find(result => result.status === 'rejected' && result.reason === controller.signal.reason)+ ?? results.find(result => result.status === 'rejected');+ if (failed) throw failed.reason;+ await writeFile(listPath, parts.map(part => `file '${part.replaceAll("'", "'\\''")}'`).join('\n'));+ const joined = await runFfmpeg({ bin: ffmpeg, signal, args: ['-hide_banner', '-loglevel', 'error', '-f', 'concat', '-safe', '0', '-i', listPath,+ '-c', 'copy', '-movflags', '+faststart', '-y', outputPath] });+ if (!joined.ok) throw new Error(`Joining render segments failed: ${joined.reason}`);+ return Object.keys(histogram).length ? { sampleHistogram: histogram } : {};+ } finally {+ signal?.removeEventListener('abort', relay);+ for (const path of [...parts, listPath]) await rm(path, { force: true }).catch(() => {});+ }+}+// A proof holds at most this many frames so one contact sheet stays readable.const PROOF_MAX_FRAMES = 60;const PROOF_COLUMNS = 6;diff --git a/server/services/htmlComposition/encode.segments.test.js b/server/services/htmlComposition/encode.segments.test.jsnew file mode 100644index 0000000000..367df272fb--- /dev/null+++ b/server/services/htmlComposition/encode.segments.test.js@@ -0,0 +1,138 @@+import { spawnSync } from 'node:child_process';+import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { EventEmitter } from 'node:events';+import sharp from 'sharp';+import { encodeComposition, encodeCompositionSegments } from './encode.js';+import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';++const contract = { fps: 24, durationSec: 60, width: 1920, height: 1080, motionBlur: 1 };+const page = (name) => ({ name, closed: 0, async close() { this.closed += 1; } });++describe('encodeCompositionSegments', () => {+ it('splits a long window into contiguous song-time segments and joins them', async () => {+ const calls = [];+ const opened = [];+ const progress = [];+ const joins = [];+ const first = page('first');+ await encodeCompositionSegments(first, contract, '/tmp/out.mp4', {+ workers: 3, offsetSec: 30,+ openPage: async () => { const p = page(`extra${opened.length}`); opened.push(p); return p; },+ videoFilterAt: (offsetSec) => `grade@${offsetSec}`,+ encode: async (p, c, path, options) => {+ calls.push({ page: p.name, frames: Math.round(c.durationSec * c.fps), path, offsetSec: options.offsetSec, continuous: options.continuous, followed: options.followed, filter: options.videoFilter });+ options.onProgress(1, { frame: Math.round(c.durationSec * c.fps) });+ return {};+ },+ locateFfmpeg: async () => 'ffmpeg',+ runFfmpeg: async ({ args }) => { joins.push(args); return { ok: true }; },+ onProgress: (fraction) => progress.push(fraction),+ });+ calls.sort((a, b) => a.offsetSec - b.offsetSec);+ expect(calls.map(({ frames, offsetSec, continuous, followed, filter }) => ({ frames, offsetSec, continuous, followed, filter }))).toEqual([+ { frames: 480, offsetSec: 30, continuous: false, followed: true, filter: 'grade@30' },+ { frames: 480, offsetSec: 50, continuous: true, followed: true, filter: 'grade@50' },+ { frames: 480, offsetSec: 70, continuous: true, followed: false, filter: 'grade@70' },+ ]);+ // The caller's page draws the first segment and stays open; the extra pages close.+ expect(calls[0].page).toBe('first');+ expect(first.closed).toBe(0);+ expect(opened.map((p) => p.closed)).toEqual([1, 1]);+ expect(progress.at(-1)).toBe(1);+ expect(joins).toHaveLength(1);+ expect(joins[0]).toEqual(expect.arrayContaining(['-f', 'concat', '-c', 'copy', '/tmp/out.mp4']));+ });++ it('renders a short window in one pass on the caller\'s page', async () => {+ const calls = [];+ await encodeCompositionSegments(page('only'), { ...contract, durationSec: 15 }, '/tmp/short.mp4', {+ workers: 4, offsetSec: 5, videoFilterAt: (offsetSec) => `grade@${offsetSec}`,+ openPage: async () => { throw new Error('no extra page for a short window'); },+ encode: async (p, c, path, options) => { calls.push([p.name, path, options.offsetSec, options.videoFilter]); return {}; },+ });+ expect(calls).toEqual([['only', '/tmp/short.mp4', 5, 'grade@5']]);+ });++ it('stops the other segments and reports the one that failed first', async () => {+ const extras = [];+ const failure = new Error('seek failed at frame 900');+ const run = encodeCompositionSegments(page('first'), contract, '/tmp/fail.mp4', {+ workers: 2,+ openPage: async () => { const p = page('extra'); extras.push(p); return p; },+ encode: (p, _c, _path, { signal }) => p.name === 'extra'+ ? Promise.reject(failure)+ : new Promise((_, reject) => signal.addEventListener('abort', () => reject(new Error('Render canceled')), { once: true })),+ locateFfmpeg: async () => 'ffmpeg',+ runFfmpeg: async () => { throw new Error('must not join a failed render'); },+ });+ await expect(run).rejects.toBe(failure);+ expect(extras[0].closed).toBe(1);+ });+});++// A real encodeComposition with the encoder stubbed: records every song time+// the page is seeked to, over identical frames (so auto shutter stays still).+const PNG = (await sharp({ create: { width: 4, height: 4, channels: 3, background: '#808080' } }).png().toBuffer()).toString('base64');+async function seeksFor(motionBlur, options) {+ const seeks = [];+ const fakePage = {+ check() {},+ async evaluate(expression) { const match = /seek\(([^)]+)\)/.exec(expression); if (match) seeks.push(Number(match[1])); },+ async send(method) { return method === 'Page.captureScreenshot' ? { data: PNG } : {}; },+ };+ const spawnProcess = () => {+ const proc = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.stdin = new EventEmitter();+ proc.stdin.write = (_bytes, callback) => { callback?.(); return true; };+ proc.stdin.end = () => proc.emit('close', 0);+ proc.kill = () => {};+ return proc;+ };+ await encodeComposition(fakePage, { fps: 10, durationSec: 0.3, width: 4, height: 4, motionBlur }, '/tmp/seam.mp4', {+ spawnProcess, locateFfmpeg: async () => 'ffmpeg', tagFilter: async () => 'format=yuv420p', ...options,+ });+ return seeks;+}++describe('encodeComposition at segment seams', () => {+ const auto = { shutter: 0.5, samples: 'auto', tolerance: 2 };+ it('compares an auto shutter against the real neighbours across both seams', async () => {+ expect(await seeksFor(auto, { offsetSec: 0 })).toEqual([0, 0.1, 0.2]);+ expect(await seeksFor(auto, { offsetSec: 10, continuous: true, followed: true })).toEqual([9.9, 10, 10.1, 10.2, 10.3]);+ });++ it('samples a fixed shutter across the window start of a continued segment, but never before song start', async () => {+ const fixed = { shutter: 0.5, samples: 4, tolerance: 2 };+ expect(Math.min(...await seeksFor(fixed, { offsetSec: 0 }))).toBe(0);+ expect(Math.min(...await seeksFor(fixed, { offsetSec: 10, continuous: true }))).toBeLessThan(10);+ });+});++const ffmpeg = await findFfmpeg();+describe.skipIf(!ffmpeg)('encodeCompositionSegments with real ffmpeg', () => {+ it('joins encoded segments into one stream with every frame and no leftovers', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'portos-segments-'));+ try {+ const output = join(dir, 'joined.mp4');+ await encodeCompositionSegments(page('first'), { ...contract, durationSec: 25, width: 320, height: 180 }, output, {+ workers: 2, openPage: async () => page('extra'),+ encode: async (_p, c, path) => {+ const result = spawnSync(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', `testsrc2=size=320x180:rate=${c.fps}`,+ '-frames:v', String(Math.round(c.durationSec * c.fps)), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-preset', 'ultrafast', '-y', path]);+ if (result.status !== 0) throw new Error(result.stderr.toString());+ return {};+ },+ runFfmpeg: runFfmpegProcess,+ });+ const probe = spawnSync('ffprobe', ['-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', output]);+ if (probe.status === 0) expect(Number(probe.stdout.toString().trim())).toBe(600);+ expect(['part0.mp4', 'part1.mp4', 'parts.txt'].some((suffix) => existsSync(`${output}.${suffix}`))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }, 60000);+});diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.jsindex ed65255f0b..9db29dfce8 100644--- a/server/services/musicVideo/documentRender.js+++ b/server/services/musicVideo/documentRender.js@@ -317,7 +317,7 @@ export async function encodeDocumentComposition({const { findFfmpeg, runFfmpegProcess, probeVideoGeometry, edgeFadeFilter } = await import('../../lib/ffmpeg.js');const { stageMusicVideoComposition } = await import('../htmlComposition/index.js');const { openComposition } = await import('../htmlComposition/browser.js');- const { encodeComposition } = await import('../htmlComposition/encode.js');+ const { encodeComposition, encodeCompositionSegments } = await import('../htmlComposition/encode.js');const { loadHistory } = await import('../videoGen/history.js');const { AUDIO_NORM, buildAudioBedMix } = await import('../videoTimeline/audioBedMix.js');const ffmpeg = await findFfmpeg();@@ -334,7 +334,8 @@ export async function encodeDocumentComposition({prepare: (dir) => stageDocumentData(dir, data, media),});signal?.throwIfAborted();- page = await openComposition(staged.directory, { signal, streamMedia: true, mediaMode: musicVideoMediaMode(project), ownedBrowser: true });+ const openPage = (pageSignal) => openComposition(staged.directory, { signal: pageSignal, streamMedia: true, mediaMode: musicVideoMediaMode(project), ownedBrowser: true });+ page = await openPage(signal);const metadata = await page.evaluate(`(() => {const c = globalThis.portosComposition;if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');@@ -367,8 +368,10 @@ export async function encodeDocumentComposition({}const target = documentTargetFrame(parsed.data, project);const window = documentRenderWindow(target, { windowStart, windowEnd });- await encodeComposition(page, { ...target, durationSec: window.durationSec }, silent, {- videoFilter: musicVideoGradeFilter(project.composition?.grade, data.scenes, { fps: target.fps, offsetSec: window.startSec }),+ // Long windows split across several browsers (encodeCompositionSegments).+ await encodeCompositionSegments(page, { ...target, durationSec: window.durationSec }, silent, {+ openPage, encode: encodeComposition,+ videoFilterAt: (offsetSec) => musicVideoGradeFilter(project.composition?.grade, data.scenes, { fps: target.fps, offsetSec }),signal, offsetSec: window.startSec, onProgress: (fraction) => onProgress?.(fraction * 0.95),});page.check();diff --git a/server/services/musicVideo/documentRender.test.js b/server/services/musicVideo/documentRender.test.jsindex e18ed13d87..5480753bb3 100644--- a/server/services/musicVideo/documentRender.test.js+++ b/server/services/musicVideo/documentRender.test.js@@ -12,7 +12,7 @@ import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';-vi.mock('../htmlComposition/encode.js', () => ({ encodeComposition: vi.fn(async () => { throw new Error('stop at encoder'); }) }));+vi.mock('../htmlComposition/encode.js', async (importOriginal) => ({ ...(await importOriginal()), encodeComposition: vi.fn(async () => { throw new Error('stop at encoder'); }) }));const { encodeComposition } = await import('../htmlComposition/encode.js');const { browser } = vi.hoisted(() => ({ browser: { seen: null, contract: null } }));