6ef7df2abfa2f5f3cd4709d9634968fbc21ba412
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / rtpjitterbuffer.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19 #include <string.h>
20 #include <stdlib.h>
21
22 #include <gst/rtp/gstrtpbuffer.h>
23 #include <gst/rtp/gstrtcpbuffer.h>
24
25 #include "rtpjitterbuffer.h"
26
27 GST_DEBUG_CATEGORY_STATIC (rtp_jitter_buffer_debug);
28 #define GST_CAT_DEFAULT rtp_jitter_buffer_debug
29
30 #define MAX_WINDOW      RTP_JITTER_BUFFER_MAX_WINDOW
31 #define MAX_TIME        (2 * GST_SECOND)
32
33 /* signals and args */
34 enum
35 {
36   LAST_SIGNAL
37 };
38
39 enum
40 {
41   PROP_0
42 };
43
44 /* GObject vmethods */
45 static void rtp_jitter_buffer_finalize (GObject * object);
46
47 GType
48 rtp_jitter_buffer_mode_get_type (void)
49 {
50   static GType jitter_buffer_mode_type = 0;
51   static const GEnumValue jitter_buffer_modes[] = {
52     {RTP_JITTER_BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
53     {RTP_JITTER_BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
54     {RTP_JITTER_BUFFER_MODE_BUFFER, "Do low/high watermark buffering",
55         "buffer"},
56     {RTP_JITTER_BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks",
57         "synced"},
58     {0, NULL, NULL},
59   };
60
61   if (!jitter_buffer_mode_type) {
62     jitter_buffer_mode_type =
63         g_enum_register_static ("RTPJitterBufferMode", jitter_buffer_modes);
64   }
65   return jitter_buffer_mode_type;
66 }
67
68 /* static guint rtp_jitter_buffer_signals[LAST_SIGNAL] = { 0 }; */
69
70 G_DEFINE_TYPE (RTPJitterBuffer, rtp_jitter_buffer, G_TYPE_OBJECT);
71
72 static void
73 rtp_jitter_buffer_class_init (RTPJitterBufferClass * klass)
74 {
75   GObjectClass *gobject_class;
76
77   gobject_class = (GObjectClass *) klass;
78
79   gobject_class->finalize = rtp_jitter_buffer_finalize;
80
81   GST_DEBUG_CATEGORY_INIT (rtp_jitter_buffer_debug, "rtpjitterbuffer", 0,
82       "RTP Jitter Buffer");
83 }
84
85 static void
86 rtp_jitter_buffer_init (RTPJitterBuffer * jbuf)
87 {
88   g_mutex_init (&jbuf->clock_lock);
89
90   g_queue_init (&jbuf->packets);
91   jbuf->mode = RTP_JITTER_BUFFER_MODE_SLAVE;
92
93   rtp_jitter_buffer_reset_skew (jbuf);
94 }
95
96 static void
97 rtp_jitter_buffer_finalize (GObject * object)
98 {
99   RTPJitterBuffer *jbuf;
100
101   jbuf = RTP_JITTER_BUFFER_CAST (object);
102
103   if (jbuf->media_clock_synced_id)
104     g_signal_handler_disconnect (jbuf->media_clock,
105         jbuf->media_clock_synced_id);
106   if (jbuf->media_clock) {
107     /* Make sure to clear any clock master before releasing the clock */
108     gst_clock_set_master (jbuf->media_clock, NULL);
109     gst_object_unref (jbuf->media_clock);
110   }
111
112   if (jbuf->pipeline_clock)
113     gst_object_unref (jbuf->pipeline_clock);
114
115   /* We cannot use g_queue_clear() as it would pass the wrong size to
116    * g_slice_free() which may lead to data corruption in the slice allocator.
117    */
118   rtp_jitter_buffer_flush (jbuf, NULL, NULL);
119
120   g_mutex_clear (&jbuf->clock_lock);
121
122   G_OBJECT_CLASS (rtp_jitter_buffer_parent_class)->finalize (object);
123 }
124
125 /**
126  * rtp_jitter_buffer_new:
127  *
128  * Create an #RTPJitterBuffer.
129  *
130  * Returns: a new #RTPJitterBuffer. Use g_object_unref() after usage.
131  */
132 RTPJitterBuffer *
133 rtp_jitter_buffer_new (void)
134 {
135   RTPJitterBuffer *jbuf;
136
137   jbuf = g_object_new (RTP_TYPE_JITTER_BUFFER, NULL);
138
139   return jbuf;
140 }
141
142 /**
143  * rtp_jitter_buffer_get_mode:
144  * @jbuf: an #RTPJitterBuffer
145  *
146  * Get the current jitterbuffer mode.
147  *
148  * Returns: the current jitterbuffer mode.
149  */
150 RTPJitterBufferMode
151 rtp_jitter_buffer_get_mode (RTPJitterBuffer * jbuf)
152 {
153   return jbuf->mode;
154 }
155
156 /**
157  * rtp_jitter_buffer_set_mode:
158  * @jbuf: an #RTPJitterBuffer
159  * @mode: a #RTPJitterBufferMode
160  *
161  * Set the buffering and clock slaving algorithm used in the @jbuf.
162  */
163 void
164 rtp_jitter_buffer_set_mode (RTPJitterBuffer * jbuf, RTPJitterBufferMode mode)
165 {
166   jbuf->mode = mode;
167 }
168
169 GstClockTime
170 rtp_jitter_buffer_get_delay (RTPJitterBuffer * jbuf)
171 {
172   return jbuf->delay;
173 }
174
175 void
176 rtp_jitter_buffer_set_delay (RTPJitterBuffer * jbuf, GstClockTime delay)
177 {
178   jbuf->delay = delay;
179   jbuf->low_level = (delay * 15) / 100;
180   /* the high level is at 90% in order to release packets before we fill up the
181    * buffer up to the latency */
182   jbuf->high_level = (delay * 90) / 100;
183
184   GST_DEBUG ("delay %" GST_TIME_FORMAT ", min %" GST_TIME_FORMAT ", max %"
185       GST_TIME_FORMAT, GST_TIME_ARGS (jbuf->delay),
186       GST_TIME_ARGS (jbuf->low_level), GST_TIME_ARGS (jbuf->high_level));
187 }
188
189 /**
190  * rtp_jitter_buffer_set_clock_rate:
191  * @jbuf: an #RTPJitterBuffer
192  * @clock_rate: the new clock rate
193  *
194  * Set the clock rate in the jitterbuffer.
195  */
196 void
197 rtp_jitter_buffer_set_clock_rate (RTPJitterBuffer * jbuf, guint32 clock_rate)
198 {
199   if (jbuf->clock_rate != clock_rate) {
200     GST_DEBUG ("Clock rate changed from %" G_GUINT32_FORMAT " to %"
201         G_GUINT32_FORMAT, jbuf->clock_rate, clock_rate);
202     jbuf->clock_rate = clock_rate;
203     rtp_jitter_buffer_reset_skew (jbuf);
204   }
205 }
206
207 /**
208  * rtp_jitter_buffer_get_clock_rate:
209  * @jbuf: an #RTPJitterBuffer
210  *
211  * Get the currently configure clock rate in @jbuf.
212  *
213  * Returns: the current clock-rate
214  */
215 guint32
216 rtp_jitter_buffer_get_clock_rate (RTPJitterBuffer * jbuf)
217 {
218   return jbuf->clock_rate;
219 }
220
221 static void
222 media_clock_synced_cb (GstClock * clock, gboolean synced,
223     RTPJitterBuffer * jbuf)
224 {
225   GstClockTime internal, external;
226
227   g_mutex_lock (&jbuf->clock_lock);
228   if (jbuf->pipeline_clock) {
229     internal = gst_clock_get_internal_time (jbuf->media_clock);
230     external = gst_clock_get_time (jbuf->pipeline_clock);
231
232     gst_clock_set_calibration (jbuf->media_clock, internal, external, 1, 1);
233   }
234   g_mutex_unlock (&jbuf->clock_lock);
235 }
236
237 /**
238  * rtp_jitter_buffer_set_media_clock:
239  * @jbuf: an #RTPJitterBuffer
240  * @clock: (transfer full): media #GstClock
241  * @clock_offset: RTP time at clock epoch or -1
242  *
243  * Sets the media clock for the media and the clock offset
244  *
245  */
246 void
247 rtp_jitter_buffer_set_media_clock (RTPJitterBuffer * jbuf, GstClock * clock,
248     guint64 clock_offset)
249 {
250   g_mutex_lock (&jbuf->clock_lock);
251   if (jbuf->media_clock) {
252     if (jbuf->media_clock_synced_id)
253       g_signal_handler_disconnect (jbuf->media_clock,
254           jbuf->media_clock_synced_id);
255     jbuf->media_clock_synced_id = 0;
256     gst_object_unref (jbuf->media_clock);
257   }
258   jbuf->media_clock = clock;
259   jbuf->media_clock_offset = clock_offset;
260
261   if (jbuf->pipeline_clock && jbuf->media_clock &&
262       jbuf->pipeline_clock != jbuf->media_clock) {
263     jbuf->media_clock_synced_id =
264         g_signal_connect (jbuf->media_clock, "synced",
265         G_CALLBACK (media_clock_synced_cb), jbuf);
266     if (gst_clock_is_synced (jbuf->media_clock)) {
267       GstClockTime internal, external;
268
269       internal = gst_clock_get_internal_time (jbuf->media_clock);
270       external = gst_clock_get_time (jbuf->pipeline_clock);
271
272       gst_clock_set_calibration (jbuf->media_clock, internal, external, 1, 1);
273     }
274
275     gst_clock_set_master (jbuf->media_clock, jbuf->pipeline_clock);
276   }
277   g_mutex_unlock (&jbuf->clock_lock);
278 }
279
280 /**
281  * rtp_jitter_buffer_set_pipeline_clock:
282  * @jbuf: an #RTPJitterBuffer
283  * @clock: pipeline #GstClock
284  *
285  * Sets the pipeline clock
286  *
287  */
288 void
289 rtp_jitter_buffer_set_pipeline_clock (RTPJitterBuffer * jbuf, GstClock * clock)
290 {
291   g_mutex_lock (&jbuf->clock_lock);
292   if (jbuf->pipeline_clock)
293     gst_object_unref (jbuf->pipeline_clock);
294   jbuf->pipeline_clock = clock ? gst_object_ref (clock) : NULL;
295
296   if (jbuf->pipeline_clock && jbuf->media_clock &&
297       jbuf->pipeline_clock != jbuf->media_clock) {
298     if (gst_clock_is_synced (jbuf->media_clock)) {
299       GstClockTime internal, external;
300
301       internal = gst_clock_get_internal_time (jbuf->media_clock);
302       external = gst_clock_get_time (jbuf->pipeline_clock);
303
304       gst_clock_set_calibration (jbuf->media_clock, internal, external, 1, 1);
305     }
306
307     gst_clock_set_master (jbuf->media_clock, jbuf->pipeline_clock);
308   }
309   g_mutex_unlock (&jbuf->clock_lock);
310 }
311
312 gboolean
313 rtp_jitter_buffer_get_rfc7273_sync (RTPJitterBuffer * jbuf)
314 {
315   return jbuf->rfc7273_sync;
316 }
317
318 void
319 rtp_jitter_buffer_set_rfc7273_sync (RTPJitterBuffer * jbuf,
320     gboolean rfc7273_sync)
321 {
322   jbuf->rfc7273_sync = rfc7273_sync;
323 }
324
325 /**
326  * rtp_jitter_buffer_reset_skew:
327  * @jbuf: an #RTPJitterBuffer
328  *
329  * Reset the skew calculations in @jbuf.
330  */
331 void
332 rtp_jitter_buffer_reset_skew (RTPJitterBuffer * jbuf)
333 {
334   jbuf->base_time = -1;
335   jbuf->base_rtptime = -1;
336   jbuf->base_extrtp = -1;
337   jbuf->media_clock_base_time = -1;
338   jbuf->ext_rtptime = -1;
339   jbuf->last_rtptime = -1;
340   jbuf->window_pos = 0;
341   jbuf->window_filling = TRUE;
342   jbuf->window_min = 0;
343   jbuf->skew = 0;
344   jbuf->prev_send_diff = -1;
345   jbuf->prev_out_time = -1;
346   jbuf->need_resync = TRUE;
347
348   GST_DEBUG ("reset skew correction");
349 }
350
351 /**
352  * rtp_jitter_buffer_disable_buffering:
353  * @jbuf: an #RTPJitterBuffer
354  * @disabled: the new state
355  *
356  * Enable or disable buffering on @jbuf.
357  */
358 void
359 rtp_jitter_buffer_disable_buffering (RTPJitterBuffer * jbuf, gboolean disabled)
360 {
361   jbuf->buffering_disabled = disabled;
362 }
363
364 static void
365 rtp_jitter_buffer_resync (RTPJitterBuffer * jbuf, GstClockTime time,
366     GstClockTime gstrtptime, guint64 ext_rtptime, gboolean reset_skew)
367 {
368   jbuf->base_time = time;
369   jbuf->media_clock_base_time = -1;
370   jbuf->base_rtptime = gstrtptime;
371   jbuf->base_extrtp = ext_rtptime;
372   jbuf->prev_out_time = -1;
373   jbuf->prev_send_diff = -1;
374   if (reset_skew) {
375     jbuf->window_filling = TRUE;
376     jbuf->window_pos = 0;
377     jbuf->window_min = 0;
378     jbuf->window_size = 0;
379     jbuf->skew = 0;
380   }
381   jbuf->need_resync = FALSE;
382 }
383
384 static guint64
385 get_buffer_level (RTPJitterBuffer * jbuf)
386 {
387   RTPJitterBufferItem *high_buf = NULL, *low_buf = NULL;
388   guint64 level;
389
390   /* first buffer with timestamp */
391   high_buf = (RTPJitterBufferItem *) g_queue_peek_tail_link (&jbuf->packets);
392   while (high_buf) {
393     if (high_buf->dts != -1 || high_buf->pts != -1)
394       break;
395
396     high_buf = (RTPJitterBufferItem *) g_list_previous (high_buf);
397   }
398
399   low_buf = (RTPJitterBufferItem *) g_queue_peek_head_link (&jbuf->packets);
400   while (low_buf) {
401     if (low_buf->dts != -1 || low_buf->pts != -1)
402       break;
403
404     low_buf = (RTPJitterBufferItem *) g_list_next (low_buf);
405   }
406
407   if (!high_buf || !low_buf || high_buf == low_buf) {
408     level = 0;
409   } else {
410     guint64 high_ts, low_ts;
411
412     high_ts = high_buf->dts != -1 ? high_buf->dts : high_buf->pts;
413     low_ts = low_buf->dts != -1 ? low_buf->dts : low_buf->pts;
414
415     if (high_ts > low_ts)
416       level = high_ts - low_ts;
417     else
418       level = 0;
419
420     GST_LOG_OBJECT (jbuf,
421         "low %" GST_TIME_FORMAT " high %" GST_TIME_FORMAT " level %"
422         G_GUINT64_FORMAT, GST_TIME_ARGS (low_ts), GST_TIME_ARGS (high_ts),
423         level);
424   }
425   return level;
426 }
427
428 static void
429 update_buffer_level (RTPJitterBuffer * jbuf, gint * percent)
430 {
431   gboolean post = FALSE;
432   guint64 level;
433
434   level = get_buffer_level (jbuf);
435   GST_DEBUG ("buffer level %" GST_TIME_FORMAT, GST_TIME_ARGS (level));
436
437   if (jbuf->buffering_disabled) {
438     GST_DEBUG ("buffering is disabled");
439     level = jbuf->high_level;
440   }
441
442   if (jbuf->buffering) {
443     post = TRUE;
444     if (level >= jbuf->high_level) {
445       GST_DEBUG ("buffering finished");
446       jbuf->buffering = FALSE;
447     }
448   } else {
449     if (level < jbuf->low_level) {
450       GST_DEBUG ("buffering started");
451       jbuf->buffering = TRUE;
452       post = TRUE;
453     }
454   }
455   if (post) {
456     gint perc;
457
458     if (jbuf->buffering && (jbuf->high_level != 0)) {
459       perc = (level * 100 / jbuf->high_level);
460       perc = MIN (perc, 100);
461     } else {
462       perc = 100;
463     }
464
465     if (percent)
466       *percent = perc;
467
468     GST_DEBUG ("buffering %d", perc);
469   }
470 }
471
472 /* For the clock skew we use a windowed low point averaging algorithm as can be
473  * found in Fober, Orlarey and Letz, 2005, "Real Time Clock Skew Estimation
474  * over Network Delays":
475  * http://www.grame.fr/Ressources/pub/TR-050601.pdf
476  * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.102.1546
477  *
478  * The idea is that the jitter is composed of:
479  *
480  *  J = N + n
481  *
482  *   N   : a constant network delay.
483  *   n   : random added noise. The noise is concentrated around 0
484  *
485  * In the receiver we can track the elapsed time at the sender with:
486  *
487  *  send_diff(i) = (Tsi - Ts0);
488  *
489  *   Tsi : The time at the sender at packet i
490  *   Ts0 : The time at the sender at the first packet
491  *
492  * This is the difference between the RTP timestamp in the first received packet
493  * and the current packet.
494  *
495  * At the receiver we have to deal with the jitter introduced by the network.
496  *
497  *  recv_diff(i) = (Tri - Tr0)
498  *
499  *   Tri : The time at the receiver at packet i
500  *   Tr0 : The time at the receiver at the first packet
501  *
502  * Both of these values contain a jitter Ji, a jitter for packet i, so we can
503  * write:
504  *
505  *  recv_diff(i) = (Cri + D + ni) - (Cr0 + D + n0))
506  *
507  *    Cri    : The time of the clock at the receiver for packet i
508  *    D + ni : The jitter when receiving packet i
509  *
510  * We see that the network delay is irrelevant here as we can eliminate D:
511  *
512  *  recv_diff(i) = (Cri + ni) - (Cr0 + n0))
513  *
514  * The drift is now expressed as:
515  *
516  *  Drift(i) = recv_diff(i) - send_diff(i);
517  *
518  * We now keep the W latest values of Drift and find the minimum (this is the
519  * one with the lowest network jitter and thus the one which is least affected
520  * by it). We average this lowest value to smooth out the resulting network skew.
521  *
522  * Both the window and the weighting used for averaging influence the accuracy
523  * of the drift estimation. Finding the correct parameters turns out to be a
524  * compromise between accuracy and inertia.
525  *
526  * We use a 2 second window or up to 512 data points, which is statistically big
527  * enough to catch spikes (FIXME, detect spikes).
528  * We also use a rather large weighting factor (125) to smoothly adapt. During
529  * startup, when filling the window, we use a parabolic weighting factor, the
530  * more the window is filled, the faster we move to the detected possible skew.
531  *
532  * Returns: @time adjusted with the clock skew.
533  */
534 static GstClockTime
535 calculate_skew (RTPJitterBuffer * jbuf, guint64 ext_rtptime,
536     GstClockTime gstrtptime, GstClockTime time, gint gap, gboolean is_rtx)
537 {
538   guint64 send_diff, recv_diff;
539   gint64 delta;
540   gint64 old;
541   gint pos, i;
542   GstClockTime out_time;
543   guint64 slope;
544
545   /* elapsed time at sender */
546   send_diff = gstrtptime - jbuf->base_rtptime;
547
548   /* we don't have an arrival timestamp so we can't do skew detection. we
549    * should still apply a timestamp based on RTP timestamp and base_time */
550   if (time == -1 || jbuf->base_time == -1 || is_rtx)
551     goto no_skew;
552
553   /* elapsed time at receiver, includes the jitter */
554   recv_diff = time - jbuf->base_time;
555
556   /* measure the diff */
557   delta = ((gint64) recv_diff) - ((gint64) send_diff);
558
559   /* measure the slope, this gives a rought estimate between the sender speed
560    * and the receiver speed. This should be approximately 8, higher values
561    * indicate a burst (especially when the connection starts) */
562   if (recv_diff > 0)
563     slope = (send_diff * 8) / recv_diff;
564   else
565     slope = 8;
566
567   GST_DEBUG ("time %" GST_TIME_FORMAT ", base %" GST_TIME_FORMAT ", recv_diff %"
568       GST_TIME_FORMAT ", slope %" G_GUINT64_FORMAT, GST_TIME_ARGS (time),
569       GST_TIME_ARGS (jbuf->base_time), GST_TIME_ARGS (recv_diff), slope);
570
571   /* if the difference between the sender timeline and the receiver timeline
572    * changed too quickly we have to resync because the server likely restarted
573    * its timestamps. */
574   if (ABS (delta - jbuf->skew) > GST_SECOND) {
575     GST_WARNING ("delta - skew: %" GST_TIME_FORMAT " too big, reset skew",
576         GST_TIME_ARGS (ABS (delta - jbuf->skew)));
577     rtp_jitter_buffer_resync (jbuf, time, gstrtptime, ext_rtptime, TRUE);
578     send_diff = 0;
579     delta = 0;
580     gap = 0;
581   }
582
583   /* only do skew calculations if we didn't have a gap. if too much time
584    * has elapsed despite there being a gap, we resynced already. */
585   if (G_UNLIKELY (gap != 0))
586     goto no_skew;
587
588   pos = jbuf->window_pos;
589
590   if (G_UNLIKELY (jbuf->window_filling)) {
591     /* we are filling the window */
592     GST_DEBUG ("filling %d, delta %" G_GINT64_FORMAT, pos, delta);
593     jbuf->window[pos++] = delta;
594     /* calc the min delta we observed */
595     if (G_UNLIKELY (pos == 1 || delta < jbuf->window_min))
596       jbuf->window_min = delta;
597
598     if (G_UNLIKELY (send_diff >= MAX_TIME || pos >= MAX_WINDOW)) {
599       jbuf->window_size = pos;
600
601       /* window filled */
602       GST_DEBUG ("min %" G_GINT64_FORMAT, jbuf->window_min);
603
604       /* the skew is now the min */
605       jbuf->skew = jbuf->window_min;
606       jbuf->window_filling = FALSE;
607     } else {
608       gint perc_time, perc_window, perc;
609
610       /* figure out how much we filled the window, this depends on the amount of
611        * time we have or the max number of points we keep. */
612       perc_time = send_diff * 100 / MAX_TIME;
613       perc_window = pos * 100 / MAX_WINDOW;
614       perc = MAX (perc_time, perc_window);
615
616       /* make a parabolic function, the closer we get to the MAX, the more value
617        * we give to the scaling factor of the new value */
618       perc = perc * perc;
619
620       /* quickly go to the min value when we are filling up, slowly when we are
621        * just starting because we're not sure it's a good value yet. */
622       jbuf->skew =
623           (perc * jbuf->window_min + ((10000 - perc) * jbuf->skew)) / 10000;
624       jbuf->window_size = pos + 1;
625     }
626   } else {
627     /* pick old value and store new value. We keep the previous value in order
628      * to quickly check if the min of the window changed */
629     old = jbuf->window[pos];
630     jbuf->window[pos++] = delta;
631
632     if (G_UNLIKELY (delta <= jbuf->window_min)) {
633       /* if the new value we inserted is smaller or equal to the current min,
634        * it becomes the new min */
635       jbuf->window_min = delta;
636     } else if (G_UNLIKELY (old == jbuf->window_min)) {
637       gint64 min = G_MAXINT64;
638
639       /* if we removed the old min, we have to find a new min */
640       for (i = 0; i < jbuf->window_size; i++) {
641         /* we found another value equal to the old min, we can stop searching now */
642         if (jbuf->window[i] == old) {
643           min = old;
644           break;
645         }
646         if (jbuf->window[i] < min)
647           min = jbuf->window[i];
648       }
649       jbuf->window_min = min;
650     }
651     /* average the min values */
652     jbuf->skew = (jbuf->window_min + (124 * jbuf->skew)) / 125;
653     GST_DEBUG ("delta %" G_GINT64_FORMAT ", new min: %" G_GINT64_FORMAT,
654         delta, jbuf->window_min);
655   }
656   /* wrap around in the window */
657   if (G_UNLIKELY (pos >= jbuf->window_size))
658     pos = 0;
659   jbuf->window_pos = pos;
660
661 no_skew:
662   /* the output time is defined as the base timestamp plus the RTP time
663    * adjusted for the clock skew .*/
664   if (jbuf->base_time != -1) {
665     out_time = jbuf->base_time + send_diff;
666     /* skew can be negative and we don't want to make invalid timestamps */
667     if (jbuf->skew < 0 && out_time < -jbuf->skew) {
668       out_time = 0;
669     } else {
670       out_time += jbuf->skew;
671     }
672   } else
673     out_time = -1;
674
675   GST_DEBUG ("skew %" G_GINT64_FORMAT ", out %" GST_TIME_FORMAT,
676       jbuf->skew, GST_TIME_ARGS (out_time));
677
678   return out_time;
679 }
680
681 static void
682 queue_do_insert (RTPJitterBuffer * jbuf, GList * list, GList * item)
683 {
684   GQueue *queue = &jbuf->packets;
685
686   /* It's more likely that the packet was inserted at the tail of the queue */
687   if (G_LIKELY (list)) {
688     item->prev = list;
689     item->next = list->next;
690     list->next = item;
691   } else {
692     item->prev = NULL;
693     item->next = queue->head;
694     queue->head = item;
695   }
696   if (item->next)
697     item->next->prev = item;
698   else
699     queue->tail = item;
700   queue->length++;
701 }
702
703 GstClockTime
704 rtp_jitter_buffer_calculate_pts (RTPJitterBuffer * jbuf, GstClockTime dts,
705     gboolean estimated_dts, guint32 rtptime, GstClockTime base_time,
706     gint gap, gboolean is_rtx)
707 {
708   guint64 ext_rtptime;
709   GstClockTime gstrtptime, pts;
710   GstClock *media_clock, *pipeline_clock;
711   guint64 media_clock_offset;
712   gboolean rfc7273_mode;
713
714   /* rtp time jumps are checked for during skew calculation, but bypassed
715    * in other mode, so mind those here and reset jb if needed.
716    * Only reset if valid input time, which is likely for UDP input
717    * where we expect this might happen due to async thread effects
718    * (in seek and state change cycles), but not so much for TCP input */
719   if (GST_CLOCK_TIME_IS_VALID (dts) && !estimated_dts &&
720       jbuf->mode != RTP_JITTER_BUFFER_MODE_SLAVE &&
721       jbuf->base_time != -1 && jbuf->last_rtptime != -1) {
722     GstClockTime ext_rtptime = jbuf->ext_rtptime;
723
724     ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
725     if (ext_rtptime > jbuf->last_rtptime + 3 * jbuf->clock_rate ||
726         ext_rtptime + 3 * jbuf->clock_rate < jbuf->last_rtptime) {
727       if (!is_rtx) {
728         /* reset even if we don't have valid incoming time;
729          * still better than producing possibly very bogus output timestamp */
730         GST_WARNING ("rtp delta too big, reset skew");
731         rtp_jitter_buffer_reset_skew (jbuf);
732       } else {
733         GST_WARNING ("rtp delta too big: ignore rtx packet");
734         media_clock = NULL;
735         pipeline_clock = NULL;
736         pts = GST_CLOCK_TIME_NONE;
737         goto done;
738       }
739     }
740   }
741
742   /* Return the last time if we got the same RTP timestamp again */
743   ext_rtptime = gst_rtp_buffer_ext_timestamp (&jbuf->ext_rtptime, rtptime);
744   if (jbuf->last_rtptime != -1 && ext_rtptime == jbuf->last_rtptime) {
745     return jbuf->prev_out_time;
746   }
747
748   /* keep track of the last extended rtptime */
749   jbuf->last_rtptime = ext_rtptime;
750
751   g_mutex_lock (&jbuf->clock_lock);
752   media_clock = jbuf->media_clock ? gst_object_ref (jbuf->media_clock) : NULL;
753   pipeline_clock =
754       jbuf->pipeline_clock ? gst_object_ref (jbuf->pipeline_clock) : NULL;
755   media_clock_offset = jbuf->media_clock_offset;
756   g_mutex_unlock (&jbuf->clock_lock);
757
758   gstrtptime =
759       gst_util_uint64_scale_int (ext_rtptime, GST_SECOND, jbuf->clock_rate);
760
761   if (G_LIKELY (jbuf->base_rtptime != -1)) {
762     /* check elapsed time in RTP units */
763     if (gstrtptime < jbuf->base_rtptime) {
764       if (!is_rtx) {
765         /* elapsed time at sender, timestamps can go backwards and thus be
766          * smaller than our base time, schedule to take a new base time in
767          * that case. */
768         GST_WARNING ("backward timestamps at server, schedule resync");
769         jbuf->need_resync = TRUE;
770       } else {
771         GST_WARNING ("backward timestamps: ignore rtx packet");
772         pts = GST_CLOCK_TIME_NONE;
773         goto done;
774       }
775     }
776   }
777
778   switch (jbuf->mode) {
779     case RTP_JITTER_BUFFER_MODE_NONE:
780     case RTP_JITTER_BUFFER_MODE_BUFFER:
781       /* send 0 as the first timestamp and -1 for the other ones. This will
782        * interpolate them from the RTP timestamps with a 0 origin. In buffering
783        * mode we will adjust the outgoing timestamps according to the amount of
784        * time we spent buffering. */
785       if (jbuf->base_time == -1)
786         dts = 0;
787       else
788         dts = -1;
789       break;
790     case RTP_JITTER_BUFFER_MODE_SYNCED:
791       /* synchronized clocks, take first timestamp as base, use RTP timestamps
792        * to interpolate */
793       if (jbuf->base_time != -1 && !jbuf->need_resync)
794         dts = -1;
795       break;
796     case RTP_JITTER_BUFFER_MODE_SLAVE:
797     default:
798       break;
799   }
800
801   /* need resync, lock on to time and gstrtptime if we can, otherwise we
802    * do with the previous values */
803   if (G_UNLIKELY (jbuf->need_resync && dts != -1)) {
804     if (is_rtx) {
805       GST_DEBUG ("not resyncing on rtx packet, discard");
806       pts = GST_CLOCK_TIME_NONE;
807       goto done;
808     }
809     GST_INFO ("resync to time %" GST_TIME_FORMAT ", rtptime %"
810         GST_TIME_FORMAT, GST_TIME_ARGS (dts), GST_TIME_ARGS (gstrtptime));
811     rtp_jitter_buffer_resync (jbuf, dts, gstrtptime, ext_rtptime, FALSE);
812   }
813
814   GST_DEBUG ("extrtp %" G_GUINT64_FORMAT ", gstrtp %" GST_TIME_FORMAT ", base %"
815       GST_TIME_FORMAT ", send_diff %" GST_TIME_FORMAT, ext_rtptime,
816       GST_TIME_ARGS (gstrtptime), GST_TIME_ARGS (jbuf->base_rtptime),
817       GST_TIME_ARGS (gstrtptime - jbuf->base_rtptime));
818
819   rfc7273_mode = media_clock && pipeline_clock
820       && gst_clock_is_synced (media_clock);
821
822   if (rfc7273_mode && jbuf->mode == RTP_JITTER_BUFFER_MODE_SLAVE
823       && (media_clock_offset == -1 || !jbuf->rfc7273_sync)) {
824     GstClockTime internal, external;
825     GstClockTime rate_num, rate_denom;
826     GstClockTime nsrtptimediff, rtpntptime, rtpsystime;
827
828     gst_clock_get_calibration (media_clock, &internal, &external, &rate_num,
829         &rate_denom);
830
831     /* Slave to the RFC7273 media clock instead of trying to estimate it
832      * based on receive times and RTP timestamps */
833
834     if (jbuf->media_clock_base_time == -1) {
835       if (jbuf->base_time != -1) {
836         jbuf->media_clock_base_time =
837             gst_clock_unadjust_with_calibration (media_clock,
838             jbuf->base_time + base_time, internal, external, rate_num,
839             rate_denom);
840       } else {
841         if (dts != -1)
842           jbuf->media_clock_base_time =
843               gst_clock_unadjust_with_calibration (media_clock, dts + base_time,
844               internal, external, rate_num, rate_denom);
845         else
846           jbuf->media_clock_base_time =
847               gst_clock_get_internal_time (media_clock);
848         jbuf->base_rtptime = gstrtptime;
849       }
850     }
851
852     if (gstrtptime > jbuf->base_rtptime)
853       nsrtptimediff = gstrtptime - jbuf->base_rtptime;
854     else
855       nsrtptimediff = 0;
856
857     rtpntptime = nsrtptimediff + jbuf->media_clock_base_time;
858
859     rtpsystime =
860         gst_clock_adjust_with_calibration (media_clock, rtpntptime, internal,
861         external, rate_num, rate_denom);
862
863     if (rtpsystime > base_time)
864       pts = rtpsystime - base_time;
865     else
866       pts = 0;
867
868     GST_DEBUG ("RFC7273 clock time %" GST_TIME_FORMAT ", out %" GST_TIME_FORMAT,
869         GST_TIME_ARGS (rtpsystime), GST_TIME_ARGS (pts));
870   } else if (rfc7273_mode && (jbuf->mode == RTP_JITTER_BUFFER_MODE_SLAVE
871           || jbuf->mode == RTP_JITTER_BUFFER_MODE_SYNCED)
872       && media_clock_offset != -1 && jbuf->rfc7273_sync) {
873     GstClockTime ntptime, rtptime_tmp;
874     GstClockTime ntprtptime, rtpsystime;
875     GstClockTime internal, external;
876     GstClockTime rate_num, rate_denom;
877
878     /* Don't do any of the dts related adjustments further down */
879     dts = -1;
880
881     /* Calculate the actual clock time on the sender side based on the
882      * RFC7273 clock and convert it to our pipeline clock
883      */
884
885     gst_clock_get_calibration (media_clock, &internal, &external, &rate_num,
886         &rate_denom);
887
888     ntptime = gst_clock_get_internal_time (media_clock);
889
890     ntprtptime = gst_util_uint64_scale (ntptime, jbuf->clock_rate, GST_SECOND);
891     ntprtptime += media_clock_offset;
892     ntprtptime &= 0xffffffff;
893
894     rtptime_tmp = rtptime;
895     /* Check for wraparounds, we assume that the diff between current RTP
896      * timestamp and current media clock time can't be bigger than
897      * 2**31 clock units */
898     if (ntprtptime > rtptime_tmp && ntprtptime - rtptime_tmp >= 0x80000000)
899       rtptime_tmp += G_GUINT64_CONSTANT (0x100000000);
900     else if (rtptime_tmp > ntprtptime && rtptime_tmp - ntprtptime >= 0x80000000)
901       ntprtptime += G_GUINT64_CONSTANT (0x100000000);
902
903     if (ntprtptime > rtptime_tmp)
904       ntptime -=
905           gst_util_uint64_scale (ntprtptime - rtptime_tmp, GST_SECOND,
906           jbuf->clock_rate);
907     else
908       ntptime +=
909           gst_util_uint64_scale (rtptime_tmp - ntprtptime, GST_SECOND,
910           jbuf->clock_rate);
911
912     rtpsystime =
913         gst_clock_adjust_with_calibration (media_clock, ntptime, internal,
914         external, rate_num, rate_denom);
915     /* All this assumes that the pipeline has enough additional
916      * latency to cover for the network delay */
917     if (rtpsystime > base_time)
918       pts = rtpsystime - base_time;
919     else
920       pts = 0;
921
922     GST_DEBUG ("RFC7273 clock time %" GST_TIME_FORMAT ", out %" GST_TIME_FORMAT,
923         GST_TIME_ARGS (rtpsystime), GST_TIME_ARGS (pts));
924   } else {
925     /* If we used the RFC7273 clock before and not anymore,
926      * we need to resync it later again */
927     jbuf->media_clock_base_time = -1;
928
929     /* do skew calculation by measuring the difference between rtptime and the
930      * receive dts, this function will return the skew corrected rtptime. */
931     pts = calculate_skew (jbuf, ext_rtptime, gstrtptime, dts, gap, is_rtx);
932   }
933
934   /* check if timestamps are not going backwards, we can only check this if we
935    * have a previous out time and a previous send_diff */
936   if (G_LIKELY (pts != -1 && jbuf->prev_out_time != -1
937           && jbuf->prev_send_diff != -1)) {
938     /* now check for backwards timestamps */
939     if (G_UNLIKELY (
940             /* if the server timestamps went up and the out_time backwards */
941             (gstrtptime - jbuf->base_rtptime > jbuf->prev_send_diff
942                 && pts < jbuf->prev_out_time) ||
943             /* if the server timestamps went backwards and the out_time forwards */
944             (gstrtptime - jbuf->base_rtptime < jbuf->prev_send_diff
945                 && pts > jbuf->prev_out_time) ||
946             /* if the server timestamps did not change */
947             gstrtptime - jbuf->base_rtptime == jbuf->prev_send_diff)) {
948       GST_DEBUG ("backwards timestamps, using previous time");
949       pts = jbuf->prev_out_time;
950     }
951   }
952
953   if (gap == 0 && dts != -1 && pts + jbuf->delay < dts) {
954     /* if we are going to produce a timestamp that is later than the input
955      * timestamp, we need to reset the jitterbuffer. Likely the server paused
956      * temporarily */
957     GST_DEBUG ("out %" GST_TIME_FORMAT " + %" G_GUINT64_FORMAT " < time %"
958         GST_TIME_FORMAT ", reset jitterbuffer and discard", GST_TIME_ARGS (pts),
959         jbuf->delay, GST_TIME_ARGS (dts));
960     rtp_jitter_buffer_reset_skew (jbuf);
961     rtp_jitter_buffer_resync (jbuf, dts, gstrtptime, ext_rtptime, TRUE);
962     pts = dts;
963   }
964
965   jbuf->prev_out_time = pts;
966   jbuf->prev_send_diff = gstrtptime - jbuf->base_rtptime;
967
968 done:
969   if (media_clock)
970     gst_object_unref (media_clock);
971   if (pipeline_clock)
972     gst_object_unref (pipeline_clock);
973
974   return pts;
975 }
976
977
978 /**
979  * rtp_jitter_buffer_insert:
980  * @jbuf: an #RTPJitterBuffer
981  * @item: an #RTPJitterBufferItem to insert
982  * @head: TRUE when the head element changed.
983  * @percent: the buffering percent after insertion
984  *
985  * Inserts @item into the packet queue of @jbuf. The sequence number of the
986  * packet will be used to sort the packets. This function takes ownerhip of
987  * @buf when the function returns %TRUE.
988  *
989  * When @head is %TRUE, the new packet was added at the head of the queue and
990  * will be available with the next call to rtp_jitter_buffer_pop() and
991  * rtp_jitter_buffer_peek().
992  *
993  * Returns: %FALSE if a packet with the same number already existed.
994  */
995 static gboolean
996 rtp_jitter_buffer_insert (RTPJitterBuffer * jbuf, RTPJitterBufferItem * item,
997     gboolean * head, gint * percent)
998 {
999   GList *list, *event = NULL;
1000   guint16 seqnum;
1001
1002   g_return_val_if_fail (jbuf != NULL, FALSE);
1003   g_return_val_if_fail (item != NULL, FALSE);
1004
1005   list = jbuf->packets.tail;
1006
1007   /* no seqnum, simply append then */
1008   if (item->seqnum == -1)
1009     goto append;
1010
1011   seqnum = item->seqnum;
1012
1013   /* loop the list to skip strictly larger seqnum buffers */
1014   for (; list; list = g_list_previous (list)) {
1015     guint16 qseq;
1016     gint gap;
1017     RTPJitterBufferItem *qitem = (RTPJitterBufferItem *) list;
1018
1019     if (qitem->seqnum == -1) {
1020       /* keep a pointer to the first consecutive event if not already
1021        * set. we will insert the packet after the event if we can't find
1022        * a packet with lower sequence number before the event. */
1023       if (event == NULL)
1024         event = list;
1025       continue;
1026     }
1027
1028     qseq = qitem->seqnum;
1029
1030     /* compare the new seqnum to the one in the buffer */
1031     gap = gst_rtp_buffer_compare_seqnum (seqnum, qseq);
1032
1033     /* we hit a packet with the same seqnum, notify a duplicate */
1034     if (G_UNLIKELY (gap == 0))
1035       goto duplicate;
1036
1037     /* seqnum > qseq, we can stop looking */
1038     if (G_LIKELY (gap < 0))
1039       break;
1040
1041     /* if we've found a packet with greater sequence number, cleanup the
1042      * event pointer as the packet will be inserted before the event */
1043     event = NULL;
1044   }
1045
1046   /* if event is set it means that packets before the event had smaller
1047    * sequence number, so we will insert our packet after the event */
1048   if (event)
1049     list = event;
1050
1051 append:
1052   queue_do_insert (jbuf, list, (GList *) item);
1053
1054   /* buffering mode, update buffer stats */
1055   if (jbuf->mode == RTP_JITTER_BUFFER_MODE_BUFFER)
1056     update_buffer_level (jbuf, percent);
1057   else if (percent)
1058     *percent = -1;
1059
1060   /* head was changed when we did not find a previous packet, we set the return
1061    * flag when requested. */
1062   if (G_LIKELY (head))
1063     *head = (list == NULL);
1064
1065   return TRUE;
1066
1067   /* ERRORS */
1068 duplicate:
1069   {
1070     GST_DEBUG ("duplicate packet %d found", (gint) seqnum);
1071     if (G_LIKELY (head))
1072       *head = FALSE;
1073     if (percent)
1074       *percent = -1;
1075     return FALSE;
1076   }
1077 }
1078
1079 /**
1080  * rtp_jitter_buffer_alloc_item:
1081  * @data: The data stored in this item
1082  * @type: User specific item type
1083  * @dts: Decoding Timestamp
1084  * @pts: Presentation Timestamp
1085  * @seqnum: Sequence number
1086  * @count: Number of packet this item represent
1087  * @rtptime: The RTP specific timestamp
1088  * @free_data: A function to free @data (optional)
1089  *
1090  * Create an item that can then be stored in the jitter buffer.
1091  *
1092  * Returns: a newly allocated RTPJitterbufferItem
1093  */
1094 static RTPJitterBufferItem *
1095 rtp_jitter_buffer_alloc_item (gpointer data, guint type, GstClockTime dts,
1096     GstClockTime pts, guint seqnum, guint count, guint rtptime,
1097     GDestroyNotify free_data)
1098 {
1099   RTPJitterBufferItem *item;
1100
1101   item = g_slice_new (RTPJitterBufferItem);
1102   item->data = data;
1103   item->next = NULL;
1104   item->prev = NULL;
1105   item->type = type;
1106   item->dts = dts;
1107   item->pts = pts;
1108   item->seqnum = seqnum;
1109   item->count = count;
1110   item->rtptime = rtptime;
1111   item->free_data = free_data;
1112
1113   return item;
1114 }
1115
1116 static inline RTPJitterBufferItem *
1117 alloc_event_item (GstEvent * event)
1118 {
1119   return rtp_jitter_buffer_alloc_item (event, ITEM_TYPE_EVENT, -1, -1, -1, 0,
1120       -1, (GDestroyNotify) gst_mini_object_unref);
1121 }
1122
1123 /**
1124  * rtp_jitter_buffer_append_event:
1125  * @jbuf: an #RTPJitterBuffer
1126  * @event: an #GstEvent to insert
1127
1128  * Inserts @event into the packet queue of @jbuf.
1129  *
1130  * Returns: %TRUE if the event is at the head of the queue
1131  */
1132 gboolean
1133 rtp_jitter_buffer_append_event (RTPJitterBuffer * jbuf, GstEvent * event)
1134 {
1135   RTPJitterBufferItem *item = alloc_event_item (event);
1136   gboolean head;
1137   rtp_jitter_buffer_insert (jbuf, item, &head, NULL);
1138   return head;
1139 }
1140
1141 /**
1142  * rtp_jitter_buffer_append_query:
1143  * @jbuf: an #RTPJitterBuffer
1144  * @query: an #GstQuery to insert
1145
1146  * Inserts @query into the packet queue of @jbuf.
1147  *
1148  * Returns: %TRUE if the query is at the head of the queue
1149  */
1150 gboolean
1151 rtp_jitter_buffer_append_query (RTPJitterBuffer * jbuf, GstQuery * query)
1152 {
1153   RTPJitterBufferItem *item =
1154       rtp_jitter_buffer_alloc_item (query, ITEM_TYPE_QUERY, -1, -1, -1, 0, -1,
1155       NULL);
1156   gboolean head;
1157   rtp_jitter_buffer_insert (jbuf, item, &head, NULL);
1158   return head;
1159 }
1160
1161 /**
1162  * rtp_jitter_buffer_append_lost_event:
1163  * @jbuf: an #RTPJitterBuffer
1164  * @event: an #GstEvent to insert
1165  * @seqnum: Sequence number
1166  * @lost_packets: Number of lost packet this item represent
1167
1168  * Inserts @event into the packet queue of @jbuf.
1169  *
1170  * Returns: %TRUE if the event is at the head of the queue
1171  */
1172 gboolean
1173 rtp_jitter_buffer_append_lost_event (RTPJitterBuffer * jbuf, GstEvent * event,
1174     guint16 seqnum, guint lost_packets)
1175 {
1176   RTPJitterBufferItem *item = rtp_jitter_buffer_alloc_item (event,
1177       ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1,
1178       (GDestroyNotify) gst_mini_object_unref);
1179   gboolean head;
1180
1181   if (!rtp_jitter_buffer_insert (jbuf, item, &head, NULL)) {
1182     /* Duplicate */
1183     rtp_jitter_buffer_free_item (item);
1184     head = FALSE;
1185   }
1186
1187   return head;
1188 }
1189
1190 /**
1191  * rtp_jitter_buffer_append_buffer:
1192  * @jbuf: an #RTPJitterBuffer
1193  * @buf: an #GstBuffer to insert
1194  * @seqnum: Sequence number
1195  * @duplicate: TRUE when the packet inserted is a duplicate
1196  * @percent: the buffering percent after insertion
1197  *
1198  * Inserts @buf into the packet queue of @jbuf.
1199  *
1200  * Returns: %TRUE if the buffer is at the head of the queue
1201  */
1202 gboolean
1203 rtp_jitter_buffer_append_buffer (RTPJitterBuffer * jbuf, GstBuffer * buf,
1204     GstClockTime dts, GstClockTime pts, guint16 seqnum, guint rtptime,
1205     gboolean * duplicate, gint * percent)
1206 {
1207   RTPJitterBufferItem *item = rtp_jitter_buffer_alloc_item (buf,
1208       ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime,
1209       (GDestroyNotify) gst_mini_object_unref);
1210   gboolean head;
1211   gboolean inserted;
1212
1213   inserted = rtp_jitter_buffer_insert (jbuf, item, &head, percent);
1214   if (!inserted)
1215     rtp_jitter_buffer_free_item (item);
1216
1217   if (duplicate)
1218     *duplicate = !inserted;
1219
1220   return head;
1221 }
1222
1223 /**
1224  * rtp_jitter_buffer_pop:
1225  * @jbuf: an #RTPJitterBuffer
1226  * @percent: the buffering percent
1227  *
1228  * Pops the oldest buffer from the packet queue of @jbuf. The popped buffer will
1229  * have its timestamp adjusted with the incoming running_time and the detected
1230  * clock skew.
1231  *
1232  * Returns: a #GstBuffer or %NULL when there was no packet in the queue.
1233  */
1234 RTPJitterBufferItem *
1235 rtp_jitter_buffer_pop (RTPJitterBuffer * jbuf, gint * percent)
1236 {
1237   GList *item = NULL;
1238   GQueue *queue;
1239
1240   g_return_val_if_fail (jbuf != NULL, NULL);
1241
1242   queue = &jbuf->packets;
1243
1244   item = queue->head;
1245   if (item) {
1246     queue->head = item->next;
1247     if (queue->head)
1248       queue->head->prev = NULL;
1249     else
1250       queue->tail = NULL;
1251     queue->length--;
1252   }
1253
1254   /* buffering mode, update buffer stats */
1255   if (jbuf->mode == RTP_JITTER_BUFFER_MODE_BUFFER)
1256     update_buffer_level (jbuf, percent);
1257   else if (percent)
1258     *percent = -1;
1259
1260   /* let's clear the pointers so we can ensure we don't free items that are
1261    * still in the jitterbuffer */
1262   item->next = item->prev = NULL;
1263
1264   return (RTPJitterBufferItem *) item;
1265 }
1266
1267 /**
1268  * rtp_jitter_buffer_peek:
1269  * @jbuf: an #RTPJitterBuffer
1270  *
1271  * Peek the oldest buffer from the packet queue of @jbuf.
1272  *
1273  * See rtp_jitter_buffer_insert() to check when an older packet was
1274  * added.
1275  *
1276  * Returns: a #GstBuffer or %NULL when there was no packet in the queue.
1277  */
1278 RTPJitterBufferItem *
1279 rtp_jitter_buffer_peek (RTPJitterBuffer * jbuf)
1280 {
1281   g_return_val_if_fail (jbuf != NULL, NULL);
1282
1283   return (RTPJitterBufferItem *) jbuf->packets.head;
1284 }
1285
1286 /**
1287  * rtp_jitter_buffer_flush:
1288  * @jbuf: an #RTPJitterBuffer
1289  * @free_func: function to free each item (optional)
1290  * @user_data: user data passed to @free_func
1291  *
1292  * Flush all packets from the jitterbuffer.
1293  */
1294 void
1295 rtp_jitter_buffer_flush (RTPJitterBuffer * jbuf, GFunc free_func,
1296     gpointer user_data)
1297 {
1298   GList *item;
1299
1300   g_return_if_fail (jbuf != NULL);
1301
1302   if (free_func == NULL)
1303     free_func = (GFunc) rtp_jitter_buffer_free_item;
1304
1305   while ((item = g_queue_pop_head_link (&jbuf->packets)))
1306     free_func ((RTPJitterBufferItem *) item, user_data);
1307 }
1308
1309 /**
1310  * rtp_jitter_buffer_is_buffering:
1311  * @jbuf: an #RTPJitterBuffer
1312  *
1313  * Check if @jbuf is buffering currently. Users of the jitterbuffer should not
1314  * pop packets while in buffering mode.
1315  *
1316  * Returns: the buffering state of @jbuf
1317  */
1318 gboolean
1319 rtp_jitter_buffer_is_buffering (RTPJitterBuffer * jbuf)
1320 {
1321   return jbuf->buffering && !jbuf->buffering_disabled;
1322 }
1323
1324 /**
1325  * rtp_jitter_buffer_set_buffering:
1326  * @jbuf: an #RTPJitterBuffer
1327  * @buffering: the new buffering state
1328  *
1329  * Forces @jbuf to go into the buffering state.
1330  */
1331 void
1332 rtp_jitter_buffer_set_buffering (RTPJitterBuffer * jbuf, gboolean buffering)
1333 {
1334   jbuf->buffering = buffering;
1335 }
1336
1337 /**
1338  * rtp_jitter_buffer_get_percent:
1339  * @jbuf: an #RTPJitterBuffer
1340  *
1341  * Get the buffering percent of the jitterbuffer.
1342  *
1343  * Returns: the buffering percent
1344  */
1345 gint
1346 rtp_jitter_buffer_get_percent (RTPJitterBuffer * jbuf)
1347 {
1348   gint percent;
1349   guint64 level;
1350
1351   if (G_UNLIKELY (jbuf->high_level == 0))
1352     return 100;
1353
1354   if (G_UNLIKELY (jbuf->buffering_disabled))
1355     return 100;
1356
1357   level = get_buffer_level (jbuf);
1358   percent = (level * 100 / jbuf->high_level);
1359   percent = MIN (percent, 100);
1360
1361   return percent;
1362 }
1363
1364 /**
1365  * rtp_jitter_buffer_num_packets:
1366  * @jbuf: an #RTPJitterBuffer
1367  *
1368  * Get the number of packets currently in "jbuf.
1369  *
1370  * Returns: The number of packets in @jbuf.
1371  */
1372 guint
1373 rtp_jitter_buffer_num_packets (RTPJitterBuffer * jbuf)
1374 {
1375   g_return_val_if_fail (jbuf != NULL, 0);
1376
1377   return jbuf->packets.length;
1378 }
1379
1380 /**
1381  * rtp_jitter_buffer_get_ts_diff:
1382  * @jbuf: an #RTPJitterBuffer
1383  *
1384  * Get the difference between the timestamps of first and last packet in the
1385  * jitterbuffer.
1386  *
1387  * Returns: The difference expressed in the timestamp units of the packets.
1388  */
1389 guint32
1390 rtp_jitter_buffer_get_ts_diff (RTPJitterBuffer * jbuf)
1391 {
1392   guint64 high_ts, low_ts;
1393   RTPJitterBufferItem *high_buf, *low_buf;
1394   guint32 result;
1395
1396   g_return_val_if_fail (jbuf != NULL, 0);
1397
1398   high_buf = (RTPJitterBufferItem *) g_queue_peek_tail_link (&jbuf->packets);
1399   low_buf = (RTPJitterBufferItem *) g_queue_peek_head_link (&jbuf->packets);
1400
1401   if (!high_buf || !low_buf || high_buf == low_buf)
1402     return 0;
1403
1404   high_ts = high_buf->rtptime;
1405   low_ts = low_buf->rtptime;
1406
1407   /* it needs to work if ts wraps */
1408   if (high_ts >= low_ts) {
1409     result = (guint32) (high_ts - low_ts);
1410   } else {
1411     result = (guint32) (high_ts + G_MAXUINT32 + 1 - low_ts);
1412   }
1413   return result;
1414 }
1415
1416
1417 /*
1418  * rtp_jitter_buffer_get_seqnum_diff:
1419  * @jbuf: an #RTPJitterBuffer
1420  *
1421  * Get the difference between the seqnum of first and last packet in the
1422  * jitterbuffer.
1423  *
1424  * Returns: The difference expressed in seqnum.
1425  */
1426 static guint16
1427 rtp_jitter_buffer_get_seqnum_diff (RTPJitterBuffer * jbuf)
1428 {
1429   guint32 high_seqnum, low_seqnum;
1430   RTPJitterBufferItem *high_buf, *low_buf;
1431   guint16 result;
1432
1433   g_return_val_if_fail (jbuf != NULL, 0);
1434
1435   high_buf = (RTPJitterBufferItem *) g_queue_peek_tail_link (&jbuf->packets);
1436   low_buf = (RTPJitterBufferItem *) g_queue_peek_head_link (&jbuf->packets);
1437
1438   while (high_buf && high_buf->seqnum == -1)
1439     high_buf = (RTPJitterBufferItem *) high_buf->prev;
1440
1441   while (low_buf && low_buf->seqnum == -1)
1442     low_buf = (RTPJitterBufferItem *) low_buf->next;
1443
1444   if (!high_buf || !low_buf || high_buf == low_buf)
1445     return 0;
1446
1447   high_seqnum = high_buf->seqnum;
1448   low_seqnum = low_buf->seqnum;
1449
1450   /* it needs to work if ts wraps */
1451   if (high_seqnum >= low_seqnum) {
1452     result = (guint32) (high_seqnum - low_seqnum);
1453   } else {
1454     result = (guint32) (high_seqnum + G_MAXUINT16 + 1 - low_seqnum);
1455   }
1456   return result;
1457 }
1458
1459 /**
1460  * rtp_jitter_buffer_get_sync:
1461  * @jbuf: an #RTPJitterBuffer
1462  * @rtptime: result RTP time
1463  * @timestamp: result GStreamer timestamp
1464  * @clock_rate: clock-rate of @rtptime
1465  * @last_rtptime: last seen rtptime.
1466  *
1467  * Calculates the relation between the RTP timestamp and the GStreamer timestamp
1468  * used for constructing timestamps.
1469  *
1470  * For extended RTP timestamp @rtptime with a clock-rate of @clock_rate,
1471  * the GStreamer timestamp is currently @timestamp.
1472  *
1473  * The last seen extended RTP timestamp with clock-rate @clock-rate is returned in
1474  * @last_rtptime.
1475  */
1476 void
1477 rtp_jitter_buffer_get_sync (RTPJitterBuffer * jbuf, guint64 * rtptime,
1478     guint64 * timestamp, guint32 * clock_rate, guint64 * last_rtptime)
1479 {
1480   if (rtptime)
1481     *rtptime = jbuf->base_extrtp;
1482   if (timestamp)
1483     *timestamp = jbuf->base_time + jbuf->skew;
1484   if (clock_rate)
1485     *clock_rate = jbuf->clock_rate;
1486   if (last_rtptime)
1487     *last_rtptime = jbuf->last_rtptime;
1488 }
1489
1490 /**
1491  * rtp_jitter_buffer_can_fast_start:
1492  * @jbuf: an #RTPJitterBuffer
1493  * @num_packets: Number of consecutive packets needed
1494  *
1495  * Check if in the queue if there is enough packets with consecutive seqnum in
1496  * order to start delivering them.
1497  *
1498  * Returns: %TRUE if the required number of consecutive packets was found.
1499  */
1500 gboolean
1501 rtp_jitter_buffer_can_fast_start (RTPJitterBuffer * jbuf, gint num_packet)
1502 {
1503   gboolean ret = TRUE;
1504   RTPJitterBufferItem *last_item = NULL, *item;
1505   gint i;
1506
1507   if (rtp_jitter_buffer_num_packets (jbuf) < num_packet)
1508     return FALSE;
1509
1510   item = rtp_jitter_buffer_peek (jbuf);
1511   for (i = 0; i < num_packet; i++) {
1512     if (G_LIKELY (last_item)) {
1513       guint16 expected_seqnum = last_item->seqnum + 1;
1514
1515       if (expected_seqnum != item->seqnum) {
1516         ret = FALSE;
1517         break;
1518       }
1519     }
1520
1521     last_item = item;
1522     item = (RTPJitterBufferItem *) last_item->next;
1523   }
1524
1525   return ret;
1526 }
1527
1528 gboolean
1529 rtp_jitter_buffer_is_full (RTPJitterBuffer * jbuf)
1530 {
1531   return rtp_jitter_buffer_get_seqnum_diff (jbuf) >= 32765 &&
1532       rtp_jitter_buffer_num_packets (jbuf) > 10000;
1533 }
1534
1535
1536 /**
1537  * rtp_jitter_buffer_free_item:
1538  * @item: the item to be freed
1539  *
1540  * Free the jitter buffer item.
1541  */
1542 void
1543 rtp_jitter_buffer_free_item (RTPJitterBufferItem * item)
1544 {
1545   g_return_if_fail (item != NULL);
1546   /* needs to be unlinked first */
1547   g_return_if_fail (item->next == NULL);
1548   g_return_if_fail (item->prev == NULL);
1549
1550   if (item->data && item->free_data)
1551     item->free_data (item->data);
1552   g_slice_free (RTPJitterBufferItem, item);
1553 }