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