all repos — mgba @ ed94288902a67d9dd0fd86211e07cb27000ec826

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