Let's also include aclocal.m4
[asterisk-bristuff.git] / main / translate.c
blobdeb977954b22c724d6a5f6733eb00f5825115de3
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 (ast_test_flag(&pvt->f, AST_FRFLAG_FROM_TRANSLATOR)) {
144 /* If this flag is still set, that means that the translation path has
145 * been torn down, while we still have a frame out there being used.
146 * When ast_frfree() gets called on that frame, this ast_trans_pvt
147 * will get destroyed, too. */
149 /* Set the magic hint that this has been requested to be destroyed. */
150 pvt->datalen = -1;
152 return;
155 if (t->destroy)
156 t->destroy(pvt);
157 free(pvt);
158 ast_module_unref(t->module);
161 /*! \brief framein wrapper, deals with plc and bound checks. */
162 static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
164 int16_t *dst = (int16_t *)pvt->outbuf;
165 int ret;
166 int samples = pvt->samples; /* initial value */
168 /* Copy the last in jb timing info to the pvt */
169 ast_copy_flags(&pvt->f, f, AST_FRFLAG_HAS_TIMING_INFO);
170 pvt->f.ts = f->ts;
171 pvt->f.len = f->len;
172 pvt->f.seqno = f->seqno;
174 if (f->samples == 0) {
175 ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
177 if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
178 if (f->datalen == 0) { /* perform PLC with nominal framesize of 20ms/160 samples */
179 if (pvt->plc) {
180 int l = pvt->t->plc_samples;
181 if (pvt->samples + l > pvt->t->buffer_samples) {
182 ast_log(LOG_WARNING, "Out of buffer space\n");
183 return -1;
185 l = plc_fillin(pvt->plc, dst + pvt->samples, l);
186 pvt->samples += l;
187 pvt->datalen = pvt->samples * 2; /* SLIN has 2bytes for 1sample */
189 /* We don't want generic PLC. If the codec has native PLC, then do that */
190 if (!pvt->t->native_plc)
191 return 0;
193 if (pvt->samples + f->samples > pvt->t->buffer_samples) {
194 ast_log(LOG_WARNING, "Out of buffer space\n");
195 return -1;
198 /* we require a framein routine, wouldn't know how to do
199 * it otherwise.
201 ret = pvt->t->framein(pvt, f);
202 /* possibly store data for plc */
203 if (!ret && pvt->plc) {
204 int l = pvt->t->plc_samples;
205 if (pvt->samples < l)
206 l = pvt->samples;
207 plc_rx(pvt->plc, dst + pvt->samples - l, l);
209 /* diagnostic ... */
210 if (pvt->samples == samples)
211 ast_log(LOG_WARNING, "%s did not update samples %d\n",
212 pvt->t->name, pvt->samples);
213 return ret;
216 /*! \brief generic frameout routine.
217 * If samples and datalen are 0, take whatever is in pvt
218 * and reset them, otherwise take the values in the caller and
219 * leave alone the pvt values.
221 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
222 int datalen, int samples)
224 struct ast_frame *f = &pvt->f;
226 if (samples)
227 f->samples = samples;
228 else {
229 if (pvt->samples == 0)
230 return NULL;
231 f->samples = pvt->samples;
232 pvt->samples = 0;
234 if (datalen)
235 f->datalen = datalen;
236 else {
237 f->datalen = pvt->datalen;
238 pvt->datalen = 0;
241 f->frametype = AST_FRAME_VOICE;
242 f->subclass = 1 << (pvt->t->dstfmt);
243 f->mallocd = 0;
244 f->offset = AST_FRIENDLY_OFFSET;
245 f->src = pvt->t->name;
246 f->data = pvt->outbuf;
248 ast_set_flag(f, AST_FRFLAG_FROM_TRANSLATOR);
250 return f;
253 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
255 return ast_trans_frameout(pvt, 0, 0);
258 /* end of callback wrappers and helpers */
260 void ast_translator_free_path(struct ast_trans_pvt *p)
262 struct ast_trans_pvt *pn = p;
263 while ( (p = pn) ) {
264 pn = p->next;
265 destroy(p);
269 /*! \brief Build a chain of translators based upon the given source and dest formats */
270 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
272 struct ast_trans_pvt *head = NULL, *tail = NULL;
274 source = powerof(source);
275 dest = powerof(dest);
277 if (source == -1 || dest == -1) {
278 ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", source == -1 ? "starting" : "ending");
279 return NULL;
282 AST_LIST_LOCK(&translators);
284 while (source != dest) {
285 struct ast_trans_pvt *cur;
286 struct ast_translator *t = tr_matrix[source][dest].step;
287 if (!t) {
288 ast_log(LOG_WARNING, "No translator path from %s to %s\n",
289 ast_getformatname(source), ast_getformatname(dest));
290 AST_LIST_UNLOCK(&translators);
291 return NULL;
293 if (!(cur = newpvt(t))) {
294 ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
295 if (head)
296 ast_translator_free_path(head);
297 AST_LIST_UNLOCK(&translators);
298 return NULL;
300 if (!head)
301 head = cur;
302 else
303 tail->next = cur;
304 tail = cur;
305 cur->nextin = cur->nextout = ast_tv(0, 0);
306 /* Keep going if this isn't the final destination */
307 source = cur->t->dstfmt;
310 AST_LIST_UNLOCK(&translators);
311 return head;
314 /*! \brief do the actual translation */
315 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
317 struct ast_trans_pvt *p = path;
318 struct ast_frame *out = f;
319 struct timeval delivery;
320 int has_timing_info;
321 long ts;
322 long len;
323 int seqno;
325 has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
326 ts = f->ts;
327 len = f->len;
328 seqno = f->seqno;
330 /* XXX hmmm... check this below */
331 if (!ast_tvzero(f->delivery)) {
332 if (!ast_tvzero(path->nextin)) {
333 /* Make sure this is in line with what we were expecting */
334 if (!ast_tveq(path->nextin, f->delivery)) {
335 /* The time has changed between what we expected and this
336 most recent time on the new packet. If we have a
337 valid prediction adjust our output time appropriately */
338 if (!ast_tvzero(path->nextout)) {
339 path->nextout = ast_tvadd(path->nextout,
340 ast_tvsub(f->delivery, path->nextin));
342 path->nextin = f->delivery;
344 } else {
345 /* This is our first pass. Make sure the timing looks good */
346 path->nextin = f->delivery;
347 path->nextout = f->delivery;
349 /* Predict next incoming sample */
350 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, ast_format_rate(f->subclass)));
352 delivery = f->delivery;
353 for ( ; out && p ; p = p->next) {
354 framein(p, out);
355 if (out != f)
356 ast_frfree(out);
357 out = p->t->frameout(p);
359 if (consume)
360 ast_frfree(f);
361 if (out == NULL)
362 return NULL;
363 /* we have a frame, play with times */
364 if (!ast_tvzero(delivery)) {
365 /* Regenerate prediction after a discontinuity */
366 if (ast_tvzero(path->nextout))
367 path->nextout = ast_tvnow();
369 /* Use next predicted outgoing timestamp */
370 out->delivery = path->nextout;
372 /* Predict next outgoing timestamp from samples in this
373 frame. */
374 path->nextout = ast_tvadd(path->nextout, ast_samp2tv(out->samples, ast_format_rate(out->subclass)));
375 } else {
376 out->delivery = ast_tv(0, 0);
377 ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
378 if (has_timing_info) {
379 out->ts = ts;
380 out->len = len;
381 out->seqno = seqno;
384 /* Invalidate prediction if we're entering a silence period */
385 if (out->frametype == AST_FRAME_CNG)
386 path->nextout = ast_tv(0, 0);
387 return out;
390 /*! \brief compute the cost of a single translation step */
391 static void calc_cost(struct ast_translator *t, int seconds)
393 int num_samples = 0;
394 struct ast_trans_pvt *pvt;
395 struct timeval start;
396 int cost;
397 int out_rate = ast_format_rate(t->dstfmt);
399 if (!seconds)
400 seconds = 1;
402 /* If they don't make samples, give them a terrible score */
403 if (!t->sample) {
404 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
405 t->cost = 99999;
406 return;
409 pvt = newpvt(t);
410 if (!pvt) {
411 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
412 t->cost = 99999;
413 return;
416 start = ast_tvnow();
418 /* Call the encoder until we've processed the required number of samples */
419 while (num_samples < seconds * out_rate) {
420 struct ast_frame *f = t->sample();
421 if (!f) {
422 ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
423 destroy(pvt);
424 t->cost = 99999;
425 return;
427 framein(pvt, f);
428 ast_frfree(f);
429 while ((f = t->frameout(pvt))) {
430 num_samples += f->samples;
431 ast_frfree(f);
435 cost = ast_tvdiff_ms(ast_tvnow(), start);
437 destroy(pvt);
439 t->cost = cost / seconds;
441 if (!t->cost)
442 t->cost = 1;
446 * \brief rebuild a translation matrix.
447 * \note This function expects the list of translators to be locked
449 static void rebuild_matrix(int samples)
451 struct ast_translator *t;
452 int x; /* source format index */
453 int y; /* intermediate format index */
454 int z; /* destination format index */
456 if (option_debug)
457 ast_log(LOG_DEBUG, "Resetting translation matrix\n");
459 bzero(tr_matrix, sizeof(tr_matrix));
461 /* first, compute all direct costs */
462 AST_LIST_TRAVERSE(&translators, t, list) {
463 if (!t->active)
464 continue;
466 x = t->srcfmt;
467 z = t->dstfmt;
469 if (samples)
470 calc_cost(t, samples);
472 if (!tr_matrix[x][z].step || t->cost < tr_matrix[x][z].cost) {
473 tr_matrix[x][z].step = t;
474 tr_matrix[x][z].cost = t->cost;
479 * For each triple x, y, z of distinct formats, check if there is
480 * a path from x to z through y which is cheaper than what is
481 * currently known, and in case, update the matrix.
482 * Repeat until the matrix is stable.
484 for (;;) {
485 int changed = 0;
486 for (x = 0; x < MAX_FORMAT; x++) { /* source format */
487 for (y=0; y < MAX_FORMAT; y++) { /* intermediate format */
488 if (x == y) /* skip ourselves */
489 continue;
491 for (z=0; z<MAX_FORMAT; z++) { /* dst format */
492 int newcost;
494 if (z == x || z == y) /* skip null conversions */
495 continue;
496 if (!tr_matrix[x][y].step) /* no path from x to y */
497 continue;
498 if (!tr_matrix[y][z].step) /* no path from y to z */
499 continue;
500 newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
501 if (tr_matrix[x][z].step && newcost >= tr_matrix[x][z].cost)
502 continue; /* x->y->z is more expensive than
503 * the existing path */
504 /* ok, we can get from x to z via y with a cost that
505 is the sum of the transition from x to y and
506 from y to z */
508 tr_matrix[x][z].step = tr_matrix[x][y].step;
509 tr_matrix[x][z].cost = newcost;
510 tr_matrix[x][z].multistep = 1;
511 if (option_debug)
512 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);
513 changed++;
517 if (!changed)
518 break;
522 /*! \brief CLI "show translation" command handler */
523 static int show_translation_deprecated(int fd, int argc, char *argv[])
525 #define SHOW_TRANS 13
526 int x, y, z;
527 int curlen = 0, longest = 0;
529 if (argc > 4)
530 return RESULT_SHOWUSAGE;
532 AST_LIST_LOCK(&translators);
534 if (argv[2] && !strcasecmp(argv[2], "recalc")) {
535 z = argv[3] ? atoi(argv[3]) : 1;
537 if (z <= 0) {
538 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
539 z = 1;
542 if (z > MAX_RECALC) {
543 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
544 z = MAX_RECALC;
546 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
547 rebuild_matrix(z);
550 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
551 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
552 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
553 for (x = 0; x < SHOW_TRANS; x++) {
554 curlen = strlen(ast_getformatname(1 << (x)));
555 if (curlen > longest)
556 longest = curlen;
558 for (x = -1; x < SHOW_TRANS; x++) {
559 char line[120];
560 char *buf = line;
561 size_t left = sizeof(line) - 1; /* one initial space */
562 /* next 2 lines run faster than using ast_build_string() */
563 *buf++ = ' ';
564 *buf = '\0';
565 for (y = -1; y < SHOW_TRANS; y++) {
566 if (y >= 0)
567 curlen = strlen(ast_getformatname(1 << (y)));
569 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
570 /* XXX 999 is a little hackish
571 We don't want this number being larger than the shortest (or current) codec
572 For now, that is "gsm" */
573 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
574 } else if (x == -1 && y >= 0) {
575 /* Top row - use a dynamic size */
576 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (y)) );
577 } else if (y == -1 && x >= 0) {
578 /* Left column - use a static size. */
579 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x)) );
580 } else if (x >= 0 && y >= 0) {
581 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
582 } else {
583 ast_build_string(&buf, &left, "%*s", longest, "");
586 ast_build_string(&buf, &left, "\n");
587 ast_cli(fd, line);
589 AST_LIST_UNLOCK(&translators);
590 return RESULT_SUCCESS;
593 static int show_translation(int fd, int argc, char *argv[])
595 int x, y, z;
596 int curlen = 0, longest = 0;
598 if (argc > 5)
599 return RESULT_SHOWUSAGE;
601 AST_LIST_LOCK(&translators);
603 if (argv[3] && !strcasecmp(argv[3], "recalc")) {
604 z = argv[4] ? atoi(argv[4]) : 1;
606 if (z <= 0) {
607 ast_cli(fd, " C'mon let's be serious here... defaulting to 1.\n");
608 z = 1;
611 if (z > MAX_RECALC) {
612 ast_cli(fd, " Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
613 z = MAX_RECALC;
615 ast_cli(fd, " Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
616 rebuild_matrix(z);
619 ast_cli(fd, " Translation times between formats (in milliseconds) for one second of data\n");
620 ast_cli(fd, " Source Format (Rows) Destination Format (Columns)\n\n");
621 /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
622 for (x = 0; x < SHOW_TRANS; x++) {
623 curlen = strlen(ast_getformatname(1 << (x)));
624 if (curlen > longest)
625 longest = curlen;
627 for (x = -1; x < SHOW_TRANS; x++) {
628 char line[120];
629 char *buf = line;
630 size_t left = sizeof(line) - 1; /* one initial space */
631 /* next 2 lines run faster than using ast_build_string() */
632 *buf++ = ' ';
633 *buf = '\0';
634 for (y = -1; y < SHOW_TRANS; y++) {
635 if (y >= 0)
636 curlen = strlen(ast_getformatname(1 << (y)));
638 if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
639 /* XXX 999 is a little hackish
640 We don't want this number being larger than the shortest (or current) codec
641 For now, that is "gsm" */
642 ast_build_string(&buf, &left, "%*d", curlen + 1, tr_matrix[x][y].cost > 999 ? 0 : tr_matrix[x][y].cost);
643 } else if (x == -1 && y >= 0) {
644 /* Top row - use a dynamic size */
645 ast_build_string(&buf, &left, "%*s", curlen + 1, ast_getformatname(1 << (y)) );
646 } else if (y == -1 && x >= 0) {
647 /* Left column - use a static size. */
648 ast_build_string(&buf, &left, "%*s", longest, ast_getformatname(1 << (x)) );
649 } else if (x >= 0 && y >= 0) {
650 ast_build_string(&buf, &left, "%*s", curlen + 1, "-");
651 } else {
652 ast_build_string(&buf, &left, "%*s", longest, "");
655 ast_build_string(&buf, &left, "\n");
656 ast_cli(fd, line);
658 AST_LIST_UNLOCK(&translators);
659 return RESULT_SUCCESS;
662 static char show_trans_usage[] =
663 "Usage: core show translation [recalc] [<recalc seconds>]\n"
664 " Displays known codec translators and the cost associated\n"
665 "with each conversion. If the argument 'recalc' is supplied along\n"
666 "with optional number of seconds to test a new test will be performed\n"
667 "as the chart is being displayed.\n";
669 static struct ast_cli_entry cli_show_translation_deprecated = {
670 { "show", "translation", NULL },
671 show_translation_deprecated, NULL,
672 NULL };
674 static struct ast_cli_entry cli_translate[] = {
675 { { "core", "show", "translation", NULL },
676 show_translation, "Display translation matrix",
677 show_trans_usage, NULL, &cli_show_translation_deprecated },
680 /*! \brief register codec translator */
681 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
683 static int added_cli = 0;
684 struct ast_translator *u;
686 if (!mod) {
687 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
688 return -1;
691 if (!t->buf_size) {
692 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
693 return -1;
696 t->module = mod;
698 t->srcfmt = powerof(t->srcfmt);
699 t->dstfmt = powerof(t->dstfmt);
700 t->active = 1;
702 if (t->srcfmt == -1 || t->dstfmt == -1) {
703 ast_log(LOG_WARNING, "Invalid translator path: (%s codec is not valid)\n", t->srcfmt == -1 ? "starting" : "ending");
704 return -1;
706 if (t->plc_samples) {
707 if (t->buffer_samples < t->plc_samples) {
708 ast_log(LOG_WARNING, "plc_samples %d buffer_samples %d\n",
709 t->plc_samples, t->buffer_samples);
710 return -1;
712 if (t->dstfmt != powerof(AST_FORMAT_SLINEAR))
713 ast_log(LOG_WARNING, "plc_samples %d format %x\n",
714 t->plc_samples, t->dstfmt);
716 if (t->srcfmt >= MAX_FORMAT) {
717 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
718 return -1;
721 if (t->dstfmt >= MAX_FORMAT) {
722 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
723 return -1;
726 if (t->buf_size) {
728 * Align buf_size properly, rounding up to the machine-specific
729 * alignment for pointers.
731 struct _test_align { void *a, *b; } p;
732 int align = (char *)&p.b - (char *)&p.a;
734 t->buf_size = ((t->buf_size + align - 1) / align) * align;
737 if (t->frameout == NULL)
738 t->frameout = default_frameout;
740 calc_cost(t, 1);
742 if (option_verbose > 1) {
743 char tmp[80];
745 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %s to %s, cost %d\n",
746 term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
747 ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
750 if (!added_cli) {
751 ast_cli_register_multiple(cli_translate, sizeof(cli_translate) / sizeof(struct ast_cli_entry));
752 added_cli++;
755 AST_LIST_LOCK(&translators);
757 /* find any existing translators that provide this same srcfmt/dstfmt,
758 and put this one in order based on cost */
759 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
760 if ((u->srcfmt == t->srcfmt) &&
761 (u->dstfmt == t->dstfmt) &&
762 (u->cost > t->cost)) {
763 AST_LIST_INSERT_BEFORE_CURRENT(&translators, t, list);
764 t = NULL;
767 AST_LIST_TRAVERSE_SAFE_END;
769 /* if no existing translator was found for this format combination,
770 add it to the beginning of the list */
771 if (t)
772 AST_LIST_INSERT_HEAD(&translators, t, list);
774 rebuild_matrix(0);
776 AST_LIST_UNLOCK(&translators);
778 return 0;
781 /*! \brief unregister codec translator */
782 int ast_unregister_translator(struct ast_translator *t)
784 char tmp[80];
785 struct ast_translator *u;
786 int found = 0;
788 AST_LIST_LOCK(&translators);
789 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
790 if (u == t) {
791 AST_LIST_REMOVE_CURRENT(&translators, list);
792 if (option_verbose > 1)
793 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));
794 found = 1;
795 break;
798 AST_LIST_TRAVERSE_SAFE_END;
800 if (found)
801 rebuild_matrix(0);
803 AST_LIST_UNLOCK(&translators);
805 return (u ? 0 : -1);
808 void ast_translator_activate(struct ast_translator *t)
810 AST_LIST_LOCK(&translators);
811 t->active = 1;
812 rebuild_matrix(0);
813 AST_LIST_UNLOCK(&translators);
816 void ast_translator_deactivate(struct ast_translator *t)
818 AST_LIST_LOCK(&translators);
819 t->active = 0;
820 rebuild_matrix(0);
821 AST_LIST_UNLOCK(&translators);
824 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
825 int ast_translator_best_choice(int *dst, int *srcs)
827 int x,y;
828 int best = -1;
829 int bestdst = 0;
830 int cur, cursrc;
831 int besttime = INT_MAX;
832 int beststeps = INT_MAX;
833 int common = ((*dst) & (*srcs)) & AST_FORMAT_AUDIO_MASK; /* are there common formats ? */
835 if (common) { /* yes, pick one and return */
836 for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
837 if (cur & common) /* guaranteed to find one */
838 break;
840 /* We are done, this is a common format to both. */
841 *srcs = *dst = cur;
842 return 0;
843 } else { /* No, we will need to translate */
844 AST_LIST_LOCK(&translators);
845 for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
846 if (! (cur & *dst))
847 continue;
848 for (cursrc = 1, x = 0; x <= MAX_AUDIO_FORMAT; cursrc <<= 1, x++) {
849 if (!(*srcs & cursrc) || !tr_matrix[x][y].step ||
850 tr_matrix[x][y].cost > besttime)
851 continue; /* not existing or no better */
852 if (tr_matrix[x][y].cost < besttime ||
853 tr_matrix[x][y].multistep < beststeps) {
854 /* better than what we have so far */
855 best = cursrc;
856 bestdst = cur;
857 besttime = tr_matrix[x][y].cost;
858 beststeps = tr_matrix[x][y].multistep;
862 AST_LIST_UNLOCK(&translators);
863 if (best > -1) {
864 *srcs = best;
865 *dst = bestdst;
866 best = 0;
868 return best;
872 unsigned int ast_translate_path_steps(unsigned int dest, unsigned int src)
874 unsigned int res = -1;
876 /* convert bitwise format numbers into array indices */
877 src = powerof(src);
878 dest = powerof(dest);
880 if (src == -1 || dest == -1) {
881 ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src == -1 ? "starting" : "ending");
882 return -1;
884 AST_LIST_LOCK(&translators);
886 if (tr_matrix[src][dest].step)
887 res = tr_matrix[src][dest].multistep + 1;
889 AST_LIST_UNLOCK(&translators);
891 return res;
894 unsigned int ast_translate_available_formats(unsigned int dest, unsigned int src)
896 unsigned int res = dest;
897 unsigned int x;
898 unsigned int src_audio = src & AST_FORMAT_AUDIO_MASK;
899 unsigned int src_video = src & AST_FORMAT_VIDEO_MASK;
901 /* if we don't have a source format, we just have to try all
902 possible destination formats */
903 if (!src)
904 return dest;
906 /* If we have a source audio format, get its format index */
907 if (src_audio)
908 src_audio = powerof(src_audio);
910 /* If we have a source video format, get its format index */
911 if (src_video)
912 src_video = powerof(src_video);
914 AST_LIST_LOCK(&translators);
916 /* For a given source audio format, traverse the list of
917 known audio formats to determine whether there exists
918 a translation path from the source format to the
919 destination format. */
920 for (x = 1; src_audio && x < AST_FORMAT_MAX_AUDIO; x <<= 1) {
921 /* if this is not a desired format, nothing to do */
922 if (!dest & x)
923 continue;
925 /* if the source is supplying this format, then
926 we can leave it in the result */
927 if (src & x)
928 continue;
930 /* if we don't have a translation path from the src
931 to this format, remove it from the result */
932 if (!tr_matrix[src_audio][powerof(x)].step) {
933 res &= ~x;
934 continue;
937 /* now check the opposite direction */
938 if (!tr_matrix[powerof(x)][src_audio].step)
939 res &= ~x;
942 /* For a given source video format, traverse the list of
943 known video formats to determine whether there exists
944 a translation path from the source format to the
945 destination format. */
946 for (; src_video && x < AST_FORMAT_MAX_VIDEO; x <<= 1) {
947 /* if this is not a desired format, nothing to do */
948 if (!dest & x)
949 continue;
951 /* if the source is supplying this format, then
952 we can leave it in the result */
953 if (src & x)
954 continue;
956 /* if we don't have a translation path from the src
957 to this format, remove it from the result */
958 if (!tr_matrix[src_video][powerof(x)].step) {
959 res &= ~x;
960 continue;
963 /* now check the opposite direction */
964 if (!tr_matrix[powerof(x)][src_video].step)
965 res &= ~x;
968 AST_LIST_UNLOCK(&translators);
970 return res;
973 void ast_translate_frame_freed(struct ast_frame *fr)
975 struct ast_trans_pvt *pvt;
977 ast_clear_flag(fr, AST_FRFLAG_FROM_TRANSLATOR);
979 pvt = (struct ast_trans_pvt *) (((char *) fr) - offsetof(struct ast_trans_pvt, f));
981 if (pvt->datalen != -1)
982 return;
984 destroy(pvt);