move extern declaration for this option to a header file where it belongs
[asterisk-bristuff.git] / main / translate.c
blobc9e16b96f85dd2fe990fe788e795095e556e6476
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 "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/time.h>
33 #include <unistd.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <stdio.h>
38 #include "asterisk/lock.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/logger.h"
41 #include "asterisk/translate.h"
42 #include "asterisk/module.h"
43 #include "asterisk/options.h"
44 #include "asterisk/frame.h"
45 #include "asterisk/sched.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/term.h"
49 #define MAX_RECALC 200 /* max sample recalc */
51 /*! \brief the list of translators */
52 static AST_LIST_HEAD_STATIC(translators, ast_translator);
54 struct translator_path {
55 struct ast_translator *step; /*!< Next step translator */
56 unsigned int cost; /*!< Complete cost to destination */
57 unsigned int multistep; /*!< Multiple conversions required for this translation */
60 /*! \brief a matrix that, for any pair of supported formats,
61 * indicates the total cost of translation and the first step.
62 * The full path can be reconstricted iterating on the matrix
63 * until step->dstfmt == desired_format.
65 * Array indexes are 'src' and 'dest', in that order.
67 * Note: the lock in the 'translators' list is also used to protect
68 * this structure.
70 static struct translator_path tr_matrix[MAX_FORMAT][MAX_FORMAT];
72 /*! \todo
73 * TODO: sample frames for each supported input format.
74 * We build this on the fly, by taking an SLIN frame and using
75 * the existing converter to play with it.
78 /*! \brief returns the index of the lowest bit set */
79 static force_inline int powerof(unsigned int d)
81 int x = ffs(d);
83 if (x)
84 return x - 1;
86 ast_log(LOG_WARNING, "No bits set? %d\n", d);
88 return -1;
92 * wrappers around the translator routines.
95 /*!
96 * \brief Allocate the descriptor, required outbuf space,
97 * and possibly also plc and desc.
99 static void *newpvt(struct ast_translator *t)
101 struct ast_trans_pvt *pvt;
102 int len;
103 int useplc = t->plc_samples > 0 && t->useplc; /* cache, because it can change on the fly */
104 char *ofs;
107 * compute the required size adding private descriptor,
108 * plc, buffer, AST_FRIENDLY_OFFSET.
110 len = sizeof(*pvt) + t->desc_size;
111 if (useplc)
112 len += sizeof(plc_state_t);
113 if (t->buf_size)
114 len += AST_FRIENDLY_OFFSET + t->buf_size;
115 pvt = ast_calloc(1, len);
116 if (!pvt)
117 return NULL;
118 pvt->t = t;
119 ofs = (char *)(pvt + 1); /* pointer to data space */
120 if (t->desc_size) { /* first comes the descriptor */
121 pvt->pvt = ofs;
122 ofs += t->desc_size;
124 if (useplc) { /* then plc state */
125 pvt->plc = (plc_state_t *)ofs;
126 ofs += sizeof(plc_state_t);
128 if (t->buf_size) /* finally buffer and header */
129 pvt->outbuf = ofs + AST_FRIENDLY_OFFSET;
130 /* call local init routine, if present */
131 if (t->newpvt && t->newpvt(pvt)) {
132 free(pvt);
133 return NULL;
135 ast_module_ref(t->module);
136 return pvt;
139 static void destroy(struct ast_trans_pvt *pvt)
141 struct ast_translator *t = pvt->t;
143 if (t->destroy)
144 t->destroy(pvt);
145 free(pvt);
146 ast_module_unref(t->module);
149 /*! \brief framein wrapper, deals with plc and bound checks. */
150 static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
152 int16_t *dst = (int16_t *)pvt->outbuf;
153 int ret;
154 int samples = pvt->samples; /* initial value */
156 /* Copy the last in jb timing info to the pvt */
157 pvt->f.has_timing_info = f->has_timing_info;
158 pvt->f.ts = f->ts;
159 pvt->f.len = f->len;
160 pvt->f.seqno = f->seqno;
162 if (f->samples == 0) {
163 ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
165 if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
166 if (f->datalen == 0) { /* perform PLC with nominal framesize of 20ms/160 samples */
167 if (pvt->plc) {
168 int l = pvt->t->plc_samples;
169 if (pvt->samples + l > pvt->t->buffer_samples) {
170 ast_log(LOG_WARNING, "Out of buffer space\n");
171 return -1;
173 l = plc_fillin(pvt->plc, dst + pvt->samples, l);
174 pvt->samples += l;
175 pvt->datalen = pvt->samples * 2; /* SLIN has 2bytes for 1sample */
177 return 0;
179 if (pvt->samples + f->samples > pvt->t->buffer_samples) {
180 ast_log(LOG_WARNING, "Out of buffer space\n");
181 return -1;
184 /* we require a framein routine, wouldn't know how to do
185 * it otherwise.
187 ret = pvt->t->framein(pvt, f);
188 /* possibly store data for plc */
189 if (!ret && pvt->plc) {
190 int l = pvt->t->plc_samples;
191 if (pvt->samples < l)
192 l = pvt->samples;
193 plc_rx(pvt->plc, dst + pvt->samples - l, l);
195 /* diagnostic ... */
196 if (pvt->samples == samples)
197 ast_log(LOG_WARNING, "%s did not update samples %d\n",
198 pvt->t->name, pvt->samples);
199 return ret;
202 /*! \brief generic frameout routine.
203 * If samples and datalen are 0, take whatever is in pvt
204 * and reset them, otherwise take the values in the caller and
205 * leave alone the pvt values.
207 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
208 int datalen, int samples)
210 struct ast_frame *f = &pvt->f;
212 if (samples)
213 f->samples = samples;
214 else {
215 if (pvt->samples == 0)
216 return NULL;
217 f->samples = pvt->samples;
218 pvt->samples = 0;
220 if (datalen)
221 f->datalen = datalen;
222 else {
223 f->datalen = pvt->datalen;
224 pvt->datalen = 0;
227 f->frametype = AST_FRAME_VOICE;
228 f->subclass = 1 << (pvt->t->dstfmt);
229 f->mallocd = 0;
230 f->offset = AST_FRIENDLY_OFFSET;
231 f->src = pvt->t->name;
232 f->data = pvt->outbuf;
233 return f;
236 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
238 return ast_trans_frameout(pvt, 0, 0);
241 /* end of callback wrappers and helpers */
243 void ast_translator_free_path(struct ast_trans_pvt *p)
245 struct ast_trans_pvt *pn = p;
246 while ( (p = pn) ) {
247 pn = p->next;
248 destroy(p);
252 /*! \brief Build a chain of translators based upon the given source and dest formats */
253 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
255 struct ast_trans_pvt *head = NULL, *tail = NULL;
257 source = powerof(source);
258 dest = powerof(dest);
260 AST_LIST_LOCK(&translators);
262 while (source != dest) {
263 struct ast_trans_pvt *cur;
264 struct ast_translator *t = tr_matrix[source][dest].step;
265 if (!t) {
266 ast_log(LOG_WARNING, "No translator path from %s to %s\n",
267 ast_getformatname(source), ast_getformatname(dest));
268 AST_LIST_UNLOCK(&translators);
269 return NULL;
271 if (!(cur = newpvt(t))) {
272 ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
273 if (head)
274 ast_translator_free_path(head);
275 AST_LIST_UNLOCK(&translators);
276 return NULL;
278 if (!head)
279 head = cur;
280 else
281 tail->next = cur;
282 tail = cur;
283 cur->nextin = cur->nextout = ast_tv(0, 0);
284 /* Keep going if this isn't the final destination */
285 source = cur->t->dstfmt;
288 AST_LIST_UNLOCK(&translators);
289 return head;
292 /*! \brief do the actual translation */
293 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
295 struct ast_trans_pvt *p = path;
296 struct ast_frame *out = f;
297 struct timeval delivery;
298 int has_timing_info;
299 long ts;
300 long len;
301 int seqno;
303 has_timing_info = f->has_timing_info;
304 ts = f->ts;
305 len = f->len;
306 seqno = f->seqno;
308 /* XXX hmmm... check this below */
309 if (!ast_tvzero(f->delivery)) {
310 if (!ast_tvzero(path->nextin)) {
311 /* Make sure this is in line with what we were expecting */
312 if (!ast_tveq(path->nextin, f->delivery)) {
313 /* The time has changed between what we expected and this
314 most recent time on the new packet. If we have a
315 valid prediction adjust our output time appropriately */
316 if (!ast_tvzero(path->nextout)) {
317 path->nextout = ast_tvadd(path->nextout,
318 ast_tvsub(f->delivery, path->nextin));
320 path->nextin = f->delivery;
322 } else {
323 /* This is our first pass. Make sure the timing looks good */
324 path->nextin = f->delivery;
325 path->nextout = f->delivery;
327 /* Predict next incoming sample */
328 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, 8000));
330 delivery = f->delivery;
331 for ( ; out && p ; p = p->next) {
332 framein(p, out);
333 out = p->t->frameout(p);
335 if (consume)
336 ast_frfree(f);
337 if (out == NULL)
338 return NULL;
339 /* we have a frame, play with times */
340 if (!ast_tvzero(delivery)) {
341 /* Regenerate prediction after a discontinuity */
342 if (ast_tvzero(path->nextout))
343 path->nextout = ast_tvnow();
345 /* Use next predicted outgoing timestamp */
346 out->delivery = path->nextout;
348 /* Predict next outgoing timestamp from samples in this
349 frame. */
350 path->nextout = ast_tvadd(path->nextout, ast_samp2tv( out->samples, 8000));
351 } else {
352 out->delivery = ast_tv(0, 0);
353 out->has_timing_info = has_timing_info;
354 if (has_timing_info) {
355 out->ts = ts;
356 out->len = len;
357 out->seqno = seqno;
360 /* Invalidate prediction if we're entering a silence period */
361 if (out->frametype == AST_FRAME_CNG)
362 path->nextout = ast_tv(0, 0);
363 return out;
366 /*! \brief compute the cost of a single translation step */
367 static void calc_cost(struct ast_translator *t, int seconds)
369 int sofar=0;
370 struct ast_trans_pvt *pvt;
371 struct timeval start;
372 int cost;
374 if (!seconds)
375 seconds = 1;
377 /* If they don't make samples, give them a terrible score */
378 if (!t->sample) {
379 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
380 t->cost = 99999;
381 return;
383 pvt = newpvt(t);
384 if (!pvt) {
385 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
386 t->cost = 99999;
387 return;
389 start = ast_tvnow();
390 /* Call the encoder until we've processed the required number of samples */
391 while (sofar < seconds * 8000) {
392 struct ast_frame *f = t->sample();
393 if (!f) {
394 ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
395 destroy(pvt);
396 t->cost = 99999;
397 return;
399 framein(pvt, f);
400 ast_frfree(f);
401 while ((f = t->frameout(pvt))) {
402 sofar += f->samples;
403 ast_frfree(f);
406 cost = ast_tvdiff_ms(ast_tvnow(), start);
407 destroy(pvt);
408 t->cost = cost / seconds;
409 if (!t->cost)
410 t->cost = 1;
414 * \brief rebuild a translation matrix.
415 * \note This function expects the list of translators to be locked
417 static void rebuild_matrix(int samples)
419 struct ast_translator *t;
420 int x; /* source format index */
421 int y; /* intermediate format index */
422 int z; /* destination format index */
424 if (option_debug)
425 ast_log(LOG_DEBUG, "Resetting translation matrix\n");
427 bzero(tr_matrix, sizeof(tr_matrix));
429 /* first, compute all direct costs */
430 AST_LIST_TRAVERSE(&translators, t, list) {
431 if (!t->active)
432 continue;
434 x = t->srcfmt;
435 z = t->dstfmt;
437 if (samples)
438 calc_cost(t, samples);
440 if (!tr_matrix[x][z].step || t->cost < tr_matrix[x][z].cost) {
441 tr_matrix[x][z].step = t;
442 tr_matrix[x][z].cost = t->cost;
447 * For each triple x, y, z of distinct formats, check if there is
448 * a path from x to z through y which is cheaper than what is
449 * currently known, and in case, update the matrix.
450 * Repeat until the matrix is stable.
452 for (;;) {
453 int changed = 0;
454 for (x = 0; x < MAX_FORMAT; x++) { /* source format */
455 for (y=0; y < MAX_FORMAT; y++) { /* intermediate format */
456 if (x == y) /* skip ourselves */
457 continue;
459 for (z=0; z<MAX_FORMAT; z++) { /* dst format */
460 int newcost;
462 if (z == x || z == y) /* skip null conversions */
463 continue;
464 if (!tr_matrix[x][y].step) /* no path from x to y */
465 continue;
466 if (!tr_matrix[y][z].step) /* no path from y to z */
467 continue;
468 newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
469 if (tr_matrix[x][z].step && newcost >= tr_matrix[x][z].cost)
470 continue; /* x->y->z is more expensive than
471 * the existing path */
472 /* ok, we can get from x to z via y with a cost that
473 is the sum of the transition from x to y and
474 from y to z */
476 tr_matrix[x][z].step = tr_matrix[x][y].step;
477 tr_matrix[x][z].cost = newcost;
478 tr_matrix[x][z].multistep = 1;
479 if (option_debug)
480 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);
481 changed++;
485 if (!changed)
486 break;
490 /*! \brief CLI "show translation" command handler */
491 static int show_translation_deprecated(int fd, int argc, char *argv[])
493 #define SHOW_TRANS 13
494 int x, y, z;
495 int curlen = 0, longest = 0;
497 if (argc > 4)
498 return RESULT_SHOWUSAGE;
500 AST_LIST_LOCK(&translators);
502 if (argv[2] && !strcasecmp(argv[2], "recalc")) {
503 z = argv[3] ? atoi(argv[3]) : 1;
505 if (z <= 0) {
506 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
507 z = 1;
510 if (z > MAX_RECALC) {
511 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
512 z = MAX_RECALC;
514 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
515 rebuild_matrix(z);
518 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
519 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
520 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
521 for (x = 0; x < SHOW_TRANS; x++) {
522 curlen = strlen(ast_getformatname(1 << (x + 1)));
523 if (curlen > longest)
524 longest = curlen;
526 for (x = -1; x < SHOW_TRANS; x++) {
527 char line[120];
528 char *buf = line;
529 size_t left = sizeof(line) - 1; /* one initial space */
530 /* next 2 lines run faster than using ast_build_string() */
531 *buf++ = ' ';
532 *buf = '\0';
533 for (y = -1; y < SHOW_TRANS; y++) {
534 curlen = strlen(ast_getformatname(1 << (y)));
536 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
537 /* XXX 999 is a little hackish
538 We don't want this number being larger than the shortest (or current) codec
539 For now, that is "gsm" */
540 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
541 } else if (x == -1 && y >= 0) {
542 /* Top row - use a dynamic size */
543 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (x + y + 1)) );
544 } else if (y == -1 && x >= 0) {
545 /* Left column - use a static size. */
546 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x + y + 1)) );
547 } else if (x >= 0 && y >= 0) {
548 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
549 } else {
550 ast_build_string(&buf, &left, "%*s", longest, "");
553 ast_build_string(&buf, &left, "\n");
554 ast_cli(fd, line);
556 AST_LIST_UNLOCK(&translators);
557 return RESULT_SUCCESS;
560 static int show_translation(int fd, int argc, char *argv[])
562 int x, y, z;
563 int curlen = 0, longest = 0;
565 if (argc > 5)
566 return RESULT_SHOWUSAGE;
568 AST_LIST_LOCK(&translators);
570 if (argv[3] && !strcasecmp(argv[3], "recalc")) {
571 z = argv[4] ? atoi(argv[4]) : 1;
573 if (z <= 0) {
574 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
575 z = 1;
578 if (z > MAX_RECALC) {
579 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
580 z = MAX_RECALC;
582 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
583 rebuild_matrix(z);
586 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
587 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
588 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
589 for (x = 0; x < SHOW_TRANS; x++) {
590 curlen = strlen(ast_getformatname(1 << (x + 1)));
591 if (curlen > longest)
592 longest = curlen;
594 for (x = -1; x < SHOW_TRANS; x++) {
595 char line[120];
596 char *buf = line;
597 size_t left = sizeof(line) - 1; /* one initial space */
598 /* next 2 lines run faster than using ast_build_string() */
599 *buf++ = ' ';
600 *buf = '\0';
601 for (y = -1; y < SHOW_TRANS; y++) {
602 curlen = strlen(ast_getformatname(1 << (y)));
604 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
605 /* XXX 999 is a little hackish
606 We don't want this number being larger than the shortest (or current) codec
607 For now, that is "gsm" */
608 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
609 } else if (x == -1 && y >= 0) {
610 /* Top row - use a dynamic size */
611 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (x + y + 1)) );
612 } else if (y == -1 && x >= 0) {
613 /* Left column - use a static size. */
614 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x + y + 1)) );
615 } else if (x >= 0 && y >= 0) {
616 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
617 } else {
618 ast_build_string(&buf, &left, "%*s", longest, "");
621 ast_build_string(&buf, &left, "\n");
622 ast_cli(fd, line);
624 AST_LIST_UNLOCK(&translators);
625 return RESULT_SUCCESS;
628 static char show_trans_usage[] =
629 "Usage: core show translation [recalc] [<recalc seconds>]\n"
630 " Displays known codec translators and the cost associated\n"
631 "with each conversion. If the argument 'recalc' is supplied along\n"
632 "with optional number of seconds to test a new test will be performed\n"
633 "as the chart is being displayed.\n";
635 static struct ast_cli_entry cli_show_translation_deprecated = {
636 { "show", "translation", NULL },
637 show_translation_deprecated, NULL,
638 NULL };
640 static struct ast_cli_entry cli_translate[] = {
641 { { "core", "show", "translation", NULL },
642 show_translation, "Display translation matrix",
643 show_trans_usage, NULL, &cli_show_translation_deprecated },
646 /*! \brief register codec translator */
647 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
649 static int added_cli = 0;
650 struct ast_translator *u;
652 if (!mod) {
653 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
654 return -1;
657 if (!t->buf_size) {
658 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
659 return -1;
662 t->module = mod;
664 t->srcfmt = powerof(t->srcfmt);
665 t->dstfmt = powerof(t->dstfmt);
666 t->active = 1;
668 if (t->plc_samples) {
669 if (t->buffer_samples < t->plc_samples) {
670 ast_log(LOG_WARNING, "plc_samples %d buffer_samples %d\n",
671 t->plc_samples, t->buffer_samples);
672 return -1;
674 if (t->dstfmt != AST_FORMAT_SLINEAR)
675 ast_log(LOG_WARNING, "plc_samples %d format %x\n",
676 t->plc_samples, t->dstfmt);
678 if (t->srcfmt >= MAX_FORMAT) {
679 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
680 return -1;
683 if (t->dstfmt >= MAX_FORMAT) {
684 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
685 return -1;
688 if (t->buf_size) {
690 * Align buf_size properly, rounding up to the machine-specific
691 * alignment for pointers.
693 struct _test_align { void *a, *b; } p;
694 int align = (char *)&p.b - (char *)&p.a;
696 t->buf_size = ((t->buf_size + align - 1) / align) * align;
699 if (t->frameout == NULL)
700 t->frameout = default_frameout;
702 calc_cost(t, 1);
704 if (option_verbose > 1) {
705 char tmp[80];
707 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %s to %s, cost %d\n",
708 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
709 ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
712 if (!added_cli) {
713 ast_cli_register_multiple(cli_translate, sizeof(cli_translate) / sizeof(struct ast_cli_entry));
714 added_cli++;
717 AST_LIST_LOCK(&translators);
719 /* find any existing translators that provide this same srcfmt/dstfmt,
720 and put this one in order based on cost */
721 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
722 if ((u->srcfmt == t->srcfmt) &&
723 (u->dstfmt == t->dstfmt) &&
724 (u->cost > t->cost)) {
725 AST_LIST_INSERT_BEFORE_CURRENT(&translators, t, list);
726 t = NULL;
729 AST_LIST_TRAVERSE_SAFE_END;
731 /* if no existing translator was found for this format combination,
732 add it to the beginning of the list */
733 if (t)
734 AST_LIST_INSERT_HEAD(&translators, t, list);
736 rebuild_matrix(0);
738 AST_LIST_UNLOCK(&translators);
740 return 0;
743 /*! \brief unregister codec translator */
744 int ast_unregister_translator(struct ast_translator *t)
746 char tmp[80];
747 struct ast_translator *u;
748 int found = 0;
750 AST_LIST_LOCK(&translators);
751 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
752 if (u == t) {
753 AST_LIST_REMOVE_CURRENT(&translators, list);
754 if (option_verbose > 1)
755 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));
756 found = 1;
757 break;
760 AST_LIST_TRAVERSE_SAFE_END;
762 if (found)
763 rebuild_matrix(0);
765 AST_LIST_UNLOCK(&translators);
767 return (u ? 0 : -1);
770 void ast_translator_activate(struct ast_translator *t)
772 AST_LIST_LOCK(&translators);
773 t->active = 1;
774 rebuild_matrix(0);
775 AST_LIST_UNLOCK(&translators);
778 void ast_translator_deactivate(struct ast_translator *t)
780 AST_LIST_LOCK(&translators);
781 t->active = 0;
782 rebuild_matrix(0);
783 AST_LIST_UNLOCK(&translators);
786 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
787 int ast_translator_best_choice(int *dst, int *srcs)
789 int x,y;
790 int best = -1;
791 int bestdst = 0;
792 int cur, cursrc;
793 int besttime = INT_MAX;
794 int beststeps = INT_MAX;
795 int common = (*dst) & (*srcs); /* are there common formats ? */
797 if (common) { /* yes, pick one and return */
798 for (cur = 1, y = 0; y < MAX_FORMAT; cur <<= 1, y++) {
799 if (cur & common) /* guaranteed to find one */
800 break;
802 /* We are done, this is a common format to both. */
803 *srcs = *dst = cur;
804 return 0;
805 } else { /* No, we will need to translate */
806 AST_LIST_LOCK(&translators);
807 for (cur = 1, y = 0; y < MAX_FORMAT; cur <<= 1, y++) {
808 if (! (cur & *dst))
809 continue;
810 for (cursrc = 1, x = 0; x < MAX_FORMAT; cursrc <<= 1, x++) {
811 if (!(*srcs & cursrc) || !tr_matrix[x][y].step ||
812 tr_matrix[x][y].cost > besttime)
813 continue; /* not existing or no better */
814 if (tr_matrix[x][y].cost < besttime ||
815 tr_matrix[x][y].multistep < beststeps) {
816 /* better than what we have so far */
817 best = cursrc;
818 bestdst = cur;
819 besttime = tr_matrix[x][y].cost;
820 beststeps = tr_matrix[x][y].multistep;
824 AST_LIST_UNLOCK(&translators);
825 if (best > -1) {
826 *srcs = best;
827 *dst = bestdst;
828 best = 0;
830 return best;
834 unsigned int ast_translate_path_steps(unsigned int dest, unsigned int src)
836 unsigned int res = -1;
838 /* convert bitwise format numbers into array indices */
839 src = powerof(src);
840 dest = powerof(dest);
842 AST_LIST_LOCK(&translators);
844 if (tr_matrix[src][dest].step)
845 res = tr_matrix[src][dest].multistep + 1;
847 AST_LIST_UNLOCK(&translators);
849 return res;
852 unsigned int ast_translate_available_formats(unsigned int dest, unsigned int src)
854 unsigned int res = dest;
855 unsigned int x;
856 unsigned int src_audio = src & AST_FORMAT_AUDIO_MASK;
857 unsigned int src_video = src & AST_FORMAT_VIDEO_MASK;
859 /* if we don't have a source format, we just have to try all
860 possible destination formats */
861 if (!src)
862 return dest;
864 /* If we have a source audio format, get its format index */
865 if (src_audio)
866 src_audio = powerof(src_audio);
868 /* If we have a source video format, get its format index */
869 if (src_video)
870 src_video = powerof(src_video);
872 AST_LIST_LOCK(&translators);
874 /* For a given source audio format, traverse the list of
875 known audio formats to determine whether there exists
876 a translation path from the source format to the
877 destination format. */
878 for (x = 1; src_audio && x < AST_FORMAT_MAX_AUDIO; x <<= 1) {
879 /* if this is not a desired format, nothing to do */
880 if (!dest & x)
881 continue;
883 /* if the source is supplying this format, then
884 we can leave it in the result */
885 if (src & x)
886 continue;
888 /* if we don't have a translation path from the src
889 to this format, remove it from the result */
890 if (!tr_matrix[src_audio][powerof(x)].step) {
891 res &= ~x;
892 continue;
895 /* now check the opposite direction */
896 if (!tr_matrix[powerof(x)][src_audio].step)
897 res &= ~x;
900 /* For a given source video format, traverse the list of
901 known video formats to determine whether there exists
902 a translation path from the source format to the
903 destination format. */
904 for (; src_video && x < AST_FORMAT_MAX_VIDEO; x <<= 1) {
905 /* if this is not a desired format, nothing to do */
906 if (!dest & x)
907 continue;
909 /* if the source is supplying this format, then
910 we can leave it in the result */
911 if (src & x)
912 continue;
914 /* if we don't have a translation path from the src
915 to this format, remove it from the result */
916 if (!tr_matrix[src_video][powerof(x)].step) {
917 res &= ~x;
918 continue;
921 /* now check the opposite direction */
922 if (!tr_matrix[powerof(x)][src_video].step)
923 res &= ~x;
926 AST_LIST_UNLOCK(&translators);
928 return res;