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)) {
438 if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
439 if (out->src != fr->src) {
440 ast_free((void *) out->src);
447 newdata += AST_FRIENDLY_OFFSET;
448 out->offset = AST_FRIENDLY_OFFSET;
449 out->datalen = fr->datalen;
450 memcpy(newdata, fr->data.ptr, fr->datalen);
451 out->data.ptr = newdata;
453 out->data = fr->data;
454 memset(&fr->data, 0, sizeof(fr->data));
455 fr->mallocd &= ~AST_MALLOCD_DATA;
458 out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA;
463 struct ast_frame *ast_frdup(const struct ast_frame *f)
465 struct ast_frame *out = NULL;
469 #if !defined(LOW_MEMORY)
470 struct ast_frame_cache *frames;
473 /* Start with standard stuff */
474 len = sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
475 /* If we have a source, add space for it */
477 * XXX Watch out here - if we receive a src which is not terminated
478 * properly, we can be easily attacked. Should limit the size we deal with.
481 srclen = strlen(f->src);
485 #if !defined(LOW_MEMORY)
486 if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
487 AST_LIST_TRAVERSE_SAFE_BEGIN(&frames->list, out, frame_list) {
488 if (out->mallocd_hdr_len >= len) {
489 size_t mallocd_len = out->mallocd_hdr_len;
491 AST_LIST_REMOVE_CURRENT(frame_list);
492 memset(out, 0, sizeof(*out));
493 out->mallocd_hdr_len = mallocd_len;
499 AST_LIST_TRAVERSE_SAFE_END;
504 if (!(buf = ast_calloc_cache(1, len)))
507 out->mallocd_hdr_len = len;
510 out->frametype = f->frametype;
511 out->subclass.codec = f->subclass.codec;
512 out->datalen = f->datalen;
513 out->samples = f->samples;
514 out->delivery = f->delivery;
515 /* Set us as having malloc'd header only, so it will eventually
517 out->mallocd = AST_MALLOCD_HDR;
518 out->offset = AST_FRIENDLY_OFFSET;
520 out->data.ptr = buf + sizeof(*out) + AST_FRIENDLY_OFFSET;
521 memcpy(out->data.ptr, f->data.ptr, out->datalen);
523 out->data.uint32 = f->data.uint32;
526 /* This may seem a little strange, but it's to avoid a gcc (4.2.4) compiler warning */
528 out->src = buf + sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
529 src = (char *) out->src;
530 /* Must have space since we allocated for it */
533 ast_copy_flags(out, f, AST_FRFLAG_HAS_TIMING_INFO);
536 out->seqno = f->seqno;
540 void ast_swapcopy_samples(void *dst, const void *src, int samples)
543 unsigned short *dst_s = dst;
544 const unsigned short *src_s = src;
546 for (i = 0; i < samples; i++)
547 dst_s[i] = (src_s[i]<<8) | (src_s[i]>>8);
551 const struct ast_format_list *ast_get_format_list_index(int idx)
553 return &AST_FORMAT_LIST[idx];
556 const struct ast_format_list *ast_get_format_list(size_t *size)
558 *size = ARRAY_LEN(AST_FORMAT_LIST);
559 return AST_FORMAT_LIST;
562 char* ast_getformatname(format_t format)
565 char *ret = "unknown";
566 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
567 if (AST_FORMAT_LIST[x].bits == format) {
568 ret = AST_FORMAT_LIST[x].name;
575 char *ast_getformatname_multiple(char *buf, size_t size, format_t format)
579 char *start, *end = buf;
583 snprintf(end, size, "0x%llx (", (unsigned long long) format);
588 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
589 if (AST_FORMAT_LIST[x].bits & format) {
590 snprintf(end, size, "%s|", AST_FORMAT_LIST[x].name);
597 ast_copy_string(start, "nothing)", size);
603 static struct ast_codec_alias_table {
606 } ast_codec_alias_table[] = {
607 { "slinear", "slin"},
608 { "slinear16", "slin16"},
610 { "g722.1", "siren7"},
611 { "g722.1c", "siren14"},
614 static const char *ast_expand_codec_alias(const char *in)
618 for (x = 0; x < ARRAY_LEN(ast_codec_alias_table); x++) {
619 if (!strcmp(in,ast_codec_alias_table[x].alias))
620 return ast_codec_alias_table[x].realname;
625 format_t ast_getformatbyname(const char *name)
630 all = strcasecmp(name, "all") ? 0 : 1;
631 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
633 !strcasecmp(AST_FORMAT_LIST[x].name,name) ||
634 !strcasecmp(AST_FORMAT_LIST[x].name, ast_expand_codec_alias(name))) {
635 format |= AST_FORMAT_LIST[x].bits;
644 char *ast_codec2str(format_t codec)
647 char *ret = "unknown";
648 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
649 if (AST_FORMAT_LIST[x].bits == codec) {
650 ret = AST_FORMAT_LIST[x].desc;
657 static char *show_codecs(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
664 e->command = "core show codecs [audio|video|image|text]";
666 "Usage: core show codecs [audio|video|image|text]\n"
667 " Displays codec mapping\n";
673 if ((a->argc < 3) || (a->argc > 4))
674 return CLI_SHOWUSAGE;
676 if (!ast_opt_dont_warn)
677 ast_cli(a->fd, "Disclaimer: this command is for informational purposes only.\n"
678 "\tIt does not indicate anything about your configuration.\n");
680 ast_cli(a->fd, "%19s %9s %20s TYPE %8s %s\n","INT","BINARY","HEX","NAME","DESCRIPTION");
681 ast_cli(a->fd, "-----------------------------------------------------------------------------------\n");
682 for (i = 0; i < 63; i++) {
685 if (!strcasecmp(a->argv[3], "audio")) {
686 if (!((1LL << i) & AST_FORMAT_AUDIO_MASK)) {
689 } else if (!strcasecmp(a->argv[3], "video")) {
690 if (!((1LL << i) & AST_FORMAT_VIDEO_MASK)) {
693 } else if (!strcasecmp(a->argv[3], "image")) {
694 if (i != 16 && i != 17) {
697 } else if (!strcasecmp(a->argv[3], "text")) {
698 if (!((1LL << i) & AST_FORMAT_TEXT_MASK)) {
706 snprintf(hex, sizeof(hex), "(0x%Lx)", 1LL << i);
707 ast_cli(a->fd, "%19Lu (1 << %2d) %20s %5s %8s (%s)\n", 1LL << i, i, hex,
708 ((1LL << i) & AST_FORMAT_AUDIO_MASK) ? "audio" :
709 i == 16 || i == 17 ? "image" :
710 ((1LL << i) & AST_FORMAT_VIDEO_MASK) ? "video" :
711 ((1LL << i) & AST_FORMAT_TEXT_MASK) ? "text" :
713 ast_getformatname(1LL << i), ast_codec2str(1LL << i));
718 return CLI_SHOWUSAGE;
724 static char *show_codec_n(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
731 e->command = "core show codec";
733 "Usage: core show codec <number>\n"
734 " Displays codec mapping\n";
741 return CLI_SHOWUSAGE;
743 if (sscanf(a->argv[3], "%30Ld", (long long *) &codec) != 1)
744 return CLI_SHOWUSAGE;
746 for (i = 0; i < 63; i++)
747 if (codec & (1LL << i)) {
749 ast_cli(a->fd, "%11Lu (1 << %2d) %s\n", 1LL << i, i, ast_codec2str(1LL << i));
753 ast_cli(a->fd, "Codec %Ld not found\n", (long long) codec);
758 /*! Dump a frame for debugging purposes */
759 void ast_frame_dump(const char *name, struct ast_frame *f, char *prefix)
761 const char noname[] = "unknown";
762 char ftype[40] = "Unknown Frametype";
764 char subclass[40] = "Unknown Subclass";
766 char moreinfo[40] = "";
770 const char *message = "Unknown";
777 ast_verbose("%s [ %s (NULL) ] [%s]\n",
778 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
779 term_color(cft, "HANGUP", COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
780 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
783 /* XXX We should probably print one each of voice and video when the format changes XXX */
784 if (f->frametype == AST_FRAME_VOICE)
786 if (f->frametype == AST_FRAME_VIDEO)
788 switch(f->frametype) {
789 case AST_FRAME_DTMF_BEGIN:
790 strcpy(ftype, "DTMF Begin");
791 subclass[0] = f->subclass.integer;
794 case AST_FRAME_DTMF_END:
795 strcpy(ftype, "DTMF End");
796 subclass[0] = f->subclass.integer;
799 case AST_FRAME_CONTROL:
800 strcpy(ftype, "Control");
801 switch (f->subclass.integer) {
802 case AST_CONTROL_HANGUP:
803 strcpy(subclass, "Hangup");
805 case AST_CONTROL_RING:
806 strcpy(subclass, "Ring");
808 case AST_CONTROL_RINGING:
809 strcpy(subclass, "Ringing");
811 case AST_CONTROL_ANSWER:
812 strcpy(subclass, "Answer");
814 case AST_CONTROL_BUSY:
815 strcpy(subclass, "Busy");
817 case AST_CONTROL_TAKEOFFHOOK:
818 strcpy(subclass, "Take Off Hook");
820 case AST_CONTROL_OFFHOOK:
821 strcpy(subclass, "Line Off Hook");
823 case AST_CONTROL_CONGESTION:
824 strcpy(subclass, "Congestion");
826 case AST_CONTROL_FLASH:
827 strcpy(subclass, "Flash");
829 case AST_CONTROL_WINK:
830 strcpy(subclass, "Wink");
832 case AST_CONTROL_OPTION:
833 strcpy(subclass, "Option");
835 case AST_CONTROL_RADIO_KEY:
836 strcpy(subclass, "Key Radio");
838 case AST_CONTROL_RADIO_UNKEY:
839 strcpy(subclass, "Unkey Radio");
841 case AST_CONTROL_HOLD:
842 strcpy(subclass, "Hold");
844 case AST_CONTROL_UNHOLD:
845 strcpy(subclass, "Unhold");
847 case AST_CONTROL_T38_PARAMETERS:
848 if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
851 struct ast_control_t38_parameters *parameters = f->data.ptr;
852 enum ast_control_t38 state = parameters->request_response;
853 if (state == AST_T38_REQUEST_NEGOTIATE)
854 message = "Negotiation Requested";
855 else if (state == AST_T38_REQUEST_TERMINATE)
856 message = "Negotiation Request Terminated";
857 else if (state == AST_T38_NEGOTIATED)
858 message = "Negotiated";
859 else if (state == AST_T38_TERMINATED)
860 message = "Terminated";
861 else if (state == AST_T38_REFUSED)
864 snprintf(subclass, sizeof(subclass), "T38_Parameters/%s", message);
867 strcpy(subclass, "Stop generators");
870 snprintf(subclass, sizeof(subclass), "Unknown control '%d'", f->subclass.integer);
874 strcpy(ftype, "Null Frame");
875 strcpy(subclass, "N/A");
878 /* Should never happen */
879 strcpy(ftype, "IAX Specific");
880 snprintf(subclass, sizeof(subclass), "IAX Frametype %d", f->subclass.integer);
883 strcpy(ftype, "Text");
884 strcpy(subclass, "N/A");
885 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
887 case AST_FRAME_IMAGE:
888 strcpy(ftype, "Image");
889 snprintf(subclass, sizeof(subclass), "Image format %s\n", ast_getformatname(f->subclass.codec));
892 strcpy(ftype, "HTML");
893 switch (f->subclass.integer) {
895 strcpy(subclass, "URL");
896 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
899 strcpy(subclass, "Data");
902 strcpy(subclass, "Begin");
905 strcpy(subclass, "End");
907 case AST_HTML_LDCOMPLETE:
908 strcpy(subclass, "Load Complete");
910 case AST_HTML_NOSUPPORT:
911 strcpy(subclass, "No Support");
913 case AST_HTML_LINKURL:
914 strcpy(subclass, "Link URL");
915 ast_copy_string(moreinfo, f->data.ptr, sizeof(moreinfo));
917 case AST_HTML_UNLINK:
918 strcpy(subclass, "Unlink");
920 case AST_HTML_LINKREJECT:
921 strcpy(subclass, "Link Reject");
924 snprintf(subclass, sizeof(subclass), "Unknown HTML frame '%d'\n", f->subclass.integer);
928 case AST_FRAME_MODEM:
929 strcpy(ftype, "Modem");
930 switch (f->subclass.integer) {
932 strcpy(subclass, "T.38");
935 strcpy(subclass, "V.150");
938 snprintf(subclass, sizeof(subclass), "Unknown MODEM frame '%d'\n", f->subclass.integer);
943 snprintf(ftype, sizeof(ftype), "Unknown Frametype '%d'", f->frametype);
945 if (!ast_strlen_zero(moreinfo))
946 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) '%s' ] [%s]\n",
947 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
948 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
950 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
952 term_color(cmn, moreinfo, COLOR_BRGREEN, COLOR_BLACK, sizeof(cmn)),
953 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
955 ast_verbose("%s [ TYPE: %s (%d) SUBCLASS: %s (%d) ] [%s]\n",
956 term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
957 term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
959 term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
961 term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
965 /* Builtin Asterisk CLI-commands for debugging */
966 static struct ast_cli_entry my_clis[] = {
967 AST_CLI_DEFINE(show_codecs, "Displays a list of codecs"),
968 AST_CLI_DEFINE(show_codec_n, "Shows a specific codec"),
971 int init_framer(void)
973 ast_cli_register_multiple(my_clis, ARRAY_LEN(my_clis));
977 void ast_codec_pref_convert(struct ast_codec_pref *pref, char *buf, size_t size, int right)
979 int x, differential = (int) 'A', mem;
989 mem = sizeof(format_t) * 8;
993 for (x = 0; x < sizeof(format_t) * 8; x++) {
996 to[x] = right ? (from[x] + differential) : (from[x] - differential);
1000 int ast_codec_pref_string(struct ast_codec_pref *pref, char *buf, size_t size)
1004 size_t total_len, slen;
1007 memset(buf, 0, size);
1011 for (x = 0; x < sizeof(format_t) * 8; x++) {
1014 if (!(codec = ast_codec_pref_index(pref,x)))
1016 if ((formatname = ast_getformatname(codec))) {
1017 slen = strlen(formatname);
1018 if (slen > total_len)
1020 strncat(buf, formatname, total_len - 1); /* safe */
1023 if (total_len && x < sizeof(format_t) * 8 - 1 && ast_codec_pref_index(pref, x + 1)) {
1024 strncat(buf, "|", total_len - 1); /* safe */
1029 strncat(buf, ")", total_len - 1); /* safe */
1033 return size - total_len;
1036 format_t ast_codec_pref_index(struct ast_codec_pref *pref, int idx)
1040 if ((idx >= 0) && (idx < sizeof(pref->order))) {
1041 slot = pref->order[idx];
1044 return slot ? AST_FORMAT_LIST[slot - 1].bits : 0;
1047 /*! \brief Remove codec from pref list */
1048 void ast_codec_pref_remove(struct ast_codec_pref *pref, format_t format)
1050 struct ast_codec_pref oldorder;
1055 if (!pref->order[0])
1058 memcpy(&oldorder, pref, sizeof(oldorder));
1059 memset(pref, 0, sizeof(*pref));
1061 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1062 slot = oldorder.order[x];
1063 size = oldorder.framing[x];
1066 if (AST_FORMAT_LIST[slot-1].bits != format) {
1067 pref->order[y] = slot;
1068 pref->framing[y++] = size;
1073 /*! \brief Append codec to list */
1074 int ast_codec_pref_append(struct ast_codec_pref *pref, format_t format)
1076 int x, newindex = 0;
1078 ast_codec_pref_remove(pref, format);
1080 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1081 if (AST_FORMAT_LIST[x].bits == format) {
1088 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1089 if (!pref->order[x]) {
1090 pref->order[x] = newindex;
1099 /*! \brief Prepend codec to list */
1100 void ast_codec_pref_prepend(struct ast_codec_pref *pref, format_t format, int only_if_existing)
1102 int x, newindex = 0;
1104 /* First step is to get the codecs "index number" */
1105 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1106 if (AST_FORMAT_LIST[x].bits == format) {
1111 /* Done if its unknown */
1115 /* Now find any existing occurrence, or the end */
1116 for (x = 0; x < sizeof(format_t) * 8; x++) {
1117 if (!pref->order[x] || pref->order[x] == newindex)
1121 if (only_if_existing && !pref->order[x])
1124 /* Move down to make space to insert - either all the way to the end,
1125 or as far as the existing location (which will be overwritten) */
1126 for (; x > 0; x--) {
1127 pref->order[x] = pref->order[x - 1];
1128 pref->framing[x] = pref->framing[x - 1];
1131 /* And insert the new entry */
1132 pref->order[0] = newindex;
1133 pref->framing[0] = 0; /* ? */
1136 /*! \brief Set packet size for codec */
1137 int ast_codec_pref_setsize(struct ast_codec_pref *pref, format_t format, int framems)
1141 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1142 if (AST_FORMAT_LIST[x].bits == format) {
1151 /* size validation */
1153 framems = AST_FORMAT_LIST[idx].def_ms;
1155 if (AST_FORMAT_LIST[idx].inc_ms && framems % AST_FORMAT_LIST[idx].inc_ms) /* avoid division by zero */
1156 framems -= framems % AST_FORMAT_LIST[idx].inc_ms;
1158 if (framems < AST_FORMAT_LIST[idx].min_ms)
1159 framems = AST_FORMAT_LIST[idx].min_ms;
1161 if (framems > AST_FORMAT_LIST[idx].max_ms)
1162 framems = AST_FORMAT_LIST[idx].max_ms;
1164 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1165 if (pref->order[x] == (idx + 1)) {
1166 pref->framing[x] = framems;
1174 /*! \brief Get packet size for codec */
1175 struct ast_format_list ast_codec_pref_getsize(struct ast_codec_pref *pref, format_t format)
1177 int x, idx = -1, framems = 0;
1178 struct ast_format_list fmt = { 0, };
1180 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1181 if (AST_FORMAT_LIST[x].bits == format) {
1182 fmt = AST_FORMAT_LIST[x];
1188 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1189 if (pref->order[x] == (idx + 1)) {
1190 framems = pref->framing[x];
1195 /* size validation */
1197 framems = AST_FORMAT_LIST[idx].def_ms;
1199 if (AST_FORMAT_LIST[idx].inc_ms && framems % AST_FORMAT_LIST[idx].inc_ms) /* avoid division by zero */
1200 framems -= framems % AST_FORMAT_LIST[idx].inc_ms;
1202 if (framems < AST_FORMAT_LIST[idx].min_ms)
1203 framems = AST_FORMAT_LIST[idx].min_ms;
1205 if (framems > AST_FORMAT_LIST[idx].max_ms)
1206 framems = AST_FORMAT_LIST[idx].max_ms;
1208 fmt.cur_ms = framems;
1213 /*! \brief Pick a codec */
1214 format_t ast_codec_choose(struct ast_codec_pref *pref, format_t formats, int find_best)
1219 for (x = 0; x < ARRAY_LEN(AST_FORMAT_LIST); x++) {
1220 slot = pref->order[x];
1224 if (formats & AST_FORMAT_LIST[slot-1].bits) {
1225 ret = AST_FORMAT_LIST[slot-1].bits;
1229 if (ret & AST_FORMAT_AUDIO_MASK)
1232 ast_debug(4, "Could not find preferred codec - %s\n", find_best ? "Going for the best codec" : "Returning zero codec");
1234 return find_best ? ast_best_codec(formats) : 0;
1237 int ast_parse_allow_disallow(struct ast_codec_pref *pref, format_t *mask, const char *list, int allowing)
1239 int errors = 0, framems = 0;
1240 char *parse = NULL, *this = NULL, *psize = NULL;
1241 format_t format = 0;
1243 parse = ast_strdupa(list);
1244 while ((this = strsep(&parse, ","))) {
1246 if ((psize = strrchr(this, ':'))) {
1248 ast_debug(1, "Packetization for codec: %s is %s\n", this, psize);
1249 framems = atoi(psize);
1253 ast_log(LOG_WARNING, "Bad packetization value for codec %s\n", this);
1256 if (!(format = ast_getformatbyname(this))) {
1257 ast_log(LOG_WARNING, "Cannot %s unknown format '%s'\n", allowing ? "allow" : "disallow", this);
1269 /* Set up a preference list for audio. Do not include video in preferences
1270 since we can not transcode video and have to use whatever is offered
1272 if (pref && (format & AST_FORMAT_AUDIO_MASK)) {
1273 if (strcasecmp(this, "all")) {
1275 ast_codec_pref_append(pref, format);
1276 ast_codec_pref_setsize(pref, format, framems);
1279 ast_codec_pref_remove(pref, format);
1280 } else if (!allowing) {
1281 memset(pref, 0, sizeof(*pref));
1288 static int g723_len(unsigned char buf)
1290 enum frame_type type = buf & TYPE_MASK;
1306 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", type);
1311 static int g723_samples(unsigned char *buf, int maxlen)
1316 while(pos < maxlen) {
1317 res = g723_len(buf[pos]);
1326 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
1328 int byte = bit / 8; /* byte containing first bit */
1329 int rem = 8 - (bit % 8); /* remaining bits in first byte */
1330 unsigned char ret = 0;
1332 if (n <= 0 || n > 8)
1336 ret = (data[byte] << (n - rem));
1337 ret |= (data[byte + 1] >> (8 - n + rem));
1339 ret = (data[byte] >> (rem - n));
1342 return (ret & (0xff >> (8 - n)));
1345 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
1347 static const int SpeexWBSubModeSz[] = {
1353 /* skip up to two wideband frames */
1354 if (((len * 8 - off) >= 5) &&
1355 get_n_bits_at(data, 1, off)) {
1356 c = get_n_bits_at(data, 3, off + 1);
1357 off += SpeexWBSubModeSz[c];
1359 if (((len * 8 - off) >= 5) &&
1360 get_n_bits_at(data, 1, off)) {
1361 c = get_n_bits_at(data, 3, off + 1);
1362 off += SpeexWBSubModeSz[c];
1364 if (((len * 8 - off) >= 5) &&
1365 get_n_bits_at(data, 1, off)) {
1366 ast_log(LOG_WARNING, "Encountered corrupt speex frame; too many wideband frames in a row.\n");
1375 static int speex_samples(unsigned char *data, int len)
1377 static const int SpeexSubModeSz[] = {
1382 static const int SpeexInBandSz[] = {
1392 while ((len * 8 - bit) >= 5) {
1393 /* skip wideband frames */
1394 off = speex_get_wb_sz_at(data, len, bit);
1396 ast_log(LOG_WARNING, "Had error while reading wideband frames for speex samples\n");
1401 if ((len * 8 - bit) < 5) {
1402 ast_log(LOG_WARNING, "Not enough bits remaining after wide band for speex samples.\n");
1406 /* get control bits */
1407 c = get_n_bits_at(data, 5, bit);
1413 } else if (c == 14) {
1414 /* in-band signal; next 4 bits contain signal id */
1415 c = get_n_bits_at(data, 4, bit);
1417 bit += SpeexInBandSz[c];
1418 } else if (c == 13) {
1419 /* user in-band; next 5 bits contain msg len */
1420 c = get_n_bits_at(data, 5, bit);
1427 /* skip number bits for submode (less the 5 control bits) */
1428 bit += SpeexSubModeSz[c] - 5;
1429 cnt += 160; /* new frame */
1435 int ast_codec_get_samples(struct ast_frame *f)
1440 switch (f->subclass.codec) {
1441 case AST_FORMAT_SPEEX:
1442 samples = speex_samples(f->data.ptr, f->datalen);
1444 case AST_FORMAT_G723_1:
1445 samples = g723_samples(f->data.ptr, f->datalen);
1447 case AST_FORMAT_ILBC:
1448 samples = 240 * (f->datalen / 50);
1450 case AST_FORMAT_GSM:
1451 samples = 160 * (f->datalen / 33);
1453 case AST_FORMAT_G729A:
1454 samples = f->datalen * 8;
1456 case AST_FORMAT_SLINEAR:
1457 case AST_FORMAT_SLINEAR16:
1458 samples = f->datalen / 2;
1460 case AST_FORMAT_LPC10:
1461 /* assumes that the RTP packet contains one LPC10 frame */
1463 samples += (((char *)(f->data.ptr))[7] & 0x1) * 8;
1465 case AST_FORMAT_ULAW:
1466 case AST_FORMAT_ALAW:
1467 case AST_FORMAT_TESTLAW:
1468 samples = f->datalen;
1470 case AST_FORMAT_G722:
1471 case AST_FORMAT_ADPCM:
1472 case AST_FORMAT_G726:
1473 case AST_FORMAT_G726_AAL2:
1474 samples = f->datalen * 2;
1476 case AST_FORMAT_SIREN7:
1477 /* 16,000 samples per second at 32kbps is 4,000 bytes per second */
1478 samples = f->datalen * (16000 / 4000);
1480 case AST_FORMAT_SIREN14:
1481 /* 32,000 samples per second at 48kbps is 6,000 bytes per second */
1482 samples = (int) f->datalen * ((float) 32000 / 6000);
1485 ast_log(LOG_WARNING, "Unable to calculate samples for format %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), f->subclass.codec));
1490 int ast_codec_get_len(format_t format, int samples)
1494 /* XXX Still need speex, and lpc10 XXX */
1496 case AST_FORMAT_G723_1:
1497 len = (samples / 240) * 20;
1499 case AST_FORMAT_ILBC:
1500 len = (samples / 240) * 50;
1502 case AST_FORMAT_GSM:
1503 len = (samples / 160) * 33;
1505 case AST_FORMAT_G729A:
1508 case AST_FORMAT_SLINEAR:
1509 case AST_FORMAT_SLINEAR16:
1512 case AST_FORMAT_ULAW:
1513 case AST_FORMAT_ALAW:
1514 case AST_FORMAT_TESTLAW:
1517 case AST_FORMAT_G722:
1518 case AST_FORMAT_ADPCM:
1519 case AST_FORMAT_G726:
1520 case AST_FORMAT_G726_AAL2:
1523 case AST_FORMAT_SIREN7:
1524 /* 16,000 samples per second at 32kbps is 4,000 bytes per second */
1525 len = samples / (16000 / 4000);
1527 case AST_FORMAT_SIREN14:
1528 /* 32,000 samples per second at 48kbps is 6,000 bytes per second */
1529 len = (int) samples / ((float) 32000 / 6000);
1532 ast_log(LOG_WARNING, "Unable to calculate sample length for format %s\n", ast_getformatname(format));
1538 int ast_frame_adjust_volume(struct ast_frame *f, int adjustment)
1541 short *fdata = f->data.ptr;
1542 short adjust_value = abs(adjustment);
1544 if ((f->frametype != AST_FRAME_VOICE) || (f->subclass.codec != AST_FORMAT_SLINEAR))
1550 for (count = 0; count < f->samples; count++) {
1551 if (adjustment > 0) {
1552 ast_slinear_saturated_multiply(&fdata[count], &adjust_value);
1553 } else if (adjustment < 0) {
1554 ast_slinear_saturated_divide(&fdata[count], &adjust_value);
1561 int ast_frame_slinear_sum(struct ast_frame *f1, struct ast_frame *f2)
1564 short *data1, *data2;
1566 if ((f1->frametype != AST_FRAME_VOICE) || (f1->subclass.codec != AST_FORMAT_SLINEAR))
1569 if ((f2->frametype != AST_FRAME_VOICE) || (f2->subclass.codec != AST_FORMAT_SLINEAR))
1572 if (f1->samples != f2->samples)
1575 for (count = 0, data1 = f1->data.ptr, data2 = f2->data.ptr;
1576 count < f1->samples;
1577 count++, data1++, data2++)
1578 ast_slinear_saturated_add(data1, data2);