My parents' TV box had been back from the dead for about an hour when I asked it for two more things. One was a camera in the room. The other was a button on my phone that puts my voice on their TV, wherever I am, so I can say "the gate is open" or "pick up the phone" without them touching anything.
This is part three of the series. Part one built the home screen; part two is how it got bricked and recovered. This part is the most engineering of the three, and it ends with the box freezing. That part is my fault too.
The talk button, end to end
The requirement was short: tap, speak, tap, and they hear it, from any phone on any network, with nothing installed on the phone, and without changing what is on their screen.
your voice is now
microphone samples
A page with one button. getUserMedia needs a secure context, which is why the page must be served over HTTPS.
the decision at this hop
A web page, not a Shortcut: the Shortcut hung because the phone was not on the private network, and it had no way to say so.
Two of those hops are mine. The rest are platform pieces chosen so that no hop has to convert anything.
The phone: a page, because the Shortcut could not say what was wrong
The first version was an iOS Shortcut: Record Audio, then Get Contents of URL with a POST. It worked from the laptop and hung on the phone. The URL was on the private Tailscale network, the phone was not on it, and the Shortcut just waited without saying why. That is the worst failure mode a tool can have.
The replacement is one HTML page with one button, and it can say exactly what went wrong:
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const type = MediaRecorder.isTypeSupported('audio/mp4') ? 'audio/mp4' : '';
rec = new MediaRecorder(stream, type ? { mimeType: type } : {});
rec.onstop = async () => {
const r = await fetch('/talk?t=KEY', { method: 'POST', body: new Blob(chunks, { type: rec.mimeType }) });
if (!r.ok) throw new Error(await r.text());
};
Every state has its own words: recording with a seconds counter, sending, "Sent ✓, they
hear it now", "the microphone is blocked: Settings › Safari › Microphone", and "couldn't
reach the TV box". getUserMedia only works in a secure context, so the page has to be
HTTPS. That requirement shaped the next hop.
Safari's MediaRecorder produces AAC in an MP4 container. Android's MediaPlayer plays
that natively, so the box never transcodes. That matters on a 2017 SoC with no ffmpeg and
1 GB of RAM.
Reaching the box from anywhere: publish a path, not a device
The box sits behind a home router with no public address. It already ran tailscaled.
Tailscale Funnel gives a node a public HTTPS name and relays traffic to it, and,
importantly, it publishes paths:
tailscale funnel --bg --set-path=/talk http://127.0.0.1:8766/talk
tailscale funnel --bg --set-path=/s/<secret> /data/local/tailscale/speak.html
TLS terminates on the box with a certificate for the node's own name, so the relay sees
only encrypted bytes. The camera, the phone remote and adb are not on that list and do
not answer from the internet at all.
who can call it
anyone with the key
what they get
Plays a voice message once. Cannot read anything back.
I checked it from the outside rather than trusting the config. Resolving the public name
through a public DNS server and pinning curl to that address: /talk with the key plays
a message, /talk with a wrong key gets 404, and /snap and / get 404 too. The camera
is unreachable from the public side.
The receiver: twenty lines in the daemon that was already there
The box already ran my camera daemon (below), so the receiver is one more handler:
http.HandleFunc("/talk", func(rw http.ResponseWriter, r *http.Request) {
if !ok(r) || r.Method != http.MethodPost { http.NotFound(rw, r); return }
data, err := io.ReadAll(io.LimitReader(r.Body, 20<<20))
if err != nil || len(data) < 100 { http.Error(rw, "no recording received", 400); return }
os.WriteFile("/data/local/tmp/talk.m4a", data, 0644)
exec.Command("/system/bin/am", "startservice",
"-n", "np.sajilo.talk/.Speak", "-d", "file:///data/local/tmp/talk.m4a").Run()
})
The key check returns NotFound, the same as an unknown path, so the public side gives
nothing away. The body is capped, and a recording under 100 bytes is rejected as empty.
The player: a 12 KB app with no screen
Playing audio "over whatever is on" is an Android audio-focus question. The talk app is
one exported Service. It asks for transient focus that allows ducking, plays the file
once, and gives focus back:
am.requestAudioFocus(this, STREAM_MUSIC, AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
mp.setDataSource(path); mp.prepare();
boost = new LoudnessEnhancer(mp.getAudioSessionId()); boost.setTargetGain(1000); // +10 dB
mp.start(); // onCompletion: release, abandonAudioFocus, stopSelf
MAY_DUCK means a player that respects focus lowers its volume rather than pausing. The
video keeps running and nothing on screen changes. It had to be exported, because the
shell cannot start a non-exported service: the first install failed with
Requires permission not exported from uid.
The bug that only a human could see: it played, and nobody heard
The first message from the phone arrived. The log said playing 3204 ms … done. Nobody in
the room noticed it.
I pulled the file back and measured it:
| Recording | Mean level | Peak |
|---|---|---|
| Laptop (ffmpeg, with a ×2 gain) | −17.8 dB | 0.0 dB |
| iPhone (Safari / Shortcuts) | −29.6 dB | −11.3 dB |
About 12 dB quieter, roughly a quarter of the loudness, under a TV that was already
talking. The fix sits where every sender passes through: a LoudnessEnhancer on the
player's audio session, +10 dB with its built-in limiting, and the laptop's own ×2 gain
removed so both senders land at the same level. The lesson is in the last hop of the
figure: "done" means heard, and only a person in the room can tell you that.
The camera: V4L2 from Go, by hand
The camera is a USB webcam on the box's side socket, a fixed-focus laptop module offering
MJPEG at 1280 × 720 or 640 × 480. Android 7's camera stack is not something I wanted to
depend on, so a small Go daemon reads /dev/video0 directly. It is built with
GOARCH=arm, no cgo, 5.8 MB static.
Without cgo there are no kernel headers, so every structure is a byte slice at the offsets the 32-bit ABI uses. The box's kernel is 64-bit, but its userland is 32-bit, and the compat layer expects 32-bit layouts. The ioctl number encodes the structure's size, so a wrong size fails loudly instead of corrupting memory:
| ioctl | struct | 32-bit size | number |
|---|---|---|---|
VIDIOC_S_FMT | v4l2_format | 204 | 0xc0cc5605 |
VIDIOC_REQBUFS | v4l2_requestbuffers | 20 | 0xc0145608 |
VIDIOC_QBUF / DQBUF | v4l2_buffer | 68 | 0xc044560f / 0xc0445611 |
VIDIOC_QUERYCTRL | v4l2_queryctrl | 68 | 0xc0445624 |
Four memory-mapped buffers, a dequeue/requeue loop, and the newest frame kept in memory. The camera's own controls showed why its picture was soft. It has sharpness, backlight compensation, gain and exposure, and no focus control at all. Raising sharpness from 2 to 5 and backlight compensation from 0 to 1 helped. Moving it so nothing was within a metre of the lens helped far more.
Why the live view lagged, and the fix
The first viewer was an MJPEG stream, a multipart response the daemon kept writing. Over the box's Tailscale link, which tops out around 440 KB/s in userspace mode, that is about 2.5 frames a second of 190 KB each. The camera makes more frames than that.
viewing for 0 s
MJPEG stream (push)
picture is 0.0 s old
Newest snapshot (pull)
picture is 0.4 s old
Run it, or jump ahead ten seconds at a time.
The viewer now asks for /snap, the newest frame, again as soon as the last one has
loaded. Measured: 8.6 frames a second on the home network, 6.1 over Tailscale, each about
0.12–0.17 s old.
The USB bug, and the freeze
Restart the daemon while it is streaming and the next start fails:
xhci-hcd: Trying to add endpoint 0x81 without dropping it.
usb 1-2: Not enough bandwidth for altsetting 3
The box's xhci driver keeps the camera's old endpoint reserved after the process dies.
Unbinding the camera's own USB driver does not clear it. Unbinding and rebinding the whole
host controller does, and so does pulling the cable out. I taught the daemon to do the
controller reset itself after two failures, and it worked, twice, on camera.
About forty minutes later the box froze completely. No ping, no shell, and a loop of
"dududu" from the speakers, which is the last audio buffer repeating while nothing
refills it. A power cycle brought it back. The kernel's saved console log was too short to
show the cause. The controller reset, which had printed a cannot create duplicate filename warning every time it ran, is the prime suspect, so it is gone. If the camera
jams now, the instruction is the honest one: unplug it and plug it back in.
What I would keep, and what I would not
- Keep: one path public, everything else private. Two paths behind a secret is a small enough surface to test from outside in two minutes.
- Keep: the format both ends already speak. No transcoding hop is a hop that cannot fail.
- Keep: polling for "newest" over pushing "everything" whenever the link is slower than the source.
- Don't: automate recovery from a kernel driver bug by poking the kernel driver. The workaround worked until it took the whole box down. A person replugging a cable is slower and never freezes the TV.
- Don't: ship five features in two hours on a box that was bricked that morning.
What they still can't do is answer. The box's sound stack accepts a USB microphone, and the plan is a walkie-talkie reply: after my message plays, the TV offers "जवाफ दिन OK थिच्नुहोस्", and they speak. That one waits until the box has run a week without freezing.
The eight rules I took away from these two days, each with the incident that wrote it, are in Eight rules I now give a coding agent before it touches a real machine.