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.
21 * \brief Frame and codec manipulation routines
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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 #include "asterisk/dsp.h"
41 #include "asterisk/file.h"
43 #if !defined(LOW_MEMORY)
44 static void frame_cache_cleanup(void *data);
46 /*! \brief A per-thread cache of frame headers */
47 AST_THREADSTORAGE_CUSTOM(frame_cache, NULL, frame_cache_cleanup);
50 * \brief Maximum ast_frame cache size
52 * In most cases where the frame header cache will be useful, the size
53 * of the cache will stay very small. However, it is not always the case that
54 * the same thread that allocates the frame will be the one freeing them, so
55 * sometimes a thread will never have any frames in its cache, or the cache
56 * will never be pulled from. For the latter case, we limit the maximum size.
58 #define FRAME_CACHE_MAX_SIZE 10
60 /*! \brief This is just so ast_frames, a list head struct for holding a list of
61 * ast_frame structures, is defined. */
62 AST_LIST_HEAD_NOLOCK(ast_frames, ast_frame);
64 struct ast_frame_cache {
65 struct ast_frames list;
70 #define SMOOTHER_SIZE 8000
75 TYPE_SILENCE, /* 0x2 */
76 TYPE_DONTSEND /* 0x3 */
86 unsigned int opt_needs_swap:1;
88 struct timeval delivery;
89 char data[SMOOTHER_SIZE];
90 char framedata[SMOOTHER_SIZE + AST_FRIENDLY_OFFSET];
91 struct ast_frame *opt;
95 /*! \brief Definition of supported media formats (codecs) */
96 static const struct ast_format_list AST_FORMAT_LIST[] = {
97 { AST_FORMAT_G723_1 , "g723", 8000, "G.723.1", 20, 30, 300, 30, 30 }, /*!< G723.1 */
98 { AST_FORMAT_GSM, "gsm", 8000, "GSM", 33, 20, 300, 20, 20 }, /*!< codec_gsm.c */
99 { AST_FORMAT_ULAW, "ulaw", 8000, "G.711 u-law", 80, 10, 150, 10, 20 }, /*!< codec_ulaw.c */
100 { AST_FORMAT_ALAW, "alaw", 8000, "G.711 A-law", 80, 10, 150, 10, 20 }, /*!< codec_alaw.c */
101 { AST_FORMAT_G726, "g726", 8000, "G.726 RFC3551", 40, 10, 300, 10, 20 }, /*!< codec_g726.c */
102 { AST_FORMAT_ADPCM, "adpcm" , 8000, "ADPCM", 40, 10, 300, 10, 20 }, /*!< codec_adpcm.c */
103 { AST_FORMAT_SLINEAR, "slin", 8000, "16 bit Signed Linear PCM", 160, 10, 70, 10, 20, AST_SMOOTHER_FLAG_BE }, /*!< Signed linear */
104 { AST_FORMAT_LPC10, "lpc10", 8000, "LPC10", 7, 20, 20, 20, 20 }, /*!< codec_lpc10.c */
105 { AST_FORMAT_G729A, "g729", 8000, "G.729A", 10, 10, 230, 10, 20, AST_SMOOTHER_FLAG_G729 }, /*!< Binary commercial distribution */
106 { AST_FORMAT_SPEEX, "speex", 8000, "SpeeX", 10, 10, 60, 10, 20 }, /*!< codec_speex.c */
107 { AST_FORMAT_ILBC, "ilbc", 8000, "iLBC", 50, 30, 30, 30, 30 }, /*!< codec_ilbc.c */ /* inc=30ms - workaround */
108 { AST_FORMAT_G726_AAL2, "g726aal2", 8000, "G.726 AAL2", 40, 10, 300, 10, 20 }, /*!< codec_g726.c */
109 { AST_FORMAT_G722, "g722", 16000, "G722", 80, 10, 150, 10, 20 }, /*!< codec_g722.c */
110 { AST_FORMAT_SLINEAR16, "slin16", 16000, "16 bit Signed Linear PCM (16kHz)", 320, 10, 70, 10, 20, AST_SMOOTHER_FLAG_BE }, /*!< Signed linear (16kHz) */
111 { AST_FORMAT_JPEG, "jpeg", 0, "JPEG image"}, /*!< See format_jpeg.c */
112 { AST_FORMAT_PNG, "png", 0, "PNG image"}, /*!< PNG Image format */
113 { AST_FORMAT_H261, "h261", 0, "H.261 Video" }, /*!< H.261 Video Passthrough */
114 { AST_FORMAT_H263, "h263", 0, "H.263 Video" }, /*!< H.263 Passthrough support, see format_h263.c */
115 { AST_FORMAT_H263_PLUS, "h263p", 0, "H.263+ Video" }, /*!< H.263plus passthrough support See format_h263.c */
116 { AST_FORMAT_H264, "h264", 0, "H.264 Video" }, /*!< Passthrough support, see format_h263.c */
117 { AST_FORMAT_MP4_VIDEO, "mpeg4", 0, "MPEG4 Video" }, /*!< Passthrough support for MPEG4 */
118 { AST_FORMAT_T140RED, "red", 1, "T.140 Realtime Text with redundancy"}, /*!< Redundant T.140 Realtime Text */
119 { AST_FORMAT_T140, "t140", 0, "Passthrough T.140 Realtime Text" }, /*!< Passthrough support for T.140 Realtime Text */
120 { AST_FORMAT_SIREN7, "siren7", 16000, "ITU G.722.1 (Siren7, licensed from Polycom)", 80, 20, 80, 20, 20 }, /*!< Binary commercial distribution */
121 { AST_FORMAT_SIREN14, "siren14", 32000, "ITU G.722.1 Annex C, (Siren14, licensed from Polycom)", 120, 20, 80, 20, 20 }, /*!< Binary commercial distribution */
122 { AST_FORMAT_TESTLAW, "testlaw", 8000, "G.711 test-law", 80, 10, 150, 10, 20 }, /*!< codec_ulaw.c */
125 struct ast_frame ast_null_frame = { AST_FRAME_NULL, };
127 static int smoother_frame_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
129 if (s->flags & AST_SMOOTHER_FLAG_G729) {
131 ast_log(LOG_NOTICE, "Dropping extra frame of G.729 since we already have a VAD frame at the end\n");
136 ast_swapcopy_samples(s->data + s->len, f->data.ptr, f->samples);
138 memcpy(s->data + s->len, f->data.ptr, f->datalen);
140 /* If either side is empty, reset the delivery time */
141 if (!s->len || ast_tvzero(f->delivery) || ast_tvzero(s->delivery)) { /* XXX really ? */
142 s->delivery = f->delivery;
144 s->len += f->datalen;
149 void ast_smoother_reset(struct ast_smoother *s, int bytes)
151 memset(s, 0, sizeof(*s));
155 void ast_smoother_reconfigure(struct ast_smoother *s, int bytes)
157 /* if there is no change, then nothing to do */
158 if (s->size == bytes) {
161 /* set the new desired output size */
163 /* if there is no 'optimized' frame in the smoother,
164 * then there is nothing left to do
169 /* there is an 'optimized' frame here at the old size,
170 * but it must now be put into the buffer so the data
171 * can be extracted at the new size
173 smoother_frame_feed(s, s->opt, s->opt_needs_swap);
177 struct ast_smoother *ast_smoother_new(int size)
179 struct ast_smoother *s;
182 if ((s = ast_malloc(sizeof(*s))))
183 ast_smoother_reset(s, size);
187 int ast_smoother_get_flags(struct ast_smoother *s)
192 void ast_smoother_set_flags(struct ast_smoother *s, int flags)
197 int ast_smoother_test_flag(struct ast_smoother *s, int flag)
199 return (s->flags & flag);
202 int __ast_smoother_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
204 if (f->frametype != AST_FRAME_VOICE) {
205 ast_log(LOG_WARNING, "Huh? Can't smooth a non-voice frame!\n");
209 s->format = f->subclass.codec;
210 s->samplesperbyte = (float)f->samples / (float)f->datalen;
211 } else if (s->format != f->subclass.codec) {
212 ast_log(LOG_WARNING, "Smoother was working on %s format frames, now trying to feed %s?\n",
213 ast_getformatname(s->format), ast_getformatname(f->subclass.codec));
216 if (s->len + f->datalen > SMOOTHER_SIZE) {
217 ast_log(LOG_WARNING, "Out of smoother space\n");
220 if (((f->datalen == s->size) ||
221 ((f->datalen < 10) && (s->flags & AST_SMOOTHER_FLAG_G729))) &&
224 (f->offset >= AST_MIN_OFFSET)) {
225 /* Optimize by sending the frame we just got
226 on the next read, thus eliminating the douple
229 ast_swapcopy_samples(f->data.ptr, f->data.ptr, f->samples);
231 s->opt_needs_swap = swap ? 1 : 0;
235 return smoother_frame_feed(s, f, swap);
238 struct ast_frame *ast_smoother_read(struct ast_smoother *s)
240 struct ast_frame *opt;
243 /* IF we have an optimization frame, send it */
245 if (s->opt->offset < AST_FRIENDLY_OFFSET)
246 ast_log(LOG_WARNING, "Returning a frame of inappropriate offset (%d).\n",
253 /* Make sure we have enough data */
254 if (s->len < s->size) {
255 /* Or, if this is a G.729 frame with VAD on it, send it immediately anyway */
256 if (!((s->flags & AST_SMOOTHER_FLAG_G729) && (s->len % 10)))
263 s->f.frametype = AST_FRAME_VOICE;
264 s->f.subclass.codec = s->format;
265 s->f.data.ptr = s->framedata + AST_FRIENDLY_OFFSET;
266 s->f.offset = AST_FRIENDLY_OFFSET;
268 /* Samples will be improper given VAD, but with VAD the concept really doesn't even exist */
269 s->f.samples = len * s->samplesperbyte; /* XXX rounding */
270 s->f.delivery = s->delivery;
272 memcpy(s->f.data.ptr, s->data, len);
274 /* Move remaining data to the front if applicable */
276 /* In principle this should all be fine because if we are sending
277 G.729 VAD, the next timestamp will take over anyawy */
278 memmove(s->data, s->data + len, s->len);
279 if (!ast_tvzero(s->delivery)) {
280 /* If we have delivery time, increment it, otherwise, leave it at 0 */
281 s->delivery = ast_tvadd(s->delivery, ast_samp2tv(s->f.samples, ast_format_rate(s->format)));
288 void ast_smoother_free(struct ast_smoother *s)
293 static struct ast_frame *ast_frame_header_new(void)
297 #if !defined(LOW_MEMORY)
298 struct ast_frame_cache *frames;
300 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
301 if ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list))) {
302 size_t mallocd_len = f->mallocd_hdr_len;
303 memset(f, 0, sizeof(*f));
304 f->mallocd_hdr_len = mallocd_len;
305 f->mallocd = AST_MALLOCD_HDR;
310 if (!(f = ast_calloc_cache(1, sizeof(*f))))
313 if (!(f = ast_calloc(1, sizeof(*f))))
317 f->mallocd_hdr_len = sizeof(*f);
322 #if !defined(LOW_MEMORY)
323 static void frame_cache_cleanup(void *data)
325 struct ast_frame_cache *frames = data;
328 while ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list)))
335 static void __frame_free(struct ast_frame *fr, int cache)
340 #if !defined(LOW_MEMORY)
341 if (cache && fr->mallocd == AST_MALLOCD_HDR) {
342 /* Cool, only the header is malloc'd, let's just cache those for now
343 * to keep things simple... */
344 struct ast_frame_cache *frames;
346 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames))) &&
347 (frames->size < FRAME_CACHE_MAX_SIZE)) {
348 AST_LIST_INSERT_HEAD(&frames->list, fr, frame_list);
355 if (fr->mallocd & AST_MALLOCD_DATA) {
357 ast_free(fr->data.ptr - fr->offset);
359 if (fr->mallocd & AST_MALLOCD_SRC) {
361 ast_free((void *) fr->src);
363 if (fr->mallocd & AST_MALLOCD_HDR) {
369 void ast_frame_free(struct ast_frame *frame, int cache)
371 struct ast_frame *next;
373 for (next = AST_LIST_NEXT(frame, frame_list);
375 frame = next, next = frame ? AST_LIST_NEXT(frame, frame_list) : NULL) {
376 __frame_free(frame, cache);
381 * \brief 'isolates' a frame by duplicating non-malloc'ed components
382 * (header, src, data).
383 * On return all components are malloc'ed
385 struct ast_frame *ast_frisolate(struct ast_frame *fr)
387 struct ast_frame *out;
390 /* if none of the existing frame is malloc'd, let ast_frdup() do it
391 since it is more efficient
393 if (fr->mallocd == 0) {
394 return ast_frdup(fr);
397 /* if everything is already malloc'd, we are done */
398 if ((fr->mallocd & (AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA)) ==
399 (AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA)) {
403 if (!(fr->mallocd & AST_MALLOCD_HDR)) {
404 /* Allocate a new header if needed */
405 if (!(out = ast_frame_header_new())) {
408 out->frametype = fr->frametype;
409 out->subclass.codec = fr->subclass.codec;
410 out->datalen = fr->datalen;
411 out->samples = fr->samples;
412 out->offset = fr->offset;
413 /* Copy the timing data */
414 ast_copy_flags(out, fr, AST_FRFLAG_HAS_TIMING_INFO);
415 if (ast_test_flag(fr, AST_FRFLAG_HAS_TIMING_INFO)) {
418 out->seqno = fr->seqno;
424 if (!(fr->mallocd & AST_MALLOCD_SRC) && fr->src) {
425 if (!(out->src = ast_strdup(fr->src))) {
434 fr->mallocd &= ~AST_MALLOCD_SRC;
437 if (!(fr->mallocd & AST_MALLOCD_DATA)) {
439 out->data.uint32 = fr->data.uint32;
440 out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC;
443 if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
444 if (out->src != fr->src) {
445 ast_free((void *) out->src);
452 newdata += AST_FRIENDLY_OFFSET;
453 out->offset = AST_FRIENDLY_OFFSET;
454 out->datalen = fr->datalen;
455 memcpy(newdata, fr->data.ptr, fr->datalen);
456 out->data.ptr = newdata;
458 out->data = fr->data;
459 memset(&fr->data, 0, sizeof(fr->data));
460 fr->mallocd &= ~AST_MALLOCD_DATA;
463 out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA;
468 struct ast_frame *ast_frdup(const struct ast_frame *f)
470 struct ast_frame *out = NULL;
474 #if !defined(LOW_MEMORY)
475 struct ast_frame_cache *frames;
478 /* Start with standard stuff */
479 len = sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
480 /* If we have a source, add space for it */
482 * XXX Watch out here - if we receive a src which is not terminated
483 * properly, we can be easily attacked. Should limit the size we deal with.
486 srclen = strlen(f->src);
490 #if !defined(LOW_MEMORY)
491 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
492 AST_LIST_TRAVERSE_SAFE_BEGIN(&frames->list, out, frame_list) {
493 if (out->mallocd_hdr_len >= len) {
494 size_t mallocd_len = out->mallocd_hdr_len;
496 AST_LIST_REMOVE_CURRENT(frame_list);
497 memset(out, 0, sizeof(*out));
498 out->mallocd_hdr_len = mallocd_len;
504 AST_LIST_TRAVERSE_SAFE_END;
509 if (!(buf = ast_calloc_cache(1, len)))
512 out->mallocd_hdr_len = len;
515 out->frametype = f->frametype;
516 out->subclass.codec = f->subclass.codec;
517 out->datalen = f->datalen;
518 out->samples = f->samples;
519 out->delivery = f->delivery;
520 /* Set us as having malloc'd header only, so it will eventually
522 out->mallocd = AST_MALLOCD_HDR;
523 out->offset = AST_FRIENDLY_OFFSET;
525 out->data.ptr = buf + sizeof(*out) + AST_FRIENDLY_OFFSET;
526 memcpy(out->data.ptr, f->data.ptr, out->datalen);
528 out->data.uint32 = f->data.uint32;
531 /* This may seem a little strange, but it's to avoid a gcc (4.2.4) compiler warning */
533 out->src = buf + sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
534 src = (char *) out->src;
535 /* Must have space since we allocated for it */
538 ast_copy_flags(out, f, AST_FRFLAG_HAS_TIMING_INFO);
541 out->seqno = f->seqno;
545 void ast_swapcopy_samples(void *dst, const void *src, int samples)
548 unsigned short *dst_s = dst;
549 const unsigned short *src_s = src;
551 for (i = 0; i < samples; i++)
552 dst_s[i] = (src_s[i]<<8) | (src_s[i]>>8);
556 const struct ast_format_list *ast_get_format_list_index(int idx)
558 return &AST_FORMAT_LIST[idx];
561 const struct ast_format_list *ast_get_format_list(size_t *size)
563 *size = ARRAY_LEN(AST_FORMAT_LIST);
564 return AST_FORMAT_LIST;
567 char* ast_getformatname(format_t format)
570 char *ret = "unknown";
571 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
572 if (AST_FORMAT_LIST[x].bits == format) {
573 ret = AST_FORMAT_LIST[x].name;
580 char *ast_getformatname_multiple(char *buf, size_t size, format_t format)
584 char *start, *end = buf;
588 snprintf(end, size, "0x%llx (", (unsigned long long) format);
593 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
594 if (AST_FORMAT_LIST[x].bits & format) {
595 snprintf(end, size, "%s|", AST_FORMAT_LIST[x].name);
602 ast_copy_string(start, "nothing)", size);
608 static struct ast_codec_alias_table {
611 } ast_codec_alias_table[] = {
612 { "slinear", "slin"},
613 { "slinear16", "slin16"},
615 { "g722.1", "siren7"},
616 { "g722.1c", "siren14"},
619 static const char *ast_expand_codec_alias(const char *in)
623 for (x = 0; x < ARRAY_LEN(ast_codec_alias_table); x++) {
624 if (!strcmp(in,ast_codec_alias_table[x].alias))
625 return ast_codec_alias_table[x].realname;
630 format_t ast_getformatbyname(const char *name)
635 all = strcasecmp(name, "all") ? 0 : 1;
636 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
638 !strcasecmp(AST_FORMAT_LIST[x].name,name) ||
639 !strcasecmp(AST_FORMAT_LIST[x].name, ast_expand_codec_alias(name))) {
640 format |= AST_FORMAT_LIST[x].bits;
649 char *ast_codec2str(format_t codec)
652 char *ret = "unknown";
653 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
654 if (AST_FORMAT_LIST[x].bits == codec) {
655 ret = AST_FORMAT_LIST[x].desc;
662 static char *show_codecs(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
669 e->command = "core show codecs [audio|video|image|text]";
671 "Usage: core show codecs [audio|video|image|text]\n"
672 " Displays codec mapping\n";
678 if ((a->argc < 3) || (a->argc > 4))
679 return CLI_SHOWUSAGE;
681 if (!ast_opt_dont_warn)
682 ast_cli(a->fd, "Disclaimer: this command is for informational purposes only.\n"
683 "\tIt does not indicate anything about your configuration.\n");
685 ast_cli(a->fd, "%19s %9s %20s TYPE %8s %s\n","INT","BINARY","HEX","NAME","DESCRIPTION");
686 ast_cli(a->fd, "-----------------------------------------------------------------------------------\n");
687 for (i = 0; i < 63; i++) {
690 if (!strcasecmp(a->argv[3], "audio")) {
691 if (!((1LL << i) & AST_FORMAT_AUDIO_MASK)) {
694 } else if (!strcasecmp(a->argv[3], "video")) {
695 if (!((1LL << i) & AST_FORMAT_VIDEO_MASK)) {
698 } else if (!strcasecmp(a->argv[3], "image")) {
699 if (i != 16 && i != 17) {
702 } else if (!strcasecmp(a->argv[3], "text")) {
703 if (!((1LL << i) & AST_FORMAT_TEXT_MASK)) {
711 snprintf(hex, sizeof(hex), "(0x%llx)", 1LL << i);
712 ast_cli(a->fd, "%19llu (1 << %2d) %20s %5s %8s (%s)\n", 1LL << i, i, hex,
713 ((1LL << i) & AST_FORMAT_AUDIO_MASK) ? "audio" :
714 i == 16 || i == 17 ? "image" :
715 ((1LL << i) & AST_FORMAT_VIDEO_MASK) ? "video" :
716 ((1LL << i) & AST_FORMAT_TEXT_MASK) ? "text" :
718 ast_getformatname(1LL << i), ast_codec2str(1LL << i));
723 return CLI_SHOWUSAGE;
729 static char *show_codec_n(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
733 long long type_punned_codec;
737 e->command = "core show codec";
739 "Usage: core show codec <number>\n"
740 " Displays codec mapping\n";
747 return CLI_SHOWUSAGE;
749 if (sscanf(a->argv[3], "%30lld", &type_punned_codec) != 1) {
750 return CLI_SHOWUSAGE;
752 codec = type_punned_codec;
754 for (i = 0; i < 63; i++)
755 if (codec & (1LL << i)) {
757 ast_cli(a->fd, "%11llu (1 << %2d) %s\n", 1LL << i, i, ast_codec2str(1LL << i));
761 ast_cli(a->fd, "Codec %lld not found\n", (long long) codec);
766 /*! Dump a frame for debugging purposes */
767 void ast_frame_dump(const char *name, struct ast_frame *f, char *prefix)
769 const char noname[] = "unknown";
770 char ftype[40] = "Unknown Frametype";
772 char subclass[40] = "Unknown Subclass";
774 char moreinfo[40] = "";
778 const char *message = "Unknown";
785 ast_verbose("%s [ %s (NULL) ] [%s]\n",
786 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
787 term_color(cft, "HANGUP", COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
788 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
791 /* XXX We should probably print one each of voice and video when the format changes XXX */
792 if (f->frametype == AST_FRAME_VOICE)
794 if (f->frametype == AST_FRAME_VIDEO)
796 switch(f->frametype) {
797 case AST_FRAME_DTMF_BEGIN:
798 strcpy(ftype, "DTMF Begin");
799 subclass[0] = f->subclass.integer;
802 case AST_FRAME_DTMF_END:
803 strcpy(ftype, "DTMF End");
804 subclass[0] = f->subclass.integer;
807 case AST_FRAME_CONTROL:
808 strcpy(ftype, "Control");
809 switch (f->subclass.integer) {
810 case AST_CONTROL_HANGUP:
811 strcpy(subclass, "Hangup");
813 case AST_CONTROL_RING:
814 strcpy(subclass, "Ring");
816 case AST_CONTROL_RINGING:
817 strcpy(subclass, "Ringing");
819 case AST_CONTROL_ANSWER:
820 strcpy(subclass, "Answer");
822 case AST_CONTROL_BUSY:
823 strcpy(subclass, "Busy");
825 case AST_CONTROL_TAKEOFFHOOK:
826 strcpy(subclass, "Take Off Hook");
828 case AST_CONTROL_OFFHOOK:
829 strcpy(subclass, "Line Off Hook");
831 case AST_CONTROL_CONGESTION:
832 strcpy(subclass, "Congestion");
834 case AST_CONTROL_FLASH:
835 strcpy(subclass, "Flash");
837 case AST_CONTROL_WINK:
838 strcpy(subclass, "Wink");
840 case AST_CONTROL_OPTION:
841 strcpy(subclass, "Option");
843 case AST_CONTROL_RADIO_KEY:
844 strcpy(subclass, "Key Radio");
846 case AST_CONTROL_RADIO_UNKEY:
847 strcpy(subclass, "Unkey Radio");
849 case AST_CONTROL_HOLD:
850 strcpy(subclass, "Hold");
852 case AST_CONTROL_UNHOLD:
853 strcpy(subclass, "Unhold");
855 case AST_CONTROL_T38_PARAMETERS:
856 if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
859 struct ast_control_t38_parameters *parameters = f->data.ptr;
860 enum ast_control_t38 state = parameters->request_response;
861 if (state == AST_T38_REQUEST_NEGOTIATE)
862 message = "Negotiation Requested";
863 else if (state == AST_T38_REQUEST_TERMINATE)
864 message = "Negotiation Request Terminated";
865 else if (state == AST_T38_NEGOTIATED)
866 message = "Negotiated";
867 else if (state == AST_T38_TERMINATED)
868 message = "Terminated";
869 else if (state == AST_T38_REFUSED)
872 snprintf(subclass, sizeof(subclass), "T38_Parameters/%s", message);
875 strcpy(subclass, "Stop generators");
878 snprintf(subclass, sizeof(subclass), "Unknown control '%d'", f->subclass.integer);
882 strcpy(ftype, "Null Frame");
883 strcpy(subclass, "N/A");
886 /* Should never happen */
887 strcpy(ftype, "IAX Specific");
888 snprintf(subclass, sizeof(subclass), "IAX Frametype %d", f->subclass.integer);
891 strcpy(ftype, "Text");
892 strcpy(subclass, "N/A");
893 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
895 case AST_FRAME_IMAGE:
896 strcpy(ftype, "Image");
897 snprintf(subclass, sizeof(subclass), "Image format %s\n", ast_getformatname(f->subclass.codec));
900 strcpy(ftype, "HTML");
901 switch (f->subclass.integer) {
903 strcpy(subclass, "URL");
904 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
907 strcpy(subclass, "Data");
910 strcpy(subclass, "Begin");
913 strcpy(subclass, "End");
915 case AST_HTML_LDCOMPLETE:
916 strcpy(subclass, "Load Complete");
918 case AST_HTML_NOSUPPORT:
919 strcpy(subclass, "No Support");
921 case AST_HTML_LINKURL:
922 strcpy(subclass, "Link URL");
923 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
925 case AST_HTML_UNLINK:
926 strcpy(subclass, "Unlink");
928 case AST_HTML_LINKREJECT:
929 strcpy(subclass, "Link Reject");
932 snprintf(subclass, sizeof(subclass), "Unknown HTML frame '%d'\n", f->subclass.integer);
936 case AST_FRAME_MODEM:
937 strcpy(ftype, "Modem");
938 switch (f->subclass.integer) {
940 strcpy(subclass, "T.38");
943 strcpy(subclass, "V.150");
946 snprintf(subclass, sizeof(subclass), "Unknown MODEM frame '%d'\n", f->subclass.integer);
951 snprintf(ftype, sizeof(ftype), "Unknown Frametype '%d'", f->frametype);
953 if (!ast_strlen_zero(moreinfo))
954 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) '%s' ] [%s]\n",
955 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
956 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
958 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
960 term_color(cmn, moreinfo, COLOR_BRGREEN, COLOR_BLACK, sizeof(cmn)),
961 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
963 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) ] [%s]\n",
964 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
965 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
967 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
969 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
973 /* Builtin Asterisk CLI-commands for debugging */
974 static struct ast_cli_entry my_clis[] = {
975 AST_CLI_DEFINE(show_codecs, "Displays a list of codecs"),
976 AST_CLI_DEFINE(show_codec_n, "Shows a specific codec"),
979 int init_framer(void)
981 ast_cli_register_multiple(my_clis, ARRAY_LEN(my_clis));
985 void ast_codec_pref_convert(struct ast_codec_pref *pref, char *buf, size_t size, int right)
987 int x, differential = (int) 'A', mem;
997 mem = sizeof(format_t) * 8;
1001 for (x = 0; x < sizeof(format_t) * 8; x++) {
1004 to[x] = right ? (from[x] + differential) : (from[x] - differential);
1008 int ast_codec_pref_string(struct ast_codec_pref *pref, char *buf, size_t size)
1012 size_t total_len, slen;
1015 memset(buf, 0, size);
1019 for (x = 0; x < sizeof(format_t) * 8; x++) {
1022 if (!(codec = ast_codec_pref_index(pref,x)))
1024 if ((formatname = ast_getformatname(codec))) {
1025 slen = strlen(formatname);
1026 if (slen > total_len)
1028 strncat(buf, formatname, total_len - 1); /* safe */
1031 if (total_len && x < sizeof(format_t) * 8 - 1 && ast_codec_pref_index(pref, x + 1)) {
1032 strncat(buf, "|", total_len - 1); /* safe */
1037 strncat(buf, ")", total_len - 1); /* safe */
1041 return size - total_len;
1044 format_t ast_codec_pref_index(struct ast_codec_pref *pref, int idx)
1048 if ((idx >= 0) && (idx < sizeof(pref->order))) {
1049 slot = pref->order[idx];
1052 return slot ? AST_FORMAT_LIST[slot - 1].bits : 0;
1055 /*! \brief Remove codec from pref list */
1056 void ast_codec_pref_remove(struct ast_codec_pref *pref, format_t format)
1058 struct ast_codec_pref oldorder;
1063 if (!pref->order[0])
1066 memcpy(&oldorder, pref, sizeof(oldorder));
1067 memset(pref, 0, sizeof(*pref));
1069 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1070 slot = oldorder.order[x];
1071 size = oldorder.framing[x];
1074 if (AST_FORMAT_LIST[slot-1].bits != format) {
1075 pref->order[y] = slot;
1076 pref->framing[y++] = size;
1081 /*! \brief Append codec to list */
1082 int ast_codec_pref_append(struct ast_codec_pref *pref, format_t format)
1084 int x, newindex = 0;
1086 ast_codec_pref_remove(pref, format);
1088 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1089 if (AST_FORMAT_LIST[x].bits == format) {
1096 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1097 if (!pref->order[x]) {
1098 pref->order[x] = newindex;
1107 /*! \brief Prepend codec to list */
1108 void ast_codec_pref_prepend(struct ast_codec_pref *pref, format_t format, int only_if_existing)
1110 int x, newindex = 0;
1112 /* First step is to get the codecs "index number" */
1113 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1114 if (AST_FORMAT_LIST[x].bits == format) {
1119 /* Done if its unknown */
1123 /* Now find any existing occurrence, or the end */
1124 for (x = 0; x < sizeof(format_t) * 8; x++) {
1125 if (!pref->order[x] || pref->order[x] == newindex)
1129 if (only_if_existing && !pref->order[x])
1132 /* Move down to make space to insert - either all the way to the end,
1133 or as far as the existing location (which will be overwritten) */
1134 for (; x > 0; x--) {
1135 pref->order[x] = pref->order[x - 1];
1136 pref->framing[x] = pref->framing[x - 1];
1139 /* And insert the new entry */
1140 pref->order[0] = newindex;
1141 pref->framing[0] = 0; /* ? */
1144 /*! \brief Set packet size for codec */
1145 int ast_codec_pref_setsize(struct ast_codec_pref *pref, format_t format, int framems)
1149 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1150 if (AST_FORMAT_LIST[x].bits == format) {
1159 /* size validation */
1161 framems = AST_FORMAT_LIST[idx].def_ms;
1163 if (AST_FORMAT_LIST[idx].inc_ms && framems % AST_FORMAT_LIST[idx].inc_ms) /* avoid division by zero */
1164 framems -= framems % AST_FORMAT_LIST[idx].inc_ms;
1166 if (framems < AST_FORMAT_LIST[idx].min_ms)
1167 framems = AST_FORMAT_LIST[idx].min_ms;
1169 if (framems > AST_FORMAT_LIST[idx].max_ms)
1170 framems = AST_FORMAT_LIST[idx].max_ms;
1172 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1173 if (pref->order[x] == (idx + 1)) {
1174 pref->framing[x] = framems;
1182 /*! \brief Get packet size for codec */
1183 struct ast_format_list ast_codec_pref_getsize(struct ast_codec_pref *pref, format_t format)
1185 int x, idx = -1, framems = 0;
1186 struct ast_format_list fmt = { 0, };
1188 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1189 if (AST_FORMAT_LIST[x].bits == format) {
1190 fmt = AST_FORMAT_LIST[x];
1196 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1197 if (pref->order[x] == (idx + 1)) {
1198 framems = pref->framing[x];
1203 /* size validation */
1205 framems = AST_FORMAT_LIST[idx].def_ms;
1207 if (AST_FORMAT_LIST[idx].inc_ms && framems % AST_FORMAT_LIST[idx].inc_ms) /* avoid division by zero */
1208 framems -= framems % AST_FORMAT_LIST[idx].inc_ms;
1210 if (framems < AST_FORMAT_LIST[idx].min_ms)
1211 framems = AST_FORMAT_LIST[idx].min_ms;
1213 if (framems > AST_FORMAT_LIST[idx].max_ms)
1214 framems = AST_FORMAT_LIST[idx].max_ms;
1216 fmt.cur_ms = framems;
1221 /*! \brief Pick a codec */
1222 format_t ast_codec_choose(struct ast_codec_pref *pref, format_t formats, int find_best)
1227 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1228 slot = pref->order[x];
1232 if (formats & AST_FORMAT_LIST[slot-1].bits) {
1233 ret = AST_FORMAT_LIST[slot-1].bits;
1237 if (ret & AST_FORMAT_AUDIO_MASK)
1240 ast_debug(4, "Could not find preferred codec - %s\n", find_best ? "Going for the best codec" : "Returning zero codec");
1242 return find_best ? ast_best_codec(formats) : 0;
1245 int ast_parse_allow_disallow(struct ast_codec_pref *pref, format_t *mask, const char *list, int allowing)
1247 int errors = 0, framems = 0;
1248 char *parse = NULL, *this = NULL, *psize = NULL;
1249 format_t format = 0;
1251 parse = ast_strdupa(list);
1252 while ((this = strsep(&parse, ","))) {
1254 if ((psize = strrchr(this, ':'))) {
1256 ast_debug(1, "Packetization for codec: %s is %s\n", this, psize);
1257 framems = atoi(psize);
1261 ast_log(LOG_WARNING, "Bad packetization value for codec %s\n", this);
1264 if (!(format = ast_getformatbyname(this))) {
1265 ast_log(LOG_WARNING, "Cannot %s unknown format '%s'\n", allowing ? "allow" : "disallow", this);
1277 /* Set up a preference list for audio. Do not include video in preferences
1278 since we can not transcode video and have to use whatever is offered
1280 if (pref && (format & AST_FORMAT_AUDIO_MASK)) {
1281 if (strcasecmp(this, "all")) {
1283 ast_codec_pref_append(pref, format);
1284 ast_codec_pref_setsize(pref, format, framems);
1287 ast_codec_pref_remove(pref, format);
1288 } else if (!allowing) {
1289 memset(pref, 0, sizeof(*pref));
1296 static int g723_len(unsigned char buf)
1298 enum frame_type type = buf & TYPE_MASK;
1314 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", type);
1319 static int g723_samples(unsigned char *buf, int maxlen)
1324 while(pos < maxlen) {
1325 res = g723_len(buf[pos]);
1334 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
1336 int byte = bit / 8; /* byte containing first bit */
1337 int rem = 8 - (bit % 8); /* remaining bits in first byte */
1338 unsigned char ret = 0;
1340 if (n <= 0 || n > 8)
1344 ret = (data[byte] << (n - rem));
1345 ret |= (data[byte + 1] >> (8 - n + rem));
1347 ret = (data[byte] >> (rem - n));
1350 return (ret & (0xff >> (8 - n)));
1353 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
1355 static const int SpeexWBSubModeSz[] = {
1361 /* skip up to two wideband frames */
1362 if (((len * 8 - off) >= 5) &&
1363 get_n_bits_at(data, 1, off)) {
1364 c = get_n_bits_at(data, 3, off + 1);
1365 off += SpeexWBSubModeSz[c];
1367 if (((len * 8 - off) >= 5) &&
1368 get_n_bits_at(data, 1, off)) {
1369 c = get_n_bits_at(data, 3, off + 1);
1370 off += SpeexWBSubModeSz[c];
1372 if (((len * 8 - off) >= 5) &&
1373 get_n_bits_at(data, 1, off)) {
1374 ast_log(LOG_WARNING, "Encountered corrupt speex frame; too many wideband frames in a row.\n");
1383 static int speex_samples(unsigned char *data, int len)
1385 static const int SpeexSubModeSz[] = {
1390 static const int SpeexInBandSz[] = {
1400 while ((len * 8 - bit) >= 5) {
1401 /* skip wideband frames */
1402 off = speex_get_wb_sz_at(data, len, bit);
1404 ast_log(LOG_WARNING, "Had error while reading wideband frames for speex samples\n");
1409 if ((len * 8 - bit) < 5) {
1410 ast_log(LOG_WARNING, "Not enough bits remaining after wide band for speex samples.\n");
1414 /* get control bits */
1415 c = get_n_bits_at(data, 5, bit);
1421 } else if (c == 14) {
1422 /* in-band signal; next 4 bits contain signal id */
1423 c = get_n_bits_at(data, 4, bit);
1425 bit += SpeexInBandSz[c];
1426 } else if (c == 13) {
1427 /* user in-band; next 5 bits contain msg len */
1428 c = get_n_bits_at(data, 5, bit);
1435 /* skip number bits for submode (less the 5 control bits) */
1436 bit += SpeexSubModeSz[c] - 5;
1437 cnt += 160; /* new frame */
1443 int ast_codec_get_samples(struct ast_frame *f)
1448 switch (f->subclass.codec) {
1449 case AST_FORMAT_SPEEX:
1450 samples = speex_samples(f->data.ptr, f->datalen);
1452 case AST_FORMAT_G723_1:
1453 samples = g723_samples(f->data.ptr, f->datalen);
1455 case AST_FORMAT_ILBC:
1456 samples = 240 * (f->datalen / 50);
1458 case AST_FORMAT_GSM:
1459 samples = 160 * (f->datalen / 33);
1461 case AST_FORMAT_G729A:
1462 samples = f->datalen * 8;
1464 case AST_FORMAT_SLINEAR:
1465 case AST_FORMAT_SLINEAR16:
1466 samples = f->datalen / 2;
1468 case AST_FORMAT_LPC10:
1469 /* assumes that the RTP packet contains one LPC10 frame */
1471 samples += (((char *)(f->data.ptr))[7] & 0x1) * 8;
1473 case AST_FORMAT_ULAW:
1474 case AST_FORMAT_ALAW:
1475 case AST_FORMAT_TESTLAW:
1476 samples = f->datalen;
1478 case AST_FORMAT_G722:
1479 case AST_FORMAT_ADPCM:
1480 case AST_FORMAT_G726:
1481 case AST_FORMAT_G726_AAL2:
1482 samples = f->datalen * 2;
1484 case AST_FORMAT_SIREN7:
1485 /* 16,000 samples per second at 32kbps is 4,000 bytes per second */
1486 samples = f->datalen * (16000 / 4000);
1488 case AST_FORMAT_SIREN14:
1489 /* 32,000 samples per second at 48kbps is 6,000 bytes per second */
1490 samples = (int) f->datalen * ((float) 32000 / 6000);
1493 ast_log(LOG_WARNING, "Unable to calculate samples for format %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), f->subclass.codec));
1498 int ast_codec_get_len(format_t format, int samples)
1502 /* XXX Still need speex, and lpc10 XXX */
1504 case AST_FORMAT_G723_1:
1505 len = (samples / 240) * 20;
1507 case AST_FORMAT_ILBC:
1508 len = (samples / 240) * 50;
1510 case AST_FORMAT_GSM:
1511 len = (samples / 160) * 33;
1513 case AST_FORMAT_G729A:
1516 case AST_FORMAT_SLINEAR:
1517 case AST_FORMAT_SLINEAR16:
1520 case AST_FORMAT_ULAW:
1521 case AST_FORMAT_ALAW:
1522 case AST_FORMAT_TESTLAW:
1525 case AST_FORMAT_G722:
1526 case AST_FORMAT_ADPCM:
1527 case AST_FORMAT_G726:
1528 case AST_FORMAT_G726_AAL2:
1531 case AST_FORMAT_SIREN7:
1532 /* 16,000 samples per second at 32kbps is 4,000 bytes per second */
1533 len = samples / (16000 / 4000);
1535 case AST_FORMAT_SIREN14:
1536 /* 32,000 samples per second at 48kbps is 6,000 bytes per second */
1537 len = (int) samples / ((float) 32000 / 6000);
1540 ast_log(LOG_WARNING, "Unable to calculate sample length for format %s\n", ast_getformatname(format));
1546 int ast_frame_adjust_volume(struct ast_frame *f, int adjustment)
1549 short *fdata = f->data.ptr;
1550 short adjust_value = abs(adjustment);
1552 if ((f->frametype != AST_FRAME_VOICE) || (f->subclass.codec != AST_FORMAT_SLINEAR))
1558 for (count = 0; count < f->samples; count++) {
1559 if (adjustment > 0) {
1560 ast_slinear_saturated_multiply(&fdata[count], &adjust_value);
1561 } else if (adjustment < 0) {
1562 ast_slinear_saturated_divide(&fdata[count], &adjust_value);
1569 int ast_frame_slinear_sum(struct ast_frame *f1, struct ast_frame *f2)
1572 short *data1, *data2;
1574 if ((f1->frametype != AST_FRAME_VOICE) || (f1->subclass.codec != AST_FORMAT_SLINEAR))
1577 if ((f2->frametype != AST_FRAME_VOICE) || (f2->subclass.codec != AST_FORMAT_SLINEAR))
1580 if (f1->samples != f2->samples)
1583 for (count = 0, data1 = f1->data.ptr, data2 = f2->data.ptr;
1584 count < f1->samples;
1585 count++, data1++, data2++)
1586 ast_slinear_saturated_add(data1, data2);