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