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