conversion from malloc to ast_malloc
[asterisk/asterisk.git] / 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 <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/time.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdio.h>
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/lock.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/logger.h"
41 #include "asterisk/translate.h"
42 #include "asterisk/options.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/sched.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/term.h"
47
48 #define MAX_RECALC 200 /* max sample recalc */
49
50 /*! \note
51    This could all be done more efficiently *IF* we chained packets together
52    by default, but it would also complicate virtually every application. */
53    
54 static AST_LIST_HEAD_STATIC(translators, ast_translator);
55
56 struct ast_translator_dir {
57         struct ast_translator *step;    /*!< Next step translator */
58         unsigned int cost;              /*!< Complete cost to destination */
59         unsigned int multistep;         /*!< Multiple conversions required for this translation */
60 };
61
62 struct ast_frame_delivery {
63         struct ast_frame *f;
64         struct ast_channel *chan;
65         int fd;
66         struct translator_pvt *owner;
67         struct ast_frame_delivery *prev;
68         struct ast_frame_delivery *next;
69 };
70
71 static struct ast_translator_dir tr_matrix[MAX_FORMAT][MAX_FORMAT];
72
73 struct ast_trans_pvt {
74         struct ast_translator *step;
75         struct ast_translator_pvt *state;
76         struct ast_trans_pvt *next;
77         struct timeval nextin;
78         struct timeval nextout;
79 };
80
81
82 static int powerof(int d)
83 {
84         int x;
85         for (x = 0; x < 32; x++)
86                 if ((1 << x) & d)
87                         return x;
88         ast_log(LOG_WARNING, "Powerof %d: No power??\n", d);
89         return -1;
90 }
91
92 void ast_translator_free_path(struct ast_trans_pvt *p)
93 {
94         struct ast_trans_pvt *pl, *pn;
95         pn = p;
96         while(pn) {
97                 pl = pn;
98                 pn = pn->next;
99                 if (pl->state && pl->step->destroy)
100                         pl->step->destroy(pl->state);
101                 free(pl);
102         }
103 }
104
105 /*! Build a set of translators based upon the given source and destination formats */
106 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
107 {
108         struct ast_trans_pvt *tmpr = NULL, *tmp = NULL;
109         
110         source = powerof(source);
111         dest = powerof(dest);
112         
113         while (source != dest) {
114                 if (!tr_matrix[source][dest].step) {
115                         /* We shouldn't have allocated any memory */
116                         ast_log(LOG_WARNING, "No translator path from %s to %s\n", 
117                                 ast_getformatname(source), ast_getformatname(dest));
118                         return NULL;
119                 }
120
121                 if (tmp) {
122                         tmp->next = ast_malloc(sizeof(*tmp));
123                         tmp = tmp->next;
124                 } else
125                         tmp = ast_malloc(sizeof(*tmp));
126                         
127                 if (!tmp) {
128                         if (tmpr)
129                                 ast_translator_free_path(tmpr); 
130                         return NULL;
131                 }
132
133                 /* Set the root, if it doesn't exist yet... */
134                 if (!tmpr)
135                         tmpr = tmp;
136
137                 tmp->next = NULL;
138                 tmp->nextin = tmp->nextout = ast_tv(0, 0);
139                 tmp->step = tr_matrix[source][dest].step;
140                 tmp->state = tmp->step->newpvt();
141                 
142                 if (!tmp->state) {
143                         ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
144                         ast_translator_free_path(tmpr); 
145                         return NULL;
146                 }
147                 
148                 /* Keep going if this isn't the final destination */
149                 source = tmp->step->dstfmt;
150         }
151         return tmpr;
152 }
153
154 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
155 {
156         struct ast_trans_pvt *p;
157         struct ast_frame *out;
158         struct timeval delivery;
159         p = path;
160         /* Feed the first frame into the first translator */
161         p->step->framein(p->state, f);
162         if (!ast_tvzero(f->delivery)) {
163                 if (!ast_tvzero(path->nextin)) {
164                         /* Make sure this is in line with what we were expecting */
165                         if (!ast_tveq(path->nextin, f->delivery)) {
166                                 /* The time has changed between what we expected and this
167                                    most recent time on the new packet.  If we have a
168                                    valid prediction adjust our output time appropriately */
169                                 if (!ast_tvzero(path->nextout)) {
170                                         path->nextout = ast_tvadd(path->nextout,
171                                                                   ast_tvsub(f->delivery, path->nextin));
172                                 }
173                                 path->nextin = f->delivery;
174                         }
175                 } else {
176                         /* This is our first pass.  Make sure the timing looks good */
177                         path->nextin = f->delivery;
178                         path->nextout = f->delivery;
179                 }
180                 /* Predict next incoming sample */
181                 path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, 8000));
182         }
183         delivery = f->delivery;
184         if (consume)
185                 ast_frfree(f);
186         while(p) {
187                 out = p->step->frameout(p->state);
188                 /* If we get nothing out, return NULL */
189                 if (!out)
190                         return NULL;
191                 /* If there is a next state, feed it in there.  If not,
192                    return this frame  */
193                 if (p->next) 
194                         p->next->step->framein(p->next->state, out);
195                 else {
196                         if (!ast_tvzero(delivery)) {
197                                 /* Regenerate prediction after a discontinuity */
198                                 if (ast_tvzero(path->nextout))
199                                         path->nextout = ast_tvnow();
200
201                                 /* Use next predicted outgoing timestamp */
202                                 out->delivery = path->nextout;
203                                 
204                                 /* Predict next outgoing timestamp from samples in this
205                                    frame. */
206                                 path->nextout = ast_tvadd(path->nextout, ast_samp2tv( out->samples, 8000));
207                         } else {
208                                 out->delivery = ast_tv(0, 0);
209                         }
210                         /* Invalidate prediction if we're entering a silence period */
211                         if (out->frametype == AST_FRAME_CNG)
212                                 path->nextout = ast_tv(0, 0);
213                         return out;
214                 }
215                 p = p->next;
216         }
217         ast_log(LOG_WARNING, "I should never get here...\n");
218         return NULL;
219 }
220
221
222 static void calc_cost(struct ast_translator *t, int samples)
223 {
224         int sofar=0;
225         struct ast_translator_pvt *pvt;
226         struct ast_frame *f, *out;
227         struct timeval start;
228         int cost;
229
230         if(!samples)
231                 samples = 1;
232         
233         /* If they don't make samples, give them a terrible score */
234         if (!t->sample) {
235                 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
236                 t->cost = 99999;
237                 return;
238         }
239         pvt = t->newpvt();
240         if (!pvt) {
241                 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
242                 t->cost = 99999;
243                 return;
244         }
245         start = ast_tvnow();
246         /* Call the encoder until we've processed one second of time */
247         while(sofar < samples * 8000) {
248                 f = t->sample();
249                 if (!f) {
250                         ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
251                         t->destroy(pvt);
252                         t->cost = 99999;
253                         return;
254                 }
255                 t->framein(pvt, f);
256                 ast_frfree(f);
257                 while((out = t->frameout(pvt))) {
258                         sofar += out->samples;
259                         ast_frfree(out);
260                 }
261         }
262         cost = ast_tvdiff_ms(ast_tvnow(), start);
263         t->destroy(pvt);
264         t->cost = cost / samples;
265         if (!t->cost)
266                 t->cost = 1;
267 }
268
269 /*! 
270   \brief Use the list of translators to build a translation matrix
271
272   \note This function expects the list of translators to be locked
273 */
274 static void rebuild_matrix(int samples)
275 {
276         struct ast_translator *t;
277         int changed;
278         int x, y, z;
279
280         if (option_debug)
281                 ast_log(LOG_DEBUG, "Resetting translation matrix\n");
282
283         bzero(tr_matrix, sizeof(tr_matrix));
284
285         AST_LIST_TRAVERSE(&translators, t, list) {
286                 if (samples)
287                         calc_cost(t, samples);
288           
289                 if (!tr_matrix[t->srcfmt][t->dstfmt].step ||
290                     tr_matrix[t->srcfmt][t->dstfmt].cost > t->cost) {
291                         tr_matrix[t->srcfmt][t->dstfmt].step = t;
292                         tr_matrix[t->srcfmt][t->dstfmt].cost = t->cost;
293                 }
294         }
295
296         do {
297                 changed = 0;
298
299                 /* Don't you just love O(N^3) operations? */
300                 for (x = 0; x< MAX_FORMAT; x++) {                       /* For each source format */
301                         for (y = 0; y < MAX_FORMAT; y++) {              /* And each destination format */
302                                 if (x == y)                             /* Except ourselves, of course */
303                                         continue;
304
305                                 for (z=0; z < MAX_FORMAT; z++) {        /* And each format it might convert to */
306                                         if ((x == z) || (y == z))       /* Don't ever convert back to us */
307                                                 continue;
308
309                                         if (tr_matrix[x][y].step &&     /* We can convert from x to y */
310                                             tr_matrix[y][z].step &&     /* And from y to z and... */
311                                             (!tr_matrix[x][z].step ||   /* Either there isn't an x->z conversion */
312                                              (tr_matrix[x][y].cost + 
313                                               tr_matrix[y][z].cost <    /* Or we're cheaper than the existing */
314                                               tr_matrix[x][z].cost)     /* solution */
315                                                     )) {
316                                                 /* We can get from x to z via y with a cost that
317                                                    is the sum of the transition from x to y and
318                                                    from y to z */
319                                                 
320                                                 tr_matrix[x][z].step = tr_matrix[x][y].step;
321                                                 tr_matrix[x][z].cost = tr_matrix[x][y].cost + 
322                                                         tr_matrix[y][z].cost;
323                                                 tr_matrix[x][z].multistep = 1;
324                                                 if (option_debug)
325                                                         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);
326                                                 changed++;
327                                         }
328                                 }
329                         }
330                 }
331         } while (changed);
332 }
333
334
335 /*! \brief CLI "show translation" command handler */
336 static int show_translation(int fd, int argc, char *argv[])
337 {
338 #define SHOW_TRANS 11
339         int x, y, z;
340         char line[80];
341         if (argc > 4) 
342                 return RESULT_SHOWUSAGE;
343
344         AST_LIST_LOCK(&translators);    
345         
346         if (argv[2] && !strcasecmp(argv[2],"recalc")) {
347                 z = argv[3] ? atoi(argv[3]) : 1;
348
349                 if (z <= 0) {
350                         ast_cli(fd,"         C'mon let's be serious here... defaulting to 1.\n");
351                         z = 1;
352                 }
353
354                 if (z > MAX_RECALC) {
355                         ast_cli(fd,"         Maximum limit of recalc exceeded by %d, truncating value to %d\n",z-MAX_RECALC,MAX_RECALC);
356                         z = MAX_RECALC;
357                 }
358                 ast_cli(fd,"         Recalculating Codec Translation (number of sample seconds: %d)\n\n",z);
359                 rebuild_matrix(z);
360         }
361
362         ast_cli(fd, "         Translation times between formats (in milliseconds)\n");
363         ast_cli(fd, "          Source Format (Rows) Destination Format(Columns)\n\n");
364         for (x = -1; x < SHOW_TRANS; x++) {
365                 /* next 2 lines run faster than using strcpy() */
366                 line[0] = ' ';
367                 line[1] = '\0';
368                 for (y=-1;y<SHOW_TRANS;y++) {
369                         if (x >= 0 && y >= 0 && tr_matrix[x][y].step)
370                                 snprintf(line + strlen(line), sizeof(line) - strlen(line), " %5d", tr_matrix[x][y].cost >= 99999 ? tr_matrix[x][y].cost-99999 : tr_matrix[x][y].cost);
371                         else
372                                 if (((x == -1 && y >= 0) || (y == -1 && x >= 0))) {
373                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), 
374                                                 " %5s", ast_getformatname(1<<(x+y+1)) );
375                                 } else if (x != -1 && y != -1) {
376                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "     -");
377                                 } else {
378                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "      ");
379                                 }
380                 }
381                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "\n");
382                 ast_cli(fd, line);                      
383         }
384         AST_LIST_UNLOCK(&translators);
385         return RESULT_SUCCESS;
386 }
387
388 static int added_cli = 0;
389
390 static char show_trans_usage[] =
391 "Usage: show translation [recalc] [<recalc seconds>]\n"
392 "       Displays known codec translators and the cost associated\n"
393 "with each conversion.  If the argument 'recalc' is supplied along\n"
394 "with optional number of seconds to test a new test will be performed\n"
395 "as the chart is being displayed.\n";
396
397 static struct ast_cli_entry show_trans =
398 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
399
400 int ast_register_translator(struct ast_translator *t)
401 {
402         char tmp[80];
403         t->srcfmt = powerof(t->srcfmt);
404         t->dstfmt = powerof(t->dstfmt);
405         if (t->srcfmt >= MAX_FORMAT) {
406                 ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
407                 return -1;
408         }
409         if (t->dstfmt >= MAX_FORMAT) {
410                 ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
411                 return -1;
412         }
413         calc_cost(t,1);
414         if (option_verbose > 1)
415                 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %s to %s, cost %d\n", term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)), ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt), t->cost);
416         AST_LIST_LOCK(&translators);
417         if (!added_cli) {
418                 ast_cli_register(&show_trans);
419                 added_cli++;
420         }
421         AST_LIST_INSERT_HEAD(&translators, t, list);
422         rebuild_matrix(0);
423         AST_LIST_UNLOCK(&translators);
424         return 0;
425 }
426
427 /*! \brief unregister codec translator */
428 int ast_unregister_translator(struct ast_translator *t)
429 {
430         char tmp[80];
431         struct ast_translator *u;
432         AST_LIST_LOCK(&translators);
433         AST_LIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
434                 if (u == t) {
435                         AST_LIST_REMOVE_CURRENT(&translators, list);
436                         if (option_verbose > 1)
437                                 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));
438                         break;
439                 }
440         }
441         AST_LIST_TRAVERSE_SAFE_END
442         rebuild_matrix(0);
443         AST_LIST_UNLOCK(&translators);
444         return (u ? 0 : -1);
445 }
446
447 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
448 int ast_translator_best_choice(int *dst, int *srcs)
449 {
450         int x,y;
451         int best = -1;
452         int bestdst = 0;
453         int cur = 1;
454         int besttime = INT_MAX;
455         int beststeps = INT_MAX;
456         int common;
457
458         if ((common = (*dst) & (*srcs))) {
459                 /* We have a format in common */
460                 for (y = 0; y < MAX_FORMAT; y++) {
461                         if (cur & common) {
462                                 /* This is a common format to both.  Pick it if we don't have one already */
463                                 bestdst = cur;
464                                 best = cur;
465                         }
466                         cur = cur << 1;
467                 }
468         } else {
469                 /* We will need to translate */
470                 AST_LIST_LOCK(&translators);
471                 for (y = 0; y < MAX_FORMAT; y++) {
472                         if (!(cur & *dst)) {
473                                 cur = cur << 1;
474                                 continue;
475                         }
476
477                         for (x = 0; x < MAX_FORMAT; x++) {
478                                 if ((*srcs & (1 << x)) &&                       /* x is a valid source format */
479                                     tr_matrix[x][y].step) {                     /* There's a step */
480                                         if (tr_matrix[x][y].cost > besttime)
481                                                 continue;                       /* It's more expensive, skip it */
482                                         
483                                         if (tr_matrix[x][y].cost == besttime &&
484                                             tr_matrix[x][y].multistep >= beststeps)
485                                                 continue;                       /* It requires the same (or more) steps,
486                                                                                    skip it */
487
488                                         /* It's better than what we have so far */
489                                         best = 1 << x;
490                                         bestdst = cur;
491                                         besttime = tr_matrix[x][y].cost;
492                                         beststeps = tr_matrix[x][y].multistep;
493                                 }
494                         }
495                         cur = cur << 1;
496                 }
497                 AST_LIST_UNLOCK(&translators);
498         }
499
500         if (best > -1) {
501                 *srcs = best;
502                 *dst = bestdst;
503                 best = 0;
504         }
505
506         return best;
507 }