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

Linux 6.18.37 · Userspace API / Media / V4L

V4L2 read()

V4L2 frame 읽기의 blocking, internal buffer와 frame 폐기 정책을 설명합니다.

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

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

1. 요약·해설

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

요약·해설

func-read.rst:1-130

V4L2 `read()`는 호출당 최대 한 frame만 완성된 상태로 반환하고, internal buffer가 부족할 때 어느 frame을 버리는지는 보고되지 않는 driver 정책입니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
2 .. c:namespace:: V4L
3
4 .. _func-read:
5
6 ***********
7 V4L2 read()
8 ***********
9
10 Name
11 ====
12
13 v4l2-read - Read from a V4L2 device
14
15 Synopsis
16 ========
17
18 .. code-block:: c
19
20 #include <unistd.h>
21
22 .. c:function:: ssize_t read( int fd, void *buf, size_t count )
23
24 Arguments
25 =========
26
27 ``fd``
28 File descriptor returned by :c:func:`open()`.
29
30 ``buf``
31 Buffer to be filled
32
33 ``count``
34 Max number of bytes to read
35
36 Description
37 ===========
38
39 :c:func:`read()` attempts to read up to ``count`` bytes from file
40 descriptor ``fd`` into the buffer starting at ``buf``. The layout of the
41 data in the buffer is discussed in the respective device interface
42 section, see ##. If ``count`` is zero, :c:func:`read()` returns zero
43 and has no other results. If ``count`` is greater than ``SSIZE_MAX``,
44 the result is unspecified. Regardless of the ``count`` value each
45 :c:func:`read()` call will provide at most one frame (two fields)
46 worth of data.
47
48 By default :c:func:`read()` blocks until data becomes available. When
49 the ``O_NONBLOCK`` flag was given to the :c:func:`open()`
50 function it returns immediately with an ``EAGAIN`` error code when no data
51 is available. The :c:func:`select()` or
52 :c:func:`poll()` functions can always be used to suspend
53 execution until data becomes available. All drivers supporting the
54 :c:func:`read()` function must also support :c:func:`select()` and
55 :c:func:`poll()`.
56
57 Drivers can implement read functionality in different ways, using a
58 single or multiple buffers and discarding the oldest or newest frames
59 once the internal buffers are filled.
60
61 :c:func:`read()` never returns a "snapshot" of a buffer being filled.
62 Using a single buffer the driver will stop capturing when the
63 application starts reading the buffer until the read is finished. Thus
64 only the period of the vertical blanking interval is available for
65 reading, or the capture rate must fall below the nominal frame rate of
66 the video standard.
67
68 The behavior of :c:func:`read()` when called during the active picture
69 period or the vertical blanking separating the top and bottom field
70 depends on the discarding policy. A driver discarding the oldest frames
71 keeps capturing into an internal buffer, continuously overwriting the
72 previously, not read frame, and returns the frame being received at the
73 time of the :c:func:`read()` call as soon as it is complete.
74
75 A driver discarding the newest frames stops capturing until the next
76 :c:func:`read()` call. The frame being received at :c:func:`read()`
77 time is discarded, returning the following frame instead. Again this
78 implies a reduction of the capture rate to one half or less of the
79 nominal frame rate. An example of this model is the video read mode of
80 the bttv driver, initiating a DMA to user memory when :c:func:`read()`
81 is called and returning when the DMA finished.
82
83 In the multiple buffer model drivers maintain a ring of internal
84 buffers, automatically advancing to the next free buffer. This allows
85 continuous capturing when the application can empty the buffers fast
86 enough. Again, the behavior when the driver runs out of free buffers
87 depends on the discarding policy.
88
89 Applications can get and set the number of buffers used internally by
90 the driver with the :ref:`VIDIOC_G_PARM <VIDIOC_G_PARM>` and
91 :ref:`VIDIOC_S_PARM <VIDIOC_G_PARM>` ioctls. They are optional,
92 however. The discarding policy is not reported and cannot be changed.
93 For minimum requirements see :ref:`devices`.
94
95 Return Value
96 ============
97
98 On success, the number of bytes read is returned. It is not an error if
99 this number is smaller than the number of bytes requested, or the amount
100 of data required for one frame. This may happen for example because
101 :c:func:`read()` was interrupted by a signal. On error, -1 is
102 returned, and the ``errno`` variable is set appropriately. In this case
103 the next read will start at the beginning of a new frame. Possible error
104 codes are:
105
106 EAGAIN
107 Non-blocking I/O has been selected using O_NONBLOCK and no data was
108 immediately available for reading.
109
110 EBADF
111 ``fd`` is not a valid file descriptor or is not open for reading, or
112 the process already has the maximum number of files open.
113
114 EBUSY
115 The driver does not support multiple read streams and the device is
116 already in use.
117
118 EFAULT
119 ``buf`` references an inaccessible memory area.
120
121 EINTR
122 The call was interrupted by a signal before any data was read.
123
124 EIO
125 I/O error. This indicates some hardware problem or a failure to
126 communicate with a remote device (USB camera etc.).
127
128 EINVAL
129 The :c:func:`read()` function is not supported by this driver, not
130 on this device, or generally not on this type of device.
131

