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

Linux 6.18.37 · Userspace API / Media / V4L

영상 크롭, 삽입과 스케일링 - CROP API

레거시 CROP API의 capture/output source·target 사각형, 하드웨어 스케일 보정과 pixel aspect 계산 예제를 설명합니다.

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

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

1. 요약·해설

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

요약·해설

crop.rst:1-317

SELECTION API 이전의 crop·삽입·스케일링 계약입니다. capture에서는 crop이 입력 source를, output에서는 삽입 target을 정한다는 방향 차이와, format 사각형과의 협상 우선순위를 구분하는 것이 핵심입니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
2
3 .. _crop:
4
5 *****************************************************
6 Image Cropping, Insertion and Scaling -- the CROP API
7 *****************************************************
8
9 .. note::
10
11 The CROP API is mostly superseded by the newer :ref:`SELECTION API
12 <selection-api>`. The new API should be preferred in most cases,
13 with the exception of pixel aspect ratio detection, which is
14 implemented by :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>` and has no
15 equivalent in the SELECTION API. See :ref:`selection-vs-crop` for a
16 comparison of the two APIs.
17
18 Some video capture devices can sample a subsection of the picture and
19 shrink or enlarge it to an image of arbitrary size. We call these
20 abilities cropping and scaling. Some video output devices can scale an
21 image up or down and insert it at an arbitrary scan line and horizontal
22 offset into a video signal.
23
24 Applications can use the following API to select an area in the video
25 signal, query the default area and the hardware limits.
26
27 .. note::
28
29 Despite their name, the :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>`,
30 :ref:`VIDIOC_G_CROP <VIDIOC_G_CROP>` and :ref:`VIDIOC_S_CROP
31 <VIDIOC_G_CROP>` ioctls apply to input as well as output devices.
32
33 Scaling requires a source and a target. On a video capture or overlay
34 device the source is the video signal, and the cropping ioctls determine
35 the area actually sampled. The target are images read by the application
36 or overlaid onto the graphics screen. Their size (and position for an
37 overlay) is negotiated with the :ref:`VIDIOC_G_FMT <VIDIOC_G_FMT>`
38 and :ref:`VIDIOC_S_FMT <VIDIOC_G_FMT>` ioctls.
39
40 On a video output device the source are the images passed in by the
41 application, and their size is again negotiated with the
42 :ref:`VIDIOC_G_FMT <VIDIOC_G_FMT>` and :ref:`VIDIOC_S_FMT <VIDIOC_G_FMT>`
43 ioctls, or may be encoded in a compressed video stream. The target is
44 the video signal, and the cropping ioctls determine the area where the
45 images are inserted.
46
47 Source and target rectangles are defined even if the device does not
48 support scaling or the :ref:`VIDIOC_G_CROP <VIDIOC_G_CROP>` and
49 :ref:`VIDIOC_S_CROP <VIDIOC_G_CROP>` ioctls. Their size (and position
50 where applicable) will be fixed in this case.
51
52 .. note::
53
54 All capture and output devices that support the CROP or SELECTION
55 API will also support the :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>`
56 ioctl.
57
58 Cropping Structures
59 ===================
60
61
62 .. _crop-scale:
63
64 .. kernel-figure:: crop.svg
65 :alt: crop.svg
66 :align: center
67
68 Image Cropping, Insertion and Scaling
69
70 The cropping, insertion and scaling process
71
72
73
74 For capture devices the coordinates of the top left corner, width and
75 height of the area which can be sampled is given by the ``bounds``
76 substructure of the struct :c:type:`v4l2_cropcap` returned
77 by the :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>` ioctl. To support a wide
78 range of hardware this specification does not define an origin or units.
79 However by convention drivers should horizontally count unscaled samples
80 relative to 0H (the leading edge of the horizontal sync pulse, see
81 :ref:`vbi-hsync`). Vertically ITU-R line numbers of the first field
82 (see ITU R-525 line numbering for :ref:`525 lines <vbi-525>` and for
83 :ref:`625 lines <vbi-625>`), multiplied by two if the driver
84 can capture both fields.
85
86 The top left corner, width and height of the source rectangle, that is
87 the area actually sampled, is given by struct
88 :c:type:`v4l2_crop` using the same coordinate system as
89 struct :c:type:`v4l2_cropcap`. Applications can use the
90 :ref:`VIDIOC_G_CROP <VIDIOC_G_CROP>` and :ref:`VIDIOC_S_CROP <VIDIOC_G_CROP>`
91 ioctls to get and set this rectangle. It must lie completely within the
92 capture boundaries and the driver may further adjust the requested size
93 and/or position according to hardware limitations.
94
95 Each capture device has a default source rectangle, given by the
96 ``defrect`` substructure of struct
97 :c:type:`v4l2_cropcap`. The center of this rectangle
98 shall align with the center of the active picture area of the video
99 signal, and cover what the driver writer considers the complete picture.
100 Drivers shall reset the source rectangle to the default when the driver
101 is first loaded, but not later.
102
103 For output devices these structures and ioctls are used accordingly,
104 defining the *target* rectangle where the images will be inserted into
105 the video signal.
106
107
108 Scaling Adjustments
109 ===================
110
111 Video hardware can have various cropping, insertion and scaling
112 limitations. It may only scale up or down, support only discrete scaling
113 factors, or have different scaling abilities in horizontal and vertical
114 direction. Also it may not support scaling at all. At the same time the
115 struct :c:type:`v4l2_crop` rectangle may have to be aligned,
116 and both the source and target rectangles may have arbitrary upper and
117 lower size limits. In particular the maximum ``width`` and ``height`` in
118 struct :c:type:`v4l2_crop` may be smaller than the struct
119 :c:type:`v4l2_cropcap`. ``bounds`` area. Therefore, as
120 usual, drivers are expected to adjust the requested parameters and
121 return the actual values selected.
122
123 Applications can change the source or the target rectangle first, as
124 they may prefer a particular image size or a certain area in the video
125 signal. If the driver has to adjust both to satisfy hardware
126 limitations, the last requested rectangle shall take priority, and the
127 driver should preferably adjust the opposite one. The
128 :ref:`VIDIOC_TRY_FMT <VIDIOC_G_FMT>` ioctl however shall not change
129 the driver state and therefore only adjust the requested rectangle.
130
131 Suppose scaling on a video capture device is restricted to a factor 1:1
132 or 2:1 in either direction and the target image size must be a multiple
133 of 16 × 16 pixels. The source cropping rectangle is set to defaults,
134 which are also the upper limit in this example, of 640 × 400 pixels at
135 offset 0, 0. An application requests an image size of 300 × 225 pixels,
136 assuming video will be scaled down from the "full picture" accordingly.
137 The driver sets the image size to the closest possible values 304 × 224,
138 then chooses the cropping rectangle closest to the requested size, that
139 is 608 × 224 (224 × 2:1 would exceed the limit 400). The offset 0, 0 is
140 still valid, thus unmodified. Given the default cropping rectangle
141 reported by :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>` the application can
142 easily propose another offset to center the cropping rectangle.
143
144 Now the application may insist on covering an area using a picture
145 aspect ratio closer to the original request, so it asks for a cropping
146 rectangle of 608 × 456 pixels. The present scaling factors limit
147 cropping to 640 × 384, so the driver returns the cropping size 608 × 384
148 and adjusts the image size to closest possible 304 × 192.
149
150
151 Examples
152 ========
153
154 Source and target rectangles shall remain unchanged across closing and
155 reopening a device, such that piping data into or out of a device will
156 work without special preparations. More advanced applications should
157 ensure the parameters are suitable before starting I/O.
158
159 .. note::
160
161 On the next two examples, a video capture device is assumed;
162 change ``V4L2_BUF_TYPE_VIDEO_CAPTURE`` for other types of device.
163
164 Example: Resetting the cropping parameters
165 ==========================================
166
167 .. code-block:: c
168
169 struct v4l2_cropcap cropcap;
170 struct v4l2_crop crop;
171
172 memset (&cropcap, 0, sizeof (cropcap));
173 cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
174
175 if (-1 == ioctl (fd, VIDIOC_CROPCAP, &cropcap)) {
176 perror ("VIDIOC_CROPCAP");
177 exit (EXIT_FAILURE);
178 }
179
180 memset (&crop, 0, sizeof (crop));
181 crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
182 crop.c = cropcap.defrect;
183
184 /* Ignore if cropping is not supported (EINVAL). */
185
186 if (-1 == ioctl (fd, VIDIOC_S_CROP, &crop)
187 && errno != EINVAL) {
188 perror ("VIDIOC_S_CROP");
189 exit (EXIT_FAILURE);
190 }
191
192
193 Example: Simple downscaling
194 ===========================
195
196 .. code-block:: c
197
198 struct v4l2_cropcap cropcap;
199 struct v4l2_format format;
200
201 reset_cropping_parameters ();
202
203 /* Scale down to 1/4 size of full picture. */
204
205 memset (&format, 0, sizeof (format)); /* defaults */
206
207 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
208
209 format.fmt.pix.width = cropcap.defrect.width >> 1;
210 format.fmt.pix.height = cropcap.defrect.height >> 1;
211 format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
212
213 if (-1 == ioctl (fd, VIDIOC_S_FMT, &format)) {
214 perror ("VIDIOC_S_FORMAT");
215 exit (EXIT_FAILURE);
216 }
217
218 /* We could check the actual image size now, the actual scaling factor
219 or if the driver can scale at all. */
220
221 Example: Selecting an output area
222 =================================
223
224 .. note:: This example assumes an output device.
225
226 .. code-block:: c
227
228 struct v4l2_cropcap cropcap;
229 struct v4l2_crop crop;
230
231 memset (&cropcap, 0, sizeof (cropcap));
232 cropcap.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
233
234 if (-1 == ioctl (fd, VIDIOC_CROPCAP;, &cropcap)) {
235 perror ("VIDIOC_CROPCAP");
236 exit (EXIT_FAILURE);
237 }
238
239 memset (&crop, 0, sizeof (crop));
240
241 crop.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
242 crop.c = cropcap.defrect;
243
244 /* Scale the width and height to 50 % of their original size
245 and center the output. */
246
247 crop.c.width /= 2;
248 crop.c.height /= 2;
249 crop.c.left += crop.c.width / 2;
250 crop.c.top += crop.c.height / 2;
251
252 /* Ignore if cropping is not supported (EINVAL). */
253
254 if (-1 == ioctl (fd, VIDIOC_S_CROP, &crop)
255 && errno != EINVAL) {
256 perror ("VIDIOC_S_CROP");
257 exit (EXIT_FAILURE);
258 }
259
260 Example: Current scaling factor and pixel aspect
261 ================================================
262
263 .. note:: This example assumes a video capture device.
264
265 .. code-block:: c
266
267 struct v4l2_cropcap cropcap;
268 struct v4l2_crop crop;
269 struct v4l2_format format;
270 double hscale, vscale;
271 double aspect;
272 int dwidth, dheight;
273
274 memset (&cropcap, 0, sizeof (cropcap));
275 cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
276
277 if (-1 == ioctl (fd, VIDIOC_CROPCAP, &cropcap)) {
278 perror ("VIDIOC_CROPCAP");
279 exit (EXIT_FAILURE);
280 }
281
282 memset (&crop, 0, sizeof (crop));
283 crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
284
285 if (-1 == ioctl (fd, VIDIOC_G_CROP, &crop)) {
286 if (errno != EINVAL) {
287 perror ("VIDIOC_G_CROP");
288 exit (EXIT_FAILURE);
289 }
290
291 /* Cropping not supported. */
292 crop.c = cropcap.defrect;
293 }
294
295 memset (&format, 0, sizeof (format));
296 format.fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
297
298 if (-1 == ioctl (fd, VIDIOC_G_FMT, &format)) {
299 perror ("VIDIOC_G_FMT");
300 exit (EXIT_FAILURE);
301 }
302
303 /* The scaling applied by the driver. */
304
305 hscale = format.fmt.pix.width / (double) crop.c.width;
306 vscale = format.fmt.pix.height / (double) crop.c.height;
307
308 aspect = cropcap.pixelaspect.numerator /
309 (double) cropcap.pixelaspect.denominator;
310 aspect = aspect * hscale / vscale;
311
312 /* Devices following ITU-R BT.601 do not capture
313 square pixels. For playback on a computer monitor
314 we should scale the images to this size. */
315
316 dwidth = format.fmt.pix.width / aspect;
317 dheight = format.fmt.pix.height;
318

3. 한국어 전문 번역

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

CROP API의 범위와 source/target

1-57

레거시 CROP API는 대부분 더 새로운 `SELECTION API`로 대체됐으므로 일반적으로 새 API를 우선해야 합니다. 예외는 `VIDIOC_CROPCAP`으로 얻는 pixel aspect ratio이며 SELECTION API에는 대응 기능이 없습니다. 두 API 비교는 `selection-vs-crop` 절에서 다룹니다.

일부 캡처 장치는 입력 영상의 일부 영역만 샘플링하고 임의 크기로 축소·확대할 수 있습니다. 출력 장치는 애플리케이션 영상을 확대·축소해 비디오 신호의 임의 scan line과 수평 오프셋에 삽입할 수 있습니다.

애플리케이션은 CROP API로 비디오 신호의 영역을 선택하고 기본 영역과 하드웨어 한계를 조회합니다. 이름과 달리 `VIDIOC_CROPCAP`, `VIDIOC_G_CROP`, `VIDIOC_S_CROP`은 입력과 출력 장치 모두에 적용됩니다.

capture와 output의 source/target
항목설명
Capture source비디오 신호에서 실제로 샘플링하는 crop 영역
Capture target애플리케이션이 읽거나 overlay하는 영상, G_FMT/S_FMT로 크기·위치 협상
Output source애플리케이션이 전달한 영상 또는 압축 스트림, G_FMT/S_FMT로 크기 협상
Output target비디오 신호 안에 영상을 삽입할 crop 영역

스케일링 방향에 따라 crop 사각형의 역할이 반대가 됩니다.

캡처 또는 overlay에서는 crop ioctl이 source 영역을 정하고 format ioctl이 target 영상 크기와 overlay 위치를 정합니다. 출력에서는 format이 source 영상 크기를, crop이 신호 속 삽입 target을 정합니다.

장치가 스케일링이나 G_CROP/S_CROP을 지원하지 않아도 source와 target 사각형은 개념적으로 존재하며 이때 크기와 필요한 위치는 고정됩니다. CROP 또는 SELECTION을 지원하는 모든 capture/output 장치는 CROPCAP도 지원해야 합니다.

CROP API 스케일링 관계
Capture: 비디오 신호의 source crop 선택Capture: 선택 영역을 format 크기의 target 영상으로 스케일Output: format 크기의 source 영상을 입력Output: crop으로 정한 비디오 신호 target에 스케일·삽입

입력 신호와 애플리케이션 영상 사이의 변환 방향입니다.

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

.. _crop:

*****************************************************
Image Cropping, Insertion and Scaling -- the CROP API
*****************************************************

.. note::

   The CROP API is mostly superseded by the newer :ref:`SELECTION API
   <selection-api>`. The new API should be preferred in most cases,
   with the exception of pixel aspect ratio detection, which is
   implemented by :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>` and has no
   equivalent in the SELECTION API. See :ref:`selection-vs-crop` for a
   comparison of the two APIs.

