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