Видео

Склеить несколько видео

Нормализует клипы и собирает их в один файл через concat без рассинхронизации.

Python Windows macOS Linux Продвинутый
Скачать concat_video.py
Описание

Что делает скрипт

Скрипт приводит все ролики к разрешению, частоте кадров и звуку первого файла, затем склеивает их через concat demuxer. Если в клипе нет звука, добавляется тишина. Оригиналы не меняются, результат сохраняется отдельно.

Запуск

Быстрый старт

python concat_video.py part1.mp4 part2.mp4 --output final.mp4

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python concat_video.py part1.mp4 part2.mp4 --output final.mp4
  • python concat_video.py intro.mov main.mkv outro.mp4 -o course.mp4 --crf 20
  • python concat_video.py clips/part1.mp4 clips/part2.mp4 -o reel.mp4
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
FFmpeg 6+ ffmpeg и ffprobe
Windows winget install Gyan.FFmpeg
macOS brew install ffmpeg
Linux sudo apt install ffmpeg
Исходник

concat_video.py

#!/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())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get video-concat-clips
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Видео

Монтаж, сжатие, субтитры, кадры и пакетная обработка видео.