all repos — mgba @ ecdcef283b14a458521e80b714cb6d43da9965f6

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