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