# `Octoroom.Worker`
[🔗](https://github.com/samrat/octoroom/blob/v0.1.0/lib/octoroom/worker.ex#L1)

A server-side participant: a process that hears input tracks and plays
output tracks as PCM, with no WebRTC in sight.

    defmodule MyApp.DelayEcho do
      use Octoroom.Worker, audio: [rate: 16_000, channels: 1]

      @impl true
      def init(_args, _ctx), do: {:ok, :queue.new()}

      @impl true
      def handle_audio(_input, pcm, q) do
        q = :queue.in(pcm, q)

        if :queue.len(q) > 100 do
          {{:value, out}, q} = :queue.out(q)
          {:ok, q, play: {:default, out}}
        else
          {:ok, q}
        end
      end
    end

A room starts workers from its `workers/1` callback (see
`Octoroom.Room.worker/3`). `audio:` picks the PCM format the worker sees,
s16le at a `rate` dividing 48 kHz and 1 or 2 `channels` (default 48 kHz
stereo, the room's own format). The worker plays audio in the same format
unless `output:` gives another, for a worker that hears at one rate and
speaks at another:

    use Octoroom.Worker, audio: [rate: 16_000, channels: 1, output: [rate: 24_000]]

Callbacks return `{:ok, state}` or `{:ok, state, actions}`, where actions
is a keyword list of:

  * `play: {output, pcm}`: queue `pcm` on an output track. Outputs are
    paced to real time, so a worker can hand over audio faster than it
    plays. `:default` is the worker's first output.
  * `flush: output`: drop that output's queued, unplayed audio (barge-in).
    The worker then gets `handle_info({:octoroom, :flushed, output,
    dropped_ms}, state)`: how many ms of audio were dropped (nil if the
    output's outlet wasn't running), so what it queued minus `dropped_ms`
    is what listeners heard, give or take the frame on its way.
  * `emit: event`: broadcast `{:worker_event, worker_id, event}` to the
    room's `scope: :room` subscribers (see `Octoroom.subscribe/2`). Any
    term; it never reaches clients.
  * `notify: {output, type, data}`: an event for clients. It goes to the
    participants subscribed to `output` (an audio or data output;
    `:default` is the first of either): to their clients as a
    `worker_event` and to their `scope: {:participant, id}` subscribers
    as `{:worker_notify, worker_id, output, type, data}`, and to
    `scope: :room` subscribers. `type` is a string and `data` a map that
    encodes as JSON; anything else raises.
  * `notify: {output, type, data, participant_id}`: the same, for one
    participant only, and not to `scope: :room` subscribers. Dropped if
    that participant isn't subscribed to `output`. For catching up a
    participant that just subscribed.
  * `presence: %{state: string | nil, attributes: map}`: what clients
    show for this worker, replacing what it set before (missing keys
    reset). It goes to everyone subscribed to any of its outputs, now
    and as they subscribe. After a restart, `state` is nil until the
    worker sets it again; `attributes` are kept.
  * `save: term`: keep `term` in the store (`Octoroom.Store`) as what
    this worker would need to carry on, such as its conversation so far.
    Each save replaces the last. The worker's next start in the same room
    gets it as `ctx.saved`: after a crash, a change of args, or the node
    restarting mid-call. It's deleted when the room stops the worker
    because `workers/1` no longer lists it, and when the room stops
    because its last participant left. Keep it small: it's written on
    every save.

`handle_info/2` also receives:

  * `{:octoroom, :inputs, names}`, `{:octoroom, :outputs, names}` and
    `{:octoroom, :data, names}` when the room changes the worker's
    inputs, outputs or data outputs; the worker keeps running. A change
    of module or args restarts it.
  * `{:octoroom, :subscribed, participant_id, output}` and
    `{:octoroom, :unsubscribed, participant_id, output}` as participants
    start and stop receiving one of its outputs (an audio subscription
    counts once its pull is open). After a restart, the worker gets
    `:subscribed` for everyone already subscribed.

A worker that crashes is restarted by its room, with backoff. Its output
tracks stay published while it restarts, so listeners hear a gap rather
than a renegotiation.

# `actions`

```elixir
@type actions() :: [
  play: {String.t() | :default, binary()},
  flush: String.t() | :default,
  emit: term(),
  notify:
    {String.t() | :default, String.t(), map()}
    | {String.t() | :default, String.t(), map(), String.t()},
  presence: %{
    optional(:state) =&gt; String.t() | nil,
    optional(:attributes) =&gt; map()
  },
  save: term()
]
```

# `result`

```elixir
@type result() :: {:ok, state()} | {:ok, state(), actions()}
```

# `state`

```elixir
@type state() :: term()
```

# `video_frame`

```elixir
@type video_frame() :: %{
  data: binary(),
  mime_type: String.t(),
  width: pos_integer() | nil,
  height: pos_integer() | nil,
  source: String.t(),
  participant_id: String.t()
}
```

# `handle_audio`
*optional* 

```elixir
@callback handle_audio(input :: String.t(), pcm :: binary(), state()) :: result()
```

# `handle_info`
*optional* 

```elixir
@callback handle_info(message :: term(), state()) :: result()
```

# `handle_video`
*optional* 

```elixir
@callback handle_video(input :: String.t(), frame :: video_frame(), state()) :: result()
```

# `init`

```elixir
@callback init(args :: term(), ctx :: Octoroom.Worker.Context.t()) ::
  result() | {:stop, reason :: term()}
```

# `terminate`
*optional* 

```elixir
@callback terminate(reason :: term(), state()) :: term()
```

# `saved`

What worker `id` in room `room_id` last saved (the `save:` action), or
nil. For apps that show what a worker kept, such as a conversation, while
the room is down or before its workers have started again.

# `send`

Sends `message` to a running worker's `handle_info/2`, for example from a
LiveView. Returns `:ok`, or `{:error, :no_worker}`.

# `whereis`

The pid of worker `id` in room `room_id`, or nil.

---

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