aboutsummaryrefslogtreecommitdiffstats
path: root/src/apu.c
blob: d40b2faf1d3ef970a49a4562228a50a6d6d6b99f (plain)
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
/*
Copyright (c) 2021 Bad Diode

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE.
*/

//
// Audio quality configuration.
//
// The AUDIO_FREQ, AUDIO_BUF_LEN and AUDIO_TIMER depend on each other. The pitch
// table is generated such as the samples are pitched with respect to C4. When
// the pitch table is multiplied by the sampling rate of the original sample,
// the resulting value will be the increment per VSYNC, which must be shifted
// AUDIO_INC_PRECISION to obtain a (20.12) fixed-point increment value.
//
#if defined(AUDIO_HIFI)
#define AUDIO_FREQ           40137
#define AUDIO_BUF_LEN        672
#define AUDIO_TIMER          65118
#define AUDIO_INC_PRECISION  6
static u16 pitch_table[120] = {
    53,     56,     59,     63,     67,     71,     75,     79,
    84,     89,     95,     100,    106,    113,    119,    126,
    134,    142,    151,    159,    169,    179,    190,    201,
    213,    226,    239,    253,    269,    285,    302,    319,
    339,    359,    380,    403,    427,    452,    479,    507,
    538,    570,    604,    639,    678,    718,    761,    806,
    854,    905,    958,    1015,   1076,   1140,   1208,   1279,
    1356,   1436,   1522,   1612,   1708,   1810,   1917,   2031,
    2152,   2280,   2416,   2559,   2712,   2873,   3044,   3225,
    3417,   3620,   3835,   4063,   4305,   4561,   4832,   5119,
    5424,   5746,   6088,   6450,   6834,   7240,   7671,   8127,
    8610,   9122,   9665,   10239,  10848,  11493,  12177,  12901,
    13668,  14481,  15342,  16254,  17221,  18245,  19330,  20479,
    21697,  22987,  24354,  25802,  27337,  28962,  30684,  32509,
    34442,  36490,  38660,  40959,  43394,  45975,  48709,  51605,
};
#elif defined(AUDIO_LOWFI)
#define AUDIO_FREQ           5734
#define AUDIO_BUF_LEN        96
#define AUDIO_TIMER          62610
#define AUDIO_INC_PRECISION  4
static u32 pitch_table[120] = {
    93,     98,     104,    111,    117,    124,    132,    139,
    148,    157,    166,    176,    186,    197,    209,    222,
    235,    249,    264,    279,    296,    314,    332,    352,
    373,    395,    419,    444,    470,    498,    528,    559,
    593,    628,    665,    705,    747,    791,    839,    888,
    941,    997,    1057,   1119,   1186,   1257,   1331,   1411,
    1494,   1583,   1678,   1777,   1883,   1995,   2114,   2239,
    2373,   2514,   2663,   2822,   2989,   3167,   3356,   3555,
    3767,   3991,   4228,   4479,   4746,   5028,   5327,   5644,
    5979,   6335,   6712,   7111,   7534,   7982,   8456,   8959,
    9492,   10056,  10654,  11288,  11959,  12670,  13424,  14222,
    15068,  15964,  16913,  17919,  18984,  20113,  21309,  22576,
    23919,  25341,  26848,  28445,  30136,  31928,  33827,  35838,
    37969,  40227,  42619,  45153,  47838,  50683,  53697,  56890,
    60273,  63857,  67654,  71677,  75939,  80454,  85238,  90307,
};
#else
#define AUDIO_FREQ           18157
#define AUDIO_BUF_LEN        304
#define AUDIO_TIMER          64612
#define AUDIO_INC_PRECISION  5
static u16 pitch_table[120] = {
    59,     62,     66,     70,     74,     78,     83,     88,
    93,     99,     105,    111,    118,    125,    132,    140,
    148,    157,    166,    176,    187,    198,    210,    222,
    236,    250,    264,    280,    297,    315,    333,    353,
    374,    396,    420,    445,    472,    500,    529,    561,
    594,    630,    667,    707,    749,    793,    841,    891,
    944,    1000,   1059,   1122,   1189,   1260,   1335,   1414,
    1498,   1587,   1682,   1782,   1888,   2000,   2119,   2245,
    2379,   2520,   2670,   2829,   2997,   3175,   3364,   3564,
    3776,   4001,   4239,   4491,   4758,   5041,   5341,   5658,
    5995,   6351,   6729,   7129,   7553,   8002,   8478,   8982,
    9517,   10083,  10682,  11317,  11990,  12703,  13459,  14259,
    15107,  16005,  16957,  17965,  19034,  20166,  21365,  22635,
    23981,  25407,  26918,  28519,  30215,  32011,  33915,  35931,
    38068,  40332,  42730,  45271,  47963,  50815,  53837,  57038,
};
#endif

