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