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