2 * jitterbuf: an application-independent jitterbuffer
5 * Copyright (C) 2004-2005, Horizon Wimba, Inc.
8 * Steve Kann <stevek@stevek.com>
10 * This program is free software, distributed under the terms of
11 * the GNU Lesser (Library) General Public License
13 * Copyright on this file is disclaimed to Digium for inclusion in Asterisk
20 #include "jitterbuf.h"
22 /* define these here, just for ancient compiler systems */
23 #define JB_LONGMAX 2147483647L
24 #define JB_LONGMIN (-JB_LONGMAX - 1L)
26 #define jb_warn(...) (warnf ? warnf(__VA_ARGS__) : (void)0)
27 #define jb_err(...) (errf ? errf(__VA_ARGS__) : (void)0)
28 #define jb_dbg(...) (dbgf ? dbgf(__VA_ARGS__) : (void)0)
31 #define jb_dbg2(...) (dbgf ? dbgf(__VA_ARGS__) : (void)0)
33 #define jb_dbg2(...) ((void)0)
36 static jb_output_function_t warnf, errf, dbgf;
38 void jb_setoutput(jb_output_function_t warn, jb_output_function_t err, jb_output_function_t dbg)
45 static void increment_losspct(jitterbuf *jb)
47 jb->info.losspct = (100000 + 499 * jb->info.losspct)/500;
50 static void decrement_losspct(jitterbuf *jb)
52 jb->info.losspct = (499 * jb->info.losspct)/500;
55 void jb_reset(jitterbuf *jb)
57 memset(jb,0,sizeof(jitterbuf));
59 /* initialize length */
60 jb->info.current = jb->info.target = JB_TARGET_EXTRA;
61 jb->info.silence_begin_ts = -1;
69 jb = malloc(sizeof(jitterbuf));
75 jb_dbg2("jb_new() = %x\n", jb);
79 void jb_destroy(jitterbuf *jb)
82 jb_dbg2("jb_destroy(%x)\n", jb);
84 /* free all the frames on the "free list" */
86 while (frame != NULL) {
87 jb_frame *next = frame->next;
98 /* simple history manipulation */
99 /* maybe later we can make the history buckets variable size, or something? */
100 /* drop parameter determines whether we will drop outliers to minimize
103 static int longcmp(const void *a, const void *b)
105 return *(long *)a - *(long *)b;
109 static int history_put(jitterbuf *jb, long ts, long now, long ms)
111 long delay = now - (ts - jb->info.resync_offset);
112 long threshold = 2 * jb->info.jitter + jb->info.resync_threshold;
115 /* don't add special/negative times to history */
119 /* check for drastic change in delay */
120 if (jb->info.resync_threshold != -1) {
121 if (abs(delay - jb->info.last_delay) > threshold) {
122 jb->info.cnt_delay_discont++;
123 if (jb->info.cnt_delay_discont > 3) {
124 /* resync the jitterbuffer */
125 jb->info.cnt_delay_discont = 0;
127 jb->hist_maxbuf_valid = 0;
129 jb_warn("Resyncing the jb. last_delay %ld, this delay %ld, threshold %ld, new offset %ld\n", jb->info.last_delay, delay, threshold, ts - now);
130 jb->info.resync_offset = ts - now;
131 jb->info.last_delay = 0; /* after resync, frame is right on time */
136 jb->info.last_delay = delay;
137 jb->info.cnt_delay_discont = 0;
141 kicked = jb->history[jb->hist_ptr & JB_HISTORY_SZ];
143 jb->history[(jb->hist_ptr++) % JB_HISTORY_SZ] = delay;
145 /* optimization; the max/min buffers don't need to be recalculated, if this packet's
146 * entry doesn't change them. This happens if this packet is not involved, _and_ any packet
147 * that got kicked out of the history is also not involved
148 * We do a number of comparisons, but it's probably still worthwhile, because it will usually
149 * succeed, and should be a lot faster than going through all 500 packets in history */
150 if (!jb->hist_maxbuf_valid)
153 /* don't do this until we've filled history
154 * (reduces some edge cases below) */
155 if (jb->hist_ptr < JB_HISTORY_SZ)
158 /* if the new delay would go into min */
159 if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1])
163 if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1])
166 /* or the kicked delay would be in min */
167 if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1])
170 if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1])
173 /* if we got here, we don't need to invalidate, 'cause this delay didn't
176 /* end optimization */
180 jb->hist_maxbuf_valid = 0;
184 static void history_calc_maxbuf(jitterbuf *jb)
188 if (jb->hist_ptr == 0)
192 /* initialize maxbuf/minbuf to the latest value */
193 for (i=0;i<JB_HISTORY_MAXBUF_SZ;i++) {
195 * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ];
196 * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ];
198 jb->hist_maxbuf[i] = JB_LONGMIN;
199 jb->hist_minbuf[i] = JB_LONGMAX;
202 /* use insertion sort to populate maxbuf */
203 /* we want it to be the top "n" values, in order */
205 /* start at the beginning, or JB_HISTORY_SZ frames ago */
206 i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0;
208 for (;i<jb->hist_ptr;i++) {
209 long toins = jb->history[i % JB_HISTORY_SZ];
211 /* if the maxbuf should get this */
212 if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) {
214 /* insertion-sort it into the maxbuf */
215 for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) {
216 /* found where it fits */
217 if (toins > jb->hist_maxbuf[j]) {
219 memmove(jb->hist_maxbuf+j+1,jb->hist_maxbuf+j, (JB_HISTORY_MAXBUF_SZ-(j+1)) * sizeof(long));
221 jb->hist_maxbuf[j] = toins;
228 /* if the minbuf should get this */
229 if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) {
231 /* insertion-sort it into the maxbuf */
232 for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) {
233 /* found where it fits */
234 if (toins < jb->hist_minbuf[j]) {
236 memmove(jb->hist_minbuf+j+1,jb->hist_minbuf+j, (JB_HISTORY_MAXBUF_SZ-(j+1)) * sizeof(long));
238 jb->hist_minbuf[j] = toins;
247 fprintf(stderr, "toins = %ld\n", toins);
248 fprintf(stderr, "maxbuf =");
249 for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++)
250 fprintf(stderr, "%ld ", jb->hist_maxbuf[k]);
251 fprintf(stderr, "\nminbuf =");
252 for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++)
253 fprintf(stderr, "%ld ", jb->hist_minbuf[k]);
254 fprintf(stderr, "\n");
258 jb->hist_maxbuf_valid = 1;
261 static void history_get(jitterbuf *jb)
263 long max, min, jitter;
267 if (!jb->hist_maxbuf_valid)
268 history_calc_maxbuf(jb);
270 /* count is how many items in history we're examining */
271 count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ;
273 /* index is the "n"ths highest/lowest that we'll look for */
274 index = count * JB_HISTORY_DROPPCT / 100;
276 /* sanity checks for index */
277 if (index > (JB_HISTORY_MAXBUF_SZ - 1))
278 index = JB_HISTORY_MAXBUF_SZ - 1;
287 max = jb->hist_maxbuf[index];
288 min = jb->hist_minbuf[index];
292 /* these debug stmts compare the difference between looking at the absolute jitter, and the
293 * values we get by throwing away the outliers */
295 fprintf(stderr, "[%d] min=%d, max=%d, jitter=%d\n", index, min, max, jitter);
296 fprintf(stderr, "[%d] min=%d, max=%d, jitter=%d\n", 0, jb->hist_minbuf[0], jb->hist_maxbuf[0], jb->hist_maxbuf[0]-jb->hist_minbuf[0]);
300 jb->info.jitter = jitter;
303 /* returns 1 if frame was inserted into head of queue, 0 otherwise */
304 static int queue_put(jitterbuf *jb, void *data, int type, long ms, long ts)
309 long resync_ts = ts - jb->info.resync_offset;
313 jb->free = frame->next;
315 frame = malloc(sizeof(jb_frame));
319 jb_err("cannot allocate frame\n");
323 jb->info.frames_cur++;
326 frame->ts = resync_ts;
331 * frames are a circular list, jb-frames points to to the lowest ts,
332 * jb->frames->prev points to the highest ts
335 if (!jb->frames) { /* queue is empty */
340 } else if (resync_ts < jb->frames->ts) {
341 frame->next = jb->frames;
342 frame->prev = jb->frames->prev;
344 frame->next->prev = frame;
345 frame->prev->next = frame;
347 /* frame is out of order */
348 jb->info.frames_ooo++;
355 /* frame is out of order */
356 if (resync_ts < p->prev->ts) jb->info.frames_ooo++;
358 while (resync_ts < p->prev->ts && p->prev != jb->frames)
362 frame->prev = p->prev;
364 frame->next->prev = frame;
365 frame->prev->next = frame;
370 static long queue_next(jitterbuf *jb)
373 return jb->frames->ts;
378 static long queue_last(jitterbuf *jb)
381 return jb->frames->prev->ts;
386 static jb_frame *_queue_get(jitterbuf *jb, long ts, int all)
394 /*jb_warn("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); */
396 if (all || ts >= frame->ts) {
397 /* remove this frame */
398 frame->prev->next = frame->next;
399 frame->next->prev = frame->prev;
401 if (frame->next == frame)
404 jb->frames = frame->next;
407 /* insert onto "free" single-linked list */
408 frame->next = jb->free;
411 jb->info.frames_cur--;
413 /* we return the frame pointer, even though it's on free list,
414 * but caller must copy data */
421 static jb_frame *queue_get(jitterbuf *jb, long ts)
423 return _queue_get(jb,ts,0);
426 static jb_frame *queue_getall(jitterbuf *jb)
428 return _queue_get(jb,0,1);
432 /* some diagnostics */
433 static void jb_dbginfo(jitterbuf *jb)
438 jb_dbg("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n",
439 jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur);
441 jb_dbg("jitter=%ld current=%ld target=%ld min=%ld sil=%d len=%d len/fcur=%ld\n",
442 jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min,
443 jb->info.frames_cur ? (jb->info.current - jb->info.min)/jb->info.frames_cur : -8);
444 if (jb->info.frames_in > 0)
445 jb_dbg("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n",
446 jb->info.frames_lost * 100/(jb->info.frames_in + jb->info.frames_lost),
447 jb->info.frames_late * 100/jb->info.frames_in);
448 jb_dbg("jb info: queue %d -> %d. last_ts %d (queue len: %d) last_ms %d\n",
451 jb->info.next_voice_ts,
452 queue_last(jb) - queue_next(jb),
453 jb->info.last_voice_ms);
458 static void jb_chkqueue(jitterbuf *jb)
461 jb_frame *p = jb->frames;
468 if (p->next == NULL) {
469 jb_err("Queue is BROKEN at item [%d]", i);
473 } while (p->next != jb->frames);
476 static void jb_dbgqueue(jitterbuf *jb)
479 jb_frame *p = jb->frames;
489 jb_dbg("[%d]=%ld ", i++, p->ts);
491 } while (p->next != jb->frames);
497 int jb_put(jitterbuf *jb, void *data, int type, long ms, long ts, long now)
499 jb_dbg2("jb_put(%x,%x,%ld,%ld,%ld)\n", jb, data, ms, ts, now);
501 jb->info.frames_in++;
503 if (type == JB_TYPE_VOICE) {
504 /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the
505 * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */
506 if (history_put(jb,ts,now,ms))
510 /* if put into head of queue, caller needs to reschedule */
511 if (queue_put(jb,data,type,ms,ts)) {
518 static int _jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl)
523 /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */
524 /* get jitter info */
529 jb->info.target = jb->info.jitter + jb->info.min + JB_TARGET_EXTRA;
531 /* if a hard clamp was requested, use it */
532 if ((jb->info.max_jitterbuf) && ((jb->info.target - jb->info.min) > jb->info.max_jitterbuf)) {
533 jb_dbg("clamping target from %d to %d\n", (jb->info.target - jb->info.min), jb->info.max_jitterbuf);
534 jb->info.target = jb->info.min + jb->info.max_jitterbuf;
537 diff = jb->info.target - jb->info.current;
539 /* jb_warn("diff = %d lms=%d last = %d now = %d\n", diff, */
540 /* jb->info.last_voice_ms, jb->info.last_adjustment, now); */
542 /* let's work on non-silent case first */
543 if (!jb->info.silence_begin_ts) {
544 /* we want to grow */
546 /* we haven't grown in the delay length */
547 (((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) ||
548 /* we need to grow more than the "length" we have left */
549 (diff > queue_last(jb) - queue_next(jb)) ) ) {
550 /* grow by interp frame length */
551 jb->info.current += interpl;
552 jb->info.next_voice_ts += interpl;
553 jb->info.last_voice_ms = interpl;
554 jb->info.last_adjustment = now;
559 frame = queue_get(jb, jb->info.next_voice_ts - jb->info.current);
561 /* not a voice frame; just return it. */
562 if (frame && frame->type != JB_TYPE_VOICE) {
563 if (frame->type == JB_TYPE_SILENCE)
564 jb->info.silence_begin_ts = frame->ts;
567 jb->info.frames_out++;
573 /* voice frame is later than expected */
574 if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) {
575 if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) {
576 /* either we interpolated past this frame in the last jb_get */
577 /* or the frame is still in order, but came a little too quick */
579 /* reset expectation for next frame */
580 jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms;
581 jb->info.frames_out++;
582 decrement_losspct(jb);
586 /* voice frame is late */
588 jb->info.frames_out++;
589 decrement_losspct(jb);
590 jb->info.frames_late++;
591 jb->info.frames_lost--;
593 /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb));
599 /* keep track of frame sizes, to allow for variable sized-frames */
600 if (frame && frame->ms > 0) {
601 jb->info.last_voice_ms = frame->ms;
604 /* we want to shrink; shrink at 1 frame / 500ms */
605 /* unless we don't have a frame, then shrink 1 frame */
606 /* every 80ms (though perhaps we can shrink even faster */
608 if (diff < -JB_TARGET_EXTRA &&
609 ((!frame && jb->info.last_adjustment + 80 < now) ||
610 (jb->info.last_adjustment + 500 < now))) {
612 jb->info.last_adjustment = now;
616 /* shrink by frame size we're throwing out */
617 jb->info.current -= frame->ms;
618 jb->info.frames_out++;
619 decrement_losspct(jb);
620 jb->info.frames_dropped++;
624 /* shrink by last_voice_ms */
625 jb->info.current -= jb->info.last_voice_ms;
626 jb->info.frames_lost++;
627 increment_losspct(jb);
635 /* this is a bit of a hack for now, but if we're close to
636 * target, and we find a missing frame, it makes sense to
637 * grow, because the frame might just be a bit late;
638 * otherwise, we presently get into a pattern where we return
639 * INTERP for the lost frame, then it shows up next, and we
640 * throw it away because it's late */
641 /* I've recently only been able to replicate this using
642 * iaxclient talking to app_echo on asterisk. In this case,
643 * my outgoing packets go through asterisk's (old)
644 * jitterbuffer, and then might get an unusual increasing delay
645 * there if it decides to grow?? */
646 /* Update: that might have been a different bug, that has been fixed..
647 * But, this still seemed like a good idea, except that it ended up making a single actual
648 * lost frame get interpolated two or more times, when there was "room" to grow, so it might
649 * be a bit of a bad idea overall */
650 /*if (diff > -1 * jb->info.last_voice_ms) {
651 jb->info.current += jb->info.last_voice_ms;
652 jb->info.last_adjustment = now;
656 jb->info.frames_lost++;
657 increment_losspct(jb);
658 jb->info.next_voice_ts += interpl;
659 jb->info.last_voice_ms = interpl;
664 /* normal case; return the frame, increment stuff */
666 jb->info.next_voice_ts += frame->ms;
667 jb->info.frames_out++;
668 decrement_losspct(jb);
672 /* TODO: after we get the non-silent case down, we'll make the
673 * silent case -- basically, we'll just grow and shrink faster
674 * here, plus handle next_voice_ts a bit differently */
676 /* to disable silent special case altogether, just uncomment this: */
677 /* jb->info.silence_begin_ts = 0; */
679 /* shrink interpl len every 10ms during silence */
680 if (diff < -JB_TARGET_EXTRA &&
681 jb->info.last_adjustment + 10 <= now) {
682 jb->info.current -= interpl;
683 jb->info.last_adjustment = now;
686 frame = queue_get(jb, now - jb->info.current);
689 } else if (frame->type != JB_TYPE_VOICE) {
690 /* normal case; in silent mode, got a non-voice frame */
692 jb->info.frames_out++;
695 if (frame->ts < jb->info.silence_begin_ts) {
696 /* voice frame is late */
698 jb->info.frames_out++;
699 decrement_losspct(jb);
700 jb->info.frames_late++;
701 jb->info.frames_lost--;
703 /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb));
708 /* try setting current to target right away here */
709 jb->info.current = jb->info.target;
710 jb->info.silence_begin_ts = 0;
711 jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms;
712 jb->info.last_voice_ms = frame->ms;
713 jb->info.frames_out++;
714 decrement_losspct(jb);
722 long jb_next(jitterbuf *jb)
724 if (jb->info.silence_begin_ts) {
725 long next = queue_next(jb);
728 /* shrink during silence */
729 if (jb->info.target - jb->info.current < -JB_TARGET_EXTRA)
730 return jb->info.last_adjustment + 10;
731 return next + jb->info.target;
736 return jb->info.next_voice_ts;
740 int jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl)
742 int ret = _jb_get(jb,frameout,now,interpl);
745 int thists = ((ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0;
746 jb_warn("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists);
747 if (thists && thists < lastts) jb_warn("XXXX timestamp roll-back!!!\n");
751 frameout->ms = jb->info.last_voice_ms;
756 int jb_getall(jitterbuf *jb, jb_frame *frameout)
759 frame = queue_getall(jb);
770 int jb_getinfo(jitterbuf *jb, jb_info *stats)
780 int jb_setinfo(jitterbuf *jb, jb_info *settings)
782 /* take selected settings from the struct */
784 jb->info.max_jitterbuf = settings->max_jitterbuf;
785 jb->info.resync_threshold = settings->resync_threshold;