3ccacb195b9aaf2bcf1e2e4e6b7874c3bcc17742
[asterisk/asterisk.git] / apps / app_festival.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2002, Christos Ricudis
5  *
6  * Christos Ricudis <ricudis@itc.auth.gr>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Connect to festival
22  *
23  * \author Christos Ricudis <ricudis@itc.auth.gr>
24  *
25  * \extref  The Festival Speech Synthesis System - http://www.cstr.ed.ac.uk/projects/festival/
26  * 
27  * \ingroup applications
28  */
29
30 /*! \li \ref app_festival.c uses the configuration file \ref festival.conf
31  * \addtogroup configuration_file Configuration Files
32  */
33
34 /*! 
35  * \page festival.conf festival.conf
36  * \verbinclude festival.conf.sample
37  */
38
39 /*** MODULEINFO
40         <support_level>extended</support_level>
41  ***/
42
43 #include "asterisk.h"
44
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
46
47 #include <sys/socket.h>
48 #include <netdb.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 #include <signal.h>
52 #include <fcntl.h>
53 #include <ctype.h>
54 #include <errno.h>
55
56 #include "asterisk/file.h"
57 #include "asterisk/channel.h"
58 #include "asterisk/pbx.h"
59 #include "asterisk/module.h"
60 #include "asterisk/md5.h"
61 #include "asterisk/config.h"
62 #include "asterisk/utils.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/app.h"
65 #include "asterisk/endian.h"
66
67 #define FESTIVAL_CONFIG "festival.conf"
68 #define MAXLEN 180
69 #define MAXFESTLEN 2048
70
71 /*** DOCUMENTATION
72         <application name="Festival" language="en_US">
73                 <synopsis>
74                         Say text to the user.
75                 </synopsis>
76                 <syntax>
77                         <parameter name="text" required="true" />
78                         <parameter name="intkeys" />
79                 </syntax>
80                 <description>
81                         <para>Connect to Festival, send the argument, get back the waveform, play it to the user,
82                         allowing any given interrupt keys to immediately terminate and return the value, or
83                         <literal>any</literal> to allow any number back (useful in dialplan).</para>
84                 </description>
85         </application>
86  ***/
87
88 static char *app = "Festival";
89
90 static char *socket_receive_file_to_buff(int fd, int *size)
91 {
92         /* Receive file (probably a waveform file) from socket using
93          * Festival key stuff technique, but long winded I know, sorry
94          * but will receive any file without closing the stream or
95          * using OOB data
96          */
97         static char *file_stuff_key = "ft_StUfF_key"; /* must == Festival's key */
98         char *buff, *tmp;
99         int bufflen;
100         int n,k,i;
101         char c;
102
103         bufflen = 1024;
104         if (!(buff = ast_malloc(bufflen)))
105                 return NULL;
106         *size = 0;
107
108         for (k = 0; file_stuff_key[k] != '\0';) {
109                 n = read(fd, &c, 1);
110                 if (n == 0)
111                         break;  /* hit stream eof before end of file */
112                 if ((*size) + k + 1 >= bufflen) {
113                         /* +1 so you can add a terminating NULL if you want */
114                         bufflen += bufflen / 4;
115                         if (!(tmp = ast_realloc(buff, bufflen))) {
116                                 ast_free(buff);
117                                 return NULL;
118                         }
119                         buff = tmp;
120                 }
121                 if (file_stuff_key[k] == c)
122                         k++;
123                 else if ((c == 'X') && (file_stuff_key[k+1] == '\0')) {
124                         /* It looked like the key but wasn't */
125                         for (i = 0; i < k; i++, (*size)++)
126                                 buff[*size] = file_stuff_key[i];
127                         k = 0;
128                         /* omit the stuffed 'X' */
129                 } else {
130                         for (i = 0; i < k; i++, (*size)++)
131                                 buff[*size] = file_stuff_key[i];
132                         k = 0;
133                         buff[*size] = c;
134                         (*size)++;
135                 }
136         }
137
138         return buff;
139 }
140
141 static int send_waveform_to_fd(char *waveform, int length, int fd)
142 {
143         int res;
144 #if __BYTE_ORDER == __BIG_ENDIAN
145         int x;
146         char c;
147 #endif
148
149         res = ast_safe_fork(0);
150         if (res < 0)
151                 ast_log(LOG_WARNING, "Fork failed\n");
152         if (res) {
153                 return res;
154         }
155         dup2(fd, 0);
156         ast_close_fds_above_n(0);
157         if (ast_opt_high_priority)
158                 ast_set_priority(0);
159 #if __BYTE_ORDER == __BIG_ENDIAN
160         for (x = 0; x < length; x += 2) {
161                 c = *(waveform + x + 1);
162                 *(waveform + x + 1) = *(waveform + x);
163                 *(waveform + x) = c;
164         }
165 #endif
166
167         if (write(0, waveform, length) < 0) {
168                 /* Cannot log -- all FDs are already closed */
169         }
170
171         close(fd);
172         _exit(0);
173 }
174
175 static int send_waveform_to_channel(struct ast_channel *chan, char *waveform, int length, char *intkeys)
176 {
177         int res = 0;
178         int fds[2];
179         int needed = 0;
180         struct ast_format owriteformat;
181         struct ast_frame *f;
182         struct myframe {
183                 struct ast_frame f;
184                 char offset[AST_FRIENDLY_OFFSET];
185                 char frdata[2048];
186         } myf = {
187                 .f = { 0, },
188         };
189
190         ast_format_clear(&owriteformat);
191         if (pipe(fds)) {
192                 ast_log(LOG_WARNING, "Unable to create pipe\n");
193                 return -1;
194         }
195
196         /* Answer if it's not already going */
197         if (ast_channel_state(chan) != AST_STATE_UP)
198                 ast_answer(chan);
199         ast_stopstream(chan);
200         ast_indicate(chan, -1);
201         
202         ast_format_copy(&owriteformat, ast_channel_writeformat(chan));
203         res = ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR);
204         if (res < 0) {
205                 ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
206                 return -1;
207         }
208         
209         res = send_waveform_to_fd(waveform, length, fds[1]);
210         if (res >= 0) {
211                 /* Order is important -- there's almost always going to be mp3...  we want to prioritize the
212                    user */
213                 for (;;) {
214                         res = ast_waitfor(chan, 1000);
215                         if (res < 1) {
216                                 res = -1;
217                                 break;
218                         }
219                         f = ast_read(chan);
220                         if (!f) {
221                                 ast_log(LOG_WARNING, "Null frame == hangup() detected\n");
222                                 res = -1;
223                                 break;
224                         }
225                         if (f->frametype == AST_FRAME_DTMF) {
226                                 ast_debug(1, "User pressed a key\n");
227                                 if (intkeys && strchr(intkeys, f->subclass.integer)) {
228                                         res = f->subclass.integer;
229                                         ast_frfree(f);
230                                         break;
231                                 }
232                         }
233                         if (f->frametype == AST_FRAME_VOICE) {
234                                 /* Treat as a generator */
235                                 needed = f->samples * 2;
236                                 if (needed > sizeof(myf.frdata)) {
237                                         ast_log(LOG_WARNING, "Only able to deliver %d of %d requested samples\n",
238                                                 (int)sizeof(myf.frdata) / 2, needed/2);
239                                         needed = sizeof(myf.frdata);
240                                 }
241                                 res = read(fds[0], myf.frdata, needed);
242                                 if (res > 0) {
243                                         myf.f.frametype = AST_FRAME_VOICE;
244                                         ast_format_set(&myf.f.subclass.format, AST_FORMAT_SLINEAR, 0);
245                                         myf.f.datalen = res;
246                                         myf.f.samples = res / 2;
247                                         myf.f.offset = AST_FRIENDLY_OFFSET;
248                                         myf.f.src = __PRETTY_FUNCTION__;
249                                         myf.f.data.ptr = myf.frdata;
250                                         if (ast_write(chan, &myf.f) < 0) {
251                                                 res = -1;
252                                                 ast_frfree(f);
253                                                 break;
254                                         }
255                                         if (res < needed) { /* last frame */
256                                                 ast_debug(1, "Last frame\n");
257                                                 res = 0;
258                                                 ast_frfree(f);
259                                                 break;
260                                         }
261                                 } else {
262                                         ast_debug(1, "No more waveform\n");
263                                         res = 0;
264                                 }
265                         }
266                         ast_frfree(f);
267                 }
268         }
269         close(fds[0]);
270         close(fds[1]);
271
272         if (!res && owriteformat.id)
273                 ast_set_write_format(chan, &owriteformat);
274         return res;
275 }
276
277 static int festival_exec(struct ast_channel *chan, const char *vdata)
278 {
279         int usecache;
280         int res = 0;
281         struct sockaddr_in serv_addr;
282         struct hostent *serverhost;
283         struct ast_hostent ahp;
284         int fd;
285         FILE *fs;
286         const char *host;
287         const char *cachedir;
288         const char *temp;
289         const char *festivalcommand;
290         int port = 1314;
291         int n;
292         char ack[4];
293         char *waveform;
294         int filesize;
295         char bigstring[MAXFESTLEN];
296         int i;
297         struct MD5Context md5ctx;
298         unsigned char MD5Res[16];
299         char MD5Hex[33] = "";
300         char koko[4] = "";
301         char cachefile[MAXFESTLEN]="";
302         int readcache = 0;
303         int writecache = 0;
304         int strln;
305         int fdesc = -1;
306         char buffer[16384];
307         int seekpos = 0;        
308         char *data;     
309         struct ast_config *cfg;
310         char *newfestivalcommand;
311         struct ast_flags config_flags = { 0 };
312         AST_DECLARE_APP_ARGS(args,
313                 AST_APP_ARG(text);
314                 AST_APP_ARG(interrupt);
315         );
316
317         if (ast_strlen_zero(vdata)) {
318                 ast_log(LOG_WARNING, "festival requires an argument (text)\n");
319                 return -1;
320         }
321
322         cfg = ast_config_load(FESTIVAL_CONFIG, config_flags);
323         if (!cfg) {
324                 ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
325                 return -1;
326         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
327                 ast_log(LOG_ERROR, "Config file " FESTIVAL_CONFIG " is in an invalid format.  Aborting.\n");
328                 return -1;
329         }
330
331         if (!(host = ast_variable_retrieve(cfg, "general", "host"))) {
332                 host = "localhost";
333         }
334         if (!(temp = ast_variable_retrieve(cfg, "general", "port"))) {
335                 port = 1314;
336         } else {
337                 port = atoi(temp);
338         }
339         if (!(temp = ast_variable_retrieve(cfg, "general", "usecache"))) {
340                 usecache = 0;
341         } else {
342                 usecache = ast_true(temp);
343         }
344         if (!(cachedir = ast_variable_retrieve(cfg, "general", "cachedir"))) {
345                 cachedir = "/tmp/";
346         }
347
348         data = ast_strdupa(vdata);
349         AST_STANDARD_APP_ARGS(args, data);
350
351         if (!(festivalcommand = ast_variable_retrieve(cfg, "general", "festivalcommand"))) {
352                 const char *startcmd = "(tts_textasterisk \"";
353                 const char *endcmd = "\" 'file)(quit)\n";
354
355                 strln = strlen(startcmd) + strlen(args.text) + strlen(endcmd) + 1;
356                 newfestivalcommand = ast_alloca(strln);
357                 snprintf(newfestivalcommand, strln, "%s%s%s", startcmd, args.text, endcmd);
358                 festivalcommand = newfestivalcommand;
359         } else { /* This else parses the festivalcommand that we're sent from the config file for \n's, etc */
360                 int x, j;
361                 newfestivalcommand = ast_alloca(strlen(festivalcommand) + strlen(args.text) + 1);
362
363                 for (x = 0, j = 0; x < strlen(festivalcommand); x++) {
364                         if (festivalcommand[x] == '\\' && festivalcommand[x + 1] == 'n') {
365                                 newfestivalcommand[j++] = '\n';
366                                 x++;
367                         } else if (festivalcommand[x] == '\\') {
368                                 newfestivalcommand[j++] = festivalcommand[x + 1];
369                                 x++;
370                         } else if (festivalcommand[x] == '%' && festivalcommand[x + 1] == 's') {
371                                 sprintf(&newfestivalcommand[j], "%s", args.text); /* we know it is big enough */
372                                 j += strlen(args.text);
373                                 x++;
374                         } else
375                                 newfestivalcommand[j++] = festivalcommand[x];
376                 }
377                 newfestivalcommand[j] = '\0';
378                 festivalcommand = newfestivalcommand;
379         }
380         
381         if (args.interrupt && !strcasecmp(args.interrupt, "any"))
382                 args.interrupt = AST_DIGIT_ANY;
383
384         ast_debug(1, "Text passed to festival server : %s\n", args.text);
385         /* Connect to local festival server */
386         
387         fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
388
389         if (fd < 0) {
390                 ast_log(LOG_WARNING, "festival_client: can't get socket\n");
391                 ast_config_destroy(cfg);
392                 return -1;
393         }
394
395         memset(&serv_addr, 0, sizeof(serv_addr));
396
397         if ((serv_addr.sin_addr.s_addr = inet_addr(host)) == -1) {
398                 /* its a name rather than an ipnum */
399                 serverhost = ast_gethostbyname(host, &ahp);
400
401                 if (serverhost == NULL) {
402                         ast_log(LOG_WARNING, "festival_client: gethostbyname failed\n");
403                         ast_config_destroy(cfg);
404                         return -1;
405                 }
406                 memmove(&serv_addr.sin_addr, serverhost->h_addr, serverhost->h_length);
407         }
408
409         serv_addr.sin_family = AF_INET;
410         serv_addr.sin_port = htons(port);
411
412         if (connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) != 0) {
413                 ast_log(LOG_WARNING, "festival_client: connect to server failed\n");
414                 ast_config_destroy(cfg);
415                 return -1;
416         }
417
418         /* Compute MD5 sum of string */
419         MD5Init(&md5ctx);
420         MD5Update(&md5ctx, (unsigned char *)args.text, strlen(args.text));
421         MD5Final(MD5Res, &md5ctx);
422         MD5Hex[0] = '\0';
423
424         /* Convert to HEX and look if there is any matching file in the cache 
425                 directory */
426         for (i = 0; i < 16; i++) {
427                 snprintf(koko, sizeof(koko), "%X", (unsigned)MD5Res[i]);
428                 strncat(MD5Hex, koko, sizeof(MD5Hex) - strlen(MD5Hex) - 1);
429         }
430         readcache = 0;
431         writecache = 0;
432         if (strlen(cachedir) + strlen(MD5Hex) + 1 <= MAXFESTLEN && (usecache == -1)) {
433                 snprintf(cachefile, sizeof(cachefile), "%s/%s", cachedir, MD5Hex);
434                 fdesc = open(cachefile, O_RDWR);
435                 if (fdesc == -1) {
436                         fdesc = open(cachefile, O_CREAT | O_RDWR, AST_FILE_MODE);
437                         if (fdesc != -1) {
438                                 writecache = 1;
439                                 strln = strlen(args.text);
440                                 ast_debug(1, "line length : %d\n", strln);
441                                 if (write(fdesc,&strln,sizeof(int)) < 0) {
442                                         ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
443                                 }
444                                 if (write(fdesc,data,strln) < 0) {
445                                         ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
446                                 }
447                                 seekpos = lseek(fdesc, 0, SEEK_CUR);
448                                 ast_debug(1, "Seek position : %d\n", seekpos);
449                         }
450                 } else {
451                         if (read(fdesc,&strln,sizeof(int)) != sizeof(int)) {
452                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
453                         }
454                         ast_debug(1, "Cache file exists, strln=%d, strlen=%d\n", strln, (int)strlen(args.text));
455                         if (strlen(args.text) == strln) {
456                                 ast_debug(1, "Size OK\n");
457                                 if (read(fdesc,&bigstring,strln) != strln) {
458                                         ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
459                                 }
460                                 bigstring[strln] = 0;
461                                 if (strcmp(bigstring, args.text) == 0) { 
462                                         readcache = 1;
463                                 } else {
464                                         ast_log(LOG_WARNING, "Strings do not match\n");
465                                 }
466                         } else {
467                                 ast_log(LOG_WARNING, "Size mismatch\n");
468                         }
469                 }
470         }
471
472         if (readcache == 1) {
473                 close(fd);
474                 fd = fdesc;
475                 ast_debug(1, "Reading from cache...\n");
476         } else {
477                 ast_debug(1, "Passing text to festival...\n");
478                 fs = fdopen(dup(fd), "wb");
479
480                 fprintf(fs, "%s", festivalcommand);
481                 fflush(fs);
482                 fclose(fs);
483         }
484         
485         /* Write to cache and then pass it down */
486         if (writecache == 1) {
487                 ast_debug(1, "Writing result to cache...\n");
488                 while ((strln = read(fd, buffer, 16384)) != 0) {
489                         if (write(fdesc,buffer,strln) < 0) {
490                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
491                         }
492                 }
493                 close(fd);
494                 close(fdesc);
495                 fd = open(cachefile, O_RDWR);
496                 lseek(fd, seekpos, SEEK_SET);
497         }
498         
499         ast_debug(1, "Passing data to channel...\n");
500
501         /* Read back info from server */
502         /* This assumes only one waveform will come back, also LP is unlikely */
503         do {
504                 int read_data;
505                 for (n = 0; n < 3; ) {
506                         read_data = read(fd, ack + n, 3 - n);
507                         /* this avoids falling in infinite loop
508                          * in case that festival server goes down
509                          */
510                         if (read_data == -1) {
511                                 ast_log(LOG_WARNING, "Unable to read from cache/festival fd\n");
512                                 close(fd);
513                                 ast_config_destroy(cfg);
514                                 return -1;
515                         }
516                         n += read_data;
517                 }
518                 ack[3] = '\0';
519                 if (strcmp(ack, "WV\n") == 0) {         /* receive a waveform */
520                         ast_debug(1, "Festival WV command\n");
521                         if ((waveform = socket_receive_file_to_buff(fd, &filesize))) {
522                                 res = send_waveform_to_channel(chan, waveform, filesize, args.interrupt);
523                                 ast_free(waveform);
524                         }
525                         break;
526                 } else if (strcmp(ack, "LP\n") == 0) {   /* receive an s-expr */
527                         ast_debug(1, "Festival LP command\n");
528                         if ((waveform = socket_receive_file_to_buff(fd, &filesize))) {
529                                 waveform[filesize] = '\0';
530                                 ast_log(LOG_WARNING, "Festival returned LP : %s\n", waveform);
531                                 ast_free(waveform);
532                         }
533                 } else if (strcmp(ack, "ER\n") == 0) {    /* server got an error */
534                         ast_log(LOG_WARNING, "Festival returned ER\n");
535                         res = -1;
536                         break;
537                 }
538         } while (strcmp(ack, "OK\n") != 0);
539         close(fd);
540         ast_config_destroy(cfg);
541         return res;
542 }
543
544 static int unload_module(void)
545 {
546         return ast_unregister_application(app);
547 }
548
549 /*!
550  * \brief Load the module
551  *
552  * Module loading including tests for configuration or dependencies.
553  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
554  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
555  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
556  * configuration file or other non-critical problem return 
557  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
558  */
559 static int load_module(void)
560 {
561         struct ast_flags config_flags = { 0 };
562         struct ast_config *cfg = ast_config_load(FESTIVAL_CONFIG, config_flags);
563         if (!cfg) {
564                 ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
565                 return AST_MODULE_LOAD_DECLINE;
566         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
567                 ast_log(LOG_ERROR, "Config file " FESTIVAL_CONFIG " is in an invalid format.  Aborting.\n");
568                 return AST_MODULE_LOAD_DECLINE;
569         }
570         ast_config_destroy(cfg);
571         return ast_register_application_xml(app, festival_exec);
572 }
573
574 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Simple Festival Interface");