# Nine batting measurements and selectable 3D The API now has calculation paths for all nine fields. A value is returned only when its recording, event, geometry and stability checks pass. Every value remains `confidence: "est"`. Implemented calculations, a successful GPU run and stable numbers do not establish real-world accuracy. ## Choose a model Set the upload option `measurement_backend`: | Value | What runs | |---|---| | `2d` | Existing RTMW-x body/foot tracking and 2D estimates; anatomical trunk/separation fields remain unavailable | | `rtmw3d` | Same 2D tracking, then RTMW3D-x ONNX on short contact/foot-plant windows | | `sam3d` | Same 2D tracking, then SAM 3D Body in a separate interpreter on the same event windows | The default remains `2d` for existing clients. The standard Docker image includes the public lightweight model. SAM is optional and requires an installed worker plus normal approved provider access to its weights. A missing/failed selected model is reported explicitly; it never silently switches to another model. Supported 2D fields can still be returned. API upload options are ordinary JSON alongside the video: ```json { "measurement_backend": "rtmw3d", "handedness": "right", "pitcher_direction": "image_left", "view": "face_on", "camera_stability": "fixed_verified", "timing": {"kind": "unretimed", "source": "original camera file; no retiming"} } ``` Use those recording declarations only when they describe the video. Changing `measurement_backend` to `sam3d` selects SAM; the three HTTP endpoints for upload, status and coach payload are unchanged. ## What each field means | Field | Calculation | Main requirements | |---|---|---| | `stride_pct_height` | Horizontal ankle-to-ankle span at estimated settled foot plant, divided by image stature | Fixed camera, identified lead leg, observed plant, valid scale | | `foot_plant_to_contact_ms` | Actual capture-time difference between estimated plant and contact | Both events, documented nominal 30 FPS or higher timestamps, adequate event resolution | | `com_drift_pct_height` | Hip midpoint horizontal position relative to lead ankle at estimated contact | Identified lead leg, pitcher direction, scale; this follows the coach contract and is not whole-body centre of mass | | `load_tempo_s` | Hand-load start to swing onset in capture seconds | Both events, documented timestamps and adequate resolution | | `load_launch_ratio` | Load duration / onset-to-contact duration | Three events, documented timestamps, denominator resolved under frame shifts | | `head_movement_pct_height` | Smoothed nose path from stance to estimated contact, divided by image stature | Fixed camera, complete analytical path, scale; noise-dominated paths withheld; reference-only | | `lead_knee_angle_contact_deg` | 3D interior hip-knee-ankle angle at estimated contact; 180° straight | Supported adjacent 3D frames and identified lead leg; 2D mode retains only its explicitly projected reference estimate | | `lateral_trunk_tilt_contact_deg` | Midhip-to-midshoulder lean in the pelvis lateral plane; positive toward the anatomical lead side | Stable 3D hip/shoulder axes and camera vertical | | `hip_shoulder_separation_foot_plant_deg` | Angle between hip/shoulder landmark lines projected onto the plane perpendicular to vertical, modulo 180°, in [-90,90) | Estimated plant and stable 3D hip/shoulder axes | These last two definitions are explicit landmark constructions. They do not claim clinical joint-coordinate-system angles or an OpenSim anatomical fit. The detailed external `POSE_DATA_SPEC.md` and coach validator were not supplied; the coach developer should confirm the signed-angle conventions. The coach's documented policy should continue treating unvalidated 3D as reference-only. Contact still means estimated lead-arm extension during the primary swing, not confirmed bat-ball impact. Plant means a settled-foot proxy, not measured full body-weight loading. A no-stride/no-load swing may legitimately lack those events. 3D cannot recover an unknown capture clock or prove ground force. ## Stability checks and evidence The raw exported 2D track stays unchanged. The analytical track retains bounded three-frame interpolation/median filtering and the v3 event repair. Version `batting-2d-v6` adds supported final-step/stance evidence and retains documented nominal 30 FPS or higher timestamps, including variable cadence and 29.97 FPS. Every capture interval in the rep must be <= `1.01/30` seconds; the 1% tolerance accommodates fractional frame rates and small timestamp jitter. Larger gaps withhold timing. Playback time still never supplies physical swing time. The final lead-foot step is tracked from a quiet old position through lift, sole return and settling at its new image position. A short confirmation window can follow onset while keeping the plant timestamp before or at onset; it cannot borrow contact/follow-through. Head path starts only at a supported quiet hands/pelvis/ankles window immediately before preparation. Walk-throughs without such a stance leave head movement unavailable. See [event evidence and thresholds](BATTING_2D_MEASUREMENTS.md#swings-and-events). 30 FPS has about 33.3 ms between frames; 60 FPS has about 16.7 ms. The previous 60 FPS cutoff was an engineering choice, not a model requirement. A longer load can be estimated at 30 FPS, while a short launch or plant-to-contact interval may remain too poorly resolved. The API quality layer rejects each duration/ratio if its ±1-frame sensitivity range is nonpositive/undefined or wider than half its value. This is a resolution stress test, not a measured error limit. The full result records `capture_interval_ms`, `event_frame_sensitivity_range` and its unit. An advisory `low_fps` capture reason can remain at 30 FPS without making capture fail. `measurement-quality-v2` includes: - Raw joint support near measurement events; large raw-versus-filtered joint changes withhold a value. - Nearby-frame position sensitivity for stride and hip position. More than six percentage points of variation withholds the value. - Raw-versus-filtered head path checks to reject noise-dominated paths. - Timing sensitivity when each event shifts by one frame. Nonpositive/poorly resolved durations or ratios are withheld. `duration_frame_intervals`, `event_frames`, `event_shift_frames`, `relative_sensitivity_width` and `resolution_status` distinguish missing events/clocks from insufficient recording resolution. Raising a file's FPS label does not add recorded samples. - 3D projections must agree with raw 2D joints within 5% of image stature. This is agreement between models, not comparison to truth. Per-frame `pose_agreement` records named rejected joints, percentage residuals, camera-projection consistency and a side-swap diagnostic. Anatomical sides and points are never shifted/swapped to force agreement. - Three consecutive supported 3D frames around the actual event. No missing-event substitution or interpolation of unavailable 3D. - Broad segment-length bounds and at most 25% local length variation. - A three-frame relative median before 3D angle calculation; knee geometry is anchored at its knee, trunk/separation at the pelvis. An unsupported opposite hip cannot invalidate an otherwise supported knee. Raw model points remain in the experimental export. - Nearby-frame angle sensitivity limits: knee 15°, trunk 12°, separation 20°. These are initial conservative engineering gates, not measured error limits. `measurement_diagnostics` in the full result explains each value or omission. Frame-shift ranges and camera-prior sensitivity are stress checks, **not accuracy confidence intervals**. The compact coach payload keeps exactly its existing nine entries, units and `est` labels; no new keys are required by the coach. ## Camera assumptions in lightweight 3D The pinned RTMW3D model predicts image/crop XY and pelvis-relative Z in metres. Crop pixels must never be combined directly with depth in metres. The adapter unwarps XY into the upright image and back-projects with camera intrinsics and an estimated pelvis depth. Optional upload inputs improve the geometry declaration: - `camera`: `{fx, fy, cx, cy, source}` in upright decoded pixels, after any rotation. - `height_m`: actual player height when known. Height alone is not camera calibration. - `root_depth_m` and `root_depth_source`: measured pelvis distance along camera Z. - `camera_up`: direction of vertical in camera axes; defaults to `[0,-1,0]`, assuming a level upright camera. Without intrinsics the declared prior is focal length `1.2 × max(width,height)` and image-centre principal point. Without measured pelvis depth, a weak-perspective depth uses declared player height, or an explicitly assumed 1.75 m stature, and the projected skeleton scale. If scale is unavailable the model's training-set depth prior is recorded. These are assumptions, not recovered camera calibration. When geometry is assumed, lightweight angles are stressed with independent ±15% focal/depth changes and withheld if they exceed the same angle sensitivity limits. The true camera can lie outside that perturbation band. Supplying accurate calibration/depth removes that particular prior check but does not validate model predictions. Inferred metre coordinates remain experimental. SAM supplies its own predicted camera translation. The adapter verifies its projection/unit convention and maps native MHR landmarks to COCO-17. The [pinned provider landmark names](https://github.com/facebookresearch/sam-3d-body/blob/b5c765a0d89d789985e186d396315e7590887b94/sam_3d_body/metadata/mhr70.py) identify native hips 9/10, knees 11/12, ankles 13/14 and wrists 62/41. It does not divide already converted coordinates by 100 or flip their axes again. SAM provides no calibrated joint confidence; its exported scores remain null. 2D agreement and stability gates still apply. Its default FOV is recorded when camera calibration is absent. Valid camera conversion does not explain away disagreement between joint predictions, and the engine does not select one as ground truth. ## Colab comparison Open [batting_measurements_test.ipynb](../notebooks/batting_measurements_test.ipynb). It has the familiar eight steps. In step 3 set `MEASUREMENT_BACKEND` to `rtmw3d`, `sam3d` or `2d`. Run steps 1–8 for the first test. To update an existing runtime's engine, rerun step 1 at `REVISION="main"`, then steps 4–8; installed models/environments can be reused. To compare another model on the same recording, change step 3 and rerun steps 3–8. A fresh job and backend-labelled ZIP are created, retaining source commit, input hash, recording options, raw points, measurements, 3D diagnostics and previews. At sampled frames the preview adds purple 3D projections and red disagreement connectors; contact/plant comparison PNGs are also displayed/exported. These diagnostics never alter measurements. The existing 2D-only notebook remains available separately. For SAM, set `EXISTING_SAM_RECORD` to an earlier installed `full-worker.json` to reuse that environment/assets. Otherwise setup installs only the isolated SAM inference environment and reads `HF_TOKEN` from a Colab secret or hidden input. Provider approval is still required. Setup never runs anatomy checks or temporal reconstruction. Each detected contact/plant requests at most five frames, deduplicated across events. The worker processes at most 300 selected frames; excess complete windows are recorded as omitted. SAM's subprocess has a 600-second timeout; the lightweight worker checks a 600-second budget between frames. The enclosing API job has its own configurable timeout. Thus a one-swing recording with only contact normally requests five 3D frames rather than every frame. These limits are not a performance guarantee. Model loading/setup remain separate costs. The full result stores selected camera-coordinate points in `experimental_body3d`, outside the validated-only `pose_track.kp3d` contract. No unvalidated dense `kp3d` block is claimed or sent to the coach. A `ready` 3D status means inference produced the requested frames, not that all measurements passed their checks. ## Accuracy status Constructed geometry tests check all nine calculation paths, known 3D angles, units, side/sign conventions, frame resolution, missing support and rejection behavior. A real ONNX run checks execution and output topology. Neither replaces an independently measured batting reference. All outputs still report `reference_validation_pending`; no high/medium labels or claimed accuracy percentages are introduced. Upstream references: [RTMW3D model definitions](https://github.com/open-mmlab/mmpose/tree/main/projects/rtmpose3d), [RTMLib 3D decoder](https://github.com/Tau-J/rtmlib/blob/03a1693e59e4f7cd84582c0fb30459b3bf18ad42/rtmlib/tools/pose_estimation/rtmpose3d.py), [pinned ONNX export](https://huggingface.co/Soykaf/RTMW3D-x/tree/a4f0d54c52ee44ee4e1dda1936d714490c6234d2), [SAM 3D Body](https://github.com/facebookresearch/sam-3d-body/tree/b5c765a0d89d789985e186d396315e7590887b94).