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