# How the Even-Sampling Algorithm Guarantees First and Last Frame Inclusion in Claude-Video

> Discover how the even-sampling algorithm in Claude-Video ensures first and last frame inclusion. Learn the sampling formula and its impact on video processing.

- Repository: [bradautomates/claude-video](https://github.com/bradautomates/claude-video)
- Tags: internals
- Published: 2026-07-09

---

**The even-sampling algorithm guarantees inclusion of the first and last frames by mapping the range `0` to `n-1` onto `0` to `count-1` using the formula `round(i * (count - 1) / (n - 1))`, ensuring the first iteration yields index `0` and the final iteration yields index `count-1`.**

When processing video content in the `bradautomates/claude-video` repository, the watch skill frequently extracts more frames than the configured maximum allows. The **even-sampling algorithm** solves this by selecting a deterministic, evenly-spaced subset from the candidate frames while mathematically preserving both the opening and closing shots of the video segment.

## The Mathematical Foundation of Even-Sampling

The guarantee rests in the pure-Python helper `_even_indices()`, located in [`skills/watch/scripts/frames.py`](https://github.com/bradautomates/claude-video/blob/main/skills/watch/scripts/frames.py) at lines 283-293. This function calculates which indices to keep when downsampling a list of `count` items to exactly `n` items.

### The Formula That Locks First and Last Positions

The implementation uses a linear mapping approach:

```python
[round(i * (count - 1) / (n - 1)) for i in range(n)]

```

This formula operates by scaling the index `i` (ranging from `0` to `n-1`) across the full span of the source list (ranging from `0` to `count-1`). Because the calculation uses `count - 1` divided by `n - 1`:

- When `i = 0`: The result is `round(0 * factor) = 0` (the first element)
- When `i = n - 1`: The result is `round((n-1) * (count-1)/(n-1)) = count-1` (the last element)

Consequently, the first and last indices are **always** present in the returned list, regardless of the values of `count` or `n` (provided `n <= count` and `n > 1`).

## Implementation in the Frame Pipeline

The `_even_sample()` function (lines 393-402 in [`skills/watch/scripts/frames.py`](https://github.com/bradautomates/claude-video/blob/main/skills/watch/scripts/frames.py)) applies this logic to actual frame objects. It takes a list of candidate frames, computes the even indices, preserves only those positions, and removes the JPEG files associated with dropped frames.

The implementation is straightforward:

```python
selected = [candidates[i] for i in _even_indices(len(candidates), n)]

```

Because `_even_indices` inherently includes `0` and `len(candidates)-1`, the `_even_sample` function **never discards** the first or final frame during the capping process. This behavior is invoked throughout the watch skill—including keyframe extraction, scene detection, and timestamp cue generation—whenever detected frames exceed the configured limit.

## Practical Code Examples

### Sampling a List of Frame Candidates

Here is how the even-sampling behaves with a simulated set of 10 frames capped to 4:

```python
from pathlib import Path
from skills.watch.scripts.frames import _even_sample

# Simulated list of 10 frame candidates

candidates = [
    {"index": i, "timestamp_seconds": i * 0.5, "path": f"/tmp/frame_{i:04d}.jpg"}
    for i in range(10)
]

# Cap to 4 frames → returns indices 0, 3, 6, 9 (first & last included)

selected = _even_sample(candidates, 4)

print([f["index"] for f in selected])

# Output: [0, 3, 6, 9]

```

### Capping Frames During Video Extraction

When extracting frames at specific timestamps with a maximum limit, the even-sampling triggers automatically:

```python
from skills.watch.scripts.frames import extract_at_timestamps

# Request multiple timestamps but cap to 5 frames maximum

frames, meta = extract_at_timestamps(
    video_path="video.mp4",
    out_dir=Path("/tmp/cues"),
    timestamps=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    max_frames=5,  # Triggers even-sampling

)

print(meta["selected_count"])  # → 5

# First timestamp (0) and last timestamp (9) are guaranteed in the output

```

## Summary

- The even-sampling algorithm uses the formula `round(i * (count - 1) / (n - 1))` to map indices linearly across the source range.
- The first index (`i=0`) always calculates to `0`, and the last index (`i=n-1`) always calculates to `count-1`.
- The `_even_indices()` function in [`skills/watch/scripts/frames.py`](https://github.com/bradautomates/claude-video/blob/main/skills/watch/scripts/frames.py) (lines 283-293) implements this mathematical guarantee.
- The `_even_sample()` function applies these indices to frame objects, ensuring the first and last frames are never removed during capping.
- This deterministic approach is used throughout the `bradautomates/claude-video` watch skill for keyframe extraction, scene detection, and timestamp processing.

## Frequently Asked Questions

### Why does the formula use `count - 1` and `n - 1` instead of `count` and `n`?

Using `count - 1` and `n - 1` ensures the linear interpolation maps the first element of the sample (`i=0`) to the first element of the source (`index 0`) and the last element of the sample (`i=n-1`) to the last element of the source (`index count-1`). If the formula used `count / n`, the last index would exceed the list bounds or fail to reach the final element.

### Does the even-sampling algorithm work with any Python list, or just video frames?

The `_even_indices()` and `_even_sample()` functions operate on any sequence where positional indices apply. While designed for video frame candidates in the `claude-video` repository, the underlying algorithm works for any list of objects, timestamps, or data points requiring evenly-spaced downsampling.

### What happens if `n` equals 1 in the even-sampling function?

When `n == 1`, the `_even_indices()` function returns `[0]` according to the source code in [`skills/watch/scripts/frames.py`](https://github.com/bradautomates/claude-video/blob/main/skills/watch/scripts/frames.py). This single index represents the first frame of the video, ensuring that at minimum, the opening shot is preserved when severe capping is required.

### How is the even-sampling behavior verified in the test suite?

The repository includes validation in [`tests/test_frames.py`](https://github.com/bradautomates/claude-video/blob/main/tests/test_frames.py) (specifically in tests like `test_keyframe_even_sampling_caps_and_spans`) and [`tests/test_timestamps.py`](https://github.com/bradautomates/claude-video/blob/main/tests/test_timestamps.py). These tests verify that when capping is applied, the resulting list contains the expected count of frames with the first timestamp equal to the video start and the last timestamp equal to the video end.