Add sounds and update config files
[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 /* Uncomment the EXPERIMENTAL_TRANSLATION to enable a more complicated, but probably more
33    correct way of handling full duplex translation */
34
35 /*
36 #define EXPERIMENTAL_TRANSLATION
37 */
38
39 /* This could all be done more efficiently *IF* we chained packets together
40    by default, but it would also complicate virtually every application. */
41    
42 static pthread_mutex_t list_lock = AST_MUTEX_INITIALIZER;
43 static struct ast_translator *list = NULL;
44
45 struct ast_translator_dir {
46         struct ast_translator *step;    /* Next step translator */
47         int cost;                                               /* Complete cost to destination */
48 };
49
50 struct ast_frame_delivery {
51         struct ast_frame *f;
52         struct ast_channel *chan;
53         int fd;
54         struct translator_pvt *owner;
55         struct ast_frame_delivery *prev;
56         struct ast_frame_delivery *next;
57 };
58
59 static struct ast_translator_dir tr_matrix[MAX_FORMAT][MAX_FORMAT];
60
61 struct ast_trans_pvt {
62         struct ast_translator *step;
63         struct ast_translator_pvt *state;
64         struct ast_trans_pvt *next;
65 };
66
67
68 static int powerof(int d)
69 {
70         int x;
71         for (x = 0; x < 32; x++)
72                 if ((1 << x) & d)
73                         return x;
74         ast_log(LOG_WARNING, "Powerof %d: No power??\n", d);
75         return -1;
76 }
77
78 void ast_translator_free_path(struct ast_trans_pvt *p)
79 {
80         struct ast_trans_pvt *pl;
81         while(p) {
82                 pl = p;
83                 p = p->next;
84                 if (pl->state && pl->step->destroy)
85                         pl->step->destroy(pl->state);
86                 free(pl);
87         }
88 }
89
90 struct ast_trans_pvt *ast_translator_build_path(int dest, int source)
91 {
92         struct ast_trans_pvt *tmpr = NULL, *tmp = NULL;
93         /* One of the hardest parts:  Build a set of translators based upon
94            the given source and destination formats */
95         source = powerof(source);
96         dest = powerof(dest);
97         while(source != dest) {
98                 if (tr_matrix[source][dest].step) {
99                         if (tmp) {
100                                 tmp->next = malloc(sizeof(struct ast_trans_pvt));
101                                 tmp = tmp->next;
102                         } else
103                                 tmp = malloc(sizeof(struct ast_trans_pvt));
104
105                                 
106                         if (tmp) {
107                                 tmp->next = NULL;
108                                 tmp->step = tr_matrix[source][dest].step;
109                                 tmp->state = tmp->step->new();
110                                 if (!tmp->state) {
111                                         ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
112                                         free(tmp);
113                                         tmp = NULL;
114                                         return NULL;
115                                 }
116                                 /* Set the root, if it doesn't exist yet... */
117                                 if (!tmpr)
118                                         tmpr = tmp;
119                                 /* Keep going if this isn't the final destination */
120                                 source = tmp->step->dstfmt;
121                         } else {
122                                 /* XXX This could leak XXX */
123                                 ast_log(LOG_WARNING, "Out of memory\n");
124                                 return NULL;
125                         }
126                 } else {
127                         /* We shouldn't have allocated any memory */
128                         ast_log(LOG_WARNING, "No translator path from %d to %d\n", source, dest);
129                         return NULL;
130                 }
131         }
132         return tmpr;
133 }
134
135 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
136 {
137         struct ast_trans_pvt *p;
138         struct ast_frame *out;
139         p = path;
140         /* Feed the first frame into the first translator */
141         p->step->framein(p->state, f);
142         if (consume)
143                 ast_frfree(f);
144         while(p) {
145                 out = p->step->frameout(p->state);
146                 /* If we get nothing out, return NULL */
147                 if (!out)
148                         return NULL;
149                 /* If there is a next state, feed it in there.  If not,
150                    return this frame  */
151                 if (p->next) 
152                         p->next->step->framein(p->next->state, out);
153                 else
154                         return out;
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 %d to %d, via %d\n", tr_matrix[x][z].cost, x, 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 14
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, "                                 Destination Format\n");
262         ast_pthread_mutex_lock(&list_lock);
263         for (x=0;x<SHOW_TRANS; x++) {
264                 if (x == 1) 
265                         strcpy(line, "  Src  ");
266                 else if (x == 2)
267                         strcpy(line, "  Fmt  ");
268                 else
269                         strcpy(line, "       ");
270                 for (y=0;y<SHOW_TRANS;y++) {
271                         if (tr_matrix[x][y].step)
272                                 snprintf(line + strlen(line), sizeof(line) - strlen(line), " %4d", tr_matrix[x][y].cost);
273                         else
274                                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "  n/a");
275                 }
276                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "\n");
277                 ast_cli(fd, line);                      
278         }
279         ast_pthread_mutex_unlock(&list_lock);
280         return RESULT_SUCCESS;
281 }
282
283 static int added_cli = 0;
284
285 static char show_trans_usage[] =
286 "Usage: show translation\n"
287 "       Displays known codec translators and the cost associated\n"
288 "with each conversion.\n";
289
290 static struct ast_cli_entry show_trans =
291 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
292
293 int ast_register_translator(struct ast_translator *t)
294 {
295         char tmp[80];
296         t->srcfmt = powerof(t->srcfmt);
297         t->dstfmt = powerof(t->dstfmt);
298         if ((t->srcfmt >= MAX_FORMAT) || (t->dstfmt >= MAX_FORMAT)) {
299                 ast_log(LOG_WARNING, "Format %d is larger than MAX_FORMAT\n", t->srcfmt);
300                 return -1;
301         }
302         calc_cost(t);
303         if (option_verbose > 1)
304                 ast_verbose(VERBOSE_PREFIX_2 "Registered translator '%s' from format %d to %d, cost %d\n", term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)), t->srcfmt, t->dstfmt, t->cost);
305         ast_pthread_mutex_lock(&list_lock);
306         if (!added_cli) {
307                 ast_cli_register(&show_trans);
308                 added_cli++;
309         }
310         t->next = list;
311         list = t;
312         rebuild_matrix();
313         ast_pthread_mutex_unlock(&list_lock);
314         return 0;
315 }
316
317 int ast_unregister_translator(struct ast_translator *t)
318 {
319         struct ast_translator *u, *ul = NULL;
320         ast_pthread_mutex_lock(&list_lock);
321         u = list;
322         while(u) {
323                 if (u == t) {
324                         if (ul)
325                                 ul->next = u->next;
326                         else
327                                 list = u->next;
328                         break;
329                 }
330                 ul = u;
331                 u = u->next;
332         }
333         rebuild_matrix();
334         ast_pthread_mutex_unlock(&list_lock);
335         return (u ? 0 : -1);
336 }
337
338 int ast_translator_best_choice(int *dst, int *srcs)
339 {
340         /* Calculate our best source format, given costs, and a desired destination */
341         int x,y;
342         int best=-1;
343         int bestdst=0;
344         int cur = 1;
345         int besttime=999999999;
346         ast_pthread_mutex_lock(&list_lock);
347         for (y=0;y<MAX_FORMAT;y++) {
348                 if ((cur & *dst) && (cur & *srcs)) {
349                         /* This is a common format to both.  Pick it if we don't have one already */
350                         besttime=0;
351                         bestdst = cur;
352                         best = cur;
353                         break;
354                 }
355                 if (cur & *dst)
356                         for (x=0;x<MAX_FORMAT;x++) {
357                                 if (tr_matrix[x][y].step &&     /* There's a step */
358                                  (tr_matrix[x][y].cost < besttime) && /* We're better than what exists now */
359                                         (*srcs & (1 << x)))                     /* x is a valid source format */
360                                         {
361                                                 best = 1 << x;
362                                                 bestdst = cur;
363                                                 besttime = tr_matrix[x][y].cost;
364                                         }
365                         }
366                 cur = cur << 1;
367         }
368         if (best > -1) {
369                 *srcs = best;
370                 *dst = bestdst;
371                 best = 0;
372         }
373         ast_pthread_mutex_unlock(&list_lock);
374         return best;
375 }