#!/usr/bin/env python3 """Склейка видео через concat demuxer после нормализации.""" from __future__ import annotations import argparse import json import shutil import subprocess import tempfile from pathlib import Path def probe(path: Path) -> dict: result = subprocess.run( [ "ffprobe", "-v", "error", "-print_format", "json", "-show_streams", "-show_format", str(path), ], capture_output=True, text=True, check=False, ) if result.returncode != 0: raise SystemExit(f"ffprobe не смог прочитать {path}:\n{result.stderr.strip()}") return json.loads(result.stdout) def video_stream(info: dict) -> dict: stream = next((item for item in info.get("streams", []) if item.get("codec_type") == "video"), None) if stream is None: raise SystemExit("В одном из файлов нет видеопотока") return stream def has_audio(info: dict) -> bool: return any(item.get("codec_type") == "audio" for item in info.get("streams", [])) def safe_rate(value: str) -> str: try: numerator, denominator = value.split("/") if int(denominator) == 0: return "30" except (ValueError, AttributeError): return "30" return value def concat_line(path: Path) -> str: text = path.as_posix().replace("'", "'\\''") return f"file '{text}'" def main() -> int: parser = argparse.ArgumentParser(description="Склеить видео в один файл") parser.add_argument("inputs", nargs="+", type=Path) parser.add_argument("--output", "-o", type=Path, required=True) parser.add_argument("--crf", type=int, default=20) parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() for tool in ("ffmpeg", "ffprobe"): if shutil.which(tool) is None: raise SystemExit(f"Не найден {tool}. Установите FFmpeg.") sources = [path.expanduser() for path in args.inputs] for source in sources: if not source.is_file(): raise SystemExit(f"Файл не найден: {source}") target = args.output.expanduser() if target.exists() and not args.overwrite: raise SystemExit(f"Файл уже существует: {target}. Добавьте --overwrite.") target.parent.mkdir(parents=True, exist_ok=True) first = probe(sources[0]) stream = video_stream(first) width = int(stream["width"]) height = int(stream["height"]) width -= width % 2 height -= height % 2 fps = safe_rate(stream.get("r_frame_rate", "30")) print(f"Целевой формат: {width}x{height}, {fps} fps") with tempfile.TemporaryDirectory(prefix="concat_") as temp_dir: work = Path(temp_dir) parts: list[Path] = [] for index, source in enumerate(sources): info = probe(source) video_stream(info) audio = has_audio(info) part = work / f"part_{index:03d}.mp4" command = ["ffmpeg", "-hide_banner", "-nostdin", "-y", "-i", str(source)] if audio: command += ["-map", "0:v:0", "-map", "0:a:0"] else: command += [ "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000", "-map", "0:v:0", "-map", "1:a:0", "-shortest", ] command += [ "-vf", ( f"scale={width}:{height}:force_original_aspect_ratio=decrease," f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}" ), "-c:v", "libx264", "-preset", "veryfast", "-crf", str(args.crf), "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", str(part), ] print(f"Подготовка {index + 1}/{len(sources)}: {source.name}") result = subprocess.run(command, check=False) if result.returncode != 0: raise SystemExit(f"Не удалось подготовить {source}") parts.append(part) list_file = work / "list.txt" list_file.write_text("\n".join(concat_line(part) for part in parts) + "\n", encoding="utf-8") command = [ "ffmpeg", "-hide_banner", "-nostdin", "-y", "-f", "concat", "-safe", "0", "-i", str(list_file), "-c", "copy", "-movflags", "+faststart", str(target), ] print("Склейка:", target) result = subprocess.run(command, check=False) if result.returncode != 0: raise SystemExit(f"ffmpeg завершился с кодом {result.returncode}") size_mb = target.stat().st_size / (1024 * 1024) print(f"Готово: {target} ({size_mb:.1f} МБ)") return 0 if __name__ == "__main__": raise SystemExit(main())