KORG microX utility.
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.

720 lines
16 KiB

  1. /*
  2. * asysex - A SysEx Utility
  3. * Copyright (C) 2012,2013 Damien Goutte-Gattat
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /** @file midi.c
  19. * MIDI I/O API.
  20. *
  21. * This module implements an abstraction layer above the system MIDI
  22. * I/O API(s).
  23. *
  24. * Currently the supported APIs are ALSA and OSS.
  25. */
  26. #ifdef HAVE_CONFIG_H
  27. #include <config.h>
  28. #endif
  29. #include <midi.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <assert.h>
  33. #include <xmem.h>
  34. #ifdef HAVE_ALSA
  35. #include <alsa/asoundlib.h>
  36. #endif
  37. #ifdef HAVE_OSS
  38. #include <fcntl.h>
  39. #include <string.h>
  40. #include <dirent.h>
  41. #endif
  42. /** Pointer to a backend-specific implementation of midi_close(). */
  43. typedef int (*m_close) (midi_io_t *);
  44. /** Pointer to a backend-specific implementation of midi_write(). */
  45. typedef ssize_t (*m_write) (midi_io_t *, unsigned char *, size_t);
  46. /** Pointer to a backend-specific implementation of midi_read(). */
  47. typedef ssize_t (*m_read) (midi_io_t *, unsigned char *, size_t);
  48. /** Pointer to a backend-specific implementation of midi_error(). */
  49. typedef const char * (*m_error) (midi_io_t *);
  50. /** The size of the internal read buffer. */
  51. #define MIDI_IO_BUFFER_SIZE 256
  52. /** An abstracted MIDI port.
  53. * This structure represents an opened MIDI port.
  54. */
  55. struct midi_io
  56. {
  57. struct {
  58. /** Pointer to a midi_close() implementation. */
  59. m_close close;
  60. /** Pointer to a midi_write() implementation. */
  61. m_write write;
  62. /** Pointer to a midi_read() implementation. */
  63. m_read read;
  64. /** Pointer to a midi_error() implementation. */
  65. m_error error;
  66. } backend;
  67. /** The error code of the last read or write operation. */
  68. int error;
  69. /** The input buffer. */
  70. unsigned char buffer[MIDI_IO_BUFFER_SIZE];
  71. /** The current position in the input buffer. */
  72. size_t pos;
  73. /** The number of available bytes in the input buffer. */
  74. size_t len;
  75. /** The current MIDI Status Byte. */
  76. unsigned char status;
  77. /** Backend-dependent data. */
  78. union {
  79. #ifdef HAVE_ALSA
  80. struct {
  81. snd_rawmidi_t *in;
  82. snd_rawmidi_t *out;
  83. } alsa;
  84. #endif
  85. #ifdef HAVE_OSS
  86. struct {
  87. int fd;
  88. } oss;
  89. #endif
  90. };
  91. };
  92. /* Backend-specific functions. */
  93. #ifdef HAVE_ALSA
  94. static int
  95. alsa_midi_close(midi_io_t *midi)
  96. {
  97. snd_rawmidi_close(midi->alsa.in);
  98. snd_rawmidi_close(midi->alsa.out);
  99. free(midi);
  100. return 0;
  101. }
  102. static ssize_t
  103. alsa_midi_write(midi_io_t *midi, unsigned char *buffer, size_t len)
  104. {
  105. ssize_t n;
  106. /* Flush reading buffer. */
  107. midi->pos = midi->len = 0;
  108. if ( (n = snd_rawmidi_write(midi->alsa.out, buffer, len)) != len ) {
  109. midi->error = n;
  110. n = -1;
  111. }
  112. else
  113. midi->error = 0;
  114. return n;
  115. }
  116. static ssize_t
  117. alsa_midi_read(midi_io_t *midi, unsigned char *buffer, size_t len)
  118. {
  119. ssize_t n;
  120. if ( (n = snd_rawmidi_read(midi->alsa.in, buffer, len)) < 0 ) {
  121. midi->error = n;
  122. n = -1;
  123. }
  124. else
  125. midi->error = 0;
  126. return n;
  127. }
  128. static const char *
  129. alsa_midi_error(midi_io_t *midi)
  130. {
  131. if ( midi->error == 0 )
  132. return NULL;
  133. else
  134. return snd_strerror(midi->error);
  135. }
  136. static midi_io_t *
  137. alsa_midi_open(const char *name)
  138. {
  139. midi_io_t *midi;
  140. midi = xmalloc(sizeof(*midi));
  141. midi->alsa.in = midi->alsa.out = NULL;
  142. midi->error = midi->pos = midi->len = midi->status = 0;
  143. midi->backend.close = alsa_midi_close;
  144. midi->backend.write = alsa_midi_write;
  145. midi->backend.read = alsa_midi_read;
  146. midi->backend.error = alsa_midi_error;
  147. if ( snd_rawmidi_open(&(midi->alsa.in), &(midi->alsa.out), name,
  148. SND_RAWMIDI_NONBLOCK) < 0 ) {
  149. free(midi);
  150. midi = NULL;
  151. }
  152. else if ( snd_rawmidi_nonblock(midi->alsa.out, 0) < 0 ) {
  153. midi_close(midi);
  154. midi = NULL;
  155. }
  156. return midi;
  157. }
  158. static void
  159. alsa_midi_get_ports(char ***ports, size_t *n, size_t *max)
  160. {
  161. char name[32];
  162. int card;
  163. card = -1;
  164. while ( snd_card_next(&card) >= 0 && card != -1 ) {
  165. snd_ctl_t *ctl;
  166. snprintf(name, sizeof(name), "hw:%d", card);
  167. if ( snd_ctl_open(&ctl, name, 0) >= 0 ) {
  168. int device;
  169. device = -1;
  170. while ( snd_ctl_rawmidi_next_device(ctl, &device) >= 0 && device >= 0 ) {
  171. snprintf(name, sizeof(name), "hw:%d,%d", card, device);
  172. if ( *n >= *max ) {
  173. *max += 10;
  174. *ports = xrealloc(*ports, *max);
  175. }
  176. (*ports)[(*n)++] = xstrdup(name);
  177. }
  178. snd_ctl_close(ctl);
  179. }
  180. }
  181. }
  182. #endif /* HAVE_ALSA */
  183. #ifdef HAVE_OSS
  184. static int
  185. oss_midi_close(midi_io_t *midi)
  186. {
  187. close(midi->oss.fd);
  188. free(midi);
  189. return 0;
  190. }
  191. static ssize_t
  192. oss_midi_write(midi_io_t *midi, unsigned char *buffer, size_t len)
  193. {
  194. ssize_t n;
  195. /* Flush reading buffer. */
  196. midi->pos = midi->len = 0;
  197. if ( (n = write(midi->oss.fd, buffer, len)) == -1 )
  198. midi->error = errno;
  199. else
  200. midi->error = 0;
  201. return n;
  202. }
  203. static ssize_t
  204. oss_midi_read(midi_io_t *midi, unsigned char *buffer, size_t len)
  205. {
  206. ssize_t n;
  207. if ( (n = read(midi->oss.fd, buffer, len)) == -1 )
  208. midi->error = errno;
  209. else
  210. midi->error = 0;
  211. return n;
  212. }
  213. static const char *
  214. oss_midi_error(midi_io_t *midi)
  215. {
  216. if ( midi->error == 0 )
  217. return NULL;
  218. else
  219. return strerror(midi->error);
  220. }
  221. static midi_io_t *
  222. oss_midi_open(const char *name)
  223. {
  224. midi_io_t *midi;
  225. assert(name != NULL);
  226. midi = xmalloc(sizeof(*midi));
  227. midi->oss.fd = -1;
  228. midi->error = midi->pos = midi->len = midi->status = 0;
  229. midi->backend.close = oss_midi_close;
  230. midi->backend.write = oss_midi_write;
  231. midi->backend.read = oss_midi_read;
  232. midi->backend.error = oss_midi_error;
  233. if ( (midi->oss.fd = open(name, O_RDWR, 0)) == -1 ) {
  234. free(midi);
  235. midi = NULL;
  236. }
  237. return midi;
  238. }
  239. static int
  240. oss_midi_device(const struct dirent *entry)
  241. {
  242. return strncmp(entry->d_name, "midi", 4) == 0;
  243. }
  244. static void
  245. oss_midi_get_ports(char ***ports, size_t *n, size_t *max)
  246. {
  247. char name[32];
  248. size_t k;
  249. struct dirent **namelist;
  250. if ( (k = scandir("/dev", &namelist, oss_midi_device, alphasort)) != -1 ) {
  251. while ( k-- ) {
  252. snprintf(name, sizeof(name), "/dev/%s", namelist[k]->d_name);
  253. free(namelist[k]);
  254. if ( *n >= *max ) {
  255. *max += 10;
  256. *ports = xrealloc(*ports, *max);
  257. }
  258. (*ports)[(*n)++] = xstrdup(name);
  259. }
  260. }
  261. }
  262. #endif /* HAVE_OSS */
  263. /* Backend-independent functions. */
  264. /**
  265. * Open a MIDI port.
  266. * This function opens the MIDI port identified by the specified
  267. * name. It allocates a midi_io structure which should be used
  268. * for all consecutive operations on that port.
  269. *
  270. * When no longer needed, the port should be closed by calling
  271. * the midi_close() function.
  272. *
  273. * @note The port name determines which MIDI backend will be
  274. * used; all available backends are tried successively until
  275. * one of them recognizes the name as a valid port name.
  276. *
  277. * @param[in] name The name of the MIDI port to open.
  278. *
  279. * @return
  280. * - A pointer to a newly allocated midi_io object;
  281. * - @c NULL if an error occured.
  282. */
  283. midi_io_t *
  284. midi_open(const char *name)
  285. {
  286. midi_io_t *midi;
  287. midi = NULL;
  288. #ifdef HAVE_ALSA
  289. if ( midi == NULL && strncmp("hw:", name, 3) == 0 )
  290. midi = alsa_midi_open(name);
  291. #endif
  292. #ifdef HAVE_OSS
  293. if ( midi == NULL && strncmp("/dev/midi", name, 9) == 0 )
  294. midi = oss_midi_open(name);
  295. #endif
  296. return midi;
  297. }
  298. /**
  299. * Close a MIDI port.
  300. * This function closes the MIDI port and frees the associated
  301. * resources.
  302. *
  303. * @return
  304. * - 0 if the port was successfully closed;
  305. * - -1 if an error occured.
  306. */
  307. int
  308. midi_close(midi_io_t *midi)
  309. {
  310. assert(midi != NULL);
  311. return midi->backend.close(midi);
  312. }
  313. /**
  314. * Write to a MIDI port.
  315. * This function writes arbitrary data to the MIDI port. It
  316. * does not perform any kind of check on the data before
  317. * sending them to the MIDI port; it is the caller's
  318. * responsibility to provide this function with valid and
  319. * meaningful MIDI data.
  320. *
  321. * @param[in] midi The MIDI port to write to.
  322. * @param[in] buffer The MIDI data to write.
  323. * @param[in] len The number of bytes from @a buffer to write.
  324. *
  325. * @return
  326. * - The number of bytes written to the port;
  327. * - -1 if an error occured.
  328. */
  329. ssize_t
  330. midi_write(midi_io_t *midi, unsigned char *buffer, size_t len)
  331. {
  332. assert(midi != NULL);
  333. assert(buffer != NULL);
  334. return midi->backend.write(midi, buffer, len);
  335. }
  336. /**
  337. * Read from a MIDI port.
  338. * This function reads data from the MIDI port and stores it
  339. * in the provided buffer.
  340. *
  341. * Note that MIDI messages may be split between two calls of
  342. * this function.
  343. *
  344. * @param[in] midi The MIDI port to read from.
  345. * @param[out] buffer The buffer where to store read data.
  346. * @param[in] len The size of the @a buffer store.
  347. *
  348. * @return
  349. * - The number of bytes read and stored into @a buffer;
  350. * - -1 if an error occured.
  351. */
  352. ssize_t
  353. midi_read(midi_io_t *midi, unsigned char *buffer, size_t len)
  354. {
  355. assert(midi != NULL);
  356. assert(buffer != NULL);
  357. return midi->backend.read(midi, buffer, len);
  358. }
  359. /**
  360. * Get a description for the last error.
  361. * This function gets an error message for the last error
  362. * that occured during a write or read operation.
  363. *
  364. * @param[in] midi The MIDI port.
  365. *
  366. * @return
  367. * A static string containing the user-readable error message,
  368. * or @c NULL if the last I/O operation was successful.
  369. */
  370. const char *
  371. midi_error(midi_io_t *midi)
  372. {
  373. assert(midi != NULL);
  374. return midi->backend.error(midi);
  375. }
  376. /**
  377. * List available MIDI ports.
  378. * This function returns a list of all available MIDI ports
  379. * for all the supported backends.
  380. *
  381. * @return
  382. * A newly allocated null-terminated array of strings, each
  383. * string being the name of a MIDI port. Freeing each string
  384. * and the array itself is the caller responsibility.
  385. */
  386. char **
  387. midi_get_ports(void)
  388. {
  389. char **ports, name[32];
  390. size_t n, max;
  391. ports = NULL;
  392. n = max = 0;
  393. #ifdef HAVE_ALSA
  394. alsa_midi_get_ports(&ports, &n, &max);
  395. #endif
  396. #ifdef HAVE_OSS
  397. oss_midi_get_ports(&ports, &n, &max);
  398. #endif
  399. if ( n >= max ) {
  400. max += 1;
  401. ports = xrealloc(ports, max);
  402. }
  403. ports[n++] = NULL;
  404. return ports;
  405. }
  406. /**
  407. * Read a MIDI byte.
  408. * This function reads a single MIDI byte from the MIDI port.
  409. *
  410. * @param[in] midi The MIDI port to read from.
  411. *
  412. * @return
  413. * - A single MIDI byte;
  414. * - -1 if an error occured.
  415. */
  416. int
  417. midi_next(midi_io_t *midi)
  418. {
  419. unsigned char b;
  420. assert(midi != NULL);
  421. if ( midi->pos >= midi->len ) {
  422. ssize_t n;
  423. if ( (n = midi_read(midi, midi->buffer, MIDI_IO_BUFFER_SIZE)) == -1 )
  424. return -1;
  425. midi->len = n;
  426. midi->pos = 0;
  427. }
  428. b = (unsigned char) midi->buffer[midi->pos++];
  429. if ( b >= 0x80 && b < 0xF8 ) /* Status byte? */
  430. midi->status = b;
  431. return b;
  432. }
  433. /**
  434. * Get the current Status Byte.
  435. * This function returns the current (Running) Status Byte in
  436. * the input MIDI stream.
  437. *
  438. * @param[in] midi The MIDI port.
  439. *
  440. * @return
  441. * The last MIDI Status byte encountered.
  442. */
  443. inline unsigned char
  444. midi_status(midi_io_t *midi)
  445. {
  446. return midi->status;
  447. }
  448. /**
  449. * Emit a Program Change message.
  450. * This function emits Bank Select and Program Change messages
  451. * to the specified MIDI channel.
  452. *
  453. * @param[in] midi The MIDI port to write to.
  454. * @param[in] channel The MIDI channel to write to.
  455. * @param[in] bank The bank number to select.
  456. * @param[in] program The program number to change to.
  457. *
  458. * @return
  459. * - 0 if the messages were successfully sent;
  460. * - -1 if an error occured.
  461. */
  462. int
  463. midi_change_program(midi_io_t *midi,
  464. unsigned char channel,
  465. unsigned short bank,
  466. unsigned char program)
  467. {
  468. unsigned char msg[] = { 0xB0, /* Control Change */
  469. 0x00, /* CC Bank Select MSB */
  470. 0x00, /* Bank number MSB */
  471. 0xB0, /* Control Change */
  472. 0x20, /* CC Bank Select LSB */
  473. 0x00, /* Bank number LSB */
  474. 0xC0, /* Program Change */
  475. 0x00 /* Program number */ };
  476. assert(midi != NULL);
  477. msg[0] |= (channel & 0x0F);
  478. msg[3] |= (channel & 0x0F);
  479. msg[6] |= (channel & 0x0F);
  480. msg[2] |= ((bank >> 7) & 0x7F);
  481. msg[5] |= (bank & 0x7F);
  482. msg[7] |= (program & 0x7F);
  483. return midi_write(midi, msg, sizeof(msg)) == sizeof(msg) ? 0 : -1;
  484. }
  485. /**
  486. * General MIDI patches.
  487. * This array contains the names of the standard GM patches.
  488. */
  489. const char *midi_gm_patches[] = {
  490. "Acoustic Grand Piano",
  491. "Bright Acoustic Piano",
  492. "Electric Grand Piano",
  493. "Honky-tonk Piano",
  494. "Electric Piano 1",
  495. "Electric Piano 2",
  496. "Harpsichord",
  497. "Clavi",
  498. "Celesta",
  499. "Glockenspiel",
  500. "Music Box",
  501. "Vibraphone",
  502. "Marimba",
  503. "Xylophone",
  504. "Tubular Bells",
  505. "Dulcimer",
  506. "Drawbar Organ",
  507. "Percussive Organ",
  508. "Rock Organ",
  509. "Church Organ",
  510. "Reed Organ",
  511. "Accordion",
  512. "Harmonica",
  513. "Tango Accordion",
  514. "Guitar (nylon)",
  515. "Acoustic Guitar (steel)",
  516. "Electric Guitar (jazz)",
  517. "Electric Guitar (clean)",
  518. "Electric Guitar (muted)",
  519. "Overdriven Guitar",
  520. "Distortion Guitar",
  521. "Guitar harmonics",
  522. "Acoustic Bass",
  523. "Electric Bass (finger)",
  524. "Electric Bass (pick)",
  525. "Fretless Bass",
  526. "Slap Bass 1",
  527. "Slap Bass 2",
  528. "Synth Bass 1",
  529. "Synth Bass 2",
  530. "Violin",
  531. "Viola",
  532. "Cello",
  533. "Contrabass",
  534. "Tremolo Strings",
  535. "Pizzicato Strings",
  536. "Orchestral Harp",
  537. "Timpani",
  538. "String Ensemble 1",
  539. "String Ensemble 2",
  540. "SynthStrings 1",
  541. "SynthStrings 2",
  542. "Choir Aahs",
  543. "Voice Oohs",
  544. "Synth Voice",
  545. "Orchestra Hit",
  546. "Trumpet",
  547. "Trombone",
  548. "Tuba",
  549. "Muted Trumpet",
  550. "French Horn",
  551. "Brass Section",
  552. "SynthBrass 1",
  553. "SynthBrass 2",
  554. "Soprano Sax",
  555. "Alto Sax",
  556. "Tenor Sax",
  557. "Baritone Sax",
  558. "Oboe",
  559. "English Horn",
  560. "Bassoon",
  561. "Clarinet",
  562. "Piccolo",
  563. "Flute",
  564. "Recorder",
  565. "Pan Flute",
  566. "Blown Bottle",
  567. "Shakuhachi",
  568. "Whistle",
  569. "Ocarina",
  570. "Lead 1 (square)",
  571. "Lead 2 (sawtooth)",
  572. "Lead 3 (calliope)",
  573. "Lead 4 (chiff)",
  574. "Lead 5 (charang)",
  575. "Lead 6 (voice)",
  576. "Lead 7 (fifths)",
  577. "Lead 8 (bass+lead)",
  578. "Pad 1 (new age)",
  579. "Pad 2 (warm)",
  580. "Pad 3 (polysynth)",
  581. "Pad 4 (choir)",
  582. "Pad 5 (bowed)",
  583. "Pad 6 (metallic)",
  584. "Pad 7 (halo)",
  585. "Pad 8 (sweep)",
  586. "FX 1 (rain)",
  587. "FX 2 (soundtrack)",
  588. "FX 3 (crystal)",
  589. "FX 4 (atmosphere)",
  590. "FX 5 (brightness)",
  591. "FX 6 (goblins)",
  592. "FX 7 (echoes)",
  593. "FX 8 (sci-fi)",
  594. "Sitar",
  595. "Banjo",
  596. "Shamisen",
  597. "Koto",
  598. "Kalimba",
  599. "Bag pipe",
  600. "Fiddle",
  601. "Shanai",
  602. "Tinkle Bell",
  603. "Agogo",
  604. "Steel Drums",
  605. "Woodblock",
  606. "Taiko drum",
  607. "Melodic Tom",
  608. "Synth Drum",
  609. "Reverse Cymbal",
  610. "Guitar Fret Noise",
  611. "Breath Noise",
  612. "Seashore",
  613. "Bird Tweet",
  614. "Telephone Ring",
  615. "Helicopter",
  616. "Applause",
  617. "Gunshot"
  618. };