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