File size: 23,029 Bytes
14c58d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""Stage 3 (pass 2) - one delivery window at full frame rate:
pose every frame -> pick the bowler -> refine release -> foot contacts, run-up,
follow-through -> 2D posture -> ball track, bounce, bat contact -> QC ->
browser-playable clips, keyframes, a clean calibration frame and the bowler pose."""
import shutil
import subprocess
from pathlib import Path
from collections import defaultdict
from datetime import datetime, timezone

import cv2
import numpy as np

from common import EVENT_NAMES, absp, now_iso, prov, r4, rel, write_json
from events import (OPP, SIDES, SKELETON, IoUTracker, find_batter_trigger, find_bfc, find_bounce, find_contact, find_ffc, find_shot_end,
                    find_followthrough_end, find_releases, find_runup_start, front_leg_label, link_ball,
                    posture_features, torso_length, wrist_height, _speed)

RED, WHITE, GREY, YELLOW, GREEN = (52, 48, 196), (245, 245, 245), (170, 170, 170), (40, 210, 250), (90, 170, 60)


def ffmpeg_ok():
    return shutil.which("ffmpeg") is not None


_ENC = None


def h264_args():
    """libx264 if available (apt ffmpeg), else openh264 (some conda builds).
    Both give H.264 that browsers play; mpeg4 is a last resort that may not."""
    global _ENC
    if _ENC is None:
        out = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True).stdout
        if " libx264 " in out:
            _ENC = ["-c:v", "libx264", "-preset", "veryfast", "-crf", "22"]
        elif " libopenh264 " in out:
            _ENC = ["-c:v", "libopenh264", "-b:v", "4M"]
        else:
            print("  ! no H.264 encoder in ffmpeg - clips may not play in the browser")
            _ENC = ["-c:v", "mpeg4", "-q:v", "3"]
    return _ENC


class H264Writer:
    """Pipes BGR frames into ffmpeg -> H.264 MP4 that every browser can play."""

    def __init__(self, path, w, h, fps):
        self.p = subprocess.Popen(
            ["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "bgr24",
             "-s", f"{w}x{h}", "-r", f"{fps}", "-i", "-", "-an", "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
             *h264_args(), "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(path)], stdin=subprocess.PIPE)

    def write(self, img):
        self.p.stdin.write(np.ascontiguousarray(img).tobytes())

    def close(self):
        self.p.stdin.close()
        self.p.wait()


def export_clip(src_path, start_s, n_frames, out):
    subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-ss", f"{start_s:.3f}", "-i", str(src_path),
                    "-frames:v", str(n_frames), "-map", "0:v:0", "-map", "0:a:0?", "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
                    *h264_args(), "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "96k", "-shortest",
                    "-movflags", "+faststart", str(out)], check=True)


def mux_audio(video_only, audio_src, out):
    """Copy the clip's sound onto the annotated video (frames were piped in silently)."""
    r = subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(video_only), "-i", str(audio_src),
                        "-map", "0:v:0", "-map", "1:a:0?", "-c", "copy", "-shortest", "-movflags", "+faststart", str(out)])
    if r.returncode == 0:
        Path(video_only).unlink(missing_ok=True)
    else:
        Path(video_only).replace(out)


def _draw_person(img, k, color, width, arm=None):
    for a, b in SKELETON:
        if k[a, 2] > 0.3 and k[b, 2] > 0.3:
            c = RED if arm and (a, b) in arm else color
            cv2.line(img, (int(k[a, 0]), int(k[a, 1])), (int(k[b, 0]), int(k[b, 1])), c,
                     width + (1 if c == RED else 0), cv2.LINE_AA)
    for i in range(5, 17):
        if k[i, 2] > 0.3:
            cv2.circle(img, (int(k[i, 0]), int(k[i, 1])), max(2, width), color, -1, cv2.LINE_AA)


def _label(img, text, y, color):
    s = max(0.5, img.shape[0] / 720 * 0.8)
    (tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, s, 2)
    cv2.rectangle(img, (10, y - th - 8), (22 + tw, y + 6), (20, 30, 24), -1)
    cv2.putText(img, text, (16, y), cv2.FONT_HERSHEY_SIMPLEX, s, color, 2, cv2.LINE_AA)


