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