diff --git a/README.md b/README.md index b9cb4eb..0bdfa08 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,11 @@ cadence recording.mp4 --preset balanced --captions - `recording.kdenlive` — the edited project. - `recording.srt` and `recording_llm_transcript.txt` — generated when `--captions` is used. +Pass `--render` to have cadence encode the final `recording.mp4` itself (same +cut decisions, single input only) instead of opening Kdenlive; add +`--keep-project` to also write the `.kdenlive` project. Multi-file edits still +use the `.kdenlive` project. + Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`. ## Development diff --git a/cadence.py b/cadence.py index 2e36d39..e51ad42 100755 --- a/cadence.py +++ b/cadence.py @@ -26,6 +26,7 @@ Features: - 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. - Generates a native .kdenlive project file with synchronized audio/video cuts. +- Optionally renders the final MP4 itself (`--render`) with the same cut decisions. - 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. """ @@ -53,7 +54,7 @@ from typing import Literal logger = logging.getLogger("cadence") -__version__ = "0.1.1" +__version__ = "0.2.0" # Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc. HESITATION_REGEX = re.compile( @@ -729,6 +730,222 @@ def compute_jl_cut_shifts( return shifts +# --------------------------------------------------------------------------- +# Render (ffmpeg) — produce the final MP4 from the same cut decisions. +# --------------------------------------------------------------------------- + +# Above this many characters the filtergraph is handed to ffmpeg through a +# script file (`-filter_complex_script`) instead of the command line. +FILTERGRAPH_SCRIPT_THRESHOLD = 4000 + +# Exact Kdenlive export settings the render must reproduce. +RENDER_VIDEO_ARGS: tuple[str, ...] = ( + "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-g", "15", "-pix_fmt", "yuv420p", +) +RENDER_AUDIO_ARGS: tuple[str, ...] = ("-c:a", "aac", "-b:a", "160k", "-ac", "2") +RENDER_MUX_ARGS: tuple[str, ...] = ("-movflags", "+faststart", "-f", "mp4", "-threads", "0") + + +@dataclass(frozen=True, slots=True) +class RenderPlan: + """A pure description of the ffmpeg filtergraph for one keep timeline.""" + + filtergraph: str + video_label: str + audio_label: str + voice_stream: int + system_stream: int | None + 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 build_video_select_expression(ranges: list[tuple[int, int]]) -> str: + """Inclusive source-frame ranges -> ffmpeg ``select`` expression. + + Uses the decoder frame counter ``n`` so cuts land exactly on frame + boundaries regardless of floating-point timestamps. + """ + terms = [f"between(n,{start},{end})" for start, end in ranges] + return "+".join(terms) if terms else "0" + + +def build_audio_select_expression(ranges: list[tuple[int, int]], fps: float) -> str: + """Inclusive source-frame ranges -> ffmpeg ``aselect`` expression. + + Audio has no frame counter, so boundaries become half-open time intervals + (a frame's samples span ``[start/fps, (end+1)/fps)``), keeping every audio + segment aligned to a video frame boundary without cumulative drift. + """ + terms = [] + for start, end in ranges: + t0 = start / fps + t1 = (end + 1) / fps + terms.append(f"gte(t,{t0:.9f})*lt(t,{t1:.9f})") + return "+".join(terms) if terms else "0" + + +def _keep_frame_ranges( + td: VideoTrackData, jl_mode: Literal["j", "l", "off"], jl_frames: int +) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]: + """(video, audio) inclusive source-frame ranges for every keep segment. + + Mirrors ``_generate_multi_kdenlive_project``: each audio segment spans + ``seg_dur_frames`` frames while the video segment is offset by the incoming + ``shifts[k-1]`` and outgoing ``shifts[k]`` J/L shift. The two totals stay + identical because the per-boundary shifts telescope. + """ + fps = td.fps + keep_segments = [s for s in td.timeline if s.action == "keep"] + shifts = compute_jl_cut_shifts(keep_segments, fps, jl_mode=jl_mode, jl_frames=jl_frames) + + video_ranges: list[tuple[int, int]] = [] + audio_ranges: list[tuple[int, int]] = [] + for k, seg in enumerate(keep_segments): + in_frame = int(round(seg.start * fps)) + out_frame_target = int(round(seg.end * fps)) + seg_dur_frames = max(1, out_frame_target - in_frame) + a_out_frame = in_frame + seg_dur_frames - 1 + + shift_prev = shifts[k - 1] if k > 0 else 0 + shift_cur = shifts[k] + video_ranges.append((in_frame + shift_prev, a_out_frame + shift_cur)) + audio_ranges.append((in_frame, a_out_frame)) + return video_ranges, audio_ranges + + +def build_render_graph( + td: VideoTrackData, + jl_mode: Literal["j", "l", "off"] = "j", + jl_frames: int = 2, +) -> RenderPlan: + """Build the ffmpeg filtergraph that reproduces the MLT cut timeline. + + Single input only: 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") + + video_ranges, audio_ranges = _keep_frame_ranges(td, jl_mode, jl_frames) + total_frames = sum(end - start + 1 for start, end in audio_ranges) + + video_expr = build_video_select_expression(video_ranges) + audio_expr = build_audio_select_expression(audio_ranges, td.fps) + + voice = td.audio_track_idx + # 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 + + video_chain = f"[0:v:0]select='{video_expr}',setpts=N/FRAME_RATE/TB[vout]" + if system_stream is None: + # Single stream: pass the chosen voice track through untouched. + chain = [ + video_chain, + f"[0:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB[voice]", + ] + audio_label = "[voice]" + else: + chain = [ + video_chain, + f"[0:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB," + "aformat=sample_fmts=fltp:channel_layouts=stereo[voice]", + f"[0:a:{system_stream}]aselect='{audio_expr}',asetpts=N/SR/TB," + "aformat=sample_fmts=fltp:channel_layouts=stereo[system]", + "[voice][system]amix=inputs=2:duration=longest:normalize=0[aout]", + ] + audio_label = "[aout]" + + return RenderPlan( + filtergraph=";".join(chain), + video_label="[vout]", + audio_label=audio_label, + voice_stream=voice, + system_stream=system_stream, + total_frames=total_frames, + fps_num=td.fps_num, + fps_den=td.fps_den, + ) + + +def build_render_command( + plan: RenderPlan, + input_video: Path, + output: Path, + *, + filter_script: Path | None = None, +) -> list[str]: + """Assemble the ffmpeg argv. ``filter_script`` selects the script variant.""" + if filter_script is not None: + filter_args = ["-filter_complex_script", str(filter_script)] + else: + filter_args = ["-filter_complex", plan.filtergraph] + return [ + "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", + "-i", str(input_video), + *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), + ] + + +def render_video( + td: VideoTrackData, + output: Path, + *, + jl_mode: Literal["j", "l", "off"] = "j", + jl_frames: int = 2, +) -> RenderPlan: + """Render ``td``'s keep timeline to ``output`` as an MP4 (single input).""" + plan = build_render_graph(td, jl_mode=jl_mode, jl_frames=jl_frames) + output.parent.mkdir(parents=True, exist_ok=True) + logger.info( + f"[*] Rendering final video: {plan.total_frames} frames " + f"({plan.duration:.2f}s) @ {plan.fps_num}/{plan.fps_den} fps..." + ) + + filter_script: Path | None = None + if len(plan.filtergraph) > FILTERGRAPH_SCRIPT_THRESHOLD: + fd, script_name = tempfile.mkstemp(prefix="cadence_render_", suffix=".ffgraph") + os.close(fd) + filter_script = Path(script_name) + filter_script.write_text(plan.filtergraph, encoding="utf-8") + + try: + cmd = build_render_command(plan, td.video, output, filter_script=filter_script) + run_ff(cmd, "video render") + finally: + if filter_script is not None: + filter_script.unlink(missing_ok=True) + + logger.info(f"[OK] Rendered video saved -> {output.name}") + return plan + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as fh: + for chunk in iter(lambda: fh.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + def _generate_multi_kdenlive_project( track_data_list: list[VideoTrackData], output: Path, @@ -1327,6 +1544,7 @@ def _build_handoff_manifest( *, jl_mode: Literal["j", "l", "off"], jl_frames: int, + master: dict | None = None, ) -> dict: """``clipwright.handoff/1`` manifest describing the edited timeline.""" base = track_data_list[0] @@ -1385,7 +1603,7 @@ def _build_handoff_manifest( "duration": _edited_duration(track_data_list), "jl_mode": jl_mode, "jl_frames": jl_frames, - "master": None, + "master": master, }, "sources": sources, "edit": edit, @@ -1402,6 +1620,7 @@ def generate_handoff( jl_mode: Literal["j", "l", "off"] = "j", jl_frames: int = 2, language: str = "en", + master: dict | None = None, ) -> None: """Write ``.transcript.json`` and ``.handoff.json``. @@ -1425,6 +1644,7 @@ def generate_handoff( transcript_name, jl_mode=jl_mode, jl_frames=jl_frames, + master=master, ) handoff_name = f"{output_path.stem}.handoff.json" handoff_path = output_path.with_name(handoff_name) @@ -1464,6 +1684,24 @@ def _non_negative_float(value: str) -> float: return fvalue +def resolve_output_path( + input_videos: list[Path], output: Path | None, *, render: bool +) -> Path: + """Resolve the primary output path. + + ``--render`` targets an ``.mp4`` (default: first input stem); without it the + historical ``.kdenlive`` default is preserved. + """ + if output is not None: + resolved = output.resolve() + return resolved.with_suffix(".mp4") if render else resolved + if render: + return input_videos[0].with_suffix(".mp4") + if len(input_videos) == 1: + return input_videos[0].with_suffix(".kdenlive") + return input_videos[0].with_name(f"{input_videos[0].stem}_concat.kdenlive") + + def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser( description="cadence: High-retention audio-visual auto-editor for raw recordings." @@ -1489,7 +1727,10 @@ def parse_args() -> argparse.Namespace: "-o", "--output", type=Path, default=None, - help="Target output path (defaults to first video path with .kdenlive suffix).", + help=( + "Target output path (defaults to first video path with .kdenlive, " + "or .mp4 when --render is used)." + ), ) p.add_argument( "--audio-track", @@ -1514,6 +1755,20 @@ def parse_args() -> argparse.Namespace: action="store_true", help="Generate synced .srt subtitles and LLM packaging transcript file.", ) + p.add_argument( + "--render", + action="store_true", + help=( + "Render the final MP4 directly with ffmpeg using the same cut " + "decisions (single input only); skips the .kdenlive export unless " + "--keep-project is also given." + ), + ) + p.add_argument( + "--keep-project", + action="store_true", + help="With --render, also write the .kdenlive project file.", + ) p.add_argument( "--handoff", action="store_true", @@ -1608,13 +1863,13 @@ def main() -> None: if not v.exists() or not v.is_file(): sys.exit(f"[!] Input file not found or invalid: {v}") - if args.output: - output = args.output.resolve() - else: - if len(input_videos) == 1: - output = input_videos[0].with_suffix(".kdenlive") - else: - output = input_videos[0].with_name(f"{input_videos[0].stem}_concat.kdenlive") + 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) single_fillers = set(HESITATION_FILLERS) if args.extra_fillers: @@ -1725,12 +1980,23 @@ def main() -> None: output.parent.mkdir(parents=True, exist_ok=True) - _generate_multi_kdenlive_project( - track_data_list, - output=output, - jl_mode=args.jl_mode, - jl_frames=args.jl_frames, - ) + master: dict | None = None + if args.render: + render_video( + track_data_list[0], + output=output, + jl_mode=args.jl_mode, + jl_frames=args.jl_frames, + ) + master = {"path": str(output), "sha256": sha256_file(output)} + + if args.keep_project or not args.render: + _generate_multi_kdenlive_project( + track_data_list, + output=output, + jl_mode=args.jl_mode, + jl_frames=args.jl_frames, + ) if args.captions: generate_combined_transcripts(track_data_list, output) @@ -1742,9 +2008,15 @@ def main() -> None: jl_mode=args.jl_mode, jl_frames=args.jl_frames, language=args.language, + master=master, ) - logger.info(f"\n[OK] Processing complete. Master project saved to:\n {output.with_suffix('.kdenlive')}") + if args.render: + logger.info(f"\n[OK] Processing complete. Master video saved to:\n {output}") + else: + logger.info( + f"\n[OK] Processing complete. Master project saved to:\n {output.with_suffix('.kdenlive')}" + ) if __name__ == "__main__": diff --git a/tests/test_render.py b/tests/test_render.py new file mode 100644 index 0000000..8268d6d --- /dev/null +++ b/tests/test_render.py @@ -0,0 +1,309 @@ +"""Tests for the ``--render`` stage (ffmpeg graph builder + CLI). + +Pure builder/parse tests run everywhere; the integration test is skipped when +ffmpeg/ffprobe are not on ``PATH``. +""" + +import hashlib +import json +import shutil +import subprocess + +import pytest + +import cadence +from cadence import Segment, Word + +HAVE_FFMPEG = ( + shutil.which("ffmpeg") is not None and shutil.which("ffprobe") is not None +) + + +# --------------------------------------------------------------------------- +# expression builders +# --------------------------------------------------------------------------- + +def test_video_select_expression_ranges(): + assert cadence.build_video_select_expression([]) == "0" + assert ( + cadence.build_video_select_expression([(0, 29), (45, 59)]) + == "between(n,0,29)+between(n,45,59)" + ) + + +def test_audio_select_expression_is_half_open(): + # Frame 0..29 at 30fps is the half-open interval [0s, 1s). + expr = cadence.build_audio_select_expression([(0, 29)], 30.0) + assert expr == "gte(t,0.000000000)*lt(t,1.000000000)" + assert cadence.build_audio_select_expression([], 30.0) == "0" + + +# --------------------------------------------------------------------------- +# graph builder +# --------------------------------------------------------------------------- + +def test_render_graph_single_stream_matches_keep_segments(make_track): + td = make_track( + duration=2.0, + audio_stream_count=1, + audio_track_idx=0, + timeline=[ + Segment(0.0, 1.0, "keep"), + Segment(1.0, 1.5, "drop", reason="silence"), + Segment(1.5, 2.0, "keep"), + ], + ) + + plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0) + + assert plan.voice_stream == 0 + assert plan.system_stream is None + assert plan.audio_label == "[voice]" + assert plan.total_frames == 45 # 30 + 15 frames kept + assert plan.duration == pytest.approx(1.5) + assert "select='between(n,0,29)+between(n,45,59)'" in plan.filtergraph + assert "setpts=N/FRAME_RATE/TB" in plan.filtergraph + assert "asetpts=N/SR/TB" in plan.filtergraph + assert "amix" not in plan.filtergraph + + +def test_render_graph_system_audio_mixes_to_stereo(make_track): + td = make_track( + duration=2.0, + audio_stream_count=2, + audio_track_idx=0, + timeline=[Segment(0.0, 2.0, "keep")], + ) + + plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0) + + assert plan.voice_stream == 0 + assert plan.system_stream == 1 + assert plan.audio_label == "[aout]" + assert "[0:a:0]" in plan.filtergraph + assert "[0:a:1]" in plan.filtergraph + assert "channel_layouts=stereo" in plan.filtergraph + assert "amix=inputs=2:duration=longest:normalize=0" in plan.filtergraph + + +def test_render_graph_system_stream_swaps_with_voice(make_track): + td = make_track( + duration=2.0, + audio_stream_count=2, + audio_track_idx=1, + timeline=[Segment(0.0, 2.0, "keep")], + ) + + plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0) + + assert plan.voice_stream == 1 + assert plan.system_stream == 0 + + +def test_render_graph_honors_jl_shifts(make_track): + td = make_track( + duration=6.0, + fps_num=30, + fps_den=1, + timeline=[ + Segment(0.0, 1.0, "keep"), + Segment(1.0, 3.0, "drop", reason="silence"), + Segment(3.0, 4.0, "keep"), + Segment(4.0, 5.0, "drop", reason="silence"), + Segment(5.0, 6.0, "keep"), + ], + ) + + plan = cadence.build_render_graph(td, jl_mode="j", jl_frames=2) + + # Each segment's video in-point inherits the *incoming* shift; the last + # segment's outgoing shift is always 0. + assert ( + "select='between(n,0,31)+between(n,92,121)+between(n,152,179)'" + in plan.filtergraph + ) + # J/L only redistributes frames, so total length is unchanged. + assert plan.total_frames == 90 + assert plan.duration == pytest.approx(3.0) + + +def test_render_graph_requires_a_keep_segment(make_track): + td = make_track( + duration=2.0, + timeline=[Segment(0.0, 2.0, "drop", reason="silence")], + ) + with pytest.raises(ValueError): + cadence.build_render_graph(td) + + +# --------------------------------------------------------------------------- +# command assembly +# --------------------------------------------------------------------------- + +def test_build_render_command_uses_exact_export_settings(make_track, tmp_path): + td = make_track( + duration=1.0, + timeline=[Segment(0.0, 1.0, "keep")], + ) + plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0) + out = tmp_path / "edited.mp4" + + cmd = cadence.build_render_command(plan, td.video, out) + + assert cmd[0] == "ffmpeg" + assert "-filter_complex" in cmd + assert "-filter_complex_script" not in cmd + assert cmd[cmd.index("-map") + 1] == "[vout]" + assert cmd[cmd.index("-r") + 1] == "30/1" + for flag in ("-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-g", "15"): + assert flag in cmd + for flag in ("-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-ac", "2"): + assert flag in cmd + for flag in ("-movflags", "+faststart", "-f", "mp4", "-threads", "0"): + assert flag in cmd + assert cmd[-1] == str(out) + + +def test_build_render_command_filter_script(make_track, tmp_path): + td = make_track(duration=1.0, timeline=[Segment(0.0, 1.0, "keep")]) + plan = cadence.build_render_graph(td) + script = tmp_path / "graph.txt" + + cmd = cadence.build_render_command(plan, td.video, tmp_path / "o.mp4", filter_script=script) + + assert "-filter_complex_script" in cmd + assert str(script) in cmd + assert "-filter_complex" not in cmd + + +# --------------------------------------------------------------------------- +# parse_args / output resolution +# --------------------------------------------------------------------------- + +def _parse(monkeypatch, argv): + monkeypatch.setattr("sys.argv", ["cadence", *argv]) + return cadence.parse_args() + + +def test_parse_args_render_flags(monkeypatch): + args = _parse(monkeypatch, ["video.mp4"]) + assert args.render is False + assert args.keep_project is False + + args = _parse(monkeypatch, ["video.mp4", "--render", "--keep-project"]) + assert args.render is True + assert args.keep_project is True + + +def test_resolve_output_path_render_default_is_mp4(tmp_path): + video = tmp_path / "recording.mkv" + assert ( + cadence.resolve_output_path([video], None, render=True) + == tmp_path / "recording.mp4" + ) + # Unchanged historical default without --render. + assert ( + cadence.resolve_output_path([video], None, render=False) + == tmp_path / "recording.kdenlive" + ) + + +def test_resolve_output_path_render_forces_mp4(tmp_path): + video = tmp_path / "recording.mkv" + explicit = tmp_path / "custom.kdenlive" + assert ( + cadence.resolve_output_path([video], explicit, render=True) + == tmp_path / "custom.mp4" + ) + assert cadence.resolve_output_path([video], explicit, render=False) == explicit + + +def test_resolve_output_path_multi_input_concat(tmp_path): + first = tmp_path / "a.mp4" + second = tmp_path / "b.mp4" + assert ( + cadence.resolve_output_path([first, second], None, render=False) + == tmp_path / "a_concat.kdenlive" + ) + + +# --------------------------------------------------------------------------- +# handoff integration +# --------------------------------------------------------------------------- + +def test_sha256_file(tmp_path): + path = tmp_path / "blob.bin" + path.write_bytes(b"cadence") + assert cadence.sha256_file(path) == hashlib.sha256(b"cadence").hexdigest() + + +def test_generate_handoff_populates_master(make_track, tmp_path): + td = make_track( + duration=1.0, + timeline=[Segment(0.0, 1.0, "keep")], + words=[Word("Hi.", 0.1, 0.3)], + ) + out = tmp_path / "recording.mp4" + master = {"path": str(out), "sha256": "deadbeef"} + + cadence.generate_handoff([td], out, master=master) + + handoff = json.loads((tmp_path / "recording.handoff.json").read_text(encoding="utf-8")) + assert handoff["edited"]["master"] == master + + +# --------------------------------------------------------------------------- +# integration (ffmpeg-gated) +# --------------------------------------------------------------------------- + +@pytest.mark.skipif(not HAVE_FFMPEG, reason="ffmpeg/ffprobe not available") +def test_render_video_end_to_end(tmp_path): + src = tmp_path / "src.mp4" + subprocess.run( + [ + "ffmpeg", "-y", "-loglevel", "error", + "-f", "lavfi", "-i", "testsrc=duration=2:size=320x240:rate=30", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2", + "-c:v", "libx264", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-b:a", "160k", + "-shortest", str(src), + ], + check=True, + ) + + td = 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" + + cadence.render_video(td, out, jl_mode="off", jl_frames=0) + + assert out.exists() + assert out.stat().st_size > 0 + assert cadence.probe_duration(out) == pytest.approx(1.5, abs=0.15) + + 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