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

Linux 6.18.37 · Userspace API / Media / V4L

V4L2 장치 열기와 닫기

MC-centric 제어, 장치 노드 이름, 관련 기능, multiple open과 streaming 소유권을 설명합니다.

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

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

1. 요약·해설

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

요약·해설

open.rst:1-238

QUERYCAP으로 MC-centric 여부를 판별하고 기능별 node를 안정적 udev symlink로 식별하며, buffer 할당 순간 filehandle이 streaming owner가 됩니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
2 .. c:namespace:: V4L
3
4 .. _open:
5
6 ***************************
7 Opening and Closing Devices
8 ***************************
9
10 .. _v4l2_hardware_control:
11
12 Controlling a hardware peripheral via V4L2
13 ==========================================
14
15 Hardware that is supported using the V4L2 uAPI often consists of multiple
16 devices or peripherals, each of which have their own driver.
17
18 The bridge driver exposes one or more V4L2 device nodes
19 (see :ref:`v4l2_device_naming`).
20
21 There are other drivers providing support for other components of
22 the hardware, which may also expose device nodes, called V4L2 sub-devices.
23
24 When such V4L2 sub-devices are exposed, they allow controlling those
25 other hardware components - usually connected via a serial bus (like
26 I²C, SMBus or SPI). Depending on the bridge driver, those sub-devices
27 can be controlled indirectly via the bridge driver or explicitly via
28 the :ref:`Media Controller <media_controller>` and via the
29 :ref:`V4L2 sub-devices <subdev>`.
30
31 The devices that require the use of the
32 :ref:`Media Controller <media_controller>` are called **MC-centric**
33 devices. The devices that are fully controlled via V4L2 device nodes
34 are called **video-node-centric**.
35
36 Userspace can check if a V4L2 hardware peripheral is MC-centric by
37 calling :ref:`VIDIOC_QUERYCAP` and checking the
38 :ref:`device_caps field <device-capabilities>`.
39
40 If the device returns ``V4L2_CAP_IO_MC`` flag at ``device_caps``,
41 then it is MC-centric, otherwise, it is video-node-centric.
42
43 It is required for MC-centric drivers to identify the V4L2
44 sub-devices and to configure the pipelines via the
45 :ref:`media controller API <media_controller>` before using the peripheral.
46 Also, the sub-devices' configuration shall be controlled via the
47 :ref:`sub-device API <subdev>`.
48
49 .. note::
50
51 A video-node-centric may still provide media-controller and
52 sub-device interfaces as well.
53
54 However, in that case the media-controller and the sub-device
55 interfaces are read-only and just provide information about the
56 device. The actual configuration is done via the video nodes.
57
58 .. _v4l2_device_naming:
59
60 V4L2 Device Node Naming
61 =======================
62
63 V4L2 drivers are implemented as kernel modules, loaded manually by the
64 system administrator or automatically when a device is first discovered.
65 The driver modules plug into the ``videodev`` kernel module. It provides
66 helper functions and a common application interface specified in this
67 document.
68
69 Each driver thus loaded registers one or more device nodes with major
70 number 81. Minor numbers are allocated dynamically unless the kernel
71 is compiled with the kernel option CONFIG_VIDEO_FIXED_MINOR_RANGES.
72 In that case minor numbers are allocated in ranges depending on the
73 device node type.
74
75 The device nodes supported by the Video4Linux subsystem are:
76
77 ======================== ====================================================
78 Default device node name Usage
79 ======================== ====================================================
80 ``/dev/videoX`` Video and metadata for capture/output devices
81 ``/dev/vbiX`` Vertical blank data (i.e. closed captions, teletext)
82 ``/dev/radioX`` Radio tuners and modulators
83 ``/dev/swradioX`` Software Defined Radio tuners and modulators
84 ``/dev/v4l-touchX`` Touch sensors
85 ``/dev/v4l-subdevX`` Video sub-devices (used by sensors and other
86 components of the hardware peripheral)\ [#]_
87 ======================== ====================================================
88
89 Where ``X`` is a non-negative integer.
90
91 .. note::
92
93 1. The actual device node name is system-dependent, as udev rules may apply.
94 2. There is no guarantee that ``X`` will remain the same for the same
95 device, as the number depends on the device driver's probe order.
96 If you need an unique name, udev default rules produce
97 ``/dev/v4l/by-id/`` and ``/dev/v4l/by-path/`` directories containing
98 links that can be used uniquely to identify a V4L2 device node::
99
100 $ tree /dev/v4l
101 /dev/v4l
102 ├── by-id
103 │   └── usb-OmniVision._USB_Camera-B4.04.27.1-video-index0 -> ../../video0
104 └── by-path
105 └── pci-0000:00:14.0-usb-0:2:1.0-video-index0 -> ../../video0
106
107 .. [#] **V4L2 sub-device nodes** (e. g. ``/dev/v4l-subdevX``) use a different
108 set of system calls, as covered at :ref:`subdev`.
109
110 Many drivers support "video_nr", "radio_nr" or "vbi_nr" module
111 options to select specific video/radio/vbi node numbers. This allows the
112 user to request that the device node is named e.g. /dev/video5 instead
113 of leaving it to chance. When the driver supports multiple devices of
114 the same type more than one device node number can be assigned,
115 separated by commas:
116
117 .. code-block:: none
118
119 # modprobe mydriver video_nr=0,1 radio_nr=0,1
120
121 In ``/etc/modules.conf`` this may be written as:
122
123 ::
124
125 options mydriver video_nr=0,1 radio_nr=0,1
126
127 When no device node number is given as module option the driver supplies
128 a default.
129
130 Normally udev will create the device nodes in /dev automatically for
131 you. If udev is not installed, then you need to enable the
132 CONFIG_VIDEO_FIXED_MINOR_RANGES kernel option in order to be able to
133 correctly relate a minor number to a device node number. I.e., you need
134 to be certain that minor number 5 maps to device node name video5. With
135 this kernel option different device types have different minor number
136 ranges. These ranges are listed in :ref:`devices`.
137
138 The creation of character special files (with mknod) is a privileged
139 operation and devices cannot be opened by major and minor number. That
140 means applications cannot *reliably* scan for loaded or installed
141 drivers. The user must enter a device name, or the application can try
142 the conventional device names.
143
144 .. _related:
145
146 Related Devices
147 ===============
148
149 Devices can support several functions. For example video capturing, VBI
150 capturing and radio support.
151
152 The V4L2 API creates different V4L2 device nodes for each of these functions.
153
154 The V4L2 API was designed with the idea that one device node could
155 support all functions. However, in practice this never worked: this
156 'feature' was never used by applications and many drivers did not
157 support it and if they did it was certainly never tested. In addition,
158 switching a device node between different functions only works when
159 using the streaming I/O API, not with the
160 :c:func:`read()`/\ :c:func:`write()` API.
161
162 Today each V4L2 device node supports just one function.
163
164 Besides video input or output the hardware may also support audio
165 sampling or playback. If so, these functions are implemented as ALSA PCM
166 devices with optional ALSA audio mixer devices.
167
168 One problem with all these devices is that the V4L2 API makes no
169 provisions to find these related V4L2 device nodes. Some really complex
170 hardware use the Media Controller (see :ref:`media_controller`) which can
171 be used for this purpose. But several drivers do not use it, and while some
172 code exists that uses sysfs to discover related V4L2 device nodes (see
173 libmedia_dev in the
174 `v4l-utils <http://git.linuxtv.org/cgit.cgi/v4l-utils.git/>`__ git
175 repository), there is no library yet that can provide a single API
176 towards both Media Controller-based devices and devices that do not use
177 the Media Controller. If you want to work on this please write to the
178 linux-media mailing list:
179 `https://linuxtv.org/lists.php <https://linuxtv.org/lists.php>`__.
180
181 Multiple Opens
182 ==============
183
184 V4L2 devices can be opened more than once. [#f1]_ When this is supported
185 by the driver, users can for example start a "panel" application to
186 change controls like brightness or audio volume, while another
187 application captures video and audio. In other words, panel applications
188 are comparable to an ALSA audio mixer application. Just opening a V4L2
189 device should not change the state of the device. [#f2]_
190
191 Once an application has allocated the memory buffers needed for
192 streaming data (by calling the :ref:`VIDIOC_REQBUFS`
193 or :ref:`VIDIOC_CREATE_BUFS` ioctls, or
194 implicitly by calling the :c:func:`read()` or
195 :c:func:`write()` functions) that application (filehandle)
196 becomes the owner of the device. It is no longer allowed to make changes
197 that would affect the buffer sizes (e.g. by calling the
198 :ref:`VIDIOC_S_FMT <VIDIOC_G_FMT>` ioctl) and other applications are
199 no longer allowed to allocate buffers or start or stop streaming. The
200 EBUSY error code will be returned instead.
201
202 Merely opening a V4L2 device does not grant exclusive access. [#f3]_
203 Initiating data exchange however assigns the right to read or write the
204 requested type of data, and to change related properties, to this file
205 descriptor. Applications can request additional access privileges using
206 the priority mechanism described in :ref:`app-pri`.
207
208 Shared Data Streams
209 ===================
210
211 V4L2 drivers should not support multiple applications reading or writing
212 the same data stream on a device by copying buffers, time multiplexing
213 or similar means. This is better handled by a proxy application in user
214 space.
215
216 Functions
217 =========
218
219 To open and close V4L2 devices applications use the
220 :c:func:`open()` and :c:func:`close()` function,
221 respectively. Devices are programmed using the
222 :ref:`ioctl() <func-ioctl>` function as explained in the following
223 sections.
224
225 .. [#f1]
226 There are still some old and obscure drivers that have not been
227 updated to allow for multiple opens. This implies that for such
228 drivers :c:func:`open()` can return an ``EBUSY`` error code
229 when the device is already in use.
230
231 .. [#f2]
232 Unfortunately, opening a radio device often switches the state of the
233 device to radio mode in many drivers. This behavior should be fixed
234 eventually as it violates the V4L2 specification.
235
236 .. [#f3]
237 Drivers could recognize the ``O_EXCL`` open flag. Presently this is
238 not required, so applications cannot know if it really works.
239

3. 한국어 전문 번역

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

MC-centric와 video-node-centric 하드웨어

1-59

V4L2 uAPI로 지원하는 하드웨어 주변장치는 흔히 각자 드라이버를 가진 여러 장치와 peripheral로 구성됩니다. Bridge driver는 하나 이상의 V4L2 device node를 노출하고 다른 구성 요소 드라이버는 sensor 등 V4L2 sub-device node를 노출할 수 있습니다.

Sub-device는 보통 I2C, SMBus, SPI 같은 serial bus로 연결된 구성 요소를 제어합니다. Bridge driver에 따라 bridge를 통해 간접 제어하거나 Media Controller와 V4L2 sub-device API로 명시적으로 제어합니다.

하드웨어 제어 모델
항목설명
MC-centric`V4L2_CAP_IO_MC`가 설정됩니다. 사용 전에 Media Controller로 sub-device를 식별하고 pipeline을 구성하며 sub-device API로 각 설정을 제어해야 합니다.
Video-node-centric`V4L2_CAP_IO_MC`가 없습니다. V4L2 video node가 주변장치를 완전히 제어합니다.
정보용 MC 노출Video-node-centric 장치도 MC와 sub-device 인터페이스를 제공할 수 있지만 이 경우 read-only 정보용이고 실제 설정은 video node에서 합니다.

`VIDIOC_QUERYCAP`의 `device_caps`에서 구분합니다.

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

.. _open:

***************************
Opening and Closing Devices
***************************

.. _v4l2_hardware_control:

Controlling a hardware peripheral via V4L2
==========================================

Hardware that is supported using the V4L2 uAPI often consists of multiple
devices or peripherals, each of which have their own driver.

The bridge driver exposes one or more V4L2 device nodes
(see :ref:`v4l2_device_naming`).

There are other drivers providing support for other components of
the hardware, which may also expose device nodes, called V4L2 sub-devices.

When such V4L2 sub-devices are exposed, they allow controlling those
other hardware components - usually connected via a serial bus (like
I²C, SMBus or SPI). Depending on the bridge driver, those sub-devices
can be controlled indirectly via the bridge driver or explicitly via
the :ref:`Media Controller <media_controller>` and via the
:ref:`V4L2 sub-devices <subdev>`.

The devices that require the use of the
:ref:`Media Controller <media_controller>` are called **MC-centric**
devices. The devices that are fully controlled via V4L2 device nodes
are called **video-node-centric**.

Userspace can check if a V4L2 hardware peripheral is MC-centric by
calling :ref:`VIDIOC_QUERYCAP` and checking the
:ref:`device_caps field <device-capabilities>`.

If the device returns ``V4L2_CAP_IO_MC`` flag at ``device_caps``,
then it is MC-centric, otherwise, it is video-node-centric.

It is required for MC-centric drivers to identify the V4L2
sub-devices and to configure the pipelines via the
:ref:`media controller API <media_controller>` before using the peripheral.
Also, the sub-devices' configuration shall be controlled via the
:ref:`sub-device API <subdev>`.

.. note::

   A video-node-centric may still provide media-controller and
   sub-device interfaces as well.

  However, in that case the media-controller and the sub-device
  interfaces are read-only and just provide information about the
  device. The actual configuration is done via the video nodes.

.. _v4l2_device_naming:

장치 노드 이름과 안정적 식별

60-145

V4L2 driver는 수동 또는 장치 발견 시 자동으로 load되는 kernel module이며 `videodev` module에 연결됩니다. 각 driver는 major 81인 device node 하나 이상을 등록합니다. Minor는 기본적으로 동적이며 `CONFIG_VIDEO_FIXED_MINOR_RANGES`를 쓰면 node type별 범위에서 할당됩니다.

기본 장치 노드
항목설명
`/dev/videoX`capture/output 장치의 video 및 metadata
`/dev/vbiX`closed caption, teletext 같은 vertical blank data
`/dev/radioX`radio tuner와 modulator
`/dev/swradioX`Software Defined Radio tuner와 modulator
`/dev/v4l-touchX`touch sensor
`/dev/v4l-subdevX`sensor와 다른 peripheral 구성 요소용 video sub-device이며 별도 system call 집합을 사용합니다.

X는 0 이상의 정수입니다.

실제 이름은 udev rule에 따라 달라질 수 있고 probe 순서 때문에 같은 장치의 X가 재부팅 뒤 같다는 보장도 없습니다. 고유 식별이 필요하면 udev 기본 rule이 만드는 `/dev/v4l/by-id/`와 `/dev/v4l/by-path/` symlink를 사용합니다.

udev 안정 경로 구조
`/dev/v4l/``by-id/` → 예: `usb-OmniVision...-video-index0` → `../../video0``by-path/` → 예: `pci-0000:00:14.0-usb-0:2:1.0-video-index0` → `../../video0`

원문의 `/dev/v4l` ASCII tree를 같은 계층으로 구조화했습니다.

일부 driver의 `video_nr`, `radio_nr`, `vbi_nr` module option으로 원하는 번호를 요청할 수 있고 같은 type 장치가 여러 개면 comma로 나열합니다. 예제는 `modprobe mydriver video_nr=0,1 radio_nr=0,1`이며 `/etc/modules.conf`에서는 options 줄로 기록합니다. 옵션이 없으면 driver 기본값을 씁니다.

보통 udev가 `/dev` node를 자동 생성합니다. udev가 없다면 minor와 node 번호의 관계를 보장하도록 `CONFIG_VIDEO_FIXED_MINOR_RANGES`가 필요합니다. `mknod`는 privileged operation이고 major/minor 번호로 직접 장치를 열 수 없으므로 응용 프로그램이 설치된 driver를 신뢰성 있게 scan할 수 없습니다. 사용자에게 이름을 받거나 관례적 이름을 시도해야 합니다.

V4L2 Device Node Naming
=======================

V4L2 drivers are implemented as kernel modules, loaded manually by the
system administrator or automatically when a device is first discovered.
The driver modules plug into the ``videodev`` kernel module. It provides
helper functions and a common application interface specified in this
document.

Each driver thus loaded registers one or more device nodes with major
number 81. Minor numbers are allocated dynamically unless the kernel
is compiled with the kernel option CONFIG_VIDEO_FIXED_MINOR_RANGES.
In that case minor numbers are allocated in ranges depending on the
device node type.

The device nodes supported by the Video4Linux subsystem are:

======================== ====================================================
Default device node name Usage
======================== ====================================================
``/dev/videoX``		 Video and metadata for capture/output devices
``/dev/vbiX``		 Vertical blank data (i.e. closed captions, teletext)
``/dev/radioX``		 Radio tuners and modulators
``/dev/swradioX``	 Software Defined Radio tuners and modulators
``/dev/v4l-touchX``	 Touch sensors
``/dev/v4l-subdevX``	 Video sub-devices (used by sensors and other
			 components of the hardware peripheral)\ [#]_
======================== ====================================================

Where ``X`` is a non-negative integer.

.. note::

   1. The actual device node name is system-dependent, as udev rules may apply.
   2. There is no guarantee that ``X`` will remain the same for the same
      device, as the number depends on the device driver's probe order.
      If you need an unique name, udev default rules produce
      ``/dev/v4l/by-id/`` and ``/dev/v4l/by-path/`` directories containing
      links that can be used uniquely to identify a V4L2 device node::

	$ tree /dev/v4l
	/dev/v4l
	├── by-id
	│   └── usb-OmniVision._USB_Camera-B4.04.27.1-video-index0 -> ../../video0
	└── by-path
	    └── pci-0000:00:14.0-usb-0:2:1.0-video-index0 -> ../../video0

.. [#] **V4L2 sub-device nodes** (e. g. ``/dev/v4l-subdevX``) use a different
       set of system calls, as covered at :ref:`subdev`.

Many drivers support "video_nr", "radio_nr" or "vbi_nr" module
options to select specific video/radio/vbi node numbers. This allows the
user to request that the device node is named e.g. /dev/video5 instead
of leaving it to chance. When the driver supports multiple devices of
the same type more than one device node number can be assigned,
separated by commas:

.. code-block:: none

   # modprobe mydriver video_nr=0,1 radio_nr=0,1

In ``/etc/modules.conf`` this may be written as:

::

    options mydriver video_nr=0,1 radio_nr=0,1

When no device node number is given as module option the driver supplies
a default.

Normally udev will create the device nodes in /dev automatically for
you. If udev is not installed, then you need to enable the
CONFIG_VIDEO_FIXED_MINOR_RANGES kernel option in order to be able to
correctly relate a minor number to a device node number. I.e., you need
to be certain that minor number 5 maps to device node name video5. With
this kernel option different device types have different minor number
ranges. These ranges are listed in :ref:`devices`.

The creation of character special files (with mknod) is a privileged
operation and devices cannot be opened by major and minor number. That
means applications cannot *reliably* scan for loaded or installed
drivers. The user must enter a device name, or the application can try
the conventional device names.

.. _related:

여러 번 열기와 streaming 소유권

181-207

Driver가 지원하면 V4L2 장치를 여러 번 열 수 있습니다. 한 응용 프로그램이 video/audio를 캡처하는 동안 panel application이 brightness나 volume을 바꾸는 식이며 ALSA mixer와 비슷합니다. 단순 open 자체는 장치 상태를 바꾸지 않아야 합니다.

응용 프로그램이 REQBUFS/CREATE_BUFS를 호출하거나 read/write로 암시적으로 streaming buffer를 할당하면 그 filehandle이 장치 owner가 됩니다. 이후 buffer 크기에 영향을 주는 S_FMT 변경은 허용되지 않고 다른 응용 프로그램도 buffer 할당이나 streaming start/stop을 할 수 없으며 `EBUSY`를 받습니다.

Open만으로 exclusive access를 얻지는 않습니다. Data exchange를 시작해야 해당 data type을 읽거나 쓰고 관련 속성을 바꿀 권리가 descriptor에 부여됩니다. 추가 권한은 application priority mechanism으로 요청할 수 있습니다.

Multiple Opens
==============

V4L2 devices can be opened more than once. [#f1]_ When this is supported
by the driver, users can for example start a "panel" application to
change controls like brightness or audio volume, while another
application captures video and audio. In other words, panel applications
are comparable to an ALSA audio mixer application. Just opening a V4L2
device should not change the state of the device. [#f2]_

Once an application has allocated the memory buffers needed for
streaming data (by calling the :ref:`VIDIOC_REQBUFS`
or :ref:`VIDIOC_CREATE_BUFS` ioctls, or
implicitly by calling the :c:func:`read()` or
:c:func:`write()` functions) that application (filehandle)
becomes the owner of the device. It is no longer allowed to make changes
that would affect the buffer sizes (e.g. by calling the
:ref:`VIDIOC_S_FMT <VIDIOC_G_FMT>` ioctl) and other applications are
no longer allowed to allocate buffers or start or stop streaming. The
EBUSY error code will be returned instead.

Merely opening a V4L2 device does not grant exclusive access. [#f3]_
Initiating data exchange however assigns the right to read or write the
requested type of data, and to change related properties, to this file
descriptor. Applications can request additional access privileges using
the priority mechanism described in :ref:`app-pri`.

공유 data stream은 사용자 공간 proxy로

208-215

V4L2 driver는 buffer 복사, time multiplexing 등으로 여러 응용 프로그램이 같은 stream을 동시에 읽고 쓰게 구현하지 않아야 합니다. 이런 공유는 사용자 공간 proxy application이 담당하는 편이 낫습니다.

Shared Data Streams
===================

V4L2 drivers should not support multiple applications reading or writing
the same data stream on a device by copying buffers, time multiplexing
or similar means. This is better handled by a proxy application in user
space.

open/close 함수와 예외 주석

216-238

응용 프로그램은 `open()`으로 V4L2 장치를 열고 `close()`로 닫으며 이후 절의 `ioctl()`로 프로그래밍합니다.

역사적 예외와 주의
항목설명
오래된 drivermultiple open으로 갱신되지 않은 일부 오래되고 드문 driver는 사용 중인 장치의 open에 `EBUSY`를 반환합니다.
Radio mode많은 driver가 radio node를 여는 것만으로 radio mode로 전환하지만 이는 상태를 바꾸지 않아야 한다는 V4L2 명세 위반이며 수정 대상입니다.
`O_EXCL`Driver가 인식할 수는 있지만 필수가 아니므로 응용 프로그램은 실제 exclusive 동작을 보장받을 수 없습니다.

문서 각주의 드라이버 현실을 정리합니다.

Functions
=========

To open and close V4L2 devices applications use the
:c:func:`open()` and :c:func:`close()` function,
respectively. Devices are programmed using the
:ref:`ioctl() <func-ioctl>` function as explained in the following
sections.

.. [#f1]
   There are still some old and obscure drivers that have not been
   updated to allow for multiple opens. This implies that for such
   drivers :c:func:`open()` can return an ``EBUSY`` error code
   when the device is already in use.

.. [#f2]
   Unfortunately, opening a radio device often switches the state of the
   device to radio mode in many drivers. This behavior should be fixed
   eventually as it violates the V4L2 specification.

.. [#f3]
   Drivers could recognize the ``O_EXCL`` open flag. Presently this is
   not required, so applications cannot know if it really works.