Allow Asterisk to compile under GCC 4.10
[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 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
40 #include "asterisk/frame.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/term.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/timing.h"
46
47 #include "asterisk/abstract_jb.h"
48 #include "fixedjitterbuf.h"
49 #include "jitterbuf.h"
50
51 /*! Internal jb flags */
52 enum {
53         JB_USE =                  (1 << 0),
54         JB_TIMEBASE_INITIALIZED = (1 << 1),
55         JB_CREATED =              (1 << 2)
56 };
57
58
59 /* Implementation functions */
60 /* fixed */
61 static void *jb_create_fixed(struct ast_jb_conf *general_config);
62 static void jb_destroy_fixed(void *jb);
63 static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now);
64 static int jb_put_fixed(void *jb, struct ast_frame *fin, long now);
65 static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl);
66 static long jb_next_fixed(void *jb);
67 static int jb_remove_fixed(void *jb, struct ast_frame **fout);
68 static void jb_force_resynch_fixed(void *jb);
69 static void jb_empty_and_reset_fixed(void *jb);
70 /* adaptive */
71 static void * jb_create_adaptive(struct ast_jb_conf *general_config);
72 static void jb_destroy_adaptive(void *jb);
73 static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now);
74 static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now);
75 static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl);
76 static long jb_next_adaptive(void *jb);
77 static int jb_remove_adaptive(void *jb, struct ast_frame **fout);
78 static void jb_force_resynch_adaptive(void *jb);
79 static void jb_empty_and_reset_adaptive(void *jb);
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         },
96         {
97                 .name = "adaptive",
98                 .type = AST_JB_ADAPTIVE,
99                 .create = jb_create_adaptive,
100                 .destroy = jb_destroy_adaptive,
101                 .put_first = jb_put_first_adaptive,
102                 .put = jb_put_adaptive,
103                 .get = jb_get_adaptive,
104                 .next = jb_next_adaptive,
105                 .remove = jb_remove_adaptive,
106                 .force_resync = jb_force_resynch_adaptive,
107                 .empty_and_reset = jb_empty_and_reset_adaptive,
108         }
109 };
110
111 static int default_impl = 0;
112
113 /* Translations between impl and abstract return codes */
114 static const int fixed_to_abstract_code[] =
115         {AST_JB_IMPL_OK, AST_JB_IMPL_DROP, AST_JB_IMPL_INTERP, AST_JB_IMPL_NOFRAME};
116 static const int adaptive_to_abstract_code[] =
117         {AST_JB_IMPL_OK, AST_JB_IMPL_NOFRAME, AST_JB_IMPL_NOFRAME, AST_JB_IMPL_INTERP, AST_JB_IMPL_DROP, AST_JB_IMPL_OK};
118
119 /* JB_GET actions (used only for the frames log) */
120 static const char * const jb_get_actions[] = {"Delivered", "Dropped", "Interpolated", "No"};
121
122 /*! \brief Macros for the frame log files */
123 #define jb_framelog(...) do { \
124         if (jb->logfile) { \
125                 fprintf(jb->logfile, __VA_ARGS__); \
126                 fflush(jb->logfile); \
127         } \
128 } while (0)
129
130
131 /* Internal utility functions */
132 static void jb_choose_impl(struct ast_channel *chan);
133 static void jb_get_and_deliver(struct ast_channel *chan);
134 static int create_jb(struct ast_channel *chan, struct ast_frame *first_frame);
135 static long get_now(struct ast_jb *jb, struct timeval *tv);
136
137
138 /* Interface ast jb functions impl */
139
140
141 static void jb_choose_impl(struct ast_channel *chan)
142 {
143         struct ast_jb *jb = ast_channel_jb(chan);
144         struct ast_jb_conf *jbconf = &jb->conf;
145         const struct ast_jb_impl *test_impl;
146         int i, avail_impl_count = ARRAY_LEN(avail_impl);
147
148         jb->impl = &avail_impl[default_impl];
149
150         if (ast_strlen_zero(jbconf->impl)) {
151                 return;
152         }
153
154         for (i = 0; i < avail_impl_count; i++) {
155                 test_impl = &avail_impl[i];
156                 if (!strcasecmp(jbconf->impl, test_impl->name)) {
157                         jb->impl = test_impl;
158                         return;
159                 }
160         }
161 }
162
163 int ast_jb_do_usecheck(struct ast_channel *c0, struct ast_channel *c1)
164 {
165         struct ast_jb *jb0 = ast_channel_jb(c0);
166         struct ast_jb *jb1 = ast_channel_jb(c1);
167         struct ast_jb_conf *conf0 = &jb0->conf;
168         struct ast_jb_conf *conf1 = &jb1->conf;
169         int c0_wants_jitter = ast_channel_tech(c0)->properties & AST_CHAN_TP_WANTSJITTER;
170         int c0_creates_jitter = ast_channel_tech(c0)->properties & AST_CHAN_TP_CREATESJITTER;
171         int c0_jb_enabled = ast_test_flag(conf0, AST_JB_ENABLED);
172         int c0_force_jb = ast_test_flag(conf0, AST_JB_FORCED);
173         int c0_jb_timebase_initialized = ast_test_flag(jb0, JB_TIMEBASE_INITIALIZED);
174         int c0_jb_created = ast_test_flag(jb0, JB_CREATED);
175         int c1_wants_jitter = ast_channel_tech(c1)->properties & AST_CHAN_TP_WANTSJITTER;
176         int c1_creates_jitter = ast_channel_tech(c1)->properties & AST_CHAN_TP_CREATESJITTER;
177         int c1_jb_enabled = ast_test_flag(conf1, AST_JB_ENABLED);
178         int c1_force_jb = ast_test_flag(conf1, AST_JB_FORCED);
179         int c1_jb_timebase_initialized = ast_test_flag(jb1, JB_TIMEBASE_INITIALIZED);
180         int c1_jb_created = ast_test_flag(jb1, JB_CREATED);
181         int inuse = 0;
182
183         /* Determine whether audio going to c0 needs a jitter buffer */
184         if (((!c0_wants_jitter && c1_creates_jitter) || (c0_force_jb && c1_creates_jitter)) && c0_jb_enabled) {
185                 ast_set_flag(jb0, JB_USE);
186                 if (!c0_jb_timebase_initialized) {
187                         if (c1_jb_timebase_initialized) {
188                                 memcpy(&jb0->timebase, &jb1->timebase, sizeof(struct timeval));
189                         } else {
190                                 gettimeofday(&jb0->timebase, NULL);
191                         }
192                         ast_set_flag(jb0, JB_TIMEBASE_INITIALIZED);
193                 }
194
195                 if (!c0_jb_created) {
196                         jb_choose_impl(c0);
197                 }
198
199                 inuse = 1;
200         }
201
202         /* Determine whether audio going to c1 needs a jitter buffer */
203         if (((!c1_wants_jitter && c0_creates_jitter) || (c1_force_jb && c0_creates_jitter)) && c1_jb_enabled) {
204                 ast_set_flag(jb1, JB_USE);
205                 if (!c1_jb_timebase_initialized) {
206                         if (c0_jb_timebase_initialized) {
207                                 memcpy(&jb1->timebase, &jb0->timebase, sizeof(struct timeval));
208                         } else {
209                                 gettimeofday(&jb1->timebase, NULL);
210                         }
211                         ast_set_flag(jb1, JB_TIMEBASE_INITIALIZED);
212                 }
213
214                 if (!c1_jb_created) {
215                         jb_choose_impl(c1);
216                 }
217
218                 inuse = 1;
219         }
220
221         return inuse;
222 }
223
224 int ast_jb_get_when_to_wakeup(struct ast_channel *c0, struct ast_channel *c1, int time_left)
225 {
226         struct ast_jb *jb0 = ast_channel_jb(c0);
227         struct ast_jb *jb1 = ast_channel_jb(c1);
228         int c0_use_jb = ast_test_flag(jb0, JB_USE);
229         int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
230         int c1_use_jb = ast_test_flag(jb1, JB_USE);
231         int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
232         int wait, wait0, wait1;
233         struct timeval tv_now;
234
235         if (time_left == 0) {
236                 /* No time left - the bridge will be retried */
237                 /* TODO: Test disable this */
238                 /*return 0;*/
239         }
240
241         if (time_left < 0) {
242                 time_left = INT_MAX;
243         }
244
245         gettimeofday(&tv_now, NULL);
246
247         wait0 = (c0_use_jb && c0_jb_is_created) ? jb0->next - get_now(jb0, &tv_now) : time_left;
248         wait1 = (c1_use_jb && c1_jb_is_created) ? jb1->next - get_now(jb1, &tv_now) : time_left;
249
250         wait = wait0 < wait1 ? wait0 : wait1;
251         wait = wait < time_left ? wait : time_left;
252
253         if (wait == INT_MAX) {
254                 wait = -1;
255         } else if (wait < 1) {
256                 /* don't let wait=0, because this can cause the pbx thread to loop without any sleeping at all */
257                 wait = 1;
258         }
259
260         return wait;
261 }
262
263
264 int ast_jb_put(struct ast_channel *chan, struct ast_frame *f)
265 {
266         struct ast_jb *jb = ast_channel_jb(chan);
267         const struct ast_jb_impl *jbimpl = jb->impl;
268         void *jbobj = jb->jbobj;
269         struct ast_frame *frr;
270         long now = 0;
271
272         if (!ast_test_flag(jb, JB_USE))
273                 return -1;
274
275         if (f->frametype != AST_FRAME_VOICE) {
276                 if (f->frametype == AST_FRAME_DTMF && ast_test_flag(jb, JB_CREATED)) {
277                         jb_framelog("JB_PUT {now=%ld}: Received DTMF frame. Force resynching jb...\n", now);
278                         jbimpl->force_resync(jbobj);
279                 }
280
281                 return -1;
282         }
283
284         /* We consider an enabled jitterbuffer should receive frames with valid timing info. */
285         if (!ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO) || f->len < 2 || f->ts < 0) {
286                 ast_log(LOG_WARNING, "%s received frame with invalid timing info: "
287                         "has_timing_info=%u, len=%ld, ts=%ld, src=%s\n",
288                         ast_channel_name(chan), ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO), f->len, f->ts, f->src);
289                 return -1;
290         }
291
292         frr = ast_frdup(f);
293
294         if (!frr) {
295                 ast_log(LOG_ERROR, "Failed to isolate frame for the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
296                 return -1;
297         }
298
299         if (!ast_test_flag(jb, JB_CREATED)) {
300                 if (create_jb(chan, frr)) {
301                         ast_frfree(frr);
302                         /* Disable the jitterbuffer */
303                         ast_clear_flag(jb, JB_USE);
304                         return -1;
305                 }
306
307                 ast_set_flag(jb, JB_CREATED);
308                 return 0;
309         } else {
310                 now = get_now(jb, NULL);
311                 if (jbimpl->put(jbobj, frr, now) != AST_JB_IMPL_OK) {
312                         jb_framelog("JB_PUT {now=%ld}: Dropped frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
313                         ast_frfree(frr);
314                         /*return -1;*/
315                         /* TODO: Check this fix - should return 0 here, because the dropped frame shouldn't
316                            be delivered at all */
317                         return 0;
318                 }
319
320                 jb->next = jbimpl->next(jbobj);
321
322                 jb_framelog("JB_PUT {now=%ld}: Queued frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len);
323
324                 return 0;
325         }
326 }
327
328
329 void ast_jb_get_and_deliver(struct ast_channel *c0, struct ast_channel *c1)
330 {
331         struct ast_jb *jb0 = ast_channel_jb(c0);
332         struct ast_jb *jb1 = ast_channel_jb(c1);
333         int c0_use_jb = ast_test_flag(jb0, JB_USE);
334         int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED);
335         int c1_use_jb = ast_test_flag(jb1, JB_USE);
336         int c1_jb_is_created = ast_test_flag(jb1, JB_CREATED);
337
338         if (c0_use_jb && c0_jb_is_created)
339                 jb_get_and_deliver(c0);
340
341         if (c1_use_jb && c1_jb_is_created)
342                 jb_get_and_deliver(c1);
343 }
344
345
346 static void jb_get_and_deliver(struct ast_channel *chan)
347 {
348         struct ast_jb *jb = ast_channel_jb(chan);
349         const struct ast_jb_impl *jbimpl = jb->impl;
350         void *jbobj = jb->jbobj;
351         struct ast_frame *f, finterp = { .frametype = AST_FRAME_VOICE, };
352         long now;
353         int interpolation_len, res;
354
355         now = get_now(jb, NULL);
356         jb->next = jbimpl->next(jbobj);
357         if (now < jb->next) {
358                 jb_framelog("\tJB_GET {now=%ld}: now < next=%ld\n", now, jb->next);
359                 return;
360         }
361
362         while (now >= jb->next) {
363                 interpolation_len = ast_codec_interp_len(&jb->last_format);
364
365                 res = jbimpl->get(jbobj, &f, now, interpolation_len);
366
367                 switch (res) {
368                 case AST_JB_IMPL_OK:
369                         /* deliver the frame */
370                         ast_write(chan, f);
371                 case AST_JB_IMPL_DROP:
372                         jb_framelog("\tJB_GET {now=%ld}: %s frame with ts=%ld and len=%ld\n",
373                                 now, jb_get_actions[res], f->ts, f->len);
374                         ast_format_copy(&jb->last_format, &f->subclass.format);
375                         ast_frfree(f);
376                         break;
377                 case AST_JB_IMPL_INTERP:
378                         /* interpolate a frame */
379                         f = &finterp;
380                         ast_format_copy(&f->subclass.format, &jb->last_format);
381                         f->samples  = interpolation_len * 8;
382                         f->src  = "JB interpolation";
383                         f->delivery = ast_tvadd(jb->timebase, ast_samp2tv(jb->next, 1000));
384                         f->offset = AST_FRIENDLY_OFFSET;
385                         /* deliver the interpolated frame */
386                         ast_write(chan, f);
387                         jb_framelog("\tJB_GET {now=%ld}: Interpolated frame with len=%d\n", now, interpolation_len);
388                         break;
389                 case AST_JB_IMPL_NOFRAME:
390                         ast_log(LOG_WARNING,
391                                 "AST_JB_IMPL_NOFRAME is returned from the %s jb when now=%ld >= next=%ld, jbnext=%ld!\n",
392                                 jbimpl->name, now, jb->next, jbimpl->next(jbobj));
393                         jb_framelog("\tJB_GET {now=%ld}: No frame for now!?\n", now);
394                         return;
395                 default:
396                         ast_log(LOG_ERROR, "This should never happen!\n");
397                         ast_assert("JB type unknown" == NULL);
398                         break;
399                 }
400
401                 jb->next = jbimpl->next(jbobj);
402         }
403 }
404
405
406 static int create_jb(struct ast_channel *chan, struct ast_frame *frr)
407 {
408         struct ast_jb *jb = ast_channel_jb(chan);
409         struct ast_jb_conf *jbconf = &jb->conf;
410         const struct ast_jb_impl *jbimpl = jb->impl;
411         void *jbobj;
412         long now;
413         char logfile_pathname[20 + AST_JB_IMPL_NAME_SIZE + 2*AST_CHANNEL_NAME + 1];
414         char name1[AST_CHANNEL_NAME], name2[AST_CHANNEL_NAME], *tmp;
415         int res;
416
417         jbobj = jb->jbobj = jbimpl->create(jbconf);
418         if (!jbobj) {
419                 ast_log(LOG_WARNING, "Failed to create jitterbuffer on channel '%s'\n", ast_channel_name(chan));
420                 return -1;
421         }
422
423         now = get_now(jb, NULL);
424         res = jbimpl->put_first(jbobj, frr, now);
425
426         /* The result of putting the first frame should not differ from OK. However, its possible
427            some implementations (i.e. adaptive's when resynch_threshold is specified) to drop it. */
428         if (res != AST_JB_IMPL_OK) {
429                 ast_log(LOG_WARNING, "Failed to put first frame in the jitterbuffer on channel '%s'\n", ast_channel_name(chan));
430                 /*
431                 jbimpl->destroy(jbobj);
432                 return -1;
433                 */
434         }
435
436         /* Init next */
437         jb->next = jbimpl->next(jbobj);
438
439         /* Init last format for a first time. */
440         ast_format_copy(&jb->last_format, &frr->subclass.format);
441
442         /* Create a frame log file */
443         if (ast_test_flag(jbconf, AST_JB_LOG)) {
444                 RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(chan), ast_channel_cleanup);
445                 char safe_logfile[30] = "/tmp/logfile-XXXXXX";
446                 int safe_fd;
447
448                 snprintf(name2, sizeof(name2), "%s", ast_channel_name(chan));
449                 while ((tmp = strchr(name2, '/'))) {
450                         *tmp = '#';
451                 }
452
453                 /* We should always have bridged chan if a jitterbuffer is in use */
454                 ast_assert(bridged != NULL);
455
456                 snprintf(name1, sizeof(name1), "%s", ast_channel_name(bridged));
457                 while ((tmp = strchr(name1, '/'))) {
458                         *tmp = '#';
459                 }
460
461                 snprintf(logfile_pathname, sizeof(logfile_pathname),
462                         "/tmp/ast_%s_jb_%s--%s.log", jbimpl->name, name1, name2);
463                 unlink(logfile_pathname);
464                 safe_fd = mkstemp(safe_logfile);
465                 if (safe_fd < 0 || link(safe_logfile, logfile_pathname) || unlink(safe_logfile) || !(jb->logfile = fdopen(safe_fd, "w+b"))) {
466                         ast_log(LOG_ERROR, "Failed to create frame log file with pathname '%s': %s\n", logfile_pathname, strerror(errno));
467                         jb->logfile = NULL;
468                         if (safe_fd > -1) {
469                                 close(safe_fd);
470                         }
471                 }
472
473                 if (res == AST_JB_IMPL_OK) {
474                         jb_framelog("JB_PUT_FIRST {now=%ld}: Queued frame with ts=%ld and len=%ld\n",
475                                 now, frr->ts, frr->len);
476                 } else {
477                         jb_framelog("JB_PUT_FIRST {now=%ld}: Dropped frame with ts=%ld and len=%ld\n",
478                                 now, frr->ts, frr->len);
479                 }
480         }
481
482         ast_verb(3, "%s jitterbuffer created on channel %s\n", jbimpl->name, ast_channel_name(chan));
483
484         /* Free the frame if it has not been queued in the jb */
485         if (res != AST_JB_IMPL_OK) {
486                 ast_frfree(frr);
487         }
488
489         return 0;
490 }
491
492
493 void ast_jb_destroy(struct ast_channel *chan)
494 {
495         struct ast_jb *jb = ast_channel_jb(chan);
496         const struct ast_jb_impl *jbimpl = jb->impl;
497         void *jbobj = jb->jbobj;
498         struct ast_frame *f;
499
500         if (jb->logfile) {
501                 fclose(jb->logfile);
502                 jb->logfile = NULL;
503         }
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;
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;
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         ast_free(framedata);
846 }
847
848 void ast_jb_conf_default(struct ast_jb_conf *conf)
849 {
850         conf->max_size = DEFAULT_SIZE;
851         conf->resync_threshold = DEFAULT_RESYNC;
852         ast_copy_string(conf->impl, "fixed", sizeof(conf->impl));
853         conf->target_extra = DEFAULT_TARGET_EXTRA;
854 }
855
856 static void datastore_destroy_cb(void *data) {
857         ast_free(data);
858         ast_debug(1, "JITTERBUFFER datastore destroyed\n");
859 }
860
861 static const struct ast_datastore_info jb_datastore = {
862         .type = "jitterbuffer",
863         .destroy = datastore_destroy_cb
864 };
865
866 static void hook_destroy_cb(void *framedata)
867 {
868         ast_debug(1, "JITTERBUFFER hook destroyed\n");
869         jb_framedata_destroy((struct jb_framedata *) framedata);
870 }
871
872 static struct ast_frame *hook_event_cb(struct ast_channel *chan, struct ast_frame *frame, enum ast_framehook_event event, void *data)
873 {
874         struct jb_framedata *framedata = data;
875         struct timeval now_tv;
876         unsigned long now;
877         int putframe = 0; /* signifies if audio frame was placed into the buffer or not */
878
879         switch (event) {
880         case AST_FRAMEHOOK_EVENT_READ:
881                 break;
882         case AST_FRAMEHOOK_EVENT_ATTACHED:
883         case AST_FRAMEHOOK_EVENT_DETACHED:
884         case AST_FRAMEHOOK_EVENT_WRITE:
885                 return frame;
886         }
887
888         if (ast_channel_fdno(chan) == AST_JITTERBUFFER_FD && framedata->timer) {
889                 if (ast_timer_ack(framedata->timer, 1) < 0) {
890                         ast_log(LOG_ERROR, "Failed to acknowledge timer in jitter buffer\n");
891                         return frame;
892                 }
893         }
894
895         if (!frame) {
896                 return frame;
897         }
898
899         now_tv = ast_tvnow();
900         now = ast_tvdiff_ms(now_tv, framedata->start_tv);
901
902         if (frame->frametype == AST_FRAME_VOICE) {
903                 int res;
904                 struct ast_frame *jbframe;
905
906                 if (!ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO) || frame->len < 2 || frame->ts < 0) {
907                         /* only frames with timing info can enter the jitterbuffer */
908                         return frame;
909                 }
910
911                 jbframe = ast_frisolate(frame);
912                 ast_format_copy(&framedata->last_format, &frame->subclass.format);
913
914                 if (frame->len && (frame->len != framedata->timer_interval)) {
915                         framedata->timer_interval = frame->len;
916                         ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
917                 }
918                 if (!framedata->first) {
919                         framedata->first = 1;
920                         res = framedata->jb_impl->put_first(framedata->jb_obj, jbframe, now);
921                 } else {
922                         res = framedata->jb_impl->put(framedata->jb_obj, jbframe, now);
923                 }
924                 if (res == AST_JB_IMPL_OK) {
925                         frame = &ast_null_frame;
926                 }
927                 putframe = 1;
928         }
929
930         if (frame->frametype == AST_FRAME_NULL) {
931                 int res;
932                 long next = framedata->jb_impl->next(framedata->jb_obj);
933
934                 /* If now is earlier than the next expected output frame
935                  * from the jitterbuffer we may choose to pass on retrieving
936                  * a frame during this read iteration.  The only exception
937                  * to this rule is when an audio frame is placed into the buffer
938                  * and the time for the next frame to come out of the buffer is
939                  * at least within the timer_interval of the next output frame. By
940                  * doing this we are able to feed off the timing of the input frames
941                  * and only rely on our jitterbuffer timer when frames are dropped.
942                  * During testing, this hybrid form of timing gave more reliable results. */
943                 if (now < next) {
944                         long int diff = next - now;
945                         if (!putframe) {
946                                 return frame;
947                         } else if (diff >= framedata->timer_interval) {
948                                 return frame;
949                         }
950                 }
951
952                 res = framedata->jb_impl->get(framedata->jb_obj, &frame, now, framedata->timer_interval);
953                 switch (res) {
954                 case AST_JB_IMPL_OK:
955                         /* got it, and pass it through */
956                         break;
957                 case AST_JB_IMPL_DROP:
958                         ast_frfree(frame);
959                         frame = &ast_null_frame;
960                         break;
961                 case AST_JB_IMPL_INTERP:
962                         if (framedata->last_format.id) {
963                                 struct ast_frame tmp = { 0, };
964                                 tmp.frametype = AST_FRAME_VOICE;
965                                 ast_format_copy(&tmp.subclass.format, &framedata->last_format);
966                                 /* example: 8000hz / (1000 / 20ms) = 160 samples */
967                                 tmp.samples = ast_format_rate(&framedata->last_format) / (1000 / framedata->timer_interval);
968                                 tmp.delivery = ast_tvadd(framedata->start_tv, ast_samp2tv(next, 1000));
969                                 tmp.offset = AST_FRIENDLY_OFFSET;
970                                 tmp.src  = "func_jitterbuffer interpolation";
971                                 frame = ast_frdup(&tmp);
972                                 break;
973                         }
974                         /* else fall through */
975                 case AST_JB_IMPL_NOFRAME:
976                         frame = &ast_null_frame;
977                         break;
978                 }
979         }
980
981         if (frame->frametype == AST_FRAME_CONTROL) {
982                 switch(frame->subclass.integer) {
983                 case AST_CONTROL_HOLD:
984                 case AST_CONTROL_UNHOLD:
985                 case AST_CONTROL_T38_PARAMETERS:
986                 case AST_CONTROL_SRCUPDATE:
987                 case AST_CONTROL_SRCCHANGE:
988                         framedata->jb_impl->force_resync(framedata->jb_obj);
989                         break;
990                 default:
991                         break;
992                 }
993         }
994
995         return frame;
996 }
997
998 /* set defaults */
999 static int jb_framedata_init(struct jb_framedata *framedata, struct ast_jb_conf *jb_conf)
1000 {
1001         int jb_impl_type = DEFAULT_TYPE;
1002         /* Initialize defaults */
1003         framedata->timer_fd = -1;
1004         memcpy(&framedata->jb_conf, jb_conf, sizeof(*jb_conf));
1005
1006         /* Figure out implementation type from the configuration implementation string */
1007         if (!ast_strlen_zero(jb_conf->impl)) {
1008                 if (!strcasecmp(jb_conf->impl, "fixed")) {
1009                         jb_impl_type = AST_JB_FIXED;
1010                 } else if (!strcasecmp(jb_conf->impl, "adaptive")) {
1011                         jb_impl_type = AST_JB_ADAPTIVE;
1012                 } else {
1013                         ast_log(LOG_WARNING, "Unknown Jitterbuffer type %s. Failed to create jitterbuffer.\n", jb_conf->impl);
1014                         return -1;
1015                 }
1016         }
1017
1018         if (!(framedata->jb_impl = ast_jb_get_impl(jb_impl_type))) {
1019                 return -1;
1020         }
1021
1022         if (!(framedata->timer = ast_timer_open())) {
1023                 return -1;
1024         }
1025
1026         framedata->timer_fd = ast_timer_fd(framedata->timer);
1027         framedata->timer_interval = DEFAULT_TIMER_INTERVAL;
1028         ast_timer_set_rate(framedata->timer, 1000 / framedata->timer_interval);
1029         framedata->start_tv = ast_tvnow();
1030
1031         framedata->jb_obj = framedata->jb_impl->create(&framedata->jb_conf);
1032         return 0;
1033 }
1034
1035
1036 void ast_jb_create_framehook(struct ast_channel *chan, struct ast_jb_conf *jb_conf, int prefer_existing)
1037 {
1038         struct jb_framedata *framedata;
1039         struct ast_datastore *datastore = NULL;
1040         struct ast_framehook_interface interface = {
1041                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
1042                 .event_cb = hook_event_cb,
1043                 .destroy_cb = hook_destroy_cb,
1044         };
1045         int i = 0;
1046
1047         /* If disabled, strip any existing jitterbuffer and don't replace it. */
1048         if (!strcasecmp(jb_conf->impl, "disabled")) {
1049                 int *id;
1050                 ast_channel_lock(chan);
1051                 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1052                         id = datastore->data;
1053                         ast_framehook_detach(chan, *id);
1054                         ast_channel_datastore_remove(chan, datastore);
1055                 }
1056                 ast_channel_unlock(chan);
1057                 return;
1058         }
1059
1060         if (!(framedata = ast_calloc(1, sizeof(*framedata)))) {
1061                 return;
1062         }
1063
1064         if (jb_framedata_init(framedata, jb_conf)) {
1065                 jb_framedata_destroy(framedata);
1066                 return;
1067         }
1068
1069         interface.data = framedata;
1070
1071         ast_channel_lock(chan);
1072         i = ast_framehook_attach(chan, &interface);
1073         if (i >= 0) {
1074                 int *id;
1075                 if ((datastore = ast_channel_datastore_find(chan, &jb_datastore, NULL))) {
1076                         /* There is already a jitterbuffer on the channel. */
1077                         if (prefer_existing) {
1078                                 /* We prefer the existing jitterbuffer, so remove the new one and keep the old one. */
1079                                 ast_framehook_detach(chan, i);
1080                                 ast_channel_unlock(chan);
1081                                 return;
1082                         }
1083                         /* We prefer the new jitterbuffer, so strip the old one. */
1084                         id = datastore->data;
1085                         ast_framehook_detach(chan, *id);
1086                         ast_channel_datastore_remove(chan, datastore);
1087                 }
1088
1089                 if (!(datastore = ast_datastore_alloc(&jb_datastore, NULL))) {
1090                         ast_framehook_detach(chan, i);
1091                         ast_channel_unlock(chan);
1092                         return;
1093                 }
1094
1095                 if (!(id = ast_calloc(1, sizeof(int)))) {
1096                         ast_datastore_free(datastore);
1097                         ast_framehook_detach(chan, i);
1098                         ast_channel_unlock(chan);
1099                         return;
1100                 }
1101
1102                 *id = i; /* Store off the id. The channel is still locked so it is safe to access this ptr. */
1103                 datastore->data = id;
1104                 ast_channel_datastore_add(chan, datastore);
1105
1106                 ast_channel_set_fd(chan, AST_JITTERBUFFER_FD, framedata->timer_fd);
1107         } else {
1108                 jb_framedata_destroy(framedata);
1109                 framedata = NULL;
1110         }
1111         ast_channel_unlock(chan);
1112
1113         return;
1114 }