all repos — mgba @ 54bda1757ee644e8bca278007f928d6fca9c4202

mGBA Game Boy Advance Emulator

src/gba/gba-audio.c (view raw)

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