app_festival.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. #include <sys/socket.h>
  40. #include <netdb.h>
  41. #include <netinet/in.h>
  42. #include <arpa/inet.h>
  43. #include <signal.h>
  44. #include <fcntl.h>
  45. #include <ctype.h>
  46. #include <errno.h>
  47. #include "asterisk/file.h"
  48. #include "asterisk/channel.h"
  49. #include "asterisk/pbx.h"
  50. #include "asterisk/module.h"
  51. #include "asterisk/md5.h"
  52. #include "asterisk/config.h"
  53. #include "asterisk/utils.h"
  54. #include "asterisk/lock.h"
  55. #include "asterisk/app.h"
  56. #include "asterisk/endian.h"
  57. #include "asterisk/format_cache.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. if (pipe(fds)) {
  170. ast_log(LOG_WARNING, "Unable to create pipe\n");
  171. return -1;
  172. }
  173. /* Answer if it's not already going */
  174. if (ast_channel_state(chan) != AST_STATE_UP)
  175. ast_answer(chan);
  176. ast_stopstream(chan);
  177. ast_indicate(chan, -1);
  178. owriteformat = ao2_bump(ast_channel_writeformat(chan));
  179. res = ast_set_write_format(chan, ast_format_slin);
  180. if (res < 0) {
  181. ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
  182. ao2_cleanup(owriteformat);
  183. return -1;
  184. }
  185. myf.f.frametype = AST_FRAME_VOICE;
  186. myf.f.subclass.format = ast_format_slin;
  187. myf.f.offset = AST_FRIENDLY_OFFSET;
  188. myf.f.src = __PRETTY_FUNCTION__;
  189. myf.f.data.ptr = myf.frdata;
  190. res = send_waveform_to_fd(waveform, length, fds[1]);
  191. if (res >= 0) {
  192. /* Order is important -- there's almost always going to be mp3... we want to prioritize the
  193. user */
  194. for (;;) {
  195. res = ast_waitfor(chan, 1000);
  196. if (res < 1) {
  197. res = -1;
  198. break;
  199. }
  200. f = ast_read(chan);
  201. if (!f) {
  202. ast_log(LOG_WARNING, "Null frame == hangup() detected\n");
  203. res = -1;
  204. break;
  205. }
  206. if (f->frametype == AST_FRAME_DTMF) {
  207. ast_debug(1, "User pressed a key\n");
  208. if (intkeys && strchr(intkeys, f->subclass.integer)) {
  209. res = f->subclass.integer;
  210. ast_frfree(f);
  211. break;
  212. }
  213. }
  214. if (f->frametype == AST_FRAME_VOICE) {
  215. /* Treat as a generator */
  216. needed = f->samples * 2;
  217. if (needed > sizeof(myf.frdata)) {
  218. ast_log(LOG_WARNING, "Only able to deliver %d of %d requested samples\n",
  219. (int)sizeof(myf.frdata) / 2, needed/2);
  220. needed = sizeof(myf.frdata);
  221. }
  222. res = read(fds[0], myf.frdata, needed);
  223. if (res > 0) {
  224. myf.f.datalen = res;
  225. myf.f.samples = res / 2;
  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)
  248. ast_set_write_format(chan, owriteformat);
  249. ao2_cleanup(owriteformat);
  250. return res;
  251. }
  252. static int festival_exec(struct ast_channel *chan, const char *vdata)
  253. {
  254. int usecache;
  255. int res = 0;
  256. struct sockaddr_in serv_addr;
  257. int fd;
  258. FILE *fs;
  259. const char *host;
  260. const char *cachedir;
  261. const char *temp;
  262. const char *festivalcommand;
  263. int port = 1314;
  264. int n;
  265. char ack[4];
  266. char *waveform;
  267. int filesize;
  268. char bigstring[MAXFESTLEN];
  269. int i;
  270. struct MD5Context md5ctx;
  271. unsigned char MD5Res[16];
  272. char MD5Hex[33] = "";
  273. char koko[4] = "";
  274. char cachefile[MAXFESTLEN]="";
  275. int readcache = 0;
  276. int writecache = 0;
  277. int strln;
  278. int fdesc = -1;
  279. char buffer[16384];
  280. int seekpos = 0;
  281. char *data;
  282. struct ast_config *cfg;
  283. char *newfestivalcommand;
  284. struct ast_flags config_flags = { 0 };
  285. AST_DECLARE_APP_ARGS(args,
  286. AST_APP_ARG(text);
  287. AST_APP_ARG(interrupt);
  288. );
  289. if (ast_strlen_zero(vdata)) {
  290. ast_log(LOG_WARNING, "festival requires an argument (text)\n");
  291. return -1;
  292. }
  293. cfg = ast_config_load(FESTIVAL_CONFIG, config_flags);
  294. if (!cfg) {
  295. ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
  296. return -1;
  297. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  298. ast_log(LOG_ERROR, "Config file " FESTIVAL_CONFIG " is in an invalid format. Aborting.\n");
  299. return -1;
  300. }
  301. if (!(host = ast_variable_retrieve(cfg, "general", "host"))) {
  302. host = "localhost";
  303. }
  304. if (!(temp = ast_variable_retrieve(cfg, "general", "port"))) {
  305. port = 1314;
  306. } else {
  307. port = atoi(temp);
  308. }
  309. if (!(temp = ast_variable_retrieve(cfg, "general", "usecache"))) {
  310. usecache = 0;
  311. } else {
  312. usecache = ast_true(temp);
  313. }
  314. if (!(cachedir = ast_variable_retrieve(cfg, "general", "cachedir"))) {
  315. cachedir = "/tmp/";
  316. }
  317. data = ast_strdupa(vdata);
  318. AST_STANDARD_APP_ARGS(args, data);
  319. if (!(festivalcommand = ast_variable_retrieve(cfg, "general", "festivalcommand"))) {
  320. const char *startcmd = "(tts_textasterisk \"";
  321. const char *endcmd = "\" 'file)(quit)\n";
  322. strln = strlen(startcmd) + strlen(args.text) + strlen(endcmd) + 1;
  323. newfestivalcommand = ast_alloca(strln);
  324. snprintf(newfestivalcommand, strln, "%s%s%s", startcmd, args.text, endcmd);
  325. festivalcommand = newfestivalcommand;
  326. } else { /* This else parses the festivalcommand that we're sent from the config file for \n's, etc */
  327. int x, j;
  328. newfestivalcommand = ast_alloca(strlen(festivalcommand) + strlen(args.text) + 1);
  329. for (x = 0, j = 0; x < strlen(festivalcommand); x++) {
  330. if (festivalcommand[x] == '\\' && festivalcommand[x + 1] == 'n') {
  331. newfestivalcommand[j++] = '\n';
  332. x++;
  333. } else if (festivalcommand[x] == '\\') {
  334. newfestivalcommand[j++] = festivalcommand[x + 1];
  335. x++;
  336. } else if (festivalcommand[x] == '%' && festivalcommand[x + 1] == 's') {
  337. sprintf(&newfestivalcommand[j], "%s", args.text); /* we know it is big enough */
  338. j += strlen(args.text);
  339. x++;
  340. } else
  341. newfestivalcommand[j++] = festivalcommand[x];
  342. }
  343. newfestivalcommand[j] = '\0';
  344. festivalcommand = newfestivalcommand;
  345. }
  346. if (args.interrupt && !strcasecmp(args.interrupt, "any"))
  347. args.interrupt = AST_DIGIT_ANY;
  348. ast_debug(1, "Text passed to festival server : %s\n", args.text);
  349. /* Connect to local festival server */
  350. fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  351. if (fd < 0) {
  352. ast_log(LOG_WARNING, "festival_client: can't get socket\n");
  353. ast_config_destroy(cfg);
  354. return -1;
  355. }
  356. memset(&serv_addr, 0, sizeof(serv_addr));
  357. if ((serv_addr.sin_addr.s_addr = inet_addr(host)) == -1) {
  358. /* its a name rather than an ipnum */
  359. struct ast_sockaddr addr = { {0,} };
  360. if (ast_sockaddr_resolve_first_af(&addr, host, PARSE_PORT_FORBID, AF_INET)) {
  361. ast_log(LOG_WARNING, "festival_client: ast_sockaddr_resolve_first_af() failed\n");
  362. ast_config_destroy(cfg);
  363. close(fd);
  364. return -1;
  365. }
  366. /* We'll overwrite port and family in a sec */
  367. ast_sockaddr_to_sin(&addr, &serv_addr);
  368. }
  369. serv_addr.sin_family = AF_INET;
  370. serv_addr.sin_port = htons(port);
  371. if (connect(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) != 0) {
  372. ast_log(LOG_WARNING, "festival_client: connect to server failed\n");
  373. ast_config_destroy(cfg);
  374. close(fd);
  375. return -1;
  376. }
  377. /* Compute MD5 sum of string */
  378. MD5Init(&md5ctx);
  379. MD5Update(&md5ctx, (unsigned char *)args.text, strlen(args.text));
  380. MD5Final(MD5Res, &md5ctx);
  381. MD5Hex[0] = '\0';
  382. /* Convert to HEX and look if there is any matching file in the cache
  383. directory */
  384. for (i = 0; i < 16; i++) {
  385. snprintf(koko, sizeof(koko), "%X", (unsigned)MD5Res[i]);
  386. strncat(MD5Hex, koko, sizeof(MD5Hex) - strlen(MD5Hex) - 1);
  387. }
  388. readcache = 0;
  389. writecache = 0;
  390. if (strlen(cachedir) + sizeof(MD5Hex) + 1 <= MAXFESTLEN && (usecache == -1)) {
  391. snprintf(cachefile, sizeof(cachefile), "%s/%s", cachedir, MD5Hex);
  392. fdesc = open(cachefile, O_RDWR);
  393. if (fdesc == -1) {
  394. fdesc = open(cachefile, O_CREAT | O_RDWR, AST_FILE_MODE);
  395. if (fdesc != -1) {
  396. writecache = 1;
  397. strln = strlen(args.text);
  398. ast_debug(1, "line length : %d\n", strln);
  399. if (write(fdesc,&strln,sizeof(int)) < 0) {
  400. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  401. }
  402. if (write(fdesc,data,strln) < 0) {
  403. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  404. }
  405. seekpos = lseek(fdesc, 0, SEEK_CUR);
  406. ast_debug(1, "Seek position : %d\n", seekpos);
  407. }
  408. } else {
  409. if (read(fdesc,&strln,sizeof(int)) != sizeof(int)) {
  410. ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
  411. }
  412. ast_debug(1, "Cache file exists, strln=%d, strlen=%d\n", strln, (int)strlen(args.text));
  413. if (strlen(args.text) == strln) {
  414. ast_debug(1, "Size OK\n");
  415. if (read(fdesc,&bigstring,strln) != strln) {
  416. ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
  417. }
  418. bigstring[strln] = 0;
  419. if (strcmp(bigstring, args.text) == 0) {
  420. readcache = 1;
  421. } else {
  422. ast_log(LOG_WARNING, "Strings do not match\n");
  423. }
  424. } else {
  425. ast_log(LOG_WARNING, "Size mismatch\n");
  426. }
  427. }
  428. }
  429. if (readcache == 1) {
  430. close(fd);
  431. fd = fdesc;
  432. ast_debug(1, "Reading from cache...\n");
  433. } else {
  434. ast_debug(1, "Passing text to festival...\n");
  435. fs = fdopen(dup(fd), "wb");
  436. fprintf(fs, "%s", festivalcommand);
  437. fflush(fs);
  438. fclose(fs);
  439. }
  440. /* Write to cache and then pass it down */
  441. if (writecache == 1) {
  442. ast_debug(1, "Writing result to cache...\n");
  443. while ((strln = read(fd, buffer, 16384)) != 0) {
  444. if (write(fdesc,buffer,strln) < 0) {
  445. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  446. }
  447. }
  448. close(fd);
  449. close(fdesc);
  450. fd = open(cachefile, O_RDWR);
  451. lseek(fd, seekpos, SEEK_SET);
  452. }
  453. ast_debug(1, "Passing data to channel...\n");
  454. /* Read back info from server */
  455. /* This assumes only one waveform will come back, also LP is unlikely */
  456. do {
  457. int read_data;
  458. for (n = 0; n < 3; ) {
  459. read_data = read(fd, ack + n, 3 - n);
  460. /* this avoids falling in infinite loop
  461. * in case that festival server goes down
  462. */
  463. if (read_data == -1) {
  464. ast_log(LOG_WARNING, "Unable to read from cache/festival fd\n");
  465. close(fd);
  466. ast_config_destroy(cfg);
  467. return -1;
  468. }
  469. n += read_data;
  470. }
  471. ack[3] = '\0';
  472. if (strcmp(ack, "WV\n") == 0) { /* receive a waveform */
  473. ast_debug(1, "Festival WV command\n");
  474. if ((waveform = socket_receive_file_to_buff(fd, &filesize))) {
  475. res = send_waveform_to_channel(chan, waveform, filesize, args.interrupt);
  476. ast_free(waveform);
  477. }
  478. break;
  479. } else if (strcmp(ack, "LP\n") == 0) { /* receive an s-expr */
  480. ast_debug(1, "Festival LP command\n");
  481. if ((waveform = socket_receive_file_to_buff(fd, &filesize))) {
  482. waveform[filesize] = '\0';
  483. ast_log(LOG_WARNING, "Festival returned LP : %s\n", waveform);
  484. ast_free(waveform);
  485. }
  486. } else if (strcmp(ack, "ER\n") == 0) { /* server got an error */
  487. ast_log(LOG_WARNING, "Festival returned ER\n");
  488. res = -1;
  489. break;
  490. }
  491. } while (strcmp(ack, "OK\n") != 0);
  492. close(fd);
  493. ast_config_destroy(cfg);
  494. return res;
  495. }
  496. static int unload_module(void)
  497. {
  498. return ast_unregister_application(app);
  499. }
  500. /*!
  501. * \brief Load the module
  502. *
  503. * Module loading including tests for configuration or dependencies.
  504. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  505. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  506. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  507. * configuration file or other non-critical problem return
  508. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  509. */
  510. static int load_module(void)
  511. {
  512. struct ast_flags config_flags = { 0 };
  513. struct ast_config *cfg = ast_config_load(FESTIVAL_CONFIG, config_flags);
  514. if (!cfg) {
  515. ast_log(LOG_WARNING, "No such configuration file %s\n", FESTIVAL_CONFIG);
  516. return AST_MODULE_LOAD_DECLINE;
  517. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  518. ast_log(LOG_ERROR, "Config file " FESTIVAL_CONFIG " is in an invalid format. Aborting.\n");
  519. return AST_MODULE_LOAD_DECLINE;
  520. }
  521. ast_config_destroy(cfg);
  522. return ast_register_application_xml(app, festival_exec);
  523. }
  524. AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Simple Festival Interface");