GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/midiplay/midiplay.c Lines: 0 182 0.0 %
Date: 2017-11-07 Branches: 0 121 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: midiplay.c,v 1.19 2017/04/24 06:45:56 ratchov Exp $	*/
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
33
#include <sys/types.h>
34
#include <sys/stat.h>
35
#include <signal.h>
36
#include <stdio.h>
37
#include <stdlib.h>
38
#include <limits.h>
39
#include <err.h>
40
#include <unistd.h>
41
#include <string.h>
42
#include <sndio.h>
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
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
81
void usage(void);
82
void send_event(u_char, u_char *, u_int);
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
void sigalrm(int);
89
int main(int argc, char **argv);
90
91
#define P(c) 1,0x90,c,0x7f,4,0x80,c,0
92
#define PL(c) 1,0x90,c,0x7f,8,0x80,c,0
93
#define C 0x3c
94
#define D 0x3e
95
#define E 0x40
96
#define F 0x41
97
98
u_char sample[] = {
99
	'M','T','h','d',  0,0,0,6,  0,1,  0,1,  0,8,
100
	'M','T','r','k',  0,0,0,4+13*8,
101
	P(C), P(C), P(C), P(E), P(D), P(D), P(D),
102
	P(F), P(E), P(E), P(D), P(D), PL(C),
103
	0, 0xff, 0x2f, 0
104
};
105
#undef P
106
#undef PL
107
#undef C
108
#undef D
109
#undef E
110
#undef F
111
112
#define MARK_HEADER "MThd"
113
#define MARK_TRACK "MTrk"
114
#define MARK_LEN 4
115
116
#define SIZE_LEN 4
117
#define HEADER_LEN 6
118
119
#define GET8(p) ((p)[0])
120
#define GET16(p) (((p)[0] << 8) | (p)[1])
121
#define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
122
#define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
123
124
void
125
usage(void)
126
{
127
	extern char *__progname;
128
129
	(void)fprintf(stderr, "usage: "
130
	       "%s [-gmqvx] [-f device] [-t tempo] [file ...]\n",
131
	       __progname);
132
	exit(1);
133
}
134
135
int showmeta = 0;
136
int verbose = 0;
137
u_int tempo = 60 * 1000000 / 100;	/* default tempo is 100bpm */
138
int play = 1;
139
struct mio_hdl *hdl;
140
struct timespec ts, ts_last;
141
142
void
143
send_event(u_char status, u_char *data, u_int len)
144
{
145
	u_int i;
146
147
	if (verbose > 1) {
148
		printf("MIDI %02x", status);
149
		for (i = 0; i < len; i++)
150
			printf(" %02x", data[i]);
151
		printf("\n");
152
	}
153
	if (play) {
154
		mio_write(hdl, &status, 1);
155
		mio_write(hdl, data, len);
156
	}
157
}
158
159
u_long
160
getvar(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(u_int meta, u_char *p, u_int len)
174
{
175
	switch (meta) {
176
	case META_TEXT:
177
	case META_COPYRIGHT:
178
	case META_TRACK:
179
	case META_INSTRUMENT:
180
	case META_LYRIC:
181
	case META_MARKER:
182
	case META_CUE:
183
		if (showmeta) {
184
			printf("%s: ", metanames[meta]);
185
			fwrite(p, len, 1, stdout);
186
			printf("\n");
187
		}
188
		break;
189
	case META_SET_TEMPO:
190
		tempo = GET24(p);
191
		if (showmeta)
192
			printf("Tempo: %d us / quarter note\n", tempo);
193
		break;
194
	case META_TIMESIGN:
195
		if (showmeta) {
196
			int n = p[1];
197
			int d = 1;
198
			while (n-- > 0)
199
				d *= 2;
200
			printf("Time signature: %d/%d %d,%d\n",
201
			       p[0], d, p[2], p[3]);
202
		}
203
		break;
204
	case META_KEY:
205
		if (showmeta)
206
			printf("Key: %d %s\n", (char)p[0],
207
			       p[1] ? "minor" : "major");
208
		break;
209
	default:
210
		break;
211
	}
212
}
213
214
void
215
midireset(void)
216
{
217
	/* General MIDI reset sequence */
218
	static u_char gm_reset[] = { 0x7e, 0x7f, 0x09, 0x01, 0xf7 };
219
220
	send_event(MIDI_SYSEX_START, gm_reset, sizeof gm_reset);
221
}
222
223
void
224
playfile(FILE *f, char *name)
225
{
226
	u_char *buf, *newbuf;
227
	u_int tot, n, size, newsize, nread;
228
229
	/*
230
	 * We need to read the whole file into memory for easy processing.
231
	 * Using mmap() would be nice, but some file systems do not support
232
	 * it, nor does reading from e.g. a pipe.  The latter also precludes
233
	 * finding out the file size without reading it.
234
	 */
235
	size = 1000;
236
	buf = malloc(size);
237
	if (buf == NULL)
238
		err(1, "malloc() failed");
239
	nread = size;
240
	tot = 0;
241
	for (;;) {
242
		n = fread(buf + tot, 1, nread, f);
243
		tot += n;
244
		if (n < nread)
245
			break;
246
		/* There must be more to read. */
247
		nread = size;
248
		newsize = size * 2;
249
		newbuf = realloc(buf, newsize);
250
		if (newbuf == NULL)
251
			err(1, "realloc() failed");
252
		buf = newbuf;
253
		size = newsize;
254
	}
255
	playdata(buf, tot, name);
256
	free(buf);
257
}
258
259
void
260
sigalrm(int i)
261
{
262
}
263
264
void
265
playdata(u_char *buf, u_int tot, char *name)
266
{
267
	long long delta_nsec = 0;
268
	u_int delta_ticks;
269
	int format, ntrks, divfmt, ticks, t, besttrk = 0;
270
	u_int len, mlen;
271
	u_char *p, *end, byte, meta;
272
	struct track *tracks;
273
	u_long bestcur, now;
274
	struct track *tp;
275
276
	end = buf + tot;
277
	if (verbose)
278
		printf("Playing %s (%d bytes) ... \n", name, tot);
279
280
	if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
281
		warnx("Not a MIDI file, missing header");
282
		return;
283
	}
284
	if (GET32(buf + MARK_LEN) != HEADER_LEN) {
285
		warnx("Not a MIDI file, bad header");
286
		return;
287
	}
288
	format = GET16(buf + MARK_LEN + SIZE_LEN);
289
	ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
290
	divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
291
	ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
292
	p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
293
	if ((divfmt & 0x80) == 0)
294
		ticks |= divfmt << 8;
295
	else
296
		errx(1, "Absolute time codes not implemented yet");
297
	if (verbose > 1)
298
		printf("format=%d ntrks=%d divfmt=%x ticks=%d\n",
299
		       format, ntrks, divfmt, ticks);
300
	if (format != 0 && format != 1) {
301
		warnx("Cannnot play MIDI file of type %d", format);
302
		return;
303
	}
304
	if (ntrks == 0)
305
		return;
306
	tracks = calloc(ntrks, sizeof(struct track));
307
	if (tracks == NULL)
308
		err(1, "malloc() tracks failed");
309
	for (t = 0; t < ntrks; ) {
310
		if (p >= end - MARK_LEN - SIZE_LEN) {
311
			warnx("Cannot find track %d", t);
312
			goto ret;
313
		}
314
		len = GET32(p + MARK_LEN);
315
		if (len > end - (p + MARK_LEN + SIZE_LEN)) {
316
			warnx("Crazy track length");
317
			goto ret;
318
		}
319
		if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
320
			tracks[t].start = p + MARK_LEN + SIZE_LEN;
321
			tracks[t].end = tracks[t].start + len;
322
			tracks[t].curtime = getvar(&tracks[t]);
323
			t++;
324
		}
325
		p += MARK_LEN + SIZE_LEN + len;
326
	}
