From b296f0d6dbad02d76beec2dcd06509662a9928d1 Mon Sep 17 00:00:00 2001 From: second Date: Mon, 7 Sep 2026 12:45:00 +0800 Subject: [PATCH 1/2] Switch to newly-connected external output devices automatically BGMPreferredOutputDevices tries to mimic macOS's own behaviour of switching the default output device when the user plugs in headphones or another output device. But its findPreferredDevice logic only worked from the "preferred devices" list CoreAudio stores in /Library/Preferences/Audio/com.apple.audio.SystemSettings.plist, and that list is only updated by CoreAudio 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 in practice, a newly-connected device was never added to that list, and BGMApp wouldn't switch to it until the user picked it from the output device menu themselves at least once. Add a separate check that diffs the currently-connected devices against the previous connected-device list on every device list change notification (connectedDeviceListChanged already listens for these). If a device that can be used as BGMApp's output device just appeared and isn't a virtual/aggregate device, switch to it immediately and record it as a preferred device, the same as if the user had picked it from the menu. Deliberately doesn't exclude kAudioDeviceTransportTypeBuiltIn from the new device check: macOS reports the built-in headphone jack's device with that transport type, but unlike the built-in speakers, it only appears in the connected-devices list while headphones are actually in the jack, so it needs the same handling as a USB or Bluetooth device appearing. Didn't add a copyright notice to the file per CONTRIBUTING.md, since this is a small, focused change -- happy to add one if the maintainer prefers. --- BGMApp/BGMApp/BGMPreferredOutputDevices.mm | 102 ++++++++++++++++++++- 1 file changed, 98 insertions(+), 4 deletions(-) diff --git a/BGMApp/BGMApp/BGMPreferredOutputDevices.mm b/BGMApp/BGMApp/BGMPreferredOutputDevices.mm index 3057f163..e341d249 100644 --- a/BGMApp/BGMApp/BGMPreferredOutputDevices.mm +++ b/BGMApp/BGMApp/BGMPreferredOutputDevices.mm @@ -54,6 +54,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 +69,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 +263,27 @@ - (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 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 +303,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 +314,74 @@ - (void) connectedDeviceListChanged { } } +// 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; From 39f96c2c52ef56fbbacf9f39515a5ed8605b57a7 Mon Sep 17 00:00:00 2001 From: second Date: Mon, 7 Sep 2026 13:50:19 +0800 Subject: [PATCH 2/2] Pause the selected music player when its output device is disconnected Previously, unplugging headphones (or another output device) would switch BGMApp back to a fallback device (e.g. the built-in speakers) and keep playing through it. That's surprising and can be annoying or embarrassing -- e.g. music suddenly playing out loud over speakers after taking headphones off in a quiet room. A lot of apps, and macOS itself in some circumstances, avoid this by pausing playback when the output device disappears instead of carrying on through whatever device is left. Give BGMPreferredOutputDevices an optional reference to BGMMusicPlayers (set by BGMAppDelegate once BGMMusicPlayers exists, since it's created after BGMPreferredOutputDevices) and, in connectedDeviceListChanged, check whether the device BGMApp was actively using has just disconnected. If so, pause the selected music player before switching to the fallback device, the same way BGMAutoPauseMusic pauses it. Pausing first, rather than after switching, matters because otherwise whatever's left in the audio buffers can briefly play out loud through the fallback device before the pause command gets back from the music player (e.g. over AppleScript, for Spotify). This only affects music players BGMApp can control directly (the ones listed in the output device menu's music player picker, e.g. Music.app or Spotify) -- it can't pause arbitrary apps like a browser tab, since there's no general way to do that. If musicPlayers hasn't been set yet (i.e. this happens very early during launch), this is a no-op. Built on top of the "switch to newly-connected external output devices automatically" change, since it reuses the connected-device diffing that adds. Didn't add a copyright notice to the files per CONTRIBUTING.md, since these are small, focused changes -- happy to add one if the maintainer prefers. --- BGMApp/BGMApp/BGMAppDelegate.mm | 5 ++++ BGMApp/BGMApp/BGMPreferredOutputDevices.h | 10 +++++++ BGMApp/BGMApp/BGMPreferredOutputDevices.mm | 35 ++++++++++++++++++++++ 3 files changed, 50 insertions(+) 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 e341d249..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" @@ -265,6 +267,23 @@ - (void) connectedDeviceListChanged { 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 @@ -314,6 +333,22 @@ - (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;