Debian Codegraph @

src/engine/platform/sound/gb/apu.c

raw
1 #include <stdint.h>
2 #include <math.h>
3 #include <string.h>
4 #include <assert.h>
5 #include "gb.h"
6
7 #define GB_CLOCK_RATE 0x400000
8
9 #ifdef __GNUC__
10 #define likely(x) __builtin_expect((x), 1)
11 #define unlikely(x) __builtin_expect((x), 0)
12 #else
13 #define likely(x) x
14 #define unlikely(x) x
15 #endif
16
17 static const uint8_t duties[] = {
18 0, 0, 0, 0, 0, 0, 0, 1,
19 1, 0, 0, 0, 0, 0, 0, 1,
20 1, 0, 0, 0, 0, 1, 1, 1,
21 0, 1, 1, 1, 1, 1, 1, 0,
22 };
23
24 static void refresh_channel(GB_gameboy_t *gb, unsigned index, unsigned cycles_offset)
25 {
26 unsigned multiplier = gb->apu_output.cycles_since_render + cycles_offset - gb->apu_output.last_update[index];
27 gb->apu_output.summed_samples[index].left += gb->apu_output.current_sample[index].left * multiplier;
28 gb->apu_output.summed_samples[index].right += gb->apu_output.current_sample[index].right * multiplier;
29 gb->apu_output.last_update[index] = gb->apu_output.cycles_since_render + cycles_offset;
30 }
31
32 bool GB_apu_is_DAC_enabled(GB_gameboy_t *gb, unsigned index)
33 {
34 if (gb->model >= GB_MODEL_AGB) {
35 /* On the AGB, mixing is done digitally, so there are no per-channel
36 DACs. Instead, all channels are summed digital regardless of
37 whatever the DAC state would be on a CGB or earlier model. */
38 return true;
39 }
40
41 switch (index) {
42 case GB_SQUARE_1:
43 return gb->io_registers[GB_IO_NR12] & 0xF8;
44
45 case GB_SQUARE_2:
46 return gb->io_registers[GB_IO_NR22] & 0xF8;
47
48 case GB_WAVE:
49 return gb->apu.wave_channel.enable;
50
51 case GB_NOISE:
52 return gb->io_registers[GB_IO_NR42] & 0xF8;
53 }
54
55 return false;
56 }
57
58 static uint8_t agb_bias_for_channel(GB_gameboy_t *gb, unsigned index)
59 {
60 if (!gb->apu.is_active[index]) return 0;
61
62 switch (index) {
63 case GB_SQUARE_1:
64 return gb->apu.square_channels[GB_SQUARE_1].current_volume;
65 case GB_SQUARE_2:
66 return gb->apu.square_channels[GB_SQUARE_2].current_volume;
67 case GB_WAVE:
68 return 0;
69 case GB_NOISE:
70 return gb->apu.noise_channel.current_volume;
71 }
72 return 0;
73 }
74
75 static void update_sample(GB_gameboy_t *gb, unsigned index, int8_t value, unsigned cycles_offset)
76 {
77 if (gb->model >= GB_MODEL_AGB) {
78 /* On the AGB, because no analog mixing is done, the behavior of NR51 is a bit different.
79 A channel that is not connected to a terminal is idenitcal to a connected channel
80 playing PCM sample 0. */
81 gb->apu.samples[index] = value;
82
83 if (gb->apu_output.sample_rate) {
84 unsigned right_volume = (gb->io_registers[GB_IO_NR50] & 7) + 1;
85 unsigned left_volume = ((gb->io_registers[GB_IO_NR50] >> 4) & 7) + 1;
86
87 if (index == GB_WAVE) {
88 /* For some reason, channel 3 is inverted on the AGB */
89 value ^= 0xF;
90 }
91
92 GB_sample_t output;
93 uint8_t bias = agb_bias_for_channel(gb, index);
94
95 if (gb->io_registers[GB_IO_NR51] & (1 << index)) {
96 output.right = (0xf - value * 2 + bias) * right_volume;
97 }
98 else {
99 output.right = 0xf * right_volume;
100 }
101
102 if (gb->io_registers[GB_IO_NR51] & (0x10 << index)) {
103 output.left = (0xf - value * 2 + bias) * left_volume;
104 }
105 else {
106 output.left = 0xf * left_volume;
107 }
108
109 if (*(uint32_t *)&(gb->apu_output.current_sample[index]) != *(uint32_t *)&output) {
110 refresh_channel(gb, index, cycles_offset);
111 gb->apu_output.current_sample[index] = output;
112 }
113 }
114
115 return;
116 }
117
118 if (!GB_apu_is_DAC_enabled(gb, index)) {
119 value = gb->apu.samples[index];
120 }
121 else {
122 gb->apu.samples[index] = value;
123 }
124
125 if (gb->apu_output.sample_rate) {
126 unsigned right_volume = 0;
127 if (gb->io_registers[GB_IO_NR51] & (1 << index)) {
128 right_volume = (gb->io_registers[GB_IO_NR50] & 7) + 1;
129 }
130 unsigned left_volume = 0;
131 if (gb->io_registers[GB_IO_NR51] & (0x10 << index)) {
132 left_volume = ((gb->io_registers[GB_IO_NR50] >> 4) & 7) + 1;
133 }
134 GB_sample_t output = {(0xf - value * 2) * left_volume, (0xf - value * 2) * right_volume};
135 if (*(uint32_t *)&(gb->apu_output.current_sample[index]) != *(uint32_t *)&output) {
136 refresh_channel(gb, index, cycles_offset);
137 gb->apu_output.current_sample[index] = output;
138 }
139 }
140 }
141
142 static double smooth(double x)
143 {
144 return 3*x*x - 2*x*x*x;
145 }
146
147 static signed interference(GB_gameboy_t *gb)
148 {
149 /* These aren't scientifically measured, but based on ear based on several recordings */
150 signed ret = 0;
151 if (gb->halted) {
152 if (gb->model != GB_MODEL_AGB) {
153 ret -= MAX_CH_AMP / 5;
154 }
155 else {
156 ret -= MAX_CH_AMP / 12;
157 }
158 }
159 if (gb->io_registers[GB_IO_LCDC] & 0x80) {
160 ret += MAX_CH_AMP / 7;
161 if ((gb->io_registers[GB_IO_STAT] & 3) == 3 && gb->model != GB_MODEL_AGB) {
162 ret += MAX_CH_AMP / 14;
163 }
164 else if ((gb->io_registers[GB_IO_STAT] & 3) == 1) {
165 ret -= MAX_CH_AMP / 7;
166 }
167 }
168
169 if (gb->apu.global_enable) {
170 ret += MAX_CH_AMP / 10;
171 }
172
173 if (CGB && gb->model < GB_MODEL_AGB && (gb->io_registers[GB_IO_RP] & 1)) {
174 ret += MAX_CH_AMP / 10;
175 }
176
177 if (!CGB) {
178 ret /= 4;
179 }
180
181 //ret += rand() % (MAX_CH_AMP / 12);
182
183 return ret;
184 }
185
186 static void render(GB_gameboy_t *gb)
187 {
188 GB_sample_t output = {0, 0};
189
190 unrolled for (unsigned i = 0; i < GB_N_CHANNELS; i++) {
191 double multiplier = CH_STEP;
192
193 if (gb->model < GB_MODEL_AGB) {
194 if (!GB_apu_is_DAC_enabled(gb, i)) {
195 gb->apu_output.dac_discharge[i] -= ((double) DAC_DECAY_SPEED) / gb->apu_output.sample_rate;
196 if (gb->apu_output.dac_discharge[i] < 0) {
197 multiplier = 0;
198 gb->apu_output.dac_discharge[i] = 0;
199 }
200 else {
201 multiplier *= smooth(gb->apu_output.dac_discharge[i]);
202 }
203 }
204 else {
205 gb->apu_output.dac_discharge[i] += ((double) DAC_ATTACK_SPEED) / gb->apu_output.sample_rate;
206 if (gb->apu_output.dac_discharge[i] > 1) {
207 gb->apu_output.dac_discharge[i] = 1;
208 }
209 else {
210 multiplier *= smooth(gb->apu_output.dac_discharge[i]);
211 }
212 }
213 }
214
215 if (likely(gb->apu_output.last_update[i] == 0)) {
216 output.left += gb->apu_output.current_sample[i].left * multiplier;
217 output.right += gb->apu_output.current_sample[i].right * multiplier;
218 }
219 else {
220 refresh_channel(gb, i, 0);
221 output.left += (signed long) gb->apu_output.summed_samples[i].left * multiplier
222 / gb->apu_output.cycles_since_render;
223 output.right += (signed long) gb->apu_output.summed_samples[i].right * multiplier
224 / gb->apu_output.cycles_since_render;
225 gb->apu_output.summed_samples[i] = (GB_sample_t){0, 0};
226 }
227 gb->apu_output.last_update[i] = 0;
228 }
229 gb->apu_output.cycles_since_render = 0;
230
231 GB_sample_t filtered_output = gb->apu_output.highpass_mode?
232 (GB_sample_t) {output.left - gb->apu_output.highpass_diff.left,
233 output.right - gb->apu_output.highpass_diff.right} :
234 output;
235
236 switch (gb->apu_output.highpass_mode) {
237 case GB_HIGHPASS_OFF:
238 gb->apu_output.highpass_diff = (GB_double_sample_t) {0, 0};
239 break;
240 case GB_HIGHPASS_ACCURATE:
241 gb->apu_output.highpass_diff = (GB_double_sample_t)
242 {output.left - filtered_output.left * gb->apu_output.highpass_rate,
243 output.right - filtered_output.right * gb->apu_output.highpass_rate};
244 break;
245 case GB_HIGHPASS_REMOVE_DC_OFFSET: {
246 unsigned mask = gb->io_registers[GB_IO_NR51];
247 unsigned left_volume = 0;
248 unsigned right_volume = 0;
249 unrolled for (unsigned i = GB_N_CHANNELS; i--;) {
250 if (gb->apu.is_active[i]) {
251 if (mask & 1) {
252 left_volume += (gb->io_registers[GB_IO_NR50] & 7) * CH_STEP * 0xF;
253 }
254 if (mask & 0x10) {
255 right_volume += ((gb->io_registers[GB_IO_NR50] >> 4) & 7) * CH_STEP * 0xF;
256 }
257 }
258 else {
259 left_volume += gb->apu_output.current_sample[i].left * CH_STEP;
260 right_volume += gb->apu_output.current_sample[i].right * CH_STEP;
261 }
262 mask >>= 1;
263 }
264 gb->apu_output.highpass_diff = (GB_double_sample_t)
265 {left_volume * (1 - gb->apu_output.highpass_rate) + gb->apu_output.highpass_diff.left * gb->apu_output.highpass_rate,
266 right_volume * (1 - gb->apu_output.highpass_rate) + gb->apu_output.highpass_diff.right * gb->apu_output.highpass_rate};
267
268 case GB_HIGHPASS_MAX:;
269 }
270
271 }
272
273
274 if (gb->apu_output.interference_volume) {
275 signed interference_bias = interference(gb);
276 int16_t interference_sample = (interference_bias - gb->apu_output.interference_highpass);
277 gb->apu_output.interference_highpass = gb->apu_output.interference_highpass * gb->apu_output.highpass_rate +
278 (1 - gb->apu_output.highpass_rate) * interference_sample;
279 interference_bias *= gb->apu_output.interference_volume;
280
281 filtered_output.left = MAX(MIN(filtered_output.left + interference_bias, 0x7FFF), -0x8000);
282 filtered_output.right = MAX(MIN(filtered_output.right + interference_bias, 0x7FFF), -0x8000);
283 }
284
285 gb->apu_output.final_sample=filtered_output;
286 }
287
288 static void update_square_sample(GB_gameboy_t *gb, unsigned index)
289 {
290 if (gb->apu.square_channels[index].current_sample_index & 0x80) return;
291
292 uint8_t duty = gb->io_registers[index == GB_SQUARE_1? GB_IO_NR11 :GB_IO_NR21] >> 6;
293 update_sample(gb, index,
294 duties[gb->apu.square_channels[index].current_sample_index + duty * 8]?
295 gb->apu.square_channels[index].current_volume : 0,
296 0);
297 }
298
299
300 /* the effects of NRX2 writes on current volume are not well documented and differ
301 between models and variants. The exact behavior can only be verified on CGB as it
302 requires the PCM12 register. The behavior implemented here was verified on *my*
303 CGB, which might behave differently from other CGB revisions, as well as from the
304 DMG, MGB or SGB/2 */
305 static void _nrx2_glitch(uint8_t *volume, uint8_t value, uint8_t old_value, uint8_t *countdown, GB_envelope_clock_t *lock)
306 {
307 if (lock->clock) {
308 *countdown = value & 7;
309 }
310 bool should_tick = (value & 7) && !(old_value & 7) && !lock->locked;
311 bool should_invert = (value & 8) ^ (old_value & 8);
312
313 if ((value & 0xF) == 8 && (old_value & 0xF) == 8 && !lock->locked) {
314 should_tick = true;
315 }
316
317 if (should_invert) {
318 // The weird way and over-the-top way clocks for this counter are connected cause
319 // some weird ways for it to invert
320 if (value & 8) {
321 if (!(old_value & 7) && !lock->locked) {
322 *volume ^= 0xF;
323 }
324 else {
325 *volume = 0xE - *volume;
326 *volume &= 0xF;
327 }
328 should_tick = false; // Somehow prevents ticking?
329 }
330 else {
331 *volume = 0x10 - *volume;
332 *volume &= 0xF;
333 }
334 }
335 if (should_tick) {
336 if (value & 8) {
337 (*volume)++;
338 }
339 else {
340 (*volume)--;
341 }
342 *volume &= 0xF;
343 }
344 else if (!(value & 7) && lock->clock) {
345 // *lock->locked = false; // Excepted from the schematics, but doesn't actually happen on any model?
346 if (!should_invert) {
347 if (*volume == 0xF && (value & 8)) {
348 lock->locked = true;
349 }
350 else if (*volume == 0 && !(value & 8)) {
351 lock->locked = true;
352 }
353 }
354 else if (*volume == 1 && !(value & 8)) {
355 lock->locked = true;
356 }
357 else if (*volume == 0xE && (value & 8)) {
358 lock->locked = true;
359 }
360 lock->clock = false;
361 }
362 }
363
364 static void nrx2_glitch(GB_gameboy_t *gb, uint8_t *volume, uint8_t value, uint8_t old_value, uint8_t *countdown, GB_envelope_clock_t *lock)
365 {
366 if (gb->model <= GB_MODEL_CGB_C) {
367 _nrx2_glitch(volume, 0xFF, old_value, countdown, lock);
368 _nrx2_glitch(volume, value, 0xFF, countdown, lock);
369 }
370 else {
371 _nrx2_glitch(volume, value, old_value, countdown, lock);
372 }
373 }
374
375 static void tick_square_envelope(GB_gameboy_t *gb, enum GB_CHANNELS index)
376 {
377 uint8_t nrx2 = gb->io_registers[index == GB_SQUARE_1? GB_IO_NR12 : GB_IO_NR22];
378
379 if (gb->apu.square_envelope_clock[index].locked) return;
380 if (!(nrx2 & 7)) return;
381 if (gb->cgb_double_speed) {
382 if (index == GB_SQUARE_1) {
383 gb->apu.pcm_mask[0] &= gb->apu.square_channels[GB_SQUARE_1].current_volume | 0xF1;
384 }
385 else {
386 gb->apu.pcm_mask[0] &= (gb->apu.square_channels[GB_SQUARE_2].current_volume << 2) | 0x1F;
387 }
388 }
389
390 if (nrx2 & 8) {
391 if (gb->apu.square_channels[index].current_volume < 0xF) {
392 gb->apu.square_channels[index].current_volume++;
393 }
394 else {
395 gb->apu.square_envelope_clock[index].locked = true;
396 }
397 }
398 else {
399 if (gb->apu.square_channels[index].current_volume > 0) {
400 gb->apu.square_channels[index].current_volume--;
401 }
402 else {
403 gb->apu.square_envelope_clock[index].locked = true;
404 }
405 }
406
407 if (gb->apu.is_active[index]) {
408 update_square_sample(gb, index);
409 }
410 }
411
412 static void tick_noise_envelope(GB_gameboy_t *gb)
413 {
414 uint8_t nr42 = gb->io_registers[GB_IO_NR42];
415
416 if (gb->apu.noise_envelope_clock.locked) return;
417 if (!(nr42 & 7)) return;
418
419 if (gb->cgb_double_speed) {
420 gb->apu.pcm_mask[0] &= (gb->apu.noise_channel.current_volume << 2) | 0x1F;
421 }
422
423 if (nr42 & 8) {
424 if (gb->apu.noise_channel.current_volume < 0xF) {
425 gb->apu.noise_channel.current_volume++;
426 }
427 else {
428 gb->apu.noise_envelope_clock.locked = true;
429 }
430 }
431 else {
432 if (gb->apu.noise_channel.current_volume > 0) {
433 gb->apu.noise_channel.current_volume--;
434 }
435 else {
436 gb->apu.noise_envelope_clock.locked = true;
437 }
438 }
439
440 if (gb->apu.is_active[GB_NOISE]) {
441 update_sample(gb, GB_NOISE,
442 (gb->apu.noise_channel.lfsr & 1) ?
443 gb->apu.noise_channel.current_volume : 0,
444 0);
445 }
446 }
447
448 static void trigger_sweep_calculation(GB_gameboy_t *gb)
449 {
450 if ((gb->io_registers[GB_IO_NR10] & 0x70) && gb->apu.square_sweep_countdown == 7) {
451 if (gb->io_registers[GB_IO_NR10] & 0x07) {
452 gb->apu.square_channels[GB_SQUARE_1].sample_length =
453 gb->apu.sweep_length_addend + gb->apu.shadow_sweep_sample_length + !!(gb->io_registers[GB_IO_NR10] & 0x8);
454 gb->apu.square_channels[GB_SQUARE_1].sample_length &= 0x7FF;
455 }
456 if (gb->apu.channel_1_restart_hold == 0) {
457 gb->apu.sweep_length_addend = gb->apu.square_channels[GB_SQUARE_1].sample_length;
458 gb->apu.sweep_length_addend >>= (gb->io_registers[GB_IO_NR10] & 7);
459 }
460
461 /* Recalculation and overflow check only occurs after a delay */
462 gb->apu.square_sweep_calculate_countdown = (gb->io_registers[GB_IO_NR10] & 0x7) * 2 + 5 - gb->apu.lf_div;
463 if (gb->model <= GB_MODEL_CGB_C && gb->apu.lf_div) {
464 // gb->apu.square_sweep_calculate_countdown += 2;
465 }
466 gb->apu.enable_zombie_calculate_stepping = false;
467 gb->apu.unshifted_sweep = !(gb->io_registers[GB_IO_NR10] & 0x7);
468 gb->apu.square_sweep_countdown = ((gb->io_registers[GB_IO_NR10] >> 4) & 7) ^ 7;
469 }
470 }
471
472 void GB_apu_div_event(GB_gameboy_t *gb)
473 {
474 if (!gb->apu.global_enable) return;
475 if (gb->apu.skip_div_event == GB_SKIP_DIV_EVENT_SKIP) {
476 gb->apu.skip_div_event = GB_SKIP_DIV_EVENT_SKIPPED;
477 return;
478 }
479 if (gb->apu.skip_div_event == GB_SKIP_DIV_EVENT_SKIPPED) {
480 gb->apu.skip_div_event = GB_SKIP_DIV_EVENT_INACTIVE;
481 }
482 else {
483 gb->apu.div_divider++;
484 }
485
486 if ((gb->apu.div_divider & 7) == 7) {
487 unrolled for (unsigned i = GB_SQUARE_2 + 1; i--;) {
488 if (!gb->apu.square_envelope_clock[i].clock) {
489 gb->apu.square_channels[i].volume_countdown--;
490 gb->apu.square_channels[i].volume_countdown &= 7;
491 }
492 }
493 if (!gb->apu.noise_envelope_clock.clock) {
494 gb->apu.noise_channel.volume_countdown--;
495 gb->apu.noise_channel.volume_countdown &= 7;
496 }
497 }
498
499 unrolled for (unsigned i = GB_SQUARE_2 + 1; i--;) {
500 if (gb->apu.square_envelope_clock[i].clock) {
501 tick_square_envelope(gb, i);
502 gb->apu.square_envelope_clock[i].clock = false;
503 }
504 }
505
506 if (gb->apu.noise_envelope_clock.clock) {
507 tick_noise_envelope(gb);
508 gb->apu.noise_envelope_clock.clock = false;
509 }
510
511 if ((gb->apu.div_divider & 1) == 1) {
512 unrolled for (unsigned i = GB_SQUARE_2 + 1; i--;) {
513 if (gb->apu.square_channels[i].length_enabled) {
514 if (gb->apu.square_channels[i].pulse_length) {
515 if (!--gb->apu.square_channels[i].pulse_length) {
516 gb->apu.is_active[i] = false;
517 update_sample(gb, i, 0, 0);
518 }
519 }
520 }
521 }
522
523 if (gb->apu.wave_channel.length_enabled) {
524 if (gb->apu.wave_channel.pulse_length) {
525 if (!--gb->apu.wave_channel.pulse_length) {
526 gb->apu.is_active[GB_WAVE] = false;
527 update_sample(gb, GB_WAVE, 0, 0);
528 }
529 }
530 }
531
532 if (gb->apu.noise_channel.length_enabled) {
533 if (gb->apu.noise_channel.pulse_length) {
534 if (!--gb->apu.noise_channel.pulse_length) {
535 gb->apu.is_active[GB_NOISE] = false;
536 update_sample(gb, GB_NOISE, 0, 0);
537 }
538 }
539 }
540 }
541
542 if ((gb->apu.div_divider & 3) == 3) {
543 gb->apu.square_sweep_countdown++;
544 gb->apu.square_sweep_countdown &= 7;
545 trigger_sweep_calculation(gb);
546 }
547 }
548
549 void GB_apu_div_secondary_event(GB_gameboy_t *gb)
550 {
551 unrolled for (unsigned i = GB_SQUARE_2 + 1; i--;) {
552 uint8_t nrx2 = gb->io_registers[i == GB_SQUARE_1? GB_IO_NR12 : GB_IO_NR22];
553 if (gb->apu.is_active[i] && gb->apu.square_channels[i].volume_countdown == 0) {
554 gb->apu.square_envelope_clock[i].clock = (gb->apu.square_channels[i].volume_countdown = nrx2 & 7);
555 }
556 }
557
558 if (gb->apu.is_active[GB_NOISE] && gb->apu.noise_channel.volume_countdown == 0) {
559 gb->apu.noise_envelope_clock.clock = (gb->apu.noise_channel.volume_countdown = gb->io_registers[GB_IO_NR42] & 7);
560 }
561 }
562
563 static void step_lfsr(GB_gameboy_t *gb, unsigned cycles_offset)
564 {
565 unsigned high_bit_mask = gb->apu.noise_channel.narrow ? 0x4040 : 0x4000;
566 bool new_high_bit = (gb->apu.noise_channel.lfsr ^ (gb->apu.noise_channel.lfsr >> 1) ^ 1) & 1;
567 gb->apu.noise_channel.lfsr >>= 1;
568
569 if (new_high_bit) {
570 gb->apu.noise_channel.lfsr |= high_bit_mask;
571 }
572 else {
573 /* This code is not redundent, it's relevant when switching LFSR widths */
574 gb->apu.noise_channel.lfsr &= ~high_bit_mask;
575 }
576
577 gb->apu.current_lfsr_sample = gb->apu.noise_channel.lfsr & 1;
578 if (gb->apu.is_active[GB_NOISE]) {
579 update_sample(gb, GB_NOISE,
580 gb->apu.current_lfsr_sample ?
581 gb->apu.noise_channel.current_volume : 0,
582 cycles_offset);
583 }
584 }
585
586 void GB_apu_run(GB_gameboy_t *gb)
587 {
588 /* Convert 4MHZ to 2MHz. apu_cycles is always divisable by 4. */
589 uint8_t cycles = gb->apu.apu_cycles >> 2;
590 gb->apu.apu_cycles = 0;
591 if (!cycles) return;
592
593 bool start_ch4 = false;
594 if (likely(!gb->stopped || CGB)) {
595 if (gb->apu.channel_4_dmg_delayed_start) {
596 if (gb->apu.channel_4_dmg_delayed_start == cycles) {
597 gb->apu.channel_4_dmg_delayed_start = 0;
598 start_ch4 = true;
599 }
600 else if (gb->apu.channel_4_dmg_delayed_start > cycles) {
601 gb->apu.channel_4_dmg_delayed_start -= cycles;
602 }
603 else {
604 /* Split it into two */
605 cycles -= gb->apu.channel_4_dmg_delayed_start;
606 gb->apu.apu_cycles = gb->apu.channel_4_dmg_delayed_start * 4;
607 GB_apu_run(gb);
608 }
609 }
610 /* To align the square signal to 1MHz */
611 gb->apu.lf_div ^= cycles & 1;
612 gb->apu.noise_channel.alignment += cycles;
613
614 if (gb->apu.square_sweep_calculate_countdown &&
615 (((gb->io_registers[GB_IO_NR10] & 7) || gb->apu.unshifted_sweep) ||
616 gb->apu.square_sweep_calculate_countdown <= 3)) { // Calculation is paused if the lower bits are 0
617 if (gb->apu.square_sweep_calculate_countdown > cycles) {
618 gb->apu.square_sweep_calculate_countdown -= cycles;
619 }
620 else {
621 /* APU bug: sweep frequency is checked after adding the sweep delta twice */
622 if (gb->apu.channel_1_restart_hold == 0) {
623 gb->apu.shadow_sweep_sample_length = gb->apu.square_channels[GB_SQUARE_1].sample_length;
624 }
625 if (gb->io_registers[GB_IO_NR10] & 8) {
626 gb->apu.sweep_length_addend ^= 0x7FF;
627 }
628 if (gb->apu.shadow_sweep_sample_length + gb->apu.sweep_length_addend > 0x7FF && !(gb->io_registers[GB_IO_NR10] & 8)) {
629 gb->apu.is_active[GB_SQUARE_1] = false;
630 update_sample(gb, GB_SQUARE_1, 0, gb->apu.square_sweep_calculate_countdown - cycles);
631 }
632 gb->apu.channel1_completed_addend = gb->apu.sweep_length_addend;
633
634 gb->apu.square_sweep_calculate_countdown = 0;
635 }
636 }
637
638 if (gb->apu.channel_1_restart_hold) {
639 if (gb->apu.channel_1_restart_hold > cycles) {
640 gb->apu.channel_1_restart_hold -= cycles;
641 }
642 else {
643 gb->apu.channel_1_restart_hold = 0;
644 }
645 }
646
647 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
648 if (gb->apu.is_active[i]) {
649 uint8_t cycles_left = cycles;
650 while (unlikely(cycles_left > gb->apu.square_channels[i].sample_countdown)) {
651 cycles_left -= gb->apu.square_channels[i].sample_countdown + 1;
652 gb->apu.square_channels[i].sample_countdown = (gb->apu.square_channels[i].sample_length ^ 0x7FF) * 2 + 1;
653 gb->apu.square_channels[i].current_sample_index++;
654 gb->apu.square_channels[i].current_sample_index &= 0x7;
655 if (cycles_left == 0 && gb->apu.samples[i] == 0) {
656 gb->apu.pcm_mask[0] &= i == GB_SQUARE_1? 0xF0 : 0x0F;
657 }
658
659 update_square_sample(gb, i);
660 }
661 if (cycles_left) {
662 gb->apu.square_channels[i].sample_countdown -= cycles_left;
663 }
664 }
665 }
666
667 gb->apu.wave_channel.wave_form_just_read = false;
668 if (gb->apu.is_active[GB_WAVE]) {
669 uint8_t cycles_left = cycles;
670 while (unlikely(cycles_left > gb->apu.wave_channel.sample_countdown)) {
671 uint8_t base = (!gb->apu.wave_channel.double_length && gb->apu.wave_channel.bank_select) ? 32 : 0;
672 cycles_left -= gb->apu.wave_channel.sample_countdown + 1;
673 gb->apu.wave_channel.sample_countdown = gb->apu.wave_channel.sample_length ^ 0x7FF;
674 gb->apu.wave_channel.current_sample_index++;
675 gb->apu.wave_channel.current_sample_index &= gb->apu.wave_channel.double_length ? 0x3F : 0x1F;
676 gb->apu.wave_channel.current_sample =
677 gb->apu.wave_channel.wave_form[base + gb->apu.wave_channel.current_sample_index];
678 int8_t sample = gb->apu.wave_channel.force_3 ?
679 (gb->apu.wave_channel.current_sample * 3) >> 2 :
680 gb->apu.wave_channel.current_sample >> gb->apu.wave_channel.shift;
681 update_sample(gb, GB_WAVE, sample, cycles - cycles_left);
682 gb->apu.wave_channel.wave_form_just_read = true;
683 }
684 if (cycles_left) {
685 gb->apu.wave_channel.sample_countdown -= cycles_left;
686 gb->apu.wave_channel.wave_form_just_read = false;
687 }
688 }
689
690 // The noise channel can step even if inactive on the DMG
691 if (gb->apu.is_active[GB_NOISE] || !CGB) {
692 uint8_t cycles_left = cycles;
693 unsigned divisor = (gb->io_registers[GB_IO_NR43] & 0x07) << 2;
694 if (!divisor) divisor = 2;
695 if (gb->apu.noise_channel.counter_countdown == 0) {
696 gb->apu.noise_channel.counter_countdown = divisor;
697 }
698 while (unlikely(cycles_left >= gb->apu.noise_channel.counter_countdown)) {
699 cycles_left -= gb->apu.noise_channel.counter_countdown;
700 gb->apu.noise_channel.counter_countdown = divisor + gb->apu.channel_4_delta;
701 gb->apu.channel_4_delta = 0;
702 bool old_bit = (gb->apu.noise_channel.counter >> (gb->io_registers[GB_IO_NR43] >> 4)) & 1;
703 gb->apu.noise_channel.counter++;
704 gb->apu.noise_channel.counter &= 0x3FFF;
705 bool new_bit = (gb->apu.noise_channel.counter >> (gb->io_registers[GB_IO_NR43] >> 4)) & 1;
706
707 /* Step LFSR */
708 if (new_bit && !old_bit) {
709 if (cycles_left == 0 && gb->apu.samples[GB_NOISE] == 0) {
710 gb->apu.pcm_mask[1] &= 0x0F;
711 }
712 step_lfsr(gb, cycles - cycles_left);
713 }
714 }
715 if (cycles_left) {
716 gb->apu.noise_channel.counter_countdown -= cycles_left;
717 gb->apu.channel_4_countdown_reloaded = false;
718 }
719 else {
720 gb->apu.channel_4_countdown_reloaded = true;
721 }
722 }
723 }
724
725 if (gb->apu_output.sample_rate) {
726 gb->apu_output.cycles_since_render += cycles;
727
728 if (gb->apu_output.sample_cycles >= gb->apu_output.cycles_per_sample) {
729 gb->apu_output.sample_cycles -= gb->apu_output.cycles_per_sample;
730 render(gb);
731 }
732 }
733 if (start_ch4) {
734 GB_apu_write(gb, GB_IO_NR44, gb->io_registers[GB_IO_NR44] | 0x80);
735 }
736 }
737
738 void GB_apu_init(GB_gameboy_t *gb)
739 {
740 memset(&gb->apu, 0, sizeof(gb->apu));
741 /* Restore the wave form */
742 for (unsigned reg = GB_IO_WAV_START; reg <= GB_IO_WAV_END; reg++) {
743 gb->apu.wave_channel.wave_form[(reg - GB_IO_WAV_START) * 2] = gb->io_registers[reg] >> 4;
744 gb->apu.wave_channel.wave_form[(reg - GB_IO_WAV_START) * 2 + 1] = gb->io_registers[reg] & 0xF;
745 gb->apu.wave_channel.wave_form[(reg - GB_IO_WAV_START) * 2 + 32] = gb->io_registers[reg] >> 4;
746 gb->apu.wave_channel.wave_form[(reg - GB_IO_WAV_START) * 2 + 33] = gb->io_registers[reg] & 0xF;
747 }
748 gb->apu.lf_div = 1;
749 /* APU glitch: When turning the APU on while DIV's bit 4 (or 5 in double speed mode) is on,
750 the first DIV/APU event is skipped. */
751 if (gb->div_counter & (gb->cgb_double_speed? 0x2000 : 0x1000)) {
752 gb->apu.skip_div_event = GB_SKIP_DIV_EVENT_SKIP;
753 gb->apu.div_divider = 1;
754 }
755 }
756
757 uint8_t GB_apu_read(GB_gameboy_t *gb, uint8_t reg)
758 {
759 if (reg == GB_IO_NR52) {
760 uint8_t value = 0;
761 for (unsigned i = 0; i < GB_N_CHANNELS; i++) {
762 value >>= 1;
763 if (gb->apu.is_active[i]) {
764 value |= 0x8;
765 }
766 }
767 if (gb->apu.global_enable) {
768 value |= 0x80;
769 }
770 value |= 0x70;
771 return value;
772 }
773
774 static const char read_mask[GB_IO_WAV_END - GB_IO_NR10 + 1] = {
775 /* NRX0 NRX1 NRX2 NRX3 NRX4 */
776 0x80, 0x3F, 0x00, 0xFF, 0xBF, // NR1X
777 0xFF, 0x3F, 0x00, 0xFF, 0xBF, // NR2X
778 0x7F, 0xFF, 0x9F, 0xFF, 0xBF, // NR3X
779 0xFF, 0xFF, 0x00, 0x00, 0xBF, // NR4X
780 0x00, 0x00, 0x70, 0xFF, 0xFF, // NR5X
781
782 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Unused
783 // Wave RAM
784 0, /* ... */
785 };
786
787 if (reg >= GB_IO_WAV_START && reg <= GB_IO_WAV_END && gb->apu.is_active[GB_WAVE]) {
788 if (!CGB && !gb->apu.wave_channel.wave_form_just_read) {
789 return 0xFF;
790 }
791 if (gb->model == GB_MODEL_AGB) {
792 return 0xFF;
793 }
794 reg = GB_IO_WAV_START + gb->apu.wave_channel.current_sample_index / 2;
795 }
796
797 return gb->io_registers[reg] | read_mask[reg - GB_IO_NR10];
798 }
799
800 static inline uint16_t effective_channel4_counter(GB_gameboy_t *gb)
801 {
802 /*
803 TODO: On revisions older than the CGB-D, this behaves differently when
804 the counter advanced this exact T-cycle. Also, in these revisions,
805 it seems that "passive" changes (due to the temporary FF value NR43
806 has during writes) behave slightly different from non-passive ones.
807 */
808 uint16_t effective_counter = gb->apu.noise_channel.counter;
809 /* Ladies and gentlemen, I present you the holy grail glitch of revision detection! */
810 switch (gb->model) {
811 /* Pre CGB revisions are assumed to be like CGB-C, A and 0 for the lack of a better guess.
812 TODO: It could be verified with audio based test ROMs. */
813 #if 0
814 case GB_MODEL_CGB_B:
815 if (effective_counter & 8) {
816 effective_counter |= 0xE; // Seems to me F under some circumstances?
817 }
818 if (effective_counter & 0x80) {
819 effective_counter |= 0xFF;
820 }
821 if (effective_counter & 0x100) {
822 effective_counter |= 0x1;
823 }
824 if (effective_counter & 0x200) {
825 effective_counter |= 0x2;
826 }
827 if (effective_counter & 0x400) {
828 effective_counter |= 0x4;
829 }
830 if (effective_counter & 0x800) {
831 effective_counter |= 0x408; // TODO: Only my CGB-B does that! Others behave like C!
832 }
833 if (effective_counter & 0x1000) {
834 effective_counter |= 0x10;
835 }
836 if (effective_counter & 0x2000) {
837 effective_counter |= 0x20;
838 }
839 break;
840 #endif
841 case GB_MODEL_DMG_B:
842 case GB_MODEL_SGB_NTSC:
843 case GB_MODEL_SGB_PAL:
844 case GB_MODEL_SGB_NTSC_NO_SFC:
845 case GB_MODEL_SGB_PAL_NO_SFC:
846 case GB_MODEL_SGB2:
847 case GB_MODEL_SGB2_NO_SFC:
848 // case GB_MODEL_CGB_0:
849 // case GB_MODEL_CGB_A:
850 case GB_MODEL_CGB_C:
851 if (effective_counter & 8) {
852 effective_counter |= 0xE; // Sometimes F on some instances
853 }
854 if (effective_counter & 0x80) {
855 effective_counter |= 0xFF;
856 }
857 if (effective_counter & 0x100) {
858 effective_counter |= 0x1;
859 }
860 if (effective_counter & 0x200) {
861 effective_counter |= 0x2;
862 }
863 if (effective_counter & 0x400) {
864 effective_counter |= 0x4;
865 }
866 if (effective_counter & 0x800) {
867 if ((gb->io_registers[GB_IO_NR43] & 8)) {
868 effective_counter |= 0x400;
869 }
870 effective_counter |= 0x8;
871 }
872 if (effective_counter & 0x1000) {
873 effective_counter |= 0x10;
874 }
875 if (effective_counter & 0x2000) {
876 effective_counter |= 0x20;
877 }
878 break;
879 #if 0
880 case GB_MODEL_CGB_D:
881 if (effective_counter & ((gb->io_registers[GB_IO_NR43] & 8)? 0x40 : 0x80)) { // This is so weird
882 effective_counter |= 0xFF;
883 }
884 if (effective_counter & 0x100) {
885 effective_counter |= 0x1;
886 }
887 if (effective_counter & 0x200) {
888 effective_counter |= 0x2;
889 }
890 if (effective_counter & 0x400) {
891 effective_counter |= 0x4;
892 }
893 if (effective_counter & 0x800) {
894 effective_counter |= 0x8;
895 }
896 if (effective_counter & 0x1000) {
897 effective_counter |= 0x10;
898 }
899 break;
900 #endif
901 case GB_MODEL_CGB_E:
902 if (effective_counter & ((gb->io_registers[GB_IO_NR43] & 8)? 0x40 : 0x80)) { // This is so weird
903 effective_counter |= 0xFF;
904 }
905 if (effective_counter & 0x1000) {
906 effective_counter |= 0x10;
907 }
908 break;
909 case GB_MODEL_AGB:
910 case GB_MODEL_AGB_NATIVE:
911 /* TODO: AGBs are not affected, but AGSes are. They don't seem to follow a simple
912 pattern like the other revisions. */
913 /* For the most part, AGS seems to do:
914 0x20 -> 0xA0
915 0x200 -> 0xA00
916 0x1000 -> 0x1010, but only if wide
917 */
918 break;
919 }
920 return effective_counter;
921 }
922
923 void GB_apu_write(GB_gameboy_t *gb, uint8_t reg, uint8_t value)
924 {
925 if (!gb->apu.global_enable && reg != GB_IO_NR52 && reg < GB_IO_WAV_START && (CGB ||
926 (
927 reg != GB_IO_NR11 &&
928 reg != GB_IO_NR21 &&
929 reg != GB_IO_NR31 &&
930 reg != GB_IO_NR41
931 )
932 )) {
933 return;
934 }
935
936 if (reg >= GB_IO_WAV_START && reg <= GB_IO_WAV_END && gb->apu.is_active[GB_WAVE]) {
937 if (!CGB && !gb->apu.wave_channel.wave_form_just_read) {
938 return;
939 }
940 reg = GB_IO_WAV_START + gb->apu.wave_channel.current_sample_index / 2;
941 }
942
943 /* Todo: this can and should be rewritten with a function table. */
944 switch (reg) {
945 /* Globals */
946 case GB_IO_NR50:
947 case GB_IO_NR51:
948 gb->io_registers[reg] = value;
949 /* These registers affect the output of all 4 channels (but not the output of the PCM registers).*/
950 /* We call update_samples with the current value so the APU output is updated with the new outputs */
951 for (unsigned i = GB_N_CHANNELS; i--;) {
952 update_sample(gb, i, gb->apu.samples[i], 0);
953 }
954 break;
955 case GB_IO_NR52: {
956
957 uint8_t old_pulse_lengths[] = {
958 gb->apu.square_channels[0].pulse_length,
959 gb->apu.square_channels[1].pulse_length,
960 gb->apu.wave_channel.pulse_length,
961 gb->apu.noise_channel.pulse_length
962 };
963 if ((value & 0x80) && !gb->apu.global_enable) {
964 GB_apu_init(gb);
965 gb->apu.global_enable = true;
966 }
967 else if (!(value & 0x80) && gb->apu.global_enable) {
968 for (unsigned i = GB_N_CHANNELS; i--;) {
969 update_sample(gb, i, 0, 0);
970 }
971 memset(&gb->apu, 0, sizeof(gb->apu));
972 memset(gb->io_registers + GB_IO_NR10, 0, GB_IO_WAV_START - GB_IO_NR10);
973 gb->apu.global_enable = false;
974 }
975
976 if (!CGB && (value & 0x80)) {
977 gb->apu.square_channels[0].pulse_length = old_pulse_lengths[0];
978 gb->apu.square_channels[1].pulse_length = old_pulse_lengths[1];
979 gb->apu.wave_channel.pulse_length = old_pulse_lengths[2];
980 gb->apu.noise_channel.pulse_length = old_pulse_lengths[3];
981 }
982 }
983 break;
984
985 /* Square channels */
986 case GB_IO_NR10:{
987 bool old_negate = gb->io_registers[GB_IO_NR10] & 8;
988 gb->io_registers[GB_IO_NR10] = value;
989 if (gb->apu.shadow_sweep_sample_length + gb->apu.channel1_completed_addend + old_negate > 0x7FF &&
990 !(value & 8)) {
991 gb->apu.is_active[GB_SQUARE_1] = false;
992 update_sample(gb, GB_SQUARE_1, 0, 0);
993 }
994 trigger_sweep_calculation(gb);
995 break;
996 }
997
998 case GB_IO_NR11:
999 case GB_IO_NR21: {
1000 unsigned index = reg == GB_IO_NR21? GB_SQUARE_2: GB_SQUARE_1;
1001 gb->apu.square_channels[index].pulse_length = (0x40 - (value & 0x3f));
1002 if (!gb->apu.global_enable) {
1003 value &= 0x3f;
1004 }
1005 break;
1006 }
1007
1008 case GB_IO_NR12:
1009 case GB_IO_NR22: {
1010 unsigned index = reg == GB_IO_NR22? GB_SQUARE_2: GB_SQUARE_1;
1011 if ((value & 0xF8) == 0) {
1012 /* This disables the DAC */
1013 gb->io_registers[reg] = value;
1014 gb->apu.is_active[index] = false;
1015 update_sample(gb, index, 0, 0);
1016 }
1017 else if (gb->apu.is_active[index]) {
1018 nrx2_glitch(gb, &gb->apu.square_channels[index].current_volume,
1019 value, gb->io_registers[reg], &gb->apu.square_channels[index].volume_countdown,
1020 &gb->apu.square_envelope_clock[index]);
1021 update_square_sample(gb, index);
1022 }
1023
1024 break;
1025 }
1026
1027 case GB_IO_NR13:
1028 case GB_IO_NR23: {
1029 unsigned index = reg == GB_IO_NR23? GB_SQUARE_2: GB_SQUARE_1;
1030 gb->apu.square_channels[index].sample_length &= ~0xFF;
1031 gb->apu.square_channels[index].sample_length |= value & 0xFF;
1032 break;
1033 }
1034
1035 case GB_IO_NR14:
1036 case GB_IO_NR24: {
1037 /* TODO: GB_MODEL_CGB_D fails channel_1_sweep_restart_2, don't forget when adding support for this revision! */
1038 unsigned index = reg == GB_IO_NR24? GB_SQUARE_2: GB_SQUARE_1;
1039 bool was_active = gb->apu.is_active[index];
1040 /* TODO: When the sample length changes right before being updated, the countdown should change to the
1041 old length, but the current sample should not change. Because our write timing isn't accurate to
1042 the T-cycle, we hack around it by stepping the sample index backwards. */
1043 if ((value & 0x80) == 0 && gb->apu.is_active[index]) {
1044 /* On an AGB, as well as on CGB C and earlier (TODO: Tested: 0, B and C), it behaves slightly different on
1045 double speed. */
1046 if (gb->model == GB_MODEL_CGB_E /* || gb->model == GB_MODEL_CGB_D */ || gb->apu.square_channels[index].sample_countdown & 1) {
1047 if (gb->apu.square_channels[index].sample_countdown >> 1 == (gb->apu.square_channels[index].sample_length ^ 0x7FF)) {
1048 gb->apu.square_channels[index].current_sample_index--;
1049 gb->apu.square_channels[index].current_sample_index &= 7;
1050 }
1051 }
1052 }
1053
1054 uint16_t old_sample_length = gb->apu.square_channels[index].sample_length;
1055 gb->apu.square_channels[index].sample_length &= 0xFF;
1056 gb->apu.square_channels[index].sample_length |= (value & 7) << 8;
1057 if (value & 0x80) {
1058 /* Current sample index remains unchanged when restarting channels 1 or 2. It is only reset by
1059 turning the APU off. */
1060 gb->apu.square_envelope_clock[index].locked = false;
1061 gb->apu.square_envelope_clock[index].clock = false;
1062 if (!gb->apu.is_active[index]) {
1063 gb->apu.square_channels[index].sample_countdown = (gb->apu.square_channels[index].sample_length ^ 0x7FF) * 2 + 6 - gb->apu.lf_div;
1064 if (gb->model <= GB_MODEL_CGB_C && gb->apu.lf_div) {
1065 gb->apu.square_channels[index].sample_countdown += 2;
1066 }
1067 }
1068 else {
1069 unsigned extra_delay = 0;
1070 if (gb->model == GB_MODEL_CGB_E /* || gb->model == GB_MODEL_CGB_D */) {
1071 if (!(value & 4) && !(((gb->apu.square_channels[index].sample_countdown - 1) / 2) & 0x400)) {
1072 gb->apu.square_channels[index].current_sample_index++;
1073 gb->apu.square_channels[index].current_sample_index &= 0x7;
1074 gb->apu.is_active[index] = true;
1075 }
1076 /* Todo: verify with the schematics what's going on in here */
1077 else if (gb->apu.square_channels[index].sample_length == 0x7FF &&
1078 old_sample_length != 0x7FF &&
1079 (gb->apu.square_channels[index].current_sample_index & 0x80)) {
1080 extra_delay += 2;
1081 }
1082 }
1083 /* Timing quirk: if already active, sound starts 2 (2MHz) ticks earlier.*/
1084 gb->apu.square_channels[index].sample_countdown = (gb->apu.square_channels[index].sample_length ^ 0x7FF) * 2 + 4 - gb->apu.lf_div + extra_delay;
1085 if (gb->model <= GB_MODEL_CGB_C && gb->apu.lf_div) {
1086 gb->apu.square_channels[index].sample_countdown += 2;
1087 }
1088 }
1089 gb->apu.square_channels[index].current_volume = gb->io_registers[index == GB_SQUARE_1 ? GB_IO_NR12 : GB_IO_NR22] >> 4;
1090 /* The volume changes caused by NRX4 sound start take effect instantly (i.e. the effect the previously
1091 started sound). The playback itself is not instant which is why we don't update the sample for other
1092 cases. */
1093 if (gb->apu.is_active[index]) {
1094 update_square_sample(gb, index);
1095 }
1096
1097 gb->apu.square_channels[index].volume_countdown = gb->io_registers[index == GB_SQUARE_1 ? GB_IO_NR12 : GB_IO_NR22] & 7;
1098
1099 if ((gb->io_registers[index == GB_SQUARE_1 ? GB_IO_NR12 : GB_IO_NR22] & 0xF8) != 0 && !gb->apu.is_active[index]) {
1100 gb->apu.is_active[index] = true;
1101 update_sample(gb, index, 0, 0);
1102 /* We use the highest bit in current_sample_index to mark this sample is not actually playing yet, */
1103 gb->apu.square_channels[index].current_sample_index |= 0x80;
1104 }
1105 if (gb->apu.square_channels[index].pulse_length == 0) {
1106 gb->apu.square_channels[index].pulse_length = 0x40;
1107 gb->apu.square_channels[index].length_enabled = false;
1108 }
1109
1110 if (index == GB_SQUARE_1) {
1111 gb->apu.shadow_sweep_sample_length = 0;
1112 gb->apu.channel1_completed_addend = 0;
1113 if (gb->io_registers[GB_IO_NR10] & 7) {
1114 /* APU bug: if shift is nonzero, overflow check also occurs on trigger */
1115 gb->apu.square_sweep_calculate_countdown = (gb->io_registers[GB_IO_NR10] & 0x7) * 2 + 5 - gb->apu.lf_div;
1116 if (gb->model <= GB_MODEL_CGB_C && gb->apu.lf_div) {
1117 /* TODO: I used to think this is correct, but it caused several regressions.
1118 More research is needed to figure how calculation time is different
1119 in models prior to CGB-D */
1120 // gb->apu.square_sweep_calculate_countdown += 2;
1121 }
1122 gb->apu.enable_zombie_calculate_stepping = false;
1123 gb->apu.unshifted_sweep = false;
1124 if (!was_active) {
1125 gb->apu.square_sweep_calculate_countdown += 2;
1126 }
1127 gb->apu.sweep_length_addend = gb->apu.square_channels[GB_SQUARE_1].sample_length;
1128 gb->apu.sweep_length_addend >>= (gb->io_registers[GB_IO_NR10] & 7);
1129 }
1130 else {
1131 gb->apu.sweep_length_addend = 0;
1132 }
1133 gb->apu.channel_1_restart_hold = 2 - gb->apu.lf_div + CGB * 2;
1134 if (gb->model <= GB_MODEL_CGB_C && gb->apu.lf_div) {
1135 gb->apu.channel_1_restart_hold += 2;
1136 }
1137 gb->apu.square_sweep_countdown = ((gb->io_registers[GB_IO_NR10] >> 4) & 7) ^ 7;
1138 }
1139 }
1140
1141 /* APU glitch - if length is enabled while the DIV-divider's LSB is 1, tick the length once. */
1142 if ((value & 0x40) &&
1143 !gb->apu.square_channels[index].length_enabled &&
1144 (gb->apu.div_divider & 1) &&
1145 gb->apu.square_channels[index].pulse_length) {
1146 gb->apu.square_channels[index].pulse_length--;
1147 if (gb->apu.square_channels[index].pulse_length == 0) {
1148 if (value & 0x80) {
1149 gb->apu.square_channels[index].pulse_length = 0x3F;
1150 }
1151 else {
1152 gb->apu.is_active[index] = false;
1153 update_sample(gb, index, 0, 0);
1154 }
1155 }
1156 }
1157 gb->apu.square_channels[index].length_enabled = value & 0x40;
1158 break;
1159 }
1160
1161 /* Wave channel */
1162 case GB_IO_NR30:
1163 gb->apu.wave_channel.enable = value & 0x80;
1164 if (!gb->apu.wave_channel.enable) {
1165 gb->apu.is_active[GB_WAVE] = false;
1166 update_sample(gb, GB_WAVE, 0, 0);
1167 }
1168 if (gb->model==GB_MODEL_AGB_NATIVE) {
1169 gb->apu.wave_channel.bank_select = value & 0x40;
1170 gb->apu.wave_channel.double_length = value & 0x20;
1171 }
1172 break;
1173 case GB_IO_NR31:
1174 gb->apu.wave_channel.pulse_length = (0x100 - value);
1175 break;
1176 case GB_IO_NR32:
1177 gb->apu.wave_channel.shift = (uint8_t[]){4, 0, 1, 2}[(value >> 5) & 3];
1178 if (gb->model==GB_MODEL_AGB_NATIVE) {
1179 gb->apu.wave_channel.force_3 = value & 0x80;
1180 }
1181 if (gb->apu.is_active[GB_WAVE]) {
1182 int8_t sample = gb->apu.wave_channel.force_3 ?
1183 (gb->apu.wave_channel.current_sample * 3) >> 2 :
1184 gb->apu.wave_channel.current_sample >> gb->apu.wave_channel.shift;
1185 update_sample(gb, GB_WAVE, sample, 0);
1186 }
1187 break;
1188 case GB_IO_NR33:
1189 gb->apu.wave_channel.sample_length &= ~0xFF;
1190 gb->apu.wave_channel.sample_length |= value & 0xFF;
1191 break;
1192 case GB_IO_NR34:
1193 gb->apu.wave_channel.sample_length &= 0xFF;
1194 gb->apu.wave_channel.sample_length |= (value & 7) << 8;
1195 if ((value & 0x80)) {
1196 /* DMG bug: wave RAM gets corrupted if the channel is retriggerred 1 cycle before the APU
1197 reads from it. */
1198 if (!CGB &&
1199 gb->apu.is_active[GB_WAVE] &&
1200 gb->apu.wave_channel.sample_countdown == 0 &&
1201 gb->apu.wave_channel.enable) {
1202 unsigned offset = ((gb->apu.wave_channel.current_sample_index + 1) >> 1) & 0xF;
1203
1204 /* This glitch varies between models and even specific instances:
1205 DMG-B: Most of them behave as emulated. A few behave differently.
1206 SGB: As far as I know, all tested instances behave as emulated.
1207 MGB, SGB2: Most instances behave non-deterministically, a few behave as emulated.
1208
1209 Additionally, I believe DMGs, including those we behave differently than emulated,
1210 are all deterministic. */
1211 if (offset < 4) {
1212 gb->io_registers[GB_IO_WAV_START] = gb->io_registers[GB_IO_WAV_START + offset];
1213 gb->apu.wave_channel.wave_form[0] = gb->apu.wave_channel.wave_form[offset / 2];
1214 gb->apu.wave_channel.wave_form[1] = gb->apu.wave_channel.wave_form[offset / 2 + 1];
1215 }
1216 else {
1217 memcpy(gb->io_registers + GB_IO_WAV_START,
1218 gb->io_registers + GB_IO_WAV_START + (offset & ~3),
1219 4);
1220 memcpy(gb->apu.wave_channel.wave_form,
1221 gb->apu.wave_channel.wave_form + (offset & ~3) * 2,
1222 8);
1223 }
1224 }
1225 if (!gb->apu.is_active[GB_WAVE]) {
1226 gb->apu.is_active[GB_WAVE] = true;
1227 int8_t sample = gb->apu.wave_channel.force_3 ?
1228 (gb->apu.wave_channel.current_sample * 3) >> 2 :
1229 gb->apu.wave_channel.current_sample >> gb->apu.wave_channel.shift;
1230 update_sample(gb, GB_WAVE, sample, 0);
1231 }
1232 gb->apu.wave_channel.sample_countdown = (gb->apu.wave_channel.sample_length ^ 0x7FF) + 3;
1233 gb->apu.wave_channel.current_sample_index = 0;
1234 if (gb->apu.wave_channel.pulse_length == 0) {
1235 gb->apu.wave_channel.pulse_length = 0x100;
1236 gb->apu.wave_channel.length_enabled = false;
1237 }
1238 /* Note that we don't change the sample just yet! This was verified on hardware. */
1239 }
1240
1241 /* APU glitch - if length is enabled while the DIV-divider's LSB is 1, tick the length once. */
1242 if ((value & 0x40) &&
1243 !gb->apu.wave_channel.length_enabled &&
1244 (gb->apu.div_divider & 1) &&
1245 gb->apu.wave_channel.pulse_length) {
1246 gb->apu.wave_channel.pulse_length--;
1247 if (gb->apu.wave_channel.pulse_length == 0) {
1248 if (value & 0x80) {
1249 gb->apu.wave_channel.pulse_length = 0xFF;
1250 }
1251 else {
1252 gb->apu.is_active[GB_WAVE] = false;
1253 update_sample(gb, GB_WAVE, 0, 0);
1254 }
1255 }
1256 }
1257 gb->apu.wave_channel.length_enabled = value & 0x40;
1258 if (gb->apu.is_active[GB_WAVE] && !gb->apu.wave_channel.enable) {
1259 gb->apu.is_active[GB_WAVE] = false;
1260 update_sample(gb, GB_WAVE, 0, 0);
1261 }
1262
1263 break;
1264
1265 /* Noise Channel */
1266
1267 case GB_IO_NR41: {
1268 gb->apu.noise_channel.pulse_length = (0x40 - (value & 0x3f));
1269 break;
1270 }
1271
1272 case GB_IO_NR42: {
1273 if ((value & 0xF8) == 0) {
1274 /* This disables the DAC */
1275 gb->io_registers[reg] = value;
1276 gb->apu.is_active[GB_NOISE] = false;
1277 update_sample(gb, GB_NOISE, 0, 0);
1278 }
1279 else if (gb->apu.is_active[GB_NOISE]) {
1280 nrx2_glitch(gb, &gb->apu.noise_channel.current_volume,
1281 value, gb->io_registers[reg], &gb->apu.noise_channel.volume_countdown,
1282 &gb->apu.noise_envelope_clock);
1283 update_sample(gb, GB_NOISE,
1284 gb->apu.current_lfsr_sample ?
1285 gb->apu.noise_channel.current_volume : 0,
1286 0);
1287 }
1288 break;
1289 }
1290
1291 case GB_IO_NR43: {
1292 gb->apu.noise_channel.narrow = value & 8;
1293 uint16_t effective_counter = effective_channel4_counter(gb);
1294 bool old_bit = (effective_counter >> (gb->io_registers[GB_IO_NR43] >> 4)) & 1;
1295 gb->io_registers[GB_IO_NR43] = value;
1296 bool new_bit = (effective_counter >> (gb->io_registers[GB_IO_NR43] >> 4)) & 1;
1297 if (gb->apu.channel_4_countdown_reloaded) {
1298 unsigned divisor = (gb->io_registers[GB_IO_NR43] & 0x07) << 2;
1299 if (!divisor) divisor = 2;
1300 if (gb->model > GB_MODEL_CGB_C) {
1301 gb->apu.noise_channel.counter_countdown =
1302 divisor + (divisor == 2? 0 : (uint8_t[]){2, 1, 0, 3}[(gb->apu.noise_channel.alignment) & 3]);
1303 }
1304 else {
1305 gb->apu.noise_channel.counter_countdown =
1306 divisor + (divisor == 2? 0 : (uint8_t[]){2, 1, 4, 3}[(gb->apu.noise_channel.alignment) & 3]);
1307 }
1308 gb->apu.channel_4_delta = 0;
1309 }
1310 /* Step LFSR */
1311 if (new_bit && (!old_bit || gb->model <= GB_MODEL_CGB_C)) {
1312 if (gb->model <= GB_MODEL_CGB_C) {
1313 bool previous_narrow = gb->apu.noise_channel.narrow;
1314 gb->apu.noise_channel.narrow = true;
1315 step_lfsr(gb, 0);
1316 gb->apu.noise_channel.narrow = previous_narrow;
1317 }
1318 else {
1319 step_lfsr(gb, 0);
1320 }
1321 }
1322 break;
1323 }
1324
1325 case GB_IO_NR44: {
1326 if (value & 0x80) {
1327 gb->apu.noise_envelope_clock.locked = false;
1328 gb->apu.noise_envelope_clock.clock = false;
1329 if (!CGB && (gb->apu.noise_channel.alignment & 3) != 0) {
1330 gb->apu.channel_4_dmg_delayed_start = 6;
1331 }
1332 else {
1333 unsigned divisor = (gb->io_registers[GB_IO_NR43] & 0x07) << 2;
1334 if (!divisor) divisor = 2;
1335 gb->apu.channel_4_delta = 0;
1336 gb->apu.noise_channel.counter_countdown = divisor + 4;
1337 if (divisor == 2) {
1338 if (gb->model <= GB_MODEL_CGB_C) {
1339 gb->apu.noise_channel.counter_countdown += gb->apu.lf_div;
1340 if (!gb->cgb_double_speed) {
1341 gb->apu.noise_channel.counter_countdown -= 1;
1342 }
1343 }
1344 else {
1345 gb->apu.noise_channel.counter_countdown += 1 - gb->apu.lf_div;
1346 }
1347 }
1348 else {
1349 if (gb->model <= GB_MODEL_CGB_C) {
1350 gb->apu.noise_channel.counter_countdown += (uint8_t[]){2, 1, 4, 3}[gb->apu.noise_channel.alignment & 3];
1351 }
1352 else {
1353 gb->apu.noise_channel.counter_countdown += (uint8_t[]){2, 1, 0, 3}[gb->apu.noise_channel.alignment & 3];
1354 }
1355 if (((gb->apu.noise_channel.alignment + 1) & 3) < 2) {
1356 if ((gb->io_registers[GB_IO_NR43] & 0x07) == 1) {
1357 gb->apu.noise_channel.counter_countdown -= 2;
1358 gb->apu.channel_4_delta = 2;
1359 }
1360 else {
1361 gb->apu.noise_channel.counter_countdown -= 4;
1362 }
1363 }
1364 }
1365
1366 /* TODO: These are quite weird. Verify further */
1367 if (gb->model <= GB_MODEL_CGB_C) {
1368 if (gb->cgb_double_speed) {
1369 if (!(gb->io_registers[GB_IO_NR43] & 0xF0) && (gb->io_registers[GB_IO_NR43] & 0x07)) {
1370 gb->apu.noise_channel.counter_countdown -= 1;
1371 }
1372 else if ((gb->io_registers[GB_IO_NR43] & 0xF0) && !(gb->io_registers[GB_IO_NR43] & 0x07)) {
1373 gb->apu.noise_channel.counter_countdown += 1;
1374 }
1375 }
1376 else {
1377 gb->apu.noise_channel.counter_countdown -= 2;
1378 }
1379 }
1380
1381 gb->apu.noise_channel.current_volume = gb->io_registers[GB_IO_NR42] >> 4;
1382
1383 /* The volume changes caused by NRX4 sound start take effect instantly (i.e. the effect the previously
1384 started sound). The playback itself is not instant which is why we don't update the sample for other
1385 cases. */
1386 if (gb->apu.is_active[GB_NOISE]) {
1387 update_sample(gb, GB_NOISE,
1388 gb->apu.current_lfsr_sample ?
1389 gb->apu.noise_channel.current_volume : 0,
1390 0);
1391 }
1392 gb->apu.noise_channel.lfsr = 0;
1393 gb->apu.current_lfsr_sample = false;
1394 gb->apu.noise_channel.volume_countdown = gb->io_registers[GB_IO_NR42] & 7;
1395
1396 if (!gb->apu.is_active[GB_NOISE] && (gb->io_registers[GB_IO_NR42] & 0xF8) != 0) {
1397 gb->apu.is_active[GB_NOISE] = true;
1398 update_sample(gb, GB_NOISE, 0, 0);
1399 }
1400
1401 if (gb->apu.noise_channel.pulse_length == 0) {
1402 gb->apu.noise_channel.pulse_length = 0x40;
1403 gb->apu.noise_channel.length_enabled = false;
1404 }
1405 }
1406 }
1407
1408 /* APU glitch - if length is enabled while the DIV-divider's LSB is 1, tick the length once. */
1409 if ((value & 0x40) &&
1410 !gb->apu.noise_channel.length_enabled &&
1411 (gb->apu.div_divider & 1) &&
1412 gb->apu.noise_channel.pulse_length) {
1413 gb->apu.noise_channel.pulse_length--;
1414 if (gb->apu.noise_channel.pulse_length == 0) {
1415 if (value & 0x80) {
1416 gb->apu.noise_channel.pulse_length = 0x3F;
1417 }
1418 else {
1419 gb->apu.is_active[GB_NOISE] = false;
1420 update_sample(gb, GB_NOISE, 0, 0);
1421 }
1422 }
1423 }
1424 gb->apu.noise_channel.length_enabled = value & 0x40;
1425 break;
1426 }
1427
1428 default:
1429 if (reg >= GB_IO_WAV_START && reg <= GB_IO_WAV_END) {
1430 uint8_t base = 0;
1431 if (gb->model == GB_MODEL_AGB_NATIVE &&
1432 (!gb->apu.global_enable || !gb->apu.wave_channel.bank_select)) {
1433 base = 32;
1434 }
1435 gb->apu.wave_channel.wave_form[base + (reg - GB_IO_WAV_START) * 2] = value >> 4;
1436 gb->apu.wave_channel.wave_form[base + (reg - GB_IO_WAV_START) * 2 + 1] = value & 0xF;
1437 }
1438 }
1439 gb->io_registers[reg] = value;
1440 }
1441
1442 void GB_set_sample_rate(GB_gameboy_t *gb, unsigned sample_rate)
1443 {
1444
1445 gb->apu_output.sample_rate = sample_rate;
1446 if (sample_rate) {
1447 gb->apu_output.highpass_rate = pow(0.999958, GB_CLOCK_RATE / (double)sample_rate);
1448 }
1449 gb->apu_output.rate_set_in_clocks = false;
1450 GB_apu_update_cycles_per_sample(gb);
1451 }
1452
1453 void GB_set_sample_rate_by_clocks(GB_gameboy_t *gb, double cycles_per_sample)
1454 {
1455
1456 if (cycles_per_sample == 0) {
1457 GB_set_sample_rate(gb, 0);
1458 return;
1459 }
1460 gb->apu_output.cycles_per_sample = cycles_per_sample;
1461 gb->apu_output.sample_rate = GB_CLOCK_RATE / cycles_per_sample * 2;
1462 gb->apu_output.highpass_rate = pow(0.999958, cycles_per_sample);
1463 gb->apu_output.rate_set_in_clocks = true;
1464 }
1465
1466 void GB_apu_set_sample_callback(GB_gameboy_t *gb, GB_sample_callback_t callback)
1467 {
1468 gb->apu_output.sample_callback = callback;
1469 }
1470
1471 void GB_set_highpass_filter_mode(GB_gameboy_t *gb, GB_highpass_mode_t mode)
1472 {
1473 gb->apu_output.highpass_mode = mode;
1474 }
1475
1476 void GB_apu_update_cycles_per_sample(GB_gameboy_t *gb)
1477 {
1478 if (gb->apu_output.rate_set_in_clocks) return;
1479 if (gb->apu_output.sample_rate) {
1480 gb->apu_output.cycles_per_sample = 2 * GB_CLOCK_RATE / (double)gb->apu_output.sample_rate; /* 2 * because we use 8MHz units */
1481 }
1482 }
1483
1484 void GB_set_interference_volume(GB_gameboy_t *gb, double volume)
1485 {
1486 gb->apu_output.interference_volume = volume;
1487 }