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