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