fix *BSD breakage from include-order changes (bug #4067)
[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 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <sys/time.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <stdio.h>
21
22 #include "asterisk/lock.h"
23 #include "asterisk/channel.h"
24 #include "asterisk/logger.h"
25 #include "asterisk/translate.h"
26 #include "asterisk/options.h"
27 #include "asterisk/frame.h"
28 #include "asterisk/sched.h"
29 #include "asterisk/cli.h"
30 #include "asterisk/term.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 AST_MUTEX_DEFINE_STATIC(list_lock);
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->newpvt();
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->newpvt();
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         ast_cli(fd, "         Translation times between formats (in milliseconds)\n");
352         ast_cli(fd, "          Source Format (Rows) Destination Format(Columns)\n\n");
353         ast_mutex_lock(&list_lock);
354         for (x=-1;x<SHOW_TRANS; x++) {
355                 /* next 2 lines run faster than using strcpy() */
356                 line[0] = ' ';
357                 line[1] = '\0';
358                 for (y=-1;y<SHOW_TRANS;y++) {
359                         if (x >= 0 && y >= 0 && tr_matrix[x][y].step)
360                                 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);
361                         else
362                                 if (((x == -1 && y >= 0) || (y == -1 && x >= 0))) {
363                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), 
364                                                 " %5s", ast_getformatname(1<<(x+y+1)) );
365                                 } else if (x != -1 && y != -1) {
366                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "     -");
367                                 } else {
368                                         snprintf(line + strlen(line), sizeof(line) - strlen(line), "      ");
369                                 }
370                 }
371                 snprintf(line + strlen(line), sizeof(line) - strlen(line), "\n");
372                 ast_cli(fd, line);                      
373         }
374         ast_mutex_unlock(&list_lock);
375         return RESULT_SUCCESS;
376 }
377
378 static int added_cli = 0;
379
380 static char show_trans_usage[] =
381 "Usage: show translation [recalc] [<recalc seconds>]\n"
382 "       Displays known codec translators and the cost associated\n"
383 "with each conversion.  if the arguement 'recalc' is supplied along\n"
384 "with optional number of seconds to test a new test will be performed\n"
385 "as the chart is being displayed.\n";
386
387 static struct ast_cli_entry show_trans =
388 { { "show", "translation", NULL }, show_translation, "Display translation matrix", show_trans_usage };
389
390 int ast_register_translator(struct ast_translator *t)
391 {
392         char tmp[80];
393         t->srcfmt = powerof(t->srcfmt);
394         t->dstfmt = powerof(t->dstfmt);
395         if ((t->srcfmt >= MAX_FORMAT) || (t->dstfmt >= MAX_FORMAT)) {
396                 ast_log(LOG_WARNING, "Format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
397                 return -1;
398         }
399         calc_cost(t,1);
400         if (option_verbose > 1)
401                 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);
402         ast_mutex_lock(&list_lock);
403         if (!added_cli) {
404                 ast_cli_register(&show_trans);
405                 added_cli++;
406         }
407         t->next = list;
408         list = t;
409         rebuild_matrix(0);
410         ast_mutex_unlock(&list_lock);
411         return 0;
412 }
413
414 int ast_unregister_translator(struct ast_translator *t)
415 {
416         char tmp[80];
417         struct ast_translator *u, *ul = NULL;
418         ast_mutex_lock(&list_lock);
419         u = list;
420         while(u) {
421                 if (u == t) {
422                         if (ul)
423                                 ul->next = u->next;
424                         else
425                                 list = u->next;
426                         if (option_verbose > 1)
427                                 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));
428                         break;
429                 }
430                 ul = u;
431                 u = u->next;
432         }
433         rebuild_matrix(0);
434         ast_mutex_unlock(&list_lock);
435         return (u ? 0 : -1);
436 }
437
438 int ast_translator_best_choice(int *dst, int *srcs)
439 {
440         /* Calculate our best source format, given costs, and a desired destination */
441         int x,y;
442         int best = -1;
443         int bestdst = 0;
444         int cur = 1;
445         int besttime = INT_MAX;
446         int common;
447
448         if ((common = (*dst) & (*srcs))) {
449                 /* We have a format in common */
450                 for (y=0; y < MAX_FORMAT; y++) {
451                         if (cur & common) {
452                                 /* This is a common format to both.  Pick it if we don't have one already */
453                                 besttime = 0;
454                                 bestdst = cur;
455                                 best = cur;
456                         }
457                         cur = cur << 1;
458                 }
459         } else {
460                 /* We will need to translate */
461                 ast_mutex_lock(&list_lock);
462                 for (y=0; y < MAX_FORMAT; y++) {
463                         if (cur & *dst)
464                                 for (x=0; x < MAX_FORMAT; x++) {
465                                         if ((*srcs & (1 << x)) &&                       /* x is a valid source format */
466                                             tr_matrix[x][y].step &&                     /* There's a step */
467                                             (tr_matrix[x][y].cost < besttime)) {        /* It's better than what we have so far */
468                                                 best = 1 << x;
469                                                 bestdst = cur;
470                                                 besttime = tr_matrix[x][y].cost;
471                                         }
472                                 }
473                         cur = cur << 1;
474                 }
475                 ast_mutex_unlock(&list_lock);
476         }
477         if (best > -1) {
478                 *srcs = best;
479                 *dst = bestdst;
480                 best = 0;
481         }
482         return best;
483 }