Memory-to-Memory Stateful Video Encoder Interface

A stateful video encoder takes raw video frames in display order and encodes them into a bytestream. It generates complete chunks of the bytestream, including all metadata, headers, etc. The resulting bytestream does not require any further post-processing by the client.

Performing software stream processing, header generation etc. in the driver in order to support this interface is strongly discouraged. In case such operations are needed, use of the Stateless Video Encoder Interface (in development) is strongly advised.

Conventions and Notations Used in This Document #

  1. The general V4L2 API rules apply if not specified in this document otherwise.

  2. The meaning of words "must", "may", "should", etc. is as per RFC 2119.

  3. All steps not marked "optional" are required.

  4. VIDIOC_G_EXT_CTRLS() and VIDIOC_S_EXT_CTRLS() may be used interchangeably with VIDIOC_G_CTRL() and VIDIOC_S_CTRL(), unless specified otherwise.

  5. Single-planar API (see Single- and multi-planar APIs) and applicable structures may be used interchangeably with multi-planar API, unless specified otherwise, depending on encoder capabilities and following the general V4L2 guidelines.

  6. i = [a..b]: sequence of integers from a to b, inclusive, i.e. i = [0..2]: i = 0, 1, 2.

  7. Given an OUTPUT buffer A, then A' represents a buffer on the CAPTURE queue containing data that resulted from processing buffer A.

Glossary #

Refer to Glossary.

State Machine #

flowchart TB
  n0((("Encoding")))
  n1(("Initialization"))
  n2(("Stopped"))
  n3(("Drain"))
  n4(("Reset"))
  n5(("#160;"))
  n5 -->|"open()"| n1
  n1 -->|"Both queues streaming"| n0
  n0 -->|"V4L2_ENC_CMD_STOP"| n3
  n0 -->|"VIDIOC_STREAMOFF(CAPTURE)"| n4
  n0 -->|"VIDIOC_STREAMOFF(OUTPUT)"| n2
  n0 --> n0
  n3 -->|"All CAPTURE<br/>buffers dequeued<br/>or<br/>VIDIOC_STREAMOFF(OUTPUT)"| n2
  n3 -->|"VIDIOC_STREAMOFF(CAPTURE)"| n4
  n4 -->|"VIDIOC_STREAMON(CAPTURE)"| n0
  n4 -->|"VIDIOC_REQBUFS(OUTPUT, 0)"| n1
  n2 -->|"V4L2_ENC_CMD_START<br/>or<br/>VIDIOC_STREAMON(OUTPUT)"| n0
  n2 -->|"VIDIOC_STREAMOFF(CAPTURE)"| n4
  style n5 fill:#333,stroke:#333

Encoder State Machine

Querying Capabilities #

  1. To enumerate the set of coded formats supported by the encoder, the client may call VIDIOC_ENUM_FMT() on CAPTURE.

    • The full set of supported formats will be returned, regardless of the format set on OUTPUT.
  2. To enumerate the set of supported raw formats, the client may call VIDIOC_ENUM_FMT() on OUTPUT.

    • Only the formats supported for the format currently active on CAPTURE will be returned.

    • In order to enumerate raw formats supported by a given coded format, the client must first set that coded format on CAPTURE and then enumerate the formats on OUTPUT.

  3. The client may use VIDIOC_ENUM_FRAMESIZES() to detect supported resolutions for a given format, passing the desired pixel format in v4l2_frmsizeenum pixel_format.

    • Values returned by VIDIOC_ENUM_FRAMESIZES() for a coded pixel format will include all possible coded resolutions supported by the encoder for the given coded pixel format.

    • Values returned by VIDIOC_ENUM_FRAMESIZES() for a raw pixel format will include all possible frame buffer resolutions supported by the encoder for the given raw pixel format and coded format currently set on CAPTURE.

  4. The client may use VIDIOC_ENUM_FRAMEINTERVALS() to detect supported frame intervals for a given format and resolution, passing the desired pixel format in v4l2_frmivalenum pixel_format and the resolution in v4l2_frmivalenum width and v4l2_frmivalenum height.

    • Values returned by VIDIOC_ENUM_FRAMEINTERVALS() for a coded pixel format and coded resolution will include all possible frame intervals supported by the encoder for the given coded pixel format and resolution.

    • Values returned by VIDIOC_ENUM_FRAMEINTERVALS() for a raw pixel format and resolution will include all possible frame intervals supported by the encoder for the given raw pixel format and resolution and for the coded format, coded resolution and coded frame interval currently set on CAPTURE.

    • Support for VIDIOC_ENUM_FRAMEINTERVALS() is optional. If it is not implemented, then there are no special restrictions other than the limits of the codec itself.

  5. Supported profiles and levels for the coded format currently set on CAPTURE, if applicable, may be queried using their respective controls via VIDIOC_QUERYCTRL().

  6. Any additional encoder capabilities may be discovered by querying their respective controls.