def _ev(t, t0, fi, conf, source_type, version, parent, **extra):
    return {"t_clip": round(t - t0, 3), "t_video": round(t, 3), "frame": int(fi),
            "confidence": round(float(conf), 3), **extra,
            "provenance": prov(source_type, version, conf, parent)}


def analyze_window(src, win, delivery_id, cfg, vision, out_dir):
    p2 = cfg["pass2"]
    fps, ts = src["fps"], src["time_scale"]
    imgsz = src.get("pose_imgsz") or p2["pose_imgsz"]
    f0, f1 = int(round(win["start_s"] * fps)), int(round(win["end_s"] * fps))
    t_hint = win["release_t_pass1"]
    ball_from, ball_to = t_hint - 0.1 * ts, t_hint + p2["ball_track_s"] * ts
    ver = cfg["project"]["pipeline_version"]
    pose_v = f"{vision.versions['pose']}+events_v{ver}"

    # ---------- pass A: inference ----------
    cap = cv2.VideoCapture(str(absp(src["path"])))
    cap.set(cv2.CAP_PROP_POS_FRAMES, f0)
    tracker = IoUTracker()
    frames, sharp, bright = [], [], []
    for fi in range(f0, f1 + 1):
        ok, img = cap.read()
        if not ok:
            break
        t = fi / fps
        persons = vision.pose(img, imgsz=imgsz, conf=cfg["pass1"]["pose_conf"])
        ids = tracker.update([p["box"] for p in persons])
        balls = vision.balls(img, imgsz=p2["ball_imgsz"], conf=p2["ball_conf"]) \
            if ball_from <= t <= ball_to else []
        bats = vision.bats(img) if hasattr(vision, "bats") and t_hint - 0.8 * ts <= t <= ball_to else []
        if (fi - f0) % 10 == 0:
            g = cv2.cvtColor(cv2.resize(img, (640, int(640 * img.shape[0] / img.shape[1]))), cv2.COLOR_BGR2GRAY)
            sharp.append(cv2.Laplacian(g, cv2.CV_64F).var()); bright.append(g.mean())
        frames.append({"fi": fi, "t": t, "persons": [dict(p, id=i) for i, p in zip(ids, persons)], "balls": balls,
                       "bats": bats})
    cap.release()
    n = len(frames)
    t0 = frames[0]["t"] if n else win["start_s"]
    exp = cfg.get("_experiment", {})
    m = {"delivery_id": delivery_id, "source_id": src["source_id"], "session_id": src["session_id"],
         "experiment_id": exp.get("experiment_id"), "protocol_version": exp.get("protocol_version"),
         "category": src["category"], "title": src["title"], "view_description": src["view_description"],
         "window": {"start_s": win["start_s"], "end_s": win["end_s"], "frames": n, "fps": fps,
                    "first_frame": f0, "duration_video_s": round(n / fps, 3),
                    "duration_real_s": round(n / fps / ts, 3), "time_scale": ts,
                    "time_scale_verified": src["time_scale_verified"]},
         "pass1": {k: win[k] for k in ("release_t_pass1", "score_pass1", "bowling_arm")}}

    # ---------- bowler = person overlapping the pass-1 bowler box at release ----------
    i_ref = int(np.argmin([abs(f["t"] - t_hint) for f in frames])) if n else 0
    bowler_id, best = None, 0.0
    for p in (frames[i_ref]["persons"] if n else []):
        sc = IoUTracker.iou(p["box"], win["bowler_box"])
        if sc > best:
            best, bowler_id = sc, p["id"]
    rows = [(j, f["t"], p["kpts"]) for j, f in enumerate(frames) for p in f["persons"] if p["id"] == bowler_id]
    reasons, status = [], "pass"
    events, posture, ball_info, series = {}, {}, {"points": [], "detected_frames": 0}, {}
    side = win["bowling_arm"]
    out_dir.mkdir(parents=True, exist_ok=True)
    if len(rows) < 5:
        status, reasons = "fail", ["bowler not tracked through the window"]
    else:
        fidx = np.array([r[0] for r in rows]); bt = np.array([r[1] for r in rows]); bk = np.stack([r[2] for r in rows])
        tl = torso_length(bk)
        FI = lambda i: frames[int(fidx[i])]["fi"]
        span = lambda a, b: f"pose:bowler frames {FI(a)}-{FI(b)}"
        cands = [c for c in find_releases(bt, bk, ts, cfg["release"]) if abs(c["t"] - t_hint) <= 0.3 * ts]
        if cands:
            rc = max(cands, key=lambda c: c["score"]); side = rc["side"]; i_rel = rc["i"]; refined = True
        else:
            i_rel = int(np.argmin(np.abs(bt - t_hint))); refined = False
            rc = {"score": win["score_pass1"] * 0.6}
            reasons.append("release not re-confirmed at full frame rate")
        events["ball_release"] = _ev(bt[i_rel], t0, FI(i_rel), rc["score"], "model", pose_v,
                                     span(max(0, i_rel - 5), min(len(bt) - 1, i_rel + 5)), refined=refined)
        ffc = find_ffc(bt, bk, i_rel, side, ts, cfg["ffc"])
        i_anchor = i_rel
        if ffc:
            events["front_foot_contact"] = _ev(ffc["t"], t0, FI(ffc["i"]), min(0.9, ffc["ankle_conf"]) * 0.8,
                                               "model", pose_v, span(ffc["i"], i_rel))
            bfc = find_bfc(bt, bk, ffc["i"], side, ts, cfg["ffc"])
            if bfc:
                events["back_foot_contact"] = _ev(bfc["t"], t0, FI(bfc["i"]), min(0.9, bfc["ankle_conf"]) * 0.7,
                                                  "model", pose_v, span(bfc["i"], ffc["i"]))
                i_anchor = bfc["i"]
            else:
                i_anchor = ffc["i"]
        else:
            reasons.append("front-foot contact not found")
        ru = find_runup_start(bt, bk, i_anchor, ts, cfg["ffc"])
        if ru:
            events["run_up_start"] = _ev(ru["t"], t0, FI(ru["i"]), ru["confidence"], "model", pose_v,
                                         span(ru["i"], i_anchor), starts_before_clip=ru["starts_before_clip"])
        ft = find_followthrough_end(bt, bk, i_rel, side, ts, cfg["ffc"])
        if ft:
            events["followthrough_end"] = _ev(ft["t"], t0, FI(ft["i"]), ft["confidence"], "model", pose_v,
                                              span(i_rel, ft["i"]))
        posture = posture_features(bk, i_rel, ffc["i"] if ffc else None, side)
        kf = posture.get("front_knee_angle_ffc_deg", {}).get("value")
        kr = posture.get("front_knee_angle_release_deg", {}).get("value")
        posture["front_leg"] = {"value": front_leg_label(kf, kr),
                                "confidence": round(min(posture.get("front_knee_angle_ffc_deg", {}).get("confidence", 0),
                                                        posture["front_knee_angle_release_deg"]["confidence"]), 3),
                                "space": "image_2d"}
        for k_, v_ in posture.items():
            v_["provenance"] = prov("deterministic_rule" if k_ == "front_leg" else "model",
                                    f"posture_v{ver}", v_.get("confidence"), span(i_rel, i_rel))
        # ---------- ball, bounce, batter, bat contact ----------
        wr = bk[i_rel, SIDES[side]["wr"], :2]
        seq = [(f["t"], f["balls"]) for f in frames if f["t"] >= bt[i_rel] - 0.02 * ts]
        track = link_ball(seq, wr, tl if np.isfinite(tl) else 50, ts)
        ball_v = f"{vision.versions['ball']}+link_v{ver}"
        ball_info = {"points": [{"t_clip": round(q["t"] - t0, 3), "x": round(q["x"], 1), "y": round(q["y"], 1),
                                 "conf": round(q["conf"], 3)} for q in track],
                     "detected_frames": sum(1 for f in frames if f["balls"]),
                     "provenance": prov("model", ball_v, None, "detector per frame + linking")}
        bounce = find_bounce(track)
        frame_at = lambda tt: min(frames, key=lambda f: abs(f["t"] - tt))
        if bounce:
            events["ball_bounce"] = _ev(bounce["t"], t0, frame_at(bounce["t"])["fi"], bounce["confidence"],
                                        "model", ball_v, f"ball_track points {max(0, bounce['i'] - 2)}-{bounce['i'] + 2}",
                                        turn_deg=bounce["turn_deg"], xy_px=[round(bounce["x"], 1), round(bounce["y"], 1)])
        # ---------- batter: identify, then trigger / bat contact / shot follow-through ----------
        t_rel = float(bt[i_rel])
        win_frames = [f for f in frames if f["t"] >= t_rel - 0.8 * ts]
        cand = {}
        for f in win_frames:
            for p in f["persons"]:
                if p["id"] != bowler_id:
                    cand.setdefault(p["id"], []).append((f["t"], p))
        cand = {k_: v for k_, v in cand.items() if len(v) >= 0.4 * max(1, len(win_frames))}
        after_pts = [q for q in track if q["t"] > (bounce["t"] if bounce else t_rel)]
        batter_id, how = None, None
        ctr = lambda bx: ((bx[0] + bx[2]) / 2, (bx[1] + bx[3]) / 2)
        if cand and after_pts:
            def _d(v):
                ds = [min(np.hypot(ctr(p["box"])[0] - q["x"], ctr(p["box"])[1] - q["y"]) for q in after_pts)
                      for tt, p in v if tt >= after_pts[0]["t"]]
                return float(np.median(ds)) if ds else 1e9
            batter_id = min(cand, key=lambda k_: _d(cand[k_])); how = "closest to the ball path"
        elif cand and src["category"] != "batter_pov":
            bwx, bwb = (win["bowler_box"][0] + win["bowler_box"][2]) / 2, win["bowler_box"][3]
            def _s(v):
                xs = [ctr(p["box"])[0] for _, p in v]; feet = [p["box"][3] for _, p in v]
                return abs(float(np.median(xs)) - bwx) + (0 if np.median(feet) < bwb else 1e6)
            k_best = min(cand, key=lambda k_: _s(cand[k_]))
            if _s(cand[k_best]) < 1e6:
                batter_id, how = k_best, "in line with the bowler, further down the pitch (no ball track)"
        m["batter"] = {"track_found": batter_id is not None, "identified_by": how}
        if batter_id is not None:
            rows_b = [(f["fi"], f["t"], p["kpts"], p["box"]) for f in frames for p in f["persons"] if p["id"] == batter_id]
            btt = np.array([r[1] for r in rows_b]); bkk = np.stack([r[2] for r in rows_b]); bfi = [r[0] for r in rows_b]
            box_at = lambda tt: min(rows_b, key=lambda r: abs(r[1] - tt))[3]
            bv = f"{vision.versions['pose']}+batter_v{ver}"
            spanb = lambda a_, b_: f"pose:batter frames {bfi[a_]}-{bfi[b_]}"
            bcfg = cfg.get("batter", {})
            trg = find_batter_trigger(btt, bkk, t_rel, ts, bcfg)
            if trg:
                events["batter_trigger_start"] = _ev(trg["t"], t0, bfi[trg["i"]], trg["confidence"], "model", bv,
                                                     spanb(max(0, trg["i"] - 3), trg["i"]))
            if bounce:
                ct = find_contact(track, bounce["i"], box_at)
                if ct:
                    events["bat_ball_contact"] = _ev(ct["t"], t0, frame_at(ct["t"])["fi"], ct["confidence"], "model",
                                                     ball_v, f"ball_track points {ct['i'] - 2}-{ct['i'] + 2} + batter box",
                                                     turn_deg=ct["turn_deg"], xy_px=[round(ct["x"], 1), round(ct["y"], 1)])
            t_after = events.get("bat_ball_contact", {}).get("t_video") or \
                (bounce["t"] + 0.1 * ts if bounce else t_rel + 0.5 * ts)
            se = find_shot_end(btt, bkk, t_after, ts, bcfg)
            if se and se["t"] > t_after:
                events["shot_followthrough_end"] = _ev(se["t"], t0, bfi[se["i"]], se["confidence"], "model", bv,
                                                       spanb(max(0, se["i"] - 5), se["i"]))
            m["batter"]["keypoint_conf"] = round(float(np.mean(bkk[:, 5:, 2])), 3)
            extra = {}
            if any(f["bats"] for f in frames):                       # detected bat nearest the batter's hands
                byfi = {f["fi"]: f["bats"] for f in frames}
                bp = np.full((len(bfi), 2, 2), np.nan); bc = np.zeros(len(bfi))
                for j, fi_ in enumerate(bfi):
                    hands = bkk[j, [9, 10], :2].mean(axis=0)
                    cands = byfi.get(fi_) or []
                    if cands:
                        c = min(cands, key=lambda b: np.hypot(*(np.array(b["handle"]) - hands)))
                        bp[j] = [c["handle"], c["toe"]]; bc[j] = c["conf"]
                extra = {"bat_pts": bp.astype(np.float32), "bat_conf": bc.astype(np.float32)}
            np.savez_compressed(out_dir / "batter_pose.npz", t=btt, frames=np.array(bfi), kpts=bkk.astype(np.float32), **extra)
        # ---------- bat contact from sound (real-time video only) ----------
        acfg = cfg.get("audio", {})
        if acfg.get("contact_from_sound", True) and ts == 1.0:
            from audio import contact_from_sound, load_audio
            a = load_audio(absp(src["path"]), t0, n / fps)
            lo = (bounce["t"] if bounce else t_rel + 0.25) - t0
            snd = contact_from_sound(a, lo, t_rel + 1.2 - t0, acfg.get("min_onset_ratio", 6.0)) if a is not None else None
            m["audio"] = {"present": a is not None, "contact_onset": snd}
            if snd:
                tv = t0 + snd["t"]
                vc = events.get("bat_ball_contact")
                if vc and abs(vc["t_video"] - tv) <= 3 / fps:
                    vc["audio_t_clip"] = round(snd["t"], 3)
                    vc["confidence"] = round(min(0.95, vc["confidence"] + 0.3), 3)
                    vc["provenance"]["source_version"] += "+audio_onset"
                elif not vc and batter_id is not None:
                    events["bat_ball_contact"] = _ev(tv, t0, int(round(tv * fps)), snd["confidence"], "model",
                                                     f"audio_onset_v{ver}", f"audio 2-8 kHz onset, strength {snd['strength']}",
                                                     audio_t_clip=round(snd["t"], 3), from_sound=True)
        if len(track) < 3 and src["category"] != "slowmo_action":
            reasons.append("ball not tracked after release")
        h = wrist_height(bk, side, tl)
        an = SIDES[OPP[side]]["an"]
        sp = _speed(bt / ts, bk[:, an, :2], bk[:, an, 2] > 0.3, tl, incoming_only=True)
        step = max(1, len(bt) // 150)
        series = {"t_clip": [round(x - t0, 3) for x in bt[::step]],
                  "wrist_height": [r4(x) for x in h[::step]], "front_ankle_speed": [r4(x) for x in sp[::step]]}
        kc = float(np.mean(bk[max(0, i_rel - 3):i_rel + 4, 5:, 2]))
        if kc < 0.3:
            status = "fail"; reasons.append(f"bowler keypoints unreliable ({kc:.2f})")
        elif kc < 0.5:
            reasons.append(f"low keypoint confidence ({kc:.2f})")
        m["bowler"] = {"track_found": True, "bowling_arm": side, "keypoint_conf": round(kc, 3),
                       "torso_px": r4(tl), "frames_tracked": len(rows),
                       "provenance": prov("model", pose_v, kc, "pose:bowler track")}
        np.savez_compressed(out_dir / "bowler_pose.npz", t=bt, frames=np.array([FI(i) for i in range(len(bt))]),
                            kpts=bk.astype(np.float32), side=np.array(side))
    if not m.get("bowler"):
        m["bowler"] = {"track_found": False, "bowling_arm": None}
    m.setdefault("batter", {"track_found": False})
    sh = float(np.median(sharp)) if sharp else 0.0
    br = float(np.median(bright)) if bright else 0.0
    if sh < 30: reasons.append(f"blurry ({sh:.0f})")
    if not 35 <= br <= 225: reasons.append(f"exposure ({br:.0f})")
    if status != "fail" and reasons:
        status = "warn"
    m["events"], m["posture"], m["ball"], m["series"] = events, posture, ball_info, series
    m["qc"] = {"status": status, "reasons": reasons, "sharpness": round(sh, 1), "mean_brightness": round(br, 1),
               "provenance": prov("deterministic_rule", f"qc_v{ver}")}

    # ---------- pass B: clips, keyframes, calibration frame ----------
    media = {"keyframes": {}}
    if ffmpeg_ok() and n:
        try:
            export_clip(absp(src["path"]), f0 / fps, n, out_dir / "clip.mp4")
            media["clip"] = rel(out_dir / "clip.mp4")
        except subprocess.CalledProcessError as e:
            m["qc"]["reasons"].append(f"clip export failed ({e.returncode})")
        ev_at = {}
        for k_, e in events.items():
            ev_at.setdefault(e["frame"], k_)
        calib_fi = events.get("ball_release", {}).get("frame", f0)
        cap = cv2.VideoCapture(str(absp(src["path"])))
        cap.set(cv2.CAP_PROP_POS_FRAMES, f0)
        writer, trail, banner = None, [], (None, -1)
        bpts = {round(p["t_clip"], 3): p for p in ball_info["points"]}
        for f in frames:
            ok, img = cap.read()
            if not ok:
                break
            if f["fi"] == calib_fi:
                cv2.imwrite(str(out_dir / "calib_frame.jpg"), img, [cv2.IMWRITE_JPEG_QUALITY, 90])
                media["calib_frame"] = rel(out_dir / "calib_frame.jpg")
                media["calib_frame_size"] = [img.shape[1], img.shape[0]]
            if writer is None:
                writer = H264Writer(out_dir / "annotated_v.mp4", img.shape[1], img.shape[0], fps)
            tc = f["t"] - t0
            for p in f["persons"]:
                if p["id"] != bowler_id:
                    _draw_person(img, p["kpts"], GREY, 1)
            for p in f["persons"]:
                if p["id"] == bowler_id:
                    s_ = SIDES[side]
                    _draw_person(img, p["kpts"], WHITE, 2, arm={(s_["sh"], s_["el"]), (s_["el"], s_["wr"])})
            bp = bpts.get(round(tc, 3))
            if bp:
                trail.append((int(bp["x"]), int(bp["y"])))
            for a, b in zip(trail[:-1], trail[1:]):
                cv2.line(img, a, b, YELLOW, 2, cv2.LINE_AA)
            if trail:
                cv2.circle(img, trail[-1], 6, YELLOW, 2, cv2.LINE_AA)
            if f["fi"] in ev_at:
                banner = (EVENT_NAMES[ev_at[f["fi"]]] + f"  {tc:.2f}s", f["fi"] + int(0.35 * fps * ts))
            if banner[0] and f["fi"] <= banner[1]:
                _label(img, banner[0], 40, YELLOW if "Bounce" in banner[0] or "Bat" in banner[0] else WHITE)
            _label(img, f"{delivery_id}   t={tc:5.2f}s", img.shape[0] - 14, GREY)
            for k_, e in events.items():
                if e["frame"] == f["fi"]:
                    cv2.imwrite(str(out_dir / f"{k_}.jpg"), img, [cv2.IMWRITE_JPEG_QUALITY, 85])
                    media["keyframes"][k_] = rel(out_dir / f"{k_}.jpg")
            writer.write(img)
        cap.release()
        if writer:
            writer.close()
            if (out_dir / "clip.mp4").exists():
                mux_audio(out_dir / "annotated_v.mp4", out_dir / "clip.mp4", out_dir / "annotated.mp4")
            else:
                (out_dir / "annotated_v.mp4").replace(out_dir / "annotated.mp4")
            media["annotated"] = rel(out_dir / "annotated.mp4")
    elif not ffmpeg_ok():
        m["qc"]["reasons"].append("ffmpeg missing - clips not exported")
    media["thumbnail"] = media["keyframes"].get("ball_release") or next(iter(media["keyframes"].values()), None)
    m["media"] = media
    m["provenance"] = {"pipeline_version": ver, "models": vision.versions, "created_at": now_iso(),
                       "measurement_space": "image_2d", "config_hash": cfg.get("_config_hash")}
    write_json(out_dir / "measurements.json", m)
    return m