feat(render): support multi-input concatenated --render
Some checks failed
CI / lint-and-test (push) Successful in 13s
CI / lint-and-test (pull_request) Successful in 12s
Version bump / version-bump (pull_request) Failing after 6s

Render the kept segments of multiple inputs into one MP4 by normalizing
each branch (yuv420p video, stereo fltp 48 kHz audio) and joining them
with ffmpeg's concat filter in input order, matching the order used by
the generated .kdenlive project. A single input keeps the existing
single-`-i` graph and output unchanged.

- add MultiRenderPlan, build_multi_render_graph, build_multi_render_command
- extract shared _input_render_fragments for single/multi builders
- render_video now accepts one track or a sequence of tracks
- default multi-input render output is <first-stem>_concat.mp4
- drop the single-input --render guard; update README and --render help
This commit is contained in:
pedro-bento 2026-10-06 20:40:12 +01:00
parent 1b0d902285
commit 6e75312c97
3 changed files with 374 additions and 53 deletions

View file

@ -64,9 +64,9 @@ cadence recording.mp4 --preset balanced --captions
- `recording.srt` and `recording_llm_transcript.txt` — generated when `--captions` is used. - `recording.srt` and `recording_llm_transcript.txt` — generated when `--captions` is used.
Pass `--render` to have cadence encode the final `recording.mp4` itself (same Pass `--render` to have cadence encode the final `recording.mp4` itself (same
cut decisions, single input only) instead of opening Kdenlive; add cut decisions) instead of opening Kdenlive; with multiple inputs the kept
`--keep-project` to also write the `.kdenlive` project. Multi-file edits still segments are concatenated in sequence order into one MP4. Add `--keep-project`
use the `.kdenlive` project. to also write the `.kdenlive` project.
Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`. Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.

View file

@ -26,7 +26,7 @@ Features:
- Eliminates stuttered word repetitions without destroying intentional pauses. - Eliminates stuttered word repetitions without destroying intentional pauses.
- Frame-locked J-Cuts and L-Cuts to mask visible jump cuts without cumulative A/V drift. - Frame-locked J-Cuts and L-Cuts to mask visible jump cuts without cumulative A/V drift.
- Generates a native .kdenlive project file with synchronized audio/video cuts. - Generates a native .kdenlive project file with synchronized audio/video cuts.
- Optionally renders the final MP4 itself (`--render`) with the same cut decisions. - Regenerates a native .kdenlive or MP4 output from the same cut decisions (`--render`).
- Generates synced YouTube .srt captions and an LLM-ready transcript (prompt + timeline) for downstream summaries. - Generates synced YouTube .srt captions and an LLM-ready transcript (prompt + timeline) for downstream summaries.
- Built-in pacing presets (relaxed, balanced, punchy) to eliminate the need for shell wrappers. - Built-in pacing presets (relaxed, balanced, punchy) to eliminate the need for shell wrappers.
""" """
@ -49,7 +49,7 @@ import tempfile
import uuid import uuid
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
import zipfile import zipfile
from collections.abc import Callable from collections.abc import Callable, Sequence
from dataclasses import asdict, dataclass from dataclasses import asdict, dataclass
from pathlib import Path from pathlib import Path
from typing import Literal from typing import Literal
@ -790,6 +790,27 @@ class RenderPlan:
return self.total_frames / self.fps return self.total_frames / self.fps
@dataclass(frozen=True, slots=True)
class MultiRenderPlan:
"""A pure description of a multi-input concatenated ffmpeg filtergraph."""
filtergraph: str
video_label: str
audio_label: str
input_count: int
total_frames: int
fps_num: int
fps_den: int
@property
def fps(self) -> float:
return self.fps_num / self.fps_den
@property
def duration(self) -> float:
return self.total_frames / self.fps
def _balanced_sum(terms: list[str]) -> str: def _balanced_sum(terms: list[str]) -> str:
"""Fold ``terms`` into a balanced binary tree of ``+``. """Fold ``terms`` into a balanced binary tree of ``+``.
@ -865,21 +886,24 @@ def _keep_frame_ranges(
return video_ranges, audio_ranges return video_ranges, audio_ranges
def build_render_graph( def _input_render_fragments(
td: VideoTrackData, td: VideoTrackData,
jl_mode: Literal["j", "l", "off"] = "j", index: int,
jl_frames: int = 2, *,
) -> RenderPlan: video_label: str,
"""Build the ffmpeg filtergraph that reproduces the MLT cut timeline. audio_label: str,
use_system: bool,
normalize: bool,
jl_mode: Literal["j", "l", "off"],
jl_frames: int,
) -> tuple[list[str], int]:
"""Filter fragments that select one input's keep ranges.
Single input only: the graph selects the kept source frames, renumbers Returns ``(fragments, total_frames)``. When ``normalize`` is set, the video
their timestamps, and (when the source carries a second audio stream) is forced to ``yuv420p`` and the audio to stereo fltp at 48 kHz so several
mixes the Voice and System streams to stereo exactly like the MLT inputs can be joined with the ``concat`` filter; otherwise the source
Voice+System tracks. formats pass through untouched (the historical single-input behavior).
""" """
if not any(seg.action == "keep" for seg in td.timeline):
raise ValueError("cannot build a render graph without a keep segment")
video_ranges, audio_ranges = _keep_frame_ranges(td, jl_mode, jl_frames) video_ranges, audio_ranges = _keep_frame_ranges(td, jl_mode, jl_frames)
total_frames = sum(end - start + 1 for start, end in audio_ranges) total_frames = sum(end - start + 1 for start, end in audio_ranges)
@ -888,29 +912,72 @@ def build_render_graph(
voice = td.audio_track_idx voice = td.audio_track_idx
# Mirror the MLT "System" stream pick: the *other* of streams 0/1. # Mirror the MLT "System" stream pick: the *other* of streams 0/1.
system_stream = (1 if voice == 0 else 0) if td.audio_stream_count >= 2 else None system_stream = (
(1 if voice == 0 else 0) if use_system and td.audio_stream_count >= 2 else None
)
video_chain = f"[0:v:0]select='{video_expr}',setpts=N/FRAME_RATE/TB[vout]" video_fmt = ",format=yuv420p" if normalize else ""
if system_stream is None: if normalize:
# Single stream: pass the chosen voice track through untouched. audio_fmt = ",aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo"
chain = [
video_chain,
f"[0:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB[voice]",
]
audio_label = "[voice]"
else: else:
chain = [ audio_fmt = ""
video_chain, mix_fmt = audio_fmt or ",aformat=sample_fmts=fltp:channel_layouts=stereo"
f"[0:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB,"
"aformat=sample_fmts=fltp:channel_layouts=stereo[voice]", fragments = [
f"[0:a:{system_stream}]aselect='{audio_expr}',asetpts=N/SR/TB," f"[{index}:v:0]select='{video_expr}'{video_fmt},setpts=N/FRAME_RATE/TB{video_label}"
"aformat=sample_fmts=fltp:channel_layouts=stereo[system]", ]
"[voice][system]amix=inputs=2:duration=longest:normalize=0[aout]", if system_stream is None:
] # Single stream: pass the chosen voice track through (normalized if needed).
audio_label = "[aout]" fragments.append(
f"[{index}:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB{audio_fmt}{audio_label}"
)
else:
voice_label = f"[voice{index}]"
sys_label = f"[system{index}]"
fragments.append(
f"[{index}:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB{mix_fmt}{voice_label}"
)
fragments.append(
f"[{index}:a:{system_stream}]aselect='{audio_expr}',asetpts=N/SR/TB{mix_fmt}{sys_label}"
)
fragments.append(
f"{voice_label}{sys_label}amix=inputs=2:duration=longest:normalize=0{audio_label}"
)
return fragments, total_frames
def build_render_graph(
td: VideoTrackData,
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> RenderPlan:
"""Build the ffmpeg filtergraph that reproduces one MLT cut timeline.
The graph selects the kept source frames, renumbers their timestamps, and
(when the source carries a second audio stream) mixes the Voice and System
streams to stereo exactly like the MLT Voice+System tracks.
"""
if not any(seg.action == "keep" for seg in td.timeline):
raise ValueError("cannot build a render graph without a keep segment")
use_system = td.audio_stream_count >= 2
voice = td.audio_track_idx
system_stream = (1 if voice == 0 else 0) if use_system else None
audio_label = "[aout]" if use_system else "[voice]"
fragments, total_frames = _input_render_fragments(
td,
0,
video_label="[vout]",
audio_label=audio_label,
use_system=use_system,
normalize=False,
jl_mode=jl_mode,
jl_frames=jl_frames,
)
return RenderPlan( return RenderPlan(
filtergraph=";".join(chain), filtergraph=";".join(fragments),
video_label="[vout]", video_label="[vout]",
audio_label=audio_label, audio_label=audio_label,
voice_stream=voice, voice_stream=voice,
@ -921,6 +988,65 @@ def build_render_graph(
) )
def build_multi_render_graph(
track_data_list: Sequence[VideoTrackData],
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> MultiRenderPlan:
"""Build a filtergraph that concatenates every input's keep timeline.
Each input is selected and normalized in its own branch, then all branches
are joined with the ``concat`` filter in input order — matching the single
shared sequence the `.kdenlive` project produces for multiple inputs.
"""
if not track_data_list:
raise ValueError("cannot build a multi render graph without input tracks")
for td in track_data_list:
if not any(seg.action == "keep" for seg in td.timeline):
raise ValueError(
f"cannot build a render graph without a keep segment in {td.video.name}"
)
# Mirror `_generate_multi_kdenlive_project`: the System track is only used
# when *every* input carries a second audio stream.
use_system = all(td.audio_stream_count >= 2 for td in track_data_list)
base = track_data_list[0]
fragments: list[str] = []
concat_labels: list[str] = []
total_frames = 0
for index, td in enumerate(track_data_list):
video_label = f"[mv{index}]"
audio_label = f"[ma{index}]"
parts, frames = _input_render_fragments(
td,
index,
video_label=video_label,
audio_label=audio_label,
use_system=use_system,
normalize=True,
jl_mode=jl_mode,
jl_frames=jl_frames,
)
fragments.extend(parts)
concat_labels.append(f"{video_label}{audio_label}")
total_frames += frames
fragments.append(
f"{''.join(concat_labels)}concat=n={len(track_data_list)}:v=1:a=1[vout][aout]"
)
return MultiRenderPlan(
filtergraph=";".join(fragments),
video_label="[vout]",
audio_label="[aout]",
input_count=len(track_data_list),
total_frames=total_frames,
fps_num=base.fps_num,
fps_den=base.fps_den,
)
def build_render_command( def build_render_command(
plan: RenderPlan, plan: RenderPlan,
input_video: Path, input_video: Path,
@ -948,19 +1074,63 @@ def build_render_command(
] ]
def build_multi_render_command(
plan: MultiRenderPlan,
input_videos: Sequence[Path],
output: Path,
*,
filter_script: Path | None = None,
) -> list[str]:
"""Assemble the ffmpeg argv for a concatenated multi-input render."""
if filter_script is not None:
filter_args = ["-filter_complex_script", str(filter_script)]
else:
filter_args = ["-filter_complex", plan.filtergraph]
cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error"]
for video in input_videos:
cmd += ["-i", str(video)]
cmd += [
*filter_args,
"-map", plan.video_label,
"-map", plan.audio_label,
"-r", f"{plan.fps_num}/{plan.fps_den}",
"-fps_mode", "cfr",
*RENDER_VIDEO_ARGS,
*RENDER_AUDIO_ARGS,
*RENDER_MUX_ARGS,
str(output),
]
return cmd
def render_video( def render_video(
td: VideoTrackData, tracks: VideoTrackData | Sequence[VideoTrackData],
output: Path, output: Path,
*, *,
jl_mode: Literal["j", "l", "off"] = "j", jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2, jl_frames: int = 2,
) -> RenderPlan: ) -> RenderPlan | MultiRenderPlan:
"""Render ``td``'s keep timeline to ``output`` as an MP4 (single input).""" """Render one or more inputs' keep timelines to ``output`` as an MP4.
plan = build_render_graph(td, jl_mode=jl_mode, jl_frames=jl_frames)
A single track uses the historical single-``-i`` graph; multiple tracks are
normalized and concatenated in input order into one MP4.
"""
track_data_list = [tracks] if isinstance(tracks, VideoTrackData) else list(tracks)
if not track_data_list:
raise ValueError("cannot render without input tracks")
multi = len(track_data_list) > 1
if multi:
plan: RenderPlan | MultiRenderPlan = build_multi_render_graph(
track_data_list, jl_mode=jl_mode, jl_frames=jl_frames
)
else:
plan = build_render_graph(track_data_list[0], jl_mode=jl_mode, jl_frames=jl_frames)
output.parent.mkdir(parents=True, exist_ok=True) output.parent.mkdir(parents=True, exist_ok=True)
logger.info( logger.info(
f"[*] Rendering final video: {plan.total_frames} frames " f"[*] Rendering final video ({plan.total_frames} frames, "
f"({plan.duration:.2f}s) @ {plan.fps_num}/{plan.fps_den} fps..." f"{plan.duration:.2f}s) @ {plan.fps_num}/{plan.fps_den} fps..."
) )
filter_script: Path | None = None filter_script: Path | None = None
@ -971,7 +1141,17 @@ def render_video(
filter_script.write_text(plan.filtergraph, encoding="utf-8") filter_script.write_text(plan.filtergraph, encoding="utf-8")
try: try:
cmd = build_render_command(plan, td.video, output, filter_script=filter_script) if multi:
cmd = build_multi_render_command(
plan,
[td.video for td in track_data_list],
output,
filter_script=filter_script,
)
else:
cmd = build_render_command(
plan, track_data_list[0].video, output, filter_script=filter_script
)
run_ff(cmd, "video render") run_ff(cmd, "video render")
finally: finally:
if filter_script is not None: if filter_script is not None:
@ -1773,7 +1953,9 @@ def resolve_output_path(
resolved = output.resolve() resolved = output.resolve()
return resolved.with_suffix(".mp4") if render else resolved return resolved.with_suffix(".mp4") if render else resolved
if render: if render:
return input_videos[0].with_suffix(".mp4") if len(input_videos) == 1:
return input_videos[0].with_suffix(".mp4")
return input_videos[0].with_name(f"{input_videos[0].stem}_concat.mp4")
if len(input_videos) == 1: if len(input_videos) == 1:
return input_videos[0].with_suffix(".kdenlive") return input_videos[0].with_suffix(".kdenlive")
return input_videos[0].with_name(f"{input_videos[0].stem}_concat.kdenlive") return input_videos[0].with_name(f"{input_videos[0].stem}_concat.kdenlive")
@ -1837,8 +2019,8 @@ def parse_args() -> argparse.Namespace:
action="store_true", action="store_true",
help=( help=(
"Render the final MP4 directly with ffmpeg using the same cut " "Render the final MP4 directly with ffmpeg using the same cut "
"decisions (single input only); skips the .kdenlive export unless " "decisions; multiple inputs are concatenated in sequence order. "
"--keep-project is also given." "Skips the .kdenlive export unless --keep-project is also given."
), ),
) )
p.add_argument( p.add_argument(
@ -1940,12 +2122,6 @@ def main() -> None:
if not v.exists() or not v.is_file(): if not v.exists() or not v.is_file():
sys.exit(f"[!] Input file not found or invalid: {v}") sys.exit(f"[!] Input file not found or invalid: {v}")
if args.render and len(input_videos) > 1:
sys.exit(
"[!] --render currently supports a single input file. "
"For multi-file edits, omit --render and use the generated .kdenlive project."
)
output = resolve_output_path(input_videos, args.output, render=args.render) output = resolve_output_path(input_videos, args.output, render=args.render)
single_fillers = set(HESITATION_FILLERS) single_fillers = set(HESITATION_FILLERS)
@ -2062,7 +2238,7 @@ def main() -> None:
master: dict | None = None master: dict | None = None
if args.render: if args.render:
render_video( render_video(
track_data_list[0], track_data_list,
output=output, output=output,
jl_mode=args.jl_mode, jl_mode=args.jl_mode,
jl_frames=args.jl_frames, jl_frames=args.jl_frames,

View file

@ -8,6 +8,7 @@ import hashlib
import json import json
import shutil import shutil
import subprocess import subprocess
from pathlib import Path
import pytest import pytest
@ -173,6 +174,71 @@ def test_render_graph_requires_a_keep_segment(make_track):
cadence.build_render_graph(td) cadence.build_render_graph(td)
def test_multi_render_graph_concatenates_inputs(make_track):
first = make_track(
name="a.mp4",
duration=2.0,
timeline=[
Segment(0.0, 1.0, "keep"),
Segment(1.0, 1.5, "drop", reason="silence"),
Segment(1.5, 2.0, "keep"),
],
)
second = make_track(
name="b.mp4",
duration=1.0,
timeline=[Segment(0.0, 1.0, "keep")],
)
plan = cadence.build_multi_render_graph([first, second], jl_mode="off", jl_frames=0)
assert plan.input_count == 2
assert plan.total_frames == 75 # 45 + 30 frames kept
assert plan.duration == pytest.approx(2.5)
assert plan.video_label == "[vout]"
assert plan.audio_label == "[aout]"
assert "[0:v:0]" in plan.filtergraph
assert "[1:v:0]" in plan.filtergraph
assert "concat=n=2:v=1:a=1[vout][aout]" in plan.filtergraph
# Inputs are normalized so concat can join them.
assert plan.filtergraph.count("format=yuv420p") == 2
assert "sample_rates=48000" in plan.filtergraph
def test_multi_render_graph_system_audio_requires_all_inputs(make_track):
stereo = make_track(
name="a.mp4",
duration=1.0,
audio_stream_count=2,
timeline=[Segment(0.0, 1.0, "keep")],
)
mono = make_track(
name="b.mp4",
duration=1.0,
audio_stream_count=1,
timeline=[Segment(0.0, 1.0, "keep")],
)
mixed = cadence.build_multi_render_graph([stereo, mono], jl_mode="off", jl_frames=0)
assert "amix" not in mixed.filtergraph
both = cadence.build_multi_render_graph([stereo, stereo], jl_mode="off", jl_frames=0)
assert "amix=inputs=2:duration=longest:normalize=0" in both.filtergraph
assert "[0:a:1]" in both.filtergraph
assert "[1:a:1]" in both.filtergraph
def test_multi_render_graph_requires_a_keep_segment(make_track):
empty = make_track(
duration=1.0,
timeline=[Segment(0.0, 1.0, "drop", reason="silence")],
)
with pytest.raises(ValueError):
cadence.build_multi_render_graph([empty])
with pytest.raises(ValueError):
cadence.build_multi_render_graph([])
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# command assembly # command assembly
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@ -213,6 +279,21 @@ def test_build_render_command_filter_script(make_track, tmp_path):
assert "-filter_complex" not in cmd assert "-filter_complex" not in cmd
def test_build_multi_render_command_has_one_input_per_track(make_track, tmp_path):
first = make_track(name="a.mp4", duration=1.0, timeline=[Segment(0.0, 1.0, "keep")])
second = make_track(name="b.mp4", duration=1.0, timeline=[Segment(0.0, 1.0, "keep")])
plan = cadence.build_multi_render_graph([first, second], jl_mode="off", jl_frames=0)
out = tmp_path / "edited.mp4"
cmd = cadence.build_multi_render_command(plan, [first.video, second.video], out)
assert cmd.count("-i") == 2
assert str(first.video) in cmd
assert str(second.video) in cmd
assert cmd[cmd.index("-map") + 1] == "[vout]"
assert cmd[-1] == str(out)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# parse_args / output resolution # parse_args / output resolution
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@ -262,6 +343,10 @@ def test_resolve_output_path_multi_input_concat(tmp_path):
cadence.resolve_output_path([first, second], None, render=False) cadence.resolve_output_path([first, second], None, render=False)
== tmp_path / "a_concat.kdenlive" == tmp_path / "a_concat.kdenlive"
) )
assert (
cadence.resolve_output_path([first, second], None, render=True)
== tmp_path / "a_concat.mp4"
)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@ -344,3 +429,63 @@ def test_render_video_end_to_end(tmp_path):
assert len(streams) == 1 assert len(streams) == 1
assert streams[0]["codec_name"] == "aac" assert streams[0]["codec_name"] == "aac"
assert streams[0]["channels"] == 2 assert streams[0]["channels"] == 2
@pytest.mark.skipif(not HAVE_FFMPEG, reason="ffmpeg/ffprobe not available")
def test_render_video_multi_end_to_end(tmp_path):
def make_source(name: str, seconds: int) -> Path:
src = tmp_path / name
subprocess.run(
[
"ffmpeg", "-y", "-loglevel", "error",
"-f", "lavfi", "-i", f"testsrc=duration={seconds}:size=320x240:rate=30",
"-f", "lavfi",
"-i", f"sine=frequency=440:sample_rate=48000:duration={seconds}",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "160k",
"-shortest", str(src),
],
check=True,
)
return src
first = make_source("first.mp4", 2)
second = make_source("second.mp4", 2)
def track(src: Path) -> cadence.VideoTrackData:
return cadence.VideoTrackData(
video=src,
duration=2.0,
fps_num=30,
fps_den=1,
width=320,
height=240,
audio_track_idx=0,
audio_stream_count=1,
words=[],
timeline=[
Segment(0.0, 1.0, "keep"),
Segment(1.0, 1.5, "drop", reason="silence"),
Segment(1.5, 2.0, "keep"),
],
)
out = tmp_path / "edited.mp4"
plan = cadence.render_video([track(first), track(second)], out, jl_mode="off", jl_frames=0)
assert plan.total_frames == 90 # (30 + 15) frames kept per input
assert out.exists()
assert cadence.probe_duration(out) == pytest.approx(3.0, abs=0.2)
raw = cadence.check_ff_output(
[
"ffprobe", "-v", "error", "-select_streams", "a",
"-show_entries", "stream=codec_name,channels",
"-of", "json", str(out),
],
"probe rendered audio",
)
streams = json.loads(raw)["streams"]
assert len(streams) == 1
assert streams[0]["codec_name"] == "aac"
assert streams[0]["channels"] == 2