Write-up10 min read

Ray-Ban Meta's camera, live on my phone

How Visor's live view gets video from Ray-Ban Meta glasses onto the phone over Wi-Fi Direct, why it only works at 2.4 GHz, how thirteen pictures a second became thirty, and the recording, replay and RTMP broadcast built on top.

Visor is my open-source Android app that replaces the Meta AI app for Ray-Ban Meta and Meta's other smart glasses. Its live view shows what the glasses' camera sees, on the phone, as it happens. It can record what it shows, keep the last few minutes in memory so you can save a moment after it happened, and broadcast to any RTMP server. All of it starts with getting a video stream out of a pair of glasses, and that turned out to be mostly a story about Wi-Fi.

Bluetooth is too slow

The glasses talk to the phone over Bluetooth most of the time, and Bluetooth Classic moves media at 120 to 165 KB/s. A 1080p stream at 4 Mbit/s needs about 500 KB/s, before anything else on the link gets a turn. So the live view runs over Wi-Fi Direct, a network the phone and the glasses make between themselves, where media moves at about 10 MB/s.

The phone hosts the network. Visor makes a Wi-Fi Direct group called DIRECT-Vi-Visor, with a random passphrase, and the phone sits at 192.168.49.1. Then it tells the glasses to join, over Bluetooth, on service 10.

The message named for this job is JoinWifiDirectGroup, and it has never worked. It fails every time with status 3, JOIN_FAILED. What works is JoinAccessPoint, which treats the phone's group as an ordinary WPA2 network. It carries four fields:

FieldValue
1the network's name
2the passphrase
3a random UUID, which has to be a real version 4 one
4the channel width: 1 for 20 MHz, 2 for 40, 3 for 80

The answer is JoinAccessPointResult, with a status, the glasses' addresses as text and a port they pick for this join. A usable answer has status 1, an address and a port. Fresh out of a crash or a restart, the glasses answer INTERNAL_ERROR for up to half a minute, so Visor tries up to eight times, four seconds apart.

A second session, not a moved one

With the glasses on the network, Visor opens a TCP connection to the address and port they gave, and starts a whole new session on it: the AirShield handshake, the trust exchange, the end of setup. Only once that session has started does Visor let go of Bluetooth.

The order matters, because the glasses keep one session per phone, and the newest one wins. When a Bluetooth Classic session reached READY, it closed the Bluetooth LE one within 50 ms. When Visor opened a Wi-Fi session for an import and Bluetooth LE then reconnected, the LE session closed the Wi-Fi one in the middle of a transfer. So the live view connects first and then pauses Bluetooth, and once the glasses are on Wi-Fi, a request sent over Bluetooth never arrives.

The Meta Ray-Ban Display later needed something gentler, a move from Bluetooth to Wi-Fi that keeps the session, its channels and its cipher. That one is a different message, SwitchTransportLink, and the live view doesn't use it.

Starting the camera

Everything to do with the stream goes on the Wi-Fi session, in this order:

  1. Service 28 starts the glasses' app for it, StartApp with app id 3. The answer says whether it started, or why not, with codes for a battery that's too low and glasses that are too hot.
  2. Service 51350, media streaming control, gets the session settings: how long to keep going once the glasses are off your face, what kind of app is asking, and a few switches. The glasses know four kinds of app: Facebook, Instagram, Meta AI's Live mode, and something called the FAIR demo. Visor's live view is the FAIR demo.
  3. ConfigureVideoStreamRequest sets the codec, the size, the bitrate, the frame rate and how often a keyframe comes.
  4. ConfigureAudioStreamRequest does the same for the sound.
  5. ControlStreamRequest with action 1, START.

Every request carries a nonce, and its answer echoes it. The first picture comes about 0.3 seconds after START.

The glasses can also stop the stream themselves, with ControlStreamStopped and one of 24 reasons. Most are what you'd expect: the battery is low, they're too hot, the signal is weak. Two of them are about the wearer. Fold the glasses and the reason is "temples closed". Take them off and it's "doff".

What a frame looks like

Video arrives on service 51350 as chunks of 964 or 968 bytes, message type 10, and the last chunk of a frame is type 12 and carries data too. Joined, a frame is eight bytes of presentation time, in microseconds, little-endian, on the glasses' own clock, followed by one HEVC access unit in Annex B form. A keyframe is a NAL unit of type 16 to 21, and the parameter sets come separately, as message type 1.

Sound comes the same way, as AAC-LC at 48 kHz, stereo, 96 kbit/s: about 47 access units a second, each with its own timestamp on the same clock as the video. The decoder needs a two-byte AudioSpecificConfig to start, and some glasses never send one, so Visor stands in 11 90, which says AAC-LC, 48 kHz, two channels, until the real one turns up.

The best the glasses would give was 1080x1920 at 30 frames a second and 4 Mbit/s. Portrait, because the camera sits in the frame of a pair of glasses and the glasses are upright.

At 5 GHz the glasses' Wi-Fi crashes

