loader: Fix comments in struct ast_module.
[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                 RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(chan), ast_channel_cleanup);
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
484         ast_verb(3, "%s jitterbuffer created on channel %s\n", jbimpl->name, ast_channel_name(chan));
485
486         /* Free the frame if it has not been queued in the jb */
487         if (res != AST_JB_IMPL_OK) {
488                 ast_frfree(frr);
489         }
490
491         return 0;
492 }
493
494
495 void ast_jb_destroy(struct ast_channel *chan)
496 {
497         struct ast_jb *jb = ast_channel_jb(chan);
498         const struct ast_jb_impl *jbimpl = jb->impl;
499         void *jbobj = jb->jbobj;
500         struct ast_frame *f;
501
502         if (jb->logfile) {
503                 fclose(jb->logfile);
504                 jb->logfile = NULL;
505         }
506
507         ao2_cleanup(jb->last_format);
508
509         if (ast_test_flag(jb, JB_CREATED)) {
510                 /* Remove and free all frames still queued in jb */
511                 while (jbimpl->remove(jbobj, &f) == AST_JB_IMPL_OK) {
512                         ast_frfree(f);
513                 }
514
515                 jbimpl->destroy(jbobj);
516                 jb->jbobj = NULL;
517
518                 ast_clear_flag(jb, JB_CREATED);
519
520                 ast_verb(3, "%s jitterbuffer destroyed on channel %s\n", jbimpl->name, ast_channel_name(chan));
521         }
522 }
523
524
525 static long get_now(struct ast_jb *jb, struct timeval *when)
526 {
527         struct timeval now;
528
529         if (!when) {
530                 when = &now;
531                 gettimeofday(when, NULL);
532         }
533
534         return ast_tvdiff_ms(*when, jb->timebase);
535 }
536
537
538 int ast_jb_read_conf(struct ast_jb_conf *conf, const char *varname, const char *value)
539 {
540         int prefixlen = sizeof(AST_JB_CONF_PREFIX) - 1;
541         const char *name;
542         int tmp;
543
544         if (strncasecmp(AST_JB_CONF_PREFIX, varname, prefixlen)) {
545                 return -1;
546         }
547
548         name = varname + prefixlen;
549
550         if (!strcasecmp(name, AST_JB_CONF_ENABLE)) {
551                 ast_set2_flag(conf, ast_true(value), AST_JB_ENABLED);
552         } else if (!strcasecmp(name, AST_JB_CONF_FORCE)) {
553                 ast_set2_flag(conf, ast_true(value), AST_JB_FORCED);
554         } else if (!strcasecmp(name, AST_JB_CONF_MAX_SIZE)) {
555                 if ((tmp = atoi(value)) > 0)
556                         conf->max_size = tmp;
557         } else if (!strcasecmp(name, AST_JB_CONF_RESYNCH_THRESHOLD)) {
558                 if ((tmp = atoi(value)) > 0)
559                         conf->resync_threshold = tmp;
560         } else if (!strcasecmp(name, AST_JB_CONF_IMPL)) {
561                 if (!ast_strlen_zero(value))
562                         snprintf(conf->impl, sizeof(conf->impl), "%s", value);
563         } else if (!strcasecmp(name, AST_JB_CONF_TARGET_EXTRA)) {
564                 if (sscanf(value, "%30d", &tmp) == 1) {
565                         conf->target_extra = tmp;
566                 }
567         } else if (!strcasecmp(name, AST_JB_CONF_LOG)) {
568                 ast_set2_flag(conf, ast_true(value), AST_JB_LOG);
569         } else {
570                 return -1;
571         }
572
573         return 0;
574 }
575
576 void ast_jb_enable_for_channel(struct ast_channel *chan)
577 {
578         struct ast_jb_conf conf = ast_channel_jb(chan)->conf;
579         if (ast_test_flag(&conf, AST_JB_ENABLED)) {
580                 ast_jb_create_framehook(chan, &conf, 1);
581         }
582 }
583
584 void ast_jb_configure(struct ast_channel *chan, const struct ast_jb_conf *conf)
585 {
586         memcpy(&ast_channel_jb(chan)->conf, conf, sizeof(*conf));
587 }
588
589
590 void ast_jb_get_config(const struct ast_channel *chan, struct ast_jb_conf *conf)
591 {
592         memcpy(conf, &ast_channel_jb((struct ast_channel *) chan)->conf, sizeof(*conf));
593 }
594
595 void ast_jb_empty_and_reset(struct ast_channel *c0, struct ast_channel *c1)
596 {
597         struct ast_jb *jb0 = ast_channel_jb(c0);
598         struct ast_jb *jb1 = ast_channel_jb(c1);
599         int c0_use_jb = ast_test_flag(jb0, JB_USE);
600         int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
601         int c1_use_jb = ast_test_flag(jb1, JB_USE);
602         int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
603
604         if (c0_use_jb && c0_jb_is_created && jb0->impl->empty_and_reset) {
605                 jb0->impl->empty_and_reset(jb0->jbobj);
606         }
607
608         if (c1_use_jb && c1_jb_is_created && jb1->impl->empty_and_reset) {
609                 jb1->impl->empty_and_reset(jb1->jbobj);
610         }
611 }
612
613 /* Implementation functions */
614
615 /* fixed */
616 static void * jb_create_fixed(struct ast_jb_conf *general_config)
617 {
618         struct fixed_jb_conf conf;
619
620         conf.jbsize = general_config->max_size;
621         conf.resync_threshold = general_config->resync_threshold;
622
623         return fixed_jb_new(&conf);
624 }
625
626 static void jb_destroy_fixed(void *jb)
627 {
628         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
629
630         /* Ensure the fixed jb is empty - otherwise it will raise an ASSERT */
631         jb_empty_and_reset_fixed(jb);
632
633         /* destroy the jb */
634         fixed_jb_destroy(fixedjb);
635 }
636
637
638 static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now)
639 {
640         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
641         int res;
642
643         res = fixed_jb_put_first(fixedjb, fin, fin->len, fin->ts, now);
644
645         return fixed_to_abstract_code[res];
646 }
647
648
649 static int jb_put_fixed(void *jb, struct ast_frame *fin, long now)
650 {
651         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
652         int res;
653
654         res = fixed_jb_put(fixedjb, fin, fin->len, fin->ts, now);
655
656         return fixed_to_abstract_code[res];
657 }
658
659
660 static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl)
661 {
662         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
663         struct fixed_jb_frame frame = { .data = &ast_null_frame };
664         int res;
665
666         res = fixed_jb_get(fixedjb, &frame, now, interpl);
667         *fout = frame.data;
668
669         return fixed_to_abstract_code[res];
670 }
671
672
673 static long jb_next_fixed(void *jb)
674 {
675         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
676
677         return fixed_jb_next(fixedjb);
678 }
679
680
681 static int jb_remove_fixed(void *jb, struct ast_frame **fout)
682 {
683         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
684         struct fixed_jb_frame frame;
685         int res;
686
687         res = fixed_jb_remove(fixedjb, &frame);
688         *fout = frame.data;
689
690         return fixed_to_abstract_code[res];
691 }
692
693
694 static void jb_force_resynch_fixed(void *jb)
695 {
696         struct fixed_jb *fixedjb = (struct fixed_jb *) jb;
697
698         fixed_jb_set_force_resynch(fixedjb);
699 }
700
701 static void jb_empty_and_reset_fixed(void *jb)
702 {
703         struct fixed_jb *fixedjb = jb;
704         struct fixed_jb_frame f;
705
706         while (fixed_jb_remove(fixedjb, &f) == FIXED_JB_OK) {
707                 ast_frfree(f.data);
708         }
709 }
710
711 static int jb_is_late_fixed(void *jb, long ts)
712 {
713         return fixed_jb_is_late(jb, ts);
714 }
715
716 /* adaptive */
717
718 static void *jb_create_adaptive(struct ast_jb_conf *general_config)
719 {
720         jb_conf jbconf;
721         jitterbuf *adaptivejb;
722
723         adaptivejb = jb_new();
724         if (adaptivejb) {
725                 jbconf.max_jitterbuf = general_config->max_size;
726                 jbconf.resync_threshold = general_config->resync_threshold;
727                 jbconf.max_contig_interp = 10;
728                 jbconf.target_extra = general_config->target_extra;
729                 jb_setconf(adaptivejb, &jbconf);
730         }
731
732         return adaptivejb;
733 }
734
735
736 static void jb_destroy_adaptive(void *jb)
737 {
738         jitterbuf *adaptivejb = (jitterbuf *) jb;
739
740         jb_destroy(adaptivejb);
741 }
742
743
744 static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now)
745 {
746         return jb_put_adaptive(jb, fin, now);
747 }
748
749
750 static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now)
751 {
752         jitterbuf *adaptivejb = (jitterbuf *) jb;
753         int res;
754
755         res = jb_put(adaptivejb, fin, JB_TYPE_VOICE, fin->len, fin->ts, now);
756
757         return adaptive_to_abstract_code[res];
758 }
759
760
761 static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl)
762 {
763         jitterbuf *adaptivejb = (jitterbuf *) jb;
764         jb_frame frame = { .data = &ast_null_frame };
765         int res;
766
767         res = jb_get(adaptivejb, &frame, now, interpl);
768         *fout = frame.data;
769
770         return adaptive_to_abstract_code[res];
771 }
772
773
774 static long jb_next_adaptive(void *jb)
775 {
776         jitterbuf *adaptivejb = (jitterbuf *) jb;
777
778         return jb_next(adaptivejb);
779 }
780
781
782 static int jb_remove_adaptive(void *jb, struct ast_frame **fout)
783 {
784         jitterbuf *adaptivejb = (jitterbuf *) jb;
785         jb_frame frame;
786         int res;
787
788         res = jb_getall(adaptivejb, &frame);
789         *fout = frame.data;
790
791         return adaptive_to_abstract_code[res];
792 }
793
794
795 static void jb_force_resynch_adaptive(void *jb)
796 {
797 }
798
799 static void jb_empty_and_reset_adaptive(void *jb)
800 {
801         jitterbuf *adaptivejb = jb;
802         jb_frame f;
803
804         while (jb_getall(adaptivejb, &f) == JB_OK) {
805                 ast_frfree(f.data);
806         }
807
808         jb_reset(adaptivejb);
809 }
810
811 const struct ast_jb_impl *ast_jb_get_impl(enum ast_jb_type type)
812 {
813         int i;
814         for (i = 0; i < ARRAY_LEN(avail_impl); i++) {
815                 if (avail_impl[i].type == type) {
816                         return &avail_impl[i];
817                 }
818         }
819         return NULL;
820 }
821
822 static int jb_is_late_adaptive(void *jb, long ts)
823 {
824         return jb_is_late(jb, ts);
825 }
826
827 #define DEFAULT_TIMER_INTERVAL 20
828 #define DEFAULT_SIZE  200
829 #define DEFAULT_TARGET_EXTRA  40
830 #define DEFAULT_RESYNC  1000
831 #define DEFAULT_TYPE AST_JB_FIXED
832
833 struct jb_framedata {
834         const struct ast_jb_impl *jb_impl;
835         struct ast_jb_conf jb_conf;
836         struct timeval start_tv;
837         struct ast_format *last_format;
838         struct ast_timer *timer;
839         int timer_interval; /* ms between deliveries */
840         int timer_fd;
841         int first;
842         void *jb_obj;
843 };
844
845 static void jb_framedata_destroy(struct jb_framedata *framedata)
846 {
847         if (framedata->timer) {
848                 ast_timer_close(framedata->timer);
849                 framedata->timer = NULL;
850         }
851         if (framedata->jb_impl && framedata->jb_obj) {
852                 struct ast_frame *f;
853                 while (framedata->jb_impl->remove(framedata->jb_obj, &f) == AST_JB_IMPL_OK) {
854                         ast_frfree(f);
855                 }
856                 framedata->jb_impl->destroy(framedata->jb_obj);
857                 framedata->jb_obj = NULL;
858         }
859         ao2_cleanup(framedata->last_format);
860         ast_free(framedata);
861 }
862
863 void ast_jb_conf_default(struct ast_jb_conf *conf)
864 {
865         conf->max_size = DEFAULT_SIZE;
866         conf->resync_threshold = DEFAULT_RESYNC;
867         ast_copy_string(conf->impl, "fixed", sizeof(conf->impl));
868         conf->target_extra = DEFAULT_TARGET_EXTRA;
869 }
870
871 static void datastore_destroy_cb(void *data) {
872         ast_free(data);
873         ast_debug(1, "JITTERBUFFER datastore destroyed\n");
874 }
875
876 static const struct ast_datastore_info jb_datastore = {
877         .type = "jitterbuffer",
878         .destroy = datastore_destroy_cb
879 };
880
881 static void hook_destroy_cb(void *framedata)
882 {
883         ast_debug(1, "JITTERBUFFER hook destroyed\n");
884         jb_framedata_destroy((struct jb_framedata *) framedata);
885 }
886
887 static struct ast_frame *hook_event_cb(struct ast_channel *chan, struct ast_frame *frame, enum ast_framehook_event event, void *data)
888 {
889         struct jb_framedata *framedata = data;
890         struct timeval now_tv;
891         unsigned long now;
892         int putframe = 0; /* signifies if audio frame was placed into the buffer or not */
893
894         switch (event) {
895         case AST_FRAMEHOOK_EVENT_READ:
896                 break;
897         case AST_FRAMEHOOK_EVENT_ATTACHED:
898         case AST_FRAMEHOOK_EVENT_DETACHED:
899         case AST_FRAMEHOOK_EVENT_WRITE:
900                 return frame;
901         }
902
903         if (ast_channel_fdno(chan) == AST_JITTERBUFFER_FD && framedata->timer) {
904                 if (ast_timer_ack(framedata->timer, 1) < 0) {
905                         ast_log(LOG_ERROR, "Failed to acknowledge timer in jitter buffer\n");
906                         return frame;
907                 }
908         }
909
910         /*
911          * If the frame has been requeued (for instance when the translate core returns
912          * more than one frame) then if the frame is late we want to immediately return
913          * it. Otherwise attempt to insert it into the jitterbuffer.
914          *
915          * If the frame is requeued and late then in all likely hood it's a frame that
916          * that was previously retrieved from the jitterbuffer, passed to the translate
917          * core, and then put back into the channel read queue. Even if it had not been
918          * in the jitterbuffer prior to now it needs to be the next frame "out".
919          *
920          * However late arriving frames that have not been requeued (i.e. regular frames)
921          * need to be passed to the jitterbuffer so they can be appropriately dropped. As
922          * well any requeued frames that are not late should be put into the jitterbuffer.
923          */
924         if (!frame || (ast_test_flag(frame, AST_FRFLAG_REQUEUED) &&
925                        framedata->jb_impl->is_late(framedata->jb_obj, frame->ts))) {
926                 return frame;
927         }
928
929         now_tv = ast_tvnow();
930         now = ast_tvdiff_ms(now_tv, framedata->start_tv);
931
932         if (frame->frametype == AST_FRAME_VOICE) {
933                 int res;
934                 struct ast_frame *jbframe;
935
936                 if (!ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO) || frame->len < 2 || frame->ts < 0) {
937                         /* only frames with timing info can enter the jitterbuffer */
938                         return frame;
939                 }
940
941                 jbframe = ast_frisolate(frame);
942                 ao2_replace(framedata->last_format, frame->subclass.format);
943
944                 if (frame->len && (frame->len != framedata->timer_interval)) {
945                         framedata->timer_interval = frame->len;
946                         ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
947                 }
948                 if (!framedata->first) {
949                         framedata->first = 1;
950                         res = framedata->jb_impl->put_first(framedata->jb_obj, jbframe, now);
951                 } else {
952                         res = framedata->jb_impl->put(framedata->jb_obj, jbframe, now);
953                 }
954
955                 if (res == AST_JB_IMPL_OK) {
956                         if (jbframe != frame) {
957                                 ast_frfree(frame);
958                         }
959                         frame = &ast_null_frame;
960                 } else if (jbframe != frame) {
961                         ast_frfree(jbframe);
962                 }
963                 putframe = 1;
964         }
965
966         if (frame->frametype == AST_FRAME_NULL) {
967                 int res;
968                 long next = framedata->jb_impl->next(framedata->jb_obj);
969
970                 /* If now is earlier than the next expected output frame
971                  * from the jitterbuffer we may choose to pass on retrieving
972                  * a frame during this read iteration.  The only exception
973                  * to this rule is when an audio frame is placed into the buffer
974                  * and the time for the next frame to come out of the buffer is
975                  * at least within the timer_interval of the next output frame. By
976                  * doing this we are able to feed off the timing of the input frames
977                  * and only rely on our jitterbuffer timer when frames are dropped.
978                  * During testing, this hybrid form of timing gave more reliable results. */
979                 if (now < next) {
980                         long int diff = next - now;
981                         if (!putframe) {
982                                 return frame;
983                         } else if (diff >= framedata->timer_interval) {
984                                 return frame;
985                         }
986                 }
987
988                 ast_frfree(frame);
989                 frame = &ast_null_frame;
990                 res = framedata->jb_impl->get(framedata->jb_obj, &frame, now, framedata->timer_interval);
991                 switch (res) {
992                 case AST_JB_IMPL_OK:
993                         /* got it, and pass it through */
994                         break;
995                 case AST_JB_IMPL_DROP:
996                         ast_frfree(frame);
997                         frame = &ast_null_frame;
998                         break;
999                 case AST_JB_IMPL_INTERP:
1000                         if (framedata->last_format) {
1001                                 struct ast_frame tmp = { 0, };
1002
1003                                 tmp.frametype = AST_FRAME_VOICE;
1004                                 tmp.subclass.format = framedata->last_format;
1005                                 /* example: 8000hz / (1000 / 20ms) = 160 samples */
1006                                 tmp.samples = ast_format_get_sample_rate(framedata->last_format) / (1000 / framedata->timer_interval);
1007                                 tmp.delivery = ast_tvadd(framedata->start_tv, ast_samp2tv(next, 1000));
1008                                 tmp.offset = AST_FRIENDLY_OFFSET;
1009                                 tmp.src  = "func_jitterbuffer interpolation";
1010                                 ast_frfree(frame);
1011                                 frame = ast_frdup(&tmp);
1012                                 break;
1013                         }
1014                         /* else fall through */
1015                 case AST_JB_IMPL_NOFRAME:
1016                         ast_frfree(frame);
1017                         frame = &ast_null_frame;
1018                         break;
1019                 }
1020         }
1021
1022         if (frame->frametype == AST_FRAME_CONTROL) {
1023                 switch(frame->subclass.integer) {
1024                 case AST_CONTROL_HOLD:
1025                 case AST_CONTROL_UNHOLD:
1026                 case AST_CONTROL_T38_PARAMETERS:
1027                 case AST_CONTROL_SRCUPDATE:
1028                 case AST_CONTROL_SRCCHANGE:
1029                         framedata->jb_impl->force_resync(framedata->jb_obj);
1030                         break;
1031                 default:
1032                         break;
1033                 }
1034         }
1035
1036         return frame;
1037 }
1038
1039 /* set defaults */
1040 static int jb_framedata_init(struct jb_framedata *framedata, struct ast_jb_conf *jb_conf)
1041 {
1042         int jb_impl_type = DEFAULT_TYPE;
1043         /* Initialize defaults */
1044         framedata->timer_fd = -1;
1045         memcpy(&framedata->jb_conf, jb_conf, sizeof(*jb_conf));
1046
1047         /* Figure out implementation type from the configuration implementation string */
1048         if (!ast_strlen_zero(jb_conf->impl)) {
1049                 if (!strcasecmp(jb_conf->impl, "fixed")) {
1050                         jb_impl_type = AST_JB_FIXED;
1051                 } else if (!strcasecmp(jb_conf->impl, "adaptive")) {
1052                         jb_impl_type = AST_JB_ADAPTIVE;
1053                 } else {
1054                         ast_log(LOG_WARNING, "Unknown Jitterbuffer type %s. Failed to create jitterbuffer.\n", jb_conf->impl);
1055                         return -1;
1056                 }
1057         }
1058
1059         if (!(framedata->jb_impl = ast_jb_get_impl(jb_impl_type))) {
1060                 return -1;
1061         }
1062
1063         if (!(framedata->timer = ast_timer_open())) {
1064                 return -1;
1065         }
1066
1067         framedata->timer_fd = ast_timer_fd(framedata->timer);
1068         framedata->timer_interval = DEFAULT_TIMER_INTERVAL;
1069         ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
1070         framedata->start_tv = ast_tvnow();
1071
1072         framedata->jb_obj = framedata->jb_impl->create(&framedata->jb_conf);
1073         return 0;
1074 }
1075
1076
1077 void ast_jb_create_framehook(struct ast_channel *chan, struct ast_jb_conf *jb_conf, int prefer_existing)
1078 {
1079         struct jb_framedata *framedata;
1080         struct ast_datastore *datastore = NULL;
1081         struct ast_framehook_interface interface = {
1082                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
1083                 .event_cb = hook_event_cb,
1084                 .destroy_cb = hook_destroy_cb,
1085         };
1086         int i = 0;
1087
1088         /* If disabled, strip any existing jitterbuffer and don't replace it. */
1089         if (!strcasecmp(jb_conf->impl, "disabled")) {
1090                 int *id;
1091                 ast_channel_lock(chan);
1092                 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1093                         id = datastore->data;
1094                         ast_framehook_detach(chan, *id);
1095                         ast_channel_datastore_remove(chan, datastore);
1096                         ast_datastore_free(datastore);
1097                 }
1098                 ast_channel_unlock(chan);
1099                 return;
1100         }
1101
1102         if (!(framedata = ast_calloc(1, sizeof(*framedata)))) {
1103                 return;
1104         }
1105
1106         if (jb_framedata_init(framedata, jb_conf)) {
1107                 jb_framedata_destroy(framedata);
1108                 return;
1109         }
1110
1111         interface.data = framedata;
1112
1113         ast_channel_lock(chan);
1114         i = ast_framehook_attach(chan, &interface);
1115         if (i >= 0) {
1116                 int *id;
1117                 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1118                         /* There is already a jitterbuffer on the channel. */
1119                         if (prefer_existing) {
1120                                 /* We prefer the existing jitterbuffer, so remove the new one and keep the old one. */
1121                                 ast_framehook_detach(chan, i);
1122                                 ast_channel_unlock(chan);
1123                                 return;
1124                         }
1125                         /* We prefer the new jitterbuffer, so strip the old one. */
1126                         id = datastore->data;
1127                         ast_framehook_detach(chan, *id);
1128                         ast_channel_datastore_remove(chan, datastore);
1129                         ast_datastore_free(datastore);
1130                 }
1131
1132                 if (!(datastore = ast_datastore_alloc(&jb_datastore, NULL))) {
1133                         ast_framehook_detach(chan, i);
1134                         ast_channel_unlock(chan);
1135                         return;
1136                 }
1137
1138                 if (!(id = ast_calloc(1, sizeof(int)))) {
1139                         ast_datastore_free(datastore);
1140                         ast_framehook_detach(chan, i);
1141                         ast_channel_unlock(chan);
1142                         return;
1143                 }
1144
1145                 *id = i; /* Store off the id. The channel is still locked so it is safe to access this ptr. */
1146                 datastore->data = id;
1147                 ast_channel_datastore_add(chan, datastore);
1148
1149                 ast_channel_set_fd(chan, AST_JITTERBUFFER_FD, framedata->timer_fd);
1150         } else {
1151                 jb_framedata_destroy(framedata);
1152                 framedata = NULL;
1153         }
1154         ast_channel_unlock(chan);
1155 }