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