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