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