coreaudio: The default SDL audio device now tracks the system output default.
authorRyan C. Gordon
Sun, 29 Mar 2020 01:54:00 -0400
changeset 13678682e469ffeed
parent 13677 498a7f27758e
child 13679 304c6020419a
coreaudio: The default SDL audio device now tracks the system output default.

So if you go into System Preferences on a MacBook and toggle between a pair of
connected bluetooth headphones and built-in internal speakers, SDL will
switch the device it is playing sound through, to match this setting, on the
fly.

Likewise if the default output device is a USB thing and is unplugged; as the
default device changes at the system level, SDL will pick this up and carry
on with the new default. This is different from our unplug detection for
specific devices, as in those cases we want to send the app a disconnect
notification, instead of migrating transparently as we now do for default
devices.

Note that this should also work for capture devices; if the device changes,
SDL will start recording from the new default.

Fixes Bugzilla #4851.
src/audio/coreaudio/SDL_coreaudio.h
src/audio/coreaudio/SDL_coreaudio.m
     1.1 --- a/src/audio/coreaudio/SDL_coreaudio.h	Thu Mar 26 22:14:59 2020 -0400
     1.2 +++ b/src/audio/coreaudio/SDL_coreaudio.h	Sun Mar 29 01:54:00 2020 -0400
     1.3 @@ -47,6 +47,7 @@
     1.4  {
     1.5      SDL_Thread *thread;
     1.6      AudioQueueRef audioQueue;
     1.7 +    int numAudioBuffers;
     1.8      AudioQueueBufferRef *audioBuffer;
     1.9      void *buffer;
    1.10      UInt32 bufferOffset;
    1.11 @@ -57,6 +58,7 @@
    1.12      SDL_atomic_t shutdown;
    1.13  #if MACOSX_COREAUDIO
    1.14      AudioDeviceID deviceID;
    1.15 +    SDL_atomic_t device_change_flag;
    1.16  #else
    1.17      SDL_bool interrupted;
    1.18      CFTypeRef interruption_listener;
     2.1 --- a/src/audio/coreaudio/SDL_coreaudio.m	Thu Mar 26 22:14:59 2020 -0400
     2.2 +++ b/src/audio/coreaudio/SDL_coreaudio.m	Sun Mar 29 01:54:00 2020 -0400
     2.3 @@ -34,11 +34,21 @@
     2.4  
     2.5  #define DEBUG_COREAUDIO 0
     2.6  
     2.7 -#define CHECK_RESULT(msg) \
     2.8 -    if (result != noErr) { \
     2.9 -        SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
    2.10 -        return 0; \
    2.11 -    }
    2.12 +#if DEBUG_COREAUDIO
    2.13 +    #define CHECK_RESULT(msg) \
    2.14 +        if (result != noErr) { \
    2.15 +            printf("COREAUDIO: Got error %d from '%s'!\n", (int) result, msg); \
    2.16 +            SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
    2.17 +            return 0; \
    2.18 +        }
    2.19 +#else
    2.20 +    #define CHECK_RESULT(msg) \
    2.21 +        if (result != noErr) { \
    2.22 +            SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
    2.23 +            return 0; \
    2.24 +        }
    2.25 +#endif
    2.26 +
    2.27  
    2.28  #if MACOSX_COREAUDIO
    2.29  static const AudioObjectPropertyAddress devlist_address = {
    2.30 @@ -441,7 +451,7 @@
    2.31      if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
    2.32          /* Supply silence if audio is not enabled or paused */
    2.33          SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity);
    2.34 -    } else if (this->stream ) {
    2.35 +    } else if (this->stream) {
    2.36          UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
    2.37          Uint8 *ptr = (Uint8 *) inBuffer->mAudioData;
    2.38  
    2.39 @@ -576,6 +586,18 @@
    2.40  
    2.41      return 0;
    2.42  }
    2.43 +
    2.44 +/* macOS calls this when the default device changed (if we have a default device open). */
    2.45 +static OSStatus
    2.46 +default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData)
    2.47 +{
    2.48 +    SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
    2.49 +    #if DEBUG_COREAUDIO
    2.50 +    printf("COREAUDIO: default device changed for SDL audio device %p!\n", this);
    2.51 +    #endif
    2.52 +    SDL_AtomicSet(&this->hidden->device_change_flag, 1);  /* let the audioqueue thread pick up on this when safe to do so. */
    2.53 +    return noErr;
    2.54 +}
    2.55  #endif
    2.56  
    2.57  static void
    2.58 @@ -586,8 +608,9 @@
    2.59  /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */
    2.60  /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */
    2.61  #if MACOSX_COREAUDIO
    2.62 -    /* Fire a callback if the device stops being "alive" (disconnected, etc). */
    2.63 -    AudioObjectRemovePropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
    2.64 +    if (this->handle != NULL) {  /* we don't register this listener for default devices. */
    2.65 +        AudioObjectRemovePropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
    2.66 +    }
    2.67  #endif
    2.68  
    2.69      if (iscapture) {
    2.70 @@ -676,6 +699,26 @@
    2.71      this->hidden->deviceID = devid;
    2.72      return 1;
    2.73  }
    2.74 +
    2.75 +static int
    2.76 +assign_device_to_audioqueue(_THIS)
    2.77 +{
    2.78 +    const AudioObjectPropertyAddress prop = {
    2.79 +        kAudioDevicePropertyDeviceUID,
    2.80 +        this->iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput,
    2.81 +        kAudioObjectPropertyElementMaster
    2.82 +    };
    2.83 +
    2.84 +    OSStatus result;
    2.85 +    CFStringRef devuid;
    2.86 +    UInt32 devuidsize = sizeof (devuid);
    2.87 +    result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid);
    2.88 +    CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)");
    2.89 +    result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize);
    2.90 +    CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)");
    2.91 +
    2.92 +    return 1;
    2.93 +}
    2.94  #endif
    2.95  
    2.96  static int
    2.97 @@ -696,26 +739,21 @@
    2.98          CHECK_RESULT("AudioQueueNewOutput");
    2.99      }
   2.100  
   2.101 -#if MACOSX_COREAUDIO
   2.102 -{
   2.103 -    const AudioObjectPropertyAddress prop = {
   2.104 -        kAudioDevicePropertyDeviceUID,
   2.105 -        iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput,
   2.106 -        kAudioObjectPropertyElementMaster
   2.107 -    };
   2.108 -    CFStringRef devuid;
   2.109 -    UInt32 devuidsize = sizeof (devuid);
   2.110 -    result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid);
   2.111 -    CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)");
   2.112 -    result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize);
   2.113 -    CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)");
   2.114 +    #if MACOSX_COREAUDIO
   2.115 +    if (!assign_device_to_audioqueue(this)) {
   2.116 +        return 0;
   2.117 +    }
   2.118  
   2.119 -    /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */
   2.120 -    /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */
   2.121 -    /* Fire a callback if the device stops being "alive" (disconnected, etc). */
   2.122 -    AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
   2.123 -}
   2.124 -#endif
   2.125 +    /* only listen for unplugging on specific devices, not the default device, as that should
   2.126 +       switch to a different device (or hang out silently if there _is_ no other device). */
   2.127 +    if (this->handle != NULL) {
   2.128 +        /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */
   2.129 +        /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */
   2.130 +        /* Fire a callback if the device stops being "alive" (disconnected, etc). */
   2.131 +        /* If this fails, oh well, we won't notice a device had an extraordinary event take place. */
   2.132 +        AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
   2.133 +    }
   2.134 +    #endif
   2.135  
   2.136      /* Calculate the final parameters for this audio specification */
   2.137      SDL_CalculateAudioSpec(&this->spec);
   2.138 @@ -779,6 +817,7 @@
   2.139          numAudioBuffers = ((int)SDL_ceil(MINIMUM_AUDIO_BUFFER_TIME_MS / msecs) * 2);
   2.140      }
   2.141  
   2.142 +    this->hidden->numAudioBuffers = numAudioBuffers;
   2.143      this->hidden->audioBuffer = SDL_calloc(1, sizeof (AudioQueueBufferRef) * numAudioBuffers);
   2.144      if (this->hidden->audioBuffer == NULL) {
   2.145          SDL_OutOfMemory();
   2.146 @@ -794,6 +833,7 @@
   2.147          CHECK_RESULT("AudioQueueAllocateBuffer");
   2.148          SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity);
   2.149          this->hidden->audioBuffer[i]->mAudioDataByteSize = this->hidden->audioBuffer[i]->mAudioDataBytesCapacity;
   2.150 +        /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */
   2.151          result = AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL);
   2.152          CHECK_RESULT("AudioQueueEnqueueBuffer");
   2.153      }
   2.154 @@ -809,6 +849,20 @@
   2.155  audioqueue_thread(void *arg)
   2.156  {
   2.157      SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
   2.158 +
   2.159 +    #if MACOSX_COREAUDIO
   2.160 +    const AudioObjectPropertyAddress default_device_address = {
   2.161 +        this->iscapture ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice,
   2.162 +        kAudioObjectPropertyScopeGlobal,
   2.163 +        kAudioObjectPropertyElementMaster
   2.164 +    };
   2.165 +
   2.166 +    if (this->handle == NULL) {  /* opened the default device? Register to know if the user picks a new default. */
   2.167 +        /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */
   2.168 +        AudioObjectAddPropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this);
   2.169 +    }
   2.170 +    #endif
   2.171 +
   2.172      const int rc = prepare_audioqueue(this);
   2.173      if (!rc) {
   2.174          this->hidden->thread_error = SDL_strdup(SDL_GetError());
   2.175 @@ -820,8 +874,36 @@
   2.176  
   2.177      /* init was successful, alert parent thread and start running... */
   2.178      SDL_SemPost(this->hidden->ready_semaphore);
   2.179 +
   2.180      while (!SDL_AtomicGet(&this->hidden->shutdown)) {
   2.181          CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
   2.182 +
   2.183 +        #if MACOSX_COREAUDIO
   2.184 +        if ((this->handle == NULL) && SDL_AtomicGet(&this->hidden->device_change_flag)) {
   2.185 +            SDL_AtomicSet(&this->hidden->device_change_flag, 0);
   2.186 +
   2.187 +            #if DEBUG_COREAUDIO
   2.188 +            printf("COREAUDIO: audioqueue_thread is trying to switch to new default device!\n");
   2.189 +            #endif
   2.190 +
   2.191 +            /* if any of this fails, there's not much to do but wait to see if the user gives up
   2.192 +               and quits (flagging the audioqueue for shutdown), or toggles to some other system
   2.193 +               output device (in which case we'll try again). */
   2.194 +            const AudioDeviceID prev_devid = this->hidden->deviceID;
   2.195 +            if (prepare_device(this, this->handle, this->iscapture) && (prev_devid != this->hidden->deviceID)) {
   2.196 +                AudioQueueStop(this->hidden->audioQueue, 1);
   2.197 +                if (assign_device_to_audioqueue(this)) {
   2.198 +                    int i;
   2.199 +                    for (i = 0; i < this->hidden->numAudioBuffers; i++) {
   2.200 +                        SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity);
   2.201 +                        /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */
   2.202 +                        AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL);
   2.203 +                    }
   2.204 +                    AudioQueueStart(this->hidden->audioQueue, NULL);
   2.205 +                }
   2.206 +            }
   2.207 +        }
   2.208 +        #endif
   2.209      }
   2.210  
   2.211      if (!this->iscapture) {  /* Drain off any pending playback. */
   2.212 @@ -829,6 +911,13 @@
   2.213          CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0);
   2.214      }
   2.215  
   2.216 +    #if MACOSX_COREAUDIO
   2.217 +    if (this->handle == NULL) {
   2.218 +        /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */
   2.219 +        AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this);
   2.220 +    }
   2.221 +    #endif
   2.222 +
   2.223      return 0;
   2.224  }
   2.225