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