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