rtpjitterbuffer: fix crash when do-retransmission=true and a lot of buffers are lost
[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  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  *
24  */
25
26 /**
27  * SECTION:element-rtpjitterbuffer
28  *
29  * This element reorders and removes duplicate RTP packets as they are received
30  * from a network source.
31  *
32  * The element needs the clock-rate of the RTP payload in order to estimate the
33  * delay. This information is obtained either from the caps on the sink pad or,
34  * when no caps are present, from the #GstRtpJitterBuffer::request-pt-map signal.
35  * To clear the previous pt-map use the #GstRtpJitterBuffer::clear-pt-map signal.
36  *
37  * The rtpjitterbuffer will wait for missing packets up to a configurable time
38  * limit using the #GstRtpJitterBuffer:latency property. Packets arriving too
39  * late are considered to be lost packets. If the #GstRtpJitterBuffer:do-lost
40  * property is set, lost packets will result in a custom serialized downstream
41  * event of name GstRTPPacketLost. The lost packet events are usually used by a
42  * depayloader or other element to create concealment data or some other logic
43  * to gracefully handle the missing packets.
44  *
45  * The jitterbuffer will use the DTS (or PTS if no DTS is set) of the incomming
46  * buffer and the rtptime inside the RTP packet to create a PTS on the outgoing
47  * buffer.
48  *
49  * The jitterbuffer can also be configured to send early retransmission events
50  * upstream by setting the #GstRtpJitterBuffer:do-retransmission property. In
51  * this mode, the jitterbuffer tries to estimate when a packet should arrive and
52  * sends a custom upstream event named GstRTPRetransmissionRequest when the
53  * packet is considered late. The initial expected packet arrival time is
54  * calculated as follows:
55  *
56  * - If seqnum N arrived at time T, seqnum N+1 is expected to arrive at
57  *     T + packet-spacing + #GstRtpJitterBuffer:rtx-delay. The packet spacing is
58  *     calculated from the DTS (or PTS is no DTS) of two consecutive RTP
59  *     packets with different rtptime.
60  *
61  * - If seqnum N0 arrived at time T0 and seqnum Nm arrived at time Tm,
62  *     seqnum Ni is expected at time Ti = T0 + i*(Tm - T0)/(Nm - N0). Any
63  *     previously scheduled timeout is overwritten.
64  *
65  * - If seqnum N arrived, all seqnum older than
66  *     N - #GstRtpJitterBuffer:rtx-delay-reorder are considered late
67  *     immediately. This is to request fast feedback for abonormally reorder
68  *     packets before any of the previous timeouts is triggered.
69  *
70  * A late packet triggers the GstRTPRetransmissionRequest custom upstream
71  * event. After the initial timeout expires and the retransmission event is
72  * sent, the timeout is scheduled for
73  * T + #GstRtpJitterBuffer:rtx-retry-timeout. If the missing packet did not
74  * arrive after #GstRtpJitterBuffer:rtx-retry-timeout, a new
75  * GstRTPRetransmissionRequest is sent upstream and the timeout is rescheduled
76  * again for T + #GstRtpJitterBuffer:rtx-retry-timeout. This repeats until
77  * #GstRtpJitterBuffer:rtx-retry-period elapsed, at which point no further
78  * retransmission requests are sent and the regular logic is performed to
79  * schedule a lost packet as discussed above.
80  *
81  * This element acts as a live element and so adds #GstRtpJitterBuffer:latency
82  * to the pipeline.
83  *
84  * This element will automatically be used inside rtpbin.
85  *
86  * <refsect2>
87  * <title>Example pipelines</title>
88  * |[
89  * gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! rtpjitterbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
90  * ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
91  * inserted into the pipeline to smooth out network jitter and to reorder the
92  * out-of-order RTP packets.
93  * </refsect2>
94  *
95  * Last reviewed on 2007-05-28 (0.10.5)
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_DELAY           20
134 #define DEFAULT_RTX_DELAY_REORDER   3
135 #define DEFAULT_RTX_RETRY_TIMEOUT   40
136 #define DEFAULT_RTX_RETRY_PERIOD    160
137
138 enum
139 {
140   PROP_0,
141   PROP_LATENCY,
142   PROP_DROP_ON_LATENCY,
143   PROP_TS_OFFSET,
144   PROP_DO_LOST,
145   PROP_MODE,
146   PROP_PERCENT,
147   PROP_DO_RETRANSMISSION,
148   PROP_RTX_DELAY,
149   PROP_RTX_DELAY_REORDER,
150   PROP_RTX_RETRY_TIMEOUT,
151   PROP_RTX_RETRY_PERIOD,
152   PROP_LAST
153 };
154
155 #define JBUF_LOCK(priv)   (g_mutex_lock (&(priv)->jbuf_lock))
156
157 #define JBUF_LOCK_CHECK(priv,label) G_STMT_START {    \
158   JBUF_LOCK (priv);                                   \
159   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))    \
160     goto label;                                       \
161 } G_STMT_END
162 #define JBUF_UNLOCK(priv) (g_mutex_unlock (&(priv)->jbuf_lock))
163
164 #define JBUF_WAIT_TIMER(priv)   G_STMT_START {            \
165   GST_DEBUG ("waiting timer");                            \
166   (priv)->waiting_timer = TRUE;                           \
167   g_cond_wait (&(priv)->jbuf_timer, &(priv)->jbuf_lock);  \
168   (priv)->waiting_timer = FALSE;                          \
169   GST_DEBUG ("waiting timer done");                       \
170 } G_STMT_END
171 #define JBUF_SIGNAL_TIMER(priv) G_STMT_START {            \
172   if (G_UNLIKELY ((priv)->waiting_timer)) {               \
173     GST_DEBUG ("signal timer");                           \
174     g_cond_signal (&(priv)->jbuf_timer);                  \
175   }                                                       \
176 } G_STMT_END
177
178 #define JBUF_WAIT_EVENT(priv,label) G_STMT_START {       \
179   GST_DEBUG ("waiting event");                           \
180   (priv)->waiting_event = TRUE;                          \
181   g_cond_wait (&(priv)->jbuf_event, &(priv)->jbuf_lock); \
182   (priv)->waiting_event = FALSE;                         \
183   GST_DEBUG ("waiting event done");                      \
184   if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))       \
185     goto label;                                          \
186 } G_STMT_END
187 #define JBUF_SIGNAL_EVENT(priv) G_STMT_START {           \
188   if (G_UNLIKELY ((priv)->waiting_event)) {              \
189     GST_DEBUG ("signal event");                          \
190     g_cond_signal (&(priv)->jbuf_event);                 \
191   }                                                      \
192 } G_STMT_END
193
194 struct _GstRtpJitterBufferPrivate
195 {
196   GstPad *sinkpad, *srcpad;
197   GstPad *rtcpsinkpad;
198
199   RTPJitterBuffer *jbuf;
200   GMutex jbuf_lock;
201   gboolean waiting_timer;
202   GCond jbuf_timer;
203   gboolean waiting_event;
204   GCond jbuf_event;
205   gboolean discont;
206   gboolean ts_discont;
207   gboolean active;
208   guint64 out_offset;
209
210   gboolean timer_running;
211   GThread *timer_thread;
212
213   /* properties */
214   guint latency_ms;
215   guint64 latency_ns;
216   gboolean drop_on_latency;
217   gint64 ts_offset;
218   gboolean do_lost;
219   gboolean do_retransmission;
220   gint rtx_delay;
221   gint rtx_delay_reorder;
222   gint rtx_retry_timeout;
223   gint rtx_retry_period;
224
225   /* the last seqnum we pushed out */
226   guint32 last_popped_seqnum;
227   /* the next expected seqnum we push */
228   guint32 next_seqnum;
229   /* last output time */
230   GstClockTime last_out_time;
231   /* last valid input timestamp and rtptime pair */
232   GstClockTime ips_dts;
233   guint64 ips_rtptime;
234   GstClockTime packet_spacing;
235
236   /* the next expected seqnum we receive */
237   GstClockTime last_in_dts;
238   guint32 last_in_seqnum;
239   guint32 next_in_seqnum;
240
241   GArray *timers;
242
243   /* start and stop ranges */
244   GstClockTime npt_start;
245   GstClockTime npt_stop;
246   guint64 ext_timestamp;
247   guint64 last_elapsed;
248   guint64 estimated_eos;
249   GstClockID eos_id;
250
251   /* state */
252   gboolean eos;
253
254   /* clock rate and rtp timestamp offset */
255   gint last_pt;
256   gint32 clock_rate;
257   gint64 clock_base;
258   gint64 prev_ts_offset;
259
260   /* when we are shutting down */
261   GstFlowReturn srcresult;
262   gboolean blocked;
263
264   /* for sync */
265   GstSegment segment;
266   GstClockID clock_id;
267   GstClockTime timer_timeout;
268   guint16 timer_seqnum;
269   /* the latency of the upstream peer, we have to take this into account when
270    * synchronizing the buffers. */
271   GstClockTime peer_latency;
272   guint64 ext_rtptime;
273   GstBuffer *last_sr;
274
275   /* some accounting */
276   guint64 num_late;
277   guint64 num_duplicates;
278   guint64 num_rtx_requests;
279   guint64 num_rtx_success;
280   guint64 num_rtx_failed;
281   gdouble avg_rtx_num;
282   guint64 avg_rtx_rtt;
283 };
284
285 typedef enum
286 {
287   TIMER_TYPE_EXPECTED,
288   TIMER_TYPE_LOST,
289   TIMER_TYPE_DEADLINE,
290   TIMER_TYPE_EOS
291 } TimerType;
292
293 typedef struct
294 {
295   guint idx;
296   guint16 seqnum;
297   guint num;
298   TimerType type;
299   GstClockTime timeout;
300   GstClockTime duration;
301   GstClockTime rtx_base;
302   GstClockTime rtx_delay;
303   GstClockTime rtx_retry;
304   GstClockTime rtx_last;
305   guint num_rtx_retry;
306 } TimerData;
307
308 #define GST_RTP_JITTER_BUFFER_GET_PRIVATE(o) \
309   (G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_RTP_JITTER_BUFFER, \
310                                 GstRtpJitterBufferPrivate))
311
312 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_template =
313 GST_STATIC_PAD_TEMPLATE ("sink",
314     GST_PAD_SINK,
315     GST_PAD_ALWAYS,
316     GST_STATIC_CAPS ("application/x-rtp, "
317         "clock-rate = (int) [ 1, 2147483647 ]"
318         /* "payload = (int) , "
319          * "encoding-name = (string) "
320          */ )
321     );
322
323 static GstStaticPadTemplate gst_rtp_jitter_buffer_sink_rtcp_template =
324 GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
325     GST_PAD_SINK,
326     GST_PAD_REQUEST,
327     GST_STATIC_CAPS ("application/x-rtcp")
328     );
329
330 static GstStaticPadTemplate gst_rtp_jitter_buffer_src_template =
331 GST_STATIC_PAD_TEMPLATE ("src",
332     GST_PAD_SRC,
333     GST_PAD_ALWAYS,
334     GST_STATIC_CAPS ("application/x-rtp"
335         /* "payload = (int) , "
336          * "clock-rate = (int) , "
337          * "encoding-name = (string) "
338          */ )
339     );
340
341 static guint gst_rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 };
342
343 #define gst_rtp_jitter_buffer_parent_class parent_class
344 G_DEFINE_TYPE (GstRtpJitterBuffer, gst_rtp_jitter_buffer, GST_TYPE_ELEMENT);
345
346 /* object overrides */
347 static void gst_rtp_jitter_buffer_set_property (GObject * object,
348     guint prop_id, const GValue * value, GParamSpec * pspec);
349 static void gst_rtp_jitter_buffer_get_property (GObject * object,
350     guint prop_id, GValue * value, GParamSpec * pspec);
351 static void gst_rtp_jitter_buffer_finalize (GObject * object);
352
353 /* element overrides */
354 static GstStateChangeReturn gst_rtp_jitter_buffer_change_state (GstElement
355     * element, GstStateChange transition);
356 static GstPad *gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
357     GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
358 static void gst_rtp_jitter_buffer_release_pad (GstElement * element,
359     GstPad * pad);
360 static GstClock *gst_rtp_jitter_buffer_provide_clock (GstElement * element);
361
362 /* pad overrides */
363 static GstCaps *gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter);
364 static GstIterator *gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad,
365     GstObject * parent);
366
367 /* sinkpad overrides */
368 static gboolean gst_rtp_jitter_buffer_sink_event (GstPad * pad,
369     GstObject * parent, GstEvent * event);
370 static GstFlowReturn gst_rtp_jitter_buffer_chain (GstPad * pad,
371     GstObject * parent, GstBuffer * buffer);
372
373 static gboolean gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad,
374     GstObject * parent, GstEvent * event);
375 static GstFlowReturn gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad,
376     GstObject * parent, GstBuffer * buffer);
377
378 static gboolean gst_rtp_jitter_buffer_sink_query (GstPad * pad,
379     GstObject * parent, GstQuery * query);
380
381 /* srcpad overrides */
382 static gboolean gst_rtp_jitter_buffer_src_event (GstPad * pad,
383     GstObject * parent, GstEvent * event);
384 static gboolean gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad,
385     GstObject * parent, GstPadMode mode, gboolean active);
386 static void gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer);
387 static gboolean gst_rtp_jitter_buffer_src_query (GstPad * pad,
388     GstObject * parent, GstQuery * query);
389
390 static void
391 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer);
392 static GstClockTime
393 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jitterbuffer,
394     gboolean active, guint64 base_time);
395 static void do_handle_sync (GstRtpJitterBuffer * jitterbuffer);
396
397 static void unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer);
398 static void remove_all_timers (GstRtpJitterBuffer * jitterbuffer);
399
400 static void wait_next_timeout (GstRtpJitterBuffer * jitterbuffer);
401
402 static void
403 gst_rtp_jitter_buffer_class_init (GstRtpJitterBufferClass * klass)
404 {
405   GObjectClass *gobject_class;
406   GstElementClass *gstelement_class;
407
408   gobject_class = (GObjectClass *) klass;
409   gstelement_class = (GstElementClass *) klass;
410
411   g_type_class_add_private (klass, sizeof (GstRtpJitterBufferPrivate));
412
413   gobject_class->finalize = gst_rtp_jitter_buffer_finalize;
414
415   gobject_class->set_property = gst_rtp_jitter_buffer_set_property;
416   gobject_class->get_property = gst_rtp_jitter_buffer_get_property;
417
418   /**
419    * GstRtpJitterBuffer::latency:
420    *
421    * The maximum latency of the jitterbuffer. Packets will be kept in the buffer
422    * for at most this time.
423    */
424   g_object_class_install_property (gobject_class, PROP_LATENCY,
425       g_param_spec_uint ("latency", "Buffer latency in ms",
426           "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
427           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
428   /**
429    * GstRtpJitterBuffer::drop-on-latency:
430    *
431    * Drop oldest buffers when the queue is completely filled.
432    */
433   g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
434       g_param_spec_boolean ("drop-on-latency",
435           "Drop buffers when maximum latency is reached",
436           "Tells the jitterbuffer to never exceed the given latency in size",
437           DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
438   /**
439    * GstRtpJitterBuffer::ts-offset:
440    *
441    * Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
442    * This is mainly used to ensure interstream synchronisation.
443    */
444   g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
445       g_param_spec_int64 ("ts-offset", "Timestamp Offset",
446           "Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
447           G_MAXINT64, DEFAULT_TS_OFFSET,
448           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
449
450   /**
451    * GstRtpJitterBuffer::do-lost:
452    *
453    * Send out a GstRTPPacketLost event downstream when a packet is considered
454    * lost.
455    */
456   g_object_class_install_property (gobject_class, PROP_DO_LOST,
457       g_param_spec_boolean ("do-lost", "Do Lost",
458           "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
459           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
460
461   /**
462    * GstRtpJitterBuffer::mode:
463    *
464    * Control the buffering and timestamping mode used by the jitterbuffer.
465    */
466   g_object_class_install_property (gobject_class, PROP_MODE,
467       g_param_spec_enum ("mode", "Mode",
468           "Control the buffering algorithm in use", RTP_TYPE_JITTER_BUFFER_MODE,
469           DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
470   /**
471    * GstRtpJitterBuffer::percent:
472    *
473    * The percent of the jitterbuffer that is filled.
474    *
475    * Since: 0.10.19
476    */
477   g_object_class_install_property (gobject_class, PROP_PERCENT,
478       g_param_spec_int ("percent", "percent",
479           "The buffer filled percent", 0, 100,
480           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
481   /**
482    * GstRtpJitterBuffer::do-retransmission:
483    *
484    * Send out a GstRTPRetransmission event upstream when a packet is considered
485    * late and should be retransmitted.
486    *
487    * Since: 1.2
488    */
489   g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
490       g_param_spec_boolean ("do-retransmission", "Do Retransmission",
491           "Send retransmission events upstream when a packet is late",
492           DEFAULT_DO_RETRANSMISSION,
493           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
494
495   /**
496    * GstRtpJitterBuffer::rtx-delay:
497    *
498    * When a packet did not arrive at the expected time, wait this extra amount
499    * of time before sending a retransmission event.
500    *
501    * When -1 is used, the max jitter will be used as extra delay.
502    *
503    * Since: 1.2
504    */
505   g_object_class_install_property (gobject_class, PROP_RTX_DELAY,
506       g_param_spec_int ("rtx-delay", "RTX Delay",
507           "Extra time in ms to wait before sending retransmission "
508           "event (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DELAY,
509           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
510   /**
511    * GstRtpJitterBuffer::rtx-delay-reorder:
512    *
513    * Assume that a retransmission event should be sent when we see
514    * this much packet reordering.
515    *
516    * When -1 is used, the value will be estimated based on observed packet
517    * reordering.
518    *
519    * Since: 1.2
520    */
521   g_object_class_install_property (gobject_class, PROP_RTX_DELAY_REORDER,
522       g_param_spec_int ("rtx-delay-reorder", "RTX Delay Reorder",
523           "Sending retransmission event when this much reordering (-1 automatic)",
524           -1, G_MAXINT, DEFAULT_RTX_DELAY_REORDER,
525           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
526   /**
527    * GstRtpJitterBuffer::rtx-retry-timeout:
528    *
529    * When no packet has been received after sending a retransmission event
530    * for this time, retry sending a retransmission event.
531    *
532    * When -1 is used, the value will be estimated based on observed round
533    * trip time.
534    *
535    * Since: 1.2
536    */
537   g_object_class_install_property (gobject_class, PROP_RTX_RETRY_TIMEOUT,
538       g_param_spec_int ("rtx-retry-timeout", "RTX Retry Timeout",
539           "Retry sending a transmission event after this timeout in "
540           "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_TIMEOUT,
541           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
542   /**
543    * GstRtpJitterBuffer::rtx-retry-period:
544    *
545    * The amount of time to try to get a retransmission.
546    *
547    * When -1 is used, the value will be estimated based on the jitterbuffer
548    * latency and the observed round trip time.
549    *
550    * Since: 1.2
551    */
552   g_object_class_install_property (gobject_class, PROP_RTX_RETRY_PERIOD,
553       g_param_spec_int ("rtx-retry-period", "RTX Retry Period",
554           "Try to get a retransmission for this many ms "
555           "(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_PERIOD,
556           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
557
558   /**
559    * GstRtpJitterBuffer::request-pt-map:
560    * @buffer: the object which received the signal
561    * @pt: the pt
562    *
563    * Request the payload type as #GstCaps for @pt.
564    */
565   gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
566       g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
567       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
568           request_pt_map), NULL, NULL, g_cclosure_marshal_generic,
569       GST_TYPE_CAPS, 1, G_TYPE_UINT);
570   /**
571    * GstRtpJitterBuffer::handle-sync:
572    * @buffer: the object which received the signal
573    * @struct: a GstStructure containing sync values.
574    *
575    * Be notified of new sync values.
576    */
577   gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC] =
578       g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
579       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
580           handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
581       G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
582
583   /**
584    * GstRtpJitterBuffer::on-npt-stop
585    * @buffer: the object which received the signal
586    *
587    * Signal that the jitterbufer has pushed the RTP packet that corresponds to
588    * the npt-stop position.
589    */
590   gst_rtp_jitter_buffer_signals[SIGNAL_ON_NPT_STOP] =
591       g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
592       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstRtpJitterBufferClass,
593           on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
594       G_TYPE_NONE, 0, G_TYPE_NONE);
595
596   /**
597    * GstRtpJitterBuffer::clear-pt-map:
598    * @buffer: the object which received the signal
599    *
600    * Invalidate the clock-rate as obtained with the
601    * #GstRtpJitterBuffer::request-pt-map signal.
602    */
603   gst_rtp_jitter_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
604       g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
605       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
606       G_STRUCT_OFFSET (GstRtpJitterBufferClass, clear_pt_map), NULL, NULL,
607       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
608
609   /**
610    * GstRtpJitterBuffer::set-active:
611    * @buffer: the object which received the signal
612    *
613    * Start pushing out packets with the given base time. This signal is only
614    * useful in buffering mode.
615    *
616    * Returns: the time of the last pushed packet.
617    *
618    * Since: 0.10.19
619    */
620   gst_rtp_jitter_buffer_signals[SIGNAL_SET_ACTIVE] =
621       g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
622       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
623       G_STRUCT_OFFSET (GstRtpJitterBufferClass, set_active), NULL, NULL,
624       g_cclosure_marshal_generic, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
625       G_TYPE_UINT64);
626
627   gstelement_class->change_state =
628       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_change_state);
629   gstelement_class->request_new_pad =
630       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_request_new_pad);
631   gstelement_class->release_pad =
632       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_release_pad);
633   gstelement_class->provide_clock =
634       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_provide_clock);
635
636   gst_element_class_add_pad_template (gstelement_class,
637       gst_static_pad_template_get (&gst_rtp_jitter_buffer_src_template));
638   gst_element_class_add_pad_template (gstelement_class,
639       gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_template));
640   gst_element_class_add_pad_template (gstelement_class,
641       gst_static_pad_template_get (&gst_rtp_jitter_buffer_sink_rtcp_template));
642
643   gst_element_class_set_static_metadata (gstelement_class,
644       "RTP packet jitter-buffer", "Filter/Network/RTP",
645       "A buffer that deals with network jitter and other transmission faults",
646       "Philippe Kalaf <philippe.kalaf@collabora.co.uk>, "
647       "Wim Taymans <wim.taymans@gmail.com>");
648
649   klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_clear_pt_map);
650   klass->set_active = GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_set_active);
651
652   GST_DEBUG_CATEGORY_INIT
653       (rtpjitterbuffer_debug, "rtpjitterbuffer", 0, "RTP Jitter Buffer");
654 }
655
656 static void
657 gst_rtp_jitter_buffer_init (GstRtpJitterBuffer * jitterbuffer)
658 {
659   GstRtpJitterBufferPrivate *priv;
660
661   priv = GST_RTP_JITTER_BUFFER_GET_PRIVATE (jitterbuffer);
662   jitterbuffer->priv = priv;
663
664   priv->latency_ms = DEFAULT_LATENCY_MS;
665   priv->latency_ns = priv->latency_ms * GST_MSECOND;
666   priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
667   priv->do_lost = DEFAULT_DO_LOST;
668   priv->do_retransmission = DEFAULT_DO_RETRANSMISSION;
669   priv->rtx_delay = DEFAULT_RTX_DELAY;
670   priv->rtx_delay_reorder = DEFAULT_RTX_DELAY_REORDER;
671   priv->rtx_retry_timeout = DEFAULT_RTX_RETRY_TIMEOUT;
672   priv->rtx_retry_period = DEFAULT_RTX_RETRY_PERIOD;
673
674   priv->timers = g_array_new (FALSE, TRUE, sizeof (TimerData));
675   priv->jbuf = rtp_jitter_buffer_new ();
676   g_mutex_init (&priv->jbuf_lock);
677   g_cond_init (&priv->jbuf_timer);
678   g_cond_init (&priv->jbuf_event);
679
680   /* reset skew detection initialy */
681   rtp_jitter_buffer_reset_skew (priv->jbuf);
682   rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
683   rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
684   priv->active = TRUE;
685
686   priv->srcpad =
687       gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_src_template,
688       "src");
689
690   gst_pad_set_activatemode_function (priv->srcpad,
691       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_activate_mode));
692   gst_pad_set_query_function (priv->srcpad,
693       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_query));
694   gst_pad_set_event_function (priv->srcpad,
695       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_src_event));
696
697   priv->sinkpad =
698       gst_pad_new_from_static_template (&gst_rtp_jitter_buffer_sink_template,
699       "sink");
700
701   gst_pad_set_chain_function (priv->sinkpad,
702       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_chain));
703   gst_pad_set_event_function (priv->sinkpad,
704       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_event));
705   gst_pad_set_query_function (priv->sinkpad,
706       GST_DEBUG_FUNCPTR (gst_rtp_jitter_buffer_sink_query));
707
708   gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
709   gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
710
711   GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
712 }
713
714 #define ITEM_TYPE_BUFFER        0
715 #define ITEM_TYPE_LOST          1
716
717 static RTPJitterBufferItem *
718 alloc_item (gpointer data, guint type, GstClockTime dts, GstClockTime pts,
719     guint seqnum, guint count, guint rtptime)
720 {
721   RTPJitterBufferItem *item;
722
723   item = g_slice_new (RTPJitterBufferItem);
724   item->data = data;
725   item->next = NULL;
726   item->prev = NULL;
727   item->type = type;
728   item->dts = dts;
729   item->pts = pts;
730   item->seqnum = seqnum;
731   item->count = count;
732   item->rtptime = rtptime;
733
734   return item;
735 }
736
737 static void
738 free_item (RTPJitterBufferItem * item)
739 {
740   if (item->data)
741     gst_mini_object_unref (item->data);
742   g_slice_free (RTPJitterBufferItem, item);
743 }
744
745 static void
746 gst_rtp_jitter_buffer_finalize (GObject * object)
747 {
748   GstRtpJitterBuffer *jitterbuffer;
749   GstRtpJitterBufferPrivate *priv;
750
751   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
752   priv = jitterbuffer->priv;
753
754   g_array_free (priv->timers, TRUE);
755   g_mutex_clear (&priv->jbuf_lock);
756   g_cond_clear (&priv->jbuf_timer);
757   g_cond_clear (&priv->jbuf_event);
758
759   rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
760   g_object_unref (priv->jbuf);
761
762   G_OBJECT_CLASS (parent_class)->finalize (object);
763 }
764
765 static GstIterator *
766 gst_rtp_jitter_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
767 {
768   GstRtpJitterBuffer *jitterbuffer;
769   GstPad *otherpad = NULL;
770   GstIterator *it;
771   GValue val = { 0, };
772
773   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
774
775   if (pad == jitterbuffer->priv->sinkpad) {
776     otherpad = jitterbuffer->priv->srcpad;
777   } else if (pad == jitterbuffer->priv->srcpad) {
778     otherpad = jitterbuffer->priv->sinkpad;
779   } else if (pad == jitterbuffer->priv->rtcpsinkpad) {
780     otherpad = NULL;
781   }
782
783   g_value_init (&val, GST_TYPE_PAD);
784   g_value_set_object (&val, otherpad);
785   it = gst_iterator_new_single (GST_TYPE_PAD, &val);
786   g_value_unset (&val);
787
788   return it;
789 }
790
791 static GstPad *
792 create_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
793 {
794   GstRtpJitterBufferPrivate *priv;
795
796   priv = jitterbuffer->priv;
797
798   GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
799
800   priv->rtcpsinkpad =
801       gst_pad_new_from_static_template
802       (&gst_rtp_jitter_buffer_sink_rtcp_template, "sink_rtcp");
803   gst_pad_set_chain_function (priv->rtcpsinkpad,
804       gst_rtp_jitter_buffer_chain_rtcp);
805   gst_pad_set_event_function (priv->rtcpsinkpad,
806       (GstPadEventFunction) gst_rtp_jitter_buffer_sink_rtcp_event);
807   gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
808       gst_rtp_jitter_buffer_iterate_internal_links);
809   gst_pad_set_active (priv->rtcpsinkpad, TRUE);
810   gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
811
812   return priv->rtcpsinkpad;
813 }
814
815 static void
816 remove_rtcp_sink (GstRtpJitterBuffer * jitterbuffer)
817 {
818   GstRtpJitterBufferPrivate *priv;
819
820   priv = jitterbuffer->priv;
821
822   GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
823
824   gst_pad_set_active (priv->rtcpsinkpad, FALSE);
825
826   gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
827   priv->rtcpsinkpad = NULL;
828 }
829
830 static GstPad *
831 gst_rtp_jitter_buffer_request_new_pad (GstElement * element,
832     GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
833 {
834   GstRtpJitterBuffer *jitterbuffer;
835   GstElementClass *klass;
836   GstPad *result;
837   GstRtpJitterBufferPrivate *priv;
838
839   g_return_val_if_fail (templ != NULL, NULL);
840   g_return_val_if_fail (GST_IS_RTP_JITTER_BUFFER (element), NULL);
841
842   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
843   priv = jitterbuffer->priv;
844   klass = GST_ELEMENT_GET_CLASS (element);
845
846   GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
847
848   /* figure out the template */
849   if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
850     if (priv->rtcpsinkpad != NULL)
851       goto exists;
852
853     result = create_rtcp_sink (jitterbuffer);
854   } else
855     goto wrong_template;
856
857   return result;
858
859   /* ERRORS */
860 wrong_template:
861   {
862     g_warning ("rtpjitterbuffer: this is not our template");
863     return NULL;
864   }
865 exists:
866   {
867     g_warning ("rtpjitterbuffer: pad already requested");
868     return NULL;
869   }
870 }
871
872 static void
873 gst_rtp_jitter_buffer_release_pad (GstElement * element, GstPad * pad)
874 {
875   GstRtpJitterBuffer *jitterbuffer;
876   GstRtpJitterBufferPrivate *priv;
877
878   g_return_if_fail (GST_IS_RTP_JITTER_BUFFER (element));
879   g_return_if_fail (GST_IS_PAD (pad));
880
881   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
882   priv = jitterbuffer->priv;
883
884   GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
885
886   if (priv->rtcpsinkpad == pad) {
887     remove_rtcp_sink (jitterbuffer);
888   } else
889     goto wrong_pad;
890
891   return;
892
893   /* ERRORS */
894 wrong_pad:
895   {
896     g_warning ("gstjitterbuffer: asked to release an unknown pad");
897     return;
898   }
899 }
900
901 static GstClock *
902 gst_rtp_jitter_buffer_provide_clock (GstElement * element)
903 {
904   return gst_system_clock_obtain ();
905 }
906
907 static void
908 gst_rtp_jitter_buffer_clear_pt_map (GstRtpJitterBuffer * jitterbuffer)
909 {
910   GstRtpJitterBufferPrivate *priv;
911
912   priv = jitterbuffer->priv;
913
914   /* this will trigger a new pt-map request signal, FIXME, do something better. */
915
916   JBUF_LOCK (priv);
917   priv->clock_rate = -1;
918   /* do not clear current content, but refresh state for new arrival */
919   GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
920   rtp_jitter_buffer_reset_skew (priv->jbuf);
921   priv->last_popped_seqnum = -1;
922   priv->next_seqnum = -1;
923   JBUF_UNLOCK (priv);
924 }
925
926 static GstClockTime
927 gst_rtp_jitter_buffer_set_active (GstRtpJitterBuffer * jbuf, gboolean active,
928     guint64 offset)
929 {
930   GstRtpJitterBufferPrivate *priv;
931   GstClockTime last_out;
932   RTPJitterBufferItem *item;
933
934   priv = jbuf->priv;
935
936   JBUF_LOCK (priv);
937   GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
938       active, GST_TIME_ARGS (offset));
939
940   if (active != priv->active) {
941     /* add the amount of time spent in paused to the output offset. All
942      * outgoing buffers will have this offset applied to their timestamps in
943      * order to make them arrive in time in the sink. */
944     priv->out_offset = offset;
945     GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
946         GST_TIME_ARGS (priv->out_offset));
947     priv->active = active;
948     JBUF_SIGNAL_EVENT (priv);
949   }
950   if (!active) {
951     rtp_jitter_buffer_set_buffering (priv->jbuf, TRUE);
952   }
953   if ((item = rtp_jitter_buffer_peek (priv->jbuf))) {
954     /* head buffer timestamp and offset gives our output time */
955     last_out = item->dts + priv->ts_offset;
956   } else {
957     /* use last known time when the buffer is empty */
958     last_out = priv->last_out_time;
959   }
960   JBUF_UNLOCK (priv);
961
962   return last_out;
963 }
964
965 static GstCaps *
966 gst_rtp_jitter_buffer_getcaps (GstPad * pad, GstCaps * filter)
967 {
968   GstRtpJitterBuffer *jitterbuffer;
969   GstRtpJitterBufferPrivate *priv;
970   GstPad *other;
971   GstCaps *caps;
972   GstCaps *templ;
973
974   jitterbuffer = GST_RTP_JITTER_BUFFER (gst_pad_get_parent (pad));
975   priv = jitterbuffer->priv;
976
977   other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
978
979   caps = gst_pad_peer_query_caps (other, filter);
980
981   templ = gst_pad_get_pad_template_caps (pad);
982   if (caps == NULL) {
983     GST_DEBUG_OBJECT (jitterbuffer, "use template");
984     caps = templ;
985   } else {
986     GstCaps *intersect;
987
988     GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
989
990     intersect = gst_caps_intersect (caps, templ);
991     gst_caps_unref (caps);
992     gst_caps_unref (templ);
993
994     caps = intersect;
995   }
996   gst_object_unref (jitterbuffer);
997
998   return caps;
999 }
1000
1001 /*
1002  * Must be called with JBUF_LOCK held
1003  */
1004
1005 static gboolean
1006 gst_jitter_buffer_sink_parse_caps (GstRtpJitterBuffer * jitterbuffer,
1007     GstCaps * caps)
1008 {
1009   GstRtpJitterBufferPrivate *priv;
1010   GstStructure *caps_struct;
1011   guint val;
1012   GstClockTime tval;
1013
1014   priv = jitterbuffer->priv;
1015
1016   /* first parse the caps */
1017   caps_struct = gst_caps_get_structure (caps, 0);
1018
1019   GST_DEBUG_OBJECT (jitterbuffer, "got caps");
1020
1021   /* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
1022    * measure the amount of data in the buffer */
1023   if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
1024     goto error;
1025
1026   if (priv->clock_rate <= 0)
1027     goto wrong_rate;
1028
1029   GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
1030
1031   rtp_jitter_buffer_set_clock_rate (priv->jbuf, priv->clock_rate);
1032
1033   /* The clock base is the RTP timestamp corrsponding to the npt-start value. We
1034    * can use this to track the amount of time elapsed on the sender. */
1035   if (gst_structure_get_uint (caps_struct, "clock-base", &val))
1036     priv->clock_base = val;
1037   else
1038     priv->clock_base = -1;
1039
1040   priv->ext_timestamp = priv->clock_base;
1041
1042   GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
1043       priv->clock_base);
1044
1045   if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
1046     /* first expected seqnum, only update when we didn't have a previous base. */
1047     if (priv->next_in_seqnum == -1)
1048       priv->next_in_seqnum = val;
1049     if (priv->next_seqnum == -1)
1050       priv->next_seqnum = val;
1051   }
1052
1053   GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
1054
1055   /* the start and stop times. The seqnum-base corresponds to the start time. We
1056    * will keep track of the seqnums on the output and when we reach the one
1057    * corresponding to npt-stop, we emit the npt-stop-reached signal */
1058   if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
1059     priv->npt_start = tval;
1060   else
1061     priv->npt_start = 0;
1062
1063   if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
1064     priv->npt_stop = tval;
1065   else
1066     priv->npt_stop = -1;
1067
1068   GST_DEBUG_OBJECT (jitterbuffer,
1069       "npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1070       GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
1071
1072   return TRUE;
1073
1074   /* ERRORS */
1075 error:
1076   {
1077     GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
1078     return FALSE;
1079   }
1080 wrong_rate:
1081   {
1082     GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
1083     return FALSE;
1084   }
1085 }
1086
1087 static void
1088 gst_rtp_jitter_buffer_flush_start (GstRtpJitterBuffer * jitterbuffer)
1089 {
1090   GstRtpJitterBufferPrivate *priv;
1091
1092   priv = jitterbuffer->priv;
1093
1094   JBUF_LOCK (priv);
1095   /* mark ourselves as flushing */
1096   priv->srcresult = GST_FLOW_FLUSHING;
1097   GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
1098   /* this unblocks any waiting pops on the src pad task */
1099   JBUF_SIGNAL_EVENT (priv);
1100   JBUF_UNLOCK (priv);
1101 }
1102
1103 static void
1104 gst_rtp_jitter_buffer_flush_stop (GstRtpJitterBuffer * jitterbuffer)
1105 {
1106   GstRtpJitterBufferPrivate *priv;
1107
1108   priv = jitterbuffer->priv;
1109
1110   JBUF_LOCK (priv);
1111   GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
1112   /* Mark as non flushing */
1113   priv->srcresult = GST_FLOW_OK;
1114   gst_segment_init (&priv->segment, GST_FORMAT_TIME);
1115   priv->last_popped_seqnum = -1;
1116   priv->last_out_time = -1;
1117   priv->next_seqnum = -1;
1118   priv->ips_rtptime = -1;
1119   priv->ips_dts = GST_CLOCK_TIME_NONE;
1120   priv->packet_spacing = 0;
1121   priv->next_in_seqnum = -1;
1122   priv->clock_rate = -1;
1123   priv->eos = FALSE;
1124   priv->estimated_eos = -1;
1125   priv->last_elapsed = 0;
1126   priv->ext_timestamp = -1;
1127   GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
1128   rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
1129   rtp_jitter_buffer_reset_skew (priv->jbuf);
1130   remove_all_timers (jitterbuffer);
1131   JBUF_UNLOCK (priv);
1132 }
1133
1134 static gboolean
1135 gst_rtp_jitter_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
1136     GstPadMode mode, gboolean active)
1137 {
1138   gboolean result;
1139   GstRtpJitterBuffer *jitterbuffer = NULL;
1140
1141   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1142
1143   switch (mode) {
1144     case GST_PAD_MODE_PUSH:
1145       if (active) {
1146         /* allow data processing */
1147         gst_rtp_jitter_buffer_flush_stop (jitterbuffer);
1148
1149         /* start pushing out buffers */
1150         GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
1151         result = gst_pad_start_task (jitterbuffer->priv->srcpad,
1152             (GstTaskFunction) gst_rtp_jitter_buffer_loop, jitterbuffer, NULL);
1153       } else {
1154         /* make sure all data processing stops ASAP */
1155         gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1156
1157         /* NOTE this will hardlock if the state change is called from the src pad
1158          * task thread because we will _join() the thread. */
1159         GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
1160         result = gst_pad_stop_task (pad);
1161       }
1162       break;
1163     default:
1164       result = FALSE;
1165       break;
1166   }
1167   return result;
1168 }
1169
1170 static GstStateChangeReturn
1171 gst_rtp_jitter_buffer_change_state (GstElement * element,
1172     GstStateChange transition)
1173 {
1174   GstRtpJitterBuffer *jitterbuffer;
1175   GstRtpJitterBufferPrivate *priv;
1176   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1177
1178   jitterbuffer = GST_RTP_JITTER_BUFFER (element);
1179   priv = jitterbuffer->priv;
1180
1181   switch (transition) {
1182     case GST_STATE_CHANGE_NULL_TO_READY:
1183       break;
1184     case GST_STATE_CHANGE_READY_TO_PAUSED:
1185       JBUF_LOCK (priv);
1186       /* reset negotiated values */
1187       priv->clock_rate = -1;
1188       priv->clock_base = -1;
1189       priv->peer_latency = 0;
1190       priv->last_pt = -1;
1191       /* block until we go to PLAYING */
1192       priv->blocked = TRUE;
1193       priv->timer_running = TRUE;
1194       priv->timer_thread =
1195           g_thread_new ("timer", (GThreadFunc) wait_next_timeout, jitterbuffer);
1196       JBUF_UNLOCK (priv);
1197       break;
1198     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1199       JBUF_LOCK (priv);
1200       /* unblock to allow streaming in PLAYING */
1201       priv->blocked = FALSE;
1202       JBUF_SIGNAL_EVENT (priv);
1203       JBUF_SIGNAL_TIMER (priv);
1204       JBUF_UNLOCK (priv);
1205       break;
1206     default:
1207       break;
1208   }
1209
1210   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1211
1212   switch (transition) {
1213     case GST_STATE_CHANGE_READY_TO_PAUSED:
1214       /* we are a live element because we sync to the clock, which we can only
1215        * do in the PLAYING state */
1216       if (ret != GST_STATE_CHANGE_FAILURE)
1217         ret = GST_STATE_CHANGE_NO_PREROLL;
1218       break;
1219     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1220       JBUF_LOCK (priv);
1221       /* block to stop streaming when PAUSED */
1222       priv->blocked = TRUE;
1223       unschedule_current_timer (jitterbuffer);
1224       JBUF_UNLOCK (priv);
1225       if (ret != GST_STATE_CHANGE_FAILURE)
1226         ret = GST_STATE_CHANGE_NO_PREROLL;
1227       break;
1228     case GST_STATE_CHANGE_PAUSED_TO_READY:
1229       JBUF_LOCK (priv);
1230       gst_buffer_replace (&priv->last_sr, NULL);
1231       priv->timer_running = FALSE;
1232       unschedule_current_timer (jitterbuffer);
1233       JBUF_SIGNAL_TIMER (priv);
1234       JBUF_UNLOCK (priv);
1235       g_thread_join (priv->timer_thread);
1236       priv->timer_thread = NULL;
1237       break;
1238     case GST_STATE_CHANGE_READY_TO_NULL:
1239       break;
1240     default:
1241       break;
1242   }
1243
1244   return ret;
1245 }
1246
1247 static gboolean
1248 gst_rtp_jitter_buffer_src_event (GstPad * pad, GstObject * parent,
1249     GstEvent * event)
1250 {
1251   gboolean ret = TRUE;
1252   GstRtpJitterBuffer *jitterbuffer;
1253   GstRtpJitterBufferPrivate *priv;
1254
1255   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1256   priv = jitterbuffer->priv;
1257
1258   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1259
1260   switch (GST_EVENT_TYPE (event)) {
1261     case GST_EVENT_LATENCY:
1262     {
1263       GstClockTime latency;
1264
1265       gst_event_parse_latency (event, &latency);
1266
1267       GST_DEBUG_OBJECT (jitterbuffer,
1268           "configuring latency of %" GST_TIME_FORMAT, GST_TIME_ARGS (latency));
1269
1270       JBUF_LOCK (priv);
1271       /* adjust the overall buffer delay to the total pipeline latency in
1272        * buffering mode because if downstream consumes too fast (because of
1273        * large latency or queues, we would start rebuffering again. */
1274       if (rtp_jitter_buffer_get_mode (priv->jbuf) ==
1275           RTP_JITTER_BUFFER_MODE_BUFFER) {
1276         rtp_jitter_buffer_set_delay (priv->jbuf, latency);
1277       }
1278       JBUF_UNLOCK (priv);
1279
1280       ret = gst_pad_push_event (priv->sinkpad, event);
1281       break;
1282     }
1283     default:
1284       ret = gst_pad_push_event (priv->sinkpad, event);
1285       break;
1286   }
1287
1288   return ret;
1289 }
1290
1291 static gboolean
1292 gst_rtp_jitter_buffer_sink_event (GstPad * pad, GstObject * parent,
1293     GstEvent * event)
1294 {
1295   gboolean ret = TRUE;
1296   GstRtpJitterBuffer *jitterbuffer;
1297   GstRtpJitterBufferPrivate *priv;
1298
1299   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1300   priv = jitterbuffer->priv;
1301
1302   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1303
1304   switch (GST_EVENT_TYPE (event)) {
1305     case GST_EVENT_CAPS:
1306     {
1307       GstCaps *caps;
1308
1309       gst_event_parse_caps (event, &caps);
1310
1311       JBUF_LOCK (priv);
1312       ret = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1313       JBUF_UNLOCK (priv);
1314
1315       /* set same caps on srcpad on success */
1316       if (ret)
1317         ret = gst_pad_push_event (priv->srcpad, event);
1318       else
1319         gst_event_unref (event);
1320       break;
1321     }
1322     case GST_EVENT_SEGMENT:
1323     {
1324       gst_event_copy_segment (event, &priv->segment);
1325
1326       /* we need time for now */
1327       if (priv->segment.format != GST_FORMAT_TIME)
1328         goto newseg_wrong_format;
1329
1330       GST_DEBUG_OBJECT (jitterbuffer,
1331           "newsegment:  %" GST_SEGMENT_FORMAT, &priv->segment);
1332
1333       /* FIXME, push SEGMENT in the queue. Sorting order might be difficult. */
1334       ret = gst_pad_push_event (priv->srcpad, event);
1335       break;
1336     }
1337     case GST_EVENT_FLUSH_START:
1338       ret = gst_pad_push_event (priv->srcpad, event);
1339       gst_rtp_jitter_buffer_flush_start (jitterbuffer);
1340       /* wait for the loop to go into PAUSED */
1341       gst_pad_pause_task (priv->srcpad);
1342       break;
1343     case GST_EVENT_FLUSH_STOP:
1344       ret = gst_pad_push_event (priv->srcpad, event);
1345       ret =
1346           gst_rtp_jitter_buffer_src_activate_mode (priv->srcpad, parent,
1347           GST_PAD_MODE_PUSH, TRUE);
1348       break;
1349     case GST_EVENT_EOS:
1350     {
1351       /* push EOS in queue. We always push it at the head */
1352       JBUF_LOCK (priv);
1353       /* check for flushing, we need to discard the event and return FALSE when
1354        * we are flushing */
1355       ret = priv->srcresult == GST_FLOW_OK;
1356       if (ret && !priv->eos) {
1357         GST_INFO_OBJECT (jitterbuffer, "queuing EOS");
1358         priv->eos = TRUE;
1359         JBUF_SIGNAL_EVENT (priv);
1360       } else if (priv->eos) {
1361         GST_DEBUG_OBJECT (jitterbuffer, "dropping EOS, we are already EOS");
1362       } else {
1363         GST_DEBUG_OBJECT (jitterbuffer, "dropping EOS, reason %s",
1364             gst_flow_get_name (priv->srcresult));
1365       }
1366       JBUF_UNLOCK (priv);
1367       gst_event_unref (event);
1368       break;
1369     }
1370     default:
1371       ret = gst_pad_push_event (priv->srcpad, event);
1372       break;
1373   }
1374
1375 done:
1376
1377   return ret;
1378
1379   /* ERRORS */
1380 newseg_wrong_format:
1381   {
1382     GST_DEBUG_OBJECT (jitterbuffer, "received non TIME newsegment");
1383     ret = FALSE;
1384     gst_event_unref (event);
1385     goto done;
1386   }
1387 }
1388
1389 static gboolean
1390 gst_rtp_jitter_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
1391     GstEvent * event)
1392 {
1393   gboolean ret = TRUE;
1394   GstRtpJitterBuffer *jitterbuffer;
1395
1396   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1397
1398   GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
1399
1400   switch (GST_EVENT_TYPE (event)) {
1401     case GST_EVENT_FLUSH_START:
1402       gst_event_unref (event);
1403       break;
1404     case GST_EVENT_FLUSH_STOP:
1405       gst_event_unref (event);
1406       break;
1407     default:
1408       ret = gst_pad_event_default (pad, parent, event);
1409       break;
1410   }
1411
1412   return ret;
1413 }
1414
1415 /*
1416  * Must be called with JBUF_LOCK held, will release the LOCK when emiting the
1417  * signal. The function returns GST_FLOW_ERROR when a parsing error happened and
1418  * GST_FLOW_FLUSHING when the element is shutting down. On success
1419  * GST_FLOW_OK is returned.
1420  */
1421 static GstFlowReturn
1422 gst_rtp_jitter_buffer_get_clock_rate (GstRtpJitterBuffer * jitterbuffer,
1423     guint8 pt)
1424 {
1425   GValue ret = { 0 };
1426   GValue args[2] = { {0}, {0} };
1427   GstCaps *caps;
1428   gboolean res;
1429
1430   g_value_init (&args[0], GST_TYPE_ELEMENT);
1431   g_value_set_object (&args[0], jitterbuffer);
1432   g_value_init (&args[1], G_TYPE_UINT);
1433   g_value_set_uint (&args[1], pt);
1434
1435   g_value_init (&ret, GST_TYPE_CAPS);
1436   g_value_set_boxed (&ret, NULL);
1437
1438   JBUF_UNLOCK (jitterbuffer->priv);
1439   g_signal_emitv (args, gst_rtp_jitter_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
1440       &ret);
1441   JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
1442
1443   g_value_unset (&args[0]);
1444   g_value_unset (&args[1]);
1445   caps = (GstCaps *) g_value_dup_boxed (&ret);
1446   g_value_unset (&ret);
1447   if (!caps)
1448     goto no_caps;
1449
1450   res = gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1451   gst_caps_unref (caps);
1452
1453   if (G_UNLIKELY (!res))
1454     goto parse_failed;
1455
1456   return GST_FLOW_OK;
1457
1458   /* ERRORS */
1459 no_caps:
1460   {
1461     GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
1462     return GST_FLOW_ERROR;
1463   }
1464 out_flushing:
1465   {
1466     GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
1467     return GST_FLOW_FLUSHING;
1468   }
1469 parse_failed:
1470   {
1471     GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
1472     return GST_FLOW_ERROR;
1473   }
1474 }
1475
1476 /* call with jbuf lock held */
1477 static void
1478 check_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint * percent)
1479 {
1480   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1481
1482   /* too short a stream, or too close to EOS will never really fill buffer */
1483   if (*percent != -1 && priv->npt_stop != -1 &&
1484       priv->npt_stop - priv->npt_start <=
1485       rtp_jitter_buffer_get_delay (priv->jbuf)) {
1486     GST_DEBUG_OBJECT (jitterbuffer, "short stream; faking full buffer");
1487     rtp_jitter_buffer_set_buffering (priv->jbuf, FALSE);
1488     *percent = 100;
1489   }
1490 }
1491
1492 static void
1493 post_buffering_percent (GstRtpJitterBuffer * jitterbuffer, gint percent)
1494 {
1495   GstMessage *message;
1496
1497   /* Post a buffering message */
1498   message = gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
1499   gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
1500
1501   gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), message);
1502 }
1503
1504 static GstClockTime
1505 apply_offset (GstRtpJitterBuffer * jitterbuffer, GstClockTime timestamp)
1506 {
1507   GstRtpJitterBufferPrivate *priv;
1508
1509   priv = jitterbuffer->priv;
1510
1511   if (timestamp == -1)
1512     return -1;
1513
1514   /* apply the timestamp offset, this is used for inter stream sync */
1515   timestamp += priv->ts_offset;
1516   /* add the offset, this is used when buffering */
1517   timestamp += priv->out_offset;
1518
1519   return timestamp;
1520 }
1521
1522 static TimerData *
1523 find_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type, guint16 seqnum)
1524 {
1525   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1526   TimerData *timer = NULL;
1527   gint i, len;
1528
1529   len = priv->timers->len;
1530   for (i = 0; i < len; i++) {
1531     TimerData *test = &g_array_index (priv->timers, TimerData, i);
1532     if (test->seqnum == seqnum && test->type == type) {
1533       timer = test;
1534       break;
1535     }
1536   }
1537   return timer;
1538 }
1539
1540 static void
1541 unschedule_current_timer (GstRtpJitterBuffer * jitterbuffer)
1542 {
1543   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1544
1545   if (priv->clock_id) {
1546     GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
1547     gst_clock_id_unschedule (priv->clock_id);
1548     priv->clock_id = NULL;
1549   }
1550 }
1551
1552 static GstClockTime
1553 get_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1554 {
1555   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1556   GstClockTime test_timeout;
1557
1558   if ((test_timeout = timer->timeout) == -1)
1559     return -1;
1560
1561   if (timer->type != TIMER_TYPE_EXPECTED) {
1562     /* add our latency and offset to get output times. */
1563     test_timeout = apply_offset (jitterbuffer, test_timeout);
1564     test_timeout += priv->latency_ns;
1565   }
1566   return test_timeout;
1567 }
1568
1569 static void
1570 recalculate_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1571 {
1572   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1573
1574   if (priv->clock_id) {
1575     GstClockTime timeout = get_timeout (jitterbuffer, timer);
1576
1577     GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
1578         GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
1579
1580     if (timeout == -1 || timeout < priv->timer_timeout)
1581       unschedule_current_timer (jitterbuffer);
1582   }
1583 }
1584
1585 static TimerData *
1586 add_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1587     guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
1588     GstClockTime duration)
1589 {
1590   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1591   TimerData *timer;
1592   gint len;
1593
1594   GST_DEBUG_OBJECT (jitterbuffer,
1595       "add timer for seqnum %d to %" GST_TIME_FORMAT ", delay %"
1596       GST_TIME_FORMAT, seqnum, GST_TIME_ARGS (timeout), GST_TIME_ARGS (delay));
1597
1598   len = priv->timers->len;
1599   g_array_set_size (priv->timers, len + 1);
1600   timer = &g_array_index (priv->timers, TimerData, len);
1601   timer->idx = len;
1602   timer->type = type;
1603   timer->seqnum = seqnum;
1604   timer->num = num;
1605   timer->timeout = timeout + delay;
1606   timer->duration = duration;
1607   if (type == TIMER_TYPE_EXPECTED) {
1608     timer->rtx_base = timeout;
1609     timer->rtx_delay = delay;
1610     timer->rtx_retry = 0;
1611   }
1612   timer->num_rtx_retry = 0;
1613   recalculate_timer (jitterbuffer, timer);
1614   JBUF_SIGNAL_TIMER (priv);
1615
1616   return timer;
1617 }
1618
1619 static void
1620 reschedule_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
1621     guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
1622 {
1623   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1624   gboolean seqchange, timechange;
1625   guint16 oldseq;
1626
1627   seqchange = timer->seqnum != seqnum;
1628   timechange = timer->timeout != timeout;
1629
1630   if (!seqchange && !timechange)
1631     return;
1632
1633   oldseq = timer->seqnum;
1634
1635   GST_DEBUG_OBJECT (jitterbuffer,
1636       "replace timer for seqnum %d->%d to %" GST_TIME_FORMAT,
1637       oldseq, seqnum, GST_TIME_ARGS (timeout + delay));
1638
1639   timer->timeout = timeout + delay;
1640   timer->seqnum = seqnum;
1641   if (reset) {
1642     timer->rtx_base = timeout;
1643     timer->rtx_delay = delay;
1644     timer->rtx_retry = 0;
1645   }
1646
1647   if (priv->clock_id) {
1648     /* we changed the seqnum and there is a timer currently waiting with this
1649      * seqnum, unschedule it */
1650     if (seqchange && priv->timer_seqnum == oldseq)
1651       unschedule_current_timer (jitterbuffer);
1652     /* we changed the time, check if it is earlier than what we are waiting
1653      * for and unschedule if so */
1654     else if (timechange)
1655       recalculate_timer (jitterbuffer, timer);
1656   }
1657 }
1658
1659 static TimerData *
1660 set_timer (GstRtpJitterBuffer * jitterbuffer, TimerType type,
1661     guint16 seqnum, GstClockTime timeout)
1662 {
1663   TimerData *timer;
1664
1665   /* find the seqnum timer */
1666   timer = find_timer (jitterbuffer, type, seqnum);
1667   if (timer == NULL) {
1668     timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
1669   } else {
1670     reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
1671   }
1672   return timer;
1673 }
1674
1675 static void
1676 remove_timer (GstRtpJitterBuffer * jitterbuffer, TimerData * timer)
1677 {
1678   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1679   guint idx;
1680
1681   if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
1682     unschedule_current_timer (jitterbuffer);
1683
1684   idx = timer->idx;
1685   GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
1686   g_array_remove_index_fast (priv->timers, idx);
1687   timer->idx = idx;
1688 }
1689
1690 static void
1691 remove_all_timers (GstRtpJitterBuffer * jitterbuffer)
1692 {
1693   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1694   GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
1695   g_array_set_size (priv->timers, 0);
1696   unschedule_current_timer (jitterbuffer);
1697 }
1698
1699 /* we just received a packet with seqnum and dts.
1700  *
1701  * First check for old seqnum that we are still expecting. If the gap with the
1702  * current seqnum is too big, unschedule the timeouts.
1703  *
1704  * If we have a valid packet spacing estimate we can set a timer for when we
1705  * should receive the next packet.
1706  * If we don't have a valid estimate, we remove any timer we might have
1707  * had for this packet.
1708  */
1709 static void
1710 update_timers (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum,
1711     GstClockTime dts, gboolean do_next_seqnum)
1712 {
1713   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1714   TimerData *timer = NULL;
1715   gint i, len;
1716
1717   /* go through all timers and unschedule the ones with a large gap, also find
1718    * the timer for the seqnum */
1719   len = priv->timers->len;
1720   for (i = 0; i < len; i++) {
1721     TimerData *test = &g_array_index (priv->timers, TimerData, i);
1722     gint gap;
1723
1724     gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
1725
1726     GST_DEBUG_OBJECT (jitterbuffer, "%d, #%d<->#%d gap %d", i,
1727         test->seqnum, seqnum, gap);
1728
1729     if (gap == 0) {
1730       GST_DEBUG ("found timer for current seqnum");
1731       /* the timer for the current seqnum */
1732       timer = test;
1733     } else if (gap > priv->rtx_delay_reorder) {
1734       /* max gap, we exceeded the max reorder distance and we don't expect the
1735        * missing packet to be this reordered */
1736       if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
1737         reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
1738     }
1739   }
1740
1741   if (priv->packet_spacing > 0 && do_next_seqnum && priv->do_retransmission) {
1742     GstClockTime expected, delay;
1743
1744     /* calculate expected arrival time of the next seqnum */
1745     expected = dts + priv->packet_spacing;
1746     delay = priv->rtx_delay * GST_MSECOND;
1747
1748     /* and update/install timer for next seqnum */
1749     if (timer)
1750       reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
1751           delay, TRUE);
1752     else
1753       add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
1754           expected, delay, priv->packet_spacing);
1755   } else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
1756
1757     if (timer->num_rtx_retry > 0) {
1758       GstClockTime rtx_last;
1759
1760       /* we scheduled a retry for this packet and now we have it */
1761       priv->num_rtx_success++;
1762       /* all the previous retry attempts failed */
1763       priv->num_rtx_failed += timer->num_rtx_retry - 1;
1764       /* number of retries before receiving the packet */
1765       if (priv->avg_rtx_num == 0.0)
1766         priv->avg_rtx_num = timer->num_rtx_retry;
1767       else
1768         priv->avg_rtx_num = (timer->num_rtx_retry + 7 * priv->avg_rtx_num) / 8;
1769       /* calculate the delay between retransmission request and receiving this
1770        * packet, start with when we scheduled this timeout last */
1771       rtx_last = timer->rtx_last;
1772       if (dts > rtx_last) {
1773         GstClockTime delay;
1774         /* we have a valid delay if this packet arrived after we scheduled the
1775          * request */
1776         delay = dts - rtx_last;
1777         if (priv->avg_rtx_rtt == 0)
1778           priv->avg_rtx_rtt = delay;
1779         else
1780           priv->avg_rtx_rtt = (delay + 7 * priv->avg_rtx_rtt) / 8;
1781       }
1782       GST_LOG_OBJECT (jitterbuffer,
1783           "RTX success %" G_GUINT64_FORMAT ", failed %" G_GUINT64_FORMAT
1784           ", requests %" G_GUINT64_FORMAT ", dups %" G_GUINT64_FORMAT
1785           ", avg-num %g, avg-rtt %" G_GUINT64_FORMAT, priv->num_rtx_success,
1786           priv->num_rtx_failed, priv->num_rtx_requests, priv->num_duplicates,
1787           priv->avg_rtx_num, priv->avg_rtx_rtt);
1788     }
1789     /* if we had a timer, remove it, we don't know when to expect the next
1790      * packet. */
1791     remove_timer (jitterbuffer, timer);
1792     /* we signal the _loop function because this new packet could be the one
1793      * it was waiting for */
1794     JBUF_SIGNAL_EVENT (priv);
1795   }
1796 }
1797
1798 static void
1799 calculate_packet_spacing (GstRtpJitterBuffer * jitterbuffer, guint32 rtptime,
1800     GstClockTime dts)
1801 {
1802   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1803
1804   /* we need consecutive seqnums with a different
1805    * rtptime to estimate the packet spacing. */
1806   if (priv->ips_rtptime != rtptime) {
1807     /* rtptime changed, check dts diff */
1808     if (priv->ips_dts != -1 && dts != -1 && dts > priv->ips_dts) {
1809       priv->packet_spacing = dts - priv->ips_dts;
1810       GST_DEBUG_OBJECT (jitterbuffer,
1811           "new packet spacing %" GST_TIME_FORMAT,
1812           GST_TIME_ARGS (priv->packet_spacing));
1813     }
1814     priv->ips_rtptime = rtptime;
1815     priv->ips_dts = dts;
1816   }
1817 }
1818
1819 static void
1820 calculate_expected (GstRtpJitterBuffer * jitterbuffer, guint32 expected,
1821     guint16 seqnum, GstClockTime dts, gint gap)
1822 {
1823   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
1824   GstClockTime total_duration, duration, expected_dts;
1825   TimerType type;
1826
1827   GST_DEBUG_OBJECT (jitterbuffer,
1828       "dts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
1829       GST_TIME_ARGS (dts), GST_TIME_ARGS (priv->last_in_dts));
1830
1831   /* the total duration spanned by the missing packets */
1832   if (dts >= priv->last_in_dts)
1833     total_duration = dts - priv->last_in_dts;
1834   else
1835     total_duration = 0;
1836
1837   /* interpolate between the current time and the last time based on
1838    * number of packets we are missing, this is the estimated duration
1839    * for the missing packet based on equidistant packet spacing. */
1840   duration = total_duration / (gap + 1);
1841
1842   GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
1843       GST_TIME_ARGS (duration));
1844
1845   if (total_duration > priv->latency_ns) {
1846     GstClockTime gap_time;
1847     guint lost_packets;
1848
1849     gap_time = total_duration - priv->latency_ns;
1850
1851     if (duration > 0) {
1852       lost_packets = gap_time / duration;
1853       gap_time = lost_packets * duration;
1854     } else {
1855       lost_packets = gap;
1856     }
1857
1858     /* too many lost packets, some of the missing packets are already
1859      * too late and we can generate lost packet events for them. */
1860     GST_DEBUG_OBJECT (jitterbuffer, "too many lost packets %" GST_TIME_FORMAT
1861         " > %" GST_TIME_FORMAT ", consider %u lost",
1862         GST_TIME_ARGS (total_duration), GST_TIME_ARGS (priv->latency_ns),
1863         lost_packets);
1864
1865     /* this timer will fire immediately and the lost event will be pushed from
1866      * the timer thread */
1867     add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
1868         priv->last_in_dts + duration, 0, gap_time);
1869
1870     expected += lost_packets;
1871     priv->last_in_dts += gap_time;
1872   }
1873
1874   expected_dts = priv->last_in_dts + duration;
1875
1876   if (priv->do_retransmission) {
1877     TimerData *timer;
1878
1879     type = TIMER_TYPE_EXPECTED;
1880     /* if we had a timer for the first missing packet, update it. */
1881     if ((timer = find_timer (jitterbuffer, type, expected))) {
1882       GstClockTime timeout = timer->timeout;
1883
1884       timer->duration = duration;
1885       if (timeout > expected_dts) {
1886         GstClockTime delay = timeout - expected_dts - timer->rtx_retry;
1887         reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_dts,
1888             delay, TRUE);
1889       }
1890       expected++;
1891       expected_dts += duration;
1892     }
1893   } else {
1894     type = TIMER_TYPE_LOST;
1895   }
1896
1897   while (expected < seqnum) {
1898     add_timer (jitterbuffer, type, expected, 0, expected_dts, 0, duration);
1899     expected_dts += duration;
1900     expected++;
1901   }
1902 }
1903
1904 static GstFlowReturn
1905 gst_rtp_jitter_buffer_chain (GstPad * pad, GstObject * parent,
1906     GstBuffer * buffer)
1907 {
1908   GstRtpJitterBuffer *jitterbuffer;
1909   GstRtpJitterBufferPrivate *priv;
1910   guint16 seqnum;
1911   guint32 expected, rtptime;
1912   GstFlowReturn ret = GST_FLOW_OK;
1913   GstClockTime dts, pts;
1914   guint64 latency_ts;
1915   gboolean tail;
1916   gint percent = -1;
1917   guint8 pt;
1918   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
1919   gboolean do_next_seqnum = FALSE;
1920   RTPJitterBufferItem *item;
1921
1922   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
1923
1924   priv = jitterbuffer->priv;
1925
1926   if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
1927     goto invalid_buffer;
1928
1929   pt = gst_rtp_buffer_get_payload_type (&rtp);
1930   seqnum = gst_rtp_buffer_get_seq (&rtp);
1931   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
1932   gst_rtp_buffer_unmap (&rtp);
1933
1934   /* make sure we have PTS and DTS set */
1935   pts = GST_BUFFER_PTS (buffer);
1936   dts = GST_BUFFER_DTS (buffer);
1937   if (dts == -1)
1938     dts = pts;
1939   else if (pts == -1)
1940     pts = dts;
1941
1942   /* take the DTS of the buffer. This is the time when the packet was
1943    * received and is used to calculate jitter and clock skew. We will adjust
1944    * this DTS with the smoothed value after processing it in the
1945    * jitterbuffer and assign it as the PTS. */
1946   /* bring to running time */
1947   dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
1948
1949   GST_DEBUG_OBJECT (jitterbuffer,
1950       "Received packet #%d at time %" GST_TIME_FORMAT ", discont %d", seqnum,
1951       GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer));
1952
1953   JBUF_LOCK_CHECK (priv, out_flushing);
1954
1955   if (G_UNLIKELY (priv->last_pt != pt)) {
1956     GstCaps *caps;
1957
1958     GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
1959         pt);
1960
1961     priv->last_pt = pt;
1962     /* reset clock-rate so that we get a new one */
1963     priv->clock_rate = -1;
1964
1965     /* Try to get the clock-rate from the caps first if we can. If there are no
1966      * caps we must fire the signal to get the clock-rate. */
1967     if ((caps = gst_pad_get_current_caps (pad))) {
1968       gst_jitter_buffer_sink_parse_caps (jitterbuffer, caps);
1969       gst_caps_unref (caps);
1970     }
1971   }
1972
1973   if (G_UNLIKELY (priv->clock_rate == -1)) {
1974     /* no clock rate given on the caps, try to get one with the signal */
1975     if (gst_rtp_jitter_buffer_get_clock_rate (jitterbuffer,
1976             pt) == GST_FLOW_FLUSHING)
1977       goto out_flushing;
1978
1979     if (G_UNLIKELY (priv->clock_rate == -1))
1980       goto no_clock_rate;
1981   }
1982
1983   /* don't accept more data on EOS */
1984   if (G_UNLIKELY (priv->eos))
1985     goto have_eos;
1986
1987   expected = priv->next_in_seqnum;
1988
1989   /* now check against our expected seqnum */
1990   if (G_LIKELY (expected != -1)) {
1991     gint gap;
1992
1993     /* now calculate gap */
1994     gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
1995
1996     GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
1997         expected, seqnum, gap);
1998
1999     if (G_LIKELY (gap == 0)) {
2000       /* packet is expected */
2001       calculate_packet_spacing (jitterbuffer, rtptime, dts);
2002       do_next_seqnum = TRUE;
2003     } else {
2004       gboolean reset = FALSE;
2005
2006       if (gap < 0) {
2007         /* we received an old packet */
2008         if (G_UNLIKELY (gap < -RTP_MAX_MISORDER)) {
2009           /* too old packet, reset */
2010           GST_DEBUG_OBJECT (jitterbuffer, "reset: buffer too old %d < %d", gap,
2011               -RTP_MAX_MISORDER);
2012           reset = TRUE;
2013         } else {
2014           GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
2015         }
2016       } else {
2017         /* new packet, we are missing some packets */
2018         if (G_UNLIKELY (gap > RTP_MAX_DROPOUT)) {
2019           /* packet too far in future, reset */
2020           GST_DEBUG_OBJECT (jitterbuffer, "reset: buffer too new %d > %d", gap,
2021               RTP_MAX_DROPOUT);
2022           reset = TRUE;
2023         } else {
2024           GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
2025           /* fill in the gap with EXPECTED timers */
2026           calculate_expected (jitterbuffer, expected, seqnum, dts, gap);
2027
2028           do_next_seqnum = TRUE;
2029         }
2030       }
2031       if (G_UNLIKELY (reset)) {
2032         GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
2033         rtp_jitter_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
2034         rtp_jitter_buffer_reset_skew (priv->jbuf);
2035         remove_all_timers (jitterbuffer);
2036         priv->last_popped_seqnum = -1;
2037         priv->next_seqnum = seqnum;
2038         do_next_seqnum = TRUE;
2039       }
2040       /* reset spacing estimation when gap */
2041       priv->ips_rtptime = -1;
2042       priv->ips_dts = GST_CLOCK_TIME_NONE;
2043     }
2044   } else {
2045     GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2046     /* we don't know what the next_in_seqnum should be, wait for the last
2047      * possible moment to push this buffer, maybe we get an earlier seqnum
2048      * while we wait */
2049     set_timer (jitterbuffer, TIMER_TYPE_DEADLINE, seqnum, dts);
2050     do_next_seqnum = TRUE;
2051     /* take rtptime and dts to calculate packet spacing */
2052     priv->ips_rtptime = rtptime;
2053     priv->ips_dts = dts;
2054   }
2055   if (do_next_seqnum) {
2056     priv->last_in_seqnum = seqnum;
2057     priv->last_in_dts = dts;
2058     priv->next_in_seqnum = (seqnum + 1) & 0xffff;
2059   }
2060
2061   /* let's check if this buffer is too late, we can only accept packets with
2062    * bigger seqnum than the one we last pushed. */
2063   if (G_LIKELY (priv->last_popped_seqnum != -1)) {
2064     gint gap;
2065
2066     gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
2067
2068     /* priv->last_popped_seqnum >= seqnum, we're too late. */
2069     if (G_UNLIKELY (gap <= 0))
2070       goto too_late;
2071   }
2072
2073   /* let's drop oldest packet if the queue is already full and drop-on-latency
2074    * is set. We can only do this when there actually is a latency. When no
2075    * latency is set, we just pump it in the queue and let the other end push it
2076    * out as fast as possible. */
2077   if (priv->latency_ms && priv->drop_on_latency) {
2078     latency_ts =
2079         gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
2080
2081     if (G_UNLIKELY (rtp_jitter_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
2082       RTPJitterBufferItem *old_item;
2083
2084       old_item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2085       GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
2086           old_item);
2087       free_item (old_item);
2088     }
2089   }
2090
2091   item = alloc_item (buffer, ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime);
2092
2093   /* now insert the packet into the queue in sorted order. This function returns
2094    * FALSE if a packet with the same seqnum was already in the queue, meaning we
2095    * have a duplicate. */
2096   if (G_UNLIKELY (!rtp_jitter_buffer_insert (priv->jbuf, item,
2097               &tail, &percent)))
2098     goto duplicate;
2099
2100   /* update timers */
2101   update_timers (jitterbuffer, seqnum, dts, do_next_seqnum);
2102
2103   /* we had an unhandled SR, handle it now */
2104   if (priv->last_sr)
2105     do_handle_sync (jitterbuffer);
2106
2107   /* signal addition of new buffer when the _loop is waiting. */
2108   if (priv->active && priv->waiting_timer)
2109     JBUF_SIGNAL_EVENT (priv);
2110
2111   /* let's unschedule and unblock any waiting buffers. We only want to do this
2112    * when the tail buffer changed */
2113   if (G_UNLIKELY (priv->clock_id && tail)) {
2114     GST_DEBUG_OBJECT (jitterbuffer, "Unscheduling waiting new buffer");
2115     unschedule_current_timer (jitterbuffer);
2116   }
2117
2118   GST_DEBUG_OBJECT (jitterbuffer, "Pushed packet #%d, now %d packets, tail: %d",
2119       seqnum, rtp_jitter_buffer_num_packets (priv->jbuf), tail);
2120
2121   check_buffering_percent (jitterbuffer, &percent);
2122
2123 finished:
2124   JBUF_UNLOCK (priv);
2125
2126   if (percent != -1)
2127     post_buffering_percent (jitterbuffer, percent);
2128
2129   return ret;
2130
2131   /* ERRORS */
2132 invalid_buffer:
2133   {
2134     /* this is not fatal but should be filtered earlier */
2135     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2136         ("Received invalid RTP payload, dropping"));
2137     gst_buffer_unref (buffer);
2138     return GST_FLOW_OK;
2139   }
2140 no_clock_rate:
2141   {
2142     GST_WARNING_OBJECT (jitterbuffer,
2143         "No clock-rate in caps!, dropping buffer");
2144     gst_buffer_unref (buffer);
2145     goto finished;
2146   }
2147 out_flushing:
2148   {
2149     ret = priv->srcresult;
2150     GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
2151     gst_buffer_unref (buffer);
2152     goto finished;
2153   }
2154 have_eos:
2155   {
2156     ret = GST_FLOW_EOS;
2157     GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
2158     gst_buffer_unref (buffer);
2159     goto finished;
2160   }
2161 too_late:
2162   {
2163     GST_WARNING_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
2164         " popped, dropping", seqnum, priv->last_popped_seqnum);
2165     priv->num_late++;
2166     gst_buffer_unref (buffer);
2167     goto finished;
2168   }
2169 duplicate:
2170   {
2171     GST_WARNING_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
2172         seqnum);
2173     priv->num_duplicates++;
2174     free_item (item);
2175     goto finished;
2176   }
2177 }
2178
2179 static GstClockTime
2180 compute_elapsed (GstRtpJitterBuffer * jitterbuffer, RTPJitterBufferItem * item)
2181 {
2182   guint64 ext_time, elapsed;
2183   guint32 rtp_time;
2184   GstRtpJitterBufferPrivate *priv;
2185
2186   priv = jitterbuffer->priv;
2187   rtp_time = item->rtptime;
2188
2189   GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
2190       G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
2191
2192   if (rtp_time < priv->ext_timestamp) {
2193     ext_time = priv->ext_timestamp;
2194   } else {
2195     ext_time = gst_rtp_buffer_ext_timestamp (&priv->ext_timestamp, rtp_time);
2196   }
2197
2198   if (ext_time > priv->clock_base)
2199     elapsed = ext_time - priv->clock_base;
2200   else
2201     elapsed = 0;
2202
2203   elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
2204   return elapsed;
2205 }
2206
2207 static void
2208 update_estimated_eos (GstRtpJitterBuffer * jitterbuffer,
2209     RTPJitterBufferItem * item)
2210 {
2211   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2212
2213   if (priv->npt_stop != -1 && priv->ext_timestamp != -1
2214       && priv->clock_base != -1 && priv->clock_rate > 0) {
2215     guint64 elapsed, estimated;
2216
2217     elapsed = compute_elapsed (jitterbuffer, item);
2218
2219     if (elapsed > priv->last_elapsed || !priv->last_elapsed) {
2220       guint64 left;
2221       GstClockTime out_time;
2222
2223       priv->last_elapsed = elapsed;
2224
2225       left = priv->npt_stop - priv->npt_start;
2226       GST_LOG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT,
2227           GST_TIME_ARGS (left));
2228
2229       out_time = item->dts;
2230
2231       if (elapsed > 0)
2232         estimated = gst_util_uint64_scale (out_time, left, elapsed);
2233       else {
2234         /* if there is almost nothing left,
2235          * we may never advance enough to end up in the above case */
2236         if (left < GST_SECOND)
2237           estimated = GST_SECOND;
2238         else
2239           estimated = -1;
2240       }
2241
2242       GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
2243           GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
2244
2245       if (estimated != -1 && priv->estimated_eos != estimated) {
2246         set_timer (jitterbuffer, TIMER_TYPE_EOS, -1, estimated);
2247         priv->estimated_eos = estimated;
2248       }
2249     }
2250   }
2251 }
2252
2253 /* take a buffer from the queue and push it */
2254 static GstFlowReturn
2255 pop_and_push_next (GstRtpJitterBuffer * jitterbuffer, guint16 seqnum)
2256 {
2257   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2258   GstFlowReturn result;
2259   RTPJitterBufferItem *item;
2260   GstBuffer *outbuf;
2261   GstEvent *outevent;
2262   GstClockTime dts, pts;
2263   gint percent = -1;
2264   gboolean is_buffer, do_push = TRUE;
2265
2266   /* when we get here we are ready to pop and push the buffer */
2267   item = rtp_jitter_buffer_pop (priv->jbuf, &percent);
2268
2269   is_buffer = GST_IS_BUFFER (item->data);
2270
2271   if (is_buffer) {
2272     check_buffering_percent (jitterbuffer, &percent);
2273
2274     /* we need to make writable to change the flags and timestamps */
2275     outbuf = gst_buffer_make_writable (item->data);
2276
2277     if (G_UNLIKELY (priv->discont)) {
2278       /* set DISCONT flag when we missed a packet. We pushed the buffer writable
2279        * into the jitterbuffer so we can modify now. */
2280       GST_DEBUG_OBJECT (jitterbuffer, "mark output buffer discont");
2281       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
2282       priv->discont = FALSE;
2283     }
2284     if (G_UNLIKELY (priv->ts_discont)) {
2285       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
2286       priv->ts_discont = FALSE;
2287     }
2288
2289     dts = gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->dts);
2290     pts = gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->pts);
2291
2292     /* apply timestamp with offset to buffer now */
2293     GST_BUFFER_DTS (outbuf) = apply_offset (jitterbuffer, dts);
2294     GST_BUFFER_PTS (outbuf) = apply_offset (jitterbuffer, pts);
2295
2296     /* update the elapsed time when we need to check against the npt stop time. */
2297     update_estimated_eos (jitterbuffer, item);
2298
2299     priv->last_out_time = GST_BUFFER_PTS (outbuf);
2300   } else {
2301     outevent = item->data;
2302     if (item->type == ITEM_TYPE_LOST) {
2303       priv->discont = TRUE;
2304       if (!priv->do_lost)
2305         do_push = FALSE;
2306     }
2307   }
2308
2309   /* now we are ready to push the buffer. Save the seqnum and release the lock
2310    * so the other end can push stuff in the queue again. */
2311   priv->last_popped_seqnum = seqnum;
2312   priv->next_seqnum = (seqnum + item->count) & 0xffff;
2313   JBUF_UNLOCK (priv);
2314
2315   item->data = NULL;
2316   free_item (item);
2317
2318   if (is_buffer) {
2319     /* push buffer */
2320     if (percent != -1)
2321       post_buffering_percent (jitterbuffer, percent);
2322
2323     GST_DEBUG_OBJECT (jitterbuffer,
2324         "Pushing buffer %d, dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2325         seqnum, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
2326         GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
2327     result = gst_pad_push (priv->srcpad, outbuf);
2328   } else {
2329     GST_DEBUG_OBJECT (jitterbuffer, "Pushing event %d", seqnum);
2330
2331     if (do_push)
2332       gst_pad_push_event (priv->srcpad, outevent);
2333     else
2334       gst_event_unref (outevent);
2335
2336     result = GST_FLOW_OK;
2337   }
2338   JBUF_LOCK_CHECK (priv, out_flushing);
2339
2340   return result;
2341
2342   /* ERRORS */
2343 out_flushing:
2344   {
2345     return priv->srcresult;
2346   }
2347 }
2348
2349 #define GST_FLOW_WAIT GST_FLOW_CUSTOM_SUCCESS
2350
2351 /* Peek a buffer and compare the seqnum to the expected seqnum.
2352  * If all is fine, the buffer is pushed.
2353  * If something is wrong, we wait for some event
2354  */
2355 static GstFlowReturn
2356 handle_next_buffer (GstRtpJitterBuffer * jitterbuffer)
2357 {
2358   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2359   GstFlowReturn result = GST_FLOW_OK;
2360   RTPJitterBufferItem *item;
2361   guint16 seqnum;
2362   guint32 next_seqnum;
2363   gint gap;
2364
2365   /* only push buffers when PLAYING and active and not buffering */
2366   if (priv->blocked || !priv->active ||
2367       rtp_jitter_buffer_is_buffering (priv->jbuf))
2368     return GST_FLOW_WAIT;
2369
2370 again:
2371   /* peek a buffer, we're just looking at the sequence number.
2372    * If all is fine, we'll pop and push it. If the sequence number is wrong we
2373    * wait for a timeout or something to change.
2374    * The peeked buffer is valid for as long as we hold the jitterbuffer lock. */
2375   item = rtp_jitter_buffer_peek (priv->jbuf);
2376   if (item == NULL)
2377     goto wait;
2378
2379   /* get the seqnum and the next expected seqnum */
2380   seqnum = item->seqnum;
2381
2382   next_seqnum = priv->next_seqnum;
2383
2384   /* get the gap between this and the previous packet. If we don't know the
2385    * previous packet seqnum assume no gap. */
2386   if (G_UNLIKELY (next_seqnum == -1)) {
2387     GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
2388     /* we don't know what the next_seqnum should be, the chain function should
2389      * have scheduled a DEADLINE timer that will increment next_seqnum when it
2390      * fires, so wait for that */
2391     result = GST_FLOW_WAIT;
2392   } else {
2393     /* else calculate GAP */
2394     gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
2395
2396     if (G_LIKELY (gap == 0)) {
2397       /* no missing packet, pop and push */
2398       result = pop_and_push_next (jitterbuffer, seqnum);
2399     } else if (G_UNLIKELY (gap < 0)) {
2400       RTPJitterBufferItem *item;
2401       /* if we have a packet that we already pushed or considered dropped, pop it
2402        * off and get the next packet */
2403       GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
2404           seqnum, next_seqnum);
2405       item = rtp_jitter_buffer_pop (priv->jbuf, NULL);
2406       free_item (item);
2407       goto again;
2408     } else {
2409       /* the chain function has scheduled timers to request retransmission or
2410        * when to consider the packet lost, wait for that */
2411       GST_DEBUG_OBJECT (jitterbuffer,
2412           "Sequence number GAP detected: expected %d instead of %d (%d missing)",
2413           next_seqnum, seqnum, gap);
2414       result = GST_FLOW_WAIT;
2415     }
2416   }
2417   return result;
2418
2419 wait:
2420   {
2421     GST_DEBUG_OBJECT (jitterbuffer, "no buffer, going to wait");
2422     if (priv->eos)
2423       result = GST_FLOW_EOS;
2424     else
2425       result = GST_FLOW_WAIT;
2426     return result;
2427   }
2428 }
2429
2430 /* the timeout for when we expected a packet expired */
2431 static gboolean
2432 do_expected_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
2433     GstClockTime now)
2434 {
2435   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2436   GstEvent *event;
2437   guint delay;
2438
2439   GST_DEBUG_OBJECT (jitterbuffer, "expected %d didn't arrive", timer->seqnum);
2440
2441   delay = timer->rtx_delay + timer->rtx_retry;
2442   event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
2443       gst_structure_new ("GstRTPRetransmissionRequest",
2444           "seqnum", G_TYPE_UINT, (guint) timer->seqnum,
2445           "running-time", G_TYPE_UINT64, timer->rtx_base,
2446           "delay", G_TYPE_UINT, GST_TIME_AS_MSECONDS (delay),
2447           "retry", G_TYPE_UINT, timer->num_rtx_retry,
2448           "frequency", G_TYPE_UINT, priv->rtx_retry_timeout,
2449           "period", G_TYPE_UINT, priv->rtx_retry_period,
2450           "deadline", G_TYPE_UINT, priv->latency_ms,
2451           "packet-spacing", G_TYPE_UINT64, priv->packet_spacing, NULL));
2452
2453   priv->num_rtx_requests++;
2454   timer->num_rtx_retry++;
2455   timer->rtx_last = now;
2456
2457   /* calculate the timeout for the next retransmission attempt */
2458   timer->rtx_retry += (priv->rtx_retry_timeout * GST_MSECOND);
2459   GST_DEBUG_OBJECT (jitterbuffer, "base %" GST_TIME_FORMAT ", delay %"
2460       GST_TIME_FORMAT ", retry %" GST_TIME_FORMAT,
2461       GST_TIME_ARGS (timer->rtx_base), GST_TIME_ARGS (timer->rtx_delay),
2462       GST_TIME_ARGS (timer->rtx_retry));
2463
2464   if (timer->rtx_retry + timer->rtx_delay >
2465       (priv->rtx_retry_period * GST_MSECOND)) {
2466     GST_DEBUG_OBJECT (jitterbuffer, "reschedule as LOST timer");
2467     /* too many retransmission request, we now convert the timer
2468      * to a lost timer, leave the num_rtx_retry as it is for stats */
2469     timer->type = TIMER_TYPE_LOST;
2470     timer->rtx_delay = 0;
2471     timer->rtx_retry = 0;
2472   }
2473   reschedule_timer (jitterbuffer, timer, timer->seqnum,
2474       timer->rtx_base + timer->rtx_retry, timer->rtx_delay, FALSE);
2475
2476   JBUF_UNLOCK (priv);
2477   gst_pad_push_event (priv->sinkpad, event);
2478   JBUF_LOCK (priv);
2479
2480   return FALSE;
2481 }
2482
2483 /* a packet is lost */
2484 static gboolean
2485 do_lost_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
2486     GstClockTime now)
2487 {
2488   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2489   GstClockTime duration, timestamp;
2490   guint seqnum, lost_packets, num_rtx_retry;
2491   gboolean late;
2492   GstEvent *event;
2493   RTPJitterBufferItem *item;
2494
2495   seqnum = timer->seqnum;
2496   timestamp = apply_offset (jitterbuffer, timer->timeout);
2497   duration = timer->duration;
2498   if (duration == GST_CLOCK_TIME_NONE && priv->packet_spacing > 0)
2499     duration = priv->packet_spacing;
2500   lost_packets = MAX (timer->num, 1);
2501   late = timer->num > 0;
2502   num_rtx_retry = timer->num_rtx_retry;
2503
2504   /* we had a gap and thus we lost some packets. Create an event for this.  */
2505   if (lost_packets > 1)
2506     GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", seqnum,
2507         seqnum + lost_packets - 1);
2508   else
2509     GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", seqnum);
2510
2511   priv->num_late += lost_packets;
2512   priv->num_rtx_failed += num_rtx_retry;
2513
2514   /* create paket lost event */
2515   event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
2516       gst_structure_new ("GstRTPPacketLost",
2517           "seqnum", G_TYPE_UINT, (guint) seqnum,
2518           "timestamp", G_TYPE_UINT64, timestamp,
2519           "duration", G_TYPE_UINT64, duration,
2520           "late", G_TYPE_BOOLEAN, late,
2521           "retry", G_TYPE_UINT, num_rtx_retry, NULL));
2522
2523   item = alloc_item (event, ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1);
2524   rtp_jitter_buffer_insert (priv->jbuf, item, NULL, NULL);
2525
2526   /* remove timer now */
2527   remove_timer (jitterbuffer, timer);
2528   JBUF_SIGNAL_EVENT (priv);
2529
2530   return TRUE;
2531 }
2532
2533 static gboolean
2534 do_eos_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
2535     GstClockTime now)
2536 {
2537   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2538
2539   GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
2540   remove_timer (jitterbuffer, timer);
2541   JBUF_SIGNAL_EVENT (priv);
2542
2543   return TRUE;
2544 }
2545
2546 static gboolean
2547 do_deadline_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
2548     GstClockTime now)
2549 {
2550   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2551
2552   GST_INFO_OBJECT (jitterbuffer, "got deadline timeout");
2553
2554   priv->next_seqnum = timer->seqnum;
2555   remove_timer (jitterbuffer, timer);
2556   JBUF_SIGNAL_EVENT (priv);
2557
2558   return TRUE;
2559 }
2560
2561 static gboolean
2562 do_timeout (GstRtpJitterBuffer * jitterbuffer, TimerData * timer,
2563     GstClockTime now)
2564 {
2565   gboolean removed = FALSE;
2566
2567   switch (timer->type) {
2568     case TIMER_TYPE_EXPECTED:
2569       removed = do_expected_timeout (jitterbuffer, timer, now);
2570       break;
2571     case TIMER_TYPE_LOST:
2572       removed = do_lost_timeout (jitterbuffer, timer, now);
2573       break;
2574     case TIMER_TYPE_DEADLINE:
2575       removed = do_deadline_timeout (jitterbuffer, timer, now);
2576       break;
2577     case TIMER_TYPE_EOS:
2578       removed = do_eos_timeout (jitterbuffer, timer, now);
2579       break;
2580   }
2581   return removed;
2582 }
2583
2584 /* called when we need to wait for the next timeout.
2585  *
2586  * We loop over the array of recorded timeouts and wait for the earliest one.
2587  * When it timed out, do the logic associated with the timer.
2588  *
2589  * If there are no timers, we wait on a gcond until something new happens.
2590  */
2591 static void
2592 wait_next_timeout (GstRtpJitterBuffer * jitterbuffer)
2593 {
2594   GstRtpJitterBufferPrivate *priv = jitterbuffer->priv;
2595   GstClockTime now = 0;
2596
2597   JBUF_LOCK (priv);
2598   while (priv->timer_running) {
2599     TimerData *timer = NULL;
2600     GstClockTime timer_timeout = -1;
2601     gint i, len;
2602
2603     GST_DEBUG_OBJECT (jitterbuffer, "now %" GST_TIME_FORMAT,
2604         GST_TIME_ARGS (now));
2605
2606     len = priv->timers->len;
2607     for (i = 0; i < len; i++) {
2608       TimerData *test = &g_array_index (priv->timers, TimerData, i);
2609       GstClockTime test_timeout = get_timeout (jitterbuffer, test);
2610       gboolean save_best = FALSE;
2611
2612       GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, %d, %" GST_TIME_FORMAT,
2613           i, test->type, test->seqnum, GST_TIME_ARGS (test_timeout));
2614
2615       /* find the smallest timeout */
2616       if (timer == NULL) {
2617         save_best = TRUE;
2618       } else if (timer_timeout == -1) {
2619         /* we already have an immediate timeout, the new timer must be an
2620          * immediate timer with smaller seqnum to become the best */
2621         if (test_timeout == -1 && test->seqnum < timer->seqnum)
2622           save_best = TRUE;
2623       } else if (test_timeout == -1) {
2624         /* first immediate timer */
2625         save_best = TRUE;
2626       } else if (test_timeout < timer_timeout) {
2627         /* earlier timer */
2628         save_best = TRUE;
2629       } else if (test_timeout == timer_timeout && test->seqnum < timer->seqnum) {
2630         /* same timer, smaller seqnum */
2631         save_best = TRUE;
2632       }
2633       if (save_best) {
2634         GST_DEBUG_OBJECT (jitterbuffer, "new best %d", i);
2635         timer = test;
2636         timer_timeout = test_timeout;
2637       }
2638     }
2639     if (timer && !priv->blocked) {
2640       GstClock *clock;
2641       GstClockTime sync_time;
2642       GstClockID id;
2643       GstClockReturn ret;
2644       GstClockTimeDiff clock_jitter;
2645
2646       if (timer_timeout == -1 || timer_timeout <= now) {
2647         do_timeout (jitterbuffer, timer, now);
2648         /* check here, do_timeout could have released the lock */
2649         if (!priv->timer_running)
2650           break;
2651         continue;
2652       }
2653
2654       GST_OBJECT_LOCK (jitterbuffer);
2655       clock = GST_ELEMENT_CLOCK (jitterbuffer);
2656       if (!clock) {
2657         GST_OBJECT_UNLOCK (jitterbuffer);
2658         /* let's just push if there is no clock */
2659         GST_DEBUG_OBJECT (jitterbuffer, "No clock, timeout right away");
2660         now = timer_timeout;
2661         continue;
2662       }
2663
2664       /* prepare for sync against clock */
2665       sync_time = timer_timeout + GST_ELEMENT_CAST (jitterbuffer)->base_time;
2666       /* add latency of peer to get input time */
2667       sync_time += priv->peer_latency;
2668
2669       GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
2670           " with sync time %" GST_TIME_FORMAT,
2671           GST_TIME_ARGS (timer_timeout), GST_TIME_ARGS (sync_time));
2672
2673       /* create an entry for the clock */
2674       id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
2675       priv->timer_timeout = timer_timeout;
2676       priv->timer_seqnum = timer->seqnum;
2677       GST_OBJECT_UNLOCK (jitterbuffer);
2678
2679       /* release the lock so that the other end can push stuff or unlock */
2680       JBUF_UNLOCK (priv);
2681
2682       ret = gst_clock_id_wait (id, &clock_jitter);
2683
2684       JBUF_LOCK (priv);
2685       if (!priv->timer_running)
2686         break;
2687
2688       if (ret != GST_CLOCK_UNSCHEDULED) {
2689         now = timer_timeout + MAX (clock_jitter, 0);
2690         GST_DEBUG_OBJECT (jitterbuffer, "sync done, %d, #%d, %" G_GINT64_FORMAT,
2691             ret, priv->timer_seqnum, clock_jitter);
2692       } else {
2693         GST_DEBUG_OBJECT (jitterbuffer, "sync unscheduled");
2694       }
2695       /* and free the entry */
2696       gst_clock_id_unref (id);
2697       priv->clock_id = NULL;
2698     } else {
2699       /* no timers, wait for activity */
2700       JBUF_WAIT_TIMER (priv);
2701     }
2702   }
2703   JBUF_UNLOCK (priv);
2704
2705   GST_DEBUG_OBJECT (jitterbuffer, "we are stopping");
2706   return;
2707 }
2708
2709 /*
2710  * This funcion implements the main pushing loop on the source pad.
2711  *
2712  * It first tries to push as many buffers as possible. If there is a seqnum
2713  * mismatch, we wait for the next timeouts.
2714  */
2715 static void
2716 gst_rtp_jitter_buffer_loop (GstRtpJitterBuffer * jitterbuffer)
2717 {
2718   GstRtpJitterBufferPrivate *priv;
2719   GstFlowReturn result;
2720
2721   priv = jitterbuffer->priv;
2722
2723   JBUF_LOCK_CHECK (priv, flushing);
2724   do {
2725     result = handle_next_buffer (jitterbuffer);
2726     if (G_LIKELY (result == GST_FLOW_WAIT)) {
2727       /* now wait for the next event */
2728       JBUF_WAIT_EVENT (priv, flushing);
2729       result = GST_FLOW_OK;
2730     }
2731   }
2732   while (result == GST_FLOW_OK);
2733   JBUF_UNLOCK (priv);
2734
2735   /* if we get here we need to pause */
2736   goto pause;
2737
2738   /* ERRORS */
2739 flushing:
2740   {
2741     result = priv->srcresult;
2742     JBUF_UNLOCK (priv);
2743     goto pause;
2744   }
2745 pause:
2746   {
2747     const gchar *reason = gst_flow_get_name (result);
2748     GstEvent *event;
2749
2750     GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s", reason);
2751     gst_pad_pause_task (priv->srcpad);
2752     if (result == GST_FLOW_EOS) {
2753       event = gst_event_new_eos ();
2754       gst_pad_push_event (priv->srcpad, event);
2755     }
2756     return;
2757   }
2758 }
2759
2760 /* collect the info from the lastest RTCP packet and the jitterbuffer sync, do
2761  * some sanity checks and then emit the handle-sync signal with the parameters.
2762  * This function must be called with the LOCK */
2763 static void
2764 do_handle_sync (GstRtpJitterBuffer * jitterbuffer)
2765 {
2766   GstRtpJitterBufferPrivate *priv;
2767   guint64 base_rtptime, base_time;
2768   guint32 clock_rate;
2769   guint64 last_rtptime;
2770   guint64 clock_base;
2771   guint64 ext_rtptime, diff;
2772   gboolean drop = FALSE;
2773
2774   priv = jitterbuffer->priv;
2775
2776   /* get the last values from the jitterbuffer */
2777   rtp_jitter_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
2778       &clock_rate, &last_rtptime);
2779
2780   clock_base = priv->clock_base;
2781   ext_rtptime = priv->ext_rtptime;
2782
2783   GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
2784       G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
2785       ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
2786       ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
2787
2788   if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
2789     GST_DEBUG_OBJECT (jitterbuffer, "dropping, no RTP values");
2790     drop = TRUE;
2791   } else {
2792     /* we can't accept anything that happened before we did the last resync */
2793     if (base_rtptime > ext_rtptime) {
2794       GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
2795       drop = TRUE;
2796     } else {
2797       /* the SR RTP timestamp must be something close to what we last observed
2798        * in the jitterbuffer */
2799       if (ext_rtptime > last_rtptime) {
2800         /* check how far ahead it is to our RTP timestamps */
2801         diff = ext_rtptime - last_rtptime;
2802         /* if bigger than 1 second, we drop it */
2803         if (diff > clock_rate) {
2804           GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
2805           /* should drop this, but some RTSP servers end up with bogus
2806            * way too ahead RTCP packet when repeated PAUSE/PLAY,
2807            * so still trigger rptbin sync but invalidate RTCP data
2808            * (sync might use other methods) */
2809           ext_rtptime = -1;
2810         }
2811         GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
2812             G_GUINT64_FORMAT, last_rtptime, diff);
2813       }
2814     }
2815   }
2816
2817   if (!drop) {
2818     GstStructure *s;
2819
2820     s = gst_structure_new ("application/x-rtp-sync",
2821         "base-rtptime", G_TYPE_UINT64, base_rtptime,
2822         "base-time", G_TYPE_UINT64, base_time,
2823         "clock-rate", G_TYPE_UINT, clock_rate,
2824         "clock-base", G_TYPE_UINT64, clock_base,
2825         "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
2826         "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
2827
2828     GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
2829     gst_buffer_replace (&priv->last_sr, NULL);
2830     JBUF_UNLOCK (priv);
2831     g_signal_emit (jitterbuffer,
2832         gst_rtp_jitter_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
2833     JBUF_LOCK (priv);
2834     gst_structure_free (s);
2835   } else {
2836     GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
2837   }
2838 }
2839
2840 static GstFlowReturn
2841 gst_rtp_jitter_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
2842     GstBuffer * buffer)
2843 {
2844   GstRtpJitterBuffer *jitterbuffer;
2845   GstRtpJitterBufferPrivate *priv;
2846   GstFlowReturn ret = GST_FLOW_OK;
2847   guint32 ssrc;
2848   GstRTCPPacket packet;
2849   guint64 ext_rtptime;
2850   guint32 rtptime;
2851   GstRTCPBuffer rtcp = { NULL, };
2852
2853   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
2854
2855   if (G_UNLIKELY (!gst_rtcp_buffer_validate (buffer)))
2856     goto invalid_buffer;
2857
2858   priv = jitterbuffer->priv;
2859
2860   gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
2861
2862   if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
2863     goto empty_buffer;
2864
2865   /* first packet must be SR or RR or else the validate would have failed */
2866   switch (gst_rtcp_packet_get_type (&packet)) {
2867     case GST_RTCP_TYPE_SR:
2868       gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
2869           NULL, NULL);
2870       break;
2871     default:
2872       goto ignore_buffer;
2873   }
2874   gst_rtcp_buffer_unmap (&rtcp);
2875
2876   GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
2877
2878   JBUF_LOCK (priv);
2879   /* convert the RTP timestamp to our extended timestamp, using the same offset
2880    * we used in the jitterbuffer */
2881   ext_rtptime = priv->jbuf->ext_rtptime;
2882   ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
2883
2884   priv->ext_rtptime = ext_rtptime;
2885   gst_buffer_replace (&priv->last_sr, buffer);
2886
2887   do_handle_sync (jitterbuffer);
2888   JBUF_UNLOCK (priv);
2889
2890 done:
2891   gst_buffer_unref (buffer);
2892
2893   return ret;
2894
2895 invalid_buffer:
2896   {
2897     /* this is not fatal but should be filtered earlier */
2898     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2899         ("Received invalid RTCP payload, dropping"));
2900     ret = GST_FLOW_OK;
2901     goto done;
2902   }
2903 empty_buffer:
2904   {
2905     /* this is not fatal but should be filtered earlier */
2906     GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
2907         ("Received empty RTCP payload, dropping"));
2908     gst_rtcp_buffer_unmap (&rtcp);
2909     ret = GST_FLOW_OK;
2910     goto done;
2911   }
2912 ignore_buffer:
2913   {
2914     GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
2915     gst_rtcp_buffer_unmap (&rtcp);
2916     ret = GST_FLOW_OK;
2917     goto done;
2918   }
2919 }
2920
2921 static gboolean
2922 gst_rtp_jitter_buffer_sink_query (GstPad * pad, GstObject * parent,
2923     GstQuery * query)
2924 {
2925   gboolean res = FALSE;
2926
2927   switch (GST_QUERY_TYPE (query)) {
2928     case GST_QUERY_CAPS:
2929     {
2930       GstCaps *filter, *caps;
2931
2932       gst_query_parse_caps (query, &filter);
2933       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
2934       gst_query_set_caps_result (query, caps);
2935       gst_caps_unref (caps);
2936       res = TRUE;
2937       break;
2938     }
2939     default:
2940       if (GST_QUERY_IS_SERIALIZED (query)) {
2941         GST_WARNING_OBJECT (pad, "unhandled serialized query");
2942         res = FALSE;
2943       } else {
2944         res = gst_pad_query_default (pad, parent, query);
2945       }
2946       break;
2947   }
2948   return res;
2949 }
2950
2951 static gboolean
2952 gst_rtp_jitter_buffer_src_query (GstPad * pad, GstObject * parent,
2953     GstQuery * query)
2954 {
2955   GstRtpJitterBuffer *jitterbuffer;
2956   GstRtpJitterBufferPrivate *priv;
2957   gboolean res = FALSE;
2958
2959   jitterbuffer = GST_RTP_JITTER_BUFFER (parent);
2960   priv = jitterbuffer->priv;
2961
2962   switch (GST_QUERY_TYPE (query)) {
2963     case GST_QUERY_LATENCY:
2964     {
2965       /* We need to send the query upstream and add the returned latency to our
2966        * own */
2967       GstClockTime min_latency, max_latency;
2968       gboolean us_live;
2969       GstClockTime our_latency;
2970
2971       if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
2972         gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
2973
2974         GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
2975             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
2976             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
2977
2978         /* store this so that we can safely sync on the peer buffers. */
2979         JBUF_LOCK (priv);
2980         priv->peer_latency = min_latency;
2981         our_latency = priv->latency_ns;
2982         JBUF_UNLOCK (priv);
2983
2984         GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
2985             GST_TIME_ARGS (our_latency));
2986
2987         /* we add some latency but can buffer an infinite amount of time */
2988         min_latency += our_latency;
2989         max_latency = -1;
2990
2991         GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
2992             GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
2993             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
2994
2995         gst_query_set_latency (query, TRUE, min_latency, max_latency);
2996       }
2997       break;
2998     }
2999     case GST_QUERY_POSITION:
3000     {
3001       GstClockTime start, last_out;
3002       GstFormat fmt;
3003
3004       gst_query_parse_position (query, &fmt, NULL);
3005       if (fmt != GST_FORMAT_TIME) {
3006         res = gst_pad_query_default (pad, parent, query);
3007         break;
3008       }
3009
3010       JBUF_LOCK (priv);
3011       start = priv->npt_start;
3012       last_out = priv->last_out_time;
3013       JBUF_UNLOCK (priv);
3014
3015       GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
3016           ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
3017           GST_TIME_ARGS (last_out));
3018
3019       if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
3020         /* bring 0-based outgoing time to stream time */
3021         gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
3022         res = TRUE;
3023       } else {
3024         res = gst_pad_query_default (pad, parent, query);
3025       }
3026       break;
3027     }
3028     case GST_QUERY_CAPS:
3029     {
3030       GstCaps *filter, *caps;
3031
3032       gst_query_parse_caps (query, &filter);
3033       caps = gst_rtp_jitter_buffer_getcaps (pad, filter);
3034       gst_query_set_caps_result (query, caps);
3035       gst_caps_unref (caps);
3036       res = TRUE;
3037       break;
3038     }
3039     default:
3040       res = gst_pad_query_default (pad, parent, query);
3041       break;
3042   }
3043
3044   return res;
3045 }
3046
3047 static void
3048 gst_rtp_jitter_buffer_set_property (GObject * object,
3049     guint prop_id, const GValue * value, GParamSpec * pspec)
3050 {
3051   GstRtpJitterBuffer *jitterbuffer;
3052   GstRtpJitterBufferPrivate *priv;
3053
3054   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3055   priv = jitterbuffer->priv;
3056
3057   switch (prop_id) {
3058     case PROP_LATENCY:
3059     {
3060       guint new_latency, old_latency;
3061
3062       new_latency = g_value_get_uint (value);
3063
3064       JBUF_LOCK (priv);
3065       old_latency = priv->latency_ms;
3066       priv->latency_ms = new_latency;
3067       priv->latency_ns = priv->latency_ms * GST_MSECOND;
3068       rtp_jitter_buffer_set_delay (priv->jbuf, priv->latency_ns);
3069       JBUF_UNLOCK (priv);
3070
3071       /* post message if latency changed, this will inform the parent pipeline
3072        * that a latency reconfiguration is possible/needed. */
3073       if (new_latency != old_latency) {
3074         GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
3075             GST_TIME_ARGS (new_latency * GST_MSECOND));
3076
3077         gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
3078             gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
3079       }
3080       break;
3081     }
3082     case PROP_DROP_ON_LATENCY:
3083       JBUF_LOCK (priv);
3084       priv->drop_on_latency = g_value_get_boolean (value);
3085       JBUF_UNLOCK (priv);
3086       break;
3087     case PROP_TS_OFFSET:
3088       JBUF_LOCK (priv);
3089       priv->ts_offset = g_value_get_int64 (value);
3090       priv->ts_discont = TRUE;
3091       JBUF_UNLOCK (priv);
3092       break;
3093     case PROP_DO_LOST:
3094       JBUF_LOCK (priv);
3095       priv->do_lost = g_value_get_boolean (value);
3096       JBUF_UNLOCK (priv);
3097       break;
3098     case PROP_MODE:
3099       JBUF_LOCK (priv);
3100       rtp_jitter_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
3101       JBUF_UNLOCK (priv);
3102       break;
3103     case PROP_DO_RETRANSMISSION:
3104       JBUF_LOCK (priv);
3105       priv->do_retransmission = g_value_get_boolean (value);
3106       JBUF_UNLOCK (priv);
3107       break;
3108     case PROP_RTX_DELAY:
3109       JBUF_LOCK (priv);
3110       priv->rtx_delay = g_value_get_int (value);
3111       JBUF_UNLOCK (priv);
3112       break;
3113     case PROP_RTX_DELAY_REORDER:
3114       JBUF_LOCK (priv);
3115       priv->rtx_delay_reorder = g_value_get_int (value);
3116       JBUF_UNLOCK (priv);
3117       break;
3118     case PROP_RTX_RETRY_TIMEOUT:
3119       JBUF_LOCK (priv);
3120       priv->rtx_retry_timeout = g_value_get_int (value);
3121       JBUF_UNLOCK (priv);
3122       break;
3123     case PROP_RTX_RETRY_PERIOD:
3124       JBUF_LOCK (priv);
3125       priv->rtx_retry_period = g_value_get_int (value);
3126       JBUF_UNLOCK (priv);
3127       break;
3128     default:
3129       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3130       break;
3131   }
3132 }
3133
3134 static void
3135 gst_rtp_jitter_buffer_get_property (GObject * object,
3136     guint prop_id, GValue * value, GParamSpec * pspec)
3137 {
3138   GstRtpJitterBuffer *jitterbuffer;
3139   GstRtpJitterBufferPrivate *priv;
3140
3141   jitterbuffer = GST_RTP_JITTER_BUFFER (object);
3142   priv = jitterbuffer->priv;
3143
3144   switch (prop_id) {
3145     case PROP_LATENCY:
3146       JBUF_LOCK (priv);
3147       g_value_set_uint (value, priv->latency_ms);
3148       JBUF_UNLOCK (priv);
3149       break;
3150     case PROP_DROP_ON_LATENCY:
3151       JBUF_LOCK (priv);
3152       g_value_set_boolean (value, priv->drop_on_latency);
3153       JBUF_UNLOCK (priv);
3154       break;
3155     case PROP_TS_OFFSET:
3156       JBUF_LOCK (priv);
3157       g_value_set_int64 (value, priv->ts_offset);
3158       JBUF_UNLOCK (priv);
3159       break;
3160     case PROP_DO_LOST:
3161       JBUF_LOCK (priv);
3162       g_value_set_boolean (value, priv->do_lost);
3163       JBUF_UNLOCK (priv);
3164       break;
3165     case PROP_MODE:
3166       JBUF_LOCK (priv);
3167       g_value_set_enum (value, rtp_jitter_buffer_get_mode (priv->jbuf));
3168       JBUF_UNLOCK (priv);
3169       break;
3170     case PROP_PERCENT:
3171     {
3172       gint percent;
3173
3174       JBUF_LOCK (priv);
3175       if (priv->srcresult != GST_FLOW_OK)
3176         percent = 100;
3177       else
3178         percent = rtp_jitter_buffer_get_percent (priv->jbuf);
3179
3180       g_value_set_int (value, percent);
3181       JBUF_UNLOCK (priv);
3182       break;
3183     }
3184     case PROP_DO_RETRANSMISSION:
3185       JBUF_LOCK (priv);
3186       g_value_set_boolean (value, priv->do_retransmission);
3187       JBUF_UNLOCK (priv);
3188       break;
3189     case PROP_RTX_DELAY:
3190       JBUF_LOCK (priv);
3191       g_value_set_int (value, priv->rtx_delay);
3192       JBUF_UNLOCK (priv);
3193       break;
3194     case PROP_RTX_DELAY_REORDER:
3195       JBUF_LOCK (priv);
3196       g_value_set_int (value, priv->rtx_delay_reorder);
3197       JBUF_UNLOCK (priv);
3198       break;
3199     case PROP_RTX_RETRY_TIMEOUT:
3200       JBUF_LOCK (priv);
3201       g_value_set_int (value, priv->rtx_retry_timeout);
3202       JBUF_UNLOCK (priv);
3203       break;
3204     case PROP_RTX_RETRY_PERIOD:
3205       JBUF_LOCK (priv);
3206       g_value_set_int (value, priv->rtx_retry_period);
3207       JBUF_UNLOCK (priv);
3208       break;
3209     default:
3210       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3211       break;
3212   }
3213 }