rtpbin/rtpjitterbuffer/rtspsrc: Add property to set maximum ms between RTCP SR RTP...
[platform/upstream/gst-plugins-good.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-rtpjitterbuffer
28  *
29  * This element reorders and removes duplicate RTP packets as they are received
30  * from a network source.
31  *
32  * The element needs the clock-rate of the RTP payload in order to estimate the
33  * delay. This information is obtained either from the caps on the sink pad or,
34  * when no caps are present, from the #GstRtpJitterBuffer::request-pt-map signal.
35  * To clear the previous pt-map use the #GstRtpJitterBuffer::clear-pt-map signal.
36  *
37  * The rtpjitterbuffer will wait for missing packets up to a configurable time
38  * limit using the #GstRtpJitterBuffer:latency property. Packets arriving too
39  * late are considered to be lost packets. If the #GstRtpJitterBuffer:do-lost
40  * property is set, lost packets will result in a custom serialized downstream
41  * event of name GstRTPPacketLost. The lost packet events are usually used by a
42  * depayloader or other element to create concealment data or some other logic
43  * to gracefully handle the missing packets.
44  *
45  * The jitterbuffer will use the DTS (or PTS if no DTS is set) of the incomming
46  * buffer and the rtptime inside the RTP packet to create a PTS on the outgoing
47  * buffer.
48  *
49  * The jitterbuffer can also be configured to send early retransmission events
50  * upstream by setting the #GstRtpJitterBuffer:do-retransmission property. In
51  * this mode, the jitterbuffer tries to estimate when a packet should arrive and
52  * sends a custom upstream event named GstRTPRetransmissionRequest when the
53  * packet is considered late. The initial expected packet arrival time is
54  * calculated as follows:
55  *
56  * - If seqnum N arrived at time T, seqnum N+1 is expected to arrive at
57  *     T + packet-spacing + #GstRtpJitterBuffer:rtx-delay. The packet spacing is
58  *     calculated from the DTS (or PTS is no DTS) of two consecutive RTP
59  *     packets with different rtptime.
60  *
61  * - If seqnum N0 arrived at time T0 and seqnum Nm arrived at time Tm,
62  *     seqnum Ni is expected at time Ti = T0 + i*(Tm - T0)/(Nm - N0). Any
63  *     previously scheduled timeout is overwritten.
64  *
65  * - If seqnum N arrived, all seqnum older than
66  *     N - #GstRtpJitterBuffer:rtx-delay-reorder are considered late
67  *     immediately. This is to request fast feedback for abonormally reorder
68  *     packets before any of the previous timeouts is triggered.
69  *
70  * A late packet triggers the GstRTPRetransmissionRequest custom upstream
71  * event. After the initial timeout expires and the retransmission event is
72  * sent, the timeout is scheduled for
73  * T + #GstRtpJitterBuffer:rtx-retry-timeout. If the missing packet did not
74  * arrive after #GstRtpJitterBuffer:rtx-retry-timeout, a new
75  * GstRTPRetransmissionRequest is sent upstream and the timeout is rescheduled
76  * again for T + #GstRtpJitterBuffer:rtx-retry-timeout. This repeats until
77  * #GstRtpJitterBuffer:rtx-retry-period elapsed, at which point no further
78  * retransmission requests are sent and the regular logic is performed to
79  * schedule a lost packet as discussed above.
80  *
81  * This element acts as a live element and so adds #GstRtpJitterBuffer:latency
82  * to the pipeline.
83  *
84  * This element will automatically be used inside rtpbin.
85  *
86  * <refsect2>
87  * <title>Example pipelines</title>
88  * |[
89  * gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! rtpjitterbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
90  * ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
91  * inserted into the pipeline to smooth out network jitter and to reorder the
92  * out-of-order RTP packets.
93  * </refsect2>
94  */
95
96 #ifdef HAVE_CONFIG_H
97 #include "config.h"
98 #endif
99
100 #include <stdlib.h>
101 #include <string.h>
102 #include <gst/rtp/gstrtpbuffer.h>
103
104 #include "gstrtpjitterbuffer.h"
105 #include "rtpjitterbuffer.h"
106 #include "rtpstats.h"
107
108 #include <gst/glib-compat-private.h>
109
110 GST_DEBUG_CATEGORY (rtpjitterbuffer_debug);
111 #define GST_CAT_DEFAULT (rtpjitterbuffer_debug)
112
113 /* RTPJitterBuffer signals and args */
114 enum
115 {
116   SIGNAL_REQUEST_PT_MAP,
117   SIGNAL_CLEAR_PT_MAP,
118   SIGNAL_HANDLE_SYNC,
119   SIGNAL_ON_NPT_STOP,
120   SIGNAL_SET_ACTIVE,
121   LAST_SIGNAL
122 };
123
124 #define DEFAULT_LATENCY_MS          200
125 #define DEFAULT_DROP_ON_LATENCY     FALSE
126 #define DEFAULT_TS_OFFSET           0
127 #define DEFAULT_DO_LOST             FALSE
128 #define DEFAULT_MODE                RTP_JITTER_BUFFER_MODE_SLAVE
129 #define DEFAULT_PERCENT             0
130 #define DEFAULT_DO_RETRANSMISSION   FALSE
131 #define DEFAULT_RTX_NEXT_SEQNUM     TRUE
132 #define DEFAULT_RTX_DELAY           -1
133 #define DEFAULT_RTX_MIN_DELAY       0
134 #define DEFAULT_RTX_DELAY_REORDER   3
135 #define DEFAULT_RTX_RETRY_TIMEOUT   -1
136 #define DEFAULT_RTX_MIN_RETRY_TIMEOUT   -1
137 #define DEFAULT_RTX_RETRY_PERIOD    -1
138 #define DEFAULT_RTX_MAX_RETRIES    -1
139 #define DEFAULT_MAX_RTCP_RTP_TIME_DIFF 1000
140
141 #define DEFAULT_AUTO_RTX_DELAY (20 * GST_MSECOND)
142 #define DEFAULT_AUTO_RTX_TIMEOUT (40 * GST_MSECOND)
143
144 enum
145 {
146   PROP_0,
147   PROP_LATENCY,
148   PROP_DROP_ON_LATENCY,
149   PROP_TS_OFFSET,
150   PROP_DO_LOST,
151   PROP_MODE,
152   PROP_PERCENT,
153   PROP_DO_RETRANSMISSION,
154   PROP_RTX_NEXT_SEQNUM,
155   PROP_RTX_DELAY,
156   PROP_RTX_MIN_DELAY,
157   PROP_RTX_DELAY_REORDER,
158   PROP_RTX_RETRY_TIMEOUT,
159   PROP_RTX_MIN_RETRY_TIMEOUT,
160   PROP_RTX_RETRY_PERIOD,
161   PROP_RTX_MAX_RETRIES,
162   PROP_STATS,
163   PROP_MAX_RTCP_RTP_TIME_DIFF
164 };
165
166 #define JBUF_LOCK(priv)   (g_mutex_lock (&(priv)->jbuf_lock))
167
168 #define JBUF_LOCK_CHECK(priv,label) G_STMT_START {    \
169   JBUF_LOCK (priv);                                   \
170   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))    \
171     goto label;                                       \
172 } G_STMT_END
173 #define JBUF_UNLOCK(priv) (g_mutex_unlock (&(priv)->jbuf_lock))
174
175 #define JBUF_WAIT_TIMER(priv)   G_STMT_START {            \
176   GST_DEBUG ("waiting timer");                            \
177   (priv)->waiting_timer = TRUE;                           \
178   g_cond_wait (&(priv)->jbuf_timer, &(priv)->jbuf_lock);  \
179   (priv)->waiting_timer = FALSE;                          \
180   GST_DEBUG ("waiting timer done");                       \
181 } G_STMT_END
182 #define JBUF_SIGNAL_TIMER(priv) G_STMT_START {            \
183   if (G_UNLIKELY ((priv)->waiting_timer)) {               \
184     GST_DEBUG ("signal timer");                           \
185     g_cond_signal (&(priv)->jbuf_timer);                  \
186   }                                                       \
187 } G_STMT_END
188
189 #define JBUF_WAIT_EVENT(priv,label) G_STMT_START {       \
190   GST_DEBUG ("waiting event");                           \
191   (priv)->waiting_event = TRUE;                          \
192   g_cond_wait (&(priv)->jbuf_event, &(priv)->jbuf_lock); \
193   (priv)->waiting_event = FALSE;                         \
194   GST_DEBUG ("waiting event done");                      \
195   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))       \
196     goto label;                                          \
197 } G_STMT_END
198 #define JBUF_SIGNAL_EVENT(priv) G_STMT_START {           \
199   if (G_UNLIKELY ((priv)->waiting_event)) {              \
200     GST_DEBUG ("signal event");                          \
201     g_cond_signal (&(priv)->jbuf_event);                 \
202   }                                                      \
203 } G_STMT_END
204
205 #define JBUF_WAIT_QUERY(priv,label) G_STMT_START {       \
206   GST_DEBUG ("waiting query");                           \
207   (priv)->waiting_query = TRUE;                          \
208   g_cond_wait (&(priv)->jbuf_query, &(priv)->jbuf_lock); \
209   (priv)->waiting_query = FALSE;                         \
210   GST_DEBUG ("waiting query done");                      \
211   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))       \
212     goto label;                                          \
213 } G_STMT_END
214 #define JBUF_SIGNAL_QUERY(priv,res) G_STMT_START {       \
215   (priv)->last_query = res;                              \
216   if (G_UNLIKELY ((priv)->waiting_query)) {              \
217     GST_DEBUG ("signal query");                          \
218     g_cond_signal (&(priv)->jbuf_query);                 \
219   }                                                      \
220 } G_STMT_END
221
222
223 struct _GstRtpJitterBufferPrivate
224 {
225   GstPad *sinkpad, *srcpad;
226   GstPad *rtcpsinkpad;
227
228   RTPJitterBuffer *jbuf;
229   GMutex jbuf_lock;
230   gboolean waiting_timer;
231   GCond jbuf_timer;
232   gboolean waiting_event;
233   GCond jbuf_event;
234   gboolean waiting_query;
235   GCond jbuf_query;
236   gboolean last_query;
237   gboolean discont;
238   gboolean ts_discont;
239   gboolean active;
240   guint64 out_offset;
241
242   gboolean timer_running;
243   GThread *timer_thread;
244
245   /* properties */
246   guint latency_ms;
247   guint64 latency_ns;
248   gboolean drop_on_latency;
249   gint64 ts_offset;
250   gboolean do_lost;
251   gboolean do_retransmission;
252   gboolean rtx_next_seqnum;
253   gint rtx_delay;
254   guint rtx_min_delay;
255   gint rtx_delay_reorder;
256   gint rtx_retry_timeout;
257   gint rtx_min_retry_timeout;
258   gint rtx_retry_period;
259   gint rtx_max_retries;
260   gint max_rtcp_rtp_time_diff;
261
262   /* the last seqnum we pushed out */
263   guint32 last_popped_seqnum;
264   /* the next expected seqnum we push */
265   guint32 next_seqnum;
266   /* seqnum-base, if known */
267   guint32 seqnum_base;
268   /* last output time */
269   GstClockTime last_out_time;
270   /* last valid input timestamp and rtptime pair */
271   GstClockTime ips_dts;
272   guint64 ips_rtptime;
273   GstClockTime packet_spacing;
274
275   GQueue gap_packets;
276
277   /* the next expected seqnum we receive */
278   GstClockTime last_in_dts;
279   guint32 next_in_seqnum;
280
281   GArray *timers;
282
283   /* start and stop ranges */
284   GstClockTime npt_start;
285   GstClockTime npt_stop;
286   guint64 ext_timestamp;
287   guint64 last_elapsed;
288   guint64 estimated_eos;
289   GstClockID eos_id;
290
291   /* state */
292   gboolean eos;
293   guint last_percent;
294
295   /* clock rate and rtp timestamp offset */
296   gint last_pt;
297   gint32 clock_rate;
298   gint64 clock_base;
299   gint64 prev_ts_offset;
300
301   /* when we are shutting down */
302   GstFlowReturn srcresult;
303   gboolean blocked;
304
305   /* for sync */
306   GstSegment segment;
307   GstClockID clock_id;
308   GstClockTime timer_timeout;
309   guint16 timer_seqnum;
310   /* the latency of the upstream peer, we have to take this into account when
311    * synchronizing the buffers. */
312   GstClockTime peer_latency;
313   guint64 ext_rtptime;
314   GstBuffer *last_sr;
315
316   /* some accounting */
317   guint64 num_late;
318   guint64 num_duplicates;
319   guint64 num_rtx_requests;
320   guint64 num_rtx_success;
321   guint64 num_rtx_failed;
322   gdouble avg_rtx_num;
323   guint64 avg_rtx_rtt;
324
325   /* for the jitter */
326   GstClockTime last_dts;
327   guint64 last_rtptime;
328   GstClockTime avg_jitter;
329 };
330
331 typedef enum
332 {
333   TIMER_TYPE_EXPECTED,
334   TIMER_TYPE_LOST,
335   TIMER_TYPE_DEADLINE,
336   TIMER_TYPE_EOS
337 } TimerType;
338
339 typedef struct
340 {
341   guint idx;
342   guint16 seqnum;
343   guint num;
344   TimerType type;
345   GstClockTime timeout;
346   GstClockTime duration;
347   GstClockTime rtx_base;
348   GstClockTime rtx_delay;
349   GstClockTime rtx_retry;
350   GstClockTime rtx_last;
351   guint num_rtx_retry;
352 } TimerData;
353
354 #define GST_RTP_JITTER_BUFFER_GET_PRIVATE(o) \
355   (G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_RTP_JITTER_BUFFER, \
356                                 GstRtpJitterBufferPrivate))
357
358 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_template =
359 GST_STATIC_PAD_TEMPLATE ("sink",
360     GST_PAD_SINK,
361     GST_PAD_ALWAYS,
362     GST_STATIC_CAPS ("application/x-rtp"
363         /* "clock-rate = (int) [ 1, 2147483647 ], "
364          * "payload = (int) , "
365          * "encoding-name = (string) "
366          */ )
367     );
368
369 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_rtcp_template =
370 GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
371     GST_PAD_SINK,
372     GST_PAD_REQUEST,
373     GST_STATIC_CAPS ("application/x-rtcp")
374     );
375
376 static GstStaticPadTemplate gst_rtp_jitter_buffer_src_template =
377 GST_STATIC_PAD_TEMPLATE ("src",
378     GST_PAD_SRC,
379     GST_PAD_ALWAYS,
380     GST_STATIC_CAPS ("application/x-rtp"
381         /* "payload = (int) , "
382          * "clock-rate = (int) , "
383          * "encoding-name = (string) "
384          */ )
385     );
386
387 static guint gst_rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 };
388
389 #define gst_rtp_jitter_buffer_parent_class parent_class
390 G_DEFINE_TYPE (GstRtpJitterBuffer, gst_rtp_jitter_buffer, GST_TYPE_ELEMENT);
391
392 /* object overrides */
393 static void gst_rtp_jitter_buffer_set_property (GObject * object,
394     guint prop_id, const GValue * value, GParamSpec * pspec);
395 static void gst_rtp_jitter_buffer_get_property (GObject * object,
396     guint prop_id, GValue * value, GParamSpec * pspec);
397 static void gst_rtp_jitter_buffer_finalize (GObject * object);
398
399 /* element overrides */
400 static GstStateChangeReturn gst_rtp_jitter_buffer_change_state (GstElement
401     * element, GstStateChange transition);
402 static GstPad *gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
403     GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
404 static void gst_rtp_jitter_buffer_release_pad (GstElement * element,
405     GstPad * pad);
406 static GstClock *gst_rtp_jitter_buffer_provide_clock (GstElement * element);
407
408 /* pad overrides */
409 static GstCaps *gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter);
410 static GstIterator *gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad,
411     GstObject * parent);
412
413 /* sinkpad overrides */
414 static gboolean gst_rtp_jitter_buffer_sink_event (GstPad * pad,
415     GstObject * parent, GstEvent * event);
416 static GstFlowReturn gst_rtp_jitter_buffer_chain (GstPad * pad,
417     GstObject * parent, GstBuffer * buffer);
418
419 static gboolean gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad,
420     GstObject * parent, GstEvent * event);
421 static GstFlowReturn gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad,
422     GstObject * parent, GstBuffer * buffer);
423
424 static gboolean gst_rtp_jitter_buffer_sink_query (GstPad * pad,
425     GstObject * parent, GstQuery * query);
426
427 /* srcpad overrides */
428 static gboolean gst_rtp_jitter_buffer_src_event (GstPad * pad,
429     GstObject * parent, GstEvent * event);
430 static gboolean gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad,
431     GstObject * parent, GstPadMode mode, gboolean active);
432 static void gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer);
433 static gboolean gst_rtp_jitter_buffer_src_query (GstPad * pad,
434     GstObject * parent, GstQuery * query);
435
436 static void
437 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer);
438 static GstClockTime
439 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jitterbuffer,
440     gboolean active, guint64 base_time);
441 static void do_handle_sync (GstRtpJitterBuffer * jitterbuffer);
442
443 static void unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer);
444 static void remove_all_timers (GstRtpJitterBuffer * jitterbuffer);
445
446 static void wait_next_timeout (GstRtpJitterBuffer * jitterbuffer);
447
448 static GstStructure *gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer *
449     jitterbuffer);
450
451 static void
452 gst_rtp_jitter_buffer_class_init (GstRtpJitterBufferClass * klass)
453 {
454   GObjectClass *gobject_class;
455   GstElementClass *gstelement_class;
456
457   gobject_class = (GObjectClass *) klass;
458   gstelement_class = (GstElementClass *) klass;
459
460   g_type_class_add_private (klass, sizeof (GstRtpJitterBufferPrivate));
461
462   gobject_class->finalize = gst_rtp_jitter_buffer_finalize;
463
464   gobject_class->set_property = gst_rtp_jitter_buffer_set_property;
465   gobject_class->get_property = gst_rtp_jitter_buffer_get_property;
466
467   /**
468    * GstRtpJitterBuffer:latency:
469    *
470    * The maximum latency of the jitterbuffer. Packets will be kept in the buffer
471    * for at most this time.
472    */
473   g_object_class_install_property (gobject_class, PROP_LATENCY,
474       g_param_spec_uint ("latency", "Buffer latency in ms",
475           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
476           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
477   /**
478    * GstRtpJitterBuffer:drop-on-latency:
479    *
480    * Drop oldest buffers when the queue is completely filled.
481    */
482   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
483       g_param_spec_boolean ("drop-on-latency",
484           "Drop buffers when maximum latency is reached",
485           "Tells the jitterbuffer to never exceed the given latency in size",
486           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
487   /**
488    * GstRtpJitterBuffer:ts-offset:
489    *
490    * Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
491    * This is mainly used to ensure interstream synchronisation.
492    */
493   g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
494       g_param_spec_int64 ("ts-offset", "Timestamp Offset",
495           "Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
496           G_MAXINT64, DEFAULT_TS_OFFSET,
497           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
498
499   /**
500    * GstRtpJitterBuffer:do-lost:
501    *
502    * Send out a GstRTPPacketLost event downstream when a packet is considered
503    * lost.
504    */
505   g_object_class_install_property (gobject_class, PROP_DO_LOST,
506       g_param_spec_boolean ("do-lost", "Do Lost",
507           "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
508           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
509
510   /**
511    * GstRtpJitterBuffer:mode:
512    *
513    * Control the buffering and timestamping mode used by the jitterbuffer.
514    */
515   g_object_class_install_property (gobject_class, PROP_MODE,
516       g_param_spec_enum ("mode", "Mode",
517           "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
518           DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
519   /**
520    * GstRtpJitterBuffer:percent:
521    *
522    * The percent of the jitterbuffer that is filled.
523    */
524   g_object_class_install_property (gobject_class, PROP_PERCENT,
525       g_param_spec_int ("percent", "percent",
526           "The buffer filled percent", 0, 100,
527           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
528   /**
529    * GstRtpJitterBuffer:do-retransmission:
530    *
531    * Send out a GstRTPRetransmission event upstream when a packet is considered
532    * late and should be retransmitted.
533    *
534    * Since: 1.2
535    */
536   g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
537       g_param_spec_boolean ("do-retransmission", "Do Retransmission",
538           "Send retransmission events upstream when a packet is late",
539           DEFAULT_DO_RETRANSMISSION,
540           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
541
542   /**
543    * GstRtpJitterBuffer:rtx-next-seqnum
544    *
545    * Estimate when the next packet should arrive and schedule a retransmission
546    * request for it.
547    * This is, when packet N arrives, a GstRTPRetransmission event is schedule
548    * for packet N+1. So it will be requested if it does not arrive at the expected time.
549    * The expected time is calculated using the dts of N and the packet spacing.
550    *
551    * Since: 1.6
552    */
553   g_object_class_install_property (gobject_class, PROP_RTX_NEXT_SEQNUM,
554       g_param_spec_boolean ("rtx-next-seqnum", "RTX next seqnum",
555           "Estimate when the next packet should arrive and schedule a "
556           "retransmission request for it.",
557           DEFAULT_RTX_NEXT_SEQNUM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
558
559   /**
560    * GstRtpJitterBuffer:rtx-delay:
561    *
562    * When a packet did not arrive at the expected time, wait this extra amount
563    * of time before sending a retransmission event.
564    *
565    * When -1 is used, the max jitter will be used as extra delay.
566    *
567    * Since: 1.2
568    */
569   g_object_class_install_property (gobject_class, PROP_RTX_DELAY,
570       g_param_spec_int ("rtx-delay", "RTX Delay",
571           "Extra time in ms to wait before sending retransmission "
572           "event (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DELAY,
573           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
574
575   /**
576    * GstRtpJitterBuffer:rtx-min-delay:
577    *
578    * When a packet did not arrive at the expected time, wait at least this extra amount
579    * of time before sending a retransmission event.
580    *
581    * Since: 1.6
582    */
583   g_object_class_install_property (gobject_class, PROP_RTX_MIN_DELAY,
584       g_param_spec_uint ("rtx-min-delay", "Minimum RTX Delay",
585           "Minimum time in ms to wait before sending retransmission "
586           "event", 0, G_MAXUINT, DEFAULT_RTX_MIN_DELAY,
587           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
588   /**
589    * GstRtpJitterBuffer:rtx-delay-reorder:
590    *
591    * Assume that a retransmission event should be sent when we see
592    * this much packet reordering.
593    *
594    * When -1 is used, the value will be estimated based on observed packet
595    * reordering.
596    *
597    * Since: 1.2
598    */
599   g_object_class_install_property (gobject_class, PROP_RTX_DELAY_REORDER,
600       g_param_spec_int ("rtx-delay-reorder", "RTX Delay Reorder",
601           "Sending retransmission event when this much reordering (-1 automatic)",
602           -1, G_MAXINT, DEFAULT_RTX_DELAY_REORDER,
603           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
604   /**
605    * GstRtpJitterBuffer::rtx-retry-timeout:
606    *
607    * When no packet has been received after sending a retransmission event
608    * for this time, retry sending a retransmission event.
609    *
610    * When -1 is used, the value will be estimated based on observed round
611    * trip time.
612    *
613    * Since: 1.2
614    */
615   g_object_class_install_property (gobject_class, PROP_RTX_RETRY_TIMEOUT,
616       g_param_spec_int ("rtx-retry-timeout", "RTX Retry Timeout",
617           "Retry sending a transmission event after this timeout in "
618           "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_TIMEOUT,
619           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
620   /**
621    * GstRtpJitterBuffer::rtx-min-retry-timeout:
622    *
623    * The minimum amount of time between retry timeouts. When
624    * GstRtpJitterBuffer::rtx-retry-timeout is -1, this value ensures a
625    * minimum interval between retry timeouts.
626    *
627    * When -1 is used, the value will be estimated based on the
628    * packet spacing.
629    *
630    * Since: 1.6
631    */
632   g_object_class_install_property (gobject_class, PROP_RTX_MIN_RETRY_TIMEOUT,
633       g_param_spec_int ("rtx-min-retry-timeout", "RTX Min Retry Timeout",
634           "Minimum timeout between sending a transmission event in "
635           "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_MIN_RETRY_TIMEOUT,
636           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
637   /**
638    * GstRtpJitterBuffer:rtx-retry-period:
639    *
640    * The amount of time to try to get a retransmission.
641    *
642    * When -1 is used, the value will be estimated based on the jitterbuffer
643    * latency and the observed round trip time.
644    *
645    * Since: 1.2
646    */
647   g_object_class_install_property (gobject_class, PROP_RTX_RETRY_PERIOD,
648       g_param_spec_int ("rtx-retry-period", "RTX Retry Period",
649           "Try to get a retransmission for this many ms "
650           "(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_PERIOD,
651           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
652   /**
653    * GstRtpJitterBuffer:rtx-max-retries:
654    *
655    * The maximum number of retries to request a retransmission.
656    *
657    * This implies that as maximum (rtx-max-retries + 1) retransmissions will be requested.
658    * When -1 is used, the number of retransmission request will not be limited.
659    *
660    * Since: 1.6
661    */
662   g_object_class_install_property (gobject_class, PROP_RTX_MAX_RETRIES,
663       g_param_spec_int ("rtx-max-retries", "RTX Max Retries",
664           "The maximum number of retries to request a retransmission. "
665           "(-1 not limited)", -1, G_MAXINT, DEFAULT_RTX_MAX_RETRIES,
666           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
667   /**
668    * GstRtpJitterBuffer:stats:
669    *
670    * Various jitterbuffer statistics. This property returns a GstStructure
671    * with name application/x-rtp-jitterbuffer-stats with the following fields:
672    *
673    * <itemizedlist>
674    * <listitem>
675    *   <para>
676    *   #guint64
677    *   <classname>&quot;rtx-count&quot;</classname>:
678    *   the number of retransmissions requested.
679    *   </para>
680    * </listitem>
681    * <listitem>
682    *   <para>
683    *   #guint64
684    *   <classname>&quot;rtx-success-count&quot;</classname>:
685    *   the number of successful retransmissions.
686    *   </para>
687    * </listitem>
688    * <listitem>
689    *   <para>
690    *   #gdouble
691    *   <classname>&quot;rtx-per-packet&quot;</classname>:
692    *   average number of RTX per packet.
693    *   </para>
694    * </listitem>
695    * <listitem>
696    *   <para>
697    *   #guint64
698    *   <classname>&quot;rtx-rtt&quot;</classname>:
699    *   average round trip time per RTX.
700    *   </para>
701    * </listitem>
702    * </itemizedlist>
703    *
704    * Since: 1.4
705    */
706   g_object_class_install_property (gobject_class, PROP_STATS,
707       g_param_spec_boxed ("stats", "Statistics",
708           "Various statistics", GST_TYPE_STRUCTURE,
709           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
710
711   /**
712    * GstRtpJitterBuffer:max-rtcp-rtp-time-diff
713    *
714    * The maximum amount of time in ms that the RTP time in the RTCP SRs
715    * is allowed to be ahead of the last RTP packet we received. Use
716    * -1 to disable ignoring of RTCP packets.
717    *
718    * Since: 1.8
719    */
720   g_object_class_install_property (gobject_class, PROP_MAX_RTCP_RTP_TIME_DIFF,
721       g_param_spec_int ("max-rtcp-rtp-time-diff", "Max RTCP RTP Time Diff",
722           "Maximum amount of time in ms that the RTP time in RTCP SRs "
723           "is allowed to be ahead (-1 disabled)", -1, G_MAXINT,
724           DEFAULT_MAX_RTCP_RTP_TIME_DIFF,
725           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
726
727   /**
728    * GstRtpJitterBuffer::request-pt-map:
729    * @buffer: the object which received the signal
730    * @pt: the pt
731    *
732    * Request the payload type as #GstCaps for @pt.
733    */
734   gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
735       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
736       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
737           request_pt_map), NULL, NULL, g_cclosure_marshal_generic,
738       GST_TYPE_CAPS, 1, G_TYPE_UINT);
739   /**
740    * GstRtpJitterBuffer::handle-sync:
741    * @buffer: the object which received the signal
742    * @struct: a GstStructure containing sync values.
743    *
744    * Be notified of new sync values.
745    */
746   gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC] =
747       g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
748       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
749           handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
750       G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
751
752   /**
753    * GstRtpJitterBuffer::on-npt-stop:
754    * @buffer: the object which received the signal
755    *
756    * Signal that the jitterbufer has pushed the RTP packet that corresponds to
757    * the npt-stop position.
758    */
759   gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP] =
760       g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
761       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
762           on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
763       G_TYPE_NONE, 0, G_TYPE_NONE);
764
765   /**
766    * GstRtpJitterBuffer::clear-pt-map:
767    * @buffer: the object which received the signal
768    *
769    * Invalidate the clock-rate as obtained with the
770    * #GstRtpJitterBuffer::request-pt-map signal.
771    */
772   gst_rtp_jitter_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
773       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
774       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
775       G_STRUCT_OFFSET (GstRtpJitterBufferClass, clear_pt_map), NULL, NULL,
776       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
777
778   /**
779    * GstRtpJitterBuffer::set-active:
780    * @buffer: the object which received the signal
781    *
782    * Start pushing out packets with the given base time. This signal is only
783    * useful in buffering mode.
784    *
785    * Returns: the time of the last pushed packet.
786    */
787   gst_rtp_jitter_buffer_signals[SIGNAL_SET_ACTIVE] =
788       g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
789       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
790       G_STRUCT_OFFSET (GstRtpJitterBufferClass, set_active), NULL, NULL,
791       g_cclosure_marshal_generic, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
792       G_TYPE_UINT64);
793
794   gstelement_class->change_state =
795       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_change_state);
796   gstelement_class->request_new_pad =
797       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_request_new_pad);
798   gstelement_class->release_pad =
799       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_release_pad);
800   gstelement_class->provide_clock =
801       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_provide_clock);
802
803   gst_element_class_add_pad_template (gstelement_class,
804       gst_static_pad_template_get (&gst_rtp_jitter_buffer_src_template));
805   gst_element_class_add_pad_template (gstelement_class,
806       gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_template));
807   gst_element_class_add_pad_template (gstelement_class,
808       gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_rtcp_template));
809
810   gst_element_class_set_static_metadata (gstelement_class,
811       "RTP packet jitter-buffer", "Filter/Network/RTP",
812       "A buffer that deals with network jitter and other transmission faults",
813       "Philippe Kalaf <philippe.kalaf@collabora.co.uk>, "
814       "Wim Taymans <wim.taymans@gmail.com>");
815
816   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_clear_pt_map);
817   klass->set_active = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_active);
818
819   GST_DEBUG_CATEGORY_INIT
820       (rtpjitterbuffer_debug, "rtpjitterbuffer", 0, "RTP Jitter Buffer");
821 }
822
823 static void
824 gst_rtp_jitter_buffer_init (GstRtpJitterBuffer * jitterbuffer)
825 {
826   GstRtpJitterBufferPrivate *priv;
827
828   priv = GST_RTP_JITTER_BUFFER_GET_PRIVATE (jitterbuffer);
829   jitterbuffer->priv = priv;
830
831   priv->latency_ms = DEFAULT_LATENCY_MS;
832   priv->latency_ns = priv->latency_ms * GST_MSECOND;
833   priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
834   priv->do_lost = DEFAULT_DO_LOST;
835   priv->do_retransmission = DEFAULT_DO_RETRANSMISSION;
836   priv->rtx_next_seqnum = DEFAULT_RTX_NEXT_SEQNUM;
837   priv->rtx_delay = DEFAULT_RTX_DELAY;
838   priv->rtx_min_delay = DEFAULT_RTX_MIN_DELAY;
839   priv->rtx_delay_reorder = DEFAULT_RTX_DELAY_REORDER;
840   priv->rtx_retry_timeout = DEFAULT_RTX_RETRY_TIMEOUT;
841   priv->rtx_min_retry_timeout = DEFAULT_RTX_MIN_RETRY_TIMEOUT;
842   priv->rtx_retry_period = DEFAULT_RTX_RETRY_PERIOD;
843   priv->rtx_max_retries = DEFAULT_RTX_MAX_RETRIES;
844   priv->max_rtcp_rtp_time_diff = DEFAULT_MAX_RTCP_RTP_TIME_DIFF;
845
846   priv->last_dts = -1;
847   priv->last_rtptime = -1;
848   priv->avg_jitter = 0;
849   priv->timers = g_array_new (FALSE, TRUE, sizeof (TimerData));
850   priv->jbuf = rtp_jitter_buffer_new ();
851   g_mutex_init (&priv->jbuf_lock);
852   g_cond_init (&priv->jbuf_timer);
853   g_cond_init (&priv->jbuf_event);
854   g_cond_init (&priv->jbuf_query);
855   g_queue_init (&priv->gap_packets);
856
857   /* reset skew detection initialy */
858   rtp_jitter_buffer_reset_skew (priv->jbuf);
859   rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
860   rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
861   priv->active = TRUE;
862
863   priv->srcpad =
864       gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_src_template,
865       "src");
866
867   gst_pad_set_activatemode_function (priv->srcpad,
868       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_activate_mode));
869   gst_pad_set_query_function (priv->srcpad,
870       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_query));
871   gst_pad_set_event_function (priv->srcpad,
872       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_event));
873
874   priv->sinkpad =
875       gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_sink_template,
876       "sink");
877
878   gst_pad_set_chain_function (priv->sinkpad,
879       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain));
880   gst_pad_set_event_function (priv->sinkpad,
881       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_event));
882   gst_pad_set_query_function (priv->sinkpad,
883       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_query));
884
885   gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
886   gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
887
888   GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
889 }
890
891 #define IS_DROPABLE(it) (((it)->type == ITEM_TYPE_BUFFER) || ((it)->type == ITEM_TYPE_LOST))
892
893 #define ITEM_TYPE_BUFFER        0
894 #define ITEM_TYPE_LOST          1
895 #define ITEM_TYPE_EVENT         2
896 #define ITEM_TYPE_QUERY         3
897
898 static RTPJitterBufferItem *
899 alloc_item (gpointer data, guint type, GstClockTime dts, GstClockTime pts,
900     guint seqnum, guint count, guint rtptime)
901 {
902   RTPJitterBufferItem *item;
903
904   item = g_slice_new (RTPJitterBufferItem);
905   item->data = data;
906   item->next = NULL;
907   item->prev = NULL;
908   item->type = type;
909   item->dts = dts;
910   item->pts = pts;
911   item->seqnum = seqnum;
912   item->count = count;
913   item->rtptime = rtptime;
914
915   return item;
916 }
917
918 static void
919 free_item (RTPJitterBufferItem * item)
920 {
921   g_return_if_fail (item != NULL);
922
923   if (item->data && item->type != ITEM_TYPE_QUERY)
924     gst_mini_object_unref (item->data);
925   g_slice_free (RTPJitterBufferItem, item);
926 }
927
928 static void
929 free_item_and_retain_events (RTPJitterBufferItem * item, gpointer user_data)
930 {
931   GList **l = user_data;
932
933   if (item->data && item->type == ITEM_TYPE_EVENT
934       && GST_EVENT_IS_STICKY (item->data)) {
935     *l = g_list_prepend (*l, item->data);
936   } else if (item->data && item->type != ITEM_TYPE_QUERY) {
937     gst_mini_object_unref (item->data);
938   }
939   g_slice_free (RTPJitterBufferItem, item);
940 }
941
942 static void
943 gst_rtp_jitter_buffer_finalize (GObject * object)
944 {
945   GstRtpJitterBuffer *jitterbuffer;
946   GstRtpJitterBufferPrivate *priv;
947
948   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
949   priv = jitterbuffer->priv;
950
951   g_array_free (priv->timers, TRUE);
952   g_mutex_clear (&priv->jbuf_lock);
953   g_cond_clear (&priv->jbuf_timer);
954   g_cond_clear (&priv->jbuf_event);
955   g_cond_clear (&priv->jbuf_query);
956
957   rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
958   g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
959   g_queue_clear (&priv->gap_packets);
960   g_object_unref (priv->jbuf);
961
962   G_OBJECT_CLASS (parent_class)->finalize (object);
963 }
964
965 static GstIterator *
966 gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
967 {
968   GstRtpJitterBuffer *jitterbuffer;
969   GstPad *otherpad = NULL;
970   GstIterator *it = NULL;
971   GValue val = { 0, };
972
973   jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
974
975   if (pad == jitterbuffer->priv->sinkpad) {
976     otherpad = jitterbuffer->priv->srcpad;
977   } else if (pad == jitterbuffer->priv->srcpad) {
978     otherpad = jitterbuffer->priv->sinkpad;
979   } else if (pad == jitterbuffer->priv->rtcpsinkpad) {
980     it = gst_iterator_new_single (GST_TYPE_PAD, NULL);
981   }
982
983   if (it == NULL) {
984     g_value_init (&val, GST_TYPE_PAD);
985     g_value_set_object (&val, otherpad);
986     it = gst_iterator_new_single (GST_TYPE_PAD, &val);
987     g_value_unset (&val);
988   }
989
990   return it;
991 }
992
993 static GstPad *
994 create_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
995 {
996   GstRtpJitterBufferPrivate *priv;
997
998   priv = jitterbuffer->priv;
999
1000   GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
1001
1002   priv->rtcpsinkpad =
1003       gst_pad_new_from_static_template
1004       (&gst_rtp_jitter_buffer_sink_rtcp_template, "sink_rtcp");
1005   gst_pad_set_chain_function (priv->rtcpsinkpad,
1006       gst_rtp_jitter_buffer_chain_rtcp);
1007   gst_pad_set_event_function (priv->rtcpsinkpad,
1008       (GstPadEventFunction) gst_rtp_jitter_buffer_sink_rtcp_event);
1009   gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
1010       gst_rtp_jitter_buffer_iterate_internal_links);
1011   gst_pad_set_active (priv->rtcpsinkpad, TRUE);
1012   gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
1013
1014   return priv->rtcpsinkpad;
1015 }
1016
1017 static void
1018 remove_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
1019 {
1020   GstRtpJitterBufferPrivate *priv;
1021
1022   priv = jitterbuffer->priv;
1023
1024   GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
1025
1026   gst_pad_set_active (priv->rtcpsinkpad, FALSE);
1027
1028   gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
1029   priv->rtcpsinkpad = NULL;
1030 }
1031
1032 static GstPad *
1033 gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
1034     GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
1035 {
1036   GstRtpJitterBuffer *jitterbuffer;
1037   GstElementClass *klass;
1038   GstPad *result;
1039   GstRtpJitterBufferPrivate *priv;
1040
1041   g_return_val_if_fail (templ != NULL, NULL);
1042   g_return_val_if_fail (GST_IS_RTP_JITTER_BUFFER (element), NULL);
1043
1044   jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
1045   priv = jitterbuffer->priv;
1046   klass = GST_ELEMENT_GET_CLASS (element);
1047
1048   GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
1049
1050   /* figure out the template */
1051   if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
1052     if (priv->rtcpsinkpad != NULL)
1053       goto exists;
1054
1055     result = create_rtcp_sink (jitterbuffer);
1056   } else
1057     goto wrong_template;
1058
1059   return result;
1060
1061   /* ERRORS */
1062 wrong_template:
1063   {
1064     g_warning ("rtpjitterbuffer: this is not our template");
1065     return NULL;
1066   }
1067 exists:
1068   {
1069     g_warning ("rtpjitterbuffer: pad already requested");
1070     return NULL;
1071   }
1072 }
1073
1074 static void
1075 gst_rtp_jitter_buffer_release_pad (GstElement * element, GstPad * pad)
1076 {
1077   GstRtpJitterBuffer *jitterbuffer;
1078   GstRtpJitterBufferPrivate *priv;
1079
1080   g_return_if_fail (GST_IS_RTP_JITTER_BUFFER (element));
1081   g_return_if_fail (GST_IS_PAD (pad));
1082
1083   jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (element);
1084   priv = jitterbuffer->priv;
1085
1086   GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1087
1088   if (priv->rtcpsinkpad == pad) {
1089     remove_rtcp_sink (jitterbuffer);
1090   } else
1091     goto wrong_pad;
1092
1093   return;
1094
1095   /* ERRORS */
1096 wrong_pad:
1097   {
1098     g_warning ("gstjitterbuffer: asked to release an unknown pad");
1099     return;
1100   }
1101 }
1102
1103 static GstClock *
1104 gst_rtp_jitter_buffer_provide_clock (GstElement * element)
1105 {
1106   return gst_system_clock_obtain ();
1107 }
1108
1109 static void
1110 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer)
1111 {
1112   GstRtpJitterBufferPrivate *priv;
1113
1114   priv = jitterbuffer->priv;
1115
1116   /* this will trigger a new pt-map request signal, FIXME, do something better. */
1117
1118   JBUF_LOCK (priv);
1119   priv->clock_rate = -1;
1120   /* do not clear current content, but refresh state for new arrival */
1121   GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
1122   rtp_jitter_buffer_reset_skew (priv->jbuf);
1123   JBUF_UNLOCK (priv);
1124 }
1125
1126 static GstClockTime
1127 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jbuf, gboolean active,
1128     guint64 offset)
1129 {
1130   GstRtpJitterBufferPrivate *priv;
1131   GstClockTime last_out;
1132   RTPJitterBufferItem *item;
1133
1134   priv = jbuf->priv;
1135
1136   JBUF_LOCK (priv);
1137   GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
1138       active, GST_TIME_ARGS (offset));
1139
1140   if (active != priv->active) {
1141     /* add the amount of time spent in paused to the output offset. All
1142      * outgoing buffers will have this offset applied to their timestamps in
1143      * order to make them arrive in time in the sink. */
1144     priv->out_offset = offset;
1145     GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
1146         GST_TIME_ARGS (priv->out_offset));
1147     priv->active = active;
1148     JBUF_SIGNAL_EVENT (priv);
1149   }
1150   if (!active) {
1151     rtp_jitter_buffer_set_buffering (priv->jbuf, TRUE);
1152   }
1153   if ((item = rtp_jitter_buffer_peek (priv->jbuf))) {
1154     /* head buffer timestamp and offset gives our output time */
1155     last_out = item->dts + priv->ts_offset;
1156   } else {
1157     /* use last known time when the buffer is empty */
1158     last_out = priv->last_out_time;
1159   }
1160   JBUF_UNLOCK (priv);
1161
1162   return last_out;
1163 }
1164
1165 static GstCaps *
1166 gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter)
1167 {
1168   GstRtpJitterBuffer *jitterbuffer;
1169   GstRtpJitterBufferPrivate *priv;
1170   GstPad *other;
1171   GstCaps *caps;
1172   GstCaps *templ;
1173
1174   jitterbuffer = GST_RTP_JITTER_BUFFER (gst_pad_get_parent (pad));
1175   priv = jitterbuffer->priv;
1176
1177   other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
1178
1179   caps = gst_pad_peer_query_caps (other, filter);
1180
1181   templ = gst_pad_get_pad_template_caps (pad);
1182   if (caps == NULL) {
1183     GST_DEBUG_OBJECT (jitterbuffer, "use template");
1184     caps = templ;
1185   } else {
1186     GstCaps *intersect;
1187
1188     GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
1189
1190     intersect = gst_caps_intersect (caps, templ);
1191     gst_caps_unref (caps);
1192     gst_caps_unref (templ);
1193
1194     caps = intersect;
1195   }
1196   gst_object_unref (jitterbuffer);
1197
1198   return caps;
1199 }
1200
1201 /*
1202  * Must be called with JBUF_LOCK held
1203  */
1204
1205 static gboolean
1206 gst_jitter_buffer_sink_parse_caps (GstRtpJitterBuffer * jitterbuffer,
1207     GstCaps * caps)
1208 {
1209   GstRtpJitterBufferPrivate *priv;
1210   GstStructure *caps_struct;
1211   guint val;
1212   GstClockTime tval;
1213
1214   priv = jitterbuffer->priv;
1215
1216   /* first parse the caps */
1217   caps_struct = gst_caps_get_structure (caps, 0);
1218
1219   GST_DEBUG_OBJECT (jitterbuffer, "got caps");
1220
1221   /* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
1222    * measure the amount of data in the buffer */
1223   if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
1224     goto error;
1225
1226   if (priv->clock_rate <= 0)
1227     goto wrong_rate;
1228
1229   GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
1230
1231   rtp_jitter_buffer_set_clock_rate (priv->jbuf, priv->clock_rate);
1232
1233   /* The clock base is the RTP timestamp corrsponding to the npt-start value. We
1234    * can use this to track the amount of time elapsed on the sender. */
1235   if (gst_structure_get_uint (caps_struct, "clock-base", &val))
1236     priv->clock_base = val;
1237   else
1238     priv->clock_base = -1;
1239
1240   priv->ext_timestamp = priv->clock_base;
1241
1242   GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
1243       priv->clock_base);
1244
1245   if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
1246     /* first expected seqnum, only update when we didn't have a previous base. */
1247     if (priv->next_in_seqnum == -1)
1248       priv->next_in_seqnum = val;
1249     if (priv->next_seqnum == -1) {
1250       priv->next_seqnum = val;
1251       JBUF_SIGNAL_EVENT (priv);
1252     }
1253     priv->seqnum_base = val;
1254   } else {
1255     priv->seqnum_base = -1;
1256   }
1257
1258   GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
1259
1260   /* the start and stop times. The seqnum-base corresponds to the start time. We
1261    * will keep track of the seqnums on the output and when we reach the one
1262    * corresponding to npt-stop, we emit the npt-stop-reached signal */
1263   if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
1264     priv->npt_start = tval;
1265   else
1266     priv->npt_start = 0;
1267
1268   if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
1269     priv->npt_stop = tval;
1270   else
1271     priv->npt_stop = -1;
1272
1273   GST_DEBUG_OBJECT (jitterbuffer,
1274       "npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1275       GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
1276
1277   return TRUE;
1278
1279   /* ERRORS */
1280 error:
1281   {
1282     GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
1283     return FALSE;
1284   }
1285 wrong_rate:
1286   {
1287     GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
1288     return FALSE;
1289   }
1290 }
1291
1292 static void
1293 gst_rtp_jitter_buffer_flush_start (GstRtpJitterBuffer * jitterbuffer)
1294 {
1295   GstRtpJitterBufferPrivate *priv;
1296
1297   priv = jitterbuffer->priv;
1298
1299   JBUF_LOCK (priv);
1300   /* mark ourselves as flushing */
1301   priv->srcresult = GST_FLOW_FLUSHING;
1302   GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
1303   /* this unblocks any waiting pops on the src pad task */
1304   JBUF_SIGNAL_EVENT (priv);
1305   JBUF_SIGNAL_QUERY (priv, FALSE);
1306   JBUF_UNLOCK (priv);
1307 }
1308
1309 static void
1310 gst_rtp_jitter_buffer_flush_stop (GstRtpJitterBuffer * jitterbuffer)
1311 {
1312   GstRtpJitterBufferPrivate *priv;
1313
1314   priv = jitterbuffer->priv;
1315
1316   JBUF_LOCK (priv);
1317   GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
1318   /* Mark as non flushing */
1319   priv->srcresult = GST_FLOW_OK;
1320   gst_segment_init (&priv->segment, GST_FORMAT_TIME);
1321   priv->last_popped_seqnum = -1;
1322   priv->last_out_time = -1;
1323   priv->next_seqnum = -1;
1324   priv->seqnum_base = -1;
1325   priv->ips_rtptime = -1;
1326   priv->ips_dts = GST_CLOCK_TIME_NONE;
1327   priv->packet_spacing = 0;
1328   priv->next_in_seqnum = -1;
1329   priv->clock_rate = -1;
1330   priv->last_pt = -1;
1331   priv->eos = FALSE;
1332   priv->estimated_eos = -1;
1333   priv->last_elapsed = 0;
1334   priv->ext_timestamp = -1;
1335   priv->avg_jitter = 0;
1336   priv->last_dts = -1;
1337   priv->last_rtptime = -1;
1338   priv->last_in_dts = 0;
1339   GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
1340   rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
1341   rtp_jitter_buffer_disable_buffering (priv->jbuf, FALSE);
1342   rtp_jitter_buffer_reset_skew (priv->jbuf);
1343   remove_all_timers (jitterbuffer);
1344   g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
1345   g_queue_clear (&priv->gap_packets);
1346   JBUF_UNLOCK (priv);
1347 }
1348
1349 static gboolean
1350 gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1351     GstPadMode mode, gboolean active)
1352 {
1353   gboolean result;
1354   GstRtpJitterBuffer *jitterbuffer = NULL;
1355
1356   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1357
1358   switch (mode) {
1359     case GST_PAD_MODE_PUSH:
1360       if (active) {
1361         /* allow data processing */
1362         gst_rtp_jitter_buffer_flush_stop (jitterbuffer);
1363
1364         /* start pushing out buffers */
1365         GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
1366         result = gst_pad_start_task (jitterbuffer->priv->srcpad,
1367             (GstTaskFunction) gst_rtp_jitter_buffer_loop, jitterbuffer, NULL);
1368       } else {
1369         /* make sure all data processing stops ASAP */
1370         gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1371
1372         /* NOTE this will hardlock if the state change is called from the src pad
1373          * task thread because we will _join() the thread. */
1374         GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
1375         result = gst_pad_stop_task (pad);
1376       }
1377       break;
1378     default:
1379       result = FALSE;
1380       break;
1381   }
1382   return result;
1383 }
1384
1385 static GstStateChangeReturn
1386 gst_rtp_jitter_buffer_change_state (GstElement * element,
1387     GstStateChange transition)
1388 {
1389   GstRtpJitterBuffer *jitterbuffer;
1390   GstRtpJitterBufferPrivate *priv;
1391   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1392
1393   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
1394   priv = jitterbuffer->priv;
1395
1396   switch (transition) {
1397     case GST_STATE_CHANGE_NULL_TO_READY:
1398       break;
1399     case GST_STATE_CHANGE_READY_TO_PAUSED:
1400       JBUF_LOCK (priv);
1401       /* reset negotiated values */
1402       priv->clock_rate = -1;
1403       priv->clock_base = -1;
1404       priv->peer_latency = 0;
1405       priv->last_pt = -1;
1406       /* block until we go to PLAYING */
1407       priv->blocked = TRUE;
1408       priv->timer_running = TRUE;
1409       priv->timer_thread =
1410           g_thread_new ("timer", (GThreadFunc) wait_next_timeout, jitterbuffer);
1411       JBUF_UNLOCK (priv);
1412       break;
1413     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1414       JBUF_LOCK (priv);
1415       /* unblock to allow streaming in PLAYING */
1416       priv->blocked = FALSE;
1417       JBUF_SIGNAL_EVENT (priv);
1418       JBUF_SIGNAL_TIMER (priv);
1419       JBUF_UNLOCK (priv);
1420       break;
1421     default:
1422       break;
1423   }
1424
1425   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1426
1427   switch (transition) {
1428     case GST_STATE_CHANGE_READY_TO_PAUSED:
1429       /* we are a live element because we sync to the clock, which we can only
1430        * do in the PLAYING state */
1431       if (ret != GST_STATE_CHANGE_FAILURE)
1432         ret = GST_STATE_CHANGE_NO_PREROLL;
1433       break;
1434     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1435       JBUF_LOCK (priv);
1436       /* block to stop streaming when PAUSED */
1437       priv->blocked = TRUE;
1438       unschedule_current_timer (jitterbuffer);
1439       JBUF_UNLOCK (priv);
1440       if (ret != GST_STATE_CHANGE_FAILURE)
1441         ret = GST_STATE_CHANGE_NO_PREROLL;
1442       break;
1443     case GST_STATE_CHANGE_PAUSED_TO_READY:
1444       JBUF_LOCK (priv);
1445       gst_buffer_replace (&priv->last_sr, NULL);
1446       priv->timer_running = FALSE;
1447       unschedule_current_timer (jitterbuffer);
1448       JBUF_SIGNAL_TIMER (priv);
1449       JBUF_SIGNAL_QUERY (priv, FALSE);
1450       JBUF_UNLOCK (priv);
1451       g_thread_join (priv->timer_thread);
1452       priv->timer_thread = NULL;
1453       break;
1454     case GST_STATE_CHANGE_READY_TO_NULL:
1455       break;
1456     default:
1457       break;
1458   }
1459
1460   return ret;
1461 }
1462
1463 static gboolean
1464 gst_rtp_jitter_buffer_src_event (GstPad * pad, GstObject * parent,
1465     GstEvent * event)
1466 {
1467   gboolean ret = TRUE;
1468   GstRtpJitterBuffer *jitterbuffer;
1469   GstRtpJitterBufferPrivate *priv;
1470
1471   jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
1472   priv = jitterbuffer->priv;
1473
1474   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1475
1476   switch (GST_EVENT_TYPE (event)) {
1477     case GST_EVENT_LATENCY:
1478     {
1479       GstClockTime latency;
1480
1481       gst_event_parse_latency (event, &latency);
1482
1483       GST_DEBUG_OBJECT (jitterbuffer,
1484           "configuring latency of %" GST_TIME_FORMAT, GST_TIME_ARGS (latency));
1485
1486       JBUF_LOCK (priv);
1487       /* adjust the overall buffer delay to the total pipeline latency in
1488        * buffering mode because if downstream consumes too fast (because of
1489        * large latency or queues, we would start rebuffering again. */
1490       if (rtp_jitter_buffer_get_mode (priv->jbuf) ==
1491           RTP_JITTER_BUFFER_MODE_BUFFER) {
1492         rtp_jitter_buffer_set_delay (priv->jbuf, latency);
1493       }
1494       JBUF_UNLOCK (priv);
1495
1496       ret = gst_pad_push_event (priv->sinkpad, event);
1497       break;
1498     }
1499     default:
1500       ret = gst_pad_push_event (priv->sinkpad, event);
1501       break;
1502   }
1503
1504   return ret;
1505 }
1506
1507 /* handles and stores the event in the jitterbuffer, must be called with
1508  * LOCK */
1509 static gboolean
1510 queue_event (GstRtpJitterBuffer * jitterbuffer, GstEvent * event)
1511 {
1512   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1513   RTPJitterBufferItem *item;
1514   gboolean head;
1515
1516   switch (GST_EVENT_TYPE (event)) {
1517     case GST_EVENT_CAPS:
1518     {
1519       GstCaps *caps;
1520
1521       gst_event_parse_caps (event, &caps);
1522       gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1523       break;
1524     }
1525     case GST_EVENT_SEGMENT:
1526       gst_event_copy_segment (event, &priv->segment);
1527
1528       /* we need time for now */
1529       if (priv->segment.format != GST_FORMAT_TIME)
1530         goto newseg_wrong_format;
1531
1532       GST_DEBUG_OBJECT (jitterbuffer,
1533           "segment:  %" GST_SEGMENT_FORMAT, &priv->segment);
1534       break;
1535     case GST_EVENT_EOS:
1536       priv->eos = TRUE;
1537       rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
1538       break;
1539     default:
1540       break;
1541   }
1542
1543
1544   GST_DEBUG_OBJECT (jitterbuffer, "adding event");
1545   item = alloc_item (event, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
1546   rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
1547   if (head)
1548     JBUF_SIGNAL_EVENT (priv);
1549
1550   return TRUE;
1551
1552   /* ERRORS */
1553 newseg_wrong_format:
1554   {
1555     GST_DEBUG_OBJECT (jitterbuffer, "received non TIME newsegment");
1556     gst_event_unref (event);
1557     return FALSE;
1558   }
1559 }
1560
1561 static gboolean
1562 gst_rtp_jitter_buffer_sink_event (GstPad * pad, GstObject * parent,
1563     GstEvent * event)
1564 {
1565   gboolean ret = TRUE;
1566   GstRtpJitterBuffer *jitterbuffer;
1567   GstRtpJitterBufferPrivate *priv;
1568
1569   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1570   priv = jitterbuffer->priv;
1571
1572   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1573
1574   switch (GST_EVENT_TYPE (event)) {
1575     case GST_EVENT_FLUSH_START:
1576       ret = gst_pad_push_event (priv->srcpad, event);
1577       gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1578       /* wait for the loop to go into PAUSED */
1579       gst_pad_pause_task (priv->srcpad);
1580       break;
1581     case GST_EVENT_FLUSH_STOP:
1582       ret = gst_pad_push_event (priv->srcpad, event);
1583       ret =
1584           gst_rtp_jitter_buffer_src_activate_mode (priv->srcpad, parent,
1585           GST_PAD_MODE_PUSH, TRUE);
1586       break;
1587     default:
1588       if (GST_EVENT_IS_SERIALIZED (event)) {
1589         /* serialized events go in the queue */
1590         JBUF_LOCK (priv);
1591         if (priv->srcresult != GST_FLOW_OK) {
1592           /* Errors in sticky event pushing are no problem and ignored here
1593            * as they will cause more meaningful errors during data flow.
1594            * For EOS events, that are not followed by data flow, we still
1595            * return FALSE here though.
1596            */
1597           if (!GST_EVENT_IS_STICKY (event) ||
1598               GST_EVENT_TYPE (event) == GST_EVENT_EOS)
1599             goto out_flow_error;
1600         }
1601         /* refuse more events on EOS */
1602         if (priv->eos)
1603           goto out_eos;
1604         ret = queue_event (jitterbuffer, event);
1605         JBUF_UNLOCK (priv);
1606       } else {
1607         /* non-serialized events are forwarded downstream immediately */
1608         ret = gst_pad_push_event (priv->srcpad, event);
1609       }
1610       break;
1611   }
1612   return ret;
1613
1614   /* ERRORS */
1615 out_flow_error:
1616   {
1617     GST_DEBUG_OBJECT (jitterbuffer,
1618         "refusing event, we have a downstream flow error: %s",
1619         gst_flow_get_name (priv->srcresult));
1620     JBUF_UNLOCK (priv);
1621     gst_event_unref (event);
1622     return FALSE;
1623   }
1624 out_eos:
1625   {
1626     GST_DEBUG_OBJECT (jitterbuffer, "refusing event, we are EOS");
1627     JBUF_UNLOCK (priv);
1628     gst_event_unref (event);
1629     return FALSE;
1630   }
1631 }
1632
1633 static gboolean
1634 gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
1635     GstEvent * event)
1636 {
1637   gboolean ret = TRUE;
1638   GstRtpJitterBuffer *jitterbuffer;
1639
1640   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1641
1642   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1643
1644   switch (GST_EVENT_TYPE (event)) {
1645     case GST_EVENT_FLUSH_START:
1646       gst_event_unref (event);
1647       break;
1648     case GST_EVENT_FLUSH_STOP:
1649       gst_event_unref (event);
1650       break;
1651     default:
1652       ret = gst_pad_event_default (pad, parent, event);
1653       break;
1654   }
1655
1656   return ret;
1657 }
1658
1659 /*
1660  * Must be called with JBUF_LOCK held, will release the LOCK when emiting the
1661  * signal. The function returns GST_FLOW_ERROR when a parsing error happened and
1662  * GST_FLOW_FLUSHING when the element is shutting down. On success
1663  * GST_FLOW_OK is returned.
1664  */
1665 static GstFlowReturn
1666 gst_rtp_jitter_buffer_get_clock_rate (GstRtpJitterBuffer * jitterbuffer,
1667     guint8 pt)
1668 {
1669   GValue ret = { 0 };
1670   GValue args[2] = { {0}, {0} };
1671   GstCaps *caps;
1672   gboolean res;
1673
1674   g_value_init (&args[0], GST_TYPE_ELEMENT);
1675   g_value_set_object (&args[0], jitterbuffer);
1676   g_value_init (&args[1], G_TYPE_UINT);
1677   g_value_set_uint (&args[1], pt);
1678
1679   g_value_init (&ret, GST_TYPE_CAPS);
1680   g_value_set_boxed (&ret, NULL);
1681
1682   JBUF_UNLOCK (jitterbuffer->priv);
1683   g_signal_emitv (args, gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
1684       &ret);
1685   JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
1686
1687   g_value_unset (&args[0]);
1688   g_value_unset (&args[1]);
1689   caps = (GstCaps *) g_value_dup_boxed (&ret);
1690   g_value_unset (&ret);
1691   if (!caps)
1692     goto no_caps;
1693
1694   res = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1695   gst_caps_unref (caps);
1696
1697   if (G_UNLIKELY (!res))
1698     goto parse_failed;
1699
1700   return GST_FLOW_OK;
1701
1702   /* ERRORS */
1703 no_caps:
1704   {
1705     GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
1706     return GST_FLOW_ERROR;
1707   }
1708 out_flushing:
1709   {
1710     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1711     return GST_FLOW_FLUSHING;
1712   }
1713 parse_failed:
1714   {
1715     GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
1716     return GST_FLOW_ERROR;
1717   }
1718 }
1719
1720 /* call with jbuf lock held */
1721 static GstMessage *
1722 check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
1723 {
1724   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1725   GstMessage *message = NULL;
1726
1727   if (percent == -1)
1728     return NULL;
1729
1730   /* Post a buffering message */
1731   if (priv->last_percent != percent) {
1732     priv->last_percent = percent;
1733     message =
1734         gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
1735     gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
1736   }
1737
1738   return message;
1739 }
1740
1741 static GstClockTime
1742 apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1743 {
1744   GstRtpJitterBufferPrivate *priv;
1745
1746   priv = jitterbuffer->priv;
1747
1748   if (timestamp == -1)
1749     return -1;
1750
1751   /* apply the timestamp offset, this is used for inter stream sync */
1752   timestamp += priv->ts_offset;
1753   /* add the offset, this is used when buffering */
1754   timestamp += priv->out_offset;
1755
1756   return timestamp;
1757 }
1758
1759 static TimerData *
1760 find_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type, guint16 seqnum)
1761 {
1762   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1763   TimerData *timer = NULL;
1764   gint i, len;
1765
1766   len = priv->timers->len;
1767   for (i = 0; i < len; i++) {
1768     TimerData *test = &g_array_index (priv->timers, TimerData, i);
1769     if (test->seqnum == seqnum && test->type == type) {
1770       timer = test;
1771       break;
1772     }
1773   }
1774   return timer;
1775 }
1776
1777 static void
1778 unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer)
1779 {
1780   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1781
1782   if (priv->clock_id) {
1783     GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
1784     gst_clock_id_unschedule (priv->clock_id);
1785     priv->clock_id = NULL;
1786   }
1787 }
1788
1789 static GstClockTime
1790 get_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1791 {
1792   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1793   GstClockTime test_timeout;
1794
1795   if ((test_timeout = timer->timeout) == -1)
1796     return -1;
1797
1798   if (timer->type != TIMER_TYPE_EXPECTED) {
1799     /* add our latency and offset to get output times. */
1800     test_timeout = apply_offset (jitterbuffer, test_timeout);
1801     test_timeout += priv->latency_ns;
1802   }
1803   return test_timeout;
1804 }
1805
1806 static void
1807 recalculate_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1808 {
1809   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1810
1811   if (priv->clock_id) {
1812     GstClockTime timeout = get_timeout (jitterbuffer, timer);
1813
1814     GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
1815         GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
1816
1817     if (timeout == -1 || timeout < priv->timer_timeout)
1818       unschedule_current_timer (jitterbuffer);
1819   }
1820 }
1821
1822 static TimerData *
1823 add_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1824     guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
1825     GstClockTime duration)
1826 {
1827   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1828   TimerData *timer;
1829   gint len;
1830
1831   GST_DEBUG_OBJECT (jitterbuffer,
1832       "add timer %d for seqnum %d to %" GST_TIME_FORMAT ", delay %"
1833       GST_TIME_FORMAT, type, seqnum, GST_TIME_ARGS (timeout),
1834       GST_TIME_ARGS (delay));
1835
1836   len = priv->timers->len;
1837   g_array_set_size (priv->timers, len + 1);
1838   timer = &g_array_index (priv->timers, TimerData, len);
1839   timer->idx = len;
1840   timer->type = type;
1841   timer->seqnum = seqnum;
1842   timer->num = num;
1843   timer->timeout = timeout + delay;
1844   timer->duration = duration;
1845   if (type == TIMER_TYPE_EXPECTED) {
1846     timer->rtx_base = timeout;
1847     timer->rtx_delay = delay;
1848     timer->rtx_retry = 0;
1849   }
1850   timer->num_rtx_retry = 0;
1851   recalculate_timer (jitterbuffer, timer);
1852   JBUF_SIGNAL_TIMER (priv);
1853
1854   return timer;
1855 }
1856
1857 static void
1858 reschedule_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
1859     guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
1860 {
1861   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1862   gboolean seqchange, timechange;
1863   guint16 oldseq;
1864
1865   seqchange = timer->seqnum != seqnum;
1866   timechange = timer->timeout != timeout;
1867
1868   if (!seqchange && !timechange)
1869     return;
1870
1871   oldseq = timer->seqnum;
1872
1873   GST_DEBUG_OBJECT (jitterbuffer,
1874       "replace timer for seqnum %d->%d to %" GST_TIME_FORMAT,
1875       oldseq, seqnum, GST_TIME_ARGS (timeout + delay));
1876
1877   timer->timeout = timeout + delay;
1878   timer->seqnum = seqnum;
1879   if (reset) {
1880     timer->rtx_base = timeout;
1881     timer->rtx_delay = delay;
1882     timer->rtx_retry = 0;
1883   }
1884   if (seqchange)
1885     timer->num_rtx_retry = 0;
1886
1887   if (priv->clock_id) {
1888     /* we changed the seqnum and there is a timer currently waiting with this
1889      * seqnum, unschedule it */
1890     if (seqchange && priv->timer_seqnum == oldseq)
1891       unschedule_current_timer (jitterbuffer);
1892     /* we changed the time, check if it is earlier than what we are waiting
1893      * for and unschedule if so */
1894     else if (timechange)
1895       recalculate_timer (jitterbuffer, timer);
1896   }
1897 }
1898
1899 static TimerData *
1900 set_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1901     guint16 seqnum, GstClockTime timeout)
1902 {
1903   TimerData *timer;
1904
1905   /* find the seqnum timer */
1906   timer = find_timer (jitterbuffer, type, seqnum);
1907   if (timer == NULL) {
1908     timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
1909   } else {
1910     reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
1911   }
1912   return timer;
1913 }
1914
1915 static void
1916 remove_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1917 {
1918   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1919   guint idx;
1920
1921   if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
1922     unschedule_current_timer (jitterbuffer);
1923
1924   idx = timer->idx;
1925   GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
1926   g_array_remove_index_fast (priv->timers, idx);
1927   timer->idx = idx;
1928 }
1929
1930 static void
1931 remove_all_timers (GstRtpJitterBuffer * jitterbuffer)
1932 {
1933   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1934   GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
1935   g_array_set_size (priv->timers, 0);
1936   unschedule_current_timer (jitterbuffer);
1937 }
1938
1939 /* get the extra delay to wait before sending RTX */
1940 static GstClockTime
1941 get_rtx_delay (GstRtpJitterBufferPrivate * priv)
1942 {
1943   GstClockTime delay;
1944
1945   if (priv->rtx_delay == -1) {
1946     if (priv->avg_jitter == 0 && priv->packet_spacing == 0) {
1947       delay = DEFAULT_AUTO_RTX_DELAY;
1948     } else {
1949       /* jitter is in nanoseconds, maximum of 2x jitter and half the
1950        * packet spacing is a good margin */
1951       delay = MAX (priv->avg_jitter * 2, priv->packet_spacing / 2);
1952     }
1953   } else {
1954     delay = priv->rtx_delay * GST_MSECOND;
1955   }
1956   if (priv->rtx_min_delay > 0)
1957     delay = MAX (delay, priv->rtx_min_delay * GST_MSECOND);
1958
1959   return delay;
1960 }
1961
1962 /* we just received a packet with seqnum and dts.
1963  *
1964  * First check for old seqnum that we are still expecting. If the gap with the
1965  * current seqnum is too big, unschedule the timeouts.
1966  *
1967  * If we have a valid packet spacing estimate we can set a timer for when we
1968  * should receive the next packet.
1969  * If we don't have a valid estimate, we remove any timer we might have
1970  * had for this packet.
1971  */
1972 static void
1973 update_timers (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum,
1974     GstClockTime dts, gboolean do_next_seqnum)
1975 {
1976   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1977   TimerData *timer = NULL;
1978   gint i, len;
1979
1980   /* go through all timers and unschedule the ones with a large gap, also find
1981    * the timer for the seqnum */
1982   len = priv->timers->len;
1983   for (i = 0; i < len; i++) {
1984     TimerData *test = &g_array_index (priv->timers, TimerData, i);
1985     gint gap;
1986
1987     gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
1988
1989     GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, #%d<->#%d gap %d", i,
1990         test->type, test->seqnum, seqnum, gap);
1991
1992     if (gap == 0) {
1993       GST_DEBUG ("found timer for current seqnum");
1994       /* the timer for the current seqnum */
1995       timer = test;
1996       /* when no retransmission, we can stop now, we only need to find the
1997        * timer for the current seqnum */
1998       if (!priv->do_retransmission)
1999         break;
2000     } else if (gap > priv->rtx_delay_reorder) {
2001       /* max gap, we exceeded the max reorder distance and we don't expect the
2002        * missing packet to be this reordered */
2003       if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
2004         reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
2005     }
2006   }
2007
2008   do_next_seqnum = do_next_seqnum && priv->packet_spacing > 0
2009       && priv->do_retransmission && priv->rtx_next_seqnum;
2010
2011   if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2012     if (timer->num_rtx_retry > 0) {
2013       GstClockTime rtx_last, delay;
2014
2015       /* we scheduled a retry for this packet and now we have it */
2016       priv->num_rtx_success++;
2017       /* all the previous retry attempts failed */
2018       priv->num_rtx_failed += timer->num_rtx_retry - 1;
2019       /* number of retries before receiving the packet */
2020       if (priv->avg_rtx_num == 0.0)
2021         priv->avg_rtx_num = timer->num_rtx_retry;
2022       else
2023         priv->avg_rtx_num = (timer->num_rtx_retry + 7 * priv->avg_rtx_num) / 8;
2024       /* calculate the delay between retransmission request and receiving this
2025        * packet, start with when we scheduled this timeout last */
2026       rtx_last = timer->rtx_last;
2027       if (dts != GST_CLOCK_TIME_NONE && dts > rtx_last) {
2028         /* we have a valid delay if this packet arrived after we scheduled the
2029          * request */
2030         delay = dts - rtx_last;
2031         if (priv->avg_rtx_rtt == 0)
2032           priv->avg_rtx_rtt = delay;
2033         else
2034           priv->avg_rtx_rtt = (delay + 7 * priv->avg_rtx_rtt) / 8;
2035       } else
2036         delay = 0;
2037
2038       GST_LOG_OBJECT (jitterbuffer,
2039           "RTX success %" G_GUINT64_FORMAT ", failed %" G_GUINT64_FORMAT
2040           ", requests %" G_GUINT64_FORMAT ", dups %" G_GUINT64_FORMAT
2041           ", avg-num %g, delay %" GST_TIME_FORMAT ", avg-rtt %" GST_TIME_FORMAT,
2042           priv->num_rtx_success, priv->num_rtx_failed, priv->num_rtx_requests,
2043           priv->num_duplicates, priv->avg_rtx_num, GST_TIME_ARGS (delay),
2044           GST_TIME_ARGS (priv->avg_rtx_rtt));
2045
2046       /* don't try to estimate the next seqnum because this is a retransmitted
2047        * packet and it probably did not arrive with the expected packet
2048        * spacing. */
2049       do_next_seqnum = FALSE;
2050     }
2051   }
2052
2053   if (do_next_seqnum && dts != GST_CLOCK_TIME_NONE) {
2054     GstClockTime expected, delay;
2055
2056     /* calculate expected arrival time of the next seqnum */
2057     expected = dts + priv->packet_spacing;
2058
2059     delay = get_rtx_delay (priv);
2060
2061     /* and update/install timer for next seqnum */
2062     if (timer) {
2063       reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
2064           delay, TRUE);
2065     } else {
2066       add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
2067           expected, delay, priv->packet_spacing);
2068     }
2069   } else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2070     /* if we had a timer, remove it, we don't know when to expect the next
2071      * packet. */
2072     remove_timer (jitterbuffer, timer);
2073   }
2074 }
2075
2076 static void
2077 calculate_packet_spacing (GstRtpJitterBuffer * jitterbuffer, guint32 rtptime,
2078     GstClockTime dts)
2079 {
2080   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2081
2082   /* we need consecutive seqnums with a different
2083    * rtptime to estimate the packet spacing. */
2084   if (priv->ips_rtptime != rtptime) {
2085     /* rtptime changed, check dts diff */
2086     if (priv->ips_dts != -1 && dts != -1 && dts > priv->ips_dts) {
2087       GstClockTime new_packet_spacing = dts - priv->ips_dts;
2088       GstClockTime old_packet_spacing = priv->packet_spacing;
2089
2090       /* Biased towards bigger packet spacings to prevent
2091        * too many unneeded retransmission requests for next
2092        * packets that just arrive a little later than we would
2093        * expect */
2094       if (old_packet_spacing > new_packet_spacing)
2095         priv->packet_spacing =
2096             (new_packet_spacing + 3 * old_packet_spacing) / 4;
2097       else if (old_packet_spacing > 0)
2098         priv->packet_spacing =
2099             (3 * new_packet_spacing + old_packet_spacing) / 4;
2100       else
2101         priv->packet_spacing = new_packet_spacing;
2102
2103       GST_DEBUG_OBJECT (jitterbuffer,
2104           "new packet spacing %" GST_TIME_FORMAT
2105           " old packet spacing %" GST_TIME_FORMAT
2106           " combined to %" GST_TIME_FORMAT,
2107           GST_TIME_ARGS (new_packet_spacing),
2108           GST_TIME_ARGS (old_packet_spacing),
2109           GST_TIME_ARGS (priv->packet_spacing));
2110     }
2111     priv->ips_rtptime = rtptime;
2112     priv->ips_dts = dts;
2113   }
2114 }
2115
2116 static void
2117 calculate_expected (GstRtpJitterBuffer * jitterbuffer, guint32 expected,
2118     guint16 seqnum, GstClockTime dts, gint gap)
2119 {
2120   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2121   GstClockTime total_duration, duration, expected_dts;
2122   TimerType type;
2123
2124   GST_DEBUG_OBJECT (jitterbuffer,
2125       "dts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
2126       GST_TIME_ARGS (dts), GST_TIME_ARGS (priv->last_in_dts));
2127
2128   if (dts == GST_CLOCK_TIME_NONE) {
2129     GST_WARNING_OBJECT (jitterbuffer, "Have no DTS");
2130     return;
2131   }
2132
2133   /* the total duration spanned by the missing packets */
2134   if (dts >= priv->last_in_dts)
2135     total_duration = dts - priv->last_in_dts;
2136   else
2137     total_duration = 0;
2138
2139   /* interpolate between the current time and the last time based on
2140    * number of packets we are missing, this is the estimated duration
2141    * for the missing packet based on equidistant packet spacing. */
2142   duration = total_duration / (gap + 1);
2143
2144   GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
2145       GST_TIME_ARGS (duration));
2146
2147   if (total_duration > priv->latency_ns) {
2148     GstClockTime gap_time;
2149     guint lost_packets;
2150
2151     if (duration > 0) {
2152       GstClockTime gap_dur = gap * duration;
2153       if (gap_dur > priv->latency_ns)
2154         gap_time = gap_dur - priv->latency_ns;
2155       else
2156         gap_time = 0;
2157       lost_packets = gap_time / duration;
2158     } else {
2159       gap_time = total_duration - priv->latency_ns;
2160       lost_packets = gap;
2161     }
2162
2163     /* too many lost packets, some of the missing packets are already
2164      * too late and we can generate lost packet events for them. */
2165     GST_DEBUG_OBJECT (jitterbuffer,
2166         "lost packets (%d, #%d->#%d) duration too large %" GST_TIME_FORMAT
2167         " > %" GST_TIME_FORMAT ", consider %u lost (%" GST_TIME_FORMAT ")",
2168         gap, expected, seqnum, GST_TIME_ARGS (total_duration),
2169         GST_TIME_ARGS (priv->latency_ns), lost_packets,
2170         GST_TIME_ARGS (gap_time));
2171
2172     /* this timer will fire immediately and the lost event will be pushed from
2173      * the timer thread */
2174     if (lost_packets > 0) {
2175       add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
2176           priv->last_in_dts + duration, 0, gap_time);
2177       expected += lost_packets;
2178       priv->last_in_dts += gap_time;
2179     }
2180   }
2181
2182   expected_dts = priv->last_in_dts + duration;
2183
2184   if (priv->do_retransmission) {
2185     TimerData *timer;
2186
2187     type = TIMER_TYPE_EXPECTED;
2188     /* if we had a timer for the first missing packet, update it. */
2189     if ((timer = find_timer (jitterbuffer, type, expected))) {
2190       GstClockTime timeout = timer->timeout;
2191
2192       timer->duration = duration;
2193       if (timeout > (expected_dts + timer->rtx_retry)) {
2194         GstClockTime delay = timeout - expected_dts - timer->rtx_retry;
2195         reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_dts,
2196             delay, TRUE);
2197       }
2198       expected++;
2199       expected_dts += duration;
2200     }
2201   } else {
2202     type = TIMER_TYPE_LOST;
2203   }
2204
2205   while (gst_rtp_buffer_compare_seqnum (expected, seqnum) > 0) {
2206     add_timer (jitterbuffer, type, expected, 0, expected_dts, 0, duration);
2207     expected_dts += duration;
2208     expected++;
2209   }
2210 }
2211
2212 static void
2213 calculate_jitter (GstRtpJitterBuffer * jitterbuffer, GstClockTime dts,
2214     guint rtptime)
2215 {
2216   gint32 rtpdiff;
2217   GstClockTimeDiff dtsdiff, rtpdiffns, diff;
2218   GstRtpJitterBufferPrivate *priv;
2219
2220   priv = jitterbuffer->priv;
2221
2222   if (G_UNLIKELY (dts == GST_CLOCK_TIME_NONE) || priv->clock_rate <= 0)
2223     goto no_time;
2224
2225   if (priv->last_dts != -1)
2226     dtsdiff = dts - priv->last_dts;
2227   else
2228     dtsdiff = 0;
2229
2230   if (priv->last_rtptime != -1)
2231     rtpdiff = rtptime - (guint32) priv->last_rtptime;
2232   else
2233     rtpdiff = 0;
2234
2235   priv->last_dts = dts;
2236   priv->last_rtptime = rtptime;
2237
2238   if (rtpdiff > 0)
2239     rtpdiffns =
2240         gst_util_uint64_scale_int (rtpdiff, GST_SECOND, priv->clock_rate);
2241   else
2242     rtpdiffns =
2243         -gst_util_uint64_scale_int (-rtpdiff, GST_SECOND, priv->clock_rate);
2244
2245   diff = ABS (dtsdiff - rtpdiffns);
2246
2247   /* jitter is stored in nanoseconds */
2248   priv->avg_jitter = (diff + (15 * priv->avg_jitter)) >> 4;
2249
2250   GST_LOG_OBJECT (jitterbuffer,
2251       "dtsdiff %" GST_TIME_FORMAT " rtptime %" GST_TIME_FORMAT
2252       ", clock-rate %d, diff %" GST_TIME_FORMAT ", jitter: %" GST_TIME_FORMAT,
2253       GST_TIME_ARGS (dtsdiff), GST_TIME_ARGS (rtpdiffns), priv->clock_rate,
2254       GST_TIME_ARGS (diff), GST_TIME_ARGS (priv->avg_jitter));
2255
2256   return;
2257
2258   /* ERRORS */
2259 no_time:
2260   {
2261     GST_DEBUG_OBJECT (jitterbuffer,
2262         "no dts or no clock-rate, can't calculate jitter");
2263     return;
2264   }
2265 }
2266
2267 static gint
2268 compare_buffer_seqnum (GstBuffer * a, GstBuffer * b, gpointer user_data)
2269 {
2270   GstRTPBuffer rtp_a = GST_RTP_BUFFER_INIT;
2271   GstRTPBuffer rtp_b = GST_RTP_BUFFER_INIT;
2272   guint seq_a, seq_b;
2273
2274   gst_rtp_buffer_map (a, GST_MAP_READ, &rtp_a);
2275   seq_a = gst_rtp_buffer_get_seq (&rtp_a);
2276   gst_rtp_buffer_unmap (&rtp_a);
2277
2278   gst_rtp_buffer_map (b, GST_MAP_READ, &rtp_b);
2279   seq_b = gst_rtp_buffer_get_seq (&rtp_b);
2280   gst_rtp_buffer_unmap (&rtp_b);
2281
2282   return gst_rtp_buffer_compare_seqnum (seq_b, seq_a);
2283 }
2284
2285 static gboolean
2286 handle_big_gap_buffer (GstRtpJitterBuffer * jitterbuffer, gboolean future,
2287     GstBuffer * buffer, guint8 pt, guint16 seqnum, gint gap)
2288 {
2289   GstRtpJitterBufferPrivate *priv;
2290   guint gap_packets_length;
2291   gboolean reset = FALSE;
2292
2293   priv = jitterbuffer->priv;
2294
2295   if ((gap_packets_length = g_queue_get_length (&priv->gap_packets)) > 0) {
2296     GList *l;
2297     guint32 prev_gap_seq = -1;
2298     gboolean all_consecutive = TRUE;
2299
2300     g_queue_insert_sorted (&priv->gap_packets, buffer,
2301         (GCompareDataFunc) compare_buffer_seqnum, NULL);
2302
2303     for (l = priv->gap_packets.head; l; l = l->next) {
2304       GstBuffer *gap_buffer = l->data;
2305       GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
2306       guint32 gap_seq;
2307
2308       gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
2309
2310       all_consecutive = (gst_rtp_buffer_get_payload_type (&gap_rtp) == pt);
2311
2312       gap_seq = gst_rtp_buffer_get_seq (&gap_rtp);
2313       if (prev_gap_seq == -1)
2314         prev_gap_seq = gap_seq;
2315       else if (gst_rtp_buffer_compare_seqnum (gap_seq, prev_gap_seq) != -1)
2316         all_consecutive = FALSE;
2317       else
2318         prev_gap_seq = gap_seq;
2319
2320       gst_rtp_buffer_unmap (&gap_rtp);
2321       if (!all_consecutive)
2322         break;
2323     }
2324
2325     if (all_consecutive && gap_packets_length > 3) {
2326       GST_DEBUG_OBJECT (jitterbuffer,
2327           "buffer too %s %d < %d, got 5 consecutive ones - reset",
2328           (future ? "new" : "old"), gap,
2329           (future ? RTP_MAX_DROPOUT : -RTP_MAX_MISORDER));
2330       reset = TRUE;
2331     } else if (!all_consecutive) {
2332       g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2333       g_queue_clear (&priv->gap_packets);
2334       GST_DEBUG_OBJECT (jitterbuffer,
2335           "buffer too %s %d < %d, got no 5 consecutive ones - dropping",
2336           (future ? "new" : "old"), gap,
2337           (future ? RTP_MAX_DROPOUT : -RTP_MAX_MISORDER));
2338       buffer = NULL;
2339     } else {
2340       GST_DEBUG_OBJECT (jitterbuffer,
2341           "buffer too %s %d < %d, got %u consecutive ones - waiting",
2342           (future ? "new" : "old"), gap,
2343           (future ? RTP_MAX_DROPOUT : -RTP_MAX_MISORDER),
2344           gap_packets_length + 1);
2345       buffer = NULL;
2346     }
2347   } else {
2348     GST_DEBUG_OBJECT (jitterbuffer,
2349         "buffer too %s %d < %d, first one - waiting", (future ? "new" : "old"),
2350         gap, -RTP_MAX_MISORDER);
2351     g_queue_push_tail (&priv->gap_packets, buffer);
2352     buffer = NULL;
2353   }
2354
2355   return reset;
2356 }
2357
2358 static GstClockTime
2359 get_current_running_time (GstRtpJitterBuffer * jitterbuffer)
2360 {
2361   GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (jitterbuffer));
2362   GstClockTime running_time = GST_CLOCK_TIME_NONE;
2363
2364   if (clock) {
2365     GstClockTime base_time =
2366         gst_element_get_base_time (GST_ELEMENT_CAST (jitterbuffer));
2367     GstClockTime clock_time = gst_clock_get_time (clock);
2368
2369     if (clock_time > base_time)
2370       running_time = clock_time - base_time;
2371     else
2372       running_time = 0;
2373
2374     gst_object_unref (clock);
2375   }
2376
2377   return running_time;
2378 }
2379
2380 static GstFlowReturn
2381 gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
2382     GstBuffer * buffer)
2383 {
2384   GstRtpJitterBuffer *jitterbuffer;
2385   GstRtpJitterBufferPrivate *priv;
2386   guint16 seqnum;
2387   guint32 expected, rtptime;
2388   GstFlowReturn ret = GST_FLOW_OK;
2389   GstClockTime dts, pts;
2390   guint64 latency_ts;
2391   gboolean head;
2392   gint percent = -1;
2393   guint8 pt;
2394   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
2395   gboolean do_next_seqnum = FALSE;
2396   RTPJitterBufferItem *item;
2397   GstMessage *msg = NULL;
2398   gboolean estimated_dts = FALSE;
2399
2400   jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
2401
2402   priv = jitterbuffer->priv;
2403
2404   if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
2405     goto invalid_buffer;
2406
2407   pt = gst_rtp_buffer_get_payload_type (&rtp);
2408   seqnum = gst_rtp_buffer_get_seq (&rtp);
2409   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
2410   gst_rtp_buffer_unmap (&rtp);
2411
2412   /* make sure we have PTS and DTS set */
2413   pts = GST_BUFFER_PTS (buffer);
2414   dts = GST_BUFFER_DTS (buffer);
2415   if (dts == -1)
2416     dts = pts;
2417   else if (pts == -1)
2418     pts = dts;
2419
2420   if (dts == -1) {
2421     /* If we have no DTS here, i.e. no capture time, get one from the
2422      * clock now to have something to calculate with in the future. */
2423     dts = get_current_running_time (jitterbuffer);
2424     pts = dts;
2425
2426     /* Remember that we estimated the DTS if we are running already
2427      * and this is not our first packet (or first packet after a reset).
2428      * If it's the first packet, we somehow must generate a timestamp for
2429      * everything, otherwise we can't calculate any times
2430      */
2431     estimated_dts = (priv->next_in_seqnum != -1);
2432   } else {
2433     /* take the DTS of the buffer. This is the time when the packet was
2434      * received and is used to calculate jitter and clock skew. We will adjust
2435      * this DTS with the smoothed value after processing it in the
2436      * jitterbuffer and assign it as the PTS. */
2437     /* bring to running time */
2438     dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
2439   }
2440
2441   GST_DEBUG_OBJECT (jitterbuffer,
2442       "Received packet #%d at time %" GST_TIME_FORMAT ", discont %d", seqnum,
2443       GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer));
2444
2445   JBUF_LOCK_CHECK (priv, out_flushing);
2446
2447   if (G_UNLIKELY (priv->last_pt != pt)) {
2448     GstCaps *caps;
2449
2450     GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
2451         pt);
2452
2453     priv->last_pt = pt;
2454     /* reset clock-rate so that we get a new one */
2455     priv->clock_rate = -1;
2456
2457     /* Try to get the clock-rate from the caps first if we can. If there are no
2458      * caps we must fire the signal to get the clock-rate. */
2459     if ((caps = gst_pad_get_current_caps (pad))) {
2460       gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
2461       gst_caps_unref (caps);
2462     }
2463   }
2464
2465   if (G_UNLIKELY (priv->clock_rate == -1)) {
2466     /* no clock rate given on the caps, try to get one with the signal */
2467     if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
2468             pt) == GST_FLOW_FLUSHING)
2469       goto out_flushing;
2470
2471     if (G_UNLIKELY (priv->clock_rate == -1))
2472       goto no_clock_rate;
2473   }
2474
2475   /* don't accept more data on EOS */
2476   if (G_UNLIKELY (priv->eos))
2477     goto have_eos;
2478
2479   calculate_jitter (jitterbuffer, dts, rtptime);
2480
2481   if (priv->seqnum_base != -1) {
2482     gint gap;
2483
2484     gap = gst_rtp_buffer_compare_seqnum (priv->seqnum_base, seqnum);
2485
2486     if (gap < 0) {
2487       GST_DEBUG_OBJECT (jitterbuffer,
2488           "packet seqnum #%d before seqnum-base #%d", seqnum,
2489           priv->seqnum_base);
2490       gst_buffer_unref (buffer);
2491       ret = GST_FLOW_OK;
2492       goto finished;
2493     } else if (gap > 16384) {
2494       /* From now on don't compare against the seqnum base anymore as
2495        * at some point in the future we will wrap around and also that
2496        * much reordering is very unlikely */
2497       priv->seqnum_base = -1;
2498     }
2499   }
2500
2501   expected = priv->next_in_seqnum;
2502
2503   /* now check against our expected seqnum */
2504   if (G_LIKELY (expected != -1)) {
2505     gint gap;
2506
2507     /* now calculate gap */
2508     gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
2509
2510     GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
2511         expected, seqnum, gap);
2512
2513     if (G_LIKELY (gap == 0)) {
2514       /* packet is expected */
2515       calculate_packet_spacing (jitterbuffer, rtptime, dts);
2516       do_next_seqnum = TRUE;
2517     } else {
2518       gboolean reset = FALSE;
2519
2520       if (gap < 0) {
2521         /* we received an old packet */
2522         if (G_UNLIKELY (gap != -1 && gap < -RTP_MAX_MISORDER)) {
2523           reset =
2524               handle_big_gap_buffer (jitterbuffer, FALSE, buffer, pt, seqnum,
2525               gap);
2526           buffer = NULL;
2527         } else {
2528           GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
2529         }
2530       } else {
2531         /* new packet, we are missing some packets */
2532         if (G_UNLIKELY (priv->timers->len >= RTP_MAX_DROPOUT)) {
2533           /* If we have timers for more than RTP_MAX_DROPOUT packets
2534            * pending this means that we have a huge gap overall. We can
2535            * reset the jitterbuffer at this point because there's
2536            * just too much data missing to be able to do anything
2537            * sensible with the past data. Just try again from the
2538            * next packet */
2539           GST_WARNING_OBJECT (jitterbuffer,
2540               "%d pending timers > %d - resetting", priv->timers->len,
2541               RTP_MAX_DROPOUT);
2542           reset = TRUE;
2543           gst_buffer_unref (buffer);
2544           buffer = NULL;
2545         } else if (G_UNLIKELY (gap >= RTP_MAX_DROPOUT)) {
2546           reset =
2547               handle_big_gap_buffer (jitterbuffer, TRUE, buffer, pt, seqnum,
2548               gap);
2549           buffer = NULL;
2550         } else {
2551           GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
2552           /* fill in the gap with EXPECTED timers */
2553           calculate_expected (jitterbuffer, expected, seqnum, dts, gap);
2554
2555           do_next_seqnum = TRUE;
2556         }
2557       }
2558       if (G_UNLIKELY (reset)) {
2559         GList *events = NULL, *l;
2560         GList *buffers;
2561
2562         GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
2563         rtp_jitter_buffer_flush (priv->jbuf,
2564             (GFunc) free_item_and_retain_events, &events);
2565         rtp_jitter_buffer_reset_skew (priv->jbuf);
2566         remove_all_timers (jitterbuffer);
2567         priv->discont = TRUE;
2568         priv->last_popped_seqnum = -1;
2569         priv->next_seqnum = seqnum;
2570
2571         priv->last_in_dts = -1;
2572         priv->next_in_seqnum = -1;
2573
2574         /* Insert all sticky events again in order, otherwise we would
2575          * potentially loose STREAM_START, CAPS or SEGMENT events
2576          */
2577         events = g_list_reverse (events);
2578         for (l = events; l; l = l->next) {
2579           RTPJitterBufferItem *item;
2580
2581           item = alloc_item (l->data, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
2582           rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
2583         }
2584         g_list_free (events);
2585
2586         JBUF_SIGNAL_EVENT (priv);
2587
2588         /* reset spacing estimation when gap */
2589         priv->ips_rtptime = -1;
2590         priv->ips_dts = GST_CLOCK_TIME_NONE;
2591
2592         buffers = g_list_copy (priv->gap_packets.head);
2593         g_queue_clear (&priv->gap_packets);
2594
2595         priv->ips_rtptime = -1;
2596         priv->ips_dts = GST_CLOCK_TIME_NONE;
2597         JBUF_UNLOCK (jitterbuffer->priv);
2598
2599         for (l = buffers; l; l = l->next) {
2600           ret = gst_rtp_jitter_buffer_chain (pad, parent, l->data);
2601           l->data = NULL;
2602           if (ret != GST_FLOW_OK)
2603             break;
2604         }
2605         for (; l; l = l->next)
2606           gst_buffer_unref (l->data);
2607         g_list_free (buffers);
2608
2609         return ret;
2610       }
2611       /* reset spacing estimation when gap */
2612       priv->ips_rtptime = -1;
2613       priv->ips_dts = GST_CLOCK_TIME_NONE;
2614     }
2615   } else {
2616     GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2617
2618     /* we don't know what the next_in_seqnum should be, wait for the last
2619      * possible moment to push this buffer, maybe we get an earlier seqnum
2620      * while we wait */
2621     set_timer (jitterbuffer, TIMER_TYPE_DEADLINE, seqnum, dts);
2622     do_next_seqnum = TRUE;
2623     /* take rtptime and dts to calculate packet spacing */
2624     priv->ips_rtptime = rtptime;
2625     priv->ips_dts = dts;
2626   }
2627
2628   /* We had no huge gap, let's drop all the gap packets */
2629   if (buffer != NULL) {
2630     GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets");
2631     g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2632     g_queue_clear (&priv->gap_packets);
2633   } else {
2634     GST_DEBUG_OBJECT (jitterbuffer,
2635         "Had big gap, waiting for more consecutive packets");
2636     JBUF_UNLOCK (jitterbuffer->priv);
2637     return GST_FLOW_OK;
2638   }
2639
2640   if (do_next_seqnum) {
2641     priv->last_in_dts = dts;
2642     priv->next_in_seqnum = (seqnum + 1) & 0xffff;
2643   }
2644
2645   /* let's check if this buffer is too late, we can only accept packets with
2646    * bigger seqnum than the one we last pushed. */
2647   if (G_LIKELY (priv->last_popped_seqnum != -1)) {
2648     gint gap;
2649
2650     gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
2651
2652     /* priv->last_popped_seqnum >= seqnum, we're too late. */
2653     if (G_UNLIKELY (gap <= 0))
2654       goto too_late;
2655   }
2656
2657   /* let's drop oldest packet if the queue is already full and drop-on-latency
2658    * is set. We can only do this when there actually is a latency. When no
2659    * latency is set, we just pump it in the queue and let the other end push it
2660    * out as fast as possible. */
2661   if (priv->latency_ms && priv->drop_on_latency) {
2662     latency_ts =
2663         gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
2664
2665     if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
2666       RTPJitterBufferItem *old_item;
2667
2668       old_item = rtp_jitter_buffer_peek (priv->jbuf);
2669
2670       if (IS_DROPABLE (old_item)) {
2671         old_item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2672         GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
2673             old_item);
2674         priv->next_seqnum = (old_item->seqnum + 1) & 0xffff;
2675         free_item (old_item);
2676       }
2677       /* we might have removed some head buffers, signal the pushing thread to
2678        * see if it can push now */
2679       JBUF_SIGNAL_EVENT (priv);
2680     }
2681   }
2682
2683   /* If we estimated the DTS, don't consider it in the clock skew calculations
2684    * later. The code above always sets dts to pts or the other way around if
2685    * any of those is valid in the buffer, so we know that if we estimated the
2686    * dts that both are unknown */
2687   if (estimated_dts)
2688     item =
2689         alloc_item (buffer, ITEM_TYPE_BUFFER, GST_CLOCK_TIME_NONE,
2690         GST_CLOCK_TIME_NONE, seqnum, 1, rtptime);
2691   else
2692     item = alloc_item (buffer, ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime);
2693
2694   /* now insert the packet into the queue in sorted order. This function returns
2695    * FALSE if a packet with the same seqnum was already in the queue, meaning we
2696    * have a duplicate. */
2697   if (G_UNLIKELY (!rtp_jitter_buffer_insert (priv->jbuf, item,
2698               &head, &percent)))
2699     goto duplicate;
2700
2701   /* update timers */
2702   update_timers (jitterbuffer, seqnum, dts, do_next_seqnum);
2703
2704   /* we had an unhandled SR, handle it now */
2705   if (priv->last_sr)
2706     do_handle_sync (jitterbuffer);
2707
2708   if (G_UNLIKELY (head)) {
2709     /* signal addition of new buffer when the _loop is waiting. */
2710     if (G_LIKELY (priv->active))
2711       JBUF_SIGNAL_EVENT (priv);
2712
2713     /* let's unschedule and unblock any waiting buffers. We only want to do this
2714      * when the head buffer changed */
2715     if (G_UNLIKELY (priv->clock_id)) {
2716       GST_DEBUG_OBJECT (jitterbuffer, "Unscheduling waiting new buffer");
2717       unschedule_current_timer (jitterbuffer);
2718     }
2719   }
2720
2721   GST_DEBUG_OBJECT (jitterbuffer,
2722       "Pushed packet #%d, now %d packets, head: %d, " "percent %d", seqnum,
2723       rtp_jitter_buffer_num_packets (priv->jbuf), head, percent);
2724
2725   msg = check_buffering_percent (jitterbuffer, percent);
2726
2727 finished:
2728   JBUF_UNLOCK (priv);
2729
2730   if (msg)
2731     gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2732
2733   return ret;
2734
2735   /* ERRORS */
2736 invalid_buffer:
2737   {
2738     /* this is not fatal but should be filtered earlier */
2739     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2740         ("Received invalid RTP payload, dropping"));
2741     gst_buffer_unref (buffer);
2742     return GST_FLOW_OK;
2743   }
2744 no_clock_rate:
2745   {
2746     GST_WARNING_OBJECT (jitterbuffer,
2747         "No clock-rate in caps!, dropping buffer");
2748     gst_buffer_unref (buffer);
2749     goto finished;
2750   }
2751 out_flushing:
2752   {
2753     ret = priv->srcresult;
2754     GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
2755     gst_buffer_unref (buffer);
2756     goto finished;
2757   }
2758 have_eos:
2759   {
2760     ret = GST_FLOW_EOS;
2761     GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
2762     gst_buffer_unref (buffer);
2763     goto finished;
2764   }
2765 too_late:
2766   {
2767     GST_WARNING_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
2768         " popped, dropping", seqnum, priv->last_popped_seqnum);
2769     priv->num_late++;
2770     gst_buffer_unref (buffer);
2771     goto finished;
2772   }
2773 duplicate:
2774   {
2775     GST_WARNING_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
2776         seqnum);
2777     priv->num_duplicates++;
2778     free_item (item);
2779     goto finished;
2780   }
2781 }
2782
2783 static GstClockTime
2784 compute_elapsed (GstRtpJitterBuffer * jitterbuffer, RTPJitterBufferItem * item)
2785 {
2786   guint64 ext_time, elapsed;
2787   guint32 rtp_time;
2788   GstRtpJitterBufferPrivate *priv;
2789
2790   priv = jitterbuffer->priv;
2791   rtp_time = item->rtptime;
2792
2793   GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
2794       G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
2795
2796   ext_time = priv->ext_timestamp;
2797   ext_time = gst_rtp_buffer_ext_timestamp (&ext_time, rtp_time);
2798   if (ext_time < priv->ext_timestamp) {
2799     ext_time = priv->ext_timestamp;
2800   } else {
2801     priv->ext_timestamp = ext_time;
2802   }
2803
2804   if (ext_time > priv->clock_base)
2805     elapsed = ext_time - priv->clock_base;
2806   else
2807     elapsed = 0;
2808
2809   elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
2810   return elapsed;
2811 }
2812
2813 static void
2814 update_estimated_eos (GstRtpJitterBuffer * jitterbuffer,
2815     RTPJitterBufferItem * item)
2816 {
2817   guint64 total, elapsed, left, estimated;
2818   GstClockTime out_time;
2819   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2820
2821   if (priv->npt_stop == -1 || priv->ext_timestamp == -1
2822       || priv->clock_base == -1 || priv->clock_rate <= 0)
2823     return;
2824
2825   /* compute the elapsed time */
2826   elapsed = compute_elapsed (jitterbuffer, item);
2827
2828   /* do nothing if elapsed time doesn't increment */
2829   if (priv->last_elapsed && elapsed <= priv->last_elapsed)
2830     return;
2831
2832   priv->last_elapsed = elapsed;
2833
2834   /* this is the total time we need to play */
2835   total = priv->npt_stop - priv->npt_start;
2836   GST_LOG_OBJECT (jitterbuffer, "total %" GST_TIME_FORMAT,
2837       GST_TIME_ARGS (total));
2838
2839   /* this is how much time there is left */
2840   if (total > elapsed)
2841     left = total - elapsed;
2842   else
2843     left = 0;
2844
2845   /* if we have less time left that the size of the buffer, we will not
2846    * be able to keep it filled, disabled buffering then */
2847   if (left < rtp_jitter_buffer_get_delay (priv->jbuf)) {
2848     GST_DEBUG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT
2849         ", disable buffering close to EOS", GST_TIME_ARGS (left));
2850     rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
2851   }
2852
2853   /* this is the current time as running-time */
2854   out_time = item->dts;
2855
2856   if (elapsed > 0)
2857     estimated = gst_util_uint64_scale (out_time, total, elapsed);
2858   else {
2859     /* if there is almost nothing left,
2860      * we may never advance enough to end up in the above case */
2861     if (total < GST_SECOND)
2862       estimated = GST_SECOND;
2863     else
2864       estimated = -1;
2865   }
2866   GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
2867       GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
2868
2869   if (estimated != -1 && priv->estimated_eos != estimated) {
2870     set_timer (jitterbuffer, TIMER_TYPE_EOS, -1, estimated);
2871     priv->estimated_eos = estimated;
2872   }
2873 }
2874
2875 /* take a buffer from the queue and push it */
2876 static GstFlowReturn
2877 pop_and_push_next (GstRtpJitterBuffer * jitterbuffer, guint seqnum)
2878 {
2879   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2880   GstFlowReturn result = GST_FLOW_OK;
2881   RTPJitterBufferItem *item;
2882   GstBuffer *outbuf = NULL;
2883   GstEvent *outevent = NULL;
2884   GstQuery *outquery = NULL;
2885   GstClockTime dts, pts;
2886   gint percent = -1;
2887   gboolean do_push = TRUE;
2888   guint type;
2889   GstMessage *msg;
2890
2891   /* when we get here we are ready to pop and push the buffer */
2892   item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2893   type = item->type;
2894
2895   switch (type) {
2896     case ITEM_TYPE_BUFFER:
2897
2898       /* we need to make writable to change the flags and timestamps */
2899       outbuf = gst_buffer_make_writable (item->data);
2900
2901       if (G_UNLIKELY (priv->discont)) {
2902         /* set DISCONT flag when we missed a packet. We pushed the buffer writable
2903          * into the jitterbuffer so we can modify now. */
2904         GST_DEBUG_OBJECT (jitterbuffer, "mark output buffer discont");
2905         GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
2906         priv->discont = FALSE;
2907       }
2908       if (G_UNLIKELY (priv->ts_discont)) {
2909         GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
2910         priv->ts_discont = FALSE;
2911       }
2912
2913       dts =
2914           gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->dts);
2915       pts =
2916           gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->pts);
2917
2918       /* apply timestamp with offset to buffer now */
2919       GST_BUFFER_DTS (outbuf) = apply_offset (jitterbuffer, dts);
2920       GST_BUFFER_PTS (outbuf) = apply_offset (jitterbuffer, pts);
2921
2922       /* update the elapsed time when we need to check against the npt stop time. */
2923       update_estimated_eos (jitterbuffer, item);
2924
2925       priv->last_out_time = GST_BUFFER_PTS (outbuf);
2926       break;
2927     case ITEM_TYPE_LOST:
2928       priv->discont = TRUE;
2929       if (!priv->do_lost)
2930         do_push = FALSE;
2931       /* FALLTHROUGH */
2932     case ITEM_TYPE_EVENT:
2933       outevent = item->data;
2934       break;
2935     case ITEM_TYPE_QUERY:
2936       outquery = item->data;
2937       break;
2938   }
2939
2940   /* now we are ready to push the buffer. Save the seqnum and release the lock
2941    * so the other end can push stuff in the queue again. */
2942   if (seqnum != -1) {
2943     priv->last_popped_seqnum = seqnum;
2944     priv->next_seqnum = (seqnum + item->count) & 0xffff;
2945   }
2946   msg = check_buffering_percent (jitterbuffer, percent);
2947   JBUF_UNLOCK (priv);
2948
2949   item->data = NULL;
2950   free_item (item);
2951
2952   if (msg)
2953     gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2954
2955   switch (type) {
2956     case ITEM_TYPE_BUFFER:
2957       /* push buffer */
2958       GST_DEBUG_OBJECT (jitterbuffer,
2959           "Pushing buffer %d, dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2960           seqnum, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
2961           GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
2962       result = gst_pad_push (priv->srcpad, outbuf);
2963
2964       JBUF_LOCK_CHECK (priv, out_flushing);
2965       break;
2966     case ITEM_TYPE_LOST:
2967     case ITEM_TYPE_EVENT:
2968       /* We got not enough consecutive packets with a huge gap, we can
2969        * as well just drop them here now on EOS */
2970       if (GST_EVENT_TYPE (outevent) == GST_EVENT_EOS) {
2971         GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets on EOS");
2972         g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2973         g_queue_clear (&priv->gap_packets);
2974       }
2975
2976       GST_DEBUG_OBJECT (jitterbuffer, "%sPushing event %" GST_PTR_FORMAT
2977           ", seqnum %d", do_push ? "" : "NOT ", outevent, seqnum);
2978
2979       if (do_push)
2980         gst_pad_push_event (priv->srcpad, outevent);
2981       else
2982         gst_event_unref (outevent);
2983
2984       result = GST_FLOW_OK;
2985
2986       JBUF_LOCK_CHECK (priv, out_flushing);
2987       break;
2988     case ITEM_TYPE_QUERY:
2989     {
2990       gboolean res;
2991
2992       res = gst_pad_peer_query (priv->srcpad, outquery);
2993
2994       JBUF_LOCK_CHECK (priv, out_flushing);
2995       result = GST_FLOW_OK;
2996       GST_LOG_OBJECT (jitterbuffer, "did query %p, return %d", outquery, res);
2997       JBUF_SIGNAL_QUERY (priv, res);
2998       break;
2999     }
3000   }
3001   return result;
3002
3003   /* ERRORS */
3004 out_flushing:
3005   {
3006     return priv->srcresult;
3007   }
3008 }
3009
3010 #define GST_FLOW_WAIT GST_FLOW_CUSTOM_SUCCESS
3011
3012 /* Peek a buffer and compare the seqnum to the expected seqnum.
3013  * If all is fine, the buffer is pushed.
3014  * If something is wrong, we wait for some event
3015  */
3016 static GstFlowReturn
3017 handle_next_buffer (GstRtpJitterBuffer * jitterbuffer)
3018 {
3019   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3020   GstFlowReturn result;
3021   RTPJitterBufferItem *item;
3022   guint seqnum;
3023   guint32 next_seqnum;
3024
3025   /* only push buffers when PLAYING and active and not buffering */
3026   if (priv->blocked || !priv->active ||
3027       rtp_jitter_buffer_is_buffering (priv->jbuf)) {
3028     return GST_FLOW_WAIT;
3029   }
3030
3031   /* peek a buffer, we're just looking at the sequence number.
3032    * If all is fine, we'll pop and push it. If the sequence number is wrong we
3033    * wait for a timeout or something to change.
3034    * The peeked buffer is valid for as long as we hold the jitterbuffer lock. */
3035   item = rtp_jitter_buffer_peek (priv->jbuf);
3036   if (item == NULL) {
3037     goto wait;
3038   }
3039
3040   /* get the seqnum and the next expected seqnum */
3041   seqnum = item->seqnum;
3042   if (seqnum == -1) {
3043     return pop_and_push_next (jitterbuffer, seqnum);
3044   }
3045
3046   next_seqnum = priv->next_seqnum;
3047
3048   /* get the gap between this and the previous packet. If we don't know the
3049    * previous packet seqnum assume no gap. */
3050   if (G_UNLIKELY (next_seqnum == -1)) {
3051     GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
3052     /* we don't know what the next_seqnum should be, the chain function should
3053      * have scheduled a DEADLINE timer that will increment next_seqnum when it
3054      * fires, so wait for that */
3055     result = GST_FLOW_WAIT;
3056   } else {
3057     gint gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
3058
3059     if (G_LIKELY (gap == 0)) {
3060       /* no missing packet, pop and push */
3061       result = pop_and_push_next (jitterbuffer, seqnum);
3062     } else if (G_UNLIKELY (gap < 0)) {
3063       /* if we have a packet that we already pushed or considered dropped, pop it
3064        * off and get the next packet */
3065       GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
3066           seqnum, next_seqnum);
3067       item = rtp_jitter_buffer_pop (priv->jbuf, NULL);
3068       free_item (item);
3069       result = GST_FLOW_OK;
3070     } else {
3071       /* the chain function has scheduled timers to request retransmission or
3072        * when to consider the packet lost, wait for that */
3073       GST_DEBUG_OBJECT (jitterbuffer,
3074           "Sequence number GAP detected: expected %d instead of %d (%d missing)",
3075           next_seqnum, seqnum, gap);
3076       result = GST_FLOW_WAIT;
3077     }
3078   }
3079
3080   return result;
3081
3082 wait:
3083   {
3084     GST_DEBUG_OBJECT (jitterbuffer, "no buffer, going to wait");
3085     if (priv->eos) {
3086       return GST_FLOW_EOS;
3087     } else {
3088       return GST_FLOW_WAIT;
3089     }
3090   }
3091 }
3092
3093 static GstClockTime
3094 get_rtx_retry_timeout (GstRtpJitterBufferPrivate * priv)
3095 {
3096   GstClockTime rtx_retry_timeout;
3097   GstClockTime rtx_min_retry_timeout;
3098
3099   if (priv->rtx_retry_timeout == -1) {
3100     if (priv->avg_rtx_rtt == 0)
3101       rtx_retry_timeout = DEFAULT_AUTO_RTX_TIMEOUT;
3102     else
3103       /* we want to ask for a retransmission after we waited for a
3104        * complete RTT and the additional jitter */
3105       rtx_retry_timeout = priv->avg_rtx_rtt + priv->avg_jitter * 2;
3106   } else {
3107     rtx_retry_timeout = priv->rtx_retry_timeout * GST_MSECOND;
3108   }
3109   /* make sure we don't retry too often. On very low latency networks,
3110    * the RTT and jitter can be very low. */
3111   if (priv->rtx_min_retry_timeout == -1) {
3112     rtx_min_retry_timeout = priv->packet_spacing;
3113   } else {
3114     rtx_min_retry_timeout = priv->rtx_min_retry_timeout * GST_MSECOND;
3115   }
3116   rtx_retry_timeout = MAX (rtx_retry_timeout, rtx_min_retry_timeout);
3117
3118   return rtx_retry_timeout;
3119 }
3120
3121 static GstClockTime
3122 get_rtx_retry_period (GstRtpJitterBufferPrivate * priv,
3123     GstClockTime rtx_retry_timeout)
3124 {
3125   GstClockTime rtx_retry_period;
3126
3127   if (priv->rtx_retry_period == -1) {
3128     /* we retry up to the configured jitterbuffer size but leaving some
3129      * room for the retransmission to arrive in time */
3130     if (rtx_retry_timeout > priv->latency_ns) {
3131       rtx_retry_period = 0;
3132     } else {
3133       rtx_retry_period = priv->latency_ns - rtx_retry_timeout;
3134     }
3135   } else {
3136     rtx_retry_period = priv->rtx_retry_period * GST_MSECOND;
3137   }
3138   return rtx_retry_period;
3139 }
3140
3141 /* the timeout for when we expected a packet expired */
3142 static gboolean
3143 do_expected_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3144     GstClockTime now)
3145 {
3146   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3147   GstEvent *event;
3148   guint delay, delay_ms, avg_rtx_rtt_ms;
3149   guint rtx_retry_timeout_ms, rtx_retry_period_ms;
3150   GstClockTime rtx_retry_period;
3151   GstClockTime rtx_retry_timeout;
3152   GstClock *clock;
3153
3154   GST_DEBUG_OBJECT (jitterbuffer, "expected %d didn't arrive, now %"
3155       GST_TIME_FORMAT, timer->seqnum, GST_TIME_ARGS (now));
3156
3157   rtx_retry_timeout = get_rtx_retry_timeout (priv);
3158   rtx_retry_period = get_rtx_retry_period (priv, rtx_retry_timeout);
3159
3160   GST_DEBUG_OBJECT (jitterbuffer, "timeout %" GST_TIME_FORMAT ", period %"
3161       GST_TIME_FORMAT, GST_TIME_ARGS (rtx_retry_timeout),
3162       GST_TIME_ARGS (rtx_retry_period));
3163
3164   delay = timer->rtx_delay + timer->rtx_retry;
3165
3166   delay_ms = GST_TIME_AS_MSECONDS (delay);
3167   rtx_retry_timeout_ms = GST_TIME_AS_MSECONDS (rtx_retry_timeout);
3168   rtx_retry_period_ms = GST_TIME_AS_MSECONDS (rtx_retry_period);
3169   avg_rtx_rtt_ms = GST_TIME_AS_MSECONDS (priv->avg_rtx_rtt);
3170
3171   event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
3172       gst_structure_new ("GstRTPRetransmissionRequest",
3173           "seqnum", G_TYPE_UINT, (guint) timer->seqnum,
3174           "running-time", G_TYPE_UINT64, timer->rtx_base,
3175           "delay", G_TYPE_UINT, delay_ms,
3176           "retry", G_TYPE_UINT, timer->num_rtx_retry,
3177           "frequency", G_TYPE_UINT, rtx_retry_timeout_ms,
3178           "period", G_TYPE_UINT, rtx_retry_period_ms,
3179           "deadline", G_TYPE_UINT, priv->latency_ms,
3180           "packet-spacing", G_TYPE_UINT64, priv->packet_spacing,
3181           "avg-rtt", G_TYPE_UINT, avg_rtx_rtt_ms, NULL));
3182
3183   priv->num_rtx_requests++;
3184   timer->num_rtx_retry++;
3185
3186   GST_OBJECT_LOCK (jitterbuffer);
3187   if ((clock = GST_ELEMENT_CLOCK (jitterbuffer))) {
3188     timer->rtx_last = gst_clock_get_time (clock);
3189     timer->rtx_last -= GST_ELEMENT_CAST (jitterbuffer)->base_time;
3190   } else {
3191     timer->rtx_last = now;
3192   }
3193   GST_OBJECT_UNLOCK (jitterbuffer);
3194
3195   /* calculate the timeout for the next retransmission attempt */
3196   timer->rtx_retry += rtx_retry_timeout;
3197   GST_DEBUG_OBJECT (jitterbuffer, "base %" GST_TIME_FORMAT ", delay %"
3198       GST_TIME_FORMAT ", retry %" GST_TIME_FORMAT ", num_retry %u",
3199       GST_TIME_ARGS (timer->rtx_base), GST_TIME_ARGS (timer->rtx_delay),
3200       GST_TIME_ARGS (timer->rtx_retry), timer->num_rtx_retry);
3201   if ((priv->rtx_max_retries != -1
3202           && timer->num_rtx_retry >= priv->rtx_max_retries)
3203       || (timer->rtx_retry + timer->rtx_delay > rtx_retry_period)) {
3204     GST_DEBUG_OBJECT (jitterbuffer, "reschedule as LOST timer");
3205     /* too many retransmission request, we now convert the timer
3206      * to a lost timer, leave the num_rtx_retry as it is for stats */
3207     timer->type = TIMER_TYPE_LOST;
3208     timer->rtx_delay = 0;
3209     timer->rtx_retry = 0;
3210   }
3211   reschedule_timer (jitterbuffer, timer, timer->seqnum,
3212       timer->rtx_base + timer->rtx_retry, timer->rtx_delay, FALSE);
3213
3214   JBUF_UNLOCK (priv);
3215   gst_pad_push_event (priv->sinkpad, event);
3216   JBUF_LOCK (priv);
3217
3218   return FALSE;
3219 }
3220
3221 /* a packet is lost */
3222 static gboolean
3223 do_lost_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3224     GstClockTime now)
3225 {
3226   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3227   GstClockTime duration, timestamp;
3228   guint seqnum, lost_packets, num_rtx_retry, next_in_seqnum;
3229   gboolean head;
3230   GstEvent *event;
3231   RTPJitterBufferItem *item;
3232
3233   seqnum = timer->seqnum;
3234   timestamp = apply_offset (jitterbuffer, timer->timeout);
3235   duration = timer->duration;
3236   if (duration == GST_CLOCK_TIME_NONE && priv->packet_spacing > 0)
3237     duration = priv->packet_spacing;
3238   lost_packets = MAX (timer->num, 1);
3239   num_rtx_retry = timer->num_rtx_retry;
3240
3241   /* we had a gap and thus we lost some packets. Create an event for this.  */
3242   if (lost_packets > 1)
3243     GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", seqnum,
3244         seqnum + lost_packets - 1);
3245   else
3246     GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", seqnum);
3247
3248   priv->num_late += lost_packets;
3249   priv->num_rtx_failed += num_rtx_retry;
3250
3251   next_in_seqnum = (seqnum + lost_packets) & 0xffff;
3252
3253   /* we now only accept seqnum bigger than this */
3254   if (gst_rtp_buffer_compare_seqnum (priv->next_in_seqnum, next_in_seqnum) > 0)
3255     priv->next_in_seqnum = next_in_seqnum;
3256
3257   /* create paket lost event */
3258   event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
3259       gst_structure_new ("GstRTPPacketLost",
3260           "seqnum", G_TYPE_UINT, (guint) seqnum,
3261           "timestamp", G_TYPE_UINT64, timestamp,
3262           "duration", G_TYPE_UINT64, duration,
3263           "retry", G_TYPE_UINT, num_rtx_retry, NULL));
3264
3265   item = alloc_item (event, ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1);
3266   rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3267
3268   /* remove timer now */
3269   remove_timer (jitterbuffer, timer);
3270   if (head)
3271     JBUF_SIGNAL_EVENT (priv);
3272
3273   return TRUE;
3274 }
3275
3276 static gboolean
3277 do_eos_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3278     GstClockTime now)
3279 {
3280   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3281
3282   GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
3283   remove_timer (jitterbuffer, timer);
3284   if (!priv->eos) {
3285     /* there was no EOS in the buffer, put one in there now */
3286     queue_event (jitterbuffer, gst_event_new_eos ());
3287   }
3288   JBUF_SIGNAL_EVENT (priv);
3289
3290   return TRUE;
3291 }
3292
3293 static gboolean
3294 do_deadline_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3295     GstClockTime now)
3296 {
3297   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3298
3299   GST_INFO_OBJECT (jitterbuffer, "got deadline timeout");
3300
3301   /* timer seqnum might have been obsoleted by caps seqnum-base,
3302    * only mess with current ongoing seqnum if still unknown */
3303   if (priv->next_seqnum == -1)
3304     priv->next_seqnum = timer->seqnum;
3305   remove_timer (jitterbuffer, timer);
3306   JBUF_SIGNAL_EVENT (priv);
3307
3308   return TRUE;
3309 }
3310
3311 static gboolean
3312 do_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3313     GstClockTime now)
3314 {
3315   gboolean removed = FALSE;
3316
3317   switch (timer->type) {
3318     case TIMER_TYPE_EXPECTED:
3319       removed = do_expected_timeout (jitterbuffer, timer, now);
3320       break;
3321     case TIMER_TYPE_LOST:
3322       removed = do_lost_timeout (jitterbuffer, timer, now);
3323       break;
3324     case TIMER_TYPE_DEADLINE:
3325       removed = do_deadline_timeout (jitterbuffer, timer, now);
3326       break;
3327     case TIMER_TYPE_EOS:
3328       removed = do_eos_timeout (jitterbuffer, timer, now);
3329       break;
3330   }
3331   return removed;
3332 }
3333
3334 /* called when we need to wait for the next timeout.
3335  *
3336  * We loop over the array of recorded timeouts and wait for the earliest one.
3337  * When it timed out, do the logic associated with the timer.
3338  *
3339  * If there are no timers, we wait on a gcond until something new happens.
3340  */
3341 static void
3342 wait_next_timeout (GstRtpJitterBuffer * jitterbuffer)
3343 {
3344   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3345   GstClockTime now = 0;
3346
3347   JBUF_LOCK (priv);
3348   while (priv->timer_running) {
3349     TimerData *timer = NULL;
3350     GstClockTime timer_timeout = -1;
3351     gint i, len;
3352
3353     /* If we have a clock, update "now" now with the very latest running time
3354      * we have. It is used below when timeouts are triggered to calculate
3355      * any next possible timeout. If we only update it after waiting for the
3356      * clock, we would give a too old time to the timeout functions.
3357      */
3358     GST_OBJECT_LOCK (jitterbuffer);
3359     if (GST_ELEMENT_CLOCK (jitterbuffer)) {
3360       now =
3361           gst_clock_get_time (GST_ELEMENT_CLOCK (jitterbuffer)) -
3362           GST_ELEMENT_CAST (jitterbuffer)->base_time;
3363     }
3364     GST_OBJECT_UNLOCK (jitterbuffer);
3365
3366     GST_DEBUG_OBJECT (jitterbuffer, "now %" GST_TIME_FORMAT,
3367         GST_TIME_ARGS (now));
3368
3369     len = priv->timers->len;
3370     for (i = 0; i < len; i++) {
3371       TimerData *test = &g_array_index (priv->timers, TimerData, i);
3372       GstClockTime test_timeout = get_timeout (jitterbuffer, test);
3373       gboolean save_best = FALSE;
3374
3375       GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, %d, %" GST_TIME_FORMAT,
3376           i, test->type, test->seqnum, GST_TIME_ARGS (test_timeout));
3377
3378       /* find the smallest timeout */
3379       if (timer == NULL) {
3380         save_best = TRUE;
3381       } else if (timer_timeout == -1) {
3382         /* we already have an immediate timeout, the new timer must be an
3383          * immediate timer with smaller seqnum to become the best */
3384         if (test_timeout == -1
3385             && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3386                     timer->seqnum) > 0))
3387           save_best = TRUE;
3388       } else if (test_timeout == -1) {
3389         /* first immediate timer */
3390         save_best = TRUE;
3391       } else if (test_timeout < timer_timeout) {
3392         /* earlier timer */
3393         save_best = TRUE;
3394       } else if (test_timeout == timer_timeout
3395           && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3396                   timer->seqnum) > 0)) {
3397         /* same timer, smaller seqnum */
3398         save_best = TRUE;
3399       }
3400       if (save_best) {
3401         GST_DEBUG_OBJECT (jitterbuffer, "new best %d", i);
3402         timer = test;
3403         timer_timeout = test_timeout;
3404       }
3405     }
3406     if (timer && !priv->blocked) {
3407       GstClock *clock;
3408       GstClockTime sync_time;
3409       GstClockID id;
3410       GstClockReturn ret;
3411       GstClockTimeDiff clock_jitter;
3412
3413       if (timer_timeout == -1 || timer_timeout <= now) {
3414         do_timeout (jitterbuffer, timer, now);
3415         /* check here, do_timeout could have released the lock */
3416         if (!priv->timer_running)
3417           break;
3418         continue;
3419       }
3420
3421       GST_OBJECT_LOCK (jitterbuffer);
3422       clock = GST_ELEMENT_CLOCK (jitterbuffer);
3423       if (!clock) {
3424         GST_OBJECT_UNLOCK (jitterbuffer);
3425         /* let's just push if there is no clock */
3426         GST_DEBUG_OBJECT (jitterbuffer, "No clock, timeout right away");
3427         now = timer_timeout;
3428         continue;
3429       }
3430
3431       /* prepare for sync against clock */
3432       sync_time = timer_timeout + GST_ELEMENT_CAST (jitterbuffer)->base_time;
3433       /* add latency of peer to get input time */
3434       sync_time += priv->peer_latency;
3435
3436       GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
3437           " with sync time %" GST_TIME_FORMAT,
3438           GST_TIME_ARGS (timer_timeout), GST_TIME_ARGS (sync_time));
3439
3440       /* create an entry for the clock */
3441       id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
3442       priv->timer_timeout = timer_timeout;
3443       priv->timer_seqnum = timer->seqnum;
3444       GST_OBJECT_UNLOCK (jitterbuffer);
3445
3446       /* release the lock so that the other end can push stuff or unlock */
3447       JBUF_UNLOCK (priv);
3448
3449       ret = gst_clock_id_wait (id, &clock_jitter);
3450
3451       JBUF_LOCK (priv);
3452       if (!priv->timer_running) {
3453         gst_clock_id_unref (id);
3454         priv->clock_id = NULL;
3455         break;
3456       }
3457
3458       if (ret != GST_CLOCK_UNSCHEDULED) {
3459         GST_DEBUG_OBJECT (jitterbuffer, "sync done, %d, #%d, %" G_GINT64_FORMAT,
3460             ret, priv->timer_seqnum, clock_jitter);
3461       } else {
3462         GST_DEBUG_OBJECT (jitterbuffer, "sync unscheduled");
3463       }
3464       /* and free the entry */
3465       gst_clock_id_unref (id);
3466       priv->clock_id = NULL;
3467     } else {
3468       /* no timers, wait for activity */
3469       JBUF_WAIT_TIMER (priv);
3470     }
3471   }
3472   JBUF_UNLOCK (priv);
3473
3474   GST_DEBUG_OBJECT (jitterbuffer, "we are stopping");
3475   return;
3476 }
3477
3478 /*
3479  * This funcion implements the main pushing loop on the source pad.
3480  *
3481  * It first tries to push as many buffers as possible. If there is a seqnum
3482  * mismatch, we wait for the next timeouts.
3483  */
3484 static void
3485 gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer)
3486 {
3487   GstRtpJitterBufferPrivate *priv;
3488   GstFlowReturn result = GST_FLOW_OK;
3489
3490   priv = jitterbuffer->priv;
3491
3492   JBUF_LOCK_CHECK (priv, flushing);
3493   do {
3494     result = handle_next_buffer (jitterbuffer);
3495     if (G_LIKELY (result == GST_FLOW_WAIT)) {
3496       /* now wait for the next event */
3497       JBUF_WAIT_EVENT (priv, flushing);
3498       result = GST_FLOW_OK;
3499     }
3500   } while (result == GST_FLOW_OK);
3501   /* store result for upstream */
3502   priv->srcresult = result;
3503   /* if we get here we need to pause */
3504   goto pause;
3505
3506   /* ERRORS */
3507 flushing:
3508   {
3509     result = priv->srcresult;
3510     goto pause;
3511   }
3512 pause:
3513   {
3514     GstEvent *event;
3515
3516     JBUF_SIGNAL_QUERY (priv, FALSE);
3517     JBUF_UNLOCK (priv);
3518
3519     GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s",
3520         gst_flow_get_name (result));
3521     gst_pad_pause_task (priv->srcpad);
3522     if (result == GST_FLOW_EOS) {
3523       event = gst_event_new_eos ();
3524       gst_pad_push_event (priv->srcpad, event);
3525     }
3526     return;
3527   }
3528 }
3529
3530 /* collect the info from the lastest RTCP packet and the jitterbuffer sync, do
3531  * some sanity checks and then emit the handle-sync signal with the parameters.
3532  * This function must be called with the LOCK */
3533 static void
3534 do_handle_sync (GstRtpJitterBuffer * jitterbuffer)
3535 {
3536   GstRtpJitterBufferPrivate *priv;
3537   guint64 base_rtptime, base_time;
3538   guint32 clock_rate;
3539   guint64 last_rtptime;
3540   guint64 clock_base;
3541   guint64 ext_rtptime, diff;
3542   gboolean valid = TRUE, keep = FALSE;
3543
3544   priv = jitterbuffer->priv;
3545
3546   /* get the last values from the jitterbuffer */
3547   rtp_jitter_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
3548       &clock_rate, &last_rtptime);
3549
3550   clock_base = priv->clock_base;
3551   ext_rtptime = priv->ext_rtptime;
3552
3553   GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
3554       G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
3555       ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
3556       ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
3557
3558   if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
3559     /* we keep this SR packet for later. When we get a valid RTP packet the
3560      * above values will be set and we can try to use the SR packet */
3561     GST_DEBUG_OBJECT (jitterbuffer, "keeping for later, no RTP values");
3562     keep = TRUE;
3563   } else {
3564     /* we can't accept anything that happened before we did the last resync */
3565     if (base_rtptime > ext_rtptime) {
3566       GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
3567       valid = FALSE;
3568     } else {
3569       /* the SR RTP timestamp must be something close to what we last observed
3570        * in the jitterbuffer */
3571       if (ext_rtptime > last_rtptime) {
3572         /* check how far ahead it is to our RTP timestamps */
3573         diff = ext_rtptime - last_rtptime;
3574         /* if bigger than 1 second, we drop it */
3575         if (jitterbuffer->priv->max_rtcp_rtp_time_diff != -1 &&
3576             diff >
3577             gst_util_uint64_scale (jitterbuffer->priv->max_rtcp_rtp_time_diff,
3578                 clock_rate, 1000)) {
3579           GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
3580           /* should drop this, but some RTSP servers end up with bogus
3581            * way too ahead RTCP packet when repeated PAUSE/PLAY,
3582            * so still trigger rptbin sync but invalidate RTCP data
3583            * (sync might use other methods) */
3584           ext_rtptime = -1;
3585         }
3586         GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
3587             G_GUINT64_FORMAT, last_rtptime, diff);
3588       }
3589     }
3590   }
3591
3592   if (keep) {
3593     GST_DEBUG_OBJECT (jitterbuffer, "keeping RTCP packet for later");
3594   } else if (valid) {
3595     GstStructure *s;
3596
3597     s = gst_structure_new ("application/x-rtp-sync",
3598         "base-rtptime", G_TYPE_UINT64, base_rtptime,
3599         "base-time", G_TYPE_UINT64, base_time,
3600         "clock-rate", G_TYPE_UINT, clock_rate,
3601         "clock-base", G_TYPE_UINT64, clock_base,
3602         "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
3603         "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
3604
3605     GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
3606     gst_buffer_replace (&priv->last_sr, NULL);
3607     JBUF_UNLOCK (priv);
3608     g_signal_emit (jitterbuffer,
3609         gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
3610     JBUF_LOCK (priv);
3611     gst_structure_free (s);
3612   } else {
3613     GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
3614     gst_buffer_replace (&priv->last_sr, NULL);
3615   }
3616 }
3617
3618 static GstFlowReturn
3619 gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
3620     GstBuffer * buffer)
3621 {
3622   GstRtpJitterBuffer *jitterbuffer;
3623   GstRtpJitterBufferPrivate *priv;
3624   GstFlowReturn ret = GST_FLOW_OK;
3625   guint32 ssrc;
3626   GstRTCPPacket packet;
3627   guint64 ext_rtptime;
3628   guint32 rtptime;
3629   GstRTCPBuffer rtcp = { NULL, };
3630
3631   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3632
3633   if (G_UNLIKELY (!gst_rtcp_buffer_validate_reduced (buffer)))
3634     goto invalid_buffer;
3635
3636   priv = jitterbuffer->priv;
3637
3638   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
3639
3640   if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
3641     goto empty_buffer;
3642
3643   /* first packet must be SR or RR or else the validate would have failed */
3644   switch (gst_rtcp_packet_get_type (&packet)) {
3645     case GST_RTCP_TYPE_SR:
3646       gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
3647           NULL, NULL);
3648       break;
3649     default:
3650       goto ignore_buffer;
3651   }
3652   gst_rtcp_buffer_unmap (&rtcp);
3653
3654   GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
3655
3656   JBUF_LOCK (priv);
3657   /* convert the RTP timestamp to our extended timestamp, using the same offset
3658    * we used in the jitterbuffer */
3659   ext_rtptime = priv->jbuf->ext_rtptime;
3660   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
3661
3662   priv->ext_rtptime = ext_rtptime;
3663   gst_buffer_replace (&priv->last_sr, buffer);
3664
3665   do_handle_sync (jitterbuffer);
3666   JBUF_UNLOCK (priv);
3667
3668 done:
3669   gst_buffer_unref (buffer);
3670
3671   return ret;
3672
3673 invalid_buffer:
3674   {
3675     /* this is not fatal but should be filtered earlier */
3676     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3677         ("Received invalid RTCP payload, dropping"));
3678     ret = GST_FLOW_OK;
3679     goto done;
3680   }
3681 empty_buffer:
3682   {
3683     /* this is not fatal but should be filtered earlier */
3684     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3685         ("Received empty RTCP payload, dropping"));
3686     gst_rtcp_buffer_unmap (&rtcp);
3687     ret = GST_FLOW_OK;
3688     goto done;
3689   }
3690 ignore_buffer:
3691   {
3692     GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
3693     gst_rtcp_buffer_unmap (&rtcp);
3694     ret = GST_FLOW_OK;
3695     goto done;
3696   }
3697 }
3698
3699 static gboolean
3700 gst_rtp_jitter_buffer_sink_query (GstPad * pad, GstObject * parent,
3701     GstQuery * query)
3702 {
3703   gboolean res = FALSE;
3704   GstRtpJitterBuffer *jitterbuffer;
3705   GstRtpJitterBufferPrivate *priv;
3706
3707   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3708   priv = jitterbuffer->priv;
3709
3710   switch (GST_QUERY_TYPE (query)) {
3711     case GST_QUERY_CAPS:
3712     {
3713       GstCaps *filter, *caps;
3714
3715       gst_query_parse_caps (query, &filter);
3716       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3717       gst_query_set_caps_result (query, caps);
3718       gst_caps_unref (caps);
3719       res = TRUE;
3720       break;
3721     }
3722     default:
3723       if (GST_QUERY_IS_SERIALIZED (query)) {
3724         RTPJitterBufferItem *item;
3725         gboolean head;
3726
3727         JBUF_LOCK_CHECK (priv, out_flushing);
3728         if (rtp_jitter_buffer_get_mode (priv->jbuf) !=
3729             RTP_JITTER_BUFFER_MODE_BUFFER) {
3730           GST_DEBUG_OBJECT (jitterbuffer, "adding serialized query");
3731           item = alloc_item (query, ITEM_TYPE_QUERY, -1, -1, -1, 0, -1);
3732           rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3733           if (head)
3734             JBUF_SIGNAL_EVENT (priv);
3735           JBUF_WAIT_QUERY (priv, out_flushing);
3736           res = priv->last_query;
3737         } else {
3738           GST_DEBUG_OBJECT (jitterbuffer, "refusing query, we are buffering");
3739           res = FALSE;
3740         }
3741         JBUF_UNLOCK (priv);
3742       } else {
3743         res = gst_pad_query_default (pad, parent, query);
3744       }
3745       break;
3746   }
3747   return res;
3748   /* ERRORS */
3749 out_flushing:
3750   {
3751     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
3752     JBUF_UNLOCK (priv);
3753     return FALSE;
3754   }
3755
3756 }
3757
3758 static gboolean
3759 gst_rtp_jitter_buffer_src_query (GstPad * pad, GstObject * parent,
3760     GstQuery * query)
3761 {
3762   GstRtpJitterBuffer *jitterbuffer;
3763   GstRtpJitterBufferPrivate *priv;
3764   gboolean res = FALSE;
3765
3766   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3767   priv = jitterbuffer->priv;
3768
3769   switch (GST_QUERY_TYPE (query)) {
3770     case GST_QUERY_LATENCY:
3771     {
3772       /* We need to send the query upstream and add the returned latency to our
3773        * own */
3774       GstClockTime min_latency, max_latency;
3775       gboolean us_live;
3776       GstClockTime our_latency;
3777
3778       if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
3779         gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
3780
3781         GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
3782             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3783             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3784
3785         /* store this so that we can safely sync on the peer buffers. */
3786         JBUF_LOCK (priv);
3787         priv->peer_latency = min_latency;
3788         our_latency = priv->latency_ns;
3789         JBUF_UNLOCK (priv);
3790
3791         GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
3792             GST_TIME_ARGS (our_latency));
3793
3794         /* we add some latency but can buffer an infinite amount of time */
3795         min_latency += our_latency;
3796         max_latency = -1;
3797
3798         GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
3799             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3800             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3801
3802         gst_query_set_latency (query, TRUE, min_latency, max_latency);
3803       }
3804       break;
3805     }
3806     case GST_QUERY_POSITION:
3807     {
3808       GstClockTime start, last_out;
3809       GstFormat fmt;
3810
3811       gst_query_parse_position (query, &fmt, NULL);
3812       if (fmt != GST_FORMAT_TIME) {
3813         res = gst_pad_query_default (pad, parent, query);
3814         break;
3815       }
3816
3817       JBUF_LOCK (priv);
3818       start = priv->npt_start;
3819       last_out = priv->last_out_time;
3820       JBUF_UNLOCK (priv);
3821
3822       GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
3823           ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3824           GST_TIME_ARGS (last_out));
3825
3826       if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
3827         /* bring 0-based outgoing time to stream time */
3828         gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
3829         res = TRUE;
3830       } else {
3831         res = gst_pad_query_default (pad, parent, query);
3832       }
3833       break;
3834     }
3835     case GST_QUERY_CAPS:
3836     {
3837       GstCaps *filter, *caps;
3838
3839       gst_query_parse_caps (query, &filter);
3840       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3841       gst_query_set_caps_result (query, caps);
3842       gst_caps_unref (caps);
3843       res = TRUE;
3844       break;
3845     }
3846     default:
3847       res = gst_pad_query_default (pad, parent, query);
3848       break;
3849   }
3850
3851   return res;
3852 }
3853
3854 static void
3855 gst_rtp_jitter_buffer_set_property (GObject * object,
3856     guint prop_id, const GValue * value, GParamSpec * pspec)
3857 {
3858   GstRtpJitterBuffer *jitterbuffer;
3859   GstRtpJitterBufferPrivate *priv;
3860
3861   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3862   priv = jitterbuffer->priv;
3863
3864   switch (prop_id) {
3865     case PROP_LATENCY:
3866     {
3867       guint new_latency, old_latency;
3868
3869       new_latency = g_value_get_uint (value);
3870
3871       JBUF_LOCK (priv);
3872       old_latency = priv->latency_ms;
3873       priv->latency_ms = new_latency;
3874       priv->latency_ns = priv->latency_ms * GST_MSECOND;
3875       rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
3876       JBUF_UNLOCK (priv);
3877
3878       /* post message if latency changed, this will inform the parent pipeline
3879        * that a latency reconfiguration is possible/needed. */
3880       if (new_latency != old_latency) {
3881         GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
3882             GST_TIME_ARGS (new_latency * GST_MSECOND));
3883
3884         gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
3885             gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
3886       }
3887       break;
3888     }
3889     case PROP_DROP_ON_LATENCY:
3890       JBUF_LOCK (priv);
3891       priv->drop_on_latency = g_value_get_boolean (value);
3892       JBUF_UNLOCK (priv);
3893       break;
3894     case PROP_TS_OFFSET:
3895       JBUF_LOCK (priv);
3896       priv->ts_offset = g_value_get_int64 (value);
3897       priv->ts_discont = TRUE;
3898       JBUF_UNLOCK (priv);
3899       break;
3900     case PROP_DO_LOST:
3901       JBUF_LOCK (priv);
3902       priv->do_lost = g_value_get_boolean (value);
3903       JBUF_UNLOCK (priv);
3904       break;
3905     case PROP_MODE:
3906       JBUF_LOCK (priv);
3907       rtp_jitter_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
3908       JBUF_UNLOCK (priv);
3909       break;
3910     case PROP_DO_RETRANSMISSION:
3911       JBUF_LOCK (priv);
3912       priv->do_retransmission = g_value_get_boolean (value);
3913       JBUF_UNLOCK (priv);
3914       break;
3915     case PROP_RTX_NEXT_SEQNUM:
3916       JBUF_LOCK (priv);
3917       priv->rtx_next_seqnum = g_value_get_boolean (value);
3918       JBUF_UNLOCK (priv);
3919       break;
3920     case PROP_RTX_DELAY:
3921       JBUF_LOCK (priv);
3922       priv->rtx_delay = g_value_get_int (value);
3923       JBUF_UNLOCK (priv);
3924       break;
3925     case PROP_RTX_MIN_DELAY:
3926       JBUF_LOCK (priv);
3927       priv->rtx_min_delay = g_value_get_uint (value);
3928       JBUF_UNLOCK (priv);
3929       break;
3930     case PROP_RTX_DELAY_REORDER:
3931       JBUF_LOCK (priv);
3932       priv->rtx_delay_reorder = g_value_get_int (value);
3933       JBUF_UNLOCK (priv);
3934       break;
3935     case PROP_RTX_RETRY_TIMEOUT:
3936       JBUF_LOCK (priv);
3937       priv->rtx_retry_timeout = g_value_get_int (value);
3938       JBUF_UNLOCK (priv);
3939       break;
3940     case PROP_RTX_MIN_RETRY_TIMEOUT:
3941       JBUF_LOCK (priv);
3942       priv->rtx_min_retry_timeout = g_value_get_int (value);
3943       JBUF_UNLOCK (priv);
3944       break;
3945     case PROP_RTX_RETRY_PERIOD:
3946       JBUF_LOCK (priv);
3947       priv->rtx_retry_period = g_value_get_int (value);
3948       JBUF_UNLOCK (priv);
3949       break;
3950     case PROP_RTX_MAX_RETRIES:
3951       JBUF_LOCK (priv);
3952       priv->rtx_max_retries = g_value_get_int (value);
3953       JBUF_UNLOCK (priv);
3954       break;
3955     case PROP_MAX_RTCP_RTP_TIME_DIFF:
3956       JBUF_LOCK (priv);
3957       priv->max_rtcp_rtp_time_diff = g_value_get_int (value);
3958       JBUF_UNLOCK (priv);
3959       break;
3960     default:
3961       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3962       break;
3963   }
3964 }
3965
3966 static void
3967 gst_rtp_jitter_buffer_get_property (GObject * object,
3968     guint prop_id, GValue * value, GParamSpec * pspec)
3969 {
3970   GstRtpJitterBuffer *jitterbuffer;
3971   GstRtpJitterBufferPrivate *priv;
3972
3973   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3974   priv = jitterbuffer->priv;
3975
3976   switch (prop_id) {
3977     case PROP_LATENCY:
3978       JBUF_LOCK (priv);
3979       g_value_set_uint (value, priv->latency_ms);
3980       JBUF_UNLOCK (priv);
3981       break;
3982     case PROP_DROP_ON_LATENCY:
3983       JBUF_LOCK (priv);
3984       g_value_set_boolean (value, priv->drop_on_latency);
3985       JBUF_UNLOCK (priv);
3986       break;
3987     case PROP_TS_OFFSET:
3988       JBUF_LOCK (priv);
3989       g_value_set_int64 (value, priv->ts_offset);
3990       JBUF_UNLOCK (priv);
3991       break;
3992     case PROP_DO_LOST:
3993       JBUF_LOCK (priv);
3994       g_value_set_boolean (value, priv->do_lost);
3995       JBUF_UNLOCK (priv);
3996       break;
3997     case PROP_MODE:
3998       JBUF_LOCK (priv);
3999       g_value_set_enum (value, rtp_jitter_buffer_get_mode (priv->jbuf));
4000       JBUF_UNLOCK (priv);
4001       break;
4002     case PROP_PERCENT:
4003     {
4004       gint percent;
4005
4006       JBUF_LOCK (priv);
4007       if (priv->srcresult != GST_FLOW_OK)
4008         percent = 100;
4009       else
4010         percent = rtp_jitter_buffer_get_percent (priv->jbuf);
4011
4012       g_value_set_int (value, percent);
4013       JBUF_UNLOCK (priv);
4014       break;
4015     }
4016     case PROP_DO_RETRANSMISSION:
4017       JBUF_LOCK (priv);
4018       g_value_set_boolean (value, priv->do_retransmission);
4019       JBUF_UNLOCK (priv);
4020       break;
4021     case PROP_RTX_NEXT_SEQNUM:
4022       JBUF_LOCK (priv);
4023       g_value_set_boolean (value, priv->rtx_next_seqnum);
4024       JBUF_UNLOCK (priv);
4025       break;
4026     case PROP_RTX_DELAY:
4027       JBUF_LOCK (priv);
4028       g_value_set_int (value, priv->rtx_delay);
4029       JBUF_UNLOCK (priv);
4030       break;
4031     case PROP_RTX_MIN_DELAY:
4032       JBUF_LOCK (priv);
4033       g_value_set_uint (value, priv->rtx_min_delay);
4034       JBUF_UNLOCK (priv);
4035       break;
4036     case PROP_RTX_DELAY_REORDER:
4037       JBUF_LOCK (priv);
4038       g_value_set_int (value, priv->rtx_delay_reorder);
4039       JBUF_UNLOCK (priv);
4040       break;
4041     case PROP_RTX_RETRY_TIMEOUT:
4042       JBUF_LOCK (priv);
4043       g_value_set_int (value, priv->rtx_retry_timeout);
4044       JBUF_UNLOCK (priv);
4045       break;
4046     case PROP_RTX_MIN_RETRY_TIMEOUT:
4047       JBUF_LOCK (priv);
4048       g_value_set_int (value, priv->rtx_min_retry_timeout);
4049       JBUF_UNLOCK (priv);
4050       break;
4051     case PROP_RTX_RETRY_PERIOD:
4052       JBUF_LOCK (priv);
4053       g_value_set_int (value, priv->rtx_retry_period);
4054       JBUF_UNLOCK (priv);
4055       break;
4056     case PROP_RTX_MAX_RETRIES:
4057       JBUF_LOCK (priv);
4058       g_value_set_int (value, priv->rtx_max_retries);
4059       JBUF_UNLOCK (priv);
4060       break;
4061     case PROP_STATS:
4062       g_value_take_boxed (value,
4063           gst_rtp_jitter_buffer_create_stats (jitterbuffer));
4064       break;
4065     case PROP_MAX_RTCP_RTP_TIME_DIFF:
4066       JBUF_LOCK (priv);
4067       g_value_set_int (value, priv->max_rtcp_rtp_time_diff);
4068       JBUF_UNLOCK (priv);
4069       break;
4070     default:
4071       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4072       break;
4073   }
4074 }
4075
4076 static GstStructure *
4077 gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer * jbuf)
4078 {
4079   GstStructure *s;
4080
4081   JBUF_LOCK (jbuf->priv);
4082   s = gst_structure_new ("application/x-rtp-jitterbuffer-stats",
4083       "rtx-count", G_TYPE_UINT64, jbuf->priv->num_rtx_requests,
4084       "rtx-success-count", G_TYPE_UINT64, jbuf->priv->num_rtx_success,
4085       "rtx-per-packet", G_TYPE_DOUBLE, jbuf->priv->avg_rtx_num,
4086       "rtx-rtt", G_TYPE_UINT64, jbuf->priv->avg_rtx_rtt, NULL);
4087   JBUF_UNLOCK (jbuf->priv);
4088
4089   return s;
4090 }