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