Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: more aiprods handoff improvements

Zack Bartelb71d2da21996
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.md
index 0c84ebd..73fab0d 100644
--- a/docs/BLUETOOTH.md
+++ b/docs/BLUETOOTH.md
@@ -526,26 +526,26 @@ unacknowledged step must not stall the session.
Two more notifications are read, and they are what the ownership handoff runs on:
```
-connected-devices 04 00 04 00 2E 00 [count] ([mac] * 6 [role] [state]) * count
+connected-devices 04 00 04 00 2E 00 [?] [?] [count] ([mac] * 6 [role] [state]) * count
audio-source 04 00 04 00 0E 00 [mac] * 6 [type]
```
-`state` is the ownership field. **Read it as a threshold, never as an exact value**: at or
-above `0x10` a host is engaged or about to be, `0x17` is an active owner, below `0x10` it
-is not engaged. The exact numbers differ between models -- an idle iPhone sits at `0x15` on
-AirPods Pro 2 and 3 and at `0x01` forever on Pro 1 -- so a rule written against exact
-values breaks on somebody else's buds.
+`state` is the ownership field. **The owner carries bit `0x02`**; never compare exact values.
+The numbers differ between buds: an iPhone idles at `0x15` and owns at `0x17` on the buds the
+first implementation was written against, and at `0x05` and `0x07` on AirPods Pro 3 measured
+2026-09-10, where this machine reads `0x00` and `0x02`. Pro 1 leaves an idle iPhone at `0x01`.
+An earlier threshold rule (`0x17` and above owns) never fired on the Pro 3 values.
-`0x15` is the one value that has to be carved out of that rule, and getting it wrong costs
-the whole feature. It is what a **connected, idle iPhone** reports, permanently, and it is
-the state this machine claims the buds *out of*. Treating it as "a peer has them" means the
-claim is never sent, this machine never owns anything, and the phone keeps the buds --
-which is exactly what a first cut of this did. So: a peer at `0x10`-`0x14` is escalating
-and blocks a claim, `0x17` is holding them and blocks a claim, `0x15` blocks nothing.
+A peer blocks a claim when it sits at `0x10` or above and is not `0x15`. Owning alone does
+not: on Pro 3 the iPhone keeps `0x02` after its call ends, until another host claims.
+`0x15` is carved out because it is what a **connected, idle iPhone** reports, permanently, and
+it is the state this machine claims the buds *out of*. Treating it as "a peer has them" means
+the claim is never sent and the phone keeps the buds -- which is exactly what a first cut of
+this did.
-The address is stored **least significant byte first in connected-devices and in normal
-order in audio-source**. That is the protocol, not a bug, and getting it wrong makes a
-machine read its own entry as a peer. Both parsers return BlueZ's own text order.
+The address is in **display order in connected-devices and least significant byte first in
+audio-source**. Getting it wrong makes a machine read its own entry as a peer. Both parsers
+return BlueZ's own text order.
`type` in audio-source is a hint and nothing more: iOS reports `MEDIA` for real calls, and
sends `NONE` every twenty seconds or so *during* one. Deciding anything from it alone
@@ -633,10 +633,22 @@ Apple's own. The buds keep both hosts connected and hand *ownership* between the
link to this machine is never dropped, the AAP channel is never given up, and the volume
the stem sets is the volume of whoever owns them.
-The trigger is the buds' own peer list, not the phone's call state, so **this path does
-not need call control**: a connected-devices notification says the iPhone went active and
-that is enough. Music started on the phone counts the same as a call, which is what the
-buds themselves do.
+**The trigger is the iPhone's call list when call control is on**, and the buds' own
+notifications otherwise. On AirPods Pro 3 the buds cannot say when a call ends: the phone
+keeps the owner bit for minutes after it, and the audio source reads none a few seconds into
+one. The call list is exact, so a ringing, dialling or connected call gives the buds up and
+its end takes them back. Without call control, a peer that owns the buds *and* has a call or
+media on them (`AirPodsState::peer_busy()`) stands in, and can take the buds back mid-call.
+Music on the phone reaches this path only through the buds.
+
+While the buds are given up the watcher sends no claim of its own -- not the one a session
+sends when it opens, and not one for local playback. Only the reclaim claims.
+
+**The call has to arrive before the phone moves the audio.** When the phone takes A2DP the
+Bluetooth sink fails and WirePlumber moves any stream still playing to the laptop speakers, so
+a pause that lands after that is heard as a burst of music from the speakers. The supervisor
+publishes the call list once a second; on this path every BlueZ object change republishes it
+straight away (`ConnectionManager::refresh_calls()`).
`ownership_action()` is pure and tested, and is the same shape as `handoff_action()`: give
them up when a peer goes active, take them back when it lets go, never twice, and buds
@@ -714,10 +726,21 @@ are connected, even while the user listens on speakers -- and so is looking for
the Bluetooth sink, because a virtual sink for an equaliser takes them instead. The
default sink is the one thing that reflects what the user actually chose.
+On the ownership path the sink also has to be **rebuilt**. The phone tears this machine's
+A2DP transport down when it takes the buds, and PipeWire never reopens a sink left sitting on
+it: playback resumes into silence until the buds are reconnected. So giving the buds up pauses
+the players, reads the sink's raw volume, and switches the card profile `off` (A2DP profiles
+only) before releasing. Taking them back claims, switches the card back to the saved profile and
+reads it back (`pactl` can report success while the card stays off), waits for the **new** sink
+-- it has a new index -- and restores the volume before anything resumes. If the phone has
+taken the buds again by then, the card goes back off and nothing resumes. A call can also drop
+the link outright and the buds reconnect with the card already back on, so there was nothing to
+switch off on release; the reclaim then switches it off first. See 2026-09-11 below.
+
ponytail: no silence stream. A host that is itself the audio source has to write inaudible
-silence to keep the sink from being torn down while idle; here the media player is the
-source and the sink wait covers the gap. Add one if a reclaim is ever seen racing a
-sink that PipeWire has already dropped.
+silence to keep the sink from being torn down while idle, and to prime the encoder after a
+rebuild; here the media player is the source and the sink wait covers the gap. Add one if
+crackling is heard after a reclaim.
**What it does not cover.** On the disconnect path, music or video playing on the iPhone
is not a call, so nothing reacts to it. Seeing that would mean the machine acting as an
@@ -3083,3 +3106,82 @@ the bearer step is a `sed` plus a restart through the machine's own service mana
Not yet verified on hardware: that `class=ok` survives a `bluetoothd` restart on a machine
without hostnamed. The `sed` leaves a `main.conf` with no `Class` or `Experimental` line,
commented or not, unchanged, and `--bt-setup` keeps listing the step.
+
+### 2026-09-11 - The AirPods sink jammed after a call
+
+Reported in #85 and reproduced on AirPods Pro 3: music on Linux, a call on the iPhone,
+playback paused, and after the call playback resumed into silence. PipeWire stayed jammed
+until the buds were reconnected.
+
+The reporter captured the working sequence from their own implementation at three stages:
+
+| Stage | Card profile | `MediaTransport1` | Sink |
+|---|---|---|---|
+| Before the call | `a2dp-sink-sbc_xq` | `active` | index 468, RUNNING |
+| During | `off` | `idle` | gone |
+| After | `a2dp-sink-sbc_xq` | `active` | index 623, RUNNING |
+
+The transport object never goes away; the sink does, and comes back as a new object. A sink
+left in place while the phone holds the transport is what jams. A first fix detected a
+suspended sink with a stream on it after the call and cycled the profile off and on two
+seconds apart. It worked, but it guessed at the jam, ran on a separate thread from the
+ownership reclaim with both resuming players, and changed the profile twice in quick
+succession, which the Apple-mode firmware tolerates badly. The card now goes off when the buds
+are given up and back on when they are taken back.
+
+That fix could only run from call state, because the ownership path never fired on these
+buds: `active()` tested `state >= 0x17` and Pro 3 reports `0x07`. That also left
+`taking_over()` false while the iPhone held the buds, so nothing in the peer state blocked a
+claim. Reading bit `0x02` fits every value recorded so far and puts iPhone media on the same
+path as calls.
+
+Volume, measured: WirePlumber restores a Bluetooth route's saved volume when the new sink's
+route comes up (`scripts/device/state-routes.lua`, "a new route is now active, restore the
+volume"), and these buds had `channelVolumes 0.174729` saved in
+`~/.local/state/wireplumber/default-routes`. The reporter saw a rebuilt sink come up at a
+default volume on their stack, so the raw value is saved on release and restored before
+resuming anyway, then read back.
+
+The first hardware run of that, 09:51 the same day, jammed again. The log shows why:
+
+- 09:51:21 the iPhone joined the host list at `0x00` and 200ms later BlueZ reported the buds
+ disconnected from this machine, `org.bluez.Reason.Remote`. No handoff, a link drop.
+- 09:51:43 the buds were back, with the iPhone at `0x02`. The owner bit alone released them, and
+ nothing was switched off: the card had not come back to an A2DP profile yet.
+- 09:51:56 WirePlumber logged `Failure in Bluetooth audio transport` on the new node, and the
+ buds reported the iPhone's call.
+- After the call ended no connected-devices notification arrived at all. The iPhone stayed at
+ `0x02`, so a reclaim waiting on the owner bit never fired. Even had it fired, its claim
+ would have been dropped, because counting the owner bit as `taking_over()` blocked claims.
+
+So handoff now yields to a peer that owns the buds **and** has audio on them, from the
+audio-source notification with the same three-second settle the call tracking already had;
+`taking_over()` is back to `0x10` and up; and a reclaim with nothing switched off on release
+switches the card off before switching it on.
+
+The second run, 10:05 to 10:10, was worse:
+
+- 10:08:49 and 10:10:09 the reclaim claimed the buds back six seconds after a single audio
+ source none, while the iPhone still read `0x07` and its call was still going.
+- The night before, 20:33:39, the iPhone took `0x07` for a call and still held it at 20:37:48,
+ with Linux playing in between. The owner bit does not mark the end of a call either.
+- Calls at 09:51:10, 10:05:31 and 10:08:56 put SCO on this machine (`corrupted SCO packet` in
+ the kernel log): iOS routed the call to the laptop's hands-free link, not the buds. At 10:05
+ the iPhone read `0x01` while an iMac on the same iCloud account held the buds at `0x07`
+ playing media. 10:08:56 came seven seconds after the early reclaim.
+- 10:05:15 the claim a session sends when it opens took the buds from that iMac mid-media,
+ while this machine had given them up.
+
+So the call list decides when call control is on, and a watcher that has given the buds up
+sends no claim of its own. Several Apple devices on one account is the normal case.
+
+The third run, 11:11 to 11:14, handed over and back correctly on every call, but music played
+briefly from the laptop speakers at the start of each. At 11:13:12 WirePlumber logged the A2DP
+transport failure at 12.000 and the release, which pauses first, logged at 12.053; at 11:13:35,
+35.569 and 35.626. SCO had reached this machine 300 to 550ms before each failure, so the phone
+was already committed to the call while Tether waited for its one-second call-list tick.
+
+Not yet verified on hardware: the full sequence on Pro 3, iPhone media rather than a call,
+the owner bit on Pro 2, and whether an `off` profile persists if tetherd dies while the buds
+are away. WirePlumber restores a saved `off` profile unless `session.dont-restore-off-profile`
+is set.
diff --git a/src/core/include/tether/audio.hpp b/src/core/include/tether/audio.hpp
index 940e83c..1449a94 100644
--- a/src/core/include/tether/audio.hpp
+++ b/src/core/include/tether/audio.hpp
@@ -19,19 +19,24 @@ 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);
+ // Switches a Bluetooth device's card off when it is on an A2DP profile, so the audio server
+ // lets go of the transport before another host takes the buds. Returns the profile to restore,
+ // empty when nothing was switched.
+ std::string release_bluez_card(const std::string& address);
+
+ // Switches the card back to `profile`, which builds a new sink under a new index. False when
+ // the card is still not on it after one retry.
+ bool restore_bluez_card(const std::string& address, const std::string& profile);
+
+ // A sink's raw per-channel volume ("45877 45877"), empty when unknown.
+ std::string sink_volume(const std::string& sink);
+
+ // Sets a raw volume from sink_volume() and reads it back. False when it did not take.
+ bool set_sink_volume(const std::string& sink, const std::string& volume);
+
+ // Parsers for `pactl list cards` and `pactl get-sink-volume`, exposed for tests.
std::string active_profile_in(const std::string& cards, const std::string& card);
+ std::string volume_in(const std::string& text);
// 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 451e8b2..48b05cd 100644
--- a/src/core/include/tether/bluetooth/airpods.hpp
+++ b/src/core/include/tether/bluetooth/airpods.hpp
@@ -36,12 +36,13 @@ namespace tether::bluetooth {
std::optional<AncMode> anc_mode_from_string(const std::string& name);
// Ownership state of one host attached to the buds, the `B` field of a
- // connected-devices notification.
+ // connected-devices notification. The owner carries bit 0x02 on every model measured:
+ // an iPhone idles at 0x15 and owns at 0x17 on some buds, 0x05 and 0x07 on others.
+ inline constexpr uint8_t AAP_PEER_OWNER = 0x02;
inline constexpr uint8_t AAP_PEER_ENGAGED = 0x10;
// Connected and idle. An iPhone sits here for as long as it is paired and doing
// nothing, so this one value is not a peer taking the buds.
inline constexpr uint8_t AAP_PEER_PASSIVE = 0x15;
- inline constexpr uint8_t AAP_PEER_ACTIVE = 0x17;
// One host in a connected-devices notification.
struct AapPeer {
@@ -51,9 +52,10 @@ namespace tether::bluetooth {
uint8_t role = 0;
uint8_t state = 0;
- bool active() const { return state >= AAP_PEER_ACTIVE; }
- // Escalating towards taking the buds, or already holding them. Claiming
- // against this leaves the host contested and the firmware closes the link.
+ // Owns the buds, which is not the same as using them: an iPhone keeps the bit after a call.
+ bool active() const { return (state & AAP_PEER_OWNER) != 0; }
+ // Escalating towards taking the buds, or holding them, on buds that report 0x10 and up.
+ // Claiming against this leaves the host contested and the firmware closes the link.
bool taking_over() const { return state >= AAP_PEER_ENGAGED && state != AAP_PEER_PASSIVE; }
bool operator==(const AapPeer&) const = default;
@@ -123,8 +125,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;
+ // A peer has a call or media on the buds, held until they have stopped reporting it for a few seconds.
+ bool peer_audio = false;
AirPodsBattery battery;
// Unset until the buds report one. Not every model has the feature.
std::optional<AncMode> anc;
@@ -133,6 +135,9 @@ namespace tether::bluetooth {
// Written for display, shown verbatim.
std::string reason;
+ // A peer owns the buds and is playing through them: what handoff yields to.
+ bool peer_busy() const { return peer_active && peer_audio; }
+
bool operator==(const AirPodsState&) const = default;
};
@@ -161,11 +166,11 @@ namespace tether::bluetooth {
// 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.
+ // peer is playing through them.
bool claims_for_playback(const AudioSourceEvent& event,
const std::string& local,
std::optional<bool> owns,
- bool peer_call);
+ bool peer_audio);
// Whether any host other than `local` is engaged with the buds, or actively
// holding them. A machine's own entry is never a peer.
@@ -188,11 +193,6 @@ 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 };
@@ -236,7 +236,8 @@ namespace tether::bluetooth {
// Takes the buds or gives them up over AAP, which is what Apple's own
// handoff does. A claim is dropped while a peer is engaged: sending one then
- // leaves this host contested and the firmware closes the link.
+ // leaves this host contested and the firmware closes the link. Giving them up
+ // also stops the watcher's own claims until they are taken back.
void set_ownership(bool own);
AirPodsState state() const;
diff --git a/src/core/include/tether/bluetooth/connection.hpp b/src/core/include/tether/bluetooth/connection.hpp
index 5ef1d76..05aa401 100644
--- a/src/core/include/tether/bluetooth/connection.hpp
+++ b/src/core/include/tether/bluetooth/connection.hpp
@@ -61,6 +61,9 @@ namespace tether::bluetooth {
void set_call_handler(CallsFn on_calls);
void set_calls_enabled(bool enabled);
+ // Publishes the call list now if it changed, instead of on the next supervisor tick.
+ void refresh_calls();
+
bool dial(const std::string& number, std::string& err);
bool call_action(const std::string& path, const std::string& action, std::string& err);
bool call_tones(const std::string& tones, std::string& err);
diff --git a/src/core/src/audio.cpp b/src/core/src/audio.cpp
index 217c42e..3d01fc0 100644
--- a/src/core/src/audio.cpp
+++ b/src/core/src/audio.cpp
@@ -6,15 +6,14 @@
#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;
+ // How long a card takes to report a profile it was switched to.
+ constexpr int PROFILE_WAIT_MS = 1500;
std::string trimmed(const std::string& text) {
const size_t begin = text.find_first_not_of(" \t\r\n");
@@ -24,15 +23,16 @@ namespace tether::audio {
return text.substr(begin, end - begin + 1);
}
- // Never blocks the caller for long, pactl answers locally or not at all.
- // `ok` reports whether pactl ran and succeeded.
+ // Bounded, because pactl can wait forever on a server that is itself waiting on
+ // BlueZ mid profile change. `ok` reports whether pactl ran and succeeded.
std::string run(const char* command, bool* ok = nullptr) {
gchar* out = nullptr;
gint status = 0;
GError* error = nullptr;
if (ok)
*ok = false;
- if (!g_spawn_command_line_sync(command, &out, nullptr, &status, &error)) {
+ const std::string bounded = std::string("timeout 5 ") + command;
+ if (!g_spawn_command_line_sync(bounded.c_str(), &out, nullptr, &status, &error)) {
g_clear_error(&error);
g_free(out);
return {};
@@ -46,12 +46,18 @@ 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;
+ std::string card_name(const std::string& address) {
+ return "bluez_card." + sink_prefix(address).substr(sizeof("bluez_output.") - 1);
+ }
+
+ bool card_reaches(const std::string& card, const std::string& profile) {
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(PROFILE_WAIT_MS);
+ while (std::chrono::steady_clock::now() < deadline) {
+ if (active_profile_in(run("pactl list cards"), card) == profile)
+ return true;
+ std::this_thread::sleep_for(std::chrono::milliseconds(POLL_INTERVAL_MS));
+ }
+ return false;
}
} // namespace
@@ -106,37 +112,6 @@ 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;
@@ -153,28 +128,70 @@ namespace tether::audio {
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);
+ std::string volume_in(const std::string& text) {
+ // "Volume: front-left: 45877 / 70% / -9.29 dB, front-right: 45877 / 70% / -9.29 dB"
+ std::string out;
+ std::istringstream channels(text.substr(0, text.find('\n')));
+ for (std::string channel; std::getline(channels, channel, ',');) {
+ const size_t colon = channel.rfind(':');
+ if (colon == std::string::npos)
+ return {};
+ const std::string raw = trimmed(channel.substr(colon + 1, channel.find('/', colon) - colon - 1));
+ if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
+ return {};
+ out += (out.empty() ? "" : " ") + raw;
+ }
+ return out;
}
- // HACK
- bool restart_bluez_card(const std::string& address) {
+ std::string release_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);
+ return {};
+ const std::string card = card_name(address);
const std::string profile = active_profile_in(run("pactl list cards"), card);
- if (profile.empty() || profile == "off")
- return false;
+ // Only the playback profile: a headset profile is carrying a call here.
+ if (profile.rfind("a2dp", 0) != 0)
+ return {};
bool ok = false;
run(("pactl set-card-profile " + card + " off").c_str(), &ok);
if (!ok)
+ return {};
+ // Gone before it can be rebuilt: switching straight back on can keep the old sink.
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(PROFILE_WAIT_MS);
+ while (!bluez_sink(address).empty() && std::chrono::steady_clock::now() < deadline)
+ std::this_thread::sleep_for(std::chrono::milliseconds(POLL_INTERVAL_MS));
+ return profile;
+ }
+
+ bool restore_bluez_card(const std::string& address, const std::string& profile) {
+ if (address.empty() || profile.empty())
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;
+ const std::string card = card_name(address);
+ // pactl can report success while the card stays off, so the result is read back.
+ for (int attempt = 0; attempt < 2; ++attempt) {
+ run(("pactl set-card-profile " + card + " " + profile).c_str());
+ if (card_reaches(card, profile))
+ return true;
+ }
+ return false;
+ }
+
+ std::string sink_volume(const std::string& sink) {
+ if (sink.empty())
+ return {};
+ return volume_in(run(("pactl get-sink-volume " + sink).c_str()));
+ }
+
+ bool set_sink_volume(const std::string& sink, const std::string& volume) {
+ if (sink.empty() || volume.empty())
+ return false;
+ // A sink created moments ago can have its volume overwritten as hardware volume settles.
+ for (int attempt = 0; attempt < 2; ++attempt) {
+ run(("pactl set-sink-volume " + sink + " " + volume).c_str());
+ if (sink_volume(sink) == volume)
+ return true;
+ }
+ return false;
}
} // namespace tether::audio
diff --git a/src/core/src/bluetooth/airpods.cpp b/src/core/src/bluetooth/airpods.cpp
index 32d2ee8..f7c7d39 100644
--- a/src/core/src/bluetooth/airpods.cpp
+++ b/src/core/src/bluetooth/airpods.cpp
@@ -111,9 +111,9 @@ namespace tether::bluetooth {
// 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:
+ // How long the buds must stop reporting a peer's audio 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 PEER_AUDIO_SETTLE_MS = 3000;
constexpr int CONNECT_TIMEOUT_MS = 8000;
constexpr int FIRST_PACKET_TIMEOUT_MS = 8000;
@@ -228,7 +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},
+ {"peer_audio", s.peer_audio},
{"status", to_string(s.status)},
{"reason", s.reason},
};
@@ -413,20 +413,12 @@ 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) {
+ bool peer_audio) {
return !local.empty() && event.address == local && event.source != AudioSource::None && owns == false &&
- !peer_call;
+ !peer_audio;
}
PeerSummary summarize_peers(const std::vector<AapPeer>& peers, const std::string& local) {
@@ -499,6 +491,8 @@ namespace tether::bluetooth {
// the one race worth not having.
std::optional<AncMode> pending_anc;
std::optional<bool> pending_ownership;
+ // This machine gave the buds up: no claim of the watcher's own goes out until it takes them back.
+ bool yielded = false;
std::chrono::steady_clock::time_point last_claim{};
bool stopping = false;
bool enabled = true;
@@ -736,7 +730,7 @@ namespace tether::bluetooth {
bool blocked = false;
{
std::lock_guard<std::mutex> lock(mutex);
- blocked = state.peer_taking_over;
+ blocked = state.peer_taking_over || yielded;
}
if (blocked)
return true;
@@ -747,15 +741,15 @@ namespace tether::bluetooth {
std::map<std::string, uint8_t> peer_states;
bool warned_unlisted = false;
std::optional<bool> owns;
- bool peer_call = false;
+ bool peer_audio = 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::optional<clock::time_point> peer_audio_ends_at;
+ // Published so local playback can step aside while the phone plays through the buds.
+ const auto set_peer_audio = [&](bool on) {
+ peer_audio = on;
{
std::lock_guard<std::mutex> lock(mutex);
- state.peer_call = on;
+ state.peer_audio = on;
}
publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");
};
@@ -774,8 +768,8 @@ namespace tether::bluetooth {
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));
+ if (peer_audio_ends_at)
+ timeout = std::min(timeout, until(*peer_audio_ends_at));
const int ready = wait_for(fd, wake_fd, POLLIN, std::max(timeout, 0));
if (ready == 0) {
drain_wake();
@@ -792,24 +786,27 @@ namespace tether::bluetooth {
break;
continue;
}
- if (call_ends_at && fired >= *call_ends_at) {
- call_ends_at.reset();
- set_peer_call(false);
+ if (peer_audio_ends_at && fired >= *peer_audio_ends_at) {
+ peer_audio_ends_at.reset();
+ set_peer_audio(false);
continue;
}
if (claim_at && fired >= *claim_at) {
claim_at.reset();
std::string local;
+ bool yielding = false;
{
std::lock_guard<std::mutex> lock(mutex);
local = local_address;
+ yielding = yielded;
}
// 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)) {
+ } else if (!yielding && latest_source &&
+ claims_for_playback(*latest_source, local, owns, peer_audio)) {
debug::log(DEBUG, "airpods: claiming for playback here");
if (!send_ownership(fd, true))
break;
@@ -881,17 +878,18 @@ namespace tether::bluetooth {
}
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)) {
+ if (claims_for_playback(*source, local, owns, peer_audio)) {
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);
+ // Media counts too: iOS reports MEDIA for real calls, and music on the phone takes the buds.
+ if (source->source != AudioSource::None && source->address != local) {
+ peer_audio_ends_at.reset();
+ if (!peer_audio)
+ set_peer_audio(true);
+ } else if (peer_audio && !peer_audio_ends_at) {
+ peer_audio_ends_at = last_packet + std::chrono::milliseconds(PEER_AUDIO_SETTLE_MS);
}
continue;
}
@@ -933,7 +931,7 @@ namespace tether::bluetooth {
std::lock_guard<std::mutex> lock(mutex);
pending_anc.reset();
pending_ownership.reset();
- state.peer_call = false;
+ state.peer_audio = false;
}
::close(fd);
}
@@ -963,7 +961,7 @@ namespace tether::bluetooth {
state.ear = {};
state.peer_taking_over = false;
state.peer_active = false;
- state.peer_call = false;
+ state.peer_audio = false;
}
publish(AirPodsStatus::Idle, "");
backoff_ms = BACKOFF_START_MS;
@@ -982,7 +980,7 @@ namespace tether::bluetooth {
state.ear = {};
state.peer_taking_over = false;
state.peer_active = false;
- state.peer_call = false;
+ state.peer_audio = false;
}
state.name = name;
}
@@ -1058,6 +1056,7 @@ namespace tether::bluetooth {
{
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->pending_ownership = own;
+ impl_->yielded = !own;
}
impl_->wake();
}
diff --git a/src/core/src/bluetooth/connection.cpp b/src/core/src/bluetooth/connection.cpp
index ecd5969..2c331e5 100644
--- a/src/core/src/bluetooth/connection.cpp
+++ b/src/core/src/bluetooth/connection.cpp
@@ -685,8 +685,10 @@ namespace tether::bluetooth {
ConnectionManager::CallsFn on_calls;
std::atomic<bool> calls_wanted{false};
bool calls_enabled = false;
- // Last published call list
+ // Last published call list. The mutex also serialises on_calls: the supervisor tick and
+ // refresh_calls() both publish.
nlohmann::json last_calls;
+ std::mutex calls_publish_mutex;
// Brings the telephony client in line with the wanted preference.
void apply_calls_preference();
@@ -1174,12 +1176,14 @@ namespace tether::bluetooth {
std::lock_guard<std::mutex> lock(telephony_mutex);
telephony = std::move(client);
}
+ std::lock_guard<std::mutex> lock(calls_publish_mutex);
last_calls = nullptr;
debug::log(INFO, "bluetooth: call control {}", wanted ? "enabled" : "disabled");
}
void ConnectionState::sync_calls() {
auto client = calls_client();
+ std::lock_guard<std::mutex> lock(calls_publish_mutex);
if (!client) {
last_calls = nullptr;
return;
@@ -1435,6 +1439,8 @@ namespace tether::bluetooth {
void ConnectionManager::set_call_handler(CallsFn on_calls) { state_->on_calls = std::move(on_calls); }
+ void ConnectionManager::refresh_calls() { state_->sync_calls(); }
+
void ConnectionManager::set_calls_enabled(bool enabled) { state_->calls_wanted = enabled; }
void ConnectionManager::set_lock_on_away(bool enabled, int grace_seconds) {
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 6290720..7ab6052 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -58,7 +58,7 @@ 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.
+// 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) {
@@ -266,6 +266,10 @@ int main(int argc, char** argv) {
std::string released;
bool busy = false;
bool own_output = false;
+ std::string profile;
+ std::string volume;
+ // phone has a call ringing, dialling or connected, from call control.
+ bool call_active = false;
bool holding_buds() const {
std::lock_guard<std::mutex> lock(mutex);
@@ -278,89 +282,146 @@ int main(int argc, char** argv) {
// the buds offer ownership to this machine instead of only to the phone.
std::atomic<bool> native_handoff{false};
- // Apple's own handoff. The buds say when the phone has taken them, and ownership
- // moves over AAP with the link left up.
- const auto run_ownership = [handoff](const tether::bluetooth::AirPodsState& state) {
+ // Whether the phone is using the buds.
+ const auto phone_busy = [handoff](const tether::bluetooth::AirPodsState& state) {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ return handoff->call_active || state.peer_busy();
+ };
+
+ // Apple's own handoff: ownership moves over AAP with the link left up. Runs on the AirPods
+ // worker, the call handler, and the end of each handoff thread, so deciding and marking busy
+ // is one step.
+ std::function<void(const tether::bluetooth::AirPodsState&)> run_ownership;
+ run_ownership = [handoff, phone_busy, &run_ownership](const tether::bluetooth::AirPodsState& state) {
const auto config = tether::bluetooth::load_config();
+ const bool busy_now = phone_busy(state);
std::string target;
- bool released_now = false;
+ auto action = tether::bluetooth::HandoffAction::None;
{
std::lock_guard<std::mutex> lock(handoff->mutex);
- if (handoff->busy)
+ if (handoff->busy || !tether::bluetooth::g_airpods)
return;
- released_now = !handoff->released.empty();
+ const bool released_now = !handoff->released.empty();
target = released_now ? handoff->released : state.address;
+ if (target.empty())
+ return;
+ action = tether::bluetooth::ownership_action(
+ busy_now, released_now, config.airpods_handoff && config.airpods_enabled);
+ if (action == tether::bluetooth::HandoffAction::None)
+ return;
+ handoff->busy = true;
+ if (action == tether::bluetooth::HandoffAction::Release)
+ handoff->released = target;
}
- if (target.empty() || !tether::bluetooth::g_airpods)
- return;
-
- const auto action = tether::bluetooth::ownership_action(
- state.peer_active, released_now, config.airpods_handoff && config.airpods_enabled);
if (action == tether::bluetooth::HandoffAction::Release) {
- if (tether::g_media)
- tether::g_media->pause();
- const bool ours = tether::audio::default_sink() == tether::audio::bluez_sink(target);
- {
- std::lock_guard<std::mutex> lock(handoff->mutex);
- handoff->released = target;
- handoff->own_output = ours;
- }
- tether::bluetooth::g_airpods->set_ownership(false);
- debug::log(INFO, "airpods: gave the buds to the iPhone");
+ std::thread([handoff, target, &run_ownership] {
+ const size_t paused = tether::g_media ? tether::g_media->pause() : 0;
+ const std::string sink = tether::audio::bluez_sink(target);
+ const bool ours = !sink.empty() && tether::audio::default_sink() == sink;
+ const std::string volume = tether::audio::sink_volume(sink);
+ const std::string profile = tether::audio::release_bluez_card(target);
+ if (tether::bluetooth::g_airpods)
+ tether::bluetooth::g_airpods->set_ownership(false);
+ debug::log(INFO,
+ "airpods: gave the buds to the iPhone (paused {}, card {}, volume {})",
+ paused,
+ profile.empty() ? "left alone" : profile + " -> off",
+ volume.empty() ? "unknown" : volume);
+ {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ handoff->own_output = ours;
+ handoff->volume = volume;
+ handoff->profile = profile;
+ handoff->busy = false;
+ }
+ if (tether::bluetooth::g_airpods)
+ run_ownership(tether::bluetooth::g_airpods->state());
+ }).detach();
return;
}
- if (action != tether::bluetooth::HandoffAction::Reclaim)
- return;
- {
- std::lock_guard<std::mutex> lock(handoff->mutex);
- handoff->busy = true;
- }
- std::thread([handoff] {
+ std::thread([handoff, phone_busy, &run_ownership] {
bool reclaimed = false;
for (int attempt = 0; attempt < HANDOFF_RECLAIM_ATTEMPTS && !reclaimed; ++attempt) {
std::this_thread::sleep_for(std::chrono::seconds(HANDOFF_GUARD_SECONDS));
if (!tether::bluetooth::g_airpods)
break;
- // The firmware reports no audio source periodically during a call.
- if (tether::bluetooth::g_airpods->state().peer_active)
+ if (phone_busy(tether::bluetooth::g_airpods->state()))
continue;
tether::bluetooth::g_airpods->set_ownership(true);
reclaimed = true;
}
- if (reclaimed) {
- bool ours = false;
- std::string address;
- {
- std::lock_guard<std::mutex> lock(handoff->mutex);
- ours = handoff->own_output;
- address = handoff->released;
+
+ std::string address;
+ std::string profile;
+ std::string volume;
+ bool ours = false;
+ {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ address = handoff->released;
+ profile = handoff->profile;
+ volume = handoff->volume;
+ ours = handoff->own_output;
+ }
+
+ if (reclaimed && profile.empty())
+ profile = tether::audio::release_bluez_card(address);
+ bool sink_back = true;
+ if (reclaimed && !profile.empty()) {
+ sink_back = tether::audio::restore_bluez_card(address, profile);
+ if (!sink_back)
+ debug::log(WARN, "airpods: the Bluetooth card for {} did not return to {}", address, profile);
+ }
+ if (reclaimed && sink_back && ours)
+ sink_back = tether::audio::restore_default_sink(address, SINK_RETURN_TIMEOUT_MS);
+ if (reclaimed && sink_back && !profile.empty())
+ std::this_thread::sleep_for(std::chrono::seconds(SINK_SETTLE_SECONDS));
+
+ if (reclaimed && tether::bluetooth::g_airpods && phone_busy(tether::bluetooth::g_airpods->state())) {
+ reclaimed = false;
+ if (const std::string again = tether::audio::release_bluez_card(address); !again.empty())
+ profile = again;
+ tether::bluetooth::g_airpods->set_ownership(false);
+ debug::log(INFO, "airpods: the iPhone took the buds back during the reclaim; leaving them to it");
+ } else if (reclaimed) {
+ if (!volume.empty() && !tether::audio::set_sink_volume(tether::audio::bluez_sink(address), volume))
+ debug::log(WARN, "airpods: could not restore the volume on the new sink for {}", address);
+ if (tether::g_media) {
+ if (sink_back)
+ tether::g_media->resume();
+ else
+ tether::g_media->forget();
}
- if (ours)
- tether::audio::restore_default_sink(address, SINK_RETURN_TIMEOUT_MS);
- if (tether::g_media)
- tether::g_media->resume();
+ debug::log(sink_back ? INFO : WARN,
+ sink_back ? "airpods: took the buds back from the iPhone"
+ : "airpods: took the buds back, but their sink did not return");
+ } else {
+ debug::log(WARN, "airpods: the iPhone still has the buds; leaving them to it");
}
- debug::log(reclaimed ? INFO : WARN,
- reclaimed ? "airpods: took the buds back from the iPhone"
- : "airpods: the iPhone still has the buds; leaving them to it");
- std::lock_guard<std::mutex> lock(handoff->mutex);
- if (reclaimed)
- handoff->released.clear();
- handoff->busy = false;
+
+ {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ if (reclaimed) {
+ handoff->released.clear();
+ handoff->profile.clear();
+ handoff->volume.clear();
+ } else {
+ handoff->profile = profile;
+ }
+ handoff->busy = false;
+ }
+ if (tether::bluetooth::g_airpods)
+ run_ownership(tether::bluetooth::g_airpods->state());
}).detach();
};
// 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, &last_peer_call, &paused_for_call, handoff, &native_handoff, &run_ownership](
- const tether::bluetooth::AirPodsState& state) {
+ [&media, &last_ear, 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())) {
@@ -376,68 +437,28 @@ int main(int argc, char** argv) {
break;
}
- 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()) {
+ 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());
});
- const auto run_handoff = [&bluez, &media, handoff, &native_handoff](const nlohmann::json& calls) {
- // Ownership handoff runs off the buds' own peer state, not the call list.
- if (native_handoff.load())
+ const auto run_handoff = [&bluez, &media, handoff, &native_handoff, &run_ownership](const nlohmann::json& calls) {
+ // Handoff takes the call list as its exact call signal.
+ if (native_handoff.load()) {
+ const bool active = tether::bluetooth::call_wants_audio(calls);
+ {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ handoff->call_active = active;
+ }
+ if (tether::bluetooth::g_airpods)
+ run_ownership(tether::bluetooth::g_airpods->state());
return;
+ }
const auto config = tether::bluetooth::load_config();
const bool active = tether::bluetooth::call_wants_audio(calls);
@@ -541,11 +562,13 @@ int main(int argc, char** argv) {
tether::bluetooth::g_bluez = &bluez;
tether::bluetooth::g_airpods = &airpods;
tether::g_media = &media;
- loop.addFd(bluez.event_fd(), [&bluez, &follow_airpods](int) {
+ loop.addFd(bluez.event_fd(), [&bluez, &follow_airpods, &connections, &native_handoff](int) {
bluez.drain();
tether::broadcast_local_event(tether::build_bt_devices().dump());
tether::broadcast_local_event(tether::build_bt_status().dump());
follow_airpods();
+ if (native_handoff.load())
+ connections.refresh_calls();
});
follow_airpods();
auto cap = bluez.capability();
diff --git a/test/test_airpods.cpp b/test/test_airpods.cpp
index 973acf5..960601b 100644
--- a/test/test_airpods.cpp
+++ b/test/test_airpods.cpp
@@ -233,17 +233,38 @@ TEST(AirPods, ParsesTheConnectedDeviceList) {
TEST(AirPods, SeparatesAnIdlePeerFromOneTakingTheBuds) {
const auto peer = [](uint8_t state) { return AapPeer{"81:71:C8:30:6A:F3", 0x02, state}; };
EXPECT_FALSE(peer(0x15).taking_over());
+ EXPECT_TRUE(peer(0x10).taking_over());
+ EXPECT_FALSE(peer(0x10).active());
EXPECT_TRUE(peer(0x12).taking_over());
EXPECT_TRUE(peer(0x17).taking_over());
EXPECT_TRUE(peer(0x17).active());
EXPECT_FALSE(peer(0x15).active());
// AirPods Pro 1 leaves a healthy iPhone at 0x01 forever.
EXPECT_FALSE(peer(0x01).taking_over());
+
+ // AirPods Pro 3 never report 0x10 and up: the iPhone read 0x05 and 0x07 on 2026-09-10, and
+ // 0x02 on 2026-09-11, where it kept 0x02 after the call ended. Owning must not block a claim.
+ EXPECT_FALSE(peer(0x05).active());
+ EXPECT_TRUE(peer(0x07).active());
+ EXPECT_TRUE(peer(0x02).active());
+ EXPECT_FALSE(peer(0x02).taking_over());
+ EXPECT_FALSE(peer(0x07).taking_over());
+}
+
+// Handoff yields to a phone that owns the buds and plays through them, never to ownership alone.
+TEST(AirPods, AnOwnerThatStoppedPlayingIsNotBusy) {
+ AirPodsState state;
+ state.peer_active = true;
+ EXPECT_FALSE(state.peer_busy());
+ state.peer_audio = true;
+ EXPECT_TRUE(state.peer_busy());
+ state.peer_active = false;
+ EXPECT_FALSE(state.peer_busy());
}
// This machine's own entry rises with its own ownership and is never a peer.
TEST(AirPods, SummarisesPeersWithoutCountingItself) {
- const std::vector<AapPeer> peers = {{"AC:F2:3C:AF:52:9C", 0x01, 0x17}, {"81:71:C8:30:6A:F3", 0x02, 0x12}};
+ const std::vector<AapPeer> peers = {{"AC:F2:3C:AF:52:9C", 0x01, 0x17}, {"81:71:C8:30:6A:F3", 0x02, 0x10}};
const auto summary = summarize_peers(peers, "AC:F2:3C:AF:52:9C");
EXPECT_TRUE(summary.taking_over);
EXPECT_FALSE(summary.active);
@@ -267,17 +288,6 @@ TEST(AirPods, ParsesTheAudioSource) {
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) {
diff --git a/test/test_audio.cpp b/test/test_audio.cpp
index e549ee5..108e1ba 100644
--- a/test/test_audio.cpp
+++ b/test/test_audio.cpp
@@ -14,21 +14,15 @@ 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, ""));
+// Raw values, not percentages: a percentage round trip loses a step on every handoff.
+TEST(Audio, ReadsARawSinkVolume) {
+ // Captured 2026-09-11 from `pactl get-sink-volume` on PipeWire 1.6.8.
+ EXPECT_EQ(volume_in("Volume: front-left: 45877 / 70% / -9.29 dB, front-right: 45877 / 70% / -9.29 dB\n"
+ " balance 0.00\n"),
+ "45877 45877");
+ EXPECT_EQ(volume_in("Volume: mono: 11453 / 17% / -45.43 dB\n"), "11453");
+ EXPECT_TRUE(volume_in("").empty());
+ EXPECT_TRUE(volume_in("Failure: No such entity\n").empty());
}
TEST(Audio, ReadsACardsActiveProfile) {