知了 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): meetings are recorded, and the recording plays back in the record, a click on a line's time plays from there, and the line playing lights up
wquguru0f98e968ba44
diff --git a/windows/README.md b/windows/README.mdindex 0bd06a0..867723c 100644--- a/windows/README.md+++ b/windows/README.md@@ -1,6 +1,6 @@# 知了 Windows 版-Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录;同声传译(按住右 Ctrl 说话,翻译后的声音经 VB-Cable 虚拟麦克风进会议);说话人识别(按声音标出说话人 1、2…,声纹模型是 WeSpeaker ResNet34-LM,CC BY 4.0,用 `scripts/compress-voiceprint.py` 压成 int8,6.7 MB,由系统自带的 Windows ML 在本机运行)。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。+Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录,连同会议录音(`system.m4a`,Windows 自带的 AAC 编码),会后在会议记录里回放;同声传译(按住右 Ctrl 说话,翻译后的声音经 VB-Cable 虚拟麦克风进会议);说话人识别(按声音标出说话人 1、2…,声纹模型是 WeSpeaker ResNet34-LM,CC BY 4.0,用 `scripts/compress-voiceprint.py` 压成 int8,6.7 MB,由系统自带的 Windows ML 在本机运行)。方案和取舍见 [docs/windows-plan.md](../docs/windows-plan.md)。- 抓声音:WASAPI 进程回环,排除知了自己(Windows 10 2004 起)。- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求同时返回语言、原文和译文;需要 Ling key。用不了 Ling 的可以在 设置 › AI 服务 换成 OpenRouter、ZenMux 或兼容 OpenAI 的地址:听交给它能输入音频的模型(同样的提示词,字幕晚 1–2 秒),纪要和翻译用它的文字模型,同传声音用它的声音模型,没有时用 Windows 的声音。diff --git a/windows/src/Cicada.Core/Adts.cs b/windows/src/Cicada.Core/Adts.csnew file mode 100644index 0000000..db4db88--- /dev/null+++ b/windows/src/Cicada.Core/Adts.cs@@ -0,0 +1,54 @@+namespace Cicada;++/// The frames of an ADTS file (`system.aac`), for rewrapping into an .m4a without re-encoding.+/// Windows' own ADTS reader hands out byte chunks of several frames each, which the MP4 sink can't+/// time, so the file is split here. A frame cut off by a crash ends the list.+public static class Adts+{+ public readonly record struct Frame(int Offset, int Length);++ /// What the frames hold: AAC object type, sample rate and channels, and the AudioSpecificConfig+ /// an MP4 track needs.+ public sealed record Config(int ObjectType, int Rate, int Channels, byte[] SpecificConfig);++ static readonly int[] Rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];++ public static Config? Read(ReadOnlySpan<byte> file)+ {+ int at = Sync(file, 0);+ if (at < 0 || file.Length - at < 7) return null;+ var h = file[at..];+ int obj = (h[2] >> 6) + 1, index = (h[2] >> 2) & 0xF, channels = ((h[2] & 1) << 2) | (h[3] >> 6);+ if (index >= Rates.Length) return null;+ byte[] asc = [(byte)((obj << 3) | (index >> 1)), (byte)(((index & 1) << 7) | (channels << 3))];+ return new Config(obj, Rates[index], channels, asc);+ }++ /// Each frame's payload (the header left out), in order.+ public static List<Frame> Frames(ReadOnlySpan<byte> file)+ {+ var frames = new List<Frame>();+ int at = Sync(file, 0);+ while (at >= 0 && file.Length - at >= 7)+ {+ var h = file[at..];+ int length = ((h[3] & 3) << 11) | (h[4] << 3) | (h[5] >> 5);+ int header = (h[1] & 1) == 1 ? 7 : 9;+ if (length <= header) { at = Sync(file, at + 1); continue; }+ if (at + length > file.Length) break; // cut off mid-frame+ frames.Add(new Frame(at + header, length - header));+ at += length;+ // Something not a frame (a torn write): skip to the next sync word.+ if (at < file.Length && !IsSync(file, at)) at = Sync(file, at);+ }+ return frames;+ }++ static bool IsSync(ReadOnlySpan<byte> f, int i) => i + 1 < f.Length && f[i] == 0xFF && (f[i + 1] & 0xF6) == 0xF0;++ static int Sync(ReadOnlySpan<byte> f, int from)+ {+ for (int i = from; i + 1 < f.Length; i++) if (IsSync(f, i)) return i;+ return -1;+ }+}diff --git a/windows/src/Cicada.Core/ListenEngine.cs b/windows/src/Cicada.Core/ListenEngine.csindex 298fa43..db6b18c 100644--- a/windows/src/Cicada.Core/ListenEngine.cs+++ b/windows/src/Cicada.Core/ListenEngine.cs@@ -18,7 +18,11 @@ public sealed class ListenEnginereadonly object gate = new();IAudioSource? source;- Channel<short[]>? audio;+ Channel<(short[] buf, double at)>? audio;+ /// When this side began (Stopwatch ticks): with `offset`, the meeting's clock.+ long began;+ /// 保存会议录音: the main side writes what it hears to the meeting's system.aac.+ IAudioWriter? recorder;Task? worker;Segmenter? segmenter;readonly Dictionary<int, Heard?> done = [];@@ -124,10 +128,23 @@ public sealed class ListenEngine{if (Listening || RoomSide) return;var session = store.Begin();+ // The clock starts with the record, not after the encoder has opened.+ var since = System.Diagnostics.Stopwatch.GetTimestamp();SessionId = session.Id;Room = room;if (room) store.MarkRoom(session.Id);- Begin(from, room, 0);+ if (settings.RecordAudio && store.Audio is { } files)+ {+ var path = Recording.Partial(Recording.SystemAudio(session.Id));+ try+ {+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ recorder = files.Open(path);+ }+ catch (Exception e) { Log.Debug($"listen: recording not started {e.GetType().Name}"); }+ if (recorder is null) Log.Debug("listen: no recording, the encoder refused");+ }+ Begin(from, room, 0, since);notes.Language = () => Languages.EnglishName(settings.NotesCode);notes.Begin(session.Id);Log.Debug($"listen: started {session.Id} target={Target}");@@ -152,7 +169,7 @@ public sealed class ListenEngineChanged?.Invoke();}- void Begin(IAudioSource from, bool room, double at)+ void Begin(IAudioSource from, bool room, double at, long? since = null){lock (gate){@@ -163,13 +180,26 @@ public sealed class ListenEngineoffset = at;segmenter = new Segmenter(room ? new VoiceGate() : null);segmenter.Emitted += Send;- audio = Channel.CreateUnbounded<short[]>(new UnboundedChannelOptions { SingleReader = true });+ audio = Channel.CreateUnbounded<(short[], double)>(new UnboundedChannelOptions { SingleReader = true });var reader = audio.Reader;- // One reader thread owns the segmenter: audio callbacks only queue buffers.+ began = since ?? System.Diagnostics.Stopwatch.GetTimestamp();+ long fed = 0;+ // One reader thread owns the segmenter (and the recording): audio callbacks only queue buffers.worker = Task.Run(async () =>{- await foreach (var buf in reader.ReadAllAsync())+ await foreach (var (buf, at) in reader.ReadAllAsync()){+ // Keep the meeting's clock: a gap the source left (the PC silent, a source switch)+ // goes in as silence, so a line's t and the recording both stay on the wall clock.+ if (Recording.Behind(at, fed, buf.Length) is > 0 and var gap)+ {+ var silence = new short[gap];+ segmenter.Feed(silence);+ Record(silence);+ fed += gap;+ }+ Record(buf);+ fed += buf.Length;Level = Rms(buf);// The computer is playing speech: the room mic would hear it from the speakers.if (!RoomSide && Echo is { } echo && Level >= Segmenter.Threshold) echo.Gate.Hold();@@ -203,7 +233,25 @@ public sealed class ListenEngine}}- void OnSamples(short[] buf) => audio?.Writer.TryWrite(buf);+ void OnSamples(short[] buf) => audio?.Writer.TryWrite((buf, System.Diagnostics.Stopwatch.GetElapsedTime(began).TotalSeconds));++ void Record(short[] pcm)+ {+ if (recorder is null) return;+ try { recorder.Write(pcm); }+ catch (Exception e)+ {+ Log.Debug($"listen: recording failed {e.GetType().Name} 0x{e.HResult:X8}, stopped");+ CloseRecording();+ }+ }++ void CloseRecording()+ {+ var r = recorder;+ recorder = null;+ try { r?.Close(); } catch (Exception e) { Log.Debug($"listen: recording close failed {e.GetType().Name}"); }+ }/// 听哪里 changed mid-meeting between the computer and the room: the same meeting goes on from the/// other source, its clock running on.@@ -241,6 +289,7 @@ public sealed class ListenEngineif (worker is not null) await worker;Task[] waiting;lock (gate) waiting = inFlight.ToArray();+ CloseRecording();await Task.WhenAny(Task.WhenAll(waiting), Task.Delay(15_000));var id = SessionId!;if (RoomSide)diff --git a/windows/src/Cicada.Core/Recording.cs b/windows/src/Cicada.Core/Recording.csnew file mode 100644index 0000000..7f3d53f--- /dev/null+++ b/windows/src/Cicada.Core/Recording.cs@@ -0,0 +1,48 @@+namespace Cicada;++/// 保存会议录音: what was heard goes into `system.m4a` beside session.json, as on the Mac+/// (AudioFiles.swift). While the meeting runs it is written as ADTS (`system.aac`), which stays+/// readable up to its last frame if the app is killed; when the meeting ends it is rewrapped into+/// the .m4a, and a partial file left by a crash is rewrapped at the next launch. The encoder is+/// the app's (Media Foundation); Core only decides what goes in and when.+public interface IAudioFiles+{+ /// An AAC (ADTS) file at `path` for 16 kHz mono; null when this PC can't encode.+ IAudioWriter? Open(string path);+ /// `from` (ADTS) into the .m4a `to`, the first `until` seconds only when given. False on failure.+ bool Rewrap(string from, string to, double? until);+}++public interface IAudioWriter+{+ void Write(ReadOnlySpan<short> pcm);+ /// Writes what is buffered and closes the file.+ void Close();+}++public static class Recording+{+ public static string SystemAudio(string sessionId) => Path.Combine(Paths.Sessions, sessionId, "system.m4a");+ public static string Partial(string m4a) => Path.ChangeExtension(m4a, ".aac");++ /// The file a record plays: its own recording, or an imported file's where it still is.+ public static string? Playable(Session s)+ {+ var own = SystemAudio(s.Id);+ if (File.Exists(own)) return own;+ if (s.SourcePath is { Length: > 0 } p && File.Exists(p)) return p;+ return null;+ }++ /// Samples of silence that go in before a buffer so the recording keeps the meeting's clock:+ /// loopback capture sends nothing while the PC is silent (SystemAudioTap fills only what it+ /// notices), a source switch leaves a gap, and a line's `t` is its time since the meeting began.+ /// `at`: meeting seconds when the buffer arrived; `fed`: samples already given; `count`: the+ /// buffer's. Nothing while the stream is within LoopbackGap.Late of the clock, so a packet that+ /// is merely late never puts a gap in a sentence.+ public static int Behind(double at, long fed, int count)+ {+ var lag = at - (fed + count) / (double)Segmenter.Rate;+ return lag >= LoopbackGap.Late ? (int)(lag * Segmenter.Rate) : 0;+ }+}diff --git a/windows/src/Cicada.Core/SessionStore.cs b/windows/src/Cicada.Core/SessionStore.csindex 8af5dbd..a0eac87 100644--- a/windows/src/Cicada.Core/SessionStore.cs+++ b/windows/src/Cicada.Core/SessionStore.cs@@ -16,6 +16,9 @@ public sealed class SessionStore/// 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;+ /// The app's audio encoder (Media Foundation); null where there is none (the Mac CLI, tests+ /// that don't set one): meetings are then kept without a recording.+ public IAudioFiles? Audio { get; set; }public SessionStore() { Load(); }@@ -120,17 +123,64 @@ public sealed class SessionStore/// The meeting ended (at `endedAt` when it ended by itself a while ago): kept if anything was/// said, removed otherwise.+ /// The meeting's recording, if any, is closed by then (ListenEngine.Stop): it is rewrapped into+ /// system.m4a in the background, cut at `endedAt` when the meeting ended by itself a while ago+ /// (its silent tail), as SessionStore.swift › end does.public void End(string id, DateTimeOffset? endedAt = null){bool empty;+ double? until = null;lock (gate){if (!sessions.TryGetValue(id, out var s)) return;s.EndedAt = endedAt is { } at ? (at > s.StartedAt ? at : s.StartedAt) : DateTimeOffset.Now;empty = s.Lines.Count == 0;+ var m4a = Recording.SystemAudio(id);+ s.HasAudio = File.Exists(m4a) || File.Exists(Recording.Partial(m4a));+ if (endedAt is not null) until = s.Duration.TotalSeconds;}- if (empty) Delete(id);- else { MarkDirty(id); Flush(); }+ if (empty) { Delete(id); return; }+ MarkDirty(id); Flush();+ _ = Task.Run(() => FinishAudio(id, until));+ }++ /// Recordings a meeting didn't get to close (the app was killed or the PC went off): the+ /// partial file is rewrapped now, as SessionStore.swift › load does. Call once Audio is set.+ public void FinishLeftovers(string? live = null)+ {+ List<string> left;+ lock (gate) left = sessions.Keys.Where(id => id != live && File.Exists(Recording.Partial(Recording.SystemAudio(id)))).ToList();+ foreach (var id in left)+ {+ Mutate(id, s => s.HasAudio = true);+ _ = Task.Run(() => FinishAudio(id, null));+ }+ }++ /// system.aac into system.m4a. A partial file beside an .m4a means the last rewrap was cut+ /// short: it is done again. One that fails leaves the partial file for the next launch.+ void FinishAudio(string id, double? until)+ {+ var m4a = Recording.SystemAudio(id);+ var partial = Recording.Partial(m4a);+ if (Audio is not { } audio || !File.Exists(partial)) return;+ try+ {+ if (File.Exists(m4a)) File.Delete(m4a);+ var started = DateTime.UtcNow;+ if (audio.Rewrap(partial, m4a, until))+ {+ File.Delete(partial);+ Log.Debug($"store: recording {id} finished in {(DateTime.UtcNow - started).TotalMilliseconds:F0} ms");+ }+ else+ {+ try { File.Delete(m4a); } catch { }+ Log.Debug($"store: recording {id} rewrap failed");+ }+ }+ catch (Exception e) { Log.Debug($"store: recording {id} rewrap failed {e.GetType().Name}"); }+ Changed?.Invoke(id);}public void Delete(string id)diff --git a/windows/src/Cicada.Core/Settings.cs b/windows/src/Cicada.Core/Settings.csindex 7b72326..06b979d 100644--- a/windows/src/Cicada.Core/Settings.cs+++ b/windows/src/Cicada.Core/Settings.cs@@ -43,6 +43,8 @@ public sealed class AppSettings[JsonPropertyName("uiLanguage")] public string UiLanguage { get; set; } = "system";/// 字幕文字大小, in px.[JsonPropertyName("subtitleSize")] public int SubtitleSize { get; set; } = 24;+ /// 保存会议录音 (the Mac's key): keep what was heard as system.m4a in the meeting's folder.+ [JsonPropertyName("recordAudio")] public bool RecordAudio { get; set; } = true;/// 说话人识别: tell the other side's voices apart (on by default, as on the Mac).[JsonPropertyName("speakerVoices")] public bool SpeakerVoices { get; set; } = true;/// 同声传译: hold right Ctrl to speak into the meeting in its language.diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.csindex 565d48c..d7bfa73 100644--- a/windows/src/Cicada/App.cs+++ b/windows/src/Cicada/App.cs@@ -148,6 +148,9 @@ sealed class Controller}Log.Debug($"app: launch {(Paths.Dev ? "dev" : "release")} {Environment.OSVersion.Version}");SetUpTray();+ // 保存会议录音: Windows' AAC encoder; a recording the last run didn't close is finished now.+ Store.Audio = new MediaFoundationAudio();+ Store.FinishLeftovers();hotkey = new Hotkey(() => Dispatch.BeginInvoke(() => _ = ToggleListening()));talk = new PushToTalk();talk.Pressed += () => Dispatch.BeginInvoke(PressBegan);@@ -840,6 +843,10 @@ sealed class Controllerpublic void ShowRecords() => ShowRecords(null);+ /// Debug pipe: a record opened at a tab, and the player in it.+ public void OpenRecord(string id, string tab) { ShowRecords(id); mainWindow?.Select(id, tab); }+ public void Play(string arg) => mainWindow?.DebugPlay(arg);+public void ShowRecords(string? id){if (mainWindow is null) { mainWindow = new MainWindow(this, id); mainWindow.Closed += (_, _) => { mainWindow = null; WindowClosed(); }; }@@ -1150,6 +1157,9 @@ sealed class Controller["roomEcho"] = Listen.Echo?.Gate.Echo,["roomMusic"] = Listen.Echo?.Gate.PlayingMusic,["room"] = Listen.Room,+ ["recordAudio"] = Settings.RecordAudio,+ ["hasAudio"] = Listen.SessionId is { } aid && Store.Get(aid) is { } a ? a.HasAudio : null,+ ["player"] = mainWindow?.PlayerState(),};}@@ -1161,6 +1171,8 @@ sealed class Controller/// updatefeed <url or file> | checkupdate/// calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice <id> (设置 › AI 服务; no id: the recommended)+/// open <id> [transcript] | play <seconds>|toggle|speed | recordaudio on|off (保存会议录音 and 回放)+/// aacencode <wav>|<out.aac> | aacrewrap <in.aac>|<out.m4a>[|<seconds>]/// ai-check | ai-check-sim <reason|lowBalance|off> (unreachable, invalidKey, noCredit, noModel, deaf, busy…)static class DebugServer{@@ -1258,6 +1270,26 @@ static class DebugServercase "speakers": app.Settings.SpeakerVoices = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;case "fakemic": app.SetFakeMic(arg == "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; }+ case "play": app.Play(arg); break;+ case "recordaudio": app.Settings.RecordAudio = arg == "on"; app.Settings.Save(); app.SettingsChanged(); break;+ // 保存会议录音 on its own: "aacencode <wav>|<out.aac>", "aacrewrap <in.aac>|<out.m4a>[|<seconds>]".+ case "aacencode":+ {+ var p = arg.Split('|');+ var w = app.Store.Audio?.Open(p[1]);+ if (w is null) return new JsonObject { ["error"] = "no encoder" };+ var pcm = Wav.Read(p[0]);+ for (int i = 0; i < pcm.Length; i += 1600) w.Write(pcm.AsSpan(i, Math.Min(1600, pcm.Length - i)));+ w.Close();+ return new JsonObject { ["ok"] = true };+ }+ case "aacrewrap":+ {+ var p = arg.Split('|');+ return new JsonObject { ["ok"] = app.Store.Audio?.Rewrap(p[0], p[1], p.Length > 2 ? double.Parse(p[2], System.Globalization.CultureInfo.InvariantCulture) : null) ?? false };+ }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]) };diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.csindex 6cda6c0..f3a0be8 100644--- a/windows/src/Cicada/MainWindow.cs+++ b/windows/src/Cicada/MainWindow.cs@@ -118,11 +118,12 @@ sealed class MainWindow : WindowContent = Ui.Frameless(this, grid);// The pill's clock and level move while listening; nothing else needs a timer.tick.Tick += (_, _) => { if (app.Listen.Listening) Pill(); else { tick.Stop(); Pill(); } };- Closed += (_, _) => tick.Stop();+ Closed += (_, _) => { tick.Stop(); ClosePlayer(); };+ playTick.Tick += (_, _) => UpdatePlayer();Refresh();}- public void Select(string id) { selected = id; tab = "notes"; shownKey = null; Fill(); }+ public void Select(string id, string page = "notes") { selected = id; tab = page; shownKey = null; Fill(); }public void Refresh(){@@ -387,7 +388,7 @@ sealed class MainWindow : Window/// What the open page shows; a store change that leaves it the same doesn't redraw it.string? PageKey() => selected is not null && app.Store.Get(selected) is { } cur- ? $"{selected}|{tab}|{SessionStore.DisplayTitle(cur)}|{cur.Lines.Count}|{cur.Notes?.Covered}|{cur.Notes?.Final}|{app.Listen.Listening}|{app.Notes.GeneratingId == selected}"+ ? $"{selected}|{tab}|{SessionStore.DisplayTitle(cur)}|{cur.Lines.Count}|{cur.Notes?.Covered}|{cur.Notes?.Final}|{app.Listen.Listening}|{app.Notes.GeneratingId == selected}|{cur.HasAudio}|{Recording.Playable(cur)}|{app.Settings.RecordAudio}": null;void ShowDetail()@@ -420,6 +421,7 @@ sealed class MainWindow : WindowtitleRow.Children.Add(reset);}top.Children.Add(titleRow);+ if (PlayerArea(s, live) is { } audio) top.Children.Add(audio);// 纪要 / 文字记录 on the left, what to do with it on the right, one hairline under both.FrameworkElement Tabs(double size) => Ui.Tabs([("notes", L("纪要")), ("transcript", s.Lines.Count > 0 ? $"{L("文字记录")} {s.Lines.Count}" : L("文字记录"))], tab, t => { tab = t; ShowDetail(); }, size);@@ -437,6 +439,7 @@ sealed class MainWindow : Windowbody.Margin = new Thickness(0, 28, 0, 0);page.Children.Add(body);var scroll = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = page };+ pageScroll = scroll;// Once the title block scrolls away, a slim bar on top keeps the title (a click goes back// up), the tabs and the tools in view: the Mac's pinned bar.@@ -604,12 +607,15 @@ sealed class MainWindow : Window{var body = new StackPanel();FrameworkElement? target = null;+ rows.Clear(); lit = -1;+ Action<double>? play = player is not null ? PlayFrom : null;// The line nearest the topic's time (older notes may hold a time no line has).var nearest = jumpTo is { } t0 && s.Lines.Count > 0 ? s.Lines.MinBy(l => Math.Abs(l.T - t0)) : null;foreach (var (l, who, ink, place) in NotesWindow.Speakers(s.Lines, app.Settings.SpeakerVoices)){- var line = NotesWindow.TranscriptRow(l, who, ink, place);+ var line = NotesWindow.TranscriptRow(l, who, ink, place, play);if (ReferenceEquals(l, nearest)) target = line;+ if (play is not null && line is Panel row0 && FindTime(row0) is { } time) rows.Add((l.T, row0, time));body.Children.Add(line);}if (target is Panel row)@@ -632,9 +638,268 @@ sealed class MainWindow : Windowfade.Start();}jumpTo = null;+ if (player is not null) Dispatcher.BeginInvoke(UpdatePlayer, DispatcherPriority.Loaded);return body;}+ static TextBlock? FindTime(Panel row) =>+ row.Children.OfType<Panel>().FirstOrDefault()?.Children.OfType<TextBlock>().FirstOrDefault(t => (t.Tag as string) == "time");++ // MARK: 回放++ // One player for the open record, kept while the page redraws (lines and notes arriving) and+ // closed when another record opens, the record is deleted or the window closes.+ MediaPlayer? player;+ string? playerPath;+ bool playing, opened;+ double speed = 1;+ double? pendingSeek;+ readonly DispatcherTimer playTick = new() { Interval = TimeSpan.FromMilliseconds(200) };+ ScrollViewer? pageScroll;+ // The transcript's lines with their times, in time order, and the one at the playhead.+ readonly List<(double t, Panel row, TextBlock time)> rows = [];+ int lit = -1;+ // The bar's moving parts, rebuilt with the page.+ TextBlock? nowText, lengthText, speedText;+ Border? played;+ FrameworkElement? thumb;+ Grid? track;+ Button? playButton;+ double fallbackLength;++ /// Under the title: the player for a recording; while live, that it plays afterwards; else+ /// why there is none (and where to turn recording on).+ FrameworkElement? PlayerArea(Session s, bool live)+ {+ FrameworkElement Note(FrameworkElement e) { e.Margin = new Thickness(0, 12, 0, 0); return e; }+ if (live)+ {+ ClosePlayer();+ return app.Settings.RecordAudio ? Note(Ui.Text(L("会议结束后可以回放录音"), 12, Palette.Secondary)) : null;+ }+ var path = Recording.Playable(s);+ if (path is null)+ {+ ClosePlayer();+ // Just ended: system.aac is being rewrapped into system.m4a, a moment.+ if (File.Exists(Recording.Partial(Recording.SystemAudio(s.Id)))) return null;+ if (s.HasAudio || s.SourcePath is not null) return Note(Ui.Text(L("找不到录音,没法播放"), 12, Palette.Secondary));+ if (s.Lines.Count == 0) return null;+ var link = Ui.LinkText(L("保存会议录音"), () => { app.ShowSettings(); app.SettingsPage("privacy"); }, 12);+ return Note(Ui.Row(4, Ui.Text(L("这场会议没存录音 ·"), 12, Palette.Secondary, wrap: false), link));+ }+ if (playerPath != path)+ {+ ClosePlayer();+ playerPath = path;+ opened = false;+ player = new MediaPlayer();+ player.MediaOpened += (_, _) =>+ {+ opened = true;+ if (!playing) player!.Pause(); // MediaPlayer starts playing by itself once opened+ if (pendingSeek is { } t) { pendingSeek = null; player!.Position = TimeSpan.FromSeconds(t); }+ UpdatePlayer();+ };+ player.MediaEnded += (_, _) => Ended();+ player.MediaFailed += (_, e) => Log.Debug($"player: failed {e.ErrorException?.GetType().Name} 0x{e.ErrorException?.HResult:X8}");+ player.Open(new Uri(path));+ player.Pause();+ player.SpeedRatio = speed;+ }+ fallbackLength = s.Duration.TotalSeconds;+ return Note(PlayerBar());+ }++ FrameworkElement PlayerBar()+ {+ playButton = Capsule(Ui.Icon(playing ? Icons.Pause : Icons.Play, 14, Brushes.White, fill: true), Palette.Ink, null, 36, new Thickness(0), TogglePlay, playing ? L("暂停") : L("播放"));+ playButton.Width = 36;+ playButton.ToolTip = playing ? L("暂停") : L("播放");+ nowText = Clock("00:00");+ lengthText = Clock(Languages.Clock(fallbackLength));+ speedText = Ui.Text(SpeedLabel(), 12, Palette.Body, Palette.Strong, wrap: false);+ var speedButton = Capsule(speedText, Palette.Surface, Palette.Line, 26, new Thickness(9, 0, 9, 0), CycleSpeed, L("播放速度"));+ speedButton.ToolTip = L("播放速度");++ // The slider: a grey rail, the played part in the accent, a round handle; click or drag.+ var rail = new Border { Height = 4, CornerRadius = new CornerRadius(2), Background = Palette.Line, VerticalAlignment = VerticalAlignment.Center };+ played = new Border { Height = 4, CornerRadius = new CornerRadius(2), Background = Palette.Live, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Width = 0 };+ thumb = new System.Windows.Shapes.Ellipse { Width = 12, Height = 12, Fill = Palette.Live, Stroke = Brushes.White, StrokeThickness = 2, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left };+ track = new Grid { Height = 24, Background = Brushes.Transparent, Cursor = System.Windows.Input.Cursors.Hand, Margin = new Thickness(12, 0, 12, 0), Children = { rail, played, thumb } };+ System.Windows.Automation.AutomationProperties.SetName(track, L("播放"));+ void SeekTo(System.Windows.Input.MouseEventArgs e)+ {+ if (track.ActualWidth <= 0) return;+ var f = Math.Clamp(e.GetPosition(track).X / track.ActualWidth, 0, 1);+ Seek(f * Length());+ }+ track.MouseLeftButtonDown += (_, e) => { track.CaptureMouse(); SeekTo(e); e.Handled = true; };+ track.MouseMove += (_, e) => { if (track.IsMouseCaptured) SeekTo(e); };+ track.MouseLeftButtonUp += (_, _) => track.ReleaseMouseCapture();+ track.SizeChanged += (_, _) => UpdatePlayer();++ var bar = new DockPanel { LastChildFill = true };+ foreach (var (e, dock, left) in new (FrameworkElement, Dock, double)[] { (playButton, Dock.Left, 0), (nowText, Dock.Left, 12), (speedButton, Dock.Right, 12), (lengthText, Dock.Right, 0) })+ {+ e.VerticalAlignment = VerticalAlignment.Center;+ e.Margin = new Thickness(left, 0, 0, 0);+ DockPanel.SetDock(e, dock);+ bar.Children.Add(e);+ }+ bar.Children.Add(track);+ Dispatcher.BeginInvoke(UpdatePlayer, DispatcherPriority.Loaded);+ return new Border+ {+ Background = Palette.PlayerFill, BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(12),+ Padding = new Thickness(8, 8, 10, 8), Child = bar,+ };++ static TextBlock Clock(string text)+ {+ var t = Ui.Text(text, 12, Palette.Secondary, wrap: false);+ System.Windows.Documents.Typography.SetNumeralAlignment(t, FontNumeralAlignment.Tabular);+ return t;+ }+ }++ string SpeedLabel() => speed == 1 ? "1×" : speed == 1.5 ? "1.5×" : "2×";++ double Length() => player is { NaturalDuration.HasTimeSpan: true } p ? p.NaturalDuration.TimeSpan.TotalSeconds : fallbackLength;++ double Now() => pendingSeek ?? player?.Position.TotalSeconds ?? 0;++ void TogglePlay()+ {+ if (player is null) return;+ if (playing) { player.Pause(); playing = false; playTick.Stop(); }+ else { player.Play(); playing = true; playTick.Start(); }+ Log.Debug($"player: {(playing ? "play" : "pause")} at {Now():F1}");+ UpdatePlayer(reveal: playing);+ }++ /// A line's time: play from there.+ void PlayFrom(double t)+ {+ if (player is null) return;+ Seek(t);+ player.Play();+ playing = true;+ playTick.Start();+ Log.Debug($"player: play from {t:F1}");+ UpdatePlayer(reveal: true);+ }++ void Seek(double t)+ {+ if (player is null) return;+ t = Math.Clamp(t, 0, Math.Max(0, Length()));+ if (opened) player.Position = TimeSpan.FromSeconds(t); else pendingSeek = t;+ UpdatePlayer();+ }++ /// Played to the end: back to the start, paused.+ void Ended()+ {+ if (player is null) return;+ player.Pause();+ player.Position = TimeSpan.Zero;+ playing = false;+ playTick.Stop();+ UpdatePlayer();+ }++ void CycleSpeed()+ {+ speed = speed == 1 ? 1.5 : speed == 1.5 ? 2 : 1;+ if (player is not null) player.SpeedRatio = speed;+ if (speedText is not null) speedText.Text = SpeedLabel();+ }++ /// The bar and the lit line follow the playhead (every 200 ms while playing).+ void UpdatePlayer() => UpdatePlayer(false);++ /// `reveal`: playing just started, so the lit line is scrolled to even if it was lit already.+ void UpdatePlayer(bool reveal)+ {+ if (player is null) return;+ var now = Now();+ var length = Length();+ // MediaEnded doesn't always come (a PC with no sound device plays on past the end).+ if (playing && opened && length > 0 && now >= length) { Ended(); return; }+ if (nowText is not null) nowText.Text = Languages.Clock(now);+ if (lengthText is not null) lengthText.Text = Languages.Clock(length);+ if (playButton is not null)+ {+ var icon = playing ? Icons.Pause : Icons.Play;+ if (playButton.Tag as string != icon)+ {+ playButton.Tag = icon;+ playButton.Content = Ui.Icon(icon, 14, Brushes.White, fill: true);+ playButton.ToolTip = playing ? L("暂停") : L("播放");+ System.Windows.Automation.AutomationProperties.SetName(playButton, playing ? L("暂停") : L("播放"));+ }+ }+ if (track is not null && played is not null && thumb is not null && track.ActualWidth > 0)+ {+ var x = track.ActualWidth * (length > 0 ? Math.Clamp(now / length, 0, 1) : 0);+ played.Width = x;+ thumb.Margin = new Thickness(Math.Max(0, Math.Min(track.ActualWidth - thumb.Width, x - thumb.Width / 2)), 0, 0, 0);+ }+ // The line being said: the last one starting by now (a little ahead, so it lights as it begins).+ var at = playing || now > 0 ? rows.FindLastIndex(r => r.t <= now + 0.2) : -1;+ if (at == lit)+ {+ if (reveal && playing && lit >= 0) KeepInView(rows[lit].row);+ return;+ }+ if (lit >= 0 && lit < rows.Count)+ {+ var (_, row, time) = rows[lit];+ row.Background = Brushes.Transparent;+ time.Foreground = Palette.TimeLink; time.FontWeight = FontWeights.Normal;+ }+ lit = at;+ if (lit < 0) return;+ var (_, r, t) = rows[lit];+ r.Background = Palette.Playing;+ t.Foreground = Palette.Live; t.FontWeight = FontWeights.SemiBold;+ if (playing) KeepInView(r);+ }++ /// Scrolls the lit line back into view when it leaves it (above, under the pinned bar, or below).+ void KeepInView(FrameworkElement row)+ {+ if (pageScroll is not { } scroll || !row.IsLoaded) return;+ var y = row.TransformToAncestor(scroll).Transform(new Point(0, 0)).Y;+ if (y >= 110 && y + row.ActualHeight <= scroll.ViewportHeight - 24) return;+ scroll.ScrollToVerticalOffset(Math.Max(0, scroll.VerticalOffset + y - scroll.ViewportHeight * 0.35));+ }++ void ClosePlayer()+ {+ playTick.Stop();+ playing = false;+ pendingSeek = null;+ if (player is not null)+ {+ player.Stop();+ player.Close();+ player = null;+ }+ playerPath = null;+ lit = -1;+ }++ /// For the debug pipe: where playback is.+ public string PlayerState() => player is null ? "none" : $"{(playing ? "playing" : "paused")} {Now():F1}/{Length():F1} x{speed} line {lit}";+ public void DebugPlay(string arg)+ {+ if (arg == "toggle") TogglePlay();+ else if (arg == "speed") CycleSpeed();+ else if (double.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var t)) PlayFrom(t);+ }+static FrameworkElement Gap(FrameworkElement e, double top) { e.Margin = new Thickness(0, top, 0, 0); return e; }static void Flash(Button b, string text)@@ -669,6 +934,9 @@ sealed class MainWindow : Windowvoid Delete(Session s){if (Dialogs.Confirm(this, L("删除这次会议?"), LF("“%@”的纪要和文字记录都会删掉,没法恢复。", SessionStore.DisplayTitle(s)), L("删除"), danger: true))+ {+ ClosePlayer(); // it holds the recording openapp.Store.Delete(s.Id);+ }}}diff --git a/windows/src/Cicada/MediaFoundation.cs b/windows/src/Cicada/MediaFoundation.csnew file mode 100644index 0000000..78bca76--- /dev/null+++ b/windows/src/Cicada/MediaFoundation.cs@@ -0,0 +1,274 @@+using System.Runtime.InteropServices;++namespace Cicada.App;++/// 保存会议录音 with Windows' own AAC encoder (Media Foundation's sink writer): no package, nothing+/// to install. The COM calls go through the vtables by slot (the interfaces are long and only a+/// few methods are used), so each `Slot` number below is that method's place in its interface.+unsafe sealed class MediaFoundationAudio : IAudioFiles+{+ // The Mac's recordings are AAC mono at ~32 kbps. Windows 11 encodes 16 kHz at 32 kbps; the+ // encoder's documentation promises only 44.1/48 kHz from 96 kbps, so a PC that refuses gets+ // those, the 16 kHz upsampled by three.+ static readonly (int Rate, uint Bytes)[] Formats = [(16000, 4000), (48000, 4000), (16000, 12000), (48000, 12000)];+ static readonly Lazy<bool> Started = new(() =>+ {+ int hr = MFStartup(0x00020070, 0);+ if (hr != 0) Log.Debug($"audio: Media Foundation unavailable 0x{hr:X8}");+ return hr == 0;+ });+ /// The format the encoder took last time, so later meetings don't try again.+ static (int Rate, uint Bytes)? chosen;++ public IAudioWriter? Open(string path)+ {+ if (!Started.Value) return null;+ foreach (var f in chosen is { } c ? new[] { c } : Formats)+ {+ try+ {+ var w = AacWriter.Create(path, f.Rate, f.Bytes);+ if (chosen is null) Log.Debug($"audio: AAC {f.Rate} Hz, {f.Bytes * 8 / 1000} kbps");+ chosen = f;+ return w;+ }+ catch (Exception e)+ {+ Log.Debug($"audio: AAC {f.Rate} Hz {f.Bytes * 8 / 1000} kbps refused 0x{e.HResult:X8}");+ try { File.Delete(path); } catch { }+ }+ }+ return null;+ }++ /// The ADTS frames into an MP4 track as they are: no re-encoding, so an hour takes a moment.+ public bool Rewrap(string from, string to, double? until)+ {+ if (!Started.Value) return false;+ try+ {+ var file = File.ReadAllBytes(from);+ if (Adts.Read(file) is not { } config) { Log.Debug("audio: rewrap found no AAC frames"); return false; }+ var frames = Adts.Frames(file);+ if (until is { } u) frames = frames.Take((int)Math.Ceiling(u * config.Rate / 1024)).ToList();+ if (frames.Count == 0) return false;+ Write(file, frames, config, to);+ return true;+ }+ catch (Exception e) { Log.Debug($"audio: rewrap failed 0x{e.HResult:X8} {e.Message}"); }+ return false;+ }++ static void Write(byte[] file, List<Adts.Frame> frames, Adts.Config config, string to)+ {+ IntPtr type = 0, writer = 0, attrs = 0;+ try+ {+ long bytes = frames.Sum(f => (long)f.Length);+ double seconds = frames.Count * 1024.0 / config.Rate;+ Check(MFCreateMediaType(out type), "type");+ AacType(type, config.Rate, (uint)(bytes / seconds), (uint)config.Channels);+ SetUInt32(type, PayloadType, 0);+ SetUInt32(type, ProfileLevel, 0x29);+ // HEAACWAVEINFO after its WAVEFORMATEX: raw frames (payload 0), then the AudioSpecificConfig.+ var info = new byte[12 + config.SpecificConfig.Length];+ info[2] = 0x29;+ config.SpecificConfig.CopyTo(info, 12);+ Check(SetBlob(type, UserData, info), "user data");+ Check(MFCreateAttributes(out attrs, 2), "attributes");+ SetGuid(attrs, ContainerType, ContainerMpeg4);+ SetUInt32(attrs, DisableThrottling, 1);+ Check(MFCreateSinkWriterFromURL(to, 0, attrs, out writer), "create");+ uint stream;+ Check(AddStream(writer, type, &stream), "add stream");+ Check(BeginWriting(writer), "begin");+ long duration = 1024L * 10_000_000 / config.Rate;+ for (int i = 0; i < frames.Count; i++)+ {+ IntPtr buffer = 0, sample = 0;+ try+ {+ var f = frames[i];+ Check(MFCreateMemoryBuffer((uint)f.Length, out buffer), "buffer");+ byte* data;+ uint max, current;+ Check(Lock(buffer, &data, &max, ¤t), "lock");+ file.AsSpan(f.Offset, f.Length).CopyTo(new Span<byte>(data, f.Length));+ Unlock(buffer);+ Check(SetCurrentLength(buffer, (uint)f.Length), "length");+ Check(MFCreateSample(out sample), "sample");+ Check(AddBuffer(sample, buffer), "add buffer");+ Check(SetSampleTime(sample, i * 1024L * 10_000_000 / config.Rate), "time");+ Check(SetSampleDuration(sample, duration), "duration");+ Check(WriteSample(writer, stream, sample), "write");+ }+ finally+ {+ if (sample != 0) Release(sample);+ if (buffer != 0) Release(buffer);+ }+ }+ Check(FinalizeWriter(writer), "finalize");+ }+ finally+ {+ foreach (var p in new[] { type, writer, attrs }) if (p != 0) Release(p);+ }+ }++ static void AacType(IntPtr t, int rate, uint bytes, uint channels = 1)+ {+ SetGuid(t, MajorType, MediaTypeAudio); SetGuid(t, Subtype, FormatAac);+ SetUInt32(t, BitsPerSample, 16); SetUInt32(t, SamplesPerSecond, (uint)rate);+ SetUInt32(t, NumChannels, channels); SetUInt32(t, AvgBytesPerSecond, bytes);+ }++ /// One meeting's ADTS file, 16 kHz mono in.+ sealed class AacWriter : IAudioWriter+ {+ IntPtr writer;+ readonly uint stream;+ readonly int rate;+ long frames;+ short previous;++ AacWriter(IntPtr writer, uint stream, int rate) { this.writer = writer; this.stream = stream; this.rate = rate; }++ public static AacWriter Create(string path, int rate, uint bytes)+ {+ IntPtr attrs = 0, output = 0, input = 0, writer = 0;+ try+ {+ Check(MFCreateAttributes(out attrs, 1), "attributes");+ SetGuid(attrs, ContainerType, ContainerAdts);+ Check(MFCreateSinkWriterFromURL(path, 0, attrs, out writer), "create");+ Check(MFCreateMediaType(out output), "output type");+ AacType(output, rate, bytes);+ uint stream;+ Check(AddStream(writer, output, &stream), "add stream");+ Check(MFCreateMediaType(out input), "input type");+ SetGuid(input, MajorType, MediaTypeAudio); SetGuid(input, Subtype, FormatPcm);+ SetUInt32(input, BitsPerSample, 16); SetUInt32(input, SamplesPerSecond, (uint)rate);+ SetUInt32(input, NumChannels, 1); SetUInt32(input, BlockAlignment, 2);+ SetUInt32(input, AvgBytesPerSecond, (uint)rate * 2);+ Check(SetInputMediaType(writer, stream, input, 0), "input");+ Check(BeginWriting(writer), "begin");+ var w = new AacWriter(writer, stream, rate);+ writer = 0;+ return w;+ }+ finally+ {+ foreach (var p in new[] { attrs, output, input, writer }) if (p != 0) Release(p);+ }+ }++ public void Write(ReadOnlySpan<short> pcm)+ {+ if (writer == 0 || pcm.IsEmpty) return;+ int factor = rate / Segmenter.Rate;+ int count = pcm.Length * factor;+ IntPtr buffer = 0, sample = 0;+ try+ {+ Check(MFCreateMemoryBuffer((uint)count * 2, out buffer), "buffer");+ byte* data;+ uint max, current;+ Check(Lock(buffer, &data, &max, ¤t), "lock");+ var o = (short*)data;+ if (factor == 1) pcm.CopyTo(new Span<short>(o, count));+ else+ // Straight lines between the 16 kHz samples: the encoder's low-pass does the rest.+ for (int i = 0, j = 0; i < pcm.Length; i++)+ {+ int a = previous, b = pcm[i];+ for (int k = 1; k <= factor; k++) o[j++] = (short)(a + (b - a) * k / factor);+ previous = pcm[i];+ }+ Unlock(buffer);+ Check(SetCurrentLength(buffer, (uint)count * 2), "length");+ Check(MFCreateSample(out sample), "sample");+ Check(AddBuffer(sample, buffer), "add buffer");+ Check(SetSampleTime(sample, frames * 10_000_000 / rate), "time");+ Check(SetSampleDuration(sample, (long)count * 10_000_000 / rate), "duration");+ Check(WriteSample(writer, stream, sample), "write");+ frames += count;+ }+ finally+ {+ if (sample != 0) Release(sample);+ if (buffer != 0) Release(buffer);+ }+ }++ public void Close()+ {+ var w = writer;+ writer = 0;+ if (w == 0) return;+ try { Check(FinalizeWriter(w), "finalize"); }+ finally { Release(w); }+ }+ }++ static void Check(int hr, string what)+ {+ if (hr < 0) throw new COMException(what, hr);+ }++ // MARK: COM by vtable slot++ static void* Slot(IntPtr p, int i) => (*(void***)p)[i];+ static uint Release(IntPtr p) => ((delegate* unmanaged[Stdcall]<IntPtr, uint>)Slot(p, 2))(p);++ // IMFAttributes (IMFMediaType and IMFSample start with it)+ static int SetBlob(IntPtr a, Guid key, byte[] blob)+ {+ fixed (byte* p = blob) return ((delegate* unmanaged[Stdcall]<IntPtr, Guid*, byte*, uint, int>)Slot(a, 26))(a, &key, p, (uint)blob.Length);+ }+ static int SetUInt32(IntPtr a, Guid key, uint v) => ((delegate* unmanaged[Stdcall]<IntPtr, Guid*, uint, int>)Slot(a, 21))(a, &key, v);+ static int SetGuid(IntPtr a, Guid key, Guid v) => ((delegate* unmanaged[Stdcall]<IntPtr, Guid*, Guid*, int>)Slot(a, 24))(a, &key, &v);++ // IMFSample+ static int SetSampleTime(IntPtr s, long t) => ((delegate* unmanaged[Stdcall]<IntPtr, long, int>)Slot(s, 36))(s, t);+ static int SetSampleDuration(IntPtr s, long d) => ((delegate* unmanaged[Stdcall]<IntPtr, long, int>)Slot(s, 38))(s, d);+ static int AddBuffer(IntPtr s, IntPtr b) => ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int>)Slot(s, 42))(s, b);++ // IMFMediaBuffer+ static int Lock(IntPtr b, byte** data, uint* max, uint* current) => ((delegate* unmanaged[Stdcall]<IntPtr, byte**, uint*, uint*, int>)Slot(b, 3))(b, data, max, current);+ static int Unlock(IntPtr b) => ((delegate* unmanaged[Stdcall]<IntPtr, int>)Slot(b, 4))(b);+ static int SetCurrentLength(IntPtr b, uint n) => ((delegate* unmanaged[Stdcall]<IntPtr, uint, int>)Slot(b, 6))(b, n);++ // IMFSinkWriter+ static int AddStream(IntPtr w, IntPtr type, uint* index) => ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, uint*, int>)Slot(w, 3))(w, type, index);+ static int SetInputMediaType(IntPtr w, uint index, IntPtr type, IntPtr parameters) => ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, IntPtr, int>)Slot(w, 4))(w, index, type, parameters);+ static int BeginWriting(IntPtr w) => ((delegate* unmanaged[Stdcall]<IntPtr, int>)Slot(w, 5))(w);+ static int WriteSample(IntPtr w, uint index, IntPtr sample) => ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, int>)Slot(w, 6))(w, index, sample);+ static int FinalizeWriter(IntPtr w) => ((delegate* unmanaged[Stdcall]<IntPtr, int>)Slot(w, 11))(w);+++ static readonly Guid MajorType = new("48eba18e-f8c9-4687-bf11-0a74c9f96a8f");+ static readonly Guid Subtype = new("f7e34c9a-42e8-4714-b74b-cb29d72c35e5");+ static readonly Guid NumChannels = new("37e48bf5-645e-4c5b-89de-ada9e29b696a");+ static readonly Guid SamplesPerSecond = new("5faeeae7-0290-4c31-9e8a-c534f68d9dba");+ static readonly Guid BitsPerSample = new("f2deb57f-40fa-4764-aa33-ed4f2d1ff669");+ static readonly Guid AvgBytesPerSecond = new("1aab75c8-cfef-451c-ab95-ac034b8e1731");+ static readonly Guid BlockAlignment = new("322de230-9eeb-43bd-ab7a-ff412251541d");+ static readonly Guid PayloadType = new("bfbabe79-7434-4d1c-94f0-72a3b9e17188");+ static readonly Guid ProfileLevel = new("7632f0e6-9538-4d61-acda-ea29c8c14456");+ static readonly Guid UserData = new("b6bc765f-4c3b-40a4-bd51-2535b66fe09d");+ static readonly Guid MediaTypeAudio = new("73647561-0000-0010-8000-00aa00389b71");+ static readonly Guid FormatPcm = new("00000001-0000-0010-8000-00aa00389b71");+ static readonly Guid FormatAac = new("00001610-0000-0010-8000-00aa00389b71");+ static readonly Guid ContainerType = new("150ff23f-4abc-478b-ac4f-e1916fba1cca");+ static readonly Guid ContainerAdts = new("132fd27d-0f02-43de-a301-38fbbbb3834e");+ static readonly Guid ContainerMpeg4 = new("dc6cd05d-b9d0-40ef-bd35-fa622c1ab28a");+ static readonly Guid DisableThrottling = new("08b845d8-2b74-4afe-9d53-be16d2d5ae4f");++ [DllImport("mfplat.dll")] static extern int MFStartup(uint version, uint flags);+ [DllImport("mfplat.dll")] static extern int MFCreateAttributes(out IntPtr attributes, uint size);+ [DllImport("mfplat.dll")] static extern int MFCreateMediaType(out IntPtr type);+ [DllImport("mfplat.dll")] static extern int MFCreateSample(out IntPtr sample);+ [DllImport("mfplat.dll")] static extern int MFCreateMemoryBuffer(uint max, out IntPtr buffer);+ [DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode)] static extern int MFCreateSinkWriterFromURL(string url, IntPtr byteStream, IntPtr attributes, out IntPtr writer);+}diff --git a/windows/src/Cicada/NotesWindow.cs b/windows/src/Cicada/NotesWindow.csindex 61f79d5..d3fffff 100644--- a/windows/src/Cicada/NotesWindow.cs+++ b/windows/src/Cicada/NotesWindow.cs@@ -568,11 +568,23 @@ sealed class NotesWindow : Window}/// One line of the transcript as on the Mac: who (in their colour) and when, the original in- /// grey, the translation in ink.- internal static FrameworkElement TranscriptRow(TranscriptLine l, string? who = null, Brush? ink = null, bool place = false)+ /// grey, the translation in ink. With `play` (a record with its recording) the time is a link+ /// that plays from there; it is tagged "time" so the player can light it.+ internal static FrameworkElement TranscriptRow(TranscriptLine l, string? who = null, Brush? ink = null, bool place = false, Action<double>? play = null){var text = new StackPanel { Margin = new Thickness(0, who is null && !place ? 0 : 6, 0, 12) };- var head = Ui.Row(8, Ui.Text(Languages.Clock(l.T), 12, Palette.Tertiary, wrap: false));+ var time = Ui.Text(Languages.Clock(l.T), 12, play is null ? Palette.Tertiary : Palette.TimeLink, wrap: false);+ if (play is not null)+ {+ time.Tag = "time";+ time.Cursor = System.Windows.Input.Cursors.Hand;+ time.ToolTip = L("从这里播放");+ time.MouseLeftButtonDown += (_, e) => { e.Handled = true; play(l.T); };+ time.MouseEnter += (_, _) => time.TextDecorations = TextDecorations.Underline;+ time.MouseLeave += (_, _) => time.TextDecorations = null;+ System.Windows.Automation.AutomationProperties.SetName(time, L("从这里播放") + " " + time.Text);+ }+ var head = Ui.Row(8, time);if (place) head.Children.Insert(0, PlaceTag(l));if (who is not null) head.Children.Insert(0, Ui.Text(who, 12, ink ?? Palette.Secondary, wrap: false));for (int i = 1; i < head.Children.Count; i++) ((FrameworkElement)head.Children[i]).Margin = new Thickness(i == 1 && place && who is not null ? 6 : 8, 0, 0, 0);diff --git a/windows/src/Cicada/SettingsWindow.cs b/windows/src/Cicada/SettingsWindow.csindex 62056d1..ed33c2b 100644--- a/windows/src/Cicada/SettingsWindow.cs+++ b/windows/src/Cicada/SettingsWindow.cs@@ -73,6 +73,7 @@ sealed class SettingsWindow : WindowSection(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("说话人识别"))),+ Card(Icons.Wave, L("保存会议录音"), L("只存在这台电脑上"), Ui.Switch(app.Settings.RecordAudio, v => { app.Settings.RecordAudio = v; Save(); }, L("保存会议录音"))),Card(Icons.Power, L("开机时启动知了"), null, Ui.Switch(AutoStart.Enabled, v => AutoStart.Enabled = v, L("开机时启动知了"))),Card(Icons.Folder, L("会议记录存放位置"), $"{Paths.Sessions} · {L("和 Mac 版格式相同")}", Ui.Button(L("打开文件夹"), () => OpenFolder(Paths.Sessions), height: 32))));// 卸载 as in Settings › Apps, with the same confirmation; only an installed copy offers it.diff --git a/windows/src/Cicada/Strings/en.lproj/Windows.strings b/windows/src/Cicada/Strings/en.lproj/Windows.stringsindex d575265..bb1a32a 100644--- a/windows/src/Cicada/Strings/en.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/en.lproj/Windows.strings@@ -319,3 +319,4 @@"例如 af_heart" = "e.g. af_heart";/* The talk key: the computer was playing through the press, so what the mic heard may be its echo. */"对方在说话时说的,没有说出去" = "Said while they were talking, so not sent";+"只存在这台电脑上" = "Stored only on this PC";diff --git a/windows/src/Cicada/Strings/ja.lproj/Windows.strings b/windows/src/Cicada/Strings/ja.lproj/Windows.stringsindex 7f2200b..c0991b7 100644--- a/windows/src/Cicada/Strings/ja.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ja.lproj/Windows.strings@@ -319,3 +319,4 @@"例如 af_heart" = "例: af_heart";/* The talk key: the computer was playing through the press, so what the mic heard may be its echo. */"对方在说话时说的,没有说出去" = "相手が話している間の発言なので、送っていません";+"只存在这台电脑上" = "このPCにのみ保存";diff --git a/windows/src/Cicada/Strings/ko.lproj/Windows.strings b/windows/src/Cicada/Strings/ko.lproj/Windows.stringsindex e2b851a..e64598e 100644--- a/windows/src/Cicada/Strings/ko.lproj/Windows.strings+++ b/windows/src/Cicada/Strings/ko.lproj/Windows.strings@@ -319,3 +319,4 @@"例如 af_heart" = "예: af_heart";/* The talk key: the computer was playing through the press, so what the mic heard may be its echo. */"对方在说话时说的,没有说出去" = "상대방이 말하는 중이라 보내지 않았어요";+"只存在这台电脑上" = "이 PC에만 저장됨";diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.csindex 55e34c3..f2eee83 100644--- a/windows/src/Cicada/Ui.cs+++ b/windows/src/Cicada/Ui.cs@@ -31,6 +31,10 @@ static class Palettepublic static readonly SolidColorBrush AccentFill = B(0xC9441D);public static readonly SolidColorBrush AccentPale = B(0xFDEBE4);public static readonly SolidColorBrush AccentText = B(0xA8370F);+ /// 回放: a line's time as a link, the line at the playhead, and the player bar's box.+ public static readonly SolidColorBrush TimeLink = B(0xB33B14);+ public static readonly SolidColorBrush Playing = B(0xFDEEE7);+ public static readonly SolidColorBrush PlayerFill = B(0xF5F6F8);public static readonly SolidColorBrush Success = B(0x0F7B3F);public static readonly SolidColorBrush Danger = B(0xC42B1C);public static readonly SolidColorBrush ErrorBg = B(0xFDECEA);@@ -64,6 +68,7 @@ static class Iconspublic const string Notes = "M5.5,2.5 H11.5 L15,6 V17.5 H5.5 Z M11.5,2.5 V6 H15 M8,10 H13 M8,13 H13";public const string Stop = "M6.5,4 H13.5 A2.5,2.5 0 0 1 16,6.5 V13.5 A2.5,2.5 0 0 1 13.5,16 H6.5 A2.5,2.5 0 0 1 4,13.5 V6.5 A2.5,2.5 0 0 1 6.5,4 Z";public const string Play = "M6.5,4.5 L15.5,10 L6.5,15.5 Z";+ public const string Pause = "M6,4.5 H8.8 V15.5 H6 Z M11.2,4.5 H14 V15.5 H11.2 Z";public const string Gear = "M12.5,10 A2.5,2.5 0 1 1 7.5,10 A2.5,2.5 0 1 1 12.5,10 Z M10,2.5 V4.5 M10,15.5 V17.5 M2.5,10 H4.5 M15.5,10 H17.5 M4.7,4.7 L6.1,6.1 M13.9,13.9 L15.3,15.3 M4.7,15.3 L6.1,13.9 M13.9,6.1 L15.3,4.7";public const string Search = "M14.5,9 A5.5,5.5 0 1 1 3.5,9 A5.5,5.5 0 1 1 14.5,9 Z M13,13 L17,17";public const string Export = "M10,3 V13 M6,7 L10,3 L14,7 M4,12 V16.5 H16 V12";diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.csindex aad3cf2..01b261b 100644--- a/windows/tests/Cicada.Tests/Program.cs+++ b/windows/tests/Cicada.Tests/Program.cs@@ -308,6 +308,127 @@ static class TestsCheck(JsonNode.DeepEquals(JsonNode.Parse(mac), JsonNode.Parse(Json.Write(s))), "written back with every key: " + Json.Write(s));}+ // MARK: 保存会议录音++ /// Records what it is given; the "file" is a list of samples, and Rewrap copies the partial file.+ sealed class FakeAudio : IAudioFiles+ {+ public readonly List<short> Samples = [];+ public bool Closed;+ public readonly List<(string from, string to, double? until)> Rewraps = [];+ public IAudioWriter? Open(string path) { File.WriteAllBytes(path, [0xFF, 0xF1]); return new Writer(this); }+ public bool Rewrap(string from, string to, double? until) { Rewraps.Add((from, to, until)); File.Copy(from, to, true); return true; }+ sealed class Writer(FakeAudio a) : IAudioWriter+ {+ public void Write(ReadOnlySpan<short> pcm) { lock (a.Samples) a.Samples.AddRange(pcm.ToArray()); }+ public void Close() => a.Closed = true;+ }+ }++ /// Loopback as it really is: sound while something plays, nothing at all in between.+ sealed class GappySource(params (double seconds, bool sound)[] parts) : IAudioSource+ {+ public event Action<short[]>? Samples;+ public event Action<string?>? Ended;+ public void Start() => Task.Run(async () =>+ {+ foreach (var (seconds, sound) in parts)+ {+ if (!sound) { await Task.Delay(TimeSpan.FromSeconds(seconds)); continue; }+ for (int i = 0; i < seconds * 10; i++) { Samples?.Invoke(Tone(0.1, 0.002)); await Task.Delay(100); }+ }+ Ended?.Invoke(null);+ });+ public void Stop() { }+ }++ public static void SilenceGoesInOnlyOnceTheStreamIsASecondBehind()+ {+ Equal(0, Recording.Behind(0.5, 0, 1600), "a packet a little late: nothing");+ Equal(0, Recording.Behind(2.0, 16000, 1600), "0.9 s behind: still nothing");+ Equal(24000, Recording.Behind(2.6, 16000, 1600), "1.5 s behind after 1.1 s of audio: 1.5 s of silence");+ Equal(0, Recording.Behind(1.0, 64000, 1600), "ahead of the clock: nothing");+ }++ public static async Task TheRecordingKeepsTheMeetingsClock()+ {+ // 0.5 s of sound, 2.5 s of nothing (loopback while the PC is silent), 0.5 s of sound.+ var fake = new Fake(_ => Reply("{}"));+ var ling = Client(fake);+ var store = new SessionStore { Audio = new FakeAudio() };+ var audio = (FakeAudio)store.Audio;+ var engine = new ListenEngine(ling, new Translator(ling), store, new NotesEngine(ling, store), new AppSettings { Target = "zh-CN", SpeakerVoices = false });+ var source = new GappySource((0.5, true), (2.5, false), (0.5, true));+ var ended = new TaskCompletionSource();+ source.Ended += _ => ended.TrySetResult();+ engine.Start(source);+ var id = engine.SessionId!;+ Check(File.Exists(Recording.Partial(Recording.SystemAudio(id))), "written as system.aac while live");+ await ended.Task;+ var wall = (DateTimeOffset.Now - store.Get(id)!.StartedAt).TotalSeconds;+ await engine.Stop();+ Check(audio.Closed, "closed when the meeting ends");+ var recorded = audio.Samples.Count / 16000.0;+ Check(recorded > wall - 1.1 && recorded < wall + 0.2, $"the recording ({recorded:F2} s) is as long as the meeting ({wall:F2} s)");++ var off = new SessionStore { Audio = new FakeAudio() };+ var quiet = new ListenEngine(ling, new Translator(ling), off, new NotesEngine(ling, off), new AppSettings { RecordAudio = false });+ quiet.Start(new GappySource((0.2, true)));+ Check(!File.Exists(Recording.Partial(Recording.SystemAudio(quiet.SessionId!))), "保存会议录音 off: no file");+ await quiet.Stop();+ }++ public static async Task EndingAMeetingFinishesItsRecording()+ {+ var audio = new FakeAudio();+ var store = new SessionStore { Audio = audio };+ var s = store.Begin(DateTimeOffset.Parse("2026-02-01T02:00:00Z"));+ store.Append(s.Id, new TranscriptLine { Id = "h1-1", Src = "hi", SrcLang = "en", DstLang = "zh-CN", T = 3 });+ var m4a = Recording.SystemAudio(s.Id);+ Directory.CreateDirectory(Path.GetDirectoryName(m4a)!);+ File.WriteAllBytes(Recording.Partial(m4a), [1]);+ store.End(s.Id, DateTimeOffset.Parse("2026-02-01T02:10:00Z"));+ Check(store.Get(s.Id)!.HasAudio, "hasAudio once a recording exists");+ for (int i = 0; i < 50 && !File.Exists(m4a); i++) await Task.Delay(20);+ Check(File.Exists(m4a) && !File.Exists(Recording.Partial(m4a)), "rewrapped into system.m4a, the partial file gone");+ Equal(600.0, audio.Rewraps[0].until, "a meeting that ended by itself is cut where it ended");+ Equal(m4a, Recording.Playable(store.Get(s.Id)!), "it plays");++ // A meeting the app didn't get to close: finished at the next launch.+ var t = store.Begin(DateTimeOffset.Parse("2026-02-02T02:00:00Z"));+ store.Append(t.Id, new TranscriptLine { Id = "h1-1", Src = "hi", SrcLang = "en", DstLang = "zh-CN" });+ store.Flush();+ File.WriteAllBytes(Recording.Partial(Recording.SystemAudio(t.Id)), [1]);+ var later = new SessionStore { Audio = audio };+ later.FinishLeftovers();+ for (int i = 0; i < 50 && !File.Exists(Recording.SystemAudio(t.Id)); i++) await Task.Delay(20);+ Check(later.Get(t.Id)!.HasAudio && File.Exists(Recording.SystemAudio(t.Id)), "a crash's recording is kept");+ Equal(null, Recording.Playable(new Session { Id = "20990101-000000" }), "no file: nothing to play");+ }++ public static void AdtsFramesAreSplitAndACutOneDropped()+ {+ // Two AAC-LC 16 kHz mono frames of 10 and 12 bytes (7-byte headers), then half a third.+ static byte[] Frame(int payload)+ {+ int length = 7 + payload;+ var f = new byte[length];+ f[0] = 0xFF; f[1] = 0xF1; f[2] = (1 << 6) | (8 << 2); f[3] = (byte)((1 << 6) | (length >> 11));+ f[4] = (byte)(length >> 3); f[5] = (byte)((length & 7) << 5 | 0x1F); f[6] = 0xFC;+ for (int i = 7; i < length; i++) f[i] = (byte)i;+ return f;+ }+ byte[] file = [.. Frame(3), .. Frame(5), .. Frame(9)[..8]];+ var config = Adts.Read(file)!;+ Equal(16000, config.Rate, "rate");+ Equal(1, config.Channels, "mono");+ Equal("14-08", BitConverter.ToString(config.SpecificConfig), "AudioSpecificConfig of AAC-LC 16 kHz mono");+ var frames = Adts.Frames(file);+ Equal(2, frames.Count, "the cut-off frame is left out");+ Equal(new Adts.Frame(7, 3), frames[0], "payload without the header");+ Equal(new Adts.Frame(17, 5), frames[1], "second frame");+ }+// MARK: 会议室public static void RoomMicSkipsTheCableAndHeadsets()