xref: /qemu/audio/sdlaudio.c (revision 138ca49a)
1 /*
2  * QEMU SDL audio driver
3  *
4  * Copyright (c) 2004-2005 Vassili Karpov (malc)
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include <SDL.h>
27 #include <SDL_thread.h>
28 #include "qemu/module.h"
29 #include "audio.h"
30 
31 #ifndef _WIN32
32 #ifdef __sun__
33 #define _POSIX_PTHREAD_SEMANTICS 1
34 #elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
35 #include <pthread.h>
36 #endif
37 #endif
38 
39 #define AUDIO_CAP "sdl"
40 #include "audio_int.h"
41 
42 typedef struct SDLVoiceOut {
43     HWVoiceOut hw;
44     int exit;
45     int initialized;
46     Audiodev *dev;
47     SDL_AudioDeviceID devid;
48 } SDLVoiceOut;
49 
50 typedef struct SDLVoiceIn {
51     HWVoiceIn hw;
52     int exit;
53     int initialized;
54     Audiodev *dev;
55     SDL_AudioDeviceID devid;
56 } SDLVoiceIn;
57 
58 static void GCC_FMT_ATTR (1, 2) sdl_logerr (const char *fmt, ...)
59 {
60     va_list ap;
61 
62     va_start (ap, fmt);
63     AUD_vlog (AUDIO_CAP, fmt, ap);
64     va_end (ap);
65 
66     AUD_log (AUDIO_CAP, "Reason: %s\n", SDL_GetError ());
67 }
68 
69 static int aud_to_sdlfmt (AudioFormat fmt)
70 {
71     switch (fmt) {
72     case AUDIO_FORMAT_S8:
73         return AUDIO_S8;
74 
75     case AUDIO_FORMAT_U8:
76         return AUDIO_U8;
77 
78     case AUDIO_FORMAT_S16:
79         return AUDIO_S16LSB;
80 
81     case AUDIO_FORMAT_U16:
82         return AUDIO_U16LSB;
83 
84     case AUDIO_FORMAT_S32:
85         return AUDIO_S32LSB;
86 
87     /* no unsigned 32-bit support in SDL */
88 
89     case AUDIO_FORMAT_F32:
90         return AUDIO_F32LSB;
91 
92     default:
93         dolog ("Internal logic error: Bad audio format %d\n", fmt);
94 #ifdef DEBUG_AUDIO
95         abort ();
96 #endif
97         return AUDIO_U8;
98     }
99 }
100 
101 static int sdl_to_audfmt(int sdlfmt, AudioFormat *fmt, int *endianness)
102 {
103     switch (sdlfmt) {
104     case AUDIO_S8:
105         *endianness = 0;
106         *fmt = AUDIO_FORMAT_S8;
107         break;
108 
109     case AUDIO_U8:
110         *endianness = 0;
111         *fmt = AUDIO_FORMAT_U8;
112         break;
113 
114     case AUDIO_S16LSB:
115         *endianness = 0;
116         *fmt = AUDIO_FORMAT_S16;
117         break;
118 
119     case AUDIO_U16LSB:
120         *endianness = 0;
121         *fmt = AUDIO_FORMAT_U16;
122         break;
123 
124     case AUDIO_S16MSB:
125         *endianness = 1;
126         *fmt = AUDIO_FORMAT_S16;
127         break;
128 
129     case AUDIO_U16MSB:
130         *endianness = 1;
131         *fmt = AUDIO_FORMAT_U16;
132         break;
133 
134     case AUDIO_S32LSB:
135         *endianness = 0;
136         *fmt = AUDIO_FORMAT_S32;
137         break;
138 
139     case AUDIO_S32MSB:
140         *endianness = 1;
141         *fmt = AUDIO_FORMAT_S32;
142         break;
143 
144     case AUDIO_F32LSB:
145         *endianness = 0;
146         *fmt = AUDIO_FORMAT_F32;
147         break;
148 
149     case AUDIO_F32MSB:
150         *endianness = 1;
151         *fmt = AUDIO_FORMAT_F32;
152         break;
153 
154     default:
155         dolog ("Unrecognized SDL audio format %d\n", sdlfmt);
156         return -1;
157     }
158 
159     return 0;
160 }
161 
162 static SDL_AudioDeviceID sdl_open(SDL_AudioSpec *req, SDL_AudioSpec *obt,
163                                   int rec)
164 {
165     SDL_AudioDeviceID devid;
166 #ifndef _WIN32
167     int err;
168     sigset_t new, old;
169 
170     /* Make sure potential threads created by SDL don't hog signals.  */
171     err = sigfillset (&new);
172     if (err) {
173         dolog ("sdl_open: sigfillset failed: %s\n", strerror (errno));
174         return 0;
175     }
176     err = pthread_sigmask (SIG_BLOCK, &new, &old);
177     if (err) {
178         dolog ("sdl_open: pthread_sigmask failed: %s\n", strerror (err));
179         return 0;
180     }
181 #endif
182 
183     devid = SDL_OpenAudioDevice(NULL, rec, req, obt, 0);
184     if (!devid) {
185         sdl_logerr("SDL_OpenAudioDevice for %s failed\n",
186                    rec ? "recording" : "playback");
187     }
188 
189 #ifndef _WIN32
190     err = pthread_sigmask (SIG_SETMASK, &old, NULL);
191     if (err) {
192         dolog ("sdl_open: pthread_sigmask (restore) failed: %s\n",
193                strerror (errno));
194         /* We have failed to restore original signal mask, all bets are off,
195            so exit the process */
196         exit (EXIT_FAILURE);
197     }
198 #endif
199     return devid;
200 }
201 
202 static void sdl_close_out(SDLVoiceOut *sdl)
203 {
204     if (sdl->initialized) {
205         SDL_LockAudioDevice(sdl->devid);
206         sdl->exit = 1;
207         SDL_UnlockAudioDevice(sdl->devid);
208         SDL_PauseAudioDevice(sdl->devid, 1);
209         sdl->initialized = 0;
210     }
211     if (sdl->devid) {
212         SDL_CloseAudioDevice(sdl->devid);
213         sdl->devid = 0;
214     }
215 }
216 
217 static void sdl_callback_out(void *opaque, Uint8 *buf, int len)
218 {
219     SDLVoiceOut *sdl = opaque;
220     HWVoiceOut *hw = &sdl->hw;
221 
222     if (!sdl->exit) {
223 
224         /* dolog("callback_out: len=%d avail=%zu\n", len, hw->pending_emul); */
225 
226         while (hw->pending_emul && len) {
227             size_t write_len;
228             ssize_t start = (ssize_t)hw->pos_emul - hw->pending_emul;
229             if (start < 0) {
230                 start += hw->size_emul;
231             }
232             assert(start >= 0 && start < hw->size_emul);
233 
234             write_len = MIN(MIN(hw->pending_emul, len),
235                             hw->size_emul - start);
236 
237             memcpy(buf, hw->buf_emul + start, write_len);
238             hw->pending_emul -= write_len;
239             len -= write_len;
240             buf += write_len;
241         }
242     }
243 
244     /* clear remaining buffer that we couldn't fill with data */
245     if (len) {
246         audio_pcm_info_clear_buf(&hw->info, buf,
247                                  len / hw->info.bytes_per_frame);
248     }
249 }
250 
251 static void sdl_close_in(SDLVoiceIn *sdl)
252 {
253     if (sdl->initialized) {
254         SDL_LockAudioDevice(sdl->devid);
255         sdl->exit = 1;
256         SDL_UnlockAudioDevice(sdl->devid);
257         SDL_PauseAudioDevice(sdl->devid, 1);
258         sdl->initialized = 0;
259     }
260     if (sdl->devid) {
261         SDL_CloseAudioDevice(sdl->devid);
262         sdl->devid = 0;
263     }
264 }
265 
266 static void sdl_callback_in(void *opaque, Uint8 *buf, int len)
267 {
268     SDLVoiceIn *sdl = opaque;
269     HWVoiceIn *hw = &sdl->hw;
270 
271     if (sdl->exit) {
272         return;
273     }
274 
275     /* dolog("callback_in: len=%d pending=%zu\n", len, hw->pending_emul); */
276 
277     while (hw->pending_emul < hw->size_emul && len) {
278         size_t read_len = MIN(len, MIN(hw->size_emul - hw->pos_emul,
279                                        hw->size_emul - hw->pending_emul));
280 
281         memcpy(hw->buf_emul + hw->pos_emul, buf, read_len);
282 
283         hw->pending_emul += read_len;
284         hw->pos_emul = (hw->pos_emul + read_len) % hw->size_emul;
285         len -= read_len;
286         buf += read_len;
287     }
288 }
289 
290 #define SDL_WRAPPER_FUNC(name, ret_type, args_decl, args, dir) \
291     static ret_type glue(sdl_, name)args_decl                  \
292     {                                                          \
293         ret_type ret;                                          \
294         glue(SDLVoice, dir) *sdl = (glue(SDLVoice, dir) *)hw;  \
295                                                                \
296         SDL_LockAudioDevice(sdl->devid);                       \
297         ret = glue(audio_generic_, name)args;                  \
298         SDL_UnlockAudioDevice(sdl->devid);                     \
299                                                                \
300         return ret;                                            \
301     }
302 
303 #define SDL_WRAPPER_VOID_FUNC(name, args_decl, args, dir)      \
304     static void glue(sdl_, name)args_decl                      \
305     {                                                          \
306         glue(SDLVoice, dir) *sdl = (glue(SDLVoice, dir) *)hw;  \
307                                                                \
308         SDL_LockAudioDevice(sdl->devid);                       \
309         glue(audio_generic_, name)args;                        \
310         SDL_UnlockAudioDevice(sdl->devid);                     \
311     }
312 
313 SDL_WRAPPER_FUNC(get_buffer_out, void *, (HWVoiceOut *hw, size_t *size),
314                  (hw, size), Out)
315 SDL_WRAPPER_FUNC(put_buffer_out, size_t,
316                  (HWVoiceOut *hw, void *buf, size_t size), (hw, buf, size), Out)
317 SDL_WRAPPER_FUNC(write, size_t,
318                  (HWVoiceOut *hw, void *buf, size_t size), (hw, buf, size), Out)
319 SDL_WRAPPER_FUNC(read, size_t, (HWVoiceIn *hw, void *buf, size_t size),
320                  (hw, buf, size), In)
321 SDL_WRAPPER_FUNC(get_buffer_in, void *, (HWVoiceIn *hw, size_t *size),
322                  (hw, size), In)
323 SDL_WRAPPER_VOID_FUNC(put_buffer_in, (HWVoiceIn *hw, void *buf, size_t size),
324                       (hw, buf, size), In)
325 #undef SDL_WRAPPER_FUNC
326 #undef SDL_WRAPPER_VOID_FUNC
327 
328 static void sdl_fini_out(HWVoiceOut *hw)
329 {
330     SDLVoiceOut *sdl = (SDLVoiceOut *)hw;
331 
332     sdl_close_out(sdl);
333 }
334 
335 static int sdl_init_out(HWVoiceOut *hw, struct audsettings *as,
336                         void *drv_opaque)
337 {
338     SDLVoiceOut *sdl = (SDLVoiceOut *)hw;
339     SDL_AudioSpec req, obt;
340     int endianness;
341     int err;
342     AudioFormat effective_fmt;
343     Audiodev *dev = drv_opaque;
344     AudiodevSdlPerDirectionOptions *spdo = dev->u.sdl.out;
345     struct audsettings obt_as;
346 
347     req.freq = as->freq;
348     req.format = aud_to_sdlfmt (as->fmt);
349     req.channels = as->nchannels;
350     /*
351      * This is wrong. SDL samples are QEMU frames. The buffer size will be
352      * the requested buffer size multiplied by the number of channels.
353      */
354     req.samples = audio_buffer_samples(
355         qapi_AudiodevSdlPerDirectionOptions_base(spdo), as, 11610);
356     req.callback = sdl_callback_out;
357     req.userdata = sdl;
358 
359     sdl->dev = dev;
360     sdl->devid = sdl_open(&req, &obt, 0);
361     if (!sdl->devid) {
362         return -1;
363     }
364 
365     err = sdl_to_audfmt(obt.format, &effective_fmt, &endianness);
366     if (err) {
367         sdl_close_out(sdl);
368         return -1;
369     }
370 
371     obt_as.freq = obt.freq;
372     obt_as.nchannels = obt.channels;
373     obt_as.fmt = effective_fmt;
374     obt_as.endianness = endianness;
375 
376     audio_pcm_init_info (&hw->info, &obt_as);
377     hw->samples = (spdo->has_buffer_count ? spdo->buffer_count : 4) *
378         obt.samples;
379 
380     sdl->initialized = 1;
381     sdl->exit = 0;
382     return 0;
383 }
384 
385 static void sdl_enable_out(HWVoiceOut *hw, bool enable)
386 {
387     SDLVoiceOut *sdl = (SDLVoiceOut *)hw;
388 
389     SDL_PauseAudioDevice(sdl->devid, !enable);
390 }
391 
392 static void sdl_fini_in(HWVoiceIn *hw)
393 {
394     SDLVoiceIn *sdl = (SDLVoiceIn *)hw;
395 
396     sdl_close_in(sdl);
397 }
398 
399 static int sdl_init_in(HWVoiceIn *hw, audsettings *as, void *drv_opaque)
400 {
401     SDLVoiceIn *sdl = (SDLVoiceIn *)hw;
402     SDL_AudioSpec req, obt;
403     int endianness;
404     int err;
405     AudioFormat effective_fmt;
406     Audiodev *dev = drv_opaque;
407     AudiodevSdlPerDirectionOptions *spdo = dev->u.sdl.in;
408     struct audsettings obt_as;
409 
410     req.freq = as->freq;
411     req.format = aud_to_sdlfmt(as->fmt);
412     req.channels = as->nchannels;
413     /* SDL samples are QEMU frames */
414     req.samples = audio_buffer_frames(
415         qapi_AudiodevSdlPerDirectionOptions_base(spdo), as, 11610);
416     req.callback = sdl_callback_in;
417     req.userdata = sdl;
418 
419     sdl->dev = dev;
420     sdl->devid = sdl_open(&req, &obt, 1);
421     if (!sdl->devid) {
422         return -1;
423     }
424 
425     err = sdl_to_audfmt(obt.format, &effective_fmt, &endianness);
426     if (err) {
427         sdl_close_in(sdl);
428         return -1;
429     }
430 
431     obt_as.freq = obt.freq;
432     obt_as.nchannels = obt.channels;
433     obt_as.fmt = effective_fmt;
434     obt_as.endianness = endianness;
435 
436     audio_pcm_init_info(&hw->info, &obt_as);
437     hw->samples = (spdo->has_buffer_count ? spdo->buffer_count : 4) *
438         obt.samples;
439     hw->size_emul = hw->samples * hw->info.bytes_per_frame;
440     hw->buf_emul = g_malloc(hw->size_emul);
441     hw->pos_emul = hw->pending_emul = 0;
442 
443     sdl->initialized = 1;
444     sdl->exit = 0;
445     return 0;
446 }
447 
448 static void sdl_enable_in(HWVoiceIn *hw, bool enable)
449 {
450     SDLVoiceIn *sdl = (SDLVoiceIn *)hw;
451 
452     SDL_PauseAudioDevice(sdl->devid, !enable);
453 }
454 
455 static void *sdl_audio_init(Audiodev *dev)
456 {
457     if (SDL_InitSubSystem (SDL_INIT_AUDIO)) {
458         sdl_logerr ("SDL failed to initialize audio subsystem\n");
459         return NULL;
460     }
461 
462     return dev;
463 }
464 
465 static void sdl_audio_fini (void *opaque)
466 {
467     SDL_QuitSubSystem (SDL_INIT_AUDIO);
468 }
469 
470 static struct audio_pcm_ops sdl_pcm_ops = {
471     .init_out = sdl_init_out,
472     .fini_out = sdl_fini_out,
473   /* wrapper for audio_generic_write */
474     .write    = sdl_write,
475   /* wrapper for audio_generic_get_buffer_out */
476     .get_buffer_out = sdl_get_buffer_out,
477   /* wrapper for audio_generic_put_buffer_out */
478     .put_buffer_out = sdl_put_buffer_out,
479     .enable_out = sdl_enable_out,
480     .init_in = sdl_init_in,
481     .fini_in = sdl_fini_in,
482   /* wrapper for audio_generic_read */
483     .read = sdl_read,
484   /* wrapper for audio_generic_get_buffer_in */
485     .get_buffer_in = sdl_get_buffer_in,
486   /* wrapper for audio_generic_put_buffer_in */
487     .put_buffer_in = sdl_put_buffer_in,
488     .enable_in = sdl_enable_in,
489 };
490 
491 static struct audio_driver sdl_audio_driver = {
492     .name           = "sdl",
493     .descr          = "SDL http://www.libsdl.org",
494     .init           = sdl_audio_init,
495     .fini           = sdl_audio_fini,
496     .pcm_ops        = &sdl_pcm_ops,
497     .can_be_default = 1,
498     .max_voices_out = INT_MAX,
499     .max_voices_in  = INT_MAX,
500     .voice_size_out = sizeof(SDLVoiceOut),
501     .voice_size_in  = sizeof(SDLVoiceIn),
502 };
503 
504 static void register_audio_sdl(void)
505 {
506     audio_driver_register(&sdl_audio_driver);
507 }
508 type_init(register_audio_sdl);
509