all repos — mgba @ 9d4ffb3e4337bcdb042666fa169662a6bc3ec4e1

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