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