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