# Motion Detection

## Usage

    motion.exe <feed_number> [settings_file]
    motion.exe --help

Argument | Description
--- | ---
`feed_number` | Which feed to monitor: 0, 1, or 2 (required)
`settings_file` | Path to settings.txt (default: `settings.txt`)

## Description

Each motion detection instance monitors one camera feed for jumper movement. When sustained motion is detected, it triggers video recording.

## Detection Pipeline

For each new frame, the pipeline executes 10 steps:

Step | Operation | Description
--- | --- | ---
1 | Frame Diff | Compute absolute pixel differences (Y, U, V) between current and previous frame
2 | Histograms | Build per-plane histograms of difference values
3 | Threshold | Derive adaptive thresholds from histograms and settings
4 | Binary Frame | Apply thresholds to create binary motion map
5 | UV Merge | Merge U/V detections into Y plane (2x2 expansion)
6 | Flood Fill | Recursive 8-neighbor connected component detection
7 | Blob Collect | Scan for blobs, compute centroids and bounding boxes
8 | Blob Merge | Merge nearby blobs within fuzz tolerance, filter by size
9 | Distance | Match blobs to previous frame, compute movement distance
10 | Trigger | Evaluate sustained motion count, trigger recording

## Motion Region

Only pixels within the configured motion region are analyzed. Set per-feed boundaries to exclude non-relevant areas:

    motion_start_x[0]=100
    motion_start_y[0]=50
    motion_end_x[0]=1800
    motion_end_y[0]=1000

## Trigger Logic

Motion detection uses a sustained-count approach:

- Each frame with valid blob movement increments `motion_count`
- When `motion_count` reaches `min_motion_count`, recording triggers
- Each frame without motion increments `nomotion_count`
- When `nomotion_count` reaches `min_nomotion_count`, recording stops

See Motion Detection Tuning for adjustment guidance.

## Output

Results are written to the frame header in shared memory:

- `motion_detected_flags` — bitmask of detection state
- `distance_traveled` — horizontal blob movement (pixels)
- `distance_traveled_y` — vertical blob movement (pixels)
- `blobs[0..9]` — up to 10 detected blobs with centroids and sizes

## See Also

- Motion Detection Tuning
- Settings Reference — threshold parameters
- Video Generator — uses motion triggers