Debian Codegraph @

src/libout123/modules/sdl.c

raw
1 /*
2 sdl: audio output via SDL cross-platform API
3
4 copyright 2006-2016 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Nicholas J. Humfrey
7 */
8
9 /* Want usleep */
10 #define _XOPEN_SOURCE 500
11 #define _DEFAULT_SOURCE
12
13 #include "../out123_int.h"
14 #include <math.h>
15
16 #include <SDL.h>
17
18 #ifdef WIN32
19 #include <windows.h>
20 #endif
21
22 /* Including the sfifo code locally, to avoid module linkage issues. */
23 #define SFIFO_STATIC
24 #include "../sfifo.c"
25
26 #include "../../common/debug.h"
27
28
29 #define SAMPLE_SIZE (2)
30 #define FRAMES_PER_BUFFER (256)
31 /* Performance of SDL with ALSA is a bit of a mystery to me. Regardless
32 of buffer size here, I just cannot avoid buffer underruns on my system.
33 SDL always chooses 1024x2 periods, which seems to be just not quite
34 enough on the Thinkpad:-/ Choosing 0.2 s as a plentiful default instead
35 of 0.5 s which is just a lie. */
36 #define FIFO_DURATION (ao->device_buffer > 0. ? ao->device_buffer : 0.2)
37 #define BUFFER_SAMPLES ((FIFO_DURATION*ao->rate)/2)
38
39 struct handle
40 {
41 int finished; /* A flag for communicating end, one-way. */
42 sfifo_t fifo;
43 };
44
45 /* Some busy waiting. Proper stuff like semaphores might add
46 dependencies (POSIX) that the platform does not know. */
47 static void ms_sleep(int milliseconds)
48 {
49 #ifdef WIN32
50 Sleep(milliseconds);
51 #else
52 usleep(milliseconds*1000);
53 #endif
54 }
55
56 /* The audio function callback takes the following parameters:
57 stream: A pointer to the audio buffer to be filled
58 len: The length (in bytes) of the audio buffer
59 */
60 static void audio_callback_sdl(void *udata, Uint8 *stream, int len)
61 {
62 out123_handle *ao = (out123_handle*)udata;
63 struct handle *sh = (struct handle*)ao->userptr;
64 sfifo_t *fifo = &sh->fifo;
65 int bytes_read;
66 int bytes_avail;
67
68 /* Until the finished flag is set, we will wait for more.
69 As the exact value does not matter and late detection of
70 a change is kindof OK, I do not see a thread safety problem here. */
71 while((bytes_avail = sfifo_used(fifo)) < len && !sh->finished)
72 {
73 int ms = (len-bytes_avail)/ao->framesize*1000/ao->rate;
74 debug1("waiting for more input, %d ms missing", ms);
75 ms_sleep(ms/10);
76 }
77 /* Read audio from FIFO to SDL's buffer */
78 if(bytes_avail > len)
79 bytes_avail = len;
80 bytes_read = sfifo_read( fifo, stream, bytes_avail );
81 if(bytes_read != bytes_avail)
82 warning2("Error reading from the FIFO (wanted=%d, bytes_read=%d).\n"
83 , bytes_avail, bytes_read);
84 if(bytes_read < 0)
85 bytes_read = 0;
86 /* Ensure that any remaining space is filled with zero bytes. */
87 if(bytes_read < len)
88 memset(stream+bytes_read, 0, len-bytes_read);
89 }
90
91 static int open_sdl(out123_handle *ao)
92 {
93 struct handle *sh = (struct handle*)ao->userptr;
94 sfifo_t *fifo = &sh->fifo;
95
96 /* Open an audio I/O stream. */
97 if (ao->rate > 0 && ao->channels >0 ) {
98 size_t ringbuffer_len;
99 SDL_AudioSpec wanted;
100
101 /* L16 uncompressed audio data, using 16-bit signed representation in twos
102 complement notation - system endian-ness. */
103 wanted.format = AUDIO_S16SYS;
104 /* Seems reasonable to demand a buffer size related to the device
105 buffer. */
106 wanted.samples = BUFFER_SAMPLES;
107 wanted.callback = audio_callback_sdl;
108 wanted.userdata = ao;
109 wanted.channels = ao->channels;
110 wanted.freq = ao->rate;
111
112 sh->finished = 0;
113 /* Open the audio device, forcing the desired format
114 Actually, it is still subject to constraints by hardware.
115 Need to have sample rate checked beforehand! SDL will
116 happily play 22 kHz files with 44 kHz hardware rate!
117 Same with channel count. No conversion. The manual is a bit
118 misleading on that (only talking about sample format, I guess). */
119 if ( SDL_OpenAudio(&wanted, NULL) )
120 {
121 if(!AOQUIET)
122 error1("Couldn't open SDL audio: %s\n", SDL_GetError());
123 return -1;
124 }
125
126 /* Initialise FIFO */
127 ringbuffer_len = ao->rate * FIFO_DURATION * SAMPLE_SIZE *ao->channels;
128 debug2( "Allocating %d byte ring-buffer (%f seconds)", (int)ringbuffer_len, (float)FIFO_DURATION);
129 if (sfifo_init( fifo, ringbuffer_len ) && !AOQUIET)
130 error1( "Failed to initialise FIFO of size %d bytes", (int)ringbuffer_len );
131 }
132
133 return(0);
134 }
135
136
137 static int get_formats_sdl(out123_handle *ao)
138 {
139 /* Got no better idea than to just take 16 bit and run with it */
140 return MPG123_ENC_SIGNED_16;
141 #if 0
142 /*
143 This code would "properly" test audio format support.
144 But thing is, SDL will always say yes and amen to everything, but it takes
145 an awful amount of time to get all the variants tested (about 2 seconds,
146 for example). I have seen SDL builds that do proper format conversion
147 behind your back, I have seen builds that do not. Every build seems to
148 claim that it does, though. Just hope you're lucky and your SDL works.
149 Otherwise, use a proper audio output API.
150 */
151 SDL_AudioSpec wanted, got;
152
153 /* Only implemented Signed 16-bit audio for now.
154 The SDL manual doesn't suggest more interesting formats
155 like S24 or S32 anyway. */
156 wanted.format = AUDIO_S16SYS;
157 wanted.samples = BUFFER_SAMPLES;
158 wanted.callback = audio_callback_sdl;
159 wanted.userdata = ao;
160 wanted.channels = ao->channels;
161 wanted.freq = ao->rate;
162
163 if(SDL_OpenAudio(&wanted, &got)) return 0;
164 SDL_CloseAudio();
165 fprintf(stderr, "wanted rate: %li got rate %li\n", (long)wanted.freq, (long)got.freq);
166 return (got.freq == ao->rate && got.channels == ao->channels)
167 ? MPG123_ENC_SIGNED_16
168 : 0;
169 #endif
170 }
171
172
173 static int write_sdl(out123_handle *ao, unsigned char *buf, int len)
174 {
175 struct handle *sh = (struct handle*)ao->userptr;
176 sfifo_t *fifo = &sh->fifo;
177 int len_remain = len;
178
179 /* Some busy waiting, but feed what is possible. */
180 while(len_remain) /* Note: input len is multiple of framesize! */
181 {
182 int block = sfifo_space(fifo);
183 block -= block % ao->framesize;
184 if(block > len_remain)
185 block = len_remain;
186 if(block)
187 {
188 sfifo_write(fifo, buf, block);
189 len_remain -= block;
190 buf += block;
191 /* Unpause once the buffer is 50% full */
192 if (sfifo_used(fifo) > (sfifo_size(fifo)/2) )
193 SDL_PauseAudio(0);
194 }
195 if(len_remain)
196 {
197 debug1("Still need to write %d bytes, sleeping a bit.", len_remain);
198 ms_sleep(0.1*FIFO_DURATION*1000);
199 }
200 }
201 return len;
202 }
203
204 static int close_sdl(out123_handle *ao)
205 {
206 int stuff;
207 struct handle *sh = (struct handle*)ao->userptr;
208 sfifo_t *fifo = &sh->fifo;
209
210 debug1("close_sdl with %d", sfifo_used(fifo));
211 sh->finished = 1;
212 /* Wait at least until SDL emptied the FIFO. */
213 while((stuff = sfifo_used(fifo))>0)
214 {
215 int ms = stuff/ao->framesize*1000/ao->rate;
216 debug1("still stuff for about %i ms there", ms);
217 ms_sleep(ms/2);
218 }
219
220 SDL_CloseAudio();
221
222 /* Free up the memory used by the FIFO */
223 sfifo_close( fifo );
224
225 return 0;
226 }
227
228 static void flush_sdl(out123_handle *ao)
229 {
230 struct handle *sh = (struct handle*)ao->userptr;
231
232 SDL_PauseAudio(1);
233 sfifo_flush(&sh->fifo);
234 }
235
236 /* You can only rely on that being called after successful init_sdl()!
237 And sdl_close() should be called before to free the sfifo. */
238 static void deinit_sdl(out123_handle* ao)
239 {
240 /* Free up memory */
241 if (ao->userptr) {
242 free( ao->userptr );
243 ao->userptr = NULL;
244 }
245
246 /* Shut down SDL */
247 SDL_Quit();
248 }
249
250 /* Remember: If this returns failure, no additional cleanup happens.
251 Resources must be freed here. */
252 static int init_sdl(out123_handle* ao)
253 {
254 struct handle *sh;
255
256 if (ao==NULL) return -1;
257
258 /* Set callbacks */
259 ao->open = open_sdl;
260 ao->flush = flush_sdl;
261 ao->write = write_sdl;
262 ao->get_formats = get_formats_sdl;
263 ao->close = close_sdl;
264 ao->deinit = deinit_sdl;
265
266 /* Initialise SDL */
267 if (SDL_Init( SDL_INIT_AUDIO ) )
268 {
269 if(!AOQUIET)
270 error1("Failed to initialise SDL: %s\n", SDL_GetError());
271 return -1;
272 }
273 /* Allocate memory _after_ checking that SDL is available, so we do not
274 have to free after failure. */
275 ao->userptr = sh = malloc( sizeof(struct handle) );
276 if (ao->userptr==NULL)
277 {
278 if(!AOQUIET)
279 error( "Failed to allocated memory for FIFO structure" );
280 return -1;
281 }
282 sh->finished = 0;
283 /* Not exactly necessary; only for somewhat safe sdl_close after a fake
284 sdl_open(). */
285 memset( &sh->fifo, 0, sizeof(sfifo_t) );
286
287 /* Success */
288 return 0;
289 }
290
291
292 /*
293 Module information data structure
294 */
295 mpg123_module_t mpg123_output_module_info = {
296 /* api_version */ MPG123_MODULE_API_VERSION,
297 /* name */ "sdl",
298 /* description */ "Output audio using SDL (Simple DirectMedia Layer).",
299 /* revision */ "$Rev:$",
300 /* handle */ NULL,
301
302 /* init_output */ init_sdl,
303 };