File size: 5,399 Bytes
2d55c63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python3
"""Measure frame-to-frame flicker in a short clip (NumPy + ffmpeg only).

Global flicker: the whole frame gets brighter/darker for a frame or two.
Local flicker:  one region (a lamp, a face, a wall) pulses while the rest is steady.
Both are measured inside shots only, so hard cuts don't count as flicker.

usage: python3 flicker.py clip.mp4 [more.mp4 ...] [--grid 4x6] [--json]
"""
import argparse, json, subprocess
import numpy as np

W, H = 180, 320            # 9:16 analysis size, gray
WIN = 9                    # trend window (frames) = the "slow" brightness

def frames(path):
    cmd = ["ffmpeg", "-v", "error", "-i", path, "-vf",
           f"scale={W}:{H}:flags=area,format=gray", "-f", "rawvideo", "-"]
    raw = subprocess.run(cmd, capture_output=True, check=True).stdout
    return np.frombuffer(raw, np.uint8).reshape(-1, H, W).astype(np.float32)

def fps_of(path):
    out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
                          "-show_entries", "stream=avg_frame_rate", "-of", "csv=p=0", path],
                         capture_output=True, text=True, check=True).stdout.strip()
    n, d = out.split("/")
    return float(n) / float(d)

def cuts(f):
    """Indices i where frame i starts a new shot.

    A cut is a *spike* in mean absolute frame difference: above max(12, 4x median)
    AND more than twice the difference on both neighbouring frame pairs. The spike
    rule keeps fast motion (a head turn raises several pairs in a row) from
    being counted as a cut.
    """
    mad = np.abs(np.diff(f, axis=0)).mean(axis=(1, 2))      # len n-1
    thr = max(12.0, 4 * float(np.median(mad)))
    out = []
    for i, v in enumerate(mad):
        prev = mad[i - 1] if i > 0 else 0.0
        nxt = mad[i + 1] if i + 1 < len(mad) else 0.0
        if v > thr and v > 2 * prev and v > 2 * nxt:
            out.append(i + 1)
    return out, mad

def detrend(x):
    """x minus its slow trend: what's left is the fast, frame-to-frame part.

    The trend is a 9-tap moving average with half-weight end taps. Those weights
    cancel a period-2 (every-other-frame) pulse and a period-4 pulse exactly, so
    the fastest flicker ends up fully in the residual instead of in the trend.
    (A moving *median* would hide an every-other-frame pulse completely.)
    """
    k = np.ones(WIN); k[0] = k[-1] = 0.5; k /= k.sum()
    pad = WIN // 2
    xp = np.pad(x, pad, mode="edge")
    return x - np.convolve(xp, k, mode="valid")

def lag1(x):
    """Lag-1 autocorrelation of a residual. Near -1 = strobing every other frame
    (true flicker); near 0 or positive = smoother change, usually motion."""
    x = x - x.mean()
    d = float((x * x).sum())
    return float((x[1:] * x[:-1]).sum() / d) if d > 0 else 0.0

def analyse(path, gy=6, gx=4):
    f = frames(path)
    fps = fps_of(path)
    cut_idx, mad = cuts(f)
    bounds = [0] + cut_idx + [len(f)]
    th, tw = H // gy, W // gx
    tiles = f[:, :th * gy, :tw * gx].reshape(len(f), gy, th, gx, tw).mean(axis=(2, 4))
    g_res, t_res, shots = [], [], []
    for a, b in zip(bounds[:-1], bounds[1:]):
        if b - a < WIN:                  # too short to separate slow from fast
            continue
        m = f[a:b].mean(axis=(1, 2))
        g = detrend(m)[2:-2]             # drop 2 frames each side of a cut
        t = np.stack([detrend(tiles[a:b, y, x]) for y in range(gy) for x in range(gx)], 1)[2:-2]
        g_res.append(g); t_res.append(t)
        tile_rms = np.sqrt((t ** 2).mean(axis=0))
        shots.append({"start_s": round(a / fps, 3), "end_s": round(b / fps, 3),
                      "global_rms": round(float(np.sqrt((g ** 2).mean())), 3),
                      "worst_tile_rms": round(float(tile_rms.max()), 3),
                      "worst_tile": int(tile_rms.argmax())})
    g_all = np.concatenate(g_res); t_all = np.concatenate(t_res)
    tile_rms = np.sqrt((t_all ** 2).mean(axis=0))
    wt = int(tile_rms.argmax())
    return {"clip": path.split("/")[-1][:12], "fps": round(fps, 3), "frames": len(f),
            "cuts_s": [round(i / fps, 3) for i in cut_idx],
            "global_rms": round(float(np.sqrt((g_all ** 2).mean())), 3),
            "global_p99": round(float(np.percentile(np.abs(g_all), 99)), 3),
            "median_tile_rms": round(float(np.median(tile_rms)), 3),
            "worst_tile_rms": round(float(tile_rms.max()), 3),
            "worst_tile": wt,
            "global_lag1": round(lag1(g_all), 2),
            "worst_tile_lag1": round(lag1(t_all[:, wt]), 2),
            "shots": shots}

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("clips", nargs="+")
    ap.add_argument("--grid", default="4x6", help="columns x rows of the tile grid")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    gx, gy = map(int, a.grid.split("x"))
    print(f"{'clip':12} {'fps':>5} {'cuts (s)':22} {'global':>7} {'p99':>6} {'tile med':>8} {'tile max':>8} {'lag1 g':>6} {'lag1 t':>6}")
    for c in a.clips:
        r = analyse(c, gy, gx)
        if a.json:
            print(json.dumps(r))
        cs = ",".join(f"{x:g}" for x in r["cuts_s"]) or "-"
        print(f"{r['clip']:12} {r['fps']:5.1f} {cs:22} {r['global_rms']:7.3f} {r['global_p99']:6.2f} "
              f"{r['median_tile_rms']:8.3f} {r['worst_tile_rms']:8.3f} {r['global_lag1']:6.2f} {r['worst_tile_lag1']:6.2f}")