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