Home | History | Annotate | Line # | Download | only in midiplay
midiplay.c revision 1.12
      1 /*	$NetBSD: midiplay.c,v 1.12 2001/02/19 23:03:49 cgd 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 #define P(c) 1,0x90,c,0x7f,4,0x80,c,0
     95 #define PL(c) 1,0x90,c,0x7f,8,0x80,c,0
     96 #define C 0x3c
     97 #define D 0x3e
     98 #define E 0x40
     99 #define F 0x41
    100 
    101 u_char sample[] = {
    102 	'M','T','h','d',  0,0,0,6,  0,1,  0,1,  0,8,
    103 	'M','T','r','k',  0,0,0,4+13*8,
    104 	P(C), P(C), P(C), P(E), P(D), P(D), P(D),
    105 	P(F), P(E), P(E), P(D), P(D), PL(C),
    106 	0, 0xff, 0x2f, 0
    107 };
    108 #undef P
    109 #undef PL
    110 #undef C
    111 #undef D
    112 #undef E
    113 #undef F
    114 
    115 #define MARK_HEADER "MThd"
    116 #define MARK_TRACK "MTrk"
    117 #define MARK_LEN 4
    118 
    119 #define SIZE_LEN 4
    120 #define HEADER_LEN 6
    121 
    122 #define GET8(p) ((p)[0])
    123 #define GET16(p) (((p)[0] << 8) | (p)[1])
    124 #define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
    125 #define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
    126 
    127 void
    128 usage()
    129 {
    130 	printf("Usage: %s [-d unit] [-f file] [-l] [-m] [-p pgm] [-q] [-t tempo] [-v] [-x] [file ...]\n",
    131 		getprogname());
    132 	exit(1);
    133 }
    134 
    135 int showmeta = 0;
    136 int verbose = 0;
    137 #define BASETEMPO 400000
    138 u_int tempo = BASETEMPO;		/* microsec / quarter note */
    139 u_int ttempo = 100;
    140 int unit = 0;
    141 int play = 1;
    142 int fd;
    143 int sameprogram = 0;
    144 
    145 void
    146 send_event(ev)
    147 	seq_event_rec *ev;
    148 {
    149 	/*
    150 	printf("%02x %02x %02x %02x %02x %02x %02x %02x\n",
    151 	       ev->arr[0], ev->arr[1], ev->arr[2], ev->arr[3],
    152 	       ev->arr[4], ev->arr[5], ev->arr[6], ev->arr[7]);
    153 	*/
    154 	if (play)
    155 		write(fd, ev, sizeof *ev);
    156 }
    157 
    158 u_long
    159 getvar(tp)
    160 	struct track *tp;
    161 {
    162 	u_long r, c;
    163 
    164 	r = 0;
    165 	do {
    166 		c = *tp->start++;
    167 		r = (r << 7) | (c & 0x7f);
    168 	} while ((c & 0x80) && tp->start < tp->end);
    169 	return (r);
    170 }
    171 
    172 void
    173 dometa(meta, p, len)
    174 	u_int meta;
    175 	u_char *p;
    176 	u_int len;
    177 {
    178 	switch (meta) {
    179 	case META_TEXT:
    180 	case META_COPYRIGHT:
    181 	case META_TRACK:
    182 	case META_INSTRUMENT:
    183 	case META_LYRIC:
    184 	case META_MARKER:
    185 	case META_CUE:
    186 		if (showmeta) {
    187 			printf("%s: ", metanames[meta]);
    188 			fwrite(p, len, 1, stdout);
    189 			printf("\n");
    190 		}
    191 		break;
    192 	case META_SET_TEMPO:
    193 		tempo = GET24(p);
    194 		if (showmeta)
    195 			printf("Tempo: %d us / quarter note\n", tempo);
    196 		break;
    197 	case META_TIMESIGN:
    198 		if (showmeta) {
    199 			int n = p[1];
    200 			int d = 1;
    201 			while (n-- > 0)
    202 				d *= 2;
    203 			printf("Time signature: %d/%d %d,%d\n",
    204 			       p[0], d, p[2], p[3]);
    205 		}
    206 		break;
    207 	case META_KEY:
    208 		if (showmeta)
    209 			printf("Key: %d %s\n", (char)p[0],
    210 			       p[1] ? "minor" : "major");
    211 		break;
    212 	default:
    213 		break;
    214 	}
    215 }
    216 
    217 void
    218 midireset()
    219 {
    220 	/* General MIDI reset sequence */
    221 	static u_char gm_reset[] = { 0x7e, 0x7f, 0x09, 0x01, 0xf7 };
    222 
    223 	send_sysex(gm_reset, sizeof gm_reset);
    224 }
    225 
    226 #define SYSEX_CHUNK 6
    227 void
    228 send_sysex(p, l)
    229 	u_char *p;
    230 	u_int l;
    231 {
    232 	seq_event_rec event;
    233 	u_int n;
    234 
    235 	event.arr[0] = SEQ_SYSEX;
    236 	event.arr[1] = unit;
    237 	do {
    238 		n = SYSEX_CHUNK;
    239 		if (l < n) {
    240 			memset(&event.arr[2], 0xff, SYSEX_CHUNK);
    241 			n = l;
    242 		}
    243 		memcpy(&event.arr[2], p, n);
    244 		send_event(&event);
    245 		l -= n;
    246 	} while (l > 0);
    247 }
    248 
    249 void
    250 playfile(f, name)
    251 	FILE *f;
    252 	char *name;
    253 {
    254 	u_char *buf;
    255 	u_int tot, n, size, nread;
    256 
    257 	/*
    258 	 * We need to read the whole file into memory for easy processing.
    259 	 * Using mmap() would be nice, but some file systems do not support
    260 	 * it, nor does reading from e.g. a pipe.  The latter also precludes
    261 	 * finding out the file size without reading it.
    262 	 */
    263 	size = 1000;
    264 	buf = malloc(size);
    265 	if (buf == 0)
    266 		errx(1, "malloc() failed\n");
    267 	nread = size;
    268 	tot = 0;
    269 	for (;;) {
    270 		n = fread(buf + tot, 1, nread, f);
    271 		tot += n;
    272 		if (n < nread)
    273 			break;
    274 		/* There must be more to read. */
    275 		nread = size;
    276 		size *= 2;
    277 		buf = realloc(buf, size);
    278 		if (buf == NULL)
    279 			errx(1, "realloc() failed\n");
    280 	}
    281 	playdata(buf, tot, name);
    282 	free(buf);
    283 }
    284 
    285 void
    286 playdata(buf, tot, name)
    287 	u_char *buf;
    288 	u_int tot;
    289 	char *name;
    290 {
    291 	int format, ntrks, divfmt, ticks, t, besttrk = 0;
    292 	u_int len, mlen, status, chan;
    293 	u_char *p, *end, byte, meta, *msg;
    294 	struct track *tracks;
    295 	u_long bestcur, now;
    296 	struct track *tp;
    297 	seq_event_rec event;
    298 
    299 	end = buf + tot;
    300 	if (verbose)
    301 		printf("Playing %s (%d bytes) ... \n", name, tot);
    302 
    303 	if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
    304 		warnx("Not a MIDI file, missing header\n");
    305 		return;
    306 	}
    307 	if (GET32(buf + MARK_LEN) != HEADER_LEN) {
    308 		warnx("Not a MIDI file, bad header\n");
    309 		return;
    310 	}
    311 	format = GET16(buf + MARK_LEN + SIZE_LEN);
    312 	ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
    313 	divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
    314 	ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
    315 	p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
    316 	if ((divfmt & 0x80) == 0)
    317 		ticks |= divfmt << 8;
    318 	else
    319 		errx(1, "Absolute time codes not implemented yet\n");
    320 	if (verbose > 1)
    321 		printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
    322 		       format, ntrks, divfmt, ticks);
    323 	if (format != 0 && format != 1) {
    324 		warnx("Cannot play MIDI file of type %d\n", format);
    325 		return;
    326 	}
    327 	if (ntrks == 0)
    328 		return;
    329 	tracks = malloc(ntrks * sizeof(struct track));
    330 	if (tracks == NULL)
    331 		errx(1, "malloc() tracks failed\n");
    332 	for (t = 0; t < ntrks; ) {
    333 		if (p >= end - MARK_LEN - SIZE_LEN) {
    334 			warnx("Cannot find track %d\n", t);
    335 			goto ret;
    336 		}
    337 		len = GET32(p + MARK_LEN);
    338 		if (len > 1000000) { /* a safe guard */
    339 			warnx("Crazy track length\n");
    340 			goto ret;
    341 		}
    342 		if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
    343 			tracks[t].start = p + MARK_LEN + SIZE_LEN;
    344 			tracks[t].end = tracks[t].start + len;
    345 			tracks[t].curtime = getvar(&tracks[t]);
    346 			t++;
    347 		}
    348 		p += MARK_LEN + SIZE_LEN + len;
    349 	}
    350 
    351 	/*
    352 	 * Play MIDI events by selecting the track track with the lowest
    353 	 * curtime.  Execute the event, update the curtime and repeat.
    354 	 */
    355 	if (sameprogram) {
    356 		for(t = 0; t < 16; t++) {
    357 			SEQ_MK_CHN_COMMON(&event, unit, MIDI_PGM_CHANGE, t,
    358 			    sameprogram+1, 0, 0);
    359 			send_event(&event);
    360 		}
    361 	}
    362 	/*
    363 	 * The ticks variable is the number of ticks that make up a quarter
    364 	 * note and is used as a reference value for the delays between
    365 	 * the MIDI events.
    366 	 */
    367 	now = 0;
    368 	for (;;) {
    369 		/* Locate lowest curtime */
    370 		bestcur = ~0;
    371 		for (t = 0; t < ntrks; t++) {
    372 			if (tracks[t].curtime < bestcur) {
    373 				bestcur = tracks[t].curtime;
    374 				besttrk = t;
    375 			}
    376 		}
    377 		if (bestcur == ~0)
    378 			break;
    379 		if (verbose > 1) {
    380 			printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
    381 			fflush(stdout);
    382 		}
    383 		if (now < bestcur) {
    384 			union {
    385 				u_int32_t i;
    386 				u_int8_t b[4];
    387 			} u;
    388 			u_int32_t delta = bestcur - now;
    389 			delta = (int)((double)delta * tempo / (1000.0*ticks));
    390 			u.i = delta;
    391 			if (delta != 0) {
    392 				event.arr[0] = SEQ_TIMING;
    393 				event.arr[1] = TMR_WAIT_REL;
    394 				event.arr[4] = u.b[0];
    395 				event.arr[5] = u.b[1];
    396 				event.arr[6] = u.b[2];
    397 				event.arr[7] = u.b[3];
    398 				send_event(&event);
    399 			}
    400 		}
    401 		now = bestcur;
    402 		tp = &tracks[besttrk];
    403 		byte = *tp->start++;
    404 		if (byte == MIDI_META) {
    405 			meta = *tp->start++;
    406 			mlen = getvar(tp);
    407 			if (verbose > 1)
    408 				printf("META %02x (%d)\n", meta, mlen);
    409 			dometa(meta, tp->start, mlen);
    410 			tp->start += mlen;
    411 		} else {
    412 			if (MIDI_IS_STATUS(byte))
    413 				tp->status = byte;
    414 			else
    415 				tp->start--;
    416 			mlen = MIDI_LENGTH(tp->status);
    417 			msg = tp->start;
    418 			if (verbose > 1) {
    419 			    if (mlen == 1)
    420 				printf("MIDI %02x (%d) %02x\n",
    421 				       tp->status, mlen, msg[0]);
    422 			    else
    423 				printf("MIDI %02x (%d) %02x %02x\n",
    424 				       tp->status, mlen, msg[0], msg[1]);
    425 			}
    426 			status = MIDI_GET_STATUS(tp->status);
    427 			chan = MIDI_GET_CHAN(tp->status);
    428 			switch (status) {
    429 			case MIDI_NOTEOFF:
    430 			case MIDI_NOTEON:
    431 			case MIDI_KEY_PRESSURE:
    432 				SEQ_MK_CHN_VOICE(&event, unit, status, chan,
    433 						 msg[0], msg[1]);
    434 				send_event(&event);
    435 				break;
    436 			case MIDI_CTL_CHANGE:
    437 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
    438 						  msg[0], 0, msg[1]);
    439 				send_event(&event);
    440 				break;
    441 			case MIDI_PGM_CHANGE:
    442 				if (sameprogram)
    443 					break;
    444 			case MIDI_CHN_PRESSURE:
    445 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
    446 						  msg[0], 0, 0);
    447 				send_event(&event);
    448 				break;
    449 			case MIDI_PITCH_BEND:
    450 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
    451 						  0, 0,
    452 						  (msg[0] & 0x7f) |
    453 						  ((msg[1] & 0x7f) << 7));
    454 				send_event(&event);
    455 				break;
    456 			case MIDI_SYSTEM_PREFIX:
    457 				mlen = getvar(tp);
    458 				if (tp->status == MIDI_SYSEX_START)
    459 					send_sysex(tp->start, mlen);
    460 				else
    461 					/* Sorry, can't do this yet */;
    462 				break;
    463 			default:
    464 				if (verbose)
    465 					printf("MIDI event 0x%02x ignored\n",
    466 					       tp->status);
    467 			}
    468 			tp->start += mlen;
    469 		}
    470 		if (tp->start >= tp->end)
    471 			tp->curtime = ~0;
    472 		else
    473 			tp->curtime += getvar(tp);
    474 	}
    475 	if (ioctl(fd, SEQUENCER_SYNC, 0) < 0)
    476 		err(1, "SEQUENCER_SYNC");
    477 
    478  ret:
    479 	free(tracks);
    480 }
    481 
    482 int
    483 main(argc, argv)
    484 	int argc;
    485 	char **argv;
    486 {
    487 	int ch;
    488 	int listdevs = 0;
    489 	int example = 0;
    490 	int nmidi;
    491 	int t;
    492 	char *file = DEVMUSIC;
    493 	struct synth_info info;
    494 	FILE *f;
    495 
    496 	while ((ch = getopt(argc, argv, "?d:f:lmp:qt:vx")) != -1) {
    497 		switch(ch) {
    498 		case 'd':
    499 			unit = atoi(optarg);
    500 			break;
    501 		case 'f':
    502 			file = optarg;
    503 			break;
    504 		case 'l':
    505 			listdevs++;
    506 			break;
    507 		case 'm':
    508 			showmeta++;
    509 			break;
    510 		case 'p':
    511 			sameprogram = atoi(optarg);
    512 			break;
    513 		case 'q':
    514 			play = 0;
    515 			break;
    516 		case 't':
    517 			ttempo = atoi(optarg);
    518 			break;
    519 		case 'v':
    520 			verbose++;
    521 			break;
    522 		case 'x':
    523 			example++;
    524 			break;
    525 		case '?':
    526 		default:
    527 			usage();
    528 		}
    529 	}
    530 	argc -= optind;
    531 	argv += optind;
    532 
    533 	fd = open(file, O_WRONLY);
    534 	if (fd < 0)
    535 		err(1, "%s", file);
    536 	if (ioctl(fd, SEQUENCER_NRMIDIS, &nmidi) < 0)
    537 		err(1, "ioctl(SEQUENCER_NRMIDIS) failed, ");
    538 	if (nmidi == 0)
    539 		errx(1, "Sorry, no MIDI devices available\n");
    540 	if (listdevs) {
    541 		for (info.device = 0; info.device < nmidi; info.device++) {
    542 			if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
    543 				err(1, "ioctl(SEQUENCER_INFO) failed, ");
    544 			printf("%d: %s\n", info.device, info.name);
    545 		}
    546 		exit(0);
    547 	}
    548 
    549 	/*
    550 	 * The sequencer has two "knobs": the TIMEBASE and the TEMPO.
    551 	 * The delay specified in TMR_WAIT_REL is specified in
    552 	 * sequencer time units.  The length of a unit is
    553 	 * 60*1000000 / (TIMEBASE * TEMPO).
    554 	 * Set it to 1ms/unit (adjusted by user tempo changes).
    555 	 */
    556 	t = 500 * ttempo / 100;
    557 	if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &t) < 0)
    558 		err(1, "SEQUENCER_TMR_TIMEBASE");
    559 	t = 120;
    560 	if (ioctl(fd, SEQUENCER_TMR_TEMPO, &t) < 0)
    561 		err(1, "SEQUENCER_TMR_TEMPO");
    562 	if (ioctl(fd, SEQUENCER_TMR_START, 0) < 0)
    563 		err(1, "SEQUENCER_TMR_START");
    564 
    565 	midireset();
    566 	if (example)
    567 		while (example--)
    568 			playdata(sample, sizeof sample, "<Gubben Noa>");
    569 	else if (argc == 0)
    570 		playfile(stdin, "<stdin>");
    571 	else
    572 		while (argc--) {
    573 			f = fopen(*argv, "r");
    574 			if (f == NULL)
    575 				err(1, "%s", *argv);
    576 			else {
    577 				playfile(f, *argv);
    578 				fclose(f);
    579 			}
    580 			argv++;
    581 		}
    582 
    583 	exit(0);
    584 }
    585