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