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