AirPlay 2 in C#: one clock syncs the speakers, and a relay makes a group show up on an iPhone
How an AirPlay 2 sender and receiver work, from pairing and encrypted audio packets to the shared clock, and how Housecast made a speaker group appear as one speaker on an iPhone.
The speaker accepted every setup request in 582 ms. Then I sent it six seconds of a 440 Hz tone, 750 packets, and heard nothing. On a 15-second retry, the speaker sent nothing back on any port.
That was the first sound from my native AirPlay engine for Housecast, a Windows app that plays the PC’s sound on several AirPlay speakers at once. The first post in this series covers the app, and the source is on GitHub. This post covers the engine that replaced its borrowed one: the parts of an AirPlay 2 sender and receiver, and the bugs between “accepted” and “heard”.
Note
Speakers stay in sync because they all follow one clock and one timeline. My speakers ignored that clock at first because new TcpClient() opens a dual-mode socket, so the address I gave them read ::ffff:a.b.c.d instead of a.b.c.d. A group shows up as one speaker on an iPhone when the PC announces itself as a receiver, decodes the phone’s audio and re-sends it a second early on one unbroken stream.
Why the borrowed engine had to go
The first version of Housecast did its AirPlay work with OwnTone, an open-source media server written in C, running inside the Windows Subsystem for Linux (WSL). For a public release, users would have to turn on WSL (admin rights and usually a restart), run Windows 11 22H2 or later, change a PC-wide setting, and wait about ten minutes while OwnTone compiled. So the engine had to run natively in C#.
That raised a licence question before any code. OwnTone’s AirPlay sender is under the GNU General Public Licence (GPL), so porting it to C# meant publishing the app’s source under the GPL too; the alternative was building from the protocol documentation, slower and riskier. I chose the GPL and the port. OwnTone’s pairing code (pair_ap) and clock code (libairptp) are MIT-licensed, and a NOTICE file credits them and, later, Shairport Sync.
How a sender talks to a speaker
An AirPlay 2 sender has four parts: finding the speaker, a control conversation, the audio packets, and a shared clock.
Finding speakers. Speakers announce themselves with DNS Service Discovery (DNS-SD) over multicast DNS, a way for devices on one network to publish a name and a port. I call the one built into Windows: a third-party library found no speakers on my PC, and the Windows service avoids a firewall prompt and a fight over UDP port 5353.
The control conversation. It runs over the Real Time Streaming Protocol (RTSP), which looks like HTTP: a method, a path, headers and a body. It starts with HomeKit-style pairing, which uses the Secure Remote Password (SRP) protocol: both sides prove they know a secret without sending it, and end up holding the same keys, which encrypt every later request. My SRP maths is checked against the published test vectors in RFC 5054.
After pairing, the order matters, so I followed OwnTone’s. These calls are abridged from the session method.
SharedSecret = pairing is null ? await HomeKitPairing.PairTransientAsync(_rtsp, cancellationToken) : await HomeKitPairing.VerifyAsync(_rtsp, pairing, pairingId, cancellationToken);// ...var session = await SendPlistAsync("SETUP", sessionSetup, cancellationToken);// ...await SendOrThrowAsync("RECORD", SessionUrl, null, null, cancellationToken);// ...await SendOrThrowAsync("SETPEERS", SessionUrl, BinaryPropertyListWriter.WriteToArray(peers), "/peer-list-changed", cancellationToken);// ...var streamReply = await SendPlistAsync("SETUP", new NSDictionary { ["streams"] = new NSArray(stream) }, cancellationToken);// ...await SetVolumeAsync(volumePercent, cancellationToken);The audio. The stream describes itself in the second SETUP: 44.1 kHz, 16-bit stereo, 352 samples a packet, compressed as Apple Lossless (ALAC). I skip the encoder: ALAC has an “uncompressed” escape, so I wrap the raw samples in a valid ALAC frame and the speaker decodes it like any other. Each packet is a 12-byte header and its frame, encrypted with ChaCha20-Poly1305 using the first 32 bytes of the pairing secret as the key. The nonce comes from the packet number, so a resent packet is identical to the original.
var nonce = new byte[12];BinaryPrimitives.WriteUInt16LittleEndian(nonce.AsSpan(4), sequence);
audioKey.Encrypt( nonce, alacFrame, packet.AsSpan(HeaderLength, alacFrame.Length), packet.AsSpan(HeaderLength + alacFrame.Length, TagLength), packet.AsSpan(4, 8)); // authenticated: rtptime and SSRCThe clock. Audio arrives about two seconds before it plays, so each speaker needs to know when “now” is. AirPlay 2 uses the Precision Time Protocol (PTP): one device is the master clock, the others follow it. The engine is the master, listening on UDP ports 319 and 320, and a sync packet tells each speaker “this sample plays at this clock time”.
The speakers that ignored my clock
My first guess was the platform. OwnTone, still running in WSL, holds UDP 319 and 320 because WSL shares the PC’s network. I stopped it and the engine could claim the ports, yet the speakers still sent nothing, even with WSL shut down. A capture of OwnTone talking to the same speaker showed the same clock messages, apart from the random clock ID, and an answer within about 40 ms, where my engine got nothing in 15 seconds.
The cause was one line. new TcpClient() opens an IPv6 socket that also accepts IPv4, called a dual-mode socket. Its local address for an IPv4 connection reads ::ffff:a.b.c.d. I put that address into the session setup, where the speaker is told where to find my clock, and the speaker couldn’t use it.
public IPEndPoint? LocalEndPoint => _tcp.Client.LocalEndPoint as IPEndPoint;// TcpClient's socket is dual-mode, so an IPv4 connection reports ::ffff:a.b.c.d; receivers// are given this address for PTP and the session URL and only understand the plain IPv4 formpublic IPEndPoint? LocalEndPoint => _tcp.Client.LocalEndPoint is IPEndPoint local ? new IPEndPoint(local.Address.IsIPv4MappedToIPv6 ? local.Address.MapToIPv4() : local.Address, local.Port) : null;What the speaker was told, before and after:
before "Addresses": ["::ffff:a.b.c.d"]after "Addresses": ["a.b.c.d"]After the fix, with WSL running and only OwnTone stopped, Bedroom 2 sent 135 clock timing requests in 15 seconds, and all were answered. I heard the tone. A test now asserts that a loopback connection reports a plain IPv4 local address.
Several speakers, one clock
I expected group playback to need coordination, but OwnTone does none. Each speaker gets its own session, and its SETPEERS request lists only that speaker and the sender. They stay in sync because every one follows the same PTP clock and the same timeline: sample N is due at the same clock time for all of them.
My streamer already worked that way. Two speakers were ready in 525 ms when set up in parallel, and a second one that joined partway through playback fell into step at once. The only per-speaker part is an offset in the sync packet, which lets a delay slider move one speaker earlier or later.
A Samsung TV still broke it: it refused the volume request with 500 Internal Server Error, and my code treated that as fatal and dropped the TV. OwnTone marks its volume step with a flag, proceed_on_rtsp_not_ok, that lets the sequence carry on when that step is refused. I did the same, and the TV now plays at its own volume.
// OwnTone sends volume last: some speakers ignore it if it comes earlier. Samsung TVs// refuse it with 500 and play anyway, so, as in OwnTone, a refusal doesn't end the session.try{ await SetVolumeAsync(volumePercent, cancellationToken);}catch (AirPlayException){}The receiver: making a group look like a speaker
The other half of the goal was the reverse: “Upper Level”, a group of four speakers, should appear in an iPhone’s AirPlay list as one speaker. So Housecast is a receiver as well as a sender: the phone plays to the PC, and the PC plays on the group.
A receiver has four jobs. It announces itself with two DNS-SD services, _airplay._tcp and the older _raop._tcp, under a device ID derived from the group’s name, so it looks the same after a restart. It answers pairing with the server side of SRP. And it answers FairPlay, Apple’s copy protection handshake, with four fixed replies copied from Shairport Sync, which the phone accepts.
The phone then sends AAC (Advanced Audio Coding) frames of 1024 samples over TCP, encrypted like mine and far ahead of playback: about 95 seconds of the song arrived within the first six. Anchors say “this sample plays at this moment on my clock”, so the receiver follows the phone’s PTP clock and decodes each frame with the AAC decoder built into Windows. In the first iPhone test, pairing, setup and audio all happened within 0.8 seconds of picking the speaker.
Two bugs after a skip
The first song played fine. After I skipped, nothing more came out, and it took two fixes to find out why.
When you skip, the phone says “flush everything up to packet number N”. I read packet numbers with a mask one bit too narrow. They are 24 bits wide and I kept 23, so numbers with the top bit set came out too small, and the new song’s packets looked older than the cut-off and were thrown away. The unit test now uses a sequence number of 0xCD8E34, which doesn’t fit in 23 bits.
// The sequence number is the low 23 bits of the header's first four bytesvar sequence = BinaryPrimitives.ReadUInt32BigEndian(packet) & 0x7F_FFFF;// The sequence number is the header's bytes 1 to 3var sequence = BinaryPrimitives.ReadUInt32BigEndian(packet) & 0xFF_FFFF;With that fixed, the first skip still ended the sound, and nothing was logged as dropped. The play loop’s log showed why:
playout stopped: System.Runtime.InteropServices.COMException (0x80004005): Unexpected HRESULT has been returned from a call to a COM component.Right after a skip, the Windows decoder refused one frame, and that one exception ended the whole playout loop. Now I skip the frame (about 23 ms), reset the decoder and carry on. In a 30-second test the phone asked to drop queued audio 13 times, and twice a frame after a skip failed to decode and was skipped.
catch (COMException ex){ // Windows' decoder fails some frames around a skip; lose that frame, not the stream _log($" frame {packet.Sequence} didn't decode (0x{ex.HResult:X8}); skipped"); _decoder.Reset(); _decoding.Clear(); continue;}Audio that has to be heard now
Next came relaying. The phone sends audio well ahead, but its anchor asks for playback to start the moment the anchor arrives, as if there were no head start, and my speakers need audio at least 250 ms before it plays. From how open-source receivers handle this, iOS expects each bit heard at the instant it names and does not wait for slow receivers. I tried telling the phone my receiver needed extra time; it kept asking for audio “now”, so I removed the hint.
So the receiver hands each decoded frame on one second before it is due, and the streamer puts it on the wire 750 ms before it plays. A frame more than 250 ms past its release time is dropped.
private static readonly TimeSpan RelayLead = TimeSpan.FromSeconds(1);private static readonly TimeSpan RelaySendLead = TimeSpan.FromMilliseconds(750);// ...receiver.AudioDue += audio => relay.Streamer.SendTimed(MemoryMarshal.Cast<byte, short>(audio.Pcm), audio.PlayAtNanoseconds);The price is silence. Each play or skip in the log lost about 0.46 s of audio that was due too soon to send ahead, so you hear about half a second of nothing, and then the group is in step with the phone. A resume lost nothing, because the phone resumes from audio it already sent. A video’s voices should stay with its picture, but I only checked music by ear.
A pause that silenced the group
My first group test played until I paused; after resuming, nothing came out, and a skip didn’t bring it back. During the pause I sent the speakers nothing for a few seconds, and the audio came back on a new timeline that they didn’t follow. I think a skip before the pause had worked only because its timing moved by about 0.1 s.
The fix was to never change the timing. While the phone holds the group, the speakers get one unbroken stream. A new class cuts the audio into a frame for every 352 samples of time and fills any gap with silence, so a seek is a jump in the sound, never in the timing.
while ((playAt = _origin + _taken * 1_000_000_000 / SampleRate) <= untilNanoseconds){ var frame = new short[FrameLength]; var available = Math.Min(FrameLength, _queued.Count); _queued.CopyTo(0, frame, 0, available); _queued.RemoveRange(0, available); // ...}Unused room in frame stays zero, which is silence. When the phone stops, the stream ends and the next play starts a new one. Play, pause, resume, skip and seek then all worked on two bedroom speakers.
Why the iPhone shows a plain speaker
In the Housecast window, a group card shows two overlapping speakers; on the iPhone the same group is a single generic speaker. I believe iOS picks the icon from a built-in list keyed on the device model, with special pictures for Apple’s own products, but I didn’t find this in Apple’s documentation. The only workaround I can see is claiming to be an Apple device, which is misleading and could make the phone expect Apple-only features. So the group’s name sets it apart.
How to check it worked
Run the engine tests. For the sender, watch a speaker’s clock traffic while it plays: a speaker that follows your clock sends timing requests, each answered.
dotnet testFor the receiver, play from an iPhone and read the log. Each anchor line says when the first frame plays and how much audio is queued.
rate 1, rtpTime 2934453013, clock {phone's clock ID}anchor plays in -10 ms; 2.2 s of audio queued, the first (seq 2102853) at rtpTime 2934466231Takeaways
- Speakers stay in sync by following one PTP clock and one timeline. Nothing coordinates them.
- Turn a dual-mode socket’s
::ffff:a.b.c.dinto plain IPv4 before telling a device where to reach you. - Treat a refused volume request as optional. My Samsung TV answered 500 and played anyway.
- A relayed stream must never change its timing. Fill pauses with silence and let seeks be jumps in the sound.
- Expect about half a second of silence after each play or skip.