The small white Xiaomi Xiaofang (model iSC5, isa.camera.isc5) can be a local RTSP camera, and it can play sound through its speaker. The path is fang-hacks on the Sonix SN98600, plus a tiny RTSP proxy in front of go2rtc. It is a different camera from the Yi and Tuya units in the previous two-way audio guide.
This SoC is Sonix. The Dafang procedure (Ingenic,
cfw.binrenamed todemo.bin, RTSP on port 8554, flashing with the SETUP button) can brick an iSC5. SETUP is only for stock pairing and for the official Sonix downgrade below.
Frigate shows the microphone button when three things are true at once:
audio, sendonly.The stock fang-hacks RTSP server does not advertise a return channel. The proxy adds one. The speaker itself is a userspace player from fang-hacks issue #305. No firmware patch is required for the audio.
CAMERA_IP in every command below is the camera address on your LAN.The speaker on this model is quiet. A blinking rear LED does not always mean it is offline. Confirm with DHCP, ARP, or HTTP. There is no boot beep. A beep when the card is inserted means snx_autorun.sh ran.
Download the 0.2.0 SD image from the fang-hacks releases. The FAT partition gets bootstrap/ and snx_autorun.sh. The ext2 partition gets data/.
On the FAT partition, write the Wi-Fi client files with no trailing newline:
printf '%s' 'YOUR_SSID' > .wifissid
printf '%s' 'YOUR_PASSWORD' > .wifipasswd
In the fang-hacks config, stay local:
HACKS_ENABLED=1
DISABLE_CLOUD=1
NETWORK_MODE=1
Firmware 3.2.x mounts the card and logs SD can Insert, then never runs snx_autorun.sh. The SD log is XOR 0x09. If it says 3.2.2_112 (or another 3.2.x), downgrade before expecting RTSP.
The official SD downgrade is documented in the fang-hacks wiki:
upd_isa.camera.isc5.bin.extracted from firmware 3.0.3.56 onto the FAT partition.0.elf to FIRMWARE_660R.bin.FIRMWARE_660R.bin once RTSP works, so a later SETUP press cannot flash again. Leave the .cramfs files where they are.Hot-plug the card. Power on with no card, insert it while the camera is already running, wait for the insert beep, then boot again with the card left in. Booting with the card already seated does not copy the Wi-Fi files. The upstream README says to wait until the blue LED stops flashing. On the unit this was written from, the LED kept blinking after the camera already answered ping, so check the network.
Open http://CAMERA_IP/cgi-bin/status and apply the hack once. Boa does not answer that CGI until fang_hacks.sh exits, and the script drops Wi-Fi while it reboots. A client timeout with an empty body is normal. Wait for the camera to come back. The page should say the script is already installed. Do not start a second Apply.
RTSP is the hardware encoder:
snx_rtsp_server -W 1920 -H 1080 -Q 10 -b 4096 -a
rtsp://CAMERA_IP/unicast
Port 554. Keep -a. That flag is the microphone towards the client. The SDP has H.264 on track1 and pcm_alaw at 8 kHz on track2. There is no a=sendonly.
ffprobe -rtsp_transport tcp -i rtsp://CAMERA_IP/unicast
While 1080p was streaming, this SoC sat around load 0.05 with about 17 MB free of 36 MB. The H.264 encoder is hardware. A software RTSP server does not fit. A return audio path does.
Point go2rtc at the camera. Frigate then reads go2rtc, same as any other camera:
go2rtc:
streams:
xiaofang:
- rtsp://CAMERA_IP/unicast#tcp
cameras:
xiaofang:
enabled: true
ffmpeg:
inputs:
- path: rtsp://127.0.0.1:8554/xiaofang
roles:
- detect
- record
Leave the camera enabled. An enabled: false left over from when the camera was offline shows 0 fps in Frigate while ffprobe still gets a picture.
snx_rtsp_server does not accept return audio. The player from the #305 zip does. snx_audio_playback is a 32-bit ARM ELF. The good file is exactly 30617 bytes and starts with \x7fELF. A short or truncated copy will not play.
Copy it to the ext2 partition, for example /media/mmcblk0p2/data/usr/bin/snx_audio_playback. The volume helper ships with fang-hacks.
Open the speaker, set the volume, then play raw PCM from a file or from stdin:
gpio_ms1 -n 7 -m 1 -v 1
/media/mmcblk0p2/data/test/audio/snx_audio_vol_ctl -d spk -v 15
snx_audio_playback -d s16 -s 32k -f /tmp/test.wav
-d s16 -s 32k means signed 16-bit little-endian, mono, 32 kHz. That is 64000 bytes per second. Guides that resample this player to 16 kHz are aimed at a different binary. A two-second file returned PLAY_RC:0 here while snx_rtsp_server -a kept sending microphone RTP. The GPIO dance from issue #310 was not required.
A listener for later, saved as /media/mmcblk0p2/data/etc/scripts/22-speaker (mode 755, LF), next to the other numbered scripts:
#!/bin/sh
# Raw speaker backchannel: s16le 32 kHz mono on TCP 11032.
if netstat -ltn 2>/dev/null | grep -q ':11032 '; then
exit 0
fi
gpio_ms1 -n 7 -m 1 -v 1
/media/mmcblk0p2/data/test/audio/snx_audio_vol_ctl -d spk -v 15 >/dev/null 2>&1
/media/mmcblk0p2/data/usr/bin/tcpsvd -E 0.0.0.0 11032 \
/media/mmcblk0p2/data/usr/bin/snx_audio_playback -d s16 -s 32k -f - \
>/tmp/spk.log 2>&1 &
Anything that connects and writes PCM is played. There is no password. Do not forward port 11032. A TCP connect wakes the player, so do not probe the port just to see if it is open. Check with netstat on the camera.
This boot script was installed and the listener was started by hand. It has not been proven across a camera reboot. After the next power cycle, netstat -ltn | grep 11032 on the camera is the check. If the port is missing, run the script once.
go2rtc can attach a return channel with an exec: source. Frigate 0.18 deletes exec:, echo:, expr:, and ${VAR} sources while it builds /dev/shm/go2rtc.yaml, unless GO2RTC_ALLOW_ARBITRARY_EXEC is set. That switch is remote code execution on the Frigate host. Leave it off, especially if the UI has no auth and port 1984 is published.
A wrapper that injected the exec: line after create_config.py still failed the UI. The producer had no medias, so Frigate never drew the microphone. The default pipe codec is PCML at 16 kHz, which is also the wrong rate for this player.
The live view looks at the active producer's medias and shows the button only when that string contains audio, sendonly. The stream list is cached for about a minute. Reload the page after the producer changes.
The proxy listens on 127.0.0.1:8556 inside the Frigate container. It forwards the camera and appends an ONVIF-style track:
m=audio 0 RTP/AVP 8
a=rtpmap:8 PCMA/8000
a=sendonly
a=control:track3
SETUP for track3 is answered locally and is not sent to the camera. Talk RTP is G.711 a-law. Each decoded sample is repeated four times (8 kHz to 32 kHz) and written to tcp://CAMERA_IP:11032 with the container ffmpeg. On the Frigate 0.18 image that binary is /usr/lib/ffmpeg/8.0/bin/ffmpeg, not on PATH. Video RTP is copied. RTP is held until the PLAY response, otherwise $ interleaved bytes land in the RTSP status line.
Rewrite only the rtsp://CAMERA_IP prefix. Replacing the bare IP also corrupts the SDP o= line. Drop every old Content-Length and write one new length after the extra track. The last header does not always have a trailing CRLF, and a regex that requires \r\n will leave a duplicate length.
Save this as /config/xiaofang_talk_proxy.py (mode 755, LF). Change CAMERA_IP.
#!/usr/bin/env python3
"""RTSP proxy for a Sonix Xiaofang (fang-hacks).
Forwards the camera stream and adds an ONVIF-style sendonly PCMA track.
Talk audio is resampled to s16le 32 kHz and sent to the speaker on TCP 11032.
Video packets are copied through. This process must stay up for that camera.
Change CAMERA_IP before use. Frigate 0.18 strips exec: sources, so this
proxy is what makes the live-view microphone appear.
"""
import queue
import re
import socket
import subprocess
import threading
CAMERA_IP = "192.168.1.50"
LISTEN = ("127.0.0.1", 8556)
CAMERA = (CAMERA_IP, 554)
PROXY_HOST = "127.0.0.1:8556"
CAMERA_HOST = CAMERA_IP
FFMPEG = "/usr/lib/ffmpeg/8.0/bin/ffmpeg"
SPEAKER = "tcp://%s:11032" % CAMERA_IP
_alaw = None
def alaw_table():
global _alaw
if _alaw is not None:
return _alaw
table = []
for i in range(256):
a = i ^ 0x55
quant = a & 0x0F
seg = (a & 0x70) >> 4
if seg == 0:
sample = (quant << 4) + 8
else:
sample = ((quant << 4) + 0x108) << (seg - 1)
if not (a & 0x80):
sample = -sample
table.append(sample)
_alaw = table
return table
def rtp_payload(packet):
if len(packet) < 12:
return b""
cc = packet[0] & 0x0F
header = 12 + 4 * cc
if packet[0] & 0x10:
if len(packet) < header + 4:
return b""
ext = int.from_bytes(packet[header + 2 : header + 4], "big")
header += 4 + ext * 4
if len(packet) < header:
return b""
return packet[header:]
class Speaker:
def __init__(self):
self.proc = None
self.lock = threading.Lock()
self.table = alaw_table()
self.chunks = queue.Queue(maxsize=25)
self.alive = True
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
def write_alaw(self, payload):
if not payload or not self.alive:
return
pcm = bytearray()
table = self.table
for byte in payload:
sample = table[byte]
pcm += sample.to_bytes(2, "little", signed=True) * 4
try:
self.chunks.put_nowait(bytes(pcm))
except queue.Full:
return
def _run(self):
while self.alive:
try:
pcm = self.chunks.get(timeout=0.5)
except queue.Empty:
continue
with self.lock:
proc = self._ensure()
if proc is None:
continue
try:
proc.stdin.write(pcm)
proc.stdin.flush()
except (BrokenPipeError, OSError):
self._stop_locked()
def _ensure(self):
if self.proc is not None and self.proc.poll() is None:
return self.proc
self.proc = subprocess.Popen(
[
FFMPEG,
"-hide_banner",
"-loglevel",
"error",
"-fflags",
"nobuffer",
"-probesize",
"32",
"-analyzeduration",
"0",
"-f",
"alaw",
"-ar",
"8000",
"-ac",
"1",
"-i",
"pipe:0",
"-f",
"s16le",
"-ar",
"32000",
"-ac",
"1",
SPEAKER,
],
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return self.proc
def _stop_locked(self):
proc = self.proc
self.proc = None
if proc is None:
return
try:
if proc.stdin:
proc.stdin.close()
except OSError:
pass
try:
proc.wait(timeout=1)
except subprocess.TimeoutExpired:
proc.kill()
def close(self):
self.alive = False
with self.lock:
self._stop_locked()
def read_some(sock, buf):
chunk = sock.recv(8192)
if not chunk:
raise ConnectionError("closed")
return buf + chunk
def pop_item(sock, buf):
while True:
if not buf:
buf = read_some(sock, buf)
continue
if buf[0:1] == b"$":
if len(buf) < 4:
buf = read_some(sock, buf)
continue
length = int.from_bytes(buf[2:4], "big")
need = 4 + length
while len(buf) < need:
buf = read_some(sock, buf)
packet = buf[1:need]
return ("rtp", packet[0], packet[3:]), buf[need:]
header_end = buf.find(b"\r\n\r\n")
if header_end < 0:
buf = read_some(sock, buf)
continue
header = buf[: header_end + 4]
match = re.search(br"(?im)^content-length:\s*(\d+)\s*$", header)
body_len = int(match.group(1)) if match else 0
total = header_end + 4 + body_len
while len(buf) < total:
buf = read_some(sock, buf)
return ("rtsp", buf[:total]), buf[total:]
def content_length(message):
match = re.search(br"(?im)^content-length:\s*(\d+)\s*$", message)
return int(match.group(1)) if match else 0
def rewrite_urls(blob):
return blob.replace(
b"rtsp://" + CAMERA_IP.encode(),
b"rtsp://" + PROXY_HOST.encode(),
)
def rewrite_response(message):
head, _, body = message.partition(b"\r\n\r\n")
lines = [rewrite_urls(line) for line in head.split(b"\r\n")]
lines = [line for line in lines if not line.lower().startswith(b"content-length:")]
if b"m=video" not in body and b"application/sdp" not in head.lower():
text = b"\r\n".join(lines)
if body:
text += b"\r\n\r\n" + rewrite_urls(body)
elif message.endswith(b"\r\n\r\n"):
text += b"\r\n\r\n"
return text, False
body = rewrite_urls(body)
if b"a=control:track3" not in body:
extra = (
b"m=audio 0 RTP/AVP 8\r\n"
b"a=rtpmap:8 PCMA/8000\r\n"
b"a=sendonly\r\n"
b"a=control:track3\r\n"
)
if body and not body.endswith(b"\r\n"):
body += b"\r\n"
body += extra
lines.append(b"Content-Length: " + str(len(body)).encode())
return b"\r\n".join(lines) + b"\r\n\r\n" + body, True
def session_of(message):
match = re.search(br"(?im)^session:\s*([^;\r\n]+)", message)
return match.group(1).strip() if match else None
def local_setup(request, session):
cseq = re.search(br"(?im)^cseq:\s*(\d+)", request)
inter = re.search(br"interleaved=(\d+)-(\d+)", request, re.I)
cseq_n = cseq.group(1) if cseq else b"1"
if inter is None:
transport = b"RTP/AVP/TCP;unicast;interleaved=4-5"
channels = (4, 5)
else:
transport = b"RTP/AVP/TCP;unicast;interleaved=%s-%s" % (inter.group(1), inter.group(2))
channels = (int(inter.group(1)), int(inter.group(2)))
sid = session or b"xf-talk"
response = (
b"RTSP/1.0 200 OK\r\n"
b"CSeq: " + cseq_n + b"\r\n"
b"Session: " + sid + b"\r\n"
b"Transport: " + transport + b"\r\n"
b"\r\n"
)
return response, channels
def rewrite_request(message):
return message.replace(PROXY_HOST.encode(), CAMERA_HOST.encode())
def is_track3(message):
first = message.split(b"\r\n", 1)[0]
return first.startswith(b"SETUP ") and b"track3" in first
def serve(client):
upstream = socket.create_connection(CAMERA, timeout=8)
client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
upstream.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
client.settimeout(None)
upstream.settimeout(None)
speaker = Speaker()
state = {
"session": None,
"back": set(),
"lock": threading.Lock(),
"hold_rtp": True,
"held": [],
}
def send_client(data):
with state["lock"]:
client.sendall(data)
def client_loop():
buf = b""
try:
while True:
item, buf = pop_item(client, buf)
if item[0] == "rtp":
channel, payload = item[1], item[2]
if channel in state["back"]:
speaker.write_alaw(rtp_payload(payload))
else:
upstream.sendall(b"$" + bytes((channel,)) + len(payload).to_bytes(2, "big") + payload)
continue
message = item[1]
if is_track3(message):
response, channels = local_setup(message, state["session"])
state["back"].update(channels)
send_client(response)
continue
if message.startswith(b"PLAY "):
state["hold_rtp"] = True
upstream.sendall(rewrite_request(message))
except (ConnectionError, OSError):
pass
finally:
speaker.close()
try:
upstream.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def camera_loop():
buf = b""
try:
while True:
item, buf = pop_item(upstream, buf)
if item[0] == "rtp":
if state["hold_rtp"]:
if len(state["held"]) < 200:
state["held"].append(item)
continue
channel, payload = item[1], item[2]
send_client(b"$" + bytes((channel,)) + len(payload).to_bytes(2, "big") + payload)
continue
message = item[1]
sid = session_of(message)
if sid:
state["session"] = sid
rewritten, _added = rewrite_response(message)
send_client(rewritten)
play_ok = message.startswith(b"RTSP/1.0 200") and (
b"RTP-Info:" in message or b"\r\nRange:" in message
)
if state["hold_rtp"] and play_ok:
state["hold_rtp"] = False
held = state["held"]
state["held"] = []
for held_item in held:
channel, payload = held_item[1], held_item[2]
send_client(b"$" + bytes((channel,)) + len(payload).to_bytes(2, "big") + payload)
except (ConnectionError, OSError):
pass
finally:
try:
client.shutdown(socket.SHUT_RDWR)
except OSError:
pass
threading.Thread(target=camera_loop, daemon=True).start()
client_loop()
try:
client.close()
except OSError:
pass
try:
upstream.close()
except OSError:
pass
def main():
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(LISTEN)
server.listen(2)
print("xiaofang talk proxy on %s:%s" % LISTEN, flush=True)
while True:
client, addr = server.accept()
print("client", addr, flush=True)
threading.Thread(target=serve, args=(client,), daemon=True).start()
if __name__ == "__main__":
main()
The go2rtc s6 service deletes /dev/shm/go2rtc.yaml, regenerates it from your config, then execs /config/go2rtc when that path is executable. A Python wrapper there can start the proxy and rewrite the generated URL, then replace itself with the real go2rtc binary.
Your config.yaml keeps the direct camera URL from Step 2. The wrapper swaps that one string for rtsp://127.0.0.1:8556/unicast#tcp in the generated file. Delete /config/go2rtc and restart the service to go back to the direct stream. Talk disappears with it. If the proxy dies while go2rtc stays up, that camera's picture goes black until the service starts the wrapper again.
Save this as /config/go2rtc (mode 755, LF shebang). The same CAMERA_IP must match the URL in config.yaml.
#!/usr/bin/env python3
"""Start the Xiaofang talk proxy, point go2rtc at it, then run real go2rtc.
Frigate 0.18 removes exec: sources unless arbitrary exec is enabled. Leave
that switch off. The proxy adds the sendonly audio track the live view needs
for the microphone button.
Install this file as /config/go2rtc inside the Frigate container and chmod 755.
The s6 run script uses it instead of /usr/local/go2rtc/bin/go2rtc when it is
executable. CAMERA_IP must match the URL in config.yaml.
"""
import os
import socket
import subprocess
import sys
import time
CAMERA_IP = "192.168.1.50"
REAL = "/usr/local/go2rtc/bin/go2rtc"
CFG = "/dev/shm/go2rtc.yaml"
PROXY = "/config/xiaofang_talk_proxy.py"
DIRECT = "rtsp://%s/unicast#tcp" % CAMERA_IP
VIA_PROXY = "rtsp://127.0.0.1:8556/unicast#tcp"
def proxy_up():
try:
sock = socket.create_connection(("127.0.0.1", 8556), timeout=0.4)
except OSError:
return False
sock.close()
return True
def start_proxy():
if proxy_up():
print("[xiaofang-talk] proxy already up", flush=True)
return True
log = open("/tmp/xiaofang-talk.log", "ab", buffering=0)
subprocess.Popen(
["python3", PROXY],
stdout=log,
stderr=log,
start_new_session=True,
)
for _ in range(30):
if proxy_up():
print("[xiaofang-talk] proxy started", flush=True)
return True
time.sleep(0.1)
print("[xiaofang-talk] proxy failed, keeping direct RTSP", flush=True)
return False
def patch(use_proxy):
if not os.path.isfile(CFG):
print("[xiaofang-talk] no go2rtc yaml", flush=True)
return
text = open(CFG, encoding="utf-8").read()
if use_proxy and DIRECT in text:
text = text.replace(DIRECT, VIA_PROXY)
open(CFG, "w", encoding="utf-8").write(text)
print("[xiaofang-talk] stream pointed at proxy", flush=True)
return
if use_proxy and VIA_PROXY in text:
print("[xiaofang-talk] stream already uses proxy", flush=True)
return
print("[xiaofang-talk] direct stream left unchanged", flush=True)
patch(start_proxy())
os.execv(REAL, [REAL, *sys.argv[1:]])
Restart only go2rtc. s6-svc is not on PATH in this image. The restart blips every live view for a few seconds.
docker exec frigate /command/s6-svc -r /run/s6-rc/servicedirs/go2rtc
The container name on a stock Compose file is often frigate. Use the name you actually have. The log should contain:
[WARN] Using go2rtc binary from '/config/go2rtc'
[xiaofang-talk] proxy started
[xiaofang-talk] stream pointed at proxy
DESCRIBE the proxy from inside the container:
docker exec frigate python3 -c "import socket; s=socket.create_connection(('127.0.0.1',8556),timeout=8); s.sendall(b'DESCRIBE rtsp://127.0.0.1:8556/unicast RTSP/1.0\r\nCSeq: 1\r\nAccept: application/sdp\r\n\r\n'); print(s.recv(8000).decode(errors='replace'))"
Expect one Content-Length, Content-Base on rtsp://127.0.0.1:8556/unicast/, H.264 track1, PCMA track2, and a=sendonly with a=control:track3.
Then the producer:
docker exec frigate python3 -c "import json,urllib.request; d=json.load(urllib.request.urlopen('http://127.0.0.1:1984/api/streams', timeout=8)); print(d['xiaofang']['producers'])"
One producer should list video, recvonly, H264, audio, recvonly, PCMA/8000, and audio, sendonly, PCMA/8000.
Reload the Frigate UI over HTTPS, open the WebRTC live view, and use the microphone icon. Give the speaker a second. It is quiet.
An optional file test does make a noise. Skip it unless you want to hear the speaker. Generate a short PCM tone and send it with ffmpeg at 32 kHz, or post a PCMA file to the go2rtc API as a temporary source. An empty src= on that API can remove sources. Stop the ffmpeg that is writing to port 11032 when you have heard enough, and leave the proxy process running.
On the camera this was built on:
ffprobe got a real 1920x1080 frame plus pcm_alaw. Frigate detect ran at 4 fps.snx_audio_playback returned PLAY_RC:0 while RTSP -a stayed up.track3 sendonly. SETUP and PLAY returned 200, and RTP followed the PLAY response.audio, sendonly, PCMA/8000.Still open: the boot script across a camera reboot, and a person confirming the browser microphone in the live view. The tone test is not that confirmation.
http://CAMERA_IP/cgi-bin/status says the fang-hacks script is installed.ffprobe rtsp://CAMERA_IP/unicast shows H.264 and pcm_alaw. The server command still has -a.snx_audio_playback is 30617 bytes and port 11032 is listening on the camera./config/go2rtc is the wrapper, executable, LF shebang.127.0.0.1:8556 includes a=sendonly on track3.audio, sendonly, PCMA/8000.