Skip to content

Linux + iPhone Continuity / iMessage / SMS

fix: complete airpods handoff implementation

Zack Bartel632cbd75229b
diff --git a/README.md b/README.md
index df0c293..48ac059 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,8 @@ Connections run over TLS 1.2 and both sides present a self-signed X.509 certific
Place, answer and end calls on the iPhone from the desktop, complete with caller ID and the phone's carrier and signal.
The call audio stays on the iPhone. If you've used Linux long enough you know why (it sounds like "FalsePotty-o"). PulsAlsaWire is too hard to support across all deployment targets.
+Stock PipeWire makes the computer a speaker for the phone, which takes call control away and moves the iPhone's music and sounds to the desktop. The recommended audio setting is in [Keeping the phone's audio on the phone](docs/BLUETOOTH.md#keeping-the-phones-audio-on-the-phone).
+
### OTP Handling
Streamline two-factor authentication across your devices:
- iOS Share Extension: Send OTP codes from your iPhone to your Linux clipboard.
diff --git a/docs/BLUETOOTH.md b/docs/BLUETOOTH.md
index d23fb08..2f1dc2e 100644
--- a/docs/BLUETOOTH.md
+++ b/docs/BLUETOOTH.md
@@ -487,7 +487,7 @@ the narrower check; it rules out the `*`/`#` supplementary-service codes deliber
## AirPods
Battery for the buds and the case, the listening mode, and in-ear detection, in the
-Devices list and from `tether --bt-airpods`. No stem control yet.
+Devices list and from `tether --bt-airpods`. A single stem press plays and pauses here.
**All of it is off until switched on** -- `tether --bt-airpods-enable on`. See "Standing
down" below.
@@ -523,7 +523,7 @@ anything sent ahead of its own pace, silently: no error, no refusal, the packet
no effect. Each step also has a deadline, because some models never acknowledge and an
unacknowledged step must not stall the session.
-Two more notifications are read, and they are what the ownership handoff runs on:
+Two more notifications are read for ownership:
```
connected-devices 04 00 04 00 2E 00 [?] [?] [count] ([mac] * 6 [role] [state]) * count
@@ -573,6 +573,57 @@ case -- and it combines with the charging bits, so a pod charging in an open cas
unknown, never as 0%. A notification carries only what changed, so anything it leaves out
keeps its previous level.
+### Stem press
+
+```
+stem config 04 00 04 00 09 00 39 [mask] 00 00 00 single 01, double 02, triple 04, long 08
+stem press 04 00 04 00 19 00 [type] [bud] type 05 single .. 08 long, bud 01 left 02 right
+```
+
+Without the stem config a single press runs the firmware's own play/pause, and **that is what moves
+the audio to the iPhone**: the Apple toggle between hosts. With mask `01` the buds send the press
+here instead and do nothing themselves, so Tether toggles MPRIS (`MediaControl::toggle()`). Double,
+triple and long keep their firmware actions. Found by AirPods Center (orychalk's fork), validated
+there on Pro 2 and Pro 3, and here on Pro 3.
+
+It is dropped silently until the state broadcast the notification request starts has finished, so
+it goes out 1.5s after the channel opens (`STEM_CONFIG_AT_MS`), and again with the notification
+request after every claim, because the firmware resets both on each handoff.
+
+### Smart routing
+
+Hosts sharing the buds talk to each other through them. A host sends opcode `0x10` addressed to
+another host; the buds deliver it as `0x11` carrying the sender:
+
+```
+04 00 04 00 10 00 [target] * 6 [length] * 2 01 [OPACK dictionary] sent
+04 00 04 00 11 00 [sender] * 6 [length] * 2 01 [OPACK dictionary] received
+```
+
+Addresses least significant byte first; `length` little-endian, counting from the `01`. The body is
+Apple's OPACK: `E0+n` a dictionary of n entries, `40+len` a short string, `08+v` a small integer,
+`30`/`31`/`32` an 8/16/32-bit little-endian integer, `01`/`02` true/false, `A0+i` a back-reference
+to the i-th distinct string or wide integer so far. `parse_smart_routing()` decodes that subset and
+`smart_routing_packet()` encodes it. LibrePods builds these packets by hand and gets several wrong
+(`42 "YES"`, a missing tag before `btName`), so nothing here is copied byte for byte.
+
+What an iPhone sends, measured 2026-09-13:
+
+| message | keys |
+|---|---|
+| media report, on every change | `playingApp`, `hostStreamingState` `YES`/`NO`, `btAddress`, `btName`, `otherDeviceAudioCategory` |
+| idle heartbeat | `idleTime`, `btAddress`, `btName`, `nearbyAudioScore`, and `newTipi` on first contact |
+| yield request | `audioRoutingSetOwnershipToFalse` true, `reason` (`ManualRoute`) |
+
+`otherDeviceAudioCategory` is `100` for nothing, `301` for media (`com.apple.Music`) and `501` for a
+call (`com.apple.TelephonyUtilities`). `YES` with `100` is a route with nothing on it -- Control
+Center, or the moment a call hangs up -- so playing is `YES` with a category above 100.
+
+This machine sends the same media report, `tipi_add_device()` when it first sees a host, and on a
+take-over `smart_routing_hijack()`: `localscore`, `reason` `Hijackv2`, `audioRoutingScore`,
+`audioRoutingSetOwnershipToFalse` and `remotescore`, LibrePods' values with its references resolved.
+`btName` is `Android`, as both references send.
+
### Listening mode
Off, Transparency, Adaptive and Noise Cancellation, set from the AirPods page in the GTK
@@ -647,59 +698,51 @@ 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 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.
-
-**Every other host in the buds' list is registered, once per session.** Two `0x10` smart-routing
-packets, `tipi_add_device()` and `tipi_media_info()`, carry the target's address and this
-machine's. Android sends them, and so does the AC fork, which holds that they are what
-moves a host from unvalidated to validated. That rationale rests on a B-field reading this
-hardware contradicts, so treat the packets as unproven here until a capture shows them changing
-something. **The session's notification request goes out again 500ms after every claim**: the
-firmware resets its AAP state on each handoff and silently drops what a session set up before it.
-
-**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
-already given up come back even if the setting was switched off while they were away.
-
-Two guards carry the weight, both learned from a working implementation rather than from
-review:
+**It runs on what the other hosts report through the buds**, the smart-routing media reports
+above. No timer decides anything, and it does not need call control.
+
+- **A call on the phone gives the buds up** the moment the phone reports category `501`, before it
+ takes them. **Media on the phone gives them up** once the phone both reports it playing and owns
+ the buds (`AirPodsState::peer_busy()`): an iPhone playing on its own speaker does not take them
+ from a Mac, and does not take them from here.
+- **The phone reporting `NO` takes them back**, and resumes what the release paused.
+- **A player starting here takes them**, wherever they are, unless the phone is on a call. MPRIS
+ `PropertiesChanged` drives it (`MediaControl::watch()`). With the card down the player is paused
+ on the signal, the card comes back, and it resumes -- the pause is what keeps it off the
+ speakers. The claim goes with a media report saying something plays here and a hijack request,
+ which the iPhone answers with `NO`. Players that leave `PlaybackStatus` empty (Chromium without
+ Plasma Browser Integration) are not seen.
+- **A yield request from another host** releases at once, without waiting for the verdict.
+- **Losing the owner bit pauses local playback** on the spot, whoever took it.
+- Every change in whether something plays here goes to the other hosts (`set_streaming()`).
+
+With `a2dp_sink` in `bluez5.roles` the iPhone falls back to this computer as a speaker when it loses
+the AirPods here, instead of staying on the buds; see "Keeping the phone's audio on the phone".
+
+Releasing pauses first, then waits for the sink to go quiet, sends the release and switches the
+card off; see "The AirPods sink jammed after a call" for why the card, not the default sink.
+
+**Both buds out moves the stem and volume target to another host.** A session that owned the
+buds when the last one came out claims again when one goes back in (reported by orychalk).
+
+`ownership_action()` and `takes_over_for_play()` are pure and tested. Buds already given up come
+back even if the setting was switched off while they were away.
+
+Kept from before, because they are firmware facts rather than guesses:
- **Never claim while a peer is taking the buds.** A claim sent then leaves this host
contested, and the firmware closes the link about twenty seconds later at the next
- physical event. The peer states from the last connected-devices notification gate every
- claim -- but an idle peer at `0x15` is not one of them, per the wire protocol above.
-- **A peer that goes quiet has not necessarily finished.** The firmware reports no audio
- source every twenty seconds or so *during* a call. So a reclaim waits three seconds and
- checks the peer again, up to three times, and stays yielded if the phone re-asserts.
-
-The claim sent when the session comes up is deliberate: AirPods Pro 2 validates a host by
-itself, 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.
+ physical event. An idle peer at `0x15` and an owner are not taking them, per the wire protocol.
+- **The session claims once when it opens**, five seconds in (`CLAIM_SETTLE_MS`): AirPods Pro 2
+ validates a host by itself, Pro 3 never does, and an unvalidated host is dropped at the first pod
+ movement. Three seconds later (`IDLE_RELEASE_MS`, `releases_when_idle()`) ownership goes back
+ unless the buds have reported audio for this machine, so a machine that is not using the buds
+ does not hide them from the phone. A watcher that has given the buds up sends no claim of its
+ own.
+- **Every other host in the buds' list is registered, once per session**, with a media report
+ and `tipi_add_device()`.
+- **The notification request and stem config go out again 500ms after every claim**: the firmware
+ resets its AAP state on each handoff and silently drops what a session set up before it.
#### Disconnect handoff
@@ -900,6 +943,7 @@ checks the daemon does not make.
| Pairing bonds but the LE half never derives, on a machine with a USB dongle plugged in | Tether used the first powered controller, which is the dongle, not the built-in one | `tether --bt-status` marks the controller in use; `tether --bt-adapter <hciN>` picks another -- see 2026-09-01 |
| The link reads down forever with `br-connection-unknown`, while messages, contacts and notifications all work | This computer offers the iPhone no BR/EDR profile to connect to, and BlueZ only reports a link up while some local profile is connected | Nothing. Tether no longer waits on that link -- see 2026-08-23 below. Call support does not change this: BlueZ's hands-free profile is not one of the local profiles BlueZ counts |
| The iPhone's audio moves to the computer when Tether connects | The machine advertises itself as a Bluetooth speaker/headset, and iOS routes to it. Not caused by Tether beyond bringing the link up | See "Keeping the phone's audio on the phone" below |
+| After this computer takes the AirPods, the iPhone plays on the computer and needs the AirPods picked in Control Center | `a2dp_sink` makes the computer a speaker for the phone, and iOS falls back to the last one it had | See "Keeping the phone's audio on the phone" below |
| `tether --bt-calls` reports call control off | PipeWire took the profile *and* its telephony D-Bus service is off, the iPhone reconnected on its own and never opened hands-free, or `bluetoothd` is running without `--experimental` | Either give BlueZ the profile by dropping `hfp_hf` from `bluez5.roles`, or set `bluez5.telephony-dbus-service = true` and let Tether drive PipeWire's gateway -- see "Calls". The daemon cycles the BR/EDR bearer once per outage for the second cause; confirm with `busctl --system tree org.bluez \| grep telephony` and `busctl --user tree org.pipewire.Telephony` |
| AirPods are listed but the battery stays blank, and the row says another program is using the channel | The AAP channel takes one client, and something else has it | Stop the other AirPods program (LibrePods, AC, a status-bar widget that reads battery), or hand it over with `tether --bt-airpods-enable off` |
| Setting the AirPods listening mode to `off` does nothing, while the other three work | The buds declined it. Apple leaves Off out of the noise-control rotation by default on Pro models, and there is no refusal to report | Add Off to the rotation on the phone, under Settings > Bluetooth > (i) > Noise Control. Tether keeps showing the mode the buds are actually in |
@@ -922,49 +966,57 @@ checks the daemon does not make.
### Keeping the phone's audio on the phone
-Unaffected by call support: calls run over BlueZ's own profile and never make this
-machine an audio destination. This still applies exactly as written -- and the role
-list below is also what hands BlueZ the hands-free profile in the first place, since
-dropping `hfp_hf` is what keeps PipeWire from taking it.
+**Recommended for every Tether user, with or without AirPods.** Stock PipeWire makes the computer
+a Bluetooth speaker and hands-free unit for the phone, and that costs three things:
-Once the Classic link is up, the iPhone's calls, music, and system sounds play on the
-computer instead of the phone. PipeWire registers A2DP sink and HFP audio-gateway
-endpoints for every adapter, so the machine advertises itself as a speaker and headset,
-and iOS routes to a bonded device that offers one. Tether only brings the link up; the
-routing decision is the phone's. Every desktop with Bluetooth audio behaves this way.
+| | Stock WirePlumber | Recommended roles |
+|---|---|---|
+| iPhone calls, music and system sounds | Play on the computer | Stay on the phone |
+| Tether call control | None: PipeWire takes hands-free, BlueZ exports no `Telephony1` | Works, on BlueZ |
+| Carrier, signal, phone battery | None | Shown |
+| AirPods handed back to this machine | iPhone falls back to the computer; pick the AirPods in Control Center each time | iPhone stays on the AirPods |
+| Call audio on the computer | Offered, played only if PipeWire's call handling is set up | No: on the phone or its headset |
-To confirm it, with the phone connected:
+The stock default, from `man pipewire-props` (PipeWire 1.6.8):
-```bash
-pactl list cards
+```
+bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source bap_bcast_sink bap_bcast_source hfp_hf hfp_ag ]
```
-The phone appears as `bluez_card.<ADDR>` with `Active Profile: audio-gateway`.
+Once the Classic link is up, iOS routes to a bonded device that offers itself as a speaker or
+headset, the way it does to a car. Tether only brings the link up; the routing decision is the
+phone's. Every desktop with Bluetooth audio behaves this way. With the phone connected,
+`pactl list cards` shows it as `bluez_card.<ADDR>`.
-The fix is to stop advertising the roles a phone connects to, while keeping the ones
-headphones use. On WirePlumber 0.5 and later, write
-`~/.config/wireplumber/wireplumber.conf.d/51-no-phone-audio.conf`:
+The fix is to stop advertising the roles a phone connects to, while keeping the ones headphones
+use. On WirePlumber 0.5 and later:
-```
+```bash
+mkdir -p ~/.config/wireplumber/wireplumber.conf.d
+cat > ~/.config/wireplumber/wireplumber.conf.d/51-no-phone-audio.conf <<'EOF'
monitor.bluez.properties = {
- bluez5.roles = [ a2dp_source hfp_ag bap_source ]
+ bluez5.roles = [ a2dp_source bap_source hfp_ag ]
}
+EOF
+systemctl --user restart wireplumber
```
-Then `systemctl --user restart wireplumber` and reconnect the phone. Role names are
-from this machine's perspective, not the remote device's: `a2dp_source` and `hfp_ag`
-are the roles that drive headphones, `a2dp_sink` and `hfp_hf` are the roles that make
-the machine a destination for a phone. Dropping the second pair leaves the iPhone
-nothing to route to, so its audio stays local, while headphones keep both A2DP
-playback and the HFP microphone. `bap_source` keeps LE Audio playback; drop it too if
-nothing here uses LE Audio. On WirePlumber 0.4 the same setting goes in
+Then turn Bluetooth off and on on the iPhone. Only one file in `wireplumber.conf.d` should set
+`bluez5.roles`; remove the key from any other. On WirePlumber 0.4 the same setting goes in
`~/.config/wireplumber/bluetooth.lua.d/51-no-phone-audio.lua` as
-`bluez_monitor.properties["bluez5.roles"]`.
+`bluez_monitor.properties["bluez5.roles"] = "[ a2dp_source bap_source hfp_ag ]"`.
+
+Role names are from this machine's perspective. `a2dp_source` and `hfp_ag` drive headphones:
+playback and the headset microphone. `bap_source` is LE Audio playback; drop it if nothing here
+uses LE Audio. `a2dp_sink`, `bap_sink`, `asha_sink` and `hfp_hf` make the machine a destination
+for a phone, and leaving them out leaves the iPhone nothing to route to. Leaving out `hfp_hf` is
+also what hands BlueZ the hands-free profile, which is where call control and the indicators come
+from -- see "Calls".
-If you later want call audio on the desktop, be aware this setting is the thing in the
-way: `a2dp_sink` is what makes iOS willing to speak hands-free to this machine at all.
-See "Getting the call audio onto the desktop instead" -- you cannot keep the music here
-and move the calls.
+The one thing given up is the phone using the computer as a speaker or speakerphone. If you want
+call audio on the desktop, `a2dp_sink` is mandatory for it, and with it the phone's music and
+sounds come here too, and AirPods handoff falls back to the computer; see "Getting the call audio
+onto the desktop instead".
Two things that look like fixes and are not:
@@ -3441,3 +3493,69 @@ Both gates now log when they hold a claim back.
Not settled: whether a claim into `0x17` survives a pod movement afterwards (the reference's
contested-host drop). Unconfirmed on `0x17` hardware.
+
+### 2026-09-13 - A stem pause handed the buds to the iPhone, and nothing brought them back
+
+Pro 3, Linux playing and owning (`us 0x03`). A stem press stopped Linux and started the iPhone.
+From then on the stem drove the iPhone, and Linux had no sink until the card profile was set
+by hand.
+
+```
+01:32:41.436 us 0x03 -> 0x01, peer 0x05 -> 0x07
+01:32:41.439 paused 2 player(s), the phone took the buds
+01:32:41.896 audio source media on the iPhone
+01:32:41.976 gave the buds to the iPhone (paused 0, card a2dp-sink -> off)
+01:32:43.592 audio source media on the iPhone <- last one; no none follows
+```
+
+The players still reported `Playing` 3 ms after the ownership change, so the buds moved it
+before any pause reached this machine. Tether did not cause the takeover.
+
+Suspected first: the `tipi_media_info()` packet each session sends, which says this host has
+`playingApp NA` and `hostStreamingState NO` even while it streams. **Ruled out the same night**:
+with the packet removed, after a restart and again after a case cycle, the press still moved the
+buds to the iPhone. The packet is back. What moves them is on the firmware or iOS side, and
+not explained.
+
+The stuck half was ours. The phone kept playing, so `peer_audio` stayed latched and no
+reclaim came; the card was off, so playing here went to the speakers, the buds reported no
+local source and nothing claimed.
+
+An MPRIS poll that reclaimed on a local play edge got the buds back, and a stem pause on the iPhone
+returned them about 6s later (`PEER_AUDIO_SETTLE_MS` plus `HANDOFF_GUARD_SECONDS`). It worked, and
+it was more timing stacked on inference. Both were replaced the same day, below.
+
+### 2026-09-13 - The stem config, and what the iPhone was saying all along
+
+AirPods Center v2.3.0, orychalk's fork, sends stem config `0x39 = 01` and handles the press itself.
+Without it the firmware's single press is Apple's host toggle. With it, from 10:44:25, ten presses
+toggled Linux and the buds never moved.
+
+Logging every packet no parser handled then showed opcode `0x11` arriving from the iPhone all
+along, in OPACK -- see "Smart routing". The capture, from 10:43 (`tetherd.log`):
+
+```
+10:45:37.445 iPhone com.apple.Music YES 301
+10:45:42.154 us 0x03 -> 0x01, peer 0x05 -> 0x07 routed from Control Center
+10:46:01.780 playback started here, taking the buds back card was off: speaker burst
+10:46:02.523 iPhone Unknown NO 100 the iPhone yields to the claim
+10:48:01.079 iPhone com.apple.TelephonyUtilities YES 501 ring
+10:48:01.339 us 0x03 -> 0x01, peer 0x05 -> 0x07
+10:49:10.948 iPhone Unknown NO 100 hangup
+10:49:16.907 claim sent 6s of latch and guard
+10:43:44.138 iPhone audioRoutingSetOwnershipToFalse, reason ManualRoute
+```
+
+The phone says when a call starts and ends, and when media starts and stops, exactly and ahead of
+the ownership change. Everything Tether inferred from the owner bit, the audio-source notification,
+`PEER_AUDIO_SETTLE_MS`, `HANDOFF_GUARD_SECONDS`, the call list and the one-second MPRIS poll was
+standing in for it. All of it is gone; "Ownership handoff" describes what replaced it.
+
+The iPhone did not take the buds for music on its own while Linux owned them (10:45:37 to 42): it
+waited for Control Center. That matches a Mac.
+
+Also from orychalk (#85): a B-field threshold does not port (Pro 1 keeps an active iPhone at
+`0x01`), which the reports make moot; forcing a claim into an owning `0x17` iPhone survived twenty
+pod movements on Pro 3; and both buds out moves the volume target, hence the ear-return claim.
+
+Not yet verified on hardware: the whole of the above.
diff --git a/src/core/include/tether/bluetooth/airpods.hpp b/src/core/include/tether/bluetooth/airpods.hpp
index 1386c6a..f535fc7 100644
--- a/src/core/include/tether/bluetooth/airpods.hpp
+++ b/src/core/include/tether/bluetooth/airpods.hpp
@@ -125,8 +125,9 @@ namespace tether::bluetooth {
std::string name;
bool peer_taking_over = false;
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.
+ // Another host reports a call or media playing, from its own smart-routing reports.
bool peer_audio = false;
+ bool peer_call = false;
bool local_audio = false;
std::optional<bool> owns;
AirPodsBattery battery;
@@ -137,9 +138,10 @@ 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. Ownership
- // alone is not enough, because the phone keeps it until another host claims.
- bool peer_busy() const { return peer_active && peer_audio; }
+ // What handoff yields to: a peer on a call, which always takes the buds, or a peer that owns
+ // them and is playing through them. Ownership alone is not enough, because the phone keeps
+ // it until another host claims.
+ bool peer_busy() const { return peer_call || (peer_active && peer_audio); }
bool operator==(const AirPodsState&) const = default;
};
@@ -166,22 +168,41 @@ namespace tether::bluetooth {
// 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 playing through them.
- bool claims_for_playback(const AudioSourceEvent& event,
- const std::string& local,
- 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.
+ // `otherDeviceAudioCategory` in a host's media report, as an iPhone sends them.
+ inline constexpr int AUDIO_CATEGORY_NONE = 100;
+ inline constexpr int AUDIO_CATEGORY_MEDIA = 301;
+ inline constexpr int AUDIO_CATEGORY_CALL = 501;
+
+ // A smart-routing message another host sent this one through the buds:
+ // 04 00 04 00 11 00 [sender] * 6 [length] * 2 01 [OPACK dictionary]
+ // with the sender least-significant byte first. Hosts report what they are playing whenever it
+ // changes, and ask the others to give up ownership when they take the buds.
+ struct SmartRoutingMessage {
+ std::string sender;
+ std::string app;
+ // Unset in messages that are not media reports.
+ std::optional<bool> streaming;
+ std::optional<int> category;
+ bool set_ownership_to_false = false;
+
+ // A call or media is actually playing; a route with nothing on it reports YES with category 100.
+ bool playing() const { return streaming.value_or(false) && category.value_or(0) > AUDIO_CATEGORY_NONE; }
+ bool call() const { return streaming.value_or(false) && category == AUDIO_CATEGORY_CALL; }
+ };
+
+ // Returns no value for anything that is not one, or whose body does not decode.
+ std::optional<SmartRoutingMessage> parse_smart_routing(const uint8_t* data, size_t len);
+
+ // Smart-routing messages this host sends to `target`, opcode 0x10. Empty for an address that will
+ // not parse. The first two are what a host sends for every other host in the buds' list, which
+ // is what moves it from unvalidated to validated.
std::vector<uint8_t> tipi_add_device(const std::string& self, const std::string& target);
- std::vector<uint8_t> tipi_media_info(const std::string& self, const std::string& target);
+ std::vector<uint8_t> smart_routing_media_info(const std::string& self, const std::string& target, bool streaming);
+ // Tells `target` this host has taken the buds and it should give up ownership.
+ std::vector<uint8_t> smart_routing_hijack(const std::string& target);
// Whether any host other than `local` is engaged with the buds, or actively
// holding them. A machine's own entry is never a peer.
@@ -195,6 +216,12 @@ namespace tether::bluetooth {
PeerSummary summarize_peers(const std::vector<AapPeer>& peers, const std::string& local);
+ enum class StemPress { Single, Double, Triple, Long };
+
+ // Decodes a stem-press notification, `04 00 04 00 19 00 [type] [bud]`. The buds send one
+ // only for the press types the host claimed with the stem config.
+ std::optional<StemPress> parse_stem_press(const uint8_t* data, size_t len);
+
// Decodes a listening-mode notification, 11 bytes carrying the mode at offset 7.
// Returns no value for anything else, including an out-of-range mode.
std::optional<AncMode> parse_anc(const uint8_t* data, size_t len);
@@ -212,6 +239,10 @@ namespace tether::bluetooth {
// native handoff: the phone taking them is a peer going active, not a call.
HandoffAction ownership_action(bool peer_active, bool released, bool enabled);
+ // Whether a player starting here takes the buds: not while this machine owns them, never from a
+ // call, and not while a handoff is already moving them.
+ bool takes_over_for_play(std::optional<bool> owns, bool peer_call, bool busy);
+
// `released` is whether this code is what disconnected them: buds the user
// took away by hand are never reclaimed. A reclaim outlives `enabled` going
// false, so turning the feature off mid-call does not strand them.
@@ -227,7 +258,9 @@ namespace tether::bluetooth {
// Keeps an AAP channel open to one set of AirPods and publishes their battery.
class AirPodsWatcher {
public:
- explicit AirPodsWatcher(std::function<void(const AirPodsState&)> on_change);
+ // `on_stem_press` runs on the worker thread for each claimed press.
+ explicit AirPodsWatcher(std::function<void(const AirPodsState&)> on_change,
+ std::function<void(StemPress)> on_stem_press = {});
~AirPodsWatcher();
AirPodsWatcher(const AirPodsWatcher&) = delete;
@@ -252,6 +285,13 @@ namespace tether::bluetooth {
// also stops the watcher's own claims until they are taken back.
void set_ownership(bool own);
+ // Takes the buds the way another Apple host does: a claim, then a smart-routing report that
+ // something plays here and a request that every other host give up ownership.
+ void take_over();
+
+ // Reports to the other hosts whether something plays here. Sent when it changes.
+ void set_streaming(bool streaming);
+
AirPodsState state() const;
private:
diff --git a/src/core/include/tether/mpris.hpp b/src/core/include/tether/mpris.hpp
index 20bd75e..85f1668 100644
--- a/src/core/include/tether/mpris.hpp
+++ b/src/core/include/tether/mpris.hpp
@@ -1,5 +1,6 @@
#pragma once
+#include <functional>
#include <memory>
#include <string>
#include <vector>
@@ -23,6 +24,11 @@ namespace tether {
// Plays what this object paused, then forgets them.
size_t resume();
+ // Play/pause for a button press: pauses what is playing, otherwise plays what this object
+ // paused, otherwise the players the last toggle paused, otherwise the first paused player.
+ // Returns how many players it touched.
+ size_t toggle();
+
// Whether anything is currently paused by this object.
bool holding() const;
@@ -32,6 +38,11 @@ namespace tether {
// Bus names of every MPRIS player currently reporting Playing.
std::vector<std::string> playing() const;
+ // Calls `on_change` on a thread of its own each time a player reports a new PlaybackStatus,
+ // with the player's unique bus name. Players that leave PlaybackStatus empty are not seen.
+ // Call once.
+ void watch(std::function<void(const std::string& player, bool playing)> on_change);
+
private:
struct Impl;
std::unique_ptr<Impl> impl_;
diff --git a/src/core/src/bluetooth/airpods.cpp b/src/core/src/bluetooth/airpods.cpp
index 1814910..df9873a 100644
--- a/src/core/src/bluetooth/airpods.cpp
+++ b/src/core/src/bluetooth/airpods.cpp
@@ -16,6 +16,7 @@
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
+#include <variant>
// The kernel's L2CAP ABI, declared here rather than pulled in from bluez-libs.
// glibc already defines some of them.
@@ -74,9 +75,14 @@ namespace tether::bluetooth {
// The firmware's own ownership verdict arrives on the same shape.
constexpr uint8_t OWNS_CONNECTION_PREFIX[] = {0x04, 0x00, 0x04, 0x00, 0x09, 0x00, 0x06};
- // Claims are answered slowly and the firmware saturates on a burst of them. Three seconds
- // is what the AirPods Center reference settled on after seek storms disconnected the buds.
- constexpr int CLAIM_COOLDOWN_MS = 3000;
+ // Stem config: the host takes single press, and the buds send it a stem-press notification
+ // instead of running their own play/pause, which moves the audio to another host. The other
+ // press types keep their firmware actions. Reset by the firmware on every handoff.
+ constexpr uint8_t STEM_CONFIG[] = {0x04, 0x00, 0x04, 0x00, 0x09, 0x00, 0x39, 0x01, 0x00, 0x00, 0x00};
+ constexpr uint8_t STEM_PRESS_PREFIX[] = {0x04, 0x00, 0x04, 0x00, 0x19, 0x00};
+ constexpr size_t STEM_PRESS_PACKET_BYTES = 8;
+ // Smart-routing messages another host relays through the buds.
+ constexpr uint8_t SMART_ROUTING_RESPONSE_PREFIX[] = {0x04, 0x00, 0x04, 0x00, 0x11, 0x00};
constexpr uint8_t HANDSHAKE_ACK[] = {0x01, 0x00, 0x04, 0x00};
constexpr uint8_t FEATURES_ACK[] = {0x04, 0x00, 0x04, 0x00, 0x2b, 0x00};
@@ -108,15 +114,15 @@ 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;
- // How long a claim waits after the channel opens or this machine starts playing.
+ // The stem config is dropped silently until the state broadcast the notification request
+ // starts has finished; AirPods Center measured this on Pro 2 and Pro 3.
+ constexpr int STEM_CONFIG_AT_MS = 1500;
+ // How long the session claim waits after the channel opens.
// 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;
// After a claim, before the session's notification request goes out again. The
// firmware discards anything sent while it is still broadcasting its own state.
constexpr int CONFIG_RESEND_MS = 500;
@@ -204,6 +210,15 @@ namespace tether::bluetooth {
return out;
}
+ // Non-printable bytes as '.'.
+ std::string printable(const uint8_t* data, size_t len) {
+ std::string out(data, data + len);
+ for (auto& c : out)
+ if (c < 0x20 || c > 0x7e)
+ c = '.';
+ return out;
+ }
+
} // namespace
const char* to_string(AirPodsStatus status) {
@@ -235,6 +250,7 @@ namespace tether::bluetooth {
{"peer_taking_over", s.peer_taking_over},
{"peer_active", s.peer_active},
{"peer_audio", s.peer_audio},
+ {"peer_call", s.peer_call},
{"status", to_string(s.status)},
{"reason", s.reason},
};
@@ -299,6 +315,25 @@ namespace tether::bluetooth {
return EarState{decode(data[6]), decode(data[7])};
}
+ std::optional<StemPress> parse_stem_press(const uint8_t* data, size_t len) {
+ if (data == nullptr || len != STEM_PRESS_PACKET_BYTES)
+ return std::nullopt;
+ if (std::memcmp(data, STEM_PRESS_PREFIX, sizeof(STEM_PRESS_PREFIX)) != 0)
+ return std::nullopt;
+ switch (data[6]) {
+ case 0x05:
+ return StemPress::Single;
+ case 0x06:
+ return StemPress::Double;
+ case 0x07:
+ return StemPress::Triple;
+ case 0x08:
+ return StemPress::Long;
+ default:
+ return std::nullopt;
+ }
+ }
+
std::optional<AncMode> parse_anc(const uint8_t* data, size_t len) {
if (data == nullptr || len != ANC_PACKET_BYTES)
return std::nullopt;
@@ -419,12 +454,8 @@ namespace tether::bluetooth {
return HandoffAction::None;
}
- bool claims_for_playback(const AudioSourceEvent& event,
- const std::string& local,
- std::optional<bool> owns,
- bool peer_audio) {
- return !local.empty() && event.address == local && event.source != AudioSource::None && owns == false &&
- !peer_audio;
+ bool takes_over_for_play(std::optional<bool> owns, bool peer_call, bool busy) {
+ return owns != true && !peer_call && !busy;
}
bool releases_when_idle(bool local_audio, bool peer_present, bool yielded) {
@@ -433,48 +464,166 @@ namespace tether::bluetooth {
namespace {
- // Both TiPi packets are opcode 0x10 (smart routing) and look alike. The target's
- // address least-significant byte first, then a body of length-tagged ASCII keys.
- std::vector<uint8_t> tipi_packet(const std::string& self,
- const std::string& target,
- const char* head,
- size_t head_len,
- const char* tail,
- size_t tail_len) {
+ // Apple's OPACK, the subset smart routing uses: one dictionary of strings, integers and booleans.
+ using OpackValue = std::variant<bool, int64_t, std::string>;
+ using OpackEntries = std::vector<std::pair<std::string, OpackValue>>;
+
+ void opack_append(std::vector<uint8_t>& out, const OpackValue& value) {
+ if (const auto* flag = std::get_if<bool>(&value)) {
+ out.push_back(*flag ? 0x01 : 0x02);
+ } else if (const auto* number = std::get_if<int64_t>(&value)) {
+ const auto n = static_cast<uint64_t>(*number);
+ if (*number >= 0 && *number <= 0x27) {
+ out.push_back(static_cast<uint8_t>(0x08 + n));
+ } else {
+ const int size = *number >= 0 && n <= 0xff ? 1 : *number >= 0 && n <= 0xffff ? 2 : 4;
+ out.push_back(static_cast<uint8_t>(0x30 + (size == 1 ? 0 : size == 2 ? 1 : 2)));
+ for (int i = 0; i < size; ++i)
+ out.push_back(static_cast<uint8_t>(n >> (8 * i)));
+ }
+ } else {
+ const auto& text = std::get<std::string>(value);
+ if (text.size() <= 0x20) {
+ out.push_back(static_cast<uint8_t>(0x40 + text.size()));
+ } else {
+ out.push_back(0x61);
+ out.push_back(static_cast<uint8_t>(text.size()));
+ }
+ out.insert(out.end(), text.begin(), text.end());
+ }
+ }
+
+ // A smart-routing packet: opcode, the target least-significant byte first, the body length,
+ // then 01 and the dictionary.
+ std::vector<uint8_t> smart_routing_packet(const std::string& target, const OpackEntries& entries) {
uint8_t addr[6] = {};
- if (self.size() != 17 || !parse_address(target, addr))
+ if (!parse_address(target, addr) || entries.size() >= 15)
return {};
+ std::vector<uint8_t> body = {0x01, static_cast<uint8_t>(0xe0 + entries.size())};
+ for (const auto& [key, value] : entries) {
+ opack_append(body, key);
+ opack_append(body, value);
+ }
static constexpr uint8_t PREFIX[] = {0x04, 0x00, 0x04, 0x00, 0x10, 0x00};
std::vector<uint8_t> packet(std::begin(PREFIX), std::end(PREFIX));
packet.insert(packet.end(), std::begin(addr), std::end(addr));
- packet.insert(packet.end(), head, head + head_len);
- packet.insert(packet.end(), self.begin(), self.end());
- packet.insert(packet.end(), tail, tail + tail_len);
+ packet.push_back(static_cast<uint8_t>(body.size()));
+ packet.push_back(static_cast<uint8_t>(body.size() >> 8));
+ packet.insert(packet.end(), body.begin(), body.end());
return packet;
}
- constexpr char TIPI_ADD_HEAD[] = "\x52\x00\x01\xe5\x48idleTime\x08\x47newTipi\x01\x49"
- "btAddress\x51";
- constexpr char TIPI_ADD_TAIL[] = "\x46"
- "btName\x47"
- "Android\x50nearbyAudioScore\x0e";
- constexpr char TIPI_MEDIA_HEAD[] = "\x6c\x00\x01\xe5\x4a"
- "playingApp\x42NA\x52hostStreamingState\x42NO\x49"
- "btAddress\x51";
- constexpr char TIPI_MEDIA_TAIL[] = "\x46"
- "btName\x47"
- "Android\x58otherDeviceAudioCategory\x30\x64";
+ // Decodes one value. `seen` is OPACK's back-reference table: every string and wide integer,
+ // once each, which 0xA0 + index refers to.
+ std::optional<OpackValue>
+ opack_read(const uint8_t* data, size_t len, size_t& at, std::vector<OpackValue>& seen) {
+ if (at >= len)
+ return std::nullopt;
+ const uint8_t tag = data[at++];
+ const auto remember = [&](OpackValue value) {
+ if (std::find(seen.begin(), seen.end(), value) == seen.end())
+ seen.push_back(value);
+ return std::optional<OpackValue>(std::move(value));
+ };
+ const auto little_endian = [&](size_t size) -> std::optional<uint64_t> {
+ if (len - at < size)
+ return std::nullopt;
+ uint64_t n = 0;
+ for (size_t i = 0; i < size; ++i)
+ n |= static_cast<uint64_t>(data[at + i]) << (8 * i);
+ at += size;
+ return n;
+ };
+ if (tag == 0x01 || tag == 0x02)
+ return OpackValue(tag == 0x01);
+ if (tag >= 0x08 && tag <= 0x2f)
+ return OpackValue(static_cast<int64_t>(tag - 0x08));
+ if (tag >= 0x30 && tag <= 0x33) {
+ const auto n = little_endian(size_t{1} << (tag - 0x30));
+ return n ? remember(static_cast<int64_t>(*n)) : std::nullopt;
+ }
+ if ((tag >= 0x40 && tag <= 0x60) || (tag >= 0x61 && tag <= 0x64)) {
+ std::optional<uint64_t> size =
+ tag <= 0x60 ? std::optional<uint64_t>(tag - 0x40) : little_endian(size_t{1} << (tag - 0x61));
+ if (!size || len - at < *size)
+ return std::nullopt;
+ std::string text(data + at, data + at + *size);
+ at += *size;
+ return remember(std::move(text));
+ }
+ if (tag >= 0xa0 && tag <= 0xc0 && static_cast<size_t>(tag - 0xa0) < seen.size())
+ return seen[tag - 0xa0];
+ return std::nullopt;
+ }
} // namespace
+ std::optional<SmartRoutingMessage> parse_smart_routing(const uint8_t* data, size_t len) {
+ constexpr size_t BODY_AT = 14;
+ if (data == nullptr || len < BODY_AT + 2 ||
+ !starts_with(data, len, SMART_ROUTING_RESPONSE_PREFIX, sizeof(SMART_ROUTING_RESPONSE_PREFIX)))
+ return std::nullopt;
+ const size_t body_len = data[12] | (data[13] << 8);
+ if (body_len < 2 || BODY_AT + body_len > len || data[BODY_AT] != 0x01)
+ return std::nullopt;
+ const uint8_t dict = data[BODY_AT + 1];
+ if (dict < 0xe0 || dict >= 0xef)
+ return std::nullopt;
+
+ SmartRoutingMessage message;
+ message.sender = format_address(data + 6, true);
+ const size_t end = BODY_AT + body_len;
+ size_t at = BODY_AT + 2;
+ std::vector<OpackValue> seen;
+ for (int i = 0; i < dict - 0xe0; ++i) {
+ const auto key = opack_read(data, end, at, seen);
+ const auto value = key ? opack_read(data, end, at, seen) : std::nullopt;
+ if (!value || !std::holds_alternative<std::string>(*key))
+ return std::nullopt;
+ const auto& name = std::get<std::string>(*key);
+ if (name == "playingApp" && std::holds_alternative<std::string>(*value))
+ message.app = std::get<std::string>(*value);
+ else if (name == "hostStreamingState" && std::holds_alternative<std::string>(*value))
+ message.streaming = std::get<std::string>(*value) == "YES";
+ else if (name == "otherDeviceAudioCategory" && std::holds_alternative<int64_t>(*value))
+ message.category = static_cast<int>(std::get<int64_t>(*value));
+ else if (name == "audioRoutingSetOwnershipToFalse" && std::holds_alternative<bool>(*value))
+ message.set_ownership_to_false = std::get<bool>(*value);
+ }
+ return message;
+ }
+
std::vector<uint8_t> tipi_add_device(const std::string& self, const std::string& target) {
- return tipi_packet(
- self, target, TIPI_ADD_HEAD, sizeof(TIPI_ADD_HEAD) - 1, TIPI_ADD_TAIL, sizeof(TIPI_ADD_TAIL) - 1);
+ if (self.size() != 17)
+ return {};
+ return smart_routing_packet(target,
+ {{"idleTime", int64_t{0}},
+ {"newTipi", true},
+ {"btAddress", self},
+ {"btName", std::string("Android")},
+ {"nearbyAudioScore", int64_t{6}}});
+ }
+
+ // The keys and their order are the iPhone's own report.
+ std::vector<uint8_t> smart_routing_media_info(const std::string& self, const std::string& target, bool streaming) {
+ if (self.size() != 17)
+ return {};
+ return smart_routing_packet(
+ target,
+ {{"playingApp", std::string(streaming ? "Unknown" : "NA")},
+ {"hostStreamingState", std::string(streaming ? "YES" : "NO")},
+ {"btAddress", self},
+ {"btName", std::string("Android")},
+ {"otherDeviceAudioCategory", int64_t{streaming ? AUDIO_CATEGORY_MEDIA : AUDIO_CATEGORY_NONE}}});
}
- std::vector<uint8_t> tipi_media_info(const std::string& self, const std::string& target) {
- return tipi_packet(
- self, target, TIPI_MEDIA_HEAD, sizeof(TIPI_MEDIA_HEAD) - 1, TIPI_MEDIA_TAIL, sizeof(TIPI_MEDIA_TAIL) - 1);
+ std::vector<uint8_t> smart_routing_hijack(const std::string& target) {
+ return smart_routing_packet(target,
+ {{"localscore", int64_t{100}},
+ {"reason", std::string("Hijackv2")},
+ {"audioRoutingScore", int64_t{301}},
+ {"audioRoutingSetOwnershipToFalse", true},
+ {"remotescore", int64_t{301}}});
}
PeerSummary summarize_peers(const std::vector<AapPeer>& peers, const std::string& local) {
@@ -533,9 +682,10 @@ namespace tether::bluetooth {
explicit Impl(std::function<void(const AirPodsState&)> cb) : on_change(std::move(cb)) {}
// Session setup, paced by the buds' own acknowledgements.
- enum class Stage { Handshake, Features, Notifications, Ready };
+ enum class Stage { Handshake, Features, Notifications, StemConfig, Ready };
std::function<void(const AirPodsState&)> on_change;
+ std::function<void(StemPress)> on_stem_press;
mutable std::mutex mutex;
AirPodsState state;
@@ -548,12 +698,16 @@ namespace tether::bluetooth {
// the one race worth not having.
std::optional<AncMode> pending_anc;
std::optional<bool> pending_ownership;
+ bool pending_take_over = false;
+ // Whether something plays here, as reported to the other hosts. `streaming_sent` is what the
+ // current session last told them.
+ bool streaming = false;
+ std::optional<bool> streaming_sent;
// This machine gave the buds up: no claim of the watcher's own goes out until it takes them back.
bool yielded = false;
// A claim has just gone out, so the session's notification request is due again: the
// firmware resets its AAP state on every handoff and silently drops what was set before.
bool config_resend_due = false;
- std::chrono::steady_clock::time_point last_claim{};
bool stopping = false;
bool enabled = true;
@@ -650,9 +804,11 @@ namespace tether::bluetooth {
// one it evicts when the pods move while another host is engaged.
bool register_hosts(int fd, const std::vector<AapPeer>& peers, std::vector<std::string>& sent) {
std::string local;
+ bool playing = false;
{
std::lock_guard<std::mutex> lock(mutex);
local = local_address;
+ playing = streaming;
}
if (local.empty())
return true;
@@ -661,7 +817,7 @@ namespace tether::bluetooth {
continue;
sent.push_back(peer.address);
for (const auto& packet :
- {tipi_media_info(local, peer.address), tipi_add_device(local, peer.address)}) {
+ {smart_routing_media_info(local, peer.address, playing), tipi_add_device(local, peer.address)}) {
if (packet.empty())
continue;
if (!write_all(fd, packet.data(), packet.size())) {
@@ -688,20 +844,12 @@ namespace tether::bluetooth {
return false;
}
- const auto now = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(mutex);
if (state.peer_taking_over) {
debug::log(DEBUG, "airpods: not claiming, a peer is taking the buds");
return true;
}
- // ponytail: a flat cooldown. Claims come from call transitions here, not
- // from every play event; measure the pause length if that ever changes.
- if (now - last_claim < std::chrono::milliseconds(CLAIM_COOLDOWN_MS)) {
- debug::log(DEBUG, "airpods: not claiming, a claim went out under {}ms ago", CLAIM_COOLDOWN_MS);
- return true;
- }
- last_claim = now;
}
if (write_all(fd, CLAIM, sizeof(CLAIM))) {
debug::log(DEBUG, "airpods: claim sent");
@@ -715,16 +863,54 @@ namespace tether::bluetooth {
// Sends whatever the caller queued, on the worker thread. False means the
// write failed and the session is over.
- bool send_pending(int fd) {
+ bool send_pending(int fd, const std::vector<AapPeer>& hosts) {
std::optional<AncMode> mode;
std::optional<bool> ownership;
+ bool take_over = false;
+ bool playing = false;
+ std::optional<bool> told;
+ std::string local;
{
std::lock_guard<std::mutex> lock(mutex);
std::swap(mode, pending_anc);
std::swap(ownership, pending_ownership);
+ std::swap(take_over, pending_take_over);
+ playing = streaming;
+ told = streaming_sent;
+ local = local_address;
}
if (ownership && !send_ownership(fd, *ownership))
return false;
+
+ // Every other host hears this one's playback state, and on a take-over is asked to let go.
+ const auto to_hosts = [&](const std::function<std::vector<uint8_t>(const std::string&)>& build) {
+ for (const auto& host : hosts) {
+ if (host.address == local)
+ continue;
+ const auto packet = build(host.address);
+ if (!packet.empty() && !write_all(fd, packet.data(), packet.size())) {
+ debug::log(DEBUG, "airpods: smart routing write failed: {}", std::strerror(errno));
+ return false;
+ }
+ }
+ return true;
+ };
+ if (take_over && !send_ownership(fd, true))
+ return false;
+ // A take-over is for playback, whether or not the player has resumed yet.
+ const bool report = take_over || playing;
+ if (!local.empty() && told != report) {
+ if (!to_hosts([&](const std::string& host) { return smart_routing_media_info(local, host, report); }))
+ return false;
+ debug::log(DEBUG, "airpods: told the other hosts {} is playing here", report ? "something" : "nothing");
+ std::lock_guard<std::mutex> lock(mutex);
+ streaming_sent = report;
+ }
+ if (take_over) {
+ if (!to_hosts([](const std::string& host) { return smart_routing_hijack(host); }))
+ return false;
+ debug::log(DEBUG, "airpods: took the buds over from the other hosts");
+ }
if (!mode)
return true;
const uint8_t packet[] = {
@@ -812,6 +998,13 @@ namespace tether::bluetooth {
case Stage::Notifications:
if (!write_all(fd, REQUEST_NOTIFICATIONS, sizeof(REQUEST_NOTIFICATIONS)))
return false;
+ stage = Stage::StemConfig;
+ due = std::max(opened + std::chrono::milliseconds(STEM_CONFIG_AT_MS), now);
+ return true;
+ case Stage::StemConfig:
+ if (!write_all(fd, STEM_CONFIG, sizeof(STEM_CONFIG)))
+ return false;
+ debug::log(DEBUG, "airpods: stem config sent");
stage = Stage::Ready;
return true;
case Stage::Ready:
@@ -856,21 +1049,19 @@ namespace tether::bluetooth {
std::optional<clock::time_point> config_at;
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.
- const auto set_peer_audio = [&](bool on) {
- peer_audio = on;
- {
- std::lock_guard<std::mutex> lock(mutex);
- state.peer_audio = on;
- }
- publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");
- };
+ // The buds' host list, and each host's latest media report.
+ std::vector<AapPeer> hosts;
+ std::map<std::string, SmartRoutingMessage> reports;
+ // Both buds out moves the stem and volume target to another host; this machine owned
+ // them when they came out, so it claims again when one goes back in.
+ bool owned_when_removed = false;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ streaming_sent.reset();
+ }
std::array<uint8_t, 1024> buffer{};
while (!retargeted(address)) {
const auto now = clock::now();
@@ -895,14 +1086,12 @@ namespace tether::bluetooth {
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)
timeout = std::min(timeout, until(*config_at));
const int ready = wait_for(fd, wake_fd, POLLIN, std::max(timeout, 0));
if (ready == 0) {
drain_wake();
- if (!send_pending(fd))
+ if (!send_pending(fd, hosts))
break;
continue;
}
@@ -915,18 +1104,14 @@ namespace tether::bluetooth {
break;
continue;
}
- if (peer_audio_ends_at && fired >= *peer_audio_ends_at) {
- peer_audio_ends_at.reset();
- set_peer_audio(false);
- continue;
- }
// The firmware drops what a session set up before a handoff, so the
- // notification request goes out again after taking the buds back.
+ // notification request and stem config go out again after taking the buds back.
if (config_at && fired >= *config_at) {
config_at.reset();
- if (!write_all(fd, REQUEST_NOTIFICATIONS, sizeof(REQUEST_NOTIFICATIONS)))
+ if (!write_all(fd, REQUEST_NOTIFICATIONS, sizeof(REQUEST_NOTIFICATIONS)) ||
+ !write_all(fd, STEM_CONFIG, sizeof(STEM_CONFIG)))
break;
- debug::log(DEBUG, "airpods: notification request re-sent after claiming");
+ debug::log(DEBUG, "airpods: notification request and stem config re-sent after claiming");
continue;
}
if (idle_release_at && fired >= *idle_release_at) {
@@ -946,24 +1131,8 @@ namespace tether::bluetooth {
}
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 (!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;
- }
+ if (!claim_sent && !claim())
+ break;
continue;
}
if (fired - quiet_since >= std::chrono::milliseconds(quiet_timeout)) {
@@ -1010,6 +1179,7 @@ namespace tether::bluetooth {
if (auto peers = parse_connected_devices(buffer.data(), size)) {
delivered = true;
peer_present = note_peers(*peers, peer_states, warned_unlisted, delivered).present;
+ hosts = *peers;
if (!register_hosts(fd, *peers, tipi_sent))
break;
// The host list proves the channel is ours; the claim waits for the audio link.
@@ -1031,7 +1201,6 @@ namespace tether::bluetooth {
std::lock_guard<std::mutex> lock(mutex);
local = local_address;
}
- latest_source = *source;
if (!local.empty() && source->address == local &&
local_audio != (source->source != AudioSource::None)) {
local_audio = source->source != AudioSource::None;
@@ -1041,20 +1210,51 @@ namespace tether::bluetooth {
}
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);
- debug::log(
- DEBUG, "airpods: playing here without owning the buds; claiming in {}ms", CLAIM_SETTLE_MS);
+ continue;
+ }
+
+ if (auto message = parse_smart_routing(buffer.data(), size)) {
+ delivered = true;
+ debug::log(DEBUG,
+ "airpods: smart routing from {}: app {}, streaming {}, category {}{}",
+ message->sender,
+ message->app.empty() ? "-" : message->app,
+ message->streaming ? (*message->streaming ? "yes" : "no") : "-",
+ message->category ? std::to_string(*message->category) : "-",
+ message->set_ownership_to_false ? ", set ownership to false" : "");
+ if (message->streaming)
+ reports[message->sender] = *message;
+
+ std::string local;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ local = local_address;
}
- // 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);
+ bool audio = false;
+ bool call = false;
+ for (const auto& [host, report] : reports) {
+ if (host == local)
+ continue;
+ audio = audio || report.playing();
+ call = call || report.call();
+ }
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ state.peer_audio = audio;
+ state.peer_call = call;
}
+
+ // The other host has taken the buds and says so; this one lets go without waiting
+ // for the buds' own verdict.
+ if (message->set_ownership_to_false && message->sender != local) {
+ if (!send_ownership(fd, false))
+ break;
+ owns = false;
+ std::lock_guard<std::mutex> lock(mutex);
+ state.owns = false;
+ yielded = true;
+ }
+ publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");
continue;
}
@@ -1070,17 +1270,43 @@ namespace tether::bluetooth {
if (auto ear = parse_ear(buffer.data(), size)) {
delivered = true;
+ bool reclaim = false;
{
std::lock_guard<std::mutex> lock(mutex);
+ if (state.ear.in_ear() > 0 && ear->in_ear() == 0) {
+ owned_when_removed = state.owns.value_or(false);
+ } else if (state.ear.in_ear() == 0 && ear->in_ear() > 0 && owned_when_removed) {
+ owned_when_removed = false;
+ reclaim = !yielded;
+ }
state.ear = *ear;
}
+ if (reclaim) {
+ debug::log(DEBUG, "airpods: a bud went back in after both were out; claiming again");
+ if (!send_ownership(fd, true))
+ break;
+ }
publish(delivered ? AirPodsStatus::Live : AirPodsStatus::Connecting, "");
continue;
}
+ if (auto press = parse_stem_press(buffer.data(), size)) {
+ delivered = true;
+ debug::log(DEBUG, "airpods: stem press {:#04x}", buffer[6]);
+ if (on_stem_press)
+ on_stem_press(*press);
+ continue;
+ }
+
auto update = parse_battery(buffer.data(), size);
- if (!update)
+ if (!update) {
+ // A smart-routing message that did not decode is shown as text: its keys are ASCII.
+ if (starts_with(
+ buffer.data(), size, SMART_ROUTING_RESPONSE_PREFIX, sizeof(SMART_ROUTING_RESPONSE_PREFIX)))
+ debug::log(DEBUG, "airpods: smart routing not decoded: {}", printable(buffer.data(), size));
+ debug::log(DEBUG, "airpods: rx unhandled {}", hex(buffer.data(), size));
continue;
+ }
delivered = true;
{
@@ -1095,7 +1321,9 @@ namespace tether::bluetooth {
std::lock_guard<std::mutex> lock(mutex);
pending_anc.reset();
pending_ownership.reset();
+ pending_take_over = false;
state.peer_audio = false;
+ state.peer_call = false;
}
::close(fd);
}
@@ -1126,6 +1354,7 @@ namespace tether::bluetooth {
state.peer_taking_over = false;
state.peer_active = false;
state.peer_audio = false;
+ state.peer_call = false;
state.local_audio = false;
state.owns.reset();
}
@@ -1147,6 +1376,7 @@ namespace tether::bluetooth {
state.peer_taking_over = false;
state.peer_active = false;
state.peer_audio = false;
+ state.peer_call = false;
state.local_audio = false;
state.owns.reset();
}
@@ -1175,8 +1405,10 @@ namespace tether::bluetooth {
}
};
- AirPodsWatcher::AirPodsWatcher(std::function<void(const AirPodsState&)> on_change)
+ AirPodsWatcher::AirPodsWatcher(std::function<void(const AirPodsState&)> on_change,
+ std::function<void(StemPress)> on_stem_press)
: impl_(std::make_unique<Impl>(std::move(on_change))) {
+ impl_->on_stem_press = std::move(on_stem_press);
impl_->wake_fd = ::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (impl_->wake_fd < 0) {
debug::log(WARN, "airpods: eventfd failed: {}", std::strerror(errno));
@@ -1229,6 +1461,25 @@ namespace tether::bluetooth {
impl_->wake();
}
+ void AirPodsWatcher::take_over() {
+ {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ impl_->pending_take_over = true;
+ impl_->yielded = false;
+ }
+ impl_->wake();
+ }
+
+ void AirPodsWatcher::set_streaming(bool streaming) {
+ {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ if (impl_->streaming == streaming)
+ return;
+ impl_->streaming = streaming;
+ }
+ impl_->wake();
+ }
+
void AirPodsWatcher::set_anc(AncMode mode) {
{
std::lock_guard<std::mutex> lock(impl_->mutex);
diff --git a/src/core/src/mpris.cpp b/src/core/src/mpris.cpp
index f3f26a6..6dc3652 100644
--- a/src/core/src/mpris.cpp
+++ b/src/core/src/mpris.cpp
@@ -2,8 +2,10 @@
#include <tether/log.hpp>
+#include <algorithm>
#include <gio/gio.h>
#include <mutex>
+#include <thread>
namespace tether {
@@ -74,6 +76,46 @@ namespace tether {
struct MediaControl::Impl {
mutable std::mutex mutex;
std::vector<std::string> paused;
+ // what the last toggle paused
+ std::vector<std::string> toggled;
+
+ std::function<void(const std::string&, bool)> on_change;
+ GMainContext* context = nullptr;
+ GMainLoop* loop = nullptr;
+ std::thread watcher;
+
+ ~Impl() {
+ if (watcher.joinable()) {
+ g_main_context_invoke(
+ context,
+ [](gpointer data) {
+ g_main_loop_quit(static_cast<GMainLoop*>(data));
+ return G_SOURCE_REMOVE;
+ },
+ loop);
+ watcher.join();
+ }
+ if (loop)
+ g_main_loop_unref(loop);
+ if (context)
+ g_main_context_unref(context);
+ }
+
+ static void on_properties_changed(GDBusConnection*,
+ const char* sender,
+ const char*,
+ const char*,
+ const char*,
+ GVariant* parameters,
+ gpointer data) {
+ const char* iface = nullptr;
+ GVariant* changed = nullptr;
+ g_variant_get(parameters, "(&s@a{sv}@as)", &iface, &changed, nullptr);
+ const char* status = nullptr;
+ if (g_strcmp0(iface, PLAYER_IFACE) == 0 && g_variant_lookup(changed, "PlaybackStatus", "&s", &status))
+ static_cast<Impl*>(data)->on_change(sender, g_strcmp0(status, "Playing") == 0);
+ g_variant_unref(changed);
+ }
// Resolved on first use: the daemon starts before the session bus is necessarily interesting.
GDBusConnection* bus() const {
@@ -183,6 +225,75 @@ namespace tether {
return resumed;
}
+ size_t MediaControl::toggle() {
+ GDBusConnection* bus = impl_->bus();
+ if (!bus)
+ return 0;
+
+ const auto now = playing();
+ if (!now.empty()) {
+ std::vector<std::string> held;
+ for (const auto& name : now)
+ if (call_player(bus, name, "Pause"))
+ held.push_back(name);
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ impl_->toggled = held;
+ return held.size();
+ }
+ if (holding())
+ return resume();
+
+ std::vector<std::string> targets;
+ {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ targets.swap(impl_->toggled);
+ }
+ const auto players = impl_->players();
+ std::erase_if(targets, [&](const std::string& name) {
+ return std::find(players.begin(), players.end(), name) == players.end();
+ });
+ if (targets.empty()) {
+ for (const auto& name : players) {
+ if (playback_status(bus, name) == "Paused") {
+ targets.push_back(name);
+ break;
+ }
+ }
+ }
+
+ size_t played = 0;
+ for (const auto& name : targets)
+ if (call_player(bus, name, "Play"))
+ ++played;
+ return played;
+ }
+
+ void MediaControl::watch(std::function<void(const std::string& player, bool playing)> on_change) {
+ GDBusConnection* bus = impl_->bus();
+ if (!bus || impl_->watcher.joinable())
+ return;
+ impl_->on_change = std::move(on_change);
+ impl_->context = g_main_context_new();
+ impl_->loop = g_main_loop_new(impl_->context, FALSE);
+ impl_->watcher = std::thread([impl = impl_.get(), bus] {
+ // Signals are delivered on the context that is thread-default where they were subscribed.
+ g_main_context_push_thread_default(impl->context);
+ const guint id = g_dbus_connection_signal_subscribe(bus,
+ nullptr,
+ "org.freedesktop.DBus.Properties",
+ "PropertiesChanged",
+ MPRIS_PATH,
+ PLAYER_IFACE,
+ G_DBUS_SIGNAL_FLAGS_NONE,
+ &Impl::on_properties_changed,
+ impl,
+ nullptr);
+ g_main_loop_run(impl->loop);
+ g_dbus_connection_signal_unsubscribe(bus, id);
+ g_main_context_pop_thread_default(impl->context);
+ });
+ }
+
bool MediaControl::holding() const {
std::lock_guard<std::mutex> lock(impl_->mutex);
return !impl_->paused.empty();
diff --git a/src/daemon/main.cpp b/src/daemon/main.cpp
index 0b565be..74b3021 100644
--- a/src/daemon/main.cpp
+++ b/src/daemon/main.cpp
@@ -54,8 +54,6 @@ static void redirect_output_to_log() {
// How long to let the phone finish with the buds before reclaiming them.
constexpr int HANDOFF_SETTLE_SECONDS = 2;
constexpr int HANDOFF_RECLAIM_ATTEMPTS = 3;
-// The phone goes quiet mid-call, so a peer that let go is checked again after this before the buds are taken back.
-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.
@@ -262,7 +260,7 @@ int main(int argc, char** argv) {
// Pick the controller before the first capability, a second adapter never comes up bound to the wrong one.
bluez.set_preferred_adapter(bt_config.adapter);
- // Handing the buds to the iPhone for a call and taking them back after.
+ // Handing the buds to the iPhone and taking them back after.
struct Handoff {
mutable std::mutex mutex;
std::string released;
@@ -270,8 +268,6 @@ int main(int argc, char** argv) {
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);
@@ -284,83 +280,16 @@ 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};
- // 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.
+ // Apple's own handoff: ownership moves over AAP with the link left up, driven by what the other
+ // hosts report through the buds. Runs on the AirPods worker, the MPRIS watcher 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, &connections, &run_ownership](const tether::bluetooth::AirPodsState& state) {
- const auto config = tether::bluetooth::load_config();
- const bool busy_now = phone_busy(state);
-
- std::string target;
- auto action = tether::bluetooth::HandoffAction::None;
- {
- std::lock_guard<std::mutex> lock(handoff->mutex);
- if (handoff->busy || !tether::bluetooth::g_airpods)
- return;
- 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 (action == tether::bluetooth::HandoffAction::Release) {
- 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);
- 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,
- "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;
- }
-
- std::thread([handoff, phone_busy, &connections, &run_ownership] {
- bool reclaimed = false;
- for (int attempt = 0; attempt < HANDOFF_RECLAIM_ATTEMPTS && !reclaimed; ++attempt) {
- if (attempt > 0 || !connections.calls_available())
- std::this_thread::sleep_for(std::chrono::seconds(HANDOFF_GUARD_SECONDS));
- if (!tether::bluetooth::g_airpods)
- break;
- if (phone_busy(tether::bluetooth::g_airpods->state()))
- continue;
- tether::bluetooth::g_airpods->set_ownership(true);
- reclaimed = true;
- }
+ // Takes the buds back on its own thread; the caller has set `busy`. `for_play` is a player that
+ // just started here, which the caller has paused: it takes the buds over from whoever holds them
+ // and resumes once the sink is back.
+ const auto reclaim = [handoff, &run_ownership](bool for_play) {
+ std::thread([handoff, for_play, &run_ownership] {
std::string address;
std::string profile;
std::string volume;
@@ -373,40 +302,37 @@ int main(int argc, char** argv) {
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) {
+ auto* airpods = tether::bluetooth::g_airpods;
+ const bool reclaimed = airpods && (for_play || !airpods->state().peer_busy());
+ if (reclaimed && for_play)
+ airpods->take_over();
+ else if (reclaimed)
+ airpods->set_ownership(true);
+
+ // Buds given up without taking the card down only need the claim.
+ if (reclaimed && !address.empty()) {
+ if (profile.empty())
+ profile = tether::audio::release_bluez_card(address);
+ bool sink_back = true;
+ if (!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 (sink_back && ours)
+ sink_back = tether::audio::restore_default_sink(address, SINK_RETURN_TIMEOUT_MS);
+ if (sink_back && !profile.empty())
+ std::this_thread::sleep_for(std::chrono::seconds(SINK_SETTLE_SECONDS));
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();
- }
debug::log(sink_back ? INFO : WARN,
- sink_back ? "airpods: took the buds back from the iPhone"
+ sink_back ? "airpods: took the buds back"
: "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");
}
+ if (!reclaimed)
+ debug::log(INFO, "airpods: the other host is playing through the buds again; leaving them to it");
+ else if (tether::g_media)
+ tether::g_media->resume();
{
std::lock_guard<std::mutex> lock(handoff->mutex);
@@ -424,6 +350,94 @@ int main(int argc, char** argv) {
}).detach();
};
+ run_ownership = [handoff, reclaim, &run_ownership](const tether::bluetooth::AirPodsState& state) {
+ const auto config = tether::bluetooth::load_config();
+
+ std::string target;
+ auto action = tether::bluetooth::HandoffAction::None;
+ {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ if (handoff->busy || !tether::bluetooth::g_airpods)
+ return;
+ const bool released_now = !handoff->released.empty();
+ target = released_now ? handoff->released : state.address;
+ if (target.empty())
+ return;
+ action = tether::bluetooth::ownership_action(
+ state.peer_busy(), 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 (action == tether::bluetooth::HandoffAction::Reclaim) {
+ reclaim(false);
+ return;
+ }
+
+ // Pause first: a card switched off under a playing stream sends it to the speakers.
+ 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 bool held = streaming || paused > 0 || (tether::g_media && tether::g_media->holding());
+ if (held)
+ tether::audio::sink_quiet(sink, SINK_QUIET_TIMEOUT_MS);
+ const std::string profile = held ? tether::audio::release_bluez_card(target) : std::string{};
+ if (tether::bluetooth::g_airpods)
+ tether::bluetooth::g_airpods->set_ownership(false);
+ debug::log(INFO,
+ "airpods: gave the buds to the other host (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();
+ };
+
+ // A player starting here takes the buds, the way playing on a Mac does. With the card down the
+ // player is paused at once, so nothing reaches the speakers, and the reclaim resumes it.
+ const auto on_local_play = [handoff, reclaim, &native_handoff](const std::string& player, bool playing) {
+ auto* airpods = tether::bluetooth::g_airpods;
+ if (!airpods || !tether::g_media)
+ return;
+ airpods->set_streaming(!tether::g_media->playing().empty());
+ const auto config = tether::bluetooth::load_config();
+ if (!playing || !native_handoff.load() || !config.airpods_enabled || !config.airpods_handoff)
+ return;
+ const auto state = airpods->state();
+ if (state.status != tether::bluetooth::AirPodsStatus::Live)
+ return;
+
+ bool released = false;
+ {
+ std::lock_guard<std::mutex> lock(handoff->mutex);
+ if (!tether::bluetooth::takes_over_for_play(state.owns, state.peer_call, handoff->busy))
+ return;
+ handoff->busy = true;
+ released = !handoff->released.empty();
+ }
+ debug::log(INFO, "airpods: {} started playing here, taking the buds", player);
+ // The players the release paused stay paused: the user already chose what plays.
+ if (released) {
+ tether::g_media->forget();
+ tether::g_media->pause();
+ }
+ reclaim(true);
+ };
+
// AirPods battery arrives on its own L2CAP channel, not through BlueZ.
tether::MediaControl media;
@@ -452,7 +466,7 @@ 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
+ // Losing the owner bit is the first sign another host 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())
@@ -466,19 +480,16 @@ int main(int argc, char** argv) {
prev.ear = state.ear;
tether::broadcast_local_event(tether::bluetooth::to_json(state).dump());
+ },
+ [&media](tether::bluetooth::StemPress press) {
+ if (press != tether::bluetooth::StemPress::Single)
+ return;
+ debug::log(INFO, "airpods: stem press, toggled {} player(s)", media.toggle());
});
- 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());
+ const auto run_handoff = [&bluez, &media, handoff, &native_handoff](const nlohmann::json& calls) {
+ // Ownership handoff follows the phone's own smart-routing reports instead.
+ if (native_handoff.load())
return;
- }
const auto config = tether::bluetooth::load_config();
const bool active = tether::bluetooth::call_wants_audio(calls);
@@ -588,13 +599,12 @@ 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, &connections, &native_handoff](int) {
+ media.watch(on_local_play);
+ loop.addFd(bluez.event_fd(), [&bluez, &follow_airpods](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 47b38cc..6ee228f 100644
--- a/test/test_airpods.cpp
+++ b/test/test_airpods.cpp
@@ -145,6 +145,21 @@ TEST(AirPods, RejectsMalformedEarDetection) {
EXPECT_FALSE(parse_ear(nullptr, 0).has_value());
}
+TEST(AirPods, ParsesStemPresses) {
+ const auto press = [](std::initializer_list<uint8_t> bytes) {
+ std::vector<uint8_t> v(bytes);
+ return parse_stem_press(v.data(), v.size());
+ };
+ EXPECT_EQ(press({0x04, 0x00, 0x04, 0x00, 0x19, 0x00, 0x05, 0x01}), StemPress::Single);
+ EXPECT_EQ(press({0x04, 0x00, 0x04, 0x00, 0x19, 0x00, 0x06, 0x02}), StemPress::Double);
+ EXPECT_EQ(press({0x04, 0x00, 0x04, 0x00, 0x19, 0x00, 0x08, 0x01}), StemPress::Long);
+ EXPECT_FALSE(press({0x04, 0x00, 0x04, 0x00, 0x19, 0x00, 0x09, 0x01}).has_value());
+ EXPECT_FALSE(press({0x04, 0x00, 0x04, 0x00, 0x19, 0x00, 0x05}).has_value());
+ // Ear detection is the same length.
+ EXPECT_FALSE(press({0x04, 0x00, 0x04, 0x00, 0x06, 0x00, 0x05, 0x01}).has_value());
+ EXPECT_FALSE(parse_stem_press(nullptr, 0).has_value());
+}
+
TEST(AirPods, PauseModeNeverDoesNothing) {
EXPECT_EQ(ear_media_action(WORN, BOTH_OUT, PauseMode::Never, false), MediaAction::None);
EXPECT_EQ(ear_media_action(BOTH_OUT, WORN, PauseMode::Never, true), MediaAction::None);
@@ -195,9 +210,8 @@ TEST(AirPods, TreatsTheBatteryStatusAsABitmask) {
TEST(AirPods, ParsesTheConnectedDeviceList) {
// 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,
- 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03,
- 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x15};
+ const std::vector<uint8_t> packet = {0x04, 0x00, 0x04, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00,
+ 0x00, 0x02, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x15};
auto peers = parse_connected_devices(packet.data(), packet.size());
ASSERT_TRUE(peers.has_value());
ASSERT_EQ(peers->size(), 2u);
@@ -264,37 +278,151 @@ TEST(AirPods, ReadsOwnershipFromTheOwnerBit) {
}
// The registration packets the buds expect for every other host, ported from a working
-// implementation. The layout is fixed: opcode, the target address least-significant byte first,
-// then ASCII keys with this machine's address in the middle.
+// implementation: opcode, the target address least-significant byte first, the body length, then
+// an OPACK dictionary with this machine's address in it.
TEST(AirPods, BuildsTheHostRegistrationPackets) {
const std::string self = "02:00:00:00:00:02";
const auto add = tipi_add_device(self, "02:00:00:00:00:01");
- ASSERT_EQ(add.size(), 96u);
- EXPECT_EQ(std::vector<uint8_t>(add.begin(), add.begin() + 6),
- (std::vector<uint8_t>{0x04, 0x00, 0x04, 0x00, 0x10, 0x00}));
- EXPECT_EQ(std::vector<uint8_t>(add.begin() + 6, add.begin() + 12),
- (std::vector<uint8_t>{0x01, 0x00, 0x00, 0x00, 0x00, 0x02}));
- // Body offsets counted from the end of the prefix.
- EXPECT_EQ(std::string(add.begin() + 6 + 11, add.begin() + 6 + 19), "idleTime");
- EXPECT_EQ(std::string(add.begin() + 6 + 40, add.begin() + 6 + 57), self);
- EXPECT_EQ(std::string(add.begin() + 6 + 65, add.begin() + 6 + 72), "Android");
- EXPECT_EQ(add.back(), 0x0e);
-
- const auto media = tipi_media_info(self, "02:00:00:00:00:01");
- ASSERT_EQ(media.size(), 122u);
- EXPECT_EQ(std::string(media.begin() + 6 + 11, media.begin() + 6 + 21), "playingApp");
- EXPECT_EQ(std::string(media.begin() + 6 + 25, media.begin() + 6 + 43), "hostStreamingState");
- EXPECT_EQ(std::string(media.begin() + 6 + 57, media.begin() + 6 + 74), self);
- EXPECT_EQ(media.back(), 0x64);
+ static constexpr char ADD_HEAD[] = "\x04\x00\x04\x00\x10\x00\x01\x00\x00\x00\x00\x02"
+ "\x52\x00\x01\xe5\x48idleTime\x08\x47newTipi\x01\x49"
+ "btAddress\x51";
+ std::string expected_add(ADD_HEAD, sizeof(ADD_HEAD) - 1);
+ expected_add += self + "\x46"
+ "btName\x47"
+ "Android\x50nearbyAudioScore\x0e";
+ EXPECT_EQ(std::string(add.begin(), add.end()), expected_add);
+
+ const auto media = smart_routing_media_info(self, "02:00:00:00:00:01", false);
+ static constexpr char MEDIA_HEAD[] = "\x04\x00\x04\x00\x10\x00\x01\x00\x00\x00\x00\x02"
+ "\x6c\x00\x01\xe5\x4a"
+ "playingApp\x42NA\x52hostStreamingState\x42NO\x49"
+ "btAddress\x51";
+ std::string expected_media(MEDIA_HEAD, sizeof(MEDIA_HEAD) - 1);
+ expected_media += self + "\x46"
+ "btName\x47"
+ "Android\x58otherDeviceAudioCategory\x30\x64";
+ EXPECT_EQ(std::string(media.begin(), media.end()), expected_media);
// An address that will not parse is no packet at all.
EXPECT_TRUE(tipi_add_device(self, "nonsense").empty());
- EXPECT_TRUE(tipi_media_info("", "02:00:00:00:00:01").empty());
+ EXPECT_TRUE(smart_routing_media_info("", "02:00:00:00:00:01", true).empty());
}
-// Handoff yields to a phone that owns the buds and is playing through them. Ownership alone is a
-// phone that finished its call and kept the bit; audio alone is a host that owns nothing.
-TEST(AirPods, YieldsOnlyToAnOwnerWithAudio) {
+namespace {
+ std::optional<SmartRoutingMessage> routing(const std::vector<uint8_t>& bytes) {
+ return parse_smart_routing(bytes.data(), bytes.size());
+ }
+
+ // What this machine sends, read back as if another host had sent it.
+ std::optional<SmartRoutingMessage> echo(std::vector<uint8_t> sent) {
+ sent[4] = 0x11;
+ return routing(sent);
+ }
+
+ // Captured 2026-09-13 from an iPhone through AirPods Pro 3: a call starting, then over.
+ const std::vector<uint8_t> IPHONE_CALL = {
+ 0x04, 0x00, 0x04, 0x00, 0x11, 0x00, 0xf7, 0x6a, 0x30, 0xc8, 0x57, 0x60, 0x87, 0x00, 0x01, 0xe5, 0x4a,
+ 0x70, 0x6c, 0x61, 0x79, 0x69, 0x6e, 0x67, 0x41, 0x70, 0x70, 0x5c, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70,
+ 0x70, 0x6c, 0x65, 0x2e, 0x54, 0x65, 0x6c, 0x65, 0x70, 0x68, 0x6f, 0x6e, 0x79, 0x55, 0x74, 0x69, 0x6c,
+ 0x69, 0x74, 0x69, 0x65, 0x73, 0x52, 0x68, 0x6f, 0x73, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69,
+ 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x65, 0x43, 0x59, 0x45, 0x53, 0x49, 0x62, 0x74, 0x41, 0x64, 0x64,
+ 0x72, 0x65, 0x73, 0x73, 0x51, 0x36, 0x30, 0x3a, 0x35, 0x37, 0x3a, 0x43, 0x38, 0x3a, 0x33, 0x30, 0x3a,
+ 0x36, 0x41, 0x3a, 0x46, 0x37, 0x46, 0x62, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x46, 0x69, 0x50, 0x68, 0x6f,
+ 0x6e, 0x65, 0x58, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x41, 0x75, 0x64,
+ 0x69, 0x6f, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x31, 0xf5, 0x01};
+ const std::vector<uint8_t> IPHONE_IDLE = {
+ 0x04, 0x00, 0x04, 0x00, 0x11, 0x00, 0xf7, 0x6a, 0x30, 0xc8, 0x57, 0x60, 0x70, 0x00, 0x01, 0xe5, 0x4a, 0x70,
+ 0x6c, 0x61, 0x79, 0x69, 0x6e, 0x67, 0x41, 0x70, 0x70, 0x47, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x52,
+ 0x68, 0x6f, 0x73, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x65,
+ 0x42, 0x4e, 0x4f, 0x49, 0x62, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x51, 0x36, 0x30, 0x3a, 0x35,
+ 0x37, 0x3a, 0x43, 0x38, 0x3a, 0x33, 0x30, 0x3a, 0x36, 0x41, 0x3a, 0x46, 0x37, 0x46, 0x62, 0x74, 0x4e, 0x61,
+ 0x6d, 0x65, 0x46, 0x69, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x58, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x44, 0x65, 0x76,
+ 0x69, 0x63, 0x65, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x43, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x30, 0x64};
+ // The iPhone routed to the buds from Control Center.
+ const std::vector<uint8_t> IPHONE_YIELD_REQUEST = {
+ 0x04, 0x00, 0x04, 0x00, 0x11, 0x00, 0xf7, 0x6a, 0x30, 0xc8, 0x57, 0x60, 0x36, 0x00, 0x01, 0xe2, 0x5f,
+ 0x61, 0x75, 0x64, 0x69, 0x6f, 0x52, 0x6f, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x65, 0x74, 0x4f, 0x77,
+ 0x6e, 0x65, 0x72, 0x73, 0x68, 0x69, 0x70, 0x54, 0x6f, 0x46, 0x61, 0x6c, 0x73, 0x65, 0x01, 0x46, 0x72,
+ 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x4b, 0x4d, 0x61, 0x6e, 0x75, 0x61, 0x6c, 0x52, 0x6f, 0x75, 0x74, 0x65};
+} // namespace
+
+TEST(AirPods, ReadsTheIPhonesSmartRoutingReports) {
+ const auto call = routing(IPHONE_CALL);
+ ASSERT_TRUE(call.has_value());
+ EXPECT_EQ(call->sender, "60:57:C8:30:6A:F7");
+ EXPECT_EQ(call->app, "com.apple.TelephonyUtilities");
+ EXPECT_EQ(call->category, AUDIO_CATEGORY_CALL);
+ EXPECT_TRUE(call->playing());
+ EXPECT_TRUE(call->call());
+
+ const auto idle = routing(IPHONE_IDLE);
+ ASSERT_TRUE(idle.has_value());
+ EXPECT_EQ(idle->streaming, false);
+ EXPECT_EQ(idle->category, AUDIO_CATEGORY_NONE);
+ EXPECT_FALSE(idle->playing());
+
+ const auto yield = routing(IPHONE_YIELD_REQUEST);
+ ASSERT_TRUE(yield.has_value());
+ EXPECT_TRUE(yield->set_ownership_to_false);
+ EXPECT_FALSE(yield->streaming.has_value());
+
+ // A route with nothing on it says YES with category 100.
+ SmartRoutingMessage route;
+ route.streaming = true;
+ route.category = AUDIO_CATEGORY_NONE;
+ EXPECT_FALSE(route.playing());
+
+ auto truncated = IPHONE_YIELD_REQUEST;
+ truncated.pop_back();
+ EXPECT_FALSE(routing(truncated).has_value());
+ // A dictionary of one entry with nothing in it.
+ EXPECT_FALSE(
+ routing({0x04, 0x00, 0x04, 0x00, 0x11, 0x00, 0xf7, 0x6a, 0x30, 0xc8, 0x57, 0x60, 0x02, 0x00, 0x01, 0xe1})
+ .has_value());
+ EXPECT_FALSE(parse_smart_routing(nullptr, 0).has_value());
+}
+
+TEST(AirPods, BuildsTheTakeOverMessages) {
+ const std::string self = "02:00:00:00:00:02";
+ const auto playing = echo(smart_routing_media_info(self, "02:00:00:00:00:01", true));
+ ASSERT_TRUE(playing.has_value());
+ EXPECT_EQ(playing->sender, "02:00:00:00:00:01");
+ EXPECT_TRUE(playing->playing());
+ EXPECT_EQ(playing->category, AUDIO_CATEGORY_MEDIA);
+
+ const auto hijack = echo(smart_routing_hijack("02:00:00:00:00:01"));
+ ASSERT_TRUE(hijack.has_value());
+ EXPECT_TRUE(hijack->set_ownership_to_false);
+
+ // LibrePods' capture of the same request refers back to 301 for remotescore (0xA5).
+ static constexpr char BODY[] = "\x01\xe5\x4alocalscore\x30\x64\x46reason\x48Hijackv2\x51"
+ "audioRoutingScore\x31\x2d\x01\x5f"
+ "audioRoutingSetOwnershipToFalse\x01\x4bremotescore\xa5";
+ const std::string body(BODY, sizeof(BODY) - 1);
+ std::vector<uint8_t> referenced = {0x04,
+ 0x00,
+ 0x04,
+ 0x00,
+ 0x11,
+ 0x00,
+ 0x01,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x02,
+ static_cast<uint8_t>(body.size()),
+ 0x00};
+ referenced.insert(referenced.end(), body.begin(), body.end());
+ const auto decoded = routing(referenced);
+ ASSERT_TRUE(decoded.has_value());
+ EXPECT_TRUE(decoded->set_ownership_to_false);
+}
+
+// Handoff yields to a phone that owns the buds and is playing through them, or to a call, which
+// always takes them. Ownership alone is a phone that finished and kept the bit; media alone is a
+// phone playing on its own speaker.
+TEST(AirPods, YieldsToAnOwnerWithAudioOrACall) {
AirPodsState state;
state.peer_active = true;
EXPECT_FALSE(state.peer_busy());
@@ -302,6 +430,8 @@ TEST(AirPods, YieldsOnlyToAnOwnerWithAudio) {
EXPECT_TRUE(state.peer_busy());
state.peer_active = false;
EXPECT_FALSE(state.peer_busy());
+ state.peer_call = true;
+ EXPECT_TRUE(state.peer_busy());
}
// This machine's own entry rises with its own ownership and is never a peer.
@@ -334,22 +464,6 @@ TEST(AirPods, ParsesTheAudioSource) {
EXPECT_FALSE(parse_audio_source(packet.data(), packet.size() - 1).has_value());
}
-// 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 = "02:00:00:00:00:02";
- 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({"02:00:00:00:00:01", AudioSource::Media}, local, false, false));
- EXPECT_FALSE(claims_for_playback({local, AudioSource::None}, local, false, false));
- 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) {
@@ -375,6 +489,15 @@ TEST(AirPods, OwnershipIsOffUnlessEnabledButStillGivesTheBudsBack) {
EXPECT_EQ(ownership_action(false, true, false), HandoffAction::Reclaim);
}
+TEST(AirPods, PlayingHereTakesTheBudsUnlessOnACall) {
+ EXPECT_TRUE(takes_over_for_play(false, false, false));
+ // No verdict yet counts as not owning.
+ EXPECT_TRUE(takes_over_for_play(std::nullopt, false, false));
+ EXPECT_FALSE(takes_over_for_play(true, false, false));
+ EXPECT_FALSE(takes_over_for_play(false, true, false));
+ EXPECT_FALSE(takes_over_for_play(false, false, true));
+}
+
TEST(AirPods, HandoffIsOffUnlessEnabled) { EXPECT_EQ(handoff_action(true, true, false, false), HandoffAction::None); }
// Turning the setting off while the phone has the buds must not strand them there.