app_festival.c 15 KB

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