add passthrough and file format support for G.722 16KHz audio (issue #5084, original...
[asterisk-bristuff.git] / main / translate.c
blob1e9c1e77bc9fb63741f92e242775f673a4be819d
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;
176 return 0;
178 if (pvt->samples + f->samples > pvt->t->buffer_samples) {
179 ast_log(LOG_WARNING, "Out of buffer space\n");
180 return -1;
183 /* we require a framein routine, wouldn't know how to do
184 * it otherwise.
186 ret = pvt->t->framein(pvt, f);
187 /* possibly store data for plc */
188 if (!ret && pvt->plc) {
189 int l = pvt->t->plc_samples;
190 if (pvt->samples < l)
191 l = pvt->samples;
192 plc_rx(pvt->plc, dst + pvt->samples - l, l);
194 /* diagnostic ... */
195 if (pvt->samples == samples)
196 ast_log(LOG_WARNING, "%s did not update samples %d\n",
197 pvt->t->name, pvt->samples);
198 return ret;
201 /*! \brief generic frameout routine.
202 * If samples and datalen are 0, take whatever is in pvt
203 * and reset them, otherwise take the values in the caller and
204 * leave alone the pvt values.
206 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
207 int datalen, int samples)
209 struct ast_frame *f = &pvt->f;
211 if (samples)
212 f->samples = samples;
213 else {
214 if (pvt->samples == 0)
215 return NULL;
216 f->samples = pvt->samples;
217 pvt->samples = 0;
219 if (datalen)
220 f->datalen = datalen;
221 else {
222 f->datalen = pvt->datalen;
223 pvt->datalen = 0;
226 f->frametype = AST_FRAME_VOICE;
227 f->subclass = 1 << (pvt->t->dstfmt);
228 f->mallocd = 0;
229 f->offset = AST_FRIENDLY_OFFSET;
230 f->src = pvt->t->name;
231 f->data = pvt->outbuf;
232 return f;
235 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
237 return ast_trans_frameout(pvt, 0, 0);
240 /* end of callback wrappers and helpers */
242 void ast_translator_free_path(struct ast_trans_pvt *p)
244 struct ast_trans_pvt *pn = p;
245 while ( (p = pn) ) {
246 pn = p->next;
247 destroy(p);
251 /*! \brief Build a chain of translators based upon the given source and dest formats */
252 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
254 struct ast_trans_pvt *head = NULL, *tail = NULL;
256 source = powerof(source);
257 dest = powerof(dest);
259 AST_LIST_LOCK(&translators);
261 while (source != dest) {
262 struct ast_trans_pvt *cur;
263 struct ast_translator *t = tr_matrix[source][dest].step;
264 if (!t) {
265 ast_log(LOG_WARNING, "No translator path from %s to %s\n",
266 ast_getformatname(source), ast_getformatname(dest));
267 AST_LIST_UNLOCK(&translators);
268 return NULL;
270 if (!(cur = newpvt(t))) {
271 ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
272 if (head)
273 ast_translator_free_path(head);
274 AST_LIST_UNLOCK(&translators);
275 return NULL;
277 if (!head)
278 head = cur;
279 else
280 tail->next = cur;
281 tail = cur;
282 cur->nextin = cur->nextout = ast_tv(0, 0);
283 /* Keep going if this isn't the final destination */
284 source = cur->t->dstfmt;
287 AST_LIST_UNLOCK(&translators);
288 return head;
291 /*! \brief do the actual translation */
292 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
294 struct ast_trans_pvt *p = path;
295 struct ast_frame *out = f;
296 struct timeval delivery;
297 int has_timing_info;
298 long ts;
299 long len;
300 int seqno;
302 has_timing_info = f->has_timing_info;
303 ts = f->ts;
304 len = f->len;
305 seqno = f->seqno;
307 /* XXX hmmm... check this below */
308 if (!ast_tvzero(f->delivery)) {
309 if (!ast_tvzero(path->nextin)) {
310 /* Make sure this is in line with what we were expecting */
311 if (!ast_tveq(path->nextin, f->delivery)) {
312 /* The time has changed between what we expected and this
313 most recent time on the new packet. If we have a
314 valid prediction adjust our output time appropriately */
315 if (!ast_tvzero(path->nextout)) {
316 path->nextout = ast_tvadd(path->nextout,
317 ast_tvsub(f->delivery, path->nextin));
319 path->nextin = f->delivery;
321 } else {
322 /* This is our first pass. Make sure the timing looks good */
323 path->nextin = f->delivery;
324 path->nextout = f->delivery;
326 /* Predict next incoming sample */
327 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, 8000));
329 delivery = f->delivery;
330 for ( ; out && p ; p = p->next) {
331 framein(p, out);
332 out = p->t->frameout(p);
334 if (consume)
335 ast_frfree(f);
336 if (out == NULL)
337 return NULL;
338 /* we have a frame, play with times */
339 if (!ast_tvzero(delivery)) {
340 /* Regenerate prediction after a discontinuity */
341 if (ast_tvzero(path->nextout))
342 path->nextout = ast_tvnow();
344 /* Use next predicted outgoing timestamp */
345 out->delivery = path->nextout;
347 /* Predict next outgoing timestamp from samples in this
348 frame. */
349 path->nextout = ast_tvadd(path->nextout, ast_samp2tv( out->samples, 8000));
350 } else {
351 out->delivery = ast_tv(0, 0);
352 out->has_timing_info = has_timing_info;
353 if (has_timing_info) {
354 out->ts = ts;
355 out->len = len;
356 out->seqno = seqno;
359 /* Invalidate prediction if we're entering a silence period */
360 if (out->frametype == AST_FRAME_CNG)
361 path->nextout = ast_tv(0, 0);
362 return out;
365 /*! \brief compute the cost of a single translation step */
366 static void calc_cost(struct ast_translator *t, int seconds)
368 int sofar=0;
369 struct ast_trans_pvt *pvt;
370 struct timeval start;
371 int cost;
373 if (!seconds)
374 seconds = 1;
376 /* If they don't make samples, give them a terrible score */
377 if (!t->sample) {
378 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
379 t->cost = 99999;
380 return;
382 pvt = newpvt(t);
383 if (!pvt) {
384 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
385 t->cost = 99999;
386 return;
388 start = ast_tvnow();
389 /* Call the encoder until we've processed the required number of samples */
390 while (sofar < seconds * 8000) {
391 struct ast_frame *f = t->sample();
392 if (!f) {
393 ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
394 destroy(pvt);
395 t->cost = 99999;
396 return;
398 framein(pvt, f);
399 ast_frfree(f);
400 while ((f = t->frameout(pvt))) {
401 sofar += f->samples;
402 ast_frfree(f);
405 cost = ast_tvdiff_ms(ast_tvnow(), start);
406 destroy(pvt);
407 t->cost = cost / seconds;
408 if (!t->cost)
409 t->cost = 1;
413 * \brief rebuild a translation matrix.
414 * \note This function expects the list of translators to be locked
416 static void rebuild_matrix(int samples)
418 struct ast_translator *t;
419 int x; /* source format index */
420 int y; /* intermediate format index */
421 int z; /* destination format index */
423 if (option_debug)
424 ast_log(LOG_DEBUG, "Resetting translation matrix\n");
426 bzero(tr_matrix, sizeof(tr_matrix));
428 /* first, compute all direct costs */
429 AST_LIST_TRAVERSE(&translators, t, list) {
430 x = t->srcfmt;
431 z = t->dstfmt;
433 if (samples)
434 calc_cost(t, samples);
436 if (!tr_matrix[x][z].step || t->cost < tr_matrix[x][z].cost) {
437 tr_matrix[x][z].step = t;
438 tr_matrix[x][z].cost = t->cost;
443 * For each triple x, y, z of distinct formats, check if there is
444 * a path from x to z through y which is cheaper than what is
445 * currently known, and in case, update the matrix.
446 * Repeat until the matrix is stable.
448 for (;;) {
449 int changed = 0;
450 for (x = 0; x < MAX_FORMAT; x++) { /* source format */
451 for (y=0; y < MAX_FORMAT; y++) { /* intermediate format */
452 if (x == y) /* skip ourselves */
453 continue;
455 for (z=0; z<MAX_FORMAT; z++) { /* dst format */
456 int newcost;
458 if (z == x || z == y) /* skip null conversions */
459 continue;
460 if (!tr_matrix[x][y].step) /* no path from x to y */
461 continue;
462 if (!tr_matrix[y][z].step) /* no path from y to z */
463 continue;
464 newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
465 if (tr_matrix[x][z].step && newcost >= tr_matrix[x][z].cost)
466 continue; /* x->y->z is more expensive than
467 * the existing path */
468 /* ok, we can get from x to z via y with a cost that
469 is the sum of the transition from x to y and
470 from y to z */
472 tr_matrix[x][z].step = tr_matrix[x][y].step;
473 tr_matrix[x][z].cost = newcost;
474 tr_matrix[x][z].multistep = 1;
475 if (option_debug)
476 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);
477 changed++;
481 if (!changed)
482 break;
486 /*! \brief CLI "show translation" command handler */
487 static int show_translation_deprecated(int fd, int argc, char *argv[])
489 #define SHOW_TRANS 13
490 int x, y, z;
491 int curlen = 0, longest = 0;
493 if (argc > 4)
494 return RESULT_SHOWUSAGE;
496 AST_LIST_LOCK(&translators);
498 if (argv[2] && !strcasecmp(argv[2], "recalc")) {
499 z = argv[3] ? atoi(argv[3]) : 1;
501 if (z <= 0) {
502 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
503 z = 1;
506 if (z > MAX_RECALC) {
507 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
508 z = MAX_RECALC;
510 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
511 rebuild_matrix(z);
514 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
515 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
516 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
517 for (x = 0; x < SHOW_TRANS; x++) {
518 curlen = strlen(ast_getformatname(1 << (x + 1)));
519 if (curlen > longest)
520 longest = curlen;
522 for (x = -1; x < SHOW_TRANS; x++) {
523 char line[80];
524 char *buf = line;
525 size_t left = sizeof(line) - 1; /* one initial space */
526 /* next 2 lines run faster than using ast_build_string() */
527 *buf++ = ' ';
528 *buf = '\0';
529 for (y = -1; y < SHOW_TRANS; y++) {
530 curlen = strlen(ast_getformatname(1 << (y)));
532 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
533 /* XXX 999 is a little hackish
534 We don't want this number being larger than the shortest (or current) codec
535 For now, that is "gsm" */
536 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
537 } else if (x == -1 && y >= 0) {
538 /* Top row - use a dynamic size */
539 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (x + y + 1)) );
540 } else if (y == -1 && x >= 0) {
541 /* Left column - use a static size. */
542 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x + y + 1)) );
543 } else if (x >= 0 && y >= 0) {
544 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
545 } else {
546 ast_build_string(&buf, &left, "%*s", longest, "");
549 ast_build_string(&buf, &left, "\n");
550 ast_cli(fd, line);
552 AST_LIST_UNLOCK(&translators);
553 return RESULT_SUCCESS;
556 static int show_translation(int fd, int argc, char *argv[])
558 int x, y, z;
559 int curlen = 0, longest = 0;
561 if (argc > 5)
562 return RESULT_SHOWUSAGE;
564 AST_LIST_LOCK(&translators);
566 if (argv[3] && !strcasecmp(argv[3], "recalc")) {
567 z = argv[4] ? atoi(argv[4]) : 1;
569 if (z <= 0) {
570 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
571 z = 1;
574 if (z > MAX_RECALC) {
575 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
576 z = MAX_RECALC;
578 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
579 rebuild_matrix(z);
582 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
583 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
584 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
585 for (x = 0; x < SHOW_TRANS; x++) {
586 curlen = strlen(ast_getformatname(1 << (x + 1)));
587 if (curlen > longest)
588 longest = curlen;
590 for (x = -1; x < SHOW_TRANS; x++) {
591 char line[80];
592 char *buf = line;
593 size_t left = sizeof(line) - 1; /* one initial space */
594 /* next 2 lines run faster than using ast_build_string() */
595 *buf++ = ' ';
596 *buf = '\0';
597 for (y = -1; y < SHOW_TRANS; y++) {
598 curlen = strlen(ast_getformatname(1 << (y)));
600 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
601 /* XXX 999 is a little hackish
602 We don't want this number being larger than the shortest (or current) codec
603 For now, that is "gsm" */
604 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
605 } else if (x == -1 && y >= 0) {
606 /* Top row - use a dynamic size */
607 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (x + y + 1)) );
608 } else if (y == -1 && x >= 0) {
609 /* Left column - use a static size. */
610 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x + y + 1)) );
611 } else if (x >= 0 && y >= 0) {
612 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
613 } else {
614 ast_build_string(&buf, &left, "%*s", longest, "");
617 ast_build_string(&buf, &left, "\n");
618 ast_cli(fd, line);
620 AST_LIST_UNLOCK(&translators);
621 return RESULT_SUCCESS;
624 static char show_trans_usage[] =
625 "Usage: core show translation [recalc] [<recalc seconds>]\n"
626 " Displays known codec translators and the cost associated\n"
627 "with each conversion. If the argument 'recalc' is supplied along\n"
628 "with optional number of seconds to test a new test will be performed\n"
629 "as the chart is being displayed.\n";
631 static struct ast_cli_entry cli_show_translation_deprecated = {
632 { "show", "translation", NULL },
633 show_translation_deprecated, NULL,
634 NULL };
636 static struct ast_cli_entry cli_translate[] = {
637 { { "core", "show", "translation", NULL },
638 show_translation, "Display translation matrix",
639 show_trans_usage, NULL, &cli_show_translation_deprecated },
642 /*! \brief register codec translator */
643 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
645 static int added_cli = 0;
646 struct ast_translator *u;
648 if (!mod) {
649 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
650 return -1;
653 if (!t->buf_size) {
654 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
655 return -1;
658 t->module = mod;
659 if (t->plc_samples) {
660 if (t->buffer_samples < t->plc_samples) {
661 ast_log(LOG_WARNING, "plc_samples %d buffer_samples %d\n",
662 t->plc_samples, t->buffer_samples);
663 return -1;
665 if (t->dstfmt != AST_FORMAT_SLINEAR)
666 ast_log(LOG_WARNING, "plc_samples %d format %x\n",
667 t->plc_samples, t->dstfmt);
669 t->srcfmt = powerof(t->srcfmt);
670 t->dstfmt = powerof(t->dstfmt);
671 /* XXX maybe check that it is not existing yet ? */
672 if (t->srcfmt >= MAX_FORMAT) {
673 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
674 return -1;
676 if (t->dstfmt >= MAX_FORMAT) {
677 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
678 return -1;
680 if (t->buf_size) {
682 * Align buf_size properly, rounding up to the machine-specific
683 * alignment for pointers.
685 struct _test_align { void *a, *b; } p;
686 int align = (char *)&p.b - (char *)&p.a;
687 t->buf_size = ((t->buf_size + align - 1) / align) * align;
689 if (t->frameout == NULL)
690 t->frameout = default_frameout;
692 calc_cost(t, 1);
693 if (option_verbose > 1) {
694 char tmp[80];
695 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %s to %s, cost %d\n",
696 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
697 ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
699 AST_LIST_LOCK(&translators);
700 if (!added_cli) {
701 ast_cli_register_multiple(cli_translate, sizeof(cli_translate) / sizeof(struct ast_cli_entry));
702 added_cli++;
705 /* find any existing translators that provide this same srcfmt/dstfmt,
706 and put this one in order based on cost */
707 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
708 if ((u->srcfmt == t->srcfmt) &&
709 (u->dstfmt == t->dstfmt) &&
710 (u->cost > t->cost)) {
711 AST_LIST_INSERT_BEFORE_CURRENT(&translators, t, list);
712 t = NULL;
715 AST_LIST_TRAVERSE_SAFE_END;
717 /* if no existing translator was found for this format combination,
718 add it to the beginning of the list */
719 if (t)
720 AST_LIST_INSERT_HEAD(&translators, t, list);
722 rebuild_matrix(0);
723 AST_LIST_UNLOCK(&translators);
724 return 0;
727 /*! \brief unregister codec translator */
728 int ast_unregister_translator(struct ast_translator *t)
730 char tmp[80];
731 struct ast_translator *u;
732 AST_LIST_LOCK(&translators);
733 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
734 if (u == t) {
735 AST_LIST_REMOVE_CURRENT(&translators, list);
736 if (option_verbose > 1)
737 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));
738 break;
741 AST_LIST_TRAVERSE_SAFE_END;
742 rebuild_matrix(0);
743 AST_LIST_UNLOCK(&translators);
744 return (u ? 0 : -1);
747 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
748 int ast_translator_best_choice(int *dst, int *srcs)
750 int x,y;
751 int best = -1;
752 int bestdst = 0;
753 int cur, cursrc;
754 int besttime = INT_MAX;
755 int beststeps = INT_MAX;
756 int common = (*dst) & (*srcs); /* are there common formats ? */
758 if (common) { /* yes, pick one and return */
759 for (cur = 1, y = 0; y < MAX_FORMAT; cur <<= 1, y++) {
760 if (cur & common) /* guaranteed to find one */
761 break;
763 /* We are done, this is a common format to both. */
764 *srcs = *dst = cur;
765 return 0;
766 } else { /* No, we will need to translate */
767 AST_LIST_LOCK(&translators);
768 for (cur = 1, y = 0; y < MAX_FORMAT; cur <<= 1, y++) {
769 if (! (cur & *dst))
770 continue;
771 for (cursrc = 1, x = 0; x < MAX_FORMAT; cursrc <<= 1, x++) {
772 if (!(*srcs & cursrc) || !tr_matrix[x][y].step ||
773 tr_matrix[x][y].cost > besttime)
774 continue; /* not existing or no better */
775 if (tr_matrix[x][y].cost < besttime ||
776 tr_matrix[x][y].multistep < beststeps) {
777 /* better than what we have so far */
778 best = cursrc;
779 bestdst = cur;
780 besttime = tr_matrix[x][y].cost;
781 beststeps = tr_matrix[x][y].multistep;
785 AST_LIST_UNLOCK(&translators);
786 if (best > -1) {
787 *srcs = best;
788 *dst = bestdst;
789 best = 0;
791 return best;
795 unsigned int ast_translate_path_steps(unsigned int dest, unsigned int src)
797 unsigned int res = -1;
799 /* convert bitwise format numbers into array indices */
800 src = powerof(src);
801 dest = powerof(dest);
803 AST_LIST_LOCK(&translators);
805 if (tr_matrix[src][dest].step)
806 res = tr_matrix[src][dest].multistep + 1;
808 AST_LIST_UNLOCK(&translators);
810 return res;
813 unsigned int ast_translate_available_formats(unsigned int dest, unsigned int src)
815 unsigned int res = dest;
816 unsigned int x;
817 unsigned int src_audio = powerof(src & AST_FORMAT_AUDIO_MASK);
818 unsigned int src_video = powerof(src & AST_FORMAT_VIDEO_MASK);
820 /* if we don't have a source format, we just have to try all
821 possible destination formats */
822 if (!src)
823 return dest;
825 AST_LIST_LOCK(&translators);
827 for (x = 1; x < AST_FORMAT_MAX_AUDIO; x <<= 1) {
828 /* if this is not a desired format, nothing to do */
829 if (!dest & x)
830 continue;
832 /* if the source is supplying this format, then
833 we can leave it in the result */
834 if (src & x)
835 continue;
837 /* if we don't have a translation path from the src
838 to this format, remove it from the result */
839 if (!tr_matrix[src_audio][powerof(x)].step)
840 res &= ~x;
843 /* roll over into video formats */
844 for (; x < AST_FORMAT_MAX_VIDEO; x <<= 1) {
845 /* if this is not a desired format, nothing to do */
846 if (!dest & x)
847 continue;
849 /* if the source is supplying this format, then
850 we can leave it in the result */
851 if (src & x)
852 continue;
854 /* if we don't have a translation path from the src
855 to this format, remove it from the result */
856 if (!tr_matrix[src_video][powerof(x)].step)
857 res &= ~x;
860 AST_LIST_UNLOCK(&translators);
862 return res;