Merge branch 'move_subdir_rtsp-server' into tizen_gst_1.19.2_mono
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / sys / v4l2 / gstv4l2src.c
1 /* GStreamer
2  *
3  * Copyright (C) 2001-2002 Ronald Bultje <rbultje@ronald.bitfreak.net>
4  *               2006 Edgard Lima <edgard.lima@gmail.com>
5  *
6  * gstv4l2src.c: Video4Linux2 source element
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:element-v4l2src
26  * @title: v4l2src
27  *
28  * v4l2src can be used to capture video from v4l2 devices, like webcams and tv
29  * cards.
30  *
31  * ## Example launch lines
32  * |[
33  * gst-launch-1.0 v4l2src ! xvimagesink
34  * ]| This pipeline shows the video captured from /dev/video0 tv card and for
35  * webcams.
36  * |[
37  * gst-launch-1.0 v4l2src ! jpegdec ! xvimagesink
38  * ]| This pipeline shows the video captured from a webcam that delivers jpeg
39  * images.
40  *
41  * Since 1.14, the use of libv4l2 has been disabled due to major bugs in the
42  * emulation layer. To enable usage of this library, set the environment
43  * variable GST_V4L2_USE_LIBV4L2=1.
44  */
45
46 #ifdef HAVE_CONFIG_H
47 #include <config.h>
48 #endif
49
50 #include <string.h>
51 #include <sys/time.h>
52 #include <unistd.h>
53
54 #include <gst/video/gstvideometa.h>
55 #include <gst/video/gstvideopool.h>
56
57 #include "gstv4l2elements.h"
58 #include "gstv4l2src.h"
59
60 #include "gstv4l2colorbalance.h"
61 #include "gstv4l2tuner.h"
62 #include "gstv4l2vidorient.h"
63
64 #include "gst/gst-i18n-plugin.h"
65
66 GST_DEBUG_CATEGORY (v4l2src_debug);
67 #define GST_CAT_DEFAULT v4l2src_debug
68
69 #define DEFAULT_PROP_DEVICE   "/dev/video0"
70
71 enum
72 {
73   PROP_0,
74   V4L2_STD_OBJECT_PROPS,
75 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
76   PROP_CAMERA_ID,
77 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
78 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
79   PROP_AUTO_SCAN_DEVICE,
80 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
81 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
82   PROP_TBM_OUTPUT,
83 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
84   PROP_LAST
85 };
86
87 /* signals and args */
88 enum
89 {
90   SIGNAL_PRE_SET_FORMAT,
91   LAST_SIGNAL
92 };
93
94 static guint gst_v4l2_signals[LAST_SIGNAL] = { 0 };
95
96 GST_IMPLEMENT_V4L2_COLOR_BALANCE_METHODS (GstV4l2Src, gst_v4l2src);
97 GST_IMPLEMENT_V4L2_TUNER_METHODS (GstV4l2Src, gst_v4l2src);
98 GST_IMPLEMENT_V4L2_VIDORIENT_METHODS (GstV4l2Src, gst_v4l2src);
99
100 static void gst_v4l2src_uri_handler_init (gpointer g_iface,
101     gpointer iface_data);
102
103 #define gst_v4l2src_parent_class parent_class
104 G_DEFINE_TYPE_WITH_CODE (GstV4l2Src, gst_v4l2src, GST_TYPE_PUSH_SRC,
105     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_v4l2src_uri_handler_init);
106     G_IMPLEMENT_INTERFACE (GST_TYPE_TUNER, gst_v4l2src_tuner_interface_init);
107     G_IMPLEMENT_INTERFACE (GST_TYPE_COLOR_BALANCE,
108         gst_v4l2src_color_balance_interface_init);
109     G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_ORIENTATION,
110         gst_v4l2src_video_orientation_interface_init));
111 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (v4l2src,
112     "v4l2src", GST_RANK_PRIMARY, GST_TYPE_V4L2SRC, v4l2_element_init (plugin));
113
114 struct PreferredCapsInfo
115 {
116   gint width;
117   gint height;
118   gint fps_n;
119   gint fps_d;
120 };
121
122 static void gst_v4l2src_finalize (GstV4l2Src * v4l2src);
123
124 /* element methods */
125 static GstStateChangeReturn gst_v4l2src_change_state (GstElement * element,
126     GstStateChange transition);
127
128 /* basesrc methods */
129 static gboolean gst_v4l2src_start (GstBaseSrc * src);
130 static gboolean gst_v4l2src_unlock (GstBaseSrc * src);
131 static gboolean gst_v4l2src_unlock_stop (GstBaseSrc * src);
132 static gboolean gst_v4l2src_stop (GstBaseSrc * src);
133 static GstCaps *gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter);
134 static gboolean gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query);
135 static gboolean gst_v4l2src_decide_allocation (GstBaseSrc * src,
136     GstQuery * query);
137 static GstFlowReturn gst_v4l2src_create (GstPushSrc * src, GstBuffer ** out);
138 static GstCaps *gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps,
139     struct PreferredCapsInfo *pref);
140 static gboolean gst_v4l2src_negotiate (GstBaseSrc * basesrc);
141
142 static void gst_v4l2src_set_property (GObject * object, guint prop_id,
143     const GValue * value, GParamSpec * pspec);
144 static void gst_v4l2src_get_property (GObject * object, guint prop_id,
145     GValue * value, GParamSpec * pspec);
146
147 static void
148 gst_v4l2src_class_init (GstV4l2SrcClass * klass)
149 {
150   GObjectClass *gobject_class;
151   GstElementClass *element_class;
152   GstBaseSrcClass *basesrc_class;
153   GstPushSrcClass *pushsrc_class;
154
155   gobject_class = G_OBJECT_CLASS (klass);
156   element_class = GST_ELEMENT_CLASS (klass);
157   basesrc_class = GST_BASE_SRC_CLASS (klass);
158   pushsrc_class = GST_PUSH_SRC_CLASS (klass);
159
160   gobject_class->finalize = (GObjectFinalizeFunc) gst_v4l2src_finalize;
161   gobject_class->set_property = gst_v4l2src_set_property;
162   gobject_class->get_property = gst_v4l2src_get_property;
163
164   element_class->change_state = gst_v4l2src_change_state;
165
166   gst_v4l2_object_install_properties_helper (gobject_class,
167       DEFAULT_PROP_DEVICE);
168
169 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
170   /**
171    * GstV4l2Src:camera-id:
172    *
173    * The value which is set by application will be used as a number of device node.
174    * ex) 1 -> /dev/video1
175    */
176   g_object_class_install_property (gobject_class, PROP_CAMERA_ID,
177       g_param_spec_uint ("camera-id", "Camera ID",
178           "Camera ID for device node", 0, G_MAXUINT, 0,
179           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
180 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
181 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
182   /**
183    * GstV4l2Src:auto-scan-device:
184    */
185   g_object_class_install_property (gobject_class, PROP_AUTO_SCAN_DEVICE,
186       g_param_spec_boolean ("auto-scan-device", "Scan device automatically",
187           "Scan all device nodes automatically until device open success.",
188           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
189 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
190 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
191   /**
192    * GstV4l2Src:tbm-output
193    */
194   g_object_class_install_property (gobject_class, PROP_TBM_OUTPUT,
195       g_param_spec_boolean ("tbm-output", "Enable TBM for output buffer",
196           "It works for only DMABUF mode.",
197           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
198 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
199
200   /**
201    * GstV4l2Src::prepare-format:
202    * @v4l2src: the v4l2src instance
203    * @fd: the file descriptor of the current device
204    * @caps: the caps of the format being set
205    *
206    * This signal gets emitted before calling the v4l2 VIDIOC_S_FMT ioctl
207    * (set format). This allows for any custom configuration of the device to
208    * happen prior to the format being set.
209    * This is mostly useful for UVC H264 encoding cameras which need the H264
210    * Probe & Commit to happen prior to the normal Probe & Commit.
211    */
212   gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT] = g_signal_new ("prepare-format",
213       G_TYPE_FROM_CLASS (klass),
214       G_SIGNAL_RUN_LAST,
215       0, NULL, NULL, NULL, G_TYPE_NONE, 2, G_TYPE_INT, GST_TYPE_CAPS);
216
217   gst_element_class_set_static_metadata (element_class,
218       "Video (video4linux2) Source", "Source/Video",
219       "Reads frames from a Video4Linux2 device",
220       "Edgard Lima <edgard.lima@gmail.com>, "
221       "Stefan Kost <ensonic@users.sf.net>");
222
223   gst_element_class_add_pad_template
224       (element_class,
225       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
226           gst_v4l2_object_get_all_caps ()));
227
228   basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_v4l2src_get_caps);
229   basesrc_class->start = GST_DEBUG_FUNCPTR (gst_v4l2src_start);
230   basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock);
231   basesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_v4l2src_unlock_stop);
232   basesrc_class->stop = GST_DEBUG_FUNCPTR (gst_v4l2src_stop);
233   basesrc_class->query = GST_DEBUG_FUNCPTR (gst_v4l2src_query);
234   basesrc_class->negotiate = GST_DEBUG_FUNCPTR (gst_v4l2src_negotiate);
235   basesrc_class->decide_allocation =
236       GST_DEBUG_FUNCPTR (gst_v4l2src_decide_allocation);
237
238   pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_v4l2src_create);
239
240   klass->v4l2_class_devices = NULL;
241
242   GST_DEBUG_CATEGORY_INIT (v4l2src_debug, "v4l2src", 0, "V4L2 source element");
243 }
244
245 static void
246 gst_v4l2src_init (GstV4l2Src * v4l2src)
247 {
248   /* fixme: give an update_fps_function */
249   v4l2src->v4l2object = gst_v4l2_object_new (GST_ELEMENT (v4l2src),
250       GST_OBJECT (GST_BASE_SRC_PAD (v4l2src)), V4L2_BUF_TYPE_VIDEO_CAPTURE,
251       DEFAULT_PROP_DEVICE, gst_v4l2_get_input, gst_v4l2_set_input, NULL);
252
253   /* Avoid the slow probes */
254   v4l2src->v4l2object->skip_try_fmt_probes = TRUE;
255 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
256   v4l2src->v4l2object->auto_scan_device = TRUE;
257 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
258
259   gst_base_src_set_format (GST_BASE_SRC (v4l2src), GST_FORMAT_TIME);
260   gst_base_src_set_live (GST_BASE_SRC (v4l2src), TRUE);
261 }
262
263
264 static void
265 gst_v4l2src_finalize (GstV4l2Src * v4l2src)
266 {
267   gst_v4l2_object_destroy (v4l2src->v4l2object);
268
269   G_OBJECT_CLASS (parent_class)->finalize ((GObject *) (v4l2src));
270 }
271
272
273 static void
274 gst_v4l2src_set_property (GObject * object,
275     guint prop_id, const GValue * value, GParamSpec * pspec)
276 {
277   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
278
279   if (!gst_v4l2_object_set_property_helper (v4l2src->v4l2object,
280           prop_id, value, pspec)) {
281     switch (prop_id) {
282 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
283       case PROP_CAMERA_ID:
284         g_free (v4l2src->v4l2object->videodev);
285
286         v4l2src->camera_id = g_value_get_uint (value);
287         v4l2src->v4l2object->videodev = g_strdup_printf ("/dev/video%u", v4l2src->camera_id);
288
289         GST_INFO_OBJECT (v4l2src, "videodev [%s]", v4l2src->v4l2object->videodev);
290         break;
291 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
292 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
293       case PROP_AUTO_SCAN_DEVICE:
294         v4l2src->v4l2object->auto_scan_device = g_value_get_boolean (value);
295         GST_INFO_OBJECT (v4l2src, "auto scan device [%d]", v4l2src->v4l2object->auto_scan_device);
296         break;
297 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
298 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
299       case PROP_TBM_OUTPUT:
300         v4l2src->v4l2object->tbm_output = g_value_get_boolean (value);
301         GST_INFO_OBJECT (v4l2src, "tbm output [%d]", v4l2src->v4l2object->tbm_output);
302         break;
303 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
304       default:
305         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
306         break;
307     }
308   }
309 }
310
311 static void
312 gst_v4l2src_get_property (GObject * object,
313     guint prop_id, GValue * value, GParamSpec * pspec)
314 {
315   GstV4l2Src *v4l2src = GST_V4L2SRC (object);
316
317   if (!gst_v4l2_object_get_property_helper (v4l2src->v4l2object,
318           prop_id, value, pspec)) {
319     switch (prop_id) {
320 #ifdef TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID
321       case PROP_CAMERA_ID:
322         g_value_set_uint (value, v4l2src->camera_id);
323         break;
324 #endif /* TIZEN_FEATURE_V4L2SRC_SUPPORT_CAMERA_ID */
325 #ifdef TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE
326       case PROP_AUTO_SCAN_DEVICE:
327         GST_INFO_OBJECT (v4l2src, "auto scan device [%d]", v4l2src->v4l2object->auto_scan_device);
328         g_value_set_boolean (value, v4l2src->v4l2object->auto_scan_device);
329         break;
330 #endif /* TIZEN_FEATURE_V4L2SRC_AUTO_SCAN_DEVICE_NODE */
331 #ifdef TIZEN_FEATURE_V4L2_TBM_SUPPORT
332       case PROP_TBM_OUTPUT:
333         GST_INFO_OBJECT (v4l2src, "tbm output [%d]", v4l2src->v4l2object->tbm_output);
334         g_value_set_boolean (value, v4l2src->v4l2object->tbm_output);
335         break;
336 #endif /* TIZEN_FEATURE_V4L2_TBM_SUPPORT */
337       default:
338         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
339         break;
340     }
341   }
342 }
343
344 static gboolean
345 gst_vl42_src_fixate_fields (GQuark field_id, GValue * value, gpointer user_data)
346 {
347   GstStructure *s = user_data;
348
349   if (field_id == g_quark_from_string ("interlace-mode"))
350     return TRUE;
351
352   if (field_id == g_quark_from_string ("colorimetry"))
353     return TRUE;
354
355   gst_structure_fixate_field (s, g_quark_to_string (field_id));
356
357   return TRUE;
358 }
359
360 static void
361 gst_v4l2_src_fixate_struct_with_preference (GstStructure * s,
362     struct PreferredCapsInfo *pref)
363 {
364   if (gst_structure_has_field (s, "width"))
365     gst_structure_fixate_field_nearest_int (s, "width", pref->width);
366
367   if (gst_structure_has_field (s, "height"))
368     gst_structure_fixate_field_nearest_int (s, "height", pref->height);
369
370   if (gst_structure_has_field (s, "framerate"))
371     gst_structure_fixate_field_nearest_fraction (s, "framerate", pref->fps_n,
372         pref->fps_d);
373
374   /* Finally, fixate everything else except the interlace-mode and colorimetry
375    * which still need further negotiation as it wasn't probed */
376   gst_structure_map_in_place (s, gst_vl42_src_fixate_fields, s);
377 }
378
379 static void
380 gst_v4l2_src_parse_fixed_struct (GstStructure * s,
381     gint * width, gint * height, gint * fps_n, gint * fps_d)
382 {
383   if (gst_structure_has_field (s, "width") && width)
384     gst_structure_get_int (s, "width", width);
385
386   if (gst_structure_has_field (s, "height") && height)
387     gst_structure_get_int (s, "height", height);
388
389   if (gst_structure_has_field (s, "framerate") && fps_n && fps_d)
390     gst_structure_get_fraction (s, "framerate", fps_n, fps_d);
391 }
392
393 /* TODO Consider framerate */
394 static gint
395 gst_v4l2src_fixed_caps_compare (GstCaps * caps_a, GstCaps * caps_b,
396     struct PreferredCapsInfo *pref)
397 {
398   GstStructure *a, *b;
399   gint aw = G_MAXINT, ah = G_MAXINT, ad = G_MAXINT;
400   gint bw = G_MAXINT, bh = G_MAXINT, bd = G_MAXINT;
401   gint ret;
402
403   a = gst_caps_get_structure (caps_a, 0);
404   b = gst_caps_get_structure (caps_b, 0);
405
406   gst_v4l2_src_parse_fixed_struct (a, &aw, &ah, NULL, NULL);
407   gst_v4l2_src_parse_fixed_struct (b, &bw, &bh, NULL, NULL);
408
409   /* When both are smaller then pref, just append to the end */
410   if ((bw < pref->width || bh < pref->height)
411       && (aw < pref->width || ah < pref->height)) {
412     ret = 1;
413     goto done;
414   }
415
416   /* If a is smaller then pref and not b, then a goes after b */
417   if (aw < pref->width || ah < pref->height) {
418     ret = 1;
419     goto done;
420   }
421
422   /* If b is smaller then pref and not a, then a goes before b */
423   if (bw < pref->width || bh < pref->height) {
424     ret = -1;
425     goto done;
426   }
427
428   /* Both are larger or equal to the preference, prefer the smallest */
429   ad = MAX (1, aw - pref->width) * MAX (1, ah - pref->height);
430   bd = MAX (1, bw - pref->width) * MAX (1, bh - pref->height);
431
432   /* Adjust slightly in case width/height matched the preference */
433   if (aw == pref->width)
434     ad -= 1;
435
436   if (ah == pref->height)
437     ad -= 1;
438
439   if (bw == pref->width)
440     bd -= 1;
441
442   if (bh == pref->height)
443     bd -= 1;
444
445   /* If the choices are equivalent, maintain the order */
446   if (ad == bd)
447     ret = 1;
448   else
449     ret = ad - bd;
450
451 done:
452   GST_TRACE ("Placing %ix%i (%s) %s %ix%i (%s)", aw, ah,
453       gst_structure_get_string (a, "format"), ret > 0 ? "after" : "before", bw,
454       bh, gst_structure_get_string (b, "format"));
455   return ret;
456 }
457
458 static gboolean
459 gst_v4l2src_set_format (GstV4l2Src * v4l2src, GstCaps * caps,
460     GstV4l2Error * error)
461 {
462   GstV4l2Object *obj;
463
464   obj = v4l2src->v4l2object;
465
466   /* make sure we stop capturing and dealloc buffers */
467   if (!gst_v4l2_object_stop (obj))
468     return FALSE;
469
470   g_signal_emit (v4l2src, gst_v4l2_signals[SIGNAL_PRE_SET_FORMAT], 0,
471       v4l2src->v4l2object->video_fd, caps);
472
473   return gst_v4l2_object_set_format (obj, caps, error);
474 }
475
476 static GstCaps *
477 gst_v4l2src_fixate (GstBaseSrc * basesrc, GstCaps * caps,
478     struct PreferredCapsInfo *pref)
479 {
480   GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
481   GstV4l2Object *obj = v4l2src->v4l2object;
482   GList *caps_list = NULL;
483   GstStructure *s;
484   gint i = G_MAXINT;
485   GstV4l2Error error = GST_V4L2_ERROR_INIT;
486   GstCaps *fcaps = NULL;
487
488   GST_DEBUG_OBJECT (basesrc, "Fixating caps %" GST_PTR_FORMAT, caps);
489   GST_DEBUG_OBJECT (basesrc, "Preferred size %ix%i", pref->width, pref->height);
490
491   /* Sort the structures to get the caps that is nearest to our preferences,
492    * first. Use single struct caps for sorting so we preserve the features.  */
493   for (i = 0; i < gst_caps_get_size (caps); i++) {
494     GstCaps *tmp = gst_caps_copy_nth (caps, i);
495
496     s = gst_caps_get_structure (tmp, 0);
497     gst_v4l2_src_fixate_struct_with_preference (s, pref);
498
499     caps_list = g_list_insert_sorted_with_data (caps_list, tmp,
500         (GCompareDataFunc) gst_v4l2src_fixed_caps_compare, pref);
501   }
502
503   gst_caps_unref (caps);
504   caps = gst_caps_new_empty ();
505
506   while (caps_list) {
507     GstCaps *tmp = caps_list->data;
508     caps_list = g_list_delete_link (caps_list, caps_list);
509     gst_caps_append (caps, tmp);
510   }
511
512   GST_DEBUG_OBJECT (basesrc, "sorted and normalized caps %" GST_PTR_FORMAT,
513       caps);
514
515   /* Each structure in the caps has been fixated, except for the
516    * interlace-mode and colorimetry. Now normalize the caps so we can
517    * enumerate the possibilities */
518   caps = gst_caps_normalize (caps);
519
520   for (i = 0; i < gst_caps_get_size (caps); ++i) {
521     gst_v4l2_clear_error (&error);
522     if (fcaps)
523       gst_caps_unref (fcaps);
524
525     fcaps = gst_caps_copy_nth (caps, i);
526
527     /* try hard to avoid TRY_FMT since some UVC camera just crash when this
528      * is called at run-time. */
529     if (gst_v4l2_object_caps_is_subset (obj, fcaps)) {
530       gst_caps_unref (fcaps);
531       fcaps = gst_v4l2_object_get_current_caps (obj);
532       break;
533     }
534
535     /* Just check if the format is acceptable, once we know
536      * no buffers should be outstanding we try S_FMT.
537      *
538      * Basesrc will do an allocation query that
539      * should indirectly reclaim buffers, after that we can
540      * set the format and then configure our pool */
541     if (gst_v4l2_object_try_format (obj, fcaps, &error)) {
542       /* make sure the caps changed before doing anything */
543       if (gst_v4l2_object_caps_equal (obj, fcaps))
544         break;
545
546       v4l2src->renegotiation_adjust = v4l2src->offset + 1;
547       v4l2src->pending_set_fmt = TRUE;
548       break;
549     }
550
551     /* Only EIVAL make sense, report any other errors, this way we don't keep
552      * probing if the device got disconnected, or if it's firmware stopped
553      * responding */
554     if (error.error->code != GST_RESOURCE_ERROR_SETTINGS) {
555       i = G_MAXINT;
556       break;
557     }
558   }
559
560   if (i >= gst_caps_get_size (caps)) {
561     gst_v4l2_error (v4l2src, &error);
562     if (fcaps)
563       gst_caps_unref (fcaps);
564     gst_caps_unref (caps);
565     return NULL;
566   }
567
568   gst_caps_unref (caps);
569
570   GST_DEBUG_OBJECT (basesrc, "fixated caps %" GST_PTR_FORMAT, fcaps);
571
572   return fcaps;
573 }
574
575 static gboolean
576 gst_v4l2src_query_preferred_dv_timings (GstV4l2Src * v4l2src,
577     struct PreferredCapsInfo *pref)
578 {
579   GstV4l2Object *obj = v4l2src->v4l2object;
580   struct v4l2_dv_timings dv_timings = { 0, };
581   const struct v4l2_bt_timings *bt = &dv_timings.bt;
582   gint tot_width, tot_height;
583   gint gcd;
584
585   if (!gst_v4l2_query_dv_timings (obj, &dv_timings))
586     return FALSE;
587
588   pref->width = bt->width;
589   pref->height = bt->height;
590
591   tot_height = bt->height +
592       bt->vfrontporch + bt->vsync + bt->vbackporch +
593       bt->il_vfrontporch + bt->il_vsync + bt->il_vbackporch;
594   tot_width = bt->width + bt->hfrontporch + bt->hsync + bt->hbackporch;
595
596   pref->fps_n = bt->pixelclock;
597   pref->fps_d = tot_width * tot_height;
598
599   if (bt->interlaced)
600     pref->fps_d /= 2;
601
602   gcd = gst_util_greatest_common_divisor (pref->fps_n, pref->fps_d);
603   pref->fps_n /= gcd;
604   pref->fps_d /= gcd;
605
606   /* If are are not streaming (e.g. we received source-change event), lock the
607    * new timing immediatly so that TRY_FMT can properly work */
608   if (!obj->pool || !GST_V4L2_BUFFER_POOL_IS_STREAMING (obj->pool)) {
609     gst_v4l2_set_dv_timings (obj, &dv_timings);
610     /* Setting a new DV timings invalidates the probed caps. */
611     gst_caps_replace (&obj->probed_caps, NULL);
612   }
613
614   GST_INFO_OBJECT (v4l2src, "Using DV Timings: %i x %i (%i/%i fps)",
615       pref->width, pref->height, pref->fps_n, pref->fps_d);
616
617   return TRUE;
618 }
619
620 static gboolean
621 gst_v4l2src_query_preferred_size (GstV4l2Src * v4l2src,
622     struct PreferredCapsInfo *pref)
623 {
624   struct v4l2_input in = { 0, };
625
626   if (!gst_v4l2_get_input (v4l2src->v4l2object, &in.index))
627     return FALSE;
628
629   if (!gst_v4l2_query_input (v4l2src->v4l2object, &in))
630     return FALSE;
631
632   GST_INFO_OBJECT (v4l2src, "Detect input %u as `%s`", in.index, in.name);
633
634   /* Notify signal status using WARNING/INFO messages */
635   if (in.status & (V4L2_IN_ST_NO_POWER | V4L2_IN_ST_NO_SIGNAL)) {
636     if (!v4l2src->no_signal)
637       /* note: taken from decklinksrc element */
638       GST_ELEMENT_WARNING (v4l2src, RESOURCE, READ, ("Signal lost"),
639           ("No input source was detected - video frames invalid"));
640     v4l2src->no_signal = TRUE;
641   } else if (v4l2src->no_signal) {
642     if (v4l2src->no_signal)
643       GST_ELEMENT_INFO (v4l2src, RESOURCE, READ,
644           ("Signal recovered"), ("Input source detected"));
645     v4l2src->no_signal = FALSE;
646   }
647
648   if (in.capabilities & V4L2_IN_CAP_NATIVE_SIZE) {
649     GST_FIXME_OBJECT (v4l2src, "missing support for native video size");
650     return FALSE;
651   } else if (in.capabilities & V4L2_IN_CAP_DV_TIMINGS) {
652     return gst_v4l2src_query_preferred_dv_timings (v4l2src, pref);
653   } else if (in.capabilities & V4L2_IN_CAP_STD) {
654     GST_FIXME_OBJECT (v4l2src, "missing support for video standards");
655     return FALSE;
656   }
657
658   return FALSE;
659 }
660
661 static gboolean
662 gst_v4l2src_negotiate (GstBaseSrc * basesrc)
663 {
664   GstV4l2Src *v4l2src = GST_V4L2SRC (basesrc);
665   GstCaps *thiscaps;
666   GstCaps *caps = NULL;
667   GstCaps *peercaps = NULL;
668   gboolean result = FALSE;
669   /* Let's prefer a good resolution as of today's standard. */
670   struct PreferredCapsInfo pref = {
671     3840, 2160, 120, 1
672   };
673   gboolean have_pref;
674
675   /* For drivers that has DV timings or other default size query
676    * capabilities, we will prefer that resolution. This must happen before we
677    * probe the caps, as locking DV Timings or standards will change result of
678    * the caps enumeration. */
679   have_pref = gst_v4l2src_query_preferred_size (v4l2src, &pref);
680
681   /* first see what is possible on our source pad */
682   thiscaps = gst_pad_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
683   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
684
685   /* nothing or anything is allowed, we're done */
686   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
687     goto no_nego_needed;
688
689   /* get the peer caps without a filter as we'll filter ourselves later on */
690   peercaps = gst_pad_peer_query_caps (GST_BASE_SRC_PAD (basesrc), NULL);
691   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
692   if (peercaps && !gst_caps_is_any (peercaps)) {
693     /* Prefer the first caps we are compatible with that the peer proposed */
694     caps = gst_caps_intersect_full (peercaps, thiscaps,
695         GST_CAPS_INTERSECT_FIRST);
696
697     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
698
699     gst_caps_unref (thiscaps);
700   } else {
701     /* no peer or peer have ANY caps, work with our own caps then */
702     caps = thiscaps;
703   }
704
705   if (caps) {
706     /* now fixate */
707     if (!gst_caps_is_empty (caps)) {
708
709       /* otherwise consider the first structure from peercaps to be a
710        * preference. This is useful for matching a reported native display,
711        * or simply to avoid transformation to happen downstream. */
712       if (!have_pref && peercaps && !gst_caps_is_any (peercaps)) {
713         GstStructure *pref_s = gst_caps_get_structure (peercaps, 0);
714         pref_s = gst_structure_copy (pref_s);
715         gst_v4l2_src_fixate_struct_with_preference (pref_s, &pref);
716         gst_v4l2_src_parse_fixed_struct (pref_s, &pref.width, &pref.height,
717             &pref.fps_n, &pref.fps_d);
718         gst_structure_free (pref_s);
719       }
720
721       caps = gst_v4l2src_fixate (basesrc, caps, &pref);
722
723       /* Fixating may fail as we now set the selected format */
724       if (!caps) {
725         result = FALSE;
726         goto done;
727       }
728
729       GST_INFO_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
730
731       if (gst_caps_is_any (caps)) {
732         /* hmm, still anything, so element can do anything and
733          * nego is not needed */
734         result = TRUE;
735       } else if (gst_caps_is_fixed (caps)) {
736         /* yay, fixed caps, use those then */
737         result = gst_base_src_set_caps (basesrc, caps);
738       }
739     }
740     gst_caps_unref (caps);
741   }
742
743 done:
744   if (peercaps)
745     gst_caps_unref (peercaps);
746
747   return result;
748
749 no_nego_needed:
750   {
751     GST_INFO_OBJECT (basesrc, "no negotiation needed");
752     if (thiscaps)
753       gst_caps_unref (thiscaps);
754     return TRUE;
755   }
756 }
757
758 static GstCaps *
759 gst_v4l2src_get_caps (GstBaseSrc * src, GstCaps * filter)
760 {
761   GstV4l2Src *v4l2src;
762   GstV4l2Object *obj;
763
764   v4l2src = GST_V4L2SRC (src);
765   obj = v4l2src->v4l2object;
766
767   if (!GST_V4L2_IS_OPEN (obj)) {
768     return gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (v4l2src));
769   }
770
771   return gst_v4l2_object_get_caps (obj, filter);
772 }
773
774 static gboolean
775 gst_v4l2src_decide_allocation (GstBaseSrc * bsrc, GstQuery * query)
776 {
777   GstV4l2Src *src = GST_V4L2SRC (bsrc);
778   gboolean ret = TRUE;
779
780   if (src->pending_set_fmt) {
781     GstCaps *caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
782     GstV4l2Error error = GST_V4L2_ERROR_INIT;
783
784     caps = gst_caps_make_writable (caps);
785
786     ret = gst_v4l2src_set_format (src, caps, &error);
787     if (ret) {
788       GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL (src->v4l2object->pool);
789       gst_v4l2_buffer_pool_enable_resolution_change (pool);
790     } else {
791       gst_v4l2_error (src, &error);
792     }
793
794     gst_caps_unref (caps);
795     src->pending_set_fmt = FALSE;
796   } else if (gst_buffer_pool_is_active (src->v4l2object->pool)) {
797     /* Trick basesrc into not deactivating the active pool. Renegotiating here
798      * would otherwise turn off and on the camera. */
799     GstAllocator *allocator;
800     GstAllocationParams params;
801     GstBufferPool *pool;
802
803     gst_base_src_get_allocator (bsrc, &allocator, &params);
804     pool = gst_base_src_get_buffer_pool (bsrc);
805
806     if (gst_query_get_n_allocation_params (query))
807       gst_query_set_nth_allocation_param (query, 0, allocator, &params);
808     else
809       gst_query_add_allocation_param (query, allocator, &params);
810
811     if (gst_query_get_n_allocation_pools (query))
812       gst_query_set_nth_allocation_pool (query, 0, pool,
813           src->v4l2object->info.size, 1, 0);
814     else
815       gst_query_add_allocation_pool (query, pool, src->v4l2object->info.size, 1,
816           0);
817
818     if (pool)
819       gst_object_unref (pool);
820     if (allocator)
821       gst_object_unref (allocator);
822
823     return GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
824   }
825
826   if (ret) {
827     ret = gst_v4l2_object_decide_allocation (src->v4l2object, query);
828     if (ret)
829       ret = GST_BASE_SRC_CLASS (parent_class)->decide_allocation (bsrc, query);
830   }
831
832   if (ret) {
833     if (!gst_buffer_pool_set_active (src->v4l2object->pool, TRUE))
834       goto activate_failed;
835   }
836
837   return ret;
838
839 activate_failed:
840   {
841     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS,
842         (_("Failed to allocate required memory.")),
843         ("Buffer pool activation failed"));
844     return FALSE;
845   }
846 }
847
848 static gboolean
849 gst_v4l2src_query (GstBaseSrc * bsrc, GstQuery * query)
850 {
851   GstV4l2Src *src;
852   GstV4l2Object *obj;
853   gboolean res = FALSE;
854
855   src = GST_V4L2SRC (bsrc);
856   obj = src->v4l2object;
857
858   switch (GST_QUERY_TYPE (query)) {
859     case GST_QUERY_LATENCY:{
860       GstClockTime min_latency, max_latency;
861       guint32 fps_n, fps_d;
862       guint num_buffers = 0;
863
864       /* device must be open */
865       if (!GST_V4L2_IS_OPEN (obj)) {
866         GST_WARNING_OBJECT (src,
867             "Can't give latency since device isn't open !");
868         goto done;
869       }
870
871       fps_n = GST_V4L2_FPS_N (obj);
872       fps_d = GST_V4L2_FPS_D (obj);
873
874       /* we must have a framerate */
875       if (fps_n <= 0 || fps_d <= 0) {
876         GST_WARNING_OBJECT (src,
877             "Can't give latency since framerate isn't fixated !");
878         goto done;
879       }
880
881       /* min latency is the time to capture one frame/field */
882       min_latency = gst_util_uint64_scale_int (GST_SECOND, fps_d, fps_n);
883       if (GST_VIDEO_INFO_INTERLACE_MODE (&obj->info) ==
884           GST_VIDEO_INTERLACE_MODE_ALTERNATE)
885         min_latency /= 2;
886
887       /* max latency is total duration of the frame buffer */
888       if (obj->pool != NULL)
889         num_buffers = GST_V4L2_BUFFER_POOL_CAST (obj->pool)->max_latency;
890
891       if (num_buffers == 0)
892         max_latency = -1;
893       else
894         max_latency = num_buffers * min_latency;
895
896       GST_DEBUG_OBJECT (bsrc,
897           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
898           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
899
900       /* we are always live, the min latency is 1 frame and the max latency is
901        * the complete buffer of frames. */
902       gst_query_set_latency (query, TRUE, min_latency, max_latency);
903
904       res = TRUE;
905       break;
906     }
907     default:
908       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
909       break;
910   }
911
912 done:
913
914   return res;
915 }
916
917 /* start and stop are not symmetric -- start will open the device, but not start
918  * capture. it's setcaps that will start capture, which is called via basesrc's
919  * negotiate method. stop will both stop capture and close the device.
920  */
921 static gboolean
922 gst_v4l2src_start (GstBaseSrc * src)
923 {
924   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
925
926   v4l2src->offset = 0;
927   v4l2src->next_offset_same = FALSE;
928   v4l2src->renegotiation_adjust = 0;
929
930   /* activate settings for first frame */
931   v4l2src->ctrl_time = 0;
932   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
933
934   v4l2src->has_bad_timestamp = FALSE;
935   v4l2src->last_timestamp = 0;
936
937   return TRUE;
938 }
939
940 static gboolean
941 gst_v4l2src_unlock (GstBaseSrc * src)
942 {
943   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
944   return gst_v4l2_object_unlock (v4l2src->v4l2object);
945 }
946
947 static gboolean
948 gst_v4l2src_unlock_stop (GstBaseSrc * src)
949 {
950   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
951
952   v4l2src->last_timestamp = 0;
953
954   return gst_v4l2_object_unlock_stop (v4l2src->v4l2object);
955 }
956
957 static gboolean
958 gst_v4l2src_stop (GstBaseSrc * src)
959 {
960   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
961   GstV4l2Object *obj = v4l2src->v4l2object;
962
963   if (GST_V4L2_IS_ACTIVE (obj)) {
964     if (!gst_v4l2_object_stop (obj))
965       return FALSE;
966   }
967
968   v4l2src->pending_set_fmt = FALSE;
969
970   return TRUE;
971 }
972
973 static GstStateChangeReturn
974 gst_v4l2src_change_state (GstElement * element, GstStateChange transition)
975 {
976   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
977   GstV4l2Src *v4l2src = GST_V4L2SRC (element);
978   GstV4l2Object *obj = v4l2src->v4l2object;
979   GstV4l2Error error = GST_V4L2_ERROR_INIT;
980
981   switch (transition) {
982     case GST_STATE_CHANGE_NULL_TO_READY:
983       /* open the device */
984       if (!gst_v4l2_object_open (obj, &error)) {
985         gst_v4l2_error (v4l2src, &error);
986         return GST_STATE_CHANGE_FAILURE;
987       }
988       break;
989     default:
990       break;
991   }
992
993   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
994
995   switch (transition) {
996     case GST_STATE_CHANGE_READY_TO_NULL:
997       /* close the device */
998       if (!gst_v4l2_object_close (obj))
999         return GST_STATE_CHANGE_FAILURE;
1000
1001       break;
1002     default:
1003       break;
1004   }
1005
1006   return ret;
1007 }
1008
1009 static GstFlowReturn
1010 gst_v4l2src_create (GstPushSrc * src, GstBuffer ** buf)
1011 {
1012   GstV4l2Src *v4l2src = GST_V4L2SRC (src);
1013   GstV4l2Object *obj = v4l2src->v4l2object;
1014   GstFlowReturn ret;
1015   GstClock *clock;
1016   GstClockTime abs_time, base_time, timestamp, duration;
1017   GstClockTime delay;
1018   GstMessage *qos_msg;
1019   gboolean half_frame;
1020
1021   do {
1022     GstV4l2BufferPool *pool = GST_V4L2_BUFFER_POOL_CAST (obj->pool);
1023
1024     ret = GST_BASE_SRC_CLASS (parent_class)->alloc (GST_BASE_SRC (src), 0,
1025         obj->info.size, buf);
1026
1027     if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1028       if (ret == GST_V4L2_FLOW_RESOLUTION_CHANGE) {
1029         GST_INFO_OBJECT (v4l2src, "Resolution change detected.");
1030
1031         /* It is required to always cycle through streamoff, we also need to
1032          * streamoff in order to allow locking a new DV_TIMING which will
1033          * influence the output of TRY_FMT */
1034         gst_v4l2src_stop (GST_BASE_SRC (src));
1035
1036         /* Force renegotiation */
1037         v4l2src->renegotiation_adjust = v4l2src->offset + 1;
1038         v4l2src->pending_set_fmt = TRUE;
1039
1040         if (!gst_base_src_negotiate (GST_BASE_SRC (src))) {
1041           ret = GST_FLOW_NOT_NEGOTIATED;
1042           goto error;
1043         }
1044
1045         continue;
1046       }
1047       goto alloc_failed;
1048     }
1049
1050     ret = gst_v4l2_buffer_pool_process (pool, buf, NULL);
1051
1052   } while (ret == GST_V4L2_FLOW_CORRUPTED_BUFFER ||
1053       ret == GST_V4L2_FLOW_RESOLUTION_CHANGE);
1054
1055   if (G_UNLIKELY (ret != GST_FLOW_OK))
1056     goto error;
1057
1058   timestamp = GST_BUFFER_TIMESTAMP (*buf);
1059   duration = obj->duration;
1060
1061   /* timestamps, LOCK to get clock and base time. */
1062   /* FIXME: element clock and base_time is rarely changing */
1063   GST_OBJECT_LOCK (v4l2src);
1064   if ((clock = GST_ELEMENT_CLOCK (v4l2src))) {
1065     /* we have a clock, get base time and ref clock */
1066     base_time = GST_ELEMENT (v4l2src)->base_time;
1067     gst_object_ref (clock);
1068   } else {
1069     /* no clock, can't set timestamps */
1070     base_time = GST_CLOCK_TIME_NONE;
1071   }
1072   GST_OBJECT_UNLOCK (v4l2src);
1073
1074   /* sample pipeline clock */
1075   if (clock) {
1076     abs_time = gst_clock_get_time (clock);
1077     gst_object_unref (clock);
1078   } else {
1079     abs_time = GST_CLOCK_TIME_NONE;
1080   }
1081
1082 retry:
1083   if (!v4l2src->has_bad_timestamp && timestamp != GST_CLOCK_TIME_NONE) {
1084     struct timespec now;
1085     GstClockTime gstnow;
1086
1087     /* v4l2 specs say to use the system time although many drivers switched to
1088      * the more desirable monotonic time. We first try to use the monotonic time
1089      * and see how that goes */
1090     clock_gettime (CLOCK_MONOTONIC, &now);
1091     gstnow = GST_TIMESPEC_TO_TIME (now);
1092
1093     if (timestamp > gstnow || (gstnow - timestamp) > (10 * GST_SECOND)) {
1094       /* very large diff, fall back to system time */
1095       gstnow = g_get_real_time () * GST_USECOND;
1096     }
1097
1098     /* Detect buggy drivers here, and stop using their timestamp. Failing any
1099      * of these condition would imply a very buggy driver:
1100      *   - Timestamp in the future
1101      *   - Timestamp is going backward compare to last seen timestamp
1102      *   - Timestamp is jumping forward for less then a frame duration
1103      *   - Delay is bigger then the actual timestamp
1104      * */
1105     if (timestamp > gstnow) {
1106       GST_WARNING_OBJECT (v4l2src,
1107           "Timestamp in the future detected, ignoring driver timestamps");
1108       v4l2src->has_bad_timestamp = TRUE;
1109       goto retry;
1110     }
1111
1112     if (v4l2src->last_timestamp > timestamp) {
1113       GST_WARNING_OBJECT (v4l2src,
1114           "Timestamp going backward, ignoring driver timestamps");
1115       v4l2src->has_bad_timestamp = TRUE;
1116       goto retry;
1117     }
1118
1119     delay = gstnow - timestamp;
1120
1121     if (delay > timestamp) {
1122       GST_WARNING_OBJECT (v4l2src,
1123           "Timestamp does not correlate with any clock, ignoring driver timestamps");
1124       v4l2src->has_bad_timestamp = TRUE;
1125       goto retry;
1126     }
1127
1128     /* Save last timestamp for sanity checks */
1129     v4l2src->last_timestamp = timestamp;
1130
1131     GST_DEBUG_OBJECT (v4l2src, "ts: %" GST_TIME_FORMAT " now %" GST_TIME_FORMAT
1132         " delay %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
1133         GST_TIME_ARGS (gstnow), GST_TIME_ARGS (delay));
1134   } else {
1135     /* we assume 1 frame/field latency otherwise */
1136     if (GST_CLOCK_TIME_IS_VALID (duration))
1137       delay = duration;
1138     else
1139       delay = 0;
1140   }
1141
1142   /* set buffer metadata */
1143
1144   if (G_LIKELY (abs_time != GST_CLOCK_TIME_NONE)) {
1145     /* the time now is the time of the clock minus the base time */
1146     timestamp = abs_time - base_time;
1147
1148     /* adjust for delay in the device */
1149     if (timestamp > delay)
1150       timestamp -= delay;
1151     else
1152       timestamp = 0;
1153   } else {
1154     timestamp = GST_CLOCK_TIME_NONE;
1155   }
1156
1157   /* activate settings for next frame */
1158   if (GST_CLOCK_TIME_IS_VALID (duration)) {
1159     v4l2src->ctrl_time += duration;
1160   } else {
1161     /* this is not very good (as it should be the next timestamp),
1162      * still good enough for linear fades (as long as it is not -1)
1163      */
1164     v4l2src->ctrl_time = timestamp;
1165   }
1166   gst_object_sync_values (GST_OBJECT (src), v4l2src->ctrl_time);
1167
1168   GST_LOG_OBJECT (src, "sync to %" GST_TIME_FORMAT " out ts %" GST_TIME_FORMAT,
1169       GST_TIME_ARGS (v4l2src->ctrl_time), GST_TIME_ARGS (timestamp));
1170
1171   if (v4l2src->next_offset_same &&
1172       GST_BUFFER_OFFSET_IS_VALID (*buf) &&
1173       GST_BUFFER_OFFSET (*buf) != v4l2src->offset) {
1174     /* Probably had a lost field then, best to forget about last field. */
1175     GST_WARNING_OBJECT (v4l2src,
1176         "lost field detected - ts: %" GST_TIME_FORMAT,
1177         GST_TIME_ARGS (timestamp));
1178     v4l2src->next_offset_same = FALSE;
1179   }
1180
1181   half_frame = (GST_BUFFER_FLAG_IS_SET (*buf, GST_VIDEO_BUFFER_FLAG_ONEFIELD));
1182   if (half_frame)
1183     v4l2src->next_offset_same = !v4l2src->next_offset_same;
1184
1185   /* use generated offset values only if there are not already valid ones
1186    * set by the v4l2 device */
1187   if (!GST_BUFFER_OFFSET_IS_VALID (*buf)
1188       || !GST_BUFFER_OFFSET_END_IS_VALID (*buf)
1189       || GST_BUFFER_OFFSET (*buf) <=
1190       (v4l2src->offset - v4l2src->renegotiation_adjust)) {
1191     GST_BUFFER_OFFSET (*buf) = v4l2src->offset;
1192     GST_BUFFER_OFFSET_END (*buf) = v4l2src->offset + 1;
1193     if (!half_frame || !v4l2src->next_offset_same)
1194       v4l2src->offset++;
1195   } else {
1196     /* adjust raw v4l2 device sequence, will restart at null in case of renegotiation
1197      * (streamoff/streamon) */
1198     GST_BUFFER_OFFSET (*buf) += v4l2src->renegotiation_adjust;
1199     GST_BUFFER_OFFSET_END (*buf) += v4l2src->renegotiation_adjust;
1200     /* check for frame loss with given (from v4l2 device) buffer offset */
1201     if ((v4l2src->offset != 0)
1202         && (!half_frame || v4l2src->next_offset_same)
1203         && (GST_BUFFER_OFFSET (*buf) != (v4l2src->offset + 1))) {
1204       guint64 lost_frame_count = GST_BUFFER_OFFSET (*buf) - v4l2src->offset - 1;
1205       GST_WARNING_OBJECT (v4l2src,
1206           "lost frames detected: count = %" G_GUINT64_FORMAT " - ts: %"
1207           GST_TIME_FORMAT, lost_frame_count, GST_TIME_ARGS (timestamp));
1208
1209       qos_msg = gst_message_new_qos (GST_OBJECT_CAST (v4l2src), TRUE,
1210           GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE, timestamp,
1211           GST_CLOCK_TIME_IS_VALID (duration) ? lost_frame_count *
1212           duration : GST_CLOCK_TIME_NONE);
1213       gst_element_post_message (GST_ELEMENT_CAST (v4l2src), qos_msg);
1214
1215     }
1216     v4l2src->offset = GST_BUFFER_OFFSET (*buf);
1217   }
1218
1219   GST_BUFFER_TIMESTAMP (*buf) = timestamp;
1220   GST_BUFFER_DURATION (*buf) = duration;
1221
1222   return ret;
1223
1224   /* ERROR */
1225 alloc_failed:
1226   {
1227     if (ret != GST_FLOW_FLUSHING)
1228       GST_ELEMENT_ERROR (src, RESOURCE, NO_SPACE_LEFT,
1229           ("Failed to allocate a buffer"), (NULL));
1230     return ret;
1231   }
1232 error:
1233   {
1234     gst_buffer_replace (buf, NULL);
1235     if (ret == GST_V4L2_FLOW_LAST_BUFFER) {
1236       GST_ELEMENT_ERROR (src, RESOURCE, FAILED,
1237           ("Driver returned a buffer with no payload, this most likely "
1238               "indicate a bug in the driver."), (NULL));
1239       ret = GST_FLOW_ERROR;
1240     } else {
1241       GST_DEBUG_OBJECT (src, "error processing buffer %d (%s)", ret,
1242           gst_flow_get_name (ret));
1243     }
1244     return ret;
1245   }
1246 }
1247
1248
1249 /* GstURIHandler interface */
1250 static GstURIType
1251 gst_v4l2src_uri_get_type (GType type)
1252 {
1253   return GST_URI_SRC;
1254 }
1255
1256 static const gchar *const *
1257 gst_v4l2src_uri_get_protocols (GType type)
1258 {
1259   static const gchar *protocols[] = { "v4l2", NULL };
1260
1261   return protocols;
1262 }
1263
1264 static gchar *
1265 gst_v4l2src_uri_get_uri (GstURIHandler * handler)
1266 {
1267   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1268
1269   if (v4l2src->v4l2object->videodev != NULL) {
1270     return g_strdup_printf ("v4l2://%s", v4l2src->v4l2object->videodev);
1271   }
1272
1273   return g_strdup ("v4l2://");
1274 }
1275
1276 static gboolean
1277 gst_v4l2src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1278     GError ** error)
1279 {
1280   GstV4l2Src *v4l2src = GST_V4L2SRC (handler);
1281   const gchar *device = DEFAULT_PROP_DEVICE;
1282
1283   if (strcmp (uri, "v4l2://") != 0) {
1284     device = uri + 7;
1285   }
1286   g_object_set (v4l2src, "device", device, NULL);
1287
1288   return TRUE;
1289 }
1290
1291
1292 static void
1293 gst_v4l2src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1294 {
1295   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1296
1297   iface->get_type = gst_v4l2src_uri_get_type;
1298   iface->get_protocols = gst_v4l2src_uri_get_protocols;
1299   iface->get_uri = gst_v4l2src_uri_get_uri;
1300   iface->set_uri = gst_v4l2src_uri_set_uri;
1301 }