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