Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: improved airpods handoff support

Zack Bartel24bc7a04f28f
diff --git a/src/core/include/tether/audio.hpp b/src/core/include/tether/audio.hpp
index 73cf572..940e83c 100644
--- a/src/core/include/tether/audio.hpp
+++ b/src/core/include/tether/audio.hpp
@@ -19,6 +19,20 @@ namespace tether::audio {
// again. False when it did not appear before the deadline.
bool restore_default_sink(const std::string& address, int timeout_ms);
+ // HACK: Whether a stream is attached to a Bluetooth device's sink while the sink stays
+ // suspended. PipeWire does not reopen a transport the device tore down under it.
+ bool bluez_sink_stuck(const std::string& address);
+
+ // HACK: Switches a Bluetooth device's card profile off and back, which rebuilds its sink.
+ bool restart_bluez_card(const std::string& address);
+
+ // HACK: Parsers for `pactl list short sinks` with `pactl list short sink-inputs`, and for
+ // `pactl list cards`, exposed for tests.
+ bool bluez_sink_stuck_in(const std::string& short_sinks,
+ const std::string& short_inputs,
+ const std::string& address);
+ std::string active_profile_in(const std::string& cards, const std::string& card);
+
// Sink name for a Bluetooth address, exposed for tests.
std::string sink_prefix(const std::string& address);
diff --git a/src/core/include/tether/bluetooth/airpods.hpp b/src/core/include/tether/bluetooth/airpods.hpp
index 36bf1ce..451e8b2 100644
--- a/src/core/include/tether/bluetooth/airpods.hpp
+++ b/src/core/include/tether/bluetooth/airpods.hpp
@@ -123,6 +123,8 @@ namespace tether::bluetooth {
std::string name;
bool peer_taking_over = false;
bool peer_active = false;
+ // A peer is on a call, held until the buds have stopped reporting it for a few seconds.
+ bool peer_call = false;
AirPodsBattery battery;
// Unset until the buds report one. Not every model has the feature.
std::optional<AncMode> anc;
@@ -148,14 +150,23 @@ namespace tether::bluetooth {
std::optional<EarState> parse_ear(const uint8_t* data, size_t len);
// Decodes a connected-devices notification:
- // 04 00 04 00 2E 00 [count] ([mac] * 6 [role] [state]) * count
- // The MAC is stored least-significant byte first here, unlike the audio-source
- // notification; both come back in BlueZ's own text order.
+ // 04 00 04 00 2E 00 [?] [?] [count] ([mac] * 6 [role] [state]) * count
+ // The MAC is in display order here and least-significant byte first in the
+ // audio-source notification; both come back in BlueZ's own text order.
std::optional<std::vector<AapPeer>> parse_connected_devices(const uint8_t* data, size_t len);
// Decodes an audio-source notification, 13 bytes: prefix, MAC, then the type.
std::optional<AudioSourceEvent> parse_audio_source(const uint8_t* data, size_t len);
+ // Whether the buds carrying this machine's audio should be answered with a claim. They
+ // route a non-owner's stream for a few seconds and then hand it back to the owner; a claim
+ // keeps it. `owns` is the last ownership verdict, unset until one arrives. Never while a
+ // peer is on a call.
+ bool claims_for_playback(const AudioSourceEvent& event,
+ const std::string& local,
+ std::optional<bool> owns,
+ bool peer_call);
+
// Whether any host other than `local` is engaged with the buds, or actively
// holding them. A machine's own entry is never a peer.
struct PeerSummary {
@@ -177,6 +188,11 @@ namespace tether::bluetooth {
// `holding` is whether the caller has a pause outstanding.
MediaAction ear_media_action(const EarState& before, const EarState& after, PauseMode mode, bool holding);
+ // What a call on the phone should do to local playback. `paused_for_call` is whether
+ // this pause is outstanding: only it is undone, and it is undone even if the setting
+ // was switched off during the call.
+ MediaAction call_media_action(bool call_before, bool call_after, bool enabled, bool paused_for_call);
+
// What an iPhone call should do to AirPods that are connected to this machine.
enum class HandoffAction { None, Release, Reclaim };
diff --git a/src/core/src/audio.cpp b/src/core/src/audio.cpp
index 474ab53..217c42e 100644
--- a/src/core/src/audio.cpp
+++ b/src/core/src/audio.cpp
@@ -6,12 +6,15 @@
#include <glib.h>
#include <sstream>
#include <thread>
+#include <vector>
namespace tether::audio {
namespace {
constexpr int POLL_INTERVAL_MS = 200;
+ // HACK: Between switching a card off and back on, so the audio server finishes tearing it down.
+ constexpr int PROFILE_SETTLE_MS = 2000;
std::string trimmed(const std::string& text) {
const size_t begin = text.find_first_not_of(" \t\r\n");
@@ -43,6 +46,14 @@ namespace tether::audio {
return text;
}
+ std::vector<std::string> tab_fields(const std::string& line) {
+ std::vector<std::string> out;
+ std::istringstream fields(line);
+ for (std::string field; std::getline(fields, field, '\t');)
+ out.push_back(field);
+ return out;
+ }
+
} // namespace
std::string sink_prefix(const std::string& address) {
@@ -95,4 +106,75 @@ namespace tether::audio {
return false;
}
+ // HACK
+ bool bluez_sink_stuck_in(const std::string& short_sinks,
+ const std::string& short_inputs,
+ const std::string& address) {
+ if (address.empty())
+ return false;
+ const std::string prefix = sink_prefix(address);
+ std::string index;
+ std::istringstream sinks(short_sinks);
+ for (std::string line; std::getline(sinks, line);) {
+ // index<TAB>name<TAB>driver<TAB>format<TAB>state
+ const auto fields = tab_fields(line);
+ if (fields.size() < 5 || fields[1].rfind(prefix, 0) != 0)
+ continue;
+ if (trimmed(fields[4]) != "SUSPENDED")
+ return false;
+ index = fields[0];
+ break;
+ }
+ if (index.empty())
+ return false;
+ std::istringstream inputs(short_inputs);
+ for (std::string line; std::getline(inputs, line);) {
+ // index<TAB>sink<TAB>client<TAB>driver<TAB>format
+ const auto fields = tab_fields(line);
+ if (fields.size() >= 2 && fields[1] == index)
+ return true;
+ }
+ return false;
+ }
+
+ std::string active_profile_in(const std::string& cards, const std::string& card) {
+ constexpr std::string_view ACTIVE = "Active Profile: ";
+ bool in_card = false;
+ std::istringstream lines(cards);
+ for (std::string line; std::getline(lines, line);) {
+ const std::string text = trimmed(line);
+ if (text.rfind("Card #", 0) == 0)
+ in_card = false;
+ else if (text == "Name: " + card)
+ in_card = true;
+ else if (in_card && text.rfind(ACTIVE, 0) == 0)
+ return text.substr(ACTIVE.size());
+ }
+ return {};
+ }
+
+ // HACK
+ bool bluez_sink_stuck(const std::string& address) {
+ if (address.empty())
+ return false;
+ return bluez_sink_stuck_in(run("pactl list short sinks"), run("pactl list short sink-inputs"), address);
+ }
+
+ // HACK
+ bool restart_bluez_card(const std::string& address) {
+ if (address.empty())
+ return false;
+ const std::string card = "bluez_card." + sink_prefix(address).substr(sizeof("bluez_output.") - 1);
+ const std::string profile = active_profile_in(run("pactl list cards"), card);
+ if (profile.empty() || profile == "off")
+ return false;
+ bool ok = false;
+ run(("pactl set-card-profile " + card + " off").c_str(), &ok);
+ if (!ok)
+ return false;
+ std::this_thread::sleep_for(std::chrono::milliseconds(PROFILE_SETTLE_MS));
+ run(("pactl set-card-profile " + card + " " + profile).c_str(), &ok);
+ return ok;
+ }
+
} // namespace tether::audio
diff --git a/src/core/src/bluetooth/airpods.cpp b/src/core/src/bluetooth/airpods.cpp
index c8ec736..32d2ee8 100644
--- a/src/core/src/bluetooth/airpods.cpp
+++ b/src/core/src/bluetooth/airpods.cpp
@@ -90,6 +90,8 @@ namespace tether::bluetooth {
constexpr size_t EAR_PACKET_BYTES = 8;
constexpr uint8_t CONNECTED_DEVICES_PREFIX[] = {0x04, 0x00, 0x04, 0x00, 0x2e, 0x00};
+ // Two bytes of unknown meaning sit between the prefix and the count.
+ constexpr size_t CONNECTED_DEVICES_COUNT_OFFSET = 8;
constexpr size_t CONNECTED_DEVICES_ENTRY_BYTES = 8;
constexpr uint8_t AUDIO_SOURCE_PREFIX[] = {0x04, 0x00, 0x04, 0x00, 0x0e, 0x00};
@@ -105,10 +107,13 @@ namespace tether::bluetooth {
// Sent anyway when the buds do not acknowledge; some models never do.
constexpr int FEATURES_FALLBACK_MS = 500;
constexpr int NOTIFICATIONS_AT_MS = 600;
- // The buds broadcast their host list unprompted at roughly 800ms. The opening
- // claim waits for it so it can be skipped when the phone already has them, and
- // goes out anyway at this deadline when no list arrives.
- constexpr int OPENING_CLAIM_BY_MS = 1500;
+ // How long a claim waits after the channel opens or this machine starts playing.
+ // A claim sent while the audio link is still being set up makes the buds drop
+ // the link; the AirPods Center reference puts audio setup safe from 5s.
+ constexpr int CLAIM_SETTLE_MS = 5000;
+ // How long the buds must stop reporting a peer's call before it counts as over:
+ // some models report no audio source every twenty seconds or so during a call.
+ constexpr int CALL_END_SETTLE_MS = 3000;
constexpr int CONNECT_TIMEOUT_MS = 8000;
constexpr int FIRST_PACKET_TIMEOUT_MS = 8000;
@@ -180,6 +185,19 @@ namespace tether::bluetooth {
return ::send(fd, data, len, MSG_NOSIGNAL) == static_cast<ssize_t>(len);
}
+ std::string hex(const uint8_t* data, size_t len) {
+ static constexpr char HEX[] = "0123456789abcdef";
+ std::string out;
+ out.reserve(len * 3);
+ for (size_t i = 0; i < len; ++i) {
+ if (i > 0)
+ out.push_back(' ');
+ out.push_back(HEX[data[i] >> 4]);
+ out.push_back(HEX[data[i] & 0x0f]);
+ }
+ return out;
+ }
+
} // namespace
const char* to_string(AirPodsStatus status) {
@@ -210,6 +228,7 @@ namespace tether::bluetooth {
{"in_ear", s.ear.in_ear()},
{"peer_taking_over", s.peer_taking_over},
{"peer_active", s.peer_active},
+ {"peer_call", s.peer_call},
{"status", to_string(s.status)},
{"reason", s.reason},
};
@@ -286,20 +305,20 @@ namespace tether::bluetooth {
}
std::optional<std::vector<AapPeer>> parse_connected_devices(const uint8_t* data, size_t len) {
- if (data == nullptr || len < sizeof(CONNECTED_DEVICES_PREFIX) + 1)
+ if (data == nullptr || len < CONNECTED_DEVICES_COUNT_OFFSET + 1)
return std::nullopt;
if (std::memcmp(data, CONNECTED_DEVICES_PREFIX, sizeof(CONNECTED_DEVICES_PREFIX)) != 0)
return std::nullopt;
- const size_t count = data[sizeof(CONNECTED_DEVICES_PREFIX)];
- size_t offset = sizeof(CONNECTED_DEVICES_PREFIX) + 1;
+ const size_t count = data[CONNECTED_DEVICES_COUNT_OFFSET];
+ size_t offset = CONNECTED_DEVICES_COUNT_OFFSET + 1;
if (offset + count * CONNECTED_DEVICES_ENTRY_BYTES > len)
return std::nullopt;
std::vector<AapPeer> peers;
peers.reserve(count);
for (size_t i = 0; i < count; ++i, offset += CONNECTED_DEVICES_ENTRY_BYTES)
- peers.push_back({format_address(data + offset, true), data[offset + 6], data[offset + 7]});
+ peers.push_back({format_address(data + offset, false), data[offset + 6], data[offset + 7]});
return peers;
}
@@ -310,7 +329,7 @@ namespace tether::bluetooth {
return std::nullopt;
AudioSourceEvent event;
- event.address = format_address(data + sizeof(AUDIO_SOURCE_PREFIX), false);
+ event.address = format_address(data + sizeof(AUDIO_SOURCE_PREFIX), true);
switch (data[AUDIO_SOURCE_PACKET_BYTES - 1]) {
case 0x01:
event.source = AudioSource::Call;
@@ -394,6 +413,22 @@ namespace tether::bluetooth {
return HandoffAction::None;
}
+ MediaAction call_media_action(bool call_before, bool call_after, bool enabled, bool paused_for_call) {
+ if (call_before && !call_after && paused_for_call)
+ return MediaAction::Resume;
+ if (enabled && !call_before && call_after)
+ return MediaAction::Pause;
+ return MediaAction::None;
+ }
+
+ bool claims_for_playback(const AudioSourceEvent& event,
+ const std::string& local,
+ std::optional<bool> owns,
+ bool peer_call) {
+ return !local.empty() && event.address == local && event.source != AudioSource::None && owns == false &&
+ !peer_call;
+ }
+
PeerSummary summarize_peers(const std::vector<AapPeer>& peers, const std::string& local) {
PeerSummary summary;
for (const auto& peer : peers) {
@@ -510,13 +545,18 @@ namespace tether::bluetooth {
// Records a peer list, logging every ownership transition: almost every
// diagnosis of a dropped link starts from one.
- void note_peers(const std::vector<AapPeer>& peers, std::map<std::string, uint8_t>& seen, bool delivered) {
+ void note_peers(const std::vector<AapPeer>& peers,
+ std::map<std::string, uint8_t>& seen,
+ bool& warned_unlisted,
+ bool delivered) {
std::string local;
{
std::lock_guard<std::mutex> lock(mutex);
local = local_address;
}
+ bool listed = false;
for (const auto& peer : peers) {
+ listed = listed || peer.address == local;
auto [it, inserted] = seen.insert({peer.address, peer.state});
if (inserted || it->second != peer.state) {
debug::log(DEBUG,
@@ -529,6 +569,12 @@ namespace tether::bluetooth {
}
}
+ // Without its own entry this machine reads as a peer: an eviction, or a misread list.
+ if (!local.empty() && !listed && !warned_unlisted) {
+ debug::log(DEBUG, "airpods: this machine ({}) is not in the buds' host list", local);
+ warned_unlisted = true;
+ }
+
const auto summary = summarize_peers(peers, local);
{
std::lock_guard<std::mutex> lock(mutex);
@@ -544,8 +590,10 @@ namespace tether::bluetooth {
// iPhone is not that: claiming out from under one is the whole point.
bool send_ownership(int fd, bool own) {
if (!own) {
- if (write_all(fd, RELEASE, sizeof(RELEASE)))
+ if (write_all(fd, RELEASE, sizeof(RELEASE))) {
+ debug::log(DEBUG, "airpods: release sent");
return true;
+ }
debug::log(DEBUG, "airpods: release write failed: {}", std::strerror(errno));
return false;
}
@@ -563,8 +611,10 @@ namespace tether::bluetooth {
return true;
last_claim = now;
}
- if (write_all(fd, CLAIM, sizeof(CLAIM)))
+ if (write_all(fd, CLAIM, sizeof(CLAIM))) {
+ debug::log(DEBUG, "airpods: claim sent");
return true;
+ }
debug::log(DEBUG, "airpods: claim write failed: {}", std::strerror(errno));
return false;
}
@@ -592,8 +642,8 @@ namespace tether::bluetooth {
return false;
}
- // Runs one channel from connect to close. Sets `delivered` when at least one
- // battery packet arrived, which is what separates a contended channel from a
+ // Runs one channel from connect to close. Sets `delivered` when the buds sent
+ // any notification, which is what separates a contended channel from a
// healthy but quiet one.
void session(const std::string& address, bool& delivered) {
uint8_t addr[6] = {};
@@ -669,7 +719,6 @@ namespace tether::bluetooth {
if (!write_all(fd, REQUEST_NOTIFICATIONS, sizeof(REQUEST_NOTIFICATIONS)))
return false;
stage = Stage::Ready;
- due = opened + std::chrono::milliseconds(OPENING_CLAIM_BY_MS);
return true;
case Stage::Ready:
return true;
@@ -679,10 +728,10 @@ namespace tether::bluetooth {
// AirPods Pro 2 validates a host by itself once the session is up; Pro 3
// never does, and an unvalidated host is dropped at the first pod movement.
- // So a session claims once it knows the phone does not have them, and keeps
- // waiting for that to be true rather than claiming into a peer's call.
+ // So a session claims once the buds' host list proves the channel is live,
+ // never into a peer taking them, and only after the audio link has settled.
bool claim_sent = false;
- bool claim_deadline_passed = false;
+ std::optional<clock::time_point> claim_at;
const auto claim = [&] {
bool blocked = false;
{
@@ -696,16 +745,37 @@ namespace tether::bluetooth {
};
std::map<std::string, uint8_t> peer_states;
+ bool warned_unlisted = false;
+ std::optional<bool> owns;
+ bool peer_call = false;
+ std::optional<AudioSourceEvent> latest_source;
+ std::optional<clock::time_point> call_ends_at;
+ // Published so local playback can step aside while the phone has a call.
+ const auto set_peer_call = [&](bool on) {
+ peer_call = on;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ state.peer_call = on;
+ }
+ publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");
+ };
std::array<uint8_t, 1024> buffer{};
while (!retargeted(address)) {
const auto now = clock::now();
- const auto quiet_for = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_packet);
+ // Until the buds send a notification, stray bytes do not keep an attempt alive:
+ // a channel another client holds stays open and says nothing useful.
+ const auto quiet_since = delivered ? last_packet : opened;
const int quiet_timeout = (delivered ? IDLE_TIMEOUT_MS : FIRST_PACKET_TIMEOUT_MS);
- int timeout = quiet_timeout - static_cast<int>(quiet_for.count());
- if (stage != Stage::Ready || !claim_deadline_passed) {
- const auto until_due = std::chrono::duration_cast<std::chrono::milliseconds>(due - now);
- timeout = std::min(timeout, static_cast<int>(until_due.count()));
- }
+ const auto until = [&](clock::time_point at) {
+ return static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(at - now).count());
+ };
+ int timeout = until(quiet_since + std::chrono::milliseconds(quiet_timeout));
+ if (stage != Stage::Ready)
+ timeout = std::min(timeout, until(due));
+ if (claim_at)
+ timeout = std::min(timeout, until(*claim_at));
+ if (call_ends_at)
+ timeout = std::min(timeout, until(*call_ends_at));
const int ready = wait_for(fd, wake_fd, POLLIN, std::max(timeout, 0));
if (ready == 0) {
drain_wake();
@@ -716,21 +786,41 @@ namespace tether::bluetooth {
if (ready == -2)
break;
if (ready < 0) {
- if (clock::now() >= due) {
- if (stage != Stage::Ready) {
- if (!advance(clock::now()))
+ const auto fired = clock::now();
+ if (stage != Stage::Ready && fired >= due) {
+ if (!advance(fired))
+ break;
+ continue;
+ }
+ if (call_ends_at && fired >= *call_ends_at) {
+ call_ends_at.reset();
+ set_peer_call(false);
+ continue;
+ }
+ if (claim_at && fired >= *claim_at) {
+ claim_at.reset();
+ std::string local;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ local = local_address;
+ }
+ // Decided on the state at firing time: a call or a new owner since
+ // the claim was armed cancels it.
+ if (!claim_sent) {
+ if (!claim())
+ break;
+ } else if (latest_source && claims_for_playback(*latest_source, local, owns, peer_call)) {
+ debug::log(DEBUG, "airpods: claiming for playback here");
+ if (!send_ownership(fd, true))
break;
- continue;
}
- // No host list arrived in time, so claim on the reference's own
- // schedule and let the peer check catch the rest.
- claim_deadline_passed = true;
- if (!claim_sent && !claim())
- break;
continue;
}
- if (clock::now() - last_packet >= std::chrono::milliseconds(quiet_timeout))
+ if (fired - quiet_since >= std::chrono::milliseconds(quiet_timeout)) {
+ if (!delivered)
+ debug::log(DEBUG, "airpods: no notification within {}ms", FIRST_PACKET_TIMEOUT_MS);
break;
+ }
continue;
}
@@ -756,29 +846,58 @@ namespace tether::bluetooth {
if (starts_with(buffer.data(), size, OWNS_CONNECTION_PREFIX, sizeof(OWNS_CONNECTION_PREFIX)) &&
size > sizeof(OWNS_CONNECTION_PREFIX)) {
+ delivered = true;
+ owns = buffer[sizeof(OWNS_CONNECTION_PREFIX)] == 0x01;
debug::log(DEBUG, "airpods: ownership verdict {:#04x}", buffer[sizeof(OWNS_CONNECTION_PREFIX)]);
continue;
}
+ // Ownership runs on these two; the raw bytes settle any doubt about the layout.
+ if (starts_with(buffer.data(), size, CONNECTED_DEVICES_PREFIX, sizeof(CONNECTED_DEVICES_PREFIX)) ||
+ starts_with(buffer.data(), size, AUDIO_SOURCE_PREFIX, sizeof(AUDIO_SOURCE_PREFIX)))
+ debug::log(DEBUG, "airpods: rx {}", hex(buffer.data(), size));
+
if (auto peers = parse_connected_devices(buffer.data(), size)) {
- note_peers(*peers, peer_states, delivered);
- // The host list is what says whether claiming is safe.
- if (stage == Stage::Ready && !claim_sent && !claim())
- break;
+ delivered = true;
+ note_peers(*peers, peer_states, warned_unlisted, delivered);
+ // The host list proves the channel is ours; the claim waits for the audio link.
+ if (!claim_sent && !claim_at)
+ claim_at = std::max(last_packet, opened + std::chrono::milliseconds(CLAIM_SETTLE_MS));
continue;
}
if (auto source = parse_audio_source(buffer.data(), size)) {
+ delivered = true;
debug::log(DEBUG,
"airpods: audio source {} on {}",
source->source == AudioSource::Call ? "call"
: source->source == AudioSource::Media ? "media"
: "none",
source->address);
+ std::string local;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ local = local_address;
+ }
+ latest_source = *source;
+ // Re-armed on every stream start, so the claim waits for the newest one to settle.
+ if (claims_for_playback(*source, local, owns, peer_call)) {
+ claim_at = last_packet + std::chrono::milliseconds(CLAIM_SETTLE_MS);
+ debug::log(
+ DEBUG, "airpods: playing here without owning the buds; claiming in {}ms", CLAIM_SETTLE_MS);
+ }
+ if (source->source == AudioSource::Call && source->address != local) {
+ call_ends_at.reset();
+ if (!peer_call)
+ set_peer_call(true);
+ } else if (peer_call && !call_ends_at) {
+ call_ends_at = last_packet + std::chrono::milliseconds(CALL_END_SETTLE_MS);
+ }
continue;
}
if (auto mode = parse_anc(buffer.data(), size)) {
+ delivered = true;
{
std::lock_guard<std::mutex> lock(mutex);
state.anc = *mode;
@@ -788,6 +907,7 @@ namespace tether::bluetooth {
}
if (auto ear = parse_ear(buffer.data(), size)) {
+ delivered = true;
{
std::lock_guard<std::mutex> lock(mutex);
state.ear = *ear;
@@ -813,6 +933,7 @@ namespace tether::bluetooth {
std::lock_guard<std::mutex> lock(mutex);
pending_anc.reset();
pending_ownership.reset();
+ state.peer_call = false;
}
::close(fd);
}
@@ -842,6 +963,7 @@ namespace tether::bluetooth {
state.ear = {};
state.peer_taking_over = false;
state.peer_active = false;
+ state.peer_call = false;
}
publish(AirPodsStatus::Idle, "");
backoff_ms = BACKOFF_START_MS;
@@ -860,6 +982,7 @@ namespace tether::bluetooth {
state.ear = {};
state.peer_taking_over = false;
state.peer_active = false;
+ state.peer_call = false;
}
state.name = name;
}
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 43d4214..a177058 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -58,6 +58,8 @@ constexpr int HANDOFF_RECLAIM_ATTEMPTS = 3;
constexpr int HANDOFF_GUARD_SECONDS = 3;
// How long to wait for the buds' sink to come back before resuming anything.
constexpr int SINK_RETURN_TIMEOUT_MS = 8000;
+// HACK: After a rebuilt Bluetooth sink reappears, time for the audio server to move streams back onto it.
+constexpr int SINK_SETTLE_SECONDS = 1;
int main(int argc, char** argv) {
redirect_output_to_log();
@@ -354,8 +356,11 @@ int main(int argc, char** argv) {
// AirPods battery arrives on its own L2CAP channel, not through BlueZ.
tether::MediaControl media;
tether::bluetooth::EarState last_ear;
+ bool last_peer_call = false;
+ bool paused_for_call = false;
tether::bluetooth::AirPodsWatcher airpods(
- [&media, &last_ear, handoff, &native_handoff, &run_ownership](const tether::bluetooth::AirPodsState& state) {
+ [&media, &last_ear, &last_peer_call, &paused_for_call, handoff, &native_handoff, &run_ownership](
+ const tether::bluetooth::AirPodsState& state) {
const auto config = tether::bluetooth::load_config();
const auto mode = config.airpods_enabled ? config.airpods_pause : tether::bluetooth::PauseMode::Never;
switch (tether::bluetooth::ear_media_action(last_ear, state.ear, mode, media.holding())) {
@@ -371,13 +376,61 @@ int main(int argc, char** argv) {
break;
}
- if (state.address.empty() && !handoff->holding_buds())
+ bool resume_after_call = false;
+ switch (tether::bluetooth::call_media_action(
+ last_peer_call, state.peer_call, config.airpods_enabled && config.airpods_handoff, paused_for_call)) {
+ case tether::bluetooth::MediaAction::Pause:
+ if (const size_t paused = media.pause()) {
+ paused_for_call = true;
+ debug::log(INFO, "airpods: paused {} player(s), the iPhone has a call", paused);
+ }
+ break;
+ case tether::bluetooth::MediaAction::Resume:
+ paused_for_call = false;
+ // Resuming without the buds would move the audio to the speakers.
+ resume_after_call = !state.address.empty();
+ break;
+ case tether::bluetooth::MediaAction::None:
+ break;
+ }
+
+ // HACK: The phone tore down this machine's transport when it took the buds, and PipeWire does
+ // not reopen it, so a sink left suspended with a stream on it is rebuilt. Players stay
+ // paused meanwhile: with the card off their streams fall back to the speakers.
+ if (last_peer_call && !state.peer_call && !state.address.empty()) {
+ std::thread([address = state.address, resume = resume_after_call] {
+ const bool stuck = tether::audio::default_sink() == tether::audio::bluez_sink(address) &&
+ tether::audio::bluez_sink_stuck(address);
+ if (stuck) {
+ debug::log(INFO, "airpods: the Bluetooth sink stayed suspended after the call; rebuilding it");
+ if (tether::g_media)
+ tether::g_media->pause();
+ if (!tether::audio::restart_bluez_card(address) ||
+ !tether::audio::restore_default_sink(address, SINK_RETURN_TIMEOUT_MS)) {
+ debug::log(WARN, "airpods: could not rebuild the Bluetooth sink for {}", address);
+ if (tether::g_media)
+ tether::g_media->forget();
+ return;
+ }
+ std::this_thread::sleep_for(std::chrono::seconds(SINK_SETTLE_SECONDS));
+ }
+ if ((resume || stuck) && tether::g_media) {
+ if (const size_t resumed = tether::g_media->resume())
+ debug::log(INFO, "airpods: resumed {} player(s), the call ended", resumed);
+ }
+ }).detach();
+ }
+
+ if (state.address.empty() && !handoff->holding_buds()) {
media.forget();
+ paused_for_call = false;
+ }
if (native_handoff.load())
run_ownership(state);
last_ear = state.ear;
+ last_peer_call = state.peer_call;
tether::broadcast_local_event(tether::bluetooth::to_json(state).dump());
});
diff --git a/test/test_airpods.cpp b/test/test_airpods.cpp
index 4eca974..973acf5 100644
--- a/test/test_airpods.cpp
+++ b/test/test_airpods.cpp
@@ -193,22 +193,36 @@ TEST(AirPods, TreatsTheBatteryStatusAsABitmask) {
}
TEST(AirPods, ParsesTheConnectedDeviceList) {
- // Two hosts: this machine, then an iPhone sitting idle. Addresses are stored
- // least-significant byte first.
- const std::vector<uint8_t> packet = {0x04, 0x00, 0x04, 0x00, 0x2e, 0x00, 0x02, 0x9c, 0x52, 0xaf, 0x3c, 0xf2,
- 0xac, 0x01, 0x03, 0xf3, 0x6a, 0x30, 0xc8, 0x71, 0x81, 0x02, 0x15};
+ // Two hosts: this machine, then an iPhone sitting idle. The count is at offset 8
+ // and addresses are in display order.
+ const std::vector<uint8_t> packet = {0x04, 0x00, 0x04, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x02,
+ 0xac, 0xf2, 0x3c, 0xaf, 0x52, 0x9c, 0x00, 0x03,
+ 0x60, 0x57, 0xc8, 0x30, 0x6a, 0xf7, 0x01, 0x15};
auto peers = parse_connected_devices(packet.data(), packet.size());
ASSERT_TRUE(peers.has_value());
ASSERT_EQ(peers->size(), 2u);
EXPECT_EQ((*peers)[0].address, "AC:F2:3C:AF:52:9C");
EXPECT_EQ((*peers)[0].state, 0x03);
- EXPECT_FALSE((*peers)[0].taking_over());
- EXPECT_EQ((*peers)[1].address, "81:71:C8:30:6A:F3");
+ EXPECT_EQ((*peers)[1].address, "60:57:C8:30:6A:F7");
// 0x15 is an iPhone sitting there doing nothing, which is the state this machine
// claims the buds out of. Reading it as "taken" means never claiming at all.
EXPECT_FALSE((*peers)[1].taking_over());
EXPECT_FALSE((*peers)[1].active());
+ // Misreading the layout makes this machine's own entry a peer holding the buds.
+ const auto summary = summarize_peers(*peers, "AC:F2:3C:AF:52:9C");
+ EXPECT_FALSE(summary.taking_over);
+ EXPECT_FALSE(summary.active);
+
+ // Captured 2026-09-10 from AirPods Pro 3 with only this machine attached.
+ const std::vector<uint8_t> alone = {
+ 0x04, 0x00, 0x04, 0x00, 0x2e, 0x00, 0x01, 0x00, 0x01, 0xac, 0xf2, 0x3c, 0xaf, 0x52, 0x9c, 0x02, 0x02};
+ auto only_us = parse_connected_devices(alone.data(), alone.size());
+ ASSERT_TRUE(only_us.has_value());
+ ASSERT_EQ(only_us->size(), 1u);
+ EXPECT_EQ((*only_us)[0].address, "AC:F2:3C:AF:52:9C");
+ EXPECT_EQ((*only_us)[0].state, 0x02);
+
// A truncated list is not a list.
EXPECT_FALSE(parse_connected_devices(packet.data(), packet.size() - 1).has_value());
EXPECT_FALSE(parse_connected_devices(packet.data(), 4).has_value());
@@ -243,16 +257,43 @@ TEST(AirPods, SummarisesPeersWithoutCountingItself) {
}
TEST(AirPods, ParsesTheAudioSource) {
- // Here the address is not reversed.
- const std::vector<uint8_t> packet = {0x04, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x81, 0x71, 0xc8, 0x30, 0x6a, 0xf3, 0x01};
+ // Here the address is least-significant byte first.
+ const std::vector<uint8_t> packet = {0x04, 0x00, 0x04, 0x00, 0x0e, 0x00, 0xf7, 0x6a, 0x30, 0xc8, 0x57, 0x60, 0x01};
auto event = parse_audio_source(packet.data(), packet.size());
ASSERT_TRUE(event.has_value());
- EXPECT_EQ(event->address, "81:71:C8:30:6A:F3");
+ EXPECT_EQ(event->address, "60:57:C8:30:6A:F7");
EXPECT_EQ(event->source, AudioSource::Call);
EXPECT_FALSE(parse_audio_source(packet.data(), packet.size() - 1).has_value());
}
+TEST(AirPods, PausesForAPhoneCallAndResumesAfter) {
+ EXPECT_EQ(call_media_action(false, true, true, false), MediaAction::Pause);
+ EXPECT_EQ(call_media_action(true, true, true, true), MediaAction::None);
+ EXPECT_EQ(call_media_action(true, false, true, true), MediaAction::Resume);
+ // Playback that was already stopped when the call came in stays stopped.
+ EXPECT_EQ(call_media_action(true, false, true, false), MediaAction::None);
+ EXPECT_EQ(call_media_action(false, true, false, false), MediaAction::None);
+ // Switching handoff off during the call still gives the music back.
+ EXPECT_EQ(call_media_action(true, false, false, true), MediaAction::Resume);
+}
+
+// Measured on AirPods Pro 3: the buds route this machine's stream while the phone still owns
+// them, then hand the route back to the phone within seconds.
+TEST(AirPods, ClaimsWhenPlayingHereWithoutOwningTheBuds) {
+ const std::string local = "AC:F2:3C:AF:52:9C";
+ const AudioSourceEvent here{local, AudioSource::Media};
+ EXPECT_TRUE(claims_for_playback(here, local, false, false));
+ EXPECT_FALSE(claims_for_playback(here, local, true, false));
+ // No verdict yet: the opening claim covers a new session.
+ EXPECT_FALSE(claims_for_playback(here, local, std::nullopt, false));
+ // Taking the buds off a phone call is the one thing this must never do.
+ EXPECT_FALSE(claims_for_playback(here, local, false, true));
+ EXPECT_FALSE(claims_for_playback({"60:57:C8:30:6A:F7", AudioSource::Media}, local, false, false));
+ EXPECT_FALSE(claims_for_playback({local, AudioSource::None}, local, false, false));
+ EXPECT_FALSE(claims_for_playback(here, "", false, false));
+}
+
TEST(AirPods, OwnershipFollowsThePeerTakingTheBuds) {
EXPECT_EQ(ownership_action(true, false, true), HandoffAction::Release);
// Given up already: nothing to give up twice.
diff --git a/test/test_audio.cpp b/test/test_audio.cpp
index 5e83d47..e549ee5 100644
--- a/test/test_audio.cpp
+++ b/test/test_audio.cpp
@@ -13,3 +13,29 @@ TEST(Audio, NamesTheSinkAfterTheAddress) {
// No address means no sink to look for, and no pactl call.
TEST(Audio, HasNoSinkWithoutAnAddress) { EXPECT_TRUE(bluez_sink("").empty()); }
+
+// Captured 2026-09-10 after an iPhone call tore down the AirPods transport: the sink
+// stayed suspended while the player kept feeding it.
+TEST(Audio, SeesAStreamStuckOnASuspendedBluetoothSink) {
+ const std::string sinks = "54\talsa_output.pci-0000_c1_00.6.analog-stereo\tPipeWire\ts32le 2ch 48000Hz\tSUSPENDED\n"
+ "249\tbluez_output.F8_D3_F0_3C_84_4A.1\tPipeWire\ts16le 2ch 48000Hz\tSUSPENDED\n";
+ const std::string inputs = "236\t249\t235\tPipeWire\tfloat32le 2ch 48000Hz\n";
+ EXPECT_TRUE(bluez_sink_stuck_in(sinks, inputs, "F8:D3:F0:3C:84:4A"));
+
+ // Nothing attached: a suspended sink is only idle.
+ EXPECT_FALSE(bluez_sink_stuck_in(sinks, "", "F8:D3:F0:3C:84:4A"));
+ // A stream on another sink is not this one's.
+ EXPECT_FALSE(bluez_sink_stuck_in(sinks, "236\t54\t235\tPipeWire\tfloat32le 2ch 48000Hz\n", "F8:D3:F0:3C:84:4A"));
+ const std::string running = "249\tbluez_output.F8_D3_F0_3C_84_4A.1\tPipeWire\ts16le 2ch 48000Hz\tRUNNING\n";
+ EXPECT_FALSE(bluez_sink_stuck_in(running, inputs, "F8:D3:F0:3C:84:4A"));
+ EXPECT_FALSE(bluez_sink_stuck_in(sinks, inputs, ""));
+}
+
+TEST(Audio, ReadsACardsActiveProfile) {
+ const std::string cards = "Card #82\n\tName: bluez_card.60_57_C8_30_6A_F7\n\tActive Profile: audio-gateway\n"
+ "Card #245\n\tName: bluez_card.F8_D3_F0_3C_84_4A\n\tProperties:\n"
+ "\t\tdevice.name = \"bluez_card.F8_D3_F0_3C_84_4A\"\n\tActive Profile: a2dp-sink\n";
+ EXPECT_EQ(active_profile_in(cards, "bluez_card.F8_D3_F0_3C_84_4A"), "a2dp-sink");
+ EXPECT_EQ(active_profile_in(cards, "bluez_card.60_57_C8_30_6A_F7"), "audio-gateway");
+ EXPECT_TRUE(active_profile_in(cards, "bluez_card.00_00_00_00_00_00").empty());
+}