all repos — mgba @ 8ac6f83bc58e9d846ca6c8d546c7eb2f6665fc1a

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