eSpeak NG is an open source speech synthesizer that supports more than hundred languages and accents.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mbrowrap.c 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*
  2. * mbrowrap -- A wrapper library around the mbrola binary
  3. * providing a subset of the API from the Windows mbrola DLL.
  4. *
  5. * Copyright (C) 2005 to 2013 by Jonathan Duddington
  6. * Copyright (C) 2010 by Nicolas Pitre <[email protected]>
  7. * Copyright (C) 2013-2016 Reece H. Dunn
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. */
  19. #include "config.h"
  20. #if defined(_WIN32) || defined(_WIN64)
  21. #include <windows.h>
  22. #endif
  23. #include "mbrowrap.h"
  24. int (WINAPI *init_MBR)(char *voice_path);
  25. void (WINAPI *close_MBR)(void);
  26. void (WINAPI *reset_MBR)(void);
  27. int (WINAPI *read_MBR)(short *buffer, int nb_samples);
  28. int (WINAPI *write_MBR)(char *data);
  29. int (WINAPI *flush_MBR)(void);
  30. int (WINAPI *getFreq_MBR)(void);
  31. void (WINAPI *setVolumeRatio_MBR)(float value);
  32. char * (WINAPI *lastErrorStr_MBR)(char *buffer, int bufsize);
  33. void (WINAPI *setNoError_MBR)(int no_error);
  34. #if defined(_WIN32) || defined(_WIN64)
  35. HINSTANCE hinstDllMBR = NULL;
  36. BOOL load_MBR()
  37. {
  38. if (hinstDllMBR != NULL)
  39. return TRUE; // already loaded
  40. if ((hinstDllMBR = LoadLibraryA("mbrola.dll")) == 0)
  41. return FALSE;
  42. init_MBR = (void *)GetProcAddress(hinstDllMBR, "init_MBR");
  43. write_MBR = (void *)GetProcAddress(hinstDllMBR, "write_MBR");
  44. flush_MBR = (void *)GetProcAddress(hinstDllMBR, "flush_MBR");
  45. read_MBR = (void *)GetProcAddress(hinstDllMBR, "read_MBR");
  46. close_MBR = (void *)GetProcAddress(hinstDllMBR, "close_MBR");
  47. reset_MBR = (void *)GetProcAddress(hinstDllMBR, "reset_MBR");
  48. lastErrorStr_MBR = (void *)GetProcAddress(hinstDllMBR, "lastErrorStr_MBR");
  49. setNoError_MBR = (void *)GetProcAddress(hinstDllMBR, "setNoError_MBR");
  50. setVolumeRatio_MBR = (void *)GetProcAddress(hinstDllMBR, "setVolumeRatio_MBR");
  51. return TRUE;
  52. }
  53. void unload_MBR()
  54. {
  55. if (hinstDllMBR) {
  56. FreeLibrary(hinstDllMBR);
  57. hinstDllMBR = NULL;
  58. }
  59. }
  60. #else
  61. #include <errno.h>
  62. #include <fcntl.h>
  63. #include <poll.h>
  64. #include <signal.h>
  65. #include <stdarg.h>
  66. #include <stdio.h>
  67. #include <stdlib.h>
  68. #include <string.h>
  69. #include <sys/types.h>
  70. #include <sys/wait.h>
  71. #include <unistd.h>
  72. #include <espeak-ng/espeak_ng.h>
  73. /*
  74. * mbrola instance parameters
  75. */
  76. enum mbr_state {
  77. MBR_INACTIVE = 0,
  78. MBR_IDLE,
  79. MBR_NEWDATA,
  80. MBR_AUDIO,
  81. MBR_WEDGED
  82. };
  83. static enum mbr_state mbr_state;
  84. static char *mbr_voice_path;
  85. static int mbr_cmd_fd, mbr_audio_fd, mbr_error_fd, mbr_proc_stat;
  86. static pid_t mbr_pid;
  87. static int mbr_samplerate;
  88. static float mbr_volume = 1.0;
  89. static char mbr_errorbuf[160];
  90. struct datablock {
  91. struct datablock *next;
  92. int done;
  93. int size;
  94. char buffer[1]; // 1 or more, dynamically allocated
  95. };
  96. static struct datablock *mbr_pending_data_head, *mbr_pending_data_tail;
  97. /*
  98. * Private support code.
  99. */
  100. static void err(const char *errmsg, ...)
  101. {
  102. va_list params;
  103. va_start(params, errmsg);
  104. vsnprintf(mbr_errorbuf, sizeof(mbr_errorbuf), errmsg, params);
  105. va_end(params);
  106. fprintf(stderr, "mbrowrap error: %s\n", mbr_errorbuf);
  107. }
  108. static int create_pipes(int p1[2], int p2[2], int p3[2])
  109. {
  110. int error;
  111. if (pipe(p1) != -1) {
  112. if (pipe(p2) != -1) {
  113. if (pipe(p3) != -1)
  114. return 0;
  115. else
  116. error = errno;
  117. close(p2[0]);
  118. close(p2[1]);
  119. } else
  120. error = errno;
  121. close(p1[0]);
  122. close(p1[1]);
  123. } else
  124. error = errno;
  125. err("pipe(): %s", strerror(error));
  126. return -1;
  127. }
  128. static void close_pipes(int p1[2], int p2[2], int p3[2])
  129. {
  130. close(p1[0]);
  131. close(p1[1]);
  132. close(p2[0]);
  133. close(p2[1]);
  134. close(p3[0]);
  135. close(p3[1]);
  136. }
  137. static int start_mbrola(const char *voice_path)
  138. {
  139. int error, p_stdin[2], p_stdout[2], p_stderr[2];
  140. ssize_t written;
  141. char charbuf[20];
  142. if (mbr_state != MBR_INACTIVE) {
  143. err("mbrola init request when already initialized");
  144. return -1;
  145. }
  146. error = create_pipes(p_stdin, p_stdout, p_stderr);
  147. if (error)
  148. return -1;
  149. mbr_pid = fork();
  150. if (mbr_pid == -1) {
  151. error = errno;
  152. close_pipes(p_stdin, p_stdout, p_stderr);
  153. err("fork(): %s", strerror(error));
  154. return -1;
  155. }
  156. if (mbr_pid == 0) {
  157. int i;
  158. if (dup2(p_stdin[0], 0) == -1 ||
  159. dup2(p_stdout[1], 1) == -1 ||
  160. dup2(p_stderr[1], 2) == -1) {
  161. snprintf(mbr_errorbuf, sizeof(mbr_errorbuf),
  162. "dup2(): %s\n", strerror(errno));
  163. written = write(p_stderr[1], mbr_errorbuf, strlen(mbr_errorbuf));
  164. (void)written; // suppress 'variable not used' warning
  165. _exit(1);
  166. }
  167. for (i = p_stderr[1]; i > 2; i--)
  168. close(i);
  169. signal(SIGHUP, SIG_IGN);
  170. signal(SIGINT, SIG_IGN);
  171. signal(SIGQUIT, SIG_IGN);
  172. signal(SIGTERM, SIG_IGN);
  173. snprintf(charbuf, sizeof(charbuf), "%g", mbr_volume);
  174. execlp("mbrola", "mbrola", "-e", "-v", charbuf,
  175. voice_path, "-", "-.wav", (char *)NULL);
  176. /* if execution reaches this point then the exec() failed */
  177. snprintf(mbr_errorbuf, sizeof(mbr_errorbuf),
  178. "mbrola: %s\n", strerror(errno));
  179. written = write(2, mbr_errorbuf, strlen(mbr_errorbuf));
  180. (void)written; // suppress 'variable not used' warning
  181. _exit(1);
  182. }
  183. snprintf(charbuf, sizeof(charbuf), "/proc/%d/stat", mbr_pid);
  184. mbr_proc_stat = open(charbuf, O_RDONLY);
  185. if (mbr_proc_stat == -1) {
  186. error = errno;
  187. close_pipes(p_stdin, p_stdout, p_stderr);
  188. waitpid(mbr_pid, NULL, 0);
  189. mbr_pid = 0;
  190. err("/proc is unaccessible: %s", strerror(error));
  191. return -1;
  192. }
  193. signal(SIGPIPE, SIG_IGN);
  194. if (fcntl(p_stdin[1], F_SETFL, O_NONBLOCK) == -1 ||
  195. fcntl(p_stdout[0], F_SETFL, O_NONBLOCK) == -1 ||
  196. fcntl(p_stderr[0], F_SETFL, O_NONBLOCK) == -1) {
  197. error = errno;
  198. close_pipes(p_stdin, p_stdout, p_stderr);
  199. waitpid(mbr_pid, NULL, 0);
  200. mbr_pid = 0;
  201. err("fcntl(): %s", strerror(error));
  202. return -1;
  203. }
  204. mbr_cmd_fd = p_stdin[1];
  205. mbr_audio_fd = p_stdout[0];
  206. mbr_error_fd = p_stderr[0];
  207. close(p_stdin[0]);
  208. close(p_stdout[1]);
  209. close(p_stderr[1]);
  210. mbr_state = MBR_IDLE;
  211. return 0;
  212. }
  213. static void stop_mbrola(void)
  214. {
  215. if (mbr_state == MBR_INACTIVE)
  216. return;
  217. close(mbr_proc_stat);
  218. close(mbr_cmd_fd);
  219. close(mbr_audio_fd);
  220. close(mbr_error_fd);
  221. if (mbr_pid) {
  222. kill(mbr_pid, SIGTERM);
  223. waitpid(mbr_pid, NULL, 0);
  224. mbr_pid = 0;
  225. }
  226. mbr_state = MBR_INACTIVE;
  227. }
  228. static void free_pending_data(void)
  229. {
  230. struct datablock *p, *head = mbr_pending_data_head;
  231. while (head) {
  232. p = head;
  233. head = head->next;
  234. free(p);
  235. }
  236. mbr_pending_data_head = NULL;
  237. mbr_pending_data_tail = NULL;
  238. }
  239. static int mbrola_died(void)
  240. {
  241. pid_t pid;
  242. int status, len;
  243. const char *msg;
  244. char msgbuf[80];
  245. pid = waitpid(mbr_pid, &status, WNOHANG);
  246. if (!pid)
  247. msg = "mbrola closed stderr and did not exit";
  248. else if (pid != mbr_pid)
  249. msg = "waitpid() is confused";
  250. else {
  251. mbr_pid = 0;
  252. if (WIFSIGNALED(status)) {
  253. int sig = WTERMSIG(status);
  254. snprintf(msgbuf, sizeof(msgbuf),
  255. "mbrola died by signal %d", sig);
  256. msg = msgbuf;
  257. } else if (WIFEXITED(status)) {
  258. int exst = WEXITSTATUS(status);
  259. snprintf(msgbuf, sizeof(msgbuf),
  260. "mbrola exited with status %d", exst);
  261. msg = msgbuf;
  262. } else
  263. msg = "mbrola died and wait status is weird";
  264. }
  265. fprintf(stderr, "mbrowrap error: %s\n", msg);
  266. len = strlen(mbr_errorbuf);
  267. if (!len)
  268. snprintf(mbr_errorbuf, sizeof(mbr_errorbuf), "%s", msg);
  269. else
  270. snprintf(mbr_errorbuf + len, sizeof(mbr_errorbuf) - len,
  271. ", (%s)", msg);
  272. return -1;
  273. }
  274. static int mbrola_has_errors(void)
  275. {
  276. int result;
  277. char buffer[256];
  278. char *buf_ptr, *lf;
  279. buf_ptr = buffer;
  280. for (;;) {
  281. result = read(mbr_error_fd, buf_ptr,
  282. sizeof(buffer) - (buf_ptr - buffer) - 1);
  283. if (result == -1) {
  284. if (errno == EAGAIN)
  285. return 0;
  286. err("read(error): %s", strerror(errno));
  287. return -1;
  288. }
  289. if (result == 0) {
  290. // EOF on stderr, assume mbrola died.
  291. return mbrola_died();
  292. }
  293. buf_ptr[result] = 0;
  294. for (; (lf = strchr(buf_ptr, '\n')); buf_ptr = lf + 1) {
  295. // inhibit the reset signal messages
  296. if (strncmp(buf_ptr, "Got a reset signal", 18) == 0 ||
  297. strncmp(buf_ptr, "Input Flush Signal", 18) == 0)
  298. continue;
  299. *lf = 0;
  300. if (strstr(buf_ptr, "mbrola: No such file or directory") != NULL)
  301. fprintf(stderr,
  302. "mbrola executable was not found. Please install MBROLA!\n");
  303. else
  304. fprintf(stderr, "mbrola: %s\n", buf_ptr);
  305. // is this the last line?
  306. if (lf == &buf_ptr[result - 1]) {
  307. snprintf(mbr_errorbuf, sizeof(mbr_errorbuf),
  308. "%s", buf_ptr);
  309. // don't consider this fatal at this point
  310. return 0;
  311. }
  312. }
  313. memmove(buffer, buf_ptr, result);
  314. buf_ptr = buffer + result;
  315. }
  316. }
  317. static int send_to_mbrola(const char *cmd)
  318. {
  319. ssize_t result;
  320. int len;
  321. if (!mbr_pid)
  322. return -1;
  323. len = strlen(cmd);
  324. result = write(mbr_cmd_fd, cmd, len);
  325. if (result == -1) {
  326. int error = errno;
  327. if (error == EPIPE && mbrola_has_errors())
  328. return -1;
  329. else if (error == EAGAIN)
  330. result = 0;
  331. else {
  332. err("write(): %s", strerror(error));
  333. return -1;
  334. }
  335. }
  336. if (result != len) {
  337. struct datablock *data;
  338. data = (struct datablock *)malloc(sizeof(*data) + len - result);
  339. if (data) {
  340. data->next = NULL;
  341. data->done = 0;
  342. data->size = len - result;
  343. memcpy(data->buffer, cmd + result, len - result);
  344. result = len;
  345. if (!mbr_pending_data_head)
  346. mbr_pending_data_head = data;
  347. else
  348. mbr_pending_data_tail->next = data;
  349. mbr_pending_data_tail = data;
  350. }
  351. }
  352. return result;
  353. }
  354. static int mbrola_is_idle(void)
  355. {
  356. char *p;
  357. char buffer[20]; // looking for "12345 (mbrola) S" so 20 is plenty
  358. // look in /proc to determine if mbrola is still running or sleeping
  359. if (lseek(mbr_proc_stat, 0, SEEK_SET) != 0)
  360. return 0;
  361. if (read(mbr_proc_stat, buffer, sizeof(buffer)) != sizeof(buffer))
  362. return 0;
  363. p = (char *)memchr(buffer, ')', sizeof(buffer));
  364. if (!p || (unsigned)(p - buffer) >= sizeof(buffer) - 2)
  365. return 0;
  366. return p[1] == ' ' && p[2] == 'S';
  367. }
  368. static ssize_t receive_from_mbrola(void *buffer, size_t bufsize)
  369. {
  370. int result, wait = 1;
  371. size_t cursize = 0;
  372. if (!mbr_pid)
  373. return -1;
  374. do {
  375. struct pollfd pollfd[3];
  376. nfds_t nfds = 0;
  377. int idle;
  378. pollfd[0].fd = mbr_audio_fd;
  379. pollfd[0].events = POLLIN;
  380. nfds++;
  381. pollfd[1].fd = mbr_error_fd;
  382. pollfd[1].events = POLLIN;
  383. nfds++;
  384. if (mbr_pending_data_head) {
  385. pollfd[2].fd = mbr_cmd_fd;
  386. pollfd[2].events = POLLOUT;
  387. nfds++;
  388. }
  389. idle = mbrola_is_idle();
  390. result = poll(pollfd, nfds, idle ? 0 : wait);
  391. if (result == -1) {
  392. err("poll(): %s", strerror(errno));
  393. return -1;
  394. }
  395. if (result == 0) {
  396. if (idle) {
  397. mbr_state = MBR_IDLE;
  398. break;
  399. } else {
  400. if (wait >= 5000 * (4-1)/4) {
  401. mbr_state = MBR_WEDGED;
  402. err("mbrola process is stalled");
  403. break;
  404. } else {
  405. wait *= 4;
  406. continue;
  407. }
  408. }
  409. }
  410. wait = 1;
  411. if (pollfd[1].revents && mbrola_has_errors())
  412. return -1;
  413. if (mbr_pending_data_head && pollfd[2].revents) {
  414. struct datablock *head = mbr_pending_data_head;
  415. char *data = head->buffer + head->done;
  416. int left = head->size - head->done;
  417. result = write(mbr_cmd_fd, data, left);
  418. if (result == -1) {
  419. int error = errno;
  420. if (error == EPIPE && mbrola_has_errors())
  421. return -1;
  422. err("write(): %s", strerror(error));
  423. return -1;
  424. }
  425. if (result != left)
  426. head->done += result;
  427. else {
  428. mbr_pending_data_head = head->next;
  429. free(head);
  430. if (!mbr_pending_data_head)
  431. mbr_pending_data_tail = NULL;
  432. else
  433. continue;
  434. }
  435. }
  436. if (pollfd[0].revents) {
  437. char *curpos = (char *)buffer + cursize;
  438. size_t space = bufsize - cursize;
  439. ssize_t obtained = read(mbr_audio_fd, curpos, space);
  440. if (obtained == -1) {
  441. err("read(): %s", strerror(errno));
  442. return -1;
  443. }
  444. cursize += obtained;
  445. mbr_state = MBR_AUDIO;
  446. }
  447. } while (cursize < bufsize);
  448. return cursize;
  449. }
  450. /*
  451. * API functions.
  452. */
  453. static int init_mbrola(char *voice_path)
  454. {
  455. int error, result;
  456. unsigned char wavhdr[45];
  457. error = start_mbrola(voice_path);
  458. if (error)
  459. return -1;
  460. // Allow mbrola time to start when running on Windows Subsystem for
  461. // Linux (WSL). Otherwise, the receive_from_mbrola call to read the
  462. // wav header from mbrola will fail.
  463. usleep(100);
  464. result = send_to_mbrola("#\n");
  465. if (result != 2) {
  466. stop_mbrola();
  467. return -1;
  468. }
  469. // we should actually be getting only 44 bytes
  470. result = receive_from_mbrola(wavhdr, 45);
  471. if (result != 44) {
  472. if (result >= 0)
  473. err("unable to get .wav header from mbrola");
  474. stop_mbrola();
  475. return -1;
  476. }
  477. // parse wavhdr to get mbrola voice samplerate
  478. if (memcmp(wavhdr, "RIFF", 4) != 0 ||
  479. memcmp(wavhdr+8, "WAVEfmt ", 8) != 0) {
  480. err("mbrola did not return a .wav header");
  481. stop_mbrola();
  482. return -1;
  483. }
  484. mbr_samplerate = wavhdr[24] + (wavhdr[25]<<8) +
  485. (wavhdr[26]<<16) + (wavhdr[27]<<24);
  486. // remember the voice path for setVolumeRatio_MBR()
  487. if (mbr_voice_path != voice_path) {
  488. free(mbr_voice_path);
  489. mbr_voice_path = strdup(voice_path);
  490. }
  491. return 0;
  492. }
  493. static void close_mbrola(void)
  494. {
  495. stop_mbrola();
  496. free_pending_data();
  497. free(mbr_voice_path);
  498. mbr_voice_path = NULL;
  499. mbr_volume = 1.0;
  500. }
  501. static void reset_mbrola(void)
  502. {
  503. int result, success = 1;
  504. char dummybuf[4096];
  505. if (mbr_state == MBR_IDLE)
  506. return;
  507. if (!mbr_pid)
  508. return;
  509. if (kill(mbr_pid, SIGUSR1) == -1)
  510. success = 0;
  511. free_pending_data();
  512. result = write(mbr_cmd_fd, "\n#\n", 3);
  513. if (result != 3)
  514. success = 0;
  515. do {
  516. result = read(mbr_audio_fd, dummybuf, sizeof(dummybuf));
  517. } while (result > 0);
  518. if (result != -1 || errno != EAGAIN)
  519. success = 0;
  520. if (!mbrola_has_errors() && success)
  521. mbr_state = MBR_IDLE;
  522. }
  523. static int read_mbrola(short *buffer, int nb_samples)
  524. {
  525. int result = receive_from_mbrola(buffer, nb_samples * 2);
  526. if (result > 0)
  527. result /= 2;
  528. return result;
  529. }
  530. static int write_mbrola(char *data)
  531. {
  532. mbr_state = MBR_NEWDATA;
  533. return send_to_mbrola(data);
  534. }
  535. static int flush_mbrola(void)
  536. {
  537. return send_to_mbrola("\n#\n") == 3;
  538. }
  539. static int getFreq_mbrola(void)
  540. {
  541. return mbr_samplerate;
  542. }
  543. static void setVolumeRatio_mbrola(float value)
  544. {
  545. if (value == mbr_volume)
  546. return;
  547. mbr_volume = value;
  548. if (mbr_state != MBR_IDLE)
  549. return;
  550. /*
  551. * We have no choice but to kill and restart mbrola with
  552. * the new argument here.
  553. */
  554. stop_mbrola();
  555. init_MBR(mbr_voice_path);
  556. }
  557. static char *lastErrorStr_mbrola(char *buffer, int bufsize)
  558. {
  559. if (mbr_pid)
  560. mbrola_has_errors();
  561. snprintf(buffer, bufsize, "%s", mbr_errorbuf);
  562. return buffer;
  563. }
  564. static void setNoError_mbrola(int no_error)
  565. {
  566. (void)no_error; // unused
  567. }
  568. BOOL load_MBR(void)
  569. {
  570. init_MBR = init_mbrola;
  571. close_MBR = close_mbrola;
  572. reset_MBR = reset_mbrola;
  573. read_MBR = read_mbrola;
  574. write_MBR = write_mbrola;
  575. flush_MBR = flush_mbrola;
  576. getFreq_MBR = getFreq_mbrola;
  577. setVolumeRatio_MBR = setVolumeRatio_mbrola;
  578. lastErrorStr_MBR = lastErrorStr_mbrola;
  579. setNoError_MBR = setNoError_mbrola;
  580. return 1;
  581. }
  582. void unload_MBR(void)
  583. {
  584. }
  585. #endif