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