gb_emulator / gb_emulator / src / gb_sound.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
/*  Copyright © 2011 Chris Spencer <spencercw@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include <sndfile.hh>

#ifdef _MSC_VER
#pragma warning(push, 0)
#endif

#include "gb.pb.h"

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <gb_emulator/gb.hpp>
#include <gb_emulator/gb_memory.hpp>
#include <gb_emulator/gb_sound.hpp>

#include "gb_sound_tables.h"

namespace fs = boost::filesystem;
using std::numeric_limits;

static const double PI = 3.14159265358979323846264338327950288;
static const double DUTY_RATIOS[] = { 0.25, 0.5, 1, 1.5 };

// Constants for channel 4
static const double BASE_FREQUENCY = 4194304 / 8;
static const double CLOCK_DIVIDER_FREQ[] = {
	BASE_FREQUENCY * 2,
	BASE_FREQUENCY,
	BASE_FREQUENCY / 2,
	BASE_FREQUENCY / 3,
	BASE_FREQUENCY / 4,
	BASE_FREQUENCY / 5,
	BASE_FREQUENCY / 6,
	BASE_FREQUENCY / 7
};
// The last two values in this array shouldn't be used and are just there to prevent a crash. I'm
// not sure what the Game Boy actually does if those values are used.
static const double PRE_SCALER[] = { 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400,
	0x800, 0x1000, 0x2000, 0x4000, 1, 1 };
static const uint32_t *LFSR[] = { lfsr15, lfsr7 };
static const unsigned LFSR_SIZE[] = { 32768, 128 };

static const double BASE_VOLUME = 1. / 64;

GbSound::GbSound(Gb &gb):
gb_(gb)
{
	reset();
}

GbSound::~GbSound()
{
}

void GbSound::reset()
{
	gbFrequency1_ = 0;
	gbFrequency2_ = 0;
	gbFrequency3_ = 0;
	actFrequency1_ = 0;
	actFrequency2_ = 0;
	actFrequency3_ = 0;
	actFrequency4_ = 0;
	hi1_ = false;
	hi2_ = false;
	duration1_ = 0;
	duration2_ = 0;
	duration3_ = 0;
	duration4_ = 0;
	duty1_ = 1;
	duty2_ = 1;
	countdown1_ = 0;
	countdown2_ = 0;
	countdown3_ = 0;
	countdown4_ = 0;
	sweepEnabled1_ = false;
	sweepNextFrequency1_ = 0;
	sweepShifts1_ = 0;
	sweepType1_ = 0;
	sweepStep1_ = 0;
	sweepCountdown1_ = 0;
	envelope1_ = 0;
	envelope2_ = 0;
	envelope4_ = 0;
	envelopeDirection1_ = false;
	envelopeDirection2_ = false;
	envelopeDirection4_ = false;
	envelopeStep1_ = 0;
	envelopeStep2_ = 0;
	envelopeStep4_ = 0;
	envelopeCountdown1_ = 0;
	envelopeCountdown2_ = 0;
	envelopeCountdown4_ = 0;
	waveIndex3_ = 0;
	outLevel3_ = 0;
	counterData4_ = lfsr15;
	counterDataSize4_ = 32768;
	counterIndex4_ = 0;

	memset(wavePattern3_, 0, 0x10);
	memset(savedRegisters, 0xff, 5);
}

double GbSound::poll()
{
	return sampleCycles_;
}

void GbSound::pollEvents()
{
}

void GbSound::writeIoPort(uint8_t ptr, uint8_t val)
{
	if (ptr != NR52 && gb_.mem_->ioPorts()[NR52] & 0x80)
	{
		gb_.mem_->ioPorts()[ptr] = val;
	}
	else if (!(gb_.mem_->ioPorts()[NR52] & 0x80))
	{
		// If the sound unit is off only NR52 is accessible
		if (ptr == NR52)
		{
			gb_.mem_->ioPorts()[ptr] &= 0x0f;
			gb_.mem_->ioPorts()[ptr] |= val & 0xf0;

			if (val & 0x80)
			{
				// Turning the sound back on so reset the registers
				resetRegisters(*gb_.mem_);
			}
		}
		return;
	}

	switch (ptr)
	{
	// Sonud channel 1
	case NR10:
		sweepEnabled1_ = (val & 0x70) != 0;
		if (sweepEnabled1_)
		{
			sweepStep1_ = sampleRate_ / (128. / (((val & 0x70) >> 4) + 1));
			sweepShifts1_ = val & 0x07;
			sweepType1_  = (val & 0x08) == 0x08;
		}
		break;

	case NR11:
		duty1_ = DUTY_RATIOS[(val & 0xc0) >> 6];
		if (gb_.mem_->ioPorts()[NR14] & 0x40)
		{
			duration1_ = (64 - (val & 0x3f)) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration1_ = numeric_limits<double>::infinity();
		}
		break;

	case NR12:
		envelope1_ = val >> 4;
		envelopeDirection1_ = (val & 0x08) == 0x08;
		envelopeStep1_ = ((val & 0x07) * (1. / 64)) * sampleRate_;
		break;

	case NR13:
		gbFrequency1_ = (val | ((gb_.mem_->ioPorts()[NR14] & 0x07) << 8));
		actFrequency1_ = 131072. / (0x800 - gbFrequency1_);
		break;

	case NR14:
		gbFrequency1_ = (gb_.mem_->ioPorts()[NR13] | ((val & 0x07) << 8));
		actFrequency1_ = 131072. / (0x800 - gbFrequency1_);
		if (val & 0x40)
		{
			duration1_ = (64 - (gb_.mem_->ioPorts()[NR11] & 0x3f)) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration1_ = numeric_limits<double>::infinity();
		}
		break;

	// Sound channel 2
	case NR21:
		duty2_ = DUTY_RATIOS[(val & 0xc0) >> 6];
		if (gb_.mem_->ioPorts()[NR24] & 0x40)
		{
			duration2_ = (64 - (val & 0x3f)) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration2_ = numeric_limits<double>::infinity();
		}
		break;

	case NR22:
		envelope2_ = val >> 4;
		envelopeDirection2_ = (val & 0x08) == 0x08;
		envelopeStep2_ = ((val & 0x07) * (1. / 64)) * sampleRate_;
		break;

	case NR23:
		gbFrequency2_ = (val | ((gb_.mem_->ioPorts()[NR24] & 0x07) << 8));
		actFrequency2_ = 131072. / (0x800 - gbFrequency2_);
		break;

	case NR24:
		gbFrequency2_ = (gb_.mem_->ioPorts()[NR23] | ((val & 0x07) << 8));
		actFrequency2_ = 131072. / (0x800 - gbFrequency2_);
		if (val & 0x40)
		{
			duration2_ = (64 - (gb_.mem_->ioPorts()[NR21] & 0x3f)) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration2_ = numeric_limits<double>::infinity();
		}
		break;

	// Sound channel 3
	case NR31:
		if (gb_.mem_->ioPorts()[NR34] & 0x40)
		{
			duration3_ = (256 - val) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration3_ = numeric_limits<double>::infinity();
		}
		break;

	case NR32:
		outLevel3_ = (gb_.mem_->ioPorts()[NR32] & 0x60) >> 5;
		break;

	case NR33:
		gbFrequency3_ = (val | ((gb_.mem_->ioPorts()[NR34] & 0x07) << 8));
		actFrequency3_ = 131072. / (0x800 - gbFrequency3_);
		break;

	case NR34:
		gbFrequency3_ = (gb_.mem_->ioPorts()[NR33] | ((val & 0x07) << 8));
		actFrequency3_ = 131072. / (0x800 - gbFrequency3_);
		if (val & 0x40)
		{
			duration3_ = (256 - gb_.mem_->ioPorts()[NR31]) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration3_ = numeric_limits<double>::infinity();
		}
		break;

	// Sound channel 4
	case NR41:
		if (gb_.mem_->ioPorts()[NR44] & 0x40)
		{
			duration4_ = (64 - (val & 0x3f)) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration4_ = numeric_limits<double>::infinity();
		}
		break;

	case NR42:
		envelope4_ = val >> 4;
		envelopeDirection4_ = (val & 0x08) == 0x08;
		envelopeStep4_ = ((val & 0x07) * (1. / 64)) * sampleRate_;
		break;

	case NR43:
		{
			actFrequency4_  = CLOCK_DIVIDER_FREQ[val & 0x07];
			actFrequency4_ /= PRE_SCALER[val >> 4];

			bool lfsrSelection = (val & 0x08) == 0x08;
			counterData4_ = LFSR[lfsrSelection];
			counterDataSize4_ = LFSR_SIZE[lfsrSelection];
			counterIndex4_ = 0;
		}
		break;

	case NR44:
		if (val & 0x40)
		{
			duration4_ = (64 - (gb_.mem_->ioPorts()[NR41] & 0x3f)) * (1. / 256) * sampleRate_;
		}
		else
		{
			duration4_ = numeric_limits<double>::infinity();
		}
		break;

	// Control registers
	case NR52:
		gb_.mem_->ioPorts()[ptr] &= 0x0f;
		gb_.mem_->ioPorts()[ptr] |= val & 0xf0;

		if (!(val & 0x80))
		{
			// Save the values of the registers that persist over power cycles
			savedRegisters[0] = gb_.mem_->ioPorts()[NR13];
			savedRegisters[1] = gb_.mem_->ioPorts()[NR20];
			savedRegisters[2] = gb_.mem_->ioPorts()[NR23];
			savedRegisters[3] = gb_.mem_->ioPorts()[NR33];
			savedRegisters[4] = gb_.mem_->ioPorts()[NR40];

			// Clear the current values in the sound registers
			gb_.mem_->ioPorts()[NR52] &= 0xf0;
			memset(&gb_.mem_->ioPorts()[NR10], 0, NR52 - NR10);
			memset(&gb_.mem_->ioPorts()[NR52 + 1], 0, 0x30 - NR52 - 1);
		}

		break;
	}
}

void GbSound::resetRegisters(GbMemory &mem) const
{
	mem.ioPorts()[NR10] = 0x80;
	mem.ioPorts()[NR11] = 0xbf;
	mem.ioPorts()[NR12] = 0xf3;
	mem.ioPorts()[NR13] = savedRegisters[0];
	mem.ioPorts()[NR14] = 0x3f;
	mem.ioPorts()[NR20] = savedRegisters[1];
	mem.ioPorts()[NR21] = 0x3f;
	mem.ioPorts()[NR22] = 0x00;
	mem.ioPorts()[NR23] = savedRegisters[2];
	mem.ioPorts()[NR24] = 0x3f;
	mem.ioPorts()[NR30] = 0x7f;
	mem.ioPorts()[NR31] = 0xff;
	mem.ioPorts()[NR32] = 0x9f;
	mem.ioPorts()[NR33] = savedRegisters[3];
	mem.ioPorts()[NR34] = 0x3f;
	mem.ioPorts()[NR40] = savedRegisters[4];
	mem.ioPorts()[NR41] = 0xff;
	mem.ioPorts()[NR42] = 0x00;
	mem.ioPorts()[NR43] = 0x00;
	mem.ioPorts()[NR44] = 0x3f;
	mem.ioPorts()[NR50] = 0x77;
	mem.ioPorts()[NR51] = 0xf3;
	mem.ioPorts()[NR52] = 0x80;
}

void GbSound::record(const fs::path &path)
{
	soundFile_.reset(new SndfileHandle(path.native().c_str(), SFM_WRITE,
		SF_FORMAT_WAVEX | SF_FORMAT_PCM_16, 2, sampleRate_));
}

void GbSound::stopRecording()
{
	soundFile_.reset();
}

double GbSound::sound1()
{
	// Return silence if nothing is playing and nothing is set to play
	if (countdown1_ <= 0 && !(gb_.mem_->ioPorts()[NR52] & 0x01) && !(gb_.mem_->ioPorts()[NR14] & 0x80))
	{
		return 0;
	}

	if (countdown1_ <= 0 || gb_.mem_->ioPorts()[NR14] & 0x80)
	{
		// Update the sound parameters if necessary
		if (gb_.mem_->ioPorts()[NR14] & 0x80)
		{
			gb_.mem_->ioPorts()[NR14] &= ~0x80;
			gb_.mem_->ioPorts()[NR52] |=  0x01;
			countdown1_ = 0;

			// Calculate the tone frequency
			gbFrequency1_ =
				(gb_.mem_->ioPorts()[NR13] | ((gb_.mem_->ioPorts()[NR14] & 0x07) << 8));
			actFrequency1_ = 131072. / (0x800 - gbFrequency1_);

			// Set the wave pattern duty
			duty1_ = DUTY_RATIOS[(gb_.mem_->ioPorts()[NR11] & 0xc0) >> 6];

			// Save the sweep parameters
			sweepEnabled1_ = (gb_.mem_->ioPorts()[NR10] & 0x70) != 0;
			if (sweepEnabled1_)
			{
				sweepStep1_ = sampleRate_ / (128. / (((gb_.mem_->ioPorts()[NR10] & 0x70) >> 4) + 1));
				sweepShifts1_ = gb_.mem_->ioPorts()[NR10] & 0x07;
				sweepType1_  = (gb_.mem_->ioPorts()[NR10] & 0x08) == 0x08;
				sweepCountdown1_ = sweepStep1_;

				// The sweep unit is always one step ahead of what is actually played, so the last
				// note is never heard (unless the number of shifts is zero)
				sweepNextFrequency1_ = 0;
				if (sweepShifts1_ && !doSweep())
				{
					return 0;
				}
				else if (!sweepShifts1_)
				{
					sweepCountdown1_ = sweepStep1_;
				}
			}

			// Save the playback duration
			if (gb_.mem_->ioPorts()[NR14] & 0x40)
			{
				duration1_ = (64 - (gb_.mem_->ioPorts()[NR11] & 0x3f)) * (1. / 256) * sampleRate_;
			}
			else
			{
				duration1_ = numeric_limits<double>::infinity();
			}

			// Set the envelope parameters
			envelope1_ = gb_.mem_->ioPorts()[NR12] >> 4;
			envelopeDirection1_ = (gb_.mem_->ioPorts()[NR12] & 0x08) == 0x08;
			envelopeStep1_ = ((gb_.mem_->ioPorts()[NR12] & 0x07) * (1. / 64)) * sampleRate_;
			envelopeCountdown1_ = envelopeStep1_;
		}
		else
		{
			// Adjust the envelope amplitude
			adjustEnvelope(envelope1_, envelopeDirection1_, envelopeStep1_, envelopeCountdown1_);
		}

		// Toggle hi/lo wave
		hi1_ = !hi1_;

		double duration = 1 / actFrequency1_ / 2 * (hi1_ ? duty1_ : 2 - duty1_) * sampleRate_;
		countdown1_ += duration;
		duration1_  -= duration;

		// Reset the playback bit if the duration has elapsed
		if (duration1_ <= 0)
		{
			gb_.mem_->ioPorts()[NR52] &= ~0x01;
		}

		// Depending on the parameters the duration might be shorter than a single sample, so just
		// toggle the hi/lo flag repeatedly to catch up
		while (countdown1_ < 0)
		{
			hi1_ = !hi1_;
			countdown1_ += duration;
			duration1_  -= duration;
		}
	}

	double amplitude = BASE_VOLUME * (envelope1_ / 15.);

	// Handle the frequency sweep
	if (sweepEnabled1_ && --sweepCountdown1_ <= 0)
	{
		// If the number of shifts is set to zero we just stop after a single iteration
		if (!sweepShifts1_)
		{
			gb_.mem_->ioPorts()[NR52] &= ~0x01;
		}
		else
		{
			doSweep();
		}
	}

	// Handle the envelope step
	if (envelopeStep1_ &&
		(envelope1_ > 0  && !envelopeDirection1_) ||
		(envelope1_ < 15 &&  envelopeDirection1_))
	{
		--envelopeCountdown1_;
	}

	--countdown1_;
	return hi1_ ? amplitude : -amplitude;
}

double GbSound::sound2()
{
	// Return silence if nothing is playing and nothing is set to play
	if (countdown2_ <= 0 && !(gb_.mem_->ioPorts()[NR52] & 0x02) && !(gb_.mem_->ioPorts()[NR24] & 0x80))
	{
		return 0;
	}

	if (countdown2_ <= 0 || gb_.mem_->ioPorts()[NR24] & 0x80)
	{
		// Update the sound parameters if necessary
		if (gb_.mem_->ioPorts()[NR24] & 0x80)
		{
			gb_.mem_->ioPorts()[NR24] &= ~0x80;
			gb_.mem_->ioPorts()[NR52] |=  0x02;
			countdown2_ = 0;

			// Calculate the tone frequency
			gbFrequency2_ =
				(gb_.mem_->ioPorts()[NR23] | ((gb_.mem_->ioPorts()[NR24] & 0x07) << 8));
			actFrequency2_ = 131072. / (0x800 - gbFrequency2_);

			// Set the wave pattern duty
			duty2_ = DUTY_RATIOS[gb_.mem_->ioPorts()[NR21] >> 6];

			// Save the playback duration
			if (gb_.mem_->ioPorts()[NR24] & 0x40)
			{
				duration2_ = (64 - (gb_.mem_->ioPorts()[NR21] & 0x3f)) * (1. / 256) * sampleRate_;
			}
			else
			{
				duration2_ = numeric_limits<double>::infinity();
			}

			// Set the envelope parameters
			envelope2_ = gb_.mem_->ioPorts()[NR22] >> 4;
			envelopeDirection2_ = (gb_.mem_->ioPorts()[NR22] & 0x08) == 0x08;
			envelopeStep2_ = ((gb_.mem_->ioPorts()[NR22] & 0x07) * (1. / 64)) * sampleRate_;
			envelopeCountdown2_ = envelopeStep2_;
		}
		else
		{
			// Adjust the envelope amplitude
			adjustEnvelope(envelope2_, envelopeDirection2_, envelopeStep2_, envelopeCountdown2_);
		}
		
		// Toggle hi/lo wave
		hi2_ = !hi2_;

		double duration = 1 / actFrequency2_ / 2 * (hi2_ ? duty2_ : 2 - duty2_) * sampleRate_;
		countdown2_ += duration;
		duration2_  -= duration;

		// Reset the playback bit if the duration has elapsed
		if (duration2_ <= 0)
		{
			gb_.mem_->ioPorts()[NR52] &= ~0x02;
		}

		// Depending on the parameters the duration might be shorter than a single sample, so just
		// toggle the hi/lo flag repeatedly to catch up
		while (countdown2_ < 0)
		{
			hi2_ = !hi2_;
			countdown2_ += duration;
			duration2_  -= duration;
		}
	}

	double amplitude = BASE_VOLUME * (envelope2_ / 15.);

	// Handle the envelope step
	if (envelopeStep2_ &&
		(envelope2_ > 0  && !envelopeDirection2_) ||
		(envelope2_ < 15 &&  envelopeDirection2_))
	{
		--envelopeCountdown2_;
	}

	--countdown2_;
	return hi2_ ? amplitude : -amplitude;
}

double GbSound::sound3()
{
	// Return silence if nothing is playing and nothing is set to play
	if (((countdown3_ <= 0 && !(gb_.mem_->ioPorts()[NR52] & 0x04)) ||
		!(gb_.mem_->ioPorts()[NR30] & 0x80)) && !(gb_.mem_->ioPorts()[NR34] & 0x80))
	{
		return 0;
	}

	if (countdown3_ <= 0 || gb_.mem_->ioPorts()[NR34] & 0x80)
	{
		// Update the sound parameters if necessary
		if (gb_.mem_->ioPorts()[NR34] & 0x80)
		{
			gb_.mem_->ioPorts()[NR34] &= ~0x80;
			gb_.mem_->ioPorts()[NR30] |=  0x80;
			gb_.mem_->ioPorts()[NR52] |=  0x04;
			countdown3_ = 0;

			// Calculate the tone frequency
			gbFrequency3_ =
				(gb_.mem_->ioPorts()[NR33] | ((gb_.mem_->ioPorts()[NR34] & 0x07) << 8));
			actFrequency3_ = 131072. / (0x800 - gbFrequency3_);

			// Save the wave pattern
			memcpy(wavePattern3_, &gb_.mem_->ioPorts()[0x30], 0x10);

			// Save the playback duration
			if (gb_.mem_->ioPorts()[NR34] & 0x40)
			{
				duration3_ = (256 - gb_.mem_->ioPorts()[NR31]) * (1. / 256) * sampleRate_;
			}
			else
			{
				duration3_ = numeric_limits<double>::infinity();
			}

			// Save the output level
			outLevel3_ = (gb_.mem_->ioPorts()[NR32] & 0x60) >> 5;
			waveIndex3_ = 0;
		}
		else
		{
			waveIndex3_ = (waveIndex3_ + 1) % 32;
		}

		double duration = 1 / actFrequency3_ / 16 * sampleRate_;
		countdown3_ += duration;
		duration3_  -= duration;

		// Reset the playback bit if the duration has elapsed
		if (duration3_ <= 0)
		{
			gb_.mem_->ioPorts()[NR52] &= ~0x04;
		}

		// Depending on the parameters the duration might be shorter than a single sample, so just
		// skip through the wave RAM to catch up.
		while (countdown3_ < 0)
		{
			waveIndex3_ = (waveIndex3_ + 1) % 32;
			countdown3_ += duration;
			duration3_  -= duration;
		}
	}

	double amplitude;
	if (!outLevel3_)
	{
		amplitude = 0;
	}
	else
	{
		uint8_t sample = wavePattern3_[waveIndex3_ / 2];
		// Samples are packed two to the byte
		if (waveIndex3_ % 2)
		{
			sample &= 0x0f;
		}
		else
		{
			sample >>= 4;
		}
		// Shift right to adjust the output level
		sample >>= outLevel3_ - 1;
		amplitude = BASE_VOLUME * ((sample - 7.5) / 7.5);
	}

	--countdown3_;
	return amplitude;
}

double GbSound::sound4()
{
	// Return silence if nothing is playing and nothing is set to play
	if (countdown4_ <= 0 && !(gb_.mem_->ioPorts()[NR52] & 0x08) && !(gb_.mem_->ioPorts()[NR44] & 0x80))
	{
		return 0;
	}

	if (countdown4_ <= 0 || gb_.mem_->ioPorts()[NR44] & 0x80)
	{
		// Update the sound parameters if necessary
		if (gb_.mem_->ioPorts()[NR44] & 0x80)
		{
			gb_.mem_->ioPorts()[NR44] &= ~0x80;
			gb_.mem_->ioPorts()[NR52] |=  0x08;
			countdown4_ = 0;

			// Get the frequency
			actFrequency4_  = CLOCK_DIVIDER_FREQ[gb_.mem_->ioPorts()[NR43] & 0x07];
			actFrequency4_ /= PRE_SCALER[gb_.mem_->ioPorts()[NR43] >> 4];

			// Save the playback duration
			if (gb_.mem_->ioPorts()[NR44] & 0x40)
			{
				duration4_ = (64 - (gb_.mem_->ioPorts()[NR41] & 0x3f)) * (1. / 256) * sampleRate_;
			}
			else
			{
				duration4_ = numeric_limits<double>::infinity();
			}

			// Select the appropriate LFSR data array
			bool lfsrSelection = (gb_.mem_->ioPorts()[NR43] & 0x08) == 0x08;
			counterData4_ = LFSR[lfsrSelection];
			counterDataSize4_ = LFSR_SIZE[lfsrSelection];
			counterIndex4_ = 0;

			// Set the envelope parameters
			envelope4_ = gb_.mem_->ioPorts()[NR42] >> 4;
			envelopeDirection4_ = (gb_.mem_->ioPorts()[NR42] & 0x08) == 0x08;
			envelopeStep4_ = ((gb_.mem_->ioPorts()[NR42] & 0x07) * (1. / 64)) * sampleRate_;
			envelopeCountdown4_ = envelopeStep4_;
		}
		else
		{
			// Increment the LFSR counter
			counterIndex4_ = (counterIndex4_ + 1) % counterDataSize4_;

			// Adjust the envelope amplitude
			adjustEnvelope(envelope4_, envelopeDirection4_, envelopeStep4_, envelopeCountdown4_);
		}

		double duration = 1 / actFrequency4_ * sampleRate_;
		countdown4_ += duration;
		duration4_  -= duration;

		// Reset the playback bit if the duration has elapsed
		if (duration4_ <= 0)
		{
			gb_.mem_->ioPorts()[NR52] &= ~0x08;
		}

		// Depending on the parameters the duration might be shorter than a single sample, so just
		// skip through the LFSR to catch up.
		while (countdown4_ < 0)
		{
			counterIndex4_ = (counterIndex4_ + 1) % counterDataSize4_;
			countdown4_ += duration;
			duration4_  -= duration;
		}
	}

	unsigned index = counterIndex4_ / 32;
	uint32_t bit = 1 << (counterIndex4_ % 32);

	static const double amplitudes[] = { -BASE_VOLUME, BASE_VOLUME };
	bool val = (counterData4_[index] & bit) == bit;
	double amplitude = amplitudes[val] * (envelope4_ / 15.);

	// Handle the envelope step
	if (envelopeStep4_ &&
		(envelope4_ > 0  && !envelopeDirection4_) ||
		(envelope4_ < 15 &&  envelopeDirection4_))
	{
		--envelopeCountdown4_;
	}

	--countdown4_;
	return amplitude;
}

void GbSound::generateSample(double &left, double &right)
{
	left = 0;
	right = 0;

	if (gb_.mem_->ioPorts()[NR52] & 0x80)
	{
		doChannel(sound1(), 1, left, right);
		doChannel(sound2(), 2, left, right);
		doChannel(sound3(), 4, left, right);
		doChannel(sound4(), 8, left, right);
		
		left  += left  *  (gb_.mem_->ioPorts()[NR50] & 0x07);
		right += right * ((gb_.mem_->ioPorts()[NR50] & 0x70) >> 4);
	}

	// Dump the audio if recording
	if (soundFile_)
	{
		int16_t samples[] = {
			static_cast<int16_t>(left * 0x8000), static_cast<int16_t>(right * 0x8000) };
		soundFile_->write(samples, 2);
	}
}

bool GbSound::doSweep()
{
	// Change the frequency if this isn't the first time we've been called for this sweep
	if (sweepNextFrequency1_)
	{
		gbFrequency1_ = sweepNextFrequency1_;
		actFrequency1_ = 131072. / (0x800 - gbFrequency1_);
		sweepCountdown1_ += sweepStep1_;
			
		gb_.mem_->ioPorts()[NR13]  = static_cast<uint8_t>(gbFrequency1_);
		gb_.mem_->ioPorts()[NR14] &= ~0x07;
		gb_.mem_->ioPorts()[NR14] |= static_cast<uint8_t>(gbFrequency1_ >> 8);
	}

	// Calculate the next frequency
	int16_t difference = gbFrequency1_ >> sweepShifts1_;
	if (sweepType1_)
	{
		difference = -difference;
	}
	sweepNextFrequency1_ = gbFrequency1_ + difference;

	// Check for overflow. If it does we stop now, so the last note is not played, even though it is
	// in range
	if (sweepNextFrequency1_ & 0xf800)
	{
		gb_.mem_->ioPorts()[NR52] &= ~0x01;
		return false;
	}

	return true;
}

void GbSound::adjustEnvelope(uint8_t &envelope, bool envelopeDirection, double envelopeStep,
	double &envelopeCountdown)
{
	if (envelope > 0 && !envelopeDirection && envelopeStep)
	{
		while (envelope > 0 && envelopeCountdown <= 0)
		{
			--envelope;
			envelopeCountdown += envelopeStep;
		}
	}
	else if (envelope < 15 && envelopeDirection && envelopeStep)
	{
		while (envelope < 15 && envelopeCountdown <= 0)
		{
			++envelope;
			envelopeCountdown += envelopeStep;
		}
	}
}

void GbSound::doChannel(double amplitude, uint8_t bit, double &left, double &right)
{
	if (gb_.mem_->ioPorts()[NR51] & (bit << 4))
	{
		left += amplitude;
	}
	if (gb_.mem_->ioPorts()[NR51] & bit)
	{
		right += amplitude;
	}
}

void GbSound::load(const GbSoundData &data)
{
	assert(data.sound_3().wave_pattern().length() == 0x10);

	const GbSoundData::Sound1 &sound1 = data.sound_1();
	gbFrequency1_ = static_cast<uint16_t>(sound1.gb_frequency());
	actFrequency1_ = sound1.act_frequency();
	hi1_ = sound1.hi();
	duty1_ = sound1.duty();
	duration1_ = sound1.duration();
	countdown1_ = sound1.countdown();
	sweepEnabled1_ = sound1.sweep_enabled();
	sweepShifts1_ = static_cast<uint8_t>(sound1.sweep_shifts());
	sweepType1_ = sound1.sweep_type();
	sweepStep1_ = sound1.sweep_step();
	sweepCountdown1_ = sound1.sweep_countdown();
	envelope1_ = static_cast<uint8_t>(sound1.envelope());
	envelopeDirection1_ = sound1.envelope_direction();
	envelopeStep1_ = sound1.envelope_step();
	envelopeCountdown1_ = sound1.envelope_countdown();

	const GbSoundData::Sound2 &sound2 = data.sound_2();
	gbFrequency2_ = static_cast<uint16_t>(sound2.gb_frequency());
	actFrequency2_ = sound2.act_frequency();
	hi2_ = sound2.hi();
	duty2_ = sound2.duty();
	duration2_ = sound2.duration();
	countdown2_ = sound2.countdown();
	envelope2_ = static_cast<uint8_t>(sound2.envelope());
	envelopeDirection2_ = sound2.envelope_direction();
	envelopeStep2_ = sound2.envelope_step();
	envelopeCountdown2_ = sound2.envelope_countdown();

	const GbSoundData::Sound3 &sound3 = data.sound_3();
	gbFrequency3_ = static_cast<uint16_t>(sound3.gb_frequency());
	actFrequency3_ = sound3.act_frequency();
	duration3_ = sound3.duration();
	countdown3_ = sound3.countdown();
	waveIndex3_ = static_cast<uint8_t>(sound3.wave_index());
	outLevel3_ = static_cast<uint8_t>(sound3.out_level());
	memcpy(wavePattern3_, sound3.wave_pattern().data(), 0x10);

	const GbSoundData::Sound4 &sound4 = data.sound_4();
	actFrequency4_ = sound4.frequency();
	duration4_ = sound4.duration();
	envelope4_ = static_cast<uint8_t>(sound4.envelope());
	envelopeDirection4_ = sound4.envelope_direction();
	envelopeStep4_ = sound4.envelope_step();
	envelopeCountdown4_ = sound4.envelope_countdown();
	counterData4_ = sound4.counter_steps() ? lfsr7 : lfsr15;
	counterDataSize4_ = sound4.counter_steps() ? 128 : 32768;
	counterIndex4_ = sound4.counter_index();
}

void GbSound::save(GbSoundData &data) const
{
	GbSoundData::Sound1 &sound1 = *data.mutable_sound_1();
	sound1.set_gb_frequency(gbFrequency1_);
	sound1.set_act_frequency(actFrequency1_);
	sound1.set_hi(hi1_);
	sound1.set_duty(duty1_);
	sound1.set_duration(duration1_);
	sound1.set_countdown(countdown1_);
	sound1.set_sweep_enabled(sweepEnabled1_);
	sound1.set_sweep_shifts(sweepShifts1_);
	sound1.set_sweep_type(sweepType1_);
	sound1.set_sweep_step(sweepStep1_);
	sound1.set_sweep_countdown(sweepCountdown1_);
	sound1.set_envelope(envelope1_);
	sound1.set_envelope_direction(envelopeDirection1_);
	sound1.set_envelope_step(envelopeStep1_);
	sound1.set_envelope_countdown(envelopeCountdown1_);

	GbSoundData::Sound2 &sound2 = *data.mutable_sound_2();
	sound2.set_gb_frequency(gbFrequency2_);
	sound2.set_act_frequency(actFrequency2_);
	sound2.set_hi(hi2_);
	sound2.set_duty(duty2_);
	sound2.set_duration(duration2_);
	sound2.set_countdown(countdown2_);
	sound2.set_envelope(envelope2_);
	sound2.set_envelope_direction(envelopeDirection2_);
	sound2.set_envelope_step(envelopeStep2_);
	sound2.set_envelope_countdown(envelopeCountdown2_);

	GbSoundData::Sound3 &sound3 = *data.mutable_sound_3();
	sound3.set_gb_frequency(gbFrequency3_);
	sound3.set_act_frequency(actFrequency3_);
	sound3.set_duration(duration3_);
	sound3.set_countdown(countdown3_);
	sound3.set_wave_index(waveIndex3_);
	sound3.set_out_level(outLevel3_);
	sound3.set_wave_pattern(wavePattern3_, 0x10);

	GbSoundData::Sound4 &sound4 = *data.mutable_sound_4();
	sound4.set_frequency(actFrequency4_);
	sound4.set_duration(duration4_);
	sound4.set_countdown(countdown4_);
	sound4.set_envelope(envelope4_);
	sound4.set_envelope_direction(envelopeDirection4_);
	sound4.set_envelope_step(envelopeStep4_);
	sound4.set_envelope_countdown(envelopeCountdown4_);
	sound4.set_counter_steps(counterData4_ == lfsr7);
	sound4.set_counter_index(counterIndex4_);
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.