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