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