Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(linux): Listen to › Computer + Room hears people online and at the table together, and marks each line In room or Online

wquguru1bafda07870f
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index 08d9c7a..5939d74 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -12,7 +12,8 @@ per connection, one JSON line back. Never in release builds.
ai-check-sim <reason|lowBalance|off> (every check ends this way: screenshots of each state) | ai-check (check now)
ask settings|fix|close (answer the 开始听 dialog a failed check put up) | settings-ai (设置 at AI 服务) | tray-menu
pill (the records window capsule's widget sizes)
- listen-source system|room|both (听哪里) | room-mic [<source>|auto] | lines [<record id>] (each line's via)"""
+ listen-source system|room|both (听哪里) | room-mic [<source>|auto] | lines [<record id>] (each line's via)
+ online both|no (answer 线上也有人?) | room-mic-force <source>|"" (a null sink's monitor as the room mic)"""
from __future__ import annotations
import os
@@ -120,7 +121,10 @@ def command(app, line: str) -> dict:
"lines": len(s.lines) if s else 0, "last": {"src": last.src, "dst": last.dst, "lang": last.srcLang} if last else None,
"pending": listen.pending, "problem": listen.problem, "problemKind": listen.problem_kind, "heardSeconds": round(listen.heard_seconds, 1),
"peak": round(listen.peak, 4), "notes": {"title": n.title, "topics": len(n.topics), "status": app.notes.status, "final": n.final},
- "key": app.ling.key_state, "ai": _ai(app), "view": app.settings.view, "listenSource": app.settings.listenSource, "target": app.settings.target_code,
+ "key": app.ling.key_state, "ai": _ai(app), "view": app.settings.view, "listenSource": app.settings.listenSource,
+ "hybrid": {"roomSide": listen.hears_room_too, "echoCancel": app.echo.on, "gated": listen.gated,
+ "note": app.hybrid_note(), "onlinePrompt": app.online_prompt},
+ "target": app.settings.target_code,
"ui": __import__("cicada.core.strings", fromlist=["language"]).language, "records": len(app.store.all()),
"tray": app.tray is not None, "home": Paths.data(),
"speak": {"enabled": app.settings.speakEnabled, "room": app.room.on, "active": app.speak.active, "stage": app.speak.stage,
@@ -165,6 +169,12 @@ def command(app, line: str) -> dict:
if cmd == "listen-source": # 听哪里 (system|room|both), mid-meeting too
app.set_listen_source(arg)
return {"ok": True, "listenSource": app.settings.listenSource, "source": listen.source_kind}
+ if cmd == "online": # answer 线上也有人? (both|no)
+ app.answer_online(arg == "both")
+ return {"ok": True, "listenSource": app.settings.listenSource}
+ if cmd == "room-mic-force": # any source as the room mic, e.g. a null sink's monitor ("" = off)
+ app.forced_room_mic = arg or None
+ return {"ok": True, "forced": app.forced_room_mic}
if cmd == "room-mic": # which microphone 会议室 would use now; with an argument, choose it ("" = 自动)
if arg:
app.settings.roomMic = "" if arg == "auto" else arg
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index 72c1c45..e1d24c6 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -79,8 +79,14 @@ class Controller:
self.listen = ListenEngine(self.ling, self.translator, self.store, self.notes, self.settings)
# 同声传译: my microphone → the AI service → 知了 麦克风. The listen side's loudness feeds its echo check.
from ..core.speak import SpeakEngine
- from .room import Player, VirtualMic
+ from .room import EchoCanceller, Player, VirtualMic
self.room = VirtualMic()
+ # 电脑和会议室: the online voices taken out of the room mic (module-echo-cancel).
+ self.echo = EchoCanceller()
+ self.online_prompt = None # 线上也有人?: the meeting app in a call, while only the room is heard
+ self.online_answered = False
+ self.headset_default = False # the default input is a Bluetooth headset's (the room uses another mic)
+ self.forced_room_mic = None
self.speak = SpeakEngine(self.ling, self.translator, self.settings, self.store, self.listen, player=lambda: Player())
self.listen.loudness = self.speak.loudness
# 说话人识别: voiceprints (native/voiceprint.c), Ling's guesses at names.
@@ -137,6 +143,7 @@ class Controller:
self.tray = tray.make(self, icon)
def prepare():
(self.room.create if self.settings.speakEnabled else self.room.leftovers)()
+ self.echo.remove() # left by a run that crashed during 电脑和会议室
if speak: # `cicada --speak` before Cicada was running: speak once 知了 麦克风 is there
GLib.idle_add(lambda: self.toggle_speaking() and False)
threading.Thread(target=prepare, daemon=True).start()
@@ -387,6 +394,8 @@ class Controller:
def room_mic(self) -> str:
"""The microphone that hears the room now (roommic.pick). 知了 麦克风 as the default input
(同声传译 on) stands for the real microphone it took the place of."""
+ if self.forced_room_mic: # debug: a null sink's monitor standing in for one (a VM has no microphone)
+ return self.forced_room_mic
inputs = roommic.parse_sources(capture.sources_text())
default = capture.default_source()
if default == "cicada_mic":
@@ -398,7 +407,10 @@ class Controller:
return picked
def heard_source(self):
- """(source, kind) for 听哪里: the computer's audio, or the room through a microphone."""
+ """(source, kind) for 听哪里: the computer's audio, or the room through a microphone. For
+ 电脑和会议室 the computer's audio; the room side starts beside it (_start_room_side)."""
+ if self.settings.listenSource == "both":
+ return SystemAudio(), "both"
if self.settings.listenSource == "room":
mic = self.room_mic()
if mic is not None:
@@ -414,11 +426,84 @@ class Controller:
self.settings.listenSource = value
self.settings.save()
Log.d("listenSource=%s" % value)
- if self.listen.listening and self.listen.source_kind in ("system", "room"):
+ if self.listen.listening and self.listen.source_kind != "file":
+ if self.listen.hears_room_too:
+ self._stop_room_side()
+ # The canceller first: it changes the default output, which the computer's audio is read from.
+ room = self._room_side_source() if value == "both" else None
source, kind = self.heard_source()
source.on_ended = self._source_ended(kind)
self.listen.source_kind = kind
self.listen.attach(source, mic=kind == "room")
+ if room is not None:
+ self.listen.start_room(*room)
+ self.changed()
+
+ def _room_side_source(self):
+ """(source, gated) for 电脑和会议室's room side, or None without a microphone: the room mic
+ through the echo canceller; without one (or the sound server won't) the plain mic, gated
+ while the computer plays speech. 戴着耳机: nothing comes out of the speakers to cancel."""
+ mic = self.room_mic()
+ if mic is None:
+ Log.d("hybrid: no microphone, the computer's audio only")
+ return None
+ default = capture.default_source()
+ bt = [i.name for i in roommic.parse_sources(capture.sources_text()) if i.bluetooth]
+ self.headset_default = (self.room.real_mic if default == "cicada_mic" else default) in bt
+ cancelled = None if self.settings.speakHeadphones else self.echo.create(mic)
+ if cancelled is None and not self.settings.speakHeadphones:
+ Log.d("hybrid: no echo cancellation, gating the room mic")
+ source = SystemAudio(cancelled or mic, L("知了 · 会议室"))
+ source.on_ended = self._room_lost
+ return source, cancelled is None and not self.settings.speakHeadphones
+
+ def _start_room_side(self) -> None:
+ room = self._room_side_source()
+ if room is not None:
+ self.listen.start_room(*room)
+
+ def _room_lost(self, why) -> None:
+ """The room side's microphone went away (unplugged, the sound server gone for 20 s): another
+ one takes over if there is one; otherwise the computer's audio goes on alone."""
+ def run():
+ if self.listen.listening and self.listen.hears_room_too and why:
+ Log.d("hybrid: room microphone lost (%s)" % why)
+ self._stop_room_side()
+ self._start_room_side()
+ self.changed()
+ return False
+ GLib.idle_add(run)
+
+ def _stop_room_side(self) -> None:
+ self.listen.stop_room()
+ if self.echo.on:
+ self.echo.remove()
+
+ def set_headphones(self, on: bool) -> None:
+ """戴着耳机 (同声传译's and 会议室's): in 电脑和会议室 the room side starts again with or without
+ taking the speakers' sound out."""
+ if on == self.settings.speakHeadphones:
+ return
+ self.settings.speakHeadphones = on
+ self.settings.save()
+ if self.listen.listening and self.listen.hears_room_too:
+ self._stop_room_side()
+ self._start_room_side()
+ self.changed()
+
+ def hybrid_note(self) -> str | None:
+ """The grey line under 听哪里 in 电脑和会议室 (roommic.hybrid_note)."""
+ key = roommic.hybrid_note(self.listen.hears_room_too, self.echo.on, self.settings.speakHeadphones,
+ self.headset_default)
+ return L(key) if key == "线上有人说话时,先不听会议室" else L("用电脑自带的麦克风听会议室") if key else None
+
+ def answer_online(self, both: bool) -> None:
+ """线上也有人? answered: 也听电脑 turns 电脑和会议室 on in the same meeting; 不用 just goes."""
+ self.online_answered = True
+ self.online_prompt = None
+ Log.d("online prompt: %s" % ("both" if both else "no"))
+ if both:
+ self.set_listen_source("both")
self.changed()
def _source_ended(self, kind: str):
@@ -504,7 +589,12 @@ class Controller:
self.auto_ended = False
self.ending = None
self.end_watch = meeting_end.MeetingEndWatch(self.end_config(), time.time())
+ self.online_answered = False
+ self.online_prompt = None
+ room = self._room_side_source() if kind == "both" else None
self.listen.start(source, kind, mic=kind == "room")
+ if room is not None:
+ self.listen.start_room(*room)
self.show_notes()
self.changed()
@@ -599,6 +689,12 @@ class Controller:
s = self.store.get(self.listen.session_id) if self.listen.session_id else None
reason = w.tick(now, calls, bool(s and s.lines))
self._set_ending(w.pending)
+ ask = roommic.asks_online(self.listen.source_kind == "room", self.online_answered, bool(calls))
+ prompt = next(iter(calls.values()), None) if ask else None
+ if prompt != self.online_prompt:
+ self.online_prompt = prompt
+ Log.d("online prompt: %s" % ("shown" if prompt else "gone"))
+ self.changed()
if reason is not None:
self._auto_end(reason, w)
elif not self.listen.listening and self.auto_ended and self.settings.endWithApp and calls:
@@ -705,9 +801,13 @@ class Controller:
self.auto_ended = auto
# stop() waits for Ming's last replies: off the main loop.
+ self.online_prompt = None
+
def run():
sid = self.listen.session_id
self.listen.stop(ended_at)
+ if self.echo.on:
+ self.echo.remove() # the speakers are the default output again
if sid and self.settings.speakerVoices:
self.namer.guess(sid, force=True) # the whole meeting read once more for names
self.changed()
@@ -811,6 +911,8 @@ class Controller:
self.speak.cancel()
if self.room.on:
self.room.remove() # the real microphone is the default again
+ if self.echo.on:
+ self.echo.remove()
if self.listen.listening:
self.listen.stop()
self.store.flush()
diff --git a/linux/cicada/app/notes_window.py b/linux/cicada/app/notes_window.py
index 92f8087..f29c08d 100644
--- a/linux/cicada/app/notes_window.py
+++ b/linux/cicada/app/notes_window.py
@@ -14,7 +14,7 @@ from datetime import datetime, timezone
from gi.repository import Gdk, GLib, Gtk
from ..core import notes as notesmod
-from ..core import speakers
+from ..core import roommic, speakers
from ..core.strings import L, LF
from ..core.support import Log, clock
from . import ui, x11
@@ -158,7 +158,7 @@ class NotesWindow(Gtk.Window):
ui.pad(self.header, 8, 8, 4, 16)
outer.pack_start(self.header, False, False, 0)
# 听哪里 while listening (正在听 · 会议室 换 ⌄): changed here, the same meeting goes on.
- self.source_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
+ self.source_row = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
self.source_row.set_no_show_all(True)
if not self.subtitles:
outer.pack_start(ui.pad(self.source_row, 0, 16, 4, 16), False, False, 0)
@@ -317,11 +317,29 @@ class NotesWindow(Gtk.Window):
return
from .tray import sources
names = dict(sources())
- row.pack_start(ui.text(names.get(self.app.settings.listenSource, ""), 12, "secondary", wrap=False), False, False, 0)
+ line = ui.hbox(6, ui.text(names.get(self.app.settings.listenSource, ""), 12, "secondary", wrap=False))
change = ui.link(L("换") + " ⌄", lambda: self._source_menu(change))
change.set_can_focus(False)
- row.pack_start(change, False, False, 0)
- row.show_all()
+ line.pack_start(change, False, False, 0)
+ row.pack_start(line, False, False, 0)
+ # How the room is heard when it isn't the plain way (one grey line, the Mac's HybridNote).
+ note = self.app.hybrid_note()
+ if note:
+ row.pack_start(ui.text(note, 11, "tertiary", width_chars=40), False, False, 0)
+ # 线上也有人?: only the room is heard while a meeting app here is in a call.
+ app_name = self.app.online_prompt
+ if app_name:
+ strip = ui.vbox(8, ui.vbox(2, ui.text(L("线上也有人?"), 13, "ink", bold=True, wrap=False),
+ ui.text(LF("%@ 正在通话", app_name), 12, "secondary", wrap=False)))
+ buttons = ui.hbox(8, ui.button(L("也听电脑"), lambda: self.app.answer_online(True), "darkbtn"),
+ ui.button(L("不用"), lambda: self.app.answer_online(False), "outline"))
+ for b in buttons.get_children():
+ b.set_can_focus(False)
+ strip.pack_start(buttons, False, False, 0)
+ row.pack_start(ui.gap(ui.panel(ui.pad(strip, 12, 14), "endingstrip"), 4), False, False, 0)
+ for c in row.get_children():
+ c.show_all()
+ row.show() # show_all() skips a no_show_all widget itself
def _source_menu(self, widget) -> None:
from .tray import sources
@@ -483,7 +501,8 @@ class NotesWindow(Gtk.Window):
names = speakers.names(session) if voices else {}
pending = self.app.listen.listening and self.app.listen.pending > 0
topics = [(t.start, t.title) for t in self.app.notes.notes.topics]
- key = (len(lines), lines[-1].id if lines else None, (lines[-1].dst or "") if lines else "", tuple(terms), current,
+ self._places = roommic.heard_both(lines) # 电脑和会议室: each of their lines says where
+ key = (self._places, len(lines), lines[-1].id if lines else None, (lines[-1].dst or "") if lines else "", tuple(terms), current,
tuple(sorted(nums.items())), tuple(sorted(names.items())), pending, tuple(topics))
self._fill_search_tools()
if key == self._transcript_key and not scroll:
@@ -547,6 +566,8 @@ class NotesWindow(Gtk.Window):
elif l.id in nums:
n = nums[l.id]
top.pack_start(ui.text(speakers.label(n, names), 11, "spk%d" % ((n - 1) % 4 + 1), bold=True, wrap=False, ellipsize=False), False, False, 0)
+ if l.speaker != "me" and getattr(self, "_places", False):
+ top.pack_start(ui.place_tag(l), False, False, 0)
top.pack_start(ui.text(clock(l.t), 11, "tertiary", wrap=False, ellipsize=False), False, False, 0)
row.pack_start(top, False, False, 0)
if l.dst and l.dst != l.src:
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
index 43cbbd7..13f8b64 100644
--- a/linux/cicada/app/records_window.py
+++ b/linux/cicada/app/records_window.py
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta, timezone
from gi.repository import Gdk, Gio, GLib, Gtk
-from ..core import session_store, speakers
+from ..core import roommic, session_store, speakers
from ..core.strings import L, LF
from ..core.support import SOURCES, TARGETS, Log, clock
from . import ui
@@ -629,7 +629,8 @@ class RecordsWindow(Gtk.Window):
if s.lines:
src, dst = s.lines[0].srcLang, s.lines[0].dstLang
langs = " · " + (lang_name(src) if src == dst else lang_name(src) + " → " + lang_name(dst))
- place = " · " + L("会议室") if s.room else "" # heard through a microphone in the room, as on the Mac
+ # Heard through a microphone in the room, and with the computer's audio too: as on the Mac.
+ place = " · " + (L("电脑和会议室") if roommic.heard_both(s.lines) else L("会议室")) if s.room else ""
return "%s · %s · %d %s%s%s" % (session_store._local_date(s.startedAt, L("M月d日 HH:mm")), L("正在听") if live else clock(s.duration),
len(s.lines), L("句"), langs, place)
@@ -659,7 +660,7 @@ class RecordsWindow(Gtk.Window):
self.columns.reorder_child(new, 0)
new.show_all()
self._nums = speakers.numbers(s.lines) if self._vnums else {}
- starts = speakers.run_starts(s.lines, self._nums)
+ starts = self._starts(s.lines)
for i, l in enumerate(s.lines[:len(self._rows)]):
if self._rows[i][0] != self._row_key(l, l.id in starts):
old_row = self._rows[i][1]
@@ -783,6 +784,7 @@ class RecordsWindow(Gtk.Window):
self.transcript = col
self._both = s.sourceFile is None and any(l.speaker == "me" for l in s.lines)
self._nums, self._vnums, self._shown = self._speakers(s)
+ self._places = roommic.heard_both(s.lines)
self._speaker_key = self._speaker_state_key(s)
self._sid = s.id
if self._vnums:
@@ -804,7 +806,9 @@ class RecordsWindow(Gtk.Window):
def _speaker_state_key(self, s):
_n, vnums, shown = self._speakers(s)
busy = s.id in self.app.namer.busy
- return (tuple(sorted(vnums.items())), tuple(sorted(shown.items())), str(sorted((s.voiceGuesses or {}).keys())), busy)
+ # The room side's first line in 电脑和会议室: every line of theirs now says where it was heard.
+ return (tuple(sorted(vnums.items())), tuple(sorted(shown.items())), str(sorted((s.voiceGuesses or {}).keys())), busy,
+ roommic.heard_both(s.lines))
def _row_key(self, l, start):
return (l.id, l.src, l.dst, l.voice, start)
@@ -976,8 +980,11 @@ class RecordsWindow(Gtk.Window):
texts = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
# Whose it is, where the speaker changes (as chat apps do): with voices told apart, or in a
# meeting I spoke in through 同声传译.
- if start and (self._both or self._vnums):
- texts.pack_start(self._speaker_label(l), False, False, 0)
+ if start and (self._both or self._vnums or self._places):
+ label = self._speaker_label(l)
+ if self._places and l.speaker != "me":
+ label = ui.hbox(6, label, ui.place_tag(l))
+ texts.pack_start(label, False, False, 0)
translated = l.dst and l.dst != l.src
texts.pack_start(ui.text(l.dst if translated else l.src, 13, "ink", selectable=True, width_chars=46,
lang=l.dstLang if translated else l.srcLang), False, False, 0)
@@ -987,6 +994,11 @@ class RecordsWindow(Gtk.Window):
ui.pad(row, 9, 0, 9, 0)
return self._row_key(l, start), ui.panel(row, "transcript-row")
+ def _starts(self, lines) -> set:
+ """Lines whose speaker label shows: a change of speaker, or in 电脑和会议室 of place too."""
+ starts = speakers.run_starts(lines, self._nums)
+ return starts | roommic.place_starts(lines) if self._places else starts
+
def _more_rows(self, first: bool = False) -> None:
"""Rows not shown yet: the first screenful at once, the rest in batches between frames, so
a two-hour meeting opens instantly."""
@@ -999,7 +1011,7 @@ class RecordsWindow(Gtk.Window):
if s is None:
return False
lines = s.lines
- starts = speakers.run_starts(lines, self._nums)
+ starts = self._starts(lines)
for l in lines[len(self._rows):len(self._rows) + count]:
k, row = self._row(l, l.id in starts)
self.transcript.pack_start(row, False, False, 0)
diff --git a/linux/cicada/app/room.py b/linux/cicada/app/room.py
index ae22130..3b7567f 100644
--- a/linux/cicada/app/room.py
+++ b/linux/cicada/app/room.py
@@ -45,6 +45,8 @@ def _lib():
l.pa_context_get_module_info_list.argtypes = [ctypes.c_void_p, _MODULE_CB, ctypes.c_void_p]
l.pa_context_set_default_source.restype = ctypes.c_void_p
l.pa_context_set_default_source.argtypes = [ctypes.c_void_p, ctypes.c_char_p, _SUCCESS_CB, ctypes.c_void_p]
+ l.pa_context_set_default_sink.restype = ctypes.c_void_p
+ l.pa_context_set_default_sink.argtypes = [ctypes.c_void_p, ctypes.c_char_p, _SUCCESS_CB, ctypes.c_void_p]
l._room_ready = True
return l
@@ -124,6 +126,12 @@ class _Session:
pass
self.wait(self.l.pa_context_set_default_source(self.ctx, name.encode(), done, None))
+ def set_default_sink(self, name: str) -> None:
+ @_SUCCESS_CB
+ def done(_c, _ok, _u):
+ pass
+ self.wait(self.l.pa_context_set_default_sink(self.ctx, name.encode(), done, None))
+
def close(self) -> None:
self.l.pa_context_disconnect(self.ctx)
self.l.pa_context_unref(self.ctx)
@@ -230,6 +238,96 @@ class VirtualMic:
s.close()
+AEC_SINK = "cicada_aec_out"
+AEC_MIC = "cicada_aec_mic"
+
+
+def _real_sink_path() -> str:
+ return os.path.join(os.path.dirname(Paths.log()), "real-sink")
+
+
+class EchoCanceller:
+ """电脑和会议室: the online voices taken out of the room mic, so a remote sentence isn't heard
+ twice and the room can talk over it (the Mac's voice-processing unit). One sound-server module,
+ module-echo-cancel (WebRTC's canceller, in PipeWire and PulseAudio):
+
+ cicada_aec_out an output in front of the speakers, made the default while it runs: what it
+ plays is what the canceller takes out (the meeting app's voices)
+ cicada_aec_mic the room microphone with them taken out: the room side listens to it
+
+ Removed when 电脑和会议室 stops, on 退出, SIGTERM, and after a crash at the next launch; the
+ output that was the default is the default again each time."""
+
+ def __init__(self):
+ self.on = False
+ try:
+ with open(_real_sink_path()) as f:
+ self.real_sink = f.read().strip() or None
+ except OSError:
+ self.real_sink = None
+
+ @staticmethod
+ def _ours(modules) -> list:
+ return [i for i, name, arg in modules if name == "module-echo-cancel" and ("sink_name=" + AEC_SINK) in arg]
+
+ def create(self, mic: str) -> str | None:
+ """Puts the canceller between `mic` and the speakers; the source to listen to, or None when the
+ sound server won't (the room is then gated instead)."""
+ try:
+ s = _Session()
+ except OSError:
+ return None
+ try:
+ if not s.ok:
+ return None
+ self._give_back(s)
+ sink = s.server().get("sink")
+ if not sink or sink == AEC_SINK:
+ return None
+ self.real_sink = sink
+ try:
+ with open(_real_sink_path(), "w") as f:
+ f.write(sink)
+ except OSError:
+ pass
+ out_desc = L("知了 · 防回声").replace("'", "")
+ index = s.load("module-echo-cancel",
+ "aec_method=webrtc source_master=%s sink_master=%s source_name=%s sink_name=%s "
+ "source_properties=\"device.description='%s'\" sink_properties=\"device.description='%s'\""
+ % (mic, sink, AEC_MIC, AEC_SINK, out_desc, out_desc))
+ if index is None:
+ Log.d("echo cancel: module not loaded")
+ return None
+ s.set_default_sink(AEC_SINK)
+ self.on = True
+ Log.d("echo cancel: on, in front of the default output")
+ return AEC_MIC
+ finally:
+ s.close()
+
+ def _give_back(self, s) -> None:
+ if s.server().get("sink") == AEC_SINK and self.real_sink:
+ s.set_default_sink(self.real_sink)
+ for index in self._ours(s.modules()):
+ s.unload(index)
+
+ def remove(self) -> None:
+ """Also what launch does (a crash may have left it): harmless when there is nothing to remove."""
+ try:
+ s = _Session()
+ except OSError:
+ return
+ try:
+ if s.ok:
+ had = bool(self._ours(s.modules()))
+ self._give_back(s)
+ if had:
+ Log.d("echo cancel: removed")
+ self.on = False
+ finally:
+ s.close()
+
+
class Player:
"""Plays 24 kHz mono 16-bit PCM into a sink: 知了 麦克风's (the room) or, for 试听, the speakers."""
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index 6fd1f87..b1e9ff3 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -418,9 +418,10 @@ class SettingsWindow(Gtk.Window):
phones.set_valign(Gtk.Align.CENTER)
def phones_toggled(sw, _p):
- s.speakHeadphones = sw.get_active()
- s.save()
+ self.app.set_headphones(sw.get_active())
+ self.room_phones.set_active(sw.get_active()) # 会议室's 戴着耳机 is the same setting
phones.connect("notify::active", phones_toggled)
+ self.speak_phones = phones
phones_row = ui.prow(L("戴着耳机"), phones, L("和对方同时说的话也会传出去"))
dependents.append(phones_row)
rows.append(phones_row)
@@ -460,7 +461,18 @@ class SettingsWindow(Gtk.Window):
if s.roomMic and all(v != s.roomMic for v, _ in options):
options.append((s.roomMic, s.roomMic)) # chosen before, not plugged in now
mic = choice(options, s.roomMic, set_mic)
- rows = [ui.prow(L("听哪里"), where), ui.prow(L("麦克风"), mic, L("戴着蓝牙耳机时,自动用电脑自带的麦克风"))]
+ # 戴着耳机, the same setting as 同声传译's: nothing comes out of the speakers, so no echo to take out.
+ phones = Gtk.Switch()
+ phones.set_active(s.speakHeadphones)
+ phones.set_valign(Gtk.Align.CENTER)
+ def toggled(sw, _p):
+ app.set_headphones(sw.get_active())
+ if getattr(self, "speak_phones", None) is not None:
+ self.speak_phones.set_active(sw.get_active())
+ phones.connect("notify::active", toggled)
+ self.room_phones = phones
+ rows = [ui.prow(L("听哪里"), where), ui.prow(L("麦克风"), mic, L("戴着蓝牙耳机时,自动用电脑自带的麦克风")),
+ ui.prow(L("戴着耳机"), phones, L("戴着就不用防回声,桌边的话不会被丢;和同声传译共用这个开关"))]
return self._group(L("会议室"), ui.boxed(rows)), [where, mic]
def _group(self, title, body, footer=None) -> Gtk.Widget:
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index 523d10e..494f373 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -13,6 +13,8 @@ gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, Gio, GLib, Gtk, Pango # noqa: E402
+from ..core.strings import L # noqa: E402
+
CSS = b"""
* { font-family: "Noto Sans", sans-serif; font-size: 13px; }
.ground { background-color: #F3F4F6; }
@@ -148,6 +150,9 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
.chip { background-color: #F2F3F5; border-radius: 5px; padding: 1px 6px; color: #15171C; }
.chip.now { background-color: #E8552B; color: #FFFFFF; }
.chip.time { background-color: transparent; padding: 0; color: #B33A14; }
+.placetag { border-radius: 4px; border: 1px solid #E4E6EA; }
+.placetag.room { background-color: #F2F3F5; border-color: #F2F3F5; }
+.placetag label { color: #5A5F6B; }
.badge { background-color: #FDEEE8; border-radius: 5px; padding: 0 6px; color: #B33A14; }
.softcard { background-color: #F5F6F8; border-radius: 12px; }
.summarycard { background-color: #F5F6F8; border-radius: 12px; }
@@ -261,6 +266,9 @@ button.pillkeep label { color: #15171C; }
.panel.dark .chip { background-color: #34363D; color: #F2F3F5; }
.panel.dark .chip.now { background-color: #E8552B; }
.panel.dark .chip.time { background-color: transparent; color: #F08A6C; }
+.panel.dark .placetag { border-color: #44474F; }
+.panel.dark .placetag.room { background-color: #34363D; border-color: #34363D; }
+.panel.dark .placetag label { color: #A3A7B1; }
.panel.dark .link { color: #F08A6C; }
.panel.dark .badge { background-color: rgba(232,85,43,0.18); color: #F08A6C; }
.panel.dark button.iconbtn:hover { background-color: rgba(255,255,255,0.08); }
@@ -629,6 +637,18 @@ def ring_pixbuf(fraction: float, px: int = 26, track: str = "#3A3D45", color: st
return loader.get_pixbuf()
+def place_tag(line) -> Gtk.Widget:
+ """现场 / 线上 beside the other side's label in a meeting that heard both (the Mac's PlaceTag): filled
+ for the room microphone, outlined for the computer's audio."""
+ room = line.via == "room"
+ l = text(L("现场") if room else L("线上"), 10, "", wrap=False, ellipsize=False)
+ pad(l, 0, 5) # a margin: GTK 3 ignores CSS padding on an EventBox
+ c = panel(l, "placetag", *(["room"] if room else []))
+ c.set_valign(Gtk.Align.CENTER)
+ c.set_tooltip_text(L("会议室的麦克风听到的") if room else L("电脑里放出来的"))
+ return c
+
+
def chip(s: str, now: bool = False) -> Gtk.Widget:
l = text(s, 11, "", bold=True, wrap=False, ellipsize=False)
if now:
diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.py
index e8a15df..37ff20b 100644
--- a/linux/cicada/core/listen.py
+++ b/linux/cicada/core/listen.py
@@ -17,12 +17,14 @@ from . import strings
from .audio import RATE, Wav
from .ling import LingError
from .models import TranscriptLine
-from .roommic import VoiceGate
+from .roommic import EchoGate, EchoMatch, Heard, VoiceGate
from .segmenter import Segmenter
from .support import Log, english_name, is_cjk_language
from .translator import Translator
_END = object()
+# Segment numbers from here up are the room side's (the Mac's ListenEngine.roomIDs).
+ROOM_IDS = 1_000_000
class _Lane:
@@ -61,6 +63,13 @@ class ListenEngine:
self._gate = threading.RLock()
self._pool = ThreadPoolExecutor(max_workers=8, thread_name_prefix="Listen")
self._main = _Lane()
+ self._room = None # 电脑和会议室's room side, while it runs
+ # Without echo cancellation the room mic hears silence while the computer plays speech.
+ self.echo_gate = EchoGate()
+ self.gated = False
+ self._recent_online: list = [] # the computer's lines of the last 20 s, as EchoMatch.Heard
+ self._held: list = [] # room lines waiting EchoMatch.hold for the computer's line they may echo
+ self._main_loud_at = 0.0
self._in_flight: list = []
self._line_count = 0
self._listeners = []
@@ -147,8 +156,9 @@ class ListenEngine:
@property
def spoken(self):
+ """The language the other side has been speaking (the room's, when only the room has spoken)."""
with self._gate:
- return self._hint
+ return self._main.hint or (self._room.hint if self._room is not None else None)
@property
def pending(self) -> int:
@@ -157,7 +167,12 @@ class ListenEngine:
return sum(len(l.segments) for l in self._lanes())
def _lanes(self) -> list:
- return [self._main]
+ return [self._main] + ([self._room] if self._room is not None else [])
+
+ @property
+ def hears_room_too(self) -> bool:
+ """电脑和会议室: the room side is running."""
+ return self._room is not None
def start(self, source, kind: str, mic: bool = False) -> None:
"""Listens to `source`; `mic` when it is a microphone in the room (会议室): speech is told
@@ -169,6 +184,8 @@ class ListenEngine:
self.source_kind = kind
with self._gate:
self._main = _Lane()
+ self._room = None
+ self._recent_online, self._held = [], []
self._in_flight.clear()
self._line_count = 0
self.problem = self.problem_kind = None
@@ -199,6 +216,9 @@ class ListenEngine:
if lane.muted:
# Silence rather than nothing keeps the segmenter's clock in step.
buf = array("h", bytes(len(buf) * 2))
+ now = time.monotonic()
+ if lane is not self._main and self.gated and self.echo_gate.closed(now):
+ buf = array("h", bytes(len(buf) * 2))
level = Wav.rms(buf)
gate = lane.gate
if gate is not None:
@@ -209,8 +229,14 @@ class ListenEngine:
segmenter.feed(buf)
lane.level = level
lane.peak = max(lane.peak * 0.995, level)
- if lane is self._main and self.loudness is not None and gate is None:
- self.loudness.add(level >= Segmenter.threshold)
+ if lane is self._main and gate is None:
+ loud = level >= Segmenter.threshold
+ if self.loudness is not None:
+ self.loudness.add(loud)
+ if loud:
+ self._main_loud_at = now
+ if self.gated:
+ self.echo_gate.hold(now)
lane.heard_seconds += seconds
segmenter.flush()
lane.worker = threading.Thread(target=work, name="ListenWorker", daemon=True)
@@ -225,6 +251,9 @@ class ListenEngine:
old.on_samples = None
old.stop()
lane.gate = VoiceGate(adaptive=True) if mic else None
+ # Lines heard through a microphone say "room", so a meeting that changes between 会议室 and
+ # 电脑和会议室 still labels each line by where it was heard (one place alone shows no labels).
+ lane.via = "room" if mic else None
if mic and self.session_id:
self.store.mark_room(self.session_id)
lane.source = source
@@ -234,10 +263,43 @@ class ListenEngine:
Log.d("listen: source changed to %s" % ("a microphone" if mic else "the computer's audio"))
def set_muted(self, on: bool) -> None:
- """会议室 while 同声传译 hears me through the same microphone: my words aren't the room's."""
- if self._main.gate is not None and self._main.muted != on:
- self._main.muted = on
- Log.d("listen: room mic %s" % ("muted" if on else "open"))
+ """The room mic while 同声传译 hears me through the same microphone: my words aren't the room's."""
+ for lane in self._lanes():
+ if lane.gate is not None and lane.muted != on:
+ lane.muted = on
+ Log.d("listen: room mic %s" % ("muted" if on else "open"))
+
+ def start_room(self, source, gated: bool) -> None:
+ """电脑和会议室: the room side, on its own microphone, beside the computer's audio. Its lines say
+ "room"; it keeps its own language and pauses. `gated`: no echo cancellation, so the room mic
+ hears silence while the computer plays speech."""
+ if not self.listening or self._room is not None:
+ return
+ lane = _Lane(via="room", first=ROOM_IDS)
+ lane.gate = VoiceGate(adaptive=True)
+ lane.muted = any(l.muted for l in self._lanes())
+ self.gated = gated
+ self._run(lane)
+ with self._gate:
+ self._room = lane
+ self.store.mark_room(self.session_id)
+ lane.source = source
+ source.on_samples = lane.audio.put
+ source.start()
+ Log.d("listen: room side started (%s)" % ("gated" if gated else "echo cancelled"))
+ self._changed()
+
+ def stop_room(self) -> None:
+ """The room side stops; its lines still waiting for their echo check are what was said: kept."""
+ with self._gate:
+ lane, self._room = self._room, None
+ if lane is None:
+ return
+ self._end_lane(lane)
+ self._release_all()
+ self.gated = False
+ Log.d("listen: room side stopped")
+ self._changed()
def stop(self, ended_at=None) -> None:
"""Stops listening, waits (briefly) for segments still at Ming, ends the record (at `ended_at`
@@ -251,6 +313,9 @@ class ListenEngine:
with self._gate:
waiting = list(self._in_flight)
wait(waiting, timeout=15)
+ self._release_all()
+ self._room = None
+ self.gated = False
sid = self.session_id
if sid is None:
return
@@ -334,11 +399,70 @@ class ListenEngine:
ready.append((lane.segments.pop(lane.next), heard))
lane.next += 1
for seg, heard in ready:
- if heard is not None:
+ if heard is None:
+ continue
+ if lane is not self._main: # the room side of 电脑和会议室
+ self._heard_in_room(lane, seg, heard)
+ else:
self._record(lane, seg, heard)
+ self._heard_online(heard.original, seg.seconds)
if ready:
self._changed()
+ # 电脑和会议室: the room's copy of an online sentence (EchoMatch)
+
+ def _heard_online(self, text: str, seconds: float) -> None:
+ """A sentence from the computer's audio, remembered to tell the room's copy of it; room lines
+ waiting for it that turn out to be its echo are dropped."""
+ if self._room is None:
+ return
+ now = time.monotonic()
+ with self._gate:
+ self._recent_online.append(Heard(text, now - seconds, now))
+ self._recent_online = [h for h in self._recent_online if h.end >= now - 20]
+ online = list(self._recent_online)
+ dropped = [h for h in self._held if EchoMatch.is_echo(h[3], online)]
+ self._held = [h for h in self._held if h not in dropped]
+ for _ in dropped:
+ Log.d("listen: room line dropped as an echo")
+
+ def _heard_in_room(self, lane, seg, heard) -> None:
+ """A sentence from the room mic: an echo of the computer's audio is dropped; the rest waits a
+ moment for the computer's line it may echo, then is recorded where it was said."""
+ now = time.monotonic()
+ h = Heard(heard.original, now - seg.seconds, now)
+ with self._gate:
+ online = list(self._recent_online)
+ if EchoMatch.is_echo(h, online):
+ Log.d("listen: room line dropped as an echo")
+ return
+ # The computer has played nothing for a while: nothing for this to echo, no need to wait.
+ if now - self._main_loud_at >= EchoMatch.window:
+ self._record(lane, seg, heard)
+ return
+ entry = (lane, seg, heard, h)
+ with self._gate:
+ self._held.append(entry)
+ timer = threading.Timer(EchoMatch.hold, self._release, (entry,))
+ timer.daemon = True
+ timer.start()
+
+ def _release(self, entry) -> None:
+ with self._deliver_lock:
+ with self._gate:
+ if entry not in self._held:
+ return
+ self._held.remove(entry)
+ self._record(*entry[:3])
+ self._changed()
+
+ def _release_all(self) -> None:
+ with self._deliver_lock:
+ with self._gate:
+ held, self._held = self._held, []
+ for entry in held:
+ self._record(*entry[:3])
+
def _voice(self, seg, heard):
"""The segment's voice, or None when unsure. A line with hardly a letter ("." from a breath or
a click) gets no voiceprint; like the Mac, every labelled segment counts towards its voice."""
diff --git a/linux/cicada/core/roommic.py b/linux/cicada/core/roommic.py
index 1992e17..bdae471 100644
--- a/linux/cicada/core/roommic.py
+++ b/linux/cicada/core/roommic.py
@@ -3,6 +3,8 @@ plays (the Mac's RoomMic.swift). Pure: which microphone, and when a block of it
The capture itself is app/capture.py's SystemAudio on a source instead of a monitor."""
from __future__ import annotations
+import threading
+
# Sources Cicada makes itself (app/room.py's 知了 麦克风), never a room microphone.
OURS = ("cicada_mic",)
@@ -111,3 +113,131 @@ class VoiceGate:
self._second = float("inf")
self._elapsed = 0.0
return on
+
+
+# 电脑和会议室: the computer's audio and the room microphone at once, each heard on its own.
+
+def heard_both(lines) -> bool:
+ """The room mic and the computer's audio both brought in the other side's lines, so each one says
+ where it was heard (the Mac's RecordList.heardBoth). Read from the lines, not stored."""
+ room = online = False
+ for l in lines:
+ if l.speaker != "them":
+ continue
+ if l.via == "room":
+ room = True
+ else:
+ online = True
+ if room and online:
+ return True
+ return False
+
+
+def place_starts(lines) -> set:
+ """Lines of the other side's where the place changes from the line before: their label shows again."""
+ out, last, first = set(), None, True
+ for l in lines:
+ key = "me" if l.speaker == "me" else l.via
+ if l.speaker != "me" and (first or key != last):
+ out.add(l.id)
+ last, first = key, False
+ return out
+
+
+def asks_online(room_only: bool, answered: bool, in_call: bool) -> bool:
+ """线上也有人?: listening to the room alone while a meeting app here is in a call, so people online
+ are likely speaking through it. Once a meeting (the Mac's RoomPrompt.asksOnline)."""
+ return room_only and not answered and in_call
+
+
+def hybrid_note(room_running: bool, echo_cancelled: bool, headphones: bool, headset_default: bool):
+ """The grey line under 听哪里 in 电脑和会议室, when the room isn't heard the plain way (the Mac's
+ HybridNote): without echo cancellation the room pauses while the computer plays speech; with a
+ Bluetooth headset as the default input the computer's own mic hears the room. The string's key."""
+ if not room_running:
+ return None
+ if not echo_cancelled and not headphones:
+ return "线上有人说话时,先不听会议室"
+ if headset_default:
+ return "用电脑自带的麦克风听会议室"
+ return None
+
+
+class EchoGate:
+ """电脑和会议室 without echo cancellation: while the computer plays speech, the room mic hears it
+ again from the speakers. Listening `hold`s the gate on every loud block of the computer's audio;
+ the room mic hears silence until `hang` after the last one (the speakers' tail, the room's echo)."""
+ hang = 0.4
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._until = 0.0
+
+ def hold(self, now: float) -> None:
+ with self._lock:
+ self._until = max(self._until, now + self.hang)
+
+ def closed(self, now: float) -> bool:
+ with self._lock:
+ return now < self._until
+
+
+class Heard:
+ def __init__(self, text: str, start: float, end: float):
+ self.text = text
+ self.start = start
+ self.end = end
+
+
+class EchoMatch:
+ """电脑和会议室's last line of defence against hearing an online sentence twice: once from the
+ computer's audio, once more from the speakers into the room mic (the Mac's EchoMatch). A room line
+ made mostly of what the computer played around the same time is dropped, matched by containment
+ in word pairs (characters for Chinese, Japanese and Korean)."""
+ window = 3.0 # seconds around the room line where the computer's lines count
+ hold = 2.5 # how long a room line waits for the computer's line it may echo
+ contained = 0.6 # share of the room line found in the computer's lines that makes it an echo
+
+ @classmethod
+ def is_echo(cls, room: Heard, online: list) -> bool:
+ near = [o for o in online if o.end >= room.start - cls.window and o.start <= room.end + cls.window]
+ if not near:
+ return False
+ r = units(room.text)
+ if not r:
+ return False
+ o = [units(x.text) for x in near]
+ if len(r) <= 2: # a word or two ("OK", "对"): the very same words near it
+ return any(x == r for x in o)
+ mine = set(_pairs(r))
+ theirs = set(p for x in o for p in _pairs(x))
+ return len(mine & theirs) / len(mine) >= cls.contained
+
+
+def _cjk(c: str) -> bool:
+ v = ord(c)
+ return (0x3040 <= v <= 0x30FF or 0x3400 <= v <= 0x4DBF or 0x4E00 <= v <= 0x9FFF or 0xAC00 <= v <= 0xD7AF
+ or 0xF900 <= v <= 0xFAFF)
+
+
+def units(text: str) -> list:
+ """Lower-case words, each CJK character on its own; punctuation and spacing don't count."""
+ out, word = [], ""
+ for c in text.lower():
+ if _cjk(c):
+ if word:
+ out.append(word)
+ word = ""
+ out.append(c)
+ elif c.isalnum():
+ word += c
+ elif word:
+ out.append(word)
+ word = ""
+ if word:
+ out.append(word)
+ return out
+
+
+def _pairs(u: list) -> list:
+ return u if len(u) < 2 else [u[i - 1] + " " + u[i] for i in range(1, len(u))]
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index 661ad5b..46e9322 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -39,8 +39,9 @@ class AppSettings:
"speakTo": "room", # what the room hears; "room" = the language they have been speaking
"speakVoices": {}, # Ming voice per language key ("en": "US_Emma")
"speakHeadphones": False, # 戴着耳机: skip the echo guard, talking over them is fine
- # 听哪里 (the Mac's listenSource): "system" (what the computer plays) or "room" (a real
- # microphone, for a meeting in the room); roomMic: the source chosen for it, "" = 自动.
+ # 听哪里 (the Mac's listenSource): "system" (what the computer plays), "room" (a real
+ # microphone, for a meeting in the room) or "both" (电脑和会议室: people online and in the
+ # room, each heard on its own); roomMic: the room's microphone, "" = 自动.
"listenSource": "system",
"roomMic": "",
# 结束会议 (meeting_end.py), the Mac's keys: end when the meeting app hangs up; when nobody
@@ -50,7 +51,7 @@ class AppSettings:
"silenceMinutes": 10,
}
- SOURCES = ("system", "room")
+ SOURCES = ("system", "room", "both")
def __init__(self, **kw):
for k, v in self.FIELDS.items():
@@ -79,7 +80,7 @@ class AppSettings:
@property
def hears_room(self) -> bool:
- """The room microphone is open: 会议室."""
+ """The room microphone is open: 会议室 or 电脑和会议室."""
return self.listenSource != "system"
@property
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 9b91084..52d6116 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -183,3 +183,10 @@
"换" = "Change";
"正在用麦克风听会议室,有人说话后约 3 秒出字幕" = "Listening to the room through the microphone. Subtitles appear about 3 s after someone speaks";
"戴着蓝牙耳机时,自动用电脑自带的麦克风" = "With a Bluetooth headset on, Auto uses the computer's own mic";
+"用电脑自带的麦克风听会议室" = "Hearing the room with the computer's own mic";
+"知了 · 防回声" = "Cicada · Echo Cancellation";
+"戴着就不用防回声,桌边的话不会被丢;和同声传译共用这个开关" = "With headphones on there's no echo to remove, so nothing said at the table is lost. Shared with Interpreting";
+"电脑和会议室" = "Computer + Room";
+"电脑声音" = "This computer";
+"也听电脑" = "Hear the computer too";
+"电脑里放出来的" = "Played by the computer";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index 9d0fc88..bf5fcb7 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -183,3 +183,10 @@
"换" = "変更";
"正在用麦克风听会议室,有人说话后约 3 秒出字幕" = "マイクで会議室を聞いています。話し始めて約 3 秒で字幕が出ます";
"戴着蓝牙耳机时,自动用电脑自带的麦克风" = "Bluetooth ヘッドセット使用中は、自動でパソコン内蔵のマイクを使います";
+"用电脑自带的麦克风听会议室" = "パソコン内蔵のマイクで会議室を聞いています";
+"知了 · 防回声" = "知了 · エコー除去";
+"戴着就不用防回声,桌边的话不会被丢;和同声传译共用这个开关" = "ヘッドホン使用中はエコー除去が不要になり、会議室の発言も落ちません。同時通訳と共通の設定です";
+"电脑和会议室" = "パソコンと会議室";
+"电脑声音" = "このパソコン";
+"也听电脑" = "パソコンも聞く";
+"电脑里放出来的" = "パソコンから流れた";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 119d22f..4fadff0 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -183,3 +183,10 @@
"换" = "변경";
"正在用麦克风听会议室,有人说话后约 3 秒出字幕" = "마이크로 회의실을 듣고 있습니다. 말하면 약 3초 뒤 자막이 나옵니다";
"戴着蓝牙耳机时,自动用电脑自带的麦克风" = "블루투스 헤드셋을 쓰는 동안 자동으로 컴퓨터 내장 마이크를 씁니다";
+"用电脑自带的麦克风听会议室" = "컴퓨터 내장 마이크로 회의실을 듣고 있습니다";
+"知了 · 防回声" = "Cicada · 에코 제거";
+"戴着就不用防回声,桌边的话不会被丢;和同声传译共用这个开关" = "헤드폰을 쓰면 에코 제거가 필요 없어 회의실의 말도 빠지지 않습니다. 동시통역과 같은 설정입니다";
+"电脑和会议室" = "컴퓨터와 회의실";
+"电脑声音" = "이 컴퓨터";
+"也听电脑" = "컴퓨터도 듣기";
+"电脑里放出来的" = "컴퓨터에서 재생된 말";
diff --git a/linux/tests/test_hybrid.py b/linux/tests/test_hybrid.py
index 35e0c44..5d8db50 100644
--- a/linux/tests/test_hybrid.py
+++ b/linux/tests/test_hybrid.py
@@ -5,13 +5,15 @@ from __future__ import annotations
import threading
import time
-from test_core import Base, Fake, client, concat, reply, silence, tone
+from test_core import Base, Fake, client, concat, content, reply, silence, tone
from cicada.core.audio import PcmAudioSource
from cicada.core.ling import LingClient
-from cicada.core.listen import ListenEngine
+from cicada.core.listen import ROOM_IDS, ListenEngine
+from cicada.core.models import TranscriptLine
from cicada.core.notes import NotesEngine
-from cicada.core.roommic import Input, VoiceGate, parse_sources, pick
+from cicada.core.roommic import (EchoGate, EchoMatch, Heard, Input, VoiceGate, asks_online, heard_both, hybrid_note, parse_sources,
+ pick, place_starts)
from cicada.core.session_store import SessionStore
from cicada.core.settings import AppSettings
from cicada.core.translator import Translator
@@ -132,7 +134,8 @@ class Room(Base):
s = store.get(e.session_id)
self.assertEqual(["Hello from the table."], [l.src for l in s.lines])
self.assertTrue(s.room, "the record says 会议室")
- self.assertIsNone(s.lines[0].via, "会议室 alone: no place on each line, as on the Mac")
+ self.assertEqual("room", s.lines[0].via)
+ self.assertFalse(heard_both(s.lines), "会议室 alone: no place on each line, as on the Mac")
def test_the_computers_audio_keeps_the_fixed_gate(self):
store = SessionStore()
@@ -173,3 +176,137 @@ class Room(Base):
time.sleep(0.3)
e.stop()
self.assertEqual(0, len(store.get(e.session_id).lines) if store.get(e.session_id) else 0)
+
+
+def h(text, start, end):
+ return Heard(text, start, end)
+
+
+class EchoMatchTests(Base):
+ """The Mac's EchoMatchTests, case for case."""
+
+ def test_the_rooms_copy_of_a_remote_sentence_is_an_echo(self):
+ online = [h("Revenue grew by 12%, mostly from the new region.", 10, 14)]
+ # Heard worse from the speakers, and a word lost.
+ self.assertTrue(EchoMatch.is_echo(h("revenue grew by 12% mostly from new region", 10.3, 14.2), online))
+
+ def test_cut_differently_still_matches(self):
+ online = [h("我们先看一下这个季度的数据。", 0, 2), h("收入增长了百分之十二,主要来自新的市场。", 2.2, 5)]
+ self.assertTrue(EchoMatch.is_echo(h("这个季度的数据收入增长了百分之十二", 0.8, 4), online))
+
+ def test_room_speech_is_kept(self):
+ online = [h("Revenue grew by 12%, mostly from the new region.", 10, 14)]
+ self.assertFalse(EchoMatch.is_echo(h("I think we should check the numbers for Europe first", 11, 15), online))
+ self.assertFalse(EchoMatch.is_echo(h("我觉得应该先看一下欧洲的情况", 11, 15), online))
+
+ def test_the_same_words_long_after_are_not_an_echo(self):
+ online = [h("Can everyone hear me okay?", 0, 2)]
+ self.assertFalse(EchoMatch.is_echo(h("can everyone hear me okay", 20, 22), online))
+
+ def test_short_lines_match_only_exactly(self):
+ online = [h("OK.", 5, 5.5)]
+ self.assertTrue(EchoMatch.is_echo(h("ok", 5.2, 5.6), online))
+ self.assertFalse(EchoMatch.is_echo(h("no", 5.2, 5.6), online))
+
+ def test_gate_closes_for_the_hang(self):
+ g = EchoGate()
+ self.assertFalse(g.closed(100))
+ g.hold(100)
+ self.assertTrue(g.closed(100.3))
+ self.assertFalse(g.closed(100 + EchoGate.hang + 0.01))
+
+
+def line(i, speaker="them", via=None):
+ return TranscriptLine(id=i, speaker=speaker, src="x", srcLang="en", dstLang="zh-CN", via=via)
+
+
+class Places(Base):
+ """The Mac's HybridRecordTests."""
+
+ def test_only_a_meeting_that_heard_both_shows_places(self):
+ self.assertFalse(heard_both([line("a"), line("b")]))
+ self.assertFalse(heard_both([line("a", via="room"), line("b", via="room")]))
+ # My own lines (同声传译) don't make it a meeting that heard the computer.
+ self.assertFalse(heard_both([line("a", via="room"), line("b", "me")]))
+ self.assertTrue(heard_both([line("a", via="room"), line("b")]))
+
+ def test_a_change_of_place_starts_a_new_run(self):
+ ls = [line("a"), line("b"), line("c", via="room"), line("d", "me"), line("e", via="room"), line("f")]
+ self.assertEqual({"a", "c", "e", "f"}, place_starts(ls))
+
+ def test_online_prompt_asks_only_in_the_room_during_a_call(self):
+ self.assertTrue(asks_online(True, False, True))
+ self.assertFalse(asks_online(True, False, False))
+ self.assertFalse(asks_online(True, True, True))
+ self.assertFalse(asks_online(False, False, True))
+
+ def test_note_says_how_the_room_is_heard(self):
+ self.assertIsNone(hybrid_note(True, True, False, False))
+ self.assertIsNone(hybrid_note(False, False, False, True))
+ self.assertEqual("线上有人说话时,先不听会议室", hybrid_note(True, False, False, True))
+ self.assertEqual("用电脑自带的麦克风听会议室", hybrid_note(True, True, False, True))
+ # 戴着耳机: nothing to cancel, nothing paused.
+ self.assertIsNone(hybrid_note(True, False, True, False))
+
+
+ONLINE = "Revenue grew by 12%, mostly from the new region."
+
+
+def both_engine(store, room_text):
+ """The computer plays a 1 s sentence; the room mic hears 1.6 s at the same time."""
+ def respond(body):
+ if "Ming-3.0-audio-flash" not in body:
+ return reply("{}")
+ short = len(content(body, 1)[0]["audio_url"]["url"]) < 60000
+ return reply("LANG: en\nORIGINAL: %s\nTRANSLATION: 译文。" % (ONLINE if short else room_text))
+ LingClient.spacing = 0.02
+ ling = client(Fake(respond))
+ return ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target="zh-CN"))
+
+
+def run_both(e, gated=False):
+ main = PcmAudioSource(lambda: concat(tone(1.0), silence(1.0)), speed=0)
+ room = PcmAudioSource(lambda: concat(silence(0.5), tone(1.6, amp=0.2), silence(1.0)), speed=0)
+ 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=gated)
+ for d in done:
+ d.wait(10)
+ time.sleep(0.6)
+ e.stop()
+
+
+class Both(Base):
+ def test_the_rooms_own_words_are_kept_and_say_room(self):
+ store = SessionStore()
+ e = both_engine(store, "I think we should check the numbers for Europe first.")
+ run_both(e)
+ s = store.get(e.session_id)
+ got = sorted((l.via or "", l.src) for l in s.lines)
+ self.assertEqual([("", ONLINE), ("room", "I think we should check the numbers for Europe first.")], got)
+ room = next(l for l in s.lines if l.via == "room")
+ self.assertTrue(room.id.endswith("-%d" % (ROOM_IDS + 1)), room.id)
+ self.assertTrue(s.room)
+ self.assertTrue(heard_both(s.lines))
+
+ def test_the_rooms_copy_of_an_online_sentence_is_dropped(self):
+ store = SessionStore()
+ e = both_engine(store, "revenue grew by 12% mostly from new region")
+ run_both(e)
+ s = store.get(e.session_id)
+ self.assertEqual([(None, ONLINE)], [(l.via, l.src) for l in s.lines])
+
+ def test_stopping_the_room_side_keeps_the_meeting(self):
+ store = SessionStore()
+ e = both_engine(store, "x")
+ e.start(PcmAudioSource(lambda: silence(0.2), speed=0), "both")
+ e.start_room(PcmAudioSource(lambda: silence(0.2), speed=0), gated=True)
+ self.assertTrue(e.hears_room_too and e.gated)
+ sid = e.session_id
+ e.stop_room()
+ self.assertFalse(e.hears_room_too or e.gated)
+ self.assertTrue(e.listening)
+ self.assertEqual(sid, e.session_id)
+ e.stop()
diff --git a/site/changelog.json b/site/changelog.json
index 6bb388e..65e9d8a 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -133,6 +133,14 @@
],
"title": "Linux 上“听哪里”可以选“会议室”:用麦克风听桌边的人。",
"text": "顶栏菜单、纪要窗和设置里都能换,开会中途换也接着记在同一场里。会议室的底噪会自己学,隔着桌子小声说话也能出字幕;戴着蓝牙耳机时自动改用电脑自带的麦克风。同声传译开着时,麦克风听到的是你,会议室这边先不记。"
+ },
+ {
+ "kind": "new",
+ "platforms": [
+ "linux"
+ ],
+ "title": "Linux 上“听哪里”多了“电脑和会议室”:线上和桌边的人一起听,每句标出是现场还是线上。",
+ "text": "线上的人从电脑声音听,桌边的人从麦克风听,各认各的语言。知了用系统声音服务的回声消除把扬声器里的线上声音从麦克风里去掉,结束、退出或崩溃后都会把原来的扬声器设回默认;用不了时线上有人说话那一会儿麦克风先不听,最后再按文字去掉重复的一句。只听会议室时,会议软件一开始通话就会问“线上也有人?”。"
}
]
},