Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(linux): with third-party media formats installed, meetings are recorded and play back in the record, a click on a line's time plays from there

wquguru9492626f044a
diff --git a/linux/README.md b/linux/README.md
index d8263c9..2bef3dd 100644
--- a/linux/README.md
+++ b/linux/README.md
@@ -55,7 +55,7 @@ linux/vm/vmctl.sh shot shot.png # 截屏(QEMU,不受 Wayland
linux/scripts/build.sh && linux/vm/push.sh # 把 build/cicada-linux 和测试工具放进虚拟机的 ~/cicada-linux
```
-在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项);只有你能修的问题(key、余额、模型、地址)在顶栏图标上加橙点,纪要窗收起时每场会议发一次通知(连不上的话持续 2 分钟后才发),`hide notes` 收起纪要窗、`problem-wait <秒>|off` 缩短这 2 分钟、`state` 的 `aiProblem` 看结果。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
+在虚拟机里 `~/cicada-linux/bin/cicada --dev` 启动开发版(记录在 `~/.local/share/cicada-dev`,日志在 `~/.local/state/cicada-dev/debug.log`),再用 `scripts/cicadactl` 驱动它:`state`、`start`、`stop`、`feed <wav>`、`sample`、`view notes|subtitles`、`show records|notes|settings|onboarding`、`windows`、`quit`;结束会议用 `calls zoom=Zoom|none|real`(假装会议软件在通话)、`realcalls`、`endtimes <没人说话秒数> <倒计时> <挂断宽限>|off`、`endkeep`;纪要窗用 `notes-tab notes|transcript`、`notes-search <词>`、`notes-wide on|off`、`notes-end ask|keep|end`(结束前的确认)、`notes-status failed|invalidKey|rateLimited|idle`(看出错横幅);记录用 `rename <id> [标题]`(不给标题即恢复自动标题)、`delete <id>`;还有 `onboarding-step <0-4>`、`settings-scroll <0-1>`;AI 服务检查用 `ai-check`(现在查一次)、`ai-check-sim <原因|lowBalance|off>`(每次检查都按这个原因结束,截各状态的图)、`ask settings|fix|close`(回答开始听时的对话框)、`settings-ai`、`tray-menu`(顶栏菜单的各项);只有你能修的问题(key、余额、模型、地址)在顶栏图标上加橙点,纪要窗收起时每场会议发一次通知(连不上的话持续 2 分钟后才发),`hide notes` 收起纪要窗、`problem-wait <秒>|off` 缩短这 2 分钟、`state` 的 `aiProblem` 看结果。保存会议录音用 `codecs`(这台电脑有没有 AAC 编码器 / 解码器)、`play [秒]`、`pause`、`rate`、`playstate`(播放到哪、亮着哪一句)、`settings-general`;Ubuntu 默认没有 AAC 编码器,测录音要先在虚拟机里 `sudo apt install gstreamer1.0-libav`,测完再删掉,看默认的灰开关。`scripts/smoke.sh` 一步跑完:开窗口、放一段声音、确认 monitor 听到了。
焦点:`bin/focus_test.sh` 开一个最大化的“会议 app”(`focus_probe.py`),用 `click.py`(uinput,真实指针)点纪要窗和“字幕”链接,再在 Mac 上 `linux/vm/vmctl.sh type ok`;`/tmp/focus-probe.log` 里不能出现 `active=False`,最后一行应是 `text=…ok`。xdotool 只到 XWayland,测不了这个。
diff --git a/linux/cicada/app/debug.py b/linux/cicada/app/debug.py
index f43e17b..aee13cc 100644
--- a/linux/cicada/app/debug.py
+++ b/linux/cicada/app/debug.py
@@ -15,7 +15,9 @@ per connection, one JSON line back. Never in release builds.
pill (the records window capsule's widget sizes)
listen-source system|room|both (听哪里) | room-mic [<source>|auto] | lines [<record id>] (each line's via)
online both|no (answer 线上也有人?) | room-mic-force <source>|"" (a null sink's monitor as the room mic)
- hide notes | problem-wait <seconds>|off (how long unreachable lasts before its notification; off: 2 min)"""
+ hide notes | problem-wait <seconds>|off (how long unreachable lasts before its notification; off: 2 min)
+ codecs (AAC encoder / decoders here) | play [<seconds>] | pause | rate (next speed) | playstate (the shown record's
+ recording: state, time, length, rate, the highlighted line) | settings-general (设置 at 通用)"""
from __future__ import annotations
import os
@@ -295,6 +297,31 @@ def command(app, line: str) -> dict:
if (arg == "on") != app.speak.active:
app.toggle_speaking()
return {"ok": True, "speaking": app.speak.active}
+ if cmd == "codecs":
+ from . import media
+ return {"ok": True, **media.codecs(), "recordAudio": app.settings.recordAudio, "recording": listen.recording}
+ if cmd in ("play", "pause", "rate", "playstate"):
+ w = app.records_window
+ p = w.player if w is not None else None
+ if cmd != "playstate" and p is None:
+ return {"ok": False, "error": "no recording shown"}
+ if cmd == "play":
+ p.play_from(float(arg)) if arg else p.play()
+ elif cmd == "pause":
+ p.pause()
+ elif cmd == "rate":
+ p.next_rate()
+ hl = w._hl_row if w is not None else None
+ sid = w.selected if w is not None else None
+ s = app.store.get(sid) if sid else None
+ return {"ok": True, "record": sid, "audio": w._built_key[3] if w is not None and w._built_key else None,
+ "hasAudio": s.hasAudio if s else None, "playing": p.playing if p else None,
+ "time": round(p.time, 2) if p else None, "length": round(p.length, 2) if p else None,
+ "rate": p.rate if p else None,
+ "line": next((i for i, (_k, r) in enumerate(w._rows) if r is hl), None) if hl is not None else None}
+ if cmd == "settings-general":
+ app.show_settings(general=True)
+ return {"ok": True}
if cmd == "select":
app.show_records()
app.records_window.selected = arg
diff --git a/linux/cicada/app/main.py b/linux/cicada/app/main.py
index e75b2a3..eb2aa09 100644
--- a/linux/cicada/app/main.py
+++ b/linux/cicada/app/main.py
@@ -97,6 +97,9 @@ class Controller:
self.listen.speakers = self.speakers
self.namer = speakers.Namer(self.ling, self.store, self.changed)
self.listen.on_voice = self.namer.guess
+ # 保存会议录音: only where GStreamer can write AAC (stock Ubuntu can't, see media.py).
+ self.listen.recorder = self._recorder
+ threading.Thread(target=self._finish_recordings, name="Rewrap", daemon=True).start()
self.notes.voices = lambda: self.settings.speakerVoices
self.speak.on_change(self.changed)
self.listen.on_change(self.changed)
@@ -129,6 +132,28 @@ class Controller:
GLib.timeout_add_seconds(1, self._tick)
GLib.timeout_add_seconds(2, self._watch_end)
+ @property
+ def can_record(self) -> bool:
+ from . import media
+ return media.encoder() is not None
+
+ def _recorder(self, sid: str):
+ """The new meeting's recorder, or None (setting off, or no AAC encoder here)."""
+ from . import media
+ if not self.settings.recordAudio or media.encoder() is None:
+ return None
+ rec = media.Recorder(self.store.audio_path(sid))
+ rec.on_finished = lambda: GLib.idle_add(lambda: self.changed() and False)
+ return rec
+
+ def _finish_recordings(self) -> None:
+ """A meeting the app didn't get to close: its system.aac becomes system.m4a now (the Mac's load())."""
+ from . import media
+ for sid in self.store.unfinished_audio():
+ if media.finish(self.store.audio_path(sid)):
+ self.store.set_has_audio(sid)
+ GLib.idle_add(lambda: self.changed() and False)
+
def _tick(self) -> bool:
if self.tray is not None and self.listen.listening:
self.tray.tick()
@@ -248,8 +273,9 @@ class Controller:
self.records_window.present()
self.records_window.set_focus(None) # not the search box: its placeholder would vanish
- def show_settings(self, ai: bool = False) -> None:
- """设置; `ai`: at AI 服务 (its first section), where every AI problem is fixed."""
+ def show_settings(self, ai: bool = False, general: bool = False) -> None:
+ """设置; `ai`: at AI 服务 (its first section), where every AI problem is fixed; `general`: at 通用
+ (保存会议录音, from a record that has none)."""
if self.settings_window is None:
from .settings_window import SettingsWindow
self.settings_window = SettingsWindow(self)
@@ -261,6 +287,8 @@ class Controller:
self.settings_window.present()
if ai:
self.settings_window.scroll.get_vadjustment().set_value(0)
+ elif general:
+ self.settings_window.scroll_to_general()
# Setup (会议记录 › 还差几步 and the capsule)
diff --git a/linux/cicada/app/media.py b/linux/cicada/app/media.py
new file mode 100644
index 0000000..bda559b
--- /dev/null
+++ b/linux/cicada/app/media.py
@@ -0,0 +1,281 @@
+"""保存会议录音 and playing it back, through GStreamer (PyGObject; Gst and GstBase are the only typelibs
+stock Ubuntu has, so appsrc is fed through its action signals, not GstApp).
+
+Stock Ubuntu ships GStreamer with no AAC encoder or decoder: they come with the third-party media
+formats (gstreamer1.0-libav and the like). So recording is offered only when an encoder is there,
+and playing only when a decoder is; nothing is bundled and nothing is installed for the user. The
+file is the Mac's: AAC mono at 32 kbit/s, ADTS while recording, rewrapped into system.m4a at the end
+(core/aac.py)."""
+from __future__ import annotations
+
+import os
+import time
+
+from ..core import aac
+from ..core.audio import RATE
+from ..core.support import Log
+
+try:
+ import gi
+ gi.require_version("Gst", "1.0")
+ from gi.repository import Gst
+ Gst.init(None)
+except (ImportError, ValueError) as _e: # no GStreamer introspection: neither records nor plays
+ Gst = None
+
+ENCODERS = ("fdkaacenc", "avenc_aac", "voaacenc", "faac")
+DECODERS = ("avdec_aac", "fdkaacdec", "faad")
+_found: dict = {}
+
+
+def _has(name: str) -> bool:
+ if name not in _found:
+ _found[name] = Gst is not None and Gst.ElementFactory.find(name) is not None
+ return _found[name]
+
+
+def encoder() -> str | None:
+ """The AAC encoder to record with, None when the meeting can't be saved as AAC here."""
+ if not all(_has(e) for e in ("appsrc", "audioconvert", "audioresample", "aacparse", "mp4mux", "filesink")):
+ return None
+ return next((e for e in ENCODERS if _has(e)), None)
+
+
+def can_play() -> bool:
+ return _has("playbin") and any(_has(d) for d in DECODERS)
+
+
+def codecs() -> dict:
+ """What this computer has (debug, the log)."""
+ return {"gst": Gst is not None, "encoder": encoder(), "decoders": [d for d in DECODERS if _has(d)], "play": can_play()}
+
+
+def _make(name: str, **props):
+ e = Gst.ElementFactory.make(name, None)
+ if e is None:
+ raise RuntimeError("no element %s" % name)
+ for k, v in props.items():
+ e.set_property(k.replace("_", "-"), v)
+ return e
+
+
+def _wait(pipeline, seconds: float):
+ """Blocks until the pipeline finishes or fails: the error's text, or None."""
+ msg = pipeline.get_bus().timed_pop_filtered(int(seconds * Gst.SECOND), Gst.MessageType.EOS | Gst.MessageType.ERROR)
+ if msg is None:
+ return "timeout"
+ if msg.type == Gst.MessageType.ERROR:
+ err, _dbg = msg.parse_error()
+ return err.message
+ return None
+
+
+class Recorder:
+ """One meeting's system.aac: 16 kHz mono samples in, AAC frames out as they are encoded, written
+ unbuffered so a crash loses at most the frame being written."""
+
+ def __init__(self, path: str):
+ self.path = path
+ self.partial = aac.partial(path)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ enc = encoder()
+ p = Gst.Pipeline.new("record")
+ self.src = _make("appsrc", format=Gst.Format.TIME, is_live=False, block=False,
+ caps=Gst.Caps.from_string("audio/x-raw,format=S16LE,rate=%d,channels=1,layout=interleaved" % RATE))
+ coder = _make(enc)
+ if coder.find_property("bitrate") is not None:
+ coder.set_property("bitrate", 32000) # the Mac's AVEncoderBitRateKey
+ chain = [self.src, _make("audioconvert"), _make("audioresample"), coder, _make("aacparse"),
+ _make("capsfilter", caps=Gst.Caps.from_string("audio/mpeg,mpegversion=4,stream-format=adts")),
+ _make("filesink", location=self.partial, buffer_mode=2, sync=False, **{"async": False})]
+ for e in chain:
+ p.add(e)
+ for a, b in zip(chain, chain[1:]):
+ if not a.link(b):
+ raise RuntimeError("can't link %s to %s" % (a.get_name(), b.get_name()))
+ if p.set_state(Gst.State.PLAYING) == Gst.StateChangeReturn.FAILURE:
+ p.set_state(Gst.State.NULL)
+ raise RuntimeError("won't start")
+ self.pipeline = p
+ self.samples = 0
+ self.failed = False
+ Log.d("record: %s with %s" % (os.path.basename(os.path.dirname(path)), enc))
+
+ def write(self, samples) -> None:
+ """On the listening worker: never blocks it (appsrc queues)."""
+ if self.failed:
+ return
+ msg = self.pipeline.get_bus().pop_filtered(Gst.MessageType.ERROR)
+ if msg is not None:
+ self.failed = True
+ Log.d("record: failed %s" % msg.parse_error()[0].message)
+ return
+ data = samples.tobytes()
+ buf = Gst.Buffer.new_wrapped(data)
+ buf.pts = self.samples * Gst.SECOND // RATE
+ buf.duration = len(samples) * Gst.SECOND // RATE
+ self.samples += len(samples)
+ self.src.emit("push-buffer", buf)
+
+ def close(self) -> None:
+ """The last frames out to the file (blocks briefly)."""
+ if self.pipeline is None:
+ return
+ self.src.emit("end-of-stream")
+ why = _wait(self.pipeline, 10)
+ self.pipeline.set_state(Gst.State.NULL)
+ self.pipeline = None
+ Log.d("record: closed after %.1f s%s" % (self.samples / RATE, (" (%s)" % why) if why else ""))
+
+ def finish(self, until: float | None = None) -> None:
+ finish(self.path, until)
+ if self.on_finished is not None:
+ self.on_finished()
+
+ on_finished = None
+
+
+def finish(path: str, until: float | None = None) -> bool:
+ """system.aac → system.m4a without re-encoding (AudioFileWriter.finish), cut at `until` seconds.
+ A partial file beside an .m4a means the last rewrap was cut short: it is done again. Needs only
+ aacparse and mp4mux (plugins-good), so a stock computer can finish a recording too."""
+ src = aac.partial(path)
+ if not os.path.isfile(src) or Gst is None or not (_has("aacparse") and _has("mp4mux")):
+ return False
+ try:
+ aac.trim(src, until)
+ except OSError as e:
+ Log.d("record: trim failed %s" % type(e).__name__)
+ try:
+ os.remove(path)
+ except OSError:
+ pass
+ if os.path.getsize(src) == 0:
+ os.remove(src)
+ return False
+ p = Gst.Pipeline.new("rewrap")
+ chain = [_make("filesrc", location=src), _make("aacparse"), _make("mp4mux"), _make("filesink", location=path)]
+ for e in chain:
+ p.add(e)
+ for a, b in zip(chain, chain[1:]):
+ a.link(b)
+ p.set_state(Gst.State.PLAYING)
+ why = _wait(p, 120)
+ p.set_state(Gst.State.NULL)
+ if why:
+ Log.d("record: rewrap failed %s: %s" % (os.path.basename(os.path.dirname(path)), why))
+ try:
+ os.remove(path)
+ except OSError:
+ pass
+ return False
+ os.remove(src)
+ Log.d("record: saved %s" % os.path.basename(os.path.dirname(path)))
+ return True
+
+
+class Player:
+ """A record's system.m4a in the records window (RecordingPlayer): play / pause, seek, 1× / 1.5× / 2×
+ at the same pitch (scaletempo). Lives on the main loop: the bus is watched there."""
+
+ def __init__(self, path: str, on_change=None):
+ self.on_change = on_change
+ self.rate = 1.0
+ self.playing = False
+ self.started = False # played at least once: the line at the playhead shows from then
+ self._length = 0.0
+ self._seeking = None # (where to, when): the position reads 0 while a flushing seek settles
+ pb = _make("playbin", uri=Gst.filename_to_uri(path))
+ tempo = Gst.ElementFactory.make("scaletempo", None)
+ if tempo is not None:
+ pb.set_property("audio-filter", tempo)
+ self.pb = pb
+ bus = pb.get_bus()
+ bus.add_signal_watch()
+ bus.connect("message::eos", self._eos)
+ bus.connect("message::error", self._error)
+ pb.set_state(Gst.State.PAUSED) # prerolled: the length is known and the first play is instant
+
+ def close(self) -> None:
+ if self.pb is None:
+ return
+ self.pb.get_bus().remove_signal_watch()
+ self.pb.set_state(Gst.State.NULL)
+ self.pb = None
+ self.playing = False
+
+ @property
+ def length(self) -> float:
+ if self._length <= 0 and self.pb is not None:
+ ok, d = self.pb.query_duration(Gst.Format.TIME)
+ if ok and d > 0:
+ self._length = d / Gst.SECOND
+ return self._length
+
+ @property
+ def time(self) -> float:
+ if self.pb is None:
+ return 0.0
+ ok, t = self.pb.query_position(Gst.Format.TIME)
+ t = max(0.0, t / Gst.SECOND) if ok else 0.0
+ if self._seeking is not None:
+ to, at = self._seeking
+ if abs(t - to) > 0.5 and time.monotonic() - at < 1.5:
+ return to # not there yet: where it is going, so the line being played doesn't jump back
+ self._seeking = None
+ return t
+
+ def toggle(self) -> None:
+ if self.playing:
+ self.pause()
+ else:
+ if self.length and self.time >= self.length - 0.1:
+ self.seek(0) # at the end: from the start again
+ self.play()
+
+ def play(self) -> None:
+ if self.pb is None:
+ return
+ self.pb.set_state(Gst.State.PLAYING)
+ self.playing = self.started = True
+ self._changed()
+
+ def pause(self) -> None:
+ if self.pb is None:
+ return
+ self.pb.set_state(Gst.State.PAUSED)
+ self.playing = False
+ self._changed()
+
+ def play_from(self, t: float) -> None:
+ self.seek(t)
+ self.play()
+
+ def seek(self, t: float) -> None:
+ """Flushing and exact; at the speed chosen (a plain seek would go back to 1×)."""
+ if self.pb is None:
+ return
+ t = max(0.0, min(t, self.length or t))
+ self._seeking = (t, time.monotonic())
+ self.pb.seek(self.rate, Gst.Format.TIME, Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
+ Gst.SeekType.SET, int(t * Gst.SECOND), Gst.SeekType.NONE, -1)
+
+ def next_rate(self) -> None:
+ """1× → 1.5× → 2×."""
+ self.rate = 1.0 if self.rate >= 2 else self.rate + 0.5
+ self.seek(self.time)
+ self._changed()
+
+ def _eos(self, *_):
+ self.pb.set_state(Gst.State.PAUSED)
+ self.playing = False
+ self._changed()
+
+ def _error(self, _bus, msg):
+ Log.d("play: %s" % msg.parse_error()[0].message)
+ self.playing = False
+ self._changed()
+
+ def _changed(self) -> None:
+ if self.on_change is not None:
+ self.on_change()
diff --git a/linux/cicada/app/records_window.py b/linux/cicada/app/records_window.py
index 609fbe5..9673b11 100644
--- a/linux/cicada/app/records_window.py
+++ b/linux/cicada/app/records_window.py
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta, timezone
from gi.repository import Gdk, Gio, GLib, Gtk, Pango
-from ..core import roommic, session_store, speakers
+from ..core import aac, roommic, session_store, speakers
from ..core.strings import L, LF
from ..core.support import SOURCES, TARGETS, Log, clock
from . import ui
@@ -38,6 +38,10 @@ class RecordsWindow(Gtk.Window):
self._both = False # the shown meeting has lines I said (同声传译): rows name 你 / 对方
self._nums, self._vnums, self._shown, self._speaker_key = {}, {}, {}, None # 说话人识别 on show
self._queued = False
+ self.player = None # the shown record's recording (media.Player), while it has one to play
+ self._player_sid = None
+ self._dragging = False
+ self._hl_row = None # the transcript row at the playhead
bar = Gtk.HeaderBar()
bar.set_show_close_button(True)
@@ -125,6 +129,8 @@ class RecordsWindow(Gtk.Window):
self.connect("size-allocate", self._resized)
self.connect("key-press-event", self._key)
self._tick = GLib.timeout_add_seconds(1, self._clock)
+ # Closed: the recording stops; it is set up again when the window is next shown.
+ self.connect("hide", lambda *_: (self._unload_player(), setattr(self, "_built_key", None)))
self.fill()
def _key(self, _w, event) -> bool:
@@ -625,6 +631,7 @@ class RecordsWindow(Gtk.Window):
d = self.content
keep = self.right.get_vadjustment().get_value()
if empty or no_match:
+ self._unload_player()
ui.clear(d)
self.top_box = None
self.pinned.hide()
@@ -648,6 +655,7 @@ class RecordsWindow(Gtk.Window):
return
s = self.app.store.get(self.selected) if self.selected else None
if s is None:
+ self._unload_player()
ui.clear(d)
self.top_box = None
self.pinned.hide()
@@ -656,12 +664,26 @@ class RecordsWindow(Gtk.Window):
d.show_all()
return
live = self.app.listen.listening and self.app.listen.session_id == s.id
- key = (s.id, self.mode, live)
+ audio = self._audio_state(s, live)
+ key = (s.id, self.mode, live, audio)
if getattr(self, "_built_key", None) == key and self.columns is not None:
self._update_detail(s, live)
return
ui.clear(d)
self._built_key = key
+ self._hl_row = None
+ if audio != "ready" or self._player_sid != s.id:
+ self._unload_player()
+ if audio == "ready" and self.player is None:
+ from . import media
+ try:
+ self.player = media.Player(self.app.store.audio_path(s.id), on_change=self._player_changed)
+ self._player_sid = s.id
+ GLib.timeout_add(250, self._poll, self.player)
+ except Exception as e: # noqa: BLE001 - a file GStreamer can't open: no player, the record still shows
+ Log.d("records: can't play %s" % type(e).__name__)
+ self.player = None
+ self._playable = self.player is not None
# Title, meta, actions
top = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
@@ -678,6 +700,9 @@ class RecordsWindow(Gtk.Window):
top.pack_end(actions, False, False, 0)
d.pack_start(top, False, False, 0)
self.top_box = top
+ recording = self._audio_view(s, audio)
+ if recording is not None:
+ d.pack_start(ui.gap(recording, 14), False, False, 0)
# Notes | transcript
self.columns = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=40)
@@ -713,6 +738,11 @@ class RecordsWindow(Gtk.Window):
def _update_detail(self, s, live) -> None:
"""The same meeting changed (a new line while listening, new notes, a rename): touch only what
changed. Rebuilding a long transcript on every line froze the window for half a second."""
+ if self._audio_state(s, live) != self._built_key[3]:
+ # The recording was rewrapped (or went missing) since: the player bar and the time links change.
+ self._built_key = None
+ self.show_detail()
+ return
if (not self._both and s.sourceFile is None and any(l.speaker == "me" for l in s.lines)) or \
self._speaker_state_key(s) != self._speaker_key:
# My first sentence, or voices newly on show / renamed / merged: every row may now say
@@ -747,6 +777,169 @@ class RecordsWindow(Gtk.Window):
self._rows[i] = (k, row)
self._more_rows()
+ # The recording (保存会议录音)
+
+ def _audio_state(self, s, live):
+ """What shows under the title: "live" (it is being recorded), "ready" (a recording to play),
+ "missing" (the record says it has one, the file is gone), "none" (no recording), or None."""
+ from . import media
+ if live:
+ return "live" if self.app.listen.recording else None
+ path = self.app.store.audio_path(s.id)
+ if os.path.isfile(path):
+ # Without an AAC decoder (a record from a Mac on a stock computer) nothing true and
+ # useful can be said here: no bar.
+ return "ready" if media.can_play() else None
+ if os.path.isfile(aac.partial(path)):
+ return None # being rewrapped into system.m4a: the bar comes a moment later
+ if s.hasAudio:
+ return "missing"
+ return "none" if s.lines else None
+
+ def _audio_view(self, s, audio):
+ if audio == "live":
+ return ui.text(L("会议结束后可以回放录音"), 12, "secondary")
+ if audio == "missing":
+ return ui.text(L("找不到录音,没法播放"), 12, "secondary")
+ if audio == "none":
+ if not self.app.can_record:
+ # 保存会议录音 can't be turned on here (no AAC encoder): no link to a greyed-out switch.
+ return ui.text(L("这场会议没存录音 ·").rstrip(" ·"), 12, "secondary", wrap=False)
+ line = ui.hbox(4, ui.text(L("这场会议没存录音 ·"), 12, "secondary", wrap=False, ellipsize=False))
+ go = Gtk.Button()
+ go.add(ui.text(L("保存会议录音"), 12, "link", wrap=False, ellipsize=False))
+ go.set_relief(Gtk.ReliefStyle.NONE)
+ ui.classes(go, "timelink")
+ go.connect("clicked", lambda *_: self.app.show_settings(general=True))
+ line.pack_start(go, False, False, 0)
+ return line
+ if audio == "ready" and self.player is not None:
+ return self._player_bar()
+ return None
+
+ def _player_bar(self) -> Gtk.Widget:
+ """Play / pause, where in the meeting, and the speed (RecordingPlayerBar), in a soft box."""
+ p = self.player
+ self._pb_icon = ui.icon("media-playback-start-symbolic", 13)
+ play = Gtk.Button()
+ play.add(self._pb_icon)
+ ui.classes(play, "playround")
+ play.set_valign(Gtk.Align.CENTER)
+ play.connect("clicked", lambda *_: self.player is not None and self.player.toggle())
+ self._pb_play = play
+ self._pb_time = ui.classes(ui.text(clock(0), 12, "secondary", wrap=False, ellipsize=False), "tnum")
+ self._pb_len = ui.classes(ui.text(clock(p.length), 12, "secondary", wrap=False, ellipsize=False), "tnum")
+ scale = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL, 0, max(p.length, 1), 0.1)
+ scale.set_draw_value(False)
+ scale.set_valign(Gtk.Align.CENTER)
+ ui.classes(scale, "playerscale")
+ scale.connect("button-press-event", lambda *_: setattr(self, "_dragging", True) or False)
+
+ def released(w, _e):
+ self._dragging = False
+ if self.player is not None:
+ self.player.seek(w.get_value())
+ return False
+ scale.connect("button-release-event", released)
+
+ def moved(_w, _scroll, value):
+ ui.retext(self._pb_time, clock(max(0, value)))
+ if not self._dragging and self.player is not None:
+ self.player.seek(value) # the keyboard
+ return False
+ scale.connect("change-value", moved)
+ self._pb_scale = scale
+ rate = Gtk.Button()
+ self._pb_rate = ui.text("1×", 11, "secondary", bold=True, wrap=False, ellipsize=False)
+ rate.add(self._pb_rate)
+ ui.classes(rate, "ratebtn")
+ rate.set_valign(Gtk.Align.CENTER)
+ rate.set_tooltip_text(L("播放速度"))
+ rate.connect("clicked", lambda *_: self.player is not None and self.player.next_rate())
+ row = ui.hbox(12, play, self._pb_time)
+ row.pack_start(scale, True, True, 0)
+ row.pack_start(self._pb_len, False, False, 0)
+ row.pack_start(rate, False, False, 0)
+ self._player_changed()
+ return ui.panel(ui.pad(row, 8, 14, 8, 10), "playerbar")
+
+ def _player_changed(self) -> None:
+ p = self.player
+ if p is None or getattr(self, "_pb_play", None) is None:
+ return
+ self._pb_icon.set_from_icon_name("media-playback-pause-symbolic" if p.playing else "media-playback-start-symbolic",
+ Gtk.IconSize.BUTTON)
+ tip = L("暂停") if p.playing else L("播放")
+ self._pb_play.set_tooltip_text(tip)
+ self._pb_play.get_accessible().set_name(tip)
+ ui.retext(self._pb_rate, {1.0: "1×", 1.5: "1.5×"}.get(p.rate, "2×"))
+
+ def _unload_player(self) -> None:
+ if self.player is not None:
+ self.player.close()
+ self.player = None
+ self._player_sid = None
+ self._pb_play = None
+ self._hl_row = None
+
+ def _poll(self, player) -> bool:
+ """Four times a second while a recording is loaded: the time, the bar, and the line being played."""
+ if player is not self.player:
+ return False
+ if getattr(self, "_pb_play", None) is None or not self.get_visible():
+ return True
+ t, length = player.time, player.length
+ ui.retext(self._pb_len, clock(length))
+ if self._pb_scale.get_adjustment().get_upper() != max(length, 1):
+ self._pb_scale.set_range(0, max(length, 1))
+ if not self._dragging:
+ ui.retext(self._pb_time, clock(t))
+ self._pb_scale.set_value(min(t, max(length, 1)))
+ self._player_changed()
+ if player.started:
+ self._highlight(t, follow=player.playing)
+ return True
+
+ def _highlight(self, now: float, follow: bool) -> None:
+ """The last line that began by now (a little ahead, so it lights as it starts) in the accent;
+ while playing, scrolled into view when it isn't."""
+ s = self.app.store.get(self._player_sid) if self._player_sid else None
+ if s is None:
+ return
+ idx = -1
+ for i, l in enumerate(s.lines):
+ if l.t <= now + 0.2:
+ idx = i
+ else:
+ break
+ row = self._rows[idx][1] if 0 <= idx < len(self._rows) else None
+ if row is self._hl_row:
+ return
+ old, self._hl_row = self._hl_row, row
+ for r, on in ((old, False), (row, True)):
+ if r is None or r.get_parent() is None: # a row rebuilt since (its line changed) is gone
+ continue
+ ctx = r.get_style_context()
+ ctx.add_class("playing") if on else ctx.remove_class("playing")
+ label = r.time_label
+ label.get_style_context().remove_class("link" if on else "accent")
+ label.get_style_context().add_class("accent" if on else "link")
+ size, lang, _bold = label.cicada_format
+ label.cicada_format = (size, lang, on)
+ ui.retext(label, label.get_text())
+ if row is not None and follow:
+ self._reveal(row)
+
+ def _reveal(self, row) -> None:
+ pos = row.translate_coordinates(self.content, 0, 0)
+ if pos is None:
+ return
+ adj = self.right.get_vadjustment()
+ y, h = pos[1], row.get_allocated_height()
+ top = adj.get_value() + (self.pinned.get_allocated_height() if self.pinned.get_visible() else 0)
+ if y < top or y + h > adj.get_value() + adj.get_page_size():
+ adj.set_value(max(0, min(y - adj.get_page_size() / 3, adj.get_upper() - adj.get_page_size())))
+
def _more_menu(self, s) -> Gtk.MenuButton:
"""The record as it is when pressed: 恢复自动标题 only for a renamed meeting the notes have
named, 删除 off for the live one (the Mac's context menu). The items stay; a menu filled
@@ -1048,9 +1241,19 @@ class RecordsWindow(Gtk.Window):
row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
t = ui.text(clock(l.t), 11, "link", wrap=False, ellipsize=False) # times in the logo's orange ink
t.set_size_request(44, -1)
- t.set_valign(Gtk.Align.START)
- t.set_margin_top(2)
- row.pack_start(t, False, False, 0)
+ time_widget = t
+ if getattr(self, "_playable", False):
+ # With a recording, a time plays from that line (the Mac's line times).
+ time_widget = Gtk.Button()
+ time_widget.add(t)
+ time_widget.set_relief(Gtk.ReliefStyle.NONE)
+ ui.classes(time_widget, "timelink")
+ time_widget.set_tooltip_text(L("播放"))
+ time_widget.connect("clicked", lambda *_: self.player is not None and self.player.play_from(l.t))
+ time_widget.set_valign(Gtk.Align.START)
+ time_widget.set_halign(Gtk.Align.START)
+ time_widget.set_margin_top(2)
+ row.pack_start(time_widget, False, False, 0)
texts = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
# Whose it is, where the speaker changes (as chat apps do): with voices told apart, or in a
# meeting I spoke in through 同声传译.
@@ -1066,7 +1269,9 @@ class RecordsWindow(Gtk.Window):
texts.pack_start(ui.text(l.src, 12, "tertiary", selectable=True, width_chars=46, lang=l.srcLang), False, False, 0)
row.pack_start(texts, True, True, 0)
ui.pad(row, 9, 0, 9, 0)
- return self._row_key(l, start), ui.panel(row, "transcript-row")
+ panel = ui.panel(row, "transcript-row")
+ panel.time_label = t
+ return self._row_key(l, start), panel
def _starts(self, lines) -> set:
"""Lines whose speaker label shows: a change of speaker, or in 电脑和会议室 of place too."""
diff --git a/linux/cicada/app/settings_window.py b/linux/cicada/app/settings_window.py
index a486248..815f3a0 100644
--- a/linux/cicada/app/settings_window.py
+++ b/linux/cicada/app/settings_window.py
@@ -200,10 +200,13 @@ class SettingsWindow(Gtk.Window):
page.pack_start(self._group(L("正在听时"), ui.boxed([
ui.prow(L("悬浮窗"), ui.segmented([("notes", L("实时纪要")), ("subtitles", L("字幕条"))], s.view, app.set_view)),
ui.prow(L("登录时打开"), switch, L("登录后在顶栏待命")),
- self._voices_row(),
self._shortcut_row(),
warn_row])), False, False, 0)
+ # 通用, the Mac's records section: what each meeting keeps.
+ self.general = self._group(L("通用"), ui.boxed([self._record_row(), self._voices_row()]))
+ page.pack_start(self.general, False, False, 0)
+
room_group, room_combos = self._room_group()
page.pack_start(room_group, False, False, 0)
combos += room_combos
@@ -311,6 +314,37 @@ class SettingsWindow(Gtk.Window):
button.set_no_show_all(True)
return ui.prow(title, box, L("在任何窗口里都能用"))
+ def _record_row(self) -> Gtk.Widget:
+ """保存会议录音: on by default, as on the Mac; greyed out, saying why, without an AAC encoder."""
+ app = self.app
+ sw = Gtk.Switch()
+ sw.set_valign(Gtk.Align.CENTER)
+ ok = app.can_record
+ sw.set_active(ok and app.settings.recordAudio)
+ sw.set_sensitive(ok)
+
+ def toggled(w, _p):
+ if not ok:
+ return
+ app.settings.recordAudio = w.get_active()
+ app.settings.save()
+ app.settings_changed()
+ sw.connect("notify::active", toggled)
+ return ui.prow(L("保存会议录音"), sw, L("只存在这台电脑上") if ok else L("这台电脑缺少 AAC 编码器,装上“第三方媒体格式”后可用"))
+
+ def scroll_to_general(self) -> None:
+ """Brings 通用 into view (the records window's 保存会议录音 link), once it is laid out."""
+ def go():
+ # In the page's own coordinates (the viewport's are shifted by the current scroll).
+ pos = self.general.translate_coordinates(self.scroll.get_child().get_child(), 0, 0)
+ if pos is not None:
+ self.scroll.get_vadjustment().set_value(max(0, pos[1] - 8))
+ return False
+ # A window just shown isn't laid out yet, and its show handlers then hide rows above 通用: once
+ # it has a size, and again once those are gone.
+ GLib.timeout_add(150, go)
+ GLib.timeout_add(500, go)
+
def _voices_row(self) -> Gtk.Widget:
"""说话人识别: on by default, as on the Mac; off when this build has no voiceprint library."""
app = self.app
diff --git a/linux/cicada/app/ui.py b/linux/cicada/app/ui.py
index fff262f..0c09858 100644
--- a/linux/cicada/app/ui.py
+++ b/linux/cicada/app/ui.py
@@ -203,6 +203,22 @@ button.iconbtn.on { background-color: #F3F4F6; color: #15171C; }
.sidebar list row:hover { background-color: #ECEEF1; }
.group-label { font-weight: 700; color: #6B7080; }
.transcript-row { border-top: 1px solid #EEF0F3; }
+.transcript-row.playing { background-color: #FDEEE7; }
+button.timelink { background-image: none; background-color: transparent; border: none; box-shadow: none; padding: 0; min-height: 0; min-width: 0; }
+button.timelink:hover label { text-decoration-line: underline; }
+
+/* The recording's player bar (RecordingPlayerBar): a soft box, a round ink play button, the played part in the accent. */
+.playerbar { background-color: #F5F6F8; border-radius: 10px; }
+button.playround { background-image: none; background-color: #15171C; border: none; box-shadow: none; border-radius: 16px; min-width: 32px; min-height: 32px; padding: 0; }
+button.playround:hover { background-color: #2A2D34; }
+button.playround image { color: #FFFFFF; }
+button.ratebtn { background-image: none; background-color: #FFFFFF; border: none; box-shadow: none; border-radius: 6px; min-height: 0; min-width: 0; padding: 2px 7px; }
+button.ratebtn:hover { background-color: #ECEEF1; }
+scale.playerscale { padding: 0; margin: 0; }
+scale.playerscale trough { background-image: none; background-color: #E2E4E9; border: none; box-shadow: none; border-radius: 2px; min-height: 4px; }
+scale.playerscale highlight { background-image: none; background-color: #E8552B; border: none; border-radius: 2px; min-height: 4px; }
+scale.playerscale slider { background-image: none; background-color: #FFFFFF; border: 1px solid #D5D8DE; box-shadow: 0 1px 2px rgba(0,0,0,0.18); border-radius: 7px; min-width: 12px; min-height: 12px; margin: -5px 0; }
+scale.playerscale slider:hover { background-color: #FFFFFF; border-color: #B9BDC6; }
.spk1 { color: #0F7B6C; } .spk2 { color: #7A4CC2; } .spk3 { color: #B03A7A; } .spk4 { color: #8A5A00; }
button.spkchip { background-image: none; background-color: #F2F3F5; border: none; box-shadow: none; border-radius: 11px; padding: 0 9px; min-height: 22px; }
button.spkchip:hover { background-color: #E8EAEE; }
diff --git a/linux/cicada/core/aac.py b/linux/cicada/core/aac.py
new file mode 100644
index 0000000..f1d91d6
--- /dev/null
+++ b/linux/cicada/core/aac.py
@@ -0,0 +1,58 @@
+"""The meeting's recording, as on the Mac (AudioFiles.swift): AAC written as ADTS (`system.aac`) while
+the meeting runs, which stays readable up to the last frame if the app is killed, then rewrapped into
+`system.m4a` without re-encoding once it ends (or at the next launch). The GStreamer side is
+app/media.py; this is the part that needs no GStreamer, so it tests on the Mac."""
+from __future__ import annotations
+
+import os
+
+SAMPLES_PER_FRAME = 1024 # AAC-LC
+_RATES = (96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350)
+
+
+def partial(path: str) -> str:
+ """system.m4a → system.aac (AudioFileWriter.partial)."""
+ return os.path.splitext(path)[0] + ".aac"
+
+
+def frames(data: bytes):
+ """(offset, length, sample rate) of each whole ADTS frame; stops at the first damaged or cut one
+ (a meeting the app didn't get to close ends mid-frame)."""
+ i = 0
+ n = len(data)
+ while i + 7 <= n:
+ if data[i] != 0xFF or (data[i + 1] & 0xF6) != 0xF0:
+ return
+ rate_index = (data[i + 2] >> 2) & 0x0F
+ length = ((data[i + 3] & 0x03) << 11) | (data[i + 4] << 3) | (data[i + 5] >> 5)
+ if length < 7 or i + length > n or rate_index >= len(_RATES):
+ return
+ yield i, length, _RATES[rate_index]
+ i += length
+
+
+def seconds(data: bytes) -> float:
+ return sum(SAMPLES_PER_FRAME / rate for _o, _l, rate in frames(data))
+
+
+def cut(data: bytes, until: float | None) -> bytes:
+ """The whole frames up to `until` seconds (all of them for None): the silent tail of a meeting that
+ ended by itself goes, as the Mac's export timeRange cuts it, and a torn last frame always goes."""
+ end = 0
+ t = 0.0
+ for off, length, rate in frames(data):
+ if until is not None and t >= until:
+ break
+ end = off + length
+ t += SAMPLES_PER_FRAME / rate
+ return data[:end]
+
+
+def trim(path: str, until: float | None) -> None:
+ """Cuts the ADTS file at `path` in place (see cut)."""
+ with open(path, "rb") as f:
+ data = f.read()
+ kept = cut(data, until)
+ if len(kept) != len(data):
+ with open(path, "wb") as f:
+ f.write(kept)
diff --git a/linux/cicada/core/listen.py b/linux/cicada/core/listen.py
index 287cc0b..0ac1713 100644
--- a/linux/cicada/core/listen.py
+++ b/linux/cicada/core/listen.py
@@ -75,6 +75,11 @@ class ListenEngine:
self._listeners = []
self.listening = False
self.session_id = None
+ # 保存会议录音: `recorder(sid)` gives the meeting's recorder (write(samples), close(), finish(until))
+ # or None; set by the app when GStreamer can encode AAC. What the main lane hears is written,
+ # buffer for buffer, so the file's clock is the lines' clock (t counts the samples heard).
+ self.recorder = None
+ self._recording = None
self.source_kind = None # what this meeting is heard from ("system", "room", "file")
self.problem = None # the last error worth showing, cleared by the next good reply
# What kind of problem, for a state the UI can draw: "key", "busy", "network", "source".
@@ -170,6 +175,11 @@ class ListenEngine:
def _lanes(self) -> list:
return [self._main] + ([self._room] if self._room is not None else [])
+ @property
+ def recording(self) -> bool:
+ """This meeting is being recorded (保存会议录音 was on and AAC could be written when it began)."""
+ return self.listening and self._recording is not None
+
@property
def hears_room_too(self) -> bool:
"""电脑和会议室: the room side is running."""
@@ -194,6 +204,12 @@ class ListenEngine:
self.notes.begin(session.id)
if self.speakers is not None:
self.speakers.reset()
+ self._recording = None
+ if self.recorder is not None:
+ try:
+ self._recording = self.recorder(session.id)
+ except Exception as e: # noqa: BLE001 - a recording that can't start never stops listening
+ Log.d("listen: no recording (%s)" % type(e).__name__)
# Listening before the source starts: a source that fails at once calls on_ended → stop(),
# which must see this meeting as running to end it.
self.listening = True
@@ -220,6 +236,9 @@ class ListenEngine:
if lane.muted:
# Silence rather than nothing keeps the segmenter's clock in step.
buf = array("h", bytes(len(buf) * 2))
+ rec = self._recording
+ if rec is not None and lane is self._main:
+ rec.write(buf)
now = time.monotonic()
if lane is not self._main and self.gated:
# What the mic really hears, for EchoGate's measurement, before any silencing.
@@ -330,9 +349,17 @@ class ListenEngine:
self._room = None
self.gated = False
sid = self.session_id
+ rec, self._recording = self._recording, None
+ if rec is not None:
+ rec.close() # every buffer the lane heard is in system.aac now
if sid is None:
return
self.store.end(sid, ended_at)
+ s = self.store.get(sid)
+ if rec is not None and s is not None:
+ # Into system.m4a off this thread; a meeting that ended by itself loses its silent tail.
+ until = s.duration if ended_at is not None else None
+ self._pool.submit(rec.finish, until)
Log.d("listen: stopped %s, %d lines" % (sid, self._line_count))
self._changed()
self._pool.submit(self.notes.finish)
diff --git a/linux/cicada/core/session_store.py b/linux/cicada/core/session_store.py
index a160a4c..168567d 100644
--- a/linux/cicada/core/session_store.py
+++ b/linux/cicada/core/session_store.py
@@ -8,7 +8,7 @@ import shutil
import threading
from datetime import datetime, timezone
-from . import speakers, strings
+from . import aac, speakers, strings
from .models import Session, now
from .support import Log, Paths, clock
@@ -43,6 +43,28 @@ class SessionStore:
def _folder(self, sid: str) -> str:
return os.path.join(Paths.sessions(), sid)
+ def audio_path(self, sid: str) -> str:
+ """What was heard, as on the Mac: system.m4a in the meeting's folder (system.aac while it is
+ being recorded, see aac.py)."""
+ return os.path.join(self._folder(sid), "system.m4a")
+
+ def unfinished_audio(self) -> list:
+ """Meetings whose recording is still the partial file (the app quit mid-meeting, or before
+ rewrapping it): their ids, to finish at launch as the Mac's load() does."""
+ with self._gate:
+ out = []
+ for s in self._sessions.values():
+ if s.id != self.live and os.path.isfile(aac.partial(self.audio_path(s.id))):
+ out.append(s.id)
+ return out
+
+ def set_has_audio(self, sid: str) -> None:
+ with self._gate:
+ s = self._sessions.get(sid)
+ if s is None or s.hasAudio:
+ return
+ self._mutate(sid, lambda s: setattr(s, "hasAudio", True))
+
def _load(self) -> None:
root = Paths.sessions()
if not os.path.isdir(root):
@@ -224,6 +246,9 @@ class SessionStore:
return
s.endedAt = max(ended_at, s.startedAt) if ended_at is not None else now()
empty = not s.lines
+ # The recording is rewrapped into system.m4a afterwards: either file means it has one.
+ path = self.audio_path(sid)
+ s.hasAudio = os.path.isfile(path) or (os.path.isfile(aac.partial(path)) and os.path.getsize(aac.partial(path)) > 0)
if empty:
self.delete(sid)
else:
diff --git a/linux/cicada/core/settings.py b/linux/cicada/core/settings.py
index 81ee64c..3eaeefa 100644
--- a/linux/cicada/core/settings.py
+++ b/linux/cicada/core/settings.py
@@ -36,6 +36,8 @@ class AppSettings:
"trayHintShown": False, # 知了还在顶栏, said once after the records window is first closed
"uiLanguage": "system", # "system", "zh-Hans", "en", "ja" or "ko"
# 同声传译: what I say is interpreted and spoken into 知了 麦克风 (the Mac's speakEnabled etc.).
+ # 保存会议录音 (the Mac's recordAudio): system.m4a beside session.json, when GStreamer has an AAC encoder.
+ "recordAudio": True,
"speakerVoices": True, # 说话人识别: tell the other side's voices apart (说话人 1、2…), as on the Mac
"speakEnabled": False,
"speakFrom": "system", # the language I speak; "system" = the subtitles' language
diff --git a/linux/scripts/cicadactl b/linux/scripts/cicadactl
index c54b867..c6e663c 100755
--- a/linux/scripts/cicadactl
+++ b/linux/scripts/cicadactl
@@ -4,6 +4,7 @@
target <code> | key-reload | windows | quit
calls <program=name,…>|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep
notes-tab notes|transcript | notes-search <text> | notes-wide on|off | onboarding-step <n> | settings-scroll <0-1>
+ codecs | play [<seconds>] | pause | rate | playstate | settings-general (保存会议录音 and its player)
Run it inside the Linux session (linux/vm/vmctl.sh ssh does that for the test VM)."""
import os
import socket
diff --git a/linux/strings/en.lproj/Linux.strings b/linux/strings/en.lproj/Linux.strings
index e534473..d41139b 100644
--- a/linux/strings/en.lproj/Linux.strings
+++ b/linux/strings/en.lproj/Linux.strings
@@ -198,3 +198,9 @@
"没填,同声传译用不了" = "Not set: no voice for interpreting";
"填上听的模型" = "Add a listening model";
"本机和局域网服务可不填" = "Optional on this computer or your local network";
+/* 保存会议录音 and the recording's player (media.py, records_window.py). */
+"会议结束后可以回放录音" = "The recording plays back once the meeting ends";
+"找不到录音,没法播放" = "Can't find the recording to play";
+"这场会议没存录音 ·" = "No recording of this meeting ·";
+"只存在这台电脑上" = "Kept only on this computer";
+"这台电脑缺少 AAC 编码器,装上“第三方媒体格式”后可用" = "This computer has no AAC encoder. Available once third-party media formats are installed";
diff --git a/linux/strings/ja.lproj/Linux.strings b/linux/strings/ja.lproj/Linux.strings
index e8d6f8e..7f4fbb6 100644
--- a/linux/strings/ja.lproj/Linux.strings
+++ b/linux/strings/ja.lproj/Linux.strings
@@ -198,3 +198,9 @@
"没填,同声传译用不了" = "未設定:同時通訳は話せません";
"填上听的模型" = "聞き取りモデルを入力";
"本机和局域网服务可不填" = "このコンピュータやローカルネットワークでは省略可";
+/* 保存会议录音 and the recording's player (media.py, records_window.py). */
+"会议结束后可以回放录音" = "録音は会議が終わると再生できます";
+"找不到录音,没法播放" = "録音が見つからず再生できません";
+"这场会议没存录音 ·" = "この会議の録音はありません ·";
+"只存在这台电脑上" = "このコンピュータにのみ保存";
+"这台电脑缺少 AAC 编码器,装上“第三方媒体格式”后可用" = "このコンピュータには AAC エンコーダーがありません。サードパーティのメディア形式を入れると使えます";
diff --git a/linux/strings/ko.lproj/Linux.strings b/linux/strings/ko.lproj/Linux.strings
index 79c3ce3..a3b299e 100644
--- a/linux/strings/ko.lproj/Linux.strings
+++ b/linux/strings/ko.lproj/Linux.strings
@@ -198,3 +198,9 @@
"没填,同声传译用不了" = "설정 안 함: 동시통역 음성을 낼 수 없음";
"填上听的模型" = "듣기 모델을 입력하세요";
"本机和局域网服务可不填" = "이 컴퓨터나 로컬 네트워크에서는 생략 가능";
+/* 保存会议录音 and the recording's player (media.py, records_window.py). */
+"会议结束后可以回放录音" = "회의가 끝나면 녹음을 다시 들을 수 있음";
+"找不到录音,没法播放" = "녹음이 없어 재생할 수 없음";
+"这场会议没存录音 ·" = "이 회의는 녹음이 없음 ·";
+"只存在这台电脑上" = "이 컴퓨터에만 저장됨";
+"这台电脑缺少 AAC 编码器,装上“第三方媒体格式”后可用" = "이 컴퓨터에는 AAC 인코더가 없음. 서드파티 미디어 형식을 설치하면 사용 가능";
diff --git a/linux/tests/test_recording.py b/linux/tests/test_recording.py
new file mode 100644
index 0000000..35267e9
--- /dev/null
+++ b/linux/tests/test_recording.py
@@ -0,0 +1,148 @@
+"""保存会议录音's parts that need no GStreamer: the ADTS file (core/aac.py), the record's hasAudio, and
+the listening engine handing the recorder every sample the lines are timed by."""
+from __future__ import annotations
+
+import os
+import sys
+import threading
+import time
+import unittest
+from datetime import datetime, timedelta, timezone
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+sys.path.insert(0, HERE)
+
+import test_core as tc # noqa: E402 - its helpers; a module import, so its tests aren't collected twice
+from cicada.core import aac # noqa: E402
+from cicada.core.audio import RATE, PcmAudioSource # noqa: E402
+from cicada.core.listen import ListenEngine # noqa: E402
+from cicada.core.models import TranscriptLine # noqa: E402
+from cicada.core.notes import NotesEngine # noqa: E402
+from cicada.core.session_store import SessionStore # noqa: E402
+from cicada.core.settings import AppSettings # noqa: E402
+from cicada.core.translator import Translator # noqa: E402
+
+
+def adts(n: int, rate_index: int = 8, body: int = 20) -> bytes:
+ """n ADTS frames (16 kHz by default) with `body` bytes each."""
+ length = 7 + body
+ head = bytes([0xFF, 0xF1, 0x40 | (rate_index << 2), 0x40 | ((length >> 11) & 0x03),
+ (length >> 3) & 0xFF, ((length & 0x07) << 5) | 0x1F, 0xFC])
+ return (head + bytes(body)) * n
+
+
+class Adts(unittest.TestCase):
+ def test_reads_frames_and_their_length(self):
+ data = adts(250)
+ self.assertEqual(250, len(list(aac.frames(data))))
+ self.assertAlmostEqual(250 * 1024 / 16000, aac.seconds(data))
+
+ def test_a_torn_last_frame_goes(self):
+ data = adts(10) + adts(1)[:12] # killed mid-write
+ self.assertEqual(adts(10), aac.cut(data, None))
+
+ def test_cuts_at_the_meetings_end(self):
+ data = adts(100) # 6.4 s
+ kept = aac.cut(data, 3.0)
+ self.assertAlmostEqual(3.008, aac.seconds(kept), places=3) # whole frames, up to the first one past 3 s
+ self.assertEqual(data, aac.cut(data, 60))
+
+ def test_partial_name(self):
+ self.assertEqual("/x/20261106-101010/system.aac", aac.partial("/x/20261106-101010/system.m4a"))
+
+
+class HasAudio(tc.Base):
+ def test_a_meeting_with_a_recording_says_so(self):
+ store = SessionStore()
+ s = store.begin(datetime(2026, 1, 1, 2, tzinfo=timezone.utc))
+ store.append(s.id, TranscriptLine(id="h1-1", src="hi", srcLang="en", dstLang="zh-CN"))
+ os.makedirs(os.path.dirname(store.audio_path(s.id)), exist_ok=True)
+ with open(aac.partial(store.audio_path(s.id)), "wb") as f:
+ f.write(adts(5))
+ store.end(s.id)
+ self.assertTrue(store.get(s.id).hasAudio)
+ with open(os.path.join(os.path.dirname(store.audio_path(s.id)), "session.json"), encoding="utf-8") as f:
+ self.assertIn('"hasAudio" : true', f.read())
+ # The app quit before rewrapping: the next launch finds it.
+ self.assertEqual([s.id], SessionStore().unfinished_audio())
+
+ def test_without_one_it_says_none(self):
+ store = SessionStore()
+ s = store.begin(datetime(2026, 1, 1, 2, tzinfo=timezone.utc))
+ store.append(s.id, TranscriptLine(id="h1-1", src="hi", srcLang="en", dstLang="zh-CN"))
+ store.end(s.id)
+ self.assertFalse(store.get(s.id).hasAudio)
+ self.assertEqual([], store.unfinished_audio())
+
+
+class FakeRecorder:
+ def __init__(self):
+ self.samples = 0
+ self.closed = False
+ self.finished = threading.Event()
+ self.until = "unset"
+
+ def write(self, buf):
+ assert not self.closed
+ self.samples += len(buf)
+
+ def close(self):
+ self.closed = True
+
+ def finish(self, until):
+ self.until = until
+ self.finished.set()
+
+
+class Recording(tc.Base):
+ def engine(self):
+ ling = tc.client(tc.Fake(lambda body: tc.reply("LANG: en\nORIGINAL: Hello.\nTRANSLATION: 你好。")
+ if "Ming-3.0-audio-flash" in body else tc.reply("{}")))
+ tc.LingClient.spacing = 0.05
+ store = SessionStore()
+ return store, ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target="zh-CN"))
+
+ def run_meeting(self, engine, ended_at=None):
+ rec = FakeRecorder()
+ engine.recorder = lambda sid: rec
+ src = PcmAudioSource(lambda: tc.concat(tc.tone(1.0), tc.silence(1.5)), speed=0)
+ done = threading.Event()
+ src.on_ended = lambda why: done.set()
+ engine.start(src, "file")
+ self.assertTrue(engine.recording)
+ done.wait(10)
+ time.sleep(0.5)
+ heard = engine.heard_seconds
+ engine.stop(ended_at)
+ return rec, heard
+
+ def test_every_sample_heard_is_written_then_rewrapped(self):
+ store, engine = self.engine()
+ rec, heard = self.run_meeting(engine)
+ self.assertTrue(rec.closed)
+ # The lines' clock is the samples the lane heard: the file holds exactly those.
+ self.assertEqual(round(heard * RATE), rec.samples)
+ self.assertTrue(rec.finished.wait(5))
+ self.assertIsNone(rec.until)
+ self.assertFalse(engine.recording)
+
+ def test_a_meeting_that_ended_by_itself_is_cut_there(self):
+ store, engine = self.engine()
+ rec, _ = self.run_meeting(engine, ended_at=datetime.now(timezone.utc) + timedelta(seconds=-0.5))
+ self.assertTrue(rec.finished.wait(5))
+ s = store.get(engine.session_id)
+ self.assertIsNotNone(s, "a line was heard, so the meeting is kept")
+ self.assertAlmostEqual(s.duration, rec.until, places=3)
+
+ def test_no_recorder_no_recording(self):
+ _store, engine = self.engine()
+ engine.recorder = lambda sid: None
+ src = PcmAudioSource(lambda: tc.silence(0.3), speed=0)
+ engine.start(src, "file")
+ self.assertFalse(engine.recording)
+ engine.stop()
+
+
+if __name__ == "__main__":
+ unittest.main()