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: master synthesized and library music in code-rendered videos to -14 LUFS and report the measured loudness (#10249)

[._.]/ Adam Eivy6503f0f47bf9
diff --git a/client/src/components/apps/LaunchVideoPanel.jsx b/client/src/components/apps/LaunchVideoPanel.jsx
index b44386b8f8..b90b975f10 100644
--- a/client/src/components/apps/LaunchVideoPanel.jsx
+++ b/client/src/components/apps/LaunchVideoPanel.jsx
@@ -15,7 +15,7 @@ import { createAppLaunchVideo, getAppLaunchVideos, getMotionToolkit, installMoti
import { listPipelineMusicLibrary } from '../../services/apiPipeline';
import { uploadFile } from '../../services/apiMedia';
import { trackAudioUrl } from '../../services/apiTracks';
-import { formatBytes, formatDateTime, formatDurationSec } from '../../utils/formatters';
+import { formatBytes, formatDateTime, formatDurationSec, formatLoudness } from '../../utils/formatters';
import toast from '../ui/Toast';
const inputClass = 'w-full rounded border border-port-border bg-port-bg p-2 text-port-text';
@@ -353,6 +353,7 @@ export default function LaunchVideoPanel({ app }) {
<Link className="text-port-accent" to="/media/history">Media History</Link>
</div>
<p className="whitespace-pre-wrap">{selected.caption}</p>
+ {selected.loudness && <p className="text-sm text-port-text-muted">Audio: {formatLoudness(selected.loudness)}</p>}
{selected.sampleHistogram && <p className="text-sm text-port-text-muted">Motion blur samples per frame: {Object.entries(selected.sampleHistogram).map(([samples, frames]) => `${samples}× → ${frames} frames`).join(', ')}</p>}
{selected.sourceVideoId && <p className="text-sm text-port-text-muted">Revised from version {selected.sourceVideoId}</p>}
<ReviseLaunchVideo key={`revision:${app.id}:${selected.id}`} appId={app.id} videoId={selected.id} />
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsx
index 4c9817de3f..6583e41e63 100644
--- a/client/src/components/codeAnimation/CodeAnimationPreview.jsx
+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx
@@ -5,6 +5,7 @@ import toast from '../ui/Toast';
import { cancelCodeAnimationExport, exportCodeAnimation, getCodeAnimationPackage, uploadGalleryVideo } from '../../services/api';
import { useSseProgress } from '../../hooks/useSseProgress';
import { downloadBlob } from '../../lib/downloadBlob';
+import { formatLoudness } from '../../utils/formatters';
// Seconds past the film's own duration before a silent recording is abandoned
// (a page that never answers the handshake must not leave Record spinning).
@@ -356,6 +357,7 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl
<a href={exportResult.path} download={`${fileBase}.mp4`} className={BUTTON_SECONDARY}>
<Download className="h-4 w-4" /> Download MP4
</a>
+ {exportResult.loudness && <span className="text-xs text-gray-400">Audio: {formatLoudness(exportResult.loudness)}</span>}
<Link to="/media/history" className="text-xs text-port-accent hover:underline">Saved to Media History</Link>
</div>
</div>
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 1fc1e0d031..39bc81d825 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -23,7 +23,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
| `trackOptionLabels` | `trackOptionLabels(tracks)` — ID-keyed library option labels with title, artist, duration, creation date, missing-audio status, and stable collision-resolving ID suffixes. Build before filtering selector eligibility. |
-| `formatters` | Date/time/duration/byte formatters (`clamp`, `shortClaudeModelName` (Claude model id → display name; strips `claude-` and only an 8-digit date suffix, so `sonnet-5-5` survives), `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `formatCount` (thousands-separated EXACT count, "2,762" — for a total the user is meant to read as a number, where "2.8K" would throw away the precision that is the point of showing it), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price; thousands are grouped, "$4,610.09") — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. `formatHourOfDay` renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (`long` "3 PM", `compact` "3PM", `tiny` "3p", `lower` "3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
+| `formatters` | Date/time/duration/byte formatters (`clamp`, `shortClaudeModelName` (Claude model id → display name; strips `claude-` and only an 8-digit date suffix, so `sonnet-5-5` survives), `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `formatCount` (thousands-separated EXACT count, "2,762" — for a total the user is meant to read as a number, where "2.8K" would throw away the precision that is the point of showing it), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price; thousands are grouped, "$4,610.09") — `formatLoudness` (a mastered render's measured audio as one line, "-14.1 LUFS, peak -1.6 dB (was -27.3 LUFS)"), `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. `formatHourOfDay` renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (`long` "3 PM", `compact` "3PM", `tiny` "3p", `lower` "3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
| `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, `cronFromIntervalMs` numeric-interval → expression conversion (mirrors the server helper), `summarizeAppSchedules` rendering of the per-app cron cadences a task's global row cannot express, and `JOB_INTERVAL_OPTIONS` / `ON_DEMAND_INTERVAL` — the interval-mode cadences for autonomous jobs, derived from the server's `INTERVAL_OPTIONS` (`on-demand` = stays enabled and manually runnable, but arms no timer). Import it rather than re-declaring the list in a scheduling component. |
| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 93117b6fdf..b6dcab4cc6 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -409,6 +409,19 @@ function roundForDisplay(value, decimals) {
return parseFloat(n.toFixed(decimals));
}
+/**
+ * One-line readout of a mastered render's measured audio (#10249).
+ * @param {{integratedLufs:number, truePeakDb:number, masteredFrom?:{integratedLufs:number}}|null|undefined} loudness
+ * @returns {string} e.g. "-14.1 LUFS, peak -1.6 dB (was -27.3 LUFS)", or '' when unmeasured
+ */
+export function formatLoudness(loudness) {
+ const lufs = roundForDisplay(loudness?.integratedLufs, 1);
+ const peak = roundForDisplay(loudness?.truePeakDb, 1);
+ if (lufs == null || peak == null) return '';
+ const was = roundForDisplay(loudness.masteredFrom?.integratedLufs, 1);
+ return `${lufs} LUFS, peak ${peak} dB${was == null ? '' : ` (was ${was} LUFS)`}`;
+}
+
/**
* Format a body weight for display. Unit-converted weights arrive as raw
* binary floats (e.g. 170.35000000000002), which read as false precision and
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index d6e65b32ce..5891085026 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
clamp, formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo, formatAgeDays,
formatCooldown, formatCountdown, recommendedRamGb, parseTimeoutMs, formatDurationSec, middleTruncate,
- formatWeight, formatPercent, formatUsd, formatBytes, formatCount,
+ formatLoudness, formatWeight, formatPercent, formatUsd, formatBytes, formatCount,
formatDateNumeric, formatTimeOfDaySeconds, formatClockTime, formatHourOfDay, formatWeekdayDate,
formatMonthDay, formatMonthYear, formatWeekdayShort, formatWeekdayTime, formatDateFull, formatDateShort, formatDateTime,
localDateKey, shiftISODate,
@@ -733,3 +733,14 @@ describe('shortClaudeModelName', () => {
expect(shortClaudeModelName(undefined)).toBe('');
});
});
+
+describe('formatLoudness', () => {
+ it('reads as one line with the pre-master level', () => {
+ expect(formatLoudness({ integratedLufs: -14.1, truePeakDb: -1.6, masteredFrom: { integratedLufs: -27.3, truePeakDb: -24 } })).toBe('-14.1 LUFS, peak -1.6 dB (was -27.3 LUFS)');
+ });
+ it('omits the pre-master clause when absent and returns blank when unmeasured', () => {
+ expect(formatLoudness({ integratedLufs: -14, truePeakDb: -2 })).toBe('-14 LUFS, peak -2 dB');
+ expect(formatLoudness(null)).toBe('');
+ expect(formatLoudness({ integratedLufs: null, truePeakDb: -2 })).toBe('');
+ });
+});
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index 35f49ffa85..32ea57a673 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -50,6 +50,25 @@ with the same tail fade, and removes the temporary file after completion or
failure. No music model, Python runtime, downloaded samples or music-library
write is required. Missing or invalid audio fails the job.
+### Loudness mastering
+
+Audio PortOS itself produces or mixes, a `synthesizeMusic` score or a
+`musicTrack` bed, is mastered by default (#10249). The encode first runs an
+ffmpeg `loudnorm` measurement pass over the trimmed bed, then applies it in
+linear mode inside the same encode to **-14 LUFS integrated, -1.5 dBTP, LRA 11**
+(`MASTER_LOUDNESS` in `server/lib/ffmpeg.js`). A bed that measures below -50
+LUFS fails the job with a "Soundtrack is silent" error before any frame is
+captured. After the encode the finished file is measured again, and the job result
+and each Media History entry carry
+`loudness: { integratedLufs, truePeakDb, loudnessRange, masteredFrom: { integratedLufs, truePeakDb }, targetLufs }`.
+The launch-video panel and the Code Animation export show it as one line, for
+example "-14.1 LUFS, peak -1.6 dB (was -27.3 LUFS)".
+
+Submit `masterLoudness: false` to opt out: the bed is then muxed exactly as before
+and no `loudness` is reported. A Music Video's exact master (`audio.path`) is never
+mastered; when a sound-design bed is mixed under the song, the mix only ends with an
+`alimiter` at the -1.5 dB ceiling, so the song's own level is unchanged.
+
SuperCollider is a planned optional native code-audio runtime, described in the
[integration decision](decisions/2026-10-01-supercollider-code-audio.md). It is not
currently installed or enabled by PortOS and cannot run through this JavaScript
diff --git a/server/lib/README.md b/server/lib/README.md
index 069ca0899b..2f9c70d7d9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -419,7 +419,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). |
| `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. |
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. `edgeFadeFilter(durationSec)` is the `-af` fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. |
+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. `edgeFadeFilter(durationSec)` is the `-af` fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. Loudness mastering (#10249): `MASTER_LOUDNESS` (-14 LUFS / -1.5 dBTP / LRA 11), `measureLoudness` (loudnorm JSON analysis pass), `planLoudnessMaster` (measure then build the linear apply filter; throws on a silent source), `reportMasteredLoudness` (post-encode before/after numbers). |
| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. |
| `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. |
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 09394734d1..6ab8fbd207 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -65,12 +65,15 @@ export const findFfmpeg = async () => {
* stderr captured, matches the historical optimize/upscale behavior).
* Default `2000` mirrors audioMux's prior cap.
*
+ * - `returnStderr`: when true a successful result also carries the captured
+ * stderr tail as `stderr` (loudness measurement reads its JSON from there).
+ *
* Returns `{ ok: true }` on exit code 0, otherwise `{ ok: false, reason }`
* where `reason` is a short human-readable string suitable for logging or
* surfacing in a UI error. Spawn errors are translated into `reason: 'spawn
* failed: …'` so callers don't need a separate `.on('error', …)` handler.
*/
-export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000 } = {}) {
+export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000, returnStderr = false } = {}) {
if (!bin || typeof bin !== 'string') {
return Promise.resolve({ ok: false, reason: 'invalid ffmpeg binary' });
}
@@ -116,7 +119,7 @@ export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000 } =
resolve({ ok: false, reason: tail ? `ffmpeg exit ${code}: ${tail}` : `ffmpeg exit ${code}` });
return;
}
- resolve({ ok: true });
+ resolve(returnStderr ? { ok: true, stderr: stderrTail } : { ok: true });
});
});
}
@@ -425,6 +428,86 @@ export const H264_ENCODE_ARGS = Object.freeze([
]);
export const AAC_ENCODE_ARGS = Object.freeze(['-c:a', 'aac', '-b:a', '192k']);
+// Loudness mastering for audio PortOS itself produces (#10249): the platform
+// target a social feed normalizes toward, and the true-peak ceiling that keeps
+// the AAC encode from clipping.
+export const MASTER_LOUDNESS = Object.freeze({ targetLufs: -14, truePeakDb: -1.5, lra: 11 });
+// Below this integrated loudness a soundtrack is treated as silent.
+export const SILENT_LUFS = -50;
+
+// loudnorm aims half a dB under the ceiling: the AAC encode that follows can
+// overshoot its input's true peak by a tenth of a dB or so.
+const AAC_HEADROOM_DB = 0.5;
+const loudnormTarget = `I=${MASTER_LOUDNESS.targetLufs}:TP=${MASTER_LOUDNESS.truePeakDb - AAC_HEADROOM_DB}:LRA=${MASTER_LOUDNESS.lra}`;
+const roundDb = (n) => (Number.isFinite(n) ? Math.round(n * 10) / 10 : n);
+// loudnorm prints numbers as strings and "-inf" for silence.
+const parseDb = (v) => (/-\s*inf/i.test(String(v)) ? -Infinity : /inf/i.test(String(v)) ? Infinity : Number(v));
+
+/**
+ * Read the JSON block `loudnorm=print_format=json` writes to stderr. Returns
+ * the unrounded measurement, or null when no block is present.
+ */
+export function parseLoudnormJson(stderr) {
+ const block = String(stderr ?? '').match(/\{[^{}]*"input_i"[^{}]*\}/g)?.pop();
+ if (!block) return null;
+ let raw;
+ try { raw = JSON.parse(block); } catch { return null; }
+ return {
+ integratedLufs: parseDb(raw.input_i), truePeakDb: parseDb(raw.input_tp), loudnessRange: parseDb(raw.input_lra),
+ thresholdDb: parseDb(raw.input_thresh), offsetDb: parseDb(raw.target_offset),
+ };
+}
+
+/**
+ * Measurement pass: run `inputArgs` (ffmpeg input options plus `-i`) through
+ * an optional `prefilter` and loudnorm in analysis mode, discarding the audio.
+ * Resolves `{ ok: true, measured }` (values rounded to 0.1 for reporting;
+ * `raw` keeps full precision for the apply pass) or `{ ok: false, reason }`.
+ */
+export async function measureLoudness({ bin, inputArgs, prefilter = '', durationSec, signal, run = runFfmpegProcess }) {
+ const filter = [prefilter, `loudnorm=${loudnormTarget}:print_format=json`].filter(Boolean).join(',');
+ const result = await run({
+ bin, signal, returnStderr: true, stderrTailBytes: 8000,
+ args: ['-hide_banner', '-nostats', ...inputArgs, '-vn', '-af', filter, ...(durationSec ? ['-t', String(durationSec)] : []), '-f', 'null', '-'],
+ });
+ if (!result.ok) return { ok: false, reason: result.reason };
+ const raw = parseLoudnormJson(result.stderr);
+ if (!raw) return { ok: false, reason: 'loudness measurement produced no result' };
+ return { ok: true, raw, measured: { integratedLufs: roundDb(raw.integratedLufs), truePeakDb: roundDb(raw.truePeakDb), loudnessRange: roundDb(raw.loudnessRange) } };
+}
+
+/** Apply pass: loudnorm in linear mode fed the numbers the measurement pass found. */
+export function loudnormApplyFilter(raw) {
+ const n = (v) => Math.round(v * 100) / 100;
+ return `loudnorm=${loudnormTarget}:measured_I=${n(raw.integratedLufs)}:measured_TP=${n(raw.truePeakDb)}:measured_LRA=${n(raw.loudnessRange)}:measured_thresh=${n(raw.thresholdDb)}:offset=${n(raw.offsetDb)}:linear=true,aresample=48000`;
+}
+
+/**
+ * Measure-then-apply for one audio source. Resolves `{ filter, before }`:
+ * `filter` is the linear loudnorm to splice into the encode's `-af`, `before`
+ * the rounded pre-master numbers. Throws, naming the cause, when the source
+ * cannot be measured or is silent.
+ */
+export async function planLoudnessMaster(options) {
+ const result = await measureLoudness(options);
+ if (!result.ok) throw new Error(`Audio mastering could not measure the soundtrack: ${result.reason}`);
+ if (!(result.raw.integratedLufs > SILENT_LUFS)) {
+ throw new Error(`Soundtrack is silent: measured ${Number.isFinite(result.raw.integratedLufs) ? `${result.measured.integratedLufs} LUFS` : 'no signal'} (below ${SILENT_LUFS} LUFS)`);
+ }
+ return { filter: loudnormApplyFilter(result.raw), before: result.measured };
+}
+
+/**
+ * Measure a finished render's audio and report it beside the pre-master
+ * numbers. Throws when the file has no measurable (or only silent) audio.
+ */
+export async function reportMasteredLoudness({ bin, outputPath, before, signal, run }) {
+ const result = await measureLoudness({ bin, inputArgs: ['-i', outputPath], signal, run });
+ if (!result.ok) throw new Error(`Rendered video has no measurable audio: ${result.reason}`);
+ if (!(result.raw.integratedLufs > SILENT_LUFS)) throw new Error(`Rendered soundtrack is silent: measured ${result.measured.integratedLufs} LUFS`);
+ return { ...result.measured, masteredFrom: { integratedLufs: before.integratedLufs, truePeakDb: before.truePeakDb }, targetLufs: MASTER_LOUDNESS.targetLufs };
+}
+
// A clip cut from mid-song (a social cut) starts and stops on a hard edge; a
// short fade in and a longer fade out keep it from clicking. Returned as an
// `-af` chain fragment (leading comma) so callers append it to their trim.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 2ed4a01f02..73b2fb0f33 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2615,6 +2615,8 @@ export const launchVideoStoryboardSchema = z.object({
export const htmlCompositionRenderSchema = z.object({
launchVideo: launchVideoOptionsSchema.optional(),
synthesizeMusic: z.boolean().optional(),
+ // Master synthesized and library music to -14 LUFS / -1.5 dBTP (#10249); false keeps the bed as supplied.
+ masterLoudness: z.boolean().optional(),
// Overrides the page's own portosComposition.motionBlur when present (#9080).
motionBlur: htmlCompositionMotionBlurChoiceSchema.optional(),
directory: z.string().min(1).max(1024).refine(value => !value.startsWith('/') && !value.includes('\\') && !value.includes(':') && !value.split('/').some(part => part === '..' || part === '.' || !part), 'directory must be a relative path inside data'),
diff --git a/server/routes/apps/launchVideos.js b/server/routes/apps/launchVideos.js
index e5a30602b8..bf8794155a 100644
--- a/server/routes/apps/launchVideos.js
+++ b/server/routes/apps/launchVideos.js
@@ -276,11 +276,12 @@ router.get('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {
// Never cut a multi-format run at the limit: a take the tab shows keeps all
// of its formats (at most two past the limit).
const keptRuns = new Set(all.slice(0, LAUNCH_VIDEO_LIST_LIMIT).map(item => item.launchVideo.runId).filter(Boolean));
- const videos = all.filter((item, index) => index < LAUNCH_VIDEO_LIST_LIMIT || keptRuns.has(item.launchVideo.runId)).map(({ id, filename, thumbnail, createdAt, durationSec, width, height, launchVideo, sampleHistogram }) => ({
+ const videos = all.filter((item, index) => index < LAUNCH_VIDEO_LIST_LIMIT || keptRuns.has(item.launchVideo.runId)).map(({ id, filename, thumbnail, createdAt, durationSec, width, height, launchVideo, sampleHistogram, loudness }) => ({
id, filename, thumbnail, createdAt, durationSec, caption: launchVideo.caption, ...(launchVideo.sourceVideoId ? { sourceVideoId: launchVideo.sourceVideoId } : {}),
// runId groups a multi-format run's entries into one take in the tab.
runId: launchVideo.runId, format: formatOf({ width, height }),
...(sampleHistogram ? { sampleHistogram } : {}),
+ ...(loudness ? { loudness } : {}),
}));
res.json({ videos });
}));
diff --git a/server/routes/htmlComposition.test.js b/server/routes/htmlComposition.test.js
index d43ea6e664..b2abd47a12 100644
--- a/server/routes/htmlComposition.test.js
+++ b/server/routes/htmlComposition.test.js
@@ -70,6 +70,15 @@ describe('HTML composition admission', () => {
expect(enqueueJob).toHaveBeenCalledWith({ kind: 'html-composition', params });
});
+ it('carries the masterLoudness opt-out to the job and rejects a non-boolean', async () => {
+ const params = { directory: 'compositions/example', synthesizeMusic: true, masterLoudness: false };
+ expect((await request(app).post('/api/html-composition/render').send(params)).status).toBe(202);
+ expect(enqueueJob).toHaveBeenCalledWith({ kind: 'html-composition', params });
+ enqueueJob.mockClear();
+ expect((await request(app).post('/api/html-composition/render').send({ ...params, masterLoudness: 'no' })).status).toBe(400);
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
it.each([{ directory: 'valid', synthesizeMusic: true, musicTrack: 'example.wav' }, { directory: '../private' }, { directory: '/etc' }, { directory: 'C:\\private' }, { directory: 'valid', musicTrack: '../track.wav' }, {}])('rejects invalid paths before queue admission: %j', async body => {
enqueueJob.mockClear();
const response = await request(app).post('/api/html-composition/render').send(body);
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 1e80aefffe..bbec579f6f 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -4,7 +4,7 @@ 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';
+import { findFfmpeg, runFfmpegProcess, probeVideoDuration, H264_ENCODE_ARGS, AAC_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter, planLoudnessMaster, reportMasteredLoudness } from '../../lib/ffmpeg.js';
// Size the viewport for this format, then let the composition reframe itself
// (#8960) before any seek captures it. A composition without a layout hook
@@ -37,7 +37,7 @@ 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, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {
+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 } = {}) {
const ffmpeg = await locateFfmpeg();
if (!ffmpeg) throw new Error('ffmpeg not found on PATH');
const tag = await tagFilter();
@@ -48,6 +48,13 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
// 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');
+ // Library and synthesized beds (never an exact music-video master) can be
+ // mastered to the loudness target (#10249): measure the trimmed bed first,
+ // then apply the linear gain inside the encode's own audio filter.
+ const bedTrim = `atrim=duration=${durationSec},asetpts=PTS-STARTPTS`;
+ const mastering = master && musicPath
+ ? await planLoudnessMaster({ bin: ffmpeg, inputArgs: ['-stream_loop', '-1', '-i', musicPath], prefilter: bedTrim, durationSec, signal, run: runFfmpeg })
+ : null;
// 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
@@ -64,7 +71,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
else if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);
args.push('-map', '0:v', '-vf', [motionBlurFilter, videoFilter, 'scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','), ...H264_ENCODE_ARGS, ...BT709_CONTAINER_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);
+ else if (musicPath) args.push('-map', '1:a', '-af', `${bedTrim}${mastering ? `,${mastering.filter}` : ''},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 = spawnProcess(ffmpeg, args, safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));
let stderr = '';
@@ -154,7 +161,8 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
proc.stdin.end();
await finished;
page.check();
- return shutter ? { sampleHistogram: histogram } : {};
+ const loudness = mastering ? await reportMasteredLoudness({ bin: ffmpeg, outputPath, before: mastering.before, signal, run: runFfmpeg }) : null;
+ return { ...(shutter ? { sampleHistogram: histogram } : {}), ...(loudness ? { loudness } : {}) };
} catch (error) {
if (error.code === 'EPIPE' || inputError?.code === 'EPIPE') {
// A closed pipe often arrives before the process's close event. Preserve
diff --git a/server/services/htmlComposition/encode.mastering.test.js b/server/services/htmlComposition/encode.mastering.test.js
new file mode 100644
index 0000000000..86632786f9
--- /dev/null
+++ b/server/services/htmlComposition/encode.mastering.test.js
@@ -0,0 +1,103 @@
+import { execFileSync } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import sharp from 'sharp';
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { MASTER_LOUDNESS, SILENT_LUFS } from '../../lib/ffmpeg.js';
+import { encodeComposition } from './encode.js';
+
+const loudnormJson = (inputI, inputTp = '-6.00') => `[Parsed_loudnorm_0 @ 0x1]\n{\n\t"input_i" : "${inputI}",\n\t"input_tp" : "${inputTp}",\n\t"input_lra" : "2.00",\n\t"input_thresh" : "-40.00",\n\t"output_i" : "-14.00",\n\t"output_tp" : "-1.50",\n\t"output_lra" : "1.00",\n\t"output_thresh" : "-24.00",\n\t"normalization_type" : "dynamic",\n\t"target_offset" : "0.30"\n}\n`;
+
+const FRAME = Buffer.alloc(16, 1).toString('base64');
+const page = { check() {}, async evaluate() {}, async send(method) { return method === 'Page.captureScreenshot' ? { data: FRAME } : {}; } };
+const contract = { fps: 4, durationSec: 1, width: 64, height: 64, motionBlur: 1 };
+const fakeEncoder = () => {
+ const spawned = [];
+ const spawnProcess = (_bin, args) => {
+ const proc = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ proc.stdin = new EventEmitter();
+ proc.stdin.write = (_bytes, cb) => { cb?.(); return true; };
+ proc.stdin.end = () => proc.emit('close', 0, null);
+ spawned.push(args);
+ return proc;
+ };
+ return { spawned, spawnProcess };
+};
+const options = (extra) => ({ locateFfmpeg: async () => '/usr/bin/ffmpeg', tagFilter: async () => null, ...extra });
+
+describe('encodeComposition loudness mastering (fake ffmpeg)', () => {
+ it('measures the trimmed bed, then applies a linear loudnorm inside the encode and reports before/after', async () => {
+ const runs = [];
+ const runFfmpeg = vi.fn(async ({ args }) => {
+ runs.push(args);
+ return { ok: true, stderr: loudnormJson(runs.length === 1 ? '-27.30' : '-14.10', runs.length === 1 ? '-24.00' : '-1.60') };
+ });
+ const { spawned, spawnProcess } = fakeEncoder();
+ const result = await encodeComposition(page, contract, '/tmp/out.mp4', options({ musicPath: '/lib/bed.wav', master: true, runFfmpeg, spawnProcess }));
+ // Pass 1 analyses the same looped, trimmed audio the encode will use.
+ expect(runs[0].join(' ')).toContain('-stream_loop -1 -i /lib/bed.wav');
+ expect(runs[0].join(' ')).toContain(`atrim=duration=1,asetpts=PTS-STARTPTS,loudnorm=I=${MASTER_LOUDNESS.targetLufs}:TP=${MASTER_LOUDNESS.truePeakDb - 0.5}:LRA=${MASTER_LOUDNESS.lra}:print_format=json`);
+ // Pass 2 is linear, fed the pass-1 numbers, before the tail fade.
+ const af = spawned[0][spawned[0].indexOf('-af') + 1];
+ expect(af).toMatch(/^atrim=duration=1,asetpts=PTS-STARTPTS,loudnorm=I=-14:TP=-2:LRA=11:measured_I=-27.3:measured_TP=-24:measured_LRA=2:measured_thresh=-40:offset=0.3:linear=true,aresample=48000,afade=t=out:st=0.5:d=0.5$/);
+ // Pass 3 reads the finished file.
+ expect(runs[1]).toContain('/tmp/out.mp4');
+ expect(result.loudness).toEqual({ integratedLufs: -14.1, truePeakDb: -1.6, loudnessRange: 2, masteredFrom: { integratedLufs: -27.3, truePeakDb: -24 }, targetLufs: -14 });
+ });
+
+ it('refuses a silent bed before spending a single frame, naming the cause', async () => {
+ const runFfmpeg = async () => ({ ok: true, stderr: loudnormJson('-inf', '-inf') });
+ const { spawned, spawnProcess } = fakeEncoder();
+ await expect(encodeComposition(page, contract, '/tmp/out.mp4', options({ musicPath: '/lib/bed.wav', master: true, runFfmpeg, spawnProcess })))
+ .rejects.toThrow(/Soundtrack is silent: measured no signal \(below -50 LUFS\)/);
+ expect(spawned).toHaveLength(0);
+ expect(SILENT_LUFS).toBe(-50);
+ });
+
+ it('says why when the bed cannot be measured', async () => {
+ const runFfmpeg = async () => ({ ok: false, reason: 'ffmpeg exit 1: Output file does not contain any stream' });
+ await expect(encodeComposition(page, contract, '/tmp/out.mp4', options({ musicPath: '/lib/bed.wav', master: true, runFfmpeg, spawnProcess: fakeEncoder().spawnProcess })))
+ .rejects.toThrow(/could not measure the soundtrack: ffmpeg exit 1/);
+ });
+
+ it('master off reproduces the unmastered mux and never measures', async () => {
+ const runFfmpeg = vi.fn();
+ const { spawned, spawnProcess } = fakeEncoder();
+ const result = await encodeComposition(page, contract, '/tmp/out.mp4', options({ musicPath: '/lib/bed.wav', master: false, runFfmpeg, spawnProcess }));
+ expect(runFfmpeg).not.toHaveBeenCalled();
+ expect(spawned[0][spawned[0].indexOf('-af') + 1]).toBe('atrim=duration=1,asetpts=PTS-STARTPTS,afade=t=out:st=0.5:d=0.5');
+ expect(result.loudness).toBeUndefined();
+ });
+
+ it('never masters an exact music-video master', async () => {
+ const runFfmpeg = vi.fn();
+ const { spawned, spawnProcess } = fakeEncoder();
+ await encodeComposition(page, contract, '/tmp/out.mp4', options({ audio: { path: '/masters/song.wav', startSec: 3 }, master: true, runFfmpeg, spawnProcess }));
+ expect(runFfmpeg).not.toHaveBeenCalled();
+ expect(spawned[0]).not.toContain('-af');
+ });
+});
+
+const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();
+
+describe.skipIf(!hasFfmpeg)('encodeComposition loudness mastering (real ffmpeg)', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'portos-mastering-'));
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+ it.each([
+ ['a sine peaking near -30 dBFS', 'sine=frequency=440:sample_rate=24000', 'volume=-12dB'],
+ ['noise at full scale', 'anoisesrc=color=pink:sample_rate=24000:amplitude=1', 'alimiter=limit=1:level=disabled'],
+ ])('masters %s to the target with true peak under the ceiling', async (label, source, filter) => {
+ const png = (await sharp({ create: { width: 64, height: 64, channels: 3, background: '#223' } }).png().toBuffer()).toString('base64');
+ const real = { ...page, async send(method) { return method === 'Page.captureScreenshot' ? { data: png } : {}; } };
+ const musicPath = join(dir, `${label.replace(/\W+/g, '-')}.wav`);
+ execFileSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', source, '-t', '6', '-af', filter, '-ac', '1', '-y', musicPath]);
+ const out = join(dir, `out-${label.replace(/\W+/g, '-')}.mp4`);
+ const { loudness } = await encodeComposition(real, { fps: 5, durationSec: 6, width: 64, height: 64, motionBlur: 1 }, out, { musicPath, master: true });
+ expect(Math.abs(loudness.integratedLufs - MASTER_LOUDNESS.targetLufs)).toBeLessThanOrEqual(1);
+ expect(loudness.truePeakDb).toBeLessThanOrEqual(MASTER_LOUDNESS.truePeakDb);
+ expect(loudness.masteredFrom.integratedLufs).not.toBe(loudness.integratedLufs);
+ }, 60000);
+});
diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.js
index 5633ff7ea0..5cf68c6c59 100644
--- a/server/services/htmlComposition/index.js
+++ b/server/services/htmlComposition/index.js
@@ -162,7 +162,7 @@ async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec,
const parsedInput = validateRequest(htmlCompositionRenderSchema, input);
let { directory } = parsedInput;
const sourceDirectory = directory;
- const { musicTrack, launchVideo, synthesizeMusic, proof, formats, motionBlur: blurChoice } = parsedInput;
+ const { musicTrack, launchVideo, synthesizeMusic, proof, formats, motionBlur: blurChoice, masterLoudness } = parsedInput;
// A music-video render may still ask for the extra frames its contract
// declares in portosComposition.formats (renderTargets enforces that).
if (musicVideo && (launchVideo || synthesizeMusic || musicTrack || proof)) {
@@ -265,8 +265,9 @@ async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec,
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, {
+ const { sampleHistogram, loudness } = await encodeComposition(page, target.contract, outputPath, {
musicPath: musicVideo ? null : musicPath,
+ master: masterLoudness !== false,
audio: musicVideo?.audio,
signal,
onProgress: (fraction, detail) => {
@@ -287,7 +288,7 @@ async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec,
});
framesDone += targetFrames;
page.check();
- rendered.push({ ...target, filename, outputPath, sampleHistogram });
+ rendered.push({ ...target, filename, outputPath, sampleHistogram, loudness });
}
// End script execution before post-processing and publishing the result.
await page.close({ verify: true });
@@ -329,6 +330,7 @@ async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec,
...frameOf(video.contract), numFrames: Math.round(contract.durationSec * contract.fps),
...(launchMetadata ? { launchVideo: launchMetadata, appId: launchMetadata.appId, posterSec: launchPlan.posterSec } : {}),
...(video.sampleHistogram ? { sampleHistogram: video.sampleHistogram } : {}),
+ ...(video.loudness ? { loudness: video.loudness } : {}),
filename: video.filename, thumbnail: video.thumbnail, createdAt,
}));
await mutateVideoHistory(history => { history.unshift(...metas); return history; });
@@ -337,8 +339,8 @@ async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec,
// is the job. A single-format render keeps id === generationId as before.
// 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 summary = ({ id, filename, thumbnail, sampleHistogram, loudness }) => ({ id, filename, thumbnail, path: `/data/videos/${filename}`,
+ ...(sampleHistogram ? { sampleHistogram } : {}), ...(loudness ? { loudness } : {}) });
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/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.js
index dbe3ef20f8..e7358a8a1f 100644
--- a/server/services/musicVideo/documentRender.js
+++ b/server/services/musicVideo/documentRender.js
@@ -297,7 +297,7 @@ function documentMuxArgs(videoPath, audioPath, outputPath, { startSec, durationS
}
const bed = buildBed({
beds: [{ assetPath: soundBed.path, offsetSec: 0, durationSec: songDurationSec, volume: soundBed.volume }],
- firstInputIdx: 2, mainLabel: '[master]', outLabel: '[mixa]',
+ firstInputIdx: 2, mainLabel: '[master]', outLabel: '[mixa]', limitPeak: true,
});
const filters = [`[1:a]${audioNorm}[master]`, ...bed.filters,
`[mixa]atrim=start=${startSec}:end=${startSec + durationSec},asetpts=PTS-STARTPTS,apad=whole_dur=${durationSec}${fade}[outa]`];
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index a986a86619..b39201e9ce 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -522,6 +522,7 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
firstInputIdx: audioIdx + 1 + overlays.length,
mainLabel: '[master]',
outLabel: '[mixa]',
+ limitPeak: true,
});
inputs.push(...bed.inputs);
filters.push(...bed.filters);
diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.js
index 250a267079..97c15ca69e 100644
--- a/server/services/musicVideo/render.test.js
+++ b/server/services/musicVideo/render.test.js
@@ -138,7 +138,10 @@ describe('sound-design bed (#8988)', () => {
expect(fc).toContain('[2:a]aresample=48000');
expect(fc).toMatch(/\[4:a\][^;]*atrim=start=0:end=4,[^;]*volume=0\.3\[bed0\]/);
// The song keeps its length and level: duration=first, normalize=0.
- expect(fc).toContain('[master][bed0]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[mixa]');
+ expect(fc).toContain('[master][bed0]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[bedmix]');
+ // Only a true-peak guard follows the mix: no gain stage on the song.
+ expect(fc).toContain('[bedmix]alimiter=limit=0.8414:level=disabled,aresample=48000');
+ expect(fc).toContain('[mixa];');
// A draft excerpt windows the MIXED audio, not the bare song.
expect(fc).toContain('[mixa]atrim=start=1:end=3,asetpts=PTS-STARTPTS[outax]');
expect(mapsOf(args)).toEqual(['[outvx]', '[outax]']);
diff --git a/server/services/videoTimeline/audioBedMix.js b/server/services/videoTimeline/audioBedMix.js
index 487f56870f..137bc49ae3 100644
--- a/server/services/videoTimeline/audioBedMix.js
+++ b/server/services/videoTimeline/audioBedMix.js
@@ -12,6 +12,9 @@
* each caller owns its own input numbering and graph labels.
*/
+/** MASTER_LOUDNESS.truePeakDb (-1.5 dB) as a linear amplitude, for alimiter's `limit`. */
+export const PEAK_CEILING_LINEAR = 0.8414;
+
/** ffmpeg-safe number formatting (six decimals, no exponent). */
export const fmtSec = (n) => String(Math.round(Number(n) * 1e6) / 1e6);
@@ -24,9 +27,11 @@ export const AUDIO_NORM = 'aresample=48000,aformat=sample_fmts=fltp:channel_layo
* @param {number} opts.firstInputIdx ffmpeg input index the first bed will take
* @param {string} opts.mainLabel the main audio's filter label, e.g. `[ca]`
* @param {string} opts.outLabel the mixed output label, e.g. `[outa]`
+ * @param {boolean} [opts.limitPeak] end the mix with an `alimiter` at the -1.5 dB ceiling (#10249).
+ * Only peaks above the ceiling are touched; the main audio gets no gain change.
* @returns {{ inputs: string[], filters: string[] }}
*/
-export function buildAudioBedMix({ beds, firstInputIdx, mainLabel, outLabel }) {
+export function buildAudioBedMix({ beds, firstInputIdx, mainLabel, outLabel, limitPeak = false }) {
const inputs = [];
const filters = [];
const bedLabels = [];
@@ -52,7 +57,9 @@ export function buildAudioBedMix({ beds, firstInputIdx, mainLabel, outLabel }) {
bedLabels.push(`[bed${j}]`);
});
if (bedLabels.length > 0) {
- filters.push(`${mainLabel}${bedLabels.join('')}amix=inputs=${bedLabels.length + 1}:duration=first:dropout_transition=0:normalize=0${outLabel}`);
+ const mixed = limitPeak ? '[bedmix]' : outLabel;
+ filters.push(`${mainLabel}${bedLabels.join('')}amix=inputs=${bedLabels.length + 1}:duration=first:dropout_transition=0:normalize=0${mixed}`);
+ if (limitPeak) filters.push(`${mixed}alimiter=limit=${PEAK_CEILING_LINEAR}:level=disabled,${AUDIO_NORM}${outLabel}`);
}
return { inputs, filters };
}
diff --git a/server/services/videoTimeline/audioBedMix.test.js b/server/services/videoTimeline/audioBedMix.test.js
new file mode 100644
index 0000000000..6d16475594
--- /dev/null
+++ b/server/services/videoTimeline/audioBedMix.test.js
@@ -0,0 +1,46 @@
+import { execFileSync, spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import { AUDIO_NORM, buildAudioBedMix, PEAK_CEILING_LINEAR } from './audioBedMix.js';
+
+const bed = { assetPath: '/lib/bed.wav', offsetSec: 0, durationSec: 4, volume: 1 };
+const mix = (extra) => buildAudioBedMix({ beds: [bed], firstInputIdx: 1, mainLabel: '[master]', outLabel: '[mixa]', ...extra });
+
+describe('buildAudioBedMix peak guard', () => {
+ it('leaves the mix exactly as before unless asked', () => {
+ expect(mix().filters.at(-1)).toMatch(/amix=inputs=2:duration=first:dropout_transition=0:normalize=0\[mixa\]$/);
+ });
+
+ it('ends the mix with an alimiter at the ceiling and no gain stage', () => {
+ const { filters } = mix({ limitPeak: true });
+ expect(filters.at(-2)).toMatch(/normalize=0\[bedmix\]$/);
+ expect(filters.at(-1)).toBe(`[bedmix]alimiter=limit=${PEAK_CEILING_LINEAR}:level=disabled,${AUDIO_NORM}[mixa]`);
+ expect(filters.join(';')).not.toMatch(/loudnorm|volume=/);
+ });
+});
+
+let hasFfmpeg = true;
+try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); } catch { hasFfmpeg = false; }
+
+describe.skipIf(!hasFfmpeg)('buildAudioBedMix peak guard (real ffmpeg)', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'portos-bedmix-'));
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+ const peak = (path) => spawnSync('ffmpeg', ['-hide_banner', '-nostats', '-i', path, '-af', 'astats=measure_overall=Peak_level', '-f', 'null', '-'], { encoding: 'utf8' }).stderr;
+ it('keeps a hot song plus a hot bed under the ceiling', () => {
+ const song = join(dir, 'song.wav');
+ const bedPath = join(dir, 'bed.wav');
+ execFileSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'sine=frequency=330:sample_rate=48000', '-t', '4', '-af', 'volume=18dB', '-c:a', 'pcm_f32le', '-y', song]);
+ execFileSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'sine=frequency=330:sample_rate=48000', '-t', '4', '-af', 'volume=18dB', '-c:a', 'pcm_f32le', '-y', bedPath]);
+ const { inputs, filters } = buildAudioBedMix({ beds: [{ ...bed, assetPath: bedPath }], firstInputIdx: 1, mainLabel: '[master]', outLabel: '[mixa]', limitPeak: true });
+ const out = join(dir, 'mix.wav');
+ const run = (graph, file) => execFileSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', song, ...inputs, '-filter_complex', graph, '-map', '[mixa]', '-c:a', 'pcm_f32le', '-y', file]);
+ run([`[0:a]${AUDIO_NORM}[master]`, ...filters].join(';'), out);
+ const unguarded = join(dir, 'unguarded.wav');
+ run([`[0:a]${AUDIO_NORM}[master]`, ...buildAudioBedMix({ beds: [{ ...bed, assetPath: bedPath }], firstInputIdx: 1, mainLabel: '[master]', outLabel: '[mixa]' }).filters].join(';'), unguarded);
+ const level = (path) => Number(/Peak level dB:\s*(-?[\d.]+)/.exec(peak(path))?.[1]);
+ expect(level(unguarded)).toBeGreaterThan(0);
+ expect(level(out)).toBeLessThanOrEqual(-1.4);
+ });
+});