Initialization #

  1. Set the coded format on the CAPTURE queue via VIDIOC_S_FMT().

    • Required fields:

      • type

        a V4L2_BUF_TYPE_* enum appropriate for CAPTURE.

      • pixelformat

        the coded format to be produced.

      • sizeimage

        desired size of CAPTURE buffers; the encoder may adjust it to match hardware requirements.

      • width, height

        ignored (read-only).

      • other fields

        follow standard semantics.

    • Returned fields:

      • sizeimage

        adjusted size of CAPTURE buffers.

      • width, height

        the coded size selected by the encoder based on current state, e.g. OUTPUT format, selection rectangles, etc. (read-only).

  2. Optional. Enumerate supported OUTPUT formats (raw formats for source) for the selected coded format via VIDIOC_ENUM_FMT().

    • Required fields:

      • type

        a V4L2_BUF_TYPE_* enum appropriate for OUTPUT.

      • other fields

        follow standard semantics.

    • Returned fields:

      • pixelformat

        raw format supported for the coded format currently selected on the CAPTURE queue.

      • other fields

        follow standard semantics.

  3. Set the raw source format on the OUTPUT queue via VIDIOC_S_FMT().

    • Required fields:

      • type

        a V4L2_BUF_TYPE_* enum appropriate for OUTPUT.

      • pixelformat

        raw format of the source.

      • width, height

        source resolution.

      • other fields

        follow standard semantics.

    • Returned fields:

      • width, height

        may be adjusted to match encoder minimums, maximums and alignment requirements, as required by the currently selected formats, as reported by VIDIOC_ENUM_FRAMESIZES().

      • other fields

        follow standard semantics.

    • Setting the OUTPUT format will reset the selection rectangles to their default values, based on the new resolution, as described in the next step.

  4. Set the raw frame interval on the OUTPUT queue via VIDIOC_S_PARM(). This also sets the coded frame interval on the CAPTURE queue to the same value.

    • Required fields:

      • type

        a V4L2_BUF_TYPE_* enum appropriate for OUTPUT.

      • parm.output

        set all fields except parm.output.timeperframe to 0.

      • parm.output.timeperframe

        the desired frame interval; the encoder may adjust it to match hardware requirements.

    • Returned fields:

      • parm.output.timeperframe

        the adjusted frame interval.

  5. Optional Set the coded frame interval on the CAPTURE queue via VIDIOC_S_PARM(). This is only necessary if the coded frame interval is different from the raw frame interval, which is typically the case for off-line encoding. Support for this feature is signalled by the V4L2_FMT_FLAG_ENC_CAP_FRAME_INTERVAL format flag.

    • Required fields:

      • type

        a V4L2_BUF_TYPE_* enum appropriate for CAPTURE.

      • parm.capture

        set all fields except parm.capture.timeperframe to 0.

      • parm.capture.timeperframe

        the desired coded frame interval; the encoder may adjust it to match hardware requirements.

    • Returned fields:

      • parm.capture.timeperframe

        the adjusted frame interval.

  6. Optional. Set the visible resolution for the stream metadata via VIDIOC_S_SELECTION() on the OUTPUT queue if it is desired to be different than the full OUTPUT resolution.

    • Required fields:

      • type

        a V4L2_BUF_TYPE_* enum appropriate for OUTPUT.

      • target

        set to V4L2_SEL_TGT_CROP.

      • r.left, r.top, r.width, r.height

        visible rectangle; this must fit within the V4L2_SEL_TGT_CROP_BOUNDS rectangle and may be subject to adjustment to match codec and hardware constraints.

    • Returned fields:

      • r.left, r.top, r.width, r.height

        visible rectangle adjusted by the encoder.

    • The following selection targets are supported on OUTPUT:

      • V4L2_SEL_TGT_CROP_BOUNDS

        equal to the full source frame, matching the active OUTPUT format.

      • V4L2_SEL_TGT_CROP_DEFAULT

        equal to V4L2_SEL_TGT_CROP_BOUNDS.

      • V4L2_SEL_TGT_CROP

        rectangle within the source buffer to be encoded into the CAPTURE stream; defaults to V4L2_SEL_TGT_CROP_DEFAULT.

  7. Allocate buffers for both OUTPUT and CAPTURE via VIDIOC_REQBUFS(). This may be performed in any order.

    • Required fields:

      • count

        requested number of buffers to allocate; greater than zero.

      • type

        a V4L2_BUF_TYPE_* enum appropriate for OUTPUT or CAPTURE.

      • other fields

        follow standard semantics.

    • Returned fields:

      • count

        actual number of buffers allocated.

    Alternatively, VIDIOC_CREATE_BUFS() can be used to have more control over buffer allocation.

    • Required fields:

      • count

        requested number of buffers to allocate; greater than zero.

      • type

        a V4L2_BUF_TYPE_* enum appropriate for OUTPUT.

      • other fields

        follow standard semantics.

    • Returned fields:

      • count

        adjusted to the number of allocated buffers.

  8. Begin streaming on both OUTPUT and CAPTURE queues via VIDIOC_STREAMON(). This may be performed in any order. The actual encoding process starts when both queues start streaming.

