diff --git a/README.md b/README.md index 4d7e3c8..9efd25f 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ Earlo brings back what you are used to from an iPhone, and adds the things Windo - **Automatic ear detection**: take an earbud out and Spotify, YouTube, Netflix or any other app pauses. Put it back in and it plays on. - **Connect in one click** from the popup, or let your earbuds switch to the PC by themselves when you put them in, like on an iPhone. - **Disconnect in one click**, so your phone can have them back. +- **Stereo sound in every app**: Windows drops AirPods to muffled call quality as soon as an app opens their microphone. One switch turns the earbuds' microphone off, so they always sound like they should (calls then use your PC's microphone). - **A volume indicator for stem swipes**: Windows changes the volume silently when you swipe; Earlo shows it, like the volume keys do. - **Noise control** (Off, Noise Cancellation, Transparency, Adaptive) and Conversation Awareness with the [experimental driver](#noise-control-it-works-but-windows-makes-it-hard). @@ -98,6 +99,11 @@ Yes. Take an earbud out and Earlo pauses Spotify, YouTube, Netflix or any other Yes: Off, Noise Cancellation, Transparency and Adaptive, plus Conversation Awareness, with Earlo's [experimental driver](#noise-control-it-works-but-windows-makes-it-hard). +**Why do my AirPods sound bad on Windows?** +As soon as an app opens the earbuds' microphone (Teams, Discord, Zoom, a browser), Windows switches them from stereo to the Hands-Free profile: +mono and muffled, like a phone call. In Earlo, turn on Settings > Sound quality > "Turn off the earbuds' microphone for the best sound". +They then always play in stereo; the catch is that their microphone no longer works, so calls use your PC's microphone. You can switch it back at any time. + **Does it work with Galaxy Buds and Beats?** Yes. Beats earbuds and headphones work like AirPods. Galaxy Buds, from the 2019 Buds to the Buds3 Pro and Buds Core, report exact battery levels once they are connected to your PC. diff --git a/docs/microsoft-store.md b/docs/microsoft-store.md index a733210..5dcbee2 100644 --- a/docs/microsoft-store.md +++ b/docs/microsoft-store.md @@ -70,6 +70,7 @@ type ("AirPods battery", "Galaxy Buds") are in the description itself, not only > • Automatic ear detection: take an earbud out and your music pauses, put it back in and it plays again (Spotify, YouTube, Netflix, browsers and more) > • Connect and disconnect your earbuds in one click > • A "Connected" notice in the top right corner when your earbuds connect, with their battery levels +> • Fix the muffled sound: Windows switches AirPods to call quality as soon as an app uses their microphone; one switch keeps them in stereo > • A volume indicator when you swipe the stem to change the volume > • Low battery warnings for each earbud and the case > • Works with AirPods 1, 2, 3 and 4, AirPods Pro 1, 2 and 3, AirPods Max, Beats earbuds and headphones (Powerbeats Pro, Beats Fit Pro, Studio Buds, Solo Buds, Studio Pro and more) and Samsung Galaxy Buds (Buds, Buds+, Buds Live, Buds Pro, Buds2, Buds2 Pro, Buds FE, Buds3, Buds3 Pro, Buds3 FE, Buds Core) @@ -91,7 +92,7 @@ type ("AirPods battery", "Galaxy Buds") are in the description itself, not only | 4 | ear detection | | 5 | Bluetooth headphones battery | | 6 | battery popup | -| 7 | wireless earbuds | +| 7 | earbuds sound quality | The old name is only mentioned in the description: another app in the Store is called PodPilot, so using it as a search term could count as misleading. If certification objects to a device brand in the search terms, diff --git a/src/Earlo.App/App.xaml.cs b/src/Earlo.App/App.xaml.cs index 5bff0fc..7177ddc 100644 --- a/src/Earlo.App/App.xaml.cs +++ b/src/Earlo.App/App.xaml.cs @@ -42,6 +42,8 @@ public partial class App : Application bool _updating; bool _driverInstalled; bool _driverBusy; + bool? _handsFreeOn; + bool _handsFreeBusy; VolumeOsdWindow? _osd; ConnectedBannerWindow? _banner; readonly HashSet _connectedIds = []; @@ -73,6 +75,11 @@ protected override void OnStartup(StartupEventArgs e) Shutdown(DriverInstaller.RunElevatedCommand(e.Args[0])); return; } + if (HandsFree.IsElevatedCommand(e.Args.FirstOrDefault())) + { + Shutdown(HandsFree.RunElevatedCommand(e.Args)); + return; + } int previewIndex = Array.IndexOf(e.Args, "--render-preview"); if (previewIndex >= 0) @@ -150,7 +157,12 @@ protected override void OnStartup(StartupEventArgs e) _scanner.Received += (_, a) => Dispatcher.BeginInvoke(() => _tracker.Process(a.Message, a.Rssi)); _scanner.StatusChanged += (_, _) => Dispatcher.BeginInvoke(Refresh); _paired.ConnectionChanged += (_, device) => Dispatcher.BeginInvoke(() => OnPairedConnectionChanged(device)); - _paired.DevicesChanged += (_, _) => Dispatcher.BeginInvoke(Refresh); + _paired.DevicesChanged += (_, _) => Dispatcher.BeginInvoke(() => + { + Refresh(); + if (_settingsWindow is not null) + _ = RefreshMicrophoneAsync(); + }); // At start Windows reports the earbuds that are already connected; that is no news. _bannerQuietUntil = DateTime.UtcNow.AddSeconds(8); @@ -332,6 +344,29 @@ async System.Threading.Tasks.Task CheckForUpdatesAsync(bool manual) } } + /// Reads whether the earbuds' microphone (their Hands-Free service) is on, for the settings window. + async System.Threading.Tasks.Task RefreshMicrophoneAsync() + { + if (_handsFreeBusy) + return; + var target = ConnectTarget; + _handsFreeOn = target is null ? null : await System.Threading.Tasks.Task.Run(() => HandsFree.IsEnabled(target.Address)); + _settingsWindow?.UpdateMicrophone(target?.Name, _handsFreeOn, _handsFreeBusy); + } + + /// Turns the earbuds' microphone off for stereo sound in every app, or back on. + async System.Threading.Tasks.Task SetMicrophoneOffAsync(bool off) + { + if (_handsFreeBusy || ConnectTarget is not { } target) + return; + _handsFreeBusy = true; + _settingsWindow?.UpdateMicrophone(target.Name, _handsFreeOn, busy: true); + bool ok = await HandsFree.SetEnabledAsync(target.Address, enabled: !off); + _handsFreeBusy = false; + await RefreshMicrophoneAsync(); + _tray?.Notify("Earlo", !ok ? Strings.MicChangeFailed : off ? Strings.MicTurnedOff(target.Name) : Strings.MicTurnedOn(target.Name)); + } + async System.Threading.Tasks.Task RefreshDriverStateAsync() { _driverInstalled = await System.Threading.Tasks.Task.Run(DriverInstaller.IsInstalled); @@ -461,9 +496,11 @@ void ShowSettings() _settingsWindow.ConversationAwarenessRequested += (_, on) => _ = SendAap(s => s.SetConversationAwarenessAsync(on)); _settingsWindow.AdaptiveStrengthRequested += (_, level) => _ = SendAap(s => s.SetAdaptiveStrengthAsync(level)); _settingsWindow.DriverButtonClicked += async (_, _) => await ToggleDriverAsync(); + _settingsWindow.MicrophoneOffRequested += async (_, off) => await SetMicrophoneOffAsync(off); _settingsWindow.CheckUpdatesRequested += async (_, _) => await CheckForUpdatesAsync(manual: true); _settingsWindow.VolumeSwipeRequested += (_, on) => _ = SendAap(s => s.SetVolumeSwipeAsync(on)); _ = RefreshDriverStateAsync(); + _ = RefreshMicrophoneAsync(); _settingsWindow.Closed += (_, _) => _settingsWindow = null; _settingsWindow.Update(CurrentState(), _paired.Devices, _aap.DriverPresent); _settingsWindow.Show(); diff --git a/src/Earlo.App/Earlo.App.csproj b/src/Earlo.App/Earlo.App.csproj index 32a2b7d..e9b562b 100644 --- a/src/Earlo.App/Earlo.App.csproj +++ b/src/Earlo.App/Earlo.App.csproj @@ -12,7 +12,7 @@ Earlo.App Assets\earlo.ico app.manifest - 0.5.0 + 0.6.0 Earlo Open-source AirPods and Beats companion for Windows Earlo contributors diff --git a/src/Earlo.App/Services/HandsFree.cs b/src/Earlo.App/Services/HandsFree.cs new file mode 100644 index 0000000..cb29d6d --- /dev/null +++ b/src/Earlo.App/Services/HandsFree.cs @@ -0,0 +1,192 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading.Tasks; + +namespace Earlo.App.Services; + +/// +/// Turns the Hands-Free service of paired earbuds off and on, which is the fix for the muffled sound +/// many people get on Windows: as soon as an app opens the earbuds' microphone (Teams, Discord, a +/// browser), Windows switches them from stereo music (A2DP) to the Hands-Free profile, which is mono +/// and sounds like a phone call. Without the service Windows can only use stereo, at the price of the +/// earbuds' microphone. It is the "Handsfree Telephony" box under Services in the classic Bluetooth +/// device properties. Changing it can need admin rights; Earlo then runs an elevated copy of itself +/// with --hands-free, like . +/// +public static class HandsFree +{ + const string Argument = "--hands-free"; + const int ERROR_SUCCESS = 0, ERROR_ACCESS_DENIED = 5, ERROR_NOT_FOUND = 1168; + const int BLUETOOTH_SERVICE_DISABLE = 0, BLUETOOTH_SERVICE_ENABLE = 1; + + static readonly Guid HandsfreeService = new("0000111E-0000-1000-8000-00805F9B34FB"); + static readonly Guid HeadsetService = new("00001108-0000-1000-8000-00805F9B34FB"); + + public static bool IsElevatedCommand(string? argument) => argument == Argument; + + /// Whether the earbuds' Hands-Free (or Headset) service is on; null when Windows cannot tell. + public static bool? IsEnabled(ulong address) + { + if (address == 0) + return null; + bool? enabled = null; + try + { + OnDevice(address, (radio, info) => + { + var services = new Guid[64]; + uint count = (uint)services.Length; + int code = BluetoothEnumerateInstalledServices(radio, ref info, ref count, services); + if (code != ERROR_SUCCESS) + return code; + enabled = services.Take((int)count).Any(s => s == HandsfreeService || s == HeadsetService); + return ERROR_SUCCESS; + }); + } + catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) + { + // No Bluetooth stack. + } + return enabled; + } + + /// Turns the service on or off, asking for admin rights (UAC) when Windows wants them. False when that failed. + public static Task SetEnabledAsync(ulong address, bool enabled) => Task.Run(() => + { + int code = Apply(address, enabled); + if (code != ERROR_ACCESS_DENIED) + return code == ERROR_SUCCESS; + try + { + string state = enabled ? "on" : "off"; + using var process = Process.Start(new ProcessStartInfo(Environment.ProcessPath!, $"{Argument} {state} {address:X12}") + { + UseShellExecute = true, + Verb = "runas", + }); + if (process is null) + return false; + process.WaitForExit(); + return process.ExitCode == ERROR_SUCCESS; + } + catch (Win32Exception) + { + return false; // the user declined the UAC prompt + } + }); + + /// Entry point of the elevated copy: --hands-free on|off <address>. Returns the process exit code. + public static int RunElevatedCommand(string[] args) + { + try + { + if (args.Length < 3 || args[1] is not ("on" or "off") + || !ulong.TryParse(args[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong address)) + return 1; + return Apply(address, enabled: args[1] == "on"); + } + catch (Exception ex) + { + CrashLog.Write(ex); + return 1; + } + } + + /// 0, or the Windows error for the Hands-Free service. + static int Apply(ulong address, bool enabled) + { + int code = OnDevice(address, (radio, info) => + { + int handsFree = SetService(radio, info, HandsfreeService, enabled); + SetService(radio, info, HeadsetService, enabled); // most earbuds have no Headset profile + return handsFree; + }); + // Windows also answers with an error when the service already was in that state. + return code != ERROR_SUCCESS && code != ERROR_ACCESS_DENIED && IsEnabled(address) == enabled ? ERROR_SUCCESS : code; + } + + static int SetService(IntPtr radio, BLUETOOTH_DEVICE_INFO info, Guid service, bool enabled) => + BluetoothSetServiceState(radio, ref info, ref service, enabled ? BLUETOOTH_SERVICE_ENABLE : BLUETOOTH_SERVICE_DISABLE); + + /// Runs the action with the radio the device is paired with. + static int OnDevice(ulong address, Func action) + { + var find = new BLUETOOTH_FIND_RADIO_PARAMS { dwSize = Marshal.SizeOf() }; + IntPtr search = BluetoothFindFirstRadio(ref find, out IntPtr radio); + if (search == IntPtr.Zero) + return ERROR_NOT_FOUND; + try + { + do + { + try + { + var info = new BLUETOOTH_DEVICE_INFO { dwSize = Marshal.SizeOf(), Address = address, szName = string.Empty }; + if (BluetoothGetDeviceInfo(radio, ref info) == ERROR_SUCCESS) + return action(radio, info); + } + finally + { + CloseHandle(radio); + } + } + while (BluetoothFindNextRadio(search, out radio)); + } + finally + { + BluetoothFindRadioClose(search); + } + return ERROR_NOT_FOUND; + } + + [StructLayout(LayoutKind.Sequential)] + struct BLUETOOTH_FIND_RADIO_PARAMS + { + public int dwSize; + } + + [StructLayout(LayoutKind.Sequential)] + struct SYSTEMTIME + { + public ushort Year, Month, DayOfWeek, Day, Hour, Minute, Second, Milliseconds; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + struct BLUETOOTH_DEVICE_INFO + { + public int dwSize; + public ulong Address; + public uint ulClassofDevice; + public int fConnected; + public int fRemembered; + public int fAuthenticated; + public SYSTEMTIME stLastSeen; + public SYSTEMTIME stLastUsed; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 248)] public string szName; + } + + [DllImport("BluetoothApis.dll", SetLastError = true)] + static extern IntPtr BluetoothFindFirstRadio(ref BLUETOOTH_FIND_RADIO_PARAMS parameters, out IntPtr radio); + + [DllImport("BluetoothApis.dll", SetLastError = true)] + static extern bool BluetoothFindNextRadio(IntPtr search, out IntPtr radio); + + [DllImport("BluetoothApis.dll")] + static extern bool BluetoothFindRadioClose(IntPtr search); + + [DllImport("BluetoothApis.dll")] + static extern int BluetoothGetDeviceInfo(IntPtr radio, ref BLUETOOTH_DEVICE_INFO info); + + [DllImport("BluetoothApis.dll")] + static extern int BluetoothSetServiceState(IntPtr radio, ref BLUETOOTH_DEVICE_INFO info, ref Guid service, int flags); + + [DllImport("BluetoothApis.dll")] + static extern int BluetoothEnumerateInstalledServices(IntPtr radio, ref BLUETOOTH_DEVICE_INFO info, ref uint count, [In, Out] Guid[] services); + + [DllImport("kernel32.dll")] + static extern bool CloseHandle(IntPtr handle); +} diff --git a/src/Earlo.App/SettingsWindow.xaml b/src/Earlo.App/SettingsWindow.xaml index 8e116ca..a84a02b 100644 --- a/src/Earlo.App/SettingsWindow.xaml +++ b/src/Earlo.App/SettingsWindow.xaml @@ -48,6 +48,11 @@ + + + + + diff --git a/src/Earlo.App/SettingsWindow.xaml.cs b/src/Earlo.App/SettingsWindow.xaml.cs index 5d26b3a..b239557 100644 --- a/src/Earlo.App/SettingsWindow.xaml.cs +++ b/src/Earlo.App/SettingsWindow.xaml.cs @@ -88,6 +88,34 @@ public void UpdateDriver(bool installed, DriverPackageKind package, bool busy) void OnDriverClick(object sender, RoutedEventArgs e) => DriverButtonClicked?.Invoke(this, EventArgs.Empty); + /// True: turn the earbuds' microphone off (their Hands-Free service), false: back on. + public event EventHandler? MicrophoneOffRequested; + + string _micDevice = string.Empty; + + /// The paired earbuds it is about, null when there are none. + /// Whether their Hands-Free service is on; null when Windows cannot tell. + public void UpdateMicrophone(string? device, bool? handsFreeOn, bool busy) + { + _micDevice = device ?? string.Empty; + MicOffCheck.IsChecked = handsFreeOn == false; + MicOffCheck.IsEnabled = handsFreeOn is not null && !busy; + MicStatusText.Text = busy ? Strings.Working : device is null ? Strings.MicNoDevice : string.Empty; + MicStatusText.Visibility = MicStatusText.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + } + + void OnMicOffClick(object sender, RoutedEventArgs e) + { + bool off = MicOffCheck.IsChecked == true; + if (off && MessageBox.Show(this, Strings.MicOffConfirm(_micDevice), Strings.MicOffConfirmTitle, + MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes) + { + MicOffCheck.IsChecked = false; + return; + } + MicrophoneOffRequested?.Invoke(this, off); + } + public event EventHandler? VolumeSwipeRequested; void OnVolumeSwipeClick(object sender, RoutedEventArgs e) => diff --git a/src/Earlo.App/Strings.cs b/src/Earlo.App/Strings.cs index 4c917e4..9fa6c25 100644 --- a/src/Earlo.App/Strings.cs +++ b/src/Earlo.App/Strings.cs @@ -83,6 +83,14 @@ public static void UseLanguage(string? code) public static string AutoConnectHint => T("Like switching on an iPhone: the earbuds move to this PC when you start wearing them. Leave it off if they should stay with your phone.", "Net als wisselen op een iPhone: de oortjes gaan naar deze pc zodra je ze indoet. Laat dit uit als ze bij je telefoon moeten blijven."); public static string VolumeOsd => T("Show the volume when it changes on the earbuds", "Volume tonen als het op de oortjes verandert"); + public static string SoundQuality => T("Sound quality", "Geluidskwaliteit"); + public static string MicOff => T("Turn off the earbuds' microphone for the best sound", "Microfoon van de oortjes uitzetten voor het beste geluid"); + public static string MicOffHint => T("As soon as an app uses the earbuds' microphone (Teams, Discord, a browser), Windows switches them to call quality: mono and muffled. With the microphone off they always play in stereo quality, but their microphone no longer works; calls use your PC's microphone. Windows may ask for administrator permission.", + "Zodra een app de microfoon van de oortjes gebruikt (Teams, Discord, een browser), zet Windows ze op gesprekskwaliteit: mono en dof. Met de microfoon uit spelen ze altijd in stereokwaliteit, maar werkt hun microfoon niet meer; bij bellen gebruik je dan de microfoon van je pc. Windows kan om beheerdersrechten vragen."); + public static string MicNoDevice => T("Pair your earbuds with this PC first.", "Koppel eerst je oortjes met deze pc."); + public static string MicOffConfirmTitle => T("Turn off the microphone?", "Microfoon uitzetten?"); + public static string MicOffConfirm(string name) => T($"The microphone of {name} will no longer work on this PC. Music and video always keep stereo quality, and calls use your PC's microphone.\n\nYou can turn it back on in Settings at any time.", + $"De microfoon van {name} werkt dan niet meer op deze pc. Muziek en video houden altijd stereokwaliteit, en bij bellen gebruik je de microfoon van je pc.\n\nJe kunt hem altijd weer aanzetten in Instellingen."); public static string EarDetection => T("Automatic ear detection", "Automatische oordetectie"); public static string PauseOnRemove => T("Pause media when you take an earbud out", "Media pauzeren als je een oortje uitdoet"); public static string PauseWhen => T("Pause when", "Pauzeren als"); @@ -163,6 +171,10 @@ public static void UseLanguage(string? code) $"{name} kon niet verbinden. Zorg dat ze uit de case en dichtbij zijn."); public static string Volume => T("Volume", "Volume"); public static string BannerConnected => T("Connected", "Verbonden"); + public static string MicTurnedOff(string name) => T($"Microphone off: {name} now always plays in stereo quality.", $"Microfoon uit: {name} speelt nu altijd in stereokwaliteit."); + public static string MicTurnedOn(string name) => T($"The microphone of {name} works again.", $"De microfoon van {name} werkt weer."); + public static string MicChangeFailed => T("The microphone could not be changed. You can also do it in Control Panel > Devices and Printers > your earbuds > Properties > Services > Handsfree Telephony.", + "De microfoon kon niet worden aangepast. Je kunt het ook zelf doen via Configuratiescherm > Apparaten en printers > je oortjes > Eigenschappen > Services > Handsfree-telefonie."); public static string FirstRun => T("Earlo runs in the notification area. Click its icon to open it.", "Earlo staat in het systeemvak (bij de klok). Klik op het icoon om het te openen."); } diff --git a/src/Earlo.Core/Bluetooth/PairedDeviceMonitor.cs b/src/Earlo.Core/Bluetooth/PairedDeviceMonitor.cs index 588bcd0..9ecfd0b 100644 --- a/src/Earlo.Core/Bluetooth/PairedDeviceMonitor.cs +++ b/src/Earlo.Core/Bluetooth/PairedDeviceMonitor.cs @@ -6,7 +6,8 @@ namespace Earlo.Core.Bluetooth; /// Groups the device with its other parts, like its Windows audio endpoints. -public sealed record PairedDeviceInfo(string Id, string Name, bool IsConnected, Guid? ContainerId = null); +/// The Bluetooth address, for the classic Bluetooth APIs. +public sealed record PairedDeviceInfo(string Id, string Name, bool IsConnected, Guid? ContainerId = null, ulong Address = 0); /// /// Tracks AirPods, Beats and Galaxy Buds that are paired with this PC and whether they are connected. @@ -103,7 +104,7 @@ void OnConnectionStatusChanged(BluetoothDevice sender, object args) PairedDeviceInfo ToInfo(BluetoothDevice d) => new(d.DeviceId, d.Name, d.ConnectionStatus == BluetoothConnectionStatus.Connected, - _containers.TryGetValue(d.DeviceId, out var container) ? container : null); + _containers.TryGetValue(d.DeviceId, out var container) ? container : null, d.BluetoothAddress); [GeneratedRegex("airpods|beats", RegexOptions.IgnoreCase)] private static partial Regex AppleAudioName();