]> Shamusworld >> Repos - apple2/blob - src/sound.cpp
Fix trash on sides of screen in full screen mode.
[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 "log.h"
28 #include "mockingboard.h"
29
30
31 // Useful defines
32
33 //#define DEBUG
34
35 #define SAMPLES_PER_FRAME       (SAMPLE_RATE / 60.0)
36 #define CYCLES_PER_SAMPLE       (1024000.0 / SAMPLE_RATE)
37 // 32K ought to be enough for anybody
38 #define SOUND_BUFFER_SIZE       (32768)
39
40 // Global variables
41
42
43 // Local variables
44
45 static SDL_AudioSpec desired, obtained;
46 static SDL_AudioDeviceID device;
47 static bool soundInitialized = false;
48 static bool speakerState = false;
49 static uint16_t soundBuffer[SOUND_BUFFER_SIZE];
50 static uint32_t soundBufferPos;
51 static uint16_t sample;
52 static uint8_t ampPtr = 12;                                             // Start with -2047 - +2047
53 static int16_t amplitude[17] = { 0, 1, 2, 3, 7, 15, 31, 63, 127, 255,
54         511, 1023, 2047, 4095, 8191, 16383, 32767 };
55
56 // Private function prototypes
57
58 static void SDLSoundCallback(void * userdata, Uint8 * buffer, int length);
59
60
61 /*
62 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.  :-/
63 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!).
64 */
65 //
66 // Initialize the SDL sound system
67 //
68 void SoundInit(void)
69 {
70         SDL_zero(desired);
71         desired.freq = SAMPLE_RATE;             // SDL will do conversion on the fly, if it can't get the exact rate. Nice!
72         desired.format = AUDIO_U16SYS;  // This uses the native endian (for portability)...
73         desired.channels = 1;
74         desired.samples = 512;                  // Let's try a 1/2K buffer
75         desired.callback = SDLSoundCallback;
76
77         device = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, 0);
78
79         if (device == 0)
80         {
81                 WriteLog("Sound: Failed to initialize SDL sound.\n");
82                 WriteLog("SDL sez: %s\n", SDL_GetError());
83                 return;
84         }
85
86         soundBufferPos = 0;
87         sample = desired.silence;               // ? wilwok ? yes
88
89         SDL_PauseAudioDevice(device, 0);// Start playback!
90         soundInitialized = true;
91         WriteLog("Sound: Successfully initialized.\n");
92 }
93
94
95 //
96 // Close down the SDL sound subsystem
97 //
98 void SoundDone(void)
99 {
100         if (soundInitialized)
101         {
102                 SDL_PauseAudioDevice(device, 1);
103                 SDL_CloseAudioDevice(device);
104                 WriteLog("Sound: Done.\n");
105         }
106 }
107
108
109 void SoundPause(void)
110 {
111         if (soundInitialized)
112                 SDL_PauseAudioDevice(device, 1);
113 }
114
115
116 void SoundResume(void)
117 {
118         if (soundInitialized)
119                 SDL_PauseAudioDevice(device, 0);
120 }
121
122
123 //
124 // Sound card callback handler
125 //
126 static uint32_t sndFrmCnt = 0;
127 static uint32_t lastStarve = 0;
128 static void SDLSoundCallback(void * /*userdata*/, Uint8 * buffer8, int length8)
129 {
130 sndFrmCnt++;
131
132         // Recast this as a 16-bit type...
133         uint16_t * buffer = (uint16_t *)buffer8;
134         uint32_t length = (uint32_t)length8 / 2;
135
136         if (soundBufferPos < length)
137         {
138 //WriteLog("*** Sound buffer starved (%d short) *** [%d delta %d]\n", length - soundBufferPos, sndFrmCnt, sndFrmCnt - lastStarve);
139 lastStarve = sndFrmCnt;
140 #if 1
141                 for(uint32_t i=0; i<length; i++)
142                         buffer[i] = desired.silence;
143 #else
144                 // The sound buffer is starved...
145                 for(uint32_t i=0; i<soundBufferPos; i++)
146                         buffer[i] = soundBuffer[i];
147
148                 // Fill buffer with last value
149                 for(uint32_t i=soundBufferPos; i<length; i++)
150                         buffer[i] = sample;
151
152                 // Reset soundBufferPos to start of buffer...
153                 soundBufferPos = 0;
154 #endif
155         }
156         else
157         {
158                 // Fill sound buffer with frame buffered sound
159                 for(uint32_t i=0; i<length; i++)
160                         buffer[i] = soundBuffer[i];
161
162                 soundBufferPos -= length;
163
164                 // Move current buffer down to start
165                 for(uint32_t i=0; i<soundBufferPos; i++)
166                         soundBuffer[i] = soundBuffer[length + i];
167         }
168 }
169
170
171 //
172 // This is called by the main CPU thread every ~21.666 cycles.
173 //
174 void WriteSampleToBuffer(void)
175 {
176 //      uint16_t s1 = AYGetSample(0);
177 //      uint16_t s2 = AYGetSample(1);
178         uint16_t s1 = mb[0].ay[0].GetSample();
179         uint16_t s2 = mb[0].ay[1].GetSample();
180
181         // This should almost never happen, but, if it does...
182         while (soundBufferPos >= (SOUND_BUFFER_SIZE - 1))
183         {
184 //WriteLog("WriteSampleToBuffer(): Waiting for sound thread. soundBufferPos=%i, SOUNDBUFFERSIZE-1=%i\n", soundBufferPos, SOUND_BUFFER_SIZE-1);
185                 SDL_Delay(1);
186         }
187
188         SDL_LockAudioDevice(device);
189         soundBuffer[soundBufferPos++] = sample + s1 + s2;
190         SDL_UnlockAudioDevice(device);
191 }
192
193
194 void ToggleSpeaker(void)
195 {
196         if (!soundInitialized)
197                 return;
198
199         speakerState = !speakerState;
200         sample = (speakerState ? amplitude[ampPtr] : 0);
201 }
202
203
204 void VolumeUp(void)
205 {
206         // Currently set for 16-bit samples
207         if (ampPtr < 16)
208                 ampPtr++;
209 }
210
211
212 void VolumeDown(void)
213 {
214         if (ampPtr > 0)
215                 ampPtr--;
216 }
217
218
219 uint8_t GetVolume(void)
220 {
221         return ampPtr;
222 }
223