jack2 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.

968 lines
25KB

  1. /*
  2. * ALSA SEQ < - > JACK MIDI bridge
  3. *
  4. * Copyright (c) 2006,2007 Dmitry S. Baikov <c0ff@konstruktiv.org>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. /*
  21. * alsa_seqmidi_read:
  22. * add new ports
  23. * reads queued snd_seq_event's
  24. * if PORT_EXIT: mark port as dead
  25. * if PORT_ADD, PORT_CHANGE: send addr to port_thread (it also may mark port as dead)
  26. * else process input event
  27. * remove dead ports and send them to port_thread
  28. *
  29. * alsa_seqmidi_write:
  30. * remove dead ports and send them to port_thread
  31. * add new ports
  32. * queue output events
  33. *
  34. * port_thread:
  35. * wait for port_sem
  36. * free deleted ports
  37. * create new ports or mark existing as dead
  38. */
  39. #include <alsa/asoundlib.h>
  40. #include <stdlib.h>
  41. #include <stdio.h>
  42. #include <signal.h>
  43. #include <semaphore.h>
  44. #include <pthread.h>
  45. #include <time.h>
  46. #include <ctype.h>
  47. #include <limits.h>
  48. #include "midiport.h"
  49. #include "ringbuffer.h"
  50. #include "alsa_midi_impl.h"
  51. #include "JackError.h"
  52. #define NSEC_PER_SEC ((int64_t)1000*1000*1000)
  53. enum {
  54. MAX_PORTS = 64,
  55. MAX_EVENT_SIZE = 1024,
  56. };
  57. typedef struct port_t port_t;
  58. enum {
  59. PORT_HASH_BITS = 4,
  60. PORT_HASH_SIZE = 1 << PORT_HASH_BITS
  61. };
  62. typedef port_t* port_hash_t[PORT_HASH_SIZE];
  63. struct port_t {
  64. port_t *next;
  65. int is_dead;
  66. char name[64];
  67. snd_seq_addr_t remote;
  68. jack_port_t *jack_port;
  69. jack_ringbuffer_t *early_events; // alsa_midi_event_t + data
  70. int64_t last_out_time;
  71. void *jack_buf;
  72. };
  73. typedef struct {
  74. snd_midi_event_t *codec;
  75. jack_ringbuffer_t *new_ports;
  76. port_t *ports[MAX_PORTS];
  77. } stream_t;
  78. typedef struct alsa_seqmidi {
  79. alsa_midi_t ops;
  80. jack_client_t *jack;
  81. snd_seq_t *seq;
  82. snd_seq_queue_timer_t* timer;
  83. int client_id;
  84. int port_id;
  85. int queue;
  86. int keep_walking;
  87. pthread_t port_thread;
  88. sem_t port_sem;
  89. jack_ringbuffer_t *port_add; // snd_seq_addr_t
  90. jack_ringbuffer_t *port_del; // port_t*
  91. stream_t stream[2];
  92. char alsa_name[32];
  93. int midi_in_cnt;
  94. int midi_out_cnt;
  95. } alsa_seqmidi_t;
  96. struct alsa_midi_event {
  97. int64_t time;
  98. int size;
  99. };
  100. typedef struct alsa_midi_event alsa_midi_event_t;
  101. struct process_info {
  102. int dir;
  103. jack_nframes_t nframes;
  104. jack_nframes_t period_start;
  105. jack_nframes_t sample_rate;
  106. jack_nframes_t cur_frames;
  107. int64_t alsa_time;
  108. };
  109. enum PortType { PORT_INPUT = 0, PORT_OUTPUT = 1 };
  110. typedef void (*port_jack_func)(alsa_seqmidi_t *self, port_t *port,struct process_info* info);
  111. static void do_jack_input(alsa_seqmidi_t *self, port_t *port, struct process_info* info);
  112. static void do_jack_output(alsa_seqmidi_t *self, port_t *port, struct process_info* info);
  113. typedef struct {
  114. int alsa_mask;
  115. int jack_caps;
  116. char name[9];
  117. port_jack_func jack_func;
  118. } port_type_t;
  119. static port_type_t port_type[2] = {
  120. {
  121. SND_SEQ_PORT_CAP_SUBS_READ,
  122. JackPortIsOutput,
  123. "capture",
  124. do_jack_input
  125. },
  126. {
  127. SND_SEQ_PORT_CAP_SUBS_WRITE,
  128. JackPortIsInput,
  129. "playback",
  130. do_jack_output
  131. }
  132. };
  133. static void alsa_seqmidi_delete(alsa_midi_t *m);
  134. static int alsa_seqmidi_attach(alsa_midi_t *m);
  135. static int alsa_seqmidi_detach(alsa_midi_t *m);
  136. static int alsa_seqmidi_start(alsa_midi_t *m);
  137. static int alsa_seqmidi_stop(alsa_midi_t *m);
  138. static void alsa_seqmidi_read(alsa_midi_t *m, jack_nframes_t nframes);
  139. static void alsa_seqmidi_write(alsa_midi_t *m, jack_nframes_t nframes);
  140. static
  141. void stream_init(alsa_seqmidi_t *self, int dir)
  142. {
  143. stream_t *str = &self->stream[dir];
  144. str->new_ports = jack_ringbuffer_create(MAX_PORTS*sizeof(port_t*));
  145. snd_midi_event_new(MAX_EVENT_SIZE, &str->codec);
  146. }
  147. static void port_free(alsa_seqmidi_t *self, port_t *port);
  148. static void free_ports(alsa_seqmidi_t *self, jack_ringbuffer_t *ports);
  149. static
  150. void stream_attach(alsa_seqmidi_t *self, int dir)
  151. {
  152. }
  153. static
  154. void stream_detach(alsa_seqmidi_t *self, int dir)
  155. {
  156. stream_t *str = &self->stream[dir];
  157. int i;
  158. free_ports(self, str->new_ports);
  159. // delete all ports from hash
  160. for (i=0; i<PORT_HASH_SIZE; ++i) {
  161. port_t *port = str->ports[i];
  162. while (port) {
  163. port_t *next = port->next;
  164. port_free(self, port);
  165. port = next;
  166. }
  167. str->ports[i] = NULL;
  168. }
  169. }
  170. static
  171. void stream_close(alsa_seqmidi_t *self, int dir)
  172. {
  173. stream_t *str = &self->stream[dir];
  174. if (str->codec)
  175. snd_midi_event_free(str->codec);
  176. if (str->new_ports)
  177. jack_ringbuffer_free(str->new_ports);
  178. }
  179. alsa_midi_t* alsa_seqmidi_new(jack_client_t *client, const char* alsa_name)
  180. {
  181. alsa_seqmidi_t *self = calloc(1, sizeof(alsa_seqmidi_t));
  182. debug_log("midi: new");
  183. if (!self)
  184. return NULL;
  185. self->jack = client;
  186. if (!alsa_name)
  187. alsa_name = "jack_midi";
  188. snprintf(self->alsa_name, sizeof(self->alsa_name), "%s", alsa_name);
  189. self->port_add = jack_ringbuffer_create(2*MAX_PORTS*sizeof(snd_seq_addr_t));
  190. self->port_del = jack_ringbuffer_create(2*MAX_PORTS*sizeof(port_t*));
  191. sem_init(&self->port_sem, 0, 0);
  192. stream_init(self, PORT_INPUT);
  193. stream_init(self, PORT_OUTPUT);
  194. self->midi_in_cnt = 0;
  195. self->midi_out_cnt = 0;
  196. self->ops.destroy = alsa_seqmidi_delete;
  197. self->ops.attach = alsa_seqmidi_attach;
  198. self->ops.detach = alsa_seqmidi_detach;
  199. self->ops.start = alsa_seqmidi_start;
  200. self->ops.stop = alsa_seqmidi_stop;
  201. self->ops.read = alsa_seqmidi_read;
  202. self->ops.write = alsa_seqmidi_write;
  203. return &self->ops;
  204. }
  205. static
  206. void alsa_seqmidi_delete(alsa_midi_t *m)
  207. {
  208. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  209. debug_log("midi: delete");
  210. alsa_seqmidi_detach(m);
  211. stream_close(self, PORT_OUTPUT);
  212. stream_close(self, PORT_INPUT);
  213. jack_ringbuffer_free(self->port_add);
  214. jack_ringbuffer_free(self->port_del);
  215. sem_close(&self->port_sem);
  216. free(self);
  217. }
  218. static
  219. int alsa_seqmidi_attach(alsa_midi_t *m)
  220. {
  221. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  222. int err;
  223. debug_log("midi: attach");
  224. if (self->seq)
  225. return -EALREADY;
  226. if ((err = snd_seq_open(&self->seq, "hw", SND_SEQ_OPEN_DUPLEX, 0)) < 0) {
  227. error_log("failed to open alsa seq");
  228. return err;
  229. }
  230. if ((err = snd_seq_queue_timer_malloc(&self->timer)) < 0) {
  231. error_log("failed to allocate timer");
  232. return err;
  233. }
  234. snd_seq_set_client_name(self->seq, self->alsa_name);
  235. self->port_id = snd_seq_create_simple_port(self->seq, "port",
  236. SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_WRITE
  237. #ifndef JACK_MIDI_DEBUG
  238. |SND_SEQ_PORT_CAP_NO_EXPORT
  239. #endif
  240. ,SND_SEQ_PORT_TYPE_APPLICATION);
  241. self->client_id = snd_seq_client_id(self->seq);
  242. self->queue = snd_seq_alloc_queue(self->seq);
  243. // set high resolution
  244. if (snd_seq_get_queue_timer(self->seq, self->queue, self->timer) == 0) {
  245. snd_seq_queue_timer_set_resolution(self->timer, UINT_MAX);
  246. snd_seq_set_queue_timer(self->seq, self->queue, self->timer);
  247. } else {
  248. error_log("failed to set alsa timer in high resolution");
  249. }
  250. snd_seq_start_queue(self->seq, self->queue, 0);
  251. stream_attach(self, PORT_INPUT);
  252. stream_attach(self, PORT_OUTPUT);
  253. snd_seq_nonblock(self->seq, 1);
  254. return 0;
  255. }
  256. static
  257. int alsa_seqmidi_detach(alsa_midi_t *m)
  258. {
  259. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  260. debug_log("midi: detach");
  261. if (!self->seq)
  262. return -EALREADY;
  263. alsa_seqmidi_stop(m);
  264. jack_ringbuffer_reset(self->port_add);
  265. free_ports(self, self->port_del);
  266. stream_detach(self, PORT_INPUT);
  267. stream_detach(self, PORT_OUTPUT);
  268. snd_seq_queue_timer_free(self->timer);
  269. snd_seq_close(self->seq);
  270. self->seq = NULL;
  271. return 0;
  272. }
  273. static void* port_thread(void *);
  274. static void add_existing_ports(alsa_seqmidi_t *self);
  275. static void update_ports(alsa_seqmidi_t *self);
  276. static void add_ports(stream_t *str);
  277. static
  278. int alsa_seqmidi_start(alsa_midi_t *m)
  279. {
  280. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  281. int err;
  282. debug_log("midi: start");
  283. if (!self->seq)
  284. return -EBADF;
  285. if (self->keep_walking)
  286. return -EALREADY;
  287. snd_seq_connect_from(self->seq, self->port_id, SND_SEQ_CLIENT_SYSTEM, SND_SEQ_PORT_SYSTEM_ANNOUNCE);
  288. snd_seq_drop_input(self->seq);
  289. add_existing_ports(self);
  290. update_ports(self);
  291. add_ports(&self->stream[PORT_INPUT]);
  292. add_ports(&self->stream[PORT_OUTPUT]);
  293. self->keep_walking = 1;
  294. if ((err = pthread_create(&self->port_thread, NULL, port_thread, self))) {
  295. self->keep_walking = 0;
  296. return -errno;
  297. }
  298. return 0;
  299. }
  300. static
  301. int alsa_seqmidi_stop(alsa_midi_t *m)
  302. {
  303. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  304. debug_log("midi: stop");
  305. if (!self->keep_walking)
  306. return -EALREADY;
  307. snd_seq_disconnect_from(self->seq, self->port_id, SND_SEQ_CLIENT_SYSTEM, SND_SEQ_PORT_SYSTEM_ANNOUNCE);
  308. self->keep_walking = 0;
  309. sem_post(&self->port_sem);
  310. pthread_join(self->port_thread, NULL);
  311. self->port_thread = 0;
  312. return 0;
  313. }
  314. static
  315. int alsa_connect_from(alsa_seqmidi_t *self, int client, int port)
  316. {
  317. snd_seq_port_subscribe_t* sub;
  318. snd_seq_addr_t seq_addr;
  319. int err;
  320. snd_seq_port_subscribe_alloca(&sub);
  321. seq_addr.client = client;
  322. seq_addr.port = port;
  323. snd_seq_port_subscribe_set_sender(sub, &seq_addr);
  324. seq_addr.client = self->client_id;
  325. seq_addr.port = self->port_id;
  326. snd_seq_port_subscribe_set_dest(sub, &seq_addr);
  327. snd_seq_port_subscribe_set_time_update(sub, 1);
  328. snd_seq_port_subscribe_set_queue(sub, self->queue);
  329. snd_seq_port_subscribe_set_time_real(sub, 1);
  330. if ((err=snd_seq_subscribe_port(self->seq, sub)))
  331. error_log("can't subscribe to %d:%d - %s", client, port, snd_strerror(err));
  332. return err;
  333. }
  334. /*
  335. * ==================== Port routines =============================
  336. */
  337. static inline
  338. int port_hash(snd_seq_addr_t addr)
  339. {
  340. return (addr.client + addr.port) % PORT_HASH_SIZE;
  341. }
  342. static
  343. port_t* port_get(port_hash_t hash, snd_seq_addr_t addr)
  344. {
  345. port_t **pport = &hash[port_hash(addr)];
  346. while (*pport) {
  347. port_t *port = *pport;
  348. if (port->remote.client == addr.client && port->remote.port == addr.port)
  349. return port;
  350. pport = &port->next;
  351. }
  352. return NULL;
  353. }
  354. static
  355. void port_insert(port_hash_t hash, port_t *port)
  356. {
  357. port_t **pport = &hash[port_hash(port->remote)];
  358. port->next = *pport;
  359. *pport = port;
  360. }
  361. static
  362. void port_setdead(port_hash_t hash, snd_seq_addr_t addr)
  363. {
  364. port_t *port = port_get(hash, addr);
  365. if (port)
  366. port->is_dead = 1; // see jack_process
  367. else {
  368. debug_log("port_setdead: not found (%d:%d)", addr.client, addr.port);
  369. }
  370. }
  371. static
  372. void port_free(alsa_seqmidi_t *self, port_t *port)
  373. {
  374. //snd_seq_disconnect_from(self->seq, self->port_id, port->remote.client, port->remote.port);
  375. //snd_seq_disconnect_to(self->seq, self->port_id, port->remote.client, port->remote.port);
  376. if (port->early_events)
  377. jack_ringbuffer_free(port->early_events);
  378. if (port->jack_port)
  379. jack_port_unregister(self->jack, port->jack_port);
  380. info_log("port deleted: %s", port->name);
  381. free(port);
  382. }
  383. static
  384. port_t* port_create(alsa_seqmidi_t *self, int type, snd_seq_addr_t addr, const snd_seq_port_info_t *info)
  385. {
  386. snd_seq_client_info_t* client_info;
  387. port_t *port;
  388. char *c;
  389. int err;
  390. int jack_caps;
  391. char name[128];
  392. port = calloc(1, sizeof(port_t));
  393. if (!port)
  394. return NULL;
  395. port->remote = addr;
  396. snd_seq_client_info_alloca (&client_info);
  397. snd_seq_get_any_client_info (self->seq, addr.client, client_info);
  398. jack_caps = port_type[type].jack_caps;
  399. /* mark anything that looks like a hardware port as physical&terminal */
  400. if (snd_seq_port_info_get_type (info) & (SND_SEQ_PORT_TYPE_HARDWARE|SND_SEQ_PORT_TYPE_PORT|SND_SEQ_PORT_TYPE_SPECIFIC)) {
  401. jack_caps |= (JackPortIsPhysical | JackPortIsTerminal);
  402. }
  403. if (jack_caps & JackPortIsOutput)
  404. snprintf(name, sizeof(name), "system:midi_capture_%d", ++self->midi_in_cnt);
  405. else
  406. snprintf(name, sizeof(name), "system:midi_playback_%d", ++self->midi_out_cnt);
  407. port->jack_port = jack_port_register(self->jack,
  408. name, JACK_DEFAULT_MIDI_TYPE, jack_caps, 0);
  409. if (!port->jack_port)
  410. goto failed;
  411. // First alias: Jack1-compatible port name. -ag
  412. const char *device_name = snd_seq_client_info_get_name(client_info);
  413. const char* port_name = snd_seq_port_info_get_name (info);
  414. const char* type_name = jack_caps & JackPortIsOutput ? "out" : "in";
  415. // This code is pilfered from Jack1. -ag
  416. if (strstr (port_name, device_name) == port_name) {
  417. /* entire client name is part of the port name so don't replicate it */
  418. snprintf (port->name,
  419. sizeof(port->name),
  420. "alsa_midi:%s (%s)",
  421. port_name,
  422. type_name);
  423. } else {
  424. snprintf (port->name,
  425. sizeof(port->name),
  426. "alsa_midi:%s %s (%s)",
  427. device_name,
  428. port_name,
  429. type_name);
  430. }
  431. // replace all offending characters with ' '
  432. for (c = port->name; *c; ++c) {
  433. if (!isalnum(*c) && *c != ' ' && *c != '/' && *c != '_' && *c != ':' && *c != '(' && *c != ')') {
  434. *c = ' ';
  435. }
  436. }
  437. jack_port_set_alias (port->jack_port, port->name);
  438. jack_port_set_default_metadata (port->jack_port, device_name);
  439. // Second alias: Strip the alsa_midi prefix, so that devices appear
  440. // under their ALSA names. Use the ALSA port names (without device
  441. // prefix) for the individual ports. -ag
  442. if (strstr (port_name, device_name) == port_name) {
  443. // remove the device name prefix from the port name if present
  444. port_name += strlen(device_name);
  445. while (*port_name == ' ' || *port_name == '\t')
  446. port_name++;
  447. }
  448. snprintf(port->name, sizeof(port->name), "%s:%s (%s)",
  449. device_name, port_name, port_type[type].name);
  450. // replace all offending characters with ' '
  451. for (c = port->name; *c; ++c) {
  452. if (!isalnum(*c) && *c != ' ' && *c != '/' && *c != '_' && *c != ':' && *c != '(' && *c != ')') {
  453. *c = ' ';
  454. }
  455. }
  456. jack_port_set_alias (port->jack_port, port->name);
  457. jack_port_set_default_metadata (port->jack_port, device_name);
  458. if (type == PORT_INPUT)
  459. err = alsa_connect_from(self, port->remote.client, port->remote.port);
  460. else
  461. err = snd_seq_connect_to(self->seq, self->port_id, port->remote.client, port->remote.port);
  462. if (err)
  463. goto failed;
  464. port->early_events = jack_ringbuffer_create(MAX_EVENT_SIZE*16);
  465. info_log("port created: %s", port->name);
  466. return port;
  467. failed:
  468. port_free(self, port);
  469. return NULL;
  470. }
  471. /*
  472. * ==================== Port add/del handling thread ==============================
  473. */
  474. static
  475. void update_port_type(alsa_seqmidi_t *self, int type, snd_seq_addr_t addr, int caps, const snd_seq_port_info_t *info)
  476. {
  477. stream_t *str = &self->stream[type];
  478. int alsa_mask = port_type[type].alsa_mask;
  479. port_t *port = port_get(str->ports, addr);
  480. debug_log("update_port_type(%d:%d)", addr.client, addr.port);
  481. if (port && (caps & alsa_mask)!=alsa_mask) {
  482. debug_log("setdead: %s", port->name);
  483. port->is_dead = 1;
  484. }
  485. if (!port && (caps & alsa_mask)==alsa_mask) {
  486. assert (jack_ringbuffer_write_space(str->new_ports) >= sizeof(port));
  487. port = port_create(self, type, addr, info);
  488. if (port)
  489. jack_ringbuffer_write(str->new_ports, (char*)&port, sizeof(port));
  490. }
  491. }
  492. static
  493. void update_port(alsa_seqmidi_t *self, snd_seq_addr_t addr, const snd_seq_port_info_t *info)
  494. {
  495. unsigned int port_caps = snd_seq_port_info_get_capability(info);
  496. if (port_caps & SND_SEQ_PORT_CAP_NO_EXPORT)
  497. return;
  498. update_port_type(self, PORT_INPUT, addr, port_caps, info);
  499. update_port_type(self, PORT_OUTPUT,addr, port_caps, info);
  500. }
  501. static
  502. void free_ports(alsa_seqmidi_t *self, jack_ringbuffer_t *ports)
  503. {
  504. port_t *port;
  505. int sz;
  506. while ((sz = jack_ringbuffer_read(ports, (char*)&port, sizeof(port)))) {
  507. assert (sz == sizeof(port));
  508. port_free(self, port);
  509. }
  510. }
  511. static
  512. void update_ports(alsa_seqmidi_t *self)
  513. {
  514. snd_seq_addr_t addr;
  515. snd_seq_port_info_t *info;
  516. int size;
  517. snd_seq_port_info_alloca(&info);
  518. while ((size = jack_ringbuffer_read(self->port_add, (char*)&addr, sizeof(addr)))) {
  519. int err;
  520. assert (size == sizeof(addr));
  521. assert (addr.client != self->client_id);
  522. if ((err=snd_seq_get_any_port_info(self->seq, addr.client, addr.port, info))>=0) {
  523. update_port(self, addr, info);
  524. } else {
  525. //port_setdead(self->stream[PORT_INPUT].ports, addr);
  526. //port_setdead(self->stream[PORT_OUTPUT].ports, addr);
  527. }
  528. }
  529. }
  530. static
  531. void* port_thread(void *arg)
  532. {
  533. alsa_seqmidi_t *self = arg;
  534. while (self->keep_walking) {
  535. sem_wait(&self->port_sem);
  536. free_ports(self, self->port_del);
  537. update_ports(self);
  538. }
  539. debug_log("port_thread exited");
  540. return NULL;
  541. }
  542. static
  543. void add_existing_ports(alsa_seqmidi_t *self)
  544. {
  545. snd_seq_addr_t addr;
  546. snd_seq_client_info_t *client_info;
  547. snd_seq_port_info_t *port_info;
  548. snd_seq_client_info_alloca(&client_info);
  549. snd_seq_port_info_alloca(&port_info);
  550. snd_seq_client_info_set_client(client_info, -1);
  551. while (snd_seq_query_next_client(self->seq, client_info) >= 0)
  552. {
  553. addr.client = snd_seq_client_info_get_client(client_info);
  554. if (addr.client == SND_SEQ_CLIENT_SYSTEM || addr.client == self->client_id)
  555. continue;
  556. snd_seq_port_info_set_client(port_info, addr.client);
  557. snd_seq_port_info_set_port(port_info, -1);
  558. while (snd_seq_query_next_port(self->seq, port_info) >= 0)
  559. {
  560. addr.port = snd_seq_port_info_get_port(port_info);
  561. update_port(self, addr, port_info);
  562. }
  563. }
  564. }
  565. /*
  566. * =================== Input/output port handling =========================
  567. */
  568. static
  569. void set_process_info(struct process_info *info, alsa_seqmidi_t *self, int dir, jack_nframes_t nframes)
  570. {
  571. const snd_seq_real_time_t* alsa_time;
  572. snd_seq_queue_status_t *status;
  573. snd_seq_queue_status_alloca(&status);
  574. info->dir = dir;
  575. info->period_start = jack_last_frame_time(self->jack);
  576. info->nframes = nframes;
  577. info->sample_rate = jack_get_sample_rate(self->jack);
  578. info->cur_frames = jack_frame_time(self->jack);
  579. // immediately get alsa'a real time (uhh, why everybody has their own 'real' time)
  580. snd_seq_get_queue_status(self->seq, self->queue, status);
  581. alsa_time = snd_seq_queue_status_get_real_time(status);
  582. info->alsa_time = alsa_time->tv_sec * NSEC_PER_SEC + alsa_time->tv_nsec;
  583. if (info->period_start + info->nframes < info->cur_frames) {
  584. int periods_lost = (info->cur_frames - info->period_start) / info->nframes;
  585. info->period_start += periods_lost * info->nframes;
  586. debug_log("xrun detected: %d periods lost\n", periods_lost);
  587. }
  588. }
  589. static
  590. void add_ports(stream_t *str)
  591. {
  592. port_t *port;
  593. while (jack_ringbuffer_read(str->new_ports, (char*)&port, sizeof(port))) {
  594. debug_log("jack: inserted port %s\n", port->name);
  595. port_insert(str->ports, port);
  596. }
  597. }
  598. static
  599. void jack_process(alsa_seqmidi_t *self, struct process_info *info)
  600. {
  601. stream_t *str = &self->stream[info->dir];
  602. port_jack_func process = port_type[info->dir].jack_func;
  603. int i, del=0;
  604. add_ports(str);
  605. // process ports
  606. for (i=0; i<PORT_HASH_SIZE; ++i) {
  607. port_t **pport = &str->ports[i];
  608. while (*pport) {
  609. port_t *port = *pport;
  610. port->jack_buf = jack_port_get_buffer(port->jack_port, info->nframes);
  611. if (info->dir == PORT_INPUT)
  612. jack_midi_clear_buffer(port->jack_buf);
  613. if (!port->is_dead)
  614. (*process)(self, port, info);
  615. else if (jack_ringbuffer_write_space(self->port_del) >= sizeof(port)) {
  616. debug_log("jack: removed port %s", port->name);
  617. *pport = port->next;
  618. jack_ringbuffer_write(self->port_del, (char*)&port, sizeof(port));
  619. del++;
  620. continue;
  621. }
  622. pport = &port->next;
  623. }
  624. }
  625. if (del)
  626. sem_post(&self->port_sem);
  627. }
  628. /*
  629. * ============================ Input ==============================
  630. */
  631. static
  632. void do_jack_input(alsa_seqmidi_t *self, port_t *port, struct process_info *info)
  633. {
  634. // process port->early_events
  635. alsa_midi_event_t ev;
  636. while (jack_ringbuffer_read(port->early_events, (char*)&ev, sizeof(ev))) {
  637. jack_midi_data_t* buf;
  638. int64_t time = ev.time - info->period_start;
  639. if (time < 0)
  640. time = 0;
  641. else if (time >= info->nframes)
  642. time = info->nframes - 1;
  643. buf = jack_midi_event_reserve(port->jack_buf, (jack_nframes_t)time, ev.size);
  644. if (buf)
  645. jack_ringbuffer_read(port->early_events, (char*)buf, ev.size);
  646. else
  647. jack_ringbuffer_read_advance(port->early_events, ev.size);
  648. debug_log("input: it's time for %d bytes at %lld", ev.size, time);
  649. }
  650. }
  651. static
  652. void port_event(alsa_seqmidi_t *self, snd_seq_event_t *ev)
  653. {
  654. const snd_seq_addr_t addr = ev->data.addr;
  655. if (addr.client == self->client_id)
  656. return;
  657. if (ev->type == SND_SEQ_EVENT_PORT_START || ev->type == SND_SEQ_EVENT_PORT_CHANGE) {
  658. assert (jack_ringbuffer_write_space(self->port_add) >= sizeof(addr));
  659. debug_log("port_event: add/change %d:%d", addr.client, addr.port);
  660. jack_ringbuffer_write(self->port_add, (char*)&addr, sizeof(addr));
  661. sem_post(&self->port_sem);
  662. } else if (ev->type == SND_SEQ_EVENT_PORT_EXIT) {
  663. debug_log("port_event: del %d:%d", addr.client, addr.port);
  664. port_setdead(self->stream[PORT_INPUT].ports, addr);
  665. port_setdead(self->stream[PORT_OUTPUT].ports, addr);
  666. }
  667. }
  668. static
  669. void input_event(alsa_seqmidi_t *self, snd_seq_event_t *alsa_event, struct process_info* info)
  670. {
  671. jack_midi_data_t data[MAX_EVENT_SIZE];
  672. stream_t *str = &self->stream[PORT_INPUT];
  673. long size;
  674. int64_t alsa_time, time_offset;
  675. int64_t frame_offset, event_frame;
  676. port_t *port;
  677. port = port_get(str->ports, alsa_event->source);
  678. if (!port)
  679. return;
  680. /*
  681. * RPNs, NRPNs, Bank Change, etc. need special handling
  682. * but seems, ALSA does it for us already.
  683. */
  684. snd_midi_event_reset_decode(str->codec);
  685. if ((size = snd_midi_event_decode(str->codec, data, sizeof(data), alsa_event))<0)
  686. return;
  687. // fixup NoteOn with vel 0
  688. if ((data[0] & 0xF0) == 0x90 && data[2] == 0x00) {
  689. data[0] = 0x80 + (data[0] & 0x0F);
  690. data[2] = 0x40;
  691. }
  692. alsa_time = alsa_event->time.time.tv_sec * NSEC_PER_SEC + alsa_event->time.time.tv_nsec;
  693. time_offset = info->alsa_time - alsa_time;
  694. frame_offset = (info->sample_rate * time_offset) / NSEC_PER_SEC;
  695. event_frame = (int64_t)info->cur_frames - info->period_start - frame_offset + info->nframes;
  696. debug_log("input: %d bytes at event_frame = %d", (int)size, (int)event_frame);
  697. if (event_frame >= info->nframes &&
  698. jack_ringbuffer_write_space(port->early_events) >= (sizeof(alsa_midi_event_t) + size)) {
  699. alsa_midi_event_t ev;
  700. ev.time = event_frame + info->period_start;
  701. ev.size = size;
  702. jack_ringbuffer_write(port->early_events, (char*)&ev, sizeof(ev));
  703. jack_ringbuffer_write(port->early_events, (char*)data, size);
  704. debug_log("postponed to next frame +%d", (int) (event_frame - info->nframes));
  705. return;
  706. }
  707. if (event_frame < 0)
  708. event_frame = 0;
  709. else if (event_frame >= info->nframes)
  710. event_frame = info->nframes - 1;
  711. jack_midi_event_write(port->jack_buf, event_frame, data, size);
  712. }
  713. static
  714. void alsa_seqmidi_read(alsa_midi_t *m, jack_nframes_t nframes)
  715. {
  716. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  717. int res;
  718. snd_seq_event_t *event;
  719. struct process_info info;
  720. if (!self->keep_walking)
  721. return;
  722. set_process_info(&info, self, PORT_INPUT, nframes);
  723. jack_process(self, &info);
  724. while ((res = snd_seq_event_input(self->seq, &event))>0) {
  725. if (event->source.client == SND_SEQ_CLIENT_SYSTEM)
  726. port_event(self, event);
  727. else
  728. input_event(self, event, &info);
  729. }
  730. }
  731. /*
  732. * ============================ Output ==============================
  733. */
  734. static
  735. void do_jack_output(alsa_seqmidi_t *self, port_t *port, struct process_info* info)
  736. {
  737. stream_t *str = &self->stream[info->dir];
  738. int nevents = jack_midi_get_event_count(port->jack_buf);
  739. int i, err;
  740. for (i=0; i<nevents; ++i) {
  741. jack_midi_event_t jack_event;
  742. snd_seq_event_t alsa_event;
  743. int64_t frame_offset;
  744. int64_t out_time;
  745. snd_seq_real_time_t out_rt;
  746. jack_midi_event_get(&jack_event, port->jack_buf, i);
  747. snd_seq_ev_clear(&alsa_event);
  748. snd_midi_event_reset_encode(str->codec);
  749. if (!snd_midi_event_encode(str->codec, jack_event.buffer, jack_event.size, &alsa_event))
  750. continue; // invalid event
  751. snd_seq_ev_set_source(&alsa_event, self->port_id);
  752. snd_seq_ev_set_dest(&alsa_event, port->remote.client, port->remote.port);
  753. /* NOTE: in case of xrun it could become negative, so it is essential to use signed type! */
  754. frame_offset = (int64_t)jack_event.time + info->period_start + info->nframes - info->cur_frames;
  755. if (frame_offset < 0) {
  756. frame_offset = info->nframes + jack_event.time;
  757. error_log("internal xrun detected: frame_offset = %"PRId64"\n", frame_offset);
  758. }
  759. /* Ken Ellinwood reported problems with this assert.
  760. * Seems, magic 2 should be replaced with nperiods. */
  761. //FIXME: assert (frame_offset < info->nframes*2);
  762. //if (frame_offset < info->nframes * info->nperiods)
  763. // debug_log("alsa_out: BLAH-BLAH-BLAH");
  764. out_time = info->alsa_time + (frame_offset * NSEC_PER_SEC) / info->sample_rate;
  765. debug_log("alsa_out: frame_offset = %lld, info->alsa_time = %lld, out_time = %lld, port->last_out_time = %lld",
  766. frame_offset, info->alsa_time, out_time, port->last_out_time);
  767. // we should use absolute time to prevent reordering caused by rounding errors
  768. if (out_time < port->last_out_time) {
  769. debug_log("alsa_out: limiting out_time %lld at %lld", out_time, port->last_out_time);
  770. out_time = port->last_out_time;
  771. } else
  772. port->last_out_time = out_time;
  773. out_rt.tv_nsec = out_time % NSEC_PER_SEC;
  774. out_rt.tv_sec = out_time / NSEC_PER_SEC;
  775. snd_seq_ev_schedule_real(&alsa_event, self->queue, 0, &out_rt);
  776. err = snd_seq_event_output(self->seq, &alsa_event);
  777. debug_log("alsa_out: written %d bytes to %s at %+d (%lld): %d", (int)jack_event.size, port->name, (int)frame_offset, out_time, err);
  778. }
  779. return;
  780. // may be unused
  781. (void)err;
  782. }
  783. static
  784. void alsa_seqmidi_write(alsa_midi_t *m, jack_nframes_t nframes)
  785. {
  786. alsa_seqmidi_t *self = (alsa_seqmidi_t*) m;
  787. struct process_info info;
  788. if (!self->keep_walking)
  789. return;
  790. set_process_info(&info, self, PORT_OUTPUT, nframes);
  791. jack_process(self, &info);
  792. snd_seq_drain_output(self->seq);
  793. }