dotfiles/config/scripts/videoQuota

70 lines
1.4 KiB
Python
Executable file

#!/usr/bin/env python3
# Compress a video to make it fit under a certain size.
# Usage: videoQuota SIZE SRC DST
# SIZE: destination video size in bytes
# SRC: source video file
# DST: destination video file
# Example: videoQuota 20971520 source.mov dest.mp4
# To make a ~20 MiB MP4 of a MOV video
import sys
import subprocess
import logging
import coloredlogs
coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s")
log = logging.getLogger()
def duration_file(path: str) -> float:
cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
path,
]
run = subprocess.run(cmd, stdout=subprocess.PIPE, check=True)
ret = run.stdout.decode().strip()
return float(ret)
# Constants
audio_br_bi = 128000
# TODO Arguments if you feel like it
quota_by = int(sys.argv[1])
in_file = sys.argv[2]
out_file = sys.argv[3]
filters = sys.argv[4:]
quota_bi = quota_by * 8
duration = duration_file(in_file)
tot_br_bi = quota_bi / duration
video_br_bi = int(tot_br_bi - audio_br_bi)
assert video_br_bi > 0, "Not even enough space for audio"
cmd = (
[
"ffmpeg",
"-i",
in_file,
]
+ filters
+ [
"-b:v",
str(video_br_bi),
"-b:a",
str(audio_br_bi),
out_file,
]
)
print(" ".join(cmd))
subprocess.run(cmd, check=True)