"""The box's ears: the mics, and when a turn is over. The mics run in their own format, S32_LE stereo at 16 kHz: the Voice HAT's amp and mics share one I2S bus, so the box's earcons play at that rate while the mics listen. """ import array import asyncio import io import logging import math import wave RATE, CHANNELS, SAMPLE_BYTES = 16000, 2, 4 # the mics' own format: S32_LE stereo FRAME_S = 0.03 FRAME_BYTES = int(RATE * FRAME_S) * CHANNELS * SAMPLE_BYTES LEAD_S, TAIL_S = 0.4, 0.3 # kept around the speech, so whisper hears its first word whole ARECORD_ARGS = ("-q", "-D", "hw:CARD=voicehat,DEV=0", "-f", "S32_LE", "-c", str(CHANNELS), "-r", str(RATE), "-t", "raw") def level_db(frame): """Loudness of one frame of S32_LE stereo, in dBFS, from its first channel, DC removed. >>> level_db(array.array('i', [2**30, 0, -2**30, 0] * 240).tobytes()) -6.0 >>> level_db(bytes(16)) -120.0 """ x = array.array('i', frame)[0::CHANNELS] mean = sum(x) / len(x) rms = math.sqrt(sum((v - mean) ** 2 for v in x) / len(x)) return round(max(20 * math.log10(rms / 2**31) if rms else -120.0, -120.0), 1) class Endpointer: """Decide from frame levels when a turn is over. Speech is a frame margin_db above the noise floor; a turn starts after start_frames of speech and ends after end_s without. The floor follows quiet frames down at once, and up slowly. Frames during skip_s (the box's own earcon) are ignored. feed(level) returns None, "done" (spoken, then quiet), "quiet" (nothing said in quiet_s), or "long" (max_s). start and end are frame indexes of the speech. >>> ep = Endpointer(skip_s=0.09, end_s=0.09, quiet_s=0.3) >>> [ep.feed(db) for db in [-40, -40, -40, -78, -77, -50, -48, -50, -78, -78, -78]] [None, None, None, None, None, None, None, None, None, None, 'done'] >>> ep.start, ep.end (5, 7) >>> ep = Endpointer(quiet_s=0.15) >>> [ep.feed(db) for db in [-78] * 5] [None, None, None, None, 'quiet'] >>> ep = Endpointer(max_s=0.15) >>> [ep.feed(db) for db in [-50] * 5] [None, None, None, None, 'long'] """ def __init__(self, skip_s=0.0, margin_db=15, floor_db=-70, start_frames=3, end_s=1.5, quiet_s=8.0, max_s=30.0, frame_s=FRAME_S): self.skip = round(skip_s / frame_s) self.margin, self.floor = margin_db, floor_db self.start_frames = start_frames self.end_frames = round(end_s / frame_s) self.quiet_frames = round(quiet_s / frame_s) self.max_frames = round(max_s / frame_s) self.n, self.run = 0, 0 self.start = self.end = None self.last_speech = None def feed(self, level): i = self.n self.n += 1 if i < self.skip: return None speech = level > self.floor + self.margin if not speech: self.floor = level if level < self.floor else self.floor + 0.05 if self.start is None: self.run = self.run + 1 if speech else 0 if self.run >= self.start_frames: self.start = i - self.start_frames + 1 self.last_speech = i elif i - self.skip + 1 >= self.quiet_frames: return "quiet" elif speech: self.last_speech = i elif self.last_speech is not None and i - self.last_speech >= self.end_frames: self.end = self.last_speech return "done" if self.n >= self.max_frames: self.end = self.last_speech if self.last_speech is not None else i return "long" return None def wav_bytes(frames): """Frames of the mics' raw audio, as a WAV file. >>> data = wav_bytes([bytes(FRAME_BYTES)] * 2) >>> data[:4], len(data) - 44 == 2 * FRAME_BYTES (b'RIFF', True) """ buf = io.BytesIO() with wave.open(buf, "wb") as w: w.setnchannels(CHANNELS) w.setsampwidth(SAMPLE_BYTES) w.setframerate(RATE) w.writeframes(b"".join(frames)) return buf.getvalue() class Mics: """listen(skip_s, button) returns ("speech", wav), ("quiet", None), or ("press", None). arecord is a Command for arecord with ARECORD_ARGS; keep(wav) keeps the latest clip. """ def __init__(self, arecord, keep): self.__arecord, self.__keep = arecord, keep async def listen(self, skip_s, button): proc = await self.__arecord.spawn(stdin=False) ep = Endpointer(skip_s=skip_s + 0.1) # and the mics' startup burst frames = [] try: while True: try: frame = await proc.stdout.readexactly(FRAME_BYTES) except asyncio.IncompleteReadError: await proc.wait() err = (await proc.stderr.read()).decode().strip() raise IOError(f"arecord exit {proc.returncode}: {err}") frames.append(frame) if button.pressed(): if ep.start is None: return ("press", None) ep.end = len(frames) - 1 break outcome = ep.feed(level_db(frame)) if outcome == "quiet": return ("quiet", None) if outcome: break finally: if proc.returncode is None: proc.terminate() await proc.wait() if ep.start is None or ep.end is None: return ("quiet", None) lead, tail = round(LEAD_S / FRAME_S), round(TAIL_S / FRAME_S) wav = wav_bytes(frames[max(ep.start - lead, 0):ep.end + tail + 1]) try: self.__keep(wav) except OSError as err: logging.info(f"keeping the clip failed: {err}") return ("speech", wav)