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