Some video capture devices can sample a subsection of the picture and
shrink or enlarge it to an image of arbitrary size. We call these
abilities cropping and scaling. Some video output devices can scale an
image up or down and insert it at an arbitrary scan line and horizontal
offset into a video signal.

Applications can use the following API to select an area in the video
signal, query the default area and the hardware limits.

.. note::

   Despite their name, the :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>`,
   :ref:`VIDIOC_G_CROP <VIDIOC_G_CROP>` and :ref:`VIDIOC_S_CROP
   <VIDIOC_G_CROP>` ioctls apply to input as well as output devices.

Scaling requires a source and a target. On a video capture or overlay
device the source is the video signal, and the cropping ioctls determine
the area actually sampled. The target are images read by the application
or overlaid onto the graphics screen. Their size (and position for an
overlay) is negotiated with the :ref:`VIDIOC_G_FMT <VIDIOC_G_FMT>`
and :ref:`VIDIOC_S_FMT <VIDIOC_G_FMT>` ioctls.

On a video output device the source are the images passed in by the
application, and their size is again negotiated with the
:ref:`VIDIOC_G_FMT <VIDIOC_G_FMT>` and :ref:`VIDIOC_S_FMT <VIDIOC_G_FMT>`
ioctls, or may be encoded in a compressed video stream. The target is
the video signal, and the cropping ioctls determine the area where the
images are inserted.

Source and target rectangles are defined even if the device does not
support scaling or the :ref:`VIDIOC_G_CROP <VIDIOC_G_CROP>` and
:ref:`VIDIOC_S_CROP <VIDIOC_G_CROP>` ioctls. Their size (and position
where applicable) will be fixed in this case.

.. note::

   All capture and output devices that support the CROP or SELECTION
   API will also support the :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>`
   ioctl.

