jack1 codebase
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.

636 lines
15KB

  1. /* -*- Mode: C ; c-basic-offset: 2 -*- */
  2. /*
  3. * ALSA SEQ < - > JACK MIDI bridge
  4. *
  5. * Copyright (c) 2006,2007 Dmitry S. Baikov <c0ff@konstruktiv.org>
  6. * Copyright (c) 2007,2008,2009 Nedko Arnaudov <nedko@arnaudov.name>
  7. * Copyright (c) 2009,2010 Paul Davis <paul@linuxaudiosystems.com>
  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; version 2 of the License.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. */
  22. #include <stdbool.h>
  23. #include <stdarg.h>
  24. #include <string.h>
  25. #include <time.h>
  26. #include <alsa/asoundlib.h>
  27. #include <jack/jack.h>
  28. #include <jack/midiport.h>
  29. #include <jack/ringbuffer.h>
  30. #include "list.h"
  31. #include "a2j.h"
  32. #include "port_hash.h"
  33. #include "port.h"
  34. #include "port_thread.h"
  35. static bool g_freewheeling = false;
  36. bool g_keep_walking = true;
  37. bool g_keep_alsa_walking = false;
  38. bool g_stop_request = false;
  39. bool g_started = false;
  40. void
  41. a2j_info (const char* fmt, ...)
  42. {
  43. va_list ap;
  44. va_start (ap, fmt);
  45. vfprintf (stdout, fmt, ap);
  46. fputc ('\n', stdout);
  47. }
  48. void
  49. a2j_error (const char* fmt, ...)
  50. {
  51. va_list ap;
  52. va_start (ap, fmt);
  53. vfprintf (stdout, fmt, ap);
  54. fputc ('\n', stdout);
  55. }
  56. void
  57. a2j_debug (const char* fmt, ...)
  58. {
  59. va_list ap;
  60. va_start (ap, fmt);
  61. vfprintf (stderr, fmt, ap);
  62. fputc ('\n', stdout);
  63. }
  64. void
  65. a2j_warning (const char* fmt, ...)
  66. {
  67. va_list ap;
  68. va_start (ap, fmt);
  69. vfprintf (stdout, fmt, ap);
  70. fputc ('\n', stdout);
  71. }
  72. static bool
  73. a2j_stream_init(struct a2j * self)
  74. {
  75. struct a2j_stream *str = &self->stream;
  76. str->new_ports = jack_ringbuffer_create (MAX_PORTS * sizeof(struct a2j_port *));
  77. if (str->new_ports == NULL) {
  78. return false;
  79. }
  80. snd_midi_event_new (MAX_EVENT_SIZE, &str->codec);
  81. INIT_LIST_HEAD (&str->list);
  82. return true;
  83. }
  84. static void
  85. a2j_stream_attach (struct a2j_stream * stream_ptr)
  86. {
  87. }
  88. static void
  89. a2j_stream_detach (struct a2j_stream * stream_ptr)
  90. {
  91. struct a2j_port * port_ptr;
  92. struct list_head * node_ptr;
  93. while (!list_empty (&stream_ptr->list)) {
  94. node_ptr = stream_ptr->list.next;
  95. list_del (node_ptr);
  96. port_ptr = list_entry (node_ptr, struct a2j_port, siblings);
  97. a2j_info ("port deleted: %s", port_ptr->name);
  98. a2j_port_free (port_ptr);
  99. }
  100. }
  101. static
  102. void
  103. a2j_stream_close (struct a2j * self)
  104. {
  105. struct a2j_stream *str = &self->stream;
  106. if (str->codec)
  107. snd_midi_event_free (str->codec);
  108. if (str->new_ports)
  109. jack_ringbuffer_free (str->new_ports);
  110. }
  111. /*
  112. * =================== Input/output port handling =========================
  113. */
  114. void a2j_add_ports (struct a2j_stream * str)
  115. {
  116. struct a2j_port * port_ptr;
  117. while (jack_ringbuffer_read (str->new_ports, (char *)&port_ptr, sizeof(port_ptr))) {
  118. a2j_debug("jack: inserted port %s", port_ptr->name);
  119. a2j_port_insert (str->port_hash, port_ptr);
  120. }
  121. }
  122. static
  123. void
  124. a2j_port_event (struct a2j * self, snd_seq_event_t * ev)
  125. {
  126. const snd_seq_addr_t addr = ev->data.addr;
  127. if (addr.client == self->client_id)
  128. return;
  129. if (ev->type == SND_SEQ_EVENT_PORT_START || ev->type == SND_SEQ_EVENT_PORT_CHANGE) {
  130. if (jack_ringbuffer_write_space(self->port_add) >= sizeof(addr)) {
  131. a2j_debug("port_event: add/change %d:%d", addr.client, addr.port);
  132. jack_ringbuffer_write(self->port_add, (char*)&addr, sizeof(addr));
  133. } else {
  134. a2j_error("dropping port_event: add/change %d:%d", addr.client, addr.port);
  135. }
  136. } else if (ev->type == SND_SEQ_EVENT_PORT_EXIT) {
  137. a2j_debug("port_event: del %d:%d", addr.client, addr.port);
  138. a2j_port_setdead(self->stream.port_hash, addr);
  139. }
  140. }
  141. static void
  142. a2j_input_event (struct a2j * self, snd_seq_event_t * alsa_event)
  143. {
  144. jack_midi_data_t data[MAX_EVENT_SIZE];
  145. struct a2j_stream *str = &self->stream;
  146. long size;
  147. struct a2j_port *port;
  148. jack_nframes_t now;
  149. now = jack_frame_time (self->jack_client);
  150. if ((port = a2j_port_get(str->port_hash, alsa_event->source)) == NULL) {
  151. return;
  152. }
  153. /*
  154. * RPNs, NRPNs, Bank Change, etc. need special handling
  155. * but seems, ALSA does it for us already.
  156. */
  157. snd_midi_event_reset_decode(str->codec);
  158. if ((size = snd_midi_event_decode(str->codec, data, sizeof(data), alsa_event))<0) {
  159. return;
  160. }
  161. // fixup NoteOn with vel 0
  162. if ((data[0] & 0xF0) == 0x90 && data[2] == 0x00) {
  163. data[0] = 0x80 + (data[0] & 0x0F);
  164. data[2] = 0x40;
  165. }
  166. a2j_debug("input: %d bytes at event_frame=%u", (int)size, now);
  167. if (jack_ringbuffer_write_space(port->inbound_events) >= (sizeof(struct a2j_alsa_midi_event) + size)) {
  168. struct a2j_alsa_midi_event ev;
  169. char *ev_charp = (char*) &ev;
  170. size_t limit;
  171. size_t to_write = sizeof(ev);
  172. jack_ringbuffer_data_t vec[2];
  173. jack_ringbuffer_get_write_vector( port->inbound_events, vec );
  174. ev.time = now;
  175. ev.size = size;
  176. limit = (to_write > vec[0].len ? vec[0].len : to_write);
  177. if( limit ) {
  178. memcpy( vec[0].buf, ev_charp, limit );
  179. to_write -= limit;
  180. ev_charp += limit;
  181. vec[0].buf += limit;
  182. vec[0].len -= limit;
  183. }
  184. if( to_write ) {
  185. memcpy( vec[1].buf, ev_charp, to_write );
  186. vec[1].buf += to_write;
  187. vec[1].len -= to_write;
  188. }
  189. to_write = size;
  190. ev_charp = (char *)data;
  191. limit = (to_write > vec[0].len ? vec[0].len : to_write);
  192. if( limit )
  193. memcpy( vec[0].buf, ev_charp, limit );
  194. to_write -= limit;
  195. ev_charp += limit;
  196. if( to_write )
  197. memcpy( vec[1].buf, ev_charp, to_write );
  198. jack_ringbuffer_write_advance( port->inbound_events, sizeof(ev) + size );
  199. } else {
  200. a2j_error ("MIDI data lost (incoming event buffer full): %ld bytes lost", size);
  201. }
  202. }
  203. /* ALSA */
  204. void* alsa_input_thread(void * arg)
  205. {
  206. struct a2j * self = arg;
  207. int npfd;
  208. struct pollfd * pfd;
  209. snd_seq_addr_t addr;
  210. snd_seq_client_info_t * client_info;
  211. snd_seq_port_info_t * port_info;
  212. bool initial;
  213. snd_seq_event_t * event;
  214. int ret;
  215. npfd = snd_seq_poll_descriptors_count(self->seq, POLLIN);
  216. pfd = (struct pollfd *)alloca(npfd * sizeof(struct pollfd));
  217. snd_seq_poll_descriptors(self->seq, pfd, npfd, POLLIN);
  218. initial = true;
  219. while (g_keep_alsa_walking) {
  220. if ((ret = poll(pfd, npfd, 1000)) > 0) {
  221. while (snd_seq_event_input (self->seq, &event) > 0) {
  222. if (initial) {
  223. snd_seq_client_info_alloca(&client_info);
  224. snd_seq_port_info_alloca(&port_info);
  225. snd_seq_client_info_set_client(client_info, -1);
  226. while (snd_seq_query_next_client(self->seq, client_info) >= 0) {
  227. addr.client = snd_seq_client_info_get_client(client_info);
  228. if (addr.client == SND_SEQ_CLIENT_SYSTEM || addr.client == self->client_id) {
  229. continue;
  230. }
  231. snd_seq_port_info_set_client(port_info, addr.client);
  232. snd_seq_port_info_set_port(port_info, -1);
  233. while (snd_seq_query_next_port(self->seq, port_info) >= 0) {
  234. addr.port = snd_seq_port_info_get_port(port_info);
  235. a2j_update_port(self, addr, port_info);
  236. }
  237. }
  238. initial = false;
  239. }
  240. if (event->source.client == SND_SEQ_CLIENT_SYSTEM) {
  241. a2j_port_event(self, event);
  242. } else {
  243. a2j_input_event(self, event);
  244. }
  245. snd_seq_free_event (event);
  246. }
  247. }
  248. }
  249. return (void*) 0;
  250. }
  251. /* JACK */
  252. static int
  253. a2j_process (jack_nframes_t nframes, void * arg)
  254. {
  255. struct a2j* self = (struct a2j *) arg;
  256. struct a2j_stream * stream_ptr;
  257. int i;
  258. struct a2j_port ** port_ptr;
  259. struct a2j_port * port;
  260. if (g_freewheeling) {
  261. return 0;
  262. }
  263. self->cycle_start = jack_last_frame_time (self->jack_client);
  264. stream_ptr = &self->stream;
  265. a2j_add_ports (stream_ptr);
  266. // process ports
  267. for (i = 0 ; i < PORT_HASH_SIZE ; i++) {
  268. port_ptr = &stream_ptr->port_hash[i];
  269. while (*port_ptr != NULL) {
  270. struct a2j_alsa_midi_event ev;
  271. jack_nframes_t now;
  272. jack_nframes_t one_period;
  273. char *ev_buf;
  274. port = *port_ptr;
  275. if (port->is_dead) {
  276. if (jack_ringbuffer_write_space (self->port_del) >= sizeof(port_ptr)) {
  277. a2j_debug("jack: removed port %s", port->name);
  278. *port_ptr = port->next;
  279. jack_ringbuffer_write (self->port_del, (char*)&port, sizeof(port));
  280. } else {
  281. a2j_error ("port deletion lost - no space in event buffer!");
  282. }
  283. port_ptr = &port->next;
  284. continue;
  285. }
  286. port->jack_buf = jack_port_get_buffer(port->jack_port, nframes);
  287. /* grab data queued by the ALSA input thread and write it into the JACK
  288. port buffer. it will delivered during the JACK period that this
  289. function is called from.
  290. */
  291. /* first clear the JACK port buffer in preparation for new data
  292. */
  293. // a2j_debug ("PORT: %s process input", jack_port_name (port->jack_port));
  294. jack_midi_clear_buffer (port->jack_buf);
  295. now = jack_frame_time (self->jack_client);
  296. one_period = jack_get_buffer_size (self->jack_client);
  297. while (jack_ringbuffer_peek (port->inbound_events, (char*)&ev, sizeof(ev) ) == sizeof(ev) ) {
  298. jack_midi_data_t* buf;
  299. jack_nframes_t offset;
  300. if (ev.time >= self->cycle_start) {
  301. break;
  302. }
  303. //jack_ringbuffer_read_advance (port->inbound_events, sizeof (ev));
  304. ev_buf = (char *) alloca( sizeof(ev) + ev.size );
  305. if (jack_ringbuffer_peek (port->inbound_events, ev_buf, sizeof(ev) + ev.size ) != sizeof(ev) + ev.size)
  306. break;
  307. offset = self->cycle_start - ev.time;
  308. if (offset > one_period) {
  309. /* from a previous cycle, somehow. cram it in at the front */
  310. offset = 0;
  311. } else {
  312. /* offset from start of the current cycle */
  313. offset = one_period - offset;
  314. }
  315. a2j_debug ("event at %d offset %d", ev.time, offset);
  316. /* make sure there is space for it */
  317. buf = jack_midi_event_reserve (port->jack_buf, offset, ev.size);
  318. if (buf) {
  319. /* grab the event */
  320. memcpy( buf, ev_buf + sizeof(ev), ev.size );
  321. } else {
  322. /* throw it away (no space) */
  323. a2j_error ("threw away MIDI event - not reserved at time %d", ev.time);
  324. }
  325. jack_ringbuffer_read_advance (port->inbound_events, sizeof(ev) + ev.size);
  326. a2j_debug("input on %s: sucked %d bytes from inbound at %d", jack_port_name (port->jack_port), ev.size, ev.time);
  327. }
  328. port_ptr = &port->next;
  329. }
  330. }
  331. return 0;
  332. }
  333. static
  334. void
  335. a2j_freewheel(
  336. int starting,
  337. void * arg)
  338. {
  339. g_freewheeling = starting;
  340. }
  341. static
  342. void
  343. a2j_shutdown(
  344. void * arg)
  345. {
  346. a2j_warning("JACK server shutdown notification received.");
  347. g_stop_request = true;
  348. }
  349. int
  350. connect_to_alsa (struct a2j* self)
  351. {
  352. int error;
  353. void * thread_status;
  354. self->port_add = jack_ringbuffer_create(2 * MAX_PORTS * sizeof(snd_seq_addr_t));
  355. if (self->port_add == NULL) {
  356. goto free_self;
  357. }
  358. self->port_del = jack_ringbuffer_create(2 * MAX_PORTS * sizeof(struct a2j_port *));
  359. if (self->port_del == NULL) {
  360. goto free_ringbuffer_add;
  361. }
  362. if (!a2j_stream_init(self)) {
  363. goto free_ringbuffer_outbound;
  364. }
  365. if ((error = snd_seq_open(&self->seq, "hw", SND_SEQ_OPEN_DUPLEX, 0)) < 0) {
  366. a2j_error("failed to open alsa seq");
  367. goto close_stream;
  368. }
  369. if ((error = snd_seq_set_client_name(self->seq, "midi_in")) < 0) {
  370. a2j_error("snd_seq_set_client_name() failed");
  371. goto close_seq_client;
  372. }
  373. if ((self->port_id = snd_seq_create_simple_port(
  374. self->seq,
  375. "port",
  376. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_WRITE
  377. #ifndef DEBUG
  378. |SND_SEQ_PORT_CAP_NO_EXPORT
  379. #endif
  380. ,SND_SEQ_PORT_TYPE_APPLICATION)) < 0) {
  381. a2j_error("snd_seq_create_simple_port() failed");
  382. goto close_seq_client;
  383. }
  384. if ((self->client_id = snd_seq_client_id(self->seq)) < 0) {
  385. a2j_error("snd_seq_client_id() failed");
  386. goto close_seq_client;
  387. }
  388. if ((self->queue = snd_seq_alloc_queue(self->seq)) < 0) {
  389. a2j_error("snd_seq_alloc_queue() failed");
  390. goto close_seq_client;
  391. }
  392. snd_seq_start_queue (self->seq, self->queue, 0);
  393. a2j_stream_attach (&self->stream);
  394. if ((error = snd_seq_nonblock(self->seq, 1)) < 0) {
  395. a2j_error("snd_seq_nonblock() failed");
  396. goto close_seq_client;
  397. }
  398. snd_seq_drop_input (self->seq);
  399. a2j_add_ports(&self->stream);
  400. if (sem_init(&self->io_semaphore, 0, 0) < 0) {
  401. a2j_error("can't create IO semaphore");
  402. goto close_jack_client;
  403. }
  404. g_keep_alsa_walking = true;
  405. if (pthread_create(&self->alsa_io_thread, NULL, alsa_input_thread, self) < 0)
  406. {
  407. a2j_error("cannot start ALSA input thread");
  408. goto sem_destroy;
  409. }
  410. /* wake the poll loop in the alsa input thread so initial ports are fetched */
  411. if ((error = snd_seq_connect_from (self->seq, self->port_id, SND_SEQ_CLIENT_SYSTEM, SND_SEQ_PORT_SYSTEM_ANNOUNCE)) < 0) {
  412. a2j_error("snd_seq_connect_from() failed");
  413. goto join_io_thread;
  414. }
  415. return 0;
  416. g_keep_alsa_walking = false; /* tell alsa threads to stop */
  417. snd_seq_disconnect_from(self->seq, self->port_id, SND_SEQ_CLIENT_SYSTEM, SND_SEQ_PORT_SYSTEM_ANNOUNCE);
  418. join_io_thread:
  419. pthread_join(self->alsa_io_thread, &thread_status);
  420. sem_destroy:
  421. sem_destroy(&self->io_semaphore);
  422. close_jack_client:
  423. if ((error = jack_client_close(self->jack_client)) < 0) {
  424. a2j_error("Cannot close jack client");
  425. }
  426. close_seq_client:
  427. snd_seq_close(self->seq);
  428. close_stream:
  429. a2j_stream_close(self);
  430. free_ringbuffer_outbound:
  431. jack_ringbuffer_free(self->outbound_events);
  432. jack_ringbuffer_free(self->port_del);
  433. free_ringbuffer_add:
  434. jack_ringbuffer_free(self->port_add);
  435. free_self:
  436. free(self);
  437. return -1;
  438. }
  439. /* JACK internal client API: 2 entry points
  440. */
  441. int
  442. jack_initialize (jack_client_t *client, const char* load_init)
  443. {
  444. struct a2j* self = calloc(1, sizeof(struct a2j));
  445. if (!self) {
  446. return -1;
  447. }
  448. self->jack_client = client;
  449. self->input = 1;
  450. self->ignore_hardware_ports = 0;
  451. self->finishing = 0;
  452. if (load_init) {
  453. char* args = strdup (load_init);
  454. char* token;
  455. char* ptr = args;
  456. char* savep;
  457. while (1) {
  458. if ((token = strtok_r (ptr, ", ", &savep)) == NULL) {
  459. break;
  460. }
  461. if (strncasecmp (token, "in", 2) == 0) {
  462. self->input = 1;
  463. }
  464. if (strncasecmp (token, "out", 2) == 0) {
  465. self->input = 0;
  466. }
  467. if (strncasecmp (token, "hw", 2) == 0) {
  468. self->ignore_hardware_ports = 0;
  469. }
  470. ptr = NULL;
  471. }
  472. free (args);
  473. }
  474. if (connect_to_alsa (self)) {
  475. free (self);
  476. return -1;
  477. }
  478. jack_set_process_callback (client, a2j_process, self);
  479. jack_set_freewheel_callback (client, a2j_freewheel, NULL);
  480. jack_on_shutdown (client, a2j_shutdown, NULL);
  481. jack_activate (client);
  482. return 0;
  483. }
  484. void
  485. jack_finish (void *arg)
  486. {
  487. struct a2j* self = (struct a2j*) arg;
  488. void* thread_status;
  489. self->finishing = 1;
  490. a2j_debug("midi: delete");
  491. g_keep_alsa_walking = false; /* tell alsa io thread to stop, whenever they wake up */
  492. /* do something that we need to do anyway and will wake the io thread, then join */
  493. snd_seq_disconnect_from (self->seq, self->port_id, SND_SEQ_CLIENT_SYSTEM, SND_SEQ_PORT_SYSTEM_ANNOUNCE);
  494. a2j_debug ("wait for ALSA io thread\n");
  495. pthread_join (self->alsa_io_thread, &thread_status);
  496. a2j_debug ("thread done\n");
  497. jack_ringbuffer_reset (self->port_add);
  498. a2j_stream_detach (&self->stream);
  499. snd_seq_close(self->seq);
  500. self->seq = NULL;
  501. a2j_stream_close (self);
  502. jack_ringbuffer_free(self->port_add);
  503. jack_ringbuffer_free(self->port_del);
  504. free (self);
  505. }