The first live views on my phone stopped after 6 to 15 seconds, every time. The glasses didn't say why, which is their habit, so I asked them for a bug report. That's a service 7006 request, and the report comes back as a zip over the same file transfer that carries photos.

Every stall lined up, to the millisecond, with one line in the glasses' kernel log:

wlan_hdd_pld_uevent: Received firmware hang event

Their Wi-Fi firmware was crashing, then dumping its memory and restarting. The phone's group had come up on the same channel as the phone's own network, 5180 MHz, and 80 MHz wide. The glasses log the width on every join, and it said 80 MHz every time, even when JoinAccessPoint had asked for 20. Field 4 turned out to change nothing on a join. The glasses only use it for a network they host themselves.

It isn't throughput alone. A media import over the same 80 MHz group at 5 GHz ran fine. The firmware only gives up when the video stream runs. On a 2.4 GHz group, 20 MHz wide, 1080p at 4 Mbit/s runs clean, so the live view always asks Android for a 2.4 GHz group now, and refuses a group that comes up anywhere else. A later firmware hung the same way, 4 seconds after a 5 GHz join. Whether 5 GHz at 20 or 40 MHz would be safe is still an open question.

Knocking on the old channel

Once the group was on 2.4 GHz, a restarted stream took half a minute to rejoin. The kernel log explained it. Every new group has the same name and the same address on the phone's side, so the glasses went straight back to the channel they remembered, 2412 MHz, and found nothing there, because the new group was on 2437. They kept trying for 22 to 35 seconds before they scanned properly.

JoinAccessPoint has no field for the channel. JoinWifiDirectGroup does, but that's the message that never works. So Visor makes the glasses' memory right instead: each new group goes on the channel of the last one, or better, on the channel of the phone's own Wi-Fi, if that's on 2.4 GHz. A restarted stream now rejoins at once.

One radio, two channels

My phone has one Wi-Fi radio and no way to be on two bands at the same time. At home it sits on a 5 GHz network, and with the group on 2.4 GHz the radio takes turns between the two. Standing still, nobody notices. Walking around, the video fell from 19 frames a second to 1.5, and the glasses' kernel log filled with failed transmissions.

Disconnecting the phone from its home network fixed it, and Android doesn't let an app do that. So Visor checks whether the radio is taking turns, and says so in its log. It also offers a way around the whole thing: the glasses can host the network instead, with CreateSoftApNetwork on service 10, and the phone joins them. That's the one case where the glasses do keep the width they're asked for. On its first run, on a Meta Ray-Ban Display, the stream ran 850 frames at 1080p and 30 frames a second without a stall until I stopped it.

That mode found one more trap. A VPN that apps aren't allowed to bypass makes Android refuse every socket on any other network, including the one the glasses are hosting a few centimetres from your eyes. Visor tests one socket first and, if it's refused, asks you to leave Visor out of the VPN.

A byte that looked like padding

Another stall came only when the wearer moved. The log filled with messages for service 0, type 0, which don't exist, and then the video stopped. A busy picture held still was fine.

Every AirShield frame ends in padding, and the messages inside run across frames as one stream. Visor's old reader checked whether a message fit against the plaintext with its pad still on. A message one byte short of the end of a frame took the first pad byte as its last byte, and the byte it was really owed, at the start of the next frame, was then read as the start of a new header. From there every message was cut in the wrong place. Moving the glasses makes the link worse, the frames get split more often, and the bad case comes up more.

I traced 47,000 Wi-Fi frames from one live view to check that taking the pad off first is exact. It is, because the glasses never end a frame's data on a byte that could pass for padding. When a message would, they move that byte into a frame of its own: the byte, then fifteen CF bytes. So the reader now strips the pad, joins what's left to what it carried over, and cuts messages by their length:

private fun splitMessages(plaintext: ByteArray): List<DataXMessage> {
    val stream = carry + AirShieldCipher.stripPad(plaintext)
    val messages = mutableListOf<DataXMessage>()
    var pos = 0
    while (stream.size - pos >= 4) {
        val wireTotal = Header.parse(stream.copyOfRange(pos, pos + 4)).wireTotal
        if (stream.size - pos < wireTotal) break
        val whole = stream.copyOfRange(pos, pos + wireTotal)
        val info = Header.parse(whole)
        messages += DataXMessage(info, whole.copyOfRange(info.headerLen, wireTotal))
        pos += wireTotal
    }
    carry = stream.copyOfRange(pos, stream.size)
    return messages
}

Thirteen pictures a second

With the link stable, the video still looked choppy. The timestamps said the glasses filmed at an even 30 frames a second, 33 ms apart. They just didn't send that way. Frames arrived in bursts, four or five within about 5 ms, then nothing for 110 to 160 ms. Pings to the glasses showed the same gaps, so the bursts came from their radio, not their encoder, and neither a lower bitrate nor extra traffic from the phone changed them. Shown as they arrived, each burst collapsed into one or two pictures, about 13 different pictures a second out of 30. The glasses film like a camera and deliver like a commuter train.

