]> Shamusworld >> Repos - apple2/blob - src/sound.cpp
Improvements to timing, disk selector; added Double LoRes.
[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 "log.h"
28
29 // Useful defines
30
31 //#define DEBUG
32
33 #define SAMPLE_RATE                     (48000.0)
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 int16_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 int16_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_S16SYS;                          // This uses the native endian (for portability)...
72         desired.channels = 1;
73         desired.samples = 512;                                          // Let's try a 1/2K buffer (can always go lower)
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 void SDLSoundCallback(void * /*userdata*/, Uint8 * buffer8, int length8)
132 {
133 //WriteLog("SDLSoundCallback(): begin (soundBufferPos=%i)\n", soundBufferPos);
134         // The sound buffer should only starve when starting which will cause it to
135         // lag behind the emulation at most by around 1 frame...
136         // (Actually, this should never happen since we fill the buffer beforehand.)
137         // (But, then again, if the sound hasn't been toggled for a while, then this
138         //  makes perfect sense as the buffer won't have been filled at all!)
139         // (Should NOT starve now, now that we properly handle frame edges...)
140
141         // Let's try using a mutex for shared resource consumption...
142 //Actually, I think Lock/UnlockAudio() does this already...
143 //WriteLog("SDLSoundCallback: soundBufferPos = %i\n", soundBufferPos);
144         SDL_mutexP(mutex2);
145
146         // Recast this as a 16-bit type...
147         int16_t * buffer = (int16_t *)buffer8;
148         uint32_t length = (uint32_t)length8 / 2;
149
150 //WriteLog("SDLSoundCallback(): filling buffer...\n");
151         if (soundBufferPos < length)
152         {
153                 // The sound buffer is starved...
154                 for(uint32_t i=0; i<soundBufferPos; i++)
155                         buffer[i] = soundBuffer[i];
156
157                 // Fill buffer with last value
158                 for(uint32_t i=soundBufferPos; i<length; i++)
159                         buffer[i] = sample;
160
161                 // Reset soundBufferPos to start of buffer...
162                 soundBufferPos = 0;
163         }
164         else
165         {
166                 // Fill sound buffer with frame buffered sound
167                 for(uint32_t i=0; i<length; i++)
168                         buffer[i] = soundBuffer[i];
169
170                 soundBufferPos -= length;
171
172                 // Move current buffer down to start
173                 for(uint32_t i=0; i<soundBufferPos; i++)
174                         soundBuffer[i] = soundBuffer[length + i];
175         }
176
177         // Free the mutex...
178 //WriteLog("SDLSoundCallback(): SDL_mutexV(mutex2)\n");
179         SDL_mutexV(mutex2);
180         // Wake up any threads waiting for the buffer to drain...
181         SDL_CondSignal(conditional);
182 //WriteLog("SDLSoundCallback(): end\n");
183 }
184
185
186 // This is called by the main CPU thread every ~21.666 cycles.
187 void WriteSampleToBuffer(void)
188 {
189 //WriteLog("WriteSampleToBuffer(): SDL_mutexP(mutex2)\n");
190         SDL_mutexP(mutex2);
191
192         // This should almost never happen, but, if it does...
193         while (soundBufferPos >= (SOUND_BUFFER_SIZE - 1))
194         {
195 //WriteLog("WriteSampleToBuffer(): Waiting for sound thread. soundBufferPos=%i, SOUNDBUFFERSIZE-1=%i\n", soundBufferPos, SOUND_BUFFER_SIZE-1);
196                 SDL_mutexV(mutex2);     // Release it so sound thread can get it,
197                 SDL_mutexP(mutex);      // Must lock the mutex for the cond to work properly...
198                 SDL_CondWait(conditional, mutex);       // Sleep/wait for the sound thread
199                 SDL_mutexV(mutex);      // Must unlock the mutex for the cond to work properly...
200                 SDL_mutexP(mutex2);     // Re-lock it until we're done with it...
201         }
202
203         soundBuffer[soundBufferPos++] = sample;
204 //WriteLog("WriteSampleToBuffer(): SDL_mutexV(mutex2)\n");
205         SDL_mutexV(mutex2);
206 }
207
208
209 void ToggleSpeaker(void)
210 {
211         if (!soundInitialized)
212                 return;
213
214         speakerState = !speakerState;
215         sample = (speakerState ? amplitude[ampPtr] : -amplitude[ampPtr]);
216 }
217
218
219 void VolumeUp(void)
220 {
221         // Currently set for 16-bit samples
222         if (ampPtr < 16)
223                 ampPtr++;
224 }
225
226
227 void VolumeDown(void)
228 {
229         if (ampPtr > 0)
230                 ampPtr--;
231 }
232
233
234 uint8_t GetVolume(void)
235 {
236         return ampPtr;
237 }
238