How the Even Sampling Algorithm Keeps First and Last Frames in Claude Video
The _even_indices function in skills/watch/scripts/frames.py mathematically guarantees first and last frame retention by using count-1 as the numerator and n-1 as the denominator, forcing indices 0 and count-1 when i equals 0 and n-1 respectively.
The bradautomates/claude-video watch skill intelligently thins dense video frames to a user-specified budget without losing narrative boundaries. At the heart of this logic sits a concise mathematical helper—_even_indices—that ensures the opening and closing frames always survive the downsampling process. This article breaks down exactly how the algorithm enforces this invariant across all edge cases.
The _even_indices Implementation in frames.py
The core logic lives in skills/watch/scripts/frames.py at lines 283-293. Here's the full implementation:
def _even_indices(count: int, n: int) -> list[int]:
"""Indices of ``n`` evenly‑spaced items out of ``count`` (first + last kept)."""
if n >= count:
return list(range(count)) # all frames kept
if n <= 1:
return [0] # only the first frame kept
return [round(i * (count - 1) / (n - 1)) for i in range(n)]
The function handles three distinct cases, each engineered to preserve boundary frames.
Case 1: Requesting More Frames Than Available (n >= count)
When the requested sample size equals or exceeds the candidate pool, _even_indices returns every index via list(range(count)). This trivially includes index 0 (first frame) and index count-1 (last frame).
>>> _even_indices(4, 10)
[0, 1, 2, 3] # first (0) and last (3) preserved
Case 2: Single Frame Selection (n <= 1)
When only one frame is requested, the function returns [0]. In this degenerate case, the first frame is the last frame, satisfying the boundary preservation constraint by definition.
>>> _even_indices(7, 1)
[0] # single frame: first equals last
Case 3: General Even Sampling (1 < n < count)
This is where the mathematical guarantee lives. The list comprehension:
[round(i * (count - 1) / (n - 1)) for i in range(n)]
produces n positions using linear interpolation across the closed interval [0, count-1].
| Position | Formula Result |
|---|---|
First (i = 0) |
0 * (count-1)/(n-1) = 0 |
Last (i = n-1) |
(n-1) * (count-1)/(n-1) = count-1 |
The count-1 and n-1 terms are deliberately paired. By anchoring the interpolation to count-1 (the final valid index) and dividing by n-1 (the number of intervals between n points), the formula maps i=0 exactly to 0 and i=n-1 exactly to count-1. Rounding occurs only for intermediate values, leaving the boundaries untouched.
>>> _even_indices(12, 5)
[0, 3, 6, 9, 11] # 0 and 11 are exact; intermediates are rounded
How _even_sample Consumes These Indices
The higher-level routine _even_sample (lines 401-413 in frames.py) applies _even_indices to actual frame data:
def _even_sample(candidates: list[dict], n: int) -> list[dict]:
selected = [candidates[i] for i in _even_indices(len(candidates), n)]
# … delete the un‑selected JPEGs and re‑index …
return selected
This function receives a list of candidate frames—typically derived from scene changes, key frames, or timestamps—and returns a thinned subset. Because _even_indices always includes indices 0 and len(candidates)-1, the first and last candidate frames are always selected regardless of how aggressive the downsampling.
Practical Example: 5 Frames From 12 Candidates
>>> candidates = list(range(12)) # simulated frame IDs
>>> indices = _even_indices(len(candidates), 5)
[0, 3, 6, 9, 11]
>>> _even_sample([{'id': i} for i in candidates], 5)
[{'id': 0}, {'id': 3}, {'id': 6}, {'id': 9}, {'id': 11}]
The spacing between frames is roughly uniform (~2.75 steps), but the critical observation is that positions 0 and 11 exist exactly, not approximately. This matters for video understanding: the opening frame establishes context and the closing frame often contains resolution or transition cues.
Why This Design Matters for Video Processing
Video frame sampling faces competing constraints. Uniform temporal sampling risks dropping semantically important boundaries. Random sampling destroys reproducibility. The _even_indices approach offers three advantages:
- Determinism: Same inputs always yield same outputs
- Boundary preservation: First and last frames survive any valid
n - Uniformity: Intermediate frames distribute evenly across the temporal span
These properties make the algorithm suitable for LLM video analysis, where consistent, bounded context windows matter.
Related Files and Testing
| File | Purpose |
|---|---|
skills/watch/scripts/frames.py |
Core extraction, sampling, and deduplication logic |
tests/test_frames.py |
Unit tests verifying _even_indices and _even_sample behavior |
tests/test_timestamps.py |
Timestamp-driven extraction tests, also uses _even_indices for capping |
The test suite validates that boundary preservation holds across edge cases including empty inputs, single-frame videos, and requests exceeding available frames.
Summary
_even_indicesusescount-1andn-1as paired terms to mathematically force first and last index inclusion- Three cases handle all scenarios: full selection (
n >= count), single frame (n <= 1), and interpolated sampling (1 < n < count) _even_sampleapplies these indices to actual frame dictionaries, preserving boundary frames through list indexing- The algorithm enables reproducible, budget-constrained video analysis without losing opening or closing context
Frequently Asked Questions
Why does the formula use count-1 instead of count?
The -1 adjustment converts from frame count (1-based cardinality) to maximum index (0-based positioning). With 12 frames indexed 0-11, count-1 equals 11—the actual last index. Using count would generate an out-of-bounds reference.
Does rounding ever affect the first or last frame?
No. Rounding applies only to intermediate values. When i=0, the product is exactly 0; when i=n-1, the (n-1) denominator cancels exactly, yielding count-1. Both results are integers before rounding.
What happens if I request zero frames?
The current implementation treats n <= 1 as a single-frame request, returning [0]. This is a conservative fallback—requesting zero frames would typically be caught at a higher validation layer before reaching _even_indices.
Is this the same as numpy's linspace?
Conceptually similar, but _even_indices uses round() rather than linspace's endpoint-handling options. The explicit count-1/n-1 construction guarantees exact boundary inclusion without floating-point edge cases that might shift endpoints slightly.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →