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