0001 .. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
0002
0003 .. _encoder:
0004
0005 *************************************************
0006 Memory-to-Memory Stateful Video Encoder Interface
0007 *************************************************
0008
0009 A stateful video encoder takes raw video frames in display order and encodes
0010 them into a bytestream. It generates complete chunks of the bytestream, including
0011 all metadata, headers, etc. The resulting bytestream does not require any
0012 further post-processing by the client.
0013
0014 Performing software stream processing, header generation etc. in the driver
0015 in order to support this interface is strongly discouraged. In case such
0016 operations are needed, use of the Stateless Video Encoder Interface (in
0017 development) is strongly advised.
0018
0019 Conventions and Notations Used in This Document
0020 ===============================================
0021
0022 1. The general V4L2 API rules apply if not specified in this document
0023 otherwise.
0024
0025 2. The meaning of words "must", "may", "should", etc. is as per `RFC
0026 2119 <https://tools.ietf.org/html/rfc2119>`_.
0027
0028 3. All steps not marked "optional" are required.
0029
0030 4. :c:func:`VIDIOC_G_EXT_CTRLS` and :c:func:`VIDIOC_S_EXT_CTRLS` may be used
0031 interchangeably with :c:func:`VIDIOC_G_CTRL` and :c:func:`VIDIOC_S_CTRL`,
0032 unless specified otherwise.
0033
0034 5. Single-planar API (see :ref:`planar-apis`) and applicable structures may be
0035 used interchangeably with multi-planar API, unless specified otherwise,
0036 depending on encoder capabilities and following the general V4L2 guidelines.
0037
0038 6. i = [a..b]: sequence of integers from a to b, inclusive, i.e. i =
0039 [0..2]: i = 0, 1, 2.
0040
0041 7. Given an ``OUTPUT`` buffer A, then A' represents a buffer on the ``CAPTURE``
0042 queue containing data that resulted from processing buffer A.
0043
0044 Glossary
0045 ========
0046
0047 Refer to :ref:`decoder-glossary`.
0048
0049 State Machine
0050 =============
0051
0052 .. kernel-render:: DOT
0053 :alt: DOT digraph of encoder state machine
0054 :caption: Encoder State Machine
0055
0056 digraph encoder_state_machine {
0057 node [shape = doublecircle, label="Encoding"] Encoding;
0058
0059 node [shape = circle, label="Initialization"] Initialization;
0060 node [shape = circle, label="Stopped"] Stopped;
0061 node [shape = circle, label="Drain"] Drain;
0062 node [shape = circle, label="Reset"] Reset;
0063
0064 node [shape = point]; qi
0065 qi -> Initialization [ label = "open()" ];
0066
0067 Initialization -> Encoding [ label = "Both queues streaming" ];
0068
0069 Encoding -> Drain [ label = "V4L2_ENC_CMD_STOP" ];
0070 Encoding -> Reset [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
0071 Encoding -> Stopped [ label = "VIDIOC_STREAMOFF(OUTPUT)" ];
0072 Encoding -> Encoding;
0073
0074 Drain -> Stopped [ label = "All CAPTURE\nbuffers dequeued\nor\nVIDIOC_STREAMOFF(OUTPUT)" ];
0075 Drain -> Reset [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
0076
0077 Reset -> Encoding [ label = "VIDIOC_STREAMON(CAPTURE)" ];
0078 Reset -> Initialization [ label = "VIDIOC_REQBUFS(OUTPUT, 0)" ];
0079
0080 Stopped -> Encoding [ label = "V4L2_ENC_CMD_START\nor\nVIDIOC_STREAMON(OUTPUT)" ];
0081 Stopped -> Reset [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
0082 }
0083
0084 Querying Capabilities
0085 =====================
0086
0087 1. To enumerate the set of coded formats supported by the encoder, the
0088 client may call :c:func:`VIDIOC_ENUM_FMT` on ``CAPTURE``.
0089
0090 * The full set of supported formats will be returned, regardless of the
0091 format set on ``OUTPUT``.
0092
0093 2. To enumerate the set of supported raw formats, the client may call
0094 :c:func:`VIDIOC_ENUM_FMT` on ``OUTPUT``.
0095
0096 * Only the formats supported for the format currently active on ``CAPTURE``
0097 will be returned.
0098
0099 * In order to enumerate raw formats supported by a given coded format,
0100 the client must first set that coded format on ``CAPTURE`` and then
0101 enumerate the formats on ``OUTPUT``.
0102
0103 3. The client may use :c:func:`VIDIOC_ENUM_FRAMESIZES` to detect supported
0104 resolutions for a given format, passing the desired pixel format in
0105 :c:type:`v4l2_frmsizeenum` ``pixel_format``.
0106
0107 * Values returned by :c:func:`VIDIOC_ENUM_FRAMESIZES` for a coded pixel
0108 format will include all possible coded resolutions supported by the
0109 encoder for the given coded pixel format.
0110
0111 * Values returned by :c:func:`VIDIOC_ENUM_FRAMESIZES` for a raw pixel format
0112 will include all possible frame buffer resolutions supported by the
0113 encoder for the given raw pixel format and coded format currently set on
0114 ``CAPTURE``.
0115
0116 4. The client may use :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` to detect supported
0117 frame intervals for a given format and resolution, passing the desired pixel
0118 format in :c:type:`v4l2_frmsizeenum` ``pixel_format`` and the resolution
0119 in :c:type:`v4l2_frmsizeenum` ``width`` and :c:type:`v4l2_frmsizeenum`
0120 ``height``.
0121
0122 * Values returned by :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` for a coded pixel
0123 format and coded resolution will include all possible frame intervals
0124 supported by the encoder for the given coded pixel format and resolution.
0125
0126 * Values returned by :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` for a raw pixel
0127 format and resolution will include all possible frame intervals supported
0128 by the encoder for the given raw pixel format and resolution and for the
0129 coded format, coded resolution and coded frame interval currently set on
0130 ``CAPTURE``.
0131
0132 * Support for :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` is optional. If it is
0133 not implemented, then there are no special restrictions other than the
0134 limits of the codec itself.
0135
0136 5. Supported profiles and levels for the coded format currently set on
0137 ``CAPTURE``, if applicable, may be queried using their respective controls
0138 via :c:func:`VIDIOC_QUERYCTRL`.
0139
0140 6. Any additional encoder capabilities may be discovered by querying
0141 their respective controls.
0142
0143 Initialization
0144 ==============
0145
0146 1. Set the coded format on the ``CAPTURE`` queue via :c:func:`VIDIOC_S_FMT`.
0147
0148 * **Required fields:**
0149
0150 ``type``
0151 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0152
0153 ``pixelformat``
0154 the coded format to be produced.
0155
0156 ``sizeimage``
0157 desired size of ``CAPTURE`` buffers; the encoder may adjust it to
0158 match hardware requirements.
0159
0160 ``width``, ``height``
0161 ignored (read-only).
0162
0163 other fields
0164 follow standard semantics.
0165
0166 * **Return fields:**
0167
0168 ``sizeimage``
0169 adjusted size of ``CAPTURE`` buffers.
0170
0171 ``width``, ``height``
0172 the coded size selected by the encoder based on current state, e.g.
0173 ``OUTPUT`` format, selection rectangles, etc. (read-only).
0174
0175 .. important::
0176
0177 Changing the ``CAPTURE`` format may change the currently set ``OUTPUT``
0178 format. How the new ``OUTPUT`` format is determined is up to the encoder
0179 and the client must ensure it matches its needs afterwards.
0180
0181 2. **Optional.** Enumerate supported ``OUTPUT`` formats (raw formats for
0182 source) for the selected coded format via :c:func:`VIDIOC_ENUM_FMT`.
0183
0184 * **Required fields:**
0185
0186 ``type``
0187 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0188
0189 other fields
0190 follow standard semantics.
0191
0192 * **Return fields:**
0193
0194 ``pixelformat``
0195 raw format supported for the coded format currently selected on
0196 the ``CAPTURE`` queue.
0197
0198 other fields
0199 follow standard semantics.
0200
0201 3. Set the raw source format on the ``OUTPUT`` queue via
0202 :c:func:`VIDIOC_S_FMT`.
0203
0204 * **Required fields:**
0205
0206 ``type``
0207 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0208
0209 ``pixelformat``
0210 raw format of the source.
0211
0212 ``width``, ``height``
0213 source resolution.
0214
0215 other fields
0216 follow standard semantics.
0217
0218 * **Return fields:**
0219
0220 ``width``, ``height``
0221 may be adjusted to match encoder minimums, maximums and alignment
0222 requirements, as required by the currently selected formats, as
0223 reported by :c:func:`VIDIOC_ENUM_FRAMESIZES`.
0224
0225 other fields
0226 follow standard semantics.
0227
0228 * Setting the ``OUTPUT`` format will reset the selection rectangles to their
0229 default values, based on the new resolution, as described in the next
0230 step.
0231
0232 4. Set the raw frame interval on the ``OUTPUT`` queue via
0233 :c:func:`VIDIOC_S_PARM`. This also sets the coded frame interval on the
0234 ``CAPTURE`` queue to the same value.
0235
0236 * ** Required fields:**
0237
0238 ``type``
0239 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0240
0241 ``parm.output``
0242 set all fields except ``parm.output.timeperframe`` to 0.
0243
0244 ``parm.output.timeperframe``
0245 the desired frame interval; the encoder may adjust it to
0246 match hardware requirements.
0247
0248 * **Return fields:**
0249
0250 ``parm.output.timeperframe``
0251 the adjusted frame interval.
0252
0253 .. important::
0254
0255 Changing the ``OUTPUT`` frame interval *also* sets the framerate that
0256 the encoder uses to encode the video. So setting the frame interval
0257 to 1/24 (or 24 frames per second) will produce a coded video stream
0258 that can be played back at that speed. The frame interval for the
0259 ``OUTPUT`` queue is just a hint, the application may provide raw
0260 frames at a different rate. It can be used by the driver to help
0261 schedule multiple encoders running in parallel.
0262
0263 In the next step the ``CAPTURE`` frame interval can optionally be
0264 changed to a different value. This is useful for off-line encoding
0265 were the coded frame interval can be different from the rate at
0266 which raw frames are supplied.
0267
0268 .. important::
0269
0270 ``timeperframe`` deals with *frames*, not fields. So for interlaced
0271 formats this is the time per two fields, since a frame consists of
0272 a top and a bottom field.
0273
0274 .. note::
0275
0276 It is due to historical reasons that changing the ``OUTPUT`` frame
0277 interval also changes the coded frame interval on the ``CAPTURE``
0278 queue. Ideally these would be independent settings, but that would
0279 break the existing API.
0280
0281 5. **Optional** Set the coded frame interval on the ``CAPTURE`` queue via
0282 :c:func:`VIDIOC_S_PARM`. This is only necessary if the coded frame
0283 interval is different from the raw frame interval, which is typically
0284 the case for off-line encoding. Support for this feature is signalled
0285 by the :ref:`V4L2_FMT_FLAG_ENC_CAP_FRAME_INTERVAL <fmtdesc-flags>` format flag.
0286
0287 * ** Required fields:**
0288
0289 ``type``
0290 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0291
0292 ``parm.capture``
0293 set all fields except ``parm.capture.timeperframe`` to 0.
0294
0295 ``parm.capture.timeperframe``
0296 the desired coded frame interval; the encoder may adjust it to
0297 match hardware requirements.
0298
0299 * **Return fields:**
0300
0301 ``parm.capture.timeperframe``
0302 the adjusted frame interval.
0303
0304 .. important::
0305
0306 Changing the ``CAPTURE`` frame interval sets the framerate for the
0307 coded video. It does *not* set the rate at which buffers arrive on the
0308 ``CAPTURE`` queue, that depends on how fast the encoder is and how
0309 fast raw frames are queued on the ``OUTPUT`` queue.
0310
0311 .. important::
0312
0313 ``timeperframe`` deals with *frames*, not fields. So for interlaced
0314 formats this is the time per two fields, since a frame consists of
0315 a top and a bottom field.
0316
0317 .. note::
0318
0319 Not all drivers support this functionality, in that case just set
0320 the desired coded frame interval for the ``OUTPUT`` queue.
0321
0322 However, drivers that can schedule multiple encoders based on the
0323 ``OUTPUT`` frame interval must support this optional feature.
0324
0325 6. **Optional.** Set the visible resolution for the stream metadata via
0326 :c:func:`VIDIOC_S_SELECTION` on the ``OUTPUT`` queue if it is desired
0327 to be different than the full OUTPUT resolution.
0328
0329 * **Required fields:**
0330
0331 ``type``
0332 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0333
0334 ``target``
0335 set to ``V4L2_SEL_TGT_CROP``.
0336
0337 ``r.left``, ``r.top``, ``r.width``, ``r.height``
0338 visible rectangle; this must fit within the `V4L2_SEL_TGT_CROP_BOUNDS`
0339 rectangle and may be subject to adjustment to match codec and
0340 hardware constraints.
0341
0342 * **Return fields:**
0343
0344 ``r.left``, ``r.top``, ``r.width``, ``r.height``
0345 visible rectangle adjusted by the encoder.
0346
0347 * The following selection targets are supported on ``OUTPUT``:
0348
0349 ``V4L2_SEL_TGT_CROP_BOUNDS``
0350 equal to the full source frame, matching the active ``OUTPUT``
0351 format.
0352
0353 ``V4L2_SEL_TGT_CROP_DEFAULT``
0354 equal to ``V4L2_SEL_TGT_CROP_BOUNDS``.
0355
0356 ``V4L2_SEL_TGT_CROP``
0357 rectangle within the source buffer to be encoded into the
0358 ``CAPTURE`` stream; defaults to ``V4L2_SEL_TGT_CROP_DEFAULT``.
0359
0360 .. note::
0361
0362 A common use case for this selection target is encoding a source
0363 video with a resolution that is not a multiple of a macroblock,
0364 e.g. the common 1920x1080 resolution may require the source
0365 buffers to be aligned to 1920x1088 for codecs with 16x16 macroblock
0366 size. To avoid encoding the padding, the client needs to explicitly
0367 configure this selection target to 1920x1080.
0368
0369 .. warning::
0370
0371 The encoder may adjust the crop/compose rectangles to the nearest
0372 supported ones to meet codec and hardware requirements. The client needs
0373 to check the adjusted rectangle returned by :c:func:`VIDIOC_S_SELECTION`.
0374
0375 7. Allocate buffers for both ``OUTPUT`` and ``CAPTURE`` via
0376 :c:func:`VIDIOC_REQBUFS`. This may be performed in any order.
0377
0378 * **Required fields:**
0379
0380 ``count``
0381 requested number of buffers to allocate; greater than zero.
0382
0383 ``type``
0384 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT`` or
0385 ``CAPTURE``.
0386
0387 other fields
0388 follow standard semantics.
0389
0390 * **Return fields:**
0391
0392 ``count``
0393 actual number of buffers allocated.
0394
0395 .. warning::
0396
0397 The actual number of allocated buffers may differ from the ``count``
0398 given. The client must check the updated value of ``count`` after the
0399 call returns.
0400
0401 .. note::
0402
0403 To allocate more than the minimum number of OUTPUT buffers (for pipeline
0404 depth), the client may query the ``V4L2_CID_MIN_BUFFERS_FOR_OUTPUT``
0405 control to get the minimum number of buffers required, and pass the
0406 obtained value plus the number of additional buffers needed in the
0407 ``count`` field to :c:func:`VIDIOC_REQBUFS`.
0408
0409 Alternatively, :c:func:`VIDIOC_CREATE_BUFS` can be used to have more
0410 control over buffer allocation.
0411
0412 * **Required fields:**
0413
0414 ``count``
0415 requested number of buffers to allocate; greater than zero.
0416
0417 ``type``
0418 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0419
0420 other fields
0421 follow standard semantics.
0422
0423 * **Return fields:**
0424
0425 ``count``
0426 adjusted to the number of allocated buffers.
0427
0428 8. Begin streaming on both ``OUTPUT`` and ``CAPTURE`` queues via
0429 :c:func:`VIDIOC_STREAMON`. This may be performed in any order. The actual
0430 encoding process starts when both queues start streaming.
0431
0432 .. note::
0433
0434 If the client stops the ``CAPTURE`` queue during the encode process and then
0435 restarts it again, the encoder will begin generating a stream independent
0436 from the stream generated before the stop. The exact constraints depend
0437 on the coded format, but may include the following implications:
0438
0439 * encoded frames produced after the restart must not reference any
0440 frames produced before the stop, e.g. no long term references for
0441 H.264/HEVC,
0442
0443 * any headers that must be included in a standalone stream must be
0444 produced again, e.g. SPS and PPS for H.264/HEVC.
0445
0446 Encoding
0447 ========
0448
0449 This state is reached after the `Initialization` sequence finishes
0450 successfully. In this state, the client queues and dequeues buffers to both
0451 queues via :c:func:`VIDIOC_QBUF` and :c:func:`VIDIOC_DQBUF`, following the
0452 standard semantics.
0453
0454 The content of encoded ``CAPTURE`` buffers depends on the active coded pixel
0455 format and may be affected by codec-specific extended controls, as stated
0456 in the documentation of each format.
0457
0458 Both queues operate independently, following standard behavior of V4L2 buffer
0459 queues and memory-to-memory devices. In addition, the order of encoded frames
0460 dequeued from the ``CAPTURE`` queue may differ from the order of queuing raw
0461 frames to the ``OUTPUT`` queue, due to properties of the selected coded format,
0462 e.g. frame reordering.
0463
0464 The client must not assume any direct relationship between ``CAPTURE`` and
0465 ``OUTPUT`` buffers and any specific timing of buffers becoming
0466 available to dequeue. Specifically:
0467
0468 * a buffer queued to ``OUTPUT`` may result in more than one buffer produced on
0469 ``CAPTURE`` (for example, if returning an encoded frame allowed the encoder
0470 to return a frame that preceded it in display, but succeeded it in the decode
0471 order; however, there may be other reasons for this as well),
0472
0473 * a buffer queued to ``OUTPUT`` may result in a buffer being produced on
0474 ``CAPTURE`` later into encode process, and/or after processing further
0475 ``OUTPUT`` buffers, or be returned out of order, e.g. if display
0476 reordering is used,
0477
0478 * buffers may become available on the ``CAPTURE`` queue without additional
0479 buffers queued to ``OUTPUT`` (e.g. during drain or ``EOS``), because of the
0480 ``OUTPUT`` buffers queued in the past whose encoding results are only
0481 available at later time, due to specifics of the encoding process,
0482
0483 * buffers queued to ``OUTPUT`` may not become available to dequeue instantly
0484 after being encoded into a corresponding ``CAPTURE`` buffer, e.g. if the
0485 encoder needs to use the frame as a reference for encoding further frames.
0486
0487 .. note::
0488
0489 To allow matching encoded ``CAPTURE`` buffers with ``OUTPUT`` buffers they
0490 originated from, the client can set the ``timestamp`` field of the
0491 :c:type:`v4l2_buffer` struct when queuing an ``OUTPUT`` buffer. The
0492 ``CAPTURE`` buffer(s), which resulted from encoding that ``OUTPUT`` buffer
0493 will have their ``timestamp`` field set to the same value when dequeued.
0494
0495 In addition to the straightforward case of one ``OUTPUT`` buffer producing
0496 one ``CAPTURE`` buffer, the following cases are defined:
0497
0498 * one ``OUTPUT`` buffer generates multiple ``CAPTURE`` buffers: the same
0499 ``OUTPUT`` timestamp will be copied to multiple ``CAPTURE`` buffers,
0500
0501 * the encoding order differs from the presentation order (i.e. the
0502 ``CAPTURE`` buffers are out-of-order compared to the ``OUTPUT`` buffers):
0503 ``CAPTURE`` timestamps will not retain the order of ``OUTPUT`` timestamps.
0504
0505 .. note::
0506
0507 To let the client distinguish between frame types (keyframes, intermediate
0508 frames; the exact list of types depends on the coded format), the
0509 ``CAPTURE`` buffers will have corresponding flag bits set in their
0510 :c:type:`v4l2_buffer` struct when dequeued. See the documentation of
0511 :c:type:`v4l2_buffer` and each coded pixel format for exact list of flags
0512 and their meanings.
0513
0514 Should an encoding error occur, it will be reported to the client with the level
0515 of details depending on the encoder capabilities. Specifically:
0516
0517 * the ``CAPTURE`` buffer (if any) that contains the results of the failed encode
0518 operation will be returned with the ``V4L2_BUF_FLAG_ERROR`` flag set,
0519
0520 * if the encoder is able to precisely report the ``OUTPUT`` buffer(s) that triggered
0521 the error, such buffer(s) will be returned with the ``V4L2_BUF_FLAG_ERROR`` flag
0522 set.
0523
0524 .. note::
0525
0526 If a ``CAPTURE`` buffer is too small then it is just returned with the
0527 ``V4L2_BUF_FLAG_ERROR`` flag set. More work is needed to detect that this
0528 error occurred because the buffer was too small, and to provide support to
0529 free existing buffers that were too small.
0530
0531 In case of a fatal failure that does not allow the encoding to continue, any
0532 further operations on corresponding encoder file handle will return the -EIO
0533 error code. The client may close the file handle and open a new one, or
0534 alternatively reinitialize the instance by stopping streaming on both queues,
0535 releasing all buffers and performing the Initialization sequence again.
0536
0537 Encoding Parameter Changes
0538 ==========================
0539
0540 The client is allowed to use :c:func:`VIDIOC_S_CTRL` to change encoder
0541 parameters at any time. The availability of parameters is encoder-specific
0542 and the client must query the encoder to find the set of available controls.
0543
0544 The ability to change each parameter during encoding is encoder-specific, as
0545 per the standard semantics of the V4L2 control interface. The client may
0546 attempt to set a control during encoding and if the operation fails with the
0547 -EBUSY error code, the ``CAPTURE`` queue needs to be stopped for the
0548 configuration change to be allowed. To do this, it may follow the `Drain`
0549 sequence to avoid losing the already queued/encoded frames.
0550
0551 The timing of parameter updates is encoder-specific, as per the standard
0552 semantics of the V4L2 control interface. If the client needs to apply the
0553 parameters exactly at specific frame, using the Request API
0554 (:ref:`media-request-api`) should be considered, if supported by the encoder.
0555
0556 Drain
0557 =====
0558
0559 To ensure that all the queued ``OUTPUT`` buffers have been processed and the
0560 related ``CAPTURE`` buffers are given to the client, the client must follow the
0561 drain sequence described below. After the drain sequence ends, the client has
0562 received all encoded frames for all ``OUTPUT`` buffers queued before the
0563 sequence was started.
0564
0565 1. Begin the drain sequence by issuing :c:func:`VIDIOC_ENCODER_CMD`.
0566
0567 * **Required fields:**
0568
0569 ``cmd``
0570 set to ``V4L2_ENC_CMD_STOP``.
0571
0572 ``flags``
0573 set to 0.
0574
0575 ``pts``
0576 set to 0.
0577
0578 .. warning::
0579
0580 The sequence can be only initiated if both ``OUTPUT`` and ``CAPTURE``
0581 queues are streaming. For compatibility reasons, the call to
0582 :c:func:`VIDIOC_ENCODER_CMD` will not fail even if any of the queues is
0583 not streaming, but at the same time it will not initiate the `Drain`
0584 sequence and so the steps described below would not be applicable.
0585
0586 2. Any ``OUTPUT`` buffers queued by the client before the
0587 :c:func:`VIDIOC_ENCODER_CMD` was issued will be processed and encoded as
0588 normal. The client must continue to handle both queues independently,
0589 similarly to normal encode operation. This includes:
0590
0591 * queuing and dequeuing ``CAPTURE`` buffers, until a buffer marked with the
0592 ``V4L2_BUF_FLAG_LAST`` flag is dequeued,
0593
0594 .. warning::
0595
0596 The last buffer may be empty (with :c:type:`v4l2_buffer`
0597 ``bytesused`` = 0) and in that case it must be ignored by the client,
0598 as it does not contain an encoded frame.
0599
0600 .. note::
0601
0602 Any attempt to dequeue more ``CAPTURE`` buffers beyond the buffer
0603 marked with ``V4L2_BUF_FLAG_LAST`` will result in a -EPIPE error from
0604 :c:func:`VIDIOC_DQBUF`.
0605
0606 * dequeuing processed ``OUTPUT`` buffers, until all the buffers queued
0607 before the ``V4L2_ENC_CMD_STOP`` command are dequeued,
0608
0609 * dequeuing the ``V4L2_EVENT_EOS`` event, if the client subscribes to it.
0610
0611 .. note::
0612
0613 For backwards compatibility, the encoder will signal a ``V4L2_EVENT_EOS``
0614 event when the last frame has been encoded and all frames are ready to be
0615 dequeued. It is deprecated behavior and the client must not rely on it.
0616 The ``V4L2_BUF_FLAG_LAST`` buffer flag should be used instead.
0617
0618 3. Once all ``OUTPUT`` buffers queued before the ``V4L2_ENC_CMD_STOP`` call are
0619 dequeued and the last ``CAPTURE`` buffer is dequeued, the encoder is stopped
0620 and it will accept, but not process any newly queued ``OUTPUT`` buffers
0621 until the client issues any of the following operations:
0622
0623 * ``V4L2_ENC_CMD_START`` - the encoder will not be reset and will resume
0624 operation normally, with all the state from before the drain,
0625
0626 * a pair of :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
0627 ``CAPTURE`` queue - the encoder will be reset (see the `Reset` sequence)
0628 and then resume encoding,
0629
0630 * a pair of :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
0631 ``OUTPUT`` queue - the encoder will resume operation normally, however any
0632 source frames queued to the ``OUTPUT`` queue between ``V4L2_ENC_CMD_STOP``
0633 and :c:func:`VIDIOC_STREAMOFF` will be discarded.
0634
0635 .. note::
0636
0637 Once the drain sequence is initiated, the client needs to drive it to
0638 completion, as described by the steps above, unless it aborts the process by
0639 issuing :c:func:`VIDIOC_STREAMOFF` on any of the ``OUTPUT`` or ``CAPTURE``
0640 queues. The client is not allowed to issue ``V4L2_ENC_CMD_START`` or
0641 ``V4L2_ENC_CMD_STOP`` again while the drain sequence is in progress and they
0642 will fail with -EBUSY error code if attempted.
0643
0644 For reference, handling of various corner cases is described below:
0645
0646 * In case of no buffer in the ``OUTPUT`` queue at the time the
0647 ``V4L2_ENC_CMD_STOP`` command was issued, the drain sequence completes
0648 immediately and the encoder returns an empty ``CAPTURE`` buffer with the
0649 ``V4L2_BUF_FLAG_LAST`` flag set.
0650
0651 * In case of no buffer in the ``CAPTURE`` queue at the time the drain
0652 sequence completes, the next time the client queues a ``CAPTURE`` buffer
0653 it is returned at once as an empty buffer with the ``V4L2_BUF_FLAG_LAST``
0654 flag set.
0655
0656 * If :c:func:`VIDIOC_STREAMOFF` is called on the ``CAPTURE`` queue in the
0657 middle of the drain sequence, the drain sequence is canceled and all
0658 ``CAPTURE`` buffers are implicitly returned to the client.
0659
0660 * If :c:func:`VIDIOC_STREAMOFF` is called on the ``OUTPUT`` queue in the
0661 middle of the drain sequence, the drain sequence completes immediately and
0662 next ``CAPTURE`` buffer will be returned empty with the
0663 ``V4L2_BUF_FLAG_LAST`` flag set.
0664
0665 Although not mandatory, the availability of encoder commands may be queried
0666 using :c:func:`VIDIOC_TRY_ENCODER_CMD`.
0667
0668 Reset
0669 =====
0670
0671 The client may want to request the encoder to reinitialize the encoding, so
0672 that the following stream data becomes independent from the stream data
0673 generated before. Depending on the coded format, that may imply that:
0674
0675 * encoded frames produced after the restart must not reference any frames
0676 produced before the stop, e.g. no long term references for H.264/HEVC,
0677
0678 * any headers that must be included in a standalone stream must be produced
0679 again, e.g. SPS and PPS for H.264/HEVC.
0680
0681 This can be achieved by performing the reset sequence.
0682
0683 1. Perform the `Drain` sequence to ensure all the in-flight encoding finishes
0684 and respective buffers are dequeued.
0685
0686 2. Stop streaming on the ``CAPTURE`` queue via :c:func:`VIDIOC_STREAMOFF`. This
0687 will return all currently queued ``CAPTURE`` buffers to the client, without
0688 valid frame data.
0689
0690 3. Start streaming on the ``CAPTURE`` queue via :c:func:`VIDIOC_STREAMON` and
0691 continue with regular encoding sequence. The encoded frames produced into
0692 ``CAPTURE`` buffers from now on will contain a standalone stream that can be
0693 decoded without the need for frames encoded before the reset sequence,
0694 starting at the first ``OUTPUT`` buffer queued after issuing the
0695 `V4L2_ENC_CMD_STOP` of the `Drain` sequence.
0696
0697 This sequence may be also used to change encoding parameters for encoders
0698 without the ability to change the parameters on the fly.
0699
0700 Commit Points
0701 =============
0702
0703 Setting formats and allocating buffers triggers changes in the behavior of the
0704 encoder.
0705
0706 1. Setting the format on the ``CAPTURE`` queue may change the set of formats
0707 supported/advertised on the ``OUTPUT`` queue. In particular, it also means
0708 that the ``OUTPUT`` format may be reset and the client must not rely on the
0709 previously set format being preserved.
0710
0711 2. Enumerating formats on the ``OUTPUT`` queue always returns only formats
0712 supported for the current ``CAPTURE`` format.
0713
0714 3. Setting the format on the ``OUTPUT`` queue does not change the list of
0715 formats available on the ``CAPTURE`` queue. An attempt to set the ``OUTPUT``
0716 format that is not supported for the currently selected ``CAPTURE`` format
0717 will result in the encoder adjusting the requested ``OUTPUT`` format to a
0718 supported one.
0719
0720 4. Enumerating formats on the ``CAPTURE`` queue always returns the full set of
0721 supported coded formats, irrespective of the current ``OUTPUT`` format.
0722
0723 5. While buffers are allocated on any of the ``OUTPUT`` or ``CAPTURE`` queues,
0724 the client must not change the format on the ``CAPTURE`` queue. Drivers will
0725 return the -EBUSY error code for any such format change attempt.
0726
0727 To summarize, setting formats and allocation must always start with the
0728 ``CAPTURE`` queue and the ``CAPTURE`` queue is the master that governs the
0729 set of supported formats for the ``OUTPUT`` queue.