But we can change the API here.
[asterisk/asterisk.git] / main / frame.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Frame and codec manipulation routines
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31 #include "asterisk/lock.h"
32 #include "asterisk/frame.h"
33 #include "asterisk/channel.h"
34 #include "asterisk/cli.h"
35 #include "asterisk/term.h"
36 #include "asterisk/utils.h"
37 #include "asterisk/threadstorage.h"
38 #include "asterisk/linkedlists.h"
39 #include "asterisk/translate.h"
40
41 #ifdef TRACE_FRAMES
42 static int headers;
43 static AST_LIST_HEAD_STATIC(headerlist, ast_frame);
44 #endif
45
46 #if !defined(LOW_MEMORY)
47 static void frame_cache_cleanup(void *data);
48
49 /*! \brief A per-thread cache of frame headers */
50 AST_THREADSTORAGE_CUSTOM(frame_cache, NULL, frame_cache_cleanup);
51
52 /*! 
53  * \brief Maximum ast_frame cache size
54  *
55  * In most cases where the frame header cache will be useful, the size
56  * of the cache will stay very small.  However, it is not always the case that
57  * the same thread that allocates the frame will be the one freeing them, so
58  * sometimes a thread will never have any frames in its cache, or the cache
59  * will never be pulled from.  For the latter case, we limit the maximum size. 
60  */ 
61 #define FRAME_CACHE_MAX_SIZE    10
62
63 /*! \brief This is just so ast_frames, a list head struct for holding a list of
64  *  ast_frame structures, is defined. */
65 AST_LIST_HEAD_NOLOCK(ast_frames, ast_frame);
66
67 struct ast_frame_cache {
68         struct ast_frames list;
69         size_t size;
70 };
71 #endif
72
73 #define SMOOTHER_SIZE 8000
74
75 enum frame_type {
76         TYPE_HIGH,     /* 0x0 */
77         TYPE_LOW,      /* 0x1 */
78         TYPE_SILENCE,  /* 0x2 */
79         TYPE_DONTSEND  /* 0x3 */
80 };
81
82 #define TYPE_MASK 0x3
83
84 struct ast_smoother {
85         int size;
86         int format;
87         int readdata;
88         int flags;
89         float samplesperbyte;
90         struct ast_frame f;
91         struct timeval delivery;
92         char data[SMOOTHER_SIZE];
93         char framedata[SMOOTHER_SIZE + AST_FRIENDLY_OFFSET];
94         struct ast_frame *opt;
95         int len;
96 };
97
98 /*! \brief Definition of supported media formats (codecs) */
99 static struct ast_format_list AST_FORMAT_LIST[] = {
100         { AST_FORMAT_G723_1 , "g723", 8000, "G.723.1", 20, 30, 300, 30, 30 },                                  /*!< G723.1 */
101         { AST_FORMAT_GSM, "gsm", 8000, "GSM", 33, 20, 300, 20, 20 },                                           /*!< codec_gsm.c */
102         { AST_FORMAT_ULAW, "ulaw", 8000, "G.711 u-law", 80, 10, 150, 10, 20 },                                 /*!< codec_ulaw.c */
103         { AST_FORMAT_ALAW, "alaw", 8000, "G.711 A-law", 80, 10, 150, 10, 20 },                                 /*!< codec_alaw.c */
104         { AST_FORMAT_G726, "g726", 8000, "G.726 RFC3551", 40, 10, 300, 10, 20 },                               /*!< codec_g726.c */
105         { AST_FORMAT_ADPCM, "adpcm" , 8000, "ADPCM", 40, 10, 300, 10, 20 },                                    /*!< codec_adpcm.c */
106         { AST_FORMAT_SLINEAR, "slin", 8000, "16 bit Signed Linear PCM", 160, 10, 70, 10, 20, AST_SMOOTHER_FLAG_BE }, /*!< Signed linear */
107         { AST_FORMAT_LPC10, "lpc10", 8000, "LPC10", 7, 20, 20, 20, 20 },                                       /*!< codec_lpc10.c */ 
108         { AST_FORMAT_G729A, "g729", 8000, "G.729A", 10, 10, 230, 10, 20, AST_SMOOTHER_FLAG_G729 },             /*!< Binary commercial distribution */
109         { AST_FORMAT_SPEEX, "speex", 8000, "SpeeX", 10, 10, 60, 10, 20 },                                      /*!< codec_speex.c */
110         { AST_FORMAT_ILBC, "ilbc", 8000, "iLBC", 50, 30, 30, 30, 30 },                                         /*!< codec_ilbc.c */ /* inc=30ms - workaround */
111         { AST_FORMAT_G726_AAL2, "g726aal2", 8000, "G.726 AAL2", 40, 10, 300, 10, 20 },                         /*!< codec_g726.c */
112         { AST_FORMAT_G722, "g722", 16000, "G722", 80, 10, 150, 10, 20 },                                       /*!< codec_g722.c */
113         { AST_FORMAT_SLINEAR16, "slin16", 16000, "16 bit Signed Linear PCM (16kHz)", 320, 10, 70, 10, 20 },    /*!< Signed linear (16kHz) */
114         { AST_FORMAT_JPEG, "jpeg", 0, "JPEG image"},                                                           /*!< See format_jpeg.c */
115         { AST_FORMAT_PNG, "png", 0, "PNG image"},                                                              /*!< PNG Image format */
116         { AST_FORMAT_H261, "h261", 0, "H.261 Video" },                                                         /*!< H.261 Video Passthrough */
117         { AST_FORMAT_H263, "h263", 0, "H.263 Video" },                                                         /*!< H.263 Passthrough support, see format_h263.c */
118         { AST_FORMAT_H263_PLUS, "h263p", 0, "H.263+ Video" },                                                  /*!< H.263plus passthrough support See format_h263.c */
119         { AST_FORMAT_H264, "h264", 0, "H.264 Video" },                                                         /*!< Passthrough support, see format_h263.c */
120         { AST_FORMAT_MP4_VIDEO, "mpeg4", 0, "MPEG4 Video" },                                                   /*!< Passthrough support for MPEG4 */
121         { AST_FORMAT_T140, "t140", 0, "Passthrough T.140 Realtime Text" },                                     /*!< Passthrough support for T.140 Realtime Text */
122 };
123
124 struct ast_frame ast_null_frame = { AST_FRAME_NULL, };
125
126 void ast_smoother_reset(struct ast_smoother *s, int size)
127 {
128         memset(s, 0, sizeof(*s));
129         s->size = size;
130 }
131
132 struct ast_smoother *ast_smoother_new(int size)
133 {
134         struct ast_smoother *s;
135         if (size < 1)
136                 return NULL;
137         if ((s = ast_malloc(sizeof(*s))))
138                 ast_smoother_reset(s, size);
139         return s;
140 }
141
142 int ast_smoother_get_flags(struct ast_smoother *s)
143 {
144         return s->flags;
145 }
146
147 void ast_smoother_set_flags(struct ast_smoother *s, int flags)
148 {
149         s->flags = flags;
150 }
151
152 int ast_smoother_test_flag(struct ast_smoother *s, int flag)
153 {
154         return (s->flags & flag);
155 }
156
157 int __ast_smoother_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
158 {
159         if (f->frametype != AST_FRAME_VOICE) {
160                 ast_log(LOG_WARNING, "Huh?  Can't smooth a non-voice frame!\n");
161                 return -1;
162         }
163         if (!s->format) {
164                 s->format = f->subclass;
165                 s->samplesperbyte = (float)f->samples / (float)f->datalen;
166         } else if (s->format != f->subclass) {
167                 ast_log(LOG_WARNING, "Smoother was working on %d format frames, now trying to feed %d?\n", s->format, f->subclass);
168                 return -1;
169         }
170         if (s->len + f->datalen > SMOOTHER_SIZE) {
171                 ast_log(LOG_WARNING, "Out of smoother space\n");
172                 return -1;
173         }
174         if (((f->datalen == s->size) || ((f->datalen < 10) && (s->flags & AST_SMOOTHER_FLAG_G729)))
175                                  && !s->opt && (f->offset >= AST_MIN_OFFSET)) {
176                 if (!s->len) {
177                         /* Optimize by sending the frame we just got
178                            on the next read, thus eliminating the douple
179                            copy */
180                         if (swap)
181                                 ast_swapcopy_samples(f->data, f->data, f->samples);
182                         s->opt = f;
183                         return 0;
184                 }
185         }
186         if (s->flags & AST_SMOOTHER_FLAG_G729) {
187                 if (s->len % 10) {
188                         ast_log(LOG_NOTICE, "Dropping extra frame of G.729 since we already have a VAD frame at the end\n");
189                         return 0;
190                 }
191         }
192         if (swap)
193                 ast_swapcopy_samples(s->data+s->len, f->data, f->samples);
194         else
195                 memcpy(s->data + s->len, f->data, f->datalen);
196         /* If either side is empty, reset the delivery time */
197         if (!s->len || ast_tvzero(f->delivery) || ast_tvzero(s->delivery))      /* XXX really ? */
198                 s->delivery = f->delivery;
199         s->len += f->datalen;
200         return 0;
201 }
202
203 struct ast_frame *ast_smoother_read(struct ast_smoother *s)
204 {
205         struct ast_frame *opt;
206         int len;
207
208         /* IF we have an optimization frame, send it */
209         if (s->opt) {
210                 if (s->opt->offset < AST_FRIENDLY_OFFSET)
211                         ast_log(LOG_WARNING, "Returning a frame of inappropriate offset (%d).\n",
212                                                         s->opt->offset);
213                 opt = s->opt;
214                 s->opt = NULL;
215                 return opt;
216         }
217
218         /* Make sure we have enough data */
219         if (s->len < s->size) {
220                 /* Or, if this is a G.729 frame with VAD on it, send it immediately anyway */
221                 if (!((s->flags & AST_SMOOTHER_FLAG_G729) && (s->size % 10)))
222                         return NULL;
223         }
224         len = s->size;
225         if (len > s->len)
226                 len = s->len;
227         /* Make frame */
228         s->f.frametype = AST_FRAME_VOICE;
229         s->f.subclass = s->format;
230         s->f.data = s->framedata + AST_FRIENDLY_OFFSET;
231         s->f.offset = AST_FRIENDLY_OFFSET;
232         s->f.datalen = len;
233         /* Samples will be improper given VAD, but with VAD the concept really doesn't even exist */
234         s->f.samples = len * s->samplesperbyte; /* XXX rounding */
235         s->f.delivery = s->delivery;
236         /* Fill Data */
237         memcpy(s->f.data, s->data, len);
238         s->len -= len;
239         /* Move remaining data to the front if applicable */
240         if (s->len) {
241                 /* In principle this should all be fine because if we are sending
242                    G.729 VAD, the next timestamp will take over anyawy */
243                 memmove(s->data, s->data + len, s->len);
244                 if (!ast_tvzero(s->delivery)) {
245                         /* If we have delivery time, increment it, otherwise, leave it at 0 */
246                         s->delivery = ast_tvadd(s->delivery, ast_samp2tv(s->f.samples, 8000));
247                 }
248         }
249         /* Return frame */
250         return &s->f;
251 }
252
253 void ast_smoother_free(struct ast_smoother *s)
254 {
255         ast_free(s);
256 }
257
258 static struct ast_frame *ast_frame_header_new(void)
259 {
260         struct ast_frame *f;
261
262 #if !defined(LOW_MEMORY)
263         struct ast_frame_cache *frames;
264
265         if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
266                 if ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list))) {
267                         size_t mallocd_len = f->mallocd_hdr_len;
268                         memset(f, 0, sizeof(*f));
269                         f->mallocd_hdr_len = mallocd_len;
270                         f->mallocd = AST_MALLOCD_HDR;
271                         frames->size--;
272                         return f;
273                 }
274         }
275         if (!(f = ast_calloc_cache(1, sizeof(*f))))
276                 return NULL;
277 #else
278         if (!(f = ast_calloc(1, sizeof(*f))))
279                 return NULL;
280 #endif
281
282         f->mallocd_hdr_len = sizeof(*f);
283 #ifdef TRACE_FRAMES
284         AST_LIST_LOCK(&headerlist);
285         headers++;
286         AST_LIST_INSERT_HEAD(&headerlist, f, frame_list);
287         AST_LIST_UNLOCK(&headerlist);
288 #endif  
289         
290         return f;
291 }
292
293 #if !defined(LOW_MEMORY)
294 static void frame_cache_cleanup(void *data)
295 {
296         struct ast_frame_cache *frames = data;
297         struct ast_frame *f;
298
299         while ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list)))
300                 ast_free(f);
301         
302         ast_free(frames);
303 }
304 #endif
305
306 void ast_frame_free(struct ast_frame *fr, int cache)
307 {
308         if (ast_test_flag(fr, AST_FRFLAG_FROM_TRANSLATOR))
309                 ast_translate_frame_freed(fr);
310
311         if (!fr->mallocd)
312                 return;
313
314 #if !defined(LOW_MEMORY)
315         if (cache && fr->mallocd == AST_MALLOCD_HDR) {
316                 /* Cool, only the header is malloc'd, let's just cache those for now 
317                  * to keep things simple... */
318                 struct ast_frame_cache *frames;
319
320                 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames))) 
321                     && frames->size < FRAME_CACHE_MAX_SIZE) {
322                         AST_LIST_INSERT_HEAD(&frames->list, fr, frame_list);
323                         frames->size++;
324                         return;
325                 }
326         }
327 #endif
328         
329         if (fr->mallocd & AST_MALLOCD_DATA) {
330                 if (fr->data) 
331                         ast_free(fr->data - fr->offset);
332         }
333         if (fr->mallocd & AST_MALLOCD_SRC) {
334                 if (fr->src)
335                         ast_free((char *)fr->src);
336         }
337         if (fr->mallocd & AST_MALLOCD_HDR) {
338 #ifdef TRACE_FRAMES
339                 AST_LIST_LOCK(&headerlist);
340                 headers--;
341                 AST_LIST_REMOVE(&headerlist, fr, frame_list);
342                 AST_LIST_UNLOCK(&headerlist);
343 #endif                  
344                 ast_free(fr);
345         }
346 }
347
348 /*!
349  * \brief 'isolates' a frame by duplicating non-malloc'ed components
350  * (header, src, data).
351  * On return all components are malloc'ed
352  */
353 struct ast_frame *ast_frisolate(struct ast_frame *fr)
354 {
355         struct ast_frame *out;
356         void *newdata;
357
358         ast_clear_flag(fr, AST_FRFLAG_FROM_TRANSLATOR);
359
360         if (!(fr->mallocd & AST_MALLOCD_HDR)) {
361                 /* Allocate a new header if needed */
362                 if (!(out = ast_frame_header_new()))
363                         return NULL;
364                 out->frametype = fr->frametype;
365                 out->subclass = fr->subclass;
366                 out->datalen = fr->datalen;
367                 out->samples = fr->samples;
368                 out->offset = fr->offset;
369                 out->data = fr->data;
370                 /* Copy the timing data */
371                 ast_copy_flags(out, fr, AST_FRFLAG_HAS_TIMING_INFO);
372                 if (ast_test_flag(fr, AST_FRFLAG_HAS_TIMING_INFO)) {
373                         out->ts = fr->ts;
374                         out->len = fr->len;
375                         out->seqno = fr->seqno;
376                 }
377         } else
378                 out = fr;
379         
380         if (!(fr->mallocd & AST_MALLOCD_SRC)) {
381                 if (fr->src) {
382                         if (!(out->src = ast_strdup(fr->src))) {
383                                 if (out != fr)
384                                         ast_free(out);
385                                 return NULL;
386                         }
387                 }
388         } else
389                 out->src = fr->src;
390         
391         if (!(fr->mallocd & AST_MALLOCD_DATA))  {
392                 if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
393                         if (out->src != fr->src)
394                                 ast_free((void *) out->src);
395                         if (out != fr)
396                                 ast_free(out);
397                         return NULL;
398                 }
399                 newdata += AST_FRIENDLY_OFFSET;
400                 out->offset = AST_FRIENDLY_OFFSET;
401                 out->datalen = fr->datalen;
402                 memcpy(newdata, fr->data, fr->datalen);
403                 out->data = newdata;
404         }
405
406         out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA;
407         
408         return out;
409 }
410
411 struct ast_frame *ast_frdup(const struct ast_frame *f)
412 {
413         struct ast_frame *out = NULL;
414         int len, srclen = 0;
415         void *buf = NULL;
416
417 #if !defined(LOW_MEMORY)
418         struct ast_frame_cache *frames;
419 #endif
420
421         /* Start with standard stuff */
422         len = sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
423         /* If we have a source, add space for it */
424         /*
425          * XXX Watch out here - if we receive a src which is not terminated
426          * properly, we can be easily attacked. Should limit the size we deal with.
427          */
428         if (f->src)
429                 srclen = strlen(f->src);
430         if (srclen > 0)
431                 len += srclen + 1;
432         
433 #if !defined(LOW_MEMORY)
434         if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
435                 AST_LIST_TRAVERSE_SAFE_BEGIN(&frames->list, out, frame_list) {
436                         if (out->mallocd_hdr_len >= len) {
437                                 size_t mallocd_len = out->mallocd_hdr_len;
438
439                                 AST_LIST_REMOVE_CURRENT(frame_list);
440                                 memset(out, 0, sizeof(*out));
441                                 out->mallocd_hdr_len = mallocd_len;
442                                 buf = out;
443                                 frames->size--;
444                                 break;
445                         }
446                 }
447                 AST_LIST_TRAVERSE_SAFE_END;
448         }
449 #endif
450
451         if (!buf) {
452                 if (!(buf = ast_calloc_cache(1, len)))
453                         return NULL;
454                 out = buf;
455                 out->mallocd_hdr_len = len;
456         }
457
458         out->frametype = f->frametype;
459         out->subclass = f->subclass;
460         out->datalen = f->datalen;
461         out->samples = f->samples;
462         out->delivery = f->delivery;
463         /* Set us as having malloc'd header only, so it will eventually
464            get freed. */
465         out->mallocd = AST_MALLOCD_HDR;
466         out->offset = AST_FRIENDLY_OFFSET;
467         if (out->datalen) {
468                 out->data = buf + sizeof(*out) + AST_FRIENDLY_OFFSET;
469                 memcpy(out->data, f->data, out->datalen);       
470         }
471         if (srclen > 0) {
472                 out->src = buf + sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
473                 /* Must have space since we allocated for it */
474                 strcpy((char *)out->src, f->src);
475         }
476         ast_copy_flags(out, f, AST_FRFLAG_HAS_TIMING_INFO);
477         out->ts = f->ts;
478         out->len = f->len;
479         out->seqno = f->seqno;
480         return out;
481 }
482
483 void ast_swapcopy_samples(void *dst, const void *src, int samples)
484 {
485         int i;
486         unsigned short *dst_s = dst;
487         const unsigned short *src_s = src;
488
489         for (i = 0; i < samples; i++)
490                 dst_s[i] = (src_s[i]<<8) | (src_s[i]>>8);
491 }
492
493
494 struct ast_format_list *ast_get_format_list_index(int index) 
495 {
496         return &AST_FORMAT_LIST[index];
497 }
498
499 struct ast_format_list *ast_get_format_list(size_t *size) 
500 {
501         *size = (sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]));
502         return AST_FORMAT_LIST;
503 }
504
505 char* ast_getformatname(int format)
506 {
507         int x;
508         char *ret = "unknown";
509         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
510                 if (AST_FORMAT_LIST[x].bits == format) {
511                         ret = AST_FORMAT_LIST[x].name;
512                         break;
513                 }
514         }
515         return ret;
516 }
517
518 char *ast_getformatname_multiple(char *buf, size_t size, int format)
519 {
520         int x;
521         unsigned len;
522         char *start, *end = buf;
523
524         if (!size)
525                 return buf;
526         snprintf(end, size, "0x%x (", format);
527         len = strlen(end);
528         end += len;
529         size -= len;
530         start = end;
531         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
532                 if (AST_FORMAT_LIST[x].bits & format) {
533                         snprintf(end, size,"%s|",AST_FORMAT_LIST[x].name);
534                         len = strlen(end);
535                         end += len;
536                         size -= len;
537                 }
538         }
539         if (start == end)
540                 ast_copy_string(start, "nothing)", size);
541         else if (size > 1)
542                 *(end -1) = ')';
543         return buf;
544 }
545
546 static struct ast_codec_alias_table {
547         char *alias;
548         char *realname;
549 } ast_codec_alias_table[] = {
550         { "slinear", "slin"},
551         { "slinear16", "slin16"},
552         { "g723.1", "g723"},
553 };
554
555 static const char *ast_expand_codec_alias(const char *in)
556 {
557         int x;
558
559         for (x = 0; x < sizeof(ast_codec_alias_table) / sizeof(ast_codec_alias_table[0]); x++) {
560                 if (!strcmp(in,ast_codec_alias_table[x].alias))
561                         return ast_codec_alias_table[x].realname;
562         }
563         return in;
564 }
565
566 int ast_getformatbyname(const char *name)
567 {
568         int x, all, format = 0;
569
570         all = strcasecmp(name, "all") ? 0 : 1;
571         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
572                 if (all || 
573                           !strcasecmp(AST_FORMAT_LIST[x].name,name) ||
574                           !strcasecmp(AST_FORMAT_LIST[x].name,ast_expand_codec_alias(name))) {
575                         format |= AST_FORMAT_LIST[x].bits;
576                         if (!all)
577                                 break;
578                 }
579         }
580
581         return format;
582 }
583
584 char *ast_codec2str(int codec)
585 {
586         int x;
587         char *ret = "unknown";
588         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
589                 if (AST_FORMAT_LIST[x].bits == codec) {
590                         ret = AST_FORMAT_LIST[x].desc;
591                         break;
592                 }
593         }
594         return ret;
595 }
596
597 static char *show_codecs(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
598 {
599         int i, found=0;
600         char hex[25];
601
602         switch (cmd) {
603         case CLI_INIT:
604                 e->command = "core show codecs [audio|video|image]";
605                 e->usage = 
606                         "Usage: core show codecs [audio|video|image]\n"
607                         "       Displays codec mapping\n";
608                 return NULL;
609         case CLI_GENERATE:
610                 return NULL;
611         }
612         
613         if ((a->argc < 3) || (a->argc > 4))
614                 return CLI_SHOWUSAGE;
615
616         if (!ast_opt_dont_warn)
617                 ast_cli(a->fd, "Disclaimer: this command is for informational purposes only.\n"
618                                 "\tIt does not indicate anything about your configuration.\n");
619
620         ast_cli(a->fd, "%11s %9s %10s   TYPE   %8s   %s\n","INT","BINARY","HEX","NAME","DESC");
621         ast_cli(a->fd, "--------------------------------------------------------------------------------\n");
622         if ((a->argc == 3) || (!strcasecmp(a->argv[3],"audio"))) {
623                 found = 1;
624                 for (i=0;i<13;i++) {
625                         snprintf(hex,25,"(0x%x)",1<<i);
626                         ast_cli(a->fd, "%11u (1 << %2d) %10s  audio   %8s   (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
627                 }
628         }
629
630         if ((a->argc == 3) || (!strcasecmp(a->argv[3],"image"))) {
631                 found = 1;
632                 for (i=16;i<18;i++) {
633                         snprintf(hex,25,"(0x%x)",1<<i);
634                         ast_cli(a->fd, "%11u (1 << %2d) %10s  image   %8s   (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
635                 }
636         }
637
638         if ((a->argc == 3) || (!strcasecmp(a->argv[3],"video"))) {
639                 found = 1;
640                 for (i=18;i<22;i++) {
641                         snprintf(hex,25,"(0x%x)",1<<i);
642                         ast_cli(a->fd, "%11u (1 << %2d) %10s  video   %8s   (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
643                 }
644         }
645
646         if (!found)
647                 return CLI_SHOWUSAGE;
648         else
649                 return CLI_SUCCESS;
650 }
651
652 static char *show_codec_n(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
653 {
654         int codec, i, found=0;
655
656         switch (cmd) {
657         case CLI_INIT:
658                 e->command = "core show codec";
659                 e->usage = 
660                         "Usage: core show codec <number>\n"
661                         "       Displays codec mapping\n";
662                 return NULL;
663         case CLI_GENERATE:
664                 return NULL;
665         }
666
667         if (a->argc != 4)
668                 return CLI_SHOWUSAGE;
669
670         if (sscanf(a->argv[3],"%d",&codec) != 1)
671                 return CLI_SHOWUSAGE;
672
673         for (i = 0; i < 32; i++)
674                 if (codec & (1 << i)) {
675                         found = 1;
676                         ast_cli(a->fd, "%11u (1 << %2d)  %s\n",1 << i,i,ast_codec2str(1<<i));
677                 }
678
679         if (!found)
680                 ast_cli(a->fd, "Codec %d not found\n", codec);
681
682         return CLI_SUCCESS;
683 }
684
685 /*! Dump a frame for debugging purposes */
686 void ast_frame_dump(const char *name, struct ast_frame *f, char *prefix)
687 {
688         const char noname[] = "unknown";
689         char ftype[40] = "Unknown Frametype";
690         char cft[80];
691         char subclass[40] = "Unknown Subclass";
692         char csub[80];
693         char moreinfo[40] = "";
694         char cn[60];
695         char cp[40];
696         char cmn[40];
697         const char *message = "Unknown";
698
699         if (!name)
700                 name = noname;
701
702
703         if (!f) {
704                 ast_verbose("%s [ %s (NULL) ] [%s]\n", 
705                         term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
706                         term_color(cft, "HANGUP", COLOR_BRRED, COLOR_BLACK, sizeof(cft)), 
707                         term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
708                 return;
709         }
710         /* XXX We should probably print one each of voice and video when the format changes XXX */
711         if (f->frametype == AST_FRAME_VOICE)
712                 return;
713         if (f->frametype == AST_FRAME_VIDEO)
714                 return;
715         switch(f->frametype) {
716         case AST_FRAME_DTMF_BEGIN:
717                 strcpy(ftype, "DTMF Begin");
718                 subclass[0] = f->subclass;
719                 subclass[1] = '\0';
720                 break;
721         case AST_FRAME_DTMF_END:
722                 strcpy(ftype, "DTMF End");
723                 subclass[0] = f->subclass;
724                 subclass[1] = '\0';
725                 break;
726         case AST_FRAME_CONTROL:
727                 strcpy(ftype, "Control");
728                 switch(f->subclass) {
729                 case AST_CONTROL_HANGUP:
730                         strcpy(subclass, "Hangup");
731                         break;
732                 case AST_CONTROL_RING:
733                         strcpy(subclass, "Ring");
734                         break;
735                 case AST_CONTROL_RINGING:
736                         strcpy(subclass, "Ringing");
737                         break;
738                 case AST_CONTROL_ANSWER:
739                         strcpy(subclass, "Answer");
740                         break;
741                 case AST_CONTROL_BUSY:
742                         strcpy(subclass, "Busy");
743                         break;
744                 case AST_CONTROL_TAKEOFFHOOK:
745                         strcpy(subclass, "Take Off Hook");
746                         break;
747                 case AST_CONTROL_OFFHOOK:
748                         strcpy(subclass, "Line Off Hook");
749                         break;
750                 case AST_CONTROL_CONGESTION:
751                         strcpy(subclass, "Congestion");
752                         break;
753                 case AST_CONTROL_FLASH:
754                         strcpy(subclass, "Flash");
755                         break;
756                 case AST_CONTROL_WINK:
757                         strcpy(subclass, "Wink");
758                         break;
759                 case AST_CONTROL_OPTION:
760                         strcpy(subclass, "Option");
761                         break;
762                 case AST_CONTROL_RADIO_KEY:
763                         strcpy(subclass, "Key Radio");
764                         break;
765                 case AST_CONTROL_RADIO_UNKEY:
766                         strcpy(subclass, "Unkey Radio");
767                         break;
768                 case AST_CONTROL_HOLD:
769                         strcpy(subclass, "Hold");
770                         break;
771                 case AST_CONTROL_UNHOLD:
772                         strcpy(subclass, "Unhold");
773                         break;
774                 case AST_CONTROL_T38:
775                         if (f->datalen != sizeof(enum ast_control_t38)) {
776                                 message = "Invalid";
777                         } else {
778                                 enum ast_control_t38 state = *((enum ast_control_t38 *) f->data);
779                                 if (state == AST_T38_REQUEST_NEGOTIATE)
780                                         message = "Negotiation Requested";
781                                 else if (state == AST_T38_REQUEST_TERMINATE)
782                                         message = "Negotiation Request Terminated";
783                                 else if (state == AST_T38_NEGOTIATED)
784                                         message = "Negotiated";
785                                 else if (state == AST_T38_TERMINATED)
786                                         message = "Terminated";
787                                 else if (state == AST_T38_REFUSED)
788                                         message = "Refused";
789                         }
790                         snprintf(subclass, sizeof(subclass), "T38/%s", message);
791                         break;
792                 case -1:
793                         strcpy(subclass, "Stop generators");
794                         break;
795                 default:
796                         snprintf(subclass, sizeof(subclass), "Unknown control '%d'", f->subclass);
797                 }
798                 break;
799         case AST_FRAME_NULL:
800                 strcpy(ftype, "Null Frame");
801                 strcpy(subclass, "N/A");
802                 break;
803         case AST_FRAME_IAX:
804                 /* Should never happen */
805                 strcpy(ftype, "IAX Specific");
806                 snprintf(subclass, sizeof(subclass), "IAX Frametype %d", f->subclass);
807                 break;
808         case AST_FRAME_TEXT:
809                 strcpy(ftype, "Text");
810                 strcpy(subclass, "N/A");
811                 ast_copy_string(moreinfo, f->data, sizeof(moreinfo));
812                 break;
813         case AST_FRAME_IMAGE:
814                 strcpy(ftype, "Image");
815                 snprintf(subclass, sizeof(subclass), "Image format %s\n", ast_getformatname(f->subclass));
816                 break;
817         case AST_FRAME_HTML:
818                 strcpy(ftype, "HTML");
819                 switch(f->subclass) {
820                 case AST_HTML_URL:
821                         strcpy(subclass, "URL");
822                         ast_copy_string(moreinfo, f->data, sizeof(moreinfo));
823                         break;
824                 case AST_HTML_DATA:
825                         strcpy(subclass, "Data");
826                         break;
827                 case AST_HTML_BEGIN:
828                         strcpy(subclass, "Begin");
829                         break;
830                 case AST_HTML_END:
831                         strcpy(subclass, "End");
832                         break;
833                 case AST_HTML_LDCOMPLETE:
834                         strcpy(subclass, "Load Complete");
835                         break;
836                 case AST_HTML_NOSUPPORT:
837                         strcpy(subclass, "No Support");
838                         break;
839                 case AST_HTML_LINKURL:
840                         strcpy(subclass, "Link URL");
841                         ast_copy_string(moreinfo, f->data, sizeof(moreinfo));
842                         break;
843                 case AST_HTML_UNLINK:
844                         strcpy(subclass, "Unlink");
845                         break;
846                 case AST_HTML_LINKREJECT:
847                         strcpy(subclass, "Link Reject");
848                         break;
849                 default:
850                         snprintf(subclass, sizeof(subclass), "Unknown HTML frame '%d'\n", f->subclass);
851                         break;
852                 }
853                 break;
854         case AST_FRAME_MODEM:
855                 strcpy(ftype, "Modem");
856                 switch (f->subclass) {
857                 case AST_MODEM_T38:
858                         strcpy(subclass, "T.38");
859                         break;
860                 case AST_MODEM_V150:
861                         strcpy(subclass, "V.150");
862                         break;
863                 default:
864                         snprintf(subclass, sizeof(subclass), "Unknown MODEM frame '%d'\n", f->subclass);
865                         break;
866                 }
867                 break;
868         default:
869                 snprintf(ftype, sizeof(ftype), "Unknown Frametype '%d'", f->frametype);
870         }
871         if (!ast_strlen_zero(moreinfo))
872                 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) '%s' ] [%s]\n",  
873                             term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
874                             term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
875                             f->frametype, 
876                             term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
877                             f->subclass, 
878                             term_color(cmn, moreinfo, COLOR_BRGREEN, COLOR_BLACK, sizeof(cmn)),
879                             term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
880         else
881                 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) ] [%s]\n",  
882                             term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
883                             term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
884                             f->frametype, 
885                             term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
886                             f->subclass, 
887                             term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
888 }
889
890
891 #ifdef TRACE_FRAMES
892 static char *show_frame_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
893 {
894         struct ast_frame *f;
895         int x=1;
896
897         switch (cmd) {
898         case CLI_INIT:
899                 e->command = "core show frame stats";
900                 e->usage = 
901                         "Usage: core show frame stats\n"
902                         "       Displays debugging statistics from framer\n";
903                 return NULL;
904         case CLI_GENERATE:
905                 return NULL;    
906         }
907
908         if (a->argc != 4)
909                 return CLI_SHOWUSAGE;
910         AST_LIST_LOCK(&headerlist);
911         ast_cli(a->fd, "     Framer Statistics     \n");
912         ast_cli(a->fd, "---------------------------\n");
913         ast_cli(a->fd, "Total allocated headers: %d\n", headers);
914         ast_cli(a->fd, "Queue Dump:\n");
915         AST_LIST_TRAVERSE(&headerlist, f, frame_list)
916                 ast_cli(a->fd, "%d.  Type %d, subclass %d from %s\n", x++, f->frametype, f->subclass, f->src ? f->src : "<Unknown>");
917         AST_LIST_UNLOCK(&headerlist);
918         return CLI_SUCCESS;
919 }
920 #endif
921
922 /* Builtin Asterisk CLI-commands for debugging */
923 static struct ast_cli_entry my_clis[] = {
924         AST_CLI_DEFINE(show_codecs, "Displays a list of codecs"),
925         AST_CLI_DEFINE(show_codec_n, "Shows a specific codec"),
926 #ifdef TRACE_FRAMES
927         AST_CLI_DEFINE(show_frame_stats, "Shows frame statistics"),
928 #endif
929 };
930
931 int init_framer(void)
932 {
933         ast_cli_register_multiple(my_clis, sizeof(my_clis) / sizeof(struct ast_cli_entry));
934         return 0;       
935 }
936
937 void ast_codec_pref_convert(struct ast_codec_pref *pref, char *buf, size_t size, int right) 
938 {
939         int x, differential = (int) 'A', mem;
940         char *from, *to;
941
942         if (right) {
943                 from = pref->order;
944                 to = buf;
945                 mem = size;
946         } else {
947                 to = pref->order;
948                 from = buf;
949                 mem = 32;
950         }
951
952         memset(to, 0, mem);
953         for (x = 0; x < 32 ; x++) {
954                 if (!from[x])
955                         break;
956                 to[x] = right ? (from[x] + differential) : (from[x] - differential);
957         }
958 }
959
960 int ast_codec_pref_string(struct ast_codec_pref *pref, char *buf, size_t size) 
961 {
962         int x, codec; 
963         size_t total_len, slen;
964         char *formatname;
965         
966         memset(buf,0,size);
967         total_len = size;
968         buf[0] = '(';
969         total_len--;
970         for(x = 0; x < 32 ; x++) {
971                 if (total_len <= 0)
972                         break;
973                 if (!(codec = ast_codec_pref_index(pref,x)))
974                         break;
975                 if ((formatname = ast_getformatname(codec))) {
976                         slen = strlen(formatname);
977                         if (slen > total_len)
978                                 break;
979                         strncat(buf, formatname, total_len - 1); /* safe */
980                         total_len -= slen;
981                 }
982                 if (total_len && x < 31 && ast_codec_pref_index(pref , x + 1)) {
983                         strncat(buf, "|", total_len - 1); /* safe */
984                         total_len--;
985                 }
986         }
987         if (total_len) {
988                 strncat(buf, ")", total_len - 1); /* safe */
989                 total_len--;
990         }
991
992         return size - total_len;
993 }
994
995 int ast_codec_pref_index(struct ast_codec_pref *pref, int index) 
996 {
997         int slot = 0;
998
999         
1000         if ((index >= 0) && (index < sizeof(pref->order))) {
1001                 slot = pref->order[index];
1002         }
1003
1004         return slot ? AST_FORMAT_LIST[slot-1].bits : 0;
1005 }
1006
1007 /*! \brief Remove codec from pref list */
1008 void ast_codec_pref_remove(struct ast_codec_pref *pref, int format)
1009 {
1010         struct ast_codec_pref oldorder;
1011         int x, y = 0;
1012         int slot;
1013         int size;
1014
1015         if (!pref->order[0])
1016                 return;
1017
1018         memcpy(&oldorder, pref, sizeof(oldorder));
1019         memset(pref, 0, sizeof(*pref));
1020
1021         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1022                 slot = oldorder.order[x];
1023                 size = oldorder.framing[x];
1024                 if (! slot)
1025                         break;
1026                 if (AST_FORMAT_LIST[slot-1].bits != format) {
1027                         pref->order[y] = slot;
1028                         pref->framing[y++] = size;
1029                 }
1030         }
1031         
1032 }
1033
1034 /*! \brief Append codec to list */
1035 int ast_codec_pref_append(struct ast_codec_pref *pref, int format)
1036 {
1037         int x, newindex = 0;
1038
1039         ast_codec_pref_remove(pref, format);
1040
1041         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1042                 if (AST_FORMAT_LIST[x].bits == format) {
1043                         newindex = x + 1;
1044                         break;
1045                 }
1046         }
1047
1048         if (newindex) {
1049                 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1050                         if (!pref->order[x]) {
1051                                 pref->order[x] = newindex;
1052                                 break;
1053                         }
1054                 }
1055         }
1056
1057         return x;
1058 }
1059
1060 /*! \brief Prepend codec to list */
1061 void ast_codec_pref_prepend(struct ast_codec_pref *pref, int format, int only_if_existing)
1062 {
1063         int x, newindex = 0;
1064
1065         /* First step is to get the codecs "index number" */
1066         for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1067                 if (AST_FORMAT_LIST[x].bits == format) {
1068                         newindex = x + 1;
1069                         break;
1070                 }
1071         }
1072         /* Done if its unknown */
1073         if (!newindex)
1074                 return;
1075
1076         /* Now find any existing occurrence, or the end */
1077         for (x = 0; x < 32; x++) {
1078                 if (!pref->order[x] || pref->order[x] == newindex)
1079                         break;
1080         }
1081
1082         if (only_if_existing && !pref->order[x])
1083                 return;
1084
1085         /* Move down to make space to insert - either all the way to the end,
1086            or as far as the existing location (which will be overwritten) */
1087         for (; x > 0; x--) {
1088                 pref->order[x] = pref->order[x - 1];
1089                 pref->framing[x] = pref->framing[x - 1];
1090         }
1091
1092         /* And insert the new entry */
1093         pref->order[0] = newindex;
1094         pref->framing[0] = 0; /* ? */
1095 }
1096
1097 /*! \brief Set packet size for codec */
1098 int ast_codec_pref_setsize(struct ast_codec_pref *pref, int format, int framems)
1099 {
1100         int x, index = -1;
1101
1102         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1103                 if (AST_FORMAT_LIST[x].bits == format) {
1104                         index = x;
1105                         break;
1106                 }
1107         }
1108
1109         if (index < 0)
1110                 return -1;
1111
1112         /* size validation */
1113         if (!framems)
1114                 framems = AST_FORMAT_LIST[index].def_ms;
1115
1116         if (AST_FORMAT_LIST[index].inc_ms && framems % AST_FORMAT_LIST[index].inc_ms) /* avoid division by zero */
1117                 framems -= framems % AST_FORMAT_LIST[index].inc_ms;
1118
1119         if (framems < AST_FORMAT_LIST[index].min_ms)
1120                 framems = AST_FORMAT_LIST[index].min_ms;
1121
1122         if (framems > AST_FORMAT_LIST[index].max_ms)
1123                 framems = AST_FORMAT_LIST[index].max_ms;
1124
1125
1126         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1127                 if (pref->order[x] == (index + 1)) {
1128                         pref->framing[x] = framems;
1129                         break;
1130                 }
1131         }
1132
1133         return x;
1134 }
1135
1136 /*! \brief Get packet size for codec */
1137 struct ast_format_list ast_codec_pref_getsize(struct ast_codec_pref *pref, int format)
1138 {
1139         int x, index = -1, framems = 0;
1140         struct ast_format_list fmt = { 0, };
1141
1142         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1143                 if (AST_FORMAT_LIST[x].bits == format) {
1144                         fmt = AST_FORMAT_LIST[x];
1145                         index = x;
1146                         break;
1147                 }
1148         }
1149
1150         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1151                 if (pref->order[x] == (index + 1)) {
1152                         framems = pref->framing[x];
1153                         break;
1154                 }
1155         }
1156
1157         /* size validation */
1158         if (!framems)
1159                 framems = AST_FORMAT_LIST[index].def_ms;
1160
1161         if (AST_FORMAT_LIST[index].inc_ms && framems % AST_FORMAT_LIST[index].inc_ms) /* avoid division by zero */
1162                 framems -= framems % AST_FORMAT_LIST[index].inc_ms;
1163
1164         if (framems < AST_FORMAT_LIST[index].min_ms)
1165                 framems = AST_FORMAT_LIST[index].min_ms;
1166
1167         if (framems > AST_FORMAT_LIST[index].max_ms)
1168                 framems = AST_FORMAT_LIST[index].max_ms;
1169
1170         fmt.cur_ms = framems;
1171
1172         return fmt;
1173 }
1174
1175 /*! \brief Pick a codec */
1176 int ast_codec_choose(struct ast_codec_pref *pref, int formats, int find_best)
1177 {
1178         int x, ret = 0, slot;
1179
1180         for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1181                 slot = pref->order[x];
1182
1183                 if (!slot)
1184                         break;
1185                 if (formats & AST_FORMAT_LIST[slot-1].bits) {
1186                         ret = AST_FORMAT_LIST[slot-1].bits;
1187                         break;
1188                 }
1189         }
1190         if (ret & AST_FORMAT_AUDIO_MASK)
1191                 return ret;
1192
1193         ast_debug(4, "Could not find preferred codec - %s\n", find_best ? "Going for the best codec" : "Returning zero codec");
1194
1195         return find_best ? ast_best_codec(formats) : 0;
1196 }
1197
1198 int ast_parse_allow_disallow(struct ast_codec_pref *pref, int *mask, const char *list, int allowing) 
1199 {
1200         int errors = 0;
1201         char *parse = NULL, *this = NULL, *psize = NULL;
1202         int format = 0, framems = 0;
1203
1204         parse = ast_strdupa(list);
1205         while ((this = strsep(&parse, ","))) {
1206                 framems = 0;
1207                 if ((psize = strrchr(this, ':'))) {
1208                         *psize++ = '\0';
1209                         ast_debug(1, "Packetization for codec: %s is %s\n", this, psize);
1210                         framems = atoi(psize);
1211                         if (framems < 0) {
1212                                 framems = 0;
1213                                 errors++;
1214                                 ast_log(LOG_WARNING, "Bad packetization value for codec %s\n", this);
1215                         }
1216                 }
1217                 if (!(format = ast_getformatbyname(this))) {
1218                         ast_log(LOG_WARNING, "Cannot %s unknown format '%s'\n", allowing ? "allow" : "disallow", this);
1219                         errors++;
1220                         continue;
1221                 }
1222
1223                 if (mask) {
1224                         if (allowing)
1225                                 *mask |= format;
1226                         else
1227                                 *mask &= ~format;
1228                 }
1229
1230                 /* Set up a preference list for audio. Do not include video in preferences 
1231                    since we can not transcode video and have to use whatever is offered
1232                  */
1233                 if (pref && (format & AST_FORMAT_AUDIO_MASK)) {
1234                         if (strcasecmp(this, "all")) {
1235                                 if (allowing) {
1236                                         ast_codec_pref_append(pref, format);
1237                                         ast_codec_pref_setsize(pref, format, framems);
1238                                 }
1239                                 else
1240                                         ast_codec_pref_remove(pref, format);
1241                         } else if (!allowing) {
1242                                 memset(pref, 0, sizeof(*pref));
1243                         }
1244                 }
1245         }
1246         return errors;
1247 }
1248
1249 static int g723_len(unsigned char buf)
1250 {
1251         enum frame_type type = buf & TYPE_MASK;
1252
1253         switch(type) {
1254         case TYPE_DONTSEND:
1255                 return 0;
1256                 break;
1257         case TYPE_SILENCE:
1258                 return 4;
1259                 break;
1260         case TYPE_HIGH:
1261                 return 24;
1262                 break;
1263         case TYPE_LOW:
1264                 return 20;
1265                 break;
1266         default:
1267                 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", type);
1268         }
1269         return -1;
1270 }
1271
1272 static int g723_samples(unsigned char *buf, int maxlen)
1273 {
1274         int pos = 0;
1275         int samples = 0;
1276         int res;
1277         while(pos < maxlen) {
1278                 res = g723_len(buf[pos]);
1279                 if (res <= 0)
1280                         break;
1281                 samples += 240;
1282                 pos += res;
1283         }
1284         return samples;
1285 }
1286
1287 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
1288 {
1289         int byte = bit / 8;       /* byte containing first bit */
1290         int rem = 8 - (bit % 8);  /* remaining bits in first byte */
1291         unsigned char ret = 0;
1292         
1293         if (n <= 0 || n > 8)
1294                 return 0;
1295
1296         if (rem < n) {
1297                 ret = (data[byte] << (n - rem));
1298                 ret |= (data[byte + 1] >> (8 - n + rem));
1299         } else {
1300                 ret = (data[byte] >> (rem - n));
1301         }
1302
1303         return (ret & (0xff >> (8 - n)));
1304 }
1305
1306 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
1307 {
1308         static int SpeexWBSubModeSz[] = {
1309                 0, 36, 112, 192,
1310                 352, 0, 0, 0 };
1311         int off = bit;
1312         unsigned char c;
1313
1314         /* skip up to two wideband frames */
1315         if (((len * 8 - off) >= 5) && 
1316                 get_n_bits_at(data, 1, off)) {
1317                 c = get_n_bits_at(data, 3, off + 1);
1318                 off += SpeexWBSubModeSz[c];
1319
1320                 if (((len * 8 - off) >= 5) && 
1321                         get_n_bits_at(data, 1, off)) {
1322                         c = get_n_bits_at(data, 3, off + 1);
1323                         off += SpeexWBSubModeSz[c];
1324
1325                         if (((len * 8 - off) >= 5) && 
1326                                 get_n_bits_at(data, 1, off)) {
1327                                 ast_log(LOG_WARNING, "Encountered corrupt speex frame; too many wideband frames in a row.\n");
1328                                 return -1;
1329                         }
1330                 }
1331
1332         }
1333         return off - bit;
1334 }
1335
1336 static int speex_samples(unsigned char *data, int len)
1337 {
1338         static int SpeexSubModeSz[] = {
1339                 5, 43, 119, 160,
1340                 220, 300, 364, 492, 
1341                 79, 0, 0, 0,
1342                 0, 0, 0, 0 };
1343         static int SpeexInBandSz[] = { 
1344                 1, 1, 4, 4,
1345                 4, 4, 4, 4,
1346                 8, 8, 16, 16,
1347                 32, 32, 64, 64 };
1348         int bit = 0;
1349         int cnt = 0;
1350         int off;
1351         unsigned char c;
1352
1353         while ((len * 8 - bit) >= 5) {
1354                 /* skip wideband frames */
1355                 off = speex_get_wb_sz_at(data, len, bit);
1356                 if (off < 0)  {
1357                         ast_log(LOG_WARNING, "Had error while reading wideband frames for speex samples\n");
1358                         break;
1359                 }
1360                 bit += off;
1361
1362                 if ((len * 8 - bit) < 5) {
1363                         ast_log(LOG_WARNING, "Not enough bits remaining after wide band for speex samples.\n");
1364                         break;
1365                 }
1366
1367                 /* get control bits */
1368                 c = get_n_bits_at(data, 5, bit);
1369                 bit += 5;
1370
1371                 if (c == 15) { 
1372                         /* terminator */
1373                         break; 
1374                 } else if (c == 14) {
1375                         /* in-band signal; next 4 bits contain signal id */
1376                         c = get_n_bits_at(data, 4, bit);
1377                         bit += 4;
1378                         bit += SpeexInBandSz[c];
1379                 } else if (c == 13) {
1380                         /* user in-band; next 5 bits contain msg len */
1381                         c = get_n_bits_at(data, 5, bit);
1382                         bit += 5;
1383                         bit += c * 8;
1384                 } else if (c > 8) {
1385                         /* unknown */
1386                         break;
1387                 } else {
1388                         /* skip number bits for submode (less the 5 control bits) */
1389                         bit += SpeexSubModeSz[c] - 5;
1390                         cnt += 160; /* new frame */
1391                 }
1392         }
1393         return cnt;
1394 }
1395
1396 int ast_codec_get_samples(struct ast_frame *f)
1397 {
1398         int samples=0;
1399         switch(f->subclass) {
1400         case AST_FORMAT_SPEEX:
1401                 samples = speex_samples(f->data, f->datalen);
1402                 break;
1403         case AST_FORMAT_G723_1:
1404                 samples = g723_samples(f->data, f->datalen);
1405                 break;
1406         case AST_FORMAT_ILBC:
1407                 samples = 240 * (f->datalen / 50);
1408                 break;
1409         case AST_FORMAT_GSM:
1410                 samples = 160 * (f->datalen / 33);
1411                 break;
1412         case AST_FORMAT_G729A:
1413                 samples = f->datalen * 8;
1414                 break;
1415         case AST_FORMAT_SLINEAR:
1416         case AST_FORMAT_SLINEAR16:
1417                 samples = f->datalen / 2;
1418                 break;
1419         case AST_FORMAT_LPC10:
1420                 /* assumes that the RTP packet contains one LPC10 frame */
1421                 samples = 22 * 8;
1422                 samples += (((char *)(f->data))[7] & 0x1) * 8;
1423                 break;
1424         case AST_FORMAT_ULAW:
1425         case AST_FORMAT_ALAW:
1426                 samples = f->datalen;
1427                 break;
1428         case AST_FORMAT_G722:
1429         case AST_FORMAT_ADPCM:
1430         case AST_FORMAT_G726:
1431         case AST_FORMAT_G726_AAL2:
1432                 samples = f->datalen * 2;
1433                 break;
1434         default:
1435                 ast_log(LOG_WARNING, "Unable to calculate samples for format %s\n", ast_getformatname(f->subclass));
1436         }
1437         return samples;
1438 }
1439
1440 int ast_codec_get_len(int format, int samples)
1441 {
1442         int len = 0;
1443
1444         /* XXX Still need speex, g723, and lpc10 XXX */ 
1445         switch(format) {
1446         case AST_FORMAT_G723_1:
1447                 len = (samples / 240) * 20;
1448                 break;
1449         case AST_FORMAT_ILBC:
1450                 len = (samples / 240) * 50;
1451                 break;
1452         case AST_FORMAT_GSM:
1453                 len = (samples / 160) * 33;
1454                 break;
1455         case AST_FORMAT_G729A:
1456                 len = samples / 8;
1457                 break;
1458         case AST_FORMAT_SLINEAR:
1459         case AST_FORMAT_SLINEAR16:
1460                 len = samples * 2;
1461                 break;
1462         case AST_FORMAT_ULAW:
1463         case AST_FORMAT_ALAW:
1464                 len = samples;
1465                 break;
1466         case AST_FORMAT_G722:
1467         case AST_FORMAT_ADPCM:
1468         case AST_FORMAT_G726:
1469         case AST_FORMAT_G726_AAL2:
1470                 len = samples / 2;
1471                 break;
1472         default:
1473                 ast_log(LOG_WARNING, "Unable to calculate sample length for format %s\n", ast_getformatname(format));
1474         }
1475
1476         return len;
1477 }
1478
1479 int ast_frame_adjust_volume(struct ast_frame *f, int adjustment)
1480 {
1481         int count;
1482         short *fdata = f->data;
1483         short adjust_value = abs(adjustment);
1484
1485         if ((f->frametype != AST_FRAME_VOICE) || (f->subclass != AST_FORMAT_SLINEAR))
1486                 return -1;
1487
1488         if (!adjustment)
1489                 return 0;
1490
1491         for (count = 0; count < f->samples; count++) {
1492                 if (adjustment > 0) {
1493                         ast_slinear_saturated_multiply(&fdata[count], &adjust_value);
1494                 } else if (adjustment < 0) {
1495                         ast_slinear_saturated_divide(&fdata[count], &adjust_value);
1496                 }
1497         }
1498
1499         return 0;
1500 }
1501
1502 int ast_frame_slinear_sum(struct ast_frame *f1, struct ast_frame *f2)
1503 {
1504         int count;
1505         short *data1, *data2;
1506
1507         if ((f1->frametype != AST_FRAME_VOICE) || (f1->subclass != AST_FORMAT_SLINEAR))
1508                 return -1;
1509
1510         if ((f2->frametype != AST_FRAME_VOICE) || (f2->subclass != AST_FORMAT_SLINEAR))
1511                 return -1;
1512
1513         if (f1->samples != f2->samples)
1514                 return -1;
1515
1516         for (count = 0, data1 = f1->data, data2 = f2->data;
1517              count < f1->samples;
1518              count++, data1++, data2++)
1519                 ast_slinear_saturated_add(data1, data2);
1520
1521         return 0;
1522 }