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