v4l2: clear cached caps on close
[platform/upstream/gstreamer.git] / sys / v4l2 / gstv4l2object.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@indt.org.br>
5  *
6  * gstv4l2object.c: base class for V4L2 elements
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Library General Public License as published
10  * by the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version. This library is distributed in the hope
12  * that it will be useful, but WITHOUT ANY WARRANTY; without even the
13  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14  * PURPOSE.  See the GNU Library General Public License for more details.
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
18  * USA.
19  */
20
21 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
22  * with newer GLib versions (>= 2.31.0) */
23 #define GLIB_DISABLE_DEPRECATION_WARNINGS
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <string.h>
34
35 #ifdef HAVE_GUDEV
36 #include <gudev/gudev.h>
37 #endif
38
39 #include "v4l2_calls.h"
40 #include "gstv4l2tuner.h"
41 #ifdef HAVE_XVIDEO
42 #include "gstv4l2videooverlay.h"
43 #endif
44 #include "gstv4l2colorbalance.h"
45
46 #include "gst/gst-i18n-plugin.h"
47
48 #include <gst/video/video.h>
49
50 /* videodev2.h is not versioned and we can't easily check for the presence
51  * of enum values at compile time, but the V4L2_CAP_VIDEO_OUTPUT_OVERLAY define
52  * was added in the same commit as V4L2_FIELD_INTERLACED_{TB,BT} (b2787845) */
53 #ifndef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
54 #define V4L2_FIELD_INTERLACED_TB 8
55 #define V4L2_FIELD_INTERLACED_BT 9
56 #endif
57
58 GST_DEBUG_CATEGORY_EXTERN (v4l2_debug);
59 GST_DEBUG_CATEGORY_EXTERN (GST_CAT_PERFORMANCE);
60 #define GST_CAT_DEFAULT v4l2_debug
61
62 #define DEFAULT_PROP_DEVICE_NAME        NULL
63 #define DEFAULT_PROP_DEVICE_FD          -1
64 #define DEFAULT_PROP_FLAGS              0
65 #define DEFAULT_PROP_TV_NORM            0
66 #define DEFAULT_PROP_CHANNEL            NULL
67 #define DEFAULT_PROP_FREQUENCY          0
68 #define DEFAULT_PROP_IO_MODE            GST_V4L2_IO_AUTO
69
70 enum
71 {
72   PROP_0,
73   V4L2_STD_OBJECT_PROPS,
74 };
75
76 static GSList *gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object);
77
78 #if 0
79 G_LOCK_DEFINE_STATIC (probe_lock);
80
81 const GList *
82 gst_v4l2_probe_get_properties (GstPropertyProbe * probe)
83 {
84   GObjectClass *klass = G_OBJECT_GET_CLASS (probe);
85   static GList *list = NULL;
86
87   G_LOCK (probe_lock);
88
89   if (!list) {
90     list = g_list_append (NULL, g_object_class_find_property (klass, "device"));
91   }
92
93   G_UNLOCK (probe_lock);
94
95   return list;
96 }
97
98 static gboolean init = FALSE;
99 static GList *devices = NULL;
100
101 #ifdef HAVE_GUDEV
102 static gboolean
103 gst_v4l2_class_probe_devices_with_udev (GstElementClass * klass, gboolean check,
104     GList ** klass_devices)
105 {
106   GUdevClient *client = NULL;
107   GList *item;
108
109   if (!check) {
110     while (devices) {
111       gchar *device = devices->data;
112       devices = g_list_remove (devices, device);
113       g_free (device);
114     }
115
116     GST_INFO ("Enumerating video4linux devices from udev");
117     client = g_udev_client_new (NULL);
118     if (!client) {
119       GST_WARNING ("Failed to initialize gudev client");
120       goto finish;
121     }
122
123     item = g_udev_client_query_by_subsystem (client, "video4linux");
124     while (item) {
125       GUdevDevice *device = item->data;
126       gchar *devnode = g_strdup (g_udev_device_get_device_file (device));
127       gint api = g_udev_device_get_property_as_int (device, "ID_V4L_VERSION");
128       GST_INFO ("Found new device: %s, API: %d", devnode, api);
129       /* Append v4l2 devices only. If api is 0 probably v4l_id has
130          been stripped out of the current udev installation, append
131          anyway */
132       if (api == 0) {
133         GST_WARNING
134             ("Couldn't retrieve ID_V4L_VERSION, silly udev installation?");
135       }
136       if ((api == 2 || api == 0)) {
137         devices = g_list_append (devices, devnode);
138       } else {
139         g_free (devnode);
140       }
141       g_object_unref (device);
142       item = item->next;
143     }
144     g_list_free (item);
145     init = TRUE;
146   }
147
148 finish:
149   if (client) {
150     g_object_unref (client);
151   }
152
153   *klass_devices = devices;
154
155   return init;
156 }
157 #endif /* HAVE_GUDEV */
158
159 static gboolean
160 gst_v4l2_class_probe_devices (GstElementClass * klass, gboolean check,
161     GList ** klass_devices)
162 {
163   if (!check) {
164     const gchar *dev_base[] = { "/dev/video", "/dev/v4l2/video", NULL };
165     gint base, n, fd;
166
167     while (devices) {
168       gchar *device = devices->data;
169       devices = g_list_remove (devices, device);
170       g_free (device);
171     }
172
173     /*
174      * detect /dev entries
175      */
176     for (n = 0; n < 64; n++) {
177       for (base = 0; dev_base[base] != NULL; base++) {
178         struct stat s;
179         gchar *device = g_strdup_printf ("%s%d",
180             dev_base[base],
181             n);
182
183         /*
184          * does the /dev/ entry exist at all?
185          */
186         if (stat (device, &s) == 0) {
187           /*
188            * yes: is a device attached?
189            */
190           if (S_ISCHR (s.st_mode)) {
191
192             if ((fd = open (device, O_RDWR | O_NONBLOCK)) > 0 || errno == EBUSY) {
193               if (fd > 0)
194                 close (fd);
195
196               devices = g_list_append (devices, device);
197               break;
198             }
199           }
200         }
201         g_free (device);
202       }
203     }
204     init = TRUE;
205   }
206
207   *klass_devices = devices;
208
209   return init;
210 }
211
212 void
213 gst_v4l2_probe_probe_property (GstPropertyProbe * probe,
214     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
215 {
216   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
217
218   switch (prop_id) {
219     case PROP_DEVICE:
220 #ifdef HAVE_GUDEV
221       if (!gst_v4l2_class_probe_devices_with_udev (klass, FALSE, klass_devices))
222         gst_v4l2_class_probe_devices (klass, FALSE, klass_devices);
223 #else /* !HAVE_GUDEV */
224       gst_v4l2_class_probe_devices (klass, FALSE, klass_devices);
225 #endif /* HAVE_GUDEV */
226       break;
227     default:
228       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
229       break;
230   }
231 }
232
233 gboolean
234 gst_v4l2_probe_needs_probe (GstPropertyProbe * probe,
235     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
236 {
237   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
238   gboolean ret = FALSE;
239
240   switch (prop_id) {
241     case PROP_DEVICE:
242 #ifdef HAVE_GUDEV
243       ret =
244           !gst_v4l2_class_probe_devices_with_udev (klass, FALSE, klass_devices);
245 #else /* !HAVE_GUDEV */
246       ret = !gst_v4l2_class_probe_devices (klass, TRUE, klass_devices);
247 #endif /* HAVE_GUDEV */
248       break;
249     default:
250       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
251       break;
252   }
253   return ret;
254 }
255
256 static GValueArray *
257 gst_v4l2_class_list_devices (GstElementClass * klass, GList ** klass_devices)
258 {
259   GValueArray *array;
260   GValue value = { 0 };
261   GList *item;
262
263   if (!*klass_devices)
264     return NULL;
265
266   array = g_value_array_new (g_list_length (*klass_devices));
267   item = *klass_devices;
268   g_value_init (&value, G_TYPE_STRING);
269   while (item) {
270     gchar *device = item->data;
271
272     g_value_set_string (&value, device);
273     g_value_array_append (array, &value);
274
275     item = item->next;
276   }
277   g_value_unset (&value);
278
279   return array;
280 }
281
282 GValueArray *
283 gst_v4l2_probe_get_values (GstPropertyProbe * probe,
284     guint prop_id, const GParamSpec * pspec, GList ** klass_devices)
285 {
286   GstElementClass *klass = GST_ELEMENT_GET_CLASS (probe);
287   GValueArray *array = NULL;
288
289   switch (prop_id) {
290     case PROP_DEVICE:
291       array = gst_v4l2_class_list_devices (klass, klass_devices);
292       break;
293     default:
294       G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
295       break;
296   }
297
298   return array;
299 }
300 #endif
301
302 #define GST_TYPE_V4L2_DEVICE_FLAGS (gst_v4l2_device_get_type ())
303 static GType
304 gst_v4l2_device_get_type (void)
305 {
306   static GType v4l2_device_type = 0;
307
308   if (v4l2_device_type == 0) {
309     static const GFlagsValue values[] = {
310       {V4L2_CAP_VIDEO_CAPTURE, "Device supports video capture", "capture"},
311       {V4L2_CAP_VIDEO_OUTPUT, "Device supports video playback", "output"},
312       {V4L2_CAP_VIDEO_OVERLAY, "Device supports video overlay", "overlay"},
313
314       {V4L2_CAP_VBI_CAPTURE, "Device supports the VBI capture", "vbi-capture"},
315       {V4L2_CAP_VBI_OUTPUT, "Device supports the VBI output", "vbi-output"},
316
317       {V4L2_CAP_TUNER, "Device has a tuner or modulator", "tuner"},
318       {V4L2_CAP_AUDIO, "Device has audio inputs or outputs", "audio"},
319
320       {0, NULL, NULL}
321     };
322
323     v4l2_device_type =
324         g_flags_register_static ("GstV4l2DeviceTypeFlags", values);
325   }
326
327   return v4l2_device_type;
328 }
329
330 #define GST_TYPE_V4L2_TV_NORM (gst_v4l2_tv_norm_get_type ())
331 static GType
332 gst_v4l2_tv_norm_get_type (void)
333 {
334   static GType v4l2_tv_norm = 0;
335
336   if (!v4l2_tv_norm) {
337     static const GEnumValue tv_norms[] = {
338       {0, "none", "none"},
339
340       {V4L2_STD_NTSC, "NTSC", "NTSC"},
341       {V4L2_STD_NTSC_M, "NTSC-M", "NTSC-M"},
342       {V4L2_STD_NTSC_M_JP, "NTSC-M-JP", "NTSC-M-JP"},
343       {V4L2_STD_NTSC_M_KR, "NTSC-M-KR", "NTSC-M-KR"},
344       {V4L2_STD_NTSC_443, "NTSC-443", "NTSC-443"},
345
346       {V4L2_STD_PAL, "PAL", "PAL"},
347       {V4L2_STD_PAL_BG, "PAL-BG", "PAL-BG"},
348       {V4L2_STD_PAL_B, "PAL-B", "PAL-B"},
349       {V4L2_STD_PAL_B1, "PAL-B1", "PAL-B1"},
350       {V4L2_STD_PAL_G, "PAL-G", "PAL-G"},
351       {V4L2_STD_PAL_H, "PAL-H", "PAL-H"},
352       {V4L2_STD_PAL_I, "PAL-I", "PAL-I"},
353       {V4L2_STD_PAL_DK, "PAL-DK", "PAL-DK"},
354       {V4L2_STD_PAL_D, "PAL-D", "PAL-D"},
355       {V4L2_STD_PAL_D1, "PAL-D1", "PAL-D1"},
356       {V4L2_STD_PAL_K, "PAL-K", "PAL-K"},
357       {V4L2_STD_PAL_M, "PAL-M", "PAL-M"},
358       {V4L2_STD_PAL_N, "PAL-N", "PAL-N"},
359       {V4L2_STD_PAL_Nc, "PAL-Nc", "PAL-Nc"},
360       {V4L2_STD_PAL_60, "PAL-60", "PAL-60"},
361
362       {V4L2_STD_SECAM, "SECAM", "SECAM"},
363       {V4L2_STD_SECAM_B, "SECAM-B", "SECAM-B"},
364       {V4L2_STD_SECAM_G, "SECAM-G", "SECAM-G"},
365       {V4L2_STD_SECAM_H, "SECAM-H", "SECAM-H"},
366       {V4L2_STD_SECAM_DK, "SECAM-DK", "SECAM-DK"},
367       {V4L2_STD_SECAM_D, "SECAM-D", "SECAM-D"},
368       {V4L2_STD_SECAM_K, "SECAM-K", "SECAM-K"},
369       {V4L2_STD_SECAM_K1, "SECAM-K1", "SECAM-K1"},
370       {V4L2_STD_SECAM_L, "SECAM-L", "SECAM-L"},
371       {V4L2_STD_SECAM_LC, "SECAM-Lc", "SECAM-Lc"},
372
373       {0, NULL, NULL}
374     };
375
376     v4l2_tv_norm = g_enum_register_static ("V4L2_TV_norms", tv_norms);
377   }
378
379   return v4l2_tv_norm;
380 }
381
382 #define GST_TYPE_V4L2_IO_MODE (gst_v4l2_io_mode_get_type ())
383 static GType
384 gst_v4l2_io_mode_get_type (void)
385 {
386   static GType v4l2_io_mode = 0;
387
388   if (!v4l2_io_mode) {
389     static const GEnumValue io_modes[] = {
390       {GST_V4L2_IO_AUTO, "GST_V4L2_IO_AUTO", "auto"},
391       {GST_V4L2_IO_RW, "GST_V4L2_IO_RW", "rw"},
392       {GST_V4L2_IO_MMAP, "GST_V4L2_IO_MMAP", "mmap"},
393       {GST_V4L2_IO_USERPTR, "GST_V4L2_IO_USERPTR", "userptr"},
394       {GST_V4L2_IO_DMABUF, "GST_V4L2_IO_DMABUF", "dmabuf"},
395
396       {0, NULL, NULL}
397     };
398     v4l2_io_mode = g_enum_register_static ("GstV4l2IOMode", io_modes);
399   }
400   return v4l2_io_mode;
401 }
402
403 void
404 gst_v4l2_object_install_properties_helper (GObjectClass * gobject_class,
405     const char *default_device)
406 {
407   g_object_class_install_property (gobject_class, PROP_DEVICE,
408       g_param_spec_string ("device", "Device", "Device location",
409           default_device, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
410   g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
411       g_param_spec_string ("device-name", "Device name",
412           "Name of the device", DEFAULT_PROP_DEVICE_NAME,
413           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
414   g_object_class_install_property (gobject_class, PROP_DEVICE_FD,
415       g_param_spec_int ("device-fd", "File descriptor",
416           "File descriptor of the device", -1, G_MAXINT, DEFAULT_PROP_DEVICE_FD,
417           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
418   g_object_class_install_property (gobject_class, PROP_FLAGS,
419       g_param_spec_flags ("flags", "Flags", "Device type flags",
420           GST_TYPE_V4L2_DEVICE_FLAGS, DEFAULT_PROP_FLAGS,
421           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
422
423   /**
424    * GstV4l2Src:brightness:
425    *
426    * Picture brightness, or more precisely, the black level
427    */
428   g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
429       g_param_spec_int ("brightness", "Brightness",
430           "Picture brightness, or more precisely, the black level", G_MININT,
431           G_MAXINT, 0,
432           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
433   /**
434    * GstV4l2Src:contrast:
435    *
436    * Picture contrast or luma gain
437    */
438   g_object_class_install_property (gobject_class, PROP_CONTRAST,
439       g_param_spec_int ("contrast", "Contrast",
440           "Picture contrast or luma gain", G_MININT,
441           G_MAXINT, 0,
442           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
443   /**
444    * GstV4l2Src:saturation:
445    *
446    * Picture color saturation or chroma gain
447    */
448   g_object_class_install_property (gobject_class, PROP_SATURATION,
449       g_param_spec_int ("saturation", "Saturation",
450           "Picture color saturation or chroma gain", G_MININT,
451           G_MAXINT, 0,
452           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
453   /**
454    * GstV4l2Src:hue:
455    *
456    * Hue or color balance
457    */
458   g_object_class_install_property (gobject_class, PROP_HUE,
459       g_param_spec_int ("hue", "Hue",
460           "Hue or color balance", G_MININT,
461           G_MAXINT, 0,
462           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
463
464   /**
465    * GstV4l2Src:norm:
466    *
467    * TV norm
468    */
469   g_object_class_install_property (gobject_class, PROP_TV_NORM,
470       g_param_spec_enum ("norm", "TV norm",
471           "video standard",
472           GST_TYPE_V4L2_TV_NORM, DEFAULT_PROP_TV_NORM,
473           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
474
475   /**
476    * GstV4l2Src:io-mode:
477    *
478    * IO Mode
479    */
480   g_object_class_install_property (gobject_class, PROP_IO_MODE,
481       g_param_spec_enum ("io-mode", "IO mode",
482           "I/O mode",
483           GST_TYPE_V4L2_IO_MODE, DEFAULT_PROP_IO_MODE,
484           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
485
486   /**
487    * GstV4l2Src:extra-controls:
488    *
489    * Additional v4l2 controls for the device. The controls are identified
490    * by the control name (lowercase with '_' for any non-alphanumeric
491    * characters).
492    *
493    * Since: 1.2
494    */
495   g_object_class_install_property (gobject_class, PROP_EXTRA_CONTROLS,
496       g_param_spec_boxed ("extra-controls", "Extra Controls",
497           "Extra v4l2 controls (CIDs) for the device",
498           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
499
500   /**
501    * GstV4l2Src:pixel-aspect-ratio:
502    *
503    * The pixel aspect ratio of the device. This overwrites the pixel aspect
504    * ratio queried from the device.
505    *
506    * Since: 1.2
507    */
508   g_object_class_install_property (gobject_class, PROP_PIXEL_ASPECT_RATIO,
509       g_param_spec_string ("pixel-aspect-ratio", "Pixel Aspect Ratio",
510           "Overwrite the pixel aspect ratio of the device", "1/1",
511           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
512
513   /**
514    * GstV4l2Src:force-aspect-ratio:
515    *
516    * When enabled, the pixel aspect ratio queried from the device or set
517    * with the pixel-aspect-ratio property will be enforced.
518    *
519    * Since: 1.2
520    */
521   g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
522       g_param_spec_boolean ("force-aspect-ratio", "Force aspect ratio",
523           "When enabled, the pixel aspect ratio will be enforced", TRUE,
524           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
525
526 }
527
528 GstV4l2Object *
529 gst_v4l2_object_new (GstElement * element,
530     enum v4l2_buf_type type,
531     const char *default_device,
532     GstV4l2GetInOutFunction get_in_out_func,
533     GstV4l2SetInOutFunction set_in_out_func,
534     GstV4l2UpdateFpsFunction update_fps_func)
535 {
536   GstV4l2Object *v4l2object;
537
538   /*
539    * some default values
540    */
541   v4l2object = g_new0 (GstV4l2Object, 1);
542
543   v4l2object->type = type;
544   v4l2object->formats = NULL;
545
546   v4l2object->element = element;
547   v4l2object->get_in_out_func = get_in_out_func;
548   v4l2object->set_in_out_func = set_in_out_func;
549   v4l2object->update_fps_func = update_fps_func;
550
551   v4l2object->video_fd = -1;
552   v4l2object->poll = gst_poll_new (TRUE);
553   v4l2object->active = FALSE;
554   v4l2object->videodev = g_strdup (default_device);
555
556   v4l2object->norms = NULL;
557   v4l2object->channels = NULL;
558   v4l2object->colors = NULL;
559
560   v4l2object->xwindow_id = 0;
561
562   v4l2object->keep_aspect = TRUE;
563
564   return v4l2object;
565 }
566
567 static gboolean gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object);
568
569
570 void
571 gst_v4l2_object_destroy (GstV4l2Object * v4l2object)
572 {
573   g_return_if_fail (v4l2object != NULL);
574
575   if (v4l2object->videodev)
576     g_free (v4l2object->videodev);
577
578   if (v4l2object->poll)
579     gst_poll_free (v4l2object->poll);
580
581   if (v4l2object->channel)
582     g_free (v4l2object->channel);
583
584   if (v4l2object->formats) {
585     gst_v4l2_object_clear_format_list (v4l2object);
586   }
587
588   if (v4l2object->probed_caps) {
589     gst_caps_unref (v4l2object->probed_caps);
590   }
591
592   g_free (v4l2object);
593 }
594
595
596 static gboolean
597 gst_v4l2_object_clear_format_list (GstV4l2Object * v4l2object)
598 {
599   g_slist_foreach (v4l2object->formats, (GFunc) g_free, NULL);
600   g_slist_free (v4l2object->formats);
601   v4l2object->formats = NULL;
602
603   return TRUE;
604 }
605
606 static gint
607 gst_v4l2_object_prop_to_cid (guint prop_id)
608 {
609   gint cid = -1;
610
611   switch (prop_id) {
612     case PROP_BRIGHTNESS:
613       cid = V4L2_CID_BRIGHTNESS;
614       break;
615     case PROP_CONTRAST:
616       cid = V4L2_CID_CONTRAST;
617       break;
618     case PROP_SATURATION:
619       cid = V4L2_CID_SATURATION;
620       break;
621     case PROP_HUE:
622       cid = V4L2_CID_HUE;
623       break;
624     default:
625       GST_WARNING ("unmapped property id: %d", prop_id);
626   }
627   return cid;
628 }
629
630
631 gboolean
632 gst_v4l2_object_set_property_helper (GstV4l2Object * v4l2object,
633     guint prop_id, const GValue * value, GParamSpec * pspec)
634 {
635   switch (prop_id) {
636     case PROP_DEVICE:
637       g_free (v4l2object->videodev);
638       v4l2object->videodev = g_value_dup_string (value);
639       break;
640     case PROP_BRIGHTNESS:
641     case PROP_CONTRAST:
642     case PROP_SATURATION:
643     case PROP_HUE:
644     {
645       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
646
647       if (cid != -1) {
648         if (GST_V4L2_IS_OPEN (v4l2object)) {
649           gst_v4l2_set_attribute (v4l2object, cid, g_value_get_int (value));
650         }
651       }
652       return TRUE;
653     }
654       break;
655     case PROP_TV_NORM:
656       v4l2object->tv_norm = g_value_get_enum (value);
657       break;
658 #if 0
659     case PROP_CHANNEL:
660       if (GST_V4L2_IS_OPEN (v4l2object)) {
661         GstTuner *tuner = GST_TUNER (v4l2object->element);
662         GstTunerChannel *channel = gst_tuner_find_channel_by_name (tuner,
663             (gchar *) g_value_get_string (value));
664
665         if (channel) {
666           /* like gst_tuner_set_channel (tuner, channel)
667              without g_object_notify */
668           gst_v4l2_tuner_set_channel (v4l2object, channel);
669         }
670       } else {
671         g_free (v4l2object->channel);
672         v4l2object->channel = g_value_dup_string (value);
673       }
674       break;
675     case PROP_FREQUENCY:
676       if (GST_V4L2_IS_OPEN (v4l2object)) {
677         GstTuner *tuner = GST_TUNER (v4l2object->element);
678         GstTunerChannel *channel = gst_tuner_get_channel (tuner);
679
680         if (channel &&
681             GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
682           /* like
683              gst_tuner_set_frequency (tuner, channel, g_value_get_ulong (value))
684              without g_object_notify */
685           gst_v4l2_tuner_set_frequency (v4l2object, channel,
686               g_value_get_ulong (value));
687         }
688       } else {
689         v4l2object->frequency = g_value_get_ulong (value);
690       }
691       break;
692 #endif
693     case PROP_IO_MODE:
694       v4l2object->req_mode = g_value_get_enum (value);
695       break;
696     case PROP_EXTRA_CONTROLS:{
697       const GstStructure *s = gst_value_get_structure (value);
698
699       if (v4l2object->extra_controls)
700         gst_structure_free (v4l2object->extra_controls);
701
702       v4l2object->extra_controls = s ? gst_structure_copy (s) : NULL;
703       if (GST_V4L2_IS_OPEN (v4l2object))
704         gst_v4l2_set_controls (v4l2object, v4l2object->extra_controls);
705       break;
706     }
707     case PROP_PIXEL_ASPECT_RATIO:
708       g_free (v4l2object->par);
709       v4l2object->par = g_new0 (GValue, 1);
710       g_value_init (v4l2object->par, GST_TYPE_FRACTION);
711       if (!g_value_transform (value, v4l2object->par)) {
712         g_warning ("Could not transform string to aspect ratio");
713         gst_value_set_fraction (v4l2object->par, 1, 1);
714       }
715       GST_DEBUG_OBJECT (v4l2object->element, "set PAR to %d/%d",
716           gst_value_get_fraction_numerator (v4l2object->par),
717           gst_value_get_fraction_denominator (v4l2object->par));
718       break;
719     case PROP_FORCE_ASPECT_RATIO:
720       v4l2object->keep_aspect = g_value_get_boolean (value);
721       break;
722     default:
723       return FALSE;
724       break;
725   }
726   return TRUE;
727 }
728
729
730 gboolean
731 gst_v4l2_object_get_property_helper (GstV4l2Object * v4l2object,
732     guint prop_id, GValue * value, GParamSpec * pspec)
733 {
734   switch (prop_id) {
735     case PROP_DEVICE:
736       g_value_set_string (value, v4l2object->videodev);
737       break;
738     case PROP_DEVICE_NAME:
739     {
740       const guchar *new = NULL;
741
742       if (GST_V4L2_IS_OPEN (v4l2object)) {
743         new = v4l2object->vcap.card;
744       } else if (gst_v4l2_open (v4l2object)) {
745         new = v4l2object->vcap.card;
746         gst_v4l2_close (v4l2object);
747       }
748       g_value_set_string (value, (gchar *) new);
749       break;
750     }
751     case PROP_DEVICE_FD:
752     {
753       if (GST_V4L2_IS_OPEN (v4l2object))
754         g_value_set_int (value, v4l2object->video_fd);
755       else
756         g_value_set_int (value, DEFAULT_PROP_DEVICE_FD);
757       break;
758     }
759     case PROP_FLAGS:
760     {
761       guint flags = 0;
762
763       if (GST_V4L2_IS_OPEN (v4l2object)) {
764         flags |= v4l2object->vcap.capabilities &
765             (V4L2_CAP_VIDEO_CAPTURE |
766             V4L2_CAP_VIDEO_OUTPUT |
767             V4L2_CAP_VIDEO_OVERLAY |
768             V4L2_CAP_VBI_CAPTURE |
769             V4L2_CAP_VBI_OUTPUT | V4L2_CAP_TUNER | V4L2_CAP_AUDIO);
770       }
771       g_value_set_flags (value, flags);
772       break;
773     }
774     case PROP_BRIGHTNESS:
775     case PROP_CONTRAST:
776     case PROP_SATURATION:
777     case PROP_HUE:
778     {
779       gint cid = gst_v4l2_object_prop_to_cid (prop_id);
780
781       if (cid != -1) {
782         if (GST_V4L2_IS_OPEN (v4l2object)) {
783           gint v;
784           if (gst_v4l2_get_attribute (v4l2object, cid, &v)) {
785             g_value_set_int (value, v);
786           }
787         }
788       }
789       return TRUE;
790     }
791       break;
792     case PROP_TV_NORM:
793       g_value_set_enum (value, v4l2object->tv_norm);
794       break;
795     case PROP_IO_MODE:
796       g_value_set_enum (value, v4l2object->req_mode);
797       break;
798     case PROP_EXTRA_CONTROLS:
799       gst_value_set_structure (value, v4l2object->extra_controls);
800       break;
801     case PROP_PIXEL_ASPECT_RATIO:
802       if (v4l2object->par)
803         g_value_transform (v4l2object->par, value);
804       break;
805     case PROP_FORCE_ASPECT_RATIO:
806       g_value_set_boolean (value, v4l2object->keep_aspect);
807       break;
808     default:
809       return FALSE;
810       break;
811   }
812   return TRUE;
813 }
814
815 static void
816 gst_v4l2_set_defaults (GstV4l2Object * v4l2object)
817 {
818   GstTunerNorm *norm = NULL;
819   GstTunerChannel *channel = NULL;
820   GstTuner *tuner;
821
822   if (!GST_IS_TUNER (v4l2object->element))
823     return;
824
825   tuner = GST_TUNER (v4l2object->element);
826
827   if (v4l2object->tv_norm)
828     norm = gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
829   GST_DEBUG_OBJECT (v4l2object->element, "tv_norm=0x%" G_GINT64_MODIFIER "x, "
830       "norm=%p", (guint64) v4l2object->tv_norm, norm);
831   if (norm) {
832     gst_tuner_set_norm (tuner, norm);
833   } else {
834     norm =
835         GST_TUNER_NORM (gst_tuner_get_norm (GST_TUNER (v4l2object->element)));
836     if (norm) {
837       v4l2object->tv_norm =
838           gst_v4l2_tuner_get_std_id_by_norm (v4l2object, norm);
839       gst_tuner_norm_changed (tuner, norm);
840     }
841   }
842
843   if (v4l2object->channel)
844     channel = gst_tuner_find_channel_by_name (tuner, v4l2object->channel);
845   if (channel) {
846     gst_tuner_set_channel (tuner, channel);
847   } else {
848     channel =
849         GST_TUNER_CHANNEL (gst_tuner_get_channel (GST_TUNER
850             (v4l2object->element)));
851     if (channel) {
852       g_free (v4l2object->channel);
853       v4l2object->channel = g_strdup (channel->label);
854       gst_tuner_channel_changed (tuner, channel);
855     }
856   }
857
858   if (channel
859       && GST_TUNER_CHANNEL_HAS_FLAG (channel, GST_TUNER_CHANNEL_FREQUENCY)) {
860     if (v4l2object->frequency != 0) {
861       gst_tuner_set_frequency (tuner, channel, v4l2object->frequency);
862     } else {
863       v4l2object->frequency = gst_tuner_get_frequency (tuner, channel);
864       if (v4l2object->frequency == 0) {
865         /* guess */
866         gst_tuner_set_frequency (tuner, channel, 1000);
867       } else {
868       }
869     }
870   }
871 }
872
873 gboolean
874 gst_v4l2_object_open (GstV4l2Object * v4l2object)
875 {
876   if (gst_v4l2_open (v4l2object))
877     gst_v4l2_set_defaults (v4l2object);
878   else
879     return FALSE;
880
881 #ifdef HAVE_XVIDEO
882   gst_v4l2_video_overlay_start (v4l2object);
883 #endif
884
885   return TRUE;
886 }
887
888 gboolean
889 gst_v4l2_object_close (GstV4l2Object * v4l2object)
890 {
891 #ifdef HAVE_XVIDEO
892   gst_v4l2_video_overlay_stop (v4l2object);
893 #endif
894
895   if (!gst_v4l2_close (v4l2object))
896     return FALSE;
897
898   gst_caps_replace (&v4l2object->probed_caps, NULL);
899
900   if (v4l2object->formats) {
901     gst_v4l2_object_clear_format_list (v4l2object);
902   }
903
904   return TRUE;
905 }
906
907
908 /*
909  * common format / caps utilities:
910  */
911 typedef struct
912 {
913   guint32 format;
914   gboolean dimensions;
915 } GstV4L2FormatDesc;
916
917 static const GstV4L2FormatDesc gst_v4l2_formats[] = {
918   /* from Linux 2.6.15 videodev2.h */
919   {V4L2_PIX_FMT_RGB332, TRUE},
920   {V4L2_PIX_FMT_RGB555, TRUE},
921   {V4L2_PIX_FMT_RGB565, TRUE},
922   {V4L2_PIX_FMT_RGB555X, TRUE},
923   {V4L2_PIX_FMT_RGB565X, TRUE},
924   {V4L2_PIX_FMT_BGR24, TRUE},
925   {V4L2_PIX_FMT_RGB24, TRUE},
926   {V4L2_PIX_FMT_BGR32, TRUE},
927   {V4L2_PIX_FMT_RGB32, TRUE},
928   {V4L2_PIX_FMT_GREY, TRUE},
929   {V4L2_PIX_FMT_YVU410, TRUE},
930   {V4L2_PIX_FMT_YVU420, TRUE},
931   {V4L2_PIX_FMT_YUYV, TRUE},
932   {V4L2_PIX_FMT_UYVY, TRUE},
933   {V4L2_PIX_FMT_YUV422P, TRUE},
934   {V4L2_PIX_FMT_YUV411P, TRUE},
935   {V4L2_PIX_FMT_Y41P, TRUE},
936
937   /* two planes -- one Y, one Cr + Cb interleaved  */
938   {V4L2_PIX_FMT_NV12, TRUE},
939   {V4L2_PIX_FMT_NV21, TRUE},
940
941   /*  The following formats are not defined in the V4L2 specification */
942   {V4L2_PIX_FMT_YUV410, TRUE},
943   {V4L2_PIX_FMT_YUV420, TRUE},
944   {V4L2_PIX_FMT_YYUV, TRUE},
945   {V4L2_PIX_FMT_HI240, TRUE},
946
947   /* see http://www.siliconimaging.com/RGB%20Bayer.htm */
948 #ifdef V4L2_PIX_FMT_SBGGR8
949   {V4L2_PIX_FMT_SBGGR8, TRUE},
950 #endif
951
952   /* compressed formats */
953   {V4L2_PIX_FMT_MJPEG, TRUE},
954   {V4L2_PIX_FMT_JPEG, TRUE},
955 #ifdef V4L2_PIX_FMT_PJPG
956   {V4L2_PIX_FMT_PJPG, TRUE},
957 #endif
958   {V4L2_PIX_FMT_DV, TRUE},
959   {V4L2_PIX_FMT_MPEG, FALSE},
960 #ifdef V4L2_PIX_FMT_MPEG4
961   {V4L2_PIX_FMT_MPEG4, TRUE},
962 #endif
963
964 #ifdef V4L2_PIX_FMT_H263
965   {V4L2_PIX_FMT_H263, TRUE},
966 #endif
967 #ifdef V4L2_PIX_FMT_H264
968   {V4L2_PIX_FMT_H264, TRUE},
969 #endif
970
971   /*  Vendor-specific formats   */
972   {V4L2_PIX_FMT_WNVA, TRUE},
973
974 #ifdef V4L2_PIX_FMT_SN9C10X
975   {V4L2_PIX_FMT_SN9C10X, TRUE},
976 #endif
977 #ifdef V4L2_PIX_FMT_PWC1
978   {V4L2_PIX_FMT_PWC1, TRUE},
979 #endif
980 #ifdef V4L2_PIX_FMT_PWC2
981   {V4L2_PIX_FMT_PWC2, TRUE},
982 #endif
983 #ifdef V4L2_PIX_FMT_YVYU
984   {V4L2_PIX_FMT_YVYU, TRUE},
985 #endif
986 };
987
988 #define GST_V4L2_FORMAT_COUNT (G_N_ELEMENTS (gst_v4l2_formats))
989
990
991 static struct v4l2_fmtdesc *
992 gst_v4l2_object_get_format_from_fourcc (GstV4l2Object * v4l2object,
993     guint32 fourcc)
994 {
995   struct v4l2_fmtdesc *fmt;
996   GSList *walk;
997
998   if (fourcc == 0)
999     return NULL;
1000
1001   walk = gst_v4l2_object_get_format_list (v4l2object);
1002   while (walk) {
1003     fmt = (struct v4l2_fmtdesc *) walk->data;
1004     if (fmt->pixelformat == fourcc)
1005       return fmt;
1006     /* special case for jpeg */
1007     if (fmt->pixelformat == V4L2_PIX_FMT_MJPEG ||
1008         fmt->pixelformat == V4L2_PIX_FMT_JPEG
1009 #ifdef V4L2_PIX_FMT_PJPG
1010         || fmt->pixelformat == V4L2_PIX_FMT_PJPG
1011 #endif
1012         ) {
1013       if (fourcc == V4L2_PIX_FMT_JPEG || fourcc == V4L2_PIX_FMT_MJPEG
1014 #ifdef V4L2_PIX_FMT_PJPG
1015           || fourcc == V4L2_PIX_FMT_PJPG
1016 #endif
1017           ) {
1018         return fmt;
1019       }
1020     }
1021     walk = g_slist_next (walk);
1022   }
1023
1024   return NULL;
1025 }
1026
1027
1028
1029 /* complete made up ranking, the values themselves are meaningless */
1030 /* These ranks MUST be X such that X<<15 fits on a signed int - see
1031    the comment at the end of gst_v4l2_object_format_get_rank. */
1032 #define YUV_BASE_RANK     1000
1033 #define JPEG_BASE_RANK     500
1034 #define DV_BASE_RANK       200
1035 #define RGB_BASE_RANK      100
1036 #define YUV_ODD_BASE_RANK   50
1037 #define RGB_ODD_BASE_RANK   25
1038 #define BAYER_BASE_RANK     15
1039 #define S910_BASE_RANK      10
1040 #define GREY_BASE_RANK       5
1041 #define PWC_BASE_RANK        1
1042
1043 /* This flag is already used by libv4l2 although
1044  * it was added to the Linux kernel in 2.6.32
1045  */
1046 #ifndef V4L2_FMT_FLAG_EMULATED
1047 #define V4L2_FMT_FLAG_EMULATED 0x0002
1048 #endif
1049
1050 static gint
1051 gst_v4l2_object_format_get_rank (const struct v4l2_fmtdesc *fmt)
1052 {
1053   guint32 fourcc = fmt->pixelformat;
1054   gboolean emulated = ((fmt->flags & V4L2_FMT_FLAG_EMULATED) != 0);
1055   gint rank = 0;
1056
1057   switch (fourcc) {
1058     case V4L2_PIX_FMT_MJPEG:
1059 #ifdef V4L2_PIX_FMT_PJPG
1060     case V4L2_PIX_FMT_PJPG:
1061       rank = JPEG_BASE_RANK;
1062       break;
1063 #endif
1064     case V4L2_PIX_FMT_JPEG:
1065       rank = JPEG_BASE_RANK + 1;
1066       break;
1067     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1068       rank = JPEG_BASE_RANK + 2;
1069       break;
1070
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       rank = RGB_ODD_BASE_RANK;
1077       break;
1078
1079     case V4L2_PIX_FMT_RGB24:
1080     case V4L2_PIX_FMT_BGR24:
1081       rank = RGB_BASE_RANK - 1;
1082       break;
1083
1084     case V4L2_PIX_FMT_RGB32:
1085     case V4L2_PIX_FMT_BGR32:
1086       rank = RGB_BASE_RANK;
1087       break;
1088
1089     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1090       rank = GREY_BASE_RANK;
1091       break;
1092
1093     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1094     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1095     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1096     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1097       rank = YUV_ODD_BASE_RANK;
1098       break;
1099
1100     case V4L2_PIX_FMT_YVU410:  /* YVU9,  9 bits per pixel */
1101       rank = YUV_BASE_RANK + 3;
1102       break;
1103     case V4L2_PIX_FMT_YUV410:  /* YUV9,  9 bits per pixel */
1104       rank = YUV_BASE_RANK + 2;
1105       break;
1106     case V4L2_PIX_FMT_YUV420:  /* I420, 12 bits per pixel */
1107       rank = YUV_BASE_RANK + 7;
1108       break;
1109     case V4L2_PIX_FMT_YUYV:    /* YUY2, 16 bits per pixel */
1110       rank = YUV_BASE_RANK + 10;
1111       break;
1112     case V4L2_PIX_FMT_YVU420:  /* YV12, 12 bits per pixel */
1113       rank = YUV_BASE_RANK + 6;
1114       break;
1115     case V4L2_PIX_FMT_UYVY:    /* UYVY, 16 bits per pixel */
1116       rank = YUV_BASE_RANK + 9;
1117       break;
1118     case V4L2_PIX_FMT_Y41P:    /* Y41P, 12 bits per pixel */
1119       rank = YUV_BASE_RANK + 5;
1120       break;
1121     case V4L2_PIX_FMT_YUV411P: /* Y41B, 12 bits per pixel */
1122       rank = YUV_BASE_RANK + 4;
1123       break;
1124     case V4L2_PIX_FMT_YUV422P: /* Y42B, 16 bits per pixel */
1125       rank = YUV_BASE_RANK + 8;
1126       break;
1127
1128     case V4L2_PIX_FMT_DV:
1129       rank = DV_BASE_RANK;
1130       break;
1131
1132     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1133       rank = 0;
1134       break;
1135
1136 #ifdef V4L2_PIX_FMT_SBGGR8
1137     case V4L2_PIX_FMT_SBGGR8:
1138       rank = BAYER_BASE_RANK;
1139       break;
1140 #endif
1141
1142 #ifdef V4L2_PIX_FMT_SN9C10X
1143     case V4L2_PIX_FMT_SN9C10X:
1144       rank = S910_BASE_RANK;
1145       break;
1146 #endif
1147
1148 #ifdef V4L2_PIX_FMT_PWC1
1149     case V4L2_PIX_FMT_PWC1:
1150       rank = PWC_BASE_RANK;
1151       break;
1152 #endif
1153 #ifdef V4L2_PIX_FMT_PWC2
1154     case V4L2_PIX_FMT_PWC2:
1155       rank = PWC_BASE_RANK;
1156       break;
1157 #endif
1158
1159     default:
1160       rank = 0;
1161       break;
1162   }
1163
1164   /* All ranks are below 1<<15 so a shift by 15
1165    * will a) make all non-emulated formats larger
1166    * than emulated and b) will not overflow
1167    */
1168   if (!emulated)
1169     rank <<= 15;
1170
1171   return rank;
1172 }
1173
1174
1175
1176 static gint
1177 format_cmp_func (gconstpointer a, gconstpointer b)
1178 {
1179   const struct v4l2_fmtdesc *fa = a;
1180   const struct v4l2_fmtdesc *fb = b;
1181
1182   if (fa->pixelformat == fb->pixelformat)
1183     return 0;
1184
1185   return gst_v4l2_object_format_get_rank (fb) -
1186       gst_v4l2_object_format_get_rank (fa);
1187 }
1188
1189 /******************************************************
1190  * gst_v4l2_object_fill_format_list():
1191  *   create list of supported capture formats
1192  * return value: TRUE on success, FALSE on error
1193  ******************************************************/
1194 static gboolean
1195 gst_v4l2_object_fill_format_list (GstV4l2Object * v4l2object)
1196 {
1197   gint n;
1198   struct v4l2_fmtdesc *format;
1199
1200   GST_DEBUG_OBJECT (v4l2object->element, "getting src format enumerations");
1201
1202   /* format enumeration */
1203   for (n = 0;; n++) {
1204     format = g_new0 (struct v4l2_fmtdesc, 1);
1205
1206     format->index = n;
1207     format->type = v4l2object->type;
1208
1209     if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_ENUM_FMT, format) < 0) {
1210       if (errno == EINVAL) {
1211         g_free (format);
1212         break;                  /* end of enumeration */
1213       } else {
1214         goto failed;
1215       }
1216     }
1217
1218     GST_LOG_OBJECT (v4l2object->element, "index:       %u", format->index);
1219     GST_LOG_OBJECT (v4l2object->element, "type:        %d", format->type);
1220     GST_LOG_OBJECT (v4l2object->element, "flags:       %08x", format->flags);
1221     GST_LOG_OBJECT (v4l2object->element, "description: '%s'",
1222         format->description);
1223     GST_LOG_OBJECT (v4l2object->element, "pixelformat: %" GST_FOURCC_FORMAT,
1224         GST_FOURCC_ARGS (format->pixelformat));
1225
1226     /* sort formats according to our preference;  we do this, because caps
1227      * are probed in the order the formats are in the list, and the order of
1228      * formats in the final probed caps matters for things like fixation */
1229     v4l2object->formats = g_slist_insert_sorted (v4l2object->formats, format,
1230         (GCompareFunc) format_cmp_func);
1231   }
1232
1233 #ifndef GST_DISABLE_GST_DEBUG
1234   {
1235     GSList *l;
1236
1237     GST_INFO_OBJECT (v4l2object->element, "got %d format(s):", n);
1238     for (l = v4l2object->formats; l != NULL; l = l->next) {
1239       format = l->data;
1240
1241       GST_INFO_OBJECT (v4l2object->element,
1242           "  %" GST_FOURCC_FORMAT "%s", GST_FOURCC_ARGS (format->pixelformat),
1243           ((format->flags & V4L2_FMT_FLAG_EMULATED)) ? " (emulated)" : "");
1244     }
1245   }
1246 #endif
1247
1248   return TRUE;
1249
1250   /* ERRORS */
1251 failed:
1252   {
1253     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
1254         (_("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)));
1255     g_free (format);
1256     return FALSE;
1257   }
1258 }
1259
1260 /*
1261  * Get the list of supported capture formats, a list of
1262  * <code>struct v4l2_fmtdesc</code>.
1263  */
1264 static GSList *
1265 gst_v4l2_object_get_format_list (GstV4l2Object * v4l2object)
1266 {
1267   if (!v4l2object->formats)
1268     gst_v4l2_object_fill_format_list (v4l2object);
1269   return v4l2object->formats;
1270 }
1271
1272
1273 GstStructure *
1274 gst_v4l2_object_v4l2fourcc_to_structure (guint32 fourcc)
1275 {
1276   GstStructure *structure = NULL;
1277
1278   switch (fourcc) {
1279     case V4L2_PIX_FMT_MJPEG:   /* Motion-JPEG */
1280 #ifdef V4L2_PIX_FMT_PJPG
1281     case V4L2_PIX_FMT_PJPG:    /* Progressive-JPEG */
1282 #endif
1283     case V4L2_PIX_FMT_JPEG:    /* JFIF JPEG */
1284       structure = gst_structure_new_empty ("image/jpeg");
1285       break;
1286     case V4L2_PIX_FMT_YYUV:    /* 16  YUV 4:2:2     */
1287     case V4L2_PIX_FMT_HI240:   /*  8  8-bit color   */
1288       /* FIXME: get correct fourccs here */
1289       break;
1290 #ifdef V4L2_PIX_FMT_MPEG4
1291     case V4L2_PIX_FMT_MPEG4:
1292       structure = gst_structure_new ("video/mpeg",
1293           "mpegversion", G_TYPE_INT, 4, "systemstream",
1294           G_TYPE_BOOLEAN, FALSE, NULL);
1295       break;
1296 #endif
1297 #ifdef V4L2_PIX_FMT_H263
1298     case V4L2_PIX_FMT_H263:
1299       structure = gst_structure_new ("video/x-h263",
1300           "variant", G_TYPE_STRING, "itu", NULL);
1301       break;
1302 #endif
1303 #ifdef V4L2_PIX_FMT_H264
1304     case V4L2_PIX_FMT_H264:    /* H.264 */
1305       structure = gst_structure_new_empty ("video/x-h264");
1306       break;
1307 #endif
1308     case V4L2_PIX_FMT_RGB332:
1309     case V4L2_PIX_FMT_RGB555X:
1310     case V4L2_PIX_FMT_RGB565X:
1311       /* FIXME: get correct fourccs here */
1312       break;
1313     case V4L2_PIX_FMT_GREY:    /*  8  Greyscale     */
1314     case V4L2_PIX_FMT_RGB555:
1315     case V4L2_PIX_FMT_RGB565:
1316     case V4L2_PIX_FMT_RGB24:
1317     case V4L2_PIX_FMT_BGR24:
1318     case V4L2_PIX_FMT_RGB32:
1319     case V4L2_PIX_FMT_BGR32:
1320     case V4L2_PIX_FMT_NV12:    /* 12  Y/CbCr 4:2:0  */
1321     case V4L2_PIX_FMT_NV21:    /* 12  Y/CrCb 4:2:0  */
1322     case V4L2_PIX_FMT_YVU410:
1323     case V4L2_PIX_FMT_YUV410:
1324     case V4L2_PIX_FMT_YUV420:  /* I420/IYUV */
1325     case V4L2_PIX_FMT_YUYV:
1326     case V4L2_PIX_FMT_YVU420:
1327     case V4L2_PIX_FMT_UYVY:
1328 #if 0
1329     case V4L2_PIX_FMT_Y41P:
1330 #endif
1331     case V4L2_PIX_FMT_YUV422P:
1332 #ifdef V4L2_PIX_FMT_YVYU
1333     case V4L2_PIX_FMT_YVYU:
1334 #endif
1335     case V4L2_PIX_FMT_YUV411P:{
1336       GstVideoFormat format;
1337
1338       switch (fourcc) {
1339         case V4L2_PIX_FMT_GREY:        /*  8  Greyscale     */
1340           format = GST_VIDEO_FORMAT_GRAY8;
1341           break;
1342         case V4L2_PIX_FMT_RGB555:
1343           format = GST_VIDEO_FORMAT_RGB15;
1344           break;
1345         case V4L2_PIX_FMT_RGB565:
1346           format = GST_VIDEO_FORMAT_RGB16;
1347           break;
1348         case V4L2_PIX_FMT_RGB24:
1349           format = GST_VIDEO_FORMAT_RGB;
1350           break;
1351         case V4L2_PIX_FMT_BGR24:
1352           format = GST_VIDEO_FORMAT_BGR;
1353           break;
1354         case V4L2_PIX_FMT_RGB32:
1355           format = GST_VIDEO_FORMAT_RGBx;
1356           break;
1357         case V4L2_PIX_FMT_BGR32:
1358           format = GST_VIDEO_FORMAT_BGRx;
1359           break;
1360         case V4L2_PIX_FMT_NV12:
1361           format = GST_VIDEO_FORMAT_NV12;
1362           break;
1363         case V4L2_PIX_FMT_NV21:
1364           format = GST_VIDEO_FORMAT_NV21;
1365           break;
1366         case V4L2_PIX_FMT_YVU410:
1367           format = GST_VIDEO_FORMAT_YVU9;
1368           break;
1369         case V4L2_PIX_FMT_YUV410:
1370           format = GST_VIDEO_FORMAT_YUV9;
1371           break;
1372         case V4L2_PIX_FMT_YUV420:
1373           format = GST_VIDEO_FORMAT_I420;
1374           break;
1375         case V4L2_PIX_FMT_YUYV:
1376           format = GST_VIDEO_FORMAT_YUY2;
1377           break;
1378         case V4L2_PIX_FMT_YVU420:
1379           format = GST_VIDEO_FORMAT_YV12;
1380           break;
1381         case V4L2_PIX_FMT_UYVY:
1382           format = GST_VIDEO_FORMAT_UYVY;
1383           break;
1384 #if 0
1385         case V4L2_PIX_FMT_Y41P:
1386           format = GST_VIDEO_FORMAT_Y41P;
1387           break;
1388 #endif
1389         case V4L2_PIX_FMT_YUV411P:
1390           format = GST_VIDEO_FORMAT_Y41B;
1391           break;
1392         case V4L2_PIX_FMT_YUV422P:
1393           format = GST_VIDEO_FORMAT_Y42B;
1394           break;
1395 #ifdef V4L2_PIX_FMT_YVYU
1396         case V4L2_PIX_FMT_YVYU:
1397           format = GST_VIDEO_FORMAT_YVYU;
1398           break;
1399 #endif
1400         default:
1401           format = GST_VIDEO_FORMAT_UNKNOWN;
1402           g_assert_not_reached ();
1403           break;
1404       }
1405       structure = gst_structure_new ("video/x-raw",
1406           "format", G_TYPE_STRING, gst_video_format_to_string (format), NULL);
1407       break;
1408     }
1409     case V4L2_PIX_FMT_DV:
1410       structure =
1411           gst_structure_new ("video/x-dv", "systemstream", G_TYPE_BOOLEAN, TRUE,
1412           NULL);
1413       break;
1414     case V4L2_PIX_FMT_MPEG:    /* MPEG          */
1415       structure = gst_structure_new_empty ("video/mpegts");
1416       break;
1417     case V4L2_PIX_FMT_WNVA:    /* Winnov hw compres */
1418       break;
1419 #ifdef V4L2_PIX_FMT_SBGGR8
1420     case V4L2_PIX_FMT_SBGGR8:
1421       structure = gst_structure_new_empty ("video/x-bayer");
1422       break;
1423 #endif
1424 #ifdef V4L2_PIX_FMT_SN9C10X
1425     case V4L2_PIX_FMT_SN9C10X:
1426       structure = gst_structure_new_empty ("video/x-sonix");
1427       break;
1428 #endif
1429 #ifdef V4L2_PIX_FMT_PWC1
1430     case V4L2_PIX_FMT_PWC1:
1431       structure = gst_structure_new_empty ("video/x-pwc1");
1432       break;
1433 #endif
1434 #ifdef V4L2_PIX_FMT_PWC2
1435     case V4L2_PIX_FMT_PWC2:
1436       structure = gst_structure_new_empty ("video/x-pwc2");
1437       break;
1438 #endif
1439     default:
1440       GST_DEBUG ("Unknown fourcc 0x%08x %" GST_FOURCC_FORMAT,
1441           fourcc, GST_FOURCC_ARGS (fourcc));
1442       break;
1443   }
1444
1445   return structure;
1446 }
1447
1448
1449
1450 GstCaps *
1451 gst_v4l2_object_get_all_caps (void)
1452 {
1453   static GstCaps *caps = NULL;
1454
1455   if (caps == NULL) {
1456     GstStructure *structure;
1457
1458     guint i;
1459
1460     caps = gst_caps_new_empty ();
1461     for (i = 0; i < GST_V4L2_FORMAT_COUNT; i++) {
1462       structure =
1463           gst_v4l2_object_v4l2fourcc_to_structure (gst_v4l2_formats[i].format);
1464       if (structure) {
1465         if (gst_v4l2_formats[i].dimensions) {
1466           gst_structure_set (structure,
1467               "width", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1468               "height", GST_TYPE_INT_RANGE, 1, GST_V4L2_MAX_SIZE,
1469               "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1, NULL);
1470         }
1471         gst_caps_append_structure (caps, structure);
1472       }
1473     }
1474   }
1475
1476   return gst_caps_ref (caps);
1477 }
1478
1479
1480 /* collect data for the given caps
1481  * @caps: given input caps
1482  * @format: location for the v4l format
1483  * @w/@h: location for width and height
1484  * @fps_n/@fps_d: location for framerate
1485  * @size: location for expected size of the frame or 0 if unknown
1486  */
1487 static gboolean
1488 gst_v4l2_object_get_caps_info (GstV4l2Object * v4l2object, GstCaps * caps,
1489     struct v4l2_fmtdesc **format, GstVideoInfo * info)
1490 {
1491   GstStructure *structure;
1492   guint32 fourcc;
1493   const gchar *mimetype;
1494   struct v4l2_fmtdesc *fmt;
1495
1496   /* default unknown values */
1497   fourcc = 0;
1498
1499   structure = gst_caps_get_structure (caps, 0);
1500
1501   mimetype = gst_structure_get_name (structure);
1502
1503   if (!gst_video_info_from_caps (info, caps))
1504     goto invalid_format;
1505
1506   if (g_str_equal (mimetype, "video/x-raw")) {
1507     switch (GST_VIDEO_INFO_FORMAT (info)) {
1508       case GST_VIDEO_FORMAT_I420:
1509         fourcc = V4L2_PIX_FMT_YUV420;
1510         break;
1511       case GST_VIDEO_FORMAT_YUY2:
1512         fourcc = V4L2_PIX_FMT_YUYV;
1513         break;
1514 #if 0
1515       case GST_VIDEO_FORMAT_Y41P:
1516         fourcc = V4L2_PIX_FMT_Y41P;
1517         break;
1518 #endif
1519       case GST_VIDEO_FORMAT_UYVY:
1520         fourcc = V4L2_PIX_FMT_UYVY;
1521         break;
1522       case GST_VIDEO_FORMAT_YV12:
1523         fourcc = V4L2_PIX_FMT_YVU420;
1524         break;
1525       case GST_VIDEO_FORMAT_Y41B:
1526         fourcc = V4L2_PIX_FMT_YUV411P;
1527         break;
1528       case GST_VIDEO_FORMAT_Y42B:
1529         fourcc = V4L2_PIX_FMT_YUV422P;
1530         break;
1531       case GST_VIDEO_FORMAT_NV12:
1532         fourcc = V4L2_PIX_FMT_NV12;
1533         break;
1534       case GST_VIDEO_FORMAT_NV21:
1535         fourcc = V4L2_PIX_FMT_NV21;
1536         break;
1537 #ifdef V4L2_PIX_FMT_YVYU
1538       case GST_VIDEO_FORMAT_YVYU:
1539         fourcc = V4L2_PIX_FMT_YVYU;
1540         break;
1541 #endif
1542       case GST_VIDEO_FORMAT_RGB15:
1543         fourcc = V4L2_PIX_FMT_RGB555;
1544         break;
1545       case GST_VIDEO_FORMAT_RGB16:
1546         fourcc = V4L2_PIX_FMT_RGB565;
1547         break;
1548       case GST_VIDEO_FORMAT_RGB:
1549         fourcc = V4L2_PIX_FMT_RGB24;
1550         break;
1551       case GST_VIDEO_FORMAT_BGR:
1552         fourcc = V4L2_PIX_FMT_BGR24;
1553         break;
1554       case GST_VIDEO_FORMAT_RGBx:
1555       case GST_VIDEO_FORMAT_RGBA:
1556         fourcc = V4L2_PIX_FMT_RGB32;
1557         break;
1558       case GST_VIDEO_FORMAT_BGRx:
1559       case GST_VIDEO_FORMAT_BGRA:
1560         fourcc = V4L2_PIX_FMT_BGR32;
1561         break;
1562       case GST_VIDEO_FORMAT_GRAY8:
1563         fourcc = V4L2_PIX_FMT_GREY;
1564       default:
1565         break;
1566     }
1567   } else {
1568     if (g_str_equal (mimetype, "video/mpegts")) {
1569       fourcc = V4L2_PIX_FMT_MPEG;
1570     } else if (g_str_equal (mimetype, "video/x-dv")) {
1571       fourcc = V4L2_PIX_FMT_DV;
1572     } else if (g_str_equal (mimetype, "image/jpeg")) {
1573       fourcc = V4L2_PIX_FMT_JPEG;
1574 #ifdef V4L2_PIX_FMT_MPEG4
1575     } else if (g_str_equal (mimetype, "video/mpeg")) {
1576       fourcc = V4L2_PIX_FMT_MPEG4;
1577 #endif
1578 #ifdef V4L2_PIX_FMT_H263
1579     } else if (g_str_equal (mimetype, "video/x-h263")) {
1580       fourcc = V4L2_PIX_FMT_H263;
1581 #endif
1582 #ifdef V4L2_PIX_FMT_H264
1583     } else if (g_str_equal (mimetype, "video/x-h264")) {
1584       fourcc = V4L2_PIX_FMT_H264;
1585 #endif
1586 #ifdef V4L2_PIX_FMT_SBGGR8
1587     } else if (g_str_equal (mimetype, "video/x-bayer")) {
1588       fourcc = V4L2_PIX_FMT_SBGGR8;
1589 #endif
1590 #ifdef V4L2_PIX_FMT_SN9C10X
1591     } else if (g_str_equal (mimetype, "video/x-sonix")) {
1592       fourcc = V4L2_PIX_FMT_SN9C10X;
1593 #endif
1594 #ifdef V4L2_PIX_FMT_PWC1
1595     } else if (g_str_equal (mimetype, "video/x-pwc1")) {
1596       fourcc = V4L2_PIX_FMT_PWC1;
1597 #endif
1598 #ifdef V4L2_PIX_FMT_PWC2
1599     } else if (g_str_equal (mimetype, "video/x-pwc2")) {
1600       fourcc = V4L2_PIX_FMT_PWC2;
1601     }
1602 #endif
1603   }
1604
1605   if (fourcc == 0)
1606     goto unhandled_format;
1607
1608   fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1609   if (fmt == NULL)
1610     goto unsupported_format;
1611
1612   *format = fmt;
1613
1614   return TRUE;
1615
1616   /* ERRORS */
1617 invalid_format:
1618   {
1619     GST_DEBUG_OBJECT (v4l2object, "invalid format");
1620     return FALSE;
1621   }
1622 unhandled_format:
1623   {
1624     GST_DEBUG_OBJECT (v4l2object, "unhandled format");
1625     return FALSE;
1626   }
1627 unsupported_format:
1628   {
1629     GST_DEBUG_OBJECT (v4l2object, "unsupported format");
1630     return FALSE;
1631   }
1632 }
1633
1634
1635 static gboolean
1636 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1637     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced);
1638
1639 static void
1640 gst_v4l2_object_add_aspect_ratio (GstV4l2Object * v4l2object, GstStructure * s)
1641 {
1642   struct v4l2_cropcap cropcap;
1643   int num = 1, den = 1;
1644
1645   if (!v4l2object->keep_aspect)
1646     return;
1647
1648   if (v4l2object->par) {
1649     num = gst_value_get_fraction_numerator (v4l2object->par);
1650     den = gst_value_get_fraction_denominator (v4l2object->par);
1651     goto done;
1652   }
1653
1654   memset (&cropcap, 0, sizeof (cropcap));
1655
1656   cropcap.type = v4l2object->type;
1657   if (v4l2_ioctl (v4l2object->video_fd, VIDIOC_CROPCAP, &cropcap) < 0)
1658     goto cropcap_failed;
1659
1660   num = cropcap.pixelaspect.numerator;
1661   den = cropcap.pixelaspect.denominator;
1662
1663 done:
1664   gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION, num, den,
1665       NULL);
1666   return;
1667
1668 cropcap_failed:
1669   if (errno != ENOTTY)
1670     GST_WARNING_OBJECT (v4l2object->element,
1671         "Failed to probe pixel aspect ratio with VIDIOC_CROPCAP: %s",
1672         g_strerror (errno));
1673   goto done;
1674 }
1675
1676
1677 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1678 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1679 static GstStructure *
1680 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1681     guint32 pixelformat,
1682     guint32 width, guint32 height, const GstStructure * template)
1683 {
1684   gint fd = v4l2object->video_fd;
1685   struct v4l2_frmivalenum ival;
1686   guint32 num, denom;
1687   GstStructure *s;
1688   GValue rates = { 0, };
1689   gboolean interlaced;
1690   gint int_width = width;
1691   gint int_height = height;
1692
1693   if (!strcmp ((char *) v4l2object->vcap.driver, "uvcvideo")) {
1694     /*
1695      * UVC devices are never interlaced, and doing VIDIOC_TRY_FMT on them
1696      * causes expensive and slow USB IO, so don't probe them for interlaced
1697      */
1698     interlaced = FALSE;
1699   } else {
1700     /* Interlaced detection using VIDIOC_TRY/S_FMT */
1701     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat,
1702             &int_width, &int_height, &interlaced))
1703       return NULL;
1704   }
1705
1706   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1707   ival.index = 0;
1708   ival.pixel_format = pixelformat;
1709   ival.width = width;
1710   ival.height = height;
1711
1712   GST_LOG_OBJECT (v4l2object->element,
1713       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1714       GST_FOURCC_ARGS (pixelformat));
1715
1716   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1717    * fraction to get framerate */
1718   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1719     goto enum_frameintervals_failed;
1720
1721   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1722     GValue rate = { 0, };
1723
1724     g_value_init (&rates, GST_TYPE_LIST);
1725     g_value_init (&rate, GST_TYPE_FRACTION);
1726
1727     do {
1728       num = ival.discrete.numerator;
1729       denom = ival.discrete.denominator;
1730
1731       if (num > G_MAXINT || denom > G_MAXINT) {
1732         /* let us hope we don't get here... */
1733         num >>= 1;
1734         denom >>= 1;
1735       }
1736
1737       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1738           denom, num);
1739
1740       /* swap to get the framerate */
1741       gst_value_set_fraction (&rate, denom, num);
1742       gst_value_list_append_value (&rates, &rate);
1743
1744       ival.index++;
1745     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1746   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1747     GValue min = { 0, };
1748     GValue step = { 0, };
1749     GValue max = { 0, };
1750     gboolean added = FALSE;
1751     guint32 minnum, mindenom;
1752     guint32 maxnum, maxdenom;
1753
1754     g_value_init (&rates, GST_TYPE_LIST);
1755
1756     g_value_init (&min, GST_TYPE_FRACTION);
1757     g_value_init (&step, GST_TYPE_FRACTION);
1758     g_value_init (&max, GST_TYPE_FRACTION);
1759
1760     /* get the min */
1761     minnum = ival.stepwise.min.numerator;
1762     mindenom = ival.stepwise.min.denominator;
1763     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1764       minnum >>= 1;
1765       mindenom >>= 1;
1766     }
1767     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1768         minnum, mindenom);
1769     gst_value_set_fraction (&min, minnum, mindenom);
1770
1771     /* get the max */
1772     maxnum = ival.stepwise.max.numerator;
1773     maxdenom = ival.stepwise.max.denominator;
1774     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1775       maxnum >>= 1;
1776       maxdenom >>= 1;
1777     }
1778
1779     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1780         maxnum, maxdenom);
1781     gst_value_set_fraction (&max, maxnum, maxdenom);
1782
1783     /* get the step */
1784     num = ival.stepwise.step.numerator;
1785     denom = ival.stepwise.step.denominator;
1786     if (num > G_MAXINT || denom > G_MAXINT) {
1787       num >>= 1;
1788       denom >>= 1;
1789     }
1790
1791     if (num == 0 || denom == 0) {
1792       /* in this case we have a wrong fraction or no step, set the step to max
1793        * so that we only add the min value in the loop below */
1794       num = maxnum;
1795       denom = maxdenom;
1796     }
1797
1798     /* since we only have gst_value_fraction_subtract and not add, negate the
1799      * numerator */
1800     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1801         num, denom);
1802     gst_value_set_fraction (&step, -num, denom);
1803
1804     while (gst_value_compare (&min, &max) != GST_VALUE_GREATER_THAN) {
1805       GValue rate = { 0, };
1806
1807       num = gst_value_get_fraction_numerator (&min);
1808       denom = gst_value_get_fraction_denominator (&min);
1809       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1810           denom, num);
1811
1812       /* invert to get the framerate */
1813       g_value_init (&rate, GST_TYPE_FRACTION);
1814       gst_value_set_fraction (&rate, denom, num);
1815       gst_value_list_append_value (&rates, &rate);
1816       added = TRUE;
1817
1818       /* we're actually adding because step was negated above. This is because
1819        * there is no _add function... */
1820       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1821         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1822         break;
1823       }
1824     }
1825     if (!added) {
1826       /* no range was added, leave the default range from the template */
1827       GST_WARNING_OBJECT (v4l2object->element,
1828           "no range added, leaving default");
1829       g_value_unset (&rates);
1830     }
1831   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1832     guint32 maxnum, maxdenom;
1833
1834     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1835
1836     num = ival.stepwise.min.numerator;
1837     denom = ival.stepwise.min.denominator;
1838     if (num > G_MAXINT || denom > G_MAXINT) {
1839       num >>= 1;
1840       denom >>= 1;
1841     }
1842
1843     maxnum = ival.stepwise.max.numerator;
1844     maxdenom = ival.stepwise.max.denominator;
1845     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1846       maxnum >>= 1;
1847       maxdenom >>= 1;
1848     }
1849
1850     GST_LOG_OBJECT (v4l2object->element,
1851         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1852         num);
1853
1854     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1855   } else {
1856     goto unknown_type;
1857   }
1858
1859 return_data:
1860   s = gst_structure_copy (template);
1861   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1862       "height", G_TYPE_INT, (gint) height, NULL);
1863   gst_v4l2_object_add_aspect_ratio (v4l2object, s);
1864   if (g_str_equal (gst_structure_get_name (s), "video/x-raw"))
1865     gst_structure_set (s, "interlace-mode", G_TYPE_STRING,
1866         (interlaced ? "mixed" : "progressive"), NULL);
1867
1868   if (G_IS_VALUE (&rates)) {
1869     /* only change the framerate on the template when we have a valid probed new
1870      * value */
1871     gst_structure_set_value (s, "framerate", &rates);
1872     g_value_unset (&rates);
1873   } else {
1874     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1875         NULL);
1876   }
1877   return s;
1878
1879   /* ERRORS */
1880 enum_frameintervals_failed:
1881   {
1882     GST_DEBUG_OBJECT (v4l2object->element,
1883         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1884         GST_FOURCC_ARGS (pixelformat), width, height);
1885     goto return_data;
1886   }
1887 unknown_type:
1888   {
1889     /* I don't see how this is actually an error, we ignore the format then */
1890     GST_WARNING_OBJECT (v4l2object->element,
1891         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1892         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1893     return NULL;
1894   }
1895 }
1896 #endif /* defined VIDIOC_ENUM_FRAMEINTERVALS */
1897
1898 #ifdef VIDIOC_ENUM_FRAMESIZES
1899 static gint
1900 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1901 {
1902   int w1, h1, w2, h2;
1903
1904   gst_structure_get_int (s1, "width", &w1);
1905   gst_structure_get_int (s1, "height", &h1);
1906   gst_structure_get_int (s2, "width", &w2);
1907   gst_structure_get_int (s2, "height", &h2);
1908
1909   /* I think it's safe to assume that this won't overflow for a while */
1910   return ((w2 * h2) - (w1 * h1));
1911 }
1912 #endif
1913
1914 static GstCaps *
1915 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
1916     guint32 pixelformat, const GstStructure * template)
1917 {
1918   GstCaps *ret = gst_caps_new_empty ();
1919   GstStructure *tmp;
1920
1921 #ifdef VIDIOC_ENUM_FRAMESIZES
1922   gint fd = v4l2object->video_fd;
1923   struct v4l2_frmsizeenum size;
1924   GList *results = NULL;
1925   guint32 w, h;
1926
1927   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G'))
1928     return gst_caps_new_empty_simple ("video/mpegts");
1929
1930   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
1931   size.index = 0;
1932   size.pixel_format = pixelformat;
1933
1934   GST_DEBUG_OBJECT (v4l2object->element,
1935       "Enumerating frame sizes for %" GST_FOURCC_FORMAT,
1936       GST_FOURCC_ARGS (pixelformat));
1937
1938   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
1939     goto enum_framesizes_failed;
1940
1941   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
1942     do {
1943       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
1944           size.discrete.width, size.discrete.height);
1945
1946       w = MIN (size.discrete.width, G_MAXINT);
1947       h = MIN (size.discrete.height, G_MAXINT);
1948
1949       if (w && h) {
1950         tmp =
1951             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1952             pixelformat, w, h, template);
1953
1954         if (tmp)
1955           results = g_list_prepend (results, tmp);
1956       }
1957
1958       size.index++;
1959     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
1960     GST_DEBUG_OBJECT (v4l2object->element,
1961         "done iterating discrete frame sizes");
1962   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
1963     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
1964     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1965         size.stepwise.min_width);
1966     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1967         size.stepwise.min_height);
1968     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1969         size.stepwise.max_width);
1970     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1971         size.stepwise.max_height);
1972     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
1973         size.stepwise.step_width);
1974     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
1975         size.stepwise.step_height);
1976
1977     for (w = size.stepwise.min_width, h = size.stepwise.min_height;
1978         w <= size.stepwise.max_width && h <= size.stepwise.max_height;
1979         w += size.stepwise.step_width, h += size.stepwise.step_height) {
1980       if (w == 0 || h == 0)
1981         continue;
1982
1983       tmp =
1984           gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1985           pixelformat, w, h, template);
1986
1987       if (tmp)
1988         results = g_list_prepend (results, tmp);
1989     }
1990     GST_DEBUG_OBJECT (v4l2object->element,
1991         "done iterating stepwise frame sizes");
1992   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
1993     guint32 maxw, maxh;
1994
1995     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
1996     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1997         size.stepwise.min_width);
1998     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1999         size.stepwise.min_height);
2000     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
2001         size.stepwise.max_width);
2002     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
2003         size.stepwise.max_height);
2004
2005     w = MAX (size.stepwise.min_width, 1);
2006     h = MAX (size.stepwise.min_height, 1);
2007     maxw = MIN (size.stepwise.max_width, G_MAXINT);
2008     maxh = MIN (size.stepwise.max_height, G_MAXINT);
2009
2010     tmp =
2011         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
2012         w, h, template);
2013     if (tmp) {
2014       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
2015           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
2016           NULL);
2017
2018       /* no point using the results list here, since there's only one struct */
2019       gst_caps_append_structure (ret, tmp);
2020     }
2021   } else {
2022     goto unknown_type;
2023   }
2024
2025   /* we use an intermediary list to store and then sort the results of the
2026    * probing because we can't make any assumptions about the order in which
2027    * the driver will give us the sizes, but we want the final caps to contain
2028    * the results starting with the highest resolution and having the lowest
2029    * resolution last, since order in caps matters for things like fixation. */
2030   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
2031   while (results != NULL) {
2032     gst_caps_append_structure (ret, GST_STRUCTURE (results->data));
2033     results = g_list_delete_link (results, results);
2034   }
2035
2036   if (gst_caps_is_empty (ret))
2037     goto enum_framesizes_no_results;
2038
2039   return ret;
2040
2041   /* ERRORS */
2042 enum_framesizes_failed:
2043   {
2044     /* I don't see how this is actually an error */
2045     GST_DEBUG_OBJECT (v4l2object->element,
2046         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
2047         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
2048     goto default_frame_sizes;
2049   }
2050 enum_framesizes_no_results:
2051   {
2052     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
2053      * question doesn't actually support it yet */
2054     GST_DEBUG_OBJECT (v4l2object->element,
2055         "No results for pixelformat %" GST_FOURCC_FORMAT
2056         " enumerating frame sizes, trying fallback",
2057         GST_FOURCC_ARGS (pixelformat));
2058     goto default_frame_sizes;
2059   }
2060 unknown_type:
2061   {
2062     GST_WARNING_OBJECT (v4l2object->element,
2063         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
2064         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
2065     goto default_frame_sizes;
2066   }
2067 default_frame_sizes:
2068 #endif /* defined VIDIOC_ENUM_FRAMESIZES */
2069   {
2070     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
2071     gboolean interlaced;
2072
2073     /* This code is for Linux < 2.6.19 */
2074     min_w = min_h = 1;
2075     max_w = max_h = GST_V4L2_MAX_SIZE;
2076     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
2077             &min_h, &interlaced)) {
2078       GST_WARNING_OBJECT (v4l2object->element,
2079           "Could not probe minimum capture size for pixelformat %"
2080           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2081     }
2082     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
2083             &max_h, &interlaced)) {
2084       GST_WARNING_OBJECT (v4l2object->element,
2085           "Could not probe maximum capture size for pixelformat %"
2086           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
2087     }
2088
2089     /* Since we can't get framerate directly, try to use the current norm */
2090     if (v4l2object->tv_norm && v4l2object->norms) {
2091       GList *norms;
2092       GstTunerNorm *norm = NULL;
2093       GstTunerNorm *current =
2094           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
2095
2096       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
2097         norm = (GstTunerNorm *) norms->data;
2098         if (!strcmp (norm->label, current->label))
2099           break;
2100       }
2101       /* If it's possible, set framerate to that (discrete) value */
2102       if (norm) {
2103         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
2104         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
2105       }
2106     }
2107
2108     tmp = gst_structure_copy (template);
2109     if (fix_num) {
2110       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
2111           fix_denom, NULL);
2112     } else {
2113       /* if norm can't be used, copy the template framerate */
2114       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
2115           100, 1, NULL);
2116     }
2117
2118     if (min_w == max_w)
2119       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
2120     else
2121       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
2122
2123     if (min_h == max_h)
2124       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
2125     else
2126       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
2127
2128     if (g_str_equal (gst_structure_get_name (tmp), "video/x-raw"))
2129       gst_structure_set (tmp, "interlace-mode", G_TYPE_STRING,
2130           (interlaced ? "mixed" : "progressive"), NULL);
2131     gst_v4l2_object_add_aspect_ratio (v4l2object, tmp);
2132
2133     gst_caps_append_structure (ret, tmp);
2134
2135     return ret;
2136   }
2137 }
2138
2139 static gboolean
2140 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
2141     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced)
2142 {
2143   struct v4l2_format fmt, prevfmt;
2144   int fd;
2145   int r;
2146   int prevfmt_valid;
2147
2148   g_return_val_if_fail (width != NULL, FALSE);
2149   g_return_val_if_fail (height != NULL, FALSE);
2150
2151   GST_LOG_OBJECT (v4l2object->element,
2152       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2153       *width, *height, GST_FOURCC_ARGS (pixelformat));
2154
2155   fd = v4l2object->video_fd;
2156
2157   /* Some drivers are buggy and will modify the currently set format
2158      when processing VIDIOC_TRY_FMT, so we remember what is set at the
2159      minute, and will reset it when done. */
2160   prevfmt.type = v4l2object->type;
2161   prevfmt_valid = (v4l2_ioctl (fd, VIDIOC_G_FMT, &prevfmt) >= 0);
2162
2163   /* get size delimiters */
2164   memset (&fmt, 0, sizeof (fmt));
2165   fmt.type = v4l2object->type;
2166   fmt.fmt.pix.width = *width;
2167   fmt.fmt.pix.height = *height;
2168   fmt.fmt.pix.pixelformat = pixelformat;
2169   fmt.fmt.pix.field = V4L2_FIELD_NONE;
2170
2171   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2172   if (r < 0 && errno == EINVAL) {
2173     /* try again with interlaced video */
2174     fmt.fmt.pix.width = *width;
2175     fmt.fmt.pix.height = *height;
2176     fmt.fmt.pix.pixelformat = pixelformat;
2177     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2178     r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2179   }
2180
2181   if (r < 0) {
2182     /* The driver might not implement TRY_FMT, in which case we will try
2183        S_FMT to probe */
2184     if (errno != ENOTTY)
2185       goto error;
2186
2187     /* Only try S_FMT if we're not actively capturing yet, which we shouldn't
2188        be, because we're still probing */
2189     if (GST_V4L2_IS_ACTIVE (v4l2object))
2190       goto error;
2191
2192     GST_LOG_OBJECT (v4l2object->element,
2193         "Failed to probe size limit with VIDIOC_TRY_FMT, trying VIDIOC_S_FMT");
2194
2195     fmt.fmt.pix.width = *width;
2196     fmt.fmt.pix.height = *height;
2197
2198     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2199     if (r < 0 && errno == EINVAL) {
2200       /* try again with progressive video */
2201       fmt.fmt.pix.width = *width;
2202       fmt.fmt.pix.height = *height;
2203       fmt.fmt.pix.pixelformat = pixelformat;
2204       fmt.fmt.pix.field = V4L2_FIELD_NONE;
2205       r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2206     }
2207
2208     if (r < 0)
2209       goto error;
2210   }
2211
2212   GST_LOG_OBJECT (v4l2object->element,
2213       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2214
2215   *width = fmt.fmt.pix.width;
2216   *height = fmt.fmt.pix.height;
2217
2218   switch (fmt.fmt.pix.field) {
2219     case V4L2_FIELD_ANY:
2220     case V4L2_FIELD_NONE:
2221       *interlaced = FALSE;
2222       break;
2223     case V4L2_FIELD_INTERLACED:
2224     case V4L2_FIELD_INTERLACED_TB:
2225     case V4L2_FIELD_INTERLACED_BT:
2226       *interlaced = TRUE;
2227       break;
2228     default:
2229       GST_WARNING_OBJECT (v4l2object->element,
2230           "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u",
2231           GST_FOURCC_ARGS (pixelformat), *width, *height);
2232       goto error;
2233   }
2234
2235   if (prevfmt_valid)
2236     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2237   return TRUE;
2238
2239 error:
2240   if (prevfmt_valid)
2241     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2242   return FALSE;
2243 }
2244
2245 static gboolean
2246 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
2247 {
2248   GstV4l2IOMode mode;
2249
2250   GST_DEBUG_OBJECT (v4l2object->element, "initializing the capture system");
2251
2252   GST_V4L2_CHECK_OPEN (v4l2object);
2253   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2254
2255   /* find transport */
2256   mode = v4l2object->req_mode;
2257
2258   if (v4l2object->vcap.capabilities & V4L2_CAP_READWRITE) {
2259     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2260       mode = GST_V4L2_IO_RW;
2261   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
2262     goto method_not_supported;
2263
2264   if (v4l2object->vcap.capabilities & V4L2_CAP_STREAMING) {
2265     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2266       mode = GST_V4L2_IO_MMAP;
2267   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP)
2268     goto method_not_supported;
2269
2270   /* if still no transport selected, error out */
2271   if (mode == GST_V4L2_IO_AUTO)
2272     goto no_supported_capture_method;
2273
2274   GST_INFO_OBJECT (v4l2object->element, "accessing buffers via mode %d", mode);
2275   v4l2object->mode = mode;
2276
2277   /* Map the buffers */
2278   GST_LOG_OBJECT (v4l2object->element, "initiating buffer pool");
2279
2280   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
2281     goto buffer_pool_new_failed;
2282
2283   GST_V4L2_SET_ACTIVE (v4l2object);
2284
2285   return TRUE;
2286
2287   /* ERRORS */
2288 buffer_pool_new_failed:
2289   {
2290     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2291         (_("Could not map buffers from device '%s'"),
2292             v4l2object->videodev),
2293         ("Failed to create buffer pool: %s", g_strerror (errno)));
2294     return FALSE;
2295   }
2296 method_not_supported:
2297   {
2298     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2299         (_("The driver of device '%s' does not support the IO method %d"),
2300             v4l2object->videodev, mode), (NULL));
2301     return FALSE;
2302   }
2303 no_supported_capture_method:
2304   {
2305     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2306         (_("The driver of device '%s' does not support any known IO "
2307                 "method."), v4l2object->videodev), (NULL));
2308     return FALSE;
2309   }
2310 }
2311
2312 gboolean
2313 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps)
2314 {
2315   gint fd = v4l2object->video_fd;
2316   struct v4l2_format format;
2317   struct v4l2_streamparm streamparm;
2318   enum v4l2_field field;
2319   guint32 pixelformat;
2320   struct v4l2_fmtdesc *fmtdesc;
2321   GstVideoInfo info;
2322   gint width, height, fps_n, fps_d, stride;
2323
2324   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
2325     goto invalid_caps;
2326
2327   pixelformat = fmtdesc->pixelformat;
2328   width = GST_VIDEO_INFO_WIDTH (&info);
2329   height = GST_VIDEO_INFO_HEIGHT (&info);
2330   fps_n = GST_VIDEO_INFO_FPS_N (&info);
2331   fps_d = GST_VIDEO_INFO_FPS_D (&info);
2332   stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
2333
2334   if (GST_VIDEO_INFO_IS_INTERLACED (&info)) {
2335     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2336     /* ideally we would differentiate between types of interlaced video
2337      * but there is not sufficient information in the caps..
2338      */
2339     field = V4L2_FIELD_INTERLACED;
2340   } else {
2341     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2342     field = V4L2_FIELD_NONE;
2343   }
2344
2345   GST_DEBUG_OBJECT (v4l2object->element, "Desired format %dx%d, format "
2346       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
2347       GST_FOURCC_ARGS (pixelformat), stride);
2348
2349   GST_V4L2_CHECK_OPEN (v4l2object);
2350   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2351
2352   /* MPEG-TS source cameras don't get their format set for some reason.
2353    * It looks wrong and we weren't able to track down the reason for that code
2354    * so it is disabled until someone who has an mpeg-ts camera complains...
2355    */
2356 #if 0
2357   /* Only unconditionally accept mpegts for sources */
2358   if ((v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
2359       (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')))
2360     goto done;
2361 #endif
2362
2363   memset (&format, 0x00, sizeof (struct v4l2_format));
2364   format.type = v4l2object->type;
2365
2366   if (v4l2_ioctl (fd, VIDIOC_G_FMT, &format) < 0)
2367     goto get_fmt_failed;
2368
2369   GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2370       "%" GST_FOURCC_FORMAT " bytesperline %d, colorspace %d",
2371       format.fmt.pix.width, format.fmt.pix.height,
2372       GST_FOURCC_ARGS (format.fmt.pix.pixelformat), format.fmt.pix.bytesperline,
2373       format.fmt.pix.colorspace);
2374
2375   if (format.type != v4l2object->type ||
2376       format.fmt.pix.width != width ||
2377       format.fmt.pix.height != height ||
2378       format.fmt.pix.pixelformat != pixelformat ||
2379       format.fmt.pix.field != field || format.fmt.pix.bytesperline != stride) {
2380     /* something different, set the format */
2381     GST_DEBUG_OBJECT (v4l2object->element, "Setting format to %dx%d, format "
2382         "%" GST_FOURCC_FORMAT " bytesperline %d", width, height,
2383         GST_FOURCC_ARGS (pixelformat), stride);
2384
2385     format.type = v4l2object->type;
2386     format.fmt.pix.width = width;
2387     format.fmt.pix.height = height;
2388     format.fmt.pix.pixelformat = pixelformat;
2389     format.fmt.pix.field = field;
2390     /* try to ask our prefered stride */
2391     format.fmt.pix.bytesperline = stride;
2392
2393     if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0)
2394       goto set_fmt_failed;
2395
2396     GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2397         "%" GST_FOURCC_FORMAT " stride %d", format.fmt.pix.width,
2398         format.fmt.pix.height, GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2399         format.fmt.pix.bytesperline);
2400
2401     if (format.fmt.pix.width != width || format.fmt.pix.height != height)
2402       goto invalid_dimensions;
2403
2404     if (format.fmt.pix.pixelformat != pixelformat)
2405       goto invalid_pixelformat;
2406   }
2407
2408   /* figure out the frame layout */
2409   v4l2object->bytesperline = format.fmt.pix.bytesperline;
2410   v4l2object->sizeimage = format.fmt.pix.sizeimage;
2411
2412   GST_DEBUG_OBJECT (v4l2object->element, "Got sizeimage %u",
2413       v4l2object->sizeimage);
2414
2415   /* Is there a reason we require the caller to always specify a framerate? */
2416   GST_DEBUG_OBJECT (v4l2object->element, "Desired framerate: %u/%u", fps_n,
2417       fps_d);
2418
2419   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2420   streamparm.type = v4l2object->type;
2421
2422   if (v4l2_ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
2423     goto get_parm_failed;
2424
2425   GST_VIDEO_INFO_FPS_N (&info) =
2426       streamparm.parm.capture.timeperframe.denominator;
2427   GST_VIDEO_INFO_FPS_D (&info) = streamparm.parm.capture.timeperframe.numerator;
2428
2429   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2430     GST_DEBUG_OBJECT (v4l2object->element, "Got framerate: %u/%u",
2431         streamparm.parm.capture.timeperframe.denominator,
2432         streamparm.parm.capture.timeperframe.numerator);
2433
2434     /* We used to skip frame rate setup if the camera was already setup
2435      * with the requested frame rate. This breaks some cameras though,
2436      * causing them to not output data (several models of Thinkpad cameras
2437      * have this problem at least).
2438      * So, don't skip. */
2439     GST_LOG_OBJECT (v4l2object->element, "Setting framerate to %u/%u", fps_n,
2440         fps_d);
2441     /* We want to change the frame rate, so check whether we can. Some cheap USB
2442      * cameras don't have the capability */
2443     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
2444       GST_DEBUG_OBJECT (v4l2object->element,
2445           "Not setting framerate (not supported)");
2446       goto done;
2447     }
2448
2449     /* Note: V4L2 wants the frame interval, we have the frame rate */
2450     streamparm.parm.capture.timeperframe.numerator = fps_d;
2451     streamparm.parm.capture.timeperframe.denominator = fps_n;
2452
2453     /* some cheap USB cam's won't accept any change */
2454     if (v4l2_ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
2455       goto set_parm_failed;
2456
2457     /* get new values */
2458     fps_d = streamparm.parm.capture.timeperframe.numerator;
2459     fps_n = streamparm.parm.capture.timeperframe.denominator;
2460
2461     GST_INFO_OBJECT (v4l2object->element, "Set framerate to %u/%u", fps_n,
2462         fps_d);
2463
2464     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
2465     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
2466   }
2467
2468 done:
2469   /* if we have a framerate pre-calculate duration */
2470   if (fps_n > 0 && fps_d > 0) {
2471     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
2472   } else {
2473     v4l2object->duration = GST_CLOCK_TIME_NONE;
2474   }
2475   v4l2object->info = info;
2476   v4l2object->fmtdesc = fmtdesc;
2477
2478   /* now configure ther pools */
2479   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
2480     goto pool_failed;
2481
2482   return TRUE;
2483
2484   /* ERRORS */
2485 invalid_caps:
2486   {
2487     GST_DEBUG_OBJECT (v4l2object->element, "can't parse caps %" GST_PTR_FORMAT,
2488         caps);
2489     return FALSE;
2490   }
2491 get_fmt_failed:
2492   {
2493     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2494         (_("Device '%s' does not support video capture"),
2495             v4l2object->videodev),
2496         ("Call to G_FMT failed: (%s)", g_strerror (errno)));
2497     return FALSE;
2498   }
2499 set_fmt_failed:
2500   {
2501     if (errno == EBUSY) {
2502       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, BUSY,
2503           (_("Device '%s' is busy"), v4l2object->videodev),
2504           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2505               GST_FOURCC_ARGS (pixelformat), width, height,
2506               g_strerror (errno)));
2507     } else {
2508       GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2509           (_("Device '%s' cannot capture at %dx%d"),
2510               v4l2object->videodev, width, height),
2511           ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2512               GST_FOURCC_ARGS (pixelformat), width, height,
2513               g_strerror (errno)));
2514     }
2515     return FALSE;
2516   }
2517 invalid_dimensions:
2518   {
2519     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2520         (_("Device '%s' cannot capture at %dx%d"),
2521             v4l2object->videodev, width, height),
2522         ("Tried to capture at %dx%d, but device returned size %dx%d",
2523             width, height, format.fmt.pix.width, format.fmt.pix.height));
2524     return FALSE;
2525   }
2526 invalid_pixelformat:
2527   {
2528     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2529         (_("Device '%s' cannot capture in the specified format"),
2530             v4l2object->videodev),
2531         ("Tried to capture in %" GST_FOURCC_FORMAT
2532             ", but device returned format" " %" GST_FOURCC_FORMAT,
2533             GST_FOURCC_ARGS (pixelformat),
2534             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2535     return FALSE;
2536   }
2537 get_parm_failed:
2538   {
2539     /* it's possible that this call is not supported */
2540     if (errno != EINVAL && errno != ENOTTY) {
2541       GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2542           (_("Could not get parameters on device '%s'"),
2543               v4l2object->videodev), GST_ERROR_SYSTEM);
2544     }
2545     goto done;
2546   }
2547 set_parm_failed:
2548   {
2549     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2550         (_("Video device did not accept new frame rate setting.")),
2551         GST_ERROR_SYSTEM);
2552     goto done;
2553   }
2554 pool_failed:
2555   {
2556     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2557         (_("Video device could not create buffer pool.")), GST_ERROR_SYSTEM);
2558     return FALSE;
2559   }
2560 }
2561
2562 gboolean
2563 gst_v4l2_object_caps_equal (GstV4l2Object * v4l2object, GstCaps * caps)
2564 {
2565   GstStructure *s;
2566   GstCaps *oldcaps;
2567
2568   if (!v4l2object->pool)
2569     return FALSE;
2570
2571   s = gst_buffer_pool_get_config (GST_BUFFER_POOL_CAST (v4l2object->pool));
2572   gst_buffer_pool_config_get_params (s, &oldcaps, NULL, NULL, NULL);
2573
2574   return oldcaps && gst_caps_is_equal (caps, oldcaps);
2575 }
2576
2577 gboolean
2578 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
2579 {
2580   GST_LOG_OBJECT (v4l2object->element, "flush poll");
2581   gst_poll_set_flushing (v4l2object->poll, TRUE);
2582
2583   return TRUE;
2584 }
2585
2586 gboolean
2587 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
2588 {
2589   GST_LOG_OBJECT (v4l2object->element, "flush stop poll");
2590   gst_poll_set_flushing (v4l2object->poll, FALSE);
2591
2592   return TRUE;
2593 }
2594
2595 gboolean
2596 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
2597 {
2598   GST_DEBUG_OBJECT (v4l2object->element, "stopping");
2599
2600   if (!GST_V4L2_IS_OPEN (v4l2object))
2601     goto done;
2602   if (!GST_V4L2_IS_ACTIVE (v4l2object))
2603     goto done;
2604
2605   if (v4l2object->pool) {
2606     GST_DEBUG_OBJECT (v4l2object->element, "deactivating pool");
2607     gst_buffer_pool_set_active (GST_BUFFER_POOL_CAST (v4l2object->pool), FALSE);
2608     gst_object_unref (v4l2object->pool);
2609     v4l2object->pool = NULL;
2610   }
2611
2612   GST_V4L2_SET_INACTIVE (v4l2object);
2613
2614 done:
2615   return TRUE;
2616 }
2617
2618 gboolean
2619 gst_v4l2_object_copy (GstV4l2Object * v4l2object, GstBuffer * dest,
2620     GstBuffer * src)
2621 {
2622   const GstVideoFormatInfo *finfo = v4l2object->info.finfo;
2623
2624   if (finfo && (finfo->format != GST_VIDEO_FORMAT_UNKNOWN &&
2625           finfo->format != GST_VIDEO_FORMAT_ENCODED)) {
2626     GstVideoFrame src_frame, dest_frame;
2627
2628     GST_DEBUG_OBJECT (v4l2object->element, "copy video frame");
2629
2630     /* we have raw video, use videoframe copy to get strides right */
2631     if (!gst_video_frame_map (&src_frame, &v4l2object->info, src, GST_MAP_READ))
2632       goto invalid_buffer;
2633
2634     if (!gst_video_frame_map (&dest_frame, &v4l2object->info, dest,
2635             GST_MAP_WRITE)) {
2636       gst_video_frame_unmap (&src_frame);
2637       goto invalid_buffer;
2638     }
2639
2640     gst_video_frame_copy (&dest_frame, &src_frame);
2641
2642     gst_video_frame_unmap (&src_frame);
2643     gst_video_frame_unmap (&dest_frame);
2644   } else {
2645     GstMapInfo map;
2646
2647     GST_DEBUG_OBJECT (v4l2object->element, "copy raw bytes");
2648     gst_buffer_map (src, &map, GST_MAP_READ);
2649     gst_buffer_fill (dest, 0, map.data, gst_buffer_get_size (src));
2650     gst_buffer_unmap (src, &map);
2651     gst_buffer_resize (dest, 0, gst_buffer_get_size (src));
2652   }
2653   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, v4l2object->element,
2654       "slow copy into buffer %p", dest);
2655
2656   return TRUE;
2657
2658   /* ERRORS */
2659 invalid_buffer:
2660   {
2661     /* No Window available to put our image into */
2662     GST_WARNING_OBJECT (v4l2object->element, "could not map image");
2663     return FALSE;
2664   }
2665 }
2666
2667 GstCaps *
2668 gst_v4l2_object_get_caps (GstV4l2Object * v4l2object, GstCaps * filter)
2669 {
2670   GstCaps *ret;
2671   GSList *walk;
2672   GSList *formats;
2673
2674   if (v4l2object->probed_caps == NULL) {
2675     formats = gst_v4l2_object_get_format_list (v4l2object);
2676
2677     ret = gst_caps_new_empty ();
2678
2679     for (walk = formats; walk; walk = walk->next) {
2680       struct v4l2_fmtdesc *format;
2681       GstStructure *template;
2682
2683       format = (struct v4l2_fmtdesc *) walk->data;
2684
2685       template = gst_v4l2_object_v4l2fourcc_to_structure (format->pixelformat);
2686
2687       if (template) {
2688         GstCaps *tmp;
2689
2690         tmp = gst_v4l2_object_probe_caps_for_format (v4l2object,
2691             format->pixelformat, template);
2692         if (tmp)
2693           gst_caps_append (ret, tmp);
2694
2695         gst_structure_free (template);
2696       } else {
2697         GST_DEBUG_OBJECT (v4l2object->element, "unknown format %u",
2698             format->pixelformat);
2699       }
2700     }
2701     v4l2object->probed_caps = ret;
2702   }
2703
2704   if (filter) {
2705     ret = gst_caps_intersect_full (filter, v4l2object->probed_caps,
2706         GST_CAPS_INTERSECT_FIRST);
2707   } else {
2708     ret = gst_caps_ref (v4l2object->probed_caps);
2709   }
2710
2711   GST_INFO_OBJECT (v4l2object->element, "probed caps: %" GST_PTR_FORMAT, ret);
2712   LOG_CAPS (v4l2object->element, ret);
2713
2714   return ret;
2715 }