# Watch live video

> Watch live video in one line: Curva drops unchanged frames, judges the changed ones with a vision model and fires your actions, with the time each step took.

Source: https://docs.tarkova.com/curva/guides/watch/

## How it works, step by step

1. **Frames in** (JPEG, PNG, WebP, SDK ffmpeg, Server pull, fps cap): The SDK reads a file, URL or webcam through ffmpeg at 5 frames a second, at most 1280 px wide, or takes your own picture bytes; with pull=True the server reads the camera itself. Frames over the fps cap are dropped before decoding, and only the newest frame waits its turn. In the example: curva.watch on a 24 s test clip made from two labelled photos with added noise: no phone for 10 s, a phone for 8 s, no phone for 6 s. 120 frames arrived.
2. **Change gate** (64×64 grey, Scene noise, max_quiet_s, No model call): Each frame becomes a 64×64 grey thumbnail and is compared with the last frame kept. It goes on if it changed by at least twice the scene's own noise, if max_quiet_s (10 s) has passed, or if a trigger that held on the last judged frame needs another look. In the example: 117 of the 120 frames stopped here. Frames 1, 51 and 91 went on: the first frame and the two cuts.
3. **Local heads** (CLIP ViT-B/32, Learning, Shadowing, On, Yes/no only): With the local image model installed, each camera trains a head per yes/no question from the hosted model's answers, and a head answers alone only after it proves itself on varied scenes. On a real fixed camera no head switched on, so plan on the hosted model. In the example: All 3 frames passed through. The head stayed at learning, and the receipt says local: 0.
4. **Reused answers** (16×16 grid, Last 30 s, Last 16 answers, Same readings, No model call): A kept frame that still needs a hosted answer is compared with the last 16 frames the model judged on this stream in the past 30 s. A near-identical frame with the same readings reuses that answer as tier cache, and a new scene clears the list. In the example: cached: 0. Frame 91 showed the first photo again, but each cut counted as a new scene and cleared the list.
5. **Hosted model** (One at a time, Newest frame, Background call, deadline_ms, Paid per frame): The frame goes to the hosted vision model in the background, with at most one call per stream in flight. While it runs, newer frames still pass the gate and only the newest changed one waits, so video is never queued. In the example: Qwen3-VL on Bedrock, timed from each frame's arrival: frame 1, no, 2,529 ms. Frame 51, yes, 1,849 ms. Frame 91, no, 740 ms.
6. **Confirmed actions** (2 of 3 frames, One at 0.95, min_p, Once per event, Webhooks): A trigger fires when its answer holds on 2 of the last 3 judged frames, or on one frame at 0.95 or above, and fires again only after it held on none of the last 3. A frame the gate dropped is not new evidence. In the example: The action phone fired on frame 51 from one answer above 0.99, 1,850 ms after that frame arrived, and only once.
7. **The receipt** (Salted hash, Signed decisions, Frame counts, Audit log): A hosted-model decision is signed and logged with a salted hash of its frame, under the stream's id, and frames are never kept. When the stream ends, the receipt counts every frame and lists the last 1,000 decisions and actions. In the example: 120 frames: 117 gated, 3 sent to the model, 0 local, 0 cached, 0 dropped, 1 action, median decision 1,849 ms.

Point Curva at a camera, a stream, a file or your own frames. It says what is happening, flags
what needs attention and runs your actions, each answer typed, timed and signed.

```python

for event in curva.watch("rtsp://cam-7/stream"):   # or "clip.mp4", or 0 for the webcam
    print(event)                                     # "Driver using phone, 95% sure (frame 41, 8.9 s)"
```

```ts

for await (const event of new Curva().watch("clip.mp4")) console.log(String(event));
```

