implemented threaded audio mixing for SDL client (required some
[divverent/darkplaces.git] / snd_sdl.c
1 /*
2 Copyright (C) 2004 Andreas Kirsch
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19 #include "quakedef.h"
20
21 #include <math.h>
22 #include <SDL.h>
23
24 #include "snd_main.h"
25
26
27 static unsigned int sdlaudiotime = 0;
28
29
30 // Note: SDL calls SDL_LockAudio() right before this function, so no need to lock the audio data here
31 static void Buffer_Callback (void *userdata, Uint8 *stream, int len)
32 {
33         unsigned int factor, RequestedFrames, MaxFrames, FrameCount;
34         unsigned int StartOffset, EndOffset;
35
36         factor = snd_renderbuffer->format.channels * snd_renderbuffer->format.width;
37         if ((unsigned int)len % factor != 0)
38                 Sys_Error("SDL sound: invalid buffer length passed to Buffer_Callback (%d bytes)\n", len);
39
40         RequestedFrames = (unsigned int)len / factor;
41
42         if (snd_usethreadedmixing)
43         {
44                 S_MixToBuffer(stream, RequestedFrames);
45                 return;
46         }
47
48         // Transfert up to a chunk of samples from snd_renderbuffer to stream
49         MaxFrames = snd_renderbuffer->endframe - snd_renderbuffer->startframe;
50         if (MaxFrames > RequestedFrames)
51                 FrameCount = RequestedFrames;
52         else
53                 FrameCount = MaxFrames;
54         StartOffset = snd_renderbuffer->startframe % snd_renderbuffer->maxframes;
55         EndOffset = (snd_renderbuffer->startframe + FrameCount) % snd_renderbuffer->maxframes;
56         if (StartOffset > EndOffset)  // if the buffer wraps
57         {
58                 unsigned int PartialLength1, PartialLength2;
59
60                 PartialLength1 = (snd_renderbuffer->maxframes - StartOffset) * factor;
61                 memcpy(stream, &snd_renderbuffer->ring[StartOffset * factor], PartialLength1);
62
63                 PartialLength2 = FrameCount * factor - PartialLength1;
64                 memcpy(&stream[PartialLength1], &snd_renderbuffer->ring[0], PartialLength2);
65         }
66         else
67                 memcpy(stream, &snd_renderbuffer->ring[StartOffset * factor], FrameCount * factor);
68
69         snd_renderbuffer->startframe += FrameCount;
70
71         if (FrameCount < RequestedFrames && developer.integer >= 1000 && vid_activewindow)
72                 Con_Printf("SDL sound: %u sample frames missing\n", RequestedFrames - FrameCount);
73
74         sdlaudiotime += RequestedFrames;
75 }
76
77
78 /*
79 ====================
80 SndSys_Init
81
82 Create "snd_renderbuffer" with the proper sound format if the call is successful
83 May return a suggested format if the requested format isn't available
84 ====================
85 */
86 qboolean SndSys_Init (const snd_format_t* requested, snd_format_t* suggested)
87 {
88         unsigned int buffersize;
89         SDL_AudioSpec wantspec;
90         SDL_AudioSpec obtainspec;
91
92         snd_threaded = false;
93
94         Con_DPrint ("SndSys_Init: using the SDL module\n");
95
96         // Init the SDL Audio subsystem
97         if( SDL_InitSubSystem( SDL_INIT_AUDIO ) ) {
98                 Con_Print( "Initializing the SDL Audio subsystem failed!\n" );
99                 return false;
100         }
101
102         buffersize = (unsigned int)ceil((double)requested->speed / 20.0);
103
104         // Init the SDL Audio subsystem
105         wantspec.callback = Buffer_Callback;
106         wantspec.userdata = NULL;
107         wantspec.freq = requested->speed;
108         wantspec.format = ((requested->width == 1) ? AUDIO_U8 : AUDIO_S16SYS);
109         wantspec.channels = requested->channels;
110         wantspec.samples = CeilPowerOf2(buffersize);  // needs to be a power of 2 on some platforms.
111
112         Con_Printf("Wanted audio Specification:\n"
113                                 "\tChannels  : %i\n"
114                                 "\tFormat    : 0x%X\n"
115                                 "\tFrequency : %i\n"
116                                 "\tSamples   : %i\n",
117                                 wantspec.channels, wantspec.format, wantspec.freq, wantspec.samples);
118
119         if( SDL_OpenAudio( &wantspec, &obtainspec ) )
120         {
121                 Con_Printf( "Failed to open the audio device! (%s)\n", SDL_GetError() );
122                 return false;
123         }
124
125         Con_Printf("Obtained audio specification:\n"
126                                 "\tChannels  : %i\n"
127                                 "\tFormat    : 0x%X\n"
128                                 "\tFrequency : %i\n"
129                                 "\tSamples   : %i\n",
130                                 obtainspec.channels, obtainspec.format, obtainspec.freq, obtainspec.samples);
131
132         // If we haven't obtained what we wanted
133         if (wantspec.freq != obtainspec.freq ||
134                 wantspec.format != obtainspec.format ||
135                 wantspec.channels != obtainspec.channels)
136         {
137                 SDL_CloseAudio();
138
139                 // Pass the obtained format as a suggested format
140                 if (suggested != NULL)
141                 {
142                         suggested->speed = obtainspec.freq;
143                         // FIXME: check the format more carefully. There are plenty of unsupported cases
144                         suggested->width = ((obtainspec.format == AUDIO_U8) ? 1 : 2);
145                         suggested->channels = obtainspec.channels;
146                 }
147
148                 return false;
149         }
150
151         snd_threaded = true;
152
153         snd_renderbuffer = Snd_CreateRingBuffer(requested, 0, NULL);
154         if (snd_channellayout.integer == SND_CHANNELLAYOUT_AUTO)
155         {
156                 int newlayout;
157
158 #ifdef __linux__
159                 newlayout = SND_CHANNELLAYOUT_ALSA;
160 #else
161                 newlayout = SND_CHANNELLAYOUT_STANDARD;
162 #endif
163                 Cvar_SetValueQuick (&snd_channellayout, newlayout);
164         }
165
166         sdlaudiotime = 0;
167         SDL_PauseAudio( false );
168
169         return true;
170 }
171
172
173 /*
174 ====================
175 SndSys_Shutdown
176
177 Stop the sound card, delete "snd_renderbuffer" and free its other resources
178 ====================
179 */
180 void SndSys_Shutdown(void)
181 {
182         SDL_CloseAudio();
183
184         if (snd_renderbuffer != NULL)
185         {
186                 Mem_Free(snd_renderbuffer->ring);
187                 Mem_Free(snd_renderbuffer);
188                 snd_renderbuffer = NULL;
189         }
190 }
191
192
193 /*
194 ====================
195 SndSys_Submit
196
197 Submit the contents of "snd_renderbuffer" to the sound card
198 ====================
199 */
200 void SndSys_Submit (void)
201 {
202         // Nothing to do here (this sound module is callback-based)
203 }
204
205
206 /*
207 ====================
208 SndSys_GetSoundTime
209
210 Returns the number of sample frames consumed since the sound started
211 ====================
212 */
213 unsigned int SndSys_GetSoundTime (void)
214 {
215         return sdlaudiotime;
216 }
217
218
219 /*
220 ====================
221 SndSys_LockRenderBuffer
222
223 Get the exclusive lock on "snd_renderbuffer"
224 ====================
225 */
226 qboolean SndSys_LockRenderBuffer (void)
227 {
228         SDL_LockAudio();
229         return true;
230 }
231
232
233 /*
234 ====================
235 SndSys_UnlockRenderBuffer
236
237 Release the exclusive lock on "snd_renderbuffer"
238 ====================
239 */
240 void SndSys_UnlockRenderBuffer (void)
241 {
242         SDL_UnlockAudio();
243 }