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