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