#!/bin/bash
# Reference probe for SDTK_MARKETING_VIDEO_PROBE_CMD — an EXAMPLE, not a dependency.
#
# The kit computes none of this: it delegates, so it stays 0-dep and GPU-free. This script shows the
# current reference-probe contract using ffmpeg/ffprobe, which most boxes already have. Wire it up with:
#
#   export SDTK_MARKETING_VIDEO_PROBE_CMD='scripts/reference-probe.sh {file}'
#
# Prints: width height duration median_mafd frozen_ratio low_motion_ratio low_motion_run_s edge_density luma  (as key=value pairs).
# median_mafd / frozen_ratio come from scdet; edge_density from edgedetect; luma from signalstats.
# Both videos and still images work, so the same probe serves `video calibrate` on captures.
# Reference probe: prints key=value for the current reference-probe contract.
f="$1"
read W H FPS_RAW < <(ffprobe -v error -select_streams v:0 -show_entries stream=width,height,r_frame_rate \
  -of default=noprint_wrappers=1:nokey=1 "$f" | tr '\n' ' ')
D=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$f")
tmp=$(mktemp); ffmpeg -i "$f" -vf "scale=320:-1,scdet=s=1:t=0,metadata=print:file=$tmp" -an -f null - >/dev/null 2>&1
tmp2=$(mktemp); ffmpeg -i "$f" -vf "fps=2,scale=480:-1,edgedetect=low=0.1:high=0.3,signalstats,metadata=print:file=$tmp2" -an -f null - >/dev/null 2>&1
tmp3=$(mktemp); trap 'rm -f "$tmp" "$tmp2" "$tmp3"' EXIT
ffmpeg -i "$f" -vf "fps=2,scale=480:-1,signalstats,metadata=print:file=$tmp3" -an -f null - >/dev/null 2>&1
python3 - "$tmp" "$tmp2" "$tmp3" "$W" "$H" "$D" "$FPS_RAW" <<'PY'
import re,sys,statistics
from fractions import Fraction
mafd=[float(m.group(1)) for m in (re.match(r'lavfi\.scd\.mafd=([0-9.]+)',l.strip()) for l in open(sys.argv[1])) if m]
edge=[float(m.group(1)) for m in (re.match(r'lavfi\.signalstats\.YAVG=([0-9.]+)',l.strip()) for l in open(sys.argv[2])) if m]
luma=[float(m.group(1)) for m in (re.match(r'lavfi\.signalstats\.YAVG=([0-9.]+)',l.strip()) for l in open(sys.argv[3])) if m]
o=[f"width={sys.argv[4]}",f"height={sys.argv[5]}",f"duration={float(sys.argv[6]):.2f}"]
try:
    fps=float(Fraction(sys.argv[7]))
except (ValueError, ZeroDivisionError):
    fps=0
if fps <= 0:
    fps=1
if mafd:
    o.append(f"median_mafd={statistics.median(mafd):.3f}")
    o.append(f"frozen_ratio={sum(1 for x in mafd if x<0.5)/len(mafd):.3f}")
    low=[x<0.1 for x in mafd]
    runs=[]; start=None
    for i,is_low in enumerate(low):
        if is_low and start is None: start=i
        elif not is_low and start is not None: runs.append(i-start); start=None
    if start is not None: runs.append(len(low)-start)
    o.append(f"low_motion_ratio={sum(low)/len(low):.3f}")
    o.append(f"low_motion_run_s={(max(runs, default=0)/fps):.3f}")
if edge: o.append(f"edge_density={statistics.mean(edge):.2f}")
if luma: o.append(f"luma={statistics.mean(luma):.1f}")
print(" ".join(o))
PY
