v4l2src: fix support for bayer format
[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     padded_height = (padded_height + tile_height - 1) / tile_height;
3307
3308     x_tiles = stride / GST_VIDEO_FORMAT_INFO_TILE_STRIDE (finfo, plane);
3309     y_tiles = padded_height / tile_height;
3310     info->stride[plane] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
3311   } else {
3312     info->stride[plane] = stride;
3313   }
3314 }
3315
3316 static void
3317 gst_v4l2_object_extrapolate_info (GstV4l2Object * v4l2object,
3318     GstVideoInfo * info, GstVideoAlignment * align, gint stride)
3319 {
3320   const GstVideoFormatInfo *finfo = info->finfo;
3321   gint i, estride, padded_height;
3322   gsize offs = 0;
3323
3324   g_return_if_fail (v4l2object->n_v4l2_planes == 1);
3325
3326   padded_height =
3327       GST_VIDEO_INFO_FIELD_HEIGHT (info) + align->padding_top +
3328       align->padding_bottom;
3329
3330   for (i = 0; i < finfo->n_planes; i++) {
3331     estride = gst_video_format_info_extrapolate_stride (finfo, i, stride);
3332
3333     gst_v4l2_object_set_stride (info, align, i, estride);
3334
3335     info->offset[i] = offs;
3336     offs += estride *
3337         GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, padded_height);
3338
3339     GST_DEBUG_OBJECT (v4l2object->dbg_obj,
3340         "Extrapolated for plane %d with base stride %d: "
3341         "stride %d, offset %" G_GSIZE_FORMAT, i, stride, info->stride[i],
3342         info->offset[i]);
3343   }
3344
3345   /* Update the image size according the amount of data we are going to
3346    * read/write. This workaround bugs in driver where the sizeimage provided
3347    * by TRY/S_FMT represent the buffer length (maximum size) rather then the expected
3348    * bytesused (buffer size). */
3349   if (offs < info->size)
3350     info->size = offs;
3351 }
3352
3353 static void
3354 gst_v4l2_object_save_format (GstV4l2Object * v4l2object,
3355     struct v4l2_fmtdesc *fmtdesc, struct v4l2_format *format,
3356     GstVideoInfo * info, GstVideoAlignment * align)
3357 {
3358   const GstVideoFormatInfo *finfo = info->finfo;
3359   gboolean standard_stride = TRUE;
3360   gint stride, pstride, padded_width, padded_height, i;
3361
3362   if (GST_VIDEO_INFO_FORMAT (info) == GST_VIDEO_FORMAT_ENCODED) {
3363     v4l2object->n_v4l2_planes = 1;
3364     info->size = format->fmt.pix.sizeimage;
3365     goto store_info;
3366   }
3367
3368   /* adjust right padding */
3369   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
3370     stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
3371   else
3372     stride = format->fmt.pix.bytesperline;
3373
3374   pstride = GST_VIDEO_FORMAT_INFO_PSTRIDE (finfo, 0);
3375   if (pstride) {
3376     padded_width = stride / pstride;
3377   } else {
3378     /* pstride can be 0 for complex formats */
3379     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3380         "format %s has a pstride of 0, cannot compute padded with",
3381         gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (info)));
3382     padded_width = stride;
3383   }
3384
3385   if (padded_width < format->fmt.pix.width)
3386     GST_WARNING_OBJECT (v4l2object->dbg_obj,
3387         "Driver bug detected, stride (%d) is too small for the width (%d)",
3388         padded_width, format->fmt.pix.width);
3389
3390   align->padding_right = padded_width - info->width - align->padding_left;
3391
3392   /* adjust bottom padding */
3393   padded_height = format->fmt.pix.height;
3394
3395   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3396     guint tile_height;
3397     tile_height = GST_VIDEO_FORMAT_INFO_TILE_HEIGHT (finfo, 0);
3398     padded_height = (padded_height + tile_height - 1) / tile_height;
3399   }
3400
3401   align->padding_bottom =
3402       padded_height - GST_VIDEO_INFO_FIELD_HEIGHT (info) - align->padding_top;
3403
3404   /* setup the strides and offset */
3405   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type)) {
3406     struct v4l2_pix_format_mplane *pix_mp = &format->fmt.pix_mp;
3407
3408     /* figure out the frame layout */
3409     v4l2object->n_v4l2_planes = MAX (1, pix_mp->num_planes);
3410     info->size = 0;
3411     for (i = 0; i < v4l2object->n_v4l2_planes; i++) {
3412       stride = pix_mp->plane_fmt[i].bytesperline;
3413
3414       if (info->stride[i] != stride)
3415         standard_stride = FALSE;
3416
3417       gst_v4l2_object_set_stride (info, align, i, stride);
3418       info->offset[i] = info->size;
3419       info->size += pix_mp->plane_fmt[i].sizeimage;
3420     }
3421
3422     /* Extrapolate stride if planar format are being set in 1 v4l2 plane */
3423     if (v4l2object->n_v4l2_planes < finfo->n_planes) {
3424       stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
3425       gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
3426     }
3427   } else {
3428     /* only one plane in non-MPLANE mode */
3429     v4l2object->n_v4l2_planes = 1;
3430     info->size = format->fmt.pix.sizeimage;
3431     stride = format->fmt.pix.bytesperline;
3432
3433     if (info->stride[0] != stride)
3434       standard_stride = FALSE;
3435
3436     gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
3437   }
3438
3439   /* adjust the offset to take into account left and top */
3440   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
3441     if ((align->padding_left + align->padding_top) > 0)
3442       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3443           "Left and top padding is not permitted for tiled formats");
3444   } else {
3445     for (i = 0; i < finfo->n_planes; i++) {
3446       gint vedge, hedge;
3447
3448       /* FIXME we assume plane as component as this is true for all supported
3449        * format we support. */
3450
3451       hedge = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, align->padding_left);
3452       vedge = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, align->padding_top);
3453
3454       info->offset[i] += (vedge * info->stride[i]) +
3455           (hedge * GST_VIDEO_INFO_COMP_PSTRIDE (info, i));
3456     }
3457   }
3458
3459 store_info:
3460   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got sizeimage %" G_GSIZE_FORMAT,
3461       info->size);
3462
3463   /* to avoid copies we need video meta if there is padding */
3464   v4l2object->need_video_meta =
3465       ((align->padding_top + align->padding_left + align->padding_right +
3466           align->padding_bottom) != 0);
3467
3468   /* ... or if stride is non "standard" */
3469   if (!standard_stride)
3470     v4l2object->need_video_meta = TRUE;
3471
3472   /* ... or also video meta if we use multiple, non-contiguous, planes */
3473   if (v4l2object->n_v4l2_planes > 1)
3474     v4l2object->need_video_meta = TRUE;
3475
3476   v4l2object->info = *info;
3477   v4l2object->align = *align;
3478   v4l2object->format = *format;
3479   v4l2object->fmtdesc = fmtdesc;
3480
3481   /* if we have a framerate pre-calculate duration */
3482   if (info->fps_n > 0 && info->fps_d > 0) {
3483     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, info->fps_d,
3484         info->fps_n);
3485     if (GST_VIDEO_INFO_INTERLACE_MODE (info) ==
3486         GST_VIDEO_INTERLACE_MODE_ALTERNATE)
3487       v4l2object->duration /= 2;
3488   } else {
3489     v4l2object->duration = GST_CLOCK_TIME_NONE;
3490   }
3491 }
3492
3493 static enum v4l2_field
3494 get_v4l2_field_for_info (GstVideoInfo * info)
3495 {
3496   if (!GST_VIDEO_INFO_IS_INTERLACED (info))
3497     return V4L2_FIELD_NONE;
3498
3499   if (GST_VIDEO_INFO_INTERLACE_MODE (info) ==
3500       GST_VIDEO_INTERLACE_MODE_ALTERNATE)
3501     return V4L2_FIELD_ALTERNATE;
3502
3503   switch (GST_VIDEO_INFO_FIELD_ORDER (info)) {
3504     case GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST:
3505       return V4L2_FIELD_INTERLACED_TB;
3506     case GST_VIDEO_FIELD_ORDER_BOTTOM_FIELD_FIRST:
3507       return V4L2_FIELD_INTERLACED_BT;
3508     case GST_VIDEO_FIELD_ORDER_UNKNOWN:
3509     default:
3510       return V4L2_FIELD_INTERLACED;
3511   }
3512 }
3513
3514 static gboolean
3515 gst_v4l2_video_colorimetry_matches (const GstVideoColorimetry * cinfo,
3516     GstCaps * caps)
3517 {
3518   GstVideoInfo info;
3519   static const GstVideoColorimetry ci_likely_jpeg = {
3520     GST_VIDEO_COLOR_RANGE_0_255, GST_VIDEO_COLOR_MATRIX_BT601,
3521     GST_VIDEO_TRANSFER_UNKNOWN, GST_VIDEO_COLOR_PRIMARIES_UNKNOWN
3522   };
3523   static const GstVideoColorimetry ci_jpeg = {
3524     GST_VIDEO_COLOR_RANGE_0_255, GST_VIDEO_COLOR_MATRIX_BT601,
3525     GST_VIDEO_TRANSFER_SRGB, GST_VIDEO_COLOR_PRIMARIES_BT709
3526   };
3527
3528   if (!gst_video_info_from_caps (&info, caps))
3529     return FALSE;
3530
3531   /* if colorimetry in caps is unknown, use the default one */
3532   if (info.colorimetry.primaries == GST_VIDEO_COLOR_PRIMARIES_UNKNOWN)
3533     info.colorimetry.primaries = cinfo->primaries;
3534   if (info.colorimetry.range == GST_VIDEO_COLOR_RANGE_UNKNOWN)
3535     info.colorimetry.range = cinfo->range;
3536   if (info.colorimetry.matrix == GST_VIDEO_COLOR_MATRIX_UNKNOWN)
3537     info.colorimetry.matrix = cinfo->matrix;
3538   if (info.colorimetry.transfer == GST_VIDEO_TRANSFER_UNKNOWN)
3539     info.colorimetry.transfer = cinfo->transfer;
3540
3541   if (gst_video_colorimetry_is_equal (&info.colorimetry, cinfo))
3542     return TRUE;
3543
3544   /* Allow 1:4:0:0 (produced by jpegdec) if the device expects 1:4:7:1 */
3545   if (gst_video_colorimetry_is_equal (&info.colorimetry, &ci_likely_jpeg)
3546       && gst_video_colorimetry_is_equal (cinfo, &ci_jpeg))
3547     return TRUE;
3548
3549   /* bypass check the below transfer types, because those types are cast to
3550    * V4L2_XFER_FUNC_NONE type when try format or set format and V4L2_XFER_FUNC_NONE
3551    * type is cast to GST_VIDEO_TRANSFER_GAMMA10 type in gst_v4l2_object_get_colorspace */
3552   if ((info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA18) ||
3553       (info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA20) ||
3554       (info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA22) ||
3555       (info.colorimetry.transfer == GST_VIDEO_TRANSFER_GAMMA28)) {
3556     info.colorimetry.transfer = GST_VIDEO_TRANSFER_GAMMA10;
3557     if (gst_video_colorimetry_is_equal (&info.colorimetry, cinfo))
3558       return TRUE;
3559   }
3560
3561   return FALSE;
3562 }
3563
3564 static const gchar *
3565 field_to_str (enum v4l2_field f)
3566 {
3567   switch (f) {
3568     case V4L2_FIELD_ANY:
3569       return "any";
3570     case V4L2_FIELD_NONE:
3571       return "none";
3572     case V4L2_FIELD_TOP:
3573       return "top";
3574     case V4L2_FIELD_BOTTOM:
3575       return "bottom";
3576     case V4L2_FIELD_INTERLACED:
3577       return "interlaced";
3578     case V4L2_FIELD_SEQ_TB:
3579       return "seq-tb";
3580     case V4L2_FIELD_SEQ_BT:
3581       return "seq-bt";
3582     case V4L2_FIELD_ALTERNATE:
3583       return "alternate";
3584     case V4L2_FIELD_INTERLACED_TB:
3585       return "interlaced-tb";
3586     case V4L2_FIELD_INTERLACED_BT:
3587       return "interlaced-bt";
3588   }
3589
3590   return "unknown";
3591 }
3592
3593 static gboolean
3594 gst_v4l2_object_set_format_full (GstV4l2Object * v4l2object, GstCaps * caps,
3595     gboolean try_only, GstV4l2Error * error)
3596 {
3597   gint fd = v4l2object->video_fd;
3598   struct v4l2_format format;
3599   struct v4l2_streamparm streamparm;
3600   enum v4l2_field field;
3601   guint32 pixelformat;
3602   struct v4l2_fmtdesc *fmtdesc;
3603   GstVideoInfo info;
3604   GstVideoAlignment align;
3605   gint width, height, fps_n, fps_d;
3606   gint n_v4l_planes;
3607   gint i = 0;
3608   gboolean is_mplane;
3609   enum v4l2_colorspace colorspace = 0;
3610   enum v4l2_quantization range = 0;
3611   enum v4l2_ycbcr_encoding matrix = 0;
3612   enum v4l2_xfer_func transfer = 0;
3613   GstStructure *s;
3614   gboolean disable_interlacing = FALSE;
3615   gboolean disable_colorimetry = FALSE;
3616
3617   g_return_val_if_fail (!v4l2object->skip_try_fmt_probes ||
3618       gst_caps_is_writable (caps), FALSE);
3619
3620   GST_V4L2_CHECK_OPEN (v4l2object);
3621   if (!try_only)
3622     GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
3623
3624   is_mplane = V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type);
3625
3626   gst_video_info_init (&info);
3627   gst_video_alignment_reset (&align);
3628   v4l2object->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
3629
3630   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
3631     goto invalid_caps;
3632
3633   pixelformat = fmtdesc->pixelformat;
3634   width = GST_VIDEO_INFO_WIDTH (&info);
3635   height = GST_VIDEO_INFO_FIELD_HEIGHT (&info);
3636   /* if caps has no width and height info, use default value */
3637   if (V4L2_TYPE_IS_OUTPUT (v4l2object->type) && width == 0 && height == 0) {
3638     width = GST_V4L2_DEFAULT_WIDTH;
3639     height = GST_V4L2_DEFAULT_HEIGHT;
3640   }
3641   fps_n = GST_VIDEO_INFO_FPS_N (&info);
3642   fps_d = GST_VIDEO_INFO_FPS_D (&info);
3643
3644   /* if encoded format (GST_VIDEO_INFO_N_PLANES return 0)
3645    * or if contiguous is preferred */
3646   n_v4l_planes = GST_VIDEO_INFO_N_PLANES (&info);
3647   if (!n_v4l_planes || !v4l2object->prefered_non_contiguous)
3648     n_v4l_planes = 1;
3649
3650   field = get_v4l2_field_for_info (&info);
3651   if (field != V4L2_FIELD_NONE)
3652     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "interlaced video");
3653   else
3654     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "progressive video");
3655
3656   /* We first pick the main colorspace from the primaries */
3657   switch (info.colorimetry.primaries) {
3658     case GST_VIDEO_COLOR_PRIMARIES_BT709:
3659       /* There is two colorspaces using these primaries, use the range to
3660        * differentiate */
3661       if (info.colorimetry.range == GST_VIDEO_COLOR_RANGE_16_235)
3662         colorspace = V4L2_COLORSPACE_REC709;
3663       else
3664         colorspace = V4L2_COLORSPACE_SRGB;
3665       break;
3666     case GST_VIDEO_COLOR_PRIMARIES_BT2020:
3667       colorspace = V4L2_COLORSPACE_BT2020;
3668       break;
3669     case GST_VIDEO_COLOR_PRIMARIES_BT470M:
3670       colorspace = V4L2_COLORSPACE_470_SYSTEM_M;
3671       break;
3672     case GST_VIDEO_COLOR_PRIMARIES_BT470BG:
3673       colorspace = V4L2_COLORSPACE_470_SYSTEM_BG;
3674       break;
3675     case GST_VIDEO_COLOR_PRIMARIES_SMPTE170M:
3676       colorspace = V4L2_COLORSPACE_SMPTE170M;
3677       break;
3678     case GST_VIDEO_COLOR_PRIMARIES_SMPTE240M:
3679       colorspace = V4L2_COLORSPACE_SMPTE240M;
3680       break;
3681
3682     case GST_VIDEO_COLOR_PRIMARIES_FILM:
3683     case GST_VIDEO_COLOR_PRIMARIES_UNKNOWN:
3684       /* We don't know, we will guess */
3685       break;
3686
3687     default:
3688       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3689           "Unknown colorimetry primaries %d", info.colorimetry.primaries);
3690       break;
3691   }
3692
3693   switch (info.colorimetry.range) {
3694     case GST_VIDEO_COLOR_RANGE_0_255:
3695       range = V4L2_QUANTIZATION_FULL_RANGE;
3696       break;
3697     case GST_VIDEO_COLOR_RANGE_16_235:
3698       range = V4L2_QUANTIZATION_LIM_RANGE;
3699       break;
3700     case GST_VIDEO_COLOR_RANGE_UNKNOWN:
3701       /* We let the driver pick a default one */
3702       break;
3703     default:
3704       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3705           "Unknown colorimetry range %d", info.colorimetry.range);
3706       break;
3707   }
3708
3709   switch (info.colorimetry.matrix) {
3710     case GST_VIDEO_COLOR_MATRIX_RGB:
3711       /* Unspecified, leave to default */
3712       break;
3713       /* FCC is about the same as BT601 with less digit */
3714     case GST_VIDEO_COLOR_MATRIX_FCC:
3715     case GST_VIDEO_COLOR_MATRIX_BT601:
3716       matrix = V4L2_YCBCR_ENC_601;
3717       break;
3718     case GST_VIDEO_COLOR_MATRIX_BT709:
3719       matrix = V4L2_YCBCR_ENC_709;
3720       break;
3721     case GST_VIDEO_COLOR_MATRIX_SMPTE240M:
3722       matrix = V4L2_YCBCR_ENC_SMPTE240M;
3723       break;
3724     case GST_VIDEO_COLOR_MATRIX_BT2020:
3725       matrix = V4L2_YCBCR_ENC_BT2020;
3726       break;
3727     case GST_VIDEO_COLOR_MATRIX_UNKNOWN:
3728       /* We let the driver pick a default one */
3729       break;
3730     default:
3731       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3732           "Unknown colorimetry matrix %d", info.colorimetry.matrix);
3733       break;
3734   }
3735
3736   switch (info.colorimetry.transfer) {
3737     case GST_VIDEO_TRANSFER_GAMMA18:
3738     case GST_VIDEO_TRANSFER_GAMMA20:
3739     case GST_VIDEO_TRANSFER_GAMMA22:
3740     case GST_VIDEO_TRANSFER_GAMMA28:
3741       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3742           "GAMMA 18, 20, 22, 28 transfer functions not supported");
3743       /* fallthrough */
3744     case GST_VIDEO_TRANSFER_GAMMA10:
3745       transfer = V4L2_XFER_FUNC_NONE;
3746       break;
3747     case GST_VIDEO_TRANSFER_SMPTE2084:
3748       transfer = V4L2_XFER_FUNC_SMPTE2084;
3749       break;
3750     case GST_VIDEO_TRANSFER_BT601:
3751     case GST_VIDEO_TRANSFER_BT2020_12:
3752     case GST_VIDEO_TRANSFER_BT2020_10:
3753     case GST_VIDEO_TRANSFER_BT709:
3754       v4l2object->transfer = info.colorimetry.transfer;
3755       transfer = V4L2_XFER_FUNC_709;
3756       break;
3757     case GST_VIDEO_TRANSFER_SMPTE240M:
3758       transfer = V4L2_XFER_FUNC_SMPTE240M;
3759       break;
3760     case GST_VIDEO_TRANSFER_SRGB:
3761       transfer = V4L2_XFER_FUNC_SRGB;
3762       break;
3763     case GST_VIDEO_TRANSFER_LOG100:
3764     case GST_VIDEO_TRANSFER_LOG316:
3765       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3766           "LOG 100, 316 transfer functions not supported");
3767       /* FIXME No known sensible default, maybe AdobeRGB ? */
3768       break;
3769     case GST_VIDEO_TRANSFER_UNKNOWN:
3770       /* We let the driver pick a default one */
3771       break;
3772     default:
3773       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3774           "Unknown colorimetry transfer %d", info.colorimetry.transfer);
3775       break;
3776   }
3777
3778   if (colorspace == 0) {
3779     /* Try to guess colorspace according to pixelformat and size */
3780     if (GST_VIDEO_INFO_IS_YUV (&info)) {
3781       if (range == V4L2_QUANTIZATION_FULL_RANGE
3782           && matrix == V4L2_YCBCR_ENC_601 && transfer == 0) {
3783         /* Full range BT.601 YCbCr encoding with unknown primaries and transfer
3784          * function most likely is JPEG */
3785         colorspace = V4L2_COLORSPACE_JPEG;
3786         transfer = V4L2_XFER_FUNC_SRGB;
3787       } else {
3788         /* SD streams likely use SMPTE170M and HD streams REC709 */
3789         if (width <= 720 && GST_VIDEO_INFO_HEIGHT (&info) <= 576)
3790           colorspace = V4L2_COLORSPACE_SMPTE170M;
3791         else
3792           colorspace = V4L2_COLORSPACE_REC709;
3793       }
3794     } else if (GST_VIDEO_INFO_IS_RGB (&info)) {
3795       colorspace = V4L2_COLORSPACE_SRGB;
3796       transfer = V4L2_XFER_FUNC_NONE;
3797     }
3798   }
3799
3800   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired format %dx%d, format "
3801       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
3802       GST_FOURCC_ARGS (pixelformat), GST_VIDEO_INFO_PLANE_STRIDE (&info, 0));
3803
3804   memset (&format, 0x00, sizeof (struct v4l2_format));
3805   format.type = v4l2object->type;
3806
3807   if (is_mplane) {
3808     format.type = v4l2object->type;
3809     format.fmt.pix_mp.pixelformat = pixelformat;
3810     format.fmt.pix_mp.width = width;
3811     format.fmt.pix_mp.height = height;
3812     format.fmt.pix_mp.field = field;
3813     format.fmt.pix_mp.num_planes = n_v4l_planes;
3814
3815     /* try to ask our preferred stride but it's not a failure if not
3816      * accepted */
3817     for (i = 0; i < n_v4l_planes; i++) {
3818       gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, i);
3819
3820       if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
3821         stride = GST_VIDEO_TILE_X_TILES (stride) *
3822             GST_VIDEO_FORMAT_INFO_TILE_STRIDE (info.finfo, i);
3823
3824       format.fmt.pix_mp.plane_fmt[i].bytesperline = stride;
3825     }
3826
3827     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
3828       format.fmt.pix_mp.plane_fmt[0].sizeimage = ENCODED_BUFFER_SIZE;
3829   } else {
3830     gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
3831
3832     format.type = v4l2object->type;
3833
3834     format.fmt.pix.width = width;
3835     format.fmt.pix.height = height;
3836     format.fmt.pix.pixelformat = pixelformat;
3837     format.fmt.pix.field = field;
3838
3839     if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
3840       stride = GST_VIDEO_TILE_X_TILES (stride) *
3841           GST_VIDEO_FORMAT_INFO_TILE_STRIDE (info.finfo, i);
3842
3843     /* try to ask our preferred stride */
3844     format.fmt.pix.bytesperline = stride;
3845
3846     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
3847       format.fmt.pix.sizeimage = ENCODED_BUFFER_SIZE;
3848   }
3849
3850   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired format is %dx%d, format "
3851       "%" GST_FOURCC_FORMAT ", nb planes %d", format.fmt.pix.width,
3852       format.fmt.pix_mp.height,
3853       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
3854       is_mplane ? format.fmt.pix_mp.num_planes : 1);
3855
3856 #ifndef GST_DISABLE_GST_DEBUG
3857   if (is_mplane) {
3858     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
3859       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d",
3860           format.fmt.pix_mp.plane_fmt[i].bytesperline);
3861   } else {
3862     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d",
3863         format.fmt.pix.bytesperline);
3864   }
3865 #endif
3866
3867   if (is_mplane) {
3868     format.fmt.pix_mp.colorspace = colorspace;
3869     format.fmt.pix_mp.quantization = range;
3870     format.fmt.pix_mp.ycbcr_enc = matrix;
3871     format.fmt.pix_mp.xfer_func = transfer;
3872   } else {
3873     format.fmt.pix.priv = V4L2_PIX_FMT_PRIV_MAGIC;
3874     format.fmt.pix.colorspace = colorspace;
3875     format.fmt.pix.quantization = range;
3876     format.fmt.pix.ycbcr_enc = matrix;
3877     format.fmt.pix.xfer_func = transfer;
3878   }
3879
3880   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired colorspace is %d:%d:%d:%d",
3881       colorspace, range, matrix, transfer);
3882
3883   if (try_only) {
3884     if (v4l2object->ioctl (fd, VIDIOC_TRY_FMT, &format) < 0)
3885       goto try_fmt_failed;
3886   } else {
3887     if (v4l2object->ioctl (fd, VIDIOC_S_FMT, &format) < 0)
3888       goto set_fmt_failed;
3889   }
3890
3891   if (is_mplane) {
3892     colorspace = format.fmt.pix_mp.colorspace;
3893     range = format.fmt.pix_mp.quantization;
3894     matrix = format.fmt.pix_mp.ycbcr_enc;
3895     transfer = format.fmt.pix_mp.xfer_func;
3896   } else {
3897     colorspace = format.fmt.pix.colorspace;
3898     range = format.fmt.pix.quantization;
3899     matrix = format.fmt.pix.ycbcr_enc;
3900     transfer = format.fmt.pix.xfer_func;
3901   }
3902
3903   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got format of %dx%d, format "
3904       "%" GST_FOURCC_FORMAT ", nb planes %d, colorspace %d:%d:%d:%d field: %s",
3905       format.fmt.pix.width, format.fmt.pix_mp.height,
3906       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
3907       is_mplane ? format.fmt.pix_mp.num_planes : 1,
3908       colorspace, range, matrix, transfer, field_to_str (format.fmt.pix.field));
3909
3910 #ifndef GST_DISABLE_GST_DEBUG
3911   if (is_mplane) {
3912     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
3913       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d, sizeimage %d",
3914           format.fmt.pix_mp.plane_fmt[i].bytesperline,
3915           format.fmt.pix_mp.plane_fmt[i].sizeimage);
3916   } else {
3917     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "  stride %d, sizeimage %d",
3918         format.fmt.pix.bytesperline, format.fmt.pix.sizeimage);
3919   }
3920 #endif
3921
3922   if (format.fmt.pix.pixelformat != pixelformat)
3923     goto invalid_pixelformat;
3924
3925   /* Only negotiate size with raw data.
3926    * For some codecs the dimensions are *not* in the bitstream, IIRC VC1
3927    * in ASF mode for example, there is also not reason for a driver to
3928    * change the size. */
3929   if (info.finfo->format != GST_VIDEO_FORMAT_ENCODED) {
3930     /* We can crop larger images */
3931     if (format.fmt.pix.width < width || format.fmt.pix.height < height)
3932       goto invalid_dimensions;
3933
3934     /* Note, this will be adjusted if upstream has non-centered cropping. */
3935     align.padding_top = 0;
3936     align.padding_bottom = format.fmt.pix.height - height;
3937     align.padding_left = 0;
3938     align.padding_right = format.fmt.pix.width - width;
3939   }
3940
3941   if (is_mplane && format.fmt.pix_mp.num_planes != n_v4l_planes)
3942     goto invalid_planes;
3943
3944   /* used to check colorimetry and interlace mode fields presence */
3945   s = gst_caps_get_structure (caps, 0);
3946
3947   if (gst_v4l2_object_get_interlace_mode (format.fmt.pix.field,
3948           &info.interlace_mode)) {
3949     if (gst_structure_has_field (s, "interlace-mode")) {
3950       if (format.fmt.pix.field != field)
3951         goto invalid_field;
3952     }
3953   } else {
3954     /* The driver (or libv4l2) is miss-behaving, just ignore interlace-mode from
3955      * the TRY_FMT */
3956     disable_interlacing = TRUE;
3957     if (gst_structure_has_field (s, "interlace-mode"))
3958       gst_structure_remove_field (s, "interlace-mode");
3959   }
3960
3961   if (gst_v4l2_object_get_colorspace (v4l2object, &format, &info.colorimetry)) {
3962     if (gst_structure_has_field (s, "colorimetry")) {
3963       if (!gst_v4l2_video_colorimetry_matches (&info.colorimetry, caps))
3964         goto invalid_colorimetry;
3965     }
3966   } else {
3967     /* The driver (or libv4l2) is miss-behaving, just ignore colorimetry from
3968      * the TRY_FMT */
3969     disable_colorimetry = TRUE;
3970     if (gst_structure_has_field (s, "colorimetry"))
3971       gst_structure_remove_field (s, "colorimetry");
3972   }
3973
3974   /* In case we have skipped the try_fmt probes, we'll need to set the
3975    * interlace-mode and colorimetry back into the caps. */
3976   if (v4l2object->skip_try_fmt_probes) {
3977     if (!disable_interlacing && !gst_structure_has_field (s, "interlace-mode")) {
3978       gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
3979           gst_video_interlace_mode_to_string (info.interlace_mode), NULL);
3980     }
3981     if (!disable_colorimetry && !gst_structure_has_field (s, "colorimetry")) {
3982       gchar *str = gst_video_colorimetry_to_string (&info.colorimetry);
3983       gst_structure_set (s, "colorimetry", G_TYPE_STRING, str, NULL);
3984       g_free (str);
3985     }
3986   }
3987
3988   if (try_only)                 /* good enough for trying only */
3989     return TRUE;
3990
3991   if (GST_VIDEO_INFO_HAS_ALPHA (&info)) {
3992     struct v4l2_control ctl = { 0, };
3993     ctl.id = V4L2_CID_ALPHA_COMPONENT;
3994     ctl.value = 0xff;
3995
3996     if (v4l2object->ioctl (fd, VIDIOC_S_CTRL, &ctl) < 0)
3997       GST_WARNING_OBJECT (v4l2object->dbg_obj,
3998           "Failed to set alpha component value");
3999   }
4000
4001   /* Is there a reason we require the caller to always specify a framerate? */
4002   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Desired framerate: %u/%u", fps_n,
4003       fps_d);
4004
4005   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
4006   streamparm.type = v4l2object->type;
4007
4008   if (v4l2object->ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
4009     goto get_parm_failed;
4010
4011   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
4012       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
4013     GST_VIDEO_INFO_FPS_N (&info) =
4014         streamparm.parm.capture.timeperframe.denominator;
4015     GST_VIDEO_INFO_FPS_D (&info) =
4016         streamparm.parm.capture.timeperframe.numerator;
4017
4018     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got capture framerate: %u/%u",
4019         streamparm.parm.capture.timeperframe.denominator,
4020         streamparm.parm.capture.timeperframe.numerator);
4021
4022     /* We used to skip frame rate setup if the camera was already setup
4023      * with the requested frame rate. This breaks some cameras though,
4024      * causing them to not output data (several models of Thinkpad cameras
4025      * have this problem at least).
4026      * So, don't skip. */
4027     GST_LOG_OBJECT (v4l2object->dbg_obj, "Setting capture framerate to %u/%u",
4028         fps_n, fps_d);
4029     /* We want to change the frame rate, so check whether we can. Some cheap USB
4030      * cameras don't have the capability */
4031     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
4032       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4033           "Not setting capture framerate (not supported)");
4034       goto done;
4035     }
4036
4037     /* Note: V4L2 wants the frame interval, we have the frame rate */
4038     streamparm.parm.capture.timeperframe.numerator = fps_d;
4039     streamparm.parm.capture.timeperframe.denominator = fps_n;
4040
4041     /* some cheap USB cam's won't accept any change */
4042     if (v4l2object->ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
4043       goto set_parm_failed;
4044
4045     if (streamparm.parm.capture.timeperframe.numerator > 0 &&
4046         streamparm.parm.capture.timeperframe.denominator > 0) {
4047       /* get new values */
4048       fps_d = streamparm.parm.capture.timeperframe.numerator;
4049       fps_n = streamparm.parm.capture.timeperframe.denominator;
4050
4051       GST_INFO_OBJECT (v4l2object->dbg_obj, "Set capture framerate to %u/%u",
4052           fps_n, fps_d);
4053     } else {
4054       /* fix v4l2 capture driver to provide framerate values */
4055       GST_WARNING_OBJECT (v4l2object->dbg_obj,
4056           "Reuse caps framerate %u/%u - fix v4l2 capture driver", fps_n, fps_d);
4057     }
4058
4059     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
4060     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
4061   } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT
4062       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
4063     GST_VIDEO_INFO_FPS_N (&info) =
4064         streamparm.parm.output.timeperframe.denominator;
4065     GST_VIDEO_INFO_FPS_D (&info) =
4066         streamparm.parm.output.timeperframe.numerator;
4067
4068     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Got output framerate: %u/%u",
4069         streamparm.parm.output.timeperframe.denominator,
4070         streamparm.parm.output.timeperframe.numerator);
4071
4072     GST_LOG_OBJECT (v4l2object->dbg_obj, "Setting output framerate to %u/%u",
4073         fps_n, fps_d);
4074     if ((streamparm.parm.output.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
4075       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4076           "Not setting output framerate (not supported)");
4077       goto done;
4078     }
4079
4080     /* Note: V4L2 wants the frame interval, we have the frame rate */
4081     streamparm.parm.output.timeperframe.numerator = fps_d;
4082     streamparm.parm.output.timeperframe.denominator = fps_n;
4083
4084     if (v4l2object->ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
4085       goto set_parm_failed;
4086
4087     if (streamparm.parm.output.timeperframe.numerator > 0 &&
4088         streamparm.parm.output.timeperframe.denominator > 0) {
4089       /* get new values */
4090       fps_d = streamparm.parm.output.timeperframe.numerator;
4091       fps_n = streamparm.parm.output.timeperframe.denominator;
4092
4093       GST_INFO_OBJECT (v4l2object->dbg_obj, "Set output framerate to %u/%u",
4094           fps_n, fps_d);
4095     } else {
4096       /* fix v4l2 output driver to provide framerate values */
4097       GST_WARNING_OBJECT (v4l2object->dbg_obj,
4098           "Reuse caps framerate %u/%u - fix v4l2 output driver", fps_n, fps_d);
4099     }
4100
4101     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
4102     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
4103   }
4104
4105 done:
4106   /* add boolean return, so we can fail on drivers bugs */
4107   gst_v4l2_object_save_format (v4l2object, fmtdesc, &format, &info, &align);
4108
4109   /* reset composition region to match the S_FMT size */
4110   gst_v4l2_object_reset_compose_region (v4l2object);
4111
4112   /* now configure the pool */
4113   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
4114     goto pool_failed;
4115
4116   return TRUE;
4117
4118   /* ERRORS */
4119 invalid_caps:
4120   {
4121     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "can't parse caps %" GST_PTR_FORMAT,
4122         caps);
4123
4124     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4125         (_("Invalid caps")), ("Can't parse caps %" GST_PTR_FORMAT, caps));
4126     return FALSE;
4127   }
4128 try_fmt_failed:
4129   {
4130     if (errno == EINVAL) {
4131       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4132           (_("Device '%s' has no supported format"), v4l2object->videodev),
4133           ("Call to TRY_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4134               GST_FOURCC_ARGS (pixelformat), width, height,
4135               g_strerror (errno)));
4136     } else {
4137       GST_V4L2_ERROR (error, RESOURCE, FAILED,
4138           (_("Device '%s' failed during initialization"),
4139               v4l2object->videodev),
4140           ("Call to TRY_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4141               GST_FOURCC_ARGS (pixelformat), width, height,
4142               g_strerror (errno)));
4143     }
4144     return FALSE;
4145   }
4146 set_fmt_failed:
4147   {
4148     if (errno == EBUSY) {
4149       GST_V4L2_ERROR (error, RESOURCE, BUSY,
4150           (_("Device '%s' is busy"), v4l2object->videodev),
4151           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4152               GST_FOURCC_ARGS (pixelformat), width, height,
4153               g_strerror (errno)));
4154     } else if (errno == EINVAL) {
4155       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4156           (_("Device '%s' has no supported format"), v4l2object->videodev),
4157           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4158               GST_FOURCC_ARGS (pixelformat), width, height,
4159               g_strerror (errno)));
4160     } else {
4161       GST_V4L2_ERROR (error, RESOURCE, FAILED,
4162           (_("Device '%s' failed during initialization"),
4163               v4l2object->videodev),
4164           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
4165               GST_FOURCC_ARGS (pixelformat), width, height,
4166               g_strerror (errno)));
4167     }
4168     return FALSE;
4169   }
4170 invalid_dimensions:
4171   {
4172     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4173         (_("Device '%s' cannot capture at %dx%d"),
4174             v4l2object->videodev, width, height),
4175         ("Tried to capture at %dx%d, but device returned size %dx%d",
4176             width, height, format.fmt.pix.width, format.fmt.pix.height));
4177     return FALSE;
4178   }
4179 invalid_pixelformat:
4180   {
4181     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4182         (_("Device '%s' cannot capture in the specified format"),
4183             v4l2object->videodev),
4184         ("Tried to capture in %" GST_FOURCC_FORMAT
4185             ", but device returned format" " %" GST_FOURCC_FORMAT,
4186             GST_FOURCC_ARGS (pixelformat),
4187             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
4188     return FALSE;
4189   }
4190 invalid_planes:
4191   {
4192     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4193         (_("Device '%s' does support non-contiguous planes"),
4194             v4l2object->videodev),
4195         ("Device wants %d planes", format.fmt.pix_mp.num_planes));
4196     return FALSE;
4197   }
4198 invalid_field:
4199   {
4200     enum v4l2_field wanted_field;
4201
4202     if (is_mplane)
4203       wanted_field = format.fmt.pix_mp.field;
4204     else
4205       wanted_field = format.fmt.pix.field;
4206
4207     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4208         (_("Device '%s' does not support %s interlacing"),
4209             v4l2object->videodev,
4210             field == V4L2_FIELD_NONE ? "progressive" : "interleaved"),
4211         ("Device wants %s interlacing",
4212             wanted_field == V4L2_FIELD_NONE ? "progressive" : "interleaved"));
4213     return FALSE;
4214   }
4215 invalid_colorimetry:
4216   {
4217     gchar *wanted_colorimetry;
4218
4219     wanted_colorimetry = gst_video_colorimetry_to_string (&info.colorimetry);
4220
4221     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4222         (_("Device '%s' does not support %s colorimetry"),
4223             v4l2object->videodev, gst_structure_get_string (s, "colorimetry")),
4224         ("Device wants %s colorimetry", wanted_colorimetry));
4225
4226     g_free (wanted_colorimetry);
4227     return FALSE;
4228   }
4229 get_parm_failed:
4230   {
4231     /* it's possible that this call is not supported */
4232     if (errno != EINVAL && errno != ENOTTY) {
4233       GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4234           (_("Could not get parameters on device '%s'"),
4235               v4l2object->videodev), GST_ERROR_SYSTEM);
4236     }
4237     goto done;
4238   }
4239 set_parm_failed:
4240   {
4241     GST_V4L2_ERROR (error, RESOURCE, SETTINGS,
4242         (_("Video device did not accept new frame rate setting.")),
4243         GST_ERROR_SYSTEM);
4244     goto done;
4245   }
4246 pool_failed:
4247   {
4248     /* setup_pool already send the error */
4249     return FALSE;
4250   }
4251 }
4252
4253 gboolean
4254 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps,
4255     GstV4l2Error * error)
4256 {
4257   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Setting format to %" GST_PTR_FORMAT,
4258       caps);
4259   return gst_v4l2_object_set_format_full (v4l2object, caps, FALSE, error);
4260 }
4261
4262 gboolean
4263 gst_v4l2_object_try_format (GstV4l2Object * v4l2object, GstCaps * caps,
4264     GstV4l2Error * error)
4265 {
4266   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Trying format %" GST_PTR_FORMAT,
4267       caps);
4268   return gst_v4l2_object_set_format_full (v4l2object, caps, TRUE, error);
4269 }
4270
4271 /**
4272  * gst_v4l2_object_acquire_format:
4273  * @v4l2object: the object
4274  * @info: a GstVideoInfo to be filled
4275  *
4276  * Acquire the driver chosen format. This is useful in decoder or encoder elements where
4277  * the output format is chosen by the HW.
4278  *
4279  * Returns: %TRUE on success, %FALSE on failure.
4280  */
4281 gboolean
4282 gst_v4l2_object_acquire_format (GstV4l2Object * v4l2object, GstVideoInfo * info)
4283 {
4284   struct v4l2_fmtdesc *fmtdesc;
4285   struct v4l2_format fmt;
4286   struct v4l2_crop crop;
4287   struct v4l2_selection sel;
4288   struct v4l2_rect *r = NULL;
4289   GstVideoFormat format;
4290   guint width, height;
4291   GstVideoAlignment align;
4292   GstVideoInterlaceMode interlace_mode;
4293
4294   gst_video_info_init (info);
4295   gst_video_alignment_reset (&align);
4296   v4l2object->transfer = GST_VIDEO_TRANSFER_UNKNOWN;
4297
4298   memset (&fmt, 0x00, sizeof (struct v4l2_format));
4299   fmt.type = v4l2object->type;
4300   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_FMT, &fmt) < 0)
4301     goto get_fmt_failed;
4302
4303   fmtdesc = gst_v4l2_object_get_format_from_fourcc (v4l2object,
4304       fmt.fmt.pix.pixelformat);
4305   if (fmtdesc == NULL)
4306     goto unsupported_format;
4307
4308   /* No need to care about mplane, the four first params are the same */
4309   format = gst_v4l2_object_v4l2fourcc_to_video_format (fmt.fmt.pix.pixelformat);
4310
4311   /* fails if we do no translate the fmt.pix.pixelformat to GstVideoFormat */
4312   if (format == GST_VIDEO_FORMAT_UNKNOWN)
4313     goto unsupported_format;
4314
4315   if (fmt.fmt.pix.width == 0 || fmt.fmt.pix.height == 0)
4316     goto invalid_dimensions;
4317
4318   width = fmt.fmt.pix.width;
4319   height = fmt.fmt.pix.height;
4320
4321   /* Use the default compose rectangle */
4322   memset (&sel, 0, sizeof (struct v4l2_selection));
4323   sel.type = v4l2object->type;
4324   sel.target = V4L2_SEL_TGT_COMPOSE_DEFAULT;
4325   if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_SELECTION, &sel) >= 0) {
4326     r = &sel.r;
4327   } else {
4328     /* For ancient kernels, fall back to G_CROP */
4329     memset (&crop, 0, sizeof (struct v4l2_crop));
4330     crop.type = v4l2object->type;
4331     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_G_CROP, &crop) >= 0)
4332       r = &crop.c;
4333   }
4334   if (r) {
4335     align.padding_left = r->left;
4336     align.padding_top = r->top;
4337     align.padding_right = width - r->width - r->left;
4338     align.padding_bottom = height - r->height - r->top;
4339     width = r->width;
4340     height = r->height;
4341   }
4342
4343   switch (fmt.fmt.pix.field) {
4344     case V4L2_FIELD_ANY:
4345     case V4L2_FIELD_NONE:
4346       interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
4347       break;
4348     case V4L2_FIELD_INTERLACED:
4349     case V4L2_FIELD_INTERLACED_TB:
4350     case V4L2_FIELD_INTERLACED_BT:
4351       interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
4352       break;
4353     case V4L2_FIELD_ALTERNATE:
4354       interlace_mode = GST_VIDEO_INTERLACE_MODE_ALTERNATE;
4355       break;
4356     default:
4357       goto unsupported_field;
4358   }
4359
4360   gst_video_info_set_interlaced_format (info, format, interlace_mode, width,
4361       height);
4362
4363   gst_v4l2_object_get_colorspace (v4l2object, &fmt, &info->colorimetry);
4364   gst_v4l2_object_get_streamparm (v4l2object, info);
4365   if ((info->fps_n == 0 && v4l2object->info.fps_d != 0)
4366       && (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
4367           || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
4368     info->fps_d = v4l2object->info.fps_d;
4369     info->fps_n = v4l2object->info.fps_n;
4370     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "Set capture fps to %d/%d",
4371         info->fps_n, info->fps_d);
4372   }
4373
4374   gst_v4l2_object_save_format (v4l2object, fmtdesc, &fmt, info, &align);
4375
4376   /* Shall we setup the pool ? */
4377
4378   return TRUE;
4379
4380 get_fmt_failed:
4381   {
4382     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
4383         (_("Video device did not provide output format.")), GST_ERROR_SYSTEM);
4384     return FALSE;
4385   }
4386 invalid_dimensions:
4387   {
4388     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
4389         (_("Video device returned invalid dimensions.")),
4390         ("Expected non 0 dimensions, got %dx%d", fmt.fmt.pix.width,
4391             fmt.fmt.pix.height));
4392     return FALSE;
4393   }
4394 unsupported_field:
4395   {
4396     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
4397         (_("Video device uses an unsupported interlacing method.")),
4398         ("V4L2 field type %d not supported", fmt.fmt.pix.field));
4399     return FALSE;
4400   }
4401 unsupported_format:
4402   {
4403     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
4404         (_("Video device uses an unsupported pixel format.")),
4405         ("V4L2 format %" GST_FOURCC_FORMAT " not supported",
4406             GST_FOURCC_ARGS (fmt.fmt.pix.pixelformat)));
4407     return FALSE;
4408   }
4409 }
4410
4411 /**
4412  * gst_v4l2_object_set_crop:
4413  * @obj: the object
4414  * @crop_rect: the region to crop
4415  *
4416  * Crop the video data to the regions specified in the @crop_rect.
4417  *
4418  * For capture devices, this crop the image sensor / video stream provided by
4419  * the V4L2 device.
4420  * For output devices, this crops the memory buffer that GStreamer passed to
4421  * the V4L2 device.
4422  *
4423  * The crop_rect may be modified by the V4L2 device to a region that
4424  * fulfills H/W requirements.
4425  *
4426  * Returns: %TRUE on success, %FALSE on failure.
4427  */
4428 gboolean
4429 gst_v4l2_object_set_crop (GstV4l2Object * obj, struct v4l2_rect * crop_rect)
4430 {
4431   struct v4l2_selection sel = { 0 };
4432   struct v4l2_crop crop = { 0 };
4433
4434   GST_V4L2_CHECK_OPEN (obj);
4435
4436   sel.type = obj->type;
4437   sel.target = V4L2_SEL_TGT_CROP;
4438   sel.flags = 0;
4439   sel.r = *crop_rect;
4440
4441   crop.type = obj->type;
4442   crop.c = sel.r;
4443
4444   GST_DEBUG_OBJECT (obj->dbg_obj,
4445       "Desired cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
4446       crop.c.width, crop.c.height);
4447
4448   if (obj->ioctl (obj->video_fd, VIDIOC_S_SELECTION, &sel) < 0) {
4449     if (errno != ENOTTY) {
4450       GST_WARNING_OBJECT (obj->dbg_obj,
4451           "Failed to set crop rectangle with VIDIOC_S_SELECTION: %s",
4452           g_strerror (errno));
4453       return FALSE;
4454     } else {
4455       if (obj->ioctl (obj->video_fd, VIDIOC_S_CROP, &crop) < 0) {
4456         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_S_CROP failed");
4457         return FALSE;
4458       }
4459
4460       if (obj->ioctl (obj->video_fd, VIDIOC_G_CROP, &crop) < 0) {
4461         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_G_CROP failed");
4462         return FALSE;
4463       }
4464
4465       sel.r = crop.c;
4466     }
4467   }
4468
4469   GST_DEBUG_OBJECT (obj->dbg_obj,
4470       "Got cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
4471       crop.c.width, crop.c.height);
4472
4473   return TRUE;
4474 }
4475
4476 /**
4477  * gst_v4l2_object_setup_padding:
4478  * @obj: v4l2 object
4479  *
4480  * Crop away the padding around the video data as specified
4481  * in GstVideoAlignement data stored in @obj.
4482  *
4483  * For capture devices, this crop the image sensor / video stream provided by
4484  * the V4L2 device.
4485  * For output devices, this crops the memory buffer that GStreamer passed to
4486  * the V4L2 device.
4487  *
4488  * Returns: %TRUE on success, %FALSE on failure.
4489  */
4490 gboolean
4491 gst_v4l2_object_setup_padding (GstV4l2Object * obj)
4492 {
4493   GstVideoAlignment *align = &obj->align;
4494   struct v4l2_rect crop;
4495
4496   if (align->padding_left + align->padding_top
4497       + align->padding_right + align->padding_bottom == 0) {
4498     GST_DEBUG_OBJECT (obj->dbg_obj, "no cropping needed");
4499     return TRUE;
4500   }
4501
4502   crop.left = align->padding_left;
4503   crop.top = align->padding_top;
4504   crop.width = obj->info.width;
4505   crop.height = GST_VIDEO_INFO_FIELD_HEIGHT (&obj->info);
4506
4507   return gst_v4l2_object_set_crop (obj, &crop);
4508 }
4509
4510 static gboolean
4511 gst_v4l2_object_get_crop_rect (GstV4l2Object * obj, guint target,
4512     struct v4l2_rect *result)
4513 {
4514   struct v4l2_rect *res_rect;
4515
4516   struct v4l2_selection sel = { 0 };
4517   struct v4l2_cropcap cropcap = { 0 };
4518
4519   GST_V4L2_CHECK_OPEN (obj);
4520
4521   if (target != V4L2_SEL_TGT_CROP_BOUNDS && target != V4L2_SEL_TGT_CROP_DEFAULT)
4522     return FALSE;
4523
4524   sel.type = obj->type;
4525   sel.target = target;
4526
4527   res_rect = &sel.r;
4528
4529   if (obj->ioctl (obj->video_fd, VIDIOC_G_SELECTION, &sel) < 0) {
4530     if (errno != ENOTTY) {
4531       GST_WARNING_OBJECT (obj->dbg_obj,
4532           "Failed to get default crop rectangle with VIDIOC_G_SELECTION: %s",
4533           g_strerror (errno));
4534       return FALSE;
4535     } else {
4536       if (obj->ioctl (obj->video_fd, VIDIOC_CROPCAP, &cropcap) < 0) {
4537         GST_WARNING_OBJECT (obj->dbg_obj, "VIDIOC_CROPCAP failed");
4538         return FALSE;
4539       }
4540       if (target == V4L2_SEL_TGT_CROP_BOUNDS)
4541         res_rect = &cropcap.bounds;
4542       else if (target == V4L2_SEL_TGT_CROP_DEFAULT)
4543         res_rect = &cropcap.defrect;
4544     }
4545   }
4546
4547   *result = *res_rect;
4548   return TRUE;
4549 }
4550
4551 gboolean
4552 gst_v4l2_object_get_crop_bounds (GstV4l2Object * obj, struct v4l2_rect * result)
4553 {
4554   return gst_v4l2_object_get_crop_rect (obj, V4L2_SEL_TGT_CROP_BOUNDS, result);
4555 }
4556
4557 gboolean
4558 gst_v4l2_object_get_crop_default (GstV4l2Object * obj,
4559     struct v4l2_rect * result)
4560 {
4561   return gst_v4l2_object_get_crop_rect (obj, V4L2_SEL_TGT_CROP_DEFAULT, result);
4562 }
4563
4564 gboolean
4565 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
4566 {
4567   GstStructure *config;
4568   GstCaps *oldcaps;
4569   gboolean ret;
4570   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4571
4572   if (!pool)
4573     return FALSE;
4574
4575   config = gst_buffer_pool_get_config (pool);
4576   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4577
4578   ret = oldcaps && gst_caps_is_equal (caps, oldcaps);
4579
4580   gst_structure_free (config);
4581
4582   gst_object_unref (pool);
4583   return ret;
4584 }
4585
4586 gboolean
4587 gst_v4l2_object_caps_is_subset (GstV4l2Object * v4l2object, GstCaps * caps)
4588 {
4589   GstStructure *config;
4590   GstCaps *oldcaps;
4591   gboolean ret;
4592   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4593
4594   if (!pool)
4595     return FALSE;
4596
4597   config = gst_buffer_pool_get_config (pool);
4598   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4599
4600   ret = oldcaps && gst_caps_is_subset (oldcaps, caps);
4601
4602   gst_structure_free (config);
4603
4604   gst_object_unref (pool);
4605   return ret;
4606 }
4607
4608 GstCaps *
4609 gst_v4l2_object_get_current_caps (GstV4l2Object * v4l2object)
4610 {
4611   GstStructure *config;
4612   GstCaps *oldcaps;
4613   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4614
4615   if (!pool)
4616     return NULL;
4617
4618   config = gst_buffer_pool_get_config (pool);
4619   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
4620
4621   if (oldcaps)
4622     gst_caps_ref (oldcaps);
4623
4624   gst_structure_free (config);
4625
4626   gst_object_unref (pool);
4627   return oldcaps;
4628 }
4629
4630 gboolean
4631 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
4632 {
4633   gboolean ret = TRUE;
4634   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4635
4636   GST_LOG_OBJECT (v4l2object->dbg_obj, "start flushing");
4637
4638   gst_poll_set_flushing (v4l2object->poll, TRUE);
4639
4640   if (!pool)
4641     return ret;
4642
4643   if (gst_buffer_pool_is_active (pool))
4644     gst_buffer_pool_set_flushing (pool, TRUE);
4645
4646   gst_object_unref (pool);
4647   return ret;
4648 }
4649
4650 gboolean
4651 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
4652 {
4653   gboolean ret = TRUE;
4654   GstBufferPool *pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4655
4656   GST_LOG_OBJECT (v4l2object->dbg_obj, "stop flushing");
4657
4658   gst_poll_set_flushing (v4l2object->poll, FALSE);
4659
4660   if (!pool)
4661     return ret;
4662
4663   if (gst_buffer_pool_is_active (pool))
4664     gst_buffer_pool_set_flushing (pool, FALSE);
4665
4666   gst_object_unref (pool);
4667   return ret;
4668 }
4669
4670 gboolean
4671 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
4672 {
4673   GstBufferPool *pool;
4674   GST_DEBUG_OBJECT (v4l2object->dbg_obj, "stopping");
4675
4676   if (!GST_V4L2_IS_OPEN (v4l2object))
4677     goto done;
4678   if (!GST_V4L2_IS_ACTIVE (v4l2object))
4679     goto done;
4680
4681   gst_poll_set_flushing (v4l2object->poll, TRUE);
4682
4683   pool = gst_v4l2_object_get_buffer_pool (v4l2object);
4684   if (pool) {
4685     if (!gst_v4l2_buffer_pool_orphan (v4l2object)) {
4686       GST_DEBUG_OBJECT (v4l2object->dbg_obj, "deactivating pool");
4687       gst_buffer_pool_set_active (pool, FALSE);
4688
4689       {
4690         GstBufferPool *old_pool;
4691         GST_OBJECT_LOCK (v4l2object->element);
4692         old_pool = v4l2object->pool;
4693         v4l2object->pool = NULL;
4694         GST_OBJECT_UNLOCK (v4l2object->element);
4695         if (old_pool)
4696           gst_object_unref (old_pool);
4697       }
4698     }
4699     gst_object_unref (pool);
4700   }
4701
4702   GST_V4L2_SET_INACTIVE (v4l2object);
4703
4704 done:
4705   return TRUE;
4706 }
4707
4708 GstCaps *
4709 gst_v4l2_object_probe_caps (GstV4l2Object * v4l2object, GstCaps * filter)
4710 {
4711   GstCaps *ret;
4712   GSList *walk;
4713   GSList *formats;
4714   guint32 fourcc = 0;
4715
4716   if (v4l2object->fmtdesc)
4717     fourcc = GST_V4L2_PIXELFORMAT (v4l2object);
4718
4719   gst_v4l2_object_clear_format_list (v4l2object);
4720   formats = gst_v4l2_object_get_format_list (v4l2object);
4721
4722   /* Recover the fmtdesc, it may no longer exist, in which case it will be set
4723    * to null */
4724   if (fourcc)
4725     v4l2object->fmtdesc =
4726         gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
4727
4728   ret = gst_caps_new_empty ();
4729
4730   if (v4l2object->keep_aspect && !v4l2object->par) {
4731     struct v4l2_cropcap cropcap;
4732
4733     memset (&cropcap, 0, sizeof (cropcap));
4734
4735     cropcap.type = v4l2object->type;
4736     if (v4l2object->ioctl (v4l2object->video_fd, VIDIOC_CROPCAP, &cropcap) < 0) {
4737       if (errno != ENOTTY)
4738         GST_WARNING_OBJECT (v4l2object->dbg_obj,
4739             "Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: %s",
4740             g_strerror (errno));
4741     } else if (cropcap.pixelaspect.numerator && cropcap.pixelaspect.denominator) {
4742       v4l2object->par = g_new0 (GValue, 1);
4743       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
4744       gst_value_set_fraction (v4l2object->par, cropcap.pixelaspect.numerator,
4745           cropcap.pixelaspect.denominator);
4746     }
4747   }
4748
4749   for (walk = formats; walk; walk = walk->next) {
4750     struct v4l2_fmtdesc *format;
4751     GstStructure *template;
4752     GstCaps *tmp;
4753
4754     format = (struct v4l2_fmtdesc *) walk->data;
4755
4756     template = gst_v4l2_object_v4l2fourcc_to_bare_struct (format->pixelformat);
4757
4758     if (!template) {
4759       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
4760           "unknown format %" GST_FOURCC_FORMAT,
4761           GST_FOURCC_ARGS (format->pixelformat));
4762       continue;
4763     }
4764
4765     /* If we have a filter, check if we need to probe this format or not */
4766     if (filter) {
4767       GstCaps *format_caps = gst_caps_new_empty ();
4768
4769       gst_caps_append_structure (format_caps, gst_structure_copy (template));
4770
4771       if (!gst_caps_can_intersect (format_caps, filter)) {
4772         gst_caps_unref (format_caps);
4773         gst_structure_free (template);
4774         continue;
4775       }
4776
4777       gst_caps_unref (format_caps);
4778     }
4779
4780     tmp = gst_v4l2_object_probe_caps_for_format (v4l2object,
4781         format->pixelformat, template);
4782     if (tmp) {
4783       gst_caps_append (ret, tmp);
4784
4785       /* Add a variant of the caps with the Interlaced feature so we can negotiate it if needed */
4786       add_alternate_variant (v4l2object, ret, gst_caps_get_structure (ret,
4787               gst_caps_get_size (ret) - 1));
4788     }
4789
4790     gst_structure_free (template);
4791   }
4792
4793   if (filter) {
4794     GstCaps *tmp;
4795
4796     tmp = ret;
4797     ret = gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
4798     gst_caps_unref (tmp);
4799   }
4800
4801   GST_INFO_OBJECT (v4l2object->dbg_obj, "probed caps: %" GST_PTR_FORMAT, ret);
4802
4803   return ret;
4804 }
4805
4806 GstCaps *
4807 gst_v4l2_object_get_caps (GstV4l2Object * v4l2object, GstCaps * filter)
4808 {
4809   GstCaps *ret;
4810
4811   if (v4l2object->probed_caps == NULL)
4812     v4l2object->probed_caps = gst_v4l2_object_probe_caps (v4l2object, NULL);
4813
4814   if (filter) {
4815     ret = gst_caps_intersect_full (filter, v4l2object->probed_caps,
4816         GST_CAPS_INTERSECT_FIRST);
4817   } else {
4818     ret = gst_caps_ref (v4l2object->probed_caps);
4819   }
4820
4821   return ret;
4822 }
4823
4824 static gboolean
4825 gst_v4l2_object_match_buffer_layout (GstV4l2Object * obj, guint n_planes,
4826     gsize offset[GST_VIDEO_MAX_PLANES], gint stride[GST_VIDEO_MAX_PLANES],
4827     gsize buffer_size, guint padded_height)
4828 {
4829   guint p;
4830   gboolean need_fmt_update = FALSE;
4831
4832   if (n_planes != GST_VIDEO_INFO_N_PLANES (&obj->info)) {
4833     GST_WARNING_OBJECT (obj->dbg_obj,
4834         "Cannot match buffers with different number planes");
4835     return FALSE;
4836   }
4837
4838   for (p = 0; p < n_planes; p++) {
4839     if (stride[p] < obj->info.stride[p]) {
4840       GST_DEBUG_OBJECT (obj->dbg_obj,
4841           "Not matching as remote stride %i is smaller than %i on plane %u",
4842           stride[p], obj->info.stride[p], p);
4843       return FALSE;
4844     } else if (stride[p] > obj->info.stride[p]) {
4845       GST_LOG_OBJECT (obj->dbg_obj,
4846           "remote stride %i is higher than %i on plane %u",
4847           stride[p], obj->info.stride[p], p);
4848       need_fmt_update = TRUE;
4849     }
4850
4851     if (offset[p] < obj->info.offset[p]) {
4852       GST_DEBUG_OBJECT (obj->dbg_obj,
4853           "Not matching as offset %" G_GSIZE_FORMAT
4854           " is smaller than %" G_GSIZE_FORMAT " on plane %u",
4855           offset[p], obj->info.offset[p], p);
4856       return FALSE;
4857     } else if (offset[p] > obj->info.offset[p]) {
4858       GST_LOG_OBJECT (obj->dbg_obj,
4859           "Remote offset %" G_GSIZE_FORMAT
4860           " is higher than %" G_GSIZE_FORMAT " on plane %u",
4861           offset[p], obj->info.offset[p], p);
4862       need_fmt_update = TRUE;
4863     }
4864
4865     if (padded_height) {
4866       guint fmt_height;
4867
4868       if (V4L2_TYPE_IS_MULTIPLANAR (obj->type))
4869         fmt_height = obj->format.fmt.pix_mp.height;
4870       else
4871         fmt_height = obj->format.fmt.pix.height;
4872
4873       if (padded_height > fmt_height)
4874         need_fmt_update = TRUE;
4875     }
4876   }
4877
4878   if (need_fmt_update) {
4879     struct v4l2_format format;
4880     gint wanted_stride[GST_VIDEO_MAX_PLANES] = { 0, };
4881
4882     format = obj->format;
4883
4884     if (padded_height) {
4885       GST_DEBUG_OBJECT (obj->dbg_obj, "Padded height %u", padded_height);
4886
4887       obj->align.padding_bottom =
4888           padded_height - GST_VIDEO_INFO_FIELD_HEIGHT (&obj->info);
4889     } else {
4890       GST_WARNING_OBJECT (obj->dbg_obj,
4891           "Failed to compute padded height; keep the default one");
4892       padded_height = format.fmt.pix_mp.height;
4893     }
4894
4895     /* update the current format with the stride we want to import from */
4896     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
4897       guint i;
4898
4899       GST_DEBUG_OBJECT (obj->dbg_obj, "Wanted strides:");
4900
4901       for (i = 0; i < obj->n_v4l2_planes; i++) {
4902         gint plane_stride = stride[i];
4903
4904         if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo))
4905           plane_stride = GST_VIDEO_TILE_X_TILES (plane_stride) *
4906               GST_VIDEO_FORMAT_INFO_TILE_STRIDE (obj->info.finfo, i);
4907
4908         format.fmt.pix_mp.plane_fmt[i].bytesperline = plane_stride;
4909         format.fmt.pix_mp.height = padded_height;
4910         wanted_stride[i] = plane_stride;
4911         GST_DEBUG_OBJECT (obj->dbg_obj, "    [%u] %i", i, wanted_stride[i]);
4912       }
4913     } else {
4914       gint plane_stride = stride[0];
4915
4916       GST_DEBUG_OBJECT (obj->dbg_obj, "Wanted stride: %i", plane_stride);
4917
4918       if (GST_VIDEO_FORMAT_INFO_IS_TILED (obj->info.finfo))
4919         plane_stride = GST_VIDEO_TILE_X_TILES (plane_stride) *
4920             GST_VIDEO_FORMAT_INFO_TILE_STRIDE (obj->info.finfo, 0);
4921
4922       format.fmt.pix.bytesperline = plane_stride;
4923       format.fmt.pix.height = padded_height;
4924       wanted_stride[0] = plane_stride;
4925     }
4926
4927     if (obj->ioctl (obj->video_fd, VIDIOC_S_FMT, &format) < 0) {
4928       GST_WARNING_OBJECT (obj->dbg_obj,
4929           "Something went wrong trying to update current format: %s",
4930           g_strerror (errno));
4931       return FALSE;
4932     }
4933
4934     gst_v4l2_object_save_format (obj, obj->fmtdesc, &format, &obj->info,
4935         &obj->align);
4936
4937     if (V4L2_TYPE_IS_MULTIPLANAR (obj->type)) {
4938       guint i;
4939
4940       for (i = 0; i < obj->n_v4l2_planes; i++) {
4941         if (format.fmt.pix_mp.plane_fmt[i].bytesperline != wanted_stride[i]) {
4942           GST_DEBUG_OBJECT (obj->dbg_obj,
4943               "[%i] Driver did not accept the new stride (wants %i, got %i)",
4944               i, wanted_stride[i], format.fmt.pix_mp.plane_fmt[i].bytesperline);
4945           return FALSE;
4946         }
4947       }
4948
4949       if (format.fmt.pix_mp.height != padded_height) {
4950         GST_DEBUG_OBJECT (obj->dbg_obj,
4951             "Driver did not accept the padded height (wants %i, got %i)",
4952             padded_height, format.fmt.pix_mp.height);
4953       }
4954     } else {
4955       if (format.fmt.pix.bytesperline != wanted_stride[0]) {
4956         GST_DEBUG_OBJECT (obj->dbg_obj,
4957             "Driver did not accept the new stride (wants %i, got %i)",
4958             wanted_stride[0], format.fmt.pix.bytesperline);
4959         return FALSE;
4960       }
4961
4962       if (format.fmt.pix.height != padded_height) {
4963         GST_DEBUG_OBJECT (obj->dbg_obj,
4964             "Driver did not accept the padded height (wants %i, got %i)",
4965             padded_height, format.fmt.pix.height);
4966       }
4967     }
4968   }
4969
4970   if (obj->align.padding_bottom) {
4971     /* Crop because of vertical padding */
4972     GST_DEBUG_OBJECT (obj->dbg_obj, "crop because of bottom padding of %d",
4973         obj->align.padding_bottom);
4974     gst_v4l2_object_setup_padding (obj);
4975   }
4976
4977   return TRUE;
4978 }
4979
4980 static gboolean
4981 validate_video_meta_struct (GstV4l2Object * obj, const GstStructure * s)
4982 {
4983   guint i;
4984
4985   for (i = 0; i < gst_structure_n_fields (s); i++) {
4986     const gchar *name = gst_structure_nth_field_name (s, i);
4987
4988     if (!g_str_equal (name, "padding-top")
4989         && !g_str_equal (name, "padding-bottom")
4990         && !g_str_equal (name, "padding-left")
4991         && !g_str_equal (name, "padding-right")) {
4992       GST_WARNING_OBJECT (obj->dbg_obj, "Unknown video meta field: '%s'", name);
4993       return FALSE;
4994     }
4995   }
4996
4997   return TRUE;
4998 }
4999
5000 static gboolean
5001 gst_v4l2_object_match_buffer_layout_from_struct (GstV4l2Object * obj,
5002     const GstStructure * s, GstCaps * caps, guint buffer_size)
5003 {
5004   GstVideoInfo info;
5005   GstVideoAlignment align;
5006   gsize plane_size[GST_VIDEO_MAX_PLANES];
5007
5008   if (!validate_video_meta_struct (obj, s))
5009     return FALSE;
5010
5011   if (!gst_video_info_from_caps (&info, caps)) {
5012     GST_WARNING_OBJECT (obj->dbg_obj, "Failed to create video info");
5013     return FALSE;
5014   }
5015
5016   gst_video_alignment_reset (&align);
5017
5018   gst_structure_get_uint (s, "padding-top", &align.padding_top);
5019   gst_structure_get_uint (s, "padding-bottom", &align.padding_bottom);
5020   gst_structure_get_uint (s, "padding-left", &align.padding_left);
5021   gst_structure_get_uint (s, "padding-right", &align.padding_right);
5022
5023   if (align.padding_top || align.padding_bottom || align.padding_left ||
5024       align.padding_right) {
5025     GST_DEBUG_OBJECT (obj->dbg_obj,
5026         "Upstream requested padding (top: %d bottom: %d left: %d right: %d)",
5027         align.padding_top, align.padding_bottom, align.padding_left,
5028         align.padding_right);
5029   }
5030
5031   if (!gst_video_info_align_full (&info, &align, plane_size)) {
5032     GST_WARNING_OBJECT (obj->dbg_obj, "Failed to align video info");
5033     return FALSE;
5034   }
5035
5036   if (GST_VIDEO_INFO_SIZE (&info) != buffer_size) {
5037     GST_WARNING_OBJECT (obj->dbg_obj,
5038         "Requested buffer size (%d) doesn't match video info size (%"
5039         G_GSIZE_FORMAT ")", buffer_size, GST_VIDEO_INFO_SIZE (&info));
5040     return FALSE;
5041   }
5042
5043   GST_DEBUG_OBJECT (obj->dbg_obj,
5044       "try matching buffer layout requested by downstream");
5045
5046   gst_v4l2_object_match_buffer_layout (obj, GST_VIDEO_INFO_N_PLANES (&info),
5047       info.offset, info.stride, buffer_size,
5048       GST_VIDEO_INFO_PLANE_HEIGHT (&info, 0, plane_size));
5049
5050   return TRUE;
5051 }
5052
5053 gboolean
5054 gst_v4l2_object_decide_allocation (GstV4l2Object * obj, GstQuery * query)
5055 {
5056   GstCaps *caps;
5057   GstBufferPool *pool = NULL, *other_pool = NULL, *obj_pool = NULL;
5058   GstStructure *config;
5059   guint size, min, max, own_min = 0;
5060   gboolean update;
5061   gboolean has_video_meta;
5062   gboolean can_share_own_pool, pushing_from_our_pool = FALSE;
5063   GstAllocator *allocator = NULL;
5064   GstAllocationParams params = { 0 };
5065   guint video_idx;
5066
5067   GST_DEBUG_OBJECT (obj->dbg_obj, "decide allocation");
5068
5069   g_return_val_if_fail (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
5070       obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, FALSE);
5071
5072   gst_query_parse_allocation (query, &caps, NULL);
5073
5074   obj_pool = gst_v4l2_object_get_buffer_pool (obj);
5075   if (obj_pool == NULL) {
5076     if (!gst_v4l2_object_setup_pool (obj, caps))
5077       goto pool_failed;
5078     obj_pool = gst_v4l2_object_get_buffer_pool (obj);
5079     if (obj_pool == NULL)
5080       goto pool_failed;
5081   }
5082
5083   if (gst_query_get_n_allocation_params (query) > 0)
5084     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
5085
5086   if (gst_query_get_n_allocation_pools (query) > 0) {
5087     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
5088     update = TRUE;
5089   } else {
5090     pool = NULL;
5091     min = max = 0;
5092     size = 0;
5093     update = FALSE;
5094   }
5095
5096   GST_DEBUG_OBJECT (obj->dbg_obj, "allocation: size:%u min:%u max:%u pool:%"
5097       GST_PTR_FORMAT, size, min, max, pool);
5098
5099   has_video_meta =
5100       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE,
5101       &video_idx);
5102
5103   if (has_video_meta) {
5104     const GstStructure *params;
5105     gst_query_parse_nth_allocation_meta (query, video_idx, &params);
5106
5107     if (params)
5108       gst_v4l2_object_match_buffer_layout_from_struct (obj, params, caps, size);
5109   }
5110
5111   can_share_own_pool = (has_video_meta || !obj->need_video_meta);
5112
5113   gst_v4l2_get_driver_min_buffers (obj);
5114   /* We can't share our own pool, if it exceed V4L2 capacity */
5115   if (min + obj->min_buffers + 1 > VIDEO_MAX_FRAME)
5116     can_share_own_pool = FALSE;
5117
5118   /* select a pool */
5119   switch (obj->mode) {
5120     case GST_V4L2_IO_RW:
5121       if (pool) {
5122         /* in READ/WRITE mode, prefer a downstream pool because our own pool
5123          * doesn't help much, we have to write to it as well */
5124         GST_DEBUG_OBJECT (obj->dbg_obj,
5125             "read/write mode: using downstream pool");
5126         /* use the bigest size, when we use our own pool we can't really do any
5127          * other size than what the hardware gives us but for downstream pools
5128          * we can try */
5129         size = MAX (size, obj->info.size);
5130       } else if (can_share_own_pool) {
5131         /* no downstream pool, use our own then */
5132         GST_DEBUG_OBJECT (obj->dbg_obj,
5133             "read/write mode: no downstream pool, using our own");
5134         pool = gst_object_ref (obj_pool);
5135         size = obj->info.size;
5136         pushing_from_our_pool = TRUE;
5137       }
5138       break;
5139
5140     case GST_V4L2_IO_USERPTR:
5141     case GST_V4L2_IO_DMABUF_IMPORT:
5142       /* in importing mode, prefer our own pool, and pass the other pool to
5143        * our own, so it can serve itself */
5144       if (pool == NULL)
5145         goto no_downstream_pool;
5146       gst_v4l2_buffer_pool_set_other_pool (GST_V4L2_BUFFER_POOL (obj_pool),
5147           pool);
5148       other_pool = pool;
5149       gst_object_unref (pool);
5150       pool = gst_object_ref (obj_pool);
5151       size = obj->info.size;
5152       break;
5153
5154     case GST_V4L2_IO_MMAP:
5155     case GST_V4L2_IO_DMABUF:
5156       /* in streaming mode, prefer our own pool */
5157       /* Check if we can use it ... */
5158       if (can_share_own_pool) {
5159         if (pool)
5160           gst_object_unref (pool);
5161         pool = gst_object_ref (obj_pool);
5162         size = obj->info.size;
5163         GST_DEBUG_OBJECT (obj->dbg_obj,
5164             "streaming mode: using our own pool %" GST_PTR_FORMAT, pool);
5165         pushing_from_our_pool = TRUE;
5166       } else if (pool) {
5167         GST_DEBUG_OBJECT (obj->dbg_obj,
5168             "streaming mode: copying to downstream pool %" GST_PTR_FORMAT,
5169             pool);
5170       } else {
5171         GST_DEBUG_OBJECT (obj->dbg_obj,
5172             "streaming mode: no usable pool, copying to generic pool");
5173         size = MAX (size, obj->info.size);
5174       }
5175       break;
5176     case GST_V4L2_IO_AUTO:
5177     default:
5178       GST_WARNING_OBJECT (obj->dbg_obj, "unhandled mode");
5179       break;
5180   }
5181
5182   if (size == 0)
5183     goto no_size;
5184
5185   /* If pushing from our own pool, configure it with queried minimum,
5186    * otherwise use the minimum required */
5187   if (pushing_from_our_pool) {
5188     /* When pushing from our own pool, we need what downstream one, to be able
5189      * to fill the pipeline, the minimum required to decoder according to the
5190      * driver and 2 more, so we don't endup up with everything downstream or
5191      * held by the decoder. We account 2 buffers for v4l2 so when one is being
5192      * pushed downstream the other one can already be queued for the next
5193      * frame. */
5194     own_min = min + obj->min_buffers + 2;
5195
5196     /* If no allocation parameters where provided, allow for a little more
5197      * buffers and enable copy threshold */
5198     if (!update) {
5199       own_min += 2;
5200       gst_v4l2_buffer_pool_copy_at_threshold (GST_V4L2_BUFFER_POOL (pool),
5201           TRUE);
5202     } else {
5203       gst_v4l2_buffer_pool_copy_at_threshold (GST_V4L2_BUFFER_POOL (pool),
5204           FALSE);
5205     }
5206
5207   } else {
5208     /* In this case we'll have to configure two buffer pool. For our buffer
5209      * pool, we'll need what the driver one, and one more, so we can dequeu */
5210     own_min = obj->min_buffers + 1;
5211     own_min = MAX (own_min, GST_V4L2_MIN_BUFFERS (obj));
5212
5213     /* for the downstream pool, we keep what downstream wants, though ensure
5214      * at least a minimum if downstream didn't suggest anything (we are
5215      * expecting the base class to create a default one for the context) */
5216     min = MAX (min, GST_V4L2_MIN_BUFFERS (obj));
5217
5218     /* To import we need the other pool to hold at least own_min */
5219     if (obj_pool == pool)
5220       min += own_min;
5221   }
5222
5223   /* Request a bigger max, if one was suggested but it's too small */
5224   if (max != 0)
5225     max = MAX (min, max);
5226
5227   /* First step, configure our own pool */
5228   config = gst_buffer_pool_get_config (obj_pool);
5229
5230   if (obj->need_video_meta || has_video_meta) {
5231     GST_DEBUG_OBJECT (obj->dbg_obj, "activate Video Meta");
5232     gst_buffer_pool_config_add_option (config,
5233         GST_BUFFER_POOL_OPTION_VIDEO_META);
5234   }
5235
5236   gst_buffer_pool_config_set_allocator (config, allocator, &params);
5237   gst_buffer_pool_config_set_params (config, caps, size, own_min, 0);
5238
5239   GST_DEBUG_OBJECT (obj->dbg_obj, "setting own pool config to %"
5240       GST_PTR_FORMAT, config);
5241
5242   /* Our pool often need to adjust the value */
5243   if (!gst_buffer_pool_set_config (obj_pool, config)) {
5244     config = gst_buffer_pool_get_config (obj_pool);
5245
5246     GST_DEBUG_OBJECT (obj->dbg_obj, "own pool config changed to %"
5247         GST_PTR_FORMAT, config);
5248
5249     /* our pool will adjust the maximum buffer, which we are fine with */
5250     if (!gst_buffer_pool_set_config (obj_pool, config))
5251       goto config_failed;
5252   }
5253
5254   /* Now configure the other pool if different */
5255   if (obj_pool != pool)
5256     other_pool = pool;
5257
5258   if (other_pool) {
5259     config = gst_buffer_pool_get_config (other_pool);
5260     gst_buffer_pool_config_set_allocator (config, allocator, &params);
5261     gst_buffer_pool_config_set_params (config, caps, size, min, max);
5262
5263     GST_DEBUG_OBJECT (obj->dbg_obj, "setting other pool config to %"
5264         GST_PTR_FORMAT, config);
5265
5266     /* if downstream supports video metadata, add this to the pool config */
5267     if (has_video_meta) {
5268       GST_DEBUG_OBJECT (obj->dbg_obj, "activate Video Meta");
5269       gst_buffer_pool_config_add_option (config,
5270           GST_BUFFER_POOL_OPTION_VIDEO_META);
5271     }
5272
5273     if (!gst_buffer_pool_set_config (other_pool, config)) {
5274       config = gst_buffer_pool_get_config (other_pool);
5275
5276       if (!gst_buffer_pool_config_validate_params (config, caps, size, min,
5277               max)) {
5278         gst_structure_free (config);
5279         goto config_failed;
5280       }
5281
5282       if (!gst_buffer_pool_set_config (other_pool, config))
5283         goto config_failed;
5284     }
5285   }
5286
5287   if (pool) {
5288     /* For simplicity, simply read back the active configuration, so our base
5289      * class get the right information */
5290     config = gst_buffer_pool_get_config (pool);
5291     gst_buffer_pool_config_get_params (config, NULL, &size, &min, &max);
5292     gst_structure_free (config);
5293   }
5294
5295   if (update)
5296     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
5297   else
5298     gst_query_add_allocation_pool (query, pool, size, min, max);
5299
5300   if (allocator)
5301     gst_object_unref (allocator);
5302
5303   if (pool)
5304     gst_object_unref (pool);
5305
5306   if (obj_pool)
5307     gst_object_unref (obj_pool);
5308
5309   return TRUE;
5310
5311 pool_failed:
5312   {
5313     /* setup_pool already send the error */
5314     goto cleanup;
5315   }
5316 config_failed:
5317   {
5318     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5319         (_("Failed to configure internal buffer pool.")), (NULL));
5320     goto cleanup;
5321   }
5322 no_size:
5323   {
5324     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5325         (_("Video device did not suggest any buffer size.")), (NULL));
5326     goto cleanup;
5327   }
5328 no_downstream_pool:
5329   {
5330     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
5331         (_("No downstream pool to import from.")),
5332         ("When importing DMABUF or USERPTR, we need a pool to import from"));
5333     goto cleanup;
5334   }
5335 cleanup:
5336   {
5337     if (allocator)
5338       gst_object_unref (allocator);
5339
5340     if (pool)
5341       gst_object_unref (pool);
5342
5343     if (obj_pool)
5344       gst_object_unref (obj_pool);
5345     return FALSE;
5346   }
5347 }
5348
5349 gboolean
5350 gst_v4l2_object_propose_allocation (GstV4l2Object * obj, GstQuery * query)
5351 {
5352   GstBufferPool *pool = NULL;
5353   /* we need at least 2 buffers to operate */
5354   guint size, min, max;
5355   GstCaps *caps;
5356   gboolean need_pool;
5357
5358   /* Set defaults allocation parameters */
5359   size = obj->info.size;
5360   min = GST_V4L2_MIN_BUFFERS (obj);
5361   max = VIDEO_MAX_FRAME;
5362
5363   gst_query_parse_allocation (query, &caps, &need_pool);
5364
5365   if (caps == NULL)
5366     goto no_caps;
5367
5368   switch (obj->mode) {
5369     case GST_V4L2_IO_MMAP:
5370     case GST_V4L2_IO_DMABUF:
5371       if (need_pool) {
5372         GstBufferPool *obj_pool = gst_v4l2_object_get_buffer_pool (obj);
5373         if (obj_pool) {
5374           if (!gst_buffer_pool_is_active (obj_pool))
5375             pool = gst_object_ref (obj_pool);
5376
5377           gst_object_unref (obj_pool);
5378         }
5379       }
5380       break;
5381     default:
5382       break;
5383   }
5384
5385   if (pool != NULL) {
5386     GstCaps *pcaps;
5387     GstStructure *config;
5388
5389     /* we had a pool, check caps */
5390     config = gst_buffer_pool_get_config (pool);
5391     gst_buffer_pool_config_get_params (config, &pcaps, NULL, NULL, NULL);
5392
5393     GST_DEBUG_OBJECT (obj->dbg_obj,
5394         "we had a pool with caps %" GST_PTR_FORMAT, pcaps);
5395     if (!gst_caps_is_equal (caps, pcaps)) {
5396       gst_structure_free (config);
5397       gst_object_unref (pool);
5398       goto different_caps;
5399     }
5400     gst_structure_free (config);
5401   }
5402   gst_v4l2_get_driver_min_buffers (obj);
5403
5404   min = MAX (obj->min_buffers, GST_V4L2_MIN_BUFFERS (obj));
5405
5406   gst_query_add_allocation_pool (query, pool, size, min, max);
5407
5408   /* we also support various metadata */
5409   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
5410
5411   if (pool)
5412     gst_object_unref (pool);
5413
5414   return TRUE;
5415
5416   /* ERRORS */
5417 no_caps:
5418   {
5419     GST_DEBUG_OBJECT (obj->dbg_obj, "no caps specified");
5420     return FALSE;
5421   }
5422 different_caps:
5423   {
5424     /* different caps, we can't use this pool */
5425     GST_DEBUG_OBJECT (obj->dbg_obj, "pool has different caps");
5426     return FALSE;
5427   }
5428 }
5429
5430 gboolean
5431 gst_v4l2_object_try_import (GstV4l2Object * obj, GstBuffer * buffer)
5432 {
5433   GstVideoMeta *vmeta;
5434   guint n_mem = gst_buffer_n_memory (buffer);
5435
5436   /* only import if requested */
5437   switch (obj->mode) {
5438     case GST_V4L2_IO_USERPTR:
5439     case GST_V4L2_IO_DMABUF_IMPORT:
5440       break;
5441     default:
5442       GST_DEBUG_OBJECT (obj->dbg_obj,
5443           "The io-mode does not enable importation");
5444       return FALSE;
5445   }
5446
5447   vmeta = gst_buffer_get_video_meta (buffer);
5448   if (!vmeta && obj->need_video_meta) {
5449     GST_DEBUG_OBJECT (obj->dbg_obj, "Downstream buffer uses standard "
5450         "stride/offset while the driver does not.");
5451     return FALSE;
5452   }
5453
5454   /* we need matching strides/offsets and size */
5455   if (vmeta) {
5456     guint plane_height[GST_VIDEO_MAX_PLANES] = { 0, };
5457
5458     gst_video_meta_get_plane_height (vmeta, plane_height);
5459
5460     if (!gst_v4l2_object_match_buffer_layout (obj, vmeta->n_planes,
5461             vmeta->offset, vmeta->stride, gst_buffer_get_size (buffer),
5462             plane_height[0]))
5463       return FALSE;
5464   }
5465
5466   /* we can always import single memory buffer, but otherwise we need the same
5467    * amount of memory object. */
5468   if (n_mem != 1 && n_mem != obj->n_v4l2_planes) {
5469     GST_DEBUG_OBJECT (obj->dbg_obj, "Can only import %i memory, "
5470         "buffers contains %u memory", obj->n_v4l2_planes, n_mem);
5471     return FALSE;
5472   }
5473
5474   /* For DMABuf importation we need DMABuf of course */
5475   if (obj->mode == GST_V4L2_IO_DMABUF_IMPORT) {
5476     guint i;
5477
5478     for (i = 0; i < n_mem; i++) {
5479       GstMemory *mem = gst_buffer_peek_memory (buffer, i);
5480
5481       if (!gst_is_dmabuf_memory (mem)) {
5482         GST_DEBUG_OBJECT (obj->dbg_obj, "Cannot import non-DMABuf memory.");
5483         return FALSE;
5484       }
5485     }
5486   }
5487
5488   /* for the remaining, only the kernel driver can tell */
5489   return TRUE;
5490 }
5491
5492 /**
5493  * gst_v4l2_object_get_buffer_pool:
5494  * @src: a #GstV4l2Object
5495  *
5496  * Returns: (nullable) (transfer full): the instance of the #GstBufferPool used
5497  * by the v4l2object; unref it after usage.
5498  */
5499 GstBufferPool *
5500 gst_v4l2_object_get_buffer_pool (GstV4l2Object * v4l2object)
5501 {
5502   GstBufferPool *ret = NULL;
5503
5504   g_return_val_if_fail (v4l2object != NULL, NULL);
5505
5506   GST_OBJECT_LOCK (v4l2object->element);
5507   if (v4l2object->pool)
5508     ret = gst_object_ref (v4l2object->pool);
5509   GST_OBJECT_UNLOCK (v4l2object->element);
5510
5511   return ret;
5512 }
5513
5514 /**
5515  * gst_v4l2_object_poll:
5516  * @v4l2object: a #GstV4l2Object
5517  * @timeout: timeout of type #GstClockTime
5518  *
5519  * Poll the video file descriptor for read when this is a capture, write when
5520  * this is an output. It will also watch for errors and source change events.
5521  * If a source change event is received, %GST_V4L2_FLOW_RESOLUTION_CHANGE will
5522  * be returned. If the poll was interrupted, %GST_FLOW_FLUSHING is returned.
5523  * If there was no read or write indicator, %GST_V4L2_FLOW_LAST_BUFFER is
5524  * returned. It may also return %GST_FLOW_ERROR if some unexpected error
5525  * occured.
5526  *
5527  * Returns: GST_FLOW_OK if buffers are ready to be queued or dequeued.
5528  */
5529 GstFlowReturn
5530 gst_v4l2_object_poll (GstV4l2Object * v4l2object, GstClockTime timeout)
5531 {
5532   gint ret;
5533
5534   if (!v4l2object->can_poll_device) {
5535     if (timeout != 0)
5536       goto done;
5537     else
5538       goto no_buffers;
5539   }
5540
5541   GST_LOG_OBJECT (v4l2object->dbg_obj, "polling device");
5542
5543 again:
5544   ret = gst_poll_wait (v4l2object->poll, timeout);
5545   if (G_UNLIKELY (ret < 0)) {
5546     switch (errno) {
5547       case EBUSY:
5548         goto stopped;
5549       case EAGAIN:
5550       case EINTR:
5551         goto again;
5552       case ENXIO:
5553         GST_WARNING_OBJECT (v4l2object->dbg_obj,
5554             "v4l2 device doesn't support polling. Disabling"
5555             " using libv4l2 in this case may cause deadlocks");
5556         v4l2object->can_poll_device = FALSE;
5557         goto done;
5558       default:
5559         goto select_error;
5560     }
5561   }
5562
5563   if (gst_poll_fd_has_error (v4l2object->poll, &v4l2object->pollfd))
5564     goto select_error;
5565
5566   /* PRI is used to signal that events are available */
5567   if (gst_poll_fd_has_pri (v4l2object->poll, &v4l2object->pollfd)) {
5568     struct v4l2_event event = { 0, };
5569
5570     if (!gst_v4l2_dequeue_event (v4l2object, &event))
5571       goto dqevent_failed;
5572
5573     if (event.type != V4L2_EVENT_SOURCE_CHANGE) {
5574       GST_INFO_OBJECT (v4l2object->dbg_obj,
5575           "Received unhandled event, ignoring.");
5576       goto again;
5577     }
5578
5579     if ((event.u.src_change.changes & V4L2_EVENT_SRC_CH_RESOLUTION) == 0) {
5580       GST_DEBUG_OBJECT (v4l2object->dbg_obj,
5581           "Received non-resolution source-change, ignoring.");
5582       goto again;
5583     }
5584
5585     return GST_V4L2_FLOW_RESOLUTION_CHANGE;
5586   }
5587
5588   if (ret == 0)
5589     goto no_buffers;
5590
5591 done:
5592   return GST_FLOW_OK;
5593
5594   /* ERRORS */
5595 stopped:
5596   {
5597     GST_DEBUG_OBJECT (v4l2object->dbg_obj, "stop called");
5598     return GST_FLOW_FLUSHING;
5599   }
5600 select_error:
5601   {
5602     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
5603         ("poll error %d: %s (%d)", ret, g_strerror (errno), errno));
5604     return GST_FLOW_ERROR;
5605   }
5606 no_buffers:
5607   {
5608     return GST_V4L2_FLOW_LAST_BUFFER;
5609   }
5610 dqevent_failed:
5611   {
5612     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ, (NULL),
5613         ("dqevent error: %s (%d)", g_strerror (errno), errno));
5614     return GST_FLOW_ERROR;
5615   }
5616 }
5617
5618 /**
5619  * gst_v4l2_object_subscribe_event:
5620  * @v4l2object: a #GstV4l2Object
5621  * @event: the event ID
5622  *
5623  * Subscribe to an event, and enable polling for these. Note that only
5624  * %V4L2_EVENT_SOURCE_CHANGE is currently supported by the poll helper.
5625  *
5626  * Returns: %TRUE if the driver supports this event
5627  */
5628 gboolean
5629 gst_v4l2_object_subscribe_event (GstV4l2Object * v4l2object, guint32 event)
5630 {
5631   guint32 id = 0;
5632
5633   g_return_val_if_fail (v4l2object != NULL, FALSE);
5634   g_return_val_if_fail (GST_V4L2_IS_OPEN (v4l2object), FALSE);
5635
5636   v4l2object->get_in_out_func (v4l2object, &id);
5637
5638   if (gst_v4l2_subscribe_event (v4l2object, event, id)) {
5639     gst_poll_fd_ctl_pri (v4l2object->poll, &v4l2object->pollfd, TRUE);
5640     return TRUE;
5641   }
5642
5643   return FALSE;
5644 }