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