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