知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix(linux): with the microphone open, the meeting recording keeps your own voice too (#19)
wquguru5e780105a105
diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.pyindex 9b7f57e..c6124b3 100644--- a/linux/cicada/core/listen.py+++ b/linux/cicada/core/listen.py@@ -27,6 +27,89 @@ _END = object()ROOM_IDS = 1_000_000+class RoomMix:+ """电脑和会议室 keeps one recording, as the Mac does: the room lane's samples are added into the+ computer's at the same place on the meeting's clock (each lane counts the samples it heard). The+ computer's audio waits `DELAY` before it is written, so a room buffer that arrives a little after+ the computer's is still mixed in; what the room says after the computer's last sample follows it."""++ DELAY = RATE # 1 s+ LIMIT = 30 * RATE # the computer's audio stalled: older room audio goes rather than piling up++ def __init__(self, rec):+ self.rec = rec+ self._lock = threading.Lock()+ self._main = array("h") # the computer's audio not written yet+ self._at = 0 # where on the clock self._main[0] is (everything before it is written)+ self._room = array("h")+ self._room_at = 0 # where on the clock self._room[0] is++ def write(self, buf) -> None:+ """The computer's audio (the main lane), in order."""+ with self._lock:+ self._main.extend(buf)+ out = self._take(len(self._main) - self.DELAY)+ if out:+ self.rec.write(out)++ def room(self, buf, at: int) -> None:+ """The room lane's audio; `at`: its first sample's place on the clock."""+ with self._lock:+ end = self._room_at + len(self._room)+ if not self._room:+ self._room_at = at+ elif at > end:+ self._room.frombytes(bytes(2 * (at - end))) # the room side stopped a while: silence+ elif at < end:+ buf = buf[end - at:]+ self._room.extend(buf)+ self._drop(self._at)+ over = len(self._room) - self.LIMIT+ if over > 0:+ del self._room[:over]+ self._room_at += over++ def close(self) -> None:+ """Everything still held goes into the file, then the recorder closes."""+ with self._lock:+ out = self._take(len(self._main))+ if self._room and self._room_at >= self._at:+ out.frombytes(bytes(2 * (self._room_at - self._at)))+ out.extend(self._room)+ self._room = array("h")+ if out:+ self.rec.write(out)+ self.rec.close()++ def finish(self, until=None) -> None:+ self.rec.finish(until)++ def _drop(self, upto: int) -> None:+ """Room audio for a place already written: too late to mix."""+ late = min(len(self._room), upto - self._room_at)+ if late > 0:+ del self._room[:late]+ self._room_at += late++ def _take(self, n: int):+ """The next `n` samples of the computer's audio with the room's added."""+ if n <= 0:+ return array("h")+ out, self._main = self._main[:n], self._main[n:]+ start, self._at = self._at, self._at + n+ self._drop(start)+ if self._room and self._room_at < self._at:+ off = self._room_at - start+ k = min(len(self._room), self._at - self._room_at)+ room = self._room+ for i in range(k):+ v = out[off + i] + room[i]+ out[off + i] = 32767 if v > 32767 else -32768 if v < -32768 else v+ del self._room[:k]+ self._room_at += k+ return out++class _Lane:"""One audio source's way through listening: its segments, their replies put back in order, itslast line and the language it hears. 电脑和会议室 runs two, as the Mac runs a main and a room@@ -77,7 +160,8 @@ class ListenEngine:self.session_id = None# 保存会议录音: `recorder(sid)` gives the meeting's recorder (write(samples), close(), finish(until))# or None; set by the app when GStreamer can encode AAC. What the main lane hears is written,- # buffer for buffer, so the file's clock is the lines' clock (t counts the samples heard).+ # buffer for buffer, so the file's clock is the lines' clock (t counts the samples heard);+ # 电脑和会议室's room lane is added in at its place on that clock (RoomMix).self.recorder = Noneself._recording = Noneself.source_kind = None # what this meeting is heard from ("system", "room", "file")@@ -208,7 +292,8 @@ class ListenEngine:self._recording = Noneif self.recorder is not None:try:- self._recording = self.recorder(session.id)+ rec = self.recorder(session.id)+ self._recording = RoomMix(rec) if rec is not None else Noneexcept Exception as e: # noqa: BLE001 - a recording that can't start never stops listeningLog.d("listen: no recording (%s)" % type(e).__name__)# Listening before the source starts: a source that fails at once calls on_ended → stop(),@@ -222,12 +307,13 @@ class ListenEngine:def _run(self, lane, at: float = 0.0) -> None:"""`at`: where in the meeting this lane begins (seconds), so its lines' times are the meeting's."""segmenter = Segmenter()- segmenter.consumed = int(at * RATE)+ segmenter.consumed = clock = int(at * RATE)segmenter.on_segment = lambda seg: self._send(lane, seg)q: queue.Queue = queue.Queue()lane.audio = qdef work():+ nonlocal clock# One worker owns the segmenter: audio callbacks only queue buffers.while True:buf = q.get()@@ -238,8 +324,13 @@ class ListenEngine:# Silence rather than nothing keeps the segmenter's clock in step.buf = array("h", bytes(len(buf) * 2))rec = self._recording- if rec is not None and lane is self._main:- rec.write(buf)+ if rec is not None:+ # The room side too, into the same file (#19): heard and kept, as on the Mac.+ if lane is self._main:+ rec.write(buf)+ else:+ rec.room(buf, clock)+ clock += len(buf)now = time.monotonic()if lane is not self._main and self.gated:# What the mic really hears, for EchoGate's measurement, before any silencing.diff --git a/linux/tests/test_recording.py b/linux/tests/test_recording.pyindex 35267e9..8fa6d42 100644--- a/linux/tests/test_recording.py+++ b/linux/tests/test_recording.py@@ -16,7 +16,8 @@ sys.path.insert(0, HERE)import test_core as tc # noqa: E402 - its helpers; a module import, so its tests aren't collected twicefrom cicada.core import aac # noqa: E402from cicada.core.audio import RATE, PcmAudioSource # noqa: E402-from cicada.core.listen import ListenEngine # noqa: E402+from cicada.core.listen import ListenEngine, RoomMix # noqa: E402+from array import array # noqa: E402from cicada.core.models import TranscriptLine # noqa: E402from cicada.core.notes import NotesEngine # noqa: E402from cicada.core.session_store import SessionStore # noqa: E402@@ -79,6 +80,7 @@ class HasAudio(tc.Base):class FakeRecorder:def __init__(self):self.samples = 0+ self.pcm = array("h")self.closed = Falseself.finished = threading.Event()self.until = "unset"@@ -86,6 +88,7 @@ class FakeRecorder:def write(self, buf):assert not self.closedself.samples += len(buf)+ self.pcm.extend(buf)def close(self):self.closed = True@@ -144,5 +147,72 @@ class Recording(tc.Base):engine.stop()+def loud(pcm, a, b):+ """The largest sample between a and b seconds."""+ return max((abs(v) for v in pcm[int(a * RATE):int(b * RATE)]), default=0)+++class Mix(unittest.TestCase):+ """电脑和会议室: the room mic goes into the meeting's one recording, at its place on the clock (#19)."""++ def test_the_room_is_added_where_it_was_heard(self):+ rec = FakeRecorder()+ mix = RoomMix(rec)+ for i in range(30): # 3 s of the computer at 1000, in 0.1 s buffers; the room at 500 from 1 s to 2 s+ mix.write(array("h", [1000] * 1600))+ if 10 <= i < 20:+ mix.room(array("h", [500] * 1600), i * 1600)+ mix.close()+ self.assertTrue(rec.closed)+ self.assertEqual(3 * RATE, rec.samples)+ self.assertEqual(1000, loud(rec.pcm, 0, 1))+ self.assertEqual(1500, loud(rec.pcm, 1, 2))+ self.assertEqual(1000, loud(rec.pcm, 2, 3))++ def test_a_room_buffer_a_little_late_is_still_mixed(self):+ rec = FakeRecorder()+ mix = RoomMix(rec)+ for i in range(20):+ mix.write(array("h", [0] * 1600))+ if i >= 5: # the room's buffer for each 0.1 s arrives half a second after the computer's+ mix.room(array("h", [700] * 1600), (i - 5) * 1600)+ mix.close()+ self.assertEqual(700, min(rec.pcm[:int(1.5 * RATE)]))++ def test_the_room_alone_is_the_recording_and_it_clips_instead_of_wrapping(self):+ rec = FakeRecorder()+ mix = RoomMix(rec)+ mix.write(array("h", [30000] * 1600))+ mix.room(array("h", [30000] * 1600), 0)+ mix.room(array("h", [800] * 1600), 2 * RATE) # the computer stopped sending: the room goes on+ mix.close()+ self.assertEqual(32767, rec.pcm[0])+ self.assertEqual(2 * RATE + 1600, rec.samples)+ self.assertEqual(0, loud(rec.pcm, 0.2, 2))+ self.assertEqual(800, rec.pcm[-1])++ def test_both_lanes_end_up_in_the_file(self):+ from test_hybrid import both_engine+ store = SessionStore()+ e = both_engine(store, "x")+ rec = FakeRecorder()+ e.recorder = lambda sid: rec+ # In real time, as the sound server sends them: the computer's tone 0-1 s, the room's 0.5-2.1 s.+ main = PcmAudioSource(lambda: tc.concat(tc.tone(1.0), tc.silence(1.0)), speed=1)+ room = PcmAudioSource(lambda: tc.concat(tc.silence(0.5), tc.tone(1.6, amp=0.2), tc.silence(0.4)), speed=1)+ done = [threading.Event(), threading.Event()]+ main.on_ended = lambda why: done[0].set()+ room.on_ended = lambda why: done[1].set()+ e.start(main, "both")+ e.start_room(room, gated=False)+ for d in done:+ d.wait(10)+ time.sleep(0.3)+ e.stop()+ self.assertTrue(rec.closed)+ self.assertTrue(rec.finished.wait(5))+ self.assertGreater(loud(rec.pcm, 1.2, 2.0), 3000, "the room's tone, after the computer's ended")++if __name__ == "__main__":unittest.main()diff --git a/site/changelog.json b/site/changelog.jsonindex 3e9c52c..9020d3b 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -9,7 +9,8 @@{"kind": "fixed","platforms": [- "mac"+ "mac",+ "linux"],"title": "打开麦克风时,会议录音里也有自己的声音。","text": "以前打开麦克风后,麦克风这一路只记文字,不存原声:会后只能回放电脑里对方的声音。现在两边录在同一个录音里,回放时都听得到。用扬声器开会时,录音里对方的声音会叠一点从麦克风收进来的回声。"