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