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