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