all repos — mgba @ a3a380d9f551bbc5ad726ef07c11d20c0263d1e5

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