> For the complete documentation index, see [llms.txt](https://docs.eyepop.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eyepop.ai/deploying/on-premise/media-cache.md). Agents can also search and read this documentation through its [MCP server](https://docs.eyepop.ai/~gitbook/mcp).

# Media Cache

Record video on the instance and read frames and clips back

The **media cache** keeps the video an instance processes, for a while, on the same machine. Predictions tell you *what* happened and *when*; the media cache lets you go back and look: the frame a prediction was made on, a crop of one object, or a clip of the moments around it.

It is off unless you turn it on, and nothing is recorded unless a source asks for it. Recordings stay on the machine: they are not uploaded to EyePop.

## How it works

With the media cache on, the instance runs a second container, `media-cache`, beside the runtime, on the same private Docker network. Nothing outside the machine can reach it.

1. **A source asks to be recorded.** A video, a stream or a camera you send the instance names how many seconds to keep, `mediaCacheSeconds`. A source that does not ask is not recorded.
2. **The instance records it while it runs inference.** The recording is the source's own video, stored as it arrives, so recording costs almost nothing. Video that cannot be stored as it arrives, such as VP8 from a browser's WebRTC, VP9, AV1 or MJPEG, is encoded again as H.264 first.
3. **The results name the recording.** The first line of the source's results is a `recording` event with a `mediaId`, before any prediction:

   ```json
   {"event": {"type": "recording", "mediaId": "v2.…"}}
   ```
4. **You read it back by `mediaId`**: the range it holds, a frame at a prediction's `timestamp`, or a clip between two timestamps.
5. **It expires.** A recording is kept for the seconds its source asked for, at most the cache's retention, and the oldest recordings go first when the cache reaches its size.

A prediction's `timestamp` is in nanoseconds of the recording's own clock, so it is exactly what a frame read takes.

## Turn it on

```bash
eyepop instance set --media-cache disk
```

That turns the cache on with its defaults, keeping recordings for up to an hour and up to 20 GB, and restarts the instance once. `eyepop instance init` takes the same flags, so a new instance can start with it:

```bash
eyepop instance init --ability eyepop.person:latest --media-cache disk
```

| Flag                      | What it sets                                                                                                                        | Default                       |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `--media-cache`           | `off`, `disk` or `memory`                                                                                                           | `off`                         |
| `--media-cache-retention` | How long recordings are kept, and the most `mediaCacheSeconds` a source may ask for, such as `30m`, `4h` or `24h`; at most 24 hours | `1h`                          |
| `--media-cache-size`      | The most recordings kept, such as `500M`, `20G` or `1T`; the oldest are removed past it                                             | `20G` on disk, `2G` in memory |
| `--media-cache-path`      | A directory on this machine for the recordings, instead of the `eyepop-media-cache` Docker volume                                   | the volume                    |

`instance set` keeps what you do not name, so `eyepop instance set --media-cache-retention 4h` changes only the retention. `--media-cache off` turns it off again and keeps the recordings it has, for when you turn it back on.

A source that asks for more seconds than the retention is refused: the cache could not keep them.

The media cache needs runtime v4.21.0 or later, the first that names a recording and reads it back. The version EyePop recommends for new instances is newer, so this matters only for an instance pinned to an older one with `--tag`: `init` and `set` refuse it. Pick v4.21.0 or later with `eyepop instance init --tag`, such as `--tag v4.22.0`, together with `--media-cache`.

## Disk or memory

|                                 | `disk`                                                          | `memory`                                                                                      |
| ------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| **Where recordings live**       | The `eyepop-media-cache` Docker volume, or `--media-cache-path` | A RAM disk inside the cache's container                                                       |
| **After a restart or a reboot** | Kept, until they expire                                         | Gone                                                                                          |
| **What the size costs**         | Disk space                                                      | The machine's memory, which the instance needs too                                            |
| **Use it for**                  | Looking back at what happened, for hours                        | Looking at what just happened, on a machine with memory to spare and a disk you want to spare |

`init` and `set` refuse a size the machine can never hold: in memory, more than half of its RAM; on disk, more than its disk. When there is less free space than the size, they say so and go ahead, since recordings the cache already holds count toward it.

`--media-cache-path` puts the recordings on a disk of your choice, such as a large or a fast one. The directory is created if it does not exist, and handed to the cache's own user, uid 999.

## How much room it needs

A recording takes about as much room as the video the camera sends. Roughly, for one camera:

| Video             | Per hour   |
| ----------------- | ---------- |
| 720p H.264        | about 1 GB |
| 1080p H.264       | about 2 GB |
| 4K H.264 or H.265 | about 7 GB |

Multiply by the number of cameras and the hours to keep. Four 1080p cameras kept for 4 hours need about 32 GB: `--media-cache-retention 4h --media-cache-size 32G`. A camera that sends less detail, or fewer frames, takes less.

## Record and read back

This records one video on an instance with the media cache on, then reads back what the cache holds of it, the frame of one prediction and a two-second clip. Use any short MP4 video.

Each example sends the video asking to keep it for 10 minutes (`mediaCacheSeconds`), collects the predictions, and takes the recording's `mediaId` from the `recording` event that starts the results. It then reads the frame of a prediction about a second in, at most 640 pixels wide, and the first two seconds the cache holds.

{% tabs %}
{% tab title="CLI" %}

```bash
eyepop run --media-path video.mp4 --media-cache-seconds 600 --json > results.jsonl

# The recording record comes first; the predictions follow, one per frame.
MEDIA_ID=$(jq -r 'select(.event.type == "recording") | .event.mediaId' results.jsonl)
TIMESTAMP=$(jq -r 'select(.response) | .response.timestamp' results.jsonl | sed -n 25p)

eyepop instance media range "$MEDIA_ID"
eyepop instance media frame "$MEDIA_ID" --timestamp "$TIMESTAMP" --max-width 640 -o frame.jpg
eyepop instance media clip "$MEDIA_ID" --duration 2s -o clip.mp4
```

With `--media-cache-seconds`, `run` prints one `recording` record for each source it recorded, `{"file": …, "event": {"type": "recording", "mediaId": …}}`, before that source's predictions. `--timestamp`, `--start` and `--end` take a prediction's `timestamp` in nanoseconds, or a duration such as `1.5s`; a clip with no `--start` starts at the first moment the cache holds.
{% endtab %}

{% tab title="Python" %}

```python
from eyepop import EyePopSdk

with EyePopSdk.sync_worker(is_local_mode=True) as endpoint:
    job = endpoint.upload("video.mp4", media_cache_seconds=600)
    predictions = []
    while (prediction := job.predict()) is not None:
        predictions.append(prediction)
    media_id = job.media_id

    start_ns, end_ns = endpoint.media_range(media_id)
    print(f"the cache holds {start_ns} to {end_ns} ns")

    frame = endpoint.media_frame(media_id, predictions[24]["timestamp"], max_width=640)
    with open("frame.jpg", "wb") as file:
        file.write(frame)

    clip = endpoint.media_clip(media_id, start_ns, start_ns + 2_000_000_000)
    with open("clip.mp4", "wb") as file:
        file.write(clip.read())
```

This needs `eyepop` 4.1.2 or later.
{% endtab %}

{% tab title="Node" %}

```typescript
import { writeFile } from 'node:fs/promises'
import { EyePop, Prediction } from '@eyepop.ai/eyepop'

async function main() {
    const endpoint = await EyePop.workerEndpoint({ isLocalMode: true }).connect()

    try {
        const results = await endpoint.process({ source: { path: 'video.mp4' }, mediaCacheSeconds: 600 })
        const predictions: Prediction[] = []
        for await (const prediction of results) {
            predictions.push(prediction)
        }
        const mediaId = results.mediaId!

        const { startNs, endNs } = await endpoint.mediaRange(mediaId)
        console.log(`the cache holds ${startNs} to ${endNs} ns`)

        const frame = await endpoint.mediaFrame(mediaId, predictions[24].timestamp!, { maxWidth: 640 })
        await writeFile('frame.jpg', frame)

        const clip = await endpoint.mediaClip(mediaId, startNs, startNs + 2e9)
        await writeFile('clip.mp4', new Uint8Array(await new Response(clip.stream).arrayBuffer()))
    } finally {
        await endpoint.disconnect()
    }
}

main().catch(console.error)
```

This needs `@eyepop.ai/eyepop` 4.2.3 or later.
{% endtab %}

{% tab title="curl" %}

```bash
PIPELINE_ID=$(curl -sS http://127.0.0.1:8080/pipelines | jq -r '.[0].id')

curl -sS -X POST \
  "http://127.0.0.1:8080/pipelines/$PIPELINE_ID/source?mode=queue&processing=sync&mediaCacheSeconds=600" \
  -H 'Content-Type: video/mp4' \
  -H 'Accept: application/jsonl' \
  --data-binary @video.mp4 > results.jsonl

# The first line names the recording; the predictions follow, one per frame.
MEDIA_ID=$(head -1 results.jsonl | jq -r '.event.mediaId')
TIMESTAMP=$(sed -n 26p results.jsonl | jq -r '.timestamp')

curl -sS "http://127.0.0.1:8080/media/$MEDIA_ID/range"
START=$(curl -sS "http://127.0.0.1:8080/media/$MEDIA_ID/range" | jq -r '.start_ns')

curl -sS -o frame.jpg \
  "http://127.0.0.1:8080/media/$MEDIA_ID/frame?timestamp=$TIMESTAMP&maxWidth=640"

curl -sS -o clip.mp4 \
  "http://127.0.0.1:8080/media/$MEDIA_ID/clip?start=$START&end=$((START + 2000000000))"
```

The range comes back as `{"start_ns": …, "end_ns": …}`.
{% endtab %}
{% endtabs %}

The CLI asks the same routes as the `curl` example, and so do the SDKs in [local mode](https://docs.eyepop.ai/deploying/on-premise/applications.md#from-your-code). In the SDKs, a `predict()` or a `for await` that has returned has seen the `recording` event, so the job's `media_id` (`mediaId` in Node) is set by then; it stays unset for a source that does not record. The CLI and the SDKs wait out a `425` or a busy cache's `503` and ask again, for up to 30 seconds, before they give up.

### What you can read

| Read  | Route                        | Takes                                                                                                                                                                                                                                                        |
| ----- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Range | `GET /media/{mediaId}/range` | —                                                                                                                                                                                                                                                            |
| Frame | `GET /media/{mediaId}/frame` | `timestamp` in nanoseconds; optionally `bbox=x,y,w,h` to crop to an object, in the frame's pixels; `maxWidth` and `maxHeight` to scale it down. JPEG, or PNG with `Accept: image/png`                                                                        |
| Clip  | `GET /media/{mediaId}/clip`  | `start` and `end` in nanoseconds, at most 5 minutes apart. `mode=exact` (the default) cuts it to exactly those bounds; `mode=keyframe` is faster and starts at the keyframe before `start`. The bounds it got are in the `X-Start-Ns` and `X-End-Ns` headers |

A moment of a live source that is not in the cache yet is waited for up to 2 seconds (`wait`, in milliseconds, up to 10 000), then answered `425` with a `Retry-After` header. A recording past its retention answers `410`. A busy cache answers `503` with `Retry-After`: read again after it.

An instance reads only its own recordings. A `mediaId` of another instance, or of EyePop's cloud, answers `404`.

## Privacy and security

* Recordings never leave the machine, and the cache is not reachable from outside it: its port is not published.
* The instance answers the read routes to whoever can reach its port 8080, as it does every other route. See [`--bind`](https://docs.eyepop.ai/deploying/on-premise/settings.md#bind) before you open that port to your network.
* Recordings are kept for the seconds their source asked for, at most the retention, and then removed.
* `eyepop instance delete` keeps the recordings, for a later `init` with the cache on. `eyepop instance delete --purge` removes them too. A `--media-cache-path` directory is never removed; delete it yourself.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.eyepop.ai/deploying/on-premise/media-cache.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
