<!--
SPDX-FileCopyrightText: 2026 James Harton

SPDX-License-Identifier: Apache-2.0
-->

# Using a camera

In this tutorial you will start a camera without hardware, read a frame, then
receive frames by demand and through a Membrane pipeline. All three interfaces
use the same hub; simultaneous consumers share one capture.

Start with an Elixir application that depends on `bb` and `bb_camera`, as in
the [installation instructions](../../README.md#installation).

## 1. Declare a synthetic camera

Put this robot in `lib/camera_robot.ex`:

```elixir
defmodule CameraRobot do
  use BB

  topology do
    link :head do
      sensor :eye, {BB.Camera.Synthetic, width: 160, height: 120, clock: {:rate, 10}}
    end
  end
end
```

The synthetic camera produces moving grey bars in raw I420. Both dimensions
must be even. Start an `iex -S mix` session and run:

```elixir
{:ok, robot} = CameraRobot.start_link()
BB.Camera.discover(CameraRobot)
```

Discovery lists `:eye`. Its process is running, but it starts capturing only
when a consumer subscribes.

## 2. Pull a frame

Open and read the session from the same IEx process:

```elixir
{:ok, session} = BB.Camera.Media.open(CameraRobot, :eye, format: {:raw, :I420})
{:ok, frame} = BB.Camera.Media.next(session, 2_000)

{frame.frame_id, frame.payload.width, frame.payload.height,
 frame.payload.format, byte_size(frame.payload.data)}
# => {:eye, 160, 120, {:raw, :I420}, 28800}

:ok = BB.Camera.Media.close(session)
```

`frame` is a `BB.Message` with a `BB.Message.Camera.Frame` payload. The
capture timestamps are in its envelope. Calling `next/2` again would wait for
a frame newer than the one already returned. It returns `{:error, error}` if
capture ends, fails, times out, or the camera dies. Closing the session releases
its subscription; capture stops when the last subscriber leaves.

## 3. Request a frame as a message

Now subscribe directly. The third argument checks the format you expect:

```elixir
{:ok, subscription} = BB.Camera.subscribe(CameraRobot, :eye, format: {:raw, :I420})
ref = subscription.ref
:ok = BB.Camera.request(subscription)

frame =
  receive do
    {:bb_camera, ^ref, %BB.Message{payload: %BB.Message.Camera.Frame{}} = message} ->
      message
  after
    2_000 -> raise "camera did not deliver a frame"
  end

frame.payload.sequence
:ok = BB.Camera.unsubscribe(subscription)
```

You requested one frame, so only one frame message arrived. In a consumer loop,
request the next frame after processing this one. Repeated requests before a
delivery do not build up demand. A slow consumer receives the newest frame
when it asks again.

A long-running consumer also handles `{:stream_info, info}`, `:end_of_capture`
and `{:capture_failed, error}` inside `{:bb_camera, ref, event}` messages, and
watches the subscription's monitor for `{:DOWN, monitor, :process, hub, reason}`.
A format notice leaves demand in place; an end or failure spends it, so request
again if staying subscribed for the next capture. See `BB.Camera.request/1`.

## 4. Read through Membrane

Add these dependencies to your application's `mix.exs`, fetch them with
`mix deps.get`, then restart IEx and start `CameraRobot` again:

```elixir
{:membrane_core, "~> 1.3"},
{:decimal, "~> 3.0", override: true}
```

`membrane_core` is optional, and `BB.Camera.Membrane.Source` is compiled only
when it is available. The top-level `decimal` override resolves Membrane's
`ratio` constraint against the version used by `bb`; see
[Membrane is optional](../../README.md#membrane-is-optional).

Use Membrane's testing sink to inspect one buffer. These helpers ship in
`membrane_core` and can be used from IEx:

```elixir
import Membrane.ChildrenSpec
import Membrane.Testing.Assertions

{:ok, _pipeline_supervisor, pipeline} =
  Membrane.Testing.Pipeline.start_link(
    spec:
      child(:camera, %BB.Camera.Membrane.Source{robot: CameraRobot, camera: :eye})
      |> child(:sink, %Membrane.Testing.Sink{autodemand: false})
  )

assert_sink_stream_format(pipeline, :sink, %Membrane.RawVideo{pixel_format: :I420}, 2_000)
:ok = Membrane.Testing.Pipeline.notify_child(pipeline, :sink, {:make_demand, 1})
assert_sink_buffer(pipeline, :sink, %Membrane.Buffer{} = buffer, 2_000)

{byte_size(buffer.payload), buffer.pts}
# => {28800, 0}

:ok = Membrane.Pipeline.terminate(pipeline)
```

Each buffer contains one raw frame. Its `pts` is nanoseconds since this source's
first frame; `buffer.metadata.bb_camera` retains the original capture timestamps
and sequence. In an application pipeline, connect the source to a scaler,
encoder or other element accepting `Membrane.RawVideo`. Pipeline demand controls
when the source asks for another frame.

By default a clean capture end ends the stream and releases the subscription.
Set `end_of_stream_on_capture_end?: false` on the source to keep it subscribed
and resume when capture restarts.

## 5. Preview the camera

The Cameras tab in `bb_liveview` can preview this same synthetic camera over
WebRTC. Follow its [Preview cameras guide](https://hexdocs.pm/bb_liveview/preview-cameras.html)
to add `bb_camera_webrtc` and mount the dashboard. Select `:eye` and start the
preview to see the grey bars moving.

When finished with the IEx robot:

```elixir
Supervisor.stop(robot)
```

## Next steps

- [Run an estimator on camera frames](../how-to/run-an-estimator-on-camera-frames.md).
- [Draw estimator results over video](../how-to/draw-estimator-results-over-video.md).
- [Why frames don't go on PubSub](../topics/why-frames-dont-go-on-pubsub.md).
