Repository navigation
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
Conversation
…-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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/audioaccessorydlogs on the Mac, not from guessing.1. HFP reconnect loop (independent of the vendor ID toggle)
AOSP answers the AirPods'
AT+XAPLwith+XAPL=iPhone,2. Firmware 9A348+ replies withAT+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 hooksHeadsetNativeInterface.atResponseStringin 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:
abece71android: 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:
ConnReq psm=0x001f. Android has no listener, answersresult=2(PSM not supported). They retry twice, 5 s apart, then drop the ACL.The refused case, from the snoop:
And accepted:
The change:
ATTManagerv2opens 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:
BluetoothAdapter#listenUsingInsecureL2capOn(int)is on the hidden API blocklist, hence the dependency onorg.lsposed.hiddenapibypass.Commits:
b1e7657(on-demand bearer; its conclusion was incomplete),848cdfeandroid: 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()setsOWNS_CONNECTION=1first. With a second host connected this takes the AirPods away from it every time the phone connects, with nothing playing on the phone (macOS logsReceived 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:"YES"is written with the length byte of"NO"(0x42), andbtNamehas no length byte. macOS logsUnable to decode relay message with -6735 kUnsupportedErrfor 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).isMusicActive == true) and once after connecting.takeOver()returns early whenOWNS_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 andgetControlCommandStatus()(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:
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:
takeOver("music")deadlockedpausedWhileTakingOverwithoutBLUETOOTH_PRIVILEGED(2bc56d7). When the Mac connected first and the phone was still disconnected, starting playback entered the disconnected takeover path, paused media, and setpausedWhileTakingOver = true— butconnectAudio()only resumed playback and clearedpausedWhileTakingOverinside theBLUETOOTH_PRIVILEGEDfinallyblock, and disconnectedtakeOver()never sentOWNS_CONNECTION = 1orHijackv2once connected.pausedWhileTakingOverstayedtruepermanently, suppressing every later takeover and letting brief Mac score-201 sounds pause phone music. Fixed by running disconnected takeover asynchronously, claiming ownership +Hijackv2once connected, always clearingpausedWhileTakingOver(with a 10 s watchdog), and clearing staleiPausedTheMediaon manual resume.2bc56d7). Once a Mac connects, byte 10 of the AirPods BLE ad moves from0x00(Disconnected) to0x04(Idle, 1 host), andBLEManageralso misparsed the 2-host bitmask (0x08–0x0B).BLEManagernow decodessourceCount+ audio state (0x04–0x0B) and AirPods Pro 3 (0x2720), andAirPodsServicesilently joins once per in-ear session whenvendor_id_hookis enabled andsourceCount < 2without stealing ownership. Also guards concurrentconnectToSocket()races, stopsconnectAudio()from leaking profile proxies / spammingA2dp.connect(), only firesonOwnershipChangeReceivedon real transitions, and usessendPause(force = true)on real ownership loss.lastKnownIsMusicActiveblocked re-takeover after a Mac hijack (d38f220). When the Mac hijacked,sendPause(force = true)ran while Android'sisMusicActivewas stilltrue, so the 800 ms self-action window savedlastKnownIsMusicActive = true. WhenreportStreamingState()ran 1.5 s later and sawisMusicActive == false, it relayed idle (100) to the Mac without resettinglastKnownIsMusicActive = false, causing subsequent Play events to relay301but skiptakeOver("music"). Fixed by resettinglastKnownIsMusicActiveon idle inreportStreamingState(), ononOwnershipLost(), duringpausedForOtherDevicedrain, and when skipping for recent ownership loss; also treatsUSAGE_MEDIAwithCONTENT_TYPE_SPEECH/CONTENT_TYPE_UNKNOWNas 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
takeOver("music")is never reached whenself_mac_addressis empty (MediaControllerreturns early), and the only lookup issu -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.ATTManagerv2falls back to a short session of its own per request, so notifications would not arrive.