264ee97e620562a1eedf37c95e5b708f4c0ba268
[asterisk/asterisk.git] / main / abstract_jb.c
1 /*
2  * abstract_jb: common implementation-independent jitterbuffer stuff
3  *
4  * Copyright (C) 2005, Attractel OOD
5  *
6  * Contributors:
7  * Slav Klenov <slav@securax.org>
8  *
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.
14  *
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.
18  *
19  * A license has been granted to Digium (via disclaimer) for the use of
20  * this code.
21  */
22
23 /*! \file
24  *
25  * \brief Common implementation-independent jitterbuffer stuff.
26  *
27  * \author Slav Klenov <slav@securax.org>
28  *
29  *
30  */
31
32 /*** MODULEINFO
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 #include "asterisk/frame.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/term.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/timing.h"
44
45 #include "asterisk/abstract_jb.h"
46 #include "fixedjitterbuf.h"
47 #include "jitterbuf.h"
48
49 /*! Internal jb flags */
50 enum {
51         JB_USE =                  (1 << 0),
52         JB_TIMEBASE_INITIALIZED = (1 << 1),
53         JB_CREATED =              (1 << 2)
54 };
55
56
57 /* Implementation functions */
58 /* fixed */
59 static void *jb_create_fixed(struct ast_jb_conf *general_config);
60 static void jb_destroy_fixed(void *jb);
61 static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now);
62 static int jb_put_fixed(void *jb, struct ast_frame *fin, long now);
63 static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl);
64 static long jb_next_fixed(void *jb);
65 static int jb_remove_fixed(void *jb, struct ast_frame **fout);
66 static void jb_force_resynch_fixed(void *jb);
67 static void jb_empty_and_reset_fixed(void *jb);
68 /* adaptive */
69 static void * jb_create_adaptive(struct ast_jb_conf *general_config);
70 static void jb_destroy_adaptive(void *jb);
71 static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now);
72 static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now);
73 static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl);
74 static long jb_next_adaptive(void *jb);
75 static int jb_remove_adaptive(void *jb, struct ast_frame **fout);
76 static void jb_force_resynch_adaptive(void *jb);
77 static void jb_empty_and_reset_adaptive(void *jb);
78
79 /* Available jb implementations */
80 static const struct ast_jb_impl avail_impl[] = {
81         {
82                 .name = "fixed",
83                 .type = AST_JB_FIXED,
84                 .create = jb_create_fixed,
85                 .destroy = jb_destroy_fixed,
86                 .put_first = jb_put_first_fixed,
87                 .put = jb_put_fixed,
88                 .get = jb_get_fixed,
89                 .next = jb_next_fixed,
90                 .remove = jb_remove_fixed,
91                 .force_resync = jb_force_resynch_fixed,
92                 .empty_and_reset = jb_empty_and_reset_fixed,
93         },
94         {
95                 .name = "adaptive",
96                 .type = AST_JB_ADAPTIVE,
97                 .create = jb_create_adaptive,
98                 .destroy = jb_destroy_adaptive,
99                 .put_first = jb_put_first_adaptive,
100                 .put = jb_put_adaptive,
101                 .get = jb_get_adaptive,
102                 .next = jb_next_adaptive,
103                 .remove = jb_remove_adaptive,
104                 .force_resync = jb_force_resynch_adaptive,
105                 .empty_and_reset = jb_empty_and_reset_adaptive,
106         }
107 };
108
109 static int default_impl = 0;
110
111 /* Translations between impl and abstract return codes */
112 static const int fixed_to_abstract_code[] =
113         {AST_JB_IMPL_OK, AST_JB_IMPL_DROP, AST_JB_IMPL_INTERP, AST_JB_IMPL_NOFRAME};
114 static const int adaptive_to_abstract_code[] =
115         {AST_JB_IMPL_OK, AST_JB_IMPL_NOFRAME, AST_JB_IMPL_NOFRAME, AST_JB_IMPL_INTERP, AST_JB_IMPL_DROP, AST_JB_IMPL_OK};
116
117 /* JB_GET actions (used only for the frames log) */
118 static const char * const jb_get_actions[] = {"Delivered", "Dropped", "Interpolated", "No"};
119
120 /*! \brief Macros for the frame log files */
121 #define jb_framelog(...) do { \
122         if (jb->logfile) { \
123                 fprintf(jb->logfile, __VA_ARGS__); \
124                 fflush(jb->logfile); \
125         } \
126 } while (0)
127
128
129 /* Internal utility functions */
130 static void jb_choose_impl(struct ast_channel *chan);
131 static void jb_get_and_deliver(struct ast_channel *chan);
132 static int create_jb(struct ast_channel *chan, struct ast_frame *first_frame);
133 static long get_now(struct ast_jb *jb, struct timeval *tv);
134
135
136 /* Interface ast jb functions impl */
137
138
139 static void jb_choose_impl(struct ast_channel *chan)
140 {
141         struct ast_jb *jb = ast_channel_jb(chan);
142         struct ast_jb_conf *jbconf = &jb->conf;
143         const struct ast_jb_impl *test_impl;
144         int i, avail_impl_count = ARRAY_LEN(avail_impl);
145
146         jb->impl = &avail_impl[default_impl];
147
148         if (ast_strlen_zero(jbconf->impl)) {
149                 return;
150         }
151
152         for (i = 0; i < avail_impl_count; i++) {
153                 test_impl = &avail_impl[i];
154                 if (!strcasecmp(jbconf->impl, test_impl->name)) {
155                         jb->impl = test_impl;
156                         return;
157                 }
158         }
159 }
160
161 int ast_jb_do_usecheck(struct ast_channel *c0, struct ast_channel *c1)
162 {
163         struct ast_jb *jb0 = ast_channel_jb(c0);
164         struct ast_jb *jb1 = ast_channel_jb(c1);
165         struct ast_jb_conf *conf0 = &jb0->conf;
166         struct ast_jb_conf *conf1 = &jb1->conf;
167         int c0_wants_jitter = ast_channel_tech(c0)->properties & AST_CHAN_TP_WANTSJITTER;
168         int c0_creates_jitter = ast_channel_tech(c0)->properties & AST_CHAN_TP_CREATESJITTER;
169         int c0_jb_enabled = ast_test_flag(conf0, AST_JB_ENABLED);
170         int c0_force_jb = ast_test_flag(conf0, AST_JB_FORCED);
171         int c0_jb_timebase_initialized = ast_test_flag(jb0, JB_TIMEBASE_INITIALIZED);
172         int c0_jb_created = ast_test_flag(jb0, JB_CREATED);
173         int c1_wants_jitter = ast_channel_tech(c1)->properties & AST_CHAN_TP_WANTSJITTER;
174         int c1_creates_jitter = ast_channel_tech(c1)->properties & AST_CHAN_TP_CREATESJITTER;
175         int c1_jb_enabled = ast_test_flag(conf1, AST_JB_ENABLED);
176         int c1_force_jb = ast_test_flag(conf1, AST_JB_FORCED);
177         int c1_jb_timebase_initialized = ast_test_flag(jb1, JB_TIMEBASE_INITIALIZED);
178         int c1_jb_created = ast_test_flag(jb1, JB_CREATED);
179         int inuse = 0;
180
181         /* Determine whether audio going to c0 needs a jitter buffer */
182         if (((!c0_wants_jitter && c1_creates_jitter) || (c0_force_jb && c1_creates_jitter)) && c0_jb_enabled) {
183                 ast_set_flag(jb0, JB_USE);
184                 if (!c0_jb_timebase_initialized) {
185                         if (c1_jb_timebase_initialized) {
186                                 memcpy(&jb0->timebase, &jb1->timebase, sizeof(struct timeval));
187                         } else {
188                                 gettimeofday(&jb0->timebase, NULL);
189                         }
190                         ast_set_flag(jb0, JB_TIMEBASE_INITIALIZED);
191                 }
192
193                 if (!c0_jb_created) {
194                         jb_choose_impl(c0);
195                 }
196
197                 inuse = 1;
198         }
199
200         /* Determine whether audio going to c1 needs a jitter buffer */
201         if (((!c1_wants_jitter && c0_creates_jitter) || (c1_force_jb && c0_creates_jitter)) && c1_jb_enabled) {
202                 ast_set_flag(jb1, JB_USE);
203                 if (!c1_jb_timebase_initialized) {
204                         if (c0_jb_timebase_initialized) {
205                                 memcpy(&jb1->timebase, &jb0->timebase, sizeof(struct timeval));
206                         } else {
207                                 gettimeofday(&jb1->timebase, NULL);
208                         }
209                         ast_set_flag(jb1, JB_TIMEBASE_INITIALIZED);
210                 }
211
212                 if (!c1_jb_created) {
213                         jb_choose_impl(c1);
214                 }
215
216                 inuse = 1;
217         }
218
219         return inuse;
220 }
221
222 int ast_jb_get_when_to_wakeup(struct ast_channel *c0, struct ast_channel *c1, int time_left)
223 {
224         struct ast_jb *jb0 = ast_channel_jb(c0);
225         struct ast_jb *jb1 = ast_channel_jb(c1);
226         int c0_use_jb = ast_test_flag(jb0, JB_USE);
227         int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
228         int c1_use_jb = ast_test_flag(jb1, JB_USE);
229         int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
230         int wait, wait0, wait1;
231         struct timeval tv_now;
232
233         if (time_left == 0) {
234                 /* No time left - the bridge will be retried */
235                 /* TODO: Test disable this */
236                 /*return 0;*/
237         }
238
239         if (time_left < 0) {
240                 time_left = INT_MAX;
241         }
242
243         gettimeofday(&tv_now, NULL);
244
245         wait0 = (c0_use_jb && c0_jb_is_created) ? jb0->next - get_now(jb0, &tv_now) : time_left;
246         wait1 = (c1_use_jb && c1_jb_is_created) ? jb1->next - get_now(jb1, &tv_now) : time_left;
247
248         wait = wait0 < wait1 ? wait0 : wait1;
249         wait = wait < time_left ? wait : time_left;
250
251         if (wait == INT_MAX) {
252                 wait = -1;
253         } else if (wait < 1) {
254                 /* don't let wait=0, because this can cause the pbx thread to loop without any sleeping at all */
255                 wait = 1;
256         }
257
258         return wait;
259 }
260
261
262 int ast_jb_put(struct ast_channel *chan, struct ast_frame *f)
263 {
264         struct ast_jb *jb = ast_channel_jb(chan);
265         const struct ast_jb_impl *jbimpl = jb->impl;
266         void *jbobj = jb->jbobj;
267         struct ast_frame *frr;
268         long now = 0;
269
270         if (!ast_test_flag(jb, JB_USE))
271                 return -1;
272
273         if (f->frametype != AST_FRAME_VOICE) {
274                 if (f->frametype == AST_FRAME_DTMF && ast_test_flag(jb, JB_CREATED)) {
275                         jb_framelog("JB_PUT {now=%ld}: Received DTMF frame. Force resynching jb...\n", now);
276                         jbimpl->force_resync(jbobj);
277                 }
278
279                 return -1;
280         }
281
282         /* We consider an enabled jitterbuffer should receive frames with valid timing info. */
283         if (!ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO) || f->len < 2 || f->ts < 0) {
284                 ast_log(LOG_WARNING, "%s received frame with invalid timing info: "
285                         "has_timing_info=%u, len=%ld, ts=%ld, src=%s\n",
286                         ast_channel_name(chan), ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO), f->len, f->ts, f->src);
287                 return -1;
288         }
289
290         frr = ast_frdup(f);
291
292         if (!frr) {
293                 ast_log(LOG_ERROR, "Failed to isolate frame for the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
294                 return -1;
295         }
296
297         if (!ast_test_flag(jb, JB_CREATED)) {
298                 if (create_jb(chan, frr)) {
299                         ast_frfree(frr);
300                         /* Disable the jitterbuffer */
301                         ast_clear_flag(jb, JB_USE);
302                         return -1;
303                 }
304
305                 ast_set_flag(jb, JB_CREATED);
306                 return 0;
307         } else {
308                 now = get_now(jb, NULL);
309                 if (jbimpl->put(jbobj, frr, now) != AST_JB_IMPL_OK) {
310                         jb_framelog("JB_PUT {now=%ld}: Dropped frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
311                         ast_frfree(frr);
312                         /*return -1;*/
313                         /* TODO: Check this fix - should return 0 here, because the dropped frame shouldn't
314                            be delivered at all */
315                         return 0;
316                 }
317
318                 jb->next = jbimpl->next(jbobj);
319
320                 jb_framelog("JB_PUT {now=%ld}: Queued frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
321
322                 return 0;
323         }
324 }
325
326
327 void ast_jb_get_and_deliver(struct ast_channel *c0, struct ast_channel *c1)
328 {
329         struct ast_jb *jb0 = ast_channel_jb(c0);
330         struct ast_jb *jb1 = ast_channel_jb(c1);
331         int c0_use_jb = ast_test_flag(jb0, JB_USE);
332         int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
333         int c1_use_jb = ast_test_flag(jb1, JB_USE);
334         int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
335
336         if (c0_use_jb && c0_jb_is_created)
337                 jb_get_and_deliver(c0);
338
339         if (c1_use_jb && c1_jb_is_created)
340                 jb_get_and_deliver(c1);
341 }
342
343
344 static void jb_get_and_deliver(struct ast_channel *chan)
345 {
346         struct ast_jb *jb = ast_channel_jb(chan);
347         const struct ast_jb_impl *jbimpl = jb->impl;
348         void *jbobj = jb->jbobj;
349         struct ast_frame *f, finterp = { .frametype = AST_FRAME_VOICE, };
350         long now;
351         int interpolation_len, res;
352
353         now = get_now(jb, NULL);
354         jb->next = jbimpl->next(jbobj);
355         if (now < jb->next) {
356                 jb_framelog("\tJB_GET {now=%ld}: now < next=%ld\n", now, jb->next);
357                 return;
358         }
359
360         while (now >= jb->next) {
361                 interpolation_len = ast_format_get_default_ms(jb->last_format);
362
363                 res = jbimpl->get(jbobj, &f, now, interpolation_len);
364
365                 switch (res) {
366                 case AST_JB_IMPL_OK:
367                         /* deliver the frame */
368                         ast_write(chan, f);
369                 case AST_JB_IMPL_DROP:
370                         jb_framelog("\tJB_GET {now=%ld}: %s frame with ts=%ld and len=%ld\n",
371                                 now, jb_get_actions[res], f->ts, f->len);
372                         ao2_replace(jb->last_format, f->subclass.format);
373                         ast_frfree(f);
374                         break;
375                 case AST_JB_IMPL_INTERP:
376                         /* interpolate a frame */
377                         f = &finterp;
378                         f->subclass.format = jb->last_format;
379                         f->samples  = interpolation_len * 8;
380                         f->src  = "JB interpolation";
381                         f->delivery = ast_tvadd(jb->timebase, ast_samp2tv(jb->next, 1000));
382                         f->offset = AST_FRIENDLY_OFFSET;
383                         /* deliver the interpolated frame */
384                         ast_write(chan, f);
385                         jb_framelog("\tJB_GET {now=%ld}: Interpolated frame with len=%d\n", now, interpolation_len);
386                         break;
387                 case AST_JB_IMPL_NOFRAME:
388                         ast_log(LOG_WARNING,
389                                 "AST_JB_IMPL_NOFRAME is returned from the %s jb when now=%ld >= next=%ld, jbnext=%ld!\n",
390                                 jbimpl->name, now, jb->next, jbimpl->next(jbobj));
391                         jb_framelog("\tJB_GET {now=%ld}: No frame for now!?\n", now);
392                         return;
393                 default:
394                         ast_log(LOG_ERROR, "This should never happen!\n");
395                         ast_assert("JB type unknown" == NULL);
396                         break;
397                 }
398
399                 jb->next = jbimpl->next(jbobj);
400         }
401 }
402
403
404 static int create_jb(struct ast_channel *chan, struct ast_frame *frr)
405 {
406         struct ast_jb *jb = ast_channel_jb(chan);
407         struct ast_jb_conf *jbconf = &jb->conf;
408         const struct ast_jb_impl *jbimpl = jb->impl;
409         void *jbobj;
410         long now;
411         char logfile_pathname[20 + AST_JB_IMPL_NAME_SIZE + 2*AST_CHANNEL_NAME + 1];
412         char name1[AST_CHANNEL_NAME], name2[AST_CHANNEL_NAME], *tmp;
413         int res;
414
415         jbobj = jb->jbobj = jbimpl->create(jbconf);
416         if (!jbobj) {
417                 ast_log(LOG_WARNING, "Failed to create jitterbuffer on channel '%s'\n", ast_channel_name(chan));
418                 return -1;
419         }
420
421         now = get_now(jb, NULL);
422         res = jbimpl->put_first(jbobj, frr, now);
423
424         /* The result of putting the first frame should not differ from OK. However, its possible
425            some implementations (i.e. adaptive's when resynch_threshold is specified) to drop it. */
426         if (res != AST_JB_IMPL_OK) {
427                 ast_log(LOG_WARNING, "Failed to put first frame in the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
428                 /*
429                 jbimpl->destroy(jbobj);
430                 return -1;
431                 */
432         }
433
434         /* Init next */
435         jb->next = jbimpl->next(jbobj);
436
437         /* Init last format for a first time. */
438         jb->last_format = ao2_bump(frr->subclass.format);
439
440         /* Create a frame log file */
441         if (ast_test_flag(jbconf, AST_JB_LOG)) {
442                 RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(chan), ast_channel_cleanup);
443                 char safe_logfile[30] = "/tmp/logfile-XXXXXX";
444                 int safe_fd;
445
446                 snprintf(name2, sizeof(name2), "%s", ast_channel_name(chan));
447                 while ((tmp = strchr(name2, '/'))) {
448                         *tmp = '#';
449                 }
450
451                 /* We should always have bridged chan if a jitterbuffer is in use */
452                 ast_assert(bridged != NULL);
453
454                 snprintf(name1, sizeof(name1), "%s", ast_channel_name(bridged));
455                 while ((tmp = strchr(name1, '/'))) {
456                         *tmp = '#';
457                 }
458
459                 snprintf(logfile_pathname, sizeof(logfile_pathname),
460                         "/tmp/ast_%s_jb_%s--%s.log", jbimpl->name, name1, name2);
461                 unlink(logfile_pathname);
462                 safe_fd = mkstemp(safe_logfile);
463                 if (safe_fd < 0 || link(safe_logfile, logfile_pathname) || unlink(safe_logfile) || !(jb->logfile = fdopen(safe_fd, "w+b"))) {
464                         ast_log(LOG_ERROR, "Failed to create frame log file with pathname '%s': %s\n", logfile_pathname, strerror(errno));
465                         jb->logfile = NULL;
466                         if (safe_fd > -1) {
467                                 close(safe_fd);
468                         }
469                 }
470
471                 if (res == AST_JB_IMPL_OK) {
472                         jb_framelog("JB_PUT_FIRST {now=%ld}: Queued frame with ts=%ld and len=%ld\n",
473                                 now, frr->ts, frr->len);
474                 } else {
475                         jb_framelog("JB_PUT_FIRST {now=%ld}: Dropped frame with ts=%ld and len=%ld\n",
476                                 now, frr->ts, frr->len);
477                 }
478         }
479
480         ast_verb(3, "%s jitterbuffer created on channel %s\n", jbimpl->name, ast_channel_name(chan));
481
482         /* Free the frame if it has not been queued in the jb */
483         if (res != AST_JB_IMPL_OK) {
484                 ast_frfree(frr);
485         }
486
487         return 0;
488 }
489
490
491 void ast_jb_destroy(struct ast_channel *chan)
492 {
493         struct ast_jb *jb = ast_channel_jb(chan);
494         const struct ast_jb_impl *jbimpl = jb->impl;
495         void *jbobj = jb->jbobj;
496         struct ast_frame *f;
497
498         if (jb->logfile) {
499                 fclose(jb->logfile);
500                 jb->logfile = NULL;
501         }
502
503         ao2_cleanup(jb->last_format);
504
505         if (ast_test_flag(jb, JB_CREATED)) {
506                 /* Remove and free all frames still queued in jb */
507                 while (jbimpl->remove(jbobj, &f) == AST_JB_IMPL_OK) {
508                         ast_frfree(f);
509                 }
510
511                 jbimpl->destroy(jbobj);
512                 jb->jbobj = NULL;
513
514                 ast_clear_flag(jb, JB_CREATED);
515
516                 ast_verb(3, "%s jitterbuffer destroyed on channel %s\n", jbimpl->name, ast_channel_name(chan));
517         }
518 }
519
520
521 static long get_now(struct ast_jb *jb, struct timeval *when)
522 {
523         struct timeval now;
524
525         if (!when) {
526                 when = &now;
527                 gettimeofday(when, NULL);
528         }
529
530         return ast_tvdiff_ms(*when, jb->timebase);
531 }
532
533
534 int ast_jb_read_conf(struct ast_jb_conf *conf, const char *varname, const char *value)
535 {
536         int prefixlen = sizeof(AST_JB_CONF_PREFIX) - 1;
537         const char *name;
538         int tmp;
539
540         if (strncasecmp(AST_JB_CONF_PREFIX, varname, prefixlen)) {
541                 return -1;
542         }
543
544         name = varname + prefixlen;
545
546         if (!strcasecmp(name, AST_JB_CONF_ENABLE)) {
547                 ast_set2_flag(conf, ast_true(value), AST_JB_ENABLED);
548         } else if (!strcasecmp(name, AST_JB_CONF_FORCE)) {
549                 ast_set2_flag(conf, ast_true(value), AST_JB_FORCED);
550         } else if (!strcasecmp(name, AST_JB_CONF_MAX_SIZE)) {
551                 if ((tmp = atoi(value)) > 0)
552                         conf->max_size = tmp;
553         } else if (!strcasecmp(name, AST_JB_CONF_RESYNCH_THRESHOLD)) {
554                 if ((tmp = atoi(value)) > 0)
555                         conf->resync_threshold = tmp;
556         } else if (!strcasecmp(name, AST_JB_CONF_IMPL)) {
557                 if (!ast_strlen_zero(value))
558                         snprintf(conf->impl, sizeof(conf->impl), "%s", value);
559         } else if (!strcasecmp(name, AST_JB_CONF_TARGET_EXTRA)) {
560                 if (sscanf(value, "%30d", &tmp) == 1) {
561                         conf->target_extra = tmp;
562                 }
563         } else if (!strcasecmp(name, AST_JB_CONF_LOG)) {
564                 ast_set2_flag(conf, ast_true(value), AST_JB_LOG);
565         } else {
566                 return -1;
567         }
568
569         return 0;
570 }
571
572 void ast_jb_enable_for_channel(struct ast_channel *chan)
573 {
574         struct ast_jb_conf conf = ast_channel_jb(chan)->conf;
575         if (ast_test_flag(&conf, AST_JB_ENABLED)) {
576                 ast_jb_create_framehook(chan, &conf, 1);
577         }
578 }
579
580 void ast_jb_configure(struct ast_channel *chan, const struct ast_jb_conf *conf)
581 {
582         memcpy(&ast_channel_jb(chan)->conf, conf, sizeof(*conf));
583 }
584
585
586 void ast_jb_get_config(const struct ast_channel *chan, struct ast_jb_conf *conf)
587 {
588         memcpy(conf, &ast_channel_jb((struct ast_channel *) chan)->conf, sizeof(*conf));
589 }
590
591 void ast_jb_empty_and_reset(struct ast_channel *c0, struct ast_channel *c1)
592 {
593         struct ast_jb *jb0 = ast_channel_jb(c0);
594         struct ast_jb *jb1 = ast_channel_jb(c1);
595         int c0_use_jb = ast_test_flag(jb0, JB_USE);
596         int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
597         int c1_use_jb = ast_test_flag(jb1, JB_USE);
598         int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
599
600         if (c0_use_jb && c0_jb_is_created && jb0->impl->empty_and_reset) {
601                 jb0->impl->empty_and_reset(jb0->jbobj);
602         }
603
604         if (c1_use_jb && c1_jb_is_created && jb1->impl->empty_and_reset) {
605                 jb1->impl->empty_and_reset(jb1->jbobj);
606         }
607 }
608
609 /* Implementation functions */
610
611 /* fixed */
612 static void * jb_create_fixed(struct ast_jb_conf *general_config)
613 {
614         struct fixed_jb_conf conf;
615
616         conf.jbsize = general_config->max_size;
617         conf.resync_threshold = general_config->resync_threshold;
618
619         return fixed_jb_new(&conf);
620 }
621
622 static void jb_destroy_fixed(void *jb)
623 {
624         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
625
626         /* Ensure the fixed jb is empty - otherwise it will raise an ASSERT */
627         jb_empty_and_reset_fixed(jb);
628
629         /* destroy the jb */
630         fixed_jb_destroy(fixedjb);
631 }
632
633
634 static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now)
635 {
636         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
637         int res;
638
639         res = fixed_jb_put_first(fixedjb, fin, fin->len, fin->ts, now);
640
641         return fixed_to_abstract_code[res];
642 }
643
644
645 static int jb_put_fixed(void *jb, struct ast_frame *fin, long now)
646 {
647         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
648         int res;
649
650         res = fixed_jb_put(fixedjb, fin, fin->len, fin->ts, now);
651
652         return fixed_to_abstract_code[res];
653 }
654
655
656 static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl)
657 {
658         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
659         struct fixed_jb_frame frame = { .data = &ast_null_frame };
660         int res;
661
662         res = fixed_jb_get(fixedjb, &frame, now, interpl);
663         *fout = frame.data;
664
665         return fixed_to_abstract_code[res];
666 }
667
668
669 static long jb_next_fixed(void *jb)
670 {
671         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
672
673         return fixed_jb_next(fixedjb);
674 }
675
676
677 static int jb_remove_fixed(void *jb, struct ast_frame **fout)
678 {
679         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
680         struct fixed_jb_frame frame;
681         int res;
682
683         res = fixed_jb_remove(fixedjb, &frame);
684         *fout = frame.data;
685
686         return fixed_to_abstract_code[res];
687 }
688
689
690 static void jb_force_resynch_fixed(void *jb)
691 {
692         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
693
694         fixed_jb_set_force_resynch(fixedjb);
695 }
696
697 static void jb_empty_and_reset_fixed(void *jb)
698 {
699         struct fixed_jb *fixedjb = jb;
700         struct fixed_jb_frame f;
701
702         while (fixed_jb_remove(fixedjb, &f) == FIXED_JB_OK) {
703                 ast_frfree(f.data);
704         }
705 }
706
707 /* adaptive */
708
709 static void *jb_create_adaptive(struct ast_jb_conf *general_config)
710 {
711         jb_conf jbconf;
712         jitterbuf *adaptivejb;
713
714         adaptivejb = jb_new();
715         if (adaptivejb) {
716                 jbconf.max_jitterbuf = general_config->max_size;
717                 jbconf.resync_threshold = general_config->resync_threshold;
718                 jbconf.max_contig_interp = 10;
719                 jbconf.target_extra = general_config->target_extra;
720                 jb_setconf(adaptivejb, &jbconf);
721         }
722
723         return adaptivejb;
724 }
725
726
727 static void jb_destroy_adaptive(void *jb)
728 {
729         jitterbuf *adaptivejb = (jitterbuf *) jb;
730
731         jb_destroy(adaptivejb);
732 }
733
734
735 static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now)
736 {
737         return jb_put_adaptive(jb, fin, now);
738 }
739
740
741 static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now)
742 {
743         jitterbuf *adaptivejb = (jitterbuf *) jb;
744         int res;
745
746         res = jb_put(adaptivejb, fin, JB_TYPE_VOICE, fin->len, fin->ts, now);
747
748         return adaptive_to_abstract_code[res];
749 }
750
751
752 static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl)
753 {
754         jitterbuf *adaptivejb = (jitterbuf *) jb;
755         jb_frame frame = { .data = &ast_null_frame };
756         int res;
757
758         res = jb_get(adaptivejb, &frame, now, interpl);
759         *fout = frame.data;
760
761         return adaptive_to_abstract_code[res];
762 }
763
764
765 static long jb_next_adaptive(void *jb)
766 {
767         jitterbuf *adaptivejb = (jitterbuf *) jb;
768
769         return jb_next(adaptivejb);
770 }
771
772
773 static int jb_remove_adaptive(void *jb, struct ast_frame **fout)
774 {
775         jitterbuf *adaptivejb = (jitterbuf *) jb;
776         jb_frame frame;
777         int res;
778
779         res = jb_getall(adaptivejb, &frame);
780         *fout = frame.data;
781
782         return adaptive_to_abstract_code[res];
783 }
784
785
786 static void jb_force_resynch_adaptive(void *jb)
787 {
788 }
789
790 static void jb_empty_and_reset_adaptive(void *jb)
791 {
792         jitterbuf *adaptivejb = jb;
793         jb_frame f;
794
795         while (jb_getall(adaptivejb, &f) == JB_OK) {
796                 ast_frfree(f.data);
797         }
798
799         jb_reset(adaptivejb);
800 }
801
802 const struct ast_jb_impl *ast_jb_get_impl(enum ast_jb_type type)
803 {
804         int i;
805         for (i = 0; i < ARRAY_LEN(avail_impl); i++) {
806                 if (avail_impl[i].type == type) {
807                         return &avail_impl[i];
808                 }
809         }
810         return NULL;
811 }
812
813 #define DEFAULT_TIMER_INTERVAL 20
814 #define DEFAULT_SIZE  200
815 #define DEFAULT_TARGET_EXTRA  40
816 #define DEFAULT_RESYNC  1000
817 #define DEFAULT_TYPE AST_JB_FIXED
818
819 struct jb_framedata {
820         const struct ast_jb_impl *jb_impl;
821         struct ast_jb_conf jb_conf;
822         struct timeval start_tv;
823         struct ast_format *last_format;
824         struct ast_timer *timer;
825         int timer_interval; /* ms between deliveries */
826         int timer_fd;
827         int first;
828         void *jb_obj;
829 };
830
831 static void jb_framedata_destroy(struct jb_framedata *framedata)
832 {
833         if (framedata->timer) {
834                 ast_timer_close(framedata->timer);
835                 framedata->timer = NULL;
836         }
837         if (framedata->jb_impl && framedata->jb_obj) {
838                 struct ast_frame *f;
839                 while (framedata->jb_impl->remove(framedata->jb_obj, &f) == AST_JB_IMPL_OK) {
840                         ast_frfree(f);
841                 }
842                 framedata->jb_impl->destroy(framedata->jb_obj);
843                 framedata->jb_obj = NULL;
844         }
845         ao2_cleanup(framedata->last_format);
846         ast_free(framedata);
847 }
848
849 void ast_jb_conf_default(struct ast_jb_conf *conf)
850 {
851         conf->max_size = DEFAULT_SIZE;
852         conf->resync_threshold = DEFAULT_RESYNC;
853         ast_copy_string(conf->impl, "fixed", sizeof(conf->impl));
854         conf->target_extra = DEFAULT_TARGET_EXTRA;
855 }
856
857 static void datastore_destroy_cb(void *data) {
858         ast_free(data);
859         ast_debug(1, "JITTERBUFFER datastore destroyed\n");
860 }
861
862 static const struct ast_datastore_info jb_datastore = {
863         .type = "jitterbuffer",
864         .destroy = datastore_destroy_cb
865 };
866
867 static void hook_destroy_cb(void *framedata)
868 {
869         ast_debug(1, "JITTERBUFFER hook destroyed\n");
870         jb_framedata_destroy((struct jb_framedata *) framedata);
871 }
872
873 static struct ast_frame *hook_event_cb(struct ast_channel *chan, struct ast_frame *frame, enum ast_framehook_event event, void *data)
874 {
875         struct jb_framedata *framedata = data;
876         struct timeval now_tv;
877         unsigned long now;
878         int putframe = 0; /* signifies if audio frame was placed into the buffer or not */
879
880         switch (event) {
881         case AST_FRAMEHOOK_EVENT_READ:
882                 break;
883         case AST_FRAMEHOOK_EVENT_ATTACHED:
884         case AST_FRAMEHOOK_EVENT_DETACHED:
885         case AST_FRAMEHOOK_EVENT_WRITE:
886                 return frame;
887         }
888
889         if (ast_channel_fdno(chan) == AST_JITTERBUFFER_FD && framedata->timer) {
890                 if (ast_timer_ack(framedata->timer, 1) < 0) {
891                         ast_log(LOG_ERROR, "Failed to acknowledge timer in jitter buffer\n");
892                         return frame;
893                 }
894         }
895
896         if (!frame) {
897                 return frame;
898         }
899
900         now_tv = ast_tvnow();
901         now = ast_tvdiff_ms(now_tv, framedata->start_tv);
902
903         if (frame->frametype == AST_FRAME_VOICE) {
904                 int res;
905                 struct ast_frame *jbframe;
906
907                 if (!ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO) || frame->len < 2 || frame->ts < 0) {
908                         /* only frames with timing info can enter the jitterbuffer */
909                         return frame;
910                 }
911
912                 jbframe = ast_frisolate(frame);
913                 ao2_replace(framedata->last_format, frame->subclass.format);
914
915                 if (frame->len && (frame->len != framedata->timer_interval)) {
916                         framedata->timer_interval = frame->len;
917                         ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
918                 }
919                 if (!framedata->first) {
920                         framedata->first = 1;
921                         res = framedata->jb_impl->put_first(framedata->jb_obj, jbframe, now);
922                 } else {
923                         res = framedata->jb_impl->put(framedata->jb_obj, jbframe, now);
924                 }
925
926                 if (res == AST_JB_IMPL_OK) {
927                         if (jbframe != frame) {
928                                 ast_frfree(frame);
929                         }
930                         frame = &ast_null_frame;
931                 } else if (jbframe != frame) {
932                         ast_frfree(jbframe);
933                 }
934                 putframe = 1;
935         }
936
937         if (frame->frametype == AST_FRAME_NULL) {
938                 int res;
939                 long next = framedata->jb_impl->next(framedata->jb_obj);
940
941                 /* If now is earlier than the next expected output frame
942                  * from the jitterbuffer we may choose to pass on retrieving
943                  * a frame during this read iteration.  The only exception
944                  * to this rule is when an audio frame is placed into the buffer
945                  * and the time for the next frame to come out of the buffer is
946                  * at least within the timer_interval of the next output frame. By
947                  * doing this we are able to feed off the timing of the input frames
948                  * and only rely on our jitterbuffer timer when frames are dropped.
949                  * During testing, this hybrid form of timing gave more reliable results. */
950                 if (now < next) {
951                         long int diff = next - now;
952                         if (!putframe) {
953                                 return frame;
954                         } else if (diff >= framedata->timer_interval) {
955                                 return frame;
956                         }
957                 }
958
959                 ast_frfree(frame);
960                 frame = &ast_null_frame;
961                 res = framedata->jb_impl->get(framedata->jb_obj, &frame, now, framedata->timer_interval);
962                 switch (res) {
963                 case AST_JB_IMPL_OK:
964                         /* got it, and pass it through */
965                         break;
966                 case AST_JB_IMPL_DROP:
967                         ast_frfree(frame);
968                         frame = &ast_null_frame;
969                         break;
970                 case AST_JB_IMPL_INTERP:
971                         if (framedata->last_format) {
972                                 struct ast_frame tmp = { 0, };
973
974                                 tmp.frametype = AST_FRAME_VOICE;
975                                 tmp.subclass.format = framedata->last_format;
976                                 /* example: 8000hz / (1000 / 20ms) = 160 samples */
977                                 tmp.samples = ast_format_get_sample_rate(framedata->last_format) / (1000 / framedata->timer_interval);
978                                 tmp.delivery = ast_tvadd(framedata->start_tv, ast_samp2tv(next, 1000));
979                                 tmp.offset = AST_FRIENDLY_OFFSET;
980                                 tmp.src  = "func_jitterbuffer interpolation";
981                                 ast_frfree(frame);
982                                 frame = ast_frdup(&tmp);
983                                 break;
984                         }
985                         /* else fall through */
986                 case AST_JB_IMPL_NOFRAME:
987                         ast_frfree(frame);
988                         frame = &ast_null_frame;
989                         break;
990                 }
991         }
992
993         if (frame->frametype == AST_FRAME_CONTROL) {
994                 switch(frame->subclass.integer) {
995                 case AST_CONTROL_HOLD:
996                 case AST_CONTROL_UNHOLD:
997                 case AST_CONTROL_T38_PARAMETERS:
998                 case AST_CONTROL_SRCUPDATE:
999                 case AST_CONTROL_SRCCHANGE:
1000                         framedata->jb_impl->force_resync(framedata->jb_obj);
1001                         break;
1002                 default:
1003                         break;
1004                 }
1005         }
1006
1007         return frame;
1008 }
1009
1010 /* set defaults */
1011 static int jb_framedata_init(struct jb_framedata *framedata, struct ast_jb_conf *jb_conf)
1012 {
1013         int jb_impl_type = DEFAULT_TYPE;
1014         /* Initialize defaults */
1015         framedata->timer_fd = -1;
1016         memcpy(&framedata->jb_conf, jb_conf, sizeof(*jb_conf));
1017
1018         /* Figure out implementation type from the configuration implementation string */
1019         if (!ast_strlen_zero(jb_conf->impl)) {
1020                 if (!strcasecmp(jb_conf->impl, "fixed")) {
1021                         jb_impl_type = AST_JB_FIXED;
1022                 } else if (!strcasecmp(jb_conf->impl, "adaptive")) {
1023                         jb_impl_type = AST_JB_ADAPTIVE;
1024                 } else {
1025                         ast_log(LOG_WARNING, "Unknown Jitterbuffer type %s. Failed to create jitterbuffer.\n", jb_conf->impl);
1026                         return -1;
1027                 }
1028         }
1029
1030         if (!(framedata->jb_impl = ast_jb_get_impl(jb_impl_type))) {
1031                 return -1;
1032         }
1033
1034         if (!(framedata->timer = ast_timer_open())) {
1035                 return -1;
1036         }
1037
1038         framedata->timer_fd = ast_timer_fd(framedata->timer);
1039         framedata->timer_interval = DEFAULT_TIMER_INTERVAL;
1040         ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
1041         framedata->start_tv = ast_tvnow();
1042
1043         framedata->jb_obj = framedata->jb_impl->create(&framedata->jb_conf);
1044         return 0;
1045 }
1046
1047
1048 void ast_jb_create_framehook(struct ast_channel *chan, struct ast_jb_conf *jb_conf, int prefer_existing)
1049 {
1050         struct jb_framedata *framedata;
1051         struct ast_datastore *datastore = NULL;
1052         struct ast_framehook_interface interface = {
1053                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
1054                 .event_cb = hook_event_cb,
1055                 .destroy_cb = hook_destroy_cb,
1056         };
1057         int i = 0;
1058
1059         /* If disabled, strip any existing jitterbuffer and don't replace it. */
1060         if (!strcasecmp(jb_conf->impl, "disabled")) {
1061                 int *id;
1062                 ast_channel_lock(chan);
1063                 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1064                         id = datastore->data;
1065                         ast_framehook_detach(chan, *id);
1066                         ast_channel_datastore_remove(chan, datastore);
1067                         ast_datastore_free(datastore);
1068                 }
1069                 ast_channel_unlock(chan);
1070                 return;
1071         }
1072
1073         if (!(framedata = ast_calloc(1, sizeof(*framedata)))) {
1074                 return;
1075         }
1076
1077         if (jb_framedata_init(framedata, jb_conf)) {
1078                 jb_framedata_destroy(framedata);
1079                 return;
1080         }
1081
1082         interface.data = framedata;
1083
1084         ast_channel_lock(chan);
1085         i = ast_framehook_attach(chan, &interface);
1086         if (i >= 0) {
1087                 int *id;
1088                 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1089                         /* There is already a jitterbuffer on the channel. */
1090                         if (prefer_existing) {
1091                                 /* We prefer the existing jitterbuffer, so remove the new one and keep the old one. */
1092                                 ast_framehook_detach(chan, i);
1093                                 ast_channel_unlock(chan);
1094                                 return;
1095                         }
1096                         /* We prefer the new jitterbuffer, so strip the old one. */
1097                         id = datastore->data;
1098                         ast_framehook_detach(chan, *id);
1099                         ast_channel_datastore_remove(chan, datastore);
1100                         ast_datastore_free(datastore);
1101                 }
1102
1103                 if (!(datastore = ast_datastore_alloc(&jb_datastore, NULL))) {
1104                         ast_framehook_detach(chan, i);
1105                         ast_channel_unlock(chan);
1106                         return;
1107                 }
1108
1109                 if (!(id = ast_calloc(1, sizeof(int)))) {
1110                         ast_datastore_free(datastore);
1111                         ast_framehook_detach(chan, i);
1112                         ast_channel_unlock(chan);
1113                         return;
1114                 }
1115
1116                 *id = i; /* Store off the id. The channel is still locked so it is safe to access this ptr. */
1117                 datastore->data = id;
1118                 ast_channel_datastore_add(chan, datastore);
1119
1120                 ast_channel_set_fd(chan, AST_JITTERBUFFER_FD, framedata->timer_fd);
1121         } else {
1122                 jb_framedata_destroy(framedata);
1123                 framedata = NULL;
1124         }
1125         ast_channel_unlock(chan);
1126 }