crop 구조체, 좌표와 기본 사각형

58-107

원문의 `crop.svg` 그림은 capture에서 신호의 일부를 잘라 target 영상으로 스케일하고, output에서는 source 영상을 target 사각형에 삽입하는 과정을 함께 나타냅니다.

CROP 구조와 사각형
항목설명
v4l2_cropcap.bounds캡처에서 샘플링 가능한 전체 좌표 범위 또는 출력 삽입 가능 범위
v4l2_cropcap.defrect드라이버가 정의한 기본 source 또는 target 사각형
v4l2_cropcap.pixelaspectpixel aspect ratio, SELECTION API에 없는 CROPCAP 고유 정보
v4l2_crop.cG_CROP/S_CROP으로 읽고 쓰는 현재 사각형
v4l2_crop.typeVIDEO_CAPTURE나 VIDEO_OUTPUT 등 대상 buffer type
v4l2_rectleft, top, width, height로 사각형 표현

CROPCAP과 CROP이 제공하는 범위·기본값·현재값입니다.

캡처 `bounds`의 원점과 단위는 다양한 하드웨어를 수용하기 위해 규격이 강제하지 않습니다. 관례적으로 수평 좌표는 horizontal sync pulse 선두인 0H에 대한 unscaled sample 수를 사용합니다.

