upload tizen1.0 source
[framework/multimedia/gst-plugins-good0.10.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 "v4l2src_calls.h"
52 #include <unistd.h>
53
54 #include "gstv4l2colorbalance.h"
55 #include "gstv4l2tuner.h"
56 #ifdef HAVE_XVIDEO
57 #include "gstv4l2xoverlay.h"
58 #endif
59 #include "gstv4l2vidorient.h"
60
61 #include "gst/gst-i18n-plugin.h"
62
63 GST_DEBUG_CATEGORY (v4l2src_debug);
64 #define GST_CAT_DEFAULT v4l2src_debug
65
66 #define PROP_DEF_QUEUE_SIZE         2
67 #define PROP_DEF_ALWAYS_COPY        TRUE
68 #define PROP_DEF_DECIMATE           1
69
70 #define DEFAULT_PROP_DEVICE   "/dev/video0"
71
72 enum
73 {
74   PROP_0,
75   V4L2_STD_OBJECT_PROPS,
76   PROP_QUEUE_SIZE,
77   PROP_ALWAYS_COPY,
78   PROP_DECIMATE
79 };
80
81 GST_IMPLEMENT_V4L2_PROBE_METHODS (GstV4l2SrcClass, gst_v4l2src);
82 GST_IMPLEMENT_V4L2_COLOR_BALANCE_METHODS (GstV4l2Src, gst_v4l2src);
83 GST_IMPLEMENT_V4L2_TUNER_METHODS (GstV4l2Src, gst_v4l2src);
84 #ifdef HAVE_XVIDEO
85 GST_IMPLEMENT_V4L2_XOVERLAY_METHODS (GstV4l2Src, gst_v4l2src);
86 #endif
87 GST_IMPLEMENT_V4L2_VIDORIENT_METHODS (GstV4l2Src, gst_v4l2src);
88
89 static void gst_v4l2src_uri_handler_init (gpointer g_iface,
90     gpointer iface_data);
91
92 static gboolean
93 gst_v4l2src_iface_supported (GstImplementsInterface * iface, GType iface_type)
94 {
95   GstV4l2Object *v4l2object = GST_V4L2SRC (iface)->v4l2object;
96
97 #ifdef HAVE_XVIDEO
98   g_assert (iface_type == GST_TYPE_TUNER ||
99       iface_type == GST_TYPE_X_OVERLAY ||
100       iface_type == GST_TYPE_COLOR_BALANCE ||
101       iface_type == GST_TYPE_VIDEO_ORIENTATION);
102 #else
103   g_assert (iface_type == GST_TYPE_TUNER ||
104       iface_type == GST_TYPE_COLOR_BALANCE ||
105       iface_type == GST_TYPE_VIDEO_ORIENTATION);
106 #endif
107
108   if (v4l2object->video_fd == -1)
109     return FALSE;
110
111 #ifdef HAVE_XVIDEO
112   if (iface_type == GST_TYPE_X_OVERLAY && !GST_V4L2_IS_OVERLAY (v4l2object))
113     return FALSE;
114 #endif
115
116   return TRUE;
117 }
118
119 static void
120 gst_v4l2src_interface_init (GstImplementsInterfaceClass * klass)
121 {
122   /*
123    * default virtual functions 
124    */
125   klass->supported = gst_v4l2src_iface_supported;
126 }
127
128 static void
129 gst_v4l2src_init_interfaces (GType type)
130 {
131   static const GInterfaceInfo urihandler_info = {
132     gst_v4l2src_uri_handler_init,
133     NULL,
134     NULL
135   };
136
137   static const GInterfaceInfo v4l2iface_info = {
138     (GInterfaceInitFunc) gst_v4l2src_interface_init,
139     NULL,
140     NULL,
141   };
142   static const GInterfaceInfo v4l2_tuner_info = {
143     (GInterfaceInitFunc) gst_v4l2src_tuner_interface_init,
144     NULL,
145     NULL,
146   };
147 #ifdef HAVE_XVIDEO
148   /* FIXME: does GstXOverlay for v4l2src make sense in a GStreamer context? */
149   static const GInterfaceInfo v4l2_xoverlay_info = {
150     (GInterfaceInitFunc) gst_v4l2src_xoverlay_interface_init,
151     NULL,
152     NULL,
153   };
154 #endif
155   static const GInterfaceInfo v4l2_colorbalance_info = {
156     (GInterfaceInitFunc) gst_v4l2src_color_balance_interface_init,
157     NULL,
158     NULL,
159   };
160   static const GInterfaceInfo v4l2_videoorientation_info = {
161     (GInterfaceInitFunc) gst_v4l2src_video_orientation_interface_init,
162     NULL,
163     NULL,
164   };
165   static const GInterfaceInfo v4l2_propertyprobe_info = {
166     (GInterfaceInitFunc) gst_v4l2src_property_probe_interface_init,
167     NULL,
168     NULL,
169   };
170
171   g_type_add_interface_static (type, GST_TYPE_URI_HANDLER, &urihandler_info);
172   g_type_add_interface_static (type,
173       GST_TYPE_IMPLEMENTS_INTERFACE, &v4l2iface_info);
174   g_type_add_interface_static (type, GST_TYPE_TUNER, &v4l2_tuner_info);
175 #ifdef HAVE_XVIDEO
176   g_type_add_interface_static (type, GST_TYPE_X_OVERLAY, &v4l2_xoverlay_info);
177 #endif
178   g_type_add_interface_static (type,
179       GST_TYPE_COLOR_BALANCE, &v4l2_colorbalance_info);
180   g_type_add_interface_static (type,
181       GST_TYPE_VIDEO_ORIENTATION, &v4l2_videoorientation_info);
182   g_type_add_interface_static (type, GST_TYPE_PROPERTY_PROBE,
183       &v4l2_propertyprobe_info);
184 }
185
186 GST_BOILERPLATE_FULL (GstV4l2Src, gst_v4l2src, GstPushSrc, GST_TYPE_PUSH_SRC,
187     gst_v4l2src_init_interfaces);
188
189 static void gst_v4l2src_dispose (GObject * object);
190 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
191
192 /* element methods */
193 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
194     GstStateChange transition);
195
196 /* basesrc methods */
197 static gboolean gst_v4l2src_start (GstBaseSrc * src);
198 static gboolean gst_v4l2src_unlock (GstBaseSrc * src);
199 static gboolean gst_v4l2src_unlock_stop (GstBaseSrc * src);
200 static gboolean gst_v4l2src_stop (GstBaseSrc * src);
201 static gboolean gst_v4l2src_set_caps (GstBaseSrc * src, GstCaps * caps);
202 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src);
203 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
204 static GstFlowReturn gst_v4l2src_create (GstPushSrc * src, GstBuffer ** out);
205 static void gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps);
206 static gboolean gst_v4l2src_negotiate (GstBaseSrc * basesrc);
207
208 static void gst_v4l2src_set_property (GObject * object, guint prop_id,
209     const GValue * value, GParamSpec * pspec);
210 static void gst_v4l2src_get_property (GObject * object, guint prop_id,
211     GValue * value, GParamSpec * pspec);
212
213 /* get_frame io methods */
214 static GstFlowReturn
215 gst_v4l2src_get_read (GstV4l2Src * v4l2src, GstBuffer ** buf);
216 static GstFlowReturn
217 gst_v4l2src_get_mmap (GstV4l2Src * v4l2src, GstBuffer ** buf);
218
219 static void
220 gst_v4l2src_base_init (gpointer g_class)
221 {
222   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
223   GstV4l2SrcClass *gstv4l2src_class = GST_V4L2SRC_CLASS (g_class);
224
225   gstv4l2src_class->v4l2_class_devices = NULL;
226
227   GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
228
229   gst_element_class_set_details_simple (gstelement_class,
230       "Video (video4linux2) Source", "Source/Video",
231       "Reads frames from a Video4Linux2 device",
232       "Edgard Lima <edgard.lima@indt.org.br>,"
233       " Stefan Kost <ensonic@users.sf.net>");
234
235   gst_element_class_add_pad_template
236       (gstelement_class,
237       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
238           gst_v4l2_object_get_all_caps ()));
239 }
240
241 static void
242 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
243 {
244   GObjectClass *gobject_class;
245   GstElementClass *element_class;
246   GstBaseSrcClass *basesrc_class;
247   GstPushSrcClass *pushsrc_class;
248
249   gobject_class = G_OBJECT_CLASS (klass);
250   element_class = GST_ELEMENT_CLASS (klass);
251   basesrc_class = GST_BASE_SRC_CLASS (klass);
252   pushsrc_class = GST_PUSH_SRC_CLASS (klass);
253
254   gobject_class->dispose = gst_v4l2src_dispose;
255   gobject_class->finalize = (GObjectFinalizeFunc) gst_v4l2src_finalize;
256   gobject_class->set_property = gst_v4l2src_set_property;
257   gobject_class->get_property = gst_v4l2src_get_property;
258
259   element_class->change_state = gst_v4l2src_change_state;
260
261   gst_v4l2_object_install_properties_helper (gobject_class,
262       DEFAULT_PROP_DEVICE);
263   g_object_class_install_property (gobject_class, PROP_QUEUE_SIZE,
264       g_param_spec_uint ("queue-size", "Queue size",
265           "Number of buffers to be enqueud in the driver in streaming mode",
266           GST_V4L2_MIN_BUFFERS, GST_V4L2_MAX_BUFFERS, PROP_DEF_QUEUE_SIZE,
267           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
268   g_object_class_install_property (gobject_class, PROP_ALWAYS_COPY,
269       g_param_spec_boolean ("always-copy", "Always Copy",
270           "If the buffer will or not be used directly from mmap",
271           PROP_DEF_ALWAYS_COPY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
272   /**
273    * GstV4l2Src:decimate
274    *
275    * Only use every nth frame
276    *
277    * Since: 0.10.26
278    */
279   g_object_class_install_property (gobject_class, PROP_DECIMATE,
280       g_param_spec_int ("decimate", "Decimate",
281           "Only use every nth frame", 1, G_MAXINT,
282           PROP_DEF_DECIMATE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
283
284   basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_get_caps);
285   basesrc_class->set_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_set_caps);
286   basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
287   basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
288   basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
289   basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
290   basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
291   basesrc_class->fixate = GST_DEBUG_FUNCPTR (gst_v4l2src_fixate);
292   basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
293
294   pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
295 }
296
297 static void
298 gst_v4l2src_init (GstV4l2Src * v4l2src, GstV4l2SrcClass * klass)
299 {
300   /* fixme: give an update_fps_function */
301   v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
302       V4L2_BUF_TYPE_VIDEO_CAPTURE, DEFAULT_PROP_DEVICE,
303       gst_v4l2_get_input, gst_v4l2_set_input, NULL);
304
305   /* number of buffers requested */
306   v4l2src->num_buffers = PROP_DEF_QUEUE_SIZE;
307
308   v4l2src->always_copy = PROP_DEF_ALWAYS_COPY;
309   v4l2src->decimate = PROP_DEF_DECIMATE;
310
311   v4l2src->is_capturing = FALSE;
312
313   gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
314   gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
315
316   v4l2src->fps_d = 0;
317   v4l2src->fps_n = 0;
318 }
319
320
321 static void
322 gst_v4l2src_dispose (GObject * object)
323 {
324   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
325
326   if (v4l2src->probed_caps) {
327     gst_caps_unref (v4l2src->probed_caps);
328   }
329
330   G_OBJECT_CLASS (parent_class)->dispose (object);
331 }
332
333
334 static void
335 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
336 {
337   gst_v4l2_object_destroy (v4l2src->v4l2object);
338
339   G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
340 }
341
342
343 static void
344 gst_v4l2src_set_property (GObject * object,
345     guint prop_id, const GValue * value, GParamSpec * pspec)
346 {
347   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
348
349   if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
350           prop_id, value, pspec)) {
351     switch (prop_id) {
352       case PROP_QUEUE_SIZE:
353         v4l2src->num_buffers = g_value_get_uint (value);
354         break;
355       case PROP_ALWAYS_COPY:
356         v4l2src->always_copy = g_value_get_boolean (value);
357         break;
358       case PROP_DECIMATE:
359         v4l2src->decimate = g_value_get_int (value);
360         break;
361       default:
362         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
363         break;
364     }
365   }
366 }
367
368
369 static void
370 gst_v4l2src_get_property (GObject * object,
371     guint prop_id, GValue * value, GParamSpec * pspec)
372 {
373   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
374
375   if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
376           prop_id, value, pspec)) {
377     switch (prop_id) {
378       case PROP_QUEUE_SIZE:
379         g_value_set_uint (value, v4l2src->num_buffers);
380         break;
381       case PROP_ALWAYS_COPY:
382         g_value_set_boolean (value, v4l2src->always_copy);
383         break;
384       case PROP_DECIMATE:
385         g_value_set_int (value, v4l2src->decimate);
386         break;
387       default:
388         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
389         break;
390     }
391   }
392 }
393
394
395 /* this function is a bit of a last resort */
396 static void
397 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps)
398 {
399   GstStructure *structure;
400   gint i;
401
402   GST_DEBUG_OBJECT (basesrc, "fixating caps %" GST_PTR_FORMAT, caps);
403
404   for (i = 0; i < gst_caps_get_size (caps); ++i) {
405     const GValue *v;
406
407     structure = gst_caps_get_structure (caps, i);
408
409     /* FIXME such sizes? we usually fixate to something in the 320x200
410      * range... */
411     /* We are fixating to greater possble size (limited to GST_V4L2_MAX_SIZE)
412        and the maximum framerate resolution for that size */
413     gst_structure_fixate_field_nearest_int (structure, "width",
414         GST_V4L2_MAX_SIZE);
415     gst_structure_fixate_field_nearest_int (structure, "height",
416         GST_V4L2_MAX_SIZE);
417     gst_structure_fixate_field_nearest_fraction (structure, "framerate",
418         G_MAXINT, 1);
419
420     v = gst_structure_get_value (structure, "format");
421     if (v && G_VALUE_TYPE (v) != GST_TYPE_FOURCC) {
422       guint32 fourcc;
423
424       g_return_if_fail (G_VALUE_TYPE (v) == GST_TYPE_LIST);
425
426       fourcc = gst_value_get_fourcc (gst_value_list_get_value (v, 0));
427       gst_structure_set (structure, "format", GST_TYPE_FOURCC, fourcc, NULL);
428     }
429   }
430
431   GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, caps);
432 }
433
434
435 static gboolean
436 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
437 {
438   GstCaps *thiscaps;
439   GstCaps *caps = NULL;
440   GstCaps *peercaps = NULL;
441   gboolean result = FALSE;
442
443   /* first see what is possible on our source pad */
444   thiscaps = gst_pad_get_caps (GST_BASE_SRC_PAD (basesrc));
445   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
446   LOG_CAPS (basesrc, thiscaps);
447
448   /* nothing or anything is allowed, we're done */
449   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
450     goto no_nego_needed;
451
452   /* get the peer caps */
453   peercaps = gst_pad_peer_get_caps (GST_BASE_SRC_PAD (basesrc));
454   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
455   LOG_CAPS (basesrc, peercaps);
456   if (peercaps && !gst_caps_is_any (peercaps)) {
457     GstCaps *icaps = NULL;
458     int i;
459
460     /* Prefer the first caps we are compatible with that the peer proposed */
461     for (i = 0; i < gst_caps_get_size (peercaps); i++) {
462       /* get intersection */
463       GstCaps *ipcaps = gst_caps_copy_nth (peercaps, i);
464
465       GST_DEBUG_OBJECT (basesrc, "peer: %" GST_PTR_FORMAT, ipcaps);
466       LOG_CAPS (basesrc, ipcaps);
467
468       icaps = gst_caps_intersect (thiscaps, ipcaps);
469       gst_caps_unref (ipcaps);
470
471       if (!gst_caps_is_empty (icaps))
472         break;
473
474       gst_caps_unref (icaps);
475       icaps = NULL;
476     }
477
478     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, icaps);
479     LOG_CAPS (basesrc, icaps);
480     if (icaps) {
481       /* If there are multiple intersections pick the one with the smallest
482        * resolution strictly bigger then the first peer caps */
483       if (gst_caps_get_size (icaps) > 1) {
484         GstStructure *s = gst_caps_get_structure (peercaps, 0);
485
486         int best = 0;
487
488         int twidth, theight;
489
490         int width = G_MAXINT, height = G_MAXINT;
491
492         if (gst_structure_get_int (s, "width", &twidth)
493             && gst_structure_get_int (s, "height", &theight)) {
494
495           /* Walk the structure backwards to get the first entry of the
496            * smallest resolution bigger (or equal to) the preferred resolution)
497            */
498           for (i = gst_caps_get_size (icaps) - 1; i >= 0; i--) {
499             GstStructure *is = gst_caps_get_structure (icaps, i);
500
501             int w, h;
502
503             if (gst_structure_get_int (is, "width", &w)
504                 && gst_structure_get_int (is, "height", &h)) {
505               if (w >= twidth && w <= width && h >= theight && h <= height) {
506                 width = w;
507                 height = h;
508                 best = i;
509               }
510             }
511           }
512         }
513
514         caps = gst_caps_copy_nth (icaps, best);
515         gst_caps_unref (icaps);
516       } else {
517         caps = icaps;
518       }
519     }
520     gst_caps_unref (thiscaps);
521     gst_caps_unref (peercaps);
522   } else {
523     /* no peer or peer have ANY caps, work with our own caps then */
524     caps = thiscaps;
525   }
526   if (caps) {
527     caps = gst_caps_make_writable (caps);
528     gst_caps_truncate (caps);
529
530     /* now fixate */
531     if (!gst_caps_is_empty (caps)) {
532       gst_pad_fixate_caps (GST_BASE_SRC_PAD (basesrc), caps);
533       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
534       LOG_CAPS (basesrc, caps);
535
536       if (gst_caps_is_any (caps)) {
537         /* hmm, still anything, so element can do anything and
538          * nego is not needed */
539         result = TRUE;
540       } else if (gst_caps_is_fixed (caps)) {
541         /* yay, fixed caps, use those then */
542         if (gst_pad_set_caps (GST_BASE_SRC_PAD (basesrc), caps))
543           result = TRUE;
544       }
545     }
546     gst_caps_unref (caps);
547   }
548   return result;
549
550 no_nego_needed:
551   {
552     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
553     if (thiscaps)
554       gst_caps_unref (thiscaps);
555     return TRUE;
556   }
557 }
558
559 static GstCaps *
560 gst_v4l2src_get_caps (GstBaseSrc * src)
561 {
562   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
563   GstCaps *ret;
564   GSList *walk;
565   GSList *formats;
566
567   if (!GST_V4L2_IS_OPEN (v4l2src->v4l2object)) {
568     /* FIXME: copy? */
569     return
570         gst_caps_copy (gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD
571             (v4l2src)));
572   }
573
574   if (v4l2src->probed_caps)
575     return gst_caps_ref (v4l2src->probed_caps);
576
577   formats = gst_v4l2_object_get_format_list (v4l2src->v4l2object);
578
579   ret = gst_caps_new_empty ();
580
581   for (walk = formats; walk; walk = walk->next) {
582     struct v4l2_fmtdesc *format;
583
584     GstStructure *template;
585
586     format = (struct v4l2_fmtdesc *) walk->data;
587
588     template = gst_v4l2_object_v4l2fourcc_to_structure (format->pixelformat);
589
590     if (template) {
591       GstCaps *tmp;
592
593       tmp =
594           gst_v4l2_object_probe_caps_for_format (v4l2src->v4l2object,
595           format->pixelformat, template);
596       if (tmp)
597         gst_caps_append (ret, tmp);
598
599       gst_structure_free (template);
600     } else {
601       GST_DEBUG_OBJECT (v4l2src, "unknown format %u", format->pixelformat);
602     }
603   }
604
605   v4l2src->probed_caps = gst_caps_ref (ret);
606
607   GST_INFO_OBJECT (v4l2src, "probed caps: %" GST_PTR_FORMAT, ret);
608
609   return ret;
610 }
611
612 static gboolean
613 gst_v4l2src_set_caps (GstBaseSrc * src, GstCaps * caps)
614 {
615   GstV4l2Src *v4l2src;
616   gint w = 0, h = 0;
617   gboolean interlaced;
618   struct v4l2_fmtdesc *format;
619   guint fps_n, fps_d;
620   guint size;
621
622   v4l2src = GST_V4L2SRC (src);
623
624   /* if we're not open, punt -- we'll get setcaps'd later via negotiate */
625   if (!GST_V4L2_IS_OPEN (v4l2src->v4l2object))
626     return FALSE;
627
628   /* make sure we stop capturing and dealloc buffers */
629   if (GST_V4L2_IS_ACTIVE (v4l2src->v4l2object)) {
630     /* both will throw an element-error on failure */
631     if (!gst_v4l2src_capture_stop (v4l2src))
632       return FALSE;
633     if (!gst_v4l2src_capture_deinit (v4l2src))
634       return FALSE;
635   }
636
637   /* we want our own v4l2 type of fourcc codes */
638   if (!gst_v4l2_object_get_caps_info (v4l2src->v4l2object, caps, &format, &w,
639           &h, &interlaced, &fps_n, &fps_d, &size)) {
640     GST_INFO_OBJECT (v4l2src,
641         "can't get capture format from caps %" GST_PTR_FORMAT, caps);
642     return FALSE;
643   }
644
645   GST_DEBUG_OBJECT (v4l2src, "trying to set_capture %dx%d at %d/%d fps, "
646       "format %s", w, h, fps_n, fps_d, format->description);
647
648   if (!gst_v4l2src_set_capture (v4l2src, format->pixelformat, w, h,
649           interlaced, fps_n, fps_d))
650     /* error already posted */
651     return FALSE;
652
653   if (!gst_v4l2src_capture_init (v4l2src, caps))
654     return FALSE;
655
656   if (v4l2src->use_mmap) {
657     v4l2src->get_frame = gst_v4l2src_get_mmap;
658   } else {
659     v4l2src->get_frame = gst_v4l2src_get_read;
660   }
661
662   if (!gst_v4l2src_capture_start (v4l2src))
663     return FALSE;
664
665   /* now store the expected output size */
666   v4l2src->frame_byte_size = size;
667
668   return TRUE;
669 }
670
671 static gboolean
672 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
673 {
674   GstV4l2Src *src;
675
676   gboolean res = FALSE;
677
678   src = GST_V4L2SRC (bsrc);
679
680   switch (GST_QUERY_TYPE (query)) {
681     case GST_QUERY_LATENCY:{
682       GstClockTime min_latency, max_latency;
683
684       /* device must be open */
685       if (!GST_V4L2_IS_OPEN (src->v4l2object)) {
686         GST_WARNING_OBJECT (src,
687             "Can't give latency since device isn't open !");
688         goto done;
689       }
690
691       /* we must have a framerate */
692       if (src->fps_n <= 0 || src->fps_d <= 0) {
693         GST_WARNING_OBJECT (src,
694             "Can't give latency since framerate isn't fixated !");
695         goto done;
696       }
697
698       /* min latency is the time to capture one frame */
699       min_latency =
700           gst_util_uint64_scale_int (GST_SECOND, src->fps_d, src->fps_n);
701
702       /* max latency is total duration of the frame buffer */
703       max_latency = src->num_buffers * min_latency;
704
705       GST_DEBUG_OBJECT (bsrc,
706           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
707           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
708
709       /* we are always live, the min latency is 1 frame and the max latency is
710        * the complete buffer of frames. */
711       gst_query_set_latency (query, TRUE, min_latency, max_latency);
712
713       res = TRUE;
714       break;
715     }
716     default:
717       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
718       break;
719   }
720
721 done:
722
723   return res;
724 }
725
726 /* start and stop are not symmetric -- start will open the device, but not start
727  * capture. it's setcaps that will start capture, which is called via basesrc's
728  * negotiate method. stop will both stop capture and close the device.
729  */
730 static gboolean
731 gst_v4l2src_start (GstBaseSrc * src)
732 {
733   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
734
735   v4l2src->offset = 0;
736
737   /* activate settings for first frame */
738   v4l2src->ctrl_time = 0;
739   gst_object_sync_values (G_OBJECT (src), v4l2src->ctrl_time);
740
741   return TRUE;
742 }
743
744 static gboolean
745 gst_v4l2src_unlock (GstBaseSrc * src)
746 {
747   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
748
749   GST_LOG_OBJECT (src, "Flushing");
750   gst_poll_set_flushing (v4l2src->v4l2object->poll, TRUE);
751
752   return TRUE;
753 }
754
755 static gboolean
756 gst_v4l2src_unlock_stop (GstBaseSrc * src)
757 {
758   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
759
760   GST_LOG_OBJECT (src, "No longer flushing");
761   gst_poll_set_flushing (v4l2src->v4l2object->poll, FALSE);
762
763   return TRUE;
764 }
765
766 static gboolean
767 gst_v4l2src_stop (GstBaseSrc * src)
768 {
769   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
770
771   if (GST_V4L2_IS_ACTIVE (v4l2src->v4l2object)
772       && !gst_v4l2src_capture_stop (v4l2src))
773     return FALSE;
774
775   if (v4l2src->v4l2object->buffer != NULL) {
776     if (!gst_v4l2src_capture_deinit (v4l2src))
777       return FALSE;
778   }
779
780   v4l2src->fps_d = 0;
781   v4l2src->fps_n = 0;
782
783   return TRUE;
784 }
785
786 static GstStateChangeReturn
787 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
788 {
789   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
790   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
791
792   switch (transition) {
793     case GST_STATE_CHANGE_NULL_TO_READY:
794       /* open the device */
795       if (!gst_v4l2_object_start (v4l2src->v4l2object))
796         return GST_STATE_CHANGE_FAILURE;
797       break;
798     default:
799       break;
800   }
801
802   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
803
804   switch (transition) {
805     case GST_STATE_CHANGE_READY_TO_NULL:
806       /* close the device */
807       if (!gst_v4l2_object_stop (v4l2src->v4l2object))
808         return GST_STATE_CHANGE_FAILURE;
809
810       if (v4l2src->probed_caps) {
811         gst_caps_unref (v4l2src->probed_caps);
812         v4l2src->probed_caps = NULL;
813       }
814       break;
815     default:
816       break;
817   }
818
819   return ret;
820 }
821
822 static GstFlowReturn
823 gst_v4l2src_get_read (GstV4l2Src * v4l2src, GstBuffer ** buf)
824 {
825   gint amount;
826   gint ret;
827
828   gint buffersize;
829
830   buffersize = v4l2src->frame_byte_size;
831   /* In case the size per frame is unknown assume it's a streaming format (e.g.
832    * mpegts) and grab a reasonable default size instead */
833   if (buffersize == 0)
834     buffersize = GST_BASE_SRC (v4l2src)->blocksize;
835
836   *buf = gst_buffer_new_and_alloc (buffersize);
837
838   do {
839     ret = gst_poll_wait (v4l2src->v4l2object->poll, GST_CLOCK_TIME_NONE);
840     if (G_UNLIKELY (ret < 0)) {
841       if (errno == EBUSY)
842         goto stopped;
843       if (errno == ENXIO) {
844         GST_DEBUG_OBJECT (v4l2src,
845             "v4l2 device doesn't support polling. Disabling");
846         v4l2src->v4l2object->can_poll_device = FALSE;
847       } else {
848         if (errno != EAGAIN && errno != EINTR)
849           goto select_error;
850       }
851     }
852     amount =
853         v4l2_read (v4l2src->v4l2object->video_fd, GST_BUFFER_DATA (*buf),
854         buffersize);
855     if (amount == buffersize) {
856       break;
857     } else if (amount == -1) {
858       if (errno == EAGAIN || errno == EINTR) {
859         continue;
860       } else
861         goto read_error;
862     } else {
863       /* short reads can happen if a signal interrupts the read */
864       continue;
865     }
866   } while (TRUE);
867
868   /* we set the buffer metadata in gst_v4l2src_create() */
869
870   return GST_FLOW_OK;
871
872   /* ERRORS */
873 select_error:
874   {
875     GST_ELEMENT_ERROR (v4l2src, RESOURCE, READ, (NULL),
876         ("select error %d: %s (%d)", ret, g_strerror (errno), errno));
877     return GST_FLOW_ERROR;
878   }
879 stopped:
880   {
881     GST_DEBUG ("stop called");
882     return GST_FLOW_WRONG_STATE;
883   }
884 read_error:
885   {
886     GST_ELEMENT_ERROR (v4l2src, RESOURCE, READ,
887         (_("Error reading %d bytes from device '%s'."),
888             buffersize, v4l2src->v4l2object->videodev), GST_ERROR_SYSTEM);
889     gst_buffer_unref (*buf);
890     return GST_FLOW_ERROR;
891   }
892 }
893
894 static GstFlowReturn
895 gst_v4l2src_get_mmap (GstV4l2Src * v4l2src, GstBuffer ** buf)
896 {
897   GstBuffer *temp;
898   GstFlowReturn ret;
899   guint size;
900   guint count = 0;
901
902 again:
903   ret = gst_v4l2src_grab_frame (v4l2src, &temp);
904   if (G_UNLIKELY (ret != GST_FLOW_OK))
905     goto done;
906
907   if (v4l2src->frame_byte_size > 0) {
908     size = GST_BUFFER_SIZE (temp);
909
910     /* if size does not match what we expected, try again */
911     if (size != v4l2src->frame_byte_size) {
912       GST_ELEMENT_WARNING (v4l2src, RESOURCE, READ,
913           (_("Got unexpected frame size of %u instead of %u."),
914               size, v4l2src->frame_byte_size), (NULL));
915       gst_buffer_unref (temp);
916       if (count++ > 50)
917         goto size_error;
918
919       goto again;
920     }
921   }
922
923   *buf = temp;
924 done:
925   return ret;
926
927   /* ERRORS */
928 size_error:
929   {
930     GST_ELEMENT_ERROR (v4l2src, RESOURCE, READ,
931         (_("Error reading %d bytes on device '%s'."),
932             v4l2src->frame_byte_size, v4l2src->v4l2object->videodev), (NULL));
933     return GST_FLOW_ERROR;
934   }
935 }
936
937 static GstFlowReturn
938 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
939 {
940   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
941   int i;
942   GstFlowReturn ret;
943
944   for (i = 0; i < v4l2src->decimate - 1; i++) {
945     ret = v4l2src->get_frame (v4l2src, buf);
946     if (ret != GST_FLOW_OK) {
947       return ret;
948     }
949     gst_buffer_unref (*buf);
950   }
951
952   ret = v4l2src->get_frame (v4l2src, buf);
953
954   /* set buffer metadata */
955   if (G_LIKELY (ret == GST_FLOW_OK && *buf)) {
956     GstClock *clock;
957     GstClockTime timestamp;
958
959     GST_BUFFER_OFFSET (*buf) = v4l2src->offset++;
960     GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset;
961
962     /* timestamps, LOCK to get clock and base time. */
963     /* FIXME: element clock and base_time is rarely changing */
964     GST_OBJECT_LOCK (v4l2src);
965     if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
966       /* we have a clock, get base time and ref clock */
967       timestamp = GST_ELEMENT (v4l2src)->base_time;
968       gst_object_ref (clock);
969     } else {
970       /* no clock, can't set timestamps */
971       timestamp = GST_CLOCK_TIME_NONE;
972     }
973     GST_OBJECT_UNLOCK (v4l2src);
974
975     if (G_LIKELY (clock)) {
976       /* the time now is the time of the clock minus the base time */
977       timestamp = gst_clock_get_time (clock) - timestamp;
978       gst_object_unref (clock);
979
980       /* if we have a framerate adjust timestamp for frame latency */
981       if (GST_CLOCK_TIME_IS_VALID (v4l2src->duration)) {
982         if (timestamp > v4l2src->duration)
983           timestamp -= v4l2src->duration;
984         else
985           timestamp = 0;
986       }
987     }
988
989     /* activate settings for next frame */
990     if (GST_CLOCK_TIME_IS_VALID (v4l2src->duration)) {
991       v4l2src->ctrl_time += v4l2src->duration;
992     } else {
993       /* this is not very good (as it should be the next timestamp),
994        * still good enough for linear fades (as long as it is not -1) 
995        */
996       v4l2src->ctrl_time = timestamp;
997     }
998     gst_object_sync_values (G_OBJECT (src), v4l2src->ctrl_time);
999     GST_INFO_OBJECT (src, "sync to %" GST_TIME_FORMAT,
1000         GST_TIME_ARGS (v4l2src->ctrl_time));
1001
1002     /* FIXME: use the timestamp from the buffer itself! */
1003     GST_BUFFER_TIMESTAMP (*buf) = timestamp;
1004     GST_BUFFER_DURATION (*buf) = v4l2src->duration;
1005   }
1006   return ret;
1007 }
1008
1009
1010 /* GstURIHandler interface */
1011 static GstURIType
1012 gst_v4l2src_uri_get_type (void)
1013 {
1014   return GST_URI_SRC;
1015 }
1016
1017 static gchar **
1018 gst_v4l2src_uri_get_protocols (void)
1019 {
1020   static gchar *protocols[] = { (char *) "v4l2", NULL };
1021
1022   return protocols;
1023 }
1024
1025 static const gchar *
1026 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
1027 {
1028   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1029
1030   if (v4l2src->v4l2object->videodev != NULL) {
1031     gchar uri[256];
1032
1033     /* need to return a const string, but also don't want to leak the generated
1034      * string, so just intern it - there's a limited number of video devices
1035      * after all */
1036     g_snprintf (uri, sizeof (uri), "v4l2://%s", v4l2src->v4l2object->videodev);
1037     return g_intern_string (uri);
1038   }
1039
1040   return "v4l2://";
1041 }
1042
1043 static gboolean
1044 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri)
1045 {
1046   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1047   const gchar *device = DEFAULT_PROP_DEVICE;
1048
1049   if (strcmp (uri, "v4l2://") != 0) {
1050     device = uri + 7;
1051   }
1052   g_object_set (v4l2src, "device", device, NULL);
1053
1054   return TRUE;
1055 }
1056
1057
1058 static void
1059 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1060 {
1061   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1062
1063   iface->get_type = gst_v4l2src_uri_get_type;
1064   iface->get_protocols = gst_v4l2src_uri_get_protocols;
1065   iface->get_uri = gst_v4l2src_uri_get_uri;
1066   iface->set_uri = gst_v4l2src_uri_set_uri;
1067 }