src/audio/SDL_audio.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 29 Oct 2006 14:45:46 +0000
changeset 2063 dea73e1d07b0
parent 2060 866052b01ee5
child 2070 dbfa1ebd73b0
permissions -rw-r--r--
Merged Ryan's fix, in case we need it later.
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2006 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 /* Allow access to a raw mixing buffer */
    25 
    26 #include "SDL.h"
    27 #include "SDL_audio_c.h"
    28 #include "SDL_audiomem.h"
    29 #include "SDL_sysaudio.h"
    30 
    31 #define _THIS	SDL_AudioDevice *this
    32 
    33 static SDL_AudioDriver current_audio;
    34 static SDL_AudioDevice *open_devices[16];
    35 
    36 /* !!! FIXME: These are wordy and unlocalized... */
    37 #define DEFAULT_OUTPUT_DEVNAME "System audio output device"
    38 #define DEFAULT_INPUT_DEVNAME "System audio capture device"
    39 
    40 
    41 /*
    42  * Not all of these will be compiled and linked in, but it's convenient
    43  *  to have a complete list here and saves yet-another block of #ifdefs...
    44  *  Please see bootstrap[], below, for the actual #ifdef mess.
    45  */
    46 extern AudioBootStrap BSD_AUDIO_bootstrap;
    47 extern AudioBootStrap DSP_bootstrap;
    48 extern AudioBootStrap DMA_bootstrap;
    49 extern AudioBootStrap ALSA_bootstrap;
    50 extern AudioBootStrap QNXNTOAUDIO_bootstrap;
    51 extern AudioBootStrap SUNAUDIO_bootstrap;
    52 extern AudioBootStrap DMEDIA_bootstrap;
    53 extern AudioBootStrap ARTS_bootstrap;
    54 extern AudioBootStrap ESD_bootstrap;
    55 extern AudioBootStrap NAS_bootstrap;
    56 extern AudioBootStrap DSOUND_bootstrap;
    57 extern AudioBootStrap WAVEOUT_bootstrap;
    58 extern AudioBootStrap PAUDIO_bootstrap;
    59 extern AudioBootStrap BEOSAUDIO_bootstrap;
    60 extern AudioBootStrap COREAUDIO_bootstrap;
    61 extern AudioBootStrap SNDMGR_bootstrap;
    62 extern AudioBootStrap MINTAUDIO_GSXB_bootstrap;
    63 extern AudioBootStrap MINTAUDIO_MCSN_bootstrap;
    64 extern AudioBootStrap MINTAUDIO_STFA_bootstrap;
    65 extern AudioBootStrap MINTAUDIO_XBIOS_bootstrap;
    66 extern AudioBootStrap MINTAUDIO_DMA8_bootstrap;
    67 extern AudioBootStrap DISKAUD_bootstrap;
    68 extern AudioBootStrap DUMMYAUD_bootstrap;
    69 extern AudioBootStrap DCAUD_bootstrap;
    70 extern AudioBootStrap MMEAUDIO_bootstrap;
    71 extern AudioBootStrap DART_bootstrap;
    72 
    73 
    74 /* Available audio drivers */
    75 static AudioBootStrap *bootstrap[] = {
    76 #if SDL_AUDIO_DRIVER_BSD
    77     &BSD_AUDIO_bootstrap,
    78 #endif
    79 #if SDL_AUDIO_DRIVER_OSS
    80     &DSP_bootstrap,
    81     &DMA_bootstrap,
    82 #endif
    83 #if SDL_AUDIO_DRIVER_ALSA
    84     &ALSA_bootstrap,
    85 #endif
    86 #if SDL_AUDIO_DRIVER_QNXNTO
    87     &QNXNTOAUDIO_bootstrap,
    88 #endif
    89 #if SDL_AUDIO_DRIVER_SUNAUDIO
    90     &SUNAUDIO_bootstrap,
    91 #endif
    92 #if SDL_AUDIO_DRIVER_DMEDIA
    93     &DMEDIA_bootstrap,
    94 #endif
    95 #if SDL_AUDIO_DRIVER_ARTS
    96     &ARTS_bootstrap,
    97 #endif
    98 #if SDL_AUDIO_DRIVER_ESD
    99     &ESD_bootstrap,
   100 #endif
   101 #if SDL_AUDIO_DRIVER_NAS
   102     &NAS_bootstrap,
   103 #endif
   104 #if SDL_AUDIO_DRIVER_DSOUND
   105     &DSOUND_bootstrap,
   106 #endif
   107 #if SDL_AUDIO_DRIVER_WAVEOUT
   108     &WAVEOUT_bootstrap,
   109 #endif
   110 #if SDL_AUDIO_DRIVER_PAUDIO
   111     &PAUDIO_bootstrap,
   112 #endif
   113 #if SDL_AUDIO_DRIVER_BEOSAUDIO
   114     &BEOSAUDIO_bootstrap,
   115 #endif
   116 #if SDL_AUDIO_DRIVER_COREAUDIO
   117     &COREAUDIO_bootstrap,
   118 #endif
   119 #if SDL_AUDIO_DRIVER_SNDMGR
   120     &SNDMGR_bootstrap,
   121 #endif
   122 #if SDL_AUDIO_DRIVER_MINT
   123     &MINTAUDIO_GSXB_bootstrap,
   124     &MINTAUDIO_MCSN_bootstrap,
   125     &MINTAUDIO_STFA_bootstrap,
   126     &MINTAUDIO_XBIOS_bootstrap,
   127     &MINTAUDIO_DMA8_bootstrap,
   128 #endif
   129 #if SDL_AUDIO_DRIVER_DISK
   130     &DISKAUD_bootstrap,
   131 #endif
   132 #if SDL_AUDIO_DRIVER_DUMMY
   133     &DUMMYAUD_bootstrap,
   134 #endif
   135 #if SDL_AUDIO_DRIVER_DC
   136     &DCAUD_bootstrap,
   137 #endif
   138 #if SDL_AUDIO_DRIVER_MMEAUDIO
   139     &MMEAUDIO_bootstrap,
   140 #endif
   141 #if SDL_AUDIO_DRIVER_DART
   142     &DART_bootstrap,
   143 #endif
   144     NULL
   145 };
   146 
   147 static SDL_AudioDevice *
   148 get_audio_device(SDL_AudioDeviceID id)
   149 {
   150     id--;
   151     if ((id >= SDL_arraysize(open_devices)) || (open_devices[id] == NULL)) {
   152         SDL_SetError("Invalid audio device ID");
   153         return NULL;
   154     }
   155 
   156     return open_devices[id];
   157 }
   158 
   159 
   160 /* stubs for audio drivers that don't need a specific entry point... */
   161 static int
   162 SDL_AudioDetectDevices_Default(int iscapture)
   163 {
   164     return -1;
   165 }
   166 static void
   167 SDL_AudioThreadInit_Default(_THIS)
   168 {                               /* no-op. */
   169 }
   170 static void
   171 SDL_AudioWaitDevice_Default(_THIS)
   172 {                               /* no-op. */
   173 }
   174 static void
   175 SDL_AudioPlayDevice_Default(_THIS)
   176 {                               /* no-op. */
   177 }
   178 static Uint8 *
   179 SDL_AudioGetDeviceBuf_Default(_THIS)
   180 {
   181     return NULL;
   182 }
   183 static void
   184 SDL_AudioWaitDone_Default(_THIS)
   185 {                               /* no-op. */
   186 }
   187 static void
   188 SDL_AudioCloseDevice_Default(_THIS)
   189 {                               /* no-op. */
   190 }
   191 static void
   192 SDL_AudioDeinitialize_Default(void)
   193 {                               /* no-op. */
   194 }
   195 
   196 static int
   197 SDL_AudioOpenDevice_Default(_THIS, const char *devname, int iscapture)
   198 {
   199     return 0;
   200 }
   201 
   202 static const char *
   203 SDL_AudioGetDeviceName_Default(int index, int iscapture)
   204 {
   205     SDL_SetError("No such device");
   206     return NULL;
   207 }
   208 
   209 static void
   210 SDL_AudioLockDevice_Default(SDL_AudioDevice * device)
   211 {
   212     if (device->thread && (SDL_ThreadID() == device->threadid)) {
   213         return;
   214     }
   215     SDL_mutexP(device->mixer_lock);
   216 }
   217 
   218 static void
   219 SDL_AudioUnlockDevice_Default(SDL_AudioDevice * device)
   220 {
   221     if (device->thread && (SDL_ThreadID() == device->threadid)) {
   222         return;
   223     }
   224     SDL_mutexV(device->mixer_lock);
   225 }
   226 
   227 
   228 static void
   229 finalize_audio_entry_points(void)
   230 {
   231     /*
   232      * Fill in stub functions for unused driver entry points. This lets us
   233      *  blindly call them without having to check for validity first.
   234      */
   235 
   236 #define FILL_STUB(x) \
   237         if (current_audio.impl.x == NULL) { \
   238             current_audio.impl.x = SDL_Audio##x##_Default; \
   239         }
   240     FILL_STUB(DetectDevices);
   241     FILL_STUB(GetDeviceName);
   242     FILL_STUB(OpenDevice);
   243     FILL_STUB(ThreadInit);
   244     FILL_STUB(WaitDevice);
   245     FILL_STUB(PlayDevice);
   246     FILL_STUB(GetDeviceBuf);
   247     FILL_STUB(WaitDone);
   248     FILL_STUB(CloseDevice);
   249     FILL_STUB(LockDevice);
   250     FILL_STUB(UnlockDevice);
   251     FILL_STUB(Deinitialize);
   252 #undef FILL_STUB
   253 }
   254 
   255 
   256 /* The general mixing thread function */
   257 int SDLCALL
   258 SDL_RunAudio(void *devicep)
   259 {
   260     SDL_AudioDevice *device = (SDL_AudioDevice *) devicep;
   261     const int legacy_device = (device == open_devices[0]);
   262     Uint8 *stream;
   263     int stream_len;
   264     void *udata;
   265     void (SDLCALL * fill) (void *userdata, Uint8 * stream, int len);
   266     int silence;
   267 
   268     /* Perform any thread setup */
   269     device->threadid = SDL_ThreadID();
   270     current_audio.impl.ThreadInit(device);
   271 
   272     /* Set up the mixing function */
   273     fill = device->spec.callback;
   274     udata = device->spec.userdata;
   275 
   276     if (device->convert.needed) {
   277         if (device->convert.src_format == AUDIO_U8) {
   278             silence = 0x80;
   279         } else {
   280             silence = 0;
   281         }
   282         stream_len = device->convert.len;
   283     } else {
   284         silence = device->spec.silence;
   285         stream_len = device->spec.size;
   286     }
   287 
   288     /* Loop, filling the audio buffers */
   289     while (device->enabled) {
   290 
   291         /* Fill the current buffer with sound */
   292         if (device->convert.needed) {
   293             if (device->convert.buf) {
   294                 stream = device->convert.buf;
   295             } else {
   296                 continue;
   297             }
   298         } else {
   299             stream = current_audio.impl.GetDeviceBuf(device);
   300             if (stream == NULL) {
   301                 stream = device->fake_stream;
   302             }
   303         }
   304 
   305         /* New code should fill buffer or set it to silence themselves. */
   306         if (legacy_device) {
   307             SDL_memset(stream, silence, stream_len);
   308         }
   309 
   310         if (!device->paused) {
   311             SDL_mutexP(device->mixer_lock);
   312             (*fill) (udata, stream, stream_len);
   313             SDL_mutexV(device->mixer_lock);
   314         }
   315 
   316         /* Convert the audio if necessary */
   317         if (device->convert.needed) {
   318             SDL_ConvertAudio(&device->convert);
   319             stream = current_audio.impl.GetDeviceBuf(device);
   320             if (stream == NULL) {
   321                 stream = device->fake_stream;
   322             }
   323             SDL_memcpy(stream, device->convert.buf, device->convert.len_cvt);
   324         }
   325 
   326         /* Ready current buffer for play and change current buffer */
   327         if (stream != device->fake_stream) {
   328             current_audio.impl.PlayDevice(device);
   329         }
   330 
   331         /* Wait for an audio buffer to become available */
   332         if (stream == device->fake_stream) {
   333             SDL_Delay((device->spec.samples * 1000) / device->spec.freq);
   334         } else {
   335             current_audio.impl.WaitDevice(device);
   336         }
   337     }
   338 
   339     /* Wait for the audio to drain.. */
   340     current_audio.impl.WaitDone(device);
   341 
   342     return (0);
   343 }
   344 
   345 
   346 static SDL_AudioFormat
   347 SDL_ParseAudioFormat(const char *string)
   348 {
   349 #define CHECK_FMT_STRING(x) if (strcmp(string, #x) == 0) return AUDIO_##x
   350     CHECK_FMT_STRING(U8);
   351     CHECK_FMT_STRING(S8);
   352     CHECK_FMT_STRING(U16LSB);
   353     CHECK_FMT_STRING(S16LSB);
   354     CHECK_FMT_STRING(U16MSB);
   355     CHECK_FMT_STRING(S16MSB);
   356     CHECK_FMT_STRING(U16SYS);
   357     CHECK_FMT_STRING(S16SYS);
   358     CHECK_FMT_STRING(U16);
   359     CHECK_FMT_STRING(S16);
   360     CHECK_FMT_STRING(S32LSB);
   361     CHECK_FMT_STRING(S32MSB);
   362     CHECK_FMT_STRING(S32SYS);
   363     CHECK_FMT_STRING(S32);
   364     CHECK_FMT_STRING(F32LSB);
   365     CHECK_FMT_STRING(F32MSB);
   366     CHECK_FMT_STRING(F32SYS);
   367     CHECK_FMT_STRING(F32);
   368 #undef CHECK_FMT_STRING
   369     return 0;
   370 }
   371 
   372 int
   373 SDL_GetNumAudioDrivers(void)
   374 {
   375     return (SDL_arraysize(bootstrap) - 1);
   376 }
   377 
   378 const char *
   379 SDL_GetAudioDriver(int index)
   380 {
   381     if (index >= 0 && index < SDL_GetNumAudioDrivers()) {
   382         return (bootstrap[index]->name);
   383     }
   384     return (NULL);
   385 }
   386 
   387 int
   388 SDL_AudioInit(const char *driver_name)
   389 {
   390     int i = 0;
   391     int initialized = 0;
   392     int tried_to_init = 0;
   393 
   394     if (SDL_WasInit(SDL_INIT_AUDIO)) {
   395         SDL_AudioQuit();        /* shutdown driver if already running. */
   396     }
   397 
   398     SDL_memset(&current_audio, '\0', sizeof(current_audio));
   399     SDL_memset(open_devices, '\0', sizeof(open_devices));
   400 
   401     /* Select the proper audio driver */
   402     if (driver_name == NULL) {
   403         driver_name = SDL_getenv("SDL_AUDIODRIVER");
   404     }
   405 
   406     for (i = 0; (!initialized) && (bootstrap[i]); ++i) {
   407         /* make sure we should even try this driver before doing so... */
   408         const AudioBootStrap *backend = bootstrap[i];
   409         if (((driver_name) && (SDL_strcasecmp(backend->name, driver_name))) ||
   410             ((!driver_name) && (backend->demand_only))) {
   411             continue;
   412         }
   413 
   414         tried_to_init = 1;
   415         SDL_memset(&current_audio, 0, sizeof(current_audio));
   416         current_audio.name = backend->name;
   417         current_audio.desc = backend->desc;
   418         initialized = backend->init(&current_audio.impl);
   419     }
   420 
   421     if (!initialized) {
   422         /* specific drivers will set the error message if they fail... */
   423         if (!tried_to_init) {
   424             if (driver_name) {
   425                 SDL_SetError("%s not available", driver_name);
   426             } else {
   427                 SDL_SetError("No available audio device");
   428             }
   429         }
   430 
   431         SDL_memset(&current_audio, 0, sizeof(current_audio));
   432         return (-1);            /* No driver was available, so fail. */
   433     }
   434 
   435     finalize_audio_entry_points();
   436 
   437     return (0);
   438 }
   439 
   440 /*
   441  * Get the current audio driver name
   442  */
   443 const char *
   444 SDL_GetCurrentAudioDriver()
   445 {
   446     return current_audio.name;
   447 }
   448 
   449 
   450 int
   451 SDL_GetNumAudioDevices(int iscapture)
   452 {
   453     if (!SDL_WasInit(SDL_INIT_AUDIO)) {
   454         return -1;
   455     }
   456     if ((iscapture) && (!current_audio.impl.HasCaptureSupport)) {
   457         return 0;
   458     }
   459 
   460     if ((iscapture) && (current_audio.impl.OnlyHasDefaultInputDevice)) {
   461         return 1;
   462     }
   463 
   464     if ((!iscapture) && (current_audio.impl.OnlyHasDefaultOutputDevice)) {
   465         return 1;
   466     }
   467 
   468     return current_audio.impl.DetectDevices(iscapture);
   469 }
   470 
   471 
   472 const char *
   473 SDL_GetAudioDeviceName(int index, int iscapture)
   474 {
   475     if (!SDL_WasInit(SDL_INIT_AUDIO)) {
   476         SDL_SetError("Audio subsystem is not initialized");
   477         return NULL;
   478     }
   479 
   480     if ((iscapture) && (!current_audio.impl.HasCaptureSupport)) {
   481         SDL_SetError("No capture support");
   482         return NULL;
   483     }
   484 
   485     if (index < 0) {
   486         SDL_SetError("No such device");
   487         return NULL;
   488     }
   489 
   490     if ((iscapture) && (current_audio.impl.OnlyHasDefaultInputDevice)) {
   491         return DEFAULT_INPUT_DEVNAME;
   492     }
   493 
   494     if ((!iscapture) && (current_audio.impl.OnlyHasDefaultOutputDevice)) {
   495         return DEFAULT_OUTPUT_DEVNAME;
   496     }
   497 
   498     return current_audio.impl.GetDeviceName(index, iscapture);
   499 }
   500 
   501 
   502 static void
   503 close_audio_device(SDL_AudioDevice * device)
   504 {
   505     device->enabled = 0;
   506     if (device->thread != NULL) {
   507         SDL_WaitThread(device->thread, NULL);
   508     }
   509     if (device->mixer_lock != NULL) {
   510         SDL_DestroyMutex(device->mixer_lock);
   511     }
   512     if (device->fake_stream != NULL) {
   513         SDL_FreeAudioMem(device->fake_stream);
   514     }
   515     if (device->convert.needed) {
   516         SDL_FreeAudioMem(device->convert.buf);
   517     }
   518     if (device->opened) {
   519         current_audio.impl.CloseDevice(device);
   520         device->opened = 0;
   521     }
   522     SDL_FreeAudioMem(device);
   523 }
   524 
   525 
   526 /*
   527  * Sanity check desired AudioSpec for SDL_OpenAudio() in (orig).
   528  *  Fills in a sanitized copy in (prepared).
   529  *  Returns non-zero if okay, zero on fatal parameters in (orig).
   530  */
   531 static int
   532 prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared)
   533 {
   534     SDL_memcpy(prepared, orig, sizeof(SDL_AudioSpec));
   535 
   536     if (orig->callback == NULL) {
   537         SDL_SetError("SDL_OpenAudio() passed a NULL callback");
   538         return 0;
   539     }
   540 
   541     if (orig->freq == 0) {
   542         const char *env = SDL_getenv("SDL_AUDIO_FREQUENCY");
   543         if ((!env) || ((prepared->freq = SDL_atoi(env)) == 0)) {
   544             prepared->freq = 22050;     /* a reasonable default */
   545         }
   546     }
   547 
   548     if (orig->format == 0) {
   549         const char *env = SDL_getenv("SDL_AUDIO_FORMAT");
   550         if ((!env) || ((prepared->format = SDL_ParseAudioFormat(env)) == 0)) {
   551             prepared->format = AUDIO_S16;       /* a reasonable default */
   552         }
   553     }
   554 
   555     switch (orig->channels) {
   556     case 0:{
   557             const char *env = SDL_getenv("SDL_AUDIO_CHANNELS");
   558             if ((!env) || ((prepared->channels = SDL_atoi(env)) == 0)) {
   559                 prepared->channels = 2; /* a reasonable default */
   560             }
   561             break;
   562         }
   563     case 1:                    /* Mono */
   564     case 2:                    /* Stereo */
   565     case 4:                    /* surround */
   566     case 6:                    /* surround with center and lfe */
   567         break;
   568     default:
   569         SDL_SetError("Unsupported number of audio channels.");
   570         return 0;
   571     }
   572 
   573     if (orig->samples == 0) {
   574         const char *env = SDL_getenv("SDL_AUDIO_SAMPLES");
   575         if ((!env) || ((prepared->samples = (Uint16) SDL_atoi(env)) == 0)) {
   576             /* Pick a default of ~46 ms at desired frequency */
   577             /* !!! FIXME: remove this when the non-Po2 resampling is in. */
   578             const int samples = (prepared->freq / 1000) * 46;
   579             int power2 = 1;
   580             while (power2 < samples) {
   581                 power2 *= 2;
   582             }
   583             prepared->samples = power2;
   584         }
   585     }
   586 
   587     /* Calculate the silence and size of the audio specification */
   588     SDL_CalculateAudioSpec(prepared);
   589 
   590     return 1;
   591 }
   592 
   593 
   594 static SDL_AudioDeviceID
   595 open_audio_device(const char *devname, int iscapture,
   596                   const SDL_AudioSpec * _desired, SDL_AudioSpec * obtained,
   597                   int min_id)
   598 {
   599     SDL_AudioDeviceID id = 0;
   600     SDL_AudioSpec desired;
   601     SDL_AudioDevice *device;
   602     int i = 0;
   603 
   604     if (!SDL_WasInit(SDL_INIT_AUDIO)) {
   605         SDL_SetError("Audio subsystem is not initialized");
   606         return 0;
   607     }
   608 
   609     if ((iscapture) && (!current_audio.impl.HasCaptureSupport)) {
   610         SDL_SetError("No capture support");
   611         return 0;
   612     }
   613 
   614     if (!prepare_audiospec(_desired, &desired)) {
   615         return 0;
   616     }
   617 
   618     /* If app doesn't care about a specific device, let the user override. */
   619     if (devname == NULL) {
   620         devname = SDL_getenv("SDL_AUDIO_DEVICE_NAME");
   621     }
   622 
   623     /*
   624      * Catch device names at the high level for the simple case...
   625      * This lets us have a basic "device enumeration" for systems that
   626      *  don't have multiple devices, but makes sure the device name is
   627      *  always NULL when it hits the low level.
   628      *
   629      * Also make sure that the simple case prevents multiple simultaneous
   630      *  opens of the default system device.
   631      */
   632 
   633     if ((iscapture) && (current_audio.impl.OnlyHasDefaultInputDevice)) {
   634         if ((devname) && (SDL_strcmp(devname, DEFAULT_INPUT_DEVNAME) != 0)) {
   635             SDL_SetError("No such device");
   636             return 0;
   637         }
   638         devname = NULL;
   639 
   640         for (i = 0; i < SDL_arraysize(open_devices); i++) {
   641             if ((open_devices[i]) && (open_devices[i]->iscapture)) {
   642                 SDL_SetError("Audio device already open");
   643                 return 0;
   644             }
   645         }
   646     }
   647 
   648     if ((!iscapture) && (current_audio.impl.OnlyHasDefaultOutputDevice)) {
   649         if ((devname) && (SDL_strcmp(devname, DEFAULT_OUTPUT_DEVNAME) != 0)) {
   650             SDL_SetError("No such device");
   651             return 0;
   652         }
   653         devname = NULL;
   654 
   655         for (i = 0; i < SDL_arraysize(open_devices); i++) {
   656             if ((open_devices[i]) && (!open_devices[i]->iscapture)) {
   657                 SDL_SetError("Audio device already open");
   658                 return 0;
   659             }
   660         }
   661     }
   662 
   663     device = (SDL_AudioDevice *) SDL_AllocAudioMem(sizeof(SDL_AudioDevice));
   664     if (device == NULL) {
   665         SDL_OutOfMemory();
   666         return 0;
   667     }
   668     SDL_memset(device, '\0', sizeof(SDL_AudioDevice));
   669     SDL_memcpy(&device->spec, &desired, sizeof(SDL_AudioSpec));
   670     device->enabled = 1;
   671     device->paused = 1;
   672     device->iscapture = iscapture;
   673 
   674     /* Create a semaphore for locking the sound buffers */
   675     if (!current_audio.impl.SkipMixerLock) {
   676         device->mixer_lock = SDL_CreateMutex();
   677         if (device->mixer_lock == NULL) {
   678             close_audio_device(device);
   679             SDL_SetError("Couldn't create mixer lock");
   680             return 0;
   681         }
   682     }
   683 
   684     if (!current_audio.impl.OpenDevice(device, devname, iscapture)) {
   685         close_audio_device(device);
   686         return 0;
   687     }
   688     device->opened = 1;
   689 
   690     /* If the audio driver changes the buffer size, accept it */
   691     if (device->spec.samples != desired.samples) {
   692         desired.samples = device->spec.samples;
   693         SDL_CalculateAudioSpec(&device->spec);
   694     }
   695 
   696     /* Allocate a fake audio memory buffer */
   697     device->fake_stream = SDL_AllocAudioMem(device->spec.size);
   698     if (device->fake_stream == NULL) {
   699         close_audio_device(device);
   700         SDL_OutOfMemory();
   701         return 0;
   702     }
   703 
   704     /* See if we need to do any conversion */
   705     if (obtained != NULL) {
   706         SDL_memcpy(obtained, &device->spec, sizeof(SDL_AudioSpec));
   707     } else if (desired.freq != device->spec.freq ||
   708                desired.format != device->spec.format ||
   709                desired.channels != device->spec.channels) {
   710         /* Build an audio conversion block */
   711         if (SDL_BuildAudioCVT(&device->convert,
   712                               desired.format, desired.channels,
   713                               desired.freq,
   714                               device->spec.format, device->spec.channels,
   715                               device->spec.freq) < 0) {
   716             close_audio_device(device);
   717             return 0;
   718         }
   719         if (device->convert.needed) {
   720             device->convert.len = (int) (((double) desired.size) /
   721                                          device->convert.len_ratio);
   722 
   723             device->convert.buf =
   724                 (Uint8 *) SDL_AllocAudioMem(device->convert.len *
   725                                             device->convert.len_mult);
   726             if (device->convert.buf == NULL) {
   727                 close_audio_device(device);
   728                 SDL_OutOfMemory();
   729                 return 0;
   730             }
   731         }
   732     }
   733 
   734     /* Find an available device ID and store the structure... */
   735     for (id = min_id - 1; id < SDL_arraysize(open_devices); id++) {
   736         if (open_devices[id] == NULL) {
   737             open_devices[id] = device;
   738             break;
   739         }
   740     }
   741 
   742     if (id == SDL_arraysize(open_devices)) {
   743         SDL_SetError("Too many open audio devices");
   744         close_audio_device(device);
   745         return 0;
   746     }
   747 
   748     /* Start the audio thread if necessary */
   749     if (!current_audio.impl.ProvidesOwnCallbackThread) {
   750         /* Start the audio thread */
   751 /* !!! FIXME: this is nasty. */
   752 #if (defined(__WIN32__) && !defined(_WIN32_WCE)) && !defined(HAVE_LIBC)
   753 #undef SDL_CreateThread
   754         device->thread = SDL_CreateThread(SDL_RunAudio, device, NULL, NULL);
   755 #else
   756         device->thread = SDL_CreateThread(SDL_RunAudio, device);
   757 #endif
   758         if (device->thread == NULL) {
   759             SDL_CloseAudioDevice(id + 1);
   760             SDL_SetError("Couldn't create audio thread");
   761             return 0;
   762         }
   763     }
   764 
   765     return id + 1;
   766 }
   767 
   768 
   769 int
   770 SDL_OpenAudio(const SDL_AudioSpec * desired, SDL_AudioSpec * obtained)
   771 {
   772     SDL_AudioDeviceID id = 0;
   773 
   774     /* Start up the audio driver, if necessary. This is legacy behaviour! */
   775     if (!SDL_WasInit(SDL_INIT_AUDIO)) {
   776         if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
   777             return (-1);
   778         }
   779     }
   780 
   781     /* SDL_OpenAudio() is legacy and can only act on Device ID #1. */
   782     if (open_devices[0] != NULL) {
   783         SDL_SetError("Audio device is already opened");
   784         return (-1);
   785     }
   786 
   787     id = open_audio_device(NULL, 0, desired, obtained, 1);
   788     if (id > 1) {               /* this should never happen in theory... */
   789         SDL_CloseAudioDevice(id);
   790         SDL_SetError("Internal error"); /* MUST be Device ID #1! */
   791         return (-1);
   792     }
   793 
   794     return ((id == 0) ? -1 : 0);
   795 }
   796 
   797 SDL_AudioDeviceID
   798 SDL_OpenAudioDevice(const char *device, int iscapture,
   799                     const SDL_AudioSpec * desired, SDL_AudioSpec * obtained)
   800 {
   801     return open_audio_device(device, iscapture, desired, obtained, 2);
   802 }
   803 
   804 SDL_audiostatus
   805 SDL_GetAudioDeviceStatus(SDL_AudioDeviceID devid)
   806 {
   807     SDL_AudioDevice *device = get_audio_device(devid);
   808     SDL_audiostatus status = SDL_AUDIO_STOPPED;
   809     if (device && device->enabled) {
   810         if (device->paused) {
   811             status = SDL_AUDIO_PAUSED;
   812         } else {
   813             status = SDL_AUDIO_PLAYING;
   814         }
   815     }
   816     return (status);
   817 }
   818 
   819 
   820 SDL_audiostatus
   821 SDL_GetAudioStatus(void)
   822 {
   823     return SDL_GetAudioDeviceStatus(1);
   824 }
   825 
   826 void
   827 SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on)
   828 {
   829     SDL_AudioDevice *device = get_audio_device(devid);
   830     if (device) {
   831         device->paused = pause_on;
   832     }
   833 }
   834 
   835 void
   836 SDL_PauseAudio(int pause_on)
   837 {
   838     SDL_PauseAudioDevice(1, pause_on);
   839 }
   840 
   841 
   842 void
   843 SDL_LockAudioDevice(SDL_AudioDeviceID devid)
   844 {
   845     /* Obtain a lock on the mixing buffers */
   846     SDL_AudioDevice *device = get_audio_device(devid);
   847     if (device) {
   848         current_audio.impl.LockDevice(device);
   849     }
   850 }
   851 
   852 void
   853 SDL_LockAudio(void)
   854 {
   855     SDL_LockAudioDevice(1);
   856 }
   857 
   858 void
   859 SDL_UnlockAudioDevice(SDL_AudioDeviceID devid)
   860 {
   861     /* Obtain a lock on the mixing buffers */
   862     SDL_AudioDevice *device = get_audio_device(devid);
   863     if (device) {
   864         current_audio.impl.UnlockDevice(device);
   865     }
   866 }
   867 
   868 void
   869 SDL_UnlockAudio(void)
   870 {
   871     SDL_UnlockAudioDevice(1);
   872 }
   873 
   874 void
   875 SDL_CloseAudioDevice(SDL_AudioDeviceID devid)
   876 {
   877     SDL_AudioDevice *device = get_audio_device(devid);
   878     if (device) {
   879         close_audio_device(device);
   880         open_devices[devid - 1] = NULL;
   881     }
   882 }
   883 
   884 void
   885 SDL_CloseAudio(void)
   886 {
   887     SDL_CloseAudioDevice(1);
   888 }
   889 
   890 void
   891 SDL_AudioQuit(void)
   892 {
   893     SDL_AudioDeviceID i;
   894     for (i = 0; i < SDL_arraysize(open_devices); i++) {
   895         SDL_CloseAudioDevice(i);
   896     }
   897 
   898     /* Free the driver data */
   899     current_audio.impl.Deinitialize();
   900     SDL_memset(&current_audio, '\0', sizeof(current_audio));
   901     SDL_memset(open_devices, '\0', sizeof(open_devices));
   902 }
   903 
   904 #define NUM_FORMATS 10
   905 static int format_idx;
   906 static int format_idx_sub;
   907 static SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS] = {
   908     {AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB,
   909      AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB},
   910     {AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB,
   911      AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB},
   912     {AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB,
   913      AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8},
   914     {AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S32MSB,
   915      AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8},
   916     {AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S32LSB,
   917      AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8},
   918     {AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_S32MSB,
   919      AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8},
   920     {AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S16LSB,
   921      AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8},
   922     {AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S16MSB,
   923      AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8},
   924     {AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S16LSB,
   925      AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8},
   926     {AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_S16MSB,
   927      AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8},
   928 };
   929 
   930 SDL_AudioFormat
   931 SDL_FirstAudioFormat(SDL_AudioFormat format)
   932 {
   933     for (format_idx = 0; format_idx < NUM_FORMATS; ++format_idx) {
   934         if (format_list[format_idx][0] == format) {
   935             break;
   936         }
   937     }
   938     format_idx_sub = 0;
   939     return (SDL_NextAudioFormat());
   940 }
   941 
   942 SDL_AudioFormat
   943 SDL_NextAudioFormat(void)
   944 {
   945     if ((format_idx == NUM_FORMATS) || (format_idx_sub == NUM_FORMATS)) {
   946         return (0);
   947     }
   948     return (format_list[format_idx][format_idx_sub++]);
   949 }
   950 
   951 void
   952 SDL_CalculateAudioSpec(SDL_AudioSpec * spec)
   953 {
   954     switch (spec->format) {
   955     case AUDIO_U8:
   956         spec->silence = 0x80;
   957         break;
   958     default:
   959         spec->silence = 0x00;
   960         break;
   961     }
   962     spec->size = SDL_AUDIO_BITSIZE(spec->format) / 8;
   963     spec->size *= spec->channels;
   964     spec->size *= spec->samples;
   965 }
   966 
   967 
   968 /*
   969  * Moved here from SDL_mixer.c, since it relies on internals of an opened
   970  *  audio device (and is deprecated, by the way!).
   971  */
   972 void
   973 SDL_MixAudio(Uint8 * dst, const Uint8 * src, Uint32 len, int volume)
   974 {
   975     /* Mix the user-level audio format */
   976     SDL_AudioDevice *device = get_audio_device(1);
   977     if (device != NULL) {
   978         SDL_AudioFormat format;
   979         if (device->convert.needed) {
   980             format = device->convert.src_format;
   981         } else {
   982             format = device->spec.format;
   983         }
   984         SDL_MixAudioFormat(dst, src, format, len, volume);
   985     }
   986 }
   987 
   988 /* vi: set ts=4 sw=4 expandtab: */