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 = 0;
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 void history_put(jitterbuf *jb, long ts, long now)
111 long delay = now - ts;
114 /* don't add special/negative times to history */
118 kicked = jb->history[jb->hist_ptr & JB_HISTORY_SZ];
120 jb->history[(jb->hist_ptr++) % JB_HISTORY_SZ] = delay;
122 /* optimization; the max/min buffers don't need to be recalculated, if this packet's
123 * entry doesn't change them. This happens if this packet is not involved, _and_ any packet
124 * that got kicked out of the history is also not involved
125 * We do a number of comparisons, but it's probably still worthwhile, because it will usually
126 * succeed, and should be a lot faster than going through all 500 packets in history */
127 if (!jb->hist_maxbuf_valid)
130 /* don't do this until we've filled history
131 * (reduces some edge cases below) */
132 if (jb->hist_ptr < JB_HISTORY_SZ)
135 /* if the new delay would go into min */
136 if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1])
140 if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1])
143 /* or the kicked delay would be in min */
144 if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1])
147 if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1])
150 /* if we got here, we don't need to invalidate, 'cause this delay didn't
153 /* end optimization */
157 jb->hist_maxbuf_valid = 0;
161 static void history_calc_maxbuf(jitterbuf *jb)
165 if (jb->hist_ptr == 0)
169 /* initialize maxbuf/minbuf to the latest value */
170 for (i=0;i<JB_HISTORY_MAXBUF_SZ;i++) {
172 * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ];
173 * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ];
175 jb->hist_maxbuf[i] = JB_LONGMIN;
176 jb->hist_minbuf[i] = JB_LONGMAX;
179 /* use insertion sort to populate maxbuf */
180 /* we want it to be the top "n" values, in order */
182 /* start at the beginning, or JB_HISTORY_SZ frames ago */
183 i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0;
185 for (;i<jb->hist_ptr;i++) {
186 long toins = jb->history[i % JB_HISTORY_SZ];
188 /* if the maxbuf should get this */
189 if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) {
191 /* insertion-sort it into the maxbuf */
192 for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) {
193 /* found where it fits */
194 if (toins > jb->hist_maxbuf[j]) {
196 memmove(jb->hist_maxbuf+j+1,jb->hist_maxbuf+j, (JB_HISTORY_MAXBUF_SZ-(j+1)) * sizeof(long));
198 jb->hist_maxbuf[j] = toins;
205 /* if the minbuf should get this */
206 if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) {
208 /* insertion-sort it into the maxbuf */
209 for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) {
210 /* found where it fits */
211 if (toins < jb->hist_minbuf[j]) {
213 memmove(jb->hist_minbuf+j+1,jb->hist_minbuf+j, (JB_HISTORY_MAXBUF_SZ-(j+1)) * sizeof(long));
215 jb->hist_minbuf[j] = toins;
224 fprintf(stderr, "toins = %ld\n", toins);
225 fprintf(stderr, "maxbuf =");
226 for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++)
227 fprintf(stderr, "%ld ", jb->hist_maxbuf[k]);
228 fprintf(stderr, "\nminbuf =");
229 for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++)
230 fprintf(stderr, "%ld ", jb->hist_minbuf[k]);
231 fprintf(stderr, "\n");
235 jb->hist_maxbuf_valid = 1;
238 static void history_get(jitterbuf *jb)
240 long max, min, jitter;
244 if (!jb->hist_maxbuf_valid)
245 history_calc_maxbuf(jb);
247 /* count is how many items in history we're examining */
248 count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ;
250 /* index is the "n"ths highest/lowest that we'll look for */
251 index = count * JB_HISTORY_DROPPCT / 100;
253 /* sanity checks for index */
254 if (index > (JB_HISTORY_MAXBUF_SZ - 1))
255 index = JB_HISTORY_MAXBUF_SZ - 1;
264 max = jb->hist_maxbuf[index];
265 min = jb->hist_minbuf[index];
269 /* these debug stmts compare the difference between looking at the absolute jitter, and the
270 * values we get by throwing away the outliers */
272 fprintf(stderr, "[%d] min=%d, max=%d, jitter=%d\n", index, min, max, jitter);
273 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]);
277 jb->info.jitter = jitter;
280 static void queue_put(jitterbuf *jb, void *data, int type, long ms, long ts)
287 jb->free = frame->next;
289 frame = malloc(sizeof(jb_frame));
293 jb_err("cannot allocate frame\n");
297 jb->info.frames_cur++;
305 * frames are a circular list, jb-frames points to to the lowest ts,
306 * jb->frames->prev points to the highest ts
309 if (!jb->frames) { /* queue is empty */
313 frame->prev = jb->frames->prev;
315 frame->next->prev = frame;
316 frame->prev->next = frame;
322 /* frame is out of order */
323 if (ts < p->prev->ts) jb->info.frames_ooo++;
325 while (ts < p->prev->ts && p->prev != jb->frames)
329 frame->prev = p->prev;
331 frame->next->prev = frame;
332 frame->prev->next = frame;
336 static long queue_next(jitterbuf *jb)
339 return jb->frames->ts;
344 static long queue_last(jitterbuf *jb)
347 return jb->frames->prev->ts;
352 static jb_frame *_queue_get(jitterbuf *jb, long ts, int all)
360 /*jb_warn("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); */
362 if (all || ts >= frame->ts) {
363 /* remove this frame */
364 frame->prev->next = frame->next;
365 frame->next->prev = frame->prev;
367 if (frame->next == frame)
370 jb->frames = frame->next;
373 /* insert onto "free" single-linked list */
374 frame->next = jb->free;
377 jb->info.frames_cur--;
379 /* we return the frame pointer, even though it's on free list,
380 * but caller must copy data */
387 static jb_frame *queue_get(jitterbuf *jb, long ts)
389 return _queue_get(jb,ts,0);
392 static jb_frame *queue_getall(jitterbuf *jb)
394 return _queue_get(jb,0,1);
398 /* some diagnostics */
399 static void jb_dbginfo(jitterbuf *jb)
404 jb_dbg("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n",
405 jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur);
407 jb_dbg("jitter=%ld current=%ld target=%ld min=%ld sil=%d len=%d len/fcur=%ld\n",
408 jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min,
409 jb->info.frames_cur ? (jb->info.current - jb->info.min)/jb->info.frames_cur : -8);
410 if (jb->info.frames_in > 0)
411 jb_dbg("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n",
412 jb->info.frames_lost * 100/(jb->info.frames_in + jb->info.frames_lost),
413 jb->info.frames_late * 100/jb->info.frames_in);
414 jb_dbg("jb info: queue %d -> %d. last_ts %d (queue len: %d) last_ms %d\n",
417 jb->info.next_voice_ts,
418 queue_last(jb) - queue_next(jb),
419 jb->info.last_voice_ms);
424 static void jb_chkqueue(jitterbuf *jb)
427 jb_frame *p = jb->frames;
434 if (p->next == NULL) {
435 jb_err("Queue is BROKEN at item [%d]", i);
439 } while (p->next != jb->frames);
442 static void jb_dbgqueue(jitterbuf *jb)
445 jb_frame *p = jb->frames;
455 jb_dbg("[%d]=%ld ", i++, p->ts);
457 } while (p->next != jb->frames);
463 int jb_put(jitterbuf *jb, void *data, int type, long ms, long ts, long now)
465 jb_dbg2("jb_put(%x,%x,%ld,%ld,%ld)\n", jb, data, ms, ts, now);
467 jb->info.frames_in++;
469 if (type == JB_TYPE_VOICE) {
470 /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the
471 * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */
472 history_put(jb,ts,now);
475 queue_put(jb,data,type,ms,ts);
481 static int _jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl)
486 /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */
487 /* get jitter info */
492 jb->info.target = jb->info.jitter + jb->info.min + JB_TARGET_EXTRA;
494 /* if a hard clamp was requested, use it */
495 if ((jb->info.max_jitterbuf) && ((jb->info.target - jb->info.min) > jb->info.max_jitterbuf)) {
496 jb_dbg("clamping target from %d to %d\n", (jb->info.target - jb->info.min), jb->info.max_jitterbuf);
497 jb->info.target = jb->info.min + jb->info.max_jitterbuf;
500 diff = jb->info.target - jb->info.current;
502 /* jb_warn("diff = %d lms=%d last = %d now = %d\n", diff, */
503 /* jb->info.last_voice_ms, jb->info.last_adjustment, now); */
505 /* let's work on non-silent case first */
506 if (!jb->info.silence_begin_ts) {
507 /* we want to grow */
509 /* we haven't grown in the delay length */
510 (((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) ||
511 /* we need to grow more than the "length" we have left */
512 (diff > queue_last(jb) - queue_next(jb)) ) ) {
513 /* grow by interp frame length */
514 jb->info.current += interpl;
515 jb->info.next_voice_ts += interpl;
516 jb->info.last_voice_ms = interpl;
517 jb->info.last_adjustment = now;
522 frame = queue_get(jb, jb->info.next_voice_ts - jb->info.current);
524 /* not a voice frame; just return it. */
525 if (frame && frame->type != JB_TYPE_VOICE) {
526 if (frame->type == JB_TYPE_SILENCE)
527 jb->info.silence_begin_ts = frame->ts;
530 jb->info.frames_out++;
536 /* voice frame is later than expected */
537 if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) {
538 if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) {
539 /* either we interpolated past this frame in the last jb_get */
540 /* or the frame is still in order, but came a little too quick */
542 /* reset expectation for next frame */
543 jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms;
544 jb->info.frames_out++;
545 decrement_losspct(jb);
549 /* voice frame is late */
551 jb->info.frames_out++;
552 decrement_losspct(jb);
553 jb->info.frames_late++;
554 jb->info.frames_lost--;
556 /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb));
562 /* keep track of frame sizes, to allow for variable sized-frames */
563 if (frame && frame->ms > 0) {
564 jb->info.last_voice_ms = frame->ms;
567 /* we want to shrink; shrink at 1 frame / 500ms */
568 /* unless we don't have a frame, then shrink 1 frame */
569 /* every 80ms (though perhaps we can shrink even faster */
571 if (diff < -JB_TARGET_EXTRA &&
572 ((!frame && jb->info.last_adjustment + 80 < now) ||
573 (jb->info.last_adjustment + 500 < now))) {
575 jb->info.last_adjustment = now;
579 /* shrink by frame size we're throwing out */
580 jb->info.current -= frame->ms;
581 jb->info.frames_out++;
582 decrement_losspct(jb);
583 jb->info.frames_dropped++;
587 /* shrink by last_voice_ms */
588 jb->info.current -= jb->info.last_voice_ms;
589 jb->info.frames_lost++;
590 increment_losspct(jb);
598 /* this is a bit of a hack for now, but if we're close to
599 * target, and we find a missing frame, it makes sense to
600 * grow, because the frame might just be a bit late;
601 * otherwise, we presently get into a pattern where we return
602 * INTERP for the lost frame, then it shows up next, and we
603 * throw it away because it's late */
604 /* I've recently only been able to replicate this using
605 * iaxclient talking to app_echo on asterisk. In this case,
606 * my outgoing packets go through asterisk's (old)
607 * jitterbuffer, and then might get an unusual increasing delay
608 * there if it decides to grow?? */
609 /* Update: that might have been a different bug, that has been fixed..
610 * But, this still seemed like a good idea, except that it ended up making a single actual
611 * lost frame get interpolated two or more times, when there was "room" to grow, so it might
612 * be a bit of a bad idea overall */
613 /*if (diff > -1 * jb->info.last_voice_ms) {
614 jb->info.current += jb->info.last_voice_ms;
615 jb->info.last_adjustment = now;
619 jb->info.frames_lost++;
620 increment_losspct(jb);
621 jb->info.next_voice_ts += interpl;
622 jb->info.last_voice_ms = interpl;
627 /* normal case; return the frame, increment stuff */
629 jb->info.next_voice_ts += frame->ms;
630 jb->info.frames_out++;
631 decrement_losspct(jb);
635 /* TODO: after we get the non-silent case down, we'll make the
636 * silent case -- basically, we'll just grow and shrink faster
637 * here, plus handle next_voice_ts a bit differently */
639 /* to disable silent special case altogether, just uncomment this: */
640 /* jb->info.silence_begin_ts = 0; */
642 /* shrink interpl len every 10ms during silence */
643 if (diff < -JB_TARGET_EXTRA &&
644 jb->info.last_adjustment + 10 <= now) {
645 jb->info.current -= interpl;
646 jb->info.last_adjustment = now;
649 frame = queue_get(jb, now - jb->info.current);
652 } else if (frame->type != JB_TYPE_VOICE) {
653 /* normal case; in silent mode, got a non-voice frame */
655 jb->info.frames_out++;
658 if (frame->ts < jb->info.silence_begin_ts) {
659 /* voice frame is late */
661 jb->info.frames_out++;
662 decrement_losspct(jb);
663 jb->info.frames_late++;
664 jb->info.frames_lost--;
666 /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb));
671 /* try setting current to target right away here */
672 jb->info.current = jb->info.target;
673 jb->info.silence_begin_ts = 0;
674 jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms;
675 jb->info.last_voice_ms = frame->ms;
676 jb->info.frames_out++;
677 decrement_losspct(jb);
685 long jb_next(jitterbuf *jb)
687 if (jb->info.silence_begin_ts) {
688 long next = queue_next(jb);
691 /* shrink during silence */
692 if (jb->info.target - jb->info.current < -JB_TARGET_EXTRA)
693 return jb->info.last_adjustment + 10;
694 return next + jb->info.target;
699 return jb->info.next_voice_ts;
703 int jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl)
705 int ret = _jb_get(jb,frameout,now,interpl);
708 int thists = ((ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0;
709 jb_warn("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists);
710 if (thists && thists < lastts) jb_warn("XXXX timestamp roll-back!!!\n");
714 frameout->ms = jb->info.last_voice_ms;
719 int jb_getall(jitterbuf *jb, jb_frame *frameout)
722 frame = queue_getall(jb);
733 int jb_getinfo(jitterbuf *jb, jb_info *stats)
743 int jb_setinfo(jitterbuf *jb, jb_info *settings)
745 /* take selected settings from the struct */
747 jb->info.max_jitterbuf = settings->max_jitterbuf;