Add missing range checks so we won't overflow the buffers, thanks to Erik Auerswald...
[mplayer/greg.git] / libao2 / ao_sdl.c
blobd2e506cf55130d4e75171306a8c60b8886066aa7
1 /*
2 * ao_sdl.c - libao2 SDLlib Audio Output Driver for MPlayer
4 * This driver is under the same license as MPlayer.
5 * (http://www.mplayerhq.hu)
7 * Copyleft 2001 by Felix Bünemann (atmosfear@users.sf.net)
9 * Thanks to Arpi for nice ringbuffer-code!
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include "config.h"
18 #include "mp_msg.h"
19 #include "help_mp.h"
21 #include "audio_out.h"
22 #include "audio_out_internal.h"
23 #include "libaf/af_format.h"
24 #include <SDL.h>
25 #include "osdep/timer.h"
27 #include "libvo/fastmemcpy.h"
29 static ao_info_t info =
31 "SDLlib audio output",
32 "sdl",
33 "Felix Buenemann <atmosfear@users.sourceforge.net>",
37 LIBAO_EXTERN(sdl)
39 // turn this on if you want to use the slower SDL_MixAudio
40 #undef USE_SDL_INTERNAL_MIXER
42 // Samplesize used by the SDLlib AudioSpec struct
43 #ifdef WIN32
44 #define SAMPLESIZE 2048
45 #else
46 #define SAMPLESIZE 1024
47 #endif
49 #define CHUNK_SIZE 4096
50 #define NUM_CHUNKS 8
51 // This type of ring buffer may never fill up completely, at least
52 // one byte must always be unused.
53 // For performance reasons (alignment etc.) one whole chunk always stays
54 // empty, not only one byte.
55 #define BUFFSIZE ((NUM_CHUNKS + 1) * CHUNK_SIZE)
57 static unsigned char *buffer;
59 // may only be modified by SDL's playback thread or while it is stopped
60 static volatile int read_pos;
61 // may only be modified by mplayer's thread
62 static volatile int write_pos;
63 #ifdef USE_SDL_INTERNAL_MIXER
64 static unsigned char volume=SDL_MIX_MAXVOLUME;
65 #endif
67 // may only be called by mplayer's thread
68 // return value may change between immediately following two calls,
69 // and the real number of free bytes might be larger!
70 static int buf_free() {
71 int free = read_pos - write_pos - CHUNK_SIZE;
72 if (free < 0) free += BUFFSIZE;
73 return free;
76 // may only be called by SDL's playback thread
77 // return value may change between immediately following two calls,
78 // and the real number of buffered bytes might be larger!
79 static int buf_used() {
80 int used = write_pos - read_pos;
81 if (used < 0) used += BUFFSIZE;
82 return used;
85 static int write_buffer(unsigned char* data,int len){
86 int first_len = BUFFSIZE - write_pos;
87 int free = buf_free();
88 if (len > free) len = free;
89 if (first_len > len) first_len = len;
90 // till end of buffer
91 memcpy (&buffer[write_pos], data, first_len);
92 if (len > first_len) { // we have to wrap around
93 // remaining part from beginning of buffer
94 memcpy (buffer, &data[first_len], len - first_len);
96 write_pos = (write_pos + len) % BUFFSIZE;
97 return len;
100 static int read_buffer(unsigned char* data,int len){
101 int first_len = BUFFSIZE - read_pos;
102 int buffered = buf_used();
103 if (len > buffered) len = buffered;
104 if (first_len > len) first_len = len;
105 // till end of buffer
106 #ifdef USE_SDL_INTERNAL_MIXER
107 SDL_MixAudio (data, &buffer[read_pos], first_len, volume);
108 #else
109 memcpy (data, &buffer[read_pos], first_len);
110 #endif
111 if (len > first_len) { // we have to wrap around
112 // remaining part from beginning of buffer
113 #ifdef USE_SDL_INTERNAL_MIXER
114 SDL_MixAudio (&data[first_len], buffer, len - first_len, volume);
115 #else
116 memcpy (&data[first_len], buffer, len - first_len);
117 #endif
119 read_pos = (read_pos + len) % BUFFSIZE;
120 return len;
123 // end ring buffer stuff
125 #if defined(__MINGW32__) || defined(HPUX) || defined(sgi) || (defined(sun) && defined(__svr4__))
126 /* setenv is missing on win32, solaris, IRIX and HPUX */
127 static void setenv(const char *name, const char *val, int _xx)
129 int len = strlen(name) + strlen(val) + 2;
130 char *env = malloc(len);
132 if (env != NULL) {
133 strcpy(env, name);
134 strcat(env, "=");
135 strcat(env, val);
136 putenv(env);
139 #endif
142 // to set/get/query special features/parameters
143 static int control(int cmd,void *arg){
144 #ifdef USE_SDL_INTERNAL_MIXER
145 switch (cmd) {
146 case AOCONTROL_GET_VOLUME:
148 ao_control_vol_t* vol = (ao_control_vol_t*)arg;
149 vol->left = vol->right = volume * 100 / SDL_MIX_MAXVOLUME;
150 return CONTROL_OK;
152 case AOCONTROL_SET_VOLUME:
154 int diff;
155 ao_control_vol_t* vol = (ao_control_vol_t*)arg;
156 diff = (vol->left+vol->right) / 2;
157 volume = diff * SDL_MIX_MAXVOLUME / 100;
158 return CONTROL_OK;
161 #endif
162 return CONTROL_UNKNOWN;
165 // SDL Callback function
166 void outputaudio(void *unused, Uint8 *stream, int len) {
167 //SDL_MixAudio(stream, read_buffer(buffers, len), len, SDL_MIX_MAXVOLUME);
168 //if(!full_buffers) printf("SDL: Buffer underrun!\n");
170 read_buffer(stream, len);
171 //printf("SDL: Full Buffers: %i\n", full_buffers);
174 // open & setup audio device
175 // return: 1=success 0=fail
176 static int init(int rate,int channels,int format,int flags){
178 /* SDL Audio Specifications */
179 SDL_AudioSpec aspec, obtained;
181 /* Allocate ring-buffer memory */
182 buffer = (unsigned char *) malloc(BUFFSIZE);
184 mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_SDL_INFO, rate, (channels > 1) ? "Stereo" : "Mono", af_fmt2str_short(format));
186 if(ao_subdevice) {
187 setenv("SDL_AUDIODRIVER", ao_subdevice, 1);
188 mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_SDL_DriverInfo, ao_subdevice);
191 ao_data.channels=channels;
192 ao_data.samplerate=rate;
193 ao_data.format=format;
195 ao_data.bps=channels*rate;
196 if(format != AF_FORMAT_U8 && format != AF_FORMAT_S8)
197 ao_data.bps*=2;
199 /* The desired audio format (see SDL_AudioSpec) */
200 switch(format) {
201 case AF_FORMAT_U8:
202 aspec.format = AUDIO_U8;
203 break;
204 case AF_FORMAT_S16_LE:
205 aspec.format = AUDIO_S16LSB;
206 break;
207 case AF_FORMAT_S16_BE:
208 aspec.format = AUDIO_S16MSB;
209 break;
210 case AF_FORMAT_S8:
211 aspec.format = AUDIO_S8;
212 break;
213 case AF_FORMAT_U16_LE:
214 aspec.format = AUDIO_U16LSB;
215 break;
216 case AF_FORMAT_U16_BE:
217 aspec.format = AUDIO_U16MSB;
218 break;
219 default:
220 aspec.format = AUDIO_S16LSB;
221 ao_data.format = AF_FORMAT_S16_LE;
222 mp_msg(MSGT_AO,MSGL_WARN,MSGTR_AO_SDL_UnsupportedAudioFmt, format);
225 /* The desired audio frequency in samples-per-second. */
226 aspec.freq = rate;
228 /* Number of channels (mono/stereo) */
229 aspec.channels = channels;
231 /* The desired size of the audio buffer in samples. This number should be a power of two, and may be adjusted by the audio driver to a value more suitable for the hardware. Good values seem to range between 512 and 8192 inclusive, depending on the application and CPU speed. Smaller values yield faster response time, but can lead to underflow if the application is doing heavy processing and cannot fill the audio buffer in time. A stereo sample consists of both right and left channels in LR ordering. Note that the number of samples is directly related to time by the following formula: ms = (samples*1000)/freq */
232 aspec.samples = SAMPLESIZE;
234 /* This should be set to a function that will be called when the audio device is ready for more data. It is passed a pointer to the audio buffer, and the length in bytes of the audio buffer. This function usually runs in a separate thread, and so you should protect data structures that it accesses by calling SDL_LockAudio and SDL_UnlockAudio in your code. The callback prototype is:
235 void callback(void *userdata, Uint8 *stream, int len); userdata is the pointer stored in userdata field of the SDL_AudioSpec. stream is a pointer to the audio buffer you want to fill with information and len is the length of the audio buffer in bytes. */
236 aspec.callback = outputaudio;
238 /* This pointer is passed as the first parameter to the callback function. */
239 aspec.userdata = NULL;
241 /* initialize the SDL Audio system */
242 if (SDL_Init (SDL_INIT_AUDIO/*|SDL_INIT_NOPARACHUTE*/)) {
243 mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_SDL_CantInit, SDL_GetError());
244 return 0;
247 /* Open the audio device and start playing sound! */
248 if(SDL_OpenAudio(&aspec, &obtained) < 0) {
249 mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_SDL_CantOpenAudio, SDL_GetError());
250 return(0);
253 /* did we got what we wanted ? */
254 ao_data.channels=obtained.channels;
255 ao_data.samplerate=obtained.freq;
257 switch(obtained.format) {
258 case AUDIO_U8 :
259 ao_data.format = AF_FORMAT_U8;
260 break;
261 case AUDIO_S16LSB :
262 ao_data.format = AF_FORMAT_S16_LE;
263 break;
264 case AUDIO_S16MSB :
265 ao_data.format = AF_FORMAT_S16_BE;
266 break;
267 case AUDIO_S8 :
268 ao_data.format = AF_FORMAT_S8;
269 break;
270 case AUDIO_U16LSB :
271 ao_data.format = AF_FORMAT_U16_LE;
272 break;
273 case AUDIO_U16MSB :
274 ao_data.format = AF_FORMAT_U16_BE;
275 break;
276 default:
277 mp_msg(MSGT_AO,MSGL_WARN,MSGTR_AO_SDL_UnsupportedAudioFmt, obtained.format);
278 return 0;
281 mp_msg(MSGT_AO,MSGL_V,"SDL: buf size = %d\n",obtained.size);
282 ao_data.buffersize=obtained.size;
283 ao_data.outburst = CHUNK_SIZE;
285 reset();
286 /* unsilence audio, if callback is ready */
287 SDL_PauseAudio(0);
289 return 1;
292 // close audio device
293 static void uninit(int immed){
294 mp_msg(MSGT_AO,MSGL_V,"SDL: Audio Subsystem shutting down!\n");
295 if (!immed)
296 usec_sleep(get_delay() * 1000 * 1000);
297 SDL_CloseAudio();
298 SDL_QuitSubSystem(SDL_INIT_AUDIO);
301 // stop playing and empty buffers (for seeking/pause)
302 static void reset(){
304 //printf("SDL: reset called!\n");
306 SDL_PauseAudio(1);
307 /* Reset ring-buffer state */
308 read_pos = 0;
309 write_pos = 0;
310 SDL_PauseAudio(0);
313 // stop playing, keep buffers (for pause)
314 static void audio_pause()
317 //printf("SDL: audio_pause called!\n");
318 SDL_PauseAudio(1);
322 // resume playing, after audio_pause()
323 static void audio_resume()
325 //printf("SDL: audio_resume called!\n");
326 SDL_PauseAudio(0);
330 // return: how many bytes can be played without blocking
331 static int get_space(){
332 return buf_free();
335 // plays 'len' bytes of 'data'
336 // it should round it down to outburst*n
337 // return: number of bytes played
338 static int play(void* data,int len,int flags){
340 len = (len/ao_data.outburst)*ao_data.outburst;
341 #if 0
342 int ret;
344 /* Audio locking prohibits call of outputaudio */
345 SDL_LockAudio();
346 // copy audio stream into ring-buffer
347 ret = write_buffer(data, len);
348 SDL_UnlockAudio();
350 return ret;
351 #else
352 return write_buffer(data, len);
353 #endif
356 // return: delay in seconds between first and last sample in buffer
357 static float get_delay(){
358 int buffered = BUFFSIZE - CHUNK_SIZE - buf_free(); // could be less
359 return (float)(buffered + ao_data.buffersize)/(float)ao_data.bps;