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