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