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