File size: 2,185 Bytes
a96d4f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import subprocess
import re
from pathlib import Path

def get_video_dimensions(file_path: str) -> tuple[int, int] | None:
    """Extract original video width and height from HandBrakeCLI --scan output."""
    try:
        # Run HandBrakeCLI --scan and capture stderr (it prints to stderr)
        result = subprocess.run(
            ["HandBrakeCLI", "-i", file_path, "--scan"],
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE,
            text=True
        )
        output = result.stderr + result.stdout

        # Find "+ size: 1920x1080" line
        match = re.search(r"\+ size:\s*(\d+)x(\d+)", output)
        if match:
            width = int(match.group(1))
            height = int(match.group(2))
            return width, height
        else:
            raise RuntimeError("Could not parse width and height from HandBrakeCLI output.")
    except Exception as e:
        print(f"[ERROR] Failed to get dimensions for {file_path}: {e}")

def process_video(file_path: str, qualities=range(40, 11, -2)):
    """Process a video at multiple quality levels, scaling to 0.25x width."""
    width,height = get_video_dimensions(file_path)
    if width is None or height is None:
        return

    new_width = width // 4
    new_height = height // 4
    print(f"Original width = {width}, new width = {new_width}")
    print(f"Original height = {height}, new width = {new_height}")

    # Ensure output folder exists
    out_dir = Path("processed")
    out_dir.mkdir(exist_ok=True)

    base_name = Path(file_path).stem
    for q in qualities:
        out_file = out_dir / f"{base_name}_{q}.mp4"
        print(f"Encoding {file_path}{out_file} (quality={q})")

        cmd = [
            "HandBrakeCLI",
            "-i", file_path,
            "-o", str(out_file),
            "-q", str(q),
            "--width", str(new_width),
            "--height", str(new_height)
        ]
        subprocess.run(cmd, check=True)

def main():
    # Process all mp4 files in the current directory
    for file in Path(".").glob("*.mp4"):
        print(f"\n=== Processing {file} ===")
        process_video(str(file))

if __name__ == "__main__":
    main()