dev-encoder.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. .. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
  2. .. c:namespace:: V4L
  3. .. _encoder:
  4. *************************************************
  5. Memory-to-Memory Stateful Video Encoder Interface
  6. *************************************************
  7. A stateful video encoder takes raw video frames in display order and encodes
  8. them into a bytestream. It generates complete chunks of the bytestream, including
  9. all metadata, headers, etc. The resulting bytestream does not require any
  10. further post-processing by the client.
  11. Performing software stream processing, header generation etc. in the driver
  12. in order to support this interface is strongly discouraged. In case such
  13. operations are needed, use of the Stateless Video Encoder Interface (in
  14. development) is strongly advised.
  15. Conventions and Notations Used in This Document
  16. ===============================================
  17. 1. The general V4L2 API rules apply if not specified in this document
  18. otherwise.
  19. 2. The meaning of words "must", "may", "should", etc. is as per `RFC
  20. 2119 <https://tools.ietf.org/html/rfc2119>`_.
  21. 3. All steps not marked "optional" are required.
  22. 4. :c:func:`VIDIOC_G_EXT_CTRLS` and :c:func:`VIDIOC_S_EXT_CTRLS` may be used
  23. interchangeably with :c:func:`VIDIOC_G_CTRL` and :c:func:`VIDIOC_S_CTRL`,
  24. unless specified otherwise.
  25. 5. Single-planar API (see :ref:`planar-apis`) and applicable structures may be
  26. used interchangeably with multi-planar API, unless specified otherwise,
  27. depending on encoder capabilities and following the general V4L2 guidelines.
  28. 6. i = [a..b]: sequence of integers from a to b, inclusive, i.e. i =
  29. [0..2]: i = 0, 1, 2.
  30. 7. Given an ``OUTPUT`` buffer A, then A' represents a buffer on the ``CAPTURE``
  31. queue containing data that resulted from processing buffer A.
  32. Glossary
  33. ========
  34. Refer to :ref:`decoder-glossary`.
  35. State Machine
  36. =============
  37. .. kernel-render:: DOT
  38. :alt: DOT digraph of encoder state machine
  39. :caption: Encoder State Machine
  40. digraph encoder_state_machine {
  41. node [shape = doublecircle, label="Encoding"] Encoding;
  42. node [shape = circle, label="Initialization"] Initialization;
  43. node [shape = circle, label="Stopped"] Stopped;
  44. node [shape = circle, label="Drain"] Drain;
  45. node [shape = circle, label="Reset"] Reset;
  46. node [shape = point]; qi
  47. qi -> Initialization [ label = "open()" ];
  48. Initialization -> Encoding [ label = "Both queues streaming" ];
  49. Encoding -> Drain [ label = "V4L2_ENC_CMD_STOP" ];
  50. Encoding -> Reset [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
  51. Encoding -> Stopped [ label = "VIDIOC_STREAMOFF(OUTPUT)" ];
  52. Encoding -> Encoding;
  53. Drain -> Stopped [ label = "All CAPTURE\nbuffers dequeued\nor\nVIDIOC_STREAMOFF(OUTPUT)" ];
  54. Drain -> Reset [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
  55. Reset -> Encoding [ label = "VIDIOC_STREAMON(CAPTURE)" ];
  56. Reset -> Initialization [ label = "VIDIOC_REQBUFS(OUTPUT, 0)" ];
  57. Stopped -> Encoding [ label = "V4L2_ENC_CMD_START\nor\nVIDIOC_STREAMON(OUTPUT)" ];
  58. Stopped -> Reset [ label = "VIDIOC_STREAMOFF(CAPTURE)" ];
  59. }
  60. Querying Capabilities
  61. =====================
  62. 1. To enumerate the set of coded formats supported by the encoder, the
  63. client may call :c:func:`VIDIOC_ENUM_FMT` on ``CAPTURE``.
  64. * The full set of supported formats will be returned, regardless of the
  65. format set on ``OUTPUT``.
  66. 2. To enumerate the set of supported raw formats, the client may call
  67. :c:func:`VIDIOC_ENUM_FMT` on ``OUTPUT``.
  68. * Only the formats supported for the format currently active on ``CAPTURE``
  69. will be returned.
  70. * In order to enumerate raw formats supported by a given coded format,
  71. the client must first set that coded format on ``CAPTURE`` and then
  72. enumerate the formats on ``OUTPUT``.
  73. 3. The client may use :c:func:`VIDIOC_ENUM_FRAMESIZES` to detect supported
  74. resolutions for a given format, passing the desired pixel format in
  75. :c:type:`v4l2_frmsizeenum` ``pixel_format``.
  76. * Values returned by :c:func:`VIDIOC_ENUM_FRAMESIZES` for a coded pixel
  77. format will include all possible coded resolutions supported by the
  78. encoder for the given coded pixel format.
  79. * Values returned by :c:func:`VIDIOC_ENUM_FRAMESIZES` for a raw pixel format
  80. will include all possible frame buffer resolutions supported by the
  81. encoder for the given raw pixel format and coded format currently set on
  82. ``CAPTURE``.
  83. 4. The client may use :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` to detect supported
  84. frame intervals for a given format and resolution, passing the desired pixel
  85. format in :c:type:`v4l2_frmivalenum` ``pixel_format`` and the resolution
  86. in :c:type:`v4l2_frmivalenum` ``width`` and :c:type:`v4l2_frmivalenum`
  87. ``height``.
  88. * Values returned by :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` for a coded pixel
  89. format and coded resolution will include all possible frame intervals
  90. supported by the encoder for the given coded pixel format and resolution.
  91. * Values returned by :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` for a raw pixel
  92. format and resolution will include all possible frame intervals supported
  93. by the encoder for the given raw pixel format and resolution and for the
  94. coded format, coded resolution and coded frame interval currently set on
  95. ``CAPTURE``.
  96. * Support for :c:func:`VIDIOC_ENUM_FRAMEINTERVALS` is optional. If it is
  97. not implemented, then there are no special restrictions other than the
  98. limits of the codec itself.
  99. 5. Supported profiles and levels for the coded format currently set on
  100. ``CAPTURE``, if applicable, may be queried using their respective controls
  101. via :c:func:`VIDIOC_QUERYCTRL`.
  102. 6. Any additional encoder capabilities may be discovered by querying
  103. their respective controls.
  104. Initialization
  105. ==============
  106. 1. Set the coded format on the ``CAPTURE`` queue via :c:func:`VIDIOC_S_FMT`.
  107. * **Required fields:**
  108. ``type``
  109. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
  110. ``pixelformat``
  111. the coded format to be produced.
  112. ``sizeimage``
  113. desired size of ``CAPTURE`` buffers; the encoder may adjust it to
  114. match hardware requirements.
  115. ``width``, ``height``
  116. ignored (read-only).
  117. other fields
  118. follow standard semantics.
  119. * **Returned fields:**
  120. ``sizeimage``
  121. adjusted size of ``CAPTURE`` buffers.
  122. ``width``, ``height``
  123. the coded size selected by the encoder based on current state, e.g.
  124. ``OUTPUT`` format, selection rectangles, etc. (read-only).
  125. .. important::
  126. Changing the ``CAPTURE`` format may change the currently set ``OUTPUT``
  127. format. How the new ``OUTPUT`` format is determined is up to the encoder
  128. and the client must ensure it matches its needs afterwards.
  129. 2. **Optional.** Enumerate supported ``OUTPUT`` formats (raw formats for
  130. source) for the selected coded format via :c:func:`VIDIOC_ENUM_FMT`.
  131. * **Required fields:**
  132. ``type``
  133. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
  134. other fields
  135. follow standard semantics.
  136. * **Returned fields:**
  137. ``pixelformat``
  138. raw format supported for the coded format currently selected on
  139. the ``CAPTURE`` queue.
  140. other fields
  141. follow standard semantics.
  142. 3. Set the raw source format on the ``OUTPUT`` queue via
  143. :c:func:`VIDIOC_S_FMT`.
  144. * **Required fields:**
  145. ``type``
  146. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
  147. ``pixelformat``
  148. raw format of the source.
  149. ``width``, ``height``
  150. source resolution.
  151. other fields
  152. follow standard semantics.
  153. * **Returned fields:**
  154. ``width``, ``height``
  155. may be adjusted to match encoder minimums, maximums and alignment
  156. requirements, as required by the currently selected formats, as
  157. reported by :c:func:`VIDIOC_ENUM_FRAMESIZES`.
  158. other fields
  159. follow standard semantics.
  160. * Setting the ``OUTPUT`` format will reset the selection rectangles to their
  161. default values, based on the new resolution, as described in the next
  162. step.
  163. 4. Set the raw frame interval on the ``OUTPUT`` queue via
  164. :c:func:`VIDIOC_S_PARM`. This also sets the coded frame interval on the
  165. ``CAPTURE`` queue to the same value.
  166. * **Required fields:**
  167. ``type``
  168. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
  169. ``parm.output``
  170. set all fields except ``parm.output.timeperframe`` to 0.
  171. ``parm.output.timeperframe``
  172. the desired frame interval; the encoder may adjust it to
  173. match hardware requirements.
  174. * **Returned fields:**
  175. ``parm.output.timeperframe``
  176. the adjusted frame interval.
  177. .. important::
  178. Changing the ``OUTPUT`` frame interval *also* sets the framerate that
  179. the encoder uses to encode the video. So setting the frame interval
  180. to 1/24 (or 24 frames per second) will produce a coded video stream
  181. that can be played back at that speed. The frame interval for the
  182. ``OUTPUT`` queue is just a hint, the application may provide raw
  183. frames at a different rate. It can be used by the driver to help
  184. schedule multiple encoders running in parallel.
  185. In the next step the ``CAPTURE`` frame interval can optionally be
  186. changed to a different value. This is useful for off-line encoding
  187. were the coded frame interval can be different from the rate at
  188. which raw frames are supplied.
  189. .. important::
  190. ``timeperframe`` deals with *frames*, not fields. So for interlaced
  191. formats this is the time per two fields, since a frame consists of
  192. a top and a bottom field.
  193. .. note::
  194. It is due to historical reasons that changing the ``OUTPUT`` frame
  195. interval also changes the coded frame interval on the ``CAPTURE``
  196. queue. Ideally these would be independent settings, but that would
  197. break the existing API.
  198. 5. **Optional** Set the coded frame interval on the ``CAPTURE`` queue via
  199. :c:func:`VIDIOC_S_PARM`. This is only necessary if the coded frame
  200. interval is different from the raw frame interval, which is typically
  201. the case for off-line encoding. Support for this feature is signalled
  202. by the :ref:`V4L2_FMT_FLAG_ENC_CAP_FRAME_INTERVAL <fmtdesc-flags>` format flag.
  203. * **Required fields:**
  204. ``type``
  205. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``CAPTURE``.
  206. ``parm.capture``
  207. set all fields except ``parm.capture.timeperframe`` to 0.
  208. ``parm.capture.timeperframe``
  209. the desired coded frame interval; the encoder may adjust it to
  210. match hardware requirements.
  211. * **Returned fields:**
  212. ``parm.capture.timeperframe``
  213. the adjusted frame interval.
  214. .. important::
  215. Changing the ``CAPTURE`` frame interval sets the framerate for the
  216. coded video. It does *not* set the rate at which buffers arrive on the
  217. ``CAPTURE`` queue, that depends on how fast the encoder is and how
  218. fast raw frames are queued on the ``OUTPUT`` queue.
  219. .. important::
  220. ``timeperframe`` deals with *frames*, not fields. So for interlaced
  221. formats this is the time per two fields, since a frame consists of
  222. a top and a bottom field.
  223. .. note::
  224. Not all drivers support this functionality, in that case just set
  225. the desired coded frame interval for the ``OUTPUT`` queue.
  226. However, drivers that can schedule multiple encoders based on the
  227. ``OUTPUT`` frame interval must support this optional feature.
  228. 6. **Optional.** Set the visible resolution for the stream metadata via
  229. :c:func:`VIDIOC_S_SELECTION` on the ``OUTPUT`` queue if it is desired
  230. to be different than the full OUTPUT resolution.
  231. * **Required fields:**
  232. ``type``
  233. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
  234. ``target``
  235. set to ``V4L2_SEL_TGT_CROP``.
  236. ``r.left``, ``r.top``, ``r.width``, ``r.height``
  237. visible rectangle; this must fit within the `V4L2_SEL_TGT_CROP_BOUNDS`
  238. rectangle and may be subject to adjustment to match codec and
  239. hardware constraints.
  240. * **Returned fields:**
  241. ``r.left``, ``r.top``, ``r.width``, ``r.height``
  242. visible rectangle adjusted by the encoder.
  243. * The following selection targets are supported on ``OUTPUT``:
  244. ``V4L2_SEL_TGT_CROP_BOUNDS``
  245. equal to the full source frame, matching the active ``OUTPUT``
  246. format.
  247. ``V4L2_SEL_TGT_CROP_DEFAULT``
  248. equal to ``V4L2_SEL_TGT_CROP_BOUNDS``.
  249. ``V4L2_SEL_TGT_CROP``
  250. rectangle within the source buffer to be encoded into the
  251. ``CAPTURE`` stream; defaults to ``V4L2_SEL_TGT_CROP_DEFAULT``.
  252. .. note::
  253. A common use case for this selection target is encoding a source
  254. video with a resolution that is not a multiple of a macroblock,
  255. e.g. the common 1920x1080 resolution may require the source
  256. buffers to be aligned to 1920x1088 for codecs with 16x16 macroblock
  257. size. To avoid encoding the padding, the client needs to explicitly
  258. configure this selection target to 1920x1080.
  259. .. warning::
  260. The encoder may adjust the crop/compose rectangles to the nearest
  261. supported ones to meet codec and hardware requirements. The client needs
  262. to check the adjusted rectangle returned by :c:func:`VIDIOC_S_SELECTION`.
  263. 7. Allocate buffers for both ``OUTPUT`` and ``CAPTURE`` via
  264. :c:func:`VIDIOC_REQBUFS`. This may be performed in any order.
  265. * **Required fields:**
  266. ``count``
  267. requested number of buffers to allocate; greater than zero.
  268. ``type``
  269. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT`` or
  270. ``CAPTURE``.
  271. other fields
  272. follow standard semantics.
  273. * **Returned fields:**
  274. ``count``
  275. actual number of buffers allocated.
  276. .. warning::
  277. The actual number of allocated buffers may differ from the ``count``
  278. given. The client must check the updated value of ``count`` after the
  279. call returns.
  280. .. note::
  281. To allocate more than the minimum number of OUTPUT buffers (for pipeline
  282. depth), the client may query the ``V4L2_CID_MIN_BUFFERS_FOR_OUTPUT``
  283. control to get the minimum number of buffers required, and pass the
  284. obtained value plus the number of additional buffers needed in the
  285. ``count`` field to :c:func:`VIDIOC_REQBUFS`.
  286. Alternatively, :c:func:`VIDIOC_CREATE_BUFS` can be used to have more
  287. control over buffer allocation.
  288. * **Required fields:**
  289. ``count``
  290. requested number of buffers to allocate; greater than zero.
  291. ``type``
  292. a ``V4L2_BUF_TYPE_*`` enum appropriate for ``OUTPUT``.
  293. other fields
  294. follow standard semantics.
  295. * **Returned fields:**
  296. ``count``
  297. adjusted to the number of allocated buffers.
  298. 8. Begin streaming on both ``OUTPUT`` and ``CAPTURE`` queues via
  299. :c:func:`VIDIOC_STREAMON`. This may be performed in any order. The actual
  300. encoding process starts when both queues start streaming.
  301. .. note::
  302. If the client stops the ``CAPTURE`` queue during the encode process and then
  303. restarts it again, the encoder will begin generating a stream independent
  304. from the stream generated before the stop. The exact constraints depend
  305. on the coded format, but may include the following implications:
  306. * encoded frames produced after the restart must not reference any
  307. frames produced before the stop, e.g. no long term references for
  308. H.264/HEVC,
  309. * any headers that must be included in a standalone stream must be
  310. produced again, e.g. SPS and PPS for H.264/HEVC.
  311. Encoding
  312. ========
  313. This state is reached after the `Initialization` sequence finishes
  314. successfully. In this state, the client queues and dequeues buffers to both
  315. queues via :c:func:`VIDIOC_QBUF` and :c:func:`VIDIOC_DQBUF`, following the
  316. standard semantics.
  317. The content of encoded ``CAPTURE`` buffers depends on the active coded pixel
  318. format and may be affected by codec-specific extended controls, as stated
  319. in the documentation of each format.
  320. Both queues operate independently, following standard behavior of V4L2 buffer
  321. queues and memory-to-memory devices. In addition, the order of encoded frames
  322. dequeued from the ``CAPTURE`` queue may differ from the order of queuing raw
  323. frames to the ``OUTPUT`` queue, due to properties of the selected coded format,
  324. e.g. frame reordering.
  325. The client must not assume any direct relationship between ``CAPTURE`` and
  326. ``OUTPUT`` buffers and any specific timing of buffers becoming
  327. available to dequeue. Specifically:
  328. * a buffer queued to ``OUTPUT`` may result in more than one buffer produced on
  329. ``CAPTURE`` (for example, if returning an encoded frame allowed the encoder
  330. to return a frame that preceded it in display, but succeeded it in the decode
  331. order; however, there may be other reasons for this as well),
  332. * a buffer queued to ``OUTPUT`` may result in a buffer being produced on
  333. ``CAPTURE`` later into encode process, and/or after processing further
  334. ``OUTPUT`` buffers, or be returned out of order, e.g. if display
  335. reordering is used,
  336. * buffers may become available on the ``CAPTURE`` queue without additional
  337. buffers queued to ``OUTPUT`` (e.g. during drain or ``EOS``), because of the
  338. ``OUTPUT`` buffers queued in the past whose encoding results are only
  339. available at later time, due to specifics of the encoding process,
  340. * buffers queued to ``OUTPUT`` may not become available to dequeue instantly
  341. after being encoded into a corresponding ``CAPTURE`` buffer, e.g. if the
  342. encoder needs to use the frame as a reference for encoding further frames.
  343. .. note::
  344. To allow matching encoded ``CAPTURE`` buffers with ``OUTPUT`` buffers they
  345. originated from, the client can set the ``timestamp`` field of the
  346. :c:type:`v4l2_buffer` struct when queuing an ``OUTPUT`` buffer. The
  347. ``CAPTURE`` buffer(s), which resulted from encoding that ``OUTPUT`` buffer
  348. will have their ``timestamp`` field set to the same value when dequeued.
  349. In addition to the straightforward case of one ``OUTPUT`` buffer producing
  350. one ``CAPTURE`` buffer, the following cases are defined:
  351. * one ``OUTPUT`` buffer generates multiple ``CAPTURE`` buffers: the same
  352. ``OUTPUT`` timestamp will be copied to multiple ``CAPTURE`` buffers,
  353. * the encoding order differs from the presentation order (i.e. the
  354. ``CAPTURE`` buffers are out-of-order compared to the ``OUTPUT`` buffers):
  355. ``CAPTURE`` timestamps will not retain the order of ``OUTPUT`` timestamps.
  356. .. note::
  357. To let the client distinguish between frame types (keyframes, intermediate
  358. frames; the exact list of types depends on the coded format), the
  359. ``CAPTURE`` buffers will have corresponding flag bits set in their
  360. :c:type:`v4l2_buffer` struct when dequeued. See the documentation of
  361. :c:type:`v4l2_buffer` and each coded pixel format for exact list of flags
  362. and their meanings.
  363. Should an encoding error occur, it will be reported to the client with the level
  364. of details depending on the encoder capabilities. Specifically:
  365. * the ``CAPTURE`` buffer (if any) that contains the results of the failed encode
  366. operation will be returned with the ``V4L2_BUF_FLAG_ERROR`` flag set,
  367. * if the encoder is able to precisely report the ``OUTPUT`` buffer(s) that triggered
  368. the error, such buffer(s) will be returned with the ``V4L2_BUF_FLAG_ERROR`` flag
  369. set.
  370. .. note::
  371. If a ``CAPTURE`` buffer is too small then it is just returned with the
  372. ``V4L2_BUF_FLAG_ERROR`` flag set. More work is needed to detect that this
  373. error occurred because the buffer was too small, and to provide support to
  374. free existing buffers that were too small.
  375. In case of a fatal failure that does not allow the encoding to continue, any
  376. further operations on corresponding encoder file handle will return the -EIO
  377. error code. The client may close the file handle and open a new one, or
  378. alternatively reinitialize the instance by stopping streaming on both queues,
  379. releasing all buffers and performing the Initialization sequence again.
  380. Encoding Parameter Changes
  381. ==========================
  382. The client is allowed to use :c:func:`VIDIOC_S_CTRL` to change encoder
  383. parameters at any time. The availability of parameters is encoder-specific
  384. and the client must query the encoder to find the set of available controls.
  385. The ability to change each parameter during encoding is encoder-specific, as
  386. per the standard semantics of the V4L2 control interface. The client may
  387. attempt to set a control during encoding and if the operation fails with the
  388. -EBUSY error code, the ``CAPTURE`` queue needs to be stopped for the
  389. configuration change to be allowed. To do this, it may follow the `Drain`
  390. sequence to avoid losing the already queued/encoded frames.
  391. The timing of parameter updates is encoder-specific, as per the standard
  392. semantics of the V4L2 control interface. If the client needs to apply the
  393. parameters exactly at specific frame, using the Request API
  394. (:ref:`media-request-api`) should be considered, if supported by the encoder.
  395. Drain
  396. =====
  397. To ensure that all the queued ``OUTPUT`` buffers have been processed and the
  398. related ``CAPTURE`` buffers are given to the client, the client must follow the
  399. drain sequence described below. After the drain sequence ends, the client has
  400. received all encoded frames for all ``OUTPUT`` buffers queued before the
  401. sequence was started.
  402. 1. Begin the drain sequence by issuing :c:func:`VIDIOC_ENCODER_CMD`.
  403. * **Required fields:**
  404. ``cmd``
  405. set to ``V4L2_ENC_CMD_STOP``.
  406. ``flags``
  407. set to 0.
  408. ``pts``
  409. set to 0.
  410. .. warning::
  411. The sequence can be only initiated if both ``OUTPUT`` and ``CAPTURE``
  412. queues are streaming. For compatibility reasons, the call to
  413. :c:func:`VIDIOC_ENCODER_CMD` will not fail even if any of the queues is
  414. not streaming, but at the same time it will not initiate the `Drain`
  415. sequence and so the steps described below would not be applicable.
  416. 2. Any ``OUTPUT`` buffers queued by the client before the
  417. :c:func:`VIDIOC_ENCODER_CMD` was issued will be processed and encoded as
  418. normal. The client must continue to handle both queues independently,
  419. similarly to normal encode operation. This includes:
  420. * queuing and dequeuing ``CAPTURE`` buffers, until a buffer marked with the
  421. ``V4L2_BUF_FLAG_LAST`` flag is dequeued,
  422. .. warning::
  423. The last buffer may be empty (with :c:type:`v4l2_buffer`
  424. ``bytesused`` = 0) and in that case it must be ignored by the client,
  425. as it does not contain an encoded frame.
  426. .. note::
  427. Any attempt to dequeue more ``CAPTURE`` buffers beyond the buffer
  428. marked with ``V4L2_BUF_FLAG_LAST`` will result in a -EPIPE error from
  429. :c:func:`VIDIOC_DQBUF`.
  430. * dequeuing processed ``OUTPUT`` buffers, until all the buffers queued
  431. before the ``V4L2_ENC_CMD_STOP`` command are dequeued,
  432. * dequeuing the ``V4L2_EVENT_EOS`` event, if the client subscribes to it.
  433. .. note::
  434. For backwards compatibility, the encoder will signal a ``V4L2_EVENT_EOS``
  435. event when the last frame has been encoded and all frames are ready to be
  436. dequeued. It is deprecated behavior and the client must not rely on it.
  437. The ``V4L2_BUF_FLAG_LAST`` buffer flag should be used instead.
  438. 3. Once all ``OUTPUT`` buffers queued before the ``V4L2_ENC_CMD_STOP`` call are
  439. dequeued and the last ``CAPTURE`` buffer is dequeued, the encoder is stopped
  440. and it will accept, but not process any newly queued ``OUTPUT`` buffers
  441. until the client issues any of the following operations:
  442. * ``V4L2_ENC_CMD_START`` - the encoder will not be reset and will resume
  443. operation normally, with all the state from before the drain,
  444. * a pair of :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
  445. ``CAPTURE`` queue - the encoder will be reset (see the `Reset` sequence)
  446. and then resume encoding,
  447. * a pair of :c:func:`VIDIOC_STREAMOFF` and :c:func:`VIDIOC_STREAMON` on the
  448. ``OUTPUT`` queue - the encoder will resume operation normally, however any
  449. source frames queued to the ``OUTPUT`` queue between ``V4L2_ENC_CMD_STOP``
  450. and :c:func:`VIDIOC_STREAMOFF` will be discarded.
  451. .. note::
  452. Once the drain sequence is initiated, the client needs to drive it to
  453. completion, as described by the steps above, unless it aborts the process by
  454. issuing :c:func:`VIDIOC_STREAMOFF` on any of the ``OUTPUT`` or ``CAPTURE``
  455. queues. The client is not allowed to issue ``V4L2_ENC_CMD_START`` or
  456. ``V4L2_ENC_CMD_STOP`` again while the drain sequence is in progress and they
  457. will fail with -EBUSY error code if attempted.
  458. For reference, handling of various corner cases is described below:
  459. * In case of no buffer in the ``OUTPUT`` queue at the time the
  460. ``V4L2_ENC_CMD_STOP`` command was issued, the drain sequence completes
  461. immediately and the encoder returns an empty ``CAPTURE`` buffer with the
  462. ``V4L2_BUF_FLAG_LAST`` flag set.
  463. * In case of no buffer in the ``CAPTURE`` queue at the time the drain
  464. sequence completes, the next time the client queues a ``CAPTURE`` buffer
  465. it is returned at once as an empty buffer with the ``V4L2_BUF_FLAG_LAST``
  466. flag set.
  467. * If :c:func:`VIDIOC_STREAMOFF` is called on the ``CAPTURE`` queue in the
  468. middle of the drain sequence, the drain sequence is canceled and all
  469. ``CAPTURE`` buffers are implicitly returned to the client.
  470. * If :c:func:`VIDIOC_STREAMOFF` is called on the ``OUTPUT`` queue in the
  471. middle of the drain sequence, the drain sequence completes immediately and
  472. next ``CAPTURE`` buffer will be returned empty with the
  473. ``V4L2_BUF_FLAG_LAST`` flag set.
  474. Although not mandatory, the availability of encoder commands may be queried
  475. using :c:func:`VIDIOC_TRY_ENCODER_CMD`.
  476. Reset
  477. =====
  478. The client may want to request the encoder to reinitialize the encoding, so
  479. that the following stream data becomes independent from the stream data
  480. generated before. Depending on the coded format, that may imply that:
  481. * encoded frames produced after the restart must not reference any frames
  482. produced before the stop, e.g. no long term references for H.264/HEVC,
  483. * any headers that must be included in a standalone stream must be produced
  484. again, e.g. SPS and PPS for H.264/HEVC.
  485. This can be achieved by performing the reset sequence.
  486. 1. Perform the `Drain` sequence to ensure all the in-flight encoding finishes
  487. and respective buffers are dequeued.
  488. 2. Stop streaming on the ``CAPTURE`` queue via :c:func:`VIDIOC_STREAMOFF`. This
  489. will return all currently queued ``CAPTURE`` buffers to the client, without
  490. valid frame data.
  491. 3. Start streaming on the ``CAPTURE`` queue via :c:func:`VIDIOC_STREAMON` and
  492. continue with regular encoding sequence. The encoded frames produced into
  493. ``CAPTURE`` buffers from now on will contain a standalone stream that can be
  494. decoded without the need for frames encoded before the reset sequence,
  495. starting at the first ``OUTPUT`` buffer queued after issuing the
  496. `V4L2_ENC_CMD_STOP` of the `Drain` sequence.
  497. This sequence may be also used to change encoding parameters for encoders
  498. without the ability to change the parameters on the fly.
  499. Commit Points
  500. =============
  501. Setting formats and allocating buffers triggers changes in the behavior of the
  502. encoder.
  503. 1. Setting the format on the ``CAPTURE`` queue may change the set of formats
  504. supported/advertised on the ``OUTPUT`` queue. In particular, it also means
  505. that the ``OUTPUT`` format may be reset and the client must not rely on the
  506. previously set format being preserved.
  507. 2. Enumerating formats on the ``OUTPUT`` queue always returns only formats
  508. supported for the current ``CAPTURE`` format.
  509. 3. Setting the format on the ``OUTPUT`` queue does not change the list of
  510. formats available on the ``CAPTURE`` queue. An attempt to set the ``OUTPUT``
  511. format that is not supported for the currently selected ``CAPTURE`` format
  512. will result in the encoder adjusting the requested ``OUTPUT`` format to a
  513. supported one.
  514. 4. Enumerating formats on the ``CAPTURE`` queue always returns the full set of
  515. supported coded formats, irrespective of the current ``OUTPUT`` format.
  516. 5. While buffers are allocated on any of the ``OUTPUT`` or ``CAPTURE`` queues,
  517. the client must not change the format on the ``CAPTURE`` queue. Drivers will
  518. return the -EBUSY error code for any such format change attempt.
  519. To summarize, setting formats and allocation must always start with the
  520. ``CAPTURE`` queue and the ``CAPTURE`` queue is the master that governs the
  521. set of supported formats for the ``OUTPUT`` queue.