all repos — mgba @ eaec17488e6d837c47a7f7ff07b3421328d5fcf2

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