Skip to content
Closed
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
Binary file added Assets/TrayQuickConnect/Connecting-Dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Assets/TrayQuickConnect/Connecting-Light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Assets/TrayQuickConnect/Settings-zh-CN.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ set(
"Source/Core/Update.cpp"
"Source/Core/AirPods.cpp"
"Source/Core/QuickConnect.cpp"
"Source/Core/PlaybackMonitor.cpp"
"Source/Core/Settings.cpp"
"Source/Core/SettingsRepository.cpp"
"Source/Core/LowAudioLatency.cpp"
Expand All @@ -350,6 +351,7 @@ set(
"Source/Gui/AnimationPlayback.cpp"

"Source/Gui/TrayIcon.cpp"
"Source/Gui/NotificationWindow.cpp"
"Source/Gui/TaskbarStatus.cpp"
"Source/Gui/MainWindow.cpp"
"Source/Gui/SelectWindow.cpp"
Expand All @@ -372,6 +374,7 @@ if (WIN32)
"Source/Core/AutoStart_win.cpp"
"Source/Core/Bluetooth_win.cpp"
"Source/Core/GlobalMedia_win.cpp"
"Source/Core/PlaybackMonitor_win.cpp"
"Source/Core/QuickConnect_win.cpp"
)
list(APPEND APD_APP_CODE_FILES
Expand Down
44 changes: 44 additions & 0 deletions Docs/AudioAutoConnect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Connect automatically when audio starts playing

In Settings, select the paired Bluetooth audio device and enable **Connect automatically when
audio starts playing**. The option is off by default and is independent of the tray-click option.
Both options use the same selected device.

When an output audio session starts running, the application checks the selected device and requests
a connection only if it is disconnected. A device that is already connected causes no notification
or window to open. Successful automatic connections open the battery window; progress and failures
use the existing application notification card.

Playback is checked on a background worker every 250 ms across active Windows output endpoints.
The application's own sounds are excluded. Audio session state is used rather than sound level,
so muted playback and quiet passages still count as playback. No audio is recorded. At least 1.5
seconds without a running output session is required before another playback start is recognized.
Applications that keep their audio streams running while paused may therefore delay recognition of
a subsequent playback start.

Each playback start can request one connection. Existing connection requests are reused. After an
automatic failure or timeout, at least 30 seconds must pass **and a new playback start must occur**
before another automatic attempt. The application does not continuously retry during playback.
Turning the option off stops playback monitoring; a connection request already submitted to Windows
is allowed to finish.

## Validation

- Build x64 `RelWithDebInfo` and run `ctest --test-dir Build -C RelWithDebInfo --output-on-failure`.
- Tests cover the independent setting, persistence/observer application, playback edges, duplicate
requests, already-connected behavior, cooldown, monitor shutdown and manual clicks during an
automatic check. UI tests use in-memory settings and do not write user preferences.
- An optional native Windows audio smoke test plays a quiet two-second tone in a separate process
and checks that the real playback probe detects its start and stop. Stop other playback first:

```powershell
$env:APD_RUN_AUDIO_SMOKE_TEST = '1'
.\Build\Binary\QuickConnectTests.exe nativePlaybackProbeDetectsExternalPlayback
Remove-Item Env:APD_RUN_AUDIO_SMOKE_TEST
```

For a hardware check, enable the option, disconnect the selected headphones, and start playback
on the PC. Confirm that one connection attempt occurs and the battery window opens on success.
Repeat while already connected and with the option off; neither case should initiate another
connection. With the headphones unavailable, confirm that continuous playback does not keep
retrying, and that restarting playback after the cooldown allows another attempt.
11 changes: 11 additions & 0 deletions Source/Application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
#include "Core/GlobalMedia.h"
#include "Core/LowAudioLatency.h"
#include "Core/QuickConnect.h"
#include "Core/PlaybackMonitor.h"
#if defined APD_OS_WIN
#include "Core/QuickConnect_win.h"
#endif
Expand Down Expand Up @@ -203,6 +204,10 @@ bool ApdApplication::Prepare(int argc, char *argv[])
_quickConnectBackend = std::make_shared<Core::QuickConnect::NullBackend>();
#endif
_quickConnect = std::make_unique<Core::QuickConnect::Controller>(_quickConnectBackend);
_playbackMonitor = std::make_unique<Core::GlobalMedia::PlaybackMonitor>();
connect(
_playbackMonitor.get(), &Core::GlobalMedia::PlaybackMonitor::PlaybackChanged,
_quickConnect.get(), &Core::QuickConnect::Controller::OnPlaybackStateChanged);

_trayIcon = std::make_unique<Gui::TrayIcon>(
[this] { return GetCurrentLoadedLocaleIndex(); }, *_quickConnect);
Expand Down Expand Up @@ -459,6 +464,12 @@ void ApdApplication::OnTrayQuickConnectDeviceChanged(const QString &deviceId)
_quickConnect->SetDeviceId(deviceId);
}

void ApdApplication::OnAudioAutoConnectEnabledChanged(bool enable)
{
_quickConnect->SetAudioAutoConnectEnabled(enable);
_playbackMonitor->SetEnabled(enable);
}

void ApdApplication::OnTaskbarBatteryChanged(Core::Settings::TaskbarStatusBehavior behavior)
{
emit _taskbarStatus->OnSettingsChangedSafely(behavior);
Expand Down
5 changes: 5 additions & 0 deletions Source/Application.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ namespace Core::QuickConnect {
class Backend;
class Controller;
} // namespace Core::QuickConnect
namespace Core::GlobalMedia {
class PlaybackMonitor;
}

namespace Gui {
class MainWindow;
Expand Down Expand Up @@ -86,6 +89,7 @@ class ApdApplication : public SingleApplication, private Core::Settings::ApplyOb
// in reverse declaration order.
std::shared_ptr<Core::QuickConnect::Backend> _quickConnectBackend;
std::unique_ptr<Core::QuickConnect::Controller> _quickConnect;
std::unique_ptr<Core::GlobalMedia::PlaybackMonitor> _playbackMonitor;
std::unique_ptr<Gui::TrayIcon> _trayIcon;
std::unique_ptr<Gui::TaskbarStatus> _taskbarStatus;
std::unique_ptr<Gui::MainWindow> _mainWindow;
Expand All @@ -111,6 +115,7 @@ class ApdApplication : public SingleApplication, private Core::Settings::ApplyOb
void OnDeviceAddressChanged(uint64_t address) override;
void OnTrayIconBatteryChanged(Core::Settings::TrayIconBatteryBehavior behavior) override;
void OnTrayQuickConnectEnabledChanged(bool enable) override;
void OnAudioAutoConnectEnabledChanged(bool enable) override;
void OnTrayQuickConnectDeviceChanged(const QString &deviceId) override;
void OnTaskbarBatteryChanged(Core::Settings::TaskbarStatusBehavior behavior) override;
};
Expand Down
41 changes: 41 additions & 0 deletions Source/Core/AirPodsStateManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,33 @@
using namespace std::chrono_literals;

namespace Core::AirPods::Details {
namespace {

bool HasConflictingPodBatteries(const State &lhs, const State &rhs)
{
const auto conflicts = [](const Battery &a, const Battery &b) {
// Broadcast batteries are quantized to 10% steps. Adjacent buckets can legitimately
// differ between pods; larger discrepancies cannot be merged as one current state.
return a.Available() && b.Available() &&
std::abs(static_cast<int>(a.Value()) - static_cast<int>(b.Value())) > 10;
};
return conflicts(lhs.pods.left.battery, rhs.pods.left.battery) ||
conflicts(lhs.pods.right.battery, rhs.pods.right.battery);
}

bool IsStrongerCompleteReport(const Advertisement &candidate, const Advertisement &cached)
{
const auto count = [](const State &state) {
return static_cast<int>(state.pods.left.battery.Available()) +
static_cast<int>(state.pods.right.battery.Available());
};
// Recover if the first observed packet was a weaker, single-pod report from another pair.
// Completeness alone must not let a distant pair replace the selected nearby single pod.
return count(candidate.GetAdvState()) > count(cached.GetAdvState()) &&
candidate.GetRssi() >= cached.GetRssi() + 10;
}

} // namespace

StateManager::StateManager()
{
Expand Down Expand Up @@ -171,6 +198,13 @@ bool StateManager::IsPossibleDesiredAdv(const Advertisement &adv) const
}

if (lastAnotherAdv.has_value()) {
if (HasConflictingPodBatteries(advState, lastAnotherAdv->first.GetAdvState())) {
if (IsStrongerCompleteReport(adv, lastAnotherAdv->first)) {
return true;
}
LOG(Trace, "Ignore conflicting battery reports from another advertisement source.");
return false;
}
int16_t rssiDiff = std::abs(advRssi - lastAnotherAdv->first.GetRssi());
if (rssiDiff > 50) {
LOG(Warn, "IsPossibleDesiredAdv returns false. Reason: Another side rssiDiff '{}'",
Expand All @@ -187,6 +221,13 @@ void StateManager::UpdateAdv(Advertisement adv)
_lostTimer.Reset();

const auto &advState = adv.GetAdvState();
auto &peer = advState.side == Side::Left ? _adv.right : _adv.left;
if (peer.has_value() && HasConflictingPodBatteries(advState, peer->first.GetAdvState()) &&
IsStrongerCompleteReport(adv, peer->first))
{
// Do not keep using the discarded source for fields missing from the replacement.
peer.reset();
}
if (advState.side == Side::Left) {
_stateResetTimer.left.Reset();
_adv.left = std::make_pair(std::move(adv), Clock::now());
Expand Down
89 changes: 89 additions & 0 deletions Source/Core/PlaybackMonitor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//
// AirPodsDesktop - AirPods Desktop User Experience Enhancement Program.
// Copyright (C) 2021-2022 SpriteOvO
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "PlaybackMonitor.h"

#include <condition_variable>
#include <mutex>
#include <utility>

#include <QMetaObject>

namespace Core::GlobalMedia {

PlaybackMonitor::PlaybackMonitor(
PlaybackProbe probe, std::chrono::milliseconds pollInterval,
std::chrono::milliseconds silenceInterval)
: _probe{std::move(probe)}, _pollInterval{pollInterval}, _silenceInterval{silenceInterval}
{
}

PlaybackMonitor::~PlaybackMonitor()
{
SetEnabled(false);
}

void PlaybackMonitor::SetEnabled(bool enabled)
{
if (enabled == _worker.joinable()) {
return;
}
++_generation;
if (!enabled) {
_worker.request_stop();
_worker.join();
return;
}

const auto generation = _generation;
_worker = std::jthread{[this, generation](std::stop_token stopToken) {
bool playing = false;
auto lastSound = std::chrono::steady_clock::now();
std::mutex mutex;
std::condition_variable_any wake;
std::unique_lock lock{mutex};
while (!stopToken.stop_requested()) {
const auto activity = _probe();
const auto now = std::chrono::steady_clock::now();
if (activity.has_value()) {
if (*activity) {
lastSound = now;
}
const bool next = *activity || (playing && now - lastSound < _silenceInterval);
if (playing != next) {
playing = next;
QMetaObject::invokeMethod(this, [this, generation, playing] {
if (_generation == generation) {
emit PlaybackChanged(playing);
}
});
}
}
wake.wait_for(lock, stopToken, _pollInterval, [] { return false; });
}
}};
}

#if !defined APD_OS_WIN
PlaybackProbe CreatePlaybackProbe()
{
return [] { return std::optional<bool>{false}; };
}
#endif

} // namespace Core::GlobalMedia
58 changes: 58 additions & 0 deletions Source/Core/PlaybackMonitor.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//
// AirPodsDesktop - AirPods Desktop User Experience Enhancement Program.
// Copyright (C) 2021-2022 SpriteOvO
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <chrono>
#include <functional>
#include <optional>
#include <thread>

#include <QObject>

namespace Core::GlobalMedia {

// Reads output activity only; no audio samples are captured or retained.
using PlaybackProbe = std::function<std::optional<bool>()>;
PlaybackProbe CreatePlaybackProbe();

class PlaybackMonitor final : public QObject
{
Q_OBJECT

public:
explicit PlaybackMonitor(
PlaybackProbe probe = CreatePlaybackProbe(),
std::chrono::milliseconds pollInterval = std::chrono::milliseconds{250},
std::chrono::milliseconds silenceInterval = std::chrono::milliseconds{1500});
~PlaybackMonitor() override;

void SetEnabled(bool enabled);

signals:
void PlaybackChanged(bool playing);

private:
PlaybackProbe _probe;
std::chrono::milliseconds _pollInterval;
std::chrono::milliseconds _silenceInterval;
std::jthread _worker;
unsigned _generation{};
};

} // namespace Core::GlobalMedia
Loading