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