File size: 16,041 Bytes
4800905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc21255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fractions import Fraction
import json

import av
import numpy as np
import pytest

from baseball_batting.ingest import ingest
from baseball_batting.storage import sha256_file, read_json, atomic_json
from baseball_batting.swing_clips import export_swing_clips, SwingsManifest


def ranges(*pairs):
    return {"reps": [{"rep": i+1, "start_frame": a, "end_frame": b,
                       "boundary_method": "caller_supplied"} for i, (a, b) in enumerate(pairs)]}


def decoded(path):
    with av.open(str(path)) as container:
        stream = container.streams.video[0]
        assert stream.codec_context.name == "h264"
        assert len(container.streams.audio) == 0
        return [(float(f.pts*f.time_base), f.to_ndarray(format="bgr24")) for f in container.decode(stream)]


def test_exact_multiple_cuts_preserve_variable_playback_cadence_and_rotation(video, tmp_path):
    capture = ingest(video, {"rotation_degrees": 90, "timing": {"kind": "constant_slowdown",
        "factor": 4, "all_captured_frames_retained": True, "source": "Generated clock"}})
    manifest = export_swing_clips(video, capture, ranges((1, 3), (4, 7)), tmp_path/"job")
    assert SwingsManifest.model_validate(manifest).model_dump(mode="json") == manifest
    assert read_json(tmp_path/"job/swings.json") == manifest
    source_pixels = decoded(video)
    for swing in manifest["swings"]:
        clip = swing["clip"]
        assert clip["status"] == "available", clip
        path = tmp_path/"job/swing-clips"/f"{swing['rep']}.mp4"
        frames = decoded(path)
        source = capture["frames"][swing["start_frame"]:swing["end_frame"]+1]
        expected_times = [f["playback_s"]-source[0]["playback_s"] for f in source]
        assert [t for t, _ in frames] == pytest.approx(expected_times, abs=2e-6)
        assert len(frames) == clip["frame_count"] == len(source)
        assert frames[0][1].shape[:2] == (160, 120)  # Upright, not container orientation.
        assert clip["width"] == 120 and clip["height"] == 160
        assert np.median(frames[0][1]) == pytest.approx(np.median(source_pixels[swing["start_frame"]][1]), abs=3)
        assert np.median(frames[-1][1]) == pytest.approx(np.median(source_pixels[swing["end_frame"]][1]), abs=3)
        assert clip["sha256"] == sha256_file(path)
        with av.open(str(path)) as container:
            stream = container.streams.video[0]
            assert float(stream.duration*stream.time_base) == pytest.approx(clip["duration_s"], abs=2e-6)
    # The first clip ends at the next sample's timestamp, not a hardcoded FPS.
    assert manifest["swings"][0]["clip"]["duration_s"] == pytest.approx(.150-.033, abs=2e-6)


def test_all_reps_export_in_one_source_pass_and_one_frame_clips_work(video, tmp_path, monkeypatch):
    import baseball_batting.swing_clips as module
    capture = ingest(video, {})
    original = module.iter_frames
    calls = []
    def once(*args, **kwargs):
        calls.append(args[0])
        yield from original(*args, **kwargs)
    monkeypatch.setattr(module, "iter_frames", once)
    manifest = export_swing_clips(video, capture, ranges(*[(i, i) for i in range(8)]), tmp_path/"job")
    assert len(calls) == 1
    assert all(s["clip"]["status"] == "available" and s["clip"]["frame_count"] == 1 for s in manifest["swings"])
    assert len(list((tmp_path/"job/swing-clips").glob("*.mp4"))) == 8


