all repos — mgba @ bbd0453c9cbd8ea4c82bd4bac99a9da91ba200a1

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		audio->nextCh3 = audio->eventDiff + audio->p->cpu->cycles + 2 + 2 * (2048 - audio->ch3.rate);
285		audio->ch3.readable = false;
286		audio->nextEvent = audio->p->cpu->cycles;
287		if (audio->p) {
288			// TODO: Don't need p
289			audio->p->cpu->nextEvent = audio->nextEvent;
290		}
291	}
292	*audio->nr52 &= ~0x0004;
293	*audio->nr52 |= audio->playingCh3 << 2;
294}
295
296void GBAudioWriteNR41(struct GBAudio* audio, uint8_t value) {
297	_writeDuty(&audio->ch4.envelope, value);
298	audio->ch4.length = 64 - audio->ch4.envelope.length;
299}
300
301void GBAudioWriteNR42(struct GBAudio* audio, uint8_t value) {
302	if (!_writeSweep(&audio->ch4.envelope, value)) {
303		audio->playingCh4 = false;
304		*audio->nr52 &= ~0x0008;
305	}
306}
307
308void GBAudioWriteNR43(struct GBAudio* audio, uint8_t value) {
309	audio->ch4.ratio = GBAudioRegisterNoiseFeedbackGetRatio(value);
310	audio->ch4.frequency = GBAudioRegisterNoiseFeedbackGetFrequency(value);
311	audio->ch4.power = GBAudioRegisterNoiseFeedbackGetPower(value);
312}
313
314void GBAudioWriteNR44(struct GBAudio* audio, uint8_t value) {
315	bool wasStop = audio->ch4.stop;
316	audio->ch4.stop = GBAudioRegisterNoiseControlGetStop(value);
317	if (!wasStop && audio->ch4.stop && audio->ch4.length && !(audio->frame & 1)) {
318		--audio->ch4.length;
319		if (audio->ch4.length == 0) {
320			audio->playingCh4 = false;
321		}
322	}
323	if (GBAudioRegisterNoiseControlIsRestart(value)) {
324		audio->playingCh4 = audio->ch4.envelope.initialVolume || audio->ch4.envelope.direction;
325		audio->ch4.envelope.currentVolume = audio->ch4.envelope.initialVolume;
326		if (audio->ch4.envelope.currentVolume > 0 && audio->ch4.envelope.stepTime) {
327			audio->ch4.envelope.dead = 0;
328		}
329		if (audio->ch4.power) {
330			audio->ch4.lfsr = 0x40;
331		} else {
332			audio->ch4.lfsr = 0x4000;
333		}
334		if (audio->nextEvent == INT_MAX) {
335			audio->eventDiff = 0;
336		}
337		if (!audio->playingCh4) {
338			audio->nextCh4 = audio->eventDiff;
339		}
340		if (!audio->ch4.length) {
341			audio->ch4.length = 64;
342			if (audio->ch4.stop && !(audio->frame & 1)) {
343				--audio->ch4.length;
344			}
345		}
346		audio->nextEvent = audio->p->cpu->cycles;
347		if (audio->p) {
348			// TODO: Don't need p
349			audio->p->cpu->nextEvent = audio->nextEvent;
350		}
351	}
352	*audio->nr52 &= ~0x0008;
353	*audio->nr52 |= audio->playingCh4 << 3;
354}
355
356void GBAudioWriteNR50(struct GBAudio* audio, uint8_t value) {
357	audio->volumeRight = GBRegisterNR50GetVolumeRight(value);
358	audio->volumeLeft = GBRegisterNR50GetVolumeLeft(value);
359}
360
361void GBAudioWriteNR51(struct GBAudio* audio, uint8_t value) {
362	audio->ch1Right = GBRegisterNR51GetCh1Right(value);
363	audio->ch2Right = GBRegisterNR51GetCh2Right(value);
364	audio->ch3Right = GBRegisterNR51GetCh3Right(value);
365	audio->ch4Right = GBRegisterNR51GetCh4Right(value);
366	audio->ch1Left = GBRegisterNR51GetCh1Left(value);
367	audio->ch2Left = GBRegisterNR51GetCh2Left(value);
368	audio->ch3Left = GBRegisterNR51GetCh3Left(value);
369	audio->ch4Left = GBRegisterNR51GetCh4Left(value);
370}
371
372void GBAudioWriteNR52(struct GBAudio* audio, uint8_t value) {
373	bool wasEnable = audio->enable;
374	audio->enable = GBAudioEnableGetEnable(value);
375	if (!audio->enable) {
376		audio->playingCh1 = 0;
377		audio->playingCh2 = 0;
378		audio->playingCh3 = 0;
379		audio->playingCh4 = 0;
380		GBAudioWriteNR10(audio, 0);
381		GBAudioWriteNR11(audio, 0);
382		GBAudioWriteNR12(audio, 0);
383		GBAudioWriteNR13(audio, 0);
384		GBAudioWriteNR14(audio, 0);
385		GBAudioWriteNR21(audio, 0);
386		GBAudioWriteNR22(audio, 0);
387		GBAudioWriteNR23(audio, 0);
388		GBAudioWriteNR24(audio, 0);
389		GBAudioWriteNR30(audio, 0);
390		GBAudioWriteNR31(audio, 0);
391		GBAudioWriteNR32(audio, 0);
392		GBAudioWriteNR33(audio, 0);
393		GBAudioWriteNR34(audio, 0);
394		// Don't write to NR41
395		GBAudioWriteNR42(audio, 0);
396		GBAudioWriteNR43(audio, 0);
397		GBAudioWriteNR44(audio, 0);
398		GBAudioWriteNR50(audio, 0);
399		GBAudioWriteNR51(audio, 0);
400		if (audio->p) {
401			audio->p->memory.io[REG_NR10] = 0;
402			audio->p->memory.io[REG_NR11] = 0;
403			audio->p->memory.io[REG_NR12] = 0;
404			audio->p->memory.io[REG_NR13] = 0;
405			audio->p->memory.io[REG_NR14] = 0;
406			audio->p->memory.io[REG_NR21] = 0;
407			audio->p->memory.io[REG_NR22] = 0;
408			audio->p->memory.io[REG_NR23] = 0;
409			audio->p->memory.io[REG_NR24] = 0;
410			audio->p->memory.io[REG_NR30] = 0;
411			audio->p->memory.io[REG_NR31] = 0;
412			audio->p->memory.io[REG_NR32] = 0;
413			audio->p->memory.io[REG_NR33] = 0;
414			audio->p->memory.io[REG_NR34] = 0;
415			audio->p->memory.io[REG_NR42] = 0;
416			audio->p->memory.io[REG_NR43] = 0;
417			audio->p->memory.io[REG_NR44] = 0;
418			audio->p->memory.io[REG_NR50] = 0;
419			audio->p->memory.io[REG_NR51] = 0;
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					audio->fadeCh3 = audio->nextCh3 + 2;
519					audio->nextCh3 += _updateChannel3(&audio->ch3, audio->style);
520					audio->ch3.readable = true;
521				}
522				if (audio->fadeCh3 < audio->nextEvent) {
523					audio->nextEvent = audio->fadeCh3;
524				}
525				if (audio->nextCh3 < audio->nextEvent) {
526					audio->nextEvent = audio->nextCh3;
527				}
528			}
529
530			if (audio->ch3.length && audio->ch3.stop && !(frame & 1)) {
531				--audio->ch3.length;
532				if (audio->ch3.length == 0) {
533					audio->playingCh3 = 0;
534				}
535			}
536
537			if (audio->playingCh4) {
538				audio->nextCh4 -= audio->eventDiff;
539				if (!audio->ch4.envelope.dead && frame == 7) {
540					--audio->ch4.envelope.nextStep;
541					if (audio->ch4.envelope.nextStep == 0) {
542						int8_t sample = (audio->ch4.sample >> 31) * 0x8;
543						_updateEnvelope(&audio->ch4.envelope);
544						audio->ch4.sample = sample * audio->ch4.envelope.currentVolume;
545					}
546				}
547
548				if (audio->ch4.envelope.dead != 2) {
549					if (audio->nextCh4 <= 0) {
550						int32_t timing = _updateChannel4(&audio->ch4);
551						if (audio->nextCh4 < -timing) {
552							int32_t bound = timing * 16;
553							// Perform negative modulo to cap to 16 iterations
554							audio->nextCh4 = bound - (audio->nextCh4 - 1) % bound - 1;
555						}
556						audio->nextCh4 += timing;
557					}
558					if (audio->nextCh4 < audio->nextEvent) {
559						audio->nextEvent = audio->nextCh4;
560					}
561				}
562			}
563
564			if (audio->ch4.length && audio->ch4.stop && !(frame & 1)) {
565				--audio->ch4.length;
566				if (audio->ch4.length == 0) {
567					audio->playingCh4 = 0;
568				}
569			}
570		}
571
572		*audio->nr52 &= ~0x000F;
573		*audio->nr52 |= audio->playingCh1;
574		*audio->nr52 |= audio->playingCh2 << 1;
575		*audio->nr52 |= audio->playingCh3 << 2;
576		*audio->nr52 |= audio->playingCh4 << 3;
577
578		if (audio->p) {
579			audio->nextSample -= audio->eventDiff;
580			if (audio->nextSample <= 0) {
581				_sample(audio, audio->sampleInterval);
582				audio->nextSample += audio->sampleInterval;
583			}
584
585			if (audio->nextSample < audio->nextEvent) {
586				audio->nextEvent = audio->nextSample;
587			}
588		}
589		audio->eventDiff = 0;
590	}
591	return audio->nextEvent;
592}
593
594void GBAudioSamplePSG(struct GBAudio* audio, int16_t* left, int16_t* right) {
595	int sampleLeft = 0;
596	int sampleRight = 0;
597
598	if (audio->playingCh1 && !audio->forceDisableCh[0]) {
599		if (audio->ch1Left) {
600			sampleLeft += audio->ch1.sample;
601		}
602
603		if (audio->ch1Right) {
604			sampleRight += audio->ch1.sample;
605		}
606	}
607
608	if (audio->playingCh2 && !audio->forceDisableCh[1]) {
609		if (audio->ch2Left) {
610			sampleLeft += audio->ch2.sample;
611		}
612
613		if (audio->ch2Right) {
614			sampleRight += audio->ch2.sample;
615		}
616	}
617
618	if (audio->playingCh3 && !audio->forceDisableCh[2]) {
619		if (audio->ch3Left) {
620			sampleLeft += audio->ch3.sample;
621		}
622
623		if (audio->ch3Right) {
624			sampleRight += audio->ch3.sample;
625		}
626	}
627
628	if (audio->playingCh4 && !audio->forceDisableCh[3]) {
629		if (audio->ch4Left) {
630			sampleLeft += audio->ch4.sample;
631		}
632
633		if (audio->ch4Right) {
634			sampleRight += audio->ch4.sample;
635		}
636	}
637
638	*left = sampleLeft * (1 + audio->volumeLeft);
639	*right = sampleRight * (1 + audio->volumeRight);
640}
641
642void _sample(struct GBAudio* audio, int32_t cycles) {
643	int16_t sampleLeft = 0;
644	int16_t sampleRight = 0;
645	GBAudioSamplePSG(audio, &sampleLeft, &sampleRight);
646	sampleLeft = (sampleLeft * audio->masterVolume) >> 6;
647	sampleRight = (sampleRight * audio->masterVolume) >> 6;
648
649	mCoreSyncLockAudio(audio->p->sync);
650	unsigned produced;
651	if ((size_t) blip_samples_avail(audio->left) < audio->samples) {
652		blip_add_delta(audio->left, audio->clock, sampleLeft - audio->lastLeft);
653		blip_add_delta(audio->right, audio->clock, sampleRight - audio->lastRight);
654		audio->lastLeft = sampleLeft;
655		audio->lastRight = sampleRight;
656		audio->clock += cycles;
657		if (audio->clock >= CLOCKS_PER_BLIP_FRAME) {
658			blip_end_frame(audio->left, audio->clock);
659			blip_end_frame(audio->right, audio->clock);
660			audio->clock -= CLOCKS_PER_BLIP_FRAME;
661		}
662	}
663	produced = blip_samples_avail(audio->left);
664	bool wait = produced >= audio->samples;
665	mCoreSyncProduceAudio(audio->p->sync, wait);
666	// TODO: Put AVStream back
667}
668
669void _writeDuty(struct GBAudioEnvelope* envelope, uint8_t value) {
670	envelope->length = GBAudioRegisterDutyGetLength(value);
671	envelope->duty = GBAudioRegisterDutyGetDuty(value);
672}
673
674bool _writeSweep(struct GBAudioEnvelope* envelope, uint8_t value) {
675	envelope->stepTime = GBAudioRegisterSweepGetStepTime(value);
676	envelope->direction = GBAudioRegisterSweepGetDirection(value);
677	envelope->initialVolume = GBAudioRegisterSweepGetInitialVolume(value);
678	if (envelope->stepTime == 0) {
679		envelope->dead = envelope->currentVolume ? 1 : 2;
680	} else if (!envelope->direction && !envelope->currentVolume) {
681		envelope->dead = 2;
682	} else if (envelope->direction && envelope->currentVolume == 0xF) {
683		envelope->dead = 1;
684	} else {
685		envelope->dead = 0;
686	}
687	envelope->nextStep = envelope->stepTime;
688	return envelope->initialVolume || envelope->direction;
689}
690
691static int32_t _updateSquareChannel(struct GBAudioSquareControl* control, int duty) {
692	control->hi = !control->hi;
693	int period = 4 * (2048 - control->frequency);
694	switch (duty) {
695	case 0:
696		return control->hi ? period : period * 7;
697	case 1:
698		return control->hi ? period * 2 : period * 6;
699	case 2:
700		return period * 4;
701	case 3:
702		return control->hi ? period * 6 : period * 2;
703	default:
704		// This should never be hit
705		return period * 4;
706	}
707}
708
709static void _updateEnvelope(struct GBAudioEnvelope* envelope) {
710	if (envelope->direction) {
711		++envelope->currentVolume;
712	} else {
713		--envelope->currentVolume;
714	}
715	if (envelope->currentVolume >= 15) {
716		envelope->currentVolume = 15;
717		envelope->dead = 1;
718	} else if (envelope->currentVolume <= 0) {
719		envelope->currentVolume = 0;
720		envelope->dead = 2;
721	} else {
722		envelope->nextStep = envelope->stepTime;
723	}
724}
725
726static bool _updateSweep(struct GBAudioChannel1* ch, bool initial) {
727	if (initial || ch->time != 8) {
728		int frequency = ch->control.frequency;
729		if (ch->direction) {
730			frequency -= frequency >> ch->shift;
731			if (!initial && frequency >= 0) {
732				ch->control.frequency = frequency;
733				ch->realFrequency = frequency;
734			}
735		} else {
736			frequency += frequency >> ch->shift;
737			if (frequency < 2048) {
738				if (!initial && ch->shift) {
739					ch->control.frequency = frequency;
740					if (!_updateSweep(ch, true)) {
741						return false;
742					}
743					ch->realFrequency = frequency;
744				}
745			} else {
746				return false;
747			}
748		}
749		ch->sweepOccurred = true;
750	}
751	ch->sweepStep = ch->time;
752	return true;
753}
754
755static int32_t _updateChannel1(struct GBAudioChannel1* ch) {
756	int timing = _updateSquareChannel(&ch->control, ch->envelope.duty);
757	ch->sample = ch->control.hi * 0x10 - 0x8;
758	ch->sample *= ch->envelope.currentVolume;
759	return timing;
760}
761
762static int32_t _updateChannel2(struct GBAudioChannel2* ch) {
763	int timing = _updateSquareChannel(&ch->control, ch->envelope.duty);
764	ch->sample = ch->control.hi * 0x10 - 0x8;
765	ch->sample *= ch->envelope.currentVolume;
766	return timing;
767}
768
769static int32_t _updateChannel3(struct GBAudioChannel3* ch, enum GBAudioStyle style) {
770	int i;
771	int volume;
772	switch (ch->volume) {
773	case 0:
774		volume = 0;
775		break;
776	case 1:
777		volume = 4;
778		break;
779	case 2:
780		volume = 2;
781		break;
782	case 3:
783		volume = 1;
784		break;
785	default:
786		volume = 3;
787		break;
788	}
789	switch (style) {
790		int start;
791		int end;
792	case GB_AUDIO_DMG:
793	default:
794		++ch->window;
795		ch->window &= 0x1F;
796		ch->sample = ch->wavedata8[ch->window >> 1];
797		if (ch->window & 1) {
798			ch->sample &= 0xF;
799		} else {
800			ch->sample >>= 4;
801		}
802		break;
803	case GB_AUDIO_GBA:
804		if (ch->size) {
805			start = 7;
806			end = 0;
807		} else if (ch->bank) {
808			start = 7;
809			end = 4;
810		} else {
811			start = 3;
812			end = 0;
813		}
814		uint32_t bitsCarry = ch->wavedata32[end] & 0x000000F0;
815		uint32_t bits;
816		for (i = start; i >= end; --i) {
817			bits = ch->wavedata32[i] & 0x000000F0;
818			ch->wavedata32[i] = ((ch->wavedata32[i] & 0x0F0F0F0F) << 4) | ((ch->wavedata32[i] & 0xF0F0F000) >> 12);
819			ch->wavedata32[i] |= bitsCarry << 20;
820			bitsCarry = bits;
821		}
822		ch->sample = bitsCarry >> 4;
823		break;
824	}
825	ch->sample -= 8;
826	ch->sample *= volume * 4;
827	return 2 * (2048 - ch->rate);
828}
829
830static int32_t _updateChannel4(struct GBAudioChannel4* ch) {
831	int lsb = ch->lfsr & 1;
832	ch->sample = lsb * 0x10 - 0x8;
833	ch->sample *= ch->envelope.currentVolume;
834	ch->lfsr >>= 1;
835	ch->lfsr ^= (lsb * 0x60) << (ch->power ? 0 : 8);
836	int timing = ch->ratio ? 2 * ch->ratio : 1;
837	timing <<= ch->frequency;
838	timing *= 8;
839	return timing;
840}