all repos — mgba @ 5b50c43857a5aa5bcefc7b339648bfc73d74fc2f

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