coreaudio: Use the standard SDL audio thread instead of spinning a new one.
authorRyan C. Gordon <icculus@icculus.org>
Mon, 16 Apr 2018 02:11:09 -0400
changeset 11945ffd52bb02bcc
parent 11944 295cf9910d75
child 11946 eae649a13dad
coreaudio: Use the standard SDL audio thread instead of spinning a new one.

Fixes corner cases, like the audio callback not firing if the device is
disconnected, etc.
src/audio/SDL_audio.c
src/audio/coreaudio/SDL_coreaudio.h
src/audio/coreaudio/SDL_coreaudio.m
     1.1 --- a/src/audio/SDL_audio.c	Sun Apr 15 17:42:09 2018 -0400
     1.2 +++ b/src/audio/SDL_audio.c	Mon Apr 16 02:11:09 2018 -0400
     1.3 @@ -832,6 +832,8 @@
     1.4          }
     1.5      }
     1.6  
     1.7 +    current_audio.impl.PrepareToClose(device);
     1.8 +
     1.9      current_audio.impl.FlushCapture(device);
    1.10  
    1.11      current_audio.impl.ThreadDeinit(device);
     2.1 --- a/src/audio/coreaudio/SDL_coreaudio.h	Sun Apr 15 17:42:09 2018 -0400
     2.2 +++ b/src/audio/coreaudio/SDL_coreaudio.h	Mon Apr 16 02:11:09 2018 -0400
     2.3 @@ -45,16 +45,14 @@
     2.4  
     2.5  struct SDL_PrivateAudioData
     2.6  {
     2.7 -    SDL_Thread *thread;
     2.8      AudioQueueRef audioQueue;
     2.9 +    int numAudioBuffers;
    2.10      AudioQueueBufferRef *audioBuffer;
    2.11      void *buffer;
    2.12 -    UInt32 bufferOffset;
    2.13      UInt32 bufferSize;
    2.14      AudioStreamBasicDescription strdesc;
    2.15 -    SDL_sem *ready_semaphore;
    2.16 -    char *thread_error;
    2.17 -    SDL_atomic_t shutdown;
    2.18 +    SDL_bool refill;
    2.19 +    SDL_AudioStream *capturestream;
    2.20  #if MACOSX_COREAUDIO
    2.21      AudioDeviceID deviceID;
    2.22  #else
     3.1 --- a/src/audio/coreaudio/SDL_coreaudio.m	Sun Apr 15 17:42:09 2018 -0400
     3.2 +++ b/src/audio/coreaudio/SDL_coreaudio.m	Mon Apr 16 02:11:09 2018 -0400
     3.3 @@ -26,6 +26,7 @@
     3.4  
     3.5  #include "SDL_audio.h"
     3.6  #include "SDL_hints.h"
     3.7 +#include "SDL_timer.h"
     3.8  #include "../SDL_audio_c.h"
     3.9  #include "../SDL_sysaudio.h"
    3.10  #include "SDL_coreaudio.h"
    3.11 @@ -409,43 +410,27 @@
    3.12  outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer)
    3.13  {
    3.14      SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
    3.15 -    if (SDL_AtomicGet(&this->hidden->shutdown)) {
    3.16 -        return;  /* don't do anything. */
    3.17 +    SDL_assert(inBuffer->mAudioDataBytesCapacity == this->hidden->bufferSize);
    3.18 +    SDL_memcpy(inBuffer->mAudioData, this->hidden->buffer, this->hidden->bufferSize);
    3.19 +    SDL_memset(this->hidden->buffer, '\0', this->hidden->bufferSize);  /* zero out in case we have to fill again without new data. */
    3.20 +    inBuffer->mAudioDataByteSize = this->hidden->bufferSize;
    3.21 +    AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
    3.22 +    this->hidden->refill = SDL_TRUE;
    3.23 +}
    3.24 +
    3.25 +static Uint8 *
    3.26 +COREAUDIO_GetDeviceBuf(_THIS)
    3.27 +{
    3.28 +    return this->hidden->buffer;
    3.29 +}
    3.30 +
    3.31 +static void
    3.32 +COREAUDIO_WaitDevice(_THIS)
    3.33 +{
    3.34 +    while (SDL_AtomicGet(&this->enabled) && !this->hidden->refill) {
    3.35 +        CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
    3.36      }
    3.37 -
    3.38 -    if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
    3.39 -        /* Supply silence if audio is not enabled or paused */
    3.40 -        SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity);
    3.41 -    } else {
    3.42 -        UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
    3.43 -        Uint8 *ptr = (Uint8 *) inBuffer->mAudioData;
    3.44 -
    3.45 -        while (remaining > 0) {
    3.46 -            UInt32 len;
    3.47 -            if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
    3.48 -                /* Generate the data */
    3.49 -                SDL_LockMutex(this->mixer_lock);
    3.50 -                (*this->callbackspec.callback)(this->callbackspec.userdata,
    3.51 -                            this->hidden->buffer, this->hidden->bufferSize);
    3.52 -                SDL_UnlockMutex(this->mixer_lock);
    3.53 -                this->hidden->bufferOffset = 0;
    3.54 -            }
    3.55 -
    3.56 -            len = this->hidden->bufferSize - this->hidden->bufferOffset;
    3.57 -            if (len > remaining) {
    3.58 -                len = remaining;
    3.59 -            }
    3.60 -            SDL_memcpy(ptr, (char *)this->hidden->buffer +
    3.61 -                       this->hidden->bufferOffset, len);
    3.62 -            ptr = ptr + len;
    3.63 -            remaining -= len;
    3.64 -            this->hidden->bufferOffset += len;
    3.65 -        }
    3.66 -    }
    3.67 -
    3.68 -    AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
    3.69 -
    3.70 -    inBuffer->mAudioDataByteSize = inBuffer->mAudioDataBytesCapacity;
    3.71 +    this->hidden->refill = SDL_FALSE;
    3.72  }
    3.73  
    3.74  static void
    3.75 @@ -454,36 +439,46 @@
    3.76                const AudioStreamPacketDescription *inPacketDescs )
    3.77  {
    3.78      SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
    3.79 +    if (SDL_AtomicGet(&this->enabled)) {
    3.80 +        SDL_AudioStream *stream = this->hidden->capturestream;
    3.81 +        if (SDL_AudioStreamPut(stream, inBuffer->mAudioData, inBuffer->mAudioDataByteSize) == -1) {
    3.82 +            /* yikes, out of memory or something. I guess drop the buffer. Our WASAPI target kills the device in this case, though */
    3.83 +        }
    3.84 +        AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
    3.85 +        this->hidden->refill = SDL_TRUE;
    3.86 +    }
    3.87 +}
    3.88  
    3.89 -    if (SDL_AtomicGet(&this->shutdown)) {
    3.90 -        return;  /* don't do anything. */
    3.91 +static int
    3.92 +COREAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
    3.93 +{
    3.94 +    SDL_AudioStream *stream = this->hidden->capturestream;
    3.95 +    while (SDL_AtomicGet(&this->enabled)) {
    3.96 +        const int avail = SDL_AudioStreamAvailable(stream);
    3.97 +        if (avail > 0) {
    3.98 +            const int cpy = SDL_min(buflen, avail);
    3.99 +            SDL_AudioStreamGet(stream, buffer, cpy);
   3.100 +            return cpy;
   3.101 +        }
   3.102 +
   3.103 +        /* wait for more data, try again. */
   3.104 +        while (SDL_AtomicGet(&this->enabled) && !this->hidden->refill) {
   3.105 +            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
   3.106 +        }
   3.107 +        this->hidden->refill = SDL_FALSE;
   3.108      }
   3.109  
   3.110 -    /* ignore unless we're active. */
   3.111 -    if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled) && !SDL_AtomicGet(&this->paused)) {
   3.112 -        const Uint8 *ptr = (const Uint8 *) inBuffer->mAudioData;
   3.113 -        UInt32 remaining = inBuffer->mAudioDataByteSize;
   3.114 -        while (remaining > 0) {
   3.115 -            UInt32 len = this->hidden->bufferSize - this->hidden->bufferOffset;
   3.116 -            if (len > remaining) {
   3.117 -                len = remaining;
   3.118 -            }
   3.119 +    return 0;  /* not enabled, giving up. */
   3.120 +}
   3.121  
   3.122 -            SDL_memcpy((char *)this->hidden->buffer + this->hidden->bufferOffset, ptr, len);
   3.123 -            ptr += len;
   3.124 -            remaining -= len;
   3.125 -            this->hidden->bufferOffset += len;
   3.126 -
   3.127 -            if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
   3.128 -                SDL_LockMutex(this->mixer_lock);
   3.129 -                (*this->callbackspec.callback)(this->callbackspec.userdata, this->hidden->buffer, this->hidden->bufferSize);
   3.130 -                SDL_UnlockMutex(this->mixer_lock);
   3.131 -                this->hidden->bufferOffset = 0;
   3.132 -            }
   3.133 -        }
   3.134 +static void
   3.135 +COREAUDIO_FlushCapture(_THIS)
   3.136 +{
   3.137 +    while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, 1) == kCFRunLoopRunHandledSource) {
   3.138 +        /* spin. */
   3.139      }
   3.140 -
   3.141 -    AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
   3.142 +    this->hidden->refill = SDL_FALSE;
   3.143 +    SDL_AudioStreamClear(this->hidden->capturestream);
   3.144  }
   3.145  
   3.146  
   3.147 @@ -541,25 +536,16 @@
   3.148      update_audio_session(this, SDL_FALSE);
   3.149  #endif
   3.150  
   3.151 -    /* if callback fires again, feed silence; don't call into the app. */
   3.152 -    SDL_AtomicSet(&this->paused, 1);
   3.153 -
   3.154      if (this->hidden->audioQueue) {
   3.155          AudioQueueDispose(this->hidden->audioQueue, 1);
   3.156      }
   3.157  
   3.158 -    if (this->hidden->thread) {
   3.159 -        SDL_AtomicSet(&this->hidden->shutdown, 1);
   3.160 -        SDL_WaitThread(this->hidden->thread, NULL);
   3.161 -    }
   3.162 -
   3.163 -    if (this->hidden->ready_semaphore) {
   3.164 -        SDL_DestroySemaphore(this->hidden->ready_semaphore);
   3.165 +    if (this->hidden->capturestream) {
   3.166 +        SDL_FreeAudioStream(this->hidden->capturestream);
   3.167      }
   3.168  
   3.169      /* AudioQueueDispose() frees the actual buffer objects. */
   3.170      SDL_free(this->hidden->audioBuffer);
   3.171 -    SDL_free(this->hidden->thread_error);
   3.172      SDL_free(this->hidden->buffer);
   3.173      SDL_free(this->hidden);
   3.174  
   3.175 @@ -625,6 +611,8 @@
   3.176  }
   3.177  #endif
   3.178  
   3.179 +
   3.180 +/* this all happens in the audio thread, since it needs a separate runloop. */
   3.181  static int
   3.182  prepare_audioqueue(_THIS)
   3.183  {
   3.184 @@ -664,19 +652,6 @@
   3.185  }
   3.186  #endif
   3.187  
   3.188 -    /* Calculate the final parameters for this audio specification */
   3.189 -    SDL_CalculateAudioSpec(&this->spec);
   3.190 -
   3.191 -    /* Allocate a sample buffer */
   3.192 -    this->hidden->bufferSize = this->spec.size;
   3.193 -    this->hidden->bufferOffset = iscapture ? 0 : this->hidden->bufferSize;
   3.194 -
   3.195 -    this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
   3.196 -    if (this->hidden->buffer == NULL) {
   3.197 -        SDL_OutOfMemory();
   3.198 -        return 0;
   3.199 -    }
   3.200 -
   3.201      /* Make sure we can feed the device a minimum amount of time */
   3.202      double MINIMUM_AUDIO_BUFFER_TIME_MS = 15.0;
   3.203  #if defined(__IPHONEOS__)
   3.204 @@ -691,6 +666,7 @@
   3.205          numAudioBuffers = ((int)SDL_ceil(MINIMUM_AUDIO_BUFFER_TIME_MS / msecs) * 2);
   3.206      }
   3.207  
   3.208 +    this->hidden->numAudioBuffers = numAudioBuffers;
   3.209      this->hidden->audioBuffer = SDL_calloc(1, sizeof (AudioQueueBufferRef) * numAudioBuffers);
   3.210      if (this->hidden->audioBuffer == NULL) {
   3.211          SDL_OutOfMemory();
   3.212 @@ -717,29 +693,23 @@
   3.213      return 1;
   3.214  }
   3.215  
   3.216 -static int
   3.217 -audioqueue_thread(void *arg)
   3.218 +static void
   3.219 +COREAUDIO_ThreadInit(_THIS)
   3.220  {
   3.221 -    SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
   3.222      const int rc = prepare_audioqueue(this);
   3.223      if (!rc) {
   3.224 -        this->hidden->thread_error = SDL_strdup(SDL_GetError());
   3.225 -        SDL_SemPost(this->hidden->ready_semaphore);
   3.226 -        return 0;
   3.227 +        /* !!! FIXME: do this in RunAudio, and maybe block OpenDevice until ThreadInit finishes, too, to report an opening error */
   3.228 +        SDL_OpenedAudioDeviceDisconnected(this);  /* oh well. */
   3.229      }
   3.230 +}
   3.231  
   3.232 -    /* init was successful, alert parent thread and start running... */
   3.233 -    SDL_SemPost(this->hidden->ready_semaphore);
   3.234 -    while (!SDL_AtomicGet(&this->hidden->shutdown)) {
   3.235 -        CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
   3.236 -    }
   3.237 -
   3.238 -    if (!this->iscapture) {  /* Drain off any pending playback. */
   3.239 -        const CFTimeInterval secs = (((this->spec.size / (SDL_AUDIO_BITSIZE(this->spec.format) / 8)) / this->spec.channels) / ((CFTimeInterval) this->spec.freq)) * 2.0;
   3.240 -        CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0);
   3.241 -    }
   3.242 -
   3.243 -    return 0;
   3.244 +static void
   3.245 +COREAUDIO_PrepareToClose(_THIS)
   3.246 +{
   3.247 +    /* run long enough to queue some silence, so we know our actual audio
   3.248 +       has been played */
   3.249 +    CFRunLoopRunInMode(kCFRunLoopDefaultMode, (((this->spec.samples * 1000) / this->spec.freq) * 2) / 1000.0f, 0);
   3.250 +    AudioQueueStop(this->hidden->audioQueue, 1);
   3.251  }
   3.252  
   3.253  static int
   3.254 @@ -826,28 +796,23 @@
   3.255      }
   3.256  #endif
   3.257  
   3.258 -    /* This has to init in a new thread so it can get its own CFRunLoop. :/ */
   3.259 -    SDL_AtomicSet(&this->hidden->shutdown, 0);
   3.260 -    this->hidden->ready_semaphore = SDL_CreateSemaphore(0);
   3.261 -    if (!this->hidden->ready_semaphore) {
   3.262 -        return -1;  /* oh well. */
   3.263 +    /* Calculate the final parameters for this audio specification */
   3.264 +    SDL_CalculateAudioSpec(&this->spec);
   3.265 +
   3.266 +    if (iscapture) {
   3.267 +        this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
   3.268 +        if (!this->hidden->capturestream) {
   3.269 +            return -1;  /* already set SDL_Error */
   3.270 +        }
   3.271 +    } else {
   3.272 +        this->hidden->bufferSize = this->spec.size;
   3.273 +        this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
   3.274 +        if (this->hidden->buffer == NULL) {
   3.275 +            return SDL_OutOfMemory();
   3.276 +        }
   3.277      }
   3.278  
   3.279 -    this->hidden->thread = SDL_CreateThreadInternal(audioqueue_thread, "AudioQueue thread", 512 * 1024, this);
   3.280 -    if (!this->hidden->thread) {
   3.281 -        return -1;
   3.282 -    }
   3.283 -
   3.284 -    SDL_SemWait(this->hidden->ready_semaphore);
   3.285 -    SDL_DestroySemaphore(this->hidden->ready_semaphore);
   3.286 -    this->hidden->ready_semaphore = NULL;
   3.287 -
   3.288 -    if ((this->hidden->thread != NULL) && (this->hidden->thread_error != NULL)) {
   3.289 -        SDL_SetError("%s", this->hidden->thread_error);
   3.290 -        return -1;
   3.291 -    }
   3.292 -
   3.293 -    return (this->hidden->thread != NULL) ? 0 : -1;
   3.294 +    return 0;
   3.295  }
   3.296  
   3.297  static void
   3.298 @@ -867,6 +832,12 @@
   3.299      impl->OpenDevice = COREAUDIO_OpenDevice;
   3.300      impl->CloseDevice = COREAUDIO_CloseDevice;
   3.301      impl->Deinitialize = COREAUDIO_Deinitialize;
   3.302 +    impl->ThreadInit = COREAUDIO_ThreadInit;
   3.303 +    impl->WaitDevice = COREAUDIO_WaitDevice;
   3.304 +    impl->GetDeviceBuf = COREAUDIO_GetDeviceBuf;
   3.305 +    impl->PrepareToClose = COREAUDIO_PrepareToClose;
   3.306 +    impl->CaptureFromDevice = COREAUDIO_CaptureFromDevice;
   3.307 +    impl->FlushCapture = COREAUDIO_FlushCapture;
   3.308  
   3.309  #if MACOSX_COREAUDIO
   3.310      impl->DetectDevices = COREAUDIO_DetectDevices;
   3.311 @@ -876,7 +847,6 @@
   3.312      impl->OnlyHasDefaultCaptureDevice = 1;
   3.313  #endif
   3.314  
   3.315 -    impl->ProvidesOwnCallbackThread = 1;
   3.316      impl->HasCaptureSupport = 1;
   3.317  
   3.318      return 1;   /* this audio target is available. */