all repos — mgba @ 555122e0a1bc1311040e6ff7a8b2d95090fa76ca

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