File size: 9,470 Bytes
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4800905
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4800905
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Source-timed decoding. Container FPS is never presumed to be the capture clock."""
from fractions import Fraction
from pathlib import Path
import hashlib
import json
import math
import shutil
import subprocess
import numpy as np
from .contracts import FrameTiming, json_safe
from .storage import sha256_file

def validate_metadata(metadata):
    allowed = {"player_id", "session_id", "handedness", "height_m", "bat_length_m",
               "age", "experience_level", "consent", "timing", "rotation_degrees",
               "calibration", "camera_stability", "swing_task", "intended_use", "audio", "event_context", "bat_geometry", "uncertainty"}
    extra = set(metadata) - allowed
    if extra:
        raise ValueError(f"Unsupported metadata fields (avoid credentials): {sorted(extra)}")
    if metadata.get("handedness") not in {None, "left", "right"}:
        raise ValueError("handedness must be left or right")
    for field in ("height_m", "bat_length_m"):
        v = metadata.get(field)
        if v is not None and (not isinstance(v, (int, float)) or not math.isfinite(v) or v <= 0):
            raise ValueError(f"{field} must be positive and finite")
    angle = metadata.get("rotation_degrees", 0)
    if angle not in {0, 90, 180, 270}:
        raise ValueError("rotation_degrees must be 0, 90, 180 or 270 clockwise")
    timing = metadata.get("timing", {"kind": "unknown"})
    if timing.get("kind") not in {"unknown", "unretimed", "constant_slowdown", "explicit"}:
        raise ValueError("Unsupported timing kind")
    if timing.get("kind") != "unknown" and not timing.get("source"):
        raise ValueError("Known physical timing requires a documented source")
    if timing.get("kind") == "constant_slowdown":
        factor = timing.get("factor")
        if not isinstance(factor, (int, float)) or not math.isfinite(factor) or factor <= 0:
            raise ValueError("slowdown factor must be positive and finite")
        if timing.get("all_captured_frames_retained") is not True:
            raise ValueError("Constant slowdown requires all captured frames retained")
    if timing.get("kind") == "explicit":
        values = timing.get("physical_times_s", [])
        if not values or any(not isinstance(x, (int, float)) or not math.isfinite(x) for x in values):
            raise ValueError("Explicit physical times must be finite")
        if any(b <= a for a, b in zip(values, values[1:])):
            raise ValueError("Explicit physical times must increase strictly")
    if metadata.get("camera_stability") not in {None, "unknown", "fixed_verified", "moving"}:
        raise ValueError("Invalid camera stability state")
    return metadata

def physical_time(playback, index, timing):
    kind = timing.get("kind", "unknown")
    if kind == "explicit":
        values = timing["physical_times_s"]
        if index >= len(values):
            raise ValueError("Physical-time map is shorter than the decoded video")
        return float(values[index])
    if playback is None or kind == "unknown":
        return None
    if kind == "unretimed":
        return playback
    return playback / timing["factor"]

def orientation_matrix(width, height, rotation):
    return {
        0: np.eye(3),
        90: np.array([[0, -1, height-1], [1, 0, 0], [0, 0, 1]]),
        180: np.array([[-1, 0, width-1], [0, -1, height-1], [0, 0, 1]]),
        270: np.array([[0, 1, 0], [-1, 0, width-1], [0, 0, 1]]),
    }[rotation].astype(float)

def probe(path):
    if not shutil.which("ffprobe"):
        return {"status": "unavailable", "reason": "ffprobe_not_installed"}
    result = subprocess.run(["ffprobe", "-v", "error", "-protocol_whitelist", "file,pipe", "-show_streams", "-show_format",
                             "-of", "json", str(path)], capture_output=True, text=True)
    if result.returncode:
        return {"status": "failed", "reason": "ffprobe_failed"}
    value = json.loads(result.stdout)
    # Avoid arbitrary file tags in exported manifests.
    return {"status": "ready", "streams": [{k: s[k] for k in
            ("index", "codec_name", "codec_type", "width", "height", "time_base",
             "r_frame_rate", "avg_frame_rate", "duration", "side_data_list") if k in s}
            for s in value.get("streams", [])]}

def iter_frames(path, rotation=0, max_pixels=None, *, include_duration=False):
    import av
    import cv2
    # Uploaded recordings must not trigger network requests through a playlist.
    with av.open(str(path), options={"protocol_whitelist": "file,pipe"}) as container:
        if not container.streams.video:
            raise ValueError("No video stream")
        stream = container.streams.video[0]
        if max_pixels is not None and stream.width * stream.height > max_pixels:
            raise ValueError("Video exceeds the configured pixel limit")
        for index, frame in enumerate(container.decode(stream)):
            if max_pixels is not None and frame.width * frame.height > max_pixels:
                raise ValueError("Video exceeds the configured pixel limit")
            image = frame.to_ndarray(format="bgr24")
            if rotation:
                image = np.ascontiguousarray(np.rot90(image, -(rotation // 90)))
            values = (index, frame.pts, frame.time_base or stream.time_base, image)
            yield (*values, frame.duration) if include_duration else values

def ingest(path, metadata, *, max_frames=None, max_pixels=None, max_duration_s=None, progress=None):
    import cv2
    validate_metadata(metadata)
    timings, quality = [], []
    prior_time, prior_hash = None, None
    rotation = metadata.get("rotation_degrees", 0)
    probe_result = probe(path)
    if "rotation_degrees" not in metadata and probe_result.get("status") == "ready":
        for s in probe_result["streams"]:
            if s.get("codec_type") == "video":
                for side in s.get("side_data_list", []):
                    if "rotation" in side:
                        rotation = int(-side["rotation"]) % 360
    if rotation not in {0, 90, 180, 270}:
        raise ValueError("Non-right-angle orientation needs an explicit tested transform")
    raw_shape = None
    first_time = None
    for index, pts, base, image in iter_frames(path, rotation, max_pixels=max_pixels):
        if max_frames is not None and index >= max_frames:
            raise ValueError("Video exceeds the configured frame limit")
        raw_shape = (image.shape[1], image.shape[0]) if not rotation % 180 else (image.shape[0], image.shape[1])
        playback = float(pts * base) if pts is not None and base else None
        if first_time is None and playback is not None:
            first_time = playback
        if (max_duration_s is not None and playback is not None and first_time is not None
                and playback - first_time > max_duration_s):
            raise ValueError("Video exceeds the configured duration limit")
        flags = []
        if playback is None:
            flags.append("missing_pts")
        elif prior_time is not None and playback <= prior_time:
            flags.append("duplicate_pts" if playback == prior_time else "nonmonotonic_pts")
        if playback is not None:
            prior_time = playback
        image_hash = hashlib.sha256(image.tobytes()).hexdigest()
        if image_hash == prior_hash:
            flags.append("duplicate_image")
        prior_hash = image_hash
        t = physical_time(playback, index, metadata.get("timing", {"kind": "unknown"}))
        timings.append(FrameTiming(index, pts, str(base) if base else None, playback,
                                   t, image.shape[1], image.shape[0], flags))
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        quality.append({"frame_id": index, "blur_laplacian_variance": float(cv2.Laplacian(gray, cv2.CV_64F).var()),
                        "mean_luminance": float(gray.mean())})
        if progress and (index + 1) % 64 == 0:
            progress(index + 1)
    if not timings:
        raise ValueError("No decodable video frames")
    timing_meta = metadata.get("timing", {"kind": "unknown"})
    if timing_meta.get("kind") == "explicit" and len(timing_meta["physical_times_s"]) != len(timings):
        raise ValueError("Physical-time map must match decoded frame count")
    intervals = [b.playback_s-a.playback_s for a, b in zip(timings, timings[1:])
                 if a.playback_s is not None and b.playback_s is not None and b.playback_s > a.playback_s]
    if intervals:
        nominal = float(np.median(intervals))
        for a, b in zip(timings, timings[1:]):
            if a.playback_s is not None and b.playback_s is not None and b.playback_s-a.playback_s > 1.5*nominal:
                b.flags.append("timestamp_gap_or_variable_cadence")
    return json_safe({"schema_version": "1.0", "input_sha256": sha256_file(path),
        "frame_count": len(timings), "frames": timings, "quality": quality,
        "metadata": metadata, "probe": probe_result, "rotation_degrees": rotation,
        "orientation_transform": orientation_matrix(*raw_shape, rotation),
        "coordinate_space": "oriented_image_pixels_x_right_y_down",
        "timing_source": timing_meta, "participant_consent_record": metadata.get("consent", "not_supplied"),
        "camera_stability": metadata.get("camera_stability", "unknown"),
        "physical_clock_known": all(t.physical_s is not None for t in timings),
        "resource_registry_ids": ["pyav", "opencv", "ffmpeg"]})