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