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
28 * v4l2src can be used to capture video from v4l2 devices, like webcams and tv
31 * ## Example launch lines
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
41 * Since 1.14, the use of libv4l2 has been disabled due to major bugs in the
42 * emulation layer. To enable usage of this library, set the environment
43 * variable GST_V4L2_USE_LIBV4L2=1.
54 #include <gst/video/gstvideometa.h>
55 #include <gst/video/gstvideopool.h>
57 #include "gstv4l2elements.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 */
81 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
83 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
87 /* signals and args */
90 SIGNAL_PRE_SET_FORMAT,
94 static guint gst_v4l2_signals[LAST_SIGNAL] = { 0 };
96 GST_IMPLEMENT_V4L2_COLOR_BALANCE_METHODS (GstV4l2Src, gst_v4l2src);
97 GST_IMPLEMENT_V4L2_TUNER_METHODS (GstV4l2Src, gst_v4l2src);
98 GST_IMPLEMENT_V4L2_VIDORIENT_METHODS (GstV4l2Src, gst_v4l2src);
100 static void gst_v4l2src_uri_handler_init (gpointer g_iface,
101 gpointer iface_data);
103 #define gst_v4l2src_parent_class parent_class
104 G_DEFINE_TYPE_WITH_CODE (GstV4l2Src, gst_v4l2src, GST_TYPE_PUSH_SRC,
105 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_v4l2src_uri_handler_init);
106 G_IMPLEMENT_INTERFACE (GST_TYPE_TUNER, gst_v4l2src_tuner_interface_init);
107 G_IMPLEMENT_INTERFACE (GST_TYPE_COLOR_BALANCE,
108 gst_v4l2src_color_balance_interface_init);
109 G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_ORIENTATION,
110 gst_v4l2src_video_orientation_interface_init));
111 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (v4l2src,
112 "v4l2src", GST_RANK_PRIMARY, GST_TYPE_V4L2SRC, v4l2_element_init (plugin));
114 struct PreferredCapsInfo
122 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
124 /* element methods */
125 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
126 GstStateChange transition);
128 /* basesrc methods */
129 static gboolean gst_v4l2src_start (GstBaseSrc * src);
130 static gboolean gst_v4l2src_unlock (GstBaseSrc * src);
131 static gboolean gst_v4l2src_unlock_stop (GstBaseSrc * src);
132 static gboolean gst_v4l2src_stop (GstBaseSrc * src);
133 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter);
134 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
135 static gboolean gst_v4l2src_decide_allocation (GstBaseSrc * src,
137 static GstFlowReturn gst_v4l2src_create (GstPushSrc * src, GstBuffer ** out);
138 static GstCaps *gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps,
139 struct PreferredCapsInfo *pref);
140 static gboolean gst_v4l2src_negotiate (GstBaseSrc * basesrc);
142 static void gst_v4l2src_set_property (GObject * object, guint prop_id,
143 const GValue * value, GParamSpec * pspec);
144 static void gst_v4l2src_get_property (GObject * object, guint prop_id,
145 GValue * value, GParamSpec * pspec);
148 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
150 GObjectClass *gobject_class;
151 GstElementClass *element_class;
152 GstBaseSrcClass *basesrc_class;
153 GstPushSrcClass *pushsrc_class;
155 gobject_class = G_OBJECT_CLASS (klass);
156 element_class = GST_ELEMENT_CLASS (klass);
157 basesrc_class = GST_BASE_SRC_CLASS (klass);
158 pushsrc_class = GST_PUSH_SRC_CLASS (klass);
160 gobject_class->finalize = (GObjectFinalizeFunc) gst_v4l2src_finalize;
161 gobject_class->set_property = gst_v4l2src_set_property;
162 gobject_class->get_property = gst_v4l2src_get_property;
164 element_class->change_state = gst_v4l2src_change_state;
166 gst_v4l2_object_install_properties_helper (gobject_class,
167 DEFAULT_PROP_DEVICE);
169 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
171 * GstV4l2Src:camera-id:
173 * The value which is set by application will be used as a number of device node.
174 * ex) 1 -> /dev/video1
176 g_object_class_install_property (gobject_class, PROP_CAMERA_ID,
177 g_param_spec_uint ("camera-id", "Camera ID",
178 "Camera ID for device node", 0, G_MAXUINT, 0,
179 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
180 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
181 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
183 * GstV4l2Src:auto-scan-device:
185 g_object_class_install_property (gobject_class, PROP_AUTO_SCAN_DEVICE,
186 g_param_spec_boolean ("auto-scan-device", "Scan device automatically",
187 "Scan all device nodes automatically until device open success.",
188 TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
189 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
190 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
192 * GstV4l2Src:tbm-output
194 g_object_class_install_property (gobject_class, PROP_TBM_OUTPUT,
195 g_param_spec_boolean ("tbm-output", "Enable TBM for output buffer",
196 "It works for only DMABUF mode.",
197 FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
198 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
201 * GstV4l2Src::prepare-format:
202 * @v4l2src: the v4l2src instance
203 * @fd: the file descriptor of the current device
204 * @caps: the caps of the format being set
206 * This signal gets emitted before calling the v4l2 VIDIOC_S_FMT ioctl
207 * (set format). This allows for any custom configuration of the device to
208 * happen prior to the format being set.
209 * This is mostly useful for UVC H264 encoding cameras which need the H264
210 * Probe & Commit to happen prior to the normal Probe & Commit.
212 gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT] = g_signal_new ("prepare-format",
213 G_TYPE_FROM_CLASS (klass),
215 0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CAPS);
217 gst_element_class_set_static_metadata (element_class,
218 "Video (video4linux2) Source", "Source/Video",
219 "Reads frames from a Video4Linux2 device",
220 "Edgard Lima <edgard.lima@gmail.com>, "
221 "Stefan Kost <ensonic@users.sf.net>");
223 gst_element_class_add_pad_template
225 gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
226 gst_v4l2_object_get_all_caps ()));
228 basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_get_caps);
229 basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
230 basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
231 basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
232 basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
233 basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
234 basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
235 basesrc_class->decide_allocation =
236 GST_DEBUG_FUNCPTR (gst_v4l2src_decide_allocation);
238 pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
240 klass->v4l2_class_devices = NULL;
242 GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
246 gst_v4l2src_init (GstV4l2Src * v4l2src)
248 /* fixme: give an update_fps_function */
249 v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
250 GST_OBJECT (GST_BASE_SRC_PAD (v4l2src)), V4L2_BUF_TYPE_VIDEO_CAPTURE,
251 DEFAULT_PROP_DEVICE, gst_v4l2_get_input, gst_v4l2_set_input, NULL);
253 /* Avoid the slow probes */
254 v4l2src->v4l2object->skip_try_fmt_probes = TRUE;
255 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
256 v4l2src->v4l2object->auto_scan_device = TRUE;
257 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
259 gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
260 gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
265 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
267 gst_v4l2_object_destroy (v4l2src->v4l2object);
269 G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
274 gst_v4l2src_set_property (GObject * object,
275 guint prop_id, const GValue * value, GParamSpec * pspec)
277 GstV4l2Src *v4l2src = GST_V4L2SRC (object);
279 if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
280 prop_id, value, pspec)) {
282 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
284 g_free (v4l2src->v4l2object->videodev);
286 v4l2src->camera_id = g_value_get_uint (value);
287 v4l2src->v4l2object->videodev = g_strdup_printf ("/dev/video%u", v4l2src->camera_id);
289 GST_INFO_OBJECT (v4l2src, "videodev [%s]", v4l2src->v4l2object->videodev);
291 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
292 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
293 case PROP_AUTO_SCAN_DEVICE:
294 v4l2src->v4l2object->auto_scan_device = g_value_get_boolean (value);
295 GST_INFO_OBJECT (v4l2src, "auto scan device [%d]", v4l2src->v4l2object->auto_scan_device);
297 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
298 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
299 case PROP_TBM_OUTPUT:
300 v4l2src->v4l2object->tbm_output = g_value_get_boolean (value);
301 GST_INFO_OBJECT (v4l2src, "tbm output [%d]", v4l2src->v4l2object->tbm_output);
303 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
305 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
312 gst_v4l2src_get_property (GObject * object,
313 guint prop_id, GValue * value, GParamSpec * pspec)
315 GstV4l2Src *v4l2src = GST_V4L2SRC (object);
317 if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
318 prop_id, value, pspec)) {
320 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
322 g_value_set_uint (value, v4l2src->camera_id);
324 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
325 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
326 case PROP_AUTO_SCAN_DEVICE:
327 GST_INFO_OBJECT (v4l2src, "auto scan device [%d]", v4l2src->v4l2object->auto_scan_device);
328 g_value_set_boolean (value, v4l2src->v4l2object->auto_scan_device);
330 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
331 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
332 case PROP_TBM_OUTPUT:
333 GST_INFO_OBJECT (v4l2src, "tbm output [%d]", v4l2src->v4l2object->tbm_output);
334 g_value_set_boolean (value, v4l2src->v4l2object->tbm_output);
336 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
338 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
345 gst_vl42_src_fixate_fields (GQuark field_id, GValue * value, gpointer user_data)
347 GstStructure *s = user_data;
349 if (field_id == g_quark_from_string ("interlace-mode"))
352 if (field_id == g_quark_from_string ("colorimetry"))
355 gst_structure_fixate_field (s, g_quark_to_string (field_id));
361 gst_v4l2_src_fixate_struct_with_preference (GstStructure * s,
362 struct PreferredCapsInfo *pref)
364 if (gst_structure_has_field (s, "width"))
365 gst_structure_fixate_field_nearest_int (s, "width", pref->width);
367 if (gst_structure_has_field (s, "height"))
368 gst_structure_fixate_field_nearest_int (s, "height", pref->height);
370 if (gst_structure_has_field (s, "framerate"))
371 gst_structure_fixate_field_nearest_fraction (s, "framerate", pref->fps_n,
374 /* Finally, fixate everything else except the interlace-mode and colorimetry
375 * which still need further negotiation as it wasn't probed */
376 gst_structure_map_in_place (s, gst_vl42_src_fixate_fields, s);
380 gst_v4l2_src_parse_fixed_struct (GstStructure * s,
381 gint * width, gint * height, gint * fps_n, gint * fps_d)
383 if (gst_structure_has_field (s, "width") && width)
384 gst_structure_get_int (s, "width", width);
386 if (gst_structure_has_field (s, "height") && height)
387 gst_structure_get_int (s, "height", height);
389 if (gst_structure_has_field (s, "framerate") && fps_n && fps_d)
390 gst_structure_get_fraction (s, "framerate", fps_n, fps_d);
393 /* TODO Consider framerate */
395 gst_v4l2src_fixed_caps_compare (GstCaps * caps_a, GstCaps * caps_b,
396 struct PreferredCapsInfo *pref)
399 gint aw = G_MAXINT, ah = G_MAXINT, ad = G_MAXINT;
400 gint bw = G_MAXINT, bh = G_MAXINT, bd = G_MAXINT;
403 a = gst_caps_get_structure (caps_a, 0);
404 b = gst_caps_get_structure (caps_b, 0);
406 gst_v4l2_src_parse_fixed_struct (a, &aw, &ah, NULL, NULL);
407 gst_v4l2_src_parse_fixed_struct (b, &bw, &bh, NULL, NULL);
409 /* When both are smaller then pref, just append to the end */
410 if ((bw < pref->width || bh < pref->height)
411 && (aw < pref->width || ah < pref->height)) {
416 /* If a is smaller then pref and not b, then a goes after b */
417 if (aw < pref->width || ah < pref->height) {
422 /* If b is smaller then pref and not a, then a goes before b */
423 if (bw < pref->width || bh < pref->height) {
428 /* Both are larger or equal to the preference, prefer the smallest */
429 ad = MAX (1, aw - pref->width) * MAX (1, ah - pref->height);
430 bd = MAX (1, bw - pref->width) * MAX (1, bh - pref->height);
432 /* Adjust slightly in case width/height matched the preference */
433 if (aw == pref->width)
436 if (ah == pref->height)
439 if (bw == pref->width)
442 if (bh == pref->height)
445 /* If the choices are equivalent, maintain the order */
452 GST_TRACE ("Placing %ix%i (%s) %s %ix%i (%s)", aw, ah,
453 gst_structure_get_string (a, "format"), ret > 0 ? "after" : "before", bw,
454 bh, gst_structure_get_string (b, "format"));
459 gst_v4l2src_set_format (GstV4l2Src * v4l2src, GstCaps * caps,
460 GstV4l2Error * error)
464 obj = v4l2src->v4l2object;
466 /* make sure we stop capturing and dealloc buffers */
467 if (!gst_v4l2_object_stop (obj))
470 g_signal_emit (v4l2src, gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT], 0,
471 v4l2src->v4l2object->video_fd, caps);
473 return gst_v4l2_object_set_format (obj, caps, error);
477 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps,
478 struct PreferredCapsInfo *pref)
480 GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
481 GstV4l2Object *obj = v4l2src->v4l2object;
482 GList *caps_list = NULL;
485 GstV4l2Error error = GST_V4L2_ERROR_INIT;
486 GstCaps *fcaps = NULL;
488 GST_DEBUG_OBJECT (basesrc, "Fixating caps %" GST_PTR_FORMAT, caps);
489 GST_DEBUG_OBJECT (basesrc, "Preferred size %ix%i", pref->width, pref->height);
491 /* Sort the structures to get the caps that is nearest to our preferences,
492 * first. Use single struct caps for sorting so we preserve the features. */
493 for (i = 0; i < gst_caps_get_size (caps); i++) {
494 GstCaps *tmp = gst_caps_copy_nth (caps, i);
496 s = gst_caps_get_structure (tmp, 0);
497 gst_v4l2_src_fixate_struct_with_preference (s, pref);
499 caps_list = g_list_insert_sorted_with_data (caps_list, tmp,
500 (GCompareDataFunc) gst_v4l2src_fixed_caps_compare, pref);
503 gst_caps_unref (caps);
504 caps = gst_caps_new_empty ();
507 GstCaps *tmp = caps_list->data;
508 caps_list = g_list_delete_link (caps_list, caps_list);
509 gst_caps_append (caps, tmp);
512 GST_DEBUG_OBJECT (basesrc, "sorted and normalized caps %" GST_PTR_FORMAT,
515 /* Each structure in the caps has been fixated, except for the
516 * interlace-mode and colorimetry. Now normalize the caps so we can
517 * enumerate the possibilities */
518 caps = gst_caps_normalize (caps);
520 for (i = 0; i < gst_caps_get_size (caps); ++i) {
521 gst_v4l2_clear_error (&error);
523 gst_caps_unref (fcaps);
525 fcaps = gst_caps_copy_nth (caps, i);
527 /* try hard to avoid TRY_FMT since some UVC camera just crash when this
528 * is called at run-time. */
529 if (gst_v4l2_object_caps_is_subset (obj, fcaps)) {
530 gst_caps_unref (fcaps);
531 fcaps = gst_v4l2_object_get_current_caps (obj);
535 /* Just check if the format is acceptable, once we know
536 * no buffers should be outstanding we try S_FMT.
538 * Basesrc will do an allocation query that
539 * should indirectly reclaim buffers, after that we can
540 * set the format and then configure our pool */
541 if (gst_v4l2_object_try_format (obj, fcaps, &error)) {
542 /* make sure the caps changed before doing anything */
543 if (gst_v4l2_object_caps_equal (obj, fcaps))
546 v4l2src->renegotiation_adjust = v4l2src->offset + 1;
547 v4l2src->pending_set_fmt = TRUE;
551 /* Only EIVAL make sense, report any other errors, this way we don't keep
552 * probing if the device got disconnected, or if it's firmware stopped
554 if (error.error->code != GST_RESOURCE_ERROR_SETTINGS) {
560 if (i >= gst_caps_get_size (caps)) {
561 gst_v4l2_error (v4l2src, &error);
563 gst_caps_unref (fcaps);
564 gst_caps_unref (caps);
568 gst_caps_unref (caps);
570 GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, fcaps);
576 gst_v4l2src_query_preferred_dv_timings (GstV4l2Src * v4l2src,
577 struct PreferredCapsInfo *pref)
579 GstV4l2Object *obj = v4l2src->v4l2object;
580 struct v4l2_dv_timings dv_timings = { 0, };
581 const struct v4l2_bt_timings *bt = &dv_timings.bt;
582 gint tot_width, tot_height;
585 if (!gst_v4l2_query_dv_timings (obj, &dv_timings))
588 pref->width = bt->width;
589 pref->height = bt->height;
591 tot_height = bt->height +
592 bt->vfrontporch + bt->vsync + bt->vbackporch +
593 bt->il_vfrontporch + bt->il_vsync + bt->il_vbackporch;
594 tot_width = bt->width + bt->hfrontporch + bt->hsync + bt->hbackporch;
596 pref->fps_n = bt->pixelclock;
597 pref->fps_d = tot_width * tot_height;
602 gcd = gst_util_greatest_common_divisor (pref->fps_n, pref->fps_d);
606 /* If are are not streaming (e.g. we received source-change event), lock the
607 * new timing immediatly so that TRY_FMT can properly work */
608 if (!obj->pool || !GST_V4L2_BUFFER_POOL_IS_STREAMING (obj->pool)) {
609 gst_v4l2_set_dv_timings (obj, &dv_timings);
610 /* Setting a new DV timings invalidates the probed caps. */
611 gst_caps_replace (&obj->probed_caps, NULL);
614 GST_INFO_OBJECT (v4l2src, "Using DV Timings: %i x %i (%i/%i fps)",
615 pref->width, pref->height, pref->fps_n, pref->fps_d);
621 gst_v4l2src_query_preferred_size (GstV4l2Src * v4l2src,
622 struct PreferredCapsInfo *pref)
624 struct v4l2_input in = { 0, };
626 if (!gst_v4l2_get_input (v4l2src->v4l2object, &in.index))
629 if (!gst_v4l2_query_input (v4l2src->v4l2object, &in))
632 GST_INFO_OBJECT (v4l2src, "Detect input %u as `%s`", in.index, in.name);
634 /* Notify signal status using WARNING/INFO messages */
635 if (in.status & (V4L2_IN_ST_NO_POWER | V4L2_IN_ST_NO_SIGNAL)) {
636 if (!v4l2src->no_signal)
637 /* note: taken from decklinksrc element */
638 GST_ELEMENT_WARNING (v4l2src, RESOURCE, READ, ("Signal lost"),
639 ("No input source was detected - video frames invalid"));
640 v4l2src->no_signal = TRUE;
641 } else if (v4l2src->no_signal) {
642 if (v4l2src->no_signal)
643 GST_ELEMENT_INFO (v4l2src, RESOURCE, READ,
644 ("Signal recovered"), ("Input source detected"));
645 v4l2src->no_signal = FALSE;
648 if (in.capabilities & V4L2_IN_CAP_NATIVE_SIZE) {
649 GST_FIXME_OBJECT (v4l2src, "missing support for native video size");
651 } else if (in.capabilities & V4L2_IN_CAP_DV_TIMINGS) {
652 return gst_v4l2src_query_preferred_dv_timings (v4l2src, pref);
653 } else if (in.capabilities & V4L2_IN_CAP_STD) {
654 GST_FIXME_OBJECT (v4l2src, "missing support for video standards");
662 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
664 GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
666 GstCaps *caps = NULL;
667 GstCaps *peercaps = NULL;
668 gboolean result = FALSE;
669 /* Let's prefer a good resolution as of today's standard. */
670 struct PreferredCapsInfo pref = {
675 /* For drivers that has DV timings or other default size query
676 * capabilities, we will prefer that resolution. This must happen before we
677 * probe the caps, as locking DV Timings or standards will change result of
678 * the caps enumeration. */
679 have_pref = gst_v4l2src_query_preferred_size (v4l2src, &pref);
681 /* first see what is possible on our source pad */
682 thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
683 GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
685 /* nothing or anything is allowed, we're done */
686 if (thiscaps == NULL || gst_caps_is_any (thiscaps))
689 /* get the peer caps without a filter as we'll filter ourselves later on */
690 peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
691 GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
692 if (peercaps && !gst_caps_is_any (peercaps)) {
693 /* Prefer the first caps we are compatible with that the peer proposed */
694 caps = gst_caps_intersect_full (peercaps, thiscaps,
695 GST_CAPS_INTERSECT_FIRST);
697 GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
699 gst_caps_unref (thiscaps);
701 /* no peer or peer have ANY caps, work with our own caps then */
707 if (!gst_caps_is_empty (caps)) {
709 /* otherwise consider the first structure from peercaps to be a
710 * preference. This is useful for matching a reported native display,
711 * or simply to avoid transformation to happen downstream. */
712 if (!have_pref && peercaps && !gst_caps_is_any (peercaps)) {
713 GstStructure *pref_s = gst_caps_get_structure (peercaps, 0);
714 pref_s = gst_structure_copy (pref_s);
715 gst_v4l2_src_fixate_struct_with_preference (pref_s, &pref);
716 gst_v4l2_src_parse_fixed_struct (pref_s, &pref.width, &pref.height,
717 &pref.fps_n, &pref.fps_d);
718 gst_structure_free (pref_s);
721 caps = gst_v4l2src_fixate (basesrc, caps, &pref);
723 /* Fixating may fail as we now set the selected format */
729 GST_INFO_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
731 if (gst_caps_is_any (caps)) {
732 /* hmm, still anything, so element can do anything and
733 * nego is not needed */
735 } else if (gst_caps_is_fixed (caps)) {
736 /* yay, fixed caps, use those then */
737 result = gst_base_src_set_caps (basesrc, caps);
740 gst_caps_unref (caps);
745 gst_caps_unref (peercaps);
751 GST_INFO_OBJECT (basesrc, "no negotiation needed");
753 gst_caps_unref (thiscaps);
759 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
764 v4l2src = GST_V4L2SRC (src);
765 obj = v4l2src->v4l2object;
767 if (!GST_V4L2_IS_OPEN (obj)) {
768 return gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (v4l2src));
771 return gst_v4l2_object_get_caps (obj, filter);
775 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
777 GstV4l2Src *src = GST_V4L2SRC (bsrc);
780 if (src->pending_set_fmt) {
781 GstCaps *caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
782 GstV4l2Error error = GST_V4L2_ERROR_INIT;
784 caps = gst_caps_make_writable (caps);
786 ret = gst_v4l2src_set_format (src, caps, &error);
788 GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (src->v4l2object->pool);
789 gst_v4l2_buffer_pool_enable_resolution_change (pool);
791 gst_v4l2_error (src, &error);
794 gst_caps_unref (caps);
795 src->pending_set_fmt = FALSE;
796 } else if (gst_buffer_pool_is_active (src->v4l2object->pool)) {
797 /* Trick basesrc into not deactivating the active pool. Renegotiating here
798 * would otherwise turn off and on the camera. */
799 GstAllocator *allocator;
800 GstAllocationParams params;
803 gst_base_src_get_allocator (bsrc, &allocator, ¶ms);
804 pool = gst_base_src_get_buffer_pool (bsrc);
806 if (gst_query_get_n_allocation_params (query))
807 gst_query_set_nth_allocation_param (query, 0, allocator, ¶ms);
809 gst_query_add_allocation_param (query, allocator, ¶ms);
811 if (gst_query_get_n_allocation_pools (query))
812 gst_query_set_nth_allocation_pool (query, 0, pool,
813 src->v4l2object->info.size, 1, 0);
815 gst_query_add_allocation_pool (query, pool, src->v4l2object->info.size, 1,
819 gst_object_unref (pool);
821 gst_object_unref (allocator);
823 return GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
827 ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
829 ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
833 if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
834 goto activate_failed;
841 GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
842 (_("Failed to allocate required memory.")),
843 ("Buffer pool activation failed"));
849 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
853 gboolean res = FALSE;
855 src = GST_V4L2SRC (bsrc);
856 obj = src->v4l2object;
858 switch (GST_QUERY_TYPE (query)) {
859 case GST_QUERY_LATENCY:{
860 GstClockTime min_latency, max_latency;
861 guint32 fps_n, fps_d;
862 guint num_buffers = 0;
864 /* device must be open */
865 if (!GST_V4L2_IS_OPEN (obj)) {
866 GST_WARNING_OBJECT (src,
867 "Can't give latency since device isn't open !");
871 fps_n = GST_V4L2_FPS_N (obj);
872 fps_d = GST_V4L2_FPS_D (obj);
874 /* we must have a framerate */
875 if (fps_n <= 0 || fps_d <= 0) {
876 GST_WARNING_OBJECT (src,
877 "Can't give latency since framerate isn't fixated !");
881 /* min latency is the time to capture one frame/field */
882 min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
883 if (GST_VIDEO_INFO_INTERLACE_MODE (&obj->info) ==
884 GST_VIDEO_INTERLACE_MODE_ALTERNATE)
887 /* max latency is total duration of the frame buffer */
888 if (obj->pool != NULL)
889 num_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_latency;
891 if (num_buffers == 0)
894 max_latency = num_buffers * min_latency;
896 GST_DEBUG_OBJECT (bsrc,
897 "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
898 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
900 /* we are always live, the min latency is 1 frame and the max latency is
901 * the complete buffer of frames. */
902 gst_query_set_latency (query, TRUE, min_latency, max_latency);
908 res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
917 /* start and stop are not symmetric -- start will open the device, but not start
918 * capture. it's setcaps that will start capture, which is called via basesrc's
919 * negotiate method. stop will both stop capture and close the device.
922 gst_v4l2src_start (GstBaseSrc * src)
924 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
927 v4l2src->next_offset_same = FALSE;
928 v4l2src->renegotiation_adjust = 0;
930 /* activate settings for first frame */
931 v4l2src->ctrl_time = 0;
932 gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
934 v4l2src->has_bad_timestamp = FALSE;
935 v4l2src->last_timestamp = 0;
941 gst_v4l2src_unlock (GstBaseSrc * src)
943 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
944 return gst_v4l2_object_unlock (v4l2src->v4l2object);
948 gst_v4l2src_unlock_stop (GstBaseSrc * src)
950 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
952 v4l2src->last_timestamp = 0;
954 return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
958 gst_v4l2src_stop (GstBaseSrc * src)
960 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
961 GstV4l2Object *obj = v4l2src->v4l2object;
963 if (GST_V4L2_IS_ACTIVE (obj)) {
964 if (!gst_v4l2_object_stop (obj))
968 v4l2src->pending_set_fmt = FALSE;
973 static GstStateChangeReturn
974 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
976 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
977 GstV4l2Src *v4l2src = GST_V4L2SRC (element);
978 GstV4l2Object *obj = v4l2src->v4l2object;
979 GstV4l2Error error = GST_V4L2_ERROR_INIT;
981 switch (transition) {
982 case GST_STATE_CHANGE_NULL_TO_READY:
983 /* open the device */
984 if (!gst_v4l2_object_open (obj, &error)) {
985 gst_v4l2_error (v4l2src, &error);
986 return GST_STATE_CHANGE_FAILURE;
993 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
995 switch (transition) {
996 case GST_STATE_CHANGE_READY_TO_NULL:
997 /* close the device */
998 if (!gst_v4l2_object_close (obj))
999 return GST_STATE_CHANGE_FAILURE;
1009 static GstFlowReturn
1010 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
1012 GstV4l2Src *v4l2src = GST_V4L2SRC (src);
1013 GstV4l2Object *obj = v4l2src->v4l2object;
1016 GstClockTime abs_time, base_time, timestamp, duration;
1018 GstMessage *qos_msg;
1019 gboolean half_frame;
1022 GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
1024 ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
1025 obj->info.size, buf);
1027 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1028 if (ret == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
1029 GST_INFO_OBJECT (v4l2src, "Resolution change detected.");
1031 /* It is required to always cycle through streamoff, we also need to
1032 * streamoff in order to allow locking a new DV_TIMING which will
1033 * influence the output of TRY_FMT */
1034 gst_v4l2src_stop (GST_BASE_SRC (src));
1036 /* Force renegotiation */
1037 v4l2src->renegotiation_adjust = v4l2src->offset + 1;
1038 v4l2src->pending_set_fmt = TRUE;
1040 if (!gst_base_src_negotiate (GST_BASE_SRC (src))) {
1041 ret = GST_FLOW_NOT_NEGOTIATED;
1050 ret = gst_v4l2_buffer_pool_process (pool, buf, NULL);
1052 } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER ||
1053 ret == GST_V4L2_FLOW_RESOLUTION_CHANGE);
1055 if (G_UNLIKELY (ret != GST_FLOW_OK))
1058 timestamp = GST_BUFFER_TIMESTAMP (*buf);
1059 duration = obj->duration;
1061 /* timestamps, LOCK to get clock and base time. */
1062 /* FIXME: element clock and base_time is rarely changing */
1063 GST_OBJECT_LOCK (v4l2src);
1064 if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
1065 /* we have a clock, get base time and ref clock */
1066 base_time = GST_ELEMENT (v4l2src)->base_time;
1067 gst_object_ref (clock);
1069 /* no clock, can't set timestamps */
1070 base_time = GST_CLOCK_TIME_NONE;
1072 GST_OBJECT_UNLOCK (v4l2src);
1074 /* sample pipeline clock */
1076 abs_time = gst_clock_get_time (clock);
1077 gst_object_unref (clock);
1079 abs_time = GST_CLOCK_TIME_NONE;
1083 if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
1084 struct timespec now;
1085 GstClockTime gstnow;
1087 /* v4l2 specs say to use the system time although many drivers switched to
1088 * the more desirable monotonic time. We first try to use the monotonic time
1089 * and see how that goes */
1090 clock_gettime (CLOCK_MONOTONIC, &now);
1091 gstnow = GST_TIMESPEC_TO_TIME (now);
1093 if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
1094 /* very large diff, fall back to system time */
1095 gstnow = g_get_real_time () * GST_USECOND;
1098 /* Detect buggy drivers here, and stop using their timestamp. Failing any
1099 * of these condition would imply a very buggy driver:
1100 * - Timestamp in the future
1101 * - Timestamp is going backward compare to last seen timestamp
1102 * - Timestamp is jumping forward for less then a frame duration
1103 * - Delay is bigger then the actual timestamp
1105 if (timestamp > gstnow) {
1106 GST_WARNING_OBJECT (v4l2src,
1107 "Timestamp in the future detected, ignoring driver timestamps");
1108 v4l2src->has_bad_timestamp = TRUE;
1112 if (v4l2src->last_timestamp > timestamp) {
1113 GST_WARNING_OBJECT (v4l2src,
1114 "Timestamp going backward, ignoring driver timestamps");
1115 v4l2src->has_bad_timestamp = TRUE;
1119 delay = gstnow - timestamp;
1121 if (delay > timestamp) {
1122 GST_WARNING_OBJECT (v4l2src,
1123 "Timestamp does not correlate with any clock, ignoring driver timestamps");
1124 v4l2src->has_bad_timestamp = TRUE;
1128 /* Save last timestamp for sanity checks */
1129 v4l2src->last_timestamp = timestamp;
1131 GST_DEBUG_OBJECT (v4l2src, "ts: %" GST_TIME_FORMAT " now %" GST_TIME_FORMAT
1132 " delay %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
1133 GST_TIME_ARGS (gstnow), GST_TIME_ARGS (delay));
1135 /* we assume 1 frame/field latency otherwise */
1136 if (GST_CLOCK_TIME_IS_VALID (duration))
1142 /* set buffer metadata */
1144 if (G_LIKELY (abs_time != GST_CLOCK_TIME_NONE)) {
1145 /* the time now is the time of the clock minus the base time */
1146 timestamp = abs_time - base_time;
1148 /* adjust for delay in the device */
1149 if (timestamp > delay)
1154 timestamp = GST_CLOCK_TIME_NONE;
1157 /* activate settings for next frame */
1158 if (GST_CLOCK_TIME_IS_VALID (duration)) {
1159 v4l2src->ctrl_time += duration;
1161 /* this is not very good (as it should be the next timestamp),
1162 * still good enough for linear fades (as long as it is not -1)
1164 v4l2src->ctrl_time = timestamp;
1166 gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
1168 GST_LOG_OBJECT (src, "sync to %" GST_TIME_FORMAT " out ts %" GST_TIME_FORMAT,
1169 GST_TIME_ARGS (v4l2src->ctrl_time), GST_TIME_ARGS (timestamp));
1171 if (v4l2src->next_offset_same &&
1172 GST_BUFFER_OFFSET_IS_VALID (*buf) &&
1173 GST_BUFFER_OFFSET (*buf) != v4l2src->offset) {
1174 /* Probably had a lost field then, best to forget about last field. */
1175 GST_WARNING_OBJECT (v4l2src,
1176 "lost field detected - ts: %" GST_TIME_FORMAT,
1177 GST_TIME_ARGS (timestamp));
1178 v4l2src->next_offset_same = FALSE;
1181 half_frame = (GST_BUFFER_FLAG_IS_SET (*buf, GST_VIDEO_BUFFER_FLAG_ONEFIELD));
1183 v4l2src->next_offset_same = !v4l2src->next_offset_same;
1185 /* use generated offset values only if there are not already valid ones
1186 * set by the v4l2 device */
1187 if (!GST_BUFFER_OFFSET_IS_VALID (*buf)
1188 || !GST_BUFFER_OFFSET_END_IS_VALID (*buf)
1189 || GST_BUFFER_OFFSET (*buf) <=
1190 (v4l2src->offset - v4l2src->renegotiation_adjust)) {
1191 GST_BUFFER_OFFSET (*buf) = v4l2src->offset;
1192 GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset + 1;
1193 if (!half_frame || !v4l2src->next_offset_same)
1196 /* adjust raw v4l2 device sequence, will restart at null in case of renegotiation
1197 * (streamoff/streamon) */
1198 GST_BUFFER_OFFSET (*buf) += v4l2src->renegotiation_adjust;
1199 GST_BUFFER_OFFSET_END (*buf) += v4l2src->renegotiation_adjust;
1200 /* check for frame loss with given (from v4l2 device) buffer offset */
1201 if ((v4l2src->offset != 0)
1202 && (!half_frame || v4l2src->next_offset_same)
1203 && (GST_BUFFER_OFFSET (*buf) != (v4l2src->offset + 1))) {
1204 guint64 lost_frame_count = GST_BUFFER_OFFSET (*buf) - v4l2src->offset - 1;
1205 GST_WARNING_OBJECT (v4l2src,
1206 "lost frames detected: count = %" G_GUINT64_FORMAT " - ts: %"
1207 GST_TIME_FORMAT, lost_frame_count, GST_TIME_ARGS (timestamp));
1209 qos_msg = gst_message_new_qos (GST_OBJECT_CAST (v4l2src), TRUE,
1210 GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, timestamp,
1211 GST_CLOCK_TIME_IS_VALID (duration) ? lost_frame_count *
1212 duration : GST_CLOCK_TIME_NONE);
1213 gst_element_post_message (GST_ELEMENT_CAST (v4l2src), qos_msg);
1216 v4l2src->offset = GST_BUFFER_OFFSET (*buf);
1219 GST_BUFFER_TIMESTAMP (*buf) = timestamp;
1220 GST_BUFFER_DURATION (*buf) = duration;
1227 if (ret != GST_FLOW_FLUSHING)
1228 GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
1229 ("Failed to allocate a buffer"), (NULL));
1234 gst_buffer_replace (buf, NULL);
1235 if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
1236 GST_ELEMENT_ERROR (src, RESOURCE, FAILED,
1237 ("Driver returned a buffer with no payload, this most likely "
1238 "indicate a bug in the driver."), (NULL));
1239 ret = GST_FLOW_ERROR;
1241 GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
1242 gst_flow_get_name (ret));
1249 /* GstURIHandler interface */
1251 gst_v4l2src_uri_get_type (GType type)
1256 static const gchar *const *
1257 gst_v4l2src_uri_get_protocols (GType type)
1259 static const gchar *protocols[] = { "v4l2", NULL };
1265 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
1267 GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1269 if (v4l2src->v4l2object->videodev != NULL) {
1270 return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
1273 return g_strdup ("v4l2://");
1277 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1280 GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1281 const gchar *device = DEFAULT_PROP_DEVICE;
1283 if (strcmp (uri, "v4l2://") != 0) {
1286 g_object_set (v4l2src, "device", device, NULL);
1293 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1295 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1297 iface->get_type = gst_v4l2src_uri_get_type;
1298 iface->get_protocols = gst_v4l2src_uri_get_protocols;
1299 iface->get_uri = gst_v4l2src_uri_get_uri;
1300 iface->set_uri = gst_v4l2src_uri_set_uri;