all repos — mgba @ c5b78f93542278add1fc347388eaf4f31d54f8a6

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