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.
21 * \brief Translate via the use of pseudo channels
23 * \author Mark Spencer <markster@digium.com>
26 #include <sys/types.h>
27 #include <sys/socket.h>
34 #define MOD_LOADER /* not really a module */
37 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
39 #include "asterisk/lock.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/logger.h"
42 #include "asterisk/translate.h"
43 #include "asterisk/module.h"
44 #include "asterisk/options.h"
45 #include "asterisk/frame.h"
46 #include "asterisk/sched.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/term.h"
50 #define MAX_RECALC 200 /* max sample recalc */
52 /*! \brief the list of translators */
53 static AST_LIST_HEAD_STATIC(translators
, ast_translator
);
55 struct translator_path
{
56 struct ast_translator
*step
; /*!< Next step translator */
57 unsigned int cost
; /*!< Complete cost to destination */
58 unsigned int multistep
; /*!< Multiple conversions required for this translation */
61 /*! \brief a matrix that, for any pair of supported formats,
62 * indicates the total cost of translation and the first step.
63 * The full path can be reconstricted iterating on the matrix
64 * until step->dstfmt == desired_format.
66 * Array indexes are 'src' and 'dest', in that order.
68 static struct translator_path tr_matrix
[MAX_FORMAT
][MAX_FORMAT
];
71 * TODO: sample frames for each supported input format.
72 * We build this on the fly, by taking an SLIN frame and using
73 * the existing converter to play with it.
76 /* returns the index of the lowest bit set */
77 static int powerof(int d
)
80 for (x
= 0; x
< MAX_FORMAT
; x
++)
83 ast_log(LOG_WARNING
, "Powerof %d: No power??\n", d
);
88 * wrappers around the translator routines.
92 * \brief Allocate the descriptor, required outbuf space,
93 * and possibly also plc and desc.
95 static void *newpvt(struct ast_translator
*t
)
97 struct ast_trans_pvt
*pvt
;
99 int useplc
= t
->plc_samples
> 0 && t
->useplc
; /* cache, because it can change on the fly */
101 struct module_symbols
*ms
= t
->module
;
104 * compute the required size adding private descriptor,
105 * plc, buffer, AST_FRIENDLY_OFFSET.
107 len
= sizeof(*pvt
) + t
->desc_size
;
109 len
+= sizeof(plc_state_t
);
111 len
+= AST_FRIENDLY_OFFSET
+ t
->buf_size
;
112 pvt
= ast_calloc(1, len
);
116 ofs
= (char *)(pvt
+ 1); /* pointer to data space */
117 if (t
->desc_size
) { /* first comes the descriptor */
121 if (useplc
) { /* then plc state */
122 pvt
->plc
= (plc_state_t
*)ofs
;
123 ofs
+= sizeof(plc_state_t
);
125 if (t
->buf_size
) /* finally buffer and header */
126 pvt
->outbuf
= ofs
+ AST_FRIENDLY_OFFSET
;
127 /* call local init routine, if present */
128 if (t
->newpvt
&& t
->newpvt(pvt
) == NULL
) {
132 ast_atomic_fetchadd_int(&ms
->usecnt
, +1);
133 ast_update_use_count();
137 static void destroy(struct ast_trans_pvt
*pvt
)
139 struct ast_translator
*t
= pvt
->t
;
140 struct module_symbols
*ms
= t
->module
;
145 ast_atomic_fetchadd_int(&ms
->usecnt
, -1);
146 ast_update_use_count();
150 * framein wrapper, deals with plc and bound checks.
152 static int framein(struct ast_trans_pvt
*pvt
, struct ast_frame
*f
)
154 int16_t *dst
= (int16_t *)pvt
->outbuf
;
156 int samples
= pvt
->samples
; /* initial value */
158 if (f
->samples
== 0) {
159 ast_log(LOG_WARNING
, "no samples for %s\n", pvt
->t
->name
);
161 if (pvt
->t
->buffer_samples
) { /* do not pass empty frames to callback */
162 if (f
->datalen
== 0) { /* perform PLC with nominal framesize of 20ms/160 samples */
164 int l
= pvt
->t
->plc_samples
;
165 if (pvt
->samples
+ l
> pvt
->t
->buffer_samples
) {
166 ast_log(LOG_WARNING
, "Out of buffer space\n");
169 l
= plc_fillin(pvt
->plc
, dst
+ pvt
->samples
, l
);
174 if (pvt
->samples
+ f
->samples
> pvt
->t
->buffer_samples
) {
175 ast_log(LOG_WARNING
, "Out of buffer space\n");
179 /* we require a framein routine, wouldn't know how to do
182 ret
= pvt
->t
->framein(pvt
, f
);
183 /* possibly store data for plc */
184 if (!ret
&& pvt
->plc
) {
185 int l
= pvt
->t
->plc_samples
;
186 if (pvt
->samples
< l
)
188 plc_rx(pvt
->plc
, dst
+ pvt
->samples
- l
, l
);
191 if (pvt
->samples
== samples
)
192 ast_log(LOG_WARNING
, "%s did not update samples %d\n",
193 pvt
->t
->name
, pvt
->samples
);
198 * generic frameout routine.
199 * If samples and datalen are 0, take whatever is in pvt
200 * and reset them, otherwise take the values in the caller and
201 * leave alone the pvt values.
203 struct ast_frame
*ast_trans_frameout(struct ast_trans_pvt
*pvt
,
204 int datalen
, int samples
)
206 struct ast_frame
*f
= &pvt
->f
;
209 f
->samples
= samples
;
211 if (pvt
->samples
== 0)
213 f
->samples
= pvt
->samples
;
217 f
->datalen
= datalen
;
219 f
->datalen
= pvt
->datalen
;
223 f
->frametype
= AST_FRAME_VOICE
;
224 f
->subclass
= 1 << (pvt
->t
->dstfmt
);
226 f
->offset
= AST_FRIENDLY_OFFSET
;
227 f
->src
= pvt
->t
->name
;
228 f
->data
= pvt
->outbuf
;
232 static struct ast_frame
*default_frameout(struct ast_trans_pvt
*pvt
)
234 return ast_trans_frameout(pvt
, 0, 0);
237 /* end of callback wrappers and helpers */
239 void ast_translator_free_path(struct ast_trans_pvt
*p
)
241 struct ast_trans_pvt
*pn
= p
;
248 /*! Build a chain of translators based upon the given source and dest formats */
249 struct ast_trans_pvt
*ast_translator_build_path(int dest
, int source
)
251 struct ast_trans_pvt
*head
= NULL
, *tail
= NULL
;
253 source
= powerof(source
);
254 dest
= powerof(dest
);
256 while (source
!= dest
) {
257 struct ast_trans_pvt
*cur
;
258 struct ast_translator
*t
= tr_matrix
[source
][dest
].step
;
260 ast_log(LOG_WARNING
, "No translator path from %s to %s\n",
261 ast_getformatname(source
), ast_getformatname(dest
));
264 if (!(cur
= newpvt(t
))) {
265 ast_log(LOG_WARNING
, "Failed to build translator step from %d to %d\n", source
, dest
);
267 ast_translator_free_path(head
);
275 cur
->nextin
= cur
->nextout
= ast_tv(0, 0);
276 /* Keep going if this isn't the final destination */
277 source
= cur
->t
->dstfmt
;
282 /*! \brief do the actual translation */
283 struct ast_frame
*ast_translate(struct ast_trans_pvt
*path
, struct ast_frame
*f
, int consume
)
285 struct ast_trans_pvt
*p
= path
;
286 struct ast_frame
*out
= f
;
287 struct timeval delivery
;
289 /* XXX hmmm... check this below */
290 if (!ast_tvzero(f
->delivery
)) {
291 if (!ast_tvzero(path
->nextin
)) {
292 /* Make sure this is in line with what we were expecting */
293 if (!ast_tveq(path
->nextin
, f
->delivery
)) {
294 /* The time has changed between what we expected and this
295 most recent time on the new packet. If we have a
296 valid prediction adjust our output time appropriately */
297 if (!ast_tvzero(path
->nextout
)) {
298 path
->nextout
= ast_tvadd(path
->nextout
,
299 ast_tvsub(f
->delivery
, path
->nextin
));
301 path
->nextin
= f
->delivery
;
304 /* This is our first pass. Make sure the timing looks good */
305 path
->nextin
= f
->delivery
;
306 path
->nextout
= f
->delivery
;
308 /* Predict next incoming sample */
309 path
->nextin
= ast_tvadd(path
->nextin
, ast_samp2tv(f
->samples
, 8000));
311 delivery
= f
->delivery
;
312 for ( ; out
&& p
; p
= p
->next
) {
314 out
= p
->t
->frameout(p
);
320 /* we have a frame, play with times */
321 if (!ast_tvzero(delivery
)) {
322 /* Regenerate prediction after a discontinuity */
323 if (ast_tvzero(path
->nextout
))
324 path
->nextout
= ast_tvnow();
326 /* Use next predicted outgoing timestamp */
327 out
->delivery
= path
->nextout
;
329 /* Predict next outgoing timestamp from samples in this
331 path
->nextout
= ast_tvadd(path
->nextout
, ast_samp2tv( out
->samples
, 8000));
333 out
->delivery
= ast_tv(0, 0);
335 /* Invalidate prediction if we're entering a silence period */
336 if (out
->frametype
== AST_FRAME_CNG
)
337 path
->nextout
= ast_tv(0, 0);
341 /*! \brief compute the cost of a single translation step */
342 static void calc_cost(struct ast_translator
*t
, int seconds
)
345 struct ast_trans_pvt
*pvt
;
346 struct timeval start
;
352 /* If they don't make samples, give them a terrible score */
354 ast_log(LOG_WARNING
, "Translator '%s' does not produce sample frames.\n", t
->name
);
360 ast_log(LOG_WARNING
, "Translator '%s' appears to be broken and will probably fail.\n", t
->name
);
365 /* Call the encoder until we've processed the required number of samples */
366 while (sofar
< seconds
* 8000) {
367 struct ast_frame
*f
= t
->sample();
369 ast_log(LOG_WARNING
, "Translator '%s' failed to produce a sample frame.\n", t
->name
);
376 while( (f
= t
->frameout(pvt
))) {
381 cost
= ast_tvdiff_ms(ast_tvnow(), start
);
383 t
->cost
= cost
/ seconds
;
389 * \brief rebuild a translation matrix.
390 * \note This function expects the list of translators to be locked
392 static void rebuild_matrix(int samples
)
394 struct ast_translator
*t
;
395 int x
; /* source format index */
396 int y
; /* intermediate format index */
397 int z
; /* destination format index */
400 ast_log(LOG_DEBUG
, "Resetting translation matrix\n");
402 bzero(tr_matrix
, sizeof(tr_matrix
));
404 /* first, compute all direct costs */
405 AST_LIST_TRAVERSE(&translators
, t
, list
) {
410 calc_cost(t
, samples
);
412 if (!tr_matrix
[x
][z
].step
|| t
->cost
< tr_matrix
[x
][z
].cost
) {
413 tr_matrix
[x
][z
].step
= t
;
414 tr_matrix
[x
][z
].cost
= t
->cost
;
419 * For each triple x, y, z of distinct formats, check if there is
420 * a path from x to z through y which is cheaper than what is
421 * currently known, and in case, update the matrix.
422 * Repeat until the matrix is stable.
426 for (x
=0; x
< MAX_FORMAT
; x
++) { /* source format */
427 for (y
=0; y
< MAX_FORMAT
; y
++) { /* intermediate format */
428 if (x
== y
) /* skip ourselves */
431 for (z
=0; z
<MAX_FORMAT
; z
++) { /* dst format */
434 if (z
== x
|| z
== y
) /* skip null conversions */
436 if (!tr_matrix
[x
][y
].step
) /* no path from x to y */
438 if (!tr_matrix
[y
][z
].step
) /* no path from y to z */
440 newcost
= tr_matrix
[x
][y
].cost
+ tr_matrix
[y
][z
].cost
;
441 if (tr_matrix
[x
][z
].step
&& newcost
>= tr_matrix
[x
][z
].cost
)
442 continue; /* x->y->z is more expensive than
443 * the existing path */
444 /* ok, we can get from x to z via y with a cost that
445 is the sum of the transition from x to y and
448 tr_matrix
[x
][z
].step
= tr_matrix
[x
][y
].step
;
449 tr_matrix
[x
][z
].cost
= newcost
;
450 tr_matrix
[x
][z
].multistep
= 1;
452 ast_log(LOG_DEBUG
, "Discovered %d cost path from %s to %s, via %d\n", tr_matrix
[x
][z
].cost
, ast_getformatname(x
), ast_getformatname(z
), y
);
462 /*! \brief CLI "show translation" command handler */
463 static int show_translation(int fd
, int argc
, char *argv
[])
465 #define SHOW_TRANS 11
469 return RESULT_SHOWUSAGE
;
471 AST_LIST_LOCK(&translators
);
473 if (argv
[2] && !strcasecmp(argv
[2],"recalc")) {
474 z
= argv
[3] ? atoi(argv
[3]) : 1;
477 ast_cli(fd
," C'mon let's be serious here... defaulting to 1.\n");
481 if (z
> MAX_RECALC
) {
482 ast_cli(fd
," Maximum limit of recalc exceeded by %d, truncating value to %d\n",z
-MAX_RECALC
,MAX_RECALC
);
485 ast_cli(fd
," Recalculating Codec Translation (number of sample seconds: %d)\n\n",z
);
489 ast_cli(fd
, " Translation times between formats (in milliseconds)\n");
490 ast_cli(fd
, " Source Format (Rows) Destination Format(Columns)\n\n");
491 for (x
= -1; x
< SHOW_TRANS
; x
++) {
494 size_t left
= sizeof(line
) - 1; /* one initial space */
495 /* next 2 lines run faster than using ast_build_string() */
498 for (y
=-1;y
<SHOW_TRANS
;y
++) {
499 if (x
>= 0 && y
>= 0 && tr_matrix
[x
][y
].step
) /* XXX what is 99999 ? */
500 ast_build_string(&buf
, &left
, " %5d", tr_matrix
[x
][y
].cost
>= 99999 ? 0 : tr_matrix
[x
][y
].cost
);
501 else if (((x
== -1 && y
>= 0) || (y
== -1 && x
>= 0))) {
502 ast_build_string(&buf
, &left
, " %5s", ast_getformatname(1<<(x
+y
+1)) );
503 } else if (x
!= -1 && y
!= -1) {
504 ast_build_string(&buf
, &left
, " -");
506 ast_build_string(&buf
, &left
, " ");
509 ast_build_string(&buf
, &left
, "\n");
512 AST_LIST_UNLOCK(&translators
);
513 return RESULT_SUCCESS
;
517 static char show_trans_usage
[] =
518 "Usage: show translation [recalc] [<recalc seconds>]\n"
519 " Displays known codec translators and the cost associated\n"
520 "with each conversion. If the argument 'recalc' is supplied along\n"
521 "with optional number of seconds to test a new test will be performed\n"
522 "as the chart is being displayed.\n";
524 static struct ast_cli_entry show_trans
=
525 { { "show", "translation", NULL
}, show_translation
, "Display translation matrix", show_trans_usage
};
527 int ast_register_translator(struct ast_translator
*t
, void *module
)
529 static int added_cli
= 0;
531 if (module
== NULL
) {
532 ast_log(LOG_WARNING
, "Missing module pointer, you need to supply one\n");
536 if (t
->buf_size
== 0) {
537 ast_log(LOG_WARNING
, "empty buf size, you need to supply one\n");
540 if (t
->plc_samples
) {
541 if (t
->buffer_samples
< t
->plc_samples
) {
542 ast_log(LOG_WARNING
, "plc_samples %d buffer_samples %d\n",
543 t
->plc_samples
, t
->buffer_samples
);
546 if (t
->dstfmt
!= AST_FORMAT_SLINEAR
)
547 ast_log(LOG_WARNING
, "plc_samples %d format %x\n",
548 t
->plc_samples
, t
->dstfmt
);
550 t
->srcfmt
= powerof(t
->srcfmt
);
551 t
->dstfmt
= powerof(t
->dstfmt
);
552 /* XXX maybe check that it is not existing yet ? */
553 if (t
->srcfmt
>= MAX_FORMAT
) {
554 ast_log(LOG_WARNING
, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t
->srcfmt
));
557 if (t
->dstfmt
>= MAX_FORMAT
) {
558 ast_log(LOG_WARNING
, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t
->dstfmt
));
563 * Align buf_size properly, rounding up to the machine-specific
564 * alignment for pointers.
566 struct _test_align
{ void *a
, *b
; } p
;
567 int align
= (char *)&p
.b
- (char *)&p
.a
;
568 t
->buf_size
= ((t
->buf_size
+ align
- 1)/align
)*align
;
570 if (t
->frameout
== NULL
)
571 t
->frameout
= default_frameout
;
574 if (option_verbose
> 1) {
576 ast_verbose(VERBOSE_PREFIX_2
"Registered translator '%s' from format %s to %s, cost %d\n",
577 term_color(tmp
, t
->name
, COLOR_MAGENTA
, COLOR_BLACK
, sizeof(tmp
)),
578 ast_getformatname(1 << t
->srcfmt
), ast_getformatname(1 << t
->dstfmt
), t
->cost
);
580 AST_LIST_LOCK(&translators
);
582 ast_cli_register(&show_trans
);
585 AST_LIST_INSERT_HEAD(&translators
, t
, list
);
587 AST_LIST_UNLOCK(&translators
);
591 /*! \brief unregister codec translator */
592 int ast_unregister_translator(struct ast_translator
*t
)
595 struct ast_translator
*u
;
596 AST_LIST_LOCK(&translators
);
597 AST_LIST_TRAVERSE_SAFE_BEGIN(&translators
, u
, list
) {
599 AST_LIST_REMOVE_CURRENT(&translators
, list
);
600 if (option_verbose
> 1)
601 ast_verbose(VERBOSE_PREFIX_2
"Unregistered translator '%s' from format %s to %s\n", term_color(tmp
, t
->name
, COLOR_MAGENTA
, COLOR_BLACK
, sizeof(tmp
)), ast_getformatname(1 << t
->srcfmt
), ast_getformatname(1 << t
->dstfmt
));
605 AST_LIST_TRAVERSE_SAFE_END
607 AST_LIST_UNLOCK(&translators
);
611 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
612 int ast_translator_best_choice(int *dst
, int *srcs
)
618 int besttime
= INT_MAX
;
619 int beststeps
= INT_MAX
;
620 int common
= (*dst
) & (*srcs
); /* are there common formats ? */
622 if (common
) { /* yes, pick one and return */
623 for (cur
= 1, y
=0; y
< MAX_FORMAT
; cur
<<=1, y
++) {
624 if (cur
& common
) /* guaranteed to find one */
627 /* We are done, this is a common format to both. */
630 } else { /* No, we will need to translate */
631 AST_LIST_LOCK(&translators
);
632 for (cur
= 1, y
=0; y
< MAX_FORMAT
; cur
<<=1, y
++) {
635 for (cursrc
= 1, x
=0; x
< MAX_FORMAT
; cursrc
<<= 1, x
++) {
636 if (!(*srcs
& cursrc
) || !tr_matrix
[x
][y
].step
||
637 tr_matrix
[x
][y
].cost
> besttime
)
638 continue; /* not existing or no better */
639 if (tr_matrix
[x
][y
].cost
< besttime
||
640 tr_matrix
[x
][y
].multistep
< beststeps
) {
641 /* better than what we have so far */
644 besttime
= tr_matrix
[x
][y
].cost
;
645 beststeps
= tr_matrix
[x
][y
].multistep
;
649 AST_LIST_UNLOCK(&translators
);
659 unsigned int ast_translate_path_steps(unsigned int dest
, unsigned int src
)
661 /* convert bitwise format numbers into array indices */
663 dest
= powerof(dest
);
664 if (!tr_matrix
[src
][dest
].step
)
667 return tr_matrix
[src
][dest
].multistep
+ 1;