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