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