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

fix: tag BT.709 color on ffmpeg-re-encoded video outputs (#3800)

[._.]/ Adam Eivy05f7f015dfb9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f5493947bd..e0ce56d07b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -100,3 +100,4 @@
- **A prompt change that skips the drift baseline no longer reddens `main` with an unreadable failure.** The stage-drift baseline is a deliberately independent hand-mirror of what the migrations export, so a prompt migration that ships a new body without carrying the baseline with it breaks a required check for every open PR — and the deep-equal it broke on reported only `expected { …(28) } to deeply equal { …(28) }`, which reads as the PR's own regression rather than an inherited one (three PRs were triaged past it before it was traced to `main`). The baseline now names the three stage prompts whose hashes moved, and the assertion reports the drifted files with their before/after hashes plus the fix to apply. The mirror stays hand-maintained on purpose: deriving it from the migrations' own exports would make it agree with them by construction and delete the guard.
- **PortOS now renders its intended typography with no route to the public internet, because the fonts ship with it.** #3808 stopped the app shell's Google Fonts stylesheet from blanking the page for ~60s on an install that can't reach Google, by loading it non-blocking — but non-blocking only meant the fonts failed *quietly*. They still never arrived, and this turned out to be broader than that fix assumed: four theme stacks in `themes/portosThemes.js` front Inter and one fronts IBM Plex Mono, so on the private-Tailscale deployment PortOS is designed for, five themes silently rendered in a system fallback and the typography was simply never seen. Both families are now vendored under `client/public/fonts/` as `woff2` and declared with `@font-face` in `client/src/index.css`, exactly as `GeistPixel-*` already was for CyberCity — scoped to the weights the stacks actually use (Inter 400/500/600/700, IBM Plex Mono 400/500/600) to keep the whole addition near 275KB. Both are SIL Open Font License 1.1, so each family's license text ships beside the files. The stylesheet `<link>`, its `<noscript>` fallback, and both `preconnect` hints are gone from `client/index.html`, which removes a third-party request from every boot; the service worker's dedicated cache for the Google font hosts went with them, since same-origin `/fonts/` was already covered by its static-asset path, and dropping it from the current-cache set means the stale one is deleted on activate. Verified in a headless browser against the built client with every external host blocked: all seven faces load, they measure differently from their fallbacks, and the page attempts zero external requests.
- **A generated Three.js model's materials are now checked against the substance they're named for.** `threejsMaterialSchema` bounds every PBR channel to what Three.js accepts, which is a much weaker claim than it looks: metalness 0.9 oak and transmission 1.0 steel both validate, both persist, and both light completely wrong — a wooden crate that reads as chrome, a window that reads as concrete — with nothing anywhere pushing back. A new material-plausibility gate keys a small per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's own id and reports the channels whose values that substance doesn't support, in both directions: metal that isn't metallic and glass that doesn't transmit are as much a finding as wood that does. It is advisory by construction and never clamps, because a stylized model is entitled to break every prior in the table — and the matching is deliberately conservative to match: a material keys a prior only when its id names exactly one family, so `mat_primary` and `wood_metal_trim` produce no feedback rather than a wrong one, and a channel the material's `type` never forwards to Three.js is skipped rather than reported as a defect the user can't see. Findings land on the record, show up in a new panel on the model detail page, and an unsteered refinement now asks for values that match the substance alongside the existing coverage, depth, and penetration feedback.
+- **Stitched and re-encoded video renders now carry BT.709 color tags, so they stop decoding washed-out.** Every ffmpeg re-encode in video-gen — the chained render's chunk stitch, the frame-exact trim behind its context window, and the 2× upscale export — wrote H.264 with no color metadata at all, leaving each player to guess a color space (and the common guess for HD content differs from the one for SD). The three `-color_primaries/-color_trc/-colorspace` container flags alone do not fix this on ffmpeg 8: the encoder reads its color properties off the *frames* coming down the filter graph, which inherit the decoded input's unspecified values and silently override the flags — verified locally on ffmpeg 8.1.1, where a flags-only output came back `color_primaries=unknown, color_transfer=unknown`. All three sites now emit the container flags *and* a trailing `setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709` on the video chain, which makes all three properties stick. The `setparams` filter only landed in ffmpeg 4.3 and an older build aborts the whole run on an unknown filter, so its availability is probed once per process from `-filters` and the tag is dropped (container flags only) when it isn't there — a probe that could not run is left uncached rather than remembered as "unsupported", so one transient failure can't disable tagging for the life of the server.
diff --git a/server/lib/README.md b/server/lib/README.md
index ba463ffaa1..b22d8b0ca4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -185,7 +185,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). 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. |
+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). 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. |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 348b3b1987..64bb3235eb 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -351,6 +351,66 @@ export const H264_ENCODE_ARGS = Object.freeze([
]);
export const AAC_ENCODE_ARGS = Object.freeze(['-c:a', 'aac', '-b:a', '192k']);
+// BT.709 color tagging for every re-encode this module writes.
+//
+// Untagged H.264 makes each player guess a color space, and the common guess
+// for HD content differs from the one for SD — so a stitched clip that carries
+// no tags decodes washed-out (or over-saturated) depending on where it's
+// opened. The renders these helpers re-encode are BT.709 in practice; the fix
+// is to SAY so on the output.
+//
+// It takes both halves to stick. The container flags below write the tags into
+// the MP4's `colr` atom, but from ffmpeg 8 the encoder reads its color
+// properties off the FRAMES coming down the filter graph — and those inherit
+// the (usually unspecified) values of the decoded input, silently overriding
+// the flags. `setparams` stamps the frame properties themselves, so the
+// encoder and the container agree.
+export const BT709_TAG_FILTER = 'setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709';
+export const BT709_CONTAINER_ARGS = Object.freeze([
+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709',
+]);
+
+// `null` = not probed yet; `true`/`false` = the answer this ffmpeg build gave.
+// A probe that couldn't run (no binary, `-filters` failed) is NOT an answer and
+// is deliberately left uncached, so a later call still gets a real result
+// instead of a permanent "unsupported" from one transient failure.
+let setparamsAvailable = null;
+
+// Test seam — resets the capability cache between cases.
+export const __resetSetparamsProbe = () => { setparamsAvailable = null; };
+
+// Does this ffmpeg build carry the `setparams` filter? It landed in ffmpeg 4.3;
+// older builds (still common in distro packages) parse it as an unknown filter
+// and abort the whole run, which would turn a color-tagging nicety into a
+// failed render. Probe once per process — the binary can't change under us.
+export const supportsSetparamsFilter = async () => {
+ if (setparamsAvailable !== null) return setparamsAvailable;
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return false;
+ const listing = await execFileAsync(ffmpeg, ['-hide_banner', '-filters'], {
+ env: safeChildProcessEnv(),
+ maxBuffer: 4 * 1024 * 1024,
+ }).then((r) => String(r.stdout || ''), () => null);
+ if (listing === null) return false;
+ setparamsAvailable = /(^|\s)setparams(\s|$)/m.test(listing);
+ if (!setparamsAvailable) {
+ console.log('⚠️ ffmpeg has no setparams filter — BT.709 tags will ride the container flags only');
+ }
+ return setparamsAvailable;
+};
+
+// The filter string to append to a re-encode's video chain, or `null` when this
+// ffmpeg build can't take it. Callers still spread `BT709_CONTAINER_ARGS`
+// unconditionally — those flags are accepted by every build worth supporting.
+export const bt709TagFilter = async () => (await supportsSetparamsFilter() ? BT709_TAG_FILTER : null);
+
+// Append a filter to a comma-separated ffmpeg filter chain, tolerating both an
+// empty chain and a `null` filter (the unsupported-build case).
+const appendFilter = (chain, filter) => {
+ if (!filter) return chain;
+ return chain ? `${chain},${filter}` : filter;
+};
+
// Move a freshly-encoded temp file over the file it replaces.
//
// POSIX rename atomically replaces an existing destination in one syscall. On
@@ -424,17 +484,19 @@ export const trimVideoFromFrame = async (videoPath, outPath, { startFrame, fps }
if (!inPlace) await ensureDir(dirname(outPath));
const audio = await hasAudioStream(videoPath);
+ const colorFilter = await bt709TagFilter();
const result = await runFfmpegProcess({
bin: ffmpeg,
args: [
'-i', videoPath,
- '-vf', `trim=start_frame=${start},setpts=PTS-STARTPTS`,
+ '-vf', appendFilter(`trim=start_frame=${start},setpts=PTS-STARTPTS`, colorFilter),
...(audio
// atrim takes seconds; the frame index converts exactly because the
// clips this runs on are CFR renders straight out of the model.
? ['-af', `atrim=start=${(start / rate).toFixed(6)},asetpts=PTS-STARTPTS`, ...AAC_ENCODE_ARGS]
: ['-an']),
...H264_ENCODE_ARGS,
+ ...BT709_CONTAINER_ARGS,
'-movflags', '+faststart',
'-y', encodePath,
],
@@ -471,7 +533,13 @@ export const trimVideoFromFrame = async (videoPath, outPath, { startFrame, fps }
// (`hasAudioStream`): `concat=a=1` needs an audio leg from each input, and
// referencing `[k:a]` on a silent clip aborts the run. A mixed set takes the
// video-only graph, which is what a chain of silent AI renders wants anyway.
-export const buildTrimConcatArgs = ({ inputs, outPath, width, height, fps, withAudio = false }) => {
+//
+// `colorTagFilter` is the `setparams` string from `bt709TagFilter()` (or `null`
+// on an ffmpeg build without the filter). It stays a PARAMETER rather than
+// being probed in here so this builder remains pure and synchronously testable
+// — the caller is already async and does the probe once. The container flags
+// need no probe and are always emitted.
+export const buildTrimConcatArgs = ({ inputs, outPath, width, height, fps, withAudio = false, colorTagFilter = null }) => {
const clips = Array.isArray(inputs) ? inputs : [];
if (clips.length < 2) return null;
const canonW = Number(width);
@@ -513,7 +581,19 @@ export const buildTrimConcatArgs = ({ inputs, outPath, width, height, fps, withA
}
concatStreams.push(audio ? `[v${i}][a${i}]` : `[v${i}]`);
});
- filters.push(`${concatStreams.join('')}concat=n=${clips.length}:v=1:a=${audio ? 1 : 0}[outv]${audio ? '[outa]' : ''}`);
+ // Tag on the way OUT of the concat rather than per input: one stamp on the
+ // joined stream is what the encoder reads, and stamping each leg would repeat
+ // the filter N times for the same result. With an audio leg the concat emits
+ // two pads, so the tag can't simply trail the concat — give the video pad its
+ // own label and hang the filter off that in both shapes, so there is one code
+ // path instead of two.
+ // Only a real filter STRING earns the extra link — anything else would splice
+ // `[cv]undefined[outv]` into the graph and fail the whole encode, which is a
+ // far worse outcome than the untagged output it was meant to improve on.
+ const tag = typeof colorTagFilter === 'string' && colorTagFilter ? colorTagFilter : null;
+ const videoPad = tag ? '[cv]' : '[outv]';
+ filters.push(`${concatStreams.join('')}concat=n=${clips.length}:v=1:a=${audio ? 1 : 0}${videoPad}${audio ? '[outa]' : ''}`);
+ if (tag) filters.push(`[cv]${tag}[outv]`);
return [
...clips.flatMap((clip) => ['-i', clip.path]),
@@ -521,6 +601,7 @@ export const buildTrimConcatArgs = ({ inputs, outPath, width, height, fps, withA
'-map', '[outv]',
...(audio ? ['-map', '[outa]'] : []),
...H264_ENCODE_ARGS,
+ ...BT709_CONTAINER_ARGS,
...(audio ? AAC_ENCODE_ARGS : ['-an']),
'-movflags', '+faststart',
'-y', outPath,
@@ -564,8 +645,9 @@ export const upscaleVideo2x = async (videoPath) => {
bin: ffmpeg,
args: [
'-i', videoPath,
- '-vf', 'scale=iw*2:-2:flags=lanczos',
+ '-vf', appendFilter('scale=iw*2:-2:flags=lanczos', await bt709TagFilter()),
...H264_ENCODE_ARGS,
+ ...BT709_CONTAINER_ARGS,
'-c:a', 'copy',
'-movflags', '+faststart',
'-y', tmpPath,
diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.js
index 0dd2eb8228..d6cf99f560 100644
--- a/server/lib/ffmpeg.test.js
+++ b/server/lib/ffmpeg.test.js
@@ -1,9 +1,12 @@
-import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
import { writeFileSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream, buildTrimConcatArgs } from './ffmpeg.js';
+import {
+ verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream, buildTrimConcatArgs,
+ BT709_TAG_FILTER, BT709_CONTAINER_ARGS, bt709TagFilter, supportsSetparamsFilter, __resetSetparamsProbe,
+} from './ffmpeg.js';
describe('verifyVideoPlayable', () => {
let tmpDir;
@@ -241,4 +244,79 @@ describe('buildTrimConcatArgs', () => {
}));
expect(graph).not.toContain('trim=start_frame');
});
+
+ it('always emits the BT.709 container flags, filter or not', () => {
+ const flagsOf = (args) => BT709_CONTAINER_ARGS.every((a, i) => args[args.indexOf('-color_primaries') + i] === a);
+ expect(flagsOf(buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4' }))).toBe(true);
+ expect(flagsOf(buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4', colorTagFilter: BT709_TAG_FILTER }))).toBe(true);
+ });
+
+ it('stamps the color filter once, on the concat output rather than per input', () => {
+ const graph = graphOf(buildTrimConcatArgs({
+ inputs: CLIPS, outPath: '/v/out.mp4', width: 512, height: 288, fps: 24, colorTagFilter: BT709_TAG_FILTER,
+ }));
+ expect(graph).toContain(`[v0][v1]concat=n=2:v=1:a=0[cv];[cv]${BT709_TAG_FILTER}[outv]`);
+ // One stamp for the whole graph — not one per input leg.
+ expect(graph.split('setparams=').length - 1).toBe(1);
+ });
+
+ it('hangs the color filter off the video pad when the concat also emits audio', () => {
+ // `concat=a=1` produces two pads, so the tag can't trail the concat itself
+ // — the audio pad must stay reachable as [outa].
+ const args = buildTrimConcatArgs({
+ inputs: CLIPS, outPath: '/v/out.mp4', width: 512, height: 288, fps: 24, withAudio: true, colorTagFilter: BT709_TAG_FILTER,
+ });
+ const graph = graphOf(args);
+ expect(graph).toContain(`concat=n=2:v=1:a=1[cv][outa];[cv]${BT709_TAG_FILTER}[outv]`);
+ expect(args).toContain('[outa]');
+ expect(args).toContain('[outv]');
+ });
+
+ it('leaves the graph unlabelled by an extra link when there is no filter to apply', () => {
+ // The unsupported-ffmpeg shape: no [cv] hop at all, so an older build sees
+ // exactly the graph it saw before this change.
+ const graph = graphOf(buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4', colorTagFilter: null }));
+ expect(graph).toContain('concat=n=2:v=1:a=0[outv]');
+ expect(graph).not.toContain('[cv]');
+ });
+
+ it('ignores a non-string filter rather than splicing it into the graph', () => {
+ // A bad value must degrade to "untagged", never to an unparseable graph
+ // that fails the whole encode.
+ for (const bad of [undefined, 42, {}, true, '']) {
+ const graph = graphOf(buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4', colorTagFilter: bad }));
+ expect(graph).toContain('concat=n=2:v=1:a=0[outv]');
+ expect(graph).not.toContain('[cv]');
+ expect(graph).not.toMatch(/undefined|NaN|\[object/);
+ }
+ });
+});
+
+describe('bt709TagFilter / supportsSetparamsFilter', () => {
+ beforeEach(() => { __resetSetparamsProbe(); });
+ afterAll(() => { __resetSetparamsProbe(); });
+
+ it('returns the filter string or null, matching the probe', async () => {
+ const supported = await supportsSetparamsFilter();
+ expect(typeof supported).toBe('boolean');
+ expect(await bt709TagFilter()).toBe(supported ? BT709_TAG_FILTER : null);
+ });
+
+ it('caches a real probe result instead of re-shelling out per encode', async () => {
+ const first = await supportsSetparamsFilter();
+ // Only a real answer is cached, so this is only assertable when the host
+ // actually has ffmpeg — a missing binary is "unknown", not "unsupported".
+ if (!first) return;
+ const started = Date.now();
+ expect(await supportsSetparamsFilter()).toBe(true);
+ // A cache hit is a property read; a second `-filters` listing is not.
+ expect(Date.now() - started).toBeLessThan(50);
+ });
+
+ it('pins all three properties in the filter string', () => {
+ expect(BT709_TAG_FILTER).toBe('setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709');
+ expect([...BT709_CONTAINER_ARGS]).toEqual([
+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709',
+ ]);
+ });
});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 3f5a0a9434..39ef22f7c1 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -29,7 +29,7 @@ import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../.
import {
findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x,
extractEvaluationFrames, probeFrameCount, trimVideoFromFrame,
- hasAudioStream, buildTrimConcatArgs,
+ hasAudioStream, buildTrimConcatArgs, bt709TagFilter,
} from '../../lib/ffmpeg.js';
import {
resolveContextFrames, resolveContinuityStrategy, extendLatentFrames,
@@ -2316,6 +2316,11 @@ export async function stitchVideos(videoIds, opts = {}) {
// `concat=a=1` needs an audio leg from EVERY input; one silent clip in
// the set makes the whole graph video-only.
withAudio: (await Promise.all(videoPaths.map((p) => hasAudioStream(p)))).every(Boolean),
+ // Pin BT.709 on the stitched output — this is the only re-encode a
+ // chained render's timeline gets, so an untagged result here is what a
+ // player would have to guess at. `null` on an ffmpeg without the
+ // filter; the container flags ride along inside the builder regardless.
+ colorTagFilter: await bt709TagFilter(),
});
const failure = args
? await runFfmpeg(args, { captureStderr: true }).then(() => null, (err) => err)
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 16c5fd161f..a15cdf9faf 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -133,6 +133,10 @@ vi.mock('../../lib/ffmpeg.js', async () => ({
// The real builder is pure and covered by ffmpeg.test.js; keep it real here
// so the chain tests assert on the argv that actually reaches ffmpeg.
buildTrimConcatArgs: (await vi.importActual('../../lib/ffmpeg.js')).buildTrimConcatArgs,
+ // Report the setparams filter as available so the chain tests assert on the
+ // fully-tagged argv (the degraded, container-flags-only shape is covered in
+ // ffmpeg.test.js).
+ bt709TagFilter: vi.fn(async () => (await vi.importActual('../../lib/ffmpeg.js')).BT709_TAG_FILTER),
}));
// hfChildEnv() carries the resolved token over the inherited child env; mocking here
@@ -464,7 +468,11 @@ describe('generateChainedVideo — continuation strategy (context window vs last
for (const i of [1, 2]) {
expect(graph).toMatch(new RegExp(`\\[${i}:v\\][^;]*trim=start_frame=${EXPECTED_PREFIX_START}`));
}
- expect(graph).toContain('concat=n=3:v=1:a=0[outv]');
+ // All three legs join in one concat, whose output is then BT.709-tagged so
+ // the stitched timeline doesn't decode washed-out (#3800).
+ expect(graph).toContain('concat=n=3:v=1:a=0[cv]');
+ expect(graph).toContain('[cv]setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709[outv]');
+ expect(concat).toContain('-color_primaries');
// And the stitched record reports the timeline that exists, not the sum of
// what each chunk was rendered at.
expect(stitched?.numFrames).toBe(STITCHED_FRAMES_3_CHUNKS);