Merge connor's exit context patch (#1737)
[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 #define MAX_RECALC 200 /* max sample recalc */
33
34 /* This could all be done more efficiently *IF* we chained packets together
35    by default, but it would also complicate virtually every application. */
36    
37 static ast_mutex_t list_lock = AST_MUTEX_INITIALIZER;
38 static struct ast_translator *list = NULL;
39
40 struct ast_translator_dir {
41         struct ast_translator *step;    /* Next step translator */
42         int cost;                                               /* Complete cost to destination */
43 };
44
45 struct ast_frame_delivery {
46         struct ast_frame *f;
47         struct ast_channel *chan;
48         int fd;
49         struct translator_pvt *owner;
50         struct ast_frame_delivery *prev;
51         struct ast_frame_delivery *next;
52 };
53
54 static struct ast_translator_dir tr_matrix[MAX_FORMAT][MAX_FORMAT];
55
56 struct ast_trans_pvt {
57         struct ast_translator *step;
58         struct ast_translator_pvt *state;
59         struct ast_trans_pvt *next;
60         struct timeval nextin;
61         struct timeval nextout;
62 };
63
64
65 static int powerof(int d)
66 {
67         int x;
68         for (x = 0; x < 32; x++)
69                 if ((1 << x) & d)
70                         return x;
71         ast_log(LOG_WARNING, "Powerof %d: No power??\n", d);
72         return -1;
73 }
74
75 void ast_translator_free_path(struct ast_trans_pvt *p)
76 {
77         struct ast_trans_pvt *pl, *pn;
78         pn = p;
79         while(pn) {
80                 pl = pn;
81                 pn = pn->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->nextin.tv_sec = 0;
107                                 tmp->nextin.tv_usec = 0;
108                                 tmp->nextout.tv_sec = 0;
109                                 tmp->nextout.tv_usec = 0;
110                                 tmp->step = tr_matrix[source][dest].step;
111                                 tmp->state = tmp->step->new();
112                                 if (!tmp->state) {
113                                         ast_log(LOG_WARNING, "Failed to build translator step from %d to %d\n", source, dest);
114                                         free(tmp);
115                                         tmp = NULL;
116                                         return NULL;
117                                 }
118                                 /* Set the root, if it doesn't exist yet... */
119                                 if (!tmpr)
120                                         tmpr = tmp;
121                                 /* Keep going if this isn't the final destination */
122                                 source = tmp->step->dstfmt;
123                         } else {
124                                 /* XXX This could leak XXX */
125                                 ast_log(LOG_WARNING, "Out of memory\n");
126                                 return NULL;
127                         }
128                 } else {
129                         /* We shouldn't have allocated any memory */
130                         ast_log(LOG_WARNING, "No translator path from %s to %s\n", 
131                                 ast_getformatname(source), ast_getformatname(dest));
132                         return NULL;
133                 }
134         }
135         return tmpr;
136 }
137
138 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
139 {
140         struct ast_trans_pvt *p;
141         struct ast_frame *out;
142         struct timeval delivery;
143         p = path;
144         /* Feed the first frame into the first translator */
145         p->step->framein(p->state, f);
146         if (f->delivery.tv_sec || f->delivery.tv_usec) {
147                 if (path->nextin.tv_sec || path->nextin.tv_usec) {
148                         /* Make sure this is in line with what we were expecting */
149                         if ((path->nextin.tv_sec != f->delivery.tv_sec) ||
150                             (path->nextin.tv_usec != f->delivery.tv_usec)) {
151                                 /* The time has changed between what we expected and this
152                                    most recent time on the new packet.  Adjust our output
153                                    time appropriately */
154                                 long sdiff;
155                                 long udiff;
156                                 sdiff = f->delivery.tv_sec - path->nextin.tv_sec;
157                                 udiff = f->delivery.tv_usec - path->nextin.tv_usec;
158                                 path->nextin.tv_sec = f->delivery.tv_sec;
159                                 path->nextin.tv_usec = f->delivery.tv_usec;
160                                 path->nextout.tv_sec += sdiff;
161                                 path->nextout.tv_usec += udiff;
162                                 if (path->nextout.tv_usec < 0) {
163                                         path->nextout.tv_usec += 1000000;
164                                         path->nextout.tv_sec--;
165                                 } else if (path->nextout.tv_usec >= 1000000) {
166                                         path->nextout.tv_usec -= 1000000;
167                                         path->nextout.tv_sec++;
168                                 }
169                         }
170                 } else {
171                         /* This is our first pass.  Make sure the timing looks good */
172                         path->nextin.tv_sec = f->delivery.tv_sec;
173                         path->nextin.tv_usec = f->delivery.tv_usec;
174                         path->nextout.tv_sec = f->delivery.tv_sec;
175                         path->nextout.tv_usec = f->delivery.tv_usec;
176                 }
177                 /* Predict next incoming sample */
178                 path->nextin.tv_sec += (f->samples / 8000);
179                 path->nextin.tv_usec += ((f->samples % 8000) * 125);
180                 if (path->nextin.tv_usec >= 1000000) {
181                         path->nextin.tv_usec -= 1000000;
182                         path->nextin.tv_sec++;
183                 }
184         }
185         delivery.tv_sec = f->delivery.tv_sec;
186         delivery.tv_usec = f->delivery.tv_usec;
187         if (consume)
188                 ast_frfree(f);
189         while(p) {
190                 out = p->step->frameout(p->state);
191                 /* If we get nothing out, return NULL */
192                 if (!out)
193                         return NULL;
194                 /* If there is a next state, feed it in there.  If not,
195                    return this frame  */
196                 if (p->next) 
197                         p->next->step->framein(p->next->state, out);
198                 else {
199                         if (delivery.tv_sec || delivery.tv_usec) {
200                                 /* Use next predicted outgoing timestamp */
201                                 out->delivery.tv_sec = path->nextout.tv_sec;
202                                 out->delivery.tv_usec = path->nextout.tv_usec;
203                                 
204                                 /* Predict next outgoing timestamp from samples in this
205                                    frame. */
206                                 path->nextout.tv_sec += (out->samples / 8000);
207                                 path->nextout.tv_usec += ((out->samples % 8000) * 125);
208                                 if (path->nextout.tv_usec >= 1000000) {
209                                         path->nextout.tv_sec++;
210                                         path->nextout.tv_usec -= 1000000;
211                                 }
212                         } else {
213                                 out->delivery.tv_sec = 0;
214                                 out->delivery.tv_usec = 0;
215                         }
216                         return out;
217                 }
218                 p = p->next;
219         }
220         ast_log(LOG_WARNING, "I should never get here...\n");
221         return NULL;
222 }
223
224
225 static void calc_cost(struct ast_translator *t,int samples)
226 {
227         int sofar=0;
228         struct ast_translator_pvt *pvt;
229         struct ast_frame *f, *out;
230         struct timeval start, finish;
231         int cost;
232         if(!samples)
233           samples = 1;
234         
235         /* If they don't make samples, give them a terrible score */
236         if (!t->sample) {
237                 ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
238                 t->cost = 99999;
239                 return;
240         }
241         pvt = t->new();
242         if (!pvt) {
243                 ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
244                 t->cost = 99999;
245                 return;
246         }
247         gettimeofday(&start, NULL);
248         /* Call the encoder until we've processed one second of time */
249         while(sofar < samples * 8000) {
250                 f = t->sample();
251                 if (!f) {
252                         ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
253                         t->destroy(pvt);
254                         t->cost = 99999;
255                         return;
256                 }
257                 t->framein(pvt, f);
258                 ast_frfree(f);
259                 while((out = t->frameout(pvt))) {
260                         sofar += out->samples;
261                         ast_frfree(out);
262                 }
263         }
264         gettimeofday(&finish, NULL);
265         t->destroy(pvt);
266         cost = (finish.tv_sec - start.tv_sec) * 1000 + (finish.tv_usec - start.tv_usec) / 1000;
267         t->cost = cost / samples;
268         if (!t->cost)
269                 t->cost = 1;
270 }
271
272 static void rebuild_matrix(int samples)
273 {
274         struct ast_translator *t;
275         int changed;
276         int x,y,z;
277         if (option_debug)
278                 ast_log(LOG_DEBUG, "Reseting translation matrix\n");
279         /* Use the list of translators to build a translation matrix */
280         bzero(tr_matrix, sizeof(tr_matrix));
281         t = list;
282         while(t) {
283           if(samples)
284             calc_cost(t,samples);
285           
286                 if (!tr_matrix[t->srcfmt][t->dstfmt].step ||
287                      tr_matrix[t->srcfmt][t->dstfmt].cost > t->cost) {
288                         tr_matrix[t->srcfmt][t->dstfmt].step = t;
289                         tr_matrix[t->srcfmt][t->dstfmt].cost = t->cost;
290                 }
291                 t = t->next;
292         }
293         do {
294                 changed = 0;
295                 /* Don't you just love O(N^3) operations? */
296                 for (x=0; x< MAX_FORMAT; x++)                           /* For each source format */
297                         for (y=0; y < MAX_FORMAT; y++)                  /* And each destination format */
298                                 if (x != y)                                                     /* Except ourselves, of course */
299                                         for (z=0; z < MAX_FORMAT; z++)  /* And each format it might convert to */
300                                                 if ((x!=z) && (y!=z))           /* Don't ever convert back to us */
301                                                         if (tr_matrix[x][y].step && /* We can convert from x to y */
302                                                                 tr_matrix[y][z].step && /* And from y to z and... */
303                                                                 (!tr_matrix[x][z].step ||       /* Either there isn't an x->z conversion */
304                                                                 (tr_matrix[x][y].cost + 
305                                                                  tr_matrix[y][z].cost < /* Or we're cheaper than the existing */
306                                                                  tr_matrix[x][z].cost)  /* solution */
307                                                              )) {
308                                                                                         /* We can get from x to z via y with a cost that
309                                                                                            is the sum of the transition from x to y and
310                                                                                            from y to z */
311                                                                  
312                                                                         tr_matrix[x][z].step = tr_matrix[x][y].step;
313                                                                         tr_matrix[x][z].cost = tr_matrix[x][y].cost + 
314                                                                                                                    tr_matrix[y][z].cost;
315                                                                         if (option_debug)
316                                                                                 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);
317                                                                         changed++;
318                                                                  }
319                 
320         } while (changed);
321 }
322
323
324
325
326
327 static int show_translation(int fd, int argc, char *argv[])
328 {
329 #define SHOW_TRANS 11
330         int x,y,z;
331         char line[80];
332         if (argc > 4) 
333                 return RESULT_SHOWUSAGE;
334
335         if(argv[2] && !strcasecmp(argv[2],"recalc")) {
336           z = argv[3] ? atoi(argv[3]) : 1;
337
338           if(z <= 0) {
339             ast_cli(fd,"         C'mon let's be serious here... defaulting to 1.\n");
340             z = 1;
341           }
342           
343           if(z > MAX_RECALC) {
344             ast_cli(fd,"         Maximum limit of recalc exceeded by %d, truncating value to %d\n",z-MAX_RECALC,MAX_RECALC);
345             z = MAX_RECALC;
346           }
347           ast_cli(fd,"         Recalculating Codec Translation (number of sample seconds: %d)\n\n",z);
348           rebuild_matrix(z);
349
350         }
351
352         ast_cli(fd, "         Translation times between formats (in milliseconds)\n");
353         ast_cli(fd, "          Source Format (Rows) Destination Format(Columns)\n\n");
354         ast_mutex_lock(&list_lock);
355         for (x=-1;x<SHOW_TRANS; x++) {
356                 strcpy(line, " ");
357                 for (y=-1;y<SHOW_TRANS;y++) {
358                         if (x >= 0 && y >= 0 && tr_matrix[x][y].step)
359                                 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);
360                         else
361                                 if (((x == -1 && y >= 0) || (y == -1 && x >= 0))) {
362                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), 
363                                                 " %5s", ast_getformatname(1<<(x+y+1)) );
364                                 } else if (x != -1 && y != -1) {
365                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "     -");
366                                 } else {
367                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "      ");
368                                 }
369                 }
370                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "\n");
371                 ast_cli(fd, line);                      
372         }
373         ast_mutex_unlock(&list_lock);
374         return RESULT_SUCCESS;
375 }
376
377 static int added_cli = 0;
378
379 static char show_trans_usage[] =
380 "Usage: show translation [recalc] [<recalc seconds>]\n"
381 "       Displays known codec translators and the cost associated\n"
382 "with each conversion.  if the arguement 'recalc' is supplied along\n"
383 "with optional number of seconds to test a new test will be performed\n"
384 "as the chart is being displayed.\n";
385
386 static struct ast_cli_entry show_trans =
387 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
388
389 int ast_register_translator(struct ast_translator *t)
390 {
391         char tmp[80];
392         t->srcfmt = powerof(t->srcfmt);
393         t->dstfmt = powerof(t->dstfmt);
394         if ((t->srcfmt >= MAX_FORMAT) || (t->dstfmt >= MAX_FORMAT)) {
395                 ast_log(LOG_WARNING, "Format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
396                 return -1;
397         }
398         calc_cost(t,1);
399         if (option_verbose > 1)
400                 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);
401         ast_mutex_lock(&list_lock);
402         if (!added_cli) {
403                 ast_cli_register(&show_trans);
404                 added_cli++;
405         }
406         t->next = list;
407         list = t;
408         rebuild_matrix(0);
409         ast_mutex_unlock(&list_lock);
410         return 0;
411 }
412
413 int ast_unregister_translator(struct ast_translator *t)
414 {
415         char tmp[80];
416         struct ast_translator *u, *ul = NULL;
417         ast_mutex_lock(&list_lock);
418         u = list;
419         while(u) {
420                 if (u == t) {
421                         if (ul)
422                                 ul->next = u->next;
423                         else
424                                 list = u->next;
425                         if (option_verbose > 1)
426                                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered translator '%s' from format %s to %s\n", term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)), ast_getformatname(1 << t->srcfmt), ast_getformatname(1 << t->dstfmt));
427                         break;
428                 }
429                 ul = u;
430                 u = u->next;
431         }
432         rebuild_matrix(0);
433         ast_mutex_unlock(&list_lock);
434         return (u ? 0 : -1);
435 }
436
437 int ast_translator_best_choice(int *dst, int *srcs)
438 {
439         /* Calculate our best source format, given costs, and a desired destination */
440         int x,y;
441         int best=-1;
442         int bestdst=0;
443         int cur = 1;
444         int besttime=999999999;
445         ast_mutex_lock(&list_lock);
446         for (y=0;y<MAX_FORMAT;y++) {
447                 if ((cur & *dst) && (cur & *srcs)) {
448                         /* This is a common format to both.  Pick it if we don't have one already */
449                         besttime=0;
450                         bestdst = cur;
451                         best = cur;
452                         break;
453                 }
454                 if (cur & *dst)
455                         for (x=0;x<MAX_FORMAT;x++) {
456                                 if (tr_matrix[x][y].step &&     /* There's a step */
457                                  (tr_matrix[x][y].cost < besttime) && /* We're better than what exists now */
458                                         (*srcs & (1 << x)))                     /* x is a valid source format */
459                                         {
460                                                 best = 1 << x;
461                                                 bestdst = cur;
462                                                 besttime = tr_matrix[x][y].cost;
463                                         }
464                         }
465                 cur = cur << 1;
466         }
467         if (best > -1) {
468                 *srcs = best;
469                 *dst = bestdst;
470                 best = 0;
471         }
472         ast_mutex_unlock(&list_lock);
473         return best;
474 }