all repos — mgba @ a93b21e88640848a0dac4a1319ffb4e3506040b6

mGBA Game Boy Advance Emulator

src/gba/audio.c (view raw)

  1/* Copyright (c) 2013-2015 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 "gba/gba.h"
  9#include "gba/io.h"
 10#include "gba/serialize.h"
 11#include "gba/supervisor/thread.h"
 12#include "gba/video.h"
 13
 14const unsigned GBA_AUDIO_SAMPLES = 2048;
 15const unsigned BLIP_BUFFER_SIZE = 0x4000;
 16const unsigned GBA_AUDIO_FIFO_SIZE = 8 * sizeof(int32_t);
 17const int GBA_AUDIO_VOLUME_MAX = 0x100;
 18#define SWEEP_CYCLES (GBA_ARM7TDMI_FREQUENCY / 128)
 19
 20#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
 21static const int CLOCKS_PER_FRAME = 0x400;
 22#endif
 23
 24static bool _writeEnvelope(struct GBAAudioEnvelope* envelope, uint16_t value);
 25static int32_t _updateSquareChannel(struct GBAAudioSquareControl* envelope, int duty);
 26static void _updateEnvelope(struct GBAAudioEnvelope* envelope);
 27static bool _updateSweep(struct GBAAudioChannel1* ch);
 28static int32_t _updateChannel1(struct GBAAudioChannel1* ch);
 29static int32_t _updateChannel2(struct GBAAudioChannel2* ch);
 30static int32_t _updateChannel3(struct GBAAudioChannel3* ch);
 31static int32_t _updateChannel4(struct GBAAudioChannel4* ch);
 32static int _applyBias(struct GBAAudio* audio, int sample);
 33static void _sample(struct GBAAudio* audio);
 34
 35void GBAAudioInit(struct GBAAudio* audio, size_t samples) {
 36	audio->samples = samples;
 37#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
 38	CircleBufferInit(&audio->left, samples * sizeof(int16_t));
 39	CircleBufferInit(&audio->right, samples * sizeof(int16_t));
 40#else
 41	audio->left = blip_new(BLIP_BUFFER_SIZE);
 42	audio->right = blip_new(BLIP_BUFFER_SIZE);
 43	// Guess too large; we hang producing extra samples if we guess too low
 44	blip_set_rates(audio->left, GBA_ARM7TDMI_FREQUENCY, 96000);
 45	blip_set_rates(audio->right, GBA_ARM7TDMI_FREQUENCY, 96000);
 46#endif
 47	CircleBufferInit(&audio->chA.fifo, GBA_AUDIO_FIFO_SIZE);
 48	CircleBufferInit(&audio->chB.fifo, GBA_AUDIO_FIFO_SIZE);
 49
 50	audio->forceDisableCh[0] = false;
 51	audio->forceDisableCh[1] = false;
 52	audio->forceDisableCh[2] = false;
 53	audio->forceDisableCh[3] = false;
 54	audio->forceDisableChA = false;
 55	audio->forceDisableChB = false;
 56	audio->masterVolume = GBA_AUDIO_VOLUME_MAX;
 57}
 58
 59void GBAAudioReset(struct GBAAudio* audio) {
 60	audio->nextEvent = 0;
 61	audio->nextCh1 = 0;
 62	audio->nextCh2 = 0;
 63	audio->nextCh3 = 0;
 64	audio->nextCh4 = 0;
 65	audio->ch1 = (struct GBAAudioChannel1) { .envelope = { .nextStep = INT_MAX }, .nextSweep = INT_MAX };
 66	audio->ch2 = (struct GBAAudioChannel2) { .envelope = { .nextStep = INT_MAX } };
 67	audio->ch3 = (struct GBAAudioChannel3) { .bank = { .bank = 0 } };
 68	audio->ch4 = (struct GBAAudioChannel4) { .envelope = { .nextStep = INT_MAX } };
 69	audio->chA.dmaSource = 1;
 70	audio->chB.dmaSource = 2;
 71	audio->chA.sample = 0;
 72	audio->chB.sample = 0;
 73	audio->eventDiff = 0;
 74	audio->nextSample = 0;
 75	audio->sampleRate = 0x8000;
 76	audio->soundbias = 0x200;
 77	audio->volumeRight = 0;
 78	audio->volumeLeft = 0;
 79	audio->ch1Right = false;
 80	audio->ch2Right = false;
 81	audio->ch3Right = false;
 82	audio->ch4Right = false;
 83	audio->ch1Left = false;
 84	audio->ch2Left = false;
 85	audio->ch3Left = false;
 86	audio->ch4Left = false;
 87	audio->volume = 0;
 88	audio->volumeChA = false;
 89	audio->volumeChB = false;
 90	audio->chARight = false;
 91	audio->chALeft = false;
 92	audio->chATimer = false;
 93	audio->chBRight = false;
 94	audio->chBLeft = false;
 95	audio->chBTimer = false;
 96	audio->playingCh1 = false;
 97	audio->playingCh2 = false;
 98	audio->playingCh3 = false;
 99	audio->playingCh4 = false;
100	audio->enable = false;
101	audio->sampleInterval = GBA_ARM7TDMI_FREQUENCY / audio->sampleRate;
102
103#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
104	CircleBufferClear(&audio->left);
105	CircleBufferClear(&audio->right);
106#else
107	blip_clear(audio->left);
108	blip_clear(audio->right);
109	audio->clock = 0;
110#endif
111	CircleBufferClear(&audio->chA.fifo);
112	CircleBufferClear(&audio->chB.fifo);
113}
114
115void GBAAudioDeinit(struct GBAAudio* audio) {
116#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
117	CircleBufferDeinit(&audio->left);
118	CircleBufferDeinit(&audio->right);
119#else
120	blip_delete(audio->left);
121	blip_delete(audio->right);
122#endif
123	CircleBufferDeinit(&audio->chA.fifo);
124	CircleBufferDeinit(&audio->chB.fifo);
125}
126
127void GBAAudioResizeBuffer(struct GBAAudio* audio, size_t samples) {
128	GBASyncLockAudio(audio->p->sync);
129	audio->samples = samples;
130#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
131	size_t oldCapacity = audio->left.capacity;
132	int16_t* buffer = malloc(oldCapacity);
133	int16_t dummy;
134	size_t read;
135	size_t i;
136
137	read = CircleBufferDump(&audio->left, buffer, oldCapacity);
138	CircleBufferDeinit(&audio->left);
139	CircleBufferInit(&audio->left, samples * sizeof(int16_t));
140	for (i = 0; i * sizeof(int16_t) < read; ++i) {
141		if (!CircleBufferWrite16(&audio->left, buffer[i])) {
142			CircleBufferRead16(&audio->left, &dummy);
143			CircleBufferWrite16(&audio->left, buffer[i]);
144		}
145	}
146
147	read = CircleBufferDump(&audio->right, buffer, oldCapacity);
148	CircleBufferDeinit(&audio->right);
149	CircleBufferInit(&audio->right, samples * sizeof(int16_t));
150	for (i = 0; i * sizeof(int16_t) < read; ++i) {
151		if (!CircleBufferWrite16(&audio->right, buffer[i])) {
152			CircleBufferRead16(&audio->right, &dummy);
153			CircleBufferWrite16(&audio->right, buffer[i]);
154		}
155	}
156
157	free(buffer);
158#else
159	blip_clear(audio->left);
160	blip_clear(audio->right);
161	audio->clock = 0;
162#endif
163
164	GBASyncConsumeAudio(audio->p->sync);
165}
166
167int32_t GBAAudioProcessEvents(struct GBAAudio* audio, int32_t cycles) {
168	audio->nextEvent -= cycles;
169	audio->eventDiff += cycles;
170	while (audio->nextEvent <= 0) {
171		audio->nextEvent = INT_MAX;
172		if (audio->enable) {
173			if (audio->playingCh1 && !audio->ch1.envelope.dead) {
174				audio->nextCh1 -= audio->eventDiff;
175				if (audio->ch1.envelope.nextStep != INT_MAX) {
176					audio->ch1.envelope.nextStep -= audio->eventDiff;
177					if (audio->ch1.envelope.nextStep <= 0) {
178						int8_t sample = audio->ch1.control.hi * 0x10 - 0x8;
179						_updateEnvelope(&audio->ch1.envelope);
180						if (audio->ch1.envelope.nextStep < audio->nextEvent) {
181							audio->nextEvent = audio->ch1.envelope.nextStep;
182						}
183						audio->ch1.sample = sample * audio->ch1.envelope.currentVolume;
184					}
185				}
186
187				if (audio->ch1.nextSweep != INT_MAX) {
188					audio->ch1.nextSweep -= audio->eventDiff;
189					if (audio->ch1.nextSweep <= 0) {
190						audio->playingCh1 = _updateSweep(&audio->ch1);
191						if (audio->ch1.nextSweep < audio->nextEvent) {
192							audio->nextEvent = audio->ch1.nextSweep;
193						}
194					}
195				}
196
197				if (audio->nextCh1 <= 0) {
198					audio->nextCh1 += _updateChannel1(&audio->ch1);
199					if (audio->nextCh1 < audio->nextEvent) {
200						audio->nextEvent = audio->nextCh1;
201					}
202				}
203
204				if (audio->ch1.control.stop) {
205					audio->ch1.control.endTime -= audio->eventDiff;
206					if (audio->ch1.control.endTime <= 0) {
207						audio->playingCh1 = 0;
208					}
209				}
210			}
211
212			if (audio->playingCh2 && !audio->ch2.envelope.dead) {
213				audio->nextCh2 -= audio->eventDiff;
214				if (audio->ch2.envelope.nextStep != INT_MAX) {
215					audio->ch2.envelope.nextStep -= audio->eventDiff;
216					if (audio->ch2.envelope.nextStep <= 0) {
217						int8_t sample = audio->ch2.control.hi * 0x10 - 0x8;
218						_updateEnvelope(&audio->ch2.envelope);
219						if (audio->ch2.envelope.nextStep < audio->nextEvent) {
220							audio->nextEvent = audio->ch2.envelope.nextStep;
221						}
222						audio->ch2.sample = sample * audio->ch2.envelope.currentVolume;
223					}
224				}
225
226				if (audio->nextCh2 <= 0) {
227					audio->nextCh2 += _updateChannel2(&audio->ch2);
228					if (audio->nextCh2 < audio->nextEvent) {
229						audio->nextEvent = audio->nextCh2;
230					}
231				}
232
233				if (audio->ch2.control.stop) {
234					audio->ch2.control.endTime -= audio->eventDiff;
235					if (audio->ch2.control.endTime <= 0) {
236						audio->playingCh2 = 0;
237					}
238				}
239			}
240
241			if (audio->playingCh3) {
242				audio->nextCh3 -= audio->eventDiff;
243				if (audio->nextCh3 <= 0) {
244					audio->nextCh3 += _updateChannel3(&audio->ch3);
245					if (audio->nextCh3 < audio->nextEvent) {
246						audio->nextEvent = audio->nextCh3;
247					}
248				}
249
250				if (audio->ch3.control.stop) {
251					audio->ch3.control.endTime -= audio->eventDiff;
252					if (audio->ch3.control.endTime <= 0) {
253						audio->playingCh3 = 0;
254					}
255				}
256			}
257
258			if (audio->playingCh4 && !audio->ch4.envelope.dead) {
259				audio->nextCh4 -= audio->eventDiff;
260				if (audio->ch4.envelope.nextStep != INT_MAX) {
261					audio->ch4.envelope.nextStep -= audio->eventDiff;
262					if (audio->ch4.envelope.nextStep <= 0) {
263						int8_t sample = (audio->ch4.sample >> 31) * 0x8;
264						_updateEnvelope(&audio->ch4.envelope);
265						if (audio->ch4.envelope.nextStep < audio->nextEvent) {
266							audio->nextEvent = audio->ch4.envelope.nextStep;
267						}
268						audio->ch4.sample = sample * audio->ch4.envelope.currentVolume;
269					}
270				}
271
272				if (audio->nextCh4 <= 0) {
273					audio->nextCh4 += _updateChannel4(&audio->ch4);
274					if (audio->nextCh4 < audio->nextEvent) {
275						audio->nextEvent = audio->nextCh4;
276					}
277				}
278
279				if (audio->ch4.control.stop) {
280					audio->ch4.control.endTime -= audio->eventDiff;
281					if (audio->ch4.control.endTime <= 0) {
282						audio->playingCh4 = 0;
283					}
284				}
285			}
286
287			audio->p->memory.io[REG_SOUNDCNT_X >> 1] &= ~0x000F;
288			audio->p->memory.io[REG_SOUNDCNT_X >> 1] |= audio->playingCh1;
289			audio->p->memory.io[REG_SOUNDCNT_X >> 1] |= audio->playingCh2 << 1;
290			audio->p->memory.io[REG_SOUNDCNT_X >> 1] |= audio->playingCh3 << 2;
291			audio->p->memory.io[REG_SOUNDCNT_X >> 1] |= audio->playingCh4 << 2;
292		}
293
294		audio->nextSample -= audio->eventDiff;
295		if (audio->nextSample <= 0) {
296			_sample(audio);
297			audio->nextSample += audio->sampleInterval;
298		}
299
300		if (audio->nextSample < audio->nextEvent) {
301			audio->nextEvent = audio->nextSample;
302		}
303		audio->eventDiff = 0;
304	}
305	return audio->nextEvent;
306}
307
308void GBAAudioScheduleFifoDma(struct GBAAudio* audio, int number, struct GBADMA* info) {
309	switch (info->dest) {
310	case BASE_IO | REG_FIFO_A_LO:
311		audio->chA.dmaSource = number;
312		break;
313	case BASE_IO | REG_FIFO_B_LO:
314		audio->chB.dmaSource = number;
315		break;
316	default:
317		GBALog(audio->p, GBA_LOG_GAME_ERROR, "Invalid FIFO destination: 0x%08X", info->dest);
318		return;
319	}
320	info->reg = GBADMARegisterSetDestControl(info->reg, DMA_FIXED);
321}
322
323void GBAAudioWriteSOUND1CNT_LO(struct GBAAudio* audio, uint16_t value) {
324	audio->ch1.sweep.shift = GBAAudioRegisterSquareSweepGetShift(value);
325	audio->ch1.sweep.direction = GBAAudioRegisterSquareSweepGetDirection(value);
326	audio->ch1.sweep.time = GBAAudioRegisterSquareSweepGetTime(value);
327	if (audio->ch1.sweep.time) {
328		audio->ch1.nextSweep = audio->ch1.sweep.time * SWEEP_CYCLES;
329	} else {
330		audio->ch1.nextSweep = INT_MAX;
331	}
332}
333
334void GBAAudioWriteSOUND1CNT_HI(struct GBAAudio* audio, uint16_t value) {
335	if (!_writeEnvelope(&audio->ch1.envelope, value)) {
336		audio->ch1.sample = 0;
337	}
338}
339
340void GBAAudioWriteSOUND1CNT_X(struct GBAAudio* audio, uint16_t value) {
341	audio->ch1.control.frequency = GBAAudioRegisterControlGetFrequency(value);
342	audio->ch1.control.stop = GBAAudioRegisterControlGetStop(value);
343	audio->ch1.control.endTime = (GBA_ARM7TDMI_FREQUENCY * (64 - audio->ch1.envelope.length)) >> 8;
344	if (GBAAudioRegisterControlIsRestart(value)) {
345		if (audio->ch1.sweep.time) {
346			audio->ch1.nextSweep = audio->ch1.sweep.time * SWEEP_CYCLES;
347		} else {
348			audio->ch1.nextSweep = INT_MAX;
349		}
350		if (!audio->playingCh1) {
351			audio->nextCh1 = 0;
352		}
353		audio->playingCh1 = 1;
354		audio->ch1.envelope.currentVolume = audio->ch1.envelope.initialVolume;
355		if (audio->ch1.envelope.currentVolume > 0) {
356			audio->ch1.envelope.dead = 0;
357		}
358		if (audio->ch1.envelope.stepTime) {
359			audio->ch1.envelope.nextStep = 0;
360		} else {
361			audio->ch1.envelope.nextStep = INT_MAX;
362		}
363	}
364}
365
366void GBAAudioWriteSOUND2CNT_LO(struct GBAAudio* audio, uint16_t value) {
367	if (!_writeEnvelope(&audio->ch2.envelope, value)) {
368		audio->ch2.sample = 0;
369	}
370}
371
372void GBAAudioWriteSOUND2CNT_HI(struct GBAAudio* audio, uint16_t value) {
373	audio->ch2.control.frequency = GBAAudioRegisterControlGetFrequency(value);
374	audio->ch2.control.stop = GBAAudioRegisterControlGetStop(value);
375	audio->ch2.control.endTime = (GBA_ARM7TDMI_FREQUENCY * (64 - audio->ch2.envelope.length)) >> 8;
376	if (GBAAudioRegisterControlIsRestart(value)) {
377		audio->playingCh2 = 1;
378		audio->ch2.envelope.currentVolume = audio->ch2.envelope.initialVolume;
379		if (audio->ch2.envelope.currentVolume > 0) {
380			audio->ch2.envelope.dead = 0;
381		}
382		if (audio->ch2.envelope.stepTime) {
383			audio->ch2.envelope.nextStep = 0;
384		} else {
385			audio->ch2.envelope.nextStep = INT_MAX;
386		}
387		audio->nextCh2 = 0;
388	}
389}
390
391void GBAAudioWriteSOUND3CNT_LO(struct GBAAudio* audio, uint16_t value) {
392	audio->ch3.bank.size = GBAAudioRegisterBankGetSize(value);
393	audio->ch3.bank.bank = GBAAudioRegisterBankGetBank(value);
394	audio->ch3.bank.enable = GBAAudioRegisterBankGetEnable(value);
395	if (audio->ch3.control.endTime >= 0) {
396		audio->playingCh3 = audio->ch3.bank.enable;
397	}
398}
399
400void GBAAudioWriteSOUND3CNT_HI(struct GBAAudio* audio, uint16_t value) {
401	audio->ch3.wave.length = GBAAudioRegisterBankWaveGetLength(value);
402	audio->ch3.wave.volume = GBAAudioRegisterBankWaveGetVolume(value);
403}
404
405void GBAAudioWriteSOUND3CNT_X(struct GBAAudio* audio, uint16_t value) {
406	audio->ch3.control.rate = GBAAudioRegisterControlGetRate(value);
407	audio->ch3.control.stop = GBAAudioRegisterControlGetStop(value);
408	audio->ch3.control.endTime = (GBA_ARM7TDMI_FREQUENCY * (256 - audio->ch3.wave.length)) >> 8;
409	if (GBAAudioRegisterControlIsRestart(value)) {
410		audio->playingCh3 = audio->ch3.bank.enable;
411	}
412}
413
414void GBAAudioWriteSOUND4CNT_LO(struct GBAAudio* audio, uint16_t value) {
415	if (!_writeEnvelope(&audio->ch4.envelope, value)) {
416		audio->ch4.sample = 0;
417	}
418}
419
420void GBAAudioWriteSOUND4CNT_HI(struct GBAAudio* audio, uint16_t value) {
421	audio->ch4.control.ratio = GBAAudioRegisterCh4ControlGetRatio(value);
422	audio->ch4.control.frequency = GBAAudioRegisterCh4ControlGetFrequency(value);
423	audio->ch4.control.power = GBAAudioRegisterCh4ControlGetPower(value);
424	audio->ch4.control.stop = GBAAudioRegisterCh4ControlGetStop(value);
425	audio->ch4.control.endTime = (GBA_ARM7TDMI_FREQUENCY * (64 - audio->ch4.envelope.length)) >> 8;
426	if (GBAAudioRegisterCh4ControlIsRestart(value)) {
427		audio->playingCh4 = 1;
428		audio->ch4.envelope.currentVolume = audio->ch4.envelope.initialVolume;
429		if (audio->ch4.envelope.currentVolume > 0) {
430			audio->ch4.envelope.dead = 0;
431		}
432		if (audio->ch4.envelope.stepTime) {
433			audio->ch4.envelope.nextStep = 0;
434		} else {
435			audio->ch4.envelope.nextStep = INT_MAX;
436		}
437		if (audio->ch4.control.power) {
438			audio->ch4.lfsr = 0x40;
439		} else {
440			audio->ch4.lfsr = 0x4000;
441		}
442		audio->nextCh4 = 0;
443	}
444}
445
446void GBAAudioWriteSOUNDCNT_LO(struct GBAAudio* audio, uint16_t value) {
447	audio->volumeRight = GBARegisterSOUNDCNT_LOGetVolumeRight(value);
448	audio->volumeLeft = GBARegisterSOUNDCNT_LOGetVolumeLeft(value);
449	audio->ch1Right = GBARegisterSOUNDCNT_LOGetCh1Right(value);
450	audio->ch2Right = GBARegisterSOUNDCNT_LOGetCh2Right(value);
451	audio->ch3Right = GBARegisterSOUNDCNT_LOGetCh3Right(value);
452	audio->ch4Right = GBARegisterSOUNDCNT_LOGetCh4Right(value);
453	audio->ch1Left = GBARegisterSOUNDCNT_LOGetCh1Left(value);
454	audio->ch2Left = GBARegisterSOUNDCNT_LOGetCh2Left(value);
455	audio->ch3Left = GBARegisterSOUNDCNT_LOGetCh3Left(value);
456	audio->ch4Left = GBARegisterSOUNDCNT_LOGetCh4Left(value);
457}
458
459void GBAAudioWriteSOUNDCNT_HI(struct GBAAudio* audio, uint16_t value) {
460	audio->volume = GBARegisterSOUNDCNT_HIGetVolume(value);
461	audio->volumeChA = GBARegisterSOUNDCNT_HIGetVolumeChA(value);
462	audio->volumeChB = GBARegisterSOUNDCNT_HIGetVolumeChB(value);
463	audio->chARight = GBARegisterSOUNDCNT_HIGetChARight(value);
464	audio->chALeft = GBARegisterSOUNDCNT_HIGetChALeft(value);
465	audio->chATimer = GBARegisterSOUNDCNT_HIGetChATimer(value);
466	audio->chBRight = GBARegisterSOUNDCNT_HIGetChBRight(value);
467	audio->chBLeft = GBARegisterSOUNDCNT_HIGetChBLeft(value);
468	audio->chBTimer = GBARegisterSOUNDCNT_HIGetChBTimer(value);
469	if (GBARegisterSOUNDCNT_HIIsChAReset(value)) {
470		CircleBufferClear(&audio->chA.fifo);
471	}
472	if (GBARegisterSOUNDCNT_HIIsChBReset(value)) {
473		CircleBufferClear(&audio->chB.fifo);
474	}
475}
476
477void GBAAudioWriteSOUNDCNT_X(struct GBAAudio* audio, uint16_t value) {
478	audio->enable = GBARegisterSOUNDCNT_XGetEnable(value);
479}
480
481void GBAAudioWriteSOUNDBIAS(struct GBAAudio* audio, uint16_t value) {
482	audio->soundbias = value;
483}
484
485void GBAAudioWriteWaveRAM(struct GBAAudio* audio, int address, uint32_t value) {
486	audio->ch3.wavedata[address | (!audio->ch3.bank.bank * 4)] = value;
487}
488
489void GBAAudioWriteFIFO(struct GBAAudio* audio, int address, uint32_t value) {
490	struct CircleBuffer* fifo;
491	switch (address) {
492	case REG_FIFO_A_LO:
493		fifo = &audio->chA.fifo;
494		break;
495	case REG_FIFO_B_LO:
496		fifo = &audio->chB.fifo;
497		break;
498	default:
499		GBALog(audio->p, GBA_LOG_ERROR, "Bad FIFO write to address 0x%03x", address);
500		return;
501	}
502	int i;
503	for (i = 0; i < 4; ++i) {
504		while (!CircleBufferWrite8(fifo, value >> (8 * i))) {
505			int8_t dummy;
506			CircleBufferRead8(fifo, &dummy);
507		}
508	}
509}
510
511void GBAAudioSampleFIFO(struct GBAAudio* audio, int fifoId, int32_t cycles) {
512	struct GBAAudioFIFO* channel;
513	if (fifoId == 0) {
514		channel = &audio->chA;
515	} else if (fifoId == 1) {
516		channel = &audio->chB;
517	} else {
518		GBALog(audio->p, GBA_LOG_ERROR, "Bad FIFO write to address 0x%03x", fifoId);
519		return;
520	}
521	if (CircleBufferSize(&channel->fifo) <= 4 * sizeof(int32_t) && channel->dmaSource > 0) {
522		struct GBADMA* dma = &audio->p->memory.dma[channel->dmaSource];
523		if (GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_CUSTOM) {
524			dma->nextCount = 4;
525			dma->nextEvent = 0;
526			dma->reg = GBADMARegisterSetWidth(dma->reg, 1);
527			GBAMemoryUpdateDMAs(audio->p, -cycles);
528		} else {
529			channel->dmaSource = 0;
530		}
531	}
532	CircleBufferRead8(&channel->fifo, (int8_t*) &channel->sample);
533}
534
535#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
536unsigned GBAAudioCopy(struct GBAAudio* audio, void* left, void* right, unsigned nSamples) {
537	GBASyncLockAudio(audio->p->sync);
538	unsigned read = 0;
539	if (left) {
540		unsigned readL = CircleBufferRead(&audio->left, left, nSamples * sizeof(int16_t)) >> 1;
541		if (readL < nSamples) {
542			memset((int16_t*) left + readL, 0, nSamples - readL);
543		}
544		read = readL;
545	}
546	if (right) {
547		unsigned readR = CircleBufferRead(&audio->right, right, nSamples * sizeof(int16_t)) >> 1;
548		if (readR < nSamples) {
549			memset((int16_t*) right + readR, 0, nSamples - readR);
550		}
551		read = read >= readR ? read : readR;
552	}
553	GBASyncConsumeAudio(audio->p->sync);
554	return read;
555}
556
557unsigned GBAAudioResampleNN(struct GBAAudio* audio, float ratio, float* drift, struct GBAStereoSample* output, unsigned nSamples) {
558	int16_t left[GBA_AUDIO_SAMPLES];
559	int16_t right[GBA_AUDIO_SAMPLES];
560
561	// toRead is in GBA samples
562	// TODO: Do this with fixed-point math
563	unsigned toRead = ceilf(nSamples / ratio);
564	unsigned totalRead = 0;
565	while (nSamples) {
566		unsigned currentRead = GBA_AUDIO_SAMPLES;
567		if (currentRead > toRead) {
568			currentRead = toRead;
569		}
570		unsigned read = GBAAudioCopy(audio, left, right, currentRead);
571		toRead -= read;
572		unsigned i;
573		for (i = 0; i < read; ++i) {
574			*drift += ratio;
575			while (*drift >= 1.f) {
576				output->left = left[i];
577				output->right = right[i];
578				++output;
579				++totalRead;
580				--nSamples;
581				*drift -= 1.f;
582				if (!nSamples) {
583					return totalRead;
584				}
585			}
586		}
587		if (read < currentRead) {
588			memset(output, 0, nSamples * sizeof(struct GBAStereoSample));
589			break;
590		}
591	}
592	return totalRead;
593}
594#endif
595
596bool _writeEnvelope(struct GBAAudioEnvelope* envelope, uint16_t value) {
597	envelope->length = GBAAudioRegisterEnvelopeGetLength(value);
598	envelope->duty = GBAAudioRegisterEnvelopeGetDuty(value);
599	envelope->stepTime = GBAAudioRegisterEnvelopeGetStepTime(value);
600	envelope->direction = GBAAudioRegisterEnvelopeGetDirection(value);
601	envelope->initialVolume = GBAAudioRegisterEnvelopeGetInitialVolume(value);
602	envelope->dead = 0;
603	if (envelope->stepTime) {
604		envelope->nextStep = 0;
605	} else {
606		envelope->nextStep = INT_MAX;
607		if (envelope->initialVolume == 0) {
608			envelope->dead = 1;
609			return false;
610		}
611	}
612	return true;
613}
614
615static int32_t _updateSquareChannel(struct GBAAudioSquareControl* control, int duty) {
616	control->hi = !control->hi;
617	int period = 16 * (2048 - control->frequency);
618	switch (duty) {
619	case 0:
620		return control->hi ? period : period * 7;
621	case 1:
622		return control->hi ? period * 2 : period * 6;
623	case 2:
624		return period * 4;
625	case 3:
626		return control->hi ? period * 6 : period * 2;
627	default:
628		// This should never be hit
629		return period * 4;
630	}
631}
632
633static void _updateEnvelope(struct GBAAudioEnvelope* envelope) {
634	if (envelope->direction) {
635		++envelope->currentVolume;
636	} else {
637		--envelope->currentVolume;
638	}
639	if (envelope->currentVolume >= 15) {
640		envelope->currentVolume = 15;
641		envelope->nextStep = INT_MAX;
642	} else if (envelope->currentVolume <= 0) {
643		envelope->currentVolume = 0;
644		envelope->dead = 1;
645		envelope->nextStep = INT_MAX;
646	} else {
647		envelope->nextStep += envelope->stepTime * (GBA_ARM7TDMI_FREQUENCY >> 6);
648	}
649}
650
651static bool _updateSweep(struct GBAAudioChannel1* ch) {
652	if (ch->sweep.direction) {
653		int frequency = ch->control.frequency;
654		frequency -= frequency >> ch->sweep.shift;
655		if (frequency >= 0) {
656			ch->control.frequency = frequency;
657		}
658	} else {
659		int frequency = ch->control.frequency;
660		frequency += frequency >> ch->sweep.shift;
661		if (frequency < 2048) {
662			ch->control.frequency = frequency;
663		} else {
664			return false;
665		}
666	}
667	ch->nextSweep += ch->sweep.time * SWEEP_CYCLES;
668	return true;
669}
670
671static int32_t _updateChannel1(struct GBAAudioChannel1* ch) {
672	int timing = _updateSquareChannel(&ch->control, ch->envelope.duty);
673	ch->sample = ch->control.hi * 0x10 - 0x8;
674	ch->sample *= ch->envelope.currentVolume;
675	return timing;
676}
677
678static int32_t _updateChannel2(struct GBAAudioChannel2* ch) {
679	int timing = _updateSquareChannel(&ch->control, ch->envelope.duty);
680	ch->sample = ch->control.hi * 0x10 - 0x8;
681	ch->sample *= ch->envelope.currentVolume;
682	return timing;
683}
684
685static int32_t _updateChannel3(struct GBAAudioChannel3* ch) {
686	int i;
687	int start;
688	int end;
689	int volume;
690	switch (ch->wave.volume) {
691	case 0:
692		volume = 0;
693		break;
694	case 1:
695		volume = 4;
696		break;
697	case 2:
698		volume = 2;
699		break;
700	case 3:
701		volume = 1;
702		break;
703	default:
704		volume = 3;
705		break;
706	}
707	if (ch->bank.size) {
708		start = 7;
709		end = 0;
710	} else if (ch->bank.bank) {
711		start = 7;
712		end = 4;
713	} else {
714		start = 3;
715		end = 0;
716	}
717	uint32_t bitsCarry = ch->wavedata[end] & 0x000000F0;
718	uint32_t bits;
719	for (i = start; i >= end; --i) {
720		bits = ch->wavedata[i] & 0x000000F0;
721		ch->wavedata[i] = ((ch->wavedata[i] & 0x0F0F0F0F) << 4) | ((ch->wavedata[i] & 0xF0F0F000) >> 12);
722		ch->wavedata[i] |= bitsCarry << 20;
723		bitsCarry = bits;
724	}
725	ch->sample = bitsCarry >> 4;
726	ch->sample -= 8;
727	ch->sample *= volume * 4;
728	return 8 * (2048 - ch->control.rate);
729}
730
731static int32_t _updateChannel4(struct GBAAudioChannel4* ch) {
732	int lsb = ch->lfsr & 1;
733	ch->sample = lsb * 0x10 - 0x8;
734	ch->sample *= ch->envelope.currentVolume;
735	ch->lfsr >>= 1;
736	ch->lfsr ^= (lsb * 0x60) << (ch->control.power ? 0 : 8);
737	int timing = ch->control.ratio ? 2 * ch->control.ratio : 1;
738	timing <<= ch->control.frequency;
739	timing *= 32;
740	return timing;
741}
742
743static int _applyBias(struct GBAAudio* audio, int sample) {
744	sample += GBARegisterSOUNDBIASGetBias(audio->soundbias);
745	if (sample >= 0x400) {
746		sample = 0x3FF;
747	} else if (sample < 0) {
748		sample = 0;
749	}
750	return ((sample - GBARegisterSOUNDBIASGetBias(audio->soundbias)) * audio->masterVolume) >> 3;
751}
752
753static void _sample(struct GBAAudio* audio) {
754	int16_t sampleLeft = 0;
755	int16_t sampleRight = 0;
756	int psgShift = 5 - audio->volume;
757
758	if (audio->playingCh1 && !audio->forceDisableCh[0]) {
759		if (audio->ch1Left) {
760			sampleLeft += audio->ch1.sample;
761		}
762
763		if (audio->ch1Right) {
764			sampleRight += audio->ch1.sample;
765		}
766	}
767
768	if (audio->playingCh2 && !audio->forceDisableCh[1]) {
769		if (audio->ch2Left) {
770			sampleLeft += audio->ch2.sample;
771		}
772
773		if (audio->ch2Right) {
774			sampleRight += audio->ch2.sample;
775		}
776	}
777
778	if (audio->playingCh3 && !audio->forceDisableCh[2]) {
779		if (audio->ch3Left) {
780			sampleLeft += audio->ch3.sample;
781		}
782
783		if (audio->ch3Right) {
784			sampleRight += audio->ch3.sample;
785		}
786	}
787
788	if (audio->playingCh4 && !audio->forceDisableCh[3]) {
789		if (audio->ch4Left) {
790			sampleLeft += audio->ch4.sample;
791		}
792
793		if (audio->ch4Right) {
794			sampleRight += audio->ch4.sample;
795		}
796	}
797
798	sampleLeft = (sampleLeft * (1 + audio->volumeLeft)) >> psgShift;
799	sampleRight = (sampleRight * (1 + audio->volumeRight)) >> psgShift;
800
801	if (!audio->forceDisableChA) {
802		if (audio->chALeft) {
803			sampleLeft += (audio->chA.sample << 2) >> !audio->volumeChA;
804		}
805
806		if (audio->chARight) {
807			sampleRight += (audio->chA.sample << 2) >> !audio->volumeChA;
808		}
809	}
810
811	if (!audio->forceDisableChB) {
812		if (audio->chBLeft) {
813			sampleLeft += (audio->chB.sample << 2) >> !audio->volumeChB;
814		}
815
816		if (audio->chBRight) {
817			sampleRight += (audio->chB.sample << 2) >> !audio->volumeChB;
818		}
819	}
820
821	sampleLeft = _applyBias(audio, sampleLeft);
822	sampleRight = _applyBias(audio, sampleRight);
823
824	GBASyncLockAudio(audio->p->sync);
825	unsigned produced;
826#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
827	CircleBufferWrite16(&audio->left, sampleLeft);
828	CircleBufferWrite16(&audio->right, sampleRight);
829	produced = CircleBufferSize(&audio->left) / 2;
830#else
831	if ((size_t) blip_samples_avail(audio->left) < audio->samples) {
832		blip_add_delta(audio->left, audio->clock, sampleLeft - audio->lastLeft);
833		blip_add_delta(audio->right, audio->clock, sampleRight - audio->lastRight);
834		audio->lastLeft = sampleLeft;
835		audio->lastRight = sampleRight;
836		audio->clock += audio->sampleInterval;
837		if (audio->clock >= CLOCKS_PER_FRAME) {
838			blip_end_frame(audio->left, audio->clock);
839			blip_end_frame(audio->right, audio->clock);
840			audio->clock -= CLOCKS_PER_FRAME;
841		}
842	}
843	produced = blip_samples_avail(audio->left);
844#endif
845	if (audio->p->stream && audio->p->stream->postAudioFrame) {
846		audio->p->stream->postAudioFrame(audio->p->stream, sampleLeft, sampleRight);
847	}
848	bool wait = produced >= audio->samples;
849	GBASyncProduceAudio(audio->p->sync, wait);
850
851	if (wait && audio->p->stream && audio->p->stream->postAudioBuffer) {
852		audio->p->stream->postAudioBuffer(audio->p->stream, audio);
853	}
854}
855
856void GBAAudioSerialize(const struct GBAAudio* audio, struct GBASerializedState* state) {
857	uint32_t flags = 0;
858
859	flags = GBASerializedAudioFlagsSetCh1Volume(flags, audio->ch1.envelope.currentVolume);
860	flags = GBASerializedAudioFlagsSetCh1Dead(flags, audio->ch1.envelope.dead);
861	flags = GBASerializedAudioFlagsSetCh1Hi(flags, audio->ch1.control.hi);
862	STORE_32(audio->ch1.envelope.nextStep, 0, &state->audio.ch1.envelopeNextStep);
863	STORE_32(audio->ch1.control.nextStep, 0, &state->audio.ch1.waveNextStep);
864	STORE_32(audio->ch1.nextSweep, 0, &state->audio.ch1.sweepNextStep);
865	STORE_32(audio->ch1.control.endTime, 0, &state->audio.ch1.endTime);
866	STORE_32(audio->nextCh1, 0, &state->audio.ch1.nextEvent);
867
868	flags = GBASerializedAudioFlagsSetCh2Volume(flags, audio->ch2.envelope.currentVolume);
869	flags = GBASerializedAudioFlagsSetCh2Dead(flags, audio->ch2.envelope.dead);
870	flags = GBASerializedAudioFlagsSetCh2Hi(flags, audio->ch2.control.hi);
871	STORE_32(audio->ch2.envelope.nextStep, 0, &state->audio.ch2.envelopeNextStep);
872	STORE_32(audio->ch2.control.nextStep, 0, &state->audio.ch2.waveNextStep);
873	STORE_32(audio->ch2.control.endTime, 0, &state->audio.ch2.endTime);
874	STORE_32(audio->nextCh2, 0, &state->audio.ch2.nextEvent);
875
876	memcpy(state->audio.ch3.wavebanks, audio->ch3.wavedata, sizeof(state->audio.ch3.wavebanks));
877	STORE_32(audio->ch3.control.endTime, 0, &state->audio.ch3.endTime);
878	STORE_32(audio->nextCh3, 0, &state->audio.ch3.nextEvent);
879
880	state->audio.flags = GBASerializedAudioFlagsSetCh4Volume(flags, audio->ch4.envelope.currentVolume);
881	state->audio.flags = GBASerializedAudioFlagsSetCh4Dead(flags, audio->ch4.envelope.dead);
882	STORE_32(audio->ch4.envelope.nextStep, 0, &state->audio.ch4.envelopeNextStep);
883	STORE_32(audio->ch4.lfsr, 0, &state->audio.ch4.lfsr);
884	STORE_32(audio->ch4.control.endTime, 0, &state->audio.ch4.endTime);
885	STORE_32(audio->nextCh4, 0, &state->audio.ch4.nextEvent);
886
887	STORE_32(flags, 0, &state->audio.flags);
888
889	CircleBufferDump(&audio->chA.fifo, state->audio.fifoA, sizeof(state->audio.fifoA));
890	CircleBufferDump(&audio->chB.fifo, state->audio.fifoB, sizeof(state->audio.fifoB));
891	uint32_t fifoSize = CircleBufferSize(&audio->chA.fifo);
892	STORE_32(fifoSize, 0, &state->audio.fifoSize);
893
894	STORE_32(audio->nextEvent, 0, &state->audio.nextEvent);
895	STORE_32(audio->eventDiff, 0, &state->audio.eventDiff);
896	STORE_32(audio->nextSample, 0, &state->audio.nextSample);
897}
898
899void GBAAudioDeserialize(struct GBAAudio* audio, const struct GBASerializedState* state) {
900	uint32_t flags;
901	LOAD_32(flags, 0, &state->audio.flags);
902	audio->ch1.envelope.currentVolume = GBASerializedAudioFlagsGetCh1Volume(flags);
903	audio->ch1.envelope.dead = GBASerializedAudioFlagsGetCh1Dead(flags);
904	audio->ch1.control.hi = GBASerializedAudioFlagsGetCh1Hi(flags);
905	LOAD_32(audio->ch1.envelope.nextStep, 0, &state->audio.ch1.envelopeNextStep);
906	LOAD_32(audio->ch1.control.nextStep, 0, &state->audio.ch1.waveNextStep);
907	LOAD_32(audio->ch1.nextSweep, 0, &state->audio.ch1.sweepNextStep);
908	LOAD_32(audio->ch1.control.endTime, 0, &state->audio.ch1.endTime);
909	LOAD_32(audio->nextCh1, 0, &state->audio.ch1.nextEvent);
910
911	audio->ch2.envelope.currentVolume = GBASerializedAudioFlagsGetCh2Volume(flags);
912	audio->ch2.envelope.dead = GBASerializedAudioFlagsGetCh2Dead(flags);
913	audio->ch2.control.hi = GBASerializedAudioFlagsGetCh2Hi(flags);
914	LOAD_32(audio->ch2.envelope.nextStep, 0, &state->audio.ch2.envelopeNextStep);
915	LOAD_32(audio->ch2.control.nextStep, 0, &state->audio.ch2.waveNextStep);
916	LOAD_32(audio->ch2.control.endTime, 0, &state->audio.ch2.endTime);
917	LOAD_32(audio->nextCh2, 0, &state->audio.ch2.nextEvent);
918
919	// TODO: Big endian?
920	memcpy(audio->ch3.wavedata, state->audio.ch3.wavebanks, sizeof(audio->ch3.wavedata));
921	LOAD_32(audio->ch3.control.endTime, 0, &state->audio.ch3.endTime);
922	LOAD_32(audio->nextCh3, 0, &state->audio.ch3.nextEvent);
923
924	audio->ch4.envelope.currentVolume = GBASerializedAudioFlagsGetCh4Volume(flags);
925	audio->ch4.envelope.dead = GBASerializedAudioFlagsGetCh4Dead(flags);
926	LOAD_32(audio->ch4.envelope.nextStep, 0, &state->audio.ch4.envelopeNextStep);
927	LOAD_32(audio->ch4.lfsr, 0, &state->audio.ch4.lfsr);
928	LOAD_32(audio->ch4.control.endTime, 0, &state->audio.ch4.endTime);
929	LOAD_32(audio->nextCh4, 0, &state->audio.ch4.nextEvent);
930
931	CircleBufferClear(&audio->chA.fifo);
932	CircleBufferClear(&audio->chB.fifo);
933	uint32_t fifoSize;
934	LOAD_32(fifoSize, 0, &state->audio.fifoSize);
935	if (state->audio.fifoSize > CircleBufferCapacity(&audio->chA.fifo)) {
936		fifoSize = CircleBufferCapacity(&audio->chA.fifo);
937	}
938	size_t i;
939	for (i = 0; i < fifoSize; ++i) {
940		CircleBufferWrite8(&audio->chA.fifo, state->audio.fifoA[i]);
941		CircleBufferWrite8(&audio->chB.fifo, state->audio.fifoB[i]);
942	}
943
944	LOAD_32(audio->nextEvent, 0, &state->audio.nextEvent);
945	LOAD_32(audio->eventDiff, 0, &state->audio.eventDiff);
946	LOAD_32(audio->nextSample, 0, &state->audio.nextSample);
947}
948
949float GBAAudioCalculateRatio(float inputSampleRate, float desiredFPS, float desiredSampleRate) {
950	return desiredSampleRate * GBA_ARM7TDMI_FREQUENCY / (VIDEO_TOTAL_LENGTH * desiredFPS * inputSampleRate);
951}