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