bolar_2 backup
This commit is contained in:
180
tools/audio_tap_dump.py
Normal file
180
tools/audio_tap_dump.py
Normal file
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Boot-to-shutdown audio recorder for the firmware2 debug audio tap.
|
||||
|
||||
The device (CONFIG_BORLA_AUDIO_TAP=y) buffers everything the microphone
|
||||
captured and everything the DAC played in PSRAM and serves both streams on
|
||||
TCP port 3401. This script connects — retrying until the device boots — and
|
||||
writes each power-on session as a timestamped pair of WAV files:
|
||||
|
||||
firmware2/temp/video/<YYYYMMDD-HHMMSS>-mic.wav (麦克风录入, 24 kHz mono)
|
||||
firmware2/temp/video/<YYYYMMDD-HHMMSS>-spk.wav (喇叭输出, 24 kHz mono)
|
||||
|
||||
Start it BEFORE powering the device on and the files are gapless from the
|
||||
boot prompt (the device pre-buffers ~32 s per channel while waiting for us).
|
||||
When the device shuts down the socket dies, the pair is finalised, and the
|
||||
script goes back to waiting for the next boot. Ctrl+C finalises and exits.
|
||||
|
||||
Usage:
|
||||
python3 tools/audio_tap_dump.py <device-ip> [--port 3401] [--out DIR]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import pathlib
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
MAGIC = b"BTAP"
|
||||
HELLO_SIZE = 16
|
||||
CHANNEL_NAMES = {0: "mic", 1: "spk", 2: "uplink"}
|
||||
|
||||
|
||||
def read_exact(sock: socket.socket, size: int) -> bytes:
|
||||
"""Reads exactly `size` bytes or raises ConnectionError on EOF."""
|
||||
chunks = []
|
||||
remaining = size
|
||||
while remaining > 0:
|
||||
chunk = sock.recv(remaining)
|
||||
if not chunk:
|
||||
raise ConnectionError("device closed the stream")
|
||||
chunks.append(chunk)
|
||||
remaining -= len(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def record_session(sock: socket.socket, out_dir: pathlib.Path) -> None:
|
||||
import wave
|
||||
|
||||
hello = read_exact(sock, HELLO_SIZE)
|
||||
if hello[:4] != MAGIC or hello[4] != 2:
|
||||
raise ConnectionError(f"unexpected hello: {hello!r}")
|
||||
sample_rate = struct.unpack_from("<I", hello, 8)[0]
|
||||
uplink_rate = struct.unpack_from("<I", hello, 12)[0]
|
||||
channel_rates = {0: sample_rate, 1: sample_rate, 2: uplink_rate}
|
||||
|
||||
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
writers = {}
|
||||
paths = {}
|
||||
for channel, name in CHANNEL_NAMES.items():
|
||||
path = out_dir / f"{stamp}-{name}.wav"
|
||||
writer = wave.open(str(path), "wb")
|
||||
writer.setnchannels(1)
|
||||
writer.setsampwidth(2)
|
||||
writer.setframerate(channel_rates[channel])
|
||||
writers[channel] = writer
|
||||
paths[channel] = path
|
||||
print(f"[tap] session {stamp} started, "
|
||||
f"mic/spk {sample_rate} Hz, uplink {uplink_rate} Hz")
|
||||
for path in paths.values():
|
||||
print(f"[tap] -> {path}")
|
||||
|
||||
received = {channel: 0 for channel in CHANNEL_NAMES}
|
||||
try:
|
||||
while True:
|
||||
header = read_exact(sock, 4)
|
||||
channel = header[0]
|
||||
payload_size = header[2] | (header[3] << 8)
|
||||
payload = read_exact(sock, payload_size)
|
||||
writer = writers.get(channel)
|
||||
if writer is not None:
|
||||
writer.writeframes(payload)
|
||||
received[channel] += payload_size
|
||||
finally:
|
||||
for channel, writer in writers.items():
|
||||
writer.close()
|
||||
seconds = received[channel] / 2 / channel_rates[channel]
|
||||
print(f"[tap] closed {paths[channel]} ({seconds:.1f}s)")
|
||||
|
||||
|
||||
def local_subnet_hosts():
|
||||
"""Yields the /24 neighbours of this machine's primary interface."""
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.connect(("8.8.8.8", 80))
|
||||
local_ip = probe.getsockname()[0]
|
||||
except OSError:
|
||||
return []
|
||||
finally:
|
||||
probe.close()
|
||||
prefix = local_ip.rsplit(".", 1)[0]
|
||||
return [f"{prefix}.{host}" for host in range(1, 255)
|
||||
if f"{prefix}.{host}" != local_ip]
|
||||
|
||||
|
||||
def discover_device(port: int) -> str:
|
||||
"""Scans the local /24 for the one host listening on the tap port."""
|
||||
import concurrent.futures
|
||||
|
||||
def probe(ip: str):
|
||||
try:
|
||||
with socket.create_connection((ip, port), timeout=0.4):
|
||||
return ip
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
hosts = local_subnet_hosts()
|
||||
while True:
|
||||
if hosts:
|
||||
with concurrent.futures.ThreadPoolExecutor(64) as pool:
|
||||
for found in pool.map(probe, hosts):
|
||||
if found:
|
||||
print(f"[tap] found device at {found}")
|
||||
return found
|
||||
print("[tap] no device on the LAN yet, rescanning in 3 s "
|
||||
"(power the device on; Ctrl+C to stop)")
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"device_ip", nargs="?", default=None,
|
||||
help="device IP address (omit to auto-scan the local network)")
|
||||
parser.add_argument("--port", type=int, default=3401)
|
||||
parser.add_argument(
|
||||
"--out",
|
||||
default=None,
|
||||
help="output directory (default: <firmware2>/temp/video)")
|
||||
arguments = parser.parse_args()
|
||||
|
||||
firmware_root = pathlib.Path(__file__).resolve().parent.parent
|
||||
out_dir = (pathlib.Path(arguments.out)
|
||||
if arguments.out
|
||||
else firmware_root / "temp" / "video")
|
||||
|
||||
device_ip = arguments.device_ip
|
||||
try:
|
||||
if device_ip is None:
|
||||
device_ip = discover_device(arguments.port)
|
||||
print(f"[tap] waiting for {device_ip}:{arguments.port} "
|
||||
f"(power the device on now; Ctrl+C to stop)")
|
||||
while True:
|
||||
try:
|
||||
sock = socket.create_connection(
|
||||
(device_ip, arguments.port), timeout=3)
|
||||
except OSError:
|
||||
# DHCP can hand the device a different address next boot;
|
||||
# fall back to a rescan instead of camping on a stale IP.
|
||||
if arguments.device_ip is None:
|
||||
device_ip = discover_device(arguments.port)
|
||||
else:
|
||||
time.sleep(1)
|
||||
continue
|
||||
sock.settimeout(None)
|
||||
try:
|
||||
record_session(sock, out_dir)
|
||||
except ConnectionError as error:
|
||||
print(f"[tap] session ended: {error}")
|
||||
finally:
|
||||
sock.close()
|
||||
print("[tap] waiting for next boot...")
|
||||
except KeyboardInterrupt:
|
||||
print("\n[tap] stopped")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user