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