def test_no_fake_clips_missing_timestamps_and_isolated_encoding_failure(video, tmp_path, monkeypatch):
    import baseball_batting.swing_clips as module
    capture = ingest(video, {})
    assert export_swing_clips(video, capture, ranges(), tmp_path/"empty")["swings"] == []
    capture["frames"][0]["pts"] = None
    manifest = export_swing_clips(video, capture, ranges((0, 2), (3, 7)), tmp_path/"missing")
    assert manifest["swings"][0]["clip"]["reason_code"] == "source_timestamps_unavailable"
    assert manifest["swings"][1]["clip"]["status"] == "available"
    capture = ingest(video, {})
    original = module._Writer.write
    def fail_first(self, image, *args):
        if np.median(image) < 30:
            raise OSError("Simulated encoder failure")
        return original(self, image, *args)
    monkeypatch.setattr(module._Writer, "write", fail_first)
    manifest = export_swing_clips(video, capture, ranges((0, 2), (3, 7)), tmp_path/"failure")
    assert manifest["swings"][0]["clip"]["status"] == "unavailable"
    assert manifest["swings"][0]["clip"]["url"] is None
    assert manifest["swings"][1]["clip"]["status"] == "available"
    assert list((tmp_path/"failure/swing-clips").glob(".*tmp*")) == []


def test_odd_dimensions_are_padded_and_export_size_is_bounded(tmp_path):
    path = tmp_path/"odd.mp4"
    with av.open(str(path), "w") as out:
        stream = out.add_stream("libx264", rate=30)
        stream.width, stream.height, stream.pix_fmt = 1301, 733, "yuv444p"
        stream.time_base = stream.codec_context.time_base = Fraction(1, 30)
        for i in range(3):
            frame = av.VideoFrame.from_ndarray(np.full((733, 1301, 3), i*70, np.uint8), format="bgr24")
            frame.pts, frame.time_base = i, Fraction(1,30)
            for packet in stream.encode(frame): out.mux(packet)
        for packet in stream.encode(): out.mux(packet)
    manifest = export_swing_clips(path, ingest(path, {}), ranges((0, 2)), tmp_path/"odd-job")
    clip = manifest["swings"][0]["clip"]
    assert clip["status"] == "available", clip
    assert clip["width"] % 2 == clip["height"] % 2 == 0
    assert max(clip["width"], clip["height"]) <= 1280
    assert len(decoded(tmp_path/"odd-job/swing-clips/1.mp4")) == 3


@pytest.fixture
def clip_api(video, tmp_path):
    pytest.importorskip("fastapi")
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    from test_api import settings, fake_service, wait_until
    s = settings(tmp_path/"api")
    service = fake_service(s)
    with TestClient(create_app(s, service)) as client:
        wait_until(lambda: service.ready)
        identifier = service.store.create(8)
        job = service.job_directory(identifier)
        job.mkdir()
        manifest = export_swing_clips(video, ingest(video, {}), ranges((0, 3), (4, 7)), job)
        service.store.update(identifier, "completed", swings_hash=sha256_file(job/"swings.json"))
        yield client, service, job, manifest


def test_authenticated_playback_ranges_integrity_and_deletion(clip_api):
    from test_api import AUTH
    client, service, job, manifest = clip_api
    url = manifest["swings"][0]["clip"]["url"]
    data = (job/"swing-clips/1.mp4").read_bytes()
    assert client.get(url).status_code == 401
    assert client.head(url).status_code == 401
    listing = client.get(f"/v1/analyses/{job.name}/swings", headers=AUTH)
    assert listing.json() == manifest
    assert client.get(f"/v1/analyses/{job.name}", headers=AUTH).json()["swings_url"] == f"/v1/analyses/{job.name}/swings"
    full = client.get(url, headers=AUTH)
    assert full.status_code == 200 and full.content == data
    assert full.headers["content-type"] == "video/mp4" and full.headers["accept-ranges"] == "bytes"
    assert client.head(url, headers=AUTH).headers["content-length"] == str(len(data))
    for value, expected, start, end in [("bytes=0-99", data[:100], 0, 99),
            ("bytes=100-", data[100:], 100, len(data)-1), ("bytes=-50", data[-50:], len(data)-50, len(data)-1),
            ("bytes=0-9999999", data, 0, len(data)-1)]:
        response = client.get(url, headers={**AUTH, "Range": value})
        assert response.status_code == 206 and response.content == expected
        assert response.headers["content-range"] == f"bytes {start}-{end}/{len(data)}"
    for value in (f"bytes={len(data)}-", "bytes=5-3", "bytes=-0", "bytes=", "bytes=0-1,3-4"):
        response = client.get(url, headers={**AUTH, "Range": value})
        assert response.status_code == 416 and response.headers["content-range"] == f"bytes */{len(data)}"
    assert client.get(url, headers={**AUTH, "Range": "bytes=0-9", "If-Range": '"old"'}).status_code == 200
    assert client.get(url, headers={**AUTH, "Range": "bytes=0-9", "If-Range": full.headers["etag"]}).status_code == 206
    assert client.get(url.replace("/1/clip", "/99/clip"), headers=AUTH).status_code == 404
    (job/"swing-clips/1.mp4").write_bytes(b"tampered")
    assert client.get(url, headers=AUTH).status_code == 500
    # A broken clip does not block the other swing.
    assert client.get(manifest["swings"][1]["clip"]["url"], headers=AUTH).status_code == 200
    client.delete(f"/v1/analyses/{job.name}", headers=AUTH)
    assert not job.exists() and service.store.get(job.name)["swings_sha256"] is None
    assert client.get(url, headers=AUTH).status_code == 409


