Minor cleanups
[asterisk/asterisk.git] / apps / app_festival.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Connect to festival
5  * 
6  * Copyright (C) 2002, Christos Ricudis
7  *
8  * Christos Ricudis <ricudis@paiko.gr>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <sys/types.h>
15 #include <asterisk/file.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/channel.h>
18 #include <asterisk/pbx.h>
19 #include <asterisk/module.h>
20 #include <asterisk/md5.h>
21 #include <asterisk/config.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netdb.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <stdio.h>
32 #include <signal.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <ctype.h>
37 #include <pthread.h>
38
39
40 #define FESTIVAL_CONFIG "festival.conf"
41
42 static char *tdesc = "Simple Festival Interface";
43
44 static char *app = "Festival";
45
46 static char *synopsis = "Say text to the user";
47
48 static char *descrip = 
49 "  Festival(text[|intkeys]):  Connect to Festival, send the argument, get back the waveform,"
50 "play it to the user, allowing any given interrupt keys to immediately terminate and return\n"
51 "the value.\n";
52
53 STANDARD_LOCAL_USER;
54
55 LOCAL_USER_DECL;
56
57 static char *socket_receive_file_to_buff(int fd,int *size)
58 {
59     /* Receive file (probably a waveform file) from socket using   */
60     /* Festival key stuff technique, but long winded I know, sorry */
61     /* but will receive any file without closeing the stream or    */
62     /* using OOB data                                              */
63     static char *file_stuff_key = "ft_StUfF_key"; /* must == Festival's key */
64     char *buff;
65     int bufflen;
66     int n,k,i;
67     char c;
68
69     bufflen = 1024;
70     buff = (char *)malloc(bufflen);
71     *size=0;
72
73     for (k=0; file_stuff_key[k] != '\0';)
74     {
75         n = read(fd,&c,1);
76         if (n==0) break;  /* hit stream eof before end of file */
77         if ((*size)+k+1 >= bufflen)
78         {   /* +1 so you can add a NULL if you want */
79             bufflen += bufflen/4;
80             buff = (char *)realloc(buff,bufflen);
81         }
82         if (file_stuff_key[k] == c)
83             k++;
84         else if ((c == 'X') && (file_stuff_key[k+1] == '\0'))
85         {   /* It looked like the key but wasn't */
86             for (i=0; i < k; i++,(*size)++)
87                 buff[*size] = file_stuff_key[i];
88             k=0;
89             /* omit the stuffed 'X' */
90         }
91         else
92         {
93             for (i=0; i < k; i++,(*size)++)
94                 buff[*size] = file_stuff_key[i];
95             k=0;
96             buff[*size] = c;
97             (*size)++;
98         }
99
100     }
101
102     return buff;
103 }
104
105 static int send_waveform_to_fd(char *waveform, int length, int fd) {
106
107         int res;
108         int x;
109         res = fork();
110         if (res < 0)
111                 ast_log(LOG_WARNING, "Fork failed\n");
112         if (res)
113                 return res;
114         for (x=0;x<256;x++) {
115                 if (x != fd)
116                         close(x);
117         }
118         write(fd,waveform,length);
119         write(fd,"a",1);
120         close(fd);
121         exit(0);
122 }
123
124
125 static int send_waveform_to_channel(struct ast_channel *chan, char *waveform, int length) {
126         int res=0;
127         int fds[2];
128         int rfds[1 + AST_MAX_FDS];
129         int ms = -1;
130         int pid = -1;
131         int us;
132         int exception;
133         int owriteformat;
134         struct timeval tv;
135         struct timeval last;
136         struct ast_frame *f;
137         int x;
138         struct myframe {
139                 struct ast_frame f;
140                 char offset[AST_FRIENDLY_OFFSET];
141                 char frdata[160];
142         } myf;
143         last.tv_usec = 0;
144         last.tv_sec = 0;
145         
146         if (pipe(fds)) {
147                  ast_log(LOG_WARNING, "Unable to create pipe\n");
148                 return -1;
149         }
150                                                         
151         ast_stopstream(chan);
152
153         owriteformat = chan->writeformat;
154         res = ast_set_write_format(chan, AST_FORMAT_SLINEAR);
155         if (res < 0) {
156                 ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
157                 return -1;
158         }
159         
160         res=send_waveform_to_fd(waveform,length,fds[1]);
161         if (res >= 0) {
162                 pid = res;
163                 /* Order is important -- there's almost always going to be mp3...  we want to prioritize the
164                    user */
165                 rfds[AST_MAX_FDS] = fds[0];
166                 for (;;) {
167                         CHECK_BLOCKING(chan);
168                         for (x=0;x<AST_MAX_FDS;x++) 
169                                 rfds[x] = chan->fds[x];
170                         res = ast_waitfor_n_fd(rfds, AST_MAX_FDS+1, &ms, &exception);
171                         chan->blocking = 0;
172                         if (res < 1) {
173                                 ast_log(LOG_DEBUG, "Hangup detected\n");
174                                 res = -1;
175                                 break;
176                         }
177                         for(x=0;x<AST_MAX_FDS;x++) 
178                                 if (res == chan->fds[x])
179                                         break;
180
181                         if (x < AST_MAX_FDS) {
182                                 if (exception)
183                                         chan->exception = 1;
184                                 f = ast_read(chan);
185                                 if (!f) {
186                                         ast_log(LOG_DEBUG, "Null frame == hangup() detected\n");
187                                         res = -1;
188                                         break;
189                                 }
190                                 if (f->frametype == AST_FRAME_DTMF) {
191                                         ast_log(LOG_DEBUG, "User pressed a key\n");
192                                         ast_frfree(f);
193                                         res = 0;
194                                         break;
195                                 }
196                                 ast_frfree(f);
197                         } else if (res == fds[0]) {
198                                 gettimeofday(&tv, NULL);
199                                 if (last.tv_sec || last.tv_usec) {
200                                         /* We should wait at least a frame length */
201                                         us = sizeof(myf.frdata) / 16 * 1000;
202                                         /* Subtract 1,000,000 us for each second late we've passed */
203                                         us -= (tv.tv_sec - last.tv_sec) * 1000000;
204                                         /* And one for each us late we've passed */
205                                         us -= (tv.tv_usec - last.tv_usec);
206                                         /* Sleep that long if needed */
207                                         if (us > 0)
208                                                 usleep(us);
209                                 }
210                                 last = tv;
211                                 res = read(fds[0], myf.frdata, sizeof(myf.frdata));
212                                 if (res > 0) {
213                                         myf.f.frametype = AST_FRAME_VOICE;
214                                         myf.f.subclass = AST_FORMAT_SLINEAR;
215                                         myf.f.datalen = res;
216                                         myf.f.samples = res / 2;
217                                         myf.f.mallocd = 0;
218                                         myf.f.offset = AST_FRIENDLY_OFFSET;
219                                         myf.f.src = __PRETTY_FUNCTION__;
220                                         myf.f.data = myf.frdata;
221                                         if (ast_write(chan, &myf.f) < 0) {
222                                                 res = -1;
223                                                 break;
224                                         }
225                                         if (res < sizeof(myf.frdata)) { // last frame
226                                                 ast_log(LOG_WARNING, "Last frame\n");
227                                                 res=0;
228                                                 break;
229                                         }
230                                 } else {
231                                         ast_log(LOG_WARNING, "No more waveform\n");
232                                         res = 0;
233                                 }
234                         } else {
235                                 ast_log(LOG_DEBUG, "HuhHHH?\n");
236                                 res = -1;
237                                 break;
238                         }
239                 }
240         }
241         close(fds[0]);
242         close(fds[1]);
243 //      if (pid > -1)
244 //              kill(pid, SIGKILL);
245         if (!res && owriteformat)
246                 ast_set_write_format(chan, owriteformat);
247         return res;
248 }
249
250 #define MAXLEN 180
251 #define MAXFESTLEN 2048
252
253
254
255
256 static int festival_exec(struct ast_channel *chan, void *data)
257 {
258         int usecache;
259         int res=0;
260         struct localuser *u;
261         struct sockaddr_in serv_addr;
262         struct hostent *serverhost;
263         int fd;
264         FILE *fs;
265         char *host;
266         char *cachedir;
267         char *temp;
268         char *festivalcommand;
269         int port=1314;
270         int n;
271         char ack[4];
272         char *waveform;
273         int filesize;
274         int wave;
275         char bigstring[MAXFESTLEN];
276         int i;
277         struct MD5Context md5ctx;
278         unsigned char MD5Res[16];
279         char MD5Hex[32];
280         char koko[4];
281         char cachefile[MAXFESTLEN];
282         int readcache=0;
283         int writecache=0;
284         int strln;
285         int fdesc;
286         char buffer[16384];
287         int seekpos;    
288         
289         struct ast_config *cfg;
290         cfg = ast_load(FESTIVAL_CONFIG);
291         if (!cfg) {
292                 ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
293                 return -1;
294         }
295         if (!(host = ast_variable_retrieve(cfg, "general", "host"))) {
296                 host = "localhost";
297         }
298         if (!(temp = ast_variable_retrieve(cfg, "general", "port"))) {
299                 port = 1314;
300         } else {
301                 port = atoi(temp);
302         }
303         if (!(temp = ast_variable_retrieve(cfg, "general", "usecache"))) {
304                 usecache=0;
305         } else {
306                 usecache = ast_true(temp);
307         }
308         if (!(cachedir = ast_variable_retrieve(cfg, "general", "cachedir"))) {
309                 cachedir = "/tmp/";
310         }
311         if (!(festivalcommand = ast_variable_retrieve(cfg, "general", "festivalcommand"))) {
312                 festivalcommand = "(tts_textasterisk \"%s\" 'file)(quit)\n";
313         }
314         
315                 
316
317         if (!data) {
318                 ast_log(LOG_WARNING, "festival requires an argument (text)\n");
319                 return -1;
320         }
321         LOCAL_USER_ADD(u);
322         ast_log(LOG_WARNING, "Text passed to festival server : %s\n",(char *)data);
323         /* Connect to local festival server */
324         
325         fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
326
327         if (fd < 0) {
328                 ast_log(LOG_WARNING,"festival_client: can't get socket\n");
329                 return -1;
330         }
331         memset(&serv_addr, 0, sizeof(serv_addr));
332         if ((serv_addr.sin_addr.s_addr = inet_addr(host)) == -1) {
333                 /* its a name rather than an ipnum */
334                 serverhost = gethostbyname(host);
335                 if (serverhost == (struct hostent *)0) {
336                         ast_log(LOG_WARNING,"festival_client: gethostbyname failed\n");
337                         return -1;
338                 }
339                 memmove(&serv_addr.sin_addr,serverhost->h_addr, serverhost->h_length);
340         }
341         serv_addr.sin_family = AF_INET;
342         serv_addr.sin_port = htons(port);
343
344         if (connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) != 0) {
345                 ast_log(LOG_WARNING,"festival_client: connect to server failed\n");
346                 return -1;
347         }
348         
349         /* Compute MD5 sum of string */
350         MD5Init(&md5ctx);
351         MD5Update(&md5ctx,(unsigned char const *)data,strlen(data));
352         MD5Final(MD5Res,&md5ctx);
353         strcpy(MD5Hex,"");
354         
355         /* Convert to HEX and look if there is any matching file in the cache 
356                 directory */
357         for (i=0;i<16;i++) {
358                 sprintf(koko,"%X",MD5Res[i]);
359                 strcat(MD5Hex,koko);
360         }
361         readcache=0;
362         writecache=0;
363         if (strlen(cachedir)+strlen(MD5Hex)+1<=MAXFESTLEN && (usecache==1)) {
364                 sprintf(cachefile,"%s/%s",cachedir,MD5Hex);
365                 fdesc=open(cachefile,O_RDWR);
366                 if (fdesc==-1) {
367                         fdesc=open(cachefile,O_CREAT|O_RDWR,0);
368                         if (fdesc!=-1) {
369                                 writecache=1;
370                                 strln=strlen((char *)data);
371                                 ast_log(LOG_WARNING,"line length : %d\n",strln);
372                                 write(fdesc,&strln,sizeof(int));
373                                 write(fdesc,data,strln);
374                                 seekpos=lseek(fdesc,0,SEEK_CUR);
375                                 ast_log(LOG_WARNING,"Seek position : %d\n",seekpos);
376                         }
377                 } else {
378                         read(fdesc,&strln,sizeof(int));
379                         ast_log(LOG_WARNING,"Cache file exists, strln=%d, strlen=%d\n",strln,strlen((char *)data));
380                         if (strlen((char *)data)==strln) {
381                                 ast_log(LOG_WARNING,"Size OK\n");
382                                 read(fdesc,&bigstring,strln);
383                                 if (strcmp(bigstring,data)==0) { 
384                                         readcache=1;
385                                 } else {
386                                         ast_log(LOG_WARNING,"Strings do not match\n");
387                                 }
388                         } else {
389                                 ast_log(LOG_WARNING,"Size mismatch\n");
390                         }
391                 }
392         }
393                         
394         if (readcache==1) {
395                 close(fd);
396                 fd=fdesc;
397                 ast_log(LOG_WARNING,"Reading from cache...\n");
398         } else {
399                 ast_log(LOG_WARNING,"Passing text to festival...\n");
400                 fs=fdopen(dup(fd),"wb");
401                 fprintf(fs,festivalcommand,(char *)data);
402                 fflush(fs);
403                 fclose(fs);
404         }
405         
406         /* Write to cache and then pass it down */
407         if (writecache==1) {
408                 ast_log(LOG_WARNING,"Writing result to cache...\n");
409                 while ((strln=read(fd,buffer,16384))!=0) {
410                         write(fdesc,buffer,strln);
411                 }
412                 close(fd);
413                 close(fdesc);
414                 fd=open(cachefile,O_RDWR);
415                 lseek(fd,seekpos,SEEK_SET);
416         }
417         
418         ast_log(LOG_WARNING,"Passing data to channel...\n");
419         
420         /* Read back info from server */
421         /* This assumes only one waveform will come back, also LP is unlikely */
422         wave = 0;
423         do {
424                 for (n=0; n < 3; )
425                         n += read(fd,ack+n,3-n);
426                 ack[3] = '\0';
427                 if (strcmp(ack,"WV\n") == 0) {         /* receive a waveform */
428                         ast_log(LOG_WARNING,"Festival WV command");
429                         waveform = socket_receive_file_to_buff(fd,&filesize);
430                         send_waveform_to_channel(chan,waveform,filesize);
431                         free(waveform);
432                         res=0;
433                         break;
434                 }
435                 else if (strcmp(ack,"LP\n") == 0) {   /* receive an s-expr */
436                         ast_log(LOG_WARNING,"Festival LP command");
437                         waveform = socket_receive_file_to_buff(fd,&filesize);
438                         waveform[filesize]='\0';
439                         ast_log(LOG_WARNING,"Festival returned LP : %s\n",waveform);
440                         free(waveform);
441                 } else if (strcmp(ack,"ER\n") == 0) {    /* server got an error */
442                         ast_log(LOG_WARNING,"Festival returned ER\n");
443                         res=-1;
444                         break;
445                 }
446         } while (strcmp(ack,"OK\n") != 0);
447         close(fd);
448         LOCAL_USER_REMOVE(u);                                                                                
449         return res;
450
451 }
452
453 int unload_module(void)
454 {
455         STANDARD_HANGUP_LOCALUSERS;
456         return ast_unregister_application(app);
457 }
458
459 int load_module(void)
460 {
461         
462         return ast_register_application(app, festival_exec, synopsis, descrip);
463 }
464
465 char *description(void)
466 {
467         return tdesc;
468 }
469
470 int usecount(void)
471 {
472         int res;
473         STANDARD_USECOUNT(res);
474         return res;
475 }
476
477 char *key()
478 {
479         return ASTERISK_GPL_KEY;
480 }