<!--
SPDX-FileCopyrightText: 2026 James Harton

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

# Draw estimator results over video

Implement `BB.Camera.Annotation` for an estimator's result payload to draw it
over the camera preview. Keep publishing the semantic result through the
estimator's usual output; the viewer derives drawing primitives from it.

You need an estimator nested under a camera, a result payload carrying the
source frame's dimensions, and a `bb_liveview` version with annotation support.
Set up the [WebRTC preview](https://hexdocs.pm/bb_liveview/preview-cameras.html)
first. For frame input and output timestamps, see
[Run an estimator on camera frames](run-an-estimator-on-camera-frames.md).

## Implement the protocol for the payload

The following example draws quadrilateral regions, with a dot at the first
corner and a label. It follows the implementation for
`BB.Message.Vision.Fiducials` in
[`bb_estimator_aruco`](https://github.com/beam-bots/bb_estimator_aruco).
Assume the detector's coordinates use integer pixel centres, as OpenCV does.

First define the result payload. Each region is a tuple of four `{x, y}` corners;
an empty regions list means nothing was found:

```elixir
defmodule MyRobot.Regions do
  defstruct [:width, :height, regions: []]

  use BB.Message,
    schema: [
      width: [type: :pos_integer, required: true],
      height: [type: :pos_integer, required: true],
      regions: [
        type: {:list, {:tuple, [
          {:tuple, [:float, :float]},
          {:tuple, [:float, :float]},
          {:tuple, [:float, :float]},
          {:tuple, [:float, :float]}
        ]}},
        default: []
      ]
    ]
end
```

Here each quadrilateral is stored as a tuple of four corners. Implement the
protocol in the package that owns this payload:

```elixir
defimpl BB.Camera.Annotation, for: MyRobot.Regions do
  import BB.Unit
  alias BB.Camera.Annotation.{Circle, Layer, Points, Text}

  @green %{red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0}
  @red %{red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0}
  @white %{red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0}

  def layer(result) do
    Layer.new!(
      width: result.width,
      height: result.height,
      lifetime: ~u(250 millisecond),
      primitives: Enum.flat_map(result.regions, &draw_region/1)
    )
  end

  defp draw_region(region) do
    corners = Enum.map(Tuple.to_list(region), fn {x, y} -> {x + 0.5, y + 0.5} end)
    [first | _] = corners

    [
      Points.new!(type: :line_loop, points: corners, outline_color: @green, thickness: 2.0),
      Circle.new!(position: first, diameter: 6.0, fill_color: @red),
      Text.new!(position: first, text: "region", font_size: 12.0, text_color: @white)
    ]
  end
end
```

Check the implementation with a payload before wiring up the viewer:

```elixir
{:ok, message} = MyRobot.Regions.new(:eye,
  width: 160,
  height: 120,
  regions: [{{20.0, 20.0}, {80.0, 20.0}, {80.0, 60.0}, {20.0, 60.0}}]
)

%BB.Camera.Annotation.Layer{primitives: [_, _, _]} =
  BB.Camera.Annotation.layer(message.payload)
```

The protocol receives the payload, not the envelope. Preserve the frame's
`monotonic_time`, `wall_time` and `frame_id` when the estimator constructs its
output with `BB.Message.new/4`; the viewer reads the envelope for expiry.

## Choose coordinates and primitives

Set the layer's `width` and `height` to the dimensions of the analysed frame,
not the displayed video element. The viewer scales it to the picture.
Coordinates are `{x, y}` in source pixels, rightwards and downwards, with
`{0, 0}` at the top-left **corner** of the top-left pixel. That pixel's centre
is `{0.5, 0.5}`. Add `0.5` to coordinates from a detector that uses integer
pixel centres, as the example does.

Use these primitives within the layer's `primitives` list:

| Primitive | Fields to supply |
|---|---|
| `BB.Camera.Annotation.Points` | `type` and `points`; optional `outline_color`, `fill_color`, `thickness` |
| `BB.Camera.Annotation.Circle` | `position` (centre), `diameter`; optional outline/fill colours and `thickness` |
| `BB.Camera.Annotation.Text` | `position` (label's bottom-left), `text`, `text_color`; optional `background_color`, `font_size` |

`Points.type` is `:points` for dots, `:line_strip` for connected segments,
`:line_loop` for a closed polygon, or `:line_list` for separate pairs of
endpoints. `fill_color` fills a line loop. Sizes and line widths are in source
pixels. A colour is `%{red: r, green: g, blue: b, alpha: a}`, with each channel
between `0` and `1`; `nil` for an optional colour omits that part of the drawing.
Primitives draw in list order, later ones on top.

## Replace, clear and expire a layer

Each publishing path owns one layer. Return its complete set of primitives
for every result: the next message replaces the entire previous layer, with
no per-primitive identifiers or update actions.

Publish an empty semantic result when nothing is found. In this example,
`regions: []` becomes `primitives: []`, which clears the previous drawing
immediately. Silence leaves it visible until its lifetime expires.

Set `lifetime` to a non-negative duration such as `~u(250 millisecond)`, long
enough to cover a few frame intervals. Expiry is counted from capture time,
so processing and delivery consume part of the lifetime before the layer is
shown. An already-expired result clears the layer. Use `:infinity` only when
you want it to stay until replaced or explicitly cleared.

## Show it in bb_liveview

Publish beneath the camera's topic. The default output of a nested estimator
already does this: an estimator `:regions` inside `:eye` on `:head` publishes
at `[:sensor, :head, :eye, :regions]`. An output path elsewhere will not be
associated with that camera's preview.

Open the Cameras tab and preview `:eye`. For each result payload with an
annotation implementation, `bb_liveview` draws the layer over the WebRTC video
and adds a toggle under **Overlays**, labelled with the publishing path's final
name (`regions` here). Each path is independent. Toggling a layer changes
visibility in that browser; it does not stop the estimator or its publishing.

Video and results travel separately. The overlay shows recent results over
live video; it does not hold video back to match a result to an exact frame.
Use capture timestamps and a finite lifetime to keep old detections from
lingering when processing stalls.
