2 * amidi.c - read from/write to RawMIDI ports
4 * Copyright (c) Clemens Ladisch <clemens@ladisch.de>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <sys/timerfd.h>
35 #include <sys/types.h>
40 #include <alsa/asoundlib.h>
43 #define NSEC_PER_SEC 1000000000L
45 static int do_print_timestamp = 0;
46 static int do_device_list, do_rawmidi_list;
47 static char *port_name = "default";
48 static char *send_file_name;
49 static char *receive_file_name;
50 static char *send_hex;
51 static char *send_data;
52 static int send_data_length;
53 static int receive_file;
57 static int sysex_interval;
58 static snd_rawmidi_t *input, **inputp;
59 static snd_rawmidi_t *output, **outputp;
61 static void error(const char *format, ...)
66 vfprintf(stderr, format, ap);
71 static void usage(void)
74 "Usage: amidi options\n"
76 "-h, --help this help\n"
77 "-V, --version print current version\n"
78 "-l, --list-devices list all hardware ports\n"
79 "-L, --list-rawmidis list all RawMIDI definitions\n"
80 "-p, --port=name select port by name\n"
81 "-s, --send=file send the contents of a (.syx) file\n"
82 "-r, --receive=file write received data into a file\n"
83 "-S, --send-hex=\"...\" send hexadecimal bytes\n"
84 "-d, --dump print received data as hexadecimal bytes\n"
85 "-T, --timestamp=... adds a timestamp in front of each dumped message\n"
88 #ifdef CLOCK_MONOTONIC_RAW
91 "-t, --timeout=seconds exits when no data has been received\n"
92 " for the specified duration\n"
93 "-a, --active-sensing include active sensing bytes\n"
94 "-c, --clock include clock bytes\n"
95 "-i, --sysex-interval=mseconds delay in between each SysEx message\n");
98 static void version(void)
100 puts("amidi version " SND_UTIL_VERSION_STR);
103 static void *my_malloc(size_t size)
105 void *p = malloc(size);
107 error("out of memory");
113 static void list_device(snd_ctl_t *ctl, int card, int device)
115 snd_rawmidi_info_t *info;
117 const char *sub_name;
118 int subs, subs_in, subs_out;
122 snd_rawmidi_info_alloca(&info);
123 snd_rawmidi_info_set_device(info, device);
125 snd_rawmidi_info_set_stream(info, SND_RAWMIDI_STREAM_INPUT);
126 err = snd_ctl_rawmidi_info(ctl, info);
128 subs_in = snd_rawmidi_info_get_subdevices_count(info);
132 snd_rawmidi_info_set_stream(info, SND_RAWMIDI_STREAM_OUTPUT);
133 err = snd_ctl_rawmidi_info(ctl, info);
135 subs_out = snd_rawmidi_info_get_subdevices_count(info);
139 subs = subs_in > subs_out ? subs_in : subs_out;
143 for (sub = 0; sub < subs; ++sub) {
144 snd_rawmidi_info_set_stream(info, sub < subs_in ?
145 SND_RAWMIDI_STREAM_INPUT :
146 SND_RAWMIDI_STREAM_OUTPUT);
147 snd_rawmidi_info_set_subdevice(info, sub);
148 err = snd_ctl_rawmidi_info(ctl, info);
150 error("cannot get rawmidi information %d:%d:%d: %s\n",
151 card, device, sub, snd_strerror(err));
154 name = snd_rawmidi_info_get_name(info);
155 sub_name = snd_rawmidi_info_get_subdevice_name(info);
156 if (sub == 0 && sub_name[0] == '\0') {
157 printf("%c%c hw:%d,%d %s",
158 sub < subs_in ? 'I' : ' ',
159 sub < subs_out ? 'O' : ' ',
162 printf(" (%d subdevices)", subs);
166 printf("%c%c hw:%d,%d,%d %s\n",
167 sub < subs_in ? 'I' : ' ',
168 sub < subs_out ? 'O' : ' ',
169 card, device, sub, sub_name);
174 static void list_card_devices(int card)
181 sprintf(name, "hw:%d", card);
182 if ((err = snd_ctl_open(&ctl, name, 0)) < 0) {
183 error("cannot open control for card %d: %s", card, snd_strerror(err));
188 if ((err = snd_ctl_rawmidi_next_device(ctl, &device)) < 0) {
189 error("cannot determine device number: %s", snd_strerror(err));
194 list_device(ctl, card, device);
199 static void device_list(void)
204 if ((err = snd_card_next(&card)) < 0) {
205 error("cannot determine card number: %s", snd_strerror(err));
209 error("no sound card found");
212 puts("Dir Device Name");
214 list_card_devices(card);
215 if ((err = snd_card_next(&card)) < 0) {
216 error("cannot determine card number: %s", snd_strerror(err));
222 static void rawmidi_list(void)
224 snd_output_t *output;
225 snd_config_t *config;
228 if ((err = snd_config_update()) < 0) {
229 error("snd_config_update failed: %s", snd_strerror(err));
232 if ((err = snd_output_stdio_attach(&output, stdout, 0)) < 0) {
233 error("snd_output_stdio_attach failed: %s", snd_strerror(err));
236 if (snd_config_search(snd_config, "rawmidi", &config) >= 0) {
237 puts("RawMIDI list:");
238 snd_config_save(config, output);
240 snd_output_close(output);
243 static int send_midi_interleaved(void)
246 char *data = send_data;
248 snd_rawmidi_params_t *param;
249 snd_rawmidi_status_t *st;
251 snd_rawmidi_status_alloca(&st);
253 snd_rawmidi_params_alloca(¶m);
254 snd_rawmidi_params_current(output, param);
255 buffer_size = snd_rawmidi_params_get_buffer_size(param);
257 while (data < (send_data + send_data_length)) {
258 int len = send_data + send_data_length - data;
261 if (data > send_data) {
262 snd_rawmidi_status(output, st);
264 /* 320 µs per byte as noted in Page 1 of MIDI spec */
265 usleep((buffer_size - snd_rawmidi_status_get_avail(st)) * 320);
266 snd_rawmidi_status(output, st);
267 } while(snd_rawmidi_status_get_avail(st) < buffer_size);
268 usleep(sysex_interval * 1000);
271 /* find end of SysEx */
272 if ((temp = memchr(data, 0xf7, len)) != NULL)
273 len = temp - data + 1;
275 if ((err = snd_rawmidi_write(output, data, len)) < 0)
284 static void load_file(void)
289 fd = open(send_file_name, O_RDONLY);
291 error("cannot open %s - %s", send_file_name, strerror(errno));
294 length = lseek(fd, 0, SEEK_END);
295 if (length == (off_t)-1) {
296 error("cannot determine length of %s: %s", send_file_name, strerror(errno));
299 send_data = my_malloc(length);
300 lseek(fd, 0, SEEK_SET);
301 if (read(fd, send_data, length) != length) {
302 error("cannot read from %s: %s", send_file_name, strerror(errno));
305 if (length >= 4 && !memcmp(send_data, "MThd", 4)) {
306 error("%s is a Standard MIDI File; use aplaymidi to send it", send_file_name);
309 send_data_length = length;
318 static int hex_value(char c)
320 if ('0' <= c && c <= '9')
322 if ('A' <= c && c <= 'F')
324 if ('a' <= c && c <= 'f')
326 error("invalid character %c", c);
330 static void parse_data(void)
335 send_data = my_malloc(strlen(send_hex)); /* guesstimate */
337 value = -1; /* value is >= 0 when the first hex digit of a byte has been read */
338 for (p = send_hex; *p; ++p) {
340 if (isspace((unsigned char)*p)) {
342 send_data[i++] = value;
347 digit = hex_value(*p);
355 send_data[i++] = (value << 4) | digit;
360 send_data[i++] = value;
361 send_data_length = i;
365 * prints MIDI commands, formatting them nicely
367 static void print_byte(unsigned char byte, struct timespec *ts)
372 STATE_1PARAM_CONTINUE,
375 STATE_2PARAM_1_CONTINUE,
377 } state = STATE_UNKNOWN;
382 else if (byte >= 0xf0) {
390 state = STATE_1PARAM;
393 state = STATE_2PARAM_1;
398 state = STATE_UNKNOWN;
401 newline = state != STATE_SYSEX;
402 state = STATE_UNKNOWN;
405 } else if (byte >= 0x80) {
407 if (byte >= 0xc0 && byte <= 0xdf)
408 state = STATE_1PARAM;
410 state = STATE_2PARAM_1;
411 } else /* b < 0x80 */ {
412 int running_status = 0;
413 newline = state == STATE_UNKNOWN;
416 state = STATE_1PARAM_CONTINUE;
418 case STATE_1PARAM_CONTINUE:
422 state = STATE_2PARAM_2;
425 state = STATE_2PARAM_1_CONTINUE;
427 case STATE_2PARAM_1_CONTINUE:
429 state = STATE_2PARAM_2;
435 fputs("\n ", stdout);
438 putchar(newline ? '\n' : ' ');
439 if (newline && do_print_timestamp) {
440 /* Nanoseconds does not make a lot of sense for serial MIDI (the
441 * 31250 bps one) but I'm not sure about MIDI over USB.
443 printf("%lld.%.9ld) ", (long long)ts->tv_sec, ts->tv_nsec);
446 printf("%02X", byte);
449 static void sig_handler(int sig ATTRIBUTE_UNUSED)
454 static void add_send_hex_data(const char *str)
459 length = (send_hex ? strlen(send_hex) + 1 : 0) + strlen(str) + 1;
460 s = my_malloc(length);
472 int main(int argc, char *argv[])
474 static const char short_options[] = "hVlLp:s:r:S::dt:aci:T:";
475 static const struct option long_options[] = {
476 {"help", 0, NULL, 'h'},
477 {"version", 0, NULL, 'V'},
478 {"list-devices", 0, NULL, 'l'},
479 {"list-rawmidis", 0, NULL, 'L'},
480 {"port", 1, NULL, 'p'},
481 {"send", 1, NULL, 's'},
482 {"receive", 1, NULL, 'r'},
483 {"send-hex", 2, NULL, 'S'},
484 {"dump", 0, NULL, 'd'},
485 {"timestamp", 1, NULL, 'T'},
486 {"timeout", 1, NULL, 't'},
487 {"active-sensing", 0, NULL, 'a'},
488 {"clock", 0, NULL, 'c'},
489 {"sysex-interval", 1, NULL, 'i'},
493 int ignore_active_sensing = 1;
494 int ignore_clock = 1;
496 clockid_t cid = CLOCK_REALTIME;
497 struct itimerspec itimerspec = { .it_interval = { 0, 0 } };
499 while ((c = getopt_long(argc, argv, short_options,
500 long_options, NULL)) != -1) {
518 send_file_name = optarg;
521 receive_file_name = optarg;
526 add_send_hex_data(optarg);
532 do_print_timestamp = 1;
534 error("Clock type missing");
535 else if (strcasecmp(optarg, "realtime") == 0)
536 cid = CLOCK_REALTIME;
537 else if (strcasecmp(optarg, "monotonic") == 0)
538 cid = CLOCK_MONOTONIC;
539 #ifdef CLOCK_MONOTONIC_RAW
540 else if (strcasecmp(optarg, "raw") == 0)
541 cid = CLOCK_MONOTONIC_RAW;
544 error("Clock type not known");
548 timeout = atof(optarg);
551 ignore_active_sensing = 0;
557 sysex_interval = atoi(optarg);
560 error("Try `amidi --help' for more information.");
565 /* data for -S can be specified as multiple arguments */
566 if (!send_hex && !argv[optind]) {
567 error("Please specify some data for --send-hex.");
570 for (; argv[optind]; ++optind)
571 add_send_hex_data(argv[optind]);
574 error("%s is not an option.", argv[optind]);
583 if (do_rawmidi_list || do_device_list)
586 if (!send_file_name && !receive_file_name && !send_hex && !dump) {
587 error("Please specify at least one of --send, --receive, --send-hex, or --dump.");
590 if (send_file_name && send_hex) {
591 error("--send and --send-hex cannot be specified at the same time.");
599 if ((send_file_name || send_hex) && !send_data)
602 if (receive_file_name) {
603 receive_file = creat(receive_file_name, 0666);
604 if (receive_file == -1) {
605 error("cannot create %s: %s", receive_file_name, strerror(errno));
612 if (receive_file_name || dump)
621 if ((err = snd_rawmidi_open(inputp, outputp, port_name, SND_RAWMIDI_NONBLOCK)) < 0) {
622 error("cannot open port \"%s\": %s", port_name, snd_strerror(err));
627 snd_rawmidi_read(input, NULL, 0); /* trigger reading */
630 if ((err = snd_rawmidi_nonblock(output, 0)) < 0) {
631 error("cannot set blocking mode: %s", snd_strerror(err));
634 if (!sysex_interval) {
635 if ((err = snd_rawmidi_write(output, send_data, send_data_length)) < 0) {
636 error("cannot send data: %s", snd_strerror(err));
640 if ((err = send_midi_interleaved()) < 0) {
641 error("cannot send data: %s", snd_strerror(err));
652 npfds = 1 + snd_rawmidi_poll_descriptors_count(input);
653 pfds = alloca(npfds * sizeof(struct pollfd));
656 pfds[0].fd = timerfd_create(CLOCK_MONOTONIC, 0);
657 if (pfds[0].fd == -1) {
658 error("cannot create timer: %s", strerror(errno));
661 pfds[0].events = POLLIN;
666 snd_rawmidi_poll_descriptors(input, &pfds[1], npfds - 1);
668 signal(SIGINT, sig_handler);
673 itimerspec.it_value.tv_nsec = modff(timeout, &timeout_int) * NSEC_PER_SEC;
674 itimerspec.it_value.tv_sec = timeout_int;
675 err = timerfd_settime(pfds[0].fd, 0, &itimerspec, NULL);
677 error("cannot set timer: %s", strerror(errno));
683 unsigned char buf[256];
685 unsigned short revents;
688 err = poll(pfds, npfds, -1);
689 if (stop || (err < 0 && errno == EINTR))
692 error("poll failed: %s", strerror(errno));
696 if (clock_gettime(cid, &ts) < 0) {
697 error("clock_getres (%d) failed: %s", cid, strerror(errno));
701 err = snd_rawmidi_poll_descriptors_revents(input, &pfds[1], npfds - 1, &revents);
703 error("cannot get poll events: %s", snd_strerror(errno));
706 if (revents & (POLLERR | POLLHUP))
708 if (!(revents & POLLIN)) {
709 if (pfds[0].revents & POLLIN)
714 err = snd_rawmidi_read(input, buf, sizeof(buf));
718 error("cannot read from port \"%s\": %s", port_name, snd_strerror(err));
722 for (i = 0; i < err; ++i)
723 if ((buf[i] != MIDI_CMD_COMMON_CLOCK &&
724 buf[i] != MIDI_CMD_COMMON_SENSING) ||
725 (buf[i] == MIDI_CMD_COMMON_CLOCK && !ignore_clock) ||
726 (buf[i] == MIDI_CMD_COMMON_SENSING && !ignore_active_sensing))
727 buf[length++] = buf[i];
732 if (receive_file != -1)
733 write(receive_file, buf, length);
735 for (i = 0; i < length; ++i)
736 print_byte(buf[i], &ts);
742 err = timerfd_settime(pfds[0].fd, 0, &itimerspec, NULL);
744 error("cannot set timer: %s", strerror(errno));
749 if (isatty(fileno(stdout)))
750 printf("\n%d bytes read\n", read);
756 snd_rawmidi_close(input);
758 snd_rawmidi_close(output);
760 if (receive_file != -1)