2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2004-2005, Horizon Wimba, Inc.
7 * Steve Kann <stevek@stevek.com>
9 * Copyright on this file is disclaimed to Digium for inclusion in Asterisk
11 * See http://www.asterisk.org for more information about
12 * the Asterisk project. Please do not directly contact
13 * any of the maintainers of this project for assistance;
14 * the project provides a web site, mailing lists and IRC
15 * channels for your use.
17 * This program is free software, distributed under the terms of
18 * the GNU General Public License Version 2. See the LICENSE file
19 * at the top of the source tree.
24 * \brief jitterbuf: an application-independent jitterbuffer
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36 #include "jitterbuf.h"
38 /* define these here, just for ancient compiler systems */
39 #define JB_LONGMAX 2147483647L
40 #define JB_LONGMIN (-JB_LONGMAX - 1L)
42 #define jb_warn(...) (warnf ? warnf(__VA_ARGS__) : (void)0)
43 #define jb_err(...) (errf ? errf(__VA_ARGS__) : (void)0)
44 #define jb_dbg(...) (dbgf ? dbgf(__VA_ARGS__) : (void)0)
47 #define jb_dbg2(...) (dbgf ? dbgf(__VA_ARGS__) : (void)0)
49 #define jb_dbg2(...) ((void)0)
52 static jb_output_function_t warnf, errf, dbgf;
54 void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg)
61 static void increment_losspct(jitterbuf *jb)
63 jb->info.losspct = (100000 + 499 * jb->info.losspct)/500;
66 static void decrement_losspct(jitterbuf *jb)
68 jb->info.losspct = (499 * jb->info.losspct)/500;
71 void jb_reset(jitterbuf *jb)
73 /* only save settings */
74 jb_conf s = jb->info.conf;
75 memset(jb,0,sizeof(jitterbuf));
78 /* initialize length */
79 jb->info.current = jb->info.target = JB_TARGET_EXTRA;
80 jb->info.silence_begin_ts = -1;
88 jb = malloc(sizeof(jitterbuf));
94 jb_dbg2("jb_new() = %x\n", jb);
98 void jb_destroy(jitterbuf *jb)
101 jb_dbg2("jb_destroy(%x)\n", jb);
103 /* free all the frames on the "free list" */
105 while (frame != NULL) {
106 jb_frame *next = frame->next;
111 /* free ourselves! */
117 /* simple history manipulation */
118 /* maybe later we can make the history buckets variable size, or something? */
119 /* drop parameter determines whether we will drop outliers to minimize
122 static int longcmp(const void *a, const void *b)
124 return *(long *)a - *(long *)b;
128 static int history_put(jitterbuf *jb, long ts, long now, long ms)
130 long delay = now - (ts - jb->info.resync_offset);
131 long threshold = 2 * jb->info.jitter + jb->info.conf.resync_threshold;
134 /* don't add special/negative times to history */
138 /* check for drastic change in delay */
139 if (jb->info.conf.resync_threshold != -1) {
140 if (abs(delay - jb->info.last_delay) > threshold) {
141 jb->info.cnt_delay_discont++;
142 if (jb->info.cnt_delay_discont > 3) {
143 /* resync the jitterbuffer */
144 jb->info.cnt_delay_discont = 0;
146 jb->hist_maxbuf_valid = 0;
148 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);
149 jb->info.resync_offset = ts - now;
150 jb->info.last_delay = delay = 0; /* after resync, frame is right on time */
155 jb->info.last_delay = delay;
156 jb->info.cnt_delay_discont = 0;
160 kicked = jb->history[jb->hist_ptr & JB_HISTORY_SZ];
162 jb->history[(jb->hist_ptr++) % JB_HISTORY_SZ] = delay;
164 /* optimization; the max/min buffers don't need to be recalculated, if this packet's
165 * entry doesn't change them. This happens if this packet is not involved, _and_ any packet
166 * that got kicked out of the history is also not involved
167 * We do a number of comparisons, but it's probably still worthwhile, because it will usually
168 * succeed, and should be a lot faster than going through all 500 packets in history */
169 if (!jb->hist_maxbuf_valid)
172 /* don't do this until we've filled history
173 * (reduces some edge cases below) */
174 if (jb->hist_ptr < JB_HISTORY_SZ)
177 /* if the new delay would go into min */
178 if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1])
182 if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1])
185 /* or the kicked delay would be in min */
186 if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1])
189 if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1])
192 /* if we got here, we don't need to invalidate, 'cause this delay didn't
195 /* end optimization */
199 jb->hist_maxbuf_valid = 0;
203 static void history_calc_maxbuf(jitterbuf *jb)
207 if (jb->hist_ptr == 0)
211 /* initialize maxbuf/minbuf to the latest value */
212 for (i=0;i<JB_HISTORY_MAXBUF_SZ;i++) {
214 * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ];
215 * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ];
217 jb->hist_maxbuf[i] = JB_LONGMIN;
218 jb->hist_minbuf[i] = JB_LONGMAX;
221 /* use insertion sort to populate maxbuf */
222 /* we want it to be the top "n" values, in order */
224 /* start at the beginning, or JB_HISTORY_SZ frames ago */
225 i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0;
227 for (;i<jb->hist_ptr;i++) {
228 long toins = jb->history[i % JB_HISTORY_SZ];
230 /* if the maxbuf should get this */
231 if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) {
233 /* insertion-sort it into the maxbuf */
234 for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) {
235 /* found where it fits */
236 if (toins > jb->hist_maxbuf[j]) {
238 memmove(jb->hist_maxbuf+j+1,jb->hist_maxbuf+j, (JB_HISTORY_MAXBUF_SZ-(j+1)) * sizeof(long));
240 jb->hist_maxbuf[j] = toins;
247 /* if the minbuf should get this */
248 if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) {
250 /* insertion-sort it into the maxbuf */
251 for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) {
252 /* found where it fits */
253 if (toins < jb->hist_minbuf[j]) {
255 memmove(jb->hist_minbuf+j+1,jb->hist_minbuf+j, (JB_HISTORY_MAXBUF_SZ-(j+1)) * sizeof(long));
257 jb->hist_minbuf[j] = toins;
266 fprintf(stderr, "toins = %ld\n", toins);
267 fprintf(stderr, "maxbuf =");
268 for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++)
269 fprintf(stderr, "%ld ", jb->hist_maxbuf[k]);
270 fprintf(stderr, "\nminbuf =");
271 for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++)
272 fprintf(stderr, "%ld ", jb->hist_minbuf[k]);
273 fprintf(stderr, "\n");
277 jb->hist_maxbuf_valid = 1;
280 static void history_get(jitterbuf *jb)
282 long max, min, jitter;
286 if (!jb->hist_maxbuf_valid)
287 history_calc_maxbuf(jb);
289 /* count is how many items in history we're examining */
290 count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ;
292 /* index is the "n"ths highest/lowest that we'll look for */
293 index = count * JB_HISTORY_DROPPCT / 100;
295 /* sanity checks for index */
296 if (index > (JB_HISTORY_MAXBUF_SZ - 1))
297 index = JB_HISTORY_MAXBUF_SZ - 1;
306 max = jb->hist_maxbuf[index];
307 min = jb->hist_minbuf[index];
311 /* these debug stmts compare the difference between looking at the absolute jitter, and the
312 * values we get by throwing away the outliers */
314 fprintf(stderr, "[%d] min=%d, max=%d, jitter=%d\n", index, min, max, jitter);
315 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]);
319 jb->info.jitter = jitter;
322 /* returns 1 if frame was inserted into head of queue, 0 otherwise */
323 static int queue_put(jitterbuf *jb, void *data, int type, long ms, long ts)
328 long resync_ts = ts - jb->info.resync_offset;
332 jb->free = frame->next;
334 frame = malloc(sizeof(jb_frame));
338 jb_err("cannot allocate frame\n");
342 jb->info.frames_cur++;
345 frame->ts = resync_ts;
350 * frames are a circular list, jb-frames points to to the lowest ts,
351 * jb->frames->prev points to the highest ts
354 if (!jb->frames) { /* queue is empty */
359 } else if (resync_ts < jb->frames->ts) {
360 frame->next = jb->frames;
361 frame->prev = jb->frames->prev;
363 frame->next->prev = frame;
364 frame->prev->next = frame;
366 /* frame is out of order */
367 jb->info.frames_ooo++;
374 /* frame is out of order */
375 if (resync_ts < p->prev->ts) jb->info.frames_ooo++;
377 while (resync_ts < p->prev->ts && p->prev != jb->frames)
381 frame->prev = p->prev;
383 frame->next->prev = frame;
384 frame->prev->next = frame;
389 static long queue_next(jitterbuf *jb)
392 return jb->frames->ts;
397 static long queue_last(jitterbuf *jb)
400 return jb->frames->prev->ts;
405 static jb_frame *_queue_get(jitterbuf *jb, long ts, int all)
413 /*jb_warn("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); */
415 if (all || ts >= frame->ts) {
416 /* remove this frame */
417 frame->prev->next = frame->next;
418 frame->next->prev = frame->prev;
420 if (frame->next == frame)
423 jb->frames = frame->next;
426 /* insert onto "free" single-linked list */
427 frame->next = jb->free;
430 jb->info.frames_cur--;
432 /* we return the frame pointer, even though it's on free list,
433 * but caller must copy data */
440 static jb_frame *queue_get(jitterbuf *jb, long ts)
442 return _queue_get(jb,ts,0);
445 static jb_frame *queue_getall(jitterbuf *jb)
447 return _queue_get(jb,0,1);
451 /* some diagnostics */
452 static void jb_dbginfo(jitterbuf *jb)
457 jb_dbg("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n",
458 jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur);
460 jb_dbg("jitter=%ld current=%ld target=%ld min=%ld sil=%d len=%d len/fcur=%ld\n",
461 jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min,
462 jb->info.frames_cur ? (jb->info.current - jb->info.min)/jb->info.frames_cur : -8);
463 if (jb->info.frames_in > 0)
464 jb_dbg("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n",
465 jb->info.frames_lost * 100/(jb->info.frames_in + jb->info.frames_lost),
466 jb->info.frames_late * 100/jb->info.frames_in);
467 jb_dbg("jb info: queue %d -> %d. last_ts %d (queue len: %d) last_ms %d\n",
470 jb->info.next_voice_ts,
471 queue_last(jb) - queue_next(jb),
472 jb->info.last_voice_ms);
477 static void jb_chkqueue(jitterbuf *jb)
480 jb_frame *p = jb->frames;
487 if (p->next == NULL) {
488 jb_err("Queue is BROKEN at item [%d]", i);
492 } while (p->next != jb->frames);
495 static void jb_dbgqueue(jitterbuf *jb)
498 jb_frame *p = jb->frames;
508 jb_dbg("[%d]=%ld ", i++, p->ts);
510 } while (p->next != jb->frames);
516 int jb_put(jitterbuf *jb, void *data, int type, long ms, long ts, long now)
518 jb_dbg2("jb_put(%x,%x,%ld,%ld,%ld)\n", jb, data, ms, ts, now);
520 jb->info.frames_in++;
522 if (type == JB_TYPE_VOICE) {
523 /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the
524 * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */
525 if (history_put(jb,ts,now,ms))
529 /* if put into head of queue, caller needs to reschedule */
530 if (queue_put(jb,data,type,ms,ts)) {
537 static int _jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl)
541 static int dbg_cnt = 0;
543 /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */
544 /* get jitter info */
547 if (dbg_cnt && dbg_cnt % 50 == 0) {
553 jb->info.target = jb->info.jitter + jb->info.min + JB_TARGET_EXTRA;
555 /* if a hard clamp was requested, use it */
556 if ((jb->info.conf.max_jitterbuf) && ((jb->info.target - jb->info.min) > jb->info.conf.max_jitterbuf)) {
557 jb_dbg("clamping target from %d to %d\n", (jb->info.target - jb->info.min), jb->info.conf.max_jitterbuf);
558 jb->info.target = jb->info.min + jb->info.conf.max_jitterbuf;
561 diff = jb->info.target - jb->info.current;
563 /* jb_warn("diff = %d lms=%d last = %d now = %d\n", diff, */
564 /* jb->info.last_voice_ms, jb->info.last_adjustment, now); */
566 /* let's work on non-silent case first */
567 if (!jb->info.silence_begin_ts) {
568 /* we want to grow */
570 /* we haven't grown in the delay length */
571 (((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) ||
572 /* we need to grow more than the "length" we have left */
573 (diff > queue_last(jb) - queue_next(jb)) ) ) {
574 /* grow by interp frame length */
575 jb->info.current += interpl;
576 jb->info.next_voice_ts += interpl;
577 jb->info.last_voice_ms = interpl;
578 jb->info.last_adjustment = now;
579 jb->info.cnt_contig_interp++;
580 if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) {
581 jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current;
587 frame = queue_get(jb, jb->info.next_voice_ts - jb->info.current);
589 /* not a voice frame; just return it. */
590 if (frame && frame->type != JB_TYPE_VOICE) {
591 if (frame->type == JB_TYPE_SILENCE) {
592 jb->info.silence_begin_ts = frame->ts;
593 jb->info.cnt_contig_interp = 0;
597 jb->info.frames_out++;
603 /* voice frame is later than expected */
604 if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) {
605 if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) {
606 /* either we interpolated past this frame in the last jb_get */
607 /* or the frame is still in order, but came a little too quick */
609 /* reset expectation for next frame */
610 jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms;
611 jb->info.frames_out++;
612 decrement_losspct(jb);
613 jb->info.cnt_contig_interp = 0;
617 /* voice frame is late */
619 jb->info.frames_out++;
620 decrement_losspct(jb);
621 jb->info.frames_late++;
622 jb->info.frames_lost--;
624 /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb));
630 /* keep track of frame sizes, to allow for variable sized-frames */
631 if (frame && frame->ms > 0) {
632 jb->info.last_voice_ms = frame->ms;
635 /* we want to shrink; shrink at 1 frame / 500ms */
636 /* unless we don't have a frame, then shrink 1 frame */
637 /* every 80ms (though perhaps we can shrink even faster */
639 if (diff < -JB_TARGET_EXTRA &&
640 ((!frame && jb->info.last_adjustment + 80 < now) ||
641 (jb->info.last_adjustment + 500 < now))) {
643 jb->info.last_adjustment = now;
644 jb->info.cnt_contig_interp = 0;
648 /* shrink by frame size we're throwing out */
649 jb->info.current -= frame->ms;
650 jb->info.frames_out++;
651 decrement_losspct(jb);
652 jb->info.frames_dropped++;
656 /* shrink by last_voice_ms */
657 jb->info.current -= jb->info.last_voice_ms;
658 jb->info.frames_lost++;
659 increment_losspct(jb);
667 /* this is a bit of a hack for now, but if we're close to
668 * target, and we find a missing frame, it makes sense to
669 * grow, because the frame might just be a bit late;
670 * otherwise, we presently get into a pattern where we return
671 * INTERP for the lost frame, then it shows up next, and we
672 * throw it away because it's late */
673 /* I've recently only been able to replicate this using
674 * iaxclient talking to app_echo on asterisk. In this case,
675 * my outgoing packets go through asterisk's (old)
676 * jitterbuffer, and then might get an unusual increasing delay
677 * there if it decides to grow?? */
678 /* Update: that might have been a different bug, that has been fixed..
679 * But, this still seemed like a good idea, except that it ended up making a single actual
680 * lost frame get interpolated two or more times, when there was "room" to grow, so it might
681 * be a bit of a bad idea overall */
682 /*if (diff > -1 * jb->info.last_voice_ms) {
683 jb->info.current += jb->info.last_voice_ms;
684 jb->info.last_adjustment = now;
688 jb->info.frames_lost++;
689 increment_losspct(jb);
690 jb->info.next_voice_ts += interpl;
691 jb->info.last_voice_ms = interpl;
692 jb->info.cnt_contig_interp++;
693 if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) {
694 jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current;
700 /* normal case; return the frame, increment stuff */
702 jb->info.next_voice_ts += frame->ms;
703 jb->info.frames_out++;
704 jb->info.cnt_contig_interp = 0;
705 decrement_losspct(jb);
709 /* TODO: after we get the non-silent case down, we'll make the
710 * silent case -- basically, we'll just grow and shrink faster
711 * here, plus handle next_voice_ts a bit differently */
713 /* to disable silent special case altogether, just uncomment this: */
714 /* jb->info.silence_begin_ts = 0; */
716 /* shrink interpl len every 10ms during silence */
717 if (diff < -JB_TARGET_EXTRA &&
718 jb->info.last_adjustment + 10 <= now) {
719 jb->info.current -= interpl;
720 jb->info.last_adjustment = now;
723 frame = queue_get(jb, now - jb->info.current);
726 } else if (frame->type != JB_TYPE_VOICE) {
727 /* normal case; in silent mode, got a non-voice frame */
729 jb->info.frames_out++;
732 if (frame->ts < jb->info.silence_begin_ts) {
733 /* voice frame is late */
735 jb->info.frames_out++;
736 decrement_losspct(jb);
737 jb->info.frames_late++;
738 jb->info.frames_lost--;
740 /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb));
745 /* try setting current to target right away here */
746 jb->info.current = jb->info.target;
747 jb->info.silence_begin_ts = 0;
748 jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms;
749 jb->info.last_voice_ms = frame->ms;
750 jb->info.frames_out++;
751 decrement_losspct(jb);
759 long jb_next(jitterbuf *jb)
761 if (jb->info.silence_begin_ts) {
762 long next = queue_next(jb);
765 /* shrink during silence */
766 if (jb->info.target - jb->info.current < -JB_TARGET_EXTRA)
767 return jb->info.last_adjustment + 10;
768 return next + jb->info.target;
773 return jb->info.next_voice_ts;
777 int jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl)
779 int ret = _jb_get(jb,frameout,now,interpl);
782 int thists = ((ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0;
783 jb_warn("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists);
784 if (thists && thists < lastts) jb_warn("XXXX timestamp roll-back!!!\n");
788 frameout->ms = jb->info.last_voice_ms;
793 int jb_getall(jitterbuf *jb, jb_frame *frameout)
796 frame = queue_getall(jb);
807 int jb_getinfo(jitterbuf *jb, jb_info *stats)
817 int jb_setconf(jitterbuf *jb, jb_conf *conf)
819 /* take selected settings from the struct */
821 jb->info.conf.max_jitterbuf = conf->max_jitterbuf;
822 jb->info.conf.resync_threshold = conf->resync_threshold;
823 jb->info.conf.max_contig_interp = conf->max_contig_interp;