| |
| """Concatenate MP4 chunks by decoding and re-encoding with PyAV.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from fractions import Fraction |
| from pathlib import Path |
|
|
| import av |
|
|
|
|
| def concat_videos(inputs: list[Path], output_path: Path, fps: float) -> int: |
| if not inputs: |
| raise ValueError("No input chunks to concatenate") |
|
|
| first = av.open(str(inputs[0])) |
| try: |
| first_stream = first.streams.video[0] |
| width = first_stream.width |
| height = first_stream.height |
| finally: |
| first.close() |
|
|
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| container = av.open(str(output_path), "w") |
| success = False |
| frame_count = 0 |
| try: |
| output_fps = round(fps) |
| time_base = Fraction(1, output_fps) |
| stream = container.add_stream("libx264", rate=output_fps, options={"crf": "19", "preset": "veryfast"}) |
| stream.width = width |
| stream.height = height |
| stream.pix_fmt = "yuv420p" |
| stream.time_base = time_base |
| stream.codec_context.thread_count = 0 |
| stream.codec_context.thread_type = "FRAME" |
|
|
| for input_path in inputs: |
| chunk = av.open(str(input_path)) |
| try: |
| video_stream = chunk.streams.video[0] |
| if video_stream.width != width or video_stream.height != height: |
| raise ValueError( |
| f"Chunk {input_path} is {video_stream.width}x{video_stream.height}, " |
| f"expected {width}x{height}" |
| ) |
| for frame in chunk.decode(video_stream): |
| frame = frame.reformat(width=width, height=height, format="yuv420p") |
| frame.pts = frame_count |
| frame.time_base = time_base |
| for packet in stream.encode(frame): |
| container.mux(packet) |
| frame_count += 1 |
| finally: |
| chunk.close() |
|
|
| for packet in stream.encode(): |
| container.mux(packet) |
| success = True |
| finally: |
| container.close() |
| if not success: |
| output_path.unlink(missing_ok=True) |
| return frame_count |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--output", required=True) |
| parser.add_argument("--fps", type=float, required=True) |
| parser.add_argument("inputs", nargs="+") |
| args = parser.parse_args() |
|
|
| frames = concat_videos([Path(p) for p in args.inputs], Path(args.output), args.fps) |
| print(json.dumps({"frames": frames})) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|