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