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