Skip to content

Instantly share code, notes, and snippets.

@idbrii
Created July 28, 2022 22:16
Show Gist options
  • Save idbrii/e849a79deb2fb2eb49e187a646ca6109 to your computer and use it in GitHub Desktop.
Save idbrii/e849a79deb2fb2eb49e187a646ca6109 to your computer and use it in GitHub Desktop.
Easily resize videos with ffmpeg
#! /usr/bin/env python3
"""
Video editing tools.
I don't remember the args for ffmpeg and it's useful to run them on multiple
videos in sequence. Great for shrinking game video that was captured at 4k.
Assumes ffmpeg is in your path. On Win10, use scoop to install (https://scoop.sh/).
Use .cmd files like this to make a drag-and-drop target:
@echo off
python3 C:\bin\ffmpeg_helper.py half_size %*
echo.
pause
"""
import subprocess
import sys
from pathlib import Path
preset_h264 = [
"-c:v",
"libx264",
"-preset",
"fast",
"-crf",
"26",
"-c:a",
"aac",
"-b:a",
"128k",
]
def _run_ffmpeg(args, suffix, files):
"""Convert input files to all be half-sized videos."""
for src in files:
src = Path(src)
dest = src.with_stem(src.stem + suffix)
cmd = ["ffmpeg", "-i", src] + args + [dest]
print()
print("Running:")
print(" ", " ".join(str(s) for s in cmd))
print()
subprocess.check_call(cmd)
def half_size(*files):
"""Convert input files to all be half-sized videos."""
cmd = [
"-vf",
"scale=w=iw/2:h=ih/2",
] + preset_h264
_run_ffmpeg(cmd, "-small", files)
def to_1080(*files):
"""Convert input files to all be 1080p videos."""
cmd = [
"-vf",
"scale=h=1080",
] + preset_h264
_run_ffmpeg(cmd, "-1080p", files)
def to_h265(*files):
"""Convert input files to all be h265 with AAC.
Xbox Game Bar produces massive files and this conversion reencodes to be
smaller at the same quality.
"""
# https://trac.ffmpeg.org/wiki/Encode/H.265
cmd = [
"-c:v",
"libx265",
"-crf",
"26",
"-preset",
"fast",
"-c:a",
"aac",
"-b:a",
"128k",
"-tag:v",
"hvc1",
]
_run_ffmpeg(cmd, "-h265", files)
def to_h264(*files):
"""Convert input files to all be h264 with AAC.
Xbox Game Bar produces massive files and this conversion reencodes to be
smaller at the same quality.
"""
# https://trac.ffmpeg.org/wiki/Encode/H.264
cmd = preset_h264
_run_ffmpeg(cmd, "-h264", files)
if __name__ == "__main__":
script_folder = Path(__file__).parent
if script_folder not in sys.path:
sys.path.insert(0, script_folder)
print("Modified sys.path to add", script_folder)
print(script_folder)
args = sys.argv
# args[0] = current file
# args[1] = function name
# args[2:] = function args : (*unpacked)
globals()[args[1]](*args[2:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment