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