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

perf: apply chained-chunk trims in the concat filter graph instead of pre-encoding each chunk (#3761)

[._.]/ Adam Eivy3926f221b795
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4781339243..ae82731e03 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -271,3 +271,5 @@
- **[issue-3737] Every video model now carries a resolved `supportedModes`, so capability is a registry fact instead of a hardcoded runtime list.** "Which modes does this model actually support?" had no single answer: `wan22` and `minimax_h3` entries declared `supportedModes`, `mlx_video` and `ltx2` declared nothing, and `hunyuan` carried a legacy `mode: 't2v'` field no reader ever consulted. The client's model picker read "declares nothing" as "supports everything" — so it offered FFLF on runtimes whose helper takes a single `--image` and silently drops the other keyframe, a UI claiming a capability the render path doesn't honor. `server/lib/videoModeProfiles.js` now states each runtime's modes once, as facts about its helper's argv (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22` text+image, `minimax_h3` text+image+fflf — also the mode ceiling `modeContract.js` enforces, so the two can't drift — `hunyuan` text only, replacing the retired `mode: 't2v'`), and `getVideoModels()` resolves it on read — the way `listVideoModels()` already decorates `lastFrameAnchored` — so it covers the load path, the user-model mutators that bypass the load-time normalizer, and peer-synced entries in one place. Deriving on read rather than backfilling into the file (as the sibling `disclosure` / `finishModelId` facts do) is deliberate: a persisted copy reads back as a *declared* list, which is exactly what no later correction to the table could reach. An entry that declares its own list always wins, and there is no migration. `isModelAllowedForMode` lost its "no `supportedModes` ⇒ allow everything" fallback as a result. mlx_video's FFLF is declared *honestly rather than absent* — the mode does run, and the caveat rides on the existing `lastFrameAnchored: false` the client renders as "last frame is advisory". The server-side gate reads the same resolver, so `videoChainUnsupportedError` no longer waves an unresolved entry through as unconstrained while the picker hides it, and the client's two hand-rolled "can this model chain?" copies now ask `isModelAllowedForMode` instead of re-reading the field. An unknown runtime — a user-added model, or one synced from a newer peer — keeps the full base mode set rather than vanishing from every picker.
- **Image Gen's agy model picker lists models again, instead of reporting an empty catalog against a healthy one.** Choosing `agy` as the Image Gen provider showed "agy models returned no model ids — renders will use the model saved in Settings → Image Gen", with `agy models` printing a full eleven-model catalog on stdout the whole time. The parser dated from a build that printed one bare model id per line; agy now prints `<id>\t<Label>` rows (`gemini-3.6-flash-high⇥Gemini 3.6 Flash (High)`), so every row failed the bare-id test and the list came back empty — which the picker correctly refuses to present as a real fetch. Both the id-only and the tab-labelled shapes are now accepted, since other installs run older builds and every previously-persisted catalog was parsed under the old rule. The label is anchored on the tab rather than split on first whitespace on purpose: agy's own banner prose ("Fetching available models…") leads with a word that passes the id pattern, and a whitespace split would have persisted "Fetching" as a model. The same stale parse sat in the provider-catalog refresh behind Settings → Providers → Refresh models, whose failure was louder (it throws rather than falling back to the shipped seed) but has the identical cause; both now share one definition — `parseAntigravityModelList` in `server/lib/antigravity.js`, mirrored into the vendored toolkit copy — with a test that fails if the two ever disagree on any output shape.
+
+- **[issue-3761] A chained video render now pays exactly one encode pass, and archives each chunk exactly as the model rendered it.** Windowed continuation conditions chunk N+1 on the tail of chunk N, and LTX-2's extend pipeline returns `source + extension` — so every chunk after the first opens with an echo of that window, which the stitched timeline already holds. Cutting the echo used to mean rewriting each chunk file in place, and a frame-index cut can't be stream-copied: an N-chunk chain spent `(N−1)` full x264 crf-18 passes whose only product was a frame offset, then knocked the trimmed chunks out of codec lockstep with the never-trimmed chunk 0 and forced the concat to re-encode the whole timeline on top. The offsets now ride into the stitch instead of into the files: `stitchVideos` takes a `trims` map and applies the cuts inside its concat's own `filter_complex` graph (`buildTrimConcatArgs` in `server/lib/ffmpeg.js`, mirroring the normalization the video-timeline renderer already proved out — `scale`/`pad`/`setsar`/`fps` on the video leg and `aresample`/`aformat` on the audio leg are what keep ffmpeg from aborting with "Input link parameters do not match"). Total cost drops to the single timeline encode that was always going to happen, the trimmed chunks stop being graded one generation lossier than chunk 0, and the archived per-chunk gallery entries stay byte-identical to the render — carrying their echo, which is invisible since those entries are hidden by default. Audio legs are emitted only when *every* input has an audio stream, because `concat=a=1` needs one from each and referencing `[k:a]` on a silent clip aborts the run; a chain of silent renders takes the video-only graph. The old `reencode` and `frameCounts` options collapse into `trims`, and the hand-stitch path from Media History — which passes no offsets — keeps its demuxer stream-copy fast path untouched. A filter graph that fails to build no longer discards the chain: it falls back to the stream-copy concat over the untrimmed chunks (which were never re-encoded, so they are still in lockstep), replaying the context at each seam rather than losing every chunk already rendered.
diff --git a/server/lib/README.md b/server/lib/README.md
index 7161430b22..f7bbcca85b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -184,7 +184,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`. `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. |
| `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 f605f5768d..b4cbb65d78 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -447,6 +447,81 @@ export const trimVideoFromFrame = async (videoPath, outPath, { startFrame, fps }
return installEncodedVideo(encodePath, videoPath, 'trimmed');
};
+// Build the ffmpeg argv that concatenates a list of clips where SOME of them
+// must drop a leading run of frames first (`startFrame > 0`).
+//
+// Why a filter graph rather than trimming the files and running the concat
+// demuxer over them: a frame-index trim can't be stream-copied, so cutting
+// each clip in place costs one full encode per clip — and it also knocks the
+// trimmed clips out of codec lockstep with the untrimmed ones, forcing the
+// concat itself to re-encode too. Doing the cut inside the concat's own graph
+// collapses all of that into the single timeline encode that was going to
+// happen anyway, and leaves the source clips byte-identical on disk.
+//
+// Mirrors the shape `services/videoTimeline/local.js` renders projects with —
+// including the belt-and-suspenders normalization. `scale`+`pad`+`setsar` and
+// `fps=` on the video leg, `aresample`+`aformat` on the audio leg, are what
+// keep ffmpeg from aborting the whole run with "Input link parameters do not
+// match" when the inputs disagree even slightly. `width`/`height`/`fps` are
+// each applied only when they resolve to a usable number, so a caller that
+// doesn't know a canonical value simply gets no normalization for it rather
+// than an `undefined` in the graph.
+//
+// `withAudio` must be true only when EVERY input carries an audio stream
+// (`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 }) => {
+ const clips = Array.isArray(inputs) ? inputs : [];
+ if (clips.length < 2) return null;
+ const canonW = Number(width);
+ const canonH = Number(height);
+ const rate = Number(fps);
+ const hasDims = Number.isFinite(canonW) && canonW > 0 && Number.isFinite(canonH) && canonH > 0;
+ const hasRate = Number.isFinite(rate) && rate > 0;
+ // An audio leg on a trimmed input needs `atrim`'s start TIMESTAMP, which
+ // only exists if we know the frame rate. Without one, drop the audio rather
+ // than emit a graph whose audio and video are offset from each other.
+ const trimsAudio = clips.some((c) => Math.floor(Number(c?.startFrame) || 0) > 0);
+ const audio = Boolean(withAudio) && (hasRate || !trimsAudio);
+
+ const filters = [];
+ const concatStreams = [];
+ clips.forEach((clip, i) => {
+ const startFrame = Math.max(0, Math.floor(Number(clip?.startFrame) || 0));
+ const video = [
+ ...(hasDims ? [`scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1`] : []),
+ ...(hasRate ? [`fps=${rate}`] : []),
+ ...(startFrame > 0 ? [`trim=start_frame=${startFrame}`] : []),
+ 'setpts=PTS-STARTPTS',
+ ];
+ filters.push(`[${i}:v]${video.join(',')}[v${i}]`);
+ if (audio) {
+ const track = [
+ 'aresample=48000',
+ 'aformat=sample_fmts=fltp:channel_layouts=stereo',
+ // The frame index converts exactly because these are CFR renders.
+ ...(startFrame > 0 ? [`atrim=start=${(startFrame / rate).toFixed(6)}`] : []),
+ 'asetpts=PTS-STARTPTS',
+ ];
+ filters.push(`[${i}:a]${track.join(',')}[a${i}]`);
+ }
+ 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]' : ''}`);
+
+ return [
+ ...clips.flatMap((clip) => ['-i', clip.path]),
+ '-filter_complex', filters.join(';'),
+ '-map', '[outv]',
+ ...(audio ? ['-map', '[outa]'] : []),
+ ...H264_ENCODE_ARGS,
+ ...(audio ? AAC_ENCODE_ARGS : ['-an']),
+ '-movflags', '+faststart',
+ '-y', outPath,
+ ];
+};
+
// 2× Lanczos upscale of an MP4 in place. Doubles width and height while
// preserving the exact aspect ratio and the audio track. Used as a quick
// post-render export option for LTX renders that come out at sub-720p
diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.js
index 3c4845cfc4..25c0f13ed1 100644
--- a/server/lib/ffmpeg.test.js
+++ b/server/lib/ffmpeg.test.js
@@ -3,7 +3,7 @@ import { writeFileSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream } from './ffmpeg.js';
+import { verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream, buildTrimConcatArgs } from './ffmpeg.js';
describe('verifyVideoPlayable', () => {
let tmpDir;
@@ -169,3 +169,74 @@ describe('safeUnder', () => {
expect(safeUnder('/tmp/portos-root', 42)).toBeNull();
});
});
+
+describe('buildTrimConcatArgs', () => {
+ const CLIPS = [
+ { path: '/v/a.mp4', startFrame: 0 },
+ { path: '/v/b.mp4', startFrame: 9 },
+ ];
+ const graphOf = (args) => args[args.indexOf('-filter_complex') + 1];
+
+ it('needs at least two inputs to concat', () => {
+ expect(buildTrimConcatArgs({ inputs: [CLIPS[0]], outPath: '/v/out.mp4' })).toBeNull();
+ expect(buildTrimConcatArgs({ inputs: [], outPath: '/v/out.mp4' })).toBeNull();
+ expect(buildTrimConcatArgs({ inputs: null, outPath: '/v/out.mp4' })).toBeNull();
+ });
+
+ it('trims only the inputs that carry an offset, and maps them in order', () => {
+ const args = buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4', width: 512, height: 288, fps: 24 });
+ expect(args.slice(0, 4)).toEqual(['-i', '/v/a.mp4', '-i', '/v/b.mp4']);
+ const graph = graphOf(args);
+ // The untrimmed input still gets normalized + PTS-rebased, but no `trim`.
+ expect(graph).toContain('[0:v]scale=512:288:force_original_aspect_ratio=decrease,pad=512:288:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=24,setpts=PTS-STARTPTS[v0]');
+ expect(graph).toContain('trim=start_frame=9,setpts=PTS-STARTPTS[v1]');
+ expect(graph).toContain('[v0][v1]concat=n=2:v=1:a=0[outv]');
+ expect(args.slice(-2)).toEqual(['-y', '/v/out.mp4']);
+ });
+
+ it('omits geometry and rate filters it has no usable value for', () => {
+ // A caller that can't name a canonical size/rate gets no normalization
+ // rather than `scale=undefined:undefined`, which ffmpeg rejects outright.
+ const graph = graphOf(buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4' }));
+ expect(graph).not.toContain('scale=');
+ expect(graph).not.toContain('fps=');
+ expect(graph).not.toContain('undefined');
+ expect(graph).not.toContain('NaN');
+ // The trim itself is a frame index, so it survives the missing rate.
+ expect(graph).toContain('trim=start_frame=9');
+ });
+
+ it('adds a matching audio leg per input when every input has audio', () => {
+ const args = buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4', width: 512, height: 288, fps: 24, withAudio: true });
+ const graph = graphOf(args);
+ // atrim takes seconds: 9 frames at 24fps.
+ expect(graph).toContain('atrim=start=0.375000');
+ expect(graph).toContain('aformat=sample_fmts=fltp:channel_layouts=stereo');
+ expect(graph).toContain('[v0][a0][v1][a1]concat=n=2:v=1:a=1[outv][outa]');
+ expect(args).toContain('-c:a');
+ expect(args).not.toContain('-an');
+ });
+
+ it('drops audio rather than desyncing it when a trim has no frame rate to convert with', () => {
+ // `atrim` is timestamp-based; without an fps the audio would keep frames
+ // the video leg just cut, so the whole track goes rather than drift.
+ const graph = graphOf(buildTrimConcatArgs({ inputs: CLIPS, outPath: '/v/out.mp4', withAudio: true }));
+ expect(graph).not.toContain(':a]');
+ expect(graph).toContain('concat=n=2:v=1:a=0[outv]');
+ });
+
+ it('keeps audio on a rate-less concat when nothing is being trimmed', () => {
+ const untrimmed = [{ path: '/v/a.mp4' }, { path: '/v/b.mp4', startFrame: 0 }];
+ const graph = graphOf(buildTrimConcatArgs({ inputs: untrimmed, outPath: '/v/out.mp4', withAudio: true }));
+ expect(graph).toContain('concat=n=2:v=1:a=1[outv][outa]');
+ expect(graph).not.toContain('atrim');
+ });
+
+ it('clamps a negative or non-numeric offset to no trim at all', () => {
+ const graph = graphOf(buildTrimConcatArgs({
+ inputs: [{ path: '/v/a.mp4', startFrame: -5 }, { path: '/v/b.mp4', startFrame: 'nope' }],
+ outPath: '/v/out.mp4',
+ }));
+ expect(graph).not.toContain('trim=start_frame');
+ });
+});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index c251578fc8..e83df0fff1 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -28,7 +28,7 @@ import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../.
import {
findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x,
extractEvaluationFrames, probeFrameCount, trimVideoFromFrame,
- H264_ENCODE_ARGS, AAC_ENCODE_ARGS,
+ hasAudioStream, buildTrimConcatArgs,
} from '../../lib/ffmpeg.js';
import {
resolveContextFrames, resolveContinuityStrategy, extendLatentFrames,
@@ -1635,8 +1635,10 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// scene's MOTION, not just its final pose. Requires a runtime with an
// extend pipeline (ltx2 today) and applies whatever mode the chain started
// in. Because extend returns `source + extension`, each windowed chunk
-// opens with an echo of the window; that echo is measured and cut back off
-// before the stitch, so the timeline holds each frame exactly once.
+// opens with an echo of the window; that echo is measured and dropped
+// inside the stitch's concat filter graph, so the timeline holds each
+// frame exactly once while the chunk files stay as the model rendered
+// them.
// 'frame' — the historical hop: extract chunk N's last frame and run chunk
// N+1 as image-to-video off that still. What every other runtime gets, and
// what `contextFrames: 0` opts back into.
@@ -1698,12 +1700,12 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
// grew with the chain. Written under tmpdir and deleted when the chain ends.
let currentContextClip = null;
const contextClipPaths = [];
- // Post-trim frame count for each chunk we cut a context prefix off. Two jobs:
- // a non-empty map means at least one chunk was re-encoded (so the concat can
- // no longer stream-copy), and it tells stitchVideos the real lengths — the
- // chunks' own history entries record the frame count that was RENDERED, which
- // is a render parameter Remix reuses, not a measurement of the trimmed file.
- const trimmedFrameCounts = new Map();
+ // Echoed-context cut for each chunk that has one: where the chunk's own new
+ // footage starts, and how many frames it therefore contributes. Handed to
+ // stitchVideos, which applies the cuts in its concat filter graph — the
+ // chunk files themselves are never rewritten, so the chain pays exactly one
+ // encode (the stitch) instead of one per chunk plus the stitch.
+ const chunkTrims = new Map();
// First chunk always preserves the user's mode (text, image, fflf or extend)
// and is never trimmed: in an extend chain its output is `source clip +
// extension`, and the source clip belongs in the result exactly once — here.
@@ -1846,33 +1848,25 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
const chunkPath = join(PATHS.videos, `${chunkId}.mp4`);
if (continuity === 'window') {
- // One probe serves both cuts below. The trim rewrites chunkPath, so
- // `frames` is decremented rather than re-probed — `ffmpeg trim` keeps
- // exactly [prefix, total), which makes the new length arithmetic, and
- // probeFrameCount can fall back to a full decode pass.
+ // One probe serves both cuts below. Neither rewrites chunkPath, so the
+ // count stays valid for both — worth keeping to one call because
+ // probeFrameCount falls back to a full decode pass when the container
+ // header carries no nb_frames.
// eslint-disable-next-line no-await-in-loop
- let frames = await probeFrameCount(chunkPath);
+ const frames = await probeFrameCount(chunkPath);
// A window hop's render is `context window + new frames`. The window is
// the tail of the chunk before it, which the stitched timeline already
- // holds, so cut it back off before this chunk joins the concat. Measured
- // from the RENDERED length rather than from the window we supplied: the
- // VAE snaps the encoded context up to a latent boundary, so the echo is
- // usually a few frames longer than what we handed in.
+ // holds, so record where the new footage starts and let the stitch drop
+ // the echo in its filter graph. Measured from the RENDERED length rather
+ // than from the window we supplied: the VAE snaps the encoded context up
+ // to a latent boundary, so the echo is usually a few frames longer than
+ // what we handed in.
+ let contextPrefix = 0;
if (i > 0) {
- const prefix = contextPrefixFrames({ totalFrames: frames, extendLatents: chunkExtendLatents });
- if (prefix > 0) {
- // eslint-disable-next-line no-await-in-loop
- const trim = await trimVideoFromFrame(chunkPath, chunkPath, { startFrame: prefix, fps: chainFps });
- if (trim.ok) {
- frames -= prefix;
- trimmedFrameCounts.set(chunkId, frames);
- } else {
- // Degrade rather than throw away the whole chain: an untrimmed
- // chunk costs the viewer a ~1s repeat at one seam, where failing
- // here would discard every chunk already rendered.
- console.log(`⚠️ Chunk ${i + 1}/${totalChunks} context trim failed, seam will repeat ${prefix} frames: ${trim.reason}`);
- }
+ contextPrefix = contextPrefixFrames({ totalFrames: frames, extendLatents: chunkExtendLatents });
+ if (contextPrefix > 0) {
+ chunkTrims.set(chunkId, { startFrame: contextPrefix, frames: frames - contextPrefix });
} else {
console.log(`⚠️ Chunk ${i + 1}/${totalChunks} context prefix unmeasurable (frames=${frames ?? 'unknown'}), leaving it untrimmed`);
}
@@ -1894,7 +1888,11 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
const contextPath = join(tmpdir(), `chaincontext-${chunkId}.mp4`);
// eslint-disable-next-line no-await-in-loop
const cut = await trimVideoFromFrame(chunkPath, contextPath, {
- startFrame: tailWindowStartFrame({ totalFrames: frames, frames: windowFrames }),
+ // Floored at the echo the stitch is going to drop: the window must
+ // come from this chunk's OWN footage, never from the replay of the
+ // one before it. (The chunk file still holds that replay now that
+ // the cut happens at stitch time.)
+ startFrame: Math.max(contextPrefix, tailWindowStartFrame({ totalFrames: frames, frames: windowFrames })),
fps: chainFps,
});
if (!cut.ok) {
@@ -1929,13 +1927,9 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
// from — the individual chunk entries only ever hold their own resolved
// prompt, which loses which of them were explicit beats vs. fallbacks.
chunkPrompts: chunkPrompts?.some(Boolean) ? chunkPrompts : null,
- // A trimmed chunk was re-encoded, so it no longer shares an identical
- // codec/parameter set with its untrimmed siblings and the concat
- // demuxer's `-c copy` fast path can't be trusted across the mix.
- reencode: trimmedFrameCounts.size > 0,
- // Trimmed chunks are shorter on disk than the frame count they were
- // rendered at, so the stitched duration can't just sum the chunk records.
- frameCounts: trimmedFrameCounts.size ? trimmedFrameCounts : null,
+ // Echoed-context prefixes to cut out of each windowed chunk as the
+ // timeline is assembled, rather than by pre-encoding the chunk files.
+ trims: chunkTrims.size ? chunkTrims : null,
}).catch((err) => ({ error: err.message }));
if (stitched?.error) {
await setHistoryItemsHidden(chunkIds, true);
@@ -2105,10 +2099,14 @@ export async function sampleEvaluationFrames(jobId, count = 5) {
}
// Concat selected videos (preserving order) into a single MP4. Uses ffmpeg's
-// concat demuxer, stream-copy by default, so it's fast and lossless — but the
+// concat demuxer with a stream copy, so it's fast and lossless — but the
// inputs must then share codec/resolution. The Media History page already only
-// lets users stitch from a single model so this holds in practice; a caller
-// whose inputs have been re-encoded out of lockstep passes `reencode: true`.
+// lets users stitch from a single model so this holds in practice.
+//
+// A caller that needs leading frames dropped from some inputs passes `trims`
+// instead; that switches to a concat FILTER GRAPH, which applies the cuts and
+// the concat in one encode. Nothing else reaches the filter graph, so the
+// hand-stitch path from Media History keeps its stream-copy fast path.
//
// `opts` lets the chained-render code reuse the same ffmpeg path with a
// different identity (id, filename prefix, history-link key, prompt, per-chunk
@@ -2122,18 +2120,19 @@ export async function stitchVideos(videoIds, opts = {}) {
// Per-chunk prompt beats to record on the stitched entry (#3695) — chained
// renders only; a hand-stitched clip has no beats.
chunkPrompts = null,
- // Normalize every input through one encoder instead of stream-copying.
- // Required when the inputs no longer share identical codec parameters —
- // the chained-render context trim re-encodes the chunks it cuts, and the
- // concat demuxer's `-c copy` needs its inputs to match exactly. Costs an
- // encode pass over the whole timeline, so it stays opt-in.
- reencode = false,
- // Optional `Map<videoId, frames>` overriding what an input contributes to
- // the stitched entry's `numFrames`. A history entry's `numFrames` is the
- // count the clip was RENDERED at — a render parameter Remix reuses — so a
- // caller that shortened a file on disk reports the real length here instead
- // of rewriting that record and changing what a Remix of it would produce.
- frameCounts = null,
+ // Optional `Map<videoId, { startFrame, frames }>` — leading frames to drop
+ // from an input, and the frame count it contributes once they're gone.
+ //
+ // A chained render's windowed chunks open with an echo of the tail window
+ // they were conditioned on, which the timeline already holds. Cutting that
+ // echo in this concat's filter graph costs nothing beyond the timeline
+ // encode; pre-trimming each chunk file instead would add one full encode
+ // per chunk and re-grade the trimmed chunks relative to their siblings.
+ //
+ // `frames` feeds the stitched entry's `numFrames`, because a history
+ // entry's own `numFrames` is the count the clip was RENDERED at — a render
+ // parameter Remix reuses, not a measurement of what it contributes here.
+ trims = null,
} = opts;
if (!Array.isArray(videoIds) || videoIds.length < 2) {
throw new ServerError('Need at least 2 videos to stitch', { status: 400, code: 'VALIDATION_ERROR' });
@@ -2156,37 +2155,77 @@ export async function stitchVideos(videoIds, opts = {}) {
if (!existsSync(p)) throw new ServerError(`Missing: ${basename(p)}`, { status: 404, code: 'NOT_FOUND' });
}
+ // Leading-frame cut per input, in `videos` order. A zero/absent offset means
+ // the input joins whole; any non-zero offset routes the whole concat through
+ // the filter graph, since only that path can express a cut.
+ const trimPlan = videos.map((v) => {
+ const startFrame = Math.max(0, Math.floor(Number(trims?.get?.(v.id)?.startFrame) || 0));
+ if (startFrame <= 0) return null;
+ const frames = Number(trims.get(v.id).frames);
+ return { startFrame, frames: Number.isFinite(frames) && frames >= 0 ? frames : null };
+ });
+
const listFile = join(tmpdir(), `concat-${id}.txt`);
- // ffmpeg concat-demuxer escape: per its docs, single quotes in filenames
- // must be replaced with `'\''`. Inside quoted strings ffmpeg also treats
- // backslash as an escape character — on Windows where paths are
- // `C:\foo\bar.mp4`, that corrupts the path. Normalize to forward slashes
- // (which ffmpeg accepts on Windows just fine) before quoting.
- const escapeForConcat = (p) => p.replace(/\\/g, '/').replace(/'/g, "'\\''");
- await writeFile(listFile, videoPaths.map((p) => `file '${escapeForConcat(p)}'`).join('\n'));
+ let listFileWritten = false;
+ const writeConcatList = async () => {
+ // ffmpeg concat-demuxer escape: per its docs, single quotes in filenames
+ // must be replaced with `'\''`. Inside quoted strings ffmpeg also treats
+ // backslash as an escape character — on Windows where paths are
+ // `C:\foo\bar.mp4`, that corrupts the path. Normalize to forward slashes
+ // (which ffmpeg accepts on Windows just fine) before quoting.
+ const escapeForConcat = (p) => p.replace(/\\/g, '/').replace(/'/g, "'\\''");
+ await writeFile(listFile, videoPaths.map((p) => `file '${escapeForConcat(p)}'`).join('\n'));
+ listFileWritten = true;
+ };
const outFilename = `${filenamePrefix}-${id}.mp4`;
const outPath = join(PATHS.videos, outFilename);
+ const runFfmpeg = (args) => new Promise((resolve, reject) => {
+ const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: 'ignore' });
+ proc.on('close', (code) => code === 0 ? resolve() : reject(new ServerError('Stitch failed', { status: 500, code: 'FFMPEG_FAILED' })));
+ proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));
+ });
+
+ // Tracks whether the trims actually made it into the output, so `numFrames`
+ // below reports the timeline that exists rather than the one we asked for.
+ let trimsApplied = trimPlan.some(Boolean);
// Use a try/finally so the concat list temp file is cleaned up even when
// ffmpeg rejects — otherwise it leaks one file per failed stitch.
try {
- await new Promise((resolve, reject) => {
- const codecArgs = reencode
- // Matches trimVideoFromFrame's encoder so a trimmed chunk isn't
- // re-graded relative to its untrimmed siblings. `-c:a` is safe to pass
- // unconditionally — ffmpeg ignores it when the concatenated inputs
- // carry no audio stream at all (every chunk in a chain shares one
- // model and one audio setting, so they're never mixed).
- ? [...H264_ENCODE_ARGS, ...AAC_ENCODE_ARGS]
- : ['-c', 'copy'];
- const proc = spawn(ffmpeg, ['-f', 'concat', '-safe', '0', '-i', listFile, ...codecArgs, '-y', outPath], { env: safeChildProcessEnv(), stdio: 'ignore' });
- proc.on('close', (code) => code === 0 ? resolve() : reject(new ServerError('Stitch failed', { status: 500, code: 'FFMPEG_FAILED' })));
- proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));
- });
+ if (trimsApplied) {
+ const args = buildTrimConcatArgs({
+ inputs: videoPaths.map((path, i) => ({ path, startFrame: trimPlan[i]?.startFrame || 0 })),
+ outPath,
+ // Canonical geometry/rate for the graph's normalization filters. Taken
+ // from the first input the same way modelId/seed are below — every
+ // caller that reaches here stitches one model's own output.
+ width: videos[0].width,
+ height: videos[0].height,
+ fps: videos[0].fps,
+ // `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),
+ });
+ const failure = args
+ ? await runFfmpeg(args).then(() => null, (err) => err)
+ : new Error('could not build the concat filter graph');
+ if (failure) {
+ // Degrade rather than throw away a whole chained render: the untrimmed
+ // inputs were never re-encoded, so they're still in codec lockstep and
+ // the stream-copy concat below can salvage the clip. The cost is the
+ // echoed context replaying at each trimmed seam.
+ console.log(`⚠️ Trimmed concat failed (${failure.message}) — falling back to a stream copy; ${trimPlan.filter(Boolean).length} seam(s) will repeat their context`);
+ trimsApplied = false;
+ }
+ }
+ if (!trimsApplied) {
+ await writeConcatList();
+ await runFfmpeg(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath]);
+ }
await optimizeForStreaming(outPath);
} finally {
- await unlink(listFile).catch(() => {});
+ if (listFileWritten) await unlink(listFile).catch(() => {});
}
const thumb = await generateThumbnail(outPath, id);
@@ -2199,7 +2238,9 @@ export async function stitchVideos(videoIds, opts = {}) {
seed: videos[0].seed ?? 0,
width: videos[0].width,
height: videos[0].height,
- numFrames: videos.reduce((sum, v) => sum + (frameCounts?.get(v.id) ?? v.numFrames ?? 0), 0),
+ numFrames: videos.reduce((sum, v, i) => sum + (
+ (trimsApplied ? trimPlan[i]?.frames : null) ?? v.numFrames ?? 0
+ ), 0),
fps: videos[0].fps,
filename: outFilename,
thumbnail: thumb,
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index a2d9656049..5a013bf01c 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -116,7 +116,7 @@ vi.mock('../../lib/sseUtils.js', () => ({
PYTHON_NOISE_RE: /^\s*$/,
}));
-vi.mock('../../lib/ffmpeg.js', () => ({
+vi.mock('../../lib/ffmpeg.js', async () => ({
findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),
safeUnder: vi.fn((base, file) => (file ? join(base, file) : null)),
generateThumbnail: vi.fn(async () => 'thumb.jpg'),
@@ -124,13 +124,15 @@ vi.mock('../../lib/ffmpeg.js', () => ({
upscaleVideo2x: vi.fn(async () => ({ ok: true })),
extractEvaluationFrames: vi.fn(async () => []),
// Chained renders on a window-continuity runtime probe each chunk's length
- // and cut two clips from it (the echoed-context trim and the next hop's
- // conditioning window). 25 matches the numFrames the chain tests render, so
- // the prefix math below lands on a realistic value.
- H264_ENCODE_ARGS: ['-c:v', 'libx264'],
- AAC_ENCODE_ARGS: ['-c:a', 'aac'],
+ // and cut the next hop's conditioning window from it. 25 matches the
+ // numFrames the chain tests render, so the prefix math below lands on a
+ // realistic value.
probeFrameCount: vi.fn(async () => 25),
trimVideoFromFrame: vi.fn(async (_videoPath, outPath) => ({ ok: true, outPath })),
+ hasAudioStream: vi.fn(async () => false),
+ // 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,
}));
// hfChildEnv() carries the resolved token over the inherited child env; mocking here
@@ -168,6 +170,9 @@ vi.mock('fs/promises', () => ({
unlink: vi.fn(async () => {}),
writeFile: vi.fn(async () => {}),
copyFile: vi.fn(async () => {}),
+ // Unused by the code under test, but lib/ffmpeg.js imports it and the ffmpeg
+ // mock above pulls the real module in for buildTrimConcatArgs.
+ rename: vi.fn(async () => {}),
}));
// Fake EventEmitter-like process that completes immediately with exit code 0.
@@ -296,17 +301,19 @@ async function runChainAndCaptureArgs(chainParams, totalChunks) {
describe('generateChainedVideo — continuation strategy (context window vs last frame)', () => {
// numFrames=25 → extendLatentFrames(25) = 3 latents = 24 new pixel frames,
// and probeFrameCount is mocked at 25. So for each rendered chunk:
- // echoed context prefix = 25 − 24 = 1 frame (chunk 0 is never trimmed)
- // chunk 0's 22-frame window starts at 25 − 22 = 3
- // a TRIMMED chunk is 24 frames, so its window starts at 24 − 22 = 2
- // The 2-vs-3 difference is the point: the orchestrator probes each chunk
- // once and subtracts the trim, so it can't cut the window from a stale
- // pre-trim length (which would hand the next hop a short window).
+ // echoed context prefix = 25 − 24 = 1 frame (chunk 0 has none)
+ // the 22-frame conditioning window starts at 25 − 22 = 3
+ // The chunk files are never rewritten, so that index is measured against the
+ // full render on every hop: index 3 of a windowed chunk is frame 2 of its own
+ // new footage, i.e. the same frames the old pre-trim path cut at index 2 of a
+ // shortened file. What the floor at `contextPrefix` guarantees is that the
+ // window can never reach back into the echo the stitch is about to drop.
const CHUNK_FRAMES = 25;
const EXPECTED_EXTEND_LATENTS = 3;
const EXPECTED_PREFIX_START = 1;
- const WINDOW_START_UNTRIMMED = 3;
- const WINDOW_START_TRIMMED = 2;
+ const WINDOW_START = 3;
+ // 25 + (25−1) + (25−1) once the echoes come out of the timeline.
+ const STITCHED_FRAMES_3_CHUNKS = 73;
const flagValue = (args, flag) => (Array.isArray(args) && args.includes(flag)
? args[args.indexOf(flag) + 1] : null);
@@ -321,17 +328,21 @@ describe('generateChainedVideo — continuation strategy (context window vs last
const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const { trimVideoFromFrame, probeFrameCount } = await import('../../lib/ffmpeg.js');
const { spawn } = await import('child_process');
- const { readJSONFile } = await import('../../lib/fileUtils.js');
+ const { readJSONFile, atomicWrite } = await import('../../lib/fileUtils.js');
vi.mocked(spawnDetached).mockClear();
vi.mocked(trimVideoFromFrame).mockClear();
vi.mocked(probeFrameCount).mockClear();
vi.mocked(spawn).mockClear();
+ vi.mocked(atomicWrite).mockClear();
// extractLastFrame and stitchVideos both look their inputs up in history;
- // feed the chunk ids back as they start so the chain can advance.
+ // feed the chunk ids back as they start so the chain can advance. The
+ // geometry matters: stitchVideos reads the canonical width/height/fps for
+ // its filter graph off the first entry, and sums numFrames for the
+ // stitched record.
const innerJobIds = [];
vi.mocked(readJSONFile).mockImplementation(async () =>
- innerJobIds.map((id) => ({ id, filename: `${id}.mp4` })),
+ innerJobIds.map((id) => ({ id, filename: `${id}.mp4`, width: 512, height: 512, fps: 24, numFrames: CHUNK_FRAMES })),
);
videoGenEvents.on('started', (e) => innerJobIds.push(e.generationId));
@@ -367,11 +378,20 @@ describe('generateChainedVideo — continuation strategy (context window vs last
await new Promise((r) => setTimeout(r, 100));
videoGenEvents.removeAllListeners('started');
+ const spawns = vi.mocked(spawn).mock.calls;
return {
innerJobIds,
renders: vi.mocked(spawnDetached).mock.calls.map(([, args]) => args),
trims: vi.mocked(trimVideoFromFrame).mock.calls,
- spawns: vi.mocked(spawn).mock.calls,
+ spawns,
+ // The one ffmpeg run that assembles the timeline — either a concat
+ // demuxer invocation or the trim-bearing filter graph that replaces it.
+ concat: (spawns.find(([, args]) => Array.isArray(args)
+ && (args.includes('concat') || args.some((a) => typeof a === 'string' && a.includes('concat=n=')))) || [])[1] || null,
+ // The stitched history entry, read off the history write it triggers.
+ stitched: vi.mocked(atomicWrite).mock.calls
+ .flatMap(([, payload]) => (Array.isArray(payload) ? payload : []))
+ .find((entry) => entry?.chainedFrom) || null,
};
}
@@ -394,38 +414,100 @@ describe('generateChainedVideo — continuation strategy (context window vs last
expect(spawns.filter(([, args]) => Array.isArray(args) && args.includes('-sseof'))).toHaveLength(0);
});
- it('cuts the echoed context back off each windowed chunk before stitching', async () => {
+ it('cuts the echoed context out of the timeline in the stitch, not out of the chunk files', async () => {
// extend_from_video returns `source + extension`, so every hop after the
// first opens with a replay of its conditioning window. Left in, the
- // stitched clip repeats ~1s of footage at every seam.
- const { innerJobIds, trims } = await runChain({}, 3);
+ // stitched clip repeats ~1s of footage at every seam. Cutting it in the
+ // concat's own filter graph costs nothing on top of the timeline encode
+ // that a trimmed concat needs anyway, where pre-trimming each chunk file
+ // would add a whole x264 pass per hop AND grade the trimmed chunks
+ // differently from the untrimmed chunk 0.
+ const { innerJobIds, trims, concat, stitched } = await runChain({}, 3);
const chunkPath = (i) => join(MOCK_PATHS.videos, `${innerJobIds[i]}.mp4`);
- const trimFor = (src, dest) => trims.find(([from, to]) => from === src && to === dest);
- // Chunk 0 is never trimmed — nothing precedes it in the timeline.
- expect(trims.some(([, to]) => to === chunkPath(0))).toBe(false);
- // Chunks 1 and 2 are trimmed in place, dropping only the echoed prefix.
+ // No chunk file is rewritten — the archived per-chunk entries stay exactly
+ // what the model rendered.
+ expect(trims.some(([from, to]) => from === to)).toBe(false);
+ for (const i of [0, 1, 2]) {
+ expect(trims.some(([, to]) => to === chunkPath(i))).toBe(false);
+ }
+
+ // Instead the offsets ride in the concat graph: chunk 0 whole, chunks 1+
+ // starting after their echoed prefix.
+ const graph = concat[concat.indexOf('-filter_complex') + 1];
+ expect(graph).toContain('[0:v]');
+ expect(graph).not.toMatch(/\[0:v\][^;]*trim=start_frame/);
for (const i of [1, 2]) {
- const trim = trimFor(chunkPath(i), chunkPath(i));
- expect(trim).toBeTruthy();
- expect(trim[2]).toMatchObject({ startFrame: EXPECTED_PREFIX_START });
+ expect(graph).toMatch(new RegExp(`\\[${i}:v\\][^;]*trim=start_frame=${EXPECTED_PREFIX_START}`));
+ }
+ expect(graph).toContain('concat=n=3:v=1:a=0[outv]');
+ // 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);
+
+ // Each hop's conditioning window is still cut from the tail into tmpdir.
+ const windowStart = (i) => trims
+ .find(([from, to]) => from === chunkPath(i) && to === join(tmpdir(), `chaincontext-${innerJobIds[i]}.mp4`))?.[2]?.startFrame;
+ expect(windowStart(0)).toBe(WINDOW_START);
+ expect(windowStart(1)).toBe(WINDOW_START);
+ });
+
+ it('encodes the timeline exactly once for an N-chunk chain', async () => {
+ // The whole point: (N−1) chunk encodes + 1 timeline encode collapses to 1.
+ const { spawns, concat } = await runChain({}, 3);
+ const encodes = spawns.filter(([, args]) => Array.isArray(args) && args.includes('libx264'));
+ expect(encodes).toHaveLength(1);
+ expect(encodes[0][1]).toBe(concat);
+ // A trim-bearing concat can't stream-copy, and it can't use the demuxer
+ // either — the demuxer has no way to express a per-input offset.
+ expect(concat.join(' ')).not.toContain('-c copy');
+ expect(concat).not.toContain('-f');
+ });
+
+ it('falls back to a stream copy when the trimmed filter graph fails, rather than losing the chain', async () => {
+ // The pre-trim implementation degraded to a repeated seam when a chunk
+ // trim failed, because failing there would have discarded every chunk
+ // already rendered. Moving the cut into the concat has to keep that: the
+ // untrimmed chunks were never re-encoded, so they're still in codec
+ // lockstep and the demuxer can still assemble them.
+ const { spawn } = await import('child_process');
+ const failingProc = () => {
+ const listeners = {};
+ const proc = {
+ pid: 12345,
+ stdout: { on: vi.fn() },
+ stderr: { on: vi.fn() },
+ on(event, fn) { listeners[event] = fn; return proc; },
+ kill: vi.fn(),
+ };
+ setImmediate(() => listeners.close?.(1, null));
+ return proc;
+ };
+ vi.mocked(spawn).mockImplementation((_bin, args) => (
+ Array.isArray(args) && args.includes('-filter_complex') ? failingProc() : makeProc()
+ ));
+ try {
+ const { spawns, stitched } = await runChain({}, 3);
+ const concats = spawns.map(([, args]) => args).filter(Array.isArray);
+ expect(concats.some((args) => args.includes('-filter_complex'))).toBe(true);
+ // …and the salvage run, which is the plain demuxer stream copy.
+ const copy = concats.find((args) => args.includes('-f') && args.includes('copy'));
+ expect(copy).toBeTruthy();
+ // The echoes are still in the output, so the record must say so rather
+ // than reporting the trimmed length we asked for and never got.
+ expect(stitched?.numFrames).toBe(CHUNK_FRAMES * 3);
+ } finally {
+ vi.mocked(spawn).mockImplementation(() => makeProc());
}
- // And each hop's conditioning window is cut from the tail into tmpdir —
- // off the chunk's post-trim length, not the length it was probed at.
- const windowStart = (i) => trimFor(chunkPath(i), join(tmpdir(), `chaincontext-${innerJobIds[i]}.mp4`))?.[2]?.startFrame;
- expect(windowStart(0)).toBe(WINDOW_START_UNTRIMMED);
- expect(windowStart(1)).toBe(WINDOW_START_TRIMMED);
});
- it('re-encodes the concat once a chunk has been trimmed', async () => {
- // A trimmed chunk was re-encoded, so it no longer shares codec parameters
- // with its untrimmed siblings and the demuxer's `-c copy` can't be trusted.
- const { spawns } = await runChain({}, 2);
- const concat = spawns.find(([, args]) => Array.isArray(args) && args.includes('-f') && args.includes('concat'));
- expect(concat).toBeTruthy();
- expect(concat[1]).toContain('libx264');
- expect(concat[1].join(' ')).not.toContain('-c copy');
+ it('keeps the graph video-only when the chunks carry no audio stream', async () => {
+ // Referencing `[k:a]` against a silent input aborts the whole ffmpeg run,
+ // and AI renders are silent unless the model generated a soundtrack.
+ const { concat } = await runChain({}, 2);
+ expect(concat.join(' ')).not.toContain(':a]');
+ expect(concat).toContain('-an');
});
it('probes each chunk once rather than re-reading it after the trim', async () => {
@@ -444,17 +526,31 @@ describe('generateChainedVideo — continuation strategy (context window vs last
expect(cut[2]).toMatchObject({ startFrame: CHUNK_FRAMES - 8 });
});
+ it('never conditions the next hop on the echo the stitch is about to drop', async () => {
+ // A window bigger than the chunk's own new footage (121 requested vs 24
+ // rendered) clamps to the start of the file — which, now that the file
+ // still holds its echoed prefix, would hand the next hop a replay of the
+ // chunk BEFORE it. The window start floors at the prefix instead.
+ const { innerJobIds, trims } = await runChain({ contextFrames: 121 }, 3);
+ const windowStart = (i) => trims
+ .find(([, to]) => to === join(tmpdir(), `chaincontext-${innerJobIds[i]}.mp4`))?.[2]?.startFrame;
+ // Chunk 0 has no echo, so its whole render is fair game as a window.
+ expect(windowStart(0)).toBe(0);
+ expect(windowStart(1)).toBe(EXPECTED_PREFIX_START);
+ });
+
it('contextFrames: 0 opts back into last-frame chaining', async () => {
// 0 is a real value, distinct from "unset" — it's how a user gets the
// historical single-still hop back on a runtime that could do better.
- const { renders, trims, spawns } = await runChain({ contextFrames: 0 }, 2);
+ const { renders, trims, concat } = await runChain({ contextFrames: 0 }, 2);
expect(flagValue(renders[1], '--mode')).toBe('image');
expect(flagValue(renders[1], '--extend-from-video')).toBeNull();
- // Nothing is trimmed, so the concat keeps the stream-copy fast path.
+ // No offsets to apply, so the concat keeps the demuxer stream-copy fast
+ // path — the same one the hand-stitch from Media History takes.
expect(trims).toHaveLength(0);
- const concat = spawns.find(([, args]) => Array.isArray(args) && args.includes('concat'));
- expect(concat[1]).toContain('copy');
+ expect(concat).toContain('copy');
+ expect(concat).not.toContain('-filter_complex');
});
it('falls back to last-frame chaining on a runtime with no extend pipeline', async () => {
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index d6cb194dff..477a579fa1 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -3,10 +3,12 @@
*
* Lets users compose multiple already-generated video clips into a single
* output video with per-clip in/out trim and drag-drop ordering. Distinct
- * from videoGen/local.js#stitchVideos: that one is stream-copy concat (no
- * trim, requires identical codec/dims). This one re-encodes through a
- * filter_complex graph so trims, mixed-audio inputs, and dim mismatches
- * across LTX-2 model versions all work safely.
+ * from videoGen/local.js#stitchVideos: that one is a stream-copy concat by
+ * default (requires identical codec/dims), and only reaches a filter graph —
+ * via lib/ffmpeg.js#buildTrimConcatArgs — when a chained render hands it
+ * leading-frame cuts. This one always re-encodes through a filter_complex
+ * graph, with per-clip in AND out points, so trims, mixed-audio inputs, and
+ * dim mismatches across LTX-2 model versions all work safely.
*
* Projects persist to data/video-projects.json. Output entries land in the
* existing data/video-history.json with a `timelineProjectId` flag so