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