3. 한국어 전문 번역

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

읽기 선언과 인자

1-35

`v4l2-read`는 V4L2 장치에서 data를 읽습니다. `<unistd.h>`를 포함하고 `ssize_t read(int fd, void *buf, size_t count)`를 호출합니다.

`read()` 인자
항목설명
`fd``open()`이 반환한 file descriptor입니다.
`buf`읽은 data로 채울 buffer입니다.
`count`최대 읽기 byte 수입니다.

읽을 장치, destination buffer와 최대 byte 수를 지정합니다.

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

.. _func-read:

***********
V4L2 read()
***********

Name
====

v4l2-read - Read from a V4L2 device

Synopsis
========

.. code-block:: c

    #include <unistd.h>

.. c:function:: ssize_t read( int fd, void *buf, size_t count )

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``buf``
   Buffer to be filled

``count``
  Max number of bytes to read

Frame 단위 읽기와 buffer 폐기 정책

36-94

`read()`는 `fd`에서 최대 `count` byte를 `buf`로 읽습니다. Buffer data layout은 해당 device interface 절을 따릅니다. `count == 0`이면 다른 효과 없이 0을 반환하고, `count > SSIZE_MAX`의 결과는 정의되지 않습니다. `count`와 관계없이 한 번의 호출은 최대 한 frame, 즉 두 field 분량만 제공합니다.

기본적으로 data가 생길 때까지 block합니다. `open()`에 `O_NONBLOCK`을 줬고 data가 없으면 즉시 `EAGAIN`을 반환합니다. `select()`와 `poll()`로 data가 준비될 때까지 기다릴 수 있으며 read를 지원하는 모든 driver는 두 함수도 지원해야 합니다.

Driver는 single 또는 multiple internal buffer를 사용하고 가득 찼을 때 oldest 또는 newest frame을 버리는 등 서로 다른 방식으로 read를 구현할 수 있습니다. 채우는 중인 buffer의 snapshot을 반환하는 일은 없습니다.

Single-buffer 방식은 application이 읽기 시작하면 완료될 때까지 capture를 멈춥니다. 따라서 vertical blanking interval 안에 읽기를 끝내거나 capture rate가 nominal frame rate보다 낮아져야 합니다. Active picture 또는 top/bottom field 사이 blanking에서 호출했을 때 동작은 폐기 정책에 달려 있습니다.

Internal buffer 폐기 정책
항목설명
Oldest frame 폐기Internal buffer에 계속 capture하며 읽지 않은 이전 frame을 덮어씁니다. `read()` 시점에 수신 중이던 frame이 완성되면 반환합니다.
Newest frame 폐기다음 `read()`까지 capture를 멈춥니다. 호출 시 수신 중이던 frame을 버리고 그 다음 frame을 반환하므로 rate가 nominal의 절반 이하로 줄 수 있습니다.
bttv video read`read()` 때 user memory로 DMA를 시작하고 DMA 완료 후 반환하는 newest-discard model의 예입니다.
Multiple-buffer ringDriver가 다음 free buffer로 자동 이동해 application이 충분히 빨리 비우면 continuous capture를 유지합니다.

Buffer가 부족할 때 어느 frame을 유지할지에 따라 반환 시점과 capture rate가 달라집니다.

Application은 선택 사항인 `VIDIOC_G_PARM`과 `VIDIOC_S_PARM`으로 driver 내부 buffer 수를 조회하거나 설정할 수 있습니다. 폐기 정책은 보고되지 않고 변경할 수도 없습니다.

Read buffer lifecycle
Driver가 internal buffer에 frame capture완성된 frame만 readable 상태로 전환Application이 `read()` 호출Free buffer가 있으면 다음 capture 계속없으면 oldest/newest 폐기 정책 적용

완성된 frame만 반환하며 free buffer가 사라지면 driver 정책이 적용됩니다.

Description
===========