327
328
	/*
329
	 * Play MIDI events by selecting the track with the lowest
330
	 * curtime.  Execute the event, update the curtime and repeat.
331
	 */
332
333
	now = 0;
334
	delta_nsec = 0;
335
	if (clock_gettime(CLOCK_MONOTONIC, &ts_last) < 0)
336
		err(1, "clock_gettime");
337
	for (;;) {
338
		/* Locate lowest curtime */
339
		bestcur = ULONG_MAX;
340
		for (t = 0; t < ntrks; t++) {
341
			if (tracks[t].curtime < bestcur) {
342
				bestcur = tracks[t].curtime;
343
				besttrk = t;
344
			}
345
		}
346
		if (bestcur == ULONG_MAX)
347
			break;
348
		if (verbose > 1) {
349
			printf("DELAY %4ld TRACK %2d ", bestcur-now, besttrk);
350
			fflush(stdout);
351
		}
352
		while (now < bestcur) {
353
			pause();
354
			if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
355
				err(1, "clock_gettime");
356
			delta_nsec += 1000000000L * (ts.tv_sec - ts_last.tv_sec);
357
			delta_nsec += ts.tv_nsec - ts_last.tv_nsec;
358
			ts_last = ts;
359
			if (delta_nsec <= 0)
360
				continue;
361
			delta_ticks = delta_nsec * ticks / (1000LL * tempo);
362
			delta_nsec -= 1000LL * delta_ticks * tempo / ticks;
363
			now += delta_ticks;
364
		}
365
		tp = &tracks[besttrk];
366
		byte = *tp->start++;
367
		if (byte == MIDI_META) {
368
			meta = *tp->start++;
369
			mlen = getvar(tp);
370
			if (verbose > 1)
371
				printf("META %02x (%d)\n", meta, mlen);
372
			dometa(meta, tp->start, mlen);
373
			tp->start += mlen;
374
		} else {
375
			if (MIDI_IS_STATUS(byte))
376
				tp->status = byte;
377
			else
378
				tp->start--;
379
			if (MIDI_IS_COMMON(tp->status)) {
380
				mlen = MIDI_LENGTH(tp->status);
381
				send_event(tp->status, tp->start, mlen);
382
			} else if (tp->status == MIDI_SYSEX_START) {
383
				mlen = getvar(tp);
384
				send_event(MIDI_SYSEX_START, tp->start, mlen);
385
			} else if (tp->status == MIDI_SYSEX_STOP) {
386
				mlen = getvar(tp);
387
				/* Sorry, can't do this yet */;
388
			} else {
389
				if (verbose)
390
					printf("MIDI event 0x%02x ignored\n",
391
					       tp->status);
392
			}
393
			tp->start += mlen;
394
		}
395
		if (tp->start >= tp->end)
396
			tp->curtime = ULONG_MAX;
397
		else
398
			tp->curtime += getvar(tp);
399
	}