The fix is a playout buffer: hold each frame back a little and show it when its timestamp says to.

  • The offset between the glasses' clock and the phone's is the smallest gap between a frame's arrival and its timestamp over the last 10 seconds.
  • The delay is the largest gap over the same window, minus the offset, plus 15 ms, kept between 20 and 500 ms.
  • The delay goes up at once, and comes down by at most 1% of the time that has passed, so nobody sees it move.
  • A jump of more than 3 seconds means the glasses' clock started again, and the window starts over.
fun due(ptsUs: Long, arrivedNs: Long): Long {
    val now = arrivedNs / 1000
    val lag = now - ptsUs
    // The glasses' clock started again.
    lows.firstOrNull()?.let { if (abs(lag - it.lag) > JUMP_US) clear() }
    while (lows.isNotEmpty() && lows.last().lag >= lag) lows.removeLast()
    while (highs.isNotEmpty() && highs.last().lag <= lag) highs.removeLast()
    lows.addLast(Sample(now, lag))
    highs.addLast(Sample(now, lag))
    while (lows.first().at < now - WINDOW_US) lows.removeFirst()
    while (highs.first().at < now - WINDOW_US) highs.removeFirst()
 
    val offset = lows.first().lag
    val target = (highs.first().lag - offset + MARGIN_US).coerceIn(MIN_US, MAX_US)
    // Up at once; down by at most 1% of the time passed, so nobody sees it.
    delayUs = if (target >= delayUs || lastUs == 0L) target else maxOf(target, delayUs - (now - lastUs) / 100)
    lastUs = now
    return (ptsUs + offset + delayUs) * 1000
}

The two windows are monotonic queues, so the smallest and the largest are always at the front. On a bursty link the delay settles near 190 ms, and all thirty pictures a second show up.

When frames go missing

A frame that never arrives leaves the decoder with nothing to build the next ones on, so after a gap in the sequence numbers Visor waits for a keyframe and skips what comes before it. A frame that arrives more than 250 ms past its turn is decoded but not shown, so the decoder catches up without needing a keyframe. And if two seconds pass with no keyframe at all, Visor sends the same ConfigureVideoStreamRequest again. The glasses take it as a change of settings and restart their encoder, which starts on a keyframe.

Above that sit the watchdogs. An empty request goes out every 2 seconds, and the glasses always answer it, so 8 seconds of silence means the session is gone. Four seconds without video means a restart of the whole chain, from the Wi-Fi group up, and after five restarts in a row Visor gives up and says the picture kept stopping.

Picking the quality

The live view picks its quality by itself, from a ladder:

SizeBitrateFrame rate
1080p4 Mbit/s30
1080p3.5 Mbit/s24
720p2.5 Mbit/s30
504p1.5 Mbit/s30
432p1 Mbit/s24
360p600 kbit/s24

A second counts as a struggle when the frame rate falls under 60% of the target, when the delay climbs 700 ms over where it was, or when a gap passes 900 ms. Two struggling seconds step down a rung, and 40 calm seconds step back up. A rung that fails within 20 seconds of a step up is off limits for three minutes. Heat sets a floor too: glasses that report themselves as moderately hot don't go above 720p. Every change is a new ConfigureVideoStreamRequest in the middle of the stream, and the encoder picks it up on its next keyframe.

Recording, replay and broadcasting

Every frame and every packet of sound goes three ways. It always goes into the replay ring. While you record, it also goes into an MP4, and while you broadcast, into a queue for the RTMP server.

The recording keeps the glasses' own HEVC as it came, with no re-encoding, so it costs almost nothing. It starts at the next keyframe, and it stays hidden from the gallery until it's finished.

The replay ring holds the last two minutes by default, or 30 seconds, one minute or three. It always starts on a keyframe, so whatever it holds can be saved and played:

@Synchronized
fun add(frame: VideoFrame) {
    if (video.isEmpty() && !frame.isKey) return
    video.addLast(frame)
    while (video.size > 1 && frame.ptsUs - video.first().ptsUs > windowUs) video.removeFirst()
    while (video.isNotEmpty() && !video.first().isKey) video.removeFirst()
    val start = video.firstOrNull()?.ptsUs ?: return
    while (audio.isNotEmpty() && audio.first().ptsUs < start) audio.removeFirst()
}

The broadcast uses an RTMP publisher I wrote for Visor, for rtmp:// and rtmps://. HEVC can go out as it is, as Enhanced RTMP. Most servers still want H.264, though, and then the phone re-encodes: a hardware decoder draws straight into a hardware encoder's input surface, so no frame passes through the app's memory. H.264 gets one and a half times the bitrate, because it needs about that much more for the same picture.

Frames wait in a queue and go out from one place, so a slow network never holds up the glasses. If the queue passes 4 MB, about eight seconds of video, it drops video up to the next keyframe. If the connection drops, Visor tries again after 2, 4, 8, 16 and 32 seconds, throws away the backlog, which is old news by then, and starts again from a keyframe.

One last thing makes all of it work: the glasses restart their clock whenever the stream restarts, so every timestamp goes through a function that only lets time go forward. A recording that survives a restart just carries on, 33 ms after its last frame.