v4l2: add a property for arbitrary v4l2 controls
[platform/upstream/gstreamer.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 GstV4l2Object *
510 gst_v4l2_object_new (GstElement * element,
511     enum v4l2_buf_type type,
512     const char *default_device,
513     GstV4l2GetInOutFunction get_in_out_func,
514     GstV4l2SetInOutFunction set_in_out_func,
515     GstV4l2UpdateFpsFunction update_fps_func)
516 {
517   GstV4l2Object *v4l2object;
518
519   /*
520    * some default values
521    */
522   v4l2object = g_new0 (GstV4l2Object, 1);
523
524   v4l2object->type = type;
525   v4l2object->formats = NULL;
526
527   v4l2object->element = element;
528   v4l2object->get_in_out_func = get_in_out_func;
529   v4l2object->set_in_out_func = set_in_out_func;
530   v4l2object->update_fps_func = update_fps_func;
531
532   v4l2object->video_fd = -1;
533   v4l2object->poll = gst_poll_new (TRUE);
534   v4l2object->active = FALSE;
535   v4l2object->videodev = g_strdup (default_device);
536
537   v4l2object->norms = NULL;
538   v4l2object->channels = NULL;
539   v4l2object->colors = NULL;
540
541   v4l2object->xwindow_id = 0;
542
543   return v4l2object;
544 }
545
546 static gboolean gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object);
547
548
549 void
550 gst_v4l2_object_destroy (GstV4l2Object * v4l2object)
551 {
552   g_return_if_fail (v4l2object != NULL);
553
554   if (v4l2object->videodev)
555     g_free (v4l2object->videodev);
556
557   if (v4l2object->poll)
558     gst_poll_free (v4l2object->poll);
559
560   if (v4l2object->channel)
561     g_free (v4l2object->channel);
562
563   if (v4l2object->formats) {
564     gst_v4l2_object_clear_format_list (v4l2object);
565   }
566
567   g_free (v4l2object);
568 }
569
570
571 static gboolean
572 gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object)
573 {
574   g_slist_foreach (v4l2object->formats, (GFunc) g_free, NULL);
575   g_slist_free (v4l2object->formats);
576   v4l2object->formats = NULL;
577
578   return TRUE;
579 }
580
581 static gint
582 gst_v4l2_object_prop_to_cid (guint prop_id)
583 {
584   gint cid = -1;
585
586   switch (prop_id) {
587     case PROP_BRIGHTNESS:
588       cid = V4L2_CID_BRIGHTNESS;
589       break;
590     case PROP_CONTRAST:
591       cid = V4L2_CID_CONTRAST;
592       break;
593     case PROP_SATURATION:
594       cid = V4L2_CID_SATURATION;
595       break;
596     case PROP_HUE:
597       cid = V4L2_CID_HUE;
598       break;
599     default:
600       GST_WARNING ("unmapped property id: %d", prop_id);
601   }
602   return cid;
603 }
604
605
606 gboolean
607 gst_v4l2_object_set_property_helper (GstV4l2Object * v4l2object,
608     guint prop_id, const GValue * value, GParamSpec * pspec)
609 {
610   switch (prop_id) {
611     case PROP_DEVICE:
612       g_free (v4l2object->videodev);
613       v4l2object->videodev = g_value_dup_string (value);
614       break;
615     case PROP_BRIGHTNESS:
616     case PROP_CONTRAST:
617     case PROP_SATURATION:
618     case PROP_HUE:
619     {
620       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
621
622       if (cid != -1) {
623         if (GST_V4L2_IS_OPEN (v4l2object)) {
624           gst_v4l2_set_attribute (v4l2object, cid, g_value_get_int (value));
625         }
626       }
627       return TRUE;
628     }
629       break;
630     case PROP_TV_NORM:
631       v4l2object->tv_norm = g_value_get_enum (value);
632       break;
633 #if 0
634     case PROP_CHANNEL:
635       if (GST_V4L2_IS_OPEN (v4l2object)) {
636         GstTuner *tuner = GST_TUNER (v4l2object->element);
637         GstTunerChannel *channel = gst_tuner_find_channel_by_name (tuner,
638             (gchar *) g_value_get_string (value));
639
640         if (channel) {
641           /* like gst_tuner_set_channel (tuner, channel)
642              without g_object_notify */
643           gst_v4l2_tuner_set_channel (v4l2object, channel);
644         }
645       } else {
646         g_free (v4l2object->channel);
647         v4l2object->channel = g_value_dup_string (value);
648       }
649       break;
650     case PROP_FREQUENCY:
651       if (GST_V4L2_IS_OPEN (v4l2object)) {
652         GstTuner *tuner = GST_TUNER (v4l2object->element);
653         GstTunerChannel *channel = gst_tuner_get_channel (tuner);
654
655         if (channel &&
656             GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
657           /* like
658              gst_tuner_set_frequency (tuner, channel, g_value_get_ulong (value))
659              without g_object_notify */
660           gst_v4l2_tuner_set_frequency (v4l2object, channel,
661               g_value_get_ulong (value));
662         }
663       } else {
664         v4l2object->frequency = g_value_get_ulong (value);
665       }
666       break;
667 #endif
668     case PROP_IO_MODE:
669       v4l2object->req_mode = g_value_get_enum (value);
670       break;
671     case PROP_EXTRA_CONTROLS:{
672       const GstStructure *s = gst_value_get_structure (value);
673
674       if (v4l2object->extra_controls)
675         gst_structure_free (v4l2object->extra_controls);
676
677       v4l2object->extra_controls = s ? gst_structure_copy (s) : NULL;
678       if (GST_V4L2_IS_OPEN (v4l2object))
679         gst_v4l2_set_controls (v4l2object, v4l2object->extra_controls);
680       break;
681     }
682     default:
683       return FALSE;
684       break;
685   }
686   return TRUE;
687 }
688
689
690 gboolean
691 gst_v4l2_object_get_property_helper (GstV4l2Object * v4l2object,
692     guint prop_id, GValue * value, GParamSpec * pspec)
693 {
694   switch (prop_id) {
695     case PROP_DEVICE:
696       g_value_set_string (value, v4l2object->videodev);
697       break;
698     case PROP_DEVICE_NAME:
699     {
700       const guchar *new = NULL;
701
702       if (GST_V4L2_IS_OPEN (v4l2object)) {
703         new = v4l2object->vcap.card;
704       } else if (gst_v4l2_open (v4l2object)) {
705         new = v4l2object->vcap.card;
706         gst_v4l2_close (v4l2object);
707       }
708       g_value_set_string (value, (gchar *) new);
709       break;
710     }
711     case PROP_DEVICE_FD:
712     {
713       if (GST_V4L2_IS_OPEN (v4l2object))
714         g_value_set_int (value, v4l2object->video_fd);
715       else
716         g_value_set_int (value, DEFAULT_PROP_DEVICE_FD);
717       break;
718     }
719     case PROP_FLAGS:
720     {
721       guint flags = 0;
722
723       if (GST_V4L2_IS_OPEN (v4l2object)) {
724         flags |= v4l2object->vcap.capabilities &
725             (V4L2_CAP_VIDEO_CAPTURE |
726             V4L2_CAP_VIDEO_OUTPUT |
727             V4L2_CAP_VIDEO_OVERLAY |
728             V4L2_CAP_VBI_CAPTURE |
729             V4L2_CAP_VBI_OUTPUT | V4L2_CAP_TUNER | V4L2_CAP_AUDIO);
730       }
731       g_value_set_flags (value, flags);
732       break;
733     }
734     case PROP_BRIGHTNESS:
735     case PROP_CONTRAST:
736     case PROP_SATURATION:
737     case PROP_HUE:
738     {
739       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
740
741       if (cid != -1) {
742         if (GST_V4L2_IS_OPEN (v4l2object)) {
743           gint v;
744           if (gst_v4l2_get_attribute (v4l2object, cid, &v)) {
745             g_value_set_int (value, v);
746           }
747         }
748       }
749       return TRUE;
750     }
751       break;
752     case PROP_TV_NORM:
753       g_value_set_enum (value, v4l2object->tv_norm);
754       break;
755     case PROP_IO_MODE:
756       g_value_set_enum (value, v4l2object->req_mode);
757       break;
758     case PROP_EXTRA_CONTROLS:
759       gst_value_set_structure (value, v4l2object->extra_controls);
760       break;
761     default:
762       return FALSE;
763       break;
764   }
765   return TRUE;
766 }
767
768 static void
769 gst_v4l2_set_defaults (GstV4l2Object * v4l2object)
770 {
771   GstTunerNorm *norm = NULL;
772   GstTunerChannel *channel = NULL;
773   GstTuner *tuner;
774
775   if (!GST_IS_TUNER (v4l2object->element))
776     return;
777
778   tuner = GST_TUNER (v4l2object->element);
779
780   if (v4l2object->tv_norm)
781     norm = gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
782   GST_DEBUG_OBJECT (v4l2object->element, "tv_norm=0x%" G_GINT64_MODIFIER "x, "
783       "norm=%p", (guint64) v4l2object->tv_norm, norm);
784   if (norm) {
785     gst_tuner_set_norm (tuner, norm);
786   } else {
787     norm =
788         GST_TUNER_NORM (gst_tuner_get_norm (GST_TUNER (v4l2object->element)));
789     if (norm) {
790       v4l2object->tv_norm =
791           gst_v4l2_tuner_get_std_id_by_norm (v4l2object, norm);
792       gst_tuner_norm_changed (tuner, norm);
793     }
794   }
795
796   if (v4l2object->channel)
797     channel = gst_tuner_find_channel_by_name (tuner, v4l2object->channel);
798   if (channel) {
799     gst_tuner_set_channel (tuner, channel);
800   } else {
801     channel =
802         GST_TUNER_CHANNEL (gst_tuner_get_channel (GST_TUNER
803             (v4l2object->element)));
804     if (channel) {
805       g_free (v4l2object->channel);
806       v4l2object->channel = g_strdup (channel->label);
807       gst_tuner_channel_changed (tuner, channel);
808     }
809   }
810
811   if (channel
812       && GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
813     if (v4l2object->frequency != 0) {
814       gst_tuner_set_frequency (tuner, channel, v4l2object->frequency);
815     } else {
816       v4l2object->frequency = gst_tuner_get_frequency (tuner, channel);
817       if (v4l2object->frequency == 0) {
818         /* guess */
819         gst_tuner_set_frequency (tuner, channel, 1000);
820       } else {
821       }
822     }
823   }
824 }
825
826 gboolean
827 gst_v4l2_object_open (GstV4l2Object * v4l2object)
828 {
829   if (gst_v4l2_open (v4l2object))
830     gst_v4l2_set_defaults (v4l2object);
831   else
832     return FALSE;
833
834 #ifdef HAVE_XVIDEO
835   gst_v4l2_video_overlay_start (v4l2object);
836 #endif
837
838   return TRUE;
839 }
840
841 gboolean
842 gst_v4l2_object_close (GstV4l2Object * v4l2object)
843 {
844 #ifdef HAVE_XVIDEO
845   gst_v4l2_video_overlay_stop (v4l2object);
846 #endif
847
848   if (!gst_v4l2_close (v4l2object))
849     return FALSE;
850
851   if (v4l2object->formats) {
852     gst_v4l2_object_clear_format_list (v4l2object);
853   }
854
855   return TRUE;
856 }
857
858
859 /*
860  * common format / caps utilities:
861  */
862 typedef struct
863 {
864   guint32 format;
865   gboolean dimensions;
866 } GstV4L2FormatDesc;
867
868 static const GstV4L2FormatDesc gst_v4l2_formats[] = {
869   /* from Linux 2.6.15 videodev2.h */
870   {V4L2_PIX_FMT_RGB332, TRUE},
871   {V4L2_PIX_FMT_RGB555, TRUE},
872   {V4L2_PIX_FMT_RGB565, TRUE},
873   {V4L2_PIX_FMT_RGB555X, TRUE},
874   {V4L2_PIX_FMT_RGB565X, TRUE},
875   {V4L2_PIX_FMT_BGR24, TRUE},
876   {V4L2_PIX_FMT_RGB24, TRUE},
877   {V4L2_PIX_FMT_BGR32, TRUE},
878   {V4L2_PIX_FMT_RGB32, TRUE},
879   {V4L2_PIX_FMT_GREY, TRUE},
880   {V4L2_PIX_FMT_YVU410, TRUE},
881   {V4L2_PIX_FMT_YVU420, TRUE},
882   {V4L2_PIX_FMT_YUYV, TRUE},
883   {V4L2_PIX_FMT_UYVY, TRUE},
884   {V4L2_PIX_FMT_YUV422P, TRUE},
885   {V4L2_PIX_FMT_YUV411P, TRUE},
886   {V4L2_PIX_FMT_Y41P, TRUE},
887
888   /* two planes -- one Y, one Cr + Cb interleaved  */
889   {V4L2_PIX_FMT_NV12, TRUE},
890   {V4L2_PIX_FMT_NV21, TRUE},
891
892   /*  The following formats are not defined in the V4L2 specification */
893   {V4L2_PIX_FMT_YUV410, TRUE},
894   {V4L2_PIX_FMT_YUV420, TRUE},
895   {V4L2_PIX_FMT_YYUV, TRUE},
896   {V4L2_PIX_FMT_HI240, TRUE},
897
898   /* see http://www.siliconimaging.com/RGB%20Bayer.htm */
899 #ifdef V4L2_PIX_FMT_SBGGR8
900   {V4L2_PIX_FMT_SBGGR8, TRUE},
901 #endif
902
903   /* compressed formats */
904   {V4L2_PIX_FMT_MJPEG, TRUE},
905   {V4L2_PIX_FMT_JPEG, TRUE},
906 #ifdef V4L2_PIX_FMT_PJPG
907   {V4L2_PIX_FMT_PJPG, TRUE},
908 #endif
909   {V4L2_PIX_FMT_DV, TRUE},
910   {V4L2_PIX_FMT_MPEG, FALSE},
911 #ifdef V4L2_PIX_FMT_MPEG4
912   {V4L2_PIX_FMT_MPEG4, TRUE},
913 #endif
914
915 #ifdef V4L2_PIX_FMT_H263
916   {V4L2_PIX_FMT_H263, TRUE},
917 #endif
918 #ifdef V4L2_PIX_FMT_H264
919   {V4L2_PIX_FMT_H264, TRUE},
920 #endif
921
922   /*  Vendor-specific formats   */
923   {V4L2_PIX_FMT_WNVA, TRUE},
924
925 #ifdef V4L2_PIX_FMT_SN9C10X
926   {V4L2_PIX_FMT_SN9C10X, TRUE},
927 #endif
928 #ifdef V4L2_PIX_FMT_PWC1
929   {V4L2_PIX_FMT_PWC1, TRUE},
930 #endif
931 #ifdef V4L2_PIX_FMT_PWC2
932   {V4L2_PIX_FMT_PWC2, TRUE},
933 #endif
934 #ifdef V4L2_PIX_FMT_YVYU
935   {V4L2_PIX_FMT_YVYU, TRUE},
936 #endif
937 };
938
939 #define GST_V4L2_FORMAT_COUNT (G_N_ELEMENTS (gst_v4l2_formats))
940
941
942 static struct v4l2_fmtdesc *
943 gst_v4l2_object_get_format_from_fourcc (GstV4l2Object * v4l2object,
944     guint32 fourcc)
945 {
946   struct v4l2_fmtdesc *fmt;
947   GSList *walk;
948
949   if (fourcc == 0)
950     return NULL;
951
952   walk = gst_v4l2_object_get_format_list (v4l2object);
953   while (walk) {
954     fmt = (struct v4l2_fmtdesc *) walk->data;
955     if (fmt->pixelformat == fourcc)
956       return fmt;
957     /* special case for jpeg */
958     if (fmt->pixelformat == V4L2_PIX_FMT_MJPEG ||
959         fmt->pixelformat == V4L2_PIX_FMT_JPEG
960 #ifdef V4L2_PIX_FMT_PJPG
961         || fmt->pixelformat == V4L2_PIX_FMT_PJPG
962 #endif
963         ) {
964       if (fourcc == V4L2_PIX_FMT_JPEG || fourcc == V4L2_PIX_FMT_MJPEG
965 #ifdef V4L2_PIX_FMT_PJPG
966           || fourcc == V4L2_PIX_FMT_PJPG
967 #endif
968           ) {
969         return fmt;
970       }
971     }
972     walk = g_slist_next (walk);
973   }
974
975   return NULL;
976 }
977
978
979
980 /* complete made up ranking, the values themselves are meaningless */
981 /* These ranks MUST be X such that X<<15 fits on a signed int - see
982    the comment at the end of gst_v4l2_object_format_get_rank. */
983 #define YUV_BASE_RANK     1000
984 #define JPEG_BASE_RANK     500
985 #define DV_BASE_RANK       200
986 #define RGB_BASE_RANK      100
987 #define YUV_ODD_BASE_RANK   50
988 #define RGB_ODD_BASE_RANK   25
989 #define BAYER_BASE_RANK     15
990 #define S910_BASE_RANK      10
991 #define GREY_BASE_RANK       5
992 #define PWC_BASE_RANK        1
993
994 /* This flag is already used by libv4l2 although
995  * it was added to the Linux kernel in 2.6.32
996  */
997 #ifndef V4L2_FMT_FLAG_EMULATED
998 #define V4L2_FMT_FLAG_EMULATED 0x0002
999 #endif
1000
1001 static gint
1002 gst_v4l2_object_format_get_rank (const struct v4l2_fmtdesc *fmt)
1003 {
1004   guint32 fourcc = fmt->pixelformat;
1005   gboolean emulated = ((fmt->flags & V4L2_FMT_FLAG_EMULATED) != 0);
1006   gint rank = 0;
1007
1008   switch (fourcc) {
1009     case V4L2_PIX_FMT_MJPEG:
1010 #ifdef V4L2_PIX_FMT_PJPG
1011     case V4L2_PIX_FMT_PJPG:
1012       rank = JPEG_BASE_RANK;
1013       break;
1014 #endif
1015     case V4L2_PIX_FMT_JPEG:
1016       rank = JPEG_BASE_RANK + 1;
1017       break;
1018     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1019       rank = JPEG_BASE_RANK + 2;
1020       break;
1021
1022     case V4L2_PIX_FMT_RGB332:
1023     case V4L2_PIX_FMT_RGB555:
1024     case V4L2_PIX_FMT_RGB555X:
1025     case V4L2_PIX_FMT_RGB565:
1026     case V4L2_PIX_FMT_RGB565X:
1027       rank = RGB_ODD_BASE_RANK;
1028       break;
1029
1030     case V4L2_PIX_FMT_RGB24:
1031     case V4L2_PIX_FMT_BGR24:
1032       rank = RGB_BASE_RANK - 1;
1033       break;
1034
1035     case V4L2_PIX_FMT_RGB32:
1036     case V4L2_PIX_FMT_BGR32:
1037       rank = RGB_BASE_RANK;
1038       break;
1039
1040     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1041       rank = GREY_BASE_RANK;
1042       break;
1043
1044     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1045     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1046     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1047     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1048       rank = YUV_ODD_BASE_RANK;
1049       break;
1050
1051     case V4L2_PIX_FMT_YVU410:  /* YVU9,  9 bits per pixel */
1052       rank = YUV_BASE_RANK + 3;
1053       break;
1054     case V4L2_PIX_FMT_YUV410:  /* YUV9,  9 bits per pixel */
1055       rank = YUV_BASE_RANK + 2;
1056       break;
1057     case V4L2_PIX_FMT_YUV420:  /* I420, 12 bits per pixel */
1058       rank = YUV_BASE_RANK + 7;
1059       break;
1060     case V4L2_PIX_FMT_YUYV:    /* YUY2, 16 bits per pixel */
1061       rank = YUV_BASE_RANK + 10;
1062       break;
1063     case V4L2_PIX_FMT_YVU420:  /* YV12, 12 bits per pixel */
1064       rank = YUV_BASE_RANK + 6;
1065       break;
1066     case V4L2_PIX_FMT_UYVY:    /* UYVY, 16 bits per pixel */
1067       rank = YUV_BASE_RANK + 9;
1068       break;
1069     case V4L2_PIX_FMT_Y41P:    /* Y41P, 12 bits per pixel */
1070       rank = YUV_BASE_RANK + 5;
1071       break;
1072     case V4L2_PIX_FMT_YUV411P: /* Y41B, 12 bits per pixel */
1073       rank = YUV_BASE_RANK + 4;
1074       break;
1075     case V4L2_PIX_FMT_YUV422P: /* Y42B, 16 bits per pixel */
1076       rank = YUV_BASE_RANK + 8;
1077       break;
1078
1079     case V4L2_PIX_FMT_DV:
1080       rank = DV_BASE_RANK;
1081       break;
1082
1083     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1084       rank = 0;
1085       break;
1086
1087 #ifdef V4L2_PIX_FMT_SBGGR8
1088     case V4L2_PIX_FMT_SBGGR8:
1089       rank = BAYER_BASE_RANK;
1090       break;
1091 #endif
1092
1093 #ifdef V4L2_PIX_FMT_SN9C10X
1094     case V4L2_PIX_FMT_SN9C10X:
1095       rank = S910_BASE_RANK;
1096       break;
1097 #endif
1098
1099 #ifdef V4L2_PIX_FMT_PWC1
1100     case V4L2_PIX_FMT_PWC1:
1101       rank = PWC_BASE_RANK;
1102       break;
1103 #endif
1104 #ifdef V4L2_PIX_FMT_PWC2
1105     case V4L2_PIX_FMT_PWC2:
1106       rank = PWC_BASE_RANK;
1107       break;
1108 #endif
1109
1110     default:
1111       rank = 0;
1112       break;
1113   }
1114
1115   /* All ranks are below 1<<15 so a shift by 15
1116    * will a) make all non-emulated formats larger
1117    * than emulated and b) will not overflow
1118    */
1119   if (!emulated)
1120     rank <<= 15;
1121
1122   return rank;
1123 }
1124
1125
1126
1127 static gint
1128 format_cmp_func (gconstpointer a, gconstpointer b)
1129 {
1130   const struct v4l2_fmtdesc *fa = a;
1131   const struct v4l2_fmtdesc *fb = b;
1132
1133   if (fa->pixelformat == fb->pixelformat)
1134     return 0;
1135
1136   return gst_v4l2_object_format_get_rank (fb) -
1137       gst_v4l2_object_format_get_rank (fa);
1138 }
1139
1140 /******************************************************
1141  * gst_v4l2_object_fill_format_list():
1142  *   create list of supported capture formats
1143  * return value: TRUE on success, FALSE on error
1144  ******************************************************/
1145 static gboolean
1146 gst_v4l2_object_fill_format_list (GstV4l2Object * v4l2object)
1147 {
1148   gint n;
1149   struct v4l2_fmtdesc *format;
1150
1151   GST_DEBUG_OBJECT (v4l2object->element, "getting src format enumerations");
1152
1153   /* format enumeration */
1154   for (n = 0;; n++) {
1155     format = g_new0 (struct v4l2_fmtdesc, 1);
1156
1157     format->index = n;
1158     format->type = v4l2object->type;
1159
1160     if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_ENUM_FMT, format) < 0) {
1161       if (errno == EINVAL) {
1162         g_free (format);
1163         break;                  /* end of enumeration */
1164       } else {
1165         goto failed;
1166       }
1167     }
1168
1169     GST_LOG_OBJECT (v4l2object->element, "index:       %u", format->index);
1170     GST_LOG_OBJECT (v4l2object->element, "type:        %d", format->type);
1171     GST_LOG_OBJECT (v4l2object->element, "flags:       %08x", format->flags);
1172     GST_LOG_OBJECT (v4l2object->element, "description: '%s'",
1173         format->description);
1174     GST_LOG_OBJECT (v4l2object->element, "pixelformat: %" GST_FOURCC_FORMAT,
1175         GST_FOURCC_ARGS (format->pixelformat));
1176
1177     /* sort formats according to our preference;  we do this, because caps
1178      * are probed in the order the formats are in the list, and the order of
1179      * formats in the final probed caps matters for things like fixation */
1180     v4l2object->formats = g_slist_insert_sorted (v4l2object->formats, format,
1181         (GCompareFunc) format_cmp_func);
1182   }
1183
1184 #ifndef GST_DISABLE_GST_DEBUG
1185   {
1186     GSList *l;
1187
1188     GST_INFO_OBJECT (v4l2object->element, "got %d format(s):", n);
1189     for (l = v4l2object->formats; l != NULL; l = l->next) {
1190       format = l->data;
1191
1192       GST_INFO_OBJECT (v4l2object->element,
1193           "  %" GST_FOURCC_FORMAT "%s", GST_FOURCC_ARGS (format->pixelformat),
1194           ((format->flags & V4L2_FMT_FLAG_EMULATED)) ? " (emulated)" : "");
1195     }
1196   }
1197 #endif
1198
1199   return TRUE;
1200
1201   /* ERRORS */
1202 failed:
1203   {
1204     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
1205         (_("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)));
1206     g_free (format);
1207     return FALSE;
1208   }
1209 }
1210
1211 /*
1212  * Get the list of supported capture formats, a list of
1213  * <code>struct v4l2_fmtdesc</code>.
1214  */
1215 GSList *
1216 gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object)
1217 {
1218   if (!v4l2object->formats)
1219     gst_v4l2_object_fill_format_list (v4l2object);
1220   return v4l2object->formats;
1221 }
1222
1223
1224 GstStructure *
1225 gst_v4l2_object_v4l2fourcc_to_structure (guint32 fourcc)
1226 {
1227   GstStructure *structure = NULL;
1228
1229   switch (fourcc) {
1230     case V4L2_PIX_FMT_MJPEG:   /* Motion-JPEG */
1231 #ifdef V4L2_PIX_FMT_PJPG
1232     case V4L2_PIX_FMT_PJPG:    /* Progressive-JPEG */
1233 #endif
1234     case V4L2_PIX_FMT_JPEG:    /* JFIF JPEG */
1235       structure = gst_structure_new_empty ("image/jpeg");
1236       break;
1237     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1238     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1239       /* FIXME: get correct fourccs here */
1240       break;
1241 #ifdef V4L2_PIX_FMT_MPEG4
1242     case V4L2_PIX_FMT_MPEG4:
1243       structure = gst_structure_new ("video/mpeg",
1244           "mpegversion", G_TYPE_INT, 4, "systemstream",
1245           G_TYPE_BOOLEAN, FALSE, NULL);
1246       break;
1247 #endif
1248 #ifdef V4L2_PIX_FMT_H263
1249     case V4L2_PIX_FMT_H263:
1250       structure = gst_structure_new ("video/x-h263",
1251           "variant", G_TYPE_STRING, "itu", NULL);
1252       break;
1253 #endif
1254 #ifdef V4L2_PIX_FMT_H264
1255     case V4L2_PIX_FMT_H264:    /* H.264 */
1256       structure = gst_structure_new_empty ("video/x-h264");
1257       break;
1258 #endif
1259     case V4L2_PIX_FMT_RGB332:
1260     case V4L2_PIX_FMT_RGB555X:
1261     case V4L2_PIX_FMT_RGB565X:
1262       /* FIXME: get correct fourccs here */
1263       break;
1264     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1265     case V4L2_PIX_FMT_RGB555:
1266     case V4L2_PIX_FMT_RGB565:
1267     case V4L2_PIX_FMT_RGB24:
1268     case V4L2_PIX_FMT_BGR24:
1269     case V4L2_PIX_FMT_RGB32:
1270     case V4L2_PIX_FMT_BGR32:
1271     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1272     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1273     case V4L2_PIX_FMT_YVU410:
1274     case V4L2_PIX_FMT_YUV410:
1275     case V4L2_PIX_FMT_YUV420:  /* I420/IYUV */
1276     case V4L2_PIX_FMT_YUYV:
1277     case V4L2_PIX_FMT_YVU420:
1278     case V4L2_PIX_FMT_UYVY:
1279 #if 0
1280     case V4L2_PIX_FMT_Y41P:
1281 #endif
1282     case V4L2_PIX_FMT_YUV422P:
1283 #ifdef V4L2_PIX_FMT_YVYU
1284     case V4L2_PIX_FMT_YVYU:
1285 #endif
1286     case V4L2_PIX_FMT_YUV411P:{
1287       GstVideoFormat format;
1288
1289       switch (fourcc) {
1290         case V4L2_PIX_FMT_GREY:        /*  8  Greyscale     */
1291           format = GST_VIDEO_FORMAT_GRAY8;
1292           break;
1293         case V4L2_PIX_FMT_RGB555:
1294           format = GST_VIDEO_FORMAT_RGB15;
1295           break;
1296         case V4L2_PIX_FMT_RGB565:
1297           format = GST_VIDEO_FORMAT_RGB16;
1298           break;
1299         case V4L2_PIX_FMT_RGB24:
1300           format = GST_VIDEO_FORMAT_RGB;
1301           break;
1302         case V4L2_PIX_FMT_BGR24:
1303           format = GST_VIDEO_FORMAT_BGR;
1304           break;
1305         case V4L2_PIX_FMT_RGB32:
1306           format = GST_VIDEO_FORMAT_RGBx;
1307           break;
1308         case V4L2_PIX_FMT_BGR32:
1309           format = GST_VIDEO_FORMAT_BGRx;
1310           break;
1311         case V4L2_PIX_FMT_NV12:
1312           format = GST_VIDEO_FORMAT_NV12;
1313           break;
1314         case V4L2_PIX_FMT_NV21:
1315           format = GST_VIDEO_FORMAT_NV21;
1316           break;
1317         case V4L2_PIX_FMT_YVU410:
1318           format = GST_VIDEO_FORMAT_YVU9;
1319           break;
1320         case V4L2_PIX_FMT_YUV410:
1321           format = GST_VIDEO_FORMAT_YUV9;
1322           break;
1323         case V4L2_PIX_FMT_YUV420:
1324           format = GST_VIDEO_FORMAT_I420;
1325           break;
1326         case V4L2_PIX_FMT_YUYV:
1327           format = GST_VIDEO_FORMAT_YUY2;
1328           break;
1329         case V4L2_PIX_FMT_YVU420:
1330           format = GST_VIDEO_FORMAT_YV12;
1331           break;
1332         case V4L2_PIX_FMT_UYVY:
1333           format = GST_VIDEO_FORMAT_UYVY;
1334           break;
1335 #if 0
1336         case V4L2_PIX_FMT_Y41P:
1337           format = GST_VIDEO_FORMAT_Y41P;
1338           break;
1339 #endif
1340         case V4L2_PIX_FMT_YUV411P:
1341           format = GST_VIDEO_FORMAT_Y41B;
1342           break;
1343         case V4L2_PIX_FMT_YUV422P:
1344           format = GST_VIDEO_FORMAT_Y42B;
1345           break;
1346 #ifdef V4L2_PIX_FMT_YVYU
1347         case V4L2_PIX_FMT_YVYU:
1348           format = GST_VIDEO_FORMAT_YVYU;
1349           break;
1350 #endif
1351         default:
1352           format = GST_VIDEO_FORMAT_UNKNOWN;
1353           g_assert_not_reached ();
1354           break;
1355       }
1356       structure = gst_structure_new ("video/x-raw",
1357           "format", G_TYPE_STRING, gst_video_format_to_string (format), NULL);
1358       break;
1359     }
1360     case V4L2_PIX_FMT_DV:
1361       structure =
1362           gst_structure_new ("video/x-dv", "systemstream", G_TYPE_BOOLEAN, TRUE,
1363           NULL);
1364       break;
1365     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1366       structure = gst_structure_new_empty ("video/mpegts");
1367       break;
1368     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1369       break;
1370 #ifdef V4L2_PIX_FMT_SBGGR8
1371     case V4L2_PIX_FMT_SBGGR8:
1372       structure = gst_structure_new_empty ("video/x-bayer");
1373       break;
1374 #endif
1375 #ifdef V4L2_PIX_FMT_SN9C10X
1376     case V4L2_PIX_FMT_SN9C10X:
1377       structure = gst_structure_new_empty ("video/x-sonix");
1378       break;
1379 #endif
1380 #ifdef V4L2_PIX_FMT_PWC1
1381     case V4L2_PIX_FMT_PWC1:
1382       structure = gst_structure_new_empty ("video/x-pwc1");
1383       break;
1384 #endif
1385 #ifdef V4L2_PIX_FMT_PWC2
1386     case V4L2_PIX_FMT_PWC2:
1387       structure = gst_structure_new_empty ("video/x-pwc2");
1388       break;
1389 #endif
1390     default:
1391       GST_DEBUG ("Unknown fourcc 0x%08x %" GST_FOURCC_FORMAT,
1392           fourcc, GST_FOURCC_ARGS (fourcc));
1393       break;
1394   }
1395
1396   return structure;
1397 }
1398
1399
1400
1401 GstCaps *
1402 gst_v4l2_object_get_all_caps (void)
1403 {
1404   static GstCaps *caps = NULL;
1405
1406   if (caps == NULL) {
1407     GstStructure *structure;
1408
1409     guint i;
1410
1411     caps = gst_caps_new_empty ();
1412     for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1413       structure =
1414           gst_v4l2_object_v4l2fourcc_to_structure (gst_v4l2_formats[i].format);
1415       if (structure) {
1416         if (gst_v4l2_formats[i].dimensions) {
1417           gst_structure_set (structure,
1418               "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1419               "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1420               "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1, NULL);
1421         }
1422         gst_caps_append_structure (caps, structure);
1423       }
1424     }
1425   }
1426
1427   return gst_caps_ref (caps);
1428 }
1429
1430
1431 /* collect data for the given caps
1432  * @caps: given input caps
1433  * @format: location for the v4l format
1434  * @w/@h: location for width and height
1435  * @fps_n/@fps_d: location for framerate
1436  * @size: location for expected size of the frame or 0 if unknown
1437  */
1438 static gboolean
1439 gst_v4l2_object_get_caps_info (GstV4l2Object * v4l2object, GstCaps * caps,
1440     struct v4l2_fmtdesc **format, GstVideoInfo * info)
1441 {
1442   GstStructure *structure;
1443   guint32 fourcc;
1444   const gchar *mimetype;
1445   struct v4l2_fmtdesc *fmt;
1446
1447   /* default unknown values */
1448   fourcc = 0;
1449
1450   structure = gst_caps_get_structure (caps, 0);
1451
1452   mimetype = gst_structure_get_name (structure);
1453
1454   if (!gst_video_info_from_caps (info, caps))
1455     goto invalid_format;
1456
1457   if (g_str_equal (mimetype, "video/x-raw")) {
1458     switch (GST_VIDEO_INFO_FORMAT (info)) {
1459       case GST_VIDEO_FORMAT_I420:
1460         fourcc = V4L2_PIX_FMT_YUV420;
1461         break;
1462       case GST_VIDEO_FORMAT_YUY2:
1463         fourcc = V4L2_PIX_FMT_YUYV;
1464         break;
1465 #if 0
1466       case GST_VIDEO_FORMAT_Y41P:
1467         fourcc = V4L2_PIX_FMT_Y41P;
1468         break;
1469 #endif
1470       case GST_VIDEO_FORMAT_UYVY:
1471         fourcc = V4L2_PIX_FMT_UYVY;
1472         break;
1473       case GST_VIDEO_FORMAT_YV12:
1474         fourcc = V4L2_PIX_FMT_YVU420;
1475         break;
1476       case GST_VIDEO_FORMAT_Y41B:
1477         fourcc = V4L2_PIX_FMT_YUV411P;
1478         break;
1479       case GST_VIDEO_FORMAT_Y42B:
1480         fourcc = V4L2_PIX_FMT_YUV422P;
1481         break;
1482       case GST_VIDEO_FORMAT_NV12:
1483         fourcc = V4L2_PIX_FMT_NV12;
1484         break;
1485       case GST_VIDEO_FORMAT_NV21:
1486         fourcc = V4L2_PIX_FMT_NV21;
1487         break;
1488 #ifdef V4L2_PIX_FMT_YVYU
1489       case GST_VIDEO_FORMAT_YVYU:
1490         fourcc = V4L2_PIX_FMT_YVYU;
1491         break;
1492 #endif
1493       case GST_VIDEO_FORMAT_RGB15:
1494         fourcc = V4L2_PIX_FMT_RGB555;
1495         break;
1496       case GST_VIDEO_FORMAT_RGB16:
1497         fourcc = V4L2_PIX_FMT_RGB565;
1498         break;
1499       case GST_VIDEO_FORMAT_RGB:
1500         fourcc = V4L2_PIX_FMT_RGB24;
1501         break;
1502       case GST_VIDEO_FORMAT_BGR:
1503         fourcc = V4L2_PIX_FMT_BGR24;
1504         break;
1505       case GST_VIDEO_FORMAT_RGBx:
1506       case GST_VIDEO_FORMAT_RGBA:
1507         fourcc = V4L2_PIX_FMT_RGB32;
1508         break;
1509       case GST_VIDEO_FORMAT_BGRx:
1510       case GST_VIDEO_FORMAT_BGRA:
1511         fourcc = V4L2_PIX_FMT_BGR32;
1512         break;
1513       case GST_VIDEO_FORMAT_GRAY8:
1514         fourcc = V4L2_PIX_FMT_GREY;
1515       default:
1516         break;
1517     }
1518   } else {
1519     gboolean dimensions = TRUE;
1520
1521     if (g_str_equal (mimetype, "video/mpegts")) {
1522       fourcc = V4L2_PIX_FMT_MPEG;
1523       dimensions = FALSE;
1524     } else if (g_str_equal (mimetype, "video/x-dv")) {
1525       fourcc = V4L2_PIX_FMT_DV;
1526     } else if (g_str_equal (mimetype, "image/jpeg")) {
1527       fourcc = V4L2_PIX_FMT_JPEG;
1528 #ifdef V4L2_PIX_FMT_MPEG4
1529     } else if (g_str_equal (mimetype, "video/mpeg")) {
1530       fourcc = V4L2_PIX_FMT_MPEG4;
1531 #endif
1532 #ifdef V4L2_PIX_FMT_H263
1533     } else if (g_str_equal (mimetype, "video/x-h263")) {
1534       fourcc = V4L2_PIX_FMT_H263;
1535 #endif
1536 #ifdef V4L2_PIX_FMT_H264
1537     } else if (g_str_equal (mimetype, "video/x-h264")) {
1538       fourcc = V4L2_PIX_FMT_H264;
1539 #endif
1540 #ifdef V4L2_PIX_FMT_SBGGR8
1541     } else if (g_str_equal (mimetype, "video/x-bayer")) {
1542       fourcc = V4L2_PIX_FMT_SBGGR8;
1543 #endif
1544 #ifdef V4L2_PIX_FMT_SN9C10X
1545     } else if (g_str_equal (mimetype, "video/x-sonix")) {
1546       fourcc = V4L2_PIX_FMT_SN9C10X;
1547 #endif
1548 #ifdef V4L2_PIX_FMT_PWC1
1549     } else if (g_str_equal (mimetype, "video/x-pwc1")) {
1550       fourcc = V4L2_PIX_FMT_PWC1;
1551 #endif
1552 #ifdef V4L2_PIX_FMT_PWC2
1553     } else if (g_str_equal (mimetype, "video/x-pwc2")) {
1554       fourcc = V4L2_PIX_FMT_PWC2;
1555     }
1556 #endif
1557
1558     if (dimensions) {
1559       const gchar *interlace_mode;
1560
1561       if (!gst_structure_get_int (structure, "width", &info->width))
1562         goto no_width;
1563
1564       if (!gst_structure_get_int (structure, "height", &info->height))
1565         goto no_height;
1566
1567       interlace_mode = gst_structure_get_string (structure, "interlace-mode");
1568       if (g_str_equal (interlace_mode, "progressive")) {
1569         info->interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
1570       } else {
1571         info->interlace_mode = GST_VIDEO_INTERLACE_MODE_MIXED;
1572       }
1573       if (!gst_structure_get_fraction (structure, "framerate", &info->fps_n,
1574               &info->fps_d))
1575         goto no_framerate;
1576     }
1577   }
1578
1579   if (fourcc == 0)
1580     goto unhandled_format;
1581
1582   fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1583   if (fmt == NULL)
1584     goto unsupported_format;
1585
1586   *format = fmt;
1587
1588   return TRUE;
1589
1590   /* ERRORS */
1591 no_width:
1592   {
1593     GST_DEBUG_OBJECT (v4l2object, "no width");
1594     return FALSE;
1595   }
1596 no_height:
1597   {
1598     GST_DEBUG_OBJECT (v4l2object, "no height");
1599     return FALSE;
1600   }
1601 no_framerate:
1602   {
1603     GST_DEBUG_OBJECT (v4l2object, "no framerate");
1604     return FALSE;
1605   }
1606 invalid_format:
1607   {
1608     GST_DEBUG_OBJECT (v4l2object, "invalid format");
1609     return FALSE;
1610   }
1611 unhandled_format:
1612   {
1613     GST_DEBUG_OBJECT (v4l2object, "unhandled format");
1614     return FALSE;
1615   }
1616 unsupported_format:
1617   {
1618     GST_DEBUG_OBJECT (v4l2object, "unsupported format");
1619     return FALSE;
1620   }
1621 }
1622
1623
1624 static gboolean
1625 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1626     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced);
1627
1628
1629 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1630 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1631 static GstStructure *
1632 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1633     guint32 pixelformat,
1634     guint32 width, guint32 height, const GstStructure * template)
1635 {
1636   gint fd = v4l2object->video_fd;
1637   struct v4l2_frmivalenum ival;
1638   guint32 num, denom;
1639   GstStructure *s;
1640   GValue rates = { 0, };
1641   gboolean interlaced;
1642   gint int_width = width;
1643   gint int_height = height;
1644
1645   if (!strcmp ((char *) v4l2object->vcap.driver, "uvcvideo")) {
1646     /*
1647      * UVC devices are never interlaced, and doing VIDIOC_TRY_FMT on them
1648      * causes expensive and slow USB IO, so don't probe them for interlaced
1649      */
1650     interlaced = FALSE;
1651   } else {
1652     /* Interlaced detection using VIDIOC_TRY/S_FMT */
1653     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat,
1654             &int_width, &int_height, &interlaced))
1655       return NULL;
1656   }
1657
1658   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1659   ival.index = 0;
1660   ival.pixel_format = pixelformat;
1661   ival.width = width;
1662   ival.height = height;
1663
1664   GST_LOG_OBJECT (v4l2object->element,
1665       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1666       GST_FOURCC_ARGS (pixelformat));
1667
1668   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1669    * fraction to get framerate */
1670   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1671     goto enum_frameintervals_failed;
1672
1673   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1674     GValue rate = { 0, };
1675
1676     g_value_init (&rates, GST_TYPE_LIST);
1677     g_value_init (&rate, GST_TYPE_FRACTION);
1678
1679     do {
1680       num = ival.discrete.numerator;
1681       denom = ival.discrete.denominator;
1682
1683       if (num > G_MAXINT || denom > G_MAXINT) {
1684         /* let us hope we don't get here... */
1685         num >>= 1;
1686         denom >>= 1;
1687       }
1688
1689       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1690           denom, num);
1691
1692       /* swap to get the framerate */
1693       gst_value_set_fraction (&rate, denom, num);
1694       gst_value_list_append_value (&rates, &rate);
1695
1696       ival.index++;
1697     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1698   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1699     GValue min = { 0, };
1700     GValue step = { 0, };
1701     GValue max = { 0, };
1702     gboolean added = FALSE;
1703     guint32 minnum, mindenom;
1704     guint32 maxnum, maxdenom;
1705
1706     g_value_init (&rates, GST_TYPE_LIST);
1707
1708     g_value_init (&min, GST_TYPE_FRACTION);
1709     g_value_init (&step, GST_TYPE_FRACTION);
1710     g_value_init (&max, GST_TYPE_FRACTION);
1711
1712     /* get the min */
1713     minnum = ival.stepwise.min.numerator;
1714     mindenom = ival.stepwise.min.denominator;
1715     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1716       minnum >>= 1;
1717       mindenom >>= 1;
1718     }
1719     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1720         minnum, mindenom);
1721     gst_value_set_fraction (&min, minnum, mindenom);
1722
1723     /* get the max */
1724     maxnum = ival.stepwise.max.numerator;
1725     maxdenom = ival.stepwise.max.denominator;
1726     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1727       maxnum >>= 1;
1728       maxdenom >>= 1;
1729     }
1730
1731     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1732         maxnum, maxdenom);
1733     gst_value_set_fraction (&max, maxnum, maxdenom);
1734
1735     /* get the step */
1736     num = ival.stepwise.step.numerator;
1737     denom = ival.stepwise.step.denominator;
1738     if (num > G_MAXINT || denom > G_MAXINT) {
1739       num >>= 1;
1740       denom >>= 1;
1741     }
1742
1743     if (num == 0 || denom == 0) {
1744       /* in this case we have a wrong fraction or no step, set the step to max
1745        * so that we only add the min value in the loop below */
1746       num = maxnum;
1747       denom = maxdenom;
1748     }
1749
1750     /* since we only have gst_value_fraction_subtract and not add, negate the
1751      * numerator */
1752     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1753         num, denom);
1754     gst_value_set_fraction (&step, -num, denom);
1755
1756     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
1757       GValue rate = { 0, };
1758
1759       num = gst_value_get_fraction_numerator (&min);
1760       denom = gst_value_get_fraction_denominator (&min);
1761       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1762           denom, num);
1763
1764       /* invert to get the framerate */
1765       g_value_init (&rate, GST_TYPE_FRACTION);
1766       gst_value_set_fraction (&rate, denom, num);
1767       gst_value_list_append_value (&rates, &rate);
1768       added = TRUE;
1769
1770       /* we're actually adding because step was negated above. This is because
1771        * there is no _add function... */
1772       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1773         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1774         break;
1775       }
1776     }
1777     if (!added) {
1778       /* no range was added, leave the default range from the template */
1779       GST_WARNING_OBJECT (v4l2object->element,
1780           "no range added, leaving default");
1781       g_value_unset (&rates);
1782     }
1783   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1784     guint32 maxnum, maxdenom;
1785
1786     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1787
1788     num = ival.stepwise.min.numerator;
1789     denom = ival.stepwise.min.denominator;
1790     if (num > G_MAXINT || denom > G_MAXINT) {
1791       num >>= 1;
1792       denom >>= 1;
1793     }
1794
1795     maxnum = ival.stepwise.max.numerator;
1796     maxdenom = ival.stepwise.max.denominator;
1797     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1798       maxnum >>= 1;
1799       maxdenom >>= 1;
1800     }
1801
1802     GST_LOG_OBJECT (v4l2object->element,
1803         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1804         num);
1805
1806     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1807   } else {
1808     goto unknown_type;
1809   }
1810
1811 return_data:
1812   s = gst_structure_copy (template);
1813   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1814       "height", G_TYPE_INT, (gint) height,
1815       "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, NULL);
1816   if (g_str_equal (gst_structure_get_name (s), "video/x-raw"))
1817     gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
1818         (interlaced ? "mixed" : "progressive"), NULL);
1819
1820   if (G_IS_VALUE (&rates)) {
1821     /* only change the framerate on the template when we have a valid probed new
1822      * value */
1823     gst_structure_set_value (s, "framerate", &rates);
1824     g_value_unset (&rates);
1825   } else {
1826     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1827         NULL);
1828   }
1829   return s;
1830
1831   /* ERRORS */
1832 enum_frameintervals_failed:
1833   {
1834     GST_DEBUG_OBJECT (v4l2object->element,
1835         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1836         GST_FOURCC_ARGS (pixelformat), width, height);
1837     goto return_data;
1838   }
1839 unknown_type:
1840   {
1841     /* I don't see how this is actually an error, we ignore the format then */
1842     GST_WARNING_OBJECT (v4l2object->element,
1843         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1844         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1845     return NULL;
1846   }
1847 }
1848 #endif /* defined VIDIOC_ENUM_FRAMEINTERVALS */
1849
1850 #ifdef VIDIOC_ENUM_FRAMESIZES
1851 static gint
1852 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1853 {
1854   int w1, h1, w2, h2;
1855
1856   gst_structure_get_int (s1, "width", &w1);
1857   gst_structure_get_int (s1, "height", &h1);
1858   gst_structure_get_int (s2, "width", &w2);
1859   gst_structure_get_int (s2, "height", &h2);
1860
1861   /* I think it's safe to assume that this won't overflow for a while */
1862   return ((w2 * h2) - (w1 * h1));
1863 }
1864 #endif
1865
1866 GstCaps *
1867 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
1868     guint32 pixelformat, const GstStructure * template)
1869 {
1870   GstCaps *ret = gst_caps_new_empty ();
1871   GstStructure *tmp;
1872
1873 #ifdef VIDIOC_ENUM_FRAMESIZES
1874   gint fd = v4l2object->video_fd;
1875   struct v4l2_frmsizeenum size;
1876   GList *results = NULL;
1877   guint32 w, h;
1878
1879   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G'))
1880     return gst_caps_new_empty_simple ("video/mpegts");
1881
1882   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
1883   size.index = 0;
1884   size.pixel_format = pixelformat;
1885
1886   GST_DEBUG_OBJECT (v4l2object->element, "Enumerating frame sizes");
1887
1888   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
1889     goto enum_framesizes_failed;
1890
1891   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
1892     do {
1893       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
1894           size.discrete.width, size.discrete.height);
1895
1896       w = MIN (size.discrete.width, G_MAXINT);
1897       h = MIN (size.discrete.height, G_MAXINT);
1898
1899       if (w && h) {
1900         tmp =
1901             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1902             pixelformat, w, h, template);
1903
1904         if (tmp)
1905           results = g_list_prepend (results, tmp);
1906       }
1907
1908       size.index++;
1909     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
1910     GST_DEBUG_OBJECT (v4l2object->element,
1911         "done iterating discrete frame sizes");
1912   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
1913     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
1914     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1915         size.stepwise.min_width);
1916     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1917         size.stepwise.min_height);
1918     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1919         size.stepwise.max_width);
1920     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1921         size.stepwise.max_height);
1922     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
1923         size.stepwise.step_width);
1924     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
1925         size.stepwise.step_height);
1926
1927     for (w = size.stepwise.min_width, h = size.stepwise.min_height;
1928         w <= size.stepwise.max_width && h <= size.stepwise.max_height;
1929         w += size.stepwise.step_width, h += size.stepwise.step_height) {
1930       if (w == 0 || h == 0)
1931         continue;
1932
1933       tmp =
1934           gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1935           pixelformat, w, h, template);
1936
1937       if (tmp)
1938         results = g_list_prepend (results, tmp);
1939     }
1940     GST_DEBUG_OBJECT (v4l2object->element,
1941         "done iterating stepwise frame sizes");
1942   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
1943     guint32 maxw, maxh;
1944
1945     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
1946     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1947         size.stepwise.min_width);
1948     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1949         size.stepwise.min_height);
1950     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1951         size.stepwise.max_width);
1952     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1953         size.stepwise.max_height);
1954
1955     w = MAX (size.stepwise.min_width, 1);
1956     h = MAX (size.stepwise.min_height, 1);
1957     maxw = MIN (size.stepwise.max_width, G_MAXINT);
1958     maxh = MIN (size.stepwise.max_height, G_MAXINT);
1959
1960     tmp =
1961         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
1962         w, h, template);
1963     if (tmp) {
1964       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
1965           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
1966           NULL);
1967
1968       /* no point using the results list here, since there's only one struct */
1969       gst_caps_append_structure (ret, tmp);
1970     }
1971   } else {
1972     goto unknown_type;
1973   }
1974
1975   /* we use an intermediary list to store and then sort the results of the
1976    * probing because we can't make any assumptions about the order in which
1977    * the driver will give us the sizes, but we want the final caps to contain
1978    * the results starting with the highest resolution and having the lowest
1979    * resolution last, since order in caps matters for things like fixation. */
1980   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
1981   while (results != NULL) {
1982     gst_caps_append_structure (ret, GST_STRUCTURE (results->data));
1983     results = g_list_delete_link (results, results);
1984   }
1985
1986   if (gst_caps_is_empty (ret))
1987     goto enum_framesizes_no_results;
1988
1989   return ret;
1990
1991   /* ERRORS */
1992 enum_framesizes_failed:
1993   {
1994     /* I don't see how this is actually an error */
1995     GST_DEBUG_OBJECT (v4l2object->element,
1996         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
1997         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
1998     goto default_frame_sizes;
1999   }
2000 enum_framesizes_no_results:
2001   {
2002     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
2003      * question doesn't actually support it yet */
2004     GST_DEBUG_OBJECT (v4l2object->element,
2005         "No results for pixelformat %" GST_FOURCC_FORMAT
2006         " enumerating frame sizes, trying fallback",
2007         GST_FOURCC_ARGS (pixelformat));
2008     goto default_frame_sizes;
2009   }
2010 unknown_type:
2011   {
2012     GST_WARNING_OBJECT (v4l2object->element,
2013         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
2014         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
2015     goto default_frame_sizes;
2016   }
2017 default_frame_sizes:
2018 #endif /* defined VIDIOC_ENUM_FRAMESIZES */
2019   {
2020     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
2021     gboolean interlaced;
2022
2023     /* This code is for Linux < 2.6.19 */
2024     min_w = min_h = 1;
2025     max_w = max_h = GST_V4L2_MAX_SIZE;
2026     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
2027             &min_h, &interlaced)) {
2028       GST_WARNING_OBJECT (v4l2object->element,
2029           "Could not probe minimum capture size for pixelformat %"
2030           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2031     }
2032     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
2033             &max_h, &interlaced)) {
2034       GST_WARNING_OBJECT (v4l2object->element,
2035           "Could not probe maximum capture size for pixelformat %"
2036           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2037     }
2038
2039     /* Since we can't get framerate directly, try to use the current norm */
2040     if (v4l2object->tv_norm && v4l2object->norms) {
2041       GList *norms;
2042       GstTunerNorm *norm = NULL;
2043       GstTunerNorm *current =
2044           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
2045
2046       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
2047         norm = (GstTunerNorm *) norms->data;
2048         if (!strcmp (norm->label, current->label))
2049           break;
2050       }
2051       /* If it's possible, set framerate to that (discrete) value */
2052       if (norm) {
2053         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
2054         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
2055       }
2056     }
2057
2058     tmp = gst_structure_copy (template);
2059     if (fix_num) {
2060       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
2061           fix_denom, NULL);
2062     } else {
2063       /* if norm can't be used, copy the template framerate */
2064       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
2065           100, 1, NULL);
2066     }
2067
2068     if (min_w == max_w)
2069       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
2070     else
2071       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
2072
2073     if (min_h == max_h)
2074       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
2075     else
2076       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
2077
2078     if (g_str_equal (gst_structure_get_name (tmp), "video/x-raw"))
2079       gst_structure_set (tmp, "interlace-mode", G_TYPE_STRING,
2080           (interlaced ? "mixed" : "progressive"), NULL);
2081     gst_structure_set (tmp, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1,
2082         NULL);
2083
2084     gst_caps_append_structure (ret, tmp);
2085
2086     return ret;
2087   }
2088 }
2089
2090 static gboolean
2091 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
2092     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced)
2093 {
2094   struct v4l2_format fmt, prevfmt;
2095   int fd;
2096   int r;
2097   int prevfmt_valid;
2098
2099   g_return_val_if_fail (width != NULL, FALSE);
2100   g_return_val_if_fail (height != NULL, FALSE);
2101
2102   GST_LOG_OBJECT (v4l2object->element,
2103       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2104       *width, *height, GST_FOURCC_ARGS (pixelformat));
2105
2106   fd = v4l2object->video_fd;
2107
2108   /* Some drivers are buggy and will modify the currently set format
2109      when processing VIDIOC_TRY_FMT, so we remember what is set at the
2110      minute, and will reset it when done. */
2111   prevfmt.type = v4l2object->type;
2112   prevfmt_valid = (v4l2_ioctl (fd, VIDIOC_G_FMT, &prevfmt) >= 0);
2113
2114   /* get size delimiters */
2115   memset (&fmt, 0, sizeof (fmt));
2116   fmt.type = v4l2object->type;
2117   fmt.fmt.pix.width = *width;
2118   fmt.fmt.pix.height = *height;
2119   fmt.fmt.pix.pixelformat = pixelformat;
2120   fmt.fmt.pix.field = V4L2_FIELD_NONE;
2121
2122   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2123   if (r < 0 && errno == EINVAL) {
2124     /* try again with interlaced video */
2125     fmt.fmt.pix.width = *width;
2126     fmt.fmt.pix.height = *height;
2127     fmt.fmt.pix.pixelformat = pixelformat;
2128     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2129     r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2130   }
2131
2132   if (r < 0) {
2133     /* The driver might not implement TRY_FMT, in which case we will try
2134        S_FMT to probe */
2135     if (errno != ENOTTY)
2136       goto error;
2137
2138     /* Only try S_FMT if we're not actively capturing yet, which we shouldn't
2139        be, because we're still probing */
2140     if (GST_V4L2_IS_ACTIVE (v4l2object))
2141       goto error;
2142
2143     GST_LOG_OBJECT (v4l2object->element,
2144         "Failed to probe size limit with VIDIOC_TRY_FMT, trying VIDIOC_S_FMT");
2145
2146     fmt.fmt.pix.width = *width;
2147     fmt.fmt.pix.height = *height;
2148
2149     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2150     if (r < 0 && errno == EINVAL) {
2151       /* try again with progressive video */
2152       fmt.fmt.pix.width = *width;
2153       fmt.fmt.pix.height = *height;
2154       fmt.fmt.pix.pixelformat = pixelformat;
2155       fmt.fmt.pix.field = V4L2_FIELD_NONE;
2156       r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2157     }
2158
2159     if (r < 0)
2160       goto error;
2161   }
2162
2163   GST_LOG_OBJECT (v4l2object->element,
2164       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2165
2166   *width = fmt.fmt.pix.width;
2167   *height = fmt.fmt.pix.height;
2168
2169   switch (fmt.fmt.pix.field) {
2170     case V4L2_FIELD_ANY:
2171     case V4L2_FIELD_NONE:
2172       *interlaced = FALSE;
2173       break;
2174     case V4L2_FIELD_INTERLACED:
2175     case V4L2_FIELD_INTERLACED_TB:
2176     case V4L2_FIELD_INTERLACED_BT:
2177       *interlaced = TRUE;
2178       break;
2179     default:
2180       GST_WARNING_OBJECT (v4l2object->element,
2181           "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u",
2182           GST_FOURCC_ARGS (pixelformat), *width, *height);
2183       goto error;
2184   }
2185
2186   if (prevfmt_valid)
2187     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2188   return TRUE;
2189
2190 error:
2191   if (prevfmt_valid)
2192     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2193   return FALSE;
2194 }
2195
2196 static gboolean
2197 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
2198 {
2199   GstV4l2IOMode mode;
2200
2201   GST_DEBUG_OBJECT (v4l2object->element, "initializing the capture system");
2202
2203   GST_V4L2_CHECK_OPEN (v4l2object);
2204   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2205
2206   /* find transport */
2207   mode = v4l2object->req_mode;
2208
2209   if (v4l2object->vcap.capabilities & V4L2_CAP_READWRITE) {
2210     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2211       mode = GST_V4L2_IO_RW;
2212   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
2213     goto method_not_supported;
2214
2215   if (v4l2object->vcap.capabilities & V4L2_CAP_STREAMING) {
2216     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2217       mode = GST_V4L2_IO_MMAP;
2218   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP)
2219     goto method_not_supported;
2220
2221   /* if still no transport selected, error out */
2222   if (mode == GST_V4L2_IO_AUTO)
2223     goto no_supported_capture_method;
2224
2225   GST_INFO_OBJECT (v4l2object->element, "accessing buffers via mode %d", mode);
2226   v4l2object->mode = mode;
2227
2228   /* Map the buffers */
2229   GST_LOG_OBJECT (v4l2object->element, "initiating buffer pool");
2230
2231   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
2232     goto buffer_pool_new_failed;
2233
2234   GST_V4L2_SET_ACTIVE (v4l2object);
2235
2236   return TRUE;
2237
2238   /* ERRORS */
2239 buffer_pool_new_failed:
2240   {
2241     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2242         (_("Could not map buffers from device '%s'"),
2243             v4l2object->videodev),
2244         ("Failed to create buffer pool: %s", g_strerror (errno)));
2245     return FALSE;
2246   }
2247 method_not_supported:
2248   {
2249     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2250         (_("The driver of device '%s' does not support the IO method %d"),
2251             v4l2object->videodev, mode), (NULL));
2252     return FALSE;
2253   }
2254 no_supported_capture_method:
2255   {
2256     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2257         (_("The driver of device '%s' does not support any known IO "
2258                 "method."), v4l2object->videodev), (NULL));
2259     return FALSE;
2260   }
2261 }
2262
2263 gboolean
2264 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps)
2265 {
2266   gint fd = v4l2object->video_fd;
2267   struct v4l2_format format;
2268   struct v4l2_streamparm streamparm;
2269   enum v4l2_field field;
2270   guint32 pixelformat;
2271   struct v4l2_fmtdesc *fmtdesc;
2272   GstVideoInfo info;
2273   gint width, height, fps_n, fps_d, stride;
2274
2275   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
2276     goto invalid_caps;
2277
2278   pixelformat = fmtdesc->pixelformat;
2279   width = GST_VIDEO_INFO_WIDTH (&info);
2280   height = GST_VIDEO_INFO_HEIGHT (&info);
2281   fps_n = GST_VIDEO_INFO_FPS_N (&info);
2282   fps_d = GST_VIDEO_INFO_FPS_D (&info);
2283   stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
2284
2285   if (GST_VIDEO_INFO_IS_INTERLACED (&info)) {
2286     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2287     /* ideally we would differentiate between types of interlaced video
2288      * but there is not sufficient information in the caps..
2289      */
2290     field = V4L2_FIELD_INTERLACED;
2291   } else {
2292     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2293     field = V4L2_FIELD_NONE;
2294   }
2295
2296   GST_DEBUG_OBJECT (v4l2object->element, "Desired format %dx%d, format "
2297       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
2298       GST_FOURCC_ARGS (pixelformat), stride);
2299
2300   GST_V4L2_CHECK_OPEN (v4l2object);
2301   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2302
2303   /* MPEG-TS source cameras don't get their format set for some reason.
2304    * It looks wrong and we weren't able to track down the reason for that code
2305    * so it is disabled until someone who has an mpeg-ts camera complains...
2306    */
2307 #if 0
2308   /* Only unconditionally accept mpegts for sources */
2309   if ((v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
2310       (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')))
2311     goto done;
2312 #endif
2313
2314   memset (&format, 0x00, sizeof (struct v4l2_format));
2315   format.type = v4l2object->type;
2316
2317   if (v4l2_ioctl (fd, VIDIOC_G_FMT, &format) < 0)
2318     goto get_fmt_failed;
2319
2320   GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2321       "%" GST_FOURCC_FORMAT " bytesperline %d, colorspace %d",
2322       format.fmt.pix.width, format.fmt.pix.height,
2323       GST_FOURCC_ARGS (format.fmt.pix.pixelformat), format.fmt.pix.bytesperline,
2324       format.fmt.pix.colorspace);
2325
2326   if (format.type != v4l2object->type ||
2327       format.fmt.pix.width != width ||
2328       format.fmt.pix.height != height ||
2329       format.fmt.pix.pixelformat != pixelformat ||
2330       format.fmt.pix.field != field || format.fmt.pix.bytesperline != stride) {
2331     /* something different, set the format */
2332     GST_DEBUG_OBJECT (v4l2object->element, "Setting format to %dx%d, format "
2333         "%" GST_FOURCC_FORMAT " bytesperline %d", width, height,
2334         GST_FOURCC_ARGS (pixelformat), stride);
2335
2336     format.type = v4l2object->type;
2337     format.fmt.pix.width = width;
2338     format.fmt.pix.height = height;
2339     format.fmt.pix.pixelformat = pixelformat;
2340     format.fmt.pix.field = field;
2341     /* try to ask our prefered stride */
2342     format.fmt.pix.bytesperline = stride;
2343
2344     if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0)
2345       goto set_fmt_failed;
2346
2347     GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2348         "%" GST_FOURCC_FORMAT " stride %d", format.fmt.pix.width,
2349         format.fmt.pix.height, GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2350         format.fmt.pix.bytesperline);
2351
2352     if (format.fmt.pix.width != width || format.fmt.pix.height != height)
2353       goto invalid_dimensions;
2354
2355     if (format.fmt.pix.pixelformat != pixelformat)
2356       goto invalid_pixelformat;
2357   }
2358
2359   /* figure out the frame layout */
2360   v4l2object->bytesperline = format.fmt.pix.bytesperline;
2361   v4l2object->sizeimage = format.fmt.pix.sizeimage;
2362
2363   GST_DEBUG_OBJECT (v4l2object->element, "Got sizeimage %u",
2364       v4l2object->sizeimage);
2365
2366   /* Is there a reason we require the caller to always specify a framerate? */
2367   GST_DEBUG_OBJECT (v4l2object->element, "Desired framerate: %u/%u", fps_n,
2368       fps_d);
2369
2370   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2371   streamparm.type = v4l2object->type;
2372
2373   if (v4l2_ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
2374     goto get_parm_failed;
2375
2376   GST_VIDEO_INFO_FPS_N (&info) =
2377       streamparm.parm.capture.timeperframe.denominator;
2378   GST_VIDEO_INFO_FPS_D (&info) = streamparm.parm.capture.timeperframe.numerator;
2379
2380   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2381     GST_DEBUG_OBJECT (v4l2object->element, "Got framerate: %u/%u",
2382         streamparm.parm.capture.timeperframe.denominator,
2383         streamparm.parm.capture.timeperframe.numerator);
2384
2385     /* We used to skip frame rate setup if the camera was already setup
2386      * with the requested frame rate. This breaks some cameras though,
2387      * causing them to not output data (several models of Thinkpad cameras
2388      * have this problem at least).
2389      * So, don't skip. */
2390     GST_LOG_OBJECT (v4l2object->element, "Setting framerate to %u/%u", fps_n,
2391         fps_d);
2392     /* We want to change the frame rate, so check whether we can. Some cheap USB
2393      * cameras don't have the capability */
2394     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
2395       GST_DEBUG_OBJECT (v4l2object->element,
2396           "Not setting framerate (not supported)");
2397       goto done;
2398     }
2399
2400     /* Note: V4L2 wants the frame interval, we have the frame rate */
2401     streamparm.parm.capture.timeperframe.numerator = fps_d;
2402     streamparm.parm.capture.timeperframe.denominator = fps_n;
2403
2404     /* some cheap USB cam's won't accept any change */
2405     if (v4l2_ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
2406       goto set_parm_failed;
2407
2408     /* get new values */
2409     fps_d = streamparm.parm.capture.timeperframe.numerator;
2410     fps_n = streamparm.parm.capture.timeperframe.denominator;
2411
2412     GST_INFO_OBJECT (v4l2object->element, "Set framerate to %u/%u", fps_n,
2413         fps_d);
2414
2415     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
2416     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
2417   }
2418
2419 done:
2420   /* if we have a framerate pre-calculate duration */
2421   if (fps_n > 0 && fps_d > 0) {
2422     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
2423   } else {
2424     v4l2object->duration = GST_CLOCK_TIME_NONE;
2425   }
2426   v4l2object->info = info;
2427   v4l2object->fmtdesc = fmtdesc;
2428
2429   /* now configure ther pools */
2430   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
2431     goto pool_failed;
2432
2433   return TRUE;
2434
2435   /* ERRORS */
2436 invalid_caps:
2437   {
2438     GST_DEBUG_OBJECT (v4l2object->element, "can't parse caps %" GST_PTR_FORMAT,
2439         caps);
2440     return FALSE;
2441   }
2442 get_fmt_failed:
2443   {
2444     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2445         (_("Device '%s' does not support video capture"),
2446             v4l2object->videodev),
2447         ("Call to G_FMT failed: (%s)", g_strerror (errno)));
2448     return FALSE;
2449   }
2450 set_fmt_failed:
2451   {
2452     if (errno == EBUSY) {
2453       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, BUSY,
2454           (_("Device '%s' is busy"), v4l2object->videodev),
2455           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2456               GST_FOURCC_ARGS (pixelformat), width, height,
2457               g_strerror (errno)));
2458     } else {
2459       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2460           (_("Device '%s' cannot capture at %dx%d"),
2461               v4l2object->videodev, width, height),
2462           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2463               GST_FOURCC_ARGS (pixelformat), width, height,
2464               g_strerror (errno)));
2465     }
2466     return FALSE;
2467   }
2468 invalid_dimensions:
2469   {
2470     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2471         (_("Device '%s' cannot capture at %dx%d"),
2472             v4l2object->videodev, width, height),
2473         ("Tried to capture at %dx%d, but device returned size %dx%d",
2474             width, height, format.fmt.pix.width, format.fmt.pix.height));
2475     return FALSE;
2476   }
2477 invalid_pixelformat:
2478   {
2479     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2480         (_("Device '%s' cannot capture in the specified format"),
2481             v4l2object->videodev),
2482         ("Tried to capture in %" GST_FOURCC_FORMAT
2483             ", but device returned format" " %" GST_FOURCC_FORMAT,
2484             GST_FOURCC_ARGS (pixelformat),
2485             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2486     return FALSE;
2487   }
2488 get_parm_failed:
2489   {
2490     /* it's possible that this call is not supported */
2491     if (errno != EINVAL && errno != ENOTTY) {
2492       GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2493           (_("Could not get parameters on device '%s'"),
2494               v4l2object->videodev), GST_ERROR_SYSTEM);
2495     }
2496     goto done;
2497   }
2498 set_parm_failed:
2499   {
2500     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2501         (_("Video device did not accept new frame rate setting.")),
2502         GST_ERROR_SYSTEM);
2503     goto done;
2504   }
2505 pool_failed:
2506   {
2507     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2508         (_("Video device could not create buffer pool.")), GST_ERROR_SYSTEM);
2509     return FALSE;
2510   }
2511 }
2512
2513 gboolean
2514 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
2515 {
2516   GstStructure *s;
2517   GstCaps *oldcaps;
2518
2519   if (!v4l2object->pool)
2520     return FALSE;
2521
2522   s = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (v4l2object->pool));
2523   gst_buffer_pool_config_get_params (s, &oldcaps, NULL, NULL, NULL);
2524
2525   return oldcaps && gst_caps_is_equal (caps, oldcaps);
2526 }
2527
2528 gboolean
2529 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
2530 {
2531   GST_LOG_OBJECT (v4l2object->element, "flush poll");
2532   gst_poll_set_flushing (v4l2object->poll, TRUE);
2533
2534   return TRUE;
2535 }
2536
2537 gboolean
2538 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
2539 {
2540   GST_LOG_OBJECT (v4l2object->element, "flush stop poll");
2541   gst_poll_set_flushing (v4l2object->poll, FALSE);
2542
2543   return TRUE;
2544 }
2545
2546 gboolean
2547 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
2548 {
2549   GST_DEBUG_OBJECT (v4l2object->element, "stopping");
2550
2551   if (!GST_V4L2_IS_OPEN (v4l2object))
2552     goto done;
2553   if (!GST_V4L2_IS_ACTIVE (v4l2object))
2554     goto done;
2555
2556   if (v4l2object->pool) {
2557     GST_DEBUG_OBJECT (v4l2object->element, "deactivating pool");
2558     gst_buffer_pool_set_active (GST_BUFFER_POOL_CAST (v4l2object->pool), FALSE);
2559     gst_object_unref (v4l2object->pool);
2560     v4l2object->pool = NULL;
2561   }
2562
2563   GST_V4L2_SET_INACTIVE (v4l2object);
2564
2565 done:
2566   return TRUE;
2567 }
2568
2569 gboolean
2570 gst_v4l2_object_copy (GstV4l2Object * v4l2object, GstBuffer * dest,
2571     GstBuffer * src)
2572 {
2573   const GstVideoFormatInfo *finfo = v4l2object->info.finfo;
2574
2575   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
2576           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
2577     GstVideoFrame src_frame, dest_frame;
2578
2579     GST_DEBUG_OBJECT (v4l2object->element, "copy video frame");
2580
2581     /* we have raw video, use videoframe copy to get strides right */
2582     if (!gst_video_frame_map (&src_frame, &v4l2object->info, src, GST_MAP_READ))
2583       goto invalid_buffer;
2584
2585     if (!gst_video_frame_map (&dest_frame, &v4l2object->info, dest,
2586             GST_MAP_WRITE)) {
2587       gst_video_frame_unmap (&src_frame);
2588       goto invalid_buffer;
2589     }
2590
2591     gst_video_frame_copy (&dest_frame, &src_frame);
2592
2593     gst_video_frame_unmap (&src_frame);
2594     gst_video_frame_unmap (&dest_frame);
2595   } else {
2596     GstMapInfo map;
2597
2598     GST_DEBUG_OBJECT (v4l2object->element, "copy raw bytes");
2599     gst_buffer_map (src, &map, GST_MAP_READ);
2600     gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src));
2601     gst_buffer_unmap (src, &map);
2602     gst_buffer_resize (dest, 0, gst_buffer_get_size (src));
2603   }
2604   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, v4l2object->element,
2605       "slow copy into buffer %p", dest);
2606
2607   return TRUE;
2608
2609   /* ERRORS */
2610 invalid_buffer:
2611   {
2612     /* No Window available to put our image into */
2613     GST_WARNING_OBJECT (v4l2object->element, "could not map image");
2614     return FALSE;
2615   }
2616 }