diff --git a/bin/vcmp b/bin/vcmp index 1b85da2..2ea6a05 100755 --- a/bin/vcmp +++ b/bin/vcmp @@ -5,6 +5,10 @@ import subprocess import shutil import sys import argparse +import fnmatch +import functools +import json +import re import tempfile import logging from logging.handlers import RotatingFileHandler @@ -14,6 +18,7 @@ from tqdm import tqdm video_extensions: list[str] = ["mp4", "mkv", "avi", "wmv", "mov", "m4v", "ts", "flv", "mpg", "webm"] embedded_sub_extensions: list[str] = ["mkv"] +vr_filename_token = re.compile(r"vr|vr180|vr360|180|360|180x180|360x180|lr|tb|sbs|3dh|3dv|eac360|mkx\d+|vrca\d+|fisheye\d*") total_files: int = 0 @@ -152,12 +157,59 @@ def clean_directory(directory_path: pathlib.Path) -> None: else: item.unlink() # Yeet the file +def is_excluded(path: pathlib.Path, root: pathlib.Path, patterns: list[str]) -> bool: + """Match patterns against the name or the path relative to root.""" + rel = path.relative_to(root).as_posix() + return any(fnmatch.fnmatch(path.name, p) or fnmatch.fnmatch(rel, p) for p in patterns) + +def walk(root: pathlib.Path, exclude: list[str]): + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if not is_excluded(pathlib.Path(dirpath) / d, root, exclude)] + for filename in filenames: + filepath = pathlib.Path(dirpath) / filename + if not is_excluded(filepath, root, exclude): + yield filepath + def is_video(path: pathlib.Path) -> bool: return path.suffix.lower()[1:] in video_extensions def is_video_with_embedded_subs(path: pathlib.Path) -> bool: return path.suffix.lower()[1:] in embedded_sub_extensions +@functools.lru_cache(maxsize=None) +def vr_reason(path: pathlib.Path) -> str | None: + tokens = re.split(r"[^a-z0-9]+", path.stem.lower()) + if any(vr_filename_token.fullmatch(t) for t in tokens): + return "filename" + + cmd = [ + "ffprobe", + "-v", "error", + "-select_streams", "v:0", + "-show_entries", "stream=width,height:stream_side_data", + "-of", "json", + str(path) + ] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stream = json.loads(result.stdout)["streams"][0] + except (subprocess.CalledProcessError, ValueError, KeyError, IndexError): + logging.error(f"Error probing {path} for VR") + return None + + for side_data in stream.get("side_data_list", []): + if side_data.get("side_data_type") == "Spherical Mapping": + return "spherical metadata" + if side_data.get("side_data_type") == "Stereo 3D" and side_data.get("type") != "2D": + return "stereo metadata" + + width, height = stream.get("width", 0), stream.get("height", 0) + if height >= 1920: + ratio = width / height + if abs(ratio - 2) < 0.02 or abs(ratio - 1) < 0.02: + return f"{width}x{height} frame" + return None + def get_video_duration(input_file: pathlib.Path) -> float: cmd = [ "ffprobe", @@ -311,39 +363,42 @@ def process_directory( temp_dir: pathlib.Path, remove_source: bool = False, nice: int = 20, - count_only: bool = False + count_only: bool = False, + exclude: list[str] = [], + include_vr: bool = False ) -> int: """Process all video files in source directory recursively.""" count = 0 successful = 0 - for dirpath, _dirnames, filenames in os.walk(source_dir): - for filename in filenames: - filepath = pathlib.Path(dirpath) / filename + for filepath in walk(source_dir, exclude): + # File might have been deleted since starting script + if not filepath.exists() or not is_video(filepath): + logging.debug(f"Skipping {filepath}: not a video file or doesn't exist") + continue + if ".cmp." in filepath.name: + logging.debug(f"Skipping {filepath}: already compressed") + continue - # File might have been deleted since starting script - if not filepath.exists() or not is_video(filepath): - logging.debug(f"Skipping {filepath}: not a video file or doesn't exist") - continue - if ".cmp." in filepath.name: - logging.debug(f"Skipping {filepath}: already compressed") - continue + # Determine destination path, remove source if already exists and requested + target_path = destination_dir / filepath.relative_to(source_dir) + target_path = target_path.with_suffix(".cmp.mp4") + if target_path.exists(): + if remove_source: + logging.info(f"Removing source file {filepath} as compressed version exists") + filepath.unlink() + logging.debug(f"Skipping {filepath}: target already exists") + continue + if not include_vr and (reason := vr_reason(filepath)): + if not count_only: + logging.info(f"Skipping {filepath}: VR video ({reason})") + continue - # Determine destination path, remove source if already exists and requested - target_path = destination_dir / filepath.relative_to(source_dir) - target_path = target_path.with_suffix(".cmp.mp4") - if target_path.exists(): - if remove_source: - logging.info(f"Removing source file {filepath} as compressed version exists") - filepath.unlink() - logging.debug(f"Skipping {filepath}: target already exists") - continue + count += 1 + if count_only: + continue - count += 1 - if count_only: - continue - - if process_single_file(filepath, target_path, temp_dir, remove_source, nice, count): - successful += 1 + if process_single_file(filepath, target_path, temp_dir, remove_source, nice, count): + successful += 1 if not count_only: logging.info(f"Processed {count} files, {successful} successful") @@ -353,22 +408,25 @@ def process_subtitles( *, source_dir: pathlib.Path, destination_dir: pathlib.Path, - temp_dir: pathlib.Path): - for dirpath, _dirnames, filenames in os.walk(source_dir): - for filename in filenames: - filepath = pathlib.Path(dirpath) / filename - # File might have been deleted since starting script - if not filepath.exists() or not is_video_with_embedded_subs(filepath): - logging.debug(f"Skipping {filepath}: not a video file or doesn't exist") + temp_dir: pathlib.Path, + exclude: list[str] = [], + include_vr: bool = False): + for filepath in walk(source_dir, exclude): + # File might have been deleted since starting script + if not filepath.exists() or not is_video_with_embedded_subs(filepath): + logging.debug(f"Skipping {filepath}: not a video file or doesn't exist") + continue + if not include_vr and (reason := vr_reason(filepath)): + logging.info(f"Skipping {filepath}: VR video ({reason})") + continue + if has_subs(filepath): + target_path = destination_dir / filepath.relative_to(source_dir) + target_path = target_path.with_suffix(".cmp.en.srt") + if target_path.exists(): + logging.debug(f"Skipping {filepath}: target already exists") continue - if has_subs(filepath): - target_path = destination_dir / filepath.relative_to(source_dir) - target_path = target_path.with_suffix(".cmp.en.srt") - if target_path.exists(): - logging.debug(f"Skipping {filepath}: target already exists") - continue - cmd = extract_sub_command(filepath, target_path) - result = subprocess.run(cmd, capture_output=True, text=True, check=True) + cmd = extract_sub_command(filepath, target_path) + result = subprocess.run(cmd, capture_output=True, text=True, check=True) def main(): parser = argparse.ArgumentParser( @@ -394,6 +452,10 @@ def main(): help='Nice value for process priority (default: 20). Valid values are 0 (highest priority) to 39 (lowest priority). Lower values use more system resources.') parser.add_argument('-i', '--ignore-busy', action='store_true', help='Ignore system busy check and run anyway') + parser.add_argument('-x', '--exclude', action='append', default=[], metavar='PATTERN', + help='Skip files and directories whose name or path relative to the source matches this glob. Repeatable.') + parser.add_argument('--include-vr', action='store_true', + help='Also process VR videos, detected by spherical/stereo metadata, filename tags, or a 2:1 or 1:1 frame of at least 1920 high') args = parser.parse_args() setup_logging(bool(args.verbose)) @@ -412,7 +474,9 @@ def main(): if args.sub: process_subtitles(source_dir=source_dir, destination_dir=destination_dir, - temp_dir=temp_dir) + temp_dir=temp_dir, + exclude=args.exclude, + include_vr=args.include_vr) else: logging.info(f"Starting video compression from {source_dir} to {destination_dir}") @@ -421,7 +485,9 @@ def main(): source_dir=source_dir, destination_dir=destination_dir, temp_dir=temp_dir, - count_only=True + count_only=True, + exclude=args.exclude, + include_vr=args.include_vr ) process_directory( @@ -429,7 +495,9 @@ def main(): destination_dir=destination_dir, temp_dir=temp_dir, remove_source=args.remove_source, - nice=args.nice + nice=args.nice, + exclude=args.exclude, + include_vr=args.include_vr ) if __name__ == "__main__": main()