Encoding #

This state is reached after the Initialization sequence finishes successfully. In this state, the client queues and dequeues buffers to both queues via VIDIOC_QBUF() and VIDIOC_DQBUF(), following the standard semantics.

The content of encoded CAPTURE buffers depends on the active coded pixel format and may be affected by codec-specific extended controls, as stated in the documentation of each format.

Both queues operate independently, following standard behavior of V4L2 buffer queues and memory-to-memory devices. In addition, the order of encoded frames dequeued from the CAPTURE queue may differ from the order of queuing raw frames to the OUTPUT queue, due to properties of the selected coded format, e.g. frame reordering.

The client must not assume any direct relationship between CAPTURE and OUTPUT buffers and any specific timing of buffers becoming available to dequeue. Specifically:

  • a buffer queued to OUTPUT may result in more than one buffer produced on CAPTURE (for example, if returning an encoded frame allowed the encoder to return a frame that preceded it in display, but succeeded it in the decode order; however, there may be other reasons for this as well),

  • a buffer queued to OUTPUT may result in a buffer being produced on CAPTURE later into encode process, and/or after processing further OUTPUT buffers, or be returned out of order, e.g. if display reordering is used,

  • buffers may become available on the CAPTURE queue without additional buffers queued to OUTPUT (e.g. during drain or EOS), because of the OUTPUT buffers queued in the past whose encoding results are only available at later time, due to specifics of the encoding process,

  • buffers queued to OUTPUT may not become available to dequeue instantly after being encoded into a corresponding CAPTURE buffer, e.g. if the encoder needs to use the frame as a reference for encoding further frames.

Should an encoding error occur, it will be reported to the client with the level of details depending on the encoder capabilities. Specifically:

  • the CAPTURE buffer (if any) that contains the results of the failed encode operation will be returned with the V4L2_BUF_FLAG_ERROR flag set,

  • if the encoder is able to precisely report the OUTPUT buffer(s) that triggered the error, such buffer(s) will be returned with the V4L2_BUF_FLAG_ERROR flag set.

In case of a fatal failure that does not allow the encoding to continue, any further operations on corresponding encoder file handle will return the -EIO error code. The client may close the file handle and open a new one, or alternatively reinitialize the instance by stopping streaming on both queues, releasing all buffers and performing the Initialization sequence again.

Encoding Parameter Changes #

The client is allowed to use VIDIOC_S_CTRL() to change encoder parameters at any time. The availability of parameters is encoder-specific and the client must query the encoder to find the set of available controls.

The ability to change each parameter during encoding is encoder-specific, as per the standard semantics of the V4L2 control interface. The client may attempt to set a control during encoding and if the operation fails with the -EBUSY error code, the CAPTURE queue needs to be stopped for the configuration change to be allowed. To do this, it may follow the Drain sequence to avoid losing the already queued/encoded frames.

