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