rtpmanager: switch G_GINT64_FORMAT for GST_STIME_ARGS
[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     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1734     return GST_FLOW_FLUSHING;
1735   }
1736 parse_failed:
1737   {
1738     GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
1739     return GST_FLOW_ERROR;
1740   }
1741 }
1742
1743 /* call with jbuf lock held */
1744 static GstMessage *
1745 check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
1746 {
1747   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1748   GstMessage *message = NULL;
1749
1750   if (percent == -1)
1751     return NULL;
1752
1753   /* Post a buffering message */
1754   if (priv->last_percent != percent) {
1755     priv->last_percent = percent;
1756     message =
1757         gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
1758     gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
1759   }
1760
1761   return message;
1762 }
1763
1764 static GstClockTime
1765 apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1766 {
1767   GstRtpJitterBufferPrivate *priv;
1768
1769   priv = jitterbuffer->priv;
1770
1771   if (timestamp == -1)
1772     return -1;
1773
1774   /* apply the timestamp offset, this is used for inter stream sync */
1775   timestamp += priv->ts_offset;
1776   /* add the offset, this is used when buffering */
1777   timestamp += priv->out_offset;
1778
1779   return timestamp;
1780 }
1781
1782 static TimerData *
1783 find_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type, guint16 seqnum)
1784 {
1785   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1786   TimerData *timer = NULL;
1787   gint i, len;
1788
1789   len = priv->timers->len;
1790   for (i = 0; i < len; i++) {
1791     TimerData *test = &g_array_index (priv->timers, TimerData, i);
1792     if (test->seqnum == seqnum && test->type == type) {
1793       timer = test;
1794       break;
1795     }
1796   }
1797   return timer;
1798 }
1799
1800 static void
1801 unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer)
1802 {
1803   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1804
1805   if (priv->clock_id) {
1806     GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
1807     gst_clock_id_unschedule (priv->clock_id);
1808     priv->clock_id = NULL;
1809   }
1810 }
1811
1812 static GstClockTime
1813 get_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1814 {
1815   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1816   GstClockTime test_timeout;
1817
1818   if ((test_timeout = timer->timeout) == -1)
1819     return -1;
1820
1821   if (timer->type != TIMER_TYPE_EXPECTED) {
1822     /* add our latency and offset to get output times. */
1823     test_timeout = apply_offset (jitterbuffer, test_timeout);
1824     test_timeout += priv->latency_ns;
1825   }
1826   return test_timeout;
1827 }
1828
1829 static void
1830 recalculate_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1831 {
1832   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1833
1834   if (priv->clock_id) {
1835     GstClockTime timeout = get_timeout (jitterbuffer, timer);
1836
1837     GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
1838         GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
1839
1840     if (timeout == -1 || timeout < priv->timer_timeout)
1841       unschedule_current_timer (jitterbuffer);
1842   }
1843 }
1844
1845 static TimerData *
1846 add_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1847     guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
1848     GstClockTime duration)
1849 {
1850   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1851   TimerData *timer;
1852   gint len;
1853
1854   GST_DEBUG_OBJECT (jitterbuffer,
1855       "add timer %d for seqnum %d to %" GST_TIME_FORMAT ", delay %"
1856       GST_TIME_FORMAT, type, seqnum, GST_TIME_ARGS (timeout),
1857       GST_TIME_ARGS (delay));
1858
1859   len = priv->timers->len;
1860   g_array_set_size (priv->timers, len + 1);
1861   timer = &g_array_index (priv->timers, TimerData, len);
1862   timer->idx = len;
1863   timer->type = type;
1864   timer->seqnum = seqnum;
1865   timer->num = num;
1866   timer->timeout = timeout + delay;
1867   timer->duration = duration;
1868   if (type == TIMER_TYPE_EXPECTED) {
1869     timer->rtx_base = timeout;
1870     timer->rtx_delay = delay;
1871     timer->rtx_retry = 0;
1872   }
1873   timer->num_rtx_retry = 0;
1874   recalculate_timer (jitterbuffer, timer);
1875   JBUF_SIGNAL_TIMER (priv);
1876
1877   return timer;
1878 }
1879
1880 static void
1881 reschedule_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
1882     guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
1883 {
1884   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1885   gboolean seqchange, timechange;
1886   guint16 oldseq;
1887
1888   seqchange = timer->seqnum != seqnum;
1889   timechange = timer->timeout != timeout;
1890
1891   if (!seqchange && !timechange)
1892     return;
1893
1894   oldseq = timer->seqnum;
1895
1896   GST_DEBUG_OBJECT (jitterbuffer,
1897       "replace timer for seqnum %d->%d to %" GST_TIME_FORMAT,
1898       oldseq, seqnum, GST_TIME_ARGS (timeout + delay));
1899
1900   timer->timeout = timeout + delay;
1901   timer->seqnum = seqnum;
1902   if (reset) {
1903     timer->rtx_base = timeout;
1904     timer->rtx_delay = delay;
1905     timer->rtx_retry = 0;
1906   }
1907   if (seqchange)
1908     timer->num_rtx_retry = 0;
1909
1910   if (priv->clock_id) {
1911     /* we changed the seqnum and there is a timer currently waiting with this
1912      * seqnum, unschedule it */
1913     if (seqchange && priv->timer_seqnum == oldseq)
1914       unschedule_current_timer (jitterbuffer);
1915     /* we changed the time, check if it is earlier than what we are waiting
1916      * for and unschedule if so */
1917     else if (timechange)
1918       recalculate_timer (jitterbuffer, timer);
1919   }
1920 }
1921
1922 static TimerData *
1923 set_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1924     guint16 seqnum, GstClockTime timeout)
1925 {
1926   TimerData *timer;
1927
1928   /* find the seqnum timer */
1929   timer = find_timer (jitterbuffer, type, seqnum);
1930   if (timer == NULL) {
1931     timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
1932   } else {
1933     reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
1934   }
1935   return timer;
1936 }
1937
1938 static void
1939 remove_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1940 {
1941   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1942   guint idx;
1943
1944   if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
1945     unschedule_current_timer (jitterbuffer);
1946
1947   idx = timer->idx;
1948   GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
1949   g_array_remove_index_fast (priv->timers, idx);
1950   timer->idx = idx;
1951 }
1952
1953 static void
1954 remove_all_timers (GstRtpJitterBuffer * jitterbuffer)
1955 {
1956   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1957   GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
1958   g_array_set_size (priv->timers, 0);
1959   unschedule_current_timer (jitterbuffer);
1960 }
1961
1962 /* get the extra delay to wait before sending RTX */
1963 static GstClockTime
1964 get_rtx_delay (GstRtpJitterBufferPrivate * priv)
1965 {
1966   GstClockTime delay;
1967
1968   if (priv->rtx_delay == -1) {
1969     if (priv->avg_jitter == 0 && priv->packet_spacing == 0) {
1970       delay = DEFAULT_AUTO_RTX_DELAY;
1971     } else {
1972       /* jitter is in nanoseconds, maximum of 2x jitter and half the
1973        * packet spacing is a good margin */
1974       delay = MAX (priv->avg_jitter * 2, priv->packet_spacing / 2);
1975     }
1976   } else {
1977     delay = priv->rtx_delay * GST_MSECOND;
1978   }
1979   if (priv->rtx_min_delay > 0)
1980     delay = MAX (delay, priv->rtx_min_delay * GST_MSECOND);
1981
1982   return delay;
1983 }
1984
1985 /* we just received a packet with seqnum and dts.
1986  *
1987  * First check for old seqnum that we are still expecting. If the gap with the
1988  * current seqnum is too big, unschedule the timeouts.
1989  *
1990  * If we have a valid packet spacing estimate we can set a timer for when we
1991  * should receive the next packet.
1992  * If we don't have a valid estimate, we remove any timer we might have
1993  * had for this packet.
1994  */
1995 static void
1996 update_timers (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum,
1997     GstClockTime dts, gboolean do_next_seqnum)
1998 {
1999   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2000   TimerData *timer = NULL;
2001   gint i, len;
2002
2003   /* go through all timers and unschedule the ones with a large gap, also find
2004    * the timer for the seqnum */
2005   len = priv->timers->len;
2006   for (i = 0; i < len; i++) {
2007     TimerData *test = &g_array_index (priv->timers, TimerData, i);
2008     gint gap;
2009
2010     gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
2011
2012     GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, #%d<->#%d gap %d", i,
2013         test->type, test->seqnum, seqnum, gap);
2014
2015     if (gap == 0) {
2016       GST_DEBUG ("found timer for current seqnum");
2017       /* the timer for the current seqnum */
2018       timer = test;
2019       /* when no retransmission, we can stop now, we only need to find the
2020        * timer for the current seqnum */
2021       if (!priv->do_retransmission)
2022         break;
2023     } else if (gap > priv->rtx_delay_reorder) {
2024       /* max gap, we exceeded the max reorder distance and we don't expect the
2025        * missing packet to be this reordered */
2026       if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
2027         reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
2028     }
2029   }
2030
2031   do_next_seqnum = do_next_seqnum && priv->packet_spacing > 0
2032       && priv->do_retransmission && priv->rtx_next_seqnum;
2033
2034   if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2035     if (timer->num_rtx_retry > 0) {
2036       GstClockTime rtx_last, delay;
2037
2038       /* we scheduled a retry for this packet and now we have it */
2039       priv->num_rtx_success++;
2040       /* all the previous retry attempts failed */
2041       priv->num_rtx_failed += timer->num_rtx_retry - 1;
2042       /* number of retries before receiving the packet */
2043       if (priv->avg_rtx_num == 0.0)
2044         priv->avg_rtx_num = timer->num_rtx_retry;
2045       else
2046         priv->avg_rtx_num = (timer->num_rtx_retry + 7 * priv->avg_rtx_num) / 8;
2047       /* calculate the delay between retransmission request and receiving this
2048        * packet, start with when we scheduled this timeout last */
2049       rtx_last = timer->rtx_last;
2050       if (dts != GST_CLOCK_TIME_NONE && dts > rtx_last) {
2051         /* we have a valid delay if this packet arrived after we scheduled the
2052          * request */
2053         delay = dts - rtx_last;
2054         if (priv->avg_rtx_rtt == 0)
2055           priv->avg_rtx_rtt = delay;
2056         else
2057           priv->avg_rtx_rtt = (delay + 7 * priv->avg_rtx_rtt) / 8;
2058       } else
2059         delay = 0;
2060
2061       GST_LOG_OBJECT (jitterbuffer,
2062           "RTX success %" G_GUINT64_FORMAT ", failed %" G_GUINT64_FORMAT
2063           ", requests %" G_GUINT64_FORMAT ", dups %" G_GUINT64_FORMAT
2064           ", avg-num %g, delay %" GST_TIME_FORMAT ", avg-rtt %" GST_TIME_FORMAT,
2065           priv->num_rtx_success, priv->num_rtx_failed, priv->num_rtx_requests,
2066           priv->num_duplicates, priv->avg_rtx_num, GST_TIME_ARGS (delay),
2067           GST_TIME_ARGS (priv->avg_rtx_rtt));
2068
2069       /* don't try to estimate the next seqnum because this is a retransmitted
2070        * packet and it probably did not arrive with the expected packet
2071        * spacing. */
2072       do_next_seqnum = FALSE;
2073     }
2074   }
2075
2076   if (do_next_seqnum && dts != GST_CLOCK_TIME_NONE) {
2077     GstClockTime expected, delay;
2078
2079     /* calculate expected arrival time of the next seqnum */
2080     expected = dts + priv->packet_spacing;
2081
2082     delay = get_rtx_delay (priv);
2083
2084     /* and update/install timer for next seqnum */
2085     if (timer) {
2086       reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
2087           delay, TRUE);
2088     } else {
2089       add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
2090           expected, delay, priv->packet_spacing);
2091     }
2092   } else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
2093     /* if we had a timer, remove it, we don't know when to expect the next
2094      * packet. */
2095     remove_timer (jitterbuffer, timer);
2096   }
2097 }
2098
2099 static void
2100 calculate_packet_spacing (GstRtpJitterBuffer * jitterbuffer, guint32 rtptime,
2101     GstClockTime dts)
2102 {
2103   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2104
2105   /* we need consecutive seqnums with a different
2106    * rtptime to estimate the packet spacing. */
2107   if (priv->ips_rtptime != rtptime) {
2108     /* rtptime changed, check dts diff */
2109     if (priv->ips_dts != -1 && dts != -1 && dts > priv->ips_dts) {
2110       GstClockTime new_packet_spacing = dts - priv->ips_dts;
2111       GstClockTime old_packet_spacing = priv->packet_spacing;
2112
2113       /* Biased towards bigger packet spacings to prevent
2114        * too many unneeded retransmission requests for next
2115        * packets that just arrive a little later than we would
2116        * expect */
2117       if (old_packet_spacing > new_packet_spacing)
2118         priv->packet_spacing =
2119             (new_packet_spacing + 3 * old_packet_spacing) / 4;
2120       else if (old_packet_spacing > 0)
2121         priv->packet_spacing =
2122             (3 * new_packet_spacing + old_packet_spacing) / 4;
2123       else
2124         priv->packet_spacing = new_packet_spacing;
2125
2126       GST_DEBUG_OBJECT (jitterbuffer,
2127           "new packet spacing %" GST_TIME_FORMAT
2128           " old packet spacing %" GST_TIME_FORMAT
2129           " combined to %" GST_TIME_FORMAT,
2130           GST_TIME_ARGS (new_packet_spacing),
2131           GST_TIME_ARGS (old_packet_spacing),
2132           GST_TIME_ARGS (priv->packet_spacing));
2133     }
2134     priv->ips_rtptime = rtptime;
2135     priv->ips_dts = dts;
2136   }
2137 }
2138
2139 static void
2140 calculate_expected (GstRtpJitterBuffer * jitterbuffer, guint32 expected,
2141     guint16 seqnum, GstClockTime dts, gint gap)
2142 {
2143   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2144   GstClockTime total_duration, duration, expected_dts;
2145   TimerType type;
2146
2147   GST_DEBUG_OBJECT (jitterbuffer,
2148       "dts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
2149       GST_TIME_ARGS (dts), GST_TIME_ARGS (priv->last_in_dts));
2150
2151   if (dts == GST_CLOCK_TIME_NONE) {
2152     GST_WARNING_OBJECT (jitterbuffer, "Have no DTS");
2153     return;
2154   }
2155
2156   /* the total duration spanned by the missing packets */
2157   if (dts >= priv->last_in_dts)
2158     total_duration = dts - priv->last_in_dts;
2159   else
2160     total_duration = 0;
2161
2162   /* interpolate between the current time and the last time based on
2163    * number of packets we are missing, this is the estimated duration
2164    * for the missing packet based on equidistant packet spacing. */
2165   duration = total_duration / (gap + 1);
2166
2167   GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
2168       GST_TIME_ARGS (duration));
2169
2170   if (total_duration > priv->latency_ns) {
2171     GstClockTime gap_time;
2172     guint lost_packets;
2173
2174     if (duration > 0) {
2175       GstClockTime gap_dur = gap * duration;
2176       if (gap_dur > priv->latency_ns)
2177         gap_time = gap_dur - priv->latency_ns;
2178       else
2179         gap_time = 0;
2180       lost_packets = gap_time / duration;
2181     } else {
2182       gap_time = total_duration - priv->latency_ns;
2183       lost_packets = gap;
2184     }
2185
2186     /* too many lost packets, some of the missing packets are already
2187      * too late and we can generate lost packet events for them. */
2188     GST_DEBUG_OBJECT (jitterbuffer,
2189         "lost packets (%d, #%d->#%d) duration too large %" GST_TIME_FORMAT
2190         " > %" GST_TIME_FORMAT ", consider %u lost (%" GST_TIME_FORMAT ")",
2191         gap, expected, seqnum, GST_TIME_ARGS (total_duration),
2192         GST_TIME_ARGS (priv->latency_ns), lost_packets,
2193         GST_TIME_ARGS (gap_time));
2194
2195     /* this timer will fire immediately and the lost event will be pushed from
2196      * the timer thread */
2197     if (lost_packets > 0) {
2198       add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
2199           priv->last_in_dts + duration, 0, gap_time);
2200       expected += lost_packets;
2201       priv->last_in_dts += gap_time;
2202     }
2203   }
2204
2205   expected_dts = priv->last_in_dts + duration;
2206
2207   if (priv->do_retransmission) {
2208     TimerData *timer;
2209
2210     type = TIMER_TYPE_EXPECTED;
2211     /* if we had a timer for the first missing packet, update it. */
2212     if ((timer = find_timer (jitterbuffer, type, expected))) {
2213       GstClockTime timeout = timer->timeout;
2214
2215       timer->duration = duration;
2216       if (timeout > (expected_dts + timer->rtx_retry)) {
2217         GstClockTime delay = timeout - expected_dts - timer->rtx_retry;
2218         reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_dts,
2219             delay, TRUE);
2220       }
2221       expected++;
2222       expected_dts += duration;
2223     }
2224   } else {
2225     type = TIMER_TYPE_LOST;
2226   }
2227
2228   while (gst_rtp_buffer_compare_seqnum (expected, seqnum) > 0) {
2229     add_timer (jitterbuffer, type, expected, 0, expected_dts, 0, duration);
2230     expected_dts += duration;
2231     expected++;
2232   }
2233 }
2234
2235 static void
2236 calculate_jitter (GstRtpJitterBuffer * jitterbuffer, GstClockTime dts,
2237     guint rtptime)
2238 {
2239   gint32 rtpdiff;
2240   GstClockTimeDiff dtsdiff, rtpdiffns, diff;
2241   GstRtpJitterBufferPrivate *priv;
2242
2243   priv = jitterbuffer->priv;
2244
2245   if (G_UNLIKELY (dts == GST_CLOCK_TIME_NONE) || priv->clock_rate <= 0)
2246     goto no_time;
2247
2248   if (priv->last_dts != -1)
2249     dtsdiff = dts - priv->last_dts;
2250   else
2251     dtsdiff = 0;
2252
2253   if (priv->last_rtptime != -1)
2254     rtpdiff = rtptime - (guint32) priv->last_rtptime;
2255   else
2256     rtpdiff = 0;
2257
2258   priv->last_dts = dts;
2259   priv->last_rtptime = rtptime;
2260
2261   if (rtpdiff > 0)
2262     rtpdiffns =
2263         gst_util_uint64_scale_int (rtpdiff, GST_SECOND, priv->clock_rate);
2264   else
2265     rtpdiffns =
2266         -gst_util_uint64_scale_int (-rtpdiff, GST_SECOND, priv->clock_rate);
2267
2268   diff = ABS (dtsdiff - rtpdiffns);
2269
2270   /* jitter is stored in nanoseconds */
2271   priv->avg_jitter = (diff + (15 * priv->avg_jitter)) >> 4;
2272
2273   GST_LOG_OBJECT (jitterbuffer,
2274       "dtsdiff %" GST_TIME_FORMAT " rtptime %" GST_TIME_FORMAT
2275       ", clock-rate %d, diff %" GST_TIME_FORMAT ", jitter: %" GST_TIME_FORMAT,
2276       GST_TIME_ARGS (dtsdiff), GST_TIME_ARGS (rtpdiffns), priv->clock_rate,
2277       GST_TIME_ARGS (diff), GST_TIME_ARGS (priv->avg_jitter));
2278
2279   return;
2280
2281   /* ERRORS */
2282 no_time:
2283   {
2284     GST_DEBUG_OBJECT (jitterbuffer,
2285         "no dts or no clock-rate, can't calculate jitter");
2286     return;
2287   }
2288 }
2289
2290 static gint
2291 compare_buffer_seqnum (GstBuffer * a, GstBuffer * b, gpointer user_data)
2292 {
2293   GstRTPBuffer rtp_a = GST_RTP_BUFFER_INIT;
2294   GstRTPBuffer rtp_b = GST_RTP_BUFFER_INIT;
2295   guint seq_a, seq_b;
2296
2297   gst_rtp_buffer_map (a, GST_MAP_READ, &rtp_a);
2298   seq_a = gst_rtp_buffer_get_seq (&rtp_a);
2299   gst_rtp_buffer_unmap (&rtp_a);
2300
2301   gst_rtp_buffer_map (b, GST_MAP_READ, &rtp_b);
2302   seq_b = gst_rtp_buffer_get_seq (&rtp_b);
2303   gst_rtp_buffer_unmap (&rtp_b);
2304
2305   return gst_rtp_buffer_compare_seqnum (seq_b, seq_a);
2306 }
2307
2308 static gboolean
2309 handle_big_gap_buffer (GstRtpJitterBuffer * jitterbuffer, gboolean future,
2310     GstBuffer * buffer, guint8 pt, guint16 seqnum, gint gap, guint max_dropout,
2311     guint max_misorder)
2312 {
2313   GstRtpJitterBufferPrivate *priv;
2314   guint gap_packets_length;
2315   gboolean reset = FALSE;
2316
2317   priv = jitterbuffer->priv;
2318
2319   if ((gap_packets_length = g_queue_get_length (&priv->gap_packets)) > 0) {
2320     GList *l;
2321     guint32 prev_gap_seq = -1;
2322     gboolean all_consecutive = TRUE;
2323
2324     g_queue_insert_sorted (&priv->gap_packets, buffer,
2325         (GCompareDataFunc) compare_buffer_seqnum, NULL);
2326
2327     for (l = priv->gap_packets.head; l; l = l->next) {
2328       GstBuffer *gap_buffer = l->data;
2329       GstRTPBuffer gap_rtp = GST_RTP_BUFFER_INIT;
2330       guint32 gap_seq;
2331
2332       gst_rtp_buffer_map (gap_buffer, GST_MAP_READ, &gap_rtp);
2333
2334       all_consecutive = (gst_rtp_buffer_get_payload_type (&gap_rtp) == pt);
2335
2336       gap_seq = gst_rtp_buffer_get_seq (&gap_rtp);
2337       if (prev_gap_seq == -1)
2338         prev_gap_seq = gap_seq;
2339       else if (gst_rtp_buffer_compare_seqnum (gap_seq, prev_gap_seq) != -1)
2340         all_consecutive = FALSE;
2341       else
2342         prev_gap_seq = gap_seq;
2343
2344       gst_rtp_buffer_unmap (&gap_rtp);
2345       if (!all_consecutive)
2346         break;
2347     }
2348
2349     if (all_consecutive && gap_packets_length > 3) {
2350       GST_DEBUG_OBJECT (jitterbuffer,
2351           "buffer too %s %d < %d, got 5 consecutive ones - reset",
2352           (future ? "new" : "old"), gap,
2353           (future ? max_dropout : -max_misorder));
2354       reset = TRUE;
2355     } else if (!all_consecutive) {
2356       g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2357       g_queue_clear (&priv->gap_packets);
2358       GST_DEBUG_OBJECT (jitterbuffer,
2359           "buffer too %s %d < %d, got no 5 consecutive ones - dropping",
2360           (future ? "new" : "old"), gap,
2361           (future ? max_dropout : -max_misorder));
2362       buffer = NULL;
2363     } else {
2364       GST_DEBUG_OBJECT (jitterbuffer,
2365           "buffer too %s %d < %d, got %u consecutive ones - waiting",
2366           (future ? "new" : "old"), gap,
2367           (future ? max_dropout : -max_misorder), gap_packets_length + 1);
2368       buffer = NULL;
2369     }
2370   } else {
2371     GST_DEBUG_OBJECT (jitterbuffer,
2372         "buffer too %s %d < %d, first one - waiting", (future ? "new" : "old"),
2373         gap, -max_misorder);
2374     g_queue_push_tail (&priv->gap_packets, buffer);
2375     buffer = NULL;
2376   }
2377
2378   return reset;
2379 }
2380
2381 static GstClockTime
2382 get_current_running_time (GstRtpJitterBuffer * jitterbuffer)
2383 {
2384   GstClock *clock = gst_element_get_clock (GST_ELEMENT_CAST (jitterbuffer));
2385   GstClockTime running_time = GST_CLOCK_TIME_NONE;
2386
2387   if (clock) {
2388     GstClockTime base_time =
2389         gst_element_get_base_time (GST_ELEMENT_CAST (jitterbuffer));
2390     GstClockTime clock_time = gst_clock_get_time (clock);
2391
2392     if (clock_time > base_time)
2393       running_time = clock_time - base_time;
2394     else
2395       running_time = 0;
2396
2397     gst_object_unref (clock);
2398   }
2399
2400   return running_time;
2401 }
2402
2403 static GstFlowReturn
2404 gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
2405     GstBuffer * buffer)
2406 {
2407   GstRtpJitterBuffer *jitterbuffer;
2408   GstRtpJitterBufferPrivate *priv;
2409   guint16 seqnum;
2410   guint32 expected, rtptime;
2411   GstFlowReturn ret = GST_FLOW_OK;
2412   GstClockTime dts, pts;
2413   guint64 latency_ts;
2414   gboolean head;
2415   gint percent = -1;
2416   guint8 pt;
2417   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
2418   gboolean do_next_seqnum = FALSE;
2419   RTPJitterBufferItem *item;
2420   GstMessage *msg = NULL;
2421   gboolean estimated_dts = FALSE;
2422   guint32 packet_rate, max_dropout, max_misorder;
2423
2424   jitterbuffer = GST_RTP_JITTER_BUFFER_CAST (parent);
2425
2426   priv = jitterbuffer->priv;
2427
2428   if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
2429     goto invalid_buffer;
2430
2431   pt = gst_rtp_buffer_get_payload_type (&rtp);
2432   seqnum = gst_rtp_buffer_get_seq (&rtp);
2433   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
2434   gst_rtp_buffer_unmap (&rtp);
2435
2436   /* make sure we have PTS and DTS set */
2437   pts = GST_BUFFER_PTS (buffer);
2438   dts = GST_BUFFER_DTS (buffer);
2439   if (dts == -1)
2440     dts = pts;
2441   else if (pts == -1)
2442     pts = dts;
2443
2444   if (dts == -1) {
2445     /* If we have no DTS here, i.e. no capture time, get one from the
2446      * clock now to have something to calculate with in the future. */
2447     dts = get_current_running_time (jitterbuffer);
2448     pts = dts;
2449
2450     /* Remember that we estimated the DTS if we are running already
2451      * and this is not our first packet (or first packet after a reset).
2452      * If it's the first packet, we somehow must generate a timestamp for
2453      * everything, otherwise we can't calculate any times
2454      */
2455     estimated_dts = (priv->next_in_seqnum != -1);
2456   } else {
2457     /* take the DTS of the buffer. This is the time when the packet was
2458      * received and is used to calculate jitter and clock skew. We will adjust
2459      * this DTS with the smoothed value after processing it in the
2460      * jitterbuffer and assign it as the PTS. */
2461     /* bring to running time */
2462     dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
2463   }
2464
2465   GST_DEBUG_OBJECT (jitterbuffer,
2466       "Received packet #%d at time %" GST_TIME_FORMAT ", discont %d", seqnum,
2467       GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer));
2468
2469   JBUF_LOCK_CHECK (priv, out_flushing);
2470
2471   if (G_UNLIKELY (priv->last_pt != pt)) {
2472     GstCaps *caps;
2473
2474     GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
2475         pt);
2476
2477     priv->last_pt = pt;
2478     /* reset clock-rate so that we get a new one */
2479     priv->clock_rate = -1;
2480
2481     /* Try to get the clock-rate from the caps first if we can. If there are no
2482      * caps we must fire the signal to get the clock-rate. */
2483     if ((caps = gst_pad_get_current_caps (pad))) {
2484       gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
2485       gst_caps_unref (caps);
2486     }
2487   }
2488
2489   if (G_UNLIKELY (priv->clock_rate == -1)) {
2490     /* no clock rate given on the caps, try to get one with the signal */
2491     if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
2492             pt) == GST_FLOW_FLUSHING)
2493       goto out_flushing;
2494
2495     if (G_UNLIKELY (priv->clock_rate == -1))
2496       goto no_clock_rate;
2497   }
2498
2499   /* don't accept more data on EOS */
2500   if (G_UNLIKELY (priv->eos))
2501     goto have_eos;
2502
2503   calculate_jitter (jitterbuffer, dts, rtptime);
2504
2505   if (priv->seqnum_base != -1) {
2506     gint gap;
2507
2508     gap = gst_rtp_buffer_compare_seqnum (priv->seqnum_base, seqnum);
2509
2510     if (gap < 0) {
2511       GST_DEBUG_OBJECT (jitterbuffer,
2512           "packet seqnum #%d before seqnum-base #%d", seqnum,
2513           priv->seqnum_base);
2514       gst_buffer_unref (buffer);
2515       ret = GST_FLOW_OK;
2516       goto finished;
2517     } else if (gap > 16384) {
2518       /* From now on don't compare against the seqnum base anymore as
2519        * at some point in the future we will wrap around and also that
2520        * much reordering is very unlikely */
2521       priv->seqnum_base = -1;
2522     }
2523   }
2524
2525   expected = priv->next_in_seqnum;
2526
2527   packet_rate =
2528       gst_rtp_packet_rate_ctx_update (&priv->packet_rate_ctx, seqnum, rtptime);
2529   max_dropout =
2530       gst_rtp_packet_rate_ctx_get_max_dropout (&priv->packet_rate_ctx,
2531       priv->max_dropout_time);
2532   max_misorder =
2533       gst_rtp_packet_rate_ctx_get_max_misorder (&priv->packet_rate_ctx,
2534       priv->max_misorder_time);
2535   GST_TRACE_OBJECT (jitterbuffer,
2536       "packet_rate: %d, max_dropout: %d, max_misorder: %d", packet_rate,
2537       max_dropout, max_misorder);
2538
2539   /* now check against our expected seqnum */
2540   if (G_LIKELY (expected != -1)) {
2541     gint gap;
2542
2543     /* now calculate gap */
2544     gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
2545
2546     GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
2547         expected, seqnum, gap);
2548
2549     if (G_LIKELY (gap == 0)) {
2550       /* packet is expected */
2551       calculate_packet_spacing (jitterbuffer, rtptime, dts);
2552       do_next_seqnum = TRUE;
2553     } else {
2554       gboolean reset = FALSE;
2555
2556       if (gap < 0) {
2557         /* we received an old packet */
2558         if (G_UNLIKELY (gap != -1 && gap < -max_misorder)) {
2559           reset =
2560               handle_big_gap_buffer (jitterbuffer, FALSE, buffer, pt, seqnum,
2561               gap, max_dropout, max_misorder);
2562           buffer = NULL;
2563         } else {
2564           GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
2565         }
2566       } else {
2567         /* new packet, we are missing some packets */
2568         if (G_UNLIKELY (priv->timers->len >= max_dropout)) {
2569           /* If we have timers for more than RTP_MAX_DROPOUT packets
2570            * pending this means that we have a huge gap overall. We can
2571            * reset the jitterbuffer at this point because there's
2572            * just too much data missing to be able to do anything
2573            * sensible with the past data. Just try again from the
2574            * next packet */
2575           GST_WARNING_OBJECT (jitterbuffer,
2576               "%d pending timers > %d - resetting", priv->timers->len,
2577               max_dropout);
2578           reset = TRUE;
2579           gst_buffer_unref (buffer);
2580           buffer = NULL;
2581         } else if (G_UNLIKELY (gap >= max_dropout)) {
2582           reset =
2583               handle_big_gap_buffer (jitterbuffer, TRUE, buffer, pt, seqnum,
2584               gap, max_dropout, max_misorder);
2585           buffer = NULL;
2586         } else {
2587           GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
2588           /* fill in the gap with EXPECTED timers */
2589           calculate_expected (jitterbuffer, expected, seqnum, dts, gap);
2590
2591           do_next_seqnum = TRUE;
2592         }
2593       }
2594       if (G_UNLIKELY (reset)) {
2595         GList *events = NULL, *l;
2596         GList *buffers;
2597
2598         GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
2599         rtp_jitter_buffer_flush (priv->jbuf,
2600             (GFunc) free_item_and_retain_events, &events);
2601         rtp_jitter_buffer_reset_skew (priv->jbuf);
2602         remove_all_timers (jitterbuffer);
2603         priv->discont = TRUE;
2604         priv->last_popped_seqnum = -1;
2605         priv->next_seqnum = seqnum;
2606
2607         priv->last_in_dts = -1;
2608         priv->next_in_seqnum = -1;
2609
2610         /* Insert all sticky events again in order, otherwise we would
2611          * potentially loose STREAM_START, CAPS or SEGMENT events
2612          */
2613         events = g_list_reverse (events);
2614         for (l = events; l; l = l->next) {
2615           RTPJitterBufferItem *item;
2616
2617           item = alloc_item (l->data, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
2618           rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
2619         }
2620         g_list_free (events);
2621
2622         JBUF_SIGNAL_EVENT (priv);
2623
2624         /* reset spacing estimation when gap */
2625         priv->ips_rtptime = -1;
2626         priv->ips_dts = GST_CLOCK_TIME_NONE;
2627
2628         buffers = g_list_copy (priv->gap_packets.head);
2629         g_queue_clear (&priv->gap_packets);
2630
2631         priv->ips_rtptime = -1;
2632         priv->ips_dts = GST_CLOCK_TIME_NONE;
2633         JBUF_UNLOCK (jitterbuffer->priv);
2634
2635         for (l = buffers; l; l = l->next) {
2636           ret = gst_rtp_jitter_buffer_chain (pad, parent, l->data);
2637           l->data = NULL;
2638           if (ret != GST_FLOW_OK)
2639             break;
2640         }
2641         for (; l; l = l->next)
2642           gst_buffer_unref (l->data);
2643         g_list_free (buffers);
2644
2645         return ret;
2646       }
2647       /* reset spacing estimation when gap */
2648       priv->ips_rtptime = -1;
2649       priv->ips_dts = GST_CLOCK_TIME_NONE;
2650     }
2651   } else {
2652     GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2653
2654     /* we don't know what the next_in_seqnum should be, wait for the last
2655      * possible moment to push this buffer, maybe we get an earlier seqnum
2656      * while we wait */
2657     set_timer (jitterbuffer, TIMER_TYPE_DEADLINE, seqnum, dts);
2658     do_next_seqnum = TRUE;
2659     /* take rtptime and dts to calculate packet spacing */
2660     priv->ips_rtptime = rtptime;
2661     priv->ips_dts = dts;
2662   }
2663
2664   /* We had no huge gap, let's drop all the gap packets */
2665   if (buffer != NULL) {
2666     GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets");
2667     g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
2668     g_queue_clear (&priv->gap_packets);
2669   } else {
2670     GST_DEBUG_OBJECT (jitterbuffer,
2671         "Had big gap, waiting for more consecutive packets");
2672     JBUF_UNLOCK (jitterbuffer->priv);
2673     return GST_FLOW_OK;
2674   }
2675
2676   if (do_next_seqnum) {
2677     priv->last_in_dts = dts;
2678     priv->next_in_seqnum = (seqnum + 1) & 0xffff;
2679   }
2680
2681   /* let's check if this buffer is too late, we can only accept packets with
2682    * bigger seqnum than the one we last pushed. */
2683   if (G_LIKELY (priv->last_popped_seqnum != -1)) {
2684     gint gap;
2685
2686     gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
2687
2688     /* priv->last_popped_seqnum >= seqnum, we're too late. */
2689     if (G_UNLIKELY (gap <= 0))
2690       goto too_late;
2691   }
2692
2693   /* let's drop oldest packet if the queue is already full and drop-on-latency
2694    * is set. We can only do this when there actually is a latency. When no
2695    * latency is set, we just pump it in the queue and let the other end push it
2696    * out as fast as possible. */
2697   if (priv->latency_ms && priv->drop_on_latency) {
2698     latency_ts =
2699         gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
2700
2701     if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
2702       RTPJitterBufferItem *old_item;
2703
2704       old_item = rtp_jitter_buffer_peek (priv->jbuf);
2705
2706       if (IS_DROPABLE (old_item)) {
2707         old_item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2708         GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
2709             old_item);
2710         priv->next_seqnum = (old_item->seqnum + 1) & 0xffff;
2711         free_item (old_item);
2712       }
2713       /* we might have removed some head buffers, signal the pushing thread to
2714        * see if it can push now */
2715       JBUF_SIGNAL_EVENT (priv);
2716     }
2717   }
2718
2719   /* If we estimated the DTS, don't consider it in the clock skew calculations
2720    * later. The code above always sets dts to pts or the other way around if
2721    * any of those is valid in the buffer, so we know that if we estimated the
2722    * dts that both are unknown */
2723   if (estimated_dts)
2724     item =
2725         alloc_item (buffer, ITEM_TYPE_BUFFER, GST_CLOCK_TIME_NONE,
2726         GST_CLOCK_TIME_NONE, seqnum, 1, rtptime);
2727   else
2728     item = alloc_item (buffer, ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime);
2729
2730   /* now insert the packet into the queue in sorted order. This function returns
2731    * FALSE if a packet with the same seqnum was already in the queue, meaning we
2732    * have a duplicate. */
2733   if (G_UNLIKELY (!rtp_jitter_buffer_insert (priv->jbuf, item,
2734               &head, &percent)))
2735     goto duplicate;
2736
2737   /* update timers */
2738   update_timers (jitterbuffer, seqnum, dts, do_next_seqnum);
2739
2740   /* we had an unhandled SR, handle it now */
2741   if (priv->last_sr)
2742     do_handle_sync (jitterbuffer);
2743
2744   if (G_UNLIKELY (head)) {
2745     /* signal addition of new buffer when the _loop is waiting. */
2746     if (G_LIKELY (priv->active))
2747       JBUF_SIGNAL_EVENT (priv);
2748
2749     /* let's unschedule and unblock any waiting buffers. We only want to do this
2750      * when the head buffer changed */
2751     if (G_UNLIKELY (priv->clock_id)) {
2752       GST_DEBUG_OBJECT (jitterbuffer, "Unscheduling waiting new buffer");
2753       unschedule_current_timer (jitterbuffer);
2754     }
2755   }
2756
2757   GST_DEBUG_OBJECT (jitterbuffer,
2758       "Pushed packet #%d, now %d packets, head: %d, " "percent %d", seqnum,
2759       rtp_jitter_buffer_num_packets (priv->jbuf), head, percent);
2760
2761   msg = check_buffering_percent (jitterbuffer, percent);
2762
2763 finished:
2764   JBUF_UNLOCK (priv);
2765
2766   if (msg)
2767     gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2768
2769   return ret;
2770
2771   /* ERRORS */
2772 invalid_buffer:
2773   {
2774     /* this is not fatal but should be filtered earlier */
2775     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2776         ("Received invalid RTP payload, dropping"));
2777     gst_buffer_unref (buffer);
2778     return GST_FLOW_OK;
2779   }
2780 no_clock_rate:
2781   {
2782     GST_WARNING_OBJECT (jitterbuffer,
2783         "No clock-rate in caps!, dropping buffer");
2784     gst_buffer_unref (buffer);
2785     goto finished;
2786   }
2787 out_flushing:
2788   {
2789     ret = priv->srcresult;
2790     GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
2791     gst_buffer_unref (buffer);
2792     goto finished;
2793   }
2794 have_eos:
2795   {
2796     ret = GST_FLOW_EOS;
2797     GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
2798     gst_buffer_unref (buffer);
2799     goto finished;
2800   }
2801 too_late:
2802   {
2803     GST_WARNING_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
2804         " popped, dropping", seqnum, priv->last_popped_seqnum);
2805     priv->num_late++;
2806     gst_buffer_unref (buffer);
2807     goto finished;
2808   }
2809 duplicate:
2810   {
2811     GST_WARNING_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
2812         seqnum);
2813     priv->num_duplicates++;
2814     free_item (item);
2815     goto finished;
2816   }
2817 }
2818
2819 static GstClockTime
2820 compute_elapsed (GstRtpJitterBuffer * jitterbuffer, RTPJitterBufferItem * item)
2821 {
2822   guint64 ext_time, elapsed;
2823   guint32 rtp_time;
2824   GstRtpJitterBufferPrivate *priv;
2825
2826   priv = jitterbuffer->priv;
2827   rtp_time = item->rtptime;
2828
2829   GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
2830       G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
2831
2832   ext_time = priv->ext_timestamp;
2833   ext_time = gst_rtp_buffer_ext_timestamp (&ext_time, rtp_time);
2834   if (ext_time < priv->ext_timestamp) {
2835     ext_time = priv->ext_timestamp;
2836   } else {
2837     priv->ext_timestamp = ext_time;
2838   }
2839
2840   if (ext_time > priv->clock_base)
2841     elapsed = ext_time - priv->clock_base;
2842   else
2843     elapsed = 0;
2844
2845   elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
2846   return elapsed;
2847 }
2848
2849 static void
2850 update_estimated_eos (GstRtpJitterBuffer * jitterbuffer,
2851     RTPJitterBufferItem * item)
2852 {
2853   guint64 total, elapsed, left, estimated;
2854   GstClockTime out_time;
2855   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2856
2857   if (priv->npt_stop == -1 || priv->ext_timestamp == -1
2858       || priv->clock_base == -1 || priv->clock_rate <= 0)
2859     return;
2860
2861   /* compute the elapsed time */
2862   elapsed = compute_elapsed (jitterbuffer, item);
2863
2864   /* do nothing if elapsed time doesn't increment */
2865   if (priv->last_elapsed && elapsed <= priv->last_elapsed)
2866     return;
2867
2868   priv->last_elapsed = elapsed;
2869
2870   /* this is the total time we need to play */
2871   total = priv->npt_stop - priv->npt_start;
2872   GST_LOG_OBJECT (jitterbuffer, "total %" GST_TIME_FORMAT,
2873       GST_TIME_ARGS (total));
2874
2875   /* this is how much time there is left */
2876   if (total > elapsed)
2877     left = total - elapsed;
2878   else
2879     left = 0;
2880
2881   /* if we have less time left that the size of the buffer, we will not
2882    * be able to keep it filled, disabled buffering then */
2883   if (left < rtp_jitter_buffer_get_delay (priv->jbuf)) {
2884     GST_DEBUG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT
2885         ", disable buffering close to EOS", GST_TIME_ARGS (left));
2886     rtp_jitter_buffer_disable_buffering (priv->jbuf, TRUE);
2887   }
2888
2889   /* this is the current time as running-time */
2890   out_time = item->dts;
2891
2892   if (elapsed > 0)
2893     estimated = gst_util_uint64_scale (out_time, total, elapsed);
2894   else {
2895     /* if there is almost nothing left,
2896      * we may never advance enough to end up in the above case */
2897     if (total < GST_SECOND)
2898       estimated = GST_SECOND;
2899     else
2900       estimated = -1;
2901   }
2902   GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
2903       GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
2904
2905   if (estimated != -1 && priv->estimated_eos != estimated) {
2906     set_timer (jitterbuffer, TIMER_TYPE_EOS, -1, estimated);
2907     priv->estimated_eos = estimated;
2908   }
2909 }
2910
2911 /* take a buffer from the queue and push it */
2912 static GstFlowReturn
2913 pop_and_push_next (GstRtpJitterBuffer * jitterbuffer, guint seqnum)
2914 {
2915   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2916   GstFlowReturn result = GST_FLOW_OK;
2917   RTPJitterBufferItem *item;
2918   GstBuffer *outbuf = NULL;
2919   GstEvent *outevent = NULL;
2920   GstQuery *outquery = NULL;
2921   GstClockTime dts, pts;
2922   gint percent = -1;
2923   gboolean do_push = TRUE;
2924   guint type;
2925   GstMessage *msg;
2926
2927   /* when we get here we are ready to pop and push the buffer */
2928   item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2929   type = item->type;
2930
2931   switch (type) {
2932     case ITEM_TYPE_BUFFER:
2933
2934       /* we need to make writable to change the flags and timestamps */
2935       outbuf = gst_buffer_make_writable (item->data);
2936
2937       if (G_UNLIKELY (priv->discont)) {
2938         /* set DISCONT flag when we missed a packet. We pushed the buffer writable
2939          * into the jitterbuffer so we can modify now. */
2940         GST_DEBUG_OBJECT (jitterbuffer, "mark output buffer discont");
2941         GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
2942         priv->discont = FALSE;
2943       }
2944       if (G_UNLIKELY (priv->ts_discont)) {
2945         GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
2946         priv->ts_discont = FALSE;
2947       }
2948
2949       dts =
2950           gst_segment_position_from_running_time (&priv->segment,
2951           GST_FORMAT_TIME, item->dts);
2952       pts =
2953           gst_segment_position_from_running_time (&priv->segment,
2954           GST_FORMAT_TIME, item->pts);
2955
2956       /* apply timestamp with offset to buffer now */
2957       GST_BUFFER_DTS (outbuf) = apply_offset (jitterbuffer, dts);
2958       GST_BUFFER_PTS (outbuf) = apply_offset (jitterbuffer, pts);
2959
2960       /* update the elapsed time when we need to check against the npt stop time. */
2961       update_estimated_eos (jitterbuffer, item);
2962
2963       priv->last_out_time = GST_BUFFER_PTS (outbuf);
2964       break;
2965     case ITEM_TYPE_LOST:
2966       priv->discont = TRUE;
2967       if (!priv->do_lost)
2968         do_push = FALSE;
2969       /* FALLTHROUGH */
2970     case ITEM_TYPE_EVENT:
2971       outevent = item->data;
2972       break;
2973     case ITEM_TYPE_QUERY:
2974       outquery = item->data;
2975       break;
2976   }
2977
2978   /* now we are ready to push the buffer. Save the seqnum and release the lock
2979    * so the other end can push stuff in the queue again. */
2980   if (seqnum != -1) {
2981     priv->last_popped_seqnum = seqnum;
2982     priv->next_seqnum = (seqnum + item->count) & 0xffff;
2983   }
2984   msg = check_buffering_percent (jitterbuffer, percent);
2985   JBUF_UNLOCK (priv);
2986
2987   item->data = NULL;
2988   free_item (item);
2989
2990   if (msg)
2991     gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
2992
2993   switch (type) {
2994     case ITEM_TYPE_BUFFER:
2995       /* push buffer */
2996       GST_DEBUG_OBJECT (jitterbuffer,
2997           "Pushing buffer %d, dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2998           seqnum, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
2999           GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
3000       result = gst_pad_push (priv->srcpad, outbuf);
3001
3002       JBUF_LOCK_CHECK (priv, out_flushing);
3003       break;
3004     case ITEM_TYPE_LOST:
3005     case ITEM_TYPE_EVENT:
3006       /* We got not enough consecutive packets with a huge gap, we can
3007        * as well just drop them here now on EOS */
3008       if (GST_EVENT_TYPE (outevent) == GST_EVENT_EOS) {
3009         GST_DEBUG_OBJECT (jitterbuffer, "Clearing gap packets on EOS");
3010         g_queue_foreach (&priv->gap_packets, (GFunc) gst_buffer_unref, NULL);
3011         g_queue_clear (&priv->gap_packets);
3012       }
3013
3014       GST_DEBUG_OBJECT (jitterbuffer, "%sPushing event %" GST_PTR_FORMAT
3015           ", seqnum %d", do_push ? "" : "NOT ", outevent, seqnum);
3016
3017       if (do_push)
3018         gst_pad_push_event (priv->srcpad, outevent);
3019       else
3020         gst_event_unref (outevent);
3021
3022       result = GST_FLOW_OK;
3023
3024       JBUF_LOCK_CHECK (priv, out_flushing);
3025       break;
3026     case ITEM_TYPE_QUERY:
3027     {
3028       gboolean res;
3029
3030       res = gst_pad_peer_query (priv->srcpad, outquery);
3031
3032       JBUF_LOCK_CHECK (priv, out_flushing);
3033       result = GST_FLOW_OK;
3034       GST_LOG_OBJECT (jitterbuffer, "did query %p, return %d", outquery, res);
3035       JBUF_SIGNAL_QUERY (priv, res);
3036       break;
3037     }
3038   }
3039   return result;
3040
3041   /* ERRORS */
3042 out_flushing:
3043   {
3044     return priv->srcresult;
3045   }
3046 }
3047
3048 #define GST_FLOW_WAIT GST_FLOW_CUSTOM_SUCCESS
3049
3050 /* Peek a buffer and compare the seqnum to the expected seqnum.
3051  * If all is fine, the buffer is pushed.
3052  * If something is wrong, we wait for some event
3053  */
3054 static GstFlowReturn
3055 handle_next_buffer (GstRtpJitterBuffer * jitterbuffer)
3056 {
3057   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3058   GstFlowReturn result;
3059   RTPJitterBufferItem *item;
3060   guint seqnum;
3061   guint32 next_seqnum;
3062
3063   /* only push buffers when PLAYING and active and not buffering */
3064   if (priv->blocked || !priv->active ||
3065       rtp_jitter_buffer_is_buffering (priv->jbuf)) {
3066     return GST_FLOW_WAIT;
3067   }
3068
3069   /* peek a buffer, we're just looking at the sequence number.
3070    * If all is fine, we'll pop and push it. If the sequence number is wrong we
3071    * wait for a timeout or something to change.
3072    * The peeked buffer is valid for as long as we hold the jitterbuffer lock. */
3073   item = rtp_jitter_buffer_peek (priv->jbuf);
3074   if (item == NULL) {
3075     goto wait;
3076   }
3077
3078   /* get the seqnum and the next expected seqnum */
3079   seqnum = item->seqnum;
3080   if (seqnum == -1) {
3081     return pop_and_push_next (jitterbuffer, seqnum);
3082   }
3083
3084   next_seqnum = priv->next_seqnum;
3085
3086   /* get the gap between this and the previous packet. If we don't know the
3087    * previous packet seqnum assume no gap. */
3088   if (G_UNLIKELY (next_seqnum == -1)) {
3089     GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
3090     /* we don't know what the next_seqnum should be, the chain function should
3091      * have scheduled a DEADLINE timer that will increment next_seqnum when it
3092      * fires, so wait for that */
3093     result = GST_FLOW_WAIT;
3094   } else {
3095     gint gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
3096
3097     if (G_LIKELY (gap == 0)) {
3098       /* no missing packet, pop and push */
3099       result = pop_and_push_next (jitterbuffer, seqnum);
3100     } else if (G_UNLIKELY (gap < 0)) {
3101       /* if we have a packet that we already pushed or considered dropped, pop it
3102        * off and get the next packet */
3103       GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
3104           seqnum, next_seqnum);
3105       item = rtp_jitter_buffer_pop (priv->jbuf, NULL);
3106       free_item (item);
3107       result = GST_FLOW_OK;
3108     } else {
3109       /* the chain function has scheduled timers to request retransmission or
3110        * when to consider the packet lost, wait for that */
3111       GST_DEBUG_OBJECT (jitterbuffer,
3112           "Sequence number GAP detected: expected %d instead of %d (%d missing)",
3113           next_seqnum, seqnum, gap);
3114       result = GST_FLOW_WAIT;
3115     }
3116   }
3117
3118   return result;
3119
3120 wait:
3121   {
3122     GST_DEBUG_OBJECT (jitterbuffer, "no buffer, going to wait");
3123     if (priv->eos) {
3124       return GST_FLOW_EOS;
3125     } else {
3126       return GST_FLOW_WAIT;
3127     }
3128   }
3129 }
3130
3131 static GstClockTime
3132 get_rtx_retry_timeout (GstRtpJitterBufferPrivate * priv)
3133 {
3134   GstClockTime rtx_retry_timeout;
3135   GstClockTime rtx_min_retry_timeout;
3136
3137   if (priv->rtx_retry_timeout == -1) {
3138     if (priv->avg_rtx_rtt == 0)
3139       rtx_retry_timeout = DEFAULT_AUTO_RTX_TIMEOUT;
3140     else
3141       /* we want to ask for a retransmission after we waited for a
3142        * complete RTT and the additional jitter */
3143       rtx_retry_timeout = priv->avg_rtx_rtt + priv->avg_jitter * 2;
3144   } else {
3145     rtx_retry_timeout = priv->rtx_retry_timeout * GST_MSECOND;
3146   }
3147   /* make sure we don't retry too often. On very low latency networks,
3148    * the RTT and jitter can be very low. */
3149   if (priv->rtx_min_retry_timeout == -1) {
3150     rtx_min_retry_timeout = priv->packet_spacing;
3151   } else {
3152     rtx_min_retry_timeout = priv->rtx_min_retry_timeout * GST_MSECOND;
3153   }
3154   rtx_retry_timeout = MAX (rtx_retry_timeout, rtx_min_retry_timeout);
3155
3156   return rtx_retry_timeout;
3157 }
3158
3159 static GstClockTime
3160 get_rtx_retry_period (GstRtpJitterBufferPrivate * priv,
3161     GstClockTime rtx_retry_timeout)
3162 {
3163   GstClockTime rtx_retry_period;
3164
3165   if (priv->rtx_retry_period == -1) {
3166     /* we retry up to the configured jitterbuffer size but leaving some
3167      * room for the retransmission to arrive in time */
3168     if (rtx_retry_timeout > priv->latency_ns) {
3169       rtx_retry_period = 0;
3170     } else {
3171       rtx_retry_period = priv->latency_ns - rtx_retry_timeout;
3172     }
3173   } else {
3174     rtx_retry_period = priv->rtx_retry_period * GST_MSECOND;
3175   }
3176   return rtx_retry_period;
3177 }
3178
3179 /* the timeout for when we expected a packet expired */
3180 static gboolean
3181 do_expected_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3182     GstClockTime now)
3183 {
3184   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3185   GstEvent *event;
3186   guint delay, delay_ms, avg_rtx_rtt_ms;
3187   guint rtx_retry_timeout_ms, rtx_retry_period_ms;
3188   GstClockTime rtx_retry_period;
3189   GstClockTime rtx_retry_timeout;
3190   GstClock *clock;
3191
3192   GST_DEBUG_OBJECT (jitterbuffer, "expected %d didn't arrive, now %"
3193       GST_TIME_FORMAT, timer->seqnum, GST_TIME_ARGS (now));
3194
3195   rtx_retry_timeout = get_rtx_retry_timeout (priv);
3196   rtx_retry_period = get_rtx_retry_period (priv, rtx_retry_timeout);
3197
3198   GST_DEBUG_OBJECT (jitterbuffer, "timeout %" GST_TIME_FORMAT ", period %"
3199       GST_TIME_FORMAT, GST_TIME_ARGS (rtx_retry_timeout),
3200       GST_TIME_ARGS (rtx_retry_period));
3201
3202   delay = timer->rtx_delay + timer->rtx_retry;
3203
3204   delay_ms = GST_TIME_AS_MSECONDS (delay);
3205   rtx_retry_timeout_ms = GST_TIME_AS_MSECONDS (rtx_retry_timeout);
3206   rtx_retry_period_ms = GST_TIME_AS_MSECONDS (rtx_retry_period);
3207   avg_rtx_rtt_ms = GST_TIME_AS_MSECONDS (priv->avg_rtx_rtt);
3208
3209   event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
3210       gst_structure_new ("GstRTPRetransmissionRequest",
3211           "seqnum", G_TYPE_UINT, (guint) timer->seqnum,
3212           "running-time", G_TYPE_UINT64, timer->rtx_base,
3213           "delay", G_TYPE_UINT, delay_ms,
3214           "retry", G_TYPE_UINT, timer->num_rtx_retry,
3215           "frequency", G_TYPE_UINT, rtx_retry_timeout_ms,
3216           "period", G_TYPE_UINT, rtx_retry_period_ms,
3217           "deadline", G_TYPE_UINT, priv->latency_ms,
3218           "packet-spacing", G_TYPE_UINT64, priv->packet_spacing,
3219           "avg-rtt", G_TYPE_UINT, avg_rtx_rtt_ms, NULL));
3220
3221   priv->num_rtx_requests++;
3222   timer->num_rtx_retry++;
3223
3224   GST_OBJECT_LOCK (jitterbuffer);
3225   if ((clock = GST_ELEMENT_CLOCK (jitterbuffer))) {
3226     timer->rtx_last = gst_clock_get_time (clock);
3227     timer->rtx_last -= GST_ELEMENT_CAST (jitterbuffer)->base_time;
3228   } else {
3229     timer->rtx_last = now;
3230   }
3231   GST_OBJECT_UNLOCK (jitterbuffer);
3232
3233   /* calculate the timeout for the next retransmission attempt */
3234   timer->rtx_retry += rtx_retry_timeout;
3235   GST_DEBUG_OBJECT (jitterbuffer, "base %" GST_TIME_FORMAT ", delay %"
3236       GST_TIME_FORMAT ", retry %" GST_TIME_FORMAT ", num_retry %u",
3237       GST_TIME_ARGS (timer->rtx_base), GST_TIME_ARGS (timer->rtx_delay),
3238       GST_TIME_ARGS (timer->rtx_retry), timer->num_rtx_retry);
3239   if ((priv->rtx_max_retries != -1
3240           && timer->num_rtx_retry >= priv->rtx_max_retries)
3241       || (timer->rtx_retry + timer->rtx_delay > rtx_retry_period)) {
3242     GST_DEBUG_OBJECT (jitterbuffer, "reschedule as LOST timer");
3243     /* too many retransmission request, we now convert the timer
3244      * to a lost timer, leave the num_rtx_retry as it is for stats */
3245     timer->type = TIMER_TYPE_LOST;
3246     timer->rtx_delay = 0;
3247     timer->rtx_retry = 0;
3248   }
3249   reschedule_timer (jitterbuffer, timer, timer->seqnum,
3250       timer->rtx_base + timer->rtx_retry, timer->rtx_delay, FALSE);
3251
3252   JBUF_UNLOCK (priv);
3253   gst_pad_push_event (priv->sinkpad, event);
3254   JBUF_LOCK (priv);
3255
3256   return FALSE;
3257 }
3258
3259 /* a packet is lost */
3260 static gboolean
3261 do_lost_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3262     GstClockTime now)
3263 {
3264   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3265   GstClockTime duration, timestamp;
3266   guint seqnum, lost_packets, num_rtx_retry, next_in_seqnum;
3267   gboolean head;
3268   GstEvent *event;
3269   RTPJitterBufferItem *item;
3270
3271   seqnum = timer->seqnum;
3272   timestamp = apply_offset (jitterbuffer, timer->timeout);
3273   duration = timer->duration;
3274   if (duration == GST_CLOCK_TIME_NONE && priv->packet_spacing > 0)
3275     duration = priv->packet_spacing;
3276   lost_packets = MAX (timer->num, 1);
3277   num_rtx_retry = timer->num_rtx_retry;
3278
3279   /* we had a gap and thus we lost some packets. Create an event for this.  */
3280   if (lost_packets > 1)
3281     GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", seqnum,
3282         seqnum + lost_packets - 1);
3283   else
3284     GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", seqnum);
3285
3286   priv->num_late += lost_packets;
3287   priv->num_rtx_failed += num_rtx_retry;
3288
3289   next_in_seqnum = (seqnum + lost_packets) & 0xffff;
3290
3291   /* we now only accept seqnum bigger than this */
3292   if (gst_rtp_buffer_compare_seqnum (priv->next_in_seqnum, next_in_seqnum) > 0)
3293     priv->next_in_seqnum = next_in_seqnum;
3294
3295   /* create paket lost event */
3296   event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
3297       gst_structure_new ("GstRTPPacketLost",
3298           "seqnum", G_TYPE_UINT, (guint) seqnum,
3299           "timestamp", G_TYPE_UINT64, timestamp,
3300           "duration", G_TYPE_UINT64, duration,
3301           "retry", G_TYPE_UINT, num_rtx_retry, NULL));
3302
3303   item = alloc_item (event, ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1);
3304   rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3305
3306   /* remove timer now */
3307   remove_timer (jitterbuffer, timer);
3308   if (head)
3309     JBUF_SIGNAL_EVENT (priv);
3310
3311   return TRUE;
3312 }
3313
3314 static gboolean
3315 do_eos_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3316     GstClockTime now)
3317 {
3318   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3319
3320   GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
3321   remove_timer (jitterbuffer, timer);
3322   if (!priv->eos) {
3323     /* there was no EOS in the buffer, put one in there now */
3324     queue_event (jitterbuffer, gst_event_new_eos ());
3325   }
3326   JBUF_SIGNAL_EVENT (priv);
3327
3328   return TRUE;
3329 }
3330
3331 static gboolean
3332 do_deadline_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3333     GstClockTime now)
3334 {
3335   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3336
3337   GST_INFO_OBJECT (jitterbuffer, "got deadline timeout");
3338
3339   /* timer seqnum might have been obsoleted by caps seqnum-base,
3340    * only mess with current ongoing seqnum if still unknown */
3341   if (priv->next_seqnum == -1)
3342     priv->next_seqnum = timer->seqnum;
3343   remove_timer (jitterbuffer, timer);
3344   JBUF_SIGNAL_EVENT (priv);
3345
3346   return TRUE;
3347 }
3348
3349 static gboolean
3350 do_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
3351     GstClockTime now)
3352 {
3353   gboolean removed = FALSE;
3354
3355   switch (timer->type) {
3356     case TIMER_TYPE_EXPECTED:
3357       removed = do_expected_timeout (jitterbuffer, timer, now);
3358       break;
3359     case TIMER_TYPE_LOST:
3360       removed = do_lost_timeout (jitterbuffer, timer, now);
3361       break;
3362     case TIMER_TYPE_DEADLINE:
3363       removed = do_deadline_timeout (jitterbuffer, timer, now);
3364       break;
3365     case TIMER_TYPE_EOS:
3366       removed = do_eos_timeout (jitterbuffer, timer, now);
3367       break;
3368   }
3369   return removed;
3370 }
3371
3372 /* called when we need to wait for the next timeout.
3373  *
3374  * We loop over the array of recorded timeouts and wait for the earliest one.
3375  * When it timed out, do the logic associated with the timer.
3376  *
3377  * If there are no timers, we wait on a gcond until something new happens.
3378  */
3379 static void
3380 wait_next_timeout (GstRtpJitterBuffer * jitterbuffer)
3381 {
3382   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
3383   GstClockTime now = 0;
3384
3385   JBUF_LOCK (priv);
3386   while (priv->timer_running) {
3387     TimerData *timer = NULL;
3388     GstClockTime timer_timeout = -1;
3389     gint i, len;
3390
3391     /* If we have a clock, update "now" now with the very
3392      * latest running time we have. If timers are unscheduled below we
3393      * otherwise wouldn't update now (it's only updated when timers
3394      * expire), and also for the very first loop iteration now would
3395      * otherwise always be 0
3396      */
3397     GST_OBJECT_LOCK (jitterbuffer);
3398     if (GST_ELEMENT_CLOCK (jitterbuffer)) {
3399       now =
3400           gst_clock_get_time (GST_ELEMENT_CLOCK (jitterbuffer)) -
3401           GST_ELEMENT_CAST (jitterbuffer)->base_time;
3402     }
3403     GST_OBJECT_UNLOCK (jitterbuffer);
3404
3405     GST_DEBUG_OBJECT (jitterbuffer, "now %" GST_TIME_FORMAT,
3406         GST_TIME_ARGS (now));
3407
3408     len = priv->timers->len;
3409     for (i = 0; i < len; i++) {
3410       TimerData *test = &g_array_index (priv->timers, TimerData, i);
3411       GstClockTime test_timeout = get_timeout (jitterbuffer, test);
3412       gboolean save_best = FALSE;
3413
3414       GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, %d, %" GST_TIME_FORMAT,
3415           i, test->type, test->seqnum, GST_TIME_ARGS (test_timeout));
3416
3417       /* find the smallest timeout */
3418       if (timer == NULL) {
3419         save_best = TRUE;
3420       } else if (timer_timeout == -1) {
3421         /* we already have an immediate timeout, the new timer must be an
3422          * immediate timer with smaller seqnum to become the best */
3423         if (test_timeout == -1
3424             && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3425                     timer->seqnum) > 0))
3426           save_best = TRUE;
3427       } else if (test_timeout == -1) {
3428         /* first immediate timer */
3429         save_best = TRUE;
3430       } else if (test_timeout < timer_timeout) {
3431         /* earlier timer */
3432         save_best = TRUE;
3433       } else if (test_timeout == timer_timeout
3434           && (gst_rtp_buffer_compare_seqnum (test->seqnum,
3435                   timer->seqnum) > 0)) {
3436         /* same timer, smaller seqnum */
3437         save_best = TRUE;
3438       }
3439       if (save_best) {
3440         GST_DEBUG_OBJECT (jitterbuffer, "new best %d", i);
3441         timer = test;
3442         timer_timeout = test_timeout;
3443       }
3444     }
3445     if (timer && !priv->blocked) {
3446       GstClock *clock;
3447       GstClockTime sync_time;
3448       GstClockID id;
3449       GstClockReturn ret;
3450       GstClockTimeDiff clock_jitter;
3451
3452       if (timer_timeout == -1 || timer_timeout <= now) {
3453         do_timeout (jitterbuffer, timer, now);
3454         /* check here, do_timeout could have released the lock */
3455         if (!priv->timer_running)
3456           break;
3457         continue;
3458       }
3459
3460       GST_OBJECT_LOCK (jitterbuffer);
3461       clock = GST_ELEMENT_CLOCK (jitterbuffer);
3462       if (!clock) {
3463         GST_OBJECT_UNLOCK (jitterbuffer);
3464         /* let's just push if there is no clock */
3465         GST_DEBUG_OBJECT (jitterbuffer, "No clock, timeout right away");
3466         now = timer_timeout;
3467         continue;
3468       }
3469
3470       /* prepare for sync against clock */
3471       sync_time = timer_timeout + GST_ELEMENT_CAST (jitterbuffer)->base_time;
3472       /* add latency of peer to get input time */
3473       sync_time += priv->peer_latency;
3474
3475       GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
3476           " with sync time %" GST_TIME_FORMAT,
3477           GST_TIME_ARGS (timer_timeout), GST_TIME_ARGS (sync_time));
3478
3479       /* create an entry for the clock */
3480       id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
3481       priv->timer_timeout = timer_timeout;
3482       priv->timer_seqnum = timer->seqnum;
3483       GST_OBJECT_UNLOCK (jitterbuffer);
3484
3485       /* release the lock so that the other end can push stuff or unlock */
3486       JBUF_UNLOCK (priv);
3487
3488       ret = gst_clock_id_wait (id, &clock_jitter);
3489
3490       JBUF_LOCK (priv);
3491       if (!priv->timer_running) {
3492         gst_clock_id_unref (id);
3493         priv->clock_id = NULL;
3494         break;
3495       }
3496
3497       if (ret != GST_CLOCK_UNSCHEDULED) {
3498         now = timer_timeout + MAX (clock_jitter, 0);
3499         GST_DEBUG_OBJECT (jitterbuffer,
3500             "sync done, %d, #%d, %" GST_STIME_FORMAT, ret, priv->timer_seqnum,
3501             GST_STIME_ARGS (clock_jitter));
3502       } else {
3503         GST_DEBUG_OBJECT (jitterbuffer, "sync unscheduled");
3504       }
3505       /* and free the entry */
3506       gst_clock_id_unref (id);
3507       priv->clock_id = NULL;
3508     } else {
3509       /* no timers, wait for activity */
3510       JBUF_WAIT_TIMER (priv);
3511     }
3512   }
3513   JBUF_UNLOCK (priv);
3514
3515   GST_DEBUG_OBJECT (jitterbuffer, "we are stopping");
3516   return;
3517 }
3518
3519 /*
3520  * This funcion implements the main pushing loop on the source pad.
3521  *
3522  * It first tries to push as many buffers as possible. If there is a seqnum
3523  * mismatch, we wait for the next timeouts.
3524  */
3525 static void
3526 gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer)
3527 {
3528   GstRtpJitterBufferPrivate *priv;
3529   GstFlowReturn result = GST_FLOW_OK;
3530
3531   priv = jitterbuffer->priv;
3532
3533   JBUF_LOCK_CHECK (priv, flushing);
3534   do {
3535     result = handle_next_buffer (jitterbuffer);
3536     if (G_LIKELY (result == GST_FLOW_WAIT)) {
3537       /* now wait for the next event */
3538       JBUF_WAIT_EVENT (priv, flushing);
3539       result = GST_FLOW_OK;
3540     }
3541   } while (result == GST_FLOW_OK);
3542   /* store result for upstream */
3543   priv->srcresult = result;
3544   /* if we get here we need to pause */
3545   goto pause;
3546
3547   /* ERRORS */
3548 flushing:
3549   {
3550     result = priv->srcresult;
3551     goto pause;
3552   }
3553 pause:
3554   {
3555     GstEvent *event;
3556
3557     JBUF_SIGNAL_QUERY (priv, FALSE);
3558     JBUF_UNLOCK (priv);
3559
3560     GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s",
3561         gst_flow_get_name (result));
3562     gst_pad_pause_task (priv->srcpad);
3563     if (result == GST_FLOW_EOS) {
3564       event = gst_event_new_eos ();
3565       gst_pad_push_event (priv->srcpad, event);
3566     }
3567     return;
3568   }
3569 }
3570
3571 /* collect the info from the lastest RTCP packet and the jitterbuffer sync, do
3572  * some sanity checks and then emit the handle-sync signal with the parameters.
3573  * This function must be called with the LOCK */
3574 static void
3575 do_handle_sync (GstRtpJitterBuffer * jitterbuffer)
3576 {
3577   GstRtpJitterBufferPrivate *priv;
3578   guint64 base_rtptime, base_time;
3579   guint32 clock_rate;
3580   guint64 last_rtptime;
3581   guint64 clock_base;
3582   guint64 ext_rtptime, diff;
3583   gboolean valid = TRUE, keep = FALSE;
3584
3585   priv = jitterbuffer->priv;
3586
3587   /* get the last values from the jitterbuffer */
3588   rtp_jitter_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
3589       &clock_rate, &last_rtptime);
3590
3591   clock_base = priv->clock_base;
3592   ext_rtptime = priv->ext_rtptime;
3593
3594   GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
3595       G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
3596       ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
3597       ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
3598
3599   if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
3600     /* we keep this SR packet for later. When we get a valid RTP packet the
3601      * above values will be set and we can try to use the SR packet */
3602     GST_DEBUG_OBJECT (jitterbuffer, "keeping for later, no RTP values");
3603     keep = TRUE;
3604   } else {
3605     /* we can't accept anything that happened before we did the last resync */
3606     if (base_rtptime > ext_rtptime) {
3607       GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
3608       valid = FALSE;
3609     } else {
3610       /* the SR RTP timestamp must be something close to what we last observed
3611        * in the jitterbuffer */
3612       if (ext_rtptime > last_rtptime) {
3613         /* check how far ahead it is to our RTP timestamps */
3614         diff = ext_rtptime - last_rtptime;
3615         /* if bigger than 1 second, we drop it */
3616         if (jitterbuffer->priv->max_rtcp_rtp_time_diff != -1 &&
3617             diff >
3618             gst_util_uint64_scale (jitterbuffer->priv->max_rtcp_rtp_time_diff,
3619                 clock_rate, 1000)) {
3620           GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
3621           /* should drop this, but some RTSP servers end up with bogus
3622            * way too ahead RTCP packet when repeated PAUSE/PLAY,
3623            * so still trigger rptbin sync but invalidate RTCP data
3624            * (sync might use other methods) */
3625           ext_rtptime = -1;
3626         }
3627         GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
3628             G_GUINT64_FORMAT, last_rtptime, diff);
3629       }
3630     }
3631   }
3632
3633   if (keep) {
3634     GST_DEBUG_OBJECT (jitterbuffer, "keeping RTCP packet for later");
3635   } else if (valid) {
3636     GstStructure *s;
3637
3638     s = gst_structure_new ("application/x-rtp-sync",
3639         "base-rtptime", G_TYPE_UINT64, base_rtptime,
3640         "base-time", G_TYPE_UINT64, base_time,
3641         "clock-rate", G_TYPE_UINT, clock_rate,
3642         "clock-base", G_TYPE_UINT64, clock_base,
3643         "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
3644         "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
3645
3646     GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
3647     gst_buffer_replace (&priv->last_sr, NULL);
3648     JBUF_UNLOCK (priv);
3649     g_signal_emit (jitterbuffer,
3650         gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
3651     JBUF_LOCK (priv);
3652     gst_structure_free (s);
3653   } else {
3654     GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
3655     gst_buffer_replace (&priv->last_sr, NULL);
3656   }
3657 }
3658
3659 static GstFlowReturn
3660 gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
3661     GstBuffer * buffer)
3662 {
3663   GstRtpJitterBuffer *jitterbuffer;
3664   GstRtpJitterBufferPrivate *priv;
3665   GstFlowReturn ret = GST_FLOW_OK;
3666   guint32 ssrc;
3667   GstRTCPPacket packet;
3668   guint64 ext_rtptime;
3669   guint32 rtptime;
3670   GstRTCPBuffer rtcp = { NULL, };
3671
3672   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3673
3674   if (G_UNLIKELY (!gst_rtcp_buffer_validate_reduced (buffer)))
3675     goto invalid_buffer;
3676
3677   priv = jitterbuffer->priv;
3678
3679   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
3680
3681   if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
3682     goto empty_buffer;
3683
3684   /* first packet must be SR or RR or else the validate would have failed */
3685   switch (gst_rtcp_packet_get_type (&packet)) {
3686     case GST_RTCP_TYPE_SR:
3687       gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
3688           NULL, NULL);
3689       break;
3690     default:
3691       goto ignore_buffer;
3692   }
3693   gst_rtcp_buffer_unmap (&rtcp);
3694
3695   GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
3696
3697   JBUF_LOCK (priv);
3698   /* convert the RTP timestamp to our extended timestamp, using the same offset
3699    * we used in the jitterbuffer */
3700   ext_rtptime = priv->jbuf->ext_rtptime;
3701   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
3702
3703   priv->ext_rtptime = ext_rtptime;
3704   gst_buffer_replace (&priv->last_sr, buffer);
3705
3706   do_handle_sync (jitterbuffer);
3707   JBUF_UNLOCK (priv);
3708
3709 done:
3710   gst_buffer_unref (buffer);
3711
3712   return ret;
3713
3714 invalid_buffer:
3715   {
3716     /* this is not fatal but should be filtered earlier */
3717     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3718         ("Received invalid RTCP payload, dropping"));
3719     ret = GST_FLOW_OK;
3720     goto done;
3721   }
3722 empty_buffer:
3723   {
3724     /* this is not fatal but should be filtered earlier */
3725     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
3726         ("Received empty RTCP payload, dropping"));
3727     gst_rtcp_buffer_unmap (&rtcp);
3728     ret = GST_FLOW_OK;
3729     goto done;
3730   }
3731 ignore_buffer:
3732   {
3733     GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
3734     gst_rtcp_buffer_unmap (&rtcp);
3735     ret = GST_FLOW_OK;
3736     goto done;
3737   }
3738 }
3739
3740 static gboolean
3741 gst_rtp_jitter_buffer_sink_query (GstPad * pad, GstObject * parent,
3742     GstQuery * query)
3743 {
3744   gboolean res = FALSE;
3745   GstRtpJitterBuffer *jitterbuffer;
3746   GstRtpJitterBufferPrivate *priv;
3747
3748   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3749   priv = jitterbuffer->priv;
3750
3751   switch (GST_QUERY_TYPE (query)) {
3752     case GST_QUERY_CAPS:
3753     {
3754       GstCaps *filter, *caps;
3755
3756       gst_query_parse_caps (query, &filter);
3757       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3758       gst_query_set_caps_result (query, caps);
3759       gst_caps_unref (caps);
3760       res = TRUE;
3761       break;
3762     }
3763     default:
3764       if (GST_QUERY_IS_SERIALIZED (query)) {
3765         RTPJitterBufferItem *item;
3766         gboolean head;
3767
3768         JBUF_LOCK_CHECK (priv, out_flushing);
3769         if (rtp_jitter_buffer_get_mode (priv->jbuf) !=
3770             RTP_JITTER_BUFFER_MODE_BUFFER) {
3771           GST_DEBUG_OBJECT (jitterbuffer, "adding serialized query");
3772           item = alloc_item (query, ITEM_TYPE_QUERY, -1, -1, -1, 0, -1);
3773           rtp_jitter_buffer_insert (priv->jbuf, item, &head, NULL);
3774           if (head)
3775             JBUF_SIGNAL_EVENT (priv);
3776           JBUF_WAIT_QUERY (priv, out_flushing);
3777           res = priv->last_query;
3778         } else {
3779           GST_DEBUG_OBJECT (jitterbuffer, "refusing query, we are buffering");
3780           res = FALSE;
3781         }
3782         JBUF_UNLOCK (priv);
3783       } else {
3784         res = gst_pad_query_default (pad, parent, query);
3785       }
3786       break;
3787   }
3788   return res;
3789   /* ERRORS */
3790 out_flushing:
3791   {
3792     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
3793     JBUF_UNLOCK (priv);
3794     return FALSE;
3795   }
3796
3797 }
3798
3799 static gboolean
3800 gst_rtp_jitter_buffer_src_query (GstPad * pad, GstObject * parent,
3801     GstQuery * query)
3802 {
3803   GstRtpJitterBuffer *jitterbuffer;
3804   GstRtpJitterBufferPrivate *priv;
3805   gboolean res = FALSE;
3806
3807   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
3808   priv = jitterbuffer->priv;
3809
3810   switch (GST_QUERY_TYPE (query)) {
3811     case GST_QUERY_LATENCY:
3812     {
3813       /* We need to send the query upstream and add the returned latency to our
3814        * own */
3815       GstClockTime min_latency, max_latency;
3816       gboolean us_live;
3817       GstClockTime our_latency;
3818
3819       if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
3820         gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
3821
3822         GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
3823             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3824             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3825
3826         /* store this so that we can safely sync on the peer buffers. */
3827         JBUF_LOCK (priv);
3828         priv->peer_latency = min_latency;
3829         our_latency = priv->latency_ns;
3830         JBUF_UNLOCK (priv);
3831
3832         GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
3833             GST_TIME_ARGS (our_latency));
3834
3835         /* we add some latency but can buffer an infinite amount of time */
3836         min_latency += our_latency;
3837         max_latency = -1;
3838
3839         GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
3840             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
3841             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3842
3843         gst_query_set_latency (query, TRUE, min_latency, max_latency);
3844       }
3845       break;
3846     }
3847     case GST_QUERY_POSITION:
3848     {
3849       GstClockTime start, last_out;
3850       GstFormat fmt;
3851
3852       gst_query_parse_position (query, &fmt, NULL);
3853       if (fmt != GST_FORMAT_TIME) {
3854         res = gst_pad_query_default (pad, parent, query);
3855         break;
3856       }
3857
3858       JBUF_LOCK (priv);
3859       start = priv->npt_start;
3860       last_out = priv->last_out_time;
3861       JBUF_UNLOCK (priv);
3862
3863       GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
3864           ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3865           GST_TIME_ARGS (last_out));
3866
3867       if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
3868         /* bring 0-based outgoing time to stream time */
3869         gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
3870         res = TRUE;
3871       } else {
3872         res = gst_pad_query_default (pad, parent, query);
3873       }
3874       break;
3875     }
3876     case GST_QUERY_CAPS:
3877     {
3878       GstCaps *filter, *caps;
3879
3880       gst_query_parse_caps (query, &filter);
3881       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3882       gst_query_set_caps_result (query, caps);
3883       gst_caps_unref (caps);
3884       res = TRUE;
3885       break;
3886     }
3887     default:
3888       res = gst_pad_query_default (pad, parent, query);
3889       break;
3890   }
3891
3892   return res;
3893 }
3894
3895 static void
3896 gst_rtp_jitter_buffer_set_property (GObject * object,
3897     guint prop_id, const GValue * value, GParamSpec * pspec)
3898 {
3899   GstRtpJitterBuffer *jitterbuffer;
3900   GstRtpJitterBufferPrivate *priv;
3901
3902   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3903   priv = jitterbuffer->priv;
3904
3905   switch (prop_id) {
3906     case PROP_LATENCY:
3907     {
3908       guint new_latency, old_latency;
3909
3910       new_latency = g_value_get_uint (value);
3911
3912       JBUF_LOCK (priv);
3913       old_latency = priv->latency_ms;
3914       priv->latency_ms = new_latency;
3915       priv->latency_ns = priv->latency_ms * GST_MSECOND;
3916       rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
3917       JBUF_UNLOCK (priv);
3918
3919       /* post message if latency changed, this will inform the parent pipeline
3920        * that a latency reconfiguration is possible/needed. */
3921       if (new_latency != old_latency) {
3922         GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
3923             GST_TIME_ARGS (new_latency * GST_MSECOND));
3924
3925         gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
3926             gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
3927       }
3928       break;
3929     }
3930     case PROP_DROP_ON_LATENCY:
3931       JBUF_LOCK (priv);
3932       priv->drop_on_latency = g_value_get_boolean (value);
3933       JBUF_UNLOCK (priv);
3934       break;
3935     case PROP_TS_OFFSET:
3936       JBUF_LOCK (priv);
3937       priv->ts_offset = g_value_get_int64 (value);
3938       priv->ts_discont = TRUE;
3939       JBUF_UNLOCK (priv);
3940       break;
3941     case PROP_DO_LOST:
3942       JBUF_LOCK (priv);
3943       priv->do_lost = g_value_get_boolean (value);
3944       JBUF_UNLOCK (priv);
3945       break;
3946     case PROP_MODE:
3947       JBUF_LOCK (priv);
3948       rtp_jitter_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
3949       JBUF_UNLOCK (priv);
3950       break;
3951     case PROP_DO_RETRANSMISSION:
3952       JBUF_LOCK (priv);
3953       priv->do_retransmission = g_value_get_boolean (value);
3954       JBUF_UNLOCK (priv);
3955       break;
3956     case PROP_RTX_NEXT_SEQNUM:
3957       JBUF_LOCK (priv);
3958       priv->rtx_next_seqnum = g_value_get_boolean (value);
3959       JBUF_UNLOCK (priv);
3960       break;
3961     case PROP_RTX_DELAY:
3962       JBUF_LOCK (priv);
3963       priv->rtx_delay = g_value_get_int (value);
3964       JBUF_UNLOCK (priv);
3965       break;
3966     case PROP_RTX_MIN_DELAY:
3967       JBUF_LOCK (priv);
3968       priv->rtx_min_delay = g_value_get_uint (value);
3969       JBUF_UNLOCK (priv);
3970       break;
3971     case PROP_RTX_DELAY_REORDER:
3972       JBUF_LOCK (priv);
3973       priv->rtx_delay_reorder = g_value_get_int (value);
3974       JBUF_UNLOCK (priv);
3975       break;
3976     case PROP_RTX_RETRY_TIMEOUT:
3977       JBUF_LOCK (priv);
3978       priv->rtx_retry_timeout = g_value_get_int (value);
3979       JBUF_UNLOCK (priv);
3980       break;
3981     case PROP_RTX_MIN_RETRY_TIMEOUT:
3982       JBUF_LOCK (priv);
3983       priv->rtx_min_retry_timeout = g_value_get_int (value);
3984       JBUF_UNLOCK (priv);
3985       break;
3986     case PROP_RTX_RETRY_PERIOD:
3987       JBUF_LOCK (priv);
3988       priv->rtx_retry_period = g_value_get_int (value);
3989       JBUF_UNLOCK (priv);
3990       break;
3991     case PROP_RTX_MAX_RETRIES:
3992       JBUF_LOCK (priv);
3993       priv->rtx_max_retries = g_value_get_int (value);
3994       JBUF_UNLOCK (priv);
3995       break;
3996     case PROP_MAX_RTCP_RTP_TIME_DIFF:
3997       JBUF_LOCK (priv);
3998       priv->max_rtcp_rtp_time_diff = g_value_get_int (value);
3999       JBUF_UNLOCK (priv);
4000       break;
4001     case PROP_MAX_DROPOUT_TIME:
4002       JBUF_LOCK (priv);
4003       priv->max_dropout_time = g_value_get_uint (value);
4004       JBUF_UNLOCK (priv);
4005       break;
4006     case PROP_MAX_MISORDER_TIME:
4007       JBUF_LOCK (priv);
4008       priv->max_misorder_time = g_value_get_uint (value);
4009       JBUF_UNLOCK (priv);
4010       break;
4011     default:
4012       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4013       break;
4014   }
4015 }
4016
4017 static void
4018 gst_rtp_jitter_buffer_get_property (GObject * object,
4019     guint prop_id, GValue * value, GParamSpec * pspec)
4020 {
4021   GstRtpJitterBuffer *jitterbuffer;
4022   GstRtpJitterBufferPrivate *priv;
4023
4024   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
4025   priv = jitterbuffer->priv;
4026
4027   switch (prop_id) {
4028     case PROP_LATENCY:
4029       JBUF_LOCK (priv);
4030       g_value_set_uint (value, priv->latency_ms);
4031       JBUF_UNLOCK (priv);
4032       break;
4033     case PROP_DROP_ON_LATENCY:
4034       JBUF_LOCK (priv);
4035       g_value_set_boolean (value, priv->drop_on_latency);
4036       JBUF_UNLOCK (priv);
4037       break;
4038     case PROP_TS_OFFSET:
4039       JBUF_LOCK (priv);
4040       g_value_set_int64 (value, priv->ts_offset);
4041       JBUF_UNLOCK (priv);
4042       break;
4043     case PROP_DO_LOST:
4044       JBUF_LOCK (priv);
4045       g_value_set_boolean (value, priv->do_lost);
4046       JBUF_UNLOCK (priv);
4047       break;
4048     case PROP_MODE:
4049       JBUF_LOCK (priv);
4050       g_value_set_enum (value, rtp_jitter_buffer_get_mode (priv->jbuf));
4051       JBUF_UNLOCK (priv);
4052       break;
4053     case PROP_PERCENT:
4054     {
4055       gint percent;
4056
4057       JBUF_LOCK (priv);
4058       if (priv->srcresult != GST_FLOW_OK)
4059         percent = 100;
4060       else
4061         percent = rtp_jitter_buffer_get_percent (priv->jbuf);
4062
4063       g_value_set_int (value, percent);
4064       JBUF_UNLOCK (priv);
4065       break;
4066     }
4067     case PROP_DO_RETRANSMISSION:
4068       JBUF_LOCK (priv);
4069       g_value_set_boolean (value, priv->do_retransmission);
4070       JBUF_UNLOCK (priv);
4071       break;
4072     case PROP_RTX_NEXT_SEQNUM:
4073       JBUF_LOCK (priv);
4074       g_value_set_boolean (value, priv->rtx_next_seqnum);
4075       JBUF_UNLOCK (priv);
4076       break;
4077     case PROP_RTX_DELAY:
4078       JBUF_LOCK (priv);
4079       g_value_set_int (value, priv->rtx_delay);
4080       JBUF_UNLOCK (priv);
4081       break;
4082     case PROP_RTX_MIN_DELAY:
4083       JBUF_LOCK (priv);
4084       g_value_set_uint (value, priv->rtx_min_delay);
4085       JBUF_UNLOCK (priv);
4086       break;
4087     case PROP_RTX_DELAY_REORDER:
4088       JBUF_LOCK (priv);
4089       g_value_set_int (value, priv->rtx_delay_reorder);
4090       JBUF_UNLOCK (priv);
4091       break;
4092     case PROP_RTX_RETRY_TIMEOUT:
4093       JBUF_LOCK (priv);
4094       g_value_set_int (value, priv->rtx_retry_timeout);
4095       JBUF_UNLOCK (priv);
4096       break;
4097     case PROP_RTX_MIN_RETRY_TIMEOUT:
4098       JBUF_LOCK (priv);
4099       g_value_set_int (value, priv->rtx_min_retry_timeout);
4100       JBUF_UNLOCK (priv);
4101       break;
4102     case PROP_RTX_RETRY_PERIOD:
4103       JBUF_LOCK (priv);
4104       g_value_set_int (value, priv->rtx_retry_period);
4105       JBUF_UNLOCK (priv);
4106       break;
4107     case PROP_RTX_MAX_RETRIES:
4108       JBUF_LOCK (priv);
4109       g_value_set_int (value, priv->rtx_max_retries);
4110       JBUF_UNLOCK (priv);
4111       break;
4112     case PROP_STATS:
4113       g_value_take_boxed (value,
4114           gst_rtp_jitter_buffer_create_stats (jitterbuffer));
4115       break;
4116     case PROP_MAX_RTCP_RTP_TIME_DIFF:
4117       JBUF_LOCK (priv);
4118       g_value_set_int (value, priv->max_rtcp_rtp_time_diff);
4119       JBUF_UNLOCK (priv);
4120       break;
4121     case PROP_MAX_DROPOUT_TIME:
4122       JBUF_LOCK (priv);
4123       g_value_set_uint (value, priv->max_dropout_time);
4124       JBUF_UNLOCK (priv);
4125       break;
4126     case PROP_MAX_MISORDER_TIME:
4127       JBUF_LOCK (priv);
4128       g_value_set_uint (value, priv->max_misorder_time);
4129       JBUF_UNLOCK (priv);
4130       break;
4131     default:
4132       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4133       break;
4134   }
4135 }
4136
4137 static GstStructure *
4138 gst_rtp_jitter_buffer_create_stats (GstRtpJitterBuffer * jbuf)
4139 {
4140   GstStructure *s;
4141
4142   JBUF_LOCK (jbuf->priv);
4143   s = gst_structure_new ("application/x-rtp-jitterbuffer-stats",
4144       "rtx-count", G_TYPE_UINT64, jbuf->priv->num_rtx_requests,
4145       "rtx-success-count", G_TYPE_UINT64, jbuf->priv->num_rtx_success,
4146       "rtx-per-packet", G_TYPE_DOUBLE, jbuf->priv->avg_rtx_num,
4147       "rtx-rtt", G_TYPE_UINT64, jbuf->priv->avg_rtx_rtt, NULL);
4148   JBUF_UNLOCK (jbuf->priv);
4149
4150   return s;
4151 }