:c:func:`read()` attempts to read up to ``count`` bytes from file
descriptor ``fd`` into the buffer starting at ``buf``. The layout of the
data in the buffer is discussed in the respective device interface
section, see ##. If ``count`` is zero, :c:func:`read()` returns zero
and has no other results. If ``count`` is greater than ``SSIZE_MAX``,
the result is unspecified. Regardless of the ``count`` value each
:c:func:`read()` call will provide at most one frame (two fields)
worth of data.

By default :c:func:`read()` blocks until data becomes available. When
the ``O_NONBLOCK`` flag was given to the :c:func:`open()`
function it returns immediately with an ``EAGAIN`` error code when no data
is available. The :c:func:`select()` or
:c:func:`poll()` functions can always be used to suspend
execution until data becomes available. All drivers supporting the
:c:func:`read()` function must also support :c:func:`select()` and
:c:func:`poll()`.

Drivers can implement read functionality in different ways, using a
single or multiple buffers and discarding the oldest or newest frames
once the internal buffers are filled.

:c:func:`read()` never returns a "snapshot" of a buffer being filled.
Using a single buffer the driver will stop capturing when the
application starts reading the buffer until the read is finished. Thus
only the period of the vertical blanking interval is available for
reading, or the capture rate must fall below the nominal frame rate of
the video standard.

The behavior of :c:func:`read()` when called during the active picture
period or the vertical blanking separating the top and bottom field
depends on the discarding policy. A driver discarding the oldest frames
keeps capturing into an internal buffer, continuously overwriting the
previously, not read frame, and returns the frame being received at the
time of the :c:func:`read()` call as soon as it is complete.

A driver discarding the newest frames stops capturing until the next
:c:func:`read()` call. The frame being received at :c:func:`read()`
time is discarded, returning the following frame instead. Again this
implies a reduction of the capture rate to one half or less of the
nominal frame rate. An example of this model is the video read mode of
the bttv driver, initiating a DMA to user memory when :c:func:`read()`
is called and returning when the DMA finished.

In the multiple buffer model drivers maintain a ring of internal
buffers, automatically advancing to the next free buffer. This allows
continuous capturing when the application can empty the buffers fast
enough. Again, the behavior when the driver runs out of free buffers
depends on the discarding policy.

Applications can get and set the number of buffers used internally by
the driver with the :ref:`VIDIOC_G_PARM <VIDIOC_G_PARM>` and
:ref:`VIDIOC_S_PARM <VIDIOC_G_PARM>` ioctls. They are optional,
however. The discarding policy is not reported and cannot be changed.
For minimum requirements see :ref:`devices`.

짧은 읽기, frame 경계와 오류

95-130

성공하면 읽은 byte 수를 반환합니다. 요청한 수나 한 frame에 필요한 양보다 작아도 오류는 아니며 signal interruption 때문에 발생할 수 있습니다. 오류면 -1과 `errno`를 반환하고 다음 `read()`는 새 frame의 시작에서 다시 시작합니다.

`read()` 오류
항목설명
`EAGAIN``O_NONBLOCK` 상태에서 즉시 읽을 data가 없습니다.
`EBADF``fd`가 유효하지 않거나 read로 열리지 않았거나 process의 open file 수가 최대입니다.
`EBUSY`Driver가 multiple read stream을 지원하지 않고 장치가 이미 사용 중입니다.
`EFAULT``buf`가 접근할 수 없는 memory를 참조합니다.
`EINTR`Data를 하나도 읽기 전에 signal이 호출을 중단했습니다.
`EIO`Hardware 문제 또는 USB camera 같은 remote device와의 통신 실패입니다.
`EINVAL`해당 driver, device 또는 device 종류가 `read()`를 지원하지 않습니다.

Non-blocking 상태, descriptor, buffer, signal과 hardware 실패를 구분합니다.

Return Value
============

On success, the number of bytes read is returned. It is not an error if
this number is smaller than the number of bytes requested, or the amount
of data required for one frame. This may happen for example because
:c:func:`read()` was interrupted by a signal. On error, -1 is
returned, and the ``errno`` variable is set appropriately. In this case
the next read will start at the beginning of a new frame. Possible error
codes are:

EAGAIN
    Non-blocking I/O has been selected using O_NONBLOCK and no data was
    immediately available for reading.

EBADF
    ``fd`` is not a valid file descriptor or is not open for reading, or
    the process already has the maximum number of files open.

EBUSY
    The driver does not support multiple read streams and the device is
    already in use.

EFAULT
    ``buf`` references an inaccessible memory area.

EINTR
    The call was interrupted by a signal before any data was read.

EIO
    I/O error. This indicates some hardware problem or a failure to
    communicate with a remote device (USB camera etc.).

EINVAL
    The :c:func:`read()` function is not supported by this driver, not
    on this device, or generally not on this type of device.