0b55b5da19653491342261fd781d5adbc1d3bae0
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2src.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@gmail.com>
5  *
6  * gstv4l2src.c: Video4Linux2 source element
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:element-v4l2src
26  *
27  * v4l2src can be used to capture video from v4l2 devices, like webcams and tv
28  * cards.
29  *
30  * <refsect2>
31  * <title>Example launch lines</title>
32  * |[
33  * gst-launch-1.0 v4l2src ! xvimagesink
34  * ]| This pipeline shows the video captured from /dev/video0 tv card and for
35  * webcams.
36  * |[
37  * gst-launch-1.0 v4l2src ! jpegdec ! xvimagesink
38  * ]| This pipeline shows the video captured from a webcam that delivers jpeg
39  * images.
40  * </refsect2>
41  *
42  * Since 1.14, the use of libv4l2 has been disabled due to major bugs in the
43  * emulation layer. To enable usage of this library, set the environment
44  * variable GST_V4L2_USE_LIBV4L2=1.
45  */
46
47 #ifdef HAVE_CONFIG_H
48 #include <config.h>
49 #endif
50
51 #include <string.h>
52 #include <sys/time.h>
53 #include <unistd.h>
54
55 #include <gst/video/gstvideometa.h>
56 #include <gst/video/gstvideopool.h>
57
58 #include "gstv4l2src.h"
59
60 #include "gstv4l2colorbalance.h"
61 #include "gstv4l2tuner.h"
62 #include "gstv4l2vidorient.h"
63
64 #include "gst/gst-i18n-plugin.h"
65
66 GST_DEBUG_CATEGORY (v4l2src_debug);
67 #define GST_CAT_DEFAULT v4l2src_debug
68
69 #define DEFAULT_PROP_DEVICE   "/dev/video0"
70
71 enum
72 {
73   PROP_0,
74   V4L2_STD_OBJECT_PROPS,
75 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
76   PROP_CAMERA_ID,
77 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
78   PROP_LAST
79 };
80
81 /* signals and args */
82 enum
83 {
84   SIGNAL_PRE_SET_FORMAT,
85   LAST_SIGNAL
86 };
87
88 static guint gst_v4l2_signals[LAST_SIGNAL] = { 0 };
89
90 GST_IMPLEMENT_V4L2_COLOR_BALANCE_METHODS (GstV4l2Src, gst_v4l2src);
91 GST_IMPLEMENT_V4L2_TUNER_METHODS (GstV4l2Src, gst_v4l2src);
92 GST_IMPLEMENT_V4L2_VIDORIENT_METHODS (GstV4l2Src, gst_v4l2src);
93
94 static void gst_v4l2src_uri_handler_init (gpointer g_iface,
95     gpointer iface_data);
96
97 #define gst_v4l2src_parent_class parent_class
98 G_DEFINE_TYPE_WITH_CODE (GstV4l2Src, gst_v4l2src, GST_TYPE_PUSH_SRC,
99     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_v4l2src_uri_handler_init);
100     G_IMPLEMENT_INTERFACE (GST_TYPE_TUNER, gst_v4l2src_tuner_interface_init);
101     G_IMPLEMENT_INTERFACE (GST_TYPE_COLOR_BALANCE,
102         gst_v4l2src_color_balance_interface_init);
103     G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_ORIENTATION,
104         gst_v4l2src_video_orientation_interface_init));
105
106 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
107
108 /* element methods */
109 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
110     GstStateChange transition);
111
112 /* basesrc methods */
113 static gboolean gst_v4l2src_start (GstBaseSrc * src);
114 static gboolean gst_v4l2src_unlock (GstBaseSrc * src);
115 static gboolean gst_v4l2src_unlock_stop (GstBaseSrc * src);
116 static gboolean gst_v4l2src_stop (GstBaseSrc * src);
117 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter);
118 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
119 static gboolean gst_v4l2src_decide_allocation (GstBaseSrc * src,
120     GstQuery * query);
121 static GstFlowReturn gst_v4l2src_create (GstPushSrc * src, GstBuffer ** out);
122 static GstCaps *gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps,
123     GstStructure * pref_s);
124 static gboolean gst_v4l2src_negotiate (GstBaseSrc * basesrc);
125
126 static void gst_v4l2src_set_property (GObject * object, guint prop_id,
127     const GValue * value, GParamSpec * pspec);
128 static void gst_v4l2src_get_property (GObject * object, guint prop_id,
129     GValue * value, GParamSpec * pspec);
130
131 static void
132 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
133 {
134   GObjectClass *gobject_class;
135   GstElementClass *element_class;
136   GstBaseSrcClass *basesrc_class;
137   GstPushSrcClass *pushsrc_class;
138
139   gobject_class = G_OBJECT_CLASS (klass);
140   element_class = GST_ELEMENT_CLASS (klass);
141   basesrc_class = GST_BASE_SRC_CLASS (klass);
142   pushsrc_class = GST_PUSH_SRC_CLASS (klass);
143
144   gobject_class->finalize = (GObjectFinalizeFunc) gst_v4l2src_finalize;
145   gobject_class->set_property = gst_v4l2src_set_property;
146   gobject_class->get_property = gst_v4l2src_get_property;
147
148   element_class->change_state = gst_v4l2src_change_state;
149
150   gst_v4l2_object_install_properties_helper (gobject_class,
151       DEFAULT_PROP_DEVICE);
152
153 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
154   /**
155    * GstV4l2Src:camera-id:
156    *
157    * The value which is set by application will be used as a number of device node.
158    * ex) 1 -> /dev/video1
159    */
160   g_object_class_install_property (gobject_class, PROP_CAMERA_ID,
161       g_param_spec_uint ("camera-id", "Camera ID",
162           "Camera ID for device node", 0, G_MAXUINT, 0,
163           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
165
166   /**
167    * GstV4l2Src::prepare-format:
168    * @v4l2src: the v4l2src instance
169    * @fd: the file descriptor of the current device
170    * @caps: the caps of the format being set
171    *
172    * This signal gets emitted before calling the v4l2 VIDIOC_S_FMT ioctl
173    * (set format). This allows for any custom configuration of the device to
174    * happen prior to the format being set.
175    * This is mostly useful for UVC H264 encoding cameras which need the H264
176    * Probe & Commit to happen prior to the normal Probe & Commit.
177    */
178   gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT] = g_signal_new ("prepare-format",
179       G_TYPE_FROM_CLASS (klass),
180       G_SIGNAL_RUN_LAST,
181       0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CAPS);
182
183   gst_element_class_set_static_metadata (element_class,
184       "Video (video4linux2) Source", "Source/Video",
185       "Reads frames from a Video4Linux2 device",
186       "Edgard Lima <edgard.lima@gmail.com>, "
187       "Stefan Kost <ensonic@users.sf.net>");
188
189   gst_element_class_add_pad_template
190       (element_class,
191       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
192           gst_v4l2_object_get_all_caps ()));
193
194   basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_get_caps);
195   basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
196   basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
197   basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
198   basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
199   basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
200   basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
201   basesrc_class->decide_allocation =
202       GST_DEBUG_FUNCPTR (gst_v4l2src_decide_allocation);
203
204   pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
205
206   klass->v4l2_class_devices = NULL;
207
208   GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
209 }
210
211 static void
212 gst_v4l2src_init (GstV4l2Src * v4l2src)
213 {
214   /* fixme: give an update_fps_function */
215   v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
216       GST_OBJECT (GST_BASE_SRC_PAD (v4l2src)), V4L2_BUF_TYPE_VIDEO_CAPTURE,
217       DEFAULT_PROP_DEVICE, gst_v4l2_get_input, gst_v4l2_set_input, NULL);
218
219   /* Avoid the slow probes */
220   v4l2src->v4l2object->skip_try_fmt_probes = TRUE;
221
222   gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
223   gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
224 }
225
226
227 static void
228 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
229 {
230   gst_v4l2_object_destroy (v4l2src->v4l2object);
231
232   G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
233 }
234
235
236 static void
237 gst_v4l2src_set_property (GObject * object,
238     guint prop_id, const GValue * value, GParamSpec * pspec)
239 {
240   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
241
242   if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
243           prop_id, value, pspec)) {
244     switch (prop_id) {
245 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
246       case PROP_CAMERA_ID:
247         g_free (v4l2src->v4l2object->videodev);
248
249         v4l2src->camera_id = g_value_get_uint (value);
250         v4l2src->v4l2object->videodev = g_strdup_printf ("/dev/video%u", v4l2src->camera_id);
251
252         GST_INFO_OBJECT(v4l2src, "videodev [%s]", v4l2src->v4l2object->videodev);
253         break;
254 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
255       default:
256         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
257         break;
258     }
259   }
260 }
261
262 static void
263 gst_v4l2src_get_property (GObject * object,
264     guint prop_id, GValue * value, GParamSpec * pspec)
265 {
266   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
267
268   if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
269           prop_id, value, pspec)) {
270     switch (prop_id) {
271 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
272       case PROP_CAMERA_ID:
273         g_value_set_uint (value, v4l2src->camera_id);
274         break;
275 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
276       default:
277         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
278         break;
279     }
280   }
281 }
282
283 struct PreferedCapsInfo
284 {
285   gint width;
286   gint height;
287   gint fps_n;
288   gint fps_d;
289 };
290
291 static gboolean
292 gst_vl42_src_fixate_fields (GQuark field_id, GValue * value, gpointer user_data)
293 {
294   GstStructure *s = user_data;
295
296   if (field_id == g_quark_from_string ("interlace-mode"))
297     return TRUE;
298
299   if (field_id == g_quark_from_string ("colorimetry"))
300     return TRUE;
301
302   gst_structure_fixate_field (s, g_quark_to_string (field_id));
303
304   return TRUE;
305 }
306
307 static void
308 gst_v4l2_src_fixate_struct_with_preference (GstStructure * s,
309     struct PreferedCapsInfo *pref)
310 {
311   if (gst_structure_has_field (s, "width"))
312     gst_structure_fixate_field_nearest_int (s, "width", pref->width);
313
314   if (gst_structure_has_field (s, "height"))
315     gst_structure_fixate_field_nearest_int (s, "height", pref->height);
316
317   if (gst_structure_has_field (s, "framerate"))
318     gst_structure_fixate_field_nearest_fraction (s, "framerate", pref->fps_n,
319         pref->fps_d);
320
321   /* Finally, fixate everything else except the interlace-mode and colorimetry
322    * which still need further negotiation as it wasn't probed */
323   gst_structure_map_in_place (s, gst_vl42_src_fixate_fields, s);
324 }
325
326 static void
327 gst_v4l2_src_parse_fixed_struct (GstStructure * s,
328     gint * width, gint * height, gint * fps_n, gint * fps_d)
329 {
330   if (gst_structure_has_field (s, "width") && width)
331     gst_structure_get_int (s, "width", width);
332
333   if (gst_structure_has_field (s, "height") && height)
334     gst_structure_get_int (s, "height", height);
335
336   if (gst_structure_has_field (s, "framerate") && fps_n && fps_d)
337     gst_structure_get_fraction (s, "framerate", fps_n, fps_d);
338 }
339
340 /* TODO Consider framerate */
341 static gint
342 gst_v4l2src_fixed_caps_compare (GstCaps * caps_a, GstCaps * caps_b,
343     struct PreferedCapsInfo *pref)
344 {
345   GstStructure *a, *b;
346   gint aw = G_MAXINT, ah = G_MAXINT, ad = G_MAXINT;
347   gint bw = G_MAXINT, bh = G_MAXINT, bd = G_MAXINT;
348   gint ret;
349
350   a = gst_caps_get_structure (caps_a, 0);
351   b = gst_caps_get_structure (caps_b, 0);
352
353   gst_v4l2_src_parse_fixed_struct (a, &aw, &ah, NULL, NULL);
354   gst_v4l2_src_parse_fixed_struct (b, &bw, &bh, NULL, NULL);
355
356   /* When both are smaller then pref, just append to the end */
357   if ((bw < pref->width || bh < pref->height)
358       && (aw < pref->width || ah < pref->height)) {
359     ret = 1;
360     goto done;
361   }
362
363   /* If a is smaller then pref and not b, then a goes after b */
364   if (aw < pref->width || ah < pref->height) {
365     ret = 1;
366     goto done;
367   }
368
369   /* If b is smaller then pref and not a, then a goes before b */
370   if (bw < pref->width || bh < pref->height) {
371     ret = -1;
372     goto done;
373   }
374
375   /* Both are larger or equal to the preference, prefer the smallest */
376   ad = MAX (1, aw - pref->width) * MAX (1, ah - pref->height);
377   bd = MAX (1, bw - pref->width) * MAX (1, bh - pref->height);
378
379   /* Adjust slightly in case width/height matched the preference */
380   if (aw == pref->width)
381     ad -= 1;
382
383   if (ah == pref->height)
384     ad -= 1;
385
386   if (bw == pref->width)
387     bd -= 1;
388
389   if (bh == pref->height)
390     bd -= 1;
391
392   /* If the choices are equivalent, maintain the order */
393   if (ad == bd)
394     ret = 1;
395   else
396     ret = ad - bd;
397
398 done:
399   GST_TRACE ("Placing %ix%i (%s) %s %ix%i (%s)", aw, ah,
400       gst_structure_get_string (a, "format"), ret > 0 ? "after" : "before", bw,
401       bh, gst_structure_get_string (b, "format"));
402   return ret;
403 }
404
405 static gboolean
406 gst_v4l2src_set_format (GstV4l2Src * v4l2src, GstCaps * caps,
407     GstV4l2Error * error)
408 {
409   GstV4l2Object *obj;
410
411   obj = v4l2src->v4l2object;
412
413   /* make sure we stop capturing and dealloc buffers */
414   if (!gst_v4l2_object_stop (obj))
415     return FALSE;
416
417   g_signal_emit (v4l2src, gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT], 0,
418       v4l2src->v4l2object->video_fd, caps);
419
420   return gst_v4l2_object_set_format (obj, caps, error);
421 }
422
423 static GstCaps *
424 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps, GstStructure * pref_s)
425 {
426   /* Let's prefer a good resolutiion as of today's standard. */
427   struct PreferedCapsInfo pref = {
428     3840, 2160, 120, 1
429   };
430   GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
431   GstV4l2Object *obj = v4l2src->v4l2object;
432   GList *caps_list = NULL;
433   GstStructure *s;
434   gint i = G_MAXINT;
435   GstV4l2Error error = GST_V4L2_ERROR_INIT;
436   GstCaps *fcaps = NULL;
437
438   GST_DEBUG_OBJECT (basesrc, "fixating caps %" GST_PTR_FORMAT, caps);
439
440   /* We consider the first structure from peercaps to be a preference. This is
441    * useful for matching a reported native display, or simply to avoid
442    * transformation to happen downstream. */
443   if (pref_s) {
444     pref_s = gst_structure_copy (pref_s);
445     gst_v4l2_src_fixate_struct_with_preference (pref_s, &pref);
446     gst_v4l2_src_parse_fixed_struct (pref_s, &pref.width, &pref.height,
447         &pref.fps_n, &pref.fps_d);
448     gst_structure_free (pref_s);
449   }
450
451   GST_DEBUG_OBJECT (basesrc, "Prefered size %ix%i", pref.width, pref.height);
452
453   /* Sort the structures to get the caps that is nearest to our preferences,
454    * first. Use single struct caps for sorting so we preserve the features.  */
455   for (i = 0; i < gst_caps_get_size (caps); i++) {
456     GstCaps *tmp = gst_caps_copy_nth (caps, i);
457
458     s = gst_caps_get_structure (tmp, 0);
459     gst_v4l2_src_fixate_struct_with_preference (s, &pref);
460
461     caps_list = g_list_insert_sorted_with_data (caps_list, tmp,
462         (GCompareDataFunc) gst_v4l2src_fixed_caps_compare, &pref);
463   }
464
465   gst_caps_unref (caps);
466   caps = gst_caps_new_empty ();
467
468   while (caps_list) {
469     GstCaps *tmp = caps_list->data;
470     caps_list = g_list_delete_link (caps_list, caps_list);
471     gst_caps_append (caps, tmp);
472   }
473
474   GST_DEBUG_OBJECT (basesrc, "sorted and normalized caps %" GST_PTR_FORMAT,
475       caps);
476
477   /* Each structure in the caps has been fixated, except for the
478    * interlace-mode and colorimetry. Now normalize the caps so we can
479    * enumerate the possibilities */
480   caps = gst_caps_normalize (caps);
481
482   for (i = 0; i < gst_caps_get_size (caps); ++i) {
483     gst_v4l2_clear_error (&error);
484     if (fcaps)
485       gst_caps_unref (fcaps);
486
487     fcaps = gst_caps_copy_nth (caps, i);
488
489     /* try hard to avoid TRY_FMT since some UVC camera just crash when this
490      * is called at run-time. */
491     if (gst_v4l2_object_caps_is_subset (obj, fcaps)) {
492       gst_caps_unref (fcaps);
493       fcaps = gst_v4l2_object_get_current_caps (obj);
494       break;
495     }
496
497     /* Just check if the format is acceptable, once we know
498      * no buffers should be outstanding we try S_FMT.
499      *
500      * Basesrc will do an allocation query that
501      * should indirectly reclaim buffers, after that we can
502      * set the format and then configure our pool */
503     if (gst_v4l2_object_try_format (obj, fcaps, &error)) {
504       /* make sure the caps changed before doing anything */
505       if (gst_v4l2_object_caps_equal (obj, fcaps))
506         break;
507
508       v4l2src->renegotiation_adjust = v4l2src->offset + 1;
509       v4l2src->pending_set_fmt = TRUE;
510       break;
511     }
512
513     /* Only EIVAL make sense, report any other errors, this way we don't keep
514      * probing if the device got disconnected, or if it's firmware stopped
515      * responding */
516     if (error.error->code != GST_RESOURCE_ERROR_SETTINGS) {
517       i = G_MAXINT;
518       break;
519     }
520   }
521
522   if (i >= gst_caps_get_size (caps)) {
523     gst_v4l2_error (v4l2src, &error);
524     if (fcaps)
525       gst_caps_unref (fcaps);
526     gst_caps_unref (caps);
527     return NULL;
528   }
529
530   gst_caps_unref (caps);
531
532   GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, fcaps);
533
534   return fcaps;
535 }
536
537 static gboolean
538 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
539 {
540   GstCaps *thiscaps;
541   GstCaps *caps = NULL;
542   GstCaps *peercaps = NULL;
543   gboolean result = FALSE;
544
545   /* first see what is possible on our source pad */
546   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
547   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
548
549   /* nothing or anything is allowed, we're done */
550   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
551     goto no_nego_needed;
552
553   /* get the peer caps without a filter as we'll filter ourselves later on */
554   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
555   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
556   if (peercaps && !gst_caps_is_any (peercaps)) {
557     /* Prefer the first caps we are compatible with that the peer proposed */
558     caps = gst_caps_intersect_full (peercaps, thiscaps,
559         GST_CAPS_INTERSECT_FIRST);
560
561     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
562
563     gst_caps_unref (thiscaps);
564   } else {
565     /* no peer or peer have ANY caps, work with our own caps then */
566     caps = thiscaps;
567   }
568
569   if (caps) {
570     /* now fixate */
571     if (!gst_caps_is_empty (caps)) {
572       GstStructure *pref = NULL;
573
574       if (peercaps && !gst_caps_is_any (peercaps))
575         pref = gst_caps_get_structure (peercaps, 0);
576
577       caps = gst_v4l2src_fixate (basesrc, caps, pref);
578
579       /* Fixating may fail as we now set the selected format */
580       if (!caps) {
581         result = FALSE;
582         goto done;
583       }
584
585       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
586
587       if (gst_caps_is_any (caps)) {
588         /* hmm, still anything, so element can do anything and
589          * nego is not needed */
590         result = TRUE;
591       } else if (gst_caps_is_fixed (caps)) {
592         /* yay, fixed caps, use those then */
593         result = gst_base_src_set_caps (basesrc, caps);
594       }
595     }
596     gst_caps_unref (caps);
597   }
598
599 done:
600   if (peercaps)
601     gst_caps_unref (peercaps);
602
603   return result;
604
605 no_nego_needed:
606   {
607     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
608     if (thiscaps)
609       gst_caps_unref (thiscaps);
610     return TRUE;
611   }
612 }
613
614 static GstCaps *
615 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
616 {
617   GstV4l2Src *v4l2src;
618   GstV4l2Object *obj;
619
620   v4l2src = GST_V4L2SRC (src);
621   obj = v4l2src->v4l2object;
622
623   if (!GST_V4L2_IS_OPEN (obj)) {
624     return gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (v4l2src));
625   }
626
627   return gst_v4l2_object_get_caps (obj, filter);
628 }
629
630 static gboolean
631 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
632 {
633   GstV4l2Src *src = GST_V4L2SRC (bsrc);
634   gboolean ret = TRUE;
635
636   if (src->pending_set_fmt) {
637     GstCaps *caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
638     GstV4l2Error error = GST_V4L2_ERROR_INIT;
639
640     caps = gst_caps_make_writable (caps);
641     if (!(ret = gst_v4l2src_set_format (src, caps, &error)))
642       gst_v4l2_error (src, &error);
643
644     gst_caps_unref (caps);
645     src->pending_set_fmt = FALSE;
646   } else if (gst_buffer_pool_is_active (src->v4l2object->pool)) {
647     /* Trick basesrc into not deactivating the active pool. Renegotiating here
648      * would otherwise turn off and on the camera. */
649     GstAllocator *allocator;
650     GstAllocationParams params;
651     GstBufferPool *pool;
652
653     gst_base_src_get_allocator (bsrc, &allocator, &params);
654     pool = gst_base_src_get_buffer_pool (bsrc);
655
656     if (gst_query_get_n_allocation_params (query))
657       gst_query_set_nth_allocation_param (query, 0, allocator, &params);
658     else
659       gst_query_add_allocation_param (query, allocator, &params);
660
661     if (gst_query_get_n_allocation_pools (query))
662       gst_query_set_nth_allocation_pool (query, 0, pool,
663           src->v4l2object->info.size, 1, 0);
664     else
665       gst_query_add_allocation_pool (query, pool, src->v4l2object->info.size, 1,
666           0);
667
668     if (pool)
669       gst_object_unref (pool);
670     if (allocator)
671       gst_object_unref (allocator);
672
673     return GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
674   }
675
676   if (ret) {
677     ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
678     if (ret)
679       ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
680   }
681
682   if (ret) {
683     if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
684       goto activate_failed;
685   }
686
687   return ret;
688
689 activate_failed:
690   {
691     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
692         (_("Failed to allocate required memory.")),
693         ("Buffer pool activation failed"));
694     return FALSE;
695   }
696 }
697
698 static gboolean
699 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
700 {
701   GstV4l2Src *src;
702   GstV4l2Object *obj;
703   gboolean res = FALSE;
704
705   src = GST_V4L2SRC (bsrc);
706   obj = src->v4l2object;
707
708   switch (GST_QUERY_TYPE (query)) {
709     case GST_QUERY_LATENCY:{
710       GstClockTime min_latency, max_latency;
711       guint32 fps_n, fps_d;
712       guint num_buffers = 0;
713
714       /* device must be open */
715       if (!GST_V4L2_IS_OPEN (obj)) {
716         GST_WARNING_OBJECT (src,
717             "Can't give latency since device isn't open !");
718         goto done;
719       }
720
721       fps_n = GST_V4L2_FPS_N (obj);
722       fps_d = GST_V4L2_FPS_D (obj);
723
724       /* we must have a framerate */
725       if (fps_n <= 0 || fps_d <= 0) {
726         GST_WARNING_OBJECT (src,
727             "Can't give latency since framerate isn't fixated !");
728         goto done;
729       }
730
731       /* min latency is the time to capture one frame */
732       min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
733
734       /* max latency is total duration of the frame buffer */
735       if (obj->pool != NULL)
736         num_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_latency;
737
738       if (num_buffers == 0)
739         max_latency = -1;
740       else
741         max_latency = num_buffers * min_latency;
742
743       GST_DEBUG_OBJECT (bsrc,
744           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
745           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
746
747       /* we are always live, the min latency is 1 frame and the max latency is
748        * the complete buffer of frames. */
749       gst_query_set_latency (query, TRUE, min_latency, max_latency);
750
751       res = TRUE;
752       break;
753     }
754     default:
755       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
756       break;
757   }
758
759 done:
760
761   return res;
762 }
763
764 /* start and stop are not symmetric -- start will open the device, but not start
765  * capture. it's setcaps that will start capture, which is called via basesrc's
766  * negotiate method. stop will both stop capture and close the device.
767  */
768 static gboolean
769 gst_v4l2src_start (GstBaseSrc * src)
770 {
771   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
772
773   v4l2src->offset = 0;
774   v4l2src->renegotiation_adjust = 0;
775
776   /* activate settings for first frame */
777   v4l2src->ctrl_time = 0;
778   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
779
780   v4l2src->has_bad_timestamp = FALSE;
781   v4l2src->last_timestamp = 0;
782
783   return TRUE;
784 }
785
786 static gboolean
787 gst_v4l2src_unlock (GstBaseSrc * src)
788 {
789   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
790   return gst_v4l2_object_unlock (v4l2src->v4l2object);
791 }
792
793 static gboolean
794 gst_v4l2src_unlock_stop (GstBaseSrc * src)
795 {
796   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
797
798   v4l2src->last_timestamp = 0;
799
800   return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
801 }
802
803 static gboolean
804 gst_v4l2src_stop (GstBaseSrc * src)
805 {
806   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
807   GstV4l2Object *obj = v4l2src->v4l2object;
808
809   if (GST_V4L2_IS_ACTIVE (obj)) {
810     if (!gst_v4l2_object_stop (obj))
811       return FALSE;
812   }
813
814   v4l2src->pending_set_fmt = FALSE;
815
816   return TRUE;
817 }
818
819 static GstStateChangeReturn
820 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
821 {
822   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
823   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
824   GstV4l2Object *obj = v4l2src->v4l2object;
825
826   switch (transition) {
827     case GST_STATE_CHANGE_NULL_TO_READY:
828       /* open the device */
829       if (!gst_v4l2_object_open (obj))
830         return GST_STATE_CHANGE_FAILURE;
831       break;
832     default:
833       break;
834   }
835
836   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
837
838   switch (transition) {
839     case GST_STATE_CHANGE_READY_TO_NULL:
840       /* close the device */
841       if (!gst_v4l2_object_close (obj))
842         return GST_STATE_CHANGE_FAILURE;
843
844       break;
845     default:
846       break;
847   }
848
849   return ret;
850 }
851
852 static GstFlowReturn
853 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
854 {
855   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
856   GstV4l2Object *obj = v4l2src->v4l2object;
857   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
858   GstFlowReturn ret;
859   GstClock *clock;
860   GstClockTime abs_time, base_time, timestamp, duration;
861   GstClockTime delay;
862   GstMessage *qos_msg;
863
864   do {
865     ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
866         obj->info.size, buf);
867
868     if (G_UNLIKELY (ret != GST_FLOW_OK))
869       goto alloc_failed;
870
871     ret = gst_v4l2_buffer_pool_process (pool, buf);
872
873   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
874
875   if (G_UNLIKELY (ret != GST_FLOW_OK))
876     goto error;
877
878   timestamp = GST_BUFFER_TIMESTAMP (*buf);
879   duration = obj->duration;
880
881   /* timestamps, LOCK to get clock and base time. */
882   /* FIXME: element clock and base_time is rarely changing */
883   GST_OBJECT_LOCK (v4l2src);
884   if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
885     /* we have a clock, get base time and ref clock */
886     base_time = GST_ELEMENT (v4l2src)->base_time;
887     gst_object_ref (clock);
888   } else {
889     /* no clock, can't set timestamps */
890     base_time = GST_CLOCK_TIME_NONE;
891   }
892   GST_OBJECT_UNLOCK (v4l2src);
893
894   /* sample pipeline clock */
895   if (clock) {
896     abs_time = gst_clock_get_time (clock);
897     gst_object_unref (clock);
898   } else {
899     abs_time = GST_CLOCK_TIME_NONE;
900   }
901
902 retry:
903   if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
904     struct timespec now;
905     GstClockTime gstnow;
906
907     /* v4l2 specs say to use the system time although many drivers switched to
908      * the more desirable monotonic time. We first try to use the monotonic time
909      * and see how that goes */
910     clock_gettime (CLOCK_MONOTONIC, &now);
911     gstnow = GST_TIMESPEC_TO_TIME (now);
912
913     if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
914       GTimeVal now;
915
916       /* very large diff, fall back to system time */
917       g_get_current_time (&now);
918       gstnow = GST_TIMEVAL_TO_TIME (now);
919     }
920
921     /* Detect buggy drivers here, and stop using their timestamp. Failing any
922      * of these condition would imply a very buggy driver:
923      *   - Timestamp in the future
924      *   - Timestamp is going backward compare to last seen timestamp
925      *   - Timestamp is jumping forward for less then a frame duration
926      *   - Delay is bigger then the actual timestamp
927      * */
928     if (timestamp > gstnow) {
929       GST_WARNING_OBJECT (v4l2src,
930           "Timestamp in the future detected, ignoring driver timestamps");
931       v4l2src->has_bad_timestamp = TRUE;
932       goto retry;
933     }
934
935     if (v4l2src->last_timestamp > timestamp) {
936       GST_WARNING_OBJECT (v4l2src,
937           "Timestamp going backward, ignoring driver timestamps");
938       v4l2src->has_bad_timestamp = TRUE;
939       goto retry;
940     }
941
942     delay = gstnow - timestamp;
943
944     if (delay > timestamp) {
945       GST_WARNING_OBJECT (v4l2src,
946           "Timestamp does not correlate with any clock, ignoring driver timestamps");
947       v4l2src->has_bad_timestamp = TRUE;
948       goto retry;
949     }
950
951     /* Save last timestamp for sanity checks */
952     v4l2src->last_timestamp = timestamp;
953
954     GST_DEBUG_OBJECT (v4l2src, "ts: %" GST_TIME_FORMAT " now %" GST_TIME_FORMAT
955         " delay %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
956         GST_TIME_ARGS (gstnow), GST_TIME_ARGS (delay));
957   } else {
958     /* we assume 1 frame latency otherwise */
959     if (GST_CLOCK_TIME_IS_VALID (duration))
960       delay = duration;
961     else
962       delay = 0;
963   }
964
965   /* set buffer metadata */
966
967   if (G_LIKELY (abs_time != GST_CLOCK_TIME_NONE)) {
968     /* the time now is the time of the clock minus the base time */
969     timestamp = abs_time - base_time;
970
971     /* adjust for delay in the device */
972     if (timestamp > delay)
973       timestamp -= delay;
974     else
975       timestamp = 0;
976   } else {
977     timestamp = GST_CLOCK_TIME_NONE;
978   }
979
980   /* activate settings for next frame */
981   if (GST_CLOCK_TIME_IS_VALID (duration)) {
982     v4l2src->ctrl_time += duration;
983   } else {
984     /* this is not very good (as it should be the next timestamp),
985      * still good enough for linear fades (as long as it is not -1)
986      */
987     v4l2src->ctrl_time = timestamp;
988   }
989   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
990
991   GST_INFO_OBJECT (src, "sync to %" GST_TIME_FORMAT " out ts %" GST_TIME_FORMAT,
992       GST_TIME_ARGS (v4l2src->ctrl_time), GST_TIME_ARGS (timestamp));
993
994   /* use generated offset values only if there are not already valid ones
995    * set by the v4l2 device */
996   if (!GST_BUFFER_OFFSET_IS_VALID (*buf)
997       || !GST_BUFFER_OFFSET_END_IS_VALID (*buf)) {
998     GST_BUFFER_OFFSET (*buf) = v4l2src->offset++;
999     GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset;
1000   } else {
1001     /* adjust raw v4l2 device sequence, will restart at null in case of renegotiation
1002      * (streamoff/streamon) */
1003     GST_BUFFER_OFFSET (*buf) += v4l2src->renegotiation_adjust;
1004     GST_BUFFER_OFFSET_END (*buf) += v4l2src->renegotiation_adjust;
1005     /* check for frame loss with given (from v4l2 device) buffer offset */
1006     if ((v4l2src->offset != 0)
1007         && (GST_BUFFER_OFFSET (*buf) != (v4l2src->offset + 1))) {
1008       guint64 lost_frame_count = GST_BUFFER_OFFSET (*buf) - v4l2src->offset - 1;
1009       GST_WARNING_OBJECT (v4l2src,
1010           "lost frames detected: count = %" G_GUINT64_FORMAT " - ts: %"
1011           GST_TIME_FORMAT, lost_frame_count, GST_TIME_ARGS (timestamp));
1012
1013       qos_msg = gst_message_new_qos (GST_OBJECT_CAST (v4l2src), TRUE,
1014           GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, timestamp,
1015           GST_CLOCK_TIME_IS_VALID (duration) ? lost_frame_count *
1016           duration : GST_CLOCK_TIME_NONE);
1017       gst_element_post_message (GST_ELEMENT_CAST (v4l2src), qos_msg);
1018
1019     }
1020     v4l2src->offset = GST_BUFFER_OFFSET (*buf);
1021   }
1022
1023   GST_BUFFER_TIMESTAMP (*buf) = timestamp;
1024   GST_BUFFER_DURATION (*buf) = duration;
1025
1026   return ret;
1027
1028   /* ERROR */
1029 alloc_failed:
1030   {
1031     if (ret != GST_FLOW_FLUSHING)
1032       GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
1033           ("Failed to allocate a buffer"), (NULL));
1034     return ret;
1035   }
1036 error:
1037   {
1038     gst_buffer_replace (buf, NULL);
1039     if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
1040       GST_ELEMENT_ERROR (src, RESOURCE, FAILED,
1041           ("Driver returned a buffer with no payload, this most likely "
1042               "indicate a bug in the driver."), (NULL));
1043       ret = GST_FLOW_ERROR;
1044     } else {
1045       GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
1046           gst_flow_get_name (ret));
1047     }
1048     return ret;
1049   }
1050 }
1051
1052
1053 /* GstURIHandler interface */
1054 static GstURIType
1055 gst_v4l2src_uri_get_type (GType type)
1056 {
1057   return GST_URI_SRC;
1058 }
1059
1060 static const gchar *const *
1061 gst_v4l2src_uri_get_protocols (GType type)
1062 {
1063   static const gchar *protocols[] = { "v4l2", NULL };
1064
1065   return protocols;
1066 }
1067
1068 static gchar *
1069 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
1070 {
1071   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1072
1073   if (v4l2src->v4l2object->videodev != NULL) {
1074     return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
1075   }
1076
1077   return g_strdup ("v4l2://");
1078 }
1079
1080 static gboolean
1081 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1082     GError ** error)
1083 {
1084   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1085   const gchar *device = DEFAULT_PROP_DEVICE;
1086
1087   if (strcmp (uri, "v4l2://") != 0) {
1088     device = uri + 7;
1089   }
1090   g_object_set (v4l2src, "device", device, NULL);
1091
1092   return TRUE;
1093 }
1094
1095
1096 static void
1097 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1098 {
1099   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1100
1101   iface->get_type = gst_v4l2src_uri_get_type;
1102   iface->get_protocols = gst_v4l2src_uri_get_protocols;
1103   iface->get_uri = gst_v4l2src_uri_get_uri;
1104   iface->set_uri = gst_v4l2src_uri_set_uri;
1105 }