midiplay.c revision 1.6 1 /* $NetBSD: midiplay.c,v 1.6 1998/08/13 21:01:53 augustss Exp $ */
2
3 /*
4 * Copyright (c) 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Author: Lennart Augustsson
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the NetBSD
20 * Foundation, Inc. and its contributors.
21 * 4. Neither the name of The NetBSD Foundation nor the names of its
22 * contributors may be used to endorse or promote products derived
23 * from this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 * POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <fcntl.h>
41 #include <err.h>
42 #include <unistd.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/ioctl.h>
47 #include <sys/midiio.h>
48
49 #define DEVMUSIC "/dev/music"
50
51 struct track {
52 u_char *start, *end;
53 u_long curtime;
54 u_char status;
55 };
56
57 #define MIDI_META 0xff
58
59 #define META_SEQNO 0x00
60 #define META_TEXT 0x01
61 #define META_COPYRIGHT 0x02
62 #define META_TRACK 0x03
63 #define META_INSTRUMENT 0x04
64 #define META_LYRIC 0x05
65 #define META_MARKER 0x06
66 #define META_CUE 0x07
67 #define META_CHPREFIX 0x20
68 #define META_EOT 0x2f
69 #define META_SET_TEMPO 0x51
70 #define META_KEY 0x59
71 #define META_SMPTE 0x54
72 #define META_TIMESIGN 0x58
73
74 char *metanames[] = {
75 "", "Text", "Copyright", "Track", "Instrument",
76 "Lyric", "Marker", "Cue",
77 };
78
79 static int midi_lengths[] = { 2,2,2,2,1,1,2,0 };
80 /* Number of bytes in a MIDI command */
81 #define MIDI_LENGTH(d) (midi_lengths[((d) >> 4) & 7])
82
83 void usage __P((void));
84 void send_event __P((seq_event_rec *));
85 void dometa __P((u_int, u_char *, u_int));
86 void midireset __P((void));
87 void send_sysex __P((u_char *, u_int));
88 u_long getvar __P((struct track *));
89 void playfile __P((FILE *, char *));
90 void playdata __P((u_char *, u_int, char *));
91 int main __P((int argc, char **argv));
92
93 extern char *__progname;
94
95 #define P(c) 1,0x90,c,0x7f,4,0x80,c,0
96 #define PL(c) 1,0x90,c,0x7f,8,0x80,c,0
97 #define C 0x3c
98 #define D 0x3e
99 #define E 0x40
100 #define F 0x41
101
102 u_char sample[] = {
103 'M','T','h','d', 0,0,0,6, 0,1, 0,1, 0,8,
104 'M','T','r','k', 0,0,0,4+13*8,
105 P(C), P(C), P(C), P(E), P(D), P(D), P(D),
106 P(F), P(E), P(E), P(D), P(D), PL(C),
107 0, 0xff, 0x2f, 0
108 };
109 #undef P
110 #undef PL
111 #undef C
112 #undef D
113 #undef E
114 #undef F
115
116 #define MARK_HEADER "MThd"
117 #define MARK_TRACK "MTrk"
118 #define MARK_LEN 4
119
120 #define SIZE_LEN 4
121 #define HEADER_LEN 6
122
123 #define GET8(p) ((p)[0])
124 #define GET16(p) (((p)[0] << 8) | (p)[1])
125 #define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
126 #define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
127
128 void
129 usage()
130 {
131 printf("Usage: %s [-d unit] [-f file] [-l] [-m] [-q] [-t tempo] [-v] [-x] [file ...]\n",
132 __progname);
133 exit(1);
134 }
135
136 int showmeta = 0;
137 int verbose = 0;
138 #define BASETEMPO 400000
139 u_int tempo = BASETEMPO; /* microsec / quarter note */
140 u_int ttempo = 100;
141 int unit = 0;
142 int play = 1;
143 int fd;
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 } while (l > 0);
247 }
248
249 void
250 playfile(f, name)
251 FILE *f;
252 char *name;
253 {
254 u_char *buf;
255 u_int tot, n, size, nread;
256
257 /*
258 * We need to read the whole file into memory for easy processing.
259 * Using mmap() would be nice, but some file systems do not support
260 * it, nor does reading from e.g. a pipe. The latter also precludes
261 * finding out the file size without reading it.
262 */
263 size = 1000;
264 buf = malloc(size);
265 if (buf == 0)
266 errx(1, "malloc() failed\n");
267 nread = size;
268 tot = 0;
269 for (;;) {
270 n = fread(buf + tot, 1, nread, f);
271 tot += n;
272 if (n < nread)
273 break;
274 /* There must be more to read. */
275 nread = size;
276 size *= 2;
277 buf = realloc(buf, size);
278 if (buf == NULL)
279 errx(1, "realloc() failed\n");
280 }
281 playdata(buf, tot, name);
282 free(buf);
283 }
284
285 void
286 playdata(buf, tot, name)
287 u_char *buf;
288 u_int tot;
289 char *name;
290 {
291 int format, ntrks, divfmt, ticks, t, besttrk = 0;
292 u_int len, mlen, status, chan;
293 u_char *p, *end, byte, meta, *msg;
294 struct track *tracks;
295 u_long bestcur, now;
296 struct track *tp;
297 seq_event_rec event;
298
299 end = buf + tot;
300 if (verbose)
301 printf("Playing %s (%d bytes) ... \n", name, tot);
302
303 if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
304 warnx("Not a MIDI file, missing header\n");
305 return;
306 }
307 if (GET32(buf + MARK_LEN) != HEADER_LEN) {
308 warnx("Not a MIDI file, bad header\n");
309 return;
310 }
311 format = GET16(buf + MARK_LEN + SIZE_LEN);
312 ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
313 divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
314 ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
315 p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
316 if ((divfmt & 0x80) == 0)
317 ticks |= divfmt << 8;
318 else
319 errx(1, "Absolute time codes not implemented yet\n");
320 if (verbose > 1)
321 printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
322 format, ntrks, divfmt, ticks);
323 if (format != 0 && format != 1) {
324 warnx("Cannnot play MIDI file of type %d\n", format);
325 return;
326 }
327 if (ntrks == 0)
328 return;
329 tracks = malloc(ntrks * sizeof(struct track));
330 if (tracks == NULL)
331 errx(1, "malloc() tracks failed\n");
332 for (t = 0; t < ntrks; ) {
333 if (p >= end - MARK_LEN - SIZE_LEN) {
334 warnx("Cannot find track %d\n", t);
335 goto ret;
336 }
337 len = GET32(p + MARK_LEN);
338 if (len > 1000000) { /* a safe guard */
339 warnx("Crazy track length\n");
340 goto ret;
341 }
342 if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
343 tracks[t].start = p + MARK_LEN + SIZE_LEN;
344 tracks[t].end = tracks[t].start + len;
345 tracks[t].curtime = getvar(&tracks[t]);
346 t++;
347 }
348 p += MARK_LEN + SIZE_LEN + len;
349 }
350
351 /*
352 * Play MIDI events by selecting the track track with the lowest
353 * curtime. Execute the event, update the curtime and repeat.
354 */
355
356 /*
357 * The ticks variable is the number of ticks that make up a quarter
358 * note and is used as a reference value for the delays between
359 * the MIDI events.
360 * The sequencer has two "knobs": the TIMEBASE and the TEMPO.
361 * The delay specified in TMR_WAIT_REL is specified in
362 * sequencer time units. The length of a unit is
363 * 60*1000000 / (TIMEBASE * TEMPO).
364 * Set it to 1ms/unit (adjusted by user tempo changes).
365 */
366 t = 500 * ttempo / 100;
367 if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &t) < 0)
368 err(1, "SEQUENCER_TMR_TIMEBASE");
369 t = 120;
370 if (ioctl(fd, SEQUENCER_TMR_TEMPO, &t) < 0)
371 err(1, "SEQUENCER_TMR_TEMPO");
372 if (ioctl(fd, SEQUENCER_TMR_START, 0) < 0)
373 err(1, "SEQUENCER_TMR_START");
374 now = 0;
375 for (;;) {
376 /* Locate lowest curtime */
377 bestcur = ~0;
378 for (t = 0; t < ntrks; t++) {
379 if (tracks[t].curtime < bestcur) {
380 bestcur = tracks[t].curtime;
381 besttrk = t;
382 }
383 }
384 if (bestcur == ~0)
385 break;
386 if (verbose > 1) {
387 printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
388 fflush(stdout);
389 }
390 if (now < bestcur) {
391 union {
392 u_int32_t i;
393 u_int8_t b[4];
394 } u;
395 u_int32_t delta = bestcur - now;
396 delta = (int)((double)delta * tempo / (1000.0*ticks));
397 u.i = delta;
398 if (delta != 0) {
399 event.arr[0] = SEQ_TIMING;
400 event.arr[1] = TMR_WAIT_REL;
401 event.arr[4] = u.b[0];
402 event.arr[5] = u.b[1];
403 event.arr[6] = u.b[2];
404 event.arr[7] = u.b[3];
405 send_event(&event);
406 }
407 }
408 now = bestcur;
409 tp = &tracks[besttrk];
410 byte = *tp->start++;
411 if (byte == MIDI_META) {
412 meta = *tp->start++;
413 mlen = getvar(tp);
414 if (verbose > 1)
415 printf("META %02x (%d)\n", meta, mlen);
416 dometa(meta, tp->start, mlen);
417 tp->start += mlen;
418 } else {
419 if (MIDI_IS_STATUS(byte))
420 tp->status = byte;
421 else
422 tp->start--;
423 mlen = MIDI_LENGTH(tp->status);
424 msg = tp->start;
425 if (verbose > 1) {
426 if (mlen == 1)
427 printf("MIDI %02x (%d) %02x\n",
428 tp->status, mlen, msg[0]);
429 else
430 printf("MIDI %02x (%d) %02x %02x\n",
431 tp->status, mlen, msg[0], msg[1]);
432 }
433 status = MIDI_GET_STATUS(tp->status);
434 chan = MIDI_GET_CHAN(tp->status);
435 switch (status) {
436 case MIDI_NOTEOFF:
437 case MIDI_NOTEON:
438 case MIDI_KEY_PRESSURE:
439 SEQ_MK_CHN_VOICE(&event, unit, status, chan,
440 msg[0], msg[1]);
441 send_event(&event);
442 break;
443 case MIDI_CTL_CHANGE:
444 SEQ_MK_CHN_COMMON(&event, unit, status, chan,
445 msg[0], 0, msg[1]);
446 send_event(&event);
447 break;
448 case MIDI_PGM_CHANGE:
449 case MIDI_CHN_PRESSURE:
450 SEQ_MK_CHN_COMMON(&event, unit, status, chan,
451 msg[0], 0, 0);
452 send_event(&event);
453 break;
454 case MIDI_PITCH_BEND:
455 SEQ_MK_CHN_COMMON(&event, unit, status, chan,
456 0, 0,
457 (msg[0] & 0x7f) |
458 ((msg[1] & 0x7f) << 7));
459 send_event(&event);
460 break;
461 case MIDI_SYSTEM_PREFIX:
462 mlen = getvar(tp);
463 if (tp->status == MIDI_SYSEX_START)
464 send_sysex(tp->start, mlen);
465 else
466 /* Sorry, can't do this yet */;
467 break;
468 default:
469 if (verbose)
470 printf("MIDI event 0x%02x ignored\n",
471 tp->status);
472 }
473 tp->start += mlen;
474 }
475 if (tp->start >= tp->end)
476 tp->curtime = ~0;
477 else
478 tp->curtime += getvar(tp);
479 }
480 if (ioctl(fd, SEQUENCER_SYNC, 0) < 0)
481 err(1, "SEQUENCER_SYNC");
482
483 ret:
484 free(tracks);
485 }
486
487 int
488 main(argc, argv)
489 int argc;
490 char **argv;
491 {
492 int ch;
493 int listdevs = 0;
494 int example = 0;
495 int nmidi;
496 char *file = DEVMUSIC;
497 struct synth_info info;
498 FILE *f;
499
500 while ((ch = getopt(argc, argv, "?d:lmqt:vx")) != -1) {
501 switch(ch) {
502 case 'd':
503 unit = atoi(optarg);
504 break;
505 case 'f':
506 file = optarg;
507 break;
508 case 'l':
509 listdevs++;
510 break;
511 case 'm':
512 showmeta++;
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 fd = open(file, O_WRONLY);
535 if (fd < 0)
536 err(1, "%s", file);
537 if (ioctl(fd, SEQUENCER_NRMIDIS, &nmidi) < 0)
538 err(1, "ioctl(SEQUENCER_NRMIDIS) failed, ");
539 if (nmidi == 0)
540 errx(1, "Sorry, no MIDI devices available\n");
541 if (listdevs) {
542 for (info.device = 0; info.device < nmidi; info.device++) {
543 if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
544 err(1, "ioctl(SEQUENCER_INFO) failed, ");
545 printf("%d: %s\n", info.device, info.name);
546 }
547 exit(0);
548 }
549 midireset();
550 if (example)
551 playdata(sample, sizeof sample, "<Gubben Noa>");
552 else if (argc == 0)
553 playfile(stdin, "<stdin>");
554 else
555 while (argc--) {
556 f = fopen(*argv, "r");
557 if (f == NULL)
558 err(1, "%s", *argv);
559 else {
560 playfile(f, *argv);
561 fclose(f);
562 }
563 argv++;
564 }
565
566 exit(0);
567 }
568