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