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