all repos — mgba @ f98da2ab3ff0a8c7171c256ead46f819536618e2

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