#!/usr/bin/env python3
"""GB per hour of your own recording (koldflux.com, 2026-12-01, updated after review the same day).
Needs ffprobe (part of FFmpeg) on your PATH. Reads size and length and prints MB per minute (1 MB = 1,000,000 bytes),
GB per hour (1 GB = 1,000,000,000 bytes), GiB per hour (the "GB" Windows shows) and, with --free, how many hours
fit in that much free space. Works on MKV, MP4, MOV and other files ffprobe can read.
Checks: the length is taken from the last packet when the container has none (a recording that was cut off), a file
whose data ends far before the length its header claims (a truncated copy) is reported with exit 1, and a test
shorter than 60 s gets a warning because it overstates GB per hour.
Usage: python3 gb-per-hour.py [--free GB] recording.mkv [more files]"""
import argparse, os, shutil, subprocess, sys

def probe(args):
    return subprocess.run(["ffprobe", "-v", "error"] + args, capture_output=True, text=True)

def last_packet(path):
    """Time where the data really ends: last packet start + its duration, video first, else any stream."""
    for sel in (["-select_streams", "v:0"], []):
        r = probe(sel + ["-show_entries", "packet=pts_time,duration_time", "-of", "csv=p=0", path])
        end = None
        for line in r.stdout.splitlines():
            p = line.split(",")
            try:
                t = float(p[0]) + (float(p[1]) if len(p) > 1 and p[1] not in ("", "N/A") else 0.0)
            except ValueError:
                continue
            end = t if end is None or t > end else end
        if end:
            return end
    return None

def length(path):
    """Returns (seconds or None, how it was found or why it failed)."""
    r = probe(["-show_entries", "format=duration", "-of", "csv=p=0", path])
    if r.returncode != 0:
        return None, (r.stderr.strip().splitlines() or ["ffprobe could not read the file"])[-1]
    v = r.stdout.strip()
    end = last_packet(path)
    if v and v != "N/A":
        dur = float(v)
        if end is None or end < 0.9 * dur:
            return None, (f"truncated: the header says {dur:.1f} s but the data ends at "
                          f"{(end or 0):.1f} s; measure the original file")
        return dur, "container"
    return (end, "last packet") if end else (None, "no duration and no packets")

def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--free", type=float, help="free space on the drive in GB (decimal, as the drive box says)")
    ap.add_argument("files", nargs="+")
    a = ap.parse_args()
    if not shutil.which("ffprobe"):
        print("ffprobe not found: install FFmpeg (it includes ffprobe) and make sure ffprobe is on your PATH")
        sys.exit(1)
    bad = 0
    for f in a.files:
        if not os.path.isfile(f) or os.path.getsize(f) == 0:
            print(f"{f}: missing or empty"); bad = 1; continue
        size = os.path.getsize(f)
        dur, how = length(f)
        if not dur:
            print(f"{f}: {size:,} bytes, length unknown ({how})"); bad = 1; continue
        bps = size / dur
        line = (f"{f}: {size:,} bytes in {dur:.1f} s ({how}) = {bps * 8 / 1000:,.0f} kbps, "
                f"{bps * 60 / 1e6:.1f} MB/min, {bps * 3600 / 1e9:.2f} GB/h ({bps * 3600 / 2**30:.2f} GiB/h)")
        if a.free is not None:
            line += f", {a.free * 1e9 / bps / 3600:.1f} h fit in {a.free:g} GB"
        if dur < 60:
            line += f" (warning: only {dur:.1f} s; record at least 60 s, a very short test overstates GB per hour)"
        print(line)
    sys.exit(bad)

if __name__ == "__main__":
    main()