def test_unavailable_and_old_jobs_do_not_expose_broken_media_links(clip_api):
    from test_api import AUTH
    client, service, job, manifest = clip_api
    manifest["swings"][0]["clip"].update(status="unavailable", reason_code="clip_export_failed", url=None)
    atomic_json(job/"swings.json", manifest)
    service.store.update(job.name, "completed", swings_hash=sha256_file(job/"swings.json"))
    url = f"/v1/analyses/{job.name}/swings/1/clip"
    response = client.get(url, headers=AUTH)
    assert response.status_code == 409 and response.json()["detail"]["code"] == "clip_export_failed"
    service.store.update(job.name, "completed")
    assert client.get(f"/v1/analyses/{job.name}/swings", headers=AUTH).status_code == 409
    service.store.update(job.name, "completed", swings_hash="wrong")
    assert client.get(f"/v1/analyses/{job.name}/swings", headers=AUTH).status_code == 500


def test_already_open_clip_survives_job_deletion(clip_api):
    import asyncio
    from starlette.requests import Request
    from baseball_batting.media import open_verified_media, media_response
    client, service, job, manifest = clip_api
    clip = manifest["swings"][0]["clip"]
    data = (job/"swing-clips/1.mp4").read_bytes()
    with service.mutation_lock:
        handle, size = open_verified_media(job/"swing-clips/1.mp4", clip["sha256"], clip["size_bytes"])
    service.delete(job.name)
    response = media_response(Request({"type":"http", "method":"GET", "headers":[]}), handle, size, clip["sha256"])
    async def consume():
        return b"".join([block async for block in response.body_iterator])
    assert asyncio.run(consume()) == data
    assert handle.closed


def test_queue_keeps_clips_when_it_removes_the_original_upload(video, tmp_path):
    import shutil
    import sys
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    from baseball_batting.api_jobs import JobService
    from test_api import AUTH, settings, wait_until
    s = settings(tmp_path/"queue")
    def command(job):
        script = ("from pathlib import Path; from baseball_batting.ingest import ingest; "
            "from baseball_batting.swing_clips import export_swing_clips; "
            "from baseball_batting.storage import atomic_json; "
            f"job=Path({str(job)!r}); video=job/'input.mp4'; "
            "export_swing_clips(video,ingest(video,{}),{'reps':[{'rep':1,'start_frame':0,'end_frame':3},"
            "{'rep':2,'start_frame':4,'end_frame':7}]},job); atomic_json(job/'result.json',{})")
        return [sys.executable, "-c", script]
    service = JobService(s, command_factory=command, preflight_command=[sys.executable,"-c","pass"])
    identifier = service.store.create(8)
    job = service.job_directory(identifier)
    job.mkdir()
    shutil.copy2(video, job/"input.mp4")
    service.store.update(identifier, "queued")
    with TestClient(create_app(s, service)) as client:
        wait_until(lambda: service.store.get(identifier)["status"] == "completed")
        wait_until(lambda: not (job/"input.mp4").exists())
        assert service.store.get(identifier)["swings_sha256"] == sha256_file(job/"swings.json")
        listing = client.get(f"/v1/analyses/{identifier}/swings", headers=AUTH).json()
        assert len(listing["swings"]) == 2
        assert all(client.get(s["clip"]["url"], headers=AUTH).status_code == 200 for s in listing["swings"])


