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