#!/usr/bin/env python3 """Изменение скорости видео с коррекцией звука.""" from __future__ import annotations import argparse import json import shutil import subprocess from pathlib import Path def has_audio(path: Path) -> bool: result = subprocess.run( [ "ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=index", "-of", "json", str(path), ], capture_output=True, text=True, check=False, ) if result.returncode != 0: raise SystemExit(f"ffprobe не смог прочитать {path}:\n{result.stderr.strip()}") return bool(json.loads(result.stdout).get("streams")) def atempo_chain(factor: float) -> str: parts: list[str] = [] value = factor while value > 2.0: parts.append("atempo=2.0") value /= 2.0 while value < 0.5: parts.append("atempo=0.5") value /= 0.5 parts.append(f"atempo={value:.6f}") return ",".join(parts) def main() -> int: parser = argparse.ArgumentParser(description="Ускорить или замедлить видео") parser.add_argument("input", type=Path) parser.add_argument("--factor", type=float, required=True, help="1.5 - быстрее, 0.5 - медленнее") parser.add_argument("--output-dir", type=Path, default=Path("speed")) parser.add_argument("--crf", type=int, default=20) parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() if shutil.which("ffmpeg") is None: raise SystemExit("Не найден ffmpeg. Установите FFmpeg.") source = args.input.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") if not 0.25 <= args.factor <= 4.0: parser.error("Коэффициент должен быть от 0.25 до 4.0") args.output_dir.mkdir(parents=True, exist_ok=True) label = str(args.factor).replace(".", "_") target = args.output_dir / f"{source.stem}_x{label}.mp4" if target.exists() and not args.overwrite: raise SystemExit(f"Файл уже существует: {target}. Добавьте --overwrite.") command = ["ffmpeg", "-hide_banner", "-nostdin", "-i", str(source)] if has_audio(source): filter_complex = ( f"[0:v]setpts=PTS/{args.factor}[v];" f"[0:a]{atempo_chain(args.factor)}[a]" ) command += [ "-filter_complex", filter_complex, "-map", "[v]", "-map", "[a]", "-c:a", "aac", "-b:a", "192k", ] else: command += ["-vf", f"setpts=PTS/{args.factor}", "-map", "0:v:0", "-an"] command += [ "-c:v", "libx264", "-preset", "medium", "-crf", str(args.crf), "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-n", str(target), ] print(f"Скорость: {args.factor}x") result = subprocess.run(command, check=False) if result.returncode != 0: raise SystemExit(f"ffmpeg завершился с кодом {result.returncode}") print(f"Готово: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())