Current section
Files
Jump to
Current section
Files
usage-rules.md
<!--
SPDX-FileCopyrightText: 2026 James Harton
SPDX-License-Identifier: Apache-2.0
-->
# bb_camera Usage Rules
`bb_camera` provides camera support for [Beam Bots](https://hexdocs.pm/bb): the
`BB.Camera` behaviour, the bounded shared capture interface `BB.Camera.Hub`,
discovery, the `BB.Message.Camera.*` payloads, a no-hardware driver
(`BB.Camera.Synthetic`) and a Membrane source. Hardware drivers live elsewhere
(`bb_camera_v4l` and friends). For BB framework basics, see `bb`'s rules
(`mix usage_rules.sync <file> bb:all`); this file covers only what's specific to
cameras.
## Core principles
1. **The hub never puts a frame on `BB.PubSub`.** A camera publishes capture
lifecycle (`BB.Message.Camera.BeginCapture`, `EndCapture`) and periodic
capture state (`CaptureState`), and nothing else — no frame bytes in
events, errors or metadata. A frame on a fan-out registry has no
backpressure behind it, and one slow subscriber is enough to take the node
down. A frame is a `BB.Message`, so you *can* publish or serialise one you
hold; if you do, bounding it is your job.
2. **A request yields exactly one frame, strictly newer than your last.** You
cannot re-read the current frame. That is what stops a `next`-in-a-loop
consumer spinning at CPU speed instead of capture rate.
3. **Capture is driver-confirmed and shared.** The hub asks a driver to start
when the first consumer arrives and to stop when the last leaves; one
capture serves every consumer. Nothing claims to be capturing until the
driver says so.
4. **A camera is configured like any other component.** `options_schema/0`,
filled from parameters with `param/1`, changed through
`c:BB.Sensor.handle_options/2`. There is no camera-specific settings
channel — there was, and it was deleted as a duplicate of the parameter
system.
## Wiring it in
A camera is an ordinary sensor whose callback module also implements
`BB.Camera`. Attach it wherever it physically is, so its pose comes out right:
```elixir
parameters do
group :camera do
param(:width, type: :integer, default: 1280)
end
end
topology do
link :base do
joint :pan do
type(:revolute)
link :head do
sensor :eye, {BB.Camera.V4L,
device: "/dev/video0",
width: param([:camera, :width]),
height: 720
}
end
end
end
end
```
Changing `[:camera, :width]` at runtime re-validates the driver's options and
calls its `handle_options/2`.
## Consuming
- `BB.Camera.Media.open/3` + `next/2` + `close/1` when you have a loop.
- `BB.Camera.subscribe/3` + `request/1` + `unsubscribe/1` when you want
messages.
- `BB.Camera.Membrane.Source` when you have a pipeline.
Frames are always raw: `{:raw, pixel_format}` with `Membrane.RawVideo`'s pixel
formats, tightly packed. Assert the one you can handle
(`format: {:raw, :I420}`) at `open/3` or `subscribe/3`. Being told at open is
better than discovering it from the bytes.
A failed capture is retried by the hub, with a backoff that doubles up to
`:max_retry_delay`, for as long as anyone is subscribed. A consumer that stays
subscribed sees frames again when a retry succeeds; one that closes on any
`{:error, _}` from `next/2` gives up, and if it was the last subscriber the
retry is cancelled. Either is reasonable. Don't build your own reconnect loop
on top.
## Estimators on camera frames
Nest an estimator in a camera sensor and it receives frames, through the
camera's `BB.Estimator.Source`:
```elixir
sensor :eye, {BB.Camera.V4L, device: "/dev/video0"} do
estimator :markers, MyDetector
end
```
- `handle_input/2` gets the frame message: capture time in the envelope, a
`BB.Message.Camera.Frame` payload. For I420, the first `width * height`
bytes of `data` are the Y plane, which is already a greyscale image.
- It gets one frame per completed `handle_input/2`, always the newest. A
detector slower than the camera skips frames rather than falling behind.
Don't buffer frames yourself to "catch up".
- Stamp outputs with the frame's capture time by passing its `monotonic_time`
and `wall_time` to `BB.Message.new/4`, so consumers measure age from when
the scene was seen.
- A failed capture moves the estimator to `:lost` with reason
`:source_failed`, and it recovers when frames resume. A camera that crashes
is restarted, then its estimators after it.
- Test with `BB.Camera.Synthetic` at `clock: :external` and
`BB.Test.RecordingEstimator` from `bb`. Set `retry_delay: :external` on a
synthetic camera that fails, and retry by sending its hub `:retry_capture`.
## Drawing results over video
To have a viewer such as `bb_liveview` draw an estimator's results over the
video, implement `BB.Camera.Annotation` for its result payload, in the
package that defines the payload. `layer/1` returns a
`BB.Camera.Annotation.Layer` with the source frame's `width` and `height`,
a `lifetime`, and `primitives` (`Points`, `Circle`, `Text`) in pixel
coordinates. Each message replaces its layer, an empty one clears it, and a
layer disappears once `lifetime` has passed since the frame was captured.
Never publish separate "drawing" messages.
## What a frame carries
A frame is a `BB.Message` whose payload is a `BB.Message.Camera.Frame`. The
envelope carries the capture time (`monotonic_time`, `wall_time`), the
capturing `node`, and the camera's name as `frame_id`. Beyond `data`, `width`
and `height`, the payload has fields the hub stamps that you get for free:
- `requested_frame_rate` / `measured_frame_rate` — what was asked for, and what
the frames before this one actually did. Compare them; they are separate
claims on purpose.
- `joint_configurations` — every joint's configuration as at capture, so a
gimballed camera's pose is recoverable later. Feed it to
`BB.Robot.Kinematics.forward_kinematics/3` with `attached_to`. It is looked
up in the robot's joint history at the frame's `monotonic_time`, so it is as
exact as the joint reports behind it.
- `attached_to` — `{:link, name}`, `{:joint, name}` or `:robot`.
`metadata` is for driver-specific extras only (a sensor's exposure time). Don't
put anything in it that every frame has.
## Discovering
Use `BB.Camera.discover/1`. Don't write a second DSL walker — it works on
stopped robots, and it deliberately omits driver options so device paths and
credentials can't leak into a UI.
If a package treats `bb_camera` as optional, guard with
`Code.ensure_loaded?(BB.Camera)` and return `[]`. A robot can't declare a
camera without the package, because `use BB.Camera` wouldn't compile.
## Writing a driver
- One module: `use BB.Sensor` and `use BB.Camera`.
- `c:BB.Camera.stream_info/1` **must be pure**. It runs during discovery
against robots that aren't running, with unresolved DSL options. Describe
what was asked for; report what you actually got through
`BB.Camera.Hub.capture_started/2` or `update_stream_info/2`.
- Start the hub in `init/1` with `BB.Camera.Hub.start_link/1`. Don't register
it yourself.
- Answer `{:bb_camera, :start_capture}` with `capture_started/2` **or**
`capture_failed/2`. Capture isn't claimed until you confirm it, and a device
that fails to open must say so rather than go quiet.
- `BB.Camera.Hub.deliver/2` is a synchronous call. That is the only bound on
ingress there is. Never wrap it in a `Task`.
- Bound what happens before the hub yourself. Ports have no ingress
backpressure, and closing a port doesn't kill the program behind it.
- Reconfigure in `handle_options/2`. Restart capture only if the change
actually reaches the device.
- Don't measure your own frame rate. The hub sees every frame and publishes
`CaptureState` for every camera.
- Pass `publish_rate` through to the hub so a robot can change how often
that is published.
- If you trap exits, which you need to in order to see a capture process exit,
stop when the hub's `{:EXIT, hub, reason}` arrives. Otherwise the link that
ties driver and hub together does nothing, and the driver outlives its hub.
- Wait for anything holding the device to exit in `terminate/2`, not just
ask it to stop. A supervisor restarts a driver at once, and the replacement
will otherwise find the device busy. `bb_camera_ffmpeg` drivers call
`BB.Camera.FFmpeg.Capture.stop_and_wait/1`.
## Anti-patterns
- **Don't add a camera-specific configuration path.** Options and parameters
are the one way in. A second channel is what was removed.
- **Don't return `{:error, _}` from `handle_options/2`.** The contract is
`{:ok, state} | {:stop, reason}`. And know what `{:stop, _}` costs: the
parameter is already stored, so the component restarts into the same bad
value. Give parameters bounds that match the options they feed.
- **Don't compute forward kinematics per frame.** Snapshot the configurations
and let the consumer compute a transform when it actually wants one; on a
small target the `Nx` cost per frame is the thing that hurts.
- **Don't sleep in tests.** Clock a synthetic or test camera `:external` and
drive it frame by frame; set the hub's `publish_rate: :external` and close a
window by sending `{:tick, monotonic_ns}`, and its `retry_delay: :external`
and retry by sending `:retry_capture`. Wait for the event that proves the
thing happened.
## Further reading
- [bb_camera docs](https://hexdocs.pm/bb_camera)
- `BB.Camera.Hub` for the capture state machine and the demand model
- [Writing a camera driver](https://hexdocs.pm/bb_camera/01-writing-a-camera-driver.html)
- [Using a camera](https://hexdocs.pm/bb_camera/02-using-a-camera.html)
- [Run an estimator on camera frames](https://hexdocs.pm/bb_camera/run-an-estimator-on-camera-frames.html)
- [Draw estimator results over video](https://hexdocs.pm/bb_camera/draw-estimator-results-over-video.html)
- [Why frames don't go on PubSub](https://hexdocs.pm/bb_camera/why-frames-dont-go-on-pubsub.html)