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