]> Shamusworld >> Repos - apple2/blob - src/sound.cpp
df2de2b4ab59d3c64b80cbc49eb8002ee68734cf
[apple2] / src / sound.cpp
1 //
2 // Sound Interface
3 //
4 // by James Hammons
5 // (C) 2005 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 uint64_t lastToggleCycles;
51 //static SDL_cond * conditional = NULL;
52 //static SDL_mutex * mutex = NULL;
53 //static SDL_mutex * mutex2 = NULL;
54 static uint16_t sample;
55 static uint8_t ampPtr = 12;                                             // Start with -2047 - +2047
56 static int16_t amplitude[17] = { 0, 1, 2, 3, 7, 15, 31, 63, 127, 255,
57         511, 1023, 2047, 4095, 8191, 16383, 32767 };
58
59 // Private function prototypes
60
61 static void SDLSoundCallback(void * userdata, Uint8 * buffer, int length);
62
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 //      conditional = SDL_CreateCond();
85 //      mutex = SDL_CreateMutex();
86 //      mutex2 = SDL_CreateMutex();// Let's try real signalling...
87         soundBufferPos = 0;
88 //      lastToggleCycles = 0;
89         sample = desired.silence;       // ? wilwok ? yes
90
91         SDL_PauseAudioDevice(device, 0);                        // Start playback!
92         soundInitialized = true;
93         WriteLog("Sound: Successfully initialized.\n");
94 }
95
96
97 //
98 // Close down the SDL sound subsystem
99 //
100 void SoundDone(void)
101 {
102         if (soundInitialized)
103         {
104                 SDL_PauseAudioDevice(device, 1);
105                 SDL_CloseAudioDevice(device);
106 //              SDL_DestroyCond(conditional);
107 //              SDL_DestroyMutex(mutex);
108 //              SDL_DestroyMutex(mutex2);
109                 WriteLog("Sound: Done.\n");
110         }
111 }
112
113
114 void SoundPause(void)
115 {
116         if (soundInitialized)
117                 SDL_PauseAudioDevice(device, 1);
118 }
119
120
121 void SoundResume(void)
122 {
123         if (soundInitialized)
124                 SDL_PauseAudioDevice(device, 0);
125 }
126
127
128 //
129 // Sound card callback handler
130 //
131 static uint32_t sndFrmCnt = 0;
132 static uint32_t lastStarve = 0;
133 static void SDLSoundCallback(void * /*userdata*/, Uint8 * buffer8, int length8)
134 {
135 sndFrmCnt++;
136 //WriteLog("SDLSoundCallback(): begin (soundBufferPos=%i)\n", soundBufferPos);
137
138         // Let's try using a mutex for shared resource consumption...
139 //Actually, I think Lock/UnlockAudio() does this already...
140 //WriteLog("SDLSoundCallback: soundBufferPos = %i\n", soundBufferPos);
141 //      SDL_mutexP(mutex2);
142
143         // Recast this as a 16-bit type...
144         uint16_t * buffer = (uint16_t *)buffer8;
145         uint32_t length = (uint32_t)length8 / 2;
146
147 //WriteLog("SDLSoundCallback(): filling buffer...\n");
148         if (soundBufferPos < length)
149         {
150 WriteLog("*** Sound buffer starved (%d short) *** [%d delta %d]\n", length - soundBufferPos, sndFrmCnt, sndFrmCnt - lastStarve);
151 lastStarve = sndFrmCnt;
152 #if 1
153                 for(uint32_t i=0; i<length; i++)
154                         buffer[i] = desired.silence;
155 #else
156                 // The sound buffer is starved...
157                 for(uint32_t i=0; i<soundBufferPos; i++)
158                         buffer[i] = soundBuffer[i];
159
160                 // Fill buffer with last value
161                 for(uint32_t i=soundBufferPos; i<length; i++)
162                         buffer[i] = sample;
163
164                 // Reset soundBufferPos to start of buffer...
165                 soundBufferPos = 0;
166 #endif
167         }
168         else
169         {
170                 // Fill sound buffer with frame buffered sound
171                 for(uint32_t i=0; i<length; i++)
172                         buffer[i] = soundBuffer[i];
173
174                 soundBufferPos -= length;
175
176                 // Move current buffer down to start
177                 for(uint32_t i=0; i<soundBufferPos; i++)
178                         soundBuffer[i] = soundBuffer[length + i];
179         }
180
181         // Free the mutex...
182 //WriteLog("SDLSoundCallback(): SDL_mutexV(mutex2)\n");
183 //      SDL_mutexV(mutex2);
184         // Wake up any threads waiting for the buffer to drain...
185 //      SDL_CondSignal(conditional);
186 //WriteLog("SDLSoundCallback(): end\n");
187 }
188
189
190 // This is called by the main CPU thread every ~21.666 cycles.
191 void WriteSampleToBuffer(void)
192 {
193 #ifdef USE_NEW_AY8910
194         uint16_t s1 = AYGetSample(0);
195         uint16_t s2 = AYGetSample(1);
196         uint16_t adjustedMockingboard = s1 + s2;
197 #else
198         int16_t s1, s2, s3, s4, s5, s6;
199         int16_t * bufPtrs[6] = { &s1, &s2, &s3, &s4, &s5, &s6 };
200         AY8910Update(0, bufPtrs, 1);
201         AY8910Update(1, &bufPtrs[3], 1);
202         int16_t adjustedMockingboard = (s1 / 8) + (s2 / 8) + (s3 / 8)
203                 + (s4 / 8) + (s5 / 8) + (s6 / 8);
204 #endif
205 //need to do this *before* mixing, as by this time, it's too late and the sample is probably already oversaturated
206 //      adjustedMockingboard /= 8;
207
208 //WriteLog("WriteSampleToBuffer(): SDL_mutexP(mutex2)\n");
209 //      SDL_mutexP(mutex2);
210
211         // This should almost never happen, but, if it does...
212         while (soundBufferPos >= (SOUND_BUFFER_SIZE - 1))
213         {
214 //WriteLog("WriteSampleToBuffer(): Waiting for sound thread. soundBufferPos=%i, SOUNDBUFFERSIZE-1=%i\n", soundBufferPos, SOUND_BUFFER_SIZE-1);
215 //              SDL_mutexV(mutex2);     // Release it so sound thread can get it,
216 //              SDL_mutexP(mutex);      // Must lock the mutex for the cond to work properly...
217 //              SDL_CondWait(conditional, mutex);       // Sleep/wait for the sound thread
218 //              SDL_mutexV(mutex);      // Must unlock the mutex for the cond to work properly...
219 //              SDL_mutexP(mutex2);     // Re-lock it until we're done with it...
220                 SDL_Delay(1);
221         }
222
223         SDL_LockAudioDevice(device);
224         soundBuffer[soundBufferPos++] = sample + adjustedMockingboard;
225         SDL_UnlockAudioDevice(device);
226
227 //      soundBuffer[soundBufferPos++] = sample;
228 //WriteLog("WriteSampleToBuffer(): SDL_mutexV(mutex2)\n");
229 //      SDL_mutexV(mutex2);
230 }
231
232
233 void ToggleSpeaker(void)
234 {
235         if (!soundInitialized)
236                 return;
237
238         speakerState = !speakerState;
239         sample = (speakerState ? amplitude[ampPtr] : 0);//-amplitude[ampPtr]);
240 }
241
242
243 void VolumeUp(void)
244 {
245         // Currently set for 16-bit samples
246         if (ampPtr < 16)
247                 ampPtr++;
248 }
249
250
251 void VolumeDown(void)
252 {
253         if (ampPtr > 0)
254                 ampPtr--;
255 }
256
257
258 uint8_t GetVolume(void)
259 {
260         return ampPtr;
261 }
262