diff --git a/BGMApp/BGMApp/BGMAppDelegate.mm b/BGMApp/BGMApp/BGMAppDelegate.mm index 2c5d47eb..c46f9490 100644 --- a/BGMApp/BGMApp/BGMAppDelegate.mm +++ b/BGMApp/BGMApp/BGMAppDelegate.mm @@ -183,6 +183,11 @@ - (void) continueLaunchAfterInputDevicePermissionGranted { musicPlayers = [[BGMMusicPlayers alloc] initWithAudioDevices:audioDevices userDefaults:userDefaults]; + // Now that musicPlayers exists, let preferredOutputDevices use it to pause the selected music + // player when its output device is disconnected. See the comment on this property in + // BGMPreferredOutputDevices.h. + preferredOutputDevices.musicPlayers = musicPlayers; + autoPauseMusic = [[BGMAutoPauseMusic alloc] initWithAudioDevices:audioDevices musicPlayers:musicPlayers userDefaults:userDefaults]; diff --git a/BGMApp/BGMApp/BGMPreferredOutputDevices.h b/BGMApp/BGMApp/BGMPreferredOutputDevices.h index ef25bfb6..1ff16388 100644 --- a/BGMApp/BGMApp/BGMPreferredOutputDevices.h +++ b/BGMApp/BGMApp/BGMPreferredOutputDevices.h @@ -34,6 +34,9 @@ #import "BGMAudioDeviceManager.h" #import "BGMUserDefaults.h" +// Forward Declarations +@class BGMMusicPlayers; + // System Includes #import #import @@ -48,6 +51,13 @@ - (instancetype) initWithDevices:(BGMAudioDeviceManager*)devices userDefaults:(BGMUserDefaults*)userDefaults; +// Not available until BGMAppDelegate sets it, once BGMMusicPlayers has been created, since it's +// created after this class (see BGMAppDelegate.mm). If it's set, we pause the selected music +// player when the output device we were using is disconnected, e.g. when headphones are unplugged, +// rather than continuing playback through whatever device we fall back to. (Matches what many +// apps, and macOS itself in some cases, do without BGMApp running.) +@property (nullable) BGMMusicPlayers* musicPlayers; + // Returns the most-preferred device that's currently connected. If no preferred devices are // connected, returns the current output device. If the current output device has been disconnected, // returns an arbitrary device. diff --git a/BGMApp/BGMApp/BGMPreferredOutputDevices.mm b/BGMApp/BGMApp/BGMPreferredOutputDevices.mm index 3057f163..df200272 100644 --- a/BGMApp/BGMApp/BGMPreferredOutputDevices.mm +++ b/BGMApp/BGMApp/BGMPreferredOutputDevices.mm @@ -27,6 +27,8 @@ #import "BGM_Types.h" #import "BGM_Utils.h" #import "BGMAudioDevice.h" +#import "BGMMusicPlayer.h" +#import "BGMMusicPlayers.h" // PublicUtility Includes #import "CAAutoDisposer.h" @@ -54,6 +56,10 @@ @implementation BGMPreferredOutputDevices { // index 0. This list is derived from several sources. NSArray* _preferredDeviceUIDs; + // The AudioObjectIDs of the devices that were connected the last time we checked. Used to work + // out which devices, if any, were just connected -- see findNewlyConnectedOutputDevice:. + NSSet* _lastConnectedDeviceIDs; + // Called when a device is connected or disconnected. AudioObjectPropertyListenerBlock _deviceListListener; } @@ -65,6 +71,7 @@ - (instancetype) initWithDevices:(BGMAudioDeviceManager*)devices _devices = devices; _userDefaults = userDefaults; _preferredDeviceUIDs = [self readPreferredDevices]; + _lastConnectedDeviceIDs = [self currentConnectedDeviceIDs]; DebugMsg("BGMPreferredOutputDevices::initWithDevices: Preferred devices: %s", _preferredDeviceUIDs.debugDescription.UTF8String); @@ -258,10 +265,44 @@ - (void) connectedDeviceListChanged { @try { [_stateLock lock]; - // Decide which device should be the output device now. If a device has been connected and - // it's preferred over the current output device, we'll change to that device. If the - // current output device has been removed, we'll change to the next most-preferred device. - AudioObjectID preferredDevice = [self findPreferredDevice]; + NSSet* currentDeviceIDs = [self currentConnectedDeviceIDs]; + + // Check whether the device we're currently using was just disconnected (e.g. the user + // unplugged their headphones), before we do anything else that might change the output + // device. + AudioObjectID outputDeviceBeforeChange = _devices.outputDevice.GetObjectID(); + bool outputDeviceWasJustDisconnected = + [_lastConnectedDeviceIDs containsObject:@(outputDeviceBeforeChange)] && + ![currentDeviceIDs containsObject:@(outputDeviceBeforeChange)]; + + // Pause the selected music player, if we're going to, before we switch the output device + // below. Otherwise, whatever's left of the current song in BGMApp's/BGMDriver's audio + // buffers can start playing out loud through the fallback device (e.g. the built-in + // speakers) in the moment before the pause command reaches the music player, since sending + // it there and back (e.g. over AppleScript, for Spotify) isn't instant. + if (outputDeviceWasJustDisconnected) { + [self pauseSelectedMusicPlayer]; + } + + // Check whether an external device (e.g. USB or Bluetooth headphones) was just connected. + // We check for this separately from findPreferredDevice's usual logic because the + // preferred-devices list that logic uses (see readPreferredDevices) is derived from data + // CoreAudio only updates when a device actually becomes the systemwide default device -- + // which mostly can't happen while BGMDevice is set as the default, since BGMApp keeps it + // that way. So that data never finds out about newly-connected devices on its own, which + // means without this, BGMApp wouldn't switch to a newly-connected device until the user + // picked it from the output device menu themselves at least once. + AudioObjectID newlyConnectedDevice = [self findNewlyConnectedOutputDevice:currentDeviceIDs]; + + _lastConnectedDeviceIDs = currentDeviceIDs; + + // Decide which device should be the output device now. If an external device has just been + // connected, prefer switching to it, the way macOS would if BGMApp wasn't running. Otherwise, + // if a device has been connected and it's preferred over the current output device, we'll + // change to that device. If the current output device has been removed, we'll change to the + // next most-preferred device. + AudioObjectID preferredDevice = (newlyConnectedDevice != kAudioObjectUnknown) ? + newlyConnectedDevice : [self findPreferredDevice]; if (preferredDevice == kAudioObjectUnknown) { LogWarning("BGMPreferredOutputDevices::connectedDeviceListChanged: " @@ -281,6 +322,10 @@ - (void) connectedDeviceListChanged { LogError("BGMPreferredOutputDevices::connectedDeviceListChanged: " "Failed to change to preferred device. Error: %s", error.debugDescription.UTF8String); + } else if (newlyConnectedDevice != kAudioObjectUnknown) { + // Remember this device as preferred so we switch straight back to it next time, + // even if CoreAudio's own preferred-devices data still doesn't reflect it. + [self userChangedOutputDeviceTo:preferredDevice]; } } } @finally { @@ -288,6 +333,90 @@ - (void) connectedDeviceListChanged { } } +// See the comment on the musicPlayers property in the header. +- (void) pauseSelectedMusicPlayer { + if (!_musicPlayers) { + return; + } + + id __nullable player = _musicPlayers.selectedMusicPlayer; + + if (player) { + DebugMsg("BGMPreferredOutputDevices::pauseSelectedMusicPlayer: " + "Output device disconnected. Pausing %s", + player.name.UTF8String); + [player pause]; + } +} + +// Returns the current set of connected devices' AudioObjectIDs, boxed as NSNumbers. +- (NSSet*) currentConnectedDeviceIDs { + CAHALAudioSystemObject audioSystem; + UInt32 numDevices = audioSystem.GetNumberAudioDevices(); + + CAAutoArrayDelete devices(numDevices); + audioSystem.GetAudioDevices(numDevices, devices); + + NSMutableSet* deviceIDs = [NSMutableSet setWithCapacity:numDevices]; + + for (UInt32 i = 0; i < numDevices; i++) { + [deviceIDs addObject:@(devices[i])]; + } + + return deviceIDs; +} + +// Looks for a device in currentDeviceIDs that wasn't in _lastConnectedDeviceIDs (i.e. that's just +// been connected), can be used as BGMApp's output device and isn't a virtual/built-in device (see +// isExternalDeviceWithID:). Returns kAudioObjectUnknown if it doesn't find one. +// +// If more than one newly-connected device qualifies, this just returns the first one it finds -- +// that shouldn't usually happen, and we don't have a good way to tell which the user would want +// anyway. +- (AudioObjectID) findNewlyConnectedOutputDevice:(NSSet*)currentDeviceIDs { + AudioObjectID newlyConnectedDevice = kAudioObjectUnknown; + + for (NSNumber* deviceIDNumber in currentDeviceIDs) { + if (newlyConnectedDevice != kAudioObjectUnknown) { + break; + } + + if (![_lastConnectedDeviceIDs containsObject:deviceIDNumber]) { + AudioObjectID deviceID = (AudioObjectID)deviceIDNumber.unsignedIntValue; + + BGM_Utils::LogAndSwallowExceptions(BGMDbgArgs, [&] { + if (BGMAudioDevice(deviceID).CanBeOutputDeviceInBGMApp() && + [self isExternalDeviceWithID:deviceID]) { + DebugMsg("BGMPreferredOutputDevices::findNewlyConnectedOutputDevice: " + "Found newly-connected external device %u", deviceID); + newlyConnectedDevice = deviceID; + } + }); + } + } + + return newlyConnectedDevice; +} + +// Returns false for virtual/aggregate devices, since those are usually created by some other app +// (or by macOS to represent something like a multi-output setup) rather than by the user plugging +// something in or pairing a device, so we don't want to treat them the same way as, say, USB or +// Bluetooth headphones being connected. +// +// Note that this deliberately doesn't exclude kAudioDeviceTransportTypeBuiltIn. macOS reports the +// built-in headphone jack's device (as opposed to the built-in speakers) with that transport type, +// but, unlike the speakers, it's only present in the device list while headphones are actually +// plugged into the jack -- so it disappears and reappears from findNewlyConnectedOutputDevice:'s +// point of view just like a USB or Bluetooth device would, which is exactly the case we want to +// handle here. +- (bool) isExternalDeviceWithID:(AudioObjectID)deviceID { + UInt32 transportType = BGMAudioDevice(deviceID).GetTransportType(); + + return transportType != kAudioDeviceTransportTypeVirtual && + transportType != kAudioDeviceTransportTypeAggregate && + transportType != kAudioDeviceTransportTypeUnknown; +} + - (AudioObjectID) findPreferredDevice { AudioObjectID preferredDevice = kAudioObjectUnknown; CAHALAudioSystemObject audioSystem;