Tizen 2.0 Release
[framework/multimedia/gst-plugins-good0.10.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 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <string.h>
30
31 #ifdef HAVE_GUDEV
32 #include <gudev/gudev.h>
33 #endif
34
35 #include "v4l2_calls.h"
36 #include "gstv4l2tuner.h"
37 #ifdef HAVE_XVIDEO
38 #include "gstv4l2xoverlay.h"
39 #endif
40 #include "gstv4l2colorbalance.h"
41
42 #include "gst/gst-i18n-plugin.h"
43
44 /* videodev2.h is not versioned and we can't easily check for the presence
45  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
46  * was added in the same commit as V4L2_FIELD_INTERLACED_{TB,BT} (b2787845) */
47 #ifndef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
48 #define V4L2_FIELD_INTERLACED_TB 8
49 #define V4L2_FIELD_INTERLACED_BT 9
50 #endif
51
52 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
53 #define GST_CAT_DEFAULT v4l2_debug
54
55
56 #define DEFAULT_PROP_DEVICE_NAME        NULL
57 #define DEFAULT_PROP_DEVICE_FD          -1
58 #define DEFAULT_PROP_FLAGS              0
59 #define DEFAULT_PROP_TV_NORM            0
60 #define DEFAULT_PROP_CHANNEL            NULL
61 #define DEFAULT_PROP_FREQUENCY          0
62
63 enum
64 {
65   PROP_0,
66   V4L2_STD_OBJECT_PROPS,
67 };
68
69 G_LOCK_DEFINE_STATIC (probe_lock);
70
71 const GList *
72 gst_v4l2_probe_get_properties (GstPropertyProbe * probe)
73 {
74   GObjectClass *klass = G_OBJECT_GET_CLASS (probe);
75   static GList *list = NULL;
76
77   /* well, not perfect, but better than no locking at all.
78    * In the worst case we leak a list node, so who cares? */
79   G_LOCK (probe_lock);
80
81   if (!list) {
82     list = g_list_append (NULL, g_object_class_find_property (klass, "device"));
83   }
84
85   G_UNLOCK (probe_lock);
86
87   return list;
88 }
89
90 static gboolean init = FALSE;
91 static GList *devices = NULL;
92
93 #ifdef HAVE_GUDEV
94 static gboolean
95 gst_v4l2_class_probe_devices_with_udev (GstElementClass * klass, gboolean check,
96     GList ** klass_devices)
97 {
98   GUdevClient *client = NULL;
99   GList *item;
100
101   if (!check) {
102     while (devices) {
103       gchar *device = devices->data;
104       devices = g_list_remove (devices, device);
105       g_free (device);
106     }
107
108     GST_INFO ("Enumerating video4linux devices from udev");
109     client = g_udev_client_new (NULL);
110     if (!client) {
111       GST_WARNING ("Failed to initialize gudev client");
112       goto finish;
113     }
114
115     item = g_udev_client_query_by_subsystem (client, "video4linux");
116     while (item) {
117       GUdevDevice *device = item->data;
118       gchar *devnode = g_strdup (g_udev_device_get_device_file (device));
119       gint api = g_udev_device_get_property_as_int (device, "ID_V4L_VERSION");
120       GST_INFO ("Found new device: %s, API: %d", devnode, api);
121       /* Append v4l2 devices only. If api is 0 probably v4l_id has
122          been stripped out of the current udev installation, append
123          anyway */
124       if (api == 0) {
125         GST_WARNING
126             ("Couldn't retrieve ID_V4L_VERSION, silly udev installation?");
127       }
128       if ((api == 2 || api == 0)) {
129         devices = g_list_append (devices, devnode);
130       } else {
131         g_free (devnode);
132       }
133       g_object_unref (device);
134       item = item->next;
135     }
136     g_list_free (item);
137     init = TRUE;
138   }
139
140 finish:
141   if (client) {
142     g_object_unref (client);
143   }
144
145   *klass_devices = devices;
146
147   return init;
148 }
149 #endif /* HAVE_GUDEV */
150
151 static gboolean
152 gst_v4l2_class_probe_devices (GstElementClass * klass, gboolean check,
153     GList ** klass_devices)
154 {
155   if (!check) {
156     const gchar *dev_base[] = { "/dev/video", "/dev/v4l2/video", NULL };
157     gint base, n, fd;
158
159     while (devices) {
160       gchar *device = devices->data;
161       devices = g_list_remove (devices, device);
162       g_free (device);
163     }
164
165     /*
166      * detect /dev entries
167      */
168     for (n = 0; n < 64; n++) {
169       for (base = 0; dev_base[base] != NULL; base++) {
170         struct stat s;
171         gchar *device = g_strdup_printf ("%s%d",
172             dev_base[base],
173             n);
174
175         /*
176          * does the /dev/ entry exist at all?
177          */
178         if (stat (device, &s) == 0) {
179           /*
180            * yes: is a device attached?
181            */
182           if (S_ISCHR (s.st_mode)) {
183
184             if ((fd = open (device, O_RDWR | O_NONBLOCK)) > 0 || errno == EBUSY) {
185               if (fd > 0)
186                 close (fd);
187
188               devices = g_list_append (devices, device);
189               break;
190             }
191           }
192         }
193         g_free (device);
194       }
195     }
196     init = TRUE;
197   }
198
199   *klass_devices = devices;
200
201   return init;
202 }
203
204 void
205 gst_v4l2_probe_probe_property (GstPropertyProbe * probe,
206     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
207 {
208   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
209
210   switch (prop_id) {
211     case PROP_DEVICE:
212 #ifdef HAVE_GUDEV
213       if (!gst_v4l2_class_probe_devices_with_udev (klass, FALSE, klass_devices))
214         gst_v4l2_class_probe_devices (klass, FALSE, klass_devices);
215 #else /* !HAVE_GUDEV */
216       gst_v4l2_class_probe_devices (klass, FALSE, klass_devices);
217 #endif /* HAVE_GUDEV */
218       break;
219     default:
220       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
221       break;
222   }
223 }
224
225 gboolean
226 gst_v4l2_probe_needs_probe (GstPropertyProbe * probe,
227     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
228 {
229   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
230   gboolean ret = FALSE;
231
232   switch (prop_id) {
233     case PROP_DEVICE:
234 #ifdef HAVE_GUDEV
235       ret =
236           !gst_v4l2_class_probe_devices_with_udev (klass, FALSE, klass_devices);
237 #else /* !HAVE_GUDEV */
238       ret = !gst_v4l2_class_probe_devices (klass, TRUE, klass_devices);
239 #endif /* HAVE_GUDEV */
240       break;
241     default:
242       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
243       break;
244   }
245   return ret;
246 }
247
248 static GValueArray *
249 gst_v4l2_class_list_devices (GstElementClass * klass, GList ** klass_devices)
250 {
251   GValueArray *array;
252   GValue value = { 0 };
253   GList *item;
254
255   if (!*klass_devices)
256     return NULL;
257
258   array = g_value_array_new (g_list_length (*klass_devices));
259   item = *klass_devices;
260   g_value_init (&value, G_TYPE_STRING);
261   while (item) {
262     gchar *device = item->data;
263
264     g_value_set_string (&value, device);
265     g_value_array_append (array, &value);
266
267     item = item->next;
268   }
269   g_value_unset (&value);
270
271   return array;
272 }
273
274 GValueArray *
275 gst_v4l2_probe_get_values (GstPropertyProbe * probe,
276     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
277 {
278   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
279   GValueArray *array = NULL;
280
281   switch (prop_id) {
282     case PROP_DEVICE:
283       array = gst_v4l2_class_list_devices (klass, klass_devices);
284       break;
285     default:
286       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
287       break;
288   }
289
290   return array;
291 }
292
293 #define GST_TYPE_V4L2_DEVICE_FLAGS (gst_v4l2_device_get_type ())
294 static GType
295 gst_v4l2_device_get_type (void)
296 {
297   static GType v4l2_device_type = 0;
298
299   if (v4l2_device_type == 0) {
300     static const GFlagsValue values[] = {
301       {V4L2_CAP_VIDEO_CAPTURE, "Device supports video capture", "capture"},
302       {V4L2_CAP_VIDEO_OUTPUT, "Device supports video playback", "output"},
303       {V4L2_CAP_VIDEO_OVERLAY, "Device supports video overlay", "overlay"},
304
305       {V4L2_CAP_VBI_CAPTURE, "Device supports the VBI capture", "vbi-capture"},
306       {V4L2_CAP_VBI_OUTPUT, "Device supports the VBI output", "vbi-output"},
307
308       {V4L2_CAP_TUNER, "Device has a tuner or modulator", "tuner"},
309       {V4L2_CAP_AUDIO, "Device has audio inputs or outputs", "audio"},
310
311       {0, NULL, NULL}
312     };
313
314     v4l2_device_type =
315         g_flags_register_static ("GstV4l2DeviceTypeFlags", values);
316   }
317
318   return v4l2_device_type;
319 }
320
321 #define GST_TYPE_V4L2_TV_NORM (gst_v4l2_tv_norm_get_type ())
322 static GType
323 gst_v4l2_tv_norm_get_type (void)
324 {
325   static GType v4l2_tv_norm = 0;
326
327   if (!v4l2_tv_norm) {
328     static const GEnumValue tv_norms[] = {
329       {0, "none", "none"},
330
331       {V4L2_STD_NTSC, "NTSC", "NTSC"},
332       {V4L2_STD_NTSC_M, "NTSC-M", "NTSC-M"},
333       {V4L2_STD_NTSC_M_JP, "NTSC-M-JP", "NTSC-M-JP"},
334       {V4L2_STD_NTSC_M_KR, "NTSC-M-KR", "NTSC-M-KR"},
335       {V4L2_STD_NTSC_443, "NTSC-443", "NTSC-443"},
336
337       {V4L2_STD_PAL, "PAL", "PAL"},
338       {V4L2_STD_PAL_BG, "PAL-BG", "PAL-BG"},
339       {V4L2_STD_PAL_B, "PAL-B", "PAL-B"},
340       {V4L2_STD_PAL_B1, "PAL-B1", "PAL-B1"},
341       {V4L2_STD_PAL_G, "PAL-G", "PAL-G"},
342       {V4L2_STD_PAL_H, "PAL-H", "PAL-H"},
343       {V4L2_STD_PAL_I, "PAL-I", "PAL-I"},
344       {V4L2_STD_PAL_DK, "PAL-DK", "PAL-DK"},
345       {V4L2_STD_PAL_D, "PAL-D", "PAL-D"},
346       {V4L2_STD_PAL_D1, "PAL-D1", "PAL-D1"},
347       {V4L2_STD_PAL_K, "PAL-K", "PAL-K"},
348       {V4L2_STD_PAL_M, "PAL-M", "PAL-M"},
349       {V4L2_STD_PAL_N, "PAL-N", "PAL-N"},
350       {V4L2_STD_PAL_Nc, "PAL-Nc", "PAL-Nc"},
351       {V4L2_STD_PAL_60, "PAL-60", "PAL-60"},
352
353       {V4L2_STD_SECAM, "SECAM", "SECAM"},
354       {V4L2_STD_SECAM_B, "SECAM-B", "SECAM-B"},
355       {V4L2_STD_SECAM_G, "SECAM-G", "SECAM-G"},
356       {V4L2_STD_SECAM_H, "SECAM-H", "SECAM-H"},
357       {V4L2_STD_SECAM_DK, "SECAM-DK", "SECAM-DK"},
358       {V4L2_STD_SECAM_D, "SECAM-D", "SECAM-D"},
359       {V4L2_STD_SECAM_K, "SECAM-K", "SECAM-K"},
360       {V4L2_STD_SECAM_K1, "SECAM-K1", "SECAM-K1"},
361       {V4L2_STD_SECAM_L, "SECAM-L", "SECAM-L"},
362       {V4L2_STD_SECAM_LC, "SECAM-Lc", "SECAM-Lc"},
363
364       {0, NULL, NULL}
365     };
366
367     v4l2_tv_norm = g_enum_register_static ("V4L2_TV_norms", tv_norms);
368   }
369
370   return v4l2_tv_norm;
371 }
372
373 void
374 gst_v4l2_object_install_properties_helper (GObjectClass * gobject_class,
375     const char *default_device)
376 {
377   g_object_class_install_property (gobject_class, PROP_DEVICE,
378       g_param_spec_string ("device", "Device", "Device location",
379           default_device, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
380   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
381       g_param_spec_string ("device-name", "Device name",
382           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
383           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
384   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
385       g_param_spec_int ("device-fd", "File descriptor",
386           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
387           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
388   g_object_class_install_property (gobject_class, PROP_FLAGS,
389       g_param_spec_flags ("flags", "Flags", "Device type flags",
390           GST_TYPE_V4L2_DEVICE_FLAGS, DEFAULT_PROP_FLAGS,
391           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
392
393   /**
394    * GstV4l2Src:brightness
395    *
396    * Picture brightness, or more precisely, the black level
397    *
398    * Since: 0.10.26
399    */
400   g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
401       g_param_spec_int ("brightness", "Brightness",
402           "Picture brightness, or more precisely, the black level", G_MININT,
403           G_MAXINT, 0,
404           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
405   /**
406    * GstV4l2Src:contrast
407    *
408    * Picture contrast or luma gain
409    *
410    * Since: 0.10.26
411    */
412   g_object_class_install_property (gobject_class, PROP_CONTRAST,
413       g_param_spec_int ("contrast", "Contrast",
414           "Picture contrast or luma gain", G_MININT,
415           G_MAXINT, 0,
416           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
417   /**
418    * GstV4l2Src:saturation
419    *
420    * Picture color saturation or chroma gain
421    *
422    * Since: 0.10.26
423    */
424   g_object_class_install_property (gobject_class, PROP_SATURATION,
425       g_param_spec_int ("saturation", "Saturation",
426           "Picture color saturation or chroma gain", G_MININT,
427           G_MAXINT, 0,
428           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
429   /**
430    * GstV4l2Src:hue
431    *
432    * Hue or color balance
433    *
434    * Since: 0.10.26
435    */
436   g_object_class_install_property (gobject_class, PROP_HUE,
437       g_param_spec_int ("hue", "Hue",
438           "Hue or color balance", G_MININT,
439           G_MAXINT, 0,
440           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
441
442   /**
443    * GstV4l2Src:norm
444    *
445    * TV norm
446    *
447    * Since: 0.10.31
448    */
449   g_object_class_install_property (gobject_class, PROP_TV_NORM,
450       g_param_spec_enum ("norm", "TV norm",
451           "video standard",
452           GST_TYPE_V4L2_TV_NORM, DEFAULT_PROP_TV_NORM,
453           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
454 }
455
456 GstV4l2Object *
457 gst_v4l2_object_new (GstElement * element,
458     enum v4l2_buf_type type,
459     const char *default_device,
460     GstV4l2GetInOutFunction get_in_out_func,
461     GstV4l2SetInOutFunction set_in_out_func,
462     GstV4l2UpdateFpsFunction update_fps_func)
463 {
464   GstV4l2Object *v4l2object;
465
466   /*
467    * some default values
468    */
469   v4l2object = g_new0 (GstV4l2Object, 1);
470
471   v4l2object->type = type;
472   v4l2object->formats = NULL;
473
474   v4l2object->element = element;
475   v4l2object->get_in_out_func = get_in_out_func;
476   v4l2object->set_in_out_func = set_in_out_func;
477   v4l2object->update_fps_func = update_fps_func;
478
479   v4l2object->video_fd = -1;
480   v4l2object->poll = gst_poll_new (TRUE);
481   v4l2object->buffer = NULL;
482   v4l2object->videodev = g_strdup (default_device);
483
484   v4l2object->norms = NULL;
485   v4l2object->channels = NULL;
486   v4l2object->colors = NULL;
487
488   v4l2object->xwindow_id = 0;
489
490   return v4l2object;
491 }
492
493 static gboolean gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object);
494
495
496 void
497 gst_v4l2_object_destroy (GstV4l2Object * v4l2object)
498 {
499   g_return_if_fail (v4l2object != NULL);
500
501   if (v4l2object->videodev)
502     g_free (v4l2object->videodev);
503
504   if (v4l2object->poll)
505     gst_poll_free (v4l2object->poll);
506
507   if (v4l2object->channel)
508     g_free (v4l2object->channel);
509
510   if (v4l2object->formats) {
511     gst_v4l2_object_clear_format_list (v4l2object);
512   }
513
514   g_free (v4l2object);
515 }
516
517
518 static gboolean
519 gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object)
520 {
521   g_slist_foreach (v4l2object->formats, (GFunc) g_free, NULL);
522   g_slist_free (v4l2object->formats);
523   v4l2object->formats = NULL;
524
525   return TRUE;
526 }
527
528 static gint
529 gst_v4l2_object_prop_to_cid (guint prop_id)
530 {
531   gint cid = -1;
532
533   switch (prop_id) {
534     case PROP_BRIGHTNESS:
535       cid = V4L2_CID_BRIGHTNESS;
536       break;
537     case PROP_CONTRAST:
538       cid = V4L2_CID_CONTRAST;
539       break;
540     case PROP_SATURATION:
541       cid = V4L2_CID_SATURATION;
542       break;
543     case PROP_HUE:
544       cid = V4L2_CID_HUE;
545       break;
546     default:
547       GST_WARNING ("unmapped property id: %d", prop_id);
548   }
549   return cid;
550 }
551
552
553 gboolean
554 gst_v4l2_object_set_property_helper (GstV4l2Object * v4l2object,
555     guint prop_id, const GValue * value, GParamSpec * pspec)
556 {
557   switch (prop_id) {
558     case PROP_DEVICE:
559       g_free (v4l2object->videodev);
560       v4l2object->videodev = g_value_dup_string (value);
561       break;
562     case PROP_BRIGHTNESS:
563     case PROP_CONTRAST:
564     case PROP_SATURATION:
565     case PROP_HUE:
566     {
567       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
568
569       if (cid != -1) {
570         if (GST_V4L2_IS_OPEN (v4l2object)) {
571           gst_v4l2_set_attribute (v4l2object, cid, g_value_get_int (value));
572         }
573       }
574       return TRUE;
575     }
576       break;
577     case PROP_TV_NORM:
578       v4l2object->tv_norm = g_value_get_enum (value);
579       break;
580 #if 0
581     case PROP_CHANNEL:
582       if (GST_V4L2_IS_OPEN (v4l2object)) {
583         GstTuner *tuner = GST_TUNER (v4l2object->element);
584         GstTunerChannel *channel = gst_tuner_find_channel_by_name (tuner,
585             (gchar *) g_value_get_string (value));
586
587         if (channel) {
588           /* like gst_tuner_set_channel (tuner, channel)
589              without g_object_notify */
590           gst_v4l2_tuner_set_channel (v4l2object, channel);
591         }
592       } else {
593         g_free (v4l2object->channel);
594         v4l2object->channel = g_value_dup_string (value);
595       }
596       break;
597     case PROP_FREQUENCY:
598       if (GST_V4L2_IS_OPEN (v4l2object)) {
599         GstTuner *tuner = GST_TUNER (v4l2object->element);
600         GstTunerChannel *channel = gst_tuner_get_channel (tuner);
601
602         if (channel &&
603             GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
604           /* like
605              gst_tuner_set_frequency (tuner, channel, g_value_get_ulong (value))
606              without g_object_notify */
607           gst_v4l2_tuner_set_frequency (v4l2object, channel,
608               g_value_get_ulong (value));
609         }
610       } else {
611         v4l2object->frequency = g_value_get_ulong (value);
612       }
613       break;
614 #endif
615     default:
616       return FALSE;
617       break;
618   }
619   return TRUE;
620 }
621
622
623 gboolean
624 gst_v4l2_object_get_property_helper (GstV4l2Object * v4l2object,
625     guint prop_id, GValue * value, GParamSpec * pspec)
626 {
627   switch (prop_id) {
628     case PROP_DEVICE:
629       g_value_set_string (value, v4l2object->videodev);
630       break;
631     case PROP_DEVICE_NAME:
632     {
633       const guchar *new = NULL;
634
635       if (GST_V4L2_IS_OPEN (v4l2object)) {
636         new = v4l2object->vcap.card;
637       } else if (gst_v4l2_open (v4l2object)) {
638         new = v4l2object->vcap.card;
639         gst_v4l2_close (v4l2object);
640       }
641       g_value_set_string (value, (gchar *) new);
642       break;
643     }
644     case PROP_DEVICE_FD:
645     {
646       if (GST_V4L2_IS_OPEN (v4l2object))
647         g_value_set_int (value, v4l2object->video_fd);
648       else
649         g_value_set_int (value, DEFAULT_PROP_DEVICE_FD);
650       break;
651     }
652     case PROP_FLAGS:
653     {
654       guint flags = 0;
655
656       if (GST_V4L2_IS_OPEN (v4l2object)) {
657         flags |= v4l2object->vcap.capabilities &
658             (V4L2_CAP_VIDEO_CAPTURE |
659             V4L2_CAP_VIDEO_OUTPUT |
660             V4L2_CAP_VIDEO_OVERLAY |
661             V4L2_CAP_VBI_CAPTURE |
662             V4L2_CAP_VBI_OUTPUT | V4L2_CAP_TUNER | V4L2_CAP_AUDIO);
663       }
664       g_value_set_flags (value, flags);
665       break;
666     }
667     case PROP_BRIGHTNESS:
668     case PROP_CONTRAST:
669     case PROP_SATURATION:
670     case PROP_HUE:
671     {
672       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
673
674       if (cid != -1) {
675         if (GST_V4L2_IS_OPEN (v4l2object)) {
676           gint v;
677           if (gst_v4l2_get_attribute (v4l2object, cid, &v)) {
678             g_value_set_int (value, v);
679           }
680         }
681       }
682       return TRUE;
683     }
684       break;
685     case PROP_TV_NORM:
686       g_value_set_enum (value, v4l2object->tv_norm);
687       break;
688     default:
689       return FALSE;
690       break;
691   }
692   return TRUE;
693 }
694
695 static void
696 gst_v4l2_set_defaults (GstV4l2Object * v4l2object)
697 {
698   GstTunerNorm *norm = NULL;
699   GstTunerChannel *channel = NULL;
700   GstTuner *tuner;
701
702   if (!GST_IS_TUNER (v4l2object->element))
703     return;
704
705   tuner = GST_TUNER (v4l2object->element);
706
707   if (v4l2object->tv_norm)
708     norm = gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
709   GST_DEBUG_OBJECT (v4l2object->element, "tv_norm=0x%" G_GINT64_MODIFIER "x, "
710       "norm=%p", (guint64) v4l2object->tv_norm, norm);
711   if (norm) {
712     gst_tuner_set_norm (tuner, norm);
713   } else {
714     norm =
715         GST_TUNER_NORM (gst_tuner_get_norm (GST_TUNER (v4l2object->element)));
716     if (norm) {
717       v4l2object->tv_norm =
718           gst_v4l2_tuner_get_std_id_by_norm (v4l2object, norm);
719       gst_tuner_norm_changed (tuner, norm);
720     }
721   }
722
723   if (v4l2object->channel)
724     channel = gst_tuner_find_channel_by_name (tuner, v4l2object->channel);
725   if (channel) {
726     gst_tuner_set_channel (tuner, channel);
727   } else {
728     channel =
729         GST_TUNER_CHANNEL (gst_tuner_get_channel (GST_TUNER
730             (v4l2object->element)));
731     if (channel) {
732       g_free (v4l2object->channel);
733       v4l2object->channel = g_strdup (channel->label);
734       gst_tuner_channel_changed (tuner, channel);
735     }
736   }
737
738   if (channel
739       && GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
740     if (v4l2object->frequency != 0) {
741       gst_tuner_set_frequency (tuner, channel, v4l2object->frequency);
742     } else {
743       v4l2object->frequency = gst_tuner_get_frequency (tuner, channel);
744       if (v4l2object->frequency == 0) {
745         /* guess */
746         gst_tuner_set_frequency (tuner, channel, 1000);
747       } else {
748       }
749     }
750   }
751 }
752
753 gboolean
754 gst_v4l2_object_start (GstV4l2Object * v4l2object)
755 {
756   if (gst_v4l2_open (v4l2object))
757     gst_v4l2_set_defaults (v4l2object);
758   else
759     return FALSE;
760
761 #ifdef HAVE_XVIDEO
762   gst_v4l2_xoverlay_start (v4l2object);
763 #endif
764
765   return TRUE;
766 }
767
768 gboolean
769 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
770 {
771 #ifdef HAVE_XVIDEO
772   gst_v4l2_xoverlay_stop (v4l2object);
773 #endif
774
775   if (!gst_v4l2_close (v4l2object))
776     return FALSE;
777
778   if (v4l2object->formats) {
779     gst_v4l2_object_clear_format_list (v4l2object);
780   }
781
782   return TRUE;
783 }
784
785
786 /*
787  * common format / caps utilities:
788  */
789 typedef struct
790 {
791   guint32 format;
792   gboolean dimensions;
793 } GstV4L2FormatDesc;
794
795 static const GstV4L2FormatDesc gst_v4l2_formats[] = {
796   /* from Linux 2.6.15 videodev2.h */
797   {V4L2_PIX_FMT_RGB332, TRUE},
798   {V4L2_PIX_FMT_RGB555, TRUE},
799   {V4L2_PIX_FMT_RGB565, TRUE},
800   {V4L2_PIX_FMT_RGB555X, TRUE},
801   {V4L2_PIX_FMT_RGB565X, TRUE},
802   {V4L2_PIX_FMT_BGR24, TRUE},
803   {V4L2_PIX_FMT_RGB24, TRUE},
804   {V4L2_PIX_FMT_BGR32, TRUE},
805   {V4L2_PIX_FMT_RGB32, TRUE},
806   {V4L2_PIX_FMT_GREY, TRUE},
807   {V4L2_PIX_FMT_YVU410, TRUE},
808   {V4L2_PIX_FMT_YVU420, TRUE},
809   {V4L2_PIX_FMT_YUYV, TRUE},
810   {V4L2_PIX_FMT_UYVY, TRUE},
811   {V4L2_PIX_FMT_YUV422P, TRUE},
812   {V4L2_PIX_FMT_YUV411P, TRUE},
813   {V4L2_PIX_FMT_Y41P, TRUE},
814
815   /* two planes -- one Y, one Cr + Cb interleaved  */
816   {V4L2_PIX_FMT_NV12, TRUE},
817   {V4L2_PIX_FMT_NV21, TRUE},
818
819   /*  The following formats are not defined in the V4L2 specification */
820   {V4L2_PIX_FMT_YUV410, TRUE},
821   {V4L2_PIX_FMT_YUV420, TRUE},
822   {V4L2_PIX_FMT_YYUV, TRUE},
823   {V4L2_PIX_FMT_HI240, TRUE},
824
825   /* see http://www.siliconimaging.com/RGB%20Bayer.htm */
826 #ifdef V4L2_PIX_FMT_SBGGR8
827   {V4L2_PIX_FMT_SBGGR8, TRUE},
828 #endif
829
830   /* compressed formats */
831   {V4L2_PIX_FMT_MJPEG, TRUE},
832   {V4L2_PIX_FMT_JPEG, TRUE},
833 #ifdef V4L2_PIX_FMT_PJPG
834   {V4L2_PIX_FMT_PJPG, TRUE},
835 #endif
836   {V4L2_PIX_FMT_DV, TRUE},
837   {V4L2_PIX_FMT_MPEG, FALSE},
838
839   /*  Vendor-specific formats   */
840   {V4L2_PIX_FMT_WNVA, TRUE},
841
842 #ifdef V4L2_PIX_FMT_SN9C10X
843   {V4L2_PIX_FMT_SN9C10X, TRUE},
844 #endif
845 #ifdef V4L2_PIX_FMT_PWC1
846   {V4L2_PIX_FMT_PWC1, TRUE},
847 #endif
848 #ifdef V4L2_PIX_FMT_PWC2
849   {V4L2_PIX_FMT_PWC2, TRUE},
850 #endif
851 #ifdef V4L2_PIX_FMT_YVYU
852   {V4L2_PIX_FMT_YVYU, TRUE},
853 #endif
854 };
855
856 #define GST_V4L2_FORMAT_COUNT (G_N_ELEMENTS (gst_v4l2_formats))
857
858
859 static struct v4l2_fmtdesc *
860 gst_v4l2_object_get_format_from_fourcc (GstV4l2Object * v4l2object,
861     guint32 fourcc)
862 {
863   struct v4l2_fmtdesc *fmt;
864   GSList *walk;
865
866   if (fourcc == 0)
867     return NULL;
868
869   walk = gst_v4l2_object_get_format_list (v4l2object);
870   while (walk) {
871     fmt = (struct v4l2_fmtdesc *) walk->data;
872     if (fmt->pixelformat == fourcc)
873       return fmt;
874     /* special case for jpeg */
875     if (fmt->pixelformat == V4L2_PIX_FMT_MJPEG ||
876         fmt->pixelformat == V4L2_PIX_FMT_JPEG
877 #ifdef V4L2_PIX_FMT_PJPG
878         || fmt->pixelformat == V4L2_PIX_FMT_PJPG
879 #endif
880         ) {
881       if (fourcc == V4L2_PIX_FMT_JPEG || fourcc == V4L2_PIX_FMT_MJPEG
882 #ifdef V4L2_PIX_FMT_PJPG
883           || fourcc == V4L2_PIX_FMT_PJPG
884 #endif
885           ) {
886         return fmt;
887       }
888     }
889     walk = g_slist_next (walk);
890   }
891
892   return NULL;
893 }
894
895
896
897 /* complete made up ranking, the values themselves are meaningless */
898 /* These ranks MUST be X such that X<<15 fits on a signed int - see
899    the comment at the end of gst_v4l2_object_format_get_rank. */
900 #define YUV_BASE_RANK     1000
901 #define JPEG_BASE_RANK     500
902 #define DV_BASE_RANK       200
903 #define RGB_BASE_RANK      100
904 #define YUV_ODD_BASE_RANK   50
905 #define RGB_ODD_BASE_RANK   25
906 #define BAYER_BASE_RANK     15
907 #define S910_BASE_RANK      10
908 #define GREY_BASE_RANK       5
909 #define PWC_BASE_RANK        1
910
911 /* This flag is already used by libv4l2 although
912  * it was added to the Linux kernel in 2.6.32
913  */
914 #ifndef V4L2_FMT_FLAG_EMULATED
915 #define V4L2_FMT_FLAG_EMULATED 0x0002
916 #endif
917
918 static gint
919 gst_v4l2_object_format_get_rank (const struct v4l2_fmtdesc *fmt)
920 {
921   guint32 fourcc = fmt->pixelformat;
922   gboolean emulated = ((fmt->flags & V4L2_FMT_FLAG_EMULATED) != 0);
923   gint rank = 0;
924
925   switch (fourcc) {
926     case V4L2_PIX_FMT_MJPEG:
927 #ifdef V4L2_PIX_FMT_PJPG
928     case V4L2_PIX_FMT_PJPG:
929       rank = JPEG_BASE_RANK;
930       break;
931 #endif
932     case V4L2_PIX_FMT_JPEG:
933       rank = JPEG_BASE_RANK + 1;
934       break;
935     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
936       rank = JPEG_BASE_RANK + 2;
937       break;
938
939     case V4L2_PIX_FMT_RGB332:
940     case V4L2_PIX_FMT_RGB555:
941     case V4L2_PIX_FMT_RGB555X:
942     case V4L2_PIX_FMT_RGB565:
943     case V4L2_PIX_FMT_RGB565X:
944       rank = RGB_ODD_BASE_RANK;
945       break;
946
947     case V4L2_PIX_FMT_RGB24:
948     case V4L2_PIX_FMT_BGR24:
949       rank = RGB_BASE_RANK - 1;
950       break;
951
952     case V4L2_PIX_FMT_RGB32:
953     case V4L2_PIX_FMT_BGR32:
954       rank = RGB_BASE_RANK;
955       break;
956
957     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
958       rank = GREY_BASE_RANK;
959       break;
960
961     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
962     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
963     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
964     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
965       rank = YUV_ODD_BASE_RANK;
966       break;
967
968     case V4L2_PIX_FMT_YVU410:  /* YVU9,  9 bits per pixel */
969       rank = YUV_BASE_RANK + 3;
970       break;
971     case V4L2_PIX_FMT_YUV410:  /* YUV9,  9 bits per pixel */
972       rank = YUV_BASE_RANK + 2;
973       break;
974     case V4L2_PIX_FMT_YUV420:  /* I420, 12 bits per pixel */
975       rank = YUV_BASE_RANK + 7;
976       break;
977     case V4L2_PIX_FMT_YUYV:    /* YUY2, 16 bits per pixel */
978       rank = YUV_BASE_RANK + 10;
979       break;
980     case V4L2_PIX_FMT_YVU420:  /* YV12, 12 bits per pixel */
981       rank = YUV_BASE_RANK + 6;
982       break;
983     case V4L2_PIX_FMT_UYVY:    /* UYVY, 16 bits per pixel */
984       rank = YUV_BASE_RANK + 9;
985       break;
986     case V4L2_PIX_FMT_Y41P:    /* Y41P, 12 bits per pixel */
987       rank = YUV_BASE_RANK + 5;
988       break;
989     case V4L2_PIX_FMT_YUV411P: /* Y41B, 12 bits per pixel */
990       rank = YUV_BASE_RANK + 4;
991       break;
992     case V4L2_PIX_FMT_YUV422P: /* Y42B, 16 bits per pixel */
993       rank = YUV_BASE_RANK + 8;
994       break;
995
996     case V4L2_PIX_FMT_DV:
997       rank = DV_BASE_RANK;
998       break;
999
1000     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1001       rank = 0;
1002       break;
1003
1004 #ifdef V4L2_PIX_FMT_SBGGR8
1005     case V4L2_PIX_FMT_SBGGR8:
1006       rank = BAYER_BASE_RANK;
1007       break;
1008 #endif
1009
1010 #ifdef V4L2_PIX_FMT_SN9C10X
1011     case V4L2_PIX_FMT_SN9C10X:
1012       rank = S910_BASE_RANK;
1013       break;
1014 #endif
1015
1016 #ifdef V4L2_PIX_FMT_PWC1
1017     case V4L2_PIX_FMT_PWC1:
1018       rank = PWC_BASE_RANK;
1019       break;
1020 #endif
1021 #ifdef V4L2_PIX_FMT_PWC2
1022     case V4L2_PIX_FMT_PWC2:
1023       rank = PWC_BASE_RANK;
1024       break;
1025 #endif
1026
1027     default:
1028       rank = 0;
1029       break;
1030   }
1031
1032   /* All ranks are below 1<<15 so a shift by 15
1033    * will a) make all non-emulated formats larger
1034    * than emulated and b) will not overflow
1035    */
1036   if (!emulated)
1037     rank <<= 15;
1038
1039   return rank;
1040 }
1041
1042
1043
1044 static gint
1045 format_cmp_func (gconstpointer a, gconstpointer b)
1046 {
1047   const struct v4l2_fmtdesc *fa = a;
1048   const struct v4l2_fmtdesc *fb = b;
1049
1050   if (fa->pixelformat == fb->pixelformat)
1051     return 0;
1052
1053   return gst_v4l2_object_format_get_rank (fb) -
1054       gst_v4l2_object_format_get_rank (fa);
1055 }
1056
1057 /******************************************************
1058  * gst_v4l2_object_fill_format_list():
1059  *   create list of supported capture formats
1060  * return value: TRUE on success, FALSE on error
1061  ******************************************************/
1062 static gboolean
1063 gst_v4l2_object_fill_format_list (GstV4l2Object * v4l2object)
1064 {
1065   gint n;
1066   struct v4l2_fmtdesc *format;
1067
1068   GST_DEBUG_OBJECT (v4l2object->element, "getting src format enumerations");
1069
1070   /* format enumeration */
1071   for (n = 0;; n++) {
1072     format = g_new0 (struct v4l2_fmtdesc, 1);
1073
1074     format->index = n;
1075     format->type = v4l2object->type;
1076
1077     if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_ENUM_FMT, format) < 0) {
1078       if (errno == EINVAL) {
1079         g_free (format);
1080         break;                  /* end of enumeration */
1081       } else {
1082         goto failed;
1083       }
1084     }
1085
1086     GST_LOG_OBJECT (v4l2object->element, "index:       %u", format->index);
1087     GST_LOG_OBJECT (v4l2object->element, "type:        %d", format->type);
1088     GST_LOG_OBJECT (v4l2object->element, "flags:       %08x", format->flags);
1089     GST_LOG_OBJECT (v4l2object->element, "description: '%s'",
1090         format->description);
1091     GST_LOG_OBJECT (v4l2object->element, "pixelformat: %" GST_FOURCC_FORMAT,
1092         GST_FOURCC_ARGS (format->pixelformat));
1093
1094     /* sort formats according to our preference;  we do this, because caps
1095      * are probed in the order the formats are in the list, and the order of
1096      * formats in the final probed caps matters for things like fixation */
1097     v4l2object->formats = g_slist_insert_sorted (v4l2object->formats, format,
1098         (GCompareFunc) format_cmp_func);
1099   }
1100
1101 #ifndef GST_DISABLE_GST_DEBUG
1102   {
1103     GSList *l;
1104
1105     GST_INFO_OBJECT (v4l2object->element, "got %d format(s):", n);
1106     for (l = v4l2object->formats; l != NULL; l = l->next) {
1107       format = l->data;
1108
1109       GST_INFO_OBJECT (v4l2object->element,
1110           "  %" GST_FOURCC_FORMAT "%s", GST_FOURCC_ARGS (format->pixelformat),
1111           ((format->flags & V4L2_FMT_FLAG_EMULATED)) ? " (emulated)" : "");
1112     }
1113   }
1114 #endif
1115
1116   return TRUE;
1117
1118   /* ERRORS */
1119 failed:
1120   {
1121     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
1122         (_("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)));
1123     g_free (format);
1124     return FALSE;
1125   }
1126 }
1127
1128 /*
1129  * Get the list of supported capture formats, a list of
1130  * <code>struct v4l2_fmtdesc</code>.
1131  */
1132 GSList *
1133 gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object)
1134 {
1135   if (!v4l2object->formats)
1136     gst_v4l2_object_fill_format_list (v4l2object);
1137   return v4l2object->formats;
1138 }
1139
1140
1141 GstStructure *
1142 gst_v4l2_object_v4l2fourcc_to_structure (guint32 fourcc)
1143 {
1144   GstStructure *structure = NULL;
1145
1146   switch (fourcc) {
1147     case V4L2_PIX_FMT_MJPEG:   /* Motion-JPEG */
1148 #ifdef V4L2_PIX_FMT_PJPG
1149     case V4L2_PIX_FMT_PJPG:    /* Progressive-JPEG */
1150 #endif
1151     case V4L2_PIX_FMT_JPEG:    /* JFIF JPEG */
1152       structure = gst_structure_new ("image/jpeg", NULL);
1153       break;
1154     case V4L2_PIX_FMT_RGB332:
1155     case V4L2_PIX_FMT_RGB555:
1156     case V4L2_PIX_FMT_RGB555X:
1157     case V4L2_PIX_FMT_RGB565:
1158     case V4L2_PIX_FMT_RGB565X:
1159     case V4L2_PIX_FMT_RGB24:
1160     case V4L2_PIX_FMT_BGR24:
1161     case V4L2_PIX_FMT_RGB32:
1162     case V4L2_PIX_FMT_BGR32:{
1163       guint depth = 0, bpp = 0;
1164
1165       gint endianness = 0;
1166
1167       guint32 r_mask = 0, b_mask = 0, g_mask = 0;
1168
1169       switch (fourcc) {
1170         case V4L2_PIX_FMT_RGB332:
1171           bpp = depth = 8;
1172           endianness = G_BYTE_ORDER;    /* 'like, whatever' */
1173           r_mask = 0xe0;
1174           g_mask = 0x1c;
1175           b_mask = 0x03;
1176           break;
1177         case V4L2_PIX_FMT_RGB555:
1178         case V4L2_PIX_FMT_RGB555X:
1179           bpp = 16;
1180           depth = 15;
1181           endianness =
1182               fourcc == V4L2_PIX_FMT_RGB555X ? G_BIG_ENDIAN : G_LITTLE_ENDIAN;
1183           r_mask = 0x7c00;
1184           g_mask = 0x03e0;
1185           b_mask = 0x001f;
1186           break;
1187         case V4L2_PIX_FMT_RGB565:
1188         case V4L2_PIX_FMT_RGB565X:
1189           bpp = depth = 16;
1190           endianness =
1191               fourcc == V4L2_PIX_FMT_RGB565X ? G_BIG_ENDIAN : G_LITTLE_ENDIAN;
1192           r_mask = 0xf800;
1193           g_mask = 0x07e0;
1194           b_mask = 0x001f;
1195           break;
1196         case V4L2_PIX_FMT_RGB24:
1197           bpp = depth = 24;
1198           endianness = G_BIG_ENDIAN;
1199           r_mask = 0xff0000;
1200           g_mask = 0x00ff00;
1201           b_mask = 0x0000ff;
1202           break;
1203         case V4L2_PIX_FMT_BGR24:
1204           bpp = depth = 24;
1205           endianness = G_BIG_ENDIAN;
1206           r_mask = 0x0000ff;
1207           g_mask = 0x00ff00;
1208           b_mask = 0xff0000;
1209           break;
1210         case V4L2_PIX_FMT_RGB32:
1211           bpp = depth = 32;
1212           endianness = G_BIG_ENDIAN;
1213           r_mask = 0xff000000;
1214           g_mask = 0x00ff0000;
1215           b_mask = 0x0000ff00;
1216           break;
1217         case V4L2_PIX_FMT_BGR32:
1218           bpp = depth = 32;
1219           endianness = G_BIG_ENDIAN;
1220           r_mask = 0x000000ff;
1221           g_mask = 0x0000ff00;
1222           b_mask = 0x00ff0000;
1223           break;
1224         default:
1225           g_assert_not_reached ();
1226           break;
1227       }
1228       structure = gst_structure_new ("video/x-raw-rgb",
1229           "bpp", G_TYPE_INT, bpp,
1230           "depth", G_TYPE_INT, depth,
1231           "red_mask", G_TYPE_INT, r_mask,
1232           "green_mask", G_TYPE_INT, g_mask,
1233           "blue_mask", G_TYPE_INT, b_mask,
1234           "endianness", G_TYPE_INT, endianness, NULL);
1235       break;
1236     }
1237     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1238       structure = gst_structure_new ("video/x-raw-gray",
1239           "bpp", G_TYPE_INT, 8, NULL);
1240       break;
1241     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1242     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1243       /* FIXME: get correct fourccs here */
1244       break;
1245     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1246     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1247     case V4L2_PIX_FMT_YVU410:
1248     case V4L2_PIX_FMT_YUV410:
1249     case V4L2_PIX_FMT_YUV420:  /* I420/IYUV */
1250     case V4L2_PIX_FMT_YUYV:
1251     case V4L2_PIX_FMT_YVU420:
1252     case V4L2_PIX_FMT_UYVY:
1253     case V4L2_PIX_FMT_Y41P:
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       guint32 fcc = 0;
1260
1261       switch (fourcc) {
1262         case V4L2_PIX_FMT_NV12:
1263           fcc = GST_MAKE_FOURCC ('N', 'V', '1', '2');
1264           break;
1265         case V4L2_PIX_FMT_NV21:
1266           fcc = GST_MAKE_FOURCC ('N', 'V', '2', '1');
1267           break;
1268         case V4L2_PIX_FMT_YVU410:
1269           fcc = GST_MAKE_FOURCC ('Y', 'V', 'U', '9');
1270           break;
1271         case V4L2_PIX_FMT_YUV410:
1272           fcc = GST_MAKE_FOURCC ('Y', 'U', 'V', '9');
1273           break;
1274         case V4L2_PIX_FMT_YUV420:
1275           fcc = GST_MAKE_FOURCC ('I', '4', '2', '0');
1276           break;
1277         case V4L2_PIX_FMT_YUYV:
1278           fcc = GST_MAKE_FOURCC ('Y', 'U', 'Y', '2');
1279           break;
1280         case V4L2_PIX_FMT_YVU420:
1281           fcc = GST_MAKE_FOURCC ('Y', 'V', '1', '2');
1282           break;
1283         case V4L2_PIX_FMT_UYVY:
1284           fcc = GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y');
1285           break;
1286         case V4L2_PIX_FMT_Y41P:
1287           fcc = GST_MAKE_FOURCC ('Y', '4', '1', 'P');
1288           break;
1289         case V4L2_PIX_FMT_YUV411P:
1290           fcc = GST_MAKE_FOURCC ('Y', '4', '1', 'B');
1291           break;
1292         case V4L2_PIX_FMT_YUV422P:
1293           fcc = GST_MAKE_FOURCC ('Y', '4', '2', 'B');
1294           break;
1295 #ifdef V4L2_PIX_FMT_YVYU
1296         case V4L2_PIX_FMT_YVYU:
1297           fcc = GST_MAKE_FOURCC ('Y', 'V', 'Y', 'U');
1298           break;
1299 #endif
1300         default:
1301           g_assert_not_reached ();
1302           break;
1303       }
1304       structure = gst_structure_new ("video/x-raw-yuv",
1305           "format", GST_TYPE_FOURCC, fcc, NULL);
1306       break;
1307     }
1308     case V4L2_PIX_FMT_DV:
1309       structure =
1310           gst_structure_new ("video/x-dv", "systemstream", G_TYPE_BOOLEAN, TRUE,
1311           NULL);
1312       break;
1313     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1314       structure = gst_structure_new ("video/mpegts", NULL);
1315       break;
1316     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1317       break;
1318 #ifdef V4L2_PIX_FMT_SBGGR8
1319     case V4L2_PIX_FMT_SBGGR8:
1320       structure = gst_structure_new ("video/x-raw-bayer", NULL);
1321       break;
1322 #endif
1323 #ifdef V4L2_PIX_FMT_SN9C10X
1324     case V4L2_PIX_FMT_SN9C10X:
1325       structure = gst_structure_new ("video/x-sonix", NULL);
1326       break;
1327 #endif
1328 #ifdef V4L2_PIX_FMT_PWC1
1329     case V4L2_PIX_FMT_PWC1:
1330       structure = gst_structure_new ("video/x-pwc1", NULL);
1331       break;
1332 #endif
1333 #ifdef V4L2_PIX_FMT_PWC2
1334     case V4L2_PIX_FMT_PWC2:
1335       structure = gst_structure_new ("video/x-pwc2", NULL);
1336       break;
1337 #endif
1338     default:
1339       GST_DEBUG ("Unknown fourcc 0x%08x %" GST_FOURCC_FORMAT,
1340           fourcc, GST_FOURCC_ARGS (fourcc));
1341       break;
1342   }
1343
1344   return structure;
1345 }
1346
1347
1348
1349 GstCaps *
1350 gst_v4l2_object_get_all_caps (void)
1351 {
1352   static GstCaps *caps = NULL;
1353
1354   if (caps == NULL) {
1355     GstStructure *structure;
1356
1357     guint i;
1358
1359     caps = gst_caps_new_empty ();
1360     for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1361       structure =
1362           gst_v4l2_object_v4l2fourcc_to_structure (gst_v4l2_formats[i].format);
1363       if (structure) {
1364         if (gst_v4l2_formats[i].dimensions) {
1365           gst_structure_set (structure,
1366               "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1367               "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1368               "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1, NULL);
1369         }
1370         gst_caps_append_structure (caps, structure);
1371       }
1372     }
1373   }
1374
1375   return gst_caps_ref (caps);
1376 }
1377
1378
1379 /* collect data for the given caps
1380  * @caps: given input caps
1381  * @format: location for the v4l format
1382  * @w/@h: location for width and height
1383  * @fps_n/@fps_d: location for framerate
1384  * @size: location for expected size of the frame or 0 if unknown
1385  */
1386 gboolean
1387 gst_v4l2_object_get_caps_info (GstV4l2Object * v4l2object, GstCaps * caps,
1388     struct v4l2_fmtdesc ** format, gint * w, gint * h,
1389     gboolean * interlaced, guint * fps_n, guint * fps_d, guint * size)
1390 {
1391   GstStructure *structure;
1392   const GValue *framerate;
1393   guint32 fourcc;
1394   const gchar *mimetype;
1395   guint outsize;
1396
1397   /* default unknown values */
1398   fourcc = 0;
1399   outsize = 0;
1400
1401   structure = gst_caps_get_structure (caps, 0);
1402
1403   mimetype = gst_structure_get_name (structure);
1404
1405   if (strcmp (mimetype, "video/mpegts") == 0) {
1406     fourcc = V4L2_PIX_FMT_MPEG;
1407     *fps_n = 0;
1408     *fps_d = 1;
1409     goto done;
1410   }
1411
1412   if (!gst_structure_get_int (structure, "width", w))
1413     return FALSE;
1414
1415   if (!gst_structure_get_int (structure, "height", h))
1416     return FALSE;
1417
1418   if (!gst_structure_get_boolean (structure, "interlaced", interlaced))
1419     *interlaced = FALSE;
1420
1421   framerate = gst_structure_get_value (structure, "framerate");
1422   if (!framerate)
1423     return FALSE;
1424
1425   *fps_n = gst_value_get_fraction_numerator (framerate);
1426   *fps_d = gst_value_get_fraction_denominator (framerate);
1427
1428   if (!strcmp (mimetype, "video/x-raw-yuv")) {
1429     gst_structure_get_fourcc (structure, "format", &fourcc);
1430
1431     switch (fourcc) {
1432       case GST_MAKE_FOURCC ('I', '4', '2', '0'):
1433       case GST_MAKE_FOURCC ('I', 'Y', 'U', 'V'):
1434         fourcc = V4L2_PIX_FMT_YUV420;
1435         outsize = GST_ROUND_UP_4 (*w) * GST_ROUND_UP_2 (*h);
1436         outsize += 2 * ((GST_ROUND_UP_8 (*w) / 2) * (GST_ROUND_UP_2 (*h) / 2));
1437         break;
1438       case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
1439         fourcc = V4L2_PIX_FMT_YUYV;
1440         outsize = (GST_ROUND_UP_2 (*w) * 2) * *h;
1441         break;
1442       case GST_MAKE_FOURCC ('Y', '4', '1', 'P'):
1443         fourcc = V4L2_PIX_FMT_Y41P;
1444         outsize = (GST_ROUND_UP_2 (*w) * 2) * *h;
1445         break;
1446       case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
1447         fourcc = V4L2_PIX_FMT_UYVY;
1448         outsize = (GST_ROUND_UP_2 (*w) * 2) * *h;
1449         break;
1450       case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
1451         fourcc = V4L2_PIX_FMT_YVU420;
1452         outsize = GST_ROUND_UP_4 (*w) * GST_ROUND_UP_2 (*h);
1453         outsize += 2 * ((GST_ROUND_UP_8 (*w) / 2) * (GST_ROUND_UP_2 (*h) / 2));
1454         break;
1455       case GST_MAKE_FOURCC ('Y', '4', '1', 'B'):
1456         fourcc = V4L2_PIX_FMT_YUV411P;
1457         outsize = GST_ROUND_UP_4 (*w) * *h;
1458         outsize += 2 * ((GST_ROUND_UP_8 (*w) / 4) * *h);
1459         break;
1460       case GST_MAKE_FOURCC ('Y', '4', '2', 'B'):
1461         fourcc = V4L2_PIX_FMT_YUV422P;
1462         outsize = GST_ROUND_UP_4 (*w) * *h;
1463         outsize += 2 * ((GST_ROUND_UP_8 (*w) / 2) * *h);
1464         break;
1465       case GST_MAKE_FOURCC ('N', 'V', '1', '2'):
1466         fourcc = V4L2_PIX_FMT_NV12;
1467         outsize = GST_ROUND_UP_4 (*w) * GST_ROUND_UP_2 (*h);
1468         outsize += (GST_ROUND_UP_4 (*w) * *h) / 2;
1469         break;
1470       case GST_MAKE_FOURCC ('N', 'V', '2', '1'):
1471         fourcc = V4L2_PIX_FMT_NV21;
1472         outsize = GST_ROUND_UP_4 (*w) * GST_ROUND_UP_2 (*h);
1473         outsize += (GST_ROUND_UP_4 (*w) * *h) / 2;
1474         break;
1475 #ifdef V4L2_PIX_FMT_YVYU
1476       case GST_MAKE_FOURCC ('Y', 'V', 'Y', 'U'):
1477         fourcc = V4L2_PIX_FMT_YVYU;
1478         outsize = (GST_ROUND_UP_2 (*w) * 2) * *h;
1479         break;
1480 #endif
1481     }
1482   } else if (!strcmp (mimetype, "video/x-raw-rgb")) {
1483     gint depth, endianness, r_mask;
1484
1485     gst_structure_get_int (structure, "depth", &depth);
1486     gst_structure_get_int (structure, "endianness", &endianness);
1487     gst_structure_get_int (structure, "red_mask", &r_mask);
1488
1489     switch (depth) {
1490       case 8:
1491         fourcc = V4L2_PIX_FMT_RGB332;
1492         break;
1493       case 15:
1494         fourcc = (endianness == G_LITTLE_ENDIAN) ?
1495             V4L2_PIX_FMT_RGB555 : V4L2_PIX_FMT_RGB555X;
1496         break;
1497       case 16:
1498         fourcc = (endianness == G_LITTLE_ENDIAN) ?
1499             V4L2_PIX_FMT_RGB565 : V4L2_PIX_FMT_RGB565X;
1500         break;
1501       case 24:
1502         fourcc = (r_mask == 0xFF) ? V4L2_PIX_FMT_BGR24 : V4L2_PIX_FMT_RGB24;
1503         break;
1504       case 32:
1505         fourcc = (r_mask == 0xFF) ? V4L2_PIX_FMT_BGR32 : V4L2_PIX_FMT_RGB32;
1506         break;
1507     }
1508   } else if (strcmp (mimetype, "video/x-dv") == 0) {
1509     fourcc = V4L2_PIX_FMT_DV;
1510   } else if (strcmp (mimetype, "image/jpeg") == 0) {
1511     fourcc = V4L2_PIX_FMT_JPEG;
1512 #ifdef V4L2_PIX_FMT_SBGGR8
1513   } else if (strcmp (mimetype, "video/x-raw-bayer") == 0) {
1514     fourcc = V4L2_PIX_FMT_SBGGR8;
1515 #endif
1516 #ifdef V4L2_PIX_FMT_SN9C10X
1517   } else if (strcmp (mimetype, "video/x-sonix") == 0) {
1518     fourcc = V4L2_PIX_FMT_SN9C10X;
1519 #endif
1520 #ifdef V4L2_PIX_FMT_PWC1
1521   } else if (strcmp (mimetype, "video/x-pwc1") == 0) {
1522     fourcc = V4L2_PIX_FMT_PWC1;
1523 #endif
1524 #ifdef V4L2_PIX_FMT_PWC2
1525   } else if (strcmp (mimetype, "video/x-pwc2") == 0) {
1526     fourcc = V4L2_PIX_FMT_PWC2;
1527 #endif
1528   } else if (strcmp (mimetype, "video/x-raw-gray") == 0) {
1529     fourcc = V4L2_PIX_FMT_GREY;
1530   }
1531
1532   if (fourcc == 0)
1533     return FALSE;
1534
1535 done:
1536   *format = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1537   *size = outsize;
1538
1539   return TRUE;
1540 }
1541
1542
1543 static gboolean
1544 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1545     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced);
1546
1547
1548 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1549 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1550 static GstStructure *
1551 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1552     guint32 pixelformat,
1553     guint32 width, guint32 height, const GstStructure * template)
1554 {
1555   gint fd = v4l2object->video_fd;
1556   struct v4l2_frmivalenum ival;
1557   guint32 num, denom;
1558   GstStructure *s;
1559   GValue rates = { 0, };
1560   gboolean interlaced;
1561   gint int_width = width;
1562   gint int_height = height;
1563
1564   /* interlaced detection using VIDIOC_TRY/S_FMT */
1565   if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat,
1566           &int_width, &int_height, &interlaced))
1567     return NULL;
1568
1569   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1570   ival.index = 0;
1571   ival.pixel_format = pixelformat;
1572   ival.width = width;
1573   ival.height = height;
1574
1575   GST_LOG_OBJECT (v4l2object->element,
1576       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1577       GST_FOURCC_ARGS (pixelformat));
1578
1579   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1580    * fraction to get framerate */
1581   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1582     goto enum_frameintervals_failed;
1583
1584   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1585     GValue rate = { 0, };
1586
1587     g_value_init (&rates, GST_TYPE_LIST);
1588     g_value_init (&rate, GST_TYPE_FRACTION);
1589
1590     do {
1591       num = ival.discrete.numerator;
1592       denom = ival.discrete.denominator;
1593
1594       if (num > G_MAXINT || denom > G_MAXINT) {
1595         /* let us hope we don't get here... */
1596         num >>= 1;
1597         denom >>= 1;
1598       }
1599
1600       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1601           denom, num);
1602
1603       /* swap to get the framerate */
1604       gst_value_set_fraction (&rate, denom, num);
1605       gst_value_list_append_value (&rates, &rate);
1606
1607       ival.index++;
1608     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1609   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1610     GValue min = { 0, };
1611     GValue step = { 0, };
1612     GValue max = { 0, };
1613     gboolean added = FALSE;
1614     guint32 minnum, mindenom;
1615     guint32 maxnum, maxdenom;
1616
1617     g_value_init (&rates, GST_TYPE_LIST);
1618
1619     g_value_init (&min, GST_TYPE_FRACTION);
1620     g_value_init (&step, GST_TYPE_FRACTION);
1621     g_value_init (&max, GST_TYPE_FRACTION);
1622
1623     /* get the min */
1624     minnum = ival.stepwise.min.numerator;
1625     mindenom = ival.stepwise.min.denominator;
1626     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1627       minnum >>= 1;
1628       mindenom >>= 1;
1629     }
1630     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1631         minnum, mindenom);
1632     gst_value_set_fraction (&min, minnum, mindenom);
1633
1634     /* get the max */
1635     maxnum = ival.stepwise.max.numerator;
1636     maxdenom = ival.stepwise.max.denominator;
1637     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1638       maxnum >>= 1;
1639       maxdenom >>= 1;
1640     }
1641
1642     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1643         maxnum, maxdenom);
1644     gst_value_set_fraction (&max, maxnum, maxdenom);
1645
1646     /* get the step */
1647     num = ival.stepwise.step.numerator;
1648     denom = ival.stepwise.step.denominator;
1649     if (num > G_MAXINT || denom > G_MAXINT) {
1650       num >>= 1;
1651       denom >>= 1;
1652     }
1653
1654     if (num == 0 || denom == 0) {
1655       /* in this case we have a wrong fraction or no step, set the step to max
1656        * so that we only add the min value in the loop below */
1657       num = maxnum;
1658       denom = maxdenom;
1659     }
1660
1661     /* since we only have gst_value_fraction_subtract and not add, negate the
1662      * numerator */
1663     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1664         num, denom);
1665     gst_value_set_fraction (&step, -num, denom);
1666
1667     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
1668       GValue rate = { 0, };
1669
1670       num = gst_value_get_fraction_numerator (&min);
1671       denom = gst_value_get_fraction_denominator (&min);
1672       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1673           denom, num);
1674
1675       /* invert to get the framerate */
1676       g_value_init (&rate, GST_TYPE_FRACTION);
1677       gst_value_set_fraction (&rate, denom, num);
1678       gst_value_list_append_value (&rates, &rate);
1679       added = TRUE;
1680
1681       /* we're actually adding because step was negated above. This is because
1682        * there is no _add function... */
1683       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1684         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1685         break;
1686       }
1687     }
1688     if (!added) {
1689       /* no range was added, leave the default range from the template */
1690       GST_WARNING_OBJECT (v4l2object->element,
1691           "no range added, leaving default");
1692       g_value_unset (&rates);
1693     }
1694   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1695     guint32 maxnum, maxdenom;
1696
1697     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1698
1699     num = ival.stepwise.min.numerator;
1700     denom = ival.stepwise.min.denominator;
1701     if (num > G_MAXINT || denom > G_MAXINT) {
1702       num >>= 1;
1703       denom >>= 1;
1704     }
1705
1706     maxnum = ival.stepwise.max.numerator;
1707     maxdenom = ival.stepwise.max.denominator;
1708     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1709       maxnum >>= 1;
1710       maxdenom >>= 1;
1711     }
1712
1713     GST_LOG_OBJECT (v4l2object->element,
1714         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1715         num);
1716
1717     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1718   } else {
1719     goto unknown_type;
1720   }
1721
1722 return_data:
1723   s = gst_structure_copy (template);
1724   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1725       "height", G_TYPE_INT, (gint) height,
1726       "interlaced", G_TYPE_BOOLEAN, interlaced,
1727       "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, NULL);
1728
1729   if (G_IS_VALUE (&rates)) {
1730     /* only change the framerate on the template when we have a valid probed new
1731      * value */
1732     gst_structure_set_value (s, "framerate", &rates);
1733     g_value_unset (&rates);
1734   } else {
1735     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1736         NULL);
1737   }
1738   return s;
1739
1740   /* ERRORS */
1741 enum_frameintervals_failed:
1742   {
1743     GST_DEBUG_OBJECT (v4l2object->element,
1744         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1745         GST_FOURCC_ARGS (pixelformat), width, height);
1746     goto return_data;
1747   }
1748 unknown_type:
1749   {
1750     /* I don't see how this is actually an error, we ignore the format then */
1751     GST_WARNING_OBJECT (v4l2object->element,
1752         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1753         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1754     return NULL;
1755   }
1756 }
1757 #endif /* defined VIDIOC_ENUM_FRAMEINTERVALS */
1758
1759 #ifdef VIDIOC_ENUM_FRAMESIZES
1760 static gint
1761 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1762 {
1763   int w1, h1, w2, h2;
1764
1765   gst_structure_get_int (s1, "width", &w1);
1766   gst_structure_get_int (s1, "height", &h1);
1767   gst_structure_get_int (s2, "width", &w2);
1768   gst_structure_get_int (s2, "height", &h2);
1769
1770   /* I think it's safe to assume that this won't overflow for a while */
1771   return ((w2 * h2) - (w1 * h1));
1772 }
1773 #endif
1774
1775 GstCaps *
1776 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
1777     guint32 pixelformat, const GstStructure * template)
1778 {
1779   GstCaps *ret = gst_caps_new_empty ();
1780   GstStructure *tmp;
1781
1782 #ifdef VIDIOC_ENUM_FRAMESIZES
1783   gint fd = v4l2object->video_fd;
1784   struct v4l2_frmsizeenum size;
1785   GList *results = NULL;
1786   guint32 w, h;
1787
1788   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G'))
1789     return gst_caps_new_simple ("video/mpegts", NULL);
1790
1791   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
1792   size.index = 0;
1793   size.pixel_format = pixelformat;
1794
1795   GST_DEBUG_OBJECT (v4l2object->element, "Enumerating frame sizes");
1796
1797   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
1798     goto enum_framesizes_failed;
1799
1800   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
1801     do {
1802       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
1803           size.discrete.width, size.discrete.height);
1804
1805       w = MIN (size.discrete.width, G_MAXINT);
1806       h = MIN (size.discrete.height, G_MAXINT);
1807
1808       if (w && h) {
1809         tmp =
1810             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1811             pixelformat, w, h, template);
1812
1813         if (tmp)
1814           results = g_list_prepend (results, tmp);
1815       }
1816
1817       size.index++;
1818     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
1819     GST_DEBUG_OBJECT (v4l2object->element,
1820         "done iterating discrete frame sizes");
1821   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
1822     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
1823     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1824         size.stepwise.min_width);
1825     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1826         size.stepwise.min_height);
1827     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1828         size.stepwise.max_width);
1829     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1830         size.stepwise.max_height);
1831     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
1832         size.stepwise.step_width);
1833     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
1834         size.stepwise.step_height);
1835
1836     for (w = size.stepwise.min_width, h = size.stepwise.min_height;
1837         w <= size.stepwise.max_width && h <= size.stepwise.max_height;
1838         w += size.stepwise.step_width, h += size.stepwise.step_height) {
1839       if (w == 0 || h == 0)
1840         continue;
1841
1842       tmp =
1843           gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1844           pixelformat, w, h, template);
1845
1846       if (tmp)
1847         results = g_list_prepend (results, tmp);
1848     }
1849     GST_DEBUG_OBJECT (v4l2object->element,
1850         "done iterating stepwise frame sizes");
1851   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
1852     guint32 maxw, maxh;
1853
1854     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
1855     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1856         size.stepwise.min_width);
1857     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1858         size.stepwise.min_height);
1859     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1860         size.stepwise.max_width);
1861     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1862         size.stepwise.max_height);
1863
1864     w = MAX (size.stepwise.min_width, 1);
1865     h = MAX (size.stepwise.min_height, 1);
1866     maxw = MIN (size.stepwise.max_width, G_MAXINT);
1867     maxh = MIN (size.stepwise.max_height, G_MAXINT);
1868
1869     tmp =
1870         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
1871         w, h, template);
1872     if (tmp) {
1873       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
1874           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
1875           NULL);
1876
1877       /* no point using the results list here, since there's only one struct */
1878       gst_caps_append_structure (ret, tmp);
1879     }
1880   } else {
1881     goto unknown_type;
1882   }
1883
1884   /* we use an intermediary list to store and then sort the results of the
1885    * probing because we can't make any assumptions about the order in which
1886    * the driver will give us the sizes, but we want the final caps to contain
1887    * the results starting with the highest resolution and having the lowest
1888    * resolution last, since order in caps matters for things like fixation. */
1889   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
1890   while (results != NULL) {
1891     gst_caps_append_structure (ret, GST_STRUCTURE (results->data));
1892     results = g_list_delete_link (results, results);
1893   }
1894
1895   if (gst_caps_is_empty (ret))
1896     goto enum_framesizes_no_results;
1897
1898   return ret;
1899
1900   /* ERRORS */
1901 enum_framesizes_failed:
1902   {
1903     /* I don't see how this is actually an error */
1904     GST_DEBUG_OBJECT (v4l2object->element,
1905         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
1906         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
1907     goto default_frame_sizes;
1908   }
1909 enum_framesizes_no_results:
1910   {
1911     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
1912      * question doesn't actually support it yet */
1913     GST_DEBUG_OBJECT (v4l2object->element,
1914         "No results for pixelformat %" GST_FOURCC_FORMAT
1915         " enumerating frame sizes, trying fallback",
1916         GST_FOURCC_ARGS (pixelformat));
1917     goto default_frame_sizes;
1918   }
1919 unknown_type:
1920   {
1921     GST_WARNING_OBJECT (v4l2object->element,
1922         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
1923         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
1924     goto default_frame_sizes;
1925   }
1926 default_frame_sizes:
1927 #endif /* defined VIDIOC_ENUM_FRAMESIZES */
1928   {
1929     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
1930     gboolean interlaced;
1931
1932     /* This code is for Linux < 2.6.19 */
1933     min_w = min_h = 1;
1934     max_w = max_h = GST_V4L2_MAX_SIZE;
1935     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
1936             &min_h, &interlaced)) {
1937       GST_WARNING_OBJECT (v4l2object->element,
1938           "Could not probe minimum capture size for pixelformat %"
1939           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
1940     }
1941     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
1942             &max_h, &interlaced)) {
1943       GST_WARNING_OBJECT (v4l2object->element,
1944           "Could not probe maximum capture size for pixelformat %"
1945           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
1946     }
1947
1948     /* Since we can't get framerate directly, try to use the current norm */
1949     if (v4l2object->tv_norm && v4l2object->norms) {
1950       GList *norms;
1951       GstTunerNorm *norm = NULL;
1952       GstTunerNorm *current =
1953           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
1954
1955       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
1956         norm = (GstTunerNorm *) norms->data;
1957         if (!strcmp (norm->label, current->label))
1958           break;
1959       }
1960       /* If it's possible, set framerate to that (discrete) value */
1961       if (norm) {
1962         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
1963         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
1964       }
1965     }
1966
1967     tmp = gst_structure_copy (template);
1968     if (fix_num) {
1969       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
1970           fix_denom, NULL);
1971     } else {
1972       /* if norm can't be used, copy the template framerate */
1973       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
1974           100, 1, NULL);
1975     }
1976
1977     if (min_w == max_w)
1978       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
1979     else
1980       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
1981
1982     if (min_h == max_h)
1983       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
1984     else
1985       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
1986
1987     gst_structure_set (tmp, "interlaced", G_TYPE_BOOLEAN, interlaced, NULL);
1988     gst_structure_set (tmp, "pixel-aspect-ratio",
1989         GST_TYPE_FRACTION, 1, 1, NULL);
1990
1991     gst_caps_append_structure (ret, tmp);
1992
1993     return ret;
1994   }
1995 }
1996
1997 static gboolean
1998 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1999     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced)
2000 {
2001   struct v4l2_format fmt, prevfmt;
2002   int fd;
2003   int r;
2004   int prevfmt_valid;
2005
2006   g_return_val_if_fail (width != NULL, FALSE);
2007   g_return_val_if_fail (height != NULL, FALSE);
2008
2009   GST_LOG_OBJECT (v4l2object->element,
2010       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2011       *width, *height, GST_FOURCC_ARGS (pixelformat));
2012
2013   fd = v4l2object->video_fd;
2014
2015   /* Some drivers are buggy and will modify the currently set format
2016      when processing VIDIOC_TRY_FMT, so we remember what is set at the
2017      minute, and will reset it when done. */
2018   prevfmt_valid = (v4l2_ioctl (fd, VIDIOC_G_FMT, &prevfmt) >= 0);
2019
2020   /* get size delimiters */
2021   memset (&fmt, 0, sizeof (fmt));
2022   fmt.type = v4l2object->type;
2023   fmt.fmt.pix.width = *width;
2024   fmt.fmt.pix.height = *height;
2025   fmt.fmt.pix.pixelformat = pixelformat;
2026   fmt.fmt.pix.field = V4L2_FIELD_NONE;
2027
2028   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2029   if (r < 0 && errno == EINVAL) {
2030     /* try again with interlaced video */
2031     fmt.fmt.pix.width = *width;
2032     fmt.fmt.pix.height = *height;
2033     fmt.fmt.pix.pixelformat = pixelformat;
2034     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2035     r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2036   }
2037
2038   if (r < 0) {
2039     /* The driver might not implement TRY_FMT, in which case we will try
2040        S_FMT to probe */
2041     if (errno != ENOTTY)
2042       goto error;
2043
2044     /* Only try S_FMT if we're not actively capturing yet, which we shouldn't
2045        be, because we're still probing */
2046     if (GST_V4L2_IS_ACTIVE (v4l2object))
2047       goto error;
2048
2049     GST_LOG_OBJECT (v4l2object->element,
2050         "Failed to probe size limit with VIDIOC_TRY_FMT, trying VIDIOC_S_FMT");
2051
2052     fmt.fmt.pix.width = *width;
2053     fmt.fmt.pix.height = *height;
2054
2055     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2056     if (r < 0 && errno == EINVAL) {
2057       /* try again with progressive video */
2058       fmt.fmt.pix.width = *width;
2059       fmt.fmt.pix.height = *height;
2060       fmt.fmt.pix.pixelformat = pixelformat;
2061       fmt.fmt.pix.field = V4L2_FIELD_NONE;
2062       r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2063     }
2064
2065     if (r < 0)
2066       goto error;
2067   }
2068
2069   GST_LOG_OBJECT (v4l2object->element,
2070       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2071
2072   *width = fmt.fmt.pix.width;
2073   *height = fmt.fmt.pix.height;
2074
2075   switch (fmt.fmt.pix.field) {
2076     case V4L2_FIELD_ANY:
2077     case V4L2_FIELD_NONE:
2078       *interlaced = FALSE;
2079       break;
2080     case V4L2_FIELD_INTERLACED:
2081     case V4L2_FIELD_INTERLACED_TB:
2082     case V4L2_FIELD_INTERLACED_BT:
2083       *interlaced = TRUE;
2084       break;
2085     default:
2086       GST_WARNING_OBJECT (v4l2object->element,
2087           "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u",
2088           GST_FOURCC_ARGS (pixelformat), *width, *height);
2089       goto error;
2090   }
2091
2092   if (prevfmt_valid)
2093     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2094   return TRUE;
2095
2096 error:
2097   if (prevfmt_valid)
2098     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2099   return FALSE;
2100 }
2101
2102
2103 gboolean
2104 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, guint32 pixelformat,
2105     guint32 width, guint32 height, gboolean interlaced)
2106 {
2107   gint fd = v4l2object->video_fd;
2108   struct v4l2_format format;
2109   enum v4l2_field field;
2110
2111   if (interlaced) {
2112     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2113     /* ideally we would differentiate between types of interlaced video
2114      * but there is not sufficient information in the caps..
2115      */
2116     field = V4L2_FIELD_INTERLACED;
2117   } else {
2118     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2119     field = V4L2_FIELD_NONE;
2120   }
2121
2122   GST_DEBUG_OBJECT (v4l2object->element, "Setting format to %dx%d, format "
2123       "%" GST_FOURCC_FORMAT, width, height, GST_FOURCC_ARGS (pixelformat));
2124
2125   GST_V4L2_CHECK_OPEN (v4l2object);
2126   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2127
2128   /* Only unconditionally accept mpegts for sources */
2129   if ((v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
2130       (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')))
2131     return TRUE;
2132
2133   memset (&format, 0x00, sizeof (struct v4l2_format));
2134   format.type = v4l2object->type;
2135
2136   if (v4l2_ioctl (fd, VIDIOC_G_FMT, &format) < 0)
2137     goto get_fmt_failed;
2138
2139   if (format.type == v4l2object->type &&
2140       format.fmt.pix.width == width &&
2141       format.fmt.pix.height == height &&
2142       format.fmt.pix.pixelformat == pixelformat &&
2143       format.fmt.pix.field == field) {
2144     /* Nothing to do. We want to succeed immediately
2145      * here because setting the same format back
2146      * can still fail due to EBUSY. By short-circuiting
2147      * here, we allow pausing and re-playing pipelines
2148      * with changed caps, as long as the changed caps
2149      * do not change the webcam's format. Otherwise,
2150      * any caps change would require us to go to NULL
2151      * state to close the device and set format.
2152      */
2153     return TRUE;
2154   }
2155
2156   format.type = v4l2object->type;
2157   format.fmt.pix.width = width;
2158   format.fmt.pix.height = height;
2159   format.fmt.pix.pixelformat = pixelformat;
2160   format.fmt.pix.field = field;
2161
2162   if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0) {
2163     goto set_fmt_failed;
2164   }
2165
2166   if (format.fmt.pix.width != width || format.fmt.pix.height != height)
2167     goto invalid_dimensions;
2168
2169   if (format.fmt.pix.pixelformat != pixelformat)
2170     goto invalid_pixelformat;
2171
2172   return TRUE;
2173
2174   /* ERRORS */
2175 get_fmt_failed:
2176   {
2177     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2178         (_("Device '%s' does not support video capture"),
2179             v4l2object->videodev),
2180         ("Call to G_FMT failed: (%s)", g_strerror (errno)));
2181     return FALSE;
2182   }
2183 set_fmt_failed:
2184   {
2185     if (errno == EBUSY) {
2186       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, BUSY,
2187           (_("Device '%s' is busy"), v4l2object->videodev),
2188           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2189               GST_FOURCC_ARGS (pixelformat), width, height,
2190               g_strerror (errno)));
2191     } else {
2192       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2193           (_("Device '%s' cannot capture at %dx%d"),
2194               v4l2object->videodev, width, height),
2195           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2196               GST_FOURCC_ARGS (pixelformat), width, height,
2197               g_strerror (errno)));
2198     }
2199     return FALSE;
2200   }
2201 invalid_dimensions:
2202   {
2203     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2204         (_("Device '%s' cannot capture at %dx%d"),
2205             v4l2object->videodev, width, height),
2206         ("Tried to capture at %dx%d, but device returned size %dx%d",
2207             width, height, format.fmt.pix.width, format.fmt.pix.height));
2208     return FALSE;
2209   }
2210 invalid_pixelformat:
2211   {
2212     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2213         (_("Device '%s' cannot capture in the specified format"),
2214             v4l2object->videodev),
2215         ("Tried to capture in %" GST_FOURCC_FORMAT
2216             ", but device returned format" " %" GST_FOURCC_FORMAT,
2217             GST_FOURCC_ARGS (pixelformat),
2218             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2219     return FALSE;
2220   }
2221 }
2222
2223 gboolean
2224 gst_v4l2_object_start_streaming (GstV4l2Object * v4l2object)
2225 {
2226   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_STREAMON,
2227           &(v4l2object->type)) < 0) {
2228     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, OPEN_READ,
2229         (_("Error starting streaming on device '%s'."), v4l2object->videodev),
2230         GST_ERROR_SYSTEM);
2231     return FALSE;
2232   }
2233   return TRUE;
2234 }
2235
2236 gboolean
2237 gst_v4l2_object_stop_streaming (GstV4l2Object * v4l2object)
2238 {
2239   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_STREAMOFF,
2240           &(v4l2object->type)) < 0) {
2241     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, OPEN_READ,
2242         (_("Error stopping streaming on device '%s'."), v4l2object->videodev),
2243         GST_ERROR_SYSTEM);
2244     return FALSE;
2245   }
2246   return TRUE;
2247 }