app_festival.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2002, Christos Ricudis
00005  *
00006  * Christos Ricudis <ricudis@itc.auth.gr>
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 Connect to festival
00022  *
00023  * \author Christos Ricudis <ricudis@itc.auth.gr>
00024  *
00025  * \extref  The Festival Speech Synthesis System - http://www.cstr.ed.ac.uk/projects/festival/
00026  * 
00027  * \ingroup applications
00028  */
00029 
00030 /*! \li \ref app_festival.c uses the configuration file \ref festival.conf
00031  * \addtogroup configuration_file Configuration Files
00032  */
00033 
00034 /*! 
00035  * \page festival.conf festival.conf
00036  * \verbinclude festival.conf.sample
00037  */
00038 
00039 /*** MODULEINFO
00040    <support_level>extended</support_level>
00041  ***/
00042 
00043 #include "asterisk.h"
00044 
00045 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 419592 $")
00046 
00047 #include <sys/socket.h>
00048 #include <netdb.h>
00049 #include <netinet/in.h>
00050 #include <arpa/inet.h>
00051 #include <signal.h>
00052 #include <fcntl.h>
00053 #include <ctype.h>
00054 #include <errno.h>
00055 
00056 #include "asterisk/file.h"
00057 #include "asterisk/channel.h"
00058 #include "asterisk/pbx.h"
00059 #include "asterisk/module.h"
00060 #include "asterisk/md5.h"
00061 #include "asterisk/config.h"
00062 #include "asterisk/utils.h"
00063 #include "asterisk/lock.h"
00064 #include "asterisk/app.h"
00065 #include "asterisk/endian.h"
00066 #include "asterisk/format_cache.h"
00067 
00068 #define FESTIVAL_CONFIG "festival.conf"
00069 #define MAXLEN 180
00070 #define MAXFESTLEN 2048
00071 
00072 /*** DOCUMENTATION
00073    <application name="Festival" language="en_US">
00074       <synopsis>
00075          Say text to the user.
00076       </synopsis>
00077       <syntax>
00078          <parameter name="text" required="true" />
00079          <parameter name="intkeys" />
00080       </syntax>
00081       <description>
00082          <para>Connect to Festival, send the argument, get back the waveform, play it to the user,
00083          allowing any given interrupt keys to immediately terminate and return the value, or
00084          <literal>any</literal> to allow any number back (useful in dialplan).</para>
00085       </description>
00086    </application>
00087  ***/
00088 
00089 static char *app = "Festival";
00090 
00091 static char *socket_receive_file_to_buff(int fd, int *size)
00092 {
00093    /* Receive file (probably a waveform file) from socket using
00094     * Festival key stuff technique, but long winded I know, sorry
00095     * but will receive any file without closing the stream or
00096     * using OOB data
00097     */
00098    static char *file_stuff_key = "ft_StUfF_key"; /* must == Festival's key */
00099    char *buff, *tmp;
00100    int bufflen;
00101    int n,k,i;
00102    char c;
00103 
00104    bufflen = 1024;
00105    if (!(buff = ast_malloc(bufflen)))
00106       return NULL;
00107    *size = 0;
00108 
00109    for (k = 0; file_stuff_key[k] != '\0';) {
00110       n = read(fd, &c, 1);
00111       if (n == 0)
00112          break;  /* hit stream eof before end of file */
00113       if ((*size) + k + 1 >= bufflen) {
00114          /* +1 so you can add a terminating NULL if you want */
00115          bufflen += bufflen / 4;
00116          if (!(tmp = ast_realloc(buff, bufflen))) {
00117             ast_free(buff);
00118             return NULL;
00119          }
00120          buff = tmp;
00121       }
00122       if (file_stuff_key[k] == c)
00123          k++;
00124       else if ((c == 'X') && (file_stuff_key[k+1] == '\0')) {
00125          /* It looked like the key but wasn't */
00126          for (i = 0; i < k; i++, (*size)++)
00127             buff[*size] = file_stuff_key[i];
00128          k = 0;
00129          /* omit the stuffed 'X' */
00130       } else {
00131          for (i = 0; i < k; i++, (*size)++)
00132             buff[*size] = file_stuff_key[i];
00133          k = 0;
00134          buff[*size] = c;
00135          (*size)++;
00136       }
00137    }
00138 
00139    return buff;
00140 }
00141 
00142 static int send_waveform_to_fd(char *waveform, int length, int fd)
00143 {
00144    int res;
00145 #if __BYTE_ORDER == __BIG_ENDIAN
00146    int x;
00147    char c;
00148 #endif
00149 
00150    res = ast_safe_fork(0);
00151    if (res < 0)
00152       ast_log(LOG_WARNING, "Fork failed\n");
00153    if (res) {
00154       return res;
00155    }
00156    dup2(fd, 0);
00157    ast_close_fds_above_n(0);
00158    if (ast_opt_high_priority)
00159       ast_set_priority(0);
00160 #if __BYTE_ORDER == __BIG_ENDIAN
00161    for (x = 0; x < length; x += 2) {
00162       c = *(waveform + x + 1);
00163       *(waveform + x + 1) = *(waveform + x);
00164       *(waveform + x) = c;
00165    }
00166 #endif
00167 
00168    if (write(0, waveform, length) < 0) {
00169       /* Cannot log -- all FDs are already closed */
00170    }
00171 
00172    close(fd);
00173    _exit(0);
00174 }
00175 
00176 static int send_waveform_to_channel(struct ast_channel *chan, char *waveform, int length, char *intkeys)
00177 {
00178    int res = 0;
00179    int fds[2];
00180    int needed = 0;
00181    struct ast_format *owriteformat;
00182    struct ast_frame *f;
00183    struct myframe {
00184       struct ast_frame f;
00185       char offset[AST_FRIENDLY_OFFSET];
00186       char frdata[2048];
00187    } myf = {
00188       .f = { 0, },
00189    };
00190 
00191    if (pipe(fds)) {
00192       ast_log(LOG_WARNING, "Unable to create pipe\n");
00193       return -1;
00194    }
00195 
00196    /* Answer if it's not already going */
00197    if (ast_channel_state(chan) != AST_STATE_UP)
00198       ast_answer(chan);
00199    ast_stopstream(chan);
00200    ast_indicate(chan, -1);
00201    
00202    owriteformat = ao2_bump(ast_channel_writeformat(chan));
00203    res = ast_set_write_format(chan, ast_format_slin);
00204    if (res < 0) {
00205       ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
00206       ao2_cleanup(owriteformat);
00207       return -1;
00208    }
00209 
00210    myf.f.frametype = AST_FRAME_VOICE;
00211    myf.f.subclass.format = ast_format_slin;
00212    myf.f.offset = AST_FRIENDLY_OFFSET;
00213    myf.f.src = __PRETTY_FUNCTION__;
00214    myf.f.data.ptr = myf.frdata;
00215    
00216    res = send_waveform_to_fd(waveform, length, fds[1]);
00217    if (res >= 0) {
00218       /* Order is important -- there's almost always going to be mp3...  we want to prioritize the
00219          user */
00220       for (;;) {
00221          res = ast_waitfor(chan, 1000);
00222          if (res < 1) {
00223             res = -1;
00224             break;
00225          }
00226          f = ast_read(chan);
00227          if (!f) {
00228             ast_log(LOG_WARNING, "Null frame == hangup() detected\n");
00229             res = -1;
00230             break;
00231          }
00232          if (f->frametype == AST_FRAME_DTMF) {
00233             ast_debug(1, "User pressed a key\n");
00234             if (intkeys && strchr(intkeys, f->subclass.integer)) {
00235                res = f->subclass.integer;
00236                ast_frfree(f);
00237                break;
00238             }
00239          }
00240          if (f->frametype == AST_FRAME_VOICE) {
00241             /* Treat as a generator */
00242             needed = f->samples * 2;
00243             if (needed > sizeof(myf.frdata)) {
00244                ast_log(LOG_WARNING, "Only able to deliver %d of %d requested samples\n",
00245                   (int)sizeof(myf.frdata) / 2, needed/2);
00246                needed = sizeof(myf.frdata);
00247             }
00248             res = read(fds[0], myf.frdata, needed);
00249             if (res > 0) {
00250                myf.f.datalen = res;
00251                myf.f.samples = res / 2;
00252                if (ast_write(chan, &myf.f) < 0) {
00253                   res = -1;
00254                   ast_frfree(f);
00255                   break;
00256                }
00257                if (res < needed) { /* last frame */
00258                   ast_debug(1, "Last frame\n");
00259                   res = 0;
00260                   ast_frfree(f);
00261                   break;
00262                }
00263             } else {
00264                ast_debug(1, "No more waveform\n");
00265                res = 0;
00266             }
00267          }
00268          ast_frfree(f);
00269       }
00270    }
00271    close(fds[0]);
00272    close(fds[1]);
00273 
00274    if (!res && owriteformat)
00275       ast_set_write_format(chan, owriteformat);
00276    ao2_cleanup(owriteformat);
00277 
00278    return res;
00279 }
00280 
00281 static int festival_exec(struct ast_channel *chan, const char *vdata)
00282 {
00283    int usecache;
00284    int res = 0;
00285    struct sockaddr_in serv_addr;
00286    struct hostent *serverhost;
00287    struct ast_hostent ahp;
00288    int fd;
00289    FILE *fs;
00290    const char *host;
00291    const char *cachedir;
00292    const char *temp;
00293    const char *festivalcommand;
00294    int port = 1314;
00295    int n;
00296    char ack[4];
00297    char *waveform;
00298    int filesize;
00299    char bigstring[MAXFESTLEN];
00300    int i;
00301    struct MD5Context md5ctx;
00302    unsigned char MD5Res[16];
00303    char MD5Hex[33] = "";
00304    char koko[4] = "";
00305    char cachefile[MAXFESTLEN]="";
00306    int readcache = 0;
00307    int writecache = 0;
00308    int strln;
00309    int fdesc = -1;
00310    char buffer[16384];
00311    int seekpos = 0;  
00312    char *data; 
00313    struct ast_config *cfg;
00314    char *newfestivalcommand;
00315    struct ast_flags config_flags = { 0 };
00316    AST_DECLARE_APP_ARGS(args,
00317       AST_APP_ARG(text);
00318       AST_APP_ARG(interrupt);
00319    );
00320 
00321    if (ast_strlen_zero(vdata)) {
00322       ast_log(LOG_WARNING, "festival requires an argument (text)\n");
00323       return -1;
00324    }
00325 
00326    cfg = ast_config_load(FESTIVAL_CONFIG, config_flags);
00327    if (!cfg) {
00328       ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
00329       return -1;
00330    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
00331       ast_log(LOG_ERROR, "Config file " FESTIVAL_CONFIG " is in an invalid format.  Aborting.\n");
00332       return -1;
00333    }
00334 
00335    if (!(host = ast_variable_retrieve(cfg, "general", "host"))) {
00336       host = "localhost";
00337    }
00338    if (!(temp = ast_variable_retrieve(cfg, "general", "port"))) {
00339       port = 1314;
00340    } else {
00341       port = atoi(temp);
00342    }
00343    if (!(temp = ast_variable_retrieve(cfg, "general", "usecache"))) {
00344       usecache = 0;
00345    } else {
00346       usecache = ast_true(temp);
00347    }
00348    if (!(cachedir = ast_variable_retrieve(cfg, "general", "cachedir"))) {
00349       cachedir = "/tmp/";
00350    }
00351 
00352    data = ast_strdupa(vdata);
00353    AST_STANDARD_APP_ARGS(args, data);
00354 
00355    if (!(festivalcommand = ast_variable_retrieve(cfg, "general", "festivalcommand"))) {
00356       const char *startcmd = "(tts_textasterisk \"";
00357       const char *endcmd = "\" 'file)(quit)\n";
00358 
00359       strln = strlen(startcmd) + strlen(args.text) + strlen(endcmd) + 1;
00360       newfestivalcommand = ast_alloca(strln);
00361       snprintf(newfestivalcommand, strln, "%s%s%s", startcmd, args.text, endcmd);
00362       festivalcommand = newfestivalcommand;
00363    } else { /* This else parses the festivalcommand that we're sent from the config file for \n's, etc */
00364       int x, j;
00365       newfestivalcommand = ast_alloca(strlen(festivalcommand) + strlen(args.text) + 1);
00366 
00367       for (x = 0, j = 0; x < strlen(festivalcommand); x++) {
00368          if (festivalcommand[x] == '\\' && festivalcommand[x + 1] == 'n') {
00369             newfestivalcommand[j++] = '\n';
00370             x++;
00371          } else if (festivalcommand[x] == '\\') {
00372             newfestivalcommand[j++] = festivalcommand[x + 1];
00373             x++;
00374          } else if (festivalcommand[x] == '%' && festivalcommand[x + 1] == 's') {
00375             sprintf(&newfestivalcommand[j], "%s", args.text); /* we know it is big enough */
00376             j += strlen(args.text);
00377             x++;
00378          } else
00379             newfestivalcommand[j++] = festivalcommand[x];
00380       }
00381       newfestivalcommand[j] = '\0';
00382       festivalcommand = newfestivalcommand;
00383    }
00384    
00385    if (args.interrupt && !strcasecmp(args.interrupt, "any"))
00386       args.interrupt = AST_DIGIT_ANY;
00387 
00388    ast_debug(1, "Text passed to festival server : %s\n", args.text);
00389    /* Connect to local festival server */
00390    
00391    fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
00392 
00393    if (fd < 0) {
00394       ast_log(LOG_WARNING, "festival_client: can't get socket\n");
00395       ast_config_destroy(cfg);
00396       return -1;
00397    }
00398 
00399    memset(&serv_addr, 0, sizeof(serv_addr));
00400 
00401    if ((serv_addr.sin_addr.s_addr = inet_addr(host)) == -1) {
00402       /* its a name rather than an ipnum */
00403       serverhost = ast_gethostbyname(host, &ahp);
00404 
00405       if (serverhost == NULL) {
00406          ast_log(LOG_WARNING, "festival_client: gethostbyname failed\n");
00407          ast_config_destroy(cfg);
00408          return -1;
00409       }
00410       memmove(&serv_addr.sin_addr, serverhost->h_addr, serverhost->h_length);
00411    }
00412 
00413    serv_addr.sin_family = AF_INET;
00414    serv_addr.sin_port = htons(port);
00415 
00416    if (connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) != 0) {
00417       ast_log(LOG_WARNING, "festival_client: connect to server failed\n");
00418       ast_config_destroy(cfg);
00419       return -1;
00420    }
00421 
00422    /* Compute MD5 sum of string */
00423    MD5Init(&md5ctx);
00424    MD5Update(&md5ctx, (unsigned char *)args.text, strlen(args.text));
00425    MD5Final(MD5Res, &md5ctx);
00426    MD5Hex[0] = '\0';
00427 
00428    /* Convert to HEX and look if there is any matching file in the cache 
00429       directory */
00430    for (i = 0; i < 16; i++) {
00431       snprintf(koko, sizeof(koko), "%X", (unsigned)MD5Res[i]);
00432       strncat(MD5Hex, koko, sizeof(MD5Hex) - strlen(MD5Hex) - 1);
00433    }
00434    readcache = 0;
00435    writecache = 0;
00436    if (strlen(cachedir) + strlen(MD5Hex) + 1 <= MAXFESTLEN && (usecache == -1)) {
00437       snprintf(cachefile, sizeof(cachefile), "%s/%s", cachedir, MD5Hex);
00438       fdesc = open(cachefile, O_RDWR);
00439       if (fdesc == -1) {
00440          fdesc = open(cachefile, O_CREAT | O_RDWR, AST_FILE_MODE);
00441          if (fdesc != -1) {
00442             writecache = 1;
00443             strln = strlen(args.text);
00444             ast_debug(1, "line length : %d\n", strln);
00445                if (write(fdesc,&strln,sizeof(int)) < 0) {
00446                ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
00447             }
00448                if (write(fdesc,data,strln) < 0) {
00449                ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
00450             }
00451             seekpos = lseek(fdesc, 0, SEEK_CUR);
00452             ast_debug(1, "Seek position : %d\n", seekpos);
00453          }
00454       } else {
00455             if (read(fdesc,&strln,sizeof(int)) != sizeof(int)) {
00456             ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
00457          }
00458          ast_debug(1, "Cache file exists, strln=%d, strlen=%d\n", strln, (int)strlen(args.text));
00459          if (strlen(args.text) == strln) {
00460             ast_debug(1, "Size OK\n");
00461                if (read(fdesc,&bigstring,strln) != strln) {
00462                ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
00463             }
00464             bigstring[strln] = 0;
00465             if (strcmp(bigstring, args.text) == 0) { 
00466                readcache = 1;
00467             } else {
00468                ast_log(LOG_WARNING, "Strings do not match\n");
00469             }
00470          } else {
00471             ast_log(LOG_WARNING, "Size mismatch\n");
00472          }
00473       }
00474    }
00475 
00476    if (readcache == 1) {
00477       close(fd);
00478       fd = fdesc;
00479       ast_debug(1, "Reading from cache...\n");
00480    } else {
00481       ast_debug(1, "Passing text to festival...\n");
00482       fs = fdopen(dup(fd), "wb");
00483 
00484       fprintf(fs, "%s", festivalcommand);
00485       fflush(fs);
00486       fclose(fs);
00487    }
00488    
00489    /* Write to cache and then pass it down */
00490    if (writecache == 1) {
00491       ast_debug(1, "Writing result to cache...\n");
00492       while ((strln = read(fd, buffer, 16384)) != 0) {
00493          if (write(fdesc,buffer,strln) < 0) {
00494             ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
00495          }
00496       }
00497       close(fd);
00498       close(fdesc);
00499       fd = open(cachefile, O_RDWR);
00500       lseek(fd, seekpos, SEEK_SET);
00501    }
00502    
00503    ast_debug(1, "Passing data to channel...\n");
00504 
00505    /* Read back info from server */
00506    /* This assumes only one waveform will come back, also LP is unlikely */
00507    do {
00508       int read_data;
00509       for (n = 0; n < 3; ) {
00510          read_data = read(fd, ack + n, 3 - n);
00511          /* this avoids falling in infinite loop
00512           * in case that festival server goes down
00513           */
00514          if (read_data == -1) {
00515             ast_log(LOG_WARNING, "Unable to read from cache/festival fd\n");
00516             close(fd);
00517             ast_config_destroy(cfg);
00518             return -1;
00519          }
00520          n += read_data;
00521       }
00522       ack[3] = '\0';
00523       if (strcmp(ack, "WV\n") == 0) {         /* receive a waveform */
00524          ast_debug(1, "Festival WV command\n");
00525          if ((waveform = socket_receive_file_to_buff(fd, &filesize))) {
00526             res = send_waveform_to_channel(chan, waveform, filesize, args.interrupt);
00527             ast_free(waveform);
00528          }
00529          break;
00530       } else if (strcmp(ack, "LP\n") == 0) {   /* receive an s-expr */
00531          ast_debug(1, "Festival LP command\n");
00532          if ((waveform = socket_receive_file_to_buff(fd, &filesize))) {
00533             waveform[filesize] = '\0';
00534             ast_log(LOG_WARNING, "Festival returned LP : %s\n", waveform);
00535             ast_free(waveform);
00536          }
00537       } else if (strcmp(ack, "ER\n") == 0) {    /* server got an error */
00538          ast_log(LOG_WARNING, "Festival returned ER\n");
00539          res = -1;
00540          break;
00541       }
00542    } while (strcmp(ack, "OK\n") != 0);
00543    close(fd);
00544    ast_config_destroy(cfg);
00545    return res;
00546 }
00547 
00548 static int unload_module(void)
00549 {
00550    return ast_unregister_application(app);
00551 }
00552 
00553 /*!
00554  * \brief Load the module
00555  *
00556  * Module loading including tests for configuration or dependencies.
00557  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
00558  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
00559  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
00560  * configuration file or other non-critical problem return 
00561  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
00562  */
00563 static int load_module(void)
00564 {
00565    struct ast_flags config_flags = { 0 };
00566    struct ast_config *cfg = ast_config_load(FESTIVAL_CONFIG, config_flags);
00567    if (!cfg) {
00568       ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
00569       return AST_MODULE_LOAD_DECLINE;
00570    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
00571       ast_log(LOG_ERROR, "Config file " FESTIVAL_CONFIG " is in an invalid format.  Aborting.\n");
00572       return AST_MODULE_LOAD_DECLINE;
00573    }
00574    ast_config_destroy(cfg);
00575    return ast_register_application_xml(app, festival_exec);
00576 }
00577 
00578 AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Simple Festival Interface");
00579 

Generated on Thu Apr 16 06:27:09 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6