Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / 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., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-videorate
22  *
23  * This element takes an incoming stream of timestamped video frames.
24  * It will produce a perfect stream that matches the source pad's framerate.
25  *
26  * The correction is performed by dropping and duplicating frames, no fancy
27  * algorithm is used to interpolate frames (yet).
28  *
29  * By default the element will simply negotiate the same framerate on its
30  * source and sink pad.
31  *
32  * This operation is useful to link to elements that require a perfect stream.
33  * Typical examples are formats that do not store timestamps for video frames,
34  * but only store a framerate, like Ogg and AVI.
35  *
36  * A conversion to a specific framerate can be forced by using filtered caps on
37  * the source pad.
38  *
39  * The properties #GstVideoRate:in, #GstVideoRate:out, #GstVideoRate:duplicate
40  * and #GstVideoRate:drop can be read to obtain information about number of
41  * input frames, output frames, dropped frames (i.e. the number of unused input
42  * frames) and duplicated frames (i.e. the number of times an input frame was
43  * duplicated, beside being used normally).
44  *
45  * An input stream that needs no adjustments will thus never have dropped or
46  * duplicated frames.
47  *
48  * When the #GstVideoRate:silent property is set to FALSE, a GObject property
49  * notification will be emitted whenever one of the #GstVideoRate:duplicate or
50  * #GstVideoRate:drop values changes.
51  * This can potentially cause performance degradation.
52  * Note that property notification will happen from the streaming thread, so
53  * applications should be prepared for this.
54  *
55  * <refsect2>
56  * <title>Example pipelines</title>
57  * |[
58  * gst-launch -v filesrc location=videotestsrc.ogg ! oggdemux ! theoradec ! videorate ! video/x-raw-yuv,framerate=15/1 ! xvimagesink
59  * ]| Decode an Ogg/Theora file and adjust the framerate to 15 fps before playing.
60  * To create the test Ogg/Theora file refer to the documentation of theoraenc.
61  * |[
62  * gst-launch -v v4lsrc ! videorate ! video/x-raw-yuv,framerate=25/2 ! theoraenc ! oggmux ! filesink location=v4l.ogg
63  * ]| Capture video from a V4L device, and adjust the stream to 12.5 fps before
64  * encoding to Ogg/Theora.
65  * </refsect2>
66  *
67  * Last reviewed on 2006-09-02 (0.10.11)
68  */
69
70 #ifdef HAVE_CONFIG_H
71 #include "config.h"
72 #endif
73
74 #include "gstvideorate.h"
75
76 GST_DEBUG_CATEGORY_STATIC (video_rate_debug);
77 #define GST_CAT_DEFAULT video_rate_debug
78
79 /* GstVideoRate signals and args */
80 enum
81 {
82   /* FILL ME */
83   LAST_SIGNAL
84 };
85
86 #define DEFAULT_SILENT          TRUE
87 #define DEFAULT_NEW_PREF        1.0
88 #define DEFAULT_SKIP_TO_FIRST   FALSE
89
90 enum
91 {
92   ARG_0,
93   ARG_IN,
94   ARG_OUT,
95   ARG_DUP,
96   ARG_DROP,
97   ARG_SILENT,
98   ARG_NEW_PREF,
99   ARG_SKIP_TO_FIRST
100       /* FILL ME */
101 };
102
103 static GstStaticPadTemplate gst_video_rate_src_template =
104     GST_STATIC_PAD_TEMPLATE ("src",
105     GST_PAD_SRC,
106     GST_PAD_ALWAYS,
107     GST_STATIC_CAPS ("video/x-raw-yuv;"
108         "video/x-raw-rgb;" "video/x-raw-gray;" "image/jpeg;" "image/png")
109     );
110
111 static GstStaticPadTemplate gst_video_rate_sink_template =
112     GST_STATIC_PAD_TEMPLATE ("sink",
113     GST_PAD_SINK,
114     GST_PAD_ALWAYS,
115     GST_STATIC_CAPS ("video/x-raw-yuv;"
116         "video/x-raw-rgb;" "video/x-raw-gray;" "image/jpeg;" "image/png")
117     );
118
119 static void gst_video_rate_swap_prev (GstVideoRate * videorate,
120     GstBuffer * buffer, gint64 time);
121 static gboolean gst_video_rate_event (GstPad * pad, GstEvent * event);
122 static gboolean gst_video_rate_query (GstPad * pad, GstQuery * query);
123 static GstFlowReturn gst_video_rate_chain (GstPad * pad, GstBuffer * buffer);
124
125 static void gst_video_rate_set_property (GObject * object,
126     guint prop_id, const GValue * value, GParamSpec * pspec);
127 static void gst_video_rate_get_property (GObject * object,
128     guint prop_id, GValue * value, GParamSpec * pspec);
129
130 static GstStateChangeReturn gst_video_rate_change_state (GstElement * element,
131     GstStateChange transition);
132
133 /*static guint gst_video_rate_signals[LAST_SIGNAL] = { 0 }; */
134
135 static GParamSpec *pspec_drop = NULL;
136 static GParamSpec *pspec_duplicate = NULL;
137
138 GST_BOILERPLATE (GstVideoRate, gst_video_rate, GstElement, GST_TYPE_ELEMENT);
139
140 static void
141 gst_video_rate_base_init (gpointer g_class)
142 {
143   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
144
145   gst_element_class_set_details_simple (element_class,
146       "Video rate adjuster", "Filter/Effect/Video",
147       "Drops/duplicates/adjusts timestamps on video frames to make a perfect stream",
148       "Wim Taymans <wim@fluendo.com>");
149
150   gst_element_class_add_pad_template (element_class,
151       gst_static_pad_template_get (&gst_video_rate_sink_template));
152   gst_element_class_add_pad_template (element_class,
153       gst_static_pad_template_get (&gst_video_rate_src_template));
154 }
155
156 static void
157 gst_video_rate_class_init (GstVideoRateClass * klass)
158 {
159   GObjectClass *object_class = G_OBJECT_CLASS (klass);
160   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
161
162   parent_class = g_type_class_peek_parent (klass);
163
164   object_class->set_property = gst_video_rate_set_property;
165   object_class->get_property = gst_video_rate_get_property;
166
167   g_object_class_install_property (object_class, ARG_IN,
168       g_param_spec_uint64 ("in", "In",
169           "Number of input frames", 0, G_MAXUINT64, 0,
170           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
171   g_object_class_install_property (object_class, ARG_OUT,
172       g_param_spec_uint64 ("out", "Out", "Number of output frames", 0,
173           G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
174   pspec_duplicate = g_param_spec_uint64 ("duplicate", "Duplicate",
175       "Number of duplicated frames", 0, G_MAXUINT64, 0,
176       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
177   g_object_class_install_property (object_class, ARG_DUP, pspec_duplicate);
178   pspec_drop = g_param_spec_uint64 ("drop", "Drop", "Number of dropped frames",
179       0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
180   g_object_class_install_property (object_class, ARG_DROP, pspec_drop);
181   g_object_class_install_property (object_class, ARG_SILENT,
182       g_param_spec_boolean ("silent", "silent",
183           "Don't emit notify for dropped and duplicated frames", DEFAULT_SILENT,
184           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
185   g_object_class_install_property (object_class, ARG_NEW_PREF,
186       g_param_spec_double ("new-pref", "New Pref",
187           "Value indicating how much to prefer new frames (unused)", 0.0, 1.0,
188           DEFAULT_NEW_PREF, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
189
190   /**
191    * GstVideoRate:skip-to-first:
192    * 
193    * Don't produce buffers before the first one we receive.
194    *
195    * Since: 0.10.25
196    */
197   g_object_class_install_property (object_class, ARG_SKIP_TO_FIRST,
198       g_param_spec_boolean ("skip-to-first", "Skip to first buffer",
199           "Don't produce buffers before the first one we receive",
200           DEFAULT_SKIP_TO_FIRST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
201
202   element_class->change_state = GST_DEBUG_FUNCPTR (gst_video_rate_change_state);
203 }
204
205 /* return the caps that can be used on out_pad given in_caps on in_pad */
206 static gboolean
207 gst_video_rate_transformcaps (GstPad * in_pad, GstCaps * in_caps,
208     GstPad * out_pad, GstCaps ** out_caps)
209 {
210   GstCaps *intersect;
211   const GstCaps *in_templ;
212   gint i;
213   GSList *extra_structures = NULL;
214   GSList *iter;
215
216   in_templ = gst_pad_get_pad_template_caps (in_pad);
217   intersect = gst_caps_intersect (in_caps, in_templ);
218
219   /* all possible framerates are allowed */
220   for (i = 0; i < gst_caps_get_size (intersect); i++) {
221     GstStructure *structure;
222
223     structure = gst_caps_get_structure (intersect, i);
224
225     if (gst_structure_has_field (structure, "framerate")) {
226       GstStructure *copy_structure;
227
228       copy_structure = gst_structure_copy (structure);
229       gst_structure_set (copy_structure,
230           "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
231       extra_structures = g_slist_append (extra_structures, copy_structure);
232     }
233   }
234
235   /* append the extra structures */
236   for (iter = extra_structures; iter != NULL; iter = g_slist_next (iter)) {
237     gst_caps_append_structure (intersect, (GstStructure *) iter->data);
238   }
239   g_slist_free (extra_structures);
240
241   *out_caps = intersect;
242
243   return TRUE;
244 }
245
246 static GstCaps *
247 gst_video_rate_getcaps (GstPad * pad)
248 {
249   GstVideoRate *videorate;
250   GstPad *otherpad;
251   GstCaps *caps;
252
253   videorate = GST_VIDEO_RATE (GST_PAD_PARENT (pad));
254
255   otherpad = (pad == videorate->srcpad) ? videorate->sinkpad :
256       videorate->srcpad;
257
258   /* we can do what the peer can */
259   caps = gst_pad_peer_get_caps (otherpad);
260   if (caps) {
261     GstCaps *transform;
262
263     gst_video_rate_transformcaps (otherpad, caps, pad, &transform);
264     gst_caps_unref (caps);
265     caps = transform;
266   } else {
267     /* no peer, our padtemplate is enough then */
268     caps = gst_caps_copy (gst_pad_get_pad_template_caps (pad));
269   }
270
271   return caps;
272 }
273
274 static gboolean
275 gst_video_rate_setcaps (GstPad * pad, GstCaps * caps)
276 {
277   GstVideoRate *videorate;
278   GstStructure *structure;
279   gboolean ret = TRUE;
280   GstPad *otherpad, *opeer;
281   gint rate_numerator, rate_denominator;
282
283   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
284
285   GST_DEBUG_OBJECT (pad, "setcaps called %" GST_PTR_FORMAT, caps);
286
287   structure = gst_caps_get_structure (caps, 0);
288   if (!gst_structure_get_fraction (structure, "framerate",
289           &rate_numerator, &rate_denominator))
290     goto no_framerate;
291
292   if (pad == videorate->srcpad) {
293     /* out_frame_count is scaled by the frame rate caps when calculating next_ts.
294      * when the frame rate caps change, we must update base_ts and reset
295      * out_frame_count */
296     if (videorate->to_rate_numerator) {
297       videorate->base_ts +=
298           gst_util_uint64_scale (videorate->out_frame_count,
299           videorate->to_rate_denominator * GST_SECOND,
300           videorate->to_rate_numerator);
301     }
302     videorate->out_frame_count = 0;
303     videorate->to_rate_numerator = rate_numerator;
304     videorate->to_rate_denominator = rate_denominator;
305     otherpad = videorate->sinkpad;
306   } else {
307     videorate->from_rate_numerator = rate_numerator;
308     videorate->from_rate_denominator = rate_denominator;
309     otherpad = videorate->srcpad;
310   }
311
312   /* now try to find something for the peer */
313   opeer = gst_pad_get_peer (otherpad);
314   if (opeer) {
315     if (gst_pad_accept_caps (opeer, caps)) {
316       /* the peer accepts the caps as they are */
317       gst_pad_set_caps (otherpad, caps);
318
319       ret = TRUE;
320     } else {
321       GstCaps *peercaps;
322       GstCaps *transform = NULL;
323
324       ret = FALSE;
325
326       /* see how we can transform the input caps */
327       if (!gst_video_rate_transformcaps (pad, caps, otherpad, &transform))
328         goto no_transform;
329
330       /* see what the peer can do */
331       peercaps = gst_pad_get_caps (opeer);
332
333       GST_DEBUG_OBJECT (opeer, "icaps %" GST_PTR_FORMAT, peercaps);
334       GST_DEBUG_OBJECT (videorate, "transform %" GST_PTR_FORMAT, transform);
335
336       /* filter against our possibilities */
337       caps = gst_caps_intersect (peercaps, transform);
338       gst_caps_unref (peercaps);
339       gst_caps_unref (transform);
340
341       GST_DEBUG_OBJECT (videorate, "intersect %" GST_PTR_FORMAT, caps);
342
343       /* take first possibility */
344       gst_caps_truncate (caps);
345       structure = gst_caps_get_structure (caps, 0);
346
347       /* and fixate */
348       gst_structure_fixate_field_nearest_fraction (structure, "framerate",
349           rate_numerator, rate_denominator);
350
351       gst_structure_get_fraction (structure, "framerate",
352           &rate_numerator, &rate_denominator);
353
354       if (otherpad == videorate->srcpad) {
355         videorate->to_rate_numerator = rate_numerator;
356         videorate->to_rate_denominator = rate_denominator;
357       } else {
358         videorate->from_rate_numerator = rate_numerator;
359         videorate->from_rate_denominator = rate_denominator;
360       }
361
362       if (gst_structure_has_field (structure, "interlaced"))
363         gst_structure_fixate_field_boolean (structure, "interlaced", FALSE);
364       if (gst_structure_has_field (structure, "color-matrix"))
365         gst_structure_fixate_field_string (structure, "color-matrix", "sdtv");
366       if (gst_structure_has_field (structure, "chroma-site"))
367         gst_structure_fixate_field_string (structure, "chroma-site", "mpeg2");
368       if (gst_structure_has_field (structure, "pixel-aspect-ratio"))
369         gst_structure_fixate_field_nearest_fraction (structure,
370             "pixel-aspect-ratio", 1, 1);
371
372       gst_pad_set_caps (otherpad, caps);
373       gst_caps_unref (caps);
374       ret = TRUE;
375     }
376     gst_object_unref (opeer);
377   }
378 done:
379   /* After a setcaps, our caps may have changed. In that case, we can't use
380    * the old buffer, if there was one (it might have different dimensions) */
381   GST_DEBUG_OBJECT (videorate, "swapping old buffers");
382   gst_video_rate_swap_prev (videorate, NULL, GST_CLOCK_TIME_NONE);
383
384   gst_object_unref (videorate);
385   return ret;
386
387 no_framerate:
388   {
389     GST_DEBUG_OBJECT (videorate, "no framerate specified");
390     goto done;
391   }
392 no_transform:
393   {
394     GST_DEBUG_OBJECT (videorate, "no framerate transform possible");
395     ret = FALSE;
396     goto done;
397   }
398 }
399
400 static void
401 gst_video_rate_reset (GstVideoRate * videorate)
402 {
403   GST_DEBUG_OBJECT (videorate, "resetting internal variables");
404
405   videorate->in = 0;
406   videorate->out = 0;
407   videorate->base_ts = 0;
408   videorate->out_frame_count = 0;
409   videorate->drop = 0;
410   videorate->dup = 0;
411   videorate->next_ts = GST_CLOCK_TIME_NONE;
412   videorate->last_ts = GST_CLOCK_TIME_NONE;
413   videorate->discont = TRUE;
414   gst_video_rate_swap_prev (videorate, NULL, 0);
415
416   gst_segment_init (&videorate->segment, GST_FORMAT_TIME);
417 }
418
419 static void
420 gst_video_rate_init (GstVideoRate * videorate, GstVideoRateClass * klass)
421 {
422   videorate->sinkpad =
423       gst_pad_new_from_static_template (&gst_video_rate_sink_template, "sink");
424   gst_pad_set_event_function (videorate->sinkpad,
425       GST_DEBUG_FUNCPTR (gst_video_rate_event));
426   gst_pad_set_chain_function (videorate->sinkpad,
427       GST_DEBUG_FUNCPTR (gst_video_rate_chain));
428   gst_pad_set_getcaps_function (videorate->sinkpad,
429       GST_DEBUG_FUNCPTR (gst_video_rate_getcaps));
430   gst_pad_set_setcaps_function (videorate->sinkpad,
431       GST_DEBUG_FUNCPTR (gst_video_rate_setcaps));
432   gst_element_add_pad (GST_ELEMENT (videorate), videorate->sinkpad);
433
434   videorate->srcpad =
435       gst_pad_new_from_static_template (&gst_video_rate_src_template, "src");
436   gst_pad_set_query_function (videorate->srcpad,
437       GST_DEBUG_FUNCPTR (gst_video_rate_query));
438   gst_pad_set_getcaps_function (videorate->srcpad,
439       GST_DEBUG_FUNCPTR (gst_video_rate_getcaps));
440   gst_pad_set_setcaps_function (videorate->srcpad,
441       GST_DEBUG_FUNCPTR (gst_video_rate_setcaps));
442   gst_element_add_pad (GST_ELEMENT (videorate), videorate->srcpad);
443
444   gst_video_rate_reset (videorate);
445   videorate->silent = DEFAULT_SILENT;
446   videorate->new_pref = DEFAULT_NEW_PREF;
447
448   videorate->from_rate_numerator = 0;
449   videorate->from_rate_denominator = 0;
450   videorate->to_rate_numerator = 0;
451   videorate->to_rate_denominator = 0;
452 }
453
454 /* flush the oldest buffer */
455 static GstFlowReturn
456 gst_video_rate_flush_prev (GstVideoRate * videorate, gboolean duplicate)
457 {
458   GstFlowReturn res;
459   GstBuffer *outbuf;
460   GstClockTime push_ts;
461
462   if (!videorate->prevbuf)
463     goto eos_before_buffers;
464
465   /* make sure we can write to the metadata */
466   outbuf = gst_buffer_make_writable (gst_buffer_ref (videorate->prevbuf));
467
468   GST_BUFFER_OFFSET (outbuf) = videorate->out;
469   GST_BUFFER_OFFSET_END (outbuf) = videorate->out + 1;
470
471   if (videorate->discont) {
472     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
473     videorate->discont = FALSE;
474   } else
475     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DISCONT);
476
477   if (duplicate)
478     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_GAP);
479   else
480     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_GAP);
481
482   /* this is the timestamp we put on the buffer */
483   push_ts = videorate->next_ts;
484
485   videorate->out++;
486   videorate->out_frame_count++;
487   if (videorate->to_rate_numerator) {
488     /* interpolate next expected timestamp in the segment */
489     videorate->next_ts =
490         videorate->segment.accum + videorate->segment.start +
491         videorate->base_ts + gst_util_uint64_scale (videorate->out_frame_count,
492         videorate->to_rate_denominator * GST_SECOND,
493         videorate->to_rate_numerator);
494     GST_BUFFER_DURATION (outbuf) = videorate->next_ts - push_ts;
495   }
496
497   /* adapt for looping, bring back to time in current segment. */
498   GST_BUFFER_TIMESTAMP (outbuf) = push_ts - videorate->segment.accum;
499
500   gst_buffer_set_caps (outbuf, GST_PAD_CAPS (videorate->srcpad));
501
502   GST_LOG_OBJECT (videorate,
503       "old is best, dup, pushing buffer outgoing ts %" GST_TIME_FORMAT,
504       GST_TIME_ARGS (push_ts));
505
506   res = gst_pad_push (videorate->srcpad, outbuf);
507
508   return res;
509
510   /* WARNINGS */
511 eos_before_buffers:
512   {
513     GST_INFO_OBJECT (videorate, "got EOS before any buffer was received");
514     return GST_FLOW_OK;
515   }
516 }
517
518 static void
519 gst_video_rate_swap_prev (GstVideoRate * videorate, GstBuffer * buffer,
520     gint64 time)
521 {
522   GST_LOG_OBJECT (videorate, "swap_prev: storing buffer %p in prev", buffer);
523   if (videorate->prevbuf)
524     gst_buffer_unref (videorate->prevbuf);
525   videorate->prevbuf = buffer;
526   videorate->prev_ts = time;
527 }
528
529 static void
530 gst_video_rate_notify_drop (GstVideoRate * videorate)
531 {
532 #if !GLIB_CHECK_VERSION(2,26,0)
533   g_object_notify ((GObject *) videorate, "drop");
534 #else
535   g_object_notify_by_pspec ((GObject *) videorate, pspec_drop);
536 #endif
537 }
538
539 static void
540 gst_video_rate_notify_duplicate (GstVideoRate * videorate)
541 {
542 #if !GLIB_CHECK_VERSION(2,26,0)
543   g_object_notify ((GObject *) videorate, "duplicate");
544 #else
545   g_object_notify_by_pspec ((GObject *) videorate, pspec_duplicate);
546 #endif
547 }
548
549 #define MAGIC_LIMIT  25
550 static gboolean
551 gst_video_rate_event (GstPad * pad, GstEvent * event)
552 {
553   GstVideoRate *videorate;
554   gboolean ret;
555
556   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
557
558   switch (GST_EVENT_TYPE (event)) {
559     case GST_EVENT_NEWSEGMENT:
560     {
561       gint64 start, stop, time;
562       gdouble rate, arate;
563       gboolean update;
564       GstFormat format;
565
566       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
567           &start, &stop, &time);
568
569       if (format != GST_FORMAT_TIME)
570         goto format_error;
571
572       GST_DEBUG_OBJECT (videorate, "handle NEWSEGMENT");
573
574       /* close up the previous segment, if appropriate */
575       if (!update && videorate->prevbuf) {
576         gint count = 0;
577         GstFlowReturn res;
578
579         res = GST_FLOW_OK;
580         /* fill up to the end of current segment,
581          * or only send out the stored buffer if there is no specific stop.
582          * regardless, prevent going loopy in strange cases */
583         while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
584             ((GST_CLOCK_TIME_IS_VALID (videorate->segment.stop) &&
585                     videorate->next_ts - videorate->segment.accum
586                     < videorate->segment.stop)
587                 || count < 1)) {
588           res = gst_video_rate_flush_prev (videorate, count > 0);
589           count++;
590         }
591         if (count > 1) {
592           videorate->dup += count - 1;
593           if (!videorate->silent)
594             gst_video_rate_notify_duplicate (videorate);
595         } else if (count == 0) {
596           videorate->drop++;
597           if (!videorate->silent)
598             gst_video_rate_notify_drop (videorate);
599         }
600         /* clean up for the new one; _chain will resume from the new start */
601         videorate->base_ts = 0;
602         videorate->out_frame_count = 0;
603         gst_video_rate_swap_prev (videorate, NULL, 0);
604         videorate->next_ts = GST_CLOCK_TIME_NONE;
605       }
606
607       /* We just want to update the accumulated stream_time  */
608       gst_segment_set_newsegment_full (&videorate->segment, update, rate, arate,
609           format, start, stop, time);
610
611       GST_DEBUG_OBJECT (videorate, "updated segment: %" GST_SEGMENT_FORMAT,
612           &videorate->segment);
613       break;
614     }
615     case GST_EVENT_EOS:{
616       gint count = 0;
617       GstFlowReturn res = GST_FLOW_OK;
618
619       GST_DEBUG_OBJECT (videorate, "Got EOS");
620
621       /* If the segment has a stop position, fill the segment */
622       if (GST_CLOCK_TIME_IS_VALID (videorate->segment.stop)) {
623         /* fill up to the end of current segment,
624          * or only send out the stored buffer if there is no specific stop.
625          * regardless, prevent going loopy in strange cases */
626         while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
627             ((videorate->next_ts - videorate->segment.accum <
628                     videorate->segment.stop)
629                 || count < 1)) {
630           res = gst_video_rate_flush_prev (videorate, count > 0);
631           count++;
632         }
633       } else if (videorate->prevbuf) {
634         /* Output at least one frame but if the buffer duration is valid, output
635          * enough frames to use the complete buffer duration */
636         if (GST_BUFFER_DURATION_IS_VALID (videorate->prevbuf)) {
637           GstClockTime end_ts =
638               videorate->next_ts + GST_BUFFER_DURATION (videorate->prevbuf);
639
640           while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
641               ((videorate->next_ts - videorate->segment.accum < end_ts)
642                   || count < 1)) {
643             res = gst_video_rate_flush_prev (videorate, count > 0);
644             count++;
645           }
646         } else {
647           res = gst_video_rate_flush_prev (videorate, FALSE);
648           count = 1;
649         }
650       }
651
652       if (count > 1) {
653         videorate->dup += count - 1;
654         if (!videorate->silent)
655           gst_video_rate_notify_duplicate (videorate);
656       } else if (count == 0) {
657         videorate->drop++;
658         if (!videorate->silent)
659           gst_video_rate_notify_drop (videorate);
660       }
661
662       break;
663     }
664     case GST_EVENT_FLUSH_STOP:
665       /* also resets the segment */
666       GST_DEBUG_OBJECT (videorate, "Got FLUSH_STOP");
667       gst_video_rate_reset (videorate);
668       break;
669     default:
670       break;
671   }
672
673   ret = gst_pad_push_event (videorate->srcpad, event);
674
675 done:
676   gst_object_unref (videorate);
677
678   return ret;
679
680   /* ERRORS */
681 format_error:
682   {
683     GST_WARNING_OBJECT (videorate,
684         "Got segment but doesn't have GST_FORMAT_TIME value");
685     gst_event_unref (event);
686     ret = FALSE;
687     goto done;
688   }
689 }
690
691 static gboolean
692 gst_video_rate_query (GstPad * pad, GstQuery * query)
693 {
694   GstVideoRate *videorate;
695   gboolean res = FALSE;
696
697   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
698
699   switch (GST_QUERY_TYPE (query)) {
700     case GST_QUERY_LATENCY:
701     {
702       GstClockTime min, max;
703       gboolean live;
704       guint64 latency;
705       GstPad *peer;
706
707       if ((peer = gst_pad_get_peer (videorate->sinkpad))) {
708         if ((res = gst_pad_query (peer, query))) {
709           gst_query_parse_latency (query, &live, &min, &max);
710
711           GST_DEBUG_OBJECT (videorate, "Peer latency: min %"
712               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
713               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
714
715           if (videorate->from_rate_numerator != 0) {
716             /* add latency. We don't really know since we hold on to the frames
717              * until we get a next frame, which can be anything. We assume
718              * however that this will take from_rate time. */
719             latency = gst_util_uint64_scale (GST_SECOND,
720                 videorate->from_rate_denominator,
721                 videorate->from_rate_numerator);
722           } else {
723             /* no input framerate, we don't know */
724             latency = 0;
725           }
726
727           GST_DEBUG_OBJECT (videorate, "Our latency: %"
728               GST_TIME_FORMAT, GST_TIME_ARGS (latency));
729
730           min += latency;
731           if (max != -1)
732             max += latency;
733
734           GST_DEBUG_OBJECT (videorate, "Calculated total latency : min %"
735               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
736               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
737
738           gst_query_set_latency (query, live, min, max);
739         }
740         gst_object_unref (peer);
741       }
742       break;
743     }
744     default:
745       res = gst_pad_query_default (pad, query);
746       break;
747   }
748   gst_object_unref (videorate);
749
750   return res;
751 }
752
753 static GstFlowReturn
754 gst_video_rate_chain (GstPad * pad, GstBuffer * buffer)
755 {
756   GstVideoRate *videorate;
757   GstFlowReturn res = GST_FLOW_OK;
758   GstClockTime intime, in_ts, in_dur;
759
760   videorate = GST_VIDEO_RATE (GST_PAD_PARENT (pad));
761
762   /* make sure the denominators are not 0 */
763   if (videorate->from_rate_denominator == 0 ||
764       videorate->to_rate_denominator == 0)
765     goto not_negotiated;
766
767   in_ts = GST_BUFFER_TIMESTAMP (buffer);
768   in_dur = GST_BUFFER_DURATION (buffer);
769
770   if (G_UNLIKELY (in_ts == GST_CLOCK_TIME_NONE)) {
771     in_ts = videorate->last_ts;
772     if (G_UNLIKELY (in_ts == GST_CLOCK_TIME_NONE))
773       goto invalid_buffer;
774   }
775
776   /* get the time of the next expected buffer timestamp, we use this when the
777    * next buffer has -1 as a timestamp */
778   videorate->last_ts = in_ts;
779   if (in_dur != GST_CLOCK_TIME_NONE)
780     videorate->last_ts += in_dur;
781
782   GST_DEBUG_OBJECT (videorate, "got buffer with timestamp %" GST_TIME_FORMAT,
783       GST_TIME_ARGS (in_ts));
784
785   /* the input time is the time in the segment + all previously accumulated
786    * segments */
787   intime = in_ts + videorate->segment.accum;
788
789   /* we need to have two buffers to compare */
790   if (videorate->prevbuf == NULL) {
791     gst_video_rate_swap_prev (videorate, buffer, intime);
792     videorate->in++;
793     if (!GST_CLOCK_TIME_IS_VALID (videorate->next_ts)) {
794       /* new buffer, we expect to output a buffer that matches the first
795        * timestamp in the segment */
796       if (videorate->skip_to_first) {
797         videorate->next_ts = intime;
798         videorate->base_ts = in_ts - videorate->segment.start;
799         videorate->out_frame_count = 0;
800       } else {
801         videorate->next_ts =
802             videorate->segment.start + videorate->segment.accum;
803       }
804     }
805   } else {
806     GstClockTime prevtime;
807     gint count = 0;
808     gint64 diff1, diff2;
809
810     prevtime = videorate->prev_ts;
811
812     GST_LOG_OBJECT (videorate,
813         "BEGINNING prev buf %" GST_TIME_FORMAT " new buf %" GST_TIME_FORMAT
814         " outgoing ts %" GST_TIME_FORMAT, GST_TIME_ARGS (prevtime),
815         GST_TIME_ARGS (intime), GST_TIME_ARGS (videorate->next_ts));
816
817     videorate->in++;
818
819     /* drop new buffer if it's before previous one */
820     if (intime < prevtime) {
821       GST_DEBUG_OBJECT (videorate,
822           "The new buffer (%" GST_TIME_FORMAT
823           ") is before the previous buffer (%"
824           GST_TIME_FORMAT "). Dropping new buffer.",
825           GST_TIME_ARGS (intime), GST_TIME_ARGS (prevtime));
826       videorate->drop++;
827       if (!videorate->silent)
828         gst_video_rate_notify_drop (videorate);
829       gst_buffer_unref (buffer);
830       goto done;
831     }
832
833     /* got 2 buffers, see which one is the best */
834     do {
835
836       diff1 = prevtime - videorate->next_ts;
837       diff2 = intime - videorate->next_ts;
838
839       /* take absolute values, beware: abs and ABS don't work for gint64 */
840       if (diff1 < 0)
841         diff1 = -diff1;
842       if (diff2 < 0)
843         diff2 = -diff2;
844
845       GST_LOG_OBJECT (videorate,
846           "diff with prev %" GST_TIME_FORMAT " diff with new %"
847           GST_TIME_FORMAT " outgoing ts %" GST_TIME_FORMAT,
848           GST_TIME_ARGS (diff1), GST_TIME_ARGS (diff2),
849           GST_TIME_ARGS (videorate->next_ts));
850
851       /* output first one when its the best */
852       if (diff1 <= diff2) {
853         count++;
854
855         /* on error the _flush function posted a warning already */
856         if ((res =
857                 gst_video_rate_flush_prev (videorate,
858                     count > 1)) != GST_FLOW_OK) {
859           gst_buffer_unref (buffer);
860           goto done;
861         }
862       }
863       /* continue while the first one was the best, if they were equal avoid
864        * going into an infinite loop */
865     }
866     while (diff1 < diff2);
867
868     /* if we outputed the first buffer more then once, we have dups */
869     if (count > 1) {
870       videorate->dup += count - 1;
871       if (!videorate->silent)
872         gst_video_rate_notify_duplicate (videorate);
873     }
874     /* if we didn't output the first buffer, we have a drop */
875     else if (count == 0) {
876       videorate->drop++;
877
878       if (!videorate->silent)
879         gst_video_rate_notify_drop (videorate);
880
881       GST_LOG_OBJECT (videorate,
882           "new is best, old never used, drop, outgoing ts %"
883           GST_TIME_FORMAT, GST_TIME_ARGS (videorate->next_ts));
884     }
885     GST_LOG_OBJECT (videorate,
886         "END, putting new in old, diff1 %" GST_TIME_FORMAT
887         ", diff2 %" GST_TIME_FORMAT ", next_ts %" GST_TIME_FORMAT
888         ", in %" G_GUINT64_FORMAT ", out %" G_GUINT64_FORMAT ", drop %"
889         G_GUINT64_FORMAT ", dup %" G_GUINT64_FORMAT, GST_TIME_ARGS (diff1),
890         GST_TIME_ARGS (diff2), GST_TIME_ARGS (videorate->next_ts),
891         videorate->in, videorate->out, videorate->drop, videorate->dup);
892
893     /* swap in new one when it's the best */
894     gst_video_rate_swap_prev (videorate, buffer, intime);
895   }
896 done:
897   return res;
898
899   /* ERRORS */
900 not_negotiated:
901   {
902     GST_WARNING_OBJECT (videorate, "no framerate negotiated");
903     gst_buffer_unref (buffer);
904     res = GST_FLOW_NOT_NEGOTIATED;
905     goto done;
906   }
907
908 invalid_buffer:
909   {
910     GST_WARNING_OBJECT (videorate,
911         "Got buffer with GST_CLOCK_TIME_NONE timestamp, discarding it");
912     gst_buffer_unref (buffer);
913     goto done;
914   }
915 }
916
917 static void
918 gst_video_rate_set_property (GObject * object,
919     guint prop_id, const GValue * value, GParamSpec * pspec)
920 {
921   GstVideoRate *videorate = GST_VIDEO_RATE (object);
922
923   switch (prop_id) {
924     case ARG_SILENT:
925       videorate->silent = g_value_get_boolean (value);
926       break;
927     case ARG_NEW_PREF:
928       videorate->new_pref = g_value_get_double (value);
929       break;
930     case ARG_SKIP_TO_FIRST:
931       videorate->skip_to_first = g_value_get_boolean (value);
932       break;
933     default:
934       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
935       break;
936   }
937 }
938
939 static void
940 gst_video_rate_get_property (GObject * object,
941     guint prop_id, GValue * value, GParamSpec * pspec)
942 {
943   GstVideoRate *videorate = GST_VIDEO_RATE (object);
944
945   switch (prop_id) {
946     case ARG_IN:
947       g_value_set_uint64 (value, videorate->in);
948       break;
949     case ARG_OUT:
950       g_value_set_uint64 (value, videorate->out);
951       break;
952     case ARG_DUP:
953       g_value_set_uint64 (value, videorate->dup);
954       break;
955     case ARG_DROP:
956       g_value_set_uint64 (value, videorate->drop);
957       break;
958     case ARG_SILENT:
959       g_value_set_boolean (value, videorate->silent);
960       break;
961     case ARG_NEW_PREF:
962       g_value_set_double (value, videorate->new_pref);
963       break;
964     case ARG_SKIP_TO_FIRST:
965       g_value_set_boolean (value, videorate->skip_to_first);
966       break;
967     default:
968       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
969       break;
970   }
971 }
972
973 static GstStateChangeReturn
974 gst_video_rate_change_state (GstElement * element, GstStateChange transition)
975 {
976   GstStateChangeReturn ret;
977   GstVideoRate *videorate;
978
979   videorate = GST_VIDEO_RATE (element);
980
981   switch (transition) {
982     case GST_STATE_CHANGE_READY_TO_PAUSED:
983       videorate->discont = TRUE;
984       videorate->last_ts = -1;
985       break;
986     default:
987       break;
988   }
989
990   ret = parent_class->change_state (element, transition);
991
992   switch (transition) {
993     case GST_STATE_CHANGE_PAUSED_TO_READY:
994       gst_video_rate_reset (videorate);
995       break;
996     default:
997       break;
998   }
999
1000   return ret;
1001 }
1002
1003 static gboolean
1004 plugin_init (GstPlugin * plugin)
1005 {
1006   GST_DEBUG_CATEGORY_INIT (video_rate_debug, "videorate", 0,
1007       "VideoRate stream fixer");
1008
1009   return gst_element_register (plugin, "videorate", GST_RANK_NONE,
1010       GST_TYPE_VIDEO_RATE);
1011 }
1012
1013 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1014     GST_VERSION_MINOR,
1015     "videorate",
1016     "Adjusts video frames",
1017     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)