수직 좌표는 첫 field의 ITU-R line number를 사용하고, 두 field를 모두 캡처할 수 있는 드라이버는 그 값에 2를 곱합니다. 525선과 625선 체계의 번호 규칙은 각각 관련 VBI 절을 참조합니다.

현재 source 사각형은 CROPCAP과 같은 좌표계의 `struct v4l2_crop`으로 표현하며 완전히 bounds 안에 있어야 합니다. 드라이버는 정렬과 하드웨어 제한에 맞춰 요청한 위치·크기를 추가 보정할 수 있습니다.

`defrect`의 중심은 비디오 신호 active picture 영역 중심과 맞아야 하고 드라이버 작성자가 완전한 영상으로 판단하는 영역을 덮습니다. 드라이버는 최초 로드 때 source를 기본값으로 초기화하되 이후에는 자동으로 되돌리지 않습니다. 출력 장치에서는 같은 구조가 삽입 target을 정의합니다.

캡처 사각형 계층
VIDIOC_CROPCAP으로 bounds와 defrect 조회bounds 좌표계와 pixelaspect 해석defrect에서 장치의 기본 전체 영상 확인VIDIOC_G_CROP으로 현재 source 확인VIDIOC_S_CROP 요청을 bounds·정렬·크기 제한에 맞춰 드라이버가 보정

