jitterbuffer: do skew estimation only for new timestamps
[platform/upstream/gstreamer.git] / gst / rtpmanager / gstrtpjitterbuffer.c
1 /*
2  * Farsight Voice+Video library
3  *
4  *  Copyright 2007 Collabora Ltd,
5  *  Copyright 2007 Nokia Corporation
6  *   @author: Philippe Kalaf <philippe.kalaf@collabora.co.uk>.
7  *  Copyright 2007 Wim Taymans <wim.taymans@gmail.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  *
24  */
25
26 /**
27  * SECTION:element-gstrtpjitterbuffer
28  *
29  * This element reorders and removes duplicate RTP packets as they are received
30  * from a network source. It will also wait for missing packets up to a
31  * configurable time limit using the #GstRtpJitterBuffer:latency property.
32  * Packets arriving too late are considered to be lost packets.
33  *
34  * This element acts as a live element and so adds #GstRtpJitterBuffer:latency
35  * to the pipeline.
36  *
37  * The element needs the clock-rate of the RTP payload in order to estimate the
38  * delay. This information is obtained either from the caps on the sink pad or,
39  * when no caps are present, from the #GstRtpJitterBuffer::request-pt-map signal.
40  * To clear the previous pt-map use the #GstRtpJitterBuffer::clear-pt-map signal.
41  *
42  * This element will automatically be used inside gstrtpbin.
43  *
44  * <refsect2>
45  * <title>Example pipelines</title>
46  * |[
47  * gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! gstrtpjitterbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
48  * ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
49  * inserted into the pipeline to smooth out network jitter and to reorder the
50  * out-of-order RTP packets.
51  * </refsect2>
52  *
53  * Last reviewed on 2007-05-28 (0.10.5)
54  */
55
56 #ifdef HAVE_CONFIG_H
57 #include "config.h"
58 #endif
59
60 #include <stdlib.h>
61 #include <string.h>
62 #include <gst/rtp/gstrtpbuffer.h>
63
64 #include "gstrtpbin-marshal.h"
65
66 #include "gstrtpjitterbuffer.h"
67 #include "rtpjitterbuffer.h"
68 #include "rtpstats.h"
69
70 #include <gst/glib-compat-private.h>
71
72 GST_DEBUG_CATEGORY (rtpjitterbuffer_debug);
73 #define GST_CAT_DEFAULT (rtpjitterbuffer_debug)
74
75 /* RTPJitterBuffer signals and args */
76 enum
77 {
78   SIGNAL_REQUEST_PT_MAP,
79   SIGNAL_CLEAR_PT_MAP,
80   SIGNAL_HANDLE_SYNC,
81   SIGNAL_ON_NPT_STOP,
82   SIGNAL_SET_ACTIVE,
83   LAST_SIGNAL
84 };
85
86 #define DEFAULT_LATENCY_MS      200
87 #define DEFAULT_DROP_ON_LATENCY FALSE
88 #define DEFAULT_TS_OFFSET       0
89 #define DEFAULT_DO_LOST         FALSE
90 #define DEFAULT_MODE            RTP_JITTER_BUFFER_MODE_SLAVE
91 #define DEFAULT_PERCENT         0
92
93 enum
94 {
95   PROP_0,
96   PROP_LATENCY,
97   PROP_DROP_ON_LATENCY,
98   PROP_TS_OFFSET,
99   PROP_DO_LOST,
100   PROP_MODE,
101   PROP_PERCENT,
102   PROP_LAST
103 };
104
105 #define JBUF_LOCK(priv)   (g_mutex_lock (&(priv)->jbuf_lock))
106
107 #define JBUF_LOCK_CHECK(priv,label) G_STMT_START {    \
108   JBUF_LOCK (priv);                                   \
109   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))    \
110     goto label;                                       \
111 } G_STMT_END
112
113 #define JBUF_UNLOCK(priv) (g_mutex_unlock (&(priv)->jbuf_lock))
114 #define JBUF_WAIT(priv)   (g_cond_wait (&(priv)->jbuf_cond, &(priv)->jbuf_lock))
115
116 #define JBUF_WAIT_CHECK(priv,label) G_STMT_START {    \
117   JBUF_WAIT(priv);                                    \
118   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))    \
119     goto label;                                       \
120 } G_STMT_END
121
122 #define JBUF_SIGNAL(priv) (g_cond_signal (&(priv)->jbuf_cond))
123
124 struct _GstRtpJitterBufferPrivate
125 {
126   GstPad *sinkpad, *srcpad;
127   GstPad *rtcpsinkpad;
128
129   RTPJitterBuffer *jbuf;
130   GMutex jbuf_lock;
131   GCond jbuf_cond;
132   gboolean waiting;
133   gboolean discont;
134   gboolean active;
135   guint64 out_offset;
136
137   /* properties */
138   guint latency_ms;
139   guint64 latency_ns;
140   gboolean drop_on_latency;
141   gint64 ts_offset;
142   gboolean do_lost;
143
144   /* the last seqnum we pushed out */
145   guint32 last_popped_seqnum;
146   /* the next expected seqnum we push */
147   guint32 next_seqnum;
148   /* last output time */
149   GstClockTime last_out_time;
150   /* the next expected seqnum we receive */
151   guint32 next_in_seqnum;
152
153   /* start and stop ranges */
154   GstClockTime npt_start;
155   GstClockTime npt_stop;
156   guint64 ext_timestamp;
157   guint64 last_elapsed;
158   guint64 estimated_eos;
159   GstClockID eos_id;
160   gboolean reached_npt_stop;
161
162   /* state */
163   gboolean eos;
164
165   /* clock rate and rtp timestamp offset */
166   gint last_pt;
167   gint32 clock_rate;
168   gint64 clock_base;
169   gint64 prev_ts_offset;
170
171   /* when we are shutting down */
172   GstFlowReturn srcresult;
173   gboolean blocked;
174
175   /* for sync */
176   GstSegment segment;
177   GstClockID clock_id;
178   gboolean unscheduled;
179   /* the latency of the upstream peer, we have to take this into account when
180    * synchronizing the buffers. */
181   GstClockTime peer_latency;
182   guint64 ext_rtptime;
183   GstBuffer *last_sr;
184
185   /* some accounting */
186   guint64 num_late;
187   guint64 num_duplicates;
188 };
189
190 #define GST_RTP_JITTER_BUFFER_GET_PRIVATE(o) \
191   (G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_RTP_JITTER_BUFFER, \
192                                 GstRtpJitterBufferPrivate))
193
194 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_template =
195 GST_STATIC_PAD_TEMPLATE ("sink",
196     GST_PAD_SINK,
197     GST_PAD_ALWAYS,
198     GST_STATIC_CAPS ("application/x-rtp, "
199         "clock-rate = (int) [ 1, 2147483647 ]"
200         /* "payload = (int) , "
201          * "encoding-name = (string) "
202          */ )
203     );
204
205 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_rtcp_template =
206 GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
207     GST_PAD_SINK,
208     GST_PAD_REQUEST,
209     GST_STATIC_CAPS ("application/x-rtcp")
210     );
211
212 static GstStaticPadTemplate gst_rtp_jitter_buffer_src_template =
213 GST_STATIC_PAD_TEMPLATE ("src",
214     GST_PAD_SRC,
215     GST_PAD_ALWAYS,
216     GST_STATIC_CAPS ("application/x-rtp"
217         /* "payload = (int) , "
218          * "clock-rate = (int) , "
219          * "encoding-name = (string) "
220          */ )
221     );
222
223 static guint gst_rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 };
224
225 #define gst_rtp_jitter_buffer_parent_class parent_class
226 G_DEFINE_TYPE (GstRtpJitterBuffer, gst_rtp_jitter_buffer, GST_TYPE_ELEMENT);
227
228 /* object overrides */
229 static void gst_rtp_jitter_buffer_set_property (GObject * object,
230     guint prop_id, const GValue * value, GParamSpec * pspec);
231 static void gst_rtp_jitter_buffer_get_property (GObject * object,
232     guint prop_id, GValue * value, GParamSpec * pspec);
233 static void gst_rtp_jitter_buffer_finalize (GObject * object);
234
235 /* element overrides */
236 static GstStateChangeReturn gst_rtp_jitter_buffer_change_state (GstElement
237     * element, GstStateChange transition);
238 static GstPad *gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
239     GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
240 static void gst_rtp_jitter_buffer_release_pad (GstElement * element,
241     GstPad * pad);
242 static GstClock *gst_rtp_jitter_buffer_provide_clock (GstElement * element);
243
244 /* pad overrides */
245 static GstCaps *gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter);
246 static GstIterator *gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad,
247     GstObject * parent);
248
249 /* sinkpad overrides */
250 static gboolean gst_rtp_jitter_buffer_sink_event (GstPad * pad,
251     GstObject * parent, GstEvent * event);
252 static GstFlowReturn gst_rtp_jitter_buffer_chain (GstPad * pad,
253     GstObject * parent, GstBuffer * buffer);
254
255 static gboolean gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad,
256     GstObject * parent, GstEvent * event);
257 static GstFlowReturn gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad,
258     GstObject * parent, GstBuffer * buffer);
259
260 static gboolean gst_rtp_jitter_buffer_sink_query (GstPad * pad,
261     GstObject * parent, GstQuery * query);
262
263 /* srcpad overrides */
264 static gboolean gst_rtp_jitter_buffer_src_event (GstPad * pad,
265     GstObject * parent, GstEvent * event);
266 static gboolean gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad,
267     GstObject * parent, GstPadMode mode, gboolean active);
268 static void gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer);
269 static gboolean gst_rtp_jitter_buffer_src_query (GstPad * pad,
270     GstObject * parent, GstQuery * query);
271
272 static void
273 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer);
274 static GstClockTime
275 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jitterbuffer,
276     gboolean active, guint64 base_time);
277
278 static void
279 gst_rtp_jitter_buffer_class_init (GstRtpJitterBufferClass * klass)
280 {
281   GObjectClass *gobject_class;
282   GstElementClass *gstelement_class;
283
284   gobject_class = (GObjectClass *) klass;
285   gstelement_class = (GstElementClass *) klass;
286
287   g_type_class_add_private (klass, sizeof (GstRtpJitterBufferPrivate));
288
289   gobject_class->finalize = gst_rtp_jitter_buffer_finalize;
290
291   gobject_class->set_property = gst_rtp_jitter_buffer_set_property;
292   gobject_class->get_property = gst_rtp_jitter_buffer_get_property;
293
294   /**
295    * GstRtpJitterBuffer::latency:
296    *
297    * The maximum latency of the jitterbuffer. Packets will be kept in the buffer
298    * for at most this time.
299    */
300   g_object_class_install_property (gobject_class, PROP_LATENCY,
301       g_param_spec_uint ("latency", "Buffer latency in ms",
302           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
303           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
304   /**
305    * GstRtpJitterBuffer::drop-on-latency:
306    *
307    * Drop oldest buffers when the queue is completely filled.
308    */
309   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
310       g_param_spec_boolean ("drop-on-latency",
311           "Drop buffers when maximum latency is reached",
312           "Tells the jitterbuffer to never exceed the given latency in size",
313           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
314   /**
315    * GstRtpJitterBuffer::ts-offset:
316    *
317    * Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
318    * This is mainly used to ensure interstream synchronisation.
319    */
320   g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
321       g_param_spec_int64 ("ts-offset", "Timestamp Offset",
322           "Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
323           G_MAXINT64, DEFAULT_TS_OFFSET,
324           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
325
326   /**
327    * GstRtpJitterBuffer::do-lost:
328    *
329    * Send out a GstRTPPacketLost event downstream when a packet is considered
330    * lost.
331    */
332   g_object_class_install_property (gobject_class, PROP_DO_LOST,
333       g_param_spec_boolean ("do-lost", "Do Lost",
334           "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
335           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
336
337   /**
338    * GstRtpJitterBuffer::mode:
339    *
340    * Control the buffering and timestamping mode used by the jitterbuffer.
341    */
342   g_object_class_install_property (gobject_class, PROP_MODE,
343       g_param_spec_enum ("mode", "Mode",
344           "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
345           DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346   /**
347    * GstRtpJitterBuffer::percent:
348    *
349    * The percent of the jitterbuffer that is filled.
350    *
351    * Since: 0.10.19
352    */
353   g_object_class_install_property (gobject_class, PROP_PERCENT,
354       g_param_spec_int ("percent", "percent",
355           "The buffer filled percent", 0, 100,
356           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
357   /**
358    * GstRtpJitterBuffer::request-pt-map:
359    * @buffer: the object which received the signal
360    * @pt: the pt
361    *
362    * Request the payload type as #GstCaps for @pt.
363    */
364   gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
365       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
366       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
367           request_pt_map), NULL, NULL, gst_rtp_bin_marshal_BOXED__UINT,
368       GST_TYPE_CAPS, 1, G_TYPE_UINT);
369   /**
370    * GstRtpJitterBuffer::handle-sync:
371    * @buffer: the object which received the signal
372    * @struct: a GstStructure containing sync values.
373    *
374    * Be notified of new sync values.
375    */
376   gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC] =
377       g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
378       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
379           handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
380       G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
381
382   /**
383    * GstRtpJitterBuffer::on-npt-stop
384    * @buffer: the object which received the signal
385    *
386    * Signal that the jitterbufer has pushed the RTP packet that corresponds to
387    * the npt-stop position.
388    */
389   gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP] =
390       g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
391       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
392           on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
393       G_TYPE_NONE, 0, G_TYPE_NONE);
394
395   /**
396    * GstRtpJitterBuffer::clear-pt-map:
397    * @buffer: the object which received the signal
398    *
399    * Invalidate the clock-rate as obtained with the
400    * #GstRtpJitterBuffer::request-pt-map signal.
401    */
402   gst_rtp_jitter_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
403       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
404       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
405       G_STRUCT_OFFSET (GstRtpJitterBufferClass, clear_pt_map), NULL, NULL,
406       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
407
408   /**
409    * GstRtpJitterBuffer::set-active:
410    * @buffer: the object which received the signal
411    *
412    * Start pushing out packets with the given base time. This signal is only
413    * useful in buffering mode.
414    *
415    * Returns: the time of the last pushed packet.
416    *
417    * Since: 0.10.19
418    */
419   gst_rtp_jitter_buffer_signals[SIGNAL_SET_ACTIVE] =
420       g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
421       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
422       G_STRUCT_OFFSET (GstRtpJitterBufferClass, set_active), NULL, NULL,
423       gst_rtp_bin_marshal_UINT64__BOOL_UINT64, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
424       G_TYPE_UINT64);
425
426   gstelement_class->change_state =
427       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_change_state);
428   gstelement_class->request_new_pad =
429       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_request_new_pad);
430   gstelement_class->release_pad =
431       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_release_pad);
432   gstelement_class->provide_clock =
433       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_provide_clock);
434
435   gst_element_class_add_pad_template (gstelement_class,
436       gst_static_pad_template_get (&gst_rtp_jitter_buffer_src_template));
437   gst_element_class_add_pad_template (gstelement_class,
438       gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_template));
439   gst_element_class_add_pad_template (gstelement_class,
440       gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_rtcp_template));
441
442   gst_element_class_set_static_metadata (gstelement_class,
443       "RTP packet jitter-buffer", "Filter/Network/RTP",
444       "A buffer that deals with network jitter and other transmission faults",
445       "Philippe Kalaf <philippe.kalaf@collabora.co.uk>, "
446       "Wim Taymans <wim.taymans@gmail.com>");
447
448   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_clear_pt_map);
449   klass->set_active = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_active);
450
451   GST_DEBUG_CATEGORY_INIT
452       (rtpjitterbuffer_debug, "gstrtpjitterbuffer", 0, "RTP Jitter Buffer");
453 }
454
455 static void
456 gst_rtp_jitter_buffer_init (GstRtpJitterBuffer * jitterbuffer)
457 {
458   GstRtpJitterBufferPrivate *priv;
459
460   priv = GST_RTP_JITTER_BUFFER_GET_PRIVATE (jitterbuffer);
461   jitterbuffer->priv = priv;
462
463   priv->latency_ms = DEFAULT_LATENCY_MS;
464   priv->latency_ns = priv->latency_ms * GST_MSECOND;
465   priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
466   priv->do_lost = DEFAULT_DO_LOST;
467
468   priv->jbuf = rtp_jitter_buffer_new ();
469   g_mutex_init (&priv->jbuf_lock);
470   g_cond_init (&priv->jbuf_cond);
471
472   /* reset skew detection initialy */
473   rtp_jitter_buffer_reset_skew (priv->jbuf);
474   rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
475   rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
476   priv->active = TRUE;
477
478   priv->srcpad =
479       gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_src_template,
480       "src");
481
482   gst_pad_set_activatemode_function (priv->srcpad,
483       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_activate_mode));
484   gst_pad_set_query_function (priv->srcpad,
485       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_query));
486   gst_pad_set_event_function (priv->srcpad,
487       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_event));
488
489   priv->sinkpad =
490       gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_sink_template,
491       "sink");
492
493   gst_pad_set_chain_function (priv->sinkpad,
494       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain));
495   gst_pad_set_event_function (priv->sinkpad,
496       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_event));
497   gst_pad_set_query_function (priv->sinkpad,
498       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_query));
499
500   gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
501   gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
502
503   GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
504 }
505
506 static void
507 gst_rtp_jitter_buffer_finalize (GObject * object)
508 {
509   GstRtpJitterBuffer *jitterbuffer;
510
511   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
512
513   g_mutex_clear (&jitterbuffer->priv->jbuf_lock);
514   g_cond_clear (&jitterbuffer->priv->jbuf_cond);
515
516   g_object_unref (jitterbuffer->priv->jbuf);
517
518   G_OBJECT_CLASS (parent_class)->finalize (object);
519 }
520
521 static GstIterator *
522 gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
523 {
524   GstRtpJitterBuffer *jitterbuffer;
525   GstPad *otherpad = NULL;
526   GstIterator *it;
527   GValue val = { 0, };
528
529   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
530
531   if (pad == jitterbuffer->priv->sinkpad) {
532     otherpad = jitterbuffer->priv->srcpad;
533   } else if (pad == jitterbuffer->priv->srcpad) {
534     otherpad = jitterbuffer->priv->sinkpad;
535   } else if (pad == jitterbuffer->priv->rtcpsinkpad) {
536     otherpad = NULL;
537   }
538
539   g_value_init (&val, GST_TYPE_PAD);
540   g_value_set_object (&val, otherpad);
541   it = gst_iterator_new_single (GST_TYPE_PAD, &val);
542   g_value_unset (&val);
543
544   return it;
545 }
546
547 static GstPad *
548 create_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
549 {
550   GstRtpJitterBufferPrivate *priv;
551
552   priv = jitterbuffer->priv;
553
554   GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
555
556   priv->rtcpsinkpad =
557       gst_pad_new_from_static_template
558       (&gst_rtp_jitter_buffer_sink_rtcp_template, "sink_rtcp");
559   gst_pad_set_chain_function (priv->rtcpsinkpad,
560       gst_rtp_jitter_buffer_chain_rtcp);
561   gst_pad_set_event_function (priv->rtcpsinkpad,
562       (GstPadEventFunction) gst_rtp_jitter_buffer_sink_rtcp_event);
563   gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
564       gst_rtp_jitter_buffer_iterate_internal_links);
565   gst_pad_set_active (priv->rtcpsinkpad, TRUE);
566   gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
567
568   return priv->rtcpsinkpad;
569 }
570
571 static void
572 remove_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
573 {
574   GstRtpJitterBufferPrivate *priv;
575
576   priv = jitterbuffer->priv;
577
578   GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
579
580   gst_pad_set_active (priv->rtcpsinkpad, FALSE);
581
582   gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
583   priv->rtcpsinkpad = NULL;
584 }
585
586 static GstPad *
587 gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
588     GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
589 {
590   GstRtpJitterBuffer *jitterbuffer;
591   GstElementClass *klass;
592   GstPad *result;
593   GstRtpJitterBufferPrivate *priv;
594
595   g_return_val_if_fail (templ != NULL, NULL);
596   g_return_val_if_fail (GST_IS_RTP_JITTER_BUFFER (element), NULL);
597
598   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
599   priv = jitterbuffer->priv;
600   klass = GST_ELEMENT_GET_CLASS (element);
601
602   GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
603
604   /* figure out the template */
605   if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
606     if (priv->rtcpsinkpad != NULL)
607       goto exists;
608
609     result = create_rtcp_sink (jitterbuffer);
610   } else
611     goto wrong_template;
612
613   return result;
614
615   /* ERRORS */
616 wrong_template:
617   {
618     g_warning ("gstrtpjitterbuffer: this is not our template");
619     return NULL;
620   }
621 exists:
622   {
623     g_warning ("gstrtpjitterbuffer: pad already requested");
624     return NULL;
625   }
626 }
627
628 static void
629 gst_rtp_jitter_buffer_release_pad (GstElement * element, GstPad * pad)
630 {
631   GstRtpJitterBuffer *jitterbuffer;
632   GstRtpJitterBufferPrivate *priv;
633
634   g_return_if_fail (GST_IS_RTP_JITTER_BUFFER (element));
635   g_return_if_fail (GST_IS_PAD (pad));
636
637   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
638   priv = jitterbuffer->priv;
639
640   GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
641
642   if (priv->rtcpsinkpad == pad) {
643     remove_rtcp_sink (jitterbuffer);
644   } else
645     goto wrong_pad;
646
647   return;
648
649   /* ERRORS */
650 wrong_pad:
651   {
652     g_warning ("gstjitterbuffer: asked to release an unknown pad");
653     return;
654   }
655 }
656
657 static GstClock *
658 gst_rtp_jitter_buffer_provide_clock (GstElement * element)
659 {
660   return gst_system_clock_obtain ();
661 }
662
663 static void
664 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer)
665 {
666   GstRtpJitterBufferPrivate *priv;
667
668   priv = jitterbuffer->priv;
669
670   /* this will trigger a new pt-map request signal, FIXME, do something better. */
671
672   JBUF_LOCK (priv);
673   priv->clock_rate = -1;
674   /* do not clear current content, but refresh state for new arrival */
675   GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
676   rtp_jitter_buffer_reset_skew (priv->jbuf);
677   priv->last_popped_seqnum = -1;
678   priv->next_seqnum = -1;
679   JBUF_UNLOCK (priv);
680 }
681
682 static GstClockTime
683 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jbuf, gboolean active,
684     guint64 offset)
685 {
686   GstRtpJitterBufferPrivate *priv;
687   GstClockTime last_out;
688   GstBuffer *head;
689
690   priv = jbuf->priv;
691
692   JBUF_LOCK (priv);
693   GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
694       active, GST_TIME_ARGS (offset));
695
696   if (active != priv->active) {
697     /* add the amount of time spent in paused to the output offset. All
698      * outgoing buffers will have this offset applied to their timestamps in
699      * order to make them arrive in time in the sink. */
700     priv->out_offset = offset;
701     GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
702         GST_TIME_ARGS (priv->out_offset));
703     priv->active = active;
704     JBUF_SIGNAL (priv);
705   }
706   if (!active) {
707     rtp_jitter_buffer_set_buffering (priv->jbuf, TRUE);
708   }
709   if ((head = rtp_jitter_buffer_peek (priv->jbuf))) {
710     /* head buffer timestamp and offset gives our output time */
711     last_out = GST_BUFFER_TIMESTAMP (head) + priv->ts_offset;
712   } else {
713     /* use last known time when the buffer is empty */
714     last_out = priv->last_out_time;
715   }
716   JBUF_UNLOCK (priv);
717
718   return last_out;
719 }
720
721 static GstCaps *
722 gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter)
723 {
724   GstRtpJitterBuffer *jitterbuffer;
725   GstRtpJitterBufferPrivate *priv;
726   GstPad *other;
727   GstCaps *caps;
728   GstCaps *templ;
729
730   jitterbuffer = GST_RTP_JITTER_BUFFER (gst_pad_get_parent (pad));
731   priv = jitterbuffer->priv;
732
733   other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
734
735   caps = gst_pad_peer_query_caps (other, filter);
736
737   templ = gst_pad_get_pad_template_caps (pad);
738   if (caps == NULL) {
739     GST_DEBUG_OBJECT (jitterbuffer, "use template");
740     caps = templ;
741   } else {
742     GstCaps *intersect;
743
744     GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
745
746     intersect = gst_caps_intersect (caps, templ);
747     gst_caps_unref (caps);
748     gst_caps_unref (templ);
749
750     caps = intersect;
751   }
752   gst_object_unref (jitterbuffer);
753
754   return caps;
755 }
756
757 /*
758  * Must be called with JBUF_LOCK held
759  */
760
761 static gboolean
762 gst_jitter_buffer_sink_parse_caps (GstRtpJitterBuffer * jitterbuffer,
763     GstCaps * caps)
764 {
765   GstRtpJitterBufferPrivate *priv;
766   GstStructure *caps_struct;
767   guint val;
768   GstClockTime tval;
769
770   priv = jitterbuffer->priv;
771
772   /* first parse the caps */
773   caps_struct = gst_caps_get_structure (caps, 0);
774
775   GST_DEBUG_OBJECT (jitterbuffer, "got caps");
776
777   /* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
778    * measure the amount of data in the buffer */
779   if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
780     goto error;
781
782   if (priv->clock_rate <= 0)
783     goto wrong_rate;
784
785   GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
786
787   /* The clock base is the RTP timestamp corrsponding to the npt-start value. We
788    * can use this to track the amount of time elapsed on the sender. */
789   if (gst_structure_get_uint (caps_struct, "clock-base", &val))
790     priv->clock_base = val;
791   else
792     priv->clock_base = -1;
793
794   priv->ext_timestamp = priv->clock_base;
795
796   GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
797       priv->clock_base);
798
799   if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
800     /* first expected seqnum, only update when we didn't have a previous base. */
801     if (priv->next_in_seqnum == -1)
802       priv->next_in_seqnum = val;
803     if (priv->next_seqnum == -1)
804       priv->next_seqnum = val;
805   }
806
807   GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
808
809   /* the start and stop times. The seqnum-base corresponds to the start time. We
810    * will keep track of the seqnums on the output and when we reach the one
811    * corresponding to npt-stop, we emit the npt-stop-reached signal */
812   if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
813     priv->npt_start = tval;
814   else
815     priv->npt_start = 0;
816
817   if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
818     priv->npt_stop = tval;
819   else
820     priv->npt_stop = -1;
821
822   GST_DEBUG_OBJECT (jitterbuffer,
823       "npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
824       GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
825
826   return TRUE;
827
828   /* ERRORS */
829 error:
830   {
831     GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
832     return FALSE;
833   }
834 wrong_rate:
835   {
836     GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
837     return FALSE;
838   }
839 }
840
841 static void
842 gst_rtp_jitter_buffer_flush_start (GstRtpJitterBuffer * jitterbuffer)
843 {
844   GstRtpJitterBufferPrivate *priv;
845
846   priv = jitterbuffer->priv;
847
848   JBUF_LOCK (priv);
849   /* mark ourselves as flushing */
850   priv->srcresult = GST_FLOW_FLUSHING;
851   GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
852   /* this unblocks any waiting pops on the src pad task */
853   JBUF_SIGNAL (priv);
854   /* unlock clock, we just unschedule, the entry will be released by the
855    * locking streaming thread. */
856   if (priv->clock_id) {
857     gst_clock_id_unschedule (priv->clock_id);
858     priv->unscheduled = TRUE;
859   }
860   JBUF_UNLOCK (priv);
861 }
862
863 static void
864 gst_rtp_jitter_buffer_flush_stop (GstRtpJitterBuffer * jitterbuffer)
865 {
866   GstRtpJitterBufferPrivate *priv;
867
868   priv = jitterbuffer->priv;
869
870   JBUF_LOCK (priv);
871   GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
872   /* Mark as non flushing */
873   priv->srcresult = GST_FLOW_OK;
874   gst_segment_init (&priv->segment, GST_FORMAT_TIME);
875   priv->last_popped_seqnum = -1;
876   priv->last_out_time = -1;
877   priv->next_seqnum = -1;
878   priv->next_in_seqnum = -1;
879   priv->clock_rate = -1;
880   priv->eos = FALSE;
881   priv->estimated_eos = -1;
882   priv->last_elapsed = 0;
883   priv->reached_npt_stop = FALSE;
884   priv->ext_timestamp = -1;
885   GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
886   rtp_jitter_buffer_flush (priv->jbuf);
887   rtp_jitter_buffer_reset_skew (priv->jbuf);
888   JBUF_UNLOCK (priv);
889 }
890
891 static gboolean
892 gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
893     GstPadMode mode, gboolean active)
894 {
895   gboolean result;
896   GstRtpJitterBuffer *jitterbuffer = NULL;
897
898   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
899
900   switch (mode) {
901     case GST_PAD_MODE_PUSH:
902       if (active) {
903         /* allow data processing */
904         gst_rtp_jitter_buffer_flush_stop (jitterbuffer);
905
906         /* start pushing out buffers */
907         GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
908         result = gst_pad_start_task (jitterbuffer->priv->srcpad,
909             (GstTaskFunction) gst_rtp_jitter_buffer_loop, jitterbuffer, NULL);
910       } else {
911         /* make sure all data processing stops ASAP */
912         gst_rtp_jitter_buffer_flush_start (jitterbuffer);
913
914         /* NOTE this will hardlock if the state change is called from the src pad
915          * task thread because we will _join() the thread. */
916         GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
917         result = gst_pad_stop_task (pad);
918       }
919       break;
920     default:
921       result = FALSE;
922       break;
923   }
924   return result;
925 }
926
927 static GstStateChangeReturn
928 gst_rtp_jitter_buffer_change_state (GstElement * element,
929     GstStateChange transition)
930 {
931   GstRtpJitterBuffer *jitterbuffer;
932   GstRtpJitterBufferPrivate *priv;
933   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
934
935   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
936   priv = jitterbuffer->priv;
937
938   switch (transition) {
939     case GST_STATE_CHANGE_NULL_TO_READY:
940       break;
941     case GST_STATE_CHANGE_READY_TO_PAUSED:
942       JBUF_LOCK (priv);
943       /* reset negotiated values */
944       priv->clock_rate = -1;
945       priv->clock_base = -1;
946       priv->peer_latency = 0;
947       priv->last_pt = -1;
948       /* block until we go to PLAYING */
949       priv->blocked = TRUE;
950       JBUF_UNLOCK (priv);
951       break;
952     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
953       JBUF_LOCK (priv);
954       /* unblock to allow streaming in PLAYING */
955       priv->blocked = FALSE;
956       JBUF_SIGNAL (priv);
957       JBUF_UNLOCK (priv);
958       break;
959     default:
960       break;
961   }
962
963   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
964
965   switch (transition) {
966     case GST_STATE_CHANGE_READY_TO_PAUSED:
967       /* we are a live element because we sync to the clock, which we can only
968        * do in the PLAYING state */
969       if (ret != GST_STATE_CHANGE_FAILURE)
970         ret = GST_STATE_CHANGE_NO_PREROLL;
971       break;
972     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
973       JBUF_LOCK (priv);
974       /* block to stop streaming when PAUSED */
975       priv->blocked = TRUE;
976       JBUF_UNLOCK (priv);
977       if (ret != GST_STATE_CHANGE_FAILURE)
978         ret = GST_STATE_CHANGE_NO_PREROLL;
979       break;
980     case GST_STATE_CHANGE_PAUSED_TO_READY:
981       gst_buffer_replace (&priv->last_sr, NULL);
982       break;
983     case GST_STATE_CHANGE_READY_TO_NULL:
984       break;
985     default:
986       break;
987   }
988
989   return ret;
990 }
991
992 static gboolean
993 gst_rtp_jitter_buffer_src_event (GstPad * pad, GstObject * parent,
994     GstEvent * event)
995 {
996   gboolean ret = TRUE;
997   GstRtpJitterBuffer *jitterbuffer;
998   GstRtpJitterBufferPrivate *priv;
999
1000   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1001   priv = jitterbuffer->priv;
1002
1003   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1004
1005   switch (GST_EVENT_TYPE (event)) {
1006     case GST_EVENT_LATENCY:
1007     {
1008       GstClockTime latency;
1009
1010       gst_event_parse_latency (event, &latency);
1011
1012       JBUF_LOCK (priv);
1013       /* adjust the overall buffer delay to the total pipeline latency in
1014        * buffering mode because if downstream consumes too fast (because of
1015        * large latency or queues, we would start rebuffering again. */
1016       if (rtp_jitter_buffer_get_mode (priv->jbuf) ==
1017           RTP_JITTER_BUFFER_MODE_BUFFER) {
1018         rtp_jitter_buffer_set_delay (priv->jbuf, latency);
1019       }
1020       JBUF_UNLOCK (priv);
1021
1022       ret = gst_pad_push_event (priv->sinkpad, event);
1023       break;
1024     }
1025     default:
1026       ret = gst_pad_push_event (priv->sinkpad, event);
1027       break;
1028   }
1029
1030   return ret;
1031 }
1032
1033 static gboolean
1034 gst_rtp_jitter_buffer_sink_event (GstPad * pad, GstObject * parent,
1035     GstEvent * event)
1036 {
1037   gboolean ret = TRUE;
1038   GstRtpJitterBuffer *jitterbuffer;
1039   GstRtpJitterBufferPrivate *priv;
1040
1041   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1042   priv = jitterbuffer->priv;
1043
1044   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1045
1046   switch (GST_EVENT_TYPE (event)) {
1047     case GST_EVENT_CAPS:
1048     {
1049       GstCaps *caps;
1050
1051       gst_event_parse_caps (event, &caps);
1052
1053       JBUF_LOCK (priv);
1054       ret = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1055       JBUF_UNLOCK (priv);
1056
1057       /* set same caps on srcpad on success */
1058       if (ret)
1059         ret = gst_pad_push_event (priv->srcpad, event);
1060       else
1061         gst_event_unref (event);
1062       break;
1063     }
1064     case GST_EVENT_SEGMENT:
1065     {
1066       gst_event_copy_segment (event, &priv->segment);
1067
1068       /* we need time for now */
1069       if (priv->segment.format != GST_FORMAT_TIME)
1070         goto newseg_wrong_format;
1071
1072       GST_DEBUG_OBJECT (jitterbuffer,
1073           "newsegment:  %" GST_SEGMENT_FORMAT, &priv->segment);
1074
1075       /* FIXME, push SEGMENT in the queue. Sorting order might be difficult. */
1076       ret = gst_pad_push_event (priv->srcpad, event);
1077       break;
1078     }
1079     case GST_EVENT_FLUSH_START:
1080       gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1081       ret = gst_pad_push_event (priv->srcpad, event);
1082       break;
1083     case GST_EVENT_FLUSH_STOP:
1084       ret = gst_pad_push_event (priv->srcpad, event);
1085       ret =
1086           gst_rtp_jitter_buffer_src_activate_mode (priv->srcpad, parent,
1087           GST_PAD_MODE_PUSH, TRUE);
1088       break;
1089     case GST_EVENT_EOS:
1090     {
1091       /* push EOS in queue. We always push it at the head */
1092       JBUF_LOCK (priv);
1093       /* check for flushing, we need to discard the event and return FALSE when
1094        * we are flushing */
1095       ret = priv->srcresult == GST_FLOW_OK;
1096       if (ret && !priv->eos) {
1097         GST_INFO_OBJECT (jitterbuffer, "queuing EOS");
1098         priv->eos = TRUE;
1099         JBUF_SIGNAL (priv);
1100       } else if (priv->eos) {
1101         GST_DEBUG_OBJECT (jitterbuffer, "dropping EOS, we are already EOS");
1102       } else {
1103         GST_DEBUG_OBJECT (jitterbuffer, "dropping EOS, reason %s",
1104             gst_flow_get_name (priv->srcresult));
1105       }
1106       JBUF_UNLOCK (priv);
1107       gst_event_unref (event);
1108       break;
1109     }
1110     default:
1111       ret = gst_pad_push_event (priv->srcpad, event);
1112       break;
1113   }
1114
1115 done:
1116
1117   return ret;
1118
1119   /* ERRORS */
1120 newseg_wrong_format:
1121   {
1122     GST_DEBUG_OBJECT (jitterbuffer, "received non TIME newsegment");
1123     ret = FALSE;
1124     gst_event_unref (event);
1125     goto done;
1126   }
1127 }
1128
1129 static gboolean
1130 gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
1131     GstEvent * event)
1132 {
1133   gboolean ret = TRUE;
1134   GstRtpJitterBuffer *jitterbuffer;
1135
1136   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1137
1138   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1139
1140   switch (GST_EVENT_TYPE (event)) {
1141     case GST_EVENT_FLUSH_START:
1142       gst_event_unref (event);
1143       break;
1144     case GST_EVENT_FLUSH_STOP:
1145       gst_event_unref (event);
1146       break;
1147     default:
1148       ret = gst_pad_event_default (pad, parent, event);
1149       break;
1150   }
1151
1152   return ret;
1153 }
1154
1155 /*
1156  * Must be called with JBUF_LOCK held, will release the LOCK when emiting the
1157  * signal. The function returns GST_FLOW_ERROR when a parsing error happened and
1158  * GST_FLOW_FLUSHING when the element is shutting down. On success
1159  * GST_FLOW_OK is returned.
1160  */
1161 static GstFlowReturn
1162 gst_rtp_jitter_buffer_get_clock_rate (GstRtpJitterBuffer * jitterbuffer,
1163     guint8 pt)
1164 {
1165   GValue ret = { 0 };
1166   GValue args[2] = { {0}, {0} };
1167   GstCaps *caps;
1168   gboolean res;
1169
1170   g_value_init (&args[0], GST_TYPE_ELEMENT);
1171   g_value_set_object (&args[0], jitterbuffer);
1172   g_value_init (&args[1], G_TYPE_UINT);
1173   g_value_set_uint (&args[1], pt);
1174
1175   g_value_init (&ret, GST_TYPE_CAPS);
1176   g_value_set_boxed (&ret, NULL);
1177
1178   JBUF_UNLOCK (jitterbuffer->priv);
1179   g_signal_emitv (args, gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
1180       &ret);
1181   JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
1182
1183   g_value_unset (&args[0]);
1184   g_value_unset (&args[1]);
1185   caps = (GstCaps *) g_value_dup_boxed (&ret);
1186   g_value_unset (&ret);
1187   if (!caps)
1188     goto no_caps;
1189
1190   res = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1191   gst_caps_unref (caps);
1192
1193   if (G_UNLIKELY (!res))
1194     goto parse_failed;
1195
1196   return GST_FLOW_OK;
1197
1198   /* ERRORS */
1199 no_caps:
1200   {
1201     GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
1202     return GST_FLOW_ERROR;
1203   }
1204 out_flushing:
1205   {
1206     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1207     return GST_FLOW_FLUSHING;
1208   }
1209 parse_failed:
1210   {
1211     GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
1212     return GST_FLOW_ERROR;
1213   }
1214 }
1215
1216 /* call with jbuf lock held */
1217 static void
1218 check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint * percent)
1219 {
1220   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1221
1222   /* too short a stream, or too close to EOS will never really fill buffer */
1223   if (*percent != -1 && priv->npt_stop != -1 &&
1224       priv->npt_stop - priv->npt_start <=
1225       rtp_jitter_buffer_get_delay (priv->jbuf)) {
1226     GST_DEBUG_OBJECT (jitterbuffer, "short stream; faking full buffer");
1227     rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
1228     *percent = 100;
1229   }
1230 }
1231
1232 static void
1233 post_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
1234 {
1235   GstMessage *message;
1236
1237   /* Post a buffering message */
1238   message = gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
1239   gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
1240
1241   gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), message);
1242 }
1243
1244 static GstFlowReturn
1245 gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
1246     GstBuffer * buffer)
1247 {
1248   GstRtpJitterBuffer *jitterbuffer;
1249   GstRtpJitterBufferPrivate *priv;
1250   guint16 seqnum;
1251   GstFlowReturn ret = GST_FLOW_OK;
1252   GstClockTime timestamp;
1253   guint64 latency_ts;
1254   gboolean tail;
1255   gint percent = -1;
1256   guint8 pt;
1257   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
1258
1259   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1260
1261   priv = jitterbuffer->priv;
1262
1263   if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
1264     goto invalid_buffer;
1265
1266   pt = gst_rtp_buffer_get_payload_type (&rtp);
1267   seqnum = gst_rtp_buffer_get_seq (&rtp);
1268   gst_rtp_buffer_unmap (&rtp);
1269
1270   /* take the timestamp of the buffer. This is the time when the packet was
1271    * received and is used to calculate jitter and clock skew. We will adjust
1272    * this timestamp with the smoothed value after processing it in the
1273    * jitterbuffer. */
1274   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1275   /* bring to running time */
1276   timestamp = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME,
1277       timestamp);
1278
1279   GST_DEBUG_OBJECT (jitterbuffer,
1280       "Received packet #%d at time %" GST_TIME_FORMAT, seqnum,
1281       GST_TIME_ARGS (timestamp));
1282
1283   JBUF_LOCK_CHECK (priv, out_flushing);
1284
1285   if (G_UNLIKELY (priv->last_pt != pt)) {
1286     GstCaps *caps;
1287
1288     GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
1289         pt);
1290
1291     priv->last_pt = pt;
1292     /* reset clock-rate so that we get a new one */
1293     priv->clock_rate = -1;
1294
1295     /* Try to get the clock-rate from the caps first if we can. If there are no
1296      * caps we must fire the signal to get the clock-rate. */
1297     if ((caps = gst_pad_get_current_caps (pad))) {
1298       gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1299       gst_caps_unref (caps);
1300     }
1301   }
1302
1303   if (G_UNLIKELY (priv->clock_rate == -1)) {
1304     /* no clock rate given on the caps, try to get one with the signal */
1305     if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
1306             pt) == GST_FLOW_FLUSHING)
1307       goto out_flushing;
1308
1309     if (G_UNLIKELY (priv->clock_rate == -1))
1310       goto no_clock_rate;
1311   }
1312
1313   /* don't accept more data on EOS */
1314   if (G_UNLIKELY (priv->eos))
1315     goto have_eos;
1316
1317   /* now check against our expected seqnum */
1318   if (G_LIKELY (priv->next_in_seqnum != -1)) {
1319     gint gap;
1320     gboolean reset = FALSE;
1321
1322     gap = gst_rtp_buffer_compare_seqnum (priv->next_in_seqnum, seqnum);
1323     if (G_UNLIKELY (gap != 0)) {
1324       GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
1325           priv->next_in_seqnum, seqnum, gap);
1326       /* priv->next_in_seqnum >= seqnum, this packet is too late or the
1327        * sender might have been restarted with different seqnum. */
1328       if (gap < -RTP_MAX_MISORDER) {
1329         GST_DEBUG_OBJECT (jitterbuffer, "reset: buffer too old %d", gap);
1330         reset = TRUE;
1331       }
1332       /* priv->next_in_seqnum < seqnum, this is a new packet */
1333       else if (G_UNLIKELY (gap > RTP_MAX_DROPOUT)) {
1334         GST_DEBUG_OBJECT (jitterbuffer, "reset: too many dropped packets %d",
1335             gap);
1336         reset = TRUE;
1337       } else {
1338         GST_DEBUG_OBJECT (jitterbuffer, "tolerable gap");
1339       }
1340     }
1341     if (G_UNLIKELY (reset)) {
1342       GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
1343       rtp_jitter_buffer_flush (priv->jbuf);
1344       rtp_jitter_buffer_reset_skew (priv->jbuf);
1345       priv->last_popped_seqnum = -1;
1346       priv->next_seqnum = seqnum;
1347     }
1348   }
1349   priv->next_in_seqnum = (seqnum + 1) & 0xffff;
1350
1351   /* let's check if this buffer is too late, we can only accept packets with
1352    * bigger seqnum than the one we last pushed. */
1353   if (G_LIKELY (priv->last_popped_seqnum != -1)) {
1354     gint gap;
1355
1356     gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
1357
1358     /* priv->last_popped_seqnum >= seqnum, we're too late. */
1359     if (G_UNLIKELY (gap <= 0))
1360       goto too_late;
1361   }
1362
1363   /* let's drop oldest packet if the queue is already full and drop-on-latency
1364    * is set. We can only do this when there actually is a latency. When no
1365    * latency is set, we just pump it in the queue and let the other end push it
1366    * out as fast as possible. */
1367   if (priv->latency_ms && priv->drop_on_latency) {
1368     latency_ts =
1369         gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
1370
1371     if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
1372       GstBuffer *old_buf;
1373
1374       old_buf = rtp_jitter_buffer_pop (priv->jbuf, &percent);
1375
1376       GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
1377           old_buf);
1378
1379       gst_buffer_unref (old_buf);
1380     }
1381   }
1382
1383   /* we need to make the metadata writable before pushing it in the jitterbuffer
1384    * because the jitterbuffer will update the timestamp */
1385   buffer = gst_buffer_make_writable (buffer);
1386
1387   /* now insert the packet into the queue in sorted order. This function returns
1388    * FALSE if a packet with the same seqnum was already in the queue, meaning we
1389    * have a duplicate. */
1390   if (G_UNLIKELY (!rtp_jitter_buffer_insert (priv->jbuf, buffer, timestamp,
1391               priv->clock_rate, &tail, &percent)))
1392     goto duplicate;
1393
1394   /* signal addition of new buffer when the _loop is waiting. */
1395   if (priv->waiting)
1396     JBUF_SIGNAL (priv);
1397
1398   /* let's unschedule and unblock any waiting buffers. We only want to do this
1399    * when the tail buffer changed */
1400   if (G_UNLIKELY (priv->clock_id && tail)) {
1401     GST_DEBUG_OBJECT (jitterbuffer,
1402         "Unscheduling waiting buffer, new tail buffer");
1403     gst_clock_id_unschedule (priv->clock_id);
1404     priv->unscheduled = TRUE;
1405   }
1406
1407   GST_DEBUG_OBJECT (jitterbuffer, "Pushed packet #%d, now %d packets, tail: %d",
1408       seqnum, rtp_jitter_buffer_num_packets (priv->jbuf), tail);
1409
1410   check_buffering_percent (jitterbuffer, &percent);
1411
1412 finished:
1413   JBUF_UNLOCK (priv);
1414
1415   if (percent != -1)
1416     post_buffering_percent (jitterbuffer, percent);
1417
1418   return ret;
1419
1420   /* ERRORS */
1421 invalid_buffer:
1422   {
1423     /* this is not fatal but should be filtered earlier */
1424     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
1425         ("Received invalid RTP payload, dropping"));
1426     gst_buffer_unref (buffer);
1427     return GST_FLOW_OK;
1428   }
1429 no_clock_rate:
1430   {
1431     GST_WARNING_OBJECT (jitterbuffer,
1432         "No clock-rate in caps!, dropping buffer");
1433     gst_buffer_unref (buffer);
1434     goto finished;
1435   }
1436 out_flushing:
1437   {
1438     ret = priv->srcresult;
1439     GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
1440     gst_buffer_unref (buffer);
1441     goto finished;
1442   }
1443 have_eos:
1444   {
1445     ret = GST_FLOW_EOS;
1446     GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
1447     gst_buffer_unref (buffer);
1448     goto finished;
1449   }
1450 too_late:
1451   {
1452     GST_WARNING_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
1453         " popped, dropping", seqnum, priv->last_popped_seqnum);
1454     priv->num_late++;
1455     gst_buffer_unref (buffer);
1456     goto finished;
1457   }
1458 duplicate:
1459   {
1460     GST_WARNING_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
1461         seqnum);
1462     priv->num_duplicates++;
1463     gst_buffer_unref (buffer);
1464     goto finished;
1465   }
1466 }
1467
1468 static GstClockTime
1469 apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1470 {
1471   GstRtpJitterBufferPrivate *priv;
1472
1473   priv = jitterbuffer->priv;
1474
1475   if (timestamp == -1)
1476     return -1;
1477
1478   /* apply the timestamp offset, this is used for inter stream sync */
1479   timestamp += priv->ts_offset;
1480   /* add the offset, this is used when buffering */
1481   timestamp += priv->out_offset;
1482
1483   return timestamp;
1484 }
1485
1486 static GstClockTime
1487 get_sync_time (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1488 {
1489   GstClockTime result;
1490   GstRtpJitterBufferPrivate *priv;
1491
1492   priv = jitterbuffer->priv;
1493
1494   result = timestamp + GST_ELEMENT_CAST (jitterbuffer)->base_time;
1495   /* add latency, this includes our own latency and the peer latency. */
1496   result += priv->latency_ns;
1497   result += priv->peer_latency;
1498
1499   return result;
1500 }
1501
1502 static gboolean
1503 eos_reached (GstClock * clock, GstClockTime time, GstClockID id,
1504     GstRtpJitterBuffer * jitterbuffer)
1505 {
1506   GstRtpJitterBufferPrivate *priv;
1507
1508   priv = jitterbuffer->priv;
1509
1510   JBUF_LOCK_CHECK (priv, flushing);
1511   if (priv->waiting) {
1512     GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
1513     priv->reached_npt_stop = TRUE;
1514     JBUF_SIGNAL (priv);
1515   }
1516   JBUF_UNLOCK (priv);
1517
1518   return TRUE;
1519
1520   /* ERRORS */
1521 flushing:
1522   {
1523     JBUF_UNLOCK (priv);
1524     return FALSE;
1525   }
1526 }
1527
1528 static GstClockTime
1529 compute_elapsed (GstRtpJitterBuffer * jitterbuffer, GstBuffer * outbuf)
1530 {
1531   guint64 ext_time, elapsed;
1532   guint32 rtp_time;
1533   GstRtpJitterBufferPrivate *priv;
1534   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
1535
1536   priv = jitterbuffer->priv;
1537   gst_rtp_buffer_map (outbuf, GST_MAP_READ, &rtp);
1538   rtp_time = gst_rtp_buffer_get_timestamp (&rtp);
1539   gst_rtp_buffer_unmap (&rtp);
1540
1541   GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
1542       G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
1543
1544   if (rtp_time < priv->ext_timestamp) {
1545     ext_time = priv->ext_timestamp;
1546   } else {
1547     ext_time = gst_rtp_buffer_ext_timestamp (&priv->ext_timestamp, rtp_time);
1548   }
1549
1550   if (ext_time > priv->clock_base)
1551     elapsed = ext_time - priv->clock_base;
1552   else
1553     elapsed = 0;
1554
1555   elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
1556   return elapsed;
1557 }
1558
1559 /*
1560  * This funcion will push out buffers on the source pad.
1561  *
1562  * For each pushed buffer, the seqnum is recorded, if the next buffer B has a
1563  * different seqnum (missing packets before B), this function will wait for the
1564  * missing packet to arrive up to the timestamp of buffer B.
1565  */
1566 static void
1567 gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer)
1568 {
1569   GstRtpJitterBufferPrivate *priv;
1570   GstBuffer *outbuf;
1571   GstFlowReturn result;
1572   guint16 seqnum;
1573   guint32 next_seqnum;
1574   GstClockTime timestamp, out_time;
1575   gboolean discont = FALSE;
1576   gint gap;
1577   GstClock *clock;
1578   GstClockID id;
1579   GstClockTime sync_time;
1580   gint percent = -1;
1581   GstRTPBuffer rtp = { NULL, };
1582
1583   priv = jitterbuffer->priv;
1584
1585   JBUF_LOCK_CHECK (priv, flushing);
1586 again:
1587   GST_DEBUG_OBJECT (jitterbuffer, "Peeking item");
1588   while (TRUE) {
1589     id = NULL;
1590     /* always wait if we are blocked */
1591     if (G_LIKELY (!priv->blocked)) {
1592       /* we're buffering but not EOS, wait. */
1593       if (!priv->eos && (!priv->active
1594               || rtp_jitter_buffer_is_buffering (priv->jbuf))) {
1595         GstClockTime elapsed, delay, left;
1596
1597         if (priv->estimated_eos == -1)
1598           goto do_wait;
1599
1600         outbuf = rtp_jitter_buffer_peek (priv->jbuf);
1601         if (outbuf != NULL) {
1602           elapsed = compute_elapsed (jitterbuffer, outbuf);
1603           if (GST_BUFFER_DURATION_IS_VALID (outbuf))
1604             elapsed += GST_BUFFER_DURATION (outbuf);
1605         } else {
1606           GST_INFO_OBJECT (jitterbuffer, "no buffer, using last_elapsed");
1607           elapsed = priv->last_elapsed;
1608         }
1609
1610         delay = rtp_jitter_buffer_get_delay (priv->jbuf);
1611
1612         if (priv->estimated_eos > elapsed)
1613           left = priv->estimated_eos - elapsed;
1614         else
1615           left = 0;
1616
1617         GST_INFO_OBJECT (jitterbuffer, "buffering, elapsed %" GST_TIME_FORMAT
1618             " estimated_eos %" GST_TIME_FORMAT " left %" GST_TIME_FORMAT
1619             " delay %" GST_TIME_FORMAT,
1620             GST_TIME_ARGS (elapsed), GST_TIME_ARGS (priv->estimated_eos),
1621             GST_TIME_ARGS (left), GST_TIME_ARGS (delay));
1622         if (left > delay)
1623           goto do_wait;
1624       }
1625       /* if we have a packet, we can exit the loop and grab it */
1626       if (rtp_jitter_buffer_num_packets (priv->jbuf) > 0)
1627         break;
1628       /* no packets but we are EOS, do eos logic */
1629       if (G_UNLIKELY (priv->eos))
1630         goto do_eos;
1631       /* underrun, wait for packets or flushing now if we are expecting an EOS
1632        * timeout, set the async timer for it too */
1633       if (priv->estimated_eos != -1 && !priv->reached_npt_stop) {
1634         sync_time = get_sync_time (jitterbuffer, priv->estimated_eos);
1635
1636         GST_OBJECT_LOCK (jitterbuffer);
1637         clock = GST_ELEMENT_CLOCK (jitterbuffer);
1638         if (clock) {
1639           GST_INFO_OBJECT (jitterbuffer, "scheduling timeout");
1640           id = gst_clock_new_single_shot_id (clock, sync_time);
1641           gst_clock_id_wait_async (id, (GstClockCallback) eos_reached,
1642               jitterbuffer, NULL);
1643         }
1644         GST_OBJECT_UNLOCK (jitterbuffer);
1645       }
1646     }
1647   do_wait:
1648     /* now we wait */
1649     GST_DEBUG_OBJECT (jitterbuffer, "waiting");
1650     priv->waiting = TRUE;
1651     JBUF_WAIT (priv);
1652     priv->waiting = FALSE;
1653     GST_DEBUG_OBJECT (jitterbuffer, "waiting done");
1654
1655     if (id) {
1656       /* unschedule any pending async notifications we might have */
1657       gst_clock_id_unschedule (id);
1658       gst_clock_id_unref (id);
1659     }
1660     if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))
1661       goto flushing;
1662
1663     if (id && priv->reached_npt_stop) {
1664       goto do_npt_stop;
1665     }
1666   }
1667
1668   /* peek a buffer, we're just looking at the timestamp and the sequence number.
1669    * If all is fine, we'll pop and push it. If the sequence number is wrong we
1670    * wait on the timestamp. In the chain function we will unlock the wait when a
1671    * new buffer is available. The peeked buffer is valid for as long as we hold
1672    * the jitterbuffer lock. */
1673   outbuf = rtp_jitter_buffer_peek (priv->jbuf);
1674
1675   /* get the seqnum and the next expected seqnum */
1676   gst_rtp_buffer_map (outbuf, GST_MAP_READ, &rtp);
1677   seqnum = gst_rtp_buffer_get_seq (&rtp);
1678   gst_rtp_buffer_unmap (&rtp);
1679   next_seqnum = priv->next_seqnum;
1680
1681   /* get the timestamp, this is already corrected for clock skew by the
1682    * jitterbuffer */
1683   timestamp = GST_BUFFER_TIMESTAMP (outbuf);
1684
1685   GST_DEBUG_OBJECT (jitterbuffer,
1686       "Peeked buffer #%d, expect #%d, timestamp %" GST_TIME_FORMAT
1687       ", now %d left", seqnum, next_seqnum, GST_TIME_ARGS (timestamp),
1688       rtp_jitter_buffer_num_packets (priv->jbuf));
1689
1690   /* apply our timestamp offset to the incomming buffer, this will be our output
1691    * timestamp. */
1692   out_time = apply_offset (jitterbuffer, timestamp);
1693
1694   /* get the gap between this and the previous packet. If we don't know the
1695    * previous packet seqnum assume no gap. */
1696   if (G_LIKELY (next_seqnum != -1)) {
1697     gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
1698
1699     /* if we have a packet that we already pushed or considered dropped, pop it
1700      * off and get the next packet */
1701     if (G_UNLIKELY (gap < 0)) {
1702       GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
1703           seqnum, next_seqnum);
1704       outbuf = rtp_jitter_buffer_pop (priv->jbuf, &percent);
1705       gst_buffer_unref (outbuf);
1706       goto again;
1707     }
1708   } else {
1709     GST_DEBUG_OBJECT (jitterbuffer, "no next seqnum known, first packet");
1710     gap = -1;
1711   }
1712
1713   /* If we don't know what the next seqnum should be (== -1) we have to wait
1714    * because it might be possible that we are not receiving this buffer in-order,
1715    * a buffer with a lower seqnum could arrive later and we want to push that
1716    * earlier buffer before this buffer then.
1717    * If we know the expected seqnum, we can compare it to the current seqnum to
1718    * determine if we have missing a packet. If we have a missing packet (which
1719    * must be before this packet) we can wait for it until the deadline for this
1720    * packet expires. */
1721   if (G_UNLIKELY (gap != 0 && out_time != -1)) {
1722     GstClockReturn ret;
1723     GstClockTime duration = GST_CLOCK_TIME_NONE;
1724     GstClockTimeDiff clock_jitter;
1725     guint32 lost_packets = 1;
1726     gboolean lost_packets_late = FALSE;
1727
1728     if (gap > 0) {
1729       /* we have a gap */
1730       GST_DEBUG_OBJECT (jitterbuffer,
1731           "Sequence number GAP detected: expected %d instead of %d (%d missing)",
1732           next_seqnum, seqnum, gap);
1733
1734       if (priv->last_out_time != -1) {
1735         GST_DEBUG_OBJECT (jitterbuffer,
1736             "out_time %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
1737             GST_TIME_ARGS (out_time), GST_TIME_ARGS (priv->last_out_time));
1738         /* interpolate between the current time and the last time based on
1739          * number of packets we are missing, this is the estimated duration
1740          * for the missing packet based on equidistant packet spacing. Also make
1741          * sure we never go negative. */
1742         if (out_time >= priv->last_out_time)
1743           duration = (out_time - priv->last_out_time) / (gap + 1);
1744         else
1745           goto lost;
1746
1747         GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
1748             GST_TIME_ARGS (duration));
1749         /* add this duration to the timestamp of the last packet we pushed */
1750         out_time = (priv->last_out_time + duration);
1751       }
1752     } else {
1753       /* we don't know what the next_seqnum should be, wait for the last
1754        * possible moment to push this buffer, maybe we get an earlier seqnum
1755        * while we wait */
1756       GST_DEBUG_OBJECT (jitterbuffer, "First buffer %d, do sync", seqnum);
1757     }
1758
1759     GST_OBJECT_LOCK (jitterbuffer);
1760     clock = GST_ELEMENT_CLOCK (jitterbuffer);
1761     if (!clock) {
1762       GST_OBJECT_UNLOCK (jitterbuffer);
1763       /* let's just push if there is no clock */
1764       GST_DEBUG_OBJECT (jitterbuffer, "No clock, push right away");
1765       goto push_buffer;
1766     }
1767
1768     /* prepare for sync against clock */
1769     sync_time = get_sync_time (jitterbuffer, out_time);
1770
1771     GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
1772         " with sync time %" GST_TIME_FORMAT,
1773         GST_TIME_ARGS (out_time), GST_TIME_ARGS (sync_time));
1774
1775     /* create an entry for the clock */
1776     id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
1777     priv->unscheduled = FALSE;
1778     GST_OBJECT_UNLOCK (jitterbuffer);
1779
1780     /* release the lock so that the other end can push stuff or unlock */
1781     JBUF_UNLOCK (priv);
1782
1783     ret = gst_clock_id_wait (id, &clock_jitter);
1784
1785     if (ret == GST_CLOCK_EARLY && gap > 0
1786         && clock_jitter > (priv->latency_ns + priv->peer_latency)) {
1787       GstClockTimeDiff total_duration;
1788       GstClockTime out_time_diff;
1789
1790       out_time_diff = apply_offset (jitterbuffer, timestamp) - out_time;
1791       total_duration = MIN (out_time_diff, clock_jitter);
1792
1793       if (duration > 0)
1794         lost_packets = total_duration / duration;
1795       else
1796         lost_packets = gap;
1797       total_duration = lost_packets * duration;
1798
1799       GST_DEBUG_OBJECT (jitterbuffer,
1800           "Current sync_time has expired a long time ago (+%" GST_TIME_FORMAT
1801           ") Cover up %d lost packets with duration %" GST_TIME_FORMAT,
1802           GST_TIME_ARGS (clock_jitter),
1803           lost_packets, GST_TIME_ARGS (total_duration));
1804
1805       duration = total_duration;
1806       lost_packets_late = TRUE;
1807     }
1808
1809     JBUF_LOCK (priv);
1810     /* and free the entry */
1811     gst_clock_id_unref (id);
1812     priv->clock_id = NULL;
1813
1814     /* at this point, the clock could have been unlocked by a timeout, a new
1815      * tail element was added to the queue or because we are shutting down. Check
1816      * for shutdown first. */
1817     if G_UNLIKELY
1818       ((priv->srcresult != GST_FLOW_OK))
1819           goto flushing;
1820
1821     /* if we got unscheduled and we are not flushing, it's because a new tail
1822      * element became available in the queue or we flushed the queue.
1823      * Grab it and try to push or sync. */
1824     if (ret == GST_CLOCK_UNSCHEDULED || priv->unscheduled) {
1825       GST_DEBUG_OBJECT (jitterbuffer,
1826           "Wait got unscheduled, will retry to push with new buffer");
1827       goto again;
1828     }
1829
1830   lost:
1831     /* we now timed out, this means we lost a packet or finished synchronizing
1832      * on the first buffer. */
1833     if (gap > 0) {
1834       GstEvent *event;
1835
1836       /* we had a gap and thus we lost some packets. Create an event for this.  */
1837       if (lost_packets > 1)
1838         GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", next_seqnum,
1839             next_seqnum + lost_packets - 1);
1840       else
1841         GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", next_seqnum);
1842
1843       priv->num_late += lost_packets;
1844       discont = TRUE;
1845
1846       /* update our expected next packet */
1847       priv->last_popped_seqnum = next_seqnum;
1848       priv->last_out_time += duration;
1849       priv->next_seqnum = (next_seqnum + lost_packets) & 0xffff;
1850
1851       if (priv->do_lost) {
1852         /* create paket lost event */
1853         event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
1854             gst_structure_new ("GstRTPPacketLost",
1855                 "seqnum", G_TYPE_UINT, (guint) next_seqnum,
1856                 "timestamp", G_TYPE_UINT64, out_time,
1857                 "duration", G_TYPE_UINT64, duration,
1858                 "late", G_TYPE_BOOLEAN, lost_packets_late, NULL));
1859         JBUF_UNLOCK (priv);
1860         gst_pad_push_event (priv->srcpad, event);
1861         JBUF_LOCK_CHECK (priv, flushing);
1862       }
1863       /* look for next packet */
1864       goto again;
1865     }
1866
1867     /* there was no known gap,just the first packet, exit the loop and push */
1868     GST_DEBUG_OBJECT (jitterbuffer, "First packet #%d synced", seqnum);
1869
1870     /* get new timestamp, latency might have changed */
1871     out_time = apply_offset (jitterbuffer, timestamp);
1872   }
1873 push_buffer:
1874
1875   /* when we get here we are ready to pop and push the buffer */
1876   outbuf = rtp_jitter_buffer_pop (priv->jbuf, &percent);
1877
1878   check_buffering_percent (jitterbuffer, &percent);
1879
1880   if (G_UNLIKELY (discont || priv->discont)) {
1881     /* set DISCONT flag when we missed a packet. We pushed the buffer writable
1882      * into the jitterbuffer so we can modify now. */
1883     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
1884     priv->discont = FALSE;
1885   }
1886
1887   /* apply timestamp with offset to buffer now */
1888   GST_BUFFER_PTS (outbuf) = out_time;
1889   GST_BUFFER_DTS (outbuf) = out_time;
1890
1891   /* update the elapsed time when we need to check against the npt stop time. */
1892   if (priv->npt_stop != -1 && priv->ext_timestamp != -1
1893       && priv->clock_base != -1 && priv->clock_rate > 0) {
1894     guint64 elapsed, estimated;
1895
1896     elapsed = compute_elapsed (jitterbuffer, outbuf);
1897
1898     if (elapsed > priv->last_elapsed || !priv->last_elapsed) {
1899       guint64 left;
1900
1901       priv->last_elapsed = elapsed;
1902
1903       left = priv->npt_stop - priv->npt_start;
1904       GST_LOG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT,
1905           GST_TIME_ARGS (left));
1906
1907       if (elapsed > 0)
1908         estimated = gst_util_uint64_scale (out_time, left, elapsed);
1909       else {
1910         /* if there is almost nothing left,
1911          * we may never advance enough to end up in the above case */
1912         if (left < GST_SECOND)
1913           estimated = GST_SECOND;
1914         else
1915           estimated = -1;
1916       }
1917
1918       GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
1919           GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
1920
1921       priv->estimated_eos = estimated;
1922     }
1923   }
1924
1925   /* now we are ready to push the buffer. Save the seqnum and release the lock
1926    * so the other end can push stuff in the queue again. */
1927   priv->last_popped_seqnum = seqnum;
1928   priv->last_out_time = out_time;
1929   priv->next_seqnum = (seqnum + 1) & 0xffff;
1930   JBUF_UNLOCK (priv);
1931
1932   if (percent != -1)
1933     post_buffering_percent (jitterbuffer, percent);
1934
1935   /* push buffer */
1936   GST_DEBUG_OBJECT (jitterbuffer,
1937       "Pushing buffer %d, timestamp %" GST_TIME_FORMAT, seqnum,
1938       GST_TIME_ARGS (out_time));
1939   result = gst_pad_push (priv->srcpad, outbuf);
1940   if (G_UNLIKELY (result != GST_FLOW_OK))
1941     goto pause;
1942
1943   return;
1944
1945   /* ERRORS */
1946 do_eos:
1947   {
1948     /* store result, we are flushing now */
1949     GST_DEBUG_OBJECT (jitterbuffer, "We are EOS, pushing EOS downstream");
1950     priv->srcresult = GST_FLOW_EOS;
1951     gst_pad_pause_task (priv->srcpad);
1952     JBUF_UNLOCK (priv);
1953     gst_pad_push_event (priv->srcpad, gst_event_new_eos ());
1954     return;
1955   }
1956 do_npt_stop:
1957   {
1958     /* store result, we are flushing now */
1959     GST_DEBUG_OBJECT (jitterbuffer, "We reached the NPT stop");
1960     JBUF_UNLOCK (priv);
1961
1962     g_signal_emit (jitterbuffer,
1963         gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP], 0, NULL);
1964     return;
1965   }
1966 flushing:
1967   {
1968     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1969     gst_pad_pause_task (priv->srcpad);
1970     JBUF_UNLOCK (priv);
1971     return;
1972   }
1973 pause:
1974   {
1975     GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s",
1976         gst_flow_get_name (result));
1977
1978     JBUF_LOCK (priv);
1979     /* store result */
1980     priv->srcresult = result;
1981     /* we don't post errors or anything because upstream will do that for us
1982      * when we pass the return value upstream. */
1983     gst_pad_pause_task (priv->srcpad);
1984     JBUF_UNLOCK (priv);
1985     return;
1986   }
1987 }
1988
1989 /* collect the info form the lastest RTCP packet and the jittebuffer sync, do
1990  * some sanity checks and then emit the handle-sync signal with the parameters.
1991  * This function must be called with the LOCK */
1992 static void
1993 do_handle_sync (GstRtpJitterBuffer * jitterbuffer)
1994 {
1995   GstRtpJitterBufferPrivate *priv;
1996   guint64 base_rtptime, base_time;
1997   guint32 clock_rate;
1998   guint64 last_rtptime;
1999   guint64 clock_base;
2000   guint64 ext_rtptime, diff;
2001   gboolean drop = FALSE;
2002
2003   priv = jitterbuffer->priv;
2004
2005   if (priv->last_sr == NULL) {
2006     GST_DEBUG_OBJECT (jitterbuffer, "dropping, no SR RTCP");
2007     return;
2008   }
2009
2010   /* get the last values from the jitterbuffer */
2011   rtp_jitter_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
2012       &clock_rate, &last_rtptime);
2013
2014   clock_base = priv->clock_base;
2015   ext_rtptime = priv->ext_rtptime;
2016
2017   GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
2018       G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
2019       ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
2020       ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
2021
2022   if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
2023     GST_DEBUG_OBJECT (jitterbuffer, "dropping, no RTP values");
2024     drop = TRUE;
2025   } else {
2026     /* we can't accept anything that happened before we did the last resync */
2027     if (base_rtptime > ext_rtptime) {
2028       GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
2029       drop = TRUE;
2030     } else {
2031       /* the SR RTP timestamp must be something close to what we last observed
2032        * in the jitterbuffer */
2033       if (ext_rtptime > last_rtptime) {
2034         /* check how far ahead it is to our RTP timestamps */
2035         diff = ext_rtptime - last_rtptime;
2036         /* if bigger than 1 second, we drop it */
2037         if (diff > clock_rate) {
2038           GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
2039           /* should drop this, but some RTSP servers end up with bogus
2040            * way too ahead RTCP packet when repeated PAUSE/PLAY,
2041            * so still trigger rptbin sync but invalidate RTCP data
2042            * (sync might use other methods) */
2043           ext_rtptime = -1;
2044         }
2045         GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
2046             G_GUINT64_FORMAT, last_rtptime, diff);
2047       }
2048     }
2049   }
2050
2051   if (!drop) {
2052     GstStructure *s;
2053
2054     s = gst_structure_new ("application/x-rtp-sync",
2055         "base-rtptime", G_TYPE_UINT64, base_rtptime,
2056         "base-time", G_TYPE_UINT64, base_time,
2057         "clock-rate", G_TYPE_UINT, clock_rate,
2058         "clock-base", G_TYPE_UINT64, clock_base,
2059         "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
2060         "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
2061
2062     GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
2063     JBUF_UNLOCK (priv);
2064     g_signal_emit (jitterbuffer,
2065         gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
2066     JBUF_LOCK (priv);
2067     gst_structure_free (s);
2068   } else {
2069     GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
2070   }
2071 }
2072
2073 static GstFlowReturn
2074 gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
2075     GstBuffer * buffer)
2076 {
2077   GstRtpJitterBuffer *jitterbuffer;
2078   GstRtpJitterBufferPrivate *priv;
2079   GstFlowReturn ret = GST_FLOW_OK;
2080   guint32 ssrc;
2081   GstRTCPPacket packet;
2082   guint64 ext_rtptime;
2083   guint32 rtptime;
2084   GstRTCPBuffer rtcp = { NULL, };
2085
2086   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
2087
2088   if (G_UNLIKELY (!gst_rtcp_buffer_validate (buffer)))
2089     goto invalid_buffer;
2090
2091   priv = jitterbuffer->priv;
2092
2093   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
2094
2095   if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
2096     goto empty_buffer;
2097
2098   /* first packet must be SR or RR or else the validate would have failed */
2099   switch (gst_rtcp_packet_get_type (&packet)) {
2100     case GST_RTCP_TYPE_SR:
2101       gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
2102           NULL, NULL);
2103       break;
2104     default:
2105       goto ignore_buffer;
2106   }
2107   gst_rtcp_buffer_unmap (&rtcp);
2108
2109   GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
2110
2111   JBUF_LOCK (priv);
2112   /* convert the RTP timestamp to our extended timestamp, using the same offset
2113    * we used in the jitterbuffer */
2114   ext_rtptime = priv->jbuf->ext_rtptime;
2115   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
2116
2117   priv->ext_rtptime = ext_rtptime;
2118   gst_buffer_replace (&priv->last_sr, buffer);
2119
2120   do_handle_sync (jitterbuffer);
2121   JBUF_UNLOCK (priv);
2122
2123 done:
2124   gst_buffer_unref (buffer);
2125
2126   return ret;
2127
2128 invalid_buffer:
2129   {
2130     /* this is not fatal but should be filtered earlier */
2131     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2132         ("Received invalid RTCP payload, dropping"));
2133     ret = GST_FLOW_OK;
2134     goto done;
2135   }
2136 empty_buffer:
2137   {
2138     /* this is not fatal but should be filtered earlier */
2139     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2140         ("Received empty RTCP payload, dropping"));
2141     gst_rtcp_buffer_unmap (&rtcp);
2142     ret = GST_FLOW_OK;
2143     goto done;
2144   }
2145 ignore_buffer:
2146   {
2147     GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
2148     gst_rtcp_buffer_unmap (&rtcp);
2149     ret = GST_FLOW_OK;
2150     goto done;
2151   }
2152 }
2153
2154 static gboolean
2155 gst_rtp_jitter_buffer_sink_query (GstPad * pad, GstObject * parent,
2156     GstQuery * query)
2157 {
2158   gboolean res = FALSE;
2159
2160   switch (GST_QUERY_TYPE (query)) {
2161     case GST_QUERY_CAPS:
2162     {
2163       GstCaps *filter, *caps;
2164
2165       gst_query_parse_caps (query, &filter);
2166       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
2167       gst_query_set_caps_result (query, caps);
2168       gst_caps_unref (caps);
2169       res = TRUE;
2170       break;
2171     }
2172     default:
2173       if (GST_QUERY_IS_SERIALIZED (query)) {
2174         GST_WARNING_OBJECT (pad, "unhandled serialized query");
2175         res = FALSE;
2176       } else {
2177         res = gst_pad_query_default (pad, parent, query);
2178       }
2179       break;
2180   }
2181   return res;
2182 }
2183
2184 static gboolean
2185 gst_rtp_jitter_buffer_src_query (GstPad * pad, GstObject * parent,
2186     GstQuery * query)
2187 {
2188   GstRtpJitterBuffer *jitterbuffer;
2189   GstRtpJitterBufferPrivate *priv;
2190   gboolean res = FALSE;
2191
2192   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
2193   priv = jitterbuffer->priv;
2194
2195   switch (GST_QUERY_TYPE (query)) {
2196     case GST_QUERY_LATENCY:
2197     {
2198       /* We need to send the query upstream and add the returned latency to our
2199        * own */
2200       GstClockTime min_latency, max_latency;
2201       gboolean us_live;
2202       GstClockTime our_latency;
2203
2204       if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
2205         gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
2206
2207         GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
2208             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
2209             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
2210
2211         /* store this so that we can safely sync on the peer buffers. */
2212         JBUF_LOCK (priv);
2213         priv->peer_latency = min_latency;
2214         our_latency = priv->latency_ns;
2215         JBUF_UNLOCK (priv);
2216
2217         GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
2218             GST_TIME_ARGS (our_latency));
2219
2220         /* we add some latency but can buffer an infinite amount of time */
2221         min_latency += our_latency;
2222         max_latency = -1;
2223
2224         GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
2225             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
2226             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
2227
2228         gst_query_set_latency (query, TRUE, min_latency, max_latency);
2229       }
2230       break;
2231     }
2232     case GST_QUERY_POSITION:
2233     {
2234       GstClockTime start, last_out;
2235       GstFormat fmt;
2236
2237       gst_query_parse_position (query, &fmt, NULL);
2238       if (fmt != GST_FORMAT_TIME) {
2239         res = gst_pad_query_default (pad, parent, query);
2240         break;
2241       }
2242
2243       JBUF_LOCK (priv);
2244       start = priv->npt_start;
2245       last_out = priv->last_out_time;
2246       JBUF_UNLOCK (priv);
2247
2248       GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
2249           ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
2250           GST_TIME_ARGS (last_out));
2251
2252       if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
2253         /* bring 0-based outgoing time to stream time */
2254         gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
2255         res = TRUE;
2256       } else {
2257         res = gst_pad_query_default (pad, parent, query);
2258       }
2259       break;
2260     }
2261     case GST_QUERY_CAPS:
2262     {
2263       GstCaps *filter, *caps;
2264
2265       gst_query_parse_caps (query, &filter);
2266       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
2267       gst_query_set_caps_result (query, caps);
2268       gst_caps_unref (caps);
2269       res = TRUE;
2270       break;
2271     }
2272     default:
2273       res = gst_pad_query_default (pad, parent, query);
2274       break;
2275   }
2276
2277   return res;
2278 }
2279
2280 static void
2281 gst_rtp_jitter_buffer_set_property (GObject * object,
2282     guint prop_id, const GValue * value, GParamSpec * pspec)
2283 {
2284   GstRtpJitterBuffer *jitterbuffer;
2285   GstRtpJitterBufferPrivate *priv;
2286
2287   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
2288   priv = jitterbuffer->priv;
2289
2290   switch (prop_id) {
2291     case PROP_LATENCY:
2292     {
2293       guint new_latency, old_latency;
2294
2295       new_latency = g_value_get_uint (value);
2296
2297       JBUF_LOCK (priv);
2298       old_latency = priv->latency_ms;
2299       priv->latency_ms = new_latency;
2300       priv->latency_ns = priv->latency_ms * GST_MSECOND;
2301       rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
2302       JBUF_UNLOCK (priv);
2303
2304       /* post message if latency changed, this will inform the parent pipeline
2305        * that a latency reconfiguration is possible/needed. */
2306       if (new_latency != old_latency) {
2307         GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
2308             GST_TIME_ARGS (new_latency * GST_MSECOND));
2309
2310         gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
2311             gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
2312       }
2313       break;
2314     }
2315     case PROP_DROP_ON_LATENCY:
2316       JBUF_LOCK (priv);
2317       priv->drop_on_latency = g_value_get_boolean (value);
2318       JBUF_UNLOCK (priv);
2319       break;
2320     case PROP_TS_OFFSET:
2321       JBUF_LOCK (priv);
2322       priv->ts_offset = g_value_get_int64 (value);
2323       /* FIXME, we don't really have a method for signaling a timestamp
2324        * DISCONT without also making this a data discont. */
2325       /* priv->discont = TRUE; */
2326       JBUF_UNLOCK (priv);
2327       break;
2328     case PROP_DO_LOST:
2329       JBUF_LOCK (priv);
2330       priv->do_lost = g_value_get_boolean (value);
2331       JBUF_UNLOCK (priv);
2332       break;
2333     case PROP_MODE:
2334       JBUF_LOCK (priv);
2335       rtp_jitter_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
2336       JBUF_UNLOCK (priv);
2337       break;
2338     default:
2339       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2340       break;
2341   }
2342 }
2343
2344 static void
2345 gst_rtp_jitter_buffer_get_property (GObject * object,
2346     guint prop_id, GValue * value, GParamSpec * pspec)
2347 {
2348   GstRtpJitterBuffer *jitterbuffer;
2349   GstRtpJitterBufferPrivate *priv;
2350
2351   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
2352   priv = jitterbuffer->priv;
2353
2354   switch (prop_id) {
2355     case PROP_LATENCY:
2356       JBUF_LOCK (priv);
2357       g_value_set_uint (value, priv->latency_ms);
2358       JBUF_UNLOCK (priv);
2359       break;
2360     case PROP_DROP_ON_LATENCY:
2361       JBUF_LOCK (priv);
2362       g_value_set_boolean (value, priv->drop_on_latency);
2363       JBUF_UNLOCK (priv);
2364       break;
2365     case PROP_TS_OFFSET:
2366       JBUF_LOCK (priv);
2367       g_value_set_int64 (value, priv->ts_offset);
2368       JBUF_UNLOCK (priv);
2369       break;
2370     case PROP_DO_LOST:
2371       JBUF_LOCK (priv);
2372       g_value_set_boolean (value, priv->do_lost);
2373       JBUF_UNLOCK (priv);
2374       break;
2375     case PROP_MODE:
2376       JBUF_LOCK (priv);
2377       g_value_set_enum (value, rtp_jitter_buffer_get_mode (priv->jbuf));
2378       JBUF_UNLOCK (priv);
2379       break;
2380     case PROP_PERCENT:
2381     {
2382       gint percent;
2383
2384       JBUF_LOCK (priv);
2385       if (priv->srcresult != GST_FLOW_OK)
2386         percent = 100;
2387       else
2388         percent = rtp_jitter_buffer_get_percent (priv->jbuf);
2389
2390       g_value_set_int (value, percent);
2391       JBUF_UNLOCK (priv);
2392       break;
2393     }
2394     default:
2395       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2396       break;
2397   }
2398 }