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(html-composition): shutter motion blur with adaptive sub-frame count (#9077)
[._.]/ Adam Eivy188f5917454b
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex a1d5904cc4..8a36887f0b 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -82,6 +82,39 @@ job result keeps `generationId` as the job and names the first format in`id`/`filename`/`thumbnail`, and lists all ofthem in `videos: [{ format, id, filename, thumbnail, path }]`.+## Motion blur++Set `motionBlur` on `portosComposition` to blend sub-frames on fast moves.++- **Integer `1`–`4`** (default `1`): captures that many sub-frames spread over+ the whole frame interval and blends them with ffmpeg `tmix`. `1` is no blur.+ Fast moves show separated copies rather than a streak.+- **Object `{ shutter, samples, tolerance }`**: samples a centred fraction of+ the frame time, at `t = (n + (k/count - ½) · shutter) / fps`, and averages+ the sub-frames in linear light. `shutter` is 0.05–1 (default 0.5; 0.2 is a+ short filmic streak, 1 smears the whole interval). `samples` is a fixed+ count from 4–64 or `'auto'` (the default). `tolerance` is 1–8 levels out of+ 255 (default 2).++`'auto'` starts at the frame's centre and refines 1 → 3 → 9 → 27 → 81 samples,+reusing every earlier sample. It stops when the worst 8×8 block of the new+average differs from the previous average by less than `tolerance`. A frame+whose centre matches both neighbouring frames' centres is still and costs a+single capture. The job result's `sampleHistogram` maps each sample count to+the number of output frames that used it.++Shutter blur relies on two scene rules:++- Output must be a pure function of `t`. Sub-frames are rendered out of order,+ may repeat, and the first frame's shutter clamps negative times to `0`.+- Per-frame flicker (grain, jitter, a random seed per frame) must stay constant+ across the shutter. Key it to `PortosMotion.frameIdx(t, fps)`, which rounds+ to the nearest frame, not to `Math.floor(t * fps)`.++```js+motionBlur: { shutter: 0.5, samples: 'auto', tolerance: 2 }+```+## Motion kit`server/services/htmlComposition/kit/portos-motion.js` is a deterministic@@ -95,6 +128,8 @@ helper script for compositions. Copy it beside `index.html`, load it withone spring per change, so motion never restarts or pops.- `indicator(t, stops, width)`, `swapAlpha(t, tIn, tOut)`, `loopT(t, dur)` —stretching selection bars, content swaps inside a morphing container, loops.+- `frameIdx(t, fps)` — the output frame `t` belongs to, constant across a+ motion-blur shutter; key per-frame flicker to it.- `rng(seed)` — seeded noise (mulberry32); never use `Math.random`.- `beats(bpm)` — a beat grid (`at`, `bar`, `index`, `phase`, `list`).- `renderCues({ sampleRate, durationSec, cues })`, `mixCues`, `toPcm` —diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d8489dc4bc..62f257656b 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2541,9 +2541,18 @@ export const htmlCompositionContractSchema = z.object({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;- // 1 (default) keeps the existing single-sample-per-frame behavior.- motionBlur: z.number().int().min(1).max(4).default(1),+ // 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(),diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.jsindex 9159ff65ab..98c308bca6 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 sharp from 'sharp';+import { blurFrame } from './shutterBlur.js';import { findFfmpeg, runFfmpegProcess, probeVideoDuration, H264_ENCODE_ARGS, AAC_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter } from '../../lib/ffmpeg.js';// Size the viewport for this format, then let the composition reframe itself@@ -25,15 +27,18 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,signal?.throwIfAborted();const { fps, durationSec, width, height, motionBlur } = contract;const numFrames = Math.round(durationSec * fps);- // 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.- const sub = motionBlur ?? 1;+ // 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+ // and pipes one raw RGB frame per output frame.+ const shutter = typeof motionBlur === 'object' ? motionBlur : null;+ const sub = shutter ? 1 : motionBlur ?? 1;const motionBlurFilter = sub > 1? `tmix=frames=${sub},select='eq(mod(n\\,${sub})\\,${sub - 1})',setpts=N/${fps}/TB`: null;await frameFormat(page, contract);- const args = ['-hide_banner', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps * sub), '-vcodec', 'png', '-i', 'pipe:0'];+ 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);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);@@ -57,25 +62,52 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,}};signal?.addEventListener('abort', stop, { once: true });+ const capture = async t => {+ page.check();+ // awaitPromise in evaluate is essential: each seek owns its paint.+ await page.evaluate(`globalThis.portosComposition.seek(${t})`);+ page.check();+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });+ page.check();+ return Buffer.from(data, 'base64');+ };+ 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'); }),+ ]);+ const toRgb = png => sharp(png).removeAlpha().raw().toBuffer();+ // Output frames per sub-frame count: where a shutter render spent its time.+ const histogram = {};try {+ let previous = null;+ let centre = shutter?.samples === 'auto' && numFrames > 0 ? await capture(0) : null;for (let n = 0; n < numFrames; n++) {- for (let k = 0; k < sub; k++) {- page.check();- // awaitPromise in evaluate is essential: each seek owns its paint.- await page.evaluate(`globalThis.portosComposition.seek(${n / fps + k / (fps * sub)})`);- page.check();- const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });- page.check();- await Promise.race([- new Promise((resolve, reject) => proc.stdin.write(Buffer.from(data, 'base64'), error => error ? reject(error) : resolve())),- finished.then(() => { throw new Error('ffmpeg exited before capture completed'); }),- ]);+ if (shutter) {+ let frame;+ if (shutter.samples === 'auto') {+ // 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 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));+ previous = centre;+ centre = next;+ } else {+ frame = await blurFrame(shutter, width, height, async offset => toRgb(await capture(Math.max(0, (n + offset * shutter.shutter) / fps))));+ }+ histogram[frame.count] = (histogram[frame.count] ?? 0) + 1;+ await write(frame.rgb);+ } else {+ for (let k = 0; k < sub; k++) await write(await capture(n / fps + k / (fps * sub)));}onProgress?.((n + 1) / numFrames);}proc.stdin.end();await finished;page.check();+ return shutter ? { sampleHistogram: histogram } : {};} finally {signal?.removeEventListener('abort', stop);stop();diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.jsindex e14dad8998..733e8fa7c7 100644--- a/server/services/htmlComposition/index.js+++ b/server/services/htmlComposition/index.js@@ -159,11 +159,11 @@ export async function renderComposition({ jobId, ...input }) {const filename = `composition-${target.id}.mp4`;const outputPath = join(PATHS.videos, filename);ownedPaths.push(outputPath, join(PATHS.videoThumbnails, `${target.id}.jpg`));- await encodeComposition(page, target.contract, outputPath, { musicPath, signal, onProgress: progress => {+ const { sampleHistogram } = await encodeComposition(page, target.contract, outputPath, { musicPath, signal, onProgress: progress => {videoGenEvents.emit('progress', { generationId: jobId, progress: (index + progress) / targets.length * 0.95 });} });page.check();- rendered.push({ ...target, filename, outputPath });+ rendered.push({ ...target, filename, outputPath, sampleHistogram });}// End script execution before post-processing and publishing the result.await page.close({ verify: true });@@ -210,7 +210,10 @@ export async function renderComposition({ jobId, ...input }) {success = true;// `id`/`filename` name a real history entry (the first format); `generationId`// is the job. A single-format render keeps id === generationId as before.- const summary = ({ id, filename, thumbnail }) => ({ id, filename, thumbnail, path: `/data/videos/${filename}` });+ // A shutter-blur render reports how many output frames took each+ // sub-frame count, so the user can see where the render time went.+ const summary = ({ id, filename, thumbnail, sampleHistogram }) => ({ id, filename, thumbnail, path: `/data/videos/${filename}`,+ ...(sampleHistogram ? { sampleHistogram } : {}) });const [first] = rendered;result = { ...(launchMetadata ? { appId: launchMetadata.appId } : {}), generationId: jobId, ...summary(first),...(formats ? { videos: rendered.map(video => ({ format: video.format, ...summary(video) })) } : {}) };diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.jsindex 8a9dad898d..d2dddce142 100644--- a/server/services/htmlComposition/index.test.js+++ b/server/services/htmlComposition/index.test.js@@ -117,6 +117,43 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpeexpect(blended[1]).toBeLessThan(220);}, 60000);+ // A 20px square crossing the 1280px frame in three frames (#9077).+ const whip = motionBlur => `<!doctype html><html><head><style>body { margin: 0; background: white; } #block { position:absolute; top:100px; width:20px; height:20px; background:rgb(255,0,0); }</style>+</head><body><div id="block"></div><script>+globalThis.portosComposition = { durationSec:1, fps:12, width:1280, height:720, motionBlur:${motionBlur},+ seek(t) { document.getElementById('block').style.left = Math.round(t * 5120) + 'px'; } };+</script></body></html>`;+ const frameRow = (filename, frame) => {+ const pixels = execFileSync(ffmpeg, ['-v', 'error', '-i', join(PATHS.videos, filename), '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 40 * 1024 * 1024 });+ const frameBytes = 1280 * 720 * 3;+ return x => pixels[frame * frameBytes + (110 * 1280 + x) * 3 + 1]; // green: 255 on white, low on red+ };++ it('streaks a whip continuously with an auto shutter where integer motionBlur leaves separated copies', async () => {+ // Frame one (t=1/12) centres the square at x≈427. Integer 4 samples+ // t..t+3/48 → copies at 427/533/640/747 with white gaps between them.+ const stepped = await renderComposition(await composition(whip(4)));+ const steppedGreen = frameRow(stepped.filename, 1);+ const steppedProfile = Array.from({ length: 300 }, (_, i) => steppedGreen(445 + i));+ expect(Math.max(...steppedProfile)).toBeGreaterThan(252);+ expect(Math.min(...steppedProfile)).toBeLessThan(200);+ // A full shutter centred on the frame spans x≈213..640: an unbroken streak.+ const streaked = await renderComposition(await composition(whip("{ shutter: 1, samples: 'auto' }")));+ const streakGreen = frameRow(streaked.filename, 1);+ const profile = Array.from({ length: 380 }, (_, i) => streakGreen(240 + i));+ // Each pixel sees the square for ~1/20 of the shutter, so the streak is+ // faint but even: no white gap and no brighter copy anywhere along it.+ expect(Math.max(...profile)).toBeLessThan(252);+ expect(Math.max(...profile) - Math.min(...profile)).toBeLessThanOrEqual(4);+ expect(Object.keys(streaked.sampleHistogram).map(Number).some(count => count >= 9)).toBe(true);+ }, 120000);++ it('stops a still composition at one capture per frame with an auto shutter', async () => {+ const html = fixture('', "motionBlur:{ samples: 'auto' }").replace("(40 + t * 480) + 'px'", "'40px'");+ const result = await renderComposition(await composition(html));+ expect(result.sampleHistogram).toEqual({ 1: 12 });+ }, 60000);+it('renders a gated launch composition and uses its declared poster beat', async () => {const html = `<!doctype html><html><body><script>globalThis.portosComposition = { durationSec:15, fps:12, width:1280, height:720,@@ -293,6 +330,7 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpe['durationSec', 'durationSec:0'], ['fps', 'fps:12.5'], ['width', 'width:123'],['durationSec', 'durationSec:1.01'], ['seek', 'seek:null'],['motionBlur', 'motionBlur:0'], ['motionBlur', 'motionBlur:5'], ['motionBlur', 'motionBlur:2.5'],+ ['motionBlur', 'motionBlur:{shutter:2}'], ['motionBlur', 'motionBlur:{samples:200}'], ['motionBlur', "motionBlur:{samples:'auto',frames:4}"],])('names the invalid %s before capture', async (field, contract) => {const input = await composition(fixture('', contract));await expect(renderComposition(input)).rejects.toThrow(field);diff --git a/server/services/htmlComposition/kit/portos-motion.js b/server/services/htmlComposition/kit/portos-motion.jsindex 5dea3873dd..10e6cbb543 100644--- a/server/services/htmlComposition/kit/portos-motion.js+++ b/server/services/htmlComposition/kit/portos-motion.js@@ -67,6 +67,11 @@// Wrap time for seamless loops; negative time wraps too.const loopT = (t, duration) => ((t % duration) + duration) % duration;+ // The output frame a time belongs to. Shutter motion blur samples times on+ // both sides of each frame's centre, so per-frame flicker keyed to+ // floor(t * fps) would change mid-shutter; rounding holds it for the frame.+ const frameIdx = (t, fps) => Math.round(t * fps);+// Seeded PRNG (mulberry32). Create one per element/scene with a fixed seed,// inside seek(t), so the same t always draws the same frame.function rng(seed) {@@ -142,7 +147,7 @@}root.PortosMotion = Object.freeze({- clamp, spring, SPRINGS, preset, track, indicator, swapAlpha, loopT, rng, beats,+ clamp, spring, SPRINGS, preset, track, indicator, swapAlpha, loopT, frameIdx, rng, beats,VOICES, mixCues, toPcm, renderCues,});})(globalThis);diff --git a/server/services/htmlComposition/shutterBlur.js b/server/services/htmlComposition/shutterBlur.jsnew file mode 100644index 0000000000..f74150fcc4--- /dev/null+++ b/server/services/htmlComposition/shutterBlur.js@@ -0,0 +1,92 @@+// Shutter motion blur for HTML compositions (#9077): average sub-frames spread+// over a centred fraction of the frame interval, in linear light, optionally+// refining the sample set until the average stops changing.++// 'auto' refines 1 → 3 → 9 → 27 → 81. Tripling keeps every earlier sample: the+// centre of each third of a stratum is that stratum's own centre, so a level+// only renders the 2n new offsets. 81 stays under the issue's 108 cap.+export const AUTO_MAX_SAMPLES = 81;+const BLOCK = 8;++/** Offsets, as fractions of the shutter, of `n` stratified samples centred on 0. */+export const shutterOffsets = n => Array.from({ length: n }, (_, k) => (k + 0.5) / n - 0.5);++/** The offsets a refinement from `n` to `3n` samples adds (the old ones are reused). */+export const refinementOffsets = n => shutterOffsets(3 * n).filter((_, k) => k % 3 !== 1);++const TO_LINEAR = Float32Array.from({ length: 256 }, (_, v) => {+ const c = v / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+});+const LINEAR_STEPS = 4096;+const TO_SRGB = Uint8Array.from({ length: LINEAR_STEPS + 1 }, (_, i) => {+ const c = i / LINEAR_STEPS;+ return Math.round(255 * (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055));+});++/** A linear-light running sum over packed 8-bit sRGB frames of one size. */+export function createAccumulator(length) {+ const sum = new Float32Array(length);+ let count = 0;+ return {+ get count() { return count; },+ add(rgb) {+ if (rgb.length !== length) throw new Error('Sub-frame size changed mid-frame');+ for (let i = 0; i < length; i++) sum[i] += TO_LINEAR[rgb[i]];+ count++;+ },+ average() {+ const out = Buffer.allocUnsafe(length);+ const scale = LINEAR_STEPS / count;+ for (let i = 0; i < length; i++) out[i] = TO_SRGB[Math.min(LINEAR_STEPS, Math.round(sum[i] * scale))];+ return out;+ },+ };+}++/**+ * Worst 8×8 block's mean absolute difference between two packed RGB frames, in+ * 0–255 levels. A block mean ignores single-pixel dither yet still catches a+ * small moving object that a whole-frame mean would dilute away.+ */+export function worstBlockDifference(a, b, width, height) {+ let worst = 0;+ for (let by = 0; by < height; by += BLOCK) {+ for (let bx = 0; bx < width; bx += BLOCK) {+ let total = 0;+ let n = 0;+ for (let y = by; y < Math.min(by + BLOCK, height); y++) {+ for (let i = (y * width + bx) * 3, end = (y * width + Math.min(bx + BLOCK, width)) * 3; i < end; i++) {+ total += Math.abs(a[i] - b[i]);+ n++;+ }+ }+ worst = Math.max(worst, total / n);+ }+ }+ return worst;+}++/**+ * Render one output frame. `sample(offset)` resolves the packed RGB sub-frame+ * at `offset` shutter-fractions from the frame centre. Fixed mode averages+ * `samples` strata; auto starts from the centre and triples until successive+ * averages differ by less than `tolerance`. Resolves `{ rgb, count }`.+ */+export async function blurFrame({ samples, tolerance }, width, height, sample, centre) {+ const acc = createAccumulator(width * height * 3);+ if (samples !== 'auto') {+ for (const offset of shutterOffsets(samples)) acc.add(await sample(offset));+ return { rgb: acc.average(), count: acc.count };+ }+ acc.add(centre ?? await sample(0));+ let previous = acc.average();+ while (acc.count < AUTO_MAX_SAMPLES) {+ for (const offset of refinementOffsets(acc.count)) acc.add(await sample(offset));+ const next = acc.average();+ const converged = worstBlockDifference(previous, next, width, height) < tolerance;+ previous = next;+ if (converged) break;+ }+ return { rgb: previous, count: acc.count };+}