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