Merge branch 'master' into 0.11
[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 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.31
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_video_overlay_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_video_overlay_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   struct v4l2_fmtdesc *fmt;
1380
1381   /* default unknown values */
1382   fourcc = 0;
1383
1384   structure = gst_caps_get_structure (caps, 0);
1385
1386   mimetype = gst_structure_get_name (structure);
1387
1388   if (g_str_equal (mimetype, "video/x-raw")) {
1389     /* raw caps, parse into video info */
1390     if (!gst_video_info_from_caps (info, caps))
1391       goto invalid_format;
1392
1393     switch (GST_VIDEO_INFO_FORMAT (info)) {
1394       case GST_VIDEO_FORMAT_I420:
1395         fourcc = V4L2_PIX_FMT_YUV420;
1396         break;
1397       case GST_VIDEO_FORMAT_YUY2:
1398         fourcc = V4L2_PIX_FMT_YUYV;
1399         break;
1400 #if 0
1401       case GST_VIDEO_FORMAT_Y41P:
1402         fourcc = V4L2_PIX_FMT_Y41P;
1403         break;
1404 #endif
1405       case GST_VIDEO_FORMAT_UYVY:
1406         fourcc = V4L2_PIX_FMT_UYVY;
1407         break;
1408       case GST_VIDEO_FORMAT_YV12:
1409         fourcc = V4L2_PIX_FMT_YVU420;
1410         break;
1411       case GST_VIDEO_FORMAT_Y41B:
1412         fourcc = V4L2_PIX_FMT_YUV411P;
1413         break;
1414       case GST_VIDEO_FORMAT_Y42B:
1415         fourcc = V4L2_PIX_FMT_YUV422P;
1416         break;
1417       case GST_VIDEO_FORMAT_NV12:
1418         fourcc = V4L2_PIX_FMT_NV12;
1419         break;
1420       case GST_VIDEO_FORMAT_NV21:
1421         fourcc = V4L2_PIX_FMT_NV21;
1422         break;
1423 #ifdef V4L2_PIX_FMT_YVYU
1424       case GST_VIDEO_FORMAT_YVYU:
1425         fourcc = V4L2_PIX_FMT_YVYU;
1426         break;
1427 #endif
1428       case GST_VIDEO_FORMAT_RGB15:
1429         fourcc = V4L2_PIX_FMT_RGB555;
1430         break;
1431       case GST_VIDEO_FORMAT_RGB16:
1432         fourcc = V4L2_PIX_FMT_RGB565;
1433         break;
1434       case GST_VIDEO_FORMAT_RGB:
1435         fourcc = V4L2_PIX_FMT_RGB24;
1436         break;
1437       case GST_VIDEO_FORMAT_BGR:
1438         fourcc = V4L2_PIX_FMT_BGR24;
1439         break;
1440       case GST_VIDEO_FORMAT_RGBx:
1441       case GST_VIDEO_FORMAT_RGBA:
1442         fourcc = V4L2_PIX_FMT_RGB32;
1443         break;
1444       case GST_VIDEO_FORMAT_BGRx:
1445       case GST_VIDEO_FORMAT_BGRA:
1446         fourcc = V4L2_PIX_FMT_BGR32;
1447         break;
1448       case GST_VIDEO_FORMAT_GRAY8:
1449         fourcc = V4L2_PIX_FMT_GREY;
1450       default:
1451         break;
1452     }
1453   } else {
1454     gboolean dimensions = TRUE;
1455
1456     /* no video caps, construct videoinfo ourselves */
1457     gst_video_info_init (info);
1458
1459     if (g_str_equal (mimetype, "video/mpegts")) {
1460       fourcc = V4L2_PIX_FMT_MPEG;
1461       dimensions = FALSE;
1462     } else if (g_str_equal (mimetype, "video/x-dv")) {
1463       fourcc = V4L2_PIX_FMT_DV;
1464     } else if (g_str_equal (mimetype, "image/jpeg")) {
1465       fourcc = V4L2_PIX_FMT_JPEG;
1466 #ifdef V4L2_PIX_FMT_SBGGR8
1467     } else if (g_str_equal (mimetype, "video/x-raw-bayer")) {
1468       fourcc = V4L2_PIX_FMT_SBGGR8;
1469 #endif
1470 #ifdef V4L2_PIX_FMT_SN9C10X
1471     } else if (g_str_equal (mimetype, "video/x-sonix")) {
1472       fourcc = V4L2_PIX_FMT_SN9C10X;
1473 #endif
1474 #ifdef V4L2_PIX_FMT_PWC1
1475     } else if (g_str_equal (mimetype, "video/x-pwc1")) {
1476       fourcc = V4L2_PIX_FMT_PWC1;
1477 #endif
1478 #ifdef V4L2_PIX_FMT_PWC2
1479     } else if (g_str_equal (mimetype, "video/x-pwc2")) {
1480       fourcc = V4L2_PIX_FMT_PWC2;
1481     }
1482 #endif
1483
1484     if (dimensions) {
1485       gboolean interlaced;
1486
1487       if (!gst_structure_get_int (structure, "width", &info->width))
1488         goto no_width;
1489
1490       if (!gst_structure_get_int (structure, "height", &info->height))
1491         goto no_height;
1492
1493       if (!gst_structure_get_boolean (structure, "interlaced", &interlaced))
1494         interlaced = FALSE;
1495       if (interlaced)
1496         info->flags |= GST_VIDEO_FLAG_INTERLACED;
1497
1498       if (!gst_structure_get_fraction (structure, "framerate", &info->fps_n,
1499               &info->fps_d))
1500         goto no_framerate;
1501     }
1502   }
1503
1504   if (fourcc == 0)
1505     goto unhandled_format;
1506
1507   fmt = gst_v4l2_object_get_format_from_fourcc (v4l2object, fourcc);
1508   if (fmt == NULL)
1509     goto unsupported_format;
1510
1511   *format = fmt;
1512
1513   return TRUE;
1514
1515   /* ERRORS */
1516 no_width:
1517   {
1518     GST_DEBUG_OBJECT (v4l2object, "no width");
1519     return FALSE;
1520   }
1521 no_height:
1522   {
1523     GST_DEBUG_OBJECT (v4l2object, "no height");
1524     return FALSE;
1525   }
1526 no_framerate:
1527   {
1528     GST_DEBUG_OBJECT (v4l2object, "no framerate");
1529     return FALSE;
1530   }
1531 invalid_format:
1532   {
1533     GST_DEBUG_OBJECT (v4l2object, "invalid format");
1534     return FALSE;
1535   }
1536 unhandled_format:
1537   {
1538     GST_DEBUG_OBJECT (v4l2object, "unhandled format");
1539     return FALSE;
1540   }
1541 unsupported_format:
1542   {
1543     GST_DEBUG_OBJECT (v4l2object, "unsupported format");
1544     return FALSE;
1545   }
1546 }
1547
1548
1549 static gboolean
1550 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
1551     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced);
1552
1553
1554 /* The frame interval enumeration code first appeared in Linux 2.6.19. */
1555 #ifdef VIDIOC_ENUM_FRAMEINTERVALS
1556 static GstStructure *
1557 gst_v4l2_object_probe_caps_for_format_and_size (GstV4l2Object * v4l2object,
1558     guint32 pixelformat,
1559     guint32 width, guint32 height, const GstStructure * template)
1560 {
1561   gint fd = v4l2object->video_fd;
1562   struct v4l2_frmivalenum ival;
1563   guint32 num, denom;
1564   GstStructure *s;
1565   GValue rates = { 0, };
1566   gboolean interlaced;
1567   gint int_width = width;
1568   gint int_height = height;
1569
1570   /* interlaced detection using VIDIOC_TRY/S_FMT */
1571   if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat,
1572           &int_width, &int_height, &interlaced))
1573     return NULL;
1574
1575   memset (&ival, 0, sizeof (struct v4l2_frmivalenum));
1576   ival.index = 0;
1577   ival.pixel_format = pixelformat;
1578   ival.width = width;
1579   ival.height = height;
1580
1581   GST_LOG_OBJECT (v4l2object->element,
1582       "get frame interval for %ux%u, %" GST_FOURCC_FORMAT, width, height,
1583       GST_FOURCC_ARGS (pixelformat));
1584
1585   /* keep in mind that v4l2 gives us frame intervals (durations); we invert the
1586    * fraction to get framerate */
1587   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) < 0)
1588     goto enum_frameintervals_failed;
1589
1590   if (ival.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
1591     GValue rate = { 0, };
1592
1593     g_value_init (&rates, GST_TYPE_LIST);
1594     g_value_init (&rate, GST_TYPE_FRACTION);
1595
1596     do {
1597       num = ival.discrete.numerator;
1598       denom = ival.discrete.denominator;
1599
1600       if (num > G_MAXINT || denom > G_MAXINT) {
1601         /* let us hope we don't get here... */
1602         num >>= 1;
1603         denom >>= 1;
1604       }
1605
1606       GST_LOG_OBJECT (v4l2object->element, "adding discrete framerate: %d/%d",
1607           denom, num);
1608
1609       /* swap to get the framerate */
1610       gst_value_set_fraction (&rate, denom, num);
1611       gst_value_list_append_value (&rates, &rate);
1612
1613       ival.index++;
1614     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival) >= 0);
1615   } else if (ival.type == V4L2_FRMIVAL_TYPE_STEPWISE) {
1616     GValue min = { 0, };
1617     GValue step = { 0, };
1618     GValue max = { 0, };
1619     gboolean added = FALSE;
1620     guint32 minnum, mindenom;
1621     guint32 maxnum, maxdenom;
1622
1623     g_value_init (&rates, GST_TYPE_LIST);
1624
1625     g_value_init (&min, GST_TYPE_FRACTION);
1626     g_value_init (&step, GST_TYPE_FRACTION);
1627     g_value_init (&max, GST_TYPE_FRACTION);
1628
1629     /* get the min */
1630     minnum = ival.stepwise.min.numerator;
1631     mindenom = ival.stepwise.min.denominator;
1632     if (minnum > G_MAXINT || mindenom > G_MAXINT) {
1633       minnum >>= 1;
1634       mindenom >>= 1;
1635     }
1636     GST_LOG_OBJECT (v4l2object->element, "stepwise min frame interval: %d/%d",
1637         minnum, mindenom);
1638     gst_value_set_fraction (&min, minnum, mindenom);
1639
1640     /* get the max */
1641     maxnum = ival.stepwise.max.numerator;
1642     maxdenom = ival.stepwise.max.denominator;
1643     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1644       maxnum >>= 1;
1645       maxdenom >>= 1;
1646     }
1647
1648     GST_LOG_OBJECT (v4l2object->element, "stepwise max frame interval: %d/%d",
1649         maxnum, maxdenom);
1650     gst_value_set_fraction (&max, maxnum, maxdenom);
1651
1652     /* get the step */
1653     num = ival.stepwise.step.numerator;
1654     denom = ival.stepwise.step.denominator;
1655     if (num > G_MAXINT || denom > G_MAXINT) {
1656       num >>= 1;
1657       denom >>= 1;
1658     }
1659
1660     if (num == 0 || denom == 0) {
1661       /* in this case we have a wrong fraction or no step, set the step to max
1662        * so that we only add the min value in the loop below */
1663       num = maxnum;
1664       denom = maxdenom;
1665     }
1666
1667     /* since we only have gst_value_fraction_subtract and not add, negate the
1668      * numerator */
1669     GST_LOG_OBJECT (v4l2object->element, "stepwise step frame interval: %d/%d",
1670         num, denom);
1671     gst_value_set_fraction (&step, -num, denom);
1672
1673     while (gst_value_compare (&min, &max) <= 0) {
1674       GValue rate = { 0, };
1675
1676       num = gst_value_get_fraction_numerator (&min);
1677       denom = gst_value_get_fraction_denominator (&min);
1678       GST_LOG_OBJECT (v4l2object->element, "adding stepwise framerate: %d/%d",
1679           denom, num);
1680
1681       /* invert to get the framerate */
1682       g_value_init (&rate, GST_TYPE_FRACTION);
1683       gst_value_set_fraction (&rate, denom, num);
1684       gst_value_list_append_value (&rates, &rate);
1685       added = TRUE;
1686
1687       /* we're actually adding because step was negated above. This is because
1688        * there is no _add function... */
1689       if (!gst_value_fraction_subtract (&min, &min, &step)) {
1690         GST_WARNING_OBJECT (v4l2object->element, "could not step fraction!");
1691         break;
1692       }
1693     }
1694     if (!added) {
1695       /* no range was added, leave the default range from the template */
1696       GST_WARNING_OBJECT (v4l2object->element,
1697           "no range added, leaving default");
1698       g_value_unset (&rates);
1699     }
1700   } else if (ival.type == V4L2_FRMIVAL_TYPE_CONTINUOUS) {
1701     guint32 maxnum, maxdenom;
1702
1703     g_value_init (&rates, GST_TYPE_FRACTION_RANGE);
1704
1705     num = ival.stepwise.min.numerator;
1706     denom = ival.stepwise.min.denominator;
1707     if (num > G_MAXINT || denom > G_MAXINT) {
1708       num >>= 1;
1709       denom >>= 1;
1710     }
1711
1712     maxnum = ival.stepwise.max.numerator;
1713     maxdenom = ival.stepwise.max.denominator;
1714     if (maxnum > G_MAXINT || maxdenom > G_MAXINT) {
1715       maxnum >>= 1;
1716       maxdenom >>= 1;
1717     }
1718
1719     GST_LOG_OBJECT (v4l2object->element,
1720         "continuous frame interval %d/%d to %d/%d", maxdenom, maxnum, denom,
1721         num);
1722
1723     gst_value_set_fraction_range_full (&rates, maxdenom, maxnum, denom, num);
1724   } else {
1725     goto unknown_type;
1726   }
1727
1728 return_data:
1729   s = gst_structure_copy (template);
1730   gst_structure_set (s, "width", G_TYPE_INT, (gint) width,
1731       "height", G_TYPE_INT, (gint) height,
1732       "interlaced", G_TYPE_BOOLEAN, interlaced, NULL);
1733
1734   if (G_IS_VALUE (&rates)) {
1735     /* only change the framerate on the template when we have a valid probed new
1736      * value */
1737     gst_structure_set_value (s, "framerate", &rates);
1738     g_value_unset (&rates);
1739   } else {
1740     gst_structure_set (s, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 100, 1,
1741         NULL);
1742   }
1743   return s;
1744
1745   /* ERRORS */
1746 enum_frameintervals_failed:
1747   {
1748     GST_DEBUG_OBJECT (v4l2object->element,
1749         "Unable to enumerate intervals for %" GST_FOURCC_FORMAT "@%ux%u",
1750         GST_FOURCC_ARGS (pixelformat), width, height);
1751     goto return_data;
1752   }
1753 unknown_type:
1754   {
1755     /* I don't see how this is actually an error, we ignore the format then */
1756     GST_WARNING_OBJECT (v4l2object->element,
1757         "Unknown frame interval type at %" GST_FOURCC_FORMAT "@%ux%u: %u",
1758         GST_FOURCC_ARGS (pixelformat), width, height, ival.type);
1759     return NULL;
1760   }
1761 }
1762 #endif /* defined VIDIOC_ENUM_FRAMEINTERVALS */
1763
1764 #ifdef VIDIOC_ENUM_FRAMESIZES
1765 static gint
1766 sort_by_frame_size (GstStructure * s1, GstStructure * s2)
1767 {
1768   int w1, h1, w2, h2;
1769
1770   gst_structure_get_int (s1, "width", &w1);
1771   gst_structure_get_int (s1, "height", &h1);
1772   gst_structure_get_int (s2, "width", &w2);
1773   gst_structure_get_int (s2, "height", &h2);
1774
1775   /* I think it's safe to assume that this won't overflow for a while */
1776   return ((w2 * h2) - (w1 * h1));
1777 }
1778 #endif
1779
1780 GstCaps *
1781 gst_v4l2_object_probe_caps_for_format (GstV4l2Object * v4l2object,
1782     guint32 pixelformat, const GstStructure * template)
1783 {
1784   GstCaps *ret = gst_caps_new_empty ();
1785   GstStructure *tmp;
1786
1787 #ifdef VIDIOC_ENUM_FRAMESIZES
1788   gint fd = v4l2object->video_fd;
1789   struct v4l2_frmsizeenum size;
1790   GList *results = NULL;
1791   guint32 w, h;
1792
1793   if (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G'))
1794     return gst_caps_new_simple ("video/mpegts", NULL);
1795
1796   memset (&size, 0, sizeof (struct v4l2_frmsizeenum));
1797   size.index = 0;
1798   size.pixel_format = pixelformat;
1799
1800   GST_DEBUG_OBJECT (v4l2object->element, "Enumerating frame sizes");
1801
1802   if (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) < 0)
1803     goto enum_framesizes_failed;
1804
1805   if (size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
1806     do {
1807       GST_LOG_OBJECT (v4l2object->element, "got discrete frame size %dx%d",
1808           size.discrete.width, size.discrete.height);
1809
1810       w = MIN (size.discrete.width, G_MAXINT);
1811       h = MIN (size.discrete.height, G_MAXINT);
1812
1813       if (w && h) {
1814         tmp =
1815             gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1816             pixelformat, w, h, template);
1817
1818         if (tmp)
1819           results = g_list_prepend (results, tmp);
1820       }
1821
1822       size.index++;
1823     } while (v4l2_ioctl (fd, VIDIOC_ENUM_FRAMESIZES, &size) >= 0);
1824     GST_DEBUG_OBJECT (v4l2object->element,
1825         "done iterating discrete frame sizes");
1826   } else if (size.type == V4L2_FRMSIZE_TYPE_STEPWISE) {
1827     GST_DEBUG_OBJECT (v4l2object->element, "we have stepwise frame sizes:");
1828     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1829         size.stepwise.min_width);
1830     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1831         size.stepwise.min_height);
1832     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1833         size.stepwise.max_width);
1834     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1835         size.stepwise.max_height);
1836     GST_DEBUG_OBJECT (v4l2object->element, "step width:  %d",
1837         size.stepwise.step_width);
1838     GST_DEBUG_OBJECT (v4l2object->element, "step height: %d",
1839         size.stepwise.step_height);
1840
1841     for (w = size.stepwise.min_width, h = size.stepwise.min_height;
1842         w < size.stepwise.max_width && h < size.stepwise.max_height;
1843         w += size.stepwise.step_width, h += size.stepwise.step_height) {
1844       if (w == 0 || h == 0)
1845         continue;
1846
1847       tmp =
1848           gst_v4l2_object_probe_caps_for_format_and_size (v4l2object,
1849           pixelformat, w, h, template);
1850
1851       if (tmp)
1852         results = g_list_prepend (results, tmp);
1853     }
1854     GST_DEBUG_OBJECT (v4l2object->element,
1855         "done iterating stepwise frame sizes");
1856   } else if (size.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) {
1857     guint32 maxw, maxh;
1858
1859     GST_DEBUG_OBJECT (v4l2object->element, "we have continuous frame sizes:");
1860     GST_DEBUG_OBJECT (v4l2object->element, "min width:   %d",
1861         size.stepwise.min_width);
1862     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1863         size.stepwise.min_height);
1864     GST_DEBUG_OBJECT (v4l2object->element, "max width:   %d",
1865         size.stepwise.max_width);
1866     GST_DEBUG_OBJECT (v4l2object->element, "min height:  %d",
1867         size.stepwise.max_height);
1868
1869     w = MAX (size.stepwise.min_width, 1);
1870     h = MAX (size.stepwise.min_height, 1);
1871     maxw = MIN (size.stepwise.max_width, G_MAXINT);
1872     maxh = MIN (size.stepwise.max_height, G_MAXINT);
1873
1874     tmp =
1875         gst_v4l2_object_probe_caps_for_format_and_size (v4l2object, pixelformat,
1876         w, h, template);
1877     if (tmp) {
1878       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, (gint) w,
1879           (gint) maxw, "height", GST_TYPE_INT_RANGE, (gint) h, (gint) maxh,
1880           NULL);
1881
1882       /* no point using the results list here, since there's only one struct */
1883       gst_caps_append_structure (ret, tmp);
1884     }
1885   } else {
1886     goto unknown_type;
1887   }
1888
1889   /* we use an intermediary list to store and then sort the results of the
1890    * probing because we can't make any assumptions about the order in which
1891    * the driver will give us the sizes, but we want the final caps to contain
1892    * the results starting with the highest resolution and having the lowest
1893    * resolution last, since order in caps matters for things like fixation. */
1894   results = g_list_sort (results, (GCompareFunc) sort_by_frame_size);
1895   while (results != NULL) {
1896     gst_caps_append_structure (ret, GST_STRUCTURE (results->data));
1897     results = g_list_delete_link (results, results);
1898   }
1899
1900   if (gst_caps_is_empty (ret))
1901     goto enum_framesizes_no_results;
1902
1903   return ret;
1904
1905   /* ERRORS */
1906 enum_framesizes_failed:
1907   {
1908     /* I don't see how this is actually an error */
1909     GST_DEBUG_OBJECT (v4l2object->element,
1910         "Failed to enumerate frame sizes for pixelformat %" GST_FOURCC_FORMAT
1911         " (%s)", GST_FOURCC_ARGS (pixelformat), g_strerror (errno));
1912     goto default_frame_sizes;
1913   }
1914 enum_framesizes_no_results:
1915   {
1916     /* it's possible that VIDIOC_ENUM_FRAMESIZES is defined but the driver in
1917      * question doesn't actually support it yet */
1918     GST_DEBUG_OBJECT (v4l2object->element,
1919         "No results for pixelformat %" GST_FOURCC_FORMAT
1920         " enumerating frame sizes, trying fallback",
1921         GST_FOURCC_ARGS (pixelformat));
1922     goto default_frame_sizes;
1923   }
1924 unknown_type:
1925   {
1926     GST_WARNING_OBJECT (v4l2object->element,
1927         "Unknown frame sizeenum type for pixelformat %" GST_FOURCC_FORMAT
1928         ": %u", GST_FOURCC_ARGS (pixelformat), size.type);
1929     goto default_frame_sizes;
1930   }
1931 default_frame_sizes:
1932 #endif /* defined VIDIOC_ENUM_FRAMESIZES */
1933   {
1934     gint min_w, max_w, min_h, max_h, fix_num = 0, fix_denom = 0;
1935     gboolean interlaced;
1936
1937     /* This code is for Linux < 2.6.19 */
1938     min_w = min_h = 1;
1939     max_w = max_h = GST_V4L2_MAX_SIZE;
1940     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &min_w,
1941             &min_h, &interlaced)) {
1942       GST_WARNING_OBJECT (v4l2object->element,
1943           "Could not probe minimum capture size for pixelformat %"
1944           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
1945     }
1946     if (!gst_v4l2_object_get_nearest_size (v4l2object, pixelformat, &max_w,
1947             &max_h, &interlaced)) {
1948       GST_WARNING_OBJECT (v4l2object->element,
1949           "Could not probe maximum capture size for pixelformat %"
1950           GST_FOURCC_FORMAT, GST_FOURCC_ARGS (pixelformat));
1951     }
1952
1953     /* Since we can't get framerate directly, try to use the current norm */
1954     if (v4l2object->tv_norm && v4l2object->norms) {
1955       GList *norms;
1956       GstTunerNorm *norm = NULL;
1957       GstTunerNorm *current =
1958           gst_v4l2_tuner_get_norm_by_std_id (v4l2object, v4l2object->tv_norm);
1959
1960       for (norms = v4l2object->norms; norms != NULL; norms = norms->next) {
1961         norm = (GstTunerNorm *) norms->data;
1962         if (!strcmp (norm->label, current->label))
1963           break;
1964       }
1965       /* If it's possible, set framerate to that (discrete) value */
1966       if (norm) {
1967         fix_num = gst_value_get_fraction_numerator (&norm->framerate);
1968         fix_denom = gst_value_get_fraction_denominator (&norm->framerate);
1969       }
1970     }
1971
1972     tmp = gst_structure_copy (template);
1973     if (fix_num) {
1974       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION, fix_num,
1975           fix_denom, NULL);
1976     } else {
1977       /* if norm can't be used, copy the template framerate */
1978       gst_structure_set (tmp, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
1979           100, 1, NULL);
1980     }
1981
1982     if (min_w == max_w)
1983       gst_structure_set (tmp, "width", G_TYPE_INT, max_w, NULL);
1984     else
1985       gst_structure_set (tmp, "width", GST_TYPE_INT_RANGE, min_w, max_w, NULL);
1986
1987     if (min_h == max_h)
1988       gst_structure_set (tmp, "height", G_TYPE_INT, max_h, NULL);
1989     else
1990       gst_structure_set (tmp, "height", GST_TYPE_INT_RANGE, min_h, max_h, NULL);
1991
1992     gst_structure_set (tmp, "interlaced", G_TYPE_BOOLEAN, interlaced, NULL);
1993
1994     gst_caps_append_structure (ret, tmp);
1995
1996     return ret;
1997   }
1998 }
1999
2000 static gboolean
2001 gst_v4l2_object_get_nearest_size (GstV4l2Object * v4l2object,
2002     guint32 pixelformat, gint * width, gint * height, gboolean * interlaced)
2003 {
2004   struct v4l2_format fmt, prevfmt;
2005   int fd;
2006   int r;
2007   int prevfmt_valid;
2008
2009   g_return_val_if_fail (width != NULL, FALSE);
2010   g_return_val_if_fail (height != NULL, FALSE);
2011
2012   GST_LOG_OBJECT (v4l2object->element,
2013       "getting nearest size to %dx%d with format %" GST_FOURCC_FORMAT,
2014       *width, *height, GST_FOURCC_ARGS (pixelformat));
2015
2016   fd = v4l2object->video_fd;
2017
2018   /* Some drivers are buggy and will modify the currently set format
2019      when processing VIDIOC_TRY_FMT, so we remember what is set at the
2020      minute, and will reset it when done. */
2021   prevfmt_valid = (v4l2_ioctl (fd, VIDIOC_G_FMT, &prevfmt) >= 0);
2022
2023   /* get size delimiters */
2024   memset (&fmt, 0, sizeof (fmt));
2025   fmt.type = v4l2object->type;
2026   fmt.fmt.pix.width = *width;
2027   fmt.fmt.pix.height = *height;
2028   fmt.fmt.pix.pixelformat = pixelformat;
2029   fmt.fmt.pix.field = V4L2_FIELD_NONE;
2030
2031   r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2032   if (r < 0 && errno == EINVAL) {
2033     /* try again with interlaced video */
2034     fmt.fmt.pix.width = *width;
2035     fmt.fmt.pix.height = *height;
2036     fmt.fmt.pix.pixelformat = pixelformat;
2037     fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
2038     r = v4l2_ioctl (fd, VIDIOC_TRY_FMT, &fmt);
2039   }
2040
2041   if (r < 0) {
2042     /* The driver might not implement TRY_FMT, in which case we will try
2043        S_FMT to probe */
2044     if (errno != ENOTTY)
2045       goto error;
2046
2047     /* Only try S_FMT if we're not actively capturing yet, which we shouldn't
2048        be, because we're still probing */
2049     if (GST_V4L2_IS_ACTIVE (v4l2object))
2050       goto error;
2051
2052     GST_LOG_OBJECT (v4l2object->element,
2053         "Failed to probe size limit with VIDIOC_TRY_FMT, trying VIDIOC_S_FMT");
2054
2055     fmt.fmt.pix.width = *width;
2056     fmt.fmt.pix.height = *height;
2057
2058     r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2059     if (r < 0 && errno == EINVAL) {
2060       /* try again with progressive video */
2061       fmt.fmt.pix.width = *width;
2062       fmt.fmt.pix.height = *height;
2063       fmt.fmt.pix.pixelformat = pixelformat;
2064       fmt.fmt.pix.field = V4L2_FIELD_NONE;
2065       r = v4l2_ioctl (fd, VIDIOC_S_FMT, &fmt);
2066     }
2067
2068     if (r < 0)
2069       goto error;
2070   }
2071
2072   GST_LOG_OBJECT (v4l2object->element,
2073       "got nearest size %dx%d", fmt.fmt.pix.width, fmt.fmt.pix.height);
2074
2075   *width = fmt.fmt.pix.width;
2076   *height = fmt.fmt.pix.height;
2077
2078   switch (fmt.fmt.pix.field) {
2079     case V4L2_FIELD_ANY:
2080     case V4L2_FIELD_NONE:
2081       *interlaced = FALSE;
2082       break;
2083     case V4L2_FIELD_INTERLACED:
2084     case V4L2_FIELD_INTERLACED_TB:
2085     case V4L2_FIELD_INTERLACED_BT:
2086       *interlaced = TRUE;
2087       break;
2088     default:
2089       GST_WARNING_OBJECT (v4l2object->element,
2090           "Unsupported field type for %" GST_FOURCC_FORMAT "@%ux%u",
2091           GST_FOURCC_ARGS (pixelformat), *width, *height);
2092       goto error;
2093   }
2094
2095   if (prevfmt_valid)
2096     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2097   return TRUE;
2098
2099 error:
2100   if (prevfmt_valid)
2101     v4l2_ioctl (fd, VIDIOC_S_FMT, &prevfmt);
2102   return FALSE;
2103 }
2104
2105 static gboolean
2106 gst_v4l2_object_setup_pool (GstV4l2Object * v4l2object, GstCaps * caps)
2107 {
2108   GstV4l2IOMode mode;
2109
2110   GST_DEBUG_OBJECT (v4l2object->element, "initializing the capture system");
2111
2112   GST_V4L2_CHECK_OPEN (v4l2object);
2113   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2114
2115   /* find transport */
2116   mode = v4l2object->req_mode;
2117
2118   if (v4l2object->vcap.capabilities & V4L2_CAP_READWRITE) {
2119     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2120       mode = GST_V4L2_IO_RW;
2121   } else if (v4l2object->req_mode == GST_V4L2_IO_RW)
2122     goto method_not_supported;
2123
2124   if (v4l2object->vcap.capabilities & V4L2_CAP_STREAMING) {
2125     if (v4l2object->req_mode == GST_V4L2_IO_AUTO)
2126       mode = GST_V4L2_IO_MMAP;
2127   } else if (v4l2object->req_mode == GST_V4L2_IO_MMAP)
2128     goto method_not_supported;
2129
2130   /* if still no transport selected, error out */
2131   if (mode == GST_V4L2_IO_AUTO)
2132     goto no_supported_capture_method;
2133
2134   GST_INFO_OBJECT (v4l2object->element, "accessing buffers via mode %d", mode);
2135   v4l2object->mode = mode;
2136
2137   /* Map the buffers */
2138   GST_LOG_OBJECT (v4l2object->element, "initiating buffer pool");
2139
2140   if (!(v4l2object->pool = gst_v4l2_buffer_pool_new (v4l2object, caps)))
2141     goto buffer_pool_new_failed;
2142
2143   GST_V4L2_SET_ACTIVE (v4l2object);
2144
2145   return TRUE;
2146
2147   /* ERRORS */
2148 buffer_pool_new_failed:
2149   {
2150     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2151         (_("Could not map buffers from device '%s'"),
2152             v4l2object->videodev),
2153         ("Failed to create buffer pool: %s", g_strerror (errno)));
2154     return FALSE;
2155   }
2156 method_not_supported:
2157   {
2158     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2159         (_("The driver of device '%s' does not support the IO method %d"),
2160             v4l2object->videodev, mode), (NULL));
2161     return FALSE;
2162   }
2163 no_supported_capture_method:
2164   {
2165     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, READ,
2166         (_("The driver of device '%s' does not support any known IO "
2167                 "method."), v4l2object->videodev), (NULL));
2168     return FALSE;
2169   }
2170 }
2171
2172
2173 /* Note about fraction simplification
2174  *  * n1/d1 == n2/d2  is also written as  n1 == ( n2 * d1 ) / d2
2175  *   */
2176 #define fractions_are_equal(n1,d1,n2,d2) ((n1) == gst_util_uint64_scale_int((n2), (d1), (d2)))
2177
2178 gboolean
2179 gst_v4l2_object_set_format (GstV4l2Object * v4l2object, GstCaps * caps)
2180 {
2181   gint fd = v4l2object->video_fd;
2182   struct v4l2_format format;
2183   struct v4l2_streamparm streamparm;
2184   enum v4l2_field field;
2185   guint32 pixelformat;
2186   struct v4l2_fmtdesc *fmtdesc;
2187   GstVideoInfo info;
2188   gint width, height, fps_n, fps_d, stride;
2189
2190   if (!gst_v4l2_object_get_caps_info (v4l2object, caps, &fmtdesc, &info))
2191     goto invalid_caps;
2192
2193   pixelformat = fmtdesc->pixelformat;
2194   width = GST_VIDEO_INFO_WIDTH (&info);
2195   height = GST_VIDEO_INFO_HEIGHT (&info);
2196   fps_n = GST_VIDEO_INFO_FPS_N (&info);
2197   fps_d = GST_VIDEO_INFO_FPS_D (&info);
2198   stride = GST_VIDEO_INFO_PLANE_STRIDE (&info, 0);
2199
2200   if (info.flags & GST_VIDEO_FLAG_INTERLACED) {
2201     GST_DEBUG_OBJECT (v4l2object->element, "interlaced video");
2202     /* ideally we would differentiate between types of interlaced video
2203      * but there is not sufficient information in the caps..
2204      */
2205     field = V4L2_FIELD_INTERLACED;
2206   } else {
2207     GST_DEBUG_OBJECT (v4l2object->element, "progressive video");
2208     field = V4L2_FIELD_NONE;
2209   }
2210
2211   GST_DEBUG_OBJECT (v4l2object->element, "Desired format %dx%d, format "
2212       "%" GST_FOURCC_FORMAT " stride: %d", width, height,
2213       GST_FOURCC_ARGS (pixelformat), stride);
2214
2215   GST_V4L2_CHECK_OPEN (v4l2object);
2216   GST_V4L2_CHECK_NOT_ACTIVE (v4l2object);
2217
2218   /* Only unconditionally accept mpegts for sources */
2219   if ((v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
2220       (pixelformat == GST_MAKE_FOURCC ('M', 'P', 'E', 'G')))
2221     goto done;
2222
2223   memset (&format, 0x00, sizeof (struct v4l2_format));
2224   format.type = v4l2object->type;
2225
2226   if (v4l2_ioctl (fd, VIDIOC_G_FMT, &format) < 0)
2227     goto get_fmt_failed;
2228
2229   GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2230       "%" GST_FOURCC_FORMAT " bytesperline %d, colorspace %d",
2231       format.fmt.pix.width, format.fmt.pix.height,
2232       GST_FOURCC_ARGS (format.fmt.pix.pixelformat), format.fmt.pix.bytesperline,
2233       format.fmt.pix.colorspace);
2234
2235   if (format.type != v4l2object->type ||
2236       format.fmt.pix.width != width ||
2237       format.fmt.pix.height != height ||
2238       format.fmt.pix.pixelformat != pixelformat ||
2239       format.fmt.pix.field != field || format.fmt.pix.bytesperline != stride) {
2240     /* something different, set the format */
2241     GST_DEBUG_OBJECT (v4l2object->element, "Setting format to %dx%d, format "
2242         "%" GST_FOURCC_FORMAT " bytesperline %d", width, height,
2243         GST_FOURCC_ARGS (pixelformat), stride);
2244
2245     format.type = v4l2object->type;
2246     format.fmt.pix.width = width;
2247     format.fmt.pix.height = height;
2248     format.fmt.pix.pixelformat = pixelformat;
2249     format.fmt.pix.field = field;
2250     /* try to ask our prefered stride */
2251     format.fmt.pix.bytesperline = stride;
2252
2253     if (v4l2_ioctl (fd, VIDIOC_S_FMT, &format) < 0)
2254       goto set_fmt_failed;
2255
2256     GST_DEBUG_OBJECT (v4l2object->element, "Got format to %dx%d, format "
2257         "%" GST_FOURCC_FORMAT " stride %d", format.fmt.pix.width,
2258         format.fmt.pix.height, GST_FOURCC_ARGS (format.fmt.pix.pixelformat),
2259         format.fmt.pix.bytesperline);
2260
2261     if (format.fmt.pix.width != width || format.fmt.pix.height != height)
2262       goto invalid_dimensions;
2263
2264     if (format.fmt.pix.pixelformat != pixelformat)
2265       goto invalid_pixelformat;
2266   }
2267
2268   /* figure out the frame layout */
2269   v4l2object->bytesperline = format.fmt.pix.bytesperline;
2270   v4l2object->sizeimage = format.fmt.pix.sizeimage;
2271
2272   GST_DEBUG_OBJECT (v4l2object->element, "Got sizeimage %u",
2273       v4l2object->sizeimage);
2274
2275   /* Is there a reason we require the caller to always specify a framerate? */
2276   GST_DEBUG_OBJECT (v4l2object->element, "Desired framerate: %u/%u", fps_n,
2277       fps_d);
2278
2279   memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
2280   streamparm.type = v4l2object->type;
2281
2282   if (v4l2_ioctl (fd, VIDIOC_G_PARM, &streamparm) < 0)
2283     goto get_parm_failed;
2284
2285   GST_VIDEO_INFO_FPS_N (&info) =
2286       streamparm.parm.capture.timeperframe.denominator;
2287   GST_VIDEO_INFO_FPS_D (&info) = streamparm.parm.capture.timeperframe.numerator;
2288
2289   if (v4l2object->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
2290     GST_DEBUG_OBJECT (v4l2object->element, "Got framerate: %u/%u",
2291         streamparm.parm.capture.timeperframe.denominator,
2292         streamparm.parm.capture.timeperframe.numerator);
2293
2294     /* We used to skip frame rate setup if the camera was already setup
2295      * with the requested frame rate. This breaks some cameras though,
2296      * causing them to not output data (several models of Thinkpad cameras
2297      * have this problem at least).
2298      * So, don't skip. */
2299     GST_LOG_OBJECT (v4l2object->element, "Setting framerate to %u/%u", fps_n,
2300         fps_d);
2301     /* We want to change the frame rate, so check whether we can. Some cheap USB
2302      * cameras don't have the capability */
2303     if ((streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) == 0) {
2304       GST_DEBUG_OBJECT (v4l2object->element,
2305           "Not setting framerate (not supported)");
2306       goto done;
2307     }
2308
2309     /* Note: V4L2 wants the frame interval, we have the frame rate */
2310     streamparm.parm.capture.timeperframe.numerator = fps_d;
2311     streamparm.parm.capture.timeperframe.denominator = fps_n;
2312
2313     /* some cheap USB cam's won't accept any change */
2314     if (v4l2_ioctl (fd, VIDIOC_S_PARM, &streamparm) < 0)
2315       goto set_parm_failed;
2316
2317     /* get new values */
2318     fps_d = streamparm.parm.capture.timeperframe.numerator;
2319     fps_n = streamparm.parm.capture.timeperframe.denominator;
2320
2321     GST_INFO_OBJECT (v4l2object->element, "Set framerate to %u/%u", fps_n,
2322         fps_d);
2323
2324     GST_VIDEO_INFO_FPS_N (&info) = fps_n;
2325     GST_VIDEO_INFO_FPS_D (&info) = fps_d;
2326   }
2327
2328 done:
2329   /* if we have a framerate pre-calculate duration */
2330   if (fps_n > 0 && fps_d > 0) {
2331     v4l2object->duration = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
2332   } else {
2333     v4l2object->duration = GST_CLOCK_TIME_NONE;
2334   }
2335   v4l2object->info = info;
2336   v4l2object->fmtdesc = fmtdesc;
2337
2338   /* now configure ther pools */
2339   if (!gst_v4l2_object_setup_pool (v4l2object, caps))
2340     goto pool_failed;
2341
2342   return TRUE;
2343
2344   /* ERRORS */
2345 invalid_caps:
2346   {
2347     GST_DEBUG_OBJECT (v4l2object->element, "can't parse caps %" GST_PTR_FORMAT,
2348         caps);
2349     return FALSE;
2350   }
2351 get_fmt_failed:
2352   {
2353     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2354         (_("Device '%s' does not support video capture"),
2355             v4l2object->videodev),
2356         ("Call to G_FMT failed: (%s)", g_strerror (errno)));
2357     return FALSE;
2358   }
2359 set_fmt_failed:
2360   {
2361     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2362         (_("Device '%s' cannot capture at %dx%d"),
2363             v4l2object->videodev, width, height),
2364         ("Call to S_FMT failed for %" GST_FOURCC_FORMAT " @ %dx%d: %s",
2365             GST_FOURCC_ARGS (pixelformat), width, height, g_strerror (errno)));
2366     return FALSE;
2367   }
2368 invalid_dimensions:
2369   {
2370     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2371         (_("Device '%s' cannot capture at %dx%d"),
2372             v4l2object->videodev, width, height),
2373         ("Tried to capture at %dx%d, but device returned size %dx%d",
2374             width, height, format.fmt.pix.width, format.fmt.pix.height));
2375     return FALSE;
2376   }
2377 invalid_pixelformat:
2378   {
2379     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2380         (_("Device '%s' cannot capture in the specified format"),
2381             v4l2object->videodev),
2382         ("Tried to capture in %" GST_FOURCC_FORMAT
2383             ", but device returned format" " %" GST_FOURCC_FORMAT,
2384             GST_FOURCC_ARGS (pixelformat),
2385             GST_FOURCC_ARGS (format.fmt.pix.pixelformat)));
2386     return FALSE;
2387   }
2388 get_parm_failed:
2389   {
2390     /* it's possible that this call is not supported */
2391     if (errno != EINVAL) {
2392       GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2393           (_("Could not get parameters on device '%s'"),
2394               v4l2object->videodev), GST_ERROR_SYSTEM);
2395     }
2396     goto done;
2397   }
2398 set_parm_failed:
2399   {
2400     GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, SETTINGS,
2401         (_("Video device did not accept new frame rate setting.")),
2402         GST_ERROR_SYSTEM);
2403     goto done;
2404   }
2405 pool_failed:
2406   {
2407     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, SETTINGS,
2408         (_("Video device could not create buffer pool.")), GST_ERROR_SYSTEM);
2409     return FALSE;
2410   }
2411 }
2412
2413 gboolean
2414 gst_v4l2_object_unlock (GstV4l2Object * v4l2object)
2415 {
2416   GST_LOG_OBJECT (v4l2object->element, "flush poll");
2417   gst_poll_set_flushing (v4l2object->poll, TRUE);
2418
2419   return TRUE;
2420 }
2421
2422 gboolean
2423 gst_v4l2_object_unlock_stop (GstV4l2Object * v4l2object)
2424 {
2425   GST_LOG_OBJECT (v4l2object->element, "flush stop poll");
2426   gst_poll_set_flushing (v4l2object->poll, FALSE);
2427
2428   return TRUE;
2429 }
2430
2431 gboolean
2432 gst_v4l2_object_stop (GstV4l2Object * v4l2object)
2433 {
2434   GST_DEBUG_OBJECT (v4l2object->element, "stopping");
2435
2436   if (!GST_V4L2_IS_OPEN (v4l2object))
2437     goto done;
2438   if (!GST_V4L2_IS_ACTIVE (v4l2object))
2439     goto done;
2440
2441   if (v4l2object->pool) {
2442     GST_DEBUG_OBJECT (v4l2object->element, "deactivating pool");
2443     gst_buffer_pool_set_active (GST_BUFFER_POOL_CAST (v4l2object->pool), FALSE);
2444     gst_object_unref (v4l2object->pool);
2445     v4l2object->pool = NULL;
2446   }
2447
2448   GST_V4L2_SET_INACTIVE (v4l2object);
2449
2450 done:
2451   return TRUE;
2452 }
2453
2454 #if 0
2455 static GstFlowReturn
2456 gst_v4l2_object_get_mmap (GstV4l2Object * v4l2object, GstBuffer ** buf)
2457 {
2458   GstFlowReturn res;
2459 #define NUM_TRIALS 50
2460   GstBufferPool *pool;
2461   gint32 trials = NUM_TRIALS;
2462   GstBuffer *pool_buffer;
2463   gboolean need_copy;
2464
2465   pool = v4l2object->pool;
2466   if (!pool)
2467     goto no_buffer_pool;
2468
2469   GST_DEBUG_OBJECT (v4l2object->element, "grab frame");
2470
2471   for (;;) {
2472     if ((res = gst_v4l2_object_poll (v4l2object)) != GST_FLOW_OK)
2473       goto poll_error;
2474
2475     res = gst_buffer_pool_acquire_buffer (pool, &pool_buffer, NULL);
2476     if (res != GST_FLOW_OK)
2477       goto no_buffer;
2478
2479     if (v4l2object->size > 0) {
2480       gsize size = gst_buffer_get_size (pool_buffer);
2481
2482       /* if size does not match what we expected, try again */
2483       if (size != v4l2object->size) {
2484         GST_ELEMENT_WARNING (v4l2object->element, RESOURCE, READ,
2485             (_("Got unexpected frame size of %u instead of %u."),
2486                 size, v4l2object->size), (NULL));
2487         gst_buffer_unref (pool_buffer);
2488         goto no_buffer;
2489       }
2490     }
2491     /* when we get here all is fine */
2492     break;
2493
2494   no_buffer:
2495     GST_WARNING_OBJECT (v4l2object->element, "trials=%d", trials);
2496
2497     /* if the sync() got interrupted, we can retry */
2498     switch (errno) {
2499       case EINVAL:
2500       case ENOMEM:
2501         /* fatal */
2502         return GST_FLOW_ERROR;
2503
2504       case EAGAIN:
2505       case EIO:
2506       case EINTR:
2507       default:
2508         /* try again, until too many trials */
2509         break;
2510     }
2511
2512     /* check nr. of attempts to capture */
2513     if (--trials == -1) {
2514       goto too_many_trials;
2515     }
2516   }
2517
2518
2519   /* if we are handing out the last buffer in the pool, we need to make a
2520    * copy and bring the buffer back in the pool. */
2521   need_copy = v4l2object->always_copy
2522       || !gst_v4l2_buffer_pool_available_buffers (pool);
2523
2524   if (G_UNLIKELY (need_copy)) {
2525     if (!v4l2object->always_copy) {
2526       GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, v4l2object->element,
2527           "running out of buffers, making a copy to reuse current one");
2528     }
2529     *buf = gst_buffer_copy (pool_buffer);
2530     /* this will requeue */
2531     gst_buffer_unref (pool_buffer);
2532   } else {
2533     *buf = pool_buffer;
2534   }
2535
2536   return GST_FLOW_OK;
2537
2538   /* ERRORS */
2539 no_buffer_pool:
2540   {
2541     GST_DEBUG_OBJECT (v4l2object->element, "no buffer pool");
2542     return GST_FLOW_WRONG_STATE;
2543   }
2544 poll_error:
2545   {
2546     return res;
2547   }
2548 too_many_trials:
2549   {
2550     GST_ELEMENT_ERROR (v4l2object->element, RESOURCE, FAILED,
2551         (_("Failed trying to get video frames from device '%s'."),
2552             v4l2object->videodev),
2553         (_("Failed after %d tries. device %s. system error: %s"),
2554             NUM_TRIALS, v4l2object->videodev, g_strerror (errno)));
2555     return GST_FLOW_ERROR;
2556   }
2557 }
2558 #endif
2559
2560 gboolean
2561 gst_v4l2_object_copy (GstV4l2Object * v4l2object, GstBuffer * dest,
2562     GstBuffer * src)
2563 {
2564   guint8 *data;
2565   gsize size;
2566
2567   if (v4l2object->info.finfo) {
2568     GstVideoFrame src_frame, dest_frame;
2569
2570     GST_DEBUG_OBJECT (v4l2object->element, "copy video frame");
2571
2572     /* we have raw video, use videoframe copy to get strides right */
2573     if (!gst_video_frame_map (&src_frame, &v4l2object->info, src, GST_MAP_READ))
2574       goto invalid_buffer;
2575
2576     if (!gst_video_frame_map (&dest_frame, &v4l2object->info, dest,
2577             GST_MAP_WRITE)) {
2578       gst_video_frame_unmap (&src_frame);
2579       goto invalid_buffer;
2580     }
2581
2582     gst_video_frame_copy (&dest_frame, &src_frame);
2583
2584     gst_video_frame_unmap (&src_frame);
2585     gst_video_frame_unmap (&dest_frame);
2586   } else {
2587     GST_DEBUG_OBJECT (v4l2object->element, "copy raw bytes");
2588     data = gst_buffer_map (src, &size, NULL, GST_MAP_READ);
2589     gst_buffer_fill (dest, 0, data, size);
2590     gst_buffer_unmap (src, data, size);
2591   }
2592   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, v4l2object->element,
2593       "slow copy into buffer %p", dest);
2594
2595   return TRUE;
2596
2597   /* ERRORS */
2598 invalid_buffer:
2599   {
2600     /* No Window available to put our image into */
2601     GST_WARNING_OBJECT (v4l2object->element, "could not map image");
2602     return FALSE;
2603   }
2604 }