def test_published_swing_schema_matches_runtime():
    from pathlib import Path
    assert read_json(Path(__file__).resolve().parents[1]/"docs/swings.schema.json") == SwingsManifest.model_json_schema()


def test_encoded_api_clip_shows_colab_skeleton_feet_and_optional_3d(video, tmp_path):
    from copy import deepcopy
    from test_colab_2d import preview_result
    result = preview_result(video)
    points = result['pose_track']['frames']['kp'][2]
    points[0], points[5], points[7], points[9], points[15] = [50,70], [35,45], [65,65], [85,60], [50,80]
    result['pose_track']['frames']['kp_extra'] = [[None]*6 for _ in range(8)]
    result['pose_track']['frames']['kp_extra'][2][0] = [58,90]
    result['pose_track']['reps'][0]['events'] = {'contact': {
        'frame':2,'method':'primary_swing_lead_arm_extension_proxy_v2'}}
    projection = [None]*17; projection[0] = [70,70]
    result['experimental_body3d'] = {'frames':[{'frame':2,'projection':projection}]}
    result['measurement_method'] = {'body_height_px':100}
    original = deepcopy(result)
    manifest = export_swing_clips(video, ingest(video, {}), result['pose_track'], tmp_path/'annotated', result=result)
    assert result == original  # Overlays do not change measurements or event labels.
    assert manifest['swings'][0]['clip']['overlay'] is True
    assert manifest['swings'][0]['clip']['status'] == 'available'
    frames = decoded(tmp_path/'annotated/swing-clips/1.mp4')
    image = frames[0][1]
    assert image[70,50,1] > 150  # Green raw nose point at the source frame's coordinate.
    assert image[55,50,1] > 150  # Green shoulder/elbow skeleton edge.
    foot = image[90,58]
    assert foot[2] > int(foot[1])+20 and foot[1] > 120  # Orange toe point.
    assert image[70,60,2] > 170  # Red disagreement connector.
    assert image[70,75,0] > 150  # Purple 3D projected point.
    # Source frame 3 has no body points: frame 2's skeleton is not carried forward.
    assert frames[1][1][70,50,1] < 120


def test_shared_overlay_scales_with_upright_frames_and_labels_contact_proxy(video, tmp_path, monkeypatch):
    from copy import deepcopy
    import cv2
    from test_colab_2d import preview_result
    from baseball_batting.preview_overlay import draw_points
    from tools.preview_swing_ranges import draw_points as colab_draw_points
    assert draw_points is colab_draw_points
    result = preview_result(video, 90)
    result['pose_track']['frames']['kp'][2][0] = [50,70]
    result['pose_track']['reps'][0]['events'] = {'contact':{'frame':2,'method':'arm_extension_proxy'}}
    original = deepcopy(result)
    labels = []
    put_text = cv2.putText
    def record(image, text, *args, **kw):
        labels.append(text)
        return put_text(image,text,*args,**kw)
    monkeypatch.setattr(cv2,'putText',record)
    manifest = export_swing_clips(video, ingest(video, {'rotation_degrees':90}),
        result['pose_track'],tmp_path/'rotated',result=result)
    assert result == original
    assert any('estimated contact proxy' in label for label in labels)
    frames = decoded(tmp_path/'rotated/swing-clips/1.mp4')
    assert frames[0][1].shape[:2] == (160,120)
    assert frames[0][1][70,50,1] > 150
    plain = export_swing_clips(video,ingest(video,{'rotation_degrees':90}),
        result['pose_track'],tmp_path/'plain',result=result,overlay=False)
    assert plain['swings'][0]['clip']['overlay'] is False
    assert decoded(tmp_path/'plain/swing-clips/1.mp4')[0][1][70,50,1] < 100


def test_missing_overlay_points_do_not_fabricate_a_skeleton():
    from baseball_batting.preview_overlay import draw_points
    source = np.zeros((160,120,3),np.uint8)
    points = [None]*17; points[0] = [float('nan'),70]
    extra = [None]*6; extra[0] = [float('inf'),90]
    image = draw_points(source,points,1,0,{},extra_points=extra)
    assert not np.any(source)
    assert not np.any(image[40:])