-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmidi2mod.c
More file actions
498 lines (435 loc) · 14.9 KB
/
midi2mod.c
File metadata and controls
498 lines (435 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "midi_file.h"
#include "mod_file.h"
#include "mod_period_table.h"
struct MIDI_INFO {
struct MIDI_DATA *midi;
uint32_t tempo;
};
struct OPTIONS {
const char *in_filename;
const char *out_filename;
uint8_t tracks[4];
int generate_sample_len;
int change_pitch;
};
struct CALC_MIDI_STATS {
struct MIDI_INFO *info;
uint32_t time_gcd;
uint32_t last_note_time;
};
struct FILL_MOD_PATTERN {
struct CALC_MIDI_STATS *stats;
struct MOD_DATA *mod;
struct OPTIONS *opt;
int channel;
};
typedef void (*midi_event_callback)(struct MIDI_EVENT *ev, uint32_t time, void *data);
static void print_help(const char *progname)
{
printf("USAGE: %s [options] in_file.midi out_file.mod\n", progname);
printf("\n");
printf("options:\n");
printf(" -h show this help\n");
printf(" -tracks 2,3,4,5 select MIDI tracks to include\n");
printf(" -sample-len 16384 generate sample of given length\n");
printf(" -pitch 12 change pitch (in semitones)\n");
}
static int opt_read_int(char *progname, char *name, char *val, int min, int max, int *set_val)
{
if (val == NULL || *val == '\0') {
fprintf(stderr, "%s: value expected for option '%s'\n", progname, name);
return 1;
}
char *end = NULL;
int read_val = (int) strtoul(val, &end, 0);
if (*end != '\0') {
fprintf(stderr, "%s: invalid sample length '%s'\n", progname, val);
return 1;
}
if (read_val < min) {
fprintf(stderr, "%s: value for '%s' too small, must be >= %d\n", progname, name, min);
return 1;
}
if (read_val > max) {
fprintf(stderr, "%s: value for '%s' too large, must be <= %d\n", progname, name, max);
return 1;
}
*set_val = (int) read_val;
return 0;
}
static int opt_read_track_list(struct OPTIONS *opt, char *progname, char *name, char *val)
{
if (val == NULL) {
fprintf(stderr, "%s: value expected for option '%s'\n", progname, name);
return 1;
}
char *pos = val;
int next_track = 0;
while (1) {
if (next_track > (int)(sizeof(opt->tracks)/sizeof(*opt->tracks))) {
fprintf(stderr, "%s: too many tracks in '%s' (max %d)\n", progname, val, (int) (sizeof(opt->tracks)/sizeof(*opt->tracks)));
}
char *end = NULL;
unsigned long n = strtoul(pos, &end, 10);
if (n > 0xff) {
fprintf(stderr, "%s: invalid track number: %lu\n", progname, n);
return 1;
}
opt->tracks[next_track++] = n;
if (*end == '\0') break;
if (*end != ',') {
fprintf(stderr, "%s: invalid track number in '%s'\n", progname, val);
return 1;
}
pos = end + 1; // skip ','
}
return 0;
}
static int read_options(int argc, char **argv, struct OPTIONS *opt)
{
opt->in_filename = NULL;
opt->out_filename = NULL;
opt->change_pitch = 0;
opt->generate_sample_len = 0;
memset(opt->tracks, 0xff, sizeof(opt->tracks));
for (int i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
if (opt->in_filename == NULL) {
opt->in_filename = argv[i];
continue;
}
if (opt->out_filename == NULL) {
opt->out_filename = argv[i];
continue;
}
fprintf(stderr, "%s: invalid option '%s'\n", argv[0], argv[i]);
return 1;
}
if (strcmp(argv[i], "-h") == 0) {
print_help(argv[0]);
return 1;
}
if (strcmp(argv[i], "-tracks") == 0) {
if (opt_read_track_list(opt, argv[0], argv[i], argv[i+1]) != 0) {
return 1;
}
i++;
continue;
}
if (strcmp(argv[i], "-sample-len") == 0) {
if (opt_read_int(argv[0], argv[i], argv[i+1], 2, 2*0xffff, &opt->generate_sample_len) != 0) {
return 1;
}
i++;
continue;
}
if (strcmp(argv[i], "-pitch") == 0) {
if (opt_read_int(argv[0], argv[i], argv[i+1], -5*12, 5*12, &opt->change_pitch) != 0) {
return 1;
}
i++;
continue;
}
fprintf(stderr, "%s: invalid option '%s'\n", argv[0], argv[i]);
return 1;
}
if (opt->in_filename == NULL || opt->out_filename == NULL) {
printf("%s: no files specified! (use -h for help)\n", argv[0]);
return 1;
}
return 0;
}
static int midi_note_to_mod_period(int note)
{
if (note > 2*12) {
note -= 2*12;
} else {
note = 0;
}
if (note >= (int) (sizeof(period_table)/sizeof(*period_table))) {
note = (int) (sizeof(period_table)/sizeof(*period_table)) - 1;
}
return period_table[note];
}
static struct MIDI_INFO get_midi_info(struct MIDI_DATA *midi)
{
struct MIDI_INFO info = {
.midi = midi,
.tempo = 1000000,
};
for (int t = 0; t < midi->n_tracks; t++) {
struct MIDI_TRACK *track = &midi->tracks[t];
uint32_t cur_time = 0;
for (int e = 0; e < track->n_events; e++) {
struct MIDI_EVENT *ev = &track->events[e];
cur_time += ev->delta_time;
if (ev->type == MIDI_EVENT_TYPE_META && ev->meta.meta_type == 0x51) {
info.tempo = ((ev->meta.short_data.data[0]<<16) |
(ev->meta.short_data.data[1]<< 8) |
(ev->meta.short_data.data[2]<< 0));
}
}
}
return info;
}
#if 0
static const char *human_note(int note)
{
static const char *note_names[] = {
"C", "C#", "D", "D#", "E", "F",
"F#", "G", "G#", "A", "A#", "B",
};
static char buf[256];
if (note < 12) {
snprintf(buf, sizeof(buf), "%-2s!", note_names[note%12]);
} else {
note -= 12;
snprintf(buf, sizeof(buf), "%-2s%d", note_names[note%12], note/12);
}
return buf;
}
static const char *human_time(struct MIDI_INFO *info, uint32_t time)
{
uint32_t seconds = (uint32_t) ((int64_t)time * info->tempo / info->midi->ticks_per_beat / 1000000);
uint32_t sec = seconds;
int hr = sec / 3600;
sec %= 3600;
int min = sec / 60;
sec %= 60;
static char buf[256];
snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hr, min, sec);
return buf;
}
#endif
static void traverse_midi_note_events(struct MIDI_TRACK *track, struct MIDI_INFO *info, int include_note_off,
midi_event_callback callback, void *data)
{
uint8_t chan_last_note[16];
memset(chan_last_note, 0xff, sizeof(chan_last_note));
uint32_t cur_time = 0;
for (int e = 0; e < track->n_events; e++) {
struct MIDI_EVENT *ev = &track->events[e];
cur_time += ev->delta_time;
#if 0
printf("[0x%08x] <%s> ", cur_time, human_time(info, cur_time));
switch (ev->type) {
case MIDI_EVENT_TYPE_SYSEX: printf("sysex 0x%02x\n", ev->sysex.sysex_type); break;
case MIDI_EVENT_TYPE_META: printf("meta 0x%02x\n", ev->meta.meta_type); break;
case MIDI_EVENT_TYPE_MIDI:
printf("midi 0x%02x ", ev->midi.status);
switch (ev->midi.status & 0xf0) {
case 0xa0: printf("(aftertouch note=%3d, value=%3d)\n", ev->midi.data1, ev->midi.data2); break;
case 0xb0: printf("(control change controller=%3d, value=%3d)\n", ev->midi.data1, ev->midi.data2); break;
case 0xc0: printf("(program change %3d)\n", ev->midi.data1); break;
case 0xe0: printf("(pitch bend %5d)\n", (int16_t) (ev->midi.data1 | (ev->midi.data2<<8))); break;
default: printf("0x%02x 0x%02x\n", ev->midi.data1, ev->midi.data2); break;
}
break;
}
#else
(void) info;
#endif
if (ev->type == MIDI_EVENT_TYPE_MIDI) {
uint8_t type = ev->midi.status & 0xf0;
uint8_t chan = ev->midi.status & 0x0f;
if (type == 0x80 || (type == 0x90 && ev->midi.data2 == 0)) {
chan_last_note[chan] = 0xff;
if (include_note_off) {
callback(ev, cur_time, data);
}
continue;
}
if (type == 0x90 && ev->midi.data1 != chan_last_note[chan]) {
chan_last_note[chan] = ev->midi.data1;
callback(ev, cur_time, data);
}
}
}
}
static uint32_t calc_gcd(uint32_t a, uint32_t b)
{
while (a != 0) {
uint32_t t = a;
a = b % a;
b = t;
}
return b;
}
static void calc_midi_stats(struct MIDI_EVENT *ev, uint32_t time, void *data)
{
struct CALC_MIDI_STATS *stats = data;
#if 0
printf("[%s] <%u> chan=%2d, note=%3d, vel=%3d (%s)\n",
human_time(stats->info, time),
time,
ev->midi.status & 0x0f,
ev->midi.data1,
ev->midi.data2,
human_note(ev->midi.data1));
#else
(void) ev;
#endif
if (stats->last_note_time < time) {
stats->last_note_time = time;
}
stats->time_gcd = calc_gcd(stats->time_gcd, time);
}
static void fill_mod_pattern(struct MIDI_EVENT *ev, uint32_t time, void *data)
{
struct FILL_MOD_PATTERN *fill = data;
int row = time / fill->stats->time_gcd;
struct MOD_CELL *cell = (struct MOD_CELL *) &fill->mod->pattern[fill->mod->num_channels * row + fill->channel];
if ((ev->midi.status & 0xf0) == 0x80 || ((ev->midi.status & 0xf0) == 0x90 && ev->midi.data2 == 0)) {
// note off
if (cell->sample == 0) {
//cell->sample = 1;
//cell->effect = 0xc00;
}
} else {
// note on
cell->sample = 1;
cell->period = midi_note_to_mod_period(ev->midi.data1 + fill->opt->change_pitch);
cell->effect = 0;
}
}
static int make_mod_sample(struct MOD_SAMPLE *spl, int num_samples)
{
const int ref_frequency = 8287;
const double pi = atan(1.0) * 4.0;
int len = (num_samples == 0) ? ref_frequency : num_samples;
int8_t *samples = malloc(len);
if (samples == NULL) return 1;
double freq = 440.0 / pow(2.0, 9.0/12.0); // C is 9 half-steps down from A
double omega = 2.0 * pi / ref_frequency;
for (int i = 0; i < len; i++) {
samples[i] = (int8_t) (127.0 * sin(freq * i * omega) * exp(-3.0 * (i+1) / ref_frequency));
}
// remove samples from the end until we change sign:
for (int i = 0; i < len-1; i++) {
if ((samples[len-1-(i+1)] < 0) && (samples[len-1-i] >= 0)) {
len -= i;
break;
}
}
// find loop start spot:
int loop_start = 7*len/8;
for (int i = loop_start; i < len; i++) {
if ((samples[i] < 0) && (samples[i+1] >= 0)) {
loop_start = i;
break;
}
}
spl->len = len;
spl->loop_start = loop_start;
spl->loop_len = spl->len - spl->loop_start - 1;
spl->finetune = 0;
spl->volume = 63;
spl->data = samples;
return 0;
}
static struct MOD_FILE *make_mod_from_midi(struct MIDI_DATA *midi, struct OPTIONS *opt)
{
// if no tracks are specified, use the first ones in order
if (opt->tracks[0] == 0xff) {
for (int i = 0; i < midi->n_tracks; i++) {
opt->tracks[i] = i;
}
}
int track_indices[sizeof(opt->tracks)/sizeof(*opt->tracks)+1];
for (int i = 0; i < (int) (sizeof(opt->tracks)/sizeof(*opt->tracks)); i++) {
track_indices[i] = (opt->tracks[i] == 0xff) ? -1 : opt->tracks[i];
}
track_indices[sizeof(track_indices)/sizeof(*track_indices)-1] = -1;
struct MIDI_INFO info = get_midi_info(midi);
// find the greatest time divisor common for midi events;
// this is what we'll use for the spacing between MOD rows
struct CALC_MIDI_STATS stats = {
.info = &info,
.time_gcd = 0,
.last_note_time = 0,
};
for (int i = 0; track_indices[i] >= 0; i++) {
struct MIDI_TRACK *track = &midi->tracks[track_indices[i]];
traverse_midi_note_events(track, &info, 0, calc_midi_stats, &stats);
}
int num_rows = (stats.last_note_time/stats.time_gcd + 1) + 3; // 3 extra rows for fading out
int num_patterns = (num_rows + 63) / 64;
if (num_patterns > 128) {
fprintf(stderr, "ERROR: song is too long\n");
return NULL;
}
struct MOD_FILE *mod_file = mod_file_new();
if (mod_file == NULL) {
fprintf(stderr, "ERROR: out of memory for mod data\n");
return NULL;
}
snprintf(mod_file->title, sizeof(mod_file->title), "Test MOD file");
snprintf(mod_file->samples[0].name, sizeof(mod_file->samples[0].name), "Converted by midi2mod");
struct MOD_DATA *mod = &mod_file->mod;
// make samples
if (make_mod_sample(&mod->samples[0], opt->generate_sample_len) != 0) {
fprintf(stderr, "ERROR: out of memory for mod samples\n");
return NULL;
}
// fill song positions
mod->num_song_positions = num_patterns;
for (int i = 0; i < num_patterns; i++) {
mod->song_positions[i] = i;
}
// place notes in the patterns
mod->num_channels = 4;
mod->num_patterns = num_patterns;
mod->pattern = malloc(sizeof(struct MOD_CELL) * mod->num_patterns * 64 * mod->num_channels);
struct FILL_MOD_PATTERN fill = {
.stats = &stats,
.mod = mod,
.opt = opt,
};
for (int i = 0; track_indices[i] >= 0; i++) {
struct MIDI_TRACK *track = &midi->tracks[track_indices[i]];
fill.channel = i;
printf("-> converting channel %d\n", fill.channel);
traverse_midi_note_events(track, &info, 1, fill_mod_pattern, &fill);
}
// set MOD tempo (effect 0xf)
int bpm = (int) (60000000 / info.tempo);
int val = midi->ticks_per_beat / bpm * 3/2; // this calculation is iffy
if (val > 31) val = 31;
printf("-> using MOD tempo %d (%d bpm)\n", val, bpm);
((struct MOD_CELL *) &mod->pattern[0])->effect = 0xf00 | val;
// fade out
struct MOD_CELL *fade_rows = ((struct MOD_CELL *) &mod->pattern[(num_rows-2)*mod->num_channels]);
for (int i = 0; i < mod->num_channels; i++) {
fade_rows->effect = 0xc00; // set volume = 0
fade_rows++;
}
fade_rows->effect = 0xd00; // jump to next pattern (end)
return mod_file;
}
int main(int argc, char *argv[])
{
struct OPTIONS options;
if (read_options(argc, argv, &options) != 0) {
return 1;
}
struct MIDI_DATA *midi = midi_file_read(options.in_filename);
if (midi == NULL) {
fprintf(stderr, "%s: error reading MIDI file\n", options.in_filename);
return 1;
}
struct MOD_FILE *mod = make_mod_from_midi(midi, &options);
if (mod == NULL) {
fprintf(stderr, "%s: error converting to MOD\n", options.in_filename);
midi_free(midi);
return 1;
}
mod_file_write(mod, options.out_filename);
mod_file_free(mod);
midi_free(midi);
return 0;
}