知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix(windows): the talk key now sends what you say while the other side talks on the speakers
wquguru6ca73c83e967
diff --git a/site/changelog.json b/site/changelog.jsonindex 594a11b..a72177a 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -61,6 +61,14 @@],"title": "Linux 上对方正在说话时,同声传译也能把你的话说出去。","text": "以前不戴耳机时,对方说话期间你说的那句会整句丢掉,怕把扬声器里对方的声音当成你的。现在打开同声传译时,知了用系统的回声消除听你的麦克风,对方的声音被去掉,你的话照常翻译、说出去。系统不支持回声消除时还是原来的做法。"+ },+ {+ "kind": "fixed",+ "platforms": [+ "windows"+ ],+ "title": "对方从扬声器说话时按住说话,说的话照样翻译发出去。",+ "text": "以前电脑在放会议声音时按住说话,会因为怕把对方的声音当成你说的,提示“对方在说话时说的,没有说出去”。现在按住说话时麦克风经过 Windows 的回声消除,对方的声音被去掉,你说的照常发出去。需要 Windows 11 和带回声消除的麦克风;没有的电脑还是和以前一样。"}]},diff --git a/windows/README.md b/windows/README.mdindex 43785aa..560698c 100644--- a/windows/README.md+++ b/windows/README.md@@ -75,3 +75,5 @@ vm/vmctl.sh g shot C:\x.png # Windows 里截图(屏幕共享看到的,不## 同声传译怎么测VM 里没有麦克风:`cicadactl fakemic <wav>` 让按住说话键时用这个文件代替麦克风(`talkkey <名字>` 换键,`talkkey choose` 等同点“更改”),`speak <wav>` 直接说一句。`record <秒> <wav>` 录下 CABLE Output(会议软件会听到的声音),拷回 Mac 用 `cicada-cli hear` 核对语言和内容。`spike/clips/me-zh.wav`、`me-en.wav` 是“我说的话”,`silence.wav` 用来测什么都不发。++按住说话键时麦克风用通话类别打开(`EchoMic`),走这台电脑的回声消除:日志 `speak: mic with echo cancellation` 时电脑放着会议声音也照发,`speak: mic plain` 时(Windows 10、驱动没有回声消除)对方说话期间按的照旧不发。`talkmic CABLE Output` 让按住说话键读这个输入(VM 只有它),和 `fakemic` 一起用时仍发文件里的话,但真的走一遍这条采集;虚拟线没有回声消除,所以 VM 里只能看到 plain 这条路。真正的回声消除要真机加扬声器测。diff --git a/windows/src/Cicada.Core/Speak.cs b/windows/src/Cicada.Core/Speak.csindex 6ac23e2..c7002be 100644--- a/windows/src/Cicada.Core/Speak.cs+++ b/windows/src/Cicada.Core/Speak.cs@@ -1,3 +1,4 @@+using System.Globalization;using System.Security.Cryptography;namespace Cicada;@@ -133,6 +134,11 @@ public sealed class SpeakEngine/// Share of the press the computer may play through before it counts as echo (Linux's 0.5).public const double EchoShare = 0.5;+ /// Whether a press is dropped as the meeting's echo: only on the plain mic (SpeakEngine.swift's+ /// `pressPlain`). Through echo cancellation the meeting's voices are taken out of the mic, and+ /// what is left is me: dropping those presses lost everything said while the other side talked.+ public static bool EchoDrop(bool echoCancelled, double playedShare) => !echoCancelled && playedShare > EchoShare;+public void BeginRecording(){pressedAt = DateTimeOffset.Now;@@ -147,14 +153,17 @@ public sealed class SpeakEngine}/// One utterance: `wav` is 16 kHz mono. Returns what the room heard, or null if nothing was sent.- public async Task<string?> Speak(byte[] wav, ISpeechSink sink)+ /// `echoCancelled`: the press was heard through Windows' echo cancellation (`EchoCancel`).+ public async Task<string?> Speak(byte[] wav, ISpeechSink sink, bool echoCancelled = false){await one.WaitAsync();try{var released = DateTime.UtcNow;// A press nobody spoke in: Ming hears 嗯 in the room's hush and the meeting would hear "Hmm."- if (!PressSpeech.Spoken(wav))+ var measure = PressSpeech.Measure(wav);+ Log.Debug($"speak: press of {Math.Max(0, wav.Length - 44) / 32000.0:F1} s, {measure.Summary}");+ if (!measure.Spoken){Log.Debug("speak: nothing said in the press, nothing sent");State = Phase.Idle; pressedAt = null;@@ -163,10 +172,15 @@ public sealed class SpeakEngine}// The meeting playing through most of the press: what the mic heard is its echo as much// as me, and Ming would send the other side's words back to them (measured on the Mac).- if (Echo is { } echo && echo.Fraction(pressedMono ?? echo.Now - wav.Length / 32000.0, echo.Now) > EchoShare)+ if (Echo is { } echo){- Log.Debug("speak: the computer was playing through the press (echo), nothing sent");- return Fail(Strings.L("对方在说话时说的,没有说出去"));+ var share = echo.Fraction(pressedMono ?? echo.Now - wav.Length / 32000.0, echo.Now);+ if (EchoDrop(echoCancelled, share))+ {+ Log.Debug($"speak: the computer played through {share * 100:F0}% of the press on the plain mic (echo), nothing sent");+ return Fail(Strings.L("对方在说话时说的,没有说出去"));+ }+ if (share > EchoShare) Log.Debug($"speak: the computer played through {share * 100:F0}% of the press, heard with echo cancellation: sending");}var to = Target;State = Phase.Translating; Said = Heard = Problem = null;@@ -301,12 +315,24 @@ public static class PressSpeechconst int Frame = 480;const double Needed = 0.3;+ /// What the check saw (PressSpeech.Measure on the Mac): seconds over the line, the press's quiet+ /// and the line (RMS, 0–1). Logged per press: echo left after cancellation raises the quiet,+ /// and a line held at its −36 dBFS cap is how a soft voice over the meeting gets dropped.+ public readonly record struct Result(double Voiced, double Floor, double Line)+ {+ public bool Spoken => Voiced >= Needed;+ public string Summary => $"voiced {Voiced.ToString("F2", CultureInfo.InvariantCulture)} s, quiet {Db(Floor)} dBFS, line {Db(Line)} dBFS";+ static string Db(double v) => v > 0 ? (20 * Math.Log10(v)).ToString("F0", CultureInfo.InvariantCulture) : "-inf";+ }+/// `wav`: 16 kHz mono 16-bit, with or without its 44-byte header.- public static bool Spoken(byte[] wav)+ public static bool Spoken(byte[] wav) => Measure(wav).Spoken;++ public static Result Measure(byte[] wav){var start = wav.Length >= 44 && wav[0] == 'R' && wav[1] == 'I' ? 44 : 0;var n = (wav.Length - start) / 2;- if (n < Frame) return false;+ if (n < Frame) return new(0, 0, 0);var levels = new List<double>();for (var i = 0; i + Frame <= n; i += Frame){@@ -316,7 +342,7 @@ public static class PressSpeech}var floor = levels.Order().ElementAt(levels.Count / 10);var line = Math.Min(0.016, Math.Max(0.0063, floor * 3));- return levels.Count(l => l >= line) * Frame / 16000.0 >= Needed;+ return new(levels.Count(l => l >= line) * Frame / 16000.0, floor, line);}static readonly HashSet<string> Fillers = ["嗯", "啊", "呃", "哦", "唔", "额", "噢", "哎", "um", "uh", "hmm", "hm", "mm", "mhm", "ah", "oh", "er", "えー", "あの", "음", "어"];@@ -357,3 +383,22 @@ public sealed class LoudnessLog(Func<double>? clock = null)}}}++/// Whether Windows' echo cancellation works on the talk key's mic. A capture stream opened in the+/// communications category gets the endpoint's AEC when its driver (or Windows 11's Voice Clarity)+/// has one, and from build 22000 the stream lists its effects. Only an AEC listed as on counts: not+/// knowing (Windows 10, a driver that lists nothing) is the plain mic, because sending the meeting's+/// own words back to it is the worse mistake.+public static class EchoCancel+{+ /// AUDIO_EFFECT_TYPE_ACOUSTIC_ECHO_CANCELLATION (ksmedia.h).+ public static readonly Guid Effect = new("6f64adbe-8211-11e2-8c70-2c27d7f001fa");++ public readonly record struct AudioEffect(Guid Id, bool CanSetState, bool On);++ /// `effects`: the stream's list, null when Windows has none to give.+ public static bool InEffect(IReadOnlyList<AudioEffect>? effects) => effects?.Any(e => e.Id == Effect && e.On) ?? false;++ /// Listed but off, and the app may turn it on: worth asking for before the press starts.+ public static bool CanTurnOn(IReadOnlyList<AudioEffect>? effects) => effects?.Any(e => e.Id == Effect && !e.On && e.CanSetState) ?? false;+}diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 8284fb8..452b2e1 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -78,9 +78,14 @@ sealed class Controllerpublic static string? Arrived;PushToTalk? talk;SpeakBar? speakBar;+ /// The press's microphone: through echo cancellation, or the plain one when that won't open.+ EchoMic? echoMic;+ bool echoLogged;DeviceRecorder? mic;/// Dev builds: a WAV that stands in for the microphone (the VM has none).string? fakeMic;+ /// Dev builds: the input the talk key reads instead of the microphone (`talkmic CABLE Output`).+ string? talkMic;readonly Forms.NotifyIcon tray = new();System.Drawing.Icon? idleIcon, liveIcon, updateIcon;/// Something only the user can fix (AICheck.Blocking), said beyond the panel: the tray's orange@@ -773,6 +778,7 @@ sealed class Controller? new Rect(notesWindow!.Left, notesWindow.Top, notesWindow.ActualWidth, notesWindow.ActualHeight) : null;public void SetFakeMic(string? path) { fakeMic = path; Log.Debug($"speak: fake mic {(path is null ? "off" : "on")}"); }+ public void SetTalkMic(string? name) { talkMic = name; Log.Debug($"speak: talk mic {name ?? "default"}"); }/// Dev: what the meeting hears. Records "CABLE Output" for `seconds` into `path` ("8 C:\x.wav").public async Task RecordCable(string arg)@@ -793,25 +799,68 @@ sealed class Controllerif (!Settings.Speak || Speak.State is SpeakEngine.Phase.Recording or SpeakEngine.Phase.Translating) return;if (!Ling.HasKey) { Speak.Report(Ling.Config.IsLing ? L("需要 Ling key 才能说") : LF("需要 %@ 的 key 才能说", Ling.Config.Name)); return; }if (Endpoints.Cable() is null) { Speak.Report(L("还没装虚拟麦克风,去设置里装一下")); return; }- if (fakeMic is null)+ // With a fake mic the WAV is what is sent; a dev talk mic still opens, to run the real capture.+ if (fakeMic is null || talkMic is not null){- if (Endpoints.Microphone() is not { } m) { Speak.Report(L("没找到麦克风")); return; }- mic = new DeviceRecorder(m.Id);- mic.Start();- if (mic.Error is { } err) { mic = null; Speak.Report(err == "denied" ? L("Windows 不让知了用麦克风:设置 › 隐私和安全性 › 麦克风") : L("麦克风打不开")); return; }+ if (TalkMic() is not { } m) { if (fakeMic is null) { Speak.Report(L("没找到麦克风")); return; } }+ else if (OpenTalkMic(m) is { } err)+ {+ if (fakeMic is 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;}+ /// The press's microphone: through Windows' echo cancellation when it opens, so what I say while+ /// the other side talks on the speakers is sent (EchoMic); the plain mic when it doesn't. Null,+ /// or why the mic can't be had ("denied").+ string? OpenTalkMic(Endpoints.Device m)+ {+ var speakers = Endpoints.Default(Endpoints.Flow.Render);+ // The cable is where my own voice goes, never the meeting's speakers.+ var reference = speakers is not null && speakers.Id != Endpoints.Cable()?.Id ? speakers.Id : null;+ var aec = new EchoMic(m.Id, reference);+ aec.Start();+ if (aec.Error is null)+ {+ echoMic = aec;+ echoLogged = aec.EchoCancelled;+ Log.Debug($"speak: mic {(aec.EchoCancelled ? "with echo cancellation" : "plain, no echo cancellation")} ({aec.Detail})");+ return null;+ }+ if (aec.Error == "denied") return "denied";+ mic = new DeviceRecorder(m.Id);+ mic.Start();+ Log.Debug($"speak: mic plain, the communications stream failed {aec.Error}");+ if (mic.Error is { } err) { mic = null; return err; }+ return null;+ }++ /// The talk key's microphone. Dev: `talkmic <name>` picks any input (the VM's only one is CABLE Output).+ Endpoints.Device? TalkMic() => talkMic is { } name+ ? Endpoints.All(Endpoints.Flow.Capture).FirstOrDefault(d => d.Description == name || d.Name.StartsWith(name))+ : Endpoints.Microphone();++ /// Ends the press's recording: what it heard, and whether through echo cancellation.+ (short[] pcm, bool echoCancelled) StopTalkMic()+ {+ // As logged when the press began (a stream still opening then counts as plain), and still so.+ var cancelled = echoLogged && echoMic?.EchoCancelled == true;+ echoLogged = false;+ var pcm = echoMic?.Stop() ?? mic?.Stop() ?? [];+ echoMic = null;+ mic = null;+ return (pcm, cancelled);+ }+/// Another key went down while a modifier talk key was held (Ctrl C): a shortcut, not talking.void PressInterrupted(){foreach (var r in roomSources) r.Muted = false;if (Speak.State != SpeakEngine.Phase.Recording) return;- mic?.Stop();- mic = null;+ StopTalkMic();Speak.Cancel();Log.Debug("talk: interrupted by another key");}@@ -837,13 +886,13 @@ sealed class Controller{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() ?? [];- mic = null;+ var (recorded, echoCancelled) = StopTalkMic();+ var pcm = fakeMic is { } f ? Wav.Read(f) : recorded;// A tap, not a sentence.if (pcm.Length < Segmenter.Rate * 3 / 10) { Speak.Cancel(); return; }// Held but nothing said (a muted mic): Ming would make something up from the hiss.if (pcm.Max(x => Math.Abs((int)x)) < 300) { Speak.Report(L("没听到你说话,没有发出去")); return; }- _ = Speak.Speak(Wav.Bytes(pcm), new DeviceSpeaker(Endpoints.Cable));+ _ = Speak.Speak(Wav.Bytes(pcm), new DeviceSpeaker(Endpoints.Cable), echoCancelled);}public enum PreviewResult { Played, Stopped, NoSpeaker, NoVoice, FellBack, Failed }@@ -1416,6 +1465,8 @@ static class DebugServerreturn new JsonObject { ["onCable"] = Endpoints.SpeakerIsCable(), ["speaker"] = Endpoints.Default(Endpoints.Flow.Render)?.Name, ["notified"] = app.Settings.CableSpeakerNotified,["defaults"] = string.Join(" ", Endpoints.Defaults().OrderBy(d => d.Key).Select(d => $"{d.Key}={(Endpoints.CableIds().Contains(d.Value) ? "cable" : "real")}")) };case "fakemic": app.SetFakeMic(arg == "off" ? null : arg); break;+ // talkmic <name>: the talk key reads this input (with fakemic the WAV is still what is sent).+ case "talkmic": app.SetTalkMic(arg is "" or "off" ? null : arg); break;case "record": _ = app.RecordCable(arg); break;// 回放: "open <id> [transcript]", "play <seconds>|toggle|speed", "recordaudio on|off".case "open": { var p = arg.Split(' '); app.OpenRecord(p[0], p.Length > 1 ? p[1] : "notes"); break; }diff --git a/windows/src/Cicada/EchoMic.cs b/windows/src/Cicada/EchoMic.csnew file mode 100644index 0000000..582b173--- /dev/null+++ b/windows/src/Cicada/EchoMic.cs@@ -0,0 +1,185 @@+using System.Runtime.InteropServices;++namespace Cicada.App;++/// The talk key's microphone through Windows' echo cancellation (VoiceMic.swift on the Mac): a+/// WASAPI capture stream in the communications category, so the endpoint's AEC (its driver's, or+/// Windows 11's Voice Clarity) takes the meeting playing on the speakers out of what I say. From+/// build 22621 the AEC is pointed at those speakers; from 22000 the stream says which effects run+/// (`EchoCancel.InEffect`). Records at 16 kHz mono until Stop, like DeviceRecorder.+///+/// EchoCancelled is true only when the stream lists an AEC that is on: then SpeakEngine skips the+/// echo drop. Otherwise (Windows 10, a driver without AEC, a virtual mic) the press is the plain+/// mic's and is dropped as before when the meeting played through it.+sealed class EchoMic+{+ readonly string id;+ readonly string? reference;+ readonly List<short> samples = [];+ Thread? thread;+ volatile bool running;+ /// "denied" (Windows' microphone privacy switch), or why the stream wouldn't open.+ public string? Error { get; private set; }+ public bool EchoCancelled { get; private set; }+ /// For the log: what Windows said about echo cancellation on this stream.+ public string Detail { get; private set; } = "";++ /// `reference`: the render endpoint the meeting plays on; null leaves the choice to Windows.+ public EchoMic(string id, string? reference) { this.id = id; this.reference = reference; }++ public void Start()+ {+ running = true;+ var ready = new ManualResetEventSlim();+ thread = new Thread(() => Run(ready)) { IsBackground = true, Name = "EchoMic" };+ thread.SetApartmentState(ApartmentState.MTA);+ thread.Start();+ ready.Wait(2000);+ }++ public short[] Stop()+ {+ running = false;+ thread?.Join(1500);+ lock (samples) return [.. samples];+ }++ void Run(ManualResetEventSlim ready)+ {+ IAudioClient? client = null;+ try+ {+ client = Endpoints.Activate(id);+ // Before Initialize: the category picks the endpoint's communications processing.+ // Options stay 0: RAW would turn off the very processing wanted here.+ var props = new AudioClientProperties { cbSize = 16, bIsOffload = 0, eCategory = 3 /* AudioCategory_Communications */, Options = 0 };+ Marshal.ThrowExceptionForHR(((IAudioClient2)client).SetClientProperties(ref props));+ var fmt = Endpoints.Pcm16(16000);+ int hr = client.Initialize(0, Endpoints.AutoConvert, 2_000_000, 0, fmt, IntPtr.Zero);+ Marshal.FreeHGlobal(fmt);+ Marshal.ThrowExceptionForHR(hr);+ var notes = new List<string>();+ // The speakers the meeting plays on as the AEC's reference (22621+). E_NOINTERFACE: no+ // AEC here, or one that picks its own reference; neither is an error.+ var iid = typeof(IAcousticEchoCancellationControl).GUID;+ if (client.GetService(ref iid, out var c) == 0 && c is IAcousticEchoCancellationControl control)+ {+ var set = control.SetEchoCancellationRenderEndpoint(reference);+ if (set != 0 && reference is not null) set = control.SetEchoCancellationRenderEndpoint(null);+ notes.Add(set == 0 ? $"reference {(reference is null ? "Windows' choice" : "the speakers")}" : $"reference failed 0x{set:X8}");+ }+ else notes.Add("no reference control");+ var effects = Effects(client, notes);+ EchoCancelled = EchoCancel.InEffect(effects);+ notes.Insert(0, effects is null ? "no effects list" : $"effects [{string.Join(", ", effects.Select(Name))}]");+ Detail = string.Join(", ", notes);+ iid = typeof(IAudioCaptureClient).GUID;+ Marshal.ThrowExceptionForHR(client.GetService(ref iid, out var s));+ var cap = (IAudioCaptureClient)s;+ Marshal.ThrowExceptionForHR(client.Start());+ ready.Set();+ while (running)+ {+ Thread.Sleep(10);+ while (cap.GetNextPacketSize(out var n) == 0 && n > 0)+ {+ if (cap.GetBuffer(out var data, out var frames, out var flags, out _, out _) != 0) break;+ var buf = new short[frames];+ if ((flags & 0x2) == 0) Marshal.Copy(data, buf, 0, (int)frames);+ cap.ReleaseBuffer(frames);+ lock (samples) samples.AddRange(buf);+ }+ }+ client.Stop();+ }+ catch (Exception e)+ {+ // 0x80070005: Windows' microphone privacy switch is off for desktop apps.+ Error = e.HResult == unchecked((int)0x80070005) ? "denied" : $"0x{e.HResult:X8}";+ EchoCancelled = false;+ Log.Debug($"echo mic: failed 0x{e.HResult:X8}");+ ready.Set();+ }+ finally { if (client is not null) Marshal.ReleaseComObject(client); }+ }++ /// The stream's effects (22000+), with an AEC that is off but may be set turned on first; null+ /// when Windows can't list them.+ static List<EchoCancel.AudioEffect>? Effects(IAudioClient client, List<string> notes)+ {+ var iid = typeof(IAudioEffectsManager).GUID;+ if (client.GetService(ref iid, out var o) != 0 || o is not IAudioEffectsManager manager) return null;+ var list = Read(manager);+ if (list is not null && EchoCancel.CanTurnOn(list))+ {+ var hr = manager.SetAudioEffectState(EchoCancel.Effect, 1 /* AUDIO_EFFECT_STATE_ON */);+ notes.Add(hr == 0 ? "turned AEC on" : $"AEC on failed 0x{hr:X8}");+ list = Read(manager);+ }+ return list;+ }++ static List<EchoCancel.AudioEffect>? Read(IAudioEffectsManager manager)+ {+ if (manager.GetAudioEffects(out var p, out var n) != 0) return null;+ var list = new List<EchoCancel.AudioEffect>();+ try+ {+ // AUDIO_EFFECT: GUID id, BOOL canSetState, AUDIO_EFFECT_STATE state: 24 bytes.+ for (int i = 0; i < n; i++)+ {+ var e = Marshal.PtrToStructure<AudioEffect>(p + i * Marshal.SizeOf<AudioEffect>());+ list.Add(new(e.id, e.canSetState != 0, e.state == 1));+ }+ }+ finally { if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); }+ return list;+ }++ static string Name(EchoCancel.AudioEffect e) =>+ (e.Id == EchoCancel.Effect ? "AEC" : e.Id.ToString()[..8]) + (e.On ? " on" : " off");++ // MARK: COM (audioclient.h, Windows SDK 10.0.22621). Nested so they can't meet other declarations.++ [StructLayout(LayoutKind.Sequential)]+ struct AudioClientProperties { public uint cbSize; public int bIsOffload; public int eCategory; public int Options; }++ [StructLayout(LayoutKind.Sequential)]+ struct AudioEffect { public Guid id; public int canSetState; public int state; }++ /// IAudioClient's methods again, in order: a ComImport interface doesn't inherit vtable slots.+ [ComImport, Guid("726778CD-F60A-4eda-82DE-E47610CD78AA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IAudioClient2+ {+ [PreserveSig] int Initialize(int shareMode, uint streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr sessionGuid);+ [PreserveSig] int GetBufferSize(out uint frames);+ [PreserveSig] int GetStreamLatency(out long latency);+ [PreserveSig] int GetCurrentPadding(out uint padding);+ [PreserveSig] int IsFormatSupported(int shareMode, IntPtr format, out IntPtr closest);+ [PreserveSig] int GetMixFormat(out IntPtr format);+ [PreserveSig] int GetDevicePeriod(out long defaultPeriod, out long minimumPeriod);+ [PreserveSig] int Start();+ [PreserveSig] int Stop();+ [PreserveSig] int Reset();+ [PreserveSig] int SetEventHandle(IntPtr handle);+ [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service);+ [PreserveSig] int IsOffloadCapable(int category, out int capable);+ [PreserveSig] int SetClientProperties(ref AudioClientProperties properties);+ [PreserveSig] int GetBufferSizeLimits(IntPtr format, int eventDriven, out long min, out long max);+ }++ [ComImport, Guid("f4ae25b5-aaa3-437d-b6b3-dbbe2d0e9549"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IAcousticEchoCancellationControl+ {+ [PreserveSig] int SetEchoCancellationRenderEndpoint([MarshalAs(UnmanagedType.LPWStr)] string? endpointId);+ }++ [ComImport, Guid("4460B3AE-4B44-4527-8676-7548A8ACD260"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+ interface IAudioEffectsManager+ {+ [PreserveSig] int RegisterAudioEffectsChangedNotificationCallback(IntPtr client);+ [PreserveSig] int UnregisterAudioEffectsChangedNotificationCallback(IntPtr client);+ [PreserveSig] int GetAudioEffects(out IntPtr effects, out uint count);+ [PreserveSig] int SetAudioEffectState(Guid effectId, int state);+ }+}diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex c173fe2..8681d00 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -1681,11 +1681,39 @@ static class Testsfor (var i = 0; i < 30; i++) { log.Add(true); now += 0.1; }Check(await engine.Speak(Wav.Bytes(Tone(1)), new Sink()) is null && asked == 1, "pressed while the meeting played: not sent");Equal(Strings.L("对方在说话时说的,没有说出去"), engine.Problem, "and the bar says why");+ // The same press through Windows' echo cancellation: the meeting is taken out, I am sent.+ reply = "LANG: zh-CN\nORIGINAL: 我们周三能测完吗?\nTRANSLATION: Can we finish testing by Wednesday?";+ engine.BeginRecording();+ for (var i = 0; i < 30; i++) { log.Add(true); now += 0.1; }+ Equal("Can we finish testing by Wednesday?", await engine.Speak(Wav.Bytes(Tone(1)), new Sink(), echoCancelled: true), "pressed while the meeting played, echo cancelled: sent");+ Check(asked == 2 && engine.Problem is null, "and heard by the service");+ // Echo cancellation doesn't let a silent press through.+ engine.BeginRecording();+ for (var i = 0; i < 30; i++) { log.Add(true); now += 0.1; }+ Check(await engine.Speak(Wav.Bytes(new short[16000 * 3]), new Sink(), echoCancelled: true) is null && asked == 2, "a silent press still sends nothing");}finally { LingClient.Spacing = old; }Check(PressSpeech.Filler("嗯嗯。") && PressSpeech.Filler("Um, uh...") && !PressSpeech.Filler("嗯,好的。") && !PressSpeech.Filler("OK."), "fillers");}+ public static void EchoIsDroppedOnlyFromThePlainMic()+ {+ Check(SpeakEngine.EchoDrop(false, 0.51), "plain mic, meeting over half the press: dropped");+ Check(!SpeakEngine.EchoDrop(false, 0.5), "half exactly: kept, as before");+ Check(!SpeakEngine.EchoDrop(true, 1.0), "echo cancelled: never dropped as echo");+ var aec = EchoCancel.Effect;+ var ns = new Guid("6f64adbf-8211-11e2-8c70-2c27d7f001fa");+ Check(!EchoCancel.InEffect(null), "no effects list (Windows 10): plain");+ Check(!EchoCancel.InEffect([]), "nothing listed: plain");+ Check(!EchoCancel.InEffect([new(ns, false, true)]), "noise suppression alone isn't echo cancellation");+ Check(!EchoCancel.InEffect([new(aec, false, false)]), "AEC listed but off: plain");+ Check(EchoCancel.InEffect([new(ns, false, true), new(aec, false, true)]), "AEC on: cancelled");+ Check(EchoCancel.CanTurnOn([new(aec, true, false)]) && !EchoCancel.CanTurnOn([new(aec, false, false)]) && !EchoCancel.CanTurnOn([new(aec, true, true)]), "only an AEC that is off and may be set is turned on");+ var m = PressSpeech.Measure(Wav.Bytes(Tone(1)));+ Check(m.Spoken && m.Summary.StartsWith("voiced ") && m.Summary.Contains("dBFS"), $"the press measure is logged: {m.Summary}");+ Check(!PressSpeech.Measure(Wav.Bytes(new short[100])).Spoken, "too short to measure");+ }+public static async Task WhatISayGoesAheadOfTheMeeting(){var old = LingClient.Spacing;