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