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