typedef struct Audio {
    s8 mix_buffer[AUDIO_BUF_LEN * 2];
    s8 *current_buffer;
    u8 active_buffer;
} Audio;

typedef struct AudioChannel {
    // Pointer to the raw data in the ROM.
    u8 *data;
    // Current position in the data (20.12 fixed-point).
    u32 pos;
    // Increment (20.12 fixed-point).
    u32 inc;
    // Volume (0-64, 1.6 fixed-point).
    u32 vol;
    // Sound length (20.12 fixed-point).
    u32 length;
    // Length of looped portion (20.12 fixed-point, 0 to disable looping).
    u32 loop_length;
    // Pitch encoded as a MIDI note.
    u8 pitch;
    // Keeping track of the original adsr values.
    u16 adsr;
    // The filter is built with the ADSR and has a maximum duration of
    // 4 seconds. Each component can last up to 1 second.
    u8 filter[240];
    // Current position in the filter (0-60).
    u8 filter_pos;
    // Duration of the filter.
    u8 filter_len;
} AudioChannel;

IWRAM_CODE
void
build_adsr(AudioChannel *chan, u16 adsr) {
    chan->filter_pos = 0;
    if (adsr == chan->adsr) {
        return;
    }

    u8 a = (adsr >> 12);
    u8 d = (adsr >> 8) & 0xF;
    u8 s = (adsr >> 4) & 0xF;
    u8 r = (adsr >> 0) & 0xF;

    // Initialize the filter array.
    dma_fill(chan->filter, 0, sizeof(chan->filter), 3);
    u8 k = 0;

    // Attack.
    u32 interval = FP_DIV(1 << 6, (4 * a) << 6, 6);
    for (u32 i = 0; i < 4 * a; ++i) {
        chan->filter[k++] = FP_LERP(0, chan->vol, i * interval, 6);
    }
    // Decay.
    interval = FP_DIV(1 << 6, (4 * d) << 6, 6);
    for (u32 i = 0; i < 4 * d; ++i) {
        chan->filter[k++] = FP_LERP(chan->vol, chan->vol / 2, i * interval, 6);
    }
    // Sustain.
    for (u32 i = 0; i < 4 * s; ++i) {
        chan->filter[k++] = chan->vol / 2;
    }
    // Release.
    interval = FP_DIV(1 << 6, (4 * r) << 6, 6);
    for (u32 i = 0; i < 4 * r; ++i) {
        chan->filter[k++] = FP_LERP(chan->vol / 2, 0, i * interval, 6);
    }

    // Setup the channel vars.
    chan->adsr = adsr;
    chan->filter_len = k;
}

static Audio audio;

#define POLYPHONY 4
static AudioChannel channels[POLYPHONY];

