app_jack.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2007 - 2008, Russell Bryant
  5. *
  6. * Russell Bryant <russell@digium.com>
  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. /*!
  19. * \file
  20. * \brief Jack Application
  21. *
  22. * \author Russell Bryant <russell@digium.com>
  23. *
  24. * This is an application to connect an Asterisk channel to an input
  25. * and output jack port so that the audio can be processed through
  26. * another application, or to play audio from another application.
  27. *
  28. * \extref http://www.jackaudio.org/
  29. *
  30. * \note To install libresample, check it out of the following repository:
  31. * <code>$ svn co http://svn.digium.com/svn/thirdparty/libresample/trunk</code>
  32. *
  33. * \ingroup applications
  34. */
  35. /*** MODULEINFO
  36. <depend>jack</depend>
  37. <depend>resample</depend>
  38. <support_level>extended</support_level>
  39. ***/
  40. #include "asterisk.h"
  41. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  42. #include <limits.h>
  43. #include <jack/jack.h>
  44. #include <jack/ringbuffer.h>
  45. #include <libresample.h>
  46. #include "asterisk/module.h"
  47. #include "asterisk/channel.h"
  48. #include "asterisk/strings.h"
  49. #include "asterisk/lock.h"
  50. #include "asterisk/app.h"
  51. #include "asterisk/pbx.h"
  52. #include "asterisk/audiohook.h"
  53. #include "asterisk/format_cache.h"
  54. #define RESAMPLE_QUALITY 1
  55. /* The number of frames the ringbuffers can store. The actual size is RINGBUFFER_FRAME_CAPACITY * jack_data->frame_datalen */
  56. #define RINGBUFFER_FRAME_CAPACITY 100
  57. /*! \brief Common options between the Jack() app and JACK_HOOK() function */
  58. #define COMMON_OPTIONS \
  59. " s(<name>) - Connect to the specified jack server name.\n" \
  60. " i(<name>) - Connect the output port that gets created to the specified\n" \
  61. " jack input port.\n" \
  62. " o(<name>) - Connect the input port that gets created to the specified\n" \
  63. " jack output port.\n" \
  64. " n - Do not automatically start the JACK server if it is not already\n" \
  65. " running.\n" \
  66. " c(<name>) - By default, Asterisk will use the channel name for the jack client\n" \
  67. " name. Use this option to specify a custom client name.\n"
  68. /*** DOCUMENTATION
  69. <application name="JACK" language="en_US">
  70. <synopsis>
  71. Jack Audio Connection Kit
  72. </synopsis>
  73. <syntax>
  74. <parameter name="options" required="false">
  75. <optionlist>
  76. <option name="s">
  77. <argument name="name" required="true">
  78. <para>Connect to the specified jack server name</para>
  79. </argument>
  80. </option>
  81. <option name="i">
  82. <argument name="name" required="true">
  83. <para>Connect the output port that gets created to the specified jack input port</para>
  84. </argument>
  85. </option>
  86. <option name="o">
  87. <argument name="name" required="true">
  88. <para>Connect the input port that gets created to the specified jack output port</para>
  89. </argument>
  90. </option>
  91. <option name="c">
  92. <argument name="name" required="true">
  93. <para>By default, Asterisk will use the channel name for the jack client name.</para>
  94. <para>Use this option to specify a custom client name.</para>
  95. </argument>
  96. </option>
  97. </optionlist>
  98. </parameter>
  99. </syntax>
  100. <description>
  101. <para>When executing this application, two jack ports will be created;
  102. one input and one output. Other applications can be hooked up to
  103. these ports to access audio coming from, or being send to the channel.</para>
  104. </description>
  105. </application>
  106. ***/
  107. static const char jack_app[] = "JACK";
  108. struct jack_data {
  109. AST_DECLARE_STRING_FIELDS(
  110. AST_STRING_FIELD(server_name);
  111. AST_STRING_FIELD(client_name);
  112. AST_STRING_FIELD(connect_input_port);
  113. AST_STRING_FIELD(connect_output_port);
  114. );
  115. jack_client_t *client;
  116. jack_port_t *input_port;
  117. jack_port_t *output_port;
  118. jack_ringbuffer_t *input_rb;
  119. jack_ringbuffer_t *output_rb;
  120. struct ast_format *audiohook_format;
  121. unsigned int audiohook_rate;
  122. unsigned int frame_datalen;
  123. void *output_resampler;
  124. double output_resample_factor;
  125. void *input_resampler;
  126. double input_resample_factor;
  127. unsigned int stop:1;
  128. unsigned int has_audiohook:1;
  129. unsigned int no_start_server:1;
  130. /*! Only used with JACK_HOOK */
  131. struct ast_audiohook audiohook;
  132. };
  133. static const struct {
  134. jack_status_t status;
  135. const char *str;
  136. } jack_status_table[] = {
  137. { JackFailure, "Failure" },
  138. { JackInvalidOption, "Invalid Option" },
  139. { JackNameNotUnique, "Name Not Unique" },
  140. { JackServerStarted, "Server Started" },
  141. { JackServerFailed, "Server Failed" },
  142. { JackServerError, "Server Error" },
  143. { JackNoSuchClient, "No Such Client" },
  144. { JackLoadFailure, "Load Failure" },
  145. { JackInitFailure, "Init Failure" },
  146. { JackShmFailure, "Shared Memory Access Failure" },
  147. { JackVersionError, "Version Mismatch" },
  148. };
  149. static const char *jack_status_to_str(jack_status_t status)
  150. {
  151. int i;
  152. for (i = 0; i < ARRAY_LEN(jack_status_table); i++) {
  153. if (jack_status_table[i].status == status)
  154. return jack_status_table[i].str;
  155. }
  156. return "Unknown Error";
  157. }
  158. static void log_jack_status(const char *prefix, jack_status_t status)
  159. {
  160. struct ast_str *str = ast_str_alloca(512);
  161. int i, first = 0;
  162. for (i = 0; i < (sizeof(status) * 8); i++) {
  163. if (!(status & (1 << i)))
  164. continue;
  165. if (!first) {
  166. ast_str_set(&str, 0, "%s", jack_status_to_str((1 << i)));
  167. first = 1;
  168. } else
  169. ast_str_append(&str, 0, ", %s", jack_status_to_str((1 << i)));
  170. }
  171. ast_log(LOG_NOTICE, "%s: %s\n", prefix, ast_str_buffer(str));
  172. }
  173. static int alloc_resampler(struct jack_data *jack_data, int input)
  174. {
  175. double from_srate, to_srate, jack_srate;
  176. void **resampler;
  177. double *resample_factor;
  178. if (input && jack_data->input_resampler)
  179. return 0;
  180. if (!input && jack_data->output_resampler)
  181. return 0;
  182. jack_srate = jack_get_sample_rate(jack_data->client);
  183. to_srate = input ? jack_data->audiohook_rate : jack_srate;
  184. from_srate = input ? jack_srate : jack_data->audiohook_rate;
  185. resample_factor = input ? &jack_data->input_resample_factor :
  186. &jack_data->output_resample_factor;
  187. if (from_srate == to_srate) {
  188. /* Awesome! The jack sample rate is the same as ours.
  189. * Resampling isn't needed. */
  190. *resample_factor = 1.0;
  191. return 0;
  192. }
  193. *resample_factor = to_srate / from_srate;
  194. resampler = input ? &jack_data->input_resampler :
  195. &jack_data->output_resampler;
  196. if (!(*resampler = resample_open(RESAMPLE_QUALITY,
  197. *resample_factor, *resample_factor))) {
  198. ast_log(LOG_ERROR, "Failed to open %s resampler\n",
  199. input ? "input" : "output");
  200. return -1;
  201. }
  202. return 0;
  203. }
  204. /*!
  205. * \brief Handle jack input port
  206. *
  207. * Read nframes number of samples from the input buffer, resample it
  208. * if necessary, and write it into the appropriate ringbuffer.
  209. */
  210. static void handle_input(void *buf, jack_nframes_t nframes,
  211. struct jack_data *jack_data)
  212. {
  213. short s_buf[nframes];
  214. float *in_buf = buf;
  215. size_t res;
  216. int i;
  217. size_t write_len = sizeof(s_buf);
  218. if (jack_data->input_resampler) {
  219. int total_in_buf_used = 0;
  220. int total_out_buf_used = 0;
  221. float f_buf[nframes + 1];
  222. memset(f_buf, 0, sizeof(f_buf));
  223. while (total_in_buf_used < nframes) {
  224. int in_buf_used;
  225. int out_buf_used;
  226. out_buf_used = resample_process(jack_data->input_resampler,
  227. jack_data->input_resample_factor,
  228. &in_buf[total_in_buf_used], nframes - total_in_buf_used,
  229. 0, &in_buf_used,
  230. &f_buf[total_out_buf_used], ARRAY_LEN(f_buf) - total_out_buf_used);
  231. if (out_buf_used < 0)
  232. break;
  233. total_out_buf_used += out_buf_used;
  234. total_in_buf_used += in_buf_used;
  235. if (total_out_buf_used == ARRAY_LEN(f_buf)) {
  236. ast_log(LOG_ERROR, "Output buffer filled ... need to increase its size, "
  237. "nframes '%d', total_out_buf_used '%d'\n", nframes, total_out_buf_used);
  238. break;
  239. }
  240. }
  241. for (i = 0; i < total_out_buf_used; i++)
  242. s_buf[i] = f_buf[i] * (SHRT_MAX / 1.0);
  243. write_len = total_out_buf_used * sizeof(int16_t);
  244. } else {
  245. /* No resampling needed */
  246. for (i = 0; i < nframes; i++)
  247. s_buf[i] = in_buf[i] * (SHRT_MAX / 1.0);
  248. }
  249. res = jack_ringbuffer_write(jack_data->input_rb, (const char *) s_buf, write_len);
  250. if (res != write_len) {
  251. ast_log(LOG_WARNING, "Tried to write %d bytes to the ringbuffer, but only wrote %d\n",
  252. (int) sizeof(s_buf), (int) res);
  253. }
  254. }
  255. /*!
  256. * \brief Handle jack output port
  257. *
  258. * Read nframes number of samples from the ringbuffer and write it out to the
  259. * output port buffer.
  260. */
  261. static void handle_output(void *buf, jack_nframes_t nframes,
  262. struct jack_data *jack_data)
  263. {
  264. size_t res, len;
  265. len = nframes * sizeof(float);
  266. res = jack_ringbuffer_read(jack_data->output_rb, buf, len);
  267. if (len != res) {
  268. ast_debug(2, "Wanted %d bytes to send to the output port, "
  269. "but only got %d\n", (int) len, (int) res);
  270. }
  271. }
  272. static int jack_process(jack_nframes_t nframes, void *arg)
  273. {
  274. struct jack_data *jack_data = arg;
  275. void *input_port_buf, *output_port_buf;
  276. if (!jack_data->input_resample_factor)
  277. alloc_resampler(jack_data, 1);
  278. input_port_buf = jack_port_get_buffer(jack_data->input_port, nframes);
  279. handle_input(input_port_buf, nframes, jack_data);
  280. output_port_buf = jack_port_get_buffer(jack_data->output_port, nframes);
  281. handle_output(output_port_buf, nframes, jack_data);
  282. return 0;
  283. }
  284. static void jack_shutdown(void *arg)
  285. {
  286. struct jack_data *jack_data = arg;
  287. jack_data->stop = 1;
  288. }
  289. static struct jack_data *destroy_jack_data(struct jack_data *jack_data)
  290. {
  291. if (jack_data->input_port) {
  292. jack_port_unregister(jack_data->client, jack_data->input_port);
  293. jack_data->input_port = NULL;
  294. }
  295. if (jack_data->output_port) {
  296. jack_port_unregister(jack_data->client, jack_data->output_port);
  297. jack_data->output_port = NULL;
  298. }
  299. if (jack_data->client) {
  300. jack_client_close(jack_data->client);
  301. jack_data->client = NULL;
  302. }
  303. if (jack_data->input_rb) {
  304. jack_ringbuffer_free(jack_data->input_rb);
  305. jack_data->input_rb = NULL;
  306. }
  307. if (jack_data->output_rb) {
  308. jack_ringbuffer_free(jack_data->output_rb);
  309. jack_data->output_rb = NULL;
  310. }
  311. if (jack_data->output_resampler) {
  312. resample_close(jack_data->output_resampler);
  313. jack_data->output_resampler = NULL;
  314. }
  315. if (jack_data->input_resampler) {
  316. resample_close(jack_data->input_resampler);
  317. jack_data->input_resampler = NULL;
  318. }
  319. if (jack_data->has_audiohook)
  320. ast_audiohook_destroy(&jack_data->audiohook);
  321. ast_string_field_free_memory(jack_data);
  322. ast_free(jack_data);
  323. return NULL;
  324. }
  325. static int init_jack_data(struct ast_channel *chan, struct jack_data *jack_data)
  326. {
  327. const char *client_name;
  328. jack_status_t status = 0;
  329. jack_options_t jack_options = JackNullOption;
  330. unsigned int channel_rate;
  331. unsigned int ringbuffer_size;
  332. /* Deducing audiohook sample rate from channel format
  333. ATTENTION: Might be problematic, if channel has different sampling than used by audiohook!
  334. */
  335. channel_rate = ast_format_get_sample_rate(ast_channel_readformat(chan));
  336. jack_data->audiohook_format = ast_format_cache_get_slin_by_rate(channel_rate);
  337. jack_data->audiohook_rate = ast_format_get_sample_rate(jack_data->audiohook_format);
  338. /* Guessing frame->datalen assuming a ptime of 20ms */
  339. jack_data->frame_datalen = jack_data->audiohook_rate / 50;
  340. ringbuffer_size = jack_data->frame_datalen * RINGBUFFER_FRAME_CAPACITY;
  341. ast_debug(1, "Audiohook parameters: slin-format:%s, rate:%d, frame-len:%d, ringbuffer_size: %d\n",
  342. ast_format_get_name(jack_data->audiohook_format), jack_data->audiohook_rate, jack_data->frame_datalen, ringbuffer_size);
  343. if (!ast_strlen_zero(jack_data->client_name)) {
  344. client_name = jack_data->client_name;
  345. } else {
  346. ast_channel_lock(chan);
  347. client_name = ast_strdupa(ast_channel_name(chan));
  348. ast_channel_unlock(chan);
  349. }
  350. if (!(jack_data->output_rb = jack_ringbuffer_create(ringbuffer_size)))
  351. return -1;
  352. if (!(jack_data->input_rb = jack_ringbuffer_create(ringbuffer_size)))
  353. return -1;
  354. if (jack_data->no_start_server)
  355. jack_options |= JackNoStartServer;
  356. if (!ast_strlen_zero(jack_data->server_name)) {
  357. jack_options |= JackServerName;
  358. jack_data->client = jack_client_open(client_name, jack_options, &status,
  359. jack_data->server_name);
  360. } else {
  361. jack_data->client = jack_client_open(client_name, jack_options, &status);
  362. }
  363. if (status)
  364. log_jack_status("Client Open Status", status);
  365. if (!jack_data->client)
  366. return -1;
  367. jack_data->input_port = jack_port_register(jack_data->client, "input",
  368. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput | JackPortIsTerminal, 0);
  369. if (!jack_data->input_port) {
  370. ast_log(LOG_ERROR, "Failed to create input port for jack port\n");
  371. return -1;
  372. }
  373. jack_data->output_port = jack_port_register(jack_data->client, "output",
  374. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput | JackPortIsTerminal, 0);
  375. if (!jack_data->output_port) {
  376. ast_log(LOG_ERROR, "Failed to create output port for jack port\n");
  377. return -1;
  378. }
  379. if (jack_set_process_callback(jack_data->client, jack_process, jack_data)) {
  380. ast_log(LOG_ERROR, "Failed to register process callback with jack client\n");
  381. return -1;
  382. }
  383. jack_on_shutdown(jack_data->client, jack_shutdown, jack_data);
  384. if (jack_activate(jack_data->client)) {
  385. ast_log(LOG_ERROR, "Unable to activate jack client\n");
  386. return -1;
  387. }
  388. while (!ast_strlen_zero(jack_data->connect_input_port)) {
  389. const char **ports;
  390. int i;
  391. ports = jack_get_ports(jack_data->client, jack_data->connect_input_port,
  392. NULL, JackPortIsInput);
  393. if (!ports) {
  394. ast_log(LOG_ERROR, "No input port matching '%s' was found\n",
  395. jack_data->connect_input_port);
  396. break;
  397. }
  398. for (i = 0; ports[i]; i++) {
  399. ast_debug(1, "Found port '%s' that matched specified input port '%s'\n",
  400. ports[i], jack_data->connect_input_port);
  401. }
  402. if (jack_connect(jack_data->client, jack_port_name(jack_data->output_port), ports[0])) {
  403. ast_log(LOG_ERROR, "Failed to connect '%s' to '%s'\n", ports[0],
  404. jack_port_name(jack_data->output_port));
  405. } else {
  406. ast_debug(1, "Connected '%s' to '%s'\n", ports[0],
  407. jack_port_name(jack_data->output_port));
  408. }
  409. free((void *) ports);
  410. break;
  411. }
  412. while (!ast_strlen_zero(jack_data->connect_output_port)) {
  413. const char **ports;
  414. int i;
  415. ports = jack_get_ports(jack_data->client, jack_data->connect_output_port,
  416. NULL, JackPortIsOutput);
  417. if (!ports) {
  418. ast_log(LOG_ERROR, "No output port matching '%s' was found\n",
  419. jack_data->connect_output_port);
  420. break;
  421. }
  422. for (i = 0; ports[i]; i++) {
  423. ast_debug(1, "Found port '%s' that matched specified output port '%s'\n",
  424. ports[i], jack_data->connect_output_port);
  425. }
  426. if (jack_connect(jack_data->client, ports[0], jack_port_name(jack_data->input_port))) {
  427. ast_log(LOG_ERROR, "Failed to connect '%s' to '%s'\n", ports[0],
  428. jack_port_name(jack_data->input_port));
  429. } else {
  430. ast_debug(1, "Connected '%s' to '%s'\n", ports[0],
  431. jack_port_name(jack_data->input_port));
  432. }
  433. free((void *) ports);
  434. break;
  435. }
  436. return 0;
  437. }
  438. static int queue_voice_frame(struct jack_data *jack_data, struct ast_frame *f)
  439. {
  440. float f_buf[f->samples * 8];
  441. size_t f_buf_used = 0;
  442. int i;
  443. int16_t *s_buf = f->data.ptr;
  444. size_t res;
  445. memset(f_buf, 0, sizeof(f_buf));
  446. if (!jack_data->output_resample_factor)
  447. alloc_resampler(jack_data, 0);
  448. if (jack_data->output_resampler) {
  449. float in_buf[f->samples];
  450. int total_in_buf_used = 0;
  451. int total_out_buf_used = 0;
  452. memset(in_buf, 0, sizeof(in_buf));
  453. for (i = 0; i < f->samples; i++)
  454. in_buf[i] = s_buf[i] * (1.0 / SHRT_MAX);
  455. while (total_in_buf_used < ARRAY_LEN(in_buf)) {
  456. int in_buf_used;
  457. int out_buf_used;
  458. out_buf_used = resample_process(jack_data->output_resampler,
  459. jack_data->output_resample_factor,
  460. &in_buf[total_in_buf_used], ARRAY_LEN(in_buf) - total_in_buf_used,
  461. 0, &in_buf_used,
  462. &f_buf[total_out_buf_used], ARRAY_LEN(f_buf) - total_out_buf_used);
  463. if (out_buf_used < 0)
  464. break;
  465. total_out_buf_used += out_buf_used;
  466. total_in_buf_used += in_buf_used;
  467. if (total_out_buf_used == ARRAY_LEN(f_buf)) {
  468. ast_log(LOG_ERROR, "Output buffer filled ... need to increase its size\n");
  469. break;
  470. }
  471. }
  472. f_buf_used = total_out_buf_used;
  473. if (f_buf_used > ARRAY_LEN(f_buf))
  474. f_buf_used = ARRAY_LEN(f_buf);
  475. } else {
  476. /* No resampling needed */
  477. for (i = 0; i < f->samples; i++)
  478. f_buf[i] = s_buf[i] * (1.0 / SHRT_MAX);
  479. f_buf_used = f->samples;
  480. }
  481. res = jack_ringbuffer_write(jack_data->output_rb, (const char *) f_buf, f_buf_used * sizeof(float));
  482. if (res != (f_buf_used * sizeof(float))) {
  483. ast_log(LOG_WARNING, "Tried to write %d bytes to the ringbuffer, but only wrote %d\n",
  484. (int) (f_buf_used * sizeof(float)), (int) res);
  485. }
  486. return 0;
  487. }
  488. /*!
  489. * \brief handle jack audio
  490. *
  491. * \param[in] chan The Asterisk channel to write the frames to if no output frame
  492. * is provided.
  493. * \param[in] jack_data This is the jack_data struct that contains the input
  494. * ringbuffer that audio will be read from.
  495. * \param[out] out_frame If this argument is non-NULL, then assuming there is
  496. * enough data avilable in the ringbuffer, the audio in this frame
  497. * will get replaced with audio from the input buffer. If there is
  498. * not enough data available to read at this time, then the frame
  499. * data gets zeroed out.
  500. *
  501. * Read data from the input ringbuffer, which is the properly resampled audio
  502. * that was read from the jack input port. Write it to the channel in 20 ms frames,
  503. * or fill up an output frame instead if one is provided.
  504. *
  505. * \return Nothing.
  506. */
  507. static void handle_jack_audio(struct ast_channel *chan, struct jack_data *jack_data,
  508. struct ast_frame *out_frame)
  509. {
  510. short buf[jack_data->frame_datalen];
  511. struct ast_frame f = {
  512. .frametype = AST_FRAME_VOICE,
  513. .subclass.format = jack_data->audiohook_format,
  514. .src = "JACK",
  515. .data.ptr = buf,
  516. .datalen = sizeof(buf),
  517. .samples = ARRAY_LEN(buf),
  518. };
  519. for (;;) {
  520. size_t res, read_len;
  521. char *read_buf;
  522. read_len = out_frame ? out_frame->datalen : sizeof(buf);
  523. read_buf = out_frame ? out_frame->data.ptr : buf;
  524. res = jack_ringbuffer_read_space(jack_data->input_rb);
  525. if (res < read_len) {
  526. /* Not enough data ready for another frame, move on ... */
  527. if (out_frame) {
  528. ast_debug(1, "Sending an empty frame for the JACK_HOOK\n");
  529. memset(out_frame->data.ptr, 0, out_frame->datalen);
  530. }
  531. break;
  532. }
  533. res = jack_ringbuffer_read(jack_data->input_rb, (char *) read_buf, read_len);
  534. if (res < read_len) {
  535. ast_log(LOG_ERROR, "Error reading from ringbuffer, even though it said there was enough data\n");
  536. break;
  537. }
  538. if (out_frame) {
  539. /* If an output frame was provided, then we just want to fill up the
  540. * buffer in that frame and return. */
  541. break;
  542. }
  543. ast_write(chan, &f);
  544. }
  545. }
  546. enum {
  547. OPT_SERVER_NAME = (1 << 0),
  548. OPT_INPUT_PORT = (1 << 1),
  549. OPT_OUTPUT_PORT = (1 << 2),
  550. OPT_NOSTART_SERVER = (1 << 3),
  551. OPT_CLIENT_NAME = (1 << 4),
  552. };
  553. enum {
  554. OPT_ARG_SERVER_NAME,
  555. OPT_ARG_INPUT_PORT,
  556. OPT_ARG_OUTPUT_PORT,
  557. OPT_ARG_CLIENT_NAME,
  558. /* Must be the last element */
  559. OPT_ARG_ARRAY_SIZE,
  560. };
  561. AST_APP_OPTIONS(jack_exec_options, BEGIN_OPTIONS
  562. AST_APP_OPTION_ARG('s', OPT_SERVER_NAME, OPT_ARG_SERVER_NAME),
  563. AST_APP_OPTION_ARG('i', OPT_INPUT_PORT, OPT_ARG_INPUT_PORT),
  564. AST_APP_OPTION_ARG('o', OPT_OUTPUT_PORT, OPT_ARG_OUTPUT_PORT),
  565. AST_APP_OPTION('n', OPT_NOSTART_SERVER),
  566. AST_APP_OPTION_ARG('c', OPT_CLIENT_NAME, OPT_ARG_CLIENT_NAME),
  567. END_OPTIONS );
  568. static struct jack_data *jack_data_alloc(void)
  569. {
  570. struct jack_data *jack_data;
  571. if (!(jack_data = ast_calloc_with_stringfields(1, struct jack_data, 32))) {
  572. return NULL;
  573. }
  574. return jack_data;
  575. }
  576. /*!
  577. * \note This must be done before calling init_jack_data().
  578. */
  579. static int handle_options(struct jack_data *jack_data, const char *__options_str)
  580. {
  581. struct ast_flags options = { 0, };
  582. char *option_args[OPT_ARG_ARRAY_SIZE];
  583. char *options_str;
  584. options_str = ast_strdupa(__options_str);
  585. ast_app_parse_options(jack_exec_options, &options, option_args, options_str);
  586. if (ast_test_flag(&options, OPT_SERVER_NAME)) {
  587. if (!ast_strlen_zero(option_args[OPT_ARG_SERVER_NAME]))
  588. ast_string_field_set(jack_data, server_name, option_args[OPT_ARG_SERVER_NAME]);
  589. else {
  590. ast_log(LOG_ERROR, "A server name must be provided with the s() option\n");
  591. return -1;
  592. }
  593. }
  594. if (ast_test_flag(&options, OPT_CLIENT_NAME)) {
  595. if (!ast_strlen_zero(option_args[OPT_ARG_CLIENT_NAME]))
  596. ast_string_field_set(jack_data, client_name, option_args[OPT_ARG_CLIENT_NAME]);
  597. else {
  598. ast_log(LOG_ERROR, "A client name must be provided with the c() option\n");
  599. return -1;
  600. }
  601. }
  602. if (ast_test_flag(&options, OPT_INPUT_PORT)) {
  603. if (!ast_strlen_zero(option_args[OPT_ARG_INPUT_PORT]))
  604. ast_string_field_set(jack_data, connect_input_port, option_args[OPT_ARG_INPUT_PORT]);
  605. else {
  606. ast_log(LOG_ERROR, "A name must be provided with the i() option\n");
  607. return -1;
  608. }
  609. }
  610. if (ast_test_flag(&options, OPT_OUTPUT_PORT)) {
  611. if (!ast_strlen_zero(option_args[OPT_ARG_OUTPUT_PORT]))
  612. ast_string_field_set(jack_data, connect_output_port, option_args[OPT_ARG_OUTPUT_PORT]);
  613. else {
  614. ast_log(LOG_ERROR, "A name must be provided with the o() option\n");
  615. return -1;
  616. }
  617. }
  618. jack_data->no_start_server = ast_test_flag(&options, OPT_NOSTART_SERVER) ? 1 : 0;
  619. return 0;
  620. }
  621. static int jack_exec(struct ast_channel *chan, const char *data)
  622. {
  623. struct jack_data *jack_data;
  624. if (!(jack_data = jack_data_alloc()))
  625. return -1;
  626. if (!ast_strlen_zero(data) && handle_options(jack_data, data)) {
  627. destroy_jack_data(jack_data);
  628. return -1;
  629. }
  630. if (init_jack_data(chan, jack_data)) {
  631. destroy_jack_data(jack_data);
  632. return -1;
  633. }
  634. if (ast_set_read_format(chan, jack_data->audiohook_format)) {
  635. destroy_jack_data(jack_data);
  636. return -1;
  637. }
  638. if (ast_set_write_format(chan, jack_data->audiohook_format)) {
  639. destroy_jack_data(jack_data);
  640. return -1;
  641. }
  642. while (!jack_data->stop) {
  643. struct ast_frame *f;
  644. if (ast_waitfor(chan, -1) < 0) {
  645. break;
  646. }
  647. f = ast_read(chan);
  648. if (!f) {
  649. jack_data->stop = 1;
  650. continue;
  651. }
  652. switch (f->frametype) {
  653. case AST_FRAME_CONTROL:
  654. if (f->subclass.integer == AST_CONTROL_HANGUP)
  655. jack_data->stop = 1;
  656. break;
  657. case AST_FRAME_VOICE:
  658. queue_voice_frame(jack_data, f);
  659. default:
  660. break;
  661. }
  662. ast_frfree(f);
  663. handle_jack_audio(chan, jack_data, NULL);
  664. }
  665. jack_data = destroy_jack_data(jack_data);
  666. return 0;
  667. }
  668. static void jack_hook_ds_destroy(void *data)
  669. {
  670. struct jack_data *jack_data = data;
  671. destroy_jack_data(jack_data);
  672. }
  673. static const struct ast_datastore_info jack_hook_ds_info = {
  674. .type = "JACK_HOOK",
  675. .destroy = jack_hook_ds_destroy,
  676. };
  677. static int jack_hook_callback(struct ast_audiohook *audiohook, struct ast_channel *chan,
  678. struct ast_frame *frame, enum ast_audiohook_direction direction)
  679. {
  680. struct ast_datastore *datastore;
  681. struct jack_data *jack_data;
  682. if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE)
  683. return 0;
  684. if (direction != AST_AUDIOHOOK_DIRECTION_READ)
  685. return 0;
  686. if (frame->frametype != AST_FRAME_VOICE)
  687. return 0;
  688. ast_channel_lock(chan);
  689. if (!(datastore = ast_channel_datastore_find(chan, &jack_hook_ds_info, NULL))) {
  690. ast_log(LOG_ERROR, "JACK_HOOK datastore not found for '%s'\n", ast_channel_name(chan));
  691. ast_channel_unlock(chan);
  692. return -1;
  693. }
  694. jack_data = datastore->data;
  695. if (ast_format_cmp(frame->subclass.format, jack_data->audiohook_format) == AST_FORMAT_CMP_NOT_EQUAL) {
  696. ast_log(LOG_WARNING, "Expected frame in %s for the audiohook, but got format %s\n",
  697. ast_format_get_name(jack_data->audiohook_format),
  698. ast_format_get_name(frame->subclass.format));
  699. ast_channel_unlock(chan);
  700. return 0;
  701. }
  702. queue_voice_frame(jack_data, frame);
  703. handle_jack_audio(chan, jack_data, frame);
  704. ast_channel_unlock(chan);
  705. return 0;
  706. }
  707. static int enable_jack_hook(struct ast_channel *chan, char *data)
  708. {
  709. struct ast_datastore *datastore;
  710. struct jack_data *jack_data = NULL;
  711. AST_DECLARE_APP_ARGS(args,
  712. AST_APP_ARG(mode);
  713. AST_APP_ARG(options);
  714. );
  715. AST_STANDARD_APP_ARGS(args, data);
  716. ast_channel_lock(chan);
  717. if ((datastore = ast_channel_datastore_find(chan, &jack_hook_ds_info, NULL))) {
  718. ast_log(LOG_ERROR, "JACK_HOOK already enabled for '%s'\n", ast_channel_name(chan));
  719. goto return_error;
  720. }
  721. if (ast_strlen_zero(args.mode) || strcasecmp(args.mode, "manipulate")) {
  722. ast_log(LOG_ERROR, "'%s' is not a supported mode. Only manipulate is supported.\n",
  723. S_OR(args.mode, "<none>"));
  724. goto return_error;
  725. }
  726. if (!(jack_data = jack_data_alloc()))
  727. goto return_error;
  728. if (!ast_strlen_zero(args.options) && handle_options(jack_data, args.options))
  729. goto return_error;
  730. if (init_jack_data(chan, jack_data))
  731. goto return_error;
  732. if (!(datastore = ast_datastore_alloc(&jack_hook_ds_info, NULL)))
  733. goto return_error;
  734. jack_data->has_audiohook = 1;
  735. ast_audiohook_init(&jack_data->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE, "JACK_HOOK", AST_AUDIOHOOK_MANIPULATE_ALL_RATES);
  736. jack_data->audiohook.manipulate_callback = jack_hook_callback;
  737. datastore->data = jack_data;
  738. if (ast_audiohook_attach(chan, &jack_data->audiohook))
  739. goto return_error;
  740. if (ast_channel_datastore_add(chan, datastore))
  741. goto return_error;
  742. ast_channel_unlock(chan);
  743. return 0;
  744. return_error:
  745. ast_channel_unlock(chan);
  746. if (jack_data) {
  747. destroy_jack_data(jack_data);
  748. }
  749. if (datastore) {
  750. datastore->data = NULL;
  751. ast_datastore_free(datastore);
  752. }
  753. return -1;
  754. }
  755. static int disable_jack_hook(struct ast_channel *chan)
  756. {
  757. struct ast_datastore *datastore;
  758. struct jack_data *jack_data;
  759. ast_channel_lock(chan);
  760. if (!(datastore = ast_channel_datastore_find(chan, &jack_hook_ds_info, NULL))) {
  761. ast_channel_unlock(chan);
  762. ast_log(LOG_WARNING, "No JACK_HOOK found to disable\n");
  763. return -1;
  764. }
  765. ast_channel_datastore_remove(chan, datastore);
  766. jack_data = datastore->data;
  767. ast_audiohook_detach(&jack_data->audiohook);
  768. /* Keep the channel locked while we destroy the datastore, so that we can
  769. * ensure that all of the jack stuff is stopped just in case another frame
  770. * tries to come through the audiohook callback. */
  771. ast_datastore_free(datastore);
  772. ast_channel_unlock(chan);
  773. return 0;
  774. }
  775. static int jack_hook_write(struct ast_channel *chan, const char *cmd, char *data,
  776. const char *value)
  777. {
  778. int res;
  779. if (!chan) {
  780. ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
  781. return -1;
  782. }
  783. if (!strcasecmp(value, "on"))
  784. res = enable_jack_hook(chan, data);
  785. else if (!strcasecmp(value, "off"))
  786. res = disable_jack_hook(chan);
  787. else {
  788. ast_log(LOG_ERROR, "'%s' is not a valid value for JACK_HOOK()\n", value);
  789. res = -1;
  790. }
  791. return res;
  792. }
  793. static struct ast_custom_function jack_hook_function = {
  794. .name = "JACK_HOOK",
  795. .synopsis = "Enable a jack hook on a channel",
  796. .syntax = "JACK_HOOK(<mode>,[options])",
  797. .desc =
  798. " The JACK_HOOK allows turning on or off jack connectivity to this channel.\n"
  799. "When the JACK_HOOK is turned on, jack ports will get created that allow\n"
  800. "access to the audio stream for this channel. The mode specifies which mode\n"
  801. "this hook should run in. A mode must be specified when turning the JACK_HOOK.\n"
  802. "on. However, all arguments are optional when turning it off.\n"
  803. "\n"
  804. " Valid modes are:\n"
  805. #if 0
  806. /* XXX TODO */
  807. " spy - Create a read-only audio hook. Only an output jack port will\n"
  808. " get created.\n"
  809. " whisper - Create a write-only audio hook. Only an input jack port will\n"
  810. " get created.\n"
  811. #endif
  812. " manipulate - Create a read/write audio hook. Both an input and an output\n"
  813. " jack port will get created. Audio from the channel will be\n"
  814. " sent out the output port and will be replaced by the audio\n"
  815. " coming in on the input port as it gets passed on.\n"
  816. "\n"
  817. " Valid options are:\n"
  818. COMMON_OPTIONS
  819. "\n"
  820. " Examples:\n"
  821. " To turn on the JACK_HOOK,\n"
  822. " Set(JACK_HOOK(manipulate,i(pure_data_0:input0)o(pure_data_0:output0))=on)\n"
  823. " To turn off the JACK_HOOK,\n"
  824. " Set(JACK_HOOK()=off)\n"
  825. "",
  826. .write = jack_hook_write,
  827. };
  828. static int unload_module(void)
  829. {
  830. int res;
  831. res = ast_unregister_application(jack_app);
  832. res |= ast_custom_function_unregister(&jack_hook_function);
  833. return res;
  834. }
  835. static int load_module(void)
  836. {
  837. if (ast_register_application_xml(jack_app, jack_exec)) {
  838. return AST_MODULE_LOAD_DECLINE;
  839. }
  840. if (ast_custom_function_register(&jack_hook_function)) {
  841. ast_unregister_application(jack_app);
  842. return AST_MODULE_LOAD_DECLINE;
  843. }
  844. return AST_MODULE_LOAD_SUCCESS;
  845. }
  846. AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "JACK Interface");