SameBoy | Accurate GB/GBC emulator |
| download: https://git.y1.nz/archives/sameboy.tar.gz | |
| README | Files | Log | Refs | LICENSE |
Core/apu.c
1 #include <stdint.h>
2 #include <math.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <errno.h>
6 #include <stdlib.h>
7 #include "gb.h"
8
9 /* Band limited synthesis loosely based on: http://www.slack.net/~ant/bl-synth/ */
10 static int32_t band_limited_steps[GB_BAND_LIMITED_PHASES][GB_BAND_LIMITED_WIDTH];
11
12 static void __attribute__((constructor)) band_limited_init(void)
13 {
14 const unsigned master_size = GB_BAND_LIMITED_WIDTH * GB_BAND_LIMITED_PHASES;
15 double *master = malloc(master_size * sizeof(*master));
16 memset(master, 0, master_size * sizeof(*master));
17
18 const double lowpass = 15.0 / 16.0; // 1.0 means using Nyquist as the exact cutoff
19 const double to_angle = M_PI / GB_BAND_LIMITED_PHASES * lowpass;
20 double sum = 0;
21 nounroll for (signed i = 0; i < master_size; i++) {
22 // Exact Blackman window
23 const double a0 = 7938 / 18608.0;
24 const double a1 = 9240 / 18608.0;
25 const double a2 = 1430 / 18608.0;
26 double window_angle = (2.0 * M_PI * i) / (master_size);
27 double window = a0 - a1 * cos(window_angle) + a2 * cos(2 * window_angle);
28
29 double angle = (i - (signed)master_size / 2) * to_angle;
30 sum += master[i] = (angle == 0? 1 : sin(angle) / angle) * window;
31 }
32
33 nounroll for (signed i = 0; i < master_size; i++) {
34 master[i] /= sum;
35 }
36
37 nounroll for (signed phase = 0; phase < GB_BAND_LIMITED_PHASES; phase++) {
38 int32_t error = GB_BAND_LIMITED_ONE;
39 nounroll for (signed i = 0; i < GB_BAND_LIMITED_WIDTH; i++) {
40 double sum = 0;
41 nounroll for (signed j = 0; j < GB_BAND_LIMITED_PHASES; j++) {
42 signed index = i * GB_BAND_LIMITED_PHASES - phase + j;
43 if (index >= 0) {
44 sum += master[index];
45 }
46 }
47 int32_t cur = sum * GB_BAND_LIMITED_ONE;
48 error -= cur;
49 band_limited_steps[phase][i] = cur;
50 }
51
52 // Make sure the deltas sum to 1.0
53 band_limited_steps[phase][GB_BAND_LIMITED_WIDTH / 2] += error;
54 }
55 free(master);
56 }
57
58 static void band_limited_update(GB_band_limited_t *band_limited, const GB_sample_t *input, unsigned phase)
59 {
60 if (input->packed == band_limited->input.packed) return;
61 unsigned delay = phase / GB_BAND_LIMITED_PHASES;
62 phase = phase & (GB_BAND_LIMITED_PHASES - 1);
63
64 struct {
65 signed left, right;
66 } delta = {
67 .left = input->left - band_limited->input.left,
68 .right = input->right - band_limited->input.right,
69 };
70 band_limited->input.packed = input->packed;
71
72 for (unsigned i = 0; i < GB_BAND_LIMITED_WIDTH; i++) {
73 unsigned offset = (i + band_limited->pos + delay) & (sizeof(band_limited->buffer) / sizeof(band_limited->buffer[0]) - 1);
74 band_limited->buffer[offset].left += delta.left * band_limited_steps[phase][i];
75 band_limited->buffer[offset].right += delta.right * band_limited_steps[phase][i];
76 }
77 }
78
79 static void band_limited_update_unfiltered(GB_band_limited_t *band_limited, const GB_sample_t *input, unsigned delay)
80 {
81 if (input->packed == band_limited->input.packed) return;
82
83 struct {
84 signed left, right;
85 } delta = {
86 .left = input->left - band_limited->input.left,
87 .right = input->right - band_limited->input.right,
88 };
89 band_limited->input.packed = input->packed;
90
91 unsigned offset = (band_limited->pos + delay) & (sizeof(band_limited->buffer) / sizeof(band_limited->buffer[0]) - 1);
92 band_limited->buffer[offset].left += delta.left * GB_BAND_LIMITED_ONE;
93 band_limited->buffer[offset].right += delta.right * GB_BAND_LIMITED_ONE;
94 }
95
96 static void band_limited_read(GB_band_limited_t *band_limited, GB_sample_t *output, uint32_t multiplier)
97 {
98 band_limited->output.left += band_limited->buffer[band_limited->pos].left;
99 band_limited->output.right += band_limited->buffer[band_limited->pos].right;
100
101 band_limited->buffer[band_limited->pos].left = band_limited->buffer[band_limited->pos].right = 0;
102 band_limited->pos = (band_limited->pos + 1) & (sizeof(band_limited->buffer) / sizeof(band_limited->buffer[0]) - 1);
103
104 output->left = band_limited->output.left * multiplier / GB_BAND_LIMITED_ONE;
105 output->right = band_limited->output.right * multiplier / GB_BAND_LIMITED_ONE;
106
107 /* This hueristic will mute the channel if it's only playing an amplitude of 1 or 2 units, usually
108 caused by rounding errors when the channel is playing a single frequency above Nyquist. */
109
110 unsigned diff = abs(output->left - band_limited->last_output.left);
111 if (diff > 4) {
112 band_limited->silence_detection = 0;
113 band_limited->last_output.packed = output->packed;
114 return;
115 }
116
117 diff = abs(output->right - band_limited->last_output.right);
118 if (diff > 4) {
119 band_limited->silence_detection = 0;
120 band_limited->last_output.packed = output->packed;
121 return;
122 }
123
124 if (band_limited->silence_detection == 4000) {
125 output->packed = band_limited->last_output.packed;
126 }
127 else {
128 band_limited->silence_detection++;
129 }
130 }
131
132 static inline uint32_t sample_fraction_multiply(GB_gameboy_t *gb, unsigned multiplier)
133 {
134 if (unlikely(multiplier == 0)) return 0;
135 if (likely(multiplier < GB_QUICK_MULTIPLY_COUNT + 1)) {
136 return gb->apu_output.quick_fraction_multiply_cache[multiplier - 1];
137 }
138 return gb->apu_output.quick_fraction_multiply_cache[0] * multiplier;
139 }
140
141 static const uint8_t duties[] = {
142 0, 0, 0, 0, 0, 0, 0, 1,
143 1, 0, 0, 0, 0, 0, 0, 1,
144 1, 0, 0, 0, 0, 1, 1, 1,
145 0, 1, 1, 1, 1, 1, 1, 0,
146 };
147
148 bool GB_apu_is_DAC_enabled(GB_gameboy_t *gb, GB_channel_t index)
149 {
150 if (gb->model > GB_MODEL_CGB_E) {
151 /* On the AGB, mixing is done digitally, so there are no per-channel
152 DACs. Instead, all channels are summed digital regardless of
153 whatever the DAC state would be on a CGB or earlier model. */
154 return true;
155 }
156
157 switch (index) {
158 case GB_SQUARE_1:
159 return gb->io_registers[GB_IO_NR12] & 0xF8;
160
161 case GB_SQUARE_2:
162 return gb->io_registers[GB_IO_NR22] & 0xF8;
163
164 case GB_WAVE:
165 return gb->apu.wave_channel.enable;
166
167 case GB_NOISE:
168 return gb->io_registers[GB_IO_NR42] & 0xF8;
169
170 nodefault;
171 }
172
173 return false;
174 }
175
176 static uint8_t agb_bias_for_channel(GB_gameboy_t *gb, GB_channel_t index)
177 {
178 if (!gb->apu.is_active[index]) return 0;
179
180 switch (index) {
181 case GB_SQUARE_1:
182 return gb->apu.square_channels[GB_SQUARE_1].current_volume;
183 case GB_SQUARE_2:
184 return gb->apu.square_channels[GB_SQUARE_2].current_volume;
185 case GB_WAVE:
186 return 0;
187 case GB_NOISE:
188 return gb->apu.noise_channel.current_volume;
189
190 nodefault;
191 }
192 }
193
194 static void update_sample(GB_gameboy_t *gb, GB_channel_t index, int8_t value, unsigned cycles_offset)
195 {
196 if (gb->model > GB_MODEL_CGB_E) {
197 /* On the AGB, because no analog mixing is done, the behavior of NR51 is a bit different.
198 A channel that is not connected to a terminal is idenitcal to a connected channel
199 playing PCM sample 0. */
200 gb->apu.samples[index] = value;
201
202 if (gb->apu_output.sample_rate) {
203 unsigned right_volume = (gb->io_registers[GB_IO_NR50] & 7) + 1;
204 unsigned left_volume = ((gb->io_registers[GB_IO_NR50] >> 4) & 7) + 1;
205 int8_t silence = 0;
206 if (index == GB_WAVE) {
207 /* For some reason, channel 3 is inverted on the AGB, and has a different "silence" value */
208 value ^= 0xF;
209 silence = 7 * 2;
210 }
211
212 uint8_t bias = agb_bias_for_channel(gb, index);
213
214 bool left = gb->io_registers[GB_IO_NR51] & (0x10 << index);
215 bool right = gb->io_registers[GB_IO_NR51] & (1 << index);
216
217 GB_sample_t output = {
218 .left = (0xF - (left? value * 2 + bias : silence)) * left_volume,
219 .right = (0xF - (right? value * 2 + bias : silence)) * right_volume
220 };
221
222 if (unlikely(gb->apu_output.channel_muted[index])) {
223 output.left = output.right = 0;
224 }
225
226 if (unlikely(gb->apu_output.max_cycles_per_sample == 1)) {
227 band_limited_update_unfiltered(&gb->apu_output.band_limited[index], &output, cycles_offset);
228 }
229 else {
230 band_limited_update(&gb->apu_output.band_limited[index],
231 &output,
232 (((gb->apu_output.sample_fraction + sample_fraction_multiply(gb, cycles_offset)) >> 8) * GB_BAND_LIMITED_PHASES) >> 20);
233 }
234 }
235
236 return;
237 }
238
239 if (value == 0 && gb->apu.samples[index] == 0) return;
240
241 if (!GB_apu_is_DAC_enabled(gb, index)) {
242 value = gb->apu.samples[index];
243 }
244 else {
245 gb->apu.samples[index] = value;
246 }
247
248 if (gb->apu_output.sample_rate) {
249 unsigned right_volume = 0;
250 if (gb->io_registers[GB_IO_NR51] & (1 << index)) {
251 right_volume = (gb->io_registers[GB_IO_NR50] & 7) + 1;
252 }
253 unsigned left_volume = 0;
254 if (gb->io_registers[GB_IO_NR51] & (0x10 << index)) {
255 left_volume = ((gb->io_registers[GB_IO_NR50] >> 4) & 7) + 1;
256 }
257 GB_sample_t output = {0, 0};
258 if (likely(!gb->apu_output.channel_muted[index])) {
259 output = (GB_sample_t){(0xF - value * 2) * left_volume, (0xF - value * 2) * right_volume};
260 }
261 if (unlikely(gb->apu_output.max_cycles_per_sample == 1)) {
262 band_limited_update_unfiltered(&gb->apu_output.band_limited[index], &output, cycles_offset);
263 }
264 else {
265 band_limited_update(&gb->apu_output.band_limited[index],
266 &output,
267 (((gb->apu_output.sample_fraction + sample_fraction_multiply(gb, cycles_offset)) >> 8) * GB_BAND_LIMITED_PHASES) >> 20);
268 }
269 }
270 }
271
272 static double smooth(double x)
273 {
274 return 3*x*x - 2*x*x*x;
275 }
276
277 static signed interference(GB_gameboy_t *gb)
278 {
279 /* These aren't scientifically measured, but based on ear based on several recordings */
280 signed ret = 0;
281 if (gb->halted) {
282 if (gb->model <= GB_MODEL_CGB_E) {
283 ret -= MAX_CH_AMP / 5;
284 }
285 else {
286 ret -= MAX_CH_AMP / 12;
287 }
288 }
289 if (gb->io_registers[GB_IO_LCDC] & GB_LCDC_ENABLE) {
290 ret += MAX_CH_AMP / 7;
291 if ((gb->io_registers[GB_IO_STAT] & 3) == 3 && gb->model <= GB_MODEL_CGB_E) {
292 ret += MAX_CH_AMP / 14;
293 }
294 else if ((gb->io_registers[GB_IO_STAT] & 3) == 1) {
295 ret -= MAX_CH_AMP / 7;
296 }
297 }
298
299 if (gb->apu.global_enable) {
300 ret += MAX_CH_AMP / 10;
301 }
302
303 if (GB_is_cgb(gb) && gb->model <= GB_MODEL_CGB_E && (gb->io_registers[GB_IO_RP] & 1)) {
304 ret += MAX_CH_AMP / 10;
305 }
306
307 if (!GB_is_cgb(gb)) {
308 ret /= 4;
309 }
310
311 ret += rand() % (MAX_CH_AMP / 12);
312
313 return ret;
314 }
315
316 static void render(GB_gameboy_t *gb)
317 {
318 GB_sample_t output = {0, 0};
319
320 unrolled for (unsigned i = 0; i < GB_N_CHANNELS; i++) {
321 double multiplier = CH_STEP;
322
323 if (gb->model <= GB_MODEL_CGB_E) {
324 if (!GB_apu_is_DAC_enabled(gb, i)) {
325 gb->apu_output.dac_discharge[i] -= ((double) DAC_DECAY_SPEED) / gb->apu_output.sample_rate;
326 if (gb->apu_output.dac_discharge[i] < 0) {
327 multiplier = 0;
328 gb->apu_output.dac_discharge[i] = 0;
329 }
330 else {
331 multiplier *= smooth(gb->apu_output.dac_discharge[i]);
332 }
333 }
334 else {
335 gb->apu_output.dac_discharge[i] += ((double) DAC_ATTACK_SPEED) / gb->apu_output.sample_rate;
336 if (gb->apu_output.dac_discharge[i] > 1) {
337 gb->apu_output.dac_discharge[i] = 1;
338 }
339 else {
340 multiplier *= smooth(gb->apu_output.dac_discharge[i]);
341 }
342 }
343 }
344
345 GB_sample_t channel_output;
346 band_limited_read(&gb->apu_output.band_limited[i], &channel_output, multiplier);
347
348 output.left += channel_output.left;
349 output.right += channel_output.right;
350 }
351 gb->apu_output.cycles_since_render = 0;
352 if (unlikely(gb->apu_output.sample_fraction < (1 << 28))) {
353 gb->apu_output.sample_fraction = 0;
354 }
355 else {
356 gb->apu_output.sample_fraction -= 1 << 28;
357 }
358
359 if (gb->sgb && gb->sgb->intro_animation < GB_SGB_INTRO_ANIMATION_LENGTH) return;
360
361 GB_sample_t filtered_output = gb->apu_output.highpass_mode?
362 (GB_sample_t) {output.left - (int16_t)gb->apu_output.highpass_diff.left,
363 output.right - (int16_t)gb->apu_output.highpass_diff.right} :
364 output;
365
366 switch (gb->apu_output.highpass_mode) {
367 case GB_HIGHPASS_OFF:
368 gb->apu_output.highpass_diff = (GB_double_sample_t) {0, 0};
369 break;
370 case GB_HIGHPASS_ACCURATE:
371 gb->apu_output.highpass_diff = (GB_double_sample_t) {
372 output.left - (output.left - gb->apu_output.highpass_diff.left) * gb->apu_output.highpass_rate,
373 output.right - (output.right - gb->apu_output.highpass_diff.right) * gb->apu_output.highpass_rate
374 };
375 break;
376 case GB_HIGHPASS_REMOVE_DC_OFFSET: {
377 unsigned mask = gb->io_registers[GB_IO_NR51];
378 unsigned left_volume = 0;
379 unsigned right_volume = 0;
380 unrolled for (unsigned i = GB_N_CHANNELS; i--;) {
381 if (GB_apu_is_DAC_enabled(gb, i)) {
382 if (mask & 1) {
383 left_volume += ((gb->io_registers[GB_IO_NR50] & 7) + 1) * CH_STEP * 0xF;
384 }
385 if (mask & 0x10) {
386 right_volume += (((gb->io_registers[GB_IO_NR50] >> 4) & 7) + 1) * CH_STEP * 0xF;
387 }
388 }
389 mask >>= 1;
390 }
391 gb->apu_output.highpass_diff = (GB_double_sample_t) {
392 left_volume * (1 - gb->apu_output.highpass_rate) + gb->apu_output.highpass_diff.left * gb->apu_output.highpass_rate,
393 right_volume * (1 - gb->apu_output.highpass_rate) + gb->apu_output.highpass_diff.right * gb->apu_output.highpass_rate
394 };
395
396 case GB_HIGHPASS_MAX:;
397 }
398
399 }
400
401
402 if (gb->apu_output.interference_volume) {
403 signed interference_bias = interference(gb);
404 int16_t interference_sample = (interference_bias - gb->apu_output.interference_highpass);
405 gb->apu_output.interference_highpass = gb->apu_output.interference_highpass * gb->apu_output.highpass_rate +
406 (1 - gb->apu_output.highpass_rate) * interference_sample;
407 interference_bias *= gb->apu_output.interference_volume;
408
409 filtered_output.left = MAX(MIN(filtered_output.left + interference_bias, 0x7FFF), -0x8000);
410 filtered_output.right = MAX(MIN(filtered_output.right + interference_bias, 0x7FFF), -0x8000);
411 }
412 assert(gb->apu_output.sample_callback);
413 gb->apu_output.sample_callback(gb, &filtered_output);
414 if (unlikely(gb->apu_output.output_file)) {
415 #ifdef GB_BIG_ENDIAN
416 if (gb->apu_output.output_format == GB_AUDIO_FORMAT_WAV) {
417 filtered_output.left = LE16(filtered_output.left);
418 filtered_output.right = LE16(filtered_output.right);
419 }
420 #endif
421 if (fwrite(&filtered_output, sizeof(filtered_output), 1, gb->apu_output.output_file) != 1) {
422 fclose(gb->apu_output.output_file);
423 gb->apu_output.output_file = NULL;
424 gb->apu_output.output_error = errno;
425 }
426 }
427 }
428
429 static void update_square_sample(GB_gameboy_t *gb, GB_channel_t index, unsigned cycles)
430 {
431 if (gb->apu.square_channels[index].sample_surpressed) {
432 if (gb->model > GB_MODEL_CGB_E) {
433 update_sample(gb, index, gb->apu.samples[index], 0);
434 }
435 return;
436 }
437
438 uint8_t duty = gb->io_registers[index == GB_SQUARE_1? GB_IO_NR11 :GB_IO_NR21] >> 6;
439 update_sample(gb, index,
440 duties[gb->apu.square_channels[index].current_sample_index + duty * 8]?
441 gb->apu.square_channels[index].current_volume : 0,
442 cycles);
443 }
444
445 static inline void update_wave_sample(GB_gameboy_t *gb, unsigned cycles)
446 {
447 if (gb->apu.wave_channel.current_sample_index & 1) {
448 update_sample(gb, GB_WAVE,
449 (gb->apu.wave_channel.current_sample_byte & 0xF) >> gb->apu.wave_channel.shift,
450 cycles);
451 }
452 else {
453 update_sample(gb, GB_WAVE,
454 (gb->apu.wave_channel.current_sample_byte >> 4) >> gb->apu.wave_channel.shift,
455 cycles);
456 }
457 }
458
459 static inline void set_envelope_clock(GB_envelope_clock_t *clock, bool value, bool direction, uint8_t volume)
460 {
461 if (clock->clock == value) return;
462 if (value) {
463 clock->clock = true;
464 clock->should_lock = (volume == 0xF && direction) || (volume == 0x0 && !direction);
465 }
466 else {
467 clock->clock = false;
468 clock->locked |= clock->should_lock;
469 }
470 }
471
472 static void _nrx2_glitch(uint8_t *volume, uint8_t value, uint8_t old_value, uint8_t *countdown, GB_envelope_clock_t *lock)
473 {
474 if (lock->clock) {
475 *countdown = value & 7;
476 }
477 bool should_tick = (value & 7) && !(old_value & 7) && !lock->locked;
478 bool should_invert = (value & 8) ^ (old_value & 8);
479
480 if ((value & 0xF) == 8 && (old_value & 0xF) == 8 && !lock->locked) {
481 should_tick = true;
482 }
483
484 if (should_invert) {
485 // The weird and over-the-top way clocks for this counter are connected cause
486 // some weird ways for it to invert
487 if (value & 8) {
488 if (!(old_value & 7) && !lock->locked) {
489 *volume ^= 0xF;
490 }
491 else {
492 *volume = 0xE - *volume;
493 *volume &= 0xF;
494 }
495 should_tick = false; // Somehow prevents ticking?
496 }
497 else {
498 *volume = 0x10 - *volume;
499 *volume &= 0xF;
500 }
501 }
502 if (should_tick) {
503 if (value & 8) {
504 (*volume)++;
505 }
506 else {
507 (*volume)--;
508 }
509 *volume &= 0xF;
510 }
511 else if (!(value & 7) && lock->clock) {
512 set_envelope_clock(lock, false, 0, 0);
513 }
514 }
515
516 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)
517 {
518 /* Note: on pre-CGB models *some* of these are non-deterministic. Specifically,
519 $x0 writes seem to be non-deterministic while $x8 always work as expected.
520 TODO: Might be useful to find which cases are non-deterministic, and allow
521 the debugger to issue warnings when they're used. I suspect writes to/from
522 $xF are guaranteed to be deterministic. */
523 if (gb->model <= GB_MODEL_CGB_C) {
524 _nrx2_glitch(volume, 0xFF, old_value, countdown, lock);
525 _nrx2_glitch(volume, value, 0xFF, countdown, lock);
526 }
527 else {
528 _nrx2_glitch(volume, value, old_value, countdown, lock);
529 }
530 }
531
532 static void tick_square_envelope(GB_gameboy_t *gb, GB_channel_t index)
533 {
534 set_envelope_clock(&gb->apu.square_channels[index].envelope_clock, false, 0, 0);
535 if (gb->apu.square_channels[index].envelope_clock.locked) return;
536 uint8_t nrx2 = gb->io_registers[index == GB_SQUARE_1? GB_IO_NR12 : GB_IO_NR22];
537
538 if (!(nrx2 & 7)) return;
539 if (gb->cgb_double_speed) {
540 if (index == GB_SQUARE_1) {
541 gb->apu.pcm_mask[0] &= gb->apu.square_channels[GB_SQUARE_1].current_volume | 0xF1;
542 }
543 else {
544 /* Note: CGB-0 behavior is instance specific and non-deterministic. Emulated behavior follows my CGB-0,
545 except that my CGB-0 sometimes yields "1" for 8->7 and 4->3 transitions. */
546 uint8_t mask;
547 if (unlikely(gb->model == GB_MODEL_CGB_0)) {
548 if (gb->apu.square_channels[GB_SQUARE_2].current_volume == 1 && (gb->io_registers[GB_IO_NR22] & 8)) {
549 mask = 0x1F;
550 }
551 else {
552 mask = 0x3F;
553 }
554 }
555 else {
556 mask = 0x3F;
557 }
558 gb->apu.pcm_mask[0] &= (gb->apu.square_channels[GB_SQUARE_2].current_volume << 4) | mask;
559 }
560 }
561
562 set_envelope_clock(&gb->apu.square_channels[index].envelope_clock, false, 0, 0);
563
564 if (nrx2 & 8) {
565 gb->apu.square_channels[index].current_volume++;
566 }
567 else {
568 gb->apu.square_channels[index].current_volume--;
569 }
570
571 if (gb->apu.is_active[index]) {
572 update_square_sample(gb, index, 0);
573 }
574 }
575
576 static void tick_noise_envelope(GB_gameboy_t *gb)
577 {
578 set_envelope_clock(&gb->apu.noise_channel.envelope_clock, false, 0, 0);
579 if (gb->apu.noise_channel.envelope_clock.locked) return;
580
581 uint8_t nr42 = gb->io_registers[GB_IO_NR42];
582 if (!(nr42 & 7)) return;
583
584 if (gb->cgb_double_speed) {
585 gb->apu.pcm_mask[1] &= (gb->apu.noise_channel.current_volume << 4) | 0x1F;
586 }
587
588 if (nr42 & 8) {
589 gb->apu.noise_channel.current_volume++;
590 }
591 else {
592 gb->apu.noise_channel.current_volume--;
593 }
594
595 if (gb->apu.is_active[GB_NOISE]) {
596 update_sample(gb, GB_NOISE,
597 (gb->apu.noise_channel.lfsr & 1) ?
598 gb->apu.noise_channel.current_volume : 0,
599 0);
600 }
601 }
602
603 static void sweep_calculation_done(GB_gameboy_t *gb, unsigned cycles)
604 {
605 /* APU bug: sweep frequency is checked after adding the sweep delta twice */
606 if (gb->apu.channel_1_restart_hold == 0) {
607 gb->apu.shadow_sweep_sample_length = gb->apu.square_channels[GB_SQUARE_1].sample_length;
608 }
609 if (gb->io_registers[GB_IO_NR10] & 8) {
610 gb->apu.sweep_length_addend ^= 0x7FF;
611 }
612 if (gb->apu.shadow_sweep_sample_length + gb->apu.sweep_length_addend > 0x7FF && !(gb->io_registers[GB_IO_NR10] & 8)) {
613 gb->apu.is_active[GB_SQUARE_1] = false;
614 update_sample(gb, GB_SQUARE_1, 0, gb->apu.square_sweep_calculate_countdown * 2 - cycles);
615 }
616 gb->apu.channel1_completed_addend = gb->apu.sweep_length_addend;
617 }
618
619 static void trigger_sweep_calculation(GB_gameboy_t *gb)
620 {
621 if ((gb->io_registers[GB_IO_NR10] & 0x70) && gb->apu.square_sweep_countdown == 7) {
622 if (gb->io_registers[GB_IO_NR10] & 0x07) {
623 gb->apu.square_channels[GB_SQUARE_1].sample_length =
624 gb->apu.sweep_length_addend + gb->apu.shadow_sweep_sample_length + !!(gb->io_registers[GB_IO_NR10] & 0x8);
625 gb->apu.square_channels[GB_SQUARE_1].sample_length &= 0x7FF;
626 }
627 if (gb->apu.channel_1_restart_hold == 0) {
628 gb->apu.sweep_length_addend = gb->apu.square_channels[GB_SQUARE_1].sample_length;
629 gb->apu.sweep_length_addend >>= (gb->io_registers[GB_IO_NR10] & 7);
630 }
631
632 /* Recalculation and overflow check only occurs after a delay */
633 gb->apu.square_sweep_calculate_countdown = gb->io_registers[GB_IO_NR10] & 0x7;
634 // TODO: this is a hack because DIV write timing is inaccurate. Will probably break on odd mode.
635 gb->apu.square_sweep_calculate_countdown_reload_timer = 1 + gb->apu.lf_div;
636 if (!gb->cgb_double_speed && gb->during_div_write) {
637 gb->apu.square_sweep_calculate_countdown_reload_timer = 1;
638 }
639 gb->apu.unshifted_sweep = !(gb->io_registers[GB_IO_NR10] & 0x7);
640 gb->apu.square_sweep_countdown = ((gb->io_registers[GB_IO_NR10] >> 4) & 7) ^ 7;
641 if (gb->apu.square_sweep_calculate_countdown == 0) {
642 gb->apu.square_sweep_instant_calculation_done = true;
643 }
644 }
645 }
646
647 noinline void GB_apu_delayed_envelope_tick(GB_gameboy_t *gb)
648 {
649 gb->apu.pending_envelope_tick = false;
650 if (!gb->apu.global_enable) return;
651
652 GB_apu_run(gb, true);
653 gb->apu.pcm_mask[0] = gb->apu.pcm_mask[1] = 0xFF;
654
655
656 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
657 if (gb->apu.square_channels[i].envelope_clock.clock) {
658 tick_square_envelope(gb, i);
659 }
660 }
661
662 if (gb->apu.noise_channel.envelope_clock.clock) {
663 tick_noise_envelope(gb);
664 }
665 }
666
667 noinline void GB_apu_div_event(GB_gameboy_t *gb)
668 {
669 GB_apu_run(gb, true);
670 gb->apu.pcm_mask[0] = gb->apu.pcm_mask[1] = 0xFF;
671
672 if (!gb->apu.global_enable) return;
673 if (gb->apu.skip_div_event == GB_SKIP_DIV_EVENT_SKIP) {
674 gb->apu.skip_div_event = GB_SKIP_DIV_EVENT_SKIPPED;
675 return;
676 }
677 if (gb->apu.skip_div_event == GB_SKIP_DIV_EVENT_SKIPPED) {
678 gb->apu.skip_div_event = GB_SKIP_DIV_EVENT_INACTIVE;
679 }
680 else {
681 gb->apu.div_divider++;
682 }
683
684 if ((gb->apu.div_divider & 7) == 7) {
685 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
686 if (!gb->apu.square_channels[i].envelope_clock.clock) {
687 gb->apu.square_channels[i].volume_countdown--;
688 gb->apu.square_channels[i].volume_countdown &= 7;
689 }
690 }
691 if (!gb->apu.noise_channel.envelope_clock.clock) {
692 gb->apu.noise_channel.volume_countdown--;
693 gb->apu.noise_channel.volume_countdown &= 7;
694 }
695 }
696
697 if (gb->cgb_double_speed && (gb->model == GB_MODEL_CGB_D || gb->model == GB_MODEL_CGB_E)) {
698 gb->apu.pending_envelope_tick = true;
699 }
700 else {
701 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
702 if (gb->apu.square_channels[i].envelope_clock.clock) {
703 tick_square_envelope(gb, i);
704 }
705 }
706
707 if (gb->apu.noise_channel.envelope_clock.clock) {
708 tick_noise_envelope(gb);
709 }
710 }
711
712 if ((gb->apu.div_divider & 1) == 1) {
713 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
714 if (gb->apu.square_channels[i].length_enabled) {
715 if (gb->apu.square_channels[i].pulse_length) {
716 if (!--gb->apu.square_channels[i].pulse_length) {
717 gb->apu.is_active[i] = false;
718 update_sample(gb, i, 0, 0);
719 }
720 }
721 }
722 }
723
724 if (gb->apu.wave_channel.length_enabled) {
725 if (gb->apu.wave_channel.pulse_length) {
726 if (!--gb->apu.wave_channel.pulse_length) {
727 if (gb->apu.is_active[GB_WAVE] && gb->model > GB_MODEL_CGB_E) {
728 if (gb->apu.wave_channel.sample_countdown == 0) {
729 gb->apu.wave_channel.current_sample_byte =
730 gb->io_registers[GB_IO_WAV_START + (((gb->apu.wave_channel.current_sample_index + 1) & 0xF) >> 1)];
731 }
732 else if (gb->apu.wave_channel.sample_countdown == 9) {
733 // TODO: wtf?
734 gb->apu.wave_channel.current_sample_byte = gb->io_registers[GB_IO_WAV_START];
735 }
736 }
737 gb->apu.is_active[GB_WAVE] = false;
738 update_sample(gb, GB_WAVE, 0, 0);
739 }
740 }
741 }
742
743 if (gb->apu.noise_channel.length_enabled) {
744 if (gb->apu.noise_channel.pulse_length) {
745 if (!--gb->apu.noise_channel.pulse_length) {
746 gb->apu.is_active[GB_NOISE] = false;
747 update_sample(gb, GB_NOISE, 0, 0);
748 }
749 }
750 }
751 }
752
753 if ((gb->apu.div_divider & 3) == 3) {
754 gb->apu.square_sweep_countdown++;
755 gb->apu.square_sweep_countdown &= 7;
756 trigger_sweep_calculation(gb);
757 }
758 }
759
760 noinline void GB_apu_div_secondary_event(GB_gameboy_t *gb)
761 {
762 GB_apu_run(gb, true);
763 gb->apu.pcm_mask[0] = gb->apu.pcm_mask[1] = 0xFF;
764
765 if (!gb->apu.global_enable) return;
766 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
767 uint8_t nrx2 = gb->io_registers[i == GB_SQUARE_1? GB_IO_NR12 : GB_IO_NR22];
768 if (gb->apu.is_active[i] && gb->apu.square_channels[i].volume_countdown == 0) {
769 set_envelope_clock(&gb->apu.square_channels[i].envelope_clock,
770 (gb->apu.square_channels[i].volume_countdown = nrx2 & 7),
771 nrx2 & 8,
772 gb->apu.square_channels[i].current_volume);
773
774 }
775 }
776
777 if (gb->apu.is_active[GB_NOISE] && gb->apu.noise_channel.volume_countdown == 0) {
778 set_envelope_clock(&gb->apu.noise_channel.envelope_clock,
779 (gb->apu.noise_channel.volume_countdown = gb->io_registers[GB_IO_NR42] & 7),
780 gb->io_registers[GB_IO_NR42] & 8,
781 gb->apu.noise_channel.current_volume);
782 }
783 }
784
785 static void update_lfsr(GB_gameboy_t *gb, unsigned cycles_offset)
786 {
787 gb->apu.noise_channel.current_lfsr_sample = gb->apu.noise_channel.lfsr & 1;
788 if (gb->apu.is_active[GB_NOISE]) {
789 update_sample(gb, GB_NOISE,
790 gb->apu.noise_channel.current_lfsr_sample ?
791 gb->apu.noise_channel.current_volume : 0,
792 cycles_offset);
793 }
794 }
795
796 static void step_lfsr(GB_gameboy_t *gb, unsigned cycles_offset)
797 {
798 gb->apu.lfsr_bit_7_before_step = gb->apu.noise_channel.lfsr & 0x80;
799 unsigned high_bit_mask = gb->apu.noise_channel.narrow ? 0x4040 : 0x4000;
800 bool new_high_bit = (gb->apu.noise_channel.lfsr ^ (gb->apu.noise_channel.lfsr >> 1) ^ 1) & 1;
801 gb->apu.noise_channel.lfsr >>= 1;
802
803 if (new_high_bit) {
804 gb->apu.noise_channel.lfsr |= high_bit_mask;
805 }
806 else {
807 /* This code is not redundent, it's relevant when switching LFSR widths */
808 gb->apu.noise_channel.lfsr &= ~high_bit_mask;
809 }
810
811 update_lfsr(gb, cycles_offset);
812 gb->apu.lfsr_stepped_in_narrow = gb->apu.noise_channel.narrow;
813 }
814
815 void GB_apu_run(GB_gameboy_t *gb, bool force)
816 {
817 uint32_t clock_rate = GB_get_clock_rate(gb);
818 bool orig_force = force;
819
820 restart:;
821 uint16_t cycles = gb->apu.apu_cycles;
822
823 if (force ||
824 (cycles + gb->apu_output.cycles_since_render >= gb->apu_output.max_cycles_per_sample) ||
825 (gb->apu_output.sample_cycles >= clock_rate) ||
826 (gb->apu.square_sweep_calculate_countdown || gb->apu.channel_1_restart_hold || gb->apu.square_sweep_calculate_countdown_reload_timer) ||
827 (gb->model <= GB_MODEL_CGB_E && (gb->apu.wave_channel.bugged_read_countdown || (gb->apu.wave_channel.enable && gb->apu.wave_channel.pulsed)))) {
828 force = true;
829 }
830 if (!force) {
831 return;
832 }
833
834 /* Force renders to never be more than max_cycles_per_sample apart by spliting runs. */
835 while (cycles + gb->apu_output.cycles_since_render > gb->apu_output.max_cycles_per_sample) {
836 /* We're already past max_cycles_per_sample. This can happen when changing clock rates, etc.
837 Let this sample render normally. */
838 if (unlikely(gb->apu_output.cycles_since_render > gb->apu_output.max_cycles_per_sample)) break;
839
840 gb->apu.apu_cycles = gb->apu_output.max_cycles_per_sample - gb->apu_output.cycles_since_render;
841
842 if (gb->apu.apu_cycles) {
843 // Run for just enough cycles to reach max_cycles_per_sample
844 cycles -= gb->apu.apu_cycles;
845 GB_apu_run(gb, true);
846 // Re-evaluate force if needed
847 if (!orig_force) {
848 force = false;
849 gb->apu.apu_cycles = cycles;
850 goto restart;
851 }
852 // Check if we need another batch
853 continue;
854 }
855
856 // Render if needed
857 if (gb->apu_output.sample_cycles >= clock_rate) {
858 gb->apu_output.sample_cycles -= clock_rate;
859 render(gb);
860 }
861 break;
862 }
863
864 gb->apu.apu_cycles = 0;
865 if (!cycles) {
866 /* This can happen in pre-CGB stop mode */
867 while (unlikely(gb->apu_output.sample_cycles >= clock_rate)) {
868 gb->apu_output.sample_cycles -= clock_rate;
869 render(gb);
870 }
871 return;
872 }
873
874 if (unlikely(gb->apu.wave_channel.bugged_read_countdown)) {
875 uint16_t cycles_left = cycles;
876 while (cycles_left) {
877 cycles_left--;
878 if (--gb->apu.wave_channel.bugged_read_countdown == 0) {
879 gb->apu.wave_channel.current_sample_byte =
880 gb->io_registers[GB_IO_WAV_START + (gb->address_bus & 0xF)];
881 if (gb->apu.is_active[GB_WAVE]) {
882 update_wave_sample(gb, 0);
883 }
884 break;
885 }
886 }
887 }
888
889 bool start_ch4 = false;
890 if (likely(!gb->stopped || GB_is_cgb(gb))) {
891 if (gb->apu.noise_channel.dmg_delayed_start) {
892 if (gb->apu.noise_channel.dmg_delayed_start == cycles) {
893 gb->apu.noise_channel.dmg_delayed_start = 0;
894 start_ch4 = true;
895 }
896 else if (gb->apu.noise_channel.dmg_delayed_start > cycles) {
897 gb->apu.noise_channel.dmg_delayed_start -= cycles;
898 }
899 else {
900 /* Split it into two */
901 cycles -= gb->apu.noise_channel.dmg_delayed_start;
902 gb->apu.apu_cycles = gb->apu.noise_channel.dmg_delayed_start;
903 GB_apu_run(gb, true);
904 }
905 }
906 /* To align the square signal to 1MHz */
907 gb->apu.lf_div ^= cycles & 1;
908 gb->apu.noise_channel.alignment += cycles;
909
910 unsigned sweep_cycles = cycles / 2;
911 if ((cycles & 1) && !gb->apu.lf_div) {
912 sweep_cycles++;
913 }
914
915 if (gb->apu.square_sweep_calculate_countdown_reload_timer > sweep_cycles) {
916 gb->apu.square_sweep_calculate_countdown_reload_timer -= sweep_cycles;
917 sweep_cycles = 0;
918 }
919 else {
920 if (gb->apu.square_sweep_calculate_countdown_reload_timer && !gb->apu.square_sweep_calculate_countdown && gb->apu.square_sweep_instant_calculation_done) {
921 sweep_calculation_done(gb, cycles);
922 }
923 gb->apu.square_sweep_instant_calculation_done = false;
924 sweep_cycles -= gb->apu.square_sweep_calculate_countdown_reload_timer;
925 gb->apu.square_sweep_calculate_countdown_reload_timer = 0;
926 }
927
928 if (gb->apu.square_sweep_calculate_countdown &&
929 (((gb->io_registers[GB_IO_NR10] & 7) || gb->apu.unshifted_sweep))) { // Calculation is paused if the lower bits are 0
930 if (gb->apu.square_sweep_calculate_countdown > sweep_cycles) {
931 gb->apu.square_sweep_calculate_countdown -= sweep_cycles;
932 }
933 else {
934 gb->apu.square_sweep_calculate_countdown = 0;
935 sweep_calculation_done(gb, cycles);
936 }
937 }
938
939 if (gb->apu.channel_1_restart_hold) {
940 if (gb->apu.channel_1_restart_hold > cycles) {
941 gb->apu.channel_1_restart_hold -= cycles;
942 }
943 else {
944 gb->apu.channel_1_restart_hold = 0;
945 }
946 }
947
948 unrolled for (unsigned i = GB_SQUARE_1; i <= GB_SQUARE_2; i++) {
949 if (gb->apu.is_active[i]) {
950 uint16_t cycles_left = cycles;
951 if (unlikely(gb->apu.square_channels[i].delay)) {
952 if (gb->apu.square_channels[i].delay < cycles_left) {
953 gb->apu.square_channels[i].delay = 0;
954 }
955 else {
956 gb->apu.square_channels[i].delay -= cycles_left;
957 }
958 }
959 while (unlikely(cycles_left > gb->apu.square_channels[i].sample_countdown)) {
960 cycles_left -= gb->apu.square_channels[i].sample_countdown + 1;
961 gb->apu.square_channels[i].sample_countdown = (gb->apu.square_channels[i].sample_length ^ 0x7FF) * 2 + 1;
962 gb->apu.square_channels[i].current_sample_index++;
963 gb->apu.square_channels[i].current_sample_index &= 0x7;
964 gb->apu.square_channels[i].sample_surpressed = false;
965 if (cycles_left == 0 && gb->apu.samples[i] == 0) {
966 gb->apu.pcm_mask[0] &= i == GB_SQUARE_1? 0xF0 : 0x0F;
967 }
968 gb->apu.square_channels[i].did_tick = true;
969 update_square_sample(gb, i, cycles - cycles_left);
970
971 uint8_t duty = gb->io_registers[i == GB_SQUARE_1? GB_IO_NR11 :GB_IO_NR21] >> 6;
972 uint8_t edge_sample_index = inline_const(uint8_t[], {7, 7, 5, 1})[duty];
973 if (gb->apu.square_channels[i].current_sample_index == edge_sample_index) {
974 gb->apu_output.edge_triggered[i] = true;
975 }
976 }
977 gb->apu.square_channels[i].just_reloaded = cycles_left == 0;
978 if (cycles_left) {
979 gb->apu.square_channels[i].sample_countdown -= cycles_left;
980 }
981 }
982 }
983
984 gb->apu.wave_channel.wave_form_just_read = false;
985 if (gb->apu.is_active[GB_WAVE]) {
986 uint16_t cycles_left = cycles;
987 while (unlikely(cycles_left > gb->apu.wave_channel.sample_countdown)) {
988 cycles_left -= gb->apu.wave_channel.sample_countdown + 1;
989 gb->apu.wave_channel.sample_countdown = gb->apu.wave_channel.sample_length ^ 0x7FF;
990 gb->apu.wave_channel.current_sample_index++;
991 gb->apu.wave_channel.current_sample_index &= 0x1F;
992 gb->apu.wave_channel.current_sample_byte =
993 gb->io_registers[GB_IO_WAV_START + (gb->apu.wave_channel.current_sample_index >> 1)];
994 update_wave_sample(gb, cycles - cycles_left);
995 gb->apu.wave_channel.wave_form_just_read = true;
996 if (gb->apu.wave_channel.current_sample_index == 0) {
997 gb->apu_output.edge_triggered[GB_WAVE] = true;
998 }
999 }
1000 if (cycles_left) {
1001 gb->apu.wave_channel.sample_countdown -= cycles_left;
1002 gb->apu.wave_channel.wave_form_just_read = false;
1003 }
1004 }
1005 else if (gb->apu.wave_channel.enable && gb->apu.wave_channel.pulsed && gb->model <= GB_MODEL_CGB_E) {
1006 uint16_t cycles_left = cycles;
1007 while (unlikely(cycles_left > gb->apu.wave_channel.sample_countdown)) {
1008 cycles_left -= gb->apu.wave_channel.sample_countdown + 1;
1009 gb->apu.wave_channel.sample_countdown = gb->apu.wave_channel.sample_length ^ 0x7FF;
1010 if (cycles_left) {
1011 gb->apu.wave_channel.current_sample_byte =
1012 gb->io_registers[GB_IO_WAV_START + (gb->address_bus & 0xF)];
1013 }
1014 else {
1015 gb->apu.wave_channel.bugged_read_countdown = 1;
1016 }
1017 }
1018 if (cycles_left) {
1019 gb->apu.wave_channel.sample_countdown -= cycles_left;
1020 }
1021 if (gb->apu.wave_channel.sample_countdown == 0) {
1022 gb->apu.wave_channel.bugged_read_countdown = 2;
1023 }
1024 }
1025
1026 // TODO: verify these conditions one a DMG somehow
1027 if (gb->apu.noise_counter_active || gb->apu.noise_background_counter_active) {
1028 uint16_t cycles_left = cycles;
1029 unsigned divisor = (gb->io_registers[GB_IO_NR43] & 0x07) << 2;
1030 if (!divisor) divisor = 2;
1031 if (gb->apu.noise_channel.counter_countdown == 0) {
1032 gb->apu.noise_channel.counter_countdown = divisor;
1033 }
1034 // This while doesn't get an unlikely because the noise channel steps frequently enough
1035 while (cycles_left >= gb->apu.noise_channel.counter_countdown) {
1036 cycles_left -= gb->apu.noise_channel.counter_countdown;
1037 gb->apu.noise_channel.counter_countdown = divisor;
1038 uint16_t mask = 1 << (gb->io_registers[GB_IO_NR43] >> 4);
1039 bool old_bit = gb->apu.noise_channel.counter & mask;
1040 gb->apu.noise_channel.counter++;
1041 gb->apu.noise_channel.counter &= 0x3FFF;
1042 gb->apu.noise_channel.did_step_counter = true;
1043 bool new_bit = gb->apu.noise_channel.counter & mask;
1044
1045 /* Step LFSR */
1046 if (new_bit && !old_bit && gb->apu.is_active[GB_NOISE]) {
1047 if (cycles_left == 0 && gb->apu.samples[GB_NOISE] == 0 && !gb->cgb_double_speed) {
1048 gb->apu.pcm_mask[1] &= 0x0F;
1049 }
1050 step_lfsr(gb, cycles - cycles_left);
1051 }
1052 }
1053 if (cycles_left) {
1054 if (likely(gb->apu.noise_counter_active || gb->apu.noise_background_counter_active)) {
1055 gb->apu.noise_channel.counter_countdown -= cycles_left;
1056 gb->apu.noise_channel.countdown_reloaded = false;
1057 }
1058 }
1059 else {
1060 gb->apu.noise_channel.countdown_reloaded = true;
1061 gb->apu_output.edge_triggered[GB_NOISE] = true;
1062 }
1063 }
1064 }
1065
1066 if (gb->apu_output.sample_rate) {
1067 gb->apu_output.cycles_since_render += cycles;
1068 gb->apu_output.sample_fraction += sample_fraction_multiply(gb, cycles);
1069 assert(gb->apu_output.sample_fraction < (4 << 28));
1070
1071 if (gb->apu_output.sample_cycles >= clock_rate) {
1072 gb->apu_output.sample_cycles -= clock_rate;
1073 render(gb);
1074 }
1075 }
1076 if (start_ch4) {
1077 GB_apu_write(gb, GB_IO_NR44, gb->io_registers[GB_IO_NR44] | 0x80);
1078 }
1079 }
1080
1081 void GB_apu_init(GB_gameboy_t *gb)
1082 {
1083 memset(&gb->apu, 0, sizeof(gb->apu));
1084 gb->apu.apu_cycles_in_2mhz = true;
1085 gb->apu.lf_div = 1;
1086 gb->apu.wave_channel.shift = 4;
1087 /* APU glitch: When turning the APU on while DIV's bit 4 (or 5 in double speed mode) is on,
1088 the first DIV/APU event is skipped. */
1089 if (gb->div_counter & (gb->cgb_double_speed? 0x2000 : 0x1000)) {
1090 gb->apu.skip_div_event = GB_SKIP_DIV_EVENT_SKIP;
1091 gb->apu.div_divider = 1;
1092 }
1093 gb->apu.square_channels[GB_SQUARE_1].sample_countdown = -1;
1094 gb->apu.square_channels[GB_SQUARE_2].sample_countdown = -1;
1095 }
1096
1097 uint8_t GB_apu_read(GB_gameboy_t *gb, uint8_t reg)
1098 {
1099 GB_apu_run(gb, true);
1100 if (reg == GB_IO_NR52) {
1101 uint8_t value = 0;
1102 for (unsigned i = 0; i < GB_N_CHANNELS; i++) {
1103 value >>= 1;
1104 if (gb->apu.is_active[i]) {
1105 value |= 0x8;
1106 }
1107 }
1108 if (gb->apu.global_enable) {
1109 value |= 0x80;
1110 }
1111 value |= 0x70;
1112 return value;
1113 }
1114
1115 static const char read_mask[GB_IO_WAV_END - GB_IO_NR10 + 1] = {
1116 /* NRX0 NRX1 NRX2 NRX3 NRX4 */
1117 0x80, 0x3F, 0x00, 0xFF, 0xBF, // NR1X
1118 0xFF, 0x3F, 0x00, 0xFF, 0xBF, // NR2X
1119 0x7F, 0xFF, 0x9F, 0xFF, 0xBF, // NR3X
1120 0xFF, 0xFF, 0x00, 0x00, 0xBF, // NR4X
1121 0x00, 0x00, 0x70, 0xFF, 0xFF, // NR5X
1122
1123 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Unused
1124 // Wave RAM
1125 0, /* ... */
1126 };
1127
1128 if (reg >= GB_IO_WAV_START && reg <= GB_IO_WAV_END && gb->apu.is_active[GB_WAVE]) {
1129 if (!GB_is_cgb(gb) && !gb->apu.wave_channel.wave_form_just_read) {
1130 return 0xFF;
1131 }
1132 if (gb->model > GB_MODEL_CGB_E) {
1133 return 0xFF;
1134 }
1135 reg = GB_IO_WAV_START + gb->apu.wave_channel.current_sample_index / 2;
1136 }
1137
1138 return gb->io_registers[reg] | read_mask[reg - GB_IO_NR10];
1139 }
1140
1141 static noinline void nr10_write_glitch(GB_gameboy_t *gb, uint8_t value)
1142 {
1143 // TODO: Check all of these in APU odd mode
1144 if (gb->model <= GB_MODEL_CGB_C) {
1145 if (gb->apu.square_sweep_calculate_countdown_reload_timer == 1 && !gb->apu.lf_div) {
1146 if (gb->cgb_double_speed) {
1147 /* This is some instance-specific data corruption. It might also be affect by revision.
1148 At least for my CGB-0 (haven't tested any other CGB-0s), the '3' case is non-deterministic. */
1149 static const uint8_t corruption[8] = {7, 7, 5, 7, 3, 3, 5, 7}; // Two of my CGB-Cs, CGB-A
1150 // static const uint8_t corruption[8] = {7, 7, 1, 3, 3, 3, 5, 7}; // My other CGB-C, Coffee Bat's CGB-C
1151 // static const uint8_t corruption[8] = {7, 1, 1, 3, 3, 5, 5, 7}; // My CGB-B
1152 // static const uint8_t corruption[8] = {7, 7, 1, *, 3, 3, 5, 7}; // My CGB-0
1153
1154 // static const uint8_t corruption[8] = {7, 5, 1, 3, 3, 1, 5, 7}; // PinoBatch's CGB-B
1155 // static const uint8_t corruption[8] = {7, 5, 1, 3, 3, *, 5, 7}; // GenericHeroGuy CGB-C
1156
1157
1158 // TODO: How does this affect actual frequency calculation?
1159
1160 gb->apu.square_sweep_calculate_countdown = corruption[gb->apu.square_sweep_calculate_countdown & 7];
1161 /* TODO: the value of 1 needs special handling, but it doesn't occur with the instance I'm emulating here */
1162 }
1163 }
1164 else if (gb->apu.square_sweep_calculate_countdown_reload_timer > 1) {
1165 if (gb->cgb_double_speed) {
1166 // TODO: How does this affect actual frequency calculation?
1167 gb->apu.square_sweep_calculate_countdown = value & 7;
1168 }
1169 }
1170 else if (gb->apu.square_sweep_calculate_countdown) {
1171 // No clue why 1 is a special case here
1172 bool should_zombie_step = false;
1173 if (!(gb->io_registers[GB_IO_NR10] & 7)) {
1174 should_zombie_step = gb->apu.lf_div ^ gb->cgb_double_speed;
1175 }
1176 else if (gb->cgb_double_speed && gb->apu.square_sweep_calculate_countdown == 1) {
1177 should_zombie_step = true;
1178 }
1179
1180 if (should_zombie_step) {
1181 gb->apu.square_sweep_calculate_countdown--;
1182 if (gb->apu.square_sweep_calculate_countdown <= 1) {
1183 gb->apu.square_sweep_calculate_countdown = 0;
1184 sweep_calculation_done(gb, 0);
1185 }
1186 }
1187 }
1188 }
1189 else {
1190 if (gb->apu.square_sweep_calculate_countdown_reload_timer == 2) {
1191 // Countdown just reloaded, re-reload it
1192 gb->apu.square_sweep_calculate_countdown = value & 0x7;
1193 if (!gb->apu.square_sweep_calculate_countdown) {
1194 gb->apu.square_sweep_calculate_countdown_reload_timer = 0;
1195 }
1196 else {
1197 // TODO: How does this affect actual frequency calculation?
1198 }
1199 }
1200 if ((value & 7) && !(gb->io_registers[GB_IO_NR10] & 7) && !gb->apu.lf_div && gb->apu.square_sweep_calculate_countdown > 1) {
1201 // TODO: Another odd glitch? Ditto
1202 gb->apu.square_sweep_calculate_countdown--;
1203 if (!gb->apu.square_sweep_calculate_countdown) {
1204 sweep_calculation_done(gb, 0);
1205 }
1206 }
1207 }
1208
1209 }
1210
1211 static void prepare_noise_start(GB_gameboy_t *gb)
1212 {
1213 /*
1214 TODO: When restarting a channel right after starting it, before it has the chance to tick the counter, things
1215 behave differently. Only certain behaviors of this edge case are emulated.
1216 */
1217
1218 /*
1219 TODO: Restarting a channel in double speed mode under CGB-C and older is not accurate if the divisor is 0 or 1.
1220 Specifically in the 0 case, the initial LFSR value seems to be deterministic, but dependant on various
1221 parameters. It is neither 0 or the equaly unexplained 0x0055.
1222 */
1223 gb->apu.noise_counter_active = gb->io_registers[GB_IO_NR42] & 0xF8; // Resets on APU off and DAC disable
1224 bool was_started_with_dac_disabled = gb->apu.noise_started_with_dac_disabled;
1225 gb->apu.noise_started_with_dac_disabled = !gb->apu.noise_counter_active;
1226 unsigned divisor = (gb->io_registers[GB_IO_NR43] & 0x07);
1227 bool was_background_counting = gb->apu.noise_background_counter_active;
1228 gb->apu.noise_background_counter_active = true;
1229 bool instant_step = false;
1230 bool div_1_glitch = false;
1231
1232 if (divisor > 1 && gb->apu.noise_channel.counter_countdown == 1) {
1233 gb->apu.noise_channel.counter++;
1234 gb->apu.noise_channel.counter &= 0x3FFF;
1235 }
1236 else if (divisor > 1 && gb->apu.noise_channel.counter_countdown == 2 && gb->apu.is_active[GB_NOISE] && gb->model <= GB_MODEL_CGB_C && gb->cgb_double_speed) {
1237 gb->apu.noise_channel.counter++;
1238 gb->apu.noise_channel.counter &= 0x3FFF;
1239 }
1240 else if (gb->apu.noise_channel.counter_countdown == 2 &&
1241 (gb->apu.noise_channel.alignment & 3) == 0 &&
1242 gb->apu.is_active[GB_NOISE]) {
1243 if (divisor == 0) {
1244 divisor = 8;
1245 }
1246 else if (divisor == 1) {
1247 if (!gb->apu.noise_channel.did_step_counter) {
1248 div_1_glitch = true;
1249 }
1250
1251 uint16_t mask = 1 << (gb->io_registers[GB_IO_NR43] >> 4);
1252 bool old_bit = gb->apu.noise_channel.counter & mask;
1253 gb->apu.noise_channel.counter++;
1254 gb->apu.noise_channel.counter &= 0x3FFF;
1255 bool new_bit = gb->apu.noise_channel.counter & mask;
1256
1257 if ((new_bit && !old_bit)) {
1258 instant_step = true;
1259 }
1260 }
1261 }
1262 gb->apu.noise_channel.counter_countdown = divisor == 0? 6 : divisor * 4 + 6;
1263 if (gb->apu.noise_channel.alignment & 1) {
1264 if (!divisor) {
1265 if (gb->model <= GB_MODEL_CGB_C) {
1266 gb->apu.noise_channel.counter_countdown++;
1267 }
1268 else if (was_background_counting) {
1269 gb->apu.noise_channel.counter_countdown--;
1270 }
1271 else {
1272 gb->apu.noise_channel.counter_countdown++;
1273 }
1274 }
1275 else {
1276 if (gb->apu.noise_channel.alignment & 2) {
1277 if (divisor == 1 && !gb->apu.is_active[GB_NOISE]) {
1278 gb->apu.noise_channel.counter_countdown++;
1279 }
1280 else {
1281 gb->apu.noise_channel.counter_countdown -= 3;
1282 }
1283 }
1284 else {
1285 gb->apu.noise_channel.counter_countdown--;
1286 if (divisor == 1 && gb->apu.is_active[GB_NOISE]) {
1287 gb->apu.noise_channel.counter_countdown -= 4;
1288 }
1289 }
1290 }
1291 }
1292 else {
1293 if (divisor) {
1294 if (gb->apu.noise_channel.alignment & 2) {
1295 if (gb->cgb_double_speed && gb->model <= GB_MODEL_CGB_C && divisor == 1) {
1296 gb->apu.noise_channel.counter_countdown += 2;
1297 }
1298 else {
1299 gb->apu.noise_channel.counter_countdown -= 2;
1300 }
1301 }
1302 else if (divisor > 1 && (!gb->cgb_double_speed || gb->model > GB_MODEL_CGB_C)) {
1303 gb->apu.noise_channel.counter_countdown -= 4;
1304 }
1305 /* TODO: This quirk seems way too specific */
1306 else if (divisor == 1 && gb->apu.is_active[GB_NOISE] && !(gb->io_registers[GB_IO_NR43] & 0xf0)) {
1307 gb->apu.noise_channel.counter_countdown -= 4;
1308 }
1309 }
1310 else if (gb->cgb_double_speed && gb->model <= GB_MODEL_CGB_C) {
1311 gb->apu.noise_channel.counter_countdown += 2;
1312 }
1313 }
1314
1315 /* Background counting glitches */
1316 /* TODO: Double speed mode not tested */
1317 if (divisor > 1) {
1318 if (!gb->apu.noise_counter_active && !(gb->apu.noise_channel.alignment & 3)) {
1319 gb->apu.noise_channel.counter_countdown += 4;
1320 }
1321 }
1322 else {
1323 if (was_background_counting && !gb->apu.is_active[GB_NOISE] && !(gb->apu.noise_channel.alignment & 3)) {
1324 if (divisor == 0) {
1325 if (was_started_with_dac_disabled) { // TODO: Why is it different?
1326 gb->apu.noise_channel.counter_countdown += 28;
1327 }
1328 }
1329 else {
1330 gb->apu.noise_channel.counter_countdown -= 4;
1331 }
1332 }
1333 }
1334
1335 /* TODO: This is weird, is the clock going out of sync? */
1336 if (!divisor && gb->model <= GB_MODEL_CGB_C && was_background_counting && !gb->apu.is_active[GB_NOISE] && gb->cgb_double_speed) {
1337 gb->apu.noise_channel.counter_countdown--;
1338 }
1339 if (div_1_glitch) {
1340 gb->apu.noise_channel.counter_countdown -= 4;
1341 }
1342
1343 if (!divisor && gb->apu.is_active[GB_NOISE] && (gb->apu.noise_channel.alignment & 3) == 3) {
1344 /* TODO: I have no clue where this number comes from, but this number is confirmed for this edge case even for
1345 side LFSR, despite being seemingly arbitrary. */
1346 gb->apu.noise_channel.lfsr = 0x0055;
1347 }
1348 else {
1349 gb->apu.noise_channel.lfsr = 0;
1350 }
1351 if (instant_step) {
1352 step_lfsr(gb, 0);
1353 }
1354 }
1355
1356 static void nr43_write(GB_gameboy_t *gb, uint8_t new)
1357 {
1358 /*
1359 NR43 writes cause glitch signals to the LFSR. They are often non-deterministic, and
1360 they're revision and instance specific. This implementation is trying to emulate a
1361 simplified and deterministic "variant" of specific instances of revisions I own.
1362
1363 For more details:
1364 https://github.com/LIJI32/SameBoy/issues/397#issuecomment-3733625631
1365 */
1366
1367 /*
1368 TODO: Non-determinism aside, this is currently only 100% accurate in CGB-E mode, where
1369 my specific CGB-E is currently emulated. My CGB-D, under rare cases, samples a second
1370 intermediate value, and this is not currently emulated. AGB revisions are extremely
1371 glitchy, and are hard to research.
1372
1373 Due to FF-write glitches in pre-CGB-D revisions, all writes (even no-change writes) go
1374 through 3 intermediate values by definition. Also, the effective counter value used is
1375 ORed with the next (or previous, timing needs to be verified) value.
1376 */
1377 bool old_narrow = gb->apu.noise_channel.narrow;
1378 gb->apu.noise_channel.narrow = new & 8;
1379 uint8_t old = gb->io_registers[GB_IO_NR43];
1380 gb->io_registers[GB_IO_NR43] = new;
1381
1382 if ((old & 0xF0) == (new & 0xF0)) return;
1383
1384 uint16_t effective_counter = gb->apu.noise_channel.counter;
1385 if (gb->model <= GB_MODEL_CGB_C && gb->apu.noise_channel.countdown_reloaded) {
1386 effective_counter |= (effective_counter - 1) & 0x3FFF;
1387 }
1388 bool old_bit = (effective_counter >> (old >> 4)) & 1;
1389
1390 uint8_t glitch_value = (old & 0x7F) | (new & 0x80);
1391 bool glitch_bit = (effective_counter >> (glitch_value >> 4)) & 1;
1392 bool new_bit = (effective_counter >> (new >> 4)) & 1;
1393 bool force_glitch = false;
1394
1395 if (gb->model == GB_MODEL_CGB_D) {
1396 if (new_bit && glitch_bit && old_bit) {
1397 if ((old ^ new) & 0x70) {
1398 force_glitch = true;
1399 }
1400 }
1401 }
1402
1403 if (gb->model > GB_MODEL_CGB_E) {
1404 /* AGB behavior is very glitchy and incosistent. It can have 2 intermediate values for
1405 NR43, and sometimes even 3, and the pattern isn't very consistent. This is a *very*
1406 rough approximation of the behavior.
1407
1408 Due to having so up to 3 intermediate value, glitch behavior is complicated to look
1409 into, so currently CGB-E behavior is arbitrarily used if a glitch occurs. */
1410
1411 uint8_t glitch_value2 = 0;
1412 if (new >= 0x80 && old >= 0x80) {
1413 glitch_value = (old & 0xCF) | (new & 0x30);
1414 glitch_value2 = (old & 0x8F) | (new & 0x70);
1415 }
1416 else {
1417 glitch_value = (old & 0xDF) | (new & 0x20);
1418 glitch_value2 = (old & 0xCF) | (new & 0x30);
1419 }
1420 glitch_bit = (gb->apu.noise_channel.counter >> (glitch_value >> 4)) & 1;
1421 uint8_t glitch_bit2 = (gb->apu.noise_channel.counter >> (glitch_value2 >> 4)) & 1;
1422 if (glitch_bit != glitch_bit2) {
1423 if (new_bit == old_bit) {
1424 glitch_bit = !new_bit;
1425 }
1426 else if (!glitch_bit && old_bit) {
1427 force_glitch = true;
1428 }
1429 }
1430 }
1431
1432 /* Step LFSR */
1433
1434 if ((old_bit == new_bit && new_bit != glitch_bit) || force_glitch) {
1435 /* Glitching write. Has two categories, both have non-deterministic
1436 variants. These are the most common variants of the two categories,
1437 which are deterministic. */
1438 if (new_bit) {
1439 /* Category 1 */
1440 if (gb->model >= GB_MODEL_CGB_E) {
1441 if (!(new & 0x80)) {
1442 step_lfsr(gb, 0);
1443 }
1444 else {
1445 /* Only happens under this odd condition */
1446 uint8_t t1 = (old >> 4) & 7;
1447 uint8_t t2 = (new >> 4) & 7;
1448
1449 if ((t1 ^ 7) + t2 > 7 || ((t1 ^ 7) & t2)) {
1450 /* Copy bit 8 to bit 7 */
1451 gb->apu.noise_channel.lfsr &= ~0x80;
1452 gb->apu.noise_channel.lfsr |= (gb->apu.noise_channel.lfsr >> 1) & 0x80;
1453
1454 /* All specific cases have non-deterministic behaviors involved */
1455 if ((t1 == 0 || t1 == 4) && t2 == 3) {
1456 gb->apu.noise_channel.lfsr &= (gb->apu.noise_channel.lfsr >> 1) | 0x545;
1457 update_lfsr(gb, 0);
1458 }
1459 else if (t1 == 2 && t2 == 3) {
1460 uint16_t mask = 0x555;
1461 if ((gb->apu.noise_channel.lfsr & 0xC) == 0xC) {
1462 mask |= 8;
1463 }
1464 if ((gb->apu.noise_channel.lfsr & 0xC00) == 0xC00) {
1465 mask |= 0x800;
1466 }
1467
1468 gb->apu.noise_channel.lfsr &= (gb->apu.noise_channel.lfsr >> 1) | mask;
1469 update_lfsr(gb, 0);
1470 }
1471 if (!gb->apu.noise_channel.narrow && old_narrow && gb->apu.lfsr_stepped_in_narrow) {
1472 /* TODO: Behaves weirder in non-deterministic t1 == 0/4 scenarios? */
1473 if (gb->apu.lfsr_bit_7_before_step) {
1474 gb->apu.noise_channel.lfsr |= 0x40;
1475 }
1476 else {
1477 gb->apu.noise_channel.lfsr &= ~0x40;
1478 }
1479 }
1480 gb->apu.noise_channel.lfsr |= gb->apu.noise_channel.narrow ? 0x4040 : 0x4000;
1481 /* TODO: verify */
1482 gb->apu.lfsr_stepped_in_narrow = gb->apu.noise_channel.narrow;
1483 }
1484 }
1485 }
1486 else if (gb->model == GB_MODEL_CGB_D) {
1487 static const uint8_t glitch_map_l2h[8 * 8] = {
1488 [000] = 0x00, 0x01, 0x01, 0x21, 0x02, 0x21,
1489 [010] = 0x03, 0x00, 0x21, 0x01, 0x04, 0x04,
1490 [020] = 0x05, 0x01, 0x00, 0x01, 0x04, 0x21,
1491 [030] = 0x03, 0x05, 0x05, 0x00, 0x01, 0x01,
1492 [040] = 0x05, 0x01, 0x01, 0x21, 0x00, 0x01,
1493 [050] = 0x05, 0x05, 0x21, 0x01, 0x05, 0x00,
1494 [060] = 0x05, 0x01, 0x05, 0x01, 0x05, 0x01,
1495 [070] = 0x03, 0x05, 0x05, 0x05, 0x05, 0x05,
1496 };
1497
1498 /* The following transitions are a bit non-deterministic (except under forced glitched):
1499 1 -> c, 2 -> c, 3 -> c, 3 -> d */
1500
1501 static const uint8_t glitch_map_h2l[8 * 8] = {
1502 [000] = 0x00, 0x27, 0x26, 0x37, 0x21, 0x38, 0x01, 0x01,
1503 [010] = 0x01, 0x00, 0x38, 0x21, 0x21, 0x21, 0x01, 0x01,
1504 [020] = 0x01, 0x27, 0x00, 0x28, 0x21, 0x38, 0x01, 0x01,
1505 [030] = 0x01, 0x02, 0x01, 0x00, 0x31, 0x21, 0x01, 0x01,
1506 [040] = 0x06, 0x28, 0x28, 0x38, 0x00, 0x27, 0x01, 0x01,
1507 [050] = 0x01, 0x03, 0x38, 0x21, 0x01, 0x00, 0x01, 0x01,
1508 };
1509 /* The following transitions are a bit non-deterministic (except under forced glitched):
1510 8 -> 5, 2 -> 9, a -> 3, c -> 3 */
1511
1512 const uint8_t *glitch_map = old & 0x80? &glitch_map_h2l[0] : &glitch_map_l2h[0];
1513
1514
1515 unsigned glitch = glitch_map[((old & 0x70) >> 1) | ((new & 0x70) >> 4)];
1516 if (force_glitch) {
1517 if (!((new ^ old) & 0x80)) {
1518 glitch = glitch & 0x20? 5 : 0;
1519 }
1520 else if (!(new & 0x80)) {
1521 glitch = glitch & 0x10? 5 : 0;
1522 }
1523 else if ((glitch & 0xF) == 1 || (glitch & 0xF) == 4) {
1524 glitch = 5;
1525 }
1526 else {
1527 glitch = 0;
1528 }
1529 }
1530 else {
1531 glitch &= 0xF;
1532 }
1533 uint16_t old_lfsr = gb->apu.noise_channel.lfsr;
1534 uint16_t lfsr_mask = gb->apu.noise_channel.narrow ? 0x4040 : 0x4000;
1535 switch (glitch) {
1536 case 6: // Like 2, but conditional
1537 case 4: // Like 2, but conditional
1538 if ((gb->apu.noise_channel.lfsr & (glitch == 4? 0x60 : 0x40)) != 0x40) { // Todo check wide mode
1539 case 2: // And bit 1 with bit 0 before doing glitch 1
1540 if (!(gb->apu.noise_channel.lfsr & 1)) {
1541 gb->apu.noise_channel.lfsr &= ~2;
1542 }
1543 }
1544 case 1: // Step and set the LFSR bit
1545 case 8: // Step and set the LFSR bit conditionally
1546 step_lfsr(gb, 0);
1547 case 5: // Just set LFSR
1548 if ((glitch != 8) || (old_lfsr & 3) != 2) {
1549 gb->apu.noise_channel.lfsr |= lfsr_mask;
1550 }
1551 else {
1552 gb->apu.noise_channel.lfsr |= old_lfsr & lfsr_mask;
1553 }
1554 break;
1555
1556 case 7: // Step and OR the LFSR bit with its old value
1557 step_lfsr(gb, 0);
1558 gb->apu.noise_channel.lfsr |= old_lfsr & lfsr_mask;
1559 break;
1560
1561 case 3: // A bit of a mess
1562 step_lfsr(gb, 0);
1563 gb->apu.noise_channel.lfsr &= old_lfsr;
1564 gb->apu.noise_channel.lfsr |= old_lfsr & 1;
1565 gb->apu.noise_channel.lfsr |= lfsr_mask;
1566 update_lfsr(gb, 0);
1567 break;
1568
1569
1570 default: break;
1571 }
1572 }
1573 }
1574 else {
1575 /* Category 2 */
1576 if (gb->model >= GB_MODEL_CGB_E) {
1577 static const uint8_t glitch_map[8 * 8] = {
1578 /* 8 9 A B C D */
1579 [002] = 4, [003] = 2, [004] = 2, [005] = 2, // 0
1580 [012] = 2, [013] = 4, [014] = 2, [015] = 2, // 1
1581 [020] = 1, [021] = 2, [023] = 1, [024] = 5, [025] = 3, // 2
1582 [034] = 2, [035] = 2, // 3
1583 [041] = 2, [042] = 2, [043] = 2, // 4
1584 [050] = 6, [052] = 2, [053] = 2, // 5
1585 };
1586
1587 /* The following transitions are a bit non-deterministic:
1588 2 -> 8, 0 -> A, 2 -> C */
1589
1590 unsigned glitch = new & 0x80? glitch_map[((old & 0x70) >> 1) | ((new & 0x70) >> 4)] : 0;
1591 switch (glitch) {
1592 case 1: /* Step, followed by bit 1 &= bit 0 */
1593 case 6: /* Variant of type 1: LFSR bit - 1 glitched by LFSR bit, LFSR bit - 2, and bit 0 */
1594 step_lfsr(gb, 0);
1595 if (glitch == 6) {
1596 /* TODO: Verify wide mode */
1597 if ((gb->apu.noise_channel.narrow &&
1598 ((gb->apu.noise_channel.lfsr & 0x71) == 0x20)) ||
1599 (gb->apu.noise_channel.lfsr & 0x71) == 0x61) {
1600 gb->apu.noise_channel.lfsr &= ~0x20;
1601 }
1602 if ((gb->apu.noise_channel.lfsr & 0x7001) == 0x2000 ||
1603 (gb->apu.noise_channel.lfsr & 0x7001) == 0x6001) {
1604 gb->apu.noise_channel.lfsr &= ~0x2000;
1605 }
1606 }
1607 if ((gb->apu.noise_channel.lfsr & 0x3) == 2) {
1608 gb->apu.noise_channel.lfsr &= ~2;
1609 }
1610 break;
1611 case 2: { /* Step, bitwise AND with previous, except for bit 0 */
1612 uint16_t prev = gb->apu.noise_channel.lfsr;
1613 step_lfsr(gb, 0);
1614 gb->apu.noise_channel.lfsr &= prev | 1;
1615 break;
1616 }
1617
1618 case 5:; /* Non deterministic variant of type 3:
1619 The LFSR is unset if bit 0 & 1 are 0b10.
1620 Bit 3 is complex and non-deterministic (TODO: wide mode) */
1621 if ((gb->apu.noise_channel.lfsr & 0x3) == 2) {
1622 gb->apu.noise_channel.lfsr &= gb->apu.noise_channel.narrow? ~0x4040 : ~0x4000;
1623 }
1624
1625 if ((gb->apu.noise_channel.lfsr & 0x19) == 8) {
1626 gb->apu.noise_channel.lfsr &= ~8;
1627 }
1628
1629 case 3: /* No step, bit 0 = bit 1, some other bits have AND glitches with next*/
1630 gb->apu.noise_channel.lfsr &= ~1;
1631 gb->apu.noise_channel.lfsr |= (gb->apu.noise_channel.lfsr >> 1) & 1;
1632
1633 update_lfsr(gb, 0);
1634 /* TODO: verify */
1635 gb->apu.lfsr_stepped_in_narrow = gb->apu.noise_channel.narrow;
1636 break;
1637
1638 case 4: { /* Step, bit 1 &= bit 0, LFSR bit -1 &= LFSR bit */
1639 uint16_t prev = gb->apu.noise_channel.lfsr;
1640 step_lfsr(gb, 0);
1641 gb->apu.noise_channel.lfsr &= prev | (gb->apu.noise_channel.narrow? ~0x2022 : ~0x2002);
1642 break;
1643 }
1644
1645 default: /* No glitch, plain step*/
1646 step_lfsr(gb, 0);
1647 break;
1648
1649 }
1650 }
1651 else {
1652 step_lfsr(gb, 0);
1653 }
1654 }
1655 }
1656 else if (!old_bit && new_bit) {
1657 if (gb->model <= GB_MODEL_CGB_C) {
1658 bool previous_narrow = gb->apu.noise_channel.narrow;
1659 gb->apu.noise_channel.narrow = true;
1660 step_lfsr(gb, 0);
1661 gb->apu.noise_channel.narrow = previous_narrow;
1662 if ((new & 0xf0) <= 0x20 && glitch_bit && !(effective_counter & 8)) { // No clue why that specific bit is tested
1663 // Non-deterministic, not fully tested for revision differences and wide mode
1664 // Step twice?
1665 step_lfsr(gb, 0);
1666 gb->apu.noise_channel.lfsr &= ~(gb->apu.noise_channel.narrow? 0x4040 : 0x4000);
1667 gb->apu.noise_channel.lfsr |= (gb->apu.noise_channel.lfsr & (gb->apu.noise_channel.narrow? 0x2020 : 0x2000)) << 1;
1668 }
1669 }
1670 else {
1671 step_lfsr(gb, 0);
1672 }
1673 }
1674 else if (gb->model <= GB_MODEL_CGB_C) {
1675 if ((new & 0xf0) <= 0x20 && !glitch_bit && !new_bit && !old_bit && (effective_counter & 8)) { // No clue why that specific bit is tested
1676 // Step twice?
1677 step_lfsr(gb, 0);
1678 }
1679 }
1680 }
1681
1682 void GB_apu_write(GB_gameboy_t *gb, uint8_t reg, uint8_t value)
1683 {
1684 GB_apu_run(gb, true);
1685 if (!gb->apu.global_enable && reg != GB_IO_NR52 && reg < GB_IO_WAV_START && (GB_is_cgb(gb) ||
1686 (
1687 reg != GB_IO_NR11 &&
1688 reg != GB_IO_NR21 &&
1689 reg != GB_IO_NR31 &&
1690 reg != GB_IO_NR41
1691 )
1692 )) {
1693 return;
1694 }
1695
1696 if (reg >= GB_IO_WAV_START && reg <= GB_IO_WAV_END && gb->apu.is_active[GB_WAVE]) {
1697 if ((!GB_is_cgb(gb) && !gb->apu.wave_channel.wave_form_just_read) || gb->model > GB_MODEL_CGB_E) {
1698 return;
1699 }
1700 reg = GB_IO_WAV_START + gb->apu.wave_channel.current_sample_index / 2;
1701 }
1702
1703 /* Todo: this can and should be rewritten with a function table. */
1704 switch (reg) {
1705 /* Globals */
1706 case GB_IO_NR50:
1707 case GB_IO_NR51:
1708 gb->io_registers[reg] = value;
1709 /* These registers affect the output of all 4 channels (but not the output of the PCM registers).*/
1710 /* We call update_samples with the current value so the APU output is updated with the new outputs */
1711 for (unsigned i = GB_N_CHANNELS; i--;) {
1712 int8_t sample = gb->apu.samples[i];
1713 gb->apu.samples[i] = 0x10; // Invalidate to force update
1714 update_sample(gb, i, sample, 0);
1715 }
1716 break;
1717 case GB_IO_NR52: {
1718
1719 uint8_t old_pulse_lengths[] = {
1720 gb->apu.square_channels[0].pulse_length,
1721 gb->apu.square_channels[1].pulse_length,
1722 gb->apu.wave_channel.pulse_length,
1723 gb->apu.noise_channel.pulse_length
1724 };
1725 if ((value & 0x80) && !gb->apu.global_enable) {
1726 GB_apu_init(gb);
1727 gb->apu.global_enable = true;
1728 }
1729 else if (!(value & 0x80) && gb->apu.global_enable) {
1730 for (unsigned i = GB_N_CHANNELS; i--;) {
1731 update_sample(gb, i, 0, 0);
1732 }
1733 memset(&gb->apu, 0, sizeof(gb->apu));
1734 memset(gb->io_registers + GB_IO_NR10, 0, GB_IO_WAV_START - GB_IO_NR10);
1735 gb->apu.global_enable = false;
1736 gb->apu.apu_cycles_in_2mhz = true;
1737 }
1738
1739 if (!GB_is_cgb(gb) && (value & 0x80)) {
1740 gb->apu.square_channels[0].pulse_length = old_pulse_lengths[0];
1741 gb->apu.square_channels[1].pulse_length = old_pulse_lengths[1];
1742 gb->apu.wave_channel.pulse_length = old_pulse_lengths[2];
1743 gb->apu.noise_channel.pulse_length = old_pulse_lengths[3];
1744 }
1745 }
1746 break;
1747
1748 /* Square channels */
1749 case GB_IO_NR10: {
1750 if (unlikely(gb->apu.square_sweep_calculate_countdown || gb->apu.square_sweep_calculate_countdown_reload_timer)) {
1751 nr10_write_glitch(gb, value);
1752 }
1753 bool old_negate = gb->io_registers[GB_IO_NR10] & 8;
1754 gb->io_registers[GB_IO_NR10] = value;
1755 if (gb->model <= GB_MODEL_CGB_C) {
1756 old_negate = true;
1757 }
1758 if (gb->apu.shadow_sweep_sample_length + gb->apu.channel1_completed_addend + old_negate > 0x7FF &&
1759 !(value & 8)) {
1760 gb->apu.is_active[GB_SQUARE_1] = false;
1761 update_sample(gb, GB_SQUARE_1, 0, 0);
1762 }
1763 trigger_sweep_calculation(gb);
1764 break;
1765 }
1766
1767 case GB_IO_NR11:
1768 case GB_IO_NR21: {
1769 GB_channel_t index = reg == GB_IO_NR21? GB_SQUARE_2: GB_SQUARE_1;
1770 gb->apu.square_channels[index].pulse_length = (0x40 - (value & 0x3F));
1771 if (!gb->apu.global_enable) {
1772 value &= 0x3F;
1773 }
1774 break;
1775 }
1776
1777 case GB_IO_NR12:
1778 case GB_IO_NR22: {
1779 GB_channel_t index = reg == GB_IO_NR22? GB_SQUARE_2: GB_SQUARE_1;
1780 if ((value & 0xF8) == 0) {
1781 /* This disables the DAC */
1782 gb->io_registers[reg] = value;
1783 gb->apu.is_active[index] = false;
1784 update_sample(gb, index, 0, 0);
1785 }
1786 else if (gb->apu.is_active[index]) {
1787 nrx2_glitch(gb, &gb->apu.square_channels[index].current_volume,
1788 value, gb->io_registers[reg], &gb->apu.square_channels[index].volume_countdown,
1789 &gb->apu.square_channels[index].envelope_clock);
1790 update_square_sample(gb, index, 0);
1791 }
1792
1793 break;
1794 }
1795
1796 case GB_IO_NR13:
1797 case GB_IO_NR23: {
1798 GB_channel_t index = reg == GB_IO_NR23? GB_SQUARE_2: GB_SQUARE_1;
1799 gb->apu.square_channels[index].sample_length &= ~0xFF;
1800 gb->apu.square_channels[index].sample_length |= value & 0xFF;
1801 if (gb->apu.square_channels[index].just_reloaded) {
1802 gb->apu.square_channels[index].sample_countdown = (gb->apu.square_channels[index].sample_length ^ 0x7FF) * 2 + 1;
1803 }
1804 break;
1805 }
1806
1807 case GB_IO_NR14:
1808 case GB_IO_NR24: {
1809 GB_channel_t index = reg == GB_IO_NR24? GB_SQUARE_2: GB_SQUARE_1;
1810 bool was_active = gb->apu.is_active[index];
1811 /* TODO: When the sample length changes right before being updated from ≥$700 to <$700, the countdown
1812 should change to the old length, but the current sample should not change. Because our write
1813 timing isn't accurate to the T-cycle, we hack around it by stepping the sample index backwards. */
1814 if ((value & 0x80) == 0 && gb->apu.is_active[index] && (gb->io_registers[reg] & 0x7) == 7 && (value & 7) != 7) {
1815 /* On an AGB, as well as on CGB C and earlier (TODO: Tested: 0, B and C), it behaves slightly different on
1816 double speed. */
1817 if (gb->model == GB_MODEL_CGB_E || gb->model == GB_MODEL_CGB_D || gb->apu.square_channels[index].sample_countdown & 1) {
1818 if (gb->apu.square_channels[index].did_tick &&
1819 gb->apu.square_channels[index].sample_countdown >> 1 == (gb->apu.square_channels[index].sample_length ^ 0x7FF)) {
1820 gb->apu.square_channels[index].current_sample_index--;
1821 gb->apu.square_channels[index].current_sample_index &= 7;
1822 gb->apu.square_channels[index].sample_surpressed = false;
1823 }
1824 }
1825 }
1826
1827 uint16_t old_sample_length = gb->apu.square_channels[index].sample_length;
1828 gb->apu.square_channels[index].sample_length &= 0xFF;
1829 gb->apu.square_channels[index].sample_length |= (value & 7) << 8;
1830 if (gb->apu.square_channels[index].just_reloaded) {
1831 gb->apu.square_channels[index].sample_countdown = (gb->apu.square_channels[index].sample_length ^ 0x7FF) * 2 + 1;
1832 }
1833 if (value & 0x80) {
1834 /* Current sample index remains unchanged when restarting channels 1 or 2. It is only reset by
1835 turning the APU off. */
1836 gb->apu.square_channels[index].envelope_clock.locked = false;
1837 gb->apu.square_channels[index].envelope_clock.clock = false;
1838 gb->apu.square_channels[index].did_tick = false;
1839 bool force_unsurpressed = false;
1840 if (!gb->apu.is_active[index]) {
1841 if (gb->model == GB_MODEL_CGB_E || gb->model == GB_MODEL_CGB_D) {
1842 if (!(value & 4) && !(((gb->apu.square_channels[index].sample_countdown - gb->apu.square_channels[index].delay) / 2) & 0x400)) {
1843 gb->apu.square_channels[index].current_sample_index++;
1844 gb->apu.square_channels[index].current_sample_index &= 0x7;
1845 force_unsurpressed = true;
1846 }
1847 }
1848 gb->apu.square_channels[index].delay = 6 + gb->apu.lf_div * (gb->model < GB_MODEL_CGB_D && gb->cgb_double_speed? 1 : -1);
1849 gb->apu.square_channels[index].sample_countdown = (gb->apu.square_channels[index].sample_length ^ 0x7FF) * 2 + gb->apu.square_channels[index].delay;
1850 }
1851 else {
1852 unsigned extra_delay = 0;
1853 if (gb->model == GB_MODEL_CGB_E || gb->model == GB_MODEL_CGB_D) {
1854 if (!gb->apu.square_channels[index].just_reloaded && !(value & 4) && !(((gb->apu.square_channels[index].sample_countdown - 1 - gb->apu.square_channels[index].delay) / 2) & 0x400)) {
1855 gb->apu.square_channels[index].current_sample_index++;
1856 gb->apu.square_channels[index].current_sample_index &= 0x7;
1857 gb->apu.square_channels[index].sample_surpressed = false;
1858 }
1859 /* Todo: verify with the schematics what's going on in here */
1860 else if (gb->apu.square_channels[index].sample_length == 0x7FF &&
1861 old_sample_length != 0x7FF &&
1862 (gb->apu.square_channels[index].sample_surpressed)) {
1863 extra_delay += 2;
1864 }
1865 }
1866 /* Timing quirk: if already active, sound starts 2 (2MHz) ticks earlier.*/
1867 gb->apu.square_channels[index].delay = 4 - gb->apu.lf_div + extra_delay;
1868 gb->apu.square_channels[index].sample_countdown = (gb->apu.square_channels[index].sample_length ^ 0x7FF) * 2 + gb->apu.square_channels[index].delay;
1869 }
1870 gb->apu.square_channels[index].current_volume = gb->io_registers[index == GB_SQUARE_1 ? GB_IO_NR12 : GB_IO_NR22] >> 4;
1871 /* The volume changes caused by NRx4 sound start takes effect instantly (i.e. the effect the previously
1872 started sound). The playback itself is not instant which is why we don't update the sample for other
1873 cases. */
1874 if (gb->apu.is_active[index]) {
1875 update_square_sample(gb, index, 0);
1876 }
1877
1878 gb->apu.square_channels[index].volume_countdown = gb->io_registers[index == GB_SQUARE_1 ? GB_IO_NR12 : GB_IO_NR22] & 7;
1879
1880 if ((gb->io_registers[index == GB_SQUARE_1 ? GB_IO_NR12 : GB_IO_NR22] & 0xF8) != 0 && !gb->apu.is_active[index]) {
1881 gb->apu.is_active[index] = true;
1882 update_sample(gb, index, 0, 0);
1883 gb->apu.square_channels[index].sample_surpressed = true && !force_unsurpressed;
1884 }
1885 if (gb->apu.square_channels[index].pulse_length == 0) {
1886 gb->apu.square_channels[index].pulse_length = 0x40;
1887 gb->apu.square_channels[index].length_enabled = false;
1888 }
1889
1890 if (index == GB_SQUARE_1) {
1891 gb->apu.square_sweep_instant_calculation_done = false;
1892 gb->apu.shadow_sweep_sample_length = 0;
1893 gb->apu.channel1_completed_addend = 0;
1894 if (gb->io_registers[GB_IO_NR10] & 7) {
1895 /* APU bug: if shift is nonzero, overflow check also occurs on trigger */
1896 gb->apu.square_sweep_calculate_countdown = gb->io_registers[GB_IO_NR10] & 0x7;
1897 if ((gb->apu.lf_div ^ !gb->cgb_double_speed) && gb->model <= GB_MODEL_CGB_C) {
1898 gb->apu.square_sweep_calculate_countdown_reload_timer = 3;
1899 }
1900 else {
1901 gb->apu.square_sweep_calculate_countdown_reload_timer = 2;
1902 }
1903 gb->apu.unshifted_sweep = false;
1904 if (!was_active) {
1905 gb->apu.square_sweep_calculate_countdown_reload_timer++;
1906 }
1907 gb->apu.sweep_length_addend = gb->apu.square_channels[GB_SQUARE_1].sample_length;
1908 gb->apu.sweep_length_addend >>= (gb->io_registers[GB_IO_NR10] & 7);
1909 }
1910 else {
1911 gb->apu.sweep_length_addend = 0;
1912 }
1913 gb->apu.channel_1_restart_hold = 2 - gb->apu.lf_div + (GB_is_cgb(gb) && gb->model != GB_MODEL_CGB_D) * 2;
1914 gb->apu.square_sweep_countdown = ((gb->io_registers[GB_IO_NR10] >> 4) & 7) ^ 7;
1915 }
1916 }
1917
1918 /* APU glitch - if length is enabled while the DIV-divider's LSB is 1, tick the length once. */
1919 if (((value & 0x40) || (GB_is_cgb(gb) && gb->model <= GB_MODEL_CGB_B)) && // Current value is irrelevant on CGB-B and older
1920 !gb->apu.square_channels[index].length_enabled &&
1921 (gb->apu.div_divider & 1) &&
1922 gb->apu.square_channels[index].pulse_length) {
1923 gb->apu.square_channels[index].pulse_length--;
1924 if (gb->apu.square_channels[index].pulse_length == 0) {
1925 if (value & 0x80) {
1926 gb->apu.square_channels[index].pulse_length = 0x3F;
1927 }
1928 else {
1929 gb->apu.is_active[index] = false;
1930 update_sample(gb, index, 0, 0);
1931 }
1932 }
1933 }
1934 gb->apu.square_channels[index].length_enabled = value & 0x40;
1935 break;
1936 }
1937
1938 /* Wave channel */
1939 case GB_IO_NR30:
1940 gb->apu.wave_channel.enable = value & 0x80;
1941 if (!gb->apu.wave_channel.enable) {
1942 gb->apu.wave_channel.pulsed = false;
1943 if (gb->apu.is_active[GB_WAVE]) {
1944 // Todo: I assume this happens on pre-CGB models; test this with an audible test
1945 if (gb->apu.wave_channel.sample_countdown == 0 && gb->model <= GB_MODEL_CGB_E) {
1946 gb->apu.wave_channel.current_sample_byte = gb->io_registers[GB_IO_WAV_START + (gb->pc & 0xF)];
1947 }
1948 else if (gb->apu.wave_channel.wave_form_just_read && gb->model <= GB_MODEL_CGB_C) {
1949 gb->apu.wave_channel.current_sample_byte = gb->io_registers[GB_IO_WAV_START + (GB_IO_NR30 & 0xF)];
1950 }
1951 }
1952 gb->apu.is_active[GB_WAVE] = false;
1953 update_sample(gb, GB_WAVE, 0, 0);
1954 }
1955 break;
1956 case GB_IO_NR31:
1957 gb->apu.wave_channel.pulse_length = (0x100 - value);
1958 break;
1959 case GB_IO_NR32:
1960 gb->apu.wave_channel.shift = inline_const(uint8_t[], {4, 0, 1, 2})[(value >> 5) & 3];
1961 if (gb->apu.is_active[GB_WAVE]) {
1962 update_wave_sample(gb, 0);
1963 }
1964 break;
1965 case GB_IO_NR33:
1966 gb->apu.wave_channel.sample_length &= ~0xFF;
1967 gb->apu.wave_channel.sample_length |= value & 0xFF;
1968 if (gb->apu.wave_channel.bugged_read_countdown == 1) { // Just reloaded countdown
1969 /* TODO: not verified with a test ROM yet */
1970 gb->apu.wave_channel.sample_countdown = gb->apu.wave_channel.sample_length ^ 0x7FF;
1971 }
1972 break;
1973 case GB_IO_NR34:
1974 gb->apu.wave_channel.sample_length &= 0xFF;
1975 gb->apu.wave_channel.sample_length |= (value & 7) << 8;
1976 if (value & 0x80) {
1977 gb->apu.wave_channel.pulsed = true;
1978 /* DMG bug: wave RAM gets corrupted if the channel is retriggerred 1 cycle before the APU
1979 reads from it. */
1980 if (!GB_is_cgb(gb) &&
1981 gb->apu.is_active[GB_WAVE] &&
1982 gb->apu.wave_channel.sample_countdown == 0) {
1983 unsigned offset = ((gb->apu.wave_channel.current_sample_index + 1) >> 1) & 0xF;
1984
1985 /* This glitch varies between models and even specific instances:
1986 DMG-B: Most of them behave as emulated. A few behave differently.
1987 SGB: As far as I know, all tested instances behave as emulated.
1988 MGB, SGB2: Most instances behave non-deterministically, a few behave as emulated.
1989
1990 For DMG-B emulation I emulate the most common behavior, which blargg's tests expect (not my own DMG-B, which fails it)
1991 For MGB emulation, I emulate my Game Boy Light, which happens to be deterministic.
1992
1993 Additionally, I believe DMGs, including those we behave differently than emulated,
1994 are all deterministic. */
1995 if (offset < 4 && gb->model != GB_MODEL_MGB) {
1996 gb->io_registers[GB_IO_WAV_START] = gb->io_registers[GB_IO_WAV_START + offset];
1997 }
1998 else {
1999 memcpy(gb->io_registers + GB_IO_WAV_START,
2000 gb->io_registers + GB_IO_WAV_START + (offset & ~3),
2001 4);
2002 }
2003 }
2004 gb->apu.wave_channel.current_sample_index = 0;
2005 if (gb->apu.is_active[GB_WAVE] && gb->apu.wave_channel.sample_countdown == 0) {
2006 gb->apu.wave_channel.current_sample_byte = gb->io_registers[GB_IO_WAV_START];
2007 }
2008 if (gb->apu.wave_channel.enable) {
2009 gb->apu.is_active[GB_WAVE] = true;
2010 update_sample(gb, GB_WAVE,
2011 (gb->apu.wave_channel.current_sample_byte >> 4) >> gb->apu.wave_channel.shift,
2012 0);
2013 }
2014 gb->apu.wave_channel.sample_countdown = (gb->apu.wave_channel.sample_length ^ 0x7FF) + 3;
2015 if (gb->apu.wave_channel.pulse_length == 0) {
2016 gb->apu.wave_channel.pulse_length = 0x100;
2017 gb->apu.wave_channel.length_enabled = false;
2018 }
2019 /* Note that we don't change the sample just yet! This was verified on hardware. */
2020 }
2021
2022 /* APU glitch - if length is enabled while the DIV-divider's LSB is 1, tick the length once. */
2023 if (((value & 0x40) || (GB_is_cgb(gb) && gb->model <= GB_MODEL_CGB_B)) && // Current value is irrelevant on CGB-B and older
2024 !gb->apu.wave_channel.length_enabled &&
2025 (gb->apu.div_divider & 1) &&
2026 gb->apu.wave_channel.pulse_length) {
2027 gb->apu.wave_channel.pulse_length--;
2028 if (gb->apu.wave_channel.pulse_length == 0) {
2029 if (value & 0x80) {
2030 gb->apu.wave_channel.pulse_length = 0xFF;
2031 }
2032 else {
2033 gb->apu.is_active[GB_WAVE] = false;
2034 update_sample(gb, GB_WAVE, 0, 0);
2035 }
2036 }
2037 }
2038 gb->apu.wave_channel.length_enabled = value & 0x40;
2039
2040 break;
2041
2042 /* Noise Channel */
2043
2044 case GB_IO_NR41: {
2045 gb->apu.noise_channel.pulse_length = (0x40 - (value & 0x3F));
2046 break;
2047 }
2048
2049 case GB_IO_NR42: {
2050 if ((value & 0xF8) == 0) {
2051 /* This disables the DAC */
2052 if (gb->apu.is_active[GB_NOISE] && gb->io_registers[GB_IO_NR43] & 7) {
2053 if (gb->apu.noise_channel.counter_countdown <= 2) {
2054 gb->apu.noise_channel.counter++;
2055 }
2056 gb->apu.noise_background_counter_active = false;
2057 }
2058
2059 gb->io_registers[reg] = value;
2060 gb->apu.is_active[GB_NOISE] = false;
2061 update_sample(gb, GB_NOISE, 0, 0);
2062 gb->apu.noise_counter_active = false;
2063 }
2064 else if (gb->apu.is_active[GB_NOISE]) {
2065 nrx2_glitch(gb, &gb->apu.noise_channel.current_volume,
2066 value, gb->io_registers[reg], &gb->apu.noise_channel.volume_countdown,
2067 &gb->apu.noise_channel.envelope_clock);
2068 update_sample(gb, GB_NOISE,
2069 gb->apu.noise_channel.current_lfsr_sample ?
2070 gb->apu.noise_channel.current_volume : 0,
2071 0);
2072 }
2073 break;
2074 }
2075
2076 case GB_IO_NR43: {
2077 if (gb->apu.noise_channel.countdown_reloaded) {
2078 unsigned divisor = (value & 0x07) << 2;
2079 if (!divisor) divisor = 2;
2080 if (gb->model > GB_MODEL_CGB_C) {
2081 gb->apu.noise_channel.counter_countdown =
2082 divisor + (divisor == 2? 0 : inline_const(uint8_t[], {2, 1, 0, 3})[(gb->apu.noise_channel.alignment) & 3]);
2083 }
2084 else {
2085 gb->apu.noise_channel.counter_countdown =
2086 divisor + (divisor == 2? 0 : inline_const(uint8_t[], {2, 1, 4, 3})[(gb->apu.noise_channel.alignment) & 3]);
2087 }
2088 }
2089 if (gb->model <= GB_MODEL_CGB_C) {
2090 /* TODO: CGB≤C (and DMG) have various unemulated quirks when you write to NR43 just as the counter reloads */
2091 if (gb->apu.noise_channel.countdown_reloaded) {
2092 bool old_bit = (gb->apu.noise_channel.counter >> (gb->io_registers[GB_IO_NR43] >> 4)) & 1;
2093 bool glitch_bit = (gb->apu.noise_channel.counter >> 7) & 1;
2094 bool new_bit = (gb->apu.noise_channel.counter >> (value >> 4)) & 1;
2095
2096 if (!old_bit && new_bit && glitch_bit) {
2097 uint16_t previous_counter = (gb->apu.noise_channel.counter - 1) & 0x3FFF;
2098 bool old_bit = (previous_counter >> (gb->io_registers[GB_IO_NR43] >> 4)) & 1;
2099 bool glitch_bit = (previous_counter >> 7) & 1;
2100 bool new_bit = (previous_counter >> (value >> 4)) & 1;
2101 if (old_bit && !new_bit && glitch_bit) {
2102 step_lfsr(gb, 0);
2103 }
2104 }
2105 }
2106 nr43_write(gb, 0xff);
2107 }
2108 nr43_write(gb, value);
2109
2110 break;
2111 }
2112
2113 case GB_IO_NR44: {
2114 if (value & 0x80) {
2115 gb->apu.noise_channel.envelope_clock.locked = false;
2116 gb->apu.noise_channel.envelope_clock.clock = false;
2117 if (!GB_is_cgb(gb) && (gb->apu.noise_channel.alignment & 3) != 0) {
2118 gb->apu.noise_channel.dmg_delayed_start = 6;
2119 }
2120 else {
2121 gb->apu.noise_channel.lfsr = 0;
2122 prepare_noise_start(gb);
2123
2124 gb->apu.noise_channel.current_volume = gb->io_registers[GB_IO_NR42] >> 4;
2125 gb->apu.noise_channel.current_lfsr_sample = false;
2126 gb->apu.noise_channel.volume_countdown = gb->io_registers[GB_IO_NR42] & 7;
2127 gb->apu.noise_channel.did_step_counter = (gb->apu.noise_channel.alignment & 3) == 2;
2128
2129 if (gb->io_registers[GB_IO_NR42] & 0xF8) {
2130 gb->apu.is_active[GB_NOISE] = true;
2131 update_sample(gb, GB_NOISE, 0, 0);
2132 }
2133
2134 if (gb->apu.noise_channel.pulse_length == 0) {
2135 gb->apu.noise_channel.pulse_length = 0x40;
2136 gb->apu.noise_channel.length_enabled = false;
2137 }
2138 }
2139 }
2140
2141 /* APU glitch - if length is enabled while the DIV-divider's LSB is 1, tick the length once. */
2142 if ((value & 0x40) &&
2143 !gb->apu.noise_channel.length_enabled &&
2144 (gb->apu.div_divider & 1) &&
2145 gb->apu.noise_channel.pulse_length) {
2146 gb->apu.noise_channel.pulse_length--;
2147 if (gb->apu.noise_channel.pulse_length == 0) {
2148 if (value & 0x80) {
2149 gb->apu.noise_channel.pulse_length = 0x3F;
2150 }
2151 else {
2152 gb->apu.is_active[GB_NOISE] = false;
2153 update_sample(gb, GB_NOISE, 0, 0);
2154 }
2155 }
2156 }
2157 gb->apu.noise_channel.length_enabled = value & 0x40;
2158 break;
2159 }
2160 }
2161 gb->io_registers[reg] = value;
2162 }
2163
2164 void GB_set_sample_rate(GB_gameboy_t *gb, unsigned sample_rate)
2165 {
2166 if (gb->apu_output.sample_rate != sample_rate) {
2167 GB_ASSERT_NOT_RUNNING_OTHER_THREAD(gb)
2168 }
2169 gb->apu_output.sample_rate = sample_rate;
2170 if (sample_rate) {
2171 gb->apu_output.highpass_rate = pow(0.999958, GB_get_clock_rate(gb) / (double)sample_rate);
2172 gb->apu_output.max_cycles_per_sample = ceil(GB_get_clock_rate(gb) / 2.0 / sample_rate);
2173 gb->apu_output.quick_fraction_multiply_cache[0] = round(sample_rate * 2.0 / GB_get_clock_rate(gb) * (1 << 28));
2174 for (unsigned i = 1; i < GB_QUICK_MULTIPLY_COUNT; i++) {
2175 gb->apu_output.quick_fraction_multiply_cache[i] = gb->apu_output.quick_fraction_multiply_cache[0] * (i + 1);
2176 }
2177 }
2178 else {
2179 gb->apu_output.max_cycles_per_sample = 0x400;
2180 }
2181 }
2182
2183 void GB_set_sample_rate_by_clocks(GB_gameboy_t *gb, double cycles_per_sample)
2184 {
2185 GB_ASSERT_NOT_RUNNING_OTHER_THREAD(gb)
2186 if (cycles_per_sample == 0) {
2187 GB_set_sample_rate(gb, 0);
2188 return;
2189 }
2190 gb->apu_output.sample_rate = GB_get_clock_rate(gb) / cycles_per_sample * 2;
2191 gb->apu_output.highpass_rate = pow(0.999958, cycles_per_sample);
2192 gb->apu_output.max_cycles_per_sample = ceil(cycles_per_sample / 4);
2193
2194 gb->apu_output.quick_fraction_multiply_cache[0] = round(gb->apu_output.sample_rate * 2.0 / GB_get_clock_rate(gb) * (1 << 28));
2195 for (unsigned i = 1; i < GB_QUICK_MULTIPLY_COUNT; i++) {
2196 gb->apu_output.quick_fraction_multiply_cache[i] = gb->apu_output.quick_fraction_multiply_cache[0] * (i + 1);
2197 }
2198 }
2199
2200 unsigned GB_get_sample_rate(GB_gameboy_t *gb)
2201 {
2202 return gb->apu_output.sample_rate;
2203 }
2204
2205 void GB_apu_set_sample_callback(GB_gameboy_t *gb, GB_sample_callback_t callback)
2206 {
2207 gb->apu_output.sample_callback = callback;
2208 }
2209
2210 void GB_set_highpass_filter_mode(GB_gameboy_t *gb, GB_highpass_mode_t mode)
2211 {
2212 gb->apu_output.highpass_mode = mode;
2213 }
2214
2215 void GB_set_interference_volume(GB_gameboy_t *gb, double volume)
2216 {
2217 gb->apu_output.interference_volume = volume;
2218 }
2219
2220 typedef struct __attribute__((packed)) {
2221 uint32_t format_chunk; // = BE32('FORM')
2222 uint32_t size; // = BE32(file size - 8)
2223 uint32_t format; // = BE32('AIFC')
2224
2225 uint32_t fver_chunk; // = BE32('FVER')
2226 uint32_t fver_size; // = BE32(4)
2227 uint32_t fver;
2228
2229 uint32_t comm_chunk; // = BE32('COMM')
2230 uint32_t comm_size; // = BE32(0x18)
2231
2232 uint16_t channels; // = BE16(2)
2233 uint32_t samples_per_channel; // = BE32(total number of samples / 2)
2234 uint16_t bit_depth; // = BE16(16)
2235 uint16_t frequency_exponent;
2236 uint64_t frequency_significand;
2237 uint32_t compression_type; // = 'NONE' (BE) or 'twos' (LE)
2238 uint16_t compression_name; // = 0
2239
2240 uint32_t ssnd_chunk; // = BE32('SSND')
2241 uint32_t ssnd_size; // = BE32(length of samples - 8)
2242 uint32_t ssnd_offset; // = 0
2243 uint32_t ssnd_block; // = 0
2244 } aiff_header_t;
2245
2246 typedef struct __attribute__((packed)) {
2247 uint32_t marker; // = BE32('RIFF')
2248 uint32_t size; // = LE32(file size - 8)
2249 uint32_t type; // = BE32('WAVE')
2250
2251 uint32_t fmt_chunk; // = BE32('fmt ')
2252 uint32_t fmt_size; // = LE16(16)
2253 uint16_t format; // = LE16(1)
2254 uint16_t channels; // = LE16(2)
2255 uint32_t sample_rate; // = LE32(sample_rate)
2256 uint32_t byte_rate; // = LE32(sample_rate * 4)
2257 uint16_t frame_size; // = LE32(4)
2258 uint16_t bit_depth; // = LE16(16)
2259
2260 uint32_t data_chunk; // = BE32('data')
2261 uint32_t data_size; // = LE32(length of samples)
2262 } wav_header_t;
2263
2264
2265 int GB_start_audio_recording(GB_gameboy_t *gb, const char *path, GB_audio_format_t format)
2266 {
2267 if (gb->apu_output.sample_rate == 0) {
2268 return EINVAL;
2269 }
2270
2271 if (gb->apu_output.output_file) {
2272 GB_stop_audio_recording(gb);
2273 }
2274 gb->apu_output.output_file = fopen(path, "wb");
2275 if (!gb->apu_output.output_file) return errno;
2276
2277 gb->apu_output.output_format = format;
2278 switch (format) {
2279 case GB_AUDIO_FORMAT_RAW:
2280 return 0;
2281 case GB_AUDIO_FORMAT_AIFF: {
2282 aiff_header_t header = {0,};
2283 if (fwrite(&header, sizeof(header), 1, gb->apu_output.output_file) != 1) {
2284 int ret = errno ?: EIO;
2285 fclose(gb->apu_output.output_file);
2286 gb->apu_output.output_file = NULL;
2287 return ret;
2288 }
2289 return 0;
2290 }
2291 case GB_AUDIO_FORMAT_WAV: {
2292 wav_header_t header = {0,};
2293 if (fwrite(&header, sizeof(header), 1, gb->apu_output.output_file) != 1) {
2294 int ret = errno ?: EIO;
2295 fclose(gb->apu_output.output_file);
2296 gb->apu_output.output_file = NULL;
2297 return ret;
2298 }
2299 return 0;
2300 }
2301 default:
2302 fclose(gb->apu_output.output_file);
2303 gb->apu_output.output_file = NULL;
2304 return EINVAL;
2305 }
2306 }
2307 int GB_stop_audio_recording(GB_gameboy_t *gb)
2308 {
2309 if (!gb->apu_output.output_file) {
2310 int ret = gb->apu_output.output_error ?: -1;
2311 gb->apu_output.output_error = 0;
2312 return ret;
2313 }
2314 gb->apu_output.output_error = 0;
2315 switch (gb->apu_output.output_format) {
2316 case GB_AUDIO_FORMAT_RAW:
2317 break;
2318 case GB_AUDIO_FORMAT_AIFF: {
2319 size_t file_size = ftell(gb->apu_output.output_file);
2320 size_t frames = (file_size - sizeof(aiff_header_t)) / sizeof(GB_sample_t);
2321 aiff_header_t header = {
2322 .format_chunk = BE32('FORM'),
2323 .size = BE32(file_size - 8),
2324 .format = BE32('AIFC'),
2325
2326 .fver_chunk = BE32('FVER'),
2327 .fver_size = BE32(4),
2328 .fver = BE32(0xA2805140),
2329
2330 .comm_chunk = BE32('COMM'),
2331 .comm_size = BE32(0x18),
2332 .channels = BE16(2),
2333 .samples_per_channel = BE32(frames),
2334 .bit_depth = BE16(16),
2335 #ifdef GB_BIG_ENDIAN
2336 .compression_type = 'NONE',
2337 #else
2338 .compression_type = 'twos',
2339 #endif
2340 .compression_name = 0,
2341 .ssnd_chunk = BE32('SSND'),
2342 .ssnd_size = BE32(frames * sizeof(GB_sample_t) - 8),
2343 .ssnd_offset = 0,
2344 .ssnd_block = 0,
2345 };
2346
2347 uint64_t significand = gb->apu_output.sample_rate;
2348 uint16_t exponent = 0x403E;
2349 while ((int64_t)significand > 0) {
2350 significand <<= 1;
2351 exponent--;
2352 }
2353 header.frequency_exponent = BE16(exponent);
2354 header.frequency_significand = BE64(significand);
2355
2356 fseek(gb->apu_output.output_file, 0, SEEK_SET);
2357 if (fwrite(&header, sizeof(header), 1, gb->apu_output.output_file) != 1) {
2358 gb->apu_output.output_error = errno;
2359 }
2360 break;
2361 }
2362 case GB_AUDIO_FORMAT_WAV: {
2363 size_t file_size = ftell(gb->apu_output.output_file);
2364 size_t frames = (file_size - sizeof(wav_header_t)) / sizeof(GB_sample_t);
2365 wav_header_t header = {
2366 .marker = BE32('RIFF'),
2367 .size = LE32(file_size - 8),
2368 .type = BE32('WAVE'),
2369
2370 .fmt_chunk = BE32('fmt '),
2371 .fmt_size = LE16(16),
2372 .format = LE16(1),
2373 .channels = LE16(2),
2374 .sample_rate = LE32(gb->apu_output.sample_rate),
2375 .byte_rate = LE32(gb->apu_output.sample_rate * 4),
2376 .frame_size = LE32(4),
2377 .bit_depth = LE16(16),
2378
2379 .data_chunk = BE32('data'),
2380 .data_size = LE32(frames * sizeof(GB_sample_t)),
2381 };
2382
2383 fseek(gb->apu_output.output_file, 0, SEEK_SET);
2384 if (fwrite(&header, sizeof(header), 1, gb->apu_output.output_file) != 1) {
2385 gb->apu_output.output_error = errno;
2386 }
2387 break;
2388 }
2389 }
2390 fclose(gb->apu_output.output_file);
2391 gb->apu_output.output_file = NULL;
2392
2393 int ret = gb->apu_output.output_error;
2394 gb->apu_output.output_error = 0;
2395 return ret;
2396 }
2397
2398
2399 void GB_set_channel_muted(GB_gameboy_t *gb, GB_channel_t channel, bool muted)
2400 {
2401 assert(channel < GB_N_CHANNELS);
2402 gb->apu_output.channel_muted[channel] = muted;
2403 }
2404
2405 bool GB_is_channel_muted(GB_gameboy_t *gb, GB_channel_t channel)
2406 {
2407 return gb->apu_output.channel_muted[channel];
2408 }
2409
2410 // Note: this intentionally does not check to see if the channel is muted.
2411 uint8_t GB_get_channel_volume(GB_gameboy_t *gb, GB_channel_t channel)
2412 {
2413 switch (channel) {
2414 case GB_SQUARE_1:
2415 case GB_SQUARE_2:
2416 return gb->apu.square_channels[channel].current_volume;
2417
2418 case GB_WAVE:
2419 return inline_const(uint8_t[], {0xF, 8, 4, 0, 0})[gb->apu.wave_channel.shift];
2420
2421 case GB_NOISE:
2422 return gb->apu.noise_channel.current_volume;
2423
2424 default:
2425 return 0;
2426 }
2427 }
2428
2429 uint8_t GB_get_channel_amplitude(GB_gameboy_t *gb, GB_channel_t channel)
2430 {
2431 return gb->apu.is_active[channel] ? gb->apu.samples[channel] : 0;
2432 }
2433
2434 uint16_t GB_get_channel_period(GB_gameboy_t *gb, GB_channel_t channel)
2435 {
2436 switch (channel) {
2437 case GB_SQUARE_1:
2438 case GB_SQUARE_2:
2439 return gb->apu.square_channels[channel].sample_length;
2440
2441 case GB_WAVE:
2442 return gb->apu.wave_channel.sample_length;
2443
2444 case GB_NOISE:
2445 return (gb->io_registers[GB_IO_NR43] & 7) << (gb->io_registers[GB_IO_NR43] >> 4);
2446
2447 default:
2448 return 0;
2449 }
2450 }
2451
2452 // wave_table is a user allocated uint8_t[32] array
2453 void GB_get_apu_wave_table(GB_gameboy_t *gb, uint8_t *wave_table)
2454 {
2455 for (unsigned i = GB_IO_WAV_START; i <= GB_IO_WAV_END; i++) {
2456 wave_table[2 * (i - GB_IO_WAV_START)] = gb->io_registers[i] >> 4;
2457 wave_table[2 * (i - GB_IO_WAV_START) + 1] = gb->io_registers[i] & 0xF;
2458 }
2459 }
2460
2461 bool GB_get_channel_edge_triggered(GB_gameboy_t *gb, GB_channel_t channel)
2462 {
2463 bool edge_triggered = gb->apu_output.edge_triggered[channel];
2464 gb->apu_output.edge_triggered[channel] = false;
2465 return edge_triggered;
2466 }
This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.