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