Just some minor coding style cleanup...
[asterisk/asterisk.git] / main / translate.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Translate via the use of pseudo channels
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include <sys/time.h>
31 #include <sys/resource.h>
32
33 #include "asterisk/lock.h"
34 #include "asterisk/channel.h"
35 #include "asterisk/translate.h"
36 #include "asterisk/module.h"
37 #include "asterisk/frame.h"
38 #include "asterisk/sched.h"
39 #include "asterisk/cli.h"
40 #include "asterisk/term.h"
41
42 #define MAX_RECALC 1000 /* max sample recalc */
43
44 /*! \brief the list of translators */
45 static AST_RWLIST_HEAD_STATIC(translators, ast_translator);
46
47 struct translator_path {
48         struct ast_translator *step;    /*!< Next step translator */
49         unsigned int cost;              /*!< Complete cost to destination */
50         unsigned int multistep;         /*!< Multiple conversions required for this translation */
51 };
52
53 /*! \brief a matrix that, for any pair of supported formats,
54  * indicates the total cost of translation and the first step.
55  * The full path can be reconstricted iterating on the matrix
56  * until step->dstfmt == desired_format.
57  *
58  * Array indexes are 'src' and 'dest', in that order.
59  *
60  * Note: the lock in the 'translators' list is also used to protect
61  * this structure.
62  */
63 static struct translator_path tr_matrix[MAX_FORMAT][MAX_FORMAT];
64
65 /*! \todo
66  * TODO: sample frames for each supported input format.
67  * We build this on the fly, by taking an SLIN frame and using
68  * the existing converter to play with it.
69  */
70
71 /*! \brief returns the index of the lowest bit set */
72 static force_inline int powerof(unsigned int d)
73 {
74         int x = ffs(d);
75
76         if (x)
77                 return x - 1;
78
79         ast_log(LOG_WARNING, "No bits set? %d\n", d);
80
81         return -1;
82 }
83
84 /*
85  * wrappers around the translator routines.
86  */
87
88 /*!
89  * \brief Allocate the descriptor, required outbuf space,
90  * and possibly also plc and desc.
91  */
92 static void *newpvt(struct ast_translator *t)
93 {
94         struct ast_trans_pvt *pvt;
95         int len;
96         int useplc = t->plc_samples > 0 && t->useplc;   /* cache, because it can change on the fly */
97         char *ofs;
98
99         /*
100          * compute the required size adding private descriptor,
101          * plc, buffer, AST_FRIENDLY_OFFSET.
102          */
103         len = sizeof(*pvt) + t->desc_size;
104         if (useplc)
105                 len += sizeof(plc_state_t);
106         if (t->buf_size)
107                 len += AST_FRIENDLY_OFFSET + t->buf_size;
108         pvt = ast_calloc(1, len);
109         if (!pvt)
110                 return NULL;
111         pvt->t = t;
112         ofs = (char *)(pvt + 1);        /* pointer to data space */
113         if (t->desc_size) {             /* first comes the descriptor */
114                 pvt->pvt = ofs;
115                 ofs += t->desc_size;
116         }
117         if (useplc) {                   /* then plc state */
118                 pvt->plc = (plc_state_t *)ofs;
119                 ofs += sizeof(plc_state_t);
120         }
121         if (t->buf_size)                /* finally buffer and header */
122                 pvt->outbuf = ofs + AST_FRIENDLY_OFFSET;
123         /* call local init routine, if present */
124         if (t->newpvt && t->newpvt(pvt)) {
125                 ast_free(pvt);
126                 return NULL;
127         }
128         ast_module_ref(t->module);
129         return pvt;
130 }
131
132 static void destroy(struct ast_trans_pvt *pvt)
133 {
134         struct ast_translator *t = pvt->t;
135
136         if (ast_test_flag(&pvt->f, AST_FRFLAG_FROM_TRANSLATOR)) {
137                 /* If this flag is still set, that means that the translation path has
138                  * been torn down, while we still have a frame out there being used.
139                  * When ast_frfree() gets called on that frame, this ast_trans_pvt
140                  * will get destroyed, too. */
141
142                 pvt->destroy = 1;
143
144                 return;
145         }
146
147         if (t->destroy)
148                 t->destroy(pvt);
149         ast_free(pvt);
150         ast_module_unref(t->module);
151 }
152
153 /*! \brief framein wrapper, deals with plc and bound checks.  */
154 static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
155 {
156         int16_t *dst = (int16_t *)pvt->outbuf;
157         int ret;
158         int samples = pvt->samples;     /* initial value */
159         
160         /* Copy the last in jb timing info to the pvt */
161         ast_copy_flags(&pvt->f, f, AST_FRFLAG_HAS_TIMING_INFO);
162         pvt->f.ts = f->ts;
163         pvt->f.len = f->len;
164         pvt->f.seqno = f->seqno;
165
166         if (f->samples == 0) {
167                 ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
168         }
169         if (pvt->t->buffer_samples) {   /* do not pass empty frames to callback */
170                 if (f->datalen == 0) { /* perform PLC with nominal framesize of 20ms/160 samples */
171                         if (pvt->plc) {
172                                 int l = pvt->t->plc_samples;
173                                 if (pvt->samples + l > pvt->t->buffer_samples) {
174                                         ast_log(LOG_WARNING, "Out of buffer space\n");
175                                         return -1;
176                                 }
177                                 l = plc_fillin(pvt->plc, dst + pvt->samples, l);
178                                 pvt->samples += l;
179                                 pvt->datalen = pvt->samples * 2;        /* SLIN has 2bytes for 1sample */
180                         }
181                         /* We don't want generic PLC. If the codec has native PLC, then do that */
182                         if (!pvt->t->native_plc)
183                                 return 0;
184                 }
185                 if (pvt->samples + f->samples > pvt->t->buffer_samples) {
186                         ast_log(LOG_WARNING, "Out of buffer space\n");
187                         return -1;
188                 }
189         }
190         /* we require a framein routine, wouldn't know how to do
191          * it otherwise.
192          */
193         ret = pvt->t->framein(pvt, f);
194         /* possibly store data for plc */
195         if (!ret && pvt->plc) {
196                 int l = pvt->t->plc_samples;
197                 if (pvt->samples < l)
198                         l = pvt->samples;
199                 plc_rx(pvt->plc, dst + pvt->samples - l, l);
200         }
201         /* diagnostic ... */
202         if (pvt->samples == samples)
203                 ast_log(LOG_WARNING, "%s did not update samples %d\n",
204                         pvt->t->name, pvt->samples);
205         return ret;
206 }
207
208 /*! \brief generic frameout routine.
209  * If samples and datalen are 0, take whatever is in pvt
210  * and reset them, otherwise take the values in the caller and
211  * leave alone the pvt values.
212  */
213 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
214         int datalen, int samples)
215 {
216         struct ast_frame *f = &pvt->f;
217
218         if (samples)
219                 f->samples = samples;
220         else {
221                 if (pvt->samples == 0)
222                         return NULL;
223                 f->samples = pvt->samples;
224                 pvt->samples = 0;
225         }
226         if (datalen)
227                 f->datalen = datalen;
228         else {
229                 f->datalen = pvt->datalen;
230                 pvt->datalen = 0;
231         }
232
233         f->frametype = AST_FRAME_VOICE;
234         f->subclass = 1 << (pvt->t->dstfmt);
235         f->mallocd = 0;
236         f->offset = AST_FRIENDLY_OFFSET;
237         f->src = pvt->t->name;
238         f->data = pvt->outbuf;
239
240         ast_set_flag(f, AST_FRFLAG_FROM_TRANSLATOR);
241
242         return f;
243 }
244
245 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
246 {
247         return ast_trans_frameout(pvt, 0, 0);
248 }
249
250 /* end of callback wrappers and helpers */
251
252 void ast_translator_free_path(struct ast_trans_pvt *p)
253 {
254         struct ast_trans_pvt *pn = p;
255         while ( (p = pn) ) {
256                 pn = p->next;
257                 destroy(p);
258         }
259 }
260
261 /*! \brief Build a chain of translators based upon the given source and dest formats */
262 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
263 {
264         struct ast_trans_pvt *head = NULL, *tail = NULL;
265         
266         source = powerof(source);
267         dest = powerof(dest);
268         
269         AST_RWLIST_RDLOCK(&translators);
270
271         while (source != dest) {
272                 struct ast_trans_pvt *cur;
273                 struct ast_translator *t = tr_matrix[source][dest].step;
274                 if (!t) {
275                         ast_log(LOG_WARNING, "No translator path from %s to %s\n", 
276                                 ast_getformatname(source), ast_getformatname(dest));
277                         AST_RWLIST_UNLOCK(&translators);
278                         return NULL;
279                 }
280                 if (!(cur = newpvt(t))) {
281                         ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
282                         if (head)
283                                 ast_translator_free_path(head); 
284                         AST_RWLIST_UNLOCK(&translators);
285                         return NULL;
286                 }
287                 if (!head)
288                         head = cur;
289                 else
290                         tail->next = cur;
291                 tail = cur;
292                 cur->nextin = cur->nextout = ast_tv(0, 0);
293                 /* Keep going if this isn't the final destination */
294                 source = cur->t->dstfmt;
295         }
296
297         AST_RWLIST_UNLOCK(&translators);
298         return head;
299 }
300
301 static inline int format_rate(int format)
302 {
303         if (format == AST_FORMAT_G722 || format == AST_FORMAT_SLINEAR16)
304                 return 16000;
305
306         return 8000;
307 }
308
309 /*! \brief do the actual translation */
310 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
311 {
312         struct ast_trans_pvt *p = path;
313         struct ast_frame *out = f;
314         struct timeval delivery;
315         int has_timing_info;
316         long ts;
317         long len;
318         int seqno;
319
320         has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
321         ts = f->ts;
322         len = f->len;
323         seqno = f->seqno;
324
325         /* XXX hmmm... check this below */
326         if (!ast_tvzero(f->delivery)) {
327                 if (!ast_tvzero(path->nextin)) {
328                         /* Make sure this is in line with what we were expecting */
329                         if (!ast_tveq(path->nextin, f->delivery)) {
330                                 /* The time has changed between what we expected and this
331                                    most recent time on the new packet.  If we have a
332                                    valid prediction adjust our output time appropriately */
333                                 if (!ast_tvzero(path->nextout)) {
334                                         path->nextout = ast_tvadd(path->nextout,
335                                                                   ast_tvsub(f->delivery, path->nextin));
336                                 }
337                                 path->nextin = f->delivery;
338                         }
339                 } else {
340                         /* This is our first pass.  Make sure the timing looks good */
341                         path->nextin = f->delivery;
342                         path->nextout = f->delivery;
343                 }
344                 /* Predict next incoming sample */
345                 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, format_rate(f->subclass)));
346         }
347         delivery = f->delivery;
348         for ( ; out && p ; p = p->next) {
349                 framein(p, out);
350                 if (out != f)
351                         ast_frfree(out);
352                 out = p->t->frameout(p);
353         }
354         if (consume)
355                 ast_frfree(f);
356         if (out == NULL)
357                 return NULL;
358         /* we have a frame, play with times */
359         if (!ast_tvzero(delivery)) {
360                 /* Regenerate prediction after a discontinuity */
361                 if (ast_tvzero(path->nextout))
362                         path->nextout = ast_tvnow();
363
364                 /* Use next predicted outgoing timestamp */
365                 out->delivery = path->nextout;
366                 
367                 /* Predict next outgoing timestamp from samples in this
368                    frame. */
369                 path->nextout = ast_tvadd(path->nextout, ast_samp2tv(out->samples, format_rate(out->subclass)));
370         } else {
371                 out->delivery = ast_tv(0, 0);
372                 ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
373                 if (has_timing_info) {
374                         out->ts = ts;
375                         out->len = len;
376                         out->seqno = seqno;
377                 }
378         }
379         /* Invalidate prediction if we're entering a silence period */
380         if (out->frametype == AST_FRAME_CNG)
381                 path->nextout = ast_tv(0, 0);
382         return out;
383 }
384
385 /*! \brief compute the cost of a single translation step */
386 static void calc_cost(struct ast_translator *t, int seconds)
387 {
388         int num_samples = 0;
389         struct ast_trans_pvt *pvt;
390         struct rusage start;
391         struct rusage end;
392         int cost;
393         int out_rate = format_rate(t->dstfmt);
394
395         if (!seconds)
396                 seconds = 1;
397         
398         /* If they don't make samples, give them a terrible score */
399         if (!t->sample) {
400                 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
401                 t->cost = 999999;
402                 return;
403         }
404
405         pvt = newpvt(t);
406         if (!pvt) {
407                 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
408                 t->cost = 999999;
409                 return;
410         }
411
412         getrusage(RUSAGE_SELF, &start);
413
414         /* Call the encoder until we've processed the required number of samples */
415         while (num_samples < seconds * out_rate) {
416                 struct ast_frame *f = t->sample();
417                 if (!f) {
418                         ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
419                         destroy(pvt);
420                         t->cost = 999999;
421                         return;
422                 }
423                 framein(pvt, f);
424                 ast_frfree(f);
425                 while ((f = t->frameout(pvt))) {
426                         num_samples += f->samples;
427                         ast_frfree(f);
428                 }
429         }
430
431         getrusage(RUSAGE_SELF, &end);
432
433         cost = ((end.ru_utime.tv_sec - start.ru_utime.tv_sec) * 1000000) + end.ru_utime.tv_usec - start.ru_utime.tv_usec;
434         cost += ((end.ru_stime.tv_sec - start.ru_stime.tv_sec) * 1000000) + end.ru_stime.tv_usec - start.ru_stime.tv_usec;
435
436         destroy(pvt);
437
438         t->cost = cost / seconds;
439
440         if (!t->cost)
441                 t->cost = 1;
442 }
443
444 /*!
445  * \brief rebuild a translation matrix.
446  * \note This function expects the list of translators to be locked
447 */
448 static void rebuild_matrix(int samples)
449 {
450         struct ast_translator *t;
451         int x;      /* source format index */
452         int y;      /* intermediate format index */
453         int z;      /* destination format index */
454
455         ast_debug(1, "Resetting translation matrix\n");
456
457         bzero(tr_matrix, sizeof(tr_matrix));
458
459         /* first, compute all direct costs */
460         AST_RWLIST_TRAVERSE(&translators, t, list) {
461                 if (!t->active)
462                         continue;
463
464                 x = t->srcfmt;
465                 z = t->dstfmt;
466
467                 if (samples)
468                         calc_cost(t, samples);
469           
470                 if (!tr_matrix[x][z].step || t->cost < tr_matrix[x][z].cost) {
471                         tr_matrix[x][z].step = t;
472                         tr_matrix[x][z].cost = t->cost;
473                 }
474         }
475
476         /*
477          * For each triple x, y, z of distinct formats, check if there is
478          * a path from x to z through y which is cheaper than what is
479          * currently known, and in case, update the matrix.
480          * Repeat until the matrix is stable.
481          */
482         for (;;) {
483                 int changed = 0;
484                 for (x = 0; x < MAX_FORMAT; x++) {      /* source format */
485                         for (y = 0; y < MAX_FORMAT; y++) {    /* intermediate format */
486                                 if (x == y)                     /* skip ourselves */
487                                         continue;
488
489                                 for (z = 0; z<MAX_FORMAT; z++) {  /* dst format */
490                                         int newcost;
491
492                                         if (z == x || z == y)       /* skip null conversions */
493                                                 continue;
494                                         if (!tr_matrix[x][y].step)  /* no path from x to y */
495                                                 continue;
496                                         if (!tr_matrix[y][z].step)  /* no path from y to z */
497                                                 continue;
498                                         newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
499                                         if (tr_matrix[x][z].step && newcost >= tr_matrix[x][z].cost)
500                                                 continue;               /* x->y->z is more expensive than
501                                                                          * the existing path */
502                                         /* ok, we can get from x to z via y with a cost that
503                                            is the sum of the transition from x to y and
504                                            from y to z */
505                                                  
506                                         tr_matrix[x][z].step = tr_matrix[x][y].step;
507                                         tr_matrix[x][z].cost = newcost;
508                                         tr_matrix[x][z].multistep = 1;
509                                         ast_debug(3, "Discovered %d cost path from %s to %s, via %d\n", tr_matrix[x][z].cost, ast_getformatname(x), ast_getformatname(z), y);
510                                         changed++;
511                                 }
512                         }
513                 }
514                 if (!changed)
515                         break;
516         }
517 }
518
519 static char *handle_cli_core_show_translation(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
520 {
521 #define SHOW_TRANS 16
522         int x, y, z;
523         int curlen = 0, longest = 0;
524
525         switch (cmd) {
526         case CLI_INIT:
527                 e->command = "core show translation [recalc]";
528                 e->usage =
529                         "Usage: core show translation [recalc [<recalc seconds>]]\n"
530                         "       Displays known codec translators and the cost associated\n"
531                         "       with each conversion.  If the argument 'recalc' is supplied along\n"
532                         "       with optional number of seconds to test a new test will be performed\n"
533                         "       as the chart is being displayed.\n";
534                 return NULL;
535         case CLI_GENERATE:
536                 return NULL;
537         }
538
539         if (a->argc > 5)
540                 return CLI_SHOWUSAGE;
541         
542         if (a->argv[3] && !strcasecmp(a->argv[3], "recalc")) {
543                 z = a->argv[4] ? atoi(a->argv[4]) : 1;
544
545                 if (z <= 0) {
546                         ast_cli(a->fd, "         Recalc must be greater than 0.  Defaulting to 1.\n");
547                         z = 1;
548                 }
549
550                 if (z > MAX_RECALC) {
551                         ast_cli(a->fd, "         Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
552                         z = MAX_RECALC;
553                 }
554                 ast_cli(a->fd, "         Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
555                 AST_RWLIST_WRLOCK(&translators);
556                 rebuild_matrix(z);
557                 AST_RWLIST_UNLOCK(&translators);
558         } else if (a->argc > 3)
559                 return CLI_SHOWUSAGE;
560
561         AST_RWLIST_RDLOCK(&translators);
562
563         ast_cli(a->fd, "         Translation times between formats (in microseconds) for one second of data\n");
564         ast_cli(a->fd, "          Source Format (Rows) Destination Format (Columns)\n\n");
565         /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
566         for (x = 0; x < SHOW_TRANS; x++) {
567                 curlen = strlen(ast_getformatname(1 << (x)));
568                 if (curlen > longest)
569                         longest = curlen;
570         }
571         for (x = -1; x < SHOW_TRANS; x++) {
572                 struct ast_str *out = ast_str_alloca(120);
573                 /*Go ahead and move to next iteration if dealing with an unknown codec*/
574                 if(x >= 0 && !strcmp(ast_getformatname(1 << (x)), "unknown"))
575                         continue;
576                 ast_str_set(&out, -1, " ");
577                 for (y = -1; y < SHOW_TRANS; y++) {
578                         /*Go ahead and move to next iteration if dealing with an unknown codec*/
579                         if (y >= 0 && !strcmp(ast_getformatname(1 << (y)), "unknown"))
580                                 continue;
581                         if (y >= 0)
582                                 curlen = strlen(ast_getformatname(1 << (y)));
583                         if (curlen < 5)
584                                 curlen = 5;
585                         if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
586                                 /* XXX 99999 is a little hackish
587                                    We don't want this number being larger than the shortest (or current) codec
588                                    For now, that is "gsm" */
589                                 ast_str_append(&out, -1, "%*d", curlen + 1, tr_matrix[x][y].cost > 99999 ? 0 : tr_matrix[x][y].cost);
590                         } else if (x == -1 && y >= 0) {
591                                 /* Top row - use a dynamic size */
592                                 ast_str_append(&out, -1, "%*s", curlen + 1, ast_getformatname(1 << (y)) );
593                         } else if (y == -1 && x >= 0) {
594                                 /* Left column - use a static size. */
595                                 ast_str_append(&out, -1, "%*s", longest, ast_getformatname(1 << (x)) );
596                         } else if (x >= 0 && y >= 0) {
597                                 ast_str_append(&out, -1, "%*s", curlen + 1, "-");
598                         } else {
599                                 ast_str_append(&out, -1, "%*s", longest, "");
600                         }
601                 }
602                 ast_str_append(&out, -1, "\n");
603                 ast_cli(a->fd, out->str);                       
604         }
605         AST_RWLIST_UNLOCK(&translators);
606         return CLI_SUCCESS;
607 }
608
609 static struct ast_cli_entry cli_translate[] = {
610         AST_CLI_DEFINE(handle_cli_core_show_translation, "Display translation matrix")
611 };
612
613 /*! \brief register codec translator */
614 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
615 {
616         static int added_cli = 0;
617         struct ast_translator *u;
618         char tmp[80];
619
620         if (!mod) {
621                 ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
622                 return -1;
623         }
624
625         if (!t->buf_size) {
626                 ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
627                 return -1;
628         }
629
630         t->module = mod;
631
632         t->srcfmt = powerof(t->srcfmt);
633         t->dstfmt = powerof(t->dstfmt);
634         t->active = 1;
635
636         if (t->plc_samples) {
637                 if (t->buffer_samples < t->plc_samples) {
638                         ast_log(LOG_WARNING, "plc_samples %d buffer_samples %d\n",
639                                 t->plc_samples, t->buffer_samples);
640                         return -1;
641                 }
642                 if (t->dstfmt != powerof(AST_FORMAT_SLINEAR))
643                         ast_log(LOG_WARNING, "plc_samples %d format %x\n",
644                                 t->plc_samples, t->dstfmt);
645         }
646         if (t->srcfmt >= MAX_FORMAT) {
647                 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
648                 return -1;
649         }
650
651         if (t->dstfmt >= MAX_FORMAT) {
652                 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
653                 return -1;
654         }
655
656         if (t->buf_size) {
657                /*
658                 * Align buf_size properly, rounding up to the machine-specific
659                 * alignment for pointers.
660                 */
661                 struct _test_align { void *a, *b; } p;
662                 int align = (char *)&p.b - (char *)&p.a;
663
664                 t->buf_size = ((t->buf_size + align - 1) / align) * align;
665         }
666
667         if (t->frameout == NULL)
668                 t->frameout = default_frameout;
669   
670         calc_cost(t, 1);
671
672         ast_verb(2, "Registered translator '%s' from format %s to %s, cost %d\n",
673                             term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
674                             ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
675
676         if (!added_cli) {
677                 ast_cli_register_multiple(cli_translate, sizeof(cli_translate) / sizeof(struct ast_cli_entry));
678                 added_cli++;
679         }
680
681         AST_RWLIST_WRLOCK(&translators);
682
683         /* find any existing translators that provide this same srcfmt/dstfmt,
684            and put this one in order based on cost */
685         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
686                 if ((u->srcfmt == t->srcfmt) &&
687                     (u->dstfmt == t->dstfmt) &&
688                     (u->cost > t->cost)) {
689                         AST_RWLIST_INSERT_BEFORE_CURRENT(t, list);
690                         t = NULL;
691                 }
692         }
693         AST_RWLIST_TRAVERSE_SAFE_END;
694
695         /* if no existing translator was found for this format combination,
696            add it to the beginning of the list */
697         if (t)
698                 AST_RWLIST_INSERT_HEAD(&translators, t, list);
699
700         rebuild_matrix(0);
701
702         AST_RWLIST_UNLOCK(&translators);
703
704         return 0;
705 }
706
707 /*! \brief unregister codec translator */
708 int ast_unregister_translator(struct ast_translator *t)
709 {
710         char tmp[80];
711         struct ast_translator *u;
712         int found = 0;
713
714         AST_RWLIST_WRLOCK(&translators);
715         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
716                 if (u == t) {
717                         AST_RWLIST_REMOVE_CURRENT(list);
718                         ast_verb(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));
719                         found = 1;
720                         break;
721                 }
722         }
723         AST_RWLIST_TRAVERSE_SAFE_END;
724
725         if (found)
726                 rebuild_matrix(0);
727
728         AST_RWLIST_UNLOCK(&translators);
729
730         return (u ? 0 : -1);
731 }
732
733 void ast_translator_activate(struct ast_translator *t)
734 {
735         AST_RWLIST_WRLOCK(&translators);
736         t->active = 1;
737         rebuild_matrix(0);
738         AST_RWLIST_UNLOCK(&translators);
739 }
740
741 void ast_translator_deactivate(struct ast_translator *t)
742 {
743         AST_RWLIST_WRLOCK(&translators);
744         t->active = 0;
745         rebuild_matrix(0);
746         AST_RWLIST_UNLOCK(&translators);
747 }
748
749 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
750 int ast_translator_best_choice(int *dst, int *srcs)
751 {
752         int x,y;
753         int best = -1;
754         int bestdst = 0;
755         int cur, cursrc;
756         int besttime = INT_MAX;
757         int beststeps = INT_MAX;
758         int common = ((*dst) & (*srcs)) & AST_FORMAT_AUDIO_MASK;        /* are there common formats ? */
759
760         if (common) { /* yes, pick one and return */
761                 for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
762                         if (cur & common)       /* guaranteed to find one */
763                                 break;
764                 }
765                 /* We are done, this is a common format to both. */
766                 *srcs = *dst = cur;
767                 return 0;
768         } else {        /* No, we will need to translate */
769                 AST_RWLIST_RDLOCK(&translators);
770                 for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
771                         if (! (cur & *dst))
772                                 continue;
773                         for (cursrc = 1, x = 0; x <= MAX_AUDIO_FORMAT; cursrc <<= 1, x++) {
774                                 if (!(*srcs & cursrc) || !tr_matrix[x][y].step ||
775                                     tr_matrix[x][y].cost >  besttime)
776                                         continue;       /* not existing or no better */
777                                 if (tr_matrix[x][y].cost < besttime ||
778                                     tr_matrix[x][y].multistep < beststeps) {
779                                         /* better than what we have so far */
780                                         best = cursrc;
781                                         bestdst = cur;
782                                         besttime = tr_matrix[x][y].cost;
783                                         beststeps = tr_matrix[x][y].multistep;
784                                 }
785                         }
786                 }
787                 AST_RWLIST_UNLOCK(&translators);
788                 if (best > -1) {
789                         *srcs = best;
790                         *dst = bestdst;
791                         best = 0;
792                 }
793                 return best;
794         }
795 }
796
797 unsigned int ast_translate_path_steps(unsigned int dest, unsigned int src)
798 {
799         unsigned int res = -1;
800
801         /* convert bitwise format numbers into array indices */
802         src = powerof(src);
803         dest = powerof(dest);
804
805         AST_RWLIST_RDLOCK(&translators);
806
807         if (tr_matrix[src][dest].step)
808                 res = tr_matrix[src][dest].multistep + 1;
809
810         AST_RWLIST_UNLOCK(&translators);
811
812         return res;
813 }
814
815 unsigned int ast_translate_available_formats(unsigned int dest, unsigned int src)
816 {
817         unsigned int res = dest;
818         unsigned int x;
819         unsigned int src_audio = src & AST_FORMAT_AUDIO_MASK;
820         unsigned int src_video = src & AST_FORMAT_VIDEO_MASK;
821
822         /* if we don't have a source format, we just have to try all
823            possible destination formats */
824         if (!src)
825                 return dest;
826
827         /* If we have a source audio format, get its format index */
828         if (src_audio)
829                 src_audio = powerof(src_audio);
830
831         /* If we have a source video format, get its format index */
832         if (src_video)
833                 src_video = powerof(src_video);
834
835         AST_RWLIST_RDLOCK(&translators);
836
837         /* For a given source audio format, traverse the list of
838            known audio formats to determine whether there exists
839            a translation path from the source format to the
840            destination format. */
841         for (x = 1; src_audio && (x & AST_FORMAT_AUDIO_MASK); x <<= 1) {
842                 /* if this is not a desired format, nothing to do */
843                 if (!dest & x)
844                         continue;
845
846                 /* if the source is supplying this format, then
847                    we can leave it in the result */
848                 if (src & x)
849                         continue;
850
851                 /* if we don't have a translation path from the src
852                    to this format, remove it from the result */
853                 if (!tr_matrix[src_audio][powerof(x)].step) {
854                         res &= ~x;
855                         continue;
856                 }
857
858                 /* now check the opposite direction */
859                 if (!tr_matrix[powerof(x)][src_audio].step)
860                         res &= ~x;
861         }
862
863         /* For a given source video format, traverse the list of
864            known video formats to determine whether there exists
865            a translation path from the source format to the
866            destination format. */
867         for (; src_video && (x & AST_FORMAT_VIDEO_MASK); x <<= 1) {
868                 /* if this is not a desired format, nothing to do */
869                 if (!dest & x)
870                         continue;
871
872                 /* if the source is supplying this format, then
873                    we can leave it in the result */
874                 if (src & x)
875                         continue;
876
877                 /* if we don't have a translation path from the src
878                    to this format, remove it from the result */
879                 if (!tr_matrix[src_video][powerof(x)].step) {
880                         res &= ~x;
881                         continue;
882                 }
883
884                 /* now check the opposite direction */
885                 if (!tr_matrix[powerof(x)][src_video].step)
886                         res &= ~x;
887         }
888
889         AST_RWLIST_UNLOCK(&translators);
890
891         return res;
892 }
893
894 void ast_translate_frame_freed(struct ast_frame *fr)
895 {
896         struct ast_trans_pvt *pvt;
897
898         ast_clear_flag(fr, AST_FRFLAG_FROM_TRANSLATOR);
899
900         pvt = (struct ast_trans_pvt *) (((char *) fr) - offsetof(struct ast_trans_pvt, f));
901
902         if (!pvt->destroy)
903                 return;
904         
905         destroy(pvt);
906 }