xref: /netbsd-src/usr.bin/midiplay/midiplay.c (revision 1ffa7b76c40339c17a0fb2a09fac93f287cfc046)
1 /*	$NetBSD: midiplay.c,v 1.18 2003/02/17 18:00:27 augustss Exp $	*/
2 
3 /*
4  * Copyright (c) 1998, 2002 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@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(void);
85 void send_event(seq_event_rec *);
86 void dometa(u_int, u_char *, u_int);
87 void midireset(void);
88 void send_sysex(u_char *, u_int);
89 u_long getvar(struct track *);
90 void playfile(FILE *, char *);
91 void playdata(u_char *, u_int, char *);
92 int main(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	RMID_SIG "RIFF"
120 #define	RMID_MIDI_ID "RMID"
121 #define	RMID_DATA_ID "data"
122 
123 #define SIZE_LEN 4
124 #define HEADER_LEN 6
125 
126 #define GET8(p) ((p)[0])
127 #define GET16(p) (((p)[0] << 8) | (p)[1])
128 #define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
129 #define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
130 #define GET32_LE(p) (((p)[3] << 24) | ((p)[2] << 16) | ((p)[1] << 8) | (p)[0])
131 
132 void
133 usage(void)
134 {
135 	printf("Usage: %s [-d unit] [-f file] [-l] [-m] [-p pgm] [-q] "
136 	       "[-t tempo] [-v] [-x] [file ...]\n",
137 		getprogname());
138 	exit(1);
139 }
140 
141 int showmeta = 0;
142 int verbose = 0;
143 #define BASETEMPO 400000
144 u_int tempo = BASETEMPO;		/* microsec / quarter note */
145 u_int ttempo = 100;
146 int unit = 0;
147 int play = 1;
148 int fd = -1;
149 int sameprogram = 0;
150 
151 void
152 send_event(seq_event_rec *ev)
153 {
154 	/*
155 	printf("%02x %02x %02x %02x %02x %02x %02x %02x\n",
156 	       ev->arr[0], ev->arr[1], ev->arr[2], ev->arr[3],
157 	       ev->arr[4], ev->arr[5], ev->arr[6], ev->arr[7]);
158 	*/
159 	if (play)
160 		write(fd, ev, sizeof *ev);
161 }
162 
163 u_long
164 getvar(struct track *tp)
165 {
166 	u_long r, c;
167 
168 	r = 0;
169 	do {
170 		c = *tp->start++;
171 		r = (r << 7) | (c & 0x7f);
172 	} while ((c & 0x80) && tp->start < tp->end);
173 	return (r);
174 }
175 
176 void
177 dometa(u_int meta, u_char *p, 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(void)
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(u_char *p, u_int l)
230 {
231 	seq_event_rec event;
232 	u_int n;
233 
234 	event.arr[0] = SEQ_SYSEX;
235 	event.arr[1] = unit;
236 	do {
237 		n = SYSEX_CHUNK;
238 		if (l < n) {
239 			memset(&event.arr[2], 0xff, SYSEX_CHUNK);
240 			n = l;
241 		}
242 		memcpy(&event.arr[2], p, n);
243 		send_event(&event);
244 		l -= n;
245 		p += n;
246 	} while (l > 0);
247 }
248 
249 void
250 playfile(FILE *f, char *name)
251 {
252 	u_char *buf;
253 	u_int tot, n, size, nread;
254 
255 	/*
256 	 * We need to read the whole file into memory for easy processing.
257 	 * Using mmap() would be nice, but some file systems do not support
258 	 * it, nor does reading from e.g. a pipe.  The latter also precludes
259 	 * finding out the file size without reading it.
260 	 */
261 	size = 1000;
262 	buf = malloc(size);
263 	if (buf == 0)
264 		errx(1, "malloc() failed");
265 	nread = size;
266 	tot = 0;
267 	for (;;) {
268 		n = fread(buf + tot, 1, nread, f);
269 		tot += n;
270 		if (n < nread)
271 			break;
272 		/* There must be more to read. */
273 		nread = size;
274 		size *= 2;
275 		buf = realloc(buf, size);
276 		if (buf == NULL)
277 			errx(1, "realloc() failed");
278 	}
279 	playdata(buf, tot, name);
280 	free(buf);
281 }
282 
283 void
284 playdata(u_char *buf, u_int tot, char *name)
285 {
286 	int format, ntrks, divfmt, ticks, t, besttrk = 0;
287 	u_int len, mlen, status, chan;
288 	u_char *p, *end, byte, meta, *msg;
289 	struct track *tracks;
290 	u_long bestcur, now;
291 	struct track *tp;
292 	seq_event_rec event;
293 
294 	end = buf + tot;
295 	if (verbose)
296 		printf("Playing %s (%d bytes) ... \n", name, tot);
297 
298 	if (tot < MARK_LEN + 4) {
299 		warnx("Not a MIDI file, too short");
300 		return;
301 	}
302 
303 	if (memcmp(buf, RMID_SIG, MARK_LEN) == 0) {
304 		u_char *eod;
305 		/* Detected a RMID file, let's just check if it's
306 		 * a MIDI file */
307 		if (GET32_LE(buf + MARK_LEN) != tot - 8) {
308 			warnx("Not a RMID file, bad header");
309 			return;
310 		}
311 
312 		buf += MARK_LEN + 4;
313 		if (memcmp(buf, RMID_MIDI_ID, MARK_LEN) != 0) {
314 			warnx("Not a RMID file, bad ID");
315 			return;
316 		}
317 
318 		/* Now look for the 'data' chunk, which contains
319 		 * MIDI data */
320 		buf += MARK_LEN;
321 
322 		/* Test against end-8 since we must have at least 8 bytes
323 		 * left to read */
324 		while(buf < end-8 && memcmp(buf, RMID_DATA_ID, MARK_LEN))
325 			buf += GET32_LE(buf+4) + 8; /* MARK_LEN + 4 */
326 
327 		if (buf >= end-8) {
328 			warnx("Not a valid RMID file, no data chunk");
329 			return;
330 		}
331 
332 		buf += MARK_LEN; /* "data" */
333 		eod = buf + 4 + GET32_LE(buf);
334 		if (eod >= end) {
335 			warnx("Not a valid RMID file, bad data chunk size");
336 			return;
337 		}
338 
339 		end = eod;
340 		buf += 4;
341 	}
342 
343 	if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
344 		warnx("Not a MIDI file, missing header");
345 		return;
346 	}
347 
348 	if (GET32(buf + MARK_LEN) != HEADER_LEN) {
349 		warnx("Not a MIDI file, bad header");
350 		return;
351 	}
352 	format = GET16(buf + MARK_LEN + SIZE_LEN);
353 	ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
354 	divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
355 	ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
356 	p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
357 	if ((divfmt & 0x80) == 0)
358 		ticks |= divfmt << 8;
359 	else
360 		errx(1, "Absolute time codes not implemented yet");
361 	if (verbose > 1)
362 		printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
363 		       format, ntrks, divfmt, ticks);
364 	if (format != 0 && format != 1) {
365 		warnx("Cannot play MIDI file of type %d", format);
366 		return;
367 	}
368 	if (ntrks == 0)
369 		return;
370 	tracks = malloc(ntrks * sizeof(struct track));
371 	if (tracks == NULL)
372 		errx(1, "malloc() tracks failed");
373 	for (t = 0; t < ntrks; ) {
374 		if (p >= end - MARK_LEN - SIZE_LEN) {
375 			warnx("Cannot find track %d", t);
376 			goto ret;
377 		}
378 		len = GET32(p + MARK_LEN);
379 		if (len > 1000000) { /* a safe guard */
380 			warnx("Crazy track length");
381 			goto ret;
382 		}
383 		if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
384 			tracks[t].start = p + MARK_LEN + SIZE_LEN;
385 			tracks[t].end = tracks[t].start + len;
386 			tracks[t].curtime = getvar(&tracks[t]);
387 			t++;
388 		}
389 		p += MARK_LEN + SIZE_LEN + len;
390 	}
391 
392 	/*
393 	 * Play MIDI events by selecting the track with the lowest
394 	 * curtime.  Execute the event, update the curtime and repeat.
395 	 */
396 	if (sameprogram) {
397 		for(t = 0; t < 16; t++) {
398 			SEQ_MK_CHN_COMMON(&event, unit, MIDI_PGM_CHANGE, t,
399 			    sameprogram-1, 0, 0);
400 			send_event(&event);
401 		}
402 	}
403 	/*
404 	 * The ticks variable is the number of ticks that make up a quarter
405 	 * note and is used as a reference value for the delays between
406 	 * the MIDI events.
407 	 */
408 	now = 0;
409 	for (;;) {
410 		/* Locate lowest curtime */
411 		bestcur = ~0;
412 		for (t = 0; t < ntrks; t++) {
413 			if (tracks[t].curtime < bestcur) {
414 				bestcur = tracks[t].curtime;
415 				besttrk = t;
416 			}
417 		}
418 		if (bestcur == ~0)
419 			break;
420 		if (verbose > 1) {
421 			printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
422 			fflush(stdout);
423 		}
424 		if (now < bestcur) {
425 			union {
426 				u_int32_t i;
427 				u_int8_t b[4];
428 			} u;
429 			u_int32_t delta = bestcur - now;
430 			delta = (int)((double)delta * tempo / (1000.0*ticks));
431 			u.i = delta;
432 			if (delta != 0) {
433 				event.arr[0] = SEQ_TIMING;
434 				event.arr[1] = TMR_WAIT_REL;
435 				event.arr[4] = u.b[0];
436 				event.arr[5] = u.b[1];
437 				event.arr[6] = u.b[2];
438 				event.arr[7] = u.b[3];
439 				send_event(&event);
440 			}
441 		}
442 		now = bestcur;
443 		tp = &tracks[besttrk];
444 		byte = *tp->start++;
445 		if (byte == MIDI_META) {
446 			meta = *tp->start++;
447 			mlen = getvar(tp);
448 			if (verbose > 1)
449 				printf("META %02x (%d)\n", meta, mlen);
450 			dometa(meta, tp->start, mlen);
451 			tp->start += mlen;
452 		} else {
453 			if (MIDI_IS_STATUS(byte))
454 				tp->status = byte;
455 			else
456 				tp->start--;
457 			mlen = MIDI_LENGTH(tp->status);
458 			msg = tp->start;
459 			if (verbose > 1) {
460 			    if (mlen == 1)
461 				printf("MIDI %02x (%d) %02x\n",
462 				       tp->status, mlen, msg[0]);
463 			    else
464 				printf("MIDI %02x (%d) %02x %02x\n",
465 				       tp->status, mlen, msg[0], msg[1]);
466 			}
467 			status = MIDI_GET_STATUS(tp->status);
468 			chan = MIDI_GET_CHAN(tp->status);
469 			switch (status) {
470 			case MIDI_NOTEOFF:
471 			case MIDI_NOTEON:
472 			case MIDI_KEY_PRESSURE:
473 				SEQ_MK_CHN_VOICE(&event, unit, status, chan,
474 						 msg[0], msg[1]);
475 				send_event(&event);
476 				break;
477 			case MIDI_CTL_CHANGE:
478 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
479 						  msg[0], 0, msg[1]);
480 				send_event(&event);
481 				break;
482 			case MIDI_PGM_CHANGE:
483 				if (sameprogram)
484 					break;
485 			case MIDI_CHN_PRESSURE:
486 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
487 						  msg[0], 0, 0);
488 				send_event(&event);
489 				break;
490 			case MIDI_PITCH_BEND:
491 				SEQ_MK_CHN_COMMON(&event, unit, status, chan,
492 						  0, 0,
493 						  (msg[0] & 0x7f) |
494 						  ((msg[1] & 0x7f) << 7));
495 				send_event(&event);
496 				break;
497 			case MIDI_SYSTEM_PREFIX:
498 				mlen = getvar(tp);
499 				if (tp->status == MIDI_SYSEX_START)
500 					send_sysex(tp->start, mlen);
501 				else
502 					/* Sorry, can't do this yet */;
503 				break;
504 			default:
505 				if (verbose)
506 					printf("MIDI event 0x%02x ignored\n",
507 					       tp->status);
508 			}
509 			tp->start += mlen;
510 		}
511 		if (tp->start >= tp->end)
512 			tp->curtime = ~0;
513 		else
514 			tp->curtime += getvar(tp);
515 	}
516 	if (ioctl(fd, SEQUENCER_SYNC, 0) < 0)
517 		err(1, "SEQUENCER_SYNC");
518 
519  ret:
520 	free(tracks);
521 }
522 
523 int
524 main(int argc, char **argv)
525 {
526 	int ch;
527 	int listdevs = 0;
528 	int example = 0;
529 	int nmidi;
530 	int t;
531 	const char *file = DEVMUSIC;
532 	const char *sunit;
533 	struct synth_info info;
534 	FILE *f;
535 
536 	if ((sunit = getenv("MIDIUNIT")))
537 		unit = atoi(sunit);
538 
539 	while ((ch = getopt(argc, argv, "?d:f:lmp:qt:vx")) != -1) {
540 		switch(ch) {
541 		case 'd':
542 			unit = atoi(optarg);
543 			break;
544 		case 'f':
545 			file = optarg;
546 			break;
547 		case 'l':
548 			listdevs++;
549 			break;
550 		case 'm':
551 			showmeta++;
552 			break;
553 		case 'p':
554 			sameprogram = atoi(optarg);
555 			break;
556 		case 'q':
557 			play = 0;
558 			break;
559 		case 't':
560 			ttempo = atoi(optarg);
561 			break;
562 		case 'v':
563 			verbose++;
564 			break;
565 		case 'x':
566 			example++;
567 			break;
568 		case '?':
569 		default:
570 			usage();
571 		}
572 	}
573 	argc -= optind;
574 	argv += optind;
575 
576 	if (!play)
577 		goto output;
578 
579 	fd = open(file, O_WRONLY);
580 	if (fd < 0)
581 		err(1, "%s", file);
582 	if (ioctl(fd, SEQUENCER_NRMIDIS, &nmidi) < 0)
583 		err(1, "ioctl(SEQUENCER_NRMIDIS) failed, ");
584 	if (nmidi == 0)
585 		errx(1, "Sorry, no MIDI devices available");
586 	if (listdevs) {
587 		for (info.device = 0; info.device < nmidi; info.device++) {
588 			if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
589 				err(1, "ioctl(SEQUENCER_INFO) failed, ");
590 			printf("%d: %s\n", info.device, info.name);
591 		}
592 		exit(0);
593 	}
594 
595 	/*
596 	 * The sequencer has two "knobs": the TIMEBASE and the TEMPO.
597 	 * The delay specified in TMR_WAIT_REL is specified in
598 	 * sequencer time units.  The length of a unit is
599 	 * 60*1000000 / (TIMEBASE * TEMPO).
600 	 * Set it to 1ms/unit (adjusted by user tempo changes).
601 	 */
602 	t = 500 * ttempo / 100;
603 	if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &t) < 0)
604 		err(1, "SEQUENCER_TMR_TIMEBASE");
605 	t = 120;
606 	if (ioctl(fd, SEQUENCER_TMR_TEMPO, &t) < 0)
607 		err(1, "SEQUENCER_TMR_TEMPO");
608 	if (ioctl(fd, SEQUENCER_TMR_START, 0) < 0)
609 		err(1, "SEQUENCER_TMR_START");
610 
611 	midireset();
612 
613  output:
614 	if (example)
615 		while (example--)
616 			playdata(sample, sizeof sample, "<Gubben Noa>");
617 	else if (argc == 0)
618 		playfile(stdin, "<stdin>");
619 	else
620 		while (argc--) {
621 			f = fopen(*argv, "r");
622 			if (f == NULL)
623 				err(1, "%s", *argv);
624 			else {
625 				playfile(f, *argv);
626 				fclose(f);
627 			}
628 			argv++;
629 		}
630 
631 	exit(0);
632 }
633