midiplay.c revision 1.19 1 /* $NetBSD: midiplay.c,v 1.19 2003/06/23 13:05:49 agc 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.19 2003/06/23 13:05:49 agc 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;
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 size *= 2;
281 buf = realloc(buf, size);
282 if (buf == NULL)
283 errx(1, "realloc() failed");
284 }
285 playdata(buf, tot, name);
286 free(buf);
287 }
288
289 void
290 playdata(u_char *buf, u_int tot, 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 (tot < MARK_LEN + 4) {
305 warnx("Not a MIDI file, too short");
306 return;
307 }
308
309 if (memcmp(buf, RMID_SIG, MARK_LEN) == 0) {
310 u_char *eod;
311 /* Detected a RMID file, let's just check if it's
312 * a MIDI file */
313 if (GET32_LE(buf + MARK_LEN) != tot - 8) {
314 warnx("Not a RMID file, bad header");
315 return;
316 }
317
318 buf += MARK_LEN + 4;
319 if (memcmp(buf, RMID_MIDI_ID, MARK_LEN) != 0) {
320 warnx("Not a RMID file, bad ID");
321 return;
322 }
323
324 /* Now look for the 'data' chunk, which contains
325 * MIDI data */
326 buf += MARK_LEN;
327
328 /* Test against end-8 since we must have at least 8 bytes
329 * left to read */
330 while(buf < end-8 && memcmp(buf, RMID_DATA_ID, MARK_LEN))
331 buf += GET32_LE(buf+4) + 8; /* MARK_LEN + 4 */
332
333 if (buf >= end-8) {
334 warnx("Not a valid RMID file, no data chunk");
335 return;
336 }
337
338 buf += MARK_LEN; /* "data" */
339 eod = buf + 4 + GET32_LE(buf);
340 if (eod >= end) {
341 warnx("Not a valid RMID file, bad data chunk size");
342 return;
343 }
344
345 end = eod;
346 buf += 4;
347 }
348
349 if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
350 warnx("Not a MIDI file, missing header");
351 return;
352 }
353
354 if (GET32(buf + MARK_LEN) != HEADER_LEN) {
355 warnx("Not a MIDI file, bad header");
356 return;
357 }
358 format = GET16(buf + MARK_LEN + SIZE_LEN);
359 ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
360 divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
361 ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
362 p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
363 if ((divfmt & 0x80) == 0)
364 ticks |= divfmt << 8;
365 else
366 errx(1, "Absolute time codes not implemented yet");
367 if (verbose > 1)
368 printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
369 format, ntrks, divfmt, ticks);
370 if (format != 0 && format != 1) {
371 warnx("Cannot play MIDI file of type %d", format);
372 return;
373 }
374 if (ntrks == 0)
375 return;
376 tracks = malloc(ntrks * sizeof(struct track));
377 if (tracks == NULL)
378 errx(1, "malloc() tracks failed");
379 for (t = 0; t < ntrks; ) {
380 if (p >= end - MARK_LEN - SIZE_LEN) {
381 warnx("Cannot find track %d", t);
382 goto ret;
383 }
384 len = GET32(p + MARK_LEN);
385 if (len > 1000000) { /* a safe guard */
386 warnx("Crazy track length");
387 goto ret;
388 }
389 if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
390 tracks[t].start = p + MARK_LEN + SIZE_LEN;
391 tracks[t].end = tracks[t].start + len;
392 tracks[t].curtime = getvar(&tracks[t]);
393 t++;
394 }
395 p += MARK_LEN + SIZE_LEN + len;
396 }
397
398 /*
399 * Play MIDI events by selecting the track with the lowest
400 * curtime. Execute the event, update the curtime and repeat.
401 */
402 if (sameprogram) {
403 for(t = 0; t < 16; t++) {
404 SEQ_MK_CHN_COMMON(&event, unit, MIDI_PGM_CHANGE, t,
405 sameprogram-1, 0, 0);
406 send_event(&event);
407 }
408 }
409 /*
410 * The ticks variable is the number of ticks that make up a quarter
411 * note and is used as a reference value for the delays between
412 * the MIDI events.
413 */
414 now = 0;
415 for (;;) {
416 /* Locate lowest curtime */
417 bestcur = ~0;
418 for (t = 0; t < ntrks; t++) {
419 if (tracks[t].curtime < bestcur) {
420 bestcur = tracks[t].curtime;
421 besttrk = t;
422 }
423 }
424 if (bestcur == ~0)
425 break;
426 if (verbose > 1) {
427 printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
428 fflush(stdout);
429 }
430 if (now < bestcur) {
431 union {
432 u_int32_t i;
433 u_int8_t b[4];
434 } u;
435 u_int32_t delta = bestcur - now;
436 delta = (int)((double)delta * tempo / (1000.0*ticks));
437 u.i = delta;
438 if (delta != 0) {
439 event.arr[0] = SEQ_TIMING;
440 event.arr[1] = TMR_WAIT_REL;
441 event.arr[4] = u.b[0];
442 event.arr[5] = u.b[1];
443 event.arr[6] = u.b[2];
444 event.arr[7] = u.b[3];
445 send_event(&event);
446 }
447 }
448 now = bestcur;
449 tp = &tracks[besttrk];
450 byte = *tp->start++;
451 if (byte == MIDI_META) {
452 meta = *tp->start++;
453 mlen = getvar(tp);
454 if (verbose > 1)
455 printf("META %02x (%d)\n", meta, mlen);
456 dometa(meta, tp->start, mlen);
457 tp->start += mlen;
458 } else {
459 if (MIDI_IS_STATUS(byte))
460 tp->status = byte;
461 else
462 tp->start--;
463 mlen = MIDI_LENGTH(tp->status);
464 msg = tp->start;
465 if (verbose > 1) {
466 if (mlen == 1)
467 printf("MIDI %02x (%d) %02x\n",
468 tp->status, mlen, msg[0]);
469 else
470 printf("MIDI %02x (%d) %02x %02x\n",
471 tp->status, mlen, msg[0], msg[1]);
472 }
473 status = MIDI_GET_STATUS(tp->status);
474 chan = MIDI_GET_CHAN(tp->status);
475 switch (status) {
476 case MIDI_NOTEOFF:
477 case MIDI_NOTEON:
478 case MIDI_KEY_PRESSURE:
479 SEQ_MK_CHN_VOICE(&event, unit, status, chan,
480 msg[0], msg[1]);
481 send_event(&event);
482 break;
483 case MIDI_CTL_CHANGE:
484 SEQ_MK_CHN_COMMON(&event, unit, status, chan,
485 msg[0], 0, msg[1]);
486 send_event(&event);
487 break;
488 case MIDI_PGM_CHANGE:
489 if (sameprogram)
490 break;
491 case MIDI_CHN_PRESSURE:
492 SEQ_MK_CHN_COMMON(&event, unit, status, chan,
493 msg[0], 0, 0);
494 send_event(&event);
495 break;
496 case MIDI_PITCH_BEND:
497 SEQ_MK_CHN_COMMON(&event, unit, status, chan,
498 0, 0,
499 (msg[0] & 0x7f) |
500 ((msg[1] & 0x7f) << 7));
501 send_event(&event);
502 break;
503 case MIDI_SYSTEM_PREFIX:
504 mlen = getvar(tp);
505 if (tp->status == MIDI_SYSEX_START)
506 send_sysex(tp->start, mlen);
507 else
508 /* Sorry, can't do this yet */;
509 break;
510 default:
511 if (verbose)
512 printf("MIDI event 0x%02x ignored\n",
513 tp->status);
514 }
515 tp->start += mlen;
516 }
517 if (tp->start >= tp->end)
518 tp->curtime = ~0;
519 else
520 tp->curtime += getvar(tp);
521 }
522 if (ioctl(fd, SEQUENCER_SYNC, 0) < 0)
523 err(1, "SEQUENCER_SYNC");
524
525 ret:
526 free(tracks);
527 }
528
529 int
530 main(int argc, char **argv)
531 {
532 int ch;
533 int listdevs = 0;
534 int example = 0;
535 int nmidi;
536 int t;
537 const char *file = DEVMUSIC;
538 const char *sunit;
539 struct synth_info info;
540 FILE *f;
541
542 if ((sunit = getenv("MIDIUNIT")))
543 unit = atoi(sunit);
544
545 while ((ch = getopt(argc, argv, "?d:f:lmp:qt:vx")) != -1) {
546 switch(ch) {
547 case 'd':
548 unit = atoi(optarg);
549 break;
550 case 'f':
551 file = optarg;
552 break;
553 case 'l':
554 listdevs++;
555 break;
556 case 'm':
557 showmeta++;
558 break;
559 case 'p':
560 sameprogram = atoi(optarg);
561 break;
562 case 'q':
563 play = 0;
564 break;
565 case 't':
566 ttempo = atoi(optarg);
567 break;
568 case 'v':
569 verbose++;
570 break;
571 case 'x':
572 example++;
573 break;
574 case '?':
575 default:
576 usage();
577 }
578 }
579 argc -= optind;
580 argv += optind;
581
582 if (!play)
583 goto output;
584
585 fd = open(file, O_WRONLY);
586 if (fd < 0)
587 err(1, "%s", file);
588 if (ioctl(fd, SEQUENCER_NRMIDIS, &nmidi) < 0)
589 err(1, "ioctl(SEQUENCER_NRMIDIS) failed, ");
590 if (nmidi == 0)
591 errx(1, "Sorry, no MIDI devices available");
592 if (listdevs) {
593 for (info.device = 0; info.device < nmidi; info.device++) {
594 if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
595 err(1, "ioctl(SEQUENCER_INFO) failed, ");
596 printf("%d: %s\n", info.device, info.name);
597 }
598 exit(0);
599 }
600
601 /*
602 * The sequencer has two "knobs": the TIMEBASE and the TEMPO.
603 * The delay specified in TMR_WAIT_REL is specified in
604 * sequencer time units. The length of a unit is
605 * 60*1000000 / (TIMEBASE * TEMPO).
606 * Set it to 1ms/unit (adjusted by user tempo changes).
607 */
608 t = 500 * ttempo / 100;
609 if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &t) < 0)
610 err(1, "SEQUENCER_TMR_TIMEBASE");
611 t = 120;
612 if (ioctl(fd, SEQUENCER_TMR_TEMPO, &t) < 0)
613 err(1, "SEQUENCER_TMR_TEMPO");
614 if (ioctl(fd, SEQUENCER_TMR_START, 0) < 0)
615 err(1, "SEQUENCER_TMR_START");
616
617 midireset();
618
619 output:
620 if (example)
621 while (example--)
622 playdata(sample, sizeof sample, "<Gubben Noa>");
623 else if (argc == 0)
624 playfile(stdin, "<stdin>");
625 else
626 while (argc--) {
627 f = fopen(*argv, "r");
628 if (f == NULL)
629 err(1, "%s", *argv);
630 else {
631 playfile(f, *argv);
632 fclose(f);
633 }
634 argv++;
635 }
636
637 exit(0);
638 }
639