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