c347b944386d4898d6de7a47281c3dbb7f2599f4
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / gst / videorate / gstvideorate.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 /**
21  * SECTION:element-videorate
22  * @title: videorate
23  *
24  * This element takes an incoming stream of timestamped video frames.
25  * It will produce a perfect stream that matches the source pad's framerate.
26  *
27  * The correction is performed by dropping and duplicating frames, no fancy
28  * algorithm is used to interpolate frames (yet).
29  *
30  * By default the element will simply negotiate the same framerate on its
31  * source and sink pad.
32  *
33  * This operation is useful to link to elements that require a perfect stream.
34  * Typical examples are formats that do not store timestamps for video frames,
35  * but only store a framerate, like Ogg and AVI.
36  *
37  * A conversion to a specific framerate can be forced by using filtered caps on
38  * the source pad.
39  *
40  * The properties #GstVideoRate:in, #GstVideoRate:out, #GstVideoRate:duplicate
41  * and #GstVideoRate:drop can be read to obtain information about number of
42  * input frames, output frames, dropped frames (i.e. the number of unused input
43  * frames) and duplicated frames (i.e. the number of times an input frame was
44  * duplicated, beside being used normally).
45  *
46  * An input stream that needs no adjustments will thus never have dropped or
47  * duplicated frames.
48  *
49  * When the #GstVideoRate:silent property is set to FALSE, a GObject property
50  * notification will be emitted whenever one of the #GstVideoRate:duplicate or
51  * #GstVideoRate:drop values changes.
52  * This can potentially cause performance degradation.
53  * Note that property notification will happen from the streaming thread, so
54  * applications should be prepared for this.
55  *
56  * The property #GstVideoRate:rate allows the modification of video speed by a
57  * certain factor. It must not be confused with framerate. Think of rate as
58  * speed and framerate as flow.
59  *
60  * ## Example pipelines
61  * |[
62  * gst-launch-1.0 -v uridecodebin uri=file:///path/to/video.ogg ! videoconvert ! videoscale ! videorate ! video/x-raw,framerate=15/1 ! autovideosink
63  * ]|
64  *  Decode a video file and adjust the framerate to 15 fps before playing.
65  * To create a test Ogg/Theora file refer to the documentation of theoraenc.
66  * |[
67  * gst-launch-1.0 -v v4l2src ! videorate ! video/x-raw,framerate=25/2 ! theoraenc ! oggmux ! filesink location=recording.ogg
68  * ]|
69  *  Capture video from a V4L device, and adjust the stream to 12.5 fps before
70  * encoding to Ogg/Theora.
71  * |[
72  * gst-launch-1.0 -v uridecodebin uri=file:///path/to/video.ogg ! videoconvert ! videoscale ! videorate ! video/x-raw,framerate=1/5 ! jpegenc ! multifilesink location=snapshot-%05d.jpg
73  * ]|
74  *  Decode a video file and save a snapshot every 5 seconds as consecutively numbered jpeg file.
75  *
76  */
77
78 #ifdef HAVE_CONFIG_H
79 #include "config.h"
80 #endif
81
82 #include "gstvideorate.h"
83 #include <gst/video/video.h>
84
85 GST_DEBUG_CATEGORY_STATIC (video_rate_debug);
86 #define GST_CAT_DEFAULT video_rate_debug
87
88 /* GstVideoRate signals and args */
89 enum
90 {
91   /* FILL ME */
92   LAST_SIGNAL
93 };
94
95 #define DEFAULT_SILENT          TRUE
96 #define DEFAULT_NEW_PREF        1.0
97 #define DEFAULT_SKIP_TO_FIRST   FALSE
98 #define DEFAULT_DROP_ONLY       FALSE
99 #define DEFAULT_AVERAGE_PERIOD  0
100 #define DEFAULT_MAX_RATE        G_MAXINT
101 #define DEFAULT_RATE            1.0
102 #define DEFAULT_MAX_DUPLICATION_TIME      0
103 #define DEFAULT_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION   GST_SECOND
104
105 enum
106 {
107   PROP_0,
108   PROP_IN,
109   PROP_OUT,
110   PROP_DUP,
111   PROP_DROP,
112   PROP_SILENT,
113   PROP_NEW_PREF,
114   PROP_SKIP_TO_FIRST,
115   PROP_DROP_ONLY,
116   PROP_AVERAGE_PERIOD,
117   PROP_MAX_RATE,
118   PROP_RATE,
119   PROP_MAX_DUPLICATION_TIME,
120   PROP_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION
121 };
122
123 static GstStaticPadTemplate gst_video_rate_src_template =
124     GST_STATIC_PAD_TEMPLATE ("src",
125     GST_PAD_SRC,
126     GST_PAD_ALWAYS,
127     GST_STATIC_CAPS ("video/x-raw(ANY);" "video/x-bayer(ANY);"
128         "image/jpeg(ANY);" "image/png(ANY)")
129     );
130
131 static GstStaticPadTemplate gst_video_rate_sink_template =
132     GST_STATIC_PAD_TEMPLATE ("sink",
133     GST_PAD_SINK,
134     GST_PAD_ALWAYS,
135     GST_STATIC_CAPS ("video/x-raw(ANY);" "video/x-bayer(ANY);"
136         "image/jpeg(ANY);" "image/png(ANY)")
137     );
138
139 static void gst_video_rate_swap_prev (GstVideoRate * videorate,
140     GstBuffer * buffer, gint64 time);
141 static gboolean gst_video_rate_sink_event (GstBaseTransform * trans,
142     GstEvent * event);
143 static gboolean gst_video_rate_src_event (GstBaseTransform * trans,
144     GstEvent * event);
145 static gboolean gst_video_rate_query (GstBaseTransform * trans,
146     GstPadDirection direction, GstQuery * query);
147
148 static gboolean gst_video_rate_setcaps (GstBaseTransform * trans,
149     GstCaps * in_caps, GstCaps * out_caps);
150
151 static GstCaps *gst_video_rate_transform_caps (GstBaseTransform * trans,
152     GstPadDirection direction, GstCaps * caps, GstCaps * filter);
153
154 static GstCaps *gst_video_rate_fixate_caps (GstBaseTransform * trans,
155     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps);
156
157 static GstFlowReturn gst_video_rate_transform_ip (GstBaseTransform * trans,
158     GstBuffer * buf);
159
160 static gboolean gst_video_rate_propose_allocation (GstBaseTransform * trans,
161     GstQuery * decide_query, GstQuery * query);
162
163 static gboolean gst_video_rate_start (GstBaseTransform * trans);
164 static gboolean gst_video_rate_stop (GstBaseTransform * trans);
165
166
167 static void gst_video_rate_set_property (GObject * object,
168     guint prop_id, const GValue * value, GParamSpec * pspec);
169 static void gst_video_rate_get_property (GObject * object,
170     guint prop_id, GValue * value, GParamSpec * pspec);
171
172 static GParamSpec *pspec_drop = NULL;
173 static GParamSpec *pspec_duplicate = NULL;
174
175 #define gst_video_rate_parent_class parent_class
176 G_DEFINE_TYPE (GstVideoRate, gst_video_rate, GST_TYPE_BASE_TRANSFORM);
177 GST_ELEMENT_REGISTER_DEFINE (videorate, "videorate",
178     GST_RANK_NONE, GST_TYPE_VIDEO_RATE);
179
180 static void
181 gst_video_rate_class_init (GstVideoRateClass * klass)
182 {
183   GObjectClass *object_class = G_OBJECT_CLASS (klass);
184   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
185   GstBaseTransformClass *base_class = GST_BASE_TRANSFORM_CLASS (klass);
186
187   object_class->set_property = gst_video_rate_set_property;
188   object_class->get_property = gst_video_rate_get_property;
189
190   base_class->set_caps = GST_DEBUG_FUNCPTR (gst_video_rate_setcaps);
191   base_class->transform_caps =
192       GST_DEBUG_FUNCPTR (gst_video_rate_transform_caps);
193   base_class->transform_ip = GST_DEBUG_FUNCPTR (gst_video_rate_transform_ip);
194   base_class->sink_event = GST_DEBUG_FUNCPTR (gst_video_rate_sink_event);
195   base_class->src_event = GST_DEBUG_FUNCPTR (gst_video_rate_src_event);
196   base_class->start = GST_DEBUG_FUNCPTR (gst_video_rate_start);
197   base_class->stop = GST_DEBUG_FUNCPTR (gst_video_rate_stop);
198   base_class->fixate_caps = GST_DEBUG_FUNCPTR (gst_video_rate_fixate_caps);
199   base_class->query = GST_DEBUG_FUNCPTR (gst_video_rate_query);
200   base_class->propose_allocation =
201       GST_DEBUG_FUNCPTR (gst_video_rate_propose_allocation);
202
203   g_object_class_install_property (object_class, PROP_IN,
204       g_param_spec_uint64 ("in", "In",
205           "Number of input frames", 0, G_MAXUINT64, 0,
206           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
207   g_object_class_install_property (object_class, PROP_OUT,
208       g_param_spec_uint64 ("out", "Out", "Number of output frames", 0,
209           G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
210   pspec_duplicate = g_param_spec_uint64 ("duplicate", "Duplicate",
211       "Number of duplicated frames", 0, G_MAXUINT64, 0,
212       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
213   g_object_class_install_property (object_class, PROP_DUP, pspec_duplicate);
214   pspec_drop = g_param_spec_uint64 ("drop", "Drop", "Number of dropped frames",
215       0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
216   g_object_class_install_property (object_class, PROP_DROP, pspec_drop);
217   g_object_class_install_property (object_class, PROP_SILENT,
218       g_param_spec_boolean ("silent", "silent",
219           "Don't emit notify for dropped and duplicated frames", DEFAULT_SILENT,
220           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
221   g_object_class_install_property (object_class, PROP_NEW_PREF,
222       g_param_spec_double ("new-pref", "New Pref",
223           "Value indicating how much to prefer new frames (unused)", 0.0, 1.0,
224           DEFAULT_NEW_PREF, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
225
226   /**
227    * GstVideoRate:skip-to-first:
228    *
229    * Don't produce buffers before the first one we receive.
230    */
231   g_object_class_install_property (object_class, PROP_SKIP_TO_FIRST,
232       g_param_spec_boolean ("skip-to-first", "Skip to first buffer",
233           "Don't produce buffers before the first one we receive",
234           DEFAULT_SKIP_TO_FIRST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
235
236   /**
237    * GstVideoRate:drop-only:
238    *
239    * Only drop frames, no duplicates are produced.
240    */
241   g_object_class_install_property (object_class, PROP_DROP_ONLY,
242       g_param_spec_boolean ("drop-only", "Only Drop",
243           "Only drop frames, no duplicates are produced",
244           DEFAULT_DROP_ONLY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
245
246   /**
247    * GstVideoRate:average-period:
248    *
249    * Arrange for maximum framerate by dropping frames beyond a certain framerate,
250    * where the framerate is calculated using a moving average over the
251    * configured.
252    */
253   g_object_class_install_property (object_class, PROP_AVERAGE_PERIOD,
254       g_param_spec_uint64 ("average-period", "Period over which to average",
255           "Period over which to average the framerate (in ns) (0 = disabled)",
256           0, G_MAXINT64, DEFAULT_AVERAGE_PERIOD,
257           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
258
259   /**
260    * GstVideoRate:max-rate:
261    *
262    * maximum framerate to pass through
263    */
264   g_object_class_install_property (object_class, PROP_MAX_RATE,
265       g_param_spec_int ("max-rate", "maximum framerate",
266           "Maximum framerate allowed to pass through "
267           "(in frames per second, implies drop-only)",
268           1, G_MAXINT, DEFAULT_MAX_RATE,
269           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
270
271   /**
272    * GstVideoRate:rate:
273    *
274    * Factor of speed for frame displaying
275    *
276    * Since: 1.12
277    */
278   g_object_class_install_property (object_class, PROP_RATE,
279       g_param_spec_double ("rate", "Rate",
280           "Factor of speed for frame displaying", 0.0, G_MAXDOUBLE,
281           DEFAULT_RATE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
282           GST_PARAM_MUTABLE_READY));
283
284   /**
285    * GstVideoRate:max-duplication-time:
286    *
287    * Duplicate frames only if the gap between two consecutive frames does not
288    * exceed this duration.
289    *
290    * Since: 1.16
291    */
292   g_object_class_install_property (object_class, PROP_MAX_DUPLICATION_TIME,
293       g_param_spec_uint64 ("max-duplication-time",
294           "Maximum time to duplicate a frame",
295           "Do not duplicate frames if the gap exceeds this period "
296           "(in ns) (0 = disabled)",
297           0, G_MAXUINT64, DEFAULT_MAX_DUPLICATION_TIME,
298           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
299
300   /**
301    * GstVideoRate:max-closing-segment-duplication-duration:
302    *
303    * Limits the maximum duration for which the last buffer is duplicated when
304    * finalizing a segment or on EOS. When receiving an EOS event or a new
305    * segment, videorate duplicates the last frame to close the configured
306    * segment (copying the last buffer until its #GstSegment.stop time (or
307    * #GstSegment.start time for reverse playback) is reached), this property
308    * ensures that it won't push buffers covering a duration longer than
309    * specified.
310    *
311    * Since: 1.22
312    */
313   g_object_class_install_property (object_class,
314       PROP_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION,
315       g_param_spec_uint64 ("max-closing-segment-duplication-duration",
316           "Maximum closing segment duplication duration",
317           "Maximum duration of duplicated buffers to close current segment", 0,
318           G_MAXUINT64, DEFAULT_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION,
319           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
320
321   gst_element_class_set_static_metadata (element_class,
322       "Video rate adjuster", "Filter/Effect/Video",
323       "Drops/duplicates/adjusts timestamps on video frames to make a perfect stream",
324       "Wim Taymans <wim@fluendo.com>");
325
326   gst_element_class_add_static_pad_template (element_class,
327       &gst_video_rate_sink_template);
328   gst_element_class_add_static_pad_template (element_class,
329       &gst_video_rate_src_template);
330 }
331
332 static void
333 gst_value_fraction_get_extremes (const GValue * v,
334     gint * min_num, gint * min_denom, gint * max_num, gint * max_denom)
335 {
336   if (GST_VALUE_HOLDS_FRACTION (v)) {
337     *min_num = *max_num = gst_value_get_fraction_numerator (v);
338     *min_denom = *max_denom = gst_value_get_fraction_denominator (v);
339   } else if (GST_VALUE_HOLDS_FRACTION_RANGE (v)) {
340     const GValue *min, *max;
341
342     min = gst_value_get_fraction_range_min (v);
343     *min_num = gst_value_get_fraction_numerator (min);
344     *min_denom = gst_value_get_fraction_denominator (min);
345
346     max = gst_value_get_fraction_range_max (v);
347     *max_num = gst_value_get_fraction_numerator (max);
348     *max_denom = gst_value_get_fraction_denominator (max);
349   } else if (GST_VALUE_HOLDS_LIST (v)) {
350     gint min_n = G_MAXINT, min_d = 1, max_n = 0, max_d = 1;
351     int i, n;
352
353     *min_num = G_MAXINT;
354     *min_denom = 1;
355     *max_num = 0;
356     *max_denom = 1;
357
358     n = gst_value_list_get_size (v);
359
360     g_assert (n > 0);
361
362     for (i = 0; i < n; i++) {
363       const GValue *t = gst_value_list_get_value (v, i);
364
365       gst_value_fraction_get_extremes (t, &min_n, &min_d, &max_n, &max_d);
366       if (gst_util_fraction_compare (min_n, min_d, *min_num, *min_denom) < 0) {
367         *min_num = min_n;
368         *min_denom = min_d;
369       }
370
371       if (gst_util_fraction_compare (max_n, max_d, *max_num, *max_denom) > 0) {
372         *max_num = max_n;
373         *max_denom = max_d;
374       }
375     }
376   } else {
377     g_warning ("Unknown type for framerate");
378     *min_num = 0;
379     *min_denom = 1;
380     *max_num = G_MAXINT;
381     *max_denom = 1;
382   }
383 }
384
385 /* Clamp the framerate in a caps structure to be a smaller range then
386  * [1...max_rate], otherwise return false */
387 static gboolean
388 gst_video_max_rate_clamp_structure (GstStructure * s, gint maxrate,
389     gint * min_num, gint * min_denom, gint * max_num, gint * max_denom)
390 {
391   gboolean ret = FALSE;
392
393   if (!gst_structure_has_field (s, "framerate")) {
394     /* No framerate field implies any framerate, clamping would result in
395      * [1..max_rate] so not a real subset */
396     goto out;
397   } else {
398     const GValue *v;
399     GValue intersection = { 0, };
400     GValue clamp = { 0, };
401     gint tmp_num, tmp_denom;
402
403     g_value_init (&clamp, GST_TYPE_FRACTION_RANGE);
404     gst_value_set_fraction_range_full (&clamp, 0, 1, maxrate, 1);
405
406     v = gst_structure_get_value (s, "framerate");
407     ret = gst_value_intersect (&intersection, v, &clamp);
408     g_value_unset (&clamp);
409
410     if (!ret)
411       goto out;
412
413     gst_value_fraction_get_extremes (&intersection,
414         min_num, min_denom, max_num, max_denom);
415
416     gst_value_fraction_get_extremes (v,
417         &tmp_num, &tmp_denom, max_num, max_denom);
418
419     if (gst_util_fraction_compare (*max_num, *max_denom, maxrate, 1) > 0) {
420       *max_num = maxrate;
421       *max_denom = 1;
422     }
423
424     gst_structure_take_value (s, "framerate", &intersection);
425   }
426
427 out:
428   return ret;
429 }
430
431 static GstCaps *
432 gst_video_rate_transform_caps (GstBaseTransform * trans,
433     GstPadDirection direction, GstCaps * caps, GstCaps * filter)
434 {
435   GstVideoRate *videorate = GST_VIDEO_RATE (trans);
436   GstCaps *ret;
437   GstStructure *s, *s1, *s2, *s3 = NULL;
438   int maxrate = g_atomic_int_get (&videorate->max_rate);
439   gint i;
440
441   ret = gst_caps_new_empty ();
442
443   for (i = 0; i < gst_caps_get_size (caps); i++) {
444     s = gst_caps_get_structure (caps, i);
445
446     s1 = gst_structure_copy (s);
447
448     if (videorate->updating_caps && direction == GST_PAD_SINK) {
449       GST_INFO_OBJECT (trans,
450           "Only updating caps %" GST_PTR_FORMAT " with framerate" " %d/%d",
451           caps, videorate->to_rate_numerator, videorate->to_rate_denominator);
452
453       gst_structure_set (s1, "framerate", GST_TYPE_FRACTION,
454           videorate->to_rate_numerator, videorate->to_rate_denominator, NULL);
455       ret = gst_caps_merge_structure (ret, s1);
456
457       continue;
458     }
459
460     s2 = gst_structure_copy (s);
461     s3 = NULL;
462
463     if (videorate->drop_only) {
464       gint min_num = 0, min_denom = 1;
465       gint max_num = G_MAXINT, max_denom = 1;
466
467       /* Clamp the caps to our maximum rate as the first caps if possible */
468       if (!gst_video_max_rate_clamp_structure (s1, maxrate,
469               &min_num, &min_denom, &max_num, &max_denom)) {
470         min_num = 0;
471         min_denom = 1;
472         max_num = maxrate;
473         max_denom = 1;
474
475         /* clamp wouldn't be a real subset of 1..maxrate, in this case the sink
476          * caps should become [1..maxrate], [1..maxint] and the src caps just
477          * [1..maxrate].  In case there was a caps incompatibility things will
478          * explode later as appropriate :)
479          *
480          * In case [X..maxrate] == [X..maxint], skip as we'll set it later
481          */
482         if (direction == GST_PAD_SRC && maxrate != G_MAXINT)
483           gst_structure_set (s1, "framerate", GST_TYPE_FRACTION_RANGE,
484               min_num, min_denom, maxrate, 1, NULL);
485         else {
486           gst_structure_free (s1);
487           s1 = NULL;
488         }
489       }
490
491       if (direction == GST_PAD_SRC) {
492         /* We can accept anything as long as it's at least the minimal framerate
493          * the the sink needs */
494         gst_structure_set (s2, "framerate", GST_TYPE_FRACTION_RANGE,
495             min_num, min_denom, G_MAXINT, 1, NULL);
496
497         /* Also allow unknown framerate, if it isn't already */
498         if (min_num != 0 || min_denom != 1) {
499           s3 = gst_structure_copy (s);
500           gst_structure_set (s3, "framerate", GST_TYPE_FRACTION, 0, 1, NULL);
501         }
502       } else if (max_num != 0 || max_denom != 1) {
503         /* We can provide everything up to the maximum framerate at the src */
504         gst_structure_set (s2, "framerate", GST_TYPE_FRACTION_RANGE,
505             0, 1, max_num, max_denom, NULL);
506       }
507     } else if (direction == GST_PAD_SINK) {
508       gint min_num = 0, min_denom = 1;
509       gint max_num = G_MAXINT, max_denom = 1;
510
511       if (!gst_video_max_rate_clamp_structure (s1, maxrate,
512               &min_num, &min_denom, &max_num, &max_denom)) {
513         gst_structure_free (s1);
514         s1 = NULL;
515       }
516       gst_structure_set (s2, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
517           maxrate, 1, NULL);
518     } else {
519       /* set the framerate as a range */
520       gst_structure_set (s2, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1,
521           G_MAXINT, 1, NULL);
522     }
523     if (s1 != NULL)
524       ret = gst_caps_merge_structure_full (ret, s1,
525           gst_caps_features_copy (gst_caps_get_features (caps, i)));
526     ret = gst_caps_merge_structure_full (ret, s2,
527         gst_caps_features_copy (gst_caps_get_features (caps, i)));
528     if (s3 != NULL)
529       ret = gst_caps_merge_structure_full (ret, s3,
530           gst_caps_features_copy (gst_caps_get_features (caps, i)));
531   }
532   if (filter) {
533     GstCaps *intersection;
534
535     intersection =
536         gst_caps_intersect_full (filter, ret, GST_CAPS_INTERSECT_FIRST);
537     gst_caps_unref (ret);
538     ret = intersection;
539   }
540   return ret;
541 }
542
543 static GstCaps *
544 gst_video_rate_fixate_caps (GstBaseTransform * trans,
545     GstPadDirection direction, GstCaps * caps, GstCaps * othercaps)
546 {
547   GstStructure *s;
548   gint num, denom;
549   const GValue *par;
550
551   s = gst_caps_get_structure (caps, 0);
552   if (G_UNLIKELY (!gst_structure_get_fraction (s, "framerate", &num, &denom)))
553     return othercaps;
554
555   othercaps = gst_caps_truncate (othercaps);
556   othercaps = gst_caps_make_writable (othercaps);
557   s = gst_caps_get_structure (othercaps, 0);
558   gst_structure_fixate_field_nearest_fraction (s, "framerate", num, denom);
559
560   if ((par = gst_structure_get_value (s, "pixel-aspect-ratio")))
561     gst_structure_fixate_field_nearest_fraction (s, "pixel-aspect-ratio", 1, 1);
562
563   return gst_caps_fixate (othercaps);
564 }
565
566 static gboolean
567 gst_video_rate_setcaps (GstBaseTransform * trans, GstCaps * in_caps,
568     GstCaps * out_caps)
569 {
570   GstVideoRate *videorate = GST_VIDEO_RATE (trans);
571   GstStructure *structure;
572   gboolean ret = TRUE;
573   gint rate_numerator, rate_denominator;
574
575   GST_DEBUG_OBJECT (trans, "setcaps called in: %" GST_PTR_FORMAT
576       " out: %" GST_PTR_FORMAT, in_caps, out_caps);
577
578   structure = gst_caps_get_structure (in_caps, 0);
579   if (!gst_structure_get_fraction (structure, "framerate",
580           &rate_numerator, &rate_denominator))
581     goto no_framerate;
582
583   videorate->from_rate_numerator = rate_numerator;
584   videorate->from_rate_denominator = rate_denominator;
585
586   structure = gst_caps_get_structure (out_caps, 0);
587   if (!gst_structure_get_fraction (structure, "framerate",
588           &rate_numerator, &rate_denominator))
589     goto no_framerate;
590
591   /* out_frame_count is scaled by the frame rate caps when calculating next_ts.
592    * when the frame rate caps change, we must update base_ts and reset
593    * out_frame_count */
594   if (videorate->to_rate_numerator) {
595     videorate->base_ts +=
596         gst_util_uint64_scale (videorate->out_frame_count +
597         (videorate->segment.rate < 0.0 ? 1 : 0),
598         videorate->to_rate_denominator * GST_SECOND,
599         videorate->to_rate_numerator);
600   }
601   videorate->out_frame_count = 0;
602   videorate->to_rate_numerator = rate_numerator;
603   videorate->to_rate_denominator = rate_denominator;
604
605   if (rate_numerator)
606     videorate->wanted_diff = gst_util_uint64_scale_int (GST_SECOND,
607         rate_denominator, rate_numerator);
608   else
609     videorate->wanted_diff = 0;
610
611 done:
612   /* After a setcaps, our caps may have changed. In that case, we can't use
613    * the old buffer, if there was one (it might have different dimensions) */
614   GST_DEBUG_OBJECT (videorate, "swapping old buffers");
615   gst_video_rate_swap_prev (videorate, NULL, GST_CLOCK_TIME_NONE);
616   videorate->last_ts = GST_CLOCK_TIME_NONE;
617   videorate->average = 0;
618
619   return ret;
620
621 no_framerate:
622   {
623     GST_DEBUG_OBJECT (videorate, "no framerate specified");
624     ret = FALSE;
625     goto done;
626   }
627 }
628
629 static void
630 gst_video_rate_reset (GstVideoRate * videorate)
631 {
632   GST_DEBUG_OBJECT (videorate, "resetting internal variables");
633
634   videorate->in = 0;
635   videorate->out = 0;
636   videorate->base_ts = 0;
637   videorate->out_frame_count = 0;
638   videorate->drop = 0;
639   videorate->dup = 0;
640   videorate->next_ts = GST_CLOCK_TIME_NONE;
641   videorate->last_ts = GST_CLOCK_TIME_NONE;
642   videorate->discont = TRUE;
643   videorate->average = 0;
644   videorate->force_variable_rate = FALSE;
645   gst_video_rate_swap_prev (videorate, NULL, 0);
646
647   gst_segment_init (&videorate->segment, GST_FORMAT_TIME);
648 }
649
650 static void
651 gst_video_rate_init (GstVideoRate * videorate)
652 {
653   gst_video_rate_reset (videorate);
654   videorate->silent = DEFAULT_SILENT;
655   videorate->new_pref = DEFAULT_NEW_PREF;
656   videorate->drop_only = DEFAULT_DROP_ONLY;
657   videorate->average_period = DEFAULT_AVERAGE_PERIOD;
658   videorate->average_period_set = DEFAULT_AVERAGE_PERIOD;
659   videorate->max_rate = DEFAULT_MAX_RATE;
660   videorate->rate = DEFAULT_RATE;
661   videorate->pending_rate = DEFAULT_RATE;
662   videorate->max_duplication_time = DEFAULT_MAX_DUPLICATION_TIME;
663   videorate->max_closing_segment_duplication_duration =
664       DEFAULT_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION;
665
666   videorate->from_rate_numerator = 0;
667   videorate->from_rate_denominator = 0;
668   videorate->to_rate_numerator = 0;
669   videorate->to_rate_denominator = 0;
670
671   gst_base_transform_set_gap_aware (GST_BASE_TRANSFORM (videorate), TRUE);
672 }
673
674 /* @outbuf: (transfer full) needs to be writable */
675 static GstFlowReturn
676 gst_video_rate_push_buffer (GstVideoRate * videorate, GstBuffer * outbuf,
677     gboolean duplicate, GstClockTime next_intime, gboolean invalid_duration)
678 {
679   GstFlowReturn res;
680   GstClockTime push_ts;
681
682   GST_BUFFER_OFFSET (outbuf) = videorate->out;
683   GST_BUFFER_OFFSET_END (outbuf) = videorate->out + 1;
684
685   if (videorate->discont) {
686     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
687     videorate->discont = FALSE;
688   } else
689     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DISCONT);
690
691   if (duplicate)
692     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_GAP);
693   else
694     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_GAP);
695
696   /* this is the timestamp we put on the buffer */
697   push_ts = videorate->next_ts;
698
699   videorate->out++;
700   videorate->out_frame_count++;
701   if (videorate->segment.rate < 0.0) {
702     if (videorate->to_rate_numerator) {
703       /* interpolate next expected timestamp in the segment */
704       GstClockTimeDiff next_ts =
705           videorate->segment.base + videorate->segment.stop -
706           videorate->base_ts -
707           gst_util_uint64_scale (videorate->out_frame_count + 1,
708           videorate->to_rate_denominator * GST_SECOND,
709           videorate->to_rate_numerator);
710
711       videorate->next_ts = next_ts < 0 ? GST_CLOCK_TIME_NONE : next_ts;
712
713       GST_BUFFER_DURATION (outbuf) =
714           gst_util_uint64_scale (videorate->out_frame_count,
715           videorate->to_rate_denominator * GST_SECOND,
716           videorate->to_rate_numerator) -
717           gst_util_uint64_scale (videorate->out_frame_count - 1,
718           videorate->to_rate_denominator * GST_SECOND,
719           videorate->to_rate_numerator);
720     } else if (next_intime != GST_CLOCK_TIME_NONE) {
721       videorate->next_ts = next_intime;
722     } else {
723       GST_FIXME_OBJECT (videorate, "No next intime for reverse playback");
724     }
725   } else {
726     if (videorate->to_rate_numerator) {
727       /* interpolate next expected timestamp in the segment */
728       videorate->next_ts =
729           videorate->segment.base + videorate->segment.start +
730           videorate->base_ts +
731           gst_util_uint64_scale (videorate->out_frame_count,
732           videorate->to_rate_denominator * GST_SECOND,
733           videorate->to_rate_numerator);
734       GST_BUFFER_DURATION (outbuf) = videorate->next_ts - push_ts;
735     } else if (!invalid_duration) {
736       /* There must always be a valid duration on prevbuf if rate > 0,
737        * it is ensured in the transform_ip function */
738       g_assert (GST_BUFFER_PTS_IS_VALID (outbuf));
739       g_assert (GST_BUFFER_DURATION_IS_VALID (outbuf));
740       g_assert (GST_BUFFER_DURATION (outbuf) != 0);
741
742       videorate->next_ts
743           = GST_BUFFER_PTS (outbuf) + GST_BUFFER_DURATION (outbuf);
744     }
745   }
746
747   /* We do not need to update time in VFR (variable frame rate) mode */
748   if (!videorate->drop_only) {
749     /* adapt for looping, bring back to time in current segment. */
750     GST_BUFFER_TIMESTAMP (outbuf) = push_ts - videorate->segment.base;
751   }
752
753   GST_LOG_OBJECT (videorate,
754       "old is best, dup, pushing buffer outgoing ts %" GST_TIME_FORMAT,
755       GST_TIME_ARGS (push_ts));
756
757   res = gst_pad_push (GST_BASE_TRANSFORM_SRC_PAD (videorate), outbuf);
758
759   return res;
760 }
761
762 /* flush the oldest buffer */
763 static GstFlowReturn
764 gst_video_rate_flush_prev (GstVideoRate * videorate, gboolean duplicate,
765     GstClockTime next_intime, gboolean invalid_duration)
766 {
767   GstBuffer *outbuf;
768
769   if (!videorate->prevbuf)
770     goto eos_before_buffers;
771
772   outbuf = gst_buffer_ref (videorate->prevbuf);
773   /* make sure we can write to the metadata */
774   outbuf = gst_buffer_make_writable (outbuf);
775
776   return gst_video_rate_push_buffer (videorate, outbuf, duplicate, next_intime,
777       invalid_duration);
778
779   /* WARNINGS */
780 eos_before_buffers:
781   {
782     GST_INFO_OBJECT (videorate, "got EOS before any buffer was received");
783     return GST_FLOW_OK;
784   }
785 }
786
787 static void
788 gst_video_rate_swap_prev (GstVideoRate * videorate, GstBuffer * buffer,
789     gint64 time)
790 {
791   GST_LOG_OBJECT (videorate, "swap_prev: storing buffer %p in prev", buffer);
792   if (videorate->prevbuf)
793     gst_buffer_unref (videorate->prevbuf);
794   videorate->prevbuf = buffer != NULL ? gst_buffer_ref (buffer) : NULL;
795   videorate->prev_ts = time;
796 }
797
798 static void
799 gst_video_rate_notify_drop (GstVideoRate * videorate)
800 {
801   g_object_notify_by_pspec ((GObject *) videorate, pspec_drop);
802 }
803
804 static void
805 gst_video_rate_notify_duplicate (GstVideoRate * videorate)
806 {
807   g_object_notify_by_pspec ((GObject *) videorate, pspec_duplicate);
808 }
809
810 static gboolean
811 gst_video_rate_check_duplicate_to_close_segment (GstVideoRate * videorate,
812     GstClockTime last_input_ts, gboolean is_first)
813 {
814   GstClockTime next_stream_time = videorate->next_ts - videorate->segment.base;
815   GstClockTime max_closing_segment_duplication_duration =
816       videorate->max_closing_segment_duplication_duration;
817
818   if (!GST_CLOCK_TIME_IS_VALID (videorate->next_ts))
819     return FALSE;
820
821   if (videorate->segment.rate > 0.0) {
822
823     if (!GST_CLOCK_TIME_IS_VALID (videorate->segment.stop)) {
824       /* Ensure that if no 'stop' is set, we push the last frame anyway */
825       return is_first;
826     }
827
828     if (next_stream_time >= videorate->segment.stop)
829       return FALSE;
830
831     if (GST_CLOCK_TIME_IS_VALID (max_closing_segment_duplication_duration)) {
832       if (last_input_ts > videorate->next_ts)
833         return TRUE;
834
835       return (videorate->next_ts - last_input_ts <
836           max_closing_segment_duplication_duration);
837     }
838
839     return TRUE;
840   }
841
842   /* Reverse playback */
843
844   if (!GST_CLOCK_TIME_IS_VALID (videorate->segment.start)) {
845     /* Ensure that if no 'start' is set, we push the last frame anyway */
846     return is_first;
847   }
848
849   if (next_stream_time < videorate->segment.start)
850     return FALSE;
851
852   if (GST_CLOCK_TIME_IS_VALID (max_closing_segment_duplication_duration)) {
853     if (last_input_ts < videorate->next_ts)
854       return TRUE;
855
856     return (last_input_ts - videorate->next_ts <
857         max_closing_segment_duplication_duration);
858   }
859
860   return TRUE;
861 }
862
863 static gint
864 gst_video_rate_duplicate_to_close_segment (GstVideoRate * videorate)
865 {
866   gint count = 0;
867   GstFlowReturn res;
868   GstClockTime last_input_ts = videorate->prev_ts;
869
870   if (videorate->drop_only)
871     return count;
872
873   if (!videorate->prevbuf) {
874     GST_INFO_OBJECT (videorate, "got EOS before any buffer was received");
875
876     return count;
877   }
878
879   res = GST_FLOW_OK;
880   /* fill up to the end of current segment */
881   while (res == GST_FLOW_OK
882       && gst_video_rate_check_duplicate_to_close_segment (videorate,
883           last_input_ts, count < 1)) {
884     res =
885         gst_video_rate_flush_prev (videorate, count > 0, GST_CLOCK_TIME_NONE,
886         FALSE);
887
888     count++;
889   }
890
891   return count;
892 }
893
894 static gboolean
895 gst_video_rate_sink_event (GstBaseTransform * trans, GstEvent * event)
896 {
897   GstVideoRate *videorate;
898
899   videorate = GST_VIDEO_RATE (trans);
900
901   switch (GST_EVENT_TYPE (event)) {
902     case GST_EVENT_SEGMENT:
903     {
904       GstSegment segment;
905       gint seqnum;
906
907       gst_event_copy_segment (event, &segment);
908       if (segment.format != GST_FORMAT_TIME)
909         goto format_error;
910
911       GST_DEBUG_OBJECT (videorate, "handle NEWSEGMENT");
912
913       /* close up the previous segment, if appropriate */
914       if (videorate->prevbuf) {
915         /* fill up to the end of current segment */
916         gint count = gst_video_rate_duplicate_to_close_segment (videorate);
917         if (count > 1) {
918           videorate->dup += count - 1;
919           if (!videorate->silent)
920             gst_video_rate_notify_duplicate (videorate);
921         }
922         /* clean up for the new one; _chain will resume from the new start */
923         gst_video_rate_swap_prev (videorate, NULL, 0);
924       }
925
926       videorate->base_ts = 0;
927       videorate->out_frame_count = 0;
928       videorate->next_ts = GST_CLOCK_TIME_NONE;
929
930       /* We just want to update the accumulated stream_time  */
931
932       segment.start = (gint64) (segment.start / videorate->rate);
933       segment.position = (gint64) (segment.position / videorate->rate);
934       if (GST_CLOCK_TIME_IS_VALID (segment.stop))
935         segment.stop = (gint64) (segment.stop / videorate->rate);
936       segment.time = (gint64) (segment.time / videorate->rate);
937
938       gst_segment_copy_into (&segment, &videorate->segment);
939       GST_DEBUG_OBJECT (videorate, "updated segment: %" GST_SEGMENT_FORMAT,
940           &videorate->segment);
941
942
943       seqnum = gst_event_get_seqnum (event);
944       gst_event_unref (event);
945       event = gst_event_new_segment (&segment);
946       gst_event_set_seqnum (event, seqnum);
947
948       break;
949     }
950     case GST_EVENT_SEGMENT_DONE:
951     case GST_EVENT_EOS:{
952       gint count = 0;
953       GstFlowReturn res = GST_FLOW_OK;
954
955       GST_DEBUG_OBJECT (videorate, "Got %s",
956           gst_event_type_get_name (GST_EVENT_TYPE (event)));
957
958       /* If the segment has a stop position, fill the segment */
959       if (GST_CLOCK_TIME_IS_VALID (videorate->segment.stop)) {
960         /* fill up to the end of current segment */
961         count = gst_video_rate_duplicate_to_close_segment (videorate);
962       } else if (!videorate->drop_only && videorate->prevbuf) {
963         /* Output at least one frame but if the buffer duration is valid, output
964          * enough frames to use the complete buffer duration */
965         if (GST_BUFFER_DURATION_IS_VALID (videorate->prevbuf)) {
966           GstClockTime end_ts, duration =
967               GST_BUFFER_DURATION (videorate->prevbuf);
968
969           if (GST_CLOCK_TIME_IS_VALID
970               (videorate->max_closing_segment_duplication_duration))
971             duration =
972                 MIN (videorate->max_closing_segment_duplication_duration,
973                 duration);
974
975           end_ts = videorate->next_ts + duration;
976           while (res == GST_FLOW_OK && ((videorate->segment.rate > 0.0
977                       && GST_CLOCK_TIME_IS_VALID (videorate->segment.stop)
978                       && GST_CLOCK_TIME_IS_VALID (videorate->next_ts)
979                       && videorate->next_ts - videorate->segment.base < end_ts)
980                   || count < 1)) {
981             res =
982                 gst_video_rate_flush_prev (videorate, count > 0,
983                 GST_CLOCK_TIME_NONE, FALSE);
984             count++;
985           }
986         } else {
987           /* allow the duration to be invalid as there is no way to infer it if we
988            * received a single buffer and not output framerate was set. */
989           res =
990               gst_video_rate_flush_prev (videorate, FALSE, GST_CLOCK_TIME_NONE,
991               TRUE);
992           count = 1;
993         }
994       }
995
996       if (count > 1) {
997         videorate->dup += count - 1;
998         if (!videorate->silent)
999           gst_video_rate_notify_duplicate (videorate);
1000       } else if (count == 0
1001           && !GST_CLOCK_TIME_IS_VALID (videorate->segment.stop)) {
1002         videorate->drop++;
1003         if (!videorate->silent)
1004           gst_video_rate_notify_drop (videorate);
1005       }
1006
1007       break;
1008     }
1009     case GST_EVENT_FLUSH_STOP:
1010       /* also resets the segment */
1011       GST_DEBUG_OBJECT (videorate, "Got FLUSH_STOP");
1012       gst_video_rate_reset (videorate);
1013       break;
1014     case GST_EVENT_GAP:
1015       /* no gaps after videorate, ignore the event */
1016       gst_event_unref (event);
1017       return TRUE;
1018     default:
1019       break;
1020   }
1021
1022   return GST_BASE_TRANSFORM_CLASS (parent_class)->sink_event (trans, event);
1023
1024   /* ERRORS */
1025 format_error:
1026   {
1027     GST_WARNING_OBJECT (videorate,
1028         "Got segment but doesn't have GST_FORMAT_TIME value");
1029     return FALSE;
1030   }
1031 }
1032
1033 static gboolean
1034 gst_video_rate_src_event (GstBaseTransform * trans, GstEvent * event)
1035 {
1036   GstVideoRate *videorate;
1037   GstPad *sinkpad;
1038   gboolean res = FALSE;
1039
1040   videorate = GST_VIDEO_RATE (trans);
1041   sinkpad = GST_BASE_TRANSFORM_SINK_PAD (trans);
1042   switch (GST_EVENT_TYPE (event)) {
1043     case GST_EVENT_SEEK:
1044     {
1045       gdouble srate;
1046       GstSeekFlags flags;
1047       GstSeekType start_type, stop_type;
1048       gint64 start, stop;
1049       gint seqnum = gst_event_get_seqnum (event);
1050
1051       gst_event_parse_seek (event, &srate, NULL, &flags, &start_type, &start,
1052           &stop_type, &stop);
1053
1054       start = (gint64) (start * videorate->rate);
1055       if (GST_CLOCK_TIME_IS_VALID (stop)) {
1056         stop = (gint64) (stop * videorate->rate);
1057       }
1058
1059       gst_event_unref (event);
1060       event = gst_event_new_seek (srate, GST_FORMAT_TIME,
1061           flags, start_type, start, stop_type, stop);
1062       gst_event_set_seqnum (event, seqnum);
1063
1064       res = gst_pad_push_event (sinkpad, event);
1065       break;
1066     }
1067     case GST_EVENT_QOS:
1068     {
1069       GstQOSType type;
1070       gdouble proportion;
1071       GstClockTimeDiff diff;
1072       GstClockTime timestamp;
1073
1074       gst_event_parse_qos (event, &type, &proportion, &diff, &timestamp);
1075
1076       if (GST_CLOCK_TIME_IS_VALID (timestamp) && videorate->rate != 1.0) {
1077         GST_OBJECT_LOCK (trans);
1078         GST_DEBUG_OBJECT (trans, "Rescaling QoS event taking our rate into"
1079             "account. Timestamp:  %" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT
1080             " - diff %" G_GINT64_FORMAT "-> %" G_GINT64_FORMAT,
1081             GST_TIME_ARGS (timestamp),
1082             GST_TIME_ARGS (videorate->base_ts + ((timestamp -
1083                         videorate->base_ts) * videorate->rate)), diff,
1084             (GstClockTimeDiff) (diff * videorate->rate));
1085
1086         if (videorate->segment.rate < 0.0)
1087           timestamp =
1088               (videorate->segment.stop - videorate->base_ts) -
1089               ((videorate->segment.stop - videorate->base_ts -
1090                   timestamp) * videorate->rate);
1091         else
1092           timestamp =
1093               videorate->base_ts + ((timestamp -
1094                   videorate->base_ts) * videorate->rate);
1095
1096         diff *= videorate->rate;
1097         GST_OBJECT_UNLOCK (trans);
1098
1099         gst_event_unref (event);
1100         event = gst_event_new_qos (type, proportion, diff, timestamp);
1101       }
1102       /* Fallthrough */
1103     }
1104     default:
1105       res = gst_pad_push_event (sinkpad, event);
1106       break;
1107   }
1108   return res;
1109 }
1110
1111 static gboolean
1112 gst_video_rate_query (GstBaseTransform * trans, GstPadDirection direction,
1113     GstQuery * query)
1114 {
1115   GstVideoRate *videorate = GST_VIDEO_RATE (trans);
1116   gboolean res = FALSE;
1117   GstPad *otherpad;
1118
1119   otherpad = (direction == GST_PAD_SRC) ?
1120       GST_BASE_TRANSFORM_SINK_PAD (trans) : GST_BASE_TRANSFORM_SRC_PAD (trans);
1121
1122   switch (GST_QUERY_TYPE (query)) {
1123     case GST_QUERY_LATENCY:
1124     {
1125       GstClockTime min, max;
1126       gboolean live;
1127       guint64 latency;
1128       guint64 avg_period;
1129       gboolean drop_only;
1130       GstPad *peer;
1131
1132       GST_OBJECT_LOCK (videorate);
1133       avg_period = videorate->average_period_set;
1134       drop_only = videorate->drop_only;
1135       GST_OBJECT_UNLOCK (videorate);
1136
1137       if (avg_period == 0 && (peer = gst_pad_get_peer (otherpad))) {
1138         if ((res = gst_pad_query (peer, query))) {
1139           gst_query_parse_latency (query, &live, &min, &max);
1140
1141           GST_DEBUG_OBJECT (videorate, "Peer latency: min %"
1142               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
1143               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
1144
1145           /* Drop only has no latency, other modes have one frame latency */
1146           if (!drop_only && videorate->from_rate_numerator != 0) {
1147             /* add latency. We don't really know since we hold on to the frames
1148              * until we get a next frame, which can be anything. We assume
1149              * however that this will take from_rate time. */
1150             latency = gst_util_uint64_scale (GST_SECOND,
1151                 videorate->from_rate_denominator,
1152                 videorate->from_rate_numerator);
1153           } else {
1154             /* no input framerate, we don't know */
1155             latency = 0;
1156           }
1157
1158           GST_DEBUG_OBJECT (videorate, "Our latency: %"
1159               GST_TIME_FORMAT, GST_TIME_ARGS (latency));
1160
1161           min += latency;
1162           if (max != -1)
1163             max += latency;
1164
1165           GST_DEBUG_OBJECT (videorate, "Calculated total latency : min %"
1166               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
1167               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
1168
1169           gst_query_set_latency (query, live, min, max);
1170         }
1171         gst_object_unref (peer);
1172         break;
1173       }
1174       /* Simple fall back if we don't have a latency or a peer that we
1175        * can ask about its latency yet.. */
1176       res =
1177           GST_BASE_TRANSFORM_CLASS (parent_class)->query (trans, direction,
1178           query);
1179       break;
1180     }
1181     case GST_QUERY_DURATION:
1182     {
1183       GstFormat format;
1184       gint64 duration;
1185       gdouble rate;
1186
1187       res =
1188           GST_BASE_TRANSFORM_CLASS (parent_class)->query (trans, direction,
1189           query);
1190
1191       if (!res)
1192         break;
1193
1194       GST_OBJECT_LOCK (videorate);
1195       rate = videorate->pending_rate;
1196       GST_OBJECT_UNLOCK (videorate);
1197
1198       if (rate == 1.0)
1199         break;
1200
1201       gst_query_parse_duration (query, &format, &duration);
1202
1203       if (format != GST_FORMAT_TIME) {
1204         GST_DEBUG_OBJECT (videorate, "not TIME format");
1205         break;
1206       }
1207       GST_LOG_OBJECT (videorate, "upstream duration: %" G_GINT64_FORMAT,
1208           duration);
1209       /* Shouldn't this be a multiplication if the direction is downstream? */
1210       if (GST_CLOCK_TIME_IS_VALID (duration)) {
1211         duration = (gint64) (duration / rate);
1212       }
1213       GST_LOG_OBJECT (videorate, "our duration: %" G_GINT64_FORMAT, duration);
1214       gst_query_set_duration (query, format, duration);
1215       break;
1216     }
1217     case GST_QUERY_POSITION:
1218     {
1219       GstFormat dst_format;
1220       gint64 dst_value;
1221       gdouble rate;
1222
1223       GST_OBJECT_LOCK (videorate);
1224       rate = videorate->rate;
1225       GST_OBJECT_UNLOCK (videorate);
1226
1227       gst_query_parse_position (query, &dst_format, NULL);
1228
1229       if (dst_format != GST_FORMAT_TIME) {
1230         GST_DEBUG_OBJECT (videorate, "not TIME format");
1231         break;
1232       }
1233       /* Shouldn't this be a multiplication if the direction is downstream? */
1234       dst_value =
1235           (gint64) (gst_segment_to_stream_time (&videorate->segment,
1236               GST_FORMAT_TIME, videorate->last_ts / rate));
1237       GST_LOG_OBJECT (videorate, "our position: %" GST_TIME_FORMAT,
1238           GST_TIME_ARGS (dst_value));
1239       gst_query_set_position (query, dst_format, dst_value);
1240       res = TRUE;
1241       break;
1242     }
1243     default:
1244       res =
1245           GST_BASE_TRANSFORM_CLASS (parent_class)->query (trans, direction,
1246           query);
1247       break;
1248   }
1249
1250   return res;
1251 }
1252
1253 static gboolean
1254 gst_video_rate_propose_allocation (GstBaseTransform * trans,
1255     GstQuery * decide_query, GstQuery * query)
1256 {
1257   GstBaseTransformClass *klass = GST_BASE_TRANSFORM_CLASS (parent_class);
1258   gboolean res;
1259
1260   /* We should always be passthrough */
1261   g_return_val_if_fail (decide_query == NULL, FALSE);
1262
1263   res = klass->propose_allocation (trans, NULL, query);
1264
1265   if (res) {
1266     guint i = 0;
1267     guint n_allocation;
1268     guint down_min = 0;
1269
1270     n_allocation = gst_query_get_n_allocation_pools (query);
1271
1272     while (i < n_allocation) {
1273       GstBufferPool *pool = NULL;
1274       guint size, min, max;
1275
1276       gst_query_parse_nth_allocation_pool (query, i, &pool, &size, &min, &max);
1277
1278       if (min == max) {
1279         if (pool)
1280           gst_object_unref (pool);
1281         gst_query_remove_nth_allocation_pool (query, i);
1282         n_allocation--;
1283         down_min = MAX (min, down_min);
1284         continue;
1285       }
1286
1287       gst_query_set_nth_allocation_pool (query, i, pool, size, min + 1, max);
1288       if (pool)
1289         gst_object_unref (pool);
1290       i++;
1291     }
1292
1293     if (n_allocation == 0) {
1294       GstCaps *caps;
1295       GstVideoInfo info;
1296
1297       gst_query_parse_allocation (query, &caps, NULL);
1298       gst_video_info_from_caps (&info, caps);
1299
1300       gst_query_add_allocation_pool (query, NULL, info.size, down_min + 1, 0);
1301     }
1302   }
1303
1304   return res;
1305 }
1306
1307 static GstFlowReturn
1308 gst_video_rate_trans_ip_max_avg (GstVideoRate * videorate, GstBuffer * buf)
1309 {
1310   GstClockTime ts = GST_BUFFER_TIMESTAMP (buf);
1311
1312   videorate->in++;
1313
1314   if (!GST_CLOCK_TIME_IS_VALID (ts) || videorate->wanted_diff == 0)
1315     goto push;
1316
1317   /* drop frames if they exceed our output rate */
1318   if (GST_CLOCK_TIME_IS_VALID (videorate->last_ts)) {
1319     GstClockTimeDiff diff =
1320         videorate->segment.rate <
1321         0 ? videorate->last_ts - ts : ts - videorate->last_ts;
1322
1323     /* Drop buffer if its early compared to the desired frame rate and
1324      * the current average is higher than the desired average
1325      */
1326     if (diff < videorate->wanted_diff &&
1327         videorate->average < videorate->wanted_diff)
1328       goto drop;
1329
1330     /* Update average */
1331     if (videorate->average) {
1332       GstClockTimeDiff wanted_diff;
1333
1334       if (G_LIKELY (videorate->average_period > videorate->wanted_diff))
1335         wanted_diff = videorate->wanted_diff;
1336       else
1337         wanted_diff = videorate->average_period * 10;
1338
1339       videorate->average =
1340           gst_util_uint64_scale_round (videorate->average,
1341           videorate->average_period - wanted_diff,
1342           videorate->average_period) +
1343           gst_util_uint64_scale_round (diff, wanted_diff,
1344           videorate->average_period);
1345     } else {
1346       videorate->average = diff;
1347     }
1348   }
1349
1350   videorate->last_ts = ts;
1351
1352 push:
1353   videorate->out++;
1354   return GST_FLOW_OK;
1355
1356 drop:
1357   if (!videorate->silent)
1358     gst_video_rate_notify_drop (videorate);
1359   return GST_BASE_TRANSFORM_FLOW_DROPPED;
1360 }
1361
1362 /* Check if downstream forces variable framerate (0/1) and if
1363  * it is the case, use variable framerate ourself
1364  * Otherwise compute the framerate from the 2 buffers that we
1365  * have already received and make use of it as wanted framerate
1366  */
1367 static void
1368 gst_video_rate_check_variable_rate (GstVideoRate * videorate,
1369     GstBuffer * buffer)
1370 {
1371   GstStructure *st;
1372   gint fps_d, fps_n;
1373   GstCaps *srcpadcaps, *tmpcaps, *downstream_caps;
1374   GstPad *pad = NULL;
1375
1376   srcpadcaps =
1377       gst_pad_get_current_caps (GST_BASE_TRANSFORM_SRC_PAD (videorate));
1378
1379   gst_video_guess_framerate (GST_BUFFER_PTS (buffer) -
1380       GST_BUFFER_PTS (videorate->prevbuf), &fps_n, &fps_d);
1381
1382   tmpcaps = gst_caps_copy (srcpadcaps);
1383   st = gst_caps_get_structure (tmpcaps, 0);
1384   gst_structure_set (st, "framerate", GST_TYPE_FRACTION, fps_n, fps_d, NULL);
1385   gst_caps_unref (srcpadcaps);
1386
1387   pad = gst_pad_get_peer (GST_BASE_TRANSFORM_SRC_PAD (videorate));
1388   downstream_caps = gst_pad_query_caps (pad, NULL);
1389   if (pad && !gst_caps_can_intersect (tmpcaps, downstream_caps)) {
1390     videorate->force_variable_rate = TRUE;
1391     gst_caps_unref (downstream_caps);
1392     GST_DEBUG_OBJECT (videorate, "Downstream forces variable framerate"
1393         " respecting it");
1394
1395     goto done;
1396   }
1397   gst_caps_unref (downstream_caps);
1398
1399   videorate->to_rate_numerator = fps_n;
1400   videorate->to_rate_denominator = fps_d;
1401
1402   GST_INFO_OBJECT (videorate, "Computed framerate to %d/%d",
1403       videorate->to_rate_numerator, videorate->to_rate_denominator);
1404
1405   videorate->updating_caps = TRUE;
1406   gst_base_transform_update_src_caps (GST_BASE_TRANSFORM (videorate), tmpcaps);
1407
1408   /* also reconfigure sink so that buffer pool can be updated again */
1409   gst_base_transform_reconfigure_sink (GST_BASE_TRANSFORM (videorate));
1410
1411 done:
1412   gst_caps_unref (tmpcaps);
1413   if (pad)
1414     gst_object_unref (pad);
1415 }
1416
1417 static gboolean
1418 gst_video_rate_switch_mode_if_needed (GstVideoRate * videorate)
1419 {
1420   gboolean switch_mode;
1421   GstClockTime avg_period;
1422   gboolean skip = FALSE;
1423
1424   GST_OBJECT_LOCK (videorate);
1425   avg_period = videorate->average_period_set;
1426   GST_OBJECT_UNLOCK (videorate);
1427
1428   /* MT-safe switching between modes */
1429   if (G_LIKELY (avg_period == videorate->average_period))
1430     return skip;
1431
1432   switch_mode = (avg_period == 0 || videorate->average_period == 0);
1433
1434   if (!switch_mode)
1435     return skip;
1436
1437
1438   videorate->average_period = avg_period;
1439   videorate->last_ts = GST_CLOCK_TIME_NONE;
1440   if (avg_period) {
1441     /* enabling average mode */
1442     videorate->average = 0;
1443     /* make sure no cached buffers from regular mode are left */
1444     gst_video_rate_swap_prev (videorate, NULL, 0);
1445   } else {
1446     /* enable regular mode */
1447     videorate->next_ts = GST_CLOCK_TIME_NONE;
1448     skip = TRUE;
1449   }
1450
1451   /* max averaging mode has no latency, normal mode does */
1452   gst_element_post_message (GST_ELEMENT (videorate),
1453       gst_message_new_latency (GST_OBJECT (videorate)));
1454
1455   return skip;
1456 }
1457
1458 static gboolean
1459 gst_video_rate_do_max_duplicate (GstVideoRate * videorate, GstBuffer * buffer,
1460     GstClockTime intime, GstClockTime prevtime, gint * count)
1461 {
1462   if (videorate->max_duplication_time <= 0)
1463     return TRUE;
1464
1465   /* We already know that intime and prevtime are not out of order, based
1466    * on the previous condition. Using ABS in case rate < 0, in which case
1467    * the order is reversed. */
1468   if (ABS (GST_CLOCK_DIFF (intime, prevtime)) > videorate->max_duplication_time) {
1469     GST_DEBUG_OBJECT (videorate,
1470         "The new buffer (%" GST_TIME_FORMAT
1471         ") is further away from previous buffer (%" GST_TIME_FORMAT
1472         ") than max-duplication-time (%" GST_TIME_FORMAT ")",
1473         GST_TIME_ARGS (intime), GST_TIME_ARGS (prevtime),
1474         GST_TIME_ARGS (videorate->max_duplication_time));
1475     /* First send out enough buffers to actually reach the time of the
1476      * previous buffer */
1477     if (videorate->segment.rate < 0.0) {
1478       while (videorate->next_ts > prevtime) {
1479         gst_video_rate_flush_prev (videorate, *count > 0, GST_CLOCK_TIME_NONE,
1480             FALSE);
1481         *count += 1;
1482       }
1483     } else {
1484       while (videorate->next_ts <= prevtime) {
1485         gst_video_rate_flush_prev (videorate, *count > 0, GST_CLOCK_TIME_NONE,
1486             FALSE);
1487         *count += 1;
1488       }
1489     }
1490
1491     if (*count > 1) {
1492       videorate->dup += *count - 1;
1493       if (!videorate->silent)
1494         gst_video_rate_notify_duplicate (videorate);
1495     }
1496
1497     /* The gap between the two buffers is too large. Don't fill it, just
1498      * let a discont through */
1499     videorate->discont = TRUE;
1500
1501     if (videorate->segment.rate < 0.0) {
1502       videorate->base_ts -= prevtime - intime;
1503     } else {
1504       videorate->base_ts += intime - prevtime;
1505     }
1506     videorate->next_ts = intime;
1507     /* Swap in new buffer and get rid of old buffer so that starting with
1508      * the next input buffer we output from the new position */
1509     gst_video_rate_swap_prev (videorate, buffer, intime);
1510     return FALSE;
1511   }
1512
1513   return TRUE;
1514 }
1515
1516 static gboolean
1517 gst_video_rate_apply_pending_rate (GstVideoRate * videorate)
1518 {
1519   gboolean ret = FALSE;
1520
1521   GST_OBJECT_LOCK (videorate);
1522   if (videorate->pending_rate == videorate->rate)
1523     goto done;
1524
1525   ret = TRUE;
1526   videorate->base_ts += gst_util_uint64_scale (videorate->out_frame_count,
1527       videorate->to_rate_denominator * GST_SECOND,
1528       videorate->to_rate_numerator);
1529   videorate->rate = videorate->pending_rate;
1530   videorate->out_frame_count = 0;
1531
1532 done:
1533   GST_OBJECT_UNLOCK (videorate);
1534
1535   return ret;
1536 }
1537
1538 static GstFlowReturn
1539 gst_video_rate_transform_ip (GstBaseTransform * trans, GstBuffer * buffer)
1540 {
1541   GstVideoRate *videorate;
1542   GstFlowReturn res = GST_BASE_TRANSFORM_FLOW_DROPPED;
1543   GstClockTime intime, in_ts, in_dur, last_ts;
1544   gboolean skip;
1545
1546   videorate = GST_VIDEO_RATE (trans);
1547
1548   /* make sure the denominators are not 0 */
1549   if (videorate->from_rate_denominator == 0 ||
1550       videorate->to_rate_denominator == 0)
1551     goto not_negotiated;
1552
1553   if (videorate->to_rate_numerator == 0 && videorate->prevbuf &&
1554       !videorate->force_variable_rate) {
1555     if (!GST_BUFFER_PTS_IS_VALID (buffer) ||
1556         !GST_BUFFER_PTS_IS_VALID (videorate->prevbuf)) {
1557       GST_ELEMENT_ERROR (videorate, STREAM, FAILED, (NULL),
1558           ("videorate requires a non-variable framerate on the output caps or the"
1559               " two first consecutive buffers to have valid timestamps to guess the"
1560               " framerate."));
1561       return GST_FLOW_ERROR;
1562     }
1563     gst_video_rate_check_variable_rate (videorate, buffer);
1564   }
1565
1566   skip = gst_video_rate_switch_mode_if_needed (videorate);
1567
1568   if (videorate->average_period > 0)
1569     return gst_video_rate_trans_ip_max_avg (videorate, buffer);
1570
1571   gst_video_rate_apply_pending_rate (videorate);
1572   in_ts = GST_BUFFER_TIMESTAMP (buffer);
1573   in_dur = GST_BUFFER_DURATION (buffer);
1574
1575   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (in_ts))) {
1576     /* For reverse playback, we need all input timestamps as we can't
1577      * guess from the previous buffers timestamp and duration */
1578     if (G_UNLIKELY (videorate->segment.rate < 0.0))
1579       goto invalid_buffer;
1580     in_ts = videorate->last_ts;
1581     if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (in_ts)))
1582       goto invalid_buffer;
1583   }
1584
1585   /* get the time of the next expected buffer timestamp, we use this when the
1586    * next buffer has -1 as a timestamp */
1587   last_ts = videorate->last_ts;
1588   videorate->last_ts = in_ts;
1589   if (GST_CLOCK_TIME_IS_VALID (in_dur) && videorate->segment.rate > 0.0)
1590     videorate->last_ts += in_dur;
1591
1592   GST_DEBUG_OBJECT (videorate, "got buffer with timestamp %" GST_TIME_FORMAT,
1593       GST_TIME_ARGS (in_ts));
1594
1595   /* the input time is the time in the segment + all previously accumulated
1596    * segments */
1597   intime = in_ts + videorate->segment.base;
1598
1599   /* we need to have two buffers to compare */
1600   if (videorate->prevbuf == NULL || videorate->drop_only) {
1601     /* We can calculate the duration of the buffer here if not given for
1602      * reverse playback. We need this later */
1603     if (videorate->segment.rate < 0.0 && !GST_BUFFER_DURATION_IS_VALID (buffer)) {
1604       /* As we require valid timestamps all the time for reverse playback, we either
1605        * have a valid last_ts or we're at the very first buffer. */
1606       if (!GST_CLOCK_TIME_IS_VALID (last_ts))
1607         GST_BUFFER_DURATION (buffer) = videorate->segment.stop - in_ts;
1608       else
1609         GST_BUFFER_DURATION (buffer) = last_ts - in_ts;
1610     }
1611
1612     gst_video_rate_swap_prev (videorate, buffer, intime);
1613     videorate->in++;
1614     if (!GST_CLOCK_TIME_IS_VALID (videorate->next_ts)) {
1615       /* new buffer, we expect to output a buffer that matches the first
1616        * timestamp in the segment */
1617       if (videorate->skip_to_first || skip) {
1618         videorate->next_ts = intime;
1619         if (videorate->segment.rate < 0.0) {
1620           videorate->base_ts = videorate->segment.stop - in_ts;
1621         } else {
1622           videorate->base_ts = in_ts - videorate->segment.start;
1623         }
1624         videorate->out_frame_count = 0;
1625       } else {
1626         if (videorate->segment.rate < 0.0) {
1627           if (videorate->to_rate_numerator) {
1628             GstClockTime frame_duration = gst_util_uint64_scale (1,
1629                 videorate->to_rate_denominator * GST_SECOND,
1630                 videorate->to_rate_numerator);
1631
1632             videorate->next_ts =
1633                 videorate->segment.stop + videorate->segment.base;
1634
1635             if (videorate->next_ts > frame_duration)
1636               videorate->next_ts =
1637                   MAX (videorate->segment.start,
1638                   videorate->next_ts - frame_duration);
1639             else
1640               videorate->next_ts = videorate->segment.start;
1641           } else {
1642             /* What else can we do? */
1643             videorate->next_ts = intime;
1644           }
1645         } else {
1646           videorate->next_ts =
1647               videorate->segment.start + videorate->segment.base;
1648         }
1649       }
1650     }
1651
1652     /* In drop-only mode we can already decide here if we should output the
1653      * current frame or drop it because it's coming earlier than our minimum
1654      * allowed frame period. This also keeps latency down to 0 frames
1655      */
1656     if (videorate->drop_only) {
1657       if ((videorate->segment.rate > 0.0 && intime >= videorate->next_ts) ||
1658           (videorate->segment.rate < 0.0 && intime <= videorate->next_ts)) {
1659         GstFlowReturn r;
1660
1661         /* The buffer received from basetransform is guaranteed to be writable.
1662          * It just needs to be reffed so the buffer won't be consumed once pushed and
1663          * GstBaseTransform can get its reference back. */
1664         if ((r = gst_video_rate_push_buffer (videorate,
1665                     gst_buffer_ref (buffer), FALSE,
1666                     GST_CLOCK_TIME_NONE, FALSE)) != GST_FLOW_OK) {
1667           res = r;
1668           goto done;
1669         }
1670       }
1671       /* No need to keep the buffer around for longer */
1672       gst_buffer_replace (&videorate->prevbuf, NULL);
1673     }
1674   } else {
1675     GstClockTime prevtime;
1676     gint count = 0;
1677     gint64 diff1 = 0, diff2 = 0;
1678
1679     prevtime = videorate->prev_ts;
1680
1681     GST_LOG_OBJECT (videorate,
1682         "BEGINNING prev buf %" GST_TIME_FORMAT " new buf %" GST_TIME_FORMAT
1683         " outgoing ts %" GST_TIME_FORMAT, GST_TIME_ARGS (prevtime),
1684         GST_TIME_ARGS (intime), GST_TIME_ARGS (videorate->next_ts));
1685
1686     videorate->in++;
1687
1688     /* drop new buffer if it's before previous one */
1689     if ((videorate->segment.rate > 0.0 && intime < prevtime) ||
1690         (videorate->segment.rate < 0.0 && intime > prevtime)) {
1691       GST_DEBUG_OBJECT (videorate,
1692           "The new buffer (%" GST_TIME_FORMAT
1693           ") is before the previous buffer (%"
1694           GST_TIME_FORMAT "). Dropping new buffer.",
1695           GST_TIME_ARGS (intime), GST_TIME_ARGS (prevtime));
1696       videorate->drop++;
1697       if (!videorate->silent)
1698         gst_video_rate_notify_drop (videorate);
1699       goto done;
1700     }
1701
1702     if (!gst_video_rate_do_max_duplicate (videorate, buffer, intime, prevtime,
1703             &count))
1704       goto done;
1705
1706     /* got 2 buffers, see which one is the best */
1707     do {
1708       GstClockTime next_ts;
1709
1710       if (gst_video_rate_apply_pending_rate (videorate))
1711         goto done;
1712
1713       if (videorate->segment.rate < 0.0) {
1714         /* Make sure that we have a duration for this buffer. The previous
1715          * buffer already has a duration given by either exactly this code,
1716          * or the code above for the very first buffer */
1717         g_assert (GST_BUFFER_DURATION_IS_VALID (videorate->prevbuf));
1718         if (!GST_BUFFER_DURATION_IS_VALID (buffer))
1719           GST_BUFFER_DURATION (buffer) =
1720               prevtime > intime ? prevtime - intime : 0;
1721       } else {
1722         /* Make sure that we have a duration for previous buffer */
1723         if (!GST_BUFFER_DURATION_IS_VALID (videorate->prevbuf))
1724           GST_BUFFER_DURATION (videorate->prevbuf) =
1725               intime > prevtime ? intime - prevtime : 0;
1726       }
1727
1728 #ifndef ABSDIFF
1729 #define ABSDIFF(a, b) (((a) > (b)) ? (a) - (b) : (b) - (a))
1730 #endif
1731
1732       /* take absolute diffs */
1733       if (videorate->segment.rate < 0.0) {
1734         GstClockTime next_end_ts;
1735         GstClockTime prev_endtime;
1736         GstClockTime in_endtime, base_ts_in_segment;
1737
1738         next_ts = videorate->next_ts;
1739
1740         if (!GST_CLOCK_TIME_IS_VALID (next_ts)) {
1741           GST_DEBUG_OBJECT (videorate, "Already reached segment start,"
1742               "ignoring buffer");
1743           break;
1744         }
1745
1746         prev_endtime = prevtime + GST_BUFFER_DURATION (videorate->prevbuf);
1747         in_endtime = intime + GST_BUFFER_DURATION (buffer);
1748
1749         if (videorate->to_rate_numerator) {
1750           GstClockTime frame_duration = gst_util_uint64_scale (1,
1751               videorate->to_rate_denominator * GST_SECOND,
1752               videorate->to_rate_numerator);
1753           next_end_ts = next_ts + frame_duration;
1754         } else {
1755           next_end_ts = next_ts + GST_BUFFER_DURATION (videorate->prevbuf);
1756         }
1757
1758         base_ts_in_segment = videorate->segment.stop - videorate->base_ts;
1759         next_ts = base_ts_in_segment - (
1760             (base_ts_in_segment - next_ts) * videorate->rate);
1761         next_end_ts = base_ts_in_segment - (MAX (0,
1762                 (base_ts_in_segment - next_end_ts)) * videorate->rate);
1763
1764         diff1 = ABSDIFF (prev_endtime, next_end_ts);
1765         diff2 = ABSDIFF (in_endtime, next_end_ts);
1766
1767         GST_LOG_OBJECT (videorate,
1768             "diff with prev %" GST_TIME_FORMAT " diff with new %"
1769             GST_TIME_FORMAT " outgoing ts %" GST_TIME_FORMAT,
1770             GST_TIME_ARGS (diff1), GST_TIME_ARGS (diff2),
1771             GST_TIME_ARGS (next_end_ts));
1772       } else {
1773         next_ts =
1774             videorate->base_ts + ((videorate->next_ts -
1775                 videorate->base_ts) * videorate->rate);
1776
1777         diff1 = ABSDIFF (prevtime, next_ts);
1778         diff2 = ABSDIFF (intime, next_ts);
1779
1780         GST_LOG_OBJECT (videorate,
1781             "diff with prev %" GST_TIME_FORMAT " diff with new %"
1782             GST_TIME_FORMAT " outgoing ts %" GST_TIME_FORMAT,
1783             GST_TIME_ARGS (diff1), GST_TIME_ARGS (diff2),
1784             GST_TIME_ARGS (next_ts));
1785       }
1786
1787       /* output first one when its the best */
1788       if (diff1 <= diff2) {
1789         GstFlowReturn r;
1790         count++;
1791
1792         /* on error the _flush function posted a warning already */
1793         if ((r = gst_video_rate_flush_prev (videorate,
1794                     count > 1, intime, FALSE)) != GST_FLOW_OK) {
1795           res = r;
1796           goto done;
1797         }
1798       }
1799
1800       /* continue while the first one was the best, if they were equal avoid
1801        * going into an infinite loop */
1802     }
1803     while (diff1 < diff2);
1804
1805     /* if we outputted the first buffer more then once, we have dups */
1806     if (count > 1) {
1807       videorate->dup += count - 1;
1808       if (!videorate->silent)
1809         gst_video_rate_notify_duplicate (videorate);
1810     }
1811     /* if we didn't output the first buffer, we have a drop */
1812     else if (count == 0) {
1813       videorate->drop++;
1814
1815       if (!videorate->silent)
1816         gst_video_rate_notify_drop (videorate);
1817
1818       GST_LOG_OBJECT (videorate,
1819           "new is best, old never used, drop, outgoing ts %"
1820           GST_TIME_FORMAT, GST_TIME_ARGS (videorate->next_ts));
1821     }
1822     GST_LOG_OBJECT (videorate,
1823         "END, putting new in old, diff1 %" GST_TIME_FORMAT
1824         ", diff2 %" GST_TIME_FORMAT ", next_ts %" GST_TIME_FORMAT
1825         ", in %" G_GUINT64_FORMAT ", out %" G_GUINT64_FORMAT ", drop %"
1826         G_GUINT64_FORMAT ", dup %" G_GUINT64_FORMAT, GST_TIME_ARGS (diff1),
1827         GST_TIME_ARGS (diff2), GST_TIME_ARGS (videorate->next_ts),
1828         videorate->in, videorate->out, videorate->drop, videorate->dup);
1829
1830     /* swap in new one when it's the best */
1831     gst_video_rate_swap_prev (videorate, buffer, intime);
1832   }
1833 done:
1834   return res;
1835
1836   /* ERRORS */
1837 not_negotiated:
1838   {
1839     GST_WARNING_OBJECT (videorate, "no framerate negotiated");
1840     res = GST_FLOW_NOT_NEGOTIATED;
1841     goto done;
1842   }
1843
1844 invalid_buffer:
1845   {
1846     GST_WARNING_OBJECT (videorate,
1847         "Got buffer with GST_CLOCK_TIME_NONE timestamp, discarding it");
1848     res = GST_BASE_TRANSFORM_FLOW_DROPPED;
1849     goto done;
1850   }
1851 }
1852
1853 static gboolean
1854 gst_video_rate_start (GstBaseTransform * trans)
1855 {
1856   gst_video_rate_reset (GST_VIDEO_RATE (trans));
1857   return TRUE;
1858 }
1859
1860 static gboolean
1861 gst_video_rate_stop (GstBaseTransform * trans)
1862 {
1863   gst_video_rate_reset (GST_VIDEO_RATE (trans));
1864   return TRUE;
1865 }
1866
1867 static void
1868 gst_videorate_update_duration (GstVideoRate * videorate)
1869 {
1870   GstMessage *m;
1871
1872   m = gst_message_new_duration_changed (GST_OBJECT (videorate));
1873   gst_element_post_message (GST_ELEMENT (videorate), m);
1874 }
1875
1876 static void
1877 gst_video_rate_set_property (GObject * object,
1878     guint prop_id, const GValue * value, GParamSpec * pspec)
1879 {
1880   GstVideoRate *videorate = GST_VIDEO_RATE (object);
1881   gboolean latency_changed = FALSE;
1882
1883   GST_OBJECT_LOCK (videorate);
1884   switch (prop_id) {
1885     case PROP_SILENT:
1886       videorate->silent = g_value_get_boolean (value);
1887       break;
1888     case PROP_NEW_PREF:
1889       videorate->new_pref = g_value_get_double (value);
1890       break;
1891     case PROP_SKIP_TO_FIRST:
1892       videorate->skip_to_first = g_value_get_boolean (value);
1893       break;
1894     case PROP_DROP_ONLY:{
1895       gboolean new_value = g_value_get_boolean (value);
1896
1897       /* Latency changes if we switch drop-only mode */
1898       latency_changed = new_value != videorate->drop_only;
1899       videorate->drop_only = g_value_get_boolean (value);
1900       goto reconfigure;
1901     }
1902     case PROP_AVERAGE_PERIOD:
1903       videorate->average_period_set = g_value_get_uint64 (value);
1904       break;
1905     case PROP_MAX_RATE:
1906       g_atomic_int_set (&videorate->max_rate, g_value_get_int (value));
1907       goto reconfigure;
1908     case PROP_RATE:
1909       videorate->pending_rate = g_value_get_double (value);
1910       GST_OBJECT_UNLOCK (videorate);
1911
1912       gst_videorate_update_duration (videorate);
1913       return;
1914     case PROP_MAX_DUPLICATION_TIME:
1915       videorate->max_duplication_time = g_value_get_uint64 (value);
1916       break;
1917     case PROP_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION:
1918       videorate->max_closing_segment_duplication_duration =
1919           g_value_get_uint64 (value);
1920       break;
1921     default:
1922       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1923       break;
1924   }
1925   GST_OBJECT_UNLOCK (videorate);
1926
1927   return;
1928
1929 reconfigure:
1930   GST_OBJECT_UNLOCK (videorate);
1931   gst_base_transform_reconfigure_src (GST_BASE_TRANSFORM (videorate));
1932
1933   if (latency_changed) {
1934     gst_element_post_message (GST_ELEMENT (videorate),
1935         gst_message_new_latency (GST_OBJECT (videorate)));
1936   }
1937 }
1938
1939 static void
1940 gst_video_rate_get_property (GObject * object,
1941     guint prop_id, GValue * value, GParamSpec * pspec)
1942 {
1943   GstVideoRate *videorate = GST_VIDEO_RATE (object);
1944
1945   GST_OBJECT_LOCK (videorate);
1946   switch (prop_id) {
1947     case PROP_IN:
1948       g_value_set_uint64 (value, videorate->in);
1949       break;
1950     case PROP_OUT:
1951       g_value_set_uint64 (value, videorate->out);
1952       break;
1953     case PROP_DUP:
1954       g_value_set_uint64 (value, videorate->dup);
1955       break;
1956     case PROP_DROP:
1957       g_value_set_uint64 (value, videorate->drop);
1958       break;
1959     case PROP_SILENT:
1960       g_value_set_boolean (value, videorate->silent);
1961       break;
1962     case PROP_NEW_PREF:
1963       g_value_set_double (value, videorate->new_pref);
1964       break;
1965     case PROP_SKIP_TO_FIRST:
1966       g_value_set_boolean (value, videorate->skip_to_first);
1967       break;
1968     case PROP_DROP_ONLY:
1969       g_value_set_boolean (value, videorate->drop_only);
1970       break;
1971     case PROP_AVERAGE_PERIOD:
1972       g_value_set_uint64 (value, videorate->average_period_set);
1973       break;
1974     case PROP_MAX_RATE:
1975       g_value_set_int (value, g_atomic_int_get (&videorate->max_rate));
1976       break;
1977     case PROP_RATE:
1978       g_value_set_double (value, videorate->pending_rate);
1979       break;
1980     case PROP_MAX_DUPLICATION_TIME:
1981       g_value_set_uint64 (value, videorate->max_duplication_time);
1982       break;
1983     case PROP_MAX_CLOSING_SEGMENT_DUPLICATION_DURATION:
1984       g_value_set_uint64 (value,
1985           videorate->max_closing_segment_duplication_duration);
1986       break;
1987     default:
1988       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1989       break;
1990   }
1991   GST_OBJECT_UNLOCK (videorate);
1992 }
1993
1994 static gboolean
1995 plugin_init (GstPlugin * plugin)
1996 {
1997   GST_DEBUG_CATEGORY_INIT (video_rate_debug, "videorate", 0,
1998       "VideoRate stream fixer");
1999
2000   return GST_ELEMENT_REGISTER (videorate, plugin);
2001 }
2002
2003 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2004     GST_VERSION_MINOR,
2005     videorate,
2006     "Adjusts video frames",
2007     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)