v4l2object: reuse caps framerate if not overwritten by v4l2 device
[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);
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 static gboolean
1629 gst_v4l2_object_get_interlace_mode (enum v4l2_field field,
1630     GstVideoInterlaceMode * interlace_mode)
1631 {
1632   /* NB: If you add new return values, please fix mode_strings in
1633    * gst_v4l2_object_add_interlace_mode */
1634   switch (field) {
1635     case V4L2_FIELD_ANY:
1636       GST_ERROR
1637           ("Driver bug detected - check driver with v4l2-compliance from http://git.linuxtv.org/v4l-utils.git\n");
1638       /* fallthrough */
1639     case V4L2_FIELD_NONE:
1640       *interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
1641       return TRUE;
1642     case V4L2_FIELD_INTERLACED:
1643     case V4L2_FIELD_INTERLACED_TB:
1644     case V4L2_FIELD_INTERLACED_BT:
1645       *interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
1646       return TRUE;
1647     default:
1648       GST_ERROR ("Unknown enum v4l2_field %d", field);
1649       return FALSE;
1650   }
1651 }
1652
1653 static int
1654 gst_v4l2_object_try_fmt (GstV4l2Object * v4l2object,
1655     struct v4l2_format *try_fmt)
1656 {
1657   int fd = v4l2object->video_fd;
1658   struct v4l2_format fmt;
1659   int r;
1660
1661   memcpy (&fmt, try_fmt, sizeof (fmt));
1662   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
1663
1664   if (r < 0 && errno == ENOTTY) {
1665     /* The driver might not implement TRY_FMT, in which case we will try
1666        S_FMT to probe */
1667     if (GST_V4L2_IS_ACTIVE (v4l2object))
1668       goto error;
1669
1670     memcpy (&fmt, try_fmt, sizeof (fmt));
1671     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
1672   }
1673   memcpy (try_fmt, &fmt, sizeof (fmt));
1674   return r;
1675
1676 error:
1677   memcpy (try_fmt, &fmt, sizeof (fmt));
1678   GST_WARNING_OBJECT (v4l2object->element,
1679       "Unable to try format: %s", g_strerror (errno));
1680   return r;
1681 }
1682
1683
1684 static void
1685 gst_v4l2_object_add_interlace_mode (GstV4l2Object * v4l2object,
1686     GstStructure * s, guint32 width, guint32 height, guint32 pixelformat)
1687 {
1688   struct v4l2_format fmt;
1689   GValue interlace_formats = { 0, };
1690   GstVideoInterlaceMode interlace_mode;
1691
1692   const gchar *mode_strings[] = { "progressive",
1693     "interleaved",
1694     "mixed"
1695   };
1696
1697   if (!g_str_equal (gst_structure_get_name (s), "video/x-raw"))
1698     return;
1699
1700   if (v4l2object->never_interlaced) {
1701     gst_structure_set (s, "interlace-mode", G_TYPE_STRING, "progressive", NULL);
1702     return;
1703   }
1704
1705   g_value_init (&interlace_formats, GST_TYPE_LIST);
1706
1707   /* Try twice - once for NONE, once for INTERLACED. */
1708   memset (&fmt, 0, sizeof (fmt));
1709   fmt.type = v4l2object->type;
1710   fmt.fmt.pix.width = width;
1711   fmt.fmt.pix.height = height;
1712   fmt.fmt.pix.pixelformat = pixelformat;
1713   fmt.fmt.pix.field = V4L2_FIELD_NONE;
1714
1715   if (gst_v4l2_object_try_fmt (v4l2object, &fmt) == 0 &&
1716       gst_v4l2_object_get_interlace_mode (fmt.fmt.pix.field, &interlace_mode)) {
1717     GValue interlace_enum = { 0, };
1718     g_value_init (&interlace_enum, G_TYPE_STRING);
1719     g_value_set_string (&interlace_enum, mode_strings[interlace_mode]);
1720     gst_value_list_append_and_take_value (&interlace_formats, &interlace_enum);
1721   }
1722
1723   memset (&fmt, 0, sizeof (fmt));
1724   fmt.type = v4l2object->type;
1725   fmt.fmt.pix.width = width;
1726   fmt.fmt.pix.height = height;
1727   fmt.fmt.pix.pixelformat = pixelformat;
1728   fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
1729
1730   if (gst_v4l2_object_try_fmt (v4l2object, &fmt) == 0 &&
1731       gst_v4l2_object_get_interlace_mode (fmt.fmt.pix.field, &interlace_mode)) {
1732     GValue interlace_enum = { 0, };
1733     g_value_init (&interlace_enum, G_TYPE_STRING);
1734     g_value_set_string (&interlace_enum, mode_strings[interlace_mode]);
1735     gst_value_list_append_and_take_value (&interlace_formats, &interlace_enum);
1736   }
1737
1738   gst_v4l2src_value_simplify (&interlace_formats);
1739   gst_structure_take_value (s, "interlace-mode", &interlace_formats);
1740   return;
1741 }
1742
1743 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1744 static GstStructure *
1745 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1746     guint32 pixelformat,
1747     guint32 width, guint32 height, const GstStructure * template)
1748 {
1749   gint fd = v4l2object->video_fd;
1750   struct v4l2_frmivalenum ival;
1751   guint32 num, denom;
1752   GstStructure *s;
1753   GValue rates = { 0, };
1754
1755   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1756   ival.index = 0;
1757   ival.pixel_format = pixelformat;
1758   ival.width = width;
1759   ival.height = height;
1760
1761   GST_LOG_OBJECT (v4l2object->element,
1762       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1763       GST_FOURCC_ARGS (pixelformat));
1764
1765   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1766    * fraction to get framerate */
1767   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1768     goto enum_frameintervals_failed;
1769
1770   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1771     GValue rate = { 0, };
1772
1773     g_value_init (&rates, GST_TYPE_LIST);
1774     g_value_init (&rate, GST_TYPE_FRACTION);
1775
1776     do {
1777       num = ival.discrete.numerator;
1778       denom = ival.discrete.denominator;
1779
1780       if (num > G_MAXINT || denom > G_MAXINT) {
1781         /* let us hope we don't get here... */
1782         num >>= 1;
1783         denom >>= 1;
1784       }
1785
1786       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1787           denom, num);
1788
1789       /* swap to get the framerate */
1790       gst_value_set_fraction (&rate, denom, num);
1791       gst_value_list_append_value (&rates, &rate);
1792
1793       ival.index++;
1794     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1795   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1796     GValue min = { 0, };
1797     GValue step = { 0, };
1798     GValue max = { 0, };
1799     gboolean added = FALSE;
1800     guint32 minnum, mindenom;
1801     guint32 maxnum, maxdenom;
1802
1803     g_value_init (&rates, GST_TYPE_LIST);
1804
1805     g_value_init (&min, GST_TYPE_FRACTION);
1806     g_value_init (&step, GST_TYPE_FRACTION);
1807     g_value_init (&max, GST_TYPE_FRACTION);
1808
1809     /* get the min */
1810     minnum = ival.stepwise.min.numerator;
1811     mindenom = ival.stepwise.min.denominator;
1812     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1813       minnum >>= 1;
1814       mindenom >>= 1;
1815     }
1816     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1817         minnum, mindenom);
1818     gst_value_set_fraction (&min, minnum, mindenom);
1819
1820     /* get the max */
1821     maxnum = ival.stepwise.max.numerator;
1822     maxdenom = ival.stepwise.max.denominator;
1823     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1824       maxnum >>= 1;
1825       maxdenom >>= 1;
1826     }
1827
1828     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1829         maxnum, maxdenom);
1830     gst_value_set_fraction (&max, maxnum, maxdenom);
1831
1832     /* get the step */
1833     num = ival.stepwise.step.numerator;
1834     denom = ival.stepwise.step.denominator;
1835     if (num > G_MAXINT || denom > G_MAXINT) {
1836       num >>= 1;
1837       denom >>= 1;
1838     }
1839
1840     if (num == 0 || denom == 0) {
1841       /* in this case we have a wrong fraction or no step, set the step to max
1842        * so that we only add the min value in the loop below */
1843       num = maxnum;
1844       denom = maxdenom;
1845     }
1846
1847     /* since we only have gst_value_fraction_subtract and not add, negate the
1848      * numerator */
1849     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1850         num, denom);
1851     gst_value_set_fraction (&step, -num, denom);
1852
1853     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
1854       GValue rate = { 0, };
1855
1856       num = gst_value_get_fraction_numerator (&min);
1857       denom = gst_value_get_fraction_denominator (&min);
1858       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1859           denom, num);
1860
1861       /* invert to get the framerate */
1862       g_value_init (&rate, GST_TYPE_FRACTION);
1863       gst_value_set_fraction (&rate, denom, num);
1864       gst_value_list_append_value (&rates, &rate);
1865       added = TRUE;
1866
1867       /* we're actually adding because step was negated above. This is because
1868        * there is no _add function... */
1869       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1870         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1871         break;
1872       }
1873     }
1874     if (!added) {
1875       /* no range was added, leave the default range from the template */
1876       GST_WARNING_OBJECT (v4l2object->element,
1877           "no range added, leaving default");
1878       g_value_unset (&rates);
1879     }
1880   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1881     guint32 maxnum, maxdenom;
1882
1883     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1884
1885     num = ival.stepwise.min.numerator;
1886     denom = ival.stepwise.min.denominator;
1887     if (num > G_MAXINT || denom > G_MAXINT) {
1888       num >>= 1;
1889       denom >>= 1;
1890     }
1891
1892     maxnum = ival.stepwise.max.numerator;
1893     maxdenom = ival.stepwise.max.denominator;
1894     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1895       maxnum >>= 1;
1896       maxdenom >>= 1;
1897     }
1898
1899     GST_LOG_OBJECT (v4l2object->element,
1900         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1901         num);
1902
1903     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1904   } else {
1905     goto unknown_type;
1906   }
1907
1908 return_data:
1909   s = gst_structure_copy (template);
1910   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1911       "height", G_TYPE_INT, (gint) height, NULL);
1912   gst_v4l2_object_add_aspect_ratio (v4l2object, s);
1913   gst_v4l2_object_add_interlace_mode (v4l2object, s, width, height,
1914       pixelformat);
1915
1916   if (G_IS_VALUE (&rates)) {
1917     gst_v4l2src_value_simplify (&rates);
1918     /* only change the framerate on the template when we have a valid probed new
1919      * value */
1920     gst_structure_take_value (s, "framerate", &rates);
1921   } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1922       v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
1923     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1924         NULL);
1925   }
1926   return s;
1927
1928   /* ERRORS */
1929 enum_frameintervals_failed:
1930   {
1931     GST_DEBUG_OBJECT (v4l2object->element,
1932         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1933         GST_FOURCC_ARGS (pixelformat), width, height);
1934     goto return_data;
1935   }
1936 unknown_type:
1937   {
1938     /* I don't see how this is actually an error, we ignore the format then */
1939     GST_WARNING_OBJECT (v4l2object->element,
1940         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1941         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1942     return NULL;
1943   }
1944 }
1945
1946 static gint
1947 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1948 {
1949   int w1, h1, w2, h2;
1950
1951   gst_structure_get_int (s1, "width", &w1);
1952   gst_structure_get_int (s1, "height", &h1);
1953   gst_structure_get_int (s2, "width", &w2);
1954   gst_structure_get_int (s2, "height", &h2);
1955
1956   /* I think it's safe to assume that this won't overflow for a while */
1957   return ((w2 * h2) - (w1 * h1));
1958 }
1959
1960 static void
1961 gst_v4l2_object_update_and_append (GstV4l2Object * v4l2object,
1962     guint32 format, GstCaps * caps, GstStructure * s)
1963 {
1964   GstStructure *alt_s = NULL;
1965
1966   /* Encoded stream on output buffer need to be parsed */
1967   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT ||
1968       v4l2object->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
1969     gint i = 0;
1970
1971     for (; i < GST_V4L2_FORMAT_COUNT; i++) {
1972       if (format == gst_v4l2_formats[i].format &&
1973           gst_v4l2_formats[i].flags & GST_V4L2_CODEC &&
1974           !(gst_v4l2_formats[i].flags & GST_V4L2_NO_PARSE)) {
1975         gst_structure_set (s, "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
1976         break;
1977       }
1978     }
1979   }
1980
1981   if (v4l2object->has_alpha_component &&
1982       (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
1983           v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
1984     switch (format) {
1985       case V4L2_PIX_FMT_RGB32:
1986         alt_s = gst_structure_copy (s);
1987         gst_structure_set (alt_s, "format", G_TYPE_STRING, "ARGB", NULL);
1988         break;
1989       case V4L2_PIX_FMT_BGR32:
1990         alt_s = gst_structure_copy (s);
1991         gst_structure_set (alt_s, "format", G_TYPE_STRING, "BGRA", NULL);
1992         break;
1993       default:
1994         break;
1995     }
1996   }
1997
1998   gst_caps_append_structure (caps, s);
1999
2000   if (alt_s)
2001     gst_caps_append_structure (caps, alt_s);
2002 }
2003
2004 static GstCaps *
2005 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
2006     guint32 pixelformat, const GstStructure * template)
2007 {
2008   GstCaps *ret = gst_caps_new_empty ();
2009   GstStructure *tmp;
2010   gint fd = v4l2object->video_fd;
2011   struct v4l2_frmsizeenum size;
2012   GList *results = NULL;
2013   guint32 w, h;
2014
2015   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')) {
2016     gst_caps_append_structure (ret, gst_structure_copy (template));
2017     return ret;
2018   }
2019
2020   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
2021   size.index = 0;
2022   size.pixel_format = pixelformat;
2023
2024   GST_DEBUG_OBJECT (v4l2object->element,
2025       "Enumerating frame sizes for %" GST_FOURCC_FORMAT,
2026       GST_FOURCC_ARGS (pixelformat));
2027
2028   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
2029     goto enum_framesizes_failed;
2030
2031   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
2032     do {
2033       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
2034           size.discrete.width, size.discrete.height);
2035
2036       w = MIN (size.discrete.width, G_MAXINT);
2037       h = MIN (size.discrete.height, G_MAXINT);
2038
2039       if (w && h) {
2040         tmp =
2041             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
2042             pixelformat, w, h, template);
2043
2044         if (tmp)
2045           results = g_list_prepend (results, tmp);
2046       }
2047
2048       size.index++;
2049     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
2050     GST_DEBUG_OBJECT (v4l2object->element,
2051         "done iterating discrete frame sizes");
2052   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
2053     guint32 maxw, maxh, step_w, step_h;
2054
2055     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
2056     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
2057         size.stepwise.min_width);
2058     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2059         size.stepwise.min_height);
2060     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
2061         size.stepwise.max_width);
2062     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2063         size.stepwise.max_height);
2064     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
2065         size.stepwise.step_width);
2066     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
2067         size.stepwise.step_height);
2068
2069     w = MAX (size.stepwise.min_width, 1);
2070     h = MAX (size.stepwise.min_height, 1);
2071     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2072     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2073
2074     step_w = MAX (size.stepwise.step_width, 1);
2075     step_h = MAX (size.stepwise.step_height, 1);
2076
2077     /* FIXME: check for sanity and that min/max are multiples of the steps */
2078
2079     /* we only query details for the max width/height since it's likely the
2080      * most restricted if there are any resolution-dependent restrictions */
2081     tmp = gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
2082         pixelformat, maxw, maxh, template);
2083
2084     if (tmp) {
2085       GValue step_range = G_VALUE_INIT;
2086
2087       g_value_init (&step_range, GST_TYPE_INT_RANGE);
2088       gst_value_set_int_range_step (&step_range, w, maxw, step_w);
2089       gst_structure_set_value (tmp, "width", &step_range);
2090
2091       gst_value_set_int_range_step (&step_range, h, maxh, step_h);
2092       gst_structure_take_value (tmp, "height", &step_range);
2093
2094       /* no point using the results list here, since there's only one struct */
2095       gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2096     }
2097   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
2098     guint32 maxw, maxh;
2099
2100     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
2101     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
2102         size.stepwise.min_width);
2103     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2104         size.stepwise.min_height);
2105     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
2106         size.stepwise.max_width);
2107     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2108         size.stepwise.max_height);
2109
2110     w = MAX (size.stepwise.min_width, 1);
2111     h = MAX (size.stepwise.min_height, 1);
2112     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2113     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2114
2115     tmp =
2116         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
2117         w, h, template);
2118     if (tmp) {
2119       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
2120           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
2121           NULL);
2122
2123       /* no point using the results list here, since there's only one struct */
2124       gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2125     }
2126   } else {
2127     goto unknown_type;
2128   }
2129
2130   /* we use an intermediary list to store and then sort the results of the
2131    * probing because we can't make any assumptions about the order in which
2132    * the driver will give us the sizes, but we want the final caps to contain
2133    * the results starting with the highest resolution and having the lowest
2134    * resolution last, since order in caps matters for things like fixation. */
2135   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
2136   while (results != NULL) {
2137     gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret,
2138         results->data);
2139     results = g_list_delete_link (results, results);
2140   }
2141
2142   if (gst_caps_is_empty (ret))
2143     goto enum_framesizes_no_results;
2144
2145   return ret;
2146
2147   /* ERRORS */
2148 enum_framesizes_failed:
2149   {
2150     /* I don't see how this is actually an error */
2151     GST_DEBUG_OBJECT (v4l2object->element,
2152         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
2153         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
2154     goto default_frame_sizes;
2155   }
2156 enum_framesizes_no_results:
2157   {
2158     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
2159      * question doesn't actually support it yet */
2160     GST_DEBUG_OBJECT (v4l2object->element,
2161         "No results for pixelformat %" GST_FOURCC_FORMAT
2162         " enumerating frame sizes, trying fallback",
2163         GST_FOURCC_ARGS (pixelformat));
2164     goto default_frame_sizes;
2165   }
2166 unknown_type:
2167   {
2168     GST_WARNING_OBJECT (v4l2object->element,
2169         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
2170         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
2171     goto default_frame_sizes;
2172   }
2173
2174 default_frame_sizes:
2175   {
2176     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
2177
2178     /* This code is for Linux < 2.6.19 */
2179     min_w = min_h = 1;
2180     max_w = max_h = GST_V4L2_MAX_SIZE;
2181     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
2182             &min_h)) {
2183       GST_WARNING_OBJECT (v4l2object->element,
2184           "Could not probe minimum capture size for pixelformat %"
2185           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2186     }
2187     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
2188             &max_h)) {
2189       GST_WARNING_OBJECT (v4l2object->element,
2190           "Could not probe maximum capture size for pixelformat %"
2191           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2192     }
2193
2194     /* Since we can't get framerate directly, try to use the current norm */
2195     if (v4l2object->tv_norm && v4l2object->norms) {
2196       GList *norms;
2197       GstTunerNorm *norm = NULL;
2198       GstTunerNorm *current =
2199           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
2200
2201       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
2202         norm = (GstTunerNorm *) norms->data;
2203         if (!strcmp (norm->label, current->label))
2204           break;
2205       }
2206       /* If it's possible, set framerate to that (discrete) value */
2207       if (norm) {
2208         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
2209         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
2210       }
2211     }
2212
2213     tmp = gst_structure_copy (template);
2214     if (fix_num) {
2215       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
2216           fix_denom, NULL);
2217     } else if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2218         v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
2219       /* if norm can't be used, copy the template framerate */
2220       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
2221           100, 1, NULL);
2222     }
2223
2224     if (min_w == max_w)
2225       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
2226     else
2227       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
2228
2229     if (min_h == max_h)
2230       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
2231     else
2232       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
2233
2234     /* We could consider setting interlace mode from min and max. */
2235     gst_v4l2_object_add_interlace_mode (v4l2object, tmp, max_w, max_h,
2236         pixelformat);
2237     gst_v4l2_object_add_aspect_ratio (v4l2object, tmp);
2238
2239     gst_v4l2_object_update_and_append (v4l2object, pixelformat, ret, tmp);
2240     return ret;
2241   }
2242 }
2243
2244 static gboolean
2245 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
2246     guint32 pixelformat, gint * width, gint * height)
2247 {
2248   struct v4l2_format fmt;
2249   gboolean ret = FALSE;
2250   GstVideoInterlaceMode interlace_mode;
2251
2252   g_return_val_if_fail (width != NULL, FALSE);
2253   g_return_val_if_fail (height != NULL, FALSE);
2254
2255   GST_LOG_OBJECT (v4l2object->element,
2256       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2257       *width, *height, GST_FOURCC_ARGS (pixelformat));
2258
2259   memset (&fmt, 0, sizeof (struct v4l2_format));
2260
2261   /* get size delimiters */
2262   memset (&fmt, 0, sizeof (fmt));
2263   fmt.type = v4l2object->type;
2264   fmt.fmt.pix.width = *width;
2265   fmt.fmt.pix.height = *height;
2266   fmt.fmt.pix.pixelformat = pixelformat;
2267   fmt.fmt.pix.field = V4L2_FIELD_ANY;
2268
2269   if (gst_v4l2_object_try_fmt (v4l2object, &fmt) < 0)
2270     goto error;
2271
2272   GST_LOG_OBJECT (v4l2object->element,
2273       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2274
2275   *width = fmt.fmt.pix.width;
2276   *height = fmt.fmt.pix.height;
2277
2278   if (!gst_v4l2_object_get_interlace_mode (fmt.fmt.pix.field, &interlace_mode)) {
2279     GST_WARNING_OBJECT (v4l2object->element,
2280         "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u: %u",
2281         GST_FOURCC_ARGS (pixelformat), *width, *height, fmt.fmt.pix.field);
2282     goto error;
2283   }
2284
2285   ret = TRUE;
2286
2287 error:
2288   if (!ret) {
2289     GST_WARNING_OBJECT (v4l2object->element,
2290         "Unable to try format: %s", g_strerror (errno));
2291   }
2292
2293   return ret;
2294 }
2295
2296 static gboolean
2297 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
2298 {
2299   GstV4l2IOMode mode;
2300
2301   GST_DEBUG_OBJECT (v4l2object->element, "initializing the %s system",
2302       V4L2_TYPE_IS_OUTPUT (v4l2object->type) ? "output" : "capture");
2303
2304   GST_V4L2_CHECK_OPEN (v4l2object);
2305   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2306
2307   /* find transport */
2308   mode = v4l2object->req_mode;
2309
2310   if (v4l2object->vcap.capabilities & V4L2_CAP_READWRITE) {
2311     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2312       mode = GST_V4L2_IO_RW;
2313   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
2314     goto method_not_supported;
2315
2316   if (v4l2object->vcap.capabilities & V4L2_CAP_STREAMING) {
2317     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2318       mode = GST_V4L2_IO_MMAP;
2319   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP)
2320     goto method_not_supported;
2321
2322   /* if still no transport selected, error out */
2323   if (mode == GST_V4L2_IO_AUTO)
2324     goto no_supported_capture_method;
2325
2326   GST_INFO_OBJECT (v4l2object->element, "accessing buffers via mode %d", mode);
2327   v4l2object->mode = mode;
2328
2329   /* Map the buffers */
2330   GST_LOG_OBJECT (v4l2object->element, "initiating buffer pool");
2331
2332   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
2333     goto buffer_pool_new_failed;
2334
2335   GST_V4L2_SET_ACTIVE (v4l2object);
2336
2337   return TRUE;
2338
2339   /* ERRORS */
2340 buffer_pool_new_failed:
2341   {
2342     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2343         (_("Could not map buffers from device '%s'"),
2344             v4l2object->videodev),
2345         ("Failed to create buffer pool: %s", g_strerror (errno)));
2346     return FALSE;
2347   }
2348 method_not_supported:
2349   {
2350     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2351         (_("The driver of device '%s' does not support the IO method %d"),
2352             v4l2object->videodev, mode), (NULL));
2353     return FALSE;
2354   }
2355 no_supported_capture_method:
2356   {
2357     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2358         (_("The driver of device '%s' does not support any known IO "
2359                 "method."), v4l2object->videodev), (NULL));
2360     return FALSE;
2361   }
2362 }
2363
2364 static void
2365 gst_v4l2_object_set_stride (GstVideoInfo * info, GstVideoAlignment * align,
2366     gint plane, gint stride)
2367 {
2368   const GstVideoFormatInfo *finfo = info->finfo;
2369
2370   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
2371     gint x_tiles, y_tiles, ws, hs, tile_height, padded_height;
2372
2373
2374     ws = GST_VIDEO_FORMAT_INFO_TILE_WS (finfo);
2375     hs = GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
2376     tile_height = 1 << hs;
2377
2378     padded_height = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, plane,
2379         info->height + align->padding_top + align->padding_bottom);
2380     padded_height = GST_ROUND_UP_N (padded_height, tile_height);
2381
2382     x_tiles = stride >> ws;
2383     y_tiles = padded_height >> hs;
2384     info->stride[plane] = GST_VIDEO_TILE_MAKE_STRIDE (x_tiles, y_tiles);
2385   } else {
2386     info->stride[plane] = stride;
2387   }
2388 }
2389
2390 static void
2391 gst_v4l2_object_extrapolate_info (GstV4l2Object * v4l2object,
2392     GstVideoInfo * info, GstVideoAlignment * align, gint stride)
2393 {
2394   const GstVideoFormatInfo *finfo = info->finfo;
2395   gint i, estride, padded_height;
2396   gsize offs = 0;
2397
2398   g_return_if_fail (v4l2object->n_v4l2_planes == 1);
2399
2400   padded_height = info->height + align->padding_top + align->padding_bottom;
2401
2402   for (i = 0; i < finfo->n_planes; i++) {
2403     switch (finfo->format) {
2404       case GST_VIDEO_FORMAT_NV12:
2405       case GST_VIDEO_FORMAT_NV12_64Z32:
2406       case GST_VIDEO_FORMAT_NV21:
2407       case GST_VIDEO_FORMAT_NV16:
2408       case GST_VIDEO_FORMAT_NV24:
2409         estride = (i == 0 ? 1 : 2) *
2410             GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, stride);
2411         break;
2412       default:
2413         estride = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, stride);
2414         break;
2415     }
2416
2417     gst_v4l2_object_set_stride (info, align, i, estride);
2418
2419     info->offset[i] = offs;
2420     offs += estride *
2421         GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, padded_height);
2422
2423     GST_DEBUG_OBJECT (v4l2object->element,
2424         "Extrapolated for plane %d with base stride %d: "
2425         "stride %d, offset %" G_GSIZE_FORMAT, i, stride, info->stride[i],
2426         info->offset[i]);
2427   }
2428 }
2429
2430 static void
2431 gst_v4l2_object_save_format (GstV4l2Object * v4l2object,
2432     struct v4l2_fmtdesc *fmtdesc, struct v4l2_format *format,
2433     GstVideoInfo * info, GstVideoAlignment * align)
2434 {
2435   const GstVideoFormatInfo *finfo = info->finfo;
2436   gboolean standard_stride = TRUE;
2437   gint stride, padded_width, padded_height, i;
2438
2439   if (GST_VIDEO_INFO_FORMAT (info) == GST_VIDEO_FORMAT_ENCODED) {
2440     v4l2object->n_v4l2_planes = 1;
2441     info->size = format->fmt.pix.sizeimage;
2442     goto store_info;
2443   }
2444
2445   /* adjust right padding */
2446   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type))
2447     stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
2448   else
2449     stride = format->fmt.pix.bytesperline;
2450
2451   padded_width = stride / GST_VIDEO_FORMAT_INFO_PSTRIDE (finfo, 0);
2452
2453   if (padded_width < format->fmt.pix.width)
2454     GST_WARNING_OBJECT (v4l2object->element,
2455         "Driver bug detected, stride is too small for the width");
2456
2457   align->padding_right = padded_width - info->width - align->padding_left;
2458
2459   /* adjust bottom padding */
2460   padded_height = format->fmt.pix.height;
2461
2462   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
2463     guint hs, tile_height;
2464
2465     hs = GST_VIDEO_FORMAT_INFO_TILE_HS (finfo);
2466     tile_height = 1 << hs;
2467
2468     padded_height = GST_ROUND_UP_N (padded_height, tile_height);
2469   }
2470
2471   align->padding_bottom = padded_height - info->height - align->padding_top;
2472
2473   /* setup the strides and offset */
2474   if (V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type)) {
2475     struct v4l2_pix_format_mplane *pix_mp = &format->fmt.pix_mp;
2476
2477     /* figure out the frame layout */
2478     v4l2object->n_v4l2_planes = MAX (1, pix_mp->num_planes);
2479     info->size = 0;
2480     for (i = 0; i < v4l2object->n_v4l2_planes; i++) {
2481       stride = pix_mp->plane_fmt[i].bytesperline;
2482
2483       if (info->stride[i] != stride)
2484         standard_stride = FALSE;
2485
2486       gst_v4l2_object_set_stride (info, align, i, stride);
2487       info->offset[i] = info->size;
2488       info->size += pix_mp->plane_fmt[i].sizeimage;
2489     }
2490
2491     /* Extrapolate stride if planar format are being set in 1 v4l2 plane */
2492     if (v4l2object->n_v4l2_planes < finfo->n_planes) {
2493       stride = format->fmt.pix_mp.plane_fmt[0].bytesperline;
2494       gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
2495     }
2496   } else {
2497     /* only one plane in non-MPLANE mode */
2498     v4l2object->n_v4l2_planes = 1;
2499     info->size = format->fmt.pix.sizeimage;
2500     stride = format->fmt.pix.bytesperline;
2501
2502     if (info->stride[0] != stride)
2503       standard_stride = FALSE;
2504
2505     gst_v4l2_object_extrapolate_info (v4l2object, info, align, stride);
2506   }
2507
2508   /* adjust the offset to take into account left and top */
2509   if (GST_VIDEO_FORMAT_INFO_IS_TILED (finfo)) {
2510     if ((align->padding_left + align->padding_top) > 0)
2511       GST_WARNING_OBJECT (v4l2object->element,
2512           "Left and top padding is not permitted for tiled formats");
2513   } else {
2514     for (i = 0; i < finfo->n_planes; i++) {
2515       gint vedge, hedge;
2516
2517       /* FIXME we assume plane as component as this is true for all supported
2518        * format we support. */
2519
2520       hedge = GST_VIDEO_FORMAT_INFO_SCALE_WIDTH (finfo, i, align->padding_left);
2521       vedge = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (finfo, i, align->padding_top);
2522
2523       info->offset[i] += (vedge * info->stride[i]) +
2524           (hedge * GST_VIDEO_INFO_COMP_PSTRIDE (info, i));
2525     }
2526   }
2527
2528 store_info:
2529   GST_DEBUG_OBJECT (v4l2object->element, "Got sizeimage %" G_GSIZE_FORMAT,
2530       info->size);
2531
2532   /* to avoid copies we need video meta if top or left padding */
2533   v4l2object->need_video_meta =
2534       ((align->padding_top + align->padding_left) != 0);
2535
2536   /* ... or if stride is non "standard" */
2537   if (!standard_stride)
2538     v4l2object->need_video_meta = TRUE;
2539
2540   /* ... or also video meta if we use multiple, non-contiguous, planes */
2541   if (v4l2object->n_v4l2_planes > 1)
2542     v4l2object->need_video_meta = TRUE;
2543
2544   v4l2object->info = *info;
2545   v4l2object->align = *align;
2546   v4l2object->format = *format;
2547   v4l2object->fmtdesc = fmtdesc;
2548
2549   /* if we have a framerate pre-calculate duration */
2550   if (info->fps_n > 0 && info->fps_d > 0) {
2551     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, info->fps_d,
2552         info->fps_n);
2553   } else {
2554     v4l2object->duration = GST_CLOCK_TIME_NONE;
2555   }
2556 }
2557
2558 gboolean
2559 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps)
2560 {
2561   gint fd = v4l2object->video_fd;
2562   struct v4l2_format format;
2563   struct v4l2_streamparm streamparm;
2564   enum v4l2_field field;
2565   guint32 pixelformat;
2566   struct v4l2_fmtdesc *fmtdesc;
2567   GstVideoInfo info;
2568   GstVideoAlignment align;
2569   gint width, height, fps_n, fps_d;
2570   gint n_v4l_planes;
2571   gint i = 0;
2572   gboolean is_mplane;
2573   enum v4l2_colorspace colorspace = 0;
2574
2575   GST_V4L2_CHECK_OPEN (v4l2object);
2576   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2577
2578   is_mplane = V4L2_TYPE_IS_MULTIPLANAR (v4l2object->type);
2579
2580   gst_video_info_init (&info);
2581   gst_video_alignment_reset (&align);
2582
2583   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
2584     goto invalid_caps;
2585
2586   pixelformat = fmtdesc->pixelformat;
2587   width = GST_VIDEO_INFO_WIDTH (&info);
2588   height = GST_VIDEO_INFO_HEIGHT (&info);
2589   fps_n = GST_VIDEO_INFO_FPS_N (&info);
2590   fps_d = GST_VIDEO_INFO_FPS_D (&info);
2591
2592   /* if encoded format (GST_VIDEO_INFO_N_PLANES return 0)
2593    * or if contiguous is prefered */
2594   n_v4l_planes = GST_VIDEO_INFO_N_PLANES (&info);
2595   if (!n_v4l_planes || !v4l2object->prefered_non_contiguous)
2596     n_v4l_planes = 1;
2597
2598   if (GST_VIDEO_INFO_IS_INTERLACED (&info)) {
2599     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2600     /* ideally we would differentiate between types of interlaced video
2601      * but there is not sufficient information in the caps..
2602      */
2603     field = V4L2_FIELD_INTERLACED;
2604   } else {
2605     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2606     field = V4L2_FIELD_NONE;
2607   }
2608
2609   if (V4L2_TYPE_IS_OUTPUT (v4l2object->type)) {
2610     /* We should set colorspace if we have it */
2611     if (gst_video_colorimetry_matches (&info.colorimetry, "bt601")) {
2612       colorspace = V4L2_COLORSPACE_SMPTE170M;
2613     } else if (gst_video_colorimetry_matches (&info.colorimetry, "bt709")) {
2614       colorspace = V4L2_COLORSPACE_REC709;
2615     } else if (gst_video_colorimetry_matches (&info.colorimetry, "smpte240m")) {
2616       colorspace = V4L2_COLORSPACE_SMPTE240M;
2617     } else {
2618       /* Try to guess colorspace according to pixelformat and size */
2619       if (GST_VIDEO_INFO_IS_YUV (&info)) {
2620         /* SD streams likely use SMPTE170M and HD streams REC709 */
2621         if (width <= 720 && height <= 576)
2622           colorspace = V4L2_COLORSPACE_SMPTE170M;
2623         else
2624           colorspace = V4L2_COLORSPACE_REC709;
2625       } else if (GST_VIDEO_INFO_IS_RGB (&info)) {
2626         colorspace = V4L2_COLORSPACE_SRGB;
2627       }
2628     }
2629   }
2630
2631   GST_DEBUG_OBJECT (v4l2object->element, "Desired format %dx%d, format "
2632       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
2633       GST_FOURCC_ARGS (pixelformat), GST_VIDEO_INFO_PLANE_STRIDE (&info, 0));
2634
2635   memset (&format, 0x00, sizeof (struct v4l2_format));
2636   format.type = v4l2object->type;
2637
2638   if (is_mplane) {
2639     format.type = v4l2object->type;
2640     format.fmt.pix_mp.pixelformat = pixelformat;
2641     format.fmt.pix_mp.width = width;
2642     format.fmt.pix_mp.height = height;
2643     format.fmt.pix_mp.field = field;
2644     format.fmt.pix_mp.num_planes = n_v4l_planes;
2645
2646     /* try to ask our prefered stride but it's not a failure if not
2647      * accepted */
2648     for (i = 0; i < n_v4l_planes; i++) {
2649       gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, i);
2650
2651       if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
2652         stride = GST_VIDEO_TILE_X_TILES (stride) <<
2653             GST_VIDEO_FORMAT_INFO_TILE_WS (info.finfo);
2654
2655       format.fmt.pix_mp.plane_fmt[i].bytesperline = stride;
2656     }
2657
2658     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
2659       format.fmt.pix_mp.plane_fmt[0].sizeimage = ENCODED_BUFFER_SIZE;
2660   } else {
2661     gint stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
2662
2663     format.type = v4l2object->type;
2664     format.fmt.pix.width = width;
2665     format.fmt.pix.height = height;
2666     format.fmt.pix.pixelformat = pixelformat;
2667     format.fmt.pix.field = field;
2668
2669     if (GST_VIDEO_FORMAT_INFO_IS_TILED (info.finfo))
2670       stride = GST_VIDEO_TILE_X_TILES (stride) <<
2671           GST_VIDEO_FORMAT_INFO_TILE_WS (info.finfo);
2672
2673     /* try to ask our prefered stride */
2674     format.fmt.pix.bytesperline = stride;
2675
2676     if (GST_VIDEO_INFO_FORMAT (&info) == GST_VIDEO_FORMAT_ENCODED)
2677       format.fmt.pix.sizeimage = ENCODED_BUFFER_SIZE;
2678   }
2679
2680   GST_DEBUG_OBJECT (v4l2object->element, "Desired format is %dx%d, format "
2681       "%" GST_FOURCC_FORMAT ", nb planes %d", format.fmt.pix.width,
2682       format.fmt.pix_mp.height,
2683       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2684       is_mplane ? format.fmt.pix_mp.num_planes : 1);
2685
2686 #ifndef GST_DISABLE_GST_DEBUG
2687   if (is_mplane) {
2688     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
2689       GST_DEBUG_OBJECT (v4l2object->element, "  stride %d",
2690           format.fmt.pix_mp.plane_fmt[i].bytesperline);
2691   } else {
2692     GST_DEBUG_OBJECT (v4l2object->element, "  stride %d",
2693         format.fmt.pix.bytesperline);
2694   }
2695 #endif
2696
2697   if (V4L2_TYPE_IS_OUTPUT (v4l2object->type)) {
2698     if (is_mplane)
2699       format.fmt.pix_mp.colorspace = colorspace;
2700     else
2701       format.fmt.pix.colorspace = colorspace;
2702
2703     GST_DEBUG_OBJECT (v4l2object->element, "Desired colorspace is %d",
2704         colorspace);
2705   }
2706
2707   if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0)
2708     goto set_fmt_failed;
2709
2710   GST_DEBUG_OBJECT (v4l2object->element, "Got format of %dx%d, format "
2711       "%" GST_FOURCC_FORMAT ", nb planes %d, colorspace %d",
2712       format.fmt.pix.width, format.fmt.pix_mp.height,
2713       GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2714       is_mplane ? format.fmt.pix_mp.num_planes : 1,
2715       is_mplane ? format.fmt.pix_mp.colorspace : format.fmt.pix.colorspace);
2716
2717 #ifndef GST_DISABLE_GST_DEBUG
2718   if (is_mplane) {
2719     for (i = 0; i < format.fmt.pix_mp.num_planes; i++)
2720       GST_DEBUG_OBJECT (v4l2object->element, "  stride %d, sizeimage %d",
2721           format.fmt.pix_mp.plane_fmt[i].bytesperline,
2722           format.fmt.pix_mp.plane_fmt[i].sizeimage);
2723   } else {
2724     GST_DEBUG_OBJECT (v4l2object->element, "  stride %d, sizeimage %d",
2725         format.fmt.pix.bytesperline, format.fmt.pix.sizeimage);
2726   }
2727 #endif
2728
2729   if (format.fmt.pix.pixelformat != pixelformat)
2730     goto invalid_pixelformat;
2731
2732   /* Only negotiate size with raw data.
2733    * For some codecs the dimensions are *not* in the bitstream, IIRC VC1
2734    * in ASF mode for example, there is also not reason for a driver to
2735    * change the size. */
2736   if (info.finfo->format != GST_VIDEO_FORMAT_ENCODED) {
2737     /* We can crop larger images */
2738     if (format.fmt.pix.width < width || format.fmt.pix.height < height)
2739       goto invalid_dimensions;
2740
2741     /* Note, this will be adjusted if upstream has non-centered cropping. */
2742     align.padding_top = 0;
2743     align.padding_bottom = format.fmt.pix.height - height;
2744     align.padding_left = 0;
2745     align.padding_right = format.fmt.pix.width - width;
2746   }
2747
2748   if (is_mplane && format.fmt.pix_mp.num_planes != n_v4l_planes)
2749     goto invalid_planes;
2750
2751   if (GST_VIDEO_INFO_HAS_ALPHA (&info)) {
2752     struct v4l2_control ctl = { 0, };
2753     ctl.id = V4L2_CID_ALPHA_COMPONENT;
2754     ctl.value = 0xff;
2755
2756     if (v4l2_ioctl (fd, VIDIOC_S_CTRL, &ctl) < 0)
2757       GST_WARNING_OBJECT (v4l2object->element,
2758           "Failed to set alpha component value");
2759   }
2760
2761   /* Is there a reason we require the caller to always specify a framerate? */
2762   GST_DEBUG_OBJECT (v4l2object->element, "Desired framerate: %u/%u", fps_n,
2763       fps_d);
2764
2765   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2766   streamparm.type = v4l2object->type;
2767
2768   if (v4l2_ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
2769     goto get_parm_failed;
2770
2771   GST_VIDEO_INFO_FPS_N (&info) =
2772       streamparm.parm.capture.timeperframe.denominator;
2773   GST_VIDEO_INFO_FPS_D (&info) = streamparm.parm.capture.timeperframe.numerator;
2774
2775   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE
2776       || v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
2777     GST_DEBUG_OBJECT (v4l2object->element, "Got framerate: %u/%u",
2778         streamparm.parm.capture.timeperframe.denominator,
2779         streamparm.parm.capture.timeperframe.numerator);
2780
2781     /* We used to skip frame rate setup if the camera was already setup
2782      * with the requested frame rate. This breaks some cameras though,
2783      * causing them to not output data (several models of Thinkpad cameras
2784      * have this problem at least).
2785      * So, don't skip. */
2786     GST_LOG_OBJECT (v4l2object->element, "Setting framerate to %u/%u", fps_n,
2787         fps_d);
2788     /* We want to change the frame rate, so check whether we can. Some cheap USB
2789      * cameras don't have the capability */
2790     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
2791       GST_DEBUG_OBJECT (v4l2object->element,
2792           "Not setting framerate (not supported)");
2793       goto done;
2794     }
2795
2796     /* Note: V4L2 wants the frame interval, we have the frame rate */
2797     streamparm.parm.capture.timeperframe.numerator = fps_d;
2798     streamparm.parm.capture.timeperframe.denominator = fps_n;
2799
2800     /* some cheap USB cam's won't accept any change */
2801     if (v4l2_ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
2802       goto set_parm_failed;
2803
2804     if (streamparm.parm.capture.timeperframe.numerator > 0 &&
2805       streamparm.parm.capture.timeperframe.denominator > 0) {
2806       /* get new values */
2807       fps_d = streamparm.parm.capture.timeperframe.numerator;
2808       fps_n = streamparm.parm.capture.timeperframe.denominator;
2809
2810       GST_INFO_OBJECT (v4l2object->element, "Set framerate to %u/%u", fps_n,
2811           fps_d);
2812     } else {
2813       /* fix v4l2 capture driver to provide framerate values */
2814       GST_WARNING_OBJECT (v4l2object->element,
2815           "Reuse caps framerate %u/%u - fix v4l2 capture driver",
2816           fps_n, fps_d);
2817     }
2818
2819     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
2820     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
2821   }
2822
2823 done:
2824   /* add boolean return, so we can fail on drivers bugs */
2825   gst_v4l2_object_save_format (v4l2object, fmtdesc, &format, &info, &align);
2826
2827   /* now configure the pool */
2828   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
2829     goto pool_failed;
2830
2831   return TRUE;
2832
2833   /* ERRORS */
2834 invalid_caps:
2835   {
2836     GST_DEBUG_OBJECT (v4l2object->element, "can't parse caps %" GST_PTR_FORMAT,
2837         caps);
2838     return FALSE;
2839   }
2840 set_fmt_failed:
2841   {
2842     if (errno == EBUSY) {
2843       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, BUSY,
2844           (_("Device '%s' is busy"), v4l2object->videodev),
2845           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2846               GST_FOURCC_ARGS (pixelformat), width, height,
2847               g_strerror (errno)));
2848     } else {
2849       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2850           (_("Device '%s' cannot capture at %dx%d"),
2851               v4l2object->videodev, width, height),
2852           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2853               GST_FOURCC_ARGS (pixelformat), width, height,
2854               g_strerror (errno)));
2855     }
2856     return FALSE;
2857   }
2858 invalid_dimensions:
2859   {
2860     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2861         (_("Device '%s' cannot capture at %dx%d"),
2862             v4l2object->videodev, width, height),
2863         ("Tried to capture at %dx%d, but device returned size %dx%d",
2864             width, height, format.fmt.pix.width, format.fmt.pix.height));
2865     return FALSE;
2866   }
2867 invalid_pixelformat:
2868   {
2869     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2870         (_("Device '%s' cannot capture in the specified format"),
2871             v4l2object->videodev),
2872         ("Tried to capture in %" GST_FOURCC_FORMAT
2873             ", but device returned format" " %" GST_FOURCC_FORMAT,
2874             GST_FOURCC_ARGS (pixelformat),
2875             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2876     return FALSE;
2877   }
2878 invalid_planes:
2879   {
2880     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2881         (_("Device '%s' does support non-contiguous planes"),
2882             v4l2object->videodev),
2883         ("Device wants %d planes", format.fmt.pix_mp.num_planes));
2884     return FALSE;
2885   }
2886 get_parm_failed:
2887   {
2888     /* it's possible that this call is not supported */
2889     if (errno != EINVAL && errno != ENOTTY) {
2890       GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2891           (_("Could not get parameters on device '%s'"),
2892               v4l2object->videodev), GST_ERROR_SYSTEM);
2893     }
2894     goto done;
2895   }
2896 set_parm_failed:
2897   {
2898     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2899         (_("Video device did not accept new frame rate setting.")),
2900         GST_ERROR_SYSTEM);
2901     goto done;
2902   }
2903 pool_failed:
2904   {
2905     /* setup_pool already send the error */
2906     return FALSE;
2907   }
2908 }
2909
2910 /**
2911  * gst_v4l2_object_acquire_format:
2912  * @v4l2object the object
2913  * @info a GstVideoInfo to be filled
2914  *
2915  * Acquire the driver choosen format. This is useful in decoder or encoder elements where
2916  * the output format is choosen by the HW.
2917  *
2918  * Returns: %TRUE on success, %FALSE on failure.
2919  */
2920 gboolean
2921 gst_v4l2_object_acquire_format (GstV4l2Object * v4l2object, GstVideoInfo * info)
2922 {
2923   struct v4l2_fmtdesc *fmtdesc;
2924   struct v4l2_format fmt;
2925   struct v4l2_crop crop;
2926   GstVideoFormat format;
2927   guint width, height;
2928   GstVideoAlignment align;
2929
2930   gst_video_info_init (info);
2931   gst_video_alignment_reset (&align);
2932
2933   memset (&fmt, 0x00, sizeof (struct v4l2_format));
2934   fmt.type = v4l2object->type;
2935   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_G_FMT, &fmt) < 0)
2936     goto get_fmt_failed;
2937
2938   fmtdesc = gst_v4l2_object_get_format_from_fourcc (v4l2object,
2939       fmt.fmt.pix.pixelformat);
2940   if (fmtdesc == NULL)
2941     goto unsupported_format;
2942
2943   /* No need to care about mplane, the four first params are the same */
2944   format = gst_v4l2_object_v4l2fourcc_to_video_format (fmt.fmt.pix.pixelformat);
2945
2946   /* fails if we do no translate the fmt.pix.pixelformat to GstVideoFormat */
2947   if (format == GST_VIDEO_FORMAT_UNKNOWN)
2948     goto unsupported_format;
2949
2950   if (fmt.fmt.pix.width == 0 || fmt.fmt.pix.height == 0)
2951     goto invalid_dimensions;
2952
2953   width = fmt.fmt.pix.width;
2954   height = fmt.fmt.pix.height;
2955
2956   memset (&crop, 0, sizeof (struct v4l2_crop));
2957   crop.type = v4l2object->type;
2958   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_G_CROP, &crop) >= 0) {
2959     align.padding_left = crop.c.left;
2960     align.padding_top = crop.c.top;
2961     align.padding_right = width - crop.c.width - crop.c.left;
2962     align.padding_bottom = height - crop.c.height - crop.c.top;
2963     width = crop.c.width;
2964     height = crop.c.height;
2965   }
2966
2967   gst_video_info_set_format (info, format, width, height);
2968
2969   switch (fmt.fmt.pix.field) {
2970     case V4L2_FIELD_ANY:
2971     case V4L2_FIELD_NONE:
2972       info->interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
2973       break;
2974     case V4L2_FIELD_INTERLACED:
2975     case V4L2_FIELD_INTERLACED_TB:
2976     case V4L2_FIELD_INTERLACED_BT:
2977       info->interlace_mode = GST_VIDEO_INTERLACE_MODE_INTERLEAVED;
2978       break;
2979     default:
2980       goto unsupported_field;
2981   }
2982
2983   gst_v4l2_object_save_format (v4l2object, fmtdesc, &fmt, info, &align);
2984
2985   /* Shall we setup the pool ? */
2986
2987   return TRUE;
2988
2989 get_fmt_failed:
2990   {
2991     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2992         (_("Video device did not provide output format.")), GST_ERROR_SYSTEM);
2993     return FALSE;
2994   }
2995 invalid_dimensions:
2996   {
2997     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2998         (_("Video device returned invalid dimensions.")),
2999         ("Expected non 0 dimensions, got %dx%d", fmt.fmt.pix.width,
3000             fmt.fmt.pix.height));
3001     return FALSE;
3002   }
3003 unsupported_field:
3004   {
3005     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
3006         (_("Video devices uses an unsupported interlacing method.")),
3007         ("V4L2 field type %d not supported", fmt.fmt.pix.field));
3008     return FALSE;
3009   }
3010 unsupported_format:
3011   {
3012     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
3013         (_("Video devices uses an unsupported pixel format.")),
3014         ("V4L2 format %" GST_FOURCC_FORMAT " not supported",
3015             GST_FOURCC_ARGS (fmt.fmt.pix.pixelformat)));
3016     return FALSE;
3017   }
3018 }
3019
3020 gboolean
3021 gst_v4l2_object_set_crop (GstV4l2Object * obj)
3022 {
3023   struct v4l2_crop crop = { 0 };
3024
3025   crop.type = obj->type;
3026   crop.c.left = obj->align.padding_left;
3027   crop.c.top = obj->align.padding_top;
3028   crop.c.width = obj->info.width;
3029   crop.c.height = obj->info.height;
3030
3031   if (obj->align.padding_left + obj->align.padding_top +
3032       obj->align.padding_right + obj->align.padding_bottom == 0) {
3033     GST_DEBUG_OBJECT (obj->element, "no cropping needed");
3034     return TRUE;
3035   }
3036
3037   GST_DEBUG_OBJECT (obj->element,
3038       "Desired cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
3039       crop.c.width, crop.c.height);
3040
3041   if (v4l2_ioctl (obj->video_fd, VIDIOC_S_CROP, &crop) < 0) {
3042     GST_WARNING_OBJECT (obj->element, "VIDIOC_S_CROP failed");
3043     return FALSE;
3044   }
3045
3046   GST_DEBUG_OBJECT (obj->element,
3047       "Got cropping left %u, top %u, size %ux%u", crop.c.left, crop.c.top,
3048       crop.c.width, crop.c.height);
3049
3050   return TRUE;
3051 }
3052
3053 gboolean
3054 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
3055 {
3056   GstStructure *config;
3057   GstCaps *oldcaps;
3058   gboolean ret;
3059
3060   if (!v4l2object->pool)
3061     return FALSE;
3062
3063   config = gst_buffer_pool_get_config (v4l2object->pool);
3064   gst_buffer_pool_config_get_params (config, &oldcaps, NULL, NULL, NULL);
3065
3066   ret = oldcaps && gst_caps_is_equal (caps, oldcaps);
3067
3068   gst_structure_free (config);
3069
3070   return ret;
3071 }
3072
3073 gboolean
3074 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
3075 {
3076   gboolean ret = TRUE;
3077
3078   GST_LOG_OBJECT (v4l2object->element, "start flushing");
3079
3080   if (v4l2object->pool && gst_buffer_pool_is_active (v4l2object->pool))
3081     gst_buffer_pool_set_flushing (v4l2object->pool, TRUE);
3082
3083   return ret;
3084 }
3085
3086 gboolean
3087 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
3088 {
3089   gboolean ret = TRUE;
3090
3091   GST_LOG_OBJECT (v4l2object->element, "stop flushing");
3092
3093   if (v4l2object->pool && gst_buffer_pool_is_active (v4l2object->pool))
3094     gst_buffer_pool_set_flushing (v4l2object->pool, FALSE);
3095
3096   return ret;
3097 }
3098
3099 gboolean
3100 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
3101 {
3102   GST_DEBUG_OBJECT (v4l2object->element, "stopping");
3103
3104   if (!GST_V4L2_IS_OPEN (v4l2object))
3105     goto done;
3106   if (!GST_V4L2_IS_ACTIVE (v4l2object))
3107     goto done;
3108
3109   if (v4l2object->pool) {
3110     GST_DEBUG_OBJECT (v4l2object->element, "deactivating pool");
3111     gst_buffer_pool_set_active (v4l2object->pool, FALSE);
3112     gst_object_unref (v4l2object->pool);
3113     v4l2object->pool = NULL;
3114   }
3115
3116   GST_V4L2_SET_INACTIVE (v4l2object);
3117
3118 done:
3119   return TRUE;
3120 }
3121
3122 GstCaps *
3123 gst_v4l2_object_get_caps (GstV4l2Object * v4l2object, GstCaps * filter)
3124 {
3125   GstCaps *ret;
3126   GSList *walk;
3127   GSList *formats;
3128
3129   if (v4l2object->probed_caps == NULL) {
3130     formats = gst_v4l2_object_get_format_list (v4l2object);
3131
3132     ret = gst_caps_new_empty ();
3133
3134     for (walk = formats; walk; walk = walk->next) {
3135       struct v4l2_fmtdesc *format;
3136       GstStructure *template;
3137
3138       format = (struct v4l2_fmtdesc *) walk->data;
3139
3140       template =
3141           gst_v4l2_object_v4l2fourcc_to_bare_struct (format->pixelformat);
3142
3143       if (template) {
3144         GstCaps *tmp;
3145
3146         tmp = gst_v4l2_object_probe_caps_for_format (v4l2object,
3147             format->pixelformat, template);
3148         if (tmp)
3149           gst_caps_append (ret, tmp);
3150
3151         gst_structure_free (template);
3152       } else {
3153         GST_DEBUG_OBJECT (v4l2object->element, "unknown format %u",
3154             format->pixelformat);
3155       }
3156     }
3157     v4l2object->probed_caps = ret;
3158   }
3159
3160   if (filter) {
3161     ret = gst_caps_intersect_full (filter, v4l2object->probed_caps,
3162         GST_CAPS_INTERSECT_FIRST);
3163   } else {
3164     ret = gst_caps_ref (v4l2object->probed_caps);
3165   }
3166
3167   GST_INFO_OBJECT (v4l2object->element, "probed caps: %" GST_PTR_FORMAT, ret);
3168   LOG_CAPS (v4l2object->element, ret);
3169
3170   return ret;
3171 }
3172
3173 gboolean
3174 gst_v4l2_object_decide_allocation (GstV4l2Object * obj, GstQuery * query)
3175 {
3176   GstCaps *caps;
3177   GstBufferPool *pool = NULL, *other_pool = NULL;
3178   GstStructure *config;
3179   guint size, min, max, own_min = 0;
3180   gboolean update;
3181   gboolean has_video_meta;
3182   gboolean can_share_own_pool, pushing_from_our_pool = FALSE;
3183   struct v4l2_control ctl = { 0, };
3184   GstAllocator *allocator = NULL;
3185   GstAllocationParams params = { 0 };
3186
3187   GST_DEBUG_OBJECT (obj->element, "decide allocation");
3188
3189   g_return_val_if_fail (obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3190       obj->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, FALSE);
3191
3192   gst_query_parse_allocation (query, &caps, NULL);
3193
3194   if (obj->pool == NULL) {
3195     if (!gst_v4l2_object_setup_pool (obj, caps))
3196       goto pool_failed;
3197   }
3198
3199   if (gst_query_get_n_allocation_params (query) > 0)
3200     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
3201
3202   if (gst_query_get_n_allocation_pools (query) > 0) {
3203     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
3204     update = TRUE;
3205   } else {
3206     pool = NULL;
3207     min = max = 0;
3208     size = 0;
3209     update = FALSE;
3210   }
3211
3212   GST_DEBUG_OBJECT (obj->element, "allocation: size:%u min:%u max:%u pool:%"
3213       GST_PTR_FORMAT, size, min, max, pool);
3214
3215   has_video_meta =
3216       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
3217
3218   can_share_own_pool = (has_video_meta || !obj->need_video_meta);
3219
3220   /* Certain driver may expose a minimum through controls */
3221   ctl.id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE;
3222   if (v4l2_ioctl (obj->video_fd, VIDIOC_G_CTRL, &ctl) >= 0) {
3223     GST_DEBUG_OBJECT (obj->element, "driver require a minimum of %d buffers",
3224         ctl.value);
3225     obj->min_buffers = ctl.value;
3226   } else {
3227     obj->min_buffers = 0;
3228   }
3229
3230   /* We can't share our own pool, if it exceed V4L2 capacity */
3231   if (min + obj->min_buffers + 1 > VIDEO_MAX_FRAME)
3232     can_share_own_pool = FALSE;
3233
3234   /* select a pool */
3235   switch (obj->mode) {
3236     case GST_V4L2_IO_RW:
3237       if (pool) {
3238         /* in READ/WRITE mode, prefer a downstream pool because our own pool
3239          * doesn't help much, we have to write to it as well */
3240         GST_DEBUG_OBJECT (obj->element,
3241             "read/write mode: using downstream pool");
3242         /* use the bigest size, when we use our own pool we can't really do any
3243          * other size than what the hardware gives us but for downstream pools
3244          * we can try */
3245         size = MAX (size, obj->info.size);
3246       } else if (can_share_own_pool) {
3247         /* no downstream pool, use our own then */
3248         GST_DEBUG_OBJECT (obj->element,
3249             "read/write mode: no downstream pool, using our own");
3250         pool = gst_object_ref (obj->pool);
3251         size = obj->info.size;
3252         pushing_from_our_pool = TRUE;
3253       }
3254       break;
3255
3256     case GST_V4L2_IO_USERPTR:
3257     case GST_V4L2_IO_DMABUF_IMPORT:
3258       /* in importing mode, prefer our own pool, and pass the other pool to
3259        * our own, so it can serve itself */
3260       if (pool == NULL)
3261         goto no_downstream_pool;
3262       gst_v4l2_buffer_pool_set_other_pool (GST_V4L2_BUFFER_POOL (obj->pool),
3263           pool);
3264       other_pool = pool;
3265       gst_object_unref (pool);
3266       pool = gst_object_ref (obj->pool);
3267       size = obj->info.size;
3268       break;
3269
3270     case GST_V4L2_IO_MMAP:
3271     case GST_V4L2_IO_DMABUF:
3272       /* in streaming mode, prefer our own pool */
3273       /* Check if we can use it ... */
3274       if (can_share_own_pool) {
3275         if (pool)
3276           gst_object_unref (pool);
3277         pool = gst_object_ref (obj->pool);
3278         size = obj->info.size;
3279         GST_DEBUG_OBJECT (obj->element,
3280             "streaming mode: using our own pool %" GST_PTR_FORMAT, pool);
3281         pushing_from_our_pool = TRUE;
3282       } else if (pool) {
3283         GST_DEBUG_OBJECT (obj->element,
3284             "streaming mode: copying to downstream pool %" GST_PTR_FORMAT,
3285             pool);
3286       } else {
3287         GST_DEBUG_OBJECT (obj->element,
3288             "streaming mode: no usable pool, copying to generic pool");
3289         size = MAX (size, obj->info.size);
3290       }
3291       break;
3292     case GST_V4L2_IO_AUTO:
3293     default:
3294       GST_WARNING_OBJECT (obj->element, "unhandled mode");
3295       break;
3296   }
3297
3298   if (size == 0)
3299     goto no_size;
3300
3301   /* If pushing from our own pool, configure it with queried minimum,
3302    * otherwise use the minimum required */
3303   if (pushing_from_our_pool) {
3304     /* When pushing from our own pool, we need what downstream one, to be able
3305      * to fill the pipeline, the minimum required to decoder according to the
3306      * driver and 1 more, so we don't endup up with everything downstream or
3307      * held by the decoder. */
3308     own_min = min + obj->min_buffers + 1;
3309   } else {
3310     /* In this case we'll have to configure two buffer pool. For our buffer
3311      * pool, we'll need what the driver one, and one more, so we can dequeu */
3312     own_min = obj->min_buffers + 1;
3313     own_min = MAX (own_min, GST_V4L2_MIN_BUFFERS);
3314
3315     /* for the downstream pool, we keep what downstream wants, though ensure
3316      * at least a minimum if downstream didn't suggest anything (we are
3317      * expecting the base class to create a default one for the context) */
3318     min = MAX (min, GST_V4L2_MIN_BUFFERS);
3319
3320     /* To import we need the other pool to hold at least own_min */
3321     if (obj->pool == pool)
3322       min += own_min;
3323   }
3324
3325   /* Request a bigger max, if one was suggested but it's too small */
3326   if (max != 0)
3327     max = MAX (min, max);
3328
3329   /* First step, configure our own pool */
3330   config = gst_buffer_pool_get_config (obj->pool);
3331
3332   if (obj->need_video_meta || has_video_meta) {
3333     GST_DEBUG_OBJECT (obj->element, "activate Video Meta");
3334     gst_buffer_pool_config_add_option (config,
3335         GST_BUFFER_POOL_OPTION_VIDEO_META);
3336   }
3337
3338   gst_buffer_pool_config_set_allocator (config, allocator, &params);
3339   gst_buffer_pool_config_set_params (config, caps, size, own_min, 0);
3340
3341   GST_DEBUG_OBJECT (obj->element, "setting own pool config to %"
3342       GST_PTR_FORMAT, config);
3343
3344   /* Our pool often need to adjust the value */
3345   if (!gst_buffer_pool_set_config (obj->pool, config)) {
3346     config = gst_buffer_pool_get_config (obj->pool);
3347
3348     GST_DEBUG_OBJECT (obj->element, "own pool config changed to %"
3349         GST_PTR_FORMAT, config);
3350
3351     /* our pool will adjust the maximum buffer, which we are fine with */
3352     if (!gst_buffer_pool_set_config (obj->pool, config))
3353       goto config_failed;
3354   }
3355
3356   /* Now configure the other pool if different */
3357   if (obj->pool != pool)
3358     other_pool = pool;
3359
3360   if (other_pool) {
3361     config = gst_buffer_pool_get_config (other_pool);
3362     gst_buffer_pool_config_set_allocator (config, allocator, &params);
3363     gst_buffer_pool_config_set_params (config, caps, size, min, max);
3364
3365     GST_DEBUG_OBJECT (obj->element, "setting other pool config to %"
3366         GST_PTR_FORMAT, config);
3367
3368     /* if downstream supports video metadata, add this to the pool config */
3369     if (has_video_meta) {
3370       GST_DEBUG_OBJECT (obj->element, "activate Video Meta");
3371       gst_buffer_pool_config_add_option (config,
3372           GST_BUFFER_POOL_OPTION_VIDEO_META);
3373     }
3374
3375     if (!gst_buffer_pool_set_config (other_pool, config)) {
3376       config = gst_buffer_pool_get_config (other_pool);
3377
3378       if (!gst_buffer_pool_config_validate_params (config, caps, size, min,
3379               max)) {
3380         gst_structure_free (config);
3381         goto config_failed;
3382       }
3383
3384       if (!gst_buffer_pool_set_config (other_pool, config))
3385         goto config_failed;
3386     }
3387   }
3388
3389   if (pool) {
3390     /* For simplicity, simply read back the active configuration, so our base
3391      * class get the right information */
3392     config = gst_buffer_pool_get_config (pool);
3393     gst_buffer_pool_config_get_params (config, NULL, &size, &min, &max);
3394     gst_structure_free (config);
3395   }
3396
3397   if (update)
3398     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
3399   else
3400     gst_query_add_allocation_pool (query, pool, size, min, max);
3401
3402   if (allocator)
3403     gst_object_unref (allocator);
3404
3405   if (pool)
3406     gst_object_unref (pool);
3407
3408   return TRUE;
3409
3410 pool_failed:
3411   {
3412     /* setup_pool already send the error */
3413     goto cleanup;
3414   }
3415 config_failed:
3416   {
3417     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
3418         (_("Failed to configure internal buffer pool.")), (NULL));
3419     goto cleanup;
3420   }
3421 no_size:
3422   {
3423     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
3424         (_("Video device did not suggest any buffer size.")), (NULL));
3425     goto cleanup;
3426   }
3427 cleanup:
3428   {
3429     if (allocator)
3430       gst_object_unref (allocator);
3431
3432     if (pool)
3433       gst_object_unref (pool);
3434     return FALSE;
3435   }
3436 no_downstream_pool:
3437   {
3438     GST_ELEMENT_ERROR (obj->element, RESOURCE, SETTINGS,
3439         (_("No downstream pool to import from.")),
3440         ("When importing DMABUF or USERPTR, we need a pool to import from"));
3441     return FALSE;
3442   }
3443 }
3444
3445 gboolean
3446 gst_v4l2_object_propose_allocation (GstV4l2Object * obj, GstQuery * query)
3447 {
3448   GstBufferPool *pool;
3449   /* we need at least 2 buffers to operate */
3450   guint size, min, max;
3451   GstCaps *caps;
3452   gboolean need_pool;
3453   struct v4l2_control ctl = { 0, };
3454
3455   /* Set defaults allocation parameters */
3456   size = obj->info.size;
3457   min = GST_V4L2_MIN_BUFFERS;
3458   max = VIDEO_MAX_FRAME;
3459
3460   gst_query_parse_allocation (query, &caps, &need_pool);
3461
3462   if (caps == NULL)
3463     goto no_caps;
3464
3465   if ((pool = obj->pool))
3466     gst_object_ref (pool);
3467
3468   if (pool != NULL) {
3469     GstCaps *pcaps;
3470     GstStructure *config;
3471
3472     /* we had a pool, check caps */
3473     config = gst_buffer_pool_get_config (pool);
3474     gst_buffer_pool_config_get_params (config, &pcaps, NULL, NULL, NULL);
3475
3476     GST_DEBUG_OBJECT (obj->element,
3477         "we had a pool with caps %" GST_PTR_FORMAT, pcaps);
3478     if (!gst_caps_is_equal (caps, pcaps)) {
3479       gst_structure_free (config);
3480       gst_object_unref (pool);
3481       goto different_caps;
3482     }
3483     gst_structure_free (config);
3484   }
3485
3486   /* Some devices may expose a minimum */
3487   ctl.id = V4L2_CID_MIN_BUFFERS_FOR_OUTPUT;
3488   if (v4l2_ioctl (obj->video_fd, VIDIOC_G_CTRL, &ctl) >= 0) {
3489     GST_DEBUG_OBJECT (obj->element, "driver require a miminum of %d buffers",
3490         ctl.value);
3491     obj->min_buffers = ctl.value;
3492   } else {
3493     obj->min_buffers = 0;
3494   }
3495
3496   min = MAX (obj->min_buffers, GST_V4L2_MIN_BUFFERS);
3497
3498   gst_query_add_allocation_pool (query, pool, size, min, max);
3499
3500   /* we also support various metadata */
3501   gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
3502
3503   if (pool)
3504     gst_object_unref (pool);
3505
3506   return TRUE;
3507
3508   /* ERRORS */
3509 no_caps:
3510   {
3511     GST_DEBUG_OBJECT (obj->element, "no caps specified");
3512     return FALSE;
3513   }
3514 different_caps:
3515   {
3516     /* different caps, we can't use this pool */
3517     GST_DEBUG_OBJECT (obj->element, "pool has different caps");
3518     return FALSE;
3519   }
3520 }