# `BB.Camera.Synthetic`
[🔗](https://github.com/beam-bots/bb_camera/blob/main/lib/bb/camera/synthetic.ex#L5)

A camera with no camera behind it.

A complete `BB.Sensor` + `BB.Camera` driver that produces raw `:I420` frames
from a generated test pattern. Drop it anywhere a real camera would go: in
tests, in a preview UI on a machine with no hardware attached, or as the
worked example to copy when writing a driver that does talk to something.

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

## Clocking

`{:rate, hertz}` runs a `BB.Loop` and produces frames on its own, which is
what you want behind a UI.

`:external` produces a frame only when `capture_frame/2` is called, which is
what you want in a test. It makes the whole pipeline deterministic: ask for a
frame, produce one, assert you received it, with no sleeps and nothing
racing. Every test in this package is written that way.

    {:ok, sub} = BB.Camera.subscribe(MyRobot, :eye)
    :ok = BB.Camera.request(sub)
    :ok = BB.Camera.Synthetic.capture_frame(MyRobot, :eye)
    assert_receive {:bb_camera, ^ref, %BB.Camera.Frame{}}

## Frames

By default it cycles through `default_frames/2`: vertical bars of grey that
shift along each frame, at whatever size it was asked for. `:I420` subsamples
its chroma by two in each direction, so the width and height must both be
even. `:frames` replaces them with your own, which must be `:I420` at the
configured size.

# `capture_frame`

```elixir
@spec capture_frame(module(), atom()) :: :ok | {:error, struct()}
```

Produce one frame now.

Only meaningful with `clock: :external`. Synchronous: it returns once the hub
has taken the frame, so a test can request, capture and assert without
waiting on anything.

Returns `{:error, %BB.Error.State.Camera.NotCapturing{}}` until a consumer
has subscribed *and* this driver has confirmed capture started. Subscribing
is not enough: the hub asks the driver to start and the driver answers
asynchronously, so a test that opens a session and immediately captures will
race that answer.

Wait for the event rather than guessing at the gap:

    BB.subscribe(MyRobot, [:sensor, :head, :eye])
    {:ok, session} = BB.Camera.Media.open(MyRobot, :eye)
    assert_receive {:bb, _, %BB.Message{payload: %BB.Message.Camera.BeginCapture{}}}

    :ok = BB.Camera.Synthetic.capture_frame(MyRobot, :eye)

Anything driving an externally clocked camera from behind a consumer needs
this, so it is worth doing once in a test `setup`.

# `default_frames`

```elixir
@spec default_frames(pos_integer(), pos_integer()) :: [binary()]
```

The `:I420` frames this camera cycles through by default at `width` x
`height`.

Vertical bars of grey, shifted along by a quarter of the width each frame,
with neutral chroma. Every frame differs from the others, so a test can tell
which one it was handed.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
