Metadata-Version: 2.4
Name: video-processor-library
Version: 0.1.1
Summary: A video processor library built on custom FFmpeg wrappers for precise frame extraction and video metadata
Author-email: kishan0822 <kishan@sportzengage.ai>
Project-URL: Homepage, https://github.com/sportzengage/detection_trajectory_complete_pipeline
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: imageio-ffmpeg>=0.5.1

# Frame Extraction Library

A small Python toolkit for extracting frames from video files with FFmpeg, while keeping frames precisely aligned to their true (possibly variable) timestamps via FFprobe.

It's built around three main pieces:

- **`VideoProbe`** — a lazy, cached wrapper around `ffprobe` that exposes geometry, rotation, codec, timing, color, audio, and packet-level statistics (VFR/VBR detection) for a video file.
- **`VideoProcessor`** — extracts frames to disk with `ffmpeg` and pairs each frame index with its exact presentation timestamp (PTS) from `VideoProbe`, so downstream kinematic/analytics code never has to assume a constant frame rate.
- **`VideoFrameLoader`** — a high-level wrapper around `VideoProcessor` that manages temporary frame extraction, offering a context manager for easy cleanup, lazy extraction, and sequence/random frame access via OpenCV.

## Why this exists

Naively extracting frames and assuming a fixed FPS breaks down on variable-frame-rate (VFR) video — common in phone-recorded footage. This library:

1. Extracts frames with `ffmpeg`, respecting device rotation metadata.
2. Independently probes the *true* per-frame timestamps with `ffprobe`.
3. Validates that the frame count and timestamp count agree, preventing silent index misalignment.
4. Gives you exact `Δt` between any two frames — essential for correct velocity/kinematic calculations on VFR footage.

## Installation

Requires Python 3.10+ and `imageio_ffmpeg`:

```bash
pip install imageio-ffmpeg
```

## Quick start: loading frames (Recommended)

The easiest way to work with video frames is using `VideoFrameLoader` as a context manager. It lazily extracts frames to a temporary directory on first access and cleans up the temporary files when done.

```python
from video_utils import VideoFrameLoader

with VideoFrameLoader("input.mp4") as loader:
    print(f"Total frames: {loader.frame_count}")
    print(f"Video resolution: {loader.display_width}x{loader.display_height}")
    
    # Iterate through frames sequentially
    for idx, timestamp, frame in loader.iter_frames():
        # frame is a numpy array from cv2.imread
        pass

    # Or access a specific frame directly
    ts, frame = loader.get_frame(10)
```

## Quick start: extracting frames manually

```python
from video_utils import VideoProcessor
from video_utils import Rotation

processor = VideoProcessor("input.mp4")

# 1. Access timestamps (triggers the frame-timestamp scan lazily)
timestamps = processor.timestamps
print(f"Video has {len(timestamps)} frames")

# 2. Extract frames to disk
frame_files = processor.extract_frames_to_disk(
    output_dir="frames/",
    filename_prefix="clip01",       # optional, produces clip01_frame_0001.png, ...
    rotation_override=None          # optional Rotation value to override source metadata
)

print(f"Extracted {len(frame_files)} frames")
print(f"Average FPS: {processor.probe.fps}")

# Exact timestamp of frame 10 (index 9)
t = timestamps[9]
```

### Notes on `VideoProcessor`

- The constructor does **no** I/O — it just probes the file's basic stream metadata.
- Frames are written as `{prefix_}frame_%04d.png` into `output_dir`.
- Pre-flight checks ensure you don't overwrite existing frames or leave stale frames behind.
- Extraction raises a `ValueError` if `ffmpeg` and `ffprobe` disagree on the final frame count.

## Probing a video directly

You can also use `VideoProbe` on its own, without extracting any frames — useful for inspecting a video's properties up front:

```python
from video_utils import VideoProbe

probe = VideoProbe("input.mp4")

probe.display_dimensions      # DisplayDimensions(width=..., height=...) — post-rotation
probe.coded_dimensions        # CodedDimensions — as stored in the file
probe.rotation                # RotationResult(degrees=..., source=...)
probe.fps                     # average FPS
probe.duration                # seconds, or None
probe.codec                   # e.g. "h264"
probe.frame_timestamps        # tuple of per-frame PTS in seconds (dedicated ffprobe scan)
probe.exact_frame_count       # authoritative count from a packet scan
probe.packet_stats            # PacketStats: cfr/vfr, cbr/vbr, per-second fps/bitrate curves
```

## API Reference

### `VideoFrameLoader`

A high-level class for managing the lifecycle of extracted frames.

**Properties:**
- `fps` (float): The average framerate of the video.
- `display_width` (int): Width of the video in display orientation (post-rotation).
- `display_height` (int): Height of the video in display orientation (post-rotation).
- `frame_count` (int): The total number of extracted frames.
- `probe` (`VideoProbe`): Access to the underlying metadata probe.

**Methods:**
- `iter_frames() -> Iterator[Tuple[int, float, np.ndarray]]`
  Yields `(index, timestamp, frame)` sequentially. `frame` is a BGR NumPy array from OpenCV. Lazily extracts frames to a temporary directory if they haven't been extracted yet.
- `get_frame(idx: int) -> Tuple[float, np.ndarray]`
  Returns `(timestamp, frame)` for a specific 0-based index. `frame` is a BGR NumPy array. Raises `IndexError` if out of bounds. Lazily extracts frames if they haven't been extracted yet.

**Usage Details:**
```python
# Iterating over all frames
with VideoFrameLoader("input.mp4") as loader:
    for idx, ts, frame in loader.iter_frames():
        # Process the BGR frame
        pass

# Fetching a single frame by index
with VideoFrameLoader("input.mp4") as loader:
    ts, frame = loader.get_frame(250)
```

### `VideoProcessor`

A lower-level class focused solely on safely extracting frames to a specified directory and calculating precise timestamps.

**Properties:**
- `probe` (`VideoProbe`): The underlying `VideoProbe` instance.
- `timestamps` (`tuple[float, ...]`): Per-frame Presentation Timestamps (PTS) in seconds. Accessing this triggers the ffprobe timestamp scan.

**Methods:**
- `extract_frames_to_disk(output_dir: str, filename_prefix: str = "", rotation_override: Rotation | None = None) -> list[str]`
  Extracts every frame to `output_dir` as `{prefix}frame_%04d.png` (rotated into display orientation automatically). Validates that FFmpeg and FFprobe agree on the frame count to prevent silent indexing bugs. Returns the written filenames in exact frame order.

## Module layout

| Module | Responsibility |
|---|---|
| `video_frame_loader.py` | `VideoFrameLoader` — context manager for lazy extraction and frame access via cv2 |
| `video_processor.py` | `VideoProcessor` — frame extraction + timestamp alignment |
| `video_probe.py` | `VideoProbe` — lazy, cached metadata/timing/packet-stats probing |
| `video_types.py` | Data types: `ExtractionFPSmode`, `Rotation`, `TimestampRegressionError`, etc. |
