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 › Room hears the people at the table through a microphone

wquguru1ca0df6e2a99
diff --git a/linux/cicada/app/capture.py b/linux/cicada/app/capture.py
index 53a481b..a6bd09f 100644
--- a/linux/cicada/app/capture.py
+++ b/linux/cicada/app/capture.py
@@ -11,6 +11,8 @@ from __future__ import annotations
import ctypes
import ctypes.util
+import os
+import subprocess
import threading
import time
from array import array
@@ -90,10 +92,28 @@ def _libpulse():
def default_sink() -> str | None:
"""The sound server's default output, or None when it can't be asked (a few ms, blocking)."""
+ return _server_info().get("sink")
+
+
+def default_source() -> str | None:
+ """The sound server's default input, or None when it can't be asked."""
+ return _server_info().get("source")
+
+
+def sources_text() -> str:
+ """`pactl list sources` in English (roommic.parse_sources reads it); empty without pactl."""
+ try:
+ return subprocess.run(["pactl", "list", "sources"], env={**os.environ, "LC_ALL": "C"}, capture_output=True,
+ text=True, timeout=3).stdout
+ except (OSError, subprocess.SubprocessError):
+ return ""
+
+
+def _server_info() -> dict:
try:
l = _libpulse()
except OSError:
- return None
+ return {}
loop = l.pa_mainloop_new()
ctx = l.pa_context_new(l.pa_mainloop_get_api(loop), b"Cicada")
found = {}
@@ -102,23 +122,25 @@ def default_sink() -> str | None:
def got(_c, info, _u):
if info and info.contents.default_sink_name:
found["sink"] = info.contents.default_sink_name.decode()
+ if info and info.contents.default_source_name:
+ found["source"] = info.contents.default_source_name.decode()
try:
if l.pa_context_connect(ctx, None, 0, None) < 0:
- return None
+ return {}
deadline = time.monotonic() + 1.0
op = None
while time.monotonic() < deadline:
l.pa_mainloop_iterate(loop, 0, None)
state = l.pa_context_get_state(ctx)
if state in (5, 6): # FAILED, TERMINATED
- return None
+ return {}
if state == 4 and op is None: # READY
op = l.pa_context_get_server_info(ctx, got, None)
if op is not None and l.pa_operation_get_state(op) != 0: # no longer RUNNING
l.pa_operation_unref(op)
break
time.sleep(0.005)
- return found.get("sink")
+ return found
finally:
l.pa_context_disconnect(ctx)
l.pa_context_unref(ctx)
@@ -134,10 +156,12 @@ def available() -> bool:
class SystemAudio(AudioSource):
- """16 kHz mono from "@DEFAULT_MONITOR@": the server resamples and downmixes for us."""
+ """16 kHz mono from "@DEFAULT_MONITOR@" (or a microphone, `device`): the server resamples and
+ downmixes for us. `name` is what the sound settings and GNOME's privacy menu show."""
- def __init__(self, device: str = "@DEFAULT_MONITOR@"):
+ def __init__(self, device: str = "@DEFAULT_MONITOR@", name: str | None = None):
self.device = device
+ self.name = name
self._stop = threading.Event()
self._thread = None
@@ -155,7 +179,7 @@ class SystemAudio(AudioSource):
attr = _Attr(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, CHUNK * 2)
err = ctypes.c_int(0)
# The stream's name is what the sound settings and GNOME's privacy menu show.
- s = lib.pa_simple_new(None, b"Cicada", PA_STREAM_RECORD, self.device.encode(), L("知了 · 系统声音").encode(),
+ s = lib.pa_simple_new(None, b"Cicada", PA_STREAM_RECORD, self.device.encode(), (self.name or L("知了 · 系统声音")).encode(),
ctypes.byref(spec), None, ctypes.byref(attr), ctypes.byref(err))
return s, (None if s else lib.strerror(err.value).decode())
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index a037794..08d9c7a 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -11,7 +11,8 @@ per connection, one JSON line back. Never in release builds.
settings-models on|off (unfold 自己选模型)
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)"""
+ pill (the records window capsule's widget sizes)
+ listen-source system|room|both (听哪里) | room-mic [<source>|auto] | lines [<record id>] (each line's via)"""
from __future__ import annotations
import os
@@ -119,7 +120,7 @@ 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, "target": app.settings.target_code,
+ "key": app.ling.key_state, "ai": _ai(app), "view": app.settings.view, "listenSource": app.settings.listenSource, "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,
@@ -161,6 +162,18 @@ def command(app, line: str) -> dict:
if cmd == "settings-ai":
app.show_settings(ai=True)
return {"ok": True}
+ 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 == "room-mic": # which microphone 会议室 would use now; with an argument, choose it ("" = 自动)
+ if arg:
+ app.settings.roomMic = "" if arg == "auto" else arg
+ app.settings.save()
+ return {"ok": True, "roomMic": app.settings.roomMic, "picked": app.room_mic()}
+ if cmd == "lines": # the live (or given) meeting's lines: where each was heard
+ s = app.store.get(arg or listen.session_id or "")
+ return {"ok": True, "room": s.room if s else None,
+ "lines": [[l.id, l.speaker, l.via, l.src[:50]] for l in s.lines] if s else []}
if cmd == "stop":
app.stop_listening()
return {"ok": True}
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index 09103d0..72c1c45 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -25,7 +25,7 @@ from gi.repository import Gdk, Gio, GLib, Gtk # noqa: E402
from ..core import strings # noqa: E402
from ..core.audio import PcmAudioSource # noqa: E402
-from ..core import meeting_end # noqa: E402
+from ..core import meeting_end, roommic # noqa: E402
from ..core.ling import AIKey, LingClient # noqa: E402
from ..core.listen import ListenEngine # noqa: E402
from ..core.notes import NotesEngine # noqa: E402
@@ -35,6 +35,7 @@ from ..core.strings import L, LF # noqa: E402
from ..core.support import Log, Paths, clock, english_name # noqa: E402
from ..core.translator import Translator # noqa: E402
from . import debug, tray, ui # noqa: E402
+from . import capture # noqa: E402
from .capture import SystemAudio # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # linux/ or the installed tree
@@ -171,6 +172,8 @@ class Controller:
def run():
self._queued = False
+ # 会议室 while 同声传译 hears me through the same microphone: what it hears is me.
+ self.listen.set_muted(self.speak.active)
if self.notes_window is not None:
self.notes_window.refresh()
if self.records_window is not None:
@@ -377,7 +380,60 @@ class Controller:
if self.listen.listening:
self.stop_listening()
else:
- self.start_listening(SystemAudio(), "system")
+ self.start_listening(*self.heard_source())
+
+ # 听哪里
+
+ 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."""
+ inputs = roommic.parse_sources(capture.sources_text())
+ default = capture.default_source()
+ if default == "cicada_mic":
+ default = self.room.real_mic
+ picked = roommic.pick(default, inputs, self.settings.roomMic)
+ if picked is None and not inputs: # no pactl to list them: the default, if it's a real one
+ picked = default or "@DEFAULT_SOURCE@"
+ Log.d("room mic: %s (default %s, %d inputs)" % (picked, default, len(inputs)))
+ return picked
+
+ def heard_source(self):
+ """(source, kind) for 听哪里: the computer's audio, or the room through a microphone."""
+ if self.settings.listenSource == "room":
+ mic = self.room_mic()
+ if mic is not None:
+ return SystemAudio(mic, L("知了 · 会议室")), "room"
+ Log.d("room mic: none, listening to the computer instead")
+ return SystemAudio(), "system"
+
+ def set_listen_source(self, value: str) -> None:
+ """听哪里 changed, from the tray, the notes window or 设置; mid-meeting the same meeting goes on
+ from the new source."""
+ if value not in AppSettings.SOURCES or value == self.settings.listenSource:
+ return
+ self.settings.listenSource = value
+ self.settings.save()
+ Log.d("listenSource=%s" % value)
+ if self.listen.listening and self.listen.source_kind in ("system", "room"):
+ source, kind = self.heard_source()
+ source.on_ended = self._source_ended(kind)
+ self.listen.source_kind = kind
+ self.listen.attach(source, mic=kind == "room")
+ self.changed()
+
+ def _source_ended(self, kind: str):
+ def ended(reason):
+ # A file that finished stops a little later, so its last sentence's pause is heard;
+ # a capture that failed stops now.
+ if reason is None:
+ GLib.timeout_add(1500, lambda: self.stop_listening() and False)
+ return
+ Log.d("listen: source ended %s" % reason)
+ # Said where the subtitles would be (start() clears it), not silently stopped.
+ self.listen.problem = L("没有可用的麦克风") if kind == "room" else L("系统声音中断")
+ self.listen.problem_kind = "source"
+ GLib.idle_add(lambda: self.stop_listening() and False)
+ return ended
def recorded(self):
"""(elapsed seconds, lines) of the live meeting, or None when nothing has been said yet."""
@@ -444,22 +500,11 @@ class Controller:
if r.reason in ("deaf", "unreachable") and not self._may_start(source, kind):
return
- def ended(reason):
- # A file that finished stops a little later, so its last sentence's pause is heard;
- # a capture that failed stops now.
- if reason is None:
- GLib.timeout_add(1500, lambda: self.stop_listening() and False)
- return
- Log.d("listen: source ended %s" % reason)
- # Said where the subtitles would be (start() clears it), not silently stopped.
- self.listen.problem = L("系统声音中断")
- self.listen.problem_kind = "source"
- GLib.idle_add(lambda: self.stop_listening() and False)
- source.on_ended = ended
+ source.on_ended = self._source_ended(kind)
self.auto_ended = False
self.ending = None
self.end_watch = meeting_end.MeetingEndWatch(self.end_config(), time.time())
- self.listen.start(source, kind)
+ self.listen.start(source, kind, mic=kind == "room")
self.show_notes()
self.changed()
@@ -558,7 +603,7 @@ class Controller:
self._auto_end(reason, w)
elif not self.listen.listening and self.auto_ended and self.settings.endWithApp and calls:
Log.d("meeting end: a meeting app started a call, starting a new meeting")
- self.start_listening(SystemAudio(), "system")
+ self.start_listening(*self.heard_source())
def _words(self, sid: str) -> None:
"""Words recognised in the live meeting (theirs or mine): the silence countdown stops now,
diff --git a/linux/cicada/app/notes_window.py b/linux/cicada/app/notes_window.py
index d90990c..92f8087 100644
--- a/linux/cicada/app/notes_window.py
+++ b/linux/cicada/app/notes_window.py
@@ -157,6 +157,11 @@ class NotesWindow(Gtk.Window):
self.header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)
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.set_no_show_all(True)
+ if not self.subtitles:
+ outer.pack_start(ui.pad(self.source_row, 0, 16, 4, 16), False, False, 0)
self.live = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
self.body = None
self.footer_time = None
@@ -301,6 +306,35 @@ class NotesWindow(Gtk.Window):
note = ui.text(self.app.ending_title(p) + " · " + LF("%lld 秒后结束", self.app.ending_left(p)), 12, "accent", wrap=False)
h.pack_start(note, False, False, 8)
h.show_all()
+ self._fill_source()
+
+ def _fill_source(self) -> None:
+ row = self.source_row
+ ui.clear(row)
+ listen = self.app.listen
+ if not listen.listening or listen.source_kind == "file" or self.subtitles:
+ row.hide()
+ 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)
+ change = ui.link(L("换") + " ⌄", lambda: self._source_menu(change))
+ change.set_can_focus(False)
+ row.pack_start(change, False, False, 0)
+ row.show_all()
+
+ def _source_menu(self, widget) -> None:
+ from .tray import sources
+ menu = Gtk.Menu()
+ for value, label in sources():
+ mark = "✓ " if value == self.app.settings.listenSource else " "
+ i = Gtk.MenuItem(label=mark + label)
+ i.connect("activate", lambda *_, v=value: self.app.set_listen_source(v))
+ menu.append(i)
+ menu.show_all()
+ menu.attach_to_widget(widget, None)
+ menu.popup_at_widget(widget, Gdk.Gravity.SOUTH_WEST, Gdk.Gravity.NORTH_WEST, None)
+ self._menu = menu # kept while open
# 纪要 / 文字记录, side by side
@@ -691,7 +725,8 @@ class NotesWindow(Gtk.Window):
if kind == "source":
# Saved only if something was heard before the audio service went away.
body = L("音频服务已断开,本次会议记录已保存") if session is not None and session.lines else L("没能开始听")
- self._state_card(box, "audio-volume-muted-symbolic", "warn", L("系统声音中断"), body, L("开始听"), self.app.toggle_listening)
+ self._state_card(box, "audio-volume-muted-symbolic", "warn", listen.problem or L("系统声音中断"), body, L("开始听"),
+ self.app.toggle_listening)
elif kind == "network" and (line is None or listen.listening):
service = self.app.ling.provider.name
self._state_card(box, "network-offline-symbolic", "warn", L("连不上 Ling") if service == "Ling" else LF("连不上 %@", service),
@@ -703,9 +738,11 @@ class NotesWindow(Gtk.Window):
elif line is None:
if listen.listening:
hearing = listen.pending > 0 or listen.level >= 0.01
- self._state_card(box, "audio-speakers-symbolic", "grey",
+ room = listen.source_kind == "room"
+ self._state_card(box, "audio-input-microphone-symbolic" if room else "audio-speakers-symbolic", "grey",
L("正在识别…") if hearing else L("等有人说话"),
- L("正在听电脑播放的声音,有声音后约 3 秒出字幕"))
+ L("正在用麦克风听会议室,有人说话后约 3 秒出字幕") if room
+ else L("正在听电脑播放的声音,有声音后约 3 秒出字幕"))
else:
self._state_card(box, "audio-speakers-symbolic", "grey", None,
L("点“开始听”,将电脑播放的声音转为双语字幕和纪要"))
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
index a8d3ed2..43cbbd7 100644
--- a/linux/cicada/app/records_window.py
+++ b/linux/cicada/app/records_window.py
@@ -629,8 +629,9 @@ 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))
- return "%s · %s · %d %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 = " · " + L("会议室") if s.room else "" # heard through a microphone in the room, as on the Mac
+ 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)
def _notes_state(self, s, live):
return (id(s.notes), s.notes.updatedAt if s.notes else None, self.app.notes.working_id == s.id, live)
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index 745f51b..6fd1f87 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -203,6 +203,9 @@ class SettingsWindow(Gtk.Window):
self._shortcut_row(),
warn_row])), False, False, 0)
+ room_group, room_combos = self._room_group()
+ page.pack_start(room_group, False, False, 0)
+ combos += room_combos
page.pack_start(self._speak_group(combos), False, False, 0)
page.pack_start(self._end_group(), False, False, 0)
@@ -435,6 +438,31 @@ class SettingsWindow(Gtk.Window):
self.speak_status.set_no_show_all(True)
return ui.vbox(6, self._group(L("同声传译"), ui.boxed(rows)), ui.pad(self.speak_status, 0, 4, 0, 4))
+ def _room_group(self):
+ """会议室: 听哪里, and the microphone that hears the room (自动 picks as roommic.pick does)."""
+ from ..core import roommic
+ from . import capture
+ from .tray import sources
+ app = self.app
+ s = app.settings
+ where = choice(sources(), s.listenSource, app.set_listen_source)
+ inputs = [i for i in roommic.parse_sources(capture.sources_text()) if not i.virtual]
+ default = capture.default_source()
+ if default == "cicada_mic":
+ default = app.room.real_mic
+ auto = roommic.pick(default, inputs)
+ auto_name = next((i.description for i in inputs if i.name == auto), None)
+
+ def set_mic(v):
+ s.roomMic = v
+ s.save()
+ options = [("", LF("自动(%@)", auto_name) if auto_name else L("自动"))] + [(i.name, i.description) for i in inputs]
+ 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("戴着蓝牙耳机时,自动用电脑自带的麦克风"))]
+ return self._group(L("会议室"), ui.boxed(rows)), [where, mic]
+
def _group(self, title, body, footer=None) -> Gtk.Widget:
box = ui.vbox(6, ui.pad(ui.text(title, 12, "group-title", bold=True, wrap=False), 0, 0, 0, 2), body)
if footer:
diff --git a/linux/cicada/app/tray.py b/linux/cicada/app/tray.py
index 9a5b4cf..764071f 100644
--- a/linux/cicada/app/tray.py
+++ b/linux/cicada/app/tray.py
@@ -92,6 +92,18 @@ class Tray:
self.detail_item = None
menu.append(Gtk.SeparatorMenuItem())
item(L("结束") if listening else L("开始听"), self.app.request_stop)
+ # 听哪里, the Mac panel's choice: changed mid-meeting, the same meeting goes on.
+ if self.app.listen.source_kind != "file" or not listening:
+ menu.append(Gtk.SeparatorMenuItem())
+ item(L("听哪里"), None, False)
+ first = None
+ for value, label in sources():
+ r = Gtk.RadioMenuItem.new_with_label_from_widget(first, label)
+ first = first or r
+ r.set_active(value == self.app.settings.listenSource)
+ r.connect("toggled", lambda w, v=value: w.get_active() and self.app.set_listen_source(v))
+ menu.append(r)
+ menu.append(Gtk.SeparatorMenuItem())
if self.app.settings.speakEnabled:
item(L("停止说") if self.app.speak.active else L("开始说"), self.app.toggle_speaking)
item(L("显示实时纪要"), self.app.show_notes)
@@ -144,6 +156,13 @@ class Tray:
self.lib.app_indicator_set_label(self.ind, self._clock().encode(), b"")
+def sources() -> list:
+ """听哪里's choices, as the tray, the notes window and 设置 list them."""
+ from ..core.settings import AppSettings
+ names = {"system": L("电脑声音"), "room": L("会议室"), "both": L("电脑和会议室")}
+ return [(v, names[v]) for v in AppSettings.SOURCES]
+
+
def badged_icon(icon: str) -> str | None:
"""A copy of the app icon (an SVG, 100 units square) with the accent dot over its top right
corner and a white ring around it, written once under the data folder. The logo itself stays
diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.py
index 0afba29..e8a15df 100644
--- a/linux/cicada/core/listen.py
+++ b/linux/cicada/core/listen.py
@@ -10,12 +10,14 @@ from __future__ import annotations
import queue
import threading
import time
+from array import array
from concurrent.futures import ThreadPoolExecutor, wait
from . import strings
from .audio import RATE, Wav
from .ling import LingError
from .models import TranscriptLine
+from .roommic import VoiceGate
from .segmenter import Segmenter
from .support import Log, english_name, is_cjk_language
from .translator import Translator
@@ -23,6 +25,32 @@ from .translator import Translator
_END = object()
+class _Lane:
+ """One audio source's way through listening: its segments, their replies put back in order, its
+ last line and the language it hears. 电脑和会议室 runs two, as the Mac runs a main and a room
+ engine; each keeps its own language and pauses."""
+
+ def __init__(self, via: str | None = None, first: int = 0):
+ self.via = via # "room" on the lines of 电脑和会议室's room side
+ self.first = first # segment numbers start above this
+ self.source = None
+ self.audio = None
+ self.worker = None
+ self.done: dict = {}
+ self.segments: dict = {}
+ self.next = first + 1
+ self.last = None
+ self.last_end = 0.0
+ self.hint = None
+ self.candidate = None
+ self.votes = 0
+ self.level = 0.0
+ self.peak = 0.0
+ self.heard_seconds = 0.0
+ self.gate = None # a microphone's VoiceGate (the room's noise, learnt)
+ self.muted = False # silence in place of the microphone (同声传译 is hearing me)
+
+
class ListenEngine:
def __init__(self, ling, translator, store, notes, settings):
self.ling = ling
@@ -32,29 +60,16 @@ class ListenEngine:
self.settings = settings
self._gate = threading.RLock()
self._pool = ThreadPoolExecutor(max_workers=8, thread_name_prefix="Listen")
- self._source = None
- self._audio = None
- self._worker = None
- self._done: dict = {}
- self._segments: dict = {}
+ self._main = _Lane()
self._in_flight: list = []
- self._next = 1
self._line_count = 0
- self._last = None
- self._last_end = 0.0
- self._hint = None
- self._candidate = None
- self._votes = 0
self._listeners = []
self.listening = False
self.session_id = None
- self.source_kind = None # what this meeting is heard from ("system", "file")
+ self.source_kind = None # what this meeting is heard from ("system", "room", "file")
self.problem = None # the last error worth showing, cleared by the next good reply
# What kind of problem, for a state the UI can draw: "key", "busy", "network", "source".
self.problem_kind = None
- self.level = 0.0
- self.heard_seconds = 0.0 # the capture is alive while this grows
- self.peak = 0.0 # 0 for a while means the source is silent
self.loudness = None # SpeakEngine's LoudnessLog: when the system audio was loud (the echo check)
# 说话人识别: a voiceprint per segment on its own thread while Ming hears it, labelled in order.
self.speakers = None # speakers.Tagger, set by the app
@@ -67,6 +82,24 @@ class ListenEngine:
notes.language = lambda sid: english_name(self.notes_code(sid))
translator.glossary = notes.glossary
+ # The main source's: level and peak (0 for a while means it is silent); the capture is alive while
+ # heard_seconds grows.
+ @property
+ def level(self) -> float:
+ return self._main.level
+
+ @property
+ def peak(self) -> float:
+ return self._main.peak
+
+ @property
+ def heard_seconds(self) -> float:
+ return self._main.heard_seconds
+
+ @property
+ def _hint(self):
+ return self._main.hint
+
def on_change(self, listener) -> None:
self._listeners.append(listener)
@@ -121,30 +154,40 @@ class ListenEngine:
def pending(self) -> int:
"""Segments sent and not yet back: the UI shows "…" while this is above zero."""
with self._gate:
- return len(self._segments)
+ return sum(len(l.segments) for l in self._lanes())
+
+ def _lanes(self) -> list:
+ return [self._main]
- def start(self, source, kind: str) -> 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
+ from the room's own noise, and the record says it was heard in the room."""
if self.listening:
return
session = self.store.begin()
self.session_id = session.id
self.source_kind = kind
with self._gate:
- self._done.clear()
- self._segments.clear()
+ self._main = _Lane()
self._in_flight.clear()
- self._next, self._line_count, self._last, self._last_end = 1, 0, None, 0.0
- self._hint, self._candidate, self._votes, self.problem = None, None, 0, None
- self.problem_kind = None
- self.heard_seconds = 0.0
- self.peak = 0.0
+ self._line_count = 0
+ self.problem = self.problem_kind = None
self.notes.begin(session.id)
if self.speakers is not None:
self.speakers.reset()
+ # Listening before the source starts: a source that fails at once calls on_ended → stop(),
+ # which must see this meeting as running to end it.
+ self.listening = True
+ self._run(self._main)
+ self.attach(source, mic)
+ Log.d("listen: started %s source=%s target=%s" % (session.id, kind, self.target))
+ self._changed()
+
+ def _run(self, lane) -> None:
segmenter = Segmenter()
- segmenter.on_segment = self._send
+ segmenter.on_segment = lambda seg: self._send(lane, seg)
q: queue.Queue = queue.Queue()
- self._audio = q
+ lane.audio = q
def work():
# One worker owns the segmenter: audio callbacks only queue buffers.
@@ -152,23 +195,49 @@ class ListenEngine:
buf = q.get()
if buf is _END:
break
+ seconds = len(buf) / RATE
+ if lane.muted:
+ # Silence rather than nothing keeps the segmenter's clock in step.
+ buf = array("h", bytes(len(buf) * 2))
+ level = Wav.rms(buf)
+ gate = lane.gate
+ if gate is not None:
+ gate.voiced(level, seconds)
+ segmenter.threshold = gate.threshold
+ elif segmenter.threshold != Segmenter.threshold:
+ del segmenter.threshold # back on the computer's audio: the fixed gate
segmenter.feed(buf)
- self.level = Wav.rms(buf)
- self.peak = max(self.peak * 0.995, self.level)
- if self.loudness is not None:
- self.loudness.add(self.level >= Segmenter.threshold)
- self.heard_seconds += len(buf) / RATE
+ 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)
+ lane.heard_seconds += seconds
segmenter.flush()
- self._worker = threading.Thread(target=work, name="ListenWorker", daemon=True)
- self._worker.start()
- self._source = source
- source.on_samples = q.put
- # Listening before the source starts: a source that fails at once calls on_ended → stop(),
- # which must see this meeting as running to end it.
- self.listening = True
+ lane.worker = threading.Thread(target=work, name="ListenWorker", daemon=True)
+ lane.worker.start()
+
+ def attach(self, source, mic: bool = False) -> None:
+ """The meeting's source, now or in place of the one before (听哪里 changed mid-meeting): the
+ same segments and lines go on from the new one."""
+ lane = self._main
+ old = lane.source
+ if old is not None:
+ old.on_samples = None
+ old.stop()
+ lane.gate = VoiceGate(adaptive=True) if mic else None
+ if mic and self.session_id:
+ self.store.mark_room(self.session_id)
+ lane.source = source
+ source.on_samples = lane.audio.put
source.start()
- Log.d("listen: started %s source=%s target=%s" % (session.id, kind, self.target))
- self._changed()
+ if old is not None:
+ 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"))
def stop(self, ended_at=None) -> None:
"""Stops listening, waits (briefly) for segments still at Ming, ends the record (at `ended_at`
@@ -177,13 +246,8 @@ class ListenEngine:
if not self.listening:
return
self.listening = False
- if self._source is not None:
- self._source.on_samples = None
- self._source.stop()
- if self._audio is not None:
- self._audio.put(_END)
- if self._worker is not None:
- self._worker.join(5)
+ for lane in self._lanes():
+ self._end_lane(lane)
with self._gate:
waiting = list(self._in_flight)
wait(waiting, timeout=15)
@@ -195,11 +259,22 @@ class ListenEngine:
self._changed()
self._pool.submit(self.notes.finish)
+ @staticmethod
+ def _end_lane(lane) -> None:
+ if lane.source is not None:
+ lane.source.on_samples = None
+ lane.source.stop()
+ if lane.audio is not None:
+ lane.audio.put(_END)
+ if lane.worker is not None:
+ lane.worker.join(5)
+
@property
def voices_on(self) -> bool:
return bool(self.speakers is not None and getattr(self.settings, "speakerVoices", False) and self.speakers.available)
- def _send(self, seg) -> None:
+ def _send(self, lane, seg) -> None:
+ seg.index += lane.first
wav = Wav.bytes(seg.samples)
seg.voiceprint = None
if self.voices_on:
@@ -220,8 +295,8 @@ class ListenEngine:
self._voices_waiting -= 1
seg.voiceprint = self._voice_pool.submit(embed)
with self._gate:
- self._segments[seg.index] = seg
- lang = self._hint
+ lane.segments[seg.index] = seg
+ lang = lane.hint
# Asked for what the meeting's language translates into; _record checks it against the
# language Ming actually heard ("follow system" turns my own language into the next one).
seg.asked = self.settings.resolved_target(lang)
@@ -241,26 +316,26 @@ class ListenEngine:
Log.d("listen: segment %d %.1fs -> %s in %d ms" % (seg.index, seg.seconds, heard.lang if heard else "nothing",
(time.monotonic() - started) * 1000))
with self._gate:
- self._done[seg.index] = heard
- self._deliver()
+ lane.done[seg.index] = heard
+ self._deliver(lane)
f = self._pool.submit(job)
with self._gate:
self._in_flight.append(f)
self._in_flight = [x for x in self._in_flight if not x.done()]
- def _deliver(self) -> None:
+ def _deliver(self, lane) -> None:
"""Hands finished segments on in order: one slow reply holds back those after it. One thread
at a time, so lines (and their voices) are recorded strictly in segment order."""
with self._deliver_lock:
ready = []
with self._gate:
- while self._next in self._done:
- heard = self._done.pop(self._next)
- ready.append((self._segments.pop(self._next), heard))
- self._next += 1
+ while lane.next in lane.done:
+ heard = lane.done.pop(lane.next)
+ ready.append((lane.segments.pop(lane.next), heard))
+ lane.next += 1
for seg, heard in ready:
if heard is not None:
- self._record(seg, heard)
+ self._record(lane, seg, heard)
if ready:
self._changed()
@@ -277,7 +352,7 @@ class ListenEngine:
return None
return self.speakers.label(vector, seg.seconds)
- def _record(self, seg, heard) -> None:
+ def _record(self, lane, seg, heard) -> None:
sid = self.session_id
if sid is None:
return
@@ -289,22 +364,22 @@ class ListenEngine:
# The meeting's language moves only after two segments agree, so one misheard stretch doesn't
# flip the hint (the Mac waits for confidence the same way).
with self._gate:
- h = self._hint
+ h = lane.hint
if h is None:
- self._hint = heard.lang
+ lane.hint = heard.lang
elif heard.lang != h:
- if self._candidate == heard.lang:
- self._votes += 1
+ if lane.candidate == heard.lang:
+ lane.votes += 1
else:
- self._candidate, self._votes = heard.lang, 1
- if self._votes >= 2:
- self._hint, self._candidate, self._votes = self._candidate, None, 0
+ lane.candidate, lane.votes = heard.lang, 1
+ if lane.votes >= 2:
+ lane.hint, lane.candidate, lane.votes = lane.candidate, None, 0
else:
- self._candidate, self._votes = None, 0
- prev = self._last
+ lane.candidate, lane.votes = None, 0
+ prev = lane.last
joined = False
# Two voices never share a line: a half sentence joins only the same voice (or an unknown one).
- if prev is not None and continues(prev, seg.start - self._last_end, heard) and (
+ if prev is not None and continues(prev, seg.start - lane.last_end, heard) and (
voice is None or prev.voice is None or voice == prev.voice):
prev.src = join(prev.src, heard.original, heard.lang)
prev.dst = None if prev.dst is None or translation is None else join(prev.dst, translation, target)
@@ -314,9 +389,9 @@ class ListenEngine:
self._line_count += 1
line = TranscriptLine(id="h%d-%d" % (self._line_count, seg.index), t=seg.start, speaker="them",
src=heard.original, dst=translation, srcLang=heard.lang, dstLang=target,
- voice=voice)
- self._last = line
- self._last_end = seg.start + seg.seconds
+ voice=voice, via=lane.via)
+ lane.last = line
+ lane.last_end = seg.start + seg.seconds
copy = line.copy()
if joined:
self.store.replace(sid, copy)
diff --git a/linux/cicada/core/roommic.py b/linux/cicada/core/roommic.py
new file mode 100644
index 0000000..1992e17
--- /dev/null
+++ b/linux/cicada/core/roommic.py
@@ -0,0 +1,113 @@
+"""会议室: listening to the people in the room through a real microphone instead of what the computer
+plays (the Mac's RoomMic.swift). Pure: which microphone, and when a block of it counts as speech.
+The capture itself is app/capture.py's SystemAudio on a source instead of a monitor."""
+from __future__ import annotations
+
+# Sources Cicada makes itself (app/room.py's 知了 麦克风), never a room microphone.
+OURS = ("cicada_mic",)
+
+
+class Input:
+ def __init__(self, name: str, description: str = "", builtin: bool = False, bluetooth: bool = False,
+ virtual: bool = False):
+ self.name = name
+ self.description = description or name
+ self.builtin = builtin
+ self.bluetooth = bluetooth
+ self.virtual = virtual
+
+ def __repr__(self):
+ return "Input(%s%s%s%s)" % (self.name, " builtin" if self.builtin else "", " bt" if self.bluetooth else "",
+ " virtual" if self.virtual else "")
+
+
+def parse_sources(text: str) -> list:
+ """The inputs in `LC_ALL=C pactl list sources`. A monitor of an output, a source a module made
+ (no device.api: 知了 麦克风, an echo canceller, a remap) or one of ours is virtual: it hears no room."""
+ out = []
+ block: dict = {}
+ props: dict = {}
+
+ def close():
+ name = block.get("Name")
+ if not name:
+ return
+ monitor = block.get("Monitor of Sink", "n/a") not in ("n/a", "")
+ api = props.get("device.api", "")
+ virtual = monitor or not api or name in OURS or name.startswith("cicada_") or props.get("device.class") == "monitor"
+ bluetooth = api == "bluez5" or props.get("device.bus") == "bluetooth"
+ builtin = not bluetooth and (props.get("device.form_factor") == "internal" or
+ (api == "alsa" and props.get("device.bus") == "pci"))
+ out.append(Input(name, block.get("Description", ""), builtin, bluetooth, virtual))
+
+ for raw in text.splitlines():
+ line = raw.strip()
+ if raw.startswith("Source #"):
+ close()
+ block, props = {}, {}
+ continue
+ if raw.startswith("\t\t") and " = " in line:
+ k, _, v = line.partition(" = ")
+ props[k.strip()] = v.strip().strip('"')
+ elif ":" in line and raw.startswith("\t") and not raw.startswith("\t\t"):
+ k, _, v = line.partition(":")
+ block[k.strip()] = v.strip()
+ close()
+ return out
+
+
+def pick(default: str | None, inputs: list, chosen: str = "") -> str | None:
+ """The microphone that hears the room (RoomMicPlan.pick): the one chosen in 设置 › 会议室 while it
+ is there; else the default input, unless it is virtual (同声传译 makes 知了 麦克风 the default) or a
+ Bluetooth headset's (it hears the wearer, not the table, and drops to call quality while open);
+ then the computer's own microphone, then any real one."""
+ real = [i for i in inputs if not i.virtual]
+ if chosen and any(i.name == chosen for i in real):
+ return chosen
+ d = next((i for i in real if i.name == default), None)
+ if d is not None and not d.bluetooth:
+ return d.name
+ for want in (lambda i: i.builtin, lambda i: not i.bluetooth, lambda i: True):
+ found = next((i for i in real if want(i)), None)
+ if found is not None:
+ return found.name
+ return None
+
+
+class VoiceGate:
+ """When a block of audio counts as speech (the Mac's VoiceGate). The computer's own audio is
+ digital silence between words, so a fixed -40 dBFS works there. A room mic always hears the room
+ (a fan, the street), and a voice across the table can be quieter than -40 dBFS: there the line
+ sits at twice the room's own noise. The noise is the quietest moment of each second (the gaps
+ between words, even while people talk on and on), taken low over the last half minute."""
+ fixed = 0.01
+ lowest = 0.0015
+
+ def __init__(self, adaptive: bool = False):
+ self.adaptive = adaptive
+ self._quietest: list = []
+ self._second = float("inf")
+ self._elapsed = 0.0
+
+ @property
+ def threshold(self) -> float:
+ if not self.adaptive:
+ return self.fixed
+ if len(self._quietest) < 3:
+ return 0.004
+ floor = sorted(self._quietest)[len(self._quietest) // 5]
+ return min(self.fixed, max(self.lowest, floor * 2))
+
+ def voiced(self, rms: float, seconds: float = 0.1) -> bool:
+ on = rms >= self.threshold
+ if not self.adaptive:
+ return on
+ self._second = min(self._second, rms)
+ self._elapsed += seconds
+ if self._elapsed >= 1 - 1e-9:
+ self._quietest.append(self._second)
+ if len(self._quietest) > 30:
+ self._quietest.pop(0)
+ self._second = float("inf")
+ self._elapsed = 0.0
+ return on
diff --git a/linux/cicada/core/segmenter.py b/linux/cicada/core/segmenter.py
index fa1640e..a9c7ca6 100644
--- a/linux/cicada/core/segmenter.py
+++ b/linux/cicada/core/segmenter.py
@@ -30,7 +30,9 @@ class Segment:
class Segmenter:
- threshold = 0.01 # the Mac AudioRouter's gate (about -40 dBFS)
+ # The Mac AudioRouter's gate (about -40 dBFS). A room microphone's segmenter has it set by
+ # roommic.VoiceGate as the room's noise is learnt.
+ threshold = 0.01
pause = 0.6
max_length = 8.0
min_speech = 0.25
@@ -95,19 +97,18 @@ class Segmenter:
cut = i
self._close(cut * FRAME)
- @classmethod
- def _steady(cls, levels) -> bool:
+ def _steady(self, levels) -> bool:
"""Steady sound just over the gate (a fan, hum, hiss) isn't speech: its loud frames barely vary
(90th / 10th percentile about 1.1; speech, even over such a floor, 3 and up). Given one, Ming
writes a stock sentence in the hint's language ("I'm going to show you a couple of things").
Speech buried under steady noise goes too; system audio rarely carries it. Every frame from
the first loud one to the last counts, the quiet ones held at the gate: counting only the
loud ones dropped quiet speech (under about -30 dBFS), whose dips fall below the gate."""
- loud = [i for i, l in enumerate(levels) if l >= cls.threshold]
+ loud = [i for i, l in enumerate(levels) if l >= self.threshold]
if len(loud) < 2:
return False
- body = sorted(max(l, cls.threshold) for l in levels[loud[0]:loud[-1] + 1])
- return body[int(0.9 * (len(body) - 1))] < cls.steady * body[int(0.1 * (len(body) - 1))]
+ body = sorted(max(l, self.threshold) for l in levels[loud[0]:loud[-1] + 1])
+ return body[int(0.9 * (len(body) - 1))] < self.steady * body[int(0.1 * (len(body) - 1))]
def _close(self, end_at: int) -> None:
"""Emits current[:end] and keeps what follows as the start of the next segment."""
diff --git a/linux/cicada/core/session_store.py b/linux/cicada/core/session_store.py
index 43c13bd..a160a4c 100644
--- a/linux/cicada/core/session_store.py
+++ b/linux/cicada/core/session_store.py
@@ -186,6 +186,14 @@ class SessionStore:
s.voiceGuesses = vg or None
self._mutate(sid, change)
+ def mark_room(self, sid: str) -> None:
+ """The meeting is (now) heard in the room: its record says 会议室 (the Mac's markLiveInRoom)."""
+ with self._gate:
+ s = self._sessions.get(sid)
+ if s is None or s.room:
+ return
+ self._mutate(sid, lambda s: setattr(s, "room", True))
+
def set_notes(self, sid: str, notes) -> None:
self._mutate(sid, lambda s: setattr(s, "notes", notes))
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index d855f2a..661ad5b 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -39,6 +39,10 @@ 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, "" = 自动.
+ "listenSource": "system",
+ "roomMic": "",
# 结束会议 (meeting_end.py), the Mac's keys: end when the meeting app hangs up; when nobody
# speaks, "prompt" (count down, then end), "end" or "off", after silenceMinutes.
"endWithApp": True,
@@ -46,6 +50,8 @@ class AppSettings:
"silenceMinutes": 10,
}
+ SOURCES = ("system", "room")
+
def __init__(self, **kw):
for k, v in self.FIELDS.items():
v = kw.get(k, v)
@@ -71,6 +77,11 @@ class AppSettings:
(`meeting`, the one it was heard in) for "source", else mine (the Mac's notesLanguageCode)."""
return meeting if (choice or self.notesLanguage) == "source" and meeting else self.target_code
+ @property
+ def hears_room(self) -> bool:
+ """The room microphone is open: 会议室."""
+ return self.listenSource != "system"
+
@property
def speak_from_code(self) -> str:
return self.target_code if self.speakFrom == "system" else self.speakFrom
@@ -101,6 +112,8 @@ class AppSettings:
# 纪要语言 was "system" or a language code before it took the Mac's two choices.
if kw.get("notesLanguage") not in (None, "mine", "source"):
kw["notesLanguage"] = "mine"
+ if kw.get("listenSource") not in (None,) + AppSettings.SOURCES:
+ kw["listenSource"] = "system"
return AppSettings(**kw)
except OSError as e:
Log.d("settings: unreadable, defaults used (%s)" % type(e).__name__)
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index 5a5989e..9b91084 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -179,3 +179,7 @@
"%lld 天前开会时用过" = "used in a meeting %lld days ago";
"文字 %@ 秒" = "text %@ s";
"听 %@ 秒" = "hearing %@ s";
+"知了 · 会议室" = "Cicada · Room";
+"换" = "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";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index d4a8617..9d0fc88 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -179,3 +179,7 @@
"%lld 天前开会时用过" = "%lld 日前に会議で使用";
"文字 %@ 秒" = "テキスト %@ 秒";
"听 %@ 秒" = "聞き取り %@ 秒";
+"知了 · 会议室" = "知了 · 会議室";
+"换" = "変更";
+"正在用麦克风听会议室,有人说话后约 3 秒出字幕" = "マイクで会議室を聞いています。話し始めて約 3 秒で字幕が出ます";
+"戴着蓝牙耳机时,自动用电脑自带的麦克风" = "Bluetooth ヘッドセット使用中は、自動でパソコン内蔵のマイクを使います";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 3743105..119d22f 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -179,3 +179,7 @@
"%lld 天前开会时用过" = "%lld일 전 회의에서 사용함";
"文字 %@ 秒" = "텍스트 %@초";
"听 %@ 秒" = "듣기 %@초";
+"知了 · 会议室" = "Cicada · 회의실";
+"换" = "변경";
+"正在用麦克风听会议室,有人说话后约 3 秒出字幕" = "마이크로 회의실을 듣고 있습니다. 말하면 약 3초 뒤 자막이 나옵니다";
+"戴着蓝牙耳机时,自动用电脑自带的麦克风" = "블루투스 헤드셋을 쓰는 동안 자동으로 컴퓨터 내장 마이크를 씁니다";
diff --git a/linux/tests/test_hybrid.py b/linux/tests/test_hybrid.py
new file mode 100644
index 0000000..35e0c44
--- /dev/null
+++ b/linux/tests/test_hybrid.py
@@ -0,0 +1,175 @@
+"""听哪里 on Linux: 会议室 (a microphone in the room) and 电脑和会议室 (both at once), the Mac's
+HybridTests / HybridRecordTests case for case where the logic is shared."""
+from __future__ import annotations
+
+import threading
+import time
+
+from test_core import Base, Fake, client, concat, reply, silence, tone
+
+from cicada.core.audio import PcmAudioSource
+from cicada.core.ling import LingClient
+from cicada.core.listen import ListenEngine
+from cicada.core.notes import NotesEngine
+from cicada.core.roommic import Input, VoiceGate, parse_sources, pick
+from cicada.core.session_store import SessionStore
+from cicada.core.settings import AppSettings
+from cicada.core.translator import Translator
+
+PACTL = """Source #47
+\tState: SUSPENDED
+\tName: alsa_output.pci-0000_00_05.0.analog-stereo.monitor
+\tDescription: Monitor of Built-in Audio
+\tMonitor of Sink: alsa_output.pci-0000_00_05.0.analog-stereo
+\tProperties:
+\t\tdevice.api = "alsa"
+\t\tdevice.class = "monitor"
+\t\tdevice.bus = "pci"
+Source #48
+\tState: SUSPENDED
+\tName: alsa_input.pci-0000_00_05.0.analog-stereo
+\tDescription: Built-in Audio Analog Stereo
+\tMonitor of Sink: n/a
+\tProperties:
+\t\tdevice.api = "alsa"
+\t\tdevice.class = "sound"
+\t\tdevice.bus = "pci"
+\t\tdevice.form_factor = "internal"
+Source #60
+\tName: bluez_input.AA_BB_CC_DD_EE_FF.0
+\tDescription: WH-1000XM4
+\tMonitor of Sink: n/a
+\tProperties:
+\t\tdevice.api = "bluez5"
+\t\tdevice.bus = "bluetooth"
+Source #61
+\tName: alsa_input.usb-Jabra_Speak_510-00.mono-fallback
+\tDescription: Jabra SPEAK 510 Mono
+\tMonitor of Sink: n/a
+\tProperties:
+\t\tdevice.api = "alsa"
+\t\tdevice.bus = "usb"
+Source #70
+\tName: cicada_mic
+\tDescription: 知了 麦克风
+\tMonitor of Sink: n/a
+\tProperties:
+\t\tdevice.class = "filter"
+"""
+
+
+class Microphones(Base):
+ def test_reads_the_inputs(self):
+ got = {i.name: i for i in parse_sources(PACTL)}
+ self.assertEqual(5, len(got))
+ self.assertTrue(got["alsa_output.pci-0000_00_05.0.analog-stereo.monitor"].virtual)
+ self.assertTrue(got["cicada_mic"].virtual, "知了 麦克风 hears no room")
+ built_in = got["alsa_input.pci-0000_00_05.0.analog-stereo"]
+ self.assertTrue(built_in.builtin and not built_in.virtual)
+ self.assertTrue(got["bluez_input.AA_BB_CC_DD_EE_FF.0"].bluetooth)
+ usb = got["alsa_input.usb-Jabra_Speak_510-00.mono-fallback"]
+ self.assertFalse(usb.builtin or usb.bluetooth or usb.virtual)
+ self.assertEqual("Jabra SPEAK 510 Mono", usb.description)
+
+ def test_picks_like_the_mac(self):
+ # RoomMicPlan: the default unless virtual or a Bluetooth headset's, then the built-in one.
+ inputs = parse_sources(PACTL)
+ usb = "alsa_input.usb-Jabra_Speak_510-00.mono-fallback"
+ built_in = "alsa_input.pci-0000_00_05.0.analog-stereo"
+ self.assertEqual(usb, pick(usb, inputs))
+ self.assertEqual(built_in, pick("bluez_input.AA_BB_CC_DD_EE_FF.0", inputs))
+ self.assertEqual(built_in, pick("cicada_mic", inputs))
+ self.assertEqual(built_in, pick(None, inputs))
+ # Chosen in 设置 › 会议室, while it is plugged in.
+ self.assertEqual(usb, pick(built_in, inputs, chosen=usb))
+ self.assertEqual(built_in, pick(built_in, inputs, chosen="gone"))
+ # Only a headset: better than nothing.
+ bt = [Input("bt", bluetooth=True), Input("cicada_mic", virtual=True)]
+ self.assertEqual("bt", pick("cicada_mic", bt))
+ self.assertIsNone(pick(None, [Input("m", virtual=True)]))
+
+ def test_voice_gate_learns_the_room(self):
+ fixed = VoiceGate()
+ self.assertFalse(fixed.voiced(0.006))
+ g = VoiceGate(adaptive=True)
+ self.assertEqual(0.004, g.threshold)
+ # Ten seconds of a quiet room (0.001) with talk at 0.006.
+ for i in range(100):
+ g.voiced(0.001 if i % 10 == 0 else 0.006, 0.1)
+ self.assertLess(g.threshold, 0.003)
+ self.assertGreaterEqual(g.threshold, VoiceGate.lowest)
+ self.assertTrue(g.voiced(0.006))
+ # A loud room: the line never goes over the fixed gate.
+ for _ in range(400):
+ g.voiced(0.05, 0.1)
+ self.assertEqual(VoiceGate.fixed, g.threshold)
+
+
+def engine(store):
+ LingClient.spacing = 0.02
+ ling = client(Fake(lambda b: reply("LANG: en\nORIGINAL: Hello from the table.\nTRANSLATION: 桌边的人好。")
+ if "Ming-3.0-audio-flash" in b else reply("{}")))
+ return ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target="zh-CN"))
+
+
+def run(e, pcm, mic):
+ src = PcmAudioSource(lambda: pcm, speed=0)
+ ended = threading.Event()
+ src.on_ended = lambda why: ended.set()
+ e.start(src, "room" if mic else "system", mic=mic)
+ ended.wait(10)
+ time.sleep(0.3)
+ e.stop()
+
+
+class Room(Base):
+ QUIET = concat(silence(3.5), tone(1.0, amp=0.01), silence(1.0)) # a voice across the table, under -40 dBFS
+
+ def test_a_quiet_voice_in_the_room_is_heard(self):
+ store = SessionStore()
+ e = engine(store)
+ run(e, self.QUIET, mic=True)
+ 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")
+
+ def test_the_computers_audio_keeps_the_fixed_gate(self):
+ store = SessionStore()
+ e = engine(store)
+ run(e, self.QUIET, mic=False)
+ self.assertIsNone(store.get(e.session_id), "nothing heard, nothing kept")
+
+ def test_changing_source_mid_meeting_goes_on_in_the_same_meeting(self):
+ store = SessionStore()
+ e = engine(store)
+ first = PcmAudioSource(lambda: silence(0.5), speed=0)
+ e.start(first, "system")
+ sid = e.session_id
+ time.sleep(0.2)
+ mic = PcmAudioSource(lambda: self.QUIET, speed=0)
+ ended = threading.Event()
+ mic.on_ended = lambda why: ended.set()
+ e.attach(mic, mic=True)
+ ended.wait(10)
+ time.sleep(0.3)
+ e.stop()
+ s = store.get(sid)
+ self.assertEqual(1, len(s.lines))
+ self.assertTrue(s.room)
+
+ def test_muted_while_i_speak_through_the_same_mic(self):
+ store = SessionStore()
+ e = engine(store)
+ src = PcmAudioSource(lambda: self.QUIET, speed=0)
+ ended = threading.Event()
+ src.on_ended = lambda why: ended.set()
+ # Muted before any audio arrives: the worker replaces it with silence.
+ e.start(PcmAudioSource(lambda: silence(0.1), speed=0), "room", mic=True)
+ e.set_muted(True)
+ e.attach(src, mic=True)
+ e.set_muted(True)
+ ended.wait(10)
+ time.sleep(0.3)
+ e.stop()
+ self.assertEqual(0, len(store.get(e.session_id).lines) if store.get(e.session_id) else 0)
diff --git a/site/changelog.json b/site/changelog.json
index a2bf67a..6bb388e 100644
--- a/site/changelog.json
+++ b/site/changelog.json
@@ -125,6 +125,14 @@
],
"title": "Windows 的“听哪里”也有了“电脑和会议室”:线上和桌边的人一起听,每句标出现场还是线上。",
"text": "电脑声音和麦克风各认各的语言。Windows 上没有可用的回声消除,电脑在放人声时麦克风先不听,最后再按文字去掉重复的一句;只听会议室时会议软件开始通话,会问要不要也听电脑。"
+ },
+ {
+ "kind": "new",
+ "platforms": [
+ "linux"
+ ],
+ "title": "Linux 上“听哪里”可以选“会议室”:用麦克风听桌边的人。",
+ "text": "顶栏菜单、纪要窗和设置里都能换,开会中途换也接着记在同一场里。会议室的底噪会自己学,隔着桌子小声说话也能出字幕;戴着蓝牙耳机时自动改用电脑自带的麦克风。同声传译开着时,麦克风听到的是你,会议室这边先不记。"
}
]
},