0f2bc9efcbfec9d3c9aa981f8fc8ea365a807e84
[asterisk/asterisk.git] / translate.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Translate via the use of pseudo channels
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <asterisk/lock.h>
15 #include <asterisk/channel.h>
16 #include <asterisk/channel_pvt.h>
17 #include <asterisk/logger.h>
18 #include <asterisk/translate.h>
19 #include <asterisk/options.h>
20 #include <asterisk/frame.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/cli.h>
23 #include <asterisk/term.h>
24 #include <sys/socket.h>
25 #include <sys/time.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <pthread.h>
29 #include <string.h>
30 #include <stdio.h>
31
32 /* This could all be done more efficiently *IF* we chained packets together
33    by default, but it would also complicate virtually every application. */
34    
35 static ast_mutex_t list_lock = AST_MUTEX_INITIALIZER;
36 static struct ast_translator *list = NULL;
37
38 struct ast_translator_dir {
39         struct ast_translator *step;    /* Next step translator */
40         int cost;                                               /* Complete cost to destination */
41 };
42
43 struct ast_frame_delivery {
44         struct ast_frame *f;
45         struct ast_channel *chan;
46         int fd;
47         struct translator_pvt *owner;
48         struct ast_frame_delivery *prev;
49         struct ast_frame_delivery *next;
50 };
51
52 static struct ast_translator_dir tr_matrix[MAX_FORMAT][MAX_FORMAT];
53
54 struct ast_trans_pvt {
55         struct ast_translator *step;
56         struct ast_translator_pvt *state;
57         struct ast_trans_pvt *next;
58 };
59
60
61 static int powerof(int d)
62 {
63         int x;
64         for (x = 0; x < 32; x++)
65                 if ((1 << x) & d)
66                         return x;
67         ast_log(LOG_WARNING, "Powerof %d: No power??\n", d);
68         return -1;
69 }
70
71 void ast_translator_free_path(struct ast_trans_pvt *p)
72 {
73         struct ast_trans_pvt *pl;
74         while(p) {
75                 pl = p;
76                 p = p->next;
77                 if (pl->state && pl->step->destroy)
78                         pl->step->destroy(pl->state);
79                 free(pl);
80         }
81 }
82
83 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
84 {
85         struct ast_trans_pvt *tmpr = NULL, *tmp = NULL;
86         /* One of the hardest parts:  Build a set of translators based upon
87            the given source and destination formats */
88         source = powerof(source);
89         dest = powerof(dest);
90         while(source != dest) {
91                 if (tr_matrix[source][dest].step) {
92                         if (tmp) {
93                                 tmp->next = malloc(sizeof(struct ast_trans_pvt));
94                                 tmp = tmp->next;
95                         } else
96                                 tmp = malloc(sizeof(struct ast_trans_pvt));
97
98                                 
99                         if (tmp) {
100                                 tmp->next = NULL;
101                                 tmp->step = tr_matrix[source][dest].step;
102                                 tmp->state = tmp->step->new();
103                                 if (!tmp->state) {
104                                         ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
105                                         free(tmp);
106                                         tmp = NULL;
107                                         return NULL;
108                                 }
109                                 /* Set the root, if it doesn't exist yet... */
110                                 if (!tmpr)
111                                         tmpr = tmp;
112                                 /* Keep going if this isn't the final destination */
113                                 source = tmp->step->dstfmt;
114                         } else {
115                                 /* XXX This could leak XXX */
116                                 ast_log(LOG_WARNING, "Out of memory\n");
117                                 return NULL;
118                         }
119                 } else {
120                         /* We shouldn't have allocated any memory */
121                         ast_log(LOG_WARNING, "No translator path from %s to %s\n", 
122                                 ast_getformatname(source), ast_getformatname(dest));
123                         return NULL;
124                 }
125         }
126         return tmpr;
127 }
128
129 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
130 {
131         struct ast_trans_pvt *p;
132         struct ast_frame *out;
133         p = path;
134         /* Feed the first frame into the first translator */
135         p->step->framein(p->state, f);
136         if (consume)
137                 ast_frfree(f);
138         while(p) {
139                 out = p->step->frameout(p->state);
140                 /* If we get nothing out, return NULL */
141                 if (!out)
142                         return NULL;
143                 /* If there is a next state, feed it in there.  If not,
144                    return this frame  */
145                 if (p->next) 
146                         p->next->step->framein(p->next->state, out);
147                 else
148                         return out;
149                 p = p->next;
150         }
151         ast_log(LOG_WARNING, "I should never get here...\n");
152         return NULL;
153 }
154
155 static void rebuild_matrix(void)
156 {
157         struct ast_translator *t;
158         int changed;
159         int x,y,z;
160         if (option_debug)
161                 ast_log(LOG_DEBUG, "Reseting translation matrix\n");
162         /* Use the list of translators to build a translation matrix */
163         bzero(tr_matrix, sizeof(tr_matrix));
164         t = list;
165         while(t) {
166                 if (!tr_matrix[t->srcfmt][t->dstfmt].step ||
167                      tr_matrix[t->srcfmt][t->dstfmt].cost > t->cost) {
168                         tr_matrix[t->srcfmt][t->dstfmt].step = t;
169                         tr_matrix[t->srcfmt][t->dstfmt].cost = t->cost;
170                 }
171                 t = t->next;
172         }
173         do {
174                 changed = 0;
175                 /* Don't you just love O(N^3) operations? */
176                 for (x=0; x< MAX_FORMAT; x++)                           /* For each source format */
177                         for (y=0; y < MAX_FORMAT; y++)                  /* And each destination format */
178                                 if (x != y)                                                     /* Except ourselves, of course */
179                                         for (z=0; z < MAX_FORMAT; z++)  /* And each format it might convert to */
180                                                 if ((x!=z) && (y!=z))           /* Don't ever convert back to us */
181                                                         if (tr_matrix[x][y].step && /* We can convert from x to y */
182                                                                 tr_matrix[y][z].step && /* And from y to z and... */
183                                                                 (!tr_matrix[x][z].step ||       /* Either there isn't an x->z conversion */
184                                                                 (tr_matrix[x][y].cost + 
185                                                                  tr_matrix[y][z].cost < /* Or we're cheaper than the existing */
186                                                                  tr_matrix[x][z].cost)  /* solution */
187                                                              )) {
188                                                                                         /* We can get from x to z via y with a cost that
189                                                                                            is the sum of the transition from x to y and
190                                                                                            from y to z */
191                                                                  
192                                                                         tr_matrix[x][z].step = tr_matrix[x][y].step;
193                                                                         tr_matrix[x][z].cost = tr_matrix[x][y].cost + 
194                                                                                                                    tr_matrix[y][z].cost;
195                                                                         if (option_debug)
196                                                                                 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);
197                                                                         changed++;
198                                                                  }
199                 
200         } while (changed);
201 }
202
203 static void calc_cost(struct ast_translator *t)
204 {
205         int sofar=0;
206         struct ast_translator_pvt *pvt;
207         struct ast_frame *f, *out;
208         struct timeval start, finish;
209         int cost;
210         /* If they don't make samples, give them a terrible score */
211         if (!t->sample) {
212                 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
213                 t->cost = 99999;
214                 return;
215         }
216         pvt = t->new();
217         if (!pvt) {
218                 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
219                 t->cost = 99999;
220                 return;
221         }
222         gettimeofday(&start, NULL);
223         /* Call the encoder until we've processed one second of time */
224         while(sofar < 8000) {
225                 f = t->sample();
226                 if (!f) {
227                         ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
228                         t->destroy(pvt);
229                         t->cost = 99999;
230                         return;
231                 }
232                 t->framein(pvt, f);
233                 ast_frfree(f);
234                 while((out = t->frameout(pvt))) {
235                         sofar += out->samples;
236                         ast_frfree(out);
237                 }
238         }
239         gettimeofday(&finish, NULL);
240         t->destroy(pvt);
241         cost = (finish.tv_sec - start.tv_sec) * 1000 + (finish.tv_usec - start.tv_usec) / 1000;
242         t->cost = cost;
243         if (!t->cost)
244                 t->cost = 1;
245 }
246
247 static int show_translation(int fd, int argc, char *argv[])
248 {
249 #define SHOW_TRANS 11
250         int x,y;
251         char line[80];
252         if (argc != 2) 
253                 return RESULT_SHOWUSAGE;
254         ast_cli(fd, "         Translation times between formats (in milliseconds)\n");
255         ast_cli(fd, "          Source Format (Rows) Destination Format(Columns)\n\n");
256         ast_mutex_lock(&list_lock);
257         for (x=-1;x<SHOW_TRANS; x++) {
258                 strcpy(line, " ");
259                 for (y=-1;y<SHOW_TRANS;y++) {
260                         if (x >= 0 && y >= 0 && tr_matrix[x][y].step)
261                                 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);
262                         else
263                                 if (((x == -1 && y >= 0) || (y == -1 && x >= 0))) {
264                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), 
265                                                 " %5s", ast_getformatname(1<<(x+y+1)) );
266                                 } else if (x != -1 && y != -1) {
267                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "     -");
268                                 } else {
269                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "      ");
270                                 }
271                 }
272                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "\n");
273                 ast_cli(fd, line);                      
274         }
275         ast_mutex_unlock(&list_lock);
276         return RESULT_SUCCESS;
277 }
278
279 static int added_cli = 0;
280
281 static char show_trans_usage[] =
282 "Usage: show translation\n"
283 "       Displays known codec translators and the cost associated\n"
284 "with each conversion.\n";
285
286 static struct ast_cli_entry show_trans =
287 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
288
289 int ast_register_translator(struct ast_translator *t)
290 {
291         char tmp[80];
292         t->srcfmt = powerof(t->srcfmt);
293         t->dstfmt = powerof(t->dstfmt);
294         if ((t->srcfmt >= MAX_FORMAT) || (t->dstfmt >= MAX_FORMAT)) {
295                 ast_log(LOG_WARNING, "Format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
296                 return -1;
297         }
298         calc_cost(t);
299         if (option_verbose > 1)
300                 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);
301         ast_mutex_lock(&list_lock);
302         if (!added_cli) {
303                 ast_cli_register(&show_trans);
304                 added_cli++;
305         }
306         t->next = list;
307         list = t;
308         rebuild_matrix();
309         ast_mutex_unlock(&list_lock);
310         return 0;
311 }
312
313 int ast_unregister_translator(struct ast_translator *t)
314 {
315         struct ast_translator *u, *ul = NULL;
316         ast_mutex_lock(&list_lock);
317         u = list;
318         while(u) {
319                 if (u == t) {
320                         if (ul)
321                                 ul->next = u->next;
322                         else
323                                 list = u->next;
324                         break;
325                 }
326                 ul = u;
327                 u = u->next;
328         }
329         rebuild_matrix();
330         ast_mutex_unlock(&list_lock);
331         return (u ? 0 : -1);
332 }
333
334 int ast_translator_best_choice(int *dst, int *srcs)
335 {
336         /* Calculate our best source format, given costs, and a desired destination */
337         int x,y;
338         int best=-1;
339         int bestdst=0;
340         int cur = 1;
341         int besttime=999999999;
342         ast_mutex_lock(&list_lock);
343         for (y=0;y<MAX_FORMAT;y++) {
344                 if ((cur & *dst) && (cur & *srcs)) {
345                         /* This is a common format to both.  Pick it if we don't have one already */
346                         besttime=0;
347                         bestdst = cur;
348                         best = cur;
349                         break;
350                 }
351                 if (cur & *dst)
352                         for (x=0;x<MAX_FORMAT;x++) {
353                                 if (tr_matrix[x][y].step &&     /* There's a step */
354                                  (tr_matrix[x][y].cost < besttime) && /* We're better than what exists now */
355                                         (*srcs & (1 << x)))                     /* x is a valid source format */
356                                         {
357                                                 best = 1 << x;
358                                                 bestdst = cur;
359                                                 besttime = tr_matrix[x][y].cost;
360                                         }
361                         }
362                 cur = cur << 1;
363         }
364         if (best > -1) {
365                 *srcs = best;
366                 *dst = bestdst;
367                 best = 0;
368         }
369         ast_mutex_unlock(&list_lock);
370         return best;
371 }