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