app_festival.c 15 KB

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