Skip to content

android: fix the ~35 s disconnect and HFP loop on AirPods firmware 9A348+ with the Apple vendor ID, and make Mac handoff work both ways - #949

Open
mteam88 wants to merge 7 commits into
librepods-org:mainfrom
mteam88:fix-782-att-hfp-handoff
Open

mteam88 wants to merge 7 commits into
librepods-org:mainfrom
mteam88:fix-782-att-hfp-handoff

Conversation

@mteam88

@mteam88 mteam88 commented Nov 30, 2026 •

Copy link
Copy Markdown

Fixes #782.

Tested on AirPods Pro 3 (A3064, firmware 9B47), Pixel 10 Pro on Android 17 (KernelSU-Next, Vector/LSPosed), with a Mac on the same iCloud account connected to the AirPods at the same time. Everything below comes from an HCI snoop on the phone and from bluetoothd / audioaccessoryd logs on the Mac, not from guessing.

1. HFP reconnect loop (independent of the vendor ID toggle)

AOSP answers the AirPods' AT+XAPL with +XAPL=iPhone,2. Firmware 9A348+ replies with AT+IPHONEACCEV=1,1,<battery> without a trailing CR. AOSP's AT parser waits for the CR forever and never answers OK, so the AirPods drop the HFP RFCOMM channel 10 s later, reconnect, and repeat. The module now hooks HeadsetNativeInterface.atResponseString in the Bluetooth process and rewrites the response to +XAPL=iPhone,0, so the AirPods never send the battery report over HFP (battery still arrives over AACP). There is a settings toggle for it, on by default.

Commit: abece71 android: fix HFP reconnect loop on AirPods firmware 9A348+

2. The disconnect ~35–40 s after connecting with "Act as an Apple device" on

With the Apple vendor ID, the AirPods expect to be the side that opens the ATT bearer (L2CAP PSM 0x1F over BR/EDR). What they do depends on what the host did with that PSM:

Host behaviour Result
Opens ATT and keeps it open (current upstream) AirPods drop the ACL ~35 s after the channel opened, reason 0x13. Traffic on the channel makes no difference; reading every 10 s does not help.
Opens ATT, reads, closes 25–40 s later the AirPods send their own ConnReq psm=0x001f. Android has no listener, answers result=2 (PSM not supported). They retry twice, 5 s apart, then drop the ACL.
Listens on PSM 0x1F and accepts their channel Link stays up. They send nothing on the channel and answer our reads on it.
Never touches ATT They never ask. Link stays up.

The refused case, from the snoop:

22:19:34.525 TX L2CAP ConnReq psm=0x001f scid=0x0040          <- our own short ATT session
22:19:34.721 RX L2CAP ConnRsp dcid=0x6b11 scid=0x0040 result=0
22:20:18.323 RX L2CAP ConnReq psm=0x001f scid=0x6c11          <- AirPods ask
22:20:18.324 TX L2CAP ConnRsp dcid=0x0000 scid=0x6c11 result=2
22:20:22.886 RX L2CAP ConnReq psm=0x001f scid=0x6d11
22:20:22.888 TX L2CAP ConnRsp dcid=0x0000 scid=0x6d11 result=2
22:20:28.645 RX L2CAP ConnReq psm=0x001f scid=0x6e11
22:20:28.646 TX L2CAP ConnRsp dcid=0x0000 scid=0x6e11 result=2
22:20:33.038 EVT DisconnectionComplete reason=0x13

And accepted:

22:39:06.625 TX L2CAP ConnReq psm=0x001f scid=0x007f          <- our initial reads
22:39:46.945 RX L2CAP ConnReq psm=0x001f scid=0x9c11
22:39:46.948 TX L2CAP ConnRsp dcid=0x0041 scid=0x9c11 result=0   (link stays up)

The change: ATTManagerv2 opens its own bearer only for as long as a request needs it, then listens on PSM 0x1F and adopts the channel the AirPods open, using that for everything afterwards.

Two details that cost time:

  • Closing one of the app's own L2CAP sockets on a PSM unregisters that PSM in the Android stack, listener included. The listener has to be created after the app's own socket is closed.
  • BluetoothAdapter#listenUsingInsecureL2capOn(int) is on the hidden API blocklist, hence the dependency on org.lsposed.hiddenapibypass.

Commits: b1e7657 (on-demand bearer; its conclusion was incomplete), 848cdfe android: let the AirPods open the ATT bearer.

3. Do not claim ownership just because we connected

