]> Shamusworld >> Repos - apple2/blob - src/sound.cpp
Misc. cleanups, incl. cleanup up Makefile.
[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 buffer
14 //                  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 //#define WRITE_OUT_WAVE
33
34 //#define SAMPLE_RATE                   (44100.0)
35 #define SAMPLE_RATE                     (48000.0)
36 #define SAMPLES_PER_FRAME       (SAMPLE_RATE / 60.0)
37 #define CYCLES_PER_SAMPLE       (1024000.0 / SAMPLE_RATE)
38 //#define SOUND_BUFFER_SIZE     (8192)
39 // 32K ought to be enough for anybody
40 #define SOUND_BUFFER_SIZE       (32768)
41
42 // Global variables
43
44
45 // Local variables
46
47 static SDL_AudioSpec desired, obtained;
48 static SDL_AudioDeviceID device;
49 static bool soundInitialized = false;
50 static bool speakerState = false;
51 static int16_t soundBuffer[SOUND_BUFFER_SIZE];
52 static uint32_t soundBufferPos;
53 static uint64_t lastToggleCycles;
54 static SDL_cond * conditional = NULL;
55 static SDL_mutex * mutex = NULL;
56 static SDL_mutex * mutex2 = NULL;
57 static int16_t sample;
58 static uint8_t ampPtr = 12;                                             // Start with -2047 - +2047
59 static int16_t amplitude[17] = { 0, 1, 2, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,
60         4095, 8191, 16383, 32767 };
61 #ifdef WRITE_OUT_WAVE
62 static FILE * fp = NULL;
63 #endif
64
65 // Private function prototypes
66
67 static void SDLSoundCallback(void * userdata, Uint8 * buffer, int length);
68
69
70 //
71 // Initialize the SDL sound system
72 //
73 void SoundInit(void)
74 {
75 #if 0
76 // To weed out problems for now...
77 return;
78 #endif
79         SDL_zero(desired);
80         desired.freq = SAMPLE_RATE;                                     // SDL will do conversion on the fly, if it can't get the exact rate. Nice!
81         desired.format = AUDIO_S16SYS;                          // This uses the native endian (for portability)...
82         desired.channels = 1;
83         desired.samples = 512;                                          // Let's try a 1/2K buffer (can always go lower)
84         desired.callback = SDLSoundCallback;
85
86         device = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, 0);
87
88         if (device == 0)
89         {
90                 WriteLog("Sound: Failed to initialize SDL sound.\n");
91                 return;
92         }
93
94         conditional = SDL_CreateCond();
95         mutex = SDL_CreateMutex();
96         mutex2 = SDL_CreateMutex();// Let's try real signalling...
97         soundBufferPos = 0;
98         lastToggleCycles = 0;
99         sample = desired.silence;       // ? wilwok ? yes
100
101         SDL_PauseAudioDevice(device, 0);                        // Start playback!
102         soundInitialized = true;
103         WriteLog("Sound: Successfully initialized.\n");
104
105 #ifdef WRITE_OUT_WAVE
106         fp = fopen("./apple2.wav", "wb");
107 #endif
108 }
109
110
111 //
112 // Close down the SDL sound subsystem
113 //
114 void SoundDone(void)
115 {
116         if (soundInitialized)
117         {
118                 SDL_PauseAudioDevice(device, 1);
119                 SDL_CloseAudioDevice(device);
120                 SDL_DestroyCond(conditional);
121                 SDL_DestroyMutex(mutex);
122                 SDL_DestroyMutex(mutex2);
123                 WriteLog("Sound: Done.\n");
124
125 #ifdef WRITE_OUT_WAVE
126                 fclose(fp);
127 #endif
128         }
129 }
130
131
132 void SoundPause(void)
133 {
134         if (soundInitialized)
135                 SDL_PauseAudioDevice(device, 1);
136 }
137
138
139 void SoundResume(void)
140 {
141         if (soundInitialized)
142                 SDL_PauseAudioDevice(device, 0);
143 }
144
145
146 //
147 // Sound card callback handler
148 //
149 static void SDLSoundCallback(void * /*userdata*/, Uint8 * buffer8, int length8)
150 {
151 //WriteLog("SDLSoundCallback(): begin (soundBufferPos=%i)\n", soundBufferPos);
152         // The sound buffer should only starve when starting which will cause it to
153         // lag behind the emulation at most by around 1 frame...
154         // (Actually, this should never happen since we fill the buffer beforehand.)
155         // (But, then again, if the sound hasn't been toggled for a while, then this
156         //  makes perfect sense as the buffer won't have been filled at all!)
157         // (Should NOT starve now, now that we properly handle frame edges...)
158
159         // Let's try using a mutex for shared resource consumption...
160 //Actually, I think Lock/UnlockAudio() does this already...
161 //WriteLog("SDLSoundCallback: soundBufferPos = %i\n", soundBufferPos);
162         SDL_mutexP(mutex2);
163
164         // Recast this as a 16-bit type...
165         int16_t * buffer = (int16_t *)buffer8;
166         uint32_t length = (uint32_t)length8 / 2;
167
168 //WriteLog("SDLSoundCallback(): filling buffer...\n");
169         if (soundBufferPos < length)
170         {
171                 // The sound buffer is starved...
172                 for(uint32_t i=0; i<soundBufferPos; i++)
173                         buffer[i] = soundBuffer[i];
174
175                 // Fill buffer with last value
176                 for(uint32_t i=soundBufferPos; i<length; i++)
177                         buffer[i] = sample;
178
179                 // Reset soundBufferPos to start of buffer...
180                 soundBufferPos = 0;
181         }
182         else
183         {
184                 // Fill sound buffer with frame buffered sound
185                 for(uint32_t i=0; i<length; i++)
186                         buffer[i] = soundBuffer[i];
187
188                 soundBufferPos -= length;
189
190                 // Move current buffer down to start
191                 for(uint32_t i=0; i<soundBufferPos; i++)
192                         soundBuffer[i] = soundBuffer[length + i];
193         }
194
195         // Free the mutex...
196 //WriteLog("SDLSoundCallback(): SDL_mutexV(mutex2)\n");
197         SDL_mutexV(mutex2);
198         // Wake up any threads waiting for the buffer to drain...
199         SDL_CondSignal(conditional);
200 //WriteLog("SDLSoundCallback(): end\n");
201 }
202
203
204 // This is called by the main CPU thread every ~21.333 cycles.
205 void WriteSampleToBuffer(void)
206 {
207 //WriteLog("WriteSampleToBuffer(): SDL_mutexP(mutex2)\n");
208         SDL_mutexP(mutex2);
209
210         // This should almost never happen, but, if it does...
211         while (soundBufferPos >= (SOUND_BUFFER_SIZE - 1))
212         {
213 //WriteLog("WriteSampleToBuffer(): Waiting for sound thread. soundBufferPos=%i, SOUNDBUFFERSIZE-1=%i\n", soundBufferPos, SOUND_BUFFER_SIZE-1);
214                 SDL_mutexV(mutex2);     // Release it so sound thread can get it,
215                 SDL_mutexP(mutex);      // Must lock the mutex for the cond to work properly...
216                 SDL_CondWait(conditional, mutex);       // Sleep/wait for the sound thread
217                 SDL_mutexV(mutex);      // Must unlock the mutex for the cond to work properly...
218                 SDL_mutexP(mutex2);     // Re-lock it until we're done with it...
219         }
220
221         soundBuffer[soundBufferPos++] = sample;
222 //WriteLog("WriteSampleToBuffer(): SDL_mutexV(mutex2)\n");
223         SDL_mutexV(mutex2);
224 }
225
226
227 void ToggleSpeaker(void)
228 {
229         if (!soundInitialized)
230                 return;
231
232         speakerState = !speakerState;
233         sample = (speakerState ? amplitude[ampPtr] : -amplitude[ampPtr]);
234 }
235
236
237 void VolumeUp(void)
238 {
239         // Currently set for 16-bit samples
240         if (ampPtr < 16)
241                 ampPtr++;
242 }
243
244
245 void VolumeDown(void)
246 {
247         if (ampPtr > 0)
248                 ampPtr--;
249 }
250
251
252 uint8_t GetVolume(void)
253 {
254         return ampPtr;
255 }
256