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