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