# Python recipes & ffmpeg

Canonical: https://interlatent.com/docs/ivy/custom-code

Run repeatable measurements and video transformations with annotate(clip, ctx), then save outputs for review.

## How a recipe runs

Section: https://interlatent.com/docs/ivy/custom-code#execution

An annotation recipe is a Python function named `annotate(clip, ctx)`. Ivy runs the same function for each selected clip. The clip provides recording metadata; ctx provides frame access, model operations, annotation helpers, and artifact output. Ask your agent to read `get_annotation_sdk` for the current API before writing a recipe.

1. Define the required inputs, camera, interval, and outputs.
2. Read the SDK and author one recipe for that task.
3. Use estimate_annotation with the selected clip IDs and script.
4. Start the estimated job with run_annotation, then poll get_job with kind="annotation".
5. Inspect the resulting tracks and artifacts. Retry failed clips only.

Note: Running a recipe uses credits. Reading the SDK and estimating a recipe do not execute it. Use get_annotations for an existing annotation document; do not run a recipe merely to read it.

## Example: measure brightness

Section: https://interlatent.com/docs/ivy/custom-code#measurements

This deterministic recipe samples frames and writes mean grayscale brightness as a scalar track. It requires no vision-model calls. Values are in the 0–255 grayscale range; this measures image brightness, not task success or image quality.

### Brightness recipe

```python
def annotate(clip, ctx):
    times, values = ctx.brightness(every_n=5)
    return {
        "tracks": [{
            "name": "mean_brightness",
            "kind": "scalar",
            "times": [float(t) for t in times],
            "values": [float(v) for v in values],
        }],
        "summary": "Mean grayscale brightness, every fifth frame.",
    }
```

Note: every_n is a number of source frames. At 30 fps, every_n=5 samples roughly six frames per second; at 60 fps it samples roughly twelve.

## Frames, intervals, and camera selection

Section: https://interlatent.com/docs/ivy/custom-code#sampling

`ctx.frames` yields a timestamp in seconds and an OpenCV BGR frame. Set `camera` explicitly when the task depends on a particular view. An integer `every_n` strides through source frames; `every_n=None` with `max_frames` spreads a finite set across the requested interval. Report this sampling when interpreting a result.

### Frame sampling

```python
# Inside annotate(clip, ctx). Choose a name from ctx.cameras.
camera = ctx.cameras[0]
for t, frame_bgr in ctx.frames(
    camera=camera,
    t0=0,
    t1=min(10.0, clip.duration_s),
    every_n=None,
    max_frames=8,
):
    # Compute a deterministic measurement from this frame.
    pass
```

Note: For model-backed labeling, combine related frames in one ctx.label_frames call or combine related questions in ctx.jev. Do not use a Python frame loop to issue one model request per frame. For a full action sequence, use subtask segmentation.

## Example: create a separate excerpt

Section: https://interlatent.com/docs/ivy/custom-code#trim-code

`ctx.trim` creates a frame-exact H.264 MP4 artifact by default. The end of the interval is exclusive. Name the output so you can find it in the clip’s artifact list. Reusing that name replaces the artifact produced under that name.

### Trim recipe

```python
def annotate(clip, ctx):
    start = 12.0
    end = min(24.0, clip.duration_s)
    if end <= start:
        raise ValueError("This recording has no frames after 12 seconds")

    ctx.trim(start, end, name="excerpt_12_24", in_place=False)
    return {
        "summary": f"Created an excerpt from {start:.2f} to {end:.2f}s."
    }
```

Note: This helper produces a video artifact and removes audio. The original video remains unchanged with in_place=False. Use explicit camera selection for a view other than the primary camera.

- [Trim behavior and timeline effects](https://interlatent.com/docs/ivy/trimming)

## Example: render timestamps onto a view

Section: https://interlatent.com/docs/ivy/custom-code#render

`ctx.render_video` calls a frame-processing function and saves the returned frames as a separate video view. Output dimensions must remain constant. The example renders only the first ten seconds and uses each frame’s source timestamp for the text.

### Timestamp overlay recipe

```python
import cv2

def annotate(clip, ctx):
    def draw_timestamp(t, frame_bgr):
        output = frame_bgr.copy()
        cv2.putText(
            output, f"{t:.2f}s", (20, 36),
            cv2.FONT_HERSHEY_SIMPLEX, 0.8,
            (255, 255, 255), 2, cv2.LINE_AA,
        )
        return output

    ctx.render_video(
        "timestamp_preview", draw_timestamp,
        every_n=1, t0=0, t1=min(10.0, clip.duration_s),
    )
    return {"summary": "Rendered source timestamps on a separate view."}
```

Note: OpenCV uses BGR color order. Use source timestamps to align saved masks or labels with frames; do not assume output frame numbers are source frame numbers after sampling or trimming.

## ffmpeg on a downloaded video

Section: https://interlatent.com/docs/ivy/custom-code#ffmpeg

The following shell command runs in your own terminal or coding-agent environment after you download the input video. It extracts source seconds 12–24, resizes to 640 pixels wide, re-encodes H.264, removes audio, and writes a browser-playable MP4. Re-encoding avoids the keyframe-boundary limitations of stream-copy cuts.

### ffmpeg excerpt command

```shell
ffmpeg -n -i input.mp4 -ss 12 -t 12 \
  -vf "scale=640:-2" \
  -c:v libx264 -crf 20 -preset medium \
  -pix_fmt yuv420p -movflags +faststart -an \
  excerpt.mp4
```

Note: Replace input.mp4 with a local file you downloaded. -n refuses to overwrite an existing output. This command creates a local file; it does not register an Ivy artifact or update annotation timestamps. To retain audio, replace -an with -c:a aac when the input has an audio stream.

## Run ffmpeg inside a recipe

Section: https://interlatent.com/docs/ivy/custom-code#ffmpeg-recipe

For a transformation beyond the video helpers, a Python recipe can invoke ffmpeg on the clip’s available media and save the result with ctx.save_file. The example creates a one-frame-per-second preview and saves it as a downloadable clip artifact. Use ctx.render_video when you need a processed video registered as a selectable view.

### ffmpeg preview recipe

```python
from pathlib import Path
import subprocess
import tempfile

def annotate(clip, ctx):
    with tempfile.TemporaryDirectory() as directory:
        output = Path(directory) / "preview.mp4"
        subprocess.run([
            "ffmpeg", "-n", "-loglevel", "error",
            "-i", str(clip.path), "-t", "10",
            "-vf", "fps=1,scale=640:-2",
            "-c:v", "libx264", "-pix_fmt", "yuv420p",
            "-movflags", "+faststart", "-an", str(output),
        ], check=True, capture_output=True, timeout=240)
        ctx.save_file("preview.mp4", output.read_bytes())
    return {"summary": "Saved a 1 fps preview of the first 10 seconds."}
```

Note: clip.path is provided for the current execution. Do not store it as a permanent video location or pass a local path from your computer as if it existed in Ivy. Use the current SDK to check media access and supported dependencies before executing custom code.

## Return tracks and save files

Section: https://interlatent.com/docs/ivy/custom-code#outputs

Return scalar tracks for measurements, span tracks for labeled intervals, and events for instants. ctx.save_file saves JSON, text, bytes, or supported image arrays as clip artifacts. ctx.read_file reads files supplied through the project’s Files panel. After the job finishes, inspect annotations and request artifact links; a file on a temporary path is not a delivered result.

Note: Existing tracks merge by name. A new result under the same track name replaces that track, so use distinct names when comparing variants. Track names differing only by case, punctuation, or spaces can collide as Dataset columns.
