Let's also include aclocal.m4
[asterisk-bristuff.git] / main / frame.c
blobd64fa09a7eae3f9b57ac02aedfcbf7ebb05e070c
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Frame and codec manipulation routines
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <stdio.h>
36 #include "asterisk/lock.h"
37 #include "asterisk/frame.h"
38 #include "asterisk/logger.h"
39 #include "asterisk/options.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/term.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/threadstorage.h"
45 #include "asterisk/linkedlists.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/dsp.h"
49 #ifdef TRACE_FRAMES
50 static int headers;
51 static AST_LIST_HEAD_STATIC(headerlist, ast_frame);
52 #endif
54 #if !defined(LOW_MEMORY)
55 static void frame_cache_cleanup(void *data);
57 /*! \brief A per-thread cache of frame headers */
58 AST_THREADSTORAGE_CUSTOM(frame_cache, frame_cache_init, frame_cache_cleanup);
60 /*!
61 * \brief Maximum ast_frame cache size
63 * In most cases where the frame header cache will be useful, the size
64 * of the cache will stay very small. However, it is not always the case that
65 * the same thread that allocates the frame will be the one freeing them, so
66 * sometimes a thread will never have any frames in its cache, or the cache
67 * will never be pulled from. For the latter case, we limit the maximum size.
68 */
69 #define FRAME_CACHE_MAX_SIZE 10
71 /*! \brief This is just so ast_frames, a list head struct for holding a list of
72 * ast_frame structures, is defined. */
73 AST_LIST_HEAD_NOLOCK(ast_frames, ast_frame);
75 struct ast_frame_cache {
76 struct ast_frames list;
77 size_t size;
79 #endif
81 #define SMOOTHER_SIZE 8000
83 enum frame_type {
84 TYPE_HIGH, /* 0x0 */
85 TYPE_LOW, /* 0x1 */
86 TYPE_SILENCE, /* 0x2 */
87 TYPE_DONTSEND /* 0x3 */
90 #define TYPE_MASK 0x3
92 struct ast_smoother {
93 int size;
94 int format;
95 int readdata;
96 int optimizablestream;
97 int flags;
98 float samplesperbyte;
99 struct ast_frame f;
100 struct timeval delivery;
101 char data[SMOOTHER_SIZE];
102 char framedata[SMOOTHER_SIZE + AST_FRIENDLY_OFFSET];
103 struct ast_frame *opt;
104 int len;
107 /*! \brief Definition of supported media formats (codecs) */
108 static struct ast_format_list AST_FORMAT_LIST[] = { /*!< Bit number: comment - Bit numbers are hard coded in show_codec() */
109 { 1, AST_FORMAT_G723_1 , "g723" , "G.723.1", 24, 30, 300, 30, 30 }, /*!< 1 */
110 { 1, AST_FORMAT_GSM, "gsm" , "GSM", 33, 20, 300, 20, 20 }, /*!< 2: codec_gsm.c */
111 { 1, AST_FORMAT_ULAW, "ulaw", "G.711 u-law", 80, 10, 150, 10, 20 }, /*!< 3: codec_ulaw.c */
112 { 1, AST_FORMAT_ALAW, "alaw", "G.711 A-law", 80, 10, 150, 10, 20 }, /*!< 4: codec_alaw.c */
113 { 1, AST_FORMAT_G726, "g726", "G.726 RFC3551", 40, 10, 300, 10, 20 }, /*!< 5: codec_g726.c */
114 { 1, AST_FORMAT_ADPCM, "adpcm" , "ADPCM", 40, 10, 300, 10, 20 }, /*!< 6: codec_adpcm.c */
115 { 1, AST_FORMAT_SLINEAR, "slin", "16 bit Signed Linear PCM", 160, 10, 70, 10, 20, AST_SMOOTHER_FLAG_BE }, /*!< 7 */
116 { 1, AST_FORMAT_LPC10, "lpc10", "LPC10", 7, 20, 20, 20, 20 }, /*!< 8: codec_lpc10.c */
117 { 1, AST_FORMAT_G729A, "g729", "G.729A", 10, 10, 230, 10, 20, AST_SMOOTHER_FLAG_G729 }, /*!< 9: Binary commercial distribution */
118 { 1, AST_FORMAT_SPEEX, "speex", "SpeeX", 10, 10, 60, 10, 20 }, /*!< 10: codec_speex.c */
119 { 1, AST_FORMAT_ILBC, "ilbc", "iLBC", 50, 30, 30, 30, 30 }, /*!< 11: codec_ilbc.c */ /* inc=30ms - workaround */
120 { 1, AST_FORMAT_G726_AAL2, "g726aal2", "G.726 AAL2", 40, 10, 300, 10, 20 }, /*!< 12: codec_g726.c */
121 { 1, AST_FORMAT_G722, "g722", "G722"}, /*!< 13 */
122 { 0, 0, "nothing", "undefined" },
123 { 0, 0, "nothing", "undefined" },
124 { 0, 0, "nothing", "undefined" },
125 { 0, 0, "nothing", "undefined" },
126 { 0, AST_FORMAT_MAX_AUDIO, "maxaudio", "Maximum audio format" },
127 { 1, AST_FORMAT_JPEG, "jpeg", "JPEG image"}, /*!< 17: See format_jpeg.c */
128 { 1, AST_FORMAT_PNG, "png", "PNG image"}, /*!< 18: Image format */
129 { 1, AST_FORMAT_H261, "h261", "H.261 Video" }, /*!< 19: Video Passthrough */
130 { 1, AST_FORMAT_H263, "h263", "H.263 Video" }, /*!< 20: Passthrough support, see format_h263.c */
131 { 1, AST_FORMAT_H263_PLUS, "h263p", "H.263+ Video" }, /*!< 21: See format_h263.c */
132 { 1, AST_FORMAT_H264, "h264", "H.264 Video" }, /*!< 22: Passthrough support, see format_h263.c */
133 { 0, 0, "nothing", "undefined" },
134 { 0, 0, "nothing", "undefined" },
135 { 0, 0, "nothing", "undefined" },
136 { 0, AST_FORMAT_MAX_VIDEO, "maxvideo", "Maximum video format" },
139 struct ast_frame ast_null_frame = { AST_FRAME_NULL, };
141 void ast_smoother_reset(struct ast_smoother *s, int size)
143 memset(s, 0, sizeof(*s));
144 s->size = size;
147 struct ast_smoother *ast_smoother_new(int size)
149 struct ast_smoother *s;
150 if (size < 1)
151 return NULL;
152 if ((s = ast_malloc(sizeof(*s))))
153 ast_smoother_reset(s, size);
154 return s;
157 int ast_smoother_get_flags(struct ast_smoother *s)
159 return s->flags;
162 void ast_smoother_set_flags(struct ast_smoother *s, int flags)
164 s->flags = flags;
167 int ast_smoother_test_flag(struct ast_smoother *s, int flag)
169 return (s->flags & flag);
172 int __ast_smoother_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
174 if (f->frametype != AST_FRAME_VOICE) {
175 ast_log(LOG_WARNING, "Huh? Can't smooth a non-voice frame!\n");
176 return -1;
178 if (!s->format) {
179 s->format = f->subclass;
180 s->samplesperbyte = (float)f->samples / (float)f->datalen;
181 } else if (s->format != f->subclass) {
182 ast_log(LOG_WARNING, "Smoother was working on %d format frames, now trying to feed %d?\n", s->format, f->subclass);
183 return -1;
185 if (s->len + f->datalen > SMOOTHER_SIZE) {
186 ast_log(LOG_WARNING, "Out of smoother space\n");
187 return -1;
189 if (((f->datalen == s->size) || ((f->datalen < 10) && (s->flags & AST_SMOOTHER_FLAG_G729)))
190 && !s->opt && (f->offset >= AST_MIN_OFFSET)) {
191 if (!s->len) {
192 /* Optimize by sending the frame we just got
193 on the next read, thus eliminating the douple
194 copy */
195 if (swap)
196 ast_swapcopy_samples(f->data, f->data, f->samples);
197 s->opt = f;
198 return 0;
201 if (s->flags & AST_SMOOTHER_FLAG_G729) {
202 if (s->len % 10) {
203 ast_log(LOG_NOTICE, "Dropping extra frame of G.729 since we already have a VAD frame at the end\n");
204 return 0;
207 if (swap)
208 ast_swapcopy_samples(s->data+s->len, f->data, f->samples);
209 else
210 memcpy(s->data + s->len, f->data, f->datalen);
211 /* If either side is empty, reset the delivery time */
212 if (!s->len || ast_tvzero(f->delivery) || ast_tvzero(s->delivery)) /* XXX really ? */
213 s->delivery = f->delivery;
214 s->len += f->datalen;
215 return 0;
218 struct ast_frame *ast_smoother_read(struct ast_smoother *s)
220 struct ast_frame *opt;
221 int len;
223 /* IF we have an optimization frame, send it */
224 if (s->opt) {
225 if (s->opt->offset < AST_FRIENDLY_OFFSET)
226 ast_log(LOG_WARNING, "Returning a frame of inappropriate offset (%d).\n",
227 s->opt->offset);
228 opt = s->opt;
229 s->opt = NULL;
230 return opt;
233 /* Make sure we have enough data */
234 if (s->len < s->size) {
235 /* Or, if this is a G.729 frame with VAD on it, send it immediately anyway */
236 if (!((s->flags & AST_SMOOTHER_FLAG_G729) && (s->size % 10)))
237 return NULL;
239 len = s->size;
240 if (len > s->len)
241 len = s->len;
242 /* Make frame */
243 s->f.frametype = AST_FRAME_VOICE;
244 s->f.subclass = s->format;
245 s->f.data = s->framedata + AST_FRIENDLY_OFFSET;
246 s->f.offset = AST_FRIENDLY_OFFSET;
247 s->f.datalen = len;
248 /* Samples will be improper given VAD, but with VAD the concept really doesn't even exist */
249 s->f.samples = len * s->samplesperbyte; /* XXX rounding */
250 s->f.delivery = s->delivery;
251 /* Fill Data */
252 memcpy(s->f.data, s->data, len);
253 s->len -= len;
254 /* Move remaining data to the front if applicable */
255 if (s->len) {
256 /* In principle this should all be fine because if we are sending
257 G.729 VAD, the next timestamp will take over anyawy */
258 memmove(s->data, s->data + len, s->len);
259 if (!ast_tvzero(s->delivery)) {
260 /* If we have delivery time, increment it, otherwise, leave it at 0 */
261 s->delivery = ast_tvadd(s->delivery, ast_samp2tv(s->f.samples, 8000));
264 /* Return frame */
265 return &s->f;
268 void ast_smoother_free(struct ast_smoother *s)
270 free(s);
273 static struct ast_frame *ast_frame_header_new(void)
275 struct ast_frame *f;
277 #if !defined(LOW_MEMORY)
278 struct ast_frame_cache *frames;
280 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
281 if ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list))) {
282 size_t mallocd_len = f->mallocd_hdr_len;
283 memset(f, 0, sizeof(*f));
284 f->mallocd_hdr_len = mallocd_len;
285 f->mallocd = AST_MALLOCD_HDR;
286 frames->size--;
287 return f;
290 if (!(f = ast_calloc_cache(1, sizeof(*f))))
291 return NULL;
292 #else
293 if (!(f = ast_calloc(1, sizeof(*f))))
294 return NULL;
295 #endif
297 f->mallocd_hdr_len = sizeof(*f);
298 #ifdef TRACE_FRAMES
299 AST_LIST_LOCK(&headerlist);
300 headers++;
301 AST_LIST_INSERT_HEAD(&headerlist, f, frame_list);
302 AST_LIST_UNLOCK(&headerlist);
303 #endif
305 return f;
308 #if !defined(LOW_MEMORY)
309 static void frame_cache_cleanup(void *data)
311 struct ast_frame_cache *frames = data;
312 struct ast_frame *f;
314 while ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list)))
315 free(f);
317 free(frames);
319 #endif
321 void ast_frame_free(struct ast_frame *fr, int cache)
323 if (ast_test_flag(fr, AST_FRFLAG_FROM_TRANSLATOR))
324 ast_translate_frame_freed(fr);
325 else if (ast_test_flag(fr, AST_FRFLAG_FROM_DSP))
326 ast_dsp_frame_freed(fr);
328 if (!fr->mallocd)
329 return;
331 #if !defined(LOW_MEMORY)
332 if (cache && fr->mallocd == AST_MALLOCD_HDR) {
333 /* Cool, only the header is malloc'd, let's just cache those for now
334 * to keep things simple... */
335 struct ast_frame_cache *frames;
337 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))
338 && frames->size < FRAME_CACHE_MAX_SIZE) {
339 AST_LIST_INSERT_HEAD(&frames->list, fr, frame_list);
340 frames->size++;
341 return;
344 #endif
346 if (fr->mallocd & AST_MALLOCD_DATA) {
347 if (fr->data)
348 free(fr->data - fr->offset);
350 if (fr->mallocd & AST_MALLOCD_SRC) {
351 if (fr->src)
352 free((char *)fr->src);
354 if (fr->mallocd & AST_MALLOCD_HDR) {
355 #ifdef TRACE_FRAMES
356 AST_LIST_LOCK(&headerlist);
357 headers--;
358 AST_LIST_REMOVE(&headerlist, fr, frame_list);
359 AST_LIST_UNLOCK(&headerlist);
360 #endif
361 free(fr);
366 * \brief 'isolates' a frame by duplicating non-malloc'ed components
367 * (header, src, data).
368 * On return all components are malloc'ed
370 struct ast_frame *ast_frisolate(struct ast_frame *fr)
372 struct ast_frame *out;
373 void *newdata;
375 ast_clear_flag(fr, AST_FRFLAG_FROM_TRANSLATOR);
376 ast_clear_flag(fr, AST_FRFLAG_FROM_DSP);
378 if (!(fr->mallocd & AST_MALLOCD_HDR)) {
379 /* Allocate a new header if needed */
380 if (!(out = ast_frame_header_new()))
381 return NULL;
382 out->frametype = fr->frametype;
383 out->subclass = fr->subclass;
384 out->datalen = fr->datalen;
385 out->samples = fr->samples;
386 out->offset = fr->offset;
387 out->data = fr->data;
388 /* Copy the timing data */
389 ast_copy_flags(out, fr, AST_FRFLAG_HAS_TIMING_INFO);
390 if (ast_test_flag(fr, AST_FRFLAG_HAS_TIMING_INFO)) {
391 out->ts = fr->ts;
392 out->len = fr->len;
393 out->seqno = fr->seqno;
395 } else
396 out = fr;
398 if (!(fr->mallocd & AST_MALLOCD_SRC)) {
399 if (fr->src) {
400 if (!(out->src = ast_strdup(fr->src))) {
401 if (out != fr)
402 free(out);
403 return NULL;
406 } else
407 out->src = fr->src;
409 if (!(fr->mallocd & AST_MALLOCD_DATA)) {
410 if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
411 if (out->src != fr->src)
412 free((void *) out->src);
413 if (out != fr)
414 free(out);
415 return NULL;
417 newdata += AST_FRIENDLY_OFFSET;
418 out->offset = AST_FRIENDLY_OFFSET;
419 out->datalen = fr->datalen;
420 memcpy(newdata, fr->data, fr->datalen);
421 out->data = newdata;
424 out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA;
426 return out;
429 struct ast_frame *ast_frdup(const struct ast_frame *f)
431 struct ast_frame *out = NULL;
432 int len, srclen = 0;
433 void *buf = NULL;
435 #if !defined(LOW_MEMORY)
436 struct ast_frame_cache *frames;
437 #endif
439 /* Start with standard stuff */
440 len = sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
441 /* If we have a source, add space for it */
443 * XXX Watch out here - if we receive a src which is not terminated
444 * properly, we can be easily attacked. Should limit the size we deal with.
446 if (f->src)
447 srclen = strlen(f->src);
448 if (srclen > 0)
449 len += srclen + 1;
451 #if !defined(LOW_MEMORY)
452 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
453 AST_LIST_TRAVERSE_SAFE_BEGIN(&frames->list, out, frame_list) {
454 if (out->mallocd_hdr_len >= len) {
455 size_t mallocd_len = out->mallocd_hdr_len;
456 AST_LIST_REMOVE_CURRENT(&frames->list, frame_list);
457 memset(out, 0, sizeof(*out));
458 out->mallocd_hdr_len = mallocd_len;
459 buf = out;
460 frames->size--;
461 break;
464 AST_LIST_TRAVERSE_SAFE_END
466 #endif
468 if (!buf) {
469 if (!(buf = ast_calloc_cache(1, len)))
470 return NULL;
471 out = buf;
472 out->mallocd_hdr_len = len;
475 out->frametype = f->frametype;
476 out->subclass = f->subclass;
477 out->datalen = f->datalen;
478 out->samples = f->samples;
479 out->delivery = f->delivery;
480 /* Set us as having malloc'd header only, so it will eventually
481 get freed. */
482 out->mallocd = AST_MALLOCD_HDR;
483 out->offset = AST_FRIENDLY_OFFSET;
484 if (out->datalen) {
485 out->data = buf + sizeof(*out) + AST_FRIENDLY_OFFSET;
486 memcpy(out->data, f->data, out->datalen);
488 if (srclen > 0) {
489 out->src = buf + sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
490 /* Must have space since we allocated for it */
491 strcpy((char *)out->src, f->src);
493 ast_copy_flags(out, f, AST_FRFLAG_HAS_TIMING_INFO);
494 out->ts = f->ts;
495 out->len = f->len;
496 out->seqno = f->seqno;
497 return out;
500 void ast_swapcopy_samples(void *dst, const void *src, int samples)
502 int i;
503 unsigned short *dst_s = dst;
504 const unsigned short *src_s = src;
506 for (i = 0; i < samples; i++)
507 dst_s[i] = (src_s[i]<<8) | (src_s[i]>>8);
511 struct ast_format_list *ast_get_format_list_index(int index)
513 return &AST_FORMAT_LIST[index];
516 struct ast_format_list *ast_get_format_list(size_t *size)
518 *size = (sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]));
519 return AST_FORMAT_LIST;
522 char* ast_getformatname(int format)
524 int x;
525 char *ret = "unknown";
526 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
527 if(AST_FORMAT_LIST[x].visible && AST_FORMAT_LIST[x].bits == format) {
528 ret = AST_FORMAT_LIST[x].name;
529 break;
532 return ret;
535 char *ast_getformatname_multiple(char *buf, size_t size, int format)
537 int x;
538 unsigned len;
539 char *start, *end = buf;
541 if (!size)
542 return buf;
543 snprintf(end, size, "0x%x (", format);
544 len = strlen(end);
545 end += len;
546 size -= len;
547 start = end;
548 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
549 if (AST_FORMAT_LIST[x].visible && (AST_FORMAT_LIST[x].bits & format)) {
550 snprintf(end, size,"%s|",AST_FORMAT_LIST[x].name);
551 len = strlen(end);
552 end += len;
553 size -= len;
556 if (start == end)
557 snprintf(start, size, "nothing)");
558 else if (size > 1)
559 *(end -1) = ')';
560 return buf;
563 static struct ast_codec_alias_table {
564 char *alias;
565 char *realname;
566 } ast_codec_alias_table[] = {
567 { "slinear", "slin"},
568 { "g723.1", "g723"},
571 static const char *ast_expand_codec_alias(const char *in)
573 int x;
575 for (x = 0; x < sizeof(ast_codec_alias_table) / sizeof(ast_codec_alias_table[0]); x++) {
576 if(!strcmp(in,ast_codec_alias_table[x].alias))
577 return ast_codec_alias_table[x].realname;
579 return in;
582 int ast_getformatbyname(const char *name)
584 int x, all, format = 0;
586 all = strcasecmp(name, "all") ? 0 : 1;
587 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
588 if(AST_FORMAT_LIST[x].visible && (all ||
589 !strcasecmp(AST_FORMAT_LIST[x].name,name) ||
590 !strcasecmp(AST_FORMAT_LIST[x].name,ast_expand_codec_alias(name)))) {
591 format |= AST_FORMAT_LIST[x].bits;
592 if(!all)
593 break;
597 return format;
600 char *ast_codec2str(int codec)
602 int x;
603 char *ret = "unknown";
604 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
605 if(AST_FORMAT_LIST[x].visible && AST_FORMAT_LIST[x].bits == codec) {
606 ret = AST_FORMAT_LIST[x].desc;
607 break;
610 return ret;
613 static int show_codecs_deprecated(int fd, int argc, char *argv[])
615 int i, found=0;
616 char hex[25];
618 if ((argc < 2) || (argc > 3))
619 return RESULT_SHOWUSAGE;
621 if (!ast_opt_dont_warn)
622 ast_cli(fd, "Disclaimer: this command is for informational purposes only.\n"
623 "\tIt does not indicate anything about your configuration.\n");
625 ast_cli(fd, "%11s %9s %10s TYPE %8s %s\n","INT","BINARY","HEX","NAME","DESC");
626 ast_cli(fd, "--------------------------------------------------------------------------------\n");
627 if ((argc == 2) || (!strcasecmp(argv[1],"audio"))) {
628 found = 1;
629 for (i=0;i<13;i++) {
630 snprintf(hex,25,"(0x%x)",1<<i);
631 ast_cli(fd, "%11u (1 << %2d) %10s audio %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
635 if ((argc == 2) || (!strcasecmp(argv[1],"image"))) {
636 found = 1;
637 for (i=16;i<18;i++) {
638 snprintf(hex,25,"(0x%x)",1<<i);
639 ast_cli(fd, "%11u (1 << %2d) %10s image %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
643 if ((argc == 2) || (!strcasecmp(argv[1],"video"))) {
644 found = 1;
645 for (i=18;i<22;i++) {
646 snprintf(hex,25,"(0x%x)",1<<i);
647 ast_cli(fd, "%11u (1 << %2d) %10s video %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
651 if (! found)
652 return RESULT_SHOWUSAGE;
653 else
654 return RESULT_SUCCESS;
657 static int show_codecs(int fd, int argc, char *argv[])
659 int i, found=0;
660 char hex[25];
662 if ((argc < 3) || (argc > 4))
663 return RESULT_SHOWUSAGE;
665 if (!ast_opt_dont_warn)
666 ast_cli(fd, "Disclaimer: this command is for informational purposes only.\n"
667 "\tIt does not indicate anything about your configuration.\n");
669 ast_cli(fd, "%11s %9s %10s TYPE %8s %s\n","INT","BINARY","HEX","NAME","DESC");
670 ast_cli(fd, "--------------------------------------------------------------------------------\n");
671 if ((argc == 3) || (!strcasecmp(argv[3],"audio"))) {
672 found = 1;
673 for (i=0;i<13;i++) {
674 snprintf(hex,25,"(0x%x)",1<<i);
675 ast_cli(fd, "%11u (1 << %2d) %10s audio %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
679 if ((argc == 3) || (!strcasecmp(argv[3],"image"))) {
680 found = 1;
681 for (i=16;i<18;i++) {
682 snprintf(hex,25,"(0x%x)",1<<i);
683 ast_cli(fd, "%11u (1 << %2d) %10s image %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
687 if ((argc == 3) || (!strcasecmp(argv[3],"video"))) {
688 found = 1;
689 for (i=18;i<22;i++) {
690 snprintf(hex,25,"(0x%x)",1<<i);
691 ast_cli(fd, "%11u (1 << %2d) %10s video %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
695 if (! found)
696 return RESULT_SHOWUSAGE;
697 else
698 return RESULT_SUCCESS;
701 static char frame_show_codecs_usage[] =
702 "Usage: core show codecs [audio|video|image]\n"
703 " Displays codec mapping\n";
705 static int show_codec_n_deprecated(int fd, int argc, char *argv[])
707 int codec, i, found=0;
709 if (argc != 3)
710 return RESULT_SHOWUSAGE;
712 if (sscanf(argv[2],"%d",&codec) != 1)
713 return RESULT_SHOWUSAGE;
715 for (i = 0; i < 32; i++)
716 if (codec & (1 << i)) {
717 found = 1;
718 ast_cli(fd, "%11u (1 << %2d) %s\n",1 << i,i,ast_codec2str(1<<i));
721 if (!found)
722 ast_cli(fd, "Codec %d not found\n", codec);
724 return RESULT_SUCCESS;
727 static int show_codec_n(int fd, int argc, char *argv[])
729 int codec, i, found=0;
731 if (argc != 4)
732 return RESULT_SHOWUSAGE;
734 if (sscanf(argv[3],"%d",&codec) != 1)
735 return RESULT_SHOWUSAGE;
737 for (i = 0; i < 32; i++)
738 if (codec & (1 << i)) {
739 found = 1;
740 ast_cli(fd, "%11u (1 << %2d) %s\n",1 << i,i,ast_codec2str(1<<i));
743 if (!found)
744 ast_cli(fd, "Codec %d not found\n", codec);
746 return RESULT_SUCCESS;
749 static char frame_show_codec_n_usage[] =
750 "Usage: core show codec <number>\n"
751 " Displays codec mapping\n";
753 /*! Dump a frame for debugging purposes */
754 void ast_frame_dump(const char *name, struct ast_frame *f, char *prefix)
756 const char noname[] = "unknown";
757 char ftype[40] = "Unknown Frametype";
758 char cft[80];
759 char subclass[40] = "Unknown Subclass";
760 char csub[80];
761 char moreinfo[40] = "";
762 char cn[60];
763 char cp[40];
764 char cmn[40];
766 if (!name)
767 name = noname;
770 if (!f) {
771 ast_verbose("%s [ %s (NULL) ] [%s]\n",
772 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
773 term_color(cft, "HANGUP", COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
774 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
775 return;
777 /* XXX We should probably print one each of voice and video when the format changes XXX */
778 if (f->frametype == AST_FRAME_VOICE)
779 return;
780 if (f->frametype == AST_FRAME_VIDEO)
781 return;
782 switch(f->frametype) {
783 case AST_FRAME_DTMF_BEGIN:
784 strcpy(ftype, "DTMF Begin");
785 subclass[0] = f->subclass;
786 subclass[1] = '\0';
787 break;
788 case AST_FRAME_DTMF_END:
789 strcpy(ftype, "DTMF End");
790 subclass[0] = f->subclass;
791 subclass[1] = '\0';
792 break;
793 case AST_FRAME_CONTROL:
794 strcpy(ftype, "Control");
795 switch(f->subclass) {
796 case AST_CONTROL_HANGUP:
797 strcpy(subclass, "Hangup");
798 break;
799 case AST_CONTROL_RING:
800 strcpy(subclass, "Ring");
801 break;
802 case AST_CONTROL_RINGING:
803 strcpy(subclass, "Ringing");
804 break;
805 case AST_CONTROL_ANSWER:
806 strcpy(subclass, "Answer");
807 break;
808 case AST_CONTROL_BUSY:
809 strcpy(subclass, "Busy");
810 break;
811 case AST_CONTROL_TAKEOFFHOOK:
812 strcpy(subclass, "Take Off Hook");
813 break;
814 case AST_CONTROL_OFFHOOK:
815 strcpy(subclass, "Line Off Hook");
816 break;
817 case AST_CONTROL_CONGESTION:
818 strcpy(subclass, "Congestion");
819 break;
820 case AST_CONTROL_FLASH:
821 strcpy(subclass, "Flash");
822 break;
823 case AST_CONTROL_WINK:
824 strcpy(subclass, "Wink");
825 break;
826 case AST_CONTROL_OPTION:
827 strcpy(subclass, "Option");
828 break;
829 case AST_CONTROL_RADIO_KEY:
830 strcpy(subclass, "Key Radio");
831 break;
832 case AST_CONTROL_RADIO_UNKEY:
833 strcpy(subclass, "Unkey Radio");
834 break;
835 case -1:
836 strcpy(subclass, "Stop generators");
837 break;
838 default:
839 snprintf(subclass, sizeof(subclass), "Unknown control '%d'", f->subclass);
841 break;
842 case AST_FRAME_NULL:
843 strcpy(ftype, "Null Frame");
844 strcpy(subclass, "N/A");
845 break;
846 case AST_FRAME_IAX:
847 /* Should never happen */
848 strcpy(ftype, "IAX Specific");
849 snprintf(subclass, sizeof(subclass), "IAX Frametype %d", f->subclass);
850 break;
851 case AST_FRAME_TEXT:
852 strcpy(ftype, "Text");
853 strcpy(subclass, "N/A");
854 ast_copy_string(moreinfo, f->data, sizeof(moreinfo));
855 break;
856 case AST_FRAME_IMAGE:
857 strcpy(ftype, "Image");
858 snprintf(subclass, sizeof(subclass), "Image format %s\n", ast_getformatname(f->subclass));
859 break;
860 case AST_FRAME_HTML:
861 strcpy(ftype, "HTML");
862 switch(f->subclass) {
863 case AST_HTML_URL:
864 strcpy(subclass, "URL");
865 ast_copy_string(moreinfo, f->data, sizeof(moreinfo));
866 break;
867 case AST_HTML_DATA:
868 strcpy(subclass, "Data");
869 break;
870 case AST_HTML_BEGIN:
871 strcpy(subclass, "Begin");
872 break;
873 case AST_HTML_END:
874 strcpy(subclass, "End");
875 break;
876 case AST_HTML_LDCOMPLETE:
877 strcpy(subclass, "Load Complete");
878 break;
879 case AST_HTML_NOSUPPORT:
880 strcpy(subclass, "No Support");
881 break;
882 case AST_HTML_LINKURL:
883 strcpy(subclass, "Link URL");
884 ast_copy_string(moreinfo, f->data, sizeof(moreinfo));
885 break;
886 case AST_HTML_UNLINK:
887 strcpy(subclass, "Unlink");
888 break;
889 case AST_HTML_LINKREJECT:
890 strcpy(subclass, "Link Reject");
891 break;
892 default:
893 snprintf(subclass, sizeof(subclass), "Unknown HTML frame '%d'\n", f->subclass);
894 break;
896 break;
897 case AST_FRAME_MODEM:
898 strcpy(ftype, "Modem");
899 switch (f->subclass) {
900 case AST_MODEM_T38:
901 strcpy(subclass, "T.38");
902 break;
903 case AST_MODEM_V150:
904 strcpy(subclass, "V.150");
905 break;
906 default:
907 snprintf(subclass, sizeof(subclass), "Unknown MODEM frame '%d'\n", f->subclass);
908 break;
910 break;
911 default:
912 snprintf(ftype, sizeof(ftype), "Unknown Frametype '%d'", f->frametype);
914 if (!ast_strlen_zero(moreinfo))
915 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) '%s' ] [%s]\n",
916 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
917 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
918 f->frametype,
919 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
920 f->subclass,
921 term_color(cmn, moreinfo, COLOR_BRGREEN, COLOR_BLACK, sizeof(cmn)),
922 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
923 else
924 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) ] [%s]\n",
925 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
926 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
927 f->frametype,
928 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
929 f->subclass,
930 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
934 #ifdef TRACE_FRAMES
935 static int show_frame_stats(int fd, int argc, char *argv[])
937 struct ast_frame *f;
938 int x=1;
939 if (argc != 4)
940 return RESULT_SHOWUSAGE;
941 AST_LIST_LOCK(&headerlist);
942 ast_cli(fd, " Framer Statistics \n");
943 ast_cli(fd, "---------------------------\n");
944 ast_cli(fd, "Total allocated headers: %d\n", headers);
945 ast_cli(fd, "Queue Dump:\n");
946 AST_LIST_TRAVERSE(&headerlist, f, frame_list)
947 ast_cli(fd, "%d. Type %d, subclass %d from %s\n", x++, f->frametype, f->subclass, f->src ? f->src : "<Unknown>");
948 AST_LIST_UNLOCK(&headerlist);
949 return RESULT_SUCCESS;
952 static char frame_stats_usage[] =
953 "Usage: core show frame stats\n"
954 " Displays debugging statistics from framer\n";
955 #endif
957 /* Builtin Asterisk CLI-commands for debugging */
958 static struct ast_cli_entry cli_show_codecs = {
959 { "show", "codecs", NULL },
960 show_codecs_deprecated, NULL,
961 NULL };
963 static struct ast_cli_entry cli_show_audio_codecs = {
964 { "show", "audio", "codecs", NULL },
965 show_codecs_deprecated, NULL,
966 NULL };
968 static struct ast_cli_entry cli_show_video_codecs = {
969 { "show", "video", "codecs", NULL },
970 show_codecs_deprecated, NULL,
971 NULL };
973 static struct ast_cli_entry cli_show_image_codecs = {
974 { "show", "image", "codecs", NULL },
975 show_codecs_deprecated, NULL,
976 NULL };
978 static struct ast_cli_entry cli_show_codec = {
979 { "show", "codec", NULL },
980 show_codec_n_deprecated, NULL,
981 NULL };
983 #ifdef TRACE_FRAMES
984 static struct ast_cli_entry cli_show_frame_stats = {
985 { "show", "frame", "stats", NULL },
986 show_frame_stats, NULL,
987 NULL };
988 #endif
990 static struct ast_cli_entry my_clis[] = {
991 { { "core", "show", "codecs", NULL },
992 show_codecs, "Displays a list of codecs",
993 frame_show_codecs_usage, NULL, &cli_show_codecs },
995 { { "core", "show", "audio", "codecs", NULL },
996 show_codecs, "Displays a list of audio codecs",
997 frame_show_codecs_usage, NULL, &cli_show_audio_codecs },
999 { { "core", "show", "video", "codecs", NULL },
1000 show_codecs, "Displays a list of video codecs",
1001 frame_show_codecs_usage, NULL, &cli_show_video_codecs },
1003 { { "core", "show", "image", "codecs", NULL },
1004 show_codecs, "Displays a list of image codecs",
1005 frame_show_codecs_usage, NULL, &cli_show_image_codecs },
1007 { { "core", "show", "codec", NULL },
1008 show_codec_n, "Shows a specific codec",
1009 frame_show_codec_n_usage, NULL, &cli_show_codec },
1011 #ifdef TRACE_FRAMES
1012 { { "core", "show", "frame", "stats", NULL },
1013 show_frame_stats, "Shows frame statistics",
1014 frame_stats_usage, NULL, &cli_show_frame_stats },
1015 #endif
1018 int init_framer(void)
1020 ast_cli_register_multiple(my_clis, sizeof(my_clis) / sizeof(struct ast_cli_entry));
1021 return 0;
1024 void ast_codec_pref_convert(struct ast_codec_pref *pref, char *buf, size_t size, int right)
1026 int x, differential = (int) 'A', mem;
1027 char *from, *to;
1029 if(right) {
1030 from = pref->order;
1031 to = buf;
1032 mem = size;
1033 } else {
1034 to = pref->order;
1035 from = buf;
1036 mem = 32;
1039 memset(to, 0, mem);
1040 for (x = 0; x < 32 ; x++) {
1041 if(!from[x])
1042 break;
1043 to[x] = right ? (from[x] + differential) : (from[x] - differential);
1047 int ast_codec_pref_string(struct ast_codec_pref *pref, char *buf, size_t size)
1049 int x, codec;
1050 size_t total_len, slen;
1051 char *formatname;
1053 memset(buf,0,size);
1054 total_len = size;
1055 buf[0] = '(';
1056 total_len--;
1057 for(x = 0; x < 32 ; x++) {
1058 if(total_len <= 0)
1059 break;
1060 if(!(codec = ast_codec_pref_index(pref,x)))
1061 break;
1062 if((formatname = ast_getformatname(codec))) {
1063 slen = strlen(formatname);
1064 if(slen > total_len)
1065 break;
1066 strncat(buf, formatname, total_len - 1); /* safe */
1067 total_len -= slen;
1069 if(total_len && x < 31 && ast_codec_pref_index(pref , x + 1)) {
1070 strncat(buf, "|", total_len - 1); /* safe */
1071 total_len--;
1074 if(total_len) {
1075 strncat(buf, ")", total_len - 1); /* safe */
1076 total_len--;
1079 return size - total_len;
1082 int ast_codec_pref_index(struct ast_codec_pref *pref, int index)
1084 int slot = 0;
1087 if((index >= 0) && (index < sizeof(pref->order))) {
1088 slot = pref->order[index];
1091 return slot ? AST_FORMAT_LIST[slot-1].bits : 0;
1094 /*! \brief Remove codec from pref list */
1095 void ast_codec_pref_remove(struct ast_codec_pref *pref, int format)
1097 struct ast_codec_pref oldorder;
1098 int x, y = 0;
1099 int slot;
1100 int size;
1102 if(!pref->order[0])
1103 return;
1105 memcpy(&oldorder, pref, sizeof(oldorder));
1106 memset(pref, 0, sizeof(*pref));
1108 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1109 slot = oldorder.order[x];
1110 size = oldorder.framing[x];
1111 if(! slot)
1112 break;
1113 if(AST_FORMAT_LIST[slot-1].bits != format) {
1114 pref->order[y] = slot;
1115 pref->framing[y++] = size;
1121 /*! \brief Append codec to list */
1122 int ast_codec_pref_append(struct ast_codec_pref *pref, int format)
1124 int x, newindex = 0;
1126 ast_codec_pref_remove(pref, format);
1128 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1129 if(AST_FORMAT_LIST[x].bits == format) {
1130 newindex = x + 1;
1131 break;
1135 if(newindex) {
1136 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1137 if(!pref->order[x]) {
1138 pref->order[x] = newindex;
1139 break;
1144 return x;
1147 /*! \brief Prepend codec to list */
1148 void ast_codec_pref_prepend(struct ast_codec_pref *pref, int format, int only_if_existing)
1150 int x, newindex = 0;
1152 /* First step is to get the codecs "index number" */
1153 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1154 if (AST_FORMAT_LIST[x].bits == format) {
1155 newindex = x + 1;
1156 break;
1159 /* Done if its unknown */
1160 if (!newindex)
1161 return;
1163 /* Now find any existing occurrence, or the end */
1164 for (x = 0; x < 32; x++) {
1165 if (!pref->order[x] || pref->order[x] == newindex)
1166 break;
1169 if (only_if_existing && !pref->order[x])
1170 return;
1172 /* Move down to make space to insert - either all the way to the end,
1173 or as far as the existing location (which will be overwritten) */
1174 for (; x > 0; x--) {
1175 pref->order[x] = pref->order[x - 1];
1176 pref->framing[x] = pref->framing[x - 1];
1179 /* And insert the new entry */
1180 pref->order[0] = newindex;
1181 pref->framing[0] = 0; /* ? */
1184 /*! \brief Set packet size for codec */
1185 int ast_codec_pref_setsize(struct ast_codec_pref *pref, int format, int framems)
1187 int x, index = -1;
1189 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1190 if(AST_FORMAT_LIST[x].bits == format) {
1191 index = x;
1192 break;
1196 if(index < 0)
1197 return -1;
1199 /* size validation */
1200 if(!framems)
1201 framems = AST_FORMAT_LIST[index].def_ms;
1203 if(AST_FORMAT_LIST[index].inc_ms && framems % AST_FORMAT_LIST[index].inc_ms) /* avoid division by zero */
1204 framems -= framems % AST_FORMAT_LIST[index].inc_ms;
1206 if(framems < AST_FORMAT_LIST[index].min_ms)
1207 framems = AST_FORMAT_LIST[index].min_ms;
1209 if(framems > AST_FORMAT_LIST[index].max_ms)
1210 framems = AST_FORMAT_LIST[index].max_ms;
1213 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1214 if(pref->order[x] == (index + 1)) {
1215 pref->framing[x] = framems;
1216 break;
1220 return x;
1223 /*! \brief Get packet size for codec */
1224 struct ast_format_list ast_codec_pref_getsize(struct ast_codec_pref *pref, int format)
1226 int x, index = -1, framems = 0;
1227 struct ast_format_list fmt = {0};
1229 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1230 if(AST_FORMAT_LIST[x].bits == format) {
1231 fmt = AST_FORMAT_LIST[x];
1232 index = x;
1233 break;
1237 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1238 if(pref->order[x] == (index + 1)) {
1239 framems = pref->framing[x];
1240 break;
1244 /* size validation */
1245 if(!framems)
1246 framems = AST_FORMAT_LIST[index].def_ms;
1248 if(AST_FORMAT_LIST[index].inc_ms && framems % AST_FORMAT_LIST[index].inc_ms) /* avoid division by zero */
1249 framems -= framems % AST_FORMAT_LIST[index].inc_ms;
1251 if(framems < AST_FORMAT_LIST[index].min_ms)
1252 framems = AST_FORMAT_LIST[index].min_ms;
1254 if(framems > AST_FORMAT_LIST[index].max_ms)
1255 framems = AST_FORMAT_LIST[index].max_ms;
1257 fmt.cur_ms = framems;
1259 return fmt;
1262 /*! \brief Pick a codec */
1263 int ast_codec_choose(struct ast_codec_pref *pref, int formats, int find_best)
1265 int x, ret = 0, slot;
1267 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1268 slot = pref->order[x];
1270 if (!slot)
1271 break;
1272 if (formats & AST_FORMAT_LIST[slot-1].bits) {
1273 ret = AST_FORMAT_LIST[slot-1].bits;
1274 break;
1277 if(ret & AST_FORMAT_AUDIO_MASK)
1278 return ret;
1280 if (option_debug > 3)
1281 ast_log(LOG_DEBUG, "Could not find preferred codec - %s\n", find_best ? "Going for the best codec" : "Returning zero codec");
1283 return find_best ? ast_best_codec(formats) : 0;
1286 void ast_parse_allow_disallow(struct ast_codec_pref *pref, int *mask, const char *list, int allowing)
1288 char *parse = NULL, *this = NULL, *psize = NULL;
1289 int format = 0, framems = 0;
1291 parse = ast_strdupa(list);
1292 while ((this = strsep(&parse, ","))) {
1293 framems = 0;
1294 if ((psize = strrchr(this, ':'))) {
1295 *psize++ = '\0';
1296 if (option_debug)
1297 ast_log(LOG_DEBUG,"Packetization for codec: %s is %s\n", this, psize);
1298 framems = atoi(psize);
1299 if (framems < 0)
1300 framems = 0;
1302 if (!(format = ast_getformatbyname(this))) {
1303 ast_log(LOG_WARNING, "Cannot %s unknown format '%s'\n", allowing ? "allow" : "disallow", this);
1304 continue;
1307 if (mask) {
1308 if (allowing)
1309 *mask |= format;
1310 else
1311 *mask &= ~format;
1314 /* Set up a preference list for audio. Do not include video in preferences
1315 since we can not transcode video and have to use whatever is offered
1317 if (pref && (format & AST_FORMAT_AUDIO_MASK)) {
1318 if (strcasecmp(this, "all")) {
1319 if (allowing) {
1320 ast_codec_pref_append(pref, format);
1321 ast_codec_pref_setsize(pref, format, framems);
1323 else
1324 ast_codec_pref_remove(pref, format);
1325 } else if (!allowing) {
1326 memset(pref, 0, sizeof(*pref));
1332 static int g723_len(unsigned char buf)
1334 enum frame_type type = buf & TYPE_MASK;
1336 switch(type) {
1337 case TYPE_DONTSEND:
1338 return 0;
1339 break;
1340 case TYPE_SILENCE:
1341 return 4;
1342 break;
1343 case TYPE_HIGH:
1344 return 24;
1345 break;
1346 case TYPE_LOW:
1347 return 20;
1348 break;
1349 default:
1350 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", type);
1352 return -1;
1355 static int g723_samples(unsigned char *buf, int maxlen)
1357 int pos = 0;
1358 int samples = 0;
1359 int res;
1360 while(pos < maxlen) {
1361 res = g723_len(buf[pos]);
1362 if (res <= 0)
1363 break;
1364 samples += 240;
1365 pos += res;
1367 return samples;
1370 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
1372 int byte = bit / 8; /* byte containing first bit */
1373 int rem = 8 - (bit % 8); /* remaining bits in first byte */
1374 unsigned char ret = 0;
1376 if (n <= 0 || n > 8)
1377 return 0;
1379 if (rem < n) {
1380 ret = (data[byte] << (n - rem));
1381 ret |= (data[byte + 1] >> (8 - n + rem));
1382 } else {
1383 ret = (data[byte] >> (rem - n));
1386 return (ret & (0xff >> (8 - n)));
1389 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
1391 static int SpeexWBSubModeSz[] = {
1392 0, 36, 112, 192,
1393 352, 0, 0, 0 };
1394 int off = bit;
1395 unsigned char c;
1397 /* skip up to two wideband frames */
1398 if (((len * 8 - off) >= 5) &&
1399 get_n_bits_at(data, 1, off)) {
1400 c = get_n_bits_at(data, 3, off + 1);
1401 off += SpeexWBSubModeSz[c];
1403 if (((len * 8 - off) >= 5) &&
1404 get_n_bits_at(data, 1, off)) {
1405 c = get_n_bits_at(data, 3, off + 1);
1406 off += SpeexWBSubModeSz[c];
1408 if (((len * 8 - off) >= 5) &&
1409 get_n_bits_at(data, 1, off)) {
1410 ast_log(LOG_WARNING, "Encountered corrupt speex frame; too many wideband frames in a row.\n");
1411 return -1;
1416 return off - bit;
1419 static int speex_samples(unsigned char *data, int len)
1421 static int SpeexSubModeSz[] = {
1422 5, 43, 119, 160,
1423 220, 300, 364, 492,
1424 79, 0, 0, 0,
1425 0, 0, 0, 0 };
1426 static int SpeexInBandSz[] = {
1427 1, 1, 4, 4,
1428 4, 4, 4, 4,
1429 8, 8, 16, 16,
1430 32, 32, 64, 64 };
1431 int bit = 0;
1432 int cnt = 0;
1433 int off;
1434 unsigned char c;
1436 while ((len * 8 - bit) >= 5) {
1437 /* skip wideband frames */
1438 off = speex_get_wb_sz_at(data, len, bit);
1439 if (off < 0) {
1440 ast_log(LOG_WARNING, "Had error while reading wideband frames for speex samples\n");
1441 break;
1443 bit += off;
1445 if ((len * 8 - bit) < 5) {
1446 ast_log(LOG_WARNING, "Not enough bits remaining after wide band for speex samples.\n");
1447 break;
1450 /* get control bits */
1451 c = get_n_bits_at(data, 5, bit);
1452 bit += 5;
1454 if (c == 15) {
1455 /* terminator */
1456 break;
1457 } else if (c == 14) {
1458 /* in-band signal; next 4 bits contain signal id */
1459 c = get_n_bits_at(data, 4, bit);
1460 bit += 4;
1461 bit += SpeexInBandSz[c];
1462 } else if (c == 13) {
1463 /* user in-band; next 5 bits contain msg len */
1464 c = get_n_bits_at(data, 5, bit);
1465 bit += 5;
1466 bit += c * 8;
1467 } else if (c > 8) {
1468 /* unknown */
1469 break;
1470 } else {
1471 /* skip number bits for submode (less the 5 control bits) */
1472 bit += SpeexSubModeSz[c] - 5;
1473 cnt += 160; /* new frame */
1476 return cnt;
1479 int ast_codec_get_samples(struct ast_frame *f)
1481 int samples=0;
1482 switch(f->subclass) {
1483 case AST_FORMAT_SPEEX:
1484 samples = speex_samples(f->data, f->datalen);
1485 break;
1486 case AST_FORMAT_G723_1:
1487 samples = g723_samples(f->data, f->datalen);
1488 break;
1489 case AST_FORMAT_ILBC:
1490 samples = 240 * (f->datalen / 50);
1491 break;
1492 case AST_FORMAT_GSM:
1493 samples = 160 * (f->datalen / 33);
1494 break;
1495 case AST_FORMAT_G729A:
1496 samples = f->datalen * 8;
1497 break;
1498 case AST_FORMAT_SLINEAR:
1499 samples = f->datalen / 2;
1500 break;
1501 case AST_FORMAT_LPC10:
1502 /* assumes that the RTP packet contains one LPC10 frame */
1503 samples = 22 * 8;
1504 samples += (((char *)(f->data))[7] & 0x1) * 8;
1505 break;
1506 case AST_FORMAT_ULAW:
1507 case AST_FORMAT_ALAW:
1508 samples = f->datalen;
1509 break;
1510 case AST_FORMAT_G722:
1511 case AST_FORMAT_ADPCM:
1512 case AST_FORMAT_G726:
1513 case AST_FORMAT_G726_AAL2:
1514 samples = f->datalen * 2;
1515 break;
1516 default:
1517 ast_log(LOG_WARNING, "Unable to calculate samples for format %s\n", ast_getformatname(f->subclass));
1519 return samples;
1522 int ast_codec_get_len(int format, int samples)
1524 int len = 0;
1526 /* XXX Still need speex, g723, and lpc10 XXX */
1527 switch(format) {
1528 case AST_FORMAT_ILBC:
1529 len = (samples / 240) * 50;
1530 break;
1531 case AST_FORMAT_GSM:
1532 len = (samples / 160) * 33;
1533 break;
1534 case AST_FORMAT_G729A:
1535 len = samples / 8;
1536 break;
1537 case AST_FORMAT_SLINEAR:
1538 len = samples * 2;
1539 break;
1540 case AST_FORMAT_ULAW:
1541 case AST_FORMAT_ALAW:
1542 len = samples;
1543 break;
1544 case AST_FORMAT_G722:
1545 case AST_FORMAT_ADPCM:
1546 case AST_FORMAT_G726:
1547 case AST_FORMAT_G726_AAL2:
1548 len = samples / 2;
1549 break;
1550 default:
1551 ast_log(LOG_WARNING, "Unable to calculate sample length for format %s\n", ast_getformatname(format));
1554 return len;
1557 int ast_frame_adjust_volume(struct ast_frame *f, int adjustment)
1559 int count;
1560 short *fdata = f->data;
1561 short adjust_value = abs(adjustment);
1563 if ((f->frametype != AST_FRAME_VOICE) || (f->subclass != AST_FORMAT_SLINEAR))
1564 return -1;
1566 if (!adjustment)
1567 return 0;
1569 for (count = 0; count < f->samples; count++) {
1570 if (adjustment > 0) {
1571 ast_slinear_saturated_multiply(&fdata[count], &adjust_value);
1572 } else if (adjustment < 0) {
1573 ast_slinear_saturated_divide(&fdata[count], &adjust_value);
1577 return 0;
1580 int ast_frame_slinear_sum(struct ast_frame *f1, struct ast_frame *f2)
1582 int count;
1583 short *data1, *data2;
1585 if ((f1->frametype != AST_FRAME_VOICE) || (f1->subclass != AST_FORMAT_SLINEAR))
1586 return -1;
1588 if ((f2->frametype != AST_FRAME_VOICE) || (f2->subclass != AST_FORMAT_SLINEAR))
1589 return -1;
1591 if (f1->samples != f2->samples)
1592 return -1;
1594 for (count = 0, data1 = f1->data, data2 = f2->data;
1595 count < f1->samples;
1596 count++, data1++, data2++)
1597 ast_slinear_saturated_add(data1, data2);
1599 return 0;