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