知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat(windows): Listen to › Room hears the people at the table through a microphone
wquguru85e1cbf63747
diff --git a/site/changelog.json b/site/changelog.jsonindex 08a30c8..076d29b 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -109,6 +109,14 @@],"title": "Windows 打开 Mac 上“电脑和会议室”的会议记录,不再丢掉每句话是现场还是线上。","text": "原来在 Windows 上改名或重写纪要后,这个标记会从记录里消失,回到 Mac 上就分不出来了。"+ },+ {+ "kind": "new",+ "platforms": [+ "windows"+ ],+ "title": "Windows 也能听会议室:用麦克风听桌边的人。",+ "text": "托盘面板的“听哪里”选“会议室”;默认麦克风是蓝牙耳机时改用别的麦克风,按住说话时麦克风先不听;会议中途切换,同一场会议接着记。"}]},diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.csindex bc3c137..9903896 100644--- a/windows/src/Cicada.Core/ListenEngine.cs+++ b/windows/src/Cicada.Core/ListenEngine.cs@@ -89,11 +89,16 @@ public sealed class ListenEnginepublic string Target => settings.TargetCode;- public void Start(IAudioSource from)+ /// 会议室: what listening hears is a microphone (its speech line follows the room's noise).+ public bool Room { get; private set; }++ public void Start(IAudioSource from, bool room = false){if (Listening) return;var session = store.Begin();SessionId = session.Id;+ Room = room;+ if (room) store.MarkRoom(session.Id);lock (gate){done.Clear(); segments.Clear(); inFlight.Clear(); prints.Clear(); clusterer = new();@@ -102,7 +107,7 @@ public sealed class ListenEngine}notes.Language = () => Languages.EnglishName(settings.NotesCode);notes.Begin(session.Id);- segmenter = new Segmenter();+ segmenter = new Segmenter(room ? new VoiceGate() : null);segmenter.Emitted += Send;audio = Channel.CreateUnbounded<short[]>(new UnboundedChannelOptions { SingleReader = true });var reader = audio.Reader;@@ -126,6 +131,22 @@ public sealed class ListenEnginevoid OnSamples(short[] buf) => audio?.Writer.TryWrite(buf);+ /// 听哪里 changed mid-meeting between the computer and the room: the same meeting goes on from the+ /// other source, its clock running on.+ public void SwitchSource(IAudioSource to, bool room)+ {+ if (!Listening || SessionId is not { } id) return;+ if (source is not null) { source.Samples -= OnSamples; source.Stop(); }+ if (room) store.MarkRoom(id);+ Room = room;+ if (segmenter is not null) segmenter.Gate = room ? new VoiceGate() : null;+ source = to;+ source.Samples += OnSamples;+ source.Start();+ Log.Debug($"listen: now {(room ? "the room" : "the computer")}");+ Changed?.Invoke();+ }+static double Rms(short[] buf){if (buf.Length == 0) return 0;diff --git a/windows/src/Cicada.Core/Room.cs b/windows/src/Cicada.Core/Room.csnew file mode 100644index 0000000..fe99126--- /dev/null+++ b/windows/src/Cicada.Core/Room.cs@@ -0,0 +1,88 @@+namespace Cicada;++// 听哪里 (the Mac's RoomMic.swift and EchoMatch.swift): 电脑声音, 会议室 (a microphone hears the+// people at the table), or 电脑和会议室 (both, each with its own ListenEngine). The parts that don't+// touch a device live here so they test on the Mac.++/// The Mac's `listenSource` values.+public static class ListenSource+{+ public const string System = "system", Room = "room", Both = "both";+ public static string Parse(string? s) => s is Room or Both ? s : System;+}++/// Which microphone hears the room.+public static class RoomMicPlan+{+ public sealed record Input(string Id, bool Bluetooth = false, bool Virtual = false);++ /// The default input, unless it is the virtual cable (同声传译's) or a Bluetooth headset's (it+ /// hears the wearer, not the table, and drops to call quality while its mic is open); then the+ /// first other one, a headset only when nothing else is left.+ public static string? Pick(string? defaultId, IReadOnlyList<Input> inputs)+ {+ if (inputs.FirstOrDefault(i => i.Id == defaultId) is { Virtual: false, Bluetooth: false } d) return d.Id;+ return inputs.FirstOrDefault(i => !i.Virtual && !i.Bluetooth)?.Id ?? inputs.FirstOrDefault(i => !i.Virtual)?.Id;+ }+}++/// When a frame counts as speech. 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 that: there the line sits at twice the room's own noise,+/// the quietest moment of each second taken low over the last half minute (VoiceGate in RoomMic.swift).+public sealed class VoiceGate+{+ public const double Fixed = 0.01, Lowest = 0.0015;+ readonly List<double> quietest = [];+ double second = double.PositiveInfinity, elapsed;++ public double Threshold+ {+ get+ {+ if (quietest.Count < 3) return 0.004;+ var floor = quietest.Order().ElementAt(quietest.Count / 5);+ return Math.Min(Fixed, Math.Max(Lowest, floor * 2));+ }+ }++ /// Takes one frame's level and length; true when it is over the line.+ public bool Voiced(double rms, double seconds)+ {+ var on = rms >= Threshold;+ second = Math.Min(second, rms);+ elapsed += seconds;+ if (elapsed >= 1 - 1e-9)+ {+ quietest.Add(second);+ if (quietest.Count > 30) quietest.RemoveAt(0);+ second = double.PositiveInfinity;+ elapsed = 0;+ }+ return on;+ }+}++/// The room mic as listening hears it: silence while `Muted` (you holding the talk key) or while+/// `Silenced` says so (电脑和会议室's echo gate). Silence rather than nothing keeps the segmenter's+/// clock in step.+public sealed class GatedSource : IAudioSource+{+ readonly IAudioSource inner;+ public Func<bool>? Silenced { get; set; }+ public volatile bool Muted;+ public event Action<short[]>? Samples;+ public event Action<string?>? Ended;+ /// The microphone's name, for the log and the panel.+ public string? Name { get; init; }++ public GatedSource(IAudioSource inner)+ {+ this.inner = inner;+ inner.Samples += buf => Samples?.Invoke(Muted || Silenced?.Invoke() == true ?new short[buf.Length] : buf);+ inner.Ended += why => Ended?.Invoke(why);+ }++ public void Start() => inner.Start();+ public void Stop() => inner.Stop();+}diff --git a/windows/src/Cicada.Core/Segmenter.cs b/windows/src/Cicada.Core/Segmenter.csindex 7edb925..f8a7b9f 100644--- a/windows/src/Cicada.Core/Segmenter.cs+++ b/windows/src/Cicada.Core/Segmenter.cs@@ -27,6 +27,16 @@ public sealed class Segmenterlong consumed; // samples seen, for timestampsdouble currentStart;int quietFrames, loudFrames, index;+ /// 会议室: a microphone's line follows the room's noise (VoiceGate); null keeps the fixed one.+ /// Swapped when 听哪里 changes mid-meeting (read once per frame on the audio thread).+ public VoiceGate? Gate { get => gate; set => gate = value; }+ volatile VoiceGate? gate;+ double line = Threshold;++ public Segmenter(VoiceGate? gate = null) { this.gate = gate; }++ /// The level that counts as speech right now.+ public double Line => line;public event Action<Segment>? Emitted;@@ -58,7 +68,9 @@ public sealed class Segmentervoid Step(short[] frame){double level = Rms(frame);- bool loud = level >= Threshold;+ var g = gate;+ line = g?.Threshold ?? Threshold;+ bool loud = g?.Voiced(level, Frame / (double)Rate) ?? level >= line;double now = consumed / (double)Rate;consumed += frame.Length;@@ -100,12 +112,13 @@ public sealed class Segmenter/// 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.- internal static bool IsSteady(IEnumerable<double> frameLevels)+ internal static bool IsSteady(IEnumerable<double> frameLevels, double? gate = null){var all = frameLevels.ToList();- int first = all.FindIndex(l => l >= Threshold), last = all.FindLastIndex(l => l >= Threshold);+ var threshold = gate ?? Threshold;+ int first = all.FindIndex(l => l >= threshold), last = all.FindLastIndex(l => l >= threshold);if (first < 0 || last <= first) return false;- var body = all.GetRange(first, last - first + 1).Select(l => Math.Max(l, Threshold)).Order().ToList();+ var body = all.GetRange(first, last - first + 1).Select(l => Math.Max(l, threshold)).Order().ToList();return body[(int)(0.9 * (body.Count - 1))] < Steady * body[(int)(0.1 * (body.Count - 1))];}@@ -117,21 +130,21 @@ public sealed class Segmentervar rest = current.GetRange(end, current.Count - end);var restLevels = levels.GetRange(end / Frame, levels.Count - end / Frame);double start = currentStart;- bool speech = loudFrames * Frame >= MinSpeech * Rate && !IsSteady(levels.GetRange(0, Math.Min(levels.Count, end / Frame)));+ bool speech = loudFrames * Frame >= MinSpeech * Rate && !IsSteady(levels.GetRange(0, Math.Min(levels.Count, end / Frame)), line);current.Clear(); levels.Clear();quietFrames = 0; loudFrames = 0;if (speech) Emitted?.Invoke(new Segment(++index, Math.Round(start, 3), samples));// A forced cut carries on with the remainder; after a pause the remainder is silence.- if (restLevels.Any(l => l >= Threshold))+ if (restLevels.Any(l => l >= line)){currentStart = start + end / (double)Rate;current.AddRange(rest);levels.AddRange(restLevels);int trailing = 0;- for (int i = levels.Count - 1; i >= 0 && levels[i] < Threshold; i--) trailing++;+ for (int i = levels.Count - 1; i >= 0 && levels[i] < line; i--) trailing++;quietFrames = trailing;- loudFrames = levels.Count(l => l >= Threshold);+ loudFrames = levels.Count(l => l >= line);}}}diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.csindex 86740f5..8af5dbd 100644--- a/windows/src/Cicada.Core/SessionStore.cs+++ b/windows/src/Cicada.Core/SessionStore.cs@@ -99,6 +99,12 @@ public sealed class SessionStorepublic void SetNotes(string id, MeetingNotes notes) => Mutate(id, s => s.Notes = notes);+ /// Heard through a microphone in the room for some or all of it (SessionStore.swift › markLiveInRoom).+ public void MarkRoom(string id)+ {+ if (Get(id) is { Room: not true }) Mutate(id, s => s.Room = true);+ }+/// An empty title, or the one shown already, goes back to / stays on the automatic one/// (SessionStore.swift › rename): saving the dialog unchanged mustn't freeze the notes' name.public void Rename(string id, string title)diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex 9408b0d..1885ba6 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -21,6 +21,11 @@ public sealed class AppSettings[JsonPropertyName("aiCustomBase")] public string AiCustomBase { get; set; } = "";[JsonPropertyName("aiCustomVoiceBase")] public string AiCustomVoiceBase { get; set; } = "";[JsonPropertyName("aiCustomVoice")] public string AiCustomVoice { get; set; } = "";+ /// 听哪里 (the Mac's key): "system" (电脑声音), "room" (会议室) or "both" (电脑和会议室).+ [JsonPropertyName("listenSource")] public string ListenSourceValue { get; set; } = ListenSource.System;+ [JsonIgnore] public string Listens => ListenSource.Parse(ListenSourceValue);+ [JsonIgnore] public bool ListensToRoom => Listens == ListenSource.Room;+ [JsonIgnore] public bool HearsBoth => Listens == ListenSource.Both;/// "notes" (the notes window, default) or "subtitles" (the subtitle bar).[JsonPropertyName("view")] public string View { get; set; } = "notes";/// Whether 知了还在任务栏右下角 was shown, after the first × on a window.diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 8833c3d..808c9b9 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -312,7 +312,57 @@ sealed class Controllerpublic async Task ToggleListening(){if (Listen.Listening) RequestStop();- else await StartChecked(() => new SystemAudioTap());+ else await StartChecked(NewSource);+ }++ /// What 听哪里 says to listen to: the PC's audio, or the room through a microphone.+ public IAudioSource NewSource() => Settings.ListensToRoom ? RoomSource() : new SystemAudioTap();++ /// The room mic, muted while you hold the talk key. Dev: a WAV stands in (the VM has no mic).+ GatedSource RoomSource()+ {+ if (fakeRoom is { } wav) return new GatedSource(new FileAudioSource(wav)) { Name = "fake" };+ return new GatedSource(new MicSource(Endpoints.RoomMic)) { Muted = Speak.State == SpeakEngine.Phase.Recording };+ }++ /// The room mic listening hears right now, if any (muted while you speak).+ readonly List<GatedSource> roomSources = [];++ /// Dev builds: a WAV the room mic hears instead of a microphone.+ string? fakeRoom;+ public void SetFakeRoom(string? path) { fakeRoom = path; Log.Debug($"room: fake mic {(path is null ? "off" : "on")}"); }++ /// 听哪里 changed. While listening the same meeting goes on from the new source.+ public void SetListenSource(string value)+ {+ value = ListenSource.Parse(value);+ if (value == Settings.Listens) return;+ Settings.ListenSourceValue = value;+ Settings.Save();+ Log.Debug($"listen source: {value}");+ if (Listen.Listening && Listen.Room != Settings.ListensToRoom) Listen.SwitchSource(Watch(NewSource()), Settings.ListensToRoom);+ Changed();+ }++ /// A source about to be listened to: a room mic is remembered (the talk key mutes it), and one+ /// that can't go on says why.+ IAudioSource Watch(IAudioSource source)+ {+ if (source is GatedSource room) roomSources.Add(room);+ source.Ended += reason =>+ {+ if (reason is null) return;+ Log.Debug($"listen: source ended {reason}");+ Dispatch.BeginInvoke(() =>+ {+ if (source is GatedSource && reason == "denied")+ Toast(L("听会议室要先允许麦克风"), L("Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风"), () => Open("ms-settings:privacy-microphone"));+ else if (source is GatedSource && reason == "none")+ Toast(L("没有可用的麦克风"), L("插上麦克风后再开始听。"));+ _ = StopListening();+ });+ };+ return source;}/// The user's 开始听: blocked only by a failure the last result knows of. A hear model that@@ -390,16 +440,11 @@ sealed class Controller{if (Listen.Listening) return;if (!Ling.HasKey) { ShowOnboarding(0); return; }- source.Ended += reason =>- {- if (reason is null) return;- Log.Debug($"listen: source ended {reason}");- Dispatch.BeginInvoke(() => _ = StopListening());- };+ Watch(source);AutoEnded = false;Ending = null;endWatch = new MeetingEndWatch(EndConfig(), DateTimeOffset.Now);- Listen.Start(source);+ Listen.Start(source, room: source is GatedSource);ShowNotes();}@@ -410,6 +455,7 @@ sealed class ControllerEnding = null;ConfirmingEnd = false;AutoEnded = auto;+ roomSources.Clear();await Listen.Stop(endedAt);Changed();NotifyUpdate(); // held while the meeting was on@@ -453,7 +499,7 @@ sealed class Controllerelse if (!Listen.Listening && AutoEnded && Settings.EndWithApp && calls.Count > 0){Log.Debug("meeting end: a meeting app started a call, starting a new meeting");- StartListening(new SystemAudioTap());+ StartListening(NewSource());}}@@ -571,12 +617,15 @@ sealed class Controllerif (mic.Error is { } err) { mic = null; Speak.Report(err == "denied" ? L("Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风") : L("麦克风打不开")); return; }}Speak.BeginRecording();+ // What you say isn't someone in the room.+ foreach (var r in roomSources) r.Muted = true;}void PressEnded(){+ foreach (var r in roomSources) r.Muted = false;if (Speak.State != SpeakEngine.Phase.Recording) return;- var pcm = fakeMic is { } f ? Wav.Read(f) : mic?.Stop() ?? [];+ var pcm =fakeMic is { } f ? Wav.Read(f) : mic?.Stop() ?? [];mic = null;// A tap, not a sentence.if (pcm.Length < Segmenter.Rate * 3 / 10) { Speak.Cancel(); return; }@@ -917,12 +966,15 @@ sealed class Controller["update"] = Updates.Available?.Version,["updateChecked"] = Updates.LastChecked?.ToString("o"),["inCall"] = endWatch is { } w ? string.Join(",", w.InCall.Values) : null,+ ["listenSource"] = Settings.Listens,+ ["room"] = Listen.Room,};}/// Debug commands over a named pipe (\\.\pipe\cicada-dev), dev builds only: the Windows/// counterpart of the Mac's `tools/lsctl`. One command per connection, one JSON line back./// state | start | stop | feed <wav> | sample | view notes|subtitles | capture on|off+/// listensource system|room|both | fakeroom <wav>|off (a WAV the room mic hears; the VM has no mic)/// show notes|records|settings [page]|flyout|menu | quit/// updatefeed <url or file> | checkupdate/// calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep@@ -976,7 +1028,9 @@ static class DebugServer"quit" => Quitting(app),_ => Opened(app),};- case "start": _ = app.StartChecked(() => new SystemAudioTap()); break;+ case "start": _ = app.StartChecked(app.NewSource); break;+ case "listensource": app.SetListenSource(arg); break;+ case "fakeroom": app.SetFakeRoom(arg is "" or "off" ? null : arg); break;case "stop": _ = app.StopListening(); break;case "end": app.RequestStop(); break; // the user's 结束: asks first when anything was saidcase "notesproblem": app.Notes.SimulateStatus(arg); break;diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.csindex adf6f92..6e2a99a 100644--- a/windows/src/Cicada/MainWindow.cs+++ b/windows/src/Cicada/MainWindow.cs@@ -401,6 +401,7 @@ sealed class MainWindow : Windowvar into = s.Lines.Select(l => l.DstLang).FirstOrDefault(x => x is not null);var meta = new List<string> { local.ToString(L("M月d日"), Culture) + " " + local.ToString("HH:mm", Culture) };meta.Add(live ? L("正在听") : LF("%@ 分钟", Math.Max(1, (int)Math.Round(s.Duration.TotalMinutes))));+ if (s.Room == true) meta.Add(L("会议室"));if (spoken is not null && into is not null) meta.Add($"{Ui.SpokenName(spoken)} → {Ui.TargetName(into)}");top.Children.Add(Ui.Text(string.Join(" · ", meta), 13, live ? Palette.AccentText : Palette.Secondary));diff --git a/windows/src/Cicada/MicSource.cs b/windows/src/Cicada/MicSource.csnew file mode 100644index 0000000..d6dd19a--- /dev/null+++ b/windows/src/Cicada/MicSource.cs@@ -0,0 +1,96 @@+using System.Runtime.InteropServices;++namespace Cicada.App;++/// 会议室: a microphone as a listening source, 16 kHz mono (Windows converts), handed on as it comes+/// in (DeviceRecorder keeps it all instead). A device pulled out or switched off ends its stream:+/// the room mic is picked again and capture goes on, so the room doesn't go quiet for the rest of+/// the meeting. Ends with "denied" when Windows' microphone privacy switch is off for desktop apps,+/// "none" when no microphone is left.+sealed class MicSource : IAudioSource+{+ readonly Func<Endpoints.Device?> pick;+ Thread? thread;+ volatile bool running;+ public event Action<short[]>? Samples;+ public event Action<string?>? Ended;+ /// The microphone in use.+ public string? DeviceName { get; private set; }++ public MicSource(Func<Endpoints.Device?> pick) { this.pick = pick; }++ public void Start()+ {+ running = true;+ thread = new Thread(Run) { IsBackground = true, Name = "MicSource", Priority = ThreadPriority.AboveNormal };+ thread.SetApartmentState(ApartmentState.MTA);+ thread.Start();+ }++ public void Stop()+ {+ running = false;+ thread?.Join(1000);+ }++ void Run()+ {+ int failures = 0;+ while (running)+ {+ if (pick() is not { } device) { Log.Debug("mic: no microphone"); Ended?.Invoke("none"); return; }+ DeviceName = device.Name;+ var started = DateTime.UtcNow;+ try { Capture(device.Id); return; }+ catch (Exception e) when (e.HResult == unchecked((int)0x80070005))+ {+ Log.Debug("mic: denied by Windows' microphone privacy setting");+ Ended?.Invoke("denied");+ return;+ }+ catch (Exception e)+ {+ // 0x88890004 AUDCLNT_E_DEVICE_INVALIDATED: unplugged, disabled, or its format changed.+ Log.Debug($"mic: {device.Name} stopped 0x{e.HResult:X8}, picking the room mic again");+ failures = DateTime.UtcNow - started > TimeSpan.FromSeconds(10) ? 1 : failures + 1;+ if (failures > 5) { Ended?.Invoke(e.Message); return; }+ Thread.Sleep(300 * failures);+ }+ }+ }++ void Capture(string id)+ {+ IAudioClient? client = null;+ try+ {+ client = Endpoints.Activate(id);+ var fmt = Endpoints.Pcm16(16000);+ // A 1 s buffer, as the system tap's: a capture thread held up a moment loses nothing.+ int hr = client.Initialize(0, Endpoints.AutoConvert, 10_000_000, 0, fmt, IntPtr.Zero);+ Marshal.FreeHGlobal(fmt);+ Marshal.ThrowExceptionForHR(hr);+ var iid = typeof(IAudioCaptureClient).GUID;+ Marshal.ThrowExceptionForHR(client.GetService(ref iid, out var s));+ var cap = (IAudioCaptureClient)s;+ Marshal.ThrowExceptionForHR(client.Start());+ Log.Debug($"mic: capturing {DeviceName}");+ while (running)+ {+ Thread.Sleep(20);+ while (true)+ {+ Marshal.ThrowExceptionForHR(cap.GetNextPacketSize(out var n));+ if (n == 0) break;+ Marshal.ThrowExceptionForHR(cap.GetBuffer(out var data, out var frames, out var flags, out _, out _));+ var buf = new short[frames];+ if ((flags & 0x2) == 0) Marshal.Copy(data, buf, 0, (int)frames);+ cap.ReleaseBuffer(frames);+ if (frames > 0) Samples?.Invoke(buf);+ }+ }+ client.Stop();+ }+ finally { if (client is not null) Marshal.ReleaseComObject(client); }+ }+}diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.stringsindex a1490b7..bc3dc4c 100644--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings@@ -299,3 +299,8 @@"%lld 小时前" = "%lld hr ago";"%lld 天前" = "%lld days ago";"这段时间的话没能识别。网络恢复后自动继续。" = "Some audio couldn't be transcribed. It picks up again when the network is back.";++/* 听哪里 › 会议室: the Mac's words name the Mac. */+"插上麦克风后再开始听。" = "Plug in a microphone, then start again.";+"电脑声音" = "This PC";+"电脑声音(线上会议、视频)" = "This PC (online meetings, videos)";diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.stringsindex ad84a25..126d300 100644--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings@@ -299,3 +299,8 @@"%lld 小时前" = "%lld 時間前";"%lld 天前" = "%lld 日前";"这段时间的话没能识别。网络恢复后自动继续。" = "この間の音声を認識できませんでした。ネットワークが戻ると自動で再開します。";++/* 听哪里 › 会议室: the Mac's words name the Mac. */+"插上麦克风后再开始听。" = "マイクをつないでからもう一度始めてください。";+"电脑声音" = "この PC";+"电脑声音(线上会议、视频)" = "この PC(オンライン会議・動画)";diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.stringsindex 4f73b75..69c5523 100644--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings@@ -299,3 +299,8 @@"%lld 小时前" = "%lld시간 전";"%lld 天前" = "%lld일 전";"这段时间的话没能识别。网络恢复后自动继续。" = "이 구간의 음성을 인식하지 못했습니다. 네트워크가 돌아오면 자동으로 이어집니다.";++/* 听哪里 › 会议室: the Mac's words name the Mac. */+"插上麦克风后再开始听。" = "마이크를 연결한 뒤 다시 시작하세요.";+"电脑声音" = "이 PC";+"电脑声音(线上会议、视频)" = "이 PC (온라인 회의, 동영상)";diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.csindex 7c15535..e301ada 100644--- a/windows/src/Cicada/TrayFlyout.cs+++ b/windows/src/Cicada/TrayFlyout.cs@@ -154,6 +154,9 @@ sealed class TrayFlyout : Windowvar spoken = Languages.Targets.FirstOrDefault(t => t.Code == Languages.FromSystem(System.Globalization.CultureInfo.CurrentUICulture.Name))?.Code;var target = s.Target == "system" ? spoken ?? "zh-Hans" : s.Target;stack.Children.Add(Gap(ChoiceRow(L("翻译成"), Ui.TargetName(target), s.Target == "system" ? L("跟随系统") : null, Ui.TargetOptions(), s.Target, app.SetTarget), 12));+ // 听哪里 (the Mac panel's row): changing it mid-meeting carries the same meeting on.+ var sources = new[] { (ListenSource.System, L("电脑声音(线上会议、视频)")), (ListenSource.Room, L("会议室(用麦克风听桌边的人)")) };+ stack.Children.Add(Gap(ChoiceRow(L("听哪里"), SourceName(s.Listens), null, sources, s.Listens, app.SetListenSource), 8));// 同声传译stack.Children.Add(Rule());@@ -189,6 +192,13 @@ sealed class TrayFlyout : Windowreturn stack;}+ public static string SourceName(string source) => source switch+ {+ ListenSource.Room => L("会议室"),+ ListenSource.Both => L("电脑和会议室"),+ _ => L("电脑声音"),+ };+static FrameworkElement Gap(FrameworkElement e, double top) { e.Margin = new Thickness(e.Margin.Left, top, e.Margin.Right, e.Margin.Bottom); return e; }static FrameworkElement Rule() => new Border { Height = 1, Background = Palette.Line, Margin = new Thickness(0, 16, 0, 16) };diff --git a/windows/src/Cicada/Wasapi.cs b/windows/src/Cicada/Wasapi.csindex bc5f3e5..3c1e5c3 100644--- a/windows/src/Cicada/Wasapi.cs+++ b/windows/src/Cicada/Wasapi.cs@@ -54,6 +54,32 @@ static class Endpointsreturn All(Flow.Capture).FirstOrDefault(x => x.Description != VirtualCable.OutputName && !x.Name.StartsWith(VirtualCable.OutputName));}+ /// 会议室: the microphone that hears the table (RoomMicPlan): the default, unless that is the+ /// virtual cable or a Bluetooth headset.+ public static Device? RoomMic()+ {+ var inputs = new List<(Device d, RoomMicPlan.Input plan)>();+ try+ {+ var e = (IMMDeviceEnumerator)new MMDeviceEnumerator();+ Marshal.ThrowExceptionForHR(e.EnumAudioEndpoints((int)Flow.Capture, 1 /* ACTIVE */, out var all));+ all.GetCount(out var n);+ for (uint i = 0; i < n; i++)+ {+ all.Item(i, out var d);+ d.GetId(out var id);+ var device = new Device(id, Prop(d, 14) ?? id, Prop(d, 2) ?? "");+ // PKEY_Device_EnumeratorName: BTHENUM, BTHHFENUM, BTHLEDEVICE for Bluetooth.+ var bus = Prop(d, 24) ?? "";+ var virtualCable = device.Description == VirtualCable.OutputName || device.Name.StartsWith(VirtualCable.OutputName);+ inputs.Add((device, new RoomMicPlan.Input(id, bus.StartsWith("BTH", StringComparison.OrdinalIgnoreCase), virtualCable)));+ }+ }+ catch (Exception ex) { Log.Debug($"endpoints: inputs failed {ex.GetType().Name}"); }+ var pick = RoomMicPlan.Pick(Default(Flow.Capture)?.Id, inputs.Select(i => i.plan).ToList());+ return inputs.FirstOrDefault(i => i.d.Id == pick).d;+ }+static string? Prop(IMMDevice d, int pid){if (d.OpenPropertyStore(0, out var store) != 0) return null;diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 5069a52..36e6a4f 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -307,6 +307,54 @@ static class TestsCheck(JsonNode.DeepEquals(JsonNode.Parse(mac), JsonNode.Parse(Json.Write(s))), "written back with every key: " + Json.Write(s));}+ // MARK: 会议室++ public static void RoomMicSkipsTheCableAndHeadsets()+ {+ RoomMicPlan.Input usb = new("usb"), headset = new("bt", Bluetooth: true), cable = new("cable", Virtual: true);+ Equal("usb", RoomMicPlan.Pick("usb", [headset, usb]), "the default");+ Equal("usb", RoomMicPlan.Pick("bt", [headset, usb]), "a headset hears the wearer, not the table");+ Equal("usb", RoomMicPlan.Pick("cable", [cable, usb]), "never the virtual cable");+ Equal("bt", RoomMicPlan.Pick("cable", [cable, headset]), "a headset when nothing else is left");+ Equal(null, RoomMicPlan.Pick(null, [cable]), "no microphone");+ }++ public static void RoomSpeechLineFollowsTheNoise()+ {+ var gate = new VoiceGate();+ Equal(0.004, gate.Threshold, "before the room is known");+ // Half a minute of a fan at 0.003 with a voice at 0.02 now and then.+ for (int i = 0; i < 30 * 33; i++) gate.Voiced(i % 10 == 0 ? 0.02 : 0.003, 0.03);+ Check(Math.Abs(gate.Threshold - 0.006) < 1e-9, $"twice the room's noise, got {gate.Threshold}");+ Check(gate.Voiced(0.008, 0.03), "a quiet voice across the table");+ Check(!gate.Voiced(0.004, 0.03), "the fan");+ var loud = new VoiceGate();+ for (int i = 0; i < 200; i++) loud.Voiced(0.5, 0.03);+ Equal(VoiceGate.Fixed, loud.Threshold, "never above the computer's line");+ }++ public static void ARoomMicHearsQuietSpeechTheFixedLineMisses()+ {+ // A voice at -48 dBFS (0.004 RMS) over a quieter floor: under the fixed 0.01 line.+ var rng = new Random(1);+ short[] Noise(double seconds, double rms) => Enumerable.Range(0, (int)(seconds * Segmenter.Rate)).Select(_ => (short)((rng.NextDouble() * 2 - 1) * rms * 1.7 * 32768)).ToArray();+ short[] Voice(double seconds, double rms) => Enumerable.Range(0, (int)(seconds * Segmenter.Rate)).Select(i => (short)(Math.Sin(i * 0.05) * Math.Sin(i * 0.0007) * rms * 2 * 32768)).ToArray();+ int Count(Segmenter s) { int n = 0; s.Emitted += _ => n++; s.Feed(Noise(5, 0.0008)); s.Feed(Voice(1.5, 0.004)); s.Feed(Noise(2, 0.0008)); s.Flush(); return n; }+ Equal(0, Count(new Segmenter()), "the computer's line hears nothing");+ Equal(1, Count(new Segmenter(new VoiceGate())), "the room's line hears the sentence");+ }++ public static void ARoomMeetingIsMarked()+ {+ var store = new SessionStore();+ var s = store.Begin(DateTimeOffset.Parse("2026-01-02T02:00:00Z"));+ store.MarkRoom(s.Id);+ Equal(true, store.Get(s.Id)!.Room, "room");+ store.Delete(s.Id);+ Equal(ListenSource.System, ListenSource.Parse("mac"), "an unknown value is the computer's audio");+ Equal(ListenSource.Both, ListenSource.Parse("both"), "both");+ }+public static void RenameLikeTheMac(){var store = new SessionStore();