void
init_sound(void) {
    // Initialize audio buffers/channels.
    audio = (Audio){0};
    for (size_t i = 0; i < POLYPHONY; ++i) {
        channels[i] = (AudioChannel){0};
    }

    // Enable the sound chip.
    SOUND_STATUS = SOUND_ENABLE;

    // Set max volume, left-right sound, fifo reset and use timer 0 for
    // DirectSound A.
    SOUND_DSOUND_MASTER = SOUND_DSOUND_RATIO_A
        | SOUND_DSOUND_LEFT_A
        | SOUND_DSOUND_RIGHT_A
        | SOUND_DSOUND_RESET_A;

    // The timer depends on the buffer length.
    TIMER_DATA_0 = AUDIO_TIMER;
    TIMER_CTRL_0 = TIMER_CTRL_ENABLE;
}

void
sound_vsync() {
    if(audio.active_buffer == 1) {
        // Start playing and set the backbuffer.
        dma_transfer_copy(SOUND_FIFO_A, audio.mix_buffer, 1, 1, DMA_DST_FIXED
                | DMA_CHUNK_32 | DMA_REFRESH | DMA_REPEAT | DMA_ENABLE);
        audio.current_buffer = audio.mix_buffer + AUDIO_BUF_LEN;
        audio.active_buffer = 0;
    } else {
        // Flip front/backbuffer.
        audio.current_buffer = audio.mix_buffer;
        audio.active_buffer = 1;
    }
}

IWRAM_CODE
void
update_channel(AudioChannel *c, u8 *data, u16 length, u8 pitch, u16 adsr,
        u8 vol, bool loop) {
    c->pos = 0;
    c->length = length << 12;
    c->data = data;
    c->vol = vol;
    c->pitch = pitch;

    if (loop) {
        c->loop_length = c->length;
    } else {
        c->loop_length = 0;
    }

    u32 sampling_rate = length;
    if (length > 256) {
        sampling_rate = 44100;
    }
    c->inc = (pitch_table[c->pitch] * sampling_rate) >> AUDIO_INC_PRECISION;

    build_adsr(c, adsr);
}

IWRAM_CODE
void
sound_mix(void) {
    // Clear mix_buffer.
    u16 mix_buffer[AUDIO_BUF_LEN];
    dma_fill(mix_buffer, 0, sizeof(mix_buffer), 3);

    // Mix channels into the temporary buffer.
    for (size_t j = 0; j < POLYPHONY; ++j) {
        AudioChannel *ch = &channels[j];
        // Check if channel is active.
        if (ch->data == NULL || ch->pitch >= 108) {
            continue;
        }

        u32 vol = ch->vol;
        if (ch->adsr != 0) {
            vol = ch->filter[ch->filter_pos++];
            if (ch->filter_pos == ch->filter_len) {
                continue;
            }
        }

        if (ch->pos + ch->inc * AUDIO_BUF_LEN >= ch->length) {
            for(size_t i = 0; i < AUDIO_BUF_LEN; i++) {
                // Remember we are using fixed point values.
                mix_buffer[i] += (0x80 ^ (s8)ch->data[ch->pos >> 12]) * vol;
                ch->pos += ch->inc;

                if (ch->pos >= ch->length) {
                    // If looping is not active disable the channel.
                    if (ch->loop_length == 0) {
                        ch->data = NULL;
                        break;
                    }

                    // Loop the sample.
                    while (ch->pos >= ch->length) {
                        ch->pos -= ch->loop_length;
                    }
                }
            }
        } else {
            for(size_t i = 0; i < AUDIO_BUF_LEN; i++) {
                mix_buffer[i] += (0x80 ^ (s8)ch->data[ch->pos >> 12]) * vol;
                ch->pos += ch->inc;
            }
        }
    }

    // Downsample and copy to the playing buffer (Vectorized).
    u64 *mix_ptr = mix_buffer;
    u32 *buf_ptr = audio.current_buffer;
    for (size_t i = 0; i < AUDIO_BUF_LEN / 4; i++) {
        u64 mix = mix_ptr[i];
        buf_ptr[i] = ((mix >> 8) & 0xFF)
            | ((mix >> 16) & 0xFF00)
            | ((mix >> 24) & 0xFF0000)
            | ((mix >> 32) & 0xFF000000);
    }
}