選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

992 行
37KB

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