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