Files
privatestudio/transcode.py
T

382 lines
13 KiB
Python

#!/usr/bin/env python3
import argparse
import os
import re
import subprocess
import sys
from pathlib import Path
try:
import yaml
except ImportError: # pragma: no cover - dependency install guidance
print("PyYAML is required. Install it with: python -m pip install pyyaml", file=sys.stderr)
raise SystemExit(1)
ENCODER_MAP = {
"cpu": {
"name": "cpu",
"codec": "libx264",
"label": "CPU (libx264)",
},
"quicksync": {
"name": "quicksync",
"codec": "h264_qsv",
"label": "Intel Quick Sync (h264_qsv)",
},
"nvidia": {
"name": "nvidia",
"codec": "h264_nvenc",
"label": "NVIDIA (h264_nvenc)",
},
}
def parse_bitrate(value):
if value is None:
raise ValueError("Profile bitrate is required")
if not isinstance(value, str):
value = str(value)
match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*([km]??)", value.strip().lower())
if not match:
raise ValueError(f"Unsupported bitrate format: {value!r}")
number = float(match.group(1))
unit = match.group(2)
if unit in ("", "k"):
return number * 1000.0
if unit == "m":
return number * 1000000.0
raise ValueError(f"Unsupported bitrate unit: {value!r}")
def bitrate_to_string(value):
value = float(value)
if value >= 1000000:
return f"{value / 1000000:.2f}M"
return f"{value / 1000:.0f}k"
def parse_resolution(value):
if value is None:
raise ValueError("Profile resolution is required")
if isinstance(value, str):
text = value.strip().replace(" ", "")
parts = text.split("x")
if len(parts) != 2:
raise ValueError(f"Resolution must be in WxH format, got {value!r}")
width, height = parts
return int(width), int(height)
raise ValueError(f"Unsupported resolution format: {value!r}")
def build_output_name(profile_name, width, height):
target_name = f"output_{height}p.mp4"
return target_name
def load_profile(path):
with open(path, "r", encoding="utf-8") as handle:
data = yaml.safe_load(handle) or {}
if not isinstance(data, dict):
raise ValueError(f"Profile config at {path} must contain a YAML mapping")
profiles = data.get("profiles")
if not isinstance(profiles, dict) or not profiles:
raise ValueError(f"Profile config at {path} must define a non-empty 'profiles' mapping")
return data, profiles
def encoder_available(encoder_name: str) -> bool:
if encoder_name == "cpu":
return True
codec = ENCODER_MAP[encoder_name]["codec"]
process = subprocess.run(
["ffmpeg", "-hide_banner", "-encoders"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
combined = (process.stdout or "") + (process.stderr or "")
return codec in combined
def is_hevc_input(input_asset: str) -> bool:
process = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name", "-of", "default=noprint_wrappers=1:nokey=1:noesc=1", input_asset],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
return "hevc" in (process.stdout or "").lower()
def build_ffmpeg_command(input_asset: str, profile_config: dict, output_dir: Path, selected_encoder: str):
if selected_encoder not in ENCODER_MAP:
raise ValueError(f"Unsupported encoder '{selected_encoder}'. Options: {', '.join(ENCODER_MAP.keys())}")
encoder_cfg = ENCODER_MAP[selected_encoder]
if "profiles" not in profile_config:
raise ValueError("Profile YAML is missing a 'profiles' section")
# pix_fmt = "p010le" if selected_encoder == "quicksync" else "yuv420p"
variant_profiles = profile_config["profiles"]
video_outputs = []
ffmpeg_args = ["ffmpeg", "-y", "-i", input_asset]
if selected_encoder == "quicksync":
ffmpeg_args = ["ffmpeg", "-y", "-hwaccel", "qsv", "-c:v", "h264_qsv", "-i", input_asset]
for profile_key, profile in variant_profiles.items():
profile = dict(profile)
codec = profile.get("codec", "h264")
if codec.lower() == "h264":
codec = encoder_cfg["codec"]
else:
codec = codec
resolution = profile.get("resolution")
bitrate = profile.get("bitrate", "1000k")
width, height = parse_resolution(resolution)
fps = profile.get("fps", 30)
base_bitrate = parse_bitrate(bitrate)
maxrate = base_bitrate * 1.07
bufsize = base_bitrate * 1.5
output_name = build_output_name(profile_key, width, height)
video_outputs.append({
"profile_key": profile_key,
"output_name": output_name,
"codec": codec,
"bitrate": bitrate,
"maxrate": maxrate,
"bufsize": bufsize,
"width": width,
"size_key": f"v{height}",
"height": height,
"fps": fps,
})
if not video_outputs:
raise ValueError("No video profiles were found in the configuration")
output_sizes = dict()
# Create complex filter map and deduplicate scale sizes using size_key
for output in video_outputs:
size_key = output["size_key"]
output_sizes[size_key] = {
"width": output["width"],
"height": output["height"],
"scalestring": f"scale=w={output['width']}:h={output['height']}[{size_key}]",
}
if selected_encoder == "quicksync":
output_sizes[size_key]["scalestring"] = f"scale_qsv=w={output['width']}:h={output['height']}[{size_key}]"
complex_filter = "[0:v]split=%d" % len(video_outputs)
complex_filter_scales = list()
complex_filter_count = 0
for size_key, size_info in output_sizes.items():
complex_filter_count += 1
size_ref = f"[s{complex_filter_count}]"
complex_filter += size_ref
complex_filter_scales.append(size_ref + size_info["scalestring"])
complex_filter += ";" + ";".join(complex_filter_scales)
ffmpeg_args.extend(["-filter_complex", complex_filter])
print(repr(complex_filter_scales))
print(repr(complex_filter))
# for _ in video_outputs:
# ffmpeg_args.extend(["-map", "0:v:0"])
# ffmpeg_args.extend(["-map", "0:a:0"])
# ffmpeg_args.extend(["-g", "72", "-keyint_min", "72", "-sc_threshold", "0"])
for index, profile in enumerate(video_outputs):
ffmpeg_args.extend([
"-map", f"[{profile['size_key']}]", # Map the scaled video stream
"-c:v",
profile["codec"],
"-b:v",
bitrate_to_string(parse_bitrate(profile["bitrate"])),
"-maxrate",
bitrate_to_string(profile["maxrate"]),
"-bufsize",
bitrate_to_string(profile["bufsize"]),
"-g", "72", "-keyint_min", "72", "-sc_threshold", "0",
# "-pix_fmt:v:%d" % index,
# pix_fmt,
# "-r:v:%d" % index,
# str(profile["fps"]),
# "-filter:v:%d" % index,
# f"scale={profile['width']}:{profile['height']}",
"-forced-idr", "1",
"-an",
str(output_dir / profile["output_name"]),
])
ffmpeg_args.extend([
"-map", "0:a?",
"-c:a",
"aac",
"-b:a",
"128k",
"-vn",
str(output_dir / "output_audio.mp4"),
])
return ffmpeg_args, [item["output_name"] for item in video_outputs] + ["output_audio.mp4"]
def parse_args():
parser = argparse.ArgumentParser(
description="Transcode an input asset to multiple H.264 quality variants with Bento4-friendly alignment settings."
)
parser.add_argument("input_asset", help="Path to the source video file (for example asset.mp4)")
parser.add_argument("profile_config", help="Path to the YAML encoding profile file")
parser.add_argument("output_dir", help="Directory to write output variants and result metadata")
parser.add_argument(
"--encoder",
choices=sorted(ENCODER_MAP.keys()),
help="Override the configured encoder: cpu, quicksync, or nvidia",
)
return parser.parse_args()
def preexec_nice():
try:
import psutil
psutil.Process().nice(10) # Lower the priority of the ffmpeg process
except ImportError:
print("Warning: psutil is not installed; ffmpeg will run at normal priority.", file=sys.stderr)
def run_ffmpeg(command, output_dir):
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True,
preexec_fn=preexec_nice, # Ensure ffmpeg runs at lower priority
)
if process.stdout is None:
raise RuntimeError("ffmpeg stdout was not captured")
merged_output = []
for line in process.stdout:
print(line, end="")
merged_output.append(line)
return_code = process.wait()
return return_code, "".join(merged_output)
def write_result_yaml(output_dir: Path, generated_files, command, input_asset, encoder_name):
output_dir.mkdir(parents=True, exist_ok=True)
result = {
"input": str(input_asset),
"encoder": encoder_name,
"ffmpeg_command": command,
"files": generated_files,
}
result_path = output_dir / "transcoderesult.yaml"
with open(result_path, "w", encoding="utf-8") as handle:
yaml.safe_dump(result, handle, sort_keys=False)
return result_path
def write_output_log(output_dir: Path, merged_output):
output_dir.mkdir(parents=True, exist_ok=True)
log_path = output_dir / "transcodeoutput.log"
with open(log_path, "w", encoding="utf-8") as handle:
handle.write(merged_output)
return log_path
def main():
args = parse_args()
input_asset = Path(args.input_asset)
output_dir = Path(args.output_dir)
profile_config_path = Path(args.profile_config)
if not input_asset.exists():
raise FileNotFoundError(f"Input asset does not exist: {input_asset}")
if not profile_config_path.exists():
raise FileNotFoundError(f"Profile config does not exist: {profile_config_path}")
data, profiles = load_profile(profile_config_path)
configured_encoder = (args.encoder or data.get("encoder") or "cpu").lower()
requested_encoder = configured_encoder
if args.encoder is None and configured_encoder != "cpu" and not encoder_available(configured_encoder):
print(
f"Warning: encoder '{configured_encoder}' is not available in this ffmpeg build; falling back to CPU.",
file=sys.stderr,
)
configured_encoder = "cpu"
elif args.encoder is not None and not encoder_available(configured_encoder):
raise ValueError(
f"Selected encoder '{configured_encoder}' is not available in this ffmpeg build. "
f"Choose one of: {', '.join(ENCODER_MAP.keys())}."
)
output_dir.mkdir(parents=True, exist_ok=True)
ffmpeg_command, generated_files = build_ffmpeg_command(
str(input_asset),
data,
output_dir,
configured_encoder,
)
print(f"FFmpeg command: {' '.join(ffmpeg_command)}")
return_code, merged_output = run_ffmpeg(ffmpeg_command, output_dir)
if return_code != 0 and args.encoder is None and requested_encoder != "cpu" and configured_encoder != "cpu":
sys.exit(1) # If the user explicitly requested a non-CPU encoder, don't retry with CPU
print(
f"Warning: encoder '{requested_encoder}' is not usable with this asset; retrying with CPU.",
file=sys.stderr,
)
configured_encoder = "cpu"
ffmpeg_command, generated_files = build_ffmpeg_command(
str(input_asset),
data,
output_dir,
configured_encoder,
)
print(f"FFmpeg fallback command: {' '.join(ffmpeg_command)}")
return_code, merged_output = run_ffmpeg(ffmpeg_command, output_dir)
result_path = write_result_yaml(
output_dir,
generated_files,
ffmpeg_command,
input_asset,
configured_encoder,
)
log_path = write_output_log(output_dir, merged_output)
if return_code != 0:
print(f"\nFFmpeg exited with code {return_code}", file=sys.stderr)
print(f"Result written to: {result_path}", file=sys.stderr)
print(f"Output log written to: {log_path}", file=sys.stderr)
return return_code
print(f"\nTranscoding complete. Result written to: {result_path}")
print(f"Output log written to: {log_path}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as exc: # pragma: no cover - CLI error path
print(f"Error: {exc}", file=sys.stderr)
raise SystemExit(1)