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