032fd69bd902fdedd32c998f4dd190d4ffed163e
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / sys / v4l2 / gstv4l2object.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@gmail.com>
5  *
6  * gstv4l2object.c: base class for V4L2 elements
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Library General Public License as published
10  * by the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version. This library is distributed in the hope
12  * that it will be useful, but WITHOUT ANY WARRANTY; without even the
13  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14  * PURPOSE.  See the GNU Library General Public License for more details.
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
18  * USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <sys/mman.h>
30 #include <sys/ioctl.h>
31
32
33 #ifdef HAVE_GUDEV
34 #include <gudev/gudev.h>
35 #endif
36
37 #include "ext/videodev2.h"
38 #include "gstv4l2object.h"
39 #include "gstv4l2tuner.h"
40 #include "gstv4l2colorbalance.h"
41
42 #include <glib/gi18n-lib.h>
43
44 #include <gst/video/video.h>
45 #include <gst/allocators/gstdmabuf.h>
46
47 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
48 #define GST_CAT_DEFAULT v4l2_debug
49
50 #define DEFAULT_PROP_DEVICE_NAME        NULL
51 #define DEFAULT_PROP_DEVICE_FD          -1
52 #define DEFAULT_PROP_FLAGS              0
53 #define DEFAULT_PROP_TV_NORM            0
54 #define DEFAULT_PROP_IO_MODE            GST_V4L2_IO_AUTO
55
56 #define ENCODED_BUFFER_SIZE             (2 * 1024 * 1024)
57 #define GST_V4L2_DEFAULT_WIDTH          320
58 #define GST_V4L2_DEFAULT_HEIGHT         240
59
60 enum
61 {
62   PROP_0,
63   V4L2_STD_OBJECT_PROPS,
64 };
65
66 /*
67  * common format / caps utilities:
68  */
69 typedef enum
70 {
71   GST_V4L2_RAW = 1 << 0,
72   GST_V4L2_CODEC = 1 << 1,
73   GST_V4L2_TRANSPORT = 1 << 2,
74   GST_V4L2_NO_PARSE = 1 << 3,
75   GST_V4L2_ALL = 0xffff
76 } GstV4L2FormatFlags;
77
78 typedef struct
79 {
80   guint32 format;
81   gboolean dimensions;
82   GstV4L2FormatFlags flags;
83 } GstV4L2FormatDesc;
84
85 static const GstV4L2FormatDesc gst_v4l2_formats[] = {
86   /* RGB formats */
87   {V4L2_PIX_FMT_RGB332, TRUE, GST_V4L2_RAW},
88   {V4L2_PIX_FMT_ARGB555, TRUE, GST_V4L2_RAW},
89   {V4L2_PIX_FMT_XRGB555, TRUE, GST_V4L2_RAW},
90   {V4L2_PIX_FMT_ARGB555X, TRUE, GST_V4L2_RAW},
91   {V4L2_PIX_FMT_XRGB555X, TRUE, GST_V4L2_RAW},
92   {V4L2_PIX_FMT_RGB565, TRUE, GST_V4L2_RAW},
93   {V4L2_PIX_FMT_RGB565X, TRUE, GST_V4L2_RAW},
94   {V4L2_PIX_FMT_BGR666, TRUE, GST_V4L2_RAW},
95   {V4L2_PIX_FMT_BGR24, TRUE, GST_V4L2_RAW},
96   {V4L2_PIX_FMT_RGB24, TRUE, GST_V4L2_RAW},
97   {V4L2_PIX_FMT_ABGR32, TRUE, GST_V4L2_RAW},
98   {V4L2_PIX_FMT_XBGR32, TRUE, GST_V4L2_RAW},
99   {V4L2_PIX_FMT_BGRA32, TRUE, GST_V4L2_RAW},
100   {V4L2_PIX_FMT_BGRX32, TRUE, GST_V4L2_RAW},
101   {V4L2_PIX_FMT_RGBA32, TRUE, GST_V4L2_RAW},
102   {V4L2_PIX_FMT_RGBX32, TRUE, GST_V4L2_RAW},
103   {V4L2_PIX_FMT_ARGB32, TRUE, GST_V4L2_RAW},
104   {V4L2_PIX_FMT_XRGB32, TRUE, GST_V4L2_RAW},
105
106   /* Deprecated Packed RGB Image Formats (alpha ambiguity) */
107   {V4L2_PIX_FMT_RGB444, TRUE, GST_V4L2_RAW},
108   {V4L2_PIX_FMT_RGB555, TRUE, GST_V4L2_RAW},
109   {V4L2_PIX_FMT_RGB555X, TRUE, GST_V4L2_RAW},
110   {V4L2_PIX_FMT_BGR32, TRUE, GST_V4L2_RAW},
111   {V4L2_PIX_FMT_RGB32, TRUE, GST_V4L2_RAW},
112
113   /* Grey formats */
114   {V4L2_PIX_FMT_GREY, TRUE, GST_V4L2_RAW},
115   {V4L2_PIX_FMT_Y4, TRUE, GST_V4L2_RAW},
116   {V4L2_PIX_FMT_Y6, TRUE, GST_V4L2_RAW},
117   {V4L2_PIX_FMT_Y10, TRUE, GST_V4L2_RAW},
118   {V4L2_PIX_FMT_Y12, TRUE, GST_V4L2_RAW},
119   {V4L2_PIX_FMT_Y16, TRUE, GST_V4L2_RAW},
120   {V4L2_PIX_FMT_Y16_BE, TRUE, GST_V4L2_RAW},
121   {V4L2_PIX_FMT_Y10BPACK, TRUE, GST_V4L2_RAW},
122
123   /* Palette formats */
124   {V4L2_PIX_FMT_PAL8, TRUE, GST_V4L2_RAW},
125
126   /* Chrominance formats */
127   {V4L2_PIX_FMT_UV8, TRUE, GST_V4L2_RAW},
128
129   /* Luminance+Chrominance formats */
130   {V4L2_PIX_FMT_YVU410, TRUE, GST_V4L2_RAW},
131   {V4L2_PIX_FMT_YVU420, TRUE, GST_V4L2_RAW},
132   {V4L2_PIX_FMT_YVU420M, TRUE, GST_V4L2_RAW},
133   {V4L2_PIX_FMT_YUYV, TRUE, GST_V4L2_RAW},
134   {V4L2_PIX_FMT_YYUV, TRUE, GST_V4L2_RAW},
135   {V4L2_PIX_FMT_YVYU, TRUE, GST_V4L2_RAW},
136   {V4L2_PIX_FMT_UYVY, TRUE, GST_V4L2_RAW},
137   {V4L2_PIX_FMT_VYUY, TRUE, GST_V4L2_RAW},
138   {V4L2_PIX_FMT_YUV422P, TRUE, GST_V4L2_RAW},
139   {V4L2_PIX_FMT_YUV411P, TRUE, GST_V4L2_RAW},
140   {V4L2_PIX_FMT_Y41P, TRUE, GST_V4L2_RAW},
141   {V4L2_PIX_FMT_YUV444, TRUE, GST_V4L2_RAW},
142   {V4L2_PIX_FMT_YUV555, TRUE, GST_V4L2_RAW},
143   {V4L2_PIX_FMT_YUV565, TRUE, GST_V4L2_RAW},
144   {V4L2_PIX_FMT_YUV32, TRUE, GST_V4L2_RAW},
145   {V4L2_PIX_FMT_YUV410, TRUE, GST_V4L2_RAW},
146   {V4L2_PIX_FMT_YUV420, TRUE, GST_V4L2_RAW},
147   {V4L2_PIX_FMT_YUV420M, TRUE, GST_V4L2_RAW},
148   {V4L2_PIX_FMT_HI240, TRUE, GST_V4L2_RAW},
149   {V4L2_PIX_FMT_HM12, TRUE, GST_V4L2_RAW},
150   {V4L2_PIX_FMT_M420, TRUE, GST_V4L2_RAW},
151
152   /* two planes -- one Y, one Cr + Cb interleaved  */
153   {V4L2_PIX_FMT_NV12, TRUE, GST_V4L2_RAW},
154   {V4L2_PIX_FMT_NV12M, TRUE, GST_V4L2_RAW},
155   {V4L2_PIX_FMT_NV12MT, TRUE, GST_V4L2_RAW},
156   {V4L2_PIX_FMT_NV12MT_16X16, TRUE, GST_V4L2_RAW},
157   {V4L2_PIX_FMT_NV12M_8L128, TRUE, GST_V4L2_RAW},
158   {V4L2_PIX_FMT_NV12M_10BE_8L128, TRUE, GST_V4L2_RAW},
159   {V4L2_PIX_FMT_NV21, TRUE, GST_V4L2_RAW},
160   {V4L2_PIX_FMT_NV21M, TRUE, GST_V4L2_RAW},
161   {V4L2_PIX_FMT_NV16, TRUE, GST_V4L2_RAW},
162   {V4L2_PIX_FMT_NV16M, TRUE, GST_V4L2_RAW},
163   {V4L2_PIX_FMT_NV61, TRUE, GST_V4L2_RAW},
164   {V4L2_PIX_FMT_NV61M, TRUE, GST_V4L2_RAW},
165   {V4L2_PIX_FMT_NV24, TRUE, GST_V4L2_RAW},
166   {V4L2_PIX_FMT_NV42, TRUE, GST_V4L2_RAW},
167   {V4L2_PIX_FMT_MM21, TRUE, GST_V4L2_RAW},
168
169   /* Bayer formats - see http://www.siliconimaging.com/RGB%20Bayer.htm */
170   {V4L2_PIX_FMT_SBGGR8, TRUE, GST_V4L2_RAW},
171   {V4L2_PIX_FMT_SGBRG8, TRUE, GST_V4L2_RAW},
172   {V4L2_PIX_FMT_SGRBG8, TRUE, GST_V4L2_RAW},
173   {V4L2_PIX_FMT_SRGGB8, TRUE, GST_V4L2_RAW},
174
175   /* compressed formats */
176   {V4L2_PIX_FMT_MJPEG, FALSE, GST_V4L2_CODEC},
177   {V4L2_PIX_FMT_JPEG, FALSE, GST_V4L2_CODEC},
178   {V4L2_PIX_FMT_PJPG, FALSE, GST_V4L2_CODEC},
179   {V4L2_PIX_FMT_DV, FALSE, GST_V4L2_TRANSPORT},
180   {V4L2_PIX_FMT_MPEG, FALSE, GST_V4L2_TRANSPORT},
181   {V4L2_PIX_FMT_FWHT, FALSE, GST_V4L2_CODEC},
182   {V4L2_PIX_FMT_H264, FALSE, GST_V4L2_CODEC},
183   {V4L2_PIX_FMT_H264_NO_SC, FALSE, GST_V4L2_CODEC},
184   {V4L2_PIX_FMT_H264_MVC, FALSE, GST_V4L2_CODEC},
185   {V4L2_PIX_FMT_HEVC, FALSE, GST_V4L2_CODEC},
186   {V4L2_PIX_FMT_H263, FALSE, GST_V4L2_CODEC},
187   {V4L2_PIX_FMT_MPEG1, FALSE, GST_V4L2_CODEC},
188   {V4L2_PIX_FMT_MPEG2, FALSE, GST_V4L2_CODEC},
189   {V4L2_PIX_FMT_MPEG4, FALSE, GST_V4L2_CODEC},
190   {V4L2_PIX_FMT_XVID, FALSE, GST_V4L2_CODEC},
191   {V4L2_PIX_FMT_VC1_ANNEX_G, FALSE, GST_V4L2_CODEC},
192   {V4L2_PIX_FMT_VC1_ANNEX_L, FALSE, GST_V4L2_CODEC},
193   {V4L2_PIX_FMT_VP8, FALSE, GST_V4L2_CODEC | GST_V4L2_NO_PARSE},
194   {V4L2_PIX_FMT_VP9, FALSE, GST_V4L2_CODEC | GST_V4L2_NO_PARSE},
195
196   /*  Vendor-specific formats   */
197   {V4L2_PIX_FMT_WNVA, TRUE, GST_V4L2_CODEC},
198   {V4L2_PIX_FMT_SN9C10X, TRUE, GST_V4L2_CODEC},
199   {V4L2_PIX_FMT_PWC1, TRUE, GST_V4L2_CODEC},
200   {V4L2_PIX_FMT_PWC2, TRUE, GST_V4L2_CODEC},
201 };
202
203 #define GST_V4L2_FORMAT_COUNT (G_N_ELEMENTS (gst_v4l2_formats))
204
205 static GSList *gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object);
206
207
208 #define GST_TYPE_V4L2_DEVICE_FLAGS (gst_v4l2_device_get_type ())
209 static GType
210 gst_v4l2_device_get_type (void)
211 {
212   static GType v4l2_device_type = 0;
213
214   if (v4l2_device_type == 0) {
215     static const GFlagsValue values[] = {
216       {V4L2_CAP_VIDEO_CAPTURE, "Device supports video capture", "capture"},
217       {V4L2_CAP_VIDEO_OUTPUT, "Device supports video playback", "output"},
218       {V4L2_CAP_VIDEO_OVERLAY, "Device supports video overlay", "overlay"},
219
220       {V4L2_CAP_VBI_CAPTURE, "Device supports the VBI capture", "vbi-capture"},
221       {V4L2_CAP_VBI_OUTPUT, "Device supports the VBI output", "vbi-output"},
222
223       {V4L2_CAP_TUNER, "Device has a tuner or modulator", "tuner"},
224       {V4L2_CAP_AUDIO, "Device has audio inputs or outputs", "audio"},
225
226       {0, NULL, NULL}
227     };
228
229     v4l2_device_type =
230         g_flags_register_static ("GstV4l2DeviceTypeFlags", values);
231   }
232
233   return v4l2_device_type;
234 }
235
236 #define GST_TYPE_V4L2_TV_NORM (gst_v4l2_tv_norm_get_type ())
237 static GType
238 gst_v4l2_tv_norm_get_type (void)
239 {
240   static GType v4l2_tv_norm = 0;
241
242   if (!v4l2_tv_norm) {
243     static const GEnumValue tv_norms[] = {
244       {0, "none", "none"},
245
246       {V4L2_STD_NTSC, "NTSC", "NTSC"},
247       {V4L2_STD_NTSC_M, "NTSC-M", "NTSC-M"},
248       {V4L2_STD_NTSC_M_JP, "NTSC-M-JP", "NTSC-M-JP"},
249       {V4L2_STD_NTSC_M_KR, "NTSC-M-KR", "NTSC-M-KR"},
250       {V4L2_STD_NTSC_443, "NTSC-443", "NTSC-443"},
251
252       {V4L2_STD_PAL, "PAL", "PAL"},
253       {V4L2_STD_PAL_BG, "PAL-BG", "PAL-BG"},
254       {V4L2_STD_PAL_B, "PAL-B", "PAL-B"},
255       {V4L2_STD_PAL_B1, "PAL-B1", "PAL-B1"},
256       {V4L2_STD_PAL_G, "PAL-G", "PAL-G"},
257       {V4L2_STD_PAL_H, "PAL-H", "PAL-H"},
258       {V4L2_STD_PAL_I, "PAL-I", "PAL-I"},
259       {V4L2_STD_PAL_DK, "PAL-DK", "PAL-DK"},
260       {V4L2_STD_PAL_D, "PAL-D", "PAL-D"},
261       {V4L2_STD_PAL_D1, "PAL-D1", "PAL-D1"},
262       {V4L2_STD_PAL_K, "PAL-K", "PAL-K"},
263       {V4L2_STD_PAL_M, "PAL-M", "PAL-M"},
264       {V4L2_STD_PAL_N, "PAL-N", "PAL-N"},
265       {V4L2_STD_PAL_Nc, "PAL-Nc", "PAL-Nc"},
266       {V4L2_STD_PAL_60, "PAL-60", "PAL-60"},
267
268       {V4L2_STD_SECAM, "SECAM", "SECAM"},
269       {V4L2_STD_SECAM_B, "SECAM-B", "SECAM-B"},
270       {V4L2_STD_SECAM_G, "SECAM-G", "SECAM-G"},
271       {V4L2_STD_SECAM_H, "SECAM-H", "SECAM-H"},
272       {V4L2_STD_SECAM_DK, "SECAM-DK", "SECAM-DK"},
273       {V4L2_STD_SECAM_D, "SECAM-D", "SECAM-D"},
274       {V4L2_STD_SECAM_K, "SECAM-K", "SECAM-K"},
275       {V4L2_STD_SECAM_K1, "SECAM-K1", "SECAM-K1"},
276       {V4L2_STD_SECAM_L, "SECAM-L", "SECAM-L"},
277       {V4L2_STD_SECAM_LC, "SECAM-Lc", "SECAM-Lc"},
278
279       {0, NULL, NULL}
280     };
281
282     v4l2_tv_norm = g_enum_register_static ("V4L2_TV_norms", tv_norms);
283   }
284
285   return v4l2_tv_norm;
286 }
287
288 GType
289 gst_v4l2_io_mode_get_type (void)
290 {
291   static GType v4l2_io_mode = 0;
292
293   if (!v4l2_io_mode) {
294     static const GEnumValue io_modes[] = {
295       {GST_V4L2_IO_AUTO, "GST_V4L2_IO_AUTO", "auto"},
296       {GST_V4L2_IO_RW, "GST_V4L2_IO_RW", "rw"},
297       {GST_V4L2_IO_MMAP, "GST_V4L2_IO_MMAP", "mmap"},
298       {GST_V4L2_IO_USERPTR, "GST_V4L2_IO_USERPTR", "userptr"},
299       {GST_V4L2_IO_DMABUF, "GST_V4L2_IO_DMABUF", "dmabuf"},
300       {GST_V4L2_IO_DMABUF_IMPORT, "GST_V4L2_IO_DMABUF_IMPORT",
301           "dmabuf-import"},
302
303       {0, NULL, NULL}
304     };
305     v4l2_io_mode = g_enum_register_static ("GstV4l2IOMode", io_modes);
306   }
307   return v4l2_io_mode;
308 }
309
310 void
311 gst_v4l2_object_install_properties_helper (GObjectClass * gobject_class,
312     const char *default_device)
313 {
314   g_object_class_install_property (gobject_class, PROP_DEVICE,
315       g_param_spec_string ("device", "Device", "Device location",
316           default_device, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
317   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
318       g_param_spec_string ("device-name", "Device name",
319           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
320           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
321   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
322       g_param_spec_int ("device-fd", "File descriptor",
323           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
324           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
325   g_object_class_install_property (gobject_class, PROP_FLAGS,
326       g_param_spec_flags ("flags", "Flags", "Device type flags",
327           GST_TYPE_V4L2_DEVICE_FLAGS, DEFAULT_PROP_FLAGS,
328           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
329
330   /**
331    * GstV4l2Src:brightness:
332    *
333    * Picture brightness, or more precisely, the black level
334    */
335   g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
336       g_param_spec_int ("brightness", "Brightness",
337           "Picture brightness, or more precisely, the black level", G_MININT,
338           G_MAXINT, 0,
339           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
340   /**
341    * GstV4l2Src:contrast:
342    *
343    * Picture contrast or luma gain
344    */
345   g_object_class_install_property (gobject_class, PROP_CONTRAST,
346       g_param_spec_int ("contrast", "Contrast",
347           "Picture contrast or luma gain", G_MININT,
348           G_MAXINT, 0,
349           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
350   /**
351    * GstV4l2Src:saturation:
352    *
353    * Picture color saturation or chroma gain
354    */
355   g_object_class_install_property (gobject_class, PROP_SATURATION,
356       g_param_spec_int ("saturation", "Saturation",
357           "Picture color saturation or chroma gain", G_MININT,
358           G_MAXINT, 0,
359           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
360   /**
361    * GstV4l2Src:hue:
362    *
363    * Hue or color balance
364    */
365   g_object_class_install_property (gobject_class, PROP_HUE,
366       g_param_spec_int ("hue", "Hue",
367           "Hue or color balance", G_MININT,
368           G_MAXINT, 0,
369           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
370
371   /**
372    * GstV4l2Src:norm:
373    *
374    * TV norm
375    */
376   g_object_class_install_property (gobject_class, PROP_TV_NORM,
377       g_param_spec_enum ("norm", "TV norm",
378           "video standard",
379           GST_TYPE_V4L2_TV_NORM, DEFAULT_PROP_TV_NORM,
380           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
381
382   /**
383    * GstV4l2Src:io-mode:
384    *
385    * IO Mode
386    */
387   g_object_class_install_property (gobject_class, PROP_IO_MODE,
388       g_param_spec_enum ("io-mode", "IO mode",
389           "I/O mode",
390           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
391           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392
393   /**
394    * GstV4l2Src:extra-controls:
395    *
396    * Additional v4l2 controls for the device. The controls are identified
397    * by the control name (lowercase with '_' for any non-alphanumeric
398    * characters).
399    *
400    * Since: 1.2
401    */
402   g_object_class_install_property (gobject_class, PROP_EXTRA_CONTROLS,
403       g_param_spec_boxed ("extra-controls", "Extra Controls",
404           "Extra v4l2 controls (CIDs) for the device",
405           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
406
407   /**
408    * GstV4l2Src:pixel-aspect-ratio:
409    *
410    * The pixel aspect ratio of the device. This overwrites the pixel aspect
411    * ratio queried from the device.
412    *
413    * Since: 1.2
414    */
415   g_object_class_install_property (gobject_class, PROP_PIXEL_ASPECT_RATIO,
416       g_param_spec_string ("pixel-aspect-ratio", "Pixel Aspect Ratio",
417           "Overwrite the pixel aspect ratio of the device", "1/1",
418           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
419
420   /**
421    * GstV4l2Src:force-aspect-ratio:
422    *
423    * When enabled, the pixel aspect ratio queried from the device or set
424    * with the pixel-aspect-ratio property will be enforced.
425    *
426    * Since: 1.2
427    */
428   g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
429       g_param_spec_boolean ("force-aspect-ratio", "Force aspect ratio",
430           "When enabled, the pixel aspect ratio will be enforced", TRUE,
431           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
432
433   gst_type_mark_as_plugin_api (GST_TYPE_V4L2_DEVICE_FLAGS, 0);
434   gst_type_mark_as_plugin_api (GST_TYPE_V4L2_TV_NORM, 0);
435   gst_type_mark_as_plugin_api (GST_TYPE_V4L2_IO_MODE, 0);
436 }
437
438 void
439 gst_v4l2_object_install_m2m_properties_helper (GObjectClass * gobject_class)
440 {
441   g_object_class_install_property (gobject_class, PROP_DEVICE,
442       g_param_spec_string ("device", "Device", "Device location",
443           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
444
445   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
446       g_param_spec_string ("device-name", "Device name",
447           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
448           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
449
450   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
451       g_param_spec_int ("device-fd", "File descriptor",
452           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
453           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
454
455   g_object_class_install_property (gobject_class, PROP_OUTPUT_IO_MODE,
456       g_param_spec_enum ("output-io-mode", "Output IO mode",
457           "Output side I/O mode (matches sink pad)",
458           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
459           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
460
461   g_object_class_install_property (gobject_class, PROP_CAPTURE_IO_MODE,
462       g_param_spec_enum ("capture-io-mode", "Capture IO mode",
463           "Capture I/O mode (matches src pad)",
464           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
465           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
466
467   g_object_class_install_property (gobject_class, PROP_EXTRA_CONTROLS,
468       g_param_spec_boxed ("extra-controls", "Extra Controls",
469           "Extra v4l2 controls (CIDs) for the device",
470           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
471 }
472
473 /* Support for 32bit off_t, this wrapper is casting off_t to gint64 */
474 #ifdef HAVE_LIBV4L2
475 #if SIZEOF_OFF_T < 8
476
477 static gpointer
478 v4l2_mmap_wrapper (gpointer start, gsize length, gint prot, gint flags, gint fd,
479     off_t offset)
480 {
481   return v4l2_mmap (start, length, prot, flags, fd, (gint64) offset);
482 }
483
484 #define v4l2_mmap v4l2_mmap_wrapper
485
486 #endif /* SIZEOF_OFF_T < 8 */
487 #endif /* HAVE_LIBV4L2 */
488
489 GstV4l2Object *
490 gst_v4l2_object_new (GstElement * element,
491     GstObject * debug_object,
492     enum v4l2_buf_type type,
493     const char *default_device,
494     GstV4l2GetInOutFunction get_in_out_func,
495     GstV4l2SetInOutFunction set_in_out_func,
496     GstV4l2UpdateFpsFunction update_fps_func)
497 {
498   GstV4l2Object *v4l2object;
499
500   /*
501    * some default values
502    */
503   v4l2object = g_new0 (GstV4l2Object, 1);
504
505   v4l2object->type = type;
506   v4l2object->formats = NULL;
507
508   v4l2object->element = element;
509   v4l2object->dbg_obj = debug_object;
510   v4l2object->get_in_out_func = get_in_out_func;
511   v4l2object->set_in_out_func = set_in_out_func;
512   v4l2object->update_fps_func = update_fps_func;
513
514   v4l2object->video_fd = -1;
515   v4l2object->active = FALSE;
516   v4l2object->videodev = g_strdup (default_device);
517
518   v4l2object->norms = NULL;
519   v4l2object->channels = NULL;
520   v4l2object->colors = NULL;
521
522   v4l2object->keep_aspect = TRUE;
523
524   v4l2object->n_v4l2_planes = 0;
525
526   v4l2object->no_initial_format = FALSE;
527
528   /* We now disable libv4l2 by default, but have an env to enable it. */
529 #ifdef HAVE_LIBV4L2
530   if (g_getenv ("GST_V4L2_USE_LIBV4L2")) {
531     v4l2object->fd_open = v4l2_fd_open;
532     v4l2object->close = v4l2_close;
533     v4l2object->dup = v4l2_dup;
534     v4l2object->ioctl = v4l2_ioctl;
535     v4l2object->read = v4l2_read;
536     v4l2object->mmap = v4l2_mmap;
537     v4l2object->munmap = v4l2_munmap;
538   } else
539 #endif
540   {
541     v4l2object->fd_open = NULL;
542     v4l2object->close = close;
543     v4l2object->dup = dup;
544     v4l2object->ioctl = ioctl;
545     v4l2object->read = read;
546     v4l2object->mmap = mmap;
547     v4l2object->munmap = munmap;
548   }
549
550   return v4l2object;
551 }
552
553 void
554 gst_v4l2_object_destroy (GstV4l2Object * v4l2object)
555 {
556   g_return_if_fail (v4l2object != NULL);
557
558   g_free (v4l2object->videodev);
559   g_free (v4l2object->par);
560   g_free (v4l2object->channel);
561
562   if (v4l2object->formats) {
563     gst_v4l2_object_clear_format_list (v4l2object);
564   }
565
566   if (v4l2object->probed_caps) {
567     gst_caps_unref (v4l2object->probed_caps);
568   }
569
570   if (v4l2object->extra_controls) {
571     gst_structure_free (v4l2object->extra_controls);
572   }
573
574   g_free (v4l2object);
575 }
576
577
578 gboolean
579 gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object)
580 {
581   g_slist_foreach (v4l2object->formats, (GFunc) g_free, NULL);
582   g_slist_free (v4l2object->formats);
583   v4l2object->formats = NULL;
584
585   return TRUE;
586 }
587
588 static gint
589 gst_v4l2_object_prop_to_cid (guint prop_id)
590 {
591   gint cid = -1;
592
593   switch (prop_id) {
594     case PROP_BRIGHTNESS:
595       cid = V4L2_CID_BRIGHTNESS;
596       break;
597     case PROP_CONTRAST:
598       cid = V4L2_CID_CONTRAST;
599       break;
600     case PROP_SATURATION:
601       cid = V4L2_CID_SATURATION;
602       break;
603     case PROP_HUE:
604       cid = V4L2_CID_HUE;
605       break;
606     default:
607       GST_WARNING ("unmapped property id: %d", prop_id);
608   }
609   return cid;
610 }
611
612
613 gboolean
614 gst_v4l2_object_set_property_helper (GstV4l2Object * v4l2object,
615     guint prop_id, const GValue * value, GParamSpec * pspec)
616 {
617   switch (prop_id) {
618     case PROP_DEVICE:
619       g_free (v4l2object->videodev);
620       v4l2object->videodev = g_value_dup_string (value);
621       break;
622     case PROP_BRIGHTNESS:
623     case PROP_CONTRAST:
624     case PROP_SATURATION:
625     case PROP_HUE:
626     {
627       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
628
629       if (cid != -1) {
630         if (GST_V4L2_IS_OPEN (v4l2object)) {
631           gst_v4l2_set_attribute (v4l2object, cid, g_value_get_int (value));
632         }
633       }
634       return TRUE;
635     }
636       break;
637     case PROP_TV_NORM:
638       v4l2object->tv_norm = g_value_get_enum (value);
639       break;
640 #if 0
641     case PROP_CHANNEL:
642       if (GST_V4L2_IS_OPEN (v4l2object)) {
643         GstTuner *tuner = GST_TUNER (v4l2object->element);
644         GstTunerChannel *channel = gst_tuner_find_channel_by_name (tuner,
645             (gchar *) g_value_get_string (value));
646
647         if (channel) {
648           /* like gst_tuner_set_channel (tuner, channel)
649              without g_object_notify */
650           gst_v4l2_tuner_set_channel (v4l2object, channel);
651         }
652       } else {
653         g_free (v4l2object->channel);
654         v4l2object->channel = g_value_dup_string (value);
655       }
656       break;
657     case PROP_FREQUENCY:
658       if (GST_V4L2_IS_OPEN (v4l2object)) {
659         GstTuner *tuner = GST_TUNER (v4l2object->element);
660         GstTunerChannel *channel = gst_tuner_get_channel (tuner);
661
662         if (channel &&
663             GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
664           /* like
665              gst_tuner_set_frequency (tuner, channel, g_value_get_ulong (value))
666              without g_object_notify */
667           gst_v4l2_tuner_set_frequency (v4l2object, channel,
668               g_value_get_ulong (value));
669         }
670       } else {
671         v4l2object->frequency = g_value_get_ulong (value);
672       }
673       break;
674 #endif
675
676     case PROP_IO_MODE:
677       v4l2object->req_mode = g_value_get_enum (value);
678       break;
679     case PROP_CAPTURE_IO_MODE:
680       g_return_val_if_fail (!V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
681       v4l2object->req_mode = g_value_get_enum (value);
682       break;
683     case PROP_OUTPUT_IO_MODE:
684       g_return_val_if_fail (V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
685       v4l2object->req_mode = g_value_get_enum (value);
686       break;
687     case PROP_EXTRA_CONTROLS:{
688       const GstStructure *s = gst_value_get_structure (value);
689
690       if (v4l2object->extra_controls)
691         gst_structure_free (v4l2object->extra_controls);
692
693       v4l2object->extra_controls = s ? gst_structure_copy (s) : NULL;
694       if (GST_V4L2_IS_OPEN (v4l2object))
695         gst_v4l2_set_controls (v4l2object, v4l2object->extra_controls);
696       break;
697     }
698     case PROP_PIXEL_ASPECT_RATIO:
699       if (v4l2object->par) {
700         g_value_unset (v4l2object->par);
701         g_free (v4l2object->par);
702       }
703       v4l2object->par = g_new0 (GValue, 1);
704       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
705       if (!g_value_transform (value, v4l2object->par)) {
706         g_warning ("Could not transform string to aspect ratio");
707         gst_value_set_fraction (v4l2object->par, 1, 1);
708       }
709
710       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "set PAR to %d/%d",
711           gst_value_get_fraction_numerator (v4l2object->par),
712           gst_value_get_fraction_denominator (v4l2object->par));
713       break;
714     case PROP_FORCE_ASPECT_RATIO:
715       v4l2object->keep_aspect = g_value_get_boolean (value);
716       break;
717     default:
718       return FALSE;
719       break;
720   }
721   return TRUE;
722 }
723
724
725 gboolean
726 gst_v4l2_object_get_property_helper (GstV4l2Object * v4l2object,
727     guint prop_id, GValue * value, GParamSpec * pspec)
728 {
729   switch (prop_id) {
730     case PROP_DEVICE:
731       g_value_set_string (value, v4l2object->videodev);
732       break;
733     case PROP_DEVICE_NAME:
734     {
735       const guchar *name = NULL;
736
737       if (GST_V4L2_IS_OPEN (v4l2object))
738         name = v4l2object->vcap.card;
739
740       g_value_set_string (value, (gchar *) name);
741       break;
742     }
743     case PROP_DEVICE_FD:
744     {
745       if (GST_V4L2_IS_OPEN (v4l2object))
746         g_value_set_int (value, v4l2object->video_fd);
747       else
748         g_value_set_int (value, DEFAULT_PROP_DEVICE_FD);
749       break;
750     }
751     case PROP_FLAGS:
752     {
753       guint flags = 0;
754
755       if (GST_V4L2_IS_OPEN (v4l2object)) {
756         flags |= v4l2object->device_caps &
757             (V4L2_CAP_VIDEO_CAPTURE |
758             V4L2_CAP_VIDEO_OUTPUT |
759             V4L2_CAP_VIDEO_OVERLAY |
760             V4L2_CAP_VBI_CAPTURE |
761             V4L2_CAP_VBI_OUTPUT | V4L2_CAP_TUNER | V4L2_CAP_AUDIO);
762
763         if (v4l2object->device_caps & V4L2_CAP_VIDEO_CAPTURE_MPLANE)
764           flags |= V4L2_CAP_VIDEO_CAPTURE;
765
766         if (v4l2object->device_caps & V4L2_CAP_VIDEO_OUTPUT_MPLANE)
767           flags |= V4L2_CAP_VIDEO_OUTPUT;
768       }
769       g_value_set_flags (value, flags);
770       break;
771     }
772     case PROP_BRIGHTNESS:
773     case PROP_CONTRAST:
774     case PROP_SATURATION:
775     case PROP_HUE:
776     {
777       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
778
779       if (cid != -1) {
780         if (GST_V4L2_IS_OPEN (v4l2object)) {
781           gint v;
782           if (gst_v4l2_get_attribute (v4l2object, cid, &v)) {
783             g_value_set_int (value, v);
784           }
785         }
786       }
787       return TRUE;
788     }
789       break;
790     case PROP_TV_NORM:
791       g_value_set_enum (value, v4l2object->tv_norm);
792       break;
793     case PROP_IO_MODE:
794       g_value_set_enum (value, v4l2object->req_mode);
795       break;
796     case PROP_CAPTURE_IO_MODE:
797       g_return_val_if_fail (!V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
798       g_value_set_enum (value, v4l2object->req_mode);
799       break;
800     case PROP_OUTPUT_IO_MODE:
801       g_return_val_if_fail (V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
802       g_value_set_enum (value, v4l2object->req_mode);
803       break;
804     case PROP_EXTRA_CONTROLS:
805       gst_value_set_structure (value, v4l2object->extra_controls);
806       break;
807     case PROP_PIXEL_ASPECT_RATIO:
808       if (v4l2object->par)
809         g_value_transform (v4l2object->par, value);
810       break;
811     case PROP_FORCE_ASPECT_RATIO:
812       g_value_set_boolean (value, v4l2object->keep_aspect);
813       break;
814     default:
815       return FALSE;
816       break;
817   }
818   return TRUE;
819 }
820
821 static void
822 gst_v4l2_get_driver_min_buffers (GstV4l2Object * v4l2object)
823 {
824   struct v4l2_control control = { 0, };
825
826   g_return_if_fail (GST_V4L2_IS_OPEN (v4l2object));
827
828   if (V4L2_TYPE_IS_OUTPUT (v4l2object->type))
829     control.id = V4L2_CID_MIN_BUFFERS_FOR_OUTPUT;
830   else
831     control.id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE;
832
833   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CTRL, &control) == 0) {
834     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
835         "driver requires a minimum of %d buffers", control.value);
836     v4l2object->min_buffers = control.value;
837   } else {
838     v4l2object->min_buffers = 0;
839   }
840 }
841
842 static void
843 gst_v4l2_set_defaults (GstV4l2Object * v4l2object)
844 {
845   GstTunerNorm *norm = NULL;
846   GstTunerChannel *channel = NULL;
847   GstTuner *tuner;
848
849   if (!GST_IS_TUNER (v4l2object->element))
850     return;
851
852   tuner = GST_TUNER (v4l2object->element);
853
854   if (v4l2object->tv_norm)
855     norm = gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
856   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "tv_norm=0x%" G_GINT64_MODIFIER "x, "
857       "norm=%p", (guint64) v4l2object->tv_norm, norm);
858   if (norm) {
859     gst_tuner_set_norm (tuner, norm);
860   } else {
861     norm =
862         GST_TUNER_NORM (gst_tuner_get_norm (GST_TUNER (v4l2object->element)));
863     if (norm) {
864       v4l2object->tv_norm =
865           gst_v4l2_tuner_get_std_id_by_norm (v4l2object, norm);
866       gst_tuner_norm_changed (tuner, norm);
867     }
868   }
869
870   if (v4l2object->channel)
871     channel = gst_tuner_find_channel_by_name (tuner, v4l2object->channel);
872   if (channel) {
873     gst_tuner_set_channel (tuner, channel);
874   } else {
875     channel =
876         GST_TUNER_CHANNEL (gst_tuner_get_channel (GST_TUNER
877             (v4l2object->element)));
878     if (channel) {
879       g_free (v4l2object->channel);
880       v4l2object->channel = g_strdup (channel->label);
881       gst_tuner_channel_changed (tuner, channel);
882     }
883   }
884
885   if (channel
886       && GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
887     if (v4l2object->frequency != 0) {
888       gst_tuner_set_frequency (tuner, channel, v4l2object->frequency);
889     } else {
890       v4l2object->frequency = gst_tuner_get_frequency (tuner, channel);
891       if (v4l2object->frequency == 0) {
892         /* guess */
893         gst_tuner_set_frequency (tuner, channel, 1000);
894       } else {
895       }
896     }
897   }
898 }
899
900 gboolean
901 gst_v4l2_object_open (GstV4l2Object * v4l2object, GstV4l2Error * error)
902 {
903   if (gst_v4l2_open (v4l2object, error))
904     gst_v4l2_set_defaults (v4l2object);
905   else
906     return FALSE;
907
908   return TRUE;
909 }
910
911 gboolean
912 gst_v4l2_object_open_shared (GstV4l2Object * v4l2object, GstV4l2Object * other)
913 {
914   gboolean ret;
915
916   ret = gst_v4l2_dup (v4l2object, other);
917
918   return ret;
919 }
920
921 gboolean
922 gst_v4l2_object_close (GstV4l2Object * v4l2object)
923 {
924   if (!gst_v4l2_close (v4l2object))
925     return FALSE;
926
927   gst_caps_replace (&v4l2object->probed_caps, NULL);
928
929   /* reset our copy of the device caps */
930   v4l2object->device_caps = 0;
931
932   if (v4l2object->formats) {
933     gst_v4l2_object_clear_format_list (v4l2object);
934   }
935
936   if (v4l2object->par) {
937     g_value_unset (v4l2object->par);
938     g_free (v4l2object->par);
939     v4l2object->par = NULL;
940   }
941
942   if (v4l2object->channel) {
943     g_free (v4l2object->channel);
944     v4l2object->channel = NULL;
945   }
946
947   return TRUE;
948 }
949
950 static struct v4l2_fmtdesc *
951 gst_v4l2_object_get_format_from_fourcc (GstV4l2Object * v4l2object,
952     guint32 fourcc)
953 {
954   struct v4l2_fmtdesc *fmt;
955   GSList *walk;
956
957   if (fourcc == 0)
958     return NULL;
959
960   walk = gst_v4l2_object_get_format_list (v4l2object);
961   while (walk) {
962     fmt = (struct v4l2_fmtdesc *) walk->data;
963     if (fmt->pixelformat == fourcc)
964       return fmt;
965     /* special case for jpeg */
966     if (fmt->pixelformat == V4L2_PIX_FMT_MJPEG ||
967         fmt->pixelformat == V4L2_PIX_FMT_JPEG ||
968         fmt->pixelformat == V4L2_PIX_FMT_PJPG) {
969       if (fourcc == V4L2_PIX_FMT_JPEG || fourcc == V4L2_PIX_FMT_MJPEG ||
970           fourcc == V4L2_PIX_FMT_PJPG) {
971         return fmt;
972       }
973     }
974     walk = g_slist_next (walk);
975   }
976
977   return NULL;
978 }
979
980
981
982 /* complete made up ranking, the values themselves are meaningless */
983 /* These ranks MUST be X such that X<<15 fits on a signed int - see
984    the comment at the end of gst_v4l2_object_format_get_rank. */
985 #define YUV_BASE_RANK     1000
986 #define JPEG_BASE_RANK     500
987 #define DV_BASE_RANK       200
988 #define RGB_BASE_RANK      100
989 #define YUV_ODD_BASE_RANK   50
990 #define RGB_ODD_BASE_RANK   25
991 #define BAYER_BASE_RANK     15
992 #define S910_BASE_RANK      10
993 #define GREY_BASE_RANK       5
994 #define PWC_BASE_RANK        1
995
996 static gint
997 gst_v4l2_object_format_get_rank (const struct v4l2_fmtdesc *fmt)
998 {
999   guint32 fourcc = fmt->pixelformat;
1000   gboolean emulated = ((fmt->flags & V4L2_FMT_FLAG_EMULATED) != 0);
1001   gint rank = 0;
1002
1003   switch (fourcc) {
1004     case V4L2_PIX_FMT_MJPEG:
1005     case V4L2_PIX_FMT_PJPG:
1006       rank = JPEG_BASE_RANK;
1007       break;
1008     case V4L2_PIX_FMT_JPEG:
1009       rank = JPEG_BASE_RANK + 1;
1010       break;
1011     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1012       rank = JPEG_BASE_RANK + 2;
1013       break;
1014
1015     case V4L2_PIX_FMT_RGB332:
1016     case V4L2_PIX_FMT_ARGB555:
1017     case V4L2_PIX_FMT_XRGB555:
1018     case V4L2_PIX_FMT_RGB555:
1019     case V4L2_PIX_FMT_ARGB555X:
1020     case V4L2_PIX_FMT_XRGB555X:
1021     case V4L2_PIX_FMT_RGB555X:
1022     case V4L2_PIX_FMT_BGR666:
1023     case V4L2_PIX_FMT_RGB565:
1024     case V4L2_PIX_FMT_RGB565X:
1025     case V4L2_PIX_FMT_RGB444:
1026     case V4L2_PIX_FMT_Y4:
1027     case V4L2_PIX_FMT_Y6:
1028     case V4L2_PIX_FMT_Y10:
1029     case V4L2_PIX_FMT_Y12:
1030     case V4L2_PIX_FMT_Y10BPACK:
1031     case V4L2_PIX_FMT_YUV555:
1032     case V4L2_PIX_FMT_YUV565:
1033     case V4L2_PIX_FMT_YUV32:
1034     case V4L2_PIX_FMT_NV12MT_16X16:
1035     case V4L2_PIX_FMT_NV42:
1036     case V4L2_PIX_FMT_H264_MVC:
1037       rank = RGB_ODD_BASE_RANK;
1038       break;
1039
1040     case V4L2_PIX_FMT_RGB24:
1041     case V4L2_PIX_FMT_BGR24:
1042       rank = RGB_BASE_RANK - 1;
1043       break;
1044
1045     case V4L2_PIX_FMT_RGB32:
1046     case V4L2_PIX_FMT_BGR32:
1047     case V4L2_PIX_FMT_ABGR32:
1048     case V4L2_PIX_FMT_XBGR32:
1049     case V4L2_PIX_FMT_BGRA32:
1050     case V4L2_PIX_FMT_BGRX32:
1051     case V4L2_PIX_FMT_RGBA32:
1052     case V4L2_PIX_FMT_RGBX32:
1053     case V4L2_PIX_FMT_ARGB32:
1054     case V4L2_PIX_FMT_XRGB32:
1055       rank = RGB_BASE_RANK;
1056       break;
1057
1058     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1059       rank = GREY_BASE_RANK;
1060       break;
1061
1062     case V4L2_PIX_FMT_NV12MT:  /* NV12 64x32 tile   */
1063     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1064     case V4L2_PIX_FMT_NV21M:   /* Same as NV21      */
1065     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1066     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1067     case V4L2_PIX_FMT_NV16:    /* 16  Y/CbCr 4:2:2  */
1068     case V4L2_PIX_FMT_NV16M:   /* Same as NV16      */
1069     case V4L2_PIX_FMT_NV61:    /* 16  Y/CrCb 4:2:2  */
1070     case V4L2_PIX_FMT_NV61M:   /* Same as NV61      */
1071     case V4L2_PIX_FMT_NV24:    /* 24  Y/CrCb 4:4:4  */
1072     case V4L2_PIX_FMT_MM21:    /* NV12 Y 16x32, UV 16x16 tile */
1073     case V4L2_PIX_FMT_NV12M_8L128:
1074     case V4L2_PIX_FMT_NV12M_10BE_8L128:
1075       rank = YUV_ODD_BASE_RANK;
1076       break;
1077
1078     case V4L2_PIX_FMT_YVU410:  /* YVU9,  9 bits per pixel */
1079       rank = YUV_BASE_RANK + 3;
1080       break;
1081     case V4L2_PIX_FMT_YUV410:  /* YUV9,  9 bits per pixel */
1082       rank = YUV_BASE_RANK + 2;
1083       break;
1084     case V4L2_PIX_FMT_YUV420:  /* I420, 12 bits per pixel */
1085     case V4L2_PIX_FMT_YUV420M:
1086       rank = YUV_BASE_RANK + 7;
1087       break;
1088     case V4L2_PIX_FMT_NV12:    /* Y/CbCr 4:2:0, 12 bits per pixel */
1089     case V4L2_PIX_FMT_NV12M:   /* Same as NV12      */
1090       rank = YUV_BASE_RANK + 8;
1091       break;
1092     case V4L2_PIX_FMT_YUYV:    /* YUY2, 16 bits per pixel */
1093       rank = YUV_BASE_RANK + 10;
1094       break;
1095     case V4L2_PIX_FMT_YVU420:  /* YV12, 12 bits per pixel */
1096       rank = YUV_BASE_RANK + 6;
1097       break;
1098     case V4L2_PIX_FMT_UYVY:    /* UYVY, 16 bits per pixel */
1099       rank = YUV_BASE_RANK + 9;
1100       break;
1101     case V4L2_PIX_FMT_YUV444:
1102       rank = YUV_BASE_RANK + 6;
1103       break;
1104     case V4L2_PIX_FMT_Y41P:    /* Y41P, 12 bits per pixel */
1105       rank = YUV_BASE_RANK + 5;
1106       break;
1107     case V4L2_PIX_FMT_YUV411P: /* Y41B, 12 bits per pixel */
1108       rank = YUV_BASE_RANK + 4;
1109       break;
1110     case V4L2_PIX_FMT_YUV422P: /* Y42B, 16 bits per pixel */
1111       rank = YUV_BASE_RANK + 8;
1112       break;
1113
1114     case V4L2_PIX_FMT_DV:
1115       rank = DV_BASE_RANK;
1116       break;
1117
1118     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compress */
1119       rank = 0;
1120       break;
1121
1122     case V4L2_PIX_FMT_SBGGR8:
1123     case V4L2_PIX_FMT_SGBRG8:
1124     case V4L2_PIX_FMT_SGRBG8:
1125     case V4L2_PIX_FMT_SRGGB8:
1126       rank = BAYER_BASE_RANK;
1127       break;
1128
1129     case V4L2_PIX_FMT_SN9C10X:
1130       rank = S910_BASE_RANK;
1131       break;
1132
1133     case V4L2_PIX_FMT_PWC1:
1134       rank = PWC_BASE_RANK;
1135       break;
1136     case V4L2_PIX_FMT_PWC2:
1137       rank = PWC_BASE_RANK;
1138       break;
1139
1140     default:
1141       rank = 0;
1142       break;
1143   }
1144
1145   /* All ranks are below 1<<15 so a shift by 15
1146    * will a) make all non-emulated formats larger
1147    * than emulated and b) will not overflow
1148    */
1149   if (!emulated)
1150     rank <<= 15;
1151
1152   return rank;
1153 }
1154
1155
1156
1157 static gint
1158 format_cmp_func (gconstpointer a, gconstpointer b)
1159 {
1160   const struct v4l2_fmtdesc *fa = a;
1161   const struct v4l2_fmtdesc *fb = b;
1162
1163   if (fa->pixelformat == fb->pixelformat)
1164     return 0;
1165
1166   return gst_v4l2_object_format_get_rank (fb) -
1167       gst_v4l2_object_format_get_rank (fa);
1168 }
1169
1170 /******************************************************
1171  * gst_v4l2_object_fill_format_list():
1172  *   create list of supported capture formats
1173  * return value: TRUE on success, FALSE on error
1174  ******************************************************/
1175 static gboolean
1176 gst_v4l2_object_fill_format_list (GstV4l2Object * v4l2object,
1177     enum v4l2_buf_type type)
1178 {
1179   gint n;
1180   struct v4l2_fmtdesc *format;
1181
1182   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "getting src format enumerations");
1183
1184   /* format enumeration */
1185   for (n = 0;; n++) {
1186     format = g_new0 (struct v4l2_fmtdesc, 1);
1187
1188     format->index = n;
1189     format->type = type;
1190
1191     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_ENUM_FMT, format) < 0) {
1192       if (errno == EINVAL) {
1193         g_free (format);
1194         break;                  /* end of enumeration */
1195       } else {
1196         goto failed;
1197       }
1198     }
1199
1200     GST_LOG_OBJECT (v4l2object->dbg_obj, "index:       %u", format->index);
1201     GST_LOG_OBJECT (v4l2object->dbg_obj, "type:        %d", format->type);
1202     GST_LOG_OBJECT (v4l2object->dbg_obj, "flags:       %08x", format->flags);
1203     GST_LOG_OBJECT (v4l2object->dbg_obj, "description: '%s'",
1204         format->description);
1205     GST_LOG_OBJECT (v4l2object->dbg_obj, "pixelformat: %" GST_FOURCC_FORMAT,
1206         GST_FOURCC_ARGS (format->pixelformat));
1207
1208     /* sort formats according to our preference;  we do this, because caps
1209      * are probed in the order the formats are in the list, and the order of
1210      * formats in the final probed caps matters for things like fixation */
1211     v4l2object->formats = g_slist_insert_sorted (v4l2object->formats, format,
1212         (GCompareFunc) format_cmp_func);
1213   }
1214
1215 #ifndef GST_DISABLE_GST_DEBUG
1216   {
1217     GSList *l;
1218
1219     GST_INFO_OBJECT (v4l2object->dbg_obj, "got %d format(s):", n);
1220     for (l = v4l2object->formats; l != NULL; l = l->next) {
1221       format = l->data;
1222
1223       GST_INFO_OBJECT (v4l2object->dbg_obj,
1224           "  %" GST_FOURCC_FORMAT "%s", GST_FOURCC_ARGS (format->pixelformat),
1225           ((format->flags & V4L2_FMT_FLAG_EMULATED)) ? " (emulated)" : "");
1226     }
1227   }
1228 #endif
1229
1230   return TRUE;
1231
1232   /* ERRORS */
1233 failed:
1234   {
1235     g_free (format);
1236
1237     if (v4l2object->element)
1238       return FALSE;
1239
1240     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
1241         (_("Failed to enumerate possible video formats device '%s' can work "
1242                 "with"), v4l2object->videodev),
1243         ("Failed to get number %d in pixelformat enumeration for %s. (%d - %s)",
1244             n, v4l2object->videodev, errno, g_strerror (errno)));
1245
1246     return FALSE;
1247   }
1248 }
1249
1250 /*
1251   * Get the list of supported capture formats, a list of
1252   * `struct v4l2_fmtdesc`.
1253   */
1254 static GSList *
1255 gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object)
1256 {
1257   if (!v4l2object->formats) {
1258
1259     /* check usual way */
1260     gst_v4l2_object_fill_format_list (v4l2object, v4l2object->type);
1261
1262     /* if our driver supports multi-planar
1263      * and if formats are still empty then we can workaround driver bug
1264      * by also looking up formats as if our device was not supporting
1265      * multiplanar */
1266     if (!v4l2object->formats) {
1267       switch (v4l2object->type) {
1268         case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1269           gst_v4l2_object_fill_format_list (v4l2object,
1270               V4L2_BUF_TYPE_VIDEO_CAPTURE);
1271           break;
1272
1273         case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1274           gst_v4l2_object_fill_format_list (v4l2object,
1275               V4L2_BUF_TYPE_VIDEO_OUTPUT);
1276           break;
1277
1278         default:
1279           break;
1280       }
1281     }
1282   }
1283   return v4l2object->formats;
1284 }
1285
1286 static GstVideoFormat
1287 gst_v4l2_object_v4l2fourcc_to_video_format (guint32 fourcc)
1288 {
1289   GstVideoFormat format;
1290
1291   switch (fourcc) {
1292     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1293       format = GST_VIDEO_FORMAT_GRAY8;
1294       break;
1295     case V4L2_PIX_FMT_Y16:
1296       format = GST_VIDEO_FORMAT_GRAY16_LE;
1297       break;
1298     case V4L2_PIX_FMT_Y16_BE:
1299       format = GST_VIDEO_FORMAT_GRAY16_BE;
1300       break;
1301     case V4L2_PIX_FMT_XRGB555:
1302     case V4L2_PIX_FMT_RGB555:
1303       format = GST_VIDEO_FORMAT_RGB15;
1304       break;
1305     case V4L2_PIX_FMT_XRGB555X:
1306     case V4L2_PIX_FMT_RGB555X:
1307       format = GST_VIDEO_FORMAT_BGR15;
1308       break;
1309     case V4L2_PIX_FMT_RGB565:
1310       format = GST_VIDEO_FORMAT_RGB16;
1311       break;
1312     case V4L2_PIX_FMT_RGB24:
1313       format = GST_VIDEO_FORMAT_RGB;
1314       break;
1315     case V4L2_PIX_FMT_BGR24:
1316       format = GST_VIDEO_FORMAT_BGR;
1317       break;
1318     case V4L2_PIX_FMT_XRGB32:
1319     case V4L2_PIX_FMT_RGB32:
1320       format = GST_VIDEO_FORMAT_xRGB;
1321       break;
1322     case V4L2_PIX_FMT_RGBX32:
1323       format = GST_VIDEO_FORMAT_RGBx;
1324       break;
1325     case V4L2_PIX_FMT_XBGR32:
1326     case V4L2_PIX_FMT_BGR32:
1327       format = GST_VIDEO_FORMAT_BGRx;
1328       break;
1329     case V4L2_PIX_FMT_BGRX32:
1330       format = GST_VIDEO_FORMAT_xBGR;
1331       break;
1332     case V4L2_PIX_FMT_ABGR32:
1333       format = GST_VIDEO_FORMAT_BGRA;
1334       break;
1335     case V4L2_PIX_FMT_BGRA32:
1336       format = GST_VIDEO_FORMAT_ABGR;
1337       break;
1338     case V4L2_PIX_FMT_RGBA32:
1339       format = GST_VIDEO_FORMAT_RGBA;
1340       break;
1341     case V4L2_PIX_FMT_ARGB32:
1342       format = GST_VIDEO_FORMAT_ARGB;
1343       break;
1344     case V4L2_PIX_FMT_NV12:
1345     case V4L2_PIX_FMT_NV12M:
1346       format = GST_VIDEO_FORMAT_NV12;
1347       break;
1348     case V4L2_PIX_FMT_NV12MT:
1349       format = GST_VIDEO_FORMAT_NV12_64Z32;
1350       break;
1351     case V4L2_PIX_FMT_MM21:
1352       format = GST_VIDEO_FORMAT_NV12_16L32S;
1353       break;
1354     case V4L2_PIX_FMT_NV12M_8L128:
1355       format = GST_VIDEO_FORMAT_NV12_8L128;
1356       break;
1357     case V4L2_PIX_FMT_NV12M_10BE_8L128:
1358       format = GST_VIDEO_FORMAT_NV12_10BE_8L128;
1359       break;
1360     case V4L2_PIX_FMT_NV21:
1361     case V4L2_PIX_FMT_NV21M:
1362       format = GST_VIDEO_FORMAT_NV21;
1363       break;
1364     case V4L2_PIX_FMT_YVU410:
1365       format = GST_VIDEO_FORMAT_YVU9;
1366       break;
1367     case V4L2_PIX_FMT_YUV410:
1368       format = GST_VIDEO_FORMAT_YUV9;
1369       break;
1370     case V4L2_PIX_FMT_YUV420:
1371     case V4L2_PIX_FMT_YUV420M:
1372       format = GST_VIDEO_FORMAT_I420;
1373       break;
1374     case V4L2_PIX_FMT_YUYV:
1375       format = GST_VIDEO_FORMAT_YUY2;
1376       break;
1377     case V4L2_PIX_FMT_YVU420:
1378       format = GST_VIDEO_FORMAT_YV12;
1379       break;
1380     case V4L2_PIX_FMT_UYVY:
1381       format = GST_VIDEO_FORMAT_UYVY;
1382       break;
1383     case V4L2_PIX_FMT_YUV411P:
1384       format = GST_VIDEO_FORMAT_Y41B;
1385       break;
1386     case V4L2_PIX_FMT_YUV422P:
1387       format = GST_VIDEO_FORMAT_Y42B;
1388       break;
1389     case V4L2_PIX_FMT_YVYU:
1390       format = GST_VIDEO_FORMAT_YVYU;
1391       break;
1392     case V4L2_PIX_FMT_NV16:
1393     case V4L2_PIX_FMT_NV16M:
1394       format = GST_VIDEO_FORMAT_NV16;
1395       break;
1396     case V4L2_PIX_FMT_NV61:
1397     case V4L2_PIX_FMT_NV61M:
1398       format = GST_VIDEO_FORMAT_NV61;
1399       break;
1400     case V4L2_PIX_FMT_NV24:
1401       format = GST_VIDEO_FORMAT_NV24;
1402       break;
1403     default:
1404       format = GST_VIDEO_FORMAT_UNKNOWN;
1405       break;
1406   }
1407
1408   return format;
1409 }
1410
1411 static gboolean
1412 gst_v4l2_object_v4l2fourcc_is_rgb (guint32 fourcc)
1413 {
1414   gboolean ret = FALSE;
1415
1416   switch (fourcc) {
1417     case V4L2_PIX_FMT_XRGB555:
1418     case V4L2_PIX_FMT_RGB555:
1419     case V4L2_PIX_FMT_XRGB555X:
1420     case V4L2_PIX_FMT_RGB555X:
1421     case V4L2_PIX_FMT_RGB565:
1422     case V4L2_PIX_FMT_RGB24:
1423     case V4L2_PIX_FMT_BGR24:
1424     case V4L2_PIX_FMT_XRGB32:
1425     case V4L2_PIX_FMT_RGB32:
1426     case V4L2_PIX_FMT_RGBA32:
1427     case V4L2_PIX_FMT_RGBX32:
1428     case V4L2_PIX_FMT_XBGR32:
1429     case V4L2_PIX_FMT_BGR32:
1430     case V4L2_PIX_FMT_BGRA32:
1431     case V4L2_PIX_FMT_BGRX32:
1432     case V4L2_PIX_FMT_ABGR32:
1433     case V4L2_PIX_FMT_ARGB32:
1434     case V4L2_PIX_FMT_SBGGR8:
1435     case V4L2_PIX_FMT_SGBRG8:
1436     case V4L2_PIX_FMT_SGRBG8:
1437     case V4L2_PIX_FMT_SRGGB8:
1438       ret = TRUE;
1439       break;
1440     default:
1441       break;
1442   }
1443
1444   return ret;
1445 }
1446
1447 static GstStructure *
1448 gst_v4l2_object_v4l2fourcc_to_bare_struct (guint32 fourcc)
1449 {
1450   GstStructure *structure = NULL;
1451
1452   switch (fourcc) {
1453     case V4L2_PIX_FMT_MJPEG:   /* Motion-JPEG */
1454     case V4L2_PIX_FMT_PJPG:    /* Progressive-JPEG */
1455     case V4L2_PIX_FMT_JPEG:    /* JFIF JPEG */
1456       structure = gst_structure_new_empty ("image/jpeg");
1457       break;
1458     case V4L2_PIX_FMT_MPEG1:
1459       structure = gst_structure_new ("video/mpeg",
1460           "mpegversion", G_TYPE_INT, 1, NULL);
1461       break;
1462     case V4L2_PIX_FMT_MPEG2:
1463       structure = gst_structure_new ("video/mpeg",
1464           "mpegversion", G_TYPE_INT, 2, NULL);
1465       break;
1466     case V4L2_PIX_FMT_MPEG4:
1467     case V4L2_PIX_FMT_XVID:
1468       structure = gst_structure_new ("video/mpeg",
1469           "mpegversion", G_TYPE_INT, 4, "systemstream",
1470           G_TYPE_BOOLEAN, FALSE, NULL);
1471       break;
1472     case V4L2_PIX_FMT_FWHT:
1473       structure = gst_structure_new_empty ("video/x-fwht");
1474       break;
1475     case V4L2_PIX_FMT_H263:
1476       structure = gst_structure_new ("video/x-h263",
1477           "variant", G_TYPE_STRING, "itu", NULL);
1478       break;
1479     case V4L2_PIX_FMT_H264:    /* H.264 */
1480       structure = gst_structure_new ("video/x-h264",
1481           "stream-format", G_TYPE_STRING, "byte-stream", "alignment",
1482           G_TYPE_STRING, "au", NULL);
1483       break;
1484     case V4L2_PIX_FMT_H264_NO_SC:
1485       structure = gst_structure_new ("video/x-h264",
1486           "stream-format", G_TYPE_STRING, "avc", "alignment",
1487           G_TYPE_STRING, "au", NULL);
1488       break;
1489     case V4L2_PIX_FMT_HEVC:    /* H.265 */
1490       structure = gst_structure_new ("video/x-h265",
1491           "stream-format", G_TYPE_STRING, "byte-stream", "alignment",
1492           G_TYPE_STRING, "au", NULL);
1493       break;
1494     case V4L2_PIX_FMT_VC1_ANNEX_G:
1495     case V4L2_PIX_FMT_VC1_ANNEX_L:
1496       structure = gst_structure_new ("video/x-wmv",
1497           "wmvversion", G_TYPE_INT, 3, "format", G_TYPE_STRING, "WVC1", NULL);
1498       break;
1499     case V4L2_PIX_FMT_VP8:
1500       structure = gst_structure_new_empty ("video/x-vp8");
1501       break;
1502     case V4L2_PIX_FMT_VP9:
1503       structure = gst_structure_new_empty ("video/x-vp9");
1504       break;
1505     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1506     case V4L2_PIX_FMT_Y16:
1507     case V4L2_PIX_FMT_Y16_BE:
1508     case V4L2_PIX_FMT_XRGB555:
1509     case V4L2_PIX_FMT_RGB555:
1510     case V4L2_PIX_FMT_XRGB555X:
1511     case V4L2_PIX_FMT_RGB555X:
1512     case V4L2_PIX_FMT_RGB565:
1513     case V4L2_PIX_FMT_RGB24:
1514     case V4L2_PIX_FMT_BGR24:
1515     case V4L2_PIX_FMT_RGB32:
1516     case V4L2_PIX_FMT_XRGB32:
1517     case V4L2_PIX_FMT_ARGB32:
1518     case V4L2_PIX_FMT_RGBX32:
1519     case V4L2_PIX_FMT_RGBA32:
1520     case V4L2_PIX_FMT_BGR32:
1521     case V4L2_PIX_FMT_BGRX32:
1522     case V4L2_PIX_FMT_BGRA32:
1523     case V4L2_PIX_FMT_XBGR32:
1524     case V4L2_PIX_FMT_ABGR32:
1525     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1526     case V4L2_PIX_FMT_NV12M:
1527     case V4L2_PIX_FMT_NV12MT:
1528     case V4L2_PIX_FMT_MM21:
1529     case V4L2_PIX_FMT_NV12M_8L128:
1530     case V4L2_PIX_FMT_NV12M_10BE_8L128:
1531     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1532     case V4L2_PIX_FMT_NV21M:
1533     case V4L2_PIX_FMT_NV16:    /* 16  Y/CbCr 4:2:2  */
1534     case V4L2_PIX_FMT_NV16M:
1535     case V4L2_PIX_FMT_NV61:    /* 16  Y/CrCb 4:2:2  */
1536     case V4L2_PIX_FMT_NV61M:
1537     case V4L2_PIX_FMT_NV24:    /* 24  Y/CrCb 4:4:4  */
1538     case V4L2_PIX_FMT_YVU410:
1539     case V4L2_PIX_FMT_YUV410:
1540     case V4L2_PIX_FMT_YUV420:  /* I420/IYUV */
1541     case V4L2_PIX_FMT_YUV420M:
1542     case V4L2_PIX_FMT_YUYV:
1543     case V4L2_PIX_FMT_YVU420:
1544     case V4L2_PIX_FMT_UYVY:
1545     case V4L2_PIX_FMT_YUV422P:
1546     case V4L2_PIX_FMT_YVYU:
1547     case V4L2_PIX_FMT_YUV411P:{
1548       GstVideoFormat format;
1549       format = gst_v4l2_object_v4l2fourcc_to_video_format (fourcc);
1550       if (format != GST_VIDEO_FORMAT_UNKNOWN)
1551         structure = gst_structure_new ("video/x-raw",
1552             "format", G_TYPE_STRING, gst_video_format_to_string (format), NULL);
1553       break;
1554     }
1555     case V4L2_PIX_FMT_DV:
1556       structure =
1557           gst_structure_new ("video/x-dv", "systemstream", G_TYPE_BOOLEAN, TRUE,
1558           NULL);
1559       break;
1560     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1561       structure = gst_structure_new ("video/mpegts",
1562           "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
1563       break;
1564     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compress */
1565       break;
1566     case V4L2_PIX_FMT_SBGGR8:
1567     case V4L2_PIX_FMT_SGBRG8:
1568     case V4L2_PIX_FMT_SGRBG8:
1569     case V4L2_PIX_FMT_SRGGB8:
1570       structure = gst_structure_new ("video/x-bayer", "format", G_TYPE_STRING,
1571           fourcc == V4L2_PIX_FMT_SBGGR8 ? "bggr" :
1572           fourcc == V4L2_PIX_FMT_SGBRG8 ? "gbrg" :
1573           fourcc == V4L2_PIX_FMT_SGRBG8 ? "grbg" :
1574           /* fourcc == V4L2_PIX_FMT_SRGGB8 ? */ "rggb", NULL);
1575       break;
1576     case V4L2_PIX_FMT_SN9C10X:
1577       structure = gst_structure_new_empty ("video/x-sonix");
1578       break;
1579     case V4L2_PIX_FMT_PWC1:
1580       structure = gst_structure_new_empty ("video/x-pwc1");
1581       break;
1582     case V4L2_PIX_FMT_PWC2:
1583       structure = gst_structure_new_empty ("video/x-pwc2");
1584       break;
1585     case V4L2_PIX_FMT_RGB332:
1586     case V4L2_PIX_FMT_BGR666:
1587     case V4L2_PIX_FMT_ARGB555X:
1588     case V4L2_PIX_FMT_RGB565X:
1589     case V4L2_PIX_FMT_RGB444:
1590     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1591     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1592     case V4L2_PIX_FMT_Y4:
1593     case V4L2_PIX_FMT_Y6:
1594     case V4L2_PIX_FMT_Y10:
1595     case V4L2_PIX_FMT_Y12:
1596     case V4L2_PIX_FMT_Y10BPACK:
1597     case V4L2_PIX_FMT_YUV444:
1598     case V4L2_PIX_FMT_YUV555:
1599     case V4L2_PIX_FMT_YUV565:
1600     case V4L2_PIX_FMT_Y41P:
1601     case V4L2_PIX_FMT_YUV32:
1602     case V4L2_PIX_FMT_NV12MT_16X16:
1603     case V4L2_PIX_FMT_NV42:
1604     case V4L2_PIX_FMT_H264_MVC:
1605     default:
1606       GST_DEBUG ("Unsupported fourcc 0x%08x %" GST_FOURCC_FORMAT,
1607           fourcc, GST_FOURCC_ARGS (fourcc));
1608       break;
1609   }
1610
1611   return structure;
1612 }
1613
1614 GstStructure *
1615 gst_v4l2_object_v4l2fourcc_to_structure (guint32 fourcc)
1616 {
1617   GstStructure *template;
1618   gint i;
1619
1620   template = gst_v4l2_object_v4l2fourcc_to_bare_struct (fourcc);
1621
1622   if (template == NULL)
1623     goto done;
1624
1625   for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1626     if (gst_v4l2_formats[i].format != fourcc)
1627       continue;
1628
1629     if (gst_v4l2_formats[i].dimensions) {
1630       gst_structure_set (template,
1631           "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1632           "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1633           "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
1634     }
1635     break;
1636   }
1637
1638 done:
1639   return template;
1640 }
1641
1642 /* Add an 'alternate' variant of the caps with the feature */
1643 static void
1644 add_alternate_variant (GstV4l2Object * v4l2object, GstCaps * caps,
1645     GstStructure * structure)
1646 {
1647   GstStructure *alt_s;
1648
1649   if (v4l2object && v4l2object->never_interlaced)
1650     return;
1651
1652   if (!gst_structure_has_name (structure, "video/x-raw"))
1653     return;
1654
1655   alt_s = gst_structure_copy (structure);
1656   gst_structure_set (alt_s, "interlace-mode", G_TYPE_STRING, "alternate", NULL);
1657
1658   gst_caps_append_structure_full (caps, alt_s,
1659       gst_caps_features_new (GST_CAPS_FEATURE_FORMAT_INTERLACED, NULL));
1660 }
1661
1662 static GstCaps *
1663 gst_v4l2_object_get_caps_helper (GstV4L2FormatFlags flags)
1664 {
1665   GstStructure *structure;
1666   GstCaps *caps, *caps_interlaced;
1667   guint i;
1668
1669   caps = gst_caps_new_empty ();
1670   caps_interlaced = gst_caps_new_empty ();
1671   for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1672
1673     if ((gst_v4l2_formats[i].flags & flags) == 0)
1674       continue;
1675
1676     structure =
1677         gst_v4l2_object_v4l2fourcc_to_bare_struct (gst_v4l2_formats[i].format);
1678
1679     if (structure) {
1680       GstStructure *alt_s = NULL;
1681
1682       if (gst_v4l2_formats[i].dimensions) {
1683         gst_structure_set (structure,
1684             "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1685             "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1686             "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
1687       }
1688
1689       switch (gst_v4l2_formats[i].format) {
1690         case V4L2_PIX_FMT_RGB32:
1691           alt_s = gst_structure_copy (structure);
1692           gst_structure_set (alt_s, "format", G_TYPE_STRING, "ARGB", NULL);
1693           break;
1694         case V4L2_PIX_FMT_BGR32:
1695           alt_s = gst_structure_copy (structure);
1696           gst_structure_set (alt_s, "format", G_TYPE_STRING, "BGRA", NULL);
1697         default:
1698           break;
1699       }
1700
1701       gst_caps_append_structure (caps, structure);
1702
1703       if (alt_s) {
1704         gst_caps_append_structure (caps, alt_s);
1705         add_alternate_variant (NULL, caps_interlaced, alt_s);
1706       }
1707
1708       add_alternate_variant (NULL, caps_interlaced, structure);
1709     }
1710   }
1711
1712   caps = gst_caps_simplify (caps);
1713   caps_interlaced = gst_caps_simplify (caps_interlaced);
1714
1715   return gst_caps_merge (caps, caps_interlaced);
1716 }
1717
1718 GstCaps *
1719 gst_v4l2_object_get_all_caps (void)
1720 {
1721   static GstCaps *caps = NULL;
1722
1723   if (g_once_init_enter (&caps)) {
1724     GstCaps *all_caps = gst_v4l2_object_get_caps_helper (GST_V4L2_ALL);
1725     GST_MINI_OBJECT_FLAG_SET (all_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1726     g_once_init_leave (&caps, all_caps);
1727   }
1728
1729   return caps;
1730 }
1731
1732 GstCaps *
1733 gst_v4l2_object_get_raw_caps (void)
1734 {
1735   static GstCaps *caps = NULL;
1736
1737   if (g_once_init_enter (&caps)) {
1738     GstCaps *raw_caps = gst_v4l2_object_get_caps_helper (GST_V4L2_RAW);
1739     GST_MINI_OBJECT_FLAG_SET (raw_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1740     g_once_init_leave (&caps, raw_caps);
1741   }
1742
1743   return caps;
1744 }
1745
1746 GstCaps *
1747 gst_v4l2_object_get_codec_caps (void)
1748 {
1749   static GstCaps *caps = NULL;
1750
1751   if (g_once_init_enter (&caps)) {
1752     GstCaps *codec_caps = gst_v4l2_object_get_caps_helper (GST_V4L2_CODEC);
1753     GST_MINI_OBJECT_FLAG_SET (codec_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1754     g_once_init_leave (&caps, codec_caps);
1755   }
1756
1757   return caps;
1758 }
1759
1760 /* collect data for the given caps
1761  * @caps: given input caps
1762  * @format: location for the v4l format
1763  * @w/@h: location for width and height
1764  * @fps_n/@fps_d: location for framerate
1765  * @size: location for expected size of the frame or 0 if unknown
1766  */
1767 static gboolean
1768 gst_v4l2_object_get_caps_info (GstV4l2Object * v4l2object, GstCaps * caps,
1769     struct v4l2_fmtdesc **format, GstVideoInfo * info)
1770 {
1771   GstStructure *structure;
1772   guint32 fourcc = 0, fourcc_nc = 0;
1773   const gchar *mimetype;
1774   struct v4l2_fmtdesc *fmt = NULL;
1775
1776   structure = gst_caps_get_structure (caps, 0);
1777
1778   mimetype = gst_structure_get_name (structure);
1779
1780   if (!gst_video_info_from_caps (info, caps))
1781     goto invalid_format;
1782
1783   if (g_str_equal (mimetype, "video/x-raw")) {
1784     switch (GST_VIDEO_INFO_FORMAT (info)) {
1785       case GST_VIDEO_FORMAT_I420:
1786         fourcc = V4L2_PIX_FMT_YUV420;
1787         fourcc_nc = V4L2_PIX_FMT_YUV420M;
1788         break;
1789       case GST_VIDEO_FORMAT_YUY2:
1790         fourcc = V4L2_PIX_FMT_YUYV;
1791         break;
1792       case GST_VIDEO_FORMAT_UYVY:
1793         fourcc = V4L2_PIX_FMT_UYVY;
1794         break;
1795       case GST_VIDEO_FORMAT_YV12:
1796         fourcc = V4L2_PIX_FMT_YVU420;
1797         break;
1798       case GST_VIDEO_FORMAT_Y41B:
1799         fourcc = V4L2_PIX_FMT_YUV411P;
1800         break;
1801       case GST_VIDEO_FORMAT_Y42B:
1802         fourcc = V4L2_PIX_FMT_YUV422P;
1803         break;
1804       case GST_VIDEO_FORMAT_NV12:
1805         fourcc = V4L2_PIX_FMT_NV12;
1806         fourcc_nc = V4L2_PIX_FMT_NV12M;
1807         break;
1808       case GST_VIDEO_FORMAT_NV12_64Z32:
1809         fourcc_nc = V4L2_PIX_FMT_NV12MT;
1810         break;
1811       case GST_VIDEO_FORMAT_NV12_16L32S:
1812         fourcc_nc = V4L2_PIX_FMT_MM21;
1813         break;
1814       case GST_VIDEO_FORMAT_NV12_8L128:
1815         fourcc_nc = V4L2_PIX_FMT_NV12M_8L128;
1816         break;
1817       case GST_VIDEO_FORMAT_NV12_10BE_8L128:
1818         fourcc_nc = V4L2_PIX_FMT_NV12M_10BE_8L128;
1819         break;
1820       case GST_VIDEO_FORMAT_NV21:
1821         fourcc = V4L2_PIX_FMT_NV21;
1822         fourcc_nc = V4L2_PIX_FMT_NV21M;
1823         break;
1824       case GST_VIDEO_FORMAT_NV16:
1825         fourcc = V4L2_PIX_FMT_NV16;
1826         fourcc_nc = V4L2_PIX_FMT_NV16M;
1827         break;
1828       case GST_VIDEO_FORMAT_NV61:
1829         fourcc = V4L2_PIX_FMT_NV61;
1830         fourcc_nc = V4L2_PIX_FMT_NV61M;
1831         break;
1832       case GST_VIDEO_FORMAT_NV24:
1833         fourcc = V4L2_PIX_FMT_NV24;
1834         break;
1835       case GST_VIDEO_FORMAT_YVYU:
1836         fourcc = V4L2_PIX_FMT_YVYU;
1837         break;
1838       case GST_VIDEO_FORMAT_RGB15:
1839         fourcc = V4L2_PIX_FMT_RGB555;
1840         fourcc_nc = V4L2_PIX_FMT_XRGB555;
1841         break;
1842       case GST_VIDEO_FORMAT_RGB16:
1843         fourcc = V4L2_PIX_FMT_RGB565;
1844         break;
1845       case GST_VIDEO_FORMAT_RGB:
1846         fourcc = V4L2_PIX_FMT_RGB24;
1847         break;
1848       case GST_VIDEO_FORMAT_BGR:
1849         fourcc = V4L2_PIX_FMT_BGR24;
1850         break;
1851       case GST_VIDEO_FORMAT_xRGB:
1852         fourcc = V4L2_PIX_FMT_RGB32;
1853         fourcc_nc = V4L2_PIX_FMT_XRGB32;
1854         break;
1855       case GST_VIDEO_FORMAT_RGBx:
1856         fourcc = V4L2_PIX_FMT_RGBX32;
1857         break;
1858       case GST_VIDEO_FORMAT_ARGB:
1859         fourcc = V4L2_PIX_FMT_RGB32;
1860         fourcc_nc = V4L2_PIX_FMT_ARGB32;
1861         break;
1862       case GST_VIDEO_FORMAT_RGBA:
1863         fourcc = V4L2_PIX_FMT_RGBA32;
1864         break;
1865       case GST_VIDEO_FORMAT_BGRx:
1866         fourcc = V4L2_PIX_FMT_BGR32;
1867         fourcc_nc = V4L2_PIX_FMT_XBGR32;
1868         break;
1869       case GST_VIDEO_FORMAT_xBGR:
1870         fourcc = V4L2_PIX_FMT_BGRX32;
1871         break;
1872       case GST_VIDEO_FORMAT_BGRA:
1873         fourcc = V4L2_PIX_FMT_BGR32;
1874         fourcc_nc = V4L2_PIX_FMT_ABGR32;
1875         break;
1876       case GST_VIDEO_FORMAT_ABGR:
1877         fourcc = V4L2_PIX_FMT_BGRA32;
1878         break;
1879       case GST_VIDEO_FORMAT_GRAY8:
1880         fourcc = V4L2_PIX_FMT_GREY;
1881         break;
1882       case GST_VIDEO_FORMAT_GRAY16_LE:
1883         fourcc = V4L2_PIX_FMT_Y16;
1884         break;
1885       case GST_VIDEO_FORMAT_GRAY16_BE:
1886         fourcc = V4L2_PIX_FMT_Y16_BE;
1887         break;
1888       case GST_VIDEO_FORMAT_BGR15:
1889         fourcc = V4L2_PIX_FMT_RGB555X;
1890         fourcc_nc = V4L2_PIX_FMT_XRGB555X;
1891         break;
1892       default:
1893         break;
1894     }
1895   } else {
1896     if (g_str_equal (mimetype, "video/mpegts")) {
1897       fourcc = V4L2_PIX_FMT_MPEG;
1898     } else if (g_str_equal (mimetype, "video/x-dv")) {
1899       fourcc = V4L2_PIX_FMT_DV;
1900     } else if (g_str_equal (mimetype, "image/jpeg")) {
1901       fourcc = V4L2_PIX_FMT_JPEG;
1902     } else if (g_str_equal (mimetype, "video/mpeg")) {
1903       gint version;
1904       if (gst_structure_get_int (structure, "mpegversion", &version)) {
1905         switch (version) {
1906           case 1:
1907             fourcc = V4L2_PIX_FMT_MPEG1;
1908             break;
1909           case 2:
1910             fourcc = V4L2_PIX_FMT_MPEG2;
1911             break;
1912           case 4:
1913             fourcc = V4L2_PIX_FMT_MPEG4;
1914             fourcc_nc = V4L2_PIX_FMT_XVID;
1915             break;
1916           default:
1917             break;
1918         }
1919       }
1920     } else if (g_str_equal (mimetype, "video/x-fwht")) {
1921       fourcc = V4L2_PIX_FMT_FWHT;
1922     } else if (g_str_equal (mimetype, "video/x-h263")) {
1923       fourcc = V4L2_PIX_FMT_H263;
1924     } else if (g_str_equal (mimetype, "video/x-h264")) {
1925       const gchar *stream_format =
1926           gst_structure_get_string (structure, "stream-format");
1927       if (g_str_equal (stream_format, "avc"))
1928         fourcc = V4L2_PIX_FMT_H264_NO_SC;
1929       else
1930         fourcc = V4L2_PIX_FMT_H264;
1931     } else if (g_str_equal (mimetype, "video/x-h265")) {
1932       fourcc = V4L2_PIX_FMT_HEVC;
1933     } else if (g_str_equal (mimetype, "video/x-vp8")) {
1934       fourcc = V4L2_PIX_FMT_VP8;
1935     } else if (g_str_equal (mimetype, "video/x-vp9")) {
1936       fourcc = V4L2_PIX_FMT_VP9;
1937     } else if (g_str_equal (mimetype, "video/x-bayer")) {
1938       const gchar *format = gst_structure_get_string (structure, "format");
1939       if (format) {
1940         if (!g_ascii_strcasecmp (format, "bggr"))
1941           fourcc = V4L2_PIX_FMT_SBGGR8;
1942         else if (!g_ascii_strcasecmp (format, "gbrg"))
1943           fourcc = V4L2_PIX_FMT_SGBRG8;
1944         else if (!g_ascii_strcasecmp (format, "grbg"))
1945           fourcc = V4L2_PIX_FMT_SGRBG8;
1946         else if (!g_ascii_strcasecmp (format, "rggb"))
1947           fourcc = V4L2_PIX_FMT_SRGGB8;
1948       }
1949     } else if (g_str_equal (mimetype, "video/x-sonix")) {
1950       fourcc = V4L2_PIX_FMT_SN9C10X;
1951     } else if (g_str_equal (mimetype, "video/x-pwc1")) {
1952       fourcc = V4L2_PIX_FMT_PWC1;
1953     } else if (g_str_equal (mimetype, "video/x-pwc2")) {
1954       fourcc = V4L2_PIX_FMT_PWC2;
1955     }
1956   }
1957
1958
1959   /* Prefer the non-contiguous if supported */
1960   v4l2object->prefered_non_contiguous = TRUE;
1961
1962   if (fourcc_nc)
1963     fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc_nc);
1964   else if (fourcc == 0)
1965     goto unhandled_format;
1966
1967   if (fmt == NULL) {
1968     fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1969     v4l2object->prefered_non_contiguous = FALSE;
1970   }
1971
1972   if (fmt == NULL)
1973     goto unsupported_format;
1974
1975   *format = fmt;
1976
1977   return TRUE;
1978
1979   /* ERRORS */
1980 invalid_format:
1981   {
1982     GST_DEBUG_OBJECT (v4l2object, "invalid format");
1983     return FALSE;
1984   }
1985 unhandled_format:
1986   {
1987     GST_DEBUG_OBJECT (v4l2object, "unhandled format");
1988     return FALSE;
1989   }
1990 unsupported_format:
1991   {
1992     GST_DEBUG_OBJECT (v4l2object, "unsupported format");
1993     return FALSE;
1994   }
1995 }
1996
1997 static gboolean
1998 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1999     guint32 pixelformat, gint * width, gint * height);
2000
2001 static void
2002 gst_v4l2_object_add_aspect_ratio (GstV4l2Object * v4l2object, GstStructure * s)
2003 {
2004   if (v4l2object->keep_aspect && v4l2object->par)
2005     gst_structure_set_value (s, "pixel-aspect-ratio", v4l2object->par);
2006 }
2007
2008 /* returns TRUE if the value was changed in place, otherwise FALSE */
2009 static gboolean
2010 gst_v4l2src_value_simplify (GValue * val)
2011 {
2012   /* simplify list of one value to one value */
2013   if (GST_VALUE_HOLDS_LIST (val) && gst_value_list_get_size (val) == 1) {
2014     const GValue *list_val;
2015     GValue new_val = G_VALUE_INIT;
2016
2017     list_val = gst_value_list_get_value (val, 0);
2018     g_value_init (&new_val, G_VALUE_TYPE (list_val));
2019     g_value_copy (list_val, &new_val);
2020     g_value_unset (val);
2021     *val = new_val;
2022     return TRUE;
2023   }
2024
2025   return FALSE;
2026 }
2027
2028 static gboolean
2029 gst_v4l2_object_get_interlace_mode (enum v4l2_field field,
2030     GstVideoInterlaceMode * interlace_mode)
2031 {
2032   switch (field) {
2033     case V4L2_FIELD_ANY:
2034       GST_ERROR
2035           ("Driver bug detected - check driver with v4l2-compliance from http://git.linuxtv.org/v4l-utils.git\n");
2036       return FALSE;
2037     case V4L2_FIELD_NONE:
2038       *interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
2039       return TRUE;
2040     case V4L2_FIELD_INTERLACED:
2041     case V4L2_FIELD_INTERLACED_TB:
2042     case V4L2_FIELD_INTERLACED_BT:
2043       *interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
2044       return TRUE;
2045     case V4L2_FIELD_ALTERNATE:
2046       *interlace_mode = GST_VIDEO_INTERLACE_MODE_ALTERNATE;
2047       return TRUE;
2048     default:
2049       GST_ERROR ("Unknown enum v4l2_field %d", field);
2050       return FALSE;
2051   }
2052 }
2053
2054 static gboolean
2055 gst_v4l2_object_get_colorspace (GstV4l2Object * v4l2object,
2056     struct v4l2_format *fmt, GstVideoColorimetry * cinfo)
2057 {
2058   gboolean is_rgb =
2059       gst_v4l2_object_v4l2fourcc_is_rgb (fmt->fmt.pix.pixelformat);
2060   enum v4l2_colorspace colorspace;
2061   enum v4l2_quantization range;
2062   enum v4l2_ycbcr_encoding matrix;
2063   enum v4l2_xfer_func transfer;
2064   gboolean ret = TRUE;
2065
2066   if (V4L2_TYPE_IS_MULTIPLANAR (fmt->type)) {
2067     colorspace = fmt->fmt.pix_mp.colorspace;
2068     range = fmt->fmt.pix_mp.quantization;
2069     matrix = fmt->fmt.pix_mp.ycbcr_enc;
2070     transfer = fmt->fmt.pix_mp.xfer_func;
2071   } else {
2072     colorspace = fmt->fmt.pix.colorspace;
2073     range = fmt->fmt.pix.quantization;
2074     matrix = fmt->fmt.pix.ycbcr_enc;
2075     transfer = fmt->fmt.pix.xfer_func;
2076   }
2077
2078   /* First step, set the defaults for each primaries */
2079   switch (colorspace) {
2080     case V4L2_COLORSPACE_SMPTE170M:
2081       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2082       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT601;
2083       cinfo->transfer = GST_VIDEO_TRANSFER_BT601;
2084       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_SMPTE170M;
2085       break;
2086     case V4L2_COLORSPACE_REC709:
2087       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2088       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT709;
2089       cinfo->transfer = GST_VIDEO_TRANSFER_BT709;
2090       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_BT709;
2091       break;
2092     case V4L2_COLORSPACE_SRGB:
2093     case V4L2_COLORSPACE_JPEG:
2094       cinfo->range = GST_VIDEO_COLOR_RANGE_0_255;
2095       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT601;
2096       cinfo->transfer = GST_VIDEO_TRANSFER_SRGB;
2097       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_BT709;
2098       break;
2099     case V4L2_COLORSPACE_OPRGB:
2100       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2101       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT601;
2102       cinfo->transfer = GST_VIDEO_TRANSFER_ADOBERGB;
2103       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_ADOBERGB;
2104       break;
2105     case V4L2_COLORSPACE_BT2020:
2106       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2107       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT2020;
2108       cinfo->transfer = GST_VIDEO_TRANSFER_BT2020_12;
2109       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_BT2020;
2110       break;
2111     case V4L2_COLORSPACE_SMPTE240M:
2112       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2113       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_SMPTE240M;
2114       cinfo->transfer = GST_VIDEO_TRANSFER_SMPTE240M;
2115       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_SMPTE240M;
2116       break;
2117     case V4L2_COLORSPACE_470_SYSTEM_M:
2118       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2119       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT601;
2120       cinfo->transfer = GST_VIDEO_TRANSFER_BT709;
2121       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_BT470M;
2122       break;
2123     case V4L2_COLORSPACE_470_SYSTEM_BG:
2124       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2125       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT601;
2126       cinfo->transfer = GST_VIDEO_TRANSFER_BT709;
2127       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_BT470BG;
2128       break;
2129     case V4L2_COLORSPACE_RAW:
2130       /* Explicitly unknown */
2131       cinfo->range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
2132       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_UNKNOWN;
2133       cinfo->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
2134       cinfo->primaries = GST_VIDEO_COLOR_PRIMARIES_UNKNOWN;
2135       break;
2136     default:
2137       GST_DEBUG ("Unknown enum v4l2_colorspace %d", colorspace);
2138       ret = FALSE;
2139       break;
2140   }
2141
2142   if (!ret)
2143     goto done;
2144
2145   /* Second step, apply any custom variation */
2146   switch (range) {
2147     case V4L2_QUANTIZATION_FULL_RANGE:
2148       cinfo->range = GST_VIDEO_COLOR_RANGE_0_255;
2149       break;
2150     case V4L2_QUANTIZATION_LIM_RANGE:
2151       cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2152       break;
2153     case V4L2_QUANTIZATION_DEFAULT:
2154       /* replicated V4L2_MAP_QUANTIZATION_DEFAULT macro behavior */
2155       if (is_rgb && colorspace == V4L2_COLORSPACE_BT2020)
2156         cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2157       else if (is_rgb || matrix == V4L2_YCBCR_ENC_XV601
2158           || matrix == V4L2_YCBCR_ENC_XV709
2159           || colorspace == V4L2_COLORSPACE_JPEG)
2160         cinfo->range = GST_VIDEO_COLOR_RANGE_0_255;
2161       else
2162         cinfo->range = GST_VIDEO_COLOR_RANGE_16_235;
2163       break;
2164     default:
2165       GST_WARNING ("Unknown enum v4l2_quantization value %d", range);
2166       cinfo->range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
2167       break;
2168   }
2169
2170   switch (matrix) {
2171     case V4L2_YCBCR_ENC_XV601:
2172     case V4L2_YCBCR_ENC_SYCC:
2173       GST_FIXME ("XV601 and SYCC not defined, assuming 601");
2174       /* fallthrough */
2175     case V4L2_YCBCR_ENC_601:
2176       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT601;
2177       break;
2178     case V4L2_YCBCR_ENC_XV709:
2179       GST_FIXME ("XV709 not defined, assuming 709");
2180       /* fallthrough */
2181     case V4L2_YCBCR_ENC_709:
2182       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT709;
2183       break;
2184     case V4L2_YCBCR_ENC_BT2020_CONST_LUM:
2185       GST_FIXME ("BT2020 with constant luma is not defined, assuming BT2020");
2186       /* fallthrough */
2187     case V4L2_YCBCR_ENC_BT2020:
2188       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_BT2020;
2189       break;
2190     case V4L2_YCBCR_ENC_SMPTE240M:
2191       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_SMPTE240M;
2192       break;
2193     case V4L2_YCBCR_ENC_DEFAULT:
2194       /* nothing, just use defaults for colorspace */
2195       break;
2196     default:
2197       GST_WARNING ("Unknown enum v4l2_ycbcr_encoding value %d", matrix);
2198       cinfo->matrix = GST_VIDEO_COLOR_MATRIX_UNKNOWN;
2199       break;
2200   }
2201
2202   /* Set identity matrix for R'G'B' formats to avoid creating
2203    * confusion. This though is cosmetic as it's now properly ignored by
2204    * the video info API and videoconvert. */
2205   if (is_rgb)
2206     cinfo->matrix = GST_VIDEO_COLOR_MATRIX_RGB;
2207
2208   switch (transfer) {
2209     case V4L2_XFER_FUNC_709:
2210       if (colorspace == V4L2_COLORSPACE_BT2020 && fmt->fmt.pix.height >= 2160)
2211         cinfo->transfer = GST_VIDEO_TRANSFER_BT2020_12;
2212       else if (colorspace == V4L2_COLORSPACE_SMPTE170M)
2213         cinfo->transfer = GST_VIDEO_TRANSFER_BT601;
2214       else
2215         cinfo->transfer = GST_VIDEO_TRANSFER_BT709;
2216
2217       if (v4l2object->transfer)
2218         cinfo->transfer = v4l2object->transfer;
2219       break;
2220     case V4L2_XFER_FUNC_SRGB:
2221       cinfo->transfer = GST_VIDEO_TRANSFER_SRGB;
2222       break;
2223     case V4L2_XFER_FUNC_OPRGB:
2224       cinfo->transfer = GST_VIDEO_TRANSFER_ADOBERGB;
2225       break;
2226     case V4L2_XFER_FUNC_SMPTE240M:
2227       cinfo->transfer = GST_VIDEO_TRANSFER_SMPTE240M;
2228       break;
2229     case V4L2_XFER_FUNC_NONE:
2230       cinfo->transfer = GST_VIDEO_TRANSFER_GAMMA10;
2231       break;
2232     case V4L2_XFER_FUNC_SMPTE2084:
2233       cinfo->transfer = GST_VIDEO_TRANSFER_SMPTE2084;
2234       break;
2235     case V4L2_XFER_FUNC_DEFAULT:
2236       /* nothing, just use defaults for colorspace */
2237       break;
2238     default:
2239       GST_WARNING ("Unknown enum v4l2_xfer_func value %d", transfer);
2240       cinfo->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
2241       break;
2242   }
2243
2244 done:
2245   return ret;
2246 }
2247
2248 static gboolean
2249 gst_v4l2_object_get_streamparm (GstV4l2Object * v4l2object, GstVideoInfo * info)
2250 {
2251   struct v4l2_streamparm streamparm;
2252   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2253   streamparm.type = v4l2object->type;
2254   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_PARM, &streamparm) < 0) {
2255     GST_WARNING_OBJECT (v4l2object->dbg_obj, "VIDIOC_G_PARM failed");
2256     return FALSE;
2257   }
2258   if ((streamparm.parm.capture.timeperframe.numerator != 0)
2259       && (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
2260           || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
2261     GST_VIDEO_INFO_FPS_N (info) =
2262         streamparm.parm.capture.timeperframe.denominator;
2263     GST_VIDEO_INFO_FPS_D (info) =
2264         streamparm.parm.capture.timeperframe.numerator;
2265   }
2266   return TRUE;
2267 }
2268
2269 static int
2270 gst_v4l2_object_try_fmt (GstV4l2Object * v4l2object,
2271     struct v4l2_format *try_fmt)
2272 {
2273   int fd = v4l2object->video_fd;
2274   struct v4l2_format fmt;
2275   int r;
2276
2277   memcpy (&fmt, try_fmt, sizeof (fmt));
2278   r = v4l2object->ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2279
2280   if (r < 0 && errno == ENOTTY) {
2281     /* The driver might not implement TRY_FMT, in which case we will try
2282        S_FMT to probe */
2283     if (GST_V4L2_IS_ACTIVE (v4l2object))
2284       goto error;
2285
2286     memcpy (&fmt, try_fmt, sizeof (fmt));
2287     r = v4l2object->ioctl (fd, VIDIOC_S_FMT, &fmt);
2288   }
2289   memcpy (try_fmt, &fmt, sizeof (fmt));
2290
2291   return r;
2292
2293 error:
2294   memcpy (try_fmt, &fmt, sizeof (fmt));
2295   GST_WARNING_OBJECT (v4l2object->dbg_obj,
2296       "Unable to try format: %s", g_strerror (errno));
2297   return r;
2298 }
2299
2300
2301 static void
2302 gst_v4l2_object_add_interlace_mode (GstV4l2Object * v4l2object,
2303     GstStructure * s, guint32 width, guint32 height, guint32 pixelformat)
2304 {
2305   struct v4l2_format fmt;
2306   GValue interlace_formats = { 0, };
2307   enum v4l2_field formats[] = { V4L2_FIELD_NONE,
2308     V4L2_FIELD_INTERLACED, V4L2_FIELD_ALTERNATE
2309   };
2310   gsize i;
2311   GstVideoInterlaceMode interlace_mode, prev = -1;
2312
2313   if (!g_str_equal (gst_structure_get_name (s), "video/x-raw"))
2314     return;
2315
2316   if (v4l2object->never_interlaced) {
2317     gst_structure_set (s, "interlace-mode", G_TYPE_STRING, "progressive", NULL);
2318     return;
2319   }
2320
2321   g_value_init (&interlace_formats, GST_TYPE_LIST);
2322
2323   /* Try thrice - once for NONE, once for INTERLACED and once for ALTERNATE. */
2324   for (i = 0; i < G_N_ELEMENTS (formats); i++) {
2325     memset (&fmt, 0, sizeof (fmt));
2326     fmt.type = v4l2object->type;
2327     fmt.fmt.pix.width = width;
2328     fmt.fmt.pix.height = height;
2329     fmt.fmt.pix.pixelformat = pixelformat;
2330     fmt.fmt.pix.field = formats[i];
2331
2332     if (fmt.fmt.pix.field == V4L2_FIELD_ALTERNATE)
2333       fmt.fmt.pix.height /= 2;
2334
2335     /* if skip_try_fmt_probes is set it's up to the caller to filter out the
2336      * formats from the formats requested by peer.
2337      * For this negotiation to work with 'alternate' we need the caps to contain
2338      * the feature so we have an intersection with downstream caps.
2339      */
2340     if (!v4l2object->skip_try_fmt_probes
2341         && gst_v4l2_object_try_fmt (v4l2object, &fmt) != 0)
2342       continue;
2343
2344     if (gst_v4l2_object_get_interlace_mode (fmt.fmt.pix.field, &interlace_mode)
2345         && prev != interlace_mode) {
2346       GValue interlace_enum = { 0, };
2347       const gchar *mode_string;
2348       g_value_init (&interlace_enum, G_TYPE_STRING);
2349       mode_string = gst_video_interlace_mode_to_string (interlace_mode);
2350       g_value_set_string (&interlace_enum, mode_string);
2351       gst_value_list_append_and_take_value (&interlace_formats,
2352           &interlace_enum);
2353       prev = interlace_mode;
2354     }
2355   }
2356
2357   if (gst_v4l2src_value_simplify (&interlace_formats)
2358       || gst_value_list_get_size (&interlace_formats) > 0)
2359     gst_structure_take_value (s, "interlace-mode", &interlace_formats);
2360   else
2361     GST_WARNING_OBJECT (v4l2object, "Failed to determine interlace mode");
2362
2363   return;
2364 }
2365
2366 static void
2367 gst_v4l2_object_fill_colorimetry_list (GValue * list,
2368     GstVideoColorimetry * cinfo)
2369 {
2370   GValue colorimetry = G_VALUE_INIT;
2371   guint size;
2372   guint i;
2373   gboolean found = FALSE;
2374
2375   g_value_init (&colorimetry, G_TYPE_STRING);
2376   g_value_take_string (&colorimetry, gst_video_colorimetry_to_string (cinfo));
2377
2378   /* only insert if no duplicate */
2379   size = gst_value_list_get_size (list);
2380   for (i = 0; i < size; i++) {
2381     const GValue *tmp;
2382
2383     tmp = gst_value_list_get_value (list, i);
2384     if (gst_value_compare (&colorimetry, tmp) == GST_VALUE_EQUAL) {
2385       found = TRUE;
2386       break;
2387     }
2388   }
2389
2390   if (!found)
2391     gst_value_list_append_and_take_value (list, &colorimetry);
2392   else
2393     g_value_unset (&colorimetry);
2394 }
2395
2396 static void
2397 gst_v4l2_object_add_colorspace (GstV4l2Object * v4l2object, GstStructure * s,
2398     guint32 width, guint32 height, guint32 pixelformat)
2399 {
2400   struct v4l2_format fmt;
2401   GValue list = G_VALUE_INIT;
2402   GstVideoColorimetry cinfo;
2403   enum v4l2_colorspace req_cspace;
2404
2405   memset (&fmt, 0, sizeof (fmt));
2406   fmt.type = v4l2object->type;
2407   fmt.fmt.pix.width = width;
2408   fmt.fmt.pix.height = height;
2409   fmt.fmt.pix.pixelformat = pixelformat;
2410
2411   g_value_init (&list, GST_TYPE_LIST);
2412
2413   /* step 1: get device default colorspace and insert it first as
2414    * it should be the preferred one */
2415   if (gst_v4l2_object_try_fmt (v4l2object, &fmt) == 0) {
2416     if (gst_v4l2_object_get_colorspace (v4l2object, &fmt, &cinfo))
2417       gst_v4l2_object_fill_colorimetry_list (&list, &cinfo);
2418   }
2419
2420   /* step 2: probe all colorspace other than default
2421    * We don't probe all colorspace, range, matrix and transfer combination to
2422    * avoid ioctl flooding which could greatly increase initialization time
2423    * with low-speed devices (UVC...) */
2424   for (req_cspace = V4L2_COLORSPACE_SMPTE170M;
2425       req_cspace <= V4L2_COLORSPACE_RAW; req_cspace++) {
2426     /* V4L2_COLORSPACE_BT878 is deprecated and shall not be used, so skip */
2427     if (req_cspace == V4L2_COLORSPACE_BT878)
2428       continue;
2429
2430     if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
2431       fmt.fmt.pix_mp.colorspace = req_cspace;
2432     else
2433       fmt.fmt.pix.colorspace = req_cspace;
2434
2435     if (gst_v4l2_object_try_fmt (v4l2object, &fmt) == 0) {
2436       enum v4l2_colorspace colorspace;
2437
2438       if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
2439         colorspace = fmt.fmt.pix_mp.colorspace;
2440       else
2441         colorspace = fmt.fmt.pix.colorspace;
2442
2443       if (colorspace == req_cspace) {
2444         if (gst_v4l2_object_get_colorspace (v4l2object, &fmt, &cinfo))
2445           gst_v4l2_object_fill_colorimetry_list (&list, &cinfo);
2446         if (colorspace == V4L2_COLORSPACE_REC709) {
2447           /* support for full-range variants of colorspaces V4L2_COLORSPACE_REC709
2448            * (such as Apple's full-range bt709 variant 1:3:5:1) */
2449           struct v4l2_format alt_fmt;
2450           memcpy (&alt_fmt, &fmt, sizeof (alt_fmt));
2451
2452           if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
2453             alt_fmt.fmt.pix_mp.quantization = V4L2_QUANTIZATION_FULL_RANGE;
2454           else
2455             alt_fmt.fmt.pix.quantization = V4L2_QUANTIZATION_FULL_RANGE;
2456
2457           if (gst_v4l2_object_get_colorspace (v4l2object, &alt_fmt, &cinfo))
2458             gst_v4l2_object_fill_colorimetry_list (&list, &cinfo);
2459         }
2460       }
2461     }
2462   }
2463
2464   if (gst_value_list_get_size (&list) > 0)
2465     gst_structure_take_value (s, "colorimetry", &list);
2466   else
2467     g_value_unset (&list);
2468
2469   return;
2470 }
2471
2472 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
2473 static GstStructure *
2474 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
2475     guint32 pixelformat,
2476     guint32 width, guint32 height, const GstStructure * template)
2477 {
2478   gint fd = v4l2object->video_fd;
2479   struct v4l2_frmivalenum ival;
2480   guint32 num, denom;
2481   GstStructure *s;
2482   GValue rates = { 0, };
2483
2484   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
2485   ival.index = 0;
2486   ival.pixel_format = pixelformat;
2487   ival.width = width;
2488   ival.height = height;
2489
2490   GST_LOG_OBJECT (v4l2object->dbg_obj,
2491       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
2492       GST_FOURCC_ARGS (pixelformat));
2493
2494   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
2495    * fraction to get framerate */
2496   if (v4l2object->ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
2497     goto enum_frameintervals_failed;
2498
2499   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
2500     GValue rate = { 0, };
2501
2502     g_value_init (&rates, GST_TYPE_LIST);
2503     g_value_init (&rate, GST_TYPE_FRACTION);
2504
2505     do {
2506       num = ival.discrete.numerator;
2507       denom = ival.discrete.denominator;
2508
2509       if (num > G_MAXINT || denom > G_MAXINT) {
2510         /* let us hope we don't get here... */
2511         num >>= 1;
2512         denom >>= 1;
2513       }
2514
2515       GST_LOG_OBJECT (v4l2object->dbg_obj, "adding discrete framerate: %d/%d",
2516           denom, num);
2517
2518       /* swap to get the framerate */
2519       gst_value_set_fraction (&rate, denom, num);
2520       gst_value_list_append_value (&rates, &rate);
2521
2522       ival.index++;
2523     } while (v4l2object->ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
2524   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
2525     GValue min = { 0, };
2526     GValue step = { 0, };
2527     GValue max = { 0, };
2528     gboolean added = FALSE;
2529     guint32 minnum, mindenom;
2530     guint32 maxnum, maxdenom;
2531
2532     g_value_init (&rates, GST_TYPE_LIST);
2533
2534     g_value_init (&min, GST_TYPE_FRACTION);
2535     g_value_init (&step, GST_TYPE_FRACTION);
2536     g_value_init (&max, GST_TYPE_FRACTION);
2537
2538     /* get the min */
2539     minnum = ival.stepwise.min.numerator;
2540     mindenom = ival.stepwise.min.denominator;
2541     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
2542       minnum >>= 1;
2543       mindenom >>= 1;
2544     }
2545     GST_LOG_OBJECT (v4l2object->dbg_obj, "stepwise min frame interval: %d/%d",
2546         minnum, mindenom);
2547     gst_value_set_fraction (&min, minnum, mindenom);
2548
2549     /* get the max */
2550     maxnum = ival.stepwise.max.numerator;
2551     maxdenom = ival.stepwise.max.denominator;
2552     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
2553       maxnum >>= 1;
2554       maxdenom >>= 1;
2555     }
2556
2557     GST_LOG_OBJECT (v4l2object->dbg_obj, "stepwise max frame interval: %d/%d",
2558         maxnum, maxdenom);
2559     gst_value_set_fraction (&max, maxnum, maxdenom);
2560
2561     /* get the step */
2562     num = ival.stepwise.step.numerator;
2563     denom = ival.stepwise.step.denominator;
2564     if (num > G_MAXINT || denom > G_MAXINT) {
2565       num >>= 1;
2566       denom >>= 1;
2567     }
2568
2569     if (num == 0 || denom == 0) {
2570       /* in this case we have a wrong fraction or no step, set the step to max
2571        * so that we only add the min value in the loop below */
2572       num = maxnum;
2573       denom = maxdenom;
2574     }
2575
2576     /* since we only have gst_value_fraction_subtract and not add, negate the
2577      * numerator */
2578     GST_LOG_OBJECT (v4l2object->dbg_obj, "stepwise step frame interval: %d/%d",
2579         num, denom);
2580     gst_value_set_fraction (&step, -num, denom);
2581
2582     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
2583       GValue rate = { 0, };
2584
2585       num = gst_value_get_fraction_numerator (&min);
2586       denom = gst_value_get_fraction_denominator (&min);
2587       GST_LOG_OBJECT (v4l2object->dbg_obj, "adding stepwise framerate: %d/%d",
2588           denom, num);
2589
2590       /* invert to get the framerate */
2591       g_value_init (&rate, GST_TYPE_FRACTION);
2592       gst_value_set_fraction (&rate, denom, num);
2593       gst_value_list_append_value (&rates, &rate);
2594       added = TRUE;
2595
2596       /* we're actually adding because step was negated above. This is because
2597        * there is no _add function... */
2598       if (!gst_value_fraction_subtract (&min, &min, &step)) {
2599         GST_WARNING_OBJECT (v4l2object->dbg_obj, "could not step fraction!");
2600         break;
2601       }
2602     }
2603     if (!added) {
2604       /* no range was added, leave the default range from the template */
2605       GST_WARNING_OBJECT (v4l2object->dbg_obj,
2606           "no range added, leaving default");
2607       g_value_unset (&rates);
2608     }
2609   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
2610     guint32 maxnum, maxdenom;
2611
2612     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
2613
2614     num = ival.stepwise.min.numerator;
2615     denom = ival.stepwise.min.denominator;
2616     if (num > G_MAXINT || denom > G_MAXINT) {
2617       num >>= 1;
2618       denom >>= 1;
2619     }
2620
2621     maxnum = ival.stepwise.max.numerator;
2622     maxdenom = ival.stepwise.max.denominator;
2623     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
2624       maxnum >>= 1;
2625       maxdenom >>= 1;
2626     }
2627
2628     GST_LOG_OBJECT (v4l2object->dbg_obj,
2629         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
2630         num);
2631
2632     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
2633   } else {
2634     goto unknown_type;
2635   }
2636
2637 return_data:
2638   s = gst_structure_copy (template);
2639   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
2640       "height", G_TYPE_INT, (gint) height, NULL);
2641
2642   gst_v4l2_object_add_aspect_ratio (v4l2object, s);
2643
2644   if (!v4l2object->skip_try_fmt_probes) {
2645     gst_v4l2_object_add_interlace_mode (v4l2object, s, width, height,
2646         pixelformat);
2647     gst_v4l2_object_add_colorspace (v4l2object, s, width, height, pixelformat);
2648   }
2649
2650   if (G_IS_VALUE (&rates)) {
2651     gst_v4l2src_value_simplify (&rates);
2652     /* only change the framerate on the template when we have a valid probed new
2653      * value */
2654     gst_structure_take_value (s, "framerate", &rates);
2655   } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2656       v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
2657     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT,
2658         1, NULL);
2659   }
2660   return s;
2661
2662   /* ERRORS */
2663 enum_frameintervals_failed:
2664   {
2665     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
2666         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
2667         GST_FOURCC_ARGS (pixelformat), width, height);
2668     goto return_data;
2669   }
2670 unknown_type:
2671   {
2672     /* I don't see how this is actually an error, we ignore the format then */
2673     GST_WARNING_OBJECT (v4l2object->dbg_obj,
2674         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
2675         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
2676     return NULL;
2677   }
2678 }
2679
2680 static gint
2681 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
2682 {
2683   int w1, h1, w2, h2;
2684
2685   gst_structure_get_int (s1, "width", &w1);
2686   gst_structure_get_int (s1, "height", &h1);
2687   gst_structure_get_int (s2, "width", &w2);
2688   gst_structure_get_int (s2, "height", &h2);
2689
2690   /* I think it's safe to assume that this won't overflow for a while */
2691   return ((w2 * h2) - (w1 * h1));
2692 }
2693
2694 static void
2695 check_alternate_and_append_struct (GstCaps * caps, GstStructure * s)
2696 {
2697   const GValue *mode;
2698
2699   mode = gst_structure_get_value (s, "interlace-mode");
2700   if (!mode)
2701     goto done;
2702
2703   if (G_VALUE_HOLDS_STRING (mode)) {
2704     /* Add the INTERLACED feature if the mode is alternate */
2705     if (!g_strcmp0 (gst_structure_get_string (s, "interlace-mode"),
2706             "alternate")) {
2707       GstCapsFeatures *feat;
2708
2709       feat = gst_caps_features_new (GST_CAPS_FEATURE_FORMAT_INTERLACED, NULL);
2710       gst_caps_set_features (caps, gst_caps_get_size (caps) - 1, feat);
2711     }
2712   } else if (GST_VALUE_HOLDS_LIST (mode)) {
2713     /* If the mode is a list containing alternate, remove it from the list and add a
2714      * variant with interlace-mode=alternate and the INTERLACED feature. */
2715     GValue alter = G_VALUE_INIT;
2716     GValue inter = G_VALUE_INIT;
2717
2718     g_value_init (&alter, G_TYPE_STRING);
2719     g_value_set_string (&alter, "alternate");
2720
2721     /* Cannot use gst_value_can_intersect() as it requires args to have the
2722      * same type. */
2723     if (gst_value_intersect (&inter, mode, &alter)) {
2724       GValue minus_alter = G_VALUE_INIT;
2725       GstStructure *copy;
2726
2727       gst_value_subtract (&minus_alter, mode, &alter);
2728       gst_structure_take_value (s, "interlace-mode", &minus_alter);
2729
2730       copy = gst_structure_copy (s);
2731       gst_structure_take_value (copy, "interlace-mode", &inter);
2732       gst_caps_append_structure_full (caps, copy,
2733           gst_caps_features_new (GST_CAPS_FEATURE_FORMAT_INTERLACED, NULL));
2734     }
2735     g_value_unset (&alter);
2736   }
2737
2738 done:
2739   gst_caps_append_structure (caps, s);
2740 }
2741
2742 static void
2743 gst_v4l2_object_update_and_append (GstV4l2Object * v4l2object,
2744     guint32 format, GstCaps * caps, GstStructure * s)
2745 {
2746   GstStructure *alt_s = NULL;
2747
2748   /* Encoded stream on output buffer need to be parsed */
2749   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT ||
2750       v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
2751     gint i = 0;
2752
2753     for (; i < GST_V4L2_FORMAT_COUNT; i++) {
2754       if (format == gst_v4l2_formats[i].format &&
2755           gst_v4l2_formats[i].flags & GST_V4L2_CODEC &&
2756           !(gst_v4l2_formats[i].flags & GST_V4L2_NO_PARSE)) {
2757         gst_structure_set (s, "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
2758         break;
2759       }
2760     }
2761   }
2762
2763   if (v4l2object->has_alpha_component &&
2764       (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2765           v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
2766     switch (format) {
2767       case V4L2_PIX_FMT_RGB32:
2768         alt_s = gst_structure_copy (s);
2769         gst_structure_set (alt_s, "format", G_TYPE_STRING, "ARGB", NULL);
2770         break;
2771       case V4L2_PIX_FMT_BGR32:
2772         alt_s = gst_structure_copy (s);
2773         gst_structure_set (alt_s, "format", G_TYPE_STRING, "BGRA", NULL);
2774         break;
2775       default:
2776         break;
2777     }
2778   }
2779
2780   check_alternate_and_append_struct (caps, s);
2781
2782   if (alt_s) {
2783     check_alternate_and_append_struct (caps, alt_s);
2784   }
2785 }
2786
2787 static GstCaps *
2788 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
2789     guint32 pixelformat, const GstStructure * template)
2790 {
2791   GstCaps *ret = gst_caps_new_empty ();
2792   GstStructure *tmp;
2793   gint fd = v4l2object->video_fd;
2794   struct v4l2_frmsizeenum size;
2795   GList *results = NULL;
2796   guint32 w, h;
2797
2798   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')) {
2799     gst_caps_append_structure (ret, gst_structure_copy (template));
2800     return ret;
2801   }
2802
2803   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
2804   size.index = 0;
2805   size.pixel_format = pixelformat;
2806
2807   GST_DEBUG_OBJECT (v4l2object->dbg_obj,
2808       "Enumerating frame sizes for %" GST_FOURCC_FORMAT,
2809       GST_FOURCC_ARGS (pixelformat));
2810
2811   if (v4l2object->ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
2812     goto enum_framesizes_failed;
2813
2814   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
2815     do {
2816       GST_LOG_OBJECT (v4l2object->dbg_obj, "got discrete frame size %dx%d",
2817           size.discrete.width, size.discrete.height);
2818
2819       w = MIN (size.discrete.width, G_MAXINT);
2820       h = MIN (size.discrete.height, G_MAXINT);
2821
2822       if (w && h) {
2823         tmp =
2824             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
2825             pixelformat, w, h, template);
2826
2827         if (tmp)
2828           results = g_list_prepend (results, tmp);
2829       }
2830
2831       size.index++;
2832     } while (v4l2object->ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
2833     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
2834         "done iterating discrete frame sizes");
2835   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
2836     guint32 maxw, maxh, step_w, step_h;
2837
2838     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "we have stepwise frame sizes:");
2839     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "min width:   %d",
2840         size.stepwise.min_width);
2841     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "min height:  %d",
2842         size.stepwise.min_height);
2843     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "max width:   %d",
2844         size.stepwise.max_width);
2845     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "min height:  %d",
2846         size.stepwise.max_height);
2847     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "step width:  %d",
2848         size.stepwise.step_width);
2849     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "step height: %d",
2850         size.stepwise.step_height);
2851
2852     w = MAX (size.stepwise.min_width, 1);
2853     h = MAX (size.stepwise.min_height, 1);
2854     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2855     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2856
2857     step_w = MAX (size.stepwise.step_width, 1);
2858     step_h = MAX (size.stepwise.step_height, 1);
2859
2860     /* FIXME: check for sanity and that min/max are multiples of the steps */
2861
2862     /* we only query details for the max width/height since it's likely the
2863      * most restricted if there are any resolution-dependent restrictions */
2864     tmp = gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
2865         pixelformat, maxw, maxh, template);
2866
2867     if (tmp) {
2868       GValue step_range = G_VALUE_INIT;
2869
2870       g_value_init (&step_range, GST_TYPE_INT_RANGE);
2871       gst_value_set_int_range_step (&step_range, w, maxw, step_w);
2872       gst_structure_set_value (tmp, "width", &step_range);
2873
2874       gst_value_set_int_range_step (&step_range, h, maxh, step_h);
2875       gst_structure_take_value (tmp, "height", &step_range);
2876
2877       /* no point using the results list here, since there's only one struct */
2878       gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2879     }
2880   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
2881     guint32 maxw, maxh;
2882
2883     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "we have continuous frame sizes:");
2884     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "min width:   %d",
2885         size.stepwise.min_width);
2886     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "min height:  %d",
2887         size.stepwise.min_height);
2888     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "max width:   %d",
2889         size.stepwise.max_width);
2890     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "min height:  %d",
2891         size.stepwise.max_height);
2892
2893     w = MAX (size.stepwise.min_width, 1);
2894     h = MAX (size.stepwise.min_height, 1);
2895     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2896     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2897
2898     tmp =
2899         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
2900         w, h, template);
2901     if (tmp) {
2902       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
2903           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
2904           NULL);
2905
2906       /* no point using the results list here, since there's only one struct */
2907       gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2908     }
2909   } else {
2910     goto unknown_type;
2911   }
2912
2913   /* we use an intermediary list to store and then sort the results of the
2914    * probing because we can't make any assumptions about the order in which
2915    * the driver will give us the sizes, but we want the final caps to contain
2916    * the results starting with the highest resolution and having the lowest
2917    * resolution last, since order in caps matters for things like fixation. */
2918   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
2919   while (results != NULL) {
2920     gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret,
2921         results->data);
2922     results = g_list_delete_link (results, results);
2923   }
2924
2925   if (gst_caps_is_empty (ret))
2926     goto enum_framesizes_no_results;
2927
2928   return ret;
2929
2930   /* ERRORS */
2931 enum_framesizes_failed:
2932   {
2933     /* I don't see how this is actually an error */
2934     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
2935         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
2936         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
2937     goto default_frame_sizes;
2938   }
2939 enum_framesizes_no_results:
2940   {
2941     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
2942      * question doesn't actually support it yet */
2943     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
2944         "No results for pixelformat %" GST_FOURCC_FORMAT
2945         " enumerating frame sizes, trying fallback",
2946         GST_FOURCC_ARGS (pixelformat));
2947     goto default_frame_sizes;
2948   }
2949 unknown_type:
2950   {
2951     GST_WARNING_OBJECT (v4l2object->dbg_obj,
2952         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
2953         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
2954     goto default_frame_sizes;
2955   }
2956
2957 default_frame_sizes:
2958   {
2959     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
2960
2961     /* This code is for Linux < 2.6.19 */
2962     min_w = min_h = 1;
2963     max_w = max_h = GST_V4L2_MAX_SIZE;
2964     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
2965             &min_h)) {
2966       GST_WARNING_OBJECT (v4l2object->dbg_obj,
2967           "Could not probe minimum capture size for pixelformat %"
2968           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2969     }
2970     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
2971             &max_h)) {
2972       GST_WARNING_OBJECT (v4l2object->dbg_obj,
2973           "Could not probe maximum capture size for pixelformat %"
2974           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2975     }
2976     if (min_w == 0 || min_h == 0)
2977       min_w = min_h = 1;
2978     if (max_w == 0 || max_h == 0)
2979       max_w = max_h = GST_V4L2_MAX_SIZE;
2980
2981     /* Since we can't get framerate directly, try to use the current norm */
2982     if (v4l2object->tv_norm && v4l2object->norms) {
2983       GList *norms;
2984       GstTunerNorm *norm = NULL;
2985       GstTunerNorm *current =
2986           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
2987
2988       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
2989         norm = (GstTunerNorm *) norms->data;
2990         if (!strcmp (norm->label, current->label))
2991           break;
2992       }
2993       /* If it's possible, set framerate to that (discrete) value */
2994       if (norm) {
2995         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
2996         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
2997       }
2998     }
2999
3000     tmp = gst_structure_copy (template);
3001     if (fix_num) {
3002       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
3003           fix_denom, NULL);
3004     } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3005         v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
3006       /* if norm can't be used, copy the template framerate */
3007       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
3008           G_MAXINT, 1, NULL);
3009     }
3010
3011     if (min_w == max_w)
3012       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
3013     else
3014       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
3015
3016     if (min_h == max_h)
3017       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
3018     else
3019       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
3020
3021     gst_v4l2_object_add_aspect_ratio (v4l2object, tmp);
3022
3023     /* We could consider setting interlace mode from min and max. */
3024     gst_v4l2_object_add_interlace_mode (v4l2object, tmp, max_w, max_h,
3025         pixelformat);
3026
3027     if (!v4l2object->skip_try_fmt_probes) {
3028       gint probed_w, probed_h;
3029       if (v4l2object->info.width >= min_w && v4l2object->info.width <= max_w &&
3030           v4l2object->info.height >= min_h
3031           && v4l2object->info.height <= max_h) {
3032         probed_w = v4l2object->info.width;
3033         probed_h = v4l2object->info.height;
3034       } else {
3035         probed_w = max_w;
3036         probed_h = max_h;
3037       }
3038       /* We could consider to check colorspace for min too, in case it depends on
3039        * the size. But in this case, min and max could not be enough */
3040       gst_v4l2_object_add_colorspace (v4l2object, tmp, probed_w, probed_h,
3041           pixelformat);
3042     }
3043
3044     gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
3045     return ret;
3046   }
3047 }
3048
3049 static gboolean
3050 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
3051     guint32 pixelformat, gint * width, gint * height)
3052 {
3053   struct v4l2_format fmt;
3054   gboolean ret = FALSE;
3055   GstVideoInterlaceMode interlace_mode;
3056
3057   g_return_val_if_fail (width != NULL, FALSE);
3058   g_return_val_if_fail (height != NULL, FALSE);
3059
3060   GST_LOG_OBJECT (v4l2object->dbg_obj,
3061       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
3062       *width, *height, GST_FOURCC_ARGS (pixelformat));
3063
3064   memset (&fmt, 0, sizeof (struct v4l2_format));
3065
3066   /* get size delimiters */
3067   memset (&fmt, 0, sizeof (fmt));
3068   fmt.type = v4l2object->type;
3069   fmt.fmt.pix.width = *width;
3070   fmt.fmt.pix.height = *height;
3071   fmt.fmt.pix.pixelformat = pixelformat;
3072   fmt.fmt.pix.field = V4L2_FIELD_ANY;
3073
3074   if (gst_v4l2_object_try_fmt (v4l2object, &fmt) < 0)
3075     goto error;
3076
3077   GST_LOG_OBJECT (v4l2object->dbg_obj,
3078       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
3079
3080   *width = fmt.fmt.pix.width;
3081   *height = fmt.fmt.pix.height;
3082
3083   if (!gst_v4l2_object_get_interlace_mode (fmt.fmt.pix.field, &interlace_mode)) {
3084     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3085         "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u: %u",
3086         GST_FOURCC_ARGS (pixelformat), *width, *height, fmt.fmt.pix.field);
3087     goto error;
3088   }
3089
3090   ret = TRUE;
3091
3092 error:
3093   if (!ret) {
3094     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3095         "Unable to try format: %s", g_strerror (errno));
3096   }
3097
3098   return ret;
3099 }
3100
3101 static gboolean
3102 gst_v4l2_object_is_dmabuf_supported (GstV4l2Object * v4l2object)
3103 {
3104   gboolean ret = TRUE;
3105   struct v4l2_exportbuffer expbuf = {
3106     .type = v4l2object->type,
3107     .index = -1,
3108     .plane = -1,
3109     .flags = O_CLOEXEC | O_RDWR,
3110   };
3111
3112   if (v4l2object->fmtdesc &&
3113       v4l2object->fmtdesc->flags & V4L2_FMT_FLAG_EMULATED) {
3114     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3115         "libv4l2 converter detected, disabling DMABuf");
3116     ret = FALSE;
3117   }
3118
3119   /* Expected to fail, but ENOTTY tells us that it is not implemented. */
3120   v4l2object->ioctl (v4l2object->video_fd, VIDIOC_EXPBUF, &expbuf);
3121   if (errno == ENOTTY)
3122     ret = FALSE;
3123
3124   return ret;
3125 }
3126
3127 static gboolean
3128 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
3129 {
3130   GstV4l2IOMode mode;
3131
3132   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "initializing the %s system",
3133       V4L2_TYPE_IS_OUTPUT (v4l2object->type) ? "output" : "capture");
3134
3135   GST_V4L2_CHECK_OPEN (v4l2object);
3136   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
3137
3138   /* find transport */
3139   mode = v4l2object->req_mode;
3140
3141   if (v4l2object->device_caps & V4L2_CAP_READWRITE) {
3142     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
3143       mode = GST_V4L2_IO_RW;
3144   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
3145     goto method_not_supported;
3146
3147   if (v4l2object->device_caps & V4L2_CAP_STREAMING) {
3148     if (v4l2object->req_mode == GST_V4L2_IO_AUTO) {
3149       if (!V4L2_TYPE_IS_OUTPUT (v4l2object->type) &&
3150           gst_v4l2_object_is_dmabuf_supported (v4l2object)) {
3151         mode = GST_V4L2_IO_DMABUF;
3152       } else {
3153         mode = GST_V4L2_IO_MMAP;
3154       }
3155     }
3156   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP ||
3157       v4l2object->req_mode == GST_V4L2_IO_DMABUF)
3158     goto method_not_supported;
3159
3160   /* if still no transport selected, error out */
3161   if (mode == GST_V4L2_IO_AUTO)
3162     goto no_supported_capture_method;
3163
3164   GST_INFO_OBJECT (v4l2object->dbg_obj, "accessing buffers via mode %d", mode);
3165   v4l2object->mode = mode;
3166
3167   /* If min_buffers is not set, the driver either does not support the control or
3168      it has not been asked yet via propose_allocation/decide_allocation. */
3169   if (!v4l2object->min_buffers)
3170     gst_v4l2_get_driver_min_buffers (v4l2object);
3171
3172   /* Map the buffers */
3173   GST_LOG_OBJECT (v4l2object->dbg_obj, "initiating buffer pool");
3174
3175   {
3176     GstBufferPool *pool = gst_v4l2_buffer_pool_new (v4l2object, caps);
3177     GST_OBJECT_LOCK (v4l2object->element);
3178     v4l2object->pool = pool;
3179     GST_OBJECT_UNLOCK (v4l2object->element);
3180     if (!pool)
3181       goto buffer_pool_new_failed;
3182   }
3183
3184   GST_V4L2_SET_ACTIVE (v4l2object);
3185
3186   return TRUE;
3187
3188   /* ERRORS */
3189 buffer_pool_new_failed:
3190   {
3191     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
3192         (_("Could not map buffers from device '%s'"),
3193             v4l2object->videodev),
3194         ("Failed to create buffer pool: %s", g_strerror (errno)));
3195     return FALSE;
3196   }
3197 method_not_supported:
3198   {
3199     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
3200         (_("The driver of device '%s' does not support the IO method %d"),
3201             v4l2object->videodev, mode), (NULL));
3202     return FALSE;
3203   }
3204 no_supported_capture_method:
3205   {
3206     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
3207         (_("The driver of device '%s' does not support any known IO "
3208                 "method."), v4l2object->videodev), (NULL));
3209     return FALSE;
3210   }
3211 }
3212
3213 static gboolean
3214 gst_v4l2_object_reset_compose_region (GstV4l2Object * obj)
3215 {
3216   struct v4l2_selection sel = { 0 };
3217
3218   GST_V4L2_CHECK_OPEN (obj);
3219
3220   sel.type = obj->type;
3221   sel.target = V4L2_SEL_TGT_COMPOSE_DEFAULT;
3222
3223   if (obj->ioctl (obj->video_fd, VIDIOC_G_SELECTION, &sel) < 0) {
3224     if (errno == ENOTTY) {
3225       /* No-op when selection API is not supported */
3226       return TRUE;
3227     } else {
3228       GST_WARNING_OBJECT (obj->dbg_obj,
3229           "Failed to get default compose rectangle with VIDIOC_G_SELECTION: %s",
3230           g_strerror (errno));
3231       return FALSE;
3232     }
3233   }
3234
3235   sel.target = V4L2_SEL_TGT_COMPOSE;
3236
3237   if (obj->ioctl (obj->video_fd, VIDIOC_S_SELECTION, &sel) < 0) {
3238     GST_WARNING_OBJECT (obj->dbg_obj,
3239         "Failed to set default compose rectangle with VIDIOC_S_SELECTION: %s",
3240         g_strerror (errno));
3241     return FALSE;
3242   }
3243
3244   return TRUE;
3245 }
3246
3247 static void
3248 gst_v4l2_object_set_stride (GstVideoInfo * info, GstVideoAlignment * align,
3249     gint plane, gint stride)
3250 {
3251   const GstVideoFormatInfo *finfo = info->finfo;
3252
3253   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3254     gint x_tiles, y_tiles, tile_height, padded_height;
3255
3256     tile_height = GST_VIDEO_FORMAT_INFO_TILE_HEIGHT (finfo, plane);
3257
3258     padded_height = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, plane,
3259         info->height + align->padding_top + align->padding_bottom);
3260     padded_height = (padded_height + tile_height - 1) / tile_height;
3261
3262     x_tiles = stride / GST_VIDEO_FORMAT_INFO_TILE_STRIDE (finfo, plane);
3263     y_tiles = padded_height / tile_height;
3264     info->stride[plane] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
3265   } else {
3266     info->stride[plane] = stride;
3267   }
3268 }
3269
3270 static void
3271 gst_v4l2_object_extrapolate_info (GstV4l2Object * v4l2object,
3272     GstVideoInfo * info, GstVideoAlignment * align, gint stride)
3273 {
3274   const GstVideoFormatInfo *finfo = info->finfo;
3275   gint i, estride, padded_height;
3276   gsize offs = 0;
3277
3278   g_return_if_fail (v4l2object->n_v4l2_planes == 1);
3279
3280   padded_height =
3281       GST_VIDEO_INFO_FIELD_HEIGHT (info) + align->padding_top +
3282       align->padding_bottom;
3283
3284   for (i = 0; i < finfo->n_planes; i++) {
3285     estride = gst_video_format_info_extrapolate_stride (finfo, i, stride);
3286
3287     gst_v4l2_object_set_stride (info, align, i, estride);
3288
3289     info->offset[i] = offs;
3290     offs += estride *
3291         GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, padded_height);
3292
3293     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
3294         "Extrapolated for plane %d with base stride %d: "
3295         "stride %d, offset %" G_GSIZE_FORMAT, i, stride, info->stride[i],
3296         info->offset[i]);
3297   }
3298
3299   /* Update the image size according the amount of data we are going to
3300    * read/write. This workaround bugs in driver where the sizeimage provided
3301    * by TRY/S_FMT represent the buffer length (maximum size) rather then the expected
3302    * bytesused (buffer size). */
3303   if (offs < info->size)
3304     info->size = offs;
3305 }
3306
3307 static void
3308 gst_v4l2_object_save_format (GstV4l2Object * v4l2object,
3309     struct v4l2_fmtdesc *fmtdesc, struct v4l2_format *format,
3310     GstVideoInfo * info, GstVideoAlignment * align)
3311 {
3312   const GstVideoFormatInfo *finfo = info->finfo;
3313   gboolean standard_stride = TRUE;
3314   gint stride, pstride, padded_width, padded_height, i;
3315
3316   if (GST_VIDEO_INFO_FORMAT (info) == GST_VIDEO_FORMAT_ENCODED) {
3317     v4l2object->n_v4l2_planes = 1;
3318     info->size = format->fmt.pix.sizeimage;
3319     goto store_info;
3320   }
3321
3322   /* adjust right padding */
3323   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
3324     stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
3325   else
3326     stride = format->fmt.pix.bytesperline;
3327
3328   pstride = GST_VIDEO_FORMAT_INFO_PSTRIDE (finfo, 0);
3329   if (pstride) {
3330     padded_width = stride / pstride;
3331   } else {
3332     /* pstride can be 0 for complex formats */
3333     GST_WARNING_OBJECT (v4l2object->element,
3334         "format %s has a pstride of 0, cannot compute padded with",
3335         gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (info)));
3336     padded_width = stride;
3337   }
3338
3339   if (padded_width < format->fmt.pix.width)
3340     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3341         "Driver bug detected, stride (%d) is too small for the width (%d)",
3342         padded_width, format->fmt.pix.width);
3343
3344   align->padding_right = padded_width - info->width - align->padding_left;
3345
3346   /* adjust bottom padding */
3347   padded_height = format->fmt.pix.height;
3348
3349   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3350     guint tile_height;
3351     tile_height = GST_VIDEO_FORMAT_INFO_TILE_HEIGHT (finfo, 0);
3352     padded_height = (padded_height + tile_height - 1) / tile_height;
3353   }
3354
3355   align->padding_bottom =
3356       padded_height - GST_VIDEO_INFO_FIELD_HEIGHT (info) - align->padding_top;
3357
3358   /* setup the strides and offset */
3359   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type)) {
3360     struct v4l2_pix_format_mplane *pix_mp = &format->fmt.pix_mp;
3361
3362     /* figure out the frame layout */
3363     v4l2object->n_v4l2_planes = MAX (1, pix_mp->num_planes);
3364     info->size = 0;
3365     for (i = 0; i < v4l2object->n_v4l2_planes; i++) {
3366       stride = pix_mp->plane_fmt[i].bytesperline;
3367
3368       if (info->stride[i] != stride)
3369         standard_stride = FALSE;
3370
3371       gst_v4l2_object_set_stride (info, align, i, stride);
3372       info->offset[i] = info->size;
3373       info->size += pix_mp->plane_fmt[i].sizeimage;
3374     }
3375
3376     /* Extrapolate stride if planar format are being set in 1 v4l2 plane */
3377     if (v4l2object->n_v4l2_planes < finfo->n_planes) {
3378       stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
3379       gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
3380     }
3381   } else {
3382     /* only one plane in non-MPLANE mode */
3383     v4l2object->n_v4l2_planes = 1;
3384     info->size = format->fmt.pix.sizeimage;
3385     stride = format->fmt.pix.bytesperline;
3386
3387     if (info->stride[0] != stride)
3388       standard_stride = FALSE;
3389
3390     gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
3391   }
3392
3393   /* adjust the offset to take into account left and top */
3394   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3395     if ((align->padding_left + align->padding_top) > 0)
3396       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3397           "Left and top padding is not permitted for tiled formats");
3398   } else {
3399     for (i = 0; i < finfo->n_planes; i++) {
3400       gint vedge, hedge;
3401
3402       /* FIXME we assume plane as component as this is true for all supported
3403        * format we support. */
3404
3405       hedge = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, align->padding_left);
3406       vedge = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, align->padding_top);
3407
3408       info->offset[i] += (vedge * info->stride[i]) +
3409           (hedge * GST_VIDEO_INFO_COMP_PSTRIDE (info, i));
3410     }
3411   }
3412
3413 store_info:
3414   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got sizeimage %" G_GSIZE_FORMAT,
3415       info->size);
3416
3417   /* to avoid copies we need video meta if there is padding */
3418   v4l2object->need_video_meta =
3419       ((align->padding_top + align->padding_left + align->padding_right +
3420           align->padding_bottom) != 0);
3421
3422   /* ... or if stride is non "standard" */
3423   if (!standard_stride)
3424     v4l2object->need_video_meta = TRUE;
3425
3426   /* ... or also video meta if we use multiple, non-contiguous, planes */
3427   if (v4l2object->n_v4l2_planes > 1)
3428     v4l2object->need_video_meta = TRUE;
3429
3430   v4l2object->info = *info;
3431   v4l2object->align = *align;
3432   v4l2object->format = *format;
3433   v4l2object->fmtdesc = fmtdesc;
3434
3435   /* if we have a framerate pre-calculate duration */
3436   if (info->fps_n > 0 && info->fps_d > 0) {
3437     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, info->fps_d,
3438         info->fps_n);
3439     if (GST_VIDEO_INFO_INTERLACE_MODE (info) ==
3440         GST_VIDEO_INTERLACE_MODE_ALTERNATE)
3441       v4l2object->duration /= 2;
3442   } else {
3443     v4l2object->duration = GST_CLOCK_TIME_NONE;
3444   }
3445 }
3446
3447 static enum v4l2_field
3448 get_v4l2_field_for_info (GstVideoInfo * info)
3449 {
3450   if (!GST_VIDEO_INFO_IS_INTERLACED (info))
3451     return V4L2_FIELD_NONE;
3452
3453   if (GST_VIDEO_INFO_INTERLACE_MODE (info) ==
3454       GST_VIDEO_INTERLACE_MODE_ALTERNATE)
3455     return V4L2_FIELD_ALTERNATE;
3456
3457   switch (GST_VIDEO_INFO_FIELD_ORDER (info)) {
3458     case GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST:
3459       return V4L2_FIELD_INTERLACED_TB;
3460     case GST_VIDEO_FIELD_ORDER_BOTTOM_FIELD_FIRST:
3461       return V4L2_FIELD_INTERLACED_BT;
3462     case GST_VIDEO_FIELD_ORDER_UNKNOWN:
3463     default:
3464       return V4L2_FIELD_INTERLACED;
3465   }
3466 }
3467
3468 static gboolean
3469 gst_v4l2_video_colorimetry_matches (const GstVideoColorimetry * cinfo,
3470     GstCaps * caps)
3471 {
3472   GstVideoInfo info;
3473   static const GstVideoColorimetry ci_likely_jpeg = {
3474     GST_VIDEO_COLOR_RANGE_0_255, GST_VIDEO_COLOR_MATRIX_BT601,
3475     GST_VIDEO_TRANSFER_UNKNOWN, GST_VIDEO_COLOR_PRIMARIES_UNKNOWN
3476   };
3477   static const GstVideoColorimetry ci_jpeg = {
3478     GST_VIDEO_COLOR_RANGE_0_255, GST_VIDEO_COLOR_MATRIX_BT601,
3479     GST_VIDEO_TRANSFER_SRGB, GST_VIDEO_COLOR_PRIMARIES_BT709
3480   };
3481
3482   if (!gst_video_info_from_caps (&info, caps))
3483     return FALSE;
3484
3485   /* if colorimetry in caps is unknown, use the default one */
3486   if (info.colorimetry.primaries == GST_VIDEO_COLOR_PRIMARIES_UNKNOWN)
3487     info.colorimetry.primaries = cinfo->primaries;
3488   if (info.colorimetry.range == GST_VIDEO_COLOR_RANGE_UNKNOWN)
3489     info.colorimetry.range = cinfo->range;
3490   if (info.colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_UNKNOWN)
3491     info.colorimetry.matrix = cinfo->matrix;
3492   if (info.colorimetry.transfer == GST_VIDEO_TRANSFER_UNKNOWN)
3493     info.colorimetry.transfer = cinfo->transfer;
3494
3495   if (gst_video_colorimetry_is_equal (&info.colorimetry, cinfo))
3496     return TRUE;
3497
3498   /* Allow 1:4:0:0 (produced by jpegdec) if the device expects 1:4:7:1 */
3499   if (gst_video_colorimetry_is_equal (&info.colorimetry, &ci_likely_jpeg)
3500       && gst_video_colorimetry_is_equal (cinfo, &ci_jpeg))
3501     return TRUE;
3502
3503   /* bypass check the below transfer types, because those types are cast to
3504    * V4L2_XFER_FUNC_NONE type when try format or set format and V4L2_XFER_FUNC_NONE
3505    * type is cast to GST_VIDEO_TRANSFER_GAMMA10 type in gst_v4l2_object_get_colorspace */
3506   if ((info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA18) ||
3507       (info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA20) ||
3508       (info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA22) ||
3509       (info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA28)) {
3510     info.colorimetry.transfer = GST_VIDEO_TRANSFER_GAMMA10;
3511     if (gst_video_colorimetry_is_equal (&info.colorimetry, cinfo))
3512       return TRUE;
3513   }
3514
3515   return FALSE;
3516 }
3517
3518 static const gchar *
3519 field_to_str (enum v4l2_field f)
3520 {
3521   switch (f) {
3522     case V4L2_FIELD_ANY:
3523       return "any";
3524     case V4L2_FIELD_NONE:
3525       return "none";
3526     case V4L2_FIELD_TOP:
3527       return "top";
3528     case V4L2_FIELD_BOTTOM:
3529       return "bottom";
3530     case V4L2_FIELD_INTERLACED:
3531       return "interlaced";
3532     case V4L2_FIELD_SEQ_TB:
3533       return "seq-tb";
3534     case V4L2_FIELD_SEQ_BT:
3535       return "seq-bt";
3536     case V4L2_FIELD_ALTERNATE:
3537       return "alternate";
3538     case V4L2_FIELD_INTERLACED_TB:
3539       return "interlaced-tb";
3540     case V4L2_FIELD_INTERLACED_BT:
3541       return "interlaced-bt";
3542   }
3543
3544   return "unknown";
3545 }
3546
3547 static gboolean
3548 gst_v4l2_object_set_format_full (GstV4l2Object * v4l2object, GstCaps * caps,
3549     gboolean try_only, GstV4l2Error * error)
3550 {
3551   gint fd = v4l2object->video_fd;
3552   struct v4l2_format format;
3553   struct v4l2_streamparm streamparm;
3554   enum v4l2_field field;
3555   guint32 pixelformat;
3556   struct v4l2_fmtdesc *fmtdesc;
3557   GstVideoInfo info;
3558   GstVideoAlignment align;
3559   gint width, height, fps_n, fps_d;
3560   gint n_v4l_planes;
3561   gint i = 0;
3562   gboolean is_mplane;
3563   enum v4l2_colorspace colorspace = 0;
3564   enum v4l2_quantization range = 0;
3565   enum v4l2_ycbcr_encoding matrix = 0;
3566   enum v4l2_xfer_func transfer = 0;
3567   GstStructure *s;
3568   gboolean disable_interlacing = FALSE;
3569   gboolean disable_colorimetry = FALSE;
3570
3571   g_return_val_if_fail (!v4l2object->skip_try_fmt_probes ||
3572       gst_caps_is_writable (caps), FALSE);
3573
3574   GST_V4L2_CHECK_OPEN (v4l2object);
3575   if (!try_only)
3576     GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
3577
3578   is_mplane = V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type);
3579
3580   gst_video_info_init (&info);
3581   gst_video_alignment_reset (&align);
3582   v4l2object->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
3583
3584   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
3585     goto invalid_caps;
3586
3587   pixelformat = fmtdesc->pixelformat;
3588   width = GST_VIDEO_INFO_WIDTH (&info);
3589   height = GST_VIDEO_INFO_FIELD_HEIGHT (&info);
3590   /* if caps has no width and height info, use default value */
3591   if (V4L2_TYPE_IS_OUTPUT (v4l2object->type) && width == 0 && height == 0) {
3592     width = GST_V4L2_DEFAULT_WIDTH;
3593     height = GST_V4L2_DEFAULT_HEIGHT;
3594   }
3595   fps_n = GST_VIDEO_INFO_FPS_N (&info);
3596   fps_d = GST_VIDEO_INFO_FPS_D (&info);
3597
3598   /* if encoded format (GST_VIDEO_INFO_N_PLANES return 0)
3599    * or if contiguous is preferred */
3600   n_v4l_planes = GST_VIDEO_INFO_N_PLANES (&info);
3601   if (!n_v4l_planes || !v4l2object->prefered_non_contiguous)
3602     n_v4l_planes = 1;
3603
3604   field = get_v4l2_field_for_info (&info);
3605   if (field != V4L2_FIELD_NONE)
3606     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
3607   else
3608     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
3609
3610   /* We first pick the main colorspace from the primaries */
3611   switch (info.colorimetry.primaries) {
3612     case GST_VIDEO_COLOR_PRIMARIES_BT709:
3613       /* There is two colorspaces using these primaries, use the range to
3614        * differentiate */
3615       if (info.colorimetry.range == GST_VIDEO_COLOR_RANGE_16_235)
3616         colorspace = V4L2_COLORSPACE_REC709;
3617       else
3618         colorspace = V4L2_COLORSPACE_SRGB;
3619       break;
3620     case GST_VIDEO_COLOR_PRIMARIES_BT2020:
3621       colorspace = V4L2_COLORSPACE_BT2020;
3622       break;
3623     case GST_VIDEO_COLOR_PRIMARIES_BT470M:
3624       colorspace = V4L2_COLORSPACE_470_SYSTEM_M;
3625       break;
3626     case GST_VIDEO_COLOR_PRIMARIES_BT470BG:
3627       colorspace = V4L2_COLORSPACE_470_SYSTEM_BG;
3628       break;
3629     case GST_VIDEO_COLOR_PRIMARIES_SMPTE170M:
3630       colorspace = V4L2_COLORSPACE_SMPTE170M;
3631       break;
3632     case GST_VIDEO_COLOR_PRIMARIES_SMPTE240M:
3633       colorspace = V4L2_COLORSPACE_SMPTE240M;
3634       break;
3635
3636     case GST_VIDEO_COLOR_PRIMARIES_FILM:
3637     case GST_VIDEO_COLOR_PRIMARIES_UNKNOWN:
3638       /* We don't know, we will guess */
3639       break;
3640
3641     default:
3642       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3643           "Unknown colorimetry primaries %d", info.colorimetry.primaries);
3644       break;
3645   }
3646
3647   switch (info.colorimetry.range) {
3648     case GST_VIDEO_COLOR_RANGE_0_255:
3649       range = V4L2_QUANTIZATION_FULL_RANGE;
3650       break;
3651     case GST_VIDEO_COLOR_RANGE_16_235:
3652       range = V4L2_QUANTIZATION_LIM_RANGE;
3653       break;
3654     case GST_VIDEO_COLOR_RANGE_UNKNOWN:
3655       /* We let the driver pick a default one */
3656       break;
3657     default:
3658       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3659           "Unknown colorimetry range %d", info.colorimetry.range);
3660       break;
3661   }
3662
3663   switch (info.colorimetry.matrix) {
3664     case GST_VIDEO_COLOR_MATRIX_RGB:
3665       /* Unspecified, leave to default */
3666       break;
3667       /* FCC is about the same as BT601 with less digit */
3668     case GST_VIDEO_COLOR_MATRIX_FCC:
3669     case GST_VIDEO_COLOR_MATRIX_BT601:
3670       matrix = V4L2_YCBCR_ENC_601;
3671       break;
3672     case GST_VIDEO_COLOR_MATRIX_BT709:
3673       matrix = V4L2_YCBCR_ENC_709;
3674       break;
3675     case GST_VIDEO_COLOR_MATRIX_SMPTE240M:
3676       matrix = V4L2_YCBCR_ENC_SMPTE240M;
3677       break;
3678     case GST_VIDEO_COLOR_MATRIX_BT2020:
3679       matrix = V4L2_YCBCR_ENC_BT2020;
3680       break;
3681     case GST_VIDEO_COLOR_MATRIX_UNKNOWN:
3682       /* We let the driver pick a default one */
3683       break;
3684     default:
3685       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3686           "Unknown colorimetry matrix %d", info.colorimetry.matrix);
3687       break;
3688   }
3689
3690   switch (info.colorimetry.transfer) {
3691     case GST_VIDEO_TRANSFER_GAMMA18:
3692     case GST_VIDEO_TRANSFER_GAMMA20:
3693     case GST_VIDEO_TRANSFER_GAMMA22:
3694     case GST_VIDEO_TRANSFER_GAMMA28:
3695       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3696           "GAMMA 18, 20, 22, 28 transfer functions not supported");
3697       /* fallthrough */
3698     case GST_VIDEO_TRANSFER_GAMMA10:
3699       transfer = V4L2_XFER_FUNC_NONE;
3700       break;
3701     case GST_VIDEO_TRANSFER_SMPTE2084:
3702       transfer = V4L2_XFER_FUNC_SMPTE2084;
3703       break;
3704     case GST_VIDEO_TRANSFER_BT601:
3705     case GST_VIDEO_TRANSFER_BT2020_12:
3706     case GST_VIDEO_TRANSFER_BT2020_10:
3707     case GST_VIDEO_TRANSFER_BT709:
3708       v4l2object->transfer = info.colorimetry.transfer;
3709       transfer = V4L2_XFER_FUNC_709;
3710       break;
3711     case GST_VIDEO_TRANSFER_SMPTE240M:
3712       transfer = V4L2_XFER_FUNC_SMPTE240M;
3713       break;
3714     case GST_VIDEO_TRANSFER_SRGB:
3715       transfer = V4L2_XFER_FUNC_SRGB;
3716       break;
3717     case GST_VIDEO_TRANSFER_LOG100:
3718     case GST_VIDEO_TRANSFER_LOG316:
3719       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3720           "LOG 100, 316 transfer functions not supported");
3721       /* FIXME No known sensible default, maybe AdobeRGB ? */
3722       break;
3723     case GST_VIDEO_TRANSFER_UNKNOWN:
3724       /* We let the driver pick a default one */
3725       break;
3726     default:
3727       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3728           "Unknown colorimetry transfer %d", info.colorimetry.transfer);
3729       break;
3730   }
3731
3732   if (colorspace == 0) {
3733     /* Try to guess colorspace according to pixelformat and size */
3734     if (GST_VIDEO_INFO_IS_YUV (&info)) {
3735       if (range == V4L2_QUANTIZATION_FULL_RANGE
3736           && matrix == V4L2_YCBCR_ENC_601 && transfer == 0) {
3737         /* Full range BT.601 YCbCr encoding with unknown primaries and transfer
3738          * function most likely is JPEG */
3739         colorspace = V4L2_COLORSPACE_JPEG;
3740         transfer = V4L2_XFER_FUNC_SRGB;
3741       } else {
3742         /* SD streams likely use SMPTE170M and HD streams REC709 */
3743         if (width <= 720 && GST_VIDEO_INFO_HEIGHT (&info) <= 576)
3744           colorspace = V4L2_COLORSPACE_SMPTE170M;
3745         else
3746           colorspace = V4L2_COLORSPACE_REC709;
3747       }
3748     } else if (GST_VIDEO_INFO_IS_RGB (&info)) {
3749       colorspace = V4L2_COLORSPACE_SRGB;
3750       transfer = V4L2_XFER_FUNC_NONE;
3751     }
3752   }
3753
3754   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired format %dx%d, format "
3755       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
3756       GST_FOURCC_ARGS (pixelformat), GST_VIDEO_INFO_PLANE_STRIDE (&info, 0));
3757
3758   memset (&format, 0x00, sizeof (struct v4l2_format));
3759   format.type = v4l2object->type;
3760
3761   if (is_mplane) {
3762     format.type = v4l2object->type;
3763     format.fmt.pix_mp.pixelformat = pixelformat;
3764     format.fmt.pix_mp.width = width;
3765     format.fmt.pix_mp.height = height;
3766     format.fmt.pix_mp.field = field;
3767     format.fmt.pix_mp.num_planes = n_v4l_planes;
3768
3769     /* try to ask our preferred stride but it's not a failure if not
3770      * accepted */
3771     for (i = 0; i < n_v4l_planes; i++) {
3772       gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, i);
3773
3774       if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
3775         stride = GST_VIDEO_TILE_X_TILES (stride) *
3776             GST_VIDEO_FORMAT_INFO_TILE_STRIDE (info.finfo, i);
3777
3778       format.fmt.pix_mp.plane_fmt[i].bytesperline = stride;
3779     }
3780
3781     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
3782       format.fmt.pix_mp.plane_fmt[0].sizeimage = ENCODED_BUFFER_SIZE;
3783   } else {
3784     gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
3785
3786     format.type = v4l2object->type;
3787
3788     format.fmt.pix.width = width;
3789     format.fmt.pix.height = height;
3790     format.fmt.pix.pixelformat = pixelformat;
3791     format.fmt.pix.field = field;
3792
3793     if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
3794       stride = GST_VIDEO_TILE_X_TILES (stride) *
3795           GST_VIDEO_FORMAT_INFO_TILE_STRIDE (info.finfo, i);
3796
3797     /* try to ask our preferred stride */
3798     format.fmt.pix.bytesperline = stride;
3799
3800     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
3801       format.fmt.pix.sizeimage = ENCODED_BUFFER_SIZE;
3802   }
3803
3804   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired format is %dx%d, format "
3805       "%" GST_FOURCC_FORMAT ", nb planes %d", format.fmt.pix.width,
3806       format.fmt.pix_mp.height,
3807       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
3808       is_mplane ? format.fmt.pix_mp.num_planes : 1);
3809
3810 #ifndef GST_DISABLE_GST_DEBUG
3811   if (is_mplane) {
3812     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
3813       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d",
3814           format.fmt.pix_mp.plane_fmt[i].bytesperline);
3815   } else {
3816     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d",
3817         format.fmt.pix.bytesperline);
3818   }
3819 #endif
3820
3821   if (is_mplane) {
3822     format.fmt.pix_mp.colorspace = colorspace;
3823     format.fmt.pix_mp.quantization = range;
3824     format.fmt.pix_mp.ycbcr_enc = matrix;
3825     format.fmt.pix_mp.xfer_func = transfer;
3826   } else {
3827     format.fmt.pix.priv = V4L2_PIX_FMT_PRIV_MAGIC;
3828     format.fmt.pix.colorspace = colorspace;
3829     format.fmt.pix.quantization = range;
3830     format.fmt.pix.ycbcr_enc = matrix;
3831     format.fmt.pix.xfer_func = transfer;
3832   }
3833
3834   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired colorspace is %d:%d:%d:%d",
3835       colorspace, range, matrix, transfer);
3836
3837   if (try_only) {
3838     if (v4l2object->ioctl (fd, VIDIOC_TRY_FMT, &format) < 0)
3839       goto try_fmt_failed;
3840   } else {
3841     if (v4l2object->ioctl (fd, VIDIOC_S_FMT, &format) < 0)
3842       goto set_fmt_failed;
3843   }
3844
3845   if (is_mplane) {
3846     colorspace = format.fmt.pix_mp.colorspace;
3847     range = format.fmt.pix_mp.quantization;
3848     matrix = format.fmt.pix_mp.ycbcr_enc;
3849     transfer = format.fmt.pix_mp.xfer_func;
3850   } else {
3851     colorspace = format.fmt.pix.colorspace;
3852     range = format.fmt.pix.quantization;
3853     matrix = format.fmt.pix.ycbcr_enc;
3854     transfer = format.fmt.pix.xfer_func;
3855   }
3856
3857   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got format of %dx%d, format "
3858       "%" GST_FOURCC_FORMAT ", nb planes %d, colorspace %d:%d:%d:%d field: %s",
3859       format.fmt.pix.width, format.fmt.pix_mp.height,
3860       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
3861       is_mplane ? format.fmt.pix_mp.num_planes : 1,
3862       colorspace, range, matrix, transfer, field_to_str (format.fmt.pix.field));
3863
3864 #ifndef GST_DISABLE_GST_DEBUG
3865   if (is_mplane) {
3866     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
3867       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d, sizeimage %d",
3868           format.fmt.pix_mp.plane_fmt[i].bytesperline,
3869           format.fmt.pix_mp.plane_fmt[i].sizeimage);
3870   } else {
3871     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d, sizeimage %d",
3872         format.fmt.pix.bytesperline, format.fmt.pix.sizeimage);
3873   }
3874 #endif
3875
3876   if (format.fmt.pix.pixelformat != pixelformat)
3877     goto invalid_pixelformat;
3878
3879   /* Only negotiate size with raw data.
3880    * For some codecs the dimensions are *not* in the bitstream, IIRC VC1
3881    * in ASF mode for example, there is also not reason for a driver to
3882    * change the size. */
3883   if (info.finfo->format != GST_VIDEO_FORMAT_ENCODED) {
3884     /* We can crop larger images */
3885     if (format.fmt.pix.width < width || format.fmt.pix.height < height)
3886       goto invalid_dimensions;
3887
3888     /* Note, this will be adjusted if upstream has non-centered cropping. */
3889     align.padding_top = 0;
3890     align.padding_bottom = format.fmt.pix.height - height;
3891     align.padding_left = 0;
3892     align.padding_right = format.fmt.pix.width - width;
3893   }
3894
3895   if (is_mplane && format.fmt.pix_mp.num_planes != n_v4l_planes)
3896     goto invalid_planes;
3897
3898   /* used to check colorimetry and interlace mode fields presence */
3899   s = gst_caps_get_structure (caps, 0);
3900
3901   if (gst_v4l2_object_get_interlace_mode (format.fmt.pix.field,
3902           &info.interlace_mode)) {
3903     if (gst_structure_has_field (s, "interlace-mode")) {
3904       if (format.fmt.pix.field != field)
3905         goto invalid_field;
3906     }
3907   } else {
3908     /* The driver (or libv4l2) is miss-behaving, just ignore interlace-mode from
3909      * the TRY_FMT */
3910     disable_interlacing = TRUE;
3911     if (gst_structure_has_field (s, "interlace-mode"))
3912       gst_structure_remove_field (s, "interlace-mode");
3913   }
3914
3915   if (gst_v4l2_object_get_colorspace (v4l2object, &format, &info.colorimetry)) {
3916     if (gst_structure_has_field (s, "colorimetry")) {
3917       if (!gst_v4l2_video_colorimetry_matches (&info.colorimetry, caps))
3918         goto invalid_colorimetry;
3919     }
3920   } else {
3921     /* The driver (or libv4l2) is miss-behaving, just ignore colorimetry from
3922      * the TRY_FMT */
3923     disable_colorimetry = TRUE;
3924     if (gst_structure_has_field (s, "colorimetry"))
3925       gst_structure_remove_field (s, "colorimetry");
3926   }
3927
3928   /* In case we have skipped the try_fmt probes, we'll need to set the
3929    * interlace-mode and colorimetry back into the caps. */
3930   if (v4l2object->skip_try_fmt_probes) {
3931     if (!disable_interlacing && !gst_structure_has_field (s, "interlace-mode")) {
3932       gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
3933           gst_video_interlace_mode_to_string (info.interlace_mode), NULL);
3934     }
3935     if (!disable_colorimetry && !gst_structure_has_field (s, "colorimetry")) {
3936       gchar *str = gst_video_colorimetry_to_string (&info.colorimetry);
3937       gst_structure_set (s, "colorimetry", G_TYPE_STRING, str, NULL);
3938       g_free (str);
3939     }
3940   }
3941
3942   if (try_only)                 /* good enough for trying only */
3943     return TRUE;
3944
3945   if (GST_VIDEO_INFO_HAS_ALPHA (&info)) {
3946     struct v4l2_control ctl = { 0, };
3947     ctl.id = V4L2_CID_ALPHA_COMPONENT;
3948     ctl.value = 0xff;
3949
3950     if (v4l2object->ioctl (fd, VIDIOC_S_CTRL, &ctl) < 0)
3951       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3952           "Failed to set alpha component value");
3953   }
3954
3955   /* Is there a reason we require the caller to always specify a framerate? */
3956   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired framerate: %u/%u", fps_n,
3957       fps_d);
3958
3959   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
3960   streamparm.type = v4l2object->type;
3961
3962   if (v4l2object->ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
3963     goto get_parm_failed;
3964
3965   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
3966       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
3967     GST_VIDEO_INFO_FPS_N (&info) =
3968         streamparm.parm.capture.timeperframe.denominator;
3969     GST_VIDEO_INFO_FPS_D (&info) =
3970         streamparm.parm.capture.timeperframe.numerator;
3971
3972     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got capture framerate: %u/%u",
3973         streamparm.parm.capture.timeperframe.denominator,
3974         streamparm.parm.capture.timeperframe.numerator);
3975
3976     /* We used to skip frame rate setup if the camera was already setup
3977      * with the requested frame rate. This breaks some cameras though,
3978      * causing them to not output data (several models of Thinkpad cameras
3979      * have this problem at least).
3980      * So, don't skip. */
3981     GST_LOG_OBJECT (v4l2object->dbg_obj, "Setting capture framerate to %u/%u",
3982         fps_n, fps_d);
3983     /* We want to change the frame rate, so check whether we can. Some cheap USB
3984      * cameras don't have the capability */
3985     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
3986       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
3987           "Not setting capture framerate (not supported)");
3988       goto done;
3989     }
3990
3991     /* Note: V4L2 wants the frame interval, we have the frame rate */
3992     streamparm.parm.capture.timeperframe.numerator = fps_d;
3993     streamparm.parm.capture.timeperframe.denominator = fps_n;
3994
3995     /* some cheap USB cam's won't accept any change */
3996     if (v4l2object->ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
3997       goto set_parm_failed;
3998
3999     if (streamparm.parm.capture.timeperframe.numerator > 0 &&
4000         streamparm.parm.capture.timeperframe.denominator > 0) {
4001       /* get new values */
4002       fps_d = streamparm.parm.capture.timeperframe.numerator;
4003       fps_n = streamparm.parm.capture.timeperframe.denominator;
4004
4005       GST_INFO_OBJECT (v4l2object->dbg_obj, "Set capture framerate to %u/%u",
4006           fps_n, fps_d);
4007     } else {
4008       /* fix v4l2 capture driver to provide framerate values */
4009       GST_WARNING_OBJECT (v4l2object->dbg_obj,
4010           "Reuse caps framerate %u/%u - fix v4l2 capture driver", fps_n, fps_d);
4011     }
4012
4013     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
4014     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
4015   } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT
4016       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
4017     GST_VIDEO_INFO_FPS_N (&info) =
4018         streamparm.parm.output.timeperframe.denominator;
4019     GST_VIDEO_INFO_FPS_D (&info) =
4020         streamparm.parm.output.timeperframe.numerator;
4021
4022     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got output framerate: %u/%u",
4023         streamparm.parm.output.timeperframe.denominator,
4024         streamparm.parm.output.timeperframe.numerator);
4025
4026     GST_LOG_OBJECT (v4l2object->dbg_obj, "Setting output framerate to %u/%u",
4027         fps_n, fps_d);
4028     if ((streamparm.parm.output.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
4029       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4030           "Not setting output framerate (not supported)");
4031       goto done;
4032     }
4033
4034     /* Note: V4L2 wants the frame interval, we have the frame rate */
4035     streamparm.parm.output.timeperframe.numerator = fps_d;
4036     streamparm.parm.output.timeperframe.denominator = fps_n;
4037
4038     if (v4l2object->ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
4039       goto set_parm_failed;
4040
4041     if (streamparm.parm.output.timeperframe.numerator > 0 &&
4042         streamparm.parm.output.timeperframe.denominator > 0) {
4043       /* get new values */
4044       fps_d = streamparm.parm.output.timeperframe.numerator;
4045       fps_n = streamparm.parm.output.timeperframe.denominator;
4046
4047       GST_INFO_OBJECT (v4l2object->dbg_obj, "Set output framerate to %u/%u",
4048           fps_n, fps_d);
4049     } else {
4050       /* fix v4l2 output driver to provide framerate values */
4051       GST_WARNING_OBJECT (v4l2object->dbg_obj,
4052           "Reuse caps framerate %u/%u - fix v4l2 output driver", fps_n, fps_d);
4053     }
4054
4055     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
4056     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
4057   }
4058
4059 done:
4060   /* add boolean return, so we can fail on drivers bugs */
4061   gst_v4l2_object_save_format (v4l2object, fmtdesc, &format, &info, &align);
4062
4063   /* reset composition region to match the S_FMT size */
4064   gst_v4l2_object_reset_compose_region (v4l2object);
4065
4066   /* now configure the pool */
4067   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
4068     goto pool_failed;
4069
4070   return TRUE;
4071
4072   /* ERRORS */
4073 invalid_caps:
4074   {
4075     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "can't parse caps %" GST_PTR_FORMAT,
4076         caps);
4077
4078     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4079         (_("Invalid caps")), ("Can't parse caps %" GST_PTR_FORMAT, caps));
4080     return FALSE;
4081   }
4082 try_fmt_failed:
4083   {
4084     if (errno == EINVAL) {
4085       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4086           (_("Device '%s' has no supported format"), v4l2object->videodev),
4087           ("Call to TRY_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4088               GST_FOURCC_ARGS (pixelformat), width, height,
4089               g_strerror (errno)));
4090     } else {
4091       GST_V4L2_ERROR (error, RESOURCE, FAILED,
4092           (_("Device '%s' failed during initialization"),
4093               v4l2object->videodev),
4094           ("Call to TRY_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4095               GST_FOURCC_ARGS (pixelformat), width, height,
4096               g_strerror (errno)));
4097     }
4098     return FALSE;
4099   }
4100 set_fmt_failed:
4101   {
4102     if (errno == EBUSY) {
4103       GST_V4L2_ERROR (error, RESOURCE, BUSY,
4104           (_("Device '%s' is busy"), v4l2object->videodev),
4105           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4106               GST_FOURCC_ARGS (pixelformat), width, height,
4107               g_strerror (errno)));
4108     } else if (errno == EINVAL) {
4109       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4110           (_("Device '%s' has no supported format"), v4l2object->videodev),
4111           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4112               GST_FOURCC_ARGS (pixelformat), width, height,
4113               g_strerror (errno)));
4114     } else {
4115       GST_V4L2_ERROR (error, RESOURCE, FAILED,
4116           (_("Device '%s' failed during initialization"),
4117               v4l2object->videodev),
4118           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4119               GST_FOURCC_ARGS (pixelformat), width, height,
4120               g_strerror (errno)));
4121     }
4122     return FALSE;
4123   }
4124 invalid_dimensions:
4125   {
4126     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4127         (_("Device '%s' cannot capture at %dx%d"),
4128             v4l2object->videodev, width, height),
4129         ("Tried to capture at %dx%d, but device returned size %dx%d",
4130             width, height, format.fmt.pix.width, format.fmt.pix.height));
4131     return FALSE;
4132   }
4133 invalid_pixelformat:
4134   {
4135     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4136         (_("Device '%s' cannot capture in the specified format"),
4137             v4l2object->videodev),
4138         ("Tried to capture in %" GST_FOURCC_FORMAT
4139             ", but device returned format" " %" GST_FOURCC_FORMAT,
4140             GST_FOURCC_ARGS (pixelformat),
4141             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
4142     return FALSE;
4143   }
4144 invalid_planes:
4145   {
4146     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4147         (_("Device '%s' does support non-contiguous planes"),
4148             v4l2object->videodev),
4149         ("Device wants %d planes", format.fmt.pix_mp.num_planes));
4150     return FALSE;
4151   }
4152 invalid_field:
4153   {
4154     enum v4l2_field wanted_field;
4155
4156     if (is_mplane)
4157       wanted_field = format.fmt.pix_mp.field;
4158     else
4159       wanted_field = format.fmt.pix.field;
4160
4161     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4162         (_("Device '%s' does not support %s interlacing"),
4163             v4l2object->videodev,
4164             field == V4L2_FIELD_NONE ? "progressive" : "interleaved"),
4165         ("Device wants %s interlacing",
4166             wanted_field == V4L2_FIELD_NONE ? "progressive" : "interleaved"));
4167     return FALSE;
4168   }
4169 invalid_colorimetry:
4170   {
4171     gchar *wanted_colorimetry;
4172
4173     wanted_colorimetry = gst_video_colorimetry_to_string (&info.colorimetry);
4174
4175     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4176         (_("Device '%s' does not support %s colorimetry"),
4177             v4l2object->videodev, gst_structure_get_string (s, "colorimetry")),
4178         ("Device wants %s colorimetry", wanted_colorimetry));
4179
4180     g_free (wanted_colorimetry);
4181     return FALSE;
4182   }
4183 get_parm_failed:
4184   {
4185     /* it's possible that this call is not supported */
4186     if (errno != EINVAL && errno != ENOTTY) {
4187       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4188           (_("Could not get parameters on device '%s'"),
4189               v4l2object->videodev), GST_ERROR_SYSTEM);
4190     }
4191     goto done;
4192   }
4193 set_parm_failed:
4194   {
4195     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4196         (_("Video device did not accept new frame rate setting.")),
4197         GST_ERROR_SYSTEM);
4198     goto done;
4199   }
4200 pool_failed:
4201   {
4202     /* setup_pool already send the error */
4203     return FALSE;
4204   }
4205 }
4206
4207 gboolean
4208 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps,
4209     GstV4l2Error * error)
4210 {
4211   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Setting format to %" GST_PTR_FORMAT,
4212       caps);
4213   return gst_v4l2_object_set_format_full (v4l2object, caps, FALSE, error);
4214 }
4215
4216 gboolean
4217 gst_v4l2_object_try_format (GstV4l2Object * v4l2object, GstCaps * caps,
4218     GstV4l2Error * error)
4219 {
4220   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Trying format %" GST_PTR_FORMAT,
4221       caps);
4222   return gst_v4l2_object_set_format_full (v4l2object, caps, TRUE, error);
4223 }
4224
4225 /**
4226  * gst_v4l2_object_acquire_format:
4227  * @v4l2object: the object
4228  * @info: a GstVideoInfo to be filled
4229  *
4230  * Acquire the driver chosen format. This is useful in decoder or encoder elements where
4231  * the output format is chosen by the HW.
4232  *
4233  * Returns: %TRUE on success, %FALSE on failure.
4234  */
4235 gboolean
4236 gst_v4l2_object_acquire_format (GstV4l2Object * v4l2object, GstVideoInfo * info)
4237 {
4238   struct v4l2_fmtdesc *fmtdesc;
4239   struct v4l2_format fmt;
4240   struct v4l2_crop crop;
4241   struct v4l2_selection sel;
4242   struct v4l2_rect *r = NULL;
4243   GstVideoFormat format;
4244   guint width, height;
4245   GstVideoAlignment align;
4246   GstVideoInterlaceMode interlace_mode;
4247
4248   gst_video_info_init (info);
4249   gst_video_alignment_reset (&align);
4250   v4l2object->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
4251
4252   memset (&fmt, 0x00, sizeof (struct v4l2_format));
4253   fmt.type = v4l2object->type;
4254   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_FMT, &fmt) < 0)
4255     goto get_fmt_failed;
4256
4257   fmtdesc = gst_v4l2_object_get_format_from_fourcc (v4l2object,
4258       fmt.fmt.pix.pixelformat);
4259   if (fmtdesc == NULL)
4260     goto unsupported_format;
4261
4262   /* No need to care about mplane, the four first params are the same */
4263   format = gst_v4l2_object_v4l2fourcc_to_video_format (fmt.fmt.pix.pixelformat);
4264
4265   /* fails if we do no translate the fmt.pix.pixelformat to GstVideoFormat */
4266   if (format == GST_VIDEO_FORMAT_UNKNOWN)
4267     goto unsupported_format;
4268
4269   if (fmt.fmt.pix.width == 0 || fmt.fmt.pix.height == 0)
4270     goto invalid_dimensions;
4271
4272   width = fmt.fmt.pix.width;
4273   height = fmt.fmt.pix.height;
4274
4275   /* Use the default compose rectangle */
4276   memset (&sel, 0, sizeof (struct v4l2_selection));
4277   sel.type = v4l2object->type;
4278   sel.target = V4L2_SEL_TGT_COMPOSE_DEFAULT;
4279   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_SELECTION, &sel) >= 0) {
4280     r = &sel.r;
4281   } else {
4282     /* For ancient kernels, fall back to G_CROP */
4283     memset (&crop, 0, sizeof (struct v4l2_crop));
4284     crop.type = v4l2object->type;
4285     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CROP, &crop) >= 0)
4286       r = &crop.c;
4287   }
4288   if (r) {
4289     align.padding_left = r->left;
4290     align.padding_top = r->top;
4291     align.padding_right = width - r->width - r->left;
4292     align.padding_bottom = height - r->height - r->top;
4293     width = r->width;
4294     height = r->height;
4295   }
4296
4297   switch (fmt.fmt.pix.field) {
4298     case V4L2_FIELD_ANY:
4299     case V4L2_FIELD_NONE:
4300       interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
4301       break;
4302     case V4L2_FIELD_INTERLACED:
4303     case V4L2_FIELD_INTERLACED_TB:
4304     case V4L2_FIELD_INTERLACED_BT:
4305       interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
4306       break;
4307     case V4L2_FIELD_ALTERNATE:
4308       interlace_mode = GST_VIDEO_INTERLACE_MODE_ALTERNATE;
4309       break;
4310     default:
4311       goto unsupported_field;
4312   }
4313
4314   gst_video_info_set_interlaced_format (info, format, interlace_mode, width,
4315       height);
4316
4317   gst_v4l2_object_get_colorspace (v4l2object, &fmt, &info->colorimetry);
4318   gst_v4l2_object_get_streamparm (v4l2object, info);
4319   if ((info->fps_n == 0 && v4l2object->info.fps_d != 0)
4320       && (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
4321           || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
4322     info->fps_d = v4l2object->info.fps_d;
4323     info->fps_n = v4l2object->info.fps_n;
4324     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Set capture fps to %d/%d",
4325         info->fps_n, info->fps_d);
4326   }
4327
4328   gst_v4l2_object_save_format (v4l2object, fmtdesc, &fmt, info, &align);
4329
4330   /* Shall we setup the pool ? */
4331
4332   return TRUE;
4333
4334 get_fmt_failed:
4335   {
4336     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
4337         (_("Video device did not provide output format.")), GST_ERROR_SYSTEM);
4338     return FALSE;
4339   }
4340 invalid_dimensions:
4341   {
4342     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
4343         (_("Video device returned invalid dimensions.")),
4344         ("Expected non 0 dimensions, got %dx%d", fmt.fmt.pix.width,
4345             fmt.fmt.pix.height));
4346     return FALSE;
4347   }
4348 unsupported_field:
4349   {
4350     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
4351         (_("Video device uses an unsupported interlacing method.")),
4352         ("V4L2 field type %d not supported", fmt.fmt.pix.field));
4353     return FALSE;
4354   }
4355 unsupported_format:
4356   {
4357     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
4358         (_("Video device uses an unsupported pixel format.")),
4359         ("V4L2 format %" GST_FOURCC_FORMAT " not supported",
4360             GST_FOURCC_ARGS (fmt.fmt.pix.pixelformat)));
4361     return FALSE;
4362   }
4363 }
4364
4365 /**
4366  * gst_v4l2_object_set_crop:
4367  * @obj: the object
4368  * @crop_rect: the region to crop
4369  *
4370  * Crop the video data to the regions specified in the @crop_rect.
4371  *
4372  * For capture devices, this crop the image sensor / video stream provided by
4373  * the V4L2 device.
4374  * For output devices, this crops the memory buffer that GStreamer passed to
4375  * the V4L2 device.
4376  *
4377  * The crop_rect may be modified by the V4L2 device to a region that
4378  * fulfills H/W requirements.
4379  *
4380  * Returns: %TRUE on success, %FALSE on failure.
4381  */
4382 gboolean
4383 gst_v4l2_object_set_crop (GstV4l2Object * obj, struct v4l2_rect * crop_rect)
4384 {
4385   struct v4l2_selection sel = { 0 };
4386   struct v4l2_crop crop = { 0 };
4387
4388   GST_V4L2_CHECK_OPEN (obj);
4389
4390   sel.type = obj->type;
4391   sel.target = V4L2_SEL_TGT_CROP;
4392   sel.flags = 0;
4393   sel.r = *crop_rect;
4394
4395   crop.type = obj->type;
4396   crop.c = sel.r;
4397
4398   GST_DEBUG_OBJECT (obj->dbg_obj,
4399       "Desired cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
4400       crop.c.width, crop.c.height);
4401
4402   if (obj->ioctl (obj->video_fd, VIDIOC_S_SELECTION, &sel) < 0) {
4403     if (errno != ENOTTY) {
4404       GST_WARNING_OBJECT (obj->dbg_obj,
4405           "Failed to set crop rectangle with VIDIOC_S_SELECTION: %s",
4406           g_strerror (errno));
4407       return FALSE;
4408     } else {
4409       if (obj->ioctl (obj->video_fd, VIDIOC_S_CROP, &crop) < 0) {
4410         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_S_CROP failed");
4411         return FALSE;
4412       }
4413
4414       if (obj->ioctl (obj->video_fd, VIDIOC_G_CROP, &crop) < 0) {
4415         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_G_CROP failed");
4416         return FALSE;
4417       }
4418
4419       sel.r = crop.c;
4420     }
4421   }
4422
4423   GST_DEBUG_OBJECT (obj->dbg_obj,
4424       "Got cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
4425       crop.c.width, crop.c.height);
4426
4427   return TRUE;
4428 }
4429
4430 /**
4431  * gst_v4l2_object_setup_padding:
4432  * @obj: v4l2 object
4433  *
4434  * Crop away the padding around the video data as specified
4435  * in GstVideoAlignement data stored in @obj.
4436  *
4437  * For capture devices, this crop the image sensor / video stream provided by
4438  * the V4L2 device.
4439  * For output devices, this crops the memory buffer that GStreamer passed to
4440  * the V4L2 device.
4441  *
4442  * Returns: %TRUE on success, %FALSE on failure.
4443  */
4444 gboolean
4445 gst_v4l2_object_setup_padding (GstV4l2Object * obj)
4446 {
4447   GstVideoAlignment *align = &obj->align;
4448   struct v4l2_rect crop;
4449
4450   if (align->padding_left + align->padding_top
4451       + align->padding_right + align->padding_bottom == 0) {
4452     GST_DEBUG_OBJECT (obj->dbg_obj, "no cropping needed");
4453     return TRUE;
4454   }
4455
4456   crop.left = align->padding_left;
4457   crop.top = align->padding_top;
4458   crop.width = obj->info.width;
4459   crop.height = GST_VIDEO_INFO_FIELD_HEIGHT (&obj->info);
4460
4461   return gst_v4l2_object_set_crop (obj, &crop);
4462 }
4463
4464 static gboolean
4465 gst_v4l2_object_get_crop_rect (GstV4l2Object * obj, guint target,
4466     struct v4l2_rect *result)
4467 {
4468   struct v4l2_rect *res_rect;
4469
4470   struct v4l2_selection sel = { 0 };
4471   struct v4l2_cropcap cropcap = { 0 };
4472
4473   GST_V4L2_CHECK_OPEN (obj);
4474
4475   if (target != V4L2_SEL_TGT_CROP_BOUNDS && target != V4L2_SEL_TGT_CROP_DEFAULT)
4476     return FALSE;
4477
4478   sel.type = obj->type;
4479   sel.target = target;
4480
4481   res_rect = &sel.r;
4482
4483   if (obj->ioctl (obj->video_fd, VIDIOC_G_SELECTION, &sel) < 0) {
4484     if (errno != ENOTTY) {
4485       GST_WARNING_OBJECT (obj->dbg_obj,
4486           "Failed to get default crop rectangle with VIDIOC_G_SELECTION: %s",
4487           g_strerror (errno));
4488       return FALSE;
4489     } else {
4490       if (obj->ioctl (obj->video_fd, VIDIOC_CROPCAP, &cropcap) < 0) {
4491         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_CROPCAP failed");
4492         return FALSE;
4493       }
4494       if (target == V4L2_SEL_TGT_CROP_BOUNDS)
4495         res_rect = &cropcap.bounds;
4496       else if (target == V4L2_SEL_TGT_CROP_DEFAULT)
4497         res_rect = &cropcap.defrect;
4498     }
4499   }
4500
4501   *result = *res_rect;
4502   return TRUE;
4503 }
4504
4505 gboolean
4506 gst_v4l2_object_get_crop_bounds (GstV4l2Object * obj, struct v4l2_rect * result)
4507 {
4508   return gst_v4l2_object_get_crop_rect (obj, V4L2_SEL_TGT_CROP_BOUNDS, result);
4509 }
4510
4511 gboolean
4512 gst_v4l2_object_get_crop_default (GstV4l2Object * obj,
4513     struct v4l2_rect * result)
4514 {
4515   return gst_v4l2_object_get_crop_rect (obj, V4L2_SEL_TGT_CROP_DEFAULT, result);
4516 }
4517
4518 gboolean
4519 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
4520 {
4521   GstStructure *config;
4522   GstCaps *oldcaps;
4523   gboolean ret;
4524   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4525
4526   if (!pool)
4527     return FALSE;
4528
4529   config = gst_buffer_pool_get_config (pool);
4530   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4531
4532   ret = oldcaps && gst_caps_is_equal (caps, oldcaps);
4533
4534   gst_structure_free (config);
4535
4536   gst_object_unref (pool);
4537   return ret;
4538 }
4539
4540 gboolean
4541 gst_v4l2_object_caps_is_subset (GstV4l2Object * v4l2object, GstCaps * caps)
4542 {
4543   GstStructure *config;
4544   GstCaps *oldcaps;
4545   gboolean ret;
4546   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4547
4548   if (!pool)
4549     return FALSE;
4550
4551   config = gst_buffer_pool_get_config (pool);
4552   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4553
4554   ret = oldcaps && gst_caps_is_subset (oldcaps, caps);
4555
4556   gst_structure_free (config);
4557
4558   gst_object_unref (pool);
4559   return ret;
4560 }
4561
4562 GstCaps *
4563 gst_v4l2_object_get_current_caps (GstV4l2Object * v4l2object)
4564 {
4565   GstStructure *config;
4566   GstCaps *oldcaps;
4567   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4568
4569   if (!pool)
4570     return NULL;
4571
4572   config = gst_buffer_pool_get_config (pool);
4573   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4574
4575   if (oldcaps)
4576     gst_caps_ref (oldcaps);
4577
4578   gst_structure_free (config);
4579
4580   gst_object_unref (pool);
4581   return oldcaps;
4582 }
4583
4584 gboolean
4585 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
4586 {
4587   gboolean ret = TRUE;
4588   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4589
4590   GST_LOG_OBJECT (v4l2object->dbg_obj, "start flushing");
4591
4592   if (!pool)
4593     return ret;
4594
4595   if (gst_buffer_pool_is_active (pool))
4596     gst_buffer_pool_set_flushing (pool, TRUE);
4597
4598   gst_object_unref (pool);
4599   return ret;
4600 }
4601
4602 gboolean
4603 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
4604 {
4605   gboolean ret = TRUE;
4606   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4607
4608   GST_LOG_OBJECT (v4l2object->dbg_obj, "stop flushing");
4609
4610   if (!pool)
4611     return ret;
4612
4613   if (gst_buffer_pool_is_active (pool))
4614     gst_buffer_pool_set_flushing (pool, FALSE);
4615
4616   gst_object_unref (pool);
4617   return ret;
4618 }
4619
4620 gboolean
4621 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
4622 {
4623   GstBufferPool *pool;
4624   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "stopping");
4625
4626   if (!GST_V4L2_IS_OPEN (v4l2object))
4627     goto done;
4628   if (!GST_V4L2_IS_ACTIVE (v4l2object))
4629     goto done;
4630
4631   pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4632   if (pool) {
4633     if (!gst_v4l2_buffer_pool_orphan (v4l2object)) {
4634       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "deactivating pool");
4635       gst_buffer_pool_set_active (pool, FALSE);
4636
4637       {
4638         GstBufferPool *old_pool;
4639         GST_OBJECT_LOCK (v4l2object->element);
4640         old_pool = v4l2object->pool;
4641         v4l2object->pool = NULL;
4642         GST_OBJECT_UNLOCK (v4l2object->element);
4643         if (old_pool)
4644           gst_object_unref (old_pool);
4645       }
4646       gst_object_unref (pool);
4647     }
4648   }
4649
4650   GST_V4L2_SET_INACTIVE (v4l2object);
4651
4652 done:
4653   return TRUE;
4654 }
4655
4656 GstCaps *
4657 gst_v4l2_object_probe_caps (GstV4l2Object * v4l2object, GstCaps * filter)
4658 {
4659   GstCaps *ret;
4660   GSList *walk;
4661   GSList *formats;
4662
4663   formats = gst_v4l2_object_get_format_list (v4l2object);
4664
4665   ret = gst_caps_new_empty ();
4666
4667   if (v4l2object->keep_aspect && !v4l2object->par) {
4668     struct v4l2_cropcap cropcap;
4669
4670     memset (&cropcap, 0, sizeof (cropcap));
4671
4672     cropcap.type = v4l2object->type;
4673     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_CROPCAP, &cropcap) < 0) {
4674       if (errno != ENOTTY)
4675         GST_WARNING_OBJECT (v4l2object->dbg_obj,
4676             "Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: %s",
4677             g_strerror (errno));
4678     } else if (cropcap.pixelaspect.numerator && cropcap.pixelaspect.denominator) {
4679       v4l2object->par = g_new0 (GValue, 1);
4680       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
4681       gst_value_set_fraction (v4l2object->par, cropcap.pixelaspect.numerator,
4682           cropcap.pixelaspect.denominator);
4683     }
4684   }
4685
4686   for (walk = formats; walk; walk = walk->next) {
4687     struct v4l2_fmtdesc *format;
4688     GstStructure *template;
4689     GstCaps *tmp;
4690
4691     format = (struct v4l2_fmtdesc *) walk->data;
4692
4693     template = gst_v4l2_object_v4l2fourcc_to_bare_struct (format->pixelformat);
4694
4695     if (!template) {
4696       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4697           "unknown format %" GST_FOURCC_FORMAT,
4698           GST_FOURCC_ARGS (format->pixelformat));
4699       continue;
4700     }
4701
4702     /* If we have a filter, check if we need to probe this format or not */
4703     if (filter) {
4704       GstCaps *format_caps = gst_caps_new_empty ();
4705
4706       gst_caps_append_structure (format_caps, gst_structure_copy (template));
4707
4708       if (!gst_caps_can_intersect (format_caps, filter)) {
4709         gst_caps_unref (format_caps);
4710         gst_structure_free (template);
4711         continue;
4712       }
4713
4714       gst_caps_unref (format_caps);
4715     }
4716
4717     tmp = gst_v4l2_object_probe_caps_for_format (v4l2object,
4718         format->pixelformat, template);
4719     if (tmp) {
4720       gst_caps_append (ret, tmp);
4721
4722       /* Add a variant of the caps with the Interlaced feature so we can negotiate it if needed */
4723       add_alternate_variant (v4l2object, ret, gst_caps_get_structure (ret,
4724               gst_caps_get_size (ret) - 1));
4725     }
4726
4727     gst_structure_free (template);
4728   }
4729
4730   if (filter) {
4731     GstCaps *tmp;
4732
4733     tmp = ret;
4734     ret = gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
4735     gst_caps_unref (tmp);
4736   }
4737
4738   GST_INFO_OBJECT (v4l2object->dbg_obj, "probed caps: %" GST_PTR_FORMAT, ret);
4739
4740   return ret;
4741 }
4742
4743 GstCaps *
4744 gst_v4l2_object_get_caps (GstV4l2Object * v4l2object, GstCaps * filter)
4745 {
4746   GstCaps *ret;
4747
4748   if (v4l2object->probed_caps == NULL)
4749     v4l2object->probed_caps = gst_v4l2_object_probe_caps (v4l2object, NULL);
4750
4751   if (filter) {
4752     ret = gst_caps_intersect_full (filter, v4l2object->probed_caps,
4753         GST_CAPS_INTERSECT_FIRST);
4754   } else {
4755     ret = gst_caps_ref (v4l2object->probed_caps);
4756   }
4757
4758   return ret;
4759 }
4760
4761 static gboolean
4762 gst_v4l2_object_match_buffer_layout (GstV4l2Object * obj, guint n_planes,
4763     gsize offset[GST_VIDEO_MAX_PLANES], gint stride[GST_VIDEO_MAX_PLANES],
4764     gsize buffer_size, guint padded_height)
4765 {
4766   guint p;
4767   gboolean need_fmt_update = FALSE;
4768
4769   if (n_planes != GST_VIDEO_INFO_N_PLANES (&obj->info)) {
4770     GST_WARNING_OBJECT (obj->dbg_obj,
4771         "Cannot match buffers with different number planes");
4772     return FALSE;
4773   }
4774
4775   for (p = 0; p < n_planes; p++) {
4776     if (stride[p] < obj->info.stride[p]) {
4777       GST_DEBUG_OBJECT (obj->dbg_obj,
4778           "Not matching as remote stride %i is smaller than %i on plane %u",
4779           stride[p], obj->info.stride[p], p);
4780       return FALSE;
4781     } else if (stride[p] > obj->info.stride[p]) {
4782       GST_LOG_OBJECT (obj->dbg_obj,
4783           "remote stride %i is higher than %i on plane %u",
4784           stride[p], obj->info.stride[p], p);
4785       need_fmt_update = TRUE;
4786     }
4787
4788     if (offset[p] < obj->info.offset[p]) {
4789       GST_DEBUG_OBJECT (obj->dbg_obj,
4790           "Not matching as offset %" G_GSIZE_FORMAT
4791           " is smaller than %" G_GSIZE_FORMAT " on plane %u",
4792           offset[p], obj->info.offset[p], p);
4793       return FALSE;
4794     } else if (offset[p] > obj->info.offset[p]) {
4795       GST_LOG_OBJECT (obj->dbg_obj,
4796           "Remote offset %" G_GSIZE_FORMAT
4797           " is higher than %" G_GSIZE_FORMAT " on plane %u",
4798           offset[p], obj->info.offset[p], p);
4799       need_fmt_update = TRUE;
4800     }
4801
4802     if (padded_height) {
4803       guint fmt_height;
4804
4805       if (V4L2_TYPE_IS_MULTIPLANAR (obj->type))
4806         fmt_height = obj->format.fmt.pix_mp.height;
4807       else
4808         fmt_height = obj->format.fmt.pix.height;
4809
4810       if (padded_height > fmt_height)
4811         need_fmt_update = TRUE;
4812     }
4813   }
4814
4815   if (need_fmt_update) {
4816     struct v4l2_format format;
4817     gint wanted_stride[GST_VIDEO_MAX_PLANES] = { 0, };
4818
4819     format = obj->format;
4820
4821     if (padded_height) {
4822       GST_DEBUG_OBJECT (obj->dbg_obj, "Padded height %u", padded_height);
4823
4824       obj->align.padding_bottom =
4825           padded_height - GST_VIDEO_INFO_FIELD_HEIGHT (&obj->info);
4826     } else {
4827       GST_WARNING_OBJECT (obj->dbg_obj,
4828           "Failed to compute padded height; keep the default one");
4829       padded_height = format.fmt.pix_mp.height;
4830     }
4831
4832     /* update the current format with the stride we want to import from */
4833     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
4834       guint i;
4835
4836       GST_DEBUG_OBJECT (obj->dbg_obj, "Wanted strides:");
4837
4838       for (i = 0; i < obj->n_v4l2_planes; i++) {
4839         gint plane_stride = stride[i];
4840
4841         if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo))
4842           plane_stride = GST_VIDEO_TILE_X_TILES (plane_stride) *
4843               GST_VIDEO_FORMAT_INFO_TILE_STRIDE (obj->info.finfo, i);
4844
4845         format.fmt.pix_mp.plane_fmt[i].bytesperline = plane_stride;
4846         format.fmt.pix_mp.height = padded_height;
4847         wanted_stride[i] = plane_stride;
4848         GST_DEBUG_OBJECT (obj->dbg_obj, "    [%u] %i", i, wanted_stride[i]);
4849       }
4850     } else {
4851       gint plane_stride = stride[0];
4852
4853       GST_DEBUG_OBJECT (obj->dbg_obj, "Wanted stride: %i", plane_stride);
4854
4855       if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo))
4856         plane_stride = GST_VIDEO_TILE_X_TILES (plane_stride) *
4857             GST_VIDEO_FORMAT_INFO_TILE_STRIDE (obj->info.finfo, 0);
4858
4859       format.fmt.pix.bytesperline = plane_stride;
4860       format.fmt.pix.height = padded_height;
4861       wanted_stride[0] = plane_stride;
4862     }
4863
4864     if (obj->ioctl (obj->video_fd, VIDIOC_S_FMT, &format) < 0) {
4865       GST_WARNING_OBJECT (obj->dbg_obj,
4866           "Something went wrong trying to update current format: %s",
4867           g_strerror (errno));
4868       return FALSE;
4869     }
4870
4871     gst_v4l2_object_save_format (obj, obj->fmtdesc, &format, &obj->info,
4872         &obj->align);
4873
4874     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
4875       guint i;
4876
4877       for (i = 0; i < obj->n_v4l2_planes; i++) {
4878         if (format.fmt.pix_mp.plane_fmt[i].bytesperline != wanted_stride[i]) {
4879           GST_DEBUG_OBJECT (obj->dbg_obj,
4880               "[%i] Driver did not accept the new stride (wants %i, got %i)",
4881               i, wanted_stride[i], format.fmt.pix_mp.plane_fmt[i].bytesperline);
4882           return FALSE;
4883         }
4884       }
4885
4886       if (format.fmt.pix_mp.height != padded_height) {
4887         GST_DEBUG_OBJECT (obj->dbg_obj,
4888             "Driver did not accept the padded height (wants %i, got %i)",
4889             padded_height, format.fmt.pix_mp.height);
4890       }
4891     } else {
4892       if (format.fmt.pix.bytesperline != wanted_stride[0]) {
4893         GST_DEBUG_OBJECT (obj->dbg_obj,
4894             "Driver did not accept the new stride (wants %i, got %i)",
4895             wanted_stride[0], format.fmt.pix.bytesperline);
4896         return FALSE;
4897       }
4898
4899       if (format.fmt.pix.height != padded_height) {
4900         GST_DEBUG_OBJECT (obj->dbg_obj,
4901             "Driver did not accept the padded height (wants %i, got %i)",
4902             padded_height, format.fmt.pix.height);
4903       }
4904     }
4905   }
4906
4907   if (obj->align.padding_bottom) {
4908     /* Crop because of vertical padding */
4909     GST_DEBUG_OBJECT (obj->dbg_obj, "crop because of bottom padding of %d",
4910         obj->align.padding_bottom);
4911     gst_v4l2_object_setup_padding (obj);
4912   }
4913
4914   return TRUE;
4915 }
4916
4917 static gboolean
4918 validate_video_meta_struct (GstV4l2Object * obj, const GstStructure * s)
4919 {
4920   guint i;
4921
4922   for (i = 0; i < gst_structure_n_fields (s); i++) {
4923     const gchar *name = gst_structure_nth_field_name (s, i);
4924
4925     if (!g_str_equal (name, "padding-top")
4926         && !g_str_equal (name, "padding-bottom")
4927         && !g_str_equal (name, "padding-left")
4928         && !g_str_equal (name, "padding-right")) {
4929       GST_WARNING_OBJECT (obj->dbg_obj, "Unknown video meta field: '%s'", name);
4930       return FALSE;
4931     }
4932   }
4933
4934   return TRUE;
4935 }
4936
4937 static gboolean
4938 gst_v4l2_object_match_buffer_layout_from_struct (GstV4l2Object * obj,
4939     const GstStructure * s, GstCaps * caps, guint buffer_size)
4940 {
4941   GstVideoInfo info;
4942   GstVideoAlignment align;
4943   gsize plane_size[GST_VIDEO_MAX_PLANES];
4944
4945   if (!validate_video_meta_struct (obj, s))
4946     return FALSE;
4947
4948   if (!gst_video_info_from_caps (&info, caps)) {
4949     GST_WARNING_OBJECT (obj->dbg_obj, "Failed to create video info");
4950     return FALSE;
4951   }
4952
4953   gst_video_alignment_reset (&align);
4954
4955   gst_structure_get_uint (s, "padding-top", &align.padding_top);
4956   gst_structure_get_uint (s, "padding-bottom", &align.padding_bottom);
4957   gst_structure_get_uint (s, "padding-left", &align.padding_left);
4958   gst_structure_get_uint (s, "padding-right", &align.padding_right);
4959
4960   if (align.padding_top || align.padding_bottom || align.padding_left ||
4961       align.padding_right) {
4962     GST_DEBUG_OBJECT (obj->dbg_obj,
4963         "Upstream requested padding (top: %d bottom: %d left: %d right: %d)",
4964         align.padding_top, align.padding_bottom, align.padding_left,
4965         align.padding_right);
4966   }
4967
4968   if (!gst_video_info_align_full (&info, &align, plane_size)) {
4969     GST_WARNING_OBJECT (obj->dbg_obj, "Failed to align video info");
4970     return FALSE;
4971   }
4972
4973   if (GST_VIDEO_INFO_SIZE (&info) != buffer_size) {
4974     GST_WARNING_OBJECT (obj->dbg_obj,
4975         "Requested buffer size (%d) doesn't match video info size (%"
4976         G_GSIZE_FORMAT ")", buffer_size, GST_VIDEO_INFO_SIZE (&info));
4977     return FALSE;
4978   }
4979
4980   GST_DEBUG_OBJECT (obj->dbg_obj,
4981       "try matching buffer layout requested by downstream");
4982
4983   gst_v4l2_object_match_buffer_layout (obj, GST_VIDEO_INFO_N_PLANES (&info),
4984       info.offset, info.stride, buffer_size,
4985       GST_VIDEO_INFO_PLANE_HEIGHT (&info, 0, plane_size));
4986
4987   return TRUE;
4988 }
4989
4990 gboolean
4991 gst_v4l2_object_decide_allocation (GstV4l2Object * obj, GstQuery * query)
4992 {
4993   GstCaps *caps;
4994   GstBufferPool *pool = NULL, *other_pool = NULL, *obj_pool = NULL;
4995   GstStructure *config;
4996   guint size, min, max, own_min = 0;
4997   gboolean update;
4998   gboolean has_video_meta;
4999   gboolean can_share_own_pool, pushing_from_our_pool = FALSE;
5000   GstAllocator *allocator = NULL;
5001   GstAllocationParams params = { 0 };
5002   guint video_idx;
5003
5004   GST_DEBUG_OBJECT (obj->dbg_obj, "decide allocation");
5005
5006   g_return_val_if_fail (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
5007       obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, FALSE);
5008
5009   gst_query_parse_allocation (query, &caps, NULL);
5010
5011   obj_pool = gst_v4l2_object_get_buffer_pool (obj);
5012   if (obj_pool == NULL) {
5013     if (!gst_v4l2_object_setup_pool (obj, caps))
5014       goto pool_failed;
5015     obj_pool = gst_v4l2_object_get_buffer_pool (obj);
5016     if (obj_pool == NULL)
5017       goto pool_failed;
5018   }
5019
5020   if (gst_query_get_n_allocation_params (query) > 0)
5021     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
5022
5023   if (gst_query_get_n_allocation_pools (query) > 0) {
5024     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
5025     update = TRUE;
5026   } else {
5027     pool = NULL;
5028     min = max = 0;
5029     size = 0;
5030     update = FALSE;
5031   }
5032
5033   GST_DEBUG_OBJECT (obj->dbg_obj, "allocation: size:%u min:%u max:%u pool:%"
5034       GST_PTR_FORMAT, size, min, max, pool);
5035
5036   has_video_meta =
5037       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE,
5038       &video_idx);
5039
5040   if (has_video_meta) {
5041     const GstStructure *params;
5042     gst_query_parse_nth_allocation_meta (query, video_idx, &params);
5043
5044     if (params)
5045       gst_v4l2_object_match_buffer_layout_from_struct (obj, params, caps, size);
5046   }
5047
5048   can_share_own_pool = (has_video_meta || !obj->need_video_meta);
5049
5050   gst_v4l2_get_driver_min_buffers (obj);
5051   /* We can't share our own pool, if it exceed V4L2 capacity */
5052   if (min + obj->min_buffers + 1 > VIDEO_MAX_FRAME)
5053     can_share_own_pool = FALSE;
5054
5055   /* select a pool */
5056   switch (obj->mode) {
5057     case GST_V4L2_IO_RW:
5058       if (pool) {
5059         /* in READ/WRITE mode, prefer a downstream pool because our own pool
5060          * doesn't help much, we have to write to it as well */
5061         GST_DEBUG_OBJECT (obj->dbg_obj,
5062             "read/write mode: using downstream pool");
5063         /* use the bigest size, when we use our own pool we can't really do any
5064          * other size than what the hardware gives us but for downstream pools
5065          * we can try */
5066         size = MAX (size, obj->info.size);
5067       } else if (can_share_own_pool) {
5068         /* no downstream pool, use our own then */
5069         GST_DEBUG_OBJECT (obj->dbg_obj,
5070             "read/write mode: no downstream pool, using our own");
5071         pool = gst_object_ref (obj_pool);
5072         size = obj->info.size;
5073         pushing_from_our_pool = TRUE;
5074       }
5075       break;
5076
5077     case GST_V4L2_IO_USERPTR:
5078     case GST_V4L2_IO_DMABUF_IMPORT:
5079       /* in importing mode, prefer our own pool, and pass the other pool to
5080        * our own, so it can serve itself */
5081       if (pool == NULL)
5082         goto no_downstream_pool;
5083       gst_v4l2_buffer_pool_set_other_pool (GST_V4L2_BUFFER_POOL (obj_pool),
5084           pool);
5085       other_pool = pool;
5086       gst_object_unref (pool);
5087       pool = gst_object_ref (obj_pool);
5088       size = obj->info.size;
5089       break;
5090
5091     case GST_V4L2_IO_MMAP:
5092     case GST_V4L2_IO_DMABUF:
5093       /* in streaming mode, prefer our own pool */
5094       /* Check if we can use it ... */
5095       if (can_share_own_pool) {
5096         if (pool)
5097           gst_object_unref (pool);
5098         pool = gst_object_ref (obj_pool);
5099         size = obj->info.size;
5100         GST_DEBUG_OBJECT (obj->dbg_obj,
5101             "streaming mode: using our own pool %" GST_PTR_FORMAT, pool);
5102         pushing_from_our_pool = TRUE;
5103       } else if (pool) {
5104         GST_DEBUG_OBJECT (obj->dbg_obj,
5105             "streaming mode: copying to downstream pool %" GST_PTR_FORMAT,
5106             pool);
5107       } else {
5108         GST_DEBUG_OBJECT (obj->dbg_obj,
5109             "streaming mode: no usable pool, copying to generic pool");
5110         size = MAX (size, obj->info.size);
5111       }
5112       break;
5113     case GST_V4L2_IO_AUTO:
5114     default:
5115       GST_WARNING_OBJECT (obj->dbg_obj, "unhandled mode");
5116       break;
5117   }
5118
5119   if (size == 0)
5120     goto no_size;
5121
5122   /* If pushing from our own pool, configure it with queried minimum,
5123    * otherwise use the minimum required */
5124   if (pushing_from_our_pool) {
5125     /* When pushing from our own pool, we need what downstream one, to be able
5126      * to fill the pipeline, the minimum required to decoder according to the
5127      * driver and 2 more, so we don't endup up with everything downstream or
5128      * held by the decoder. We account 2 buffers for v4l2 so when one is being
5129      * pushed downstream the other one can already be queued for the next
5130      * frame. */
5131     own_min = min + obj->min_buffers + 2;
5132
5133     /* If no allocation parameters where provided, allow for a little more
5134      * buffers and enable copy threshold */
5135     if (!update) {
5136       own_min += 2;
5137       gst_v4l2_buffer_pool_copy_at_threshold (GST_V4L2_BUFFER_POOL (pool),
5138           TRUE);
5139     } else {
5140       gst_v4l2_buffer_pool_copy_at_threshold (GST_V4L2_BUFFER_POOL (pool),
5141           FALSE);
5142     }
5143
5144   } else {
5145     /* In this case we'll have to configure two buffer pool. For our buffer
5146      * pool, we'll need what the driver one, and one more, so we can dequeu */
5147     own_min = obj->min_buffers + 1;
5148     own_min = MAX (own_min, GST_V4L2_MIN_BUFFERS (obj));
5149
5150     /* for the downstream pool, we keep what downstream wants, though ensure
5151      * at least a minimum if downstream didn't suggest anything (we are
5152      * expecting the base class to create a default one for the context) */
5153     min = MAX (min, GST_V4L2_MIN_BUFFERS (obj));
5154
5155     /* To import we need the other pool to hold at least own_min */
5156     if (obj_pool == pool)
5157       min += own_min;
5158   }
5159
5160   /* Request a bigger max, if one was suggested but it's too small */
5161   if (max != 0)
5162     max = MAX (min, max);
5163
5164   /* First step, configure our own pool */
5165   config = gst_buffer_pool_get_config (obj_pool);
5166
5167   if (obj->need_video_meta || has_video_meta) {
5168     GST_DEBUG_OBJECT (obj->dbg_obj, "activate Video Meta");
5169     gst_buffer_pool_config_add_option (config,
5170         GST_BUFFER_POOL_OPTION_VIDEO_META);
5171   }
5172
5173   gst_buffer_pool_config_set_allocator (config, allocator, &params);
5174   gst_buffer_pool_config_set_params (config, caps, size, own_min, 0);
5175
5176   GST_DEBUG_OBJECT (obj->dbg_obj, "setting own pool config to %"
5177       GST_PTR_FORMAT, config);
5178
5179   /* Our pool often need to adjust the value */
5180   if (!gst_buffer_pool_set_config (obj_pool, config)) {
5181     config = gst_buffer_pool_get_config (obj_pool);
5182
5183     GST_DEBUG_OBJECT (obj->dbg_obj, "own pool config changed to %"
5184         GST_PTR_FORMAT, config);
5185
5186     /* our pool will adjust the maximum buffer, which we are fine with */
5187     if (!gst_buffer_pool_set_config (obj_pool, config))
5188       goto config_failed;
5189   }
5190
5191   /* Now configure the other pool if different */
5192   if (obj_pool != pool)
5193     other_pool = pool;
5194
5195   if (other_pool) {
5196     config = gst_buffer_pool_get_config (other_pool);
5197     gst_buffer_pool_config_set_allocator (config, allocator, &params);
5198     gst_buffer_pool_config_set_params (config, caps, size, min, max);
5199
5200     GST_DEBUG_OBJECT (obj->dbg_obj, "setting other pool config to %"
5201         GST_PTR_FORMAT, config);
5202
5203     /* if downstream supports video metadata, add this to the pool config */
5204     if (has_video_meta) {
5205       GST_DEBUG_OBJECT (obj->dbg_obj, "activate Video Meta");
5206       gst_buffer_pool_config_add_option (config,
5207           GST_BUFFER_POOL_OPTION_VIDEO_META);
5208     }
5209
5210     if (!gst_buffer_pool_set_config (other_pool, config)) {
5211       config = gst_buffer_pool_get_config (other_pool);
5212
5213       if (!gst_buffer_pool_config_validate_params (config, caps, size, min,
5214               max)) {
5215         gst_structure_free (config);
5216         goto config_failed;
5217       }
5218
5219       if (!gst_buffer_pool_set_config (other_pool, config))
5220         goto config_failed;
5221     }
5222   }
5223
5224   if (pool) {
5225     /* For simplicity, simply read back the active configuration, so our base
5226      * class get the right information */
5227     config = gst_buffer_pool_get_config (pool);
5228     gst_buffer_pool_config_get_params (config, NULL, &size, &min, &max);
5229     gst_structure_free (config);
5230   }
5231
5232   if (update)
5233     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
5234   else
5235     gst_query_add_allocation_pool (query, pool, size, min, max);
5236
5237   if (allocator)
5238     gst_object_unref (allocator);
5239
5240   if (pool)
5241     gst_object_unref (pool);
5242
5243   if (obj_pool)
5244     gst_object_unref (obj_pool);
5245
5246   return TRUE;
5247
5248 pool_failed:
5249   {
5250     /* setup_pool already send the error */
5251     goto cleanup;
5252   }
5253 config_failed:
5254   {
5255     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5256         (_("Failed to configure internal buffer pool.")), (NULL));
5257     goto cleanup;
5258   }
5259 no_size:
5260   {
5261     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5262         (_("Video device did not suggest any buffer size.")), (NULL));
5263     goto cleanup;
5264   }
5265 no_downstream_pool:
5266   {
5267     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5268         (_("No downstream pool to import from.")),
5269         ("When importing DMABUF or USERPTR, we need a pool to import from"));
5270     goto cleanup;
5271   }
5272 cleanup:
5273   {
5274     if (allocator)
5275       gst_object_unref (allocator);
5276
5277     if (pool)
5278       gst_object_unref (pool);
5279
5280     if (obj_pool)
5281       gst_object_unref (obj_pool);
5282     return FALSE;
5283   }
5284 }
5285
5286 gboolean
5287 gst_v4l2_object_propose_allocation (GstV4l2Object * obj, GstQuery * query)
5288 {
5289   GstBufferPool *pool = NULL;
5290   /* we need at least 2 buffers to operate */
5291   guint size, min, max;
5292   GstCaps *caps;
5293   gboolean need_pool;
5294
5295   /* Set defaults allocation parameters */
5296   size = obj->info.size;
5297   min = GST_V4L2_MIN_BUFFERS (obj);
5298   max = VIDEO_MAX_FRAME;
5299
5300   gst_query_parse_allocation (query, &caps, &need_pool);
5301
5302   if (caps == NULL)
5303     goto no_caps;
5304
5305   switch (obj->mode) {
5306     case GST_V4L2_IO_MMAP:
5307     case GST_V4L2_IO_DMABUF:
5308       if (need_pool) {
5309         GstBufferPool *obj_pool = gst_v4l2_object_get_buffer_pool (obj);
5310         if (obj_pool) {
5311           if (!gst_buffer_pool_is_active (obj_pool))
5312             pool = gst_object_ref (obj_pool);
5313
5314           gst_object_unref (obj_pool);
5315         }
5316       }
5317       break;
5318     default:
5319       break;
5320   }
5321
5322   if (pool != NULL) {
5323     GstCaps *pcaps;
5324     GstStructure *config;
5325
5326     /* we had a pool, check caps */
5327     config = gst_buffer_pool_get_config (pool);
5328     gst_buffer_pool_config_get_params (config, &pcaps, NULL, NULL, NULL);
5329
5330     GST_DEBUG_OBJECT (obj->dbg_obj,
5331         "we had a pool with caps %" GST_PTR_FORMAT, pcaps);
5332     if (!gst_caps_is_equal (caps, pcaps)) {
5333       gst_structure_free (config);
5334       gst_object_unref (pool);
5335       goto different_caps;
5336     }
5337     gst_structure_free (config);
5338   }
5339   gst_v4l2_get_driver_min_buffers (obj);
5340
5341   min = MAX (obj->min_buffers, GST_V4L2_MIN_BUFFERS (obj));
5342
5343   gst_query_add_allocation_pool (query, pool, size, min, max);
5344
5345   /* we also support various metadata */
5346   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
5347
5348   if (pool)
5349     gst_object_unref (pool);
5350
5351   return TRUE;
5352
5353   /* ERRORS */
5354 no_caps:
5355   {
5356     GST_DEBUG_OBJECT (obj->dbg_obj, "no caps specified");
5357     return FALSE;
5358   }
5359 different_caps:
5360   {
5361     /* different caps, we can't use this pool */
5362     GST_DEBUG_OBJECT (obj->dbg_obj, "pool has different caps");
5363     return FALSE;
5364   }
5365 }
5366
5367 gboolean
5368 gst_v4l2_object_try_import (GstV4l2Object * obj, GstBuffer * buffer)
5369 {
5370   GstVideoMeta *vmeta;
5371   guint n_mem = gst_buffer_n_memory (buffer);
5372
5373   /* only import if requested */
5374   switch (obj->mode) {
5375     case GST_V4L2_IO_USERPTR:
5376     case GST_V4L2_IO_DMABUF_IMPORT:
5377       break;
5378     default:
5379       GST_DEBUG_OBJECT (obj->dbg_obj,
5380           "The io-mode does not enable importation");
5381       return FALSE;
5382   }
5383
5384   vmeta = gst_buffer_get_video_meta (buffer);
5385   if (!vmeta && obj->need_video_meta) {
5386     GST_DEBUG_OBJECT (obj->dbg_obj, "Downstream buffer uses standard "
5387         "stride/offset while the driver does not.");
5388     return FALSE;
5389   }
5390
5391   /* we need matching strides/offsets and size */
5392   if (vmeta) {
5393     guint plane_height[GST_VIDEO_MAX_PLANES] = { 0, };
5394
5395     gst_video_meta_get_plane_height (vmeta, plane_height);
5396
5397     if (!gst_v4l2_object_match_buffer_layout (obj, vmeta->n_planes,
5398             vmeta->offset, vmeta->stride, gst_buffer_get_size (buffer),
5399             plane_height[0]))
5400       return FALSE;
5401   }
5402
5403   /* we can always import single memory buffer, but otherwise we need the same
5404    * amount of memory object. */
5405   if (n_mem != 1 && n_mem != obj->n_v4l2_planes) {
5406     GST_DEBUG_OBJECT (obj->dbg_obj, "Can only import %i memory, "
5407         "buffers contains %u memory", obj->n_v4l2_planes, n_mem);
5408     return FALSE;
5409   }
5410
5411   /* For DMABuf importation we need DMABuf of course */
5412   if (obj->mode == GST_V4L2_IO_DMABUF_IMPORT) {
5413     guint i;
5414
5415     for (i = 0; i < n_mem; i++) {
5416       GstMemory *mem = gst_buffer_peek_memory (buffer, i);
5417
5418       if (!gst_is_dmabuf_memory (mem)) {
5419         GST_DEBUG_OBJECT (obj->dbg_obj, "Cannot import non-DMABuf memory.");
5420         return FALSE;
5421       }
5422     }
5423   }
5424
5425   /* for the remaining, only the kernel driver can tell */
5426   return TRUE;
5427 }
5428
5429 /**
5430  * gst_v4l2_object_get_buffer_pool:
5431  * @src: a #GstV4l2Object
5432  *
5433  * Returns: (nullable) (transfer full): the instance of the #GstBufferPool used
5434  * by the v4l2object; unref it after usage.
5435  */
5436 GstBufferPool *
5437 gst_v4l2_object_get_buffer_pool (GstV4l2Object * v4l2object)
5438 {
5439   GstBufferPool *ret = NULL;
5440
5441   g_return_val_if_fail (v4l2object != NULL, NULL);
5442
5443   GST_OBJECT_LOCK (v4l2object->element);
5444   if (v4l2object->pool)
5445     ret = gst_object_ref (v4l2object->pool);
5446   GST_OBJECT_UNLOCK (v4l2object->element);
5447
5448   return ret;
5449 }