all repos — mgba @ 5d28145b525e81de9c531b1dbc531203d9827e03

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