3 * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4 * 2006 Edgard Lima <edgard.lima@gmail.com>
6 * gstv4l2src.c: Video4Linux2 source element
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.
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.
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.
25 * SECTION:element-v4l2src
27 * v4l2src can be used to capture video from v4l2 devices, like webcams and tv
31 * <title>Example launch lines</title>
33 * gst-launch-1.0 v4l2src ! xvimagesink
34 * ]| This pipeline shows the video captured from /dev/video0 tv card and for
37 * gst-launch-1.0 v4l2src ! jpegdec ! xvimagesink
38 * ]| This pipeline shows the video captured from a webcam that delivers jpeg
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.
55 #include <gst/video/gstvideometa.h>
56 #include <gst/video/gstvideopool.h>
58 #include "gstv4l2src.h"
60 #include "gstv4l2colorbalance.h"
61 #include "gstv4l2tuner.h"
62 #include "gstv4l2vidorient.h"
64 #include "gst/gst-i18n-plugin.h"
66 GST_DEBUG_CATEGORY (v4l2src_debug);
67 #define GST_CAT_DEFAULT v4l2src_debug
69 #define DEFAULT_PROP_DEVICE "/dev/video0"
74 V4L2_STD_OBJECT_PROPS,
75 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
77 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
78 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
79 PROP_AUTO_SCAN_DEVICE,
80 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
84 /* signals and args */
87 SIGNAL_PRE_SET_FORMAT,
91 static guint gst_v4l2_signals[LAST_SIGNAL] = { 0 };
93 GST_IMPLEMENT_V4L2_COLOR_BALANCE_METHODS (GstV4l2Src, gst_v4l2src);
94 GST_IMPLEMENT_V4L2_TUNER_METHODS (GstV4l2Src, gst_v4l2src);
95 GST_IMPLEMENT_V4L2_VIDORIENT_METHODS (GstV4l2Src, gst_v4l2src);
97 static void gst_v4l2src_uri_handler_init (gpointer g_iface,
100 #define gst_v4l2src_parent_class parent_class
101 G_DEFINE_TYPE_WITH_CODE (GstV4l2Src, gst_v4l2src, GST_TYPE_PUSH_SRC,
102 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_v4l2src_uri_handler_init);
103 G_IMPLEMENT_INTERFACE (GST_TYPE_TUNER, gst_v4l2src_tuner_interface_init);
104 G_IMPLEMENT_INTERFACE (GST_TYPE_COLOR_BALANCE,
105 gst_v4l2src_color_balance_interface_init);
106 G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_ORIENTATION,
107 gst_v4l2src_video_orientation_interface_init));
109 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
111 /* element methods */
112 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
113 GstStateChange transition);
115 /* basesrc methods */
116 static gboolean gst_v4l2src_start (GstBaseSrc * src);
117 static gboolean gst_v4l2src_unlock (GstBaseSrc * src);
118 static gboolean gst_v4l2src_unlock_stop (GstBaseSrc * src);
119 static gboolean gst_v4l2src_stop (GstBaseSrc * src);
120 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter);
121 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
122 static gboolean gst_v4l2src_decide_allocation (GstBaseSrc * src,
124 static GstFlowReturn gst_v4l2src_create (GstPushSrc * src, GstBuffer ** out);
125 static GstCaps *gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps,
126 GstStructure * pref_s);
127 static gboolean gst_v4l2src_negotiate (GstBaseSrc * basesrc);
129 static void gst_v4l2src_set_property (GObject * object, guint prop_id,
130 const GValue * value, GParamSpec * pspec);
131 static void gst_v4l2src_get_property (GObject * object, guint prop_id,
132 GValue * value, GParamSpec * pspec);
135 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
137 GObjectClass *gobject_class;
138 GstElementClass *element_class;
139 GstBaseSrcClass *basesrc_class;
140 GstPushSrcClass *pushsrc_class;
142 gobject_class = G_OBJECT_CLASS (klass);
143 element_class = GST_ELEMENT_CLASS (klass);
144 basesrc_class = GST_BASE_SRC_CLASS (klass);
145 pushsrc_class = GST_PUSH_SRC_CLASS (klass);
147 gobject_class->finalize = (GObjectFinalizeFunc) gst_v4l2src_finalize;
148 gobject_class->set_property = gst_v4l2src_set_property;
149 gobject_class->get_property = gst_v4l2src_get_property;
151 element_class->change_state = gst_v4l2src_change_state;
153 gst_v4l2_object_install_properties_helper (gobject_class,
154 DEFAULT_PROP_DEVICE);
156 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
158 * GstV4l2Src:camera-id:
160 * The value which is set by application will be used as a number of device node.
161 * ex) 1 -> /dev/video1
163 g_object_class_install_property (gobject_class, PROP_CAMERA_ID,
164 g_param_spec_uint ("camera-id", "Camera ID",
165 "Camera ID for device node", 0, G_MAXUINT, 0,
166 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
167 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
169 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
171 * GstV4l2Src:auto-scan-device:
173 g_object_class_install_property (gobject_class, PROP_AUTO_SCAN_DEVICE,
174 g_param_spec_boolean ("auto-scan-device", "Scan device automatically",
175 "Scan all device nodes automatically until device open success.",
176 TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
177 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
180 * GstV4l2Src::prepare-format:
181 * @v4l2src: the v4l2src instance
182 * @fd: the file descriptor of the current device
183 * @caps: the caps of the format being set
185 * This signal gets emitted before calling the v4l2 VIDIOC_S_FMT ioctl
186 * (set format). This allows for any custom configuration of the device to
187 * happen prior to the format being set.
188 * This is mostly useful for UVC H264 encoding cameras which need the H264
189 * Probe & Commit to happen prior to the normal Probe & Commit.
191 gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT] = g_signal_new ("prepare-format",
192 G_TYPE_FROM_CLASS (klass),
194 0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CAPS);
196 gst_element_class_set_static_metadata (element_class,
197 "Video (video4linux2) Source", "Source/Video",
198 "Reads frames from a Video4Linux2 device",
199 "Edgard Lima <edgard.lima@gmail.com>, "
200 "Stefan Kost <ensonic@users.sf.net>");
202 gst_element_class_add_pad_template
204 gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
205 gst_v4l2_object_get_all_caps ()));
207 basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_get_caps);
208 basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
209 basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
210 basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
211 basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
212 basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
213 basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
214 basesrc_class->decide_allocation =
215 GST_DEBUG_FUNCPTR (gst_v4l2src_decide_allocation);
217 pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
219 klass->v4l2_class_devices = NULL;
221 GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
225 gst_v4l2src_init (GstV4l2Src * v4l2src)
227 /* fixme: give an update_fps_function */
228 v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
229 GST_OBJECT (GST_BASE_SRC_PAD (v4l2src)), V4L2_BUF_TYPE_VIDEO_CAPTURE,
230 DEFAULT_PROP_DEVICE, gst_v4l2_get_input, gst_v4l2_set_input, NULL);
232 /* Avoid the slow probes */
233 v4l2src->v4l2object->skip_try_fmt_probes = TRUE;
234 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
235 v4l2src->v4l2object->auto_scan_device = TRUE;
236 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
238 gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
239 gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
244 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
246 gst_v4l2_object_destroy (v4l2src->v4l2object);
248 G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
253 gst_v4l2src_set_property (GObject * object,
254 guint prop_id, const GValue * value, GParamSpec * pspec)
256 GstV4l2Src *v4l2src = GST_V4L2SRC (object);
258 if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
259 prop_id, value, pspec)) {
261 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
263 g_free (v4l2src->v4l2object->videodev);
265 v4l2src->camera_id = g_value_get_uint (value);
266 v4l2src->v4l2object->videodev = g_strdup_printf ("/dev/video%u", v4l2src->camera_id);
268 GST_INFO_OBJECT (v4l2src, "videodev [%s]", v4l2src->v4l2object->videodev);
270 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
271 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
272 case PROP_AUTO_SCAN_DEVICE:
273 v4l2src->v4l2object->auto_scan_device = g_value_get_boolean (value);
274 GST_INFO_OBJECT (v4l2src, "auto scan device [%d]", v4l2src->v4l2object->auto_scan_device);
276 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
278 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
285 gst_v4l2src_get_property (GObject * object,
286 guint prop_id, GValue * value, GParamSpec * pspec)
288 GstV4l2Src *v4l2src = GST_V4L2SRC (object);
290 if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
291 prop_id, value, pspec)) {
293 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
295 g_value_set_uint (value, v4l2src->camera_id);
297 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
298 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
299 case PROP_AUTO_SCAN_DEVICE:
300 GST_INFO_OBJECT (v4l2src, "auto scan device [%d]", v4l2src->v4l2object->auto_scan_device);
301 g_value_set_boolean (value, v4l2src->v4l2object->auto_scan_device);
303 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
305 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
311 struct PreferedCapsInfo
320 gst_vl42_src_fixate_fields (GQuark field_id, GValue * value, gpointer user_data)
322 GstStructure *s = user_data;
324 if (field_id == g_quark_from_string ("interlace-mode"))
327 if (field_id == g_quark_from_string ("colorimetry"))
330 gst_structure_fixate_field (s, g_quark_to_string (field_id));
336 gst_v4l2_src_fixate_struct_with_preference (GstStructure * s,
337 struct PreferedCapsInfo *pref)
339 if (gst_structure_has_field (s, "width"))
340 gst_structure_fixate_field_nearest_int (s, "width", pref->width);
342 if (gst_structure_has_field (s, "height"))
343 gst_structure_fixate_field_nearest_int (s, "height", pref->height);
345 if (gst_structure_has_field (s, "framerate"))
346 gst_structure_fixate_field_nearest_fraction (s, "framerate", pref->fps_n,
349 /* Finally, fixate everything else except the interlace-mode and colorimetry
350 * which still need further negotiation as it wasn't probed */
351 gst_structure_map_in_place (s, gst_vl42_src_fixate_fields, s);
355 gst_v4l2_src_parse_fixed_struct (GstStructure * s,
356 gint * width, gint * height, gint * fps_n, gint * fps_d)
358 if (gst_structure_has_field (s, "width") && width)
359 gst_structure_get_int (s, "width", width);
361 if (gst_structure_has_field (s, "height") && height)
362 gst_structure_get_int (s, "height", height);
364 if (gst_structure_has_field (s, "framerate") && fps_n && fps_d)
365 gst_structure_get_fraction (s, "framerate", fps_n, fps_d);
368 /* TODO Consider framerate */
370 gst_v4l2src_fixed_caps_compare (GstCaps * caps_a, GstCaps * caps_b,
371 struct PreferedCapsInfo *pref)
374 gint aw = G_MAXINT, ah = G_MAXINT, ad = G_MAXINT;
375 gint bw = G_MAXINT, bh = G_MAXINT, bd = G_MAXINT;
378 a = gst_caps_get_structure (caps_a, 0);
379 b = gst_caps_get_structure (caps_b, 0);
381 gst_v4l2_src_parse_fixed_struct (a, &aw, &ah, NULL, NULL);
382 gst_v4l2_src_parse_fixed_struct (b, &bw, &bh, NULL, NULL);
384 /* When both are smaller then pref, just append to the end */
385 if ((bw < pref->width || bh < pref->height)
386 && (aw < pref->width || ah < pref->height)) {
391 /* If a is smaller then pref and not b, then a goes after b */
392 if (aw < pref->width || ah < pref->height) {
397 /* If b is smaller then pref and not a, then a goes before b */
398 if (bw < pref->width || bh < pref->height) {
403 /* Both are larger or equal to the preference, prefer the smallest */
404 ad = MAX (1, aw - pref->width) * MAX (1, ah - pref->height);
405 bd = MAX (1, bw - pref->width) * MAX (1, bh - pref->height);
407 /* Adjust slightly in case width/height matched the preference */
408 if (aw == pref->width)
411 if (ah == pref->height)
414 if (bw == pref->width)
417 if (bh == pref->height)
420 /* If the choices are equivalent, maintain the order */
427 GST_TRACE ("Placing %ix%i (%s) %s %ix%i (%s)", aw, ah,
428 gst_structure_get_string (a, "format"), ret > 0 ? "after" : "before", bw,
429 bh, gst_structure_get_string (b, "format"));
434 gst_v4l2src_set_format (GstV4l2Src * v4l2src, GstCaps * caps,
435 GstV4l2Error * error)
439 obj = v4l2src->v4l2object;
441 /* make sure we stop capturing and dealloc buffers */
442 if (!gst_v4l2_object_stop (obj))
445 g_signal_emit (v4l2src, gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT], 0,
446 v4l2src->v4l2object->video_fd, caps);
448 return gst_v4l2_object_set_format (obj, caps, error);
452 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps, GstStructure * pref_s)
454 /* Let's prefer a good resolutiion as of today's standard. */
455 struct PreferedCapsInfo pref = {
458 GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
459 GstV4l2Object *obj = v4l2src->v4l2object;
460 GList *caps_list = NULL;
463 GstV4l2Error error = GST_V4L2_ERROR_INIT;
464 GstCaps *fcaps = NULL;
466 GST_DEBUG_OBJECT (basesrc, "fixating caps %" GST_PTR_FORMAT, caps);
468 /* We consider the first structure from peercaps to be a preference. This is
469 * useful for matching a reported native display, or simply to avoid
470 * transformation to happen downstream. */
472 pref_s = gst_structure_copy (pref_s);
473 gst_v4l2_src_fixate_struct_with_preference (pref_s, &pref);
474 gst_v4l2_src_parse_fixed_struct (pref_s, &pref.width, &pref.height,
475 &pref.fps_n, &pref.fps_d);
476 gst_structure_free (pref_s);
479 GST_DEBUG_OBJECT (basesrc, "Prefered size %ix%i", pref.width, pref.height);
481 /* Sort the structures to get the caps that is nearest to our preferences,
482 * first. Use single struct caps for sorting so we preserve the features. */
483 for (i = 0; i < gst_caps_get_size (caps); i++) {
484 GstCaps *tmp = gst_caps_copy_nth (caps, i);
486 s = gst_caps_get_structure (tmp, 0);
487 gst_v4l2_src_fixate_struct_with_preference (s, &pref);
489 caps_list = g_list_insert_sorted_with_data (caps_list, tmp,
490 (GCompareDataFunc) gst_v4l2src_fixed_caps_compare, &pref);
493 gst_caps_unref (caps);
494 caps = gst_caps_new_empty ();
497 GstCaps *tmp = caps_list->data;
498 caps_list = g_list_delete_link (caps_list, caps_list);
499 gst_caps_append (caps, tmp);
502 GST_DEBUG_OBJECT (basesrc, "sorted and normalized caps %" GST_PTR_FORMAT,
505 /* Each structure in the caps has been fixated, except for the
506 * interlace-mode and colorimetry. Now normalize the caps so we can
507 * enumerate the possibilities */
508 caps = gst_caps_normalize (caps);
510 for (i = 0; i < gst_caps_get_size (caps); ++i) {
511 gst_v4l2_clear_error (&error);
513 gst_caps_unref (fcaps);
515 fcaps = gst_caps_copy_nth (caps, i);
517 /* try hard to avoid TRY_FMT since some UVC camera just crash when this
518 * is called at run-time. */
519 if (gst_v4l2_object_caps_is_subset (obj, fcaps)) {
520 gst_caps_unref (fcaps);
521 fcaps = gst_v4l2_object_get_current_caps (obj);
525 /* Just check if the format is acceptable, once we know
526 * no buffers should be outstanding we try S_FMT.
528 * Basesrc will do an allocation query that
529 * should indirectly reclaim buffers, after that we can
530 * set the format and then configure our pool */
531 if (gst_v4l2_object_try_format (obj, fcaps, &error)) {
532 /* make sure the caps changed before doing anything */
533 if (gst_v4l2_object_caps_equal (obj, fcaps))
536 v4l2src->renegotiation_adjust = v4l2src->offset + 1;
537 v4l2src->pending_set_fmt = TRUE;
541 /* Only EIVAL make sense, report any other errors, this way we don't keep
542 * probing if the device got disconnected, or if it's firmware stopped
544 if (error.error->code != GST_RESOURCE_ERROR_SETTINGS) {
550 if (i >= gst_caps_get_size (caps)) {
551 gst_v4l2_error (v4l2src, &error);
553 gst_caps_unref (fcaps);
554 gst_caps_unref (caps);
558 gst_caps_unref (caps);
560 GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, fcaps);
566 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
569 GstCaps *caps = NULL;
570 GstCaps *peercaps = NULL;
571 gboolean result = FALSE;
573 /* first see what is possible on our source pad */
574 thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
575 GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
577 /* nothing or anything is allowed, we're done */
578 if (thiscaps == NULL || gst_caps_is_any (thiscaps))
581 /* get the peer caps without a filter as we'll filter ourselves later on */
582 peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
583 GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
584 if (peercaps && !gst_caps_is_any (peercaps)) {
585 /* Prefer the first caps we are compatible with that the peer proposed */
586 caps = gst_caps_intersect_full (peercaps, thiscaps,
587 GST_CAPS_INTERSECT_FIRST);
589 GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
591 gst_caps_unref (thiscaps);
593 /* no peer or peer have ANY caps, work with our own caps then */
599 if (!gst_caps_is_empty (caps)) {
600 GstStructure *pref = NULL;
602 if (peercaps && !gst_caps_is_any (peercaps))
603 pref = gst_caps_get_structure (peercaps, 0);
605 caps = gst_v4l2src_fixate (basesrc, caps, pref);
607 /* Fixating may fail as we now set the selected format */
613 GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
615 if (gst_caps_is_any (caps)) {
616 /* hmm, still anything, so element can do anything and
617 * nego is not needed */
619 } else if (gst_caps_is_fixed (caps)) {
620 /* yay, fixed caps, use those then */
621 result = gst_base_src_set_caps (basesrc, caps);
624 gst_caps_unref (caps);
629 gst_caps_unref (peercaps);
635 GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
637 gst_caps_unref (thiscaps);
643 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
648 v4l2src = GST_V4L2SRC (src);
649 obj = v4l2src->v4l2object;
651 if (!GST_V4L2_IS_OPEN (obj)) {
652 return gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (v4l2src));
655 return gst_v4l2_object_get_caps (obj, filter);
659 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
661 GstV4l2Src *src = GST_V4L2SRC (bsrc);
664 if (src->pending_set_fmt) {
665 GstCaps *caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
666 GstV4l2Error error = GST_V4L2_ERROR_INIT;
668 caps = gst_caps_make_writable (caps);
669 if (!(ret = gst_v4l2src_set_format (src, caps, &error)))
670 gst_v4l2_error (src, &error);
672 gst_caps_unref (caps);
673 src->pending_set_fmt = FALSE;
674 } else if (gst_buffer_pool_is_active (src->v4l2object->pool)) {
675 /* Trick basesrc into not deactivating the active pool. Renegotiating here
676 * would otherwise turn off and on the camera. */
677 GstAllocator *allocator;
678 GstAllocationParams params;
681 gst_base_src_get_allocator (bsrc, &allocator, ¶ms);
682 pool = gst_base_src_get_buffer_pool (bsrc);
684 if (gst_query_get_n_allocation_params (query))
685 gst_query_set_nth_allocation_param (query, 0, allocator, ¶ms);
687 gst_query_add_allocation_param (query, allocator, ¶ms);
689 if (gst_query_get_n_allocation_pools (query))
690 gst_query_set_nth_allocation_pool (query, 0, pool,
691 src->v4l2object->info.size, 1, 0);
693 gst_query_add_allocation_pool (query, pool, src->v4l2object->info.size, 1,
697 gst_object_unref (pool);
699 gst_object_unref (allocator);
701 return GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
705 ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
707 ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
711 if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
712 goto activate_failed;
719 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
720 (_("Failed to allocate required memory.")),
721 ("Buffer pool activation failed"));
727 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
731 gboolean res = FALSE;
733 src = GST_V4L2SRC (bsrc);
734 obj = src->v4l2object;
736 switch (GST_QUERY_TYPE (query)) {
737 case GST_QUERY_LATENCY:{
738 GstClockTime min_latency, max_latency;
739 guint32 fps_n, fps_d;
740 guint num_buffers = 0;
742 /* device must be open */
743 if (!GST_V4L2_IS_OPEN (obj)) {
744 GST_WARNING_OBJECT (src,
745 "Can't give latency since device isn't open !");
749 fps_n = GST_V4L2_FPS_N (obj);
750 fps_d = GST_V4L2_FPS_D (obj);
752 /* we must have a framerate */
753 if (fps_n <= 0 || fps_d <= 0) {
754 GST_WARNING_OBJECT (src,
755 "Can't give latency since framerate isn't fixated !");
759 /* min latency is the time to capture one frame */
760 min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
762 /* max latency is total duration of the frame buffer */
763 if (obj->pool != NULL)
764 num_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_latency;
766 if (num_buffers == 0)
769 max_latency = num_buffers * min_latency;
771 GST_DEBUG_OBJECT (bsrc,
772 "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
773 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
775 /* we are always live, the min latency is 1 frame and the max latency is
776 * the complete buffer of frames. */
777 gst_query_set_latency (query, TRUE, min_latency, max_latency);
783 res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
792 /* start and stop are not symmetric -- start will open the device, but not start
793 * capture. it's setcaps that will start capture, which is called via basesrc's
794 * negotiate method. stop will both stop capture and close the device.
797 gst_v4l2src_start (GstBaseSrc * src)
799 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
802 v4l2src->renegotiation_adjust = 0;
804 /* activate settings for first frame */
805 v4l2src->ctrl_time = 0;
806 gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
808 v4l2src->has_bad_timestamp = FALSE;
809 v4l2src->last_timestamp = 0;
815 gst_v4l2src_unlock (GstBaseSrc * src)
817 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
818 return gst_v4l2_object_unlock (v4l2src->v4l2object);
822 gst_v4l2src_unlock_stop (GstBaseSrc * src)
824 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
826 v4l2src->last_timestamp = 0;
828 return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
832 gst_v4l2src_stop (GstBaseSrc * src)
834 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
835 GstV4l2Object *obj = v4l2src->v4l2object;
837 if (GST_V4L2_IS_ACTIVE (obj)) {
838 if (!gst_v4l2_object_stop (obj))
842 v4l2src->pending_set_fmt = FALSE;
847 static GstStateChangeReturn
848 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
850 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
851 GstV4l2Src *v4l2src = GST_V4L2SRC (element);
852 GstV4l2Object *obj = v4l2src->v4l2object;
854 switch (transition) {
855 case GST_STATE_CHANGE_NULL_TO_READY:
856 /* open the device */
857 if (!gst_v4l2_object_open (obj))
858 return GST_STATE_CHANGE_FAILURE;
864 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
866 switch (transition) {
867 case GST_STATE_CHANGE_READY_TO_NULL:
868 /* close the device */
869 if (!gst_v4l2_object_close (obj))
870 return GST_STATE_CHANGE_FAILURE;
881 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
883 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
884 GstV4l2Object *obj = v4l2src->v4l2object;
885 GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
888 GstClockTime abs_time, base_time, timestamp, duration;
893 ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
894 obj->info.size, buf);
896 if (G_UNLIKELY (ret != GST_FLOW_OK))
899 ret = gst_v4l2_buffer_pool_process (pool, buf);
901 } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
903 if (G_UNLIKELY (ret != GST_FLOW_OK))
906 timestamp = GST_BUFFER_TIMESTAMP (*buf);
907 duration = obj->duration;
909 /* timestamps, LOCK to get clock and base time. */
910 /* FIXME: element clock and base_time is rarely changing */
911 GST_OBJECT_LOCK (v4l2src);
912 if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
913 /* we have a clock, get base time and ref clock */
914 base_time = GST_ELEMENT (v4l2src)->base_time;
915 gst_object_ref (clock);
917 /* no clock, can't set timestamps */
918 base_time = GST_CLOCK_TIME_NONE;
920 GST_OBJECT_UNLOCK (v4l2src);
922 /* sample pipeline clock */
924 abs_time = gst_clock_get_time (clock);
925 gst_object_unref (clock);
927 abs_time = GST_CLOCK_TIME_NONE;
931 if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
935 /* v4l2 specs say to use the system time although many drivers switched to
936 * the more desirable monotonic time. We first try to use the monotonic time
937 * and see how that goes */
938 clock_gettime (CLOCK_MONOTONIC, &now);
939 gstnow = GST_TIMESPEC_TO_TIME (now);
941 if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
944 /* very large diff, fall back to system time */
945 g_get_current_time (&now);
946 gstnow = GST_TIMEVAL_TO_TIME (now);
949 /* Detect buggy drivers here, and stop using their timestamp. Failing any
950 * of these condition would imply a very buggy driver:
951 * - Timestamp in the future
952 * - Timestamp is going backward compare to last seen timestamp
953 * - Timestamp is jumping forward for less then a frame duration
954 * - Delay is bigger then the actual timestamp
956 if (timestamp > gstnow) {
957 GST_WARNING_OBJECT (v4l2src,
958 "Timestamp in the future detected, ignoring driver timestamps");
959 v4l2src->has_bad_timestamp = TRUE;
963 if (v4l2src->last_timestamp > timestamp) {
964 GST_WARNING_OBJECT (v4l2src,
965 "Timestamp going backward, ignoring driver timestamps");
966 v4l2src->has_bad_timestamp = TRUE;
970 delay = gstnow - timestamp;
972 if (delay > timestamp) {
973 GST_WARNING_OBJECT (v4l2src,
974 "Timestamp does not correlate with any clock, ignoring driver timestamps");
975 v4l2src->has_bad_timestamp = TRUE;
979 /* Save last timestamp for sanity checks */
980 v4l2src->last_timestamp = timestamp;
982 GST_DEBUG_OBJECT (v4l2src, "ts: %" GST_TIME_FORMAT " now %" GST_TIME_FORMAT
983 " delay %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
984 GST_TIME_ARGS (gstnow), GST_TIME_ARGS (delay));
986 /* we assume 1 frame latency otherwise */
987 if (GST_CLOCK_TIME_IS_VALID (duration))
993 /* set buffer metadata */
995 if (G_LIKELY (abs_time != GST_CLOCK_TIME_NONE)) {
996 /* the time now is the time of the clock minus the base time */
997 timestamp = abs_time - base_time;
999 /* adjust for delay in the device */
1000 if (timestamp > delay)
1005 timestamp = GST_CLOCK_TIME_NONE;
1008 /* activate settings for next frame */
1009 if (GST_CLOCK_TIME_IS_VALID (duration)) {
1010 v4l2src->ctrl_time += duration;
1012 /* this is not very good (as it should be the next timestamp),
1013 * still good enough for linear fades (as long as it is not -1)
1015 v4l2src->ctrl_time = timestamp;
1017 gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
1019 GST_INFO_OBJECT (src, "sync to %" GST_TIME_FORMAT " out ts %" GST_TIME_FORMAT,
1020 GST_TIME_ARGS (v4l2src->ctrl_time), GST_TIME_ARGS (timestamp));
1022 /* use generated offset values only if there are not already valid ones
1023 * set by the v4l2 device */
1024 if (!GST_BUFFER_OFFSET_IS_VALID (*buf)
1025 || !GST_BUFFER_OFFSET_END_IS_VALID (*buf)) {
1026 GST_BUFFER_OFFSET (*buf) = v4l2src->offset++;
1027 GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset;
1029 /* adjust raw v4l2 device sequence, will restart at null in case of renegotiation
1030 * (streamoff/streamon) */
1031 GST_BUFFER_OFFSET (*buf) += v4l2src->renegotiation_adjust;
1032 GST_BUFFER_OFFSET_END (*buf) += v4l2src->renegotiation_adjust;
1033 /* check for frame loss with given (from v4l2 device) buffer offset */
1034 if ((v4l2src->offset != 0)
1035 && (GST_BUFFER_OFFSET (*buf) != (v4l2src->offset + 1))) {
1036 guint64 lost_frame_count = GST_BUFFER_OFFSET (*buf) - v4l2src->offset - 1;
1037 GST_WARNING_OBJECT (v4l2src,
1038 "lost frames detected: count = %" G_GUINT64_FORMAT " - ts: %"
1039 GST_TIME_FORMAT, lost_frame_count, GST_TIME_ARGS (timestamp));
1041 qos_msg = gst_message_new_qos (GST_OBJECT_CAST (v4l2src), TRUE,
1042 GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, timestamp,
1043 GST_CLOCK_TIME_IS_VALID (duration) ? lost_frame_count *
1044 duration : GST_CLOCK_TIME_NONE);
1045 gst_element_post_message (GST_ELEMENT_CAST (v4l2src), qos_msg);
1048 v4l2src->offset = GST_BUFFER_OFFSET (*buf);
1051 GST_BUFFER_TIMESTAMP (*buf) = timestamp;
1052 GST_BUFFER_DURATION (*buf) = duration;
1059 if (ret != GST_FLOW_FLUSHING)
1060 GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
1061 ("Failed to allocate a buffer"), (NULL));
1066 gst_buffer_replace (buf, NULL);
1067 if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
1068 GST_ELEMENT_ERROR (src, RESOURCE, FAILED,
1069 ("Driver returned a buffer with no payload, this most likely "
1070 "indicate a bug in the driver."), (NULL));
1071 ret = GST_FLOW_ERROR;
1073 GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
1074 gst_flow_get_name (ret));
1081 /* GstURIHandler interface */
1083 gst_v4l2src_uri_get_type (GType type)
1088 static const gchar *const *
1089 gst_v4l2src_uri_get_protocols (GType type)
1091 static const gchar *protocols[] = { "v4l2", NULL };
1097 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
1099 GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1101 if (v4l2src->v4l2object->videodev != NULL) {
1102 return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
1105 return g_strdup ("v4l2://");
1109 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1112 GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1113 const gchar *device = DEFAULT_PROP_DEVICE;
1115 if (strcmp (uri, "v4l2://") != 0) {
1118 g_object_set (v4l2src, "device", device, NULL);
1125 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1127 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1129 iface->get_type = gst_v4l2src_uri_get_type;
1130 iface->get_protocols = gst_v4l2src_uri_get_protocols;
1131 iface->get_uri = gst_v4l2src_uri_get_uri;
1132 iface->set_uri = gst_v4l2src_uri_set_uri;