Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

976 lines
38KB

  1. /*********************************************************************************
  2. *
  3. * MIDITONES
  4. *
  5. * Convert a MIDI file into a bytestream of notes
  6. *
  7. *
  8. * (C) Copyright 2011, Len Shustek
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of version 3 of the GNU General Public License as
  12. * published by the Free Software Foundation at http://www.gnu.org/licenses,
  13. * with Additional Permissions under term 7(b) that the original copyright
  14. * notice and author attibution must be preserved and under term 7(c) that
  15. * modified versions be marked as different from the original.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. ***********************************************************************************/
  23. /*
  24. * Change log
  25. * 19 January 2011, L.Shustek, V1.0
  26. * -Initial release.
  27. * 26 February 2011, L. Shustek, V1.1
  28. * -Expand the documentation generated in the output file.
  29. * -End the binary output file with an "end of score" command.
  30. * -Fix bug: Some "stop note" commands were generated too early.
  31. * 04 March 2011, L. Shustek, V1.2
  32. * -Minor error message rewording.
  33. * 13 June 2011, L. Shustek, V1.3
  34. * -Add -s2 strategy to try to keep each track on its own tone generator
  35. * for when there are separate speakers. This obviously works only when
  36. * each track is monophonic. (Suggested by Michal Pustejovsky)
  37. * 20 November 2011, L. Shustek, V1.4
  38. * -Add -cn option to mask which channels (tracks) to process
  39. * -Add -kn option to change key
  40. * Both of these are in support of music-playing on my Tesla Coil.
  41. * 05 December 2011, L. Shustek, V1.5
  42. * -Fix command line parsing error for option -s1
  43. * -Display the commandline in the C file output
  44. * -Change to decimal instead of hex for note numbers in the C file output
  45. * 06 August 2013, L. Shustek, V1.6
  46. * -Changed to allow compilation and execution in 64-bit environments
  47. * by using C99 standard intN_t and uintN_t types for MIDI structures,
  48. * and formatting specifications like "PRId32" instead of "ld".
  49. */
  50. // Sept 2014 - Add option for velocity output
  51. #define VERSION "1.6"
  52. /*--------------------------------------------------------------------------------
  53. *
  54. *
  55. * About MIDITONES
  56. *
  57. *
  58. * MIDITONES converts a MIDI music file into a much simplified stream of commands,
  59. * so that a version of the music can be played on a synthesizer having only
  60. * tone generators without any volume or tone controls.
  61. *
  62. * Volume ("velocity") and instrument specifications in the MIDI files are discarded.
  63. * All the tracks are prcoessed and merged into a single time-ordered stream of
  64. * "note on", "note off", and "delay" commands.
  65. *
  66. * This was written for the "Playtune" Arduino library, which plays polyphonic music
  67. * using up to 6 tone generators run by the timers on the processor. See the separate
  68. * documentation for Playtune. But MIDITONES may prove useful for other tone
  69. * generating systems.
  70. *
  71. * The output can be either a C-language source code fragment that initializes an
  72. * array with the command bytestream, or a binary file with the bytestream itself.
  73. *
  74. * MIDITONES is written in standard ANSI C (plus strlcpy and strlcat functions), and
  75. * is meant to be executed from the command line. There is no GUI interface.
  76. *
  77. * The MIDI file format is complicated, and this has not been tested on a very
  78. * wide variety of file types. In particular, we have tested only format type "1",
  79. * which seems to be what most of them are. Let me know if you find MIDI files
  80. * that it won't digest and I'll see if I can fix it.
  81. * This has been tested only on a little-endian PC, but I think it should work on
  82. * big-endian processors too. Note that the MIDI file format is inherently
  83. * big-endian.
  84. *
  85. *
  86. * ***** The command line *****
  87. *
  88. * To convert a MIDI file called "chopin.mid" into a command bytestream, execute
  89. *
  90. * miditones chopin
  91. *
  92. * It will create a file in the same directory called "chopin.c" which contains
  93. * the C-language statement to intiialize an array called "score" with the bytestream.
  94. *
  95. *
  96. * The general form for command line execution is this:
  97. *
  98. * miditones [-p] [-lg] [-lp] [-s1] [-tn] [-b] [-cn] [-kn] <basefilename>
  99. *
  100. * The <basefilename> is the base name, without an extension, for the input and
  101. * output files. It can contain directory path information, or not.
  102. *
  103. * The input file is the base name with the extension ".mid". The output filename(s)
  104. * are the base name with ".c", ".bin", and/or ".log" extensions.
  105. *
  106. *
  107. * The following command-line options can be specified:
  108. *
  109. * -p Only parse the MIDI file; don't generate an output file.
  110. * Tracks are processed sequentially instead of being merged into chronological order.
  111. * This is mostly useful when generating a log to debug MIDI file parsing problems.
  112. *
  113. * -lp Log input file parsing information to the <basefilename>.log file
  114. *
  115. * -lg Log output bytestream generation information to the <basefilename>.log file
  116. *
  117. * -sn Use bytestream generation strategy "n".
  118. * Two strategies are currently implemented:
  119. * 1: favor track 1 notes instead of all tracks equally
  120. * 2: try to keep each track to its own tone generator
  121. *
  122. * -tn Generate the bytestream so that at most n tone generators are used.
  123. * The default is 6 tone generators, and the maximum is 16.
  124. * The program will report how many notes had to be discarded because there
  125. * weren't enough tone generators. Note that for the Arduino Playtunes
  126. * library, it's ok to have the bytestream use more tone genreators than
  127. * exist on your processor because any extra notes will be ignored, although
  128. * it does make the file bigger than necessary . Of course, too many ignored
  129. * notes will make the music sound really strange!
  130. *
  131. * -b Generate a binary file with the name <basefilename>.bin, instead of a
  132. * C-language source file with the name <basefilename>.c.
  133. *
  134. * -cn Only process the channel numbers whose bits are on in the number "n".
  135. * For example, -c3 means "only process channels 0 and 1"
  136. *
  137. * -kn Change the musical key of the output by n chromatic notes.
  138. * -k-12 goes one octave down, -k12 goes one octave up, etc.
  139. *
  140. * -v Add velocity information to output
  141. *
  142. *
  143. * ***** The score bytestream *****
  144. *
  145. * The generated bytestream is a series of commands that turn notes on and off, and
  146. * start delays until the next note change. Here are the details, with numbers
  147. * shown in hexadecimal.
  148. *
  149. * If the high-order bit of the byte is 1, then it is one of the following commands:
  150. *
  151. * 9t nn Start playing note nn on tone generator t. Generators are numbered
  152. * starting with 0. The notes numbers are the MIDI numbers for the chromatic
  153. * scale, with decimal 60 being Middle C, and decimal 69 being Middle A (440 Hz).
  154. *
  155. * 8t Stop playing the note on tone generator t.
  156. *
  157. * F0 End of score: stop playing.
  158. *
  159. * E0 End of score: start playing again from the beginning.
  160. * (Shown for completeness; MIDITONES won't generate this.)
  161. *
  162. * If the high-order bit of the byte is 0, it is a command to delay for a while until
  163. * the next note change.. The other 7 bits and the 8 bits of the following byte are
  164. * interpreted as a 15-bit big-endian integer that is the number of milliseconds to
  165. * wait before processing the next command. For example,
  166. *
  167. * 07 D0
  168. *
  169. * would cause a delay of 0x07d0 = 2000 decimal millisconds, or 2 seconds. Any tones
  170. * that were playing before the delay command will continue to play.
  171. *
  172. *
  173. * Len Shustek, 4 Feb 2011
  174. *
  175. *----------------------------------------------------------------------------------*/
  176. #include <stdio.h>
  177. #include <stdlib.h>
  178. #include <string.h>
  179. #include <ctype.h>
  180. #include <stdbool.h>
  181. #include <time.h>
  182. #include <inttypes.h>
  183. /*********** MIDI file header formats *****************/
  184. struct midi_header {
  185. int8_t MThd[4];
  186. uint32_t header_size;
  187. uint16_t format_type;
  188. uint16_t number_of_tracks;
  189. uint16_t time_division;
  190. };
  191. struct track_header {
  192. int8_t MTrk[4];
  193. uint32_t track_size;
  194. };
  195. /*********** Global variables ******************/
  196. #define MAX_TONEGENS 16 /* max tone generators: tones we can play simultaneously */
  197. #define DEFAULT_TONEGENS 6 /* default number of tone generators */
  198. #define MAX_TRACKS 24 /* max number of MIDI tracks we will process */
  199. bool loggen, logparse, parseonly, strategy1, strategy2, binaryoutput, velocityoutput;
  200. FILE *infile, *outfile, *logfile;
  201. uint8_t *buffer, *hdrptr;
  202. unsigned long buflen;
  203. int num_tracks;
  204. int tracks_done = 0;
  205. int outfile_itemcount = 0;
  206. int num_tonegens = DEFAULT_TONEGENS;
  207. int num_tonegens_used = 0;
  208. unsigned channel_mask = 0xffff; // bit mask of channels to process
  209. int keyshift = 0; // optional chromatic note shift for output file
  210. long int outfile_bytecount = 0;
  211. unsigned int ticks_per_beat = 240;
  212. unsigned long timenow = 0;
  213. unsigned long tempo; /* current tempo in usec/qnote */
  214. struct tonegen_status { /* current status of a tone generator */
  215. bool playing; /* is it playing? */
  216. int track; /* if so, which track is the note from? */
  217. int note; /* what note is playing? */
  218. }
  219. tonegen [MAX_TONEGENS] = {
  220. {0}};
  221. struct track_status { /* current processing point of a MIDI track */
  222. uint8_t *trkptr; /* ptr to the next note change */
  223. uint8_t *trkend; /* ptr past the end of the track */
  224. unsigned long time; /* what time we're at in the score */
  225. unsigned long tempo; /* the tempo last set, in usec/qnote */
  226. unsigned int preferred_tonegen; /* for strategy2: try to use this generator */
  227. unsigned char cmd; /* CMD_xxxx next to do */
  228. unsigned char note; /* for which note */
  229. unsigned char velocity;
  230. unsigned char last_event; /* the last event, for MIDI's "running status" */
  231. bool tonegens[MAX_TONEGENS];/* which tone generators our notes are playing on */
  232. }
  233. track[MAX_TRACKS] = {
  234. {0}};
  235. /* output bytestream commands, which are also stored in track_status.cmd */
  236. #define CMD_PLAYNOTE 0x90 /* play a note: low nibble is generator #, note is next byte */
  237. #define CMD_STOPNOTE 0x80 /* stop a note: low nibble is generator # */
  238. #define CMD_RESTART 0xe0 /* restart the score from the beginning */
  239. #define CMD_STOP 0xf0 /* stop playing */
  240. /* if CMD < 0x80, then the other 7 bits and the next byte are a 15-bit number of msec to delay */
  241. /* these other commands stored in the track_status.com */
  242. #define CMD_TEMPO 0xFE /* tempo in usec per quarter note ("beat") */
  243. #define CMD_TRACKDONE 0xFF /* no more data left in this track */
  244. /************** command-line processing *******************/
  245. void SayUsage(char *programName){
  246. static char *usage[] = {
  247. "Convert MIDI files to an Arduino PLAYTUNE bytestream",
  248. "miditones [-p] [-lg] [-lp] [-s1] [-tn] <basefilename>",
  249. " -p parse only, don't generate bytestream",
  250. " -lp log input parsing",
  251. " -lg log output generation",
  252. " -s1 strategy 1: favor track 1",
  253. " -s2 strategy 2: try to assign tracks to specific tone generators",
  254. " -tn use at most n tone generators (default is 6, max is 16)",
  255. " -b binary file output instead of C source text",
  256. " -cn mask for which tracks to process, e.g. -c3 for only 0 and 1",
  257. " -kn key shift in chromatic notes, positive or negative",
  258. "input file: <basefilename>.mid",
  259. "output file: <basefilename>.bin or .c",
  260. "log file: <basefilename>.log",
  261. "" };
  262. int i=0;
  263. while (usage[i][0] != '\0') fprintf(stderr, "%s\n", usage[i++]);
  264. }
  265. int HandleOptions(int argc,char *argv[]) {
  266. /* returns the index of the first argument that is not an option; i.e.
  267. does not start with a dash or a slash*/
  268. int i,firstnonoption=0;
  269. /* --- The following skeleton comes from C:\lcc\lib\wizard\textmode.tpl. */
  270. for (i=1; i< argc;i++) {
  271. if (argv[i][0] == '/' || argv[i][0] == '-') {
  272. switch (toupper(argv[i][1])) {
  273. case 'H':
  274. case '?':
  275. SayUsage(argv[0]);
  276. exit(1);
  277. case 'L':
  278. if (toupper(argv[i][2]) == 'G') loggen = true;
  279. else if (toupper(argv[i][2]) == 'P') logparse = true;
  280. else goto opterror;
  281. break;
  282. case 'P':
  283. parseonly = true;
  284. break;
  285. case 'B':
  286. binaryoutput = true;
  287. break;
  288. case 'V':
  289. velocityoutput = true;
  290. break;
  291. case 'S':
  292. if (argv[i][2] == '1') strategy1 = true;
  293. else if (argv[i][2] == '2') strategy2 = true;
  294. else goto opterror;
  295. break;
  296. case 'T':
  297. if (sscanf(&argv[i][2],"%d",&num_tonegens) != 1 || num_tonegens <1 || num_tonegens > MAX_TONEGENS) goto opterror;
  298. printf("Using %d tone generators.\n", num_tonegens);
  299. break;
  300. case 'C':
  301. if (sscanf(&argv[i][2],"%d",&channel_mask) != 1 || channel_mask > 0xffff) goto opterror;
  302. printf("Channel (track) mask is %04X.\n", channel_mask);
  303. break;
  304. case 'K':
  305. if (sscanf(&argv[i][2],"%d",&keyshift) != 1 || keyshift < -100 || keyshift > 100) goto opterror;
  306. printf("Using keyshift %d.\n", keyshift);
  307. break;
  308. /* add more option switches here */
  309. opterror:
  310. default:
  311. fprintf(stderr,"unknown option: %s\n",argv[i]);
  312. SayUsage(argv[0]);
  313. exit(4);
  314. }
  315. }
  316. else {
  317. firstnonoption = i;
  318. break;
  319. }
  320. }
  321. return firstnonoption;
  322. }
  323. void print_command_line (int argc,char *argv[]) {
  324. int i;
  325. fprintf(outfile, "// command line: ");
  326. for (i=0; i< argc; i++) fprintf(outfile,"%s ",argv[i]);
  327. fprintf(outfile, "\n");
  328. }
  329. /**************** utility routines **********************/
  330. size_t strlcat (char *dst, const char *src, size_t siz)
  331. {
  332. char *d = dst;
  333. const char *s = src;
  334. size_t n = siz;
  335. size_t dlen;
  336. /* Find the end of dst and adjust bytes left but don't go past end */
  337. while (n-- != 0 && *d != '\0')
  338. d++;
  339. dlen = d - dst;
  340. n = siz - dlen;
  341. if (n == 0)
  342. return (dlen + strlen(s));
  343. while (*s != '\0') {
  344. if (n != 1) {
  345. *d++ = *s;
  346. n--;
  347. }
  348. s++;
  349. }
  350. *d = '\0';
  351. return (dlen + (s - src)); /* count does not include NUL */
  352. }
  353. size_t strlcpy(char *dst, const char *src, size_t siz)
  354. {
  355. char *d = dst;
  356. const char *s = src;
  357. size_t n = siz;
  358. /* Copy as many bytes as will fit */
  359. if (n != 0) {
  360. while (--n != 0) {
  361. if ((*d++ = *s++) == '\0') break;
  362. }
  363. }
  364. /* Not enough room in dst, add NUL and traverse rest of src */
  365. if (n == 0) {
  366. if (siz != 0)
  367. *d = '\0'; /* NUL-terminate dst */
  368. while (*s++)
  369. ;
  370. }
  371. return (s - src - 1); /* count does not include NUL */
  372. }
  373. /* match a constant character sequence */
  374. int charcmp (const char *buf, const char *match) {
  375. int len, i;
  376. len = strlen (match);
  377. for (i=0; i<len; ++i)
  378. if (buf[i] != match[i]) return 0;
  379. return 1;
  380. }
  381. /* announce a fatal MIDI file format error */
  382. void midi_error (char *msg, unsigned char *bufptr) {
  383. unsigned char *ptr;
  384. fprintf(stderr, "---> MIDI file error at position %04X (%d): %s\n", (uint16_t)(bufptr-buffer), (uint16_t)(bufptr-buffer), msg);
  385. /* print some bytes surrounding the error */
  386. ptr = bufptr - 16;
  387. if (ptr < buffer) ptr = buffer;
  388. for (; ptr <= bufptr+16 && ptr < buffer+buflen; ++ptr) fprintf (stderr, ptr==bufptr ? " [%02X] ":"%02X ", *ptr);
  389. fprintf(stderr, "\n");
  390. exit(8);
  391. }
  392. /* check that we have a specified number of bytes left in the buffer */
  393. void chk_bufdata(unsigned char *ptr, int len) {
  394. if (ptr + len - buffer > buflen) midi_error("data missing", ptr);
  395. }
  396. /* fetch big-endian numbers */
  397. uint16_t rev_short (uint16_t val) {
  398. return ((val&0xff)<<8) | ((val>>8)&0xff);
  399. }
  400. uint32_t rev_long (uint32_t val){
  401. return (((rev_short((uint16_t)val) & 0xffff) << 16) |
  402. (rev_short((uint16_t)(val >> 16)) & 0xffff));
  403. }
  404. /* account for new items in the non-binary output file
  405. and generate a newline every so often. */
  406. void outfile_items (int n) {
  407. outfile_bytecount += n;
  408. outfile_itemcount += n;
  409. if (!binaryoutput && outfile_itemcount > 20) {
  410. fprintf (outfile, "\n");
  411. outfile_itemcount = 0;
  412. }
  413. }
  414. /************** process the MIDI file header *****************/
  415. void process_header (void) {
  416. struct midi_header *hdr;
  417. unsigned int time_division;
  418. chk_bufdata(hdrptr, sizeof(struct midi_header));
  419. hdr = (struct midi_header *) hdrptr;
  420. if (!charcmp((char *)(hdr->MThd),"MThd")) midi_error("Missing 'MThd'", hdrptr);
  421. num_tracks = rev_short(hdr->number_of_tracks);
  422. time_division = rev_short(hdr->time_division);
  423. if (time_division < 0x8000) ticks_per_beat = time_division;
  424. else ticks_per_beat = ((time_division >> 8) & 0x7f) /* SMTE frames/sec */ * (time_division & 0xff); /* ticks/SMTE frame */
  425. if (logparse) {
  426. fprintf (logfile, "Header size %" PRId32 "\n", rev_long(hdr->header_size));
  427. fprintf (logfile, "Format type %d\n", rev_short(hdr->format_type));
  428. fprintf (logfile, "Number of tracks %d\n", num_tracks);
  429. fprintf (logfile, "Time division %04X\n", time_division);
  430. fprintf (logfile, "Ticks/beat = %d\n", ticks_per_beat);
  431. }
  432. hdrptr += rev_long(hdr->header_size) + 8; /* point past header to track header, presumably. */
  433. return;
  434. }
  435. /**************** Process a MIDI track header *******************/
  436. void start_track (int tracknum) {
  437. struct track_header *hdr;
  438. unsigned long tracklen;
  439. chk_bufdata(hdrptr, sizeof(struct track_header));
  440. hdr = (struct track_header *) hdrptr;
  441. if (!charcmp((char *)(hdr->MTrk),"MTrk")) midi_error("Missing 'MTrk'", hdrptr);
  442. tracklen = rev_long(hdr->track_size);
  443. if (logparse) fprintf (logfile, "\nTrack %d length %ld\n", tracknum, tracklen);
  444. hdrptr += sizeof (struct track_header); /* point past header */
  445. chk_bufdata(hdrptr, tracklen);
  446. track[tracknum].trkptr = hdrptr;
  447. hdrptr += tracklen; /* point to the start of the next track */
  448. track[tracknum].trkend = hdrptr; /* the point past the end of the track */
  449. }
  450. /* Get a MIDI-style variable-length integer */
  451. unsigned long get_varlen (uint8_t **ptr) {
  452. /* Get a 1-4 byte variable-length value and adjust the pointer past it.
  453. These are a succession of 7-bit values with a MSB bit of zero marking the end */
  454. unsigned long val;
  455. int i, byte;
  456. val = 0;
  457. for (i=0; i<4; ++i){
  458. byte = *(*ptr)++;
  459. val = (val<<7) | (byte&0x7f);
  460. if (!(byte&0x80)) return val;
  461. }
  462. return val;
  463. }
  464. /*************** Process the MIDI track data ***************************/
  465. /* Skip in the track for the next "note on", "note off" or "set tempo" command,
  466. then record that information in the track status block and return. */
  467. void find_note (int tracknum) {
  468. unsigned long int delta_time;
  469. int event, chan;
  470. int i;
  471. int note, velocity; // , parm;
  472. int meta_cmd, meta_length;
  473. unsigned long int sysex_length;
  474. struct track_status *t;
  475. /* process events */
  476. t = &track[tracknum]; /* our track status structure */
  477. while (t->trkptr < t->trkend) {
  478. delta_time = get_varlen(&t->trkptr);
  479. if (logparse) {
  480. fprintf (logfile, "trk %d ", tracknum);
  481. fprintf (logfile, delta_time ? "delta time %4ld, " : " ", delta_time);
  482. }
  483. t->time += delta_time;
  484. if (*t->trkptr < 0x80) /* "running status" */ event = t->last_event;/* means same event as before */
  485. else { /* new "status" (event type) */
  486. event = *t->trkptr++;
  487. t->last_event = event;
  488. }
  489. if (event == 0xff) { /* meta-event */
  490. meta_cmd = *t->trkptr++;
  491. meta_length = *t->trkptr++;
  492. switch (meta_cmd) {
  493. case 0x2f:
  494. if (logparse) fprintf(logfile, "end of track\n");
  495. break;
  496. case 0x00:
  497. if (logparse) fprintf(logfile, "sequence number %d\n", rev_short(*(unsigned short *)t->trkptr));
  498. break;
  499. case 0x20:
  500. if (logparse) fprintf(logfile, "channel prefix %d\n", *t->trkptr);
  501. break;
  502. case 0x51: /* tempo: 3 byte big-endian integer! */
  503. t->cmd = CMD_TEMPO;
  504. t->tempo = rev_long(*(unsigned long *)(t->trkptr-1)) & 0xffffffL;
  505. if (logparse) fprintf(logfile, "set tempo %ld usec/qnote\n", t->tempo);
  506. t->trkptr += meta_length;
  507. return;
  508. case 0x54:
  509. if (logparse) fprintf(logfile, "SMPTE offset %08" PRIx32 "\n", rev_long(*(unsigned long *)t->trkptr));
  510. break;
  511. case 0x58:
  512. if (logparse) fprintf(logfile, "time signature %08" PRIx32 "\n", rev_long(*(unsigned long *)t->trkptr));
  513. break;
  514. case 0x59:
  515. if (logparse) fprintf(logfile, "key signature %04X\n", rev_short(*(unsigned short *)t->trkptr));
  516. break;
  517. default: /* assume it is a string */
  518. if (logparse) {
  519. fprintf(logfile, "meta cmd %02X, length %d, \"", meta_cmd, meta_length);
  520. for (i=0; i<meta_length; ++i) {
  521. int ch = t->trkptr[i];
  522. fprintf(logfile, "%c", isprint(ch) ? ch : '?');
  523. }
  524. fprintf(logfile, "\"\n");
  525. }
  526. if (tracknum==0 && meta_cmd==0x03 && !parseonly && !binaryoutput) {
  527. /* Incredibly, MIDI has no standard for recording the name of the piece!
  528. Track 0's "trackname" (meta 0x03) is sometimes used for that, so
  529. we output it to the C file as documentation. */
  530. fprintf(outfile, "// ");
  531. for (i=0; i<meta_length; ++i) {
  532. int ch = t->trkptr[i];
  533. fprintf(outfile, "%c", isprint(ch) ? ch : '?');
  534. }
  535. fprintf(outfile, "\n");
  536. }
  537. break;
  538. }
  539. t->trkptr += meta_length;
  540. }
  541. else if (event <0x80) midi_error("Unknown MIDI event type", t->trkptr);
  542. else {
  543. chan = event & 0xf;
  544. switch (event>>4) {
  545. case 0x8:
  546. t->note = *t->trkptr++;
  547. velocity = *t->trkptr++;
  548. note_off:
  549. if (logparse) fprintf (logfile, "note %02X off, chan %d, velocity %d\n", t->note, chan, velocity);
  550. if ((1<<chan) & channel_mask) { // if we're processing this channel
  551. t->cmd = CMD_STOPNOTE;
  552. return; /* stop processing and return */
  553. }
  554. break; // else keep looking
  555. case 0x9:
  556. t->note = *t->trkptr++;
  557. velocity = *t->trkptr++;
  558. if (velocity == 0) /* some scores use note-on with zero velocity for off! */ goto note_off;
  559. t->velocity = velocity;
  560. if (logparse) fprintf (logfile, "note %02X on, chan %d, velocity %d\n", t->note, chan, velocity);
  561. if ((1<<chan) & channel_mask) { // if we're processing this channel
  562. t->cmd = CMD_PLAYNOTE;
  563. return; /* stop processing and return */
  564. }
  565. break; // else keep looking
  566. case 0xa:
  567. note = *t->trkptr++;
  568. velocity = *t->trkptr++;
  569. if (logparse) fprintf (logfile, "after-touch %02X, %02X\n", note, velocity);
  570. break;
  571. case 0xb:
  572. note = *t->trkptr++;
  573. velocity = *t->trkptr++;
  574. if (logparse) fprintf (logfile, "control change %02X, %02X\n", note, velocity);
  575. break;
  576. case 0xc:
  577. note = *t->trkptr++;
  578. if (logparse) fprintf(logfile, "program patch %02X\n", note);
  579. break;
  580. case 0xd:
  581. chan = *t->trkptr++;
  582. if (logparse) fprintf(logfile, "channel after-touch %02X\n", chan);
  583. break;
  584. case 0xe:
  585. note = *t->trkptr++;
  586. velocity = *t->trkptr++;
  587. if (logparse) fprintf(logfile, "pitch wheel change %02X, %02X\n", note, velocity);
  588. break;
  589. case 0xf:
  590. sysex_length = get_varlen(&t->trkptr);
  591. if (logparse) fprintf(logfile, "SysEx event %02X, %ld bytes\n", event, sysex_length);
  592. t->trkptr += sysex_length;
  593. break;
  594. default:
  595. midi_error("Unknown MIDI command", t->trkptr);
  596. }
  597. }
  598. }
  599. t->cmd = CMD_TRACKDONE; /* no more notes to process */
  600. ++tracks_done;
  601. }
  602. /********************* main ****************************/
  603. int main(int argc,char *argv[]) {
  604. int argno;
  605. char *filebasename;
  606. #define MAXPATH 120
  607. char filename[MAXPATH];
  608. //int i;
  609. int tracknum;
  610. int earliest_tracknum;
  611. unsigned long earliest_time;
  612. int notes_skipped = 0;
  613. printf("MIDITONES V%s, (C) 2011 Len Shustek\n", VERSION);
  614. printf("See the source code for license information.\n\n");
  615. if (argc == 1) { /* no arguments */
  616. SayUsage(argv[0]);
  617. return 1;
  618. }
  619. /* process options */
  620. argno = HandleOptions(argc,argv);
  621. filebasename = argv[argno];
  622. /* Open the log file */
  623. if (logparse || loggen) {
  624. strlcpy(filename, filebasename, MAXPATH);
  625. strlcat(filename, ".log", MAXPATH);
  626. logfile = fopen(filename, "w");
  627. if (!logfile) {
  628. fprintf(stderr, "Unable to open log file %s", filename);
  629. return 1;
  630. }
  631. }
  632. /* Open the input file */
  633. strlcpy(filename, filebasename, MAXPATH);
  634. strlcat(filename, ".mid", MAXPATH);
  635. infile = fopen(filename, "rb");
  636. if (!infile) {
  637. fprintf(stderr, "Unable to open input file %s", filename);
  638. return 1;
  639. }
  640. /* Read the whole input file into memory */
  641. fseek(infile, 0, SEEK_END); /* find file size */
  642. buflen = ftell(infile);
  643. fseek(infile, 0, SEEK_SET);
  644. buffer = (unsigned char *) malloc (buflen+1);
  645. if (!buffer) {
  646. fprintf(stderr, "Unable to allocate %ld bytes for the file", buflen);
  647. return 1;
  648. }
  649. fread(buffer, buflen, 1, infile);
  650. fclose(infile);
  651. if (logparse) fprintf(logfile, "Processing %s, %ld bytes\n", filename, buflen);
  652. /* Create the output file */
  653. if (!parseonly) {
  654. strlcpy(filename, filebasename, MAXPATH);
  655. if (binaryoutput) {
  656. strlcat(filename, ".bin", MAXPATH);
  657. outfile = fopen(filename, "wb");
  658. }
  659. else {
  660. strlcat(filename, ".c", MAXPATH);
  661. outfile = fopen(filename, "w");
  662. }
  663. if (!outfile) {
  664. fprintf(stderr, "Unable to open output file %s", filename);
  665. return 1;
  666. }
  667. if (!binaryoutput) { /* create header of C file that initializes score data */
  668. time_t rawtime;
  669. //struct tm *ptime;
  670. time (&rawtime);
  671. fprintf(outfile, "// Playtune bytestream for file \"%s.mid\" ", filebasename);
  672. fprintf(outfile, "created by MIDITONES V%s on %s", VERSION, asctime(localtime(&rawtime)));
  673. print_command_line(argc,argv);
  674. if (channel_mask != 0xffff)
  675. fprintf(outfile, "// Only the masked channels were processed: %04X\n", channel_mask);
  676. if (keyshift != 0)
  677. fprintf(outfile, "// Keyshift was %d chromatic notes\n", keyshift);
  678. fprintf(outfile, "#ifdef __AVR__\n");
  679. fprintf(outfile, "#include <avr/pgmspace.h>\n");
  680. fprintf(outfile, "#else\n");
  681. fprintf(outfile, "#define PROGMEM\n");
  682. fprintf(outfile, "#endif\n");
  683. fprintf(outfile, "const unsigned char PROGMEM score [] = {\n");
  684. }
  685. }
  686. /* process the MIDI file header */
  687. hdrptr = buffer; /* pointer to file and track headers */
  688. process_header ();
  689. printf (" Processing %d tracks.\n", num_tracks);
  690. if (num_tracks > MAX_TRACKS) midi_error ("Too many tracks", buffer);
  691. /* initialize processing of all the tracks */
  692. for (tracknum=0; tracknum < num_tracks; ++tracknum) {
  693. start_track (tracknum); /* process the track header */
  694. find_note (tracknum); /* position to the first note on/off */
  695. /* if we are in "parse only" mode, do the whole track,
  696. so we do them one at a time instead of time-synchronized. */
  697. if (parseonly) while (track[tracknum].cmd != CMD_TRACKDONE) find_note(tracknum);
  698. }
  699. /* Continue processing all tracks, in an order based on the simulated time.
  700. This is not unlike multiway merging used for tape sorting algoritms in the 50's! */
  701. tracknum = 0;
  702. if (!parseonly) do { /* while there are still track notes to process */
  703. struct track_status *trk;
  704. struct tonegen_status *tg;
  705. int tgnum;
  706. int count_tracks;
  707. unsigned long delta_time, delta_msec;
  708. /* Find the track with the earliest event time,
  709. and output a delay command if time has advanced.
  710. A potential improvement: If there are multiple tracks with the same time,
  711. first do the ones with STOPNOTE as the next command, if any. That would
  712. help avoid running out of tone generators. In practice, though, most MIDI
  713. files do all the STOPNOTEs first anyway, so it won't have much effect.
  714. */
  715. earliest_time = 0x7fffffff;
  716. /* Usually we start with the track after the one we did last time (tracknum),
  717. so that if we run out of tone generators, we have been fair to all the tracks.
  718. The alternate "strategy1" says we always start with track 0, which means
  719. that we favor early tracks over later ones when there aren't enough tone generators.
  720. */
  721. count_tracks = num_tracks;
  722. if (strategy1) tracknum = num_tracks; /* beyond the end, so we start with track 0 */
  723. do {
  724. if (++tracknum >= num_tracks) tracknum=0;
  725. trk = &track[tracknum];
  726. if (trk->cmd != CMD_TRACKDONE && trk->time < earliest_time) {
  727. earliest_time = trk->time;
  728. earliest_tracknum = tracknum;
  729. }
  730. }
  731. while (--count_tracks);
  732. tracknum = earliest_tracknum; /* the track we picked */
  733. trk = &track[tracknum];
  734. if (loggen) fprintf (logfile, "Earliest time is trk %d, time %ld\n", tracknum, earliest_time);
  735. if (earliest_time < timenow) midi_error ("INTERNAL: time went backwards", trk->trkptr);
  736. /* If time has advanced, output a "delay" command */
  737. delta_time = earliest_time - timenow;
  738. if (delta_time) {
  739. /* Convert ticks to milliseconds based on the current tempo */
  740. delta_msec = ((unsigned long) delta_time * tempo) / ticks_per_beat / 1000;
  741. if (loggen) fprintf (logfile, "->Delay %ld msec (%ld ticks)\n", delta_msec, delta_time);
  742. if (delta_msec > 0x7fff) midi_error ("INTERNAL: time delta too big", trk->trkptr);
  743. /* output a 15-bit delay in big-endian format */
  744. if (binaryoutput) {
  745. putc ((unsigned char) (delta_msec >> 8), outfile);
  746. putc ((unsigned char) (delta_msec & 0xff), outfile);
  747. outfile_bytecount += 2;
  748. }
  749. else {
  750. fprintf (outfile, "%ld,%ld, ", delta_msec >> 8, delta_msec & 0xff);
  751. outfile_items(2);
  752. }
  753. }
  754. timenow = earliest_time;
  755. /* If this track event is "set tempo", just change the global tempo.
  756. That affects how we generate "delay" commands. */
  757. if (trk->cmd == CMD_TEMPO) {
  758. tempo = trk->tempo;
  759. if (loggen) fprintf (logfile, "Tempo changed to %ld usec/qnote\n", tempo);
  760. find_note (tracknum);
  761. }
  762. /* If this track event is "stop note", process it and all subsequent "stop notes" for this track
  763. that are happening at the same time. Doing so frees up as many tone generators as possible. */
  764. else if (trk->cmd == CMD_STOPNOTE) do {
  765. // stop a note
  766. for (tgnum=0; tgnum < num_tonegens; ++tgnum) { /* find which generator is playing it */
  767. tg = &tonegen[tgnum];
  768. if (tg->playing && tg->track == tracknum && tg->note == trk->note) {
  769. if (loggen) fprintf (logfile, "->Stop note %02X, generator %d, track %d\n", tg->note, tgnum, tracknum);
  770. if (binaryoutput) {
  771. putc (CMD_STOPNOTE | tgnum, outfile);
  772. outfile_bytecount += 1;
  773. }
  774. else {
  775. fprintf (outfile, "0x%02X, ", CMD_STOPNOTE | tgnum);
  776. outfile_items (1);
  777. }
  778. tg->playing = false;
  779. trk->tonegens[tgnum] = false;
  780. }
  781. }
  782. find_note (tracknum); // use up the note
  783. }
  784. while (trk->cmd == CMD_STOPNOTE && trk->time == timenow);
  785. /* If this track event is "start note", process only it.
  786. Don't do more than one, so we allow other tracks their chance at grabbing tone generators. */
  787. else if (trk->cmd == CMD_PLAYNOTE) {
  788. bool foundgen = false;
  789. if (strategy2) { /* try to use the same tone generator this track used last time */
  790. tg = &tonegen [trk->preferred_tonegen];
  791. if (!tg->playing) {
  792. tgnum = trk->preferred_tonegen;
  793. foundgen = true;
  794. }
  795. }
  796. if (!foundgen) for (tgnum=0; tgnum < num_tonegens; ++tgnum) { /* search for a free tone generator */
  797. tg = &tonegen[tgnum];
  798. if (!tg->playing) {
  799. foundgen = true;
  800. break;
  801. }
  802. }
  803. if (foundgen) {
  804. int shifted_note;
  805. if (tgnum+1 > num_tonegens_used) num_tonegens_used = tgnum+1;
  806. tg->playing = true;
  807. tg->track = tracknum;
  808. tg->note = trk->note;
  809. trk->tonegens[tgnum] = true;
  810. trk->preferred_tonegen = tgnum;
  811. if (loggen) fprintf (logfile, "->Start note %02X, generator %d, track %d\n", trk->note, tgnum, tracknum);
  812. shifted_note = trk->note + keyshift;
  813. if (shifted_note < 0) shifted_note = 0;
  814. if (shifted_note > 127) shifted_note = 127;
  815. if (binaryoutput) {
  816. putc (CMD_PLAYNOTE | tgnum, outfile);
  817. putc (shifted_note, outfile);
  818. outfile_bytecount += 2;
  819. if (velocityoutput) {
  820. putc (shifted_note, outfile);
  821. outfile_bytecount++;
  822. }
  823. }
  824. else {
  825. if (velocityoutput == 0) {
  826. fprintf (outfile, "0x%02X,%d, ", CMD_PLAYNOTE | tgnum, shifted_note);
  827. outfile_items(2);
  828. } else {
  829. fprintf (outfile, "0x%02X,%d,%d, ", CMD_PLAYNOTE | tgnum, shifted_note, trk->velocity);
  830. outfile_items(3);
  831. }
  832. }
  833. }
  834. else {
  835. if (loggen) fprintf (logfile, "----> No free generator, skipping note %02X, track %d\n", trk->note, tracknum);
  836. ++notes_skipped;
  837. }
  838. find_note (tracknum); // use up the note
  839. }
  840. } /* !parseonly do */
  841. while (tracks_done < num_tracks);
  842. if (!parseonly) {
  843. // generate the end-of-score command and some commentary
  844. if(binaryoutput) putc(CMD_STOP, outfile);
  845. else {
  846. fprintf(outfile, "0x%02x};\n// This score contains %ld bytes, and %d tone generator%s used.\n", CMD_STOP, outfile_bytecount, num_tonegens_used, num_tonegens_used == 1 ? " is" : "s are");
  847. if (notes_skipped) fprintf(outfile, "// %d notes had to be skipped.\n", notes_skipped);
  848. }
  849. printf (" %s %d tone generators were used.\n", num_tonegens_used < num_tonegens ? "Only":"All", num_tonegens_used);
  850. if (notes_skipped) printf(" %d notes were skipped because there weren't enough tone generators.\n", notes_skipped);
  851. printf (" %ld bytes of score data were generated.\n", outfile_bytecount);
  852. }
  853. printf (" Done.\n");
  854. return 0;
  855. }