raop
An AirPlay audio receiver for Android. iPhones, iPads and Macs play to the device like any AirPlay speaker.
An AirPlay 1 receiver for Android, in plain Kotlin. Senders find the device in their AirPlay menu and play to it: the library answers their RTSP session, proves it holds the key they check for, unwraps the session's AES key, decrypts and decodes the audio (Apple Lossless or PCM), and asks again for packets the network lost. It hands you PCM with the time each packet should be heard on your clock, so several receivers playing the same stream stay together.
RAOP (Remote Audio Output Protocol) is the protocol's own name, and the one AirPlay speakers announce
over mDNS (_raop._tcp). AirPlay 2 isn't supported yet.
It has no Pane API and no app classes. The Glassworks music pane wraps it with settings and entities.
Package dev.glassworks.raop, MIT licensed (the ported ALAC decoder stays Apache-2.0), minSdk 23.
Use it in your own app
The receiver hands you PCM and the time to play it. synced-audio
plays it at that time:
val playing = AtomicBoolean(true) // the audio thread runs until stop() clears it
val sink = AudioTrackSink()
val scheduler = PlaybackScheduler(sink, { StreamClock.LOCAL }) // presentAtNanos is on this device's clock
var rate = 44_100
val receiver = RaopReceiver(
name = "Kitchen panel", // what the AirPlay menu shows
hardwareId = myStableRandomId, // 6 bytes, the same on every start; not the real MAC
output = object : RaopReceiver.Output {
override fun start(sampleRate: Int, channels: Int) { rate = sampleRate; scheduler.start(PcmFormat(sampleRate, channels)) }
override fun write(pcm: ShortArray, frames: Int, presentAtNanos: Long) {
scheduler.push(PcmChunk(presentAtNanos / 1000, pcm, frames, rate, pcm.size / frames))
}
override fun flush() = scheduler.clear()
override fun stop() = scheduler.end()
},
listener = object : RaopReceiver.Listener {
override fun onVolume(db: Float) = sink.setGain(RaopReceiver.gainOf(db))
override fun onMetadata(metadata: RaopReceiver.Metadata) { showNowPlaying(metadata.title, metadata.artist) }
},
)
thread(name = "audio", isDaemon = true) {
try {
while (playing.get()) if (!scheduler.step()) scheduler.awaitWork(200)
} finally {
scheduler.end()
sink.close() // the audio thread owns the output: it releases the AudioTrack when it stops
}
}
val port = receiver.start(5000)
Then announce it, with Android's NsdManager or any mDNS responder:
val info = NsdServiceInfo().apply {
serviceName = receiver.serviceName // "021122334455@Kitchen panel"
serviceType = "_raop._tcp"
this.port = port
receiver.txtRecord.forEach { (k, v) -> setAttribute(k, v) }
}
nsdManager.registerService(info, NsdManager.PROTOCOL_DNS_SD, registrationListener)
When you're done, undo all three: take it out of the AirPlay menu, stop the receiver, and let the
audio thread end, which closes the AudioTrack:
nsdManager.unregisterService(registrationListener) // the same listener it was registered with
receiver.stop() // closes its sockets and ends the sender's session
playing.set(false) // the audio thread leaves its loop and closes the sink
One sender plays at a time; a new sender takes over from the one playing, as AirPlay speakers do.
write gets packets in arrival order, and a packet the network lost arrives late, when it's resent.
The scheduler puts them back in order by presentAtNanos. With an output of your own, order them
yourself and start each one when System.nanoTime() reaches it, less the output's own latency.
What's in it
RaopReceiver |
The receiver: RTSP (OPTIONS, ANNOUNCE, SETUP, RECORD, FLUSH, PAUSE, SET_PARAMETER, GET_PARAMETER, TEARDOWN), the Apple-Challenge, the audio, control and timing sockets, resend requests, and the track's volume, metadata, cover and progress. |
RaopReceiver.Output, RaopReceiver.Listener |
Where the audio and the track details go. Output calls come one at a time; listener calls come in order on their own thread, so a listener may call stop(). |
RaopReceiver.gainOf |
AirPlay's volume (-30 to 0 dB, -144 for mute) as a gain from 0 to 1. |
| internal | The ALAC decoder (a port of Apple's), RSA and AES, the SDP and DMAP parsers, and the clock sync with the sender. |
The manifest adds INTERNET. The library doesn't log.
How AirPlay 1 works
The parts a receiver has to get right, in the order a sender uses them:
- The challenge. On
OPTIONS, the sender sends 16 random bytes inApple-Challenge. The receiver appends the address the sender reached it on and its 6-byte hardware id, pads it to 32 bytes and signs it with the AirPort Express's RSA key (PKCS#1 v1.5, no digest). That key has been public since 2011 and every open receiver carries it. - The keys.
ANNOUNCEcarries SDP: the codec (AppleLosslesswith its parameters ina=fmtp, orL16PCM), and the session's AES-128 key, wrapped with the same RSA key (OAEP, SHA-1), with its IV. - The sockets.
SETUPnames the sender's control and timing ports; the receiver opens three UDP ports (audio, control, timing) and answers with them. - The audio. RTP packets of 352 frames, each payload AES-CBC encrypted from the same IV (only whole 16-byte blocks; the tail is clear). A gap in sequence numbers is asked for again on the control port.
- The timing. The receiver sends NTP-style timing requests to learn the offset between the sender's clock and its own. On the control port, sync packets say which RTP time is heard at which NTP time. Together they give each packet's time on the receiver's clock.
Gradle
Not on Maven Central yet. In this repository: implementation(project(":raop")). An Android library
(AAR), minSdk 23 (Android 6), with no dependencies beyond the Kotlin standard library.
Tests
./gradlew :raop:testDebugUnitTest.
AlacDecoderTestdecodes ffmpeg's Apple Lossless and checks every sample against the source, stereo and mono. The source takes every path in the decoder: predicted and verbatim frames, zero runs and matrixed stereo.src/test/resources/make-alac-fixtures.shmakes the files.RaopReceiverTestplays a sender written from the protocol against the receiver: the challenge (checked with the public key), an encrypted ALAC stream with one packet lost and resent, the times each packet is heard, volume, metadata, progress, a second sender taking over and a format it refuses.PyatvInteropTeststreams a WAV from pyatv 0.18.0, an AirPlay sender we didn't write, and checks every sample. It skips unlessRAOP_ATVREMOTEpoints at pyatv'satvremote; CI installs it fromtest-requirements.txt.