-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathsound.c
1910 lines (1554 loc) · 66.5 KB
/
sound.c
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
/*
Hatari - sound.c
This file is distributed under the GNU General Public License, version 2
or at your option any later version. Read the file gpl.txt for details.
This is where we emulate the YM2149. To obtain cycle-accurate timing we store
the current cycle time and this is incremented during each instruction.
When a write occurs in the PSG registers we take the difference in time and
generate this many samples using the previous register data.
Now we begin again from this point. To make sure we always have 1/50th of
samples we update the buffer generation every 1/50th second, just in case no
write took place on the PSG.
NOTE: If the emulator runs slower than 50fps it cannot update the buffers,
but the sound thread still needs some data to play to prevent a 'pop'. The
ONLY feasible solution is to play the same buffer again. I have tried all
kinds of methods to play the sound 'slower', but this produces un-even timing
in the sound and it simply doesn't work. If the emulator cannot keep the
speed, users will have to turn off the sound - that's it.
The new version of the sound core uses/used some code/ideas from the following GPL projects :
- tone and noise steps computations are from StSound 1.2 by Arnaud Carré (Leonard/Oxygene)
(not used since Hatari 1.1.0)
- 5 bits volume table and 16*16*16 combinations of all volume are from Sc68 by Benjamin Gerard
- 4 bits to 5 bits volume interpolation from 16*16*16 to 32*32*32 from YM blep synthesis by Antti Lankila
Special case for per==0 : as measured on a real STF, when tone/noise/env's per==0, we get
the same sound output as when per==1.
NOTE [NP] : As of June 2017, Hatari uses a completely new/rewritten cycle exact YM2149 emulation.
Instead of updating YM2149's state on every host call (for example at 44.1 kHz), YM2149's state is now updated
at 250 kHz (which is the base frequency used by real YM2149 to handle its various counters) and
then downsampled to the host frequency.
This is required to perfectly emulate transitions when the periods for tone/noise/envelope
are changed and whether a new phase should be started or the current phase should be extended.
Using a custom program on a real STF, it's possible to change YM2149 registers at very precise
cycles during various sound phases and to record the STF sound output as a wav file on a modern PC.
The wav file can then be studied (using Audacity for example) to precisely see how and when
a change in a register affects the sound output.
Based on these measures I made, the following behaviours of the YM2149 were confirmed :
- unlike what it written in Yamaha documentation, each period counter doesn't count
from 'period' down to 0, but count up from 0 until the counter reaches 'period'.
The counter is incremented at 250 kHz, with the following pseudo code :
tone_counter = tone_counter+1
if ( tone_counter >= tone_period )
tone_counter = 0
invert tone output
This means that when a new value is written in tone period A for example, the current phase
will be either extended (if new_period_A > tone_counter_A) or a new phase will be
started immediately (if new_period_A < tone_counter_A).
- noise counter is incremented twice slower than tone counter ; for example with period=31
a tone phase will remain up or down for ~0.0001 sec, but a noise phase will remain up or down
for ~0.0002 sec. This is equivalent to incrementing noise counter at 125 kHz instead
of 250 kHz like tone counter.
- it is known that when writing to the env wave register (reg 13) the current envelope
is restarted from the start (this is often used in so called sync-buzzer effects).
But the measures on the resulting wav file of the YM2149 also show that the current
envelope phase is restarted at the same time that envelope wave register is written to.
- The various counters for tone/noise/env all give the same result when period=1 and when period=0.
For noise and envelope, this can be seen when sampling the sound output as above
For tone, this was also measured using a logic analyser (to sample at much higher rate than 250 kHz)
- 2 voices playing tones at the same frequency and at the same volume can cancel each other partially
or completely, giving no sound output at all.
This happens when the phase for one voice is "up" while the phase for the other voice
is "down", then on the next phase inversion, 1st voice will be "down" and 2nd voice will be "up".
In such cases, the sum of these 2 tone waveforms will give a constant output signal, producing no sound at all.
If both voices are not fully in opposite phase, the resulting sound will vary depending
on how much phases are in common and how much they "cancel" each other
*/
/* 2008/05/05 [NP] Fix case where period is 0 for noise, sound or envelope. */
/* In that case, a real ST sounds as if period was in fact 1. */
/* (fix buggy sound replay in ESwat that set volume<0 and trigger */
/* a badly initialised envelope with envper=0). */
/* 2008/07/27 [NP] Better separation between accesses to the YM hardware registers */
/* and the sound rendering routines. Use Sound_WriteReg() to pass */
/* all writes to the sound rendering functions. This allows to */
/* have sound.c independent of psg.c (to ease replacement of */
/* sound.c by another rendering method). */
/* 2008/08/02 [NP] Initial convert of Ym2149Ex.cpp from C++ to C. */
/* Remove unused part of the code (StSound specific). */
/* 2008/08/09 [NP] Complete integration of StSound routines into sound.c */
/* Set EnvPer=3 if EnvPer<3 (ESwat buggy replay). */
/* 2008/08/13 [NP] StSound was generating samples in the range 0-32767, instead */
/* of really signed samples between -32768 and 32767, which could */
/* give incorrect results in many case. */
/* 2008/09/06 [NP] Use sc68 volumes table for a more accurate mixing of the voices */
/* All volumes are converted to 5 bits and the table contains */
/* 32*32*32 values. Samples are signed and centered to get the */
/* biggest amplitude possible. */
/* Faster mixing routines for tone+volume+envelope (don't use */
/* StSound's version anymore, it gave problem with some GCC). */
/* 2008/09/17 [NP] Add ym_normalise_5bit_table to normalise the 32*32*32 table and */
/* to optionally center 16 bit signed sample. */
/* Possibility to mix volumes using a table measured on ST or a */
/* linear mean of the 3 channels' volume. */
/* Default mixing set to YM_LINEAR_MIXING. */
/* 2008/10/14 [NP] Full support for 5 bits volumes : envelopes are generated with */
/* 32 volumes per pattern as on a real YM-2149. Fixed volumes */
/* on 4 bits are converted to their 5 bits equivalent. This should */
/* give the maximum accuracy possible when computing volumes. */
/* New version of Ym2149_EnvStepCompute to handle 5 bits volumes. */
/* Function YM2149_EnvBuild to compute the 96 volumes that define */
/* a single envelope (32 initial volumes, then 64 repeated values).*/
/* 2008/10/26 [NP] Correctly save/restore all necessary variables in */
/* Sound_MemorySnapShot_Capture. */
/* 2008/11/23 [NP] Clean source, remove old sound core. */
/* 2011/11/03 [DS] Stereo DC filtering which accounts for DMA sound. */
/* 2017/06/xx [NP] New cycle exact emulation method, all counters are incremented */
/* using a simulated freq of 250 kHz. Some undocumented cases */
/* where also measured on real STF to improve accuracy. */
/* 2019/09/09 [NP] Add YM2149_Next_Resample_Weighted_Average_N for better */
/* downsampling of the internal 250 kHz sound buffer. */
/* 2021/07/23 [NP] Default to 250 kHz cycle accurate emulation and remove older */
/* rendering and associated functions/variables. */
const char Sound_fileid[] = "Hatari sound.c";
#include "main.h"
#include "audio.h"
#include "cycles.h"
#include "m68000.h"
#include "configuration.h"
#include "dmaSnd.h"
#include "crossbar.h"
#include "file.h"
#include "cycInt.h"
#include "log.h"
#include "memorySnapShot.h"
#include "psg.h"
#include "sound.h"
#include "screen.h"
#include "video.h"
#include "wavFormat.h"
#include "ymFormat.h"
#include "avi_record.h"
#include "clocks_timings.h"
/*--------------------------------------------------------------*/
/* Definition of the possible envelopes shapes (using 5 bits) */
/*--------------------------------------------------------------*/
#define ENV_GODOWN 0 /* 31 -> 0 */
#define ENV_GOUP 1 /* 0 -> 31 */
#define ENV_DOWN 2 /* 0 -> 0 */
#define ENV_UP 3 /* 31 -> 31 */
/* To generate an envelope, we first use block 0, then we repeat blocks 1 and 2 */
static const int YmEnvDef[ 16 ][ 3 ] = {
{ ENV_GODOWN, ENV_DOWN, ENV_DOWN } , /* 0 \___ */
{ ENV_GODOWN, ENV_DOWN, ENV_DOWN } , /* 1 \___ */
{ ENV_GODOWN, ENV_DOWN, ENV_DOWN } , /* 2 \___ */
{ ENV_GODOWN, ENV_DOWN, ENV_DOWN } , /* 3 \___ */
{ ENV_GOUP, ENV_DOWN, ENV_DOWN } , /* 4 /___ */
{ ENV_GOUP, ENV_DOWN, ENV_DOWN } , /* 5 /___ */
{ ENV_GOUP, ENV_DOWN, ENV_DOWN } , /* 6 /___ */
{ ENV_GOUP, ENV_DOWN, ENV_DOWN } , /* 7 /___ */
{ ENV_GODOWN, ENV_GODOWN, ENV_GODOWN } , /* 8 \\\\ */
{ ENV_GODOWN, ENV_DOWN, ENV_DOWN } , /* 9 \___ */
{ ENV_GODOWN, ENV_GOUP, ENV_GODOWN } , /* A \/\/ */
{ ENV_GODOWN, ENV_UP, ENV_UP } , /* B \--- */
{ ENV_GOUP, ENV_GOUP, ENV_GOUP } , /* C //// */
{ ENV_GOUP, ENV_UP, ENV_UP } , /* D /--- */
{ ENV_GOUP, ENV_GODOWN, ENV_GOUP } , /* E /\/\ */
{ ENV_GOUP, ENV_DOWN, ENV_DOWN } , /* F /___ */
};
/* Buffer to store the 16 envelopes built from YmEnvDef */
static ymu16 YmEnvWaves[ 16 ][ 32 * 3 ]; /* 16 envelopes with 3 blocks of 32 volumes */
/*--------------------------------------------------------------*/
/* Definition of the volumes tables (using 5 bits) and of the */
/* mixing parameters for the 3 voices. */
/*--------------------------------------------------------------*/
/* Table of unsigned 5 bit D/A output level for 1 channel as measured on a real ST (expanded from 4 bits to 5 bits) */
/* Vol 0 should be 310 when measuread as a voltage, but we set it to 0 in order to have a volume=0 matching */
/* the 0 level of a 16 bits unsigned sample (no sound output) */
static const ymu16 ymout1c5bit[ 32 ] =
{
0 /*310*/, 369, 438, 521, 619, 735, 874, 1039,
1234, 1467, 1744, 2072, 2463, 2927, 3479, 4135,
4914, 5841, 6942, 8250, 9806,11654,13851,16462,
19565,23253,27636,32845,39037,46395,55141,65535
};
/* Convert a constant 4 bits volume to the internal 5 bits value : */
/* volume5=volume4*2+1, except for volumes 0 and 1 which remain 0 and 1, */
/* in order to map [0,15] into [0,31] (O must remain 0, and 15 must give 31) */
static const ymu16 YmVolume4to5[ 16 ] = { 0,1,5,7,9,11,13,15,17,19,21,23,25,27,29,31 };
/* Table of unsigned 4 bit D/A output level for 3 channels as measured on a real ST */
static ymu16 volumetable_original[16][16][16] =
#include "ym2149_fixed_vol.h"
/* Corresponding table interpolated to 5 bit D/A output level (16 bits unsigned) */
static ymu16 ymout5_u16[32][32][32];
/* Same table, after conversion to signed results (same pointer, with different type) */
static yms16 *ymout5 = (yms16 *)ymout5_u16;
/*--------------------------------------------------------------*/
/* Other constants / macros */
/*--------------------------------------------------------------*/
/* Number of generated samples per frame (eg. 44Khz=882) */
#define SAMPLES_PER_FRAME (nAudioFrequency/nScreenRefreshRate)
/* Current sound replay freq (usually 44100 Hz) */
#define YM_REPLAY_FREQ nAudioFrequency
/* YM-2149 clock on all Atari models is 2 MHz (CPU freq / 4) */
/* Period counters for tone/noise/env are based on YM clock / 8 = 250 kHz */
#define YM_ATARI_CLOCK (MachineClocks.YM_Freq)
#define YM_ATARI_CLOCK_COUNTER (YM_ATARI_CLOCK / 8)
/* Merge/read the 3 volumes in a single integer (5 bits per volume) */
#define YM_MERGE_VOICE(C,B,A) ( (C)<<10 | (B)<<5 | A )
#define YM_MASK_1VOICE 0x1f
#define YM_MASK_A 0x1f
#define YM_MASK_B (0x1f<<5)
#define YM_MASK_C (0x1f<<10)
/* Constants for YM2149_Normalise_5bit_Table */
#define YM_OUTPUT_LEVEL 0x7fff /* amplitude of the final signal (0..65535 if centered, 0..32767 if not) */
#define YM_OUTPUT_CENTERED false
/*--------------------------------------------------------------*/
/* Variables for the YM2149 emulator (need to be saved and */
/* restored in memory snapshots) */
/*--------------------------------------------------------------*/
/* Uncomment next line to write raw 250 kHz samples to a file 'hatari_250.wav' */
//#define YM_250_DEBUG
/* For our internal computations to convert down/up square wave signals into 0-31 volume, */
/* we consider that 'up' is 31 and 'down' is 0 */
#define YM_SQUARE_UP 0x1f
#define YM_SQUARE_DOWN 0x00
static ymu16 ToneA_per , ToneA_count , ToneA_val;
static ymu16 ToneB_per , ToneB_count , ToneB_val;
static ymu16 ToneC_per , ToneC_count , ToneC_val;
static ymu16 Noise_per , Noise_count , Noise_val;
static ymu16 Env_per , Env_count;
static ymu32 Env_pos;
static int Env_shape;
static ymu32 mixerTA , mixerTB , mixerTC;
static ymu32 mixerNA , mixerNB , mixerNC;
static ymu32 RndRack; /* current random seed */
static ymu16 EnvMask3Voices = 0; /* mask is 0x1f for voices having an active envelope */
static ymu16 Vol3Voices = 0; /* volume 0-0x1f for voices having a constant volume */
/* volume is set to 0 if voice has an envelope in EnvMask3Voices */
/* Global variables that can be changed/read from other parts of Hatari */
uint8_t SoundRegs[ 14 ];
int YmVolumeMixing = YM_TABLE_MIXING;
int YM2149_LPF_Filter = YM2149_LPF_FILTER_PWM;
// int YM2149_LPF_Filter = YM2149_LPF_FILTER_NONE; /* For debug */
int YM2149_HPF_Filter = YM2149_HPF_FILTER_IIR;
// int YM2149_HPF_Filter = YM2149_HPF_FILTER_NONE; /* For debug */
//int YM2149_Resample_Method = YM2149_RESAMPLE_METHOD_NEAREST;
//int YM2149_Resample_Method = YM2149_RESAMPLE_METHOD_WEIGHTED_AVERAGE_2;
int YM2149_Resample_Method = YM2149_RESAMPLE_METHOD_WEIGHTED_AVERAGE_N;
bool bEnvelopeFreqFlag; /* Cleared each frame for YM saving */
int16_t AudioMixBuffer[AUDIOMIXBUFFER_SIZE][2]; /* Ring buffer to store mixed audio output (YM2149, DMA sound, ...) */
int AudioMixBuffer_pos_write; /* Current writing position into above buffer */
int AudioMixBuffer_pos_read; /* Current reading position into above buffer */
int nGeneratedSamples; /* Generated samples since audio buffer update */
static int AudioMixBuffer_pos_write_avi; /* Current working index to save an AVI audio frame */
bool Sound_BufferIndexNeedReset = false;
#define YM_BUFFER_250_SIZE 32768 /* Size to store YM samples generated at 250 kHz (must be a power of 2) */
/* As we fill YM_Buffer_250[] at least once per VBL (min freq = 50 Hz) */
/* we can have 5000 YM samples per VBL. We use a slightly larger buffer */
/* to have some kind of double buffering */
#define YM_BUFFER_250_SIZE_MASK ( YM_BUFFER_250_SIZE - 1 ) /* To limit index values inside the ring buffer */
ymsample YM_Buffer_250[ YM_BUFFER_250_SIZE ]; /* Ring buffer to store YM samples */
static int YM_Buffer_250_pos_write; /* Current writing position into above buffer */
static int YM_Buffer_250_pos_read; /* Current reading position into above buffer */
static uint64_t YM2149_Clock_250; /* 250 kHz counter */
static uint64_t YM2149_Clock_250_CpuClock; /* Corresponding value of CyclesGlobalClockCounter at the time YM2149_Clock_250 was updated */
/* Some variables used for stats / debug */
#define SOUND_STATS_SIZE 60
static int Sound_Stats_Array[ SOUND_STATS_SIZE ];
static int Sound_Stats_Index = 0;
static int Sound_Stats_SamplePerVBL;
static CLOCKS_CYCLES_STRUCT YM2149_ConvertCycles_250;
/*--------------------------------------------------------------*/
/* Local functions prototypes */
/*--------------------------------------------------------------*/
static ymsample LowPassFilter (ymsample x0);
static ymsample PWMaliasFilter (ymsample x0);
static void interpolate_volumetable (ymu16 volumetable[32][32][32]);
static void YM2149_BuildModelVolumeTable(ymu16 volumetable[32][32][32]);
static void YM2149_BuildLinearVolumeTable(ymu16 volumetable[32][32][32]);
static void YM2149_Normalise_5bit_Table(ymu16 *in_5bit , yms16 *out_5bit, unsigned int Level, bool DoCenter);
static void YM2149_EnvBuild (void);
static void Ym2149_BuildVolumeTable (void);
static void YM2149_UpdateClock_250 ( uint64_t CpuClock );
static void Ym2149_Init (void);
static void Ym2149_Reset (void);
static ymu32 YM2149_RndCompute (void);
static ymu16 YM2149_TonePer (ymu8 rHigh , ymu8 rLow);
static ymu16 YM2149_NoisePer (ymu8 rNoise);
static ymu16 YM2149_EnvPer (ymu8 rHigh , ymu8 rLow);
static void YM2149_Run ( uint64_t CPU_Clock );
static int Sound_GenerateSamples ( uint64_t CPU_Clock);
static void YM2149_DoSamples_250 ( int SamplesToGenerate_250 );
#ifdef YM_250_DEBUG
static void YM2149_DoSamples_250_Debug ( int SamplesToGenerate , int pos );
#endif
/*--------------------------------------------------------------*/
/* DC Adjuster */
/*--------------------------------------------------------------*/
/**
* 6dB/octave first order HPF fc = (1.0-0.998)*44100/(2.0*pi)
* Z pole = 0.99804 --> FS = 44100 Hz : fc=13.7 Hz (11 Hz meas)
* a = (int32_t)(32768.0*(1.0 - pole)) : a = 64 !!!
* Input range: -32768 to 32767 Maximum step: +65536 or -65472
*/
ymsample Subsonic_IIR_HPF_Left(ymsample x0)
{
static yms32 x1 = 0, y1 = 0, y0 = 0;
if ( YM2149_HPF_Filter == YM2149_HPF_FILTER_NONE )
return x0;
y1 += ((x0 - x1)<<15) - (y0<<6); /* 64*y0 */
y0 = y1>>15;
x1 = x0;
return y0;
}
ymsample Subsonic_IIR_HPF_Right(ymsample x0)
{
static yms32 x1 = 0, y1 = 0, y0 = 0;
if ( YM2149_HPF_Filter == YM2149_HPF_FILTER_NONE )
return x0;
y1 += ((x0 - x1)<<15) - (y0<<6); /* 64*y0 */
y0 = y1>>15;
x1 = x0;
return y0;
}
/*--------------------------------------------------------------*/
/* Low Pass Filter routines. */
/*--------------------------------------------------------------*/
/**
* Get coefficients for different Fs (C10 is in ST only):
* Wc = 2*M_PI*4895.1;
* Fs = 44100;
* warp = Wc/tanf((Wc/2)/Fs);
* b = Wc/(warp+Wc);
* a = (Wc-warp)/(warp+Wc);
*
* #define B_z (yms32)( 0.2667*(1<<15))
* #define A_z (yms32)(-0.4667*(1<<15))
*
* y0 = (B_z*(x0 + x1) - A_z*y0) >> 15;
* x1 = x0;
*
* The Lowpass Filter formed by C10 = 0.1 uF
* and
* R8=1k // 1k*(65119-46602)/65119 // R9=10k // R10=5.1k //
* (R12=470)*(100=Q1_HFE) = 206.865 ohms when YM2149 is High
* and
* R8=1k // R9=10k // R10=5.1k // (R12=470)*(100=Q1_HFE)
* = 759.1 ohms when YM2149 is Low
* High corner is 1/(2*pi*(0.1*10e-6)*206.865) fc = 7693.7 Hz
* Low corner is 1/(2*pi*(0.1*10e-6)*795.1) fc = 2096.6 Hz
* Notes:
* - using STF reference designators R8 R9 R10 C10 (from dec 1986 schematics)
* - using corresponding numbers from psgstrep and psgquart
* - 65119 is the largest value in Paulo's psgstrep table
* - 46602 is the largest value in Paulo's psgquart table
* - this low pass filter uses the highest cutoff frequency
* on the STf (a slightly lower frequency is reasonable).
*
* A first order lowpass filter with a high cutoff frequency
* is used when the YM2149 pulls high, and a lowpass filter
* with a low cutoff frequency is used when R8 pulls low.
*/
static ymsample LowPassFilter(ymsample x0)
{
static yms32 y0 = 0, x1 = 0;
if (x0 >= y0)
/* YM Pull up: fc = 7586.1 Hz (44.1 KHz), fc = 8257.0 Hz (48 KHz) */
y0 = (3*(x0 + x1) + (y0<<1)) >> 3;
else
/* R8 Pull down: fc = 1992.0 Hz (44.1 KHz), fc = 2168.0 Hz (48 KHz) */
y0 = ((x0 + x1) + (6*y0)) >> 3;
x1 = x0;
return y0;
}
/**
* This piecewise selective filter works by filtering the falling
* edge of a sampled pulse-wave differently from the rising edge.
*
* Piecewise selective filtering is effective because harmonics on
* one part of a wave partially define harmonics on other portions.
*
* Piecewise selective filtering can efficiently reduce aliasing
* with minimal harmonic removal.
*
* I disclose this information into the public domain so that it
* cannot be patented. May 23 2012 David Savinkoff.
*/
static ymsample PWMaliasFilter(ymsample x0)
{
static yms32 y0 = 0, x1 = 0;
if (x0 >= y0)
/* YM Pull up */
y0 = x0;
else
/* R8 Pull down */
y0 = (3*(x0 + x1) + (y0<<1)) >> 3;
x1 = x0;
return y0;
}
/*--------------------------------------------------------------*/
/* Build the volume conversion table used to simulate the */
/* behaviour of DAC used with the YM2149 in the atari ST. */
/* The final 32*32*32 table is built using a 16*16*16 table */
/* of all possible fixed volume combinations on a ST. */
/*--------------------------------------------------------------*/
static void interpolate_volumetable(ymu16 volumetable[32][32][32])
{
int i, j, k;
for (i = 1; i < 32; i += 2) { /* Copy 16 Panels to make a Block */
for (j = 1; j < 32; j += 2) { /* Copy 16 Rows to make a Panel */
for (k = 1; k < 32; k += 2) { /* Copy 16 Elements to make a Row */
volumetable[i][j][k] = volumetable_original[(i-1)/2][(j-1)/2][(k-1)/2];
}
volumetable[i][j][0] = volumetable[i][j][1]; /* Move 0th Element */
volumetable[i][j][1] = volumetable[i][j][3]; /* Move 1st Element */
/* Interpolate 3rd Element */
volumetable[i][j][3] = (ymu16)(0.5 + sqrt((double)volumetable[i][j][1] * volumetable[i][j][5]));
for (k = 2; k < 32; k += 2) /* Interpolate Even Elements */
volumetable[i][j][k] = (ymu16)(0.5 + sqrt((double)volumetable[i][j][k-1] * volumetable[i][j][k+1]));
}
for (k = 0; k < 32; k++) {
volumetable[i][0][k] = volumetable[i][1][k]; /* Move 0th Row */
volumetable[i][1][k] = volumetable[i][3][k]; /* Move 1st Row */
/* Interpolate 3rd Row */
volumetable[i][3][k] = (ymu16)(0.5 + sqrt((double)volumetable[i][1][k] * volumetable[i][5][k]));
}
for (j = 2; j < 32; j += 2) /* Interpolate Even Rows */
for (k = 0; k < 32; k++)
volumetable[i][j][k] = (ymu16)(0.5 + sqrt((double)volumetable[i][j-1][k] * volumetable[i][j+1][k]));
}
for (j = 0; j < 32; j++)
for (k = 0; k < 32; k++) {
volumetable[0][j][k] = volumetable[1][j][k]; /* Move 0th Panel */
volumetable[1][j][k] = volumetable[3][j][k]; /* Move 1st Panel */
/* Interpolate 3rd Panel */
volumetable[3][j][k] = (ymu16)(0.5 + sqrt((double)volumetable[1][j][k] * volumetable[5][j][k]));
}
for (i = 2; i < 32; i += 2) /* Interpolate Even Panels */
for (j = 0; j < 32; j++) /* Interpolate Even Panels */
for (k = 0; k < 32; k++)
volumetable[i][j][k] = (ymu16)(0.5 + sqrt((double)volumetable[i-1][j][k] * volumetable[i+1][j][k]));
}
/*-----------------------------------------------------------------------*/
/**
* Build a linear version of the conversion table.
* We use the mean of the 3 volumes converted to 16 bit values
* (each value of ymout1c5bit is in [0,65535])
*/
static void YM2149_BuildLinearVolumeTable(ymu16 volumetable[32][32][32])
{
int i, j, k;
for (i = 0; i < 32; i++)
for (j = 0; j < 32; j++)
for (k = 0; k < 32; k++)
volumetable[i][j][k] = (ymu16)( ((ymu32)ymout1c5bit[i] + ymout1c5bit[j] + ymout1c5bit[k]) / 3);
}
/*-----------------------------------------------------------------------*/
/**
* Build a circuit analysed version of the conversion table.
* David Savinkoff designed this algorithm by analysing data
* measured by Paulo Simoes and Benjamin Gerard.
* The numbers are arrived at by assuming a current steering
* resistor ladder network and using the voltage divider rule.
*
* If one looks at the ST schematic of the YM2149, one sees
* three sound pins tied together and attached to a 1000 ohm
* resistor (1k) that has the other end grounded.
* The 1k resistor is also in parallel with a 0.1 microfarad
* capacitor (on the Atari ST, not STE or others). The voltage
* developed across the 1K resistor is the output voltage which
* I call Vout.
*
* The output of the YM2149 is modelled well as pullup resistors.
* Thus, the three sound pins are seen as three parallel
* computer-controlled, adjustable pull-up resistors.
* To emulate the output of the YM2149, one must determine the
* resistance values of the YM2149 relative to the 1k resistor,
* which is done by the 'math model'.
*
* The AC + DC math model is:
*
* (MaxVol*WARP) / (1.0 + 1.0/(conductance_[i]+conductance_[j]+conductance_[k]))
* or
* (MaxVol*WARP) / (1.0 + 1.0/( 1/Ra +1/Rb +1/Rc )) , Ra = channel A resistance
*
* Note that the first 1.0 in the formula represents the
* normalized 1k resistor (1.0 * 1000 ohms = 1k).
*
* The YM2149 DC component model represents the output voltage
* filtered of high frequency AC component, but DC component
* remains.
* The YM2149 DC component mode treats the voltage exactly as if
* it were low pass filtered. This is more than what is required
* to make 'quartet mode sound'. Simplicity leads to Generality!
*
* The DC component model model is:
*
* (MaxVol*WARP) / (2.0 + 1.0/( 1/Ra + 1/Rb + 1/Rc))
* or
* (MaxVol*WARP*0.5) / (1.0 + 0.5/( 1/Ra + 1/Rb + 1/Rc))
*
* Note that the 1.0 represents the normalized 1k resistor.
* 0.5 represents 50% duty cycle for the parallel resistors
* being summed (this effectively doubles the pull-up resistance).
*/
static void YM2149_BuildModelVolumeTable(ymu16 volumetable[32][32][32])
{
#define MaxVol 65535.0 /* Normal Mode Maximum value in table */
#define FOURTH2 1.19 /* Fourth root of two from YM2149 */
#define WARP 1.666666666666666667 /* measured as 1.65932 from 46602 */
double conductance;
double conductance_[32];
int i, j, k;
/**
* YM2149 and R8=1k follows (2^-1/4)^(n-31) better when 2 voices are
* summed (A+B or B+C or C+A) rather than individually (A or B or C):
* conductance = 2.0/3.0/(1.0-1.0/WARP)-2.0/3.0;
* When taken into consideration with three voices.
*
* Note that the YM2149 does not use laser trimmed resistances, thus
* has offsets that are added and/or multiplied with (2^-1/4)^(n-31).
*/
conductance = 2.0/3.0/(1.0-1.0/WARP)-2.0/3.0; /* conductance = 1.0 */
/**
* Because the YM current output (voltage source with series resistances)
* is connected to a grounded resistor to develop the output voltage
* (instead of a current to voltage converter), the output transfer
* function is not linear. Thus:
* 2.0*conductance_[n] = 1.0/(1.0-1.0/FOURTH2/(1.0/conductance + 1.0))-1.0;
*/
for (i = 31; i >= 1; i--)
{
conductance_[i] = conductance/2.0;
conductance = 1.0/(1.0-1.0/FOURTH2/(1.0/conductance + 1.0))-1.0;
}
conductance_[0] = 1.0e-8; /* Avoid divide by zero */
/**
* YM2149 AC + DC components model:
* (Note that Maxvol is 65119 in Simoes' table, 65535 in Gerard's)
*
* Sum the conductances as a function of a voltage divider:
* Vout=Vin*Rout/(Rout+Rin)
*/
for (i = 0; i < 32; i++)
for (j = 0; j < 32; j++)
for (k = 0; k < 32; k++)
{
volumetable[i][j][k] = (ymu16)(0.5+(MaxVol*WARP)/(1.0 +
1.0/(conductance_[i]+conductance_[j]+conductance_[k])));
}
/**
* YM2149 DC component model:
* R8=1k (pulldown) + YM//1K (pullup) with YM 50% duty PWM
* (Note that MaxVol is 46602 in Paulo Simoes Quartet mode table)
*
* for (i = 0; i < 32; i++)
* for (j = 0; j < 32; j++)
* for (k = 0; k < 32; k++)
* {
* volumetable[i][j][k] = (ymu16)(0.5+(MaxVol*WARP)/(1.0 +
* 2.0/(conductance_[i]+conductance_[j]+conductance_[k])));
* }
*/
}
/*-----------------------------------------------------------------------*/
/**
* Normalise and optionally center the volume table used to
* convert the 3 volumes to a final signed 16 bit sample.
* This allows to adapt the amplitude/volume of the samples and
* to convert unsigned values to signed values.
* - in_5bit contains 32*32*32 unsigned values in the range
* [0,65535].
* - out_5bit will contain signed values
* Possible values are :
* Level=65535 and DoCenter=TRUE -> [-32768,32767]
* Level=32767 and DoCenter=false -> [0,32767]
* Level=16383 and DoCenter=false -> [0,16383] (to avoid overflow with DMA sound on STe)
*/
static void YM2149_Normalise_5bit_Table(ymu16 *in_5bit , yms16 *out_5bit, unsigned int Level, bool DoCenter)
{
if ( Level )
{
int h;
int Max = in_5bit[0x7fff];
int Center = (Level+1)>>1;
//fprintf ( stderr , "level %d max %d center %d\n" , Level, Max, Center );
/* Change the amplitude of the signal to 'level' : [0,max] -> [0,level] */
/* Then optionally center the signal around Level/2 */
/* This means we go from sthg like [0,65535] to [-32768, 32767] if Level=65535 and DoCenter=TRUE */
for (h=0; h<32*32*32; h++)
{
int tmp = in_5bit[h], res;
res = tmp * Level / Max;
if ( DoCenter )
res -= Center;
out_5bit[h] = res;
//fprintf ( stderr , "h %d in %d out %d\n" , h , tmp , res );
}
}
}
/*-----------------------------------------------------------------------*/
/**
* Precompute all 16 possible envelopes.
* Each envelope is made of 3 blocks of 32 volumes.
*/
static void YM2149_EnvBuild ( void )
{
int env;
int block;
int vol=0 , inc=0;
int i;
for ( env=0 ; env<16 ; env++ ) /* 16 possible envelopes */
for ( block=0 ; block<3 ; block++ ) /* 3 blocks to define an envelope */
{
switch ( YmEnvDef[ env ][ block ] )
{
case ENV_GODOWN : vol=31 ; inc=-1 ; break;
case ENV_GOUP : vol=0 ; inc=1 ; break;
case ENV_DOWN : vol=0 ; inc=0 ; break;
case ENV_UP : vol=31 ; inc=0 ; break;
}
for ( i=0 ; i<32 ; i++ ) /* 32 volumes per block */
{
YmEnvWaves[ env ][ block*32 + i ] = YM_MERGE_VOICE ( vol , vol , vol );
vol += inc;
}
}
}
/*-----------------------------------------------------------------------*/
/**
* Depending on the YM mixing method, build the table used to convert
* the 3 YM volumes into a single sample.
*/
static void Ym2149_BuildVolumeTable(void)
{
/* Depending on the volume mixing method, we use a table based on real measures */
/* or a table based on a linear volume mixing. */
if ( YmVolumeMixing == YM_MODEL_MIXING )
YM2149_BuildModelVolumeTable(ymout5_u16); /* create 32*32*32 circuit analysed model of the volume table */
else if ( YmVolumeMixing == YM_TABLE_MIXING )
interpolate_volumetable(ymout5_u16); /* expand the 16*16*16 values in volumetable_original to 32*32*32 */
else
YM2149_BuildLinearVolumeTable(ymout5_u16); /* combine the 32 possible volumes */
/* Normalise/center the values (convert from u16 to s16) */
/* On STE/TT, we use YM_OUTPUT_LEVEL>>1 to avoid overflow with DMA sound */
if (Config_IsMachineSTE() || Config_IsMachineTT())
YM2149_Normalise_5bit_Table ( ymout5_u16[0][0] , ymout5 , (YM_OUTPUT_LEVEL>>1) , YM_OUTPUT_CENTERED );
else
YM2149_Normalise_5bit_Table ( ymout5_u16[0][0] , ymout5 , YM_OUTPUT_LEVEL , YM_OUTPUT_CENTERED );
}
/*-----------------------------------------------------------------------*/
/**
* Convert a CPU clock value (as in CyclesGlobalClockCounter)
* into a 250 kHz YM2149 clock.
*
* NOTE : we should not use this simple method :
* Clock_250 = CpuClock / ( 32 << nCpuFreqShift )
* because it won't work if nCpuFreqShift is changed on the fly (when the
* CPU goes from 8 MHz to 16 MHz in the case of the MegaSTE for example)
*
* To get the correct 250 kHZ clock, we must compute how many CpuClock units
* elapsed since the previous call and convert this increment into
* an increment for the 250 kHz clock
* After each call the remainder will be saved to be used on the next call
*/
#if 0
/* integer version : use it when YM2149's clock is the same as CPU's clock (eg STF) */
static void YM2149_UpdateClock_250_int ( uint64_t CpuClock )
{
uint64_t CpuClockDiff;
uint64_t YM_Div;
uint64_t YM_Inc;
/* We divide CpuClockDiff by YM_Div to get a 250 Hz YM clock increment (YM_Div=32 for an STF with a 8 MHz CPU) */
YM_Div = 32 << nCpuFreqShift;
//fprintf ( stderr , "ym_div %lu %f\n" , YM_Div , ((double)MachineClocks.CPU_Freq_Emul) / YM_ATARI_CLOCK_COUNTER );
/* We update YM2149_Clock_250 only if enough CpuClock units elapsed (at least YM_Div) */
CpuClockDiff = CpuClock - YM2149_Clock_250_CpuClock;
if ( CpuClockDiff >= YM_Div )
{
YM_Inc = CpuClockDiff / YM_Div; /* truncate to lower integer */
//fprintf ( stderr , "update_250 in div=%lu clock_cpu=%lu cpu_diff=%lu inc=%lu clock_250_in=%lu\n" , YM_Div, CpuClock, CpuClockDiff, YM_Inc, YM2149_Clock_250 );
YM2149_Clock_250 += YM_Inc;
YM2149_Clock_250_CpuClock = CpuClock - CpuClockDiff % YM_Div;
//fprintf ( stderr , "update_250 out div=%lu clock_cpu=%lu cpu_diff=%lu inc=%lu clock_250_in=%lu\n" , YM_Div, CpuClock, CpuClockDiff, YM_Inc, YM2149_Clock_250 );
}
//fprintf ( stderr , "update_250 clock_cpu=%ld -> ym_inc=%ld clock_250=%ld clock_250_cpu_clock=%ld\n" , CpuClock , YM_Inc , YM2149_Clock_250 , YM2149_Clock_250_CpuClock );
}
/* floating point version : use it when YM2149's clock is different from CPU's clock (eg STE) */
static void YM2149_UpdateClock_250_float ( uint64_t CpuClock )
{
uint64_t CpuClockDiff;
double YM_Div;
uint64_t YM_Inc;
/* We divide CpuClockDiff by YM_Div to get a 250 Hz YM clock increment (YM_Div=32.0425 for an STE with a 8 MHz CPU) */
YM_Div = ((double)MachineClocks.CPU_Freq_Emul) / YM_ATARI_CLOCK_COUNTER;
//fprintf ( stderr , "ym_div %f\n" , YM_Div );
/* We update YM2149_Clock_250 only if enough CpuClock units elapsed (at least YM_Div) */
CpuClockDiff = CpuClock - YM2149_Clock_250_CpuClock;
if ( CpuClockDiff >= YM_Div )
{
YM_Inc = CpuClockDiff / YM_Div; /* will truncate to lower integer when casting to uint64_t */
//fprintf ( stderr , "update_250 in div=%f clock_cpu=%lu cpu_diff=%lu inc=%lu clock_250_in=%lu\n" , YM_Div, CpuClock, CpuClockDiff, YM_Inc, YM2149_Clock_250 );
YM2149_Clock_250 += YM_Inc;
YM2149_Clock_250_CpuClock = CpuClock - round ( fmod ( CpuClockDiff , YM_Div ) );
//fprintf ( stderr , "update_250 out div=%f clock_cpu=%lu cpu_diff=%lu inc=%lu clock_250_in=%lu\n" , YM_Div, CpuClock, CpuClockDiff, YM_Inc, YM2149_Clock_250 );
}
//fprintf ( stderr , "update_250 clock_cpu=%ld -> ym_inc=%ld clock_250=%ld clock_250_cpu_clock=%ld\n" , CpuClock , YM_Inc , YM2149_Clock_250 , YM2149_Clock_250_CpuClock );
}
#endif
static void YM2149_UpdateClock_250_int_new ( uint64_t CpuClock )
{
uint64_t CpuClockDiff;
CpuClockDiff = CpuClock - YM2149_Clock_250_CpuClock;
ClocksTimings_ConvertCycles ( CpuClockDiff , MachineClocks.CPU_Freq_Emul , &YM2149_ConvertCycles_250 , YM_ATARI_CLOCK_COUNTER );
YM2149_Clock_250 += YM2149_ConvertCycles_250.Cycles;
YM2149_Clock_250_CpuClock = CpuClock;
//fprintf ( stderr , "update_250_new out clock_cpu=%lu cpu_diff=%lu inc=%lu rem=%lu clock_250_in=%lu\n" , CpuClock, CpuClockDiff, YM2149_ConvertCycles_250.Cycles, YM2149_ConvertCycles_250.Remainder , YM2149_Clock_250 );
//fprintf ( stderr , "update_250 clock_cpu=%ld -> ym_inc=%ld clock_250=%ld clock_250_cpu_clock=%ld\n" , CpuClock , YM2149_ConvertCycles_250.Cycles , YM2149_Clock_250 , YM2149_Clock_250_CpuClock );
}
/*
* In case of STF/MegaST, we use the 'integer' version that should give less rounding
* than the 'floating point' version. It should slightly faster too.
* For other machines, we use the 'floating point' version because CPU and YM/DMA Audio don't
* share the same clock.
*
* In the end, 'integer' and 'floating point' versions will sound the same because
* floating point precision should be good enough to avoid rounding errors.
*/
static void YM2149_UpdateClock_250 ( uint64_t CpuClock )
{
if ( ConfigureParams.System.nMachineType == MACHINE_ST || ConfigureParams.System.nMachineType == MACHINE_MEGA_ST )
{
// YM2149_UpdateClock_250_int ( CpuClock );
YM2149_UpdateClock_250_int_new ( CpuClock );
}
else
// YM2149_UpdateClock_250_float ( CpuClock );
YM2149_UpdateClock_250_int_new ( CpuClock );
}
/*-----------------------------------------------------------------------*/
/**
* Init some internal tables for faster results (env, volume)
* and reset the internal states.
*/
static void Ym2149_Init(void)
{
/* Build the 16 envelope shapes */
YM2149_EnvBuild();
/* Build the volume conversion table */
Ym2149_BuildVolumeTable();
/* Reset YM2149 internal states */
Ym2149_Reset();
/* Reset 250 Hz clock */
YM2149_Clock_250 = 0;
YM2149_Clock_250_CpuClock = CyclesGlobalClockCounter;
/* Clear internal YM audio buffer at 250 kHz */
memset ( YM_Buffer_250 , 0 , sizeof(YM_Buffer_250) );
YM_Buffer_250_pos_write = 0;
YM_Buffer_250_pos_read = 0;
}
/*-----------------------------------------------------------------------*/
/**
* Reset all ym registers as well as the internal variables
*/
static void Ym2149_Reset(void)
{
int i;
for ( i=0 ; i<14 ; i++ )
Sound_WriteReg ( i , 0 );
Sound_WriteReg ( 7 , 0xff );
/* Reset internal variables and counters */
ToneA_per = ToneA_count = 0;
ToneB_per = ToneB_count = 0;
ToneC_per = ToneC_count = 0;
Noise_per = Noise_count = 0;
Env_per = Env_count = 0;
Env_shape = Env_pos = 0;
ToneA_val = ToneB_val = ToneC_val = Noise_val = YM_SQUARE_DOWN;
RndRack = 1;
}
/*-----------------------------------------------------------------------*/
/**
* Returns a pseudo random value, used to generate white noise.
* As measured by David Savinkoff, the YM2149 uses a 17 stage LSFR with
* 2 taps (17,14)
*/
static ymu32 YM2149_RndCompute(void)
{
/* 17 stage, 2 taps (17, 14) LFSR */
if (RndRack & 1)
{
RndRack = RndRack>>1 ^ 0x12000; /* bits 17 and 14 are ones */
return 0xffff;
}
else
{ RndRack >>= 1;
return 0;
}
}
static ymu16 YM2149_TonePer(ymu8 rHigh , ymu8 rLow)
{
ymu16 per;
per = ( ( rHigh & 0x0f ) << 8 ) + rLow;
return per;
}
static ymu16 YM2149_NoisePer(ymu8 rNoise)
{
ymu16 per;
per = rNoise & 0x1f;
return per;
}
static ymu16 YM2149_EnvPer(ymu8 rHigh , ymu8 rLow)
{
ymu16 per;
per = ( rHigh << 8 ) + rLow;