← Documents Documentation/userspace-api/media/v4l/buffer.rst GitHub 원문 ↗

Linux 6.18.37 · Userspace API / Media / V4L

V4L2 buffer

Streaming buffer의 layout 변경 규칙, 핵심 structure, buffer type·flag·memory model과 SMPTE 계열 timecode ABI를 정의합니다.

Source pathDocumentation/userspace-api/media/v4l/buffer.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

buffer.rst:1-801

V4L2 streaming buffer ABI의 중심 문서입니다. Format/control이 layout 또는 size를 바꿀 때의 정지·재할당·오류 계약부터 `v4l2_buffer`와 plane field, queue state, frame/timestamp flag, memory model과 timecode까지 application과 driver 양쪽의 책임을 함께 규정합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
2 .. c:namespace:: V4L
3
4 .. _buffer:
5
6 *******
7 Buffers
8 *******
9
10 A buffer contains data exchanged by application and driver using one of
11 the Streaming I/O methods. In the multi-planar API, the data is held in
12 planes, while the buffer structure acts as a container for the planes.
13 Only pointers to buffers (planes) are exchanged, the data itself is not
14 copied. These pointers, together with meta-information like timestamps
15 or field parity, are stored in a struct :c:type:`v4l2_buffer`,
16 argument to the :ref:`VIDIOC_QUERYBUF`,
17 :ref:`VIDIOC_QBUF <VIDIOC_QBUF>` and
18 :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl. In the multi-planar API,
19 some plane-specific members of struct :c:type:`v4l2_buffer`,
20 such as pointers and sizes for each plane, are stored in
21 struct :c:type:`v4l2_plane` instead. In that case,
22 struct :c:type:`v4l2_buffer` contains an array of plane structures.
23
24 Dequeued video buffers come with timestamps. The driver decides at which
25 part of the frame and with which clock the timestamp is taken. Please
26 see flags in the masks ``V4L2_BUF_FLAG_TIMESTAMP_MASK`` and
27 ``V4L2_BUF_FLAG_TSTAMP_SRC_MASK`` in :ref:`buffer-flags`. These flags
28 are always valid and constant across all buffers during the whole video
29 stream. Changes in these flags may take place as a side effect of
30 :ref:`VIDIOC_S_INPUT <VIDIOC_G_INPUT>` or
31 :ref:`VIDIOC_S_OUTPUT <VIDIOC_G_OUTPUT>` however. The
32 ``V4L2_BUF_FLAG_TIMESTAMP_COPY`` timestamp type which is used by e.g. on
33 mem-to-mem devices is an exception to the rule: the timestamp source
34 flags are copied from the OUTPUT video buffer to the CAPTURE video
35 buffer.
36
37 Interactions between formats, controls and buffers
38 ==================================================
39
40 V4L2 exposes parameters that influence the buffer size, or the way data is
41 laid out in the buffer. Those parameters are exposed through both formats and
42 controls. One example of such a control is the ``V4L2_CID_ROTATE`` control
43 that modifies the direction in which pixels are stored in the buffer, as well
44 as the buffer size when the selected format includes padding at the end of
45 lines.
46
47 The set of information needed to interpret the content of a buffer (e.g. the
48 pixel format, the line stride, the tiling orientation or the rotation) is
49 collectively referred to in the rest of this section as the buffer layout.
50
51 Controls that can modify the buffer layout shall set the
52 ``V4L2_CTRL_FLAG_MODIFY_LAYOUT`` flag.
53
54 Modifying formats or controls that influence the buffer size or layout require
55 the stream to be stopped. Any attempt at such a modification while the stream
56 is active shall cause the ioctl setting the format or the control to return
57 the ``EBUSY`` error code. In that case drivers shall also set the
58 ``V4L2_CTRL_FLAG_GRABBED`` flag when calling
59 :c:func:`VIDIOC_QUERYCTRL` or :c:func:`VIDIOC_QUERY_EXT_CTRL` for such a
60 control while the stream is active.
61
62 .. note::
63
64 The :c:func:`VIDIOC_S_SELECTION` ioctl can, depending on the hardware (for
65 instance if the device doesn't include a scaler), modify the format in
66 addition to the selection rectangle. Similarly, the
67 :c:func:`VIDIOC_S_INPUT`, :c:func:`VIDIOC_S_OUTPUT`, :c:func:`VIDIOC_S_STD`
68 and :c:func:`VIDIOC_S_DV_TIMINGS` ioctls can also modify the format and
69 selection rectangles. When those ioctls result in a buffer size or layout
70 change, drivers shall handle that condition as they would handle it in the
71 :c:func:`VIDIOC_S_FMT` ioctl in all cases described in this section.
72
73 Controls that only influence the buffer layout can be modified at any time
74 when the stream is stopped. As they don't influence the buffer size, no
75 special handling is needed to synchronize those controls with buffer
76 allocation and the ``V4L2_CTRL_FLAG_GRABBED`` flag is cleared once the
77 stream is stopped.
78
79 Formats and controls that influence the buffer size interact with buffer
80 allocation. The simplest way to handle this is for drivers to always require
81 buffers to be reallocated in order to change those formats or controls. In
82 that case, to perform such changes, userspace applications shall first stop
83 the video stream with the :c:func:`VIDIOC_STREAMOFF` ioctl if it is running
84 and free all buffers with the :c:func:`VIDIOC_REQBUFS` ioctl if they are
85 allocated. After freeing all buffers the ``V4L2_CTRL_FLAG_GRABBED`` flag
86 for controls is cleared. The format or controls can then be modified, and
87 buffers shall then be reallocated and the stream restarted. A typical ioctl
88 sequence is
89
90 #. VIDIOC_STREAMOFF
91 #. VIDIOC_REQBUFS(0)
92 #. VIDIOC_S_EXT_CTRLS
93 #. VIDIOC_S_FMT
94 #. VIDIOC_REQBUFS(n)
95 #. VIDIOC_QBUF
96 #. VIDIOC_STREAMON
97
98 The second :c:func:`VIDIOC_REQBUFS` call will take the new format and control
99 value into account to compute the buffer size to allocate. Applications can
100 also retrieve the size by calling the :c:func:`VIDIOC_G_FMT` ioctl if needed.
101
102 .. note::
103
104 The API doesn't mandate the above order for control (3.) and format (4.)
105 changes. Format and controls can be set in a different order, or even
106 interleaved, depending on the device and use case. For instance some
107 controls might behave differently for different pixel formats, in which
108 case the format might need to be set first.
109
110 When reallocation is required, any attempt to modify format or controls that
111 influences the buffer size while buffers are allocated shall cause the format
112 or control set ioctl to return the ``EBUSY`` error. Any attempt to queue a
113 buffer too small for the current format or controls shall cause the
114 :c:func:`VIDIOC_QBUF` ioctl to return a ``EINVAL`` error.
115
116 Buffer reallocation is an expensive operation. To avoid that cost, drivers can
117 (and are encouraged to) allow format or controls that influence the buffer
118 size to be changed with buffers allocated. In that case, a typical ioctl
119 sequence to modify format and controls is
120
121 #. VIDIOC_STREAMOFF
122 #. VIDIOC_S_EXT_CTRLS
123 #. VIDIOC_S_FMT
124 #. VIDIOC_QBUF
125 #. VIDIOC_STREAMON
126
127 For this sequence to operate correctly, queued buffers need to be large enough
128 for the new format or controls. Drivers shall return a ``ENOSPC`` error in
129 response to format change (:c:func:`VIDIOC_S_FMT`) or control changes
130 (:c:func:`VIDIOC_S_CTRL` or :c:func:`VIDIOC_S_EXT_CTRLS`) if buffers too small
131 for the new format are currently queued. As a simplification, drivers are
132 allowed to return a ``EBUSY`` error from these ioctls if any buffer is
133 currently queued, without checking the queued buffers sizes.
134
135 Additionally, drivers shall return a ``EINVAL`` error from the
136 :c:func:`VIDIOC_QBUF` ioctl if the buffer being queued is too small for the
137 current format or controls. Together, these requirements ensure that queued
138 buffers will always be large enough for the configured format and controls.
139
140 Userspace applications can query the buffer size required for a given format
141 and controls by first setting the desired control values and then trying the
142 desired format. The :c:func:`VIDIOC_TRY_FMT` ioctl will return the required
143 buffer size.
144
145 #. VIDIOC_S_EXT_CTRLS(x)
146 #. VIDIOC_TRY_FMT()
147 #. VIDIOC_S_EXT_CTRLS(y)
148 #. VIDIOC_TRY_FMT()
149
150 The :c:func:`VIDIOC_CREATE_BUFS` ioctl can then be used to allocate buffers
151 based on the queried sizes (for instance by allocating a set of buffers large
152 enough for all the desired formats and controls, or by allocating separate set
153 of appropriately sized buffers for each use case).
154
155 .. c:type:: v4l2_buffer
156
157 struct v4l2_buffer
158 ==================
159
160 .. tabularcolumns:: |p{2.9cm}|p{2.4cm}|p{12.0cm}|
161
162 .. cssclass:: longtable
163
164 .. flat-table:: struct v4l2_buffer
165 :header-rows: 0
166 :stub-columns: 0
167 :widths: 1 2 10
168
169 * - __u32
170 - ``index``
171 - Number of the buffer, set by the application except when calling
172 :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>`, then it is set by the
173 driver. This field can range from zero to the number of buffers
174 allocated with the :ref:`VIDIOC_REQBUFS` ioctl
175 (struct :c:type:`v4l2_requestbuffers`
176 ``count``), plus any buffers allocated with
177 :ref:`VIDIOC_CREATE_BUFS` minus one.
178 * - __u32
179 - ``type``
180 - Type of the buffer, same as struct
181 :c:type:`v4l2_format` ``type`` or struct
182 :c:type:`v4l2_requestbuffers` ``type``, set
183 by the application. See :c:type:`v4l2_buf_type`
184 * - __u32
185 - ``bytesused``
186 - The number of bytes occupied by the data in the buffer. It depends
187 on the negotiated data format and may change with each buffer for
188 compressed variable size data like JPEG images. Drivers must set
189 this field when ``type`` refers to a capture stream, applications
190 when it refers to an output stream. For multiplanar formats this field
191 is ignored and the
192 ``planes`` pointer is used instead.
193 * - __u32
194 - ``flags``
195 - Flags set by the application or driver, see :ref:`buffer-flags`.
196 * - __u32
197 - ``field``
198 - Indicates the field order of the image in the buffer, see
199 :c:type:`v4l2_field`. This field is not used when the buffer
200 contains VBI data. Drivers must set it when ``type`` refers to a
201 capture stream, applications when it refers to an output stream.
202 * - struct timeval
203 - ``timestamp``
204 - For capture streams this is time when the first data byte was
205 captured, as returned by the :c:func:`clock_gettime()` function
206 for the relevant clock id; see ``V4L2_BUF_FLAG_TIMESTAMP_*`` in
207 :ref:`buffer-flags`. For output streams the driver stores the
208 time at which the last data byte was actually sent out in the
209 ``timestamp`` field. This permits applications to monitor the
210 drift between the video and system clock. For output streams that
211 use ``V4L2_BUF_FLAG_TIMESTAMP_COPY`` the application has to fill
212 in the timestamp which will be copied by the driver to the capture
213 stream.
214 * - struct :c:type:`v4l2_timecode`
215 - ``timecode``
216 - When the ``V4L2_BUF_FLAG_TIMECODE`` flag is set in ``flags``, this
217 structure contains a frame timecode. In
218 :c:type:`V4L2_FIELD_ALTERNATE <v4l2_field>` mode the top and
219 bottom field contain the same timecode. Timecodes are intended to
220 help video editing and are typically recorded on video tapes, but
221 also embedded in compressed formats like MPEG. This field is
222 independent of the ``timestamp`` and ``sequence`` fields.
223 * - __u32
224 - ``sequence``
225 - Set by the driver, counting the frames (not fields!) in sequence.
226 This field is set for both input and output devices.
227 * - :cspan:`2`
228
229 In :c:type:`V4L2_FIELD_ALTERNATE <v4l2_field>` mode the top and
230 bottom field have the same sequence number. The count starts at
231 zero and includes dropped or repeated frames. A dropped frame was
232 received by an input device but could not be stored due to lack of
233 free buffer space. A repeated frame was displayed again by an
234 output device because the application did not pass new data in
235 time.
236
237 .. note::
238
239 This may count the frames received e.g. over USB, without
240 taking into account the frames dropped by the remote hardware due
241 to limited compression throughput or bus bandwidth. These devices
242 identify by not enumerating any video standards, see
243 :ref:`standard`.
244
245 * - __u32
246 - ``memory``
247 - This field must be set by applications and/or drivers in
248 accordance with the selected I/O method. See :c:type:`v4l2_memory`
249 * - union {
250 - ``m``
251 * - __u32
252 - ``offset``
253 - For the single-planar API and when ``memory`` is
254 ``V4L2_MEMORY_MMAP`` this is the offset of the buffer from the
255 start of the device memory. The value is returned by the driver
256 and apart of serving as parameter to the
257 :c:func:`mmap()` function not useful for applications.
258 See :ref:`mmap` for details
259 * - unsigned long
260 - ``userptr``
261 - For the single-planar API and when ``memory`` is
262 ``V4L2_MEMORY_USERPTR`` this is a pointer to the buffer (casted to
263 unsigned long type) in virtual memory, set by the application. See
264 :ref:`userp` for details.
265 * - struct v4l2_plane
266 - ``*planes``
267 - When using the multi-planar API, contains a userspace pointer to
268 an array of struct :c:type:`v4l2_plane`. The size of
269 the array should be put in the ``length`` field of this
270 struct :c:type:`v4l2_buffer` structure.
271 * - int
272 - ``fd``
273 - For the single-plane API and when ``memory`` is
274 ``V4L2_MEMORY_DMABUF`` this is the file descriptor associated with
275 a DMABUF buffer.
276 * - }
277 -
278 * - __u32
279 - ``length``
280 - Size of the buffer (not the payload) in bytes for the
281 single-planar API. This is set by the driver based on the calls to
282 :ref:`VIDIOC_REQBUFS` and/or
283 :ref:`VIDIOC_CREATE_BUFS`. For the
284 multi-planar API the application sets this to the number of
285 elements in the ``planes`` array. The driver will fill in the
286 actual number of valid elements in that array.
287 * - __u32
288 - ``reserved2``
289 - A place holder for future extensions. Drivers and applications
290 must set this to 0.
291 * - __u32
292 - ``request_fd``
293 - The file descriptor of the request to queue the buffer to. If the flag
294 ``V4L2_BUF_FLAG_REQUEST_FD`` is set, then the buffer will be
295 queued to this request. If the flag is not set, then this field will
296 be ignored.
297
298 The ``V4L2_BUF_FLAG_REQUEST_FD`` flag and this field are only used by
299 :ref:`ioctl VIDIOC_QBUF <VIDIOC_QBUF>` and ignored by other ioctls that
300 take a :c:type:`v4l2_buffer` as argument.
301
302 Applications should not set ``V4L2_BUF_FLAG_REQUEST_FD`` for any ioctls
303 other than :ref:`VIDIOC_QBUF <VIDIOC_QBUF>`.
304
305 If the device does not support requests, then ``EBADR`` will be returned.
306 If requests are supported but an invalid request file descriptor is
307 given, then ``EINVAL`` will be returned.
308
309
310 .. c:type:: v4l2_plane
311
312 struct v4l2_plane
313 =================
314
315 .. tabularcolumns:: |p{3.5cm}|p{3.5cm}|p{10.3cm}|
316
317 .. cssclass:: longtable
318
319 .. flat-table::
320 :header-rows: 0
321 :stub-columns: 0
322 :widths: 1 1 2
323
324 * - __u32
325 - ``bytesused``
326 - The number of bytes occupied by data in the plane (its payload).
327 Drivers must set this field when ``type`` refers to a capture
328 stream, applications when it refers to an output stream.
329
330 .. note::
331
332 Note that the actual image data starts at ``data_offset``
333 which may not be 0.
334 * - __u32
335 - ``length``
336 - Size in bytes of the plane (not its payload). This is set by the
337 driver based on the calls to
338 :ref:`VIDIOC_REQBUFS` and/or
339 :ref:`VIDIOC_CREATE_BUFS`.
340 * - union {
341 - ``m``
342 * - __u32
343 - ``mem_offset``
344 - When the memory type in the containing struct
345 :c:type:`v4l2_buffer` is ``V4L2_MEMORY_MMAP``, this
346 is the value that should be passed to :c:func:`mmap()`,
347 similar to the ``offset`` field in struct
348 :c:type:`v4l2_buffer`.
349 * - unsigned long
350 - ``userptr``
351 - When the memory type in the containing struct
352 :c:type:`v4l2_buffer` is ``V4L2_MEMORY_USERPTR``,
353 this is a userspace pointer to the memory allocated for this plane
354 by an application.
355 * - int
356 - ``fd``
357 - When the memory type in the containing struct
358 :c:type:`v4l2_buffer` is ``V4L2_MEMORY_DMABUF``,
359 this is a file descriptor associated with a DMABUF buffer, similar
360 to the ``fd`` field in struct :c:type:`v4l2_buffer`.
361 * - }
362 -
363 * - __u32
364 - ``data_offset``
365 - Offset in bytes to video data in the plane. Drivers must set this
366 field when ``type`` refers to a capture stream, applications when
367 it refers to an output stream.
368
369 .. note::
370
371 That data_offset is included in ``bytesused``. So the
372 size of the image in the plane is ``bytesused``-``data_offset``
373 at offset ``data_offset`` from the start of the plane.
374 * - __u32
375 - ``reserved[11]``
376 - Reserved for future use. Should be zeroed by drivers and
377 applications.
378
379
380 .. c:type:: v4l2_buf_type
381
382 enum v4l2_buf_type
383 ==================
384
385 .. cssclass:: longtable
386
387 .. tabularcolumns:: |p{7.8cm}|p{0.6cm}|p{8.9cm}|
388
389 .. flat-table::
390 :header-rows: 0
391 :stub-columns: 0
392 :widths: 4 1 9
393
394 * - ``V4L2_BUF_TYPE_VIDEO_CAPTURE``
395 - 1
396 - Buffer of a single-planar video capture stream, see
397 :ref:`capture`.
398 * - ``V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE``
399 - 9
400 - Buffer of a multi-planar video capture stream, see
401 :ref:`capture`.
402 * - ``V4L2_BUF_TYPE_VIDEO_OUTPUT``
403 - 2
404 - Buffer of a single-planar video output stream, see
405 :ref:`output`.
406 * - ``V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE``
407 - 10
408 - Buffer of a multi-planar video output stream, see :ref:`output`.
409 * - ``V4L2_BUF_TYPE_VIDEO_OVERLAY``
410 - 3
411 - Buffer for video overlay, see :ref:`overlay`.
412 * - ``V4L2_BUF_TYPE_VBI_CAPTURE``
413 - 4
414 - Buffer of a raw VBI capture stream, see :ref:`raw-vbi`.
415 * - ``V4L2_BUF_TYPE_VBI_OUTPUT``
416 - 5
417 - Buffer of a raw VBI output stream, see :ref:`raw-vbi`.
418 * - ``V4L2_BUF_TYPE_SLICED_VBI_CAPTURE``
419 - 6
420 - Buffer of a sliced VBI capture stream, see :ref:`sliced`.
421 * - ``V4L2_BUF_TYPE_SLICED_VBI_OUTPUT``
422 - 7
423 - Buffer of a sliced VBI output stream, see :ref:`sliced`.
424 * - ``V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY``
425 - 8
426 - Buffer for video output overlay (OSD), see :ref:`osd`.
427 * - ``V4L2_BUF_TYPE_SDR_CAPTURE``
428 - 11
429 - Buffer for Software Defined Radio (SDR) capture stream, see
430 :ref:`sdr`.
431 * - ``V4L2_BUF_TYPE_SDR_OUTPUT``
432 - 12
433 - Buffer for Software Defined Radio (SDR) output stream, see
434 :ref:`sdr`.
435 * - ``V4L2_BUF_TYPE_META_CAPTURE``
436 - 13
437 - Buffer for metadata capture, see :ref:`metadata`.
438 * - ``V4L2_BUF_TYPE_META_OUTPUT``
439 - 14
440 - Buffer for metadata output, see :ref:`metadata`.
441
442
443 .. _buffer-flags:
444
445 Buffer Flags
446 ============
447
448 .. raw:: latex
449
450 \footnotesize
451
452 .. tabularcolumns:: |p{6.5cm}|p{1.8cm}|p{9.0cm}|
453
454 .. cssclass:: longtable
455
456 .. flat-table::
457 :header-rows: 0
458 :stub-columns: 0
459 :widths: 65 18 70
460
461 * .. _`V4L2-BUF-FLAG-MAPPED`:
462
463 - ``V4L2_BUF_FLAG_MAPPED``
464 - 0x00000001
465 - The buffer resides in device memory and has been mapped into the
466 application's address space, see :ref:`mmap` for details.
467 Drivers set or clear this flag when the
468 :ref:`VIDIOC_QUERYBUF`,
469 :ref:`VIDIOC_QBUF` or
470 :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl is called. Set by the
471 driver.
472 * .. _`V4L2-BUF-FLAG-QUEUED`:
473
474 - ``V4L2_BUF_FLAG_QUEUED``
475 - 0x00000002
476 - Internally drivers maintain two buffer queues, an incoming and
477 outgoing queue. When this flag is set, the buffer is currently on
478 the incoming queue. It automatically moves to the outgoing queue
479 after the buffer has been filled (capture devices) or displayed
480 (output devices). Drivers set or clear this flag when the
481 ``VIDIOC_QUERYBUF`` ioctl is called. After (successful) calling
482 the ``VIDIOC_QBUF``\ ioctl it is always set and after
483 ``VIDIOC_DQBUF`` always cleared.
484 * .. _`V4L2-BUF-FLAG-DONE`:
485
486 - ``V4L2_BUF_FLAG_DONE``
487 - 0x00000004
488 - When this flag is set, the buffer is currently on the outgoing
489 queue, ready to be dequeued from the driver. Drivers set or clear
490 this flag when the ``VIDIOC_QUERYBUF`` ioctl is called. After
491 calling the ``VIDIOC_QBUF`` or ``VIDIOC_DQBUF`` it is always
492 cleared. Of course a buffer cannot be on both queues at the same
493 time, the ``V4L2_BUF_FLAG_QUEUED`` and ``V4L2_BUF_FLAG_DONE`` flag
494 are mutually exclusive. They can be both cleared however, then the
495 buffer is in "dequeued" state, in the application domain so to
496 say.
497 * .. _`V4L2-BUF-FLAG-ERROR`:
498
499 - ``V4L2_BUF_FLAG_ERROR``
500 - 0x00000040
501 - When this flag is set, the buffer has been dequeued successfully,
502 although the data might have been corrupted. This is recoverable,
503 streaming may continue as normal and the buffer may be reused
504 normally. Drivers set this flag when the ``VIDIOC_DQBUF`` ioctl is
505 called.
506 * .. _`V4L2-BUF-FLAG-IN-REQUEST`:
507
508 - ``V4L2_BUF_FLAG_IN_REQUEST``
509 - 0x00000080
510 - This buffer is part of a request that hasn't been queued yet.
511 * .. _`V4L2-BUF-FLAG-KEYFRAME`:
512
513 - ``V4L2_BUF_FLAG_KEYFRAME``
514 - 0x00000008
515 - Drivers set or clear this flag when calling the ``VIDIOC_DQBUF``
516 ioctl. It may be set by video capture devices when the buffer
517 contains a compressed image which is a key frame (or field), i. e.
518 can be decompressed on its own. Also known as an I-frame.
519 Applications can set this bit when ``type`` refers to an output
520 stream.
521 * .. _`V4L2-BUF-FLAG-PFRAME`:
522
523 - ``V4L2_BUF_FLAG_PFRAME``
524 - 0x00000010
525 - Similar to ``V4L2_BUF_FLAG_KEYFRAME`` this flags predicted frames
526 or fields which contain only differences to a previous key frame.
527 Applications can set this bit when ``type`` refers to an output
528 stream.
529 * .. _`V4L2-BUF-FLAG-BFRAME`:
530
531 - ``V4L2_BUF_FLAG_BFRAME``
532 - 0x00000020
533 - Similar to ``V4L2_BUF_FLAG_KEYFRAME`` this flags a bi-directional
534 predicted frame or field which contains only the differences
535 between the current frame and both the preceding and following key
536 frames to specify its content. Applications can set this bit when
537 ``type`` refers to an output stream.
538 * .. _`V4L2-BUF-FLAG-TIMECODE`:
539
540 - ``V4L2_BUF_FLAG_TIMECODE``
541 - 0x00000100
542 - The ``timecode`` field is valid. Drivers set or clear this flag
543 when the ``VIDIOC_DQBUF`` ioctl is called. Applications can set
544 this bit and the corresponding ``timecode`` structure when
545 ``type`` refers to an output stream.
546 * .. _`V4L2-BUF-FLAG-PREPARED`:
547
548 - ``V4L2_BUF_FLAG_PREPARED``
549 - 0x00000400
550 - The buffer has been prepared for I/O and can be queued by the
551 application. Drivers set or clear this flag when the
552 :ref:`VIDIOC_QUERYBUF <VIDIOC_QUERYBUF>`,
553 :ref:`VIDIOC_PREPARE_BUF <VIDIOC_QBUF>`,
554 :ref:`VIDIOC_QBUF <VIDIOC_QBUF>` or
555 :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl is called.
556 * .. _`V4L2-BUF-FLAG-NO-CACHE-INVALIDATE`:
557
558 - ``V4L2_BUF_FLAG_NO_CACHE_INVALIDATE``
559 - 0x00000800
560 - Caches do not have to be invalidated for this buffer. Typically
561 applications shall use this flag if the data captured in the
562 buffer is not going to be touched by the CPU, instead the buffer
563 will, probably, be passed on to a DMA-capable hardware unit for
564 further processing or output. This flag is ignored unless the
565 queue is used for :ref:`memory mapping <mmap>` streaming I/O and
566 reports :ref:`V4L2_BUF_CAP_SUPPORTS_MMAP_CACHE_HINTS
567 <V4L2-BUF-CAP-SUPPORTS-MMAP-CACHE-HINTS>` capability.
568 * .. _`V4L2-BUF-FLAG-NO-CACHE-CLEAN`:
569
570 - ``V4L2_BUF_FLAG_NO_CACHE_CLEAN``
571 - 0x00001000
572 - Caches do not have to be cleaned for this buffer. Typically
573 applications shall use this flag for output buffers if the data in
574 this buffer has not been created by the CPU but by some
575 DMA-capable unit, in which case caches have not been used. This flag
576 is ignored unless the queue is used for :ref:`memory mapping <mmap>`
577 streaming I/O and reports :ref:`V4L2_BUF_CAP_SUPPORTS_MMAP_CACHE_HINTS
578 <V4L2-BUF-CAP-SUPPORTS-MMAP-CACHE-HINTS>` capability.
579 * .. _`V4L2-BUF-FLAG-M2M-HOLD-CAPTURE-BUF`:
580
581 - ``V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF``
582 - 0x00000200
583 - Only valid if struct :c:type:`v4l2_requestbuffers` flag ``V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF`` is
584 set. It is typically used with stateless decoders where multiple
585 output buffers each decode to a slice of the decoded frame.
586 Applications can set this flag when queueing the output buffer
587 to prevent the driver from dequeueing the capture buffer after
588 the output buffer has been decoded (i.e. the capture buffer is
589 'held'). If the timestamp of this output buffer differs from that
590 of the previous output buffer, then that indicates the start of a
591 new frame and the previously held capture buffer is dequeued.
592 * .. _`V4L2-BUF-FLAG-LAST`:
593
594 - ``V4L2_BUF_FLAG_LAST``
595 - 0x00100000
596 - Last buffer produced by the hardware. mem2mem codec drivers set
597 this flag on the capture queue for the last buffer when the
598 :ref:`VIDIOC_QUERYBUF` or
599 :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl is called. Due to
600 hardware limitations, the last buffer may be empty. In this case
601 the driver will set the ``bytesused`` field to 0, regardless of
602 the format. Any subsequent call to the
603 :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl will not block anymore,
604 but return an ``EPIPE`` error code.
605 * .. _`V4L2-BUF-FLAG-REQUEST-FD`:
606
607 - ``V4L2_BUF_FLAG_REQUEST_FD``
608 - 0x00800000
609 - The ``request_fd`` field contains a valid file descriptor.
610 * .. _`V4L2-BUF-FLAG-TIMESTAMP-MASK`:
611
612 - ``V4L2_BUF_FLAG_TIMESTAMP_MASK``
613 - 0x0000e000
614 - Mask for timestamp types below. To test the timestamp type, mask
615 out bits not belonging to timestamp type by performing a logical
616 and operation with buffer flags and timestamp mask.
617 * .. _`V4L2-BUF-FLAG-TIMESTAMP-UNKNOWN`:
618
619 - ``V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN``
620 - 0x00000000
621 - Unknown timestamp type. This type is used by drivers before Linux
622 3.9 and may be either monotonic (see below) or realtime (wall
623 clock). Monotonic clock has been favoured in embedded systems
624 whereas most of the drivers use the realtime clock. Either kinds
625 of timestamps are available in user space via
626 :c:func:`clock_gettime` using clock IDs ``CLOCK_MONOTONIC``
627 and ``CLOCK_REALTIME``, respectively.
628 * .. _`V4L2-BUF-FLAG-TIMESTAMP-MONOTONIC`:
629
630 - ``V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC``
631 - 0x00002000
632 - The buffer timestamp has been taken from the ``CLOCK_MONOTONIC``
633 clock. To access the same clock outside V4L2, use
634 :c:func:`clock_gettime`.
635 * .. _`V4L2-BUF-FLAG-TIMESTAMP-COPY`:
636
637 - ``V4L2_BUF_FLAG_TIMESTAMP_COPY``
638 - 0x00004000
639 - The CAPTURE buffer timestamp has been taken from the corresponding
640 OUTPUT buffer. This flag applies only to mem2mem devices.
641 * .. _`V4L2-BUF-FLAG-TSTAMP-SRC-MASK`:
642
643 - ``V4L2_BUF_FLAG_TSTAMP_SRC_MASK``
644 - 0x00070000
645 - Mask for timestamp sources below. The timestamp source defines the
646 point of time the timestamp is taken in relation to the frame.
647 Logical 'and' operation between the ``flags`` field and
648 ``V4L2_BUF_FLAG_TSTAMP_SRC_MASK`` produces the value of the
649 timestamp source. Applications must set the timestamp source when
650 ``type`` refers to an output stream and
651 ``V4L2_BUF_FLAG_TIMESTAMP_COPY`` is set.
652 * .. _`V4L2-BUF-FLAG-TSTAMP-SRC-EOF`:
653
654 - ``V4L2_BUF_FLAG_TSTAMP_SRC_EOF``
655 - 0x00000000
656 - End Of Frame. The buffer timestamp has been taken when the last
657 pixel of the frame has been received or the last pixel of the
658 frame has been transmitted. In practice, software generated
659 timestamps will typically be read from the clock a small amount of
660 time after the last pixel has been received or transmitten,
661 depending on the system and other activity in it.
662 * .. _`V4L2-BUF-FLAG-TSTAMP-SRC-SOE`:
663
664 - ``V4L2_BUF_FLAG_TSTAMP_SRC_SOE``
665 - 0x00010000
666 - Start Of Exposure. The buffer timestamp has been taken when the
667 exposure of the frame has begun. This is only valid for the
668 ``V4L2_BUF_TYPE_VIDEO_CAPTURE`` buffer type.
669
670 .. raw:: latex
671
672 \normalsize
673
674 enum v4l2_memory
675 ================
676
677 .. tabularcolumns:: |p{5.0cm}|p{0.8cm}|p{11.5cm}|
678
679 .. flat-table::
680 :header-rows: 0
681 :stub-columns: 0
682 :widths: 3 1 4
683
684 * - ``V4L2_MEMORY_MMAP``
685 - 1
686 - The buffer is used for :ref:`memory mapping <mmap>` I/O.
687 * - ``V4L2_MEMORY_USERPTR``
688 - 2
689 - The buffer is used for :ref:`user pointer <userp>` I/O.
690 * - ``V4L2_MEMORY_OVERLAY``
691 - 3
692 - [to do]
693 * - ``V4L2_MEMORY_DMABUF``
694 - 4
695 - The buffer is used for :ref:`DMA shared buffer <dmabuf>` I/O.
696
697 .. raw:: latex
698
699 \normalsize
700
701 Timecodes
702 =========
703
704 The :c:type:`v4l2_buffer_timecode` structure is designed to hold a
705 :ref:`smpte12m` or similar timecode.
706 (struct :c:type:`timeval` timestamps are stored in the struct
707 :c:type:`v4l2_buffer` ``timestamp`` field.)
708
709 .. c:type:: v4l2_timecode
710
711 struct v4l2_timecode
712 --------------------
713
714 .. tabularcolumns:: |p{1.4cm}|p{2.8cm}|p{13.1cm}|
715
716 .. flat-table::
717 :header-rows: 0
718 :stub-columns: 0
719 :widths: 1 1 2
720
721 * - __u32
722 - ``type``
723 - Frame rate the timecodes are based on, see :ref:`timecode-type`.
724 * - __u32
725 - ``flags``
726 - Timecode flags, see :ref:`timecode-flags`.
727 * - __u8
728 - ``frames``
729 - Frame count, 0 ... 23/24/29/49/59, depending on the type of
730 timecode.
731 * - __u8
732 - ``seconds``
733 - Seconds count, 0 ... 59. This is a binary, not BCD number.
734 * - __u8
735 - ``minutes``
736 - Minutes count, 0 ... 59. This is a binary, not BCD number.
737 * - __u8
738 - ``hours``
739 - Hours count, 0 ... 29. This is a binary, not BCD number.
740 * - __u8
741 - ``userbits``\ [4]
742 - The "user group" bits from the timecode.
743
744
745 .. _timecode-type:
746
747 Timecode Types
748 --------------
749
750 .. flat-table::
751 :header-rows: 0
752 :stub-columns: 0
753 :widths: 3 1 4
754
755 * - ``V4L2_TC_TYPE_24FPS``
756 - 1
757 - 24 frames per second, i. e. film.
758 * - ``V4L2_TC_TYPE_25FPS``
759 - 2
760 - 25 frames per second, i. e. PAL or SECAM video.
761 * - ``V4L2_TC_TYPE_30FPS``
762 - 3
763 - 30 frames per second, i. e. NTSC video.
764 * - ``V4L2_TC_TYPE_50FPS``
765 - 4
766 -
767 * - ``V4L2_TC_TYPE_60FPS``
768 - 5
769 -
770
771
772 .. _timecode-flags:
773
774 Timecode Flags
775 --------------
776
777 .. tabularcolumns:: |p{6.6cm}|p{1.4cm}|p{9.3cm}|
778
779 .. flat-table::
780 :header-rows: 0
781 :stub-columns: 0
782 :widths: 3 1 4
783
784 * - ``V4L2_TC_FLAG_DROPFRAME``
785 - 0x0001
786 - Indicates "drop frame" semantics for counting frames in 29.97 fps
787 material. When set, frame numbers 0 and 1 at the start of each
788 minute, except minutes 0, 10, 20, 30, 40, 50 are omitted from the
789 count.
790 * - ``V4L2_TC_FLAG_COLORFRAME``
791 - 0x0002
792 - The "color frame" flag.
793 * - ``V4L2_TC_USERBITS_field``
794 - 0x000C
795 - Field mask for the "binary group flags".
796 * - ``V4L2_TC_USERBITS_USERDEFINED``
797 - 0x0000
798 - Unspecified format.
799 * - ``V4L2_TC_USERBITS_8BITCHARS``
800 - 0x0008
801 - 8-bit ISO characters.
802

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Streaming I/O buffer와 timestamp

1-36

Buffer는 Streaming I/O 방식 중 하나로 application과 driver가 교환하는 data를 담습니다. Multi-planar API에서는 data가 plane에 있고 buffer structure는 plane의 container 역할을 합니다. 실제 data를 copy하지 않고 buffer 또는 plane을 가리키는 pointer만 교환합니다.

Pointer와 timestamp, field parity 같은 metadata는 `VIDIOC_QUERYBUF`, `VIDIOC_QBUF`, `VIDIOC_DQBUF`의 argument인 `struct v4l2_buffer`에 저장됩니다. Multi-planar API에서는 plane별 pointer와 size 같은 member가 `struct v4l2_plane`에 있고, `struct v4l2_buffer`가 plane structure array를 가리킵니다.

Dequeued video buffer에는 timestamp가 있습니다. Driver가 frame의 어느 지점에서 어떤 clock으로 timestamp를 얻을지 정하며, `V4L2_BUF_FLAG_TIMESTAMP_MASK`와 `V4L2_BUF_FLAG_TSTAMP_SRC_MASK`가 이를 나타냅니다.

이 flag들은 전체 video stream 동안 모든 buffer에서 항상 유효하고 일정합니다. 다만 `VIDIOC_S_INPUT` 또는 `VIDIOC_S_OUTPUT`의 부작용으로 바뀔 수 있습니다. Mem-to-mem device 등이 쓰는 `V4L2_BUF_FLAG_TIMESTAMP_COPY`는 예외로, timestamp source flag를 OUTPUT video buffer에서 CAPTURE video buffer로 copy합니다.

Multi-planar buffer 교환
Application과 driver가 struct v4l2_buffer 교환Buffer가 struct v4l2_plane array를 가리킴각 plane이 data pointer와 size 보유Timestamp와 field parity 같은 metadata를 함께 전달

Data copy 없이 container와 plane pointer 및 metadata를 교환합니다.

.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: V4L

.. _buffer:

*******
Buffers
*******

A buffer contains data exchanged by application and driver using one of
the Streaming I/O methods. In the multi-planar API, the data is held in
planes, while the buffer structure acts as a container for the planes.
Only pointers to buffers (planes) are exchanged, the data itself is not
copied. These pointers, together with meta-information like timestamps
or field parity, are stored in a struct :c:type:`v4l2_buffer`,
argument to the :ref:`VIDIOC_QUERYBUF`,
:ref:`VIDIOC_QBUF <VIDIOC_QBUF>` and
:ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl. In the multi-planar API,
some plane-specific members of struct :c:type:`v4l2_buffer`,
such as pointers and sizes for each plane, are stored in
struct :c:type:`v4l2_plane` instead. In that case,
struct :c:type:`v4l2_buffer` contains an array of plane structures.

Dequeued video buffers come with timestamps. The driver decides at which
part of the frame and with which clock the timestamp is taken. Please
see flags in the masks ``V4L2_BUF_FLAG_TIMESTAMP_MASK`` and
``V4L2_BUF_FLAG_TSTAMP_SRC_MASK`` in :ref:`buffer-flags`. These flags
are always valid and constant across all buffers during the whole video
stream. Changes in these flags may take place as a side effect of
:ref:`VIDIOC_S_INPUT <VIDIOC_G_INPUT>` or
:ref:`VIDIOC_S_OUTPUT <VIDIOC_G_OUTPUT>` however. The
``V4L2_BUF_FLAG_TIMESTAMP_COPY`` timestamp type which is used by e.g. on
mem-to-mem devices is an exception to the rule: the timestamp source
flags are copied from the OUTPUT video buffer to the CAPTURE video
buffer.

Format, control과 buffer layout 상호작용

37-78

V4L2는 buffer size나 buffer 안에서 data가 배치되는 방식에 영향을 주는 parameter를 format과 control로 노출합니다. 예를 들어 `V4L2_CID_ROTATE`는 pixel 저장 방향을 바꾸며, line 끝에 padding이 있는 format에서는 buffer size도 바꿉니다.

Pixel format, line stride, tiling orientation, rotation처럼 buffer 내용을 해석하는 데 필요한 정보 집합을 이 절에서는 buffer layout이라고 부릅니다. Buffer layout을 수정할 수 있는 control은 `V4L2_CTRL_FLAG_MODIFY_LAYOUT` flag를 설정해야 합니다.

Buffer size 또는 layout에 영향을 주는 format/control을 바꾸려면 stream이 멈춰 있어야 합니다. Stream이 active일 때 변경하면 설정 ioctl은 `EBUSY`를 반환해야 하며, driver는 `VIDIOC_QUERYCTRL` 또는 `VIDIOC_QUERY_EXT_CTRL` 응답에서 해당 control에 `V4L2_CTRL_FLAG_GRABBED`를 설정해야 합니다.

Hardware에 scaler가 없는 경우처럼 `VIDIOC_S_SELECTION`은 selection rectangle뿐 아니라 format도 바꿀 수 있습니다. `VIDIOC_S_INPUT`, `VIDIOC_S_OUTPUT`, `VIDIOC_S_STD`, `VIDIOC_S_DV_TIMINGS`도 format과 selection rectangle을 바꿀 수 있습니다. 이 ioctl로 buffer size/layout이 변경되면 driver는 이 절의 모든 경우에서 `VIDIOC_S_FMT` 변경과 같은 방식으로 처리해야 합니다.

Buffer layout에만 영향을 주고 size에는 영향을 주지 않는 control은 stream이 멈춘 동안 언제든 변경할 수 있습니다. Buffer allocation과 동기화할 특별 처리가 필요 없으며 stream이 멈추면 `V4L2_CTRL_FLAG_GRABBED`가 clear됩니다.

Layout 변경 관련 flag
Flag의미
V4L2_CTRL_FLAG_MODIFY_LAYOUTControl이 buffer layout을 변경할 수 있음
V4L2_CTRL_FLAG_GRABBEDActive stream에서 control 변경이 금지됨

Control이 layout을 바꾸거나 active stream에서 잡혀 있음을 나타냅니다.

Interactions between formats, controls and buffers
==================================================

V4L2 exposes parameters that influence the buffer size, or the way data is
laid out in the buffer. Those parameters are exposed through both formats and
controls. One example of such a control is the ``V4L2_CID_ROTATE`` control
that modifies the direction in which pixels are stored in the buffer, as well
as the buffer size when the selected format includes padding at the end of
lines.

The set of information needed to interpret the content of a buffer (e.g. the
pixel format, the line stride, the tiling orientation or the rotation) is
collectively referred to in the rest of this section as the buffer layout.

Controls that can modify the buffer layout shall set the
``V4L2_CTRL_FLAG_MODIFY_LAYOUT`` flag.

Modifying formats or controls that influence the buffer size or layout require
the stream to be stopped. Any attempt at such a modification while the stream
is active shall cause the ioctl setting the format or the control to return
the ``EBUSY`` error code. In that case drivers shall also set the
``V4L2_CTRL_FLAG_GRABBED`` flag when calling
:c:func:`VIDIOC_QUERYCTRL` or :c:func:`VIDIOC_QUERY_EXT_CTRL` for such a
control while the stream is active.

.. note::

   The :c:func:`VIDIOC_S_SELECTION` ioctl can, depending on the hardware (for
   instance if the device doesn't include a scaler), modify the format in
   addition to the selection rectangle. Similarly, the
   :c:func:`VIDIOC_S_INPUT`, :c:func:`VIDIOC_S_OUTPUT`, :c:func:`VIDIOC_S_STD`
   and :c:func:`VIDIOC_S_DV_TIMINGS` ioctls can also modify the format and
   selection rectangles. When those ioctls result in a buffer size or layout
   change, drivers shall handle that condition as they would handle it in the
   :c:func:`VIDIOC_S_FMT` ioctl in all cases described in this section.

Controls that only influence the buffer layout can be modified at any time
when the stream is stopped. As they don't influence the buffer size, no
special handling is needed to synchronize those controls with buffer
allocation and the ``V4L2_CTRL_FLAG_GRABBED`` flag is cleared once the
stream is stopped.

Buffer 재할당이 필요한 변경

79-115

Buffer size에 영향을 주는 format/control은 buffer allocation과 상호작용합니다. 가장 단순한 driver 정책은 이런 값을 바꾸려면 항상 buffer를 재할당하도록 요구하는 것입니다.

Application은 실행 중인 stream을 `VIDIOC_STREAMOFF`로 멈추고, 할당된 buffer를 `VIDIOC_REQBUFS(0)`로 모두 해제합니다. 모든 buffer가 해제되면 control의 `V4L2_CTRL_FLAG_GRABBED`가 clear되고 format/control을 바꾼 뒤 buffer를 다시 할당해 stream을 재시작합니다.

재할당을 요구하는 일반 ioctl sequence
VIDIOC_STREAMOFFVIDIOC_REQBUFS(0)VIDIOC_S_EXT_CTRLSVIDIOC_S_FMTVIDIOC_REQBUFS(n)VIDIOC_QBUFVIDIOC_STREAMON

새 format과 control을 반영해 buffer size를 다시 계산합니다.

두 번째 `VIDIOC_REQBUFS`는 새 format과 control 값을 반영해 할당할 buffer size를 계산합니다. 필요하면 `VIDIOC_G_FMT`로 size를 조회할 수도 있습니다.

API는 control 변경과 format 변경의 순서를 강제하지 않습니다. Device와 use case에 따라 순서를 바꾸거나 interleave할 수 있습니다. 특정 control이 pixel format에 따라 다르게 동작한다면 format을 먼저 설정해야 할 수도 있습니다.

재할당이 필수인 경우 buffer가 할당된 동안 size에 영향을 주는 format/control을 바꾸면 설정 ioctl은 `EBUSY`를 반환합니다. 현재 format/control에 비해 너무 작은 buffer를 queue하려 하면 `VIDIOC_QBUF`는 `EINVAL`을 반환합니다.

Formats and controls that influence the buffer size interact with buffer
allocation. The simplest way to handle this is for drivers to always require
buffers to be reallocated in order to change those formats or controls. In
that case, to perform such changes, userspace applications shall first stop
the video stream with the :c:func:`VIDIOC_STREAMOFF` ioctl if it is running
and free all buffers with the :c:func:`VIDIOC_REQBUFS` ioctl if they are
allocated. After freeing all buffers the ``V4L2_CTRL_FLAG_GRABBED`` flag
for controls is cleared. The format or controls can then be modified, and
buffers shall then be reallocated and the stream restarted. A typical ioctl
sequence is

 #. VIDIOC_STREAMOFF
 #. VIDIOC_REQBUFS(0)
 #. VIDIOC_S_EXT_CTRLS
 #. VIDIOC_S_FMT
 #. VIDIOC_REQBUFS(n)
 #. VIDIOC_QBUF
 #. VIDIOC_STREAMON

The second :c:func:`VIDIOC_REQBUFS` call will take the new format and control
value into account to compute the buffer size to allocate. Applications can
also retrieve the size by calling the :c:func:`VIDIOC_G_FMT` ioctl if needed.

.. note::

   The API doesn't mandate the above order for control (3.) and format (4.)
   changes. Format and controls can be set in a different order, or even
   interleaved, depending on the device and use case. For instance some
   controls might behave differently for different pixel formats, in which
   case the format might need to be set first.

When reallocation is required, any attempt to modify format or controls that
influences the buffer size while buffers are allocated shall cause the format
or control set ioctl to return the ``EBUSY`` error. Any attempt to queue a
buffer too small for the current format or controls shall cause the
:c:func:`VIDIOC_QBUF` ioctl to return a ``EINVAL`` error.

할당된 buffer를 유지하는 size 변경

116-154

Buffer 재할당은 비용이 큽니다. 이를 피하기 위해 driver는 buffer가 할당된 상태에서도 size에 영향을 주는 format/control 변경을 허용할 수 있으며 권장됩니다.

재할당 없이 변경하는 ioctl sequence
VIDIOC_STREAMOFFVIDIOC_S_EXT_CTRLSVIDIOC_S_FMTVIDIOC_QBUFVIDIOC_STREAMON

기존 buffer가 새 요구 size보다 충분히 큰 경우의 흐름입니다.

이 sequence가 동작하려면 queued buffer가 새 format/control에 충분히 커야 합니다. 너무 작은 buffer가 queue되어 있으면 `VIDIOC_S_FMT`, `VIDIOC_S_CTRL`, `VIDIOC_S_EXT_CTRLS`는 `ENOSPC`를 반환해야 합니다. 단순화를 위해 driver는 size를 검사하지 않고 queue된 buffer가 하나라도 있으면 `EBUSY`를 반환할 수 있습니다.

Queue하려는 buffer가 현재 format/control에 너무 작으면 `VIDIOC_QBUF`는 `EINVAL`을 반환해야 합니다. 이 요구사항은 queue된 buffer가 설정된 format/control에 항상 충분히 크도록 보장합니다.

Application은 원하는 control 값을 설정한 뒤 원하는 format을 `VIDIOC_TRY_FMT`로 시험하여 필요한 buffer size를 조회할 수 있습니다.

여러 control 값의 size 질의
VIDIOC_S_EXT_CTRLS(x)VIDIOC_TRY_FMT()VIDIOC_S_EXT_CTRLS(y)VIDIOC_TRY_FMT()

각 use case의 필요 size를 format 변경 없이 계산합니다.

그 뒤 `VIDIOC_CREATE_BUFS`로 조회한 size에 맞춰 buffer를 할당할 수 있습니다. 모든 format/control에 충분히 큰 하나의 buffer set을 만들거나 use case별로 적정 size의 별도 set을 만들 수 있습니다.

Buffer reallocation is an expensive operation. To avoid that cost, drivers can
(and are encouraged to) allow format or controls that influence the buffer
size to be changed with buffers allocated. In that case, a typical ioctl
sequence to modify format and controls is

 #. VIDIOC_STREAMOFF
 #. VIDIOC_S_EXT_CTRLS
 #. VIDIOC_S_FMT
 #. VIDIOC_QBUF
 #. VIDIOC_STREAMON

For this sequence to operate correctly, queued buffers need to be large enough
for the new format or controls. Drivers shall return a ``ENOSPC`` error in
response to format change (:c:func:`VIDIOC_S_FMT`) or control changes
(:c:func:`VIDIOC_S_CTRL` or :c:func:`VIDIOC_S_EXT_CTRLS`) if buffers too small
for the new format are currently queued. As a simplification, drivers are
allowed to return a ``EBUSY`` error from these ioctls if any buffer is
currently queued, without checking the queued buffers sizes.

Additionally, drivers shall return a ``EINVAL`` error from the
:c:func:`VIDIOC_QBUF` ioctl if the buffer being queued is too small for the
current format or controls. Together, these requirements ensure that queued
buffers will always be large enough for the configured format and controls.

Userspace applications can query the buffer size required for a given format
and controls by first setting the desired control values and then trying the
desired format. The :c:func:`VIDIOC_TRY_FMT` ioctl will return the required
buffer size.

 #. VIDIOC_S_EXT_CTRLS(x)
 #. VIDIOC_TRY_FMT()
 #. VIDIOC_S_EXT_CTRLS(y)
 #. VIDIOC_TRY_FMT()

The :c:func:`VIDIOC_CREATE_BUFS` ioctl can then be used to allocate buffers
based on the queried sizes (for instance by allocating a set of buffers large
enough for all the desired formats and controls, or by allocating separate set
of appropriately sized buffers for each use case).

struct v4l2_buffer

155-309

`struct v4l2_buffer`는 buffer identity, stream type, payload, field order, timestamp/timecode, sequence, memory handle과 request association을 전달합니다.

struct v4l2_buffer field
TypeField설명
__u32indexApplication이 설정하되 `VIDIOC_DQBUF`에서는 driver가 설정하는 buffer 번호. 0부터 `VIDIOC_REQBUFS` count와 `VIDIOC_CREATE_BUFS` 추가분을 합친 마지막 index까지
__u32typeApplication이 설정하는 buffer type. `struct v4l2_format.type` 및 `struct v4l2_requestbuffers.type`과 같고 `enum v4l2_buf_type` 사용
__u32bytesusedPayload byte 수. Capture에서는 driver, output에서는 application이 설정. JPEG 같은 가변 압축 data는 buffer마다 달라질 수 있음. Multi-planar에서는 무시하고 planes 사용
__u32flagsApplication 또는 driver가 설정하는 buffer flag
__u32fieldImage field order. VBI data에는 사용하지 않음. Capture에서는 driver, output에서는 application이 설정
struct timevaltimestampCapture는 첫 data byte가 capture된 시각, output은 마지막 data byte가 실제 전송된 시각. COPY mode에서는 application timestamp가 capture stream으로 copy됨
struct v4l2_timecodetimecodeV4L2_BUF_FLAG_TIMECODE가 설정되면 frame timecode. ALTERNATE mode의 top/bottom field는 같은 timecode. timestamp 및 sequence와 독립
__u32sequenceDriver가 frame을 0부터 세며 input/output 모두에 설정. Field가 아니라 frame을 세고 dropped/repeated frame도 포함
__u32memory선택한 I/O 방식에 맞춰 application/driver가 설정하는 enum v4l2_memory 값
union m / __u32offsetSingle-planar + V4L2_MEMORY_MMAP에서 device memory 시작 기준 offset. Driver가 반환하며 mmap parameter 외 용도는 없음
union m / unsigned longuserptrSingle-planar + V4L2_MEMORY_USERPTR에서 application이 설정하는 virtual-memory buffer pointer
union m / struct v4l2_plane *planesMulti-planar API의 userspace plane array pointer. Array size는 v4l2_buffer.length에 입력
union m / intfdSingle-planar + V4L2_MEMORY_DMABUF에서 DMABUF buffer file descriptor
__u32lengthSingle-planar에서는 payload가 아닌 buffer byte size를 driver가 설정. Multi-planar에서는 application이 planes array element 수를 넣고 driver가 유효 element 수를 채움
__u32reserved2향후 확장용 placeholder. Driver와 application 모두 0으로 설정
__u32request_fdV4L2_BUF_FLAG_REQUEST_FD가 설정된 경우 buffer를 queue할 request의 file descriptor

Single-planar와 multi-planar API에서 field의 소유자와 의미가 달라지는 지점을 포함합니다.

`sequence`는 `V4L2_FIELD_ALTERNATE`에서 top/bottom field에 같은 값을 사용합니다. Free buffer 부족으로 저장하지 못한 input frame과 새 data가 늦어 output에서 다시 표시한 frame도 count합니다.

USB 등 remote hardware가 compression throughput 또는 bus bandwidth 때문에 먼저 버린 frame은 count하지 않을 수 있습니다. 이런 device는 video standard를 열거하지 않는 특성으로 식별됩니다.

`V4L2_BUF_FLAG_REQUEST_FD`와 `request_fd`는 `VIDIOC_QBUF`에서만 사용되고 다른 `v4l2_buffer` ioctl에서는 무시됩니다. 다른 ioctl에 이 flag를 설정하면 안 됩니다. Request를 지원하지 않으면 `EBADR`, invalid request fd이면 `EINVAL`을 반환합니다.

.. c:type:: v4l2_buffer

struct v4l2_buffer
==================

.. tabularcolumns:: |p{2.9cm}|p{2.4cm}|p{12.0cm}|

.. cssclass:: longtable

.. flat-table:: struct v4l2_buffer
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 2 10

    * - __u32
      - ``index``
      - Number of the buffer, set by the application except when calling
	:ref:`VIDIOC_DQBUF <VIDIOC_QBUF>`, then it is set by the
	driver. This field can range from zero to the number of buffers
	allocated with the :ref:`VIDIOC_REQBUFS` ioctl
	(struct :c:type:`v4l2_requestbuffers`
	``count``), plus any buffers allocated with
	:ref:`VIDIOC_CREATE_BUFS` minus one.
    * - __u32
      - ``type``
      - Type of the buffer, same as struct
	:c:type:`v4l2_format` ``type`` or struct
	:c:type:`v4l2_requestbuffers` ``type``, set
	by the application. See :c:type:`v4l2_buf_type`
    * - __u32
      - ``bytesused``
      - The number of bytes occupied by the data in the buffer. It depends
	on the negotiated data format and may change with each buffer for
	compressed variable size data like JPEG images. Drivers must set
	this field when ``type`` refers to a capture stream, applications
	when it refers to an output stream. For multiplanar formats this field
        is ignored and the
	``planes`` pointer is used instead.
    * - __u32
      - ``flags``
      - Flags set by the application or driver, see :ref:`buffer-flags`.
    * - __u32
      - ``field``
      - Indicates the field order of the image in the buffer, see
	:c:type:`v4l2_field`. This field is not used when the buffer
	contains VBI data. Drivers must set it when ``type`` refers to a
	capture stream, applications when it refers to an output stream.
    * - struct timeval
      - ``timestamp``
      - For capture streams this is time when the first data byte was
	captured, as returned by the :c:func:`clock_gettime()` function
	for the relevant clock id; see ``V4L2_BUF_FLAG_TIMESTAMP_*`` in
	:ref:`buffer-flags`. For output streams the driver stores the
	time at which the last data byte was actually sent out in the
	``timestamp`` field. This permits applications to monitor the
	drift between the video and system clock. For output streams that
	use ``V4L2_BUF_FLAG_TIMESTAMP_COPY`` the application has to fill
	in the timestamp which will be copied by the driver to the capture
	stream.
    * - struct :c:type:`v4l2_timecode`
      - ``timecode``
      - When the ``V4L2_BUF_FLAG_TIMECODE`` flag is set in ``flags``, this
	structure contains a frame timecode. In
	:c:type:`V4L2_FIELD_ALTERNATE <v4l2_field>` mode the top and
	bottom field contain the same timecode. Timecodes are intended to
	help video editing and are typically recorded on video tapes, but
	also embedded in compressed formats like MPEG. This field is
	independent of the ``timestamp`` and ``sequence`` fields.
    * - __u32
      - ``sequence``
      - Set by the driver, counting the frames (not fields!) in sequence.
	This field is set for both input and output devices.
    * - :cspan:`2`

	In :c:type:`V4L2_FIELD_ALTERNATE <v4l2_field>` mode the top and
	bottom field have the same sequence number. The count starts at
	zero and includes dropped or repeated frames. A dropped frame was
	received by an input device but could not be stored due to lack of
	free buffer space. A repeated frame was displayed again by an
	output device because the application did not pass new data in
	time.

	.. note::

	   This may count the frames received e.g. over USB, without
	   taking into account the frames dropped by the remote hardware due
	   to limited compression throughput or bus bandwidth. These devices
	   identify by not enumerating any video standards, see
	   :ref:`standard`.

    * - __u32
      - ``memory``
      - This field must be set by applications and/or drivers in
	accordance with the selected I/O method. See :c:type:`v4l2_memory`
    * - union {
      - ``m``
    * - __u32
      - ``offset``
      - For the single-planar API and when ``memory`` is
	``V4L2_MEMORY_MMAP`` this is the offset of the buffer from the
	start of the device memory. The value is returned by the driver
	and apart of serving as parameter to the
	:c:func:`mmap()` function not useful for applications.
	See :ref:`mmap` for details
    * - unsigned long
      - ``userptr``
      - For the single-planar API and when ``memory`` is
	``V4L2_MEMORY_USERPTR`` this is a pointer to the buffer (casted to
	unsigned long type) in virtual memory, set by the application. See
	:ref:`userp` for details.
    * - struct v4l2_plane
      - ``*planes``
      - When using the multi-planar API, contains a userspace pointer to
	an array of struct :c:type:`v4l2_plane`. The size of
	the array should be put in the ``length`` field of this
	struct :c:type:`v4l2_buffer` structure.
    * - int
      - ``fd``
      - For the single-plane API and when ``memory`` is
	``V4L2_MEMORY_DMABUF`` this is the file descriptor associated with
	a DMABUF buffer.
    * - }
      -
    * - __u32
      - ``length``
      - Size of the buffer (not the payload) in bytes for the
	single-planar API. This is set by the driver based on the calls to
	:ref:`VIDIOC_REQBUFS` and/or
	:ref:`VIDIOC_CREATE_BUFS`. For the
	multi-planar API the application sets this to the number of
	elements in the ``planes`` array. The driver will fill in the
	actual number of valid elements in that array.
    * - __u32
      - ``reserved2``
      - A place holder for future extensions. Drivers and applications
	must set this to 0.
    * - __u32
      - ``request_fd``
      - The file descriptor of the request to queue the buffer to. If the flag
        ``V4L2_BUF_FLAG_REQUEST_FD`` is set, then the buffer will be
	queued to this request. If the flag is not set, then this field will
	be ignored.

	The ``V4L2_BUF_FLAG_REQUEST_FD`` flag and this field are only used by
	:ref:`ioctl VIDIOC_QBUF <VIDIOC_QBUF>` and ignored by other ioctls that
	take a :c:type:`v4l2_buffer` as argument.

	Applications should not set ``V4L2_BUF_FLAG_REQUEST_FD`` for any ioctls
	other than :ref:`VIDIOC_QBUF <VIDIOC_QBUF>`.

	If the device does not support requests, then ``EBADR`` will be returned.
	If requests are supported but an invalid request file descriptor is
	given, then ``EINVAL`` will be returned.

struct v4l2_plane

310-379

Multi-planar API의 각 plane은 payload와 allocation size, memory handle, 실제 video data offset을 별도로 가집니다.

struct v4l2_plane field
TypeField설명
__u32bytesusedPlane payload byte 수. Capture에서는 driver, output에서는 application이 설정. 실제 image data는 0이 아닐 수 있는 data_offset에서 시작
__u32lengthPayload가 아닌 plane 전체 byte size. VIDIOC_REQBUFS/VIDIOC_CREATE_BUFS에 따라 driver가 설정
union m / __u32mem_offsetV4L2_MEMORY_MMAP에서 mmap()에 전달할 값. v4l2_buffer.offset과 유사
union m / unsigned longuserptrV4L2_MEMORY_USERPTR에서 application이 plane용으로 할당한 memory의 userspace pointer
union m / intfdV4L2_MEMORY_DMABUF에서 DMABUF buffer file descriptor
__u32data_offsetPlane 시작 기준 video data byte offset. Capture에서는 driver, output에서는 application이 설정
__u32reserved[11]향후 사용을 위해 예약. Driver와 application이 0으로 초기화

Containing v4l2_buffer의 memory type에 따라 union m member가 달라집니다.

`data_offset`은 `bytesused`에 포함됩니다. 따라서 plane의 image size는 `bytesused - data_offset`이고, image는 plane 시작에서 `data_offset` byte 떨어진 곳에 있습니다.

.. c:type:: v4l2_plane

struct v4l2_plane
=================

.. tabularcolumns:: |p{3.5cm}|p{3.5cm}|p{10.3cm}|

.. cssclass:: longtable

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``bytesused``
      - The number of bytes occupied by data in the plane (its payload).
	Drivers must set this field when ``type`` refers to a capture
	stream, applications when it refers to an output stream.

	.. note::

	   Note that the actual image data starts at ``data_offset``
	   which may not be 0.
    * - __u32
      - ``length``
      - Size in bytes of the plane (not its payload). This is set by the
	driver based on the calls to
	:ref:`VIDIOC_REQBUFS` and/or
	:ref:`VIDIOC_CREATE_BUFS`.
    * - union {
      - ``m``
    * - __u32
      - ``mem_offset``
      - When the memory type in the containing struct
	:c:type:`v4l2_buffer` is ``V4L2_MEMORY_MMAP``, this
	is the value that should be passed to :c:func:`mmap()`,
	similar to the ``offset`` field in struct
	:c:type:`v4l2_buffer`.
    * - unsigned long
      - ``userptr``
      - When the memory type in the containing struct
	:c:type:`v4l2_buffer` is ``V4L2_MEMORY_USERPTR``,
	this is a userspace pointer to the memory allocated for this plane
	by an application.
    * - int
      - ``fd``
      - When the memory type in the containing struct
	:c:type:`v4l2_buffer` is ``V4L2_MEMORY_DMABUF``,
	this is a file descriptor associated with a DMABUF buffer, similar
	to the ``fd`` field in struct :c:type:`v4l2_buffer`.
    * - }
      -
    * - __u32
      - ``data_offset``
      - Offset in bytes to video data in the plane. Drivers must set this
	field when ``type`` refers to a capture stream, applications when
	it refers to an output stream.

	.. note::

	   That data_offset is included  in ``bytesused``. So the
	   size of the image in the plane is ``bytesused``-``data_offset``
	   at offset ``data_offset`` from the start of the plane.
    * - __u32
      - ``reserved[11]``
      - Reserved for future use. Should be zeroed by drivers and
	applications.

enum v4l2_buf_type

380-442
V4L2 buffer type
Symbol설명
V4L2_BUF_TYPE_VIDEO_CAPTURE1Single-planar video capture stream buffer
V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE9Multi-planar video capture stream buffer
V4L2_BUF_TYPE_VIDEO_OUTPUT2Single-planar video output stream buffer
V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE10Multi-planar video output stream buffer
V4L2_BUF_TYPE_VIDEO_OVERLAY3Video overlay buffer
V4L2_BUF_TYPE_VBI_CAPTURE4Raw VBI capture stream buffer
V4L2_BUF_TYPE_VBI_OUTPUT5Raw VBI output stream buffer
V4L2_BUF_TYPE_SLICED_VBI_CAPTURE6Sliced VBI capture stream buffer
V4L2_BUF_TYPE_SLICED_VBI_OUTPUT7Sliced VBI output stream buffer
V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY8Video output overlay(OSD) buffer
V4L2_BUF_TYPE_SDR_CAPTURE11Software Defined Radio capture stream buffer
V4L2_BUF_TYPE_SDR_OUTPUT12Software Defined Radio output stream buffer
V4L2_BUF_TYPE_META_CAPTURE13Metadata capture buffer
V4L2_BUF_TYPE_META_OUTPUT14Metadata output buffer

Single/multi-planar video, VBI, SDR와 metadata stream을 구분합니다.

.. c:type:: v4l2_buf_type

enum v4l2_buf_type
==================

.. cssclass:: longtable

.. tabularcolumns:: |p{7.8cm}|p{0.6cm}|p{8.9cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       4 1 9

    * - ``V4L2_BUF_TYPE_VIDEO_CAPTURE``
      - 1
      - Buffer of a single-planar video capture stream, see
	:ref:`capture`.
    * - ``V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE``
      - 9
      - Buffer of a multi-planar video capture stream, see
	:ref:`capture`.
    * - ``V4L2_BUF_TYPE_VIDEO_OUTPUT``
      - 2
      - Buffer of a single-planar video output stream, see
	:ref:`output`.
    * - ``V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE``
      - 10
      - Buffer of a multi-planar video output stream, see :ref:`output`.
    * - ``V4L2_BUF_TYPE_VIDEO_OVERLAY``
      - 3
      - Buffer for video overlay, see :ref:`overlay`.
    * - ``V4L2_BUF_TYPE_VBI_CAPTURE``
      - 4
      - Buffer of a raw VBI capture stream, see :ref:`raw-vbi`.
    * - ``V4L2_BUF_TYPE_VBI_OUTPUT``
      - 5
      - Buffer of a raw VBI output stream, see :ref:`raw-vbi`.
    * - ``V4L2_BUF_TYPE_SLICED_VBI_CAPTURE``
      - 6
      - Buffer of a sliced VBI capture stream, see :ref:`sliced`.
    * - ``V4L2_BUF_TYPE_SLICED_VBI_OUTPUT``
      - 7
      - Buffer of a sliced VBI output stream, see :ref:`sliced`.
    * - ``V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY``
      - 8
      - Buffer for video output overlay (OSD), see :ref:`osd`.
    * - ``V4L2_BUF_TYPE_SDR_CAPTURE``
      - 11
      - Buffer for Software Defined Radio (SDR) capture stream, see
	:ref:`sdr`.
    * - ``V4L2_BUF_TYPE_SDR_OUTPUT``
      - 12
      - Buffer for Software Defined Radio (SDR) output stream, see
	:ref:`sdr`.
    * - ``V4L2_BUF_TYPE_META_CAPTURE``
      - 13
      - Buffer for metadata capture, see :ref:`metadata`.
    * - ``V4L2_BUF_TYPE_META_OUTPUT``
      - 14
      - Buffer for metadata output, see :ref:`metadata`.

Buffer state, frame과 cache flag

443-578

첫 번째 flag 군은 mapping/queue state, recoverable error, frame dependency, timecode, preparation과 mmap cache hint를 나타냅니다.

Buffer state와 frame flag
Symbol설명
V4L2_BUF_FLAG_MAPPED0x00000001Device memory buffer가 application address space에 mapping됨. QUERYBUF/QBUF/DQBUF에서 driver가 설정 또는 clear
V4L2_BUF_FLAG_QUEUED0x00000002Buffer가 incoming queue에 있음. QBUF 성공 후 항상 set, DQBUF 후 항상 clear
V4L2_BUF_FLAG_DONE0x00000004Buffer가 outgoing queue에서 dequeue 준비됨. QUEUED와 상호 배타적이며 둘 다 clear이면 application domain의 dequeued state
V4L2_BUF_FLAG_ERROR0x00000040Dequeue는 성공했지만 data가 손상됐을 수 있음. Recoverable하며 streaming과 buffer 재사용 가능
V4L2_BUF_FLAG_IN_REQUEST0x00000080아직 queue되지 않은 request에 buffer가 포함됨
V4L2_BUF_FLAG_KEYFRAME0x00000008독립 decompress 가능한 key frame/I-frame. Capture는 driver, output은 application이 설정 가능
V4L2_BUF_FLAG_PFRAME0x00000010이전 key frame과의 차이만 담는 predicted frame/field
V4L2_BUF_FLAG_BFRAME0x00000020앞뒤 key frame과의 차이로 표현하는 bidirectional predicted frame/field
V4L2_BUF_FLAG_TIMECODE0x00000100timecode field가 유효함. DQBUF에서 driver가 설정/clear하며 output에서는 application도 timecode와 함께 설정 가능
V4L2_BUF_FLAG_PREPARED0x00000400Buffer가 I/O 준비되어 application이 queue 가능. QUERYBUF/PREPARE_BUF/QBUF/DQBUF에서 driver가 관리
V4L2_BUF_FLAG_NO_CACHE_INVALIDATE0x00000800Capture data를 CPU가 만지지 않고 DMA hardware로 넘길 때 cache invalidate 생략 hint. MMAP cache-hint capability가 있어야 유효
V4L2_BUF_FLAG_NO_CACHE_CLEAN0x00001000Output data를 CPU가 아닌 DMA unit이 만들었을 때 cache clean 생략 hint. MMAP cache-hint capability가 있어야 유효

Flag value와 설정 주체 및 전이 의미를 보존합니다.

.. _buffer-flags:

Buffer Flags
============

.. raw:: latex

    \footnotesize

.. tabularcolumns:: |p{6.5cm}|p{1.8cm}|p{9.0cm}|

.. cssclass:: longtable

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       65 18 70

    * .. _`V4L2-BUF-FLAG-MAPPED`:

      - ``V4L2_BUF_FLAG_MAPPED``
      - 0x00000001
      - The buffer resides in device memory and has been mapped into the
	application's address space, see :ref:`mmap` for details.
	Drivers set or clear this flag when the
	:ref:`VIDIOC_QUERYBUF`,
	:ref:`VIDIOC_QBUF` or
	:ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl is called. Set by the
	driver.
    * .. _`V4L2-BUF-FLAG-QUEUED`:

      - ``V4L2_BUF_FLAG_QUEUED``
      - 0x00000002
      - Internally drivers maintain two buffer queues, an incoming and
	outgoing queue. When this flag is set, the buffer is currently on
	the incoming queue. It automatically moves to the outgoing queue
	after the buffer has been filled (capture devices) or displayed
	(output devices). Drivers set or clear this flag when the
	``VIDIOC_QUERYBUF`` ioctl is called. After (successful) calling
	the ``VIDIOC_QBUF``\ ioctl it is always set and after
	``VIDIOC_DQBUF`` always cleared.
    * .. _`V4L2-BUF-FLAG-DONE`:

      - ``V4L2_BUF_FLAG_DONE``
      - 0x00000004
      - When this flag is set, the buffer is currently on the outgoing
	queue, ready to be dequeued from the driver. Drivers set or clear
	this flag when the ``VIDIOC_QUERYBUF`` ioctl is called. After
	calling the ``VIDIOC_QBUF`` or ``VIDIOC_DQBUF`` it is always
	cleared. Of course a buffer cannot be on both queues at the same
	time, the ``V4L2_BUF_FLAG_QUEUED`` and ``V4L2_BUF_FLAG_DONE`` flag
	are mutually exclusive. They can be both cleared however, then the
	buffer is in "dequeued" state, in the application domain so to
	say.
    * .. _`V4L2-BUF-FLAG-ERROR`:

      - ``V4L2_BUF_FLAG_ERROR``
      - 0x00000040
      - When this flag is set, the buffer has been dequeued successfully,
	although the data might have been corrupted. This is recoverable,
	streaming may continue as normal and the buffer may be reused
	normally. Drivers set this flag when the ``VIDIOC_DQBUF`` ioctl is
	called.
    * .. _`V4L2-BUF-FLAG-IN-REQUEST`:

      - ``V4L2_BUF_FLAG_IN_REQUEST``
      - 0x00000080
      - This buffer is part of a request that hasn't been queued yet.
    * .. _`V4L2-BUF-FLAG-KEYFRAME`:

      - ``V4L2_BUF_FLAG_KEYFRAME``
      - 0x00000008
      - Drivers set or clear this flag when calling the ``VIDIOC_DQBUF``
	ioctl. It may be set by video capture devices when the buffer
	contains a compressed image which is a key frame (or field), i. e.
	can be decompressed on its own. Also known as an I-frame.
	Applications can set this bit when ``type`` refers to an output
	stream.
    * .. _`V4L2-BUF-FLAG-PFRAME`:

      - ``V4L2_BUF_FLAG_PFRAME``
      - 0x00000010
      - Similar to ``V4L2_BUF_FLAG_KEYFRAME`` this flags predicted frames
	or fields which contain only differences to a previous key frame.
	Applications can set this bit when ``type`` refers to an output
	stream.
    * .. _`V4L2-BUF-FLAG-BFRAME`:

      - ``V4L2_BUF_FLAG_BFRAME``
      - 0x00000020
      - Similar to ``V4L2_BUF_FLAG_KEYFRAME`` this flags a bi-directional
	predicted frame or field which contains only the differences
	between the current frame and both the preceding and following key
	frames to specify its content. Applications can set this bit when
	``type`` refers to an output stream.
    * .. _`V4L2-BUF-FLAG-TIMECODE`:

      - ``V4L2_BUF_FLAG_TIMECODE``
      - 0x00000100
      - The ``timecode`` field is valid. Drivers set or clear this flag
	when the ``VIDIOC_DQBUF`` ioctl is called. Applications can set
	this bit and the corresponding ``timecode`` structure when
	``type`` refers to an output stream.
    * .. _`V4L2-BUF-FLAG-PREPARED`:

      - ``V4L2_BUF_FLAG_PREPARED``
      - 0x00000400
      - The buffer has been prepared for I/O and can be queued by the
	application. Drivers set or clear this flag when the
	:ref:`VIDIOC_QUERYBUF <VIDIOC_QUERYBUF>`,
	:ref:`VIDIOC_PREPARE_BUF <VIDIOC_QBUF>`,
	:ref:`VIDIOC_QBUF <VIDIOC_QBUF>` or
	:ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl is called.
    * .. _`V4L2-BUF-FLAG-NO-CACHE-INVALIDATE`:

      - ``V4L2_BUF_FLAG_NO_CACHE_INVALIDATE``
      - 0x00000800
      - Caches do not have to be invalidated for this buffer. Typically
	applications shall use this flag if the data captured in the
	buffer is not going to be touched by the CPU, instead the buffer
	will, probably, be passed on to a DMA-capable hardware unit for
	further processing or output. This flag is ignored unless the
	queue is used for :ref:`memory mapping <mmap>` streaming I/O and
	reports :ref:`V4L2_BUF_CAP_SUPPORTS_MMAP_CACHE_HINTS
	<V4L2-BUF-CAP-SUPPORTS-MMAP-CACHE-HINTS>` capability.
    * .. _`V4L2-BUF-FLAG-NO-CACHE-CLEAN`:

      - ``V4L2_BUF_FLAG_NO_CACHE_CLEAN``
      - 0x00001000
      - Caches do not have to be cleaned for this buffer. Typically
	applications shall use this flag for output buffers if the data in
	this buffer has not been created by the CPU but by some
	DMA-capable unit, in which case caches have not been used. This flag
	is ignored unless the queue is used for :ref:`memory mapping <mmap>`
	streaming I/O and reports :ref:`V4L2_BUF_CAP_SUPPORTS_MMAP_CACHE_HINTS
	<V4L2-BUF-CAP-SUPPORTS-MMAP-CACHE-HINTS>` capability.

Mem2mem, request와 timestamp flag

579-673

두 번째 flag 군은 stateless decoder의 capture buffer hold, stream의 마지막 buffer, request fd, timestamp type과 frame 기준 timestamp source를 나타냅니다.

Request, 종료 및 timestamp flag
Symbol설명
V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF0x00000200Capability가 있을 때 stateless decoder의 여러 output slice가 같은 capture frame을 유지. Output timestamp가 바뀌면 새 frame 시작으로 보고 이전 capture buffer dequeue
V4L2_BUF_FLAG_LAST0x00100000Hardware가 만든 마지막 buffer. 빈 buffer일 수 있어 bytesused=0이며 이후 DQBUF는 block하지 않고 EPIPE 반환
V4L2_BUF_FLAG_REQUEST_FD0x00800000request_fd field에 유효 file descriptor가 있음
V4L2_BUF_FLAG_TIMESTAMP_MASK0x0000e000아래 timestamp type bit를 고르는 mask
V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN0x00000000알 수 없는 timestamp type. Linux 3.9 이전 driver에서 monotonic 또는 realtime일 수 있음
V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC0x00002000Timestamp가 CLOCK_MONOTONIC에서 얻어짐
V4L2_BUF_FLAG_TIMESTAMP_COPY0x00004000CAPTURE timestamp가 대응 OUTPUT buffer에서 copy됨. Mem2mem device에만 적용
V4L2_BUF_FLAG_TSTAMP_SRC_MASK0x00070000Frame과 관련해 timestamp를 얻은 시점을 고르는 source mask. COPY output stream에서는 application이 source 설정
V4L2_BUF_FLAG_TSTAMP_SRC_EOF0x00000000End Of Frame. 마지막 pixel을 수신 또는 전송한 때의 timestamp. Software timestamp는 실제로 약간 뒤일 수 있음
V4L2_BUF_FLAG_TSTAMP_SRC_SOE0x00010000Start Of Exposure. Frame exposure가 시작된 때의 timestamp이며 VIDEO_CAPTURE type에만 유효

Timestamp mask와 source mask는 flags에 logical AND를 적용해 해석합니다.

`V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN`의 monotonic/realtime clock은 userspace에서 각각 `clock_gettime(CLOCK_MONOTONIC)`과 `clock_gettime(CLOCK_REALTIME)`으로 접근할 수 있습니다.

    * .. _`V4L2-BUF-FLAG-M2M-HOLD-CAPTURE-BUF`:

      - ``V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF``
      - 0x00000200
      - Only valid if struct :c:type:`v4l2_requestbuffers` flag ``V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF`` is
	set. It is typically used with stateless decoders where multiple
	output buffers each decode to a slice of the decoded frame.
	Applications can set this flag when queueing the output buffer
	to prevent the driver from dequeueing the capture buffer after
	the output buffer has been decoded (i.e. the capture buffer is
	'held'). If the timestamp of this output buffer differs from that
	of the previous output buffer, then that indicates the start of a
	new frame and the previously held capture buffer is dequeued.
    * .. _`V4L2-BUF-FLAG-LAST`:

      - ``V4L2_BUF_FLAG_LAST``
      - 0x00100000
      - Last buffer produced by the hardware. mem2mem codec drivers set
	this flag on the capture queue for the last buffer when the
	:ref:`VIDIOC_QUERYBUF` or
	:ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl is called. Due to
	hardware limitations, the last buffer may be empty. In this case
	the driver will set the ``bytesused`` field to 0, regardless of
	the format. Any subsequent call to the
	:ref:`VIDIOC_DQBUF <VIDIOC_QBUF>` ioctl will not block anymore,
	but return an ``EPIPE`` error code.
    * .. _`V4L2-BUF-FLAG-REQUEST-FD`:

      - ``V4L2_BUF_FLAG_REQUEST_FD``
      - 0x00800000
      - The ``request_fd`` field contains a valid file descriptor.
    * .. _`V4L2-BUF-FLAG-TIMESTAMP-MASK`:

      - ``V4L2_BUF_FLAG_TIMESTAMP_MASK``
      - 0x0000e000
      - Mask for timestamp types below. To test the timestamp type, mask
	out bits not belonging to timestamp type by performing a logical
	and operation with buffer flags and timestamp mask.
    * .. _`V4L2-BUF-FLAG-TIMESTAMP-UNKNOWN`:

      - ``V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN``
      - 0x00000000
      - Unknown timestamp type. This type is used by drivers before Linux
	3.9 and may be either monotonic (see below) or realtime (wall
	clock). Monotonic clock has been favoured in embedded systems
	whereas most of the drivers use the realtime clock. Either kinds
	of timestamps are available in user space via
	:c:func:`clock_gettime` using clock IDs ``CLOCK_MONOTONIC``
	and ``CLOCK_REALTIME``, respectively.
    * .. _`V4L2-BUF-FLAG-TIMESTAMP-MONOTONIC`:

      - ``V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC``
      - 0x00002000
      - The buffer timestamp has been taken from the ``CLOCK_MONOTONIC``
	clock. To access the same clock outside V4L2, use
	:c:func:`clock_gettime`.
    * .. _`V4L2-BUF-FLAG-TIMESTAMP-COPY`:

      - ``V4L2_BUF_FLAG_TIMESTAMP_COPY``
      - 0x00004000
      - The CAPTURE buffer timestamp has been taken from the corresponding
	OUTPUT buffer. This flag applies only to mem2mem devices.
    * .. _`V4L2-BUF-FLAG-TSTAMP-SRC-MASK`:

      - ``V4L2_BUF_FLAG_TSTAMP_SRC_MASK``
      - 0x00070000
      - Mask for timestamp sources below. The timestamp source defines the
	point of time the timestamp is taken in relation to the frame.
	Logical 'and' operation between the ``flags`` field and
	``V4L2_BUF_FLAG_TSTAMP_SRC_MASK`` produces the value of the
	timestamp source. Applications must set the timestamp source when
	``type`` refers to an output stream and
	``V4L2_BUF_FLAG_TIMESTAMP_COPY`` is set.
    * .. _`V4L2-BUF-FLAG-TSTAMP-SRC-EOF`:

      - ``V4L2_BUF_FLAG_TSTAMP_SRC_EOF``
      - 0x00000000
      - End Of Frame. The buffer timestamp has been taken when the last
	pixel of the frame has been received or the last pixel of the
	frame has been transmitted. In practice, software generated
	timestamps will typically be read from the clock a small amount of
	time after the last pixel has been received or transmitten,
	depending on the system and other activity in it.
    * .. _`V4L2-BUF-FLAG-TSTAMP-SRC-SOE`:

      - ``V4L2_BUF_FLAG_TSTAMP_SRC_SOE``
      - 0x00010000
      - Start Of Exposure. The buffer timestamp has been taken when the
	exposure of the frame has begun. This is only valid for the
	``V4L2_BUF_TYPE_VIDEO_CAPTURE`` buffer type.

.. raw:: latex

    \normalsize

enum v4l2_memory

674-700
V4L2 memory type
Symbol설명
V4L2_MEMORY_MMAP1Memory mapping I/O용 buffer
V4L2_MEMORY_USERPTR2User pointer I/O용 buffer
V4L2_MEMORY_OVERLAY3원문 설명은 [to do]
V4L2_MEMORY_DMABUF4DMA shared buffer I/O용 buffer

Buffer를 application과 driver 사이에 공유하는 I/O memory model입니다.

enum v4l2_memory
================

.. tabularcolumns:: |p{5.0cm}|p{0.8cm}|p{11.5cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * - ``V4L2_MEMORY_MMAP``
      - 1
      - The buffer is used for :ref:`memory mapping <mmap>` I/O.
    * - ``V4L2_MEMORY_USERPTR``
      - 2
      - The buffer is used for :ref:`user pointer <userp>` I/O.
    * - ``V4L2_MEMORY_OVERLAY``
      - 3
      - [to do]
    * - ``V4L2_MEMORY_DMABUF``
      - 4
      - The buffer is used for :ref:`DMA shared buffer <dmabuf>` I/O.

.. raw:: latex

    \normalsize

Timecode와 struct v4l2_timecode

701-744

원문이 `v4l2_buffer_timecode`라고 부르는 structure는 SMPTE 12M 또는 유사한 timecode를 담도록 설계되었습니다. `struct timeval` timestamp는 별도로 `struct v4l2_buffer.timestamp`에 저장됩니다.

struct v4l2_timecode field
TypeField설명
__u32typeTimecode가 기반으로 하는 frame rate
__u32flagsTimecode flag
__u8framesType에 따라 0...23/24/29/49/59의 frame count
__u8seconds0...59의 초. BCD가 아닌 binary 값
__u8minutes0...59의 분. BCD가 아닌 binary 값
__u8hours0...29의 시. BCD가 아닌 binary 값
__u8userbits[4]Timecode의 user group bit

Timecode frame rate, flag와 binary counter 및 user group bit를 저장합니다.

Timecodes
=========

The :c:type:`v4l2_buffer_timecode` structure is designed to hold a
:ref:`smpte12m` or similar timecode.
(struct :c:type:`timeval` timestamps are stored in the struct
:c:type:`v4l2_buffer` ``timestamp`` field.)

.. c:type:: v4l2_timecode

struct v4l2_timecode
--------------------

.. tabularcolumns:: |p{1.4cm}|p{2.8cm}|p{13.1cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 2

    * - __u32
      - ``type``
      - Frame rate the timecodes are based on, see :ref:`timecode-type`.
    * - __u32
      - ``flags``
      - Timecode flags, see :ref:`timecode-flags`.
    * - __u8
      - ``frames``
      - Frame count, 0 ... 23/24/29/49/59, depending on the type of
	timecode.
    * - __u8
      - ``seconds``
      - Seconds count, 0 ... 59. This is a binary, not BCD number.
    * - __u8
      - ``minutes``
      - Minutes count, 0 ... 59. This is a binary, not BCD number.
    * - __u8
      - ``hours``
      - Hours count, 0 ... 29. This is a binary, not BCD number.
    * - __u8
      - ``userbits``\ [4]
      - The "user group" bits from the timecode.

Timecode type

745-771
V4L2 timecode type
Symbol설명
V4L2_TC_TYPE_24FPS1초당 24 frame, film
V4L2_TC_TYPE_25FPS2초당 25 frame, PAL 또는 SECAM video
V4L2_TC_TYPE_30FPS3초당 30 frame, NTSC video
V4L2_TC_TYPE_50FPS4원문에 추가 설명 없음
V4L2_TC_TYPE_60FPS5원문에 추가 설명 없음

Timecode count가 기반으로 하는 초당 frame 수입니다.

.. _timecode-type:

Timecode Types
--------------

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * - ``V4L2_TC_TYPE_24FPS``
      - 1
      - 24 frames per second, i. e. film.
    * - ``V4L2_TC_TYPE_25FPS``
      - 2
      - 25 frames per second, i. e. PAL or SECAM video.
    * - ``V4L2_TC_TYPE_30FPS``
      - 3
      - 30 frames per second, i. e. NTSC video.
    * - ``V4L2_TC_TYPE_50FPS``
      - 4
      -
    * - ``V4L2_TC_TYPE_60FPS``
      - 5
      -

Timecode flag

772-801
V4L2 timecode flag
Symbol설명
V4L2_TC_FLAG_DROPFRAME0x000129.97 fps material의 drop-frame counting. 0,10,20,30,40,50분을 제외한 각 분 시작에서 frame 번호 0과 1을 생략
V4L2_TC_FLAG_COLORFRAME0x0002Color frame flag
V4L2_TC_USERBITS_field0x000CBinary group flag용 field mask
V4L2_TC_USERBITS_USERDEFINED0x0000지정되지 않은 format
V4L2_TC_USERBITS_8BITCHARS0x00088-bit ISO character

Drop-frame counting, color-frame와 userbits format을 나타냅니다.

.. _timecode-flags:

Timecode Flags
--------------

.. tabularcolumns:: |p{6.6cm}|p{1.4cm}|p{9.3cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * - ``V4L2_TC_FLAG_DROPFRAME``
      - 0x0001
      - Indicates "drop frame" semantics for counting frames in 29.97 fps
	material. When set, frame numbers 0 and 1 at the start of each
	minute, except minutes 0, 10, 20, 30, 40, 50 are omitted from the
	count.
    * - ``V4L2_TC_FLAG_COLORFRAME``
      - 0x0002
      - The "color frame" flag.
    * - ``V4L2_TC_USERBITS_field``
      - 0x000C
      - Field mask for the "binary group flags".
    * - ``V4L2_TC_USERBITS_USERDEFINED``
      - 0x0000
      - Unspecified format.
    * - ``V4L2_TC_USERBITS_8BITCHARS``
      - 0x0008
      - 8-bit ISO characters.