e2e6324f40228627658926c526cdade1c9b1254f
[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         struct timeval delivery;
134         p = path;
135         /* Feed the first frame into the first translator */
136         p->step->framein(p->state, f);
137         delivery.tv_sec = f->delivery.tv_sec;
138         delivery.tv_usec = f->delivery.tv_usec;
139         if (consume)
140                 ast_frfree(f);
141         while(p) {
142                 out = p->step->frameout(p->state);
143                 /* If we get nothing out, return NULL */
144                 if (!out)
145                         return NULL;
146                 /* If there is a next state, feed it in there.  If not,
147                    return this frame  */
148                 if (p->next) 
149                         p->next->step->framein(p->next->state, out);
150                 else {
151                         out->delivery.tv_sec = delivery.tv_sec;
152                         out->delivery.tv_usec = delivery.tv_usec;
153                         return out;
154                 }
155                 p = p->next;
156         }
157         ast_log(LOG_WARNING, "I should never get here...\n");
158         return NULL;
159 }
160
161 static void rebuild_matrix(void)
162 {
163         struct ast_translator *t;
164         int changed;
165         int x,y,z;
166         if (option_debug)
167                 ast_log(LOG_DEBUG, "Reseting translation matrix\n");
168         /* Use the list of translators to build a translation matrix */
169         bzero(tr_matrix, sizeof(tr_matrix));
170         t = list;
171         while(t) {
172                 if (!tr_matrix[t->srcfmt][t->dstfmt].step ||
173                      tr_matrix[t->srcfmt][t->dstfmt].cost > t->cost) {
174                         tr_matrix[t->srcfmt][t->dstfmt].step = t;
175                         tr_matrix[t->srcfmt][t->dstfmt].cost = t->cost;
176                 }
177                 t = t->next;
178         }
179         do {
180                 changed = 0;
181                 /* Don't you just love O(N^3) operations? */
182                 for (x=0; x< MAX_FORMAT; x++)                           /* For each source format */
183                         for (y=0; y < MAX_FORMAT; y++)                  /* And each destination format */
184                                 if (x != y)                                                     /* Except ourselves, of course */
185                                         for (z=0; z < MAX_FORMAT; z++)  /* And each format it might convert to */
186                                                 if ((x!=z) && (y!=z))           /* Don't ever convert back to us */
187                                                         if (tr_matrix[x][y].step && /* We can convert from x to y */
188                                                                 tr_matrix[y][z].step && /* And from y to z and... */
189                                                                 (!tr_matrix[x][z].step ||       /* Either there isn't an x->z conversion */
190                                                                 (tr_matrix[x][y].cost + 
191                                                                  tr_matrix[y][z].cost < /* Or we're cheaper than the existing */
192                                                                  tr_matrix[x][z].cost)  /* solution */
193                                                              )) {
194                                                                                         /* We can get from x to z via y with a cost that
195                                                                                            is the sum of the transition from x to y and
196                                                                                            from y to z */
197                                                                  
198                                                                         tr_matrix[x][z].step = tr_matrix[x][y].step;
199                                                                         tr_matrix[x][z].cost = tr_matrix[x][y].cost + 
200                                                                                                                    tr_matrix[y][z].cost;
201                                                                         if (option_debug)
202                                                                                 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);
203                                                                         changed++;
204                                                                  }
205                 
206         } while (changed);
207 }
208
209 static void calc_cost(struct ast_translator *t)
210 {
211         int sofar=0;
212         struct ast_translator_pvt *pvt;
213         struct ast_frame *f, *out;
214         struct timeval start, finish;
215         int cost;
216         /* If they don't make samples, give them a terrible score */
217         if (!t->sample) {
218                 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
219                 t->cost = 99999;
220                 return;
221         }
222         pvt = t->new();
223         if (!pvt) {
224                 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
225                 t->cost = 99999;
226                 return;
227         }
228         gettimeofday(&start, NULL);
229         /* Call the encoder until we've processed one second of time */
230         while(sofar < 8000) {
231                 f = t->sample();
232                 if (!f) {
233                         ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
234                         t->destroy(pvt);
235                         t->cost = 99999;
236                         return;
237                 }
238                 t->framein(pvt, f);
239                 ast_frfree(f);
240                 while((out = t->frameout(pvt))) {
241                         sofar += out->samples;
242                         ast_frfree(out);
243                 }
244         }
245         gettimeofday(&finish, NULL);
246         t->destroy(pvt);
247         cost = (finish.tv_sec - start.tv_sec) * 1000 + (finish.tv_usec - start.tv_usec) / 1000;
248         t->cost = cost;
249         if (!t->cost)
250                 t->cost = 1;
251 }
252
253 static int show_translation(int fd, int argc, char *argv[])
254 {
255 #define SHOW_TRANS 11
256         int x,y;
257         char line[80];
258         if (argc != 2) 
259                 return RESULT_SHOWUSAGE;
260         ast_cli(fd, "         Translation times between formats (in milliseconds)\n");
261         ast_cli(fd, "          Source Format (Rows) Destination Format(Columns)\n\n");
262         ast_mutex_lock(&list_lock);
263         for (x=-1;x<SHOW_TRANS; x++) {
264                 strcpy(line, " ");
265                 for (y=-1;y<SHOW_TRANS;y++) {
266                         if (x >= 0 && y >= 0 && tr_matrix[x][y].step)
267                                 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);
268                         else
269                                 if (((x == -1 && y >= 0) || (y == -1 && x >= 0))) {
270                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), 
271                                                 " %5s", ast_getformatname(1<<(x+y+1)) );
272                                 } else if (x != -1 && y != -1) {
273                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "     -");
274                                 } else {
275                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "      ");
276                                 }
277                 }
278                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "\n");
279                 ast_cli(fd, line);                      
280         }
281         ast_mutex_unlock(&list_lock);
282         return RESULT_SUCCESS;
283 }
284
285 static int added_cli = 0;
286
287 static char show_trans_usage[] =
288 "Usage: show translation\n"
289 "       Displays known codec translators and the cost associated\n"
290 "with each conversion.\n";
291
292 static struct ast_cli_entry show_trans =
293 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
294
295 int ast_register_translator(struct ast_translator *t)
296 {
297         char tmp[80];
298         t->srcfmt = powerof(t->srcfmt);
299         t->dstfmt = powerof(t->dstfmt);
300         if ((t->srcfmt >= MAX_FORMAT) || (t->dstfmt >= MAX_FORMAT)) {
301                 ast_log(LOG_WARNING, "Format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
302                 return -1;
303         }
304         calc_cost(t);
305         if (option_verbose > 1)
306                 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);
307         ast_mutex_lock(&list_lock);
308         if (!added_cli) {
309                 ast_cli_register(&show_trans);
310                 added_cli++;
311         }
312         t->next = list;
313         list = t;
314         rebuild_matrix();
315         ast_mutex_unlock(&list_lock);
316         return 0;
317 }
318
319 int ast_unregister_translator(struct ast_translator *t)
320 {
321         struct ast_translator *u, *ul = NULL;
322         ast_mutex_lock(&list_lock);
323         u = list;
324         while(u) {
325                 if (u == t) {
326                         if (ul)
327                                 ul->next = u->next;
328                         else
329                                 list = u->next;
330                         break;
331                 }
332                 ul = u;
333                 u = u->next;
334         }
335         rebuild_matrix();
336         ast_mutex_unlock(&list_lock);
337         return (u ? 0 : -1);
338 }
339
340 int ast_translator_best_choice(int *dst, int *srcs)
341 {
342         /* Calculate our best source format, given costs, and a desired destination */
343         int x,y;
344         int best=-1;
345         int bestdst=0;
346         int cur = 1;
347         int besttime=999999999;
348         ast_mutex_lock(&list_lock);
349         for (y=0;y<MAX_FORMAT;y++) {
350                 if ((cur & *dst) && (cur & *srcs)) {
351                         /* This is a common format to both.  Pick it if we don't have one already */
352                         besttime=0;
353                         bestdst = cur;
354                         best = cur;
355                         break;
356                 }
357                 if (cur & *dst)
358                         for (x=0;x<MAX_FORMAT;x++) {
359                                 if (tr_matrix[x][y].step &&     /* There's a step */
360                                  (tr_matrix[x][y].cost < besttime) && /* We're better than what exists now */
361                                         (*srcs & (1 << x)))                     /* x is a valid source format */
362                                         {
363                                                 best = 1 << x;
364                                                 bestdst = cur;
365                                                 besttime = tr_matrix[x][y].cost;
366                                         }
367                         }
368                 cur = cur << 1;
369         }
370         if (best > -1) {
371                 *srcs = best;
372                 *dst = bestdst;
373                 best = 0;
374         }
375         ast_mutex_unlock(&list_lock);
376         return best;
377 }