midiplay.c revision 1.29 1 1.29 jmcneill /* $NetBSD: midiplay.c,v 1.29 2011/11/25 01:39:47 jmcneill Exp $ */
2 1.1 augustss
3 1.1 augustss /*
4 1.16 augustss * Copyright (c) 1998, 2002 The NetBSD Foundation, Inc.
5 1.1 augustss * All rights reserved.
6 1.1 augustss *
7 1.8 augustss * This code is derived from software contributed to The NetBSD Foundation
8 1.20 salo * by Lennart Augustsson (augustss (at) NetBSD.org).
9 1.1 augustss *
10 1.1 augustss * Redistribution and use in source and binary forms, with or without
11 1.1 augustss * modification, are permitted provided that the following conditions
12 1.1 augustss * are met:
13 1.1 augustss * 1. Redistributions of source code must retain the above copyright
14 1.1 augustss * notice, this list of conditions and the following disclaimer.
15 1.1 augustss * 2. Redistributions in binary form must reproduce the above copyright
16 1.1 augustss * notice, this list of conditions and the following disclaimer in the
17 1.1 augustss * documentation and/or other materials provided with the distribution.
18 1.1 augustss *
19 1.1 augustss * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 1.1 augustss * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 1.1 augustss * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 1.1 augustss * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 1.1 augustss * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 1.1 augustss * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 1.1 augustss * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 1.1 augustss * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 1.1 augustss * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 1.1 augustss * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 1.1 augustss * POSSIBILITY OF SUCH DAMAGE.
30 1.1 augustss */
31 1.19 agc #include <sys/cdefs.h>
32 1.19 agc
33 1.19 agc #ifndef lint
34 1.29 jmcneill __RCSID("$NetBSD: midiplay.c,v 1.29 2011/11/25 01:39:47 jmcneill Exp $");
35 1.19 agc #endif
36 1.19 agc
37 1.1 augustss
38 1.1 augustss #include <stdio.h>
39 1.1 augustss #include <stdlib.h>
40 1.1 augustss #include <fcntl.h>
41 1.1 augustss #include <err.h>
42 1.29 jmcneill #include <errno.h>
43 1.29 jmcneill #include <limits.h>
44 1.1 augustss #include <unistd.h>
45 1.1 augustss #include <string.h>
46 1.1 augustss #include <sys/types.h>
47 1.1 augustss #include <sys/stat.h>
48 1.1 augustss #include <sys/ioctl.h>
49 1.1 augustss #include <sys/midiio.h>
50 1.1 augustss
51 1.1 augustss #define DEVMUSIC "/dev/music"
52 1.1 augustss
53 1.1 augustss struct track {
54 1.23 chap struct track *indirect; /* for fast swaps in heap code */
55 1.1 augustss u_char *start, *end;
56 1.23 chap u_long delta;
57 1.1 augustss u_char status;
58 1.1 augustss };
59 1.1 augustss
60 1.1 augustss #define MIDI_META 0xff
61 1.1 augustss
62 1.1 augustss #define META_SEQNO 0x00
63 1.1 augustss #define META_TEXT 0x01
64 1.1 augustss #define META_COPYRIGHT 0x02
65 1.1 augustss #define META_TRACK 0x03
66 1.1 augustss #define META_INSTRUMENT 0x04
67 1.1 augustss #define META_LYRIC 0x05
68 1.1 augustss #define META_MARKER 0x06
69 1.1 augustss #define META_CUE 0x07
70 1.1 augustss #define META_CHPREFIX 0x20
71 1.1 augustss #define META_EOT 0x2f
72 1.1 augustss #define META_SET_TEMPO 0x51
73 1.1 augustss #define META_KEY 0x59
74 1.1 augustss #define META_SMPTE 0x54
75 1.1 augustss #define META_TIMESIGN 0x58
76 1.1 augustss
77 1.28 christos static const char *metanames[] = {
78 1.28 christos "", "Text", "Copyright", "Track", "Instrument",
79 1.1 augustss "Lyric", "Marker", "Cue",
80 1.1 augustss };
81 1.1 augustss
82 1.28 christos static int midi_lengths[] = { 2, 2, 2, 2, 1, 1, 2, 0 };
83 1.1 augustss /* Number of bytes in a MIDI command */
84 1.1 augustss #define MIDI_LENGTH(d) (midi_lengths[((d) >> 4) & 7])
85 1.1 augustss
86 1.28 christos #define SEQ_MK_SYSEX0(_dev,...) \
87 1.28 christos SEQ_MK_EVENT(sysex, 0x94, .device=(_dev), .buffer={__VA_ARGS__})
88 1.28 christos
89 1.28 christos
90 1.28 christos static void usage(void);
91 1.28 christos static void send_event(seq_event_t *);
92 1.28 christos static void dometa(u_int, u_char *, u_int);
93 1.28 christos #if 0
94 1.28 christos static void midireset(void);
95 1.28 christos #endif
96 1.28 christos static void send_sysex(u_char *, u_int);
97 1.28 christos static u_long getvar(struct track *);
98 1.28 christos static u_long getlen(struct track *);
99 1.28 christos static void playfile(FILE *, const char *);
100 1.28 christos static void playdata(u_char *, u_int, const char *);
101 1.28 christos
102 1.28 christos static void Heapify(struct track *, int, int);
103 1.28 christos static void BuildHeap(struct track *, int);
104 1.28 christos static int ShrinkHeap(struct track *, int);
105 1.23 chap
106 1.23 chap /*
107 1.23 chap * This sample plays at an apparent tempo of 120 bpm when the BASETEMPO is 150
108 1.23 chap * bpm, because the quavers are 5 divisions (4 on 1 off) rather than 4 total.
109 1.23 chap */
110 1.28 christos #define P(c) 1, 0x90, c, 0x7f, 4, 0x80, c, 0
111 1.28 christos #define PL(c) 1, 0x90, c, 0x7f, 8, 0x80, c, 0
112 1.1 augustss #define C 0x3c
113 1.1 augustss #define D 0x3e
114 1.1 augustss #define E 0x40
115 1.1 augustss #define F 0x41
116 1.1 augustss
117 1.28 christos static u_char sample[] = {
118 1.28 christos 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 8,
119 1.28 christos 'M', 'T', 'r', 'k', 0, 0, 0, 4+13*8,
120 1.28 christos P(C), P(C), P(C), P(E), P(D), P(D), P(D),
121 1.1 augustss P(F), P(E), P(E), P(D), P(D), PL(C),
122 1.1 augustss 0, 0xff, 0x2f, 0
123 1.1 augustss };
124 1.1 augustss #undef P
125 1.1 augustss #undef PL
126 1.1 augustss #undef C
127 1.1 augustss #undef D
128 1.1 augustss #undef E
129 1.1 augustss #undef F
130 1.1 augustss
131 1.1 augustss #define MARK_HEADER "MThd"
132 1.1 augustss #define MARK_TRACK "MTrk"
133 1.1 augustss #define MARK_LEN 4
134 1.1 augustss
135 1.18 augustss #define RMID_SIG "RIFF"
136 1.18 augustss #define RMID_MIDI_ID "RMID"
137 1.18 augustss #define RMID_DATA_ID "data"
138 1.18 augustss
139 1.1 augustss #define SIZE_LEN 4
140 1.1 augustss #define HEADER_LEN 6
141 1.1 augustss
142 1.1 augustss #define GET8(p) ((p)[0])
143 1.1 augustss #define GET16(p) (((p)[0] << 8) | (p)[1])
144 1.1 augustss #define GET24(p) (((p)[0] << 16) | ((p)[1] << 8) | (p)[2])
145 1.1 augustss #define GET32(p) (((p)[0] << 24) | ((p)[1] << 16) | ((p)[2] << 8) | (p)[3])
146 1.18 augustss #define GET32_LE(p) (((p)[3] << 24) | ((p)[2] << 16) | ((p)[1] << 8) | (p)[0])
147 1.1 augustss
148 1.28 christos static void __attribute__((__noreturn__))
149 1.16 augustss usage(void)
150 1.1 augustss {
151 1.28 christos fprintf(stderr, "usage: %s [-d unit] [-f file] [-l] [-m] [-p pgm] [-q] "
152 1.23 chap "[-t %%tempo] [-v] [-x] [file ...]\n",
153 1.12 cgd getprogname());
154 1.1 augustss exit(1);
155 1.1 augustss }
156 1.1 augustss
157 1.28 christos static int showmeta = 0;
158 1.28 christos static int verbose = 0;
159 1.23 chap #define BASETEMPO 400000 /* us/beat(=24 clks or qn) (150 bpm) */
160 1.28 christos static u_int tempo_set = 0;
161 1.28 christos static u_int tempo_abs = 0;
162 1.28 christos static u_int ttempo = 100;
163 1.28 christos static int unit = 0;
164 1.28 christos static int play = 1;
165 1.28 christos static int fd = -1;
166 1.28 christos static int sameprogram = 0;
167 1.28 christos static int insysex = 0;
168 1.28 christos static int svsysex = 0; /* number of sysex bytes saved internally */
169 1.1 augustss
170 1.28 christos static void
171 1.23 chap send_event(seq_event_t *ev)
172 1.1 augustss {
173 1.3 augustss /*
174 1.3 augustss printf("%02x %02x %02x %02x %02x %02x %02x %02x\n",
175 1.28 christos ev->arr[0], ev->arr[1], ev->arr[2], ev->arr[3],
176 1.3 augustss ev->arr[4], ev->arr[5], ev->arr[6], ev->arr[7]);
177 1.3 augustss */
178 1.3 augustss if (play)
179 1.3 augustss write(fd, ev, sizeof *ev);
180 1.1 augustss }
181 1.1 augustss
182 1.28 christos static u_long
183 1.16 augustss getvar(struct track *tp)
184 1.1 augustss {
185 1.1 augustss u_long r, c;
186 1.1 augustss
187 1.1 augustss r = 0;
188 1.1 augustss do {
189 1.1 augustss c = *tp->start++;
190 1.1 augustss r = (r << 7) | (c & 0x7f);
191 1.1 augustss } while ((c & 0x80) && tp->start < tp->end);
192 1.23 chap return r;
193 1.23 chap }
194 1.23 chap
195 1.28 christos static u_long
196 1.23 chap getlen(struct track *tp)
197 1.23 chap {
198 1.23 chap u_long len;
199 1.23 chap len = getvar(tp);
200 1.23 chap if (tp->start + len > tp->end)
201 1.23 chap errx(1, "bogus item length exceeds remaining track size");
202 1.23 chap return len;
203 1.1 augustss }
204 1.1 augustss
205 1.28 christos static void
206 1.16 augustss dometa(u_int meta, u_char *p, u_int len)
207 1.1 augustss {
208 1.23 chap static char const * const keys[] = {
209 1.23 chap "Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F",
210 1.23 chap "C",
211 1.23 chap "G", "D", "A", "E", "B", "F#", "C#",
212 1.23 chap "G#", "D#", "A#" /* for minors */
213 1.23 chap };
214 1.23 chap seq_event_t ev;
215 1.23 chap uint32_t usperbeat;
216 1.28 christos
217 1.1 augustss switch (meta) {
218 1.1 augustss case META_TEXT:
219 1.1 augustss case META_COPYRIGHT:
220 1.1 augustss case META_TRACK:
221 1.1 augustss case META_INSTRUMENT:
222 1.1 augustss case META_LYRIC:
223 1.1 augustss case META_MARKER:
224 1.1 augustss case META_CUE:
225 1.1 augustss if (showmeta) {
226 1.1 augustss printf("%s: ", metanames[meta]);
227 1.1 augustss fwrite(p, len, 1, stdout);
228 1.1 augustss printf("\n");
229 1.1 augustss }
230 1.1 augustss break;
231 1.1 augustss case META_SET_TEMPO:
232 1.23 chap usperbeat = GET24(p);
233 1.23 chap ev = SEQ_MK_TIMING(TEMPO,
234 1.23 chap .bpm=(60000000. / usperbeat) * (ttempo / 100.) + 0.5);
235 1.1 augustss if (showmeta)
236 1.23 chap printf("Tempo: %u us/'beat'(24 midiclks)"
237 1.23 chap " at %u%%; adjusted bpm = %u\n",
238 1.23 chap usperbeat, ttempo, ev.t_TEMPO.bpm);
239 1.23 chap if (tempo_abs)
240 1.23 chap warnx("tempo event ignored"
241 1.23 chap " in absolute-timed MIDI file");
242 1.23 chap else {
243 1.23 chap send_event(&ev);
244 1.23 chap if (!tempo_set) {
245 1.23 chap tempo_set = 1;
246 1.23 chap send_event(&SEQ_MK_TIMING(START));
247 1.23 chap }
248 1.23 chap }
249 1.1 augustss break;
250 1.1 augustss case META_TIMESIGN:
251 1.23 chap ev = SEQ_MK_TIMING(TIMESIG,
252 1.23 chap .numerator=p[0], .lg2denom=p[1],
253 1.23 chap .clks_per_click=p[2], .dsq_per_24clks=p[3]);
254 1.1 augustss if (showmeta) {
255 1.23 chap printf("Time signature: %d/%d."
256 1.23 chap " Click every %d midiclk%s"
257 1.23 chap " (24 midiclks = %d 32nd note%s)\n",
258 1.23 chap ev.t_TIMESIG.numerator,
259 1.23 chap 1 << ev.t_TIMESIG.lg2denom,
260 1.23 chap ev.t_TIMESIG.clks_per_click,
261 1.23 chap 1 == ev.t_TIMESIG.clks_per_click ? "" : "s",
262 1.23 chap ev.t_TIMESIG.dsq_per_24clks,
263 1.23 chap 1 == ev.t_TIMESIG.dsq_per_24clks ? "" : "s");
264 1.1 augustss }
265 1.23 chap /* send_event(&ev); not implemented in sequencer */
266 1.1 augustss break;
267 1.1 augustss case META_KEY:
268 1.1 augustss if (showmeta)
269 1.23 chap printf("Key: %s %s\n",
270 1.23 chap keys[((char)p[0]) + p[1] ? 10 : 7],
271 1.1 augustss p[1] ? "minor" : "major");
272 1.1 augustss break;
273 1.1 augustss default:
274 1.1 augustss break;
275 1.1 augustss }
276 1.1 augustss }
277 1.1 augustss
278 1.28 christos #if 0
279 1.28 christos static void
280 1.16 augustss midireset(void)
281 1.1 augustss {
282 1.1 augustss /* General MIDI reset sequence */
283 1.28 christos send_event(&SEQ_MK_SYSEX0(unit, 0x7e, 0x7f, 0x09, 0x01, 0xf7, 0xff));
284 1.6 augustss }
285 1.28 christos #endif
286 1.6 augustss
287 1.6 augustss #define SYSEX_CHUNK 6
288 1.28 christos static void
289 1.16 augustss send_sysex(u_char *p, u_int l)
290 1.6 augustss {
291 1.23 chap seq_event_t event;
292 1.23 chap static u_char bf[6];
293 1.28 christos
294 1.28 christos if (0 == l) {
295 1.23 chap warnx("zero-length system-exclusive event");
296 1.23 chap return;
297 1.23 chap }
298 1.28 christos
299 1.23 chap /*
300 1.23 chap * This block is needed only to handle the possibility that a sysex
301 1.23 chap * message is broken into multiple events in a MIDI file that do not
302 1.23 chap * have length six; the /dev/music sequencer assumes a sysex message is
303 1.23 chap * finished with the first SYSEX event carrying fewer than six bytes,
304 1.23 chap * even if the last is not MIDI_SYSEX_END. So, we need to be careful
305 1.23 chap * not to send a short sysex event until we have seen the end byte.
306 1.23 chap * Instead, save some straggling bytes in bf, and send when we have a
307 1.23 chap * full six (or an end byte). Note bf/saved/insysex should be per-
308 1.23 chap * device, if we supported output to more than one device at a time.
309 1.23 chap */
310 1.28 christos if (svsysex > 0) {
311 1.28 christos if (l > sizeof bf - svsysex) {
312 1.23 chap memcpy(bf + svsysex, p, sizeof bf - svsysex);
313 1.23 chap l -= sizeof bf - svsysex;
314 1.23 chap p += sizeof bf - svsysex;
315 1.28 christos send_event(&SEQ_MK_SYSEX0(unit,
316 1.28 christos bf[0], bf[1], bf[2], bf[3], bf[4], bf[5]));
317 1.23 chap svsysex = 0;
318 1.23 chap } else {
319 1.23 chap memcpy(bf + svsysex, p, l);
320 1.23 chap svsysex += l;
321 1.23 chap p += l;
322 1.28 christos if (MIDI_SYSEX_END == bf[svsysex-1]) {
323 1.23 chap event = SEQ_MK_SYSEX(unit);
324 1.23 chap memcpy(event.sysex.buffer, bf, svsysex);
325 1.23 chap send_event(&event);
326 1.23 chap svsysex = insysex = 0;
327 1.23 chap } else
328 1.23 chap insysex = 1;
329 1.23 chap return;
330 1.23 chap }
331 1.23 chap }
332 1.28 christos
333 1.23 chap /*
334 1.23 chap * l > 0. May as well test now whether we will be left 'insysex'
335 1.23 chap * after processing this event.
336 1.28 christos */
337 1.28 christos insysex = (MIDI_SYSEX_END != p[l-1]);
338 1.28 christos
339 1.23 chap /*
340 1.23 chap * If not for multi-event sysexes and chunk-size weirdness, this
341 1.23 chap * function could pretty much start here. :)
342 1.23 chap */
343 1.28 christos while (l >= SYSEX_CHUNK) {
344 1.28 christos send_event(&SEQ_MK_SYSEX0(unit, p[0], p[1], p[2], p[3], p[4], p[5]));
345 1.23 chap p += SYSEX_CHUNK;
346 1.23 chap l -= SYSEX_CHUNK;
347 1.23 chap }
348 1.28 christos if (l > 0) {
349 1.28 christos if (insysex) {
350 1.23 chap memcpy(bf, p, l);
351 1.23 chap svsysex = l;
352 1.23 chap } else { /* a <6 byte chunk is ok if it's REALLY the end */
353 1.23 chap event = SEQ_MK_SYSEX(unit);
354 1.23 chap memcpy(event.sysex.buffer, p, l);
355 1.23 chap send_event(&event);
356 1.23 chap }
357 1.23 chap }
358 1.1 augustss }
359 1.1 augustss
360 1.28 christos static void
361 1.27 lukem playfile(FILE *f, const char *name)
362 1.1 augustss {
363 1.21 itojun u_char *buf, *nbuf;
364 1.1 augustss u_int tot, n, size, nread;
365 1.1 augustss
366 1.28 christos /*
367 1.1 augustss * We need to read the whole file into memory for easy processing.
368 1.1 augustss * Using mmap() would be nice, but some file systems do not support
369 1.1 augustss * it, nor does reading from e.g. a pipe. The latter also precludes
370 1.1 augustss * finding out the file size without reading it.
371 1.1 augustss */
372 1.1 augustss size = 1000;
373 1.1 augustss buf = malloc(size);
374 1.1 augustss if (buf == 0)
375 1.17 itojun errx(1, "malloc() failed");
376 1.1 augustss nread = size;
377 1.1 augustss tot = 0;
378 1.1 augustss for (;;) {
379 1.1 augustss n = fread(buf + tot, 1, nread, f);
380 1.1 augustss tot += n;
381 1.1 augustss if (n < nread)
382 1.1 augustss break;
383 1.1 augustss /* There must be more to read. */
384 1.1 augustss nread = size;
385 1.21 itojun nbuf = realloc(buf, size * 2);
386 1.21 itojun if (nbuf == NULL)
387 1.21 itojun errx(1, "realloc() failed");
388 1.21 itojun buf = nbuf;
389 1.1 augustss size *= 2;
390 1.1 augustss }
391 1.1 augustss playdata(buf, tot, name);
392 1.1 augustss free(buf);
393 1.1 augustss }
394 1.1 augustss
395 1.28 christos static void
396 1.27 lukem playdata(u_char *buf, u_int tot, const char *name)
397 1.1 augustss {
398 1.23 chap int format, ntrks, divfmt, ticks, t;
399 1.1 augustss u_int len, mlen, status, chan;
400 1.1 augustss u_char *p, *end, byte, meta, *msg;
401 1.29 jmcneill struct synth_info info;
402 1.1 augustss struct track *tracks;
403 1.1 augustss struct track *tp;
404 1.1 augustss
405 1.29 jmcneill /* verify that the requested midi unit exists */
406 1.29 jmcneill info.device = unit;
407 1.29 jmcneill if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
408 1.29 jmcneill err(1, "ioctl(SEQUENCER_INFO) failed");
409 1.29 jmcneill
410 1.1 augustss end = buf + tot;
411 1.1 augustss if (verbose)
412 1.29 jmcneill printf("Playing %s (%d bytes) on %s (unit %d)... \n",
413 1.29 jmcneill name, tot, info.name, info.device);
414 1.1 augustss
415 1.18 augustss if (tot < MARK_LEN + 4) {
416 1.18 augustss warnx("Not a MIDI file, too short");
417 1.18 augustss return;
418 1.18 augustss }
419 1.18 augustss
420 1.18 augustss if (memcmp(buf, RMID_SIG, MARK_LEN) == 0) {
421 1.18 augustss u_char *eod;
422 1.18 augustss /* Detected a RMID file, let's just check if it's
423 1.18 augustss * a MIDI file */
424 1.27 lukem if ((u_int)GET32_LE(buf + MARK_LEN) != tot - 8) {
425 1.18 augustss warnx("Not a RMID file, bad header");
426 1.18 augustss return;
427 1.18 augustss }
428 1.18 augustss
429 1.18 augustss buf += MARK_LEN + 4;
430 1.18 augustss if (memcmp(buf, RMID_MIDI_ID, MARK_LEN) != 0) {
431 1.18 augustss warnx("Not a RMID file, bad ID");
432 1.18 augustss return;
433 1.18 augustss }
434 1.18 augustss
435 1.18 augustss /* Now look for the 'data' chunk, which contains
436 1.18 augustss * MIDI data */
437 1.18 augustss buf += MARK_LEN;
438 1.18 augustss
439 1.18 augustss /* Test against end-8 since we must have at least 8 bytes
440 1.18 augustss * left to read */
441 1.18 augustss while(buf < end-8 && memcmp(buf, RMID_DATA_ID, MARK_LEN))
442 1.18 augustss buf += GET32_LE(buf+4) + 8; /* MARK_LEN + 4 */
443 1.18 augustss
444 1.18 augustss if (buf >= end-8) {
445 1.18 augustss warnx("Not a valid RMID file, no data chunk");
446 1.18 augustss return;
447 1.18 augustss }
448 1.18 augustss
449 1.18 augustss buf += MARK_LEN; /* "data" */
450 1.18 augustss eod = buf + 4 + GET32_LE(buf);
451 1.18 augustss if (eod >= end) {
452 1.18 augustss warnx("Not a valid RMID file, bad data chunk size");
453 1.18 augustss return;
454 1.18 augustss }
455 1.18 augustss
456 1.18 augustss end = eod;
457 1.18 augustss buf += 4;
458 1.18 augustss }
459 1.18 augustss
460 1.1 augustss if (memcmp(buf, MARK_HEADER, MARK_LEN) != 0) {
461 1.17 itojun warnx("Not a MIDI file, missing header");
462 1.1 augustss return;
463 1.1 augustss }
464 1.18 augustss
465 1.1 augustss if (GET32(buf + MARK_LEN) != HEADER_LEN) {
466 1.17 itojun warnx("Not a MIDI file, bad header");
467 1.1 augustss return;
468 1.1 augustss }
469 1.1 augustss format = GET16(buf + MARK_LEN + SIZE_LEN);
470 1.1 augustss ntrks = GET16(buf + MARK_LEN + SIZE_LEN + 2);
471 1.1 augustss divfmt = GET8(buf + MARK_LEN + SIZE_LEN + 4);
472 1.1 augustss ticks = GET8(buf + MARK_LEN + SIZE_LEN + 5);
473 1.1 augustss p = buf + MARK_LEN + SIZE_LEN + HEADER_LEN;
474 1.23 chap /*
475 1.23 chap * Set the timebase (or timebase and tempo, for absolute-timed files).
476 1.23 chap * PORTABILITY: some sequencers actually check the timebase against
477 1.23 chap * available timing sources and may adjust it accordingly (storing a
478 1.23 chap * new value in the ioctl arg) which would require us to compensate
479 1.23 chap * somehow. That possibility is ignored for now, as NetBSD's sequencer
480 1.23 chap * currently synthesizes all timebases, for better or worse, from the
481 1.23 chap * system clock.
482 1.23 chap *
483 1.23 chap * For a non-absolute file, if timebase is set to the file's divisions
484 1.23 chap * value, and tempo set in the obvious way, then the timing deltas in
485 1.23 chap * the MTrks require no scaling. A downside to this approach is that
486 1.23 chap * the sequencer API wants tempo in (integer) beats per minute, which
487 1.23 chap * limits how finely tempo can be specified. That might be got around
488 1.23 chap * in some cases by frobbing tempo and timebase more obscurely, but this
489 1.23 chap * player is meant to be simple and clear.
490 1.23 chap */
491 1.23 chap if ((divfmt & 0x80) == 0) {
492 1.1 augustss ticks |= divfmt << 8;
493 1.23 chap if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &(int){ticks}) < 0)
494 1.23 chap err(1, "SEQUENCER_TMR_TIMEBASE");
495 1.23 chap } else {
496 1.23 chap tempo_abs = tempo_set = 1;
497 1.23 chap divfmt = -(int8_t)divfmt;
498 1.23 chap /*
499 1.23 chap * divfmt is frames per second; multiplying by 60 to set tempo
500 1.23 chap * in frames per minute could exceed sequencer's (arbitrary)
501 1.23 chap * tempo limits, so factor 60 as 12*5, set tempo in frames per
502 1.23 chap * 12 seconds, and account for the 5 in timebase.
503 1.23 chap */
504 1.23 chap send_event(&SEQ_MK_TIMING(TEMPO,
505 1.23 chap .bpm=(12*divfmt) * (ttempo/100.) + 0.5));
506 1.23 chap if (ioctl(fd, SEQUENCER_TMR_TIMEBASE, &(int){5*ticks}) < 0)
507 1.23 chap err(1, "SEQUENCER_TMR_TIMEBASE");
508 1.23 chap }
509 1.1 augustss if (verbose > 1)
510 1.23 chap printf(tempo_abs ?
511 1.23 chap "format=%d ntrks=%d abs fps=%u subdivs=%u\n" :
512 1.23 chap "format=%d ntrks=%d divisions=%u\n",
513 1.23 chap format, ntrks, tempo_abs ? divfmt : ticks, ticks);
514 1.1 augustss if (format != 0 && format != 1) {
515 1.17 itojun warnx("Cannot play MIDI file of type %d", format);
516 1.1 augustss return;
517 1.1 augustss }
518 1.1 augustss if (ntrks == 0)
519 1.1 augustss return;
520 1.1 augustss tracks = malloc(ntrks * sizeof(struct track));
521 1.1 augustss if (tracks == NULL)
522 1.17 itojun errx(1, "malloc() tracks failed");
523 1.28 christos for (t = 0; t < ntrks;) {
524 1.1 augustss if (p >= end - MARK_LEN - SIZE_LEN) {
525 1.17 itojun warnx("Cannot find track %d", t);
526 1.6 augustss goto ret;
527 1.1 augustss }
528 1.1 augustss len = GET32(p + MARK_LEN);
529 1.1 augustss if (len > 1000000) { /* a safe guard */
530 1.17 itojun warnx("Crazy track length");
531 1.6 augustss goto ret;
532 1.1 augustss }
533 1.1 augustss if (memcmp(p, MARK_TRACK, MARK_LEN) == 0) {
534 1.1 augustss tracks[t].start = p + MARK_LEN + SIZE_LEN;
535 1.1 augustss tracks[t].end = tracks[t].start + len;
536 1.23 chap tracks[t].delta = getvar(&tracks[t]);
537 1.23 chap tracks[t].indirect = &tracks[t]; /* -> self for now */
538 1.1 augustss t++;
539 1.1 augustss }
540 1.1 augustss p += MARK_LEN + SIZE_LEN + len;
541 1.1 augustss }
542 1.1 augustss
543 1.23 chap /*
544 1.23 chap * Force every channel to the same patch if requested by the user.
545 1.1 augustss */
546 1.11 augustss if (sameprogram) {
547 1.11 augustss for(t = 0; t < 16; t++) {
548 1.23 chap send_event(&SEQ_MK_CHN(PGM_CHANGE, .device=unit,
549 1.23 chap .channel=t, .program=sameprogram-1));
550 1.10 augustss }
551 1.10 augustss }
552 1.28 christos /*
553 1.23 chap * Play MIDI events by selecting the track with the lowest
554 1.23 chap * delta. Execute the event, update the delta and repeat.
555 1.23 chap *
556 1.23 chap * The ticks variable is the number of ticks that make up a beat
557 1.23 chap * (beat: 24 MIDI clocks always, a quarter note by usual convention)
558 1.23 chap * and is used as a reference value for the delays between
559 1.1 augustss * the MIDI events.
560 1.1 augustss */
561 1.23 chap BuildHeap(tracks, ntrks); /* tracks[0].indirect is always next */
562 1.1 augustss for (;;) {
563 1.23 chap tp = tracks[0].indirect;
564 1.23 chap if ((verbose > 2 && tp->delta > 0) || verbose > 3) {
565 1.25 he printf("DELAY %4ld TRACK %2td%s",
566 1.25 he tp->delta, tp - tracks, verbose>3?" ":"\n");
567 1.1 augustss fflush(stdout);
568 1.1 augustss }
569 1.23 chap if (tp->delta > 0) {
570 1.23 chap if (!tempo_set) {
571 1.23 chap if (verbose || showmeta)
572 1.23 chap printf("No initial tempo;"
573 1.23 chap " defaulting:\n");
574 1.23 chap dometa(META_SET_TEMPO, (u_char[]){
575 1.23 chap BASETEMPO >> 16,
576 1.23 chap (BASETEMPO >> 8) & 0xff,
577 1.23 chap BASETEMPO & 0xff},
578 1.23 chap 3);
579 1.1 augustss }
580 1.23 chap send_event(&SEQ_MK_TIMING(WAIT_REL,
581 1.23 chap .divisions=tp->delta));
582 1.1 augustss }
583 1.1 augustss byte = *tp->start++;
584 1.1 augustss if (byte == MIDI_META) {
585 1.1 augustss meta = *tp->start++;
586 1.23 chap mlen = getlen(tp);
587 1.23 chap if (verbose > 3)
588 1.1 augustss printf("META %02x (%d)\n", meta, mlen);
589 1.1 augustss dometa(meta, tp->start, mlen);
590 1.1 augustss tp->start += mlen;
591 1.1 augustss } else {
592 1.1 augustss if (MIDI_IS_STATUS(byte))
593 1.1 augustss tp->status = byte;
594 1.4 augustss else
595 1.4 augustss tp->start--;
596 1.1 augustss mlen = MIDI_LENGTH(tp->status);
597 1.3 augustss msg = tp->start;
598 1.23 chap if (verbose > 3) {
599 1.3 augustss if (mlen == 1)
600 1.3 augustss printf("MIDI %02x (%d) %02x\n",
601 1.3 augustss tp->status, mlen, msg[0]);
602 1.28 christos else
603 1.3 augustss printf("MIDI %02x (%d) %02x %02x\n",
604 1.3 augustss tp->status, mlen, msg[0], msg[1]);
605 1.3 augustss }
606 1.23 chap if (insysex && tp->status != MIDI_SYSEX_END) {
607 1.23 chap warnx("incomplete system exclusive message"
608 1.23 chap " aborted");
609 1.23 chap svsysex = insysex = 0;
610 1.23 chap }
611 1.1 augustss status = MIDI_GET_STATUS(tp->status);
612 1.1 augustss chan = MIDI_GET_CHAN(tp->status);
613 1.1 augustss switch (status) {
614 1.1 augustss case MIDI_NOTEOFF:
615 1.23 chap send_event(&SEQ_MK_CHN(NOTEOFF, .device=unit,
616 1.23 chap .channel=chan, .key=msg[0], .velocity=msg[1]));
617 1.23 chap break;
618 1.1 augustss case MIDI_NOTEON:
619 1.23 chap send_event(&SEQ_MK_CHN(NOTEON, .device=unit,
620 1.23 chap .channel=chan, .key=msg[0], .velocity=msg[1]));
621 1.23 chap break;
622 1.1 augustss case MIDI_KEY_PRESSURE:
623 1.23 chap send_event(&SEQ_MK_CHN(KEY_PRESSURE,
624 1.23 chap .device=unit, .channel=chan,
625 1.23 chap .key=msg[0], .pressure=msg[1]));
626 1.1 augustss break;
627 1.1 augustss case MIDI_CTL_CHANGE:
628 1.23 chap send_event(&SEQ_MK_CHN(CTL_CHANGE,
629 1.23 chap .device=unit, .channel=chan,
630 1.23 chap .controller=msg[0], .value=msg[1]));
631 1.1 augustss break;
632 1.1 augustss case MIDI_PGM_CHANGE:
633 1.23 chap if (!sameprogram)
634 1.23 chap send_event(&SEQ_MK_CHN(PGM_CHANGE,
635 1.23 chap .device=unit, .channel=chan,
636 1.23 chap .program=msg[0]));
637 1.23 chap break;
638 1.1 augustss case MIDI_CHN_PRESSURE:
639 1.23 chap send_event(&SEQ_MK_CHN(CHN_PRESSURE,
640 1.23 chap .device=unit, .channel=chan, .pressure=msg[0]));
641 1.1 augustss break;
642 1.1 augustss case MIDI_PITCH_BEND:
643 1.23 chap send_event(&SEQ_MK_CHN(PITCH_BEND,
644 1.23 chap .device=unit, .channel=chan,
645 1.23 chap .value=(msg[0] & 0x7f) | ((msg[1] & 0x7f)<<7)));
646 1.1 augustss break;
647 1.6 augustss case MIDI_SYSTEM_PREFIX:
648 1.23 chap mlen = getlen(tp);
649 1.23 chap if (tp->status == MIDI_SYSEX_START) {
650 1.6 augustss send_sysex(tp->start, mlen);
651 1.23 chap break;
652 1.23 chap } else if (tp->status == MIDI_SYSEX_END) {
653 1.23 chap /* SMF uses SYSEX_END as CONTINUATION/ESCAPE */
654 1.23 chap if (insysex) { /* CONTINUATION */
655 1.23 chap send_sysex(tp->start, mlen);
656 1.23 chap } else { /* ESCAPE */
657 1.28 christos for (; mlen > 0 ; -- mlen) {
658 1.23 chap send_event(
659 1.23 chap &SEQ_MK_EVENT(putc,
660 1.23 chap SEQOLD_MIDIPUTC,
661 1.23 chap .device=unit,
662 1.23 chap .byte=*(tp->start++)
663 1.28 christos ));
664 1.23 chap }
665 1.23 chap }
666 1.23 chap break;
667 1.23 chap }
668 1.23 chap /* Sorry, can't do this yet; FALLTHROUGH */
669 1.3 augustss default:
670 1.3 augustss if (verbose)
671 1.3 augustss printf("MIDI event 0x%02x ignored\n",
672 1.3 augustss tp->status);
673 1.1 augustss }
674 1.1 augustss tp->start += mlen;
675 1.1 augustss }
676 1.23 chap if (tp->start >= tp->end) {
677 1.23 chap ntrks = ShrinkHeap(tracks, ntrks); /* track gone */
678 1.23 chap if (0 == ntrks)
679 1.23 chap break;
680 1.23 chap } else
681 1.23 chap tp->delta = getvar(tp);
682 1.23 chap Heapify(tracks, ntrks, 0);
683 1.1 augustss }
684 1.6 augustss if (ioctl(fd, SEQUENCER_SYNC, 0) < 0)
685 1.6 augustss err(1, "SEQUENCER_SYNC");
686 1.1 augustss
687 1.6 augustss ret:
688 1.1 augustss free(tracks);
689 1.1 augustss }
690 1.1 augustss
691 1.29 jmcneill static int
692 1.29 jmcneill parse_unit(const char *sunit)
693 1.29 jmcneill {
694 1.29 jmcneill const char *osunit = sunit;
695 1.29 jmcneill long n;
696 1.29 jmcneill char *ep;
697 1.29 jmcneill
698 1.29 jmcneill if (strncmp(sunit, "midi", strlen("midi")) == 0)
699 1.29 jmcneill sunit += strlen("midi");
700 1.29 jmcneill
701 1.29 jmcneill errno = 0;
702 1.29 jmcneill n = strtol(sunit, &ep, 10);
703 1.29 jmcneill if (n < 0 || n > INT_MAX || *ep != '\0' ||
704 1.29 jmcneill (errno == ERANGE &&
705 1.29 jmcneill (n == LONG_MAX || n == LONG_MIN)))
706 1.29 jmcneill errx(1, "bad midi unit -- %s", osunit);
707 1.29 jmcneill
708 1.29 jmcneill return (int)n;
709 1.29 jmcneill }
710 1.29 jmcneill
711 1.1 augustss int
712 1.16 augustss main(int argc, char **argv)
713 1.1 augustss {
714 1.1 augustss int ch;
715 1.1 augustss int listdevs = 0;
716 1.1 augustss int example = 0;
717 1.1 augustss int nmidi;
718 1.16 augustss const char *file = DEVMUSIC;
719 1.16 augustss const char *sunit;
720 1.1 augustss struct synth_info info;
721 1.1 augustss FILE *f;
722 1.16 augustss
723 1.16 augustss if ((sunit = getenv("MIDIUNIT")))
724 1.29 jmcneill unit = parse_unit(sunit);
725 1.1 augustss
726 1.10 augustss while ((ch = getopt(argc, argv, "?d:f:lmp:qt:vx")) != -1) {
727 1.1 augustss switch(ch) {
728 1.1 augustss case 'd':
729 1.29 jmcneill unit = parse_unit(optarg);
730 1.1 augustss break;
731 1.1 augustss case 'f':
732 1.1 augustss file = optarg;
733 1.1 augustss break;
734 1.1 augustss case 'l':
735 1.1 augustss listdevs++;
736 1.1 augustss break;
737 1.1 augustss case 'm':
738 1.1 augustss showmeta++;
739 1.10 augustss break;
740 1.10 augustss case 'p':
741 1.10 augustss sameprogram = atoi(optarg);
742 1.3 augustss break;
743 1.3 augustss case 'q':
744 1.3 augustss play = 0;
745 1.1 augustss break;
746 1.1 augustss case 't':
747 1.2 augustss ttempo = atoi(optarg);
748 1.1 augustss break;
749 1.1 augustss case 'v':
750 1.1 augustss verbose++;
751 1.1 augustss break;
752 1.1 augustss case 'x':
753 1.1 augustss example++;
754 1.1 augustss break;
755 1.1 augustss case '?':
756 1.1 augustss default:
757 1.1 augustss usage();
758 1.1 augustss }
759 1.1 augustss }
760 1.1 augustss argc -= optind;
761 1.1 augustss argv += optind;
762 1.28 christos
763 1.15 augustss if (!play)
764 1.15 augustss goto output;
765 1.15 augustss
766 1.1 augustss fd = open(file, O_WRONLY);
767 1.1 augustss if (fd < 0)
768 1.1 augustss err(1, "%s", file);
769 1.1 augustss if (ioctl(fd, SEQUENCER_NRMIDIS, &nmidi) < 0)
770 1.1 augustss err(1, "ioctl(SEQUENCER_NRMIDIS) failed, ");
771 1.1 augustss if (nmidi == 0)
772 1.17 itojun errx(1, "Sorry, no MIDI devices available");
773 1.1 augustss if (listdevs) {
774 1.1 augustss for (info.device = 0; info.device < nmidi; info.device++) {
775 1.1 augustss if (ioctl(fd, SEQUENCER_INFO, &info) < 0)
776 1.1 augustss err(1, "ioctl(SEQUENCER_INFO) failed, ");
777 1.1 augustss printf("%d: %s\n", info.device, info.name);
778 1.1 augustss }
779 1.1 augustss exit(0);
780 1.1 augustss }
781 1.9 augustss
782 1.15 augustss output:
783 1.1 augustss if (example)
784 1.9 augustss while (example--)
785 1.9 augustss playdata(sample, sizeof sample, "<Gubben Noa>");
786 1.1 augustss else if (argc == 0)
787 1.1 augustss playfile(stdin, "<stdin>");
788 1.1 augustss else
789 1.1 augustss while (argc--) {
790 1.1 augustss f = fopen(*argv, "r");
791 1.1 augustss if (f == NULL)
792 1.1 augustss err(1, "%s", *argv);
793 1.1 augustss else {
794 1.1 augustss playfile(f, *argv);
795 1.1 augustss fclose(f);
796 1.1 augustss }
797 1.1 augustss argv++;
798 1.1 augustss }
799 1.1 augustss
800 1.1 augustss exit(0);
801 1.1 augustss }
802 1.23 chap
803 1.23 chap /*
804 1.23 chap * relative-time priority queue (min-heap). Properties:
805 1.23 chap * 1. The delta time at a node is relative to the node's parent's time.
806 1.23 chap * 2. When an event is dequeued from a track, the delta time of the new head
807 1.23 chap * event is relative to the time of the event just dequeued.
808 1.23 chap * Therefore:
809 1.23 chap * 3. After dequeueing the head event from the track at heap root, the next
810 1.23 chap * event's time is directly comparable to the root's children.
811 1.23 chap * These properties allow the heap to be maintained with delta times throughout.
812 1.23 chap * Insert is also implementable, but not needed: all the tracks are present
813 1.23 chap * at first; they just go away as they end.
814 1.23 chap */
815 1.23 chap
816 1.28 christos #define PARENT(i) ((i - 1) >> 1)
817 1.28 christos #define LEFT(i) ((i << 1) + 1)
818 1.28 christos #define RIGHT(i) ((i + 1) << 1)
819 1.23 chap #define DTIME(i) (t[i].indirect->delta)
820 1.28 christos #define SWAP(i, j) do { \
821 1.23 chap struct track *_t = t[i].indirect; \
822 1.23 chap t[i].indirect = t[j].indirect; \
823 1.23 chap t[j].indirect = _t; \
824 1.28 christos } while (/*CONSTCOND*/ 0)
825 1.23 chap
826 1.28 christos static void
827 1.23 chap Heapify(struct track *t, int ntrks, int node)
828 1.23 chap {
829 1.23 chap int lc, rc, mn;
830 1.28 christos
831 1.23 chap lc = LEFT(node);
832 1.23 chap rc = RIGHT(node);
833 1.28 christos
834 1.23 chap if (rc >= ntrks) { /* no right child */
835 1.23 chap if (lc >= ntrks) /* node is a leaf */
836 1.23 chap return;
837 1.23 chap if (DTIME(node) > DTIME(lc))
838 1.28 christos SWAP(node, lc);
839 1.23 chap DTIME(lc) -= DTIME(node);
840 1.23 chap return; /* no rc ==> lc is a leaf */
841 1.23 chap }
842 1.23 chap
843 1.23 chap mn = lc;
844 1.23 chap if (DTIME(lc) > DTIME(rc))
845 1.23 chap mn = rc;
846 1.23 chap if (DTIME(node) <= DTIME(mn)) {
847 1.23 chap DTIME(rc) -= DTIME(node);
848 1.23 chap DTIME(lc) -= DTIME(node);
849 1.23 chap return;
850 1.23 chap }
851 1.28 christos
852 1.28 christos SWAP(node, mn);
853 1.23 chap DTIME(rc) -= DTIME(node);
854 1.23 chap DTIME(lc) -= DTIME(node);
855 1.23 chap Heapify(t, ntrks, mn); /* gcc groks tail recursion */
856 1.23 chap }
857 1.23 chap
858 1.28 christos static void
859 1.23 chap BuildHeap(struct track *t, int ntrks)
860 1.23 chap {
861 1.23 chap int node;
862 1.28 christos
863 1.28 christos for (node = PARENT(ntrks - 1); node --> 0;)
864 1.23 chap Heapify(t, ntrks, node);
865 1.23 chap }
866 1.23 chap
867 1.23 chap /*
868 1.23 chap * Make the heap 1 item smaller by discarding the track at the root. Move the
869 1.23 chap * rightmost bottom-level leaf to the root and decrement ntrks. It remains to
870 1.23 chap * run Heapify, which the caller is expected to do. Returns the new ntrks.
871 1.23 chap */
872 1.28 christos static int
873 1.23 chap ShrinkHeap(struct track *t, int ntrks)
874 1.23 chap {
875 1.23 chap int ancest;
876 1.28 christos
877 1.28 christos --ntrks;
878 1.28 christos for (ancest = PARENT(ntrks); ancest > 0; ancest = PARENT(ancest))
879 1.23 chap DTIME(ntrks) += DTIME(ancest);
880 1.23 chap t[0].indirect = t[ntrks].indirect;
881 1.23 chap return ntrks;
882 1.23 chap }
883