Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/microsoft-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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,
Expand Down
39 changes: 38 additions & 1 deletion src/Earlo.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> _connectedIds = [];
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -332,6 +344,29 @@ async System.Threading.Tasks.Task CheckForUpdatesAsync(bool manual)
}
}

/// <summary>Reads whether the earbuds' microphone (their Hands-Free service) is on, for the settings window.</summary>
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);
}

/// <summary>Turns the earbuds' microphone off for stereo sound in every app, or back on.</summary>
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);
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/Earlo.App/Earlo.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<RootNamespace>Earlo.App</RootNamespace>
<ApplicationIcon>Assets\earlo.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Version>0.5.0</Version>
<Version>0.6.0</Version>
<Product>Earlo</Product>
<Description>Open-source AirPods and Beats companion for Windows</Description>
<Copyright>Earlo contributors</Copyright>
Expand Down
192 changes: 192 additions & 0 deletions src/Earlo.App/Services/HandsFree.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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 <see cref="DriverInstaller"/>.
/// </summary>
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;

/// <summary>Whether the earbuds' Hands-Free (or Headset) service is on; null when Windows cannot tell.</summary>
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;
}

/// <summary>Turns the service on or off, asking for admin rights (UAC) when Windows wants them. False when that failed.</summary>
public static Task<bool> 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
}
});

/// <summary>Entry point of the elevated copy: --hands-free on|off &lt;address&gt;. Returns the process exit code.</summary>
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;
}
}

/// <returns>0, or the Windows error for the Hands-Free service.</returns>
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);

/// <summary>Runs the action with the radio the device is paired with.</summary>
static int OnDevice(ulong address, Func<IntPtr, BLUETOOTH_DEVICE_INFO, int> action)
{
var find = new BLUETOOTH_FIND_RADIO_PARAMS { dwSize = Marshal.SizeOf<BLUETOOTH_FIND_RADIO_PARAMS>() };
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<BLUETOOTH_DEVICE_INFO>(), 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);
}
5 changes: 5 additions & 0 deletions src/Earlo.App/SettingsWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
<TextBlock Style="{StaticResource Hint}" Text="{x:Static app:Strings.AutoConnectHint}" />
<CheckBox Content="{x:Static app:Strings.VolumeOsd}" Margin="0,8,0,0" IsChecked="{Binding VolumeOsd}" />

<TextBlock Text="{x:Static app:Strings.SoundQuality}" Style="{StaticResource SectionHeader}" />
<CheckBox x:Name="MicOffCheck" Content="{x:Static app:Strings.MicOff}" IsEnabled="False" Click="OnMicOffClick" />
<TextBlock Style="{StaticResource Hint}" Text="{x:Static app:Strings.MicOffHint}" />
<TextBlock x:Name="MicStatusText" Style="{StaticResource Hint}" Visibility="Collapsed" />

<TextBlock Text="{x:Static app:Strings.EarDetection}" Style="{StaticResource SectionHeader}" />
<CheckBox Content="{x:Static app:Strings.PauseOnRemove}" IsChecked="{Binding EarDetection}" />
<DockPanel Margin="28,6,0,6" IsEnabled="{Binding EarDetection}">
Expand Down
28 changes: 28 additions & 0 deletions src/Earlo.App/SettingsWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,34 @@ public void UpdateDriver(bool installed, DriverPackageKind package, bool busy)

void OnDriverClick(object sender, RoutedEventArgs e) => DriverButtonClicked?.Invoke(this, EventArgs.Empty);

/// <summary>True: turn the earbuds' microphone off (their Hands-Free service), false: back on.</summary>
public event EventHandler<bool>? MicrophoneOffRequested;

string _micDevice = string.Empty;

/// <param name="device">The paired earbuds it is about, null when there are none.</param>
/// <param name="handsFreeOn">Whether their Hands-Free service is on; null when Windows cannot tell.</param>
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<bool>? VolumeSwipeRequested;

void OnVolumeSwipeClick(object sender, RoutedEventArgs e) =>
Expand Down
Loading
Loading