The connect sequence starts and stops head tracking once, and startHeadTracking() sets OWNS_CONNECTION=1 first. With a second host connected this takes the AirPods away from it every time the phone connects, with nothing playing on the phone (macOS logs Received Ownership state (control cmd 0x06) as not owned). Head tracking started from the connect sequence no longer takes over. e99811c.

4. Handoff with a second Apple device

With the link stable, audio moved to the phone once and then stuck. Four bugs plus a debounce problem, all in fe9c9e8:

  • The media information relay message is not valid OPACK. "YES" is written with the length byte of "NO" (0x42), and btName has no length byte. macOS logs Unable to decode relay message with -6735 kUnsupportedErr for every one and keeps the last state it understood, which after a takeover is the 301 from the hijack request. It then refuses to take the AirPods back for anything but media (Allow hijack=no, Local audio category=201, Remote audio category=301 ... Deny reason=Rejected) and falls back to its speakers. The message is now encoded properly, using the keys macOS itself sends (playingApp, hostStreamingState, btAddress, btName, otherDeviceAudioCategory).
  • Nothing reports that playback stopped. The category was always 301. macOS uses 100 for idle, 201 for system sounds and 301 for media. The phone now reports 100 when idle, a moment after each playback callback (the callback that follows a pause still sees isMusicActive == true) and once after connecting.
  • takeOver() returns early when OWNS_CONNECTION == 0 (added in 481d5f1). That is the value the AirPods report once the other device has taken them, so the phone could take them once and never again.
  • setControlCommandStatusValue() keeps stale values. It removes the existing entry only when the new value is equal, so a changed value is appended behind the old one and getControlCommandStatus() (first match) keeps returning the old one. This affects every control command, not only ownership.

Also in that commit: the playback debounce keeps the first callback of a burst and drops the rest. Starting playback produces a burst and the first callback usually predates the player starting, so takeovers were missed at random. The state is now re-evaluated once the burst is over.

Mac side after the fix:

[Hijackv2] Received audio category 301 from tipi device <phone> through relay message
Setting OtherTipiAudioCategory for Wx <airpods> 301 -> 100
[Hijackv2] Allow hijack=yes, Local audio category=201, Remote audio category=100

5. Disconnected takeover deadlock, TiPi background auto-connect, and re-takeover after Mac hijack

24 h of daily use turned up three more issues in the handoff/auto-connect paths:

  • Disconnected takeOver("music") deadlocked pausedWhileTakingOver without BLUETOOTH_PRIVILEGED (2bc56d7). When the Mac connected first and the phone was still disconnected, starting playback entered the disconnected takeover path, paused media, and set pausedWhileTakingOver = true — but connectAudio() only resumed playback and cleared pausedWhileTakingOver inside the BLUETOOTH_PRIVILEGED finally block, and disconnected takeOver() never sent OWNS_CONNECTION = 1 or Hijackv2 once connected. pausedWhileTakingOver stayed true permanently, suppressing every later takeover and letting brief Mac score-201 sounds pause phone music. Fixed by running disconnected takeover asynchronously, claiming ownership + Hijackv2 once connected, always clearing pausedWhileTakingOver (with a 10 s watchdog), and clearing stale iPausedTheMedia on manual resume.
  • No background TiPi join when the Mac connects first (2bc56d7). Once a Mac connects, byte 10 of the AirPods BLE ad moves from 0x00 (Disconnected) to 0x04 (Idle, 1 host), and BLEManager also misparsed the 2-host bitmask (0x08–0x0B). BLEManager now decodes sourceCount + audio state (0x04–0x0B) and AirPods Pro 3 (0x2720), and AirPodsService silently joins once per in-ear session when vendor_id_hook is enabled and sourceCount < 2 without stealing ownership. Also guards concurrent connectToSocket() races, stops connectAudio() from leaking profile proxies / spamming A2dp.connect(), only fires onOwnershipChangeReceived on real transitions, and uses sendPause(force = true) on real ownership loss.
  • Stale lastKnownIsMusicActive blocked re-takeover after a Mac hijack (d38f220). When the Mac hijacked, sendPause(force = true) ran while Android's isMusicActive was still true, so the 800 ms self-action window saved lastKnownIsMusicActive = true. When reportStreamingState() ran 1.5 s later and saw isMusicActive == false, it relayed idle (100) to the Mac without resetting lastKnownIsMusicActive = false, causing subsequent Play events to relay 301 but skip takeOver("music"). Fixed by resetting lastKnownIsMusicActive on idle in reportStreamingState(), on onOwnershipLost(), during pausedForOtherDevice drain, and when skipping for recent ownership loss; also treats USAGE_MEDIA with CONTENT_TYPE_SPEECH/CONTENT_TYPE_UNKNOWN as takeover-eligible.

