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"
44 static AST_LIST_HEAD_STATIC(headerlist, ast_frame);
47 #if !defined(LOW_MEMORY)
48 static void frame_cache_cleanup(void *data);
50 /*! \brief A per-thread cache of frame headers */
51 AST_THREADSTORAGE_CUSTOM(frame_cache, NULL, frame_cache_cleanup);
54 * \brief Maximum ast_frame cache size
56 * In most cases where the frame header cache will be useful, the size
57 * of the cache will stay very small. However, it is not always the case that
58 * the same thread that allocates the frame will be the one freeing them, so
59 * sometimes a thread will never have any frames in its cache, or the cache
60 * will never be pulled from. For the latter case, we limit the maximum size.
62 #define FRAME_CACHE_MAX_SIZE 10
64 /*! \brief This is just so ast_frames, a list head struct for holding a list of
65 * ast_frame structures, is defined. */
66 AST_LIST_HEAD_NOLOCK(ast_frames, ast_frame);
68 struct ast_frame_cache {
69 struct ast_frames list;
74 #define SMOOTHER_SIZE 8000
79 TYPE_SILENCE, /* 0x2 */
80 TYPE_DONTSEND /* 0x3 */
92 struct timeval delivery;
93 char data[SMOOTHER_SIZE];
94 char framedata[SMOOTHER_SIZE + AST_FRIENDLY_OFFSET];
95 struct ast_frame *opt;
99 /*! \brief Definition of supported media formats (codecs) */
100 static struct ast_format_list AST_FORMAT_LIST[] = {
101 { AST_FORMAT_G723_1 , "g723", 8000, "G.723.1", 20, 30, 300, 30, 30 }, /*!< G723.1 */
102 { AST_FORMAT_GSM, "gsm", 8000, "GSM", 33, 20, 300, 20, 20 }, /*!< codec_gsm.c */
103 { AST_FORMAT_ULAW, "ulaw", 8000, "G.711 u-law", 80, 10, 150, 10, 20 }, /*!< codec_ulaw.c */
104 { AST_FORMAT_ALAW, "alaw", 8000, "G.711 A-law", 80, 10, 150, 10, 20 }, /*!< codec_alaw.c */
105 { AST_FORMAT_G726, "g726", 8000, "G.726 RFC3551", 40, 10, 300, 10, 20 }, /*!< codec_g726.c */
106 { AST_FORMAT_ADPCM, "adpcm" , 8000, "ADPCM", 40, 10, 300, 10, 20 }, /*!< codec_adpcm.c */
107 { AST_FORMAT_SLINEAR, "slin", 8000, "16 bit Signed Linear PCM", 160, 10, 70, 10, 20, AST_SMOOTHER_FLAG_BE }, /*!< Signed linear */
108 { AST_FORMAT_LPC10, "lpc10", 8000, "LPC10", 7, 20, 20, 20, 20 }, /*!< codec_lpc10.c */
109 { AST_FORMAT_G729A, "g729", 8000, "G.729A", 10, 10, 230, 10, 20, AST_SMOOTHER_FLAG_G729 }, /*!< Binary commercial distribution */
110 { AST_FORMAT_SPEEX, "speex", 8000, "SpeeX", 10, 10, 60, 10, 20 }, /*!< codec_speex.c */
111 { AST_FORMAT_ILBC, "ilbc", 8000, "iLBC", 50, 30, 30, 30, 30 }, /*!< codec_ilbc.c */ /* inc=30ms - workaround */
112 { AST_FORMAT_G726_AAL2, "g726aal2", 8000, "G.726 AAL2", 40, 10, 300, 10, 20 }, /*!< codec_g726.c */
113 { AST_FORMAT_G722, "g722", 16000, "G722", 80, 10, 150, 10, 20 }, /*!< codec_g722.c */
114 { AST_FORMAT_SLINEAR16, "slin16", 16000, "16 bit Signed Linear PCM (16kHz)", 320, 10, 70, 10, 20 }, /*!< Signed linear (16kHz) */
115 { AST_FORMAT_JPEG, "jpeg", 0, "JPEG image"}, /*!< See format_jpeg.c */
116 { AST_FORMAT_PNG, "png", 0, "PNG image"}, /*!< PNG Image format */
117 { AST_FORMAT_H261, "h261", 0, "H.261 Video" }, /*!< H.261 Video Passthrough */
118 { AST_FORMAT_H263, "h263", 0, "H.263 Video" }, /*!< H.263 Passthrough support, see format_h263.c */
119 { AST_FORMAT_H263_PLUS, "h263p", 0, "H.263+ Video" }, /*!< H.263plus passthrough support See format_h263.c */
120 { AST_FORMAT_H264, "h264", 0, "H.264 Video" }, /*!< Passthrough support, see format_h263.c */
121 { AST_FORMAT_MP4_VIDEO, "mpeg4", 0, "MPEG4 Video" }, /*!< Passthrough support for MPEG4 */
122 { AST_FORMAT_T140RED, "red", 1, "T.140 Realtime Text with redundancy"}, /*!< Redundant T.140 Realtime Text */
123 { AST_FORMAT_T140, "t140", 0, "Passthrough T.140 Realtime Text" }, /*!< Passthrough support for T.140 Realtime Text */
126 struct ast_frame ast_null_frame = { AST_FRAME_NULL, };
128 void ast_smoother_reset(struct ast_smoother *s, int size)
130 memset(s, 0, sizeof(*s));
134 struct ast_smoother *ast_smoother_new(int size)
136 struct ast_smoother *s;
139 if ((s = ast_malloc(sizeof(*s))))
140 ast_smoother_reset(s, size);
144 int ast_smoother_get_flags(struct ast_smoother *s)
149 void ast_smoother_set_flags(struct ast_smoother *s, int flags)
154 int ast_smoother_test_flag(struct ast_smoother *s, int flag)
156 return (s->flags & flag);
159 int __ast_smoother_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
161 if (f->frametype != AST_FRAME_VOICE) {
162 ast_log(LOG_WARNING, "Huh? Can't smooth a non-voice frame!\n");
166 s->format = f->subclass;
167 s->samplesperbyte = (float)f->samples / (float)f->datalen;
168 } else if (s->format != f->subclass) {
169 ast_log(LOG_WARNING, "Smoother was working on %d format frames, now trying to feed %d?\n", s->format, f->subclass);
172 if (s->len + f->datalen > SMOOTHER_SIZE) {
173 ast_log(LOG_WARNING, "Out of smoother space\n");
176 if (((f->datalen == s->size) || ((f->datalen < 10) && (s->flags & AST_SMOOTHER_FLAG_G729)))
177 && !s->opt && (f->offset >= AST_MIN_OFFSET)) {
179 /* Optimize by sending the frame we just got
180 on the next read, thus eliminating the douple
183 ast_swapcopy_samples(f->data.ptr, f->data.ptr, f->samples);
188 if (s->flags & AST_SMOOTHER_FLAG_G729) {
190 ast_log(LOG_NOTICE, "Dropping extra frame of G.729 since we already have a VAD frame at the end\n");
195 ast_swapcopy_samples(s->data+s->len, f->data.ptr, f->samples);
197 memcpy(s->data + s->len, f->data.ptr, f->datalen);
198 /* If either side is empty, reset the delivery time */
199 if (!s->len || ast_tvzero(f->delivery) || ast_tvzero(s->delivery)) /* XXX really ? */
200 s->delivery = f->delivery;
201 s->len += f->datalen;
205 struct ast_frame *ast_smoother_read(struct ast_smoother *s)
207 struct ast_frame *opt;
210 /* IF we have an optimization frame, send it */
212 if (s->opt->offset < AST_FRIENDLY_OFFSET)
213 ast_log(LOG_WARNING, "Returning a frame of inappropriate offset (%d).\n",
220 /* Make sure we have enough data */
221 if (s->len < s->size) {
222 /* Or, if this is a G.729 frame with VAD on it, send it immediately anyway */
223 if (!((s->flags & AST_SMOOTHER_FLAG_G729) && (s->size % 10)))
230 s->f.frametype = AST_FRAME_VOICE;
231 s->f.subclass = s->format;
232 s->f.data.ptr = s->framedata + AST_FRIENDLY_OFFSET;
233 s->f.offset = AST_FRIENDLY_OFFSET;
235 /* Samples will be improper given VAD, but with VAD the concept really doesn't even exist */
236 s->f.samples = len * s->samplesperbyte; /* XXX rounding */
237 s->f.delivery = s->delivery;
239 memcpy(s->f.data.ptr, s->data, len);
241 /* Move remaining data to the front if applicable */
243 /* In principle this should all be fine because if we are sending
244 G.729 VAD, the next timestamp will take over anyawy */
245 memmove(s->data, s->data + len, s->len);
246 if (!ast_tvzero(s->delivery)) {
247 /* If we have delivery time, increment it, otherwise, leave it at 0 */
248 s->delivery = ast_tvadd(s->delivery, ast_samp2tv(s->f.samples, 8000));
255 void ast_smoother_free(struct ast_smoother *s)
260 static struct ast_frame *ast_frame_header_new(void)
264 #if !defined(LOW_MEMORY)
265 struct ast_frame_cache *frames;
267 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
268 if ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list))) {
269 size_t mallocd_len = f->mallocd_hdr_len;
270 memset(f, 0, sizeof(*f));
271 f->mallocd_hdr_len = mallocd_len;
272 f->mallocd = AST_MALLOCD_HDR;
277 if (!(f = ast_calloc_cache(1, sizeof(*f))))
280 if (!(f = ast_calloc(1, sizeof(*f))))
284 f->mallocd_hdr_len = sizeof(*f);
286 AST_LIST_LOCK(&headerlist);
288 AST_LIST_INSERT_HEAD(&headerlist, f, frame_list);
289 AST_LIST_UNLOCK(&headerlist);
295 #if !defined(LOW_MEMORY)
296 static void frame_cache_cleanup(void *data)
298 struct ast_frame_cache *frames = data;
301 while ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list)))
308 void ast_frame_free(struct ast_frame *fr, int cache)
310 if (ast_test_flag(fr, AST_FRFLAG_FROM_TRANSLATOR))
311 ast_translate_frame_freed(fr);
312 else if (ast_test_flag(fr, AST_FRFLAG_FROM_DSP))
313 ast_dsp_frame_freed(fr);
318 #if !defined(LOW_MEMORY)
319 if (cache && fr->mallocd == AST_MALLOCD_HDR) {
320 /* Cool, only the header is malloc'd, let's just cache those for now
321 * to keep things simple... */
322 struct ast_frame_cache *frames;
324 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))
325 && frames->size < FRAME_CACHE_MAX_SIZE) {
326 AST_LIST_INSERT_HEAD(&frames->list, fr, frame_list);
333 if (fr->mallocd & AST_MALLOCD_DATA) {
335 ast_free(fr->data.ptr - fr->offset);
337 if (fr->mallocd & AST_MALLOCD_SRC) {
339 ast_free((char *)fr->src);
341 if (fr->mallocd & AST_MALLOCD_HDR) {
343 AST_LIST_LOCK(&headerlist);
345 AST_LIST_REMOVE(&headerlist, fr, frame_list);
346 AST_LIST_UNLOCK(&headerlist);
353 * \brief 'isolates' a frame by duplicating non-malloc'ed components
354 * (header, src, data).
355 * On return all components are malloc'ed
357 struct ast_frame *ast_frisolate(struct ast_frame *fr)
359 struct ast_frame *out;
362 ast_clear_flag(fr, AST_FRFLAG_FROM_TRANSLATOR);
363 ast_clear_flag(fr, AST_FRFLAG_FROM_DSP);
365 if (!(fr->mallocd & AST_MALLOCD_HDR)) {
366 /* Allocate a new header if needed */
367 if (!(out = ast_frame_header_new()))
369 out->frametype = fr->frametype;
370 out->subclass = fr->subclass;
371 out->datalen = fr->datalen;
372 out->samples = fr->samples;
373 out->offset = fr->offset;
374 out->data = fr->data;
375 /* Copy the timing data */
376 ast_copy_flags(out, fr, AST_FRFLAG_HAS_TIMING_INFO);
377 if (ast_test_flag(fr, AST_FRFLAG_HAS_TIMING_INFO)) {
380 out->seqno = fr->seqno;
385 if (!(fr->mallocd & AST_MALLOCD_SRC)) {
387 if (!(out->src = ast_strdup(fr->src))) {
396 if (!(fr->mallocd & AST_MALLOCD_DATA)) {
397 if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
398 if (out->src != fr->src)
399 ast_free((void *) out->src);
404 newdata += AST_FRIENDLY_OFFSET;
405 out->offset = AST_FRIENDLY_OFFSET;
406 out->datalen = fr->datalen;
407 memcpy(newdata, fr->data.ptr, fr->datalen);
408 out->data.ptr = newdata;
411 out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA;
416 struct ast_frame *ast_frdup(const struct ast_frame *f)
418 struct ast_frame *out = NULL;
422 #if !defined(LOW_MEMORY)
423 struct ast_frame_cache *frames;
426 /* Start with standard stuff */
427 len = sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
428 /* If we have a source, add space for it */
430 * XXX Watch out here - if we receive a src which is not terminated
431 * properly, we can be easily attacked. Should limit the size we deal with.
434 srclen = strlen(f->src);
438 #if !defined(LOW_MEMORY)
439 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
440 AST_LIST_TRAVERSE_SAFE_BEGIN(&frames->list, out, frame_list) {
441 if (out->mallocd_hdr_len >= len) {
442 size_t mallocd_len = out->mallocd_hdr_len;
444 AST_LIST_REMOVE_CURRENT(frame_list);
445 memset(out, 0, sizeof(*out));
446 out->mallocd_hdr_len = mallocd_len;
452 AST_LIST_TRAVERSE_SAFE_END;
457 if (!(buf = ast_calloc_cache(1, len)))
460 out->mallocd_hdr_len = len;
463 out->frametype = f->frametype;
464 out->subclass = f->subclass;
465 out->datalen = f->datalen;
466 out->samples = f->samples;
467 out->delivery = f->delivery;
468 /* Set us as having malloc'd header only, so it will eventually
470 out->mallocd = AST_MALLOCD_HDR;
471 out->offset = AST_FRIENDLY_OFFSET;
473 out->data.ptr = buf + sizeof(*out) + AST_FRIENDLY_OFFSET;
474 memcpy(out->data.ptr, f->data.ptr, out->datalen);
477 out->src = buf + sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
478 /* Must have space since we allocated for it */
479 strcpy((char *)out->src, f->src);
481 ast_copy_flags(out, f, AST_FRFLAG_HAS_TIMING_INFO);
484 out->seqno = f->seqno;
488 void ast_swapcopy_samples(void *dst, const void *src, int samples)
491 unsigned short *dst_s = dst;
492 const unsigned short *src_s = src;
494 for (i = 0; i < samples; i++)
495 dst_s[i] = (src_s[i]<<8) | (src_s[i]>>8);
499 struct ast_format_list *ast_get_format_list_index(int index)
501 return &AST_FORMAT_LIST[index];
504 struct ast_format_list *ast_get_format_list(size_t *size)
506 *size = (sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]));
507 return AST_FORMAT_LIST;
510 char* ast_getformatname(int format)
513 char *ret = "unknown";
514 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
515 if (AST_FORMAT_LIST[x].bits == format) {
516 ret = AST_FORMAT_LIST[x].name;
523 char *ast_getformatname_multiple(char *buf, size_t size, int format)
527 char *start, *end = buf;
531 snprintf(end, size, "0x%x (", format);
536 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
537 if (AST_FORMAT_LIST[x].bits & format) {
538 snprintf(end, size,"%s|",AST_FORMAT_LIST[x].name);
545 ast_copy_string(start, "nothing)", size);
551 static struct ast_codec_alias_table {
554 } ast_codec_alias_table[] = {
555 { "slinear", "slin"},
556 { "slinear16", "slin16"},
560 static const char *ast_expand_codec_alias(const char *in)
564 for (x = 0; x < sizeof(ast_codec_alias_table) / sizeof(ast_codec_alias_table[0]); x++) {
565 if (!strcmp(in,ast_codec_alias_table[x].alias))
566 return ast_codec_alias_table[x].realname;
571 int ast_getformatbyname(const char *name)
573 int x, all, format = 0;
575 all = strcasecmp(name, "all") ? 0 : 1;
576 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
578 !strcasecmp(AST_FORMAT_LIST[x].name,name) ||
579 !strcasecmp(AST_FORMAT_LIST[x].name, ast_expand_codec_alias(name))) {
580 format |= AST_FORMAT_LIST[x].bits;
589 char *ast_codec2str(int codec)
592 char *ret = "unknown";
593 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
594 if (AST_FORMAT_LIST[x].bits == codec) {
595 ret = AST_FORMAT_LIST[x].desc;
602 static char *show_codecs(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
609 e->command = "core show codecs [audio|video|image]";
611 "Usage: core show codecs [audio|video|image]\n"
612 " Displays codec mapping\n";
618 if ((a->argc < 3) || (a->argc > 4))
619 return CLI_SHOWUSAGE;
621 if (!ast_opt_dont_warn)
622 ast_cli(a->fd, "Disclaimer: this command is for informational purposes only.\n"
623 "\tIt does not indicate anything about your configuration.\n");
625 ast_cli(a->fd, "%11s %9s %10s TYPE %8s %s\n","INT","BINARY","HEX","NAME","DESC");
626 ast_cli(a->fd, "--------------------------------------------------------------------------------\n");
627 if ((a->argc == 3) || (!strcasecmp(a->argv[3],"audio"))) {
630 snprintf(hex,25,"(0x%x)",1<<i);
631 ast_cli(a->fd, "%11u (1 << %2d) %10s audio %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
635 if ((a->argc == 3) || (!strcasecmp(a->argv[3],"image"))) {
637 for (i=16;i<18;i++) {
638 snprintf(hex,25,"(0x%x)",1<<i);
639 ast_cli(a->fd, "%11u (1 << %2d) %10s image %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
643 if ((a->argc == 3) || (!strcasecmp(a->argv[3],"video"))) {
645 for (i=18;i<22;i++) {
646 snprintf(hex,25,"(0x%x)",1<<i);
647 ast_cli(a->fd, "%11u (1 << %2d) %10s video %8s (%s)\n",1 << i,i,hex,ast_getformatname(1<<i),ast_codec2str(1<<i));
652 return CLI_SHOWUSAGE;
657 static char *show_codec_n(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
659 int codec, i, found=0;
663 e->command = "core show codec";
665 "Usage: core show codec <number>\n"
666 " Displays codec mapping\n";
673 return CLI_SHOWUSAGE;
675 if (sscanf(a->argv[3],"%d",&codec) != 1)
676 return CLI_SHOWUSAGE;
678 for (i = 0; i < 32; i++)
679 if (codec & (1 << i)) {
681 ast_cli(a->fd, "%11u (1 << %2d) %s\n",1 << i,i,ast_codec2str(1<<i));
685 ast_cli(a->fd, "Codec %d not found\n", codec);
690 /*! Dump a frame for debugging purposes */
691 void ast_frame_dump(const char *name, struct ast_frame *f, char *prefix)
693 const char noname[] = "unknown";
694 char ftype[40] = "Unknown Frametype";
696 char subclass[40] = "Unknown Subclass";
698 char moreinfo[40] = "";
702 const char *message = "Unknown";
709 ast_verbose("%s [ %s (NULL) ] [%s]\n",
710 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
711 term_color(cft, "HANGUP", COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
712 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
715 /* XXX We should probably print one each of voice and video when the format changes XXX */
716 if (f->frametype == AST_FRAME_VOICE)
718 if (f->frametype == AST_FRAME_VIDEO)
720 switch(f->frametype) {
721 case AST_FRAME_DTMF_BEGIN:
722 strcpy(ftype, "DTMF Begin");
723 subclass[0] = f->subclass;
726 case AST_FRAME_DTMF_END:
727 strcpy(ftype, "DTMF End");
728 subclass[0] = f->subclass;
731 case AST_FRAME_CONTROL:
732 strcpy(ftype, "Control");
733 switch(f->subclass) {
734 case AST_CONTROL_HANGUP:
735 strcpy(subclass, "Hangup");
737 case AST_CONTROL_RING:
738 strcpy(subclass, "Ring");
740 case AST_CONTROL_RINGING:
741 strcpy(subclass, "Ringing");
743 case AST_CONTROL_ANSWER:
744 strcpy(subclass, "Answer");
746 case AST_CONTROL_BUSY:
747 strcpy(subclass, "Busy");
749 case AST_CONTROL_TAKEOFFHOOK:
750 strcpy(subclass, "Take Off Hook");
752 case AST_CONTROL_OFFHOOK:
753 strcpy(subclass, "Line Off Hook");
755 case AST_CONTROL_CONGESTION:
756 strcpy(subclass, "Congestion");
758 case AST_CONTROL_FLASH:
759 strcpy(subclass, "Flash");
761 case AST_CONTROL_WINK:
762 strcpy(subclass, "Wink");
764 case AST_CONTROL_OPTION:
765 strcpy(subclass, "Option");
767 case AST_CONTROL_RADIO_KEY:
768 strcpy(subclass, "Key Radio");
770 case AST_CONTROL_RADIO_UNKEY:
771 strcpy(subclass, "Unkey Radio");
773 case AST_CONTROL_HOLD:
774 strcpy(subclass, "Hold");
776 case AST_CONTROL_UNHOLD:
777 strcpy(subclass, "Unhold");
779 case AST_CONTROL_T38:
780 if (f->datalen != sizeof(enum ast_control_t38)) {
783 enum ast_control_t38 state = *((enum ast_control_t38 *) f->data.ptr);
784 if (state == AST_T38_REQUEST_NEGOTIATE)
785 message = "Negotiation Requested";
786 else if (state == AST_T38_REQUEST_TERMINATE)
787 message = "Negotiation Request Terminated";
788 else if (state == AST_T38_NEGOTIATED)
789 message = "Negotiated";
790 else if (state == AST_T38_TERMINATED)
791 message = "Terminated";
792 else if (state == AST_T38_REFUSED)
795 snprintf(subclass, sizeof(subclass), "T38/%s", message);
798 strcpy(subclass, "Stop generators");
801 snprintf(subclass, sizeof(subclass), "Unknown control '%d'", f->subclass);
805 strcpy(ftype, "Null Frame");
806 strcpy(subclass, "N/A");
809 /* Should never happen */
810 strcpy(ftype, "IAX Specific");
811 snprintf(subclass, sizeof(subclass), "IAX Frametype %d", f->subclass);
814 strcpy(ftype, "Text");
815 strcpy(subclass, "N/A");
816 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
818 case AST_FRAME_IMAGE:
819 strcpy(ftype, "Image");
820 snprintf(subclass, sizeof(subclass), "Image format %s\n", ast_getformatname(f->subclass));
823 strcpy(ftype, "HTML");
824 switch(f->subclass) {
826 strcpy(subclass, "URL");
827 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
830 strcpy(subclass, "Data");
833 strcpy(subclass, "Begin");
836 strcpy(subclass, "End");
838 case AST_HTML_LDCOMPLETE:
839 strcpy(subclass, "Load Complete");
841 case AST_HTML_NOSUPPORT:
842 strcpy(subclass, "No Support");
844 case AST_HTML_LINKURL:
845 strcpy(subclass, "Link URL");
846 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
848 case AST_HTML_UNLINK:
849 strcpy(subclass, "Unlink");
851 case AST_HTML_LINKREJECT:
852 strcpy(subclass, "Link Reject");
855 snprintf(subclass, sizeof(subclass), "Unknown HTML frame '%d'\n", f->subclass);
859 case AST_FRAME_MODEM:
860 strcpy(ftype, "Modem");
861 switch (f->subclass) {
863 strcpy(subclass, "T.38");
866 strcpy(subclass, "V.150");
869 snprintf(subclass, sizeof(subclass), "Unknown MODEM frame '%d'\n", f->subclass);
874 snprintf(ftype, sizeof(ftype), "Unknown Frametype '%d'", f->frametype);
876 if (!ast_strlen_zero(moreinfo))
877 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) '%s' ] [%s]\n",
878 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
879 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
881 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
883 term_color(cmn, moreinfo, COLOR_BRGREEN, COLOR_BLACK, sizeof(cmn)),
884 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
886 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) ] [%s]\n",
887 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
888 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
890 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
892 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
897 static char *show_frame_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
904 e->command = "core show frame stats";
906 "Usage: core show frame stats\n"
907 " Displays debugging statistics from framer\n";
914 return CLI_SHOWUSAGE;
915 AST_LIST_LOCK(&headerlist);
916 ast_cli(a->fd, " Framer Statistics \n");
917 ast_cli(a->fd, "---------------------------\n");
918 ast_cli(a->fd, "Total allocated headers: %d\n", headers);
919 ast_cli(a->fd, "Queue Dump:\n");
920 AST_LIST_TRAVERSE(&headerlist, f, frame_list)
921 ast_cli(a->fd, "%d. Type %d, subclass %d from %s\n", x++, f->frametype, f->subclass, f->src ? f->src : "<Unknown>");
922 AST_LIST_UNLOCK(&headerlist);
927 /* Builtin Asterisk CLI-commands for debugging */
928 static struct ast_cli_entry my_clis[] = {
929 AST_CLI_DEFINE(show_codecs, "Displays a list of codecs"),
930 AST_CLI_DEFINE(show_codec_n, "Shows a specific codec"),
932 AST_CLI_DEFINE(show_frame_stats, "Shows frame statistics"),
936 int init_framer(void)
938 ast_cli_register_multiple(my_clis, sizeof(my_clis) / sizeof(struct ast_cli_entry));
942 void ast_codec_pref_convert(struct ast_codec_pref *pref, char *buf, size_t size, int right)
944 int x, differential = (int) 'A', mem;
958 for (x = 0; x < 32 ; x++) {
961 to[x] = right ? (from[x] + differential) : (from[x] - differential);
965 int ast_codec_pref_string(struct ast_codec_pref *pref, char *buf, size_t size)
968 size_t total_len, slen;
975 for(x = 0; x < 32 ; x++) {
978 if (!(codec = ast_codec_pref_index(pref,x)))
980 if ((formatname = ast_getformatname(codec))) {
981 slen = strlen(formatname);
982 if (slen > total_len)
984 strncat(buf, formatname, total_len - 1); /* safe */
987 if (total_len && x < 31 && ast_codec_pref_index(pref , x + 1)) {
988 strncat(buf, "|", total_len - 1); /* safe */
993 strncat(buf, ")", total_len - 1); /* safe */
997 return size - total_len;
1000 int ast_codec_pref_index(struct ast_codec_pref *pref, int index)
1005 if ((index >= 0) && (index < sizeof(pref->order))) {
1006 slot = pref->order[index];
1009 return slot ? AST_FORMAT_LIST[slot-1].bits : 0;
1012 /*! \brief Remove codec from pref list */
1013 void ast_codec_pref_remove(struct ast_codec_pref *pref, int format)
1015 struct ast_codec_pref oldorder;
1020 if (!pref->order[0])
1023 memcpy(&oldorder, pref, sizeof(oldorder));
1024 memset(pref, 0, sizeof(*pref));
1026 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1027 slot = oldorder.order[x];
1028 size = oldorder.framing[x];
1031 if (AST_FORMAT_LIST[slot-1].bits != format) {
1032 pref->order[y] = slot;
1033 pref->framing[y++] = size;
1039 /*! \brief Append codec to list */
1040 int ast_codec_pref_append(struct ast_codec_pref *pref, int format)
1042 int x, newindex = 0;
1044 ast_codec_pref_remove(pref, format);
1046 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1047 if (AST_FORMAT_LIST[x].bits == format) {
1054 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1055 if (!pref->order[x]) {
1056 pref->order[x] = newindex;
1065 /*! \brief Prepend codec to list */
1066 void ast_codec_pref_prepend(struct ast_codec_pref *pref, int format, int only_if_existing)
1068 int x, newindex = 0;
1070 /* First step is to get the codecs "index number" */
1071 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1072 if (AST_FORMAT_LIST[x].bits == format) {
1077 /* Done if its unknown */
1081 /* Now find any existing occurrence, or the end */
1082 for (x = 0; x < 32; x++) {
1083 if (!pref->order[x] || pref->order[x] == newindex)
1087 if (only_if_existing && !pref->order[x])
1090 /* Move down to make space to insert - either all the way to the end,
1091 or as far as the existing location (which will be overwritten) */
1092 for (; x > 0; x--) {
1093 pref->order[x] = pref->order[x - 1];
1094 pref->framing[x] = pref->framing[x - 1];
1097 /* And insert the new entry */
1098 pref->order[0] = newindex;
1099 pref->framing[0] = 0; /* ? */
1102 /*! \brief Set packet size for codec */
1103 int ast_codec_pref_setsize(struct ast_codec_pref *pref, int format, int framems)
1107 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1108 if (AST_FORMAT_LIST[x].bits == format) {
1117 /* size validation */
1119 framems = AST_FORMAT_LIST[index].def_ms;
1121 if (AST_FORMAT_LIST[index].inc_ms && framems % AST_FORMAT_LIST[index].inc_ms) /* avoid division by zero */
1122 framems -= framems % AST_FORMAT_LIST[index].inc_ms;
1124 if (framems < AST_FORMAT_LIST[index].min_ms)
1125 framems = AST_FORMAT_LIST[index].min_ms;
1127 if (framems > AST_FORMAT_LIST[index].max_ms)
1128 framems = AST_FORMAT_LIST[index].max_ms;
1131 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1132 if (pref->order[x] == (index + 1)) {
1133 pref->framing[x] = framems;
1141 /*! \brief Get packet size for codec */
1142 struct ast_format_list ast_codec_pref_getsize(struct ast_codec_pref *pref, int format)
1144 int x, index = -1, framems = 0;
1145 struct ast_format_list fmt = { 0, };
1147 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1148 if (AST_FORMAT_LIST[x].bits == format) {
1149 fmt = AST_FORMAT_LIST[x];
1155 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1156 if (pref->order[x] == (index + 1)) {
1157 framems = pref->framing[x];
1162 /* size validation */
1164 framems = AST_FORMAT_LIST[index].def_ms;
1166 if (AST_FORMAT_LIST[index].inc_ms && framems % AST_FORMAT_LIST[index].inc_ms) /* avoid division by zero */
1167 framems -= framems % AST_FORMAT_LIST[index].inc_ms;
1169 if (framems < AST_FORMAT_LIST[index].min_ms)
1170 framems = AST_FORMAT_LIST[index].min_ms;
1172 if (framems > AST_FORMAT_LIST[index].max_ms)
1173 framems = AST_FORMAT_LIST[index].max_ms;
1175 fmt.cur_ms = framems;
1180 /*! \brief Pick a codec */
1181 int ast_codec_choose(struct ast_codec_pref *pref, int formats, int find_best)
1183 int x, ret = 0, slot;
1185 for (x = 0; x < sizeof(AST_FORMAT_LIST) / sizeof(AST_FORMAT_LIST[0]); x++) {
1186 slot = pref->order[x];
1190 if (formats & AST_FORMAT_LIST[slot-1].bits) {
1191 ret = AST_FORMAT_LIST[slot-1].bits;
1195 if (ret & AST_FORMAT_AUDIO_MASK)
1198 ast_debug(4, "Could not find preferred codec - %s\n", find_best ? "Going for the best codec" : "Returning zero codec");
1200 return find_best ? ast_best_codec(formats) : 0;
1203 int ast_parse_allow_disallow(struct ast_codec_pref *pref, int *mask, const char *list, int allowing)
1206 char *parse = NULL, *this = NULL, *psize = NULL;
1207 int format = 0, framems = 0;
1209 parse = ast_strdupa(list);
1210 while ((this = strsep(&parse, ","))) {
1212 if ((psize = strrchr(this, ':'))) {
1214 ast_debug(1, "Packetization for codec: %s is %s\n", this, psize);
1215 framems = atoi(psize);
1219 ast_log(LOG_WARNING, "Bad packetization value for codec %s\n", this);
1222 if (!(format = ast_getformatbyname(this))) {
1223 ast_log(LOG_WARNING, "Cannot %s unknown format '%s'\n", allowing ? "allow" : "disallow", this);
1235 /* Set up a preference list for audio. Do not include video in preferences
1236 since we can not transcode video and have to use whatever is offered
1238 if (pref && (format & AST_FORMAT_AUDIO_MASK)) {
1239 if (strcasecmp(this, "all")) {
1241 ast_codec_pref_append(pref, format);
1242 ast_codec_pref_setsize(pref, format, framems);
1245 ast_codec_pref_remove(pref, format);
1246 } else if (!allowing) {
1247 memset(pref, 0, sizeof(*pref));
1254 static int g723_len(unsigned char buf)
1256 enum frame_type type = buf & TYPE_MASK;
1272 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", type);
1277 static int g723_samples(unsigned char *buf, int maxlen)
1282 while(pos < maxlen) {
1283 res = g723_len(buf[pos]);
1292 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
1294 int byte = bit / 8; /* byte containing first bit */
1295 int rem = 8 - (bit % 8); /* remaining bits in first byte */
1296 unsigned char ret = 0;
1298 if (n <= 0 || n > 8)
1302 ret = (data[byte] << (n - rem));
1303 ret |= (data[byte + 1] >> (8 - n + rem));
1305 ret = (data[byte] >> (rem - n));
1308 return (ret & (0xff >> (8 - n)));
1311 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
1313 static int SpeexWBSubModeSz[] = {
1319 /* skip up to two wideband frames */
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];
1325 if (((len * 8 - off) >= 5) &&
1326 get_n_bits_at(data, 1, off)) {
1327 c = get_n_bits_at(data, 3, off + 1);
1328 off += SpeexWBSubModeSz[c];
1330 if (((len * 8 - off) >= 5) &&
1331 get_n_bits_at(data, 1, off)) {
1332 ast_log(LOG_WARNING, "Encountered corrupt speex frame; too many wideband frames in a row.\n");
1341 static int speex_samples(unsigned char *data, int len)
1343 static int SpeexSubModeSz[] = {
1348 static int SpeexInBandSz[] = {
1358 while ((len * 8 - bit) >= 5) {
1359 /* skip wideband frames */
1360 off = speex_get_wb_sz_at(data, len, bit);
1362 ast_log(LOG_WARNING, "Had error while reading wideband frames for speex samples\n");
1367 if ((len * 8 - bit) < 5) {
1368 ast_log(LOG_WARNING, "Not enough bits remaining after wide band for speex samples.\n");
1372 /* get control bits */
1373 c = get_n_bits_at(data, 5, bit);
1379 } else if (c == 14) {
1380 /* in-band signal; next 4 bits contain signal id */
1381 c = get_n_bits_at(data, 4, bit);
1383 bit += SpeexInBandSz[c];
1384 } else if (c == 13) {
1385 /* user in-band; next 5 bits contain msg len */
1386 c = get_n_bits_at(data, 5, bit);
1393 /* skip number bits for submode (less the 5 control bits) */
1394 bit += SpeexSubModeSz[c] - 5;
1395 cnt += 160; /* new frame */
1401 int ast_codec_get_samples(struct ast_frame *f)
1404 switch(f->subclass) {
1405 case AST_FORMAT_SPEEX:
1406 samples = speex_samples(f->data.ptr, f->datalen);
1408 case AST_FORMAT_G723_1:
1409 samples = g723_samples(f->data.ptr, f->datalen);
1411 case AST_FORMAT_ILBC:
1412 samples = 240 * (f->datalen / 50);
1414 case AST_FORMAT_GSM:
1415 samples = 160 * (f->datalen / 33);
1417 case AST_FORMAT_G729A:
1418 samples = f->datalen * 8;
1420 case AST_FORMAT_SLINEAR:
1421 case AST_FORMAT_SLINEAR16:
1422 samples = f->datalen / 2;
1424 case AST_FORMAT_LPC10:
1425 /* assumes that the RTP packet contains one LPC10 frame */
1427 samples += (((char *)(f->data.ptr))[7] & 0x1) * 8;
1429 case AST_FORMAT_ULAW:
1430 case AST_FORMAT_ALAW:
1431 samples = f->datalen;
1433 case AST_FORMAT_G722:
1434 case AST_FORMAT_ADPCM:
1435 case AST_FORMAT_G726:
1436 case AST_FORMAT_G726_AAL2:
1437 samples = f->datalen * 2;
1440 ast_log(LOG_WARNING, "Unable to calculate samples for format %s\n", ast_getformatname(f->subclass));
1445 int ast_codec_get_len(int format, int samples)
1449 /* XXX Still need speex, g723, and lpc10 XXX */
1451 case AST_FORMAT_G723_1:
1452 len = (samples / 240) * 20;
1454 case AST_FORMAT_ILBC:
1455 len = (samples / 240) * 50;
1457 case AST_FORMAT_GSM:
1458 len = (samples / 160) * 33;
1460 case AST_FORMAT_G729A:
1463 case AST_FORMAT_SLINEAR:
1464 case AST_FORMAT_SLINEAR16:
1467 case AST_FORMAT_ULAW:
1468 case AST_FORMAT_ALAW:
1471 case AST_FORMAT_G722:
1472 case AST_FORMAT_ADPCM:
1473 case AST_FORMAT_G726:
1474 case AST_FORMAT_G726_AAL2:
1478 ast_log(LOG_WARNING, "Unable to calculate sample length for format %s\n", ast_getformatname(format));
1484 int ast_frame_adjust_volume(struct ast_frame *f, int adjustment)
1487 short *fdata = f->data.ptr;
1488 short adjust_value = abs(adjustment);
1490 if ((f->frametype != AST_FRAME_VOICE) || (f->subclass != AST_FORMAT_SLINEAR))
1496 for (count = 0; count < f->samples; count++) {
1497 if (adjustment > 0) {
1498 ast_slinear_saturated_multiply(&fdata[count], &adjust_value);
1499 } else if (adjustment < 0) {
1500 ast_slinear_saturated_divide(&fdata[count], &adjust_value);
1507 int ast_frame_slinear_sum(struct ast_frame *f1, struct ast_frame *f2)
1510 short *data1, *data2;
1512 if ((f1->frametype != AST_FRAME_VOICE) || (f1->subclass != AST_FORMAT_SLINEAR))
1515 if ((f2->frametype != AST_FRAME_VOICE) || (f2->subclass != AST_FORMAT_SLINEAR))
1518 if (f1->samples != f2->samples)
1521 for (count = 0, data1 = f1->data.ptr, data2 = f2->data.ptr;
1522 count < f1->samples;
1523 count++, data1++, data2++)
1524 ast_slinear_saturated_add(data1, data2);