]> Shamusworld >> Repos - apple2/blob - src/sound.cpp
67b3090b6be2efa9c17f1f64a2efc4a7678fd74d
[apple2] / src / sound.cpp
1 //
2 // Sound Interface
3 //
4 // by James Hammons
5 // (C) 2005-2018 Underground Software
6 //
7 // JLH = James Hammons <jlhamm@acm.org>
8 //
9 // WHO  WHEN        WHAT
10 // ---  ----------  -----------------------------------------------------------
11 // JLH  12/02/2005  Fixed a problem with sound callback thread signaling the
12 //                  main thread
13 // JLH  12/03/2005  Fixed sound callback dropping samples when the sample
14 //                  buffer is shorter than the callback sample buffer
15 //
16
17 // STILL TO DO:
18 //
19 // - Figure out why it's losing samples (Bard's Tale) [DONE]
20 // - Figure out why it's playing too fast [DONE]
21 //
22
23 #include "sound.h"
24
25 #include <string.h>                     // For memset, memcpy
26 #include <SDL2/SDL.h>
27 #include "ay8910.h"
28 #include "log.h"
29
30 // Useful defines
31
32 //#define DEBUG
33
34 #define SAMPLES_PER_FRAME       (SAMPLE_RATE / 60.0)
35 #define CYCLES_PER_SAMPLE       (1024000.0 / SAMPLE_RATE)
36 // 32K ought to be enough for anybody
37 #define SOUND_BUFFER_SIZE       (32768)
38
39 // Global variables
40
41
42 // Local variables
43
44 static SDL_AudioSpec desired, obtained;
45 static SDL_AudioDeviceID device;
46 static bool soundInitialized = false;
47 static bool speakerState = false;
48 static uint16_t soundBuffer[SOUND_BUFFER_SIZE];
49 static uint32_t soundBufferPos;
50 static uint16_t sample;
51 static uint8_t ampPtr = 12;                                             // Start with -2047 - +2047
52 static int16_t amplitude[17] = { 0, 1, 2, 3, 7, 15, 31, 63, 127, 255,
53         511, 1023, 2047, 4095, 8191, 16383, 32767 };
54
55 // Private function prototypes
56
57 static void SDLSoundCallback(void * userdata, Uint8 * buffer, int length);
58
59
60 /*
61 N.B: We can convert this from the current callback model to a push model by using SDL_QueueAudio(SDL_AudioDeviceID id, const void * data, Uint32 len) where id is the audio device ID, data is a pointer to the sound buffer, and len is the size of the buffer in *bytes* (not samples!).  To use this method, we need to set up things as usual but instead of putting the callback function pointer in desired.callback, we put a NULL there.  The downside is that we can't tell if the buffer is being starved or not, which is why we haven't kicked it to the curb just yet--we want to know why we're still getting buffer starvation even if it's not as frequent as it used to be.  :-/
62 You can get the size of the audio already queued with SDL_GetQueuedAudioSize(SDL_AudioDeviceID id), which will return the size of the buffer in bytes (again, *not* samples!).
63 */
64 //
65 // Initialize the SDL sound system
66 //
67 void SoundInit(void)
68 {
69         SDL_zero(desired);
70         desired.freq = SAMPLE_RATE;             // SDL will do conversion on the fly, if it can't get the exact rate. Nice!
71         desired.format = AUDIO_U16SYS;  // This uses the native endian (for portability)...
72         desired.channels = 1;
73         desired.samples = 512;                  // Let's try a 1/2K buffer
74         desired.callback = SDLSoundCallback;
75
76         device = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, 0);
77
78         if (device == 0)
79         {
80                 WriteLog("Sound: Failed to initialize SDL sound.\n");
81                 return;
82         }
83
84         soundBufferPos = 0;
85         sample = desired.silence;               // ? wilwok ? yes
86
87         SDL_PauseAudioDevice(device, 0);// Start playback!
88         soundInitialized = true;
89         WriteLog("Sound: Successfully initialized.\n");
90 }
91
92
93 //
94 // Close down the SDL sound subsystem
95 //
96 void SoundDone(void)
97 {
98         if (soundInitialized)
99         {
100                 SDL_PauseAudioDevice(device, 1);
101                 SDL_CloseAudioDevice(device);
102                 WriteLog("Sound: Done.\n");
103         }
104 }
105
106
107 void SoundPause(void)
108 {
109         if (soundInitialized)
110                 SDL_PauseAudioDevice(device, 1);
111 }
112
113
114 void SoundResume(void)
115 {
116         if (soundInitialized)
117                 SDL_PauseAudioDevice(device, 0);
118 }
119
120
121 //
122 // Sound card callback handler
123 //
124 static uint32_t sndFrmCnt = 0;
125 static uint32_t lastStarve = 0;
126 static void SDLSoundCallback(void * /*userdata*/, Uint8 * buffer8, int length8)
127 {
128 sndFrmCnt++;
129
130         // Recast this as a 16-bit type...
131         uint16_t * buffer = (uint16_t *)buffer8;
132         uint32_t length = (uint32_t)length8 / 2;
133
134         if (soundBufferPos < length)
135         {
136 WriteLog("*** Sound buffer starved (%d short) *** [%d delta %d]\n", length - soundBufferPos, sndFrmCnt, sndFrmCnt - lastStarve);
137 lastStarve = sndFrmCnt;
138 #if 1
139                 for(uint32_t i=0; i<length; i++)
140                         buffer[i] = desired.silence;
141 #else
142                 // The sound buffer is starved...
143                 for(uint32_t i=0; i<soundBufferPos; i++)
144                         buffer[i] = soundBuffer[i];
145
146                 // Fill buffer with last value
147                 for(uint32_t i=soundBufferPos; i<length; i++)
148                         buffer[i] = sample;
149
150                 // Reset soundBufferPos to start of buffer...
151                 soundBufferPos = 0;
152 #endif
153         }
154         else
155         {
156                 // Fill sound buffer with frame buffered sound
157                 for(uint32_t i=0; i<length; i++)
158                         buffer[i] = soundBuffer[i];
159
160                 soundBufferPos -= length;
161
162                 // Move current buffer down to start
163                 for(uint32_t i=0; i<soundBufferPos; i++)
164                         soundBuffer[i] = soundBuffer[length + i];
165         }
166 }
167
168
169 //
170 // This is called by the main CPU thread every ~21.666 cycles.
171 //
172 void WriteSampleToBuffer(void)
173 {
174 #ifdef USE_NEW_AY8910
175         uint16_t s1 = AYGetSample(0);
176         uint16_t s2 = AYGetSample(1);
177         uint16_t adjustedMockingboard = s1 + s2;
178 #else
179         int16_t s1, s2, s3, s4, s5, s6;
180         int16_t * bufPtrs[6] = { &s1, &s2, &s3, &s4, &s5, &s6 };
181         AY8910Update(0, bufPtrs, 1);
182         AY8910Update(1, &bufPtrs[3], 1);
183         int16_t adjustedMockingboard = (s1 / 8) + (s2 / 8) + (s3 / 8)
184                 + (s4 / 8) + (s5 / 8) + (s6 / 8);
185 #endif
186
187         // This should almost never happen, but, if it does...
188         while (soundBufferPos >= (SOUND_BUFFER_SIZE - 1))
189         {
190 //WriteLog("WriteSampleToBuffer(): Waiting for sound thread. soundBufferPos=%i, SOUNDBUFFERSIZE-1=%i\n", soundBufferPos, SOUND_BUFFER_SIZE-1);
191                 SDL_Delay(1);
192         }
193
194         SDL_LockAudioDevice(device);
195         soundBuffer[soundBufferPos++] = sample + adjustedMockingboard;
196         SDL_UnlockAudioDevice(device);
197 }
198
199
200 void ToggleSpeaker(void)
201 {
202         if (!soundInitialized)
203                 return;
204
205         speakerState = !speakerState;
206         sample = (speakerState ? amplitude[ampPtr] : 0);
207 }
208
209
210 void VolumeUp(void)
211 {
212         // Currently set for 16-bit samples
213         if (ampPtr < 16)
214                 ampPtr++;
215 }
216
217
218 void VolumeDown(void)
219 {
220         if (ampPtr > 0)
221                 ampPtr--;
222 }
223
224
225 uint8_t GetVolume(void)
226 {
227         return ampPtr;
228 }
229