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