知了 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): end a meeting by itself when the meeting app hangs up or nobody has spoken for a while
wqugurue491656b39b0
diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1index 00d69d1..6342a1c 100644--- a/windows/scripts/cicadactl.ps1+++ b/windows/scripts/cicadactl.ps1@@ -1,5 +1,6 @@# Sends one debug command to a running dev build (Cicada.exe --dev) and prints its JSON state.# .\cicadactl.ps1 state | start | stop | sample | feed C:\clip.wav | view subtitles | capture on | show records | quit+# 结束会议: calls zoom.exe=Zoom|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeepparam([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "cicada-dev", [System.IO.Pipes.PipeDirection]::InOut)$pipe.Connect(3000)diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.csindex 1f38f57..e48bc3e 100644--- a/windows/src/Cicada.Core/ListenEngine.cs+++ b/windows/src/Cicada.Core/ListenEngine.cs@@ -107,9 +107,10 @@ public sealed class ListenEnginereturn Math.Sqrt(sum / buf.Length) / 32768;}- /// Stops listening, waits (briefly) for segments still at Ming, ends the record and writes the- /// final notes. The task ends when the record is saved; the notes' final pass may run on.- public async Task Stop()+ /// Stops listening, waits (briefly) for segments still at Ming, ends the record (at `endedAt` for+ /// a meeting that ended by itself) and writes the final notes. The task ends when the record is+ /// saved; the notes' final pass may run on.+ public async Task Stop(DateTimeOffset? endedAt = null){if (!Listening) return;Listening = false;@@ -120,7 +121,7 @@ public sealed class ListenEnginelock (gate) waiting = inFlight.ToArray();await Task.WhenAny(Task.WhenAll(waiting), Task.Delay(15_000));var id = SessionId!;- store.End(id);+ store.End(id, endedAt);Log.Debug($"listen: stopped {id}, {lineCount} lines");Changed?.Invoke();_ = notes.Finish();diff --git a/windows/src/Cicada.Core/MeetingEnd.cs b/windows/src/Cicada.Core/MeetingEnd.csnew file mode 100644index 0000000..b6425c8--- /dev/null+++ b/windows/src/Cicada.Core/MeetingEnd.cs@@ -0,0 +1,137 @@+namespace Cicada;++/// When a meeting is over (MeetingEnd.swift), so one nobody ended doesn't run on for hours and pull+/// the next video or meeting into its notes.+///+/// Two signals, as on the Mac. The main one: a meeting app (Zoom, 腾讯会议…) that was reading a+/// microphone during this meeting lets go of it, which is what hanging up looks like from outside; a+/// short grace covers switching devices. The fallback, for meetings in a browser or in the room:+/// nothing was recognised for a while ("nothing recognised" counts words, not sound, so background+/// music doesn't keep a meeting alive). While a meeting app is still in a call, silence doesn't+/// count. Pure: the controller ticks it with the clock and `MicUse.Calls`.+public sealed class MeetingEndWatch+{+ public enum Silence { Prompt, End, Off }++ public sealed record Config(bool FollowApps = true, Silence Silence = Silence.Prompt, double SilenceAfter = 600,+ double Countdown = 60, double AppGrace = 30);++ /// Why the meeting ends: an app hung up (its name), silence, or nobody spoke at all (nothing to+ /// keep, so it just stops, without a countdown).+ public sealed record Reason(string Kind, string Name = "")+ {+ public static readonly Reason SilenceEnd = new("silence");+ public static readonly Reason Nobody = new("nobody");+ public static Reason AppLeft(string name) => new("app", name);+ public override string ToString() => Name.Length > 0 ? $"{Kind}({Name})" : Kind;+ }++ public sealed record Pending(Reason Reason, DateTimeOffset Deadline);++ public Config Settings;+ public Pending? Waiting { get; private set; }+ public DateTimeOffset LastSpeech { get; private set; }+ /// Meeting apps seen in a call during this meeting (id → name).+ public Dictionary<string, string> InCall { get; private set; } = [];++ public MeetingEndWatch(Config config, DateTimeOffset start)+ {+ Settings = config;+ LastSpeech = start;+ }++ /// Words were recognised (theirs or mine): a silence countdown stops. A hang-up doesn't: the+ /// next video would talk over it.+ public void Heard(DateTimeOffset now)+ {+ LastSpeech = now;+ if (Waiting?.Reason.Kind == "silence") Waiting = null;+ }++ /// 继续记录: forget the hang-up and start counting silence again.+ public void KeepGoing(DateTimeOffset now)+ {+ Waiting = null;+ LastSpeech = now;+ InCall = [];+ }++ /// `calls`: meeting apps reading a microphone now. `said`: the meeting has lines. One without+ /// keeps listening for the silence time, then stops quietly. Returns why it ends now, if it does.+ public Reason? Tick(DateTimeOffset now, IReadOnlyDictionary<string, string> calls, bool said)+ {+ var c = Settings;+ bool inACall = c.FollowApps && calls.Count > 0;+ double silent = (now - LastSpeech).TotalSeconds;+ if (!said)+ {+ InCall = c.FollowApps ? new Dictionary<string, string>(calls) : [];+ Waiting = null;+ return c.Silence != Silence.Off && !inACall && silent >= c.SilenceAfter ? Reason.Nobody : null;+ }+ bool appWaiting = Waiting?.Reason.Kind == "app";+ if (c.FollowApps)+ {+ foreach (var (id, name) in calls) InCall[id] = name;+ bool hungUp = InCall.Count > 0 && InCall.Keys.All(k => !calls.ContainsKey(k));+ if (appWaiting && !hungUp) Waiting = null; // rejoined+ if (hungUp && (Waiting is null || Waiting.Reason.Kind == "silence"))+ {+ var name = InCall.OrderBy(p => p.Key, StringComparer.Ordinal).First().Value;+ Waiting = new Pending(Reason.AppLeft(name), now.AddSeconds(c.AppGrace));+ }+ }+ else if (appWaiting) Waiting = null;+ if (Waiting is null && c.Silence != Silence.Off && !inACall && silent >= c.SilenceAfter)+ {+ if (c.Silence == Silence.End) return Reason.SilenceEnd;+ Waiting = new Pending(Reason.SilenceEnd, now.AddSeconds(c.Countdown));+ }+ if ((c.Silence == Silence.Off || inACall) && Waiting?.Reason.Kind == "silence") Waiting = null;+ if (Waiting is { } p && now >= p.Deadline)+ {+ Waiting = null;+ return p.Reason;+ }+ return null;+ }++ public static Silence ParseSilence(string s) => s switch { "end" => Silence.End, "off" => Silence.Off, _ => Silence.Prompt };+}++/// Which meeting apps are reading a microphone, from what Windows records for its privacy settings:+/// under HKCU\…\CapabilityAccessManager\ConsentStore\microphone every app that used the mic has a key+/// (desktop apps under NonPackaged, by their path with `#` for `\`; Store apps by package family)+/// whose LastUsedTimeStop is 0 while it has the mic open. The reading is in the app; this is pure.+public static class MicUse+{+ /// Dedicated meeting apps (lower case program or package family prefix) → the name shown.+ /// Browsers aren't here, as on the Mac: a browser holding a mic isn't necessarily a meeting.+ static readonly (string Key, string Name)[] Apps =+ [+ ("zoom.exe", "Zoom"), ("wemeetapp.exe", "腾讯会议"), ("feishu.exe", "飞书"), ("lark.exe", "Lark"),+ ("dingtalk.exe", "钉钉"), ("teams.exe", "Teams"), ("ms-teams.exe", "Teams"), ("msteams_", "Teams"),+ ("ciscocollabhost.exe", "Webex"), ("webex.exe", "Webex"), ("cisco.webex", "Webex"),+ ];++ /// `entries`: each key's name (a path like "C:#Program Files#Zoom#bin#Zoom.exe" or a package family)+ /// and its LastUsedTimeStop. → {program: name} for the meeting apps using a mic now.+ public static Dictionary<string, string> Calls(IEnumerable<(string Key, long LastUsedTimeStop)> entries)+ {+ var byName = new SortedDictionary<string, string>(StringComparer.Ordinal); // one entry per app+ foreach (var (key, stop) in entries)+ {+ if (stop != 0) continue;+ var program = key.Split('#', '\\').Last().ToLowerInvariant();+ foreach (var (k, name) in Apps)+ {+ if (k.EndsWith('_') ? program.StartsWith(k, StringComparison.Ordinal) : program == k)+ {+ if (!byName.ContainsKey(name)) byName[name] = k.TrimEnd('_');+ break;+ }+ }+ }+ return byName.ToDictionary(p => p.Value, p => p.Key);+ }+}diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.csindex f5a48fa..92766b8 100644--- a/windows/src/Cicada.Core/SessionStore.cs+++ b/windows/src/Cicada.Core/SessionStore.cs@@ -13,6 +13,9 @@ public sealed class SessionStorereadonly HashSet<string> dirty = [];Timer? saveTimer;public event Action<string>? Changed;+ /// The moment recognised words land in a record: a new line (theirs or mine) or a half sentence+ /// that grew. What 结束会议 counts as someone speaking (MeetingEndWatch.Heard).+ public event Action<string>? Words;public SessionStore() { Load(); }@@ -72,13 +75,24 @@ public sealed class SessionStorereturn $"{date} {s.Notes!.Title}";}- public void Append(string id, TranscriptLine line) => Mutate(id, s => s.Lines.Add(line));+ public void Append(string id, TranscriptLine line)+ {+ Mutate(id, s => s.Lines.Add(line));+ Words?.Invoke(id);+ }- public void Replace(string id, TranscriptLine line) => Mutate(id, s =>+ public void Replace(string id, TranscriptLine line){- int i = s.Lines.FindIndex(l => l.Id == line.Id);- if (i >= 0) s.Lines[i] = line;- });+ bool grew = false;+ Mutate(id, s =>+ {+ int i = s.Lines.FindIndex(l => l.Id == line.Id);+ if (i < 0) return;+ grew = line.Src.Length > s.Lines[i].Src.Length; // a half sentence joined, not a retranslation+ s.Lines[i] = line;+ });+ if (grew) Words?.Invoke(id);+ }public void SetNotes(string id, MeetingNotes notes) => Mutate(id, s => s.Notes = notes);@@ -87,14 +101,15 @@ public sealed class SessionStore/// Back to the default title, so the name the notes give the meeting shows again.public void ResetTitle(string id) => Mutate(id, s => { s.Title = DefaultTitle(s.StartedAt); s.Renamed = false; });- /// The meeting ended: kept if anything was said, removed otherwise.- public void End(string id)+ /// The meeting ended (at `endedAt` when it ended by itself a while ago): kept if anything was+ /// said, removed otherwise.+ public void End(string id, DateTimeOffset? endedAt = null){bool empty;lock (gate){if (!sessions.TryGetValue(id, out var s)) return;- s.EndedAt = DateTimeOffset.Now;+ s.EndedAt = endedAt is { } at ? (at > s.StartedAt ? at : s.StartedAt) : DateTimeOffset.Now;empty = s.Lines.Count == 0;}if (empty) Delete(id);diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex 3f39a17..a3fb631 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -32,6 +32,11 @@ public sealed class AppSettings[JsonPropertyName("speakVoices")] public Dictionary<string, string> SpeakVoices { get; set; } = [];/// The one-time "知了还在听" notice after the panel is first collapsed while listening.[JsonPropertyName("toldStillListening")] public bool ToldStillListening { get; set; }+ /// 结束会议 (MeetingEnd.cs), the Mac's keys: end when the meeting app hangs up; when nobody+ /// speaks, "prompt" (count down, then end), "end" or "off", after silenceMinutes.+ [JsonPropertyName("endWithApp")] public bool EndWithApp { get; set; } = true;+ [JsonPropertyName("silenceEnd")] public string SilenceEnd { get; set; } = "prompt";+ [JsonPropertyName("silenceMinutes")] public double SilenceMinutes { get; set; } = 10;[JsonIgnore] public string TargetCode => Target == "system" ? Languages.FromSystem(CultureInfo.CurrentUICulture.Name) : Target;[JsonIgnore] public string NotesCode => NotesLanguage == "system" ? TargetCode : NotesLanguage;diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 639b71e..b87b786 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -60,6 +60,15 @@ sealed class ControllerMainWindow? mainWindow;SettingsWindow? settingsWindow;Dispatcher Dispatch => application.Dispatcher;+ // 结束会议 (MeetingEnd.cs): `Ending` while a meeting is about to end by itself, `AutoEnded` after+ // one did (the tray says so, and the next call starts a new meeting).+ MeetingEndWatch? endWatch;+ public MeetingEndWatch.Pending? Ending { get; private set; }+ public bool AutoEnded { get; private set; }+ /// Dev: meeting apps pretending to be in a call, and (silence, countdown, grace) in seconds.+ public Dictionary<string, string>? FakeCalls;+ public (double Silence, double Countdown, double Grace)? EndTimes;+ bool readingCalls;public Controller(Application application){@@ -77,6 +86,7 @@ sealed class ControllerListen.Changed += Changed;Notes.Changed += Changed;Store.Changed += _ => Changed();+ Store.Words += id => Dispatch.BeginInvoke(() => HeardWords(id));}public void Launch()@@ -96,6 +106,9 @@ sealed class Controllertalk.Released += () => Dispatch.BeginInvoke(PressEnded);Log.Debug($"audio: speakers {Endpoints.Default(Endpoints.Flow.Render)?.Name ?? "none"}, mic {Endpoints.Microphone()?.Name ?? "none"}, cable {(Endpoints.Cable() is null ? "absent" : "present")}");DebugServer.Start(this);+ var watch = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };+ watch.Tick += (_, _) => _ = WatchEnd();+ watch.Start();if (!Settings.Onboarded) new Onboarding(this).Show();else if (Ling.HasKey) _ = Ling.Check();}@@ -223,18 +236,107 @@ sealed class ControllerLog.Debug($"listen: source ended {reason}");Dispatch.BeginInvoke(() => _ = StopListening());};+ AutoEnded = false;+ Ending = null;+ endWatch = new MeetingEndWatch(EndConfig(), DateTimeOffset.Now);Listen.Start(source);ShowNotes();}- public async Task StopListening()+ public async Task StopListening(DateTimeOffset? endedAt = null, bool auto = false){var id = Listen.SessionId;- await Listen.Stop();+ endWatch = null;+ Ending = null;+ AutoEnded = auto;+ await Listen.Stop(endedAt);Changed();if (id is not null) _ = TellWhenNotesReady(id);}+ // MARK: 结束会议++ MeetingEndWatch.Config EndConfig()+ {+ var c = new MeetingEndWatch.Config(Settings.EndWithApp, MeetingEndWatch.ParseSilence(Settings.SilenceEnd), Settings.SilenceMinutes * 60);+ return EndTimes is { } t ? c with { SilenceAfter = t.Silence, Countdown = t.Countdown, AppGrace = t.Grace } : c;+ }++ /// Words recognised in the live meeting (theirs or mine): the silence countdown stops now.+ void HeardWords(string id)+ {+ if (endWatch is null || !Listen.Listening || id != Listen.SessionId) return;+ endWatch.Heard(DateTimeOffset.Now);+ SetEnding(endWatch.Waiting);+ }++ /// Every 2 s: while listening, whether the meeting is over; after one ended by itself, whether a+ /// meeting app started the next call. The registry is read off the UI thread.+ async Task WatchEnd()+ {+ bool live = Listen.Listening && endWatch is not null, after = !Listen.Listening && AutoEnded;+ if (readingCalls || !(live || after) || (!live && !Settings.EndWithApp)) return;+ readingCalls = true;+ Dictionary<string, string> calls = !Settings.EndWithApp ? new() : FakeCalls ?? await Task.Run(MicReaders.Calls);+ readingCalls = false;+ var now = DateTimeOffset.Now;+ if (Listen.Listening && endWatch is { } w)+ {+ w.Settings = EndConfig();+ var said = Listen.SessionId is { } id && Store.Get(id) is { Lines.Count: > 0 };+ var reason = w.Tick(now, calls, said);+ SetEnding(w.Waiting);+ if (reason is not null) await AutoEnd(reason, w);+ }+ else 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());+ }+ }++ void SetEnding(MeetingEndWatch.Pending? p)+ {+ if (p == Ending) return;+ if (p is not null) Log.Debug($"meeting end: pending {p.Reason}, ends in {(int)(p.Deadline - DateTimeOffset.Now).TotalSeconds} s");+ else if (Ending is not null) Log.Debug("meeting end: pending cleared");+ Ending = p;+ Changed();+ }++ /// Ends where the meeting really ended: a little after the last words, or at the hang-up if that+ /// was later.+ async Task AutoEnd(MeetingEndWatch.Reason reason, MeetingEndWatch w)+ {+ if (reason.Kind == "nobody")+ {+ // Nothing to keep or summarise: back to 开始听, not 会议已自动结束.+ Log.Debug($"meeting end: nobody spoke for {(int)w.Settings.SilenceAfter} s, stopped");+ await StopListening();+ return;+ }+ var now = DateTimeOffset.Now;+ var at = w.LastSpeech.AddSeconds(5);+ if (reason.Kind == "app" && now.AddSeconds(-w.Settings.AppGrace) > at) at = now.AddSeconds(-w.Settings.AppGrace);+ if (at > now) at = now;+ Log.Debug($"meeting end: ended by itself ({reason}), end time {(int)(now - at).TotalSeconds} s ago");+ await StopListening(at, auto: true);+ }++ /// 继续记录 on the ending prompt.+ public void KeepRecording()+ {+ endWatch?.KeepGoing(DateTimeOffset.Now);+ SetEnding(null);+ Log.Debug("meeting end: kept going");+ }++ public string EndingTitle(MeetingEndWatch.Pending p) => p.Reason.Kind == "app"+ ? LF("%@ 已挂断", p.Reason.Name)+ : LF("已经 %lld 分钟没人说话", Math.Max(1, (int)Math.Round(EndConfig().SilenceAfter / 60)));++ public static int EndingLeft(MeetingEndWatch.Pending p) => Math.Max(0, (int)Math.Round((p.Deadline - DateTimeOffset.Now).TotalSeconds));+/// The final notes take a few seconds after 结束; say so once they're written.async Task TellWhenNotesReady(string id){@@ -420,6 +522,9 @@ sealed class Controller["voice"] = Speak.LastVoice,["cable"] = Endpoints.Cable() is not null,["autostart"] = AutoStart.Enabled,+ ["ending"] = Ending is { } p ? $"{EndingTitle(p)} · {EndingLeft(p)}" : null,+ ["autoEnded"] = AutoEnded,+ ["inCall"] = endWatch is { } w ? string.Join(",", w.InCall.Values) : null,};}@@ -427,6 +532,7 @@ sealed class Controller/// 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/// show notes|records|settings | quit+/// calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeepstatic class DebugServer{static string Pipe => Paths.Dev ? "cicada-dev" : "cicada";@@ -487,6 +593,14 @@ static class DebugServercase "fakemic": app.SetFakeMic(arg == "off" ? null : arg); break;case "record": _ = app.RecordCable(arg); break;case "preview": _ = app.Preview(arg.Length > 0 ? arg : app.Speak.Target); break;+ case "calls":+ app.FakeCalls = arg switch { "real" => null, "" or "none" => [], _ => arg.Split(',').Select(p => p.Split('=', 2)).ToDictionary(p => p[0], p => p[^1]) };+ break;+ case "realcalls": return new JsonObject { ["calls"] = string.Join(",", MicReaders.Calls().Select(p => $"{p.Key}={p.Value}")) };+ case "endtimes":+ app.EndTimes = arg is "" or "off" ? null : arg.Split(' ') is [var a, var b, var c] ? (double.Parse(a), double.Parse(b), double.Parse(c)) : null;+ break;+ case "endkeep": app.KeepRecording(); break;case "quit": _ = app.Quit(); break;case "state": break;default: return new JsonObject { ["error"] = $"unknown command {parts[0]}" };diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.csindex 7f11067..5d6cb47 100644--- a/windows/src/Cicada/NotesWindow.cs+++ b/windows/src/Cicada/NotesWindow.cs@@ -110,6 +110,31 @@ sealed class NotesWindow : Windowvar session = app.Listen.SessionId is { } id ? app.Store.Get(id) : null;clockText.Text = app.Listen.Listening && session is not null ? Languages.Clock((DateTimeOffset.Now - session.StartedAt).TotalSeconds) : "";dueText.Text = Due() ?? "";+ if (app.Ending is { } p)+ {+ endingDetail.Text = LF("%lld 秒后结束会议并整理纪要", Controller.EndingLeft(p));+ endingNotice.Text = $"{app.EndingTitle(p)} · {LF("%lld 秒后结束", Controller.EndingLeft(p))}";+ }+ }++ ContentControl ending = new();+ string? endingKey;+ readonly TextBlock endingDetail = Ui.Text("", 12, Palette.Secondary);+ readonly TextBlock endingNotice = Ui.Text("", 13, Brushes.White, FontWeights.SemiBold, wrap: false);++ /// 已经 10 分钟没人说话 · 60 秒后结束 (MeetingEndingStrip): what will happen, and 继续记录 / 现在结束.+ /// The window never takes focus, so a click lands on the buttons at once.+ FrameworkElement EndingStrip()+ {+ if (!app.Listen.Listening || app.Ending is not { } p) return new Border();+ Detach(endingDetail);+ var buttons = Ui.Row(8, Ui.Button(L("继续记录"), app.KeepRecording, Ui.Kind.Primary, height: 32),+ Ui.Button(L("现在结束"), () => _ = app.StopListening(), height: 32));+ var stack = Ui.Stack(3, Ui.Text(app.EndingTitle(p), 14, Palette.Ink, FontWeights.Bold), endingDetail);+ buttons.Margin = new Thickness(0, 10, 0, 0);+ stack.Children.Add(buttons);+ Tick();+ return new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(12), Padding = new Thickness(14), Margin = new Thickness(12, 0, 12, 8), Child = stack };}static void Detach(FrameworkElement e) { if (e.Parent is Panel p) p.Children.Remove(e); }@@ -120,7 +145,7 @@ sealed class NotesWindow : Windowif (builtFor != mode){builtFor = mode; headerKey = tabsKey = barsKey = null;- header = new ContentControl(); bars = new ContentControl(); live = new ContentControl(); tabs = new ContentControl(); footer = new ContentControl();+ header = new ContentControl(); bars = new ContentControl(); ending = new ContentControl(); endingKey = null; live = new ContentControl(); tabs = new ContentControl(); footer = new ContentControl();scroll = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Padding = new Thickness(16, 14, 12, 16) };Content = Subtitles ? SubtitleFrame() : PanelFrame();}@@ -128,6 +153,8 @@ sealed class NotesWindow : Windowif (key != headerKey) { headerKey = key; header.Content = Header(); }Tick();if (Subtitles) { live.Content = SubtitleLine(); return; }+ var ek = app.Listen.Listening && app.Ending is { } p ? p.Reason.ToString() : null;+ if (ek != endingKey) { endingKey = ek; ending.Content = EndingStrip(); }var bk = $"{app.Listen.Problem}|{app.Settings.ShowInCapture}|{hiddenFromCapture}";if (bk != barsKey) { barsKey = bk; bars.Content = Bars(); }live.Content = LiveCard();@@ -148,6 +175,7 @@ sealed class NotesWindow : Windowvar dock = new DockPanel();void Top(UIElement e) { DockPanel.SetDock(e, Dock.Top); dock.Children.Add(e); }Top(header);+ Top(ending);Top(bars);Top(live);tabs.Margin = new Thickness(12, 10, 12, 0);@@ -414,6 +442,15 @@ sealed class NotesWindow : Windowleft.Children.Add(clockText);}var text = new StackPanel { VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 12, 0) };+ // The subtitle bar has no room for buttons: it says what will happen (the Mac's notice).+ if (listen.Listening && app.Ending is not null)+ {+ Detach(endingNotice);+ endingNotice.Foreground = new SolidColorBrush(Color.FromRgb(0xF4, 0xA5, 0x8C));+ endingNotice.Margin = new Thickness(0, 0, 0, 4);+ text.Children.Add(endingNotice);+ Tick();+ }if (line is null)text.Children.Add(Ui.Text(listen.Listening ? L("等有人说话") : L("点“开始听”,电脑里播放的声音会变成双语字幕和纪要"), 15, Palette.NightText));elsediff --git a/windows/src/Cicada/Platform.cs b/windows/src/Cicada/Platform.csindex e53e822..4247e6d 100644--- a/windows/src/Cicada/Platform.cs+++ b/windows/src/Cicada/Platform.cs@@ -117,3 +117,34 @@ static class AudioDevice[DllImport("ole32.dll")] static extern int PropVariantClear(ref PropVariant value);}++/// The meeting apps reading a microphone now (MicUse in Cicada.Core reads the entries): what+/// Windows keeps for Settings › 隐私和安全性 › 麦克风, whose LastUsedTimeStop is 0 while an app has+/// the mic open. Both desktop apps (NonPackaged) and Store apps (the new Teams).+static class MicReaders+{+ const string Root = @"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\microphone";++ public static Dictionary<string, string> Calls()+ {+ var entries = new List<(string, long)>();+ try+ {+ using var root = Registry.CurrentUser.OpenSubKey(Root);+ if (root is null) return [];+ void Read(RegistryKey parent)+ {+ foreach (var name in parent.GetSubKeyNames())+ {+ if (name == "NonPackaged") continue;+ using var k = parent.OpenSubKey(name);+ if (k?.GetValue("LastUsedTimeStop") is long stop) entries.Add((name, stop));+ }+ }+ Read(root);+ using (var desktop = root.OpenSubKey("NonPackaged")) if (desktop is not null) Read(desktop);+ }+ catch (Exception e) { Log.Debug($"mic users: unreadable ({e.GetType().Name})"); }+ return MicUse.Calls(entries);+ }+}diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex ac2c373..1840a41 100644--- a/windows/src/Cicada/SettingsWindow.cs+++ b/windows/src/Cicada/SettingsWindow.cs@@ -61,6 +61,7 @@ sealed class SettingsWindow : WindowCard(null, L("字幕文字大小"), null, size),Card(Icons.Keyboard, L("开始或结束"), app.HotkeyRegistered ? L("在任何程序里都能按") : L("这个快捷键被别的程序占用了"), Keys(Hotkey.Label))));Section(page, "speak", L("同声传译"), SpeakCards());+ Section(page, "end", L("结束会议"), EndCards());Section(page, "privacy", L("隐私与启动"), Group(Card(Icons.Eye, L("共享屏幕时让对方看到"), L("关着时,截图和屏幕共享里看不到纪要和字幕"), Ui.Switch(app.Settings.ShowInCapture, app.SetShowInCapture, L("共享屏幕时让对方看到"))),Card(Icons.List, L("说话人识别"), L("按声音标出说话人 1、2…,只在这台电脑上处理"), Ui.Switch(app.Settings.SpeakerVoices, v => { app.Settings.SpeakerVoices = v; Save(); }, L("说话人识别"))),@@ -79,7 +80,7 @@ sealed class SettingsWindow : Window(string id, string icon, string label)[] items =[("ling", Icons.Key, L("Ling")), ("lang", Icons.Globe, L("语言")), ("listen", Icons.Wave, L("听的时候")),- ("speak", Icons.Mic, L("同声传译")), ("privacy", Icons.Shield, L("隐私与启动")), ("about", Icons.Info, L("关于")),+ ("speak", Icons.Mic, L("同声传译")), ("end", Icons.Stop, L("结束会议")), ("privacy", Icons.Shield, L("隐私与启动")), ("about", Icons.Info, L("关于")),];foreach (var (id, icon, label) in items){@@ -159,6 +160,22 @@ sealed class SettingsWindow : Windowstring? cableProgress;/// 同声传译: the switch, the virtual mic, the two languages and the room's voice.+ /// 结束会议: when a meeting ends by itself (MeetingEnd.cs), as the Mac's settings say it.+ FrameworkElement EndCards()+ {+ var s = app.Settings;+ var cards = new List<FrameworkElement>+ {+ Card(Icons.Stop, L("会议应用挂断后结束"), L("Zoom、腾讯会议、飞书、Teams 等"), Ui.Switch(s.EndWithApp, v => { s.EndWithApp = v; Save(); }, L("会议应用挂断后结束"))),+ Card(null, L("没人说话时"), L("按识别出的话算,背景音乐不算"),+ Ui.Segmented([("prompt", L("提醒后结束")), ("end", L("直接结束")), ("off", L("一直记录"))], s.SilenceEnd, v => { s.SilenceEnd = v; Save(); Render(); })),+ };+ if (s.SilenceEnd != "off")+ cards.Add(Card(null, L("多久算没人说话"), null,+ Ui.Segmented(new[] { 5, 10, 15, 30 }.Select(m => (m.ToString(), LF("%lld 分钟", m))), ((int)s.SilenceMinutes).ToString(), v => { s.SilenceMinutes = double.Parse(v); Save(); })));+ return Group(cards.ToArray());+ }+FrameworkElement SpeakCards(){var s = app.Settings;diff --git a/windows/src/Cicada/TrayFlyout.cs b/windows/src/Cicada/TrayFlyout.csindex a9f7767..fabb71c 100644--- a/windows/src/Cicada/TrayFlyout.cs+++ b/windows/src/Cicada/TrayFlyout.cs@@ -59,6 +59,8 @@ sealed class TrayFlyout : Window// Who and how it isvar status = listen.Listening && listen.SessionId is { } sid && app.Store.Get(sid) is { } live? Ui.Row(6, Ui.LiveDot(6), Ui.Text($"{L("正在听")} {Languages.Clock((DateTimeOffset.Now - live.StartedAt).TotalSeconds)}", 12, Palette.Secondary, wrap: false))+ : app.AutoEnded+ ? Ui.Row(6, Ui.Dot(Palette.Tertiary, 6), Ui.Text(L("会议已自动结束"), 12, Palette.Secondary, wrap: false)): app.Ling.HasKey? Ui.Row(6, Ui.Dot(Palette.Success, 6), Ui.Text(L("就绪 · Ling 已连接"), 12, Palette.Secondary, wrap: false)): Ui.Row(6, Ui.Dot(Palette.Tertiary, 6), Ui.Text(L("还没接上 Ling"), 12, Palette.Secondary, wrap: false));@@ -69,6 +71,17 @@ sealed class TrayFlyout : Window// The one thing to dovar main = new StackPanel { Margin = new Thickness(16, 4, 16, 16) };+ if (listen.Listening && app.Ending is { } p)+ {+ // About to end by itself (MeetingEndingStrip, compact): the panel takes no focus either.+ var strip = Ui.Stack(3, Ui.Text(app.EndingTitle(p), 13, Palette.Ink, FontWeights.Bold),+ Ui.Text(LF("%lld 秒后结束会议并整理纪要", Controller.EndingLeft(p)), 12, Palette.Secondary));+ var keep = Ui.Row(8, Ui.Button(L("继续记录"), app.KeepRecording, Ui.Kind.Primary, height: 32),+ Ui.Button(L("现在结束"), () => { Hide(); _ = app.StopListening(); }, height: 32));+ keep.Margin = new Thickness(0, 8, 0, 0);+ strip.Children.Add(keep);+ main.Children.Add(new Border { Background = Palette.AccentPale, CornerRadius = new CornerRadius(10), Padding = new Thickness(12), Margin = new Thickness(0, 0, 0, 10), Child = strip });+ }if (listen.Listening){var grid = new Grid();diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex 59c112b..b40a540 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -35,6 +35,138 @@ static class Testsif (!EqualityComparer<T>.Default.Equals(expected, actual)) throw new Exception($"{what}: expected «{expected}», got «{actual}»");}+ // MARK: 结束会议 (the Mac's MeetingEndTests, case for case)++ static readonly DateTimeOffset T0 = DateTimeOffset.FromUnixTimeSeconds(1_000_000);+ static readonly Dictionary<string, string> Zoom = new() { ["zoom.exe"] = "Zoom" };+ static readonly Dictionary<string, string> NoCalls = [];+ static MeetingEndWatch Watch(MeetingEndWatch.Silence silence = MeetingEndWatch.Silence.Prompt, bool followApps = true) =>+ new(new MeetingEndWatch.Config(FollowApps: followApps, Silence: silence), T0);+ static DateTimeOffset At(double s) => T0.AddSeconds(s);++ public static void HangUpEndsAfterTheGrace()+ {+ var w = Watch();+ Equal(null, w.Tick(At(10), Zoom, true), "in a call");+ Equal(null, w.Tick(At(20), NoCalls, true), "hung up");+ Equal(new MeetingEndWatch.Pending(MeetingEndWatch.Reason.AppLeft("Zoom"), At(50)), w.Waiting, "the grace");+ Equal(null, w.Tick(At(49), NoCalls, true), "still in the grace");+ Equal(MeetingEndWatch.Reason.AppLeft("Zoom"), w.Tick(At(50), NoCalls, true), "ends");+ }++ public static void RejoiningWithinTheGraceKeepsGoing()+ {+ var w = Watch();+ w.Tick(At(10), Zoom, true); w.Tick(At(20), NoCalls, true);+ Equal(null, w.Tick(At(30), Zoom, true), "rejoined");+ Equal(null, w.Waiting, "nothing pending");+ }++ public static void SpeechDoesNotCancelAHangUp()+ {+ var w = Watch();+ w.Tick(At(10), Zoom, true); w.Tick(At(20), NoCalls, true);+ w.Heard(At(25));+ Equal(MeetingEndWatch.Reason.AppLeft("Zoom"), w.Tick(At(50), NoCalls, true), "the next video would talk over it");+ }++ public static void KeepGoingForgetsTheHangUp()+ {+ var w = Watch();+ w.Tick(At(10), Zoom, true); w.Tick(At(20), NoCalls, true);+ w.KeepGoing(At(30));+ Equal(null, w.Tick(At(100), NoCalls, true), "kept going");+ Equal(null, w.Waiting, "nothing pending");+ }++ public static void SilencePromptsThenEnds()+ {+ var w = Watch();+ w.Heard(At(5));+ Equal(null, w.Tick(At(604), NoCalls, true), "not yet");+ Equal(null, w.Waiting, "no prompt yet");+ Equal(null, w.Tick(At(605), NoCalls, true), "the prompt");+ Equal(new MeetingEndWatch.Pending(MeetingEndWatch.Reason.SilenceEnd, At(665)), w.Waiting, "a countdown");+ Equal(MeetingEndWatch.Reason.SilenceEnd, w.Tick(At(665), NoCalls, true), "ends");+ }++ public static void WordsCancelTheSilencePrompt()+ {+ var w = Watch();+ w.Tick(At(600), NoCalls, true);+ Equal("silence", w.Waiting?.Reason.Kind, "prompted");+ w.Heard(At(620));+ Equal(null, w.Waiting, "words cancel it");+ Equal(null, w.Tick(At(700), NoCalls, true), "and it starts over");+ }++ public static void SilenceEndModeEndsAtOnceAndOffNever()+ {+ Equal(MeetingEndWatch.Reason.SilenceEnd, Watch(MeetingEndWatch.Silence.End).Tick(At(600), NoCalls, true), "end");+ var off = Watch(MeetingEndWatch.Silence.Off);+ Equal(null, off.Tick(At(99_999), NoCalls, true), "off");+ Equal(null, off.Waiting, "off: nothing pending");+ }++ public static void SilenceDoesNotCountDuringACall()+ {+ var w = Watch();+ Equal(null, w.Tick(At(5_000), Zoom, true), "a muted call");+ Equal(null, w.Waiting, "no prompt in a call");+ var plain = Watch(followApps: false);+ Equal(null, plain.Tick(At(600), Zoom, true), "not following apps");+ Equal("silence", plain.Waiting?.Reason.Kind, "then a call says nothing");+ }++ public static void NothingSaidStopsQuietlyAfterTheSilence()+ {+ var w = Watch();+ Equal(null, w.Tick(At(599), NoCalls, false), "not yet");+ Equal(MeetingEndWatch.Reason.Nobody, w.Tick(At(600), NoCalls, false), "stops");+ Equal(null, w.Waiting, "no countdown");+ Equal(MeetingEndWatch.Reason.Nobody, Watch(MeetingEndWatch.Silence.End).Tick(At(600), NoCalls, false), "end mode too");+ Equal(null, Watch(MeetingEndWatch.Silence.Off).Tick(At(5_000), NoCalls, false), "off keeps listening");+ Equal(null, Watch().Tick(At(5_000), Zoom, false), "a muted webinar keeps listening");+ }++ public static void NothingSaidKeepsListening()+ {+ var w = Watch();+ w.Tick(At(10), Zoom, false);+ Equal(null, w.Tick(At(500), NoCalls, false), "a call that ended before anyone spoke");+ Equal(null, w.Waiting, "nothing pending");+ w.Heard(At(5_001));+ Equal(null, w.Tick(At(5_002), NoCalls, true), "is forgotten once someone does");+ Equal(null, w.Waiting, "still nothing pending");+ }++ public static void MicUseCountsOnlyMeetingAppsWithTheMicOpen()+ {+ var calls = MicUse.Calls([+ ("C:#Program Files#Zoom#bin#Zoom.exe", 0), ("C:#Users#me#AppData#Roaming#Zoom#bin#Zoom.exe", 0),+ ("C:#Program Files (x86)#Tencent#WeMeet#wemeetapp.exe", 133_000_000_000), // used earlier, closed now+ ("C:#Program Files#Google#Chrome#Application#chrome.exe", 0), // a browser isn't a meeting app+ ("MSTeams_8wekyb3d8bbwe", 0),+ ]);+ Equal("Teams=msteams,Zoom=zoom.exe", string.Join(",", calls.OrderBy(p => p.Value).Select(p => $"{p.Value}={p.Key}")), "meeting apps reading a mic");+ Equal(0, MicUse.Calls([]).Count, "none");+ }++ public static void WordsFireOnNewAndGrownLinesOnly()+ {+ var store = new SessionStore();+ var id = store.Begin().Id;+ int heard = 0;+ store.Words += w => { if (w == id) heard++; };+ store.Append(id, new TranscriptLine { Id = "h1-1", Src = "so we will", Dst = "所以我们会", SrcLang = "en", DstLang = "zh-CN" });+ store.Append(id, new TranscriptLine { Id = "m1", Speaker = "me", Src = "好的", Dst = "OK", SrcLang = "zh-CN", DstLang = "en" });+ store.Replace(id, new TranscriptLine { Id = "h1-1", Src = "so we will", Dst = "所以我们将", SrcLang = "en", DstLang = "zh-CN" });+ Equal(2, heard, "a retranslation isn't speech");+ store.Replace(id, new TranscriptLine { Id = "h1-1", Src = "so we will ship", Dst = "所以我们会发布", SrcLang = "en", DstLang = "zh-CN" });+ Equal(3, heard, "a half sentence that grew is");+ store.Delete(id);+ }+// MARK: Recordspublic static void SessionJsonMatchesTheMac()