#!/usr/bin/env python3
"""measure.py geom <source.mp4> <watermarked.mp4>
Reads one frame (1 s in) of both files as 8-bit grey through ffmpeg, finds the box where they differ by more than 12 grey levels and prints
the box size, its four distances to the frame edges and the mean grey inside it for source and output. Standard library plus ffmpeg only.
Exit 2 on a missing or empty file, 3 when no difference is found."""
import subprocess, sys, os

def frame(path):
    if not os.path.isfile(path) or os.path.getsize(path) == 0:
        print("missing or empty file: " + path, file=sys.stderr); sys.exit(2)
    p = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", path], capture_output=True, text=True)
    try: w, h = map(int, p.stdout.strip().split(","))
    except ValueError: print("no video stream: " + path, file=sys.stderr); sys.exit(2)
    raw = subprocess.run(["ffmpeg", "-v", "error", "-ss", "1", "-i", path, "-frames:v", "1", "-pix_fmt", "gray", "-f", "rawvideo", "-"], capture_output=True).stdout
    if len(raw) != w * h: print("could not read a frame at 1 s: " + path, file=sys.stderr); sys.exit(2)
    return w, h, raw

def geom(src, out):
    w, h, a = frame(src); w2, h2, b = frame(out)
    if (w, h) != (w2, h2): print("sizes differ", file=sys.stderr); sys.exit(2)
    x0, y0, x1, y1 = w, h, -1, -1
    for y in range(h):
        ra, rb = a[y * w:(y + 1) * w], b[y * w:(y + 1) * w]
        if ra == rb: continue
        xs = [x for x in range(w) if abs(ra[x] - rb[x]) > 12]
        if xs:
            x0, x1 = min(x0, xs[0]), max(x1, xs[-1]); y0, y1 = min(y0, y), max(y1, y)
    if x1 < 0: print("no difference found"); sys.exit(3)
    n = (x1 - x0 + 1) * (y1 - y0 + 1)
    ms = sum(sum(a[y * w + x0:y * w + x1 + 1]) for y in range(y0, y1 + 1)) / n
    mo = sum(sum(b[y * w + x0:y * w + x1 + 1]) for y in range(y0, y1 + 1)) / n
    print(f"frame={w}x{h} box={x1-x0+1}x{y1-y0+1} left={x0} right={w-1-x1} top={y0} bottom={h-1-y1} mean_src={ms:.1f} mean_out={mo:.1f}")

if __name__ == "__main__" and len(sys.argv) == 4 and sys.argv[1] == "geom": geom(sys.argv[2], sys.argv[3])
else: print(__doc__); sys.exit(1)
