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