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