Version 0.3.0 from FTP
[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 <asterisk/file.h>
15 #include <asterisk/logger.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/pbx.h>
18 #include <asterisk/module.h>
19 #include <asterisk/md5.h>
20 #include <asterisk/config.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <stdio.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <pthread.h>
37
38
39 #define FESTIVAL_CONFIG "festival.conf"
40
41 static char *tdesc = "Simple Festival Interface";
42
43 static char *app = "Festival";
44
45 static char *synopsis = "Say text to the user";
46
47 static char *descrip = 
48 "  Festival():  Connect to Festival, send the argument, get back the waveform,"
49 "play it to the user.\n";
50
51 STANDARD_LOCAL_USER;
52
53 LOCAL_USER_DECL;
54
55 static char *socket_receive_file_to_buff(int fd,int *size)
56 {
57     /* Receive file (probably a waveform file) from socket using   */
58     /* Festival key stuff technique, but long winded I know, sorry */
59     /* but will receive any file without closeing the stream or    */
60     /* using OOB data                                              */
61     static char *file_stuff_key = "ft_StUfF_key"; /* must == Festival's key */
62     char *buff;
63     int bufflen;
64     int n,k,i;
65     char c;
66
67     bufflen = 1024;
68     buff = (char *)malloc(bufflen);
69     *size=0;
70
71     for (k=0; file_stuff_key[k] != '\0';)
72     {
73         n = read(fd,&c,1);
74         if (n==0) break;  /* hit stream eof before end of file */
75         if ((*size)+k+1 >= bufflen)
76         {   /* +1 so you can add a NULL if you want */
77             bufflen += bufflen/4;
78             buff = (char *)realloc(buff,bufflen);
79         }
80         if (file_stuff_key[k] == c)
81             k++;
82         else if ((c == 'X') && (file_stuff_key[k+1] == '\0'))
83         {   /* It looked like the key but wasn't */
84             for (i=0; i < k; i++,(*size)++)
85                 buff[*size] = file_stuff_key[i];
86             k=0;
87             /* omit the stuffed 'X' */
88         }
89         else
90         {
91             for (i=0; i < k; i++,(*size)++)
92                 buff[*size] = file_stuff_key[i];
93             k=0;
94             buff[*size] = c;
95             (*size)++;
96         }
97
98     }
99
100     return buff;
101 }
102
103 static int send_waveform_to_fd(char *waveform, int length, int fd) {
104
105         int res;
106         int x;
107         res = fork();
108         if (res < 0)
109                 ast_log(LOG_WARNING, "Fork failed\n");
110         if (res)
111                 return res;
112         for (x=0;x<256;x++) {
113                 if (x != fd)
114                         close(x);
115         }
116         write(fd,waveform,length);
117         write(fd,"a",1);
118         close(fd);
119         exit(0);
120 }
121
122
123 static int send_waveform_to_channel(struct ast_channel *chan, char *waveform, int length) {
124         int res=0;
125         int fds[2];
126         int rfds[1 + AST_MAX_FDS];
127         int ms = -1;
128         int pid = -1;
129         int us;
130         int exception;
131         int owriteformat;
132         struct timeval tv;
133         struct timeval last;
134         struct ast_frame *f;
135         int x;
136         struct myframe {
137                 struct ast_frame f;
138                 char offset[AST_FRIENDLY_OFFSET];
139                 char frdata[160];
140         } myf;
141         last.tv_usec = 0;
142         last.tv_sec = 0;
143         
144         if (pipe(fds)) {
145                  ast_log(LOG_WARNING, "Unable to create pipe\n");
146                 return -1;
147         }
148                                                         
149         ast_stopstream(chan);
150
151         owriteformat = chan->writeformat;
152         res = ast_set_write_format(chan, AST_FORMAT_SLINEAR);
153         if (res < 0) {
154                 ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
155                 return -1;
156         }
157         
158         res=send_waveform_to_fd(waveform,length,fds[1]);
159         if (res >= 0) {
160                 pid = res;
161                 /* Order is important -- there's almost always going to be mp3...  we want to prioritize the
162                    user */
163                 rfds[AST_MAX_FDS] = fds[0];
164                 for (;;) {
165                         CHECK_BLOCKING(chan);
166                         for (x=0;x<AST_MAX_FDS;x++) 
167                                 rfds[x] = chan->fds[x];
168                         res = ast_waitfor_n_fd(rfds, AST_MAX_FDS+1, &ms, &exception);
169                         chan->blocking = 0;
170                         if (res < 1) {
171                                 ast_log(LOG_DEBUG, "Hangup detected\n");
172                                 res = -1;
173                                 break;
174                         }
175                         for(x=0;x<AST_MAX_FDS;x++) 
176                                 if (res == chan->fds[x])
177                                         break;
178
179                         if (x < AST_MAX_FDS) {
180                                 if (exception)
181                                         chan->exception = 1;
182                                 f = ast_read(chan);
183                                 if (!f) {
184                                         ast_log(LOG_DEBUG, "Null frame == hangup() detected\n");
185                                         res = -1;
186                                         break;
187                                 }
188                                 if (f->frametype == AST_FRAME_DTMF) {
189                                         ast_log(LOG_DEBUG, "User pressed a key\n");
190                                         ast_frfree(f);
191                                         res = 0;
192                                         break;
193                                 }
194                                 ast_frfree(f);
195                         } else if (res == fds[0]) {
196                                 gettimeofday(&tv, NULL);
197                                 if (last.tv_sec || last.tv_usec) {
198                                         /* We should wait at least a frame length */
199                                         us = sizeof(myf.frdata) / 16 * 1000;
200                                         /* Subtract 1,000,000 us for each second late we've passed */
201                                         us -= (tv.tv_sec - last.tv_sec) * 1000000;
202                                         /* And one for each us late we've passed */
203                                         us -= (tv.tv_usec - last.tv_usec);
204                                         /* Sleep that long if needed */
205                                         if (us > 0)
206                                                 usleep(us);
207                                 }
208                                 last = tv;
209                                 res = read(fds[0], myf.frdata, sizeof(myf.frdata));
210                                 if (res > 0) {
211                                         myf.f.frametype = AST_FRAME_VOICE;
212                                         myf.f.subclass = AST_FORMAT_SLINEAR;
213                                         myf.f.datalen = res;
214                                         myf.f.samples = res / 2;
215                                         myf.f.mallocd = 0;
216                                         myf.f.offset = AST_FRIENDLY_OFFSET;
217                                         myf.f.src = __PRETTY_FUNCTION__;
218                                         myf.f.data = myf.frdata;
219                                         if (ast_write(chan, &myf.f) < 0) {
220                                                 res = -1;
221                                                 break;
222                                         }
223                                         if (res < sizeof(myf.frdata)) { // last frame
224                                                 ast_log(LOG_WARNING, "Last frame\n");
225                                                 res=0;
226                                                 break;
227                                         }
228                                 } else {
229                                         ast_log(LOG_WARNING, "No more waveform\n");
230                                         res = 0;
231                                 }
232                         } else {
233                                 ast_log(LOG_DEBUG, "HuhHHH?\n");
234                                 res = -1;
235                                 break;
236                         }
237                 }
238         }
239         close(fds[0]);
240         close(fds[1]);
241 //      if (pid > -1)
242 //              kill(pid, SIGKILL);
243         if (!res && owriteformat)
244                 ast_set_write_format(chan, owriteformat);
245         return res;
246 }
247
248 #define MAXLEN 180
249 #define MAXFESTLEN 2048
250
251
252
253
254 static int festival_exec(struct ast_channel *chan, void *data)
255 {
256         int usecache;
257         int res=0;
258         struct localuser *u;
259         struct sockaddr_in serv_addr;
260         struct hostent *serverhost;
261         int fd;
262         FILE *fs;
263         char *host;
264         char *cachedir;
265         char *temp;
266         char *festivalcommand;
267         int port=1314;
268         int n;
269         char ack[4];
270         char *waveform;
271         int filesize;
272         int wave;
273         char bigstring[MAXFESTLEN];
274         int i;
275         struct MD5Context md5ctx;
276         unsigned char MD5Res[16];
277         char MD5Hex[32];
278         char koko[4];
279         char cachefile[MAXFESTLEN];
280         int readcache=0;
281         int writecache=0;
282         int strln;
283         int fdesc;
284         char buffer[16384];
285         int seekpos;    
286         
287         struct ast_config *cfg;
288         cfg = ast_load(FESTIVAL_CONFIG);
289         if (!cfg) {
290                 ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
291                 return -1;
292         }
293         if (!(host = ast_variable_retrieve(cfg, "general", "host"))) {
294                 host = "localhost";
295         }
296         if (!(temp = ast_variable_retrieve(cfg, "general", "port"))) {
297                 port = 1314;
298         } else {
299                 port = atoi(temp);
300         }
301         if (!(temp = ast_variable_retrieve(cfg, "general", "usecache"))) {
302                 usecache=0;
303         } else {
304                 if (strcasecmp(temp,"yes")==0) {
305                         usecache=1;
306                 }
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 }