Annotation of src/usr.bin/midiplay/midiplay.c, Revision 1.14
1.14 ! ratchov 1: /* $OpenBSD: midiplay.c,v 1.13 2011/04/28 07:23:46 ratchov Exp $ */
1.1 niklas 2: /* $NetBSD: midiplay.c,v 1.8 1998/11/25 22:17:07 augustss Exp $ */
3:
4: /*
5: * Copyright (c) 1998 The NetBSD Foundation, Inc.
6: * All rights reserved.
7: *
8: * This code is derived from software contributed to The NetBSD Foundation
9: * by Lennart Augustsson (augustss@netbsd.org).
10: *
11: * Redistribution and use in source and binary forms, with or without
12: * modification, are permitted provided that the following conditions
13: * are met:
14: * 1. Redistributions of source code must retain the above copyright
15: * notice, this list of conditions and the following disclaimer.
16: * 2. Redistributions in binary form must reproduce the above copyright
17: * notice, this list of conditions and the following disclaimer in the
18: * documentation and/or other materials provided with the distribution.
19: *
20: * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21: * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22: * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23: * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24: * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30: * POSSIBILITY OF SUCH DAMAGE.
31: */
32:
1.5 tedu 33: #include <sys/types.h>
34: #include <sys/stat.h>
1.12 ratchov 35: #include <signal.h>
1.1 niklas 36: #include <stdio.h>
37: #include <stdlib.h>
1.5 tedu 38: #include <limits.h>
1.1 niklas 39: #include <err.h>
40: #include <unistd.h>
41: #include <string.h>
1.12 ratchov 42: #include <sndio.h>
1.1 niklas 43:
44: struct track {
45: u_char *start, *end;
46: u_long curtime;
47: u_char status;
48: };
49:
50: #define MIDI_META 0xff
51:
52: #define META_SEQNO 0x00
53: #define META_TEXT 0x01
54: #define META_COPYRIGHT 0x02
55: #define META_TRACK 0x03
56: #define META_INSTRUMENT 0x04
57: #define META_LYRIC 0x05
58: #define META_MARKER 0x06
59: #define META_CUE 0x07
60: #define META_CHPREFIX 0x20
61: #define META_EOT 0x2f
62: #define META_SET_TEMPO 0x51
63: #define META_KEY 0x59
64: #define META_SMPTE 0x54
65: #define META_TIMESIGN 0x58
66:
67: char *metanames[] = {
68: "", "Text", "Copyright", "Track", "Instrument",
69: "Lyric", "Marker", "Cue",
70: };
71:
72: static int midi_lengths[] = { 2,2,2,2,1,1,2,0 };
73: /* Number of bytes in a MIDI command */
74: #define MIDI_LENGTH(d) (midi_lengths[((d) >> 4) & 7])
75:
1.12 ratchov 76: #define MIDI_IS_STATUS(d) ((d) & 0x80)
77: #define MIDI_IS_COMMON(d) ((d) < 0xf0)
78: #define MIDI_SYSEX_START 0xf0
79: #define MIDI_SYSEX_STOP 0xf7
80:
1.2 millert 81: void usage(void);
1.12 ratchov 82: void send_event(u_char, u_char *, u_int);
1.2 millert 83: void dometa(u_int, u_char *, u_int);
84: void midireset(void);
85: u_long getvar(struct track *);
86: void playfile(FILE *, char *);
87: void playdata(u_char *, u_int, char *);
88: int main(int argc, char **argv);
1.1 niklas 89:
90: extern char *__progname;
91:
92: #define P(c) 1,0x90,c,0x7f,4,0x80,c,0
93: #define PL(c) 1,0x90,c,0x7f,8,0x80,c,0
94: #define C 0x3c
95: #define D 0x3e
96: #define E 0x40
97: #define F 0x41
98:
99: u_char sample[] = {
100: 'M','T','h','d', 0,0,0,6, 0,1, 0,1, 0,8,
101: 'M','T','r','k', 0,0,0,4+13*8,
102: P(C), P(C), P(C), P(E), P(D), P(D), P(D),
103: P(F), P(E), P(E), P(D), P(D), PL(C),
104: 0, 0xff, 0x2f, 0
105: };
106: #undef P
107: #undef PL
108: #undef C
109: #undef D
110: #undef E
111: #undef F
112:
113: #define MARK_HEADER "MThd"
114: #define MARK_TRACK "MTrk"
115: #define MARK_LEN 4
116:
117: #define SIZE_LEN 4
118: #define HEADER_LEN 6
119:
120: #define GET8(p) ((p)[0])
121: #define GET16(p) (((p)[0] << 8) | (p)[1])
122: #define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
123: #define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
124:
125: void
1.4 deraadt 126: usage(void)
1.1 niklas 127: {
1.11 sobrado 128: printf("usage: "
1.12 ratchov 129: "%s [-gmqvx] [-f device] [-t tempo] [file ...]\n",
1.11 sobrado 130: __progname);
1.1 niklas 131: exit(1);
132: }
133:
134: int showmeta = 0;
135: int verbose = 0;
1.12 ratchov 136: u_int tempo = 60 * 1000000 / 100; /* default tempo is 100bpm */
1.1 niklas 137: int play = 1;
1.12 ratchov 138: struct mio_hdl *hdl;
139: struct timespec ts, ts_last;
1.1 niklas 140:
141: void
1.12 ratchov 142: send_event(u_char status, u_char *data, u_int len)
1.1 niklas 143: {
1.12 ratchov 144: u_int i;
145:
146: if (verbose > 1) {
147: printf("MIDI %02x", status);
148: for (i = 0; i < len; i++)
149: printf(" %02x", data[i]);
150: printf("\n");
151: }
152: if (play) {
153: mio_write(hdl, &status, 1);
154: mio_write(hdl, data, len);
155: }
1.1 niklas 156: }
157:
158: u_long
1.4 deraadt 159: getvar(struct track *tp)
1.1 niklas 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
1.4 deraadt 172: dometa(u_int meta, u_char *p, u_int len)
1.1 niklas 173: {
174: switch (meta) {
175: case META_TEXT:
176: case META_COPYRIGHT:
177: case META_TRACK:
178: case META_INSTRUMENT:
179: case META_LYRIC:
180: case META_MARKER:
181: case META_CUE:
182: if (showmeta) {
183: printf("%s: ", metanames[meta]);
184: fwrite(p, len, 1, stdout);
185: printf("\n");
186: }
187: break;
188: case META_SET_TEMPO:
189: tempo = GET24(p);
190: if (showmeta)
191: printf("Tempo: %d us / quarter note\n", tempo);
192: break;
193: case META_TIMESIGN:
194: if (showmeta) {
195: int n = p[1];
196: int d = 1;
197: while (n-- > 0)
198: d *= 2;
199: printf("Time signature: %d/%d %d,%d\n",
200: p[0], d, p[2], p[3]);
201: }
202: break;
203: case META_KEY:
204: if (showmeta)
205: printf("Key: %d %s\n", (char)p[0],
206: p[1] ? "minor" : "major");
207: break;
208: default:
209: break;
210: }
211: }
212:
213: void
1.4 deraadt 214: midireset(void)
1.1 niklas 215: {
216: /* General MIDI reset sequence */
217: static u_char gm_reset[] = { 0x7e, 0x7f, 0x09, 0x01, 0xf7 };
218:
1.12 ratchov 219: send_event(MIDI_SYSEX_START, gm_reset, sizeof gm_reset);
1.1 niklas 220: }
221:
222: void
1.4 deraadt 223: playfile(FILE *f, char *name)
1.1 niklas 224: {
1.5 tedu 225: u_char *buf, *newbuf;
226: u_int tot, n, size, newsize, nread;
1.1 niklas 227:
228: /*
229: * We need to read the whole file into memory for easy processing.
230: * Using mmap() would be nice, but some file systems do not support
231: * it, nor does reading from e.g. a pipe. The latter also precludes
232: * finding out the file size without reading it.
233: */
234: size = 1000;
235: buf = malloc(size);
1.5 tedu 236: if (buf == NULL)
237: err(1, "malloc() failed");
1.1 niklas 238: nread = size;
239: tot = 0;
240: for (;;) {
241: n = fread(buf + tot, 1, nread, f);
242: tot += n;
243: if (n < nread)
244: break;
245: /* There must be more to read. */
246: nread = size;
1.5 tedu 247: newsize = size * 2;
248: newbuf = realloc(buf, newsize);
249: if (newbuf == NULL)
250: err(1, "realloc() failed");
251: buf = newbuf;
252: size = newsize;
1.1 niklas 253: }
254: playdata(buf, tot, name);
255: free(buf);
256: }
257:
258: void
1.12 ratchov 259: sigalrm(int i)
260: {
261: }
262:
263: void
1.4 deraadt 264: playdata(u_char *buf, u_int tot, char *name)
1.1 niklas 265: {
1.12 ratchov 266: long long delta_nsec = 0;
267: u_int delta_ticks;
1.1 niklas 268: int format, ntrks, divfmt, ticks, t, besttrk = 0;
1.12 ratchov 269: u_int len, mlen;
270: u_char *p, *end, byte, meta;
1.1 niklas 271: struct track *tracks;
272: u_long bestcur, now;
273: struct track *tp;
274:
275: end = buf + tot;
276: if (verbose)
277: printf("Playing %s (%d bytes) ... \n", name, tot);
278:
279: if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
1.3 mpech 280: warnx("Not a MIDI file, missing header");
1.1 niklas 281: return;
282: }
283: if (GET32(buf + MARK_LEN) != HEADER_LEN) {
1.3 mpech 284: warnx("Not a MIDI file, bad header");
1.1 niklas 285: return;
286: }
287: format = GET16(buf + MARK_LEN + SIZE_LEN);
288: ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
289: divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
290: ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
291: p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
292: if ((divfmt & 0x80) == 0)
293: ticks |= divfmt << 8;
294: else
1.3 mpech 295: errx(1, "Absolute time codes not implemented yet");
1.1 niklas 296: if (verbose > 1)
297: printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
298: format, ntrks, divfmt, ticks);
299: if (format != 0 && format != 1) {
1.3 mpech 300: warnx("Cannnot play MIDI file of type %d", format);
1.1 niklas 301: return;
302: }
303: if (ntrks == 0)
304: return;
1.9 deraadt 305: tracks = calloc(ntrks, sizeof(struct track));
1.1 niklas 306: if (tracks == NULL)
1.5 tedu 307: err(1, "malloc() tracks failed");
1.1 niklas 308: for (t = 0; t < ntrks; ) {
309: if (p >= end - MARK_LEN - SIZE_LEN) {
1.3 mpech 310: warnx("Cannot find track %d", t);
1.1 niklas 311: goto ret;
312: }
313: len = GET32(p + MARK_LEN);
314: if (len > 1000000) { /* a safe guard */
1.3 mpech 315: warnx("Crazy track length");
1.1 niklas 316: goto ret;
317: }
318: if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
319: tracks[t].start = p + MARK_LEN + SIZE_LEN;
320: tracks[t].end = tracks[t].start + len;
321: tracks[t].curtime = getvar(&tracks[t]);
322: t++;
323: }
324: p += MARK_LEN + SIZE_LEN + len;
325: }
326:
327: /*
328: * Play MIDI events by selecting the track track with the lowest
329: * curtime. Execute the event, update the curtime and repeat.
330: */
331:
332: now = 0;
1.12 ratchov 333: delta_nsec = 0;
334: if (clock_gettime(CLOCK_MONOTONIC, &ts_last) < 0)
335: err(1, "clock_gettime");
1.1 niklas 336: for (;;) {
337: /* Locate lowest curtime */
1.13 ratchov 338: bestcur = ULONG_MAX;
1.1 niklas 339: for (t = 0; t < ntrks; t++) {
340: if (tracks[t].curtime < bestcur) {
341: bestcur = tracks[t].curtime;
342: besttrk = t;
343: }
344: }
1.13 ratchov 345: if (bestcur == ULONG_MAX)
1.1 niklas 346: break;
347: if (verbose > 1) {
348: printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
349: fflush(stdout);
350: }
1.12 ratchov 351: while (now < bestcur) {
352: pause();
353: if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
354: err(1, "clock_gettime");
355: delta_nsec += 1000000000L * (ts.tv_sec - ts_last.tv_sec);
356: delta_nsec += ts.tv_nsec - ts_last.tv_nsec;
357: ts_last = ts;
358: if (delta_nsec <= 0)
359: continue;
360: delta_ticks = delta_nsec * ticks / (1000LL * tempo);
361: delta_nsec -= 1000LL * delta_ticks * tempo / ticks;
362: now += delta_ticks;
1.1 niklas 363: }
364: tp = &tracks[besttrk];
365: byte = *tp->start++;
366: if (byte == MIDI_META) {
367: meta = *tp->start++;
368: mlen = getvar(tp);
369: if (verbose > 1)
370: printf("META %02x (%d)\n", meta, mlen);
371: dometa(meta, tp->start, mlen);
372: tp->start += mlen;
373: } else {
374: if (MIDI_IS_STATUS(byte))
375: tp->status = byte;
376: else
377: tp->start--;
1.12 ratchov 378: if (MIDI_IS_COMMON(tp->status)) {
379: mlen = MIDI_LENGTH(tp->status);
380: send_event(tp->status, tp->start, mlen);
381: } else if (tp->status == MIDI_SYSEX_START) {
382: mlen = getvar(tp);
383: send_event(MIDI_SYSEX_START, tp->start, mlen);
384: } else if (tp->status == MIDI_SYSEX_STOP) {
1.1 niklas 385: mlen = getvar(tp);
1.12 ratchov 386: /* Sorry, can't do this yet */;
387: } else {
1.1 niklas 388: if (verbose)
389: printf("MIDI event 0x%02x ignored\n",
390: tp->status);
391: }
392: tp->start += mlen;
393: }
394: if (tp->start >= tp->end)
1.13 ratchov 395: tp->curtime = ULONG_MAX;
1.1 niklas 396: else
397: tp->curtime += getvar(tp);
398: }
399: ret:
400: free(tracks);
401: }
402:
403: int
1.4 deraadt 404: main(int argc, char **argv)
1.1 niklas 405: {
406: int ch;
407: int example = 0;
1.8 jsg 408: int gmreset = 0;
1.12 ratchov 409: char *file = NULL;
1.1 niklas 410: FILE *f;
1.5 tedu 411: const char *errstr;
1.12 ratchov 412: struct sigaction sa;
413: struct itimerval it;
1.1 niklas 414:
1.8 jsg 415: while ((ch = getopt(argc, argv, "?d:f:glmqt:vx")) != -1) {
1.5 tedu 416: switch (ch) {
1.1 niklas 417: case 'f':
418: file = optarg;
419: break;
1.8 jsg 420: case 'g':
421: gmreset++;
422: break;
1.1 niklas 423: case 'm':
424: showmeta++;
425: break;
426: case 'q':
427: play = 0;
428: break;
429: case 't':
1.12 ratchov 430: tempo = 60 * 1000000 /
431: strtonum(optarg, 40, 240, &errstr);
1.5 tedu 432: if (errstr)
433: errx(1, "tempo is %s: %s", errstr, optarg);
1.1 niklas 434: break;
435: case 'v':
436: verbose++;
437: break;
438: case 'x':
439: example++;
440: break;
441: case '?':
442: default:
443: usage();
444: }
445: }
446: argc -= optind;
447: argv += optind;
448:
1.12 ratchov 449: hdl = mio_open(file, MIO_OUT, 0);
1.14 ! ratchov 450: if (hdl == NULL)
! 451: errx(1, "failed to open MIDI output");
1.8 jsg 452: if (gmreset)
453: midireset();
1.12 ratchov 454:
455: sa.sa_flags = SA_RESTART;
456: sa.sa_handler = sigalrm;
457: sigfillset(&sa.sa_mask);
458: if (sigaction(SIGALRM, &sa, NULL) < 0)
459: err(1, "sigaction");
460: it.it_interval.tv_sec = it.it_value.tv_sec = 0;
461: it.it_interval.tv_usec = it.it_value.tv_usec = 1000;
462: if (setitimer(ITIMER_REAL, &it, NULL) < 0)
463: err(1, "setitimer");
464:
1.1 niklas 465: if (example)
466: playdata(sample, sizeof sample, "<Gubben Noa>");
467: else if (argc == 0)
468: playfile(stdin, "<stdin>");
469: else
470: while (argc--) {
471: f = fopen(*argv, "r");
472: if (f == NULL)
473: err(1, "%s", *argv);
474: else {
475: playfile(f, *argv);
476: fclose(f);
477: }
478: argv++;
479: }
480:
481: exit(0);
482: }