all repos — mgba @ 3ead128a2d1868917c2765c3e71571a54a530327

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