0001 .. SPDX-License-Identifier: GPL-2.0
0002
0003 .. _decoder:
0004
0005 *************************************************
0006 Memory-to-Memory Stateful Video Decoder Interface
0007 *************************************************
0008
0009 A stateful video decoder takes complete chunks of the bytestream (e.g. Annex-B
0010 H.264/HEVC stream, raw VP8/9 stream) and decodes them into raw video frames in
0011 display order. The decoder is expected not to require any additional information
0012 from the client to process these buffers.
0013
0014 Performing software parsing, processing etc. of the stream in the driver in
0015 order to support this interface is strongly discouraged. In case such
0016 operations are needed, use of the Stateless Video Decoder 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 decoder 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 .. _decoder-glossary:
0045
0046 Glossary
0047 ========
0048
0049 CAPTURE
0050 the destination buffer queue; for decoders, the queue of buffers containing
0051 decoded frames; for encoders, the queue of buffers containing an encoded
0052 bytestream; ``V4L2_BUF_TYPE_VIDEO_CAPTURE`` or
0053 ``V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE``; data is captured from the hardware
0054 into ``CAPTURE`` buffers.
0055
0056 client
0057 the application communicating with the decoder or encoder implementing
0058 this interface.
0059
0060 coded format
0061 encoded/compressed video bytestream format (e.g. H.264, VP8, etc.); see
0062 also: raw format.
0063
0064 coded height
0065 height for given coded resolution.
0066
0067 coded resolution
0068 stream resolution in pixels aligned to codec and hardware requirements;
0069 typically visible resolution rounded up to full macroblocks;
0070 see also: visible resolution.
0071
0072 coded width
0073 width for given coded resolution.
0074
0075 coding tree unit
0076 processing unit of the HEVC codec (corresponds to macroblock units in
0077 H.264, VP8, VP9),
0078 can use block structures of up to 64×64 pixels.
0079 Good at sub-partitioning the picture into variable sized structures.
0080
0081 decode order
0082 the order in which frames are decoded; may differ from display order if the
0083 coded format includes a feature of frame reordering; for decoders,
0084 ``OUTPUT`` buffers must be queued by the client in decode order; for
0085 encoders ``CAPTURE`` buffers must be returned by the encoder in decode order.
0086
0087 destination
0088 data resulting from the decode process; see ``CAPTURE``.
0089
0090 display order
0091 the order in which frames must be displayed; for encoders, ``OUTPUT``
0092 buffers must be queued by the client in display order; for decoders,
0093 ``CAPTURE`` buffers must be returned by the decoder in display order.
0094
0095 DPB
0096 Decoded Picture Buffer; an H.264/HEVC term for a buffer that stores a decoded
0097 raw frame available for reference in further decoding steps.
0098
0099 EOS
0100 end of stream.
0101
0102 IDR
0103 Instantaneous Decoder Refresh; a type of a keyframe in an H.264/HEVC-encoded
0104 stream, which clears the list of earlier reference frames (DPBs).
0105
0106 keyframe
0107 an encoded frame that does not reference frames decoded earlier, i.e.
0108 can be decoded fully on its own.
0109
0110 macroblock
0111 a processing unit in image and video compression formats based on linear
0112 block transforms (e.g. H.264, VP8, VP9); codec-specific, but for most of
0113 popular codecs the size is 16x16 samples (pixels). The HEVC codec uses a
0114 slightly more flexible processing unit called coding tree unit (CTU).
0115
0116 OUTPUT
0117 the source buffer queue; for decoders, the queue of buffers containing
0118 an encoded bytestream; for encoders, the queue of buffers containing raw
0119 frames; ``V4L2_BUF_TYPE_VIDEO_OUTPUT`` or
0120 ``V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE``; the hardware is fed with data
0121 from ``OUTPUT`` buffers.
0122
0123 PPS
0124 Picture Parameter Set; a type of metadata entity in an H.264/HEVC bytestream.
0125
0126 raw format
0127 uncompressed format containing raw pixel data (e.g. YUV, RGB formats).
0128
0129 resume point
0130 a point in the bytestream from which decoding may start/continue, without
0131 any previous state/data present, e.g.: a keyframe (VP8/VP9) or
0132 SPS/PPS/IDR sequence (H.264/HEVC); a resume point is required to start decode
0133 of a new stream, or to resume decoding after a seek.
0134
0135 source
0136 data fed to the decoder or encoder; see ``OUTPUT``.
0137
0138 source height
0139 height in pixels for given source resolution; relevant to encoders only.
0140
0141 source resolution
0142 resolution in pixels of source frames being source to the encoder and
0143 subject to further cropping to the bounds of visible resolution; relevant to
0144 encoders only.
0145
0146 source width
0147 width in pixels for given source resolution; relevant to encoders only.
0148
0149 SPS
0150 Sequence Parameter Set; a type of metadata entity in an H.264/HEVC bytestream.
0151
0152 stream metadata
0153 additional (non-visual) information contained inside encoded bytestream;
0154 for example: coded resolution, visible resolution, codec profile.
0155
0156 visible height
0157 height for given visible resolution; display height.
0158
0159 visible resolution
0160 stream resolution of the visible picture, in pixels, to be used for
0161 display purposes; must be smaller or equal to coded resolution;
0162 display resolution.
0163
0164 visible width
0165 width for given visible resolution; display width.
0166
0167 State Machine
0168 =============
0169
0170 .. kernel-render:: DOT
0171 :alt: DOT digraph of decoder state machine
0172 :caption: Decoder State Machine
0173
0174 digraph decoder_state_machine {
0175 node [shape = doublecircle, label="Decoding"] Decoding;
0176
0177 node [shape = circle, label="Initialization"] Initialization;
0178 node [shape = circle, label="Capture\nsetup"] CaptureSetup;
0179 node [shape = circle, label="Dynamic\nResolution\nChange"] ResChange;
0180 node [shape = circle, label="Stopped"] Stopped;
0181 node [shape = circle, label="Drain"] Drain;
0182 node [shape = circle, label="Seek"] Seek;
0183 node [shape = circle, label="End of Stream"] EoS;
0184
0185 node [shape = point]; qi
0186 qi -> Initialization [ label = "open()" ];
0187
0188 Initialization -> CaptureSetup [ label = "CAPTURE\nformat\nestablished" ];
0189
0190 CaptureSetup -> Stopped [ label = "CAPTURE\nbuffers\nready" ];
0191
0192 Decoding -> ResChange [ label = "Stream\nresolution\nchange" ];
0193 Decoding -> Drain [ label = "V4L2_DEC_CMD_STOP" ];
0194 Decoding -> EoS [ label = "EoS mark\nin the stream" ];
0195 Decoding -> Seek [ label = "VIDIOC_STREAMOFF(OUTPUT)" ];
0196 Decoding -> Stopped [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
0197 Decoding -> Decoding;
0198
0199 ResChange -> CaptureSetup [ label = "CAPTURE\nformat\nestablished" ];
0200 ResChange -> Seek [ label = "VIDIOC_STREAMOFF(OUTPUT)" ];
0201
0202 EoS -> Drain [ label = "Implicit\ndrain" ];
0203
0204 Drain -> Stopped [ label = "All CAPTURE\nbuffers dequeued\nor\nVIDIOC_STREAMOFF(CAPTURE)" ];
0205 Drain -> Seek [ label = "VIDIOC_STREAMOFF(OUTPUT)" ];
0206
0207 Seek -> Decoding [ label = "VIDIOC_STREAMON(OUTPUT)" ];
0208 Seek -> Initialization [ label = "VIDIOC_REQBUFS(OUTPUT, 0)" ];
0209
0210 Stopped -> Decoding [ label = "V4L2_DEC_CMD_START\nor\nVIDIOC_STREAMON(CAPTURE)" ];
0211 Stopped -> Seek [ label = "VIDIOC_STREAMOFF(OUTPUT)" ];
0212 }
0213
0214 Querying Capabilities
0215 =====================
0216
0217 1. To enumerate the set of coded formats supported by the decoder, the
0218 client may call :c:func:`VIDIOC_ENUM_FMT` on ``OUTPUT``.
0219
0220 * The full set of supported formats will be returned, regardless of the
0221 format set on ``CAPTURE``.
0222 * Check the flags field of :c:type:`v4l2_fmtdesc` for more information
0223 about the decoder's capabilities with respect to each coded format.
0224 In particular whether or not the decoder has a full-fledged bytestream
0225 parser and if the decoder supports dynamic resolution changes.
0226
0227 2. To enumerate the set of supported raw formats, the client may call
0228 :c:func:`VIDIOC_ENUM_FMT` on ``CAPTURE``.
0229
0230 * Only the formats supported for the format currently active on ``OUTPUT``
0231 will be returned.
0232
0233 * In order to enumerate raw formats supported by a given coded format,
0234 the client must first set that coded format on ``OUTPUT`` and then
0235 enumerate formats on ``CAPTURE``.
0236
0237 3. The client may use :c:func:`VIDIOC_ENUM_FRAMESIZES` to detect supported
0238 resolutions for a given format, passing desired pixel format in
0239 :c:type:`v4l2_frmsizeenum` ``pixel_format``.
0240
0241 * Values returned by :c:func:`VIDIOC_ENUM_FRAMESIZES` for a coded pixel
0242 format will include all possible coded resolutions supported by the
0243 decoder for given coded pixel format.
0244
0245 * Values returned by :c:func:`VIDIOC_ENUM_FRAMESIZES` for a raw pixel format
0246 will include all possible frame buffer resolutions supported by the
0247 decoder for given raw pixel format and the coded format currently set on
0248 ``OUTPUT``.
0249
0250 4. Supported profiles and levels for the coded format currently set on
0251 ``OUTPUT``, if applicable, may be queried using their respective controls
0252 via :c:func:`VIDIOC_QUERYCTRL`.
0253
0254 Initialization
0255 ==============
0256
0257 1. Set the coded format on ``OUTPUT`` via :c:func:`VIDIOC_S_FMT`.
0258
0259 * **Required fields:**
0260
0261 ``type``
0262 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0263
0264 ``pixelformat``
0265 a coded pixel format.
0266
0267 ``width``, ``height``
0268 coded resolution of the stream; required only if it cannot be parsed
0269 from the stream for the given coded format; otherwise the decoder will
0270 use this resolution as a placeholder resolution that will likely change
0271 as soon as it can parse the actual coded resolution from the stream.
0272
0273 ``sizeimage``
0274 desired size of ``OUTPUT`` buffers; the decoder may adjust it to
0275 match hardware requirements.
0276
0277 other fields
0278 follow standard semantics.
0279
0280 * **Return fields:**
0281
0282 ``sizeimage``
0283 adjusted size of ``OUTPUT`` buffers.
0284
0285 * The ``CAPTURE`` format will be updated with an appropriate frame buffer
0286 resolution instantly based on the width and height returned by
0287 :c:func:`VIDIOC_S_FMT`.
0288 However, for coded formats that include stream resolution information,
0289 after the decoder is done parsing the information from the stream, it will
0290 update the ``CAPTURE`` format with new values and signal a source change
0291 event, regardless of whether they match the values set by the client or
0292 not.
0293
0294 .. important::
0295
0296 Changing the ``OUTPUT`` format may change the currently set ``CAPTURE``
0297 format. How the new ``CAPTURE`` format is determined is up to the decoder
0298 and the client must ensure it matches its needs afterwards.
0299
0300 2. Allocate source (bytestream) buffers via :c:func:`VIDIOC_REQBUFS` on
0301 ``OUTPUT``.
0302
0303 * **Required fields:**
0304
0305 ``count``
0306 requested number of buffers to allocate; greater than zero.
0307
0308 ``type``
0309 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0310
0311 ``memory``
0312 follows standard semantics.
0313
0314 * **Return fields:**
0315
0316 ``count``
0317 the actual number of buffers allocated.
0318
0319 .. warning::
0320
0321 The actual number of allocated buffers may differ from the ``count``
0322 given. The client must check the updated value of ``count`` after the
0323 call returns.
0324
0325 Alternatively, :c:func:`VIDIOC_CREATE_BUFS` on the ``OUTPUT`` queue can be
0326 used to have more control over buffer allocation.
0327
0328 * **Required fields:**
0329
0330 ``count``
0331 requested number of buffers to allocate; greater than zero.
0332
0333 ``type``
0334 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0335
0336 ``memory``
0337 follows standard semantics.
0338
0339 ``format``
0340 follows standard semantics.
0341
0342 * **Return fields:**
0343
0344 ``count``
0345 adjusted to the number of allocated buffers.
0346
0347 .. warning::
0348
0349 The actual number of allocated buffers may differ from the ``count``
0350 given. The client must check the updated value of ``count`` after the
0351 call returns.
0352
0353 3. Start streaming on the ``OUTPUT`` queue via :c:func:`VIDIOC_STREAMON`.
0354
0355 4. **This step only applies to coded formats that contain resolution information
0356 in the stream.** Continue queuing/dequeuing bytestream buffers to/from the
0357 ``OUTPUT`` queue via :c:func:`VIDIOC_QBUF` and :c:func:`VIDIOC_DQBUF`. The
0358 buffers will be processed and returned to the client in order, until
0359 required metadata to configure the ``CAPTURE`` queue are found. This is
0360 indicated by the decoder sending a ``V4L2_EVENT_SOURCE_CHANGE`` event with
0361 ``changes`` set to ``V4L2_EVENT_SRC_CH_RESOLUTION``.
0362
0363 * It is not an error if the first buffer does not contain enough data for
0364 this to occur. Processing of the buffers will continue as long as more
0365 data is needed.
0366
0367 * If data in a buffer that triggers the event is required to decode the
0368 first frame, it will not be returned to the client, until the
0369 initialization sequence completes and the frame is decoded.
0370
0371 * If the client has not set the coded resolution of the stream on its own,
0372 calling :c:func:`VIDIOC_G_FMT`, :c:func:`VIDIOC_S_FMT`,
0373 :c:func:`VIDIOC_TRY_FMT` or :c:func:`VIDIOC_REQBUFS` on the ``CAPTURE``
0374 queue will not return the real values for the stream until a
0375 ``V4L2_EVENT_SOURCE_CHANGE`` event with ``changes`` set to
0376 ``V4L2_EVENT_SRC_CH_RESOLUTION`` is signaled.
0377
0378 .. important::
0379
0380 Any client query issued after the decoder queues the event will return
0381 values applying to the just parsed stream, including queue formats,
0382 selection rectangles and controls.
0383
0384 .. note::
0385
0386 A client capable of acquiring stream parameters from the bytestream on
0387 its own may attempt to set the width and height of the ``OUTPUT`` format
0388 to non-zero values matching the coded size of the stream, skip this step
0389 and continue with the `Capture Setup` sequence. However, it must not
0390 rely on any driver queries regarding stream parameters, such as
0391 selection rectangles and controls, since the decoder has not parsed them
0392 from the stream yet. If the values configured by the client do not match
0393 those parsed by the decoder, a `Dynamic Resolution Change` will be
0394 triggered to reconfigure them.
0395
0396 .. note::
0397
0398 No decoded frames are produced during this phase.
0399
0400 5. Continue with the `Capture Setup` sequence.
0401
0402 Capture Setup
0403 =============
0404
0405 1. Call :c:func:`VIDIOC_G_FMT` on the ``CAPTURE`` queue to get format for the
0406 destination buffers parsed/decoded from the bytestream.
0407
0408 * **Required fields:**
0409
0410 ``type``
0411 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0412
0413 * **Return fields:**
0414
0415 ``width``, ``height``
0416 frame buffer resolution for the decoded frames.
0417
0418 ``pixelformat``
0419 pixel format for decoded frames.
0420
0421 ``num_planes`` (for _MPLANE ``type`` only)
0422 number of planes for pixelformat.
0423
0424 ``sizeimage``, ``bytesperline``
0425 as per standard semantics; matching frame buffer format.
0426
0427 .. note::
0428
0429 The value of ``pixelformat`` may be any pixel format supported by the
0430 decoder for the current stream. The decoder should choose a
0431 preferred/optimal format for the default configuration. For example, a
0432 YUV format may be preferred over an RGB format if an additional
0433 conversion step would be required for the latter.
0434
0435 2. **Optional.** Acquire the visible resolution via
0436 :c:func:`VIDIOC_G_SELECTION`.
0437
0438 * **Required fields:**
0439
0440 ``type``
0441 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0442
0443 ``target``
0444 set to ``V4L2_SEL_TGT_COMPOSE``.
0445
0446 * **Return fields:**
0447
0448 ``r.left``, ``r.top``, ``r.width``, ``r.height``
0449 the visible rectangle; it must fit within the frame buffer resolution
0450 returned by :c:func:`VIDIOC_G_FMT` on ``CAPTURE``.
0451
0452 * The following selection targets are supported on ``CAPTURE``:
0453
0454 ``V4L2_SEL_TGT_CROP_BOUNDS``
0455 corresponds to the coded resolution of the stream.
0456
0457 ``V4L2_SEL_TGT_CROP_DEFAULT``
0458 the rectangle covering the part of the ``CAPTURE`` buffer that
0459 contains meaningful picture data (visible area); width and height
0460 will be equal to the visible resolution of the stream.
0461
0462 ``V4L2_SEL_TGT_CROP``
0463 the rectangle within the coded resolution to be output to
0464 ``CAPTURE``; defaults to ``V4L2_SEL_TGT_CROP_DEFAULT``; read-only on
0465 hardware without additional compose/scaling capabilities.
0466
0467 ``V4L2_SEL_TGT_COMPOSE_BOUNDS``
0468 the maximum rectangle within a ``CAPTURE`` buffer, which the cropped
0469 frame can be composed into; equal to ``V4L2_SEL_TGT_CROP`` if the
0470 hardware does not support compose/scaling.
0471
0472 ``V4L2_SEL_TGT_COMPOSE_DEFAULT``
0473 equal to ``V4L2_SEL_TGT_CROP``.
0474
0475 ``V4L2_SEL_TGT_COMPOSE``
0476 the rectangle inside a ``CAPTURE`` buffer into which the cropped
0477 frame is written; defaults to ``V4L2_SEL_TGT_COMPOSE_DEFAULT``;
0478 read-only on hardware without additional compose/scaling capabilities.
0479
0480 ``V4L2_SEL_TGT_COMPOSE_PADDED``
0481 the rectangle inside a ``CAPTURE`` buffer which is overwritten by the
0482 hardware; equal to ``V4L2_SEL_TGT_COMPOSE`` if the hardware does not
0483 write padding pixels.
0484
0485 .. warning::
0486
0487 The values are guaranteed to be meaningful only after the decoder
0488 successfully parses the stream metadata. The client must not rely on the
0489 query before that happens.
0490
0491 3. **Optional.** Enumerate ``CAPTURE`` formats via :c:func:`VIDIOC_ENUM_FMT` on
0492 the ``CAPTURE`` queue. Once the stream information is parsed and known, the
0493 client may use this ioctl to discover which raw formats are supported for
0494 given stream and select one of them via :c:func:`VIDIOC_S_FMT`.
0495
0496 .. important::
0497
0498 The decoder will return only formats supported for the currently
0499 established coded format, as per the ``OUTPUT`` format and/or stream
0500 metadata parsed in this initialization sequence, even if more formats
0501 may be supported by the decoder in general. In other words, the set
0502 returned will be a subset of the initial query mentioned in the
0503 `Querying Capabilities` section.
0504
0505 For example, a decoder may support YUV and RGB formats for resolutions
0506 1920x1088 and lower, but only YUV for higher resolutions (due to
0507 hardware limitations). After parsing a resolution of 1920x1088 or lower,
0508 :c:func:`VIDIOC_ENUM_FMT` may return a set of YUV and RGB pixel formats,
0509 but after parsing resolution higher than 1920x1088, the decoder will not
0510 return RGB, unsupported for this resolution.
0511
0512 However, subsequent resolution change event triggered after
0513 discovering a resolution change within the same stream may switch
0514 the stream into a lower resolution and :c:func:`VIDIOC_ENUM_FMT`
0515 would return RGB formats again in that case.
0516
0517 4. **Optional.** Set the ``CAPTURE`` format via :c:func:`VIDIOC_S_FMT` on the
0518 ``CAPTURE`` queue. The client may choose a different format than
0519 selected/suggested by the decoder in :c:func:`VIDIOC_G_FMT`.
0520
0521 * **Required fields:**
0522
0523 ``type``
0524 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0525
0526 ``pixelformat``
0527 a raw pixel format.
0528
0529 ``width``, ``height``
0530 frame buffer resolution of the decoded stream; typically unchanged from
0531 what was returned with :c:func:`VIDIOC_G_FMT`, but it may be different
0532 if the hardware supports composition and/or scaling.
0533
0534 * Setting the ``CAPTURE`` format will reset the compose selection rectangles
0535 to their default values, based on the new resolution, as described in the
0536 previous step.
0537
0538 5. **Optional.** Set the compose rectangle via :c:func:`VIDIOC_S_SELECTION` on
0539 the ``CAPTURE`` queue if it is desired and if the decoder has compose and/or
0540 scaling capabilities.
0541
0542 * **Required fields:**
0543
0544 ``type``
0545 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0546
0547 ``target``
0548 set to ``V4L2_SEL_TGT_COMPOSE``.
0549
0550 ``r.left``, ``r.top``, ``r.width``, ``r.height``
0551 the rectangle inside a ``CAPTURE`` buffer into which the cropped
0552 frame is written; defaults to ``V4L2_SEL_TGT_COMPOSE_DEFAULT``;
0553 read-only on hardware without additional compose/scaling capabilities.
0554
0555 * **Return fields:**
0556
0557 ``r.left``, ``r.top``, ``r.width``, ``r.height``
0558 the visible rectangle; it must fit within the frame buffer resolution
0559 returned by :c:func:`VIDIOC_G_FMT` on ``CAPTURE``.
0560
0561 .. warning::
0562
0563 The decoder may adjust the compose rectangle to the nearest
0564 supported one to meet codec and hardware requirements. The client needs
0565 to check the adjusted rectangle returned by :c:func:`VIDIOC_S_SELECTION`.
0566
0567 6. If all the following conditions are met, the client may resume the decoding
0568 instantly:
0569
0570 * ``sizeimage`` of the new format (determined in previous steps) is less
0571 than or equal to the size of currently allocated buffers,
0572
0573 * the number of buffers currently allocated is greater than or equal to the
0574 minimum number of buffers acquired in previous steps. To fulfill this
0575 requirement, the client may use :c:func:`VIDIOC_CREATE_BUFS` to add new
0576 buffers.
0577
0578 In that case, the remaining steps do not apply and the client may resume
0579 the decoding by one of the following actions:
0580
0581 * if the ``CAPTURE`` queue is streaming, call :c:func:`VIDIOC_DECODER_CMD`
0582 with the ``V4L2_DEC_CMD_START`` command,
0583
0584 * if the ``CAPTURE`` queue is not streaming, call :c:func:`VIDIOC_STREAMON`
0585 on the ``CAPTURE`` queue.
0586
0587 However, if the client intends to change the buffer set, to lower
0588 memory usage or for any other reasons, it may be achieved by following
0589 the steps below.
0590
0591 7. **If the** ``CAPTURE`` **queue is streaming,** keep queuing and dequeuing
0592 buffers on the ``CAPTURE`` queue until a buffer marked with the
0593 ``V4L2_BUF_FLAG_LAST`` flag is dequeued.
0594
0595 8. **If the** ``CAPTURE`` **queue is streaming,** call :c:func:`VIDIOC_STREAMOFF`
0596 on the ``CAPTURE`` queue to stop streaming.
0597
0598 .. warning::
0599
0600 The ``OUTPUT`` queue must remain streaming. Calling
0601 :c:func:`VIDIOC_STREAMOFF` on it would abort the sequence and trigger a
0602 seek.
0603
0604 9. **If the** ``CAPTURE`` **queue has buffers allocated,** free the ``CAPTURE``
0605 buffers using :c:func:`VIDIOC_REQBUFS`.
0606
0607 * **Required fields:**
0608
0609 ``count``
0610 set to 0.
0611
0612 ``type``
0613 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0614
0615 ``memory``
0616 follows standard semantics.
0617
0618 10. Allocate ``CAPTURE`` buffers via :c:func:`VIDIOC_REQBUFS` on the
0619 ``CAPTURE`` queue.
0620
0621 * **Required fields:**
0622
0623 ``count``
0624 requested number of buffers to allocate; greater than zero.
0625
0626 ``type``
0627 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0628
0629 ``memory``
0630 follows standard semantics.
0631
0632 * **Return fields:**
0633
0634 ``count``
0635 actual number of buffers allocated.
0636
0637 .. warning::
0638
0639 The actual number of allocated buffers may differ from the ``count``
0640 given. The client must check the updated value of ``count`` after the
0641 call returns.
0642
0643 .. note::
0644
0645 To allocate more than the minimum number of buffers (for pipeline
0646 depth), the client may query the ``V4L2_CID_MIN_BUFFERS_FOR_CAPTURE``
0647 control to get the minimum number of buffers required, and pass the
0648 obtained value plus the number of additional buffers needed in the
0649 ``count`` field to :c:func:`VIDIOC_REQBUFS`.
0650
0651 Alternatively, :c:func:`VIDIOC_CREATE_BUFS` on the ``CAPTURE`` queue can be
0652 used to have more control over buffer allocation. For example, by
0653 allocating buffers larger than the current ``CAPTURE`` format, future
0654 resolution changes can be accommodated.
0655
0656 * **Required fields:**
0657
0658 ``count``
0659 requested number of buffers to allocate; greater than zero.
0660
0661 ``type``
0662 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
0663
0664 ``memory``
0665 follows standard semantics.
0666
0667 ``format``
0668 a format representing the maximum framebuffer resolution to be
0669 accommodated by newly allocated buffers.
0670
0671 * **Return fields:**
0672
0673 ``count``
0674 adjusted to the number of allocated buffers.
0675
0676 .. warning::
0677
0678 The actual number of allocated buffers may differ from the ``count``
0679 given. The client must check the updated value of ``count`` after the
0680 call returns.
0681
0682 .. note::
0683
0684 To allocate buffers for a format different than parsed from the stream
0685 metadata, the client must proceed as follows, before the metadata
0686 parsing is initiated:
0687
0688 * set width and height of the ``OUTPUT`` format to desired coded resolution to
0689 let the decoder configure the ``CAPTURE`` format appropriately,
0690
0691 * query the ``CAPTURE`` format using :c:func:`VIDIOC_G_FMT` and save it
0692 until this step.
0693
0694 The format obtained in the query may be then used with
0695 :c:func:`VIDIOC_CREATE_BUFS` in this step to allocate the buffers.
0696
0697 11. Call :c:func:`VIDIOC_STREAMON` on the ``CAPTURE`` queue to start decoding
0698 frames.
0699
0700 Decoding
0701 ========
0702
0703 This state is reached after the `Capture Setup` sequence finishes successfully.
0704 In this state, the client queues and dequeues buffers to both queues via
0705 :c:func:`VIDIOC_QBUF` and :c:func:`VIDIOC_DQBUF`, following the standard
0706 semantics.
0707
0708 The content of the source ``OUTPUT`` buffers depends on the active coded pixel
0709 format and may be affected by codec-specific extended controls, as stated in
0710 the documentation of each format.
0711
0712 Both queues operate independently, following the standard behavior of V4L2
0713 buffer queues and memory-to-memory devices. In addition, the order of decoded
0714 frames dequeued from the ``CAPTURE`` queue may differ from the order of queuing
0715 coded frames to the ``OUTPUT`` queue, due to properties of the selected coded
0716 format, e.g. frame reordering.
0717
0718 The client must not assume any direct relationship between ``CAPTURE``
0719 and ``OUTPUT`` buffers and any specific timing of buffers becoming
0720 available to dequeue. Specifically:
0721
0722 * a buffer queued to ``OUTPUT`` may result in no buffers being produced
0723 on ``CAPTURE`` (e.g. if it does not contain encoded data, or if only
0724 metadata syntax structures are present in it),
0725
0726 * a buffer queued to ``OUTPUT`` may result in more than one buffer produced
0727 on ``CAPTURE`` (if the encoded data contained more than one frame, or if
0728 returning a decoded frame allowed the decoder to return a frame that
0729 preceded it in decode, but succeeded it in the display order),
0730
0731 * a buffer queued to ``OUTPUT`` may result in a buffer being produced on
0732 ``CAPTURE`` later into decode process, and/or after processing further
0733 ``OUTPUT`` buffers, or be returned out of order, e.g. if display
0734 reordering is used,
0735
0736 * buffers may become available on the ``CAPTURE`` queue without additional
0737 buffers queued to ``OUTPUT`` (e.g. during drain or ``EOS``), because of the
0738 ``OUTPUT`` buffers queued in the past whose decoding results are only
0739 available at later time, due to specifics of the decoding process.
0740
0741 .. note::
0742
0743 To allow matching decoded ``CAPTURE`` buffers with ``OUTPUT`` buffers they
0744 originated from, the client can set the ``timestamp`` field of the
0745 :c:type:`v4l2_buffer` struct when queuing an ``OUTPUT`` buffer. The
0746 ``CAPTURE`` buffer(s), which resulted from decoding that ``OUTPUT`` buffer
0747 will have their ``timestamp`` field set to the same value when dequeued.
0748
0749 In addition to the straightforward case of one ``OUTPUT`` buffer producing
0750 one ``CAPTURE`` buffer, the following cases are defined:
0751
0752 * one ``OUTPUT`` buffer generates multiple ``CAPTURE`` buffers: the same
0753 ``OUTPUT`` timestamp will be copied to multiple ``CAPTURE`` buffers.
0754
0755 * multiple ``OUTPUT`` buffers generate one ``CAPTURE`` buffer: timestamp of
0756 the ``OUTPUT`` buffer queued first will be copied.
0757
0758 * the decoding order differs from the display order (i.e. the ``CAPTURE``
0759 buffers are out-of-order compared to the ``OUTPUT`` buffers): ``CAPTURE``
0760 timestamps will not retain the order of ``OUTPUT`` timestamps.
0761
0762 .. note::
0763
0764 The backing memory of ``CAPTURE`` buffers that are used as reference frames
0765 by the stream may be read by the hardware even after they are dequeued.
0766 Consequently, the client should avoid writing into this memory while the
0767 ``CAPTURE`` queue is streaming. Failure to observe this may result in
0768 corruption of decoded frames.
0769
0770 Similarly, when using a memory type other than ``V4L2_MEMORY_MMAP``, the
0771 client should make sure that each ``CAPTURE`` buffer is always queued with
0772 the same backing memory for as long as the ``CAPTURE`` queue is streaming.
0773 The reason for this is that V4L2 buffer indices can be used by drivers to
0774 identify frames. Thus, if the backing memory of a reference frame is
0775 submitted under a different buffer ID, the driver may misidentify it and
0776 decode a new frame into it while it is still in use, resulting in corruption
0777 of the following frames.
0778
0779 During the decoding, the decoder may initiate one of the special sequences, as
0780 listed below. The sequences will result in the decoder returning all the
0781 ``CAPTURE`` buffers that originated from all the ``OUTPUT`` buffers processed
0782 before the sequence started. Last of the buffers will have the
0783 ``V4L2_BUF_FLAG_LAST`` flag set. To determine the sequence to follow, the client
0784 must check if there is any pending event and:
0785
0786 * if a ``V4L2_EVENT_SOURCE_CHANGE`` event with ``changes`` set to
0787 ``V4L2_EVENT_SRC_CH_RESOLUTION`` is pending, the `Dynamic Resolution
0788 Change` sequence needs to be followed,
0789
0790 * if a ``V4L2_EVENT_EOS`` event is pending, the `End of Stream` sequence needs
0791 to be followed.
0792
0793 Some of the sequences can be intermixed with each other and need to be handled
0794 as they happen. The exact operation is documented for each sequence.
0795
0796 Should a decoding error occur, it will be reported to the client with the level
0797 of details depending on the decoder capabilities. Specifically:
0798
0799 * the CAPTURE buffer that contains the results of the failed decode operation
0800 will be returned with the V4L2_BUF_FLAG_ERROR flag set,
0801
0802 * if the decoder is able to precisely report the OUTPUT buffer that triggered
0803 the error, such buffer will be returned with the V4L2_BUF_FLAG_ERROR flag
0804 set.
0805
0806 In case of a fatal failure that does not allow the decoding to continue, any
0807 further operations on corresponding decoder file handle will return the -EIO
0808 error code. The client may close the file handle and open a new one, or
0809 alternatively reinitialize the instance by stopping streaming on both queues,
0810 releasing all buffers and performing the Initialization sequence again.
0811
0812 Seek
0813 ====
0814
0815 Seek is controlled by the ``OUTPUT`` queue, as it is the source of coded data.
0816 The seek does not require any specific operation on the ``CAPTURE`` queue, but
0817 it may be affected as per normal decoder operation.
0818
0819 1. Stop the ``OUTPUT`` queue to begin the seek sequence via
0820 :c:func:`VIDIOC_STREAMOFF`.
0821
0822 * **Required fields:**
0823
0824 ``type``
0825 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0826
0827 * The decoder will drop all the pending ``OUTPUT`` buffers and they must be
0828 treated as returned to the client (following standard semantics).
0829
0830 2. Restart the ``OUTPUT`` queue via :c:func:`VIDIOC_STREAMON`.
0831
0832 * **Required fields:**
0833
0834 ``type``
0835 a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
0836
0837 * The decoder will start accepting new source bytestream buffers after the
0838 call returns.
0839
0840 3. Start queuing buffers containing coded data after the seek to the ``OUTPUT``
0841 queue until a suitable resume point is found.
0842
0843 .. note::
0844
0845 There is no requirement to begin queuing coded data starting exactly
0846 from a resume point (e.g. SPS or a keyframe). Any queued ``OUTPUT``
0847 buffers will be processed and returned to the client until a suitable
0848 resume point is found. While looking for a resume point, the decoder
0849 should not produce any decoded frames into ``CAPTURE`` buffers.
0850
0851 Some hardware is known to mishandle seeks to a non-resume point. Such an
0852 operation may result in an unspecified number of corrupted decoded frames
0853 being made available on the ``CAPTURE`` queue. Drivers must ensure that
0854 no fatal decoding errors or crashes occur, and implement any necessary
0855 handling and workarounds for hardware issues related to seek operations.
0856
0857 .. warning::
0858
0859 In case of the H.264/HEVC codec, the client must take care not to seek
0860 over a change of SPS/PPS. Even though the target frame could be a
0861 keyframe, the stale SPS/PPS inside decoder state would lead to undefined
0862 results when decoding. Although the decoder must handle that case without
0863 a crash or a fatal decode error, the client must not expect a sensible
0864 decode output.
0865
0866 If the hardware can detect such corrupted decoded frames, then
0867 corresponding buffers will be returned to the client with the
0868 V4L2_BUF_FLAG_ERROR set. See the `Decoding` section for further
0869 description of decode error reporting.
0870
0871 4. After a resume point is found, the decoder will start returning ``CAPTURE``
0872 buffers containing decoded frames.
0873
0874 .. important::
0875
0876 A seek may result in the `Dynamic Resolution Change` sequence being
0877 initiated, due to the seek target having decoding parameters different from
0878 the part of the stream decoded before the seek. The sequence must be handled
0879 as per normal decoder operation.
0880
0881 .. warning::
0882
0883 It is not specified when the ``CAPTURE`` queue starts producing buffers
0884 containing decoded data from the ``OUTPUT`` buffers queued after the seek,
0885 as it operates independently from the ``OUTPUT`` queue.
0886
0887 The decoder may return a number of remaining ``CAPTURE`` buffers containing
0888 decoded frames originating from the ``OUTPUT`` buffers queued before the
0889 seek sequence is performed.
0890
0891 The ``VIDIOC_STREAMOFF`` operation discards any remaining queued
0892 ``OUTPUT`` buffers, which means that not all of the ``OUTPUT`` buffers
0893 queued before the seek sequence may have matching ``CAPTURE`` buffers
0894 produced. For example, given the sequence of operations on the
0895 ``OUTPUT`` queue:
0896
0897 QBUF(A), QBUF(B), STREAMOFF(), STREAMON(), QBUF(G), QBUF(H),
0898
0899 any of the following results on the ``CAPTURE`` queue is allowed:
0900
0901 {A', B', G', H'}, {A', G', H'}, {G', H'}.
0902
0903 To determine the CAPTURE buffer containing the first decoded frame after the
0904 seek, the client may observe the timestamps to match the CAPTURE and OUTPUT
0905 buffers or use V4L2_DEC_CMD_STOP and V4L2_DEC_CMD_START to drain the
0906 decoder.
0907
0908 .. note::
0909
0910 To achieve instantaneous seek, the client may restart streaming on the
0911 ``CAPTURE`` queue too to discard decoded, but not yet dequeued buffers.
0912
0913 Dynamic Resolution Change
0914 =========================
0915
0916 Streams that include resolution metadata in the bytestream may require switching
0917 to a different resolution during the decoding.
0918
0919 .. note::
0920
0921 Not all decoders can detect resolution changes. Those that do set the
0922 ``V4L2_FMT_FLAG_DYN_RESOLUTION`` flag for the coded format when
0923 :c:func:`VIDIOC_ENUM_FMT` is called.
0924
0925 The sequence starts when the decoder detects a coded frame with one or more of
0926 the following parameters different from those previously established (and
0927 reflected by corresponding queries):
0928
0929 * coded resolution (``OUTPUT`` width and height),
0930
0931 * visible resolution (selection rectangles),
0932
0933 * the minimum number of buffers needed for decoding,
0934
0935 * bit-depth of the bitstream has been changed.
0936
0937 Whenever that happens, the decoder must proceed as follows:
0938
0939 1. After encountering a resolution change in the stream, the decoder sends a
0940 ``V4L2_EVENT_SOURCE_CHANGE`` event with ``changes`` set to
0941 ``V4L2_EVENT_SRC_CH_RESOLUTION``.
0942
0943 .. important::
0944
0945 Any client query issued after the decoder queues the event will return
0946 values applying to the stream after the resolution change, including
0947 queue formats, selection rectangles and controls.
0948
0949 2. The decoder will then process and decode all remaining buffers from before
0950 the resolution change point.
0951
0952 * The last buffer from before the change must be marked with the
0953 ``V4L2_BUF_FLAG_LAST`` flag, similarly to the `Drain` sequence above.
0954
0955 .. warning::
0956
0957 The last buffer may be empty (with :c:type:`v4l2_buffer` ``bytesused``
0958 = 0) and in that case it must be ignored by the client, as it does not
0959 contain a decoded frame.
0960
0961 .. note::
0962
0963 Any attempt to dequeue more ``CAPTURE`` buffers beyond the buffer marked
0964 with ``V4L2_BUF_FLAG_LAST`` will result in a -EPIPE error from
0965 :c:func:`VIDIOC_DQBUF`.
0966
0967 The client must continue the sequence as described below to continue the
0968 decoding process.
0969
0970 1. Dequeue the source change event.
0971
0972 .. important::
0973
0974 A source change triggers an implicit decoder drain, similar to the
0975 explicit `Drain` sequence. The decoder is stopped after it completes.
0976 The decoding process must be resumed with either a pair of calls to
0977 :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
0978 ``CAPTURE`` queue, or a call to :c:func:`VIDIOC_DECODER_CMD` with the
0979 ``V4L2_DEC_CMD_START`` command.
0980
0981 2. Continue with the `Capture Setup` sequence.
0982
0983 .. note::
0984
0985 During the resolution change sequence, the ``OUTPUT`` queue must remain
0986 streaming. Calling :c:func:`VIDIOC_STREAMOFF` on the ``OUTPUT`` queue would
0987 abort the sequence and initiate a seek.
0988
0989 In principle, the ``OUTPUT`` queue operates separately from the ``CAPTURE``
0990 queue and this remains true for the duration of the entire resolution change
0991 sequence as well.
0992
0993 The client should, for best performance and simplicity, keep queuing/dequeuing
0994 buffers to/from the ``OUTPUT`` queue even while processing this sequence.
0995
0996 Drain
0997 =====
0998
0999 To ensure that all queued ``OUTPUT`` buffers have been processed and related
1000 ``CAPTURE`` buffers are given to the client, the client must follow the drain
1001 sequence described below. After the drain sequence ends, the client has
1002 received all decoded frames for all ``OUTPUT`` buffers queued before the
1003 sequence was started.
1004
1005 1. Begin drain by issuing :c:func:`VIDIOC_DECODER_CMD`.
1006
1007 * **Required fields:**
1008
1009 ``cmd``
1010 set to ``V4L2_DEC_CMD_STOP``.
1011
1012 ``flags``
1013 set to 0.
1014
1015 ``pts``
1016 set to 0.
1017
1018 .. warning::
1019
1020 The sequence can be only initiated if both ``OUTPUT`` and ``CAPTURE``
1021 queues are streaming. For compatibility reasons, the call to
1022 :c:func:`VIDIOC_DECODER_CMD` will not fail even if any of the queues is
1023 not streaming, but at the same time it will not initiate the `Drain`
1024 sequence and so the steps described below would not be applicable.
1025
1026 2. Any ``OUTPUT`` buffers queued by the client before the
1027 :c:func:`VIDIOC_DECODER_CMD` was issued will be processed and decoded as
1028 normal. The client must continue to handle both queues independently,
1029 similarly to normal decode operation. This includes:
1030
1031 * handling any operations triggered as a result of processing those buffers,
1032 such as the `Dynamic Resolution Change` sequence, before continuing with
1033 the drain sequence,
1034
1035 * queuing and dequeuing ``CAPTURE`` buffers, until a buffer marked with the
1036 ``V4L2_BUF_FLAG_LAST`` flag is dequeued,
1037
1038 .. warning::
1039
1040 The last buffer may be empty (with :c:type:`v4l2_buffer`
1041 ``bytesused`` = 0) and in that case it must be ignored by the client,
1042 as it does not contain a decoded frame.
1043
1044 .. note::
1045
1046 Any attempt to dequeue more ``CAPTURE`` buffers beyond the buffer
1047 marked with ``V4L2_BUF_FLAG_LAST`` will result in a -EPIPE error from
1048 :c:func:`VIDIOC_DQBUF`.
1049
1050 * dequeuing processed ``OUTPUT`` buffers, until all the buffers queued
1051 before the ``V4L2_DEC_CMD_STOP`` command are dequeued,
1052
1053 * dequeuing the ``V4L2_EVENT_EOS`` event, if the client subscribed to it.
1054
1055 .. note::
1056
1057 For backwards compatibility, the decoder will signal a ``V4L2_EVENT_EOS``
1058 event when the last frame has been decoded and all frames are ready to be
1059 dequeued. It is a deprecated behavior and the client must not rely on it.
1060 The ``V4L2_BUF_FLAG_LAST`` buffer flag should be used instead.
1061
1062 3. Once all the ``OUTPUT`` buffers queued before the ``V4L2_DEC_CMD_STOP`` call
1063 are dequeued and the last ``CAPTURE`` buffer is dequeued, the decoder is
1064 stopped and it will accept, but not process, any newly queued ``OUTPUT``
1065 buffers until the client issues any of the following operations:
1066
1067 * ``V4L2_DEC_CMD_START`` - the decoder will not be reset and will resume
1068 operation normally, with all the state from before the drain,
1069
1070 * a pair of :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
1071 ``CAPTURE`` queue - the decoder will resume the operation normally,
1072 however any ``CAPTURE`` buffers still in the queue will be returned to the
1073 client,
1074
1075 * a pair of :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
1076 ``OUTPUT`` queue - any pending source buffers will be returned to the
1077 client and the `Seek` sequence will be triggered.
1078
1079 .. note::
1080
1081 Once the drain sequence is initiated, the client needs to drive it to
1082 completion, as described by the steps above, unless it aborts the process by
1083 issuing :c:func:`VIDIOC_STREAMOFF` on any of the ``OUTPUT`` or ``CAPTURE``
1084 queues. The client is not allowed to issue ``V4L2_DEC_CMD_START`` or
1085 ``V4L2_DEC_CMD_STOP`` again while the drain sequence is in progress and they
1086 will fail with -EBUSY error code if attempted.
1087
1088 Although not mandatory, the availability of decoder commands may be queried
1089 using :c:func:`VIDIOC_TRY_DECODER_CMD`.
1090
1091 End of Stream
1092 =============
1093
1094 If the decoder encounters an end of stream marking in the stream, the decoder
1095 will initiate the `Drain` sequence, which the client must handle as described
1096 above, skipping the initial :c:func:`VIDIOC_DECODER_CMD`.
1097
1098 Commit Points
1099 =============
1100
1101 Setting formats and allocating buffers trigger changes in the behavior of the
1102 decoder.
1103
1104 1. Setting the format on the ``OUTPUT`` queue may change the set of formats
1105 supported/advertised on the ``CAPTURE`` queue. In particular, it also means
1106 that the ``CAPTURE`` format may be reset and the client must not rely on the
1107 previously set format being preserved.
1108
1109 2. Enumerating formats on the ``CAPTURE`` queue always returns only formats
1110 supported for the current ``OUTPUT`` format.
1111
1112 3. Setting the format on the ``CAPTURE`` queue does not change the list of
1113 formats available on the ``OUTPUT`` queue. An attempt to set a ``CAPTURE``
1114 format that is not supported for the currently selected ``OUTPUT`` format
1115 will result in the decoder adjusting the requested ``CAPTURE`` format to a
1116 supported one.
1117
1118 4. Enumerating formats on the ``OUTPUT`` queue always returns the full set of
1119 supported coded formats, irrespectively of the current ``CAPTURE`` format.
1120
1121 5. While buffers are allocated on any of the ``OUTPUT`` or ``CAPTURE`` queues,
1122 the client must not change the format on the ``OUTPUT`` queue. Drivers will
1123 return the -EBUSY error code for any such format change attempt.
1124
1125 To summarize, setting formats and allocation must always start with the
1126 ``OUTPUT`` queue and the ``OUTPUT`` queue is the master that governs the
1127 set of supported formats for the ``CAPTURE`` queue.