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