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