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