# `NanoKVMGo.Video`
[🔗](https://github.com/cocoa-xu/nano_kvm_go/blob/v0.4.0/lib/nano_kvm_go/video.ex#L1)

Capture of the HDMI/DisplayPort input with the hardware encoders.

The process runs the `nano_kvm_go_video` port program. It captures the input
at the input's own size and encodes each frame from the capture buffer, with
no copy:

  * to JPEG, which the program serves itself as MJPEG over HTTP:
    `http://<device>:<mjpeg_port>/stream.mjpg`, with a viewer page at `/`
  * to H.264 or H.265 (Annex B), sent to the subscribers while there are
    any

When the input changes, the program stops and starts again at the new size;
subscribers get the new input, then a keyframe.

## Options

  * `:name` - the name to register, `NanoKVMGo.Video` by default
  * `:mjpeg_port` - the TCP port of the MJPEG server, 8088 by default
  * `:mjpeg_token` - a token the MJPEG stream asks for,
    `/stream.mjpg?token=<token>`: at least 16 of the characters `A-Z`,
    `a-z`, `0-9`, `-` and `_`, which go in a URL as they are, such as
    `Base.url_encode64(:crypto.strong_rand_bytes(18), padding: false)`.
    Without one the stream and a viewer page are open to anyone who
    reaches the port
  * `:jpeg_quality` - 1 to 100, 60 by default
  * `:encoding` - how the stream is encoded, see `t:encoding/0`: the
    codec every subscriber decodes, VBR of up to 8 Mbit/s at QP 24,
    keyframes only when a subscriber needs one, by default. Or `{module, function, args}`
    that returns it, called each time the process starts: a restart by
    its supervisor then takes the encoding saved last, a user's settings
    say
  * `:devices` - the devices to capture and encode with, see
    `t:devices/0`, by default the board's, found by their drivers each
    time the capture starts
  * `:capture_buffers` - how many frames the capture holds, 2 to 6, which
    the encoders read in place: by default four with a video CMA pool of
    176 MiB or more, three with less, as on the Go with 256 MiB (see
    `NanoKVMGo.CMA`)
  * `:program` - the port program, the library's `nano_kvm_go_video` by
    default

## Messages

Subscribers receive:

  * `{NanoKVMGo.Video, {:input, input}}` when subscribing and when the input
    changes, once the capture knows it, see `t:input/0`
  * `{NanoKVMGo.Video, {codec, :key | :delta, data}}`, one access unit each
    of the codec, `:h264` or `:h265`, starting with a keyframe. The
    parameter sets come before every keyframe. When the codec changes, the
    next access unit is a keyframe of the new one. A subscriber that asks
    for timestamps gets `{codec, :key | :delta, data, microseconds}`, the
    capture's frame-end time in microseconds, calibrated to the VM's
    monotonic clock when the port starts. Intervals follow the capture
    clock, independent of pipe, process and network delays.
  * `{NanoKVMGo.Video, {:stats, stats}}` once a second while the stream
    runs: what the capture and the encoder did, see `t:stats/0`

A subscriber with more than 30 messages waiting misses the deltas until
it has caught up, then gets a keyframe, asked for then. One on another
node gets them all: its messages waiting cannot be counted.

## EDID

The bridge presents an EDID to the source, kept in its flash: `edid/1`
reads it and `set_edid/2` replaces it, with or without the process.

# `devices`

```elixir
@type devices() :: %{
  :capture =&gt; Path.t(),
  :jpeg =&gt; Path.t(),
  optional(:encoder) =&gt; Path.t() | nil
}
```

The video devices: the capture's, the JPEG encoder's and, for the stream,
the H.264 and H.265 encoder's.

# `edid_option`

```elixir
@type edid_option() :: {:device, Path.t()} | {:program, Path.t()}
```

# `encoding`

```elixir
@type encoding() :: %{
  codec: :auto | :h264 | :h265,
  rate_control: :constant_qp | :cbr | :vbr,
  bitrate: pos_integer(),
  qp: 0..51,
  keyframe_interval: non_neg_integer(),
  max_fps: non_neg_integer(),
  color_matrix: :auto | :bt601 | :bt709,
  color_range: :auto | :full | :limited
}
```

How the stream is encoded:

  * `:codec` - `:h264`, `:h265`, or `:auto` for H.265 while every
    subscriber decodes it and H.264 otherwise (see `subscribe/2`)
  * `:rate_control` - `:constant_qp`, every frame at `:qp`; `:cbr`, at a
    constant `:bitrate`; `:vbr`, at `:qp` unless the bitrate would go over
    `:bitrate`, then at the QP that keeps it
  * `:bitrate` - bits a second: what CBR keeps to, the most VBR takes
  * `:qp` - the quantizer, 0 (the best picture) to 51: constant QP's, the
    best VBR goes to
  * `:keyframe_interval` - frames from a keyframe to the next, unless one
    is asked for sooner; 0 for keyframes only when a subscriber needs one,
    starting or catching up: a stream that loses nothing needs no others
  * `:max_fps` - frames a second at most, 0 for as many as the input has
  * `:color_matrix` - the matrix that turns the samples into RGB,
    `:bt601` or `:bt709`
  * `:color_range` - whether the samples use the `:full` range or the
    `:limited` one

The bitrate a still picture takes is low whatever the rate control: CBR
and VBR save no bits for later.

Where the capture converts the colour (the system's HDMI bridge driver
from linux-ax620e 4bd74a0 on), the bridge turns the picture into the
colour asked for, and the streams and snapshots carry it; `:auto` keeps
the bridge's own choice, BT.709 at full range for a computer's RGB. JPEG
decoders take BT.601 for granted: with BT.709 the MJPEG stream shows the
strongest colours a little off, with `:bt601` right. Elsewhere the colour
only labels the samples as the bridge hands them over: `:auto` is that,
BT.709 at full range, and another label shifts the colours a decoder shows.

# `input`

```elixir
@type input() ::
  %{width: pos_integer(), height: pos_integer(), fps: non_neg_integer()}
  | :none
  | :unsupported
```

The signal at the input, as the LT7911EXC bridge reports it: the size of
a frame in pixels and the frame rate, `:none` without a signal, or
`:unsupported` for a signal the bridge cannot pass on.

# `message`

```elixir
@type message() ::
  {NanoKVMGo.Video,
   {:input, input()}
   | {:h264 | :h265, :key | :delta, binary()}
   | {:h264 | :h265, :key | :delta, binary(), integer()}
   | {:stats, stats()}}
```

A message to subscribers, see the module documentation.

# `option`

```elixir
@type option() ::
  {:name, GenServer.name()}
  | {:mjpeg_port, :inet.port_number()}
  | {:mjpeg_token, String.t() | nil}
  | {:jpeg_quality, 1..100}
  | {:encoding, keyword() | map() | {module(), atom(), [term()]}}
  | {:devices, devices() | nil}
  | {:capture_buffers, 2..6 | :auto}
  | {:program, Path.t()}
```

# `region`

```elixir
@type region() ::
  {non_neg_integer(), non_neg_integer(), non_neg_integer(), non_neg_integer()}
```

A rectangle of the input's pixels: `{x, y, width, height}`.

# `snapshot`

```elixir
@type snapshot() :: %{
  width: non_neg_integer(),
  height: non_neg_integer(),
  data: binary()
}
```

A picture of `snapshot/3`: RGB, three bytes a pixel, rows top to bottom.

# `stats`

```elixir
@type stats() :: %{optional(atom()) =&gt; number()}
```

What the stream did over the last `:seconds`: frames `:captured`,
`:encoded`, and `:skipped`, held while the encoder was busy and then
passed by a newer one; the time a frame took through the encoder, `:encode_ms` on
average and `:encode_max_ms` at most; from the end of a frame to the
program having it, `:dequeue_ms` and `:dequeue_max_ms`, and to its coming
out of the encoder, `:ready_ms` and `:ready_max_ms`; the `:bytes` sent; the QP, `:qp` on
average and `:qp_max`; the keyframes, `:keys`.

Writer samples (`:writer_frames`) report mean/max `:writer_queue_ms`,
`:copy_ms`, and `:pipe_ms`, including scheduling or blocking in each stage.
`:port_ms` and `:port_max_ms` measure capture EOF to this process handling
the packet, over `:port_frames` samples. These windows need not contain
the same frames as the encoder window. `:key_bytes`, `:key_max_bytes`,
and `:delta_max_bytes` expose encoded bursts.

# `subscribe_option`

```elixir
@type subscribe_option() :: {:codecs, [:h264 | :h265, ...]} | {:timestamps, boolean()}
```

An option of `subscribe/2`: the codecs the subscriber decodes, and whether
access units come with their timestamps.

# `capture_stats`

```elixir
@spec capture_stats() :: %{
  mid_frame_stops: non_neg_integer() | nil,
  csi_recoveries: non_neg_integer() | nil
}
```

Counters of the capture driver since the device started, `nil` when the
driver does not have them:

  * `:mid_frame_stops` - captures stopped in the middle of a frame; input
    changes cause them
  * `:csi_recoveries` - restarts of the CSI-2 receiver after receive errors

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `codec`

```elixir
@spec codec(GenServer.server()) :: :h264 | :h265
```

The codec the stream takes now, `:h264` or `:h265`: the encoding's, or
for `:auto` the one every subscriber decodes.

# `edid`

```elixir
@spec edid([edid_option()]) :: {:ok, binary()} | {:error, term()}
```

The EDID the input presents to the source: one to four blocks of 128 bytes.

The first read takes over a second, as the bridge reads its flash.
`NanoKVMGo.EDID.decode/1` tells what it says. A failure of the
`nano_kvm_go_edid` program gives `{:error, {:exit_status, status,
output}}`.

## Options

  * `:device` - the video capture device, by default the board's
  * `:program` - the program that reads and stores the EDID, the
    library's `nano_kvm_go_edid` by default

# `encoding`

```elixir
@spec encoding(GenServer.server()) :: encoding()
```

How the stream is encoded, see `t:encoding/0`.

# `input`

```elixir
@spec input(GenServer.server()) :: input() | nil
```

The current input, `nil` until known.

# `request_keyframe`

```elixir
@spec request_keyframe(GenServer.server()) :: :ok
```

Asks for a keyframe soon.

# `set_edid`

```elixir
@spec set_edid(binary(), [edid_option()]) :: :ok | {:error, term()}
```

Stores an EDID for the input to present to the source, one that
`NanoKVMGo.EDID.valid?/1` takes. Takes a few seconds.

The source reads it when it next connects, for example when the NanoKVM is
plugged in again. Read the current EDID with `edid/1` first to be able to
go back to it. The options are those of `edid/1`.

# `set_encoding`

```elixir
@spec set_encoding(GenServer.server(), keyword() | map()) :: encoding()
```

Changes how the stream is encoded, from the next frame: the keys given, see
`t:encoding/0`. Returns the encoding, and raises `ArgumentError` for one
it does not take.

    NanoKVMGo.Video.set_encoding(codec: :h265, rate_control: :cbr, bitrate: 3_000_000)

# `snapshot`

```elixir
@spec snapshot(GenServer.server(), region() | :all, timeout()) ::
  {:ok, snapshot()} | {:error, :no_input | :timeout | :stopped}
```

A region of the next captured picture, `{x, y, width, height}` in the
input's pixels, or the whole of it, as RGB: three bytes a pixel, rows top
to bottom, in the colours the streams declare. A region partly outside the
picture is cut to it, one outside gives an empty picture.

`{:error, :no_input}` without a picture to take it from, `:timeout` when
none came within `timeout` milliseconds, `:stopped` when the capture
stopped first.

# `start_link`

```elixir
@spec start_link([option()]) :: GenServer.on_start()
```

Starts the capture. See the module documentation for the options.

# `stats`

```elixir
@spec stats(GenServer.server()) :: stats() | nil
```

The stream's last second, see `t:stats/0`; `nil` while it does not run.

# `subscribe`

```elixir
@spec subscribe(GenServer.server(), [subscribe_option()]) ::
  :ok | {:error, :no_encoder}
```

Sends the input and the stream to the caller until it unsubscribes or
exits. Returns `{:error, :no_encoder}` without the H.264 and H.265 encoder.

The option `:codecs` names those the caller decodes, `[:h264]` by
default: with the `:auto` codec the stream takes H.265 while every
subscriber decodes it. With `timestamps: true` each access unit comes
with the time it came from the encoder (see the module documentation).
Subscribing again changes them. With options, name the server first:

    NanoKVMGo.Video.subscribe(NanoKVMGo.Video, codecs: [:h264, :h265])

# `unsubscribe`

```elixir
@spec unsubscribe(GenServer.server()) :: :ok
```

Stops sending to the caller.

---

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