Use the constant that I really meant to use here ...
[asterisk-bristuff.git] / main / translate.c
blobe01ce93212e8af231a71b146b86b9f1bf0077092
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 /* We don't want generic PLC. If the codec has native PLC, then do that */
178 if (!pvt->t->native_plc)
179 return 0;
181 if (pvt->samples + f->samples > pvt->t->buffer_samples) {
182 ast_log(LOG_WARNING, "Out of buffer space\n");
183 return -1;
186 /* we require a framein routine, wouldn't know how to do
187 * it otherwise.
189 ret = pvt->t->framein(pvt, f);
190 /* possibly store data for plc */
191 if (!ret && pvt->plc) {
192 int l = pvt->t->plc_samples;
193 if (pvt->samples < l)
194 l = pvt->samples;
195 plc_rx(pvt->plc, dst + pvt->samples - l, l);
197 /* diagnostic ... */
198 if (pvt->samples == samples)
199 ast_log(LOG_WARNING, "%s did not update samples %d\n",
200 pvt->t->name, pvt->samples);
201 return ret;
204 /*! \brief generic frameout routine.
205 * If samples and datalen are 0, take whatever is in pvt
206 * and reset them, otherwise take the values in the caller and
207 * leave alone the pvt values.
209 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
210 int datalen, int samples)
212 struct ast_frame *f = &pvt->f;
214 if (samples)
215 f->samples = samples;
216 else {
217 if (pvt->samples == 0)
218 return NULL;
219 f->samples = pvt->samples;
220 pvt->samples = 0;
222 if (datalen)
223 f->datalen = datalen;
224 else {
225 f->datalen = pvt->datalen;
226 pvt->datalen = 0;
229 f->frametype = AST_FRAME_VOICE;
230 f->subclass = 1 << (pvt->t->dstfmt);
231 f->mallocd = 0;
232 f->offset = AST_FRIENDLY_OFFSET;
233 f->src = pvt->t->name;
234 f->data = pvt->outbuf;
235 return f;
238 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
240 return ast_trans_frameout(pvt, 0, 0);
243 /* end of callback wrappers and helpers */
245 void ast_translator_free_path(struct ast_trans_pvt *p)
247 struct ast_trans_pvt *pn = p;
248 while ( (p = pn) ) {
249 pn = p->next;
250 destroy(p);
254 /*! \brief Build a chain of translators based upon the given source and dest formats */
255 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
257 struct ast_trans_pvt *head = NULL, *tail = NULL;
259 source = powerof(source);
260 dest = powerof(dest);
262 AST_LIST_LOCK(&translators);
264 while (source != dest) {
265 struct ast_trans_pvt *cur;
266 struct ast_translator *t = tr_matrix[source][dest].step;
267 if (!t) {
268 ast_log(LOG_WARNING, "No translator path from %s to %s\n",
269 ast_getformatname(source), ast_getformatname(dest));
270 AST_LIST_UNLOCK(&translators);
271 return NULL;
273 if (!(cur = newpvt(t))) {
274 ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
275 if (head)
276 ast_translator_free_path(head);
277 AST_LIST_UNLOCK(&translators);
278 return NULL;
280 if (!head)
281 head = cur;
282 else
283 tail->next = cur;
284 tail = cur;
285 cur->nextin = cur->nextout = ast_tv(0, 0);
286 /* Keep going if this isn't the final destination */
287 source = cur->t->dstfmt;
290 AST_LIST_UNLOCK(&translators);
291 return head;
294 /*! \brief do the actual translation */
295 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
297 struct ast_trans_pvt *p = path;
298 struct ast_frame *out = f;
299 struct timeval delivery;
300 int has_timing_info;
301 long ts;
302 long len;
303 int seqno;
305 has_timing_info = f->has_timing_info;
306 ts = f->ts;
307 len = f->len;
308 seqno = f->seqno;
310 /* XXX hmmm... check this below */
311 if (!ast_tvzero(f->delivery)) {
312 if (!ast_tvzero(path->nextin)) {
313 /* Make sure this is in line with what we were expecting */
314 if (!ast_tveq(path->nextin, f->delivery)) {
315 /* The time has changed between what we expected and this
316 most recent time on the new packet. If we have a
317 valid prediction adjust our output time appropriately */
318 if (!ast_tvzero(path->nextout)) {
319 path->nextout = ast_tvadd(path->nextout,
320 ast_tvsub(f->delivery, path->nextin));
322 path->nextin = f->delivery;
324 } else {
325 /* This is our first pass. Make sure the timing looks good */
326 path->nextin = f->delivery;
327 path->nextout = f->delivery;
329 /* Predict next incoming sample */
330 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, 8000));
332 delivery = f->delivery;
333 for ( ; out && p ; p = p->next) {
334 framein(p, out);
335 out = p->t->frameout(p);
337 if (consume)
338 ast_frfree(f);
339 if (out == NULL)
340 return NULL;
341 /* we have a frame, play with times */
342 if (!ast_tvzero(delivery)) {
343 /* Regenerate prediction after a discontinuity */
344 if (ast_tvzero(path->nextout))
345 path->nextout = ast_tvnow();
347 /* Use next predicted outgoing timestamp */
348 out->delivery = path->nextout;
350 /* Predict next outgoing timestamp from samples in this
351 frame. */
352 path->nextout = ast_tvadd(path->nextout, ast_samp2tv( out->samples, 8000));
353 } else {
354 out->delivery = ast_tv(0, 0);
355 out->has_timing_info = has_timing_info;
356 if (has_timing_info) {
357 out->ts = ts;
358 out->len = len;
359 out->seqno = seqno;
362 /* Invalidate prediction if we're entering a silence period */
363 if (out->frametype == AST_FRAME_CNG)
364 path->nextout = ast_tv(0, 0);
365 return out;
368 /*! \brief compute the cost of a single translation step */
369 static void calc_cost(struct ast_translator *t, int seconds)
371 int sofar=0;
372 struct ast_trans_pvt *pvt;
373 struct timeval start;
374 int cost;
376 if (!seconds)
377 seconds = 1;
379 /* If they don't make samples, give them a terrible score */
380 if (!t->sample) {
381 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
382 t->cost = 99999;
383 return;
385 pvt = newpvt(t);
386 if (!pvt) {
387 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
388 t->cost = 99999;
389 return;
391 start = ast_tvnow();
392 /* Call the encoder until we've processed the required number of samples */
393 while (sofar < seconds * 8000) {
394 struct ast_frame *f = t->sample();
395 if (!f) {
396 ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
397 destroy(pvt);
398 t->cost = 99999;
399 return;
401 framein(pvt, f);
402 ast_frfree(f);
403 while ((f = t->frameout(pvt))) {
404 sofar += f->samples;
405 ast_frfree(f);
408 cost = ast_tvdiff_ms(ast_tvnow(), start);
409 destroy(pvt);
410 t->cost = cost / seconds;
411 if (!t->cost)
412 t->cost = 1;
416 * \brief rebuild a translation matrix.
417 * \note This function expects the list of translators to be locked
419 static void rebuild_matrix(int samples)
421 struct ast_translator *t;
422 int x; /* source format index */
423 int y; /* intermediate format index */
424 int z; /* destination format index */
426 if (option_debug)
427 ast_log(LOG_DEBUG, "Resetting translation matrix\n");
429 bzero(tr_matrix, sizeof(tr_matrix));
431 /* first, compute all direct costs */
432 AST_LIST_TRAVERSE(&translators, t, list) {
433 if (!t->active)
434 continue;
436 x = t->srcfmt;
437 z = t->dstfmt;
439 if (samples)
440 calc_cost(t, samples);
442 if (!tr_matrix[x][z].step || t->cost < tr_matrix[x][z].cost) {
443 tr_matrix[x][z].step = t;
444 tr_matrix[x][z].cost = t->cost;
449 * For each triple x, y, z of distinct formats, check if there is
450 * a path from x to z through y which is cheaper than what is
451 * currently known, and in case, update the matrix.
452 * Repeat until the matrix is stable.
454 for (;;) {
455 int changed = 0;
456 for (x = 0; x < MAX_FORMAT; x++) { /* source format */
457 for (y=0; y < MAX_FORMAT; y++) { /* intermediate format */
458 if (x == y) /* skip ourselves */
459 continue;
461 for (z=0; z<MAX_FORMAT; z++) { /* dst format */
462 int newcost;
464 if (z == x || z == y) /* skip null conversions */
465 continue;
466 if (!tr_matrix[x][y].step) /* no path from x to y */
467 continue;
468 if (!tr_matrix[y][z].step) /* no path from y to z */
469 continue;
470 newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
471 if (tr_matrix[x][z].step && newcost >= tr_matrix[x][z].cost)
472 continue; /* x->y->z is more expensive than
473 * the existing path */
474 /* ok, we can get from x to z via y with a cost that
475 is the sum of the transition from x to y and
476 from y to z */
478 tr_matrix[x][z].step = tr_matrix[x][y].step;
479 tr_matrix[x][z].cost = newcost;
480 tr_matrix[x][z].multistep = 1;
481 if (option_debug)
482 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);
483 changed++;
487 if (!changed)
488 break;
492 /*! \brief CLI "show translation" command handler */
493 static int show_translation_deprecated(int fd, int argc, char *argv[])
495 #define SHOW_TRANS 13
496 int x, y, z;
497 int curlen = 0, longest = 0;
499 if (argc > 4)
500 return RESULT_SHOWUSAGE;
502 AST_LIST_LOCK(&translators);
504 if (argv[2] && !strcasecmp(argv[2], "recalc")) {
505 z = argv[3] ? atoi(argv[3]) : 1;
507 if (z <= 0) {
508 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
509 z = 1;
512 if (z > MAX_RECALC) {
513 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
514 z = MAX_RECALC;
516 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
517 rebuild_matrix(z);
520 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
521 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
522 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
523 for (x = 0; x < SHOW_TRANS; x++) {
524 curlen = strlen(ast_getformatname(1 << (x)));
525 if (curlen > longest)
526 longest = curlen;
528 for (x = -1; x < SHOW_TRANS; x++) {
529 char line[120];
530 char *buf = line;
531 size_t left = sizeof(line) - 1; /* one initial space */
532 /* next 2 lines run faster than using ast_build_string() */
533 *buf++ = ' ';
534 *buf = '\0';
535 for (y = -1; y < SHOW_TRANS; y++) {
536 if (y >= 0)
537 curlen = strlen(ast_getformatname(1 << (y)));
539 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
540 /* XXX 999 is a little hackish
541 We don't want this number being larger than the shortest (or current) codec
542 For now, that is "gsm" */
543 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
544 } else if (x == -1 && y >= 0) {
545 /* Top row - use a dynamic size */
546 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (y)) );
547 } else if (y == -1 && x >= 0) {
548 /* Left column - use a static size. */
549 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x)) );
550 } else if (x >= 0 && y >= 0) {
551 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
552 } else {
553 ast_build_string(&buf, &left, "%*s", longest, "");
556 ast_build_string(&buf, &left, "\n");
557 ast_cli(fd, line);
559 AST_LIST_UNLOCK(&translators);
560 return RESULT_SUCCESS;
563 static int show_translation(int fd, int argc, char *argv[])
565 int x, y, z;
566 int curlen = 0, longest = 0;
568 if (argc > 5)
569 return RESULT_SHOWUSAGE;
571 AST_LIST_LOCK(&translators);
573 if (argv[3] && !strcasecmp(argv[3], "recalc")) {
574 z = argv[4] ? atoi(argv[4]) : 1;
576 if (z <= 0) {
577 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
578 z = 1;
581 if (z > MAX_RECALC) {
582 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
583 z = MAX_RECALC;
585 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
586 rebuild_matrix(z);
589 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
590 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
591 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
592 for (x = 0; x < SHOW_TRANS; x++) {
593 curlen = strlen(ast_getformatname(1 << (x)));
594 if (curlen > longest)
595 longest = curlen;
597 for (x = -1; x < SHOW_TRANS; x++) {
598 char line[120];
599 char *buf = line;
600 size_t left = sizeof(line) - 1; /* one initial space */
601 /* next 2 lines run faster than using ast_build_string() */
602 *buf++ = ' ';
603 *buf = '\0';
604 for (y = -1; y < SHOW_TRANS; y++) {
605 if (y >= 0)
606 curlen = strlen(ast_getformatname(1 << (y)));
608 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
609 /* XXX 999 is a little hackish
610 We don't want this number being larger than the shortest (or current) codec
611 For now, that is "gsm" */
612 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
613 } else if (x == -1 && y >= 0) {
614 /* Top row - use a dynamic size */
615 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (y)) );
616 } else if (y == -1 && x >= 0) {
617 /* Left column - use a static size. */
618 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x)) );
619 } else if (x >= 0 && y >= 0) {
620 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
621 } else {
622 ast_build_string(&buf, &left, "%*s", longest, "");
625 ast_build_string(&buf, &left, "\n");
626 ast_cli(fd, line);
628 AST_LIST_UNLOCK(&translators);
629 return RESULT_SUCCESS;
632 static char show_trans_usage[] =
633 "Usage: core show translation [recalc] [<recalc seconds>]\n"
634 " Displays known codec translators and the cost associated\n"
635 "with each conversion. If the argument 'recalc' is supplied along\n"
636 "with optional number of seconds to test a new test will be performed\n"
637 "as the chart is being displayed.\n";
639 static struct ast_cli_entry cli_show_translation_deprecated = {
640 { "show", "translation", NULL },
641 show_translation_deprecated, NULL,
642 NULL };
644 static struct ast_cli_entry cli_translate[] = {
645 { { "core", "show", "translation", NULL },
646 show_translation, "Display translation matrix",
647 show_trans_usage, NULL, &cli_show_translation_deprecated },
650 /*! \brief register codec translator */
651 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
653 static int added_cli = 0;
654 struct ast_translator *u;
656 if (!mod) {
657 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
658 return -1;
661 if (!t->buf_size) {
662 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
663 return -1;
666 t->module = mod;
668 t->srcfmt = powerof(t->srcfmt);
669 t->dstfmt = powerof(t->dstfmt);
670 t->active = 1;
672 if (t->plc_samples) {
673 if (t->buffer_samples < t->plc_samples) {
674 ast_log(LOG_WARNING, "plc_samples %d buffer_samples %d\n",
675 t->plc_samples, t->buffer_samples);
676 return -1;
678 if (t->dstfmt != powerof(AST_FORMAT_SLINEAR))
679 ast_log(LOG_WARNING, "plc_samples %d format %x\n",
680 t->plc_samples, t->dstfmt);
682 if (t->srcfmt >= MAX_FORMAT) {
683 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
684 return -1;
687 if (t->dstfmt >= MAX_FORMAT) {
688 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
689 return -1;
692 if (t->buf_size) {
694 * Align buf_size properly, rounding up to the machine-specific
695 * alignment for pointers.
697 struct _test_align { void *a, *b; } p;
698 int align = (char *)&p.b - (char *)&p.a;
700 t->buf_size = ((t->buf_size + align - 1) / align) * align;
703 if (t->frameout == NULL)
704 t->frameout = default_frameout;
706 calc_cost(t, 1);
708 if (option_verbose > 1) {
709 char tmp[80];
711 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %s to %s, cost %d\n",
712 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
713 ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
716 if (!added_cli) {
717 ast_cli_register_multiple(cli_translate, sizeof(cli_translate) / sizeof(struct ast_cli_entry));
718 added_cli++;
721 AST_LIST_LOCK(&translators);
723 /* find any existing translators that provide this same srcfmt/dstfmt,
724 and put this one in order based on cost */
725 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
726 if ((u->srcfmt == t->srcfmt) &&
727 (u->dstfmt == t->dstfmt) &&
728 (u->cost > t->cost)) {
729 AST_LIST_INSERT_BEFORE_CURRENT(&translators, t, list);
730 t = NULL;
733 AST_LIST_TRAVERSE_SAFE_END;
735 /* if no existing translator was found for this format combination,
736 add it to the beginning of the list */
737 if (t)
738 AST_LIST_INSERT_HEAD(&translators, t, list);
740 rebuild_matrix(0);
742 AST_LIST_UNLOCK(&translators);
744 return 0;
747 /*! \brief unregister codec translator */
748 int ast_unregister_translator(struct ast_translator *t)
750 char tmp[80];
751 struct ast_translator *u;
752 int found = 0;
754 AST_LIST_LOCK(&translators);
755 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
756 if (u == t) {
757 AST_LIST_REMOVE_CURRENT(&translators, list);
758 if (option_verbose > 1)
759 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));
760 found = 1;
761 break;
764 AST_LIST_TRAVERSE_SAFE_END;
766 if (found)
767 rebuild_matrix(0);
769 AST_LIST_UNLOCK(&translators);
771 return (u ? 0 : -1);
774 void ast_translator_activate(struct ast_translator *t)
776 AST_LIST_LOCK(&translators);
777 t->active = 1;
778 rebuild_matrix(0);
779 AST_LIST_UNLOCK(&translators);
782 void ast_translator_deactivate(struct ast_translator *t)
784 AST_LIST_LOCK(&translators);
785 t->active = 0;
786 rebuild_matrix(0);
787 AST_LIST_UNLOCK(&translators);
790 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
791 int ast_translator_best_choice(int *dst, int *srcs)
793 int x,y;
794 int best = -1;
795 int bestdst = 0;
796 int cur, cursrc;
797 int besttime = INT_MAX;
798 int beststeps = INT_MAX;
799 int common = ((*dst) & (*srcs)) & AST_FORMAT_AUDIO_MASK; /* are there common formats ? */
801 if (common) { /* yes, pick one and return */
802 for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
803 if (cur & common) /* guaranteed to find one */
804 break;
806 /* We are done, this is a common format to both. */
807 *srcs = *dst = cur;
808 return 0;
809 } else { /* No, we will need to translate */
810 AST_LIST_LOCK(&translators);
811 for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
812 if (! (cur & *dst))
813 continue;
814 for (cursrc = 1, x = 0; x <= MAX_AUDIO_FORMAT; cursrc <<= 1, x++) {
815 if (!(*srcs & cursrc) || !tr_matrix[x][y].step ||
816 tr_matrix[x][y].cost > besttime)
817 continue; /* not existing or no better */
818 if (tr_matrix[x][y].cost < besttime ||
819 tr_matrix[x][y].multistep < beststeps) {
820 /* better than what we have so far */
821 best = cursrc;
822 bestdst = cur;
823 besttime = tr_matrix[x][y].cost;
824 beststeps = tr_matrix[x][y].multistep;
828 AST_LIST_UNLOCK(&translators);
829 if (best > -1) {
830 *srcs = best;
831 *dst = bestdst;
832 best = 0;
834 return best;
838 unsigned int ast_translate_path_steps(unsigned int dest, unsigned int src)
840 unsigned int res = -1;
842 /* convert bitwise format numbers into array indices */
843 src = powerof(src);
844 dest = powerof(dest);
846 AST_LIST_LOCK(&translators);
848 if (tr_matrix[src][dest].step)
849 res = tr_matrix[src][dest].multistep + 1;
851 AST_LIST_UNLOCK(&translators);
853 return res;
856 unsigned int ast_translate_available_formats(unsigned int dest, unsigned int src)
858 unsigned int res = dest;
859 unsigned int x;
860 unsigned int src_audio = src & AST_FORMAT_AUDIO_MASK;
861 unsigned int src_video = src & AST_FORMAT_VIDEO_MASK;
863 /* if we don't have a source format, we just have to try all
864 possible destination formats */
865 if (!src)
866 return dest;
868 /* If we have a source audio format, get its format index */
869 if (src_audio)
870 src_audio = powerof(src_audio);
872 /* If we have a source video format, get its format index */
873 if (src_video)
874 src_video = powerof(src_video);
876 AST_LIST_LOCK(&translators);
878 /* For a given source audio format, traverse the list of
879 known audio formats to determine whether there exists
880 a translation path from the source format to the
881 destination format. */
882 for (x = 1; src_audio && x < AST_FORMAT_MAX_AUDIO; x <<= 1) {
883 /* if this is not a desired format, nothing to do */
884 if (!dest & x)
885 continue;
887 /* if the source is supplying this format, then
888 we can leave it in the result */
889 if (src & x)
890 continue;
892 /* if we don't have a translation path from the src
893 to this format, remove it from the result */
894 if (!tr_matrix[src_audio][powerof(x)].step) {
895 res &= ~x;
896 continue;
899 /* now check the opposite direction */
900 if (!tr_matrix[powerof(x)][src_audio].step)
901 res &= ~x;
904 /* For a given source video format, traverse the list of
905 known video formats to determine whether there exists
906 a translation path from the source format to the
907 destination format. */
908 for (; src_video && x < AST_FORMAT_MAX_VIDEO; x <<= 1) {
909 /* if this is not a desired format, nothing to do */
910 if (!dest & x)
911 continue;
913 /* if the source is supplying this format, then
914 we can leave it in the result */
915 if (src & x)
916 continue;
918 /* if we don't have a translation path from the src
919 to this format, remove it from the result */
920 if (!tr_matrix[src_video][powerof(x)].step) {
921 res &= ~x;
922 continue;
925 /* now check the opposite direction */
926 if (!tr_matrix[powerof(x)][src_video].step)
927 res &= ~x;
930 AST_LIST_UNLOCK(&translators);
932 return res;