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