8899d1f1a29cc104f32da3c0c2833beaac60d1f3
[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   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
3176     goto buffer_pool_new_failed;
3177
3178   GST_V4L2_SET_ACTIVE (v4l2object);
3179
3180   return TRUE;
3181
3182   /* ERRORS */
3183 buffer_pool_new_failed:
3184   {
3185     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
3186         (_("Could not map buffers from device '%s'"),
3187             v4l2object->videodev),
3188         ("Failed to create buffer pool: %s", g_strerror (errno)));
3189     return FALSE;
3190   }
3191 method_not_supported:
3192   {
3193     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
3194         (_("The driver of device '%s' does not support the IO method %d"),
3195             v4l2object->videodev, mode), (NULL));
3196     return FALSE;
3197   }
3198 no_supported_capture_method:
3199   {
3200     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
3201         (_("The driver of device '%s' does not support any known IO "
3202                 "method."), v4l2object->videodev), (NULL));
3203     return FALSE;
3204   }
3205 }
3206
3207 static gboolean
3208 gst_v4l2_object_reset_compose_region (GstV4l2Object * obj)
3209 {
3210   struct v4l2_selection sel = { 0 };
3211
3212   GST_V4L2_CHECK_OPEN (obj);
3213
3214   sel.type = obj->type;
3215   sel.target = V4L2_SEL_TGT_COMPOSE_DEFAULT;
3216
3217   if (obj->ioctl (obj->video_fd, VIDIOC_G_SELECTION, &sel) < 0) {
3218     if (errno == ENOTTY) {
3219       /* No-op when selection API is not supported */
3220       return TRUE;
3221     } else {
3222       GST_WARNING_OBJECT (obj->dbg_obj,
3223           "Failed to get default compose rectangle with VIDIOC_G_SELECTION: %s",
3224           g_strerror (errno));
3225       return FALSE;
3226     }
3227   }
3228
3229   sel.target = V4L2_SEL_TGT_COMPOSE;
3230
3231   if (obj->ioctl (obj->video_fd, VIDIOC_S_SELECTION, &sel) < 0) {
3232     GST_WARNING_OBJECT (obj->dbg_obj,
3233         "Failed to set default compose rectangle with VIDIOC_S_SELECTION: %s",
3234         g_strerror (errno));
3235     return FALSE;
3236   }
3237
3238   return TRUE;
3239 }
3240
3241 static void
3242 gst_v4l2_object_set_stride (GstVideoInfo * info, GstVideoAlignment * align,
3243     gint plane, gint stride)
3244 {
3245   const GstVideoFormatInfo *finfo = info->finfo;
3246
3247   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3248     gint x_tiles, y_tiles, tile_height, padded_height;
3249
3250     tile_height = GST_VIDEO_FORMAT_INFO_TILE_HEIGHT (finfo, plane);
3251
3252     padded_height = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, plane,
3253         info->height + align->padding_top + align->padding_bottom);
3254     padded_height = (padded_height + tile_height - 1) / tile_height;
3255
3256     x_tiles = stride / GST_VIDEO_FORMAT_INFO_TILE_STRIDE (finfo, plane);
3257     y_tiles = padded_height / tile_height;
3258     info->stride[plane] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
3259   } else {
3260     info->stride[plane] = stride;
3261   }
3262 }
3263
3264 static void
3265 gst_v4l2_object_extrapolate_info (GstV4l2Object * v4l2object,
3266     GstVideoInfo * info, GstVideoAlignment * align, gint stride)
3267 {
3268   const GstVideoFormatInfo *finfo = info->finfo;
3269   gint i, estride, padded_height;
3270   gsize offs = 0;
3271
3272   g_return_if_fail (v4l2object->n_v4l2_planes == 1);
3273
3274   padded_height =
3275       GST_VIDEO_INFO_FIELD_HEIGHT (info) + align->padding_top +
3276       align->padding_bottom;
3277
3278   for (i = 0; i < finfo->n_planes; i++) {
3279     estride = gst_video_format_info_extrapolate_stride (finfo, i, stride);
3280
3281     gst_v4l2_object_set_stride (info, align, i, estride);
3282
3283     info->offset[i] = offs;
3284     offs += estride *
3285         GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, padded_height);
3286
3287     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
3288         "Extrapolated for plane %d with base stride %d: "
3289         "stride %d, offset %" G_GSIZE_FORMAT, i, stride, info->stride[i],
3290         info->offset[i]);
3291   }
3292
3293   /* Update the image size according the amount of data we are going to
3294    * read/write. This workaround bugs in driver where the sizeimage provided
3295    * by TRY/S_FMT represent the buffer length (maximum size) rather then the expected
3296    * bytesused (buffer size). */
3297   if (offs < info->size)
3298     info->size = offs;
3299 }
3300
3301 static void
3302 gst_v4l2_object_save_format (GstV4l2Object * v4l2object,
3303     struct v4l2_fmtdesc *fmtdesc, struct v4l2_format *format,
3304     GstVideoInfo * info, GstVideoAlignment * align)
3305 {
3306   const GstVideoFormatInfo *finfo = info->finfo;
3307   gboolean standard_stride = TRUE;
3308   gint stride, pstride, padded_width, padded_height, i;
3309
3310   if (GST_VIDEO_INFO_FORMAT (info) == GST_VIDEO_FORMAT_ENCODED) {
3311     v4l2object->n_v4l2_planes = 1;
3312     info->size = format->fmt.pix.sizeimage;
3313     goto store_info;
3314   }
3315
3316   /* adjust right padding */
3317   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
3318     stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
3319   else
3320     stride = format->fmt.pix.bytesperline;
3321
3322   pstride = GST_VIDEO_FORMAT_INFO_PSTRIDE (finfo, 0);
3323   if (pstride) {
3324     padded_width = stride / pstride;
3325   } else {
3326     /* pstride can be 0 for complex formats */
3327     GST_WARNING_OBJECT (v4l2object->element,
3328         "format %s has a pstride of 0, cannot compute padded with",
3329         gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (info)));
3330     padded_width = stride;
3331   }
3332
3333   if (padded_width < format->fmt.pix.width)
3334     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3335         "Driver bug detected, stride (%d) is too small for the width (%d)",
3336         padded_width, format->fmt.pix.width);
3337
3338   align->padding_right = padded_width - info->width - align->padding_left;
3339
3340   /* adjust bottom padding */
3341   padded_height = format->fmt.pix.height;
3342
3343   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3344     guint tile_height;
3345     tile_height = GST_VIDEO_FORMAT_INFO_TILE_HEIGHT (finfo, 0);
3346     padded_height = (padded_height + tile_height - 1) / tile_height;
3347   }
3348
3349   align->padding_bottom =
3350       padded_height - GST_VIDEO_INFO_FIELD_HEIGHT (info) - align->padding_top;
3351
3352   /* setup the strides and offset */
3353   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type)) {
3354     struct v4l2_pix_format_mplane *pix_mp = &format->fmt.pix_mp;
3355
3356     /* figure out the frame layout */
3357     v4l2object->n_v4l2_planes = MAX (1, pix_mp->num_planes);
3358     info->size = 0;
3359     for (i = 0; i < v4l2object->n_v4l2_planes; i++) {
3360       stride = pix_mp->plane_fmt[i].bytesperline;
3361
3362       if (info->stride[i] != stride)
3363         standard_stride = FALSE;
3364
3365       gst_v4l2_object_set_stride (info, align, i, stride);
3366       info->offset[i] = info->size;
3367       info->size += pix_mp->plane_fmt[i].sizeimage;
3368     }
3369
3370     /* Extrapolate stride if planar format are being set in 1 v4l2 plane */
3371     if (v4l2object->n_v4l2_planes < finfo->n_planes) {
3372       stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
3373       gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
3374     }
3375   } else {
3376     /* only one plane in non-MPLANE mode */
3377     v4l2object->n_v4l2_planes = 1;
3378     info->size = format->fmt.pix.sizeimage;
3379     stride = format->fmt.pix.bytesperline;
3380
3381     if (info->stride[0] != stride)
3382       standard_stride = FALSE;
3383
3384     gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
3385   }
3386
3387   /* adjust the offset to take into account left and top */
3388   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3389     if ((align->padding_left + align->padding_top) > 0)
3390       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3391           "Left and top padding is not permitted for tiled formats");
3392   } else {
3393     for (i = 0; i < finfo->n_planes; i++) {
3394       gint vedge, hedge;
3395
3396       /* FIXME we assume plane as component as this is true for all supported
3397        * format we support. */
3398
3399       hedge = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, align->padding_left);
3400       vedge = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, align->padding_top);
3401
3402       info->offset[i] += (vedge * info->stride[i]) +
3403           (hedge * GST_VIDEO_INFO_COMP_PSTRIDE (info, i));
3404     }
3405   }
3406
3407 store_info:
3408   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got sizeimage %" G_GSIZE_FORMAT,
3409       info->size);
3410
3411   /* to avoid copies we need video meta if there is padding */
3412   v4l2object->need_video_meta =
3413       ((align->padding_top + align->padding_left + align->padding_right +
3414           align->padding_bottom) != 0);
3415
3416   /* ... or if stride is non "standard" */
3417   if (!standard_stride)
3418     v4l2object->need_video_meta = TRUE;
3419
3420   /* ... or also video meta if we use multiple, non-contiguous, planes */
3421   if (v4l2object->n_v4l2_planes > 1)
3422     v4l2object->need_video_meta = TRUE;
3423
3424   v4l2object->info = *info;
3425   v4l2object->align = *align;
3426   v4l2object->format = *format;
3427   v4l2object->fmtdesc = fmtdesc;
3428
3429   /* if we have a framerate pre-calculate duration */
3430   if (info->fps_n > 0 && info->fps_d > 0) {
3431     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, info->fps_d,
3432         info->fps_n);
3433     if (GST_VIDEO_INFO_INTERLACE_MODE (info) ==
3434         GST_VIDEO_INTERLACE_MODE_ALTERNATE)
3435       v4l2object->duration /= 2;
3436   } else {
3437     v4l2object->duration = GST_CLOCK_TIME_NONE;
3438   }
3439 }
3440
3441 static enum v4l2_field
3442 get_v4l2_field_for_info (GstVideoInfo * info)
3443 {
3444   if (!GST_VIDEO_INFO_IS_INTERLACED (info))
3445     return V4L2_FIELD_NONE;
3446
3447   if (GST_VIDEO_INFO_INTERLACE_MODE (info) ==
3448       GST_VIDEO_INTERLACE_MODE_ALTERNATE)
3449     return V4L2_FIELD_ALTERNATE;
3450
3451   switch (GST_VIDEO_INFO_FIELD_ORDER (info)) {
3452     case GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST:
3453       return V4L2_FIELD_INTERLACED_TB;
3454     case GST_VIDEO_FIELD_ORDER_BOTTOM_FIELD_FIRST:
3455       return V4L2_FIELD_INTERLACED_BT;
3456     case GST_VIDEO_FIELD_ORDER_UNKNOWN:
3457     default:
3458       return V4L2_FIELD_INTERLACED;
3459   }
3460 }
3461
3462 static gboolean
3463 gst_v4l2_video_colorimetry_matches (const GstVideoColorimetry * cinfo,
3464     GstCaps * caps)
3465 {
3466   GstVideoInfo info;
3467   static const GstVideoColorimetry ci_likely_jpeg = {
3468     GST_VIDEO_COLOR_RANGE_0_255, GST_VIDEO_COLOR_MATRIX_BT601,
3469     GST_VIDEO_TRANSFER_UNKNOWN, GST_VIDEO_COLOR_PRIMARIES_UNKNOWN
3470   };
3471   static const GstVideoColorimetry ci_jpeg = {
3472     GST_VIDEO_COLOR_RANGE_0_255, GST_VIDEO_COLOR_MATRIX_BT601,
3473     GST_VIDEO_TRANSFER_SRGB, GST_VIDEO_COLOR_PRIMARIES_BT709
3474   };
3475
3476   if (!gst_video_info_from_caps (&info, caps))
3477     return FALSE;
3478
3479   /* if colorimetry in caps is unknown, use the default one */
3480   if (info.colorimetry.primaries == GST_VIDEO_COLOR_PRIMARIES_UNKNOWN)
3481     info.colorimetry.primaries = cinfo->primaries;
3482   if (info.colorimetry.range == GST_VIDEO_COLOR_RANGE_UNKNOWN)
3483     info.colorimetry.range = cinfo->range;
3484   if (info.colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_UNKNOWN)
3485     info.colorimetry.matrix = cinfo->matrix;
3486   if (info.colorimetry.transfer == GST_VIDEO_TRANSFER_UNKNOWN)
3487     info.colorimetry.transfer = cinfo->transfer;
3488
3489   if (gst_video_colorimetry_is_equal (&info.colorimetry, cinfo))
3490     return TRUE;
3491
3492   /* Allow 1:4:0:0 (produced by jpegdec) if the device expects 1:4:7:1 */
3493   if (gst_video_colorimetry_is_equal (&info.colorimetry, &ci_likely_jpeg)
3494       && gst_video_colorimetry_is_equal (cinfo, &ci_jpeg))
3495     return TRUE;
3496
3497   return FALSE;
3498 }
3499
3500 static const gchar *
3501 field_to_str (enum v4l2_field f)
3502 {
3503   switch (f) {
3504     case V4L2_FIELD_ANY:
3505       return "any";
3506     case V4L2_FIELD_NONE:
3507       return "none";
3508     case V4L2_FIELD_TOP:
3509       return "top";
3510     case V4L2_FIELD_BOTTOM:
3511       return "bottom";
3512     case V4L2_FIELD_INTERLACED:
3513       return "interlaced";
3514     case V4L2_FIELD_SEQ_TB:
3515       return "seq-tb";
3516     case V4L2_FIELD_SEQ_BT:
3517       return "seq-bt";
3518     case V4L2_FIELD_ALTERNATE:
3519       return "alternate";
3520     case V4L2_FIELD_INTERLACED_TB:
3521       return "interlaced-tb";
3522     case V4L2_FIELD_INTERLACED_BT:
3523       return "interlaced-bt";
3524   }
3525
3526   return "unknown";
3527 }
3528
3529 static gboolean
3530 gst_v4l2_object_set_format_full (GstV4l2Object * v4l2object, GstCaps * caps,
3531     gboolean try_only, GstV4l2Error * error)
3532 {
3533   gint fd = v4l2object->video_fd;
3534   struct v4l2_format format;
3535   struct v4l2_streamparm streamparm;
3536   enum v4l2_field field;
3537   guint32 pixelformat;
3538   struct v4l2_fmtdesc *fmtdesc;
3539   GstVideoInfo info;
3540   GstVideoAlignment align;
3541   gint width, height, fps_n, fps_d;
3542   gint n_v4l_planes;
3543   gint i = 0;
3544   gboolean is_mplane;
3545   enum v4l2_colorspace colorspace = 0;
3546   enum v4l2_quantization range = 0;
3547   enum v4l2_ycbcr_encoding matrix = 0;
3548   enum v4l2_xfer_func transfer = 0;
3549   GstStructure *s;
3550   gboolean disable_interlacing = FALSE;
3551   gboolean disable_colorimetry = FALSE;
3552
3553   g_return_val_if_fail (!v4l2object->skip_try_fmt_probes ||
3554       gst_caps_is_writable (caps), FALSE);
3555
3556   GST_V4L2_CHECK_OPEN (v4l2object);
3557   if (!try_only)
3558     GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
3559
3560   is_mplane = V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type);
3561
3562   gst_video_info_init (&info);
3563   gst_video_alignment_reset (&align);
3564   v4l2object->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
3565
3566   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
3567     goto invalid_caps;
3568
3569   pixelformat = fmtdesc->pixelformat;
3570   width = GST_VIDEO_INFO_WIDTH (&info);
3571   height = GST_VIDEO_INFO_FIELD_HEIGHT (&info);
3572   /* if caps has no width and height info, use default value */
3573   if (V4L2_TYPE_IS_OUTPUT (v4l2object->type) && width == 0 && height == 0) {
3574     width = GST_V4L2_DEFAULT_WIDTH;
3575     height = GST_V4L2_DEFAULT_HEIGHT;
3576   }
3577   fps_n = GST_VIDEO_INFO_FPS_N (&info);
3578   fps_d = GST_VIDEO_INFO_FPS_D (&info);
3579
3580   /* if encoded format (GST_VIDEO_INFO_N_PLANES return 0)
3581    * or if contiguous is preferred */
3582   n_v4l_planes = GST_VIDEO_INFO_N_PLANES (&info);
3583   if (!n_v4l_planes || !v4l2object->prefered_non_contiguous)
3584     n_v4l_planes = 1;
3585
3586   field = get_v4l2_field_for_info (&info);
3587   if (field != V4L2_FIELD_NONE)
3588     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
3589   else
3590     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
3591
3592   /* We first pick the main colorspace from the primaries */
3593   switch (info.colorimetry.primaries) {
3594     case GST_VIDEO_COLOR_PRIMARIES_BT709:
3595       /* There is two colorspaces using these primaries, use the range to
3596        * differentiate */
3597       if (info.colorimetry.range == GST_VIDEO_COLOR_RANGE_16_235)
3598         colorspace = V4L2_COLORSPACE_REC709;
3599       else
3600         colorspace = V4L2_COLORSPACE_SRGB;
3601       break;
3602     case GST_VIDEO_COLOR_PRIMARIES_BT2020:
3603       colorspace = V4L2_COLORSPACE_BT2020;
3604       break;
3605     case GST_VIDEO_COLOR_PRIMARIES_BT470M:
3606       colorspace = V4L2_COLORSPACE_470_SYSTEM_M;
3607       break;
3608     case GST_VIDEO_COLOR_PRIMARIES_BT470BG:
3609       colorspace = V4L2_COLORSPACE_470_SYSTEM_BG;
3610       break;
3611     case GST_VIDEO_COLOR_PRIMARIES_SMPTE170M:
3612       colorspace = V4L2_COLORSPACE_SMPTE170M;
3613       break;
3614     case GST_VIDEO_COLOR_PRIMARIES_SMPTE240M:
3615       colorspace = V4L2_COLORSPACE_SMPTE240M;
3616       break;
3617
3618     case GST_VIDEO_COLOR_PRIMARIES_FILM:
3619     case GST_VIDEO_COLOR_PRIMARIES_UNKNOWN:
3620       /* We don't know, we will guess */
3621       break;
3622
3623     default:
3624       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3625           "Unknown colorimetry primaries %d", info.colorimetry.primaries);
3626       break;
3627   }
3628
3629   switch (info.colorimetry.range) {
3630     case GST_VIDEO_COLOR_RANGE_0_255:
3631       range = V4L2_QUANTIZATION_FULL_RANGE;
3632       break;
3633     case GST_VIDEO_COLOR_RANGE_16_235:
3634       range = V4L2_QUANTIZATION_LIM_RANGE;
3635       break;
3636     case GST_VIDEO_COLOR_RANGE_UNKNOWN:
3637       /* We let the driver pick a default one */
3638       break;
3639     default:
3640       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3641           "Unknown colorimetry range %d", info.colorimetry.range);
3642       break;
3643   }
3644
3645   switch (info.colorimetry.matrix) {
3646     case GST_VIDEO_COLOR_MATRIX_RGB:
3647       /* Unspecified, leave to default */
3648       break;
3649       /* FCC is about the same as BT601 with less digit */
3650     case GST_VIDEO_COLOR_MATRIX_FCC:
3651     case GST_VIDEO_COLOR_MATRIX_BT601:
3652       matrix = V4L2_YCBCR_ENC_601;
3653       break;
3654     case GST_VIDEO_COLOR_MATRIX_BT709:
3655       matrix = V4L2_YCBCR_ENC_709;
3656       break;
3657     case GST_VIDEO_COLOR_MATRIX_SMPTE240M:
3658       matrix = V4L2_YCBCR_ENC_SMPTE240M;
3659       break;
3660     case GST_VIDEO_COLOR_MATRIX_BT2020:
3661       matrix = V4L2_YCBCR_ENC_BT2020;
3662       break;
3663     case GST_VIDEO_COLOR_MATRIX_UNKNOWN:
3664       /* We let the driver pick a default one */
3665       break;
3666     default:
3667       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3668           "Unknown colorimetry matrix %d", info.colorimetry.matrix);
3669       break;
3670   }
3671
3672   switch (info.colorimetry.transfer) {
3673     case GST_VIDEO_TRANSFER_GAMMA18:
3674     case GST_VIDEO_TRANSFER_GAMMA20:
3675     case GST_VIDEO_TRANSFER_GAMMA22:
3676     case GST_VIDEO_TRANSFER_GAMMA28:
3677       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3678           "GAMMA 18, 20, 22, 28 transfer functions not supported");
3679       /* fallthrough */
3680     case GST_VIDEO_TRANSFER_GAMMA10:
3681       transfer = V4L2_XFER_FUNC_NONE;
3682       break;
3683     case GST_VIDEO_TRANSFER_SMPTE2084:
3684       transfer = V4L2_XFER_FUNC_SMPTE2084;
3685       break;
3686     case GST_VIDEO_TRANSFER_BT601:
3687     case GST_VIDEO_TRANSFER_BT2020_12:
3688     case GST_VIDEO_TRANSFER_BT2020_10:
3689     case GST_VIDEO_TRANSFER_BT709:
3690       v4l2object->transfer = info.colorimetry.transfer;
3691       transfer = V4L2_XFER_FUNC_709;
3692       break;
3693     case GST_VIDEO_TRANSFER_SMPTE240M:
3694       transfer = V4L2_XFER_FUNC_SMPTE240M;
3695       break;
3696     case GST_VIDEO_TRANSFER_SRGB:
3697       transfer = V4L2_XFER_FUNC_SRGB;
3698       break;
3699     case GST_VIDEO_TRANSFER_LOG100:
3700     case GST_VIDEO_TRANSFER_LOG316:
3701       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3702           "LOG 100, 316 transfer functions not supported");
3703       /* FIXME No known sensible default, maybe AdobeRGB ? */
3704       break;
3705     case GST_VIDEO_TRANSFER_UNKNOWN:
3706       /* We let the driver pick a default one */
3707       break;
3708     default:
3709       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3710           "Unknown colorimetry transfer %d", info.colorimetry.transfer);
3711       break;
3712   }
3713
3714   if (colorspace == 0) {
3715     /* Try to guess colorspace according to pixelformat and size */
3716     if (GST_VIDEO_INFO_IS_YUV (&info)) {
3717       if (range == V4L2_QUANTIZATION_FULL_RANGE
3718           && matrix == V4L2_YCBCR_ENC_601 && transfer == 0) {
3719         /* Full range BT.601 YCbCr encoding with unknown primaries and transfer
3720          * function most likely is JPEG */
3721         colorspace = V4L2_COLORSPACE_JPEG;
3722         transfer = V4L2_XFER_FUNC_SRGB;
3723       } else {
3724         /* SD streams likely use SMPTE170M and HD streams REC709 */
3725         if (width <= 720 && GST_VIDEO_INFO_HEIGHT (&info) <= 576)
3726           colorspace = V4L2_COLORSPACE_SMPTE170M;
3727         else
3728           colorspace = V4L2_COLORSPACE_REC709;
3729       }
3730     } else if (GST_VIDEO_INFO_IS_RGB (&info)) {
3731       colorspace = V4L2_COLORSPACE_SRGB;
3732       transfer = V4L2_XFER_FUNC_NONE;
3733     }
3734   }
3735
3736   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired format %dx%d, format "
3737       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
3738       GST_FOURCC_ARGS (pixelformat), GST_VIDEO_INFO_PLANE_STRIDE (&info, 0));
3739
3740   memset (&format, 0x00, sizeof (struct v4l2_format));
3741   format.type = v4l2object->type;
3742
3743   if (is_mplane) {
3744     format.type = v4l2object->type;
3745     format.fmt.pix_mp.pixelformat = pixelformat;
3746     format.fmt.pix_mp.width = width;
3747     format.fmt.pix_mp.height = height;
3748     format.fmt.pix_mp.field = field;
3749     format.fmt.pix_mp.num_planes = n_v4l_planes;
3750
3751     /* try to ask our preferred stride but it's not a failure if not
3752      * accepted */
3753     for (i = 0; i < n_v4l_planes; i++) {
3754       gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, i);
3755
3756       if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
3757         stride = GST_VIDEO_TILE_X_TILES (stride) *
3758             GST_VIDEO_FORMAT_INFO_TILE_STRIDE (info.finfo, i);
3759
3760       format.fmt.pix_mp.plane_fmt[i].bytesperline = stride;
3761     }
3762
3763     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
3764       format.fmt.pix_mp.plane_fmt[0].sizeimage = ENCODED_BUFFER_SIZE;
3765   } else {
3766     gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
3767
3768     format.type = v4l2object->type;
3769
3770     format.fmt.pix.width = width;
3771     format.fmt.pix.height = height;
3772     format.fmt.pix.pixelformat = pixelformat;
3773     format.fmt.pix.field = field;
3774
3775     if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
3776       stride = GST_VIDEO_TILE_X_TILES (stride) *
3777           GST_VIDEO_FORMAT_INFO_TILE_STRIDE (info.finfo, i);
3778
3779     /* try to ask our preferred stride */
3780     format.fmt.pix.bytesperline = stride;
3781
3782     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
3783       format.fmt.pix.sizeimage = ENCODED_BUFFER_SIZE;
3784   }
3785
3786   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired format is %dx%d, format "
3787       "%" GST_FOURCC_FORMAT ", nb planes %d", format.fmt.pix.width,
3788       format.fmt.pix_mp.height,
3789       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
3790       is_mplane ? format.fmt.pix_mp.num_planes : 1);
3791
3792 #ifndef GST_DISABLE_GST_DEBUG
3793   if (is_mplane) {
3794     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
3795       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d",
3796           format.fmt.pix_mp.plane_fmt[i].bytesperline);
3797   } else {
3798     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d",
3799         format.fmt.pix.bytesperline);
3800   }
3801 #endif
3802
3803   if (is_mplane) {
3804     format.fmt.pix_mp.colorspace = colorspace;
3805     format.fmt.pix_mp.quantization = range;
3806     format.fmt.pix_mp.ycbcr_enc = matrix;
3807     format.fmt.pix_mp.xfer_func = transfer;
3808   } else {
3809     format.fmt.pix.priv = V4L2_PIX_FMT_PRIV_MAGIC;
3810     format.fmt.pix.colorspace = colorspace;
3811     format.fmt.pix.quantization = range;
3812     format.fmt.pix.ycbcr_enc = matrix;
3813     format.fmt.pix.xfer_func = transfer;
3814   }
3815
3816   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired colorspace is %d:%d:%d:%d",
3817       colorspace, range, matrix, transfer);
3818
3819   if (try_only) {
3820     if (v4l2object->ioctl (fd, VIDIOC_TRY_FMT, &format) < 0)
3821       goto try_fmt_failed;
3822   } else {
3823     if (v4l2object->ioctl (fd, VIDIOC_S_FMT, &format) < 0)
3824       goto set_fmt_failed;
3825   }
3826
3827   if (is_mplane) {
3828     colorspace = format.fmt.pix_mp.colorspace;
3829     range = format.fmt.pix_mp.quantization;
3830     matrix = format.fmt.pix_mp.ycbcr_enc;
3831     transfer = format.fmt.pix_mp.xfer_func;
3832   } else {
3833     colorspace = format.fmt.pix.colorspace;
3834     range = format.fmt.pix.quantization;
3835     matrix = format.fmt.pix.ycbcr_enc;
3836     transfer = format.fmt.pix.xfer_func;
3837   }
3838
3839   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got format of %dx%d, format "
3840       "%" GST_FOURCC_FORMAT ", nb planes %d, colorspace %d:%d:%d:%d field: %s",
3841       format.fmt.pix.width, format.fmt.pix_mp.height,
3842       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
3843       is_mplane ? format.fmt.pix_mp.num_planes : 1,
3844       colorspace, range, matrix, transfer, field_to_str (format.fmt.pix.field));
3845
3846 #ifndef GST_DISABLE_GST_DEBUG
3847   if (is_mplane) {
3848     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
3849       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d, sizeimage %d",
3850           format.fmt.pix_mp.plane_fmt[i].bytesperline,
3851           format.fmt.pix_mp.plane_fmt[i].sizeimage);
3852   } else {
3853     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d, sizeimage %d",
3854         format.fmt.pix.bytesperline, format.fmt.pix.sizeimage);
3855   }
3856 #endif
3857
3858   if (format.fmt.pix.pixelformat != pixelformat)
3859     goto invalid_pixelformat;
3860
3861   /* Only negotiate size with raw data.
3862    * For some codecs the dimensions are *not* in the bitstream, IIRC VC1
3863    * in ASF mode for example, there is also not reason for a driver to
3864    * change the size. */
3865   if (info.finfo->format != GST_VIDEO_FORMAT_ENCODED) {
3866     /* We can crop larger images */
3867     if (format.fmt.pix.width < width || format.fmt.pix.height < height)
3868       goto invalid_dimensions;
3869
3870     /* Note, this will be adjusted if upstream has non-centered cropping. */
3871     align.padding_top = 0;
3872     align.padding_bottom = format.fmt.pix.height - height;
3873     align.padding_left = 0;
3874     align.padding_right = format.fmt.pix.width - width;
3875   }
3876
3877   if (is_mplane && format.fmt.pix_mp.num_planes != n_v4l_planes)
3878     goto invalid_planes;
3879
3880   /* used to check colorimetry and interlace mode fields presence */
3881   s = gst_caps_get_structure (caps, 0);
3882
3883   if (gst_v4l2_object_get_interlace_mode (format.fmt.pix.field,
3884           &info.interlace_mode)) {
3885     if (gst_structure_has_field (s, "interlace-mode")) {
3886       if (format.fmt.pix.field != field)
3887         goto invalid_field;
3888     }
3889   } else {
3890     /* The driver (or libv4l2) is miss-behaving, just ignore interlace-mode from
3891      * the TRY_FMT */
3892     disable_interlacing = TRUE;
3893     if (gst_structure_has_field (s, "interlace-mode"))
3894       gst_structure_remove_field (s, "interlace-mode");
3895   }
3896
3897   if (gst_v4l2_object_get_colorspace (v4l2object, &format, &info.colorimetry)) {
3898     if (gst_structure_has_field (s, "colorimetry")) {
3899       if (!gst_v4l2_video_colorimetry_matches (&info.colorimetry, caps))
3900         goto invalid_colorimetry;
3901     }
3902   } else {
3903     /* The driver (or libv4l2) is miss-behaving, just ignore colorimetry from
3904      * the TRY_FMT */
3905     disable_colorimetry = TRUE;
3906     if (gst_structure_has_field (s, "colorimetry"))
3907       gst_structure_remove_field (s, "colorimetry");
3908   }
3909
3910   /* In case we have skipped the try_fmt probes, we'll need to set the
3911    * interlace-mode and colorimetry back into the caps. */
3912   if (v4l2object->skip_try_fmt_probes) {
3913     if (!disable_interlacing && !gst_structure_has_field (s, "interlace-mode")) {
3914       gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
3915           gst_video_interlace_mode_to_string (info.interlace_mode), NULL);
3916     }
3917     if (!disable_colorimetry && !gst_structure_has_field (s, "colorimetry")) {
3918       gchar *str = gst_video_colorimetry_to_string (&info.colorimetry);
3919       gst_structure_set (s, "colorimetry", G_TYPE_STRING, str, NULL);
3920       g_free (str);
3921     }
3922   }
3923
3924   if (try_only)                 /* good enough for trying only */
3925     return TRUE;
3926
3927   if (GST_VIDEO_INFO_HAS_ALPHA (&info)) {
3928     struct v4l2_control ctl = { 0, };
3929     ctl.id = V4L2_CID_ALPHA_COMPONENT;
3930     ctl.value = 0xff;
3931
3932     if (v4l2object->ioctl (fd, VIDIOC_S_CTRL, &ctl) < 0)
3933       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3934           "Failed to set alpha component value");
3935   }
3936
3937   /* Is there a reason we require the caller to always specify a framerate? */
3938   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired framerate: %u/%u", fps_n,
3939       fps_d);
3940
3941   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
3942   streamparm.type = v4l2object->type;
3943
3944   if (v4l2object->ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
3945     goto get_parm_failed;
3946
3947   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
3948       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
3949     GST_VIDEO_INFO_FPS_N (&info) =
3950         streamparm.parm.capture.timeperframe.denominator;
3951     GST_VIDEO_INFO_FPS_D (&info) =
3952         streamparm.parm.capture.timeperframe.numerator;
3953
3954     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got capture framerate: %u/%u",
3955         streamparm.parm.capture.timeperframe.denominator,
3956         streamparm.parm.capture.timeperframe.numerator);
3957
3958     /* We used to skip frame rate setup if the camera was already setup
3959      * with the requested frame rate. This breaks some cameras though,
3960      * causing them to not output data (several models of Thinkpad cameras
3961      * have this problem at least).
3962      * So, don't skip. */
3963     GST_LOG_OBJECT (v4l2object->dbg_obj, "Setting capture framerate to %u/%u",
3964         fps_n, fps_d);
3965     /* We want to change the frame rate, so check whether we can. Some cheap USB
3966      * cameras don't have the capability */
3967     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
3968       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
3969           "Not setting capture framerate (not supported)");
3970       goto done;
3971     }
3972
3973     /* Note: V4L2 wants the frame interval, we have the frame rate */
3974     streamparm.parm.capture.timeperframe.numerator = fps_d;
3975     streamparm.parm.capture.timeperframe.denominator = fps_n;
3976
3977     /* some cheap USB cam's won't accept any change */
3978     if (v4l2object->ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
3979       goto set_parm_failed;
3980
3981     if (streamparm.parm.capture.timeperframe.numerator > 0 &&
3982         streamparm.parm.capture.timeperframe.denominator > 0) {
3983       /* get new values */
3984       fps_d = streamparm.parm.capture.timeperframe.numerator;
3985       fps_n = streamparm.parm.capture.timeperframe.denominator;
3986
3987       GST_INFO_OBJECT (v4l2object->dbg_obj, "Set capture framerate to %u/%u",
3988           fps_n, fps_d);
3989     } else {
3990       /* fix v4l2 capture driver to provide framerate values */
3991       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3992           "Reuse caps framerate %u/%u - fix v4l2 capture driver", fps_n, fps_d);
3993     }
3994
3995     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
3996     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
3997   } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT
3998       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
3999     GST_VIDEO_INFO_FPS_N (&info) =
4000         streamparm.parm.output.timeperframe.denominator;
4001     GST_VIDEO_INFO_FPS_D (&info) =
4002         streamparm.parm.output.timeperframe.numerator;
4003
4004     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got output framerate: %u/%u",
4005         streamparm.parm.output.timeperframe.denominator,
4006         streamparm.parm.output.timeperframe.numerator);
4007
4008     GST_LOG_OBJECT (v4l2object->dbg_obj, "Setting output framerate to %u/%u",
4009         fps_n, fps_d);
4010     if ((streamparm.parm.output.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
4011       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4012           "Not setting output framerate (not supported)");
4013       goto done;
4014     }
4015
4016     /* Note: V4L2 wants the frame interval, we have the frame rate */
4017     streamparm.parm.output.timeperframe.numerator = fps_d;
4018     streamparm.parm.output.timeperframe.denominator = fps_n;
4019
4020     if (v4l2object->ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
4021       goto set_parm_failed;
4022
4023     if (streamparm.parm.output.timeperframe.numerator > 0 &&
4024         streamparm.parm.output.timeperframe.denominator > 0) {
4025       /* get new values */
4026       fps_d = streamparm.parm.output.timeperframe.numerator;
4027       fps_n = streamparm.parm.output.timeperframe.denominator;
4028
4029       GST_INFO_OBJECT (v4l2object->dbg_obj, "Set output framerate to %u/%u",
4030           fps_n, fps_d);
4031     } else {
4032       /* fix v4l2 output driver to provide framerate values */
4033       GST_WARNING_OBJECT (v4l2object->dbg_obj,
4034           "Reuse caps framerate %u/%u - fix v4l2 output driver", fps_n, fps_d);
4035     }
4036
4037     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
4038     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
4039   }
4040
4041 done:
4042   /* add boolean return, so we can fail on drivers bugs */
4043   gst_v4l2_object_save_format (v4l2object, fmtdesc, &format, &info, &align);
4044
4045   /* reset composition region to match the S_FMT size */
4046   gst_v4l2_object_reset_compose_region (v4l2object);
4047
4048   /* now configure the pool */
4049   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
4050     goto pool_failed;
4051
4052   return TRUE;
4053
4054   /* ERRORS */
4055 invalid_caps:
4056   {
4057     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "can't parse caps %" GST_PTR_FORMAT,
4058         caps);
4059
4060     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4061         (_("Invalid caps")), ("Can't parse caps %" GST_PTR_FORMAT, caps));
4062     return FALSE;
4063   }
4064 try_fmt_failed:
4065   {
4066     if (errno == EINVAL) {
4067       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4068           (_("Device '%s' has no supported format"), v4l2object->videodev),
4069           ("Call to TRY_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4070               GST_FOURCC_ARGS (pixelformat), width, height,
4071               g_strerror (errno)));
4072     } else {
4073       GST_V4L2_ERROR (error, RESOURCE, FAILED,
4074           (_("Device '%s' failed during initialization"),
4075               v4l2object->videodev),
4076           ("Call to TRY_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4077               GST_FOURCC_ARGS (pixelformat), width, height,
4078               g_strerror (errno)));
4079     }
4080     return FALSE;
4081   }
4082 set_fmt_failed:
4083   {
4084     if (errno == EBUSY) {
4085       GST_V4L2_ERROR (error, RESOURCE, BUSY,
4086           (_("Device '%s' is busy"), v4l2object->videodev),
4087           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4088               GST_FOURCC_ARGS (pixelformat), width, height,
4089               g_strerror (errno)));
4090     } else if (errno == EINVAL) {
4091       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4092           (_("Device '%s' has no supported format"), v4l2object->videodev),
4093           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4094               GST_FOURCC_ARGS (pixelformat), width, height,
4095               g_strerror (errno)));
4096     } else {
4097       GST_V4L2_ERROR (error, RESOURCE, FAILED,
4098           (_("Device '%s' failed during initialization"),
4099               v4l2object->videodev),
4100           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4101               GST_FOURCC_ARGS (pixelformat), width, height,
4102               g_strerror (errno)));
4103     }
4104     return FALSE;
4105   }
4106 invalid_dimensions:
4107   {
4108     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4109         (_("Device '%s' cannot capture at %dx%d"),
4110             v4l2object->videodev, width, height),
4111         ("Tried to capture at %dx%d, but device returned size %dx%d",
4112             width, height, format.fmt.pix.width, format.fmt.pix.height));
4113     return FALSE;
4114   }
4115 invalid_pixelformat:
4116   {
4117     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4118         (_("Device '%s' cannot capture in the specified format"),
4119             v4l2object->videodev),
4120         ("Tried to capture in %" GST_FOURCC_FORMAT
4121             ", but device returned format" " %" GST_FOURCC_FORMAT,
4122             GST_FOURCC_ARGS (pixelformat),
4123             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
4124     return FALSE;
4125   }
4126 invalid_planes:
4127   {
4128     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4129         (_("Device '%s' does support non-contiguous planes"),
4130             v4l2object->videodev),
4131         ("Device wants %d planes", format.fmt.pix_mp.num_planes));
4132     return FALSE;
4133   }
4134 invalid_field:
4135   {
4136     enum v4l2_field wanted_field;
4137
4138     if (is_mplane)
4139       wanted_field = format.fmt.pix_mp.field;
4140     else
4141       wanted_field = format.fmt.pix.field;
4142
4143     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4144         (_("Device '%s' does not support %s interlacing"),
4145             v4l2object->videodev,
4146             field == V4L2_FIELD_NONE ? "progressive" : "interleaved"),
4147         ("Device wants %s interlacing",
4148             wanted_field == V4L2_FIELD_NONE ? "progressive" : "interleaved"));
4149     return FALSE;
4150   }
4151 invalid_colorimetry:
4152   {
4153     gchar *wanted_colorimetry;
4154
4155     wanted_colorimetry = gst_video_colorimetry_to_string (&info.colorimetry);
4156
4157     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4158         (_("Device '%s' does not support %s colorimetry"),
4159             v4l2object->videodev, gst_structure_get_string (s, "colorimetry")),
4160         ("Device wants %s colorimetry", wanted_colorimetry));
4161
4162     g_free (wanted_colorimetry);
4163     return FALSE;
4164   }
4165 get_parm_failed:
4166   {
4167     /* it's possible that this call is not supported */
4168     if (errno != EINVAL && errno != ENOTTY) {
4169       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4170           (_("Could not get parameters on device '%s'"),
4171               v4l2object->videodev), GST_ERROR_SYSTEM);
4172     }
4173     goto done;
4174   }
4175 set_parm_failed:
4176   {
4177     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4178         (_("Video device did not accept new frame rate setting.")),
4179         GST_ERROR_SYSTEM);
4180     goto done;
4181   }
4182 pool_failed:
4183   {
4184     /* setup_pool already send the error */
4185     return FALSE;
4186   }
4187 }
4188
4189 gboolean
4190 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps,
4191     GstV4l2Error * error)
4192 {
4193   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Setting format to %" GST_PTR_FORMAT,
4194       caps);
4195   return gst_v4l2_object_set_format_full (v4l2object, caps, FALSE, error);
4196 }
4197
4198 gboolean
4199 gst_v4l2_object_try_format (GstV4l2Object * v4l2object, GstCaps * caps,
4200     GstV4l2Error * error)
4201 {
4202   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Trying format %" GST_PTR_FORMAT,
4203       caps);
4204   return gst_v4l2_object_set_format_full (v4l2object, caps, TRUE, error);
4205 }
4206
4207 /**
4208  * gst_v4l2_object_acquire_format:
4209  * @v4l2object: the object
4210  * @info: a GstVideoInfo to be filled
4211  *
4212  * Acquire the driver chosen format. This is useful in decoder or encoder elements where
4213  * the output format is chosen by the HW.
4214  *
4215  * Returns: %TRUE on success, %FALSE on failure.
4216  */
4217 gboolean
4218 gst_v4l2_object_acquire_format (GstV4l2Object * v4l2object, GstVideoInfo * info)
4219 {
4220   struct v4l2_fmtdesc *fmtdesc;
4221   struct v4l2_format fmt;
4222   struct v4l2_crop crop;
4223   struct v4l2_selection sel;
4224   struct v4l2_rect *r = NULL;
4225   GstVideoFormat format;
4226   guint width, height;
4227   GstVideoAlignment align;
4228   GstVideoInterlaceMode interlace_mode;
4229
4230   gst_video_info_init (info);
4231   gst_video_alignment_reset (&align);
4232   v4l2object->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
4233
4234   memset (&fmt, 0x00, sizeof (struct v4l2_format));
4235   fmt.type = v4l2object->type;
4236   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_FMT, &fmt) < 0)
4237     goto get_fmt_failed;
4238
4239   fmtdesc = gst_v4l2_object_get_format_from_fourcc (v4l2object,
4240       fmt.fmt.pix.pixelformat);
4241   if (fmtdesc == NULL)
4242     goto unsupported_format;
4243
4244   /* No need to care about mplane, the four first params are the same */
4245   format = gst_v4l2_object_v4l2fourcc_to_video_format (fmt.fmt.pix.pixelformat);
4246
4247   /* fails if we do no translate the fmt.pix.pixelformat to GstVideoFormat */
4248   if (format == GST_VIDEO_FORMAT_UNKNOWN)
4249     goto unsupported_format;
4250
4251   if (fmt.fmt.pix.width == 0 || fmt.fmt.pix.height == 0)
4252     goto invalid_dimensions;
4253
4254   width = fmt.fmt.pix.width;
4255   height = fmt.fmt.pix.height;
4256
4257   /* Use the default compose rectangle */
4258   memset (&sel, 0, sizeof (struct v4l2_selection));
4259   sel.type = v4l2object->type;
4260   sel.target = V4L2_SEL_TGT_COMPOSE_DEFAULT;
4261   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_SELECTION, &sel) >= 0) {
4262     r = &sel.r;
4263   } else {
4264     /* For ancient kernels, fall back to G_CROP */
4265     memset (&crop, 0, sizeof (struct v4l2_crop));
4266     crop.type = v4l2object->type;
4267     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CROP, &crop) >= 0)
4268       r = &crop.c;
4269   }
4270   if (r) {
4271     align.padding_left = r->left;
4272     align.padding_top = r->top;
4273     align.padding_right = width - r->width - r->left;
4274     align.padding_bottom = height - r->height - r->top;
4275     width = r->width;
4276     height = r->height;
4277   }
4278
4279   switch (fmt.fmt.pix.field) {
4280     case V4L2_FIELD_ANY:
4281     case V4L2_FIELD_NONE:
4282       interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
4283       break;
4284     case V4L2_FIELD_INTERLACED:
4285     case V4L2_FIELD_INTERLACED_TB:
4286     case V4L2_FIELD_INTERLACED_BT:
4287       interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
4288       break;
4289     case V4L2_FIELD_ALTERNATE:
4290       interlace_mode = GST_VIDEO_INTERLACE_MODE_ALTERNATE;
4291       break;
4292     default:
4293       goto unsupported_field;
4294   }
4295
4296   gst_video_info_set_interlaced_format (info, format, interlace_mode, width,
4297       height);
4298
4299   gst_v4l2_object_get_colorspace (v4l2object, &fmt, &info->colorimetry);
4300   gst_v4l2_object_get_streamparm (v4l2object, info);
4301   if ((info->fps_n == 0 && v4l2object->info.fps_d != 0)
4302       && (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
4303           || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
4304     info->fps_d = v4l2object->info.fps_d;
4305     info->fps_n = v4l2object->info.fps_n;
4306     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Set capture fps to %d/%d",
4307         info->fps_n, info->fps_d);
4308   }
4309
4310   gst_v4l2_object_save_format (v4l2object, fmtdesc, &fmt, info, &align);
4311
4312   /* Shall we setup the pool ? */
4313
4314   return TRUE;
4315
4316 get_fmt_failed:
4317   {
4318     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
4319         (_("Video device did not provide output format.")), GST_ERROR_SYSTEM);
4320     return FALSE;
4321   }
4322 invalid_dimensions:
4323   {
4324     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
4325         (_("Video device returned invalid dimensions.")),
4326         ("Expected non 0 dimensions, got %dx%d", fmt.fmt.pix.width,
4327             fmt.fmt.pix.height));
4328     return FALSE;
4329   }
4330 unsupported_field:
4331   {
4332     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
4333         (_("Video device uses an unsupported interlacing method.")),
4334         ("V4L2 field type %d not supported", fmt.fmt.pix.field));
4335     return FALSE;
4336   }
4337 unsupported_format:
4338   {
4339     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
4340         (_("Video device uses an unsupported pixel format.")),
4341         ("V4L2 format %" GST_FOURCC_FORMAT " not supported",
4342             GST_FOURCC_ARGS (fmt.fmt.pix.pixelformat)));
4343     return FALSE;
4344   }
4345 }
4346
4347 /**
4348  * gst_v4l2_object_set_crop:
4349  * @obj: the object
4350  * @crop_rect: the region to crop
4351  *
4352  * Crop the video data to the regions specified in the @crop_rect.
4353  *
4354  * For capture devices, this crop the image sensor / video stream provided by
4355  * the V4L2 device.
4356  * For output devices, this crops the memory buffer that GStreamer passed to
4357  * the V4L2 device.
4358  *
4359  * The crop_rect may be modified by the V4L2 device to a region that
4360  * fulfills H/W requirements.
4361  *
4362  * Returns: %TRUE on success, %FALSE on failure.
4363  */
4364 gboolean
4365 gst_v4l2_object_set_crop (GstV4l2Object * obj, struct v4l2_rect * crop_rect)
4366 {
4367   struct v4l2_selection sel = { 0 };
4368   struct v4l2_crop crop = { 0 };
4369
4370   GST_V4L2_CHECK_OPEN (obj);
4371
4372   sel.type = obj->type;
4373   sel.target = V4L2_SEL_TGT_CROP;
4374   sel.flags = 0;
4375   sel.r = *crop_rect;
4376
4377   crop.type = obj->type;
4378   crop.c = sel.r;
4379
4380   GST_DEBUG_OBJECT (obj->dbg_obj,
4381       "Desired cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
4382       crop.c.width, crop.c.height);
4383
4384   if (obj->ioctl (obj->video_fd, VIDIOC_S_SELECTION, &sel) < 0) {
4385     if (errno != ENOTTY) {
4386       GST_WARNING_OBJECT (obj->dbg_obj,
4387           "Failed to set crop rectangle with VIDIOC_S_SELECTION: %s",
4388           g_strerror (errno));
4389       return FALSE;
4390     } else {
4391       if (obj->ioctl (obj->video_fd, VIDIOC_S_CROP, &crop) < 0) {
4392         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_S_CROP failed");
4393         return FALSE;
4394       }
4395
4396       if (obj->ioctl (obj->video_fd, VIDIOC_G_CROP, &crop) < 0) {
4397         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_G_CROP failed");
4398         return FALSE;
4399       }
4400
4401       sel.r = crop.c;
4402     }
4403   }
4404
4405   GST_DEBUG_OBJECT (obj->dbg_obj,
4406       "Got cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
4407       crop.c.width, crop.c.height);
4408
4409   return TRUE;
4410 }
4411
4412 /**
4413  * gst_v4l2_object_setup_padding:
4414  * @obj: v4l2 object
4415  *
4416  * Crop away the padding around the video data as specified
4417  * in GstVideoAlignement data stored in @obj.
4418  *
4419  * For capture devices, this crop the image sensor / video stream provided by
4420  * the V4L2 device.
4421  * For output devices, this crops the memory buffer that GStreamer passed to
4422  * the V4L2 device.
4423  *
4424  * Returns: %TRUE on success, %FALSE on failure.
4425  */
4426 gboolean
4427 gst_v4l2_object_setup_padding (GstV4l2Object * obj)
4428 {
4429   GstVideoAlignment *align = &obj->align;
4430   struct v4l2_rect crop;
4431
4432   if (align->padding_left + align->padding_top
4433       + align->padding_right + align->padding_bottom == 0) {
4434     GST_DEBUG_OBJECT (obj->dbg_obj, "no cropping needed");
4435     return TRUE;
4436   }
4437
4438   crop.left = align->padding_left;
4439   crop.top = align->padding_top;
4440   crop.width = obj->info.width;
4441   crop.height = GST_VIDEO_INFO_FIELD_HEIGHT (&obj->info);
4442
4443   return gst_v4l2_object_set_crop (obj, &crop);
4444 }
4445
4446 static gboolean
4447 gst_v4l2_object_get_crop_rect (GstV4l2Object * obj, guint target,
4448     struct v4l2_rect *result)
4449 {
4450   struct v4l2_rect *res_rect;
4451
4452   struct v4l2_selection sel = { 0 };
4453   struct v4l2_cropcap cropcap = { 0 };
4454
4455   GST_V4L2_CHECK_OPEN (obj);
4456
4457   if (target != V4L2_SEL_TGT_CROP_BOUNDS && target != V4L2_SEL_TGT_CROP_DEFAULT)
4458     return FALSE;
4459
4460   sel.type = obj->type;
4461   sel.target = target;
4462
4463   res_rect = &sel.r;
4464
4465   if (obj->ioctl (obj->video_fd, VIDIOC_G_SELECTION, &sel) < 0) {
4466     if (errno != ENOTTY) {
4467       GST_WARNING_OBJECT (obj->dbg_obj,
4468           "Failed to get default crop rectangle with VIDIOC_G_SELECTION: %s",
4469           g_strerror (errno));
4470       return FALSE;
4471     } else {
4472       if (obj->ioctl (obj->video_fd, VIDIOC_CROPCAP, &cropcap) < 0) {
4473         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_CROPCAP failed");
4474         return FALSE;
4475       }
4476       if (target == V4L2_SEL_TGT_CROP_BOUNDS)
4477         res_rect = &cropcap.bounds;
4478       else if (target == V4L2_SEL_TGT_CROP_DEFAULT)
4479         res_rect = &cropcap.defrect;
4480     }
4481   }
4482
4483   *result = *res_rect;
4484   return TRUE;
4485 }
4486
4487 gboolean
4488 gst_v4l2_object_get_crop_bounds (GstV4l2Object * obj, struct v4l2_rect * result)
4489 {
4490   return gst_v4l2_object_get_crop_rect (obj, V4L2_SEL_TGT_CROP_BOUNDS, result);
4491 }
4492
4493 gboolean
4494 gst_v4l2_object_get_crop_default (GstV4l2Object * obj,
4495     struct v4l2_rect * result)
4496 {
4497   return gst_v4l2_object_get_crop_rect (obj, V4L2_SEL_TGT_CROP_DEFAULT, result);
4498 }
4499
4500 gboolean
4501 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
4502 {
4503   GstStructure *config;
4504   GstCaps *oldcaps;
4505   gboolean ret;
4506
4507   if (!v4l2object->pool)
4508     return FALSE;
4509
4510   config = gst_buffer_pool_get_config (v4l2object->pool);
4511   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4512
4513   ret = oldcaps && gst_caps_is_equal (caps, oldcaps);
4514
4515   gst_structure_free (config);
4516
4517   return ret;
4518 }
4519
4520 gboolean
4521 gst_v4l2_object_caps_is_subset (GstV4l2Object * v4l2object, GstCaps * caps)
4522 {
4523   GstStructure *config;
4524   GstCaps *oldcaps;
4525   gboolean ret;
4526
4527   if (!v4l2object->pool)
4528     return FALSE;
4529
4530   config = gst_buffer_pool_get_config (v4l2object->pool);
4531   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4532
4533   ret = oldcaps && gst_caps_is_subset (oldcaps, caps);
4534
4535   gst_structure_free (config);
4536
4537   return ret;
4538 }
4539
4540 GstCaps *
4541 gst_v4l2_object_get_current_caps (GstV4l2Object * v4l2object)
4542 {
4543   GstStructure *config;
4544   GstCaps *oldcaps;
4545
4546   if (!v4l2object->pool)
4547     return NULL;
4548
4549   config = gst_buffer_pool_get_config (v4l2object->pool);
4550   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4551
4552   if (oldcaps)
4553     gst_caps_ref (oldcaps);
4554
4555   gst_structure_free (config);
4556
4557   return oldcaps;
4558 }
4559
4560 gboolean
4561 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
4562 {
4563   gboolean ret = TRUE;
4564
4565   GST_LOG_OBJECT (v4l2object->dbg_obj, "start flushing");
4566
4567   if (v4l2object->pool && gst_buffer_pool_is_active (v4l2object->pool))
4568     gst_buffer_pool_set_flushing (v4l2object->pool, TRUE);
4569
4570   return ret;
4571 }
4572
4573 gboolean
4574 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
4575 {
4576   gboolean ret = TRUE;
4577
4578   GST_LOG_OBJECT (v4l2object->dbg_obj, "stop flushing");
4579
4580   if (v4l2object->pool && gst_buffer_pool_is_active (v4l2object->pool))
4581     gst_buffer_pool_set_flushing (v4l2object->pool, FALSE);
4582
4583   return ret;
4584 }
4585
4586 gboolean
4587 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
4588 {
4589   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "stopping");
4590
4591   if (!GST_V4L2_IS_OPEN (v4l2object))
4592     goto done;
4593   if (!GST_V4L2_IS_ACTIVE (v4l2object))
4594     goto done;
4595
4596   if (v4l2object->pool) {
4597     if (!gst_v4l2_buffer_pool_orphan (&v4l2object->pool)) {
4598       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "deactivating pool");
4599       gst_buffer_pool_set_active (v4l2object->pool, FALSE);
4600       gst_object_unref (v4l2object->pool);
4601     }
4602     v4l2object->pool = NULL;
4603   }
4604
4605   GST_V4L2_SET_INACTIVE (v4l2object);
4606
4607 done:
4608   return TRUE;
4609 }
4610
4611 GstCaps *
4612 gst_v4l2_object_probe_caps (GstV4l2Object * v4l2object, GstCaps * filter)
4613 {
4614   GstCaps *ret;
4615   GSList *walk;
4616   GSList *formats;
4617
4618   formats = gst_v4l2_object_get_format_list (v4l2object);
4619
4620   ret = gst_caps_new_empty ();
4621
4622   if (v4l2object->keep_aspect && !v4l2object->par) {
4623     struct v4l2_cropcap cropcap;
4624
4625     memset (&cropcap, 0, sizeof (cropcap));
4626
4627     cropcap.type = v4l2object->type;
4628     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_CROPCAP, &cropcap) < 0) {
4629       if (errno != ENOTTY)
4630         GST_WARNING_OBJECT (v4l2object->dbg_obj,
4631             "Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: %s",
4632             g_strerror (errno));
4633     } else if (cropcap.pixelaspect.numerator && cropcap.pixelaspect.denominator) {
4634       v4l2object->par = g_new0 (GValue, 1);
4635       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
4636       gst_value_set_fraction (v4l2object->par, cropcap.pixelaspect.numerator,
4637           cropcap.pixelaspect.denominator);
4638     }
4639   }
4640
4641   for (walk = formats; walk; walk = walk->next) {
4642     struct v4l2_fmtdesc *format;
4643     GstStructure *template;
4644     GstCaps *tmp;
4645
4646     format = (struct v4l2_fmtdesc *) walk->data;
4647
4648     template = gst_v4l2_object_v4l2fourcc_to_bare_struct (format->pixelformat);
4649
4650     if (!template) {
4651       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4652           "unknown format %" GST_FOURCC_FORMAT,
4653           GST_FOURCC_ARGS (format->pixelformat));
4654       continue;
4655     }
4656
4657     /* If we have a filter, check if we need to probe this format or not */
4658     if (filter) {
4659       GstCaps *format_caps = gst_caps_new_empty ();
4660
4661       gst_caps_append_structure (format_caps, gst_structure_copy (template));
4662
4663       if (!gst_caps_can_intersect (format_caps, filter)) {
4664         gst_caps_unref (format_caps);
4665         gst_structure_free (template);
4666         continue;
4667       }
4668
4669       gst_caps_unref (format_caps);
4670     }
4671
4672     tmp = gst_v4l2_object_probe_caps_for_format (v4l2object,
4673         format->pixelformat, template);
4674     if (tmp) {
4675       gst_caps_append (ret, tmp);
4676
4677       /* Add a variant of the caps with the Interlaced feature so we can negotiate it if needed */
4678       add_alternate_variant (v4l2object, ret, gst_caps_get_structure (ret,
4679               gst_caps_get_size (ret) - 1));
4680     }
4681
4682     gst_structure_free (template);
4683   }
4684
4685   if (filter) {
4686     GstCaps *tmp;
4687
4688     tmp = ret;
4689     ret = gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
4690     gst_caps_unref (tmp);
4691   }
4692
4693   GST_INFO_OBJECT (v4l2object->dbg_obj, "probed caps: %" GST_PTR_FORMAT, ret);
4694
4695   return ret;
4696 }
4697
4698 GstCaps *
4699 gst_v4l2_object_get_caps (GstV4l2Object * v4l2object, GstCaps * filter)
4700 {
4701   GstCaps *ret;
4702
4703   if (v4l2object->probed_caps == NULL)
4704     v4l2object->probed_caps = gst_v4l2_object_probe_caps (v4l2object, NULL);
4705
4706   if (filter) {
4707     ret = gst_caps_intersect_full (filter, v4l2object->probed_caps,
4708         GST_CAPS_INTERSECT_FIRST);
4709   } else {
4710     ret = gst_caps_ref (v4l2object->probed_caps);
4711   }
4712
4713   return ret;
4714 }
4715
4716 static gboolean
4717 gst_v4l2_object_match_buffer_layout (GstV4l2Object * obj, guint n_planes,
4718     gsize offset[GST_VIDEO_MAX_PLANES], gint stride[GST_VIDEO_MAX_PLANES],
4719     gsize buffer_size, guint padded_height)
4720 {
4721   guint p;
4722   gboolean need_fmt_update = FALSE;
4723
4724   if (n_planes != GST_VIDEO_INFO_N_PLANES (&obj->info)) {
4725     GST_WARNING_OBJECT (obj->dbg_obj,
4726         "Cannot match buffers with different number planes");
4727     return FALSE;
4728   }
4729
4730   for (p = 0; p < n_planes; p++) {
4731     if (stride[p] < obj->info.stride[p]) {
4732       GST_DEBUG_OBJECT (obj->dbg_obj,
4733           "Not matching as remote stride %i is smaller than %i on plane %u",
4734           stride[p], obj->info.stride[p], p);
4735       return FALSE;
4736     } else if (stride[p] > obj->info.stride[p]) {
4737       GST_LOG_OBJECT (obj->dbg_obj,
4738           "remote stride %i is higher than %i on plane %u",
4739           stride[p], obj->info.stride[p], p);
4740       need_fmt_update = TRUE;
4741     }
4742
4743     if (offset[p] < obj->info.offset[p]) {
4744       GST_DEBUG_OBJECT (obj->dbg_obj,
4745           "Not matching as offset %" G_GSIZE_FORMAT
4746           " is smaller than %" G_GSIZE_FORMAT " on plane %u",
4747           offset[p], obj->info.offset[p], p);
4748       return FALSE;
4749     } else if (offset[p] > obj->info.offset[p]) {
4750       GST_LOG_OBJECT (obj->dbg_obj,
4751           "Remote offset %" G_GSIZE_FORMAT
4752           " is higher than %" G_GSIZE_FORMAT " on plane %u",
4753           offset[p], obj->info.offset[p], p);
4754       need_fmt_update = TRUE;
4755     }
4756
4757     if (padded_height) {
4758       guint fmt_height;
4759
4760       if (V4L2_TYPE_IS_MULTIPLANAR (obj->type))
4761         fmt_height = obj->format.fmt.pix_mp.height;
4762       else
4763         fmt_height = obj->format.fmt.pix.height;
4764
4765       if (padded_height > fmt_height)
4766         need_fmt_update = TRUE;
4767     }
4768   }
4769
4770   if (need_fmt_update) {
4771     struct v4l2_format format;
4772     gint wanted_stride[GST_VIDEO_MAX_PLANES] = { 0, };
4773
4774     format = obj->format;
4775
4776     if (padded_height) {
4777       GST_DEBUG_OBJECT (obj->dbg_obj, "Padded height %u", padded_height);
4778
4779       obj->align.padding_bottom =
4780           padded_height - GST_VIDEO_INFO_FIELD_HEIGHT (&obj->info);
4781     } else {
4782       GST_WARNING_OBJECT (obj->dbg_obj,
4783           "Failed to compute padded height; keep the default one");
4784       padded_height = format.fmt.pix_mp.height;
4785     }
4786
4787     /* update the current format with the stride we want to import from */
4788     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
4789       guint i;
4790
4791       GST_DEBUG_OBJECT (obj->dbg_obj, "Wanted strides:");
4792
4793       for (i = 0; i < obj->n_v4l2_planes; i++) {
4794         gint plane_stride = stride[i];
4795
4796         if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo))
4797           plane_stride = GST_VIDEO_TILE_X_TILES (plane_stride) *
4798               GST_VIDEO_FORMAT_INFO_TILE_STRIDE (obj->info.finfo, i);
4799
4800         format.fmt.pix_mp.plane_fmt[i].bytesperline = plane_stride;
4801         format.fmt.pix_mp.height = padded_height;
4802         wanted_stride[i] = plane_stride;
4803         GST_DEBUG_OBJECT (obj->dbg_obj, "    [%u] %i", i, wanted_stride[i]);
4804       }
4805     } else {
4806       gint plane_stride = stride[0];
4807
4808       GST_DEBUG_OBJECT (obj->dbg_obj, "Wanted stride: %i", plane_stride);
4809
4810       if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo))
4811         plane_stride = GST_VIDEO_TILE_X_TILES (plane_stride) *
4812             GST_VIDEO_FORMAT_INFO_TILE_STRIDE (obj->info.finfo, 0);
4813
4814       format.fmt.pix.bytesperline = plane_stride;
4815       format.fmt.pix.height = padded_height;
4816       wanted_stride[0] = plane_stride;
4817     }
4818
4819     if (obj->ioctl (obj->video_fd, VIDIOC_S_FMT, &format) < 0) {
4820       GST_WARNING_OBJECT (obj->dbg_obj,
4821           "Something went wrong trying to update current format: %s",
4822           g_strerror (errno));
4823       return FALSE;
4824     }
4825
4826     gst_v4l2_object_save_format (obj, obj->fmtdesc, &format, &obj->info,
4827         &obj->align);
4828
4829     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
4830       guint i;
4831
4832       for (i = 0; i < obj->n_v4l2_planes; i++) {
4833         if (format.fmt.pix_mp.plane_fmt[i].bytesperline != wanted_stride[i]) {
4834           GST_DEBUG_OBJECT (obj->dbg_obj,
4835               "[%i] Driver did not accept the new stride (wants %i, got %i)",
4836               i, wanted_stride[i], format.fmt.pix_mp.plane_fmt[i].bytesperline);
4837           return FALSE;
4838         }
4839       }
4840
4841       if (format.fmt.pix_mp.height != padded_height) {
4842         GST_DEBUG_OBJECT (obj->dbg_obj,
4843             "Driver did not accept the padded height (wants %i, got %i)",
4844             padded_height, format.fmt.pix_mp.height);
4845       }
4846     } else {
4847       if (format.fmt.pix.bytesperline != wanted_stride[0]) {
4848         GST_DEBUG_OBJECT (obj->dbg_obj,
4849             "Driver did not accept the new stride (wants %i, got %i)",
4850             wanted_stride[0], format.fmt.pix.bytesperline);
4851         return FALSE;
4852       }
4853
4854       if (format.fmt.pix.height != padded_height) {
4855         GST_DEBUG_OBJECT (obj->dbg_obj,
4856             "Driver did not accept the padded height (wants %i, got %i)",
4857             padded_height, format.fmt.pix.height);
4858       }
4859     }
4860   }
4861
4862   if (obj->align.padding_bottom) {
4863     /* Crop because of vertical padding */
4864     GST_DEBUG_OBJECT (obj->dbg_obj, "crop because of bottom padding of %d",
4865         obj->align.padding_bottom);
4866     gst_v4l2_object_setup_padding (obj);
4867   }
4868
4869   return TRUE;
4870 }
4871
4872 static gboolean
4873 validate_video_meta_struct (GstV4l2Object * obj, const GstStructure * s)
4874 {
4875   guint i;
4876
4877   for (i = 0; i < gst_structure_n_fields (s); i++) {
4878     const gchar *name = gst_structure_nth_field_name (s, i);
4879
4880     if (!g_str_equal (name, "padding-top")
4881         && !g_str_equal (name, "padding-bottom")
4882         && !g_str_equal (name, "padding-left")
4883         && !g_str_equal (name, "padding-right")) {
4884       GST_WARNING_OBJECT (obj->dbg_obj, "Unknown video meta field: '%s'", name);
4885       return FALSE;
4886     }
4887   }
4888
4889   return TRUE;
4890 }
4891
4892 static gboolean
4893 gst_v4l2_object_match_buffer_layout_from_struct (GstV4l2Object * obj,
4894     const GstStructure * s, GstCaps * caps, guint buffer_size)
4895 {
4896   GstVideoInfo info;
4897   GstVideoAlignment align;
4898   gsize plane_size[GST_VIDEO_MAX_PLANES];
4899
4900   if (!validate_video_meta_struct (obj, s))
4901     return FALSE;
4902
4903   if (!gst_video_info_from_caps (&info, caps)) {
4904     GST_WARNING_OBJECT (obj->dbg_obj, "Failed to create video info");
4905     return FALSE;
4906   }
4907
4908   gst_video_alignment_reset (&align);
4909
4910   gst_structure_get_uint (s, "padding-top", &align.padding_top);
4911   gst_structure_get_uint (s, "padding-bottom", &align.padding_bottom);
4912   gst_structure_get_uint (s, "padding-left", &align.padding_left);
4913   gst_structure_get_uint (s, "padding-right", &align.padding_right);
4914
4915   if (align.padding_top || align.padding_bottom || align.padding_left ||
4916       align.padding_right) {
4917     GST_DEBUG_OBJECT (obj->dbg_obj,
4918         "Upstream requested padding (top: %d bottom: %d left: %d right: %d)",
4919         align.padding_top, align.padding_bottom, align.padding_left,
4920         align.padding_right);
4921   }
4922
4923   if (!gst_video_info_align_full (&info, &align, plane_size)) {
4924     GST_WARNING_OBJECT (obj->dbg_obj, "Failed to align video info");
4925     return FALSE;
4926   }
4927
4928   if (GST_VIDEO_INFO_SIZE (&info) != buffer_size) {
4929     GST_WARNING_OBJECT (obj->dbg_obj,
4930         "Requested buffer size (%d) doesn't match video info size (%"
4931         G_GSIZE_FORMAT ")", buffer_size, GST_VIDEO_INFO_SIZE (&info));
4932     return FALSE;
4933   }
4934
4935   GST_DEBUG_OBJECT (obj->dbg_obj,
4936       "try matching buffer layout requested by downstream");
4937
4938   gst_v4l2_object_match_buffer_layout (obj, GST_VIDEO_INFO_N_PLANES (&info),
4939       info.offset, info.stride, buffer_size,
4940       GST_VIDEO_INFO_PLANE_HEIGHT (&info, 0, plane_size));
4941
4942   return TRUE;
4943 }
4944
4945 gboolean
4946 gst_v4l2_object_decide_allocation (GstV4l2Object * obj, GstQuery * query)
4947 {
4948   GstCaps *caps;
4949   GstBufferPool *pool = NULL, *other_pool = NULL;
4950   GstStructure *config;
4951   guint size, min, max, own_min = 0;
4952   gboolean update;
4953   gboolean has_video_meta;
4954   gboolean can_share_own_pool, pushing_from_our_pool = FALSE;
4955   GstAllocator *allocator = NULL;
4956   GstAllocationParams params = { 0 };
4957   guint video_idx;
4958
4959   GST_DEBUG_OBJECT (obj->dbg_obj, "decide allocation");
4960
4961   g_return_val_if_fail (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
4962       obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, FALSE);
4963
4964   gst_query_parse_allocation (query, &caps, NULL);
4965
4966   if (obj->pool == NULL) {
4967     if (!gst_v4l2_object_setup_pool (obj, caps))
4968       goto pool_failed;
4969   }
4970
4971   if (gst_query_get_n_allocation_params (query) > 0)
4972     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
4973
4974   if (gst_query_get_n_allocation_pools (query) > 0) {
4975     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
4976     update = TRUE;
4977   } else {
4978     pool = NULL;
4979     min = max = 0;
4980     size = 0;
4981     update = FALSE;
4982   }
4983
4984   GST_DEBUG_OBJECT (obj->dbg_obj, "allocation: size:%u min:%u max:%u pool:%"
4985       GST_PTR_FORMAT, size, min, max, pool);
4986
4987   has_video_meta =
4988       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE,
4989       &video_idx);
4990
4991   if (has_video_meta) {
4992     const GstStructure *params;
4993     gst_query_parse_nth_allocation_meta (query, video_idx, &params);
4994
4995     if (params)
4996       gst_v4l2_object_match_buffer_layout_from_struct (obj, params, caps, size);
4997   }
4998
4999   can_share_own_pool = (has_video_meta || !obj->need_video_meta);
5000
5001   gst_v4l2_get_driver_min_buffers (obj);
5002   /* We can't share our own pool, if it exceed V4L2 capacity */
5003   if (min + obj->min_buffers + 1 > VIDEO_MAX_FRAME)
5004     can_share_own_pool = FALSE;
5005
5006   /* select a pool */
5007   switch (obj->mode) {
5008     case GST_V4L2_IO_RW:
5009       if (pool) {
5010         /* in READ/WRITE mode, prefer a downstream pool because our own pool
5011          * doesn't help much, we have to write to it as well */
5012         GST_DEBUG_OBJECT (obj->dbg_obj,
5013             "read/write mode: using downstream pool");
5014         /* use the bigest size, when we use our own pool we can't really do any
5015          * other size than what the hardware gives us but for downstream pools
5016          * we can try */
5017         size = MAX (size, obj->info.size);
5018       } else if (can_share_own_pool) {
5019         /* no downstream pool, use our own then */
5020         GST_DEBUG_OBJECT (obj->dbg_obj,
5021             "read/write mode: no downstream pool, using our own");
5022         pool = gst_object_ref (obj->pool);
5023         size = obj->info.size;
5024         pushing_from_our_pool = TRUE;
5025       }
5026       break;
5027
5028     case GST_V4L2_IO_USERPTR:
5029     case GST_V4L2_IO_DMABUF_IMPORT:
5030       /* in importing mode, prefer our own pool, and pass the other pool to
5031        * our own, so it can serve itself */
5032       if (pool == NULL)
5033         goto no_downstream_pool;
5034       gst_v4l2_buffer_pool_set_other_pool (GST_V4L2_BUFFER_POOL (obj->pool),
5035           pool);
5036       other_pool = pool;
5037       gst_object_unref (pool);
5038       pool = gst_object_ref (obj->pool);
5039       size = obj->info.size;
5040       break;
5041
5042     case GST_V4L2_IO_MMAP:
5043     case GST_V4L2_IO_DMABUF:
5044       /* in streaming mode, prefer our own pool */
5045       /* Check if we can use it ... */
5046       if (can_share_own_pool) {
5047         if (pool)
5048           gst_object_unref (pool);
5049         pool = gst_object_ref (obj->pool);
5050         size = obj->info.size;
5051         GST_DEBUG_OBJECT (obj->dbg_obj,
5052             "streaming mode: using our own pool %" GST_PTR_FORMAT, pool);
5053         pushing_from_our_pool = TRUE;
5054       } else if (pool) {
5055         GST_DEBUG_OBJECT (obj->dbg_obj,
5056             "streaming mode: copying to downstream pool %" GST_PTR_FORMAT,
5057             pool);
5058       } else {
5059         GST_DEBUG_OBJECT (obj->dbg_obj,
5060             "streaming mode: no usable pool, copying to generic pool");
5061         size = MAX (size, obj->info.size);
5062       }
5063       break;
5064     case GST_V4L2_IO_AUTO:
5065     default:
5066       GST_WARNING_OBJECT (obj->dbg_obj, "unhandled mode");
5067       break;
5068   }
5069
5070   if (size == 0)
5071     goto no_size;
5072
5073   /* If pushing from our own pool, configure it with queried minimum,
5074    * otherwise use the minimum required */
5075   if (pushing_from_our_pool) {
5076     /* When pushing from our own pool, we need what downstream one, to be able
5077      * to fill the pipeline, the minimum required to decoder according to the
5078      * driver and 2 more, so we don't endup up with everything downstream or
5079      * held by the decoder. We account 2 buffers for v4l2 so when one is being
5080      * pushed downstream the other one can already be queued for the next
5081      * frame. */
5082     own_min = min + obj->min_buffers + 2;
5083
5084     /* If no allocation parameters where provided, allow for a little more
5085      * buffers and enable copy threshold */
5086     if (!update) {
5087       own_min += 2;
5088       gst_v4l2_buffer_pool_copy_at_threshold (GST_V4L2_BUFFER_POOL (pool),
5089           TRUE);
5090     } else {
5091       gst_v4l2_buffer_pool_copy_at_threshold (GST_V4L2_BUFFER_POOL (pool),
5092           FALSE);
5093     }
5094
5095   } else {
5096     /* In this case we'll have to configure two buffer pool. For our buffer
5097      * pool, we'll need what the driver one, and one more, so we can dequeu */
5098     own_min = obj->min_buffers + 1;
5099     own_min = MAX (own_min, GST_V4L2_MIN_BUFFERS (obj));
5100
5101     /* for the downstream pool, we keep what downstream wants, though ensure
5102      * at least a minimum if downstream didn't suggest anything (we are
5103      * expecting the base class to create a default one for the context) */
5104     min = MAX (min, GST_V4L2_MIN_BUFFERS (obj));
5105
5106     /* To import we need the other pool to hold at least own_min */
5107     if (obj->pool == pool)
5108       min += own_min;
5109   }
5110
5111   /* Request a bigger max, if one was suggested but it's too small */
5112   if (max != 0)
5113     max = MAX (min, max);
5114
5115   /* First step, configure our own pool */
5116   config = gst_buffer_pool_get_config (obj->pool);
5117
5118   if (obj->need_video_meta || has_video_meta) {
5119     GST_DEBUG_OBJECT (obj->dbg_obj, "activate Video Meta");
5120     gst_buffer_pool_config_add_option (config,
5121         GST_BUFFER_POOL_OPTION_VIDEO_META);
5122   }
5123
5124   gst_buffer_pool_config_set_allocator (config, allocator, &params);
5125   gst_buffer_pool_config_set_params (config, caps, size, own_min, 0);
5126
5127   GST_DEBUG_OBJECT (obj->dbg_obj, "setting own pool config to %"
5128       GST_PTR_FORMAT, config);
5129
5130   /* Our pool often need to adjust the value */
5131   if (!gst_buffer_pool_set_config (obj->pool, config)) {
5132     config = gst_buffer_pool_get_config (obj->pool);
5133
5134     GST_DEBUG_OBJECT (obj->dbg_obj, "own pool config changed to %"
5135         GST_PTR_FORMAT, config);
5136
5137     /* our pool will adjust the maximum buffer, which we are fine with */
5138     if (!gst_buffer_pool_set_config (obj->pool, config))
5139       goto config_failed;
5140   }
5141
5142   /* Now configure the other pool if different */
5143   if (obj->pool != pool)
5144     other_pool = pool;
5145
5146   if (other_pool) {
5147     config = gst_buffer_pool_get_config (other_pool);
5148     gst_buffer_pool_config_set_allocator (config, allocator, &params);
5149     gst_buffer_pool_config_set_params (config, caps, size, min, max);
5150
5151     GST_DEBUG_OBJECT (obj->dbg_obj, "setting other pool config to %"
5152         GST_PTR_FORMAT, config);
5153
5154     /* if downstream supports video metadata, add this to the pool config */
5155     if (has_video_meta) {
5156       GST_DEBUG_OBJECT (obj->dbg_obj, "activate Video Meta");
5157       gst_buffer_pool_config_add_option (config,
5158           GST_BUFFER_POOL_OPTION_VIDEO_META);
5159     }
5160
5161     if (!gst_buffer_pool_set_config (other_pool, config)) {
5162       config = gst_buffer_pool_get_config (other_pool);
5163
5164       if (!gst_buffer_pool_config_validate_params (config, caps, size, min,
5165               max)) {
5166         gst_structure_free (config);
5167         goto config_failed;
5168       }
5169
5170       if (!gst_buffer_pool_set_config (other_pool, config))
5171         goto config_failed;
5172     }
5173   }
5174
5175   if (pool) {
5176     /* For simplicity, simply read back the active configuration, so our base
5177      * class get the right information */
5178     config = gst_buffer_pool_get_config (pool);
5179     gst_buffer_pool_config_get_params (config, NULL, &size, &min, &max);
5180     gst_structure_free (config);
5181   }
5182
5183   if (update)
5184     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
5185   else
5186     gst_query_add_allocation_pool (query, pool, size, min, max);
5187
5188   if (allocator)
5189     gst_object_unref (allocator);
5190
5191   if (pool)
5192     gst_object_unref (pool);
5193
5194   return TRUE;
5195
5196 pool_failed:
5197   {
5198     /* setup_pool already send the error */
5199     goto cleanup;
5200   }
5201 config_failed:
5202   {
5203     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5204         (_("Failed to configure internal buffer pool.")), (NULL));
5205     goto cleanup;
5206   }
5207 no_size:
5208   {
5209     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5210         (_("Video device did not suggest any buffer size.")), (NULL));
5211     goto cleanup;
5212   }
5213 cleanup:
5214   {
5215     if (allocator)
5216       gst_object_unref (allocator);
5217
5218     if (pool)
5219       gst_object_unref (pool);
5220     return FALSE;
5221   }
5222 no_downstream_pool:
5223   {
5224     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5225         (_("No downstream pool to import from.")),
5226         ("When importing DMABUF or USERPTR, we need a pool to import from"));
5227     return FALSE;
5228   }
5229 }
5230
5231 gboolean
5232 gst_v4l2_object_propose_allocation (GstV4l2Object * obj, GstQuery * query)
5233 {
5234   GstBufferPool *pool = NULL;
5235   /* we need at least 2 buffers to operate */
5236   guint size, min, max;
5237   GstCaps *caps;
5238   gboolean need_pool;
5239
5240   /* Set defaults allocation parameters */
5241   size = obj->info.size;
5242   min = GST_V4L2_MIN_BUFFERS (obj);
5243   max = VIDEO_MAX_FRAME;
5244
5245   gst_query_parse_allocation (query, &caps, &need_pool);
5246
5247   if (caps == NULL)
5248     goto no_caps;
5249
5250   switch (obj->mode) {
5251     case GST_V4L2_IO_MMAP:
5252     case GST_V4L2_IO_DMABUF:
5253       if (need_pool && obj->pool) {
5254         if (!gst_buffer_pool_is_active (obj->pool))
5255           pool = gst_object_ref (obj->pool);
5256       }
5257       break;
5258     default:
5259       break;
5260   }
5261
5262   if (pool != NULL) {
5263     GstCaps *pcaps;
5264     GstStructure *config;
5265
5266     /* we had a pool, check caps */
5267     config = gst_buffer_pool_get_config (pool);
5268     gst_buffer_pool_config_get_params (config, &pcaps, NULL, NULL, NULL);
5269
5270     GST_DEBUG_OBJECT (obj->dbg_obj,
5271         "we had a pool with caps %" GST_PTR_FORMAT, pcaps);
5272     if (!gst_caps_is_equal (caps, pcaps)) {
5273       gst_structure_free (config);
5274       gst_object_unref (pool);
5275       goto different_caps;
5276     }
5277     gst_structure_free (config);
5278   }
5279   gst_v4l2_get_driver_min_buffers (obj);
5280
5281   min = MAX (obj->min_buffers, GST_V4L2_MIN_BUFFERS (obj));
5282
5283   gst_query_add_allocation_pool (query, pool, size, min, max);
5284
5285   /* we also support various metadata */
5286   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
5287
5288   if (pool)
5289     gst_object_unref (pool);
5290
5291   return TRUE;
5292
5293   /* ERRORS */
5294 no_caps:
5295   {
5296     GST_DEBUG_OBJECT (obj->dbg_obj, "no caps specified");
5297     return FALSE;
5298   }
5299 different_caps:
5300   {
5301     /* different caps, we can't use this pool */
5302     GST_DEBUG_OBJECT (obj->dbg_obj, "pool has different caps");
5303     return FALSE;
5304   }
5305 }
5306
5307 gboolean
5308 gst_v4l2_object_try_import (GstV4l2Object * obj, GstBuffer * buffer)
5309 {
5310   GstVideoMeta *vmeta;
5311   guint n_mem = gst_buffer_n_memory (buffer);
5312
5313   /* only import if requested */
5314   switch (obj->mode) {
5315     case GST_V4L2_IO_USERPTR:
5316     case GST_V4L2_IO_DMABUF_IMPORT:
5317       break;
5318     default:
5319       GST_DEBUG_OBJECT (obj->dbg_obj,
5320           "The io-mode does not enable importation");
5321       return FALSE;
5322   }
5323
5324   vmeta = gst_buffer_get_video_meta (buffer);
5325   if (!vmeta && obj->need_video_meta) {
5326     GST_DEBUG_OBJECT (obj->dbg_obj, "Downstream buffer uses standard "
5327         "stride/offset while the driver does not.");
5328     return FALSE;
5329   }
5330
5331   /* we need matching strides/offsets and size */
5332   if (vmeta) {
5333     guint plane_height[GST_VIDEO_MAX_PLANES] = { 0, };
5334
5335     gst_video_meta_get_plane_height (vmeta, plane_height);
5336
5337     if (!gst_v4l2_object_match_buffer_layout (obj, vmeta->n_planes,
5338             vmeta->offset, vmeta->stride, gst_buffer_get_size (buffer),
5339             plane_height[0]))
5340       return FALSE;
5341   }
5342
5343   /* we can always import single memory buffer, but otherwise we need the same
5344    * amount of memory object. */
5345   if (n_mem != 1 && n_mem != obj->n_v4l2_planes) {
5346     GST_DEBUG_OBJECT (obj->dbg_obj, "Can only import %i memory, "
5347         "buffers contains %u memory", obj->n_v4l2_planes, n_mem);
5348     return FALSE;
5349   }
5350
5351   /* For DMABuf importation we need DMABuf of course */
5352   if (obj->mode == GST_V4L2_IO_DMABUF_IMPORT) {
5353     guint i;
5354
5355     for (i = 0; i < n_mem; i++) {
5356       GstMemory *mem = gst_buffer_peek_memory (buffer, i);
5357
5358       if (!gst_is_dmabuf_memory (mem)) {
5359         GST_DEBUG_OBJECT (obj->dbg_obj, "Cannot import non-DMABuf memory.");
5360         return FALSE;
5361       }
5362     }
5363   }
5364
5365   /* for the remaining, only the kernel driver can tell */
5366   return TRUE;
5367 }