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