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