Files: dc2fadcea45c02d204f58e09305b7bcb0c89b025 / tune.c
2122 bytesRaw
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | static float notes[256] = {0}; |
9 | static float dampen[256] = {0}; |
10 | |
11 | static float freqs[256] = {0}; |
12 | static int got_freqs = 0; |
13 | |
14 | // static float buf[48000] = {0}; |
15 | |
16 | float get_freq(int i) |
17 | { |
18 | if (!got_freqs) { |
19 | for (int i = 0; i < 256; i++) { |
20 | freqs[i] = 440. * exp2((i-69) / 12.); |
21 | } |
22 | got_freqs = 1; |
23 | } |
24 | return freqs[i]; |
25 | } |
26 | |
27 | float saw(float x, float t) |
28 | { |
29 | return fmodf(t, 1./x) * x*2. - 1.; |
30 | } |
31 | |
32 | float play(void **obj, double time, float in, unsigned char midi_cmd[3]) |
33 | { |
34 | // return in * 10; |
35 | // return sin(2. * M_PI * time * 440.) * 0.1 + in * 0.9; |
36 | struct { |
37 | struct foobuf *buf; |
38 | // float *keymap; |
39 | } **statep = (void *)obj, *state; |
40 | |
41 | if (struct_init(statep)) { |
42 | warn("foobuf_init"); |
43 | return 0; |
44 | } |
45 | state = *statep; |
46 | if (foobuf_init(&state->buf, 48000)) { |
47 | warn("foobuf_init"); |
48 | return 0; |
49 | } |
50 | // array_init(&state->keymap, 256); |
51 | |
52 | /* |
53 | static float keymap[256]; |
54 | if (!state->keymap) { |
55 | state->keymap = keymap; |
56 | for (size_t i = 0; i < 256; i++) keymap[i] = 0; |
57 | } |
58 | */ |
59 | |
60 | float out = 0; |
61 | |
62 | if (midi_cmd) { |
63 | // float val = sin(2. * M_PI * (float)i/buf_size * freq); |
64 | if (midi_cmd[0] == 0x90) { |
65 | // printf("key %u\n", midi_cmd[1]); |
66 | notes[midi_cmd[1]] += (float)midi_cmd[2]/255.; |
67 | dampen[midi_cmd[1]] = 0; |
68 | } else if (midi_cmd[0] == 0x80) { |
69 | dampen[midi_cmd[1]] += (float)midi_cmd[2]/255.; |
70 | } else { |
71 | // printf("midi %x %x %x\n", buf[0], buf[1], buf[2]); |
72 | } |
73 | } |
74 | |
75 | float total = 0; |
76 | |
77 | for (int i = 0; i < 256; i++) { |
78 | if (notes[i] > 0.01) { |
79 | float freq = get_freq(i); |
80 | total += notes[i]; |
81 | out += notes[i] * saw(freq, time); |
82 | // out += notes[i] * sin(2. * M_PI * time * freq); |
83 | notes[i] *= 0.99999 * (1 - dampen[i] * 0.001); |
84 | } |
85 | if (dampen[i] > 0.001) dampen[i] *= 0.9999; |
86 | } |
87 | |
88 | // return sin(2. * M_PI * time * 440.) * 0.25 + in * 0.75; |
89 | |
90 | // out += foobuf_read(state->buf, 500)*0.9; |
91 | out += in*180; |
92 | // out = in*0.1 + foobuf_read(state->buf, 48000)*0.9; |
93 | foobuf_write(state->buf, out); |
94 | // return out; |
95 | return out * 0.25; |
96 | // return out / total; |
97 | // return 1/(1. + exp(-out * 4)) * 0.99; |
98 | } |
99 |
Built with git-ssb-web