Back

Writing an AirPlay Receiver in Kotlin: What Real iPhones Actually Send

Nov 1, 2026 (3d ago)

I wanted to pick my TV in the AirPlay menu on my iPhone and hear music through its speakers, with cover art on the screen. My TV runs on a Chromecast with Google TV, which doesn't speak AirPlay. So I built Crosscast, an open-source app that turns a Google TV into an always-on AirPlay speaker.

The source is on GitHub. This post is about the parts that surprised me, and most of those came from testing against a real iPhone.

Why not just port Shairport Sync?

Shairport Sync is the established open-source AirPlay receiver, so the first plan was to compile it for Android with the NDK. A source audit killed that plan, and the reason is one function.

Shairport's classic code calls pthread_cancel 27 times, and those calls sit on the session teardown path, which runs on every disconnect and every sender switch. Android's libc doesn't implement it. Bionic's own status document says thread cancellation is "unlikely to ever be implemented".

The workarounds are all poor:

  • A signal-based shim cancels asynchronously, possibly inside malloc or while holding a lock, so you risk deadlocks on random teardowns.
  • Rewriting cancellation cooperatively means maintaining a permanent fork of the most delicate part of the code.
  • Pinning a version from before it was used gives up eight years of fixes. Termux tried that with 3.1.2 from 2017, and has since disabled the package anyway.

So it would compile, but it wouldn't run correctly. The existing Java servers didn't fit either: one had the right protocol but a 2011-era stack and no metadata, another only handled AirPlay 2's path, and two had licence problems.

Classic AirPlay audio, though, is a small and well-understood protocol, and Android's SDK covers almost every piece of it:

Piece Implementation
Discovery mDNS via NsdManager
Control RTSP text protocol
Key exchange RSA-OAEP (SHA-1) unwrap of the AES key, plus an Apple-Challenge signature
Audio AES-128-CBC packets over UDP, decoded from Apple Lossless
Output AudioTrack
Remote control DACP, back to the sender

ALAC is the exception. It isn't a guaranteed MediaCodec codec on Android, only an extra on some devices, so I ported David Hammerton's MIT-licensed decoder to Kotlin. Writing everything in Kotlin also removes the ABI matrix, and it means network input is parsed in a memory-safe language, so a decoder bug becomes an exception rather than memory corruption.

Shairport Sync stayed essential as the reference for protocol details and timing. It just isn't a dependency.

Staying in sync

Sync was the main risk, because it's where Shairport is strongest. Sender and receiver each have their own clock, and they disagree.

Timing-port exchanges estimate the offset between the clocks, and control-port sync packets map RTP timestamps to sender time. Playback starts at the negotiated latency of about 2 seconds, and drift gets corrected by inserting or dropping single frames.

You can't wait around for a 30-minute real-world test on every change, so I wrote a simulation with a virtual clock: sender at +60 ppm, DAC at −40 ppm, 50 ms of output latency, ±1.5 ms of timestamp jitter, 1–8 ms of network delay and 0.1% loss. Over a simulated 30 minutes, it gave:

  • Maximum error: 2.99 ms
  • Mean error: 1.38 ms
  • Net frames dropped: 7,853, about 100 ppm, which matches the combined clock difference
  • Re-alignments and underruns: none

The simulation also found a tuning bug that I wouldn't have noticed by ear. A stuffing tolerance of ±2 ms left the error sitting at +2 ms, and ±1 ms centres it.

What real iPhones do

My notes up to this point came from documentation and from a test sender, pyatv. Then I connected a real iPhone, on iOS's AirPlay/980.77.1, and a lot of assumptions fell over.

Pause doesn't send FLUSH. I'd assumed a pause would announce itself. Instead, iOS keeps streaming at the full packet rate, sending digital silence, along with a progress update. So the receiver detects a pause by listening: ¾ of a second of near-silence (|sample| ≤ 8, about −72 dBFS) counts as paused.

Skipping doesn't send FLUSH either. The stream carries on and the new track's metadata arrives. iOS also often sends a stale progress just before the correct one, so you can't trust the first one you see.

The progress bar should follow what you hear. progress arrives when the sender sends a frame, about 2 seconds before it plays. Extrapolating from wall-clock time left the bar running 2 seconds ahead, and still moving after a pause. Now the position comes from the frame that's actually audible, and it stops when the sound does.

The sender's name is in the SDP. It's in the i= line, rather than in the X-Apple-Client-Name header I'd expected.

The iPhone connects over IPv6 link-local. RTSP, RTP and DACP all arrive on addresses like fe80::…%wlan0. Android's URL and HttpURLConnection reject scoped literals as an invalid host, so every remote-control command was failing. DACP is now raw HTTP/1.1 over a Socket.

A receiver can't move the iPhone's volume slider. setproperty?dmcp.device-volume=… returns 200 and changes nothing, and most of the properties I'd hoped to read return 400. Every new session also opens at −20. So Crosscast pins the level you last listened at to that opening position, and maps the slider around it. It's a compromise, and it's still the part I'm least happy with.

The TV is a stranger environment than the phone

Some discoveries about the device itself:

  • A sleeping TV has no HDMI audio. Output reroutes to a dummy device, and the audio track barely drains. So a session must wake the TV, and waking at RECORD gives HDMI about 2 seconds to return before the first audio is due.
  • The userspace is 32-bit on a 64-bit kernel, which would have mattered a lot for a native build.
  • The CPU never suspends, even with the TV asleep, so an idle listener doesn't need a wake lock.
  • Three full-screen blended layers would be about 6 megapixels of fill per frame on the Chromecast's GPU. The moving background is composited on the CPU into a 192×108 bitmap at about 30 fps instead, then scaled up as a single layer.

My favourite one is about my own notes. I'd written that Google TV has no settings screen for the overlay permission, and that setup therefore needed adb. That had been assumed rather than tested, and all of it was wrong. On a fresh install, the screen exists, and setup needs one permission, granted from the TV remote and no computer.

What I'd tell you if you're building something similar

  • Keep a notes file of what you actually observed. Mine changed the design more than any plan did, and it also caught its own wrong entries.
  • Test against the real sender as early as possible. None of the iPhone section above showed up with my test sender, because pyatv doesn't behave like an iPhone.
  • Simulate time. Thirty minutes of drift in a unit test makes timing work something you can iterate on.

Crosscast is on GitHub under the MIT licence, and the APK is in the releases. I've only tested it on a Chromecast with Google TV 4K so far, so I'd like to hear how it behaves on other TVs.