400
 ret:
401
	free(tracks);
402
}
403
404
int
405
main(int argc, char **argv)
406
{
407
	int ch;
408
	int example = 0;
409
	int gmreset = 0;
410
	char *file = NULL;
411
	FILE *f;
412
	const char *errstr;
413
	struct sigaction sa;
414
	struct itimerval it;
415
416
	while ((ch = getopt(argc, argv, "?d:f:glmqt:vx")) != -1) {
417
		switch (ch) {
418
		case 'f':
419
			file = optarg;
420
			break;
421
		case 'g':
422
			gmreset = 1;
423
			break;
424
		case 'm':
425
			showmeta = 1;
426
			break;
427
		case 'q':
428
			play = 0;
429
			break;
430
		case 't':
431
			tempo = 60 * 1000000 /
432
			    strtonum(optarg, 40, 240, &errstr);
433
			if (errstr)
434
				errx(1, "tempo is %s: %s", errstr, optarg);
435
			break;
436
		case 'v':
437
			verbose++;
438
			break;
439
		case 'x':
440
			example = 1;
441
			break;
442
		case '?':
443
		default:
444
			usage();
445
		}
446
	}
447
	argc -= optind;
448
	argv += optind;
449
450
	hdl = mio_open(file, MIO_OUT, 0);
451
	if (hdl == NULL)
452
		errx(1, "failed to open MIDI output");
453
	if (gmreset)
454
		midireset();
455
456
	sa.sa_flags = SA_RESTART;
457
	sa.sa_handler = sigalrm;
458
	sigfillset(&sa.sa_mask);
459
	if (sigaction(SIGALRM, &sa, NULL) < 0)
460
		err(1, "sigaction");
461
	it.it_interval.tv_sec = it.it_value.tv_sec = 0;
462
	it.it_interval.tv_usec = it.it_value.tv_usec = 1000;
463
	if (setitimer(ITIMER_REAL, &it, NULL) < 0)
464
		err(1, "setitimer");
465
466
	if (example)
467
		playdata(sample, sizeof sample, "<Gubben Noa>");
468
	else if (argc == 0)
469
		playfile(stdin, "<stdin>");
470
	else
471
		while (argc--) {
472
			f = fopen(*argv, "r");
473
			if (f == NULL)
474
				err(1, "%s", *argv);
475
			else {
476
				playfile(f, *argv);
477
				fclose(f);
478
			}
479
			argv++;
480
		}
481
482
	exit(0);
483
}