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