Home | History | Annotate | Line # | Download | only in midiplay
midiplay.c revision 1.9
      1 /*	$NetBSD: midiplay.c,v 1.9 1999/10/11 12:52:10 augustss Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (augustss (at) netbsd.org).
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <stdio.h>
     40 #include <stdlib.h>
     41 #include <fcntl.h>
     42 #include <err.h>
     43 #include <unistd.h>
     44 #include <string.h>
     45 #include <sys/types.h>
     46 #include <sys/stat.h>
     47 #include <sys/ioctl.h>
     48 #include <sys/midiio.h>
     49 
     50 #define DEVMUSIC "/dev/music"
     51 
     52 struct track {
     53 	u_char *start, *end;
     54 	u_long curtime;
     55 	u_char status;
     56 };
     57 
     58 #define MIDI_META 0xff
     59 
     60 #define META_SEQNO	0x00
     61 #define META_TEXT	0x01
     62 #define META_COPYRIGHT	0x02
     63 #define META_TRACK	0x03
     64 #define META_INSTRUMENT	0x04
     65 #define META_LYRIC	0x05
     66 #define META_MARKER	0x06
     67 #define META_CUE	0x07
     68 #define META_CHPREFIX	0x20
     69 #define META_EOT	0x2f
     70 #define META_SET_TEMPO	0x51
     71 #define META_KEY	0x59
     72 #define META_SMPTE	0x54
     73 #define META_TIMESIGN	0x58
     74 
     75 char *metanames[] = {
     76 	"", "Text", "Copyright", "Track", "Instrument",
     77 	"Lyric", "Marker", "Cue",
     78 };
     79 
     80 static int midi_lengths[] = { 2,2,2,2,1,1,2,0 };
     81 /* Number of bytes in a MIDI command */
     82 #define MIDI_LENGTH(d) (midi_lengths[((d) >> 4) & 7])
     83 
     84 void usage __P((void));
     85 void send_event __P((seq_event_rec *));
     86 void dometa __P((u_int, u_char *, u_int));
     87 void midireset __P((void));
     88 void send_sysex __P((u_char *, u_int));
     89 u_long getvar __P((struct track *));
     90 void playfile __P((FILE *, char *));
     91 void playdata __P((u_char *, u_int, char *));
     92 int main __P((int argc, char **argv));
     93 
     94 extern char *__progname;
     95 
     96 #define P(c) 1,0x90,c,0x7f,4,0x80,c,0
     97 #define PL(c) 1,0x90,c,0x7f,8,0x80,c,0
     98 #define C 0x3c
     99 #define D 0x3e
    100 #define E 0x40
    101 #define F 0x41
    102 
    103 u_char sample[] = {
    104 	'M','T','h','d',  0,0,0,6,  0,1,  0,1,  0,8,
    105 	'M','T','r','k',  0,0,0,4+13*8,
    106 	P(C), P(C), P(C), P(E), P(D), P(D), P(D),
    107 	P(F), P(E), P(E), P(D), P(D), PL(C),
    108 	0, 0xff, 0x2f, 0
    109 };
    110 #undef P
    111 #undef PL
    112 #undef C
    113 #undef D
    114 #undef E
    115 #undef F
    116 
    117 #define MARK_HEADER "MThd"
    118 #define MARK_TRACK "MTrk"
    119 #define MARK_LEN 4
    120 
    121 #define SIZE_LEN 4
    122 #define HEADER_LEN 6
    123 
    124 #define GET8(p) ((p)[0])
    125 #define GET16(p) (((p)[0] << 8) | (p)[1])
    126 #define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
    127 #define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
    128 
    129 void
    130 usage()
    131 {
    132 	printf("Usage: %s [-d unit] [-f file] [-l] [-m] [-q] [-t tempo] [-v] [-x] [file ...]\n",
    133 		__progname);
    134 	exit(1);
    135 }
    136 
    137 int showmeta = 0;
    138 int verbose = 0;
    139 #define BASETEMPO 400000
    140 u_int tempo = BASETEMPO;		/* microsec / quarter note */
    141 u_int ttempo = 100;
    142 int unit = 0;
    143 int play = 1;
    144 int fd;
    145 
    146 void
    147 send_event(ev)
    148 	seq_event_rec *ev;
    149 {
    150 	/*
    151 	printf("%02x %02x %02x %02x %02x %02x %02x %02x\n",
    152 	       ev->arr[0], ev->arr[1], ev->arr[2], ev->arr[3],
    153 	       ev->arr[4], ev->arr[5], ev->arr[6], ev->arr[7]);
    154 	*/
    155 	if (play)
    156 		write(fd, ev, sizeof *ev);
    157 }
    158 
    159 u_long
    160 getvar(tp)
    161 	struct track *tp;
    162 {
    163 	u_long r, c;
    164 
    165 	r = 0;
    166 	do {
    167 		c = *tp->start++;
    168 		r = (r << 7) | (c & 0x7f);
    169 	} while ((c & 0x80) && tp->start < tp->end);
    170 	return (r);
    171 }
    172 
    173 void
    174 dometa(meta, p, len)
    175 	u_int meta;
    176 	u_char *p;
    177 	u_int len;
    178 {
    179 	switch (meta) {
    180 	case META_TEXT:
    181 	case META_COPYRIGHT:
    182 	case META_TRACK:
    183 	case META_INSTRUMENT:
    184 	case META_LYRIC:
    185 	case META_MARKER:
    186 	case META_CUE:
    187 		if (showmeta) {
    188 			printf("%s: ", metanames[meta]);
    189 			fwrite(p, len, 1, stdout);
    190 			printf("\n");
    191 		}
    192 		break;
    193 	case META_SET_TEMPO:
    194 		tempo = GET24(p);
    195 		if (showmeta)
    196 			printf("Tempo: %d us / quarter note\n", tempo);
    197 		break;
    198 	case META_TIMESIGN:
    199 		if (showmeta) {
    200 			int n = p[1];
    201 			int d = 1;
    202 			while (n-- > 0)
    203 				d *= 2;
    204 			printf("Time signature: %d/%d %d,%d\n",
    205 			       p[0], d, p[2], p[3]);
    206 		}
    207 		break;
    208 	case META_KEY:
    209 		if (showmeta)
    210 			printf("Key: %d %s\n", (char)p[0],
    211 			       p[1] ? "minor" : "major");
    212 		break;
    213 	default:
    214 		break;
    215 	}
    216 }
    217 
    218 void
    219 midireset()
    220 {
    221 	/* General MIDI reset sequence */
    222 	static u_char gm_reset[] = { 0x7e, 0x7f, 0x09, 0x01, 0xf7 };
    223 
    224 	send_sysex(gm_reset, sizeof gm_reset);
    225 }
    226 
    227 #define SYSEX_CHUNK 6
    228 void
    229 send_sysex(p, l)
    230 	u_char *p;
    231 	u_int l;
    232 {
    233 	seq_event_rec event;
    234 	u_int n;
    235 
    236 	event.arr[0] = SEQ_SYSEX;
    237 	event.arr[1] = unit;
    238 	do {
    239 		n = SYSEX_CHUNK;
    240 		if (l < n) {
    241 			memset(&event.arr[2], 0xff, SYSEX_CHUNK);
    242 			n = l;
    243 		}
    244 		memcpy(&event.arr[2], p, n);
    245 		send_event(&event);
    246 		l -= n;
    247 	} while (l > 0);
    248 }
    249 
    250 void
    251 playfile(f, name)
    252 	FILE *f;
    253 	char *name;
    254 {
    255 	u_char *buf;
    256 	u_int tot, n, size, nread;
    257 
    258 	/*
    259 	 * We need to read the whole file into memory for easy processing.
    260 	 * Using mmap() would be nice, but some file systems do not support
    261 	 * it, nor does reading from e.g. a pipe.  The latter also precludes
    262 	 * finding out the file size without reading it.
    263 	 */
    264 	size = 1000;
    265 	buf = malloc(size);
    266 	if (buf == 0)
    267 		errx(1, "malloc() failed\n");
    268 	nread = size;
    269 	tot = 0;
    270 	for (;;) {
    271 		n = fread(buf + tot, 1, nread, f);
    272 		tot += n;
    273 		if (n < nread)
    274 			break;
    275 		/* There must be more to read. */
    276 		nread = size;
    277 		size *= 2;
    278 		buf = realloc(buf, size);
    279 		if (buf == NULL)
    280 			errx(1, "realloc() failed\n");
    281 	}
    282 	playdata(buf, tot, name);
    283 	free(buf);
    284 }
    285 
    286 void
    287 playdata(buf, tot, name)
    288 	u_char *buf;
    289 	u_int tot;
    290 	char *name;
    291 {
    292 	int format, ntrks, divfmt, ticks, t, besttrk = 0;
    293 	u_int len, mlen, status, chan;
    294 	u_char *p, *end, byte, meta, *msg;
    295 	struct track *tracks;
    296 	u_long bestcur, now;
    297 	struct track *tp;
    298 	seq_event_rec event;
    299 
    300 	end = buf + tot;
    301 	if (verbose)
    302 		printf("Playing %s (%d bytes) ... \n", name, tot);
    303 
    304 	if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
    305 		warnx("Not a MIDI file, missing header\n");
    306 		return;
    307 	}
    308 	if (GET32(buf + MARK_LEN) != HEADER_LEN) {
    309 		warnx("Not a MIDI file, bad header\n");
    310 		return;
    311 	}
    312 	format = GET16(buf + MARK_LEN + SIZE_LEN);
    313 	ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
    314 	divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
    315 	ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
    316 	p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
    317 	if ((divfmt & 0x80) == 0)
    318 		ticks |= divfmt << 8;
    319 	else
    320 		errx(1, "Absolute time codes not implemented yet\n");
    321 	if (verbose > 1)
    322 		printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
    323 		       format, ntrks, divfmt, ticks);
    324 	if (format != 0 && format != 1) {
    325 		warnx("Cannnot play MIDI file of type %d\n", format);
    326 		return;
    327 	}
    328 	if (ntrks == 0)
    329 		return;
    330 	tracks = malloc(ntrks * sizeof(struct track));
    331 	if (tracks == NULL)
    332 		errx(1, "malloc() tracks failed\n");
    333 	for (t = 0; t < ntrks; ) {
    334 		if (p >= end - MARK_LEN - SIZE_LEN) {
    335 			warnx("Cannot find track %d\n", t);
    336 			goto ret;
    337 		}
    338 		len = GET32(p + MARK_LEN);
    339 		if (len > 1000000) { /* a safe guard */
    340 			warnx("Crazy track length\n");
    341 			goto ret;
    342 		}
    343 		if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
    344 			tracks[t].start = p + MARK_LEN + SIZE_LEN;
    345 			tracks[t].end = tracks[t].start + len;
    346 			tracks[t].curtime = getvar(&tracks[t]);
    347 			t++;
    348 		}
    349 		p += MARK_LEN + SIZE_LEN + len;
    350 	}
    351 
    352 	/*
    353 	 * Play MIDI events by selecting the track track with the lowest
    354 	 * curtime.  Execute the event, update the curtime and repeat.
    355 	 */
    356 
    357 	/*
    358 	 * The ticks variable is the number of ticks that make up a quarter
    359 	 * note and is used as a reference value for the delays between
    360 	 * the MIDI events.
    361 	 */
    362 	now = 0;
    363 	for (;;) {
    364 		/* Locate lowest curtime */
    365 		bestcur = ~0;
    366 		for (t = 0; t < ntrks; t++) {
    367 			if (tracks[t].curtime < bestcur) {
    368 				bestcur = tracks[t].curtime;
    369 				besttrk = t;
    370 			}
    371 		}
    372 		if (bestcur == ~0)
    373 			break;
    374 		if (verbose > 1) {
    375 			printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
    376 			fflush(stdout);
    377 		}
    378 		if (now < bestcur) {
    379 			union {
    380 				u_int32_t i;
    381 				u_int8_t b[4];
    382 			} u;
    383 			u_int32_t delta = bestcur - now;
    384 			delta = (int)((double)delta * tempo / (1000.0*ticks));
    385 			u.i = delta;
    386 			if (delta != 0) {
    387 				event.arr[0] = SEQ_TIMING;
    388 				event.arr[1] = TMR_WAIT_REL;
    389 				event.arr[4] = u.b[0];
    390 				event.arr[5] = u.b[1];
    391 				event.arr[6] = u.b[2];
    392 				event.arr[7] = u.b[3];
    393 				send_event(&event);
    394 			}
    395 		}
    396 		now = bestcur;
    397 		tp = &tracks[besttrk];
    398 		byte = *tp->start++;
    399 		if (byte == MIDI_META) {
    400 			meta = *tp->start++;
    401 			mlen = getvar(tp);
    402 			if (verbose > 1)
    403 				printf("META %02x (%d)\n", meta, mlen);
    404 			dometa(meta, tp->start, mlen);
    405 			tp->start += mlen;
    406 		} else {
    407 			if (MIDI_IS_STATUS(byte))
    408 				tp->status = byte;
    409 			else
    410 				tp->start--;
    411 			mlen = MIDI_LENGTH(tp->status);
    412 			msg = tp->start;
    413 			if (verbose > 1) {
    414 			    if (mlen == 1)
    415 				printf("MIDI %02x (%d) %02x\n",
    416 				       tp->status, mlen, msg[0]);
    417 			    else
    418 				printf("MIDI %02x (%d) %02x %02x\n",
    419 				       tp->status, mlen, msg[0], msg[1]);
    420 			}
    421 			status = MIDI_GET_STATUS(tp->status);
    422 			chan = MIDI_GET_CHAN(tp->status);
    423 			switch (status) {
    424 			case MIDI_NOTEOFF:
    425 			case MIDI_NOTEON:
    426 			case MIDI_KEY_PRESSURE:
    427 				SEQ_MK_CHN_VOICE(&event, unit, status, chan,
    428 						 msg[0], msg[1]);
    429 				send_event(&event);
    430 				break;
    431 			case MIDI_CTL_CHANGE:
    432 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
    433 						  msg[0], 0, msg[1]);
    434 				send_event(&event);
    435 				break;
    436 			case MIDI_PGM_CHANGE:
    437 			case MIDI_CHN_PRESSURE:
    438 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
    439 						  msg[0], 0, 0);
    440 				send_event(&event);
    441 				break;
    442 			case MIDI_PITCH_BEND:
    443 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
    444 						  0, 0,
    445 						  (msg[0] & 0x7f) |
    446 						  ((msg[1] & 0x7f) << 7));
    447 				send_event(&event);
    448 				break;
    449 			case MIDI_SYSTEM_PREFIX:
    450 				mlen = getvar(tp);
    451 				if (tp->status == MIDI_SYSEX_START)
    452 					send_sysex(tp->start, mlen);
    453 				else
    454 					/* Sorry, can't do this yet */;
    455 				break;
    456 			default:
    457 				if (verbose)
    458 					printf("MIDI event 0x%02x ignored\n",
    459 					       tp->status);
    460 			}
    461 			tp->start += mlen;
    462 		}
    463 		if (tp->start >= tp->end)
    464 			tp->curtime = ~0;
    465 		else
    466 			tp->curtime += getvar(tp);
    467 	}
    468 	if (ioctl(fd, SEQUENCER_SYNC, 0) < 0)
    469 		err(1, "SEQUENCER_SYNC");
    470 
    471  ret:
    472 	free(tracks);
    473 }
    474 
    475 int
    476 main(argc, argv)
    477 	int argc;
    478 	char **argv;
    479 {
    480 	int ch;
    481 	int listdevs = 0;
    482 	int example = 0;
    483 	int nmidi;
    484 	int t;
    485 	char *file = DEVMUSIC;
    486 	struct synth_info info;
    487 	FILE *f;
    488 
    489 	while ((ch = getopt(argc, argv, "?d:f:lmqt:vx")) != -1) {
    490 		switch(ch) {
    491 		case 'd':
    492 			unit = atoi(optarg);
    493 			break;
    494 		case 'f':
    495 			file = optarg;
    496 			break;
    497 		case 'l':
    498 			listdevs++;
    499 			break;
    500 		case 'm':
    501 			showmeta++;
    502 			break;
    503 		case 'q':
    504 			play = 0;
    505 			break;
    506 		case 't':
    507 			ttempo = atoi(optarg);
    508 			break;
    509 		case 'v':
    510 			verbose++;
    511 			break;
    512 		case 'x':
    513 			example++;
    514 			break;
    515 		case '?':
    516 		default:
    517 			usage();
    518 		}
    519 	}
    520 	argc -= optind;
    521 	argv += optind;
    522 
    523 	fd = open(file, O_WRONLY);
    524 	if (fd < 0)
    525 		err(1, "%s", file);
    526 	if (ioctl(fd, SEQUENCER_NRMIDIS, &nmidi) < 0)
    527 		err(1, "ioctl(SEQUENCER_NRMIDIS) failed, ");
    528 	if (nmidi == 0)
    529 		errx(1, "Sorry, no MIDI devices available\n");
    530 	if (listdevs) {
    531 		for (info.device = 0; info.device < nmidi; info.device++) {
    532 			if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
    533 				err(1, "ioctl(SEQUENCER_INFO) failed, ");
    534 			printf("%d: %s\n", info.device, info.name);
    535 		}
    536 		exit(0);
    537 	}
    538 
    539 	/*
    540 	 * The sequencer has two "knobs": the TIMEBASE and the TEMPO.
    541 	 * The delay specified in TMR_WAIT_REL is specified in
    542 	 * sequencer time units.  The length of a unit is
    543 	 * 60*1000000 / (TIMEBASE * TEMPO).
    544 	 * Set it to 1ms/unit (adjusted by user tempo changes).
    545 	 */
    546 	t = 500 * ttempo / 100;
    547 	if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &t) < 0)
    548 		err(1, "SEQUENCER_TMR_TIMEBASE");
    549 	t = 120;
    550 	if (ioctl(fd, SEQUENCER_TMR_TEMPO, &t) < 0)
    551 		err(1, "SEQUENCER_TMR_TEMPO");
    552 	if (ioctl(fd, SEQUENCER_TMR_START, 0) < 0)
    553 		err(1, "SEQUENCER_TMR_START");
    554 
    555 	midireset();
    556 	if (example)
    557 		while (example--)
    558 			playdata(sample, sizeof sample, "<Gubben Noa>");
    559 	else if (argc == 0)
    560 		playfile(stdin, "<stdin>");
    561 	else
    562 		while (argc--) {
    563 			f = fopen(*argv, "r");
    564 			if (f == NULL)
    565 				err(1, "%s", *argv);
    566 			else {
    567 				playfile(f, *argv);
    568 				fclose(f);
    569 			}
    570 			argv++;
    571 		}
    572 
    573 	exit(0);
    574 }
    575