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