Mon Jun 18 2012 03:55:42

Asterisk developer's documentation


translate.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, 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 Translate via the use of pseudo channels
00022  *
00023  * \author Mark Spencer <markster@digium.com> 
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 357760 $")
00029 
00030 #include <sys/time.h>
00031 #include <sys/resource.h>
00032 #include <math.h>
00033 
00034 #include "asterisk/lock.h"
00035 #include "asterisk/channel.h"
00036 #include "asterisk/translate.h"
00037 #include "asterisk/module.h"
00038 #include "asterisk/frame.h"
00039 #include "asterisk/sched.h"
00040 #include "asterisk/cli.h"
00041 #include "asterisk/term.h"
00042 
00043 #define MAX_RECALC 1000 /* max sample recalc */
00044 
00045 /*! \brief the list of translators */
00046 static AST_RWLIST_HEAD_STATIC(translators, ast_translator);
00047 
00048 
00049 /*! \brief these values indicate how a translation path will affect the sample rate
00050  *
00051  *  \note These must stay in this order.  They are ordered by most optimal selection first.
00052  */
00053 enum path_samp_change {
00054 
00055    /* Lossless Source Translation Costs */
00056 
00057    /*! [lossless -> lossless] original sampling */
00058    AST_TRANS_COST_LL_LL_ORIGSAMP = 400000,
00059    /*! [lossless -> lossy]    original sampling */
00060    AST_TRANS_COST_LL_LY_ORIGSAMP = 600000,
00061 
00062    /*! [lossless -> lossless] up sample */
00063    AST_TRANS_COST_LL_LL_UPSAMP   = 800000,
00064    /*! [lossless -> lossy]    up sample */
00065    AST_TRANS_COST_LL_LY_UPSAMP   = 825000,
00066 
00067    /*! [lossless -> lossless] down sample */
00068    AST_TRANS_COST_LL_LL_DOWNSAMP = 850000,
00069    /*! [lossless -> lossy]    down sample */
00070    AST_TRANS_COST_LL_LY_DOWNSAMP = 875000,
00071 
00072    /*! [lossless -> unknown]    unknown.
00073     * This value is for a lossless source translation
00074     * with an unknown destination and or sample rate conversion. */
00075    AST_TRANS_COST_LL_UNKNOWN     = 885000,
00076 
00077    /* Lossy Source Translation Costs */
00078 
00079    /*! [lossy -> lossless]    original sampling */
00080    AST_TRANS_COST_LY_LL_ORIGSAMP = 900000,
00081    /*! [lossy -> lossy]       original sampling */
00082    AST_TRANS_COST_LY_LY_ORIGSAMP = 915000,
00083 
00084    /*! [lossy -> lossless]    up sample */
00085    AST_TRANS_COST_LY_LL_UPSAMP   = 930000,
00086    /*! [lossy -> lossy]       up sample */
00087    AST_TRANS_COST_LY_LY_UPSAMP   = 945000,
00088 
00089    /*! [lossy -> lossless]    down sample */
00090    AST_TRANS_COST_LY_LL_DOWNSAMP = 960000,
00091    /*! [lossy -> lossy]       down sample */
00092    AST_TRANS_COST_LY_LY_DOWNSAMP = 975000,
00093 
00094    /*! [lossy -> unknown]    unknown.
00095     * This value is for a lossy source translation
00096     * with an unknown destination and or sample rate conversion. */
00097    AST_TRANS_COST_LY_UNKNOWN     = 985000,
00098 };
00099 
00100 struct translator_path {
00101    struct ast_translator *step;  /*!< Next step translator */
00102    unsigned int cost;      /*!< Complete cost to destination */
00103    unsigned int multistep;    /*!< Multiple conversions required for this translation */
00104    enum path_samp_change rate_change; /*!< does this path require a sample rate change, if so what kind. */
00105 };
00106 
00107 /*! \brief a matrix that, for any pair of supported formats,
00108  * indicates the total cost of translation and the first step.
00109  * The full path can be reconstricted iterating on the matrix
00110  * until step->dstfmt == desired_format.
00111  *
00112  * Array indexes are 'src' and 'dest', in that order.
00113  *
00114  * Note: the lock in the 'translators' list is also used to protect
00115  * this structure.
00116  */
00117 static struct translator_path tr_matrix[MAX_FORMAT][MAX_FORMAT];
00118 
00119 /*! \todo
00120  * TODO: sample frames for each supported input format.
00121  * We build this on the fly, by taking an SLIN frame and using
00122  * the existing converter to play with it.
00123  */
00124 
00125 /*! \brief returns the index of the lowest bit set */
00126 static force_inline int powerof(format_t d)
00127 {
00128    int x = ffsll(d);
00129 
00130    if (x)
00131       return x - 1;
00132 
00133    ast_log(LOG_WARNING, "No bits set? %llu\n", (unsigned long long) d);
00134 
00135    return -1;
00136 }
00137 
00138 /*
00139  * wrappers around the translator routines.
00140  */
00141 
00142 /*!
00143  * \brief Allocate the descriptor, required outbuf space,
00144  * and possibly desc.
00145  */
00146 static void *newpvt(struct ast_translator *t)
00147 {
00148    struct ast_trans_pvt *pvt;
00149    int len;
00150    char *ofs;
00151 
00152    /*
00153     * compute the required size adding private descriptor,
00154     * buffer, AST_FRIENDLY_OFFSET.
00155     */
00156    len = sizeof(*pvt) + t->desc_size;
00157    if (t->buf_size)
00158       len += AST_FRIENDLY_OFFSET + t->buf_size;
00159    pvt = ast_calloc(1, len);
00160    if (!pvt)
00161       return NULL;
00162    pvt->t = t;
00163    ofs = (char *)(pvt + 1);   /* pointer to data space */
00164    if (t->desc_size) {     /* first comes the descriptor */
00165       pvt->pvt = ofs;
00166       ofs += t->desc_size;
00167    }
00168    if (t->buf_size)     /* finally buffer and header */
00169       pvt->outbuf.c = ofs + AST_FRIENDLY_OFFSET;
00170    /* call local init routine, if present */
00171    if (t->newpvt && t->newpvt(pvt)) {
00172       ast_free(pvt);
00173       return NULL;
00174    }
00175    ast_module_ref(t->module);
00176    return pvt;
00177 }
00178 
00179 static void destroy(struct ast_trans_pvt *pvt)
00180 {
00181    struct ast_translator *t = pvt->t;
00182 
00183    if (t->destroy)
00184       t->destroy(pvt);
00185    ast_free(pvt);
00186    ast_module_unref(t->module);
00187 }
00188 
00189 /*! \brief framein wrapper, deals with bound checks.  */
00190 static int framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
00191 {
00192    int ret;
00193    int samples = pvt->samples;   /* initial value */
00194    
00195    /* Copy the last in jb timing info to the pvt */
00196    ast_copy_flags(&pvt->f, f, AST_FRFLAG_HAS_TIMING_INFO);
00197    pvt->f.ts = f->ts;
00198    pvt->f.len = f->len;
00199    pvt->f.seqno = f->seqno;
00200 
00201    if (f->samples == 0) {
00202       ast_log(LOG_WARNING, "no samples for %s\n", pvt->t->name);
00203    }
00204    if (pvt->t->buffer_samples) { /* do not pass empty frames to callback */
00205       if (f->datalen == 0) { /* perform native PLC if available */
00206          /* If the codec has native PLC, then do that */
00207          if (!pvt->t->native_plc)
00208             return 0;
00209       }
00210       if (pvt->samples + f->samples > pvt->t->buffer_samples) {
00211          ast_log(LOG_WARNING, "Out of buffer space\n");
00212          return -1;
00213       }
00214    }
00215    /* we require a framein routine, wouldn't know how to do
00216     * it otherwise.
00217     */
00218    ret = pvt->t->framein(pvt, f);
00219    /* diagnostic ... */
00220    if (pvt->samples == samples)
00221       ast_log(LOG_WARNING, "%s did not update samples %d\n",
00222          pvt->t->name, pvt->samples);
00223    return ret;
00224 }
00225 
00226 /*! \brief generic frameout routine.
00227  * If samples and datalen are 0, take whatever is in pvt
00228  * and reset them, otherwise take the values in the caller and
00229  * leave alone the pvt values.
00230  */
00231 struct ast_frame *ast_trans_frameout(struct ast_trans_pvt *pvt,
00232    int datalen, int samples)
00233 {
00234    struct ast_frame *f = &pvt->f;
00235 
00236    if (samples)
00237       f->samples = samples;
00238    else {
00239       if (pvt->samples == 0)
00240          return NULL;
00241       f->samples = pvt->samples;
00242       pvt->samples = 0;
00243    }
00244    if (datalen)
00245       f->datalen = datalen;
00246    else {
00247       f->datalen = pvt->datalen;
00248       pvt->datalen = 0;
00249    }
00250 
00251    f->frametype = AST_FRAME_VOICE;
00252    f->subclass.codec = 1LL << (pvt->t->dstfmt);
00253    f->mallocd = 0;
00254    f->offset = AST_FRIENDLY_OFFSET;
00255    f->src = pvt->t->name;
00256    f->data.ptr = pvt->outbuf.c;
00257 
00258    return ast_frisolate(f);
00259 }
00260 
00261 static struct ast_frame *default_frameout(struct ast_trans_pvt *pvt)
00262 {
00263    return ast_trans_frameout(pvt, 0, 0);
00264 }
00265 
00266 /* end of callback wrappers and helpers */
00267 
00268 void ast_translator_free_path(struct ast_trans_pvt *p)
00269 {
00270    struct ast_trans_pvt *pn = p;
00271    while ( (p = pn) ) {
00272       pn = p->next;
00273       destroy(p);
00274    }
00275 }
00276 
00277 /*! \brief Build a chain of translators based upon the given source and dest formats */
00278 struct ast_trans_pvt *ast_translator_build_path(format_t dest, format_t source)
00279 {
00280    struct ast_trans_pvt *head = NULL, *tail = NULL;
00281    
00282    source = powerof(source);
00283    dest = powerof(dest);
00284 
00285    if (source == -1 || dest == -1) {
00286       ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", source == -1 ? "starting" : "ending");
00287       return NULL;
00288    }
00289 
00290    AST_RWLIST_RDLOCK(&translators);
00291 
00292    while (source != dest) {
00293       struct ast_trans_pvt *cur;
00294       struct ast_translator *t = tr_matrix[source][dest].step;
00295       if (!t) {
00296          ast_log(LOG_WARNING, "No translator path from %s to %s\n", 
00297             ast_getformatname(source), ast_getformatname(dest));
00298          AST_RWLIST_UNLOCK(&translators);
00299          return NULL;
00300       }
00301       if (!(cur = newpvt(t))) {
00302          ast_log(LOG_WARNING, "Failed to build translator step from %s to %s\n",
00303             ast_getformatname(source), ast_getformatname(dest));
00304          if (head)
00305             ast_translator_free_path(head);  
00306          AST_RWLIST_UNLOCK(&translators);
00307          return NULL;
00308       }
00309       if (!head)
00310          head = cur;
00311       else
00312          tail->next = cur;
00313       tail = cur;
00314       cur->nextin = cur->nextout = ast_tv(0, 0);
00315       /* Keep going if this isn't the final destination */
00316       source = cur->t->dstfmt;
00317    }
00318 
00319    AST_RWLIST_UNLOCK(&translators);
00320    return head;
00321 }
00322 
00323 /*! \brief do the actual translation */
00324 struct ast_frame *ast_translate(struct ast_trans_pvt *path, struct ast_frame *f, int consume)
00325 {
00326    struct ast_trans_pvt *p = path;
00327    struct ast_frame *out = f;
00328    struct timeval delivery;
00329    int has_timing_info;
00330    long ts;
00331    long len;
00332    int seqno;
00333 
00334    has_timing_info = ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO);
00335    ts = f->ts;
00336    len = f->len;
00337    seqno = f->seqno;
00338 
00339    /* XXX hmmm... check this below */
00340    if (!ast_tvzero(f->delivery)) {
00341       if (!ast_tvzero(path->nextin)) {
00342          /* Make sure this is in line with what we were expecting */
00343          if (!ast_tveq(path->nextin, f->delivery)) {
00344             /* The time has changed between what we expected and this
00345                most recent time on the new packet.  If we have a
00346                valid prediction adjust our output time appropriately */
00347             if (!ast_tvzero(path->nextout)) {
00348                path->nextout = ast_tvadd(path->nextout,
00349                           ast_tvsub(f->delivery, path->nextin));
00350             }
00351             path->nextin = f->delivery;
00352          }
00353       } else {
00354          /* This is our first pass.  Make sure the timing looks good */
00355          path->nextin = f->delivery;
00356          path->nextout = f->delivery;
00357       }
00358       /* Predict next incoming sample */
00359       path->nextin = ast_tvadd(path->nextin, ast_samp2tv(f->samples, ast_format_rate(f->subclass.codec)));
00360    }
00361    delivery = f->delivery;
00362    for ( ; out && p ; p = p->next) {
00363       framein(p, out);
00364       if (out != f)
00365          ast_frfree(out);
00366       out = p->t->frameout(p);
00367    }
00368    if (consume)
00369       ast_frfree(f);
00370    if (out == NULL)
00371       return NULL;
00372    /* we have a frame, play with times */
00373    if (!ast_tvzero(delivery)) {
00374       /* Regenerate prediction after a discontinuity */
00375       if (ast_tvzero(path->nextout))
00376          path->nextout = ast_tvnow();
00377 
00378       /* Use next predicted outgoing timestamp */
00379       out->delivery = path->nextout;
00380       
00381       /* Predict next outgoing timestamp from samples in this
00382          frame. */
00383       path->nextout = ast_tvadd(path->nextout, ast_samp2tv(out->samples, ast_format_rate(out->subclass.codec)));
00384    } else {
00385       out->delivery = ast_tv(0, 0);
00386       ast_set2_flag(out, has_timing_info, AST_FRFLAG_HAS_TIMING_INFO);
00387       if (has_timing_info) {
00388          out->ts = ts;
00389          out->len = len;
00390          out->seqno = seqno;
00391       }
00392    }
00393    /* Invalidate prediction if we're entering a silence period */
00394    if (out->frametype == AST_FRAME_CNG)
00395       path->nextout = ast_tv(0, 0);
00396    return out;
00397 }
00398 
00399 /*! \brief compute the cost of a single translation step */
00400 static void calc_cost(struct ast_translator *t, int seconds)
00401 {
00402    int num_samples = 0;
00403    struct ast_trans_pvt *pvt;
00404    struct rusage start;
00405    struct rusage end;
00406    int cost;
00407    int out_rate = ast_format_rate(t->dstfmt);
00408 
00409    if (!seconds)
00410       seconds = 1;
00411    
00412    /* If they don't make samples, give them a terrible score */
00413    if (!t->sample) {
00414       ast_log(LOG_WARNING, "Translator '%s' does not produce sample frames.\n", t->name);
00415       t->cost = 999999;
00416       return;
00417    }
00418 
00419    pvt = newpvt(t);
00420    if (!pvt) {
00421       ast_log(LOG_WARNING, "Translator '%s' appears to be broken and will probably fail.\n", t->name);
00422       t->cost = 999999;
00423       return;
00424    }
00425 
00426    getrusage(RUSAGE_SELF, &start);
00427 
00428    /* Call the encoder until we've processed the required number of samples */
00429    while (num_samples < seconds * out_rate) {
00430       struct ast_frame *f = t->sample();
00431       if (!f) {
00432          ast_log(LOG_WARNING, "Translator '%s' failed to produce a sample frame.\n", t->name);
00433          destroy(pvt);
00434          t->cost = 999999;
00435          return;
00436       }
00437       framein(pvt, f);
00438       ast_frfree(f);
00439       while ((f = t->frameout(pvt))) {
00440          num_samples += f->samples;
00441          ast_frfree(f);
00442       }
00443    }
00444 
00445    getrusage(RUSAGE_SELF, &end);
00446 
00447    cost = ((end.ru_utime.tv_sec - start.ru_utime.tv_sec) * 1000000) + end.ru_utime.tv_usec - start.ru_utime.tv_usec;
00448    cost += ((end.ru_stime.tv_sec - start.ru_stime.tv_sec) * 1000000) + end.ru_stime.tv_usec - start.ru_stime.tv_usec;
00449 
00450    destroy(pvt);
00451 
00452    t->cost = cost / seconds;
00453 
00454    if (!t->cost)
00455       t->cost = 1;
00456 }
00457 
00458 static enum path_samp_change get_rate_change_result(format_t src, format_t dst)
00459 {
00460    int src_ll = src == AST_FORMAT_SLINEAR || src == AST_FORMAT_SLINEAR16;
00461    int dst_ll = dst == AST_FORMAT_SLINEAR || src == AST_FORMAT_SLINEAR16;
00462    int src_rate = ast_format_rate(src);
00463    int dst_rate = ast_format_rate(dst);
00464 
00465    if (src_ll) {
00466       if (dst_ll && (src_rate == dst_rate)) {
00467          return AST_TRANS_COST_LL_LL_ORIGSAMP;
00468       } else if (!dst_ll && (src_rate == dst_rate)) {
00469          return AST_TRANS_COST_LL_LY_ORIGSAMP;
00470       } else if (dst_ll && (src_rate < dst_rate)) {
00471          return AST_TRANS_COST_LL_LL_UPSAMP;
00472       } else if (!dst_ll && (src_rate < dst_rate)) {
00473          return AST_TRANS_COST_LL_LY_UPSAMP;
00474       } else if (dst_ll && (src_rate > dst_rate)) {
00475          return AST_TRANS_COST_LL_LL_DOWNSAMP;
00476       } else if (!dst_ll && (src_rate > dst_rate)) {
00477          return AST_TRANS_COST_LL_LY_DOWNSAMP;
00478       } else {
00479          return AST_TRANS_COST_LL_UNKNOWN;
00480       }
00481    } else {
00482       if (dst_ll && (src_rate == dst_rate)) {
00483          return AST_TRANS_COST_LY_LL_ORIGSAMP;
00484       } else if (!dst_ll && (src_rate == dst_rate)) {
00485          return AST_TRANS_COST_LY_LY_ORIGSAMP;
00486       } else if (dst_ll && (src_rate < dst_rate)) {
00487          return AST_TRANS_COST_LY_LL_UPSAMP;
00488       } else if (!dst_ll && (src_rate < dst_rate)) {
00489          return AST_TRANS_COST_LY_LY_UPSAMP;
00490       } else if (dst_ll && (src_rate > dst_rate)) {
00491          return AST_TRANS_COST_LY_LL_DOWNSAMP;
00492       } else if (!dst_ll && (src_rate > dst_rate)) {
00493          return AST_TRANS_COST_LY_LY_DOWNSAMP;
00494       } else {
00495          return AST_TRANS_COST_LY_UNKNOWN;
00496       }
00497    }
00498 }
00499 
00500 /*!
00501  * \brief rebuild a translation matrix.
00502  * \note This function expects the list of translators to be locked
00503 */
00504 static void rebuild_matrix(int samples)
00505 {
00506    struct ast_translator *t;
00507    int new_rate_change;
00508    int newcost;
00509    int x;      /* source format index */
00510    int y;      /* intermediate format index */
00511    int z;      /* destination format index */
00512 
00513    ast_debug(1, "Resetting translation matrix\n");
00514 
00515    memset(tr_matrix, '\0', sizeof(tr_matrix));
00516 
00517    /* first, compute all direct costs */
00518    AST_RWLIST_TRAVERSE(&translators, t, list) {
00519       if (!t->active)
00520          continue;
00521 
00522       x = t->srcfmt;
00523       z = t->dstfmt;
00524 
00525       if (samples)
00526          calc_cost(t, samples);
00527 
00528       new_rate_change = get_rate_change_result(1LL << t->srcfmt, 1LL << t->dstfmt);
00529 
00530       /* this translator is the best choice if any of the below are true.
00531        * 1. no translation path is set between x and z yet.
00532        * 2. the new translation costs less and sample rate is no worse than old one. 
00533        * 3. the new translation has a better sample rate conversion than the old one.
00534        */
00535       if (!tr_matrix[x][z].step ||
00536          ((t->cost < tr_matrix[x][z].cost) && (new_rate_change <= tr_matrix[x][z].rate_change)) ||
00537          (new_rate_change < tr_matrix[x][z].rate_change)) {
00538 
00539          tr_matrix[x][z].step = t;
00540          tr_matrix[x][z].cost = t->cost;
00541          tr_matrix[x][z].rate_change = new_rate_change;
00542       }
00543    }
00544 
00545    /*
00546     * For each triple x, y, z of distinct formats, check if there is
00547     * a path from x to z through y which is cheaper than what is
00548     * currently known, and in case, update the matrix.
00549     * Repeat until the matrix is stable.
00550     */
00551    for (;;) {
00552       int changed = 0;
00553       int better_choice = 0;
00554       for (x = 0; x < MAX_FORMAT; x++) {      /* source format */
00555          for (y = 0; y < MAX_FORMAT; y++) {    /* intermediate format */
00556             if (x == y)                     /* skip ourselves */
00557                continue;
00558             for (z = 0; z < MAX_FORMAT; z++) {  /* dst format */
00559                if (z == x || z == y)       /* skip null conversions */
00560                   continue;
00561                if (!tr_matrix[x][y].step)  /* no path from x to y */
00562                   continue;
00563                if (!tr_matrix[y][z].step)  /* no path from y to z */
00564                   continue;
00565 
00566                /* Does x->y->z result in a less optimal sample rate change?
00567                 * Never downgrade the sample rate conversion quality regardless
00568                 * of any cost improvements */
00569                if (tr_matrix[x][z].step &&
00570                   ((tr_matrix[x][z].rate_change < tr_matrix[x][y].rate_change) ||
00571                   (tr_matrix[x][z].rate_change < tr_matrix[y][z].rate_change))) {
00572                   continue;
00573                }
00574 
00575                /* is x->y->z a better sample rate confersion that the current x->z? */
00576                new_rate_change = tr_matrix[x][y].rate_change + tr_matrix[y][z].rate_change;
00577 
00578                /* calculate cost from x->y->z */
00579                newcost = tr_matrix[x][y].cost + tr_matrix[y][z].cost;
00580 
00581                /* Is x->y->z a better choice than x->z?
00582                 * There are three conditions for x->y->z to be a better choice than x->z
00583                 * 1. if there is no step directly between x->z then x->y->z is the best and only current option.
00584                 * 2. if x->y->z results in a more optimal sample rate conversion. */
00585                if (!tr_matrix[x][z].step) {
00586                   better_choice = 1;
00587                } else if (new_rate_change < tr_matrix[x][z].rate_change) {
00588                   better_choice = 1;
00589                } else {
00590                   better_choice = 0;
00591                }
00592 
00593                if (!better_choice) {
00594                   continue;
00595                }
00596                /* ok, we can get from x to z via y with a cost that
00597                   is the sum of the transition from x to y and from y to z */
00598                tr_matrix[x][z].step = tr_matrix[x][y].step;
00599                tr_matrix[x][z].cost = newcost;
00600                tr_matrix[x][z].multistep = 1;
00601 
00602                /* now calculate what kind of sample rate change is required for this multi-step path
00603                 * 
00604                 * if both paths require a change in rate, and they are not in the same direction
00605                 * then this is a up sample down sample conversion scenario. */
00606                tr_matrix[x][z].rate_change = tr_matrix[x][y].rate_change + tr_matrix[y][z].rate_change;
00607 
00608                ast_debug(3, "Discovered %d cost path from %s to %s, via %s\n", tr_matrix[x][z].cost,
00609                     ast_getformatname(1LL << x), ast_getformatname(1LL << z), ast_getformatname(1LL << y));
00610                changed++;
00611             }
00612          }
00613       }
00614       if (!changed)
00615          break;
00616    }
00617 }
00618 
00619 const char *ast_translate_path_to_str(struct ast_trans_pvt *p, struct ast_str **str)
00620 {
00621    struct ast_trans_pvt *pn = p;
00622 
00623    if (!p || !p->t) {
00624       return "";
00625    }
00626 
00627    ast_str_set(str, 0, "%s", ast_getformatname(1LL << p->t->srcfmt));
00628 
00629    while ( (p = pn) ) {
00630       pn = p->next;
00631       ast_str_append(str, 0, "->%s", ast_getformatname(1LL << p->t->dstfmt));
00632    }
00633 
00634    return ast_str_buffer(*str);
00635 }
00636 
00637 static char *complete_trans_path_choice(const char *line, const char *word, int pos, int state)
00638 {
00639    int which = 0;
00640    int wordlen = strlen(word);
00641    int i;
00642    char *ret = NULL;
00643    size_t len = 0;
00644    const struct ast_format_list *format_list = ast_get_format_list(&len);
00645 
00646    for (i = 0; i < len; i++) {
00647       if (!(format_list[i].bits & AST_FORMAT_AUDIO_MASK)) {
00648          continue;
00649       }
00650       if (!strncasecmp(word, format_list[i].name, wordlen) && ++which > state) {
00651          ret = ast_strdup(format_list[i].name);
00652          break;
00653       }
00654    }
00655    return ret;
00656 }
00657 
00658 static char *handle_cli_core_show_translation(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00659 {
00660 #define SHOW_TRANS 64
00661    static const char * const option1[] = { "recalc", "paths", NULL };
00662    int x, y, z;
00663    int curlen = 0, longest = 0, magnitude[SHOW_TRANS] = { 0, };
00664 
00665    switch (cmd) {
00666    case CLI_INIT:
00667       e->command = "core show translation";
00668       e->usage =
00669          "Usage: 'core show translation' can be used in two ways.\n"
00670          "       1. 'core show translation [recalc [<recalc seconds>]]\n"
00671          "          Displays known codec translators and the cost associated\n"
00672          "          with each conversion.  If the argument 'recalc' is supplied along\n"
00673          "          with optional number of seconds to test a new test will be performed\n"
00674          "          as the chart is being displayed.\n"
00675          "       2. 'core show translation paths [codec]'\n"
00676          "           This will display all the translation paths associated with a codec\n";
00677       return NULL;
00678    case CLI_GENERATE:
00679       if (a->pos == 3) {
00680          return ast_cli_complete(a->word, option1, a->n);
00681       }
00682       if (a->pos == 4 && !strcasecmp(a->argv[3], option1[1])) {
00683          return complete_trans_path_choice(a->line, a->word, a->pos, a->n);
00684       }
00685       return NULL;
00686    }
00687 
00688    if (a->argc > 5)
00689       return CLI_SHOWUSAGE;
00690 
00691    if (a->argv[3] && !strcasecmp(a->argv[3], option1[1]) && a->argc == 5) {
00692       format_t input_src = 0;
00693       format_t src = 0;
00694       size_t len = 0;
00695       int dst;
00696       int i;
00697       const struct ast_format_list *format_list = ast_get_format_list(&len);
00698       struct ast_str *str = ast_str_alloca(256);
00699       struct ast_translator *step;
00700 
00701       for (i = 0; i < len; i++) {
00702          if (!(format_list[i].bits & AST_FORMAT_AUDIO_MASK)) {
00703             continue;
00704          }
00705          if (!strncasecmp(format_list[i].name, a->argv[4], strlen(format_list[i].name))) {
00706             input_src = format_list[i].bits;
00707          }
00708       }
00709 
00710       if (!input_src) {
00711          ast_cli(a->fd, "Source codec \"%s\" is not found.\n", a->argv[4]);
00712          return CLI_FAILURE;
00713       }
00714 
00715       AST_RWLIST_RDLOCK(&translators);
00716       ast_cli(a->fd, "--- Translation paths SRC Codec \"%s\" sample rate %d ---\n", a->argv[4], ast_format_rate(input_src));
00717       for (i = 0; i < len; i++) {
00718          if (!(format_list[i].bits & AST_FORMAT_AUDIO_MASK) || (format_list[i].bits == input_src)) {
00719             continue;
00720          }
00721          dst = powerof(format_list[i].bits);
00722          src = powerof(input_src);
00723          ast_str_reset(str);
00724          if (tr_matrix[src][dst].step) {
00725             ast_str_append(&str, 0, "%s", ast_getformatname(1LL << tr_matrix[src][dst].step->srcfmt));
00726             while (src != dst) {
00727                step = tr_matrix[src][dst].step;
00728                if (!step) {
00729                   ast_str_reset(str);
00730                   break;
00731                }
00732                ast_str_append(&str, 0, "->%s", ast_getformatname(1LL << step->dstfmt));
00733                src = step->dstfmt;
00734             }
00735          }
00736 
00737          if (ast_strlen_zero(ast_str_buffer(str))) {
00738             ast_str_set(&str, 0, "No Translation Path");
00739          }
00740 
00741          ast_cli(a->fd, "\t%-10.10s To %-10.10s: %-60.60s\n", a->argv[4], format_list[i].name, ast_str_buffer(str));
00742       }
00743       AST_RWLIST_UNLOCK(&translators);
00744 
00745       return CLI_SUCCESS;
00746    } else if (a->argv[3] && !strcasecmp(a->argv[3], "recalc")) {
00747       z = a->argv[4] ? atoi(a->argv[4]) : 1;
00748 
00749       if (z <= 0) {
00750          ast_cli(a->fd, "         Recalc must be greater than 0.  Defaulting to 1.\n");
00751          z = 1;
00752       }
00753 
00754       if (z > MAX_RECALC) {
00755          ast_cli(a->fd, "         Maximum limit of recalc exceeded by %d, truncating value to %d\n", z - MAX_RECALC, MAX_RECALC);
00756          z = MAX_RECALC;
00757       }
00758       ast_cli(a->fd, "         Recalculating Codec Translation (number of sample seconds: %d)\n\n", z);
00759       AST_RWLIST_WRLOCK(&translators);
00760       rebuild_matrix(z);
00761       AST_RWLIST_UNLOCK(&translators);
00762    } else if (a->argc > 3)
00763       return CLI_SHOWUSAGE;
00764 
00765    AST_RWLIST_RDLOCK(&translators);
00766 
00767    ast_cli(a->fd, "         Translation times between formats (in microseconds) for one second of data\n");
00768    ast_cli(a->fd, "          Source Format (Rows) Destination Format (Columns)\n\n");
00769    /* Get the length of the longest (usable?) codec name, so we know how wide the left side should be */
00770    for (x = 0; x < SHOW_TRANS; x++) {
00771       /* translation only applies to audio right now. */
00772       if (!(AST_FORMAT_AUDIO_MASK & (1LL << (x))))
00773          continue;
00774       curlen = strlen(ast_getformatname(1LL << (x)));
00775       if (curlen > longest)
00776          longest = curlen;
00777       for (y = 0; y < SHOW_TRANS; y++) {
00778          if (!(AST_FORMAT_AUDIO_MASK & (1LL << (y))))
00779             continue;
00780          if (tr_matrix[x][y].cost > pow(10, magnitude[x])) {
00781             magnitude[y] = floor(log10(tr_matrix[x][y].cost));
00782          }
00783       }
00784    }
00785    for (x = -1; x < SHOW_TRANS; x++) {
00786       struct ast_str *out = ast_str_alloca(256);
00787       /* translation only applies to audio right now. */
00788       if (x >= 0 && !(AST_FORMAT_AUDIO_MASK & (1LL << (x))))
00789          continue;
00790       /*Go ahead and move to next iteration if dealing with an unknown codec*/
00791       if(x >= 0 && !strcmp(ast_getformatname(1LL << (x)), "unknown"))
00792          continue;
00793       ast_str_set(&out, -1, " ");
00794       for (y = -1; y < SHOW_TRANS; y++) {
00795          /* translation only applies to audio right now. */
00796          if (y >= 0 && !(AST_FORMAT_AUDIO_MASK & (1LL << (y))))
00797             continue;
00798          /*Go ahead and move to next iteration if dealing with an unknown codec*/
00799          if (y >= 0 && !strcmp(ast_getformatname(1LL << (y)), "unknown"))
00800             continue;
00801          if (y >= 0)
00802             curlen = strlen(ast_getformatname(1LL << (y)));
00803          if (y >= 0 && magnitude[y] + 1 > curlen) {
00804             curlen = magnitude[y] + 1;
00805          }
00806          if (curlen < 5)
00807             curlen = 5;
00808          if (x >= 0 && y >= 0 && tr_matrix[x][y].step) {
00809             /* Actual codec output */
00810             ast_str_append(&out, -1, "%*d", curlen + 1, tr_matrix[x][y].cost);
00811          } else if (x == -1 && y >= 0) {
00812             /* Top row - use a dynamic size */
00813             ast_str_append(&out, -1, "%*s", curlen + 1, ast_getformatname(1LL << (y)) );
00814          } else if (y == -1 && x >= 0) {
00815             /* Left column - use a static size. */
00816             ast_str_append(&out, -1, "%*s", longest, ast_getformatname(1LL << (x)) );
00817          } else if (x >= 0 && y >= 0) {
00818             /* Codec not supported */
00819             ast_str_append(&out, -1, "%*s", curlen + 1, "-");
00820          } else {
00821             /* Upper left hand corner */
00822             ast_str_append(&out, -1, "%*s", longest, "");
00823          }
00824       }
00825       ast_str_append(&out, -1, "\n");
00826       ast_cli(a->fd, "%s", ast_str_buffer(out));
00827    }
00828    AST_RWLIST_UNLOCK(&translators);
00829    return CLI_SUCCESS;
00830 }
00831 
00832 static struct ast_cli_entry cli_translate[] = {
00833    AST_CLI_DEFINE(handle_cli_core_show_translation, "Display translation matrix")
00834 };
00835 
00836 /*! \brief register codec translator */
00837 int __ast_register_translator(struct ast_translator *t, struct ast_module *mod)
00838 {
00839    static int added_cli = 0;
00840    struct ast_translator *u;
00841    char tmp[80];
00842 
00843    if (!mod) {
00844       ast_log(LOG_WARNING, "Missing module pointer, you need to supply one\n");
00845       return -1;
00846    }
00847 
00848    if (!t->buf_size) {
00849       ast_log(LOG_WARNING, "empty buf size, you need to supply one\n");
00850       return -1;
00851    }
00852 
00853    t->module = mod;
00854 
00855    t->srcfmt = powerof(t->srcfmt);
00856    t->dstfmt = powerof(t->dstfmt);
00857    t->active = 1;
00858 
00859    if (t->srcfmt == -1 || t->dstfmt == -1) {
00860       ast_log(LOG_WARNING, "Invalid translator path: (%s codec is not valid)\n", t->srcfmt == -1 ? "starting" : "ending");
00861       return -1;
00862    }
00863    if (t->srcfmt >= MAX_FORMAT) {
00864       ast_log(LOG_WARNING, "Source format %s is larger than MAX_FORMAT\n", ast_getformatname(t->srcfmt));
00865       return -1;
00866    }
00867 
00868    if (t->dstfmt >= MAX_FORMAT) {
00869       ast_log(LOG_WARNING, "Destination format %s is larger than MAX_FORMAT\n", ast_getformatname(t->dstfmt));
00870       return -1;
00871    }
00872 
00873    if (t->buf_size) {
00874       /*
00875        * Align buf_size properly, rounding up to the machine-specific
00876        * alignment for pointers.
00877        */
00878       struct _test_align { void *a, *b; } p;
00879       int align = (char *)&p.b - (char *)&p.a;
00880 
00881       t->buf_size = ((t->buf_size + align - 1) / align) * align;
00882    }
00883 
00884    if (t->frameout == NULL)
00885       t->frameout = default_frameout;
00886   
00887    calc_cost(t, 1);
00888 
00889    ast_verb(2, "Registered translator '%s' from format %s to %s, cost %d\n",
00890              term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)),
00891              ast_getformatname(1LL << t->srcfmt), ast_getformatname(1LL << t->dstfmt), t->cost);
00892 
00893    if (!added_cli) {
00894       ast_cli_register_multiple(cli_translate, ARRAY_LEN(cli_translate));
00895       added_cli++;
00896    }
00897 
00898    AST_RWLIST_WRLOCK(&translators);
00899 
00900    /* find any existing translators that provide this same srcfmt/dstfmt,
00901       and put this one in order based on cost */
00902    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
00903       if ((u->srcfmt == t->srcfmt) &&
00904           (u->dstfmt == t->dstfmt) &&
00905           (u->cost > t->cost)) {
00906          AST_RWLIST_INSERT_BEFORE_CURRENT(t, list);
00907          t = NULL;
00908          break;
00909       }
00910    }
00911    AST_RWLIST_TRAVERSE_SAFE_END;
00912 
00913    /* if no existing translator was found for this format combination,
00914       add it to the beginning of the list */
00915    if (t)
00916       AST_RWLIST_INSERT_HEAD(&translators, t, list);
00917 
00918    rebuild_matrix(0);
00919 
00920    AST_RWLIST_UNLOCK(&translators);
00921 
00922    return 0;
00923 }
00924 
00925 /*! \brief unregister codec translator */
00926 int ast_unregister_translator(struct ast_translator *t)
00927 {
00928    char tmp[80];
00929    struct ast_translator *u;
00930    int found = 0;
00931 
00932    AST_RWLIST_WRLOCK(&translators);
00933    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&translators, u, list) {
00934       if (u == t) {
00935          AST_RWLIST_REMOVE_CURRENT(list);
00936          ast_verb(2, "Unregistered translator '%s' from format %s to %s\n", term_color(tmp, t->name, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp)), ast_getformatname(1LL << t->srcfmt), ast_getformatname(1LL << t->dstfmt));
00937          found = 1;
00938          break;
00939       }
00940    }
00941    AST_RWLIST_TRAVERSE_SAFE_END;
00942 
00943    if (found)
00944       rebuild_matrix(0);
00945 
00946    AST_RWLIST_UNLOCK(&translators);
00947 
00948    return (u ? 0 : -1);
00949 }
00950 
00951 void ast_translator_activate(struct ast_translator *t)
00952 {
00953    AST_RWLIST_WRLOCK(&translators);
00954    t->active = 1;
00955    rebuild_matrix(0);
00956    AST_RWLIST_UNLOCK(&translators);
00957 }
00958 
00959 void ast_translator_deactivate(struct ast_translator *t)
00960 {
00961    AST_RWLIST_WRLOCK(&translators);
00962    t->active = 0;
00963    rebuild_matrix(0);
00964    AST_RWLIST_UNLOCK(&translators);
00965 }
00966 
00967 /*! \brief Calculate our best translator source format, given costs, and a desired destination */
00968 format_t ast_translator_best_choice(format_t *dst, format_t *srcs)
00969 {
00970    int x,y;
00971    int better = 0;
00972    int besttime = INT_MAX;
00973    int beststeps = INT_MAX;
00974    unsigned int best_rate_change = INT_MAX;
00975    format_t best = -1;
00976    format_t bestdst = 0;
00977    format_t cur, cursrc;
00978    format_t common = ((*dst) & (*srcs)) & AST_FORMAT_AUDIO_MASK;  /* are there common formats ? */
00979 
00980    if (common) { /* yes, pick one and return */
00981       for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
00982          if (!(cur & common)) {
00983             continue;
00984          }
00985 
00986          /* We are guaranteed to find one common format. */
00987          if (best == -1) {
00988             best = cur;
00989             continue;
00990          }
00991          /* If there are multiple common formats, pick the one with the highest sample rate */
00992          if (ast_format_rate(best) < ast_format_rate(cur)) {
00993             best = cur;
00994             continue;
00995          }
00996       }
00997       /* We are done, this is a common format to both. */
00998       *srcs = *dst = best;
00999       return 0;
01000    } else {      /* No, we will need to translate */
01001       AST_RWLIST_RDLOCK(&translators);
01002       for (cur = 1, y = 0; y <= MAX_AUDIO_FORMAT; cur <<= 1, y++) {
01003          if (! (cur & *dst)) {
01004             continue;
01005          }
01006          for (cursrc = 1, x = 0; x <= MAX_AUDIO_FORMAT; cursrc <<= 1, x++) {
01007             if (!(*srcs & cursrc) || !tr_matrix[x][y].step) {
01008                continue;
01009             }
01010 
01011             /* This is a better choice if any of the following are true.
01012              * 1. The sample rate conversion is better than the current pick.
01013              * 2. the sample rate conversion is no worse than the current pick and the cost or multistep is better
01014              */
01015             better = 0;
01016             if (tr_matrix[x][y].rate_change < best_rate_change) {
01017                better = 1; /* this match has a better rate conversion */
01018             }
01019             if ((tr_matrix[x][y].rate_change <= best_rate_change) &&
01020                (tr_matrix[x][y].cost < besttime || tr_matrix[x][y].multistep < beststeps)) {
01021                better = 1; /* this match has no worse rate conversion and the conversion cost is less */
01022             }
01023             if (better) {
01024                /* better than what we have so far */
01025                best = cursrc;
01026                bestdst = cur;
01027                besttime = tr_matrix[x][y].cost;
01028                beststeps = tr_matrix[x][y].multistep;
01029                best_rate_change = tr_matrix[x][y].rate_change;
01030             }
01031          }
01032       }
01033       AST_RWLIST_UNLOCK(&translators);
01034       if (best > -1) {
01035          *srcs = best;
01036          *dst = bestdst;
01037          best = 0;
01038       }
01039       return best;
01040    }
01041 }
01042 
01043 unsigned int ast_translate_path_steps(format_t dest, format_t src)
01044 {
01045    unsigned int res = -1;
01046 
01047    /* convert bitwise format numbers into array indices */
01048    src = powerof(src);
01049    dest = powerof(dest);
01050 
01051    if (src == -1 || dest == -1) {
01052       ast_log(LOG_WARNING, "No translator path: (%s codec is not valid)\n", src == -1 ? "starting" : "ending");
01053       return -1;
01054    }
01055    AST_RWLIST_RDLOCK(&translators);
01056 
01057    if (tr_matrix[src][dest].step)
01058       res = tr_matrix[src][dest].multistep + 1;
01059 
01060    AST_RWLIST_UNLOCK(&translators);
01061 
01062    return res;
01063 }
01064 
01065 format_t ast_translate_available_formats(format_t dest, format_t src)
01066 {
01067    format_t res = dest;
01068    format_t x;
01069    format_t src_audio = src & AST_FORMAT_AUDIO_MASK;
01070    format_t src_video = src & AST_FORMAT_VIDEO_MASK;
01071 
01072    /* if we don't have a source format, we just have to try all
01073       possible destination formats */
01074    if (!src)
01075       return dest;
01076 
01077    /* If we have a source audio format, get its format index */
01078    if (src_audio)
01079       src_audio = powerof(src_audio);
01080 
01081    /* If we have a source video format, get its format index */
01082    if (src_video)
01083       src_video = powerof(src_video);
01084 
01085    AST_RWLIST_RDLOCK(&translators);
01086 
01087    /* For a given source audio format, traverse the list of
01088       known audio formats to determine whether there exists
01089       a translation path from the source format to the
01090       destination format. */
01091    for (x = 1LL; src_audio && x > 0; x <<= 1) {
01092       if (!(x & AST_FORMAT_AUDIO_MASK)) {
01093          continue;
01094       }
01095 
01096       /* if this is not a desired format, nothing to do */
01097       if (!(dest & x))
01098          continue;
01099 
01100       /* if the source is supplying this format, then
01101          we can leave it in the result */
01102       if (src & x)
01103          continue;
01104 
01105       /* if we don't have a translation path from the src
01106          to this format, remove it from the result */
01107       if (!tr_matrix[src_audio][powerof(x)].step) {
01108          res &= ~x;
01109          continue;
01110       }
01111 
01112       /* now check the opposite direction */
01113       if (!tr_matrix[powerof(x)][src_audio].step)
01114          res &= ~x;
01115    }
01116 
01117    /* For a given source video format, traverse the list of
01118       known video formats to determine whether there exists
01119       a translation path from the source format to the
01120       destination format. */
01121    for (x = 1LL; src_video && x > 0; x <<= 1) {
01122       if (!(x & AST_FORMAT_VIDEO_MASK)) {
01123          continue;
01124       }
01125 
01126       /* if this is not a desired format, nothing to do */
01127       if (!(dest & x))
01128          continue;
01129 
01130       /* if the source is supplying this format, then
01131          we can leave it in the result */
01132       if (src & x)
01133          continue;
01134 
01135       /* if we don't have a translation path from the src
01136          to this format, remove it from the result */
01137       if (!tr_matrix[src_video][powerof(x)].step) {
01138          res &= ~x;
01139          continue;
01140       }
01141 
01142       /* now check the opposite direction */
01143       if (!tr_matrix[powerof(x)][src_video].step)
01144          res &= ~x;
01145    }
01146 
01147    AST_RWLIST_UNLOCK(&translators);
01148 
01149    return res;
01150 }