Verified over 24 h on AirPods Pro 3 (9B47), Pixel 10 Pro, and macOS: 5/5 silent TiPi background joins in 3–40 s, 104 min continuous dual-host session, Mac properly rejecting brief score-201 sounds while the phone plays, and clean Mac → phone → Mac → phone round-trips.

Not addressed

  • Self MAC lookup. takeOver("music") is never reached when self_mac_address is empty (MediaController returns early), and the only lookup is su -c settings get secure bluetooth_address, which fails silently when the app has no root grant. Takeover is then disabled with no hint in the UI. The module already runs inside the Bluetooth process and could supply the address.
  • The vendor ID spoof is unconditional in the native hook, whatever the toggle says. The toggle only gates the ATT side.
  • Older firmware. Not tested. If the AirPods never open ATT themselves, ATTManagerv2 falls back to a short session of its own per request, so notifications would not arrive.

…-org#782)

Recent AirPods firmware replies to AOSP's `+XAPL=iPhone,2` with
`AT+IPHONEACCEV=1,1,<battery>` without a trailing CR. AOSP's AT parser waits
for the CR forever, never answers OK, and the AirPods drop the HFP RFCOMM
channel 10 s later, then reconnect, in a loop.

Hook HeadsetNativeInterface.atResponseString in the Bluetooth process and
rewrite the response to `+XAPL=iPhone,0` so the AirPods never send the
battery report over HFP (battery still arrives over AACP). Adds a settings
toggle (default on) next to "Act as an Apple device".
…brepods-org#782)

With "Act as an Apple device" enabled the app opened ATT over BR/EDR
(PSM 0x1F) at connect and kept it for the whole connection. AirPods
firmware 9A348+ ends the ACL link about 35 s after a host opens that
channel and leaves it open (HCI reason 0x13, sometimes 0x08), so the
AirPods disconnected again and again.

Measured on AirPods Pro 3 (A3064, 9B47) with a Mac connected as the
second host:

- toggle on, ATT never opened: link stays up
- ATT opened, three reads, closed after 3 s: link stays up
- ATT held open, idle: dropped 35.3 s after the channel opened
- ATT held open, one read every 10 s: dropped after ~35 s as well
- ten back-to-back ATT sessions of ~10 s each: link stays up

The timer is therefore tied to how long one bearer stays open, not to
traffic on it. ATTManagerv2 now opens the bearer for a request, reuses
it for requests that follow within 3 s, never reuses one older than
10 s, and closes it when idle. The socket is owned by the manager and
is closed on disconnect; previously it was only dropped.

Notifications are now only delivered while the bearer is open.
The connect sequence starts and stops head tracking once, and
startHeadTracking() took over the connection first. With "Act as an
Apple device" enabled that sent OWNS_CONNECTION=1 every time the phone
connected, taking the AirPods away from the other host (macOS logs
"Received Ownership state (control cmd 0x06) as not owned") even though
nothing was playing on the phone.

Head tracking started from the connect sequence no longer takes over.
Starting it for a gesture or from the UI behaves as before.
Follow-up to d0cc1d4, whose conclusion was incomplete. Closing our ATT
bearer quickly does avoid the drop 35 s after it was opened, but HCI
captures show what happens next: 25-40 s after the host-opened bearer
is closed, the AirPods send their own L2CAP connection request for
PSM 0x1F. Android has nothing registered there and answers "PSM not
supported"; the AirPods retry up to three times, 5 s apart, and then
end the ACL link (reason 0x13). So opening ATT on demand only moved
the disconnect to about a minute after the last use.

AirPods firmware 9A348+ evidently wants to be the side that opens the
bearer. Measured on AirPods Pro 3 (A3064, 9B47), Pixel 10 Pro on
Android 17, with a Mac connected as the second host:

- host opens the bearer and keeps it: ACL dropped ~35 s later
- host opens it, closes it, refuses the AirPods' request: ACL dropped
- host opens it, closes it, accepts the AirPods' request: the bearer
  the AirPods opened stays up, answers our reads, and the link is
  stable
- host never opens ATT: the AirPods never ask, link is stable

