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