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