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