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