all repos — mgba @ 6b1cbbd5e2f08c52a5f22ac6a71c3b2caba523d1

mGBA Game Boy Advance Emulator

src/gb/audio.c (view raw)

  1/* Copyright (c) 2013-2016 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "audio.h"
  7
  8#include "core/interface.h"
  9#include "core/sync.h"
 10#include "gb/gb.h"
 11#include "gb/serialize.h"
 12#include "gb/io.h"
 13
 14#ifdef _3DS
 15#define blip_add_delta blip_add_delta_fast
 16#endif
 17
 18#define FRAME_CYCLES (DMG_LR35902_FREQUENCY >> 9)
 19
 20const uint32_t DMG_LR35902_FREQUENCY = 0x400000;
 21static const int CLOCKS_PER_BLIP_FRAME = 0x1000;
 22static const unsigned BLIP_BUFFER_SIZE = 0x4000;
 23const int GB_AUDIO_VOLUME_MAX = 0x100;
 24
 25static void _writeDuty(struct GBAudioEnvelope* envelope, uint8_t value);
 26static bool _writeSweep(struct GBAudioEnvelope* envelope, uint8_t value);
 27static int32_t _updateSquareChannel(struct GBAudioSquareControl* envelope, int duty);
 28static void _updateEnvelope(struct GBAudioEnvelope* envelope);
 29static bool _updateSweep(struct GBAudioChannel1* ch, bool initial);
 30static int32_t _updateChannel1(struct GBAudioChannel1* ch);
 31static int32_t _updateChannel2(struct GBAudioChannel2* ch);
 32static int32_t _updateChannel3(struct GBAudioChannel3* ch, enum GBAudioStyle style);
 33static int32_t _updateChannel4(struct GBAudioChannel4* ch);
 34static void _sample(struct GBAudio* audio, int32_t cycles);
 35static void _scheduleEvent(struct GBAudio* audio);
 36
 37void GBAudioInit(struct GBAudio* audio, size_t samples, uint8_t* nr52, enum GBAudioStyle style) {
 38	audio->samples = samples;
 39	audio->left = blip_new(BLIP_BUFFER_SIZE);
 40	audio->right = blip_new(BLIP_BUFFER_SIZE);
 41	audio->clockRate = DMG_LR35902_FREQUENCY;
 42	// Guess too large; we hang producing extra samples if we guess too low
 43	blip_set_rates(audio->left, DMG_LR35902_FREQUENCY, 96000);
 44	blip_set_rates(audio->right, DMG_LR35902_FREQUENCY, 96000);
 45	audio->forceDisableCh[0] = false;
 46	audio->forceDisableCh[1] = false;
 47	audio->forceDisableCh[2] = false;
 48	audio->forceDisableCh[3] = false;
 49	audio->masterVolume = GB_AUDIO_VOLUME_MAX;
 50	audio->nr52 = nr52;
 51	audio->style = style;
 52}
 53
 54void GBAudioDeinit(struct GBAudio* audio) {
 55	blip_delete(audio->left);
 56	blip_delete(audio->right);
 57}
 58
 59void GBAudioReset(struct GBAudio* audio) {
 60	audio->nextEvent = 0;
 61	audio->nextCh1 = 0;
 62	audio->nextCh2 = 0;
 63	audio->nextCh3 = 0;
 64	audio->fadeCh3 = 0;
 65	audio->nextCh4 = 0;
 66	audio->ch1 = (struct GBAudioChannel1) { .envelope = { .dead = 2 } };
 67	audio->ch2 = (struct GBAudioChannel2) { .envelope = { .dead = 2 } };
 68	audio->ch3 = (struct GBAudioChannel3) { .bank = 0 };
 69	audio->ch4 = (struct GBAudioChannel4) { .envelope = { .dead = 2 } };
 70	audio->eventDiff = 0;
 71	audio->nextFrame = 0;
 72	audio->frame = 0;
 73	audio->nextSample = 0;
 74	audio->sampleInterval = 128;
 75	audio->lastLeft = 0;
 76	audio->lastRight = 0;
 77	audio->clock = 0;
 78	audio->volumeRight = 0;
 79	audio->volumeLeft = 0;
 80	audio->ch1Right = false;
 81	audio->ch2Right = false;
 82	audio->ch3Right = false;
 83	audio->ch4Right = false;
 84	audio->ch1Left = false;
 85	audio->ch2Left = false;
 86	audio->ch3Left = false;
 87	audio->ch4Left = false;
 88	audio->playingCh1 = false;
 89	audio->playingCh2 = false;
 90	audio->playingCh3 = false;
 91	audio->playingCh4 = false;
 92}
 93
 94void GBAudioResizeBuffer(struct GBAudio* audio, size_t samples) {
 95	mCoreSyncLockAudio(audio->p->sync);
 96	audio->samples = samples;
 97	blip_clear(audio->left);
 98	blip_clear(audio->right);
 99	audio->clock = 0;
100	mCoreSyncConsumeAudio(audio->p->sync);
101}
102
103void GBAudioWriteNR10(struct GBAudio* audio, uint8_t value) {
104	audio->ch1.shift = GBAudioRegisterSquareSweepGetShift(value);
105	bool oldDirection = audio->ch1.direction;
106	audio->ch1.direction = GBAudioRegisterSquareSweepGetDirection(value);
107	if (audio->ch1.sweepOccurred && oldDirection && !audio->ch1.direction) {
108		audio->playingCh1 = false;
109		*audio->nr52 &= ~0x0001;
110	}
111	audio->ch1.sweepOccurred = false;
112	audio->ch1.time = GBAudioRegisterSquareSweepGetTime(value);
113	if (!audio->ch1.time) {
114		audio->ch1.time = 8;
115	}
116}
117
118void GBAudioWriteNR11(struct GBAudio* audio, uint8_t value) {
119	_writeDuty(&audio->ch1.envelope, value);
120	audio->ch1.control.length = 64 - audio->ch1.envelope.length;
121}
122
123void GBAudioWriteNR12(struct GBAudio* audio, uint8_t value) {
124	if (!_writeSweep(&audio->ch1.envelope, value)) {
125		audio->playingCh1 = false;
126		*audio->nr52 &= ~0x0001;
127	}
128}
129
130void GBAudioWriteNR13(struct GBAudio* audio, uint8_t value) {
131	audio->ch1.control.frequency &= 0x700;
132	audio->ch1.control.frequency |= GBAudioRegisterControlGetFrequency(value);
133}
134
135void GBAudioWriteNR14(struct GBAudio* audio, uint8_t value) {
136	audio->ch1.control.frequency &= 0xFF;
137	audio->ch1.control.frequency |= GBAudioRegisterControlGetFrequency(value << 8);
138	bool wasStop = audio->ch1.control.stop;
139	audio->ch1.control.stop = GBAudioRegisterControlGetStop(value << 8);
140	if (!wasStop && audio->ch1.control.stop && audio->ch1.control.length && !(audio->frame & 1)) {
141		--audio->ch1.control.length;
142		if (audio->ch1.control.length == 0) {
143			audio->playingCh1 = false;
144		}
145	}
146	if (GBAudioRegisterControlIsRestart(value << 8)) {
147		if (audio->nextEvent == INT_MAX) {
148			audio->eventDiff = 0;
149		}
150		if (audio->playingCh1) {
151			audio->ch1.control.hi = !audio->ch1.control.hi;
152		}
153		audio->nextCh1 = audio->eventDiff;
154		audio->playingCh1 = audio->ch1.envelope.initialVolume || audio->ch1.envelope.direction;
155		audio->ch1.envelope.currentVolume = audio->ch1.envelope.initialVolume;
156		if (audio->ch1.envelope.currentVolume > 0) {
157			audio->ch1.envelope.dead = audio->ch1.envelope.stepTime ? 0 : 1;
158		} else {
159			audio->ch1.envelope.dead = audio->ch1.envelope.stepTime ? 0 : 2;
160		}
161		audio->ch1.realFrequency = audio->ch1.control.frequency;
162		audio->ch1.sweepStep = audio->ch1.time;
163		audio->ch1.sweepEnable = (audio->ch1.sweepStep != 8) || audio->ch1.shift;
164		audio->ch1.sweepOccurred = false;
165		if (audio->playingCh1 && audio->ch1.shift) {
166			audio->playingCh1 = _updateSweep(&audio->ch1, true);
167		}
168		if (!audio->ch1.control.length) {
169			audio->ch1.control.length = 64;
170			if (audio->ch1.control.stop && !(audio->frame & 1)) {
171				--audio->ch1.control.length;
172			}
173		}
174		_scheduleEvent(audio);
175	}
176	*audio->nr52 &= ~0x0001;
177	*audio->nr52 |= audio->playingCh1;
178}
179
180void GBAudioWriteNR21(struct GBAudio* audio, uint8_t value) {
181	_writeDuty(&audio->ch2.envelope, value);
182	audio->ch2.control.length = 64 - audio->ch2.envelope.length;
183}
184
185void GBAudioWriteNR22(struct GBAudio* audio, uint8_t value) {
186	if (!_writeSweep(&audio->ch2.envelope, value)) {
187		audio->playingCh2 = false;
188		*audio->nr52 &= ~0x0002;
189	}
190}
191
192void GBAudioWriteNR23(struct GBAudio* audio, uint8_t value) {
193	audio->ch2.control.frequency &= 0x700;
194	audio->ch2.control.frequency |= GBAudioRegisterControlGetFrequency(value);
195}
196
197void GBAudioWriteNR24(struct GBAudio* audio, uint8_t value) {
198	audio->ch2.control.frequency &= 0xFF;
199	audio->ch2.control.frequency |= GBAudioRegisterControlGetFrequency(value << 8);
200	bool wasStop = audio->ch2.control.stop;
201	audio->ch2.control.stop = GBAudioRegisterControlGetStop(value << 8);
202	if (!wasStop && audio->ch2.control.stop && audio->ch2.control.length && !(audio->frame & 1)) {
203		--audio->ch2.control.length;
204		if (audio->ch2.control.length == 0) {
205			audio->playingCh2 = false;
206		}
207	}
208	if (GBAudioRegisterControlIsRestart(value << 8)) {
209		audio->playingCh2 = audio->ch2.envelope.initialVolume || audio->ch2.envelope.direction;
210		audio->ch2.envelope.currentVolume = audio->ch2.envelope.initialVolume;
211		if (audio->ch2.envelope.currentVolume > 0) {
212			audio->ch2.envelope.dead = audio->ch2.envelope.stepTime ? 0 : 1;
213		} else {
214			audio->ch2.envelope.dead = audio->ch2.envelope.stepTime ? 0 : 2;
215		}
216		if (audio->nextEvent == INT_MAX) {
217			audio->eventDiff = 0;
218		}
219		if (audio->playingCh2) {
220			audio->ch2.control.hi = !audio->ch2.control.hi;
221		}
222		audio->nextCh2 = audio->eventDiff;
223		if (!audio->ch2.control.length) {
224			audio->ch2.control.length = 64;
225			if (audio->ch2.control.stop && !(audio->frame & 1)) {
226				--audio->ch2.control.length;
227			}
228		}
229		_scheduleEvent(audio);
230	}
231	*audio->nr52 &= ~0x0002;
232	*audio->nr52 |= audio->playingCh2 << 1;
233}
234
235void GBAudioWriteNR30(struct GBAudio* audio, uint8_t value) {
236	audio->ch3.enable = GBAudioRegisterBankGetEnable(value);
237	if (!audio->ch3.enable) {
238		audio->playingCh3 = false;
239		*audio->nr52 &= ~0x0004;
240	}
241}
242
243void GBAudioWriteNR31(struct GBAudio* audio, uint8_t value) {
244	audio->ch3.length = 256 - value;
245}
246
247void GBAudioWriteNR32(struct GBAudio* audio, uint8_t value) {
248	audio->ch3.volume = GBAudioRegisterBankVolumeGetVolumeGB(value);
249}
250
251void GBAudioWriteNR33(struct GBAudio* audio, uint8_t value) {
252	audio->ch3.rate &= 0x700;
253	audio->ch3.rate |= GBAudioRegisterControlGetRate(value);
254}
255
256void GBAudioWriteNR34(struct GBAudio* audio, uint8_t value) {
257	audio->ch3.rate &= 0xFF;
258	audio->ch3.rate |= GBAudioRegisterControlGetRate(value << 8);
259	bool wasStop = audio->ch3.stop;
260	audio->ch3.stop = GBAudioRegisterControlGetStop(value << 8);
261	if (!wasStop && audio->ch3.stop && audio->ch3.length && !(audio->frame & 1)) {
262		--audio->ch3.length;
263		if (audio->ch3.length == 0) {
264			audio->playingCh3 = false;
265		}
266	}
267	bool wasEnable = audio->playingCh3;
268	if (GBAudioRegisterControlIsRestart(value << 8)) {
269		audio->playingCh3 = audio->ch3.enable;
270		if (!audio->ch3.length) {
271			audio->ch3.length = 256;
272			if (audio->ch3.stop && !(audio->frame & 1)) {
273				--audio->ch3.length;
274			}
275		}
276
277		if (audio->style == GB_AUDIO_DMG && wasEnable && audio->playingCh3 && audio->ch3.readable) {
278			if (audio->ch3.window < 8) {
279				audio->ch3.wavedata8[0] = audio->ch3.wavedata8[audio->ch3.window >> 1];
280			} else {
281				audio->ch3.wavedata8[0] = audio->ch3.wavedata8[((audio->ch3.window >> 1) & ~3)];
282				audio->ch3.wavedata8[1] = audio->ch3.wavedata8[((audio->ch3.window >> 1) & ~3) + 1];
283				audio->ch3.wavedata8[2] = audio->ch3.wavedata8[((audio->ch3.window >> 1) & ~3) + 2];
284				audio->ch3.wavedata8[3] = audio->ch3.wavedata8[((audio->ch3.window >> 1) & ~3) + 3];
285			}
286		}
287		audio->ch3.window = 0;
288	}
289	if (audio->playingCh3) {
290		if (audio->nextEvent == INT_MAX) {
291			audio->eventDiff = 0;
292		}
293		audio->ch3.readable = audio->style != GB_AUDIO_DMG;
294		_scheduleEvent(audio);
295		// TODO: Where does this cycle delay come from?
296		audio->nextCh3 = audio->eventDiff + audio->nextEvent + 4 + 2 * (2048 - audio->ch3.rate);
297	}
298	*audio->nr52 &= ~0x0004;
299	*audio->nr52 |= audio->playingCh3 << 2;
300}
301
302void GBAudioWriteNR41(struct GBAudio* audio, uint8_t value) {
303	_writeDuty(&audio->ch4.envelope, value);
304	audio->ch4.length = 64 - audio->ch4.envelope.length;
305}
306
307void GBAudioWriteNR42(struct GBAudio* audio, uint8_t value) {
308	if (!_writeSweep(&audio->ch4.envelope, value)) {
309		audio->playingCh4 = false;
310		*audio->nr52 &= ~0x0008;
311	}
312}
313
314void GBAudioWriteNR43(struct GBAudio* audio, uint8_t value) {
315	audio->ch4.ratio = GBAudioRegisterNoiseFeedbackGetRatio(value);
316	audio->ch4.frequency = GBAudioRegisterNoiseFeedbackGetFrequency(value);
317	audio->ch4.power = GBAudioRegisterNoiseFeedbackGetPower(value);
318}
319
320void GBAudioWriteNR44(struct GBAudio* audio, uint8_t value) {
321	bool wasStop = audio->ch4.stop;
322	audio->ch4.stop = GBAudioRegisterNoiseControlGetStop(value);
323	if (!wasStop && audio->ch4.stop && audio->ch4.length && !(audio->frame & 1)) {
324		--audio->ch4.length;
325		if (audio->ch4.length == 0) {
326			audio->playingCh4 = false;
327		}
328	}
329	if (GBAudioRegisterNoiseControlIsRestart(value)) {
330		audio->playingCh4 = audio->ch4.envelope.initialVolume || audio->ch4.envelope.direction;
331		audio->ch4.envelope.currentVolume = audio->ch4.envelope.initialVolume;
332		if (audio->ch4.envelope.currentVolume > 0) {
333			audio->ch4.envelope.dead = audio->ch4.envelope.stepTime ? 0 : 1;
334		} else {
335			audio->ch4.envelope.dead = audio->ch4.envelope.stepTime ? 0 : 2;
336		}
337		if (audio->ch4.power) {
338			audio->ch4.lfsr = 0x40;
339		} else {
340			audio->ch4.lfsr = 0x4000;
341		}
342		if (audio->nextEvent == INT_MAX) {
343			audio->eventDiff = 0;
344		}
345		audio->nextCh4 = audio->eventDiff;
346		if (!audio->ch4.length) {
347			audio->ch4.length = 64;
348			if (audio->ch4.stop && !(audio->frame & 1)) {
349				--audio->ch4.length;
350			}
351		}
352		_scheduleEvent(audio);
353	}
354	*audio->nr52 &= ~0x0008;
355	*audio->nr52 |= audio->playingCh4 << 3;
356}
357
358void GBAudioWriteNR50(struct GBAudio* audio, uint8_t value) {
359	audio->volumeRight = GBRegisterNR50GetVolumeRight(value);
360	audio->volumeLeft = GBRegisterNR50GetVolumeLeft(value);
361}
362
363void GBAudioWriteNR51(struct GBAudio* audio, uint8_t value) {
364	audio->ch1Right = GBRegisterNR51GetCh1Right(value);
365	audio->ch2Right = GBRegisterNR51GetCh2Right(value);
366	audio->ch3Right = GBRegisterNR51GetCh3Right(value);
367	audio->ch4Right = GBRegisterNR51GetCh4Right(value);
368	audio->ch1Left = GBRegisterNR51GetCh1Left(value);
369	audio->ch2Left = GBRegisterNR51GetCh2Left(value);
370	audio->ch3Left = GBRegisterNR51GetCh3Left(value);
371	audio->ch4Left = GBRegisterNR51GetCh4Left(value);
372}
373
374void GBAudioWriteNR52(struct GBAudio* audio, uint8_t value) {
375	bool wasEnable = audio->enable;
376	audio->enable = GBAudioEnableGetEnable(value);
377	if (!audio->enable) {
378		audio->playingCh1 = 0;
379		audio->playingCh2 = 0;
380		audio->playingCh3 = 0;
381		audio->playingCh4 = 0;
382		GBAudioWriteNR10(audio, 0);
383		GBAudioWriteNR12(audio, 0);
384		GBAudioWriteNR13(audio, 0);
385		GBAudioWriteNR14(audio, 0);
386		GBAudioWriteNR22(audio, 0);
387		GBAudioWriteNR23(audio, 0);
388		GBAudioWriteNR24(audio, 0);
389		GBAudioWriteNR30(audio, 0);
390		GBAudioWriteNR32(audio, 0);
391		GBAudioWriteNR33(audio, 0);
392		GBAudioWriteNR34(audio, 0);
393		GBAudioWriteNR42(audio, 0);
394		GBAudioWriteNR43(audio, 0);
395		GBAudioWriteNR44(audio, 0);
396		GBAudioWriteNR50(audio, 0);
397		GBAudioWriteNR51(audio, 0);
398		if (audio->style != GB_AUDIO_DMG) {
399			GBAudioWriteNR11(audio, 0);
400			GBAudioWriteNR21(audio, 0);
401			GBAudioWriteNR31(audio, 0);
402			GBAudioWriteNR41(audio, 0);
403		}
404
405		if (audio->p) {
406			audio->p->memory.io[REG_NR10] = 0;
407			audio->p->memory.io[REG_NR11] = 0;
408			audio->p->memory.io[REG_NR12] = 0;
409			audio->p->memory.io[REG_NR13] = 0;
410			audio->p->memory.io[REG_NR14] = 0;
411			audio->p->memory.io[REG_NR21] = 0;
412			audio->p->memory.io[REG_NR22] = 0;
413			audio->p->memory.io[REG_NR23] = 0;
414			audio->p->memory.io[REG_NR24] = 0;
415			audio->p->memory.io[REG_NR30] = 0;
416			audio->p->memory.io[REG_NR31] = 0;
417			audio->p->memory.io[REG_NR32] = 0;
418			audio->p->memory.io[REG_NR33] = 0;
419			audio->p->memory.io[REG_NR34] = 0;
420			audio->p->memory.io[REG_NR42] = 0;
421			audio->p->memory.io[REG_NR43] = 0;
422			audio->p->memory.io[REG_NR44] = 0;
423			audio->p->memory.io[REG_NR50] = 0;
424			audio->p->memory.io[REG_NR51] = 0;
425			if (audio->style != GB_AUDIO_DMG) {
426				audio->p->memory.io[REG_NR11] = 0;
427				audio->p->memory.io[REG_NR21] = 0;
428				audio->p->memory.io[REG_NR31] = 0;
429				audio->p->memory.io[REG_NR41] = 0;
430			}
431		}
432		*audio->nr52 &= ~0x000F;
433	} else if (!wasEnable) {
434		audio->frame = 7;
435	}
436}
437
438int32_t GBAudioProcessEvents(struct GBAudio* audio, int32_t cycles) {
439	if (audio->nextEvent == INT_MAX) {
440		return INT_MAX;
441	}
442	audio->nextEvent -= cycles;
443	audio->eventDiff += cycles;
444	while (audio->nextEvent <= 0) {
445		audio->nextEvent = INT_MAX;
446		if (audio->enable) {
447			audio->nextFrame -= audio->eventDiff;
448			int frame = -1;
449			if (audio->nextFrame <= 0) {
450				frame = (audio->frame + 1) & 7;
451				audio->frame = frame;
452				audio->nextFrame += FRAME_CYCLES;
453				if (audio->nextFrame < audio->nextEvent) {
454					audio->nextEvent = audio->nextFrame;
455				}
456			}
457
458			if (audio->playingCh1) {
459				audio->nextCh1 -= audio->eventDiff;
460				if (!audio->ch1.envelope.dead && frame == 7) {
461					--audio->ch1.envelope.nextStep;
462					if (audio->ch1.envelope.nextStep == 0) {
463						int8_t sample = audio->ch1.control.hi * 0x10 - 0x8;
464						_updateEnvelope(&audio->ch1.envelope);
465						audio->ch1.sample = sample * audio->ch1.envelope.currentVolume;
466					}
467				}
468
469				if (audio->ch1.sweepEnable && (frame & 3) == 2) {
470					--audio->ch1.sweepStep;
471					if (audio->ch1.sweepStep == 0) {
472						audio->playingCh1 = _updateSweep(&audio->ch1, false);
473					}
474				}
475
476				if (audio->ch1.envelope.dead != 2) {
477					if (audio->nextCh1 <= 0) {
478						audio->nextCh1 += _updateChannel1(&audio->ch1);
479					}
480					if (audio->nextCh1 < audio->nextEvent) {
481						audio->nextEvent = audio->nextCh1;
482					}
483				}
484			}
485
486			if (audio->ch1.control.length && audio->ch1.control.stop && !(frame & 1)) {
487				--audio->ch1.control.length;
488				if (audio->ch1.control.length == 0) {
489					audio->playingCh1 = 0;
490				}
491			}
492
493			if (audio->playingCh2) {
494				audio->nextCh2 -= audio->eventDiff;
495				if (!audio->ch2.envelope.dead && frame == 7) {
496					--audio->ch2.envelope.nextStep;
497					if (audio->ch2.envelope.nextStep == 0) {
498						int8_t sample = audio->ch2.control.hi * 0x10 - 0x8;
499						_updateEnvelope(&audio->ch2.envelope);
500						audio->ch2.sample = sample * audio->ch2.envelope.currentVolume;
501					}
502				}
503
504				if (audio->ch2.envelope.dead != 2) {
505					if (audio->nextCh2 <= 0) {
506						audio->nextCh2 += _updateChannel2(&audio->ch2);
507					}
508					if (audio->nextCh2 < audio->nextEvent) {
509						audio->nextEvent = audio->nextCh2;
510					}
511				}
512			}
513
514			if (audio->ch2.control.length && audio->ch2.control.stop && !(frame & 1)) {
515				--audio->ch2.control.length;
516				if (audio->ch2.control.length == 0) {
517					audio->playingCh2 = 0;
518				}
519			}
520
521			if (audio->playingCh3) {
522				audio->nextCh3 -= audio->eventDiff;
523				audio->fadeCh3 -= audio->eventDiff;
524				if (audio->fadeCh3 <= 0) {
525					audio->ch3.readable = false;
526					audio->fadeCh3 = INT_MAX;
527				}
528				if (audio->nextCh3 <= 0) {
529					if (audio->style == GB_AUDIO_DMG) {
530						audio->fadeCh3 = audio->nextCh3 + 2;
531					}
532					audio->nextCh3 += _updateChannel3(&audio->ch3, audio->style);
533					audio->ch3.readable = true;
534				}
535				if (audio->fadeCh3 < audio->nextEvent) {
536					audio->nextEvent = audio->fadeCh3;
537				}
538				if (audio->nextCh3 < audio->nextEvent) {
539					audio->nextEvent = audio->nextCh3;
540				}
541			}
542
543			if (audio->ch3.length && audio->ch3.stop && !(frame & 1)) {
544				--audio->ch3.length;
545				if (audio->ch3.length == 0) {
546					audio->playingCh3 = 0;
547				}
548			}
549
550			if (audio->playingCh4) {
551				audio->nextCh4 -= audio->eventDiff;
552				if (!audio->ch4.envelope.dead && frame == 7) {
553					--audio->ch4.envelope.nextStep;
554					if (audio->ch4.envelope.nextStep == 0) {
555						int8_t sample = (audio->ch4.sample >> 31) * 0x8;
556						_updateEnvelope(&audio->ch4.envelope);
557						audio->ch4.sample = sample * audio->ch4.envelope.currentVolume;
558					}
559				}
560			}
561
562			if (audio->ch4.length && audio->ch4.stop && !(frame & 1)) {
563				--audio->ch4.length;
564				if (audio->ch4.length == 0) {
565					audio->playingCh4 = 0;
566				}
567			}
568		}
569
570		*audio->nr52 &= ~0x000F;
571		*audio->nr52 |= audio->playingCh1;
572		*audio->nr52 |= audio->playingCh2 << 1;
573		*audio->nr52 |= audio->playingCh3 << 2;
574		*audio->nr52 |= audio->playingCh4 << 3;
575
576		if (audio->p) {
577			audio->nextSample -= audio->eventDiff;
578			if (audio->nextSample <= 0) {
579				_sample(audio, audio->sampleInterval);
580				audio->nextSample += audio->sampleInterval;
581			}
582
583			if (audio->nextSample < audio->nextEvent) {
584				audio->nextEvent = audio->nextSample;
585			}
586		}
587		audio->eventDiff = 0;
588	}
589	return audio->nextEvent;
590}
591
592void GBAudioSamplePSG(struct GBAudio* audio, int16_t* left, int16_t* right) {
593	int sampleLeft = 0;
594	int sampleRight = 0;
595
596	if (audio->ch4.envelope.dead != 2) {
597		while (audio->nextCh4 <= 0) {
598			audio->nextCh4 += _updateChannel4(&audio->ch4);
599		}
600		if (audio->nextCh4 < audio->nextEvent) {
601			audio->nextEvent = audio->nextCh4;
602		}
603	}
604
605	if (audio->playingCh1 && !audio->forceDisableCh[0]) {
606		if (audio->ch1Left) {
607			sampleLeft += audio->ch1.sample;
608		}
609
610		if (audio->ch1Right) {
611			sampleRight += audio->ch1.sample;
612		}
613	}
614
615	if (audio->playingCh2 && !audio->forceDisableCh[1]) {
616		if (audio->ch2Left) {
617			sampleLeft += audio->ch2.sample;
618		}
619
620		if (audio->ch2Right) {
621			sampleRight += audio->ch2.sample;
622		}
623	}
624
625	if (audio->playingCh3 && !audio->forceDisableCh[2]) {
626		if (audio->ch3Left) {
627			sampleLeft += audio->ch3.sample;
628		}
629
630		if (audio->ch3Right) {
631			sampleRight += audio->ch3.sample;
632		}
633	}
634
635	if (audio->playingCh4 && !audio->forceDisableCh[3]) {
636		if (audio->ch4Left) {
637			sampleLeft += audio->ch4.sample;
638		}
639
640		if (audio->ch4Right) {
641			sampleRight += audio->ch4.sample;
642		}
643	}
644
645	*left = sampleLeft * (1 + audio->volumeLeft);
646	*right = sampleRight * (1 + audio->volumeRight);
647}
648
649void _sample(struct GBAudio* audio, int32_t cycles) {
650	int16_t sampleLeft = 0;
651	int16_t sampleRight = 0;
652	GBAudioSamplePSG(audio, &sampleLeft, &sampleRight);
653	sampleLeft = (sampleLeft * audio->masterVolume) >> 6;
654	sampleRight = (sampleRight * audio->masterVolume) >> 6;
655
656	mCoreSyncLockAudio(audio->p->sync);
657	unsigned produced;
658	if ((size_t) blip_samples_avail(audio->left) < audio->samples) {
659		blip_add_delta(audio->left, audio->clock, sampleLeft - audio->lastLeft);
660		blip_add_delta(audio->right, audio->clock, sampleRight - audio->lastRight);
661		audio->lastLeft = sampleLeft;
662		audio->lastRight = sampleRight;
663		audio->clock += cycles;
664		if (audio->clock >= CLOCKS_PER_BLIP_FRAME) {
665			blip_end_frame(audio->left, audio->clock);
666			blip_end_frame(audio->right, audio->clock);
667			audio->clock -= CLOCKS_PER_BLIP_FRAME;
668		}
669	}
670	produced = blip_samples_avail(audio->left);
671	if (audio->p->stream && audio->p->stream->postAudioFrame) {
672		audio->p->stream->postAudioFrame(audio->p->stream, sampleLeft, sampleRight);
673	}
674	bool wait = produced >= audio->samples;
675	mCoreSyncProduceAudio(audio->p->sync, wait);
676
677	if (wait && audio->p->stream && audio->p->stream->postAudioBuffer) {
678		audio->p->stream->postAudioBuffer(audio->p->stream, audio->left, audio->right);
679	}
680}
681
682void _writeDuty(struct GBAudioEnvelope* envelope, uint8_t value) {
683	envelope->length = GBAudioRegisterDutyGetLength(value);
684	envelope->duty = GBAudioRegisterDutyGetDuty(value);
685}
686
687bool _writeSweep(struct GBAudioEnvelope* envelope, uint8_t value) {
688	envelope->stepTime = GBAudioRegisterSweepGetStepTime(value);
689	envelope->direction = GBAudioRegisterSweepGetDirection(value);
690	envelope->initialVolume = GBAudioRegisterSweepGetInitialVolume(value);
691	if (envelope->stepTime == 0) {
692		envelope->dead = envelope->currentVolume ? 1 : 2;
693	} else if (!envelope->direction && !envelope->currentVolume) {
694		envelope->dead = 2;
695	} else if (envelope->direction && envelope->currentVolume == 0xF) {
696		envelope->dead = 1;
697	} else {
698		envelope->dead = 0;
699	}
700	envelope->nextStep = envelope->stepTime;
701	return envelope->initialVolume || envelope->direction;
702}
703
704static int32_t _updateSquareChannel(struct GBAudioSquareControl* control, int duty) {
705	control->hi = !control->hi;
706	int period = 4 * (2048 - control->frequency);
707	switch (duty) {
708	case 0:
709		return control->hi ? period : period * 7;
710	case 1:
711		return control->hi ? period * 2 : period * 6;
712	case 2:
713		return period * 4;
714	case 3:
715		return control->hi ? period * 6 : period * 2;
716	default:
717		// This should never be hit
718		return period * 4;
719	}
720}
721
722static void _updateEnvelope(struct GBAudioEnvelope* envelope) {
723	if (envelope->direction) {
724		++envelope->currentVolume;
725	} else {
726		--envelope->currentVolume;
727	}
728	if (envelope->currentVolume >= 15) {
729		envelope->currentVolume = 15;
730		envelope->dead = 1;
731	} else if (envelope->currentVolume <= 0) {
732		envelope->currentVolume = 0;
733		envelope->dead = 2;
734	} else {
735		envelope->nextStep = envelope->stepTime;
736	}
737}
738
739static bool _updateSweep(struct GBAudioChannel1* ch, bool initial) {
740	if (initial || ch->time != 8) {
741		int frequency = ch->realFrequency;
742		if (ch->direction) {
743			frequency -= frequency >> ch->shift;
744			if (!initial && frequency >= 0) {
745				ch->control.frequency = frequency;
746				ch->realFrequency = frequency;
747			}
748		} else {
749			frequency += frequency >> ch->shift;
750			if (frequency < 2048) {
751				if (!initial && ch->shift) {
752					ch->control.frequency = frequency;
753					ch->realFrequency = frequency;
754					if (!_updateSweep(ch, true)) {
755						return false;
756					}
757				}
758			} else {
759				return false;
760			}
761		}
762		ch->sweepOccurred = true;
763	}
764	ch->sweepStep = ch->time;
765	return true;
766}
767
768static int32_t _updateChannel1(struct GBAudioChannel1* ch) {
769	int timing = _updateSquareChannel(&ch->control, ch->envelope.duty);
770	ch->sample = ch->control.hi * 0x10 - 0x8;
771	ch->sample *= ch->envelope.currentVolume;
772	return timing;
773}
774
775static int32_t _updateChannel2(struct GBAudioChannel2* ch) {
776	int timing = _updateSquareChannel(&ch->control, ch->envelope.duty);
777	ch->sample = ch->control.hi * 0x10 - 0x8;
778	ch->sample *= ch->envelope.currentVolume;
779	return timing;
780}
781
782static int32_t _updateChannel3(struct GBAudioChannel3* ch, enum GBAudioStyle style) {
783	int i;
784	int volume;
785	switch (ch->volume) {
786	case 0:
787		volume = 0;
788		break;
789	case 1:
790		volume = 4;
791		break;
792	case 2:
793		volume = 2;
794		break;
795	case 3:
796		volume = 1;
797		break;
798	default:
799		volume = 3;
800		break;
801	}
802	switch (style) {
803		int start;
804		int end;
805	case GB_AUDIO_DMG:
806	default:
807		++ch->window;
808		ch->window &= 0x1F;
809		ch->sample = ch->wavedata8[ch->window >> 1];
810		if (!(ch->window & 1)) {
811			ch->sample >>= 4;
812		}
813		ch->sample &= 0xF;
814		break;
815	case GB_AUDIO_GBA:
816		if (ch->size) {
817			start = 7;
818			end = 0;
819		} else if (ch->bank) {
820			start = 7;
821			end = 4;
822		} else {
823			start = 3;
824			end = 0;
825		}
826		uint32_t bitsCarry = ch->wavedata32[end] & 0x000000F0;
827		uint32_t bits;
828		for (i = start; i >= end; --i) {
829			bits = ch->wavedata32[i] & 0x000000F0;
830			ch->wavedata32[i] = ((ch->wavedata32[i] & 0x0F0F0F0F) << 4) | ((ch->wavedata32[i] & 0xF0F0F000) >> 12);
831			ch->wavedata32[i] |= bitsCarry << 20;
832			bitsCarry = bits;
833		}
834		ch->sample = bitsCarry >> 4;
835		break;
836	}
837	ch->sample -= 8;
838	ch->sample *= volume * 4;
839	return 2 * (2048 - ch->rate);
840}
841
842static int32_t _updateChannel4(struct GBAudioChannel4* ch) {
843	int lsb = ch->lfsr & 1;
844	ch->sample = lsb * 0x10 - 0x8;
845	ch->sample *= ch->envelope.currentVolume;
846	ch->lfsr >>= 1;
847	ch->lfsr ^= (lsb * 0x60) << (ch->power ? 0 : 8);
848	int timing = ch->ratio ? 2 * ch->ratio : 1;
849	timing <<= ch->frequency;
850	timing *= 8;
851	return timing;
852}
853
854void _scheduleEvent(struct GBAudio* audio) {
855	// TODO: Don't need p
856	if (audio->p) {
857		audio->nextEvent = audio->p->cpu->cycles >> audio->p->doubleSpeed;
858		audio->p->cpu->nextEvent = audio->nextEvent;
859	} else {
860		audio->nextEvent = 0;
861	}
862}
863
864void GBAudioPSGSerialize(const struct GBAudio* audio, struct GBSerializedPSGState* state, uint32_t* flagsOut) {
865	uint32_t flags = 0;
866	uint32_t ch1Flags = 0;
867	uint32_t ch2Flags = 0;
868	uint32_t ch4Flags = 0;
869
870	flags = GBSerializedAudioFlagsSetFrame(flags, audio->frame);
871
872	flags = GBSerializedAudioFlagsSetCh1Volume(flags, audio->ch1.envelope.currentVolume);
873	flags = GBSerializedAudioFlagsSetCh1Dead(flags, audio->ch1.envelope.dead);
874	flags = GBSerializedAudioFlagsSetCh1Hi(flags, audio->ch1.control.hi);
875	flags = GBSerializedAudioFlagsSetCh1SweepEnabled(flags, audio->ch1.sweepEnable);
876	flags = GBSerializedAudioFlagsSetCh1SweepOccurred(flags, audio->ch1.sweepOccurred);
877	ch1Flags = GBSerializedAudioEnvelopeSetLength(ch1Flags, audio->ch1.control.length);
878	ch1Flags = GBSerializedAudioEnvelopeSetNextStep(ch1Flags, audio->ch1.envelope.nextStep);
879	ch1Flags = GBSerializedAudioEnvelopeSetFrequency(ch1Flags, audio->ch1.realFrequency);
880	STORE_32LE(ch1Flags, 0, &state->ch1.envelope);
881	STORE_32LE(audio->nextFrame, 0, &state->ch1.nextFrame);
882	STORE_32LE(audio->nextCh1, 0, &state->ch1.nextEvent);
883
884	flags = GBSerializedAudioFlagsSetCh2Volume(flags, audio->ch2.envelope.currentVolume);
885	flags = GBSerializedAudioFlagsSetCh2Dead(flags, audio->ch2.envelope.dead);
886	flags = GBSerializedAudioFlagsSetCh2Hi(flags, audio->ch2.control.hi);
887	ch2Flags = GBSerializedAudioEnvelopeSetLength(ch2Flags, audio->ch2.control.length);
888	ch2Flags = GBSerializedAudioEnvelopeSetNextStep(ch2Flags, audio->ch2.envelope.nextStep);
889	STORE_32LE(ch2Flags, 0, &state->ch2.envelope);
890	STORE_32LE(audio->nextCh2, 0, &state->ch2.nextEvent);
891
892	memcpy(state->ch3.wavebanks, audio->ch3.wavedata32, sizeof(state->ch3.wavebanks));
893	STORE_16LE(audio->ch3.length, 0, &state->ch3.length);
894	STORE_32LE(audio->nextCh3, 0, &state->ch3.nextEvent);
895
896	flags = GBSerializedAudioFlagsSetCh4Volume(flags, audio->ch4.envelope.currentVolume);
897	flags = GBSerializedAudioFlagsSetCh4Dead(flags, audio->ch4.envelope.dead);
898	STORE_32LE(audio->ch4.lfsr, 0, &state->ch4.lfsr);
899	ch4Flags = GBSerializedAudioEnvelopeSetLength(ch4Flags, audio->ch4.length);
900	ch4Flags = GBSerializedAudioEnvelopeSetNextStep(ch4Flags, audio->ch4.envelope.nextStep);
901	STORE_32LE(ch4Flags, 0, &state->ch4.envelope);
902	STORE_32LE(audio->nextCh4, 0, &state->ch4.nextEvent);
903
904	STORE_32LE(flags, 0, flagsOut);
905}
906
907void GBAudioPSGDeserialize(struct GBAudio* audio, const struct GBSerializedPSGState* state, const uint32_t* flagsIn) {
908	uint32_t flags;
909	uint32_t ch1Flags = 0;
910	uint32_t ch2Flags = 0;
911	uint32_t ch4Flags = 0;
912
913	LOAD_32LE(flags, 0, flagsIn);
914	LOAD_32LE(ch1Flags, 0, &state->ch1.envelope);
915	audio->ch1.envelope.currentVolume = GBSerializedAudioFlagsGetCh1Volume(flags);
916	audio->ch1.envelope.dead = GBSerializedAudioFlagsGetCh1Dead(flags);
917	audio->ch1.control.hi = GBSerializedAudioFlagsGetCh1Hi(flags);
918	audio->ch1.sweepEnable = GBSerializedAudioFlagsGetCh1SweepEnabled(flags);
919	audio->ch1.sweepOccurred = GBSerializedAudioFlagsGetCh1SweepOccurred(flags);
920	audio->ch1.control.length = GBSerializedAudioEnvelopeGetLength(ch1Flags);
921	audio->ch1.envelope.nextStep = GBSerializedAudioEnvelopeGetNextStep(ch1Flags);
922	audio->ch1.realFrequency = GBSerializedAudioEnvelopeGetFrequency(ch1Flags);
923	LOAD_32LE(audio->nextFrame, 0, &state->ch1.nextFrame);
924	LOAD_32LE(audio->nextCh1, 0, &state->ch1.nextEvent);
925
926	LOAD_32LE(ch2Flags, 0, &state->ch1.envelope);
927	audio->ch2.envelope.currentVolume = GBSerializedAudioFlagsGetCh2Volume(flags);
928	audio->ch2.envelope.dead = GBSerializedAudioFlagsGetCh2Dead(flags);
929	audio->ch2.control.hi = GBSerializedAudioFlagsGetCh2Hi(flags);
930	audio->ch2.control.length = GBSerializedAudioEnvelopeGetLength(ch2Flags);
931	audio->ch2.envelope.nextStep = GBSerializedAudioEnvelopeGetNextStep(ch2Flags);
932	LOAD_32LE(audio->nextCh2, 0, &state->ch2.nextEvent);
933
934	// TODO: Big endian?
935	memcpy(audio->ch3.wavedata32, state->ch3.wavebanks, sizeof(audio->ch3.wavedata32));
936	LOAD_16LE(audio->ch3.length, 0, &state->ch3.length);
937	LOAD_32LE(audio->nextCh3, 0, &state->ch3.nextEvent);
938
939	LOAD_32LE(ch4Flags, 0, &state->ch1.envelope);
940	audio->ch4.envelope.currentVolume = GBSerializedAudioFlagsGetCh4Volume(flags);
941	audio->ch4.envelope.dead = GBSerializedAudioFlagsGetCh4Dead(flags);
942	audio->ch4.length = GBSerializedAudioEnvelopeGetLength(ch4Flags);
943	audio->ch4.envelope.nextStep = GBSerializedAudioEnvelopeGetNextStep(ch4Flags);
944	LOAD_32LE(audio->ch4.lfsr, 0, &state->ch4.lfsr);
945	LOAD_32LE(audio->nextCh4, 0, &state->ch4.nextEvent);
946}
947
948void GBAudioSerialize(const struct GBAudio* audio, struct GBSerializedState* state) {
949	GBAudioPSGSerialize(audio, &state->audio.psg, &state->audio.flags);
950
951	STORE_32LE(audio->nextEvent, 0, &state->audio.nextEvent);
952	STORE_32LE(audio->eventDiff, 0, &state->audio.eventDiff);
953	STORE_32LE(audio->nextSample, 0, &state->audio.nextSample);
954}
955
956void GBAudioDeserialize(struct GBAudio* audio, const struct GBSerializedState* state) {
957	GBAudioPSGDeserialize(audio, &state->audio.psg, &state->audio.flags);
958
959	LOAD_32LE(audio->nextEvent, 0, &state->audio.nextEvent);
960	LOAD_32LE(audio->eventDiff, 0, &state->audio.eventDiff);
961	LOAD_32LE(audio->nextSample, 0, &state->audio.nextSample);
962}
963