Merged revisions 30874 via svnmerge from
[asterisk-bristuff.git] / translate.c
blobd71381753957fc0bd0feeaff2b380b0b0ab48d88
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*! \file
21 * \brief Translate via the use of pseudo channels
23 * \author Mark Spencer <markster@digium.com>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/time.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdio.h>
34 #define MOD_LOADER /* not really a module */
35 #include "asterisk.h"
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39 #include "asterisk/lock.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/logger.h"
42 #include "asterisk/translate.h"
43 #include "asterisk/module.h"
44 #include "asterisk/options.h"
45 #include "asterisk/frame.h"
46 #include "asterisk/sched.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/term.h"
50 #define MAX_RECALC 200 /* max sample recalc */
52 /*! \brief the list of translators */
53 static AST_LIST_HEAD_STATIC(translators, ast_translator);
55 struct translator_path {
56 struct ast_translator *step; /*!< Next step translator */
57 unsigned int cost; /*!< Complete cost to destination */
58 unsigned int multistep; /*!< Multiple conversions required for this translation */
61 /*! \brief a matrix that, for any pair of supported formats,
62 * indicates the total cost of translation and the first step.
63 * The full path can be reconstricted iterating on the matrix
64 * until step->dstfmt == desired_format.
66 * Array indexes are 'src' and 'dest', in that order.
68 static struct translator_path tr_matrix[MAX_FORMAT][MAX_FORMAT];
71 * TODO: sample frames for each supported input format.
72 * We build this on the fly, by taking an SLIN frame and using
73 * the existing converter to play with it.
76 /* returns the index of the lowest bit set */
77 static int powerof(int d)
79 int x;
80 for (x = 0; x < MAX_FORMAT; x++)
81 if ((1 << x) & d)
82 return x;
83 ast_log(LOG_WARNING, "Powerof %d: No power??\n", d);
84 return -1;
88 * wrappers around the translator routines.
91 /*!
92 * \brief Allocate the descriptor, required outbuf space,
93 * and possibly also plc and desc.
95 static void *newpvt(struct ast_translator *t)
97 struct ast_trans_pvt *pvt;
98 int len;
99 int useplc = t->plc_samples > 0 && t->useplc; /* cache, because it can change on the fly */
100 char *ofs;
101 struct module_symbols *ms = t->module;
104 * compute the required size adding private descriptor,
105 * plc, buffer, AST_FRIENDLY_OFFSET.
107 len = sizeof(*pvt) + t->desc_size;
108 if (useplc)
109 len += sizeof(plc_state_t);
110 if (t->buf_size)
111 len += AST_FRIENDLY_OFFSET + t->buf_size;
112 pvt = ast_calloc(1, len);
113 if (!pvt)
114 return NULL;
115 pvt->t = t;
116 ofs = (char *)(pvt + 1); /* pointer to data space */
117 if (t->desc_size) { /* first comes the descriptor */
118 pvt->pvt = ofs;
119 ofs += t->desc_size;
121 if (useplc) { /* then plc state */
122 pvt->plc = (plc_state_t *)ofs;
123 ofs += sizeof(plc_state_t);
125 if (t->buf_size) /* finally buffer and header */
126 pvt->outbuf = ofs + AST_FRIENDLY_OFFSET;
127 /* call local init routine, if present */
128 if (t->newpvt && t->newpvt(pvt) == NULL) {
129 free(pvt);
130 return NULL;
132 ast_atomic_fetchadd_int(&ms->usecnt, +1);
133 ast_update_use_count();
134 return pvt;
137 static void destroy(struct ast_trans_pvt *pvt)
139 struct ast_translator *t = pvt->t;
140 struct module_symbols *ms = t->module;
142 if (t->destroy)
143 t->destroy(pvt);
144 free(pvt);
145 ast_atomic_fetchadd_int(&ms->usecnt, -1);
146 ast_update_use_count();
150 * framein wrapper, deals with plc and bound checks.
152 static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
154 int16_t *dst = (int16_t *)pvt->outbuf;
155 int ret;
156 int samples = pvt->samples; /* initial value */
158 if (f->samples == 0) {
159 ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
161 if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
162 if (f->datalen == 0) { /* perform PLC with nominal framesize of 20ms/160 samples */
163 if (pvt->plc) {
164 int l = pvt->t->plc_samples;
165 if (pvt->samples + l > pvt->t->buffer_samples) {
166 ast_log(LOG_WARNING, "Out of buffer space\n");
167 return -1;
169 l = plc_fillin(pvt->plc, dst + pvt->samples, l);
170 pvt->samples += l;
172 return 0;
174 if (pvt->samples + f->samples > pvt->t->buffer_samples) {
175 ast_log(LOG_WARNING, "Out of buffer space\n");
176 return -1;
179 /* we require a framein routine, wouldn't know how to do
180 * it otherwise.
182 ret = pvt->t->framein(pvt, f);
183 /* possibly store data for plc */
184 if (!ret && pvt->plc) {
185 int l = pvt->t->plc_samples;
186 if (pvt->samples < l)
187 l = pvt->samples;
188 plc_rx(pvt->plc, dst + pvt->samples - l, l);
190 /* diagnostic ... */
191 if (pvt->samples == samples)
192 ast_log(LOG_WARNING, "%s did not update samples %d\n",
193 pvt->t->name, pvt->samples);
194 return ret;
198 * generic frameout routine.
199 * If samples and datalen are 0, take whatever is in pvt
200 * and reset them, otherwise take the values in the caller and
201 * leave alone the pvt values.
203 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
204 int datalen, int samples)
206 struct ast_frame *f = &pvt->f;
208 if (samples)
209 f->samples = samples;
210 else {
211 if (pvt->samples == 0)
212 return NULL;
213 f->samples = pvt->samples;
214 pvt->samples = 0;
216 if (datalen)
217 f->datalen = datalen;
218 else {
219 f->datalen = pvt->datalen;
220 pvt->datalen = 0;
223 f->frametype = AST_FRAME_VOICE;
224 f->subclass = 1 << (pvt->t->dstfmt);
225 f->mallocd = 0;
226 f->offset = AST_FRIENDLY_OFFSET;
227 f->src = pvt->t->name;
228 f->data = pvt->outbuf;
229 return f;
232 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
234 return ast_trans_frameout(pvt, 0, 0);
237 /* end of callback wrappers and helpers */
239 void ast_translator_free_path(struct ast_trans_pvt *p)
241 struct ast_trans_pvt *pn = p;
242 while ( (p = pn) ) {
243 pn = p->next;
244 destroy(p);
248 /*! Build a chain of translators based upon the given source and dest formats */
249 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
251 struct ast_trans_pvt *head = NULL, *tail = NULL;
253 source = powerof(source);
254 dest = powerof(dest);
256 while (source != dest) {
257 struct ast_trans_pvt *cur;
258 struct ast_translator *t = tr_matrix[source][dest].step;
259 if (!t) {
260 ast_log(LOG_WARNING, "No translator path from %s to %s\n",
261 ast_getformatname(source), ast_getformatname(dest));
262 return NULL;
264 if (!(cur = newpvt(t))) {
265 ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
266 if (head)
267 ast_translator_free_path(head);
268 return NULL;
270 if (!head)
271 head = cur;
272 else
273 tail->next = cur;
274 tail = cur;
275 cur->nextin = cur->nextout = ast_tv(0, 0);
276 /* Keep going if this isn't the final destination */
277 source = cur->t->dstfmt;
279 return head;
282 /*! \brief do the actual translation */
283 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
285 struct ast_trans_pvt *p = path;
286 struct ast_frame *out = f;
287 struct timeval delivery;
289 /* XXX hmmm... check this below */
290 if (!ast_tvzero(f->delivery)) {
291 if (!ast_tvzero(path->nextin)) {
292 /* Make sure this is in line with what we were expecting */
293 if (!ast_tveq(path->nextin, f->delivery)) {
294 /* The time has changed between what we expected and this
295 most recent time on the new packet. If we have a
296 valid prediction adjust our output time appropriately */
297 if (!ast_tvzero(path->nextout)) {
298 path->nextout = ast_tvadd(path->nextout,
299 ast_tvsub(f->delivery, path->nextin));
301 path->nextin = f->delivery;
303 } else {
304 /* This is our first pass. Make sure the timing looks good */
305 path->nextin = f->delivery;
306 path->nextout = f->delivery;
308 /* Predict next incoming sample */
309 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, 8000));
311 delivery = f->delivery;
312 for ( ; out && p ; p = p->next) {
313 framein(p, out);
314 out = p->t->frameout(p);
316 if (consume)
317 ast_frfree(f);
318 if (out == NULL)
319 return NULL;
320 /* we have a frame, play with times */
321 if (!ast_tvzero(delivery)) {
322 /* Regenerate prediction after a discontinuity */
323 if (ast_tvzero(path->nextout))
324 path->nextout = ast_tvnow();
326 /* Use next predicted outgoing timestamp */
327 out->delivery = path->nextout;
329 /* Predict next outgoing timestamp from samples in this
330 frame. */
331 path->nextout = ast_tvadd(path->nextout, ast_samp2tv( out->samples, 8000));
332 } else {
333 out->delivery = ast_tv(0, 0);
335 /* Invalidate prediction if we're entering a silence period */
336 if (out->frametype == AST_FRAME_CNG)
337 path->nextout = ast_tv(0, 0);
338 return out;
341 /*! \brief compute the cost of a single translation step */
342 static void calc_cost(struct ast_translator *t, int seconds)
344 int sofar=0;
345 struct ast_trans_pvt *pvt;
346 struct timeval start;
347 int cost;
349 if (!seconds)
350 seconds = 1;
352 /* If they don't make samples, give them a terrible score */
353 if (!t->sample) {
354 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
355 t->cost = 99999;
356 return;
358 pvt = newpvt(t);
359 if (!pvt) {
360 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
361 t->cost = 99999;
362 return;
364 start = ast_tvnow();
365 /* Call the encoder until we've processed the required number of samples */
366 while (sofar < seconds * 8000) {
367 struct ast_frame *f = t->sample();
368 if (!f) {
369 ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
370 destroy(pvt);
371 t->cost = 99999;
372 return;
374 framein(pvt, f);
375 ast_frfree(f);
376 while( (f = t->frameout(pvt))) {
377 sofar += f->samples;
378 ast_frfree(f);
381 cost = ast_tvdiff_ms(ast_tvnow(), start);
382 destroy(pvt);
383 t->cost = cost / seconds;
384 if (!t->cost)
385 t->cost = 1;
389 * \brief rebuild a translation matrix.
390 * \note This function expects the list of translators to be locked
392 static void rebuild_matrix(int samples)
394 struct ast_translator *t;
395 int x; /* source format index */
396 int y; /* intermediate format index */
397 int z; /* destination format index */
399 if (option_debug)
400 ast_log(LOG_DEBUG, "Resetting translation matrix\n");
402 bzero(tr_matrix, sizeof(tr_matrix));
404 /* first, compute all direct costs */
405 AST_LIST_TRAVERSE(&translators, t, list) {
406 x = t->srcfmt;
407 z = t->dstfmt;
409 if (samples)
410 calc_cost(t, samples);
412 if (!tr_matrix[x][z].step || t->cost < tr_matrix[x][z].cost) {
413 tr_matrix[x][z].step = t;
414 tr_matrix[x][z].cost = t->cost;
419 * For each triple x, y, z of distinct formats, check if there is
420 * a path from x to z through y which is cheaper than what is
421 * currently known, and in case, update the matrix.
422 * Repeat until the matrix is stable.
424 for (;;) {
425 int changed = 0;
426 for (x=0; x < MAX_FORMAT; x++) { /* source format */
427 for (y=0; y < MAX_FORMAT; y++) { /* intermediate format */
428 if (x == y) /* skip ourselves */
429 continue;
431 for (z=0; z<MAX_FORMAT; z++) { /* dst format */
432 int newcost;
434 if (z == x || z == y) /* skip null conversions */
435 continue;
436 if (!tr_matrix[x][y].step) /* no path from x to y */
437 continue;
438 if (!tr_matrix[y][z].step) /* no path from y to z */
439 continue;
440 newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
441 if (tr_matrix[x][z].step && newcost >= tr_matrix[x][z].cost)
442 continue; /* x->y->z is more expensive than
443 * the existing path */
444 /* ok, we can get from x to z via y with a cost that
445 is the sum of the transition from x to y and
446 from y to z */
448 tr_matrix[x][z].step = tr_matrix[x][y].step;
449 tr_matrix[x][z].cost = newcost;
450 tr_matrix[x][z].multistep = 1;
451 if (option_debug)
452 ast_log(LOG_DEBUG, "Discovered %d cost path from %s to %s, via %d\n", tr_matrix[x][z].cost, ast_getformatname(x), ast_getformatname(z), y);
453 changed++;
457 if (!changed)
458 break;
462 /*! \brief CLI "show translation" command handler */
463 static int show_translation(int fd, int argc, char *argv[])
465 #define SHOW_TRANS 11
466 int x, y, z;
468 if (argc > 4)
469 return RESULT_SHOWUSAGE;
471 AST_LIST_LOCK(&translators);
473 if (argv[2] && !strcasecmp(argv[2],"recalc")) {
474 z = argv[3] ? atoi(argv[3]) : 1;
476 if (z <= 0) {
477 ast_cli(fd," C'mon let's be serious here... defaulting to 1.\n");
478 z = 1;
481 if (z > MAX_RECALC) {
482 ast_cli(fd," Maximum limit of recalc exceeded by %d, truncating value to %d\n",z-MAX_RECALC,MAX_RECALC);
483 z = MAX_RECALC;
485 ast_cli(fd," Recalculating Codec Translation (number of sample seconds: %d)\n\n",z);
486 rebuild_matrix(z);
489 ast_cli(fd, " Translation times between formats (in milliseconds)\n");
490 ast_cli(fd, " Source Format (Rows) Destination Format(Columns)\n\n");
491 for (x = -1; x < SHOW_TRANS; x++) {
492 char line[80];
493 char *buf = line;
494 size_t left = sizeof(line) - 1; /* one initial space */
495 /* next 2 lines run faster than using ast_build_string() */
496 *buf++ = ' ';
497 *buf = '\0';
498 for (y=-1;y<SHOW_TRANS;y++) {
499 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) /* XXX what is 99999 ? */
500 ast_build_string(&buf, &left, " %5d", tr_matrix[x][y].cost >= 99999 ? 0 : tr_matrix[x][y].cost);
501 else if (((x == -1 && y >= 0) || (y == -1 && x >= 0))) {
502 ast_build_string(&buf, &left, " %5s", ast_getformatname(1<<(x+y+1)) );
503 } else if (x != -1 && y != -1) {
504 ast_build_string(&buf, &left, " -");
505 } else {
506 ast_build_string(&buf, &left, " ");
509 ast_build_string(&buf, &left, "\n");
510 ast_cli(fd, line);
512 AST_LIST_UNLOCK(&translators);
513 return RESULT_SUCCESS;
517 static char show_trans_usage[] =
518 "Usage: show translation [recalc] [<recalc seconds>]\n"
519 " Displays known codec translators and the cost associated\n"
520 "with each conversion. If the argument 'recalc' is supplied along\n"
521 "with optional number of seconds to test a new test will be performed\n"
522 "as the chart is being displayed.\n";
524 static struct ast_cli_entry show_trans =
525 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
527 int ast_register_translator(struct ast_translator *t, void *module)
529 static int added_cli = 0;
531 if (module == NULL) {
532 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
533 return -1;
535 t->module = module;
536 if (t->buf_size == 0) {
537 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
538 return -1;
540 if (t->plc_samples) {
541 if (t->buffer_samples < t->plc_samples) {
542 ast_log(LOG_WARNING, "plc_samples %d buffer_samples %d\n",
543 t->plc_samples, t->buffer_samples);
544 return -1;
546 if (t->dstfmt != AST_FORMAT_SLINEAR)
547 ast_log(LOG_WARNING, "plc_samples %d format %x\n",
548 t->plc_samples, t->dstfmt);
550 t->srcfmt = powerof(t->srcfmt);
551 t->dstfmt = powerof(t->dstfmt);
552 /* XXX maybe check that it is not existing yet ? */
553 if (t->srcfmt >= MAX_FORMAT) {
554 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
555 return -1;
557 if (t->dstfmt >= MAX_FORMAT) {
558 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
559 return -1;
561 if (t->buf_size) {
563 * Align buf_size properly, rounding up to the machine-specific
564 * alignment for pointers.
566 struct _test_align { void *a, *b; } p;
567 int align = (char *)&p.b - (char *)&p.a;
568 t->buf_size = ((t->buf_size + align - 1)/align)*align;
570 if (t->frameout == NULL)
571 t->frameout = default_frameout;
573 calc_cost(t,1);
574 if (option_verbose > 1) {
575 char tmp[80];
576 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %s to %s, cost %d\n",
577 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
578 ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
580 AST_LIST_LOCK(&translators);
581 if (!added_cli) {
582 ast_cli_register(&show_trans);
583 added_cli++;
585 AST_LIST_INSERT_HEAD(&translators, t, list);
586 rebuild_matrix(0);
587 AST_LIST_UNLOCK(&translators);
588 return 0;
591 /*! \brief unregister codec translator */
592 int ast_unregister_translator(struct ast_translator *t)
594 char tmp[80];
595 struct ast_translator *u;
596 AST_LIST_LOCK(&translators);
597 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
598 if (u == t) {
599 AST_LIST_REMOVE_CURRENT(&translators, list);
600 if (option_verbose > 1)
601 ast_verbose(VERBOSE_PREFIX_2 "Unregistered translator '%s' from format %s to %s\n", term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)), ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt));
602 break;
605 AST_LIST_TRAVERSE_SAFE_END
606 rebuild_matrix(0);
607 AST_LIST_UNLOCK(&translators);
608 return (u ? 0 : -1);
611 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
612 int ast_translator_best_choice(int *dst, int *srcs)
614 int x,y;
615 int best = -1;
616 int bestdst = 0;
617 int cur, cursrc;
618 int besttime = INT_MAX;
619 int beststeps = INT_MAX;
620 int common = (*dst) & (*srcs); /* are there common formats ? */
622 if (common) { /* yes, pick one and return */
623 for (cur = 1, y=0; y < MAX_FORMAT; cur <<=1, y++) {
624 if (cur & common) /* guaranteed to find one */
625 break;
627 /* We are done, this is a common format to both. */
628 *srcs = *dst = cur;
629 return 0;
630 } else { /* No, we will need to translate */
631 AST_LIST_LOCK(&translators);
632 for (cur = 1, y=0; y < MAX_FORMAT; cur <<=1, y++) {
633 if (! (cur & *dst))
634 continue;
635 for (cursrc = 1, x=0; x < MAX_FORMAT; cursrc <<= 1, x++) {
636 if (!(*srcs & cursrc) || !tr_matrix[x][y].step ||
637 tr_matrix[x][y].cost > besttime)
638 continue; /* not existing or no better */
639 if (tr_matrix[x][y].cost < besttime ||
640 tr_matrix[x][y].multistep < beststeps) {
641 /* better than what we have so far */
642 best = cursrc;
643 bestdst = cur;
644 besttime = tr_matrix[x][y].cost;
645 beststeps = tr_matrix[x][y].multistep;
649 AST_LIST_UNLOCK(&translators);
650 if (best > -1) {
651 *srcs = best;
652 *dst = bestdst;
653 best = 0;
655 return best;
659 unsigned int ast_translate_path_steps(unsigned int dest, unsigned int src)
661 /* convert bitwise format numbers into array indices */
662 src = powerof(src);
663 dest = powerof(dest);
664 if (!tr_matrix[src][dest].step)
665 return -1;
666 else
667 return tr_matrix[src][dest].multistep + 1;