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