---
title: "Several programs need the same camera"
description: "Run a detector, alerts and a recording on one camera, each where it can change or fail without touching the others. A security and operations example."
type: "docs-page"
url: "https://tatolab.com/docs/use-cases/video-analytics"
site: "Tatolab"
section: "Use cases"
---

# Several programs need the same camera

> Run a detector, alerts and a recording on one camera, each where it can change or fail without touching the others. A security and operations example.

A camera in a lobby, on a loading dock or over a workbench usually ends up with several jobs: a model that counts or detects, a recording, an alert when something happens, and a person or an agent who wants to look now and then. Each job wants the camera, and a camera can only be opened by one program at a time. So the jobs get bundled into one application, where changing the model means restarting the recording, and a crash in the detector takes everything down.

With Tato, one project owns the camera, encodes it, keeps the recording and sends the video to a MoQ relay. Each other job reads it there, in a project of its own.

```txt
lobby-camera:  CameraSource ─▶ H264Encoder ─┬─▶ H264File (recording)
                                            └─▶ MoqTrackSend ─▶ relay: lobby-camera.hang, track video
lobby-counts:  MoqTrackReceive (lobby-camera.hang, video) ─▶ H264Decoder ─▶ ObjectDetector ─▶ ZoneCounter ─▶ CrowdingAlert
```

## The camera project

`lobby-camera` holds a `CameraSource`, an `H264Encoder`, the `H264File` node from [Encode and save](https://tatolab.com/docs/build/recording#save-it-to-a-file), and a `MoqGateway`, `MoqTrack` and `MoqTrackSend` that send the encoded video to the relay as the track `video` of the broadcast `lobby-camera`, as in [Share between streams](https://tatolab.com/docs/share/between-streams#send-a-track). Set the camera's `max_width` and `max_height` to `1280` and `720`.

It does one job and changes rarely. The recording is in the same stream as the camera, so it runs whenever the camera does, and a change to the counting never restarts it.

## The counting project

`lobby-counts` reads the track with a `MoqTrackReceive` (`broadcast` `lobby-camera.hang`, `track` `video`, `family` `packets`, `codec` `h264`) through a gateway of its own, decodes it with an `H264Decoder`, and runs `ObjectDetector` from [Use your model](https://tatolab.com/docs/build/models) on the pictures. Two small nodes of yours do the rest:

```python title="nodes/zone_counter.py"
from dataclasses import dataclass
from typing import Annotated

from tatolab.stream import Input, Output, Records, RuntimeContextLimitedAccess, node


@dataclass
class ZoneCounterConfig:
    label: Annotated[str, "What to count."] = "person"
    zone: Annotated[tuple[int, int, int, int], "The area to count in, as [left, top, right, bottom] in pixels."] = (0, 0, 1280, 720)


@node.meta(category="Analysis", description="Counts the detections of one label whose centre is inside a zone.")
@node.process
class ZoneCounter:
    detections = Input(Records, delivery="ordered", requires=("objects",))
    occupancy = Output(Records, names=("count",))

    def __init__(self, config: ZoneCounterConfig) -> None:
        self.label = config.label
        self.left, self.top, self.right, self.bottom = config.zone

    def process(self, ctx: RuntimeContextLimitedAccess) -> None:
        while True:
            detections, timestamp_ns = ctx.inputs.read_with_timestamp(self.detections)
            if detections is None:
                return
            count = 0
            for each in detections["objects"]:
                left, top, right, bottom = each["box"]
                x, y = (left + right) / 2, (top + bottom) / 2
                if each["label"] == self.label and self.left <= x <= self.right and self.top <= y <= self.bottom:
                    count += 1
            ctx.outputs.write(self.occupancy, {"count": count}, timestamp_ns=timestamp_ns)
```

```python title="nodes/crowding_alert.py"
import json
import os
import urllib.request
from dataclasses import dataclass

from tatolab.stream import Input, Records, RuntimeContextFullAccess, RuntimeContextLimitedAccess, log, node


@dataclass
class CrowdingAlertConfig:
    limit: int = 8


@node.meta(category="Output", description="Posts to a webhook when the count goes over its limit.")
@node.process
class CrowdingAlert:
    occupancy = Input(Records, delivery="ordered", requires=("count",))

    def __init__(self, config: CrowdingAlertConfig) -> None:
        self.limit = config.limit
        self.over = False

    def setup(self, ctx: RuntimeContextFullAccess) -> None:
        self.webhook = os.environ["LOBBY_ALERT_WEBHOOK"]

    def process(self, ctx: RuntimeContextLimitedAccess) -> None:
        while (reading := ctx.inputs.read(self.occupancy)) is not None:
            over = reading["count"] > self.limit
            if over and not self.over:
                body = json.dumps({"text": f"Lobby crowded: {reading['count']} people"}).encode()
                request = urllib.request.Request(self.webhook, body, {"Content-Type": "application/json"})
                try:
                    urllib.request.urlopen(request, timeout=5)
                except OSError as failure:
                    log.warn("alert not sent", error=str(failure))
            self.over = over
```

The webhook's URL comes from the runtime's environment, so it's never in the graph document. Each node's process inherits `tatolabd`'s environment.

## What you get from splitting them up

- **Change the model without touching the camera.** Edit `lobby-counts` and reload it. `lobby-camera`, and its recording, never notice.
- **A detector crash doesn't stop the camera.** It's in another project, and its nodes run in their own processes.
- **Anyone can add a reader.** A dashboard, a second model or an agent's stream reads `lobby-camera.hang` from the relay without changing it.

The counting project decodes the video it reads, which costs a hardware decode. That's the price of keeping the camera in a project of its own. If you'd rather not pay it, put the detector in the camera's stream, as one more reader of the camera's `video`.

## What leaves the machine

Only what you send: the alert's webhook message, anything a node of yours posts, and the tracks you send to a relay. A relay on loopback keeps them on the machine. Follow the rules for video surveillance where you operate.

## Today's limits

- **IP cameras aren't built in.** `CameraSource` reads cameras the operating system sees. An RTSP camera needs a source node you write, for example with PyAV. ONVIF, VMS integration and event clips with pre-roll aren't built in either.
- **USB webcam frame rates on Linux.** `CameraSource` reads uncompressed video only, so most USB 2.0 webcams deliver 5 to 10 frames per second in HD.
- **Alert on silence too.** If `occupancy` stops arriving, the detector isn't running; a node that dies five times in a row stays in `Error` until the project reloads.
- **Recordings are yours to keep.** If they may be used as evidence, add your own log of times, checksums and export procedure, and delete old files on your own schedule.

## Related guides

- [Share between streams](https://tatolab.com/docs/share/between-streams): the MoQ nodes.
- [Use your model](https://tatolab.com/docs/build/models): the detector.
- [Encode and save](https://tatolab.com/docs/build/recording): the encoders, and saving to a file.
- [Deploy to a machine](https://tatolab.com/docs/run/deploy): run it on a box near the camera.
