180313323a0a1a030e6f8a932bd7565c499d0425
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2object.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@indt.org.br>
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 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
22  * with newer GLib versions (>= 2.31.0) */
23 #define GLIB_DISABLE_DEPRECATION_WARNINGS
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <string.h>
34
35 #ifdef HAVE_GUDEV
36 #include <gudev/gudev.h>
37 #endif
38
39 #include "v4l2_calls.h"
40 #include "gstv4l2tuner.h"
41 #include "gstv4l2colorbalance.h"
42
43 #include "gst/gst-i18n-plugin.h"
44
45 #include <gst/video/video.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_CHANNEL            NULL
55 #define DEFAULT_PROP_FREQUENCY          0
56 #define DEFAULT_PROP_IO_MODE            GST_V4L2_IO_AUTO
57
58 #define ENCODED_BUFFER_SIZE             (1 * 1024 * 1024)
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   /* from Linux 2.6.15 videodev2.h */
87   {V4L2_PIX_FMT_RGB332, TRUE, GST_V4L2_RAW},
88   {V4L2_PIX_FMT_RGB555, TRUE, GST_V4L2_RAW},
89   {V4L2_PIX_FMT_RGB565, TRUE, GST_V4L2_RAW},
90   {V4L2_PIX_FMT_RGB555X, TRUE, GST_V4L2_RAW},
91   {V4L2_PIX_FMT_RGB565X, TRUE, GST_V4L2_RAW},
92   {V4L2_PIX_FMT_BGR24, TRUE, GST_V4L2_RAW},
93   {V4L2_PIX_FMT_RGB24, TRUE, GST_V4L2_RAW},
94   {V4L2_PIX_FMT_BGR32, TRUE, GST_V4L2_RAW},
95   {V4L2_PIX_FMT_RGB32, TRUE, GST_V4L2_RAW},
96   {V4L2_PIX_FMT_GREY, TRUE, GST_V4L2_RAW},
97   {V4L2_PIX_FMT_YVU410, TRUE, GST_V4L2_RAW},
98   {V4L2_PIX_FMT_YVU420, TRUE, GST_V4L2_RAW},
99   {V4L2_PIX_FMT_YUYV, TRUE, GST_V4L2_RAW},
100   {V4L2_PIX_FMT_UYVY, TRUE, GST_V4L2_RAW},
101   {V4L2_PIX_FMT_YUV422P, TRUE, GST_V4L2_RAW},
102   {V4L2_PIX_FMT_YUV411P, TRUE, GST_V4L2_RAW},
103   {V4L2_PIX_FMT_Y41P, TRUE, GST_V4L2_RAW},
104
105   /* two planes -- one Y, one Cr + Cb interleaved  */
106   {V4L2_PIX_FMT_NV12, TRUE, GST_V4L2_RAW},
107   {V4L2_PIX_FMT_NV12M, TRUE, GST_V4L2_RAW},
108   {V4L2_PIX_FMT_NV12MT, TRUE, GST_V4L2_RAW},
109   {V4L2_PIX_FMT_NV21, TRUE, GST_V4L2_RAW},
110   {V4L2_PIX_FMT_NV21M, TRUE, GST_V4L2_RAW},
111
112   /*  The following formats are not defined in the V4L2 specification */
113   {V4L2_PIX_FMT_YUV410, TRUE, GST_V4L2_RAW},
114   {V4L2_PIX_FMT_YUV420, TRUE, GST_V4L2_RAW},
115   {V4L2_PIX_FMT_YYUV, TRUE, GST_V4L2_RAW},
116   {V4L2_PIX_FMT_HI240, TRUE, GST_V4L2_RAW},
117
118   /* see http://www.siliconimaging.com/RGB%20Bayer.htm */
119   {V4L2_PIX_FMT_SBGGR8, TRUE, GST_V4L2_CODEC},
120
121   /* compressed formats */
122   {V4L2_PIX_FMT_MJPEG, FALSE, GST_V4L2_CODEC},
123   {V4L2_PIX_FMT_JPEG, FALSE, GST_V4L2_CODEC},
124   {V4L2_PIX_FMT_PJPG, FALSE, GST_V4L2_CODEC},
125   {V4L2_PIX_FMT_DV, FALSE, GST_V4L2_TRANSPORT},
126   {V4L2_PIX_FMT_MPEG, FALSE, GST_V4L2_TRANSPORT},
127   {V4L2_PIX_FMT_MPEG1, FALSE, GST_V4L2_CODEC},
128   {V4L2_PIX_FMT_MPEG2, FALSE, GST_V4L2_CODEC},
129   {V4L2_PIX_FMT_MPEG4, FALSE, GST_V4L2_CODEC},
130   {V4L2_PIX_FMT_H263, FALSE, GST_V4L2_CODEC},
131   {V4L2_PIX_FMT_H264, FALSE, GST_V4L2_CODEC},
132   /* VP8 not parseable */
133   {V4L2_PIX_FMT_VP8, FALSE, GST_V4L2_CODEC | GST_V4L2_NO_PARSE},
134
135   /*  Vendor-specific formats   */
136   {V4L2_PIX_FMT_WNVA, TRUE, GST_V4L2_CODEC},
137   {V4L2_PIX_FMT_SN9C10X, TRUE, GST_V4L2_CODEC},
138   {V4L2_PIX_FMT_PWC1, TRUE, GST_V4L2_CODEC},
139   {V4L2_PIX_FMT_PWC2, TRUE, GST_V4L2_CODEC},
140   {V4L2_PIX_FMT_YVYU, TRUE, GST_V4L2_RAW},
141 };
142
143 #define GST_V4L2_FORMAT_COUNT (G_N_ELEMENTS (gst_v4l2_formats))
144
145 static GSList *gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object);
146
147
148 #define GST_TYPE_V4L2_DEVICE_FLAGS (gst_v4l2_device_get_type ())
149 static GType
150 gst_v4l2_device_get_type (void)
151 {
152   static GType v4l2_device_type = 0;
153
154   if (v4l2_device_type == 0) {
155     static const GFlagsValue values[] = {
156       {V4L2_CAP_VIDEO_CAPTURE, "Device supports video capture", "capture"},
157       {V4L2_CAP_VIDEO_OUTPUT, "Device supports video playback", "output"},
158       {V4L2_CAP_VIDEO_OVERLAY, "Device supports video overlay", "overlay"},
159
160       {V4L2_CAP_VBI_CAPTURE, "Device supports the VBI capture", "vbi-capture"},
161       {V4L2_CAP_VBI_OUTPUT, "Device supports the VBI output", "vbi-output"},
162
163       {V4L2_CAP_TUNER, "Device has a tuner or modulator", "tuner"},
164       {V4L2_CAP_AUDIO, "Device has audio inputs or outputs", "audio"},
165
166       {0, NULL, NULL}
167     };
168
169     v4l2_device_type =
170         g_flags_register_static ("GstV4l2DeviceTypeFlags", values);
171   }
172
173   return v4l2_device_type;
174 }
175
176 #define GST_TYPE_V4L2_TV_NORM (gst_v4l2_tv_norm_get_type ())
177 static GType
178 gst_v4l2_tv_norm_get_type (void)
179 {
180   static GType v4l2_tv_norm = 0;
181
182   if (!v4l2_tv_norm) {
183     static const GEnumValue tv_norms[] = {
184       {0, "none", "none"},
185
186       {V4L2_STD_NTSC, "NTSC", "NTSC"},
187       {V4L2_STD_NTSC_M, "NTSC-M", "NTSC-M"},
188       {V4L2_STD_NTSC_M_JP, "NTSC-M-JP", "NTSC-M-JP"},
189       {V4L2_STD_NTSC_M_KR, "NTSC-M-KR", "NTSC-M-KR"},
190       {V4L2_STD_NTSC_443, "NTSC-443", "NTSC-443"},
191
192       {V4L2_STD_PAL, "PAL", "PAL"},
193       {V4L2_STD_PAL_BG, "PAL-BG", "PAL-BG"},
194       {V4L2_STD_PAL_B, "PAL-B", "PAL-B"},
195       {V4L2_STD_PAL_B1, "PAL-B1", "PAL-B1"},
196       {V4L2_STD_PAL_G, "PAL-G", "PAL-G"},
197       {V4L2_STD_PAL_H, "PAL-H", "PAL-H"},
198       {V4L2_STD_PAL_I, "PAL-I", "PAL-I"},
199       {V4L2_STD_PAL_DK, "PAL-DK", "PAL-DK"},
200       {V4L2_STD_PAL_D, "PAL-D", "PAL-D"},
201       {V4L2_STD_PAL_D1, "PAL-D1", "PAL-D1"},
202       {V4L2_STD_PAL_K, "PAL-K", "PAL-K"},
203       {V4L2_STD_PAL_M, "PAL-M", "PAL-M"},
204       {V4L2_STD_PAL_N, "PAL-N", "PAL-N"},
205       {V4L2_STD_PAL_Nc, "PAL-Nc", "PAL-Nc"},
206       {V4L2_STD_PAL_60, "PAL-60", "PAL-60"},
207
208       {V4L2_STD_SECAM, "SECAM", "SECAM"},
209       {V4L2_STD_SECAM_B, "SECAM-B", "SECAM-B"},
210       {V4L2_STD_SECAM_G, "SECAM-G", "SECAM-G"},
211       {V4L2_STD_SECAM_H, "SECAM-H", "SECAM-H"},
212       {V4L2_STD_SECAM_DK, "SECAM-DK", "SECAM-DK"},
213       {V4L2_STD_SECAM_D, "SECAM-D", "SECAM-D"},
214       {V4L2_STD_SECAM_K, "SECAM-K", "SECAM-K"},
215       {V4L2_STD_SECAM_K1, "SECAM-K1", "SECAM-K1"},
216       {V4L2_STD_SECAM_L, "SECAM-L", "SECAM-L"},
217       {V4L2_STD_SECAM_LC, "SECAM-Lc", "SECAM-Lc"},
218
219       {0, NULL, NULL}
220     };
221
222     v4l2_tv_norm = g_enum_register_static ("V4L2_TV_norms", tv_norms);
223   }
224
225   return v4l2_tv_norm;
226 }
227
228 GType
229 gst_v4l2_io_mode_get_type (void)
230 {
231   static GType v4l2_io_mode = 0;
232
233   if (!v4l2_io_mode) {
234     static const GEnumValue io_modes[] = {
235       {GST_V4L2_IO_AUTO, "GST_V4L2_IO_AUTO", "auto"},
236       {GST_V4L2_IO_RW, "GST_V4L2_IO_RW", "rw"},
237       {GST_V4L2_IO_MMAP, "GST_V4L2_IO_MMAP", "mmap"},
238       {GST_V4L2_IO_USERPTR, "GST_V4L2_IO_USERPTR", "userptr"},
239       {GST_V4L2_IO_DMABUF, "GST_V4L2_IO_DMABUF", "dmabuf"},
240       {GST_V4L2_IO_DMABUF_IMPORT, "GST_V4L2_IO_DMABUF_IMPORT",
241           "dmabuf-import"},
242
243       {0, NULL, NULL}
244     };
245     v4l2_io_mode = g_enum_register_static ("GstV4l2IOMode", io_modes);
246   }
247   return v4l2_io_mode;
248 }
249
250 void
251 gst_v4l2_object_install_properties_helper (GObjectClass * gobject_class,
252     const char *default_device)
253 {
254   g_object_class_install_property (gobject_class, PROP_DEVICE,
255       g_param_spec_string ("device", "Device", "Device location",
256           default_device, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
257   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
258       g_param_spec_string ("device-name", "Device name",
259           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
260           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
261   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
262       g_param_spec_int ("device-fd", "File descriptor",
263           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
264           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
265   g_object_class_install_property (gobject_class, PROP_FLAGS,
266       g_param_spec_flags ("flags", "Flags", "Device type flags",
267           GST_TYPE_V4L2_DEVICE_FLAGS, DEFAULT_PROP_FLAGS,
268           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
269
270   /**
271    * GstV4l2Src:brightness:
272    *
273    * Picture brightness, or more precisely, the black level
274    */
275   g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
276       g_param_spec_int ("brightness", "Brightness",
277           "Picture brightness, or more precisely, the black level", G_MININT,
278           G_MAXINT, 0,
279           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
280   /**
281    * GstV4l2Src:contrast:
282    *
283    * Picture contrast or luma gain
284    */
285   g_object_class_install_property (gobject_class, PROP_CONTRAST,
286       g_param_spec_int ("contrast", "Contrast",
287           "Picture contrast or luma gain", G_MININT,
288           G_MAXINT, 0,
289           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
290   /**
291    * GstV4l2Src:saturation:
292    *
293    * Picture color saturation or chroma gain
294    */
295   g_object_class_install_property (gobject_class, PROP_SATURATION,
296       g_param_spec_int ("saturation", "Saturation",
297           "Picture color saturation or chroma gain", G_MININT,
298           G_MAXINT, 0,
299           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
300   /**
301    * GstV4l2Src:hue:
302    *
303    * Hue or color balance
304    */
305   g_object_class_install_property (gobject_class, PROP_HUE,
306       g_param_spec_int ("hue", "Hue",
307           "Hue or color balance", G_MININT,
308           G_MAXINT, 0,
309           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
310
311   /**
312    * GstV4l2Src:norm:
313    *
314    * TV norm
315    */
316   g_object_class_install_property (gobject_class, PROP_TV_NORM,
317       g_param_spec_enum ("norm", "TV norm",
318           "video standard",
319           GST_TYPE_V4L2_TV_NORM, DEFAULT_PROP_TV_NORM,
320           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
321
322   /**
323    * GstV4l2Src:io-mode:
324    *
325    * IO Mode
326    */
327   g_object_class_install_property (gobject_class, PROP_IO_MODE,
328       g_param_spec_enum ("io-mode", "IO mode",
329           "I/O mode",
330           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
331           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
332
333   /**
334    * GstV4l2Src:extra-controls:
335    *
336    * Additional v4l2 controls for the device. The controls are identified
337    * by the control name (lowercase with '_' for any non-alphanumeric
338    * characters).
339    *
340    * Since: 1.2
341    */
342   g_object_class_install_property (gobject_class, PROP_EXTRA_CONTROLS,
343       g_param_spec_boxed ("extra-controls", "Extra Controls",
344           "Extra v4l2 controls (CIDs) for the device",
345           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346
347   /**
348    * GstV4l2Src:pixel-aspect-ratio:
349    *
350    * The pixel aspect ratio of the device. This overwrites the pixel aspect
351    * ratio queried from the device.
352    *
353    * Since: 1.2
354    */
355   g_object_class_install_property (gobject_class, PROP_PIXEL_ASPECT_RATIO,
356       g_param_spec_string ("pixel-aspect-ratio", "Pixel Aspect Ratio",
357           "Overwrite the pixel aspect ratio of the device", "1/1",
358           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
359
360   /**
361    * GstV4l2Src:force-aspect-ratio:
362    *
363    * When enabled, the pixel aspect ratio queried from the device or set
364    * with the pixel-aspect-ratio property will be enforced.
365    *
366    * Since: 1.2
367    */
368   g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
369       g_param_spec_boolean ("force-aspect-ratio", "Force aspect ratio",
370           "When enabled, the pixel aspect ratio will be enforced", TRUE,
371           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
372
373 }
374
375 void
376 gst_v4l2_object_install_m2m_properties_helper (GObjectClass * gobject_class)
377 {
378   g_object_class_install_property (gobject_class, PROP_DEVICE,
379       g_param_spec_string ("device", "Device", "Device location",
380           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
381
382   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
383       g_param_spec_string ("device-name", "Device name",
384           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
385           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
386
387   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
388       g_param_spec_int ("device-fd", "File descriptor",
389           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
390           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
391
392   g_object_class_install_property (gobject_class, PROP_OUTPUT_IO_MODE,
393       g_param_spec_enum ("output-io-mode", "Output IO mode",
394           "Output side I/O mode (matches sink pad)",
395           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
396           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
397
398   g_object_class_install_property (gobject_class, PROP_CAPTURE_IO_MODE,
399       g_param_spec_enum ("capture-io-mode", "Capture IO mode",
400           "Capture I/O mode (matches src pad)",
401           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
402           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
403
404   g_object_class_install_property (gobject_class, PROP_EXTRA_CONTROLS,
405       g_param_spec_boxed ("extra-controls", "Extra Controls",
406           "Extra v4l2 controls (CIDs) for the device",
407           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
408 }
409
410 GstV4l2Object *
411 gst_v4l2_object_new (GstElement * element,
412     enum v4l2_buf_type type,
413     const char *default_device,
414     GstV4l2GetInOutFunction get_in_out_func,
415     GstV4l2SetInOutFunction set_in_out_func,
416     GstV4l2UpdateFpsFunction update_fps_func)
417 {
418   GstV4l2Object *v4l2object;
419
420   /*
421    * some default values
422    */
423   v4l2object = g_new0 (GstV4l2Object, 1);
424
425   v4l2object->type = type;
426   v4l2object->formats = NULL;
427
428   v4l2object->element = element;
429   v4l2object->get_in_out_func = get_in_out_func;
430   v4l2object->set_in_out_func = set_in_out_func;
431   v4l2object->update_fps_func = update_fps_func;
432
433   v4l2object->video_fd = -1;
434   v4l2object->active = FALSE;
435   v4l2object->videodev = g_strdup (default_device);
436
437   v4l2object->norms = NULL;
438   v4l2object->channels = NULL;
439   v4l2object->colors = NULL;
440
441   v4l2object->xwindow_id = 0;
442
443   v4l2object->keep_aspect = TRUE;
444
445   v4l2object->n_v4l2_planes = 0;
446
447   v4l2object->no_initial_format = FALSE;
448
449   return v4l2object;
450 }
451
452 static gboolean gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object);
453
454
455 void
456 gst_v4l2_object_destroy (GstV4l2Object * v4l2object)
457 {
458   g_return_if_fail (v4l2object != NULL);
459
460   if (v4l2object->videodev)
461     g_free (v4l2object->videodev);
462
463   if (v4l2object->channel)
464     g_free (v4l2object->channel);
465
466   if (v4l2object->formats) {
467     gst_v4l2_object_clear_format_list (v4l2object);
468   }
469
470   if (v4l2object->probed_caps) {
471     gst_caps_unref (v4l2object->probed_caps);
472   }
473
474   g_free (v4l2object);
475 }
476
477
478 static gboolean
479 gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object)
480 {
481   g_slist_foreach (v4l2object->formats, (GFunc) g_free, NULL);
482   g_slist_free (v4l2object->formats);
483   v4l2object->formats = NULL;
484
485   return TRUE;
486 }
487
488 static gint
489 gst_v4l2_object_prop_to_cid (guint prop_id)
490 {
491   gint cid = -1;
492
493   switch (prop_id) {
494     case PROP_BRIGHTNESS:
495       cid = V4L2_CID_BRIGHTNESS;
496       break;
497     case PROP_CONTRAST:
498       cid = V4L2_CID_CONTRAST;
499       break;
500     case PROP_SATURATION:
501       cid = V4L2_CID_SATURATION;
502       break;
503     case PROP_HUE:
504       cid = V4L2_CID_HUE;
505       break;
506     default:
507       GST_WARNING ("unmapped property id: %d", prop_id);
508   }
509   return cid;
510 }
511
512
513 gboolean
514 gst_v4l2_object_set_property_helper (GstV4l2Object * v4l2object,
515     guint prop_id, const GValue * value, GParamSpec * pspec)
516 {
517   switch (prop_id) {
518     case PROP_DEVICE:
519       g_free (v4l2object->videodev);
520       v4l2object->videodev = g_value_dup_string (value);
521       break;
522     case PROP_BRIGHTNESS:
523     case PROP_CONTRAST:
524     case PROP_SATURATION:
525     case PROP_HUE:
526     {
527       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
528
529       if (cid != -1) {
530         if (GST_V4L2_IS_OPEN (v4l2object)) {
531           gst_v4l2_set_attribute (v4l2object, cid, g_value_get_int (value));
532         }
533       }
534       return TRUE;
535     }
536       break;
537     case PROP_TV_NORM:
538       v4l2object->tv_norm = g_value_get_enum (value);
539       break;
540 #if 0
541     case PROP_CHANNEL:
542       if (GST_V4L2_IS_OPEN (v4l2object)) {
543         GstTuner *tuner = GST_TUNER (v4l2object->element);
544         GstTunerChannel *channel = gst_tuner_find_channel_by_name (tuner,
545             (gchar *) g_value_get_string (value));
546
547         if (channel) {
548           /* like gst_tuner_set_channel (tuner, channel)
549              without g_object_notify */
550           gst_v4l2_tuner_set_channel (v4l2object, channel);
551         }
552       } else {
553         g_free (v4l2object->channel);
554         v4l2object->channel = g_value_dup_string (value);
555       }
556       break;
557     case PROP_FREQUENCY:
558       if (GST_V4L2_IS_OPEN (v4l2object)) {
559         GstTuner *tuner = GST_TUNER (v4l2object->element);
560         GstTunerChannel *channel = gst_tuner_get_channel (tuner);
561
562         if (channel &&
563             GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
564           /* like
565              gst_tuner_set_frequency (tuner, channel, g_value_get_ulong (value))
566              without g_object_notify */
567           gst_v4l2_tuner_set_frequency (v4l2object, channel,
568               g_value_get_ulong (value));
569         }
570       } else {
571         v4l2object->frequency = g_value_get_ulong (value);
572       }
573       break;
574 #endif
575
576     case PROP_IO_MODE:
577       v4l2object->req_mode = g_value_get_enum (value);
578       break;
579     case PROP_CAPTURE_IO_MODE:
580       g_return_val_if_fail (!V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
581       v4l2object->req_mode = g_value_get_enum (value);
582       break;
583     case PROP_OUTPUT_IO_MODE:
584       g_return_val_if_fail (V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
585       v4l2object->req_mode = g_value_get_enum (value);
586       break;
587     case PROP_EXTRA_CONTROLS:{
588       const GstStructure *s = gst_value_get_structure (value);
589
590       if (v4l2object->extra_controls)
591         gst_structure_free (v4l2object->extra_controls);
592
593       v4l2object->extra_controls = s ? gst_structure_copy (s) : NULL;
594       if (GST_V4L2_IS_OPEN (v4l2object))
595         gst_v4l2_set_controls (v4l2object, v4l2object->extra_controls);
596       break;
597     }
598     case PROP_PIXEL_ASPECT_RATIO:
599       g_free (v4l2object->par);
600       v4l2object->par = g_new0 (GValue, 1);
601       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
602       if (!g_value_transform (value, v4l2object->par)) {
603         g_warning ("Could not transform string to aspect ratio");
604         gst_value_set_fraction (v4l2object->par, 1, 1);
605       }
606       GST_DEBUG_OBJECT (v4l2object->element, "set PAR to %d/%d",
607           gst_value_get_fraction_numerator (v4l2object->par),
608           gst_value_get_fraction_denominator (v4l2object->par));
609       break;
610     case PROP_FORCE_ASPECT_RATIO:
611       v4l2object->keep_aspect = g_value_get_boolean (value);
612       break;
613     default:
614       return FALSE;
615       break;
616   }
617   return TRUE;
618 }
619
620
621 gboolean
622 gst_v4l2_object_get_property_helper (GstV4l2Object * v4l2object,
623     guint prop_id, GValue * value, GParamSpec * pspec)
624 {
625   switch (prop_id) {
626     case PROP_DEVICE:
627       g_value_set_string (value, v4l2object->videodev);
628       break;
629     case PROP_DEVICE_NAME:
630     {
631       const guchar *new = NULL;
632
633       if (GST_V4L2_IS_OPEN (v4l2object)) {
634         new = v4l2object->vcap.card;
635       } else if (gst_v4l2_open (v4l2object)) {
636         new = v4l2object->vcap.card;
637         gst_v4l2_close (v4l2object);
638       }
639       g_value_set_string (value, (gchar *) new);
640       break;
641     }
642     case PROP_DEVICE_FD:
643     {
644       if (GST_V4L2_IS_OPEN (v4l2object))
645         g_value_set_int (value, v4l2object->video_fd);
646       else
647         g_value_set_int (value, DEFAULT_PROP_DEVICE_FD);
648       break;
649     }
650     case PROP_FLAGS:
651     {
652       guint flags = 0;
653
654       if (GST_V4L2_IS_OPEN (v4l2object)) {
655         flags |= v4l2object->vcap.capabilities &
656             (V4L2_CAP_VIDEO_CAPTURE |
657             V4L2_CAP_VIDEO_OUTPUT |
658             V4L2_CAP_VIDEO_OVERLAY |
659             V4L2_CAP_VBI_CAPTURE |
660             V4L2_CAP_VBI_OUTPUT | V4L2_CAP_TUNER | V4L2_CAP_AUDIO);
661
662         if (v4l2object->vcap.capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE)
663           flags |= V4L2_CAP_VIDEO_CAPTURE;
664
665         if (v4l2object->vcap.capabilities & V4L2_CAP_VIDEO_OUTPUT_MPLANE)
666           flags |= V4L2_CAP_VIDEO_OUTPUT;
667       }
668       g_value_set_flags (value, flags);
669       break;
670     }
671     case PROP_BRIGHTNESS:
672     case PROP_CONTRAST:
673     case PROP_SATURATION:
674     case PROP_HUE:
675     {
676       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
677
678       if (cid != -1) {
679         if (GST_V4L2_IS_OPEN (v4l2object)) {
680           gint v;
681           if (gst_v4l2_get_attribute (v4l2object, cid, &v)) {
682             g_value_set_int (value, v);
683           }
684         }
685       }
686       return TRUE;
687     }
688       break;
689     case PROP_TV_NORM:
690       g_value_set_enum (value, v4l2object->tv_norm);
691       break;
692     case PROP_IO_MODE:
693       g_value_set_enum (value, v4l2object->req_mode);
694       break;
695     case PROP_CAPTURE_IO_MODE:
696       g_return_val_if_fail (!V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
697       g_value_set_enum (value, v4l2object->req_mode);
698       break;
699     case PROP_OUTPUT_IO_MODE:
700       g_return_val_if_fail (V4L2_TYPE_IS_OUTPUT (v4l2object->type), FALSE);
701       g_value_set_enum (value, v4l2object->req_mode);
702       break;
703     case PROP_EXTRA_CONTROLS:
704       gst_value_set_structure (value, v4l2object->extra_controls);
705       break;
706     case PROP_PIXEL_ASPECT_RATIO:
707       if (v4l2object->par)
708         g_value_transform (v4l2object->par, value);
709       break;
710     case PROP_FORCE_ASPECT_RATIO:
711       g_value_set_boolean (value, v4l2object->keep_aspect);
712       break;
713     default:
714       return FALSE;
715       break;
716   }
717   return TRUE;
718 }
719
720 static void
721 gst_v4l2_set_defaults (GstV4l2Object * v4l2object)
722 {
723   GstTunerNorm *norm = NULL;
724   GstTunerChannel *channel = NULL;
725   GstTuner *tuner;
726
727   if (!GST_IS_TUNER (v4l2object->element))
728     return;
729
730   tuner = GST_TUNER (v4l2object->element);
731
732   if (v4l2object->tv_norm)
733     norm = gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
734   GST_DEBUG_OBJECT (v4l2object->element, "tv_norm=0x%" G_GINT64_MODIFIER "x, "
735       "norm=%p", (guint64) v4l2object->tv_norm, norm);
736   if (norm) {
737     gst_tuner_set_norm (tuner, norm);
738   } else {
739     norm =
740         GST_TUNER_NORM (gst_tuner_get_norm (GST_TUNER (v4l2object->element)));
741     if (norm) {
742       v4l2object->tv_norm =
743           gst_v4l2_tuner_get_std_id_by_norm (v4l2object, norm);
744       gst_tuner_norm_changed (tuner, norm);
745     }
746   }
747
748   if (v4l2object->channel)
749     channel = gst_tuner_find_channel_by_name (tuner, v4l2object->channel);
750   if (channel) {
751     gst_tuner_set_channel (tuner, channel);
752   } else {
753     channel =
754         GST_TUNER_CHANNEL (gst_tuner_get_channel (GST_TUNER
755             (v4l2object->element)));
756     if (channel) {
757       g_free (v4l2object->channel);
758       v4l2object->channel = g_strdup (channel->label);
759       gst_tuner_channel_changed (tuner, channel);
760     }
761   }
762
763   if (channel
764       && GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
765     if (v4l2object->frequency != 0) {
766       gst_tuner_set_frequency (tuner, channel, v4l2object->frequency);
767     } else {
768       v4l2object->frequency = gst_tuner_get_frequency (tuner, channel);
769       if (v4l2object->frequency == 0) {
770         /* guess */
771         gst_tuner_set_frequency (tuner, channel, 1000);
772       } else {
773       }
774     }
775   }
776 }
777
778 gboolean
779 gst_v4l2_object_open (GstV4l2Object * v4l2object)
780 {
781   if (gst_v4l2_open (v4l2object))
782     gst_v4l2_set_defaults (v4l2object);
783   else
784     return FALSE;
785
786   return TRUE;
787 }
788
789 gboolean
790 gst_v4l2_object_open_shared (GstV4l2Object * v4l2object, GstV4l2Object * other)
791 {
792   gboolean ret;
793
794   ret = gst_v4l2_dup (v4l2object, other);
795
796   return ret;
797 }
798
799 gboolean
800 gst_v4l2_object_close (GstV4l2Object * v4l2object)
801 {
802   if (!gst_v4l2_close (v4l2object))
803     return FALSE;
804
805   gst_caps_replace (&v4l2object->probed_caps, NULL);
806
807   if (v4l2object->formats) {
808     gst_v4l2_object_clear_format_list (v4l2object);
809   }
810
811   return TRUE;
812 }
813
814 static struct v4l2_fmtdesc *
815 gst_v4l2_object_get_format_from_fourcc (GstV4l2Object * v4l2object,
816     guint32 fourcc)
817 {
818   struct v4l2_fmtdesc *fmt;
819   GSList *walk;
820
821   if (fourcc == 0)
822     return NULL;
823
824   walk = gst_v4l2_object_get_format_list (v4l2object);
825   while (walk) {
826     fmt = (struct v4l2_fmtdesc *) walk->data;
827     if (fmt->pixelformat == fourcc)
828       return fmt;
829     /* special case for jpeg */
830     if (fmt->pixelformat == V4L2_PIX_FMT_MJPEG ||
831         fmt->pixelformat == V4L2_PIX_FMT_JPEG ||
832         fmt->pixelformat == V4L2_PIX_FMT_PJPG) {
833       if (fourcc == V4L2_PIX_FMT_JPEG || fourcc == V4L2_PIX_FMT_MJPEG ||
834           fourcc == V4L2_PIX_FMT_PJPG) {
835         return fmt;
836       }
837     }
838     walk = g_slist_next (walk);
839   }
840
841   return NULL;
842 }
843
844
845
846 /* complete made up ranking, the values themselves are meaningless */
847 /* These ranks MUST be X such that X<<15 fits on a signed int - see
848    the comment at the end of gst_v4l2_object_format_get_rank. */
849 #define YUV_BASE_RANK     1000
850 #define JPEG_BASE_RANK     500
851 #define DV_BASE_RANK       200
852 #define RGB_BASE_RANK      100
853 #define YUV_ODD_BASE_RANK   50
854 #define RGB_ODD_BASE_RANK   25
855 #define BAYER_BASE_RANK     15
856 #define S910_BASE_RANK      10
857 #define GREY_BASE_RANK       5
858 #define PWC_BASE_RANK        1
859
860 static gint
861 gst_v4l2_object_format_get_rank (const struct v4l2_fmtdesc *fmt)
862 {
863   guint32 fourcc = fmt->pixelformat;
864   gboolean emulated = ((fmt->flags & V4L2_FMT_FLAG_EMULATED) != 0);
865   gint rank = 0;
866
867   switch (fourcc) {
868     case V4L2_PIX_FMT_MJPEG:
869     case V4L2_PIX_FMT_PJPG:
870       rank = JPEG_BASE_RANK;
871       break;
872     case V4L2_PIX_FMT_JPEG:
873       rank = JPEG_BASE_RANK + 1;
874       break;
875     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
876       rank = JPEG_BASE_RANK + 2;
877       break;
878
879     case V4L2_PIX_FMT_RGB332:
880     case V4L2_PIX_FMT_RGB555:
881     case V4L2_PIX_FMT_RGB555X:
882     case V4L2_PIX_FMT_RGB565:
883     case V4L2_PIX_FMT_RGB565X:
884       rank = RGB_ODD_BASE_RANK;
885       break;
886
887     case V4L2_PIX_FMT_RGB24:
888     case V4L2_PIX_FMT_BGR24:
889       rank = RGB_BASE_RANK - 1;
890       break;
891
892     case V4L2_PIX_FMT_RGB32:
893     case V4L2_PIX_FMT_BGR32:
894       rank = RGB_BASE_RANK;
895       break;
896
897     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
898       rank = GREY_BASE_RANK;
899       break;
900
901     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
902     case V4L2_PIX_FMT_NV12M:   /* Same as NV12      */
903     case V4L2_PIX_FMT_NV12MT:  /* NV12 64x32 tile   */
904     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
905     case V4L2_PIX_FMT_NV21M:   /* Same as NV21      */
906     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
907     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
908       rank = YUV_ODD_BASE_RANK;
909       break;
910
911     case V4L2_PIX_FMT_YVU410:  /* YVU9,  9 bits per pixel */
912       rank = YUV_BASE_RANK + 3;
913       break;
914     case V4L2_PIX_FMT_YUV410:  /* YUV9,  9 bits per pixel */
915       rank = YUV_BASE_RANK + 2;
916       break;
917     case V4L2_PIX_FMT_YUV420:  /* I420, 12 bits per pixel */
918       rank = YUV_BASE_RANK + 7;
919       break;
920     case V4L2_PIX_FMT_YUYV:    /* YUY2, 16 bits per pixel */
921       rank = YUV_BASE_RANK + 10;
922       break;
923     case V4L2_PIX_FMT_YVU420:  /* YV12, 12 bits per pixel */
924       rank = YUV_BASE_RANK + 6;
925       break;
926     case V4L2_PIX_FMT_UYVY:    /* UYVY, 16 bits per pixel */
927       rank = YUV_BASE_RANK + 9;
928       break;
929     case V4L2_PIX_FMT_Y41P:    /* Y41P, 12 bits per pixel */
930       rank = YUV_BASE_RANK + 5;
931       break;
932     case V4L2_PIX_FMT_YUV411P: /* Y41B, 12 bits per pixel */
933       rank = YUV_BASE_RANK + 4;
934       break;
935     case V4L2_PIX_FMT_YUV422P: /* Y42B, 16 bits per pixel */
936       rank = YUV_BASE_RANK + 8;
937       break;
938
939     case V4L2_PIX_FMT_DV:
940       rank = DV_BASE_RANK;
941       break;
942
943     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
944       rank = 0;
945       break;
946
947     case V4L2_PIX_FMT_SBGGR8:
948       rank = BAYER_BASE_RANK;
949       break;
950
951     case V4L2_PIX_FMT_SN9C10X:
952       rank = S910_BASE_RANK;
953       break;
954
955     case V4L2_PIX_FMT_PWC1:
956       rank = PWC_BASE_RANK;
957       break;
958     case V4L2_PIX_FMT_PWC2:
959       rank = PWC_BASE_RANK;
960       break;
961
962     default:
963       rank = 0;
964       break;
965   }
966
967   /* All ranks are below 1<<15 so a shift by 15
968    * will a) make all non-emulated formats larger
969    * than emulated and b) will not overflow
970    */
971   if (!emulated)
972     rank <<= 15;
973
974   return rank;
975 }
976
977
978
979 static gint
980 format_cmp_func (gconstpointer a, gconstpointer b)
981 {
982   const struct v4l2_fmtdesc *fa = a;
983   const struct v4l2_fmtdesc *fb = b;
984
985   if (fa->pixelformat == fb->pixelformat)
986     return 0;
987
988   return gst_v4l2_object_format_get_rank (fb) -
989       gst_v4l2_object_format_get_rank (fa);
990 }
991
992 /******************************************************
993  * gst_v4l2_object_fill_format_list():
994  *   create list of supported capture formats
995  * return value: TRUE on success, FALSE on error
996  ******************************************************/
997 static gboolean
998 gst_v4l2_object_fill_format_list (GstV4l2Object * v4l2object,
999     enum v4l2_buf_type type)
1000 {
1001   gint n;
1002   struct v4l2_fmtdesc *format;
1003
1004   GST_DEBUG_OBJECT (v4l2object->element, "getting src format enumerations");
1005
1006   /* format enumeration */
1007   for (n = 0;; n++) {
1008     format = g_new0 (struct v4l2_fmtdesc, 1);
1009
1010     format->index = n;
1011     format->type = type;
1012
1013     if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_ENUM_FMT, format) < 0) {
1014       if (errno == EINVAL) {
1015         g_free (format);
1016         break;                  /* end of enumeration */
1017       } else {
1018         goto failed;
1019       }
1020     }
1021
1022     GST_LOG_OBJECT (v4l2object->element, "index:       %u", format->index);
1023     GST_LOG_OBJECT (v4l2object->element, "type:        %d", format->type);
1024     GST_LOG_OBJECT (v4l2object->element, "flags:       %08x", format->flags);
1025     GST_LOG_OBJECT (v4l2object->element, "description: '%s'",
1026         format->description);
1027     GST_LOG_OBJECT (v4l2object->element, "pixelformat: %" GST_FOURCC_FORMAT,
1028         GST_FOURCC_ARGS (format->pixelformat));
1029
1030     /* sort formats according to our preference;  we do this, because caps
1031      * are probed in the order the formats are in the list, and the order of
1032      * formats in the final probed caps matters for things like fixation */
1033     v4l2object->formats = g_slist_insert_sorted (v4l2object->formats, format,
1034         (GCompareFunc) format_cmp_func);
1035   }
1036
1037 #ifndef GST_DISABLE_GST_DEBUG
1038   {
1039     GSList *l;
1040
1041     GST_INFO_OBJECT (v4l2object->element, "got %d format(s):", n);
1042     for (l = v4l2object->formats; l != NULL; l = l->next) {
1043       format = l->data;
1044
1045       GST_INFO_OBJECT (v4l2object->element,
1046           "  %" GST_FOURCC_FORMAT "%s", GST_FOURCC_ARGS (format->pixelformat),
1047           ((format->flags & V4L2_FMT_FLAG_EMULATED)) ? " (emulated)" : "");
1048     }
1049   }
1050 #endif
1051
1052   return TRUE;
1053
1054   /* ERRORS */
1055 failed:
1056   {
1057     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
1058         (_("Failed to enumerate possible video formats device '%s' can work with"), v4l2object->videodev), ("Failed to get number %d in pixelformat enumeration for %s. (%d - %s)", n, v4l2object->videodev, errno, g_strerror (errno)));
1059     g_free (format);
1060     return FALSE;
1061   }
1062 }
1063
1064 /*
1065   * Get the list of supported capture formats, a list of
1066   * <code>struct v4l2_fmtdesc</code>.
1067   */
1068 static GSList *
1069 gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object)
1070 {
1071   if (!v4l2object->formats) {
1072
1073     /* check usual way */
1074     gst_v4l2_object_fill_format_list (v4l2object, v4l2object->type);
1075
1076     /* if our driver supports multi-planar
1077      * and if formats are still empty then we can workaround driver bug
1078      * by also looking up formats as if our device was not supporting
1079      * multiplanar */
1080     if (!v4l2object->formats) {
1081       switch (v4l2object->type) {
1082         case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1083           gst_v4l2_object_fill_format_list (v4l2object,
1084               V4L2_BUF_TYPE_VIDEO_CAPTURE);
1085           break;
1086
1087         case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
1088           gst_v4l2_object_fill_format_list (v4l2object,
1089               V4L2_BUF_TYPE_VIDEO_OUTPUT);
1090           break;
1091
1092         default:
1093           break;
1094       }
1095     }
1096   }
1097   return v4l2object->formats;
1098 }
1099
1100 static GstVideoFormat
1101 gst_v4l2_object_v4l2fourcc_to_video_format (guint32 fourcc)
1102 {
1103   GstVideoFormat format;
1104
1105   switch (fourcc) {
1106     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1107       format = GST_VIDEO_FORMAT_GRAY8;
1108       break;
1109     case V4L2_PIX_FMT_RGB555:
1110       format = GST_VIDEO_FORMAT_RGB15;
1111       break;
1112     case V4L2_PIX_FMT_RGB565:
1113       format = GST_VIDEO_FORMAT_RGB16;
1114       break;
1115     case V4L2_PIX_FMT_RGB24:
1116       format = GST_VIDEO_FORMAT_RGB;
1117       break;
1118     case V4L2_PIX_FMT_BGR24:
1119       format = GST_VIDEO_FORMAT_BGR;
1120       break;
1121     case V4L2_PIX_FMT_RGB32:
1122       format = GST_VIDEO_FORMAT_xRGB;
1123       break;
1124     case V4L2_PIX_FMT_BGR32:
1125       format = GST_VIDEO_FORMAT_BGRx;
1126       break;
1127     case V4L2_PIX_FMT_NV12:
1128     case V4L2_PIX_FMT_NV12M:
1129       format = GST_VIDEO_FORMAT_NV12;
1130       break;
1131     case V4L2_PIX_FMT_NV12MT:
1132       format = GST_VIDEO_FORMAT_NV12_64Z32;
1133       break;
1134     case V4L2_PIX_FMT_NV21:
1135     case V4L2_PIX_FMT_NV21M:
1136       format = GST_VIDEO_FORMAT_NV21;
1137       break;
1138     case V4L2_PIX_FMT_YVU410:
1139       format = GST_VIDEO_FORMAT_YVU9;
1140       break;
1141     case V4L2_PIX_FMT_YUV410:
1142       format = GST_VIDEO_FORMAT_YUV9;
1143       break;
1144     case V4L2_PIX_FMT_YUV420:
1145       format = GST_VIDEO_FORMAT_I420;
1146       break;
1147     case V4L2_PIX_FMT_YUYV:
1148       format = GST_VIDEO_FORMAT_YUY2;
1149       break;
1150     case V4L2_PIX_FMT_YVU420:
1151       format = GST_VIDEO_FORMAT_YV12;
1152       break;
1153     case V4L2_PIX_FMT_UYVY:
1154       format = GST_VIDEO_FORMAT_UYVY;
1155       break;
1156 #if 0
1157     case V4L2_PIX_FMT_Y41P:
1158       format = GST_VIDEO_FORMAT_Y41P;
1159       break;
1160 #endif
1161     case V4L2_PIX_FMT_YUV411P:
1162       format = GST_VIDEO_FORMAT_Y41B;
1163       break;
1164     case V4L2_PIX_FMT_YUV422P:
1165       format = GST_VIDEO_FORMAT_Y42B;
1166       break;
1167     case V4L2_PIX_FMT_YVYU:
1168       format = GST_VIDEO_FORMAT_YVYU;
1169       break;
1170     default:
1171       format = GST_VIDEO_FORMAT_UNKNOWN;
1172       break;
1173   }
1174
1175   return format;
1176 }
1177
1178 static GstStructure *
1179 gst_v4l2_object_v4l2fourcc_to_bare_struct (guint32 fourcc)
1180 {
1181   GstStructure *structure = NULL;
1182
1183   switch (fourcc) {
1184     case V4L2_PIX_FMT_MJPEG:   /* Motion-JPEG */
1185     case V4L2_PIX_FMT_PJPG:    /* Progressive-JPEG */
1186     case V4L2_PIX_FMT_JPEG:    /* JFIF JPEG */
1187       structure = gst_structure_new_empty ("image/jpeg");
1188       break;
1189     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1190     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1191       /* FIXME: get correct fourccs here */
1192       break;
1193     case V4L2_PIX_FMT_MPEG1:
1194       structure = gst_structure_new ("video/mpeg",
1195           "mpegversion", G_TYPE_INT, 2, NULL);
1196       break;
1197     case V4L2_PIX_FMT_MPEG2:
1198       structure = gst_structure_new ("video/mpeg",
1199           "mpegversion", G_TYPE_INT, 2, NULL);
1200       break;
1201     case V4L2_PIX_FMT_MPEG4:
1202       structure = gst_structure_new ("video/mpeg",
1203           "mpegversion", G_TYPE_INT, 4, "systemstream",
1204           G_TYPE_BOOLEAN, FALSE, NULL);
1205       break;
1206     case V4L2_PIX_FMT_H263:
1207       structure = gst_structure_new ("video/x-h263",
1208           "variant", G_TYPE_STRING, "itu", NULL);
1209       break;
1210     case V4L2_PIX_FMT_H264:    /* H.264 */
1211       structure = gst_structure_new ("video/x-h264",
1212           "stream-format", G_TYPE_STRING, "byte-stream", "alignment",
1213           G_TYPE_STRING, "au", NULL);
1214       break;
1215     case V4L2_PIX_FMT_VP8:
1216       structure = gst_structure_new_empty ("video/x-vp8");
1217       break;
1218     case V4L2_PIX_FMT_RGB332:
1219     case V4L2_PIX_FMT_RGB555X:
1220     case V4L2_PIX_FMT_RGB565X:
1221       /* FIXME: get correct fourccs here */
1222       break;
1223     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1224     case V4L2_PIX_FMT_RGB555:
1225     case V4L2_PIX_FMT_RGB565:
1226     case V4L2_PIX_FMT_RGB24:
1227     case V4L2_PIX_FMT_BGR24:
1228     case V4L2_PIX_FMT_RGB32:
1229     case V4L2_PIX_FMT_BGR32:
1230     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1231     case V4L2_PIX_FMT_NV12M:
1232     case V4L2_PIX_FMT_NV12MT:
1233     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1234     case V4L2_PIX_FMT_NV21M:
1235     case V4L2_PIX_FMT_YVU410:
1236     case V4L2_PIX_FMT_YUV410:
1237     case V4L2_PIX_FMT_YUV420:  /* I420/IYUV */
1238     case V4L2_PIX_FMT_YUYV:
1239     case V4L2_PIX_FMT_YVU420:
1240     case V4L2_PIX_FMT_UYVY:
1241 #if 0
1242     case V4L2_PIX_FMT_Y41P:
1243 #endif
1244     case V4L2_PIX_FMT_YUV422P:
1245     case V4L2_PIX_FMT_YVYU:
1246     case V4L2_PIX_FMT_YUV411P:{
1247       GstVideoFormat format;
1248       format = gst_v4l2_object_v4l2fourcc_to_video_format (fourcc);
1249       if (format != GST_VIDEO_FORMAT_UNKNOWN)
1250         structure = gst_structure_new ("video/x-raw",
1251             "format", G_TYPE_STRING, gst_video_format_to_string (format), NULL);
1252       break;
1253     }
1254     case V4L2_PIX_FMT_DV:
1255       structure =
1256           gst_structure_new ("video/x-dv", "systemstream", G_TYPE_BOOLEAN, TRUE,
1257           NULL);
1258       break;
1259     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1260       structure = gst_structure_new ("video/mpegts",
1261           "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
1262       break;
1263     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1264       break;
1265     case V4L2_PIX_FMT_SBGGR8:
1266       structure = gst_structure_new_empty ("video/x-bayer");
1267       break;
1268     case V4L2_PIX_FMT_SN9C10X:
1269       structure = gst_structure_new_empty ("video/x-sonix");
1270       break;
1271     case V4L2_PIX_FMT_PWC1:
1272       structure = gst_structure_new_empty ("video/x-pwc1");
1273       break;
1274     case V4L2_PIX_FMT_PWC2:
1275       structure = gst_structure_new_empty ("video/x-pwc2");
1276       break;
1277     default:
1278       GST_DEBUG ("Unknown fourcc 0x%08x %" GST_FOURCC_FORMAT,
1279           fourcc, GST_FOURCC_ARGS (fourcc));
1280       break;
1281   }
1282
1283   return structure;
1284 }
1285
1286 GstStructure *
1287 gst_v4l2_object_v4l2fourcc_to_structure (guint32 fourcc)
1288 {
1289   GstStructure *template;
1290   gint i;
1291
1292   template = gst_v4l2_object_v4l2fourcc_to_bare_struct (fourcc);
1293
1294   if (template == NULL)
1295     goto done;
1296
1297   for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1298     if (gst_v4l2_formats[i].format != fourcc)
1299       continue;
1300
1301     if (gst_v4l2_formats[i].dimensions) {
1302       gst_structure_set (template,
1303           "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1304           "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1305           "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1, NULL);
1306     }
1307     break;
1308   }
1309
1310 done:
1311   return template;
1312 }
1313
1314
1315 static GstCaps *
1316 gst_v4l2_object_get_caps_helper (GstV4L2FormatFlags flags)
1317 {
1318   GstStructure *structure;
1319   GstCaps *caps;
1320   guint i;
1321
1322   caps = gst_caps_new_empty ();
1323   for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1324
1325     if ((gst_v4l2_formats[i].flags & flags) == 0)
1326       continue;
1327
1328     structure =
1329         gst_v4l2_object_v4l2fourcc_to_bare_struct (gst_v4l2_formats[i].format);
1330
1331     if (structure) {
1332       GstStructure *alt_s = NULL;
1333
1334       if (gst_v4l2_formats[i].dimensions) {
1335         gst_structure_set (structure,
1336             "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1337             "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1338             "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1, NULL);
1339       }
1340
1341       switch (gst_v4l2_formats[i].format) {
1342         case V4L2_PIX_FMT_RGB32:
1343           alt_s = gst_structure_copy (structure);
1344           gst_structure_set (alt_s, "format", G_TYPE_STRING, "ARGB", NULL);
1345           break;
1346         case V4L2_PIX_FMT_BGR32:
1347           alt_s = gst_structure_copy (structure);
1348           gst_structure_set (alt_s, "format", G_TYPE_STRING, "BGRA", NULL);
1349         default:
1350           break;
1351       }
1352
1353       gst_caps_append_structure (caps, structure);
1354
1355       if (alt_s)
1356         gst_caps_append_structure (caps, alt_s);
1357     }
1358   }
1359
1360   return gst_caps_simplify (caps);
1361 }
1362
1363 GstCaps *
1364 gst_v4l2_object_get_all_caps (void)
1365 {
1366   static GstCaps *caps = NULL;
1367
1368   if (caps == NULL)
1369     caps = gst_v4l2_object_get_caps_helper (GST_V4L2_ALL);
1370
1371   return gst_caps_ref (caps);
1372 }
1373
1374 GstCaps *
1375 gst_v4l2_object_get_raw_caps (void)
1376 {
1377   static GstCaps *caps = NULL;
1378
1379   if (caps == NULL)
1380     caps = gst_v4l2_object_get_caps_helper (GST_V4L2_RAW);
1381
1382   return gst_caps_ref (caps);
1383 }
1384
1385 GstCaps *
1386 gst_v4l2_object_get_codec_caps (void)
1387 {
1388   static GstCaps *caps = NULL;
1389
1390   if (caps == NULL)
1391     caps = gst_v4l2_object_get_caps_helper (GST_V4L2_CODEC);
1392
1393   return gst_caps_ref (caps);
1394 }
1395
1396 /* collect data for the given caps
1397  * @caps: given input caps
1398  * @format: location for the v4l format
1399  * @w/@h: location for width and height
1400  * @fps_n/@fps_d: location for framerate
1401  * @size: location for expected size of the frame or 0 if unknown
1402  */
1403 static gboolean
1404 gst_v4l2_object_get_caps_info (GstV4l2Object * v4l2object, GstCaps * caps,
1405     struct v4l2_fmtdesc **format, GstVideoInfo * info)
1406 {
1407   GstStructure *structure;
1408   guint32 fourcc = 0, fourcc_nc = 0;
1409   const gchar *mimetype;
1410   struct v4l2_fmtdesc *fmt = NULL;
1411
1412   structure = gst_caps_get_structure (caps, 0);
1413
1414   mimetype = gst_structure_get_name (structure);
1415
1416   if (!gst_video_info_from_caps (info, caps))
1417     goto invalid_format;
1418
1419   if (g_str_equal (mimetype, "video/x-raw")) {
1420     switch (GST_VIDEO_INFO_FORMAT (info)) {
1421       case GST_VIDEO_FORMAT_I420:
1422         fourcc = V4L2_PIX_FMT_YUV420;
1423         break;
1424       case GST_VIDEO_FORMAT_YUY2:
1425         fourcc = V4L2_PIX_FMT_YUYV;
1426         break;
1427 #if 0
1428       case GST_VIDEO_FORMAT_Y41P:
1429         fourcc = V4L2_PIX_FMT_Y41P;
1430         break;
1431 #endif
1432       case GST_VIDEO_FORMAT_UYVY:
1433         fourcc = V4L2_PIX_FMT_UYVY;
1434         break;
1435       case GST_VIDEO_FORMAT_YV12:
1436         fourcc = V4L2_PIX_FMT_YVU420;
1437         break;
1438       case GST_VIDEO_FORMAT_Y41B:
1439         fourcc = V4L2_PIX_FMT_YUV411P;
1440         break;
1441       case GST_VIDEO_FORMAT_Y42B:
1442         fourcc = V4L2_PIX_FMT_YUV422P;
1443         break;
1444       case GST_VIDEO_FORMAT_NV12:
1445         fourcc = V4L2_PIX_FMT_NV12;
1446         fourcc_nc = V4L2_PIX_FMT_NV12M;
1447         break;
1448       case GST_VIDEO_FORMAT_NV12_64Z32:
1449         fourcc_nc = V4L2_PIX_FMT_NV12MT;
1450         break;
1451       case GST_VIDEO_FORMAT_NV21:
1452         fourcc = V4L2_PIX_FMT_NV21;
1453         fourcc_nc = V4L2_PIX_FMT_NV21M;
1454         break;
1455       case GST_VIDEO_FORMAT_YVYU:
1456         fourcc = V4L2_PIX_FMT_YVYU;
1457         break;
1458       case GST_VIDEO_FORMAT_RGB15:
1459         fourcc = V4L2_PIX_FMT_RGB555;
1460         break;
1461       case GST_VIDEO_FORMAT_RGB16:
1462         fourcc = V4L2_PIX_FMT_RGB565;
1463         break;
1464       case GST_VIDEO_FORMAT_RGB:
1465         fourcc = V4L2_PIX_FMT_RGB24;
1466         break;
1467       case GST_VIDEO_FORMAT_BGR:
1468         fourcc = V4L2_PIX_FMT_BGR24;
1469         break;
1470       case GST_VIDEO_FORMAT_xRGB:
1471       case GST_VIDEO_FORMAT_ARGB:
1472         fourcc = V4L2_PIX_FMT_RGB32;
1473         break;
1474       case GST_VIDEO_FORMAT_BGRx:
1475       case GST_VIDEO_FORMAT_BGRA:
1476         fourcc = V4L2_PIX_FMT_BGR32;
1477         break;
1478       case GST_VIDEO_FORMAT_GRAY8:
1479         fourcc = V4L2_PIX_FMT_GREY;
1480       default:
1481         break;
1482     }
1483   } else {
1484     if (g_str_equal (mimetype, "video/mpegts")) {
1485       fourcc = V4L2_PIX_FMT_MPEG;
1486     } else if (g_str_equal (mimetype, "video/x-dv")) {
1487       fourcc = V4L2_PIX_FMT_DV;
1488     } else if (g_str_equal (mimetype, "image/jpeg")) {
1489       fourcc = V4L2_PIX_FMT_JPEG;
1490     } else if (g_str_equal (mimetype, "video/mpeg")) {
1491       gint version;
1492       if (gst_structure_get_int (structure, "mpegversion", &version)) {
1493         switch (version) {
1494           case 1:
1495             fourcc = V4L2_PIX_FMT_MPEG1;
1496             break;
1497           case 2:
1498             fourcc = V4L2_PIX_FMT_MPEG2;
1499             break;
1500           case 4:
1501             fourcc = V4L2_PIX_FMT_MPEG4;
1502             break;
1503           default:
1504             break;
1505         }
1506       }
1507     } else if (g_str_equal (mimetype, "video/x-h263")) {
1508       fourcc = V4L2_PIX_FMT_H263;
1509     } else if (g_str_equal (mimetype, "video/x-h264")) {
1510       fourcc = V4L2_PIX_FMT_H264;
1511     } else if (g_str_equal (mimetype, "video/x-vp8")) {
1512       fourcc = V4L2_PIX_FMT_VP8;
1513     } else if (g_str_equal (mimetype, "video/x-bayer")) {
1514       fourcc = V4L2_PIX_FMT_SBGGR8;
1515     } else if (g_str_equal (mimetype, "video/x-sonix")) {
1516       fourcc = V4L2_PIX_FMT_SN9C10X;
1517     } else if (g_str_equal (mimetype, "video/x-pwc1")) {
1518       fourcc = V4L2_PIX_FMT_PWC1;
1519     } else if (g_str_equal (mimetype, "video/x-pwc2")) {
1520       fourcc = V4L2_PIX_FMT_PWC2;
1521     }
1522   }
1523
1524
1525   /* Prefer the non-contiguous if supported */
1526   v4l2object->prefered_non_contiguous = TRUE;
1527
1528   if (fourcc_nc)
1529     fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc_nc);
1530   else if (fourcc == 0)
1531     goto unhandled_format;
1532
1533   if (fmt == NULL) {
1534     fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1535     v4l2object->prefered_non_contiguous = FALSE;
1536   }
1537
1538   if (fmt == NULL)
1539     goto unsupported_format;
1540
1541   *format = fmt;
1542
1543   return TRUE;
1544
1545   /* ERRORS */
1546 invalid_format:
1547   {
1548     GST_DEBUG_OBJECT (v4l2object, "invalid format");
1549     return FALSE;
1550   }
1551 unhandled_format:
1552   {
1553     GST_DEBUG_OBJECT (v4l2object, "unhandled format");
1554     return FALSE;
1555   }
1556 unsupported_format:
1557   {
1558     GST_DEBUG_OBJECT (v4l2object, "unsupported format");
1559     return FALSE;
1560   }
1561 }
1562
1563 static gboolean
1564 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1565     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced);
1566
1567 static void
1568 gst_v4l2_object_add_aspect_ratio (GstV4l2Object * v4l2object, GstStructure * s)
1569 {
1570   struct v4l2_cropcap cropcap;
1571   int num = 1, den = 1;
1572
1573   if (!v4l2object->keep_aspect)
1574     return;
1575
1576   if (v4l2object->par) {
1577     num = gst_value_get_fraction_numerator (v4l2object->par);
1578     den = gst_value_get_fraction_denominator (v4l2object->par);
1579     goto done;
1580   }
1581
1582   memset (&cropcap, 0, sizeof (cropcap));
1583
1584   cropcap.type = v4l2object->type;
1585   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_CROPCAP, &cropcap) < 0)
1586     goto cropcap_failed;
1587
1588   num = cropcap.pixelaspect.numerator;
1589   den = cropcap.pixelaspect.denominator;
1590
1591   /* Ignore PAR that are 0/0 */
1592   if (den == 0)
1593     return;
1594
1595 done:
1596   gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION, num, den,
1597       NULL);
1598   return;
1599
1600 cropcap_failed:
1601   if (errno != ENOTTY)
1602     GST_WARNING_OBJECT (v4l2object->element,
1603         "Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: %s",
1604         g_strerror (errno));
1605   goto done;
1606 }
1607
1608 /* returns TRUE if the value was changed in place, otherwise FALSE */
1609 static gboolean
1610 gst_v4l2src_value_simplify (GValue * val)
1611 {
1612   /* simplify list of one value to one value */
1613   if (GST_VALUE_HOLDS_LIST (val) && gst_value_list_get_size (val) == 1) {
1614     const GValue *list_val;
1615     GValue new_val = G_VALUE_INIT;
1616
1617     list_val = gst_value_list_get_value (val, 0);
1618     g_value_init (&new_val, G_VALUE_TYPE (list_val));
1619     g_value_copy (list_val, &new_val);
1620     g_value_unset (val);
1621     *val = new_val;
1622     return TRUE;
1623   }
1624
1625   return FALSE;
1626 }
1627
1628 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1629 static GstStructure *
1630 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1631     guint32 pixelformat,
1632     guint32 width, guint32 height, const GstStructure * template)
1633 {
1634   gint fd = v4l2object->video_fd;
1635   struct v4l2_frmivalenum ival;
1636   guint32 num, denom;
1637   GstStructure *s;
1638   GValue rates = { 0, };
1639   gboolean interlaced;
1640   gint int_width = width;
1641   gint int_height = height;
1642
1643   if (v4l2object->never_interlaced) {
1644     interlaced = FALSE;
1645   } else {
1646     /* Interlaced detection using VIDIOC_TRY/S_FMT */
1647     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat,
1648             &int_width, &int_height, &interlaced))
1649       return NULL;
1650   }
1651
1652   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1653   ival.index = 0;
1654   ival.pixel_format = pixelformat;
1655   ival.width = width;
1656   ival.height = height;
1657
1658   GST_LOG_OBJECT (v4l2object->element,
1659       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1660       GST_FOURCC_ARGS (pixelformat));
1661
1662   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1663    * fraction to get framerate */
1664   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1665     goto enum_frameintervals_failed;
1666
1667   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1668     GValue rate = { 0, };
1669
1670     g_value_init (&rates, GST_TYPE_LIST);
1671     g_value_init (&rate, GST_TYPE_FRACTION);
1672
1673     do {
1674       num = ival.discrete.numerator;
1675       denom = ival.discrete.denominator;
1676
1677       if (num > G_MAXINT || denom > G_MAXINT) {
1678         /* let us hope we don't get here... */
1679         num >>= 1;
1680         denom >>= 1;
1681       }
1682
1683       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1684           denom, num);
1685
1686       /* swap to get the framerate */
1687       gst_value_set_fraction (&rate, denom, num);
1688       gst_value_list_append_value (&rates, &rate);
1689
1690       ival.index++;
1691     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1692   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1693     GValue min = { 0, };
1694     GValue step = { 0, };
1695     GValue max = { 0, };
1696     gboolean added = FALSE;
1697     guint32 minnum, mindenom;
1698     guint32 maxnum, maxdenom;
1699
1700     g_value_init (&rates, GST_TYPE_LIST);
1701
1702     g_value_init (&min, GST_TYPE_FRACTION);
1703     g_value_init (&step, GST_TYPE_FRACTION);
1704     g_value_init (&max, GST_TYPE_FRACTION);
1705
1706     /* get the min */
1707     minnum = ival.stepwise.min.numerator;
1708     mindenom = ival.stepwise.min.denominator;
1709     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1710       minnum >>= 1;
1711       mindenom >>= 1;
1712     }
1713     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1714         minnum, mindenom);
1715     gst_value_set_fraction (&min, minnum, mindenom);
1716
1717     /* get the max */
1718     maxnum = ival.stepwise.max.numerator;
1719     maxdenom = ival.stepwise.max.denominator;
1720     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1721       maxnum >>= 1;
1722       maxdenom >>= 1;
1723     }
1724
1725     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1726         maxnum, maxdenom);
1727     gst_value_set_fraction (&max, maxnum, maxdenom);
1728
1729     /* get the step */
1730     num = ival.stepwise.step.numerator;
1731     denom = ival.stepwise.step.denominator;
1732     if (num > G_MAXINT || denom > G_MAXINT) {
1733       num >>= 1;
1734       denom >>= 1;
1735     }
1736
1737     if (num == 0 || denom == 0) {
1738       /* in this case we have a wrong fraction or no step, set the step to max
1739        * so that we only add the min value in the loop below */
1740       num = maxnum;
1741       denom = maxdenom;
1742     }
1743
1744     /* since we only have gst_value_fraction_subtract and not add, negate the
1745      * numerator */
1746     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1747         num, denom);
1748     gst_value_set_fraction (&step, -num, denom);
1749
1750     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
1751       GValue rate = { 0, };
1752
1753       num = gst_value_get_fraction_numerator (&min);
1754       denom = gst_value_get_fraction_denominator (&min);
1755       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1756           denom, num);
1757
1758       /* invert to get the framerate */
1759       g_value_init (&rate, GST_TYPE_FRACTION);
1760       gst_value_set_fraction (&rate, denom, num);
1761       gst_value_list_append_value (&rates, &rate);
1762       added = TRUE;
1763
1764       /* we're actually adding because step was negated above. This is because
1765        * there is no _add function... */
1766       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1767         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1768         break;
1769       }
1770     }
1771     if (!added) {
1772       /* no range was added, leave the default range from the template */
1773       GST_WARNING_OBJECT (v4l2object->element,
1774           "no range added, leaving default");
1775       g_value_unset (&rates);
1776     }
1777   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1778     guint32 maxnum, maxdenom;
1779
1780     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1781
1782     num = ival.stepwise.min.numerator;
1783     denom = ival.stepwise.min.denominator;
1784     if (num > G_MAXINT || denom > G_MAXINT) {
1785       num >>= 1;
1786       denom >>= 1;
1787     }
1788
1789     maxnum = ival.stepwise.max.numerator;
1790     maxdenom = ival.stepwise.max.denominator;
1791     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1792       maxnum >>= 1;
1793       maxdenom >>= 1;
1794     }
1795
1796     GST_LOG_OBJECT (v4l2object->element,
1797         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1798         num);
1799
1800     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1801   } else {
1802     goto unknown_type;
1803   }
1804
1805 return_data:
1806   s = gst_structure_copy (template);
1807   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1808       "height", G_TYPE_INT, (gint) height, NULL);
1809   gst_v4l2_object_add_aspect_ratio (v4l2object, s);
1810   if (g_str_equal (gst_structure_get_name (s), "video/x-raw"))
1811     gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
1812         (interlaced ? "mixed" : "progressive"), NULL);
1813
1814   if (G_IS_VALUE (&rates)) {
1815     gst_v4l2src_value_simplify (&rates);
1816     /* only change the framerate on the template when we have a valid probed new
1817      * value */
1818     gst_structure_take_value (s, "framerate", &rates);
1819   } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1820       v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
1821     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1822         NULL);
1823   }
1824   return s;
1825
1826   /* ERRORS */
1827 enum_frameintervals_failed:
1828   {
1829     GST_DEBUG_OBJECT (v4l2object->element,
1830         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1831         GST_FOURCC_ARGS (pixelformat), width, height);
1832     goto return_data;
1833   }
1834 unknown_type:
1835   {
1836     /* I don't see how this is actually an error, we ignore the format then */
1837     GST_WARNING_OBJECT (v4l2object->element,
1838         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1839         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1840     return NULL;
1841   }
1842 }
1843
1844 static gint
1845 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1846 {
1847   int w1, h1, w2, h2;
1848
1849   gst_structure_get_int (s1, "width", &w1);
1850   gst_structure_get_int (s1, "height", &h1);
1851   gst_structure_get_int (s2, "width", &w2);
1852   gst_structure_get_int (s2, "height", &h2);
1853
1854   /* I think it's safe to assume that this won't overflow for a while */
1855   return ((w2 * h2) - (w1 * h1));
1856 }
1857
1858 static void
1859 gst_v4l2_object_update_and_append (GstV4l2Object * v4l2object,
1860     guint32 format, GstCaps * caps, GstStructure * s)
1861 {
1862   GstStructure *alt_s = NULL;
1863
1864   /* Encoded stream on output buffer need to be parsed */
1865   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT ||
1866       v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
1867     gint i = 0;
1868
1869     for (; i < GST_V4L2_FORMAT_COUNT; i++) {
1870       if (format == gst_v4l2_formats[i].format &&
1871           gst_v4l2_formats[i].flags & GST_V4L2_CODEC &&
1872           !(gst_v4l2_formats[i].flags & GST_V4L2_NO_PARSE)) {
1873         gst_structure_set (s, "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
1874         break;
1875       }
1876     }
1877   }
1878
1879   if (v4l2object->has_alpha_component &&
1880       (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1881           v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
1882     switch (format) {
1883       case V4L2_PIX_FMT_RGB32:
1884         alt_s = gst_structure_copy (s);
1885         gst_structure_set (alt_s, "format", G_TYPE_STRING, "ARGB", NULL);
1886         break;
1887       case V4L2_PIX_FMT_BGR32:
1888         alt_s = gst_structure_copy (s);
1889         gst_structure_set (alt_s, "format", G_TYPE_STRING, "BGRA", NULL);
1890         break;
1891       default:
1892         break;
1893     }
1894   }
1895
1896   gst_caps_append_structure (caps, s);
1897
1898   if (alt_s)
1899     gst_caps_append_structure (caps, alt_s);
1900 }
1901
1902 static GstCaps *
1903 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
1904     guint32 pixelformat, const GstStructure * template)
1905 {
1906   GstCaps *ret = gst_caps_new_empty ();
1907   GstStructure *tmp;
1908   gint fd = v4l2object->video_fd;
1909   struct v4l2_frmsizeenum size;
1910   GList *results = NULL;
1911   guint32 w, h;
1912
1913   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')) {
1914     gst_caps_append_structure (ret, gst_structure_copy (template));
1915     return ret;
1916   }
1917
1918   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
1919   size.index = 0;
1920   size.pixel_format = pixelformat;
1921
1922   GST_DEBUG_OBJECT (v4l2object->element,
1923       "Enumerating frame sizes for %" GST_FOURCC_FORMAT,
1924       GST_FOURCC_ARGS (pixelformat));
1925
1926   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
1927     goto enum_framesizes_failed;
1928
1929   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
1930     do {
1931       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
1932           size.discrete.width, size.discrete.height);
1933
1934       w = MIN (size.discrete.width, G_MAXINT);
1935       h = MIN (size.discrete.height, G_MAXINT);
1936
1937       if (w && h) {
1938         tmp =
1939             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1940             pixelformat, w, h, template);
1941
1942         if (tmp)
1943           results = g_list_prepend (results, tmp);
1944       }
1945
1946       size.index++;
1947     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
1948     GST_DEBUG_OBJECT (v4l2object->element,
1949         "done iterating discrete frame sizes");
1950   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
1951     guint32 maxw, maxh, step_w, step_h;
1952
1953     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
1954     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1955         size.stepwise.min_width);
1956     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1957         size.stepwise.min_height);
1958     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1959         size.stepwise.max_width);
1960     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1961         size.stepwise.max_height);
1962     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
1963         size.stepwise.step_width);
1964     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
1965         size.stepwise.step_height);
1966
1967     w = MAX (size.stepwise.min_width, 1);
1968     h = MAX (size.stepwise.min_height, 1);
1969     maxw = MIN (size.stepwise.max_width, G_MAXINT);
1970     maxh = MIN (size.stepwise.max_height, G_MAXINT);
1971
1972     step_w = MAX (size.stepwise.step_width, 1);
1973     step_h = MAX (size.stepwise.step_height, 1);
1974
1975     /* FIXME: check for sanity and that min/max are multiples of the steps */
1976
1977     /* we only query details for the max width/height since it's likely the
1978      * most restricted if there are any resolution-dependent restrictions */
1979     tmp = gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1980         pixelformat, maxw, maxh, template);
1981
1982     if (tmp) {
1983       GValue step_range = G_VALUE_INIT;
1984
1985       g_value_init (&step_range, GST_TYPE_INT_RANGE);
1986       gst_value_set_int_range_step (&step_range, w, maxw, step_w);
1987       gst_structure_set_value (tmp, "width", &step_range);
1988
1989       gst_value_set_int_range_step (&step_range, h, maxh, step_h);
1990       gst_structure_take_value (tmp, "height", &step_range);
1991
1992       /* no point using the results list here, since there's only one struct */
1993       gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
1994     }
1995   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
1996     guint32 maxw, maxh;
1997
1998     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
1999     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
2000         size.stepwise.min_width);
2001     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2002         size.stepwise.min_height);
2003     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
2004         size.stepwise.max_width);
2005     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2006         size.stepwise.max_height);
2007
2008     w = MAX (size.stepwise.min_width, 1);
2009     h = MAX (size.stepwise.min_height, 1);
2010     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2011     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2012
2013     tmp =
2014         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
2015         w, h, template);
2016     if (tmp) {
2017       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
2018           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
2019           NULL);
2020
2021       /* no point using the results list here, since there's only one struct */
2022       gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2023     }
2024   } else {
2025     goto unknown_type;
2026   }
2027
2028   /* we use an intermediary list to store and then sort the results of the
2029    * probing because we can't make any assumptions about the order in which
2030    * the driver will give us the sizes, but we want the final caps to contain
2031    * the results starting with the highest resolution and having the lowest
2032    * resolution last, since order in caps matters for things like fixation. */
2033   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
2034   while (results != NULL) {
2035     gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret,
2036         results->data);
2037     results = g_list_delete_link (results, results);
2038   }
2039
2040   if (gst_caps_is_empty (ret))
2041     goto enum_framesizes_no_results;
2042
2043   return ret;
2044
2045   /* ERRORS */
2046 enum_framesizes_failed:
2047   {
2048     /* I don't see how this is actually an error */
2049     GST_DEBUG_OBJECT (v4l2object->element,
2050         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
2051         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
2052     goto default_frame_sizes;
2053   }
2054 enum_framesizes_no_results:
2055   {
2056     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
2057      * question doesn't actually support it yet */
2058     GST_DEBUG_OBJECT (v4l2object->element,
2059         "No results for pixelformat %" GST_FOURCC_FORMAT
2060         " enumerating frame sizes, trying fallback",
2061         GST_FOURCC_ARGS (pixelformat));
2062     goto default_frame_sizes;
2063   }
2064 unknown_type:
2065   {
2066     GST_WARNING_OBJECT (v4l2object->element,
2067         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
2068         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
2069     goto default_frame_sizes;
2070   }
2071
2072 default_frame_sizes:
2073   {
2074     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
2075     gboolean interlaced;
2076
2077     /* This code is for Linux < 2.6.19 */
2078     min_w = min_h = 1;
2079     max_w = max_h = GST_V4L2_MAX_SIZE;
2080     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
2081             &min_h, &interlaced)) {
2082       GST_WARNING_OBJECT (v4l2object->element,
2083           "Could not probe minimum capture size for pixelformat %"
2084           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2085     }
2086     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
2087             &max_h, &interlaced)) {
2088       GST_WARNING_OBJECT (v4l2object->element,
2089           "Could not probe maximum capture size for pixelformat %"
2090           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2091     }
2092
2093     /* Since we can't get framerate directly, try to use the current norm */
2094     if (v4l2object->tv_norm && v4l2object->norms) {
2095       GList *norms;
2096       GstTunerNorm *norm = NULL;
2097       GstTunerNorm *current =
2098           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
2099
2100       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
2101         norm = (GstTunerNorm *) norms->data;
2102         if (!strcmp (norm->label, current->label))
2103           break;
2104       }
2105       /* If it's possible, set framerate to that (discrete) value */
2106       if (norm) {
2107         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
2108         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
2109       }
2110     }
2111
2112     tmp = gst_structure_copy (template);
2113     if (fix_num) {
2114       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
2115           fix_denom, NULL);
2116     } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2117         v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
2118       /* if norm can't be used, copy the template framerate */
2119       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
2120           100, 1, NULL);
2121     }
2122
2123     if (min_w == max_w)
2124       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
2125     else
2126       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
2127
2128     if (min_h == max_h)
2129       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
2130     else
2131       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
2132
2133     if (g_str_equal (gst_structure_get_name (tmp), "video/x-raw"))
2134       gst_structure_set (tmp, "interlace-mode", G_TYPE_STRING,
2135           (interlaced ? "mixed" : "progressive"), NULL);
2136     gst_v4l2_object_add_aspect_ratio (v4l2object, tmp);
2137
2138     gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2139     return ret;
2140   }
2141 }
2142
2143 static gboolean
2144 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
2145     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced)
2146 {
2147   struct v4l2_format fmt;
2148   int fd;
2149   int r;
2150   gboolean ret = FALSE;
2151
2152   g_return_val_if_fail (width != NULL, FALSE);
2153   g_return_val_if_fail (height != NULL, FALSE);
2154
2155   GST_LOG_OBJECT (v4l2object->element,
2156       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2157       *width, *height, GST_FOURCC_ARGS (pixelformat));
2158
2159   fd = v4l2object->video_fd;
2160
2161   memset (&fmt, 0, sizeof (struct v4l2_format));
2162
2163   /* get size delimiters */
2164   memset (&fmt, 0, sizeof (fmt));
2165   fmt.type = v4l2object->type;
2166   fmt.fmt.pix.width = *width;
2167   fmt.fmt.pix.height = *height;
2168   fmt.fmt.pix.pixelformat = pixelformat;
2169   fmt.fmt.pix.field = V4L2_FIELD_NONE;
2170
2171   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2172   if (r < 0 && errno == EINVAL) {
2173     /* try again with interlaced video */
2174     fmt.fmt.pix.width = *width;
2175     fmt.fmt.pix.height = *height;
2176     fmt.fmt.pix.pixelformat = pixelformat;
2177     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2178     r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2179   }
2180
2181   if (r < 0) {
2182     /* The driver might not implement TRY_FMT, in which case we will try
2183        S_FMT to probe */
2184     if (errno != ENOTTY)
2185       goto error;
2186
2187     /* Only try S_FMT if we're not actively capturing yet, which we shouldn't
2188        be, because we're still probing */
2189     if (GST_V4L2_IS_ACTIVE (v4l2object))
2190       goto error;
2191
2192     GST_LOG_OBJECT (v4l2object->element,
2193         "Failed to probe size limit with VIDIOC_TRY_FMT, trying VIDIOC_S_FMT");
2194
2195     fmt.fmt.pix.width = *width;
2196     fmt.fmt.pix.height = *height;
2197
2198     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2199     if (r < 0 && errno == EINVAL) {
2200       /* try again with progressive video */
2201       fmt.fmt.pix.width = *width;
2202       fmt.fmt.pix.height = *height;
2203       fmt.fmt.pix.pixelformat = pixelformat;
2204       fmt.fmt.pix.field = V4L2_FIELD_NONE;
2205       r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2206     }
2207
2208     if (r < 0)
2209       goto error;
2210   }
2211
2212   GST_LOG_OBJECT (v4l2object->element,
2213       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2214
2215   *width = fmt.fmt.pix.width;
2216   *height = fmt.fmt.pix.height;
2217
2218   switch (fmt.fmt.pix.field) {
2219     case V4L2_FIELD_ANY:
2220     case V4L2_FIELD_NONE:
2221       *interlaced = FALSE;
2222       break;
2223     case V4L2_FIELD_INTERLACED:
2224     case V4L2_FIELD_INTERLACED_TB:
2225     case V4L2_FIELD_INTERLACED_BT:
2226       *interlaced = TRUE;
2227       break;
2228     default:
2229       GST_WARNING_OBJECT (v4l2object->element,
2230           "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u",
2231           GST_FOURCC_ARGS (pixelformat), *width, *height);
2232       goto error;
2233   }
2234
2235   ret = TRUE;
2236
2237 error:
2238   if (!ret) {
2239     GST_WARNING_OBJECT (v4l2object->element,
2240         "Unable to try format: %s", g_strerror (errno));
2241   }
2242
2243   return ret;
2244 }
2245
2246 static gboolean
2247 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
2248 {
2249   GstV4l2IOMode mode;
2250
2251   GST_DEBUG_OBJECT (v4l2object->element, "initializing the %s system",
2252       V4L2_TYPE_IS_OUTPUT (v4l2object->type) ? "output" : "capture");
2253
2254   GST_V4L2_CHECK_OPEN (v4l2object);
2255   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2256
2257   /* find transport */
2258   mode = v4l2object->req_mode;
2259
2260   if (v4l2object->vcap.capabilities & V4L2_CAP_READWRITE) {
2261     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2262       mode = GST_V4L2_IO_RW;
2263   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
2264     goto method_not_supported;
2265
2266   if (v4l2object->vcap.capabilities & V4L2_CAP_STREAMING) {
2267     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2268       mode = GST_V4L2_IO_MMAP;
2269   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP)
2270     goto method_not_supported;
2271
2272   /* if still no transport selected, error out */
2273   if (mode == GST_V4L2_IO_AUTO)
2274     goto no_supported_capture_method;
2275
2276   GST_INFO_OBJECT (v4l2object->element, "accessing buffers via mode %d", mode);
2277   v4l2object->mode = mode;
2278
2279   /* Map the buffers */
2280   GST_LOG_OBJECT (v4l2object->element, "initiating buffer pool");
2281
2282   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
2283     goto buffer_pool_new_failed;
2284
2285   GST_V4L2_SET_ACTIVE (v4l2object);
2286
2287   return TRUE;
2288
2289   /* ERRORS */
2290 buffer_pool_new_failed:
2291   {
2292     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2293         (_("Could not map buffers from device '%s'"),
2294             v4l2object->videodev),
2295         ("Failed to create buffer pool: %s", g_strerror (errno)));
2296     return FALSE;
2297   }
2298 method_not_supported:
2299   {
2300     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2301         (_("The driver of device '%s' does not support the IO method %d"),
2302             v4l2object->videodev, mode), (NULL));
2303     return FALSE;
2304   }
2305 no_supported_capture_method:
2306   {
2307     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2308         (_("The driver of device '%s' does not support any known IO "
2309                 "method."), v4l2object->videodev), (NULL));
2310     return FALSE;
2311   }
2312 }
2313
2314 static void
2315 gst_v4l2_object_set_stride (GstVideoInfo * info, GstVideoAlignment * align,
2316     gint plane, gint stride)
2317 {
2318   const GstVideoFormatInfo *finfo = info->finfo;
2319
2320   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
2321     gint x_tiles, y_tiles, ws, hs, tile_height, padded_height;
2322
2323
2324     ws = GST_VIDEO_FORMAT_INFO_TILE_WS (finfo);
2325     hs = GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
2326     tile_height = 1 << hs;
2327
2328     padded_height = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, plane,
2329         info->height + align->padding_top + align->padding_bottom);
2330     padded_height = GST_ROUND_UP_N (padded_height, tile_height);
2331
2332     x_tiles = stride >> ws;
2333     y_tiles = padded_height >> hs;
2334     info->stride[plane] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
2335   } else {
2336     info->stride[plane] = stride;
2337   }
2338 }
2339
2340 static void
2341 gst_v4l2_object_extrapolate_info (GstV4l2Object * v4l2object,
2342     GstVideoInfo * info, GstVideoAlignment * align, gint stride)
2343 {
2344   const GstVideoFormatInfo *finfo = info->finfo;
2345   gint i, estride, padded_height;
2346   gsize offs = 0;
2347
2348   g_return_if_fail (v4l2object->n_v4l2_planes == 1);
2349
2350   padded_height = info->height + align->padding_top + align->padding_bottom;
2351
2352   for (i = 0; i < finfo->n_planes; i++) {
2353     switch (finfo->format) {
2354       case GST_VIDEO_FORMAT_NV12:
2355       case GST_VIDEO_FORMAT_NV12_64Z32:
2356       case GST_VIDEO_FORMAT_NV21:
2357       case GST_VIDEO_FORMAT_NV16:
2358       case GST_VIDEO_FORMAT_NV24:
2359         estride = (i == 0 ? 1 : 2) *
2360             GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, stride);
2361         break;
2362       default:
2363         estride = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, stride);
2364         break;
2365     }
2366
2367     gst_v4l2_object_set_stride (info, align, i, estride);
2368
2369     info->offset[i] = offs;
2370     offs += estride *
2371         GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, padded_height);
2372
2373     GST_DEBUG_OBJECT (v4l2object->element,
2374         "Extrapolated for plane %d with base stride %d: "
2375         "stride %d, offset %" G_GSIZE_FORMAT, i, stride, info->stride[i],
2376         info->offset[i]);
2377   }
2378 }
2379
2380 static void
2381 gst_v4l2_object_save_format (GstV4l2Object * v4l2object,
2382     struct v4l2_fmtdesc *fmtdesc, struct v4l2_format *format,
2383     GstVideoInfo * info, GstVideoAlignment * align)
2384 {
2385   const GstVideoFormatInfo *finfo = info->finfo;
2386   gboolean standard_stride = TRUE;
2387   gint stride, padded_width, padded_height, i;
2388
2389   if (GST_VIDEO_INFO_FORMAT (info) == GST_VIDEO_FORMAT_ENCODED) {
2390     v4l2object->n_v4l2_planes = 1;
2391     info->size = format->fmt.pix.sizeimage;
2392     goto store_info;
2393   }
2394
2395   /* adjust right padding */
2396   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
2397     stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
2398   else
2399     stride = format->fmt.pix.bytesperline;
2400
2401   padded_width = stride / GST_VIDEO_FORMAT_INFO_PSTRIDE (finfo, 0);
2402
2403   if (padded_width < format->fmt.pix.width)
2404     GST_WARNING_OBJECT (v4l2object->element,
2405         "Driver bug detected, stride is too small for the width");
2406
2407   align->padding_right = padded_width - info->width - align->padding_left;
2408
2409   /* adjust bottom padding */
2410   padded_height = format->fmt.pix.height;
2411
2412   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
2413     guint hs, tile_height;
2414
2415     hs = GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
2416     tile_height = 1 << hs;
2417
2418     padded_height = GST_ROUND_UP_N (padded_height, tile_height);
2419   }
2420
2421   align->padding_bottom = padded_height - info->height - align->padding_top;
2422
2423   /* setup the strides and offset */
2424   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type)) {
2425     struct v4l2_pix_format_mplane *pix_mp = &format->fmt.pix_mp;
2426
2427     /* figure out the frame layout */
2428     v4l2object->n_v4l2_planes = MAX (1, pix_mp->num_planes);
2429     info->size = 0;
2430     for (i = 0; i < v4l2object->n_v4l2_planes; i++) {
2431       stride = pix_mp->plane_fmt[i].bytesperline;
2432
2433       if (info->stride[i] != stride)
2434         standard_stride = FALSE;
2435
2436       gst_v4l2_object_set_stride (info, align, i, stride);
2437       info->offset[i] = info->size;
2438       info->size += pix_mp->plane_fmt[i].sizeimage;
2439     }
2440
2441     /* Extrapolate stride if planar format are being set in 1 v4l2 plane */
2442     if (v4l2object->n_v4l2_planes < finfo->n_planes) {
2443       stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
2444       gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
2445     }
2446   } else {
2447     /* only one plane in non-MPLANE mode */
2448     v4l2object->n_v4l2_planes = 1;
2449     info->size = format->fmt.pix.sizeimage;
2450     stride = format->fmt.pix.bytesperline;
2451
2452     if (info->stride[0] != stride)
2453       standard_stride = FALSE;
2454
2455     gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
2456   }
2457
2458   /* adjust the offset to take into account left and top */
2459   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
2460     if ((align->padding_left + align->padding_top) > 0)
2461       GST_WARNING_OBJECT (v4l2object->element,
2462           "Left and top padding is not permitted for tiled formats");
2463   } else {
2464     for (i = 0; i < finfo->n_planes; i++) {
2465       gint vedge, hedge;
2466
2467       /* FIXME we assume plane as component as this is true for all supported
2468        * format we support. */
2469
2470       hedge = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, align->padding_left);
2471       vedge = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, align->padding_top);
2472
2473       info->offset[i] += (vedge * info->stride[i]) +
2474           (hedge * GST_VIDEO_INFO_COMP_PSTRIDE (info, i));
2475     }
2476   }
2477
2478 store_info:
2479   GST_DEBUG_OBJECT (v4l2object->element, "Got sizeimage %" G_GSIZE_FORMAT,
2480       info->size);
2481
2482   /* to avoid copies we need video meta if top or left padding */
2483   v4l2object->need_video_meta =
2484       ((align->padding_top + align->padding_left) != 0);
2485
2486   /* ... or if stride is non "standard" */
2487   if (!standard_stride)
2488     v4l2object->need_video_meta = TRUE;
2489
2490   /* ... or also video meta if we use multiple, non-contiguous, planes */
2491   if (v4l2object->n_v4l2_planes > 1)
2492     v4l2object->need_video_meta = TRUE;
2493
2494   v4l2object->info = *info;
2495   v4l2object->align = *align;
2496   v4l2object->format = *format;
2497   v4l2object->fmtdesc = fmtdesc;
2498
2499   /* if we have a framerate pre-calculate duration */
2500   if (info->fps_n > 0 && info->fps_d > 0) {
2501     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, info->fps_d,
2502         info->fps_n);
2503   } else {
2504     v4l2object->duration = GST_CLOCK_TIME_NONE;
2505   }
2506 }
2507
2508 gboolean
2509 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps)
2510 {
2511   gint fd = v4l2object->video_fd;
2512   struct v4l2_format format;
2513   struct v4l2_streamparm streamparm;
2514   enum v4l2_field field;
2515   guint32 pixelformat;
2516   struct v4l2_fmtdesc *fmtdesc;
2517   GstVideoInfo info;
2518   GstVideoAlignment align;
2519   gint width, height, fps_n, fps_d;
2520   gint n_v4l_planes;
2521   gint i = 0;
2522   gboolean is_mplane, format_changed;
2523
2524   GST_V4L2_CHECK_OPEN (v4l2object);
2525   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2526
2527   is_mplane = V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type);
2528
2529   gst_video_info_init (&info);
2530   gst_video_alignment_reset (&align);
2531
2532   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
2533     goto invalid_caps;
2534
2535   pixelformat = fmtdesc->pixelformat;
2536   width = GST_VIDEO_INFO_WIDTH (&info);
2537   height = GST_VIDEO_INFO_HEIGHT (&info);
2538   fps_n = GST_VIDEO_INFO_FPS_N (&info);
2539   fps_d = GST_VIDEO_INFO_FPS_D (&info);
2540
2541   /* if encoded format (GST_VIDEO_INFO_N_PLANES return 0)
2542    * or if contiguous is prefered */
2543   n_v4l_planes = GST_VIDEO_INFO_N_PLANES (&info);
2544   if (!n_v4l_planes || !v4l2object->prefered_non_contiguous)
2545     n_v4l_planes = 1;
2546
2547   if (GST_VIDEO_INFO_IS_INTERLACED (&info)) {
2548     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2549     /* ideally we would differentiate between types of interlaced video
2550      * but there is not sufficient information in the caps..
2551      */
2552     field = V4L2_FIELD_INTERLACED;
2553   } else {
2554     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2555     field = V4L2_FIELD_NONE;
2556   }
2557
2558   GST_DEBUG_OBJECT (v4l2object->element, "Desired format %dx%d, format "
2559       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
2560       GST_FOURCC_ARGS (pixelformat), GST_VIDEO_INFO_PLANE_STRIDE (&info, 0));
2561
2562   memset (&format, 0x00, sizeof (struct v4l2_format));
2563   format.type = v4l2object->type;
2564
2565   if (v4l2object->no_initial_format) {
2566     format_changed = TRUE;
2567   } else {
2568     if (v4l2_ioctl (fd, VIDIOC_G_FMT, &format) < 0)
2569       goto get_fmt_failed;
2570
2571     /* Note that four first fields are the same between v4l2_pix_format and
2572      * v4l2_pix_format_mplane, so we don't need to duplicate he checks */
2573
2574     /* If no size in caps, use configured size */
2575     if (width == 0 && height == 0) {
2576       width = format.fmt.pix_mp.width;
2577       height = format.fmt.pix_mp.height;
2578     }
2579
2580     format_changed = format.type != v4l2object->type ||
2581         format.fmt.pix_mp.width != width ||
2582         format.fmt.pix_mp.height != height ||
2583         format.fmt.pix_mp.pixelformat != pixelformat ||
2584         format.fmt.pix_mp.field != field;
2585   }
2586
2587 #ifndef GST_DISABLE_GST_DEBUG
2588   if (is_mplane) {
2589     GST_DEBUG_OBJECT (v4l2object->element, "Current size is %dx%d, format "
2590         "%" GST_FOURCC_FORMAT " colorspace %d, nb planes %d",
2591         format.fmt.pix_mp.width, format.fmt.pix_mp.height,
2592         GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2593         format.fmt.pix_mp.colorspace, format.fmt.pix_mp.num_planes);
2594
2595     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
2596       GST_DEBUG_OBJECT (v4l2object->element, "  stride %d",
2597           format.fmt.pix_mp.plane_fmt[i].bytesperline);
2598   } else {
2599     GST_DEBUG_OBJECT (v4l2object->element, "Current size is %dx%d, format "
2600         "%" GST_FOURCC_FORMAT " stride %d, colorspace %d",
2601         format.fmt.pix.width, format.fmt.pix.height,
2602         GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2603         format.fmt.pix.bytesperline, format.fmt.pix.colorspace);
2604   }
2605 #endif
2606
2607   /* If nothing changed, we are done */
2608   if (!format_changed)
2609     goto done;
2610
2611   /* something different, set the format */
2612   GST_DEBUG_OBJECT (v4l2object->element, "Setting format to %dx%d, format "
2613       "%" GST_FOURCC_FORMAT, width, height, GST_FOURCC_ARGS (pixelformat));
2614
2615   if (is_mplane) {
2616     format.type = v4l2object->type;
2617     format.fmt.pix_mp.pixelformat = pixelformat;
2618     format.fmt.pix_mp.width = width;
2619     format.fmt.pix_mp.height = height;
2620     format.fmt.pix_mp.field = field;
2621     format.fmt.pix_mp.num_planes = n_v4l_planes;
2622
2623     /* try to ask our prefered stride but it's not a failure if not
2624      * accepted */
2625     for (i = 0; i < n_v4l_planes; i++) {
2626       gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, i);
2627
2628       if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
2629         stride = GST_VIDEO_TILE_X_TILES (stride) <<
2630             GST_VIDEO_FORMAT_INFO_TILE_WS (info.finfo);
2631
2632       format.fmt.pix_mp.plane_fmt[i].bytesperline = stride;
2633     }
2634
2635     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
2636       format.fmt.pix_mp.plane_fmt[0].sizeimage = ENCODED_BUFFER_SIZE;
2637   } else {
2638     gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
2639
2640     format.type = v4l2object->type;
2641     format.fmt.pix.width = width;
2642     format.fmt.pix.height = height;
2643     format.fmt.pix.pixelformat = pixelformat;
2644     format.fmt.pix.field = field;
2645
2646     if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
2647       stride = GST_VIDEO_TILE_X_TILES (stride) <<
2648           GST_VIDEO_FORMAT_INFO_TILE_WS (info.finfo);
2649
2650     /* try to ask our prefered stride */
2651     format.fmt.pix.bytesperline = stride;
2652
2653     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
2654       format.fmt.pix.sizeimage = ENCODED_BUFFER_SIZE;
2655   }
2656
2657   GST_DEBUG_OBJECT (v4l2object->element, "Desired format is %dx%d, format "
2658       "%" GST_FOURCC_FORMAT ", nb planes %d", format.fmt.pix.width,
2659       format.fmt.pix_mp.height,
2660       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2661       is_mplane ? format.fmt.pix_mp.num_planes : 1);
2662
2663 #ifndef GST_DISABLE_GST_DEBUG
2664   if (is_mplane) {
2665     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
2666       GST_DEBUG_OBJECT (v4l2object->element, "  stride %d",
2667           format.fmt.pix_mp.plane_fmt[i].bytesperline);
2668   } else {
2669     GST_DEBUG_OBJECT (v4l2object->element, "  stride %d",
2670         format.fmt.pix.bytesperline);
2671   }
2672 #endif
2673
2674   if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0)
2675     goto set_fmt_failed;
2676
2677   GST_DEBUG_OBJECT (v4l2object->element, "Got format of %dx%d, format "
2678       "%" GST_FOURCC_FORMAT ", nb planes %d", format.fmt.pix.width,
2679       format.fmt.pix_mp.height,
2680       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2681       is_mplane ? format.fmt.pix_mp.num_planes : 1);
2682
2683 #ifndef GST_DISABLE_GST_DEBUG
2684   if (is_mplane) {
2685     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
2686       GST_DEBUG_OBJECT (v4l2object->element, "  stride %d, sizeimage %d",
2687           format.fmt.pix_mp.plane_fmt[i].bytesperline,
2688           format.fmt.pix_mp.plane_fmt[i].sizeimage);
2689   } else {
2690     GST_DEBUG_OBJECT (v4l2object->element, "  stride %d, sizeimage %d",
2691         format.fmt.pix.bytesperline, format.fmt.pix.sizeimage);
2692   }
2693 #endif
2694
2695   if (format.fmt.pix.pixelformat != pixelformat)
2696     goto invalid_pixelformat;
2697
2698   /* Only negotiate size with raw data.
2699    * For some codecs the dimensions are *not* in the bitstream, IIRC VC1
2700    * in ASF mode for example, there is also not reason for a driver to
2701    * change the size. */
2702   if (info.finfo->format != GST_VIDEO_FORMAT_ENCODED) {
2703     /* We can crop larger images */
2704     if (format.fmt.pix.width < width || format.fmt.pix.height < height)
2705       goto invalid_dimensions;
2706
2707     /* Note, this will be adjusted if upstream has non-centered cropping. */
2708     align.padding_top = 0;
2709     align.padding_bottom = format.fmt.pix.height - height;
2710     align.padding_left = 0;
2711     align.padding_right = format.fmt.pix.width - width;
2712   }
2713
2714   if (is_mplane && format.fmt.pix_mp.num_planes != n_v4l_planes)
2715     goto invalid_planes;
2716
2717   if (GST_VIDEO_INFO_HAS_ALPHA (&info)) {
2718     struct v4l2_control ctl = { 0, };
2719     ctl.id = V4L2_CID_ALPHA_COMPONENT;
2720     ctl.value = 0xff;
2721
2722     if (v4l2_ioctl (fd, VIDIOC_S_CTRL, &ctl) < 0)
2723       GST_WARNING_OBJECT (v4l2object->element,
2724           "Failed to set alpha component value");
2725   }
2726
2727   /* Is there a reason we require the caller to always specify a framerate? */
2728   GST_DEBUG_OBJECT (v4l2object->element, "Desired framerate: %u/%u", fps_n,
2729       fps_d);
2730
2731   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2732   streamparm.type = v4l2object->type;
2733
2734   if (v4l2_ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
2735     goto get_parm_failed;
2736
2737   GST_VIDEO_INFO_FPS_N (&info) =
2738       streamparm.parm.capture.timeperframe.denominator;
2739   GST_VIDEO_INFO_FPS_D (&info) = streamparm.parm.capture.timeperframe.numerator;
2740
2741   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
2742       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
2743     GST_DEBUG_OBJECT (v4l2object->element, "Got framerate: %u/%u",
2744         streamparm.parm.capture.timeperframe.denominator,
2745         streamparm.parm.capture.timeperframe.numerator);
2746
2747     /* We used to skip frame rate setup if the camera was already setup
2748      * with the requested frame rate. This breaks some cameras though,
2749      * causing them to not output data (several models of Thinkpad cameras
2750      * have this problem at least).
2751      * So, don't skip. */
2752     GST_LOG_OBJECT (v4l2object->element, "Setting framerate to %u/%u", fps_n,
2753         fps_d);
2754     /* We want to change the frame rate, so check whether we can. Some cheap USB
2755      * cameras don't have the capability */
2756     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
2757       GST_DEBUG_OBJECT (v4l2object->element,
2758           "Not setting framerate (not supported)");
2759       goto done;
2760     }
2761
2762     /* Note: V4L2 wants the frame interval, we have the frame rate */
2763     streamparm.parm.capture.timeperframe.numerator = fps_d;
2764     streamparm.parm.capture.timeperframe.denominator = fps_n;
2765
2766     /* some cheap USB cam's won't accept any change */
2767     if (v4l2_ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
2768       goto set_parm_failed;
2769
2770     /* get new values */
2771     fps_d = streamparm.parm.capture.timeperframe.numerator;
2772     fps_n = streamparm.parm.capture.timeperframe.denominator;
2773
2774     GST_INFO_OBJECT (v4l2object->element, "Set framerate to %u/%u", fps_n,
2775         fps_d);
2776
2777     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
2778     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
2779   }
2780
2781 done:
2782   /* add boolean return, so we can fail on drivers bugs */
2783   gst_v4l2_object_save_format (v4l2object, fmtdesc, &format, &info, &align);
2784
2785   /* now configure the pool */
2786   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
2787     goto pool_failed;
2788
2789   return TRUE;
2790
2791   /* ERRORS */
2792 invalid_caps:
2793   {
2794     GST_DEBUG_OBJECT (v4l2object->element, "can't parse caps %" GST_PTR_FORMAT,
2795         caps);
2796     return FALSE;
2797   }
2798 get_fmt_failed:
2799   {
2800     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2801         (_("Device '%s' does not support video capture"),
2802             v4l2object->videodev),
2803         ("Call to G_FMT failed: (%s)", g_strerror (errno)));
2804     return FALSE;
2805   }
2806 set_fmt_failed:
2807   {
2808     if (errno == EBUSY) {
2809       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, BUSY,
2810           (_("Device '%s' is busy"), v4l2object->videodev),
2811           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2812               GST_FOURCC_ARGS (pixelformat), width, height,
2813               g_strerror (errno)));
2814     } else {
2815       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2816           (_("Device '%s' cannot capture at %dx%d"),
2817               v4l2object->videodev, width, height),
2818           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2819               GST_FOURCC_ARGS (pixelformat), width, height,
2820               g_strerror (errno)));
2821     }
2822     return FALSE;
2823   }
2824 invalid_dimensions:
2825   {
2826     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2827         (_("Device '%s' cannot capture at %dx%d"),
2828             v4l2object->videodev, width, height),
2829         ("Tried to capture at %dx%d, but device returned size %dx%d",
2830             width, height, format.fmt.pix.width, format.fmt.pix.height));
2831     return FALSE;
2832   }
2833 invalid_pixelformat:
2834   {
2835     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2836         (_("Device '%s' cannot capture in the specified format"),
2837             v4l2object->videodev),
2838         ("Tried to capture in %" GST_FOURCC_FORMAT
2839             ", but device returned format" " %" GST_FOURCC_FORMAT,
2840             GST_FOURCC_ARGS (pixelformat),
2841             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2842     return FALSE;
2843   }
2844 invalid_planes:
2845   {
2846     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2847         (_("Device '%s' does support non-contiguous planes"),
2848             v4l2object->videodev),
2849         ("Device wants %d planes", format.fmt.pix_mp.num_planes));
2850     return FALSE;
2851   }
2852 get_parm_failed:
2853   {
2854     /* it's possible that this call is not supported */
2855     if (errno != EINVAL && errno != ENOTTY) {
2856       GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2857           (_("Could not get parameters on device '%s'"),
2858               v4l2object->videodev), GST_ERROR_SYSTEM);
2859     }
2860     goto done;
2861   }
2862 set_parm_failed:
2863   {
2864     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2865         (_("Video device did not accept new frame rate setting.")),
2866         GST_ERROR_SYSTEM);
2867     goto done;
2868   }
2869 pool_failed:
2870   {
2871     /* setup_pool already send the error */
2872     return FALSE;
2873   }
2874 }
2875
2876 /**
2877  * gst_v4l2_object_acquire_format:
2878  * @v4l2object the object
2879  * @info a GstVideoInfo to be filled
2880  *
2881  * Acquire the driver choosen format. This is useful in decoder or encoder elements where
2882  * the output format is choosen by the HW.
2883  *
2884  * Returns: %TRUE on success, %FALSE on failure.
2885  */
2886 gboolean
2887 gst_v4l2_object_acquire_format (GstV4l2Object * v4l2object, GstVideoInfo * info)
2888 {
2889   struct v4l2_fmtdesc *fmtdesc;
2890   struct v4l2_format fmt;
2891   struct v4l2_crop crop;
2892   GstVideoFormat format;
2893   guint width, height;
2894   GstVideoAlignment align;
2895
2896   gst_video_info_init (info);
2897   gst_video_alignment_reset (&align);
2898
2899   memset (&fmt, 0x00, sizeof (struct v4l2_format));
2900   fmt.type = v4l2object->type;
2901   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_G_FMT, &fmt) < 0)
2902     goto get_fmt_failed;
2903
2904   fmtdesc = gst_v4l2_object_get_format_from_fourcc (v4l2object,
2905       fmt.fmt.pix.pixelformat);
2906   if (fmtdesc == NULL)
2907     goto unsupported_format;
2908
2909   /* No need to care about mplane, the four first params are the same */
2910   format = gst_v4l2_object_v4l2fourcc_to_video_format (fmt.fmt.pix.pixelformat);
2911
2912   /* fails if we do no translate the fmt.pix.pixelformat to GstVideoFormat */
2913   if (format == GST_VIDEO_FORMAT_UNKNOWN)
2914     goto unsupported_format;
2915
2916   if (fmt.fmt.pix.width == 0 || fmt.fmt.pix.height == 0)
2917     goto invalid_dimensions;
2918
2919   width = fmt.fmt.pix.width;
2920   height = fmt.fmt.pix.height;
2921
2922   memset (&crop, 0, sizeof (struct v4l2_crop));
2923   crop.type = v4l2object->type;
2924   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_G_CROP, &crop) >= 0) {
2925     align.padding_left = crop.c.left;
2926     align.padding_top = crop.c.top;
2927     align.padding_right = width - crop.c.width - crop.c.left;
2928     align.padding_bottom = height - crop.c.height - crop.c.top;
2929     width = crop.c.width;
2930     height = crop.c.height;
2931   }
2932
2933   gst_video_info_set_format (info, format, width, height);
2934
2935   switch (fmt.fmt.pix.field) {
2936     case V4L2_FIELD_ANY:
2937     case V4L2_FIELD_NONE:
2938       info->interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
2939       break;
2940     case V4L2_FIELD_INTERLACED:
2941     case V4L2_FIELD_INTERLACED_TB:
2942     case V4L2_FIELD_INTERLACED_BT:
2943       info->interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
2944       break;
2945     default:
2946       goto unsupported_field;
2947   }
2948
2949   gst_v4l2_object_save_format (v4l2object, fmtdesc, &fmt, info, &align);
2950
2951   /* Shall we setup the pool ? */
2952
2953   return TRUE;
2954
2955 get_fmt_failed:
2956   {
2957     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2958         (_("Video device did not provide output format.")), GST_ERROR_SYSTEM);
2959     return FALSE;
2960   }
2961 invalid_dimensions:
2962   {
2963     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2964         (_("Video device returned invalid dimensions.")),
2965         ("Expected non 0 dimensions, got %dx%d", fmt.fmt.pix.width,
2966             fmt.fmt.pix.height));
2967     return FALSE;
2968   }
2969 unsupported_field:
2970   {
2971     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2972         (_("Video devices uses an unsupported interlacing method.")),
2973         ("V4L2 field type %d not supported", fmt.fmt.pix.field));
2974     return FALSE;
2975   }
2976 unsupported_format:
2977   {
2978     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2979         (_("Video devices uses an unsupported pixel format.")),
2980         ("V4L2 format %" GST_FOURCC_FORMAT " not supported",
2981             GST_FOURCC_ARGS (fmt.fmt.pix.pixelformat)));
2982     return FALSE;
2983   }
2984 }
2985
2986 gboolean
2987 gst_v4l2_object_set_crop (GstV4l2Object * obj)
2988 {
2989   struct v4l2_crop crop = { 0 };
2990
2991   crop.type = obj->type;
2992   crop.c.left = obj->align.padding_left;
2993   crop.c.top = obj->align.padding_top;
2994   crop.c.width = obj->info.width;
2995   crop.c.height = obj->info.height;
2996
2997   if (obj->align.padding_left + obj->align.padding_top +
2998       obj->align.padding_right + obj->align.padding_bottom == 0) {
2999     GST_DEBUG_OBJECT (obj->element, "no cropping needed");
3000     return TRUE;
3001   }
3002
3003   GST_DEBUG_OBJECT (obj->element,
3004       "Desired cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
3005       crop.c.width, crop.c.height);
3006
3007   if (v4l2_ioctl (obj->video_fd, VIDIOC_S_CROP, &crop) < 0) {
3008     GST_WARNING_OBJECT (obj->element, "VIDIOC_S_CROP failed");
3009     return FALSE;
3010   }
3011
3012   GST_DEBUG_OBJECT (obj->element,
3013       "Got cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
3014       crop.c.width, crop.c.height);
3015
3016   return TRUE;
3017 }
3018
3019 gboolean
3020 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
3021 {
3022   GstStructure *config;
3023   GstCaps *oldcaps;
3024   gboolean ret;
3025
3026   if (!v4l2object->pool)
3027     return FALSE;
3028
3029   config = gst_buffer_pool_get_config (v4l2object->pool);
3030   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
3031
3032   ret = oldcaps && gst_caps_is_equal (caps, oldcaps);
3033
3034   gst_structure_free (config);
3035
3036   return ret;
3037 }
3038
3039 gboolean
3040 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
3041 {
3042   gboolean ret = TRUE;
3043
3044   GST_LOG_OBJECT (v4l2object->element, "start flushing");
3045
3046   if (v4l2object->pool && gst_buffer_pool_is_active (v4l2object->pool))
3047     gst_buffer_pool_set_flushing (v4l2object->pool, TRUE);
3048
3049   return ret;
3050 }
3051
3052 gboolean
3053 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
3054 {
3055   gboolean ret = TRUE;
3056
3057   GST_LOG_OBJECT (v4l2object->element, "stop flushing");
3058
3059   if (v4l2object->pool && gst_buffer_pool_is_active (v4l2object->pool))
3060     gst_buffer_pool_set_flushing (v4l2object->pool, FALSE);
3061
3062   return ret;
3063 }
3064
3065 gboolean
3066 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
3067 {
3068   GST_DEBUG_OBJECT (v4l2object->element, "stopping");
3069
3070   if (!GST_V4L2_IS_OPEN (v4l2object))
3071     goto done;
3072   if (!GST_V4L2_IS_ACTIVE (v4l2object))
3073     goto done;
3074
3075   if (v4l2object->pool) {
3076     GST_DEBUG_OBJECT (v4l2object->element, "deactivating pool");
3077     gst_buffer_pool_set_active (v4l2object->pool, FALSE);
3078     gst_object_unref (v4l2object->pool);
3079     v4l2object->pool = NULL;
3080   }
3081
3082   GST_V4L2_SET_INACTIVE (v4l2object);
3083
3084 done:
3085   return TRUE;
3086 }
3087
3088 GstCaps *
3089 gst_v4l2_object_get_caps (GstV4l2Object * v4l2object, GstCaps * filter)
3090 {
3091   GstCaps *ret;
3092   GSList *walk;
3093   GSList *formats;
3094
3095   if (v4l2object->probed_caps == NULL) {
3096     formats = gst_v4l2_object_get_format_list (v4l2object);
3097
3098     ret = gst_caps_new_empty ();
3099
3100     for (walk = formats; walk; walk = walk->next) {
3101       struct v4l2_fmtdesc *format;
3102       GstStructure *template;
3103
3104       format = (struct v4l2_fmtdesc *) walk->data;
3105
3106       template =
3107           gst_v4l2_object_v4l2fourcc_to_bare_struct (format->pixelformat);
3108
3109       if (template) {
3110         GstCaps *tmp;
3111
3112         tmp = gst_v4l2_object_probe_caps_for_format (v4l2object,
3113             format->pixelformat, template);
3114         if (tmp)
3115           gst_caps_append (ret, tmp);
3116
3117         gst_structure_free (template);
3118       } else {
3119         GST_DEBUG_OBJECT (v4l2object->element, "unknown format %u",
3120             format->pixelformat);
3121       }
3122     }
3123     v4l2object->probed_caps = ret;
3124   }
3125
3126   if (filter) {
3127     ret = gst_caps_intersect_full (filter, v4l2object->probed_caps,
3128         GST_CAPS_INTERSECT_FIRST);
3129   } else {
3130     ret = gst_caps_ref (v4l2object->probed_caps);
3131   }
3132
3133   GST_INFO_OBJECT (v4l2object->element, "probed caps: %" GST_PTR_FORMAT, ret);
3134   LOG_CAPS (v4l2object->element, ret);
3135
3136   return ret;
3137 }
3138
3139 gboolean
3140 gst_v4l2_object_decide_allocation (GstV4l2Object * obj, GstQuery * query)
3141 {
3142   GstCaps *caps;
3143   GstBufferPool *pool = NULL, *other_pool = NULL;
3144   GstStructure *config;
3145   guint size, min, max, own_min = 0;
3146   gboolean update;
3147   gboolean has_video_meta;
3148   gboolean can_share_own_pool, pushing_from_our_pool = FALSE;
3149   struct v4l2_control ctl = { 0, };
3150   GstAllocator *allocator = NULL;
3151   GstAllocationParams params = { 0 };
3152
3153   GST_DEBUG_OBJECT (obj->element, "decide allocation");
3154
3155   g_return_val_if_fail (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3156       obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, FALSE);
3157
3158   gst_query_parse_allocation (query, &caps, NULL);
3159
3160   if (obj->pool == NULL) {
3161     if (!gst_v4l2_object_setup_pool (obj, caps))
3162       goto pool_failed;
3163   }
3164
3165   if (gst_query_get_n_allocation_params (query) > 0)
3166     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
3167
3168   if (gst_query_get_n_allocation_pools (query) > 0) {
3169     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
3170     update = TRUE;
3171   } else {
3172     pool = NULL;
3173     min = max = 0;
3174     size = 0;
3175     update = FALSE;
3176   }
3177
3178   GST_DEBUG_OBJECT (obj->element, "allocation: size:%u min:%u max:%u pool:%"
3179       GST_PTR_FORMAT, size, min, max, pool);
3180
3181   has_video_meta =
3182       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
3183
3184   can_share_own_pool = (has_video_meta || !obj->need_video_meta);
3185
3186   /* Certain driver may expose a minimum through controls */
3187   ctl.id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE;
3188   if (v4l2_ioctl (obj->video_fd, VIDIOC_G_CTRL, &ctl) >= 0) {
3189     GST_DEBUG_OBJECT (obj->element, "driver require a minimum of %d buffers",
3190         ctl.value);
3191     obj->min_buffers_for_capture = ctl.value;
3192   } else {
3193     obj->min_buffers_for_capture = 0;
3194   }
3195
3196   /* We can't share our own pool, if it exceed V4L2 capacity */
3197   if (min + obj->min_buffers_for_capture + 1 > VIDEO_MAX_FRAME)
3198     can_share_own_pool = FALSE;
3199
3200   /* select a pool */
3201   switch (obj->mode) {
3202     case GST_V4L2_IO_RW:
3203       if (pool) {
3204         /* in READ/WRITE mode, prefer a downstream pool because our own pool
3205          * doesn't help much, we have to write to it as well */
3206         GST_DEBUG_OBJECT (obj->element,
3207             "read/write mode: using downstream pool");
3208         /* use the bigest size, when we use our own pool we can't really do any
3209          * other size than what the hardware gives us but for downstream pools
3210          * we can try */
3211         size = MAX (size, obj->info.size);
3212       } else if (can_share_own_pool) {
3213         /* no downstream pool, use our own then */
3214         GST_DEBUG_OBJECT (obj->element,
3215             "read/write mode: no downstream pool, using our own");
3216         pool = gst_object_ref (obj->pool);
3217         size = obj->info.size;
3218         pushing_from_our_pool = TRUE;
3219       }
3220       break;
3221
3222     case GST_V4L2_IO_USERPTR:
3223     case GST_V4L2_IO_DMABUF_IMPORT:
3224       /* in importing mode, prefer our own pool, and pass the other pool to
3225        * our own, so it can serve itself */
3226       if (pool == NULL)
3227         goto no_downstream_pool;
3228       gst_v4l2_buffer_pool_set_other_pool (GST_V4L2_BUFFER_POOL (obj->pool),
3229           pool);
3230       other_pool = pool;
3231       gst_object_unref (pool);
3232       pool = gst_object_ref (obj->pool);
3233       size = obj->info.size;
3234       break;
3235
3236     case GST_V4L2_IO_MMAP:
3237     case GST_V4L2_IO_DMABUF:
3238       /* in streaming mode, prefer our own pool */
3239       /* Check if we can use it ... */
3240       if (can_share_own_pool) {
3241         if (pool)
3242           gst_object_unref (pool);
3243         pool = gst_object_ref (obj->pool);
3244         size = obj->info.size;
3245         GST_DEBUG_OBJECT (obj->element,
3246             "streaming mode: using our own pool %" GST_PTR_FORMAT, pool);
3247         pushing_from_our_pool = TRUE;
3248       } else if (pool) {
3249         GST_DEBUG_OBJECT (obj->element,
3250             "streaming mode: copying to downstream pool %" GST_PTR_FORMAT,
3251             pool);
3252       } else {
3253         GST_DEBUG_OBJECT (obj->element,
3254             "streaming mode: no usable pool, copying to generic pool");
3255         size = MAX (size, obj->info.size);
3256       }
3257       break;
3258     case GST_V4L2_IO_AUTO:
3259     default:
3260       GST_WARNING_OBJECT (obj->element, "unhandled mode");
3261       break;
3262   }
3263
3264   if (size == 0)
3265     goto no_size;
3266
3267   /* If pushing from our own pool, configure it with queried minimum,
3268    * otherwise use the minimum required */
3269   if (pushing_from_our_pool) {
3270     /* When pushing from our own pool, we need what downstream one, to be able
3271      * to fill the pipeline, the minimum required to decoder according to the
3272      * driver and 1 more, so we don't endup up with everything downstream or
3273      * held by the decoder. */
3274     own_min = min + obj->min_buffers_for_capture + 1;
3275   } else {
3276     /* In this case we'll have to configure two buffer pool. For our buffer
3277      * pool, we'll need what the driver one, and one more, so we can dequeu */
3278     own_min = obj->min_buffers_for_capture + 1;
3279     own_min = MAX (own_min, GST_V4L2_MIN_BUFFERS);
3280
3281     /* for the downstream pool, we keep what downstream wants, though ensure
3282      * at least a minimum if downstream didn't suggest anything (we are
3283      * expecting the base class to create a default one for the context) */
3284     min = MAX (min, GST_V4L2_MIN_BUFFERS);
3285
3286     /* To import we need the other pool to hold at least own_min */
3287     if (obj->pool == pool)
3288       min += own_min;
3289   }
3290
3291   /* Request a bigger max, if one was suggested but it's too small */
3292   if (max != 0)
3293     max = MAX (min, max);
3294
3295   /* First step, configure our own pool */
3296   config = gst_buffer_pool_get_config (obj->pool);
3297
3298   if (obj->need_video_meta || has_video_meta) {
3299     GST_DEBUG_OBJECT (obj->element, "activate Video Meta");
3300     gst_buffer_pool_config_add_option (config,
3301         GST_BUFFER_POOL_OPTION_VIDEO_META);
3302   }
3303
3304   gst_buffer_pool_config_set_allocator (config, allocator, &params);
3305   gst_buffer_pool_config_set_params (config, caps, size, own_min, 0);
3306
3307   GST_DEBUG_OBJECT (obj->element, "setting own pool config to %"
3308       GST_PTR_FORMAT, config);
3309
3310   /* Our pool often need to adjust the value */
3311   if (!gst_buffer_pool_set_config (obj->pool, config)) {
3312     config = gst_buffer_pool_get_config (obj->pool);
3313
3314     GST_DEBUG_OBJECT (obj->element, "own pool config changed to %"
3315         GST_PTR_FORMAT, config);
3316
3317     /* our pool will adjust the maximum buffer, which we are fine with */
3318     if (!gst_buffer_pool_set_config (obj->pool, config))
3319       goto config_failed;
3320   }
3321
3322   /* Now configure the other pool if different */
3323   if (obj->pool != pool)
3324     other_pool = pool;
3325
3326   if (other_pool) {
3327     config = gst_buffer_pool_get_config (other_pool);
3328     gst_buffer_pool_config_set_allocator (config, allocator, &params);
3329     gst_buffer_pool_config_set_params (config, caps, size, min, max);
3330
3331     GST_DEBUG_OBJECT (obj->element, "setting other pool config to %"
3332         GST_PTR_FORMAT, config);
3333
3334     /* if downstream supports video metadata, add this to the pool config */
3335     if (has_video_meta) {
3336       GST_DEBUG_OBJECT (obj->element, "activate Video Meta");
3337       gst_buffer_pool_config_add_option (config,
3338           GST_BUFFER_POOL_OPTION_VIDEO_META);
3339     }
3340
3341     if (!gst_buffer_pool_set_config (other_pool, config)) {
3342       config = gst_buffer_pool_get_config (other_pool);
3343
3344       if (!gst_buffer_pool_config_validate_params (config, caps, size, min,
3345               max)) {
3346         gst_structure_free (config);
3347         goto config_failed;
3348       }
3349
3350       if (!gst_buffer_pool_set_config (other_pool, config))
3351         goto config_failed;
3352     }
3353   }
3354
3355   if (pool) {
3356     /* For simplicity, simply read back the active configuration, so our base
3357      * class get the right information */
3358     config = gst_buffer_pool_get_config (pool);
3359     gst_buffer_pool_config_get_params (config, NULL, &size, &min, &max);
3360     gst_structure_free (config);
3361   }
3362
3363   if (update)
3364     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
3365   else
3366     gst_query_add_allocation_pool (query, pool, size, min, max);
3367
3368   if (allocator)
3369     gst_object_unref (allocator);
3370
3371   if (pool)
3372     gst_object_unref (pool);
3373
3374   return TRUE;
3375
3376 pool_failed:
3377   {
3378     /* setup_pool already send the error */
3379     goto cleanup;
3380   }
3381 config_failed:
3382   {
3383     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
3384         (_("Failed to configure internal buffer pool.")), (NULL));
3385     goto cleanup;
3386   }
3387 no_size:
3388   {
3389     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
3390         (_("Video device did not suggest any buffer size.")), (NULL));
3391     goto cleanup;
3392   }
3393 cleanup:
3394   {
3395     if (allocator)
3396       gst_object_unref (allocator);
3397
3398     if (pool)
3399       gst_object_unref (pool);
3400     return FALSE;
3401   }
3402 no_downstream_pool:
3403   {
3404     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
3405         (_("No downstream pool to import from.")),
3406         ("When importing DMABUF or USERPTR, we need a pool to import from"));
3407     return FALSE;
3408   }
3409 }
3410
3411 gboolean
3412 gst_v4l2_object_propose_allocation (GstV4l2Object * obj, GstQuery * query)
3413 {
3414   GstBufferPool *pool;
3415   /* we need at least 2 buffers to operate */
3416   guint size, min, max;
3417   GstCaps *caps;
3418   gboolean need_pool;
3419   struct v4l2_control ctl = { 0, };
3420
3421   /* Set defaults allocation parameters */
3422   size = obj->info.size;
3423   min = GST_V4L2_MIN_BUFFERS;
3424   max = VIDEO_MAX_FRAME;
3425
3426   gst_query_parse_allocation (query, &caps, &need_pool);
3427
3428   if (caps == NULL)
3429     goto no_caps;
3430
3431   if ((pool = obj->pool))
3432     gst_object_ref (pool);
3433
3434   if (pool != NULL) {
3435     GstCaps *pcaps;
3436     GstStructure *config;
3437
3438     /* we had a pool, check caps */
3439     config = gst_buffer_pool_get_config (pool);
3440     gst_buffer_pool_config_get_params (config, &pcaps, NULL, NULL, NULL);
3441
3442     GST_DEBUG_OBJECT (obj->element,
3443         "we had a pool with caps %" GST_PTR_FORMAT, pcaps);
3444     if (!gst_caps_is_equal (caps, pcaps)) {
3445       gst_structure_free (config);
3446       gst_object_unref (pool);
3447       goto different_caps;
3448     }
3449     gst_structure_free (config);
3450   }
3451
3452   /* Some devices may expose a minimum */
3453   ctl.id = V4L2_CID_MIN_BUFFERS_FOR_OUTPUT;
3454   if (v4l2_ioctl (obj->video_fd, VIDIOC_G_CTRL, &ctl) >= 0) {
3455     GST_DEBUG_OBJECT (obj->element, "driver require a miminum of %d buffers",
3456         ctl.value);
3457
3458     min = MAX (ctl.value, GST_V4L2_MIN_BUFFERS);
3459   }
3460
3461   gst_query_add_allocation_pool (query, pool, size, min, max);
3462
3463   /* we also support various metadata */
3464   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
3465
3466   if (pool)
3467     gst_object_unref (pool);
3468
3469   return TRUE;
3470
3471   /* ERRORS */
3472 no_caps:
3473   {
3474     GST_DEBUG_OBJECT (obj->element, "no caps specified");
3475     return FALSE;
3476   }
3477 different_caps:
3478   {
3479     /* different caps, we can't use this pool */
3480     GST_DEBUG_OBJECT (obj->element, "pool has different caps");
3481     return FALSE;
3482   }
3483 }