Sat Apr 26 2014 22:01:36

Asterisk developer's documentation


file.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 Generic File Format Support.
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: 406567 $")
00033 
00034 #include <dirent.h>
00035 #include <sys/stat.h>
00036 #include <sys/wait.h>
00037 #include <math.h>
00038 
00039 #include "asterisk/_private.h"   /* declare ast_file_init() */
00040 #include "asterisk/paths.h"   /* use ast_config_AST_DATA_DIR */
00041 #include "asterisk/mod_format.h"
00042 #include "asterisk/cli.h"
00043 #include "asterisk/channel.h"
00044 #include "asterisk/sched.h"
00045 #include "asterisk/translate.h"
00046 #include "asterisk/utils.h"
00047 #include "asterisk/lock.h"
00048 #include "asterisk/app.h"
00049 #include "asterisk/pbx.h"
00050 #include "asterisk/linkedlists.h"
00051 #include "asterisk/module.h"
00052 #include "asterisk/astobj2.h"
00053 #include "asterisk/test.h"
00054 
00055 /*! \brief
00056  * The following variable controls the layout of localized sound files.
00057  * If 0, use the historical layout with prefix just before the filename
00058  * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
00059  * if 1 put the prefix at the beginning of the filename
00060  * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
00061  * The latter permits a language to be entirely in one directory.
00062  *
00063  * This is settable in asterisk.conf.
00064  */
00065 int ast_language_is_prefix = 1;
00066 
00067 static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
00068 
00069 int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
00070 {
00071    struct ast_format_def *tmp;
00072 
00073    AST_RWLIST_WRLOCK(&formats);
00074    AST_RWLIST_TRAVERSE(&formats, tmp, list) {
00075       if (!strcasecmp(f->name, tmp->name)) {
00076          AST_RWLIST_UNLOCK(&formats);
00077          ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
00078          return -1;
00079       }
00080    }
00081    if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
00082       AST_RWLIST_UNLOCK(&formats);
00083       return -1;
00084    }
00085    *tmp = *f;
00086    tmp->module = mod;
00087    if (tmp->buf_size) {
00088       /*
00089        * Align buf_size properly, rounding up to the machine-specific
00090        * alignment for pointers.
00091        */
00092       struct _test_align { void *a, *b; } p;
00093       int align = (char *)&p.b - (char *)&p.a;
00094       tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
00095    }
00096 
00097    memset(&tmp->list, 0, sizeof(tmp->list));
00098 
00099    AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
00100    AST_RWLIST_UNLOCK(&formats);
00101    ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
00102 
00103    return 0;
00104 }
00105 
00106 int ast_format_def_unregister(const char *name)
00107 {
00108    struct ast_format_def *tmp;
00109    int res = -1;
00110 
00111    AST_RWLIST_WRLOCK(&formats);
00112    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
00113       if (!strcasecmp(name, tmp->name)) {
00114          AST_RWLIST_REMOVE_CURRENT(list);
00115          ast_free(tmp);
00116          res = 0;
00117       }
00118    }
00119    AST_RWLIST_TRAVERSE_SAFE_END;
00120    AST_RWLIST_UNLOCK(&formats);
00121 
00122    if (!res)
00123       ast_verb(2, "Unregistered format %s\n", name);
00124    else
00125       ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
00126 
00127    return res;
00128 }
00129 
00130 int ast_stopstream(struct ast_channel *tmp)
00131 {
00132    ast_channel_lock(tmp);
00133 
00134    /* Stop a running stream if there is one */
00135    if (ast_channel_stream(tmp)) {
00136       ast_closestream(ast_channel_stream(tmp));
00137       ast_channel_stream_set(tmp, NULL);
00138       if (ast_channel_oldwriteformat(tmp)->id && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
00139          ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(ast_channel_oldwriteformat(tmp)));
00140    }
00141    /* Stop the video stream too */
00142    if (ast_channel_vstream(tmp) != NULL) {
00143       ast_closestream(ast_channel_vstream(tmp));
00144       ast_channel_vstream_set(tmp, NULL);
00145    }
00146 
00147    ast_channel_unlock(tmp);
00148 
00149    return 0;
00150 }
00151 
00152 int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
00153 {
00154    int res = -1;
00155    if (f->frametype == AST_FRAME_VIDEO) {
00156       if (AST_FORMAT_GET_TYPE(fs->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
00157          /* This is the audio portion.  Call the video one... */
00158          if (!fs->vfs && fs->filename) {
00159             const char *type = ast_getformatname(&f->subclass.format);
00160             fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
00161             ast_debug(1, "Opened video output file\n");
00162          }
00163          if (fs->vfs)
00164             return ast_writestream(fs->vfs, f);
00165          /* else ignore */
00166          return 0;
00167       }
00168    } else if (f->frametype != AST_FRAME_VOICE) {
00169       ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
00170       return -1;
00171    }
00172    if (ast_format_cmp(&f->subclass.format, &fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
00173       res =  fs->fmt->write(fs, f);
00174       if (res < 0)
00175          ast_log(LOG_WARNING, "Natural write failed\n");
00176       else if (res > 0)
00177          ast_log(LOG_WARNING, "Huh??\n");
00178    } else {
00179       /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
00180              the one we've setup a translator for, we do the "wrong thing" XXX */
00181       if (fs->trans && (ast_format_cmp(&f->subclass.format, &fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
00182          ast_translator_free_path(fs->trans);
00183          fs->trans = NULL;
00184       }
00185       if (!fs->trans)
00186          fs->trans = ast_translator_build_path(&fs->fmt->format, &f->subclass.format);
00187       if (!fs->trans)
00188          ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
00189             fs->fmt->name, ast_getformatname(&f->subclass.format));
00190       else {
00191          struct ast_frame *trf;
00192          ast_format_copy(&fs->lastwriteformat, &f->subclass.format);
00193          /* Get the translated frame but don't consume the original in case they're using it on another stream */
00194          if ((trf = ast_translate(fs->trans, f, 0))) {
00195             struct ast_frame *cur;
00196 
00197             /* the translator may have returned multiple frames, so process them */
00198             for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
00199                if ((res = fs->fmt->write(fs, trf))) {
00200                   ast_log(LOG_WARNING, "Translated frame write failed\n");
00201                   break;
00202                }
00203             }
00204             ast_frfree(trf);
00205          } else {
00206             res = 0;
00207          }
00208       }
00209    }
00210    return res;
00211 }
00212 
00213 static int copy(const char *infile, const char *outfile)
00214 {
00215    int ifd, ofd, len;
00216    char buf[4096];   /* XXX make it lerger. */
00217 
00218    if ((ifd = open(infile, O_RDONLY)) < 0) {
00219       ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
00220       return -1;
00221    }
00222    if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
00223       ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
00224       close(ifd);
00225       return -1;
00226    }
00227    while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
00228       int res;
00229       if (len < 0) {
00230          ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
00231          break;
00232       }
00233       /* XXX handle partial writes */
00234       res = write(ofd, buf, len);
00235       if (res != len) {
00236          ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
00237          len = -1; /* error marker */
00238          break;
00239       }
00240    }
00241    close(ifd);
00242    close(ofd);
00243    if (len < 0) {
00244       unlink(outfile);
00245       return -1; /* error */
00246    }
00247    return 0;   /* success */
00248 }
00249 
00250 /*!
00251  * \brief construct a filename. Absolute pathnames are preserved,
00252  * relative names are prefixed by the sounds/ directory.
00253  * The wav49 suffix is replaced by 'WAV'.
00254  * Returns a malloc'ed string to be freed by the caller.
00255  */
00256 static char *build_filename(const char *filename, const char *ext)
00257 {
00258    char *fn = NULL;
00259 
00260    if (!strcmp(ext, "wav49"))
00261       ext = "WAV";
00262 
00263    if (filename[0] == '/') {
00264       if (ast_asprintf(&fn, "%s.%s", filename, ext) < 0) {
00265          fn = NULL;
00266       }
00267    } else {
00268       if (ast_asprintf(&fn, "%s/sounds/%s.%s",
00269               ast_config_AST_DATA_DIR, filename, ext) < 0) {
00270          fn = NULL;
00271       }
00272    }
00273    return fn;
00274 }
00275 
00276 /* compare type against the list 'exts' */
00277 /* XXX need a better algorithm */
00278 static int exts_compare(const char *exts, const char *type)
00279 {
00280    char tmp[256];
00281    char *stringp = tmp, *ext;
00282 
00283    ast_copy_string(tmp, exts, sizeof(tmp));
00284    while ((ext = strsep(&stringp, "|"))) {
00285       if (!strcmp(ext, type))
00286          return 1;
00287    }
00288 
00289    return 0;
00290 }
00291 
00292 /*! \internal \brief Close the file stream by canceling any pending read / write callbacks */
00293 static void filestream_close(struct ast_filestream *f)
00294 {
00295    enum ast_format_type format_type = AST_FORMAT_GET_TYPE(f->fmt->format.id);
00296 
00297    if (!f->owner) {
00298       return;
00299    }
00300 
00301    /* Stop a running stream if there is one */
00302    switch (format_type)
00303    {
00304    case AST_FORMAT_TYPE_AUDIO:
00305       ast_channel_stream_set(f->owner, NULL);
00306       AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
00307       ast_settimeout(f->owner, 0, NULL, NULL);
00308       break;
00309    case AST_FORMAT_TYPE_VIDEO:
00310       ast_channel_vstream_set(f->owner, NULL);
00311       AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
00312       break;
00313    default:
00314       ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
00315       break;
00316    }
00317 }
00318 
00319 static void filestream_destructor(void *arg)
00320 {
00321    struct ast_filestream *f = arg;
00322    int status;
00323    int pid = -1;
00324 
00325    /* Stop a running stream if there is one */
00326    filestream_close(f);
00327 
00328    /* destroy the translator on exit */
00329    if (f->trans)
00330       ast_translator_free_path(f->trans);
00331 
00332    if (f->fmt->close) {
00333       void (*closefn)(struct ast_filestream *) = f->fmt->close;
00334       closefn(f);
00335    }
00336 
00337    if (f->f) {
00338       fclose(f->f);
00339    }
00340 
00341    if (f->realfilename && f->filename) {
00342       pid = ast_safe_fork(0);
00343       if (!pid) {
00344          execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
00345          _exit(1);
00346       }
00347       else if (pid > 0) {
00348          /* Block the parent until the move is complete.*/
00349          waitpid(pid, &status, 0);
00350       }
00351    }
00352 
00353    if (f->filename)
00354       free(f->filename);
00355    if (f->realfilename)
00356       free(f->realfilename);
00357    if (f->vfs)
00358       ast_closestream(f->vfs);
00359    if (f->write_buffer) {
00360       ast_free(f->write_buffer);
00361    }
00362    if (f->orig_chan_name)
00363       free((void *) f->orig_chan_name);
00364    ast_module_unref(f->fmt->module);
00365 }
00366 
00367 static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
00368 {
00369    struct ast_filestream *s;
00370 
00371    int l = sizeof(*s) + fmt->buf_size + fmt->desc_size;  /* total allocation size */
00372    if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
00373       return NULL;
00374    s->fmt = fmt;
00375    s->f = bfile;
00376 
00377    if (fmt->desc_size)
00378       s->_private = ((char *)(s + 1)) + fmt->buf_size;
00379    if (fmt->buf_size)
00380       s->buf = (char *)(s + 1);
00381    s->fr.src = fmt->name;
00382    return s;
00383 }
00384 
00385 /*
00386  * Default implementations of open and rewrite.
00387  * Only use them if you don't have expensive stuff to do.
00388  */
00389 enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
00390 
00391 static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
00392 {
00393    struct ast_format_def *f = s->fmt;
00394    int ret = -1;
00395    int (*openfn)(struct ast_filestream *s);
00396 
00397    if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
00398       ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
00399    else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
00400       ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
00401    else {
00402       /* preliminary checks succeed. update usecount */
00403       ast_module_ref(f->module);
00404       ret = 0;
00405    }
00406    return ret;
00407 }
00408 
00409 static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
00410 {
00411    return fn_wrapper(s, comment, WRAP_REWRITE);
00412 }
00413 
00414 static int open_wrapper(struct ast_filestream *s)
00415 {
00416    return fn_wrapper(s, NULL, WRAP_OPEN);
00417 }
00418 
00419 enum file_action {
00420    ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
00421    ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
00422    ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
00423    ACTION_OPEN,
00424    ACTION_COPY /* copy file. return 0 on success, -1 on error */
00425 };
00426 
00427 /*!
00428  * \internal
00429  * \brief perform various actions on a file. Second argument
00430  * \note arg2 depends on the command:
00431  * unused for DELETE
00432  *  optional ast_format_cap holding all the formats found for a file, for EXISTS.
00433  * destination file name (const char *) for COPY and RENAME
00434  * struct ast_channel * for OPEN
00435  * if fmt is NULL, OPEN will return the first matching entry,
00436  * whereas other functions will run on all matching entries.
00437  */
00438 static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
00439 {
00440    struct ast_format_def *f;
00441    int res = (action == ACTION_EXISTS) ? 0 : -1;
00442 
00443    AST_RWLIST_RDLOCK(&formats);
00444    /* Check for a specific format */
00445    AST_RWLIST_TRAVERSE(&formats, f, list) {
00446       char *stringp, *ext = NULL;
00447 
00448       if (fmt && !exts_compare(f->exts, fmt))
00449          continue;
00450 
00451       /* Look for a file matching the supported extensions.
00452        * The file must exist, and for OPEN, must match
00453        * one of the formats supported by the channel.
00454        */
00455       stringp = ast_strdupa(f->exts);  /* this is in the stack so does not need to be freed */
00456       while ( (ext = strsep(&stringp, "|")) ) {
00457          struct stat st;
00458          char *fn = build_filename(filename, ext);
00459 
00460          if (fn == NULL)
00461             continue;
00462 
00463          if ( stat(fn, &st) ) { /* file not existent */
00464             ast_free(fn);
00465             continue;
00466          }
00467          /* for 'OPEN' we need to be sure that the format matches
00468           * what the channel can process
00469           */
00470          if (action == ACTION_OPEN) {
00471             struct ast_channel *chan = (struct ast_channel *)arg2;
00472             FILE *bfile;
00473             struct ast_filestream *s;
00474 
00475             if ((ast_format_cmp(ast_channel_writeformat(chan), &f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
00476                  !(((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_AUDIO) && fmt) ||
00477                  ((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_VIDEO) && fmt))) {
00478                ast_free(fn);
00479                continue;   /* not a supported format */
00480             }
00481             if ( (bfile = fopen(fn, "r")) == NULL) {
00482                ast_free(fn);
00483                continue;   /* cannot open file */
00484             }
00485             s = get_filestream(f, bfile);
00486             if (!s) {
00487                fclose(bfile);
00488                ast_free(fn);  /* cannot allocate descriptor */
00489                continue;
00490             }
00491             if (open_wrapper(s)) {
00492                ast_free(fn);
00493                ast_closestream(s);
00494                continue;   /* cannot run open on file */
00495             }
00496             if (st.st_size == 0) {
00497                ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
00498             }
00499             /* ok this is good for OPEN */
00500             res = 1; /* found */
00501             s->lasttimeout = -1;
00502             s->fmt = f;
00503             s->trans = NULL;
00504             s->filename = NULL;
00505             if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
00506                if (ast_channel_stream(chan))
00507                   ast_closestream(ast_channel_stream(chan));
00508                ast_channel_stream_set(chan, s);
00509             } else {
00510                if (ast_channel_vstream(chan))
00511                   ast_closestream(ast_channel_vstream(chan));
00512                ast_channel_vstream_set(chan, s);
00513             }
00514             ast_free(fn);
00515             break;
00516          }
00517          switch (action) {
00518          case ACTION_OPEN:
00519             break;   /* will never get here */
00520 
00521          case ACTION_EXISTS:  /* return the matching format */
00522             /* if arg2 is present, it is a format capabilities structure.
00523              * Add this format to the set of formats this file can be played in */
00524             if (arg2) {
00525                ast_format_cap_add((struct ast_format_cap *) arg2, &f->format);
00526             }
00527             res = 1; /* file does exist and format it exists in is returned in arg2 */
00528             break;
00529 
00530          case ACTION_DELETE:
00531             if ( (res = unlink(fn)) )
00532                ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
00533             break;
00534 
00535          case ACTION_RENAME:
00536          case ACTION_COPY: {
00537             char *nfn = build_filename((const char *)arg2, ext);
00538             if (!nfn)
00539                ast_log(LOG_WARNING, "Out of memory\n");
00540             else {
00541                res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
00542                if (res)
00543                   ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
00544                      action == ACTION_COPY ? "copy" : "rename",
00545                       fn, nfn, strerror(errno));
00546                ast_free(nfn);
00547             }
00548              }
00549             break;
00550 
00551          default:
00552             ast_log(LOG_WARNING, "Unknown helper %d\n", action);
00553          }
00554          ast_free(fn);
00555       }
00556    }
00557    AST_RWLIST_UNLOCK(&formats);
00558    return res;
00559 }
00560 
00561 static int is_absolute_path(const char *filename)
00562 {
00563    return filename[0] == '/';
00564 }
00565 
00566 /*!
00567  * \brief test if a file exists for a given format.
00568  * \note result_cap is OPTIONAL
00569  * \retval 1, true and result_cap represents format capabilities file exists in.
00570  * \retval 0, false
00571  */
00572 static int fileexists_test(const char *filename, const char *fmt, const char *lang,
00573             char *buf, int buflen, struct ast_format_cap *result_cap)
00574 {
00575    if (buf == NULL) {
00576       return 0;
00577    }
00578 
00579    if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
00580       if (lang) {
00581          snprintf(buf, buflen, "%s/%s", lang, filename);
00582       } else {
00583          snprintf(buf, buflen, "%s", filename);
00584       }
00585    } else { /* old layout */
00586       strcpy(buf, filename);  /* first copy the full string */
00587       if (lang) {
00588          /* insert the language and suffix if needed */
00589          const char *c = strrchr(filename, '/');
00590          int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
00591          snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
00592       }
00593    }
00594 
00595    return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
00596 }
00597 
00598 /*!
00599  * \brief helper routine to locate a file with a given format
00600  * and language preference.
00601  *
00602  * \note Try preflang, preflang with stripped '_' suffices, or NULL.
00603  *
00604  * \note The last parameter(s) point to a buffer of sufficient size,
00605  * which on success is filled with the matching filename.
00606  *
00607  * \param filename, name of the file.
00608  * \param fmt, format to look for the file in. OPTIONAL
00609  * \param preflang, the perfered language
00610  * \param buf, returns the matching filename
00611  * \param buflen, size of the buf
00612  * \param result_cap, OPTIONAL format capabilities result structure
00613  *        returns what formats the file was found in.
00614  *
00615  * \retval 1, true. file exists and result format is set
00616  * \retval 0, false. file does not exist.
00617  */
00618 static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
00619             char *buf, int buflen, struct ast_format_cap *result_cap)
00620 {
00621    char *lang;
00622 
00623    if (buf == NULL) {
00624       return 0;
00625    }
00626 
00627    /* We try languages in the following order:
00628     *    preflang (may include dialect and style codes)
00629     *    lang (preflang without dialect - if any)
00630     *    <none>
00631     *    default (unless the same as preflang or lang without dialect)
00632     */
00633 
00634    lang = ast_strdupa(preflang);
00635 
00636    /* Try preferred language, including removing any style or dialect codes */
00637    while (!ast_strlen_zero(lang)) {
00638       char *end;
00639 
00640       if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
00641          return 1;
00642       }
00643 
00644       if ((end = strrchr(lang, '_')) != NULL) {
00645          *end = '\0';
00646          continue;
00647       }
00648 
00649       break;
00650    }
00651 
00652    /* Try without any language */
00653    if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
00654       return 1;
00655    }
00656 
00657    /* Finally try the default language unless it was already tried before */
00658    if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
00659       if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
00660          return 1;
00661       }
00662    }
00663 
00664    return 0;
00665 }
00666 
00667 struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
00668 {
00669    return ast_openstream_full(chan, filename, preflang, 0);
00670 }
00671 
00672 struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
00673 {
00674    /*
00675     * Use fileexists_core() to find a file in a compatible
00676     * language and format, set up a suitable translator,
00677     * and open the stream.
00678     */
00679    struct ast_format_cap *file_fmt_cap;
00680    int res;
00681    int buflen;
00682    char *buf;
00683 
00684    if (!asis) {
00685       /* do this first, otherwise we detect the wrong writeformat */
00686       ast_stopstream(chan);
00687       if (ast_channel_generator(chan))
00688          ast_deactivate_generator(chan);
00689    }
00690    if (preflang == NULL)
00691       preflang = "";
00692    buflen = strlen(preflang) + strlen(filename) + 4;
00693    buf = ast_alloca(buflen);
00694 
00695    if (!(file_fmt_cap = ast_format_cap_alloc_nolock())) {
00696       return NULL;
00697    }
00698    if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
00699       !ast_format_cap_has_type(file_fmt_cap, AST_FORMAT_TYPE_AUDIO)) {
00700 
00701       ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
00702       file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
00703       return NULL;
00704    }
00705 
00706    /* Set the channel to a format we can work with and save off the previous format. */
00707    ast_format_copy(ast_channel_oldwriteformat(chan), ast_channel_writeformat(chan));
00708    /* Set the channel to the best format that exists for the file. */
00709    res = ast_set_write_format_from_cap(chan, file_fmt_cap);
00710    /* don't need this anymore now that the channel's write format is set. */
00711    file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
00712 
00713    if (res == -1) {  /* No format available that works with this channel */
00714       return NULL;
00715    }
00716    res = filehelper(buf, chan, NULL, ACTION_OPEN);
00717    if (res >= 0)
00718       return ast_channel_stream(chan);
00719    return NULL;
00720 }
00721 
00722 struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
00723 {
00724    /* As above, but for video. But here we don't have translators
00725     * so we must enforce a format.
00726     */
00727    struct ast_format tmp_fmt;
00728    struct ast_format_cap *tmp_cap;
00729    char *buf;
00730    int buflen;
00731    const char *fmt;
00732    int fd;
00733 
00734    if (preflang == NULL)
00735       preflang = "";
00736    buflen = strlen(preflang) + strlen(filename) + 4;
00737    buf = ast_alloca(buflen);
00738 
00739    /* is the channel capable of video without translation ?*/
00740    if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_FORMAT_TYPE_VIDEO)) {
00741       return NULL;
00742    }
00743    if (!(tmp_cap = ast_format_cap_alloc_nolock())) {
00744       return NULL;
00745    }
00746    /* Video is supported, so see what video formats exist for this file */
00747    if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
00748       tmp_cap = ast_format_cap_destroy(tmp_cap);
00749       return NULL;
00750    }
00751 
00752    /* iterate over file formats and pick the first one compatible with the channel's native formats */
00753    ast_format_cap_iter_start(tmp_cap);
00754    while (!ast_format_cap_iter_next(tmp_cap, &tmp_fmt)) {
00755       fmt = ast_getformatname(&tmp_fmt);
00756       if ((AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_VIDEO) ||
00757          !ast_format_cap_iscompatible(ast_channel_nativeformats(chan), &tmp_fmt)) {
00758          continue;
00759       }
00760 
00761       fd = filehelper(buf, chan, fmt, ACTION_OPEN);
00762       if (fd >= 0) {
00763          ast_format_cap_iter_end(tmp_cap);
00764          tmp_cap = ast_format_cap_destroy(tmp_cap);
00765          return ast_channel_vstream(chan);
00766       }
00767       ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
00768    }
00769    ast_format_cap_iter_end(tmp_cap);
00770    tmp_cap = ast_format_cap_destroy(tmp_cap);
00771 
00772    return NULL;
00773 }
00774 
00775 static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
00776 {
00777    struct ast_frame *fr, *new_fr;
00778 
00779    if (!s || !s->fmt) {
00780       return NULL;
00781    }
00782 
00783    if (!(fr = s->fmt->read(s, whennext))) {
00784       return NULL;
00785    }
00786 
00787    if (!(new_fr = ast_frisolate(fr))) {
00788       ast_frfree(fr);
00789       return NULL;
00790    }
00791 
00792    if (new_fr != fr) {
00793       ast_frfree(fr);
00794       fr = new_fr;
00795    }
00796 
00797    return fr;
00798 }
00799 
00800 struct ast_frame *ast_readframe(struct ast_filestream *s)
00801 {
00802    int whennext = 0;
00803 
00804    return read_frame(s, &whennext);
00805 }
00806 
00807 enum fsread_res {
00808    FSREAD_FAILURE,
00809    FSREAD_SUCCESS_SCHED,
00810    FSREAD_SUCCESS_NOSCHED,
00811 };
00812 
00813 static int ast_fsread_audio(const void *data);
00814 
00815 static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
00816 {
00817    int whennext = 0;
00818 
00819    while (!whennext) {
00820       struct ast_frame *fr;
00821 
00822       if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
00823          goto return_failure;
00824       }
00825 
00826       fr = read_frame(s, &whennext);
00827 
00828       if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
00829          if (fr) {
00830             ast_log(LOG_WARNING, "Failed to write frame\n");
00831             ast_frfree(fr);
00832          }
00833          goto return_failure;
00834       }
00835 
00836       if (fr) {
00837          ast_frfree(fr);
00838       }
00839    }
00840 
00841    if (whennext != s->lasttimeout) {
00842       if (ast_channel_timingfd(s->owner) > -1) {
00843          float samp_rate = (float) ast_format_rate(&s->fmt->format);
00844          unsigned int rate;
00845 
00846          rate = (unsigned int) roundf(samp_rate / ((float) whennext));
00847 
00848          ast_settimeout_full(s->owner, rate, ast_fsread_audio, s, 1);
00849       } else {
00850          ast_channel_streamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_audio, s));
00851       }
00852       s->lasttimeout = whennext;
00853       return FSREAD_SUCCESS_NOSCHED;
00854    }
00855    return FSREAD_SUCCESS_SCHED;
00856 
00857 return_failure:
00858    ast_channel_streamid_set(s->owner, -1);
00859    ast_settimeout(s->owner, 0, NULL, NULL);
00860    return FSREAD_FAILURE;
00861 }
00862 
00863 static int ast_fsread_audio(const void *data)
00864 {
00865    struct ast_filestream *fs = (struct ast_filestream *)data;
00866    enum fsread_res res;
00867 
00868    res = ast_readaudio_callback(fs);
00869 
00870    if (res == FSREAD_SUCCESS_SCHED)
00871       return 1;
00872 
00873    return 0;
00874 }
00875 
00876 static int ast_fsread_video(const void *data);
00877 
00878 static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
00879 {
00880    int whennext = 0;
00881 
00882    while (!whennext) {
00883       struct ast_frame *fr = read_frame(s, &whennext);
00884 
00885       if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
00886          if (fr) {
00887             ast_log(LOG_WARNING, "Failed to write frame\n");
00888             ast_frfree(fr);
00889          }
00890          ast_channel_vstreamid_set(s->owner, -1);
00891          return FSREAD_FAILURE;
00892       }
00893 
00894       if (fr) {
00895          ast_frfree(fr);
00896       }
00897    }
00898 
00899    if (whennext != s->lasttimeout) {
00900       ast_channel_vstreamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_video, s));
00901       s->lasttimeout = whennext;
00902       return FSREAD_SUCCESS_NOSCHED;
00903    }
00904 
00905    return FSREAD_SUCCESS_SCHED;
00906 }
00907 
00908 static int ast_fsread_video(const void *data)
00909 {
00910    struct ast_filestream *fs = (struct ast_filestream *)data;
00911    enum fsread_res res;
00912 
00913    res = ast_readvideo_callback(fs);
00914 
00915    if (res == FSREAD_SUCCESS_SCHED)
00916       return 1;
00917 
00918    return 0;
00919 }
00920 
00921 int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
00922 {
00923    s->owner = chan;
00924    return 0;
00925 }
00926 
00927 int ast_playstream(struct ast_filestream *s)
00928 {
00929    enum fsread_res res;
00930 
00931    if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO)
00932       res = ast_readaudio_callback(s);
00933    else
00934       res = ast_readvideo_callback(s);
00935 
00936    return (res == FSREAD_FAILURE) ? -1 : 0;
00937 }
00938 
00939 int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
00940 {
00941    return fs->fmt->seek(fs, sample_offset, whence);
00942 }
00943 
00944 int ast_truncstream(struct ast_filestream *fs)
00945 {
00946    return fs->fmt->trunc(fs);
00947 }
00948 
00949 off_t ast_tellstream(struct ast_filestream *fs)
00950 {
00951    return fs->fmt->tell(fs);
00952 }
00953 
00954 int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
00955 {
00956    return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
00957 }
00958 
00959 int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
00960 {
00961    return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
00962 }
00963 
00964 int ast_closestream(struct ast_filestream *f)
00965 {
00966    /* This used to destroy the filestream, but it now just decrements a refcount.
00967     * We close the stream in order to quit queuing frames now, because we might
00968     * change the writeformat, which could result in a subsequent write error, if
00969     * the format is different. */
00970    filestream_close(f);
00971    ao2_ref(f, -1);
00972    return 0;
00973 }
00974 
00975 
00976 /*
00977  * Look the various language-specific places where a file could exist.
00978  */
00979 int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
00980 {
00981    char *buf;
00982    int buflen;
00983 
00984    if (preflang == NULL)
00985       preflang = "";
00986    buflen = strlen(preflang) + strlen(filename) + 4;  /* room for everything */
00987    buf = ast_alloca(buflen);
00988    return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
00989 }
00990 
00991 int ast_filedelete(const char *filename, const char *fmt)
00992 {
00993    return filehelper(filename, NULL, fmt, ACTION_DELETE);
00994 }
00995 
00996 int ast_filerename(const char *filename, const char *filename2, const char *fmt)
00997 {
00998    return filehelper(filename, filename2, fmt, ACTION_RENAME);
00999 }
01000 
01001 int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
01002 {
01003    return filehelper(filename, filename2, fmt, ACTION_COPY);
01004 }
01005 
01006 int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
01007 {
01008    struct ast_filestream *fs;
01009    struct ast_filestream *vfs=NULL;
01010    char fmt[256];
01011    off_t pos;
01012    int seekattempt;
01013    int res;
01014 
01015    fs = ast_openstream(chan, filename, preflang);
01016    if (!fs) {
01017       ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), ast_channel_nativeformats(chan)), strerror(errno));
01018       return -1;
01019    }
01020 
01021    /* check to see if there is any data present (not a zero length file),
01022     * done this way because there is no where for ast_openstream_full to
01023     * return the file had no data. */
01024    pos = ftello(fs->f);
01025    seekattempt = fseeko(fs->f, -1, SEEK_END);
01026    if (seekattempt) {
01027       if (errno == EINVAL) {
01028          /* Zero-length file, as opposed to a pipe */
01029          return 0;
01030       } else {
01031          ast_seekstream(fs, 0, SEEK_SET);
01032       }
01033    } else {
01034       fseeko(fs->f, pos, SEEK_SET);
01035    }
01036 
01037    vfs = ast_openvstream(chan, filename, preflang);
01038    if (vfs) {
01039       ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(&vfs->fmt->format));
01040    }
01041 
01042    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
01043       fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
01044    if (ast_applystream(chan, fs))
01045       return -1;
01046    if (vfs && ast_applystream(chan, vfs))
01047       return -1;
01048    res = ast_playstream(fs);
01049    if (!res && vfs)
01050       res = ast_playstream(vfs);
01051    ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", ast_channel_name(chan), filename, ast_getformatname(ast_channel_writeformat(chan)), preflang ? preflang : "default");
01052 
01053    return res;
01054 }
01055 
01056 struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
01057 {
01058    FILE *bfile;
01059    struct ast_format_def *f;
01060    struct ast_filestream *fs = NULL;
01061    char *fn;
01062    int format_found = 0;
01063 
01064    AST_RWLIST_RDLOCK(&formats);
01065 
01066    AST_RWLIST_TRAVERSE(&formats, f, list) {
01067       fs = NULL;
01068       if (!exts_compare(f->exts, type))
01069          continue;
01070       else
01071          format_found = 1;
01072 
01073       fn = build_filename(filename, type);
01074       if (!fn) {
01075          continue;
01076       }
01077       errno = 0;
01078       bfile = fopen(fn, "r");
01079 
01080       if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
01081          ast_log(LOG_WARNING, "Unable to open %s\n", fn);
01082          if (fs) {
01083             ast_closestream(fs);
01084          }
01085          fs = NULL;
01086          bfile = NULL;
01087          ast_free(fn);
01088          break;
01089       }
01090       /* found it */
01091       fs->trans = NULL;
01092       fs->fmt = f;
01093       fs->flags = flags;
01094       fs->mode = mode;
01095       fs->filename = ast_strdup(filename);
01096       fs->vfs = NULL;
01097       ast_free(fn);
01098       break;
01099    }
01100 
01101    AST_RWLIST_UNLOCK(&formats);
01102    if (!format_found)
01103       ast_log(LOG_WARNING, "No such format '%s'\n", type);
01104 
01105    return fs;
01106 }
01107 
01108 struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
01109 {
01110    int fd, myflags = 0;
01111    /* compiler claims this variable can be used before initialization... */
01112    FILE *bfile = NULL;
01113    struct ast_format_def *f;
01114    struct ast_filestream *fs = NULL;
01115    char *buf = NULL;
01116    size_t size = 0;
01117    int format_found = 0;
01118 
01119    AST_RWLIST_RDLOCK(&formats);
01120 
01121    /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
01122    /* We really can't use O_APPEND as it will break WAV header updates */
01123    if (flags & O_APPEND) {
01124       flags &= ~O_APPEND;
01125    } else {
01126       myflags = O_TRUNC;
01127    }
01128 
01129    myflags |= O_WRONLY | O_CREAT;
01130 
01131    /* XXX need to fix this - we should just do the fopen,
01132     * not open followed by fdopen()
01133     */
01134    AST_RWLIST_TRAVERSE(&formats, f, list) {
01135       char *fn, *orig_fn = NULL;
01136       if (fs)
01137          break;
01138 
01139       if (!exts_compare(f->exts, type))
01140          continue;
01141       else
01142          format_found = 1;
01143 
01144       fn = build_filename(filename, type);
01145       if (!fn) {
01146          continue;
01147       }
01148       fd = open(fn, flags | myflags, mode);
01149       if (fd > -1) {
01150          /* fdopen() the resulting file stream */
01151          bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
01152          if (!bfile) {
01153             ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
01154             close(fd);
01155             fd = -1;
01156          }
01157       }
01158 
01159       if (ast_opt_cache_record_files && (fd > -1)) {
01160          char *c;
01161 
01162          fclose(bfile); /* this also closes fd */
01163          /*
01164            We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
01165            What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
01166          */
01167          orig_fn = ast_strdupa(fn);
01168          for (c = fn; *c; c++)
01169             if (*c == '/')
01170                *c = '_';
01171 
01172          size = strlen(fn) + strlen(record_cache_dir) + 2;
01173          buf = ast_alloca(size);
01174          strcpy(buf, record_cache_dir);
01175          strcat(buf, "/");
01176          strcat(buf, fn);
01177          ast_free(fn);
01178          fn = buf;
01179          fd = open(fn, flags | myflags, mode);
01180          if (fd > -1) {
01181             /* fdopen() the resulting file stream */
01182             bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
01183             if (!bfile) {
01184                ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
01185                close(fd);
01186                fd = -1;
01187             }
01188          }
01189       }
01190       if (fd > -1) {
01191          errno = 0;
01192          fs = get_filestream(f, bfile);
01193          if (fs) {
01194             if ((fs->write_buffer = ast_malloc(32768))) {
01195                setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
01196             }
01197          }
01198          if (!fs || rewrite_wrapper(fs, comment)) {
01199             ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
01200             close(fd);
01201             if (orig_fn) {
01202                unlink(fn);
01203                unlink(orig_fn);
01204             }
01205             if (fs) {
01206                ast_closestream(fs);
01207                fs = NULL;
01208             }
01209             if (!buf) {
01210                ast_free(fn);
01211             }
01212             continue;
01213          }
01214          fs->trans = NULL;
01215          fs->fmt = f;
01216          fs->flags = flags;
01217          fs->mode = mode;
01218          if (orig_fn) {
01219             fs->realfilename = ast_strdup(orig_fn);
01220             fs->filename = ast_strdup(fn);
01221          } else {
01222             fs->realfilename = NULL;
01223             fs->filename = ast_strdup(filename);
01224          }
01225          fs->vfs = NULL;
01226          /* If truncated, we'll be at the beginning; if not truncated, then append */
01227          f->seek(fs, 0, SEEK_END);
01228       } else if (errno != EEXIST) {
01229          ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
01230          if (orig_fn)
01231             unlink(orig_fn);
01232       }
01233       /* if buf != NULL then fn is already free and pointing to it */
01234       if (!buf)
01235          ast_free(fn);
01236    }
01237 
01238    AST_RWLIST_UNLOCK(&formats);
01239 
01240    if (!format_found)
01241       ast_log(LOG_WARNING, "No such format '%s'\n", type);
01242 
01243    return fs;
01244 }
01245 
01246 /*!
01247  * \brief the core of all waitstream() functions
01248  */
01249 static int waitstream_core(struct ast_channel *c,
01250    const char *breakon,
01251    const char *forward,
01252    const char *reverse,
01253    int skip_ms,
01254    int audiofd,
01255    int cmdfd,
01256    const char *context,
01257    ast_waitstream_fr_cb cb)
01258 {
01259    const char *orig_chan_name = NULL;
01260 
01261    int err = 0;
01262 
01263    if (!breakon)
01264       breakon = "";
01265    if (!forward)
01266       forward = "";
01267    if (!reverse)
01268       reverse = "";
01269 
01270    /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
01271    ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01272 
01273    if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
01274       orig_chan_name = ast_strdupa(ast_channel_name(c));
01275 
01276    if (ast_channel_stream(c) && cb) {
01277       long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_rate(&ast_channel_stream(c)->fmt->format) / 1000);
01278       cb(c, ms_len, AST_WAITSTREAM_CB_START);
01279    }
01280 
01281    while (ast_channel_stream(c)) {
01282       int res;
01283       int ms;
01284 
01285       if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
01286          ast_stopstream(c);
01287          err = 1;
01288          break;
01289       }
01290 
01291       ms = ast_sched_wait(ast_channel_sched(c));
01292 
01293       if (ms < 0 && !ast_channel_timingfunc(c)) {
01294          ast_stopstream(c);
01295          break;
01296       }
01297       if (ms < 0)
01298          ms = 1000;
01299       if (cmdfd < 0) {
01300          res = ast_waitfor(c, ms);
01301          if (res < 0) {
01302             ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
01303             ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01304             return res;
01305          }
01306       } else {
01307          int outfd;
01308          struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
01309          if (!rchan && (outfd < 0) && (ms)) {
01310             /* Continue */
01311             if (errno == EINTR)
01312                continue;
01313             ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
01314             ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01315             return -1;
01316          } else if (outfd > -1) { /* this requires cmdfd set */
01317             /* The FD we were watching has something waiting */
01318             ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01319             return 1;
01320          }
01321          /* if rchan is set, it is 'c' */
01322          res = rchan ? 1 : 0; /* map into 'res' values */
01323       }
01324       if (res > 0) {
01325          struct ast_frame *fr = ast_read(c);
01326          if (!fr) {
01327             ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01328             return -1;
01329          }
01330          switch (fr->frametype) {
01331          case AST_FRAME_DTMF_END:
01332             if (context) {
01333                const char exten[2] = { fr->subclass.integer, '\0' };
01334                if (ast_exists_extension(c, context, exten, 1,
01335                   S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
01336                   res = fr->subclass.integer;
01337                   ast_frfree(fr);
01338                   ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01339                   return res;
01340                }
01341             } else {
01342                enum ast_waitstream_fr_cb_values cb_val = 0;
01343                res = fr->subclass.integer;
01344                if (strchr(forward, res)) {
01345                   int eoftest;
01346                   ast_stream_fastforward(ast_channel_stream(c), skip_ms);
01347                   eoftest = fgetc(ast_channel_stream(c)->f);
01348                   if (feof(ast_channel_stream(c)->f)) {
01349                      ast_stream_rewind(ast_channel_stream(c), skip_ms);
01350                   } else {
01351                      ungetc(eoftest, ast_channel_stream(c)->f);
01352                   }
01353                   cb_val = AST_WAITSTREAM_CB_FASTFORWARD;
01354                } else if (strchr(reverse, res)) {
01355                   ast_stream_rewind(ast_channel_stream(c), skip_ms);
01356                   cb_val = AST_WAITSTREAM_CB_REWIND;
01357                } else if (strchr(breakon, res)) {
01358                   ast_frfree(fr);
01359                   ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01360                   return res;
01361                }
01362                if (cb_val && cb) {
01363                   long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_rate(&ast_channel_stream(c)->fmt->format) / 1000);
01364                   cb(c, ms_len, cb_val);
01365                }
01366             }
01367             break;
01368          case AST_FRAME_CONTROL:
01369             switch (fr->subclass.integer) {
01370             case AST_CONTROL_HANGUP:
01371             case AST_CONTROL_BUSY:
01372             case AST_CONTROL_CONGESTION:
01373                ast_frfree(fr);
01374                ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01375                return -1;
01376             case AST_CONTROL_RINGING:
01377             case AST_CONTROL_ANSWER:
01378             case AST_CONTROL_VIDUPDATE:
01379             case AST_CONTROL_SRCUPDATE:
01380             case AST_CONTROL_SRCCHANGE:
01381             case AST_CONTROL_HOLD:
01382             case AST_CONTROL_UNHOLD:
01383             case AST_CONTROL_CONNECTED_LINE:
01384             case AST_CONTROL_REDIRECTING:
01385             case AST_CONTROL_AOC:
01386             case AST_CONTROL_UPDATE_RTP_PEER:
01387             case AST_CONTROL_PVT_CAUSE_CODE:
01388             case -1:
01389                /* Unimportant */
01390                break;
01391             default:
01392                ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
01393             }
01394             break;
01395          case AST_FRAME_VOICE:
01396             /* Write audio if appropriate */
01397             if (audiofd > -1) {
01398                if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
01399                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
01400                }
01401             }
01402          default:
01403             /* Ignore all others */
01404             break;
01405          }
01406          ast_frfree(fr);
01407       }
01408       ast_sched_runq(ast_channel_sched(c));
01409    }
01410 
01411    ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
01412 
01413    return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
01414 }
01415 
01416 int ast_waitstream_fr_w_cb(struct ast_channel *c,
01417    const char *breakon,
01418    const char *forward,
01419    const char *reverse,
01420    int ms,
01421    ast_waitstream_fr_cb cb)
01422 {
01423    return waitstream_core(c, breakon, forward, reverse, ms,
01424       -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, cb);
01425 }
01426 
01427 int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
01428 {
01429    return waitstream_core(c, breakon, forward, reverse, ms,
01430       -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, NULL /* no callback */);
01431 }
01432 
01433 int ast_waitstream(struct ast_channel *c, const char *breakon)
01434 {
01435    return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL, NULL /* no callback */);
01436 }
01437 
01438 int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
01439 {
01440    return waitstream_core(c, breakon, NULL, NULL, 0,
01441       audiofd, cmdfd, NULL /* no context */, NULL /* no callback */);
01442 }
01443 
01444 int ast_waitstream_exten(struct ast_channel *c, const char *context)
01445 {
01446    /* Waitstream, with return in the case of a valid 1 digit extension */
01447    /* in the current or specified context being pressed */
01448 
01449    if (!context)
01450       context = ast_channel_context(c);
01451    return waitstream_core(c, NULL, NULL, NULL, 0,
01452       -1, -1, context, NULL /* no callback */);
01453 }
01454 
01455 /*
01456  * if the file name is non-empty, try to play it.
01457  * Return 0 if success, -1 if error, digit if interrupted by a digit.
01458  * If digits == "" then we can simply check for non-zero.
01459  */
01460 int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
01461 {
01462    int res = 0;
01463    if (!ast_strlen_zero(file)) {
01464       ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", file, ast_channel_name(chan));
01465       res = ast_streamfile(chan, file, ast_channel_language(chan));
01466       if (!res) {
01467          res = ast_waitstream(chan, digits);
01468       }
01469    }
01470    return res;
01471 }
01472 
01473 char *ast_format_str_reduce(char *fmts)
01474 {
01475    struct ast_format_def *f;
01476    struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
01477    char *fmts_str[AST_MAX_FORMATS];
01478    char *stringp, *type;
01479    char *orig = fmts;
01480    int i, j, x, first, found = 0;
01481    int len = strlen(fmts) + 1;
01482    int res;
01483 
01484    if (AST_RWLIST_RDLOCK(&formats)) {
01485       ast_log(LOG_WARNING, "Unable to lock format list\n");
01486       return NULL;
01487    }
01488 
01489    stringp = ast_strdupa(fmts);
01490 
01491    for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
01492       AST_RWLIST_TRAVERSE(&formats, f, list) {
01493          if (exts_compare(f->exts, type)) {
01494             found = 1;
01495             break;
01496          }
01497       }
01498 
01499       fmts_str[x] = type;
01500       if (found) {
01501          fmts_ptr[x] = f;
01502       } else {
01503          fmts_ptr[x] = NULL;
01504       }
01505    }
01506    AST_RWLIST_UNLOCK(&formats);
01507 
01508    first = 1;
01509    for (i = 0; i < x; i++) {
01510       /* ignore invalid entries */
01511       if (!fmts_ptr[i]) {
01512          ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
01513          continue;
01514       }
01515 
01516       /* special handling for the first entry */
01517       if (first) {
01518          res = snprintf(fmts, len, "%s", fmts_str[i]);
01519          fmts += res;
01520          len -= res;
01521          first = 0;
01522          continue;
01523       }
01524 
01525       found = 0;
01526       for (j = 0; j < i; j++) {
01527          /* this is a duplicate */
01528          if (fmts_ptr[j] == fmts_ptr[i]) {
01529             found = 1;
01530             break;
01531          }
01532       }
01533 
01534       if (!found) {
01535          res = snprintf(fmts, len, "|%s", fmts_str[i]);
01536          fmts += res;
01537          len -= res;
01538       }
01539    }
01540 
01541    if (first) {
01542       ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
01543       return NULL;
01544    }
01545 
01546    return orig;
01547 }
01548 
01549 static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01550 {
01551 #define FORMAT "%-10s %-10s %-20s\n"
01552 #define FORMAT2 "%-10s %-10s %-20s\n"
01553    struct ast_format_def *f;
01554    int count_fmt = 0;
01555 
01556    switch (cmd) {
01557    case CLI_INIT:
01558       e->command = "core show file formats";
01559       e->usage =
01560          "Usage: core show file formats\n"
01561          "       Displays currently registered file formats (if any).\n";
01562       return NULL;
01563    case CLI_GENERATE:
01564       return NULL;
01565    }
01566 
01567    if (a->argc != 4)
01568       return CLI_SHOWUSAGE;
01569 
01570    ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
01571    ast_cli(a->fd, FORMAT, "------", "----", "----------");
01572 
01573    AST_RWLIST_RDLOCK(&formats);
01574    AST_RWLIST_TRAVERSE(&formats, f, list) {
01575       ast_cli(a->fd, FORMAT2, ast_getformatname(&f->format), f->name, f->exts);
01576       count_fmt++;
01577    }
01578    AST_RWLIST_UNLOCK(&formats);
01579    ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
01580    return CLI_SUCCESS;
01581 #undef FORMAT
01582 #undef FORMAT2
01583 }
01584 
01585 static struct ast_cli_entry cli_file[] = {
01586    AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
01587 };
01588 
01589 static void file_shutdown(void)
01590 {
01591    ast_cli_unregister_multiple(cli_file, ARRAY_LEN(cli_file));
01592 }
01593 
01594 int ast_file_init(void)
01595 {
01596    ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
01597    ast_register_atexit(file_shutdown);
01598    return 0;
01599 }