With no questions Curva uses the `auto` set: `happening` (one sentence), `attention` (a calibrated
probability that something is unusual, unsafe or worth a person's attention), `event` (a short
label, or `nothing`) and `where` (a Box). An `attention` action fires when `attention` is at least
0.8 on 2 of the last 3 judged frames, or at least 0.95 on one (see [Confirmation](#confirmation-and-speculative-alerts)).

Files, URLs and the webcam are read by ffmpeg on your machine (`brew install ffmpeg` or
`apt install ffmpeg`), at 5 frames a second, at most 1280 px wide. Without ffmpeg, pass the frames
yourself: any iterable of JPEG, PNG or WebP bytes (OpenCV, a phone, a screen grabber). Leaving the
loop stops ffmpeg and the stream; the loop also ends when the server ends the stream.

## A camera by URL: the server reads it

With `pull=True` the server reads the camera itself, so nothing runs on your machine but the loop:

```python
for event in curva.watch("rtsp://user:pass@cam-7.example.com/stream", pull=True, fps=2):
    print(event)
```

```ts
for await (const event of new Curva().watch("rtsp://user:pass@cam-7.example.com/stream", { pull: true, fps: 2 })) console.log(String(event));
```

On the socket this is `"source": "rtsp://..."` in the `start` message instead of frames. It takes
`rtsp://`, `rtsps://`, `http://` (an MJPEG camera) and `https://` (an HLS playlist), and nothing
else: no `file:` and no ffmpeg tricks such as `concat:`. The server needs ffmpeg.

- **Public addresses only, unless the owner says so.** The camera's host is resolved and every
  address checked at `start`, and again for every connection ffmpeg opens, redirects and HLS
  segments included. A camera on a private network (`10.x`, `192.168.x`, `localhost`, a cloud
  metadata address) is refused with a `forbidden` error until the server's owner lists it:
  `CURVA_WATCH_ALLOW=10.0.0.0/8,192.168.1.20,cam-7.local` (networks, addresses or host names).
- **RTSP runs over TCP**, and a camera that answers with an RTSP redirect is not followed: the
  stream ends saying so, and you give the address it points to. An `rtsps://` camera needs a
  certificate the server's system trusts.
- **Passwords stay out of sight.** Events, errors, logs and the receipt show the camera as
  `rtsp://cam-7.example.com/stream`, without the user name, password or query. On the server the
  URL is on ffmpeg's command line, so other users of that machine who can list processes can see
  it.
- **A dead camera ends with one sentence.** A camera that sends no frame for 10 s (20 s for the
  first) counts as dropped. One that drops after sending frames is reopened up to 6 times (0.5 s,
  then doubling to 8 s between tries). One that never sends a frame, sends something that is not
  video, or cannot be reopened ends the stream with a `source_error` and the receipt. A camera that ends its own stream ends the watch the same
  way, without an error.
- Frames are read at `fps`, at most 1280 px on the long side, and go through the same gate and
  models as pushed ones. 8 cameras per API key and 64 per server. Pull mode is for live sources: a
  recording at a URL is read as fast as it downloads, so judge recordings with
  [video on `/v1/decide`](/curva/guides/video/) instead.
- Measured on this laptop (Apple M1), 2026-10-23: from the camera sending a changed frame to the
  action reaching the client, ffmpeg included, p50 310 ms and p99 419 ms (147 scene changes, a
  stand-in local model; the server's own share p50 1 ms). Live on qwen3-vl, model decisions on
  pulled frames took 585 to 934 ms. A still camera with sensor noise sent 30 frames to the model
  in 5 minutes, one each `max_quiet_s`: 360 a camera-hour at the default 10 s (a larger
  `max_quiet_s` sends fewer). The frames are the same bytes the SDK's own ffmpeg makes, so the answers
  are the same as in push mode.

## Your own questions and actions

```python
def stop_line(action):
    print("phone at speed:", action["because"])

watch = curva.watch(
    camera_frames(),                                  # your iterator of JPEG bytes
    questions={
        "phone_in_hand": "Does the driver hold a phone in a hand?",
        "moving": {"type": "noul", "instructions": "The vehicle is moving",
                   "rules": [{"if": {"speed_kmh": {"gt": 20}}, "answer": True}, {"if": {}, "answer": False}]},
    },
    state={"speed_kmh": 42},                          # readings for rules; never guessed from video
    triggers={"phone": {"if": {"@phone_in_hand": True, "@moving": True}, "min_p": 0.8}},
    on={"phone": stop_line},
)
for event in watch:
    print(event)
```

- A frame can be `(jpeg, {"speed_kmh": 12})` to update the readings from that frame on.
- `ask="driving"` starts from the ready-made driving set: no seat belt, phone in hand, eyes closed,
  no helmet on a two-wheeler. It is **experimental** until it passes the quality bar on a labelled
  set of at least 50 + 50 per question; see Known limits.
- A trigger with `webhook` POSTs the action, signed with the project's webhook secret, as on
  `/v1/listen`; [Actions](/curva/guides/actions/) has Slack, Teams, Discord, Telegram and replay. Each trigger fires once per event: again only after it stopped holding (see
  [Confirmation](#confirmation-and-speculative-alerts)).
- `deadline_ms` with `fallback` answers a frame with the fallback when the model is late.

## How a frame is answered

Every frame goes through up to four tiers, and the event says which one answered (`tier`):

| Tier | What answers | Cost |
|---|---|---|
| `gate` | a 64×64 grey thumbnail compared with the last frame kept; the threshold follows the scene's own noise, and one frame goes on at least every `max_quiet_s` (10 s) | $0; the frame is not yielded by the SDKs, only counted |
| `local` | the camera's own heads on the local image model, on the server, once they have earned it (see [The fast path](#the-fast-path-answers-on-this-server)) | $0 |
| `cache` | the hosted model's answer to a near-identical frame of the same stream in the last 30 s (see [Reused answers](#reused-answers)) | $0 |
| `model` | the hosted vision model, in the background | paid per frame sent |

- **Video is never queued.** At most one model call per stream is in flight; while it runs, newer
  frames still pass the gate, and only the newest changed frame waits for the next call. An older
  one waiting is replaced and counted as `dropped`.
- **Act now, check after.** With a local model, an action fires on its first sure answer at once,
  marked `confirmed: false`, before its decision is even signed; the hosted model then sends
  `confirmed` or `retracted`. See below.
- **Nothing is stored but hashes.** Frames are never kept. A decision is signed and logged with a
  salted hash of its frame, under the stream's id, so `/v1/audit?call=cam_7` and feedback by
  `call` work as for calls.

When the stream ends, the receipt counts every frame: `frames`, `gated`, `sent_to_model`,
`local`, `cached`, `dropped`, `refused` (unreadable, or over the API key's rate: `rate_limited` says how many), with the last 1,000 decisions and actions, and the actions:
`fired`, `confirmed`, `retracted`, `unconfirmed` (still waiting) and `median_check_ms`.

## The fast path: answers on this server

:::caution[Plan on the hosted model]
No head switched on for a real fixed camera, so on that camera the server answered nothing itself
([measured](#the-fast-path-on-real-footage-2026-10-27), [Known limits](/curva/known-limits/#live-video)).
This section describes how the path works; it has no current speed, share or accuracy figure.
:::

With the local image model installed, the server learns each camera and, once it is sure, answers
familiar frames itself, without the hosted model. A head needs varied scenes before it switches on;
until then, every frame that needs a fresh look goes to the hosted model. Install the model once per
server (one 605 MB download, kept as 153 MB of int8 weights in `~/.curva/models`, or where
`CURVA_CLIP_DIR` points):

```sh
curva vision-model fetch
```

and restart `curva serve`. Without it, `/v1/watch` works as before, every changed frame goes to
the hosted model, and the server says so once in its log at start.

How a camera earns it, per yes/no question:

1. **Learning.** Every frame the gate keeps is turned into an image vector by the local model
   (CLIP ViT-B/32, int8, Curva's own Rust) and sent to the hosted model as usual. The hosted
   model's answer becomes a training label for that camera's head on that question. Training runs
   on the server's worker pool, never in the frame's path, from 200 labels on and again every 50.
2. **Shadowing.** The trained head answers every frame before the hosted model's answer arrives,
   and the two are compared. Nothing is decided by the head yet.
3. **On.** The head answers alone only above a confidence where its shadowed answers agreed with
   the hosted model at least 95% of the time (a Wilson lower bound, so it takes about 50 sure
   answers in a row), its "no" answers kept 90% of the events, and its probabilities are
   calibrated (ECE at most 0.05). Only a new scene counts toward that evidence: a frame almost the
   same as one the head already learned with the same answer (image vectors at a cosine of 0.95 or
   more, such as the next frames of a parked car) still trains the head but is not counted again. Below that confidence, or on a frame unlike the ones it learned
   from, the frame still goes to the hosted model.

Once on, a frame every question's head answers alone gets a `local` decision and is not sent to
the hosted model, except:

- **Alerts.** An action fired from a local answer is speculative (`confirmed: false`) and its
  frame goes to the hosted model, which confirms or retracts it as described below.
- **Audits.** One alone answer in 20 also goes to the hosted model, so a camera that drifts (a
  moved lamp, a new season) is noticed while its head is on. The receipt's `audits` counts them.
- **A new scene.** When most of the picture changes at once (the camera moved, the lights went
  off), the gate tells the camera's heads, and they go back to shadowing until they earn it again
  on the new scene. A slower change is caught the same way: when half of a head's recent frames
  look unlike what it learned from, it starts over.

Only yes/no (`noul`) questions get heads; a rule answers its question locally from `state` as
usual. A frame with any other kind of question to answer (a sentence, a choice, a Box, or the
`auto` set's `happening`) still goes to the hosted model, so `auto` streams learn but do not skip
the hosted model yet.

Heads are kept per project, stream name and question (its exact wording), in the server's
database after every training and when the stream ends, so a restarted server, or another server
on the same database, answers a camera it already knows from the first frame. Use the same
`stream` name for the same camera. A server keeps at most 1,024 heads in memory (the least
recently used go first, and come back from the database when that camera returns) and 4,096 in
the database.

A person's correction teaches the camera too: `POST /v1/feedback` with a watch decision's `id`
(every hosted-model decision has one, and so does every local decision that fired an action) and
`label: true` or `false` replaces the hosted model's label for that frame, and the hosted model can
no longer overwrite it. The server remembers the last 4,096 such frames.

Key limits hold on this path as on the other: a local action counts against the API key's rate
(an action over it is refused and counted in `rate_limited`), and a revoked key ends the stream at
its first local decision a second or more after the revocation.

What to watch:

| Where | What |
|---|---|
| receipt | `local` (frames answered on the server, which is also the hosted-model calls saved), `cached` (frames answered with a reused answer), `audits`, `heads` (each question's stage: `learning`, `shadowing` or `on`) and `local_latency_ms` (`p50`, `p99` over the last 1,000 local decisions) |
| `/metrics` | `curva_watch_stream_frames_total{outcome="local"}`, `curva_watch_stream_heads{stage=...}` and `curva_watch_stream_local_seconds{quantile="0.5"\|"0.99"}` per open stream |
| log | one line when a camera's head changes stage, and one when a new scene sends it back |

One encoder per server turns frames into image vectors, two at a time. A frame of a camera whose
heads are on goes first; when two such frames already wait, the next one goes to the hosted model
instead, so a busy server costs more but never answers late. A frame the hosted model judged for a
camera that is still learning waits its turn instead (one turn in four when the encoder is busy,
at most 64 MiB of such frames per server), so every camera learns even when many are busy.

### Reused answers

A frame that would go to the hosted model because no head could answer it alone (the camera is
still learning, or its heads are unsure) is first compared with the frames the hosted model judged
on that stream in the last 30 s (the last 16). When it is near-identical to one
(the same 16 × 16 grid of brightness on the 64 × 64 thumbnail, after the whole picture's brightness
is taken out, within the larger of 3 grey levels and twice the camera's own noise), the hosted model's answer to that frame is used
again: the decision has `"tier": "cache"`, nothing is paid, and the receipt counts it in `cached`
and `reused`. The readings sent with `state` must be the same too. Answers are kept per stream only,
so they are never shared across streams, projects or API keys. A frame that fired a speculative
action, and an audit, still go to the hosted model. A new scene clears them. Set
`CURVA_WATCH_REUSE=off` on the server to turn this off.

`CURVA_WATCH_CROPS=on` (off by default) sends the hosted model only the part of a yes/no frame that
changed since the last frame it answered all "no" to, with a quarter of that area again as
context, when that part is under 60% of the picture. The receipt's `cropped` counts them. It is
off until its accuracy is measured against the hosted model on whole frames.

## Confirmation and speculative alerts

One bad frame should not raise an alarm, and a real event should raise one alarm, not one per
frame. So on `/v1/watch` a trigger fires when its answer holds on **k of the last n judged
frames** (default 2 of 3), or on **one frame at `min_p_single`** or above (default 0.95). Only
frames that reached a model count: a frame the gate drops repeats the last answer but is no new
evidence. When a trigger held on the last judged frame and needs more frames to fire, the next
frame is judged even if the scene did not change, up to k - 1 times, so a phone that comes into
view and then stays still fires within a few frames instead of waiting for `max_quiet_s`. A
flicker still fires nothing: the extra look does not hold. Once fired, a trigger fires again only after its answer held on none of the last n
judged frames. `repeat: true` fires on every judged frame where the rule is met.

```python
triggers={
    "smoke": {"if": {"@smoke": True}},                                     # 2 of 3, or one frame at 0.95
    "intruder": {"if": {"@person_in_area": True}, "confirm": {"k": 3, "n": 5}, "min_p_single": 0.99},
}
```

With a local model, `speculative` (default true) fires an action on the local model's **first
frame where the trigger holds**, marked `confirmed: false`, without waiting for more frames. The
hosted model answers that frame (or a newer one) in the background and the stream gets a
`confirmed` or `retracted` event with the same action id, the frame it fired on, the frame that
checked it and `after_ms`, the time from the frame to the check. A trigger with a `webhook` gets
the same follow-up as a second signed POST: the body has `type`, `action` (the action's id) and
`confirmed: true` or `false`; its `x-curva-idempotency-key` is the action id with `.confirmed`
or `.retracted`, so a receiver that removes duplicates keeps both.

With `speculative: false` nothing fires before the frames agree: k of n, or one frame at
`min_p_single`, counted over the local model's and the hosted model's answers as they arrive.
Without a local model every judged frame is the hosted model's, and the same rule applies.

`/metrics` counts the checks (`curva_watch_checked_total{outcome="confirmed"|"retracted"}`, per
open stream too) and the time to them (`curva_watch_check_seconds`).

## Measured

Live, 2026-10-21, this laptop (Apple M1, 8 cores, shared with other builds), the server and the
Python SDK on the same machine, `qwen.qwen3-vl-235b-a22b-instruct` on Bedrock (ap-south-1):

| Run | What | Result |
|---|---|---|
| 68 s clip, 1024×576, 5 fps, one yes/no question plus a speed rule | 8 scenes with a phone in hand, 9 without, 4 s each, with sensor noise | 340 frames: 294 dropped by the gate, 18 sent to the model, 28 replaced by a newer frame; actions on 6 of the 8 phone scenes (both misses were the same photo), none on the 9 others |
| | model decision, frame arrival to answer | p50 811 ms, p90 2,340 ms (n 18) |
| | event to action (first frame of the scene to the action) | 659, 738, 855, 1,015, 1,416, 2,644 ms (n 6) |
| 30 s clip, `auto` set (four answers, one a sentence and one a Box) | 2 phone scenes | 150 frames, 5 to the model; model decision 3.6 to 5.1 s (n 5) |

The model path cannot meet a 100 ms budget.

### The fast path on real footage (2026-10-27)

We replayed a real fixed camera through `/v1/watch`: the waiting room of a bus station in the
MEVA dataset (camera G331, CC BY 4.0), 36 five-minute recordings from 8 days, morning to night,
empty and crowded. One frame every 3 s gave 3,600 frames of 640×360, replayed at 10 fps (a 30×
time-lapse, 6 minutes a run). Qwen3-VL on Bedrock labelled each frame for two questions, "At least
one person is in the room" (yes on 937 frames) and "Someone is sitting on a bench" (yes on 880),
and we checked 30 random labels by eye (30 of 30 right). The hosted model in the run was a stand-in
that gives Qwen3-VL's label after 1.0 s, so every number below is about Curva, not Qwen.

| | Local tier installed | Hosted model only |
|---|---|---|
| Heads switched on | none, for either question (both still `shadowing` at the end) | |
| Frames answered on the server (`local`) | 0 of 3,600 | |
| Hosted-model calls a run (one camera, 6 minutes) | 302 for each question | 301 for each question |
| Reused answers | 25 and 29, none wrong | 28 and 28 |
| Frame to action, all from the hosted model | p50 1,024 and 1,070 ms, p99 1,077 and 1,116 ms (n 6 each) | p50 1,017 and 1,044 ms |

So on this camera the fast path gave no answers, and precision, recall and ECE of answers on the
server could not be measured (n 0). Why: the picture of a fixed camera hardly changes as a whole
when people come and go. Two frames of the same recording have image vectors at a cosine of 0.985
(median), and a frame of an unseen recording is at 0.988 from its nearest learned frame, so almost
every frame counts as a near copy. Of the 3,600 frames, only 102 (people) and 107 (sitting) count
as a new scene. Even with every frame of 24 of the recordings labelled (2,400 frames) and tested on
the other 12, no head switched on.

Earlier runs, on 24 October, let a head switch on from near copies of a few scenes, before the
switch-on fix below, so their latency and local-share numbers are not repeated here.

Since 2026-10-26 a head counts only new scenes toward switching on (see How a camera earns it),
because many near copies of a few scenes had let a head switch on and then answer new scenes
wrongly. Our 10-minute lobby test clip is one cut-out dog on one photo, so on it no camera
switches on any more, even after 30 minutes, and frames that need a fresh look wait about a
second for the hosted model. Reused answers cut hosted-model calls a camera-hour by 8% at 1 camera, 15% at 10 and 16% at
25 on that clip (2,772 to 2,550 at 1), and by 42% on a kitchen clip with a cat a quarter of the
time, with no reused answer wrong against the truth.

The change gate alone, decode included: p99 1.1 ms at 640×480 and 3.5 ms at 1280×720 (n 300 each, 98.3% of a static clip
dropped, the scripted event kept).

Load, 200 streams at 2 frames a second of 640×480 JPEG for 3 minutes (about 71,000 frames), a
fake model answering in 300 ms: with the laptop at a load average of 6 to 10 from other builds,
gate decisions p50 3 ms, p99 16 ms, model decisions p50 318 ms, p99 462 ms, 1.2% of frames
dropped; at a load average of 25 to 45, gate p99 64 to 100 ms and 15 to 27% dropped (a newer
frame won, or the decode pool was full), never queued, no errors. Server memory stayed between
81 and 142 MB through each run. A flood of 1,000 junk frames a second on one stream for 20 s
(1.25 GB): all but 630 dropped at the fps cap before decoding, those 630 refused by the decoder,
memory 16 MB before, 19 MB at the peak.

Cost per camera-hour depends on how often the scene changes: about $0.017 at one changed frame a
minute and $0.34 at twenty, with qwen3-vl at 640 px and one yes/no question.

## Limits

| | |
|---|---|
| Frame | 2 MiB and 9 million pixels (DCI 4K, 4096×2160, fits; a larger frame gets an error read from its header and the stream goes on); a message over 4 MiB closes the socket; JPEG, PNG or WebP |
| Frames a second | `fps`, default 10 on the socket and 5 in the SDKs, from 0.1 to 30; up to a second's worth of jitter is allowed, more is dropped before decoding |
| Streams | 64 per API key, 1,024 per server; cameras read by the server (`source`): 8 per API key, 64 per server |
| Messages | `start` 64 KiB, other text 32 KiB |
| Frames held at once | 512 MiB across the server, 128 MiB per API key; a frame over it is dropped and counted |
| Decoding | a fixed pool of one thread per core, at most half of it (at least 2) for one API key; when either is full the frame is dropped and counted, never queued |
| Idle | 30 s without a frame closes the stream (with `source`, the camera's own limits above apply), and so does a client that reads none of its events for 30 s |
| State | 16 KiB of JSON |

`/metrics` has frames by outcome, actions and their checks, in total and per open stream, and the
time from a frame's arrival to its decision per tier. On shutdown, every stream gets an `error` and its
receipt. See the [HTTP reference](/curva/reference/http-api/#get-v1watch-websocket) for every
message.
