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