v4l2: use v4l2 capture device sequence counter
[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@indt.org.br>
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 gboolean gst_v4l2src_set_caps (GstBaseSrc * src, GstCaps * caps);
111 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter);
112 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
113 static gboolean gst_v4l2src_decide_allocation (GstBaseSrc * src,
114     GstQuery * query);
115 static GstFlowReturn gst_v4l2src_create (GstPushSrc * src, GstBuffer ** out);
116 static GstCaps *gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps);
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@indt.org.br>, "
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->set_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_set_caps);
178   basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
179   basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
180   basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
181   basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
182   basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
183   basesrc_class->fixate = GST_DEBUG_FUNCPTR (gst_v4l2src_fixate);
184   basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
185   basesrc_class->decide_allocation =
186       GST_DEBUG_FUNCPTR (gst_v4l2src_decide_allocation);
187
188   pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
189
190   klass->v4l2_class_devices = NULL;
191
192   GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
193 }
194
195 static void
196 gst_v4l2src_init (GstV4l2Src * v4l2src)
197 {
198   /* fixme: give an update_fps_function */
199   v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
200       V4L2_BUF_TYPE_VIDEO_CAPTURE, DEFAULT_PROP_DEVICE,
201       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
202
203   gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
204   gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
205 }
206
207
208 static void
209 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
210 {
211   gst_v4l2_object_destroy (v4l2src->v4l2object);
212
213   G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
214 }
215
216
217 static void
218 gst_v4l2src_set_property (GObject * object,
219     guint prop_id, const GValue * value, GParamSpec * pspec)
220 {
221   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
222
223   if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
224           prop_id, value, pspec)) {
225     switch (prop_id) {
226       default:
227         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
228         break;
229     }
230   }
231 }
232
233 static void
234 gst_v4l2src_get_property (GObject * object,
235     guint prop_id, GValue * value, GParamSpec * pspec)
236 {
237   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
238
239   if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
240           prop_id, value, pspec)) {
241     switch (prop_id) {
242       default:
243         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
244         break;
245     }
246   }
247 }
248
249 /* this function is a bit of a last resort */
250 static GstCaps *
251 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps)
252 {
253   GstStructure *structure;
254   gint i;
255
256   GST_DEBUG_OBJECT (basesrc, "fixating caps %" GST_PTR_FORMAT, caps);
257
258   caps = gst_caps_make_writable (caps);
259
260   for (i = 0; i < gst_caps_get_size (caps); ++i) {
261     structure = gst_caps_get_structure (caps, i);
262
263     /* We are fixating to a reasonable 320x200 resolution
264        and the maximum framerate resolution for that size */
265     if (gst_structure_has_field (structure, "width"))
266       gst_structure_fixate_field_nearest_int (structure, "width", 320);
267
268     if (gst_structure_has_field (structure, "height"))
269       gst_structure_fixate_field_nearest_int (structure, "height", 200);
270
271     if (gst_structure_has_field (structure, "framerate"))
272       gst_structure_fixate_field_nearest_fraction (structure, "framerate",
273           G_MAXINT, 1);
274
275     if (gst_structure_has_field (structure, "format"))
276       gst_structure_fixate_field (structure, "format");
277
278     if (gst_structure_has_field (structure, "interlace-mode"))
279       gst_structure_fixate_field (structure, "interlace-mode");
280   }
281
282   GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, caps);
283
284   caps = GST_BASE_SRC_CLASS (parent_class)->fixate (basesrc, caps);
285
286   return caps;
287 }
288
289
290 static gboolean
291 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
292 {
293   GstCaps *thiscaps;
294   GstCaps *caps = NULL;
295   GstCaps *peercaps = NULL;
296   gboolean result = FALSE;
297
298   /* first see what is possible on our source pad */
299   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
300   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
301   LOG_CAPS (basesrc, thiscaps);
302
303   /* nothing or anything is allowed, we're done */
304   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
305     goto no_nego_needed;
306
307   /* get the peer caps without a filter as we'll filter ourselves later on */
308   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
309   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
310   LOG_CAPS (basesrc, peercaps);
311   if (peercaps && !gst_caps_is_any (peercaps)) {
312     GstCaps *icaps = NULL;
313     int i;
314
315     /* Prefer the first caps we are compatible with that the peer proposed */
316     for (i = 0; i < gst_caps_get_size (peercaps); i++) {
317       /* get intersection */
318       GstCaps *ipcaps = gst_caps_copy_nth (peercaps, i);
319
320       GST_DEBUG_OBJECT (basesrc, "peer: %" GST_PTR_FORMAT, ipcaps);
321       LOG_CAPS (basesrc, ipcaps);
322
323       icaps = gst_caps_intersect (thiscaps, ipcaps);
324       gst_caps_unref (ipcaps);
325
326       if (!gst_caps_is_empty (icaps))
327         break;
328
329       gst_caps_unref (icaps);
330       icaps = NULL;
331     }
332
333     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, icaps);
334     LOG_CAPS (basesrc, icaps);
335     if (icaps) {
336       /* If there are multiple intersections pick the one with the smallest
337        * resolution strictly bigger then the first peer caps */
338       if (gst_caps_get_size (icaps) > 1) {
339         GstStructure *s = gst_caps_get_structure (peercaps, 0);
340         int best = 0;
341         int twidth, theight;
342         int width = G_MAXINT, height = G_MAXINT;
343
344         if (gst_structure_get_int (s, "width", &twidth)
345             && gst_structure_get_int (s, "height", &theight)) {
346
347           /* Walk the structure backwards to get the first entry of the
348            * smallest resolution bigger (or equal to) the preferred resolution)
349            */
350           for (i = gst_caps_get_size (icaps) - 1; i >= 0; i--) {
351             GstStructure *is = gst_caps_get_structure (icaps, i);
352             int w, h;
353
354             if (gst_structure_get_int (is, "width", &w)
355                 && gst_structure_get_int (is, "height", &h)) {
356               if (w >= twidth && w <= width && h >= theight && h <= height) {
357                 width = w;
358                 height = h;
359                 best = i;
360               }
361             }
362           }
363         }
364
365         caps = gst_caps_copy_nth (icaps, best);
366         gst_caps_unref (icaps);
367       } else {
368         caps = icaps;
369       }
370     }
371     gst_caps_unref (thiscaps);
372   } else {
373     /* no peer or peer have ANY caps, work with our own caps then */
374     caps = thiscaps;
375   }
376   if (peercaps)
377     gst_caps_unref (peercaps);
378   if (caps) {
379     caps = gst_caps_truncate (caps);
380
381     /* now fixate */
382     if (!gst_caps_is_empty (caps)) {
383       caps = gst_v4l2src_fixate (basesrc, caps);
384       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
385       LOG_CAPS (basesrc, caps);
386
387       if (gst_caps_is_any (caps)) {
388         /* hmm, still anything, so element can do anything and
389          * nego is not needed */
390         result = TRUE;
391       } else if (gst_caps_is_fixed (caps)) {
392         /* yay, fixed caps, use those then */
393         result = gst_base_src_set_caps (basesrc, caps);
394       }
395     }
396     gst_caps_unref (caps);
397   }
398   return result;
399
400 no_nego_needed:
401   {
402     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
403     if (thiscaps)
404       gst_caps_unref (thiscaps);
405     return TRUE;
406   }
407 }
408
409 static GstCaps *
410 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
411 {
412   GstV4l2Src *v4l2src;
413   GstV4l2Object *obj;
414
415   v4l2src = GST_V4L2SRC (src);
416   obj = v4l2src->v4l2object;
417
418   if (!GST_V4L2_IS_OPEN (obj)) {
419     return gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (v4l2src));
420   }
421
422   return gst_v4l2_object_get_caps (obj, filter);
423 }
424
425 static gboolean
426 gst_v4l2src_set_format (GstV4l2Src * v4l2src, GstCaps * caps)
427 {
428   GstV4l2Object *obj;
429
430   obj = v4l2src->v4l2object;
431
432   g_signal_emit (v4l2src, gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT], 0,
433       v4l2src->v4l2object->video_fd, caps);
434
435   if (!gst_v4l2_object_set_format (obj, caps))
436     /* error already posted */
437     return FALSE;
438
439   return TRUE;
440 }
441
442 static gboolean
443 gst_v4l2src_set_caps (GstBaseSrc * src, GstCaps * caps)
444 {
445   GstV4l2Src *v4l2src;
446   GstV4l2Object *obj;
447
448   v4l2src = GST_V4L2SRC (src);
449   obj = v4l2src->v4l2object;
450
451   /* make sure the caps changed before doing anything */
452   if (gst_v4l2_object_caps_equal (obj, caps))
453     return TRUE;
454
455   if (GST_V4L2_IS_ACTIVE (obj)) {
456     /* Just check if the format is acceptable, once we know
457      * no buffers should be outstanding we try S_FMT.
458      *
459      * Basesrc will do an allocation query that
460      * should indirectly reclaim buffers, after that we can
461      * set the format and then configure our pool */
462     if (gst_v4l2_object_try_format (obj, caps))
463       v4l2src->pending_set_fmt = TRUE;
464     else
465       return FALSE;
466   } else {
467     /* make sure we stop capturing and dealloc buffers */
468     if (!gst_v4l2_object_stop (obj))
469       return FALSE;
470
471     return gst_v4l2src_set_format (v4l2src, caps);
472   }
473
474   return TRUE;
475 }
476
477 static gboolean
478 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
479 {
480   GstV4l2Src *src = GST_V4L2SRC (bsrc);
481   gboolean ret = TRUE;
482
483   if (src->pending_set_fmt) {
484     GstCaps *caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
485
486     if (!gst_v4l2_object_stop (src->v4l2object))
487       return FALSE;
488     ret = gst_v4l2src_set_format (src, caps);
489     gst_caps_unref (caps);
490     src->pending_set_fmt = FALSE;
491   }
492
493   if (ret) {
494     ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
495     if (ret)
496       ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
497   }
498
499   if (ret) {
500     if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
501       goto activate_failed;
502   }
503
504   return ret;
505
506 activate_failed:
507   {
508     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
509         (_("Failed to allocate required memory.")),
510         ("Buffer pool activation failed"));
511     return FALSE;
512   }
513 }
514
515 static gboolean
516 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
517 {
518   GstV4l2Src *src;
519   GstV4l2Object *obj;
520   gboolean res = FALSE;
521
522   src = GST_V4L2SRC (bsrc);
523   obj = src->v4l2object;
524
525   switch (GST_QUERY_TYPE (query)) {
526     case GST_QUERY_LATENCY:{
527       GstClockTime min_latency, max_latency;
528       guint32 fps_n, fps_d;
529       guint num_buffers = 0;
530
531       /* device must be open */
532       if (!GST_V4L2_IS_OPEN (obj)) {
533         GST_WARNING_OBJECT (src,
534             "Can't give latency since device isn't open !");
535         goto done;
536       }
537
538       fps_n = GST_V4L2_FPS_N (obj);
539       fps_d = GST_V4L2_FPS_D (obj);
540
541       /* we must have a framerate */
542       if (fps_n <= 0 || fps_d <= 0) {
543         GST_WARNING_OBJECT (src,
544             "Can't give latency since framerate isn't fixated !");
545         goto done;
546       }
547
548       /* min latency is the time to capture one frame */
549       min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
550
551       /* max latency is total duration of the frame buffer */
552       if (obj->pool != NULL)
553         num_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_latency;
554
555       if (num_buffers == 0)
556         max_latency = -1;
557       else
558         max_latency = num_buffers * min_latency;
559
560       GST_DEBUG_OBJECT (bsrc,
561           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
562           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
563
564       /* we are always live, the min latency is 1 frame and the max latency is
565        * the complete buffer of frames. */
566       gst_query_set_latency (query, TRUE, min_latency, max_latency);
567
568       res = TRUE;
569       break;
570     }
571     default:
572       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
573       break;
574   }
575
576 done:
577
578   return res;
579 }
580
581 /* start and stop are not symmetric -- start will open the device, but not start
582  * capture. it's setcaps that will start capture, which is called via basesrc's
583  * negotiate method. stop will both stop capture and close the device.
584  */
585 static gboolean
586 gst_v4l2src_start (GstBaseSrc * src)
587 {
588   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
589
590   v4l2src->offset = 0;
591
592   /* activate settings for first frame */
593   v4l2src->ctrl_time = 0;
594   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
595
596   v4l2src->has_bad_timestamp = FALSE;
597   v4l2src->last_timestamp = 0;
598
599   return TRUE;
600 }
601
602 static gboolean
603 gst_v4l2src_unlock (GstBaseSrc * src)
604 {
605   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
606   return gst_v4l2_object_unlock (v4l2src->v4l2object);
607 }
608
609 static gboolean
610 gst_v4l2src_unlock_stop (GstBaseSrc * src)
611 {
612   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
613
614   v4l2src->last_timestamp = 0;
615
616   return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
617 }
618
619 static gboolean
620 gst_v4l2src_stop (GstBaseSrc * src)
621 {
622   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
623   GstV4l2Object *obj = v4l2src->v4l2object;
624
625   if (GST_V4L2_IS_ACTIVE (obj)) {
626     if (!gst_v4l2_object_stop (obj))
627       return FALSE;
628   }
629
630   v4l2src->pending_set_fmt = FALSE;
631
632   return TRUE;
633 }
634
635 static GstStateChangeReturn
636 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
637 {
638   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
639   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
640   GstV4l2Object *obj = v4l2src->v4l2object;
641
642   switch (transition) {
643     case GST_STATE_CHANGE_NULL_TO_READY:
644       /* open the device */
645       if (!gst_v4l2_object_open (obj))
646         return GST_STATE_CHANGE_FAILURE;
647       break;
648     default:
649       break;
650   }
651
652   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
653
654   switch (transition) {
655     case GST_STATE_CHANGE_READY_TO_NULL:
656       /* close the device */
657       if (!gst_v4l2_object_close (obj))
658         return GST_STATE_CHANGE_FAILURE;
659
660       break;
661     default:
662       break;
663   }
664
665   return ret;
666 }
667
668 static GstFlowReturn
669 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
670 {
671   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
672   GstV4l2Object *obj = v4l2src->v4l2object;
673   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
674   GstFlowReturn ret;
675   GstClock *clock;
676   GstClockTime abs_time, base_time, timestamp, duration;
677   GstClockTime delay;
678
679   do {
680     ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
681         obj->info.size, buf);
682
683     if (G_UNLIKELY (ret != GST_FLOW_OK))
684       goto alloc_failed;
685
686     ret = gst_v4l2_buffer_pool_process (pool, buf);
687
688   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
689
690   if (G_UNLIKELY (ret != GST_FLOW_OK))
691     goto error;
692
693   timestamp = GST_BUFFER_TIMESTAMP (*buf);
694   duration = obj->duration;
695
696   /* timestamps, LOCK to get clock and base time. */
697   /* FIXME: element clock and base_time is rarely changing */
698   GST_OBJECT_LOCK (v4l2src);
699   if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
700     /* we have a clock, get base time and ref clock */
701     base_time = GST_ELEMENT (v4l2src)->base_time;
702     gst_object_ref (clock);
703   } else {
704     /* no clock, can't set timestamps */
705     base_time = GST_CLOCK_TIME_NONE;
706   }
707   GST_OBJECT_UNLOCK (v4l2src);
708
709   /* sample pipeline clock */
710   if (clock) {
711     abs_time = gst_clock_get_time (clock);
712     gst_object_unref (clock);
713   } else {
714     abs_time = GST_CLOCK_TIME_NONE;
715   }
716
717 retry:
718   if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
719     struct timespec now;
720     GstClockTime gstnow;
721
722     /* v4l2 specs say to use the system time although many drivers switched to
723      * the more desirable monotonic time. We first try to use the monotonic time
724      * and see how that goes */
725     clock_gettime (CLOCK_MONOTONIC, &now);
726     gstnow = GST_TIMESPEC_TO_TIME (now);
727
728     if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
729       GTimeVal now;
730
731       /* very large diff, fall back to system time */
732       g_get_current_time (&now);
733       gstnow = GST_TIMEVAL_TO_TIME (now);
734     }
735
736     /* Detect buggy drivers here, and stop using their timestamp. Failing any
737      * of these condition would imply a very buggy driver:
738      *   - Timestamp in the future
739      *   - Timestamp is going backward compare to last seen timestamp
740      *   - Timestamp is jumping forward for less then a frame duration
741      *   - Delay is bigger then the actual timestamp
742      * */
743     if (timestamp > gstnow) {
744       GST_WARNING_OBJECT (v4l2src,
745           "Timestamp in the future detected, ignoring driver timestamps");
746       v4l2src->has_bad_timestamp = TRUE;
747       goto retry;
748     }
749
750     if (v4l2src->last_timestamp > timestamp) {
751       GST_WARNING_OBJECT (v4l2src,
752           "Timestamp going backward, ignoring driver timestamps");
753       v4l2src->has_bad_timestamp = TRUE;
754       goto retry;
755     }
756
757     delay = gstnow - timestamp;
758
759     if (delay > timestamp) {
760       GST_WARNING_OBJECT (v4l2src,
761           "Timestamp does not correlate with any clock, ignoring driver timestamps");
762       v4l2src->has_bad_timestamp = TRUE;
763       goto retry;
764     }
765
766     /* Save last timestamp for sanity checks */
767     v4l2src->last_timestamp = timestamp;
768
769     GST_DEBUG_OBJECT (v4l2src, "ts: %" GST_TIME_FORMAT " now %" GST_TIME_FORMAT
770         " delay %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
771         GST_TIME_ARGS (gstnow), GST_TIME_ARGS (delay));
772   } else {
773     /* we assume 1 frame latency otherwise */
774     if (GST_CLOCK_TIME_IS_VALID (duration))
775       delay = duration;
776     else
777       delay = 0;
778   }
779
780   /* set buffer metadata */
781
782   /* use generated offset values only if there are not already valid ones
783    * set by the v4l2 device */
784   if (!GST_BUFFER_OFFSET_IS_VALID (*buf) || !GST_BUFFER_OFFSET_END_IS_VALID (*buf)) {
785     GST_BUFFER_OFFSET (*buf) = v4l2src->offset++;
786     GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset;
787   }
788
789   if (G_LIKELY (abs_time != GST_CLOCK_TIME_NONE)) {
790     /* the time now is the time of the clock minus the base time */
791     timestamp = abs_time - base_time;
792
793     /* adjust for delay in the device */
794     if (timestamp > delay)
795       timestamp -= delay;
796     else
797       timestamp = 0;
798   } else {
799     timestamp = GST_CLOCK_TIME_NONE;
800   }
801
802   /* activate settings for next frame */
803   if (GST_CLOCK_TIME_IS_VALID (duration)) {
804     v4l2src->ctrl_time += duration;
805   } else {
806     /* this is not very good (as it should be the next timestamp),
807      * still good enough for linear fades (as long as it is not -1)
808      */
809     v4l2src->ctrl_time = timestamp;
810   }
811   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
812
813   GST_INFO_OBJECT (src, "sync to %" GST_TIME_FORMAT " out ts %" GST_TIME_FORMAT,
814       GST_TIME_ARGS (v4l2src->ctrl_time), GST_TIME_ARGS (timestamp));
815
816   GST_BUFFER_TIMESTAMP (*buf) = timestamp;
817   GST_BUFFER_DURATION (*buf) = duration;
818
819   return ret;
820
821   /* ERROR */
822 alloc_failed:
823   {
824     if (ret != GST_FLOW_FLUSHING)
825       GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
826           ("Failed to allocate a buffer"), (NULL));
827     return ret;
828   }
829 error:
830   {
831     if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
832       GST_ELEMENT_ERROR (src, RESOURCE, FAILED,
833           ("Driver returned a buffer with no payload, this most likely "
834               "indicate a bug in the driver."), (NULL));
835       ret = GST_FLOW_ERROR;
836     } else {
837       GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
838           gst_flow_get_name (ret));
839     }
840     return ret;
841   }
842 }
843
844
845 /* GstURIHandler interface */
846 static GstURIType
847 gst_v4l2src_uri_get_type (GType type)
848 {
849   return GST_URI_SRC;
850 }
851
852 static const gchar *const *
853 gst_v4l2src_uri_get_protocols (GType type)
854 {
855   static const gchar *protocols[] = { "v4l2", NULL };
856
857   return protocols;
858 }
859
860 static gchar *
861 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
862 {
863   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
864
865   if (v4l2src->v4l2object->videodev != NULL) {
866     return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
867   }
868
869   return g_strdup ("v4l2://");
870 }
871
872 static gboolean
873 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
874     GError ** error)
875 {
876   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
877   const gchar *device = DEFAULT_PROP_DEVICE;
878
879   if (strcmp (uri, "v4l2://") != 0) {
880     device = uri + 7;
881   }
882   g_object_set (v4l2src, "device", device, NULL);
883
884   return TRUE;
885 }
886
887
888 static void
889 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
890 {
891   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
892
893   iface->get_type = gst_v4l2src_uri_get_type;
894   iface->get_protocols = gst_v4l2src_uri_get_protocols;
895   iface->get_uri = gst_v4l2src_uri_get_uri;
896   iface->set_uri = gst_v4l2src_uri_set_uri;
897 }