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