Linux + iPhone Continuity / iMessage / SMS
fix: airpods handoff linux steals audio
Zack Bartel47acf9542d99
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.mdindex d6bac0d..9dacdb8 100644--- a/docs/BLUETOOTH.md+++ b/docs/BLUETOOTH.md@@ -689,6 +689,17 @@ review:The claim sent when the session comes up is deliberate: AirPods Pro 2 validates a host byitself, Pro 3 never does, and an unvalidated host is dropped at the first pod movement.+**That claim validates the host, it does not entitle it to keep the buds.** Three seconds+later (`IDLE_RELEASE_MS`) the session hands ownership straight back, unless the buds have+reported an audio source for *this* machine in the meantime. `releases_when_idle()` is pure+and tested: give them back when another host is in the list, nothing is playing here and+the buds were not already yielded for a call. Buds held by a machine that is not using them+do not appear as an output route on the phone at all, which is what "Linux stole my AirPods+at boot" is. The way back is the existing claim for local playback: the card profile is+deliberately left alone here, because tearing the sink down means the next thing the user+plays goes to the speakers, the buds never report a local audio source, and nothing ever+claims again.+#### Disconnect handoffThe fallback. When the iPhone has a call and the AirPods are connected to *this machine*,@@ -3265,3 +3276,79 @@ Not covered: a controller that re-enumerates at runtime with no `bluetoothd` resre-runs the unit there, and `bluetoothd` applies its own default class to the new adapter, sothe class is wrong until `bluetooth.service` restarts. A udev rule tagging adapter `add` with`SYSTEMD_WANTS` would close that, and would also remove the manual enable step.++### 2026-09-12 - The buds were taken at boot and never given back++Reported on 0.2.30 against both Pro 2 and Pro 3 (issue #85): after starting the machine, the+iPhone could not see the AirPods at all, and the only way back was forcing the connection+from the phone's own Bluetooth menu.++Every session claims ownership five seconds after the channel opens+(`CLAIM_SETTLE_MS`). The claim is gated on `peer_taking_over` and `yielded` and on nothing+else -- not on whether this machine has any audio, and not on `airpods_handoff`. An idle+iPhone sits at `0x15`, which `taking_over()` excludes on purpose, so nothing blocked it. On+the other side, `ownership_action()` only gives the buds up for a peer that owns them *and*+has audio on them, so a phone that was merely idle never got them back. The machine held+ownership from boot until the user intervened.++Not a new failure: the same claim is what took the buds from an iMac mid-media on 2026-09-11+below. The fix then was the `yielded` flag, which is false on a fresh daemon and on a first+connect -- exactly the boot case.++The claim itself has to stay, for the Pro 3 validation reason above. What was missing is the+other half of the arbitration: three seconds after the claim, ownership goes back unless the+buds have reported an audio source for this machine. `releases_when_idle()` in+`src/core/src/bluetooth/airpods.cpp`, and `PeerSummary::present` so a session alone with the+buds keeps them.++Deliberately not touching the card profile on this path, unlike the call handoff. Releasing+it destroys the sink, and with no bluez sink the next thing the user plays goes to the+speakers, the buds never report an audio source for this machine, and the claim for local+playback can never fire. An idle `MediaTransport1` does not stop the phone taking the buds.++**Verified on hardware the same day, Pro 3, twice**: with the phone owning the buds and both+sides quiet, `claim sent` at opened+5s, verdict `0x01`, `nothing playing here, handing ownership+back` at +3.003s, verdict `0x00`, phone back to `0x07`. A pod out and back in without closing the+case left the link up past thirty seconds, so releasing straight after the validation claim does+**not** cost this host its validation. No gating to `0x10` and above is needed.++Three preconditions silently decline the release, and each one blocked a test run before the+first success. A peer must be in the buds' host list, or there is nobody to hand them to. Nothing+may be streaming here -- a *paused* Electron player still holds an uncorked stream and the buds+still report media for this machine, so such a player has to be quit, not paused. And the phone+must be quiet, or `peer_busy()` releases at ~0.4s, long before the validation claim is due.++### 2026-09-12 - Four more, from testing the release above++**The release tore the sink down over an idle card.** `release_bluez_card()` ran on every+handoff. When this machine was not playing, that left no sink, so the next thing the user played+went to the speakers, the buds never reported an audio source for this machine, and the claim for+local playback could never fire -- once measured at 3m52s of dead audio. The teardown now needs+`AirPodsState::local_audio`, the buds' own view of whether they carry this machine's audio.+`paused > 0` was tried first and is wrong: a browser tab streams with no MPRIS player at all, and+leaving that running pumps audio into buds just given away, which produced a release/reclaim+ping-pong every time the phone paused.++**The card teardown raced the pause.** MPRIS `Pause` is a request; the player keeps feeding the+sink for a moment after it returns, and a card switched off under a live stream has the audio+server move it to the speakers. `audio::sink_quiet()` waits up to `SINK_QUIET_TIMEOUT_MS` (300)+for the sink to leave `RUNNING` first. That removed the burst on the call path. The bound is+short because the buds still have to reach the phone before iOS picks the call's route; it is a+bounded wait, not a confirmation, and `still running after 300ms` does appear for Electron+players without being audible.++**Phone media gives no warning, and cannot be fixed here.** `AirPodsState::owns` now carries this+machine's owner bit from the host list, and losing it pauses MPRIS at once -- 471ms earlier than+waiting for the release decision. It is not enough. The phone takes the A2DP transport at the+same instant it takes ownership, so the host-list packet is already past tense and the audio+server rescues the stream before a D-Bus pause reaches the player. A call is fixable only because+the call list fires while it is still ringing. The remaining lever is audio-server side: stopping+PipeWire rescuing streams off a sink that vanishes, PulseAudio's `module-rescue-streams`+equivalent in WirePlumber's linking policy. Not attempted.++**An `off` profile outlives the daemon.** Listed as unverified under 2026-09-11; it is real and+survives a reboot. WirePlumber saves the profile a handoff switched off and restores it on the+next connect, so the buds arrive with no sink and everything plays out of the laptop speakers. A+fresh daemon has an empty `handoff->released` and restores nothing. `audio::revive_bluez_card()`+runs on the AirPods connect edge -- not on every BlueZ property change, the check costs a `pactl`+of its own -- and switches A2DP back on for buds this run did not release.diff --git a/src/core/include/tether/audio.hpp b/src/core/include/tether/audio.hppindex 1449a94..4f8adc3 100644--- a/src/core/include/tether/audio.hpp+++ b/src/core/include/tether/audio.hpp@@ -24,6 +24,11 @@ namespace tether::audio {// empty when nothing was switched.std::string release_bluez_card(const std::string& address);+ // Switches a Bluetooth card off `off` and back onto A2DP. The audio server saves the profile+ // a handoff switched off and restores it on the next connect, so buds can arrive with no sink+ // at all and nothing to play through. True when one was switched back on.+ bool revive_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);@@ -34,6 +39,11 @@ namespace tether::audio {// 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);+ // Waits for a sink to stop carrying a stream. Switching a card off under a live stream+ // makes the audio server move it to the speakers, heard as a burst of whatever was+ // playing. False when it is still running at the deadline.+ bool sink_quiet(const std::string& sink, int timeout_ms);+// 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);diff --git a/src/core/include/tether/bluetooth/airpods.hpp b/src/core/include/tether/bluetooth/airpods.hppindex 7cd6168..ee16f6e 100644--- a/src/core/include/tether/bluetooth/airpods.hpp+++ b/src/core/include/tether/bluetooth/airpods.hpp@@ -126,6 +126,8 @@ namespace tether::bluetooth {bool peer_active = 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;+ bool local_audio = false;+ std::optional<bool> owns;AirPodsBattery battery;// Unset until the buds report one. Not every model has the feature.std::optional<AncMode> anc;@@ -172,6 +174,9 @@ namespace tether::bluetooth {std::optional<bool> owns,bool peer_audio);+ // Whether a session that has claimed the buds to validate itself should hand ownership straight back.+ bool releases_when_idle(bool local_audio, bool peer_present, bool yielded);+// The two registration packets a host sends for every other host in the buds' list, which is// what moves it from unvalidated to validated. Empty for an address that will not parse.std::vector<uint8_t> tipi_add_device(const std::string& self, const std::string& target);@@ -182,6 +187,7 @@ namespace tether::bluetooth {struct PeerSummary {bool taking_over = false;bool active = false;+ bool present = false;bool operator==(const PeerSummary&) const = default;};diff --git a/src/core/src/audio.cpp b/src/core/src/audio.cppindex 3d01fc0..4d1e71d 100644--- a/src/core/src/audio.cpp+++ b/src/core/src/audio.cpp@@ -12,6 +12,8 @@ namespace tether::audio {namespace {constexpr int POLL_INTERVAL_MS = 200;+ // A paused player stops feeding its sink in tens of milliseconds.+ constexpr int SINK_QUIET_POLL_MS = 25;// How long a card takes to report a profile it was switched to.constexpr int PROFILE_WAIT_MS = 1500;@@ -112,6 +114,30 @@ namespace tether::audio {return false;}+ bool sink_quiet(const std::string& sink, int timeout_ms) {+ if (sink.empty())+ return true;+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);+ while (true) {+ bool running = false;+ std::istringstream lines(run("pactl list short sinks"));+ for (std::string line; std::getline(lines, line);) {+ if (line.find(sink) == std::string::npos)+ continue;+ // index<TAB>name<TAB>driver<TAB>format<TAB>rate<TAB>state+ running = line.rfind("RUNNING") != std::string::npos;+ break;+ }+ if (!running)+ return true;+ if (std::chrono::steady_clock::now() >= deadline)+ break;+ std::this_thread::sleep_for(std::chrono::milliseconds(SINK_QUIET_POLL_MS));+ }+ debug::log(DEBUG, "audio: {} still running after {}ms", sink, timeout_ms);+ 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;@@ -163,6 +189,14 @@ namespace tether::audio {return profile;}+ bool revive_bluez_card(const std::string& address) {+ const std::string card = card_name(address);+ if (active_profile_in(run("pactl list cards"), card) != "off")+ return false;+ debug::log(INFO, "audio: {} came back with its profile off; switching A2DP on", card);+ return restore_bluez_card(address, "a2dp-sink");+ }+bool restore_bluez_card(const std::string& address, const std::string& profile) {if (address.empty() || profile.empty())return false;diff --git a/src/core/src/bluetooth/airpods.cpp b/src/core/src/bluetooth/airpods.cppindex 17057f2..2a1f160 100644--- a/src/core/src/bluetooth/airpods.cpp+++ b/src/core/src/bluetooth/airpods.cpp@@ -112,6 +112,8 @@ 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;+ // After that claim, how long this machine has to start playing before ownership goes back.+ constexpr int IDLE_RELEASE_MS = 3000;// 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 PEER_AUDIO_SETTLE_MS = 3000;@@ -425,6 +427,10 @@ namespace tether::bluetooth {!peer_audio;}+ bool releases_when_idle(bool local_audio, bool peer_present, bool yielded) {+ return peer_present && !local_audio && !yielded;+ }+namespace {// Both TiPi packets are opcode 0x10 (smart routing) and look alike. The target's@@ -476,6 +482,7 @@ namespace tether::bluetooth {for (const auto& peer : peers) {if (!local.empty() && peer.address == local)continue;+ summary.present = summary.present || !local.empty();summary.taking_over = summary.taking_over || peer.taking_over();summary.active = summary.active || peer.active();}@@ -592,18 +599,22 @@ 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& warned_unlisted,- bool delivered) {+ PeerSummary 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;+ std::optional<bool> mine;for (const auto& peer : peers) {- listed = listed || peer.address == local;+ if (peer.address == local) {+ listed = true;+ mine = peer.active();+ }auto [it, inserted] = seen.insert({peer.address, peer.state});if (inserted || it->second != peer.state) {debug::log(DEBUG,@@ -627,8 +638,11 @@ namespace tether::bluetooth {std::lock_guard<std::mutex> lock(mutex);state.peer_taking_over = summary.taking_over;state.peer_active = summary.active;+ if (mine)+ state.owns = mine;}publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");+ return summary;}// Registers every other host in the buds' list, once each per session. A host the@@ -810,6 +824,8 @@ namespace tether::bluetooth {// never into a peer taking them, and only after the audio link has settled.bool claim_sent = false;std::optional<clock::time_point> claim_at;+ // Ownership taken to validate this host goes back unless something here is playing.+ std::optional<clock::time_point> idle_release_at;const auto claim = [&] {bool blocked = false;{@@ -819,7 +835,10 @@ namespace tether::bluetooth {if (blocked)return true;claim_sent = true;- return send_ownership(fd, true);+ if (!send_ownership(fd, true))+ return false;+ idle_release_at = clock::now() + std::chrono::milliseconds(IDLE_RELEASE_MS);+ return true;};std::map<std::string, uint8_t> peer_states;@@ -830,6 +849,9 @@ namespace tether::bluetooth {bool warned_unlisted = false;std::optional<bool> owns;bool peer_audio = false;+ // Another host is attached to the buds, this machine is playing through them.+ bool peer_present = false;+ bool local_audio = false;std::optional<AudioSourceEvent> latest_source;std::optional<clock::time_point> peer_audio_ends_at;// Published so local playback can step aside while the phone plays through the buds.@@ -863,6 +885,8 @@ namespace tether::bluetooth {timeout = std::min(timeout, until(due));if (claim_at)timeout = std::min(timeout, until(*claim_at));+ if (idle_release_at)+ timeout = std::min(timeout, until(*idle_release_at));if (peer_audio_ends_at)timeout = std::min(timeout, until(*peer_audio_ends_at));if (config_at)@@ -897,6 +921,21 @@ namespace tether::bluetooth {debug::log(DEBUG, "airpods: notification request re-sent after claiming");continue;}+ if (idle_release_at && fired >= *idle_release_at) {+ idle_release_at.reset();+ bool yielding = false;+ {+ std::lock_guard<std::mutex> lock(mutex);+ yielding = yielded;+ }+ if (releases_when_idle(local_audio, peer_present, yielding)) {+ debug::log(DEBUG, "airpods: nothing playing here, handing ownership back");+ if (!send_ownership(fd, false))+ break;+ owns = false;+ }+ continue;+ }if (claim_at && fired >= *claim_at) {claim_at.reset();std::string local;@@ -962,7 +1001,7 @@ namespace tether::bluetooth {if (auto peers = parse_connected_devices(buffer.data(), size)) {delivered = true;- note_peers(*peers, peer_states, warned_unlisted, delivered);+ peer_present = note_peers(*peers, peer_states, warned_unlisted, delivered).present;if (!register_hosts(fd, *peers, tipi_sent))break;// The host list proves the channel is ours; the claim waits for the audio link.@@ -985,6 +1024,15 @@ namespace tether::bluetooth {local = local_address;}latest_source = *source;+ if (!local.empty() && source->address == local &&+ local_audio != (source->source != AudioSource::None)) {+ local_audio = source->source != AudioSource::None;+ {+ std::lock_guard<std::mutex> lock(mutex);+ state.local_audio = local_audio;+ }+ publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");+ }// Re-armed on every stream start, so the claim waits for the newest one to settle.if (claims_for_playback(*source, local, owns, peer_audio)) {claim_at = last_packet + std::chrono::milliseconds(CLAIM_SETTLE_MS);@@ -1070,6 +1118,8 @@ namespace tether::bluetooth {state.peer_taking_over = false;state.peer_active = false;state.peer_audio = false;+ state.local_audio = false;+ state.owns.reset();}publish(AirPodsStatus::Idle, "");backoff_ms = BACKOFF_START_MS;@@ -1089,6 +1139,8 @@ namespace tether::bluetooth {state.peer_taking_over = false;state.peer_active = false;state.peer_audio = false;+ state.local_audio = false;+ state.owns.reset();}state.name = name;}diff --git a/src/daemon/main.cpp b/src/daemon/main.cppindex 7ab6052..10af28c 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;+// MPRIS pause, how long to let the player actually stop feeding sink before switching the card off under it.+constexpr int SINK_QUIET_TIMEOUT_MS = 300;// After a rebuilt Bluetooth sink reappears, time for the audio server to move streams back onto it.constexpr int SINK_SETTLE_SECONDS = 1;@@ -316,12 +318,16 @@ int main(int argc, char** argv) {}if (action == tether::bluetooth::HandoffAction::Release) {- std::thread([handoff, target, &run_ownership] {+ const bool streaming = state.local_audio;+ std::thread([handoff, target, streaming, &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 (streaming || paused > 0)+ tether::audio::sink_quiet(sink, SINK_QUIET_TIMEOUT_MS);+ const std::string profile =+ (streaming || paused > 0) ? tether::audio::release_bluez_card(target) : std::string{};if (tether::bluetooth::g_airpods)tether::bluetooth::g_airpods->set_ownership(false);debug::log(INFO,@@ -419,12 +425,17 @@ 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;++ struct {+ tether::bluetooth::EarState ear;+ std::optional<bool> owns;+ } prev;+tether::bluetooth::AirPodsWatcher airpods(- [&media, &last_ear, handoff, &native_handoff, &run_ownership](const tether::bluetooth::AirPodsState& state) {+ [&media, &prev, 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())) {+ switch (tether::bluetooth::ear_media_action(prev.ear, state.ear, mode, media.holding())) {case tether::bluetooth::MediaAction::Pause:if (const size_t paused = media.pause())debug::log(INFO, "airpods: paused {} player(s), a bud came out", paused);@@ -440,10 +451,18 @@ int main(int argc, char** argv) {if (state.address.empty() && !handoff->holding_buds())media.forget();+ // Losing the owner bit is the first sign the phone has taken the buds+ if (native_handoff.load() && prev.owns.value_or(false) && state.owns == false && state.local_audio &&+ !handoff->holding_buds()) {+ if (const size_t paused = media.pause())+ debug::log(INFO, "airpods: paused {} player(s), the phone took the buds", paused);+ }+ prev.owns = state.owns;+if (native_handoff.load())run_ownership(state);- last_ear = state.ear;+ prev.ear = state.ear;tether::broadcast_local_event(tether::bluetooth::to_json(state).dump());});@@ -546,12 +565,18 @@ int main(int argc, char** argv) {}).detach();};- const auto follow_airpods = [&bluez, &airpods, &native_handoff]() {+ // The buds this callback last saw connected, so the profile check runs on the connect edge.+ std::string airpods_at;+ const auto follow_airpods = [&bluez, &airpods, &native_handoff, handoff, &airpods_at]() {const auto snapshot = bluez.snapshot();const auto* device = tether::bluetooth::find_airpods(snapshot);// The buds report this machine back in their own peer list.const auto* adapter = tether::bluetooth::preferred_adapter(snapshot, bluez.preferred_adapter_id());native_handoff.store(adapter != nullptr && adapter->presents_as_apple());+ const std::string now_at = device != nullptr ? device->address : std::string{};+ if (!now_at.empty() && now_at != airpods_at && !handoff->holding_buds())+ tether::audio::revive_bluez_card(now_at);+ airpods_at = now_at;airpods.set_device(device ? device->address : std::string{},device ? device->name : std::string{},adapter ? adapter->address : std::string{});diff --git a/test/test_airpods.cpp b/test/test_airpods.cppindex f21dcec..d3c79b7 100644--- a/test/test_airpods.cpp+++ b/test/test_airpods.cpp@@ -314,6 +314,10 @@ TEST(AirPods, SummarisesPeersWithoutCountingItself) {// Without a local address every entry counts, which is the safe way round.EXPECT_TRUE(summarize_peers(peers, "").active);+ // `present` errs the other way: with no local address there is no peer to hand the buds to.+ EXPECT_TRUE(summarize_peers(peers, "AC:F2:3C:AF:52:9C").present);+ EXPECT_FALSE(summarize_peers(peers, "").present);+ EXPECT_FALSE(summarize_peers({{"AC:F2:3C:AF:52:9C", 0x02, 0x02}}, "AC:F2:3C:AF:52:9C").present);}TEST(AirPods, ParsesTheAudioSource) {@@ -343,6 +347,18 @@ TEST(AirPods, ClaimsWhenPlayingHereWithoutOwningTheBuds) {EXPECT_FALSE(claims_for_playback(here, "", false, false));}+// The opening claim validates this host; keeping the buds it took is what stops the phone+// from routing to them at all. Reported on 0.2.30, issue #85.+TEST(AirPods, GivesOwnershipBackWhenNothingIsPlayingHere) {+ EXPECT_TRUE(releases_when_idle(false, true, false));+ // Playing here is the whole reason to hold them.+ EXPECT_FALSE(releases_when_idle(true, true, false));+ // Alone with the buds there is nobody to hand them to.+ EXPECT_FALSE(releases_when_idle(false, false, false));+ // Already given up for a call: that release is the handoff's to undo.+ EXPECT_FALSE(releases_when_idle(false, true, true));+}+TEST(AirPods, OwnershipFollowsThePeerTakingTheBuds) {EXPECT_EQ(ownership_action(true, false, true), HandoffAction::Release);// Given up already: nothing to give up twice.