#!/usr/bin/env python3
"""Print the time of the first video frame whose average brightness is above 230 (a white clap flash).
Usage: python3 flash.py <video>   Needs ffmpeg on the PATH."""
import os, re, subprocess, sys

if len(sys.argv) < 2:
    sys.exit("usage: python3 flash.py <video>")
path = sys.argv[1]
if not os.path.isfile(path):
    sys.exit("flash: file not found: " + path)
if os.path.getsize(path) == 0:
    sys.exit("flash: file is empty: " + path)
cmd = ["ffmpeg", "-v", "error", "-i", path, "-map", "0:v:0", "-vf",
       "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-", "-f", "null", "-"]
p = subprocess.run(cmd, capture_output=True, text=True)
if p.returncode != 0:
    sys.exit("flash: ffmpeg could not read video from " + path + ": " + p.stderr.strip()[:200])
t = None
for line in p.stdout.splitlines():
    m = re.search(r"pts_time:([0-9.]+)", line)
    if m:
        t = float(m.group(1))
        continue
    m = re.search(r"YAVG=([0-9.]+)", line)
    if m and t is not None and float(m.group(1)) > 230:
        print("%.3f s" % t)
        break
else:
    sys.exit("flash: no frame brighter than 230 found in " + path)