The timing of parameter updates is encoder-specific, as per the standard semantics of the V4L2 control interface. If the client needs to apply the parameters exactly at specific frame, using the Request API (Request API) should be considered, if supported by the encoder.

Drain #

To ensure that all the queued OUTPUT buffers have been processed and the related CAPTURE buffers are given to the client, the client must follow the drain sequence described below. After the drain sequence ends, the client has received all encoded frames for all OUTPUT buffers queued before the sequence was started.

  1. Begin the drain sequence by issuing VIDIOC_ENCODER_CMD().

    • Required fields:

      • cmd

        set to V4L2_ENC_CMD_STOP.

      • flags

        set to 0.

      • pts

        set to 0.

  2. Any OUTPUT buffers queued by the client before the VIDIOC_ENCODER_CMD() was issued will be processed and encoded as normal. The client must continue to handle both queues independently, similarly to normal encode operation. This includes:

    • queuing and dequeuing CAPTURE buffers, until a buffer marked with the V4L2_BUF_FLAG_LAST flag is dequeued,

    • dequeuing processed OUTPUT buffers, until all the buffers queued before the V4L2_ENC_CMD_STOP command are dequeued,

    • dequeuing the V4L2_EVENT_EOS event, if the client subscribes to it.

  3. Once all OUTPUT buffers queued before the V4L2_ENC_CMD_STOP call are dequeued and the last CAPTURE buffer is dequeued, the encoder is stopped and it will accept, but not process any newly queued OUTPUT buffers until the client issues any of the following operations:

    • V4L2_ENC_CMD_START - the encoder will not be reset and will resume operation normally, with all the state from before the drain,

    • a pair of VIDIOC_STREAMOFF() and VIDIOC_STREAMON() on the CAPTURE queue - the encoder will be reset (see the Reset sequence) and then resume encoding,

    • a pair of VIDIOC_STREAMOFF() and VIDIOC_STREAMON() on the OUTPUT queue - the encoder will resume operation normally, however any source frames queued to the OUTPUT queue between V4L2_ENC_CMD_STOP and VIDIOC_STREAMOFF() will be discarded.

Reset #

The client may want to request the encoder to reinitialize the encoding, so that the following stream data becomes independent from the stream data generated before. Depending on the coded format, that may imply that:

  • encoded frames produced after the restart must not reference any frames produced before the stop, e.g. no long term references for H.264/HEVC,

  • any headers that must be included in a standalone stream must be produced again, e.g. SPS and PPS for H.264/HEVC.

This can be achieved by performing the reset sequence.

  1. Perform the Drain sequence to ensure all the in-flight encoding finishes and respective buffers are dequeued.

  2. Stop streaming on the CAPTURE queue via VIDIOC_STREAMOFF(). This will return all currently queued CAPTURE buffers to the client, without valid frame data.

  3. Start streaming on the CAPTURE queue via VIDIOC_STREAMON() and continue with regular encoding sequence. The encoded frames produced into CAPTURE buffers from now on will contain a standalone stream that can be decoded without the need for frames encoded before the reset sequence, starting at the first OUTPUT buffer queued after issuing the V4L2_ENC_CMD_STOP of the Drain sequence.

This sequence may be also used to change encoding parameters for encoders without the ability to change the parameters on the fly.

Commit Points #

Setting formats and allocating buffers triggers changes in the behavior of the encoder.

  1. Setting the format on the CAPTURE queue may change the set of formats supported/advertised on the OUTPUT queue. In particular, it also means that the OUTPUT format may be reset and the client must not rely on the previously set format being preserved.

  2. Enumerating formats on the OUTPUT queue always returns only formats supported for the current CAPTURE format.

  3. Setting the format on the OUTPUT queue does not change the list of formats available on the CAPTURE queue. An attempt to set the OUTPUT format that is not supported for the currently selected CAPTURE format will result in the encoder adjusting the requested OUTPUT format to a supported one.

  4. Enumerating formats on the CAPTURE queue always returns the full set of supported coded formats, irrespective of the current OUTPUT format.

  5. While buffers are allocated on any of the OUTPUT or CAPTURE queues, the client must not change the format on the CAPTURE queue. Drivers will return the -EBUSY error code for any such format change attempt.

To summarize, setting formats and allocation must always start with the CAPTURE queue and the CAPTURE queue is the master that governs the set of supported formats for the OUTPUT queue.

Edit this page