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