전체 가능 범위에서 기본값과 실제 선택값이 정해집니다.

Cropping Structures
===================


.. _crop-scale:

.. kernel-figure:: crop.svg
    :alt:    crop.svg
    :align:  center

    Image Cropping, Insertion and Scaling

    The cropping, insertion and scaling process



For capture devices the coordinates of the top left corner, width and
height of the area which can be sampled is given by the ``bounds``
substructure of the struct :c:type:`v4l2_cropcap` returned
by the :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>` ioctl. To support a wide
range of hardware this specification does not define an origin or units.
However by convention drivers should horizontally count unscaled samples
relative to 0H (the leading edge of the horizontal sync pulse, see
:ref:`vbi-hsync`). Vertically ITU-R line numbers of the first field
(see ITU R-525 line numbering for :ref:`525 lines <vbi-525>` and for
:ref:`625 lines <vbi-625>`), multiplied by two if the driver
can capture both fields.

The top left corner, width and height of the source rectangle, that is
the area actually sampled, is given by struct
:c:type:`v4l2_crop` using the same coordinate system as
struct :c:type:`v4l2_cropcap`. Applications can use the
:ref:`VIDIOC_G_CROP <VIDIOC_G_CROP>` and :ref:`VIDIOC_S_CROP <VIDIOC_G_CROP>`
ioctls to get and set this rectangle. It must lie completely within the
capture boundaries and the driver may further adjust the requested size
and/or position according to hardware limitations.

Each capture device has a default source rectangle, given by the
``defrect`` substructure of struct
:c:type:`v4l2_cropcap`. The center of this rectangle
shall align with the center of the active picture area of the video
signal, and cover what the driver writer considers the complete picture.
Drivers shall reset the source rectangle to the default when the driver
is first loaded, but not later.

For output devices these structures and ioctls are used accordingly,
defining the *target* rectangle where the images will be inserted into
the video signal.

스케일링 제한과 사각형 보정 우선순위

108-150

하드웨어는 확대만 또는 축소만 가능하거나, 불연속 스케일 계수만 지원하거나, 수평·수직 능력이 다를 수 있습니다. 스케일링을 전혀 지원하지 않는 장치도 있습니다.

대표 하드웨어 제약
항목설명
방향확대 전용, 축소 전용 또는 양방향
배율1:1, 2:1 같은 불연속 계수
축별 능력수평과 수직의 서로 다른 스케일 범위
정렬left, top, width, height의 픽셀 배수 요구
크기source와 target의 독립적인 상·하한

드라이버가 요청 사각형과 형식을 보정하는 이유입니다.

`v4l2_crop` 사각형 자체에 정렬 조건이 있을 수 있고 source와 target 모두 임의 상·하한을 가질 수 있습니다. 특히 crop의 최대 width/height가 CROPCAP `bounds`보다 작을 수 있으므로 드라이버는 실제 선택값을 반환해야 합니다.

애플리케이션은 원하는 영상 크기 또는 신호 영역의 우선순위에 따라 source와 target 중 어느 쪽이든 먼저 설정할 수 있습니다. 두 값을 함께 조정해야 한다면 마지막에 요청한 사각형을 우선하고 반대쪽을 보정하는 것이 원칙입니다. `VIDIOC_TRY_FMT`은 상태를 바꾸지 않으므로 전달된 요청 사각형만 보정합니다.

제약 예제의 두 요청
항목설명
Target 300x225 요청target 304x224, source 608x224, offset 0,0
Source 608x456 요청source 608x384, target 304x192

1:1·2:1 배율과 16x16 target 정렬에서 드라이버가 선택한 결과입니다.

첫 예제의 기본 source 상한은 offset 0,0의 640x400입니다. 요청 target 300x225는 가장 가까운 16픽셀 배수 304x224가 되고, 2:1 수평 축소와 source 높이 상한을 만족하는 crop은 608x224가 됩니다. 224를 수직으로 두 배 한 448은 상한 400을 넘기 때문에 수직은 1:1입니다.

애플리케이션이 원래 aspect ratio에 더 가까운 source 608x456을 다시 요구하면 하드웨어 제한이 이를 608x384로 만들고 target도 304x192로 조정됩니다. 마지막 source 요청이 우선된 결과입니다.

상충하는 source/target 요청 해결
요청한 source 또는 target을 정렬 단위에 맞춤지원하는 수평·수직 배율 후보 계산bounds와 source/target 크기 상한 검사마지막 요청 사각형에 가장 가까운 유효값 선택반대쪽 사각형을 선택한 배율에 맞춰 조정실제 선택된 두 사각형을 애플리케이션에 반환

마지막 요청을 보존하며 반대 사각형을 조정합니다.

Scaling Adjustments
===================

Video hardware can have various cropping, insertion and scaling
limitations. It may only scale up or down, support only discrete scaling
factors, or have different scaling abilities in horizontal and vertical
direction. Also it may not support scaling at all. At the same time the
struct :c:type:`v4l2_crop` rectangle may have to be aligned,
and both the source and target rectangles may have arbitrary upper and
lower size limits. In particular the maximum ``width`` and ``height`` in
struct :c:type:`v4l2_crop` may be smaller than the struct
:c:type:`v4l2_cropcap`. ``bounds`` area. Therefore, as
usual, drivers are expected to adjust the requested parameters and
return the actual values selected.

Applications can change the source or the target rectangle first, as
they may prefer a particular image size or a certain area in the video
signal. If the driver has to adjust both to satisfy hardware
limitations, the last requested rectangle shall take priority, and the
driver should preferably adjust the opposite one. The
:ref:`VIDIOC_TRY_FMT <VIDIOC_G_FMT>` ioctl however shall not change
the driver state and therefore only adjust the requested rectangle.

Suppose scaling on a video capture device is restricted to a factor 1:1
or 2:1 in either direction and the target image size must be a multiple
of 16 × 16 pixels. The source cropping rectangle is set to defaults,
which are also the upper limit in this example, of 640 × 400 pixels at
offset 0, 0. An application requests an image size of 300 × 225 pixels,
assuming video will be scaled down from the "full picture" accordingly.
The driver sets the image size to the closest possible values 304 × 224,
then chooses the cropping rectangle closest to the requested size, that
is 608 × 224 (224 × 2:1 would exceed the limit 400). The offset 0, 0 is
still valid, thus unmodified. Given the default cropping rectangle
reported by :ref:`VIDIOC_CROPCAP <VIDIOC_CROPCAP>` the application can
easily propose another offset to center the cropping rectangle.

Now the application may insist on covering an area using a picture
aspect ratio closer to the original request, so it asks for a cropping
rectangle of 608 × 456 pixels. The present scaling factors limit
cropping to 640 × 384, so the driver returns the cropping size 608 × 384
and adjusts the image size to closest possible 304 × 192.

crop 상태 유지와 기본값 복원 예제

151-192

source와 target 사각형은 장치를 닫았다 다시 열어도 유지되어야 합니다. 따라서 단순 파이프 방식 I/O는 특별한 준비 없이 동작하지만, 고급 애플리케이션은 I/O 시작 전에 현재 파라미터가 적합한지 확인해야 합니다.

기본값 복원 예제는 VIDEO_CAPTURE 형식으로 CROPCAP을 조회하고 `crop.c = cropcap.defrect`를 설정한 뒤 S_CROP을 호출합니다. 크롭 미지원의 `EINVAL`만 무시하고 다른 오류는 실패로 처리합니다.

다른 장치 유형에 적용하려면 `V4L2_BUF_TYPE_VIDEO_CAPTURE`를 해당 buffer type으로 바꿔야 합니다.

기본 crop 복원
v4l2_cropcap과 v4l2_crop을 0으로 초기화type을 V4L2_BUF_TYPE_VIDEO_CAPTURE로 설정VIDIOC_CROPCAP으로 defrect 조회crop.c에 defrect 복사VIDIOC_S_CROP 호출, EINVAL만 미지원으로 무시

드라이버가 보고한 defrect를 현재 사각형에 적용합니다.

Examples
========

Source and target rectangles shall remain unchanged across closing and
reopening a device, such that piping data into or out of a device will
work without special preparations. More advanced applications should
ensure the parameters are suitable before starting I/O.

.. note::

   On the next two examples, a video capture device is assumed;
   change ``V4L2_BUF_TYPE_VIDEO_CAPTURE`` for other types of device.

Example: Resetting the cropping parameters
==========================================

.. code-block:: c

    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;

    memset (&cropcap, 0, sizeof (cropcap));
    cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == ioctl (fd, VIDIOC_CROPCAP, &cropcap)) {
	perror ("VIDIOC_CROPCAP");
	exit (EXIT_FAILURE);
    }

    memset (&crop, 0, sizeof (crop));
    crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    crop.c = cropcap.defrect;

    /* Ignore if cropping is not supported (EINVAL). */

    if (-1 == ioctl (fd, VIDIOC_S_CROP, &crop)
	&& errno != EINVAL) {
	perror ("VIDIOC_S_CROP");
	exit (EXIT_FAILURE);
    }

단순 1/4 면적 축소 예제

193-220

단순 축소 예제는 먼저 crop 파라미터를 기본값으로 되돌리고 VIDEO_CAPTURE format을 준비합니다.

width와 height를 각각 `defrect.width >> 1`, `defrect.height >> 1`로 설정하여 가로·세로를 절반으로 줄이고 면적을 1/4로 만듭니다. 픽셀 형식은 `V4L2_PIX_FMT_YUYV`입니다.

`VIDIOC_S_FMT` 뒤에는 드라이버가 실제로 선택한 영상 크기와 배율, 스케일링 가능 여부를 반환 구조체에서 다시 확인할 수 있습니다.

단순 downscale
crop을 defrect로 복원target width와 height를 각각 절반으로 요청YUYV 픽셀 형식 지정VIDIOC_S_FMT 후 실제 반환 크기 확인

기본 source 전체를 절반 크기 target으로 협상합니다.

Example: Simple downscaling
===========================

.. code-block:: c

    struct v4l2_cropcap cropcap;
    struct v4l2_format format;

    reset_cropping_parameters ();

    /* Scale down to 1/4 size of full picture. */

    memset (&format, 0, sizeof (format)); /* defaults */

    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    format.fmt.pix.width = cropcap.defrect.width >> 1;
    format.fmt.pix.height = cropcap.defrect.height >> 1;
    format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;

    if (-1 == ioctl (fd, VIDIOC_S_FMT, &format)) {
	perror ("VIDIOC_S_FORMAT");
	exit (EXIT_FAILURE);
    }

    /* We could check the actual image size now, the actual scaling factor
       or if the driver can scale at all. */

출력 삽입 영역 선택 예제

221-259

출력 예제는 `V4L2_BUF_TYPE_VIDEO_OUTPUT`으로 CROPCAP의 기본 target 사각형을 조회합니다.

기본 사각형의 width와 height를 절반으로 나누고, 줄어든 폭·높이의 절반만큼 left와 top을 증가시켜 원래 영역 중앙에 50% 크기의 출력을 배치합니다.

계산한 target은 S_CROP으로 설정하며 크롭 미지원 `EINVAL`만 무시합니다. 이 절에서 crop은 잘라낼 capture source가 아니라 비디오 신호 속 출력 삽입 영역입니다.

로컬 v6.18.37 원문의 호출은 `VIDIOC_CROPCAP;`처럼 세미콜론이 포함된 표기를 사용합니다. 원문과 줄 좌표는 그대로 보존했으며, 실제 C 코드로 사용할 때는 ioctl 요청 상수 `VIDIOC_CROPCAP`을 사용해야 합니다.

출력 중앙 삽입
VIDEO_OUTPUT CROPCAP으로 defrect 조회width와 height를 각각 2로 나눔left에 새 width/2를 더함top에 새 height/2를 더함VIDIOC_S_CROP으로 target 설정

기본 target의 중앙에 절반 크기 영상을 놓습니다.

Example: Selecting an output area
=================================

.. note:: This example assumes an output device.

.. code-block:: c

    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;

    memset (&cropcap, 0, sizeof (cropcap));
    cropcap.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;

    if (-1 == ioctl (fd, VIDIOC_CROPCAP;, &cropcap)) {
	perror ("VIDIOC_CROPCAP");
	exit (EXIT_FAILURE);
    }

    memset (&crop, 0, sizeof (crop));

    crop.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    crop.c = cropcap.defrect;

    /* Scale the width and height to 50 % of their original size
       and center the output. */

    crop.c.width /= 2;
    crop.c.height /= 2;
    crop.c.left += crop.c.width / 2;
    crop.c.top += crop.c.height / 2;

    /* Ignore if cropping is not supported (EINVAL). */

    if (-1 == ioctl (fd, VIDIOC_S_CROP, &crop)
	&& errno != EINVAL) {
	perror ("VIDIOC_S_CROP");
	exit (EXIT_FAILURE);
    }

현재 배율과 pixel aspect 계산

260-317

마지막 예제는 VIDEO_CAPTURE 장치에서 CROPCAP, 현재 crop, 현재 format을 조회해 드라이버가 적용한 수평·수직 배율과 표시용 pixel aspect를 계산합니다.

G_CROP이 크롭 미지원 `EINVAL`을 반환하면 현재 crop 대신 `cropcap.defrect`를 사용합니다. 다른 오류는 치명적으로 처리합니다.

배율과 표시 크기 식
항목설명
hscaleformat.fmt.pix.width / crop.c.width
vscaleformat.fmt.pix.height / crop.c.height
기본 aspectpixelaspect.numerator / pixelaspect.denominator
스케일 반영 aspect기본 aspect * hscale / vscale
표시 크기dwidth = target width / aspect, dheight = target height

source crop, target format과 pixel aspect의 결합입니다.

ITU-R BT.601 계열 장치는 정사각 픽셀을 캡처하지 않으므로 컴퓨터 모니터에 표시할 때 계산한 aspect를 사용해 가로 크기를 조정해야 합니다.

로컬 원문은 format type 대입을 `format.fmt.type`으로 표기합니다. 원문은 변경하지 않았으며, 실제 `struct v4l2_format` 사용 시 type 필드 위치를 헤더 정의와 대조해야 합니다.

표시용 aspect 계산
VIDIOC_CROPCAP으로 pixelaspect 조회VIDIOC_G_CROP 또는 defrect로 source 크기 결정VIDIOC_G_FMT로 target 영상 크기 조회hscale과 vscale 계산pixelaspect*hscale/vscale로 최종 aspect와 표시 폭 계산

아날로그 신호의 pixel aspect와 드라이버 스케일을 함께 반영합니다.

Example: Current scaling factor and pixel aspect
================================================

.. note:: This example assumes a video capture device.

.. code-block:: c

    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;
    struct v4l2_format format;
    double hscale, vscale;
    double aspect;
    int dwidth, dheight;

    memset (&cropcap, 0, sizeof (cropcap));
    cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == ioctl (fd, VIDIOC_CROPCAP, &cropcap)) {
	perror ("VIDIOC_CROPCAP");
	exit (EXIT_FAILURE);
    }

    memset (&crop, 0, sizeof (crop));
    crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == ioctl (fd, VIDIOC_G_CROP, &crop)) {
	if (errno != EINVAL) {
	    perror ("VIDIOC_G_CROP");
	    exit (EXIT_FAILURE);
	}

	/* Cropping not supported. */
	crop.c = cropcap.defrect;
    }

    memset (&format, 0, sizeof (format));
    format.fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (-1 == ioctl (fd, VIDIOC_G_FMT, &format)) {
	perror ("VIDIOC_G_FMT");
	exit (EXIT_FAILURE);
    }

    /* The scaling applied by the driver. */

    hscale = format.fmt.pix.width / (double) crop.c.width;
    vscale = format.fmt.pix.height / (double) crop.c.height;

    aspect = cropcap.pixelaspect.numerator /
	 (double) cropcap.pixelaspect.denominator;
    aspect = aspect * hscale / vscale;

    /* Devices following ITU-R BT.601 do not capture
       square pixels. For playback on a computer monitor
       we should scale the images to this size. */

    dwidth = format.fmt.pix.width / aspect;
    dheight = format.fmt.pix.height;