Sat Apr 26 2014 22:01:36

Asterisk developer's documentation


frame.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Frame and codec manipulation routines
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 370431 $")
00033 
00034 #include "asterisk/_private.h"
00035 #include "asterisk/lock.h"
00036 #include "asterisk/frame.h"
00037 #include "asterisk/channel.h"
00038 #include "asterisk/cli.h"
00039 #include "asterisk/term.h"
00040 #include "asterisk/utils.h"
00041 #include "asterisk/threadstorage.h"
00042 #include "asterisk/linkedlists.h"
00043 #include "asterisk/translate.h"
00044 #include "asterisk/dsp.h"
00045 #include "asterisk/file.h"
00046 
00047 #if !defined(LOW_MEMORY)
00048 static void frame_cache_cleanup(void *data);
00049 
00050 /*! \brief A per-thread cache of frame headers */
00051 AST_THREADSTORAGE_CUSTOM(frame_cache, NULL, frame_cache_cleanup);
00052 
00053 /*!
00054  * \brief Maximum ast_frame cache size
00055  *
00056  * In most cases where the frame header cache will be useful, the size
00057  * of the cache will stay very small.  However, it is not always the case that
00058  * the same thread that allocates the frame will be the one freeing them, so
00059  * sometimes a thread will never have any frames in its cache, or the cache
00060  * will never be pulled from.  For the latter case, we limit the maximum size.
00061  */
00062 #define FRAME_CACHE_MAX_SIZE  10
00063 
00064 /*! \brief This is just so ast_frames, a list head struct for holding a list of
00065  *  ast_frame structures, is defined. */
00066 AST_LIST_HEAD_NOLOCK(ast_frames, ast_frame);
00067 
00068 struct ast_frame_cache {
00069    struct ast_frames list;
00070    size_t size;
00071 };
00072 #endif
00073 
00074 #define SMOOTHER_SIZE 8000
00075 
00076 enum frame_type {
00077    TYPE_HIGH,     /* 0x0 */
00078    TYPE_LOW,      /* 0x1 */
00079    TYPE_SILENCE,  /* 0x2 */
00080    TYPE_DONTSEND  /* 0x3 */
00081 };
00082 
00083 #define TYPE_MASK 0x3
00084 
00085 struct ast_smoother {
00086    int size;
00087    struct ast_format format;
00088    int flags;
00089    float samplesperbyte;
00090    unsigned int opt_needs_swap:1;
00091    struct ast_frame f;
00092    struct timeval delivery;
00093    char data[SMOOTHER_SIZE];
00094    char framedata[SMOOTHER_SIZE + AST_FRIENDLY_OFFSET];
00095    struct ast_frame *opt;
00096    int len;
00097 };
00098 
00099 struct ast_frame ast_null_frame = { AST_FRAME_NULL, };
00100 
00101 static int smoother_frame_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
00102 {
00103    if (s->flags & AST_SMOOTHER_FLAG_G729) {
00104       if (s->len % 10) {
00105          ast_log(LOG_NOTICE, "Dropping extra frame of G.729 since we already have a VAD frame at the end\n");
00106          return 0;
00107       }
00108    }
00109    if (swap) {
00110       ast_swapcopy_samples(s->data + s->len, f->data.ptr, f->samples);
00111    } else {
00112       memcpy(s->data + s->len, f->data.ptr, f->datalen);
00113    }
00114    /* If either side is empty, reset the delivery time */
00115    if (!s->len || ast_tvzero(f->delivery) || ast_tvzero(s->delivery)) { /* XXX really ? */
00116       s->delivery = f->delivery;
00117    }
00118    s->len += f->datalen;
00119 
00120    return 0;
00121 }
00122 
00123 void ast_smoother_reset(struct ast_smoother *s, int bytes)
00124 {
00125    memset(s, 0, sizeof(*s));
00126    s->size = bytes;
00127 }
00128 
00129 void ast_smoother_reconfigure(struct ast_smoother *s, int bytes)
00130 {
00131    /* if there is no change, then nothing to do */
00132    if (s->size == bytes) {
00133       return;
00134    }
00135    /* set the new desired output size */
00136    s->size = bytes;
00137    /* if there is no 'optimized' frame in the smoother,
00138     *   then there is nothing left to do
00139     */
00140    if (!s->opt) {
00141       return;
00142    }
00143    /* there is an 'optimized' frame here at the old size,
00144     * but it must now be put into the buffer so the data
00145     * can be extracted at the new size
00146     */
00147    smoother_frame_feed(s, s->opt, s->opt_needs_swap);
00148    s->opt = NULL;
00149 }
00150 
00151 struct ast_smoother *ast_smoother_new(int size)
00152 {
00153    struct ast_smoother *s;
00154    if (size < 1)
00155       return NULL;
00156    if ((s = ast_malloc(sizeof(*s))))
00157       ast_smoother_reset(s, size);
00158    return s;
00159 }
00160 
00161 int ast_smoother_get_flags(struct ast_smoother *s)
00162 {
00163    return s->flags;
00164 }
00165 
00166 void ast_smoother_set_flags(struct ast_smoother *s, int flags)
00167 {
00168    s->flags = flags;
00169 }
00170 
00171 int ast_smoother_test_flag(struct ast_smoother *s, int flag)
00172 {
00173    return (s->flags & flag);
00174 }
00175 
00176 int __ast_smoother_feed(struct ast_smoother *s, struct ast_frame *f, int swap)
00177 {
00178    if (f->frametype != AST_FRAME_VOICE) {
00179       ast_log(LOG_WARNING, "Huh?  Can't smooth a non-voice frame!\n");
00180       return -1;
00181    }
00182    if (!s->format.id) {
00183       ast_format_copy(&s->format, &f->subclass.format);
00184       s->samplesperbyte = (float)f->samples / (float)f->datalen;
00185    } else if (ast_format_cmp(&s->format, &f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
00186       ast_log(LOG_WARNING, "Smoother was working on %s format frames, now trying to feed %s?\n",
00187          ast_getformatname(&s->format), ast_getformatname(&f->subclass.format));
00188       return -1;
00189    }
00190    if (s->len + f->datalen > SMOOTHER_SIZE) {
00191       ast_log(LOG_WARNING, "Out of smoother space\n");
00192       return -1;
00193    }
00194    if (((f->datalen == s->size) ||
00195         ((f->datalen < 10) && (s->flags & AST_SMOOTHER_FLAG_G729))) &&
00196        !s->opt &&
00197        !s->len &&
00198        (f->offset >= AST_MIN_OFFSET)) {
00199       /* Optimize by sending the frame we just got
00200          on the next read, thus eliminating the douple
00201          copy */
00202       if (swap)
00203          ast_swapcopy_samples(f->data.ptr, f->data.ptr, f->samples);
00204       s->opt = f;
00205       s->opt_needs_swap = swap ? 1 : 0;
00206       return 0;
00207    }
00208 
00209    return smoother_frame_feed(s, f, swap);
00210 }
00211 
00212 struct ast_frame *ast_smoother_read(struct ast_smoother *s)
00213 {
00214    struct ast_frame *opt;
00215    int len;
00216 
00217    /* IF we have an optimization frame, send it */
00218    if (s->opt) {
00219       if (s->opt->offset < AST_FRIENDLY_OFFSET)
00220          ast_log(LOG_WARNING, "Returning a frame of inappropriate offset (%d).\n",
00221                      s->opt->offset);
00222       opt = s->opt;
00223       s->opt = NULL;
00224       return opt;
00225    }
00226 
00227    /* Make sure we have enough data */
00228    if (s->len < s->size) {
00229       /* Or, if this is a G.729 frame with VAD on it, send it immediately anyway */
00230       if (!((s->flags & AST_SMOOTHER_FLAG_G729) && (s->len % 10)))
00231          return NULL;
00232    }
00233    len = s->size;
00234    if (len > s->len)
00235       len = s->len;
00236    /* Make frame */
00237    s->f.frametype = AST_FRAME_VOICE;
00238    ast_format_copy(&s->f.subclass.format, &s->format);
00239    s->f.data.ptr = s->framedata + AST_FRIENDLY_OFFSET;
00240    s->f.offset = AST_FRIENDLY_OFFSET;
00241    s->f.datalen = len;
00242    /* Samples will be improper given VAD, but with VAD the concept really doesn't even exist */
00243    s->f.samples = len * s->samplesperbyte;   /* XXX rounding */
00244    s->f.delivery = s->delivery;
00245    /* Fill Data */
00246    memcpy(s->f.data.ptr, s->data, len);
00247    s->len -= len;
00248    /* Move remaining data to the front if applicable */
00249    if (s->len) {
00250       /* In principle this should all be fine because if we are sending
00251          G.729 VAD, the next timestamp will take over anyawy */
00252       memmove(s->data, s->data + len, s->len);
00253       if (!ast_tvzero(s->delivery)) {
00254          /* If we have delivery time, increment it, otherwise, leave it at 0 */
00255          s->delivery = ast_tvadd(s->delivery, ast_samp2tv(s->f.samples, ast_format_rate(&s->format)));
00256       }
00257    }
00258    /* Return frame */
00259    return &s->f;
00260 }
00261 
00262 void ast_smoother_free(struct ast_smoother *s)
00263 {
00264    ast_free(s);
00265 }
00266 
00267 static struct ast_frame *ast_frame_header_new(void)
00268 {
00269    struct ast_frame *f;
00270 
00271 #if !defined(LOW_MEMORY)
00272    struct ast_frame_cache *frames;
00273 
00274    if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
00275       if ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list))) {
00276          size_t mallocd_len = f->mallocd_hdr_len;
00277          memset(f, 0, sizeof(*f));
00278          f->mallocd_hdr_len = mallocd_len;
00279          f->mallocd = AST_MALLOCD_HDR;
00280          frames->size--;
00281          return f;
00282       }
00283    }
00284    if (!(f = ast_calloc_cache(1, sizeof(*f))))
00285       return NULL;
00286 #else
00287    if (!(f = ast_calloc(1, sizeof(*f))))
00288       return NULL;
00289 #endif
00290 
00291    f->mallocd_hdr_len = sizeof(*f);
00292 
00293    return f;
00294 }
00295 
00296 #if !defined(LOW_MEMORY)
00297 static void frame_cache_cleanup(void *data)
00298 {
00299    struct ast_frame_cache *frames = data;
00300    struct ast_frame *f;
00301 
00302    while ((f = AST_LIST_REMOVE_HEAD(&frames->list, frame_list)))
00303       ast_free(f);
00304 
00305    ast_free(frames);
00306 }
00307 #endif
00308 
00309 static void __frame_free(struct ast_frame *fr, int cache)
00310 {
00311    if (!fr->mallocd)
00312       return;
00313 
00314 #if !defined(LOW_MEMORY)
00315    if (cache && fr->mallocd == AST_MALLOCD_HDR) {
00316       /* Cool, only the header is malloc'd, let's just cache those for now
00317        * to keep things simple... */
00318       struct ast_frame_cache *frames;
00319 
00320       if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames))) &&
00321           (frames->size < FRAME_CACHE_MAX_SIZE)) {
00322          AST_LIST_INSERT_HEAD(&frames->list, fr, frame_list);
00323          frames->size++;
00324          return;
00325       }
00326    }
00327 #endif
00328 
00329    if (fr->mallocd & AST_MALLOCD_DATA) {
00330       if (fr->data.ptr)
00331          ast_free(fr->data.ptr - fr->offset);
00332    }
00333    if (fr->mallocd & AST_MALLOCD_SRC) {
00334       if (fr->src)
00335          ast_free((void *) fr->src);
00336    }
00337    if (fr->mallocd & AST_MALLOCD_HDR) {
00338       ast_free(fr);
00339    }
00340 }
00341 
00342 
00343 void ast_frame_free(struct ast_frame *frame, int cache)
00344 {
00345    struct ast_frame *next;
00346 
00347    for (next = AST_LIST_NEXT(frame, frame_list);
00348         frame;
00349         frame = next, next = frame ? AST_LIST_NEXT(frame, frame_list) : NULL) {
00350       __frame_free(frame, cache);
00351    }
00352 }
00353 
00354 /*!
00355  * \brief 'isolates' a frame by duplicating non-malloc'ed components
00356  * (header, src, data).
00357  * On return all components are malloc'ed
00358  */
00359 struct ast_frame *ast_frisolate(struct ast_frame *fr)
00360 {
00361    struct ast_frame *out;
00362    void *newdata;
00363 
00364    /* if none of the existing frame is malloc'd, let ast_frdup() do it
00365       since it is more efficient
00366    */
00367    if (fr->mallocd == 0) {
00368       return ast_frdup(fr);
00369    }
00370 
00371    /* if everything is already malloc'd, we are done */
00372    if ((fr->mallocd & (AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA)) ==
00373        (AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA)) {
00374       return fr;
00375    }
00376 
00377    if (!(fr->mallocd & AST_MALLOCD_HDR)) {
00378       /* Allocate a new header if needed */
00379       if (!(out = ast_frame_header_new())) {
00380          return NULL;
00381       }
00382       out->frametype = fr->frametype;
00383       ast_format_copy(&out->subclass.format, &fr->subclass.format);
00384       out->datalen = fr->datalen;
00385       out->samples = fr->samples;
00386       out->offset = fr->offset;
00387       /* Copy the timing data */
00388       ast_copy_flags(out, fr, AST_FLAGS_ALL);
00389       if (ast_test_flag(fr, AST_FRFLAG_HAS_TIMING_INFO)) {
00390          out->ts = fr->ts;
00391          out->len = fr->len;
00392          out->seqno = fr->seqno;
00393       }
00394    } else {
00395       out = fr;
00396    }
00397 
00398    if (!(fr->mallocd & AST_MALLOCD_SRC) && fr->src) {
00399       if (!(out->src = ast_strdup(fr->src))) {
00400          if (out != fr) {
00401             ast_free(out);
00402          }
00403          return NULL;
00404       }
00405    } else {
00406       out->src = fr->src;
00407       fr->src = NULL;
00408       fr->mallocd &= ~AST_MALLOCD_SRC;
00409    }
00410 
00411    if (!(fr->mallocd & AST_MALLOCD_DATA))  {
00412       if (!fr->datalen) {
00413          out->data.uint32 = fr->data.uint32;
00414          out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC;
00415          return out;
00416       }
00417       if (!(newdata = ast_malloc(fr->datalen + AST_FRIENDLY_OFFSET))) {
00418          if (out->src != fr->src) {
00419             ast_free((void *) out->src);
00420          }
00421          if (out != fr) {
00422             ast_free(out);
00423          }
00424          return NULL;
00425       }
00426       newdata += AST_FRIENDLY_OFFSET;
00427       out->offset = AST_FRIENDLY_OFFSET;
00428       out->datalen = fr->datalen;
00429       memcpy(newdata, fr->data.ptr, fr->datalen);
00430       out->data.ptr = newdata;
00431    } else {
00432       out->data = fr->data;
00433       memset(&fr->data, 0, sizeof(fr->data));
00434       fr->mallocd &= ~AST_MALLOCD_DATA;
00435    }
00436 
00437    out->mallocd = AST_MALLOCD_HDR | AST_MALLOCD_SRC | AST_MALLOCD_DATA;
00438 
00439    return out;
00440 }
00441 
00442 struct ast_frame *ast_frdup(const struct ast_frame *f)
00443 {
00444    struct ast_frame *out = NULL;
00445    int len, srclen = 0;
00446    void *buf = NULL;
00447 
00448 #if !defined(LOW_MEMORY)
00449    struct ast_frame_cache *frames;
00450 #endif
00451 
00452    /* Start with standard stuff */
00453    len = sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
00454    /* If we have a source, add space for it */
00455    /*
00456     * XXX Watch out here - if we receive a src which is not terminated
00457     * properly, we can be easily attacked. Should limit the size we deal with.
00458     */
00459    if (f->src)
00460       srclen = strlen(f->src);
00461    if (srclen > 0)
00462       len += srclen + 1;
00463 
00464 #if !defined(LOW_MEMORY)
00465    if ((frames = ast_threadstorage_get(&frame_cache, sizeof(*frames)))) {
00466       AST_LIST_TRAVERSE_SAFE_BEGIN(&frames->list, out, frame_list) {
00467          if (out->mallocd_hdr_len >= len) {
00468             size_t mallocd_len = out->mallocd_hdr_len;
00469 
00470             AST_LIST_REMOVE_CURRENT(frame_list);
00471             memset(out, 0, sizeof(*out));
00472             out->mallocd_hdr_len = mallocd_len;
00473             buf = out;
00474             frames->size--;
00475             break;
00476          }
00477       }
00478       AST_LIST_TRAVERSE_SAFE_END;
00479    }
00480 #endif
00481 
00482    if (!buf) {
00483       if (!(buf = ast_calloc_cache(1, len)))
00484          return NULL;
00485       out = buf;
00486       out->mallocd_hdr_len = len;
00487    }
00488 
00489    out->frametype = f->frametype;
00490    ast_format_copy(&out->subclass.format, &f->subclass.format);
00491    out->datalen = f->datalen;
00492    out->samples = f->samples;
00493    out->delivery = f->delivery;
00494    /* Even though this new frame was allocated from the heap, we can't mark it
00495     * with AST_MALLOCD_HDR, AST_MALLOCD_DATA and AST_MALLOCD_SRC, because that
00496     * would cause ast_frfree() to attempt to individually free each of those
00497     * under the assumption that they were separately allocated. Since this frame
00498     * was allocated in a single allocation, we'll only mark it as if the header
00499     * was heap-allocated; this will result in the entire frame being properly freed.
00500     */
00501    out->mallocd = AST_MALLOCD_HDR;
00502    out->offset = AST_FRIENDLY_OFFSET;
00503    if (out->datalen) {
00504       out->data.ptr = buf + sizeof(*out) + AST_FRIENDLY_OFFSET;
00505       memcpy(out->data.ptr, f->data.ptr, out->datalen);
00506    } else {
00507       out->data.uint32 = f->data.uint32;
00508    }
00509    if (srclen > 0) {
00510       /* This may seem a little strange, but it's to avoid a gcc (4.2.4) compiler warning */
00511       char *src;
00512       out->src = buf + sizeof(*out) + AST_FRIENDLY_OFFSET + f->datalen;
00513       src = (char *) out->src;
00514       /* Must have space since we allocated for it */
00515       strcpy(src, f->src);
00516    }
00517    ast_copy_flags(out, f, AST_FLAGS_ALL);
00518    out->ts = f->ts;
00519    out->len = f->len;
00520    out->seqno = f->seqno;
00521    return out;
00522 }
00523 
00524 void ast_swapcopy_samples(void *dst, const void *src, int samples)
00525 {
00526    int i;
00527    unsigned short *dst_s = dst;
00528    const unsigned short *src_s = src;
00529 
00530    for (i = 0; i < samples; i++)
00531       dst_s[i] = (src_s[i]<<8) | (src_s[i]>>8);
00532 }
00533 
00534 void ast_frame_subclass2str(struct ast_frame *f, char *subclass, size_t slen, char *moreinfo, size_t mlen)
00535 {
00536    switch(f->frametype) {
00537    case AST_FRAME_DTMF_BEGIN:
00538       if (slen > 1) {
00539          subclass[0] = f->subclass.integer;
00540          subclass[1] = '\0';
00541       }
00542       break;
00543    case AST_FRAME_DTMF_END:
00544       if (slen > 1) {
00545          subclass[0] = f->subclass.integer;
00546          subclass[1] = '\0';
00547       }
00548       break;
00549    case AST_FRAME_CONTROL:
00550       switch (f->subclass.integer) {
00551       case AST_CONTROL_HANGUP:
00552          ast_copy_string(subclass, "Hangup", slen);
00553          break;
00554       case AST_CONTROL_RING:
00555          ast_copy_string(subclass, "Ring", slen);
00556          break;
00557       case AST_CONTROL_RINGING:
00558          ast_copy_string(subclass, "Ringing", slen);
00559          break;
00560       case AST_CONTROL_ANSWER:
00561          ast_copy_string(subclass, "Answer", slen);
00562          break;
00563       case AST_CONTROL_BUSY:
00564          ast_copy_string(subclass, "Busy", slen);
00565          break;
00566       case AST_CONTROL_TAKEOFFHOOK:
00567          ast_copy_string(subclass, "Take Off Hook", slen);
00568          break;
00569       case AST_CONTROL_OFFHOOK:
00570          ast_copy_string(subclass, "Line Off Hook", slen);
00571          break;
00572       case AST_CONTROL_CONGESTION:
00573          ast_copy_string(subclass, "Congestion", slen);
00574          break;
00575       case AST_CONTROL_FLASH:
00576          ast_copy_string(subclass, "Flash", slen);
00577          break;
00578       case AST_CONTROL_WINK:
00579          ast_copy_string(subclass, "Wink", slen);
00580          break;
00581       case AST_CONTROL_OPTION:
00582          ast_copy_string(subclass, "Option", slen);
00583          break;
00584       case AST_CONTROL_RADIO_KEY:
00585          ast_copy_string(subclass, "Key Radio", slen);
00586          break;
00587       case AST_CONTROL_RADIO_UNKEY:
00588          ast_copy_string(subclass, "Unkey Radio", slen);
00589          break;
00590       case AST_CONTROL_HOLD:
00591          ast_copy_string(subclass, "Hold", slen);
00592          break;
00593       case AST_CONTROL_UNHOLD:
00594          ast_copy_string(subclass, "Unhold", slen);
00595          break;
00596       case AST_CONTROL_T38_PARAMETERS: {
00597          char *message = "Unknown";
00598          if (f->datalen != sizeof(struct ast_control_t38_parameters)) {
00599             message = "Invalid";
00600          } else {
00601             struct ast_control_t38_parameters *parameters = f->data.ptr;
00602             enum ast_control_t38 state = parameters->request_response;
00603             if (state == AST_T38_REQUEST_NEGOTIATE)
00604                message = "Negotiation Requested";
00605             else if (state == AST_T38_REQUEST_TERMINATE)
00606                message = "Negotiation Request Terminated";
00607             else if (state == AST_T38_NEGOTIATED)
00608                message = "Negotiated";
00609             else if (state == AST_T38_TERMINATED)
00610                message = "Terminated";
00611             else if (state == AST_T38_REFUSED)
00612                message = "Refused";
00613          }
00614          snprintf(subclass, slen, "T38_Parameters/%s", message);
00615          break;
00616       }
00617       case -1:
00618          ast_copy_string(subclass, "Stop generators", slen);
00619          break;
00620       default:
00621          snprintf(subclass, slen, "Unknown control '%d'", f->subclass.integer);
00622       }
00623       break;
00624    case AST_FRAME_NULL:
00625       ast_copy_string(subclass, "N/A", slen);
00626       break;
00627    case AST_FRAME_IAX:
00628       /* Should never happen */
00629       snprintf(subclass, slen, "IAX Frametype %d", f->subclass.integer);
00630       break;
00631    case AST_FRAME_TEXT:
00632       ast_copy_string(subclass, "N/A", slen);
00633       if (moreinfo) {
00634          ast_copy_string(moreinfo, f->data.ptr, mlen);
00635       }
00636       break;
00637    case AST_FRAME_IMAGE:
00638       snprintf(subclass, slen, "Image format %s\n", ast_getformatname(&f->subclass.format));
00639       break;
00640    case AST_FRAME_HTML:
00641       switch (f->subclass.integer) {
00642       case AST_HTML_URL:
00643          ast_copy_string(subclass, "URL", slen);
00644          if (moreinfo) {
00645             ast_copy_string(moreinfo, f->data.ptr, mlen);
00646          }
00647          break;
00648       case AST_HTML_DATA:
00649          ast_copy_string(subclass, "Data", slen);
00650          break;
00651       case AST_HTML_BEGIN:
00652          ast_copy_string(subclass, "Begin", slen);
00653          break;
00654       case AST_HTML_END:
00655          ast_copy_string(subclass, "End", slen);
00656          break;
00657       case AST_HTML_LDCOMPLETE:
00658          ast_copy_string(subclass, "Load Complete", slen);
00659          break;
00660       case AST_HTML_NOSUPPORT:
00661          ast_copy_string(subclass, "No Support", slen);
00662          break;
00663       case AST_HTML_LINKURL:
00664          ast_copy_string(subclass, "Link URL", slen);
00665          if (moreinfo) {
00666             ast_copy_string(moreinfo, f->data.ptr, mlen);
00667          }
00668          break;
00669       case AST_HTML_UNLINK:
00670          ast_copy_string(subclass, "Unlink", slen);
00671          break;
00672       case AST_HTML_LINKREJECT:
00673          ast_copy_string(subclass, "Link Reject", slen);
00674          break;
00675       default:
00676          snprintf(subclass, slen, "Unknown HTML frame '%d'\n", f->subclass.integer);
00677          break;
00678       }
00679       break;
00680    case AST_FRAME_MODEM:
00681       switch (f->subclass.integer) {
00682       case AST_MODEM_T38:
00683          ast_copy_string(subclass, "T.38", slen);
00684          break;
00685       case AST_MODEM_V150:
00686          ast_copy_string(subclass, "V.150", slen);
00687          break;
00688       default:
00689          snprintf(subclass, slen, "Unknown MODEM frame '%d'\n", f->subclass.integer);
00690          break;
00691       }
00692       break;
00693    default:
00694       ast_copy_string(subclass, "Unknown Subclass", slen);
00695    }
00696 }
00697 
00698 void ast_frame_type2str(enum ast_frame_type frame_type, char *ftype, size_t len)
00699 {
00700    switch (frame_type) {
00701    case AST_FRAME_DTMF_BEGIN:
00702       ast_copy_string(ftype, "DTMF Begin", len);
00703       break;
00704    case AST_FRAME_DTMF_END:
00705       ast_copy_string(ftype, "DTMF End", len);
00706       break;
00707    case AST_FRAME_CONTROL:
00708       ast_copy_string(ftype, "Control", len);
00709       break;
00710    case AST_FRAME_NULL:
00711       ast_copy_string(ftype, "Null Frame", len);
00712       break;
00713    case AST_FRAME_IAX:
00714       /* Should never happen */
00715       ast_copy_string(ftype, "IAX Specific", len);
00716       break;
00717    case AST_FRAME_TEXT:
00718       ast_copy_string(ftype, "Text", len);
00719       break;
00720    case AST_FRAME_IMAGE:
00721       ast_copy_string(ftype, "Image", len);
00722       break;
00723    case AST_FRAME_HTML:
00724       ast_copy_string(ftype, "HTML", len);
00725       break;
00726    case AST_FRAME_MODEM:
00727       ast_copy_string(ftype, "Modem", len);
00728       break;
00729    case AST_FRAME_VOICE:
00730       ast_copy_string(ftype, "Voice", len);
00731       break;
00732    case AST_FRAME_VIDEO:
00733       ast_copy_string(ftype, "Video", len);
00734       break;
00735    default:
00736       snprintf(ftype, len, "Unknown Frametype '%d'", frame_type);
00737    }
00738 }
00739 
00740 /*! Dump a frame for debugging purposes */
00741 void ast_frame_dump(const char *name, struct ast_frame *f, char *prefix)
00742 {
00743    const char noname[] = "unknown";
00744    char ftype[40] = "Unknown Frametype";
00745    char cft[80];
00746    char subclass[40] = "Unknown Subclass";
00747    char csub[80];
00748    char moreinfo[40] = "";
00749    char cn[60];
00750    char cp[40];
00751    char cmn[40];
00752 
00753    if (!name) {
00754       name = noname;
00755    }
00756 
00757    if (!f) {
00758       ast_verb(-1, "%s [ %s (NULL) ] [%s]\n",
00759          term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
00760          term_color(cft, "HANGUP", COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
00761          term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
00762       return;
00763    }
00764    /* XXX We should probably print one each of voice and video when the format changes XXX */
00765    if (f->frametype == AST_FRAME_VOICE) {
00766       return;
00767    }
00768    if (f->frametype == AST_FRAME_VIDEO) {
00769       return;
00770    }
00771 
00772    ast_frame_type2str(f->frametype, ftype, sizeof(ftype));
00773    ast_frame_subclass2str(f, subclass, sizeof(subclass), moreinfo, sizeof(moreinfo));
00774 
00775    if (!ast_strlen_zero(moreinfo))
00776       ast_verb(-1, "%s [ TYPE: %s (%d) SUBCLASS: %s (%d) '%s' ] [%s]\n",
00777              term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
00778              term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
00779              f->frametype,
00780              term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
00781              f->subclass.integer,
00782              term_color(cmn, moreinfo, COLOR_BRGREEN, COLOR_BLACK, sizeof(cmn)),
00783              term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
00784    else
00785       ast_verb(-1, "%s [ TYPE: %s (%d) SUBCLASS: %s (%d) ] [%s]\n",
00786              term_color(cp, prefix, COLOR_BRMAGENTA, COLOR_BLACK, sizeof(cp)),
00787              term_color(cft, ftype, COLOR_BRRED, COLOR_BLACK, sizeof(cft)),
00788              f->frametype,
00789              term_color(csub, subclass, COLOR_BRCYAN, COLOR_BLACK, sizeof(csub)),
00790              f->subclass.integer,
00791              term_color(cn, name, COLOR_YELLOW, COLOR_BLACK, sizeof(cn)));
00792 }
00793 
00794 int ast_parse_allow_disallow(struct ast_codec_pref *pref, struct ast_format_cap *cap, const char *list, int allowing)
00795 {
00796    int errors = 0, framems = 0, all = 0, iter_allowing;
00797    char *parse = NULL, *this = NULL, *psize = NULL;
00798    struct ast_format format;
00799 
00800    parse = ast_strdupa(list);
00801    while ((this = strsep(&parse, ","))) {
00802       iter_allowing = allowing;
00803       framems = 0;
00804       if (*this == '!') {
00805          this++;
00806          iter_allowing = !allowing;
00807       }
00808       if ((psize = strrchr(this, ':'))) {
00809          *psize++ = '\0';
00810          ast_debug(1, "Packetization for codec: %s is %s\n", this, psize);
00811          framems = atoi(psize);
00812          if (framems < 0) {
00813             framems = 0;
00814             errors++;
00815             ast_log(LOG_WARNING, "Bad packetization value for codec %s\n", this);
00816          }
00817       }
00818       all = strcasecmp(this, "all") ? 0 : 1;
00819 
00820       if (!all && !ast_getformatbyname(this, &format)) {
00821          ast_log(LOG_WARNING, "Cannot %s unknown format '%s'\n", iter_allowing ? "allow" : "disallow", this);
00822          errors++;
00823          continue;
00824       }
00825 
00826       if (cap) {
00827          if (iter_allowing) {
00828             if (all) {
00829                ast_format_cap_add_all(cap);
00830             } else {
00831                ast_format_cap_add(cap, &format);
00832             }
00833          } else {
00834             if (all) {
00835                ast_format_cap_remove_all(cap);
00836             } else {
00837                ast_format_cap_remove(cap, &format);
00838             }
00839          }
00840       }
00841 
00842       if (pref) {
00843          if (!all) {
00844             if (iter_allowing) {
00845                ast_codec_pref_append(pref, &format);
00846                ast_codec_pref_setsize(pref, &format, framems);
00847             } else {
00848                ast_codec_pref_remove(pref, &format);
00849             }
00850          } else if (!iter_allowing) {
00851             memset(pref, 0, sizeof(*pref));
00852          }
00853       }
00854    }
00855    return errors;
00856 }
00857 
00858 static int g723_len(unsigned char buf)
00859 {
00860    enum frame_type type = buf & TYPE_MASK;
00861 
00862    switch(type) {
00863    case TYPE_DONTSEND:
00864       return 0;
00865       break;
00866    case TYPE_SILENCE:
00867       return 4;
00868       break;
00869    case TYPE_HIGH:
00870       return 24;
00871       break;
00872    case TYPE_LOW:
00873       return 20;
00874       break;
00875    default:
00876       ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", type);
00877    }
00878    return -1;
00879 }
00880 
00881 static int g723_samples(unsigned char *buf, int maxlen)
00882 {
00883    int pos = 0;
00884    int samples = 0;
00885    int res;
00886    while(pos < maxlen) {
00887       res = g723_len(buf[pos]);
00888       if (res <= 0)
00889          break;
00890       samples += 240;
00891       pos += res;
00892    }
00893    return samples;
00894 }
00895 
00896 static unsigned char get_n_bits_at(unsigned char *data, int n, int bit)
00897 {
00898    int byte = bit / 8;       /* byte containing first bit */
00899    int rem = 8 - (bit % 8);  /* remaining bits in first byte */
00900    unsigned char ret = 0;
00901 
00902    if (n <= 0 || n > 8)
00903       return 0;
00904 
00905    if (rem < n) {
00906       ret = (data[byte] << (n - rem));
00907       ret |= (data[byte + 1] >> (8 - n + rem));
00908    } else {
00909       ret = (data[byte] >> (rem - n));
00910    }
00911 
00912    return (ret & (0xff >> (8 - n)));
00913 }
00914 
00915 static int speex_get_wb_sz_at(unsigned char *data, int len, int bit)
00916 {
00917    static const int SpeexWBSubModeSz[] = {
00918       4, 36, 112, 192,
00919       352, 0, 0, 0 };
00920    int off = bit;
00921    unsigned char c;
00922 
00923    /* skip up to two wideband frames */
00924    if (((len * 8 - off) >= 5) &&
00925       get_n_bits_at(data, 1, off)) {
00926       c = get_n_bits_at(data, 3, off + 1);
00927       off += SpeexWBSubModeSz[c];
00928 
00929       if (((len * 8 - off) >= 5) &&
00930          get_n_bits_at(data, 1, off)) {
00931          c = get_n_bits_at(data, 3, off + 1);
00932          off += SpeexWBSubModeSz[c];
00933 
00934          if (((len * 8 - off) >= 5) &&
00935             get_n_bits_at(data, 1, off)) {
00936             ast_log(LOG_WARNING, "Encountered corrupt speex frame; too many wideband frames in a row.\n");
00937             return -1;
00938          }
00939       }
00940 
00941    }
00942    return off - bit;
00943 }
00944 
00945 static int speex_samples(unsigned char *data, int len)
00946 {
00947    static const int SpeexSubModeSz[] = {
00948       5, 43, 119, 160,
00949       220, 300, 364, 492,
00950       79, 0, 0, 0,
00951       0, 0, 0, 0 };
00952    static const int SpeexInBandSz[] = {
00953       1, 1, 4, 4,
00954       4, 4, 4, 4,
00955       8, 8, 16, 16,
00956       32, 32, 64, 64 };
00957    int bit = 0;
00958    int cnt = 0;
00959    int off;
00960    unsigned char c;
00961 
00962    while ((len * 8 - bit) >= 5) {
00963       /* skip wideband frames */
00964       off = speex_get_wb_sz_at(data, len, bit);
00965       if (off < 0)  {
00966          ast_log(LOG_WARNING, "Had error while reading wideband frames for speex samples\n");
00967          break;
00968       }
00969       bit += off;
00970 
00971       if ((len * 8 - bit) < 5)
00972          break;
00973 
00974       /* get control bits */
00975       c = get_n_bits_at(data, 5, bit);
00976       bit += 5;
00977 
00978       if (c == 15) {
00979          /* terminator */
00980          break;
00981       } else if (c == 14) {
00982          /* in-band signal; next 4 bits contain signal id */
00983          c = get_n_bits_at(data, 4, bit);
00984          bit += 4;
00985          bit += SpeexInBandSz[c];
00986       } else if (c == 13) {
00987          /* user in-band; next 4 bits contain msg len */
00988          c = get_n_bits_at(data, 4, bit);
00989          bit += 4;
00990          /* after which it's 5-bit signal id + c bytes of data */
00991          bit += 5 + c * 8;
00992       } else if (c > 8) {
00993          /* unknown */
00994          ast_log(LOG_WARNING, "Unknown speex control frame %d\n", c);
00995          break;
00996       } else {
00997          /* skip number bits for submode (less the 5 control bits) */
00998          bit += SpeexSubModeSz[c] - 5;
00999          cnt += 160; /* new frame */
01000       }
01001    }
01002    return cnt;
01003 }
01004 
01005 int ast_codec_get_samples(struct ast_frame *f)
01006 {
01007    int samples = 0;
01008 
01009    switch (f->subclass.format.id) {
01010    case AST_FORMAT_SPEEX:
01011       samples = speex_samples(f->data.ptr, f->datalen);
01012       break;
01013    case AST_FORMAT_SPEEX16:
01014       samples = 2 * speex_samples(f->data.ptr, f->datalen);
01015       break;
01016    case AST_FORMAT_SPEEX32:
01017       samples = 4 * speex_samples(f->data.ptr, f->datalen);
01018       break;
01019    case AST_FORMAT_G723_1:
01020       samples = g723_samples(f->data.ptr, f->datalen);
01021       break;
01022    case AST_FORMAT_ILBC:
01023       samples = 240 * (f->datalen / 50);
01024       break;
01025    case AST_FORMAT_GSM:
01026       samples = 160 * (f->datalen / 33);
01027       break;
01028    case AST_FORMAT_G729A:
01029       samples = f->datalen * 8;
01030       break;
01031    case AST_FORMAT_SLINEAR:
01032    case AST_FORMAT_SLINEAR16:
01033       samples = f->datalen / 2;
01034       break;
01035    case AST_FORMAT_LPC10:
01036       /* assumes that the RTP packet contains one LPC10 frame */
01037       samples = 22 * 8;
01038       samples += (((char *)(f->data.ptr))[7] & 0x1) * 8;
01039       break;
01040    case AST_FORMAT_ULAW:
01041    case AST_FORMAT_ALAW:
01042    case AST_FORMAT_TESTLAW:
01043       samples = f->datalen;
01044       break;
01045    case AST_FORMAT_G722:
01046    case AST_FORMAT_ADPCM:
01047    case AST_FORMAT_G726:
01048    case AST_FORMAT_G726_AAL2:
01049       samples = f->datalen * 2;
01050       break;
01051    case AST_FORMAT_SIREN7:
01052       /* 16,000 samples per second at 32kbps is 4,000 bytes per second */
01053       samples = f->datalen * (16000 / 4000);
01054       break;
01055    case AST_FORMAT_SIREN14:
01056       /* 32,000 samples per second at 48kbps is 6,000 bytes per second */
01057       samples = (int) f->datalen * ((float) 32000 / 6000);
01058       break;
01059    case AST_FORMAT_G719:
01060       /* 48,000 samples per second at 64kbps is 8,000 bytes per second */
01061       samples = (int) f->datalen * ((float) 48000 / 8000);
01062       break;
01063    case AST_FORMAT_SILK:
01064       if (!(ast_format_isset(&f->subclass.format,
01065          SILK_ATTR_KEY_SAMP_RATE,
01066          SILK_ATTR_VAL_SAMP_24KHZ,
01067          AST_FORMAT_ATTR_END))) {
01068          return 480;
01069       } else if (!(ast_format_isset(&f->subclass.format,
01070          SILK_ATTR_KEY_SAMP_RATE,
01071          SILK_ATTR_VAL_SAMP_16KHZ,
01072          AST_FORMAT_ATTR_END))) {
01073          return 320;
01074       } else if (!(ast_format_isset(&f->subclass.format,
01075          SILK_ATTR_KEY_SAMP_RATE,
01076          SILK_ATTR_VAL_SAMP_12KHZ,
01077          AST_FORMAT_ATTR_END))) {
01078          return 240;
01079       } else {
01080          return 160;
01081       }
01082    case AST_FORMAT_CELT:
01083       /* TODO The assumes 20ms delivery right now, which is incorrect */
01084       samples = ast_format_rate(&f->subclass.format) / 50;
01085       break;
01086    default:
01087       ast_log(LOG_WARNING, "Unable to calculate samples for format %s\n", ast_getformatname(&f->subclass.format));
01088    }
01089    return samples;
01090 }
01091 
01092 int ast_codec_get_len(struct ast_format *format, int samples)
01093 {
01094    int len = 0;
01095 
01096    /* XXX Still need speex, and lpc10 XXX */
01097    switch(format->id) {
01098    case AST_FORMAT_G723_1:
01099       len = (samples / 240) * 20;
01100       break;
01101    case AST_FORMAT_ILBC:
01102       len = (samples / 240) * 50;
01103       break;
01104    case AST_FORMAT_GSM:
01105       len = (samples / 160) * 33;
01106       break;
01107    case AST_FORMAT_G729A:
01108       len = samples / 8;
01109       break;
01110    case AST_FORMAT_SLINEAR:
01111    case AST_FORMAT_SLINEAR16:
01112       len = samples * 2;
01113       break;
01114    case AST_FORMAT_ULAW:
01115    case AST_FORMAT_ALAW:
01116    case AST_FORMAT_TESTLAW:
01117       len = samples;
01118       break;
01119    case AST_FORMAT_G722:
01120    case AST_FORMAT_ADPCM:
01121    case AST_FORMAT_G726:
01122    case AST_FORMAT_G726_AAL2:
01123       len = samples / 2;
01124       break;
01125    case AST_FORMAT_SIREN7:
01126       /* 16,000 samples per second at 32kbps is 4,000 bytes per second */
01127       len = samples / (16000 / 4000);
01128       break;
01129    case AST_FORMAT_SIREN14:
01130       /* 32,000 samples per second at 48kbps is 6,000 bytes per second */
01131       len = (int) samples / ((float) 32000 / 6000);
01132       break;
01133    case AST_FORMAT_G719:
01134       /* 48,000 samples per second at 64kbps is 8,000 bytes per second */
01135       len = (int) samples / ((float) 48000 / 8000);
01136       break;
01137    default:
01138       ast_log(LOG_WARNING, "Unable to calculate sample length for format %s\n", ast_getformatname(format));
01139    }
01140 
01141    return len;
01142 }
01143 
01144 int ast_frame_adjust_volume(struct ast_frame *f, int adjustment)
01145 {
01146    int count;
01147    short *fdata = f->data.ptr;
01148    short adjust_value = abs(adjustment);
01149 
01150    if ((f->frametype != AST_FRAME_VOICE) || !(ast_format_is_slinear(&f->subclass.format))) {
01151       return -1;
01152    }
01153 
01154    if (!adjustment) {
01155       return 0;
01156    }
01157 
01158    for (count = 0; count < f->samples; count++) {
01159       if (adjustment > 0) {
01160          ast_slinear_saturated_multiply(&fdata[count], &adjust_value);
01161       } else if (adjustment < 0) {
01162          ast_slinear_saturated_divide(&fdata[count], &adjust_value);
01163       }
01164    }
01165 
01166    return 0;
01167 }
01168 
01169 int ast_frame_slinear_sum(struct ast_frame *f1, struct ast_frame *f2)
01170 {
01171    int count;
01172    short *data1, *data2;
01173 
01174    if ((f1->frametype != AST_FRAME_VOICE) || (f1->subclass.format.id != AST_FORMAT_SLINEAR))
01175       return -1;
01176 
01177    if ((f2->frametype != AST_FRAME_VOICE) || (f2->subclass.format.id != AST_FORMAT_SLINEAR))
01178       return -1;
01179 
01180    if (f1->samples != f2->samples)
01181       return -1;
01182 
01183    for (count = 0, data1 = f1->data.ptr, data2 = f2->data.ptr;
01184         count < f1->samples;
01185         count++, data1++, data2++)
01186       ast_slinear_saturated_add(data1, data2);
01187 
01188    return 0;
01189 }
01190 
01191 int ast_frame_clear(struct ast_frame *frame)
01192 {
01193    struct ast_frame *next;
01194 
01195    for (next = AST_LIST_NEXT(frame, frame_list);
01196        frame;
01197        frame = next, next = frame ? AST_LIST_NEXT(frame, frame_list) : NULL) {
01198       memset(frame->data.ptr, 0, frame->datalen);
01199    }
01200    return 0;
01201 }