<!--
SPDX-FileCopyrightText: 2026 James Harton

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

# Run an estimator on camera frames

Nest a `BB.Estimator` under a camera sensor to process its raw frames. This
guide assumes you can write an estimator; see the
[BB state estimation tutorial](https://hexdocs.pm/bb/13-state-estimation.html)
for the callback contract.

## Read the frame message

`handle_input/2` receives a `%BB.Message{payload: %BB.Message.Camera.Frame{}}`.
The envelope's `frame_id` is the camera's sensor name; `monotonic_time` and
`wall_time` are capture times in nanoseconds, and `node` identifies the
capturing BEAM node. The payload carries `format`, `width`, `height`, `data`
and `sequence`, along with the hub's frame-rate and joint-configuration fields.

For I420, the first `width * height` bytes are the Y plane: one unsigned byte
per pixel, tightly packed in row order. Read it directly for a greyscale
algorithm. The following estimator computes mean luma and emits a small
result stamped with the original capture time:

```elixir
defmodule MyRobot.Brightness do
  defstruct [:mean, :width, :height]

  use BB.Message,
    schema: [
      mean: [type: :float, required: true],
      width: [type: :pos_integer, required: true],
      height: [type: :pos_integer, required: true]
    ]
end

defmodule MyRobot.MeanLuma do
  use BB.Estimator

  alias BB.Message
  alias BB.Message.Camera.Frame

  @impl BB.Estimator
  def init(_opts), do: {:ok, %{}}

  @impl BB.Estimator
  def handle_input(%Message{payload: %Frame{format: {:raw, :I420}} = frame} = message, state) do
    size = frame.width * frame.height
    luma = binary_part(frame.data, 0, size)
    sum = for <<value <- luma>>, reduce: 0 do
      total -> total + value
    end

    {:ok, output} =
      Message.new(
        MyRobot.Brightness,
        message.frame_id,
        [mean: sum / size, width: frame.width, height: frame.height],
        monotonic_time: message.monotonic_time,
        wall_time: message.wall_time
      )

    {:reply, [out: output], state}
  end

  def handle_input(_other_format, state), do: {:noreply, state}
end
```

Check the payload format before interpreting its bytes. The hub supports other
raw pixel formats too; this estimator deliberately ignores them. With `evision`,
you can make a single-channel matrix from the same Y plane with
`Evision.Mat.from_binary(luma, {:u, 8}, frame.height, frame.width, 1)`.

Keep the capture timestamp on derived outputs using `BB.Message.new/4`, as
above. Downstream age checks and annotation expiry then use when the scene
was seen. Leaving out the options would stamp when processing finished.

## Nest it under the camera

```elixir
defmodule MyRobot do
  use BB

  topology do
    link :head do
      sensor :eye, {BB.Camera.Synthetic, width: 160, height: 120, clock: {:rate, 10}} do
        estimator :brightness, MyRobot.MeanLuma do
          max_input_age ~u(100 millisecond)
          latency_budget ~u(50 millisecond)
          lost_after ~u(1 second)
          recover_after 3
        end
      end
    end
  end
end
```

Every driver using `use BB.Camera` selects `BB.Camera.EstimatorSource` for its
nested estimators. Do not add an `input` block or subscribe to raw frames on
PubSub. The estimator's subscription starts capture even with no preview open.
Read its results at `[:sensor, :head, :eye, :brightness]` using `BB.subscribe/2`.

The server requests another frame only after the previous dispatch finishes.
If processing is slower than capture, the next input is the newest frame and
intermediate frames are skipped. Keep processing inside the dispatch; handing
every frame to a new asynchronous task would remove that processing bound.

## Set health limits

Choose the estimator's limits according to these measurements:

| Setting or measurement | What it measures |
|---|---|
| `max_input_age` | Capture to intake, using the envelope's `monotonic_time`; older frames are dropped with reason `:stale_input` |
| `latency_budget` | Time spent in `handle_input/2`; an overrun degrades health with `:latency_overrun` |
| `lost_after` | Time since the last driver input passed intake checks, or since startup before the first input |
| Latency telemetry `input_to_output` | Capture to output emission, including time before the callback began |

`lost_after` and `latency_budget` are not capture-age limits. A stale or
cross-node frame does not reset the lost timer. Callbacks run in the estimator
process, so a blocked callback also delays handling its timer messages.

A capture failure moves the estimator to `:lost` with `:source_failed` and
requests again. The hub retries failed capture with backoff while subscribers
remain; the estimator recovers when in-budget processing resumes. A clean
capture end spends demand and requests again without an immediate health
transition. If the hub dies, the source reports `:source_ended`; the estimator
moves to `:lost` and stops requesting from it. The sensor's supervisor restarts
the sensor first, then its nested estimators against the replacement hub.

Use `on_degraded`, `on_lost` and `on_recovered` to connect these transitions to
robot commands, as in [Configure estimator health](https://hexdocs.pm/bb/configure-estimator-health.html).

## Test without hardware

Use `BB.Camera.Synthetic` with `clock: :external` and produce one frame per
assertion. `BB.Test.RecordingEstimator` from `bb` reports every dispatched
input to the test process:

```elixir
defmodule CameraInputTest do
  use ExUnit.Case, async: false

  defmodule Robot do
    use BB

    topology do
      link :head do
        sensor :eye, {BB.Camera.Synthetic, clock: :external} do
          estimator :recorder, BB.Test.RecordingEstimator
        end
      end
    end
  end

  test "the nested estimator receives a frame" do
    key = {BB.Test.RecordingEstimator, Robot}
    :persistent_term.put(key, self())
    on_exit(fn -> :persistent_term.erase(key) end)
    start_supervised!(Robot)

    # The estimator subscribed during startup. This call passes through the
    # driver after its queued start-capture request has been handled.
    :sys.get_state(BB.Process.whereis(Robot, :eye))

    :ok = BB.Camera.Synthetic.capture_frame(Robot, :eye)
    assert_receive {:received, :input,
                    %BB.Message{frame_id: :eye, payload: %BB.Message.Camera.Frame{sequence: 0}}}
  end
end
```

For a slow-consumer test, use `{BB.Test.RecordingEstimator, gated: true}`.
Wait for `{:received, :holding, frame}`, capture more frames, then send the
estimator process `:release`. It reports the held input and then holds the
newest frame. Release every held frame before ending the test. This tests
backpressure without sleeps or assumptions about scheduler speed.

For an algorithm test, pass known I420 binaries in Synthetic's `:frames`
option, with matching even `:width` and `:height`, and subscribe to the
estimator's output before calling `capture_frame/2`.

## Worked example

[`bb_estimator_aruco`](https://github.com/beam-bots/bb_estimator_aruco) implements
`BB.Estimator.ArUco` using `evision`. It reads the Y plane, publishes
`BB.Message.Vision.Fiducials` with marker IDs and four corners per marker, and
preserves capture time. A frame with no markers emits an empty result. Its
payload also implements `BB.Camera.Annotation`; see
[Draw estimator results over video](draw-estimator-results-over-video.md).
