235eda471c92c682cc0fd12635d1aa1518068ee1
[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           100, 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->renegotiation_adjust = v4l2src->offset + 1;
464       v4l2src->pending_set_fmt = TRUE;
465     } else
466       return FALSE;
467   } else {
468     /* make sure we stop capturing and dealloc buffers */
469     if (!gst_v4l2_object_stop (obj))
470       return FALSE;
471
472     return gst_v4l2src_set_format (v4l2src, caps);
473   }
474
475   return TRUE;
476 }
477
478 static gboolean
479 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
480 {
481   GstV4l2Src *src = GST_V4L2SRC (bsrc);
482   gboolean ret = TRUE;
483
484   if (src->pending_set_fmt) {
485     GstCaps *caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
486
487     if (!gst_v4l2_object_stop (src->v4l2object))
488       return FALSE;
489     ret = gst_v4l2src_set_format (src, caps);
490     gst_caps_unref (caps);
491     src->pending_set_fmt = FALSE;
492   }
493
494   if (ret) {
495     ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
496     if (ret)
497       ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
498   }
499
500   if (ret) {
501     if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
502       goto activate_failed;
503   }
504
505   return ret;
506
507 activate_failed:
508   {
509     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
510         (_("Failed to allocate required memory.")),
511         ("Buffer pool activation failed"));
512     return FALSE;
513   }
514 }
515
516 static gboolean
517 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
518 {
519   GstV4l2Src *src;
520   GstV4l2Object *obj;
521   gboolean res = FALSE;
522
523   src = GST_V4L2SRC (bsrc);
524   obj = src->v4l2object;
525
526   switch (GST_QUERY_TYPE (query)) {
527     case GST_QUERY_LATENCY:{
528       GstClockTime min_latency, max_latency;
529       guint32 fps_n, fps_d;
530       guint num_buffers = 0;
531
532       /* device must be open */
533       if (!GST_V4L2_IS_OPEN (obj)) {
534         GST_WARNING_OBJECT (src,
535             "Can't give latency since device isn't open !");
536         goto done;
537       }
538
539       fps_n = GST_V4L2_FPS_N (obj);
540       fps_d = GST_V4L2_FPS_D (obj);
541
542       /* we must have a framerate */
543       if (fps_n <= 0 || fps_d <= 0) {
544         GST_WARNING_OBJECT (src,
545             "Can't give latency since framerate isn't fixated !");
546         goto done;
547       }
548
549       /* min latency is the time to capture one frame */
550       min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
551
552       /* max latency is total duration of the frame buffer */
553       if (obj->pool != NULL)
554         num_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_latency;
555
556       if (num_buffers == 0)
557         max_latency = -1;
558       else
559         max_latency = num_buffers * min_latency;
560
561       GST_DEBUG_OBJECT (bsrc,
562           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
563           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
564
565       /* we are always live, the min latency is 1 frame and the max latency is
566        * the complete buffer of frames. */
567       gst_query_set_latency (query, TRUE, min_latency, max_latency);
568
569       res = TRUE;
570       break;
571     }
572     default:
573       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
574       break;
575   }
576
577 done:
578
579   return res;
580 }
581
582 /* start and stop are not symmetric -- start will open the device, but not start
583  * capture. it's setcaps that will start capture, which is called via basesrc's
584  * negotiate method. stop will both stop capture and close the device.
585  */
586 static gboolean
587 gst_v4l2src_start (GstBaseSrc * src)
588 {
589   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
590
591   v4l2src->offset = 0;
592   v4l2src->renegotiation_adjust = 0;
593
594   /* activate settings for first frame */
595   v4l2src->ctrl_time = 0;
596   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
597
598   v4l2src->has_bad_timestamp = FALSE;
599   v4l2src->last_timestamp = 0;
600
601   return TRUE;
602 }
603
604 static gboolean
605 gst_v4l2src_unlock (GstBaseSrc * src)
606 {
607   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
608   return gst_v4l2_object_unlock (v4l2src->v4l2object);
609 }
610
611 static gboolean
612 gst_v4l2src_unlock_stop (GstBaseSrc * src)
613 {
614   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
615
616   v4l2src->last_timestamp = 0;
617
618   return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
619 }
620
621 static gboolean
622 gst_v4l2src_stop (GstBaseSrc * src)
623 {
624   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
625   GstV4l2Object *obj = v4l2src->v4l2object;
626
627   if (GST_V4L2_IS_ACTIVE (obj)) {
628     if (!gst_v4l2_object_stop (obj))
629       return FALSE;
630   }
631
632   v4l2src->pending_set_fmt = FALSE;
633
634   return TRUE;
635 }
636
637 static GstStateChangeReturn
638 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
639 {
640   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
641   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
642   GstV4l2Object *obj = v4l2src->v4l2object;
643
644   switch (transition) {
645     case GST_STATE_CHANGE_NULL_TO_READY:
646       /* open the device */
647       if (!gst_v4l2_object_open (obj))
648         return GST_STATE_CHANGE_FAILURE;
649       break;
650     default:
651       break;
652   }
653
654   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
655
656   switch (transition) {
657     case GST_STATE_CHANGE_READY_TO_NULL:
658       /* close the device */
659       if (!gst_v4l2_object_close (obj))
660         return GST_STATE_CHANGE_FAILURE;
661
662       break;
663     default:
664       break;
665   }
666
667   return ret;
668 }
669
670 static GstFlowReturn
671 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
672 {
673   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
674   GstV4l2Object *obj = v4l2src->v4l2object;
675   GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
676   GstFlowReturn ret;
677   GstClock *clock;
678   GstClockTime abs_time, base_time, timestamp, duration;
679   GstClockTime delay;
680   GstMessage *qos_msg;
681
682   do {
683     ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
684         obj->info.size, buf);
685
686     if (G_UNLIKELY (ret != GST_FLOW_OK))
687       goto alloc_failed;
688
689     ret = gst_v4l2_buffer_pool_process (pool, buf);
690
691   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER);
692
693   if (G_UNLIKELY (ret != GST_FLOW_OK))
694     goto error;
695
696   timestamp = GST_BUFFER_TIMESTAMP (*buf);
697   duration = obj->duration;
698
699   /* timestamps, LOCK to get clock and base time. */
700   /* FIXME: element clock and base_time is rarely changing */
701   GST_OBJECT_LOCK (v4l2src);
702   if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
703     /* we have a clock, get base time and ref clock */
704     base_time = GST_ELEMENT (v4l2src)->base_time;
705     gst_object_ref (clock);
706   } else {
707     /* no clock, can't set timestamps */
708     base_time = GST_CLOCK_TIME_NONE;
709   }
710   GST_OBJECT_UNLOCK (v4l2src);
711
712   /* sample pipeline clock */
713   if (clock) {
714     abs_time = gst_clock_get_time (clock);
715     gst_object_unref (clock);
716   } else {
717     abs_time = GST_CLOCK_TIME_NONE;
718   }
719
720 retry:
721   if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
722     struct timespec now;
723     GstClockTime gstnow;
724
725     /* v4l2 specs say to use the system time although many drivers switched to
726      * the more desirable monotonic time. We first try to use the monotonic time
727      * and see how that goes */
728     clock_gettime (CLOCK_MONOTONIC, &now);
729     gstnow = GST_TIMESPEC_TO_TIME (now);
730
731     if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
732       GTimeVal now;
733
734       /* very large diff, fall back to system time */
735       g_get_current_time (&now);
736       gstnow = GST_TIMEVAL_TO_TIME (now);
737     }
738
739     /* Detect buggy drivers here, and stop using their timestamp. Failing any
740      * of these condition would imply a very buggy driver:
741      *   - Timestamp in the future
742      *   - Timestamp is going backward compare to last seen timestamp
743      *   - Timestamp is jumping forward for less then a frame duration
744      *   - Delay is bigger then the actual timestamp
745      * */
746     if (timestamp > gstnow) {
747       GST_WARNING_OBJECT (v4l2src,
748           "Timestamp in the future detected, ignoring driver timestamps");
749       v4l2src->has_bad_timestamp = TRUE;
750       goto retry;
751     }
752
753     if (v4l2src->last_timestamp > timestamp) {
754       GST_WARNING_OBJECT (v4l2src,
755           "Timestamp going backward, ignoring driver timestamps");
756       v4l2src->has_bad_timestamp = TRUE;
757       goto retry;
758     }
759
760     delay = gstnow - timestamp;
761
762     if (delay > timestamp) {
763       GST_WARNING_OBJECT (v4l2src,
764           "Timestamp does not correlate with any clock, ignoring driver timestamps");
765       v4l2src->has_bad_timestamp = TRUE;
766       goto retry;
767     }
768
769     /* Save last timestamp for sanity checks */
770     v4l2src->last_timestamp = timestamp;
771
772     GST_DEBUG_OBJECT (v4l2src, "ts: %" GST_TIME_FORMAT " now %" GST_TIME_FORMAT
773         " delay %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
774         GST_TIME_ARGS (gstnow), GST_TIME_ARGS (delay));
775   } else {
776     /* we assume 1 frame latency otherwise */
777     if (GST_CLOCK_TIME_IS_VALID (duration))
778       delay = duration;
779     else
780       delay = 0;
781   }
782
783   /* set buffer metadata */
784
785   if (G_LIKELY (abs_time != GST_CLOCK_TIME_NONE)) {
786     /* the time now is the time of the clock minus the base time */
787     timestamp = abs_time - base_time;
788
789     /* adjust for delay in the device */
790     if (timestamp > delay)
791       timestamp -= delay;
792     else
793       timestamp = 0;
794   } else {
795     timestamp = GST_CLOCK_TIME_NONE;
796   }
797
798   /* activate settings for next frame */
799   if (GST_CLOCK_TIME_IS_VALID (duration)) {
800     v4l2src->ctrl_time += duration;
801   } else {
802     /* this is not very good (as it should be the next timestamp),
803      * still good enough for linear fades (as long as it is not -1)
804      */
805     v4l2src->ctrl_time = timestamp;
806   }
807   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
808
809   GST_INFO_OBJECT (src, "sync to %" GST_TIME_FORMAT " out ts %" GST_TIME_FORMAT,
810       GST_TIME_ARGS (v4l2src->ctrl_time), GST_TIME_ARGS (timestamp));
811
812   /* use generated offset values only if there are not already valid ones
813    * set by the v4l2 device */
814   if (!GST_BUFFER_OFFSET_IS_VALID (*buf)
815       || !GST_BUFFER_OFFSET_END_IS_VALID (*buf)) {
816     GST_BUFFER_OFFSET (*buf) = v4l2src->offset++;
817     GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset;
818   } else {
819     /* adjust raw v4l2 device sequence, will restart at null in case of renegotiation
820      * (streamoff/streamon) */
821     GST_BUFFER_OFFSET (*buf) += v4l2src->renegotiation_adjust;
822     GST_BUFFER_OFFSET_END (*buf) += v4l2src->renegotiation_adjust;
823     /* check for frame loss with given (from v4l2 device) buffer offset */
824     if ((v4l2src->offset != 0)
825         && (GST_BUFFER_OFFSET (*buf) != (v4l2src->offset + 1))) {
826       guint64 lost_frame_count = GST_BUFFER_OFFSET (*buf) - v4l2src->offset - 1;
827       GST_WARNING_OBJECT (v4l2src,
828           "lost frames detected: count = %" G_GUINT64_FORMAT " - ts: %"
829           GST_TIME_FORMAT, lost_frame_count, GST_TIME_ARGS (timestamp));
830
831       qos_msg = gst_message_new_qos (GST_OBJECT_CAST (v4l2src), TRUE,
832           GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, timestamp,
833           GST_CLOCK_TIME_IS_VALID (duration) ? lost_frame_count *
834           duration : GST_CLOCK_TIME_NONE);
835       gst_element_post_message (GST_ELEMENT_CAST (v4l2src), qos_msg);
836
837     }
838     v4l2src->offset = GST_BUFFER_OFFSET (*buf);
839   }
840
841   GST_BUFFER_TIMESTAMP (*buf) = timestamp;
842   GST_BUFFER_DURATION (*buf) = duration;
843
844   return ret;
845
846   /* ERROR */
847 alloc_failed:
848   {
849     if (ret != GST_FLOW_FLUSHING)
850       GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
851           ("Failed to allocate a buffer"), (NULL));
852     return ret;
853   }
854 error:
855   {
856     if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
857       GST_ELEMENT_ERROR (src, RESOURCE, FAILED,
858           ("Driver returned a buffer with no payload, this most likely "
859               "indicate a bug in the driver."), (NULL));
860       ret = GST_FLOW_ERROR;
861     } else {
862       GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
863           gst_flow_get_name (ret));
864     }
865     return ret;
866   }
867 }
868
869
870 /* GstURIHandler interface */
871 static GstURIType
872 gst_v4l2src_uri_get_type (GType type)
873 {
874   return GST_URI_SRC;
875 }
876
877 static const gchar *const *
878 gst_v4l2src_uri_get_protocols (GType type)
879 {
880   static const gchar *protocols[] = { "v4l2", NULL };
881
882   return protocols;
883 }
884
885 static gchar *
886 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
887 {
888   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
889
890   if (v4l2src->v4l2object->videodev != NULL) {
891     return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
892   }
893
894   return g_strdup ("v4l2://");
895 }
896
897 static gboolean
898 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
899     GError ** error)
900 {
901   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
902   const gchar *device = DEFAULT_PROP_DEVICE;
903
904   if (strcmp (uri, "v4l2://") != 0) {
905     device = uri + 7;
906   }
907   g_object_set (v4l2src, "device", device, NULL);
908
909   return TRUE;
910 }
911
912
913 static void
914 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
915 {
916   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
917
918   iface->get_type = gst_v4l2src_uri_get_type;
919   iface->get_protocols = gst_v4l2src_uri_get_protocols;
920   iface->get_uri = gst_v4l2src_uri_get_uri;
921   iface->set_uri = gst_v4l2src_uri_set_uri;
922 }