v4l2src: don't error in shutdown
[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., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, 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 v4l2src ! xvimagesink
34  * ]| This pipeline shows the video captured from /dev/video0 tv card and for
35  * webcams.
36  * |[
37  * gst-launch 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 #undef HAVE_XVIDEO
48
49 #include <string.h>
50 #include <sys/time.h>
51 #include <unistd.h>
52
53 #include "gst/video/gstvideometa.h"
54 #include "gst/video/gstvideopool.h"
55
56 #include "gstv4l2src.h"
57
58 #include "gstv4l2colorbalance.h"
59 #include "gstv4l2tuner.h"
60 #ifdef HAVE_XVIDEO
61 #include "gstv4l2xoverlay.h"
62 #endif
63 #include "gstv4l2vidorient.h"
64
65 #include "gst/gst-i18n-plugin.h"
66
67 GST_DEBUG_CATEGORY (v4l2src_debug);
68 #define GST_CAT_DEFAULT v4l2src_debug
69
70 #define PROP_DEF_ALWAYS_COPY        TRUE
71 #define PROP_DEF_DECIMATE           1
72
73 #define DEFAULT_PROP_DEVICE   "/dev/video0"
74
75 enum
76 {
77   PROP_0,
78   V4L2_STD_OBJECT_PROPS,
79   PROP_ALWAYS_COPY,
80   PROP_DECIMATE
81 };
82
83 GST_IMPLEMENT_V4L2_COLOR_BALANCE_METHODS (GstV4l2Src, gst_v4l2src);
84 GST_IMPLEMENT_V4L2_TUNER_METHODS (GstV4l2Src, gst_v4l2src);
85 #ifdef HAVE_XVIDEO
86 GST_IMPLEMENT_V4L2_XOVERLAY_METHODS (GstV4l2Src, gst_v4l2src);
87 #endif
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 #ifdef HAVE_XVIDEO
98     /* FIXME: does GstXOverlay for v4l2src make sense in a GStreamer context? */
99     G_IMPLEMENT_INTERFACE (GST_TYPE_X_OVERLAY,
100         gst_v4l2src_xoverlay_interface_init);
101 #endif
102     G_IMPLEMENT_INTERFACE (GST_TYPE_COLOR_BALANCE,
103         gst_v4l2src_color_balance_interface_init);
104     G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_ORIENTATION,
105         gst_v4l2src_video_orientation_interface_init));
106
107 static void gst_v4l2src_dispose (GObject * object);
108 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
109
110 /* element methods */
111 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
112     GstStateChange transition);
113
114 /* basesrc methods */
115 static gboolean gst_v4l2src_start (GstBaseSrc * src);
116 static gboolean gst_v4l2src_unlock (GstBaseSrc * src);
117 static gboolean gst_v4l2src_unlock_stop (GstBaseSrc * src);
118 static gboolean gst_v4l2src_stop (GstBaseSrc * src);
119 static gboolean gst_v4l2src_set_caps (GstBaseSrc * src, GstCaps * caps);
120 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter);
121 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
122 static gboolean gst_v4l2src_decide_allocation (GstBaseSrc * src,
123     GstQuery * query);
124 static GstFlowReturn gst_v4l2src_fill (GstPushSrc * src, GstBuffer * out);
125 static GstCaps *gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps);
126 static gboolean gst_v4l2src_negotiate (GstBaseSrc * basesrc);
127
128 static void gst_v4l2src_set_property (GObject * object, guint prop_id,
129     const GValue * value, GParamSpec * pspec);
130 static void gst_v4l2src_get_property (GObject * object, guint prop_id,
131     GValue * value, GParamSpec * pspec);
132
133 static void
134 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
135 {
136   GObjectClass *gobject_class;
137   GstElementClass *element_class;
138   GstBaseSrcClass *basesrc_class;
139   GstPushSrcClass *pushsrc_class;
140
141   gobject_class = G_OBJECT_CLASS (klass);
142   element_class = GST_ELEMENT_CLASS (klass);
143   basesrc_class = GST_BASE_SRC_CLASS (klass);
144   pushsrc_class = GST_PUSH_SRC_CLASS (klass);
145
146   gobject_class->dispose = gst_v4l2src_dispose;
147   gobject_class->finalize = (GObjectFinalizeFunc) gst_v4l2src_finalize;
148   gobject_class->set_property = gst_v4l2src_set_property;
149   gobject_class->get_property = gst_v4l2src_get_property;
150
151   element_class->change_state = gst_v4l2src_change_state;
152
153   gst_v4l2_object_install_properties_helper (gobject_class,
154       DEFAULT_PROP_DEVICE);
155   g_object_class_install_property (gobject_class, PROP_ALWAYS_COPY,
156       g_param_spec_boolean ("always-copy", "Always Copy",
157           "If the buffer will or not be used directly from mmap",
158           PROP_DEF_ALWAYS_COPY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
159   /**
160    * GstV4l2Src:decimate
161    *
162    * Only use every nth frame
163    *
164    * Since: 0.10.26
165    */
166   g_object_class_install_property (gobject_class, PROP_DECIMATE,
167       g_param_spec_int ("decimate", "Decimate",
168           "Only use every nth frame", 1, G_MAXINT,
169           PROP_DEF_DECIMATE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
170
171   gst_element_class_set_details_simple (element_class,
172       "Video (video4linux2) Source", "Source/Video",
173       "Reads frames from a Video4Linux2 device",
174       "Edgard Lima <edgard.lima@indt.org.br>, "
175       "Stefan Kost <ensonic@users.sf.net>");
176
177   gst_element_class_add_pad_template
178       (element_class,
179       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
180           gst_v4l2_object_get_all_caps ()));
181
182   basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_get_caps);
183   basesrc_class->set_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_set_caps);
184   basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
185   basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
186   basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
187   basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
188   basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
189   basesrc_class->fixate = GST_DEBUG_FUNCPTR (gst_v4l2src_fixate);
190   basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
191   basesrc_class->decide_allocation =
192       GST_DEBUG_FUNCPTR (gst_v4l2src_decide_allocation);
193
194   pushsrc_class->fill = GST_DEBUG_FUNCPTR (gst_v4l2src_fill);
195
196   klass->v4l2_class_devices = NULL;
197
198   GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
199 }
200
201 static void
202 gst_v4l2src_init (GstV4l2Src * v4l2src)
203 {
204   /* fixme: give an update_fps_function */
205   v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
206       V4L2_BUF_TYPE_VIDEO_CAPTURE, DEFAULT_PROP_DEVICE,
207       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
208
209   v4l2src->v4l2object->always_copy = PROP_DEF_ALWAYS_COPY;
210   v4l2src->decimate = PROP_DEF_DECIMATE;
211
212   gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
213   gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
214 }
215
216 static void
217 gst_v4l2src_dispose (GObject * object)
218 {
219   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
220
221   if (v4l2src->probed_caps) {
222     gst_caps_unref (v4l2src->probed_caps);
223   }
224
225   G_OBJECT_CLASS (parent_class)->dispose (object);
226 }
227
228
229 static void
230 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
231 {
232   gst_v4l2_object_destroy (v4l2src->v4l2object);
233
234   G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
235 }
236
237
238 static void
239 gst_v4l2src_set_property (GObject * object,
240     guint prop_id, const GValue * value, GParamSpec * pspec)
241 {
242   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
243
244   if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
245           prop_id, value, pspec)) {
246     switch (prop_id) {
247       case PROP_ALWAYS_COPY:
248         v4l2src->v4l2object->always_copy = g_value_get_boolean (value);
249         break;
250       case PROP_DECIMATE:
251         v4l2src->decimate = g_value_get_int (value);
252         break;
253       default:
254         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
255         break;
256     }
257   }
258 }
259
260 static void
261 gst_v4l2src_get_property (GObject * object,
262     guint prop_id, GValue * value, GParamSpec * pspec)
263 {
264   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
265
266   if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
267           prop_id, value, pspec)) {
268     switch (prop_id) {
269       case PROP_ALWAYS_COPY:
270         g_value_set_boolean (value, v4l2src->v4l2object->always_copy);
271         break;
272       case PROP_DECIMATE:
273         g_value_set_int (value, v4l2src->decimate);
274         break;
275       default:
276         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
277         break;
278     }
279   }
280 }
281
282 /* this function is a bit of a last resort */
283 static GstCaps *
284 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps)
285 {
286   GstStructure *structure;
287   gint i;
288
289   GST_DEBUG_OBJECT (basesrc, "fixating caps %" GST_PTR_FORMAT, caps);
290
291   caps = gst_caps_make_writable (caps);
292
293   for (i = 0; i < gst_caps_get_size (caps); ++i) {
294     structure = gst_caps_get_structure (caps, i);
295
296     /* We are fixating to a resonable 320x200 resolution
297        and the maximum framerate resolution for that size */
298     gst_structure_fixate_field_nearest_int (structure, "width", 320);
299     gst_structure_fixate_field_nearest_int (structure, "height", 200);
300     gst_structure_fixate_field_nearest_fraction (structure, "framerate",
301         G_MAXINT, 1);
302     gst_structure_fixate_field (structure, "format");
303   }
304
305   GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, caps);
306
307   caps = GST_BASE_SRC_CLASS (parent_class)->fixate (basesrc, caps);
308
309   return caps;
310 }
311
312
313 static gboolean
314 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
315 {
316   GstCaps *thiscaps;
317   GstCaps *caps = NULL;
318   GstCaps *peercaps = NULL;
319   gboolean result = FALSE;
320
321   /* first see what is possible on our source pad */
322   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
323   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
324   LOG_CAPS (basesrc, thiscaps);
325
326   /* nothing or anything is allowed, we're done */
327   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
328     goto no_nego_needed;
329
330   /* get the peer caps */
331   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), thiscaps);
332   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
333   LOG_CAPS (basesrc, peercaps);
334   if (peercaps && !gst_caps_is_any (peercaps)) {
335     GstCaps *icaps = NULL;
336     int i;
337
338     /* Prefer the first caps we are compatible with that the peer proposed */
339     for (i = 0; i < gst_caps_get_size (peercaps); i++) {
340       /* get intersection */
341       GstCaps *ipcaps = gst_caps_copy_nth (peercaps, i);
342
343       GST_DEBUG_OBJECT (basesrc, "peer: %" GST_PTR_FORMAT, ipcaps);
344       LOG_CAPS (basesrc, ipcaps);
345
346       icaps = gst_caps_intersect (thiscaps, ipcaps);
347       gst_caps_unref (ipcaps);
348
349       if (!gst_caps_is_empty (icaps))
350         break;
351
352       gst_caps_unref (icaps);
353       icaps = NULL;
354     }
355
356     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, icaps);
357     LOG_CAPS (basesrc, icaps);
358     if (icaps) {
359       /* If there are multiple intersections pick the one with the smallest
360        * resolution strictly bigger then the first peer caps */
361       if (gst_caps_get_size (icaps) > 1) {
362         GstStructure *s = gst_caps_get_structure (peercaps, 0);
363         int best = 0;
364         int twidth, theight;
365         int width = G_MAXINT, height = G_MAXINT;
366
367         if (gst_structure_get_int (s, "width", &twidth)
368             && gst_structure_get_int (s, "height", &theight)) {
369
370           /* Walk the structure backwards to get the first entry of the
371            * smallest resolution bigger (or equal to) the preferred resolution)
372            */
373           for (i = gst_caps_get_size (icaps) - 1; i >= 0; i--) {
374             GstStructure *is = gst_caps_get_structure (icaps, i);
375             int w, h;
376
377             if (gst_structure_get_int (is, "width", &w)
378                 && gst_structure_get_int (is, "height", &h)) {
379               if (w >= twidth && w <= width && h >= theight && h <= height) {
380                 width = w;
381                 height = h;
382                 best = i;
383               }
384             }
385           }
386         }
387
388         caps = gst_caps_copy_nth (icaps, best);
389         gst_caps_unref (icaps);
390       } else {
391         caps = icaps;
392       }
393     }
394     gst_caps_unref (thiscaps);
395   } else {
396     /* no peer or peer have ANY caps, work with our own caps then */
397     caps = thiscaps;
398   }
399   if (peercaps)
400     gst_caps_unref (peercaps);
401   if (caps) {
402     caps = gst_caps_truncate (caps);
403
404     /* now fixate */
405     if (!gst_caps_is_empty (caps)) {
406       caps = gst_v4l2src_fixate (basesrc, caps);
407       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
408       LOG_CAPS (basesrc, caps);
409
410       if (gst_caps_is_any (caps)) {
411         /* hmm, still anything, so element can do anything and
412          * nego is not needed */
413         result = TRUE;
414       } else if (gst_caps_is_fixed (caps)) {
415         /* yay, fixed caps, use those then */
416         result = gst_base_src_set_caps (basesrc, caps);
417       }
418     }
419     gst_caps_unref (caps);
420   }
421   return result;
422
423 no_nego_needed:
424   {
425     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
426     if (thiscaps)
427       gst_caps_unref (thiscaps);
428     return TRUE;
429   }
430 }
431
432 static GstCaps *
433 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
434 {
435   GstV4l2Src *v4l2src;
436   GstV4l2Object *obj;
437   GstCaps *ret;
438   GSList *walk;
439   GSList *formats;
440
441   v4l2src = GST_V4L2SRC (src);
442   obj = v4l2src->v4l2object;
443
444   if (!GST_V4L2_IS_OPEN (obj)) {
445     /* FIXME: copy? */
446     return
447         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD
448             (v4l2src)));
449   }
450
451   if (v4l2src->probed_caps)
452     return gst_caps_ref (v4l2src->probed_caps);
453
454   formats = gst_v4l2_object_get_format_list (obj);
455
456   ret = gst_caps_new_empty ();
457
458   for (walk = formats; walk; walk = walk->next) {
459     struct v4l2_fmtdesc *format;
460     GstStructure *template;
461
462     format = (struct v4l2_fmtdesc *) walk->data;
463
464     template = gst_v4l2_object_v4l2fourcc_to_structure (format->pixelformat);
465
466     if (template) {
467       GstCaps *tmp;
468
469       tmp =
470           gst_v4l2_object_probe_caps_for_format (obj,
471           format->pixelformat, template);
472       if (tmp)
473         gst_caps_append (ret, tmp);
474
475       gst_structure_free (template);
476     } else {
477       GST_DEBUG_OBJECT (v4l2src, "unknown format %u", format->pixelformat);
478     }
479   }
480
481   v4l2src->probed_caps = gst_caps_ref (ret);
482
483   GST_INFO_OBJECT (v4l2src, "probed caps: %" GST_PTR_FORMAT, ret);
484
485   return ret;
486 }
487
488 static gboolean
489 gst_v4l2src_set_caps (GstBaseSrc * src, GstCaps * caps)
490 {
491   GstV4l2Src *v4l2src;
492   GstV4l2Object *obj;
493
494   v4l2src = GST_V4L2SRC (src);
495   obj = v4l2src->v4l2object;
496
497   /* make sure we stop capturing and dealloc buffers */
498   if (!gst_v4l2_object_stop (obj))
499     return FALSE;
500
501   if (!gst_v4l2_object_set_format (obj, caps))
502     /* error already posted */
503     return FALSE;
504
505   return TRUE;
506 }
507
508 static gboolean
509 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
510 {
511   GstV4l2Src *src;
512   GstV4l2Object *obj;
513   GstBufferPool *pool;
514   guint size, min, max;
515   gboolean update;
516
517   src = GST_V4L2SRC (bsrc);
518   obj = src->v4l2object;
519
520   if (gst_query_get_n_allocation_pools (query) > 0) {
521     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
522     update = TRUE;
523   } else {
524     pool = NULL;
525     min = max = 0;
526     size = 0;
527     update = FALSE;
528   }
529
530   GST_DEBUG_OBJECT (src, "allocation: size:%u min:%u max:%u pool:%"
531       GST_PTR_FORMAT, size, min, max, pool);
532
533   if (min != 0) {
534     /* if there is a min-buffers suggestion, use it. We add 1 because we need 1
535      * buffer extra to capture while the other two buffers are downstream */
536     min += 1;
537   } else {
538     min = 2;
539   }
540
541   /* select a pool */
542   switch (obj->mode) {
543     case GST_V4L2_IO_RW:
544       if (pool == NULL) {
545         /* no downstream pool, use our own then */
546         GST_DEBUG_OBJECT (src,
547             "read/write mode: no downstream pool, using our own");
548         pool = GST_BUFFER_POOL_CAST (obj->pool);
549         size = obj->sizeimage;
550       } else {
551         /* in READ/WRITE mode, prefer a downstream pool because our own pool
552          * doesn't help much, we have to write to it as well */
553         GST_DEBUG_OBJECT (src, "read/write mode: using downstream pool");
554         /* use the bigest size, when we use our own pool we can't really do any
555          * other size than what the hardware gives us but for downstream pools
556          * we can try */
557         size = MAX (size, obj->sizeimage);
558       }
559       break;
560     case GST_V4L2_IO_MMAP:
561     case GST_V4L2_IO_USERPTR:
562       /* in streaming mode, prefer our own pool */
563       pool = GST_BUFFER_POOL_CAST (obj->pool);
564       size = obj->sizeimage;
565       GST_DEBUG_OBJECT (src,
566           "streaming mode: using our own pool %" GST_PTR_FORMAT, pool);
567       break;
568     case GST_V4L2_IO_AUTO:
569     default:
570       GST_WARNING_OBJECT (src, "unhandled mode");
571       break;
572   }
573
574   if (pool) {
575     GstStructure *config;
576     const GstCaps *caps;
577
578     config = gst_buffer_pool_get_config (pool);
579     gst_buffer_pool_config_get_params (config, &caps, NULL, NULL, NULL);
580     gst_buffer_pool_config_set_params (config, caps, size, min, max);
581
582     /* if downstream supports video metadata, add this to the pool config */
583     if (gst_query_has_allocation_meta (query, GST_VIDEO_META_API_TYPE))
584       gst_buffer_pool_config_add_option (config,
585           GST_BUFFER_POOL_OPTION_VIDEO_META);
586
587     gst_buffer_pool_set_config (pool, config);
588   }
589
590   if (update)
591     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
592   else
593     gst_query_add_allocation_pool (query, pool, size, min, max);
594
595   return TRUE;
596 }
597
598 static gboolean
599 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
600 {
601   GstV4l2Src *src;
602   GstV4l2Object *obj;
603   gboolean res = FALSE;
604
605   src = GST_V4L2SRC (bsrc);
606   obj = src->v4l2object;
607
608   switch (GST_QUERY_TYPE (query)) {
609     case GST_QUERY_LATENCY:{
610       GstClockTime min_latency, max_latency;
611       guint32 fps_n, fps_d;
612       guint max_buffers;
613
614       /* device must be open */
615       if (!GST_V4L2_IS_OPEN (obj)) {
616         GST_WARNING_OBJECT (src,
617             "Can't give latency since device isn't open !");
618         goto done;
619       }
620
621       fps_n = GST_V4L2_FPS_N (obj);
622       fps_d = GST_V4L2_FPS_D (obj);
623
624       /* we must have a framerate */
625       if (fps_n <= 0 || fps_d <= 0) {
626         GST_WARNING_OBJECT (src,
627             "Can't give latency since framerate isn't fixated !");
628         goto done;
629       }
630
631       /* min latency is the time to capture one frame */
632       min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
633
634       /* max latency is total duration of the frame buffer */
635       max_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_buffers;
636
637       if (max_buffers == 0)
638         max_latency = -1;
639       else
640         max_latency = max_buffers * min_latency;
641
642       GST_DEBUG_OBJECT (bsrc,
643           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
644           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
645
646       /* we are always live, the min latency is 1 frame and the max latency is
647        * the complete buffer of frames. */
648       gst_query_set_latency (query, TRUE, min_latency, max_latency);
649
650       res = TRUE;
651       break;
652     }
653     default:
654       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
655       break;
656   }
657
658 done:
659
660   return res;
661 }
662
663 /* start and stop are not symmetric -- start will open the device, but not start
664  * capture. it's setcaps that will start capture, which is called via basesrc's
665  * negotiate method. stop will both stop capture and close the device.
666  */
667 static gboolean
668 gst_v4l2src_start (GstBaseSrc * src)
669 {
670   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
671
672   v4l2src->offset = 0;
673
674   /* activate settings for first frame */
675   v4l2src->ctrl_time = 0;
676   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
677
678   return TRUE;
679 }
680
681 static gboolean
682 gst_v4l2src_unlock (GstBaseSrc * src)
683 {
684   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
685   return gst_v4l2_object_unlock (v4l2src->v4l2object);
686 }
687
688 static gboolean
689 gst_v4l2src_unlock_stop (GstBaseSrc * src)
690 {
691   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
692   return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
693 }
694
695 static gboolean
696 gst_v4l2src_stop (GstBaseSrc * src)
697 {
698   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
699   GstV4l2Object *obj = v4l2src->v4l2object;
700
701   if (GST_V4L2_IS_ACTIVE (obj)) {
702     if (!gst_v4l2_object_stop (obj))
703       return FALSE;
704   }
705   return TRUE;
706 }
707
708 static GstStateChangeReturn
709 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
710 {
711   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
712   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
713   GstV4l2Object *obj = v4l2src->v4l2object;
714
715   switch (transition) {
716     case GST_STATE_CHANGE_NULL_TO_READY:
717       /* open the device */
718       if (!gst_v4l2_object_open (obj))
719         return GST_STATE_CHANGE_FAILURE;
720       break;
721     default:
722       break;
723   }
724
725   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
726
727   switch (transition) {
728     case GST_STATE_CHANGE_READY_TO_NULL:
729       /* close the device */
730       if (!gst_v4l2_object_close (obj))
731         return GST_STATE_CHANGE_FAILURE;
732
733       if (v4l2src->probed_caps) {
734         gst_caps_unref (v4l2src->probed_caps);
735         v4l2src->probed_caps = NULL;
736       }
737       break;
738     default:
739       break;
740   }
741
742   return ret;
743 }
744
745 static GstFlowReturn
746 gst_v4l2src_fill (GstPushSrc * src, GstBuffer * buf)
747 {
748   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
749   GstV4l2Object *obj = v4l2src->v4l2object;
750   GstFlowReturn ret;
751   GstClock *clock;
752   GstClockTime timestamp, duration;
753
754 #if 0
755   int i;
756   /* decimate, just capture and throw away frames */
757   for (i = 0; i < v4l2src->decimate - 1; i++) {
758     ret = gst_v4l2_buffer_pool_process (obj, buf);
759     if (ret != GST_FLOW_OK) {
760       return ret;
761     }
762     gst_buffer_unref (*buf);
763   }
764 #endif
765
766   ret =
767       gst_v4l2_buffer_pool_process (GST_V4L2_BUFFER_POOL_CAST (obj->pool), buf);
768
769   if (G_UNLIKELY (ret != GST_FLOW_OK))
770     goto error;
771
772   /* set buffer metadata */
773   GST_BUFFER_OFFSET (buf) = v4l2src->offset++;
774   GST_BUFFER_OFFSET_END (buf) = v4l2src->offset;
775
776   /* timestamps, LOCK to get clock and base time. */
777   /* FIXME: element clock and base_time is rarely changing */
778   GST_OBJECT_LOCK (v4l2src);
779   if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
780     /* we have a clock, get base time and ref clock */
781     timestamp = GST_ELEMENT (v4l2src)->base_time;
782     gst_object_ref (clock);
783   } else {
784     /* no clock, can't set timestamps */
785     timestamp = GST_CLOCK_TIME_NONE;
786   }
787   GST_OBJECT_UNLOCK (v4l2src);
788
789   duration = obj->duration;
790
791   if (G_LIKELY (clock)) {
792     /* the time now is the time of the clock minus the base time */
793     timestamp = gst_clock_get_time (clock) - timestamp;
794     gst_object_unref (clock);
795
796     /* if we have a framerate adjust timestamp for frame latency */
797     if (GST_CLOCK_TIME_IS_VALID (duration)) {
798       if (timestamp > duration)
799         timestamp -= duration;
800       else
801         timestamp = 0;
802     }
803   }
804
805   /* activate settings for next frame */
806   if (GST_CLOCK_TIME_IS_VALID (duration)) {
807     v4l2src->ctrl_time += duration;
808   } else {
809     /* this is not very good (as it should be the next timestamp),
810      * still good enough for linear fades (as long as it is not -1)
811      */
812     v4l2src->ctrl_time = timestamp;
813   }
814   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
815   GST_INFO_OBJECT (src, "sync to %" GST_TIME_FORMAT,
816       GST_TIME_ARGS (v4l2src->ctrl_time));
817
818   /* FIXME: use the timestamp from the buffer itself! */
819   GST_BUFFER_TIMESTAMP (buf) = timestamp;
820   GST_BUFFER_DURATION (buf) = duration;
821
822   return ret;
823
824   /* ERROR */
825 error:
826   {
827     GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
828         gst_flow_get_name (ret));
829     return ret;
830   }
831 }
832
833
834 /* GstURIHandler interface */
835 static GstURIType
836 gst_v4l2src_uri_get_type (GType type)
837 {
838   return GST_URI_SRC;
839 }
840
841 static const gchar *const *
842 gst_v4l2src_uri_get_protocols (GType type)
843 {
844   static const gchar *protocols[] = { "v4l2", NULL };
845
846   return protocols;
847 }
848
849 static gchar *
850 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
851 {
852   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
853
854   if (v4l2src->v4l2object->videodev != NULL) {
855     return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
856   }
857
858   return g_strdup ("v4l2://");
859 }
860
861 static gboolean
862 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
863     GError ** error)
864 {
865   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
866   const gchar *device = DEFAULT_PROP_DEVICE;
867
868   if (strcmp (uri, "v4l2://") != 0) {
869     device = uri + 7;
870   }
871   g_object_set (v4l2src, "device", device, NULL);
872
873   return TRUE;
874 }
875
876
877 static void
878 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
879 {
880   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
881
882   iface->get_type = gst_v4l2src_uri_get_type;
883   iface->get_protocols = gst_v4l2src_uri_get_protocols;
884   iface->get_uri = gst_v4l2src_uri_get_uri;
885   iface->set_uri = gst_v4l2src_uri_set_uri;
886 }