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