videorate: trucate own caps, instead of copying and using the first only
[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 GST_BOILERPLATE (GstVideoRate, gst_video_rate, GstElement, GST_TYPE_ELEMENT);
136
137 static void
138 gst_video_rate_base_init (gpointer g_class)
139 {
140   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
141
142   gst_element_class_set_details_simple (element_class,
143       "Video rate adjuster", "Filter/Effect/Video",
144       "Drops/duplicates/adjusts timestamps on video frames to make a perfect stream",
145       "Wim Taymans <wim@fluendo.com>");
146
147   gst_element_class_add_pad_template (element_class,
148       gst_static_pad_template_get (&gst_video_rate_sink_template));
149   gst_element_class_add_pad_template (element_class,
150       gst_static_pad_template_get (&gst_video_rate_src_template));
151 }
152
153 static void
154 gst_video_rate_class_init (GstVideoRateClass * klass)
155 {
156   GObjectClass *object_class = G_OBJECT_CLASS (klass);
157   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
158
159   parent_class = g_type_class_peek_parent (klass);
160
161   object_class->set_property = gst_video_rate_set_property;
162   object_class->get_property = gst_video_rate_get_property;
163
164   g_object_class_install_property (object_class, ARG_IN,
165       g_param_spec_uint64 ("in", "In",
166           "Number of input frames", 0, G_MAXUINT64, 0,
167           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
168   g_object_class_install_property (object_class, ARG_OUT,
169       g_param_spec_uint64 ("out", "Out", "Number of output frames", 0,
170           G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
171   g_object_class_install_property (object_class, ARG_DUP,
172       g_param_spec_uint64 ("duplicate", "Duplicate",
173           "Number of duplicated frames", 0, G_MAXUINT64, 0,
174           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
175   g_object_class_install_property (object_class, ARG_DROP,
176       g_param_spec_uint64 ("drop", "Drop", "Number of dropped frames", 0,
177           G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
178   g_object_class_install_property (object_class, ARG_SILENT,
179       g_param_spec_boolean ("silent", "silent",
180           "Don't emit notify for dropped and duplicated frames", DEFAULT_SILENT,
181           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
182   g_object_class_install_property (object_class, ARG_NEW_PREF,
183       g_param_spec_double ("new-pref", "New Pref",
184           "Value indicating how much to prefer new frames (unused)", 0.0, 1.0,
185           DEFAULT_NEW_PREF, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
186
187   /**
188    * GstVideoRate:skip-to-first:
189    * 
190    * Don't produce buffers before the first one we receive.
191    *
192    * Since: 0.10.25
193    */
194   g_object_class_install_property (object_class, ARG_SKIP_TO_FIRST,
195       g_param_spec_boolean ("skip-to-first", "Skip to first buffer",
196           "Don't produce buffers before the first one we receive",
197           DEFAULT_SKIP_TO_FIRST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
198
199   element_class->change_state = gst_video_rate_change_state;
200 }
201
202 /* return the caps that can be used on out_pad given in_caps on in_pad */
203 static gboolean
204 gst_video_rate_transformcaps (GstPad * in_pad, GstCaps * in_caps,
205     GstPad * out_pad, GstCaps ** out_caps)
206 {
207   GstCaps *intersect;
208   const GstCaps *in_templ;
209   gint i;
210   GSList *extra_structures = NULL;
211   GSList *iter;
212
213   in_templ = gst_pad_get_pad_template_caps (in_pad);
214   intersect = gst_caps_intersect (in_caps, in_templ);
215
216   /* all possible framerates are allowed */
217   for (i = 0; i < gst_caps_get_size (intersect); i++) {
218     GstStructure *structure;
219
220     structure = gst_caps_get_structure (intersect, i);
221
222     if (gst_structure_has_field (structure, "framerate")) {
223       GstStructure *copy_structure;
224
225       copy_structure = gst_structure_copy (structure);
226       gst_structure_set (copy_structure,
227           "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
228       extra_structures = g_slist_append (extra_structures, copy_structure);
229     }
230   }
231
232   /* append the extra structures */
233   for (iter = extra_structures; iter != NULL; iter = g_slist_next (iter)) {
234     gst_caps_append_structure (intersect, (GstStructure *) iter->data);
235   }
236   g_slist_free (extra_structures);
237
238   *out_caps = intersect;
239
240   return TRUE;
241 }
242
243 static GstCaps *
244 gst_video_rate_getcaps (GstPad * pad)
245 {
246   GstVideoRate *videorate;
247   GstPad *otherpad;
248   GstCaps *caps;
249
250   videorate = GST_VIDEO_RATE (GST_PAD_PARENT (pad));
251
252   otherpad = (pad == videorate->srcpad) ? videorate->sinkpad :
253       videorate->srcpad;
254
255   /* we can do what the peer can */
256   caps = gst_pad_peer_get_caps (otherpad);
257   if (caps) {
258     GstCaps *transform;
259
260     gst_video_rate_transformcaps (otherpad, caps, pad, &transform);
261     gst_caps_unref (caps);
262     caps = transform;
263   } else {
264     /* no peer, our padtemplate is enough then */
265     caps = gst_caps_copy (gst_pad_get_pad_template_caps (pad));
266   }
267
268   return caps;
269 }
270
271 static gboolean
272 gst_video_rate_setcaps (GstPad * pad, GstCaps * caps)
273 {
274   GstVideoRate *videorate;
275   GstStructure *structure;
276   gboolean ret = TRUE;
277   GstPad *otherpad, *opeer;
278   gint rate_numerator, rate_denominator;
279
280   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
281
282   GST_DEBUG ("setcaps called %" GST_PTR_FORMAT, caps);
283
284   structure = gst_caps_get_structure (caps, 0);
285   if (!gst_structure_get_fraction (structure, "framerate",
286           &rate_numerator, &rate_denominator))
287     goto no_framerate;
288
289   if (pad == videorate->srcpad) {
290     videorate->to_rate_numerator = rate_numerator;
291     videorate->to_rate_denominator = rate_denominator;
292     otherpad = videorate->sinkpad;
293   } else {
294     videorate->from_rate_numerator = rate_numerator;
295     videorate->from_rate_denominator = rate_denominator;
296     otherpad = videorate->srcpad;
297   }
298
299   /* now try to find something for the peer */
300   opeer = gst_pad_get_peer (otherpad);
301   if (opeer) {
302     if (gst_pad_accept_caps (opeer, caps)) {
303       /* the peer accepts the caps as they are */
304       gst_pad_set_caps (otherpad, caps);
305
306       ret = TRUE;
307     } else {
308       GstCaps *peercaps;
309       GstCaps *transform = NULL;
310
311       ret = FALSE;
312
313       /* see how we can transform the input caps */
314       if (!gst_video_rate_transformcaps (pad, caps, otherpad, &transform))
315         goto no_transform;
316
317       /* see what the peer can do */
318       peercaps = gst_pad_get_caps (opeer);
319
320       GST_DEBUG ("icaps %" GST_PTR_FORMAT, peercaps);
321       GST_DEBUG ("transform %" GST_PTR_FORMAT, transform);
322
323       /* filter against our possibilities */
324       caps = gst_caps_intersect (peercaps, transform);
325       gst_caps_unref (peercaps);
326       gst_caps_unref (transform);
327
328       GST_DEBUG ("intersect %" GST_PTR_FORMAT, caps);
329
330       /* take first possibility */
331       gst_caps_truncate (caps);
332       structure = gst_caps_get_structure (caps, 0);
333
334       /* and fixate */
335       gst_structure_fixate_field_nearest_fraction (structure, "framerate",
336           rate_numerator, rate_denominator);
337
338       gst_structure_get_fraction (structure, "framerate",
339           &rate_numerator, &rate_denominator);
340
341       if (otherpad == videorate->srcpad) {
342         videorate->to_rate_numerator = rate_numerator;
343         videorate->to_rate_denominator = rate_denominator;
344       } else {
345         videorate->from_rate_numerator = rate_numerator;
346         videorate->from_rate_denominator = rate_denominator;
347       }
348       gst_pad_set_caps (otherpad, caps);
349       gst_caps_unref (caps);
350       ret = TRUE;
351     }
352     gst_object_unref (opeer);
353   }
354 done:
355   /* After a setcaps, our caps may have changed. In that case, we can't use
356    * the old buffer, if there was one (it might have different dimensions) */
357   GST_DEBUG ("swapping old buffers");
358   gst_video_rate_swap_prev (videorate, NULL, GST_CLOCK_TIME_NONE);
359
360   gst_object_unref (videorate);
361   return ret;
362
363 no_framerate:
364   {
365     GST_DEBUG_OBJECT (videorate, "no framerate specified");
366     goto done;
367   }
368 no_transform:
369   {
370     GST_DEBUG_OBJECT (videorate, "no framerate transform possible");
371     ret = FALSE;
372     goto done;
373   }
374 }
375
376 static void
377 gst_video_rate_reset (GstVideoRate * videorate)
378 {
379   GST_DEBUG ("resetting internal variables");
380
381   videorate->in = 0;
382   videorate->out = 0;
383   videorate->segment_out = 0;
384   videorate->drop = 0;
385   videorate->dup = 0;
386   videorate->next_ts = GST_CLOCK_TIME_NONE;
387   videorate->last_ts = GST_CLOCK_TIME_NONE;
388   videorate->discont = TRUE;
389   gst_video_rate_swap_prev (videorate, NULL, 0);
390
391   gst_segment_init (&videorate->segment, GST_FORMAT_TIME);
392 }
393
394 static void
395 gst_video_rate_init (GstVideoRate * videorate, GstVideoRateClass * klass)
396 {
397   GST_DEBUG ("gst_video_rate_init");
398   videorate->sinkpad =
399       gst_pad_new_from_static_template (&gst_video_rate_sink_template, "sink");
400   gst_pad_set_event_function (videorate->sinkpad, gst_video_rate_event);
401   gst_pad_set_chain_function (videorate->sinkpad, gst_video_rate_chain);
402   gst_pad_set_getcaps_function (videorate->sinkpad, gst_video_rate_getcaps);
403   gst_pad_set_setcaps_function (videorate->sinkpad, gst_video_rate_setcaps);
404   gst_element_add_pad (GST_ELEMENT (videorate), videorate->sinkpad);
405
406   videorate->srcpad =
407       gst_pad_new_from_static_template (&gst_video_rate_src_template, "src");
408   gst_pad_set_query_function (videorate->srcpad, gst_video_rate_query);
409   gst_pad_set_getcaps_function (videorate->srcpad, gst_video_rate_getcaps);
410   gst_pad_set_setcaps_function (videorate->srcpad, gst_video_rate_setcaps);
411   gst_element_add_pad (GST_ELEMENT (videorate), videorate->srcpad);
412
413   gst_video_rate_reset (videorate);
414   videorate->silent = DEFAULT_SILENT;
415   videorate->new_pref = DEFAULT_NEW_PREF;
416
417   videorate->from_rate_numerator = 0;
418   videorate->from_rate_denominator = 0;
419   videorate->to_rate_numerator = 0;
420   videorate->to_rate_denominator = 0;
421 }
422
423 /* flush the oldest buffer */
424 static GstFlowReturn
425 gst_video_rate_flush_prev (GstVideoRate * videorate)
426 {
427   GstFlowReturn res;
428   GstBuffer *outbuf;
429   GstClockTime push_ts;
430
431   if (!videorate->prevbuf)
432     goto eos_before_buffers;
433
434   /* make sure we can write to the metadata */
435   outbuf = gst_buffer_make_metadata_writable
436       (gst_buffer_ref (videorate->prevbuf));
437
438   GST_BUFFER_OFFSET (outbuf) = videorate->out;
439   GST_BUFFER_OFFSET_END (outbuf) = videorate->out + 1;
440
441   if (videorate->discont) {
442     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
443     videorate->discont = FALSE;
444   } else
445     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DISCONT);
446
447   /* this is the timestamp we put on the buffer */
448   push_ts = videorate->next_ts;
449
450   videorate->out++;
451   videorate->segment_out++;
452   if (videorate->to_rate_numerator) {
453     /* interpolate next expected timestamp in the segment */
454     videorate->next_ts = videorate->segment.accum + videorate->segment.start +
455         gst_util_uint64_scale (videorate->segment_out,
456         videorate->to_rate_denominator * GST_SECOND,
457         videorate->to_rate_numerator);
458     GST_BUFFER_DURATION (outbuf) = videorate->next_ts - push_ts;
459   }
460
461   /* adapt for looping, bring back to time in current segment. */
462   GST_BUFFER_TIMESTAMP (outbuf) = push_ts - videorate->segment.accum;
463
464   gst_buffer_set_caps (outbuf, GST_PAD_CAPS (videorate->srcpad));
465
466   GST_LOG_OBJECT (videorate,
467       "old is best, dup, pushing buffer outgoing ts %" GST_TIME_FORMAT,
468       GST_TIME_ARGS (push_ts));
469
470   res = gst_pad_push (videorate->srcpad, outbuf);
471
472   return res;
473
474   /* WARNINGS */
475 eos_before_buffers:
476   {
477     GST_INFO_OBJECT (videorate, "got EOS before any buffer was received");
478     return GST_FLOW_OK;
479   }
480 }
481
482 static void
483 gst_video_rate_swap_prev (GstVideoRate * videorate, GstBuffer * buffer,
484     gint64 time)
485 {
486   GST_LOG_OBJECT (videorate, "swap_prev: storing buffer %p in prev", buffer);
487   if (videorate->prevbuf)
488     gst_buffer_unref (videorate->prevbuf);
489   videorate->prevbuf = buffer;
490   videorate->prev_ts = time;
491 }
492
493 #define MAGIC_LIMIT  25
494 static gboolean
495 gst_video_rate_event (GstPad * pad, GstEvent * event)
496 {
497   GstVideoRate *videorate;
498   gboolean ret;
499
500   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
501
502   switch (GST_EVENT_TYPE (event)) {
503     case GST_EVENT_NEWSEGMENT:
504     {
505       gint64 start, stop, time;
506       gdouble rate, arate;
507       gboolean update;
508       GstFormat format;
509
510       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
511           &start, &stop, &time);
512
513       if (format != GST_FORMAT_TIME)
514         goto format_error;
515
516       GST_DEBUG_OBJECT (videorate, "handle NEWSEGMENT");
517
518       /* close up the previous segment, if appropriate */
519       if (!update && videorate->prevbuf) {
520         gint count = 0;
521         GstFlowReturn res;
522
523         res = GST_FLOW_OK;
524         /* fill up to the end of current segment,
525          * or only send out the stored buffer if there is no specific stop.
526          * regardless, prevent going loopy in strange cases */
527         while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
528             ((GST_CLOCK_TIME_IS_VALID (videorate->segment.stop) &&
529                     videorate->next_ts - videorate->segment.accum
530                     < videorate->segment.stop)
531                 || count < 1)) {
532           gst_video_rate_flush_prev (videorate);
533           count++;
534         }
535         if (count > 1) {
536           videorate->dup += count - 1;
537           if (!videorate->silent)
538             g_object_notify (G_OBJECT (videorate), "duplicate");
539         } else if (count == 0) {
540           videorate->drop++;
541           if (!videorate->silent)
542             g_object_notify (G_OBJECT (videorate), "drop");
543         }
544         /* clean up for the new one; _chain will resume from the new start */
545         videorate->segment_out = 0;
546         gst_video_rate_swap_prev (videorate, NULL, 0);
547         videorate->next_ts = GST_CLOCK_TIME_NONE;
548       }
549
550       /* We just want to update the accumulated stream_time  */
551       gst_segment_set_newsegment_full (&videorate->segment, update, rate, arate,
552           format, start, stop, time);
553
554       GST_DEBUG_OBJECT (videorate, "updated segment: %" GST_SEGMENT_FORMAT,
555           &videorate->segment);
556       break;
557     }
558     case GST_EVENT_EOS:
559       /* flush last queued frame */
560       GST_DEBUG_OBJECT (videorate, "Got EOS");
561       gst_video_rate_flush_prev (videorate);
562       break;
563     case GST_EVENT_FLUSH_STOP:
564       /* also resets the segment */
565       GST_DEBUG_OBJECT (videorate, "Got FLUSH_STOP");
566       gst_video_rate_reset (videorate);
567       break;
568     default:
569       break;
570   }
571
572   ret = gst_pad_push_event (videorate->srcpad, event);
573
574 done:
575   gst_object_unref (videorate);
576
577   return ret;
578
579   /* ERRORS */
580 format_error:
581   {
582     GST_WARNING_OBJECT (videorate,
583         "Got segment but doesn't have GST_FORMAT_TIME value");
584     gst_event_unref (event);
585     ret = FALSE;
586     goto done;
587   }
588 }
589
590 static gboolean
591 gst_video_rate_query (GstPad * pad, GstQuery * query)
592 {
593   GstVideoRate *videorate;
594   gboolean res = FALSE;
595
596   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
597
598   switch (GST_QUERY_TYPE (query)) {
599     case GST_QUERY_LATENCY:
600     {
601       GstClockTime min, max;
602       gboolean live;
603       guint64 latency;
604       GstPad *peer;
605
606       if ((peer = gst_pad_get_peer (videorate->sinkpad))) {
607         if ((res = gst_pad_query (peer, query))) {
608           gst_query_parse_latency (query, &live, &min, &max);
609
610           GST_DEBUG_OBJECT (videorate, "Peer latency: min %"
611               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
612               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
613
614           if (videorate->from_rate_numerator != 0) {
615             /* add latency. We don't really know since we hold on to the frames
616              * until we get a next frame, which can be anything. We assume
617              * however that this will take from_rate time. */
618             latency = gst_util_uint64_scale (GST_SECOND,
619                 videorate->from_rate_denominator,
620                 videorate->from_rate_numerator);
621           } else {
622             /* no input framerate, we don't know */
623             latency = 0;
624           }
625
626           GST_DEBUG_OBJECT (videorate, "Our latency: %"
627               GST_TIME_FORMAT, GST_TIME_ARGS (latency));
628
629           min += latency;
630           if (max != -1)
631             max += latency;
632
633           GST_DEBUG_OBJECT (videorate, "Calculated total latency : min %"
634               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
635               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
636
637           gst_query_set_latency (query, live, min, max);
638         }
639         gst_object_unref (peer);
640       }
641       break;
642     }
643     default:
644       res = gst_pad_query_default (pad, query);
645       break;
646   }
647   gst_object_unref (videorate);
648
649   return res;
650 }
651
652 static GstFlowReturn
653 gst_video_rate_chain (GstPad * pad, GstBuffer * buffer)
654 {
655   GstVideoRate *videorate;
656   GstFlowReturn res = GST_FLOW_OK;
657   GstClockTime intime, in_ts, in_dur;
658
659   videorate = GST_VIDEO_RATE (GST_PAD_PARENT (pad));
660
661   /* make sure the denominators are not 0 */
662   if (videorate->from_rate_denominator == 0 ||
663       videorate->to_rate_denominator == 0)
664     goto not_negotiated;
665
666   in_ts = GST_BUFFER_TIMESTAMP (buffer);
667   in_dur = GST_BUFFER_DURATION (buffer);
668
669   if (G_UNLIKELY (in_ts == GST_CLOCK_TIME_NONE)) {
670     in_ts = videorate->last_ts;
671     if (G_UNLIKELY (in_ts == GST_CLOCK_TIME_NONE))
672       goto invalid_buffer;
673   }
674
675   /* get the time of the next expected buffer timestamp, we use this when the
676    * next buffer has -1 as a timestamp */
677   videorate->last_ts = in_ts;
678   if (in_dur != GST_CLOCK_TIME_NONE)
679     videorate->last_ts += in_dur;
680
681   GST_DEBUG_OBJECT (videorate, "got buffer with timestamp %" GST_TIME_FORMAT,
682       GST_TIME_ARGS (in_ts));
683
684   /* the input time is the time in the segment + all previously accumulated
685    * segments */
686   intime = in_ts + videorate->segment.accum;
687
688   /* we need to have two buffers to compare */
689   if (videorate->prevbuf == NULL) {
690     gst_video_rate_swap_prev (videorate, buffer, intime);
691     videorate->in++;
692     if (!GST_CLOCK_TIME_IS_VALID (videorate->next_ts)) {
693       /* new buffer, we expect to output a buffer that matches the first
694        * timestamp in the segment */
695       if (videorate->skip_to_first) {
696         videorate->next_ts = in_ts;
697         videorate->segment_out = gst_util_uint64_scale (in_ts,
698             videorate->to_rate_numerator,
699             videorate->to_rate_denominator * GST_SECOND) -
700             (videorate->segment.accum + videorate->segment.start);
701       } else {
702         videorate->next_ts =
703             videorate->segment.start + videorate->segment.accum;
704       }
705     }
706   } else {
707     GstClockTime prevtime;
708     gint count = 0;
709     gint64 diff1, diff2;
710
711     prevtime = videorate->prev_ts;
712
713     GST_LOG_OBJECT (videorate,
714         "BEGINNING prev buf %" GST_TIME_FORMAT " new buf %" GST_TIME_FORMAT
715         " outgoing ts %" GST_TIME_FORMAT, GST_TIME_ARGS (prevtime),
716         GST_TIME_ARGS (intime), GST_TIME_ARGS (videorate->next_ts));
717
718     videorate->in++;
719
720     /* drop new buffer if it's before previous one */
721     if (intime < prevtime) {
722       GST_DEBUG_OBJECT (videorate,
723           "The new buffer (%" GST_TIME_FORMAT
724           ") is before the previous buffer (%"
725           GST_TIME_FORMAT "). Dropping new buffer.",
726           GST_TIME_ARGS (intime), GST_TIME_ARGS (prevtime));
727       videorate->drop++;
728       if (!videorate->silent)
729         g_object_notify (G_OBJECT (videorate), "drop");
730       gst_buffer_unref (buffer);
731       goto done;
732     }
733
734     /* got 2 buffers, see which one is the best */
735     do {
736
737       diff1 = prevtime - videorate->next_ts;
738       diff2 = intime - videorate->next_ts;
739
740       /* take absolute values, beware: abs and ABS don't work for gint64 */
741       if (diff1 < 0)
742         diff1 = -diff1;
743       if (diff2 < 0)
744         diff2 = -diff2;
745
746       GST_LOG_OBJECT (videorate,
747           "diff with prev %" GST_TIME_FORMAT " diff with new %"
748           GST_TIME_FORMAT " outgoing ts %" GST_TIME_FORMAT,
749           GST_TIME_ARGS (diff1), GST_TIME_ARGS (diff2),
750           GST_TIME_ARGS (videorate->next_ts));
751
752       /* output first one when its the best */
753       if (diff1 <= diff2) {
754         count++;
755
756         /* on error the _flush function posted a warning already */
757         if ((res = gst_video_rate_flush_prev (videorate)) != GST_FLOW_OK) {
758           gst_buffer_unref (buffer);
759           goto done;
760         }
761       }
762       /* continue while the first one was the best, if they were equal avoid
763        * going into an infinite loop */
764     }
765     while (diff1 < diff2);
766
767     /* if we outputed the first buffer more then once, we have dups */
768     if (count > 1) {
769       videorate->dup += count - 1;
770       if (!videorate->silent)
771         g_object_notify (G_OBJECT (videorate), "duplicate");
772     }
773     /* if we didn't output the first buffer, we have a drop */
774     else if (count == 0) {
775       videorate->drop++;
776
777       if (!videorate->silent)
778         g_object_notify (G_OBJECT (videorate), "drop");
779
780       GST_LOG_OBJECT (videorate,
781           "new is best, old never used, drop, outgoing ts %"
782           GST_TIME_FORMAT, GST_TIME_ARGS (videorate->next_ts));
783     }
784     GST_LOG_OBJECT (videorate,
785         "END, putting new in old, diff1 %" GST_TIME_FORMAT
786         ", diff2 %" GST_TIME_FORMAT ", next_ts %" GST_TIME_FORMAT
787         ", in %" G_GUINT64_FORMAT ", out %" G_GUINT64_FORMAT ", drop %"
788         G_GUINT64_FORMAT ", dup %" G_GUINT64_FORMAT, GST_TIME_ARGS (diff1),
789         GST_TIME_ARGS (diff2), GST_TIME_ARGS (videorate->next_ts),
790         videorate->in, videorate->out, videorate->drop, videorate->dup);
791
792     /* swap in new one when it's the best */
793     gst_video_rate_swap_prev (videorate, buffer, intime);
794   }
795 done:
796   return res;
797
798   /* ERRORS */
799 not_negotiated:
800   {
801     GST_WARNING_OBJECT (videorate, "no framerate negotiated");
802     gst_buffer_unref (buffer);
803     res = GST_FLOW_NOT_NEGOTIATED;
804     goto done;
805   }
806
807 invalid_buffer:
808   {
809     GST_WARNING_OBJECT (videorate,
810         "Got buffer with GST_CLOCK_TIME_NONE timestamp, discarding it");
811     gst_buffer_unref (buffer);
812     goto done;
813   }
814 }
815
816 static void
817 gst_video_rate_set_property (GObject * object,
818     guint prop_id, const GValue * value, GParamSpec * pspec)
819 {
820   GstVideoRate *videorate = GST_VIDEO_RATE (object);
821
822   switch (prop_id) {
823     case ARG_SILENT:
824       videorate->silent = g_value_get_boolean (value);
825       break;
826     case ARG_NEW_PREF:
827       videorate->new_pref = g_value_get_double (value);
828       break;
829     case ARG_SKIP_TO_FIRST:
830       videorate->skip_to_first = g_value_get_boolean (value);
831       break;
832     default:
833       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
834       break;
835   }
836 }
837
838 static void
839 gst_video_rate_get_property (GObject * object,
840     guint prop_id, GValue * value, GParamSpec * pspec)
841 {
842   GstVideoRate *videorate = GST_VIDEO_RATE (object);
843
844   switch (prop_id) {
845     case ARG_IN:
846       g_value_set_uint64 (value, videorate->in);
847       break;
848     case ARG_OUT:
849       g_value_set_uint64 (value, videorate->out);
850       break;
851     case ARG_DUP:
852       g_value_set_uint64 (value, videorate->dup);
853       break;
854     case ARG_DROP:
855       g_value_set_uint64 (value, videorate->drop);
856       break;
857     case ARG_SILENT:
858       g_value_set_boolean (value, videorate->silent);
859       break;
860     case ARG_NEW_PREF:
861       g_value_set_double (value, videorate->new_pref);
862       break;
863     case ARG_SKIP_TO_FIRST:
864       g_value_set_boolean (value, videorate->skip_to_first);
865       break;
866     default:
867       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
868       break;
869   }
870 }
871
872 static GstStateChangeReturn
873 gst_video_rate_change_state (GstElement * element, GstStateChange transition)
874 {
875   GstStateChangeReturn ret;
876   GstVideoRate *videorate;
877
878   videorate = GST_VIDEO_RATE (element);
879
880   switch (transition) {
881     case GST_STATE_CHANGE_READY_TO_PAUSED:
882       videorate->discont = TRUE;
883       videorate->last_ts = -1;
884       break;
885     default:
886       break;
887   }
888
889   ret = parent_class->change_state (element, transition);
890
891   switch (transition) {
892     case GST_STATE_CHANGE_PAUSED_TO_READY:
893       gst_video_rate_reset (videorate);
894       break;
895     default:
896       break;
897   }
898
899   return ret;
900 }
901
902 static gboolean
903 plugin_init (GstPlugin * plugin)
904 {
905   GST_DEBUG_CATEGORY_INIT (video_rate_debug, "videorate", 0,
906       "VideoRate stream fixer");
907
908   return gst_element_register (plugin, "videorate", GST_RANK_NONE,
909       GST_TYPE_VIDEO_RATE);
910 }
911
912 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
913     GST_VERSION_MINOR,
914     "videorate",
915     "Adjusts video frames",
916     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)