-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathAPU.cs
More file actions
1511 lines (1309 loc) · 42.4 KB
/
APU.cs
File metadata and controls
1511 lines (1309 loc) · 42.4 KB
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TODO - so many integers in the square wave output keep us from exactly unbiasing the waveform. also other waves probably. consider improving the unbiasing.
// ALSO - consider whether we should even be doing it: the nonlinear-mixing behaviour probably depends on those biases being there.
// if we have a better high-pass filter somewhere then we might could cope with the weird biases
// (mix higher integer precision with the non-linear mixer and then highpass filter befoure outputting s16s)
// http://wiki.nesdev.com/w/index.php/APU_Mixer_Emulation
// http://wiki.nesdev.com/w/index.php/APU
// http://wiki.nesdev.com/w/index.php/APU_Pulse
// sequencer ref: http://wiki.nesdev.com/w/index.php/APU_Frame_Counter
// TODO - refactor length counter to be separate component
using System.Runtime.CompilerServices;
using BizHawk.Common;
using BizHawk.Common.NumberExtensions;
namespace BizHawk.Emulation.Cores.Nintendo.NES
{
public sealed class APU
{
public int m_vol = 1;
public int dmc_dma_countdown = -1;
public int DMC_RDY_check;
public bool call_from_write;
public bool recalculate = false;
private readonly NES nes;
public APU(NES nes, APU old, bool pal)
{
this.nes = nes;
dmc = new DMCUnit(this, pal);
sequencer_lut = pal ? sequencer_lut_pal : sequencer_lut_ntsc;
noise = new NoiseUnit(this, pal);
triangle = new TriangleUnit(this);
pulse[0] = new PulseUnit(this, 1);
pulse[1] = new PulseUnit(this, 0);
if (old != null)
{
m_vol = old.m_vol;
}
}
private static readonly int[] DMC_RATE_NTSC = { 428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54 };
private static readonly int[] DMC_RATE_PAL = { 398, 354, 316, 298, 276, 236, 210, 198, 176, 148, 132, 118, 98, 78, 66, 50 };
private static readonly int[] LENGTH_TABLE = { 10, 254, 20, 2, 40, 4, 80, 6, 160, 8, 60, 10, 14, 12, 26, 14, 12, 16, 24, 18, 48, 20, 96, 22, 192, 24, 72, 26, 16, 28, 32, 30 };
private static readonly byte[,] PULSE_DUTY = {
{0,1,0,0,0,0,0,0}, // (12.5%)
{0,1,1,0,0,0,0,0}, // (25%)
{0,1,1,1,1,0,0,0}, // (50%)
{1,0,0,1,1,1,1,1}, // (25% negated (75%))
};
private static readonly byte[] TRIANGLE_TABLE =
{
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
};
private static readonly int[] NOISE_TABLE_NTSC =
{
4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068
};
private static readonly int[] NOISE_TABLE_PAL =
{
4, 7, 14, 30, 60, 88, 118, 148, 188, 236, 354, 472, 708, 944, 1890, 3778
};
public sealed class PulseUnit
{
public PulseUnit(APU apu, int unit) { this.unit = unit; this.apu = apu; }
public int unit;
private readonly APU apu;
// reg0
private int duty_cnt, env_loop, env_constant, env_cnt_value;
public bool len_halt;
// reg1
private int sweep_en, sweep_divider_cnt, sweep_negate, sweep_shiftcount;
private bool sweep_reload;
// reg2/3
private int len_cnt;
public int timer_raw_reload_value, timer_reload_value;
// misc..
private int lenctr_en;
public void SyncState(Serializer ser)
{
ser.BeginSection("Pulse" + unit);
ser.Sync(nameof(duty_cnt), ref duty_cnt);
ser.Sync(nameof(env_loop), ref env_loop);
ser.Sync(nameof(env_constant), ref env_constant);
ser.Sync(nameof(env_cnt_value), ref env_cnt_value);
ser.Sync(nameof(len_halt), ref len_halt);
ser.Sync(nameof(sweep_en), ref sweep_en);
ser.Sync(nameof(sweep_divider_cnt), ref sweep_divider_cnt);
ser.Sync(nameof(sweep_negate), ref sweep_negate);
ser.Sync(nameof(sweep_shiftcount), ref sweep_shiftcount);
ser.Sync(nameof(sweep_reload), ref sweep_reload);
ser.Sync(nameof(len_cnt), ref len_cnt);
ser.Sync(nameof(timer_raw_reload_value), ref timer_raw_reload_value);
ser.Sync(nameof(timer_reload_value), ref timer_reload_value);
ser.Sync(nameof(lenctr_en), ref lenctr_en);
ser.Sync(nameof(swp_divider_counter), ref swp_divider_counter);
ser.Sync(nameof(swp_silence), ref swp_silence);
ser.Sync(nameof(duty_step), ref duty_step);
ser.Sync(nameof(timer_counter), ref timer_counter);
ser.Sync(nameof(sample), ref sample);
ser.Sync(nameof(duty_value), ref duty_value);
ser.Sync(nameof(env_start_flag), ref env_start_flag);
ser.Sync(nameof(env_divider), ref env_divider);
ser.Sync(nameof(env_counter), ref env_counter);
ser.Sync(nameof(env_output), ref env_output);
ser.EndSection();
}
public bool IsLenCntNonZero() { return len_cnt > 0; }
public void WriteReg(int addr, byte val)
{
// Console.WriteLine("write pulse {0:X} {1:X}", addr, val);
switch (addr)
{
case 0:
env_cnt_value = val & 0xF;
env_constant = (val >> 4) & 1;
env_loop = (val >> 5) & 1;
duty_cnt = (val >> 6) & 3;
break;
case 1:
sweep_shiftcount = val & 7;
sweep_negate = (val >> 3) & 1;
sweep_divider_cnt = (val >> 4) & 7;
sweep_en = (val >> 7) & 1;
sweep_reload = true;
break;
case 2:
timer_reload_value = (timer_reload_value & 0x700) | val;
timer_raw_reload_value = timer_reload_value * 2 + 2;
// if (unit == 1) Console.WriteLine("{0} timer_reload_value: {1}", unit, timer_reload_value);
break;
case 3:
if (apu.len_clock_active)
{
if (len_cnt == 0)
{
len_cnt = LENGTH_TABLE[(val >> 3) & 0x1F] + 1;
}
} else
{
len_cnt = LENGTH_TABLE[(val >> 3) & 0x1F];
}
timer_reload_value = (timer_reload_value & 0xFF) | ((val & 0x07) << 8);
timer_raw_reload_value = timer_reload_value * 2 + 2;
duty_step = 0;
env_start_flag = 1;
// allow the lenctr_en to kill the len_cnt
set_lenctr_en(lenctr_en);
// serves as a useful note-on diagnostic
// if(unit==1) Console.WriteLine("{0} timer_reload_value: {1}", unit, timer_reload_value);
break;
}
}
public void set_lenctr_en(int value)
{
lenctr_en = value;
// if the length counter is not enabled, then we must disable the length system in this way
if (lenctr_en == 0) len_cnt = 0;
}
// state
private int swp_divider_counter;
private bool swp_silence;
private int duty_step;
private int timer_counter;
public int sample;
private bool duty_value;
private int env_start_flag, env_divider, env_counter;
public int env_output;
public void clock_length_and_sweep()
{
// this should be optimized to update only when `timer_reload_value` changes
int sweep_shifter = timer_reload_value >> sweep_shiftcount;
if (sweep_negate == 1)
sweep_shifter = -sweep_shifter - unit;
sweep_shifter += timer_reload_value;
// this sweep logic is always enabled:
swp_silence = (timer_reload_value < 8 || (sweep_shifter > 0x7FF)); // && sweep_negate == 0));
// does enable only block the pitch bend? does the clocking proceed?
if (sweep_en == 1)
{
// clock divider
if (swp_divider_counter != 0) swp_divider_counter--;
if (swp_divider_counter == 0)
{
swp_divider_counter = sweep_divider_cnt + 1;
// divider was clocked: process sweep pitch bend
if (sweep_shiftcount != 0 && !swp_silence)
{
timer_reload_value = sweep_shifter;
timer_raw_reload_value = (timer_reload_value << 1) + 2;
}
// TODO - does this change the user's reload value or the latched reload value?
}
// handle divider reload, after clocking happens
if (sweep_reload)
{
swp_divider_counter = sweep_divider_cnt + 1;
sweep_reload = false;
}
}
// env_loop doubles as "halt length counter"
if ((env_loop == 0 || len_halt) && len_cnt > 0)
len_cnt--;
}
public void clock_env()
{
if (env_start_flag == 1)
{
env_start_flag = 0;
env_divider = env_cnt_value;
env_counter = 15;
}
else
{
if (env_divider != 0)
{
env_divider--;
} else if (env_divider == 0)
{
env_divider = env_cnt_value;
if (env_counter == 0)
{
if (env_loop == 1)
{
env_counter = 15;
}
}
else env_counter--;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Run()
{
if (env_constant == 1)
env_output = env_cnt_value;
else env_output = env_counter;
if (timer_counter > 0) timer_counter--;
if (timer_counter == 0 && timer_raw_reload_value != 0)
{
if (duty_step==7)
{
duty_step = 0;
} else
{
duty_step++;
}
duty_value = PULSE_DUTY[duty_cnt, duty_step] == 1;
// reload timer
timer_counter = timer_raw_reload_value;
}
int newsample;
if (duty_value) // high state of duty cycle
{
newsample = env_output;
if (swp_silence || len_cnt == 0)
newsample = 0; // silenced
}
else
newsample = 0; // duty cycle is 0, silenced.
// newsample -= env_output >> 1; //unbias
if (newsample != sample)
{
apu.recalculate = true;
sample = newsample;
}
}
public bool Debug_IsSilenced => swp_silence || len_cnt == 0;
public int Debug_DutyType => duty_cnt;
public int Debug_Volume => env_output;
}
public sealed class NoiseUnit
{
private readonly APU apu;
// reg0 (sweep)
private int env_cnt_value, env_loop, env_constant;
public bool len_halt;
// reg2 (mode and period)
private int mode_cnt, period_cnt;
// reg3 (length counter and envelop trigger)
private int len_cnt;
// set from apu:
private int lenctr_en;
// state
private int shift_register = 1;
private int timer_counter;
public int sample;
private int env_output, env_start_flag, env_divider, env_counter;
private bool noise_bit = true;
private readonly int[] NOISE_TABLE;
public NoiseUnit(APU apu, bool pal)
{
this.apu = apu;
NOISE_TABLE = pal ? NOISE_TABLE_PAL : NOISE_TABLE_NTSC;
}
public bool Debug_IsSilenced
{
get
{
if (len_cnt == 0) return true;
return false;
}
}
public int Debug_Period => period_cnt;
public int Debug_Volume => env_output;
public void SyncState(Serializer ser)
{
ser.BeginSection("Noise");
ser.Sync(nameof(env_cnt_value), ref env_cnt_value);
ser.Sync(nameof(env_loop), ref env_loop);
ser.Sync(nameof(env_constant), ref env_constant);
ser.Sync(nameof(mode_cnt), ref mode_cnt);
ser.Sync(nameof(period_cnt), ref period_cnt);
ser.Sync(nameof(len_halt), ref len_halt);
ser.Sync(nameof(len_cnt), ref len_cnt);
ser.Sync(nameof(lenctr_en), ref lenctr_en);
ser.Sync(nameof(shift_register), ref shift_register);
ser.Sync(nameof(timer_counter), ref timer_counter);
ser.Sync(nameof(sample), ref sample);
ser.Sync(nameof(env_output), ref env_output);
ser.Sync(nameof(env_start_flag), ref env_start_flag);
ser.Sync(nameof(env_divider), ref env_divider);
ser.Sync(nameof(env_counter), ref env_counter);
ser.Sync(nameof(noise_bit), ref noise_bit);
ser.EndSection();
}
public bool IsLenCntNonZero() => len_cnt > 0;
public void WriteReg(int addr, byte val)
{
switch (addr)
{
case 0:
env_cnt_value = val & 0xF;
env_constant = (val >> 4) & 1;
// we want to delay a halt until after a length clock if they happen on the same cycle
if (env_loop==0 && ((val >> 5) & 1)==1)
{
len_halt = true;
}
env_loop = (val >> 5) & 1;
break;
case 1:
break;
case 2:
period_cnt = NOISE_TABLE[val & 0xF];
mode_cnt = (val >> 7) & 1;
// Console.WriteLine("noise period: {0}, vol: {1}", (val & 0xF), env_cnt_value);
break;
case 3:
if (apu.len_clock_active)
{
if (len_cnt == 0)
{
len_cnt = LENGTH_TABLE[(val >> 3) & 0x1F] + 1;
}
}
else
{
len_cnt = LENGTH_TABLE[(val >> 3) & 0x1F];
}
set_lenctr_en(lenctr_en);
env_start_flag = 1;
break;
}
}
public void set_lenctr_en(int value)
{
lenctr_en = value;
// Console.WriteLine("noise lenctr_en: " + lenctr_en);
// if the length counter is not enabled, then we must disable the length system in this way
if (lenctr_en == 0) len_cnt = 0;
}
public void clock_env()
{
if (env_start_flag == 1)
{
env_start_flag = 0;
env_divider = (env_cnt_value + 1);
env_counter = 15;
}
else
{
if (env_divider != 0) env_divider--;
if (env_divider == 0)
{
env_divider = (env_cnt_value + 1);
if (env_counter == 0)
{
if (env_loop == 1)
{
env_counter = 15;
}
}
else env_counter--;
}
}
}
public void clock_length_and_sweep()
{
if (len_cnt > 0 && (env_loop == 0 || len_halt))
len_cnt--;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Run()
{
if (env_constant == 1)
env_output = env_cnt_value;
else env_output = env_counter;
if (timer_counter > 0) timer_counter--;
if (timer_counter == 0 && period_cnt != 0)
{
// reload timer
timer_counter = period_cnt;
int feedback_bit;
if (mode_cnt == 1) feedback_bit = (shift_register >> 6) & 1;
else feedback_bit = (shift_register >> 1) & 1;
int feedback = feedback_bit ^ (shift_register & 1);
shift_register >>= 1;
shift_register &= ~(1 << 14);
shift_register |= (feedback << 14);
noise_bit = (shift_register & 1) != 0;
}
int newsample;
if (len_cnt == 0) newsample = 0;
else if (noise_bit) newsample = env_output; // switched, was 0?
else newsample = 0;
if (newsample != sample)
{
apu.recalculate = true;
sample = newsample;
}
}
}
public sealed class TriangleUnit
{
// reg0
private int linear_counter_reload, control_flag;
// reg1 (n/a)
// reg2/3
private int timer_cnt, reload_flag, len_cnt;
public bool halt_2;
// misc..
private int lenctr_en;
private int linear_counter, timer, timer_cnt_reload;
private int seq = 0;
public int sample;
private readonly APU apu;
public TriangleUnit(APU apu) { this.apu = apu; }
public void SyncState(Serializer ser)
{
ser.BeginSection("Triangle");
ser.Sync(nameof(linear_counter_reload), ref linear_counter_reload);
ser.Sync(nameof(control_flag), ref control_flag);
ser.Sync(nameof(timer_cnt), ref timer_cnt);
ser.Sync(nameof(reload_flag), ref reload_flag);
ser.Sync(nameof(len_cnt), ref len_cnt);
ser.Sync(nameof(lenctr_en), ref lenctr_en);
ser.Sync(nameof(linear_counter), ref linear_counter);
ser.Sync(nameof(timer), ref timer);
ser.Sync(nameof(timer_cnt_reload), ref timer_cnt_reload);
ser.Sync(nameof(seq), ref seq);
ser.Sync(nameof(sample), ref sample);
ser.EndSection();
}
public bool IsLenCntNonZero() { return len_cnt > 0; }
public void set_lenctr_en(int value)
{
lenctr_en = value;
// if the length counter is not enabled, then we must disable the length system in this way
if (lenctr_en == 0) len_cnt = 0;
}
public void WriteReg(int addr, byte val)
{
// Console.WriteLine("tri writes addr={0}, val={1:x2}", addr, val);
switch (addr)
{
case 0:
linear_counter_reload = (val & 0x7F);
control_flag = (val >> 7) & 1;
break;
case 1: break;
case 2:
timer_cnt = (timer_cnt & ~0xFF) | val;
timer_cnt_reload = timer_cnt + 1;
break;
case 3:
timer_cnt = (timer_cnt & 0xFF) | ((val & 0x7) << 8);
timer_cnt_reload = timer_cnt + 1;
if (apu.len_clock_active)
{
if (len_cnt == 0)
{
len_cnt = LENGTH_TABLE[(val >> 3) & 0x1F] + 1;
}
}
else
{
len_cnt = LENGTH_TABLE[(val >> 3) & 0x1F];
}
reload_flag = 1;
// allow the lenctr_en to kill the len_cnt
set_lenctr_en(lenctr_en);
break;
}
// Console.WriteLine("tri timer_reload_value: {0}", timer_cnt_reload);
}
public bool Debug_IsSilenced
{
get
{
bool en = len_cnt != 0 && linear_counter != 0;
return !en;
}
}
public int Debug_PeriodValue => timer_cnt;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Run()
{
// when clocked by timer, seq steps forward
// except when linear counter or length counter is 0
bool en = len_cnt != 0 && linear_counter != 0;
bool do_clock = false;
if (timer > 0) timer--;
if (timer == 0)
{
do_clock = true;
timer = timer_cnt_reload;
}
if (en && do_clock)
{
int newsample;
seq = (seq + 1) & 0x1F;
newsample = TRIANGLE_TABLE[seq];
// special hack: frequently, games will use the maximum frequency triangle in order to mute it
// apparently this results in the DAC for the triangle wave outputting a steady level at about 7.5
// so we'll emulate it at the digital level
if (timer_cnt_reload == 1) newsample = 8;
if (newsample != sample)
{
apu.recalculate = true;
sample = newsample;
}
}
}
public void clock_length_and_sweep()
{
// env_loopdoubles as "halt length counter"
if (len_cnt > 0 && control_flag == 0)
len_cnt--;
}
public void clock_linear_counter()
{
//Console.WriteLine("linear_counter: {0}", linear_counter);
if (reload_flag == 1)
{
linear_counter = linear_counter_reload;
}
else if (linear_counter != 0)
{
linear_counter--;
}
if (control_flag == 0) { reload_flag = 0; }
}
} // class TriangleUnit
public sealed class DMCUnit
{
private readonly APU apu;
private readonly NES nes;
private readonly int[] DMC_RATE;
public DMCUnit(APU apu, bool pal)
{
this.apu = apu;
nes = apu.nes;
out_silence = true;
DMC_RATE = pal ? DMC_RATE_PAL : DMC_RATE_NTSC;
timer_reload = DMC_RATE[0];
timer = 1020; // confirmed in VisualNES, on console it seems the APU runs a couple cycles before CPU exits reset
sample_buffer_filled = false;
out_deltacounter = 64;
out_bits_remaining = 7; //confirmed in VisualNES
user_address = 0xC000;
sample_address = 0xC000;
user_length = 1;
}
public bool irq_enabled;
public bool loop_flag;
public int timer_reload;
// dmc delay per visual 2a03
public int delay;
// this timer never stops, ever, so it is convenient to use for even/odd timing used elsewhere
public int timer;
public int user_address;
public uint user_length, sample_length;
public int sample_address, sample_buffer;
public bool sample_buffer_filled;
public int out_shift, out_bits_remaining, out_deltacounter;
public bool out_silence;
// happens when buffer is filled and emptied at the same time
public bool fill_glitch;
// happens when a write triggered refill that sets length to zero happens too close to an automatic DMA
// (causes 1-cycle blips in dmc_dma_start_test_v2)
public bool fill_glitch_2;
public bool fill_glitch_2_end;
public bool pending_disable;
public bool timer_just_reloaded;
public int sample => out_deltacounter /* - 64*/;
public void SyncState(Serializer ser)
{
ser.BeginSection("DMC");
ser.Sync(nameof(irq_enabled), ref irq_enabled);
ser.Sync(nameof(loop_flag), ref loop_flag);
ser.Sync(nameof(timer_reload), ref timer_reload);
ser.Sync(nameof(timer), ref timer);
ser.Sync(nameof(user_address), ref user_address);
ser.Sync(nameof(user_length), ref user_length);
ser.Sync(nameof(sample_address), ref sample_address);
ser.Sync(nameof(sample_length), ref sample_length);
ser.Sync(nameof(sample_buffer), ref sample_buffer);
ser.Sync(nameof(sample_buffer_filled), ref sample_buffer_filled);
ser.Sync(nameof(out_shift), ref out_shift);
ser.Sync(nameof(out_bits_remaining), ref out_bits_remaining);
ser.Sync(nameof(out_deltacounter), ref out_deltacounter);
ser.Sync(nameof(out_silence), ref out_silence);
ser.Sync(nameof(fill_glitch), ref fill_glitch);
ser.Sync(nameof(fill_glitch_2), ref fill_glitch_2);
ser.Sync(nameof(fill_glitch_2_end), ref fill_glitch_2_end);
ser.Sync(nameof(timer_just_reloaded), ref timer_just_reloaded);
ser.Sync(nameof(pending_disable), ref pending_disable);
ser.Sync(nameof(delay), ref delay);
ser.EndSection();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Run()
{
timer_just_reloaded = false;
if (timer > 0) timer--;
if (timer == 0)
{
timer = timer_reload;
Clock();
timer_just_reloaded = true;
}
// Any time the sample buffer is in an empty state and bytes remaining is not zero, the following occur:
// also note that the halt for DMC DMA occurs on APU cycles only (hence the timer check)
if (!sample_buffer_filled && ((sample_length > 0) || fill_glitch_2) && (apu.dmc_dma_countdown == -1) && (delay == 0))
{
if (!fill_glitch)
{
if (!apu.call_from_write)
{
// when called due to empty bueffer while DMC running, there is no delay
nes.cpu.RDY = false;
nes.dmc_dma_exec = true;
if (fill_glitch_2)
{
// this will only run for one cycle and not actually run a DMA
//Console.WriteLine("fill glitch 2");
apu.dmc_dma_countdown = -2;
apu.DMC_RDY_check = -2;
fill_glitch_2_end = true;
}
else
{
apu.dmc_dma_countdown = 3;
apu.DMC_RDY_check = 2;
}
}
else
{
// when called from write, either a 2 or 3 cycle delay in activation.
if (timer % 2 == 0)
{
delay = 3;
}
else
{
delay = 2;
}
}
}
else
{
// if refill and empty happen simultaneously, do not do another refill and act as though the sample buffer was filled
//Console.WriteLine("fill glitch");
sample_buffer_filled = true;
fill_glitch = false;
}
}
// VisualNES and test roms verify that DMC DMA is 1 cycle shorter for calls from writes
// however, if the third cycle lands on a write, there is a 2 cycle delay even if the instruction only has a single write
// therefore, the RDY_check is 2 in both cases.
if (delay != 0)
{
delay--;
if (delay == 0)
{
apu.dmc_dma_countdown = 3;
apu.DMC_RDY_check = 2;
apu.call_from_write = false;
}
}
}
private void Clock()
{
// If the silence flag is clear, bit 0 of the shift register is applied to the counter as follows:
// if bit 0 is clear and the delta-counter is greater than 1, the counter is decremented by 2;
// otherwise, if bit 0 is set and the delta-counter is less than 126, the counter is incremented by 2
if (!out_silence)
{
// apply current sample bit to delta counter
if (out_shift.Bit(0))
{
if (out_deltacounter < 126)
out_deltacounter += 2;
}
else
{
if (out_deltacounter > 1)
out_deltacounter -= 2;
}
// Console.WriteLine("dmc out sample: {0}", out_deltacounter);
apu.recalculate = true;
}
// The right shift register is clocked.
out_shift >>= 1;
// The bits-remaining counter is decremented. If it becomes zero, a new cycle is started.
if (out_bits_remaining == 0)
{
// The bits-remaining counter is loaded with 8.
out_bits_remaining = 7;
// If the sample buffer is empty then the silence flag is set
if (!sample_buffer_filled)
{
out_silence = true;
}
else
// otherwise, the silence flag is cleared and the sample buffer is emptied into the shift register.
{
out_silence = false;
out_shift = sample_buffer;
sample_buffer_filled = false;
}
}
else out_bits_remaining--;
}
public void set_lenctr_en(bool en)
{
if(!en)
{
// in these cases, the disable happens right as the reload begins, it is cancelled similar to a write triggered reload
// cancelling an automatic reload, and has the same timing (still uses fill_glitch_2)
if (((timer == 3) || (timer == 2)) && (out_bits_remaining == 0) && (sample_length != 0))
{
//Console.WriteLine("glitch 3 " + timer);
sample_length = 0;
fill_glitch_2 = true;
apu.dmc_irq = false;
apu.SyncIRQ();
return;
}
// in these cases the disable happens too late and the reload (andpotential IRQ) still happen
if ((timer == 1) && (out_bits_remaining == 0) && (sample_length != 0))
{
//Console.WriteLine("glitch 4 " + timer);
pending_disable = true;
apu.dmc_irq = false;
apu.SyncIRQ();
return;
}
// if a fetch / reload is in progress, writing here as no immediate effect
// but it seems IRQs can be cancelled after the fetch before IRQ
if ((apu.dmc_dma_countdown > 0) || (delay != 0) || (apu.dmc_reload_countdown!= 0))
{
if (apu.dmc_reload_countdown != 0) { apu.dmc_irq_glitch = true; }
pending_disable = true;
}
else
{
sample_length = 0;
}
}
else
{
// only start playback if playback is stopped
// Console.Write(sample_length); Console.Write(" "); Console.Write(sample_buffer_filled); Console.Write(" "); Console.Write(apu.dmc_irq); Console.Write("\n");
if (sample_length == 0)
{
sample_address = user_address;
sample_length = user_length;
}
if (!sample_buffer_filled)
{
// apparently the dmc is different if called from a cpu write, let's try
apu.call_from_write = true;
}
}
// irq is acknowledged or sure to be clear, in either case
apu.dmc_irq = false;
apu.SyncIRQ();
}
public bool IsLenCntNonZero()
{
return sample_length != 0;
}
public void WriteReg(int addr, byte val)
{
// Console.WriteLine("DMC writes addr={0}, val={1:x2}", addr, val);
switch (addr)
{
case 0:
irq_enabled = val.Bit(7);
loop_flag = val.Bit(6);
timer_reload = DMC_RATE[val & 0xF];
if (!irq_enabled) apu.dmc_irq = false;
// apu.dmc_irq = false;
apu.SyncIRQ();
break;
case 1:
out_deltacounter = val & 0x7F;
// apu.nes.LogLine("~~ out_deltacounter set to {0}", out_deltacounter);
apu.recalculate = true;
break;
case 2:
user_address = 0xC000 | (val << 6);
break;
case 3:
user_length = ((uint)val << 4) + 1;
break;
}
}
public void Fetch()
{
if (sample_length != 0)
{
nes.dmc_dma_controller_conflict = true;
sample_buffer = apu.nes.ReadMemory((ushort) sample_address);
nes.dmc_dma_controller_conflict = false;
sample_buffer_filled = true;
if (nes.cpu.address_bus >= 0x4000 && nes.cpu.address_bus <= 0x401F)
{
if ((sample_address & 0x1F) == 0x15)
{
nes.DB = (byte)sample_buffer;
}
else if ((sample_address & 0x1F) == 0x16 || (sample_address & 0x1F) == 0x4017)
{
nes.DB = (byte) ((sample_buffer & 0xE0) | (nes.DB & 0x1F)); // The bus conflict leaves the open bus bits of the controller filled with the bits from the sample buffer.
// NOTE: When reading a controller port, different console revisions have different open bus bits.
}
}
sample_address = (ushort) (sample_address + 1);
//sample address wraps to 0x8000, even though this cannot be reached by write to address reg
if (sample_address == 0) { sample_address = 0x8000; }
// Console.WriteLine(sample_length);
// Console.WriteLine(user_length);
apu.dmc_reload_countdown = 3;
}
// Console.WriteLine("fetching dmc byte: {0:X2}", sample_buffer);
}
}
public void SyncState(Serializer ser)
{
ser.Sync(nameof(irq_pending), ref irq_pending);
ser.Sync(nameof(dmc_irq), ref dmc_irq);
ser.Sync(nameof(dmc_irq_glitch), ref dmc_irq_glitch);
ser.Sync(nameof(dmc_reload_countdown), ref dmc_reload_countdown);
ser.Sync(nameof(pending_reg), ref pending_reg);
ser.Sync(nameof(pending_val), ref pending_val);
ser.Sync(nameof(sequencer_counter), ref sequencer_counter);
ser.Sync(nameof(sequencer_step), ref sequencer_step);
ser.Sync(nameof(sequencer_mode), ref sequencer_mode);
ser.Sync(nameof(sequencer_irq_inhibit), ref sequencer_irq_inhibit);
ser.Sync(nameof(sequencer_irq), ref sequencer_irq);
ser.Sync(nameof(sequence_reset_pending), ref sequence_reset_pending);
ser.Sync(nameof(sequencer_irq_clear_pending), ref sequencer_irq_clear_pending);
ser.Sync(nameof(sequencer_irq_assert), ref sequencer_irq_assert);