2 * abstract_jb: common implementation-independent jitterbuffer stuff
4 * Copyright (C) 2005, Attractel OOD
7 * Slav Klenov <slav@securax.org>
9 * See http://www.asterisk.org for more information about
10 * the Asterisk project. Please do not directly contact
11 * any of the maintainers of this project for assistance;
12 * the project provides a web site, mailing lists and IRC
13 * channels for your use.
15 * This program is free software, distributed under the terms of
16 * the GNU General Public License Version 2. See the LICENSE file
17 * at the top of the source tree.
19 * A license has been granted to Digium (via disclaimer) for the use of
25 * \brief Common implementation-independent jitterbuffer stuff.
27 * \author Slav Klenov <slav@securax.org>
33 <support_level>core</support_level>
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include "asterisk/frame.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/term.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/timing.h"
47 #include "asterisk/abstract_jb.h"
48 #include "fixedjitterbuf.h"
49 #include "jitterbuf.h"
51 /*! Internal jb flags */
54 JB_TIMEBASE_INITIALIZED = (1 << 1),
59 /* Implementation functions */
61 static void *jb_create_fixed(struct ast_jb_conf *general_config);
62 static void jb_destroy_fixed(void *jb);
63 static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now);
64 static int jb_put_fixed(void *jb, struct ast_frame *fin, long now);
65 static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl);
66 static long jb_next_fixed(void *jb);
67 static int jb_remove_fixed(void *jb, struct ast_frame **fout);
68 static void jb_force_resynch_fixed(void *jb);
69 static void jb_empty_and_reset_fixed(void *jb);
71 static void * jb_create_adaptive(struct ast_jb_conf *general_config);
72 static void jb_destroy_adaptive(void *jb);
73 static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now);
74 static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now);
75 static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl);
76 static long jb_next_adaptive(void *jb);
77 static int jb_remove_adaptive(void *jb, struct ast_frame **fout);
78 static void jb_force_resynch_adaptive(void *jb);
79 static void jb_empty_and_reset_adaptive(void *jb);
81 /* Available jb implementations */
82 static const struct ast_jb_impl avail_impl[] = {
86 .create = jb_create_fixed,
87 .destroy = jb_destroy_fixed,
88 .put_first = jb_put_first_fixed,
91 .next = jb_next_fixed,
92 .remove = jb_remove_fixed,
93 .force_resync = jb_force_resynch_fixed,
94 .empty_and_reset = jb_empty_and_reset_fixed,
98 .type = AST_JB_ADAPTIVE,
99 .create = jb_create_adaptive,
100 .destroy = jb_destroy_adaptive,
101 .put_first = jb_put_first_adaptive,
102 .put = jb_put_adaptive,
103 .get = jb_get_adaptive,
104 .next = jb_next_adaptive,
105 .remove = jb_remove_adaptive,
106 .force_resync = jb_force_resynch_adaptive,
107 .empty_and_reset = jb_empty_and_reset_adaptive,
111 static int default_impl = 0;
113 /* Translations between impl and abstract return codes */
114 static const int fixed_to_abstract_code[] =
115 {AST_JB_IMPL_OK, AST_JB_IMPL_DROP, AST_JB_IMPL_INTERP, AST_JB_IMPL_NOFRAME};
116 static const int adaptive_to_abstract_code[] =
117 {AST_JB_IMPL_OK, AST_JB_IMPL_NOFRAME, AST_JB_IMPL_NOFRAME, AST_JB_IMPL_INTERP, AST_JB_IMPL_DROP, AST_JB_IMPL_OK};
119 /* JB_GET actions (used only for the frames log) */
120 static const char * const jb_get_actions[] = {"Delivered", "Dropped", "Interpolated", "No"};
122 /*! \brief Macros for the frame log files */
123 #define jb_framelog(...) do { \
125 fprintf(jb->logfile, __VA_ARGS__); \
126 fflush(jb->logfile); \
131 /* Internal utility functions */
132 static void jb_choose_impl(struct ast_channel *chan);
133 static void jb_get_and_deliver(struct ast_channel *chan);
134 static int create_jb(struct ast_channel *chan, struct ast_frame *first_frame);
135 static long get_now(struct ast_jb *jb, struct timeval *tv);
138 /* Interface ast jb functions impl */
141 static void jb_choose_impl(struct ast_channel *chan)
143 struct ast_jb *jb = ast_channel_jb(chan);
144 struct ast_jb_conf *jbconf = &jb->conf;
145 const struct ast_jb_impl *test_impl;
146 int i, avail_impl_count = ARRAY_LEN(avail_impl);
148 jb->impl = &avail_impl[default_impl];
150 if (ast_strlen_zero(jbconf->impl)) {
154 for (i = 0; i < avail_impl_count; i++) {
155 test_impl = &avail_impl[i];
156 if (!strcasecmp(jbconf->impl, test_impl->name)) {
157 jb->impl = test_impl;
163 int ast_jb_do_usecheck(struct ast_channel *c0, struct ast_channel *c1)
165 struct ast_jb *jb0 = ast_channel_jb(c0);
166 struct ast_jb *jb1 = ast_channel_jb(c1);
167 struct ast_jb_conf *conf0 = &jb0->conf;
168 struct ast_jb_conf *conf1 = &jb1->conf;
169 int c0_wants_jitter = ast_channel_tech(c0)->properties & AST_CHAN_TP_WANTSJITTER;
170 int c0_creates_jitter = ast_channel_tech(c0)->properties & AST_CHAN_TP_CREATESJITTER;
171 int c0_jb_enabled = ast_test_flag(conf0, AST_JB_ENABLED);
172 int c0_force_jb = ast_test_flag(conf0, AST_JB_FORCED);
173 int c0_jb_timebase_initialized = ast_test_flag(jb0, JB_TIMEBASE_INITIALIZED);
174 int c0_jb_created = ast_test_flag(jb0, JB_CREATED);
175 int c1_wants_jitter = ast_channel_tech(c1)->properties & AST_CHAN_TP_WANTSJITTER;
176 int c1_creates_jitter = ast_channel_tech(c1)->properties & AST_CHAN_TP_CREATESJITTER;
177 int c1_jb_enabled = ast_test_flag(conf1, AST_JB_ENABLED);
178 int c1_force_jb = ast_test_flag(conf1, AST_JB_FORCED);
179 int c1_jb_timebase_initialized = ast_test_flag(jb1, JB_TIMEBASE_INITIALIZED);
180 int c1_jb_created = ast_test_flag(jb1, JB_CREATED);
183 /* Determine whether audio going to c0 needs a jitter buffer */
184 if (((!c0_wants_jitter && c1_creates_jitter) || (c0_force_jb && c1_creates_jitter)) && c0_jb_enabled) {
185 ast_set_flag(jb0, JB_USE);
186 if (!c0_jb_timebase_initialized) {
187 if (c1_jb_timebase_initialized) {
188 memcpy(&jb0->timebase, &jb1->timebase, sizeof(struct timeval));
190 gettimeofday(&jb0->timebase, NULL);
192 ast_set_flag(jb0, JB_TIMEBASE_INITIALIZED);
195 if (!c0_jb_created) {
202 /* Determine whether audio going to c1 needs a jitter buffer */
203 if (((!c1_wants_jitter && c0_creates_jitter) || (c1_force_jb && c0_creates_jitter)) && c1_jb_enabled) {
204 ast_set_flag(jb1, JB_USE);
205 if (!c1_jb_timebase_initialized) {
206 if (c0_jb_timebase_initialized) {
207 memcpy(&jb1->timebase, &jb0->timebase, sizeof(struct timeval));
209 gettimeofday(&jb1->timebase, NULL);
211 ast_set_flag(jb1, JB_TIMEBASE_INITIALIZED);
214 if (!c1_jb_created) {
224 int ast_jb_get_when_to_wakeup(struct ast_channel *c0, struct ast_channel *c1, int time_left)
226 struct ast_jb *jb0 = ast_channel_jb(c0);
227 struct ast_jb *jb1 = ast_channel_jb(c1);
228 int c0_use_jb = ast_test_flag(jb0, JB_USE);
229 int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
230 int c1_use_jb = ast_test_flag(jb1, JB_USE);
231 int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
232 int wait, wait0, wait1;
233 struct timeval tv_now;
235 if (time_left == 0) {
236 /* No time left - the bridge will be retried */
237 /* TODO: Test disable this */
245 gettimeofday(&tv_now, NULL);
247 wait0 = (c0_use_jb && c0_jb_is_created) ? jb0->next - get_now(jb0, &tv_now) : time_left;
248 wait1 = (c1_use_jb && c1_jb_is_created) ? jb1->next - get_now(jb1, &tv_now) : time_left;
250 wait = wait0 < wait1 ? wait0 : wait1;
251 wait = wait < time_left ? wait : time_left;
253 if (wait == INT_MAX) {
255 } else if (wait < 1) {
256 /* don't let wait=0, because this can cause the pbx thread to loop without any sleeping at all */
264 int ast_jb_put(struct ast_channel *chan, struct ast_frame *f)
266 struct ast_jb *jb = ast_channel_jb(chan);
267 const struct ast_jb_impl *jbimpl = jb->impl;
268 void *jbobj = jb->jbobj;
269 struct ast_frame *frr;
272 if (!ast_test_flag(jb, JB_USE))
275 if (f->frametype != AST_FRAME_VOICE) {
276 if (f->frametype == AST_FRAME_DTMF && ast_test_flag(jb, JB_CREATED)) {
277 jb_framelog("JB_PUT {now=%ld}: Received DTMF frame. Force resynching jb...\n", now);
278 jbimpl->force_resync(jbobj);
284 /* We consider an enabled jitterbuffer should receive frames with valid timing info. */
285 if (!ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO) || f->len < 2 || f->ts < 0) {
286 ast_log(LOG_WARNING, "%s received frame with invalid timing info: "
287 "has_timing_info=%u, len=%ld, ts=%ld, src=%s\n",
288 ast_channel_name(chan), ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO), f->len, f->ts, f->src);
295 ast_log(LOG_ERROR, "Failed to isolate frame for the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
299 if (!ast_test_flag(jb, JB_CREATED)) {
300 if (create_jb(chan, frr)) {
302 /* Disable the jitterbuffer */
303 ast_clear_flag(jb, JB_USE);
307 ast_set_flag(jb, JB_CREATED);
310 now = get_now(jb, NULL);
311 if (jbimpl->put(jbobj, frr, now) != AST_JB_IMPL_OK) {
312 jb_framelog("JB_PUT {now=%ld}: Dropped frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
315 /* TODO: Check this fix - should return 0 here, because the dropped frame shouldn't
316 be delivered at all */
320 jb->next = jbimpl->next(jbobj);
322 jb_framelog("JB_PUT {now=%ld}: Queued frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
329 void ast_jb_get_and_deliver(struct ast_channel *c0, struct ast_channel *c1)
331 struct ast_jb *jb0 = ast_channel_jb(c0);
332 struct ast_jb *jb1 = ast_channel_jb(c1);
333 int c0_use_jb = ast_test_flag(jb0, JB_USE);
334 int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
335 int c1_use_jb = ast_test_flag(jb1, JB_USE);
336 int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
338 if (c0_use_jb && c0_jb_is_created)
339 jb_get_and_deliver(c0);
341 if (c1_use_jb && c1_jb_is_created)
342 jb_get_and_deliver(c1);
346 static void jb_get_and_deliver(struct ast_channel *chan)
348 struct ast_jb *jb = ast_channel_jb(chan);
349 const struct ast_jb_impl *jbimpl = jb->impl;
350 void *jbobj = jb->jbobj;
351 struct ast_frame *f, finterp = { .frametype = AST_FRAME_VOICE, };
353 int interpolation_len, res;
355 now = get_now(jb, NULL);
356 jb->next = jbimpl->next(jbobj);
357 if (now < jb->next) {
358 jb_framelog("\tJB_GET {now=%ld}: now < next=%ld\n", now, jb->next);
362 while (now >= jb->next) {
363 interpolation_len = ast_format_get_default_ms(jb->last_format);
365 res = jbimpl->get(jbobj, &f, now, interpolation_len);
369 /* deliver the frame */
371 case AST_JB_IMPL_DROP:
372 jb_framelog("\tJB_GET {now=%ld}: %s frame with ts=%ld and len=%ld\n",
373 now, jb_get_actions[res], f->ts, f->len);
374 ao2_replace(jb->last_format, f->subclass.format);
377 case AST_JB_IMPL_INTERP:
378 /* interpolate a frame */
380 f->subclass.format = jb->last_format;
381 f->samples = interpolation_len * 8;
382 f->src = "JB interpolation";
383 f->delivery = ast_tvadd(jb->timebase, ast_samp2tv(jb->next, 1000));
384 f->offset = AST_FRIENDLY_OFFSET;
385 /* deliver the interpolated frame */
387 jb_framelog("\tJB_GET {now=%ld}: Interpolated frame with len=%d\n", now, interpolation_len);
389 case AST_JB_IMPL_NOFRAME:
391 "AST_JB_IMPL_NOFRAME is returned from the %s jb when now=%ld >= next=%ld, jbnext=%ld!\n",
392 jbimpl->name, now, jb->next, jbimpl->next(jbobj));
393 jb_framelog("\tJB_GET {now=%ld}: No frame for now!?\n", now);
396 ast_log(LOG_ERROR, "This should never happen!\n");
397 ast_assert("JB type unknown" == NULL);
401 jb->next = jbimpl->next(jbobj);
406 static int create_jb(struct ast_channel *chan, struct ast_frame *frr)
408 struct ast_jb *jb = ast_channel_jb(chan);
409 struct ast_jb_conf *jbconf = &jb->conf;
410 const struct ast_jb_impl *jbimpl = jb->impl;
413 char logfile_pathname[20 + AST_JB_IMPL_NAME_SIZE + 2*AST_CHANNEL_NAME + 1];
414 char name1[AST_CHANNEL_NAME], name2[AST_CHANNEL_NAME], *tmp;
417 jbobj = jb->jbobj = jbimpl->create(jbconf);
419 ast_log(LOG_WARNING, "Failed to create jitterbuffer on channel '%s'\n", ast_channel_name(chan));
423 now = get_now(jb, NULL);
424 res = jbimpl->put_first(jbobj, frr, now);
426 /* The result of putting the first frame should not differ from OK. However, its possible
427 some implementations (i.e. adaptive's when resynch_threshold is specified) to drop it. */
428 if (res != AST_JB_IMPL_OK) {
429 ast_log(LOG_WARNING, "Failed to put first frame in the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
431 jbimpl->destroy(jbobj);
437 jb->next = jbimpl->next(jbobj);
439 /* Init last format for a first time. */
440 jb->last_format = ao2_bump(frr->subclass.format);
442 /* Create a frame log file */
443 if (ast_test_flag(jbconf, AST_JB_LOG)) {
444 RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(chan), ast_channel_cleanup);
445 char safe_logfile[30] = "/tmp/logfile-XXXXXX";
448 snprintf(name2, sizeof(name2), "%s", ast_channel_name(chan));
449 while ((tmp = strchr(name2, '/'))) {
453 /* We should always have bridged chan if a jitterbuffer is in use */
454 ast_assert(bridged != NULL);
456 snprintf(name1, sizeof(name1), "%s", ast_channel_name(bridged));
457 while ((tmp = strchr(name1, '/'))) {
461 snprintf(logfile_pathname, sizeof(logfile_pathname),
462 "/tmp/ast_%s_jb_%s--%s.log", jbimpl->name, name1, name2);
463 unlink(logfile_pathname);
464 safe_fd = mkstemp(safe_logfile);
465 if (safe_fd < 0 || link(safe_logfile, logfile_pathname) || unlink(safe_logfile) || !(jb->logfile = fdopen(safe_fd, "w+b"))) {
466 ast_log(LOG_ERROR, "Failed to create frame log file with pathname '%s': %s\n", logfile_pathname, strerror(errno));
473 if (res == AST_JB_IMPL_OK) {
474 jb_framelog("JB_PUT_FIRST {now=%ld}: Queued frame with ts=%ld and len=%ld\n",
475 now, frr->ts, frr->len);
477 jb_framelog("JB_PUT_FIRST {now=%ld}: Dropped frame with ts=%ld and len=%ld\n",
478 now, frr->ts, frr->len);
482 ast_verb(3, "%s jitterbuffer created on channel %s\n", jbimpl->name, ast_channel_name(chan));
484 /* Free the frame if it has not been queued in the jb */
485 if (res != AST_JB_IMPL_OK) {
493 void ast_jb_destroy(struct ast_channel *chan)
495 struct ast_jb *jb = ast_channel_jb(chan);
496 const struct ast_jb_impl *jbimpl = jb->impl;
497 void *jbobj = jb->jbobj;
505 ao2_cleanup(jb->last_format);
507 if (ast_test_flag(jb, JB_CREATED)) {
508 /* Remove and free all frames still queued in jb */
509 while (jbimpl->remove(jbobj, &f) == AST_JB_IMPL_OK) {
513 jbimpl->destroy(jbobj);
516 ast_clear_flag(jb, JB_CREATED);
518 ast_verb(3, "%s jitterbuffer destroyed on channel %s\n", jbimpl->name, ast_channel_name(chan));
523 static long get_now(struct ast_jb *jb, struct timeval *when)
529 gettimeofday(when, NULL);
532 return ast_tvdiff_ms(*when, jb->timebase);
536 int ast_jb_read_conf(struct ast_jb_conf *conf, const char *varname, const char *value)
538 int prefixlen = sizeof(AST_JB_CONF_PREFIX) - 1;
542 if (strncasecmp(AST_JB_CONF_PREFIX, varname, prefixlen)) {
546 name = varname + prefixlen;
548 if (!strcasecmp(name, AST_JB_CONF_ENABLE)) {
549 ast_set2_flag(conf, ast_true(value), AST_JB_ENABLED);
550 } else if (!strcasecmp(name, AST_JB_CONF_FORCE)) {
551 ast_set2_flag(conf, ast_true(value), AST_JB_FORCED);
552 } else if (!strcasecmp(name, AST_JB_CONF_MAX_SIZE)) {
553 if ((tmp = atoi(value)) > 0)
554 conf->max_size = tmp;
555 } else if (!strcasecmp(name, AST_JB_CONF_RESYNCH_THRESHOLD)) {
556 if ((tmp = atoi(value)) > 0)
557 conf->resync_threshold = tmp;
558 } else if (!strcasecmp(name, AST_JB_CONF_IMPL)) {
559 if (!ast_strlen_zero(value))
560 snprintf(conf->impl, sizeof(conf->impl), "%s", value);
561 } else if (!strcasecmp(name, AST_JB_CONF_TARGET_EXTRA)) {
562 if (sscanf(value, "%30d", &tmp) == 1) {
563 conf->target_extra = tmp;
565 } else if (!strcasecmp(name, AST_JB_CONF_LOG)) {
566 ast_set2_flag(conf, ast_true(value), AST_JB_LOG);
574 void ast_jb_enable_for_channel(struct ast_channel *chan)
576 struct ast_jb_conf conf = ast_channel_jb(chan)->conf;
577 if (ast_test_flag(&conf, AST_JB_ENABLED)) {
578 ast_jb_create_framehook(chan, &conf, 1);
582 void ast_jb_configure(struct ast_channel *chan, const struct ast_jb_conf *conf)
584 memcpy(&ast_channel_jb(chan)->conf, conf, sizeof(*conf));
588 void ast_jb_get_config(const struct ast_channel *chan, struct ast_jb_conf *conf)
590 memcpy(conf, &ast_channel_jb((struct ast_channel *) chan)->conf, sizeof(*conf));
593 void ast_jb_empty_and_reset(struct ast_channel *c0, struct ast_channel *c1)
595 struct ast_jb *jb0 = ast_channel_jb(c0);
596 struct ast_jb *jb1 = ast_channel_jb(c1);
597 int c0_use_jb = ast_test_flag(jb0, JB_USE);
598 int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
599 int c1_use_jb = ast_test_flag(jb1, JB_USE);
600 int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
602 if (c0_use_jb && c0_jb_is_created && jb0->impl->empty_and_reset) {
603 jb0->impl->empty_and_reset(jb0->jbobj);
606 if (c1_use_jb && c1_jb_is_created && jb1->impl->empty_and_reset) {
607 jb1->impl->empty_and_reset(jb1->jbobj);
611 /* Implementation functions */
614 static void * jb_create_fixed(struct ast_jb_conf *general_config)
616 struct fixed_jb_conf conf;
618 conf.jbsize = general_config->max_size;
619 conf.resync_threshold = general_config->resync_threshold;
621 return fixed_jb_new(&conf);
624 static void jb_destroy_fixed(void *jb)
626 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
628 /* Ensure the fixed jb is empty - otherwise it will raise an ASSERT */
629 jb_empty_and_reset_fixed(jb);
632 fixed_jb_destroy(fixedjb);
636 static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now)
638 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
641 res = fixed_jb_put_first(fixedjb, fin, fin->len, fin->ts, now);
643 return fixed_to_abstract_code[res];
647 static int jb_put_fixed(void *jb, struct ast_frame *fin, long now)
649 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
652 res = fixed_jb_put(fixedjb, fin, fin->len, fin->ts, now);
654 return fixed_to_abstract_code[res];
658 static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl)
660 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
661 struct fixed_jb_frame frame;
664 res = fixed_jb_get(fixedjb, &frame, now, interpl);
667 return fixed_to_abstract_code[res];
671 static long jb_next_fixed(void *jb)
673 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
675 return fixed_jb_next(fixedjb);
679 static int jb_remove_fixed(void *jb, struct ast_frame **fout)
681 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
682 struct fixed_jb_frame frame;
685 res = fixed_jb_remove(fixedjb, &frame);
688 return fixed_to_abstract_code[res];
692 static void jb_force_resynch_fixed(void *jb)
694 struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
696 fixed_jb_set_force_resynch(fixedjb);
699 static void jb_empty_and_reset_fixed(void *jb)
701 struct fixed_jb *fixedjb = jb;
702 struct fixed_jb_frame f;
704 while (fixed_jb_remove(fixedjb, &f) == FIXED_JB_OK) {
711 static void *jb_create_adaptive(struct ast_jb_conf *general_config)
714 jitterbuf *adaptivejb;
716 adaptivejb = jb_new();
718 jbconf.max_jitterbuf = general_config->max_size;
719 jbconf.resync_threshold = general_config->resync_threshold;
720 jbconf.max_contig_interp = 10;
721 jbconf.target_extra = general_config->target_extra;
722 jb_setconf(adaptivejb, &jbconf);
729 static void jb_destroy_adaptive(void *jb)
731 jitterbuf *adaptivejb = (jitterbuf *) jb;
733 jb_destroy(adaptivejb);
737 static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now)
739 return jb_put_adaptive(jb, fin, now);
743 static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now)
745 jitterbuf *adaptivejb = (jitterbuf *) jb;
748 res = jb_put(adaptivejb, fin, JB_TYPE_VOICE, fin->len, fin->ts, now);
750 return adaptive_to_abstract_code[res];
754 static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl)
756 jitterbuf *adaptivejb = (jitterbuf *) jb;
760 res = jb_get(adaptivejb, &frame, now, interpl);
763 return adaptive_to_abstract_code[res];
767 static long jb_next_adaptive(void *jb)
769 jitterbuf *adaptivejb = (jitterbuf *) jb;
771 return jb_next(adaptivejb);
775 static int jb_remove_adaptive(void *jb, struct ast_frame **fout)
777 jitterbuf *adaptivejb = (jitterbuf *) jb;
781 res = jb_getall(adaptivejb, &frame);
784 return adaptive_to_abstract_code[res];
788 static void jb_force_resynch_adaptive(void *jb)
792 static void jb_empty_and_reset_adaptive(void *jb)
794 jitterbuf *adaptivejb = jb;
797 while (jb_getall(adaptivejb, &f) == JB_OK) {
801 jb_reset(adaptivejb);
804 const struct ast_jb_impl *ast_jb_get_impl(enum ast_jb_type type)
807 for (i = 0; i < ARRAY_LEN(avail_impl); i++) {
808 if (avail_impl[i].type == type) {
809 return &avail_impl[i];
815 #define DEFAULT_TIMER_INTERVAL 20
816 #define DEFAULT_SIZE 200
817 #define DEFAULT_TARGET_EXTRA 40
818 #define DEFAULT_RESYNC 1000
819 #define DEFAULT_TYPE AST_JB_FIXED
821 struct jb_framedata {
822 const struct ast_jb_impl *jb_impl;
823 struct ast_jb_conf jb_conf;
824 struct timeval start_tv;
825 struct ast_format *last_format;
826 struct ast_timer *timer;
827 int timer_interval; /* ms between deliveries */
833 static void jb_framedata_destroy(struct jb_framedata *framedata)
835 if (framedata->timer) {
836 ast_timer_close(framedata->timer);
837 framedata->timer = NULL;
839 if (framedata->jb_impl && framedata->jb_obj) {
841 while (framedata->jb_impl->remove(framedata->jb_obj, &f) == AST_JB_IMPL_OK) {
844 framedata->jb_impl->destroy(framedata->jb_obj);
845 framedata->jb_obj = NULL;
847 ao2_cleanup(framedata->last_format);
851 void ast_jb_conf_default(struct ast_jb_conf *conf)
853 conf->max_size = DEFAULT_SIZE;
854 conf->resync_threshold = DEFAULT_RESYNC;
855 ast_copy_string(conf->impl, "fixed", sizeof(conf->impl));
856 conf->target_extra = DEFAULT_TARGET_EXTRA;
859 static void datastore_destroy_cb(void *data) {
861 ast_debug(1, "JITTERBUFFER datastore destroyed\n");
864 static const struct ast_datastore_info jb_datastore = {
865 .type = "jitterbuffer",
866 .destroy = datastore_destroy_cb
869 static void hook_destroy_cb(void *framedata)
871 ast_debug(1, "JITTERBUFFER hook destroyed\n");
872 jb_framedata_destroy((struct jb_framedata *) framedata);
875 static struct ast_frame *hook_event_cb(struct ast_channel *chan, struct ast_frame *frame, enum ast_framehook_event event, void *data)
877 struct jb_framedata *framedata = data;
878 struct timeval now_tv;
880 int putframe = 0; /* signifies if audio frame was placed into the buffer or not */
883 case AST_FRAMEHOOK_EVENT_READ:
885 case AST_FRAMEHOOK_EVENT_ATTACHED:
886 case AST_FRAMEHOOK_EVENT_DETACHED:
887 case AST_FRAMEHOOK_EVENT_WRITE:
891 if (ast_channel_fdno(chan) == AST_JITTERBUFFER_FD && framedata->timer) {
892 if (ast_timer_ack(framedata->timer, 1) < 0) {
893 ast_log(LOG_ERROR, "Failed to acknowledge timer in jitter buffer\n");
902 now_tv = ast_tvnow();
903 now = ast_tvdiff_ms(now_tv, framedata->start_tv);
905 if (frame->frametype == AST_FRAME_VOICE) {
907 struct ast_frame *jbframe;
909 if (!ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO) || frame->len < 2 || frame->ts < 0) {
910 /* only frames with timing info can enter the jitterbuffer */
914 jbframe = ast_frisolate(frame);
915 ao2_replace(framedata->last_format, frame->subclass.format);
917 if (frame->len && (frame->len != framedata->timer_interval)) {
918 framedata->timer_interval = frame->len;
919 ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
921 if (!framedata->first) {
922 framedata->first = 1;
923 res = framedata->jb_impl->put_first(framedata->jb_obj, jbframe, now);
925 res = framedata->jb_impl->put(framedata->jb_obj, jbframe, now);
927 if (res == AST_JB_IMPL_OK) {
928 frame = &ast_null_frame;
933 if (frame->frametype == AST_FRAME_NULL) {
935 long next = framedata->jb_impl->next(framedata->jb_obj);
937 /* If now is earlier than the next expected output frame
938 * from the jitterbuffer we may choose to pass on retrieving
939 * a frame during this read iteration. The only exception
940 * to this rule is when an audio frame is placed into the buffer
941 * and the time for the next frame to come out of the buffer is
942 * at least within the timer_interval of the next output frame. By
943 * doing this we are able to feed off the timing of the input frames
944 * and only rely on our jitterbuffer timer when frames are dropped.
945 * During testing, this hybrid form of timing gave more reliable results. */
947 long int diff = next - now;
950 } else if (diff >= framedata->timer_interval) {
955 res = framedata->jb_impl->get(framedata->jb_obj, &frame, now, framedata->timer_interval);
958 /* got it, and pass it through */
960 case AST_JB_IMPL_DROP:
962 frame = &ast_null_frame;
964 case AST_JB_IMPL_INTERP:
965 if (framedata->last_format) {
966 struct ast_frame tmp = { 0, };
967 tmp.frametype = AST_FRAME_VOICE;
968 tmp.subclass.format = framedata->last_format;
969 /* example: 8000hz / (1000 / 20ms) = 160 samples */
970 tmp.samples = ast_format_get_sample_rate(framedata->last_format) / (1000 / framedata->timer_interval);
971 tmp.delivery = ast_tvadd(framedata->start_tv, ast_samp2tv(next, 1000));
972 tmp.offset = AST_FRIENDLY_OFFSET;
973 tmp.src = "func_jitterbuffer interpolation";
974 frame = ast_frdup(&tmp);
977 /* else fall through */
978 case AST_JB_IMPL_NOFRAME:
979 frame = &ast_null_frame;
984 if (frame->frametype == AST_FRAME_CONTROL) {
985 switch(frame->subclass.integer) {
986 case AST_CONTROL_HOLD:
987 case AST_CONTROL_UNHOLD:
988 case AST_CONTROL_T38_PARAMETERS:
989 case AST_CONTROL_SRCUPDATE:
990 case AST_CONTROL_SRCCHANGE:
991 framedata->jb_impl->force_resync(framedata->jb_obj);
1002 static int jb_framedata_init(struct jb_framedata *framedata, struct ast_jb_conf *jb_conf)
1004 int jb_impl_type = DEFAULT_TYPE;
1005 /* Initialize defaults */
1006 framedata->timer_fd = -1;
1007 memcpy(&framedata->jb_conf, jb_conf, sizeof(*jb_conf));
1009 /* Figure out implementation type from the configuration implementation string */
1010 if (!ast_strlen_zero(jb_conf->impl)) {
1011 if (!strcasecmp(jb_conf->impl, "fixed")) {
1012 jb_impl_type = AST_JB_FIXED;
1013 } else if (!strcasecmp(jb_conf->impl, "adaptive")) {
1014 jb_impl_type = AST_JB_ADAPTIVE;
1016 ast_log(LOG_WARNING, "Unknown Jitterbuffer type %s. Failed to create jitterbuffer.\n", jb_conf->impl);
1021 if (!(framedata->jb_impl = ast_jb_get_impl(jb_impl_type))) {
1025 if (!(framedata->timer = ast_timer_open())) {
1029 framedata->timer_fd = ast_timer_fd(framedata->timer);
1030 framedata->timer_interval = DEFAULT_TIMER_INTERVAL;
1031 ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
1032 framedata->start_tv = ast_tvnow();
1034 framedata->jb_obj = framedata->jb_impl->create(&framedata->jb_conf);
1039 void ast_jb_create_framehook(struct ast_channel *chan, struct ast_jb_conf *jb_conf, int prefer_existing)
1041 struct jb_framedata *framedata;
1042 struct ast_datastore *datastore = NULL;
1043 struct ast_framehook_interface interface = {
1044 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
1045 .event_cb = hook_event_cb,
1046 .destroy_cb = hook_destroy_cb,
1050 /* If disabled, strip any existing jitterbuffer and don't replace it. */
1051 if (!strcasecmp(jb_conf->impl, "disabled")) {
1053 ast_channel_lock(chan);
1054 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1055 id = datastore->data;
1056 ast_framehook_detach(chan, *id);
1057 ast_channel_datastore_remove(chan, datastore);
1059 ast_channel_unlock(chan);
1063 if (!(framedata = ast_calloc(1, sizeof(*framedata)))) {
1067 if (jb_framedata_init(framedata, jb_conf)) {
1068 jb_framedata_destroy(framedata);
1072 interface.data = framedata;
1074 ast_channel_lock(chan);
1075 i = ast_framehook_attach(chan, &interface);
1078 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1079 /* There is already a jitterbuffer on the channel. */
1080 if (prefer_existing) {
1081 /* We prefer the existing jitterbuffer, so remove the new one and keep the old one. */
1082 ast_framehook_detach(chan, i);
1083 ast_channel_unlock(chan);
1086 /* We prefer the new jitterbuffer, so strip the old one. */
1087 id = datastore->data;
1088 ast_framehook_detach(chan, *id);
1089 ast_channel_datastore_remove(chan, datastore);
1092 if (!(datastore = ast_datastore_alloc(&jb_datastore, NULL))) {
1093 ast_framehook_detach(chan, i);
1094 ast_channel_unlock(chan);
1098 if (!(id = ast_calloc(1, sizeof(int)))) {
1099 ast_datastore_free(datastore);
1100 ast_framehook_detach(chan, i);
1101 ast_channel_unlock(chan);
1105 *id = i; /* Store off the id. The channel is still locked so it is safe to access this ptr. */
1106 datastore->data = id;
1107 ast_channel_datastore_add(chan, datastore);
1109 ast_channel_set_fd(chan, AST_JITTERBUFFER_FD, framedata->timer_fd);
1111 jb_framedata_destroy(framedata);
1114 ast_channel_unlock(chan);