File size: 4,215 Bytes
7ce6d3d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | #!/usr/bin/env python3
"""
Batch-encode videos to the Hap family (hap / hap_q / hap_alpha / hap_q_alpha).
Only the newest non-Hap video per folder is encoded.
Outputs are written next to each source file with a Hap suffix in the filename.
"""
import os
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
HAP_FORMAT = os.environ.get("HAP_FORMAT", "hap")
HAP_COMPRESSOR = os.environ.get("HAP_COMPRESSOR", "snappy")
FFMPEG_THREADS = os.environ.get("FFMPEG_THREADS", "0")
RED = "\033[0;31m"
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
NC = "\033[0m"
VIDEO_EXTENSIONS = {".mp4", ".mov", ".avi", ".mkv", ".m4v", ".flv", ".wmv"}
HAP_SUFFIXES = ("_hap", "_hapq", "_hapalpha", "_hapqalpha")
FORMAT_TO_SUFFIX = {
"hap": "hap",
"hap_q": "hapq",
"hap_alpha": "hapalpha",
"hap_q_alpha": "hapqalpha",
}
def find_newest_per_folder(root: Path) -> list[Path]:
"""Group non-Hap video files by folder, return only the newest from each."""
folders: dict[Path, list[Path]] = defaultdict(list)
for path in root.rglob("*"):
if not path.is_file():
continue
if path.suffix.lower() not in VIDEO_EXTENSIONS:
continue
if path.stem.endswith(HAP_SUFFIXES):
continue
folders[path.parent].append(path)
newest = []
for folder, files in sorted(folders.items()):
files.sort(key=lambda f: f.stat().st_mtime, reverse=True)
newest.append(files[0])
if len(files) > 1:
skipped = [f.name for f in files[1:]]
print(
f"{YELLOW}[{folder}] Picking newest: {files[0].name}, "
f"skipping {len(skipped)} older: {', '.join(skipped)}{NC}"
)
return newest
def encode_video(input_file: Path, suffix: str) -> bool:
output_file = input_file.parent / f"{input_file.stem}_{suffix}.mov"
if output_file.exists():
print(f"{YELLOW}Skipping {input_file} - output already exists{NC}")
return True
print(f"{GREEN}Encoding: {input_file}{NC}")
print(f" Output: {output_file}")
result = subprocess.run(
[
"ffmpeg",
"-nostdin",
"-threads",
FFMPEG_THREADS,
"-i",
str(input_file),
"-vf",
"pad=ceil(iw/4)*4:ceil(ih/4)*4",
"-c:v",
"hap",
"-format",
HAP_FORMAT,
"-compressor",
HAP_COMPRESSOR,
"-an",
"-y",
str(output_file),
],
)
if result.returncode == 0:
print(f"{GREEN} Success{NC}")
return True
else:
print(f"{RED} Failed{NC}")
return False
def main():
if HAP_FORMAT not in FORMAT_TO_SUFFIX:
print(
f"{RED}Error: Unsupported HAP_FORMAT='{HAP_FORMAT}' "
f"(use hap|hap_q|hap_alpha|hap_q_alpha){NC}"
)
sys.exit(1)
if HAP_COMPRESSOR not in ("snappy", "none"):
print(
f"{RED}Error: Unsupported HAP_COMPRESSOR='{HAP_COMPRESSOR}' "
f"(use snappy|none){NC}"
)
sys.exit(1)
try:
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
except (FileNotFoundError, subprocess.CalledProcessError):
print(f"{RED}Error: ffmpeg is not installed or not in PATH{NC}")
sys.exit(1)
suffix = FORMAT_TO_SUFFIX[HAP_FORMAT]
root = Path(".")
print(f"{GREEN}Searching for video files (newest per folder)...{NC}")
print()
candidates = find_newest_per_folder(root)
if not candidates:
print(f"{YELLOW}No video files found.{NC}")
return
print()
success = 0
failed = 0
for file in candidates:
if encode_video(file, suffix):
success += 1
else:
failed += 1
print()
print(f"{GREEN}{'=' * 40}{NC}")
print(f"{GREEN}Encoding complete!{NC}")
print(f"Folders processed: {len(candidates)}")
print(f"{GREEN}Successfully encoded: {success}{NC}")
if failed > 0:
print(f"{RED}Failed: {failed}{NC}")
print(f"{GREEN}{'=' * 40}{NC}")
if __name__ == "__main__":
main()
|