36a7fa0bcb2bddb5ef37d2e3895930f0cb5f5b2d
[platform/upstream/gst-plugins-good.git] / sys / v4l2 / gstv4l2src.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@gmail.com>
5  *
6  * gstv4l2src.c: Video4Linux2 source element
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:element-v4l2src
26  *
27  * v4l2src can be used to capture video from v4l2 devices, like webcams and tv
28  * cards.
29  *
30  * <refsect2>
31  * <title>Example launch lines</title>
32  * |[
33  * gst-launch-1.0 v4l2src ! xvimagesink
34  * ]| This pipeline shows the video captured from /dev/video0 tv card and for
35  * webcams.
36  * |[
37  * gst-launch-1.0 v4l2src ! jpegdec ! xvimagesink
38  * ]| This pipeline shows the video captured from a webcam that delivers jpeg
39  * images.
40  * </refsect2>
41  *
42  * Since 1.14, the use of libv4l2 has been disabled due to major bugs in the
43  * emulation layer. To enable usage of this library, set the environment
44  * variable GST_V4L2_USE_LIBV4L2=1.
45  */
46
47 #ifdef HAVE_CONFIG_H
48 #include <config.h>
49 #endif
50
51 #include <string.h>
52 #include <sys/time.h>
53 #include <unistd.h>
54
55 #include <gst/video/gstvideometa.h>
56 #include <gst/video/gstvideopool.h>
57
58 #include "gstv4l2src.h"
59
60 #include "gstv4l2colorbalance.h"
61 #include "gstv4l2tuner.h"
62 #include "gstv4l2vidorient.h"
63
64 #include "gst/gst-i18n-plugin.h"
65
66 GST_DEBUG_CATEGORY (v4l2src_debug);
67 #define GST_CAT_DEFAULT v4l2src_debug
68
69 #define DEFAULT_PROP_DEVICE   "/dev/video0"
70
71 enum
72 {
73   PROP_0,
74   V4L2_STD_OBJECT_PROPS,
75 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
76   PROP_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   PROP_LAST
82 };
83
84 /* signals and args */
85 enum
86 {
87   SIGNAL_PRE_SET_FORMAT,
88   LAST_SIGNAL
89 };
90
91 static guint gst_v4l2_signals[LAST_SIGNAL] = { 0 };
92
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);
96
97 static void gst_v4l2src_uri_handler_init (gpointer g_iface,
98     gpointer iface_data);
99
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));
108
109 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
110
111 /* element methods */
112 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
113     GstStateChange transition);
114
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,
123     GstQuery * query);
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);
128
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);
133
134 static void
135 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
136 {
137   GObjectClass *gobject_class;
138   GstElementClass *element_class;
139   GstBaseSrcClass *basesrc_class;
140   GstPushSrcClass *pushsrc_class;
141
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);
146
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;
150
151   element_class->change_state = gst_v4l2src_change_state;
152
153   gst_v4l2_object_install_properties_helper (gobject_class,
154       DEFAULT_PROP_DEVICE);
155
156 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
157   /**
158    * GstV4l2Src:camera-id:
159    *
160    * The value which is set by application will be used as a number of device node.
161    * ex) 1 -> /dev/video1
162    */
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 */
168
169 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
170   /**
171    * GstV4l2Src:auto-scan-device:
172    */
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 */
178
179   /**
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
184    *
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.
190    */
191   gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT] = g_signal_new ("prepare-format",
192       G_TYPE_FROM_CLASS (klass),
193       G_SIGNAL_RUN_LAST,
194       0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CAPS);
195
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>");
201
202   gst_element_class_add_pad_template
203       (element_class,
204       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
205           gst_v4l2_object_get_all_caps ()));
206
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);
216
217   pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
218
219   klass->v4l2_class_devices = NULL;
220
221   GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
222 }
223
224 static void
225 gst_v4l2src_init (GstV4l2Src * v4l2src)
226 {
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);
231
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 */
237
238   gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
239   gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
240 }
241
242
243 static void
244 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
245 {
246   gst_v4l2_object_destroy (v4l2src->v4l2object);
247
248   G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
249 }
250
251
252 static void
253 gst_v4l2src_set_property (GObject * object,
254     guint prop_id, const GValue * value, GParamSpec * pspec)
255 {
256   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
257
258   if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
259           prop_id, value, pspec)) {
260     switch (prop_id) {
261 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
262       case PROP_CAMERA_ID:
263         g_free (v4l2src->v4l2object->videodev);
264
265         v4l2src->camera_id = g_value_get_uint (value);
266         v4l2src->v4l2object->videodev = g_strdup_printf ("/dev/video%u", v4l2src->camera_id);
267
268         GST_INFO_OBJECT (v4l2src, "videodev [%s]", v4l2src->v4l2object->videodev);
269         break;
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);
275         break;
276 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
277       default:
278         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
279         break;
280     }
281   }
282 }
283
284 static void
285 gst_v4l2src_get_property (GObject * object,
286     guint prop_id, GValue * value, GParamSpec * pspec)
287 {
288   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
289
290   if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
291           prop_id, value, pspec)) {
292     switch (prop_id) {
293 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
294       case PROP_CAMERA_ID:
295         g_value_set_uint (value, v4l2src->camera_id);
296         break;
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);
302         break;
303 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
304       default:
305         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
306         break;
307     }
308   }
309 }
310
311 struct PreferedCapsInfo
312 {
313   gint width;
314   gint height;
315   gint fps_n;
316   gint fps_d;
317 };
318
319 static gboolean
320 gst_vl42_src_fixate_fields (GQuark field_id, GValue * value, gpointer user_data)
321 {
322   GstStructure *s = user_data;
323
324   if (field_id == g_quark_from_string ("interlace-mode"))
325     return TRUE;
326
327   if (field_id == g_quark_from_string ("colorimetry"))
328     return TRUE;
329
330   gst_structure_fixate_field (s, g_quark_to_string (field_id));
331
332   return TRUE;
333 }
334
335 static void
336 gst_v4l2_src_fixate_struct_with_preference (GstStructure * s,
337     struct PreferedCapsInfo *pref)
338 {
339   if (gst_structure_has_field (s, "width"))
340     gst_structure_fixate_field_nearest_int (s, "width", pref->width);
341
342   if (gst_structure_has_field (s, "height"))
343     gst_structure_fixate_field_nearest_int (s, "height", pref->height);
344
345   if (gst_structure_has_field (s, "framerate"))
346     gst_structure_fixate_field_nearest_fraction (s, "framerate", pref->fps_n,
347         pref->fps_d);
348
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);
352 }
353
354 static void
355 gst_v4l2_src_parse_fixed_struct (GstStructure * s,
356     gint * width, gint * height, gint * fps_n, gint * fps_d)
357 {
358   if (gst_structure_has_field (s, "width") && width)
359     gst_structure_get_int (s, "width", width);
360
361   if (gst_structure_has_field (s, "height") && height)
362     gst_structure_get_int (s, "height", height);
363
364   if (gst_structure_has_field (s, "framerate") && fps_n && fps_d)
365     gst_structure_get_fraction (s, "framerate", fps_n, fps_d);
366 }
367
368 /* TODO Consider framerate */
369 static gint
370 gst_v4l2src_fixed_caps_compare (GstCaps * caps_a, GstCaps * caps_b,
371     struct PreferedCapsInfo *pref)
372 {
373   GstStructure *a, *b;
374   gint aw = G_MAXINT, ah = G_MAXINT, ad = G_MAXINT;
375   gint bw = G_MAXINT, bh = G_MAXINT, bd = G_MAXINT;
376   gint ret;
377
378   a = gst_caps_get_structure (caps_a, 0);
379   b = gst_caps_get_structure (caps_b, 0);
380
381   gst_v4l2_src_parse_fixed_struct (a, &aw, &ah, NULL, NULL);
382   gst_v4l2_src_parse_fixed_struct (b, &bw, &bh, NULL, NULL);
383
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)) {
387     ret = 1;
388     goto done;
389   }
390
391   /* If a is smaller then pref and not b, then a goes after b */
392   if (aw < pref->width || ah < pref->height) {
393     ret = 1;
394     goto done;
395   }
396
397   /* If b is smaller then pref and not a, then a goes before b */
398   if (bw < pref->width || bh < pref->height) {
399     ret = -1;
400     goto done;
401   }
402
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);
406
407   /* Adjust slightly in case width/height matched the preference */
408   if (aw == pref->width)
409     ad -= 1;
410
411   if (ah == pref->height)
412     ad -= 1;
413
414   if (bw == pref->width)
415     bd -= 1;
416
417   if (bh == pref->height)
418     bd -= 1;
419
420   /* If the choices are equivalent, maintain the order */
421   if (ad == bd)
422     ret = 1;
423   else
424     ret = ad - bd;
425
426 done:
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"));
430   return ret;
431 }
432
433 static gboolean
434 gst_v4l2src_set_format (GstV4l2Src * v4l2src, GstCaps * caps,
435     GstV4l2Error * error)
436 {
437   GstV4l2Object *obj;
438
439   obj = v4l2src->v4l2object;
440
441   /* make sure we stop capturing and dealloc buffers */
442   if (!gst_v4l2_object_stop (obj))
443     return FALSE;
444
445   g_signal_emit (v4l2src, gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT], 0,
446       v4l2src->v4l2object->video_fd, caps);
447
448   return gst_v4l2_object_set_format (obj, caps, error);
449 }
450
451 static GstCaps *
452 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps, GstStructure * pref_s)
453 {
454   /* Let's prefer a good resolutiion as of today's standard. */
455   struct PreferedCapsInfo pref = {
456     3840, 2160, 120, 1
457   };
458   GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
459   GstV4l2Object *obj = v4l2src->v4l2object;
460   GList *caps_list = NULL;
461   GstStructure *s;
462   gint i = G_MAXINT;
463   GstV4l2Error error = GST_V4L2_ERROR_INIT;
464   GstCaps *fcaps = NULL;
465
466   GST_DEBUG_OBJECT (basesrc, "fixating caps %" GST_PTR_FORMAT, caps);
467
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. */
471   if (pref_s) {
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);
477   }
478
479   GST_DEBUG_OBJECT (basesrc, "Prefered size %ix%i", pref.width, pref.height);
480
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);
485
486     s = gst_caps_get_structure (tmp, 0);
487     gst_v4l2_src_fixate_struct_with_preference (s, &pref);
488
489     caps_list = g_list_insert_sorted_with_data (caps_list, tmp,
490         (GCompareDataFunc) gst_v4l2src_fixed_caps_compare, &pref);
491   }
492
493   gst_caps_unref (caps);
494   caps = gst_caps_new_empty ();
495
496   while (caps_list) {
497     GstCaps *tmp = caps_list->data;
498     caps_list = g_list_delete_link (caps_list, caps_list);
499     gst_caps_append (caps, tmp);
500   }
501
502   GST_DEBUG_OBJECT (basesrc, "sorted and normalized caps %" GST_PTR_FORMAT,
503       caps);
504
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);
509
510   for (i = 0; i < gst_caps_get_size (caps); ++i) {
511     gst_v4l2_clear_error (&error);
512     if (fcaps)
513       gst_caps_unref (fcaps);
514
515     fcaps = gst_caps_copy_nth (caps, i);
516
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);
522       break;
523     }
524
525     /* Just check if the format is acceptable, once we know
526      * no buffers should be outstanding we try S_FMT.
527      *
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))
534         break;
535
536       v4l2src->renegotiation_adjust = v4l2src->offset + 1;
537       v4l2src->pending_set_fmt = TRUE;
538       break;
539     }
540
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
543      * responding */
544     if (error.error->code != GST_RESOURCE_ERROR_SETTINGS) {
545       i = G_MAXINT;
546       break;
547     }
548   }
549
550   if (i >= gst_caps_get_size (caps)) {
551     gst_v4l2_error (v4l2src, &error);
552     if (fcaps)
553       gst_caps_unref (fcaps);
554     gst_caps_unref (caps);
555     return NULL;
556   }
557
558   gst_caps_unref (caps);
559
560   GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, fcaps);
561
562   return fcaps;
563 }
564
565 static gboolean
566 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
567 {
568   GstCaps *thiscaps;
569   GstCaps *caps = NULL;
570   GstCaps *peercaps = NULL;
571   gboolean result = FALSE;
572
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);
576
577   /* nothing or anything is allowed, we're done */
578   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
579     goto no_nego_needed;
580
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);
588
589     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
590
591     gst_caps_unref (thiscaps);
592   } else {
593     /* no peer or peer have ANY caps, work with our own caps then */
594     caps = thiscaps;
595   }
596
597   if (caps) {
598     /* now fixate */
599     if (!gst_caps_is_empty (caps)) {
600       GstStructure *pref = NULL;
601
602       if (peercaps && !gst_caps_is_any (peercaps))
603         pref = gst_caps_get_structure (peercaps, 0);
604
605       caps = gst_v4l2src_fixate (basesrc, caps, pref);
606
607       /* Fixating may fail as we now set the selected format */
608       if (!caps) {
609         result = FALSE;
610         goto done;
611       }
612
613       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
614
615       if (gst_caps_is_any (caps)) {
616         /* hmm, still anything, so element can do anything and
617          * nego is not needed */
618         result = TRUE;
619       } else if (gst_caps_is_fixed (caps)) {
620         /* yay, fixed caps, use those then */
621         result = gst_base_src_set_caps (basesrc, caps);
622       }
623     }
624     gst_caps_unref (caps);
625   }
626
627 done:
628   if (peercaps)
629     gst_caps_unref (peercaps);
630
631   return result;
632
633 no_nego_needed:
634   {
635     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
636     if (thiscaps)
637       gst_caps_unref (thiscaps);
638     return TRUE;
639   }
640 }
641
642 static GstCaps *
643 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
644 {
645   GstV4l2Src *v4l2src;
646   GstV4l2Object *obj;
647
648   v4l2src = GST_V4L2SRC (src);
649   obj = v4l2src->v4l2object;
650
651   if (!GST_V4L2_IS_OPEN (obj)) {
652     return gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (v4l2src));
653   }
654
655   return gst_v4l2_object_get_caps (obj, filter);
656 }
657
658 static gboolean
659 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
660 {
661   GstV4l2Src *src = GST_V4L2SRC (bsrc);
662   gboolean ret = TRUE;
663
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;
667
668     caps = gst_caps_make_writable (caps);
669     if (!(ret = gst_v4l2src_set_format (src, caps, &error)))
670       gst_v4l2_error (src, &error);
671
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;
679     GstBufferPool *pool;
680
681     gst_base_src_get_allocator (bsrc, &allocator, &params);
682     pool = gst_base_src_get_buffer_pool (bsrc);
683
684     if (gst_query_get_n_allocation_params (query))
685       gst_query_set_nth_allocation_param (query, 0, allocator, &params);
686     else
687       gst_query_add_allocation_param (query, allocator, &params);
688
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);
692     else
693       gst_query_add_allocation_pool (query, pool, src->v4l2object->info.size, 1,
694           0);
695
696     if (pool)
697       gst_object_unref (pool);
698     if (allocator)
699       gst_object_unref (allocator);
700
701     return GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
702   }
703
704   if (ret) {
705     ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
706     if (ret)
707       ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
708   }
709
710   if (ret) {
711     if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
712       goto activate_failed;
713   }
714
715   return ret;
716
717 activate_failed:
718   {
719     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
720         (_("Failed to allocate required memory.")),
721         ("Buffer pool activation failed"));
722     return FALSE;
723   }
724 }
725
726 static gboolean
727 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
728 {
729   GstV4l2Src *src;
730   GstV4l2Object *obj;
731   gboolean res = FALSE;
732
733   src = GST_V4L2SRC (bsrc);
734   obj = src->v4l2object;
735
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;
741
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 !");
746         goto done;
747       }
748
749       fps_n = GST_V4L2_FPS_N (obj);
750       fps_d = GST_V4L2_FPS_D (obj);
751
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 !");
756         goto done;
757       }
758
759       /* min latency is the time to capture one frame */
760       min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
761
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;
765
766       if (num_buffers == 0)
767         max_latency = -1;
768       else
769         max_latency = num_buffers * min_latency;
770
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));
774
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);
778
779       res = TRUE;
780       break;
781     }
782     default:
783       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
784       break;
785   }
786
787 done:
788
789   return res;
790 }
791
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.
795  */
796 static gboolean
797 gst_v4l2src_start (GstBaseSrc * src)
798 {
799   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
800
801   v4l2src->offset = 0;
802   v4l2src->renegotiation_adjust = 0;
803
804   /* activate settings for first frame */
805   v4l2src->ctrl_time = 0;
806   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
807
808   v4l2src->has_bad_timestamp = FALSE;
809   v4l2src->last_timestamp = 0;
810
811   return TRUE;
812 }
813
814 static gboolean
815 gst_v4l2src_unlock (GstBaseSrc * src)
816 {
817   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
818   return gst_v4l2_object_unlock (v4l2src->v4l2object);
819 }
820
821 static gboolean
822 gst_v4l2src_unlock_stop (GstBaseSrc * src)
823 {
824   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
825
826   v4l2src->last_timestamp = 0;
827
828   return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
829 }
830
831 static gboolean
832 gst_v4l2src_stop (GstBaseSrc * src)
833 {
834   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
835   GstV4l2Object *obj = v4l2src->v4l2object;
836
837   if (GST_V4L2_IS_ACTIVE (obj)) {
838     if (!gst_v4l2_object_stop (obj))
839       return FALSE;
840   }
841
842   v4l2src->pending_set_fmt = FALSE;
843
844   return TRUE;
845 }
846
847 static GstStateChangeReturn
848 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
849 {
850   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
851   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
852   GstV4l2Object *obj = v4l2src->v4l2object;
853
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;
859       break;
860     default:
861       break;
862   }
863
864   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
865
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;
871
872       break;
873     default:
874       break;
875   }
876
877   return ret;
878 }
879
880 static GstFlowReturn
881 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
882 {
883   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
884   GstV4l2Object *obj = v4l2src->v4l2object;
885   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
886   GstFlowReturn ret;
887   GstClock *clock;
888   GstClockTime abs_time, base_time, timestamp, duration;
889   GstClockTime delay;
890   GstMessage *qos_msg;
891
892   do {
893     ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
894         obj->info.size, buf);
895
896     if (G_UNLIKELY (ret != GST_FLOW_OK))
897       goto alloc_failed;
898
899     ret = gst_v4l2_buffer_pool_process (pool, buf);
900
901   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
902
903   if (G_UNLIKELY (ret != GST_FLOW_OK))
904     goto error;
905
906   timestamp = GST_BUFFER_TIMESTAMP (*buf);
907   duration = obj->duration;
908
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);
916   } else {
917     /* no clock, can't set timestamps */
918     base_time = GST_CLOCK_TIME_NONE;
919   }
920   GST_OBJECT_UNLOCK (v4l2src);
921
922   /* sample pipeline clock */
923   if (clock) {
924     abs_time = gst_clock_get_time (clock);
925     gst_object_unref (clock);
926   } else {
927     abs_time = GST_CLOCK_TIME_NONE;
928   }
929
930 retry:
931   if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
932     struct timespec now;
933     GstClockTime gstnow;
934
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);
940
941     if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
942       GTimeVal now;
943
944       /* very large diff, fall back to system time */
945       g_get_current_time (&now);
946       gstnow = GST_TIMEVAL_TO_TIME (now);
947     }
948
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
955      * */
956     if (timestamp > gstnow) {
957       GST_WARNING_OBJECT (v4l2src,
958           "Timestamp in the future detected, ignoring driver timestamps");
959       v4l2src->has_bad_timestamp = TRUE;
960       goto retry;
961     }
962
963     if (v4l2src->last_timestamp > timestamp) {
964       GST_WARNING_OBJECT (v4l2src,
965           "Timestamp going backward, ignoring driver timestamps");
966       v4l2src->has_bad_timestamp = TRUE;
967       goto retry;
968     }
969
970     delay = gstnow - timestamp;
971
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;
976       goto retry;
977     }
978
979     /* Save last timestamp for sanity checks */
980     v4l2src->last_timestamp = timestamp;
981
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));
985   } else {
986     /* we assume 1 frame latency otherwise */
987     if (GST_CLOCK_TIME_IS_VALID (duration))
988       delay = duration;
989     else
990       delay = 0;
991   }
992
993   /* set buffer metadata */
994
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;
998
999     /* adjust for delay in the device */
1000     if (timestamp > delay)
1001       timestamp -= delay;
1002     else
1003       timestamp = 0;
1004   } else {
1005     timestamp = GST_CLOCK_TIME_NONE;
1006   }
1007
1008   /* activate settings for next frame */
1009   if (GST_CLOCK_TIME_IS_VALID (duration)) {
1010     v4l2src->ctrl_time += duration;
1011   } else {
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)
1014      */
1015     v4l2src->ctrl_time = timestamp;
1016   }
1017   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
1018
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));
1021
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;
1028   } else {
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));
1040
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);
1046
1047     }
1048     v4l2src->offset = GST_BUFFER_OFFSET (*buf);
1049   }
1050
1051   GST_BUFFER_TIMESTAMP (*buf) = timestamp;
1052   GST_BUFFER_DURATION (*buf) = duration;
1053
1054   return ret;
1055
1056   /* ERROR */
1057 alloc_failed:
1058   {
1059     if (ret != GST_FLOW_FLUSHING)
1060       GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
1061           ("Failed to allocate a buffer"), (NULL));
1062     return ret;
1063   }
1064 error:
1065   {
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;
1072     } else {
1073       GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
1074           gst_flow_get_name (ret));
1075     }
1076     return ret;
1077   }
1078 }
1079
1080
1081 /* GstURIHandler interface */
1082 static GstURIType
1083 gst_v4l2src_uri_get_type (GType type)
1084 {
1085   return GST_URI_SRC;
1086 }
1087
1088 static const gchar *const *
1089 gst_v4l2src_uri_get_protocols (GType type)
1090 {
1091   static const gchar *protocols[] = { "v4l2", NULL };
1092
1093   return protocols;
1094 }
1095
1096 static gchar *
1097 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
1098 {
1099   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1100
1101   if (v4l2src->v4l2object->videodev != NULL) {
1102     return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
1103   }
1104
1105   return g_strdup ("v4l2://");
1106 }
1107
1108 static gboolean
1109 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1110     GError ** error)
1111 {
1112   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1113   const gchar *device = DEFAULT_PROP_DEVICE;
1114
1115   if (strcmp (uri, "v4l2://") != 0) {
1116     device = uri + 7;
1117   }
1118   g_object_set (v4l2src, "device", device, NULL);
1119
1120   return TRUE;
1121 }
1122
1123
1124 static void
1125 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1126 {
1127   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1128
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;
1133 }