v4l2: don't extract data from caps twice
[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 #ifdef HAVE_XVIDEO
42 #include "gstv4l2videooverlay.h"
43 #endif
44 #include "gstv4l2colorbalance.h"
45
46 #include "gst/gst-i18n-plugin.h"
47
48 #include <gst/video/video.h>
49
50 /* videodev2.h is not versioned and we can't easily check for the presence
51  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
52  * was added in the same commit as V4L2_FIELD_INTERLACED_{TB,BT} (b2787845) */
53 #ifndef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
54 #define V4L2_FIELD_INTERLACED_TB 8
55 #define V4L2_FIELD_INTERLACED_BT 9
56 #endif
57
58 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
59 GST_DEBUG_CATEGORY_EXTERN (GST_CAT_PERFORMANCE);
60 #define GST_CAT_DEFAULT v4l2_debug
61
62 #define DEFAULT_PROP_DEVICE_NAME        NULL
63 #define DEFAULT_PROP_DEVICE_FD          -1
64 #define DEFAULT_PROP_FLAGS              0
65 #define DEFAULT_PROP_TV_NORM            0
66 #define DEFAULT_PROP_CHANNEL            NULL
67 #define DEFAULT_PROP_FREQUENCY          0
68 #define DEFAULT_PROP_IO_MODE            GST_V4L2_IO_AUTO
69
70 enum
71 {
72   PROP_0,
73   V4L2_STD_OBJECT_PROPS,
74 };
75
76 #if 0
77 G_LOCK_DEFINE_STATIC (probe_lock);
78
79 const GList *
80 gst_v4l2_probe_get_properties (GstPropertyProbe * probe)
81 {
82   GObjectClass *klass = G_OBJECT_GET_CLASS (probe);
83   static GList *list = NULL;
84
85   G_LOCK (probe_lock);
86
87   if (!list) {
88     list = g_list_append (NULL, g_object_class_find_property (klass, "device"));
89   }
90
91   G_UNLOCK (probe_lock);
92
93   return list;
94 }
95
96 static gboolean init = FALSE;
97 static GList *devices = NULL;
98
99 #ifdef HAVE_GUDEV
100 static gboolean
101 gst_v4l2_class_probe_devices_with_udev (GstElementClass * klass, gboolean check,
102     GList ** klass_devices)
103 {
104   GUdevClient *client = NULL;
105   GList *item;
106
107   if (!check) {
108     while (devices) {
109       gchar *device = devices->data;
110       devices = g_list_remove (devices, device);
111       g_free (device);
112     }
113
114     GST_INFO ("Enumerating video4linux devices from udev");
115     client = g_udev_client_new (NULL);
116     if (!client) {
117       GST_WARNING ("Failed to initialize gudev client");
118       goto finish;
119     }
120
121     item = g_udev_client_query_by_subsystem (client, "video4linux");
122     while (item) {
123       GUdevDevice *device = item->data;
124       gchar *devnode = g_strdup (g_udev_device_get_device_file (device));
125       gint api = g_udev_device_get_property_as_int (device, "ID_V4L_VERSION");
126       GST_INFO ("Found new device: %s, API: %d", devnode, api);
127       /* Append v4l2 devices only. If api is 0 probably v4l_id has
128          been stripped out of the current udev installation, append
129          anyway */
130       if (api == 0) {
131         GST_WARNING
132             ("Couldn't retrieve ID_V4L_VERSION, silly udev installation?");
133       }
134       if ((api == 2 || api == 0)) {
135         devices = g_list_append (devices, devnode);
136       } else {
137         g_free (devnode);
138       }
139       g_object_unref (device);
140       item = item->next;
141     }
142     g_list_free (item);
143     init = TRUE;
144   }
145
146 finish:
147   if (client) {
148     g_object_unref (client);
149   }
150
151   *klass_devices = devices;
152
153   return init;
154 }
155 #endif /* HAVE_GUDEV */
156
157 static gboolean
158 gst_v4l2_class_probe_devices (GstElementClass * klass, gboolean check,
159     GList ** klass_devices)
160 {
161   if (!check) {
162     const gchar *dev_base[] = { "/dev/video", "/dev/v4l2/video", NULL };
163     gint base, n, fd;
164
165     while (devices) {
166       gchar *device = devices->data;
167       devices = g_list_remove (devices, device);
168       g_free (device);
169     }
170
171     /*
172      * detect /dev entries
173      */
174     for (n = 0; n < 64; n++) {
175       for (base = 0; dev_base[base] != NULL; base++) {
176         struct stat s;
177         gchar *device = g_strdup_printf ("%s%d",
178             dev_base[base],
179             n);
180
181         /*
182          * does the /dev/ entry exist at all?
183          */
184         if (stat (device, &s) == 0) {
185           /*
186            * yes: is a device attached?
187            */
188           if (S_ISCHR (s.st_mode)) {
189
190             if ((fd = open (device, O_RDWR | O_NONBLOCK)) > 0 || errno == EBUSY) {
191               if (fd > 0)
192                 close (fd);
193
194               devices = g_list_append (devices, device);
195               break;
196             }
197           }
198         }
199         g_free (device);
200       }
201     }
202     init = TRUE;
203   }
204
205   *klass_devices = devices;
206
207   return init;
208 }
209
210 void
211 gst_v4l2_probe_probe_property (GstPropertyProbe * probe,
212     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
213 {
214   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
215
216   switch (prop_id) {
217     case PROP_DEVICE:
218 #ifdef HAVE_GUDEV
219       if (!gst_v4l2_class_probe_devices_with_udev (klass, FALSE, klass_devices))
220         gst_v4l2_class_probe_devices (klass, FALSE, klass_devices);
221 #else /* !HAVE_GUDEV */
222       gst_v4l2_class_probe_devices (klass, FALSE, klass_devices);
223 #endif /* HAVE_GUDEV */
224       break;
225     default:
226       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
227       break;
228   }
229 }
230
231 gboolean
232 gst_v4l2_probe_needs_probe (GstPropertyProbe * probe,
233     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
234 {
235   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
236   gboolean ret = FALSE;
237
238   switch (prop_id) {
239     case PROP_DEVICE:
240 #ifdef HAVE_GUDEV
241       ret =
242           !gst_v4l2_class_probe_devices_with_udev (klass, FALSE, klass_devices);
243 #else /* !HAVE_GUDEV */
244       ret = !gst_v4l2_class_probe_devices (klass, TRUE, klass_devices);
245 #endif /* HAVE_GUDEV */
246       break;
247     default:
248       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
249       break;
250   }
251   return ret;
252 }
253
254 static GValueArray *
255 gst_v4l2_class_list_devices (GstElementClass * klass, GList ** klass_devices)
256 {
257   GValueArray *array;
258   GValue value = { 0 };
259   GList *item;
260
261   if (!*klass_devices)
262     return NULL;
263
264   array = g_value_array_new (g_list_length (*klass_devices));
265   item = *klass_devices;
266   g_value_init (&value, G_TYPE_STRING);
267   while (item) {
268     gchar *device = item->data;
269
270     g_value_set_string (&value, device);
271     g_value_array_append (array, &value);
272
273     item = item->next;
274   }
275   g_value_unset (&value);
276
277   return array;
278 }
279
280 GValueArray *
281 gst_v4l2_probe_get_values (GstPropertyProbe * probe,
282     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
283 {
284   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
285   GValueArray *array = NULL;
286
287   switch (prop_id) {
288     case PROP_DEVICE:
289       array = gst_v4l2_class_list_devices (klass, klass_devices);
290       break;
291     default:
292       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
293       break;
294   }
295
296   return array;
297 }
298 #endif
299
300 #define GST_TYPE_V4L2_DEVICE_FLAGS (gst_v4l2_device_get_type ())
301 static GType
302 gst_v4l2_device_get_type (void)
303 {
304   static GType v4l2_device_type = 0;
305
306   if (v4l2_device_type == 0) {
307     static const GFlagsValue values[] = {
308       {V4L2_CAP_VIDEO_CAPTURE, "Device supports video capture", "capture"},
309       {V4L2_CAP_VIDEO_OUTPUT, "Device supports video playback", "output"},
310       {V4L2_CAP_VIDEO_OVERLAY, "Device supports video overlay", "overlay"},
311
312       {V4L2_CAP_VBI_CAPTURE, "Device supports the VBI capture", "vbi-capture"},
313       {V4L2_CAP_VBI_OUTPUT, "Device supports the VBI output", "vbi-output"},
314
315       {V4L2_CAP_TUNER, "Device has a tuner or modulator", "tuner"},
316       {V4L2_CAP_AUDIO, "Device has audio inputs or outputs", "audio"},
317
318       {0, NULL, NULL}
319     };
320
321     v4l2_device_type =
322         g_flags_register_static ("GstV4l2DeviceTypeFlags", values);
323   }
324
325   return v4l2_device_type;
326 }
327
328 #define GST_TYPE_V4L2_TV_NORM (gst_v4l2_tv_norm_get_type ())
329 static GType
330 gst_v4l2_tv_norm_get_type (void)
331 {
332   static GType v4l2_tv_norm = 0;
333
334   if (!v4l2_tv_norm) {
335     static const GEnumValue tv_norms[] = {
336       {0, "none", "none"},
337
338       {V4L2_STD_NTSC, "NTSC", "NTSC"},
339       {V4L2_STD_NTSC_M, "NTSC-M", "NTSC-M"},
340       {V4L2_STD_NTSC_M_JP, "NTSC-M-JP", "NTSC-M-JP"},
341       {V4L2_STD_NTSC_M_KR, "NTSC-M-KR", "NTSC-M-KR"},
342       {V4L2_STD_NTSC_443, "NTSC-443", "NTSC-443"},
343
344       {V4L2_STD_PAL, "PAL", "PAL"},
345       {V4L2_STD_PAL_BG, "PAL-BG", "PAL-BG"},
346       {V4L2_STD_PAL_B, "PAL-B", "PAL-B"},
347       {V4L2_STD_PAL_B1, "PAL-B1", "PAL-B1"},
348       {V4L2_STD_PAL_G, "PAL-G", "PAL-G"},
349       {V4L2_STD_PAL_H, "PAL-H", "PAL-H"},
350       {V4L2_STD_PAL_I, "PAL-I", "PAL-I"},
351       {V4L2_STD_PAL_DK, "PAL-DK", "PAL-DK"},
352       {V4L2_STD_PAL_D, "PAL-D", "PAL-D"},
353       {V4L2_STD_PAL_D1, "PAL-D1", "PAL-D1"},
354       {V4L2_STD_PAL_K, "PAL-K", "PAL-K"},
355       {V4L2_STD_PAL_M, "PAL-M", "PAL-M"},
356       {V4L2_STD_PAL_N, "PAL-N", "PAL-N"},
357       {V4L2_STD_PAL_Nc, "PAL-Nc", "PAL-Nc"},
358       {V4L2_STD_PAL_60, "PAL-60", "PAL-60"},
359
360       {V4L2_STD_SECAM, "SECAM", "SECAM"},
361       {V4L2_STD_SECAM_B, "SECAM-B", "SECAM-B"},
362       {V4L2_STD_SECAM_G, "SECAM-G", "SECAM-G"},
363       {V4L2_STD_SECAM_H, "SECAM-H", "SECAM-H"},
364       {V4L2_STD_SECAM_DK, "SECAM-DK", "SECAM-DK"},
365       {V4L2_STD_SECAM_D, "SECAM-D", "SECAM-D"},
366       {V4L2_STD_SECAM_K, "SECAM-K", "SECAM-K"},
367       {V4L2_STD_SECAM_K1, "SECAM-K1", "SECAM-K1"},
368       {V4L2_STD_SECAM_L, "SECAM-L", "SECAM-L"},
369       {V4L2_STD_SECAM_LC, "SECAM-Lc", "SECAM-Lc"},
370
371       {0, NULL, NULL}
372     };
373
374     v4l2_tv_norm = g_enum_register_static ("V4L2_TV_norms", tv_norms);
375   }
376
377   return v4l2_tv_norm;
378 }
379
380 #define GST_TYPE_V4L2_IO_MODE (gst_v4l2_io_mode_get_type ())
381 static GType
382 gst_v4l2_io_mode_get_type (void)
383 {
384   static GType v4l2_io_mode = 0;
385
386   if (!v4l2_io_mode) {
387     static const GEnumValue io_modes[] = {
388       {GST_V4L2_IO_AUTO, "GST_V4L2_IO_AUTO", "auto"},
389       {GST_V4L2_IO_RW, "GST_V4L2_IO_RW", "rw"},
390       {GST_V4L2_IO_MMAP, "GST_V4L2_IO_MMAP", "mmap"},
391       {GST_V4L2_IO_USERPTR, "GST_V4L2_IO_USERPTR", "userptr"},
392       {GST_V4L2_IO_DMABUF, "GST_V4L2_IO_DMABUF", "dmabuf"},
393
394       {0, NULL, NULL}
395     };
396     v4l2_io_mode = g_enum_register_static ("GstV4l2IOMode", io_modes);
397   }
398   return v4l2_io_mode;
399 }
400
401 void
402 gst_v4l2_object_install_properties_helper (GObjectClass * gobject_class,
403     const char *default_device)
404 {
405   g_object_class_install_property (gobject_class, PROP_DEVICE,
406       g_param_spec_string ("device", "Device", "Device location",
407           default_device, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
408   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
409       g_param_spec_string ("device-name", "Device name",
410           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
411           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
412   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
413       g_param_spec_int ("device-fd", "File descriptor",
414           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
415           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
416   g_object_class_install_property (gobject_class, PROP_FLAGS,
417       g_param_spec_flags ("flags", "Flags", "Device type flags",
418           GST_TYPE_V4L2_DEVICE_FLAGS, DEFAULT_PROP_FLAGS,
419           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
420
421   /**
422    * GstV4l2Src:brightness
423    *
424    * Picture brightness, or more precisely, the black level
425    *
426    * Since: 0.10.26
427    */
428   g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
429       g_param_spec_int ("brightness", "Brightness",
430           "Picture brightness, or more precisely, the black level", G_MININT,
431           G_MAXINT, 0,
432           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
433   /**
434    * GstV4l2Src:contrast
435    *
436    * Picture contrast or luma gain
437    *
438    * Since: 0.10.26
439    */
440   g_object_class_install_property (gobject_class, PROP_CONTRAST,
441       g_param_spec_int ("contrast", "Contrast",
442           "Picture contrast or luma gain", G_MININT,
443           G_MAXINT, 0,
444           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
445   /**
446    * GstV4l2Src:saturation
447    *
448    * Picture color saturation or chroma gain
449    *
450    * Since: 0.10.26
451    */
452   g_object_class_install_property (gobject_class, PROP_SATURATION,
453       g_param_spec_int ("saturation", "Saturation",
454           "Picture color saturation or chroma gain", G_MININT,
455           G_MAXINT, 0,
456           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
457   /**
458    * GstV4l2Src:hue
459    *
460    * Hue or color balance
461    *
462    * Since: 0.10.26
463    */
464   g_object_class_install_property (gobject_class, PROP_HUE,
465       g_param_spec_int ("hue", "Hue",
466           "Hue or color balance", G_MININT,
467           G_MAXINT, 0,
468           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
469
470   /**
471    * GstV4l2Src:norm
472    *
473    * TV norm
474    *
475    * Since: 0.10.31
476    */
477   g_object_class_install_property (gobject_class, PROP_TV_NORM,
478       g_param_spec_enum ("norm", "TV norm",
479           "video standard",
480           GST_TYPE_V4L2_TV_NORM, DEFAULT_PROP_TV_NORM,
481           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
482
483   /**
484    * GstV4l2Src:io-mode
485    *
486    * IO Mode
487    */
488   g_object_class_install_property (gobject_class, PROP_IO_MODE,
489       g_param_spec_enum ("io-mode", "IO mode",
490           "I/O mode",
491           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
492           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
493
494   /**
495    * GstV4l2Src:extra-controls
496    *
497    * Additional v4l2 controls for the device. The controls are identified
498    * by the control name (lowercase with '_' for any non-alphanumeric
499    * characters).
500    *
501    * Since: 1.2
502    */
503   g_object_class_install_property (gobject_class, PROP_EXTRA_CONTROLS,
504       g_param_spec_boxed ("extra-controls", "Extra Controls",
505           "Extra v4l2 controls (CIDs) for the device",
506           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
507
508   /**
509    * GstV4l2Src:pixel-aspect-ratio
510    *
511    * The pixel aspect ratio of the device. This overwrites the pixel aspect
512    * ratio queried from the device.
513    *
514    * Since: 1.2
515    */
516   g_object_class_install_property (gobject_class, PROP_PIXEL_ASPECT_RATIO,
517       g_param_spec_string ("pixel-aspect-ratio", "Pixel Aspect Ratio",
518           "Overwrite the pixel aspect ratio of the device", "1/1",
519           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
520
521   /**
522    * GstV4l2Src:force-aspect-ratio
523    *
524    * When enabled, the pixel aspect ratio queried from the device or set
525    * with the pixel-aspect-ratio property will be enforced.
526    *
527    * Since: 1.2
528    */
529   g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
530       g_param_spec_boolean ("force-aspect-ratio", "Force aspect ratio",
531           "When enabled, the pixel aspect ratio will be enforced", TRUE,
532           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
533
534 }
535
536 GstV4l2Object *
537 gst_v4l2_object_new (GstElement * element,
538     enum v4l2_buf_type type,
539     const char *default_device,
540     GstV4l2GetInOutFunction get_in_out_func,
541     GstV4l2SetInOutFunction set_in_out_func,
542     GstV4l2UpdateFpsFunction update_fps_func)
543 {
544   GstV4l2Object *v4l2object;
545
546   /*
547    * some default values
548    */
549   v4l2object = g_new0 (GstV4l2Object, 1);
550
551   v4l2object->type = type;
552   v4l2object->formats = NULL;
553
554   v4l2object->element = element;
555   v4l2object->get_in_out_func = get_in_out_func;
556   v4l2object->set_in_out_func = set_in_out_func;
557   v4l2object->update_fps_func = update_fps_func;
558
559   v4l2object->video_fd = -1;
560   v4l2object->poll = gst_poll_new (TRUE);
561   v4l2object->active = FALSE;
562   v4l2object->videodev = g_strdup (default_device);
563
564   v4l2object->norms = NULL;
565   v4l2object->channels = NULL;
566   v4l2object->colors = NULL;
567
568   v4l2object->xwindow_id = 0;
569
570   v4l2object->keep_aspect = TRUE;
571
572   return v4l2object;
573 }
574
575 static gboolean gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object);
576
577
578 void
579 gst_v4l2_object_destroy (GstV4l2Object * v4l2object)
580 {
581   g_return_if_fail (v4l2object != NULL);
582
583   if (v4l2object->videodev)
584     g_free (v4l2object->videodev);
585
586   if (v4l2object->poll)
587     gst_poll_free (v4l2object->poll);
588
589   if (v4l2object->channel)
590     g_free (v4l2object->channel);
591
592   if (v4l2object->formats) {
593     gst_v4l2_object_clear_format_list (v4l2object);
594   }
595
596   g_free (v4l2object);
597 }
598
599
600 static gboolean
601 gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object)
602 {
603   g_slist_foreach (v4l2object->formats, (GFunc) g_free, NULL);
604   g_slist_free (v4l2object->formats);
605   v4l2object->formats = NULL;
606
607   return TRUE;
608 }
609
610 static gint
611 gst_v4l2_object_prop_to_cid (guint prop_id)
612 {
613   gint cid = -1;
614
615   switch (prop_id) {
616     case PROP_BRIGHTNESS:
617       cid = V4L2_CID_BRIGHTNESS;
618       break;
619     case PROP_CONTRAST:
620       cid = V4L2_CID_CONTRAST;
621       break;
622     case PROP_SATURATION:
623       cid = V4L2_CID_SATURATION;
624       break;
625     case PROP_HUE:
626       cid = V4L2_CID_HUE;
627       break;
628     default:
629       GST_WARNING ("unmapped property id: %d", prop_id);
630   }
631   return cid;
632 }
633
634
635 gboolean
636 gst_v4l2_object_set_property_helper (GstV4l2Object * v4l2object,
637     guint prop_id, const GValue * value, GParamSpec * pspec)
638 {
639   switch (prop_id) {
640     case PROP_DEVICE:
641       g_free (v4l2object->videodev);
642       v4l2object->videodev = g_value_dup_string (value);
643       break;
644     case PROP_BRIGHTNESS:
645     case PROP_CONTRAST:
646     case PROP_SATURATION:
647     case PROP_HUE:
648     {
649       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
650
651       if (cid != -1) {
652         if (GST_V4L2_IS_OPEN (v4l2object)) {
653           gst_v4l2_set_attribute (v4l2object, cid, g_value_get_int (value));
654         }
655       }
656       return TRUE;
657     }
658       break;
659     case PROP_TV_NORM:
660       v4l2object->tv_norm = g_value_get_enum (value);
661       break;
662 #if 0
663     case PROP_CHANNEL:
664       if (GST_V4L2_IS_OPEN (v4l2object)) {
665         GstTuner *tuner = GST_TUNER (v4l2object->element);
666         GstTunerChannel *channel = gst_tuner_find_channel_by_name (tuner,
667             (gchar *) g_value_get_string (value));
668
669         if (channel) {
670           /* like gst_tuner_set_channel (tuner, channel)
671              without g_object_notify */
672           gst_v4l2_tuner_set_channel (v4l2object, channel);
673         }
674       } else {
675         g_free (v4l2object->channel);
676         v4l2object->channel = g_value_dup_string (value);
677       }
678       break;
679     case PROP_FREQUENCY:
680       if (GST_V4L2_IS_OPEN (v4l2object)) {
681         GstTuner *tuner = GST_TUNER (v4l2object->element);
682         GstTunerChannel *channel = gst_tuner_get_channel (tuner);
683
684         if (channel &&
685             GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
686           /* like
687              gst_tuner_set_frequency (tuner, channel, g_value_get_ulong (value))
688              without g_object_notify */
689           gst_v4l2_tuner_set_frequency (v4l2object, channel,
690               g_value_get_ulong (value));
691         }
692       } else {
693         v4l2object->frequency = g_value_get_ulong (value);
694       }
695       break;
696 #endif
697     case PROP_IO_MODE:
698       v4l2object->req_mode = g_value_get_enum (value);
699       break;
700     case PROP_EXTRA_CONTROLS:{
701       const GstStructure *s = gst_value_get_structure (value);
702
703       if (v4l2object->extra_controls)
704         gst_structure_free (v4l2object->extra_controls);
705
706       v4l2object->extra_controls = s ? gst_structure_copy (s) : NULL;
707       if (GST_V4L2_IS_OPEN (v4l2object))
708         gst_v4l2_set_controls (v4l2object, v4l2object->extra_controls);
709       break;
710     }
711     case PROP_PIXEL_ASPECT_RATIO:
712       g_free (v4l2object->par);
713       v4l2object->par = g_new0 (GValue, 1);
714       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
715       if (!g_value_transform (value, v4l2object->par)) {
716         g_warning ("Could not transform string to aspect ratio");
717         gst_value_set_fraction (v4l2object->par, 1, 1);
718       }
719       GST_DEBUG_OBJECT (v4l2object->element, "set PAR to %d/%d",
720           gst_value_get_fraction_numerator (v4l2object->par),
721           gst_value_get_fraction_denominator (v4l2object->par));
722       break;
723     case PROP_FORCE_ASPECT_RATIO:
724       v4l2object->keep_aspect = g_value_get_boolean (value);
725       break;
726     default:
727       return FALSE;
728       break;
729   }
730   return TRUE;
731 }
732
733
734 gboolean
735 gst_v4l2_object_get_property_helper (GstV4l2Object * v4l2object,
736     guint prop_id, GValue * value, GParamSpec * pspec)
737 {
738   switch (prop_id) {
739     case PROP_DEVICE:
740       g_value_set_string (value, v4l2object->videodev);
741       break;
742     case PROP_DEVICE_NAME:
743     {
744       const guchar *new = NULL;
745
746       if (GST_V4L2_IS_OPEN (v4l2object)) {
747         new = v4l2object->vcap.card;
748       } else if (gst_v4l2_open (v4l2object)) {
749         new = v4l2object->vcap.card;
750         gst_v4l2_close (v4l2object);
751       }
752       g_value_set_string (value, (gchar *) new);
753       break;
754     }
755     case PROP_DEVICE_FD:
756     {
757       if (GST_V4L2_IS_OPEN (v4l2object))
758         g_value_set_int (value, v4l2object->video_fd);
759       else
760         g_value_set_int (value, DEFAULT_PROP_DEVICE_FD);
761       break;
762     }
763     case PROP_FLAGS:
764     {
765       guint flags = 0;
766
767       if (GST_V4L2_IS_OPEN (v4l2object)) {
768         flags |= v4l2object->vcap.capabilities &
769             (V4L2_CAP_VIDEO_CAPTURE |
770             V4L2_CAP_VIDEO_OUTPUT |
771             V4L2_CAP_VIDEO_OVERLAY |
772             V4L2_CAP_VBI_CAPTURE |
773             V4L2_CAP_VBI_OUTPUT | V4L2_CAP_TUNER | V4L2_CAP_AUDIO);
774       }
775       g_value_set_flags (value, flags);
776       break;
777     }
778     case PROP_BRIGHTNESS:
779     case PROP_CONTRAST:
780     case PROP_SATURATION:
781     case PROP_HUE:
782     {
783       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
784
785       if (cid != -1) {
786         if (GST_V4L2_IS_OPEN (v4l2object)) {
787           gint v;
788           if (gst_v4l2_get_attribute (v4l2object, cid, &v)) {
789             g_value_set_int (value, v);
790           }
791         }
792       }
793       return TRUE;
794     }
795       break;
796     case PROP_TV_NORM:
797       g_value_set_enum (value, v4l2object->tv_norm);
798       break;
799     case PROP_IO_MODE:
800       g_value_set_enum (value, v4l2object->req_mode);
801       break;
802     case PROP_EXTRA_CONTROLS:
803       gst_value_set_structure (value, v4l2object->extra_controls);
804       break;
805     case PROP_PIXEL_ASPECT_RATIO:
806       if (v4l2object->par)
807         g_value_transform (v4l2object->par, value);
808       break;
809     case PROP_FORCE_ASPECT_RATIO:
810       g_value_set_boolean (value, v4l2object->keep_aspect);
811       break;
812     default:
813       return FALSE;
814       break;
815   }
816   return TRUE;
817 }
818
819 static void
820 gst_v4l2_set_defaults (GstV4l2Object * v4l2object)
821 {
822   GstTunerNorm *norm = NULL;
823   GstTunerChannel *channel = NULL;
824   GstTuner *tuner;
825
826   if (!GST_IS_TUNER (v4l2object->element))
827     return;
828
829   tuner = GST_TUNER (v4l2object->element);
830
831   if (v4l2object->tv_norm)
832     norm = gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
833   GST_DEBUG_OBJECT (v4l2object->element, "tv_norm=0x%" G_GINT64_MODIFIER "x, "
834       "norm=%p", (guint64) v4l2object->tv_norm, norm);
835   if (norm) {
836     gst_tuner_set_norm (tuner, norm);
837   } else {
838     norm =
839         GST_TUNER_NORM (gst_tuner_get_norm (GST_TUNER (v4l2object->element)));
840     if (norm) {
841       v4l2object->tv_norm =
842           gst_v4l2_tuner_get_std_id_by_norm (v4l2object, norm);
843       gst_tuner_norm_changed (tuner, norm);
844     }
845   }
846
847   if (v4l2object->channel)
848     channel = gst_tuner_find_channel_by_name (tuner, v4l2object->channel);
849   if (channel) {
850     gst_tuner_set_channel (tuner, channel);
851   } else {
852     channel =
853         GST_TUNER_CHANNEL (gst_tuner_get_channel (GST_TUNER
854             (v4l2object->element)));
855     if (channel) {
856       g_free (v4l2object->channel);
857       v4l2object->channel = g_strdup (channel->label);
858       gst_tuner_channel_changed (tuner, channel);
859     }
860   }
861
862   if (channel
863       && GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
864     if (v4l2object->frequency != 0) {
865       gst_tuner_set_frequency (tuner, channel, v4l2object->frequency);
866     } else {
867       v4l2object->frequency = gst_tuner_get_frequency (tuner, channel);
868       if (v4l2object->frequency == 0) {
869         /* guess */
870         gst_tuner_set_frequency (tuner, channel, 1000);
871       } else {
872       }
873     }
874   }
875 }
876
877 gboolean
878 gst_v4l2_object_open (GstV4l2Object * v4l2object)
879 {
880   if (gst_v4l2_open (v4l2object))
881     gst_v4l2_set_defaults (v4l2object);
882   else
883     return FALSE;
884
885 #ifdef HAVE_XVIDEO
886   gst_v4l2_video_overlay_start (v4l2object);
887 #endif
888
889   return TRUE;
890 }
891
892 gboolean
893 gst_v4l2_object_close (GstV4l2Object * v4l2object)
894 {
895 #ifdef HAVE_XVIDEO
896   gst_v4l2_video_overlay_stop (v4l2object);
897 #endif
898
899   if (!gst_v4l2_close (v4l2object))
900     return FALSE;
901
902   if (v4l2object->formats) {
903     gst_v4l2_object_clear_format_list (v4l2object);
904   }
905
906   return TRUE;
907 }
908
909
910 /*
911  * common format / caps utilities:
912  */
913 typedef struct
914 {
915   guint32 format;
916   gboolean dimensions;
917 } GstV4L2FormatDesc;
918
919 static const GstV4L2FormatDesc gst_v4l2_formats[] = {
920   /* from Linux 2.6.15 videodev2.h */
921   {V4L2_PIX_FMT_RGB332, TRUE},
922   {V4L2_PIX_FMT_RGB555, TRUE},
923   {V4L2_PIX_FMT_RGB565, TRUE},
924   {V4L2_PIX_FMT_RGB555X, TRUE},
925   {V4L2_PIX_FMT_RGB565X, TRUE},
926   {V4L2_PIX_FMT_BGR24, TRUE},
927   {V4L2_PIX_FMT_RGB24, TRUE},
928   {V4L2_PIX_FMT_BGR32, TRUE},
929   {V4L2_PIX_FMT_RGB32, TRUE},
930   {V4L2_PIX_FMT_GREY, TRUE},
931   {V4L2_PIX_FMT_YVU410, TRUE},
932   {V4L2_PIX_FMT_YVU420, TRUE},
933   {V4L2_PIX_FMT_YUYV, TRUE},
934   {V4L2_PIX_FMT_UYVY, TRUE},
935   {V4L2_PIX_FMT_YUV422P, TRUE},
936   {V4L2_PIX_FMT_YUV411P, TRUE},
937   {V4L2_PIX_FMT_Y41P, TRUE},
938
939   /* two planes -- one Y, one Cr + Cb interleaved  */
940   {V4L2_PIX_FMT_NV12, TRUE},
941   {V4L2_PIX_FMT_NV21, TRUE},
942
943   /*  The following formats are not defined in the V4L2 specification */
944   {V4L2_PIX_FMT_YUV410, TRUE},
945   {V4L2_PIX_FMT_YUV420, TRUE},
946   {V4L2_PIX_FMT_YYUV, TRUE},
947   {V4L2_PIX_FMT_HI240, TRUE},
948
949   /* see http://www.siliconimaging.com/RGB%20Bayer.htm */
950 #ifdef V4L2_PIX_FMT_SBGGR8
951   {V4L2_PIX_FMT_SBGGR8, TRUE},
952 #endif
953
954   /* compressed formats */
955   {V4L2_PIX_FMT_MJPEG, TRUE},
956   {V4L2_PIX_FMT_JPEG, TRUE},
957 #ifdef V4L2_PIX_FMT_PJPG
958   {V4L2_PIX_FMT_PJPG, TRUE},
959 #endif
960   {V4L2_PIX_FMT_DV, TRUE},
961   {V4L2_PIX_FMT_MPEG, FALSE},
962 #ifdef V4L2_PIX_FMT_MPEG4
963   {V4L2_PIX_FMT_MPEG4, TRUE},
964 #endif
965
966 #ifdef V4L2_PIX_FMT_H263
967   {V4L2_PIX_FMT_H263, TRUE},
968 #endif
969 #ifdef V4L2_PIX_FMT_H264
970   {V4L2_PIX_FMT_H264, TRUE},
971 #endif
972
973   /*  Vendor-specific formats   */
974   {V4L2_PIX_FMT_WNVA, TRUE},
975
976 #ifdef V4L2_PIX_FMT_SN9C10X
977   {V4L2_PIX_FMT_SN9C10X, TRUE},
978 #endif
979 #ifdef V4L2_PIX_FMT_PWC1
980   {V4L2_PIX_FMT_PWC1, TRUE},
981 #endif
982 #ifdef V4L2_PIX_FMT_PWC2
983   {V4L2_PIX_FMT_PWC2, TRUE},
984 #endif
985 #ifdef V4L2_PIX_FMT_YVYU
986   {V4L2_PIX_FMT_YVYU, TRUE},
987 #endif
988 };
989
990 #define GST_V4L2_FORMAT_COUNT (G_N_ELEMENTS (gst_v4l2_formats))
991
992
993 static struct v4l2_fmtdesc *
994 gst_v4l2_object_get_format_from_fourcc (GstV4l2Object * v4l2object,
995     guint32 fourcc)
996 {
997   struct v4l2_fmtdesc *fmt;
998   GSList *walk;
999
1000   if (fourcc == 0)
1001     return NULL;
1002
1003   walk = gst_v4l2_object_get_format_list (v4l2object);
1004   while (walk) {
1005     fmt = (struct v4l2_fmtdesc *) walk->data;
1006     if (fmt->pixelformat == fourcc)
1007       return fmt;
1008     /* special case for jpeg */
1009     if (fmt->pixelformat == V4L2_PIX_FMT_MJPEG ||
1010         fmt->pixelformat == V4L2_PIX_FMT_JPEG
1011 #ifdef V4L2_PIX_FMT_PJPG
1012         || fmt->pixelformat == V4L2_PIX_FMT_PJPG
1013 #endif
1014         ) {
1015       if (fourcc == V4L2_PIX_FMT_JPEG || fourcc == V4L2_PIX_FMT_MJPEG
1016 #ifdef V4L2_PIX_FMT_PJPG
1017           || fourcc == V4L2_PIX_FMT_PJPG
1018 #endif
1019           ) {
1020         return fmt;
1021       }
1022     }
1023     walk = g_slist_next (walk);
1024   }
1025
1026   return NULL;
1027 }
1028
1029
1030
1031 /* complete made up ranking, the values themselves are meaningless */
1032 /* These ranks MUST be X such that X<<15 fits on a signed int - see
1033    the comment at the end of gst_v4l2_object_format_get_rank. */
1034 #define YUV_BASE_RANK     1000
1035 #define JPEG_BASE_RANK     500
1036 #define DV_BASE_RANK       200
1037 #define RGB_BASE_RANK      100
1038 #define YUV_ODD_BASE_RANK   50
1039 #define RGB_ODD_BASE_RANK   25
1040 #define BAYER_BASE_RANK     15
1041 #define S910_BASE_RANK      10
1042 #define GREY_BASE_RANK       5
1043 #define PWC_BASE_RANK        1
1044
1045 /* This flag is already used by libv4l2 although
1046  * it was added to the Linux kernel in 2.6.32
1047  */
1048 #ifndef V4L2_FMT_FLAG_EMULATED
1049 #define V4L2_FMT_FLAG_EMULATED 0x0002
1050 #endif
1051
1052 static gint
1053 gst_v4l2_object_format_get_rank (const struct v4l2_fmtdesc *fmt)
1054 {
1055   guint32 fourcc = fmt->pixelformat;
1056   gboolean emulated = ((fmt->flags & V4L2_FMT_FLAG_EMULATED) != 0);
1057   gint rank = 0;
1058
1059   switch (fourcc) {
1060     case V4L2_PIX_FMT_MJPEG:
1061 #ifdef V4L2_PIX_FMT_PJPG
1062     case V4L2_PIX_FMT_PJPG:
1063       rank = JPEG_BASE_RANK;
1064       break;
1065 #endif
1066     case V4L2_PIX_FMT_JPEG:
1067       rank = JPEG_BASE_RANK + 1;
1068       break;
1069     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1070       rank = JPEG_BASE_RANK + 2;
1071       break;
1072
1073     case V4L2_PIX_FMT_RGB332:
1074     case V4L2_PIX_FMT_RGB555:
1075     case V4L2_PIX_FMT_RGB555X:
1076     case V4L2_PIX_FMT_RGB565:
1077     case V4L2_PIX_FMT_RGB565X:
1078       rank = RGB_ODD_BASE_RANK;
1079       break;
1080
1081     case V4L2_PIX_FMT_RGB24:
1082     case V4L2_PIX_FMT_BGR24:
1083       rank = RGB_BASE_RANK - 1;
1084       break;
1085
1086     case V4L2_PIX_FMT_RGB32:
1087     case V4L2_PIX_FMT_BGR32:
1088       rank = RGB_BASE_RANK;
1089       break;
1090
1091     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1092       rank = GREY_BASE_RANK;
1093       break;
1094
1095     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1096     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1097     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1098     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1099       rank = YUV_ODD_BASE_RANK;
1100       break;
1101
1102     case V4L2_PIX_FMT_YVU410:  /* YVU9,  9 bits per pixel */
1103       rank = YUV_BASE_RANK + 3;
1104       break;
1105     case V4L2_PIX_FMT_YUV410:  /* YUV9,  9 bits per pixel */
1106       rank = YUV_BASE_RANK + 2;
1107       break;
1108     case V4L2_PIX_FMT_YUV420:  /* I420, 12 bits per pixel */
1109       rank = YUV_BASE_RANK + 7;
1110       break;
1111     case V4L2_PIX_FMT_YUYV:    /* YUY2, 16 bits per pixel */
1112       rank = YUV_BASE_RANK + 10;
1113       break;
1114     case V4L2_PIX_FMT_YVU420:  /* YV12, 12 bits per pixel */
1115       rank = YUV_BASE_RANK + 6;
1116       break;
1117     case V4L2_PIX_FMT_UYVY:    /* UYVY, 16 bits per pixel */
1118       rank = YUV_BASE_RANK + 9;
1119       break;
1120     case V4L2_PIX_FMT_Y41P:    /* Y41P, 12 bits per pixel */
1121       rank = YUV_BASE_RANK + 5;
1122       break;
1123     case V4L2_PIX_FMT_YUV411P: /* Y41B, 12 bits per pixel */
1124       rank = YUV_BASE_RANK + 4;
1125       break;
1126     case V4L2_PIX_FMT_YUV422P: /* Y42B, 16 bits per pixel */
1127       rank = YUV_BASE_RANK + 8;
1128       break;
1129
1130     case V4L2_PIX_FMT_DV:
1131       rank = DV_BASE_RANK;
1132       break;
1133
1134     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1135       rank = 0;
1136       break;
1137
1138 #ifdef V4L2_PIX_FMT_SBGGR8
1139     case V4L2_PIX_FMT_SBGGR8:
1140       rank = BAYER_BASE_RANK;
1141       break;
1142 #endif
1143
1144 #ifdef V4L2_PIX_FMT_SN9C10X
1145     case V4L2_PIX_FMT_SN9C10X:
1146       rank = S910_BASE_RANK;
1147       break;
1148 #endif
1149
1150 #ifdef V4L2_PIX_FMT_PWC1
1151     case V4L2_PIX_FMT_PWC1:
1152       rank = PWC_BASE_RANK;
1153       break;
1154 #endif
1155 #ifdef V4L2_PIX_FMT_PWC2
1156     case V4L2_PIX_FMT_PWC2:
1157       rank = PWC_BASE_RANK;
1158       break;
1159 #endif
1160
1161     default:
1162       rank = 0;
1163       break;
1164   }
1165
1166   /* All ranks are below 1<<15 so a shift by 15
1167    * will a) make all non-emulated formats larger
1168    * than emulated and b) will not overflow
1169    */
1170   if (!emulated)
1171     rank <<= 15;
1172
1173   return rank;
1174 }
1175
1176
1177
1178 static gint
1179 format_cmp_func (gconstpointer a, gconstpointer b)
1180 {
1181   const struct v4l2_fmtdesc *fa = a;
1182   const struct v4l2_fmtdesc *fb = b;
1183
1184   if (fa->pixelformat == fb->pixelformat)
1185     return 0;
1186
1187   return gst_v4l2_object_format_get_rank (fb) -
1188       gst_v4l2_object_format_get_rank (fa);
1189 }
1190
1191 /******************************************************
1192  * gst_v4l2_object_fill_format_list():
1193  *   create list of supported capture formats
1194  * return value: TRUE on success, FALSE on error
1195  ******************************************************/
1196 static gboolean
1197 gst_v4l2_object_fill_format_list (GstV4l2Object * v4l2object)
1198 {
1199   gint n;
1200   struct v4l2_fmtdesc *format;
1201
1202   GST_DEBUG_OBJECT (v4l2object->element, "getting src format enumerations");
1203
1204   /* format enumeration */
1205   for (n = 0;; n++) {
1206     format = g_new0 (struct v4l2_fmtdesc, 1);
1207
1208     format->index = n;
1209     format->type = v4l2object->type;
1210
1211     if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_ENUM_FMT, format) < 0) {
1212       if (errno == EINVAL) {
1213         g_free (format);
1214         break;                  /* end of enumeration */
1215       } else {
1216         goto failed;
1217       }
1218     }
1219
1220     GST_LOG_OBJECT (v4l2object->element, "index:       %u", format->index);
1221     GST_LOG_OBJECT (v4l2object->element, "type:        %d", format->type);
1222     GST_LOG_OBJECT (v4l2object->element, "flags:       %08x", format->flags);
1223     GST_LOG_OBJECT (v4l2object->element, "description: '%s'",
1224         format->description);
1225     GST_LOG_OBJECT (v4l2object->element, "pixelformat: %" GST_FOURCC_FORMAT,
1226         GST_FOURCC_ARGS (format->pixelformat));
1227
1228     /* sort formats according to our preference;  we do this, because caps
1229      * are probed in the order the formats are in the list, and the order of
1230      * formats in the final probed caps matters for things like fixation */
1231     v4l2object->formats = g_slist_insert_sorted (v4l2object->formats, format,
1232         (GCompareFunc) format_cmp_func);
1233   }
1234
1235 #ifndef GST_DISABLE_GST_DEBUG
1236   {
1237     GSList *l;
1238
1239     GST_INFO_OBJECT (v4l2object->element, "got %d format(s):", n);
1240     for (l = v4l2object->formats; l != NULL; l = l->next) {
1241       format = l->data;
1242
1243       GST_INFO_OBJECT (v4l2object->element,
1244           "  %" GST_FOURCC_FORMAT "%s", GST_FOURCC_ARGS (format->pixelformat),
1245           ((format->flags & V4L2_FMT_FLAG_EMULATED)) ? " (emulated)" : "");
1246     }
1247   }
1248 #endif
1249
1250   return TRUE;
1251
1252   /* ERRORS */
1253 failed:
1254   {
1255     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
1256         (_("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)));
1257     g_free (format);
1258     return FALSE;
1259   }
1260 }
1261
1262 /*
1263  * Get the list of supported capture formats, a list of
1264  * <code>struct v4l2_fmtdesc</code>.
1265  */
1266 GSList *
1267 gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object)
1268 {
1269   if (!v4l2object->formats)
1270     gst_v4l2_object_fill_format_list (v4l2object);
1271   return v4l2object->formats;
1272 }
1273
1274
1275 GstStructure *
1276 gst_v4l2_object_v4l2fourcc_to_structure (guint32 fourcc)
1277 {
1278   GstStructure *structure = NULL;
1279
1280   switch (fourcc) {
1281     case V4L2_PIX_FMT_MJPEG:   /* Motion-JPEG */
1282 #ifdef V4L2_PIX_FMT_PJPG
1283     case V4L2_PIX_FMT_PJPG:    /* Progressive-JPEG */
1284 #endif
1285     case V4L2_PIX_FMT_JPEG:    /* JFIF JPEG */
1286       structure = gst_structure_new_empty ("image/jpeg");
1287       break;
1288     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1289     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1290       /* FIXME: get correct fourccs here */
1291       break;
1292 #ifdef V4L2_PIX_FMT_MPEG4
1293     case V4L2_PIX_FMT_MPEG4:
1294       structure = gst_structure_new ("video/mpeg",
1295           "mpegversion", G_TYPE_INT, 4, "systemstream",
1296           G_TYPE_BOOLEAN, FALSE, NULL);
1297       break;
1298 #endif
1299 #ifdef V4L2_PIX_FMT_H263
1300     case V4L2_PIX_FMT_H263:
1301       structure = gst_structure_new ("video/x-h263",
1302           "variant", G_TYPE_STRING, "itu", NULL);
1303       break;
1304 #endif
1305 #ifdef V4L2_PIX_FMT_H264
1306     case V4L2_PIX_FMT_H264:    /* H.264 */
1307       structure = gst_structure_new_empty ("video/x-h264");
1308       break;
1309 #endif
1310     case V4L2_PIX_FMT_RGB332:
1311     case V4L2_PIX_FMT_RGB555X:
1312     case V4L2_PIX_FMT_RGB565X:
1313       /* FIXME: get correct fourccs here */
1314       break;
1315     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1316     case V4L2_PIX_FMT_RGB555:
1317     case V4L2_PIX_FMT_RGB565:
1318     case V4L2_PIX_FMT_RGB24:
1319     case V4L2_PIX_FMT_BGR24:
1320     case V4L2_PIX_FMT_RGB32:
1321     case V4L2_PIX_FMT_BGR32:
1322     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1323     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1324     case V4L2_PIX_FMT_YVU410:
1325     case V4L2_PIX_FMT_YUV410:
1326     case V4L2_PIX_FMT_YUV420:  /* I420/IYUV */
1327     case V4L2_PIX_FMT_YUYV:
1328     case V4L2_PIX_FMT_YVU420:
1329     case V4L2_PIX_FMT_UYVY:
1330 #if 0
1331     case V4L2_PIX_FMT_Y41P:
1332 #endif
1333     case V4L2_PIX_FMT_YUV422P:
1334 #ifdef V4L2_PIX_FMT_YVYU
1335     case V4L2_PIX_FMT_YVYU:
1336 #endif
1337     case V4L2_PIX_FMT_YUV411P:{
1338       GstVideoFormat format;
1339
1340       switch (fourcc) {
1341         case V4L2_PIX_FMT_GREY:        /*  8  Greyscale     */
1342           format = GST_VIDEO_FORMAT_GRAY8;
1343           break;
1344         case V4L2_PIX_FMT_RGB555:
1345           format = GST_VIDEO_FORMAT_RGB15;
1346           break;
1347         case V4L2_PIX_FMT_RGB565:
1348           format = GST_VIDEO_FORMAT_RGB16;
1349           break;
1350         case V4L2_PIX_FMT_RGB24:
1351           format = GST_VIDEO_FORMAT_RGB;
1352           break;
1353         case V4L2_PIX_FMT_BGR24:
1354           format = GST_VIDEO_FORMAT_BGR;
1355           break;
1356         case V4L2_PIX_FMT_RGB32:
1357           format = GST_VIDEO_FORMAT_RGBx;
1358           break;
1359         case V4L2_PIX_FMT_BGR32:
1360           format = GST_VIDEO_FORMAT_BGRx;
1361           break;
1362         case V4L2_PIX_FMT_NV12:
1363           format = GST_VIDEO_FORMAT_NV12;
1364           break;
1365         case V4L2_PIX_FMT_NV21:
1366           format = GST_VIDEO_FORMAT_NV21;
1367           break;
1368         case V4L2_PIX_FMT_YVU410:
1369           format = GST_VIDEO_FORMAT_YVU9;
1370           break;
1371         case V4L2_PIX_FMT_YUV410:
1372           format = GST_VIDEO_FORMAT_YUV9;
1373           break;
1374         case V4L2_PIX_FMT_YUV420:
1375           format = GST_VIDEO_FORMAT_I420;
1376           break;
1377         case V4L2_PIX_FMT_YUYV:
1378           format = GST_VIDEO_FORMAT_YUY2;
1379           break;
1380         case V4L2_PIX_FMT_YVU420:
1381           format = GST_VIDEO_FORMAT_YV12;
1382           break;
1383         case V4L2_PIX_FMT_UYVY:
1384           format = GST_VIDEO_FORMAT_UYVY;
1385           break;
1386 #if 0
1387         case V4L2_PIX_FMT_Y41P:
1388           format = GST_VIDEO_FORMAT_Y41P;
1389           break;
1390 #endif
1391         case V4L2_PIX_FMT_YUV411P:
1392           format = GST_VIDEO_FORMAT_Y41B;
1393           break;
1394         case V4L2_PIX_FMT_YUV422P:
1395           format = GST_VIDEO_FORMAT_Y42B;
1396           break;
1397 #ifdef V4L2_PIX_FMT_YVYU
1398         case V4L2_PIX_FMT_YVYU:
1399           format = GST_VIDEO_FORMAT_YVYU;
1400           break;
1401 #endif
1402         default:
1403           format = GST_VIDEO_FORMAT_UNKNOWN;
1404           g_assert_not_reached ();
1405           break;
1406       }
1407       structure = gst_structure_new ("video/x-raw",
1408           "format", G_TYPE_STRING, gst_video_format_to_string (format), NULL);
1409       break;
1410     }
1411     case V4L2_PIX_FMT_DV:
1412       structure =
1413           gst_structure_new ("video/x-dv", "systemstream", G_TYPE_BOOLEAN, TRUE,
1414           NULL);
1415       break;
1416     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1417       structure = gst_structure_new_empty ("video/mpegts");
1418       break;
1419     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1420       break;
1421 #ifdef V4L2_PIX_FMT_SBGGR8
1422     case V4L2_PIX_FMT_SBGGR8:
1423       structure = gst_structure_new_empty ("video/x-bayer");
1424       break;
1425 #endif
1426 #ifdef V4L2_PIX_FMT_SN9C10X
1427     case V4L2_PIX_FMT_SN9C10X:
1428       structure = gst_structure_new_empty ("video/x-sonix");
1429       break;
1430 #endif
1431 #ifdef V4L2_PIX_FMT_PWC1
1432     case V4L2_PIX_FMT_PWC1:
1433       structure = gst_structure_new_empty ("video/x-pwc1");
1434       break;
1435 #endif
1436 #ifdef V4L2_PIX_FMT_PWC2
1437     case V4L2_PIX_FMT_PWC2:
1438       structure = gst_structure_new_empty ("video/x-pwc2");
1439       break;
1440 #endif
1441     default:
1442       GST_DEBUG ("Unknown fourcc 0x%08x %" GST_FOURCC_FORMAT,
1443           fourcc, GST_FOURCC_ARGS (fourcc));
1444       break;
1445   }
1446
1447   return structure;
1448 }
1449
1450
1451
1452 GstCaps *
1453 gst_v4l2_object_get_all_caps (void)
1454 {
1455   static GstCaps *caps = NULL;
1456
1457   if (caps == NULL) {
1458     GstStructure *structure;
1459
1460     guint i;
1461
1462     caps = gst_caps_new_empty ();
1463     for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1464       structure =
1465           gst_v4l2_object_v4l2fourcc_to_structure (gst_v4l2_formats[i].format);
1466       if (structure) {
1467         if (gst_v4l2_formats[i].dimensions) {
1468           gst_structure_set (structure,
1469               "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1470               "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1471               "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1, NULL);
1472         }
1473         gst_caps_append_structure (caps, structure);
1474       }
1475     }
1476   }
1477
1478   return gst_caps_ref (caps);
1479 }
1480
1481
1482 /* collect data for the given caps
1483  * @caps: given input caps
1484  * @format: location for the v4l format
1485  * @w/@h: location for width and height
1486  * @fps_n/@fps_d: location for framerate
1487  * @size: location for expected size of the frame or 0 if unknown
1488  */
1489 static gboolean
1490 gst_v4l2_object_get_caps_info (GstV4l2Object * v4l2object, GstCaps * caps,
1491     struct v4l2_fmtdesc **format, GstVideoInfo * info)
1492 {
1493   GstStructure *structure;
1494   guint32 fourcc;
1495   const gchar *mimetype;
1496   struct v4l2_fmtdesc *fmt;
1497
1498   /* default unknown values */
1499   fourcc = 0;
1500
1501   structure = gst_caps_get_structure (caps, 0);
1502
1503   mimetype = gst_structure_get_name (structure);
1504
1505   if (!gst_video_info_from_caps (info, caps))
1506     goto invalid_format;
1507
1508   if (g_str_equal (mimetype, "video/x-raw")) {
1509     switch (GST_VIDEO_INFO_FORMAT (info)) {
1510       case GST_VIDEO_FORMAT_I420:
1511         fourcc = V4L2_PIX_FMT_YUV420;
1512         break;
1513       case GST_VIDEO_FORMAT_YUY2:
1514         fourcc = V4L2_PIX_FMT_YUYV;
1515         break;
1516 #if 0
1517       case GST_VIDEO_FORMAT_Y41P:
1518         fourcc = V4L2_PIX_FMT_Y41P;
1519         break;
1520 #endif
1521       case GST_VIDEO_FORMAT_UYVY:
1522         fourcc = V4L2_PIX_FMT_UYVY;
1523         break;
1524       case GST_VIDEO_FORMAT_YV12:
1525         fourcc = V4L2_PIX_FMT_YVU420;
1526         break;
1527       case GST_VIDEO_FORMAT_Y41B:
1528         fourcc = V4L2_PIX_FMT_YUV411P;
1529         break;
1530       case GST_VIDEO_FORMAT_Y42B:
1531         fourcc = V4L2_PIX_FMT_YUV422P;
1532         break;
1533       case GST_VIDEO_FORMAT_NV12:
1534         fourcc = V4L2_PIX_FMT_NV12;
1535         break;
1536       case GST_VIDEO_FORMAT_NV21:
1537         fourcc = V4L2_PIX_FMT_NV21;
1538         break;
1539 #ifdef V4L2_PIX_FMT_YVYU
1540       case GST_VIDEO_FORMAT_YVYU:
1541         fourcc = V4L2_PIX_FMT_YVYU;
1542         break;
1543 #endif
1544       case GST_VIDEO_FORMAT_RGB15:
1545         fourcc = V4L2_PIX_FMT_RGB555;
1546         break;
1547       case GST_VIDEO_FORMAT_RGB16:
1548         fourcc = V4L2_PIX_FMT_RGB565;
1549         break;
1550       case GST_VIDEO_FORMAT_RGB:
1551         fourcc = V4L2_PIX_FMT_RGB24;
1552         break;
1553       case GST_VIDEO_FORMAT_BGR:
1554         fourcc = V4L2_PIX_FMT_BGR24;
1555         break;
1556       case GST_VIDEO_FORMAT_RGBx:
1557       case GST_VIDEO_FORMAT_RGBA:
1558         fourcc = V4L2_PIX_FMT_RGB32;
1559         break;
1560       case GST_VIDEO_FORMAT_BGRx:
1561       case GST_VIDEO_FORMAT_BGRA:
1562         fourcc = V4L2_PIX_FMT_BGR32;
1563         break;
1564       case GST_VIDEO_FORMAT_GRAY8:
1565         fourcc = V4L2_PIX_FMT_GREY;
1566       default:
1567         break;
1568     }
1569   } else {
1570     if (g_str_equal (mimetype, "video/mpegts")) {
1571       fourcc = V4L2_PIX_FMT_MPEG;
1572     } else if (g_str_equal (mimetype, "video/x-dv")) {
1573       fourcc = V4L2_PIX_FMT_DV;
1574     } else if (g_str_equal (mimetype, "image/jpeg")) {
1575       fourcc = V4L2_PIX_FMT_JPEG;
1576 #ifdef V4L2_PIX_FMT_MPEG4
1577     } else if (g_str_equal (mimetype, "video/mpeg")) {
1578       fourcc = V4L2_PIX_FMT_MPEG4;
1579 #endif
1580 #ifdef V4L2_PIX_FMT_H263
1581     } else if (g_str_equal (mimetype, "video/x-h263")) {
1582       fourcc = V4L2_PIX_FMT_H263;
1583 #endif
1584 #ifdef V4L2_PIX_FMT_H264
1585     } else if (g_str_equal (mimetype, "video/x-h264")) {
1586       fourcc = V4L2_PIX_FMT_H264;
1587 #endif
1588 #ifdef V4L2_PIX_FMT_SBGGR8
1589     } else if (g_str_equal (mimetype, "video/x-bayer")) {
1590       fourcc = V4L2_PIX_FMT_SBGGR8;
1591 #endif
1592 #ifdef V4L2_PIX_FMT_SN9C10X
1593     } else if (g_str_equal (mimetype, "video/x-sonix")) {
1594       fourcc = V4L2_PIX_FMT_SN9C10X;
1595 #endif
1596 #ifdef V4L2_PIX_FMT_PWC1
1597     } else if (g_str_equal (mimetype, "video/x-pwc1")) {
1598       fourcc = V4L2_PIX_FMT_PWC1;
1599 #endif
1600 #ifdef V4L2_PIX_FMT_PWC2
1601     } else if (g_str_equal (mimetype, "video/x-pwc2")) {
1602       fourcc = V4L2_PIX_FMT_PWC2;
1603     }
1604 #endif
1605   }
1606
1607   if (fourcc == 0)
1608     goto unhandled_format;
1609
1610   fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1611   if (fmt == NULL)
1612     goto unsupported_format;
1613
1614   *format = fmt;
1615
1616   return TRUE;
1617
1618   /* ERRORS */
1619 invalid_format:
1620   {
1621     GST_DEBUG_OBJECT (v4l2object, "invalid format");
1622     return FALSE;
1623   }
1624 unhandled_format:
1625   {
1626     GST_DEBUG_OBJECT (v4l2object, "unhandled format");
1627     return FALSE;
1628   }
1629 unsupported_format:
1630   {
1631     GST_DEBUG_OBJECT (v4l2object, "unsupported format");
1632     return FALSE;
1633   }
1634 }
1635
1636
1637 static gboolean
1638 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1639     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced);
1640
1641 static void
1642 gst_v4l2_object_add_aspect_ratio (GstV4l2Object * v4l2object, GstStructure * s)
1643 {
1644   struct v4l2_cropcap cropcap;
1645   int num = 1, den = 1;
1646
1647   if (!v4l2object->keep_aspect)
1648     return;
1649
1650   if (v4l2object->par) {
1651     num = gst_value_get_fraction_numerator (v4l2object->par);
1652     den = gst_value_get_fraction_denominator (v4l2object->par);
1653     goto done;
1654   }
1655
1656   memset (&cropcap, 0, sizeof (cropcap));
1657
1658   cropcap.type = v4l2object->type;
1659   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_CROPCAP, &cropcap) < 0)
1660     goto cropcap_failed;
1661
1662   num = cropcap.pixelaspect.numerator;
1663   den = cropcap.pixelaspect.denominator;
1664
1665 done:
1666   gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION, num, den,
1667       NULL);
1668   return;
1669
1670 cropcap_failed:
1671   if (errno != ENOTTY)
1672     GST_WARNING_OBJECT (v4l2object->element,
1673         "Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: %s",
1674         g_strerror (errno));
1675   goto done;
1676 }
1677
1678
1679 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1680 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1681 static GstStructure *
1682 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1683     guint32 pixelformat,
1684     guint32 width, guint32 height, const GstStructure * template)
1685 {
1686   gint fd = v4l2object->video_fd;
1687   struct v4l2_frmivalenum ival;
1688   guint32 num, denom;
1689   GstStructure *s;
1690   GValue rates = { 0, };
1691   gboolean interlaced;
1692   gint int_width = width;
1693   gint int_height = height;
1694
1695   if (!strcmp ((char *) v4l2object->vcap.driver, "uvcvideo")) {
1696     /*
1697      * UVC devices are never interlaced, and doing VIDIOC_TRY_FMT on them
1698      * causes expensive and slow USB IO, so don't probe them for interlaced
1699      */
1700     interlaced = FALSE;
1701   } else {
1702     /* Interlaced detection using VIDIOC_TRY/S_FMT */
1703     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat,
1704             &int_width, &int_height, &interlaced))
1705       return NULL;
1706   }
1707
1708   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1709   ival.index = 0;
1710   ival.pixel_format = pixelformat;
1711   ival.width = width;
1712   ival.height = height;
1713
1714   GST_LOG_OBJECT (v4l2object->element,
1715       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1716       GST_FOURCC_ARGS (pixelformat));
1717
1718   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1719    * fraction to get framerate */
1720   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1721     goto enum_frameintervals_failed;
1722
1723   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1724     GValue rate = { 0, };
1725
1726     g_value_init (&rates, GST_TYPE_LIST);
1727     g_value_init (&rate, GST_TYPE_FRACTION);
1728
1729     do {
1730       num = ival.discrete.numerator;
1731       denom = ival.discrete.denominator;
1732
1733       if (num > G_MAXINT || denom > G_MAXINT) {
1734         /* let us hope we don't get here... */
1735         num >>= 1;
1736         denom >>= 1;
1737       }
1738
1739       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1740           denom, num);
1741
1742       /* swap to get the framerate */
1743       gst_value_set_fraction (&rate, denom, num);
1744       gst_value_list_append_value (&rates, &rate);
1745
1746       ival.index++;
1747     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1748   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1749     GValue min = { 0, };
1750     GValue step = { 0, };
1751     GValue max = { 0, };
1752     gboolean added = FALSE;
1753     guint32 minnum, mindenom;
1754     guint32 maxnum, maxdenom;
1755
1756     g_value_init (&rates, GST_TYPE_LIST);
1757
1758     g_value_init (&min, GST_TYPE_FRACTION);
1759     g_value_init (&step, GST_TYPE_FRACTION);
1760     g_value_init (&max, GST_TYPE_FRACTION);
1761
1762     /* get the min */
1763     minnum = ival.stepwise.min.numerator;
1764     mindenom = ival.stepwise.min.denominator;
1765     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1766       minnum >>= 1;
1767       mindenom >>= 1;
1768     }
1769     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1770         minnum, mindenom);
1771     gst_value_set_fraction (&min, minnum, mindenom);
1772
1773     /* get the max */
1774     maxnum = ival.stepwise.max.numerator;
1775     maxdenom = ival.stepwise.max.denominator;
1776     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1777       maxnum >>= 1;
1778       maxdenom >>= 1;
1779     }
1780
1781     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1782         maxnum, maxdenom);
1783     gst_value_set_fraction (&max, maxnum, maxdenom);
1784
1785     /* get the step */
1786     num = ival.stepwise.step.numerator;
1787     denom = ival.stepwise.step.denominator;
1788     if (num > G_MAXINT || denom > G_MAXINT) {
1789       num >>= 1;
1790       denom >>= 1;
1791     }
1792
1793     if (num == 0 || denom == 0) {
1794       /* in this case we have a wrong fraction or no step, set the step to max
1795        * so that we only add the min value in the loop below */
1796       num = maxnum;
1797       denom = maxdenom;
1798     }
1799
1800     /* since we only have gst_value_fraction_subtract and not add, negate the
1801      * numerator */
1802     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1803         num, denom);
1804     gst_value_set_fraction (&step, -num, denom);
1805
1806     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
1807       GValue rate = { 0, };
1808
1809       num = gst_value_get_fraction_numerator (&min);
1810       denom = gst_value_get_fraction_denominator (&min);
1811       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1812           denom, num);
1813
1814       /* invert to get the framerate */
1815       g_value_init (&rate, GST_TYPE_FRACTION);
1816       gst_value_set_fraction (&rate, denom, num);
1817       gst_value_list_append_value (&rates, &rate);
1818       added = TRUE;
1819
1820       /* we're actually adding because step was negated above. This is because
1821        * there is no _add function... */
1822       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1823         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1824         break;
1825       }
1826     }
1827     if (!added) {
1828       /* no range was added, leave the default range from the template */
1829       GST_WARNING_OBJECT (v4l2object->element,
1830           "no range added, leaving default");
1831       g_value_unset (&rates);
1832     }
1833   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1834     guint32 maxnum, maxdenom;
1835
1836     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1837
1838     num = ival.stepwise.min.numerator;
1839     denom = ival.stepwise.min.denominator;
1840     if (num > G_MAXINT || denom > G_MAXINT) {
1841       num >>= 1;
1842       denom >>= 1;
1843     }
1844
1845     maxnum = ival.stepwise.max.numerator;
1846     maxdenom = ival.stepwise.max.denominator;
1847     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1848       maxnum >>= 1;
1849       maxdenom >>= 1;
1850     }
1851
1852     GST_LOG_OBJECT (v4l2object->element,
1853         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1854         num);
1855
1856     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1857   } else {
1858     goto unknown_type;
1859   }
1860
1861 return_data:
1862   s = gst_structure_copy (template);
1863   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1864       "height", G_TYPE_INT, (gint) height, NULL);
1865   gst_v4l2_object_add_aspect_ratio (v4l2object, s);
1866   if (g_str_equal (gst_structure_get_name (s), "video/x-raw"))
1867     gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
1868         (interlaced ? "mixed" : "progressive"), NULL);
1869
1870   if (G_IS_VALUE (&rates)) {
1871     /* only change the framerate on the template when we have a valid probed new
1872      * value */
1873     gst_structure_set_value (s, "framerate", &rates);
1874     g_value_unset (&rates);
1875   } else {
1876     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1877         NULL);
1878   }
1879   return s;
1880
1881   /* ERRORS */
1882 enum_frameintervals_failed:
1883   {
1884     GST_DEBUG_OBJECT (v4l2object->element,
1885         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1886         GST_FOURCC_ARGS (pixelformat), width, height);
1887     goto return_data;
1888   }
1889 unknown_type:
1890   {
1891     /* I don't see how this is actually an error, we ignore the format then */
1892     GST_WARNING_OBJECT (v4l2object->element,
1893         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1894         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1895     return NULL;
1896   }
1897 }
1898 #endif /* defined VIDIOC_ENUM_FRAMEINTERVALS */
1899
1900 #ifdef VIDIOC_ENUM_FRAMESIZES
1901 static gint
1902 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1903 {
1904   int w1, h1, w2, h2;
1905
1906   gst_structure_get_int (s1, "width", &w1);
1907   gst_structure_get_int (s1, "height", &h1);
1908   gst_structure_get_int (s2, "width", &w2);
1909   gst_structure_get_int (s2, "height", &h2);
1910
1911   /* I think it's safe to assume that this won't overflow for a while */
1912   return ((w2 * h2) - (w1 * h1));
1913 }
1914 #endif
1915
1916 GstCaps *
1917 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
1918     guint32 pixelformat, const GstStructure * template)
1919 {
1920   GstCaps *ret = gst_caps_new_empty ();
1921   GstStructure *tmp;
1922
1923 #ifdef VIDIOC_ENUM_FRAMESIZES
1924   gint fd = v4l2object->video_fd;
1925   struct v4l2_frmsizeenum size;
1926   GList *results = NULL;
1927   guint32 w, h;
1928
1929   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G'))
1930     return gst_caps_new_empty_simple ("video/mpegts");
1931
1932   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
1933   size.index = 0;
1934   size.pixel_format = pixelformat;
1935
1936   GST_DEBUG_OBJECT (v4l2object->element, "Enumerating frame sizes");
1937
1938   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
1939     goto enum_framesizes_failed;
1940
1941   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
1942     do {
1943       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
1944           size.discrete.width, size.discrete.height);
1945
1946       w = MIN (size.discrete.width, G_MAXINT);
1947       h = MIN (size.discrete.height, G_MAXINT);
1948
1949       if (w && h) {
1950         tmp =
1951             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1952             pixelformat, w, h, template);
1953
1954         if (tmp)
1955           results = g_list_prepend (results, tmp);
1956       }
1957
1958       size.index++;
1959     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
1960     GST_DEBUG_OBJECT (v4l2object->element,
1961         "done iterating discrete frame sizes");
1962   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
1963     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
1964     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1965         size.stepwise.min_width);
1966     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1967         size.stepwise.min_height);
1968     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1969         size.stepwise.max_width);
1970     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1971         size.stepwise.max_height);
1972     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
1973         size.stepwise.step_width);
1974     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
1975         size.stepwise.step_height);
1976
1977     for (w = size.stepwise.min_width, h = size.stepwise.min_height;
1978         w <= size.stepwise.max_width && h <= size.stepwise.max_height;
1979         w += size.stepwise.step_width, h += size.stepwise.step_height) {
1980       if (w == 0 || h == 0)
1981         continue;
1982
1983       tmp =
1984           gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1985           pixelformat, w, h, template);
1986
1987       if (tmp)
1988         results = g_list_prepend (results, tmp);
1989     }
1990     GST_DEBUG_OBJECT (v4l2object->element,
1991         "done iterating stepwise frame sizes");
1992   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
1993     guint32 maxw, maxh;
1994
1995     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
1996     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1997         size.stepwise.min_width);
1998     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1999         size.stepwise.min_height);
2000     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
2001         size.stepwise.max_width);
2002     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2003         size.stepwise.max_height);
2004
2005     w = MAX (size.stepwise.min_width, 1);
2006     h = MAX (size.stepwise.min_height, 1);
2007     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2008     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2009
2010     tmp =
2011         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
2012         w, h, template);
2013     if (tmp) {
2014       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
2015           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
2016           NULL);
2017
2018       /* no point using the results list here, since there's only one struct */
2019       gst_caps_append_structure (ret, tmp);
2020     }
2021   } else {
2022     goto unknown_type;
2023   }
2024
2025   /* we use an intermediary list to store and then sort the results of the
2026    * probing because we can't make any assumptions about the order in which
2027    * the driver will give us the sizes, but we want the final caps to contain
2028    * the results starting with the highest resolution and having the lowest
2029    * resolution last, since order in caps matters for things like fixation. */
2030   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
2031   while (results != NULL) {
2032     gst_caps_append_structure (ret, GST_STRUCTURE (results->data));
2033     results = g_list_delete_link (results, results);
2034   }
2035
2036   if (gst_caps_is_empty (ret))
2037     goto enum_framesizes_no_results;
2038
2039   return ret;
2040
2041   /* ERRORS */
2042 enum_framesizes_failed:
2043   {
2044     /* I don't see how this is actually an error */
2045     GST_DEBUG_OBJECT (v4l2object->element,
2046         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
2047         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
2048     goto default_frame_sizes;
2049   }
2050 enum_framesizes_no_results:
2051   {
2052     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
2053      * question doesn't actually support it yet */
2054     GST_DEBUG_OBJECT (v4l2object->element,
2055         "No results for pixelformat %" GST_FOURCC_FORMAT
2056         " enumerating frame sizes, trying fallback",
2057         GST_FOURCC_ARGS (pixelformat));
2058     goto default_frame_sizes;
2059   }
2060 unknown_type:
2061   {
2062     GST_WARNING_OBJECT (v4l2object->element,
2063         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
2064         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
2065     goto default_frame_sizes;
2066   }
2067 default_frame_sizes:
2068 #endif /* defined VIDIOC_ENUM_FRAMESIZES */
2069   {
2070     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
2071     gboolean interlaced;
2072
2073     /* This code is for Linux < 2.6.19 */
2074     min_w = min_h = 1;
2075     max_w = max_h = GST_V4L2_MAX_SIZE;
2076     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
2077             &min_h, &interlaced)) {
2078       GST_WARNING_OBJECT (v4l2object->element,
2079           "Could not probe minimum capture size for pixelformat %"
2080           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2081     }
2082     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
2083             &max_h, &interlaced)) {
2084       GST_WARNING_OBJECT (v4l2object->element,
2085           "Could not probe maximum capture size for pixelformat %"
2086           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2087     }
2088
2089     /* Since we can't get framerate directly, try to use the current norm */
2090     if (v4l2object->tv_norm && v4l2object->norms) {
2091       GList *norms;
2092       GstTunerNorm *norm = NULL;
2093       GstTunerNorm *current =
2094           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
2095
2096       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
2097         norm = (GstTunerNorm *) norms->data;
2098         if (!strcmp (norm->label, current->label))
2099           break;
2100       }
2101       /* If it's possible, set framerate to that (discrete) value */
2102       if (norm) {
2103         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
2104         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
2105       }
2106     }
2107
2108     tmp = gst_structure_copy (template);
2109     if (fix_num) {
2110       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
2111           fix_denom, NULL);
2112     } else {
2113       /* if norm can't be used, copy the template framerate */
2114       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
2115           100, 1, NULL);
2116     }
2117
2118     if (min_w == max_w)
2119       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
2120     else
2121       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
2122
2123     if (min_h == max_h)
2124       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
2125     else
2126       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
2127
2128     if (g_str_equal (gst_structure_get_name (tmp), "video/x-raw"))
2129       gst_structure_set (tmp, "interlace-mode", G_TYPE_STRING,
2130           (interlaced ? "mixed" : "progressive"), NULL);
2131     gst_v4l2_object_add_aspect_ratio (v4l2object, tmp);
2132
2133     gst_caps_append_structure (ret, tmp);
2134
2135     return ret;
2136   }
2137 }
2138
2139 static gboolean
2140 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
2141     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced)
2142 {
2143   struct v4l2_format fmt, prevfmt;
2144   int fd;
2145   int r;
2146   int prevfmt_valid;
2147
2148   g_return_val_if_fail (width != NULL, FALSE);
2149   g_return_val_if_fail (height != NULL, FALSE);
2150
2151   GST_LOG_OBJECT (v4l2object->element,
2152       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2153       *width, *height, GST_FOURCC_ARGS (pixelformat));
2154
2155   fd = v4l2object->video_fd;
2156
2157   /* Some drivers are buggy and will modify the currently set format
2158      when processing VIDIOC_TRY_FMT, so we remember what is set at the
2159      minute, and will reset it when done. */
2160   prevfmt.type = v4l2object->type;
2161   prevfmt_valid = (v4l2_ioctl (fd, VIDIOC_G_FMT, &prevfmt) >= 0);
2162
2163   /* get size delimiters */
2164   memset (&fmt, 0, sizeof (fmt));
2165   fmt.type = v4l2object->type;
2166   fmt.fmt.pix.width = *width;
2167   fmt.fmt.pix.height = *height;
2168   fmt.fmt.pix.pixelformat = pixelformat;
2169   fmt.fmt.pix.field = V4L2_FIELD_NONE;
2170
2171   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2172   if (r < 0 && errno == EINVAL) {
2173     /* try again with interlaced video */
2174     fmt.fmt.pix.width = *width;
2175     fmt.fmt.pix.height = *height;
2176     fmt.fmt.pix.pixelformat = pixelformat;
2177     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2178     r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2179   }
2180
2181   if (r < 0) {
2182     /* The driver might not implement TRY_FMT, in which case we will try
2183        S_FMT to probe */
2184     if (errno != ENOTTY)
2185       goto error;
2186
2187     /* Only try S_FMT if we're not actively capturing yet, which we shouldn't
2188        be, because we're still probing */
2189     if (GST_V4L2_IS_ACTIVE (v4l2object))
2190       goto error;
2191
2192     GST_LOG_OBJECT (v4l2object->element,
2193         "Failed to probe size limit with VIDIOC_TRY_FMT, trying VIDIOC_S_FMT");
2194
2195     fmt.fmt.pix.width = *width;
2196     fmt.fmt.pix.height = *height;
2197
2198     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2199     if (r < 0 && errno == EINVAL) {
2200       /* try again with progressive video */
2201       fmt.fmt.pix.width = *width;
2202       fmt.fmt.pix.height = *height;
2203       fmt.fmt.pix.pixelformat = pixelformat;
2204       fmt.fmt.pix.field = V4L2_FIELD_NONE;
2205       r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2206     }
2207
2208     if (r < 0)
2209       goto error;
2210   }
2211
2212   GST_LOG_OBJECT (v4l2object->element,
2213       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2214
2215   *width = fmt.fmt.pix.width;
2216   *height = fmt.fmt.pix.height;
2217
2218   switch (fmt.fmt.pix.field) {
2219     case V4L2_FIELD_ANY:
2220     case V4L2_FIELD_NONE:
2221       *interlaced = FALSE;
2222       break;
2223     case V4L2_FIELD_INTERLACED:
2224     case V4L2_FIELD_INTERLACED_TB:
2225     case V4L2_FIELD_INTERLACED_BT:
2226       *interlaced = TRUE;
2227       break;
2228     default:
2229       GST_WARNING_OBJECT (v4l2object->element,
2230           "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u",
2231           GST_FOURCC_ARGS (pixelformat), *width, *height);
2232       goto error;
2233   }
2234
2235   if (prevfmt_valid)
2236     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2237   return TRUE;
2238
2239 error:
2240   if (prevfmt_valid)
2241     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2242   return FALSE;
2243 }
2244
2245 static gboolean
2246 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
2247 {
2248   GstV4l2IOMode mode;
2249
2250   GST_DEBUG_OBJECT (v4l2object->element, "initializing the capture system");
2251
2252   GST_V4L2_CHECK_OPEN (v4l2object);
2253   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2254
2255   /* find transport */
2256   mode = v4l2object->req_mode;
2257
2258   if (v4l2object->vcap.capabilities & V4L2_CAP_READWRITE) {
2259     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2260       mode = GST_V4L2_IO_RW;
2261   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
2262     goto method_not_supported;
2263
2264   if (v4l2object->vcap.capabilities & V4L2_CAP_STREAMING) {
2265     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2266       mode = GST_V4L2_IO_MMAP;
2267   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP)
2268     goto method_not_supported;
2269
2270   /* if still no transport selected, error out */
2271   if (mode == GST_V4L2_IO_AUTO)
2272     goto no_supported_capture_method;
2273
2274   GST_INFO_OBJECT (v4l2object->element, "accessing buffers via mode %d", mode);
2275   v4l2object->mode = mode;
2276
2277   /* Map the buffers */
2278   GST_LOG_OBJECT (v4l2object->element, "initiating buffer pool");
2279
2280   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
2281     goto buffer_pool_new_failed;
2282
2283   GST_V4L2_SET_ACTIVE (v4l2object);
2284
2285   return TRUE;
2286
2287   /* ERRORS */
2288 buffer_pool_new_failed:
2289   {
2290     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2291         (_("Could not map buffers from device '%s'"),
2292             v4l2object->videodev),
2293         ("Failed to create buffer pool: %s", g_strerror (errno)));
2294     return FALSE;
2295   }
2296 method_not_supported:
2297   {
2298     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2299         (_("The driver of device '%s' does not support the IO method %d"),
2300             v4l2object->videodev, mode), (NULL));
2301     return FALSE;
2302   }
2303 no_supported_capture_method:
2304   {
2305     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2306         (_("The driver of device '%s' does not support any known IO "
2307                 "method."), v4l2object->videodev), (NULL));
2308     return FALSE;
2309   }
2310 }
2311
2312 gboolean
2313 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps)
2314 {
2315   gint fd = v4l2object->video_fd;
2316   struct v4l2_format format;
2317   struct v4l2_streamparm streamparm;
2318   enum v4l2_field field;
2319   guint32 pixelformat;
2320   struct v4l2_fmtdesc *fmtdesc;
2321   GstVideoInfo info;
2322   gint width, height, fps_n, fps_d, stride;
2323
2324   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
2325     goto invalid_caps;
2326
2327   pixelformat = fmtdesc->pixelformat;
2328   width = GST_VIDEO_INFO_WIDTH (&info);
2329   height = GST_VIDEO_INFO_HEIGHT (&info);
2330   fps_n = GST_VIDEO_INFO_FPS_N (&info);
2331   fps_d = GST_VIDEO_INFO_FPS_D (&info);
2332   stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
2333
2334   if (GST_VIDEO_INFO_IS_INTERLACED (&info)) {
2335     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2336     /* ideally we would differentiate between types of interlaced video
2337      * but there is not sufficient information in the caps..
2338      */
2339     field = V4L2_FIELD_INTERLACED;
2340   } else {
2341     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2342     field = V4L2_FIELD_NONE;
2343   }
2344
2345   GST_DEBUG_OBJECT (v4l2object->element, "Desired format %dx%d, format "
2346       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
2347       GST_FOURCC_ARGS (pixelformat), stride);
2348
2349   GST_V4L2_CHECK_OPEN (v4l2object);
2350   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2351
2352   /* MPEG-TS source cameras don't get their format set for some reason.
2353    * It looks wrong and we weren't able to track down the reason for that code
2354    * so it is disabled until someone who has an mpeg-ts camera complains...
2355    */
2356 #if 0
2357   /* Only unconditionally accept mpegts for sources */
2358   if ((v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
2359       (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')))
2360     goto done;
2361 #endif
2362
2363   memset (&format, 0x00, sizeof (struct v4l2_format));
2364   format.type = v4l2object->type;
2365
2366   if (v4l2_ioctl (fd, VIDIOC_G_FMT, &format) < 0)
2367     goto get_fmt_failed;
2368
2369   GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2370       "%" GST_FOURCC_FORMAT " bytesperline %d, colorspace %d",
2371       format.fmt.pix.width, format.fmt.pix.height,
2372       GST_FOURCC_ARGS (format.fmt.pix.pixelformat), format.fmt.pix.bytesperline,
2373       format.fmt.pix.colorspace);
2374
2375   if (format.type != v4l2object->type ||
2376       format.fmt.pix.width != width ||
2377       format.fmt.pix.height != height ||
2378       format.fmt.pix.pixelformat != pixelformat ||
2379       format.fmt.pix.field != field || format.fmt.pix.bytesperline != stride) {
2380     /* something different, set the format */
2381     GST_DEBUG_OBJECT (v4l2object->element, "Setting format to %dx%d, format "
2382         "%" GST_FOURCC_FORMAT " bytesperline %d", width, height,
2383         GST_FOURCC_ARGS (pixelformat), stride);
2384
2385     format.type = v4l2object->type;
2386     format.fmt.pix.width = width;
2387     format.fmt.pix.height = height;
2388     format.fmt.pix.pixelformat = pixelformat;
2389     format.fmt.pix.field = field;
2390     /* try to ask our prefered stride */
2391     format.fmt.pix.bytesperline = stride;
2392
2393     if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0)
2394       goto set_fmt_failed;
2395
2396     GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2397         "%" GST_FOURCC_FORMAT " stride %d", format.fmt.pix.width,
2398         format.fmt.pix.height, GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2399         format.fmt.pix.bytesperline);
2400
2401     if (format.fmt.pix.width != width || format.fmt.pix.height != height)
2402       goto invalid_dimensions;
2403
2404     if (format.fmt.pix.pixelformat != pixelformat)
2405       goto invalid_pixelformat;
2406   }
2407
2408   /* figure out the frame layout */
2409   v4l2object->bytesperline = format.fmt.pix.bytesperline;
2410   v4l2object->sizeimage = format.fmt.pix.sizeimage;
2411
2412   GST_DEBUG_OBJECT (v4l2object->element, "Got sizeimage %u",
2413       v4l2object->sizeimage);
2414
2415   /* Is there a reason we require the caller to always specify a framerate? */
2416   GST_DEBUG_OBJECT (v4l2object->element, "Desired framerate: %u/%u", fps_n,
2417       fps_d);
2418
2419   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2420   streamparm.type = v4l2object->type;
2421
2422   if (v4l2_ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
2423     goto get_parm_failed;
2424
2425   GST_VIDEO_INFO_FPS_N (&info) =
2426       streamparm.parm.capture.timeperframe.denominator;
2427   GST_VIDEO_INFO_FPS_D (&info) = streamparm.parm.capture.timeperframe.numerator;
2428
2429   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2430     GST_DEBUG_OBJECT (v4l2object->element, "Got framerate: %u/%u",
2431         streamparm.parm.capture.timeperframe.denominator,
2432         streamparm.parm.capture.timeperframe.numerator);
2433
2434     /* We used to skip frame rate setup if the camera was already setup
2435      * with the requested frame rate. This breaks some cameras though,
2436      * causing them to not output data (several models of Thinkpad cameras
2437      * have this problem at least).
2438      * So, don't skip. */
2439     GST_LOG_OBJECT (v4l2object->element, "Setting framerate to %u/%u", fps_n,
2440         fps_d);
2441     /* We want to change the frame rate, so check whether we can. Some cheap USB
2442      * cameras don't have the capability */
2443     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
2444       GST_DEBUG_OBJECT (v4l2object->element,
2445           "Not setting framerate (not supported)");
2446       goto done;
2447     }
2448
2449     /* Note: V4L2 wants the frame interval, we have the frame rate */
2450     streamparm.parm.capture.timeperframe.numerator = fps_d;
2451     streamparm.parm.capture.timeperframe.denominator = fps_n;
2452
2453     /* some cheap USB cam's won't accept any change */
2454     if (v4l2_ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
2455       goto set_parm_failed;
2456
2457     /* get new values */
2458     fps_d = streamparm.parm.capture.timeperframe.numerator;
2459     fps_n = streamparm.parm.capture.timeperframe.denominator;
2460
2461     GST_INFO_OBJECT (v4l2object->element, "Set framerate to %u/%u", fps_n,
2462         fps_d);
2463
2464     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
2465     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
2466   }
2467
2468 done:
2469   /* if we have a framerate pre-calculate duration */
2470   if (fps_n > 0 && fps_d > 0) {
2471     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
2472   } else {
2473     v4l2object->duration = GST_CLOCK_TIME_NONE;
2474   }
2475   v4l2object->info = info;
2476   v4l2object->fmtdesc = fmtdesc;
2477
2478   /* now configure ther pools */
2479   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
2480     goto pool_failed;
2481
2482   return TRUE;
2483
2484   /* ERRORS */
2485 invalid_caps:
2486   {
2487     GST_DEBUG_OBJECT (v4l2object->element, "can't parse caps %" GST_PTR_FORMAT,
2488         caps);
2489     return FALSE;
2490   }
2491 get_fmt_failed:
2492   {
2493     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2494         (_("Device '%s' does not support video capture"),
2495             v4l2object->videodev),
2496         ("Call to G_FMT failed: (%s)", g_strerror (errno)));
2497     return FALSE;
2498   }
2499 set_fmt_failed:
2500   {
2501     if (errno == EBUSY) {
2502       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, BUSY,
2503           (_("Device '%s' is busy"), v4l2object->videodev),
2504           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2505               GST_FOURCC_ARGS (pixelformat), width, height,
2506               g_strerror (errno)));
2507     } else {
2508       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2509           (_("Device '%s' cannot capture at %dx%d"),
2510               v4l2object->videodev, width, height),
2511           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2512               GST_FOURCC_ARGS (pixelformat), width, height,
2513               g_strerror (errno)));
2514     }
2515     return FALSE;
2516   }
2517 invalid_dimensions:
2518   {
2519     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2520         (_("Device '%s' cannot capture at %dx%d"),
2521             v4l2object->videodev, width, height),
2522         ("Tried to capture at %dx%d, but device returned size %dx%d",
2523             width, height, format.fmt.pix.width, format.fmt.pix.height));
2524     return FALSE;
2525   }
2526 invalid_pixelformat:
2527   {
2528     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2529         (_("Device '%s' cannot capture in the specified format"),
2530             v4l2object->videodev),
2531         ("Tried to capture in %" GST_FOURCC_FORMAT
2532             ", but device returned format" " %" GST_FOURCC_FORMAT,
2533             GST_FOURCC_ARGS (pixelformat),
2534             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2535     return FALSE;
2536   }
2537 get_parm_failed:
2538   {
2539     /* it's possible that this call is not supported */
2540     if (errno != EINVAL && errno != ENOTTY) {
2541       GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2542           (_("Could not get parameters on device '%s'"),
2543               v4l2object->videodev), GST_ERROR_SYSTEM);
2544     }
2545     goto done;
2546   }
2547 set_parm_failed:
2548   {
2549     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2550         (_("Video device did not accept new frame rate setting.")),
2551         GST_ERROR_SYSTEM);
2552     goto done;
2553   }
2554 pool_failed:
2555   {
2556     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2557         (_("Video device could not create buffer pool.")), GST_ERROR_SYSTEM);
2558     return FALSE;
2559   }
2560 }
2561
2562 gboolean
2563 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
2564 {
2565   GstStructure *s;
2566   GstCaps *oldcaps;
2567
2568   if (!v4l2object->pool)
2569     return FALSE;
2570
2571   s = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (v4l2object->pool));
2572   gst_buffer_pool_config_get_params (s, &oldcaps, NULL, NULL, NULL);
2573
2574   return oldcaps && gst_caps_is_equal (caps, oldcaps);
2575 }
2576
2577 gboolean
2578 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
2579 {
2580   GST_LOG_OBJECT (v4l2object->element, "flush poll");
2581   gst_poll_set_flushing (v4l2object->poll, TRUE);
2582
2583   return TRUE;
2584 }
2585
2586 gboolean
2587 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
2588 {
2589   GST_LOG_OBJECT (v4l2object->element, "flush stop poll");
2590   gst_poll_set_flushing (v4l2object->poll, FALSE);
2591
2592   return TRUE;
2593 }
2594
2595 gboolean
2596 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
2597 {
2598   GST_DEBUG_OBJECT (v4l2object->element, "stopping");
2599
2600   if (!GST_V4L2_IS_OPEN (v4l2object))
2601     goto done;
2602   if (!GST_V4L2_IS_ACTIVE (v4l2object))
2603     goto done;
2604
2605   if (v4l2object->pool) {
2606     GST_DEBUG_OBJECT (v4l2object->element, "deactivating pool");
2607     gst_buffer_pool_set_active (GST_BUFFER_POOL_CAST (v4l2object->pool), FALSE);
2608     gst_object_unref (v4l2object->pool);
2609     v4l2object->pool = NULL;
2610   }
2611
2612   GST_V4L2_SET_INACTIVE (v4l2object);
2613
2614 done:
2615   return TRUE;
2616 }
2617
2618 gboolean
2619 gst_v4l2_object_copy (GstV4l2Object * v4l2object, GstBuffer * dest,
2620     GstBuffer * src)
2621 {
2622   const GstVideoFormatInfo *finfo = v4l2object->info.finfo;
2623
2624   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
2625           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
2626     GstVideoFrame src_frame, dest_frame;
2627
2628     GST_DEBUG_OBJECT (v4l2object->element, "copy video frame");
2629
2630     /* we have raw video, use videoframe copy to get strides right */
2631     if (!gst_video_frame_map (&src_frame, &v4l2object->info, src, GST_MAP_READ))
2632       goto invalid_buffer;
2633
2634     if (!gst_video_frame_map (&dest_frame, &v4l2object->info, dest,
2635             GST_MAP_WRITE)) {
2636       gst_video_frame_unmap (&src_frame);
2637       goto invalid_buffer;
2638     }
2639
2640     gst_video_frame_copy (&dest_frame, &src_frame);
2641
2642     gst_video_frame_unmap (&src_frame);
2643     gst_video_frame_unmap (&dest_frame);
2644   } else {
2645     GstMapInfo map;
2646
2647     GST_DEBUG_OBJECT (v4l2object->element, "copy raw bytes");
2648     gst_buffer_map (src, &map, GST_MAP_READ);
2649     gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src));
2650     gst_buffer_unmap (src, &map);
2651     gst_buffer_resize (dest, 0, gst_buffer_get_size (src));
2652   }
2653   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, v4l2object->element,
2654       "slow copy into buffer %p", dest);
2655
2656   return TRUE;
2657
2658   /* ERRORS */
2659 invalid_buffer:
2660   {
2661     /* No Window available to put our image into */
2662     GST_WARNING_OBJECT (v4l2object->element, "could not map image");
2663     return FALSE;
2664   }
2665 }