3156c5fd269516b4552eba24f7d2523314513fe7
[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 v4l2src ! videorate ! video/x-raw-yuv,framerate=25/2 ! theoraenc ! oggmux ! filesink location=recording.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 #define DEFAULT_DROP_ONLY       FALSE
90 #define DEFAULT_AVERAGE_PERIOD  0
91
92 enum
93 {
94   ARG_0,
95   ARG_IN,
96   ARG_OUT,
97   ARG_DUP,
98   ARG_DROP,
99   ARG_SILENT,
100   ARG_NEW_PREF,
101   ARG_SKIP_TO_FIRST,
102   ARG_DROP_ONLY,
103   ARG_AVERAGE_PERIOD
104       /* FILL ME */
105 };
106
107 static GstStaticPadTemplate gst_video_rate_src_template =
108     GST_STATIC_PAD_TEMPLATE ("src",
109     GST_PAD_SRC,
110     GST_PAD_ALWAYS,
111     GST_STATIC_CAPS ("video/x-raw-yuv;"
112         "video/x-raw-rgb;" "video/x-raw-gray;" "image/jpeg;" "image/png")
113     );
114
115 static GstStaticPadTemplate gst_video_rate_sink_template =
116     GST_STATIC_PAD_TEMPLATE ("sink",
117     GST_PAD_SINK,
118     GST_PAD_ALWAYS,
119     GST_STATIC_CAPS ("video/x-raw-yuv;"
120         "video/x-raw-rgb;" "video/x-raw-gray;" "image/jpeg;" "image/png")
121     );
122
123 static void gst_video_rate_swap_prev (GstVideoRate * videorate,
124     GstBuffer * buffer, gint64 time);
125 static gboolean gst_video_rate_event (GstPad * pad, GstEvent * event);
126 static gboolean gst_video_rate_query (GstPad * pad, GstQuery * query);
127 static GstFlowReturn gst_video_rate_chain (GstPad * pad, GstBuffer * buffer);
128
129 static void gst_video_rate_set_property (GObject * object,
130     guint prop_id, const GValue * value, GParamSpec * pspec);
131 static void gst_video_rate_get_property (GObject * object,
132     guint prop_id, GValue * value, GParamSpec * pspec);
133
134 static GstStateChangeReturn gst_video_rate_change_state (GstElement * element,
135     GstStateChange transition);
136
137 /*static guint gst_video_rate_signals[LAST_SIGNAL] = { 0 }; */
138
139 static GParamSpec *pspec_drop = NULL;
140 static GParamSpec *pspec_duplicate = NULL;
141
142 #define gst_video_rate_parent_class parent_class
143 G_DEFINE_TYPE (GstVideoRate, gst_video_rate, GST_TYPE_ELEMENT);
144
145 static void
146 gst_video_rate_class_init (GstVideoRateClass * klass)
147 {
148   GObjectClass *object_class = G_OBJECT_CLASS (klass);
149   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
150
151   parent_class = g_type_class_peek_parent (klass);
152
153   object_class->set_property = gst_video_rate_set_property;
154   object_class->get_property = gst_video_rate_get_property;
155
156   g_object_class_install_property (object_class, ARG_IN,
157       g_param_spec_uint64 ("in", "In",
158           "Number of input frames", 0, G_MAXUINT64, 0,
159           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
160   g_object_class_install_property (object_class, ARG_OUT,
161       g_param_spec_uint64 ("out", "Out", "Number of output frames", 0,
162           G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
163   pspec_duplicate = g_param_spec_uint64 ("duplicate", "Duplicate",
164       "Number of duplicated frames", 0, G_MAXUINT64, 0,
165       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
166   g_object_class_install_property (object_class, ARG_DUP, pspec_duplicate);
167   pspec_drop = g_param_spec_uint64 ("drop", "Drop", "Number of dropped frames",
168       0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
169   g_object_class_install_property (object_class, ARG_DROP, pspec_drop);
170   g_object_class_install_property (object_class, ARG_SILENT,
171       g_param_spec_boolean ("silent", "silent",
172           "Don't emit notify for dropped and duplicated frames", DEFAULT_SILENT,
173           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
174   g_object_class_install_property (object_class, ARG_NEW_PREF,
175       g_param_spec_double ("new-pref", "New Pref",
176           "Value indicating how much to prefer new frames (unused)", 0.0, 1.0,
177           DEFAULT_NEW_PREF, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
178
179   /**
180    * GstVideoRate:skip-to-first:
181    * 
182    * Don't produce buffers before the first one we receive.
183    *
184    * Since: 0.10.25
185    */
186   g_object_class_install_property (object_class, ARG_SKIP_TO_FIRST,
187       g_param_spec_boolean ("skip-to-first", "Skip to first buffer",
188           "Don't produce buffers before the first one we receive",
189           DEFAULT_SKIP_TO_FIRST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
190
191   gst_element_class_set_details_simple (element_class,
192       "Video rate adjuster", "Filter/Effect/Video",
193       "Drops/duplicates/adjusts timestamps on video frames to make a perfect stream",
194       "Wim Taymans <wim@fluendo.com>");
195
196   gst_element_class_add_pad_template (element_class,
197       gst_static_pad_template_get (&gst_video_rate_sink_template));
198   gst_element_class_add_pad_template (element_class,
199       gst_static_pad_template_get (&gst_video_rate_src_template));
200
201   /**
202    * GstVideoRate:drop-only:
203    *
204    * Only drop frames, no duplicates are produced.
205    *
206    * Since: 0.10.34
207    */
208   g_object_class_install_property (object_class, ARG_DROP_ONLY,
209       g_param_spec_boolean ("drop-only", "Only Drop",
210           "Only drop frames, no duplicates are produced",
211           DEFAULT_DROP_ONLY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
212
213   /**
214    * GstVideoRate:average-period:
215    *
216    * Arrange for maximum framerate by dropping frames beyond a certain framerate,
217    * where the framerate is calculated using a moving average over the
218    * configured.
219    *
220    * Since: 0.10.34
221    */
222   g_object_class_install_property (object_class, ARG_AVERAGE_PERIOD,
223       g_param_spec_uint64 ("average-period", "Period over which to average",
224           "Period over which to average the framerate (in ns) (0 = disabled)",
225           0, G_MAXINT64, DEFAULT_AVERAGE_PERIOD,
226           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
227
228   element_class->change_state = GST_DEBUG_FUNCPTR (gst_video_rate_change_state);
229 }
230
231 /* return the caps that can be used on out_pad given in_caps on in_pad */
232 static gboolean
233 gst_video_rate_transformcaps (GstPad * in_pad, GstCaps * in_caps,
234     GstPad * out_pad, GstCaps ** out_caps, GstCaps * filter)
235 {
236   GstCaps *intersect, *in_templ;
237   gint i;
238   GSList *extra_structures = NULL;
239   GSList *iter;
240
241   in_templ = gst_pad_get_pad_template_caps (in_pad);
242   intersect =
243       gst_caps_intersect_full (in_caps, in_templ, GST_CAPS_INTERSECT_FIRST);
244   gst_caps_unref (in_templ);
245
246   /* all possible framerates are allowed */
247   for (i = 0; i < gst_caps_get_size (intersect); i++) {
248     GstStructure *structure;
249
250     structure = gst_caps_get_structure (intersect, i);
251
252     if (gst_structure_has_field (structure, "framerate")) {
253       GstStructure *copy_structure;
254
255       copy_structure = gst_structure_copy (structure);
256       gst_structure_set (copy_structure,
257           "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
258       extra_structures = g_slist_append (extra_structures, copy_structure);
259     }
260   }
261
262   /* append the extra structures */
263   for (iter = extra_structures; iter != NULL; iter = g_slist_next (iter)) {
264     gst_caps_append_structure (intersect, (GstStructure *) iter->data);
265   }
266   g_slist_free (extra_structures);
267
268   if (filter) {
269     GstCaps *tmp;
270
271     tmp = gst_caps_intersect_full (filter, intersect, GST_CAPS_INTERSECT_FIRST);
272     gst_caps_unref (intersect);
273     intersect = tmp;
274   }
275
276   *out_caps = intersect;
277
278   return TRUE;
279 }
280
281 static GstCaps *
282 gst_video_rate_getcaps (GstPad * pad, GstCaps * filter)
283 {
284   GstVideoRate *videorate;
285   GstPad *otherpad;
286   GstCaps *caps;
287
288   videorate = GST_VIDEO_RATE (GST_PAD_PARENT (pad));
289
290   otherpad = (pad == videorate->srcpad) ? videorate->sinkpad :
291       videorate->srcpad;
292
293   /* we can do what the peer can */
294   caps = gst_pad_peer_get_caps (otherpad, filter);
295   if (caps) {
296     GstCaps *transform, *intersect;
297
298     gst_video_rate_transformcaps (otherpad, caps, pad, &transform, filter);
299
300     /* Now prefer the downstream caps if possible */
301     intersect =
302         gst_caps_intersect_full (caps, transform, GST_CAPS_INTERSECT_FIRST);
303     if (!gst_caps_is_empty (intersect)) {
304       gst_caps_append (intersect, transform);
305       gst_caps_unref (caps);
306       caps = intersect;
307     } else {
308       gst_caps_unref (intersect);
309       caps = transform;
310     }
311   } else {
312     /* no peer, our padtemplate is enough then */
313     caps = gst_pad_get_pad_template_caps (pad);
314     if (filter) {
315       GstCaps *intersection;
316       intersection =
317           gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
318       gst_caps_unref (caps);
319       caps = intersection;
320     }
321   }
322
323   return caps;
324 }
325
326 static gboolean
327 gst_video_rate_set_src_caps (GstVideoRate * videorate, GstCaps * caps)
328 {
329   GstStructure *structure;
330   gint rate_numerator, rate_denominator;
331
332   GST_DEBUG_OBJECT (videorate, "src caps %" GST_PTR_FORMAT, caps);
333
334   structure = gst_caps_get_structure (caps, 0);
335   if (!gst_structure_get_fraction (structure, "framerate",
336           &rate_numerator, &rate_denominator))
337     goto no_framerate;
338
339   /* out_frame_count is scaled by the frame rate caps when calculating next_ts.
340    * when the frame rate caps change, we must update base_ts and reset
341    * out_frame_count */
342   if (videorate->to_rate_numerator) {
343     videorate->base_ts +=
344         gst_util_uint64_scale (videorate->out_frame_count,
345         videorate->to_rate_denominator * GST_SECOND,
346         videorate->to_rate_numerator);
347   }
348   videorate->out_frame_count = 0;
349   videorate->to_rate_numerator = rate_numerator;
350   videorate->to_rate_denominator = rate_denominator;
351   videorate->wanted_diff = gst_util_uint64_scale_int (GST_SECOND,
352       rate_denominator, rate_numerator);
353
354   gst_pad_push_event (videorate->srcpad, gst_event_new_caps (caps));
355
356   return TRUE;
357
358   /* ERRORS */
359 no_framerate:
360   {
361     GST_DEBUG_OBJECT (videorate, "no framerate specified");
362     return FALSE;
363   }
364 }
365
366 static gboolean
367 gst_video_rate_set_sink_caps (GstVideoRate * videorate, GstCaps * caps)
368 {
369   GstStructure *structure;
370   gboolean ret = TRUE;
371   gint rate_numerator, rate_denominator;
372
373   GST_DEBUG_OBJECT (videorate, "sink caps %" GST_PTR_FORMAT, caps);
374
375   structure = gst_caps_get_structure (caps, 0);
376   if (!gst_structure_get_fraction (structure, "framerate",
377           &rate_numerator, &rate_denominator))
378     goto no_framerate;
379
380   videorate->from_rate_numerator = rate_numerator;
381   videorate->from_rate_denominator = rate_denominator;
382
383   /* now try to find something for the peer */
384   if (gst_pad_peer_accept_caps (videorate->srcpad, caps)) {
385     /* the peer accepts the caps as they are */
386     ret = gst_video_rate_set_src_caps (videorate, caps);
387   } else {
388     GstCaps *transform = NULL;
389
390     ret = FALSE;
391
392     /* see how we can transform the input caps */
393     if (!gst_video_rate_transformcaps (videorate->sinkpad, caps,
394             videorate->srcpad, &transform, NULL))
395       goto no_transform;
396
397     GST_DEBUG_OBJECT (videorate, "transform %" GST_PTR_FORMAT, transform);
398
399     /* see what the peer can do */
400     caps = gst_pad_peer_get_caps (videorate->srcpad, transform);
401
402     GST_DEBUG_OBJECT (videorate, "icaps %" GST_PTR_FORMAT, caps);
403
404     /* could turn up empty, due to e.g. colorspace etc */
405     if (gst_caps_get_size (caps) == 0) {
406       gst_caps_unref (caps);
407       goto no_transform;
408     }
409
410     /* take first possibility */
411     caps = gst_caps_make_writable (caps);
412     gst_caps_truncate (caps);
413     structure = gst_caps_get_structure (caps, 0);
414
415     /* and fixate */
416     gst_structure_fixate_field_nearest_fraction (structure, "framerate",
417         rate_numerator, rate_denominator);
418     gst_structure_get_fraction (structure, "framerate",
419         &rate_numerator, &rate_denominator);
420
421     videorate->to_rate_numerator = rate_numerator;
422     videorate->to_rate_denominator = rate_denominator;
423
424     if (gst_structure_has_field (structure, "interlaced"))
425       gst_structure_fixate_field_boolean (structure, "interlaced", FALSE);
426     if (gst_structure_has_field (structure, "color-matrix"))
427       gst_structure_fixate_field_string (structure, "color-matrix", "sdtv");
428     if (gst_structure_has_field (structure, "chroma-site"))
429       gst_structure_fixate_field_string (structure, "chroma-site", "mpeg2");
430     if (gst_structure_has_field (structure, "pixel-aspect-ratio"))
431       gst_structure_fixate_field_nearest_fraction (structure,
432           "pixel-aspect-ratio", 1, 1);
433
434     ret = gst_video_rate_set_src_caps (videorate, caps);
435     gst_caps_unref (caps);
436   }
437 done:
438   /* After a setcaps, our caps may have changed. In that case, we can't use
439    * the old buffer, if there was one (it might have different dimensions) */
440   GST_DEBUG_OBJECT (videorate, "swapping old buffers");
441   gst_video_rate_swap_prev (videorate, NULL, GST_CLOCK_TIME_NONE);
442
443   return ret;
444
445 no_framerate:
446   {
447     GST_DEBUG_OBJECT (videorate, "no framerate specified");
448     goto done;
449   }
450 no_transform:
451   {
452     GST_DEBUG_OBJECT (videorate, "no framerate transform possible");
453     ret = FALSE;
454     goto done;
455   }
456 }
457
458 static void
459 gst_video_rate_reset (GstVideoRate * videorate)
460 {
461   GST_DEBUG_OBJECT (videorate, "resetting internal variables");
462
463   videorate->in = 0;
464   videorate->out = 0;
465   videorate->base_ts = 0;
466   videorate->out_frame_count = 0;
467   videorate->drop = 0;
468   videorate->dup = 0;
469   videorate->next_ts = GST_CLOCK_TIME_NONE;
470   videorate->last_ts = GST_CLOCK_TIME_NONE;
471   videorate->discont = TRUE;
472   videorate->average = 0;
473   gst_video_rate_swap_prev (videorate, NULL, 0);
474
475   gst_segment_init (&videorate->segment, GST_FORMAT_TIME);
476 }
477
478 static void
479 gst_video_rate_init (GstVideoRate * videorate)
480 {
481   videorate->sinkpad =
482       gst_pad_new_from_static_template (&gst_video_rate_sink_template, "sink");
483   gst_pad_set_event_function (videorate->sinkpad,
484       GST_DEBUG_FUNCPTR (gst_video_rate_event));
485   gst_pad_set_chain_function (videorate->sinkpad,
486       GST_DEBUG_FUNCPTR (gst_video_rate_chain));
487   gst_pad_set_getcaps_function (videorate->sinkpad,
488       GST_DEBUG_FUNCPTR (gst_video_rate_getcaps));
489   gst_element_add_pad (GST_ELEMENT (videorate), videorate->sinkpad);
490
491   videorate->srcpad =
492       gst_pad_new_from_static_template (&gst_video_rate_src_template, "src");
493   gst_pad_set_query_function (videorate->srcpad,
494       GST_DEBUG_FUNCPTR (gst_video_rate_query));
495   gst_pad_set_getcaps_function (videorate->srcpad,
496       GST_DEBUG_FUNCPTR (gst_video_rate_getcaps));
497   gst_element_add_pad (GST_ELEMENT (videorate), videorate->srcpad);
498
499   gst_video_rate_reset (videorate);
500   videorate->silent = DEFAULT_SILENT;
501   videorate->new_pref = DEFAULT_NEW_PREF;
502   videorate->drop_only = DEFAULT_DROP_ONLY;
503   videorate->average_period = DEFAULT_AVERAGE_PERIOD;
504
505   videorate->from_rate_numerator = 0;
506   videorate->from_rate_denominator = 0;
507   videorate->to_rate_numerator = 0;
508   videorate->to_rate_denominator = 0;
509 }
510
511 /* flush the oldest buffer */
512 static GstFlowReturn
513 gst_video_rate_flush_prev (GstVideoRate * videorate, gboolean duplicate)
514 {
515   GstFlowReturn res;
516   GstBuffer *outbuf;
517   GstClockTime push_ts;
518
519   if (!videorate->prevbuf)
520     goto eos_before_buffers;
521
522   /* make sure we can write to the metadata */
523   outbuf = gst_buffer_make_writable (gst_buffer_ref (videorate->prevbuf));
524
525   GST_BUFFER_OFFSET (outbuf) = videorate->out;
526   GST_BUFFER_OFFSET_END (outbuf) = videorate->out + 1;
527
528   if (videorate->discont) {
529     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
530     videorate->discont = FALSE;
531   } else
532     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DISCONT);
533
534   if (duplicate)
535     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_GAP);
536   else
537     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_GAP);
538
539   /* this is the timestamp we put on the buffer */
540   push_ts = videorate->next_ts;
541
542   videorate->out++;
543   videorate->out_frame_count++;
544   if (videorate->to_rate_numerator) {
545     /* interpolate next expected timestamp in the segment */
546     videorate->next_ts =
547         videorate->segment.base + videorate->segment.start +
548         videorate->base_ts + gst_util_uint64_scale (videorate->out_frame_count,
549         videorate->to_rate_denominator * GST_SECOND,
550         videorate->to_rate_numerator);
551     GST_BUFFER_DURATION (outbuf) = videorate->next_ts - push_ts;
552   }
553
554   /* We do not need to update time in VFR (variable frame rate) mode */
555   if (!videorate->drop_only) {
556     /* adapt for looping, bring back to time in current segment. */
557     GST_BUFFER_TIMESTAMP (outbuf) = push_ts - videorate->segment.base;
558   }
559
560   GST_LOG_OBJECT (videorate,
561       "old is best, dup, pushing buffer outgoing ts %" GST_TIME_FORMAT,
562       GST_TIME_ARGS (push_ts));
563
564   res = gst_pad_push (videorate->srcpad, outbuf);
565
566   return res;
567
568   /* WARNINGS */
569 eos_before_buffers:
570   {
571     GST_INFO_OBJECT (videorate, "got EOS before any buffer was received");
572     return GST_FLOW_OK;
573   }
574 }
575
576 static void
577 gst_video_rate_swap_prev (GstVideoRate * videorate, GstBuffer * buffer,
578     gint64 time)
579 {
580   GST_LOG_OBJECT (videorate, "swap_prev: storing buffer %p in prev", buffer);
581   if (videorate->prevbuf)
582     gst_buffer_unref (videorate->prevbuf);
583   videorate->prevbuf = buffer;
584   videorate->prev_ts = time;
585 }
586
587 static void
588 gst_video_rate_notify_drop (GstVideoRate * videorate)
589 {
590 #if !GLIB_CHECK_VERSION(2,26,0)
591   g_object_notify ((GObject *) videorate, "drop");
592 #else
593   g_object_notify_by_pspec ((GObject *) videorate, pspec_drop);
594 #endif
595 }
596
597 static void
598 gst_video_rate_notify_duplicate (GstVideoRate * videorate)
599 {
600 #if !GLIB_CHECK_VERSION(2,26,0)
601   g_object_notify ((GObject *) videorate, "duplicate");
602 #else
603   g_object_notify_by_pspec ((GObject *) videorate, pspec_duplicate);
604 #endif
605 }
606
607 #define MAGIC_LIMIT  25
608 static gboolean
609 gst_video_rate_event (GstPad * pad, GstEvent * event)
610 {
611   GstVideoRate *videorate;
612   gboolean ret;
613
614   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
615
616   switch (GST_EVENT_TYPE (event)) {
617     case GST_EVENT_CAPS:
618     {
619       GstCaps *caps;
620
621       gst_event_parse_caps (event, &caps);
622       ret = gst_video_rate_set_sink_caps (videorate, caps);
623       gst_event_unref (event);
624
625       /* don't forward */
626       goto done;
627     }
628     case GST_EVENT_SEGMENT:
629     {
630       const GstSegment *segment;
631
632       gst_event_parse_segment (event, &segment);
633
634       if (segment->format != GST_FORMAT_TIME)
635         goto format_error;
636
637       GST_DEBUG_OBJECT (videorate, "handle NEWSEGMENT");
638
639       /* close up the previous segment, if appropriate */
640       if (videorate->prevbuf) {
641         gint count = 0;
642         GstFlowReturn res;
643
644         res = GST_FLOW_OK;
645         /* fill up to the end of current segment,
646          * or only send out the stored buffer if there is no specific stop.
647          * regardless, prevent going loopy in strange cases */
648         while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
649             ((GST_CLOCK_TIME_IS_VALID (videorate->segment.stop) &&
650                     videorate->next_ts - videorate->segment.base
651                     < videorate->segment.stop)
652                 || count < 1)) {
653           res = gst_video_rate_flush_prev (videorate, count > 0);
654           count++;
655         }
656         if (count > 1) {
657           videorate->dup += count - 1;
658           if (!videorate->silent)
659             gst_video_rate_notify_duplicate (videorate);
660         } else if (count == 0) {
661           videorate->drop++;
662           if (!videorate->silent)
663             gst_video_rate_notify_drop (videorate);
664         }
665         /* clean up for the new one; _chain will resume from the new start */
666         videorate->base_ts = 0;
667         videorate->out_frame_count = 0;
668         gst_video_rate_swap_prev (videorate, NULL, 0);
669         videorate->next_ts = GST_CLOCK_TIME_NONE;
670       }
671
672       /* We just want to update the accumulated stream_time  */
673       gst_segment_copy_into (segment, &videorate->segment);
674
675       GST_DEBUG_OBJECT (videorate, "updated segment: %" GST_SEGMENT_FORMAT,
676           &videorate->segment);
677       break;
678     }
679     case GST_EVENT_EOS:{
680       gint count = 0;
681       GstFlowReturn res = GST_FLOW_OK;
682
683       GST_DEBUG_OBJECT (videorate, "Got EOS");
684
685       /* If the segment has a stop position, fill the segment */
686       if (GST_CLOCK_TIME_IS_VALID (videorate->segment.stop)) {
687         /* fill up to the end of current segment,
688          * or only send out the stored buffer if there is no specific stop.
689          * regardless, prevent going loopy in strange cases */
690         while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
691             ((videorate->next_ts - videorate->segment.base <
692                     videorate->segment.stop)
693                 || count < 1)) {
694           res = gst_video_rate_flush_prev (videorate, count > 0);
695           count++;
696         }
697       } else if (videorate->prevbuf) {
698         /* Output at least one frame but if the buffer duration is valid, output
699          * enough frames to use the complete buffer duration */
700         if (GST_BUFFER_DURATION_IS_VALID (videorate->prevbuf)) {
701           GstClockTime end_ts =
702               videorate->next_ts + GST_BUFFER_DURATION (videorate->prevbuf);
703
704           while (res == GST_FLOW_OK && count <= MAGIC_LIMIT &&
705               ((videorate->next_ts - videorate->segment.base < end_ts)
706                   || count < 1)) {
707             res = gst_video_rate_flush_prev (videorate, count > 0);
708             count++;
709           }
710         } else {
711           res = gst_video_rate_flush_prev (videorate, FALSE);
712           count = 1;
713         }
714       }
715
716       if (count > 1) {
717         videorate->dup += count - 1;
718         if (!videorate->silent)
719           gst_video_rate_notify_duplicate (videorate);
720       } else if (count == 0) {
721         videorate->drop++;
722         if (!videorate->silent)
723           gst_video_rate_notify_drop (videorate);
724       }
725
726       break;
727     }
728     case GST_EVENT_FLUSH_STOP:
729       /* also resets the segment */
730       GST_DEBUG_OBJECT (videorate, "Got FLUSH_STOP");
731       gst_video_rate_reset (videorate);
732       break;
733     default:
734       break;
735   }
736
737   ret = gst_pad_push_event (videorate->srcpad, event);
738
739 done:
740   gst_object_unref (videorate);
741
742   return ret;
743
744   /* ERRORS */
745 format_error:
746   {
747     GST_WARNING_OBJECT (videorate,
748         "Got segment but doesn't have GST_FORMAT_TIME value");
749     gst_event_unref (event);
750     ret = FALSE;
751     goto done;
752   }
753 }
754
755 static gboolean
756 gst_video_rate_query (GstPad * pad, GstQuery * query)
757 {
758   GstVideoRate *videorate;
759   gboolean res = FALSE;
760
761   videorate = GST_VIDEO_RATE (gst_pad_get_parent (pad));
762
763   switch (GST_QUERY_TYPE (query)) {
764     case GST_QUERY_LATENCY:
765     {
766       GstClockTime min, max;
767       gboolean live;
768       guint64 latency;
769       GstPad *peer;
770
771       if ((peer = gst_pad_get_peer (videorate->sinkpad))) {
772         if ((res = gst_pad_query (peer, query))) {
773           gst_query_parse_latency (query, &live, &min, &max);
774
775           GST_DEBUG_OBJECT (videorate, "Peer latency: min %"
776               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
777               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
778
779           if (videorate->from_rate_numerator != 0) {
780             /* add latency. We don't really know since we hold on to the frames
781              * until we get a next frame, which can be anything. We assume
782              * however that this will take from_rate time. */
783             latency = gst_util_uint64_scale (GST_SECOND,
784                 videorate->from_rate_denominator,
785                 videorate->from_rate_numerator);
786           } else {
787             /* no input framerate, we don't know */
788             latency = 0;
789           }
790
791           GST_DEBUG_OBJECT (videorate, "Our latency: %"
792               GST_TIME_FORMAT, GST_TIME_ARGS (latency));
793
794           min += latency;
795           if (max != -1)
796             max += latency;
797
798           GST_DEBUG_OBJECT (videorate, "Calculated total latency : min %"
799               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
800               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
801
802           gst_query_set_latency (query, live, min, max);
803         }
804         gst_object_unref (peer);
805       }
806       break;
807     }
808     default:
809       res = gst_pad_query_default (pad, query);
810       break;
811   }
812   gst_object_unref (videorate);
813
814   return res;
815 }
816
817 static GstFlowReturn
818 gst_video_rate_chain_max_avg (GstVideoRate * videorate, GstBuffer * buf)
819 {
820   GstClockTime ts = GST_BUFFER_TIMESTAMP (buf);
821
822   videorate->in++;
823
824   if (!GST_CLOCK_TIME_IS_VALID (ts) || videorate->wanted_diff == 0)
825     goto push;
826
827   /* drop frames if they exceed our output rate */
828   if (GST_CLOCK_TIME_IS_VALID (videorate->last_ts)) {
829     GstClockTimeDiff diff = ts - videorate->last_ts;
830
831     /* Drop buffer if its early compared to the desired frame rate and
832      * the current average is higher than the desired average
833      */
834     if (diff < videorate->wanted_diff &&
835         videorate->average < videorate->wanted_diff)
836       goto drop;
837
838     /* Update average */
839     if (videorate->average) {
840       GstClockTimeDiff wanted_diff;
841
842       if (G_LIKELY (videorate->average_period > videorate->wanted_diff))
843         wanted_diff = videorate->wanted_diff;
844       else
845         wanted_diff = videorate->average_period * 10;
846
847       videorate->average =
848           gst_util_uint64_scale_round (videorate->average,
849           videorate->average_period - wanted_diff,
850           videorate->average_period) +
851           gst_util_uint64_scale_round (diff, wanted_diff,
852           videorate->average_period);
853     } else {
854       videorate->average = diff;
855     }
856   }
857
858   videorate->last_ts = ts;
859
860 push:
861   videorate->out++;
862
863   return gst_pad_push (videorate->srcpad, buf);
864
865 drop:
866   gst_buffer_unref (buf);
867   if (!videorate->silent)
868     gst_video_rate_notify_drop (videorate);
869   return GST_FLOW_OK;
870 }
871
872 static GstFlowReturn
873 gst_video_rate_chain (GstPad * pad, GstBuffer * buffer)
874 {
875   GstVideoRate *videorate;
876   GstFlowReturn res = GST_FLOW_OK;
877   GstClockTime intime, in_ts, in_dur;
878   GstClockTime avg_period;
879   gboolean skip = FALSE;
880
881   videorate = GST_VIDEO_RATE (GST_PAD_PARENT (pad));
882
883   /* make sure the denominators are not 0 */
884   if (videorate->from_rate_denominator == 0 ||
885       videorate->to_rate_denominator == 0)
886     goto not_negotiated;
887
888   GST_OBJECT_LOCK (videorate);
889   avg_period = videorate->average_period_set;
890   GST_OBJECT_UNLOCK (videorate);
891
892   /* MT-safe switching between modes */
893   if (G_UNLIKELY (avg_period != videorate->average_period)) {
894     videorate->average_period = avg_period;
895     videorate->last_ts = GST_CLOCK_TIME_NONE;
896     if (avg_period && !videorate->average) {
897       /* enabling average mode */
898       videorate->average = 0;
899     } else {
900       /* enable regular mode */
901       gst_video_rate_swap_prev (videorate, NULL, 0);
902       /* arrange for skip-to-first behaviour */
903       videorate->next_ts = GST_CLOCK_TIME_NONE;
904       skip = TRUE;
905     }
906   }
907
908   if (videorate->average_period > 0)
909     return gst_video_rate_chain_max_avg (videorate, buffer);
910
911   in_ts = GST_BUFFER_TIMESTAMP (buffer);
912   in_dur = GST_BUFFER_DURATION (buffer);
913
914   if (G_UNLIKELY (in_ts == GST_CLOCK_TIME_NONE)) {
915     in_ts = videorate->last_ts;
916     if (G_UNLIKELY (in_ts == GST_CLOCK_TIME_NONE))
917       goto invalid_buffer;
918   }
919
920   /* get the time of the next expected buffer timestamp, we use this when the
921    * next buffer has -1 as a timestamp */
922   videorate->last_ts = in_ts;
923   if (in_dur != GST_CLOCK_TIME_NONE)
924     videorate->last_ts += in_dur;
925
926   GST_DEBUG_OBJECT (videorate, "got buffer with timestamp %" GST_TIME_FORMAT,
927       GST_TIME_ARGS (in_ts));
928
929   /* the input time is the time in the segment + all previously accumulated
930    * segments */
931   intime = in_ts + videorate->segment.base;
932
933   /* we need to have two buffers to compare */
934   if (videorate->prevbuf == NULL) {
935     gst_video_rate_swap_prev (videorate, buffer, intime);
936     videorate->in++;
937     if (!GST_CLOCK_TIME_IS_VALID (videorate->next_ts)) {
938       /* new buffer, we expect to output a buffer that matches the first
939        * timestamp in the segment */
940       if (videorate->skip_to_first || skip) {
941         videorate->next_ts = intime;
942         videorate->base_ts = in_ts - videorate->segment.start;
943         videorate->out_frame_count = 0;
944       } else {
945         videorate->next_ts = videorate->segment.start + videorate->segment.base;
946       }
947     }
948   } else {
949     GstClockTime prevtime;
950     gint count = 0;
951     gint64 diff1, diff2;
952
953     prevtime = videorate->prev_ts;
954
955     GST_LOG_OBJECT (videorate,
956         "BEGINNING prev buf %" GST_TIME_FORMAT " new buf %" GST_TIME_FORMAT
957         " outgoing ts %" GST_TIME_FORMAT, GST_TIME_ARGS (prevtime),
958         GST_TIME_ARGS (intime), GST_TIME_ARGS (videorate->next_ts));
959
960     videorate->in++;
961
962     /* drop new buffer if it's before previous one */
963     if (intime < prevtime) {
964       GST_DEBUG_OBJECT (videorate,
965           "The new buffer (%" GST_TIME_FORMAT
966           ") is before the previous buffer (%"
967           GST_TIME_FORMAT "). Dropping new buffer.",
968           GST_TIME_ARGS (intime), GST_TIME_ARGS (prevtime));
969       videorate->drop++;
970       if (!videorate->silent)
971         gst_video_rate_notify_drop (videorate);
972       gst_buffer_unref (buffer);
973       goto done;
974     }
975
976     /* got 2 buffers, see which one is the best */
977     do {
978
979       diff1 = prevtime - videorate->next_ts;
980       diff2 = intime - videorate->next_ts;
981
982       /* take absolute values, beware: abs and ABS don't work for gint64 */
983       if (diff1 < 0)
984         diff1 = -diff1;
985       if (diff2 < 0)
986         diff2 = -diff2;
987
988       GST_LOG_OBJECT (videorate,
989           "diff with prev %" GST_TIME_FORMAT " diff with new %"
990           GST_TIME_FORMAT " outgoing ts %" GST_TIME_FORMAT,
991           GST_TIME_ARGS (diff1), GST_TIME_ARGS (diff2),
992           GST_TIME_ARGS (videorate->next_ts));
993
994       /* output first one when its the best */
995       if (diff1 <= diff2) {
996         count++;
997
998         /* on error the _flush function posted a warning already */
999         if ((res =
1000                 gst_video_rate_flush_prev (videorate,
1001                     count > 1)) != GST_FLOW_OK) {
1002           gst_buffer_unref (buffer);
1003           goto done;
1004         }
1005       }
1006
1007       /* Do not produce any dups. We can exit loop now */
1008       if (videorate->drop_only)
1009         break;
1010       /* continue while the first one was the best, if they were equal avoid
1011        * going into an infinite loop */
1012     }
1013     while (diff1 < diff2);
1014
1015     /* if we outputed the first buffer more then once, we have dups */
1016     if (count > 1) {
1017       videorate->dup += count - 1;
1018       if (!videorate->silent)
1019         gst_video_rate_notify_duplicate (videorate);
1020     }
1021     /* if we didn't output the first buffer, we have a drop */
1022     else if (count == 0) {
1023       videorate->drop++;
1024
1025       if (!videorate->silent)
1026         gst_video_rate_notify_drop (videorate);
1027
1028       GST_LOG_OBJECT (videorate,
1029           "new is best, old never used, drop, outgoing ts %"
1030           GST_TIME_FORMAT, GST_TIME_ARGS (videorate->next_ts));
1031     }
1032     GST_LOG_OBJECT (videorate,
1033         "END, putting new in old, diff1 %" GST_TIME_FORMAT
1034         ", diff2 %" GST_TIME_FORMAT ", next_ts %" GST_TIME_FORMAT
1035         ", in %" G_GUINT64_FORMAT ", out %" G_GUINT64_FORMAT ", drop %"
1036         G_GUINT64_FORMAT ", dup %" G_GUINT64_FORMAT, GST_TIME_ARGS (diff1),
1037         GST_TIME_ARGS (diff2), GST_TIME_ARGS (videorate->next_ts),
1038         videorate->in, videorate->out, videorate->drop, videorate->dup);
1039
1040     /* swap in new one when it's the best */
1041     gst_video_rate_swap_prev (videorate, buffer, intime);
1042   }
1043 done:
1044   return res;
1045
1046   /* ERRORS */
1047 not_negotiated:
1048   {
1049     GST_WARNING_OBJECT (videorate, "no framerate negotiated");
1050     gst_buffer_unref (buffer);
1051     res = GST_FLOW_NOT_NEGOTIATED;
1052     goto done;
1053   }
1054
1055 invalid_buffer:
1056   {
1057     GST_WARNING_OBJECT (videorate,
1058         "Got buffer with GST_CLOCK_TIME_NONE timestamp, discarding it");
1059     gst_buffer_unref (buffer);
1060     goto done;
1061   }
1062 }
1063
1064 static void
1065 gst_video_rate_set_property (GObject * object,
1066     guint prop_id, const GValue * value, GParamSpec * pspec)
1067 {
1068   GstVideoRate *videorate = GST_VIDEO_RATE (object);
1069
1070   GST_OBJECT_LOCK (videorate);
1071   switch (prop_id) {
1072     case ARG_SILENT:
1073       videorate->silent = g_value_get_boolean (value);
1074       break;
1075     case ARG_NEW_PREF:
1076       videorate->new_pref = g_value_get_double (value);
1077       break;
1078     case ARG_SKIP_TO_FIRST:
1079       videorate->skip_to_first = g_value_get_boolean (value);
1080       break;
1081     case ARG_DROP_ONLY:
1082       videorate->drop_only = g_value_get_boolean (value);
1083       break;
1084     case ARG_AVERAGE_PERIOD:
1085       videorate->average_period = g_value_get_uint64 (value);
1086       break;
1087     default:
1088       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1089       break;
1090   }
1091   GST_OBJECT_UNLOCK (videorate);
1092 }
1093
1094 static void
1095 gst_video_rate_get_property (GObject * object,
1096     guint prop_id, GValue * value, GParamSpec * pspec)
1097 {
1098   GstVideoRate *videorate = GST_VIDEO_RATE (object);
1099
1100   GST_OBJECT_LOCK (videorate);
1101   switch (prop_id) {
1102     case ARG_IN:
1103       g_value_set_uint64 (value, videorate->in);
1104       break;
1105     case ARG_OUT:
1106       g_value_set_uint64 (value, videorate->out);
1107       break;
1108     case ARG_DUP:
1109       g_value_set_uint64 (value, videorate->dup);
1110       break;
1111     case ARG_DROP:
1112       g_value_set_uint64 (value, videorate->drop);
1113       break;
1114     case ARG_SILENT:
1115       g_value_set_boolean (value, videorate->silent);
1116       break;
1117     case ARG_NEW_PREF:
1118       g_value_set_double (value, videorate->new_pref);
1119       break;
1120     case ARG_SKIP_TO_FIRST:
1121       g_value_set_boolean (value, videorate->skip_to_first);
1122       break;
1123     case ARG_DROP_ONLY:
1124       g_value_set_boolean (value, videorate->drop_only);
1125       break;
1126     case ARG_AVERAGE_PERIOD:
1127       g_value_set_uint64 (value, videorate->average_period);
1128       break;
1129     default:
1130       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1131       break;
1132   }
1133   GST_OBJECT_UNLOCK (videorate);
1134 }
1135
1136 static GstStateChangeReturn
1137 gst_video_rate_change_state (GstElement * element, GstStateChange transition)
1138 {
1139   GstStateChangeReturn ret;
1140   GstVideoRate *videorate;
1141
1142   videorate = GST_VIDEO_RATE (element);
1143
1144   switch (transition) {
1145     case GST_STATE_CHANGE_READY_TO_PAUSED:
1146       videorate->discont = TRUE;
1147       videorate->last_ts = -1;
1148       break;
1149     default:
1150       break;
1151   }
1152
1153   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1154
1155   switch (transition) {
1156     case GST_STATE_CHANGE_PAUSED_TO_READY:
1157       gst_video_rate_reset (videorate);
1158       break;
1159     default:
1160       break;
1161   }
1162
1163   return ret;
1164 }
1165
1166 static gboolean
1167 plugin_init (GstPlugin * plugin)
1168 {
1169   GST_DEBUG_CATEGORY_INIT (video_rate_debug, "videorate", 0,
1170       "VideoRate stream fixer");
1171
1172   return gst_element_register (plugin, "videorate", GST_RANK_NONE,
1173       GST_TYPE_VIDEO_RATE);
1174 }
1175
1176 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1177     GST_VERSION_MINOR,
1178     "videorate",
1179     "Adjusts video frames",
1180     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)