ATTManagerv2 therefore opens its own bearer only for the duration of
a request, listens on PSM 0x1F in between, and uses the bearer the
AirPods open as soon as there is one. The listener has to be created
after our own socket is closed, because closing an L2CAP socket
unregisters the PSM in the stack together with any listener on it.

BluetoothAdapter#listenUsingInsecureL2capOn(int) is on the hidden API
blocklist, hence the new dependency on LSPosed's HiddenApiBypass.

Requests the AirPods might send on their bearer get a proper "no such
attribute" answer, and CCCD subscriptions are written again whenever a
new bearer comes up.
With the Apple vendor ID on and a Mac sharing the AirPods, audio moved to
the phone once and then stuck. Four things were in the way, found by
reading audioaccessoryd's log on the Mac next to the phone's.

The media information message was not valid OPACK. It was assembled by
hand: "YES" went out with the length byte of "NO", and btName had no
length byte at all. macOS logged "Unable to decode relay message" for
every one of them and kept the last state it had understood, which after
a takeover is the 301 from our hijack request. From then on it refused to
take the AirPods back for anything but media ("Remote Category 301 >
Local Category 201 ... Deny reason=Rejected") and fell back to its
speakers. Encode the message properly, with the keys and values macOS
uses itself, and build the new-device variant from the same code.

Nothing ever said we had stopped playing. The category was always 301,
and the playback callback that follows a pause still sees isMusicActive
true. Report 100 when idle, as macOS does, and look again a moment after
each callback and once after connecting.

takeOver() returned early when OWNS_CONNECTION was 0. That is what the
AirPods report once the other device has taken them, so the phone could
take them the first time and never again.

setControlCommandStatusValue() only dropped the old entry when the new
value was the same, so a changed value was appended behind the stale one
and getControlCommandStatus() kept returning the stale one. Ownership
read as 1 after it had been lost.

Also, the playback debounce kept the first callback of a burst and dropped
the rest. Starting playback is a burst, and the first callback usually
predates the player starting, so takeovers were missed at random.
Re-evaluate once the burst is over.

Verified on AirPods Pro 3 (9B47), Pixel 10 Pro, macOS: phone takes over on
play ("ReceivedOwnershipLost: Hijackv2 localScore 100 remoteHijackScore
301"), Mac sees "Received audio category 301" then "301 -> 100" after
pause and takes them back ("Allow hijack=yes, Local audio category=201,
Remote audio category=100"). Taking over a second time after the Mac took
them back is not yet confirmed on hardware.
…uto-connect

Fix three interacting multipoint bugs caught on AirPods Pro 3 + Mac + Pixel 10 Pro:

1. Disconnected takeover permanently wedged MediaController.pausedWhileTakingOver=true:
   takeOver("music") paused media and set pausedWhileTakingOver=true, then relied on
   connectAudio()'s BLUETOOTH_PRIVILEGED finally block to resume and clear it. Without
   BLUETOOTH_PRIVILEGED, the else branch never cleared pausedWhileTakingOver (and leaked
   profile proxies), and never sent OWNS_CONNECTION=1 / Hijackv2 after connecting. Every
   subsequent play on the phone then skipped takeOver(), leaving macOS thinking it still
   owned the AirPods so any brief Mac sound (score 201) fired AVDTP_Start and paused phone
   music (score 301). Run disconnected takeover asynchronously, claim ownership + send
   Hijackv2 once connected, always clear pausedWhileTakingOver (plus a 10s watchdog),
   and clear stale iPausedTheMedia when the user manually resumes.

2. Missing TiPi auto-connect when another Apple host connects first:
   BLEManager misparsed byte 10 for 2-host advertisements (0x08/0x09) and AirPodsService
   only auto-connected when connectionState == "Disconnected". Decode sourceCount and
   audio state from byte 10, add AirPods Pro 3 (0x2720), and trigger background TiPi
   healing (once per in-ear session, without claiming ownership) when in-ear and
   sourceCount < 2 with vendor_id_hook enabled. Guard connectToSocket() against concurrent
   races and close profile proxies in connectAudio().

3. Spurious ownership-lost on initial connect and ignored pause on real hijack:
   Only invoke onOwnershipChangeReceived when OWNS_CONNECTION actually changes, and use
   sendPause(force = true) when another host genuinely hijacks ownership.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AirPods firmware 9442752 (9A348): constant disconnects — two distinct root causes, with packet-level analysis and a macOS reference trace

1 participant