1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// ── CH3 — Wave ────────────────────────────────────────────────────────────────
use serde::{Deserialize, Serialize};
/// Number of 4-bit samples per wave RAM bank.
pub(super) const SAMPLES_PER_BANK: u8 = 32;
/// Channel 3: wave playback (32 × 4-bit samples, or 64 × 4-bit samples in two-bank mode).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Channel3 {
pub dac_on: bool,
/// Bit 5 of SOUND3CNT_L: 0 = one bank (32 samples), 1 = two banks (64 samples).
pub two_banks: bool,
/// Bit 6 of SOUND3CNT_L: selects which bank (0 or 1) is played back.
/// The OTHER bank is accessible via Wave RAM register reads/writes.
pub bank_select: bool,
pub length_counter: u16,
pub output_level: u8, // 0=mute, 1=100%, 2=50%, 3=25%
/// Bit 15 of SOUND3CNT_H: when true, forces 75% volume regardless of output_level.
pub force_volume: bool,
pub freq: u16,
pub length_en: bool,
pub active: bool,
pub wave_pos: u8, // 0-31 (single bank) or 0-63 (two banks)
pub freq_timer: u32,
/// Wave RAM: 2 banks × 16 bytes = 32 bytes total (64 × 4-bit samples).
pub wave_ram: [[u8; 16]; 2],
/// Current 4-bit output nibble.
pub current_sample: u8,
}
impl Channel3 {
/// Analogue output in `[-1.0, +1.0]`; 0.0 when inactive, DAC is off
/// (disconnected), or output_level mutes the channel.
///
/// Per GBATek, the PSG DAC converts digital value D (0–15) to bipolar:
/// output = (D / 7.5) − 1.0
pub fn output(&self) -> f32 {
if !self.active || !self.dac_on {
return 0.0;
}
// Bit 15 of SOUND3CNT_H: force 75% volume regardless of output_level.
let d = if self.force_volume {
((self.current_sample as u16 * 3) / 4) as f32
} else {
let shift: u8 = match self.output_level {
1 => 0, // 100 %
2 => 1, // 50 %
3 => 2, // 25 %
_ => return 0.0,
};
(self.current_sample >> shift) as f32
};
d / 7.5 - 1.0
}
/// Advance channel by `cycles` GBA cycles.
/// Each wave_pos step takes (2048 − freq) × 8 GBA cycles.
pub fn tick(&mut self, cycles: u32) {
if !self.active {
return;
}
let period = (2048_u32.wrapping_sub(self.freq as u32)) * 8;
if period == 0 {
return;
}
// Use a bitmask to wrap wave_pos: single-bank → mask 0x1F (& 31), two-bank → 0x3F (& 63).
let pos_mask: u8 = if self.two_banks { 0x3F } else { 0x1F };
let mut rem = cycles;
while rem > 0 {
if self.freq_timer == 0 {
self.freq_timer = period;
}
let advance = rem.min(self.freq_timer);
self.freq_timer -= advance;
rem -= advance;
if self.freq_timer == 0 {
self.wave_pos = (self.wave_pos + 1) & pos_mask;
// Samples 0..(SAMPLES_PER_BANK-1) come from bank_select; the rest from the other bank.
let bank = if self.wave_pos < SAMPLES_PER_BANK {
self.bank_select as usize
} else {
(self.bank_select as usize) ^ 1
};
let pos_in_bank = self.wave_pos & (SAMPLES_PER_BANK - 1);
let byte = self.wave_ram[bank][(pos_in_bank / 2) as usize];
self.current_sample = if pos_in_bank & 1 == 0 {
(byte >> 4) & 0x0F // high nibble
} else {
byte & 0x0F // low nibble
};
self.freq_timer = period;
}
}
}
pub fn clock_length(&mut self) {
if !self.length_en || self.length_counter == 0 {
return;
}
self.length_counter -= 1;
if self.length_counter == 0 {
self.active = false;
}
}
fn trigger(&mut self) {
self.active = self.dac_on;
if self.length_counter == 0 {
self.length_counter = 256;
}
let period = (2048_u32.wrapping_sub(self.freq as u32)) * 8;
self.freq_timer = period;
self.wave_pos = 0;
// Read first sample from the playing bank (position 0 = high nibble of byte 0).
let bank = self.bank_select as usize;
self.current_sample = (self.wave_ram[bank][0] >> 4) & 0x0F;
}
// ── Register writes ───────────────────────────────────────────────────
/// SOUND3CNT_L: wave RAM dimension (bit 5), bank select (bit 6), DAC enable (bit 7).
pub fn write_cnt_l(&mut self, val: u16) {
self.two_banks = (val & 0x0020) != 0;
self.bank_select = (val & 0x0040) != 0;
self.dac_on = (val & 0x0080) != 0;
if !self.dac_on {
self.active = false;
}
}
/// SOUND3CNT_H: sound length (bits 7-0), output level (bits 14-13), force volume (bit 15).
pub fn write_cnt_h(&mut self, val: u16) {
// Lower byte = sound length (0-255, counter = 256 - length)
self.length_counter = 256 - (val & 0x00FF);
// Bits 14-13: output level
self.output_level = ((val >> 13) & 0x03) as u8;
// Bit 15: force 75% volume regardless of output_level
self.force_volume = (val & 0x8000) != 0;
}
/// SOUND3CNT_X: frequency and trigger.
///
/// `extra_clk` — see Channel1::write_cnt_x for the full description.
/// Note: CH3's maximum length counter is 256 (not 64).
pub fn write_cnt_x(&mut self, val: u16, extra_clk: bool) {
self.freq = val & 0x7FF;
let old_length_en = self.length_en;
self.length_en = (val & 0x4000) != 0;
// Extra clock when enabling length_en (0→1) and next FS step won't clock.
if extra_clk && !old_length_en && self.length_en && self.length_counter > 0 {
self.length_counter -= 1;
if self.length_counter == 0 {
self.active = false;
}
}
if val & 0x8000 != 0 {
let reloaded_length = self.length_counter == 0;
self.trigger();
// CH3 reloads to 256 (not 64).
if extra_clk && self.length_en && reloaded_length {
self.length_counter = 255;
}
}
}
/// Write one byte to wave RAM (address offset 0x00–0x0F from wave RAM base).
/// Always accesses the bank NOT currently selected for playback.
pub fn write_wave_ram(&mut self, offset: usize, val: u8) {
let other_bank = (self.bank_select as usize) ^ 1;
if offset < 16 {
self.wave_ram[other_bank][offset] = val;
}
}
/// Read one byte from wave RAM.
/// Always accesses the bank NOT currently selected for playback.
///
/// Per mGBA / GBATek: the shift-register rotation only physically affects the
/// **playing** bank. The non-playing bank is never rotated, so CPU reads always
/// return the raw stored byte at the given offset regardless of playback state.
pub fn read_wave_ram(&self, offset: usize) -> u8 {
let other_bank = (self.bank_select as usize) ^ 1;
if offset >= 16 {
return 0xFF;
}
self.wave_ram[other_bank][offset]
}
pub fn power_off(&mut self) {
let wave_ram = self.wave_ram;
*self = Self::default();
self.wave_ram = wave_ram; // both wave RAM banks survive power-off
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ch3_force_volume_output_is_75_percent() {
// When force_volume is set, output() must apply 75% scaling then bipolar formula.
// Sample = 1 -> (1*3)/4 = 0 (integer truncation), D=0, output = 0/7.5 - 1.0 = -1.0.
let ch3 = Channel3 {
dac_on: true,
active: true,
force_volume: true,
current_sample: 1,
output_level: 0, // would normally mute — force_volume overrides
..Channel3::default()
};
let got = ch3.output();
let d = (3_u16 / 4) as f32;
let expected = d / 7.5 - 1.0;
assert!(
(got - expected).abs() < 1e-5,
"force_volume output mismatch: expected {expected}, got {got}"
);
}
#[test]
fn test_ch3_force_volume_overrides_output_level() {
// When force_volume is set and output_level=3 (25%), 75% applies instead.
// Sample = 12 → force 75%: D = 12*3/4 = 9; output = 9/7.5 - 1.0 = 0.2
// Normal 25%: 12 >> 2 = 3; 3/7.5 - 1.0 = -0.6
let ch3 = Channel3 {
dac_on: true,
active: true,
force_volume: true,
current_sample: 12,
output_level: 3, // 25% — should be overridden
..Channel3::default()
};
let got = ch3.output();
let d = ((12_u16 * 3) / 4) as f32; // = 9.0
let expected = d / 7.5 - 1.0; // = 0.2
assert!(
(got - expected).abs() < 1e-5,
"force_volume should override output_level: expected {expected}, got {got}"
);
}
// ── Bipolar output formula tests ──────────────────────────────────────────
#[test]
fn test_ch3_dac_off_outputs_zero() {
let ch3 = Channel3 {
dac_on: false,
active: false,
..Channel3::default()
};
assert_eq!(ch3.output(), 0.0);
}
#[test]
fn test_ch3_sample_zero_outputs_minus_one() {
// D=0 → output = 0/7.5 - 1.0 = -1.0
let ch3 = Channel3 {
dac_on: true,
active: true,
output_level: 1, // 100%
current_sample: 0,
..Channel3::default()
};
let got = ch3.output();
assert!(
(got - (-1.0_f32)).abs() < 1e-5,
"sample=0 must produce -1.0, got {got}"
);
}
#[test]
fn test_ch3_sample_fifteen_outputs_plus_one() {
// D=15 → output = 15/7.5 - 1.0 = +1.0
let ch3 = Channel3 {
dac_on: true,
active: true,
output_level: 1, // 100%
current_sample: 15,
..Channel3::default()
};
let got = ch3.output();
assert!(
(got - 1.0_f32).abs() < 1e-5,
"sample=15 must produce +1.0, got {got}"
);
}
#[test]
fn test_ch3_sample_eight_at_50pct_is_bipolar() {
// output_level=2 (50%): D = 8 >> 1 = 4; output = 4/7.5 - 1.0 ≈ -0.4667
let ch3 = Channel3 {
dac_on: true,
active: true,
output_level: 2,
current_sample: 8,
..Channel3::default()
};
let expected = 4.0_f32 / 7.5 - 1.0;
let got = ch3.output();
assert!(
(got - expected).abs() < 1e-5,
"50% level sample=8: expected {expected}, got {got}"
);
}
// ── Shift-register read-during-playback tests ─────────────────────────
#[test]
fn test_wave_ram_read_not_active_returns_direct_offset() {
// When CH3 is stopped, reads return data at the exact written offset (no shift).
let mut ch3 = Channel3::default();
// bank_select=0 → other bank = 1
for i in 0..16u8 {
ch3.wave_ram[1][i as usize] = i * 0x11;
}
ch3.wave_pos = 4; // even with wave_pos set, no shift when stopped
// active=false (default)
assert_eq!(
ch3.read_wave_ram(0),
0x00,
"stopped: offset 0 must return wave_ram[1][0]"
);
assert_eq!(
ch3.read_wave_ram(2),
0x22,
"stopped: offset 2 must return wave_ram[1][2]"
);
}
#[test]
fn test_wave_ram_read_active_wave_pos_0_returns_direct_offset() {
// Active playback with wave_pos=0: reads return raw data from the non-playing bank.
let mut ch3 = Channel3::default();
for i in 0..16u8 {
ch3.wave_ram[1][i as usize] = i + 1;
}
ch3.active = true;
ch3.wave_pos = 0;
assert_eq!(
ch3.read_wave_ram(0),
1, // wave_ram[1][0] = 1
"wave_pos=0, active: offset 0 must return wave_ram[1][0]"
);
assert_eq!(
ch3.read_wave_ram(3),
4, // wave_ram[1][3] = 4
"wave_pos=0, active: offset 3 must return wave_ram[1][3]"
);
}
#[test]
fn test_wave_ram_read_active_non_zero_wave_pos_returns_direct_offset() {
// wave_pos must NOT shift reads. The non-playing bank is never rotated by the
// hardware's shift register (only the playing bank rotates), so every offset
// returns the raw stored byte from the non-playing bank regardless of wave_pos.
let mut ch3 = Channel3::default();
// bank_select=0 → other_bank=1
for i in 0..16u8 {
ch3.wave_ram[1][i as usize] = 0xA0 + i;
}
ch3.active = true;
ch3.wave_pos = 4;
assert_eq!(
ch3.read_wave_ram(0),
0xA0,
"wave_pos=4: offset 0 must return wave_ram[1][0] (no shift)"
);
assert_eq!(
ch3.read_wave_ram(1),
0xA1,
"wave_pos=4: offset 1 must return wave_ram[1][1] (no shift)"
);
}
#[test]
fn test_wave_ram_read_active_all_offsets_match_stored_bytes() {
// All 16 offsets should return exactly what was written to the non-playing bank,
// regardless of playback state or wave_pos value.
let mut ch3 = Channel3::default();
for i in 0..16u8 {
let sample_base = i.wrapping_mul(2);
ch3.wave_ram[1][i as usize] = (sample_base << 4) | ((sample_base + 1) & 0x0F);
}
ch3.active = true;
ch3.wave_pos = 1;
for offset in 0..16usize {
let sample_base = (offset as u8).wrapping_mul(2);
let expected = (sample_base << 4) | ((sample_base + 1) & 0x0F);
assert_eq!(
ch3.read_wave_ram(offset),
expected,
"wave_pos=1: offset {offset} must return stored byte {expected:#04x}"
);
}
}
#[test]
fn test_wave_ram_read_active_returns_stored_not_adjacent() {
// Confirm the non-playing bank's last byte is returned as-is (no wrapping/rotation).
let mut ch3 = Channel3::default();
ch3.wave_ram[1][0] = 0xBB;
ch3.wave_ram[1][15] = 0xFF;
ch3.active = true;
ch3.wave_pos = 2;
assert_eq!(
ch3.read_wave_ram(15),
0xFF,
"wave_pos=2: offset 15 must return wave_ram[1][15] = 0xFF (no wrap/rotation)"
);
assert_eq!(
ch3.read_wave_ram(0),
0xBB,
"wave_pos=2: offset 0 must return wave_ram[1][0] = 0xBB (no wrap/rotation)"
);
}
#[test]
fn test_wave_ram_read_active_no_shift_raw_offset() {
// Per mGBA (GBAAudioReadWaveRAM): the physical shift-register rotation only affects
// the PLAYING bank; the non-playing bank is never rotated. CPU reads always target
// the non-playing bank and must return raw, unshifted data regardless of wave_pos.
let mut ch3 = Channel3::default();
// bank_select=0 → other_bank=1
for i in 0..16u8 {
ch3.wave_ram[1][i as usize] = 0xA0 + i;
}
ch3.active = true;
ch3.wave_pos = 4; // must NOT rotate the read
assert_eq!(
ch3.read_wave_ram(0),
0xA0,
"active playback: wave_pos must not rotate wave RAM reads; offset 0 = wave_ram[1][0]"
);
assert_eq!(
ch3.read_wave_ram(5),
0xA5,
"active playback: wave_pos must not rotate wave RAM reads; offset 5 = wave_ram[1][5]"
);
// Verify the same holds for an odd wave_pos value.
ch3.wave_pos = 7;
assert_eq!(
ch3.read_wave_ram(0),
0xA0,
"active, wave_pos=7: offset 0 must still return wave_ram[1][0] (no nibble rotation)"
);
}
}