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