Push-to-talk key
diff --git a/app/renderer/js/app.js b/app/renderer/js/app.js
index 9b2bd41..b5c8b8b 100644
--- a/app/renderer/js/app.js
+++ b/app/renderer/js/app.js
@@ -67,17 +67,22 @@ function onCoreStatus(status) {
showView('#boot');
break;
case 'stopped':
+ voice.forgetCoreTransmitMode();
setText($('#boot-text'), () => t('ui.restarting.core'));
showView('#boot');
resetConnection(null);
break;
case 'ready':
+ // A (re)started core transmits directly until told otherwise: apply the chosen mode first.
+ voice.forgetCoreTransmitMode();
+ voice.applyTransmitMode();
loadProfile();
break;
case 'missing':
showFatal(t('ui.teamspeach.core.not.found'), t('ui.the.core.executable.is.missing.build.it'), status.candidates ?? []);
break;
default:
+ voice.forgetCoreTransmitMode();
resetConnection(null);
showFatal(t('ui.the.core.stopped'), coreStatusText(status), []);
}
@@ -467,7 +472,7 @@ Object.defineProperty(window, 'teamspeachDiagnostics', {
clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [],
talking: Array.from(S.talking),
audio: { ...S.audio },
- voice: { ...voice.voiceStats, sending: voice.isSending(), capturing: voice.isCapturing() },
+ voice: { ...voice.voiceStats, sending: voice.isSending(), capturing: voice.isCapturing(), coreMode: voice.confirmedTransmitMode() },
streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })),
watch: { ...watch.watchStats },
videoCodecs: settings.videoCodecs(),
diff --git a/app/renderer/js/settings.js b/app/renderer/js/settings.js
index 6a28cb3..a530e45 100644
--- a/app/renderer/js/settings.js
+++ b/app/renderer/js/settings.js
@@ -135,10 +135,17 @@ export function initSettings(h0) {
if (radio.checked) {
await hooks.savePrefs({ transmitMode: radio.value });
renderAudio();
+ await voice.applyTransmitMode();
}
});
}
+ $('#vad-sensitivity').addEventListener('change', async (e) => {
+ await hooks.savePrefs({ vadSensitivity: e.target.value });
+ renderAudio();
+ await voice.applyTransmitMode();
+ });
+
$('#ptt-assign').addEventListener('click', async () => {
const btn = $('#ptt-assign');
btn.disabled = true;
@@ -189,6 +196,8 @@ export function renderProfile() {
export function renderAudio() {
const prefs = S.prefs;
for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode;
+ $('#vad-options').hidden = prefs.transmitMode !== 'vad';
+ $('#vad-sensitivity').value = prefs.vadSensitivity;
setText($('#ptt-key'), () => keyLabel(prefs.pttCode));
$('#ptt-assign').disabled = false;
$('#opt-ns').checked = prefs.noiseSuppression;
diff --git a/app/renderer/js/voice.js b/app/renderer/js/voice.js
index e0454e3..de054d5 100644
--- a/app/renderer/js/voice.js
+++ b/app/renderer/js/voice.js
@@ -2,7 +2,7 @@
// device selection and push-to-talk keys.
import { $, setText } from './dom.js';
import { S, isConnected, ownChannel } from './state.js';
-import { tp, log } from './core.js';
+import { tp, log, call } from './core.js';
import { AudioEngine } from './audio/engine.js';
import { buildDeviceOptions } from './audio/devices.js';
import { toast } from './toast.js';
@@ -79,18 +79,81 @@ function channelCanTransmit() {
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
}
-export function shouldTransmit() {
- return isConnected()
- && !S.audio.input_muted
- && !S.audio.output_muted
- && (S.prefs.transmitMode === 'open' || S.ptt)
- && channelCanTransmit();
+// Transmit mode confirmed by the core (`set_transmit`): null until acknowledged. Frames are forwarded only
+// when it matches what the preferences ask for, so audio never reaches the core under the wrong mode.
+// "direct": the core sends every forwarded frame (push to talk, open microphone). "vad": the core's voice
+// detector decides, so frames are forwarded continuously and only speech is sent.
+let coreTx = null;
+let coreTxPending = null;
+let coreTxFailed = false;
+
+function wantedCoreTx() {
+ return S.prefs?.transmitMode === 'vad' ? { mode: 'vad', sensitivity: S.prefs.vadSensitivity } : { mode: 'direct' };
+}
+
+const txKey = (mode) => (mode ? `${mode.mode}:${mode.sensitivity ?? ''}` : '');
+
+/** Stops forwarding at once and ends an open burst (the core ends its talk spurt on audio_end). */
+function stopForwarding() {
+ if (!sending) return;
+ tp.endAudio();
+ sending = false;
+ log('debug', `voice: burst end frames=${burst.frames} peak=${burst.peakMax > 0 ? (20 * Math.log10(burst.peakMax)).toFixed(1) : '-inf'} dBFS`);
+ burst = null;
+ hooks.onTransmitChanged();
+}
+
+/**
+ * Asks the core to use the transmit mode the preferences select. Nothing is forwarded until the core has
+ * acknowledged it; a failure leaves the mode unapplied (nothing is sent) and is shown, never replaced by
+ * another mode.
+ */
+export async function applyTransmitMode() {
+ if (!S.prefs) return;
+ const want = wantedCoreTx();
+ const key = txKey(want);
+ if (txKey(coreTx) === key && !coreTxFailed) return;
+ coreTx = null;
+ stopForwarding();
+ coreTxPending = key;
+ try {
+ const result = await call('set_transmit', want);
+ if (coreTxPending !== key) return; // a newer change is on its way
+ coreTx = { mode: result.mode, sensitivity: result.sensitivity };
+ coreTxFailed = false;
+ log('info', `voice: transmit mode ${result.mode}${result.sensitivity ? ` (${result.sensitivity})` : ''}`);
+ } catch (err) {
+ if (coreTxPending !== key) return;
+ coreTxFailed = true;
+ log('error', `voice: set_transmit failed: ${err.code} ${err.message}`);
+ toast(() => t('error.transmit_mode', { detail: errorText(err) }), 'error');
+ } finally {
+ if (coreTxPending === key) coreTxPending = null;
+ hooks.onTransmitChanged();
+ }
+}
+
+/** The core stopped or restarted: its transmit mode is unknown until applied again. */
+export function forgetCoreTransmitMode() {
+ coreTx = null;
+ coreTxPending = null;
+ sending = false;
+ burst = null;
+}
+
+/** Whether captured frames go to the core right now (not whether voice is sent: see S.audio.transmitting). */
+export function shouldForward() {
+ if (!isConnected() || S.audio.input_muted || S.audio.output_muted || !channelCanTransmit()) return false;
+ const mode = S.prefs.transmitMode;
+ if (mode === 'vad') return coreTx?.mode === 'vad' && coreTx.sensitivity === S.prefs.vadSensitivity;
+ if (coreTx?.mode !== 'direct') return false;
+ return mode === 'open' || S.ptt;
}
function onFrame(pcm, rms, peak) {
voiceStats.level = peak;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
- if (shouldTransmit()) {
+ if (shouldForward()) {
tp.sendAudioFrame(new Uint8Array(pcm));
voiceStats.framesSent += 1;
if (!sending) {
@@ -102,12 +165,8 @@ function onFrame(pcm, rms, peak) {
}
burst.frames += 1;
if (peak > burst.peakMax) burst.peakMax = peak;
- } else if (sending) {
- tp.endAudio();
- sending = false;
- log('debug', `voice: burst end frames=${burst.frames} peak=${burst.peakMax > 0 ? (20 * Math.log10(burst.peakMax)).toFixed(1) : '-inf'} dBFS`);
- burst = null;
- hooks.onTransmitChanged();
+ } else {
+ stopForwarding();
}
}
@@ -126,10 +185,7 @@ export async function syncCapture() {
const want = isConnected() || micTest;
if (!want) {
engine.stopCapture();
- if (sending) {
- tp.endAudio();
- sending = false;
- }
+ stopForwarding();
return;
}
if (engine.capturing || engine.captureStarting) return;
@@ -154,6 +210,7 @@ export async function syncCapture() {
*/
export async function restartCapture() {
engine.stopCapture();
+ stopForwarding();
await syncCapture();
}
@@ -290,6 +347,7 @@ export function capturePttKey() {
export function transmitHint() {
if (!S.prefs) return '';
if (S.prefs.transmitMode === 'open') return t('ui.open.microphone');
+ if (S.prefs.transmitMode === 'vad') return t('transmit.header.vad');
// The key is read only from this window: say so whenever another window has the focus.
if (!document.hasFocus()) return t('message.window.unfocused.p0.will.not.work', { p0: keyLabel(S.prefs.pttCode) });
return t('message.key.p0', { p0: keyLabel(S.prefs.pttCode) });
@@ -299,6 +357,11 @@ export function isCapturing() {
return Boolean(engine && engine.capturing);
}
+/** The transmit mode the core confirmed, or null (diagnostics). */
+export function confirmedTransmitMode() {
+ return coreTx ? { ...coreTx } : null;
+}
+
export function isSending() {
return sending;
}
diff --git a/app/renderer/shared/en.js b/app/renderer/shared/en.js
index 72660af..5a06913 100644
--- a/app/renderer/shared/en.js
+++ b/app/renderer/shared/en.js
@@ -108,6 +108,16 @@
"ui.transmission.mode": "Transmission mode",
"ui.push.to.talk": "Push to talk",
"ui.open.microphone": "Open microphone",
+ "transmit.mode.vad": "Voice activation",
+ "transmit.mode.open": "Open microphone (continuous transmission)",
+ "transmit.vad.sensitivity": "Voice activation sensitivity",
+ "transmit.vad.high": "High: quieter speech",
+ "transmit.vad.normal": "Normal",
+ "transmit.vad.low": "Low: noisier surroundings",
+ "transmit.vad.hint": "Voice detection runs locally on this computer, not in the cloud. It detects speech rather than just sound level; audio is only held briefly in memory to decide, and nothing is saved as a recording or transcribed into words. Transmission starts when speech is detected and ends about 0.4 s after the last detected speech. Noise suppression can help, but a TV, other voices, or noise may still trigger transmission or keep it open.",
+ "transmit.mic.test.hint": "The microphone test shows the input level, not whether speech is detected. The test itself never sends audio. In a channel, the selected transmission mode and mute controls determine when others hear you.",
+ "transmit.header.vad": "Voice activation",
+ "error.transmit_mode": "The transmission mode could not be applied ({detail}). Nothing is transmitted until it is applied.",
"ui.push.to.talk.key": "Push-to-talk key",
"ui.assign": "Assign",
"ui.the.key.works.while.teamspeach.is.focused": "The key works while TeamsPeach is focused. Letter keys do not trigger while typing. Press Esc to cancel assignment.",
diff --git a/app/renderer/shared/ru.js b/app/renderer/shared/ru.js
index b76aba6..066075c 100644
--- a/app/renderer/shared/ru.js
+++ b/app/renderer/shared/ru.js
@@ -108,6 +108,16 @@
"ui.transmission.mode": "Режим передачи",
"ui.push.to.talk": "Нажми и говори",
"ui.open.microphone": "Открытый микрофон",
+ "transmit.mode.vad": "Активация голосом",
+ "transmit.mode.open": "Открытый микрофон (непрерывная передача)",
+ "transmit.vad.sensitivity": "Чувствительность активации голосом",
+ "transmit.vad.high": "Высокая: для тихой речи",
+ "transmit.vad.normal": "Обычная",
+ "transmit.vad.low": "Низкая: для шумной обстановки",
+ "transmit.vad.hint": "Детектор работает на этом компьютере, без облачных сервисов. Он определяет наличие речи, а не просто уровень звука; звук лишь кратко держится в памяти для решения, ничего не сохраняется как запись и не переводится в текст. Передача начинается при обнаружении речи и заканчивается примерно через 0,4 с после последней обнаруженной речи. Шумоподавление может помочь, но телевизор, чужие голоса или шум всё равно могут включить передачу или продлить её.",
+ "transmit.mic.test.hint": "Проверка микрофона показывает уровень входного сигнала, а не результат определения речи. Сама проверка не отправляет звук. В канале слышимость вашего голоса зависит от выбранного режима передачи и кнопок отключения микрофона и звука.",
+ "transmit.header.vad": "Активация голосом",
+ "error.transmit_mode": "Не удалось применить режим передачи ({detail}). Пока он не применён, ничего не передаётся.",
"ui.push.to.talk.key": "Клавиша «нажми и говори»",
"ui.assign": "Назначить",
"ui.the.key.works.while.teamspeach.is.focused": "Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста. Esc отменяет назначение.",
diff --git a/core/Cargo.lock b/core/Cargo.lock
index d20893e..73822bd 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -411,6 +411,12 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "earshot"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "afea66474c4036a7e5fa4b072a3b0a09cd0b01f00134da3115d76b7cc5899f03"
+
[[package]]
name = "eax"
version = "0.5.0"
@@ -1869,10 +1875,11 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
[[package]]
name = "teamspeach-core"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"audiopus",
"base64 0.22.1",
+ "earshot",
"futures",
"num-traits",
"serde",
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 69e2bab..e4aed3a 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "teamspeach-core"
-version = "0.1.2"
+version = "0.1.3"
edition = "2021"
rust-version = "1.89"
description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)"
@@ -24,6 +24,8 @@ serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
sha-1 = "0.10"
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
simple_asn1 = "0.6"
+# Voice activation detector (pure Rust, embedded model; MIT OR Apache-2.0). Pinned: newer releases change the API.
+earshot = "=1.2.2"
thiserror = "2"
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
tracing = "0.1"
diff --git a/core/THIRD_PARTY_NOTICES.md b/core/THIRD_PARTY_NOTICES.md
index ce563ab..c84341f 100644
--- a/core/THIRD_PARTY_NOTICES.md
+++ b/core/THIRD_PARTY_NOTICES.md
@@ -48,6 +48,7 @@ platform build links), followed by the license texts shipped with those crates.
| digest | 0.10.7 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| digest | 0.9.0 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| displaydoc | 0.2.7 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
+| earshot | 1.2.2 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
| eax | 0.5.0 | Apache-2.0 OR MIT | registry+https://github.com/rust-lang/crates.io-index |
| ecdsa | 0.16.9 | Apache-2.0 OR MIT | registry+https://github.com/rust-lang/crates.io-index |
| either | 1.19.0 | MIT OR Apache-2.0 | registry+https://github.com/rust-lang/crates.io-index |
@@ -253,7 +254,7 @@ platform build links), followed by the license texts shipped with those crates.
| zerovec-derive | 0.11.7 | Unicode-3.0 | registry+https://github.com/rust-lang/crates.io-index |
| zmij | 1.0.23 | MIT | registry+https://github.com/rust-lang/crates.io-index |
-Crates whose package ships no license file (standard texts of their declared license are included below with the authors from their Cargo.toml): git-testament 0.2.6, git-testament-derive 0.2.1, jni 0.22.4, jni-macros 0.22.4, jni-sys-macros 0.4.1, ndk-context 0.1.1, quicklz 0.3.1, r-efi 6.0.0, valuable 0.1.1.
+Crates whose package ships no license file (standard texts of their declared license are included below with the authors from their Cargo.toml): earshot 1.2.2, git-testament 0.2.6, git-testament-derive 0.2.1, jni 0.22.4, jni-macros 0.22.4, jni-sys-macros 0.4.1, ndk-context 0.1.1, quicklz 0.3.1, r-efi 6.0.0, valuable 0.1.1.
## libopus (bundled in audiopus_sys, statically linked)
@@ -2964,6 +2965,30 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+### earshot 1.2.2 (no license file in package; standard MIT text, license MIT OR Apache-2.0)
+
+```
+Copyright (c) Carson M
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
### eax 0.5.0 (LICENSE-MIT)
```
diff --git a/core/src/audio.rs b/core/src/audio.rs
index bd0f8f9..56a6a95 100644
--- a/core/src/audio.rs
+++ b/core/src/audio.rs
@@ -84,6 +84,15 @@ impl AudioInQueue {
pub fn pop(&self) -> Option { self.items.lock().expect("audio queue poisoned").pop_front() }
+ /// Discards everything queued, e.g. frames captured under a previous transmit mode. Returns the number
+ /// of discarded frames (not counted as overflow drops).
+ pub fn clear(&self) -> usize {
+ let mut q = self.items.lock().expect("audio queue poisoned");
+ let frames = q.iter().filter(|i| matches!(i, AudioIn::Frame(_))).count();
+ q.clear();
+ frames
+ }
+
pub async fn notified(&self) { self.notify.notified().await }
/// Number of frames dropped since the last call.
@@ -316,6 +325,18 @@ mod tests {
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
}
+ #[test]
+ fn clear_discards_queued_frames_without_counting_drops() {
+ let q = AudioInQueue::new();
+ for _ in 0..3 {
+ q.push(AudioIn::Frame(Box::new([1; FRAME_SAMPLES])));
+ }
+ q.push(AudioIn::End);
+ assert_eq!(q.clear(), 3);
+ assert!(q.pop().is_none());
+ assert_eq!(q.take_dropped(), 0);
+ }
+
#[test]
fn encode_decode_mix_roundtrip_both_codecs() {
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
diff --git a/core/src/main.rs b/core/src/main.rs
index 99b8a0c..a93eb4f 100644
--- a/core/src/main.rs
+++ b/core/src/main.rs
@@ -11,6 +11,7 @@ mod secure_fs;
mod session;
mod snapshot;
mod stdio;
+mod vad;
use std::fs::{File, OpenOptions, TryLockError};
use std::io::{Read, Write};
diff --git a/core/src/protocol.rs b/core/src/protocol.rs
index 6da2957..6b7f611 100644
--- a/core/src/protocol.rs
+++ b/core/src/protocol.rs
@@ -8,6 +8,8 @@ use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use serde_json::Value;
+use crate::vad::Sensitivity;
+
pub const PROTOCOL_VERSION: u32 = 1;
/// Maximum accepted stdin line (bytes, without the newline).
pub const MAX_LINE_BYTES: usize = 256 * 1024;
@@ -108,6 +110,8 @@ pub enum Command {
JoinChannel { channel_id: u64, password: Option },
SendText { target: TextTarget, client_id: Option, message: String },
SetAudio { input_muted: Option, output_muted: Option },
+ /// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
+ SetTransmit { vad: Option },
StreamList { client_id: Option },
StreamJoin { stream_id: String, client_id: u16, message: Option },
/// `json` is already compact-serialized and size checked.
@@ -131,6 +135,7 @@ impl Command {
Command::JoinChannel { .. } => "join_channel",
Command::SendText { .. } => "send_text",
Command::SetAudio { .. } => "set_audio",
+ Command::SetTransmit { .. } => "set_transmit",
Command::StreamList { .. } => "stream_list",
Command::StreamJoin { .. } => "stream_join",
Command::StreamSignal { .. } => "stream_signal",
@@ -211,6 +216,14 @@ struct SendTextArgs {
message: String,
}
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct SetTransmitArgs {
+ mode: String,
+ #[serde(default)]
+ sensitivity: Option,
+}
+
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetAudioArgs {
@@ -425,6 +438,19 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result
let a: SetAudioArgs = args_owned(raw)?;
Command::SetAudio { input_muted: a.input_muted, output_muted: a.output_muted }
}
+ "set_transmit" => {
+ let a: SetTransmitArgs = args_owned(raw)?;
+ let vad = match (a.mode.as_str(), a.sensitivity.as_deref()) {
+ ("direct", None) => None,
+ ("direct", Some(_)) => return Err(bad("set_transmit: sensitivity applies to mode 'vad' only")),
+ ("vad", None | Some("normal")) => Some(Sensitivity::Normal),
+ ("vad", Some("high")) => Some(Sensitivity::High),
+ ("vad", Some("low")) => Some(Sensitivity::Low),
+ ("vad", Some(_)) => return Err(bad("set_transmit: sensitivity must be 'high', 'normal' or 'low'")),
+ _ => return Err(bad("set_transmit: mode must be 'direct' or 'vad'")),
+ };
+ Command::SetTransmit { vad }
+ }
"stream_list" => Command::StreamList { client_id: args_owned::(raw)?.client_id },
"stream_join" => {
let a: StreamJoinArgs = args_owned(raw)?;
@@ -511,6 +537,21 @@ mod tests {
}
}
+ #[test]
+ fn set_transmit_modes_and_sensitivities() {
+ let parse = |args: &str| parse_line(&format!(r#"{{"id":"t","cmd":"set_transmit","args":{args}}}"#));
+ assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: Command::SetTransmit { vad: None }, .. }));
+ assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(Sensitivity::Normal) }, .. }));
+ assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(Sensitivity::High) }, .. }));
+ assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(Sensitivity::Low) }, .. }));
+ for bad in [r#"{"mode":"open"}"#, r#"{"mode":"direct","sensitivity":"low"}"#, r#"{"mode":"vad","sensitivity":"max"}"#, r#"{"mode":"vad","threshold":0.1}"#, r#"{}"#] {
+ match parse(bad) {
+ Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
+ other => panic!("{bad}: {other:?}"),
+ }
+ }
+ }
+
#[test]
fn requests_need_valid_id_and_known_args() {
assert!(matches!(
diff --git a/core/src/session.rs b/core/src/session.rs
index 81f67bd..5415c24 100644
--- a/core/src/session.rs
+++ b/core/src/session.rs
@@ -20,6 +20,7 @@ use tsclientlib::messages::c2s::{OutInitDownloadMessage, OutInitDownloadPart};
use tsproto_packets::packets::OutCommand;
use crate::audio::{self, AudioIn, AudioInQueue, Receiver, RxEvent, TxCodec, TxEncoder};
+use crate::vad::{Decision, Sensitivity, VoiceGate, MAX_PREROLL_FRAMES};
use crate::media::{self, MediaKind};
use crate::profile::{validate_nickname, Store, StoreError, StoredIdentity};
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Frame, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
@@ -156,11 +157,12 @@ struct FtJob {
impl Conn {
fn connected(&self) -> bool { matches!(self.phase, Phase::Connected) }
- fn own_channel_codec(&self) -> Option<(tsclientlib::Codec, u8)> {
+ /// Own channel id, codec and codec quality.
+ fn own_channel_codec(&self) -> Option<(u64, tsclientlib::Codec, u8)> {
let book = self.con.get_state().ok()?;
let me = book.clients.get(&book.own_client)?;
let ch = book.channels.get(&me.channel)?;
- Some((ch.codec, ch.codec_quality.unwrap_or(DEFAULT_CODEC_QUALITY)))
+ Some((me.channel.0, ch.codec, ch.codec_quality.unwrap_or(DEFAULT_CODEC_QUALITY)))
}
fn send(&mut self, cmd: impl OutCommandExt) -> Result {
@@ -178,6 +180,14 @@ struct Tx {
last_overflow_report: Option,
}
+/// Voice activation state; present only in the "vad" transmit mode.
+struct VadState {
+ gate: VoiceGate,
+ /// Channel and codec the gate's audio belongs to; a change resets the gate so nothing heard before
+ /// it is sent afterwards.
+ route: Option<(u64, TxCodec, u8)>,
+}
+
enum Exit {
Running,
Requested { req: Option },
@@ -191,6 +201,9 @@ pub struct Session {
flags: AudioFlags,
conn: Option,
tx: Tx,
+ /// `None` = direct transmission: every frame the renderer forwards is sent.
+ vad: Option>,
+ preroll_buf: Box<[Frame; MAX_PREROLL_FRAMES]>,
pcm: Box<[i16; FRAME_SAMPLES]>,
rev: u64,
exit: Exit,
@@ -218,6 +231,8 @@ impl Session {
flags: AudioFlags::default(),
conn: None,
tx: Tx::default(),
+ vad: None,
+ preroll_buf: Box::new([[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES]),
pcm: Box::new([0; FRAME_SAMPLES]),
rev: 0,
exit: Exit::Running,
@@ -346,6 +361,7 @@ impl Session {
Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password),
Command::SendText { target, client_id, message } => self.send_text(&id, target, client_id, &message),
Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await,
+ Command::SetTransmit { vad } => self.set_transmit(vad).await.map(Some),
Command::StreamList { client_id } => self.stream_list(&id, client_id).await,
Command::StreamJoin { stream_id, client_id, message } => {
self.stream_join(&id, &stream_id, client_id, message)
@@ -1189,38 +1205,107 @@ impl Session {
}
}
+ /// Applies the transmit mode. Frames still queued from the previous mode are discarded and any open
+ /// burst is ended before the answer, so nothing captured under the old mode is sent under the new one.
+ async fn set_transmit(&mut self, vad: Option) -> Result {
+ let discarded = self.audio_in.clear();
+ self.tx_end().await;
+ match (vad, self.vad.as_mut()) {
+ (None, _) => self.vad = None,
+ (Some(s), Some(state)) => state.gate.set_sensitivity(s),
+ (Some(s), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(s), route: None })),
+ }
+ let result = match vad {
+ None => json!({ "mode": "direct" }),
+ Some(s) => json!({ "mode": "vad", "sensitivity": s.name() }),
+ };
+ info!(mode = %result["mode"], sensitivity = %result["sensitivity"], discarded, "transmit mode applied");
+ Ok(result)
+ }
+
+ /// Checks every condition for sending voice right now and returns the own channel id, codec and
+ /// quality; reports the first failing condition once per burst.
+ async fn tx_route(&mut self) -> Option<(u64, TxCodec, u8)> {
+ let flags = self.flags;
+ let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else {
+ self.report_once(ErrorObj::new(ErrorCode::NotConnected, "audio_frame while not connected; frames dropped")).await;
+ return None;
+ };
+ if flags.input_muted || flags.output_muted {
+ self.report_once(ErrorObj::new(ErrorCode::AudioMuted, "audio_frame while muted or deafened; frames dropped")).await;
+ return None;
+ }
+ let Some((channel, codec, quality)) = c.own_channel_codec() else {
+ self.report_once(ErrorObj::new(ErrorCode::Internal, "own channel is unknown")).await;
+ return None;
+ };
+ let Some(tx_codec) = TxCodec::for_channel(codec) else {
+ self.report_once(
+ ErrorObj::new(
+ ErrorCode::AudioCodecUnsupported,
+ format!("channel codec {} is not supported for sending (Opus only)", audio::codec_name(codec)),
+ )
+ .with_detail(json!({ "codec": audio::codec_name(codec) })),
+ )
+ .await;
+ return None;
+ };
+ if !c.con.can_send_audio() {
+ self.report_once(ErrorObj::new(
+ ErrorCode::AudioMuted,
+ "the server does not let this client talk here (talk power, away or server mute); frames dropped",
+ ))
+ .await;
+ return None;
+ }
+ Some((channel, tx_codec, quality))
+ }
+
async fn tx_frame(&mut self, frame: &Frame) {
self.tx.burst_open = true;
self.tx.last_frame = Some(Instant::now());
- let flags = self.flags;
- let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else {
- return self.report_once(ErrorObj::new(ErrorCode::NotConnected, "audio_frame while not connected; frames dropped")).await;
+ let Some(route) = self.tx_route().await else {
+ // Nothing may be sent now; forget what voice activation heard so it is never sent later.
+ self.vad_reset();
+ self.end_spurt().await;
+ return;
};
- if flags.input_muted || flags.output_muted {
- return self.report_once(ErrorObj::new(ErrorCode::AudioMuted, "audio_frame while muted or deafened; frames dropped")).await;
+ let (_, tx_codec, quality) = route;
+ let Some(vad) = self.vad.as_mut() else {
+ self.tx_send(frame, tx_codec, quality).await;
+ return;
+ };
+ if vad.route != Some(route) {
+ vad.gate.reset();
+ vad.route = Some(route);
}
- let Some((codec, quality)) = c.own_channel_codec() else {
- return self.report_once(ErrorObj::new(ErrorCode::Internal, "own channel is unknown")).await;
- };
- let Some(tx_codec) = TxCodec::for_channel(codec) else {
- return self
- .report_once(
- ErrorObj::new(
- ErrorCode::AudioCodecUnsupported,
- format!("channel codec {} is not supported for sending (Opus only)", audio::codec_name(codec)),
- )
- .with_detail(json!({ "codec": audio::codec_name(codec) })),
- )
- .await;
- };
- if !c.con.can_send_audio() {
- return self
- .report_once(ErrorObj::new(
- ErrorCode::AudioMuted,
- "the server does not let this client talk here (talk power, away or server mute); frames dropped",
- ))
- .await;
+ let decision = vad.gate.push(frame);
+ let held = if decision == Decision::Start { vad.gate.take_preroll(&mut self.preroll_buf) } else { 0 };
+ match decision {
+ Decision::Hold => {}
+ Decision::Start => {
+ for i in 0..held {
+ let earlier = self.preroll_buf[i];
+ if !self.tx_send(&earlier, tx_codec, quality).await {
+ return;
+ }
+ }
+ self.tx_send(frame, tx_codec, quality).await;
+ }
+ Decision::Send => {
+ self.tx_send(frame, tx_codec, quality).await;
+ }
+ Decision::SendAndEnd => {
+ if self.tx_send(frame, tx_codec, quality).await {
+ self.end_spurt().await;
+ }
+ }
}
+ }
+
+ /// Encodes and sends one frame; returns false if it could not be sent (reported once per burst).
+ async fn tx_send(&mut self, frame: &Frame, tx_codec: TxCodec, quality: u8) -> bool {
+ let Some(c) = self.conn.as_mut().filter(|c| c.connected()) else { return false };
if !self.tx.encoder.as_ref().is_some_and(|e| e.matches(tx_codec, quality)) {
if let (true, Some(old)) = (self.tx.transmitting, &self.tx.encoder) {
let _ = c.con.send_audio(audio::end_of_voice(old.codec()));
@@ -1228,27 +1313,39 @@ impl Session {
match TxEncoder::new(tx_codec, quality) {
Ok(e) => self.tx.encoder = Some(e),
Err(e) => {
- return self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("creating Opus encoder: {e}"))).await;
+ self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("creating Opus encoder: {e}"))).await;
+ return false;
}
}
}
let encoder = self.tx.encoder.as_mut().expect("set above");
let packet = match encoder.encode(frame) {
Ok(p) => p,
- Err(e) => return self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await,
+ Err(e) => {
+ self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await;
+ return false;
+ }
};
if let Err(e) = c.con.send_audio(packet) {
- return self.report_once(lib_error(ErrorCode::Io, &e)).await;
+ self.report_once(lib_error(ErrorCode::Io, &e)).await;
+ return false;
}
if !self.tx.transmitting {
self.tx.transmitting = true;
self.emit_audio_state().await;
}
+ true
}
- async fn tx_end(&mut self) {
- self.tx.burst_open = false;
- self.tx.reported = false;
+ fn vad_reset(&mut self) {
+ if let Some(state) = self.vad.as_mut() {
+ state.gate.reset();
+ state.route = None;
+ }
+ }
+
+ /// Ends the current talk spurt (end-of-voice packet, `transmitting: false`) if one is open.
+ async fn end_spurt(&mut self) {
if !self.tx.transmitting {
return;
}
@@ -1263,6 +1360,14 @@ impl Session {
self.emit_audio_state().await;
}
+ /// The renderer stopped sending (audio_end, mute, deafen, disconnect, capture stopped, timeout).
+ async fn tx_end(&mut self) {
+ self.tx.burst_open = false;
+ self.tx.reported = false;
+ self.vad_reset();
+ self.end_spurt().await;
+ }
+
async fn on_tick(&mut self) {
let now = Instant::now();
if self.tx.burst_open && self.tx.last_frame.is_some_and(|t| now - t > BURST_TIMEOUT) {
diff --git a/core/src/vad.rs b/core/src/vad.rs
new file mode 100644
index 0000000..0b8f99a
--- /dev/null
+++ b/core/src/vad.rs
@@ -0,0 +1,644 @@
+//! Voice activation: decides which captured 20 ms frames are sent when the user chose "voice activation".
+//!
+//! The detector is earshot (pure Rust, MIT OR Apache-2.0): a small embedded neural network that returns
+//! a voice probability for every 16 ms window of 16 kHz mono audio. It is a statistical detector, not a
+//! speech recogniser: loud speech-like noise can open the gate and quiet speech under heavy noise can be
+//! missed. The input has already passed Chromium's WebRTC capture processing (noise suppression, echo
+//! cancellation, gain control as configured by the user).
+//!
+//! All buffers are fixed-size and allocated once when the gate is created; processing a frame does not
+//! allocate.
+
+use earshot::Detector;
+
+use crate::protocol::{Frame, FRAME_SAMPLES};
+
+/// Frames kept from before the onset so the start of a word is not cut off (5 × 20 ms = 100 ms).
+pub const PREROLL_FRAMES: usize = 5;
+/// Frames sent after the last voiced frame so word endings and short pauses are kept (400 ms).
+pub const HANGOVER_FRAMES: u32 = 20;
+/// While a spurt is open, a window keeps it open at this much below the opening threshold.
+pub const RELEASE_MARGIN: f32 = 0.15;
+/// Consecutive voiced detector windows (16 ms each) needed to open the gate.
+pub const ONSET_WINDOWS: u32 = 3;
+
+/// Frames after a reset during which the gate cannot open: a freshly reset network scores the first
+/// ~150 ms of any input (noise, clicks) higher than it settles to. Nothing heard in that time is lost:
+/// every frame since the reset is kept (see [`MAX_PREROLL_FRAMES`]) and sent if speech opens the gate.
+pub const WARMUP_FRAMES: u32 = 10;
+/// Frames held at most: the whole warm-up plus the normal preroll (300 ms). The first spurt after a
+/// reset sends everything since the reset; later spurts send the last [`PREROLL_FRAMES`].
+pub const MAX_PREROLL_FRAMES: usize = WARMUP_FRAMES as usize + PREROLL_FRAMES;
+/// Detector input: 16 ms at 16 kHz.
+const WINDOW: usize = 256;
+/// 48 kHz → 16 kHz.
+const DECIMATION: usize = 3;
+const OUT_PER_FRAME: usize = FRAME_SAMPLES / DECIMATION;
+/// Anti-aliasing low-pass in front of the decimation (odd length, linear phase).
+const TAPS: usize = 63;
+const HISTORY: usize = TAPS - 1;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Sensitivity {
+ High,
+ Normal,
+ Low,
+}
+
+impl Sensitivity {
+ /// Voice probability a detector window needs to count as voiced.
+ pub fn threshold(self) -> f32 {
+ match self {
+ Sensitivity::High => 0.45,
+ Sensitivity::Normal => 0.6,
+ Sensitivity::Low => 0.75,
+ }
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Sensitivity::High => "high",
+ Sensitivity::Normal => "normal",
+ Sensitivity::Low => "low",
+ }
+ }
+}
+
+/// What to do with the frame just pushed.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Decision {
+ /// Not speech: keep it only as possible preroll.
+ Hold,
+ /// Speech starts: send the returned preroll frames (oldest first), then the current frame.
+ Start,
+ /// Inside a talk spurt: send the current frame.
+ Send,
+ /// Send the current frame, then end the talk spurt (hangover ran out).
+ SendAndEnd,
+}
+
+/// 48 kHz → 16 kHz decimator whose filter history carries over between 960-sample frames.
+struct Decimator {
+ coeffs: [f32; TAPS],
+ /// The last `HISTORY` input samples of the previous frame, then the current frame.
+ buf: [f32; HISTORY + FRAME_SAMPLES],
+}
+
+impl Decimator {
+ fn new() -> Self {
+ // Windowed sinc (Blackman), cut-off 7 kHz at 48 kHz, unity gain at DC.
+ let fc = 7_000.0_f64 / 48_000.0;
+ let m = (TAPS - 1) as f64;
+ let mut c = [0.0_f64; TAPS];
+ for (i, v) in c.iter_mut().enumerate() {
+ let x = i as f64 - m / 2.0;
+ let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) };
+ let w = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / m).cos() + 0.08 * (4.0 * std::f64::consts::PI * i as f64 / m).cos();
+ *v = sinc * w;
+ }
+ let sum: f64 = c.iter().sum();
+ let mut coeffs = [0.0_f32; TAPS];
+ for (o, v) in coeffs.iter_mut().zip(c) {
+ *o = (v / sum) as f32;
+ }
+ Self { coeffs, buf: [0.0; HISTORY + FRAME_SAMPLES] }
+ }
+
+ fn reset(&mut self) { self.buf = [0.0; HISTORY + FRAME_SAMPLES]; }
+
+ /// Decimates one 20 ms frame into `out` (320 samples). The low-pass can overshoot full-scale input
+ /// slightly (ringing), so outputs are clamped to [-1, 1], the range the detector expects.
+ fn process(&mut self, frame: &Frame, out: &mut [f32; OUT_PER_FRAME]) {
+ for (dst, s) in self.buf[HISTORY..].iter_mut().zip(frame.iter()) {
+ *dst = f32::from(*s) / 32_768.0;
+ }
+ // Output k uses the TAPS inputs ending at input sample 3k (+2 to stay causal within the frame).
+ for (k, o) in out.iter_mut().enumerate() {
+ let end = HISTORY + k * DECIMATION + (DECIMATION - 1);
+ let window = &self.buf[end + 1 - TAPS..=end];
+ let y: f32 = window.iter().zip(self.coeffs.iter()).map(|(x, c)| x * c).sum();
+ *o = y.clamp(-1.0, 1.0);
+ }
+ self.buf.copy_within(FRAME_SAMPLES.., 0);
+ }
+}
+
+pub struct VoiceGate {
+ detector: Box,
+ decimator: Decimator,
+ threshold: f32,
+ sensitivity: Sensitivity,
+ /// 16 kHz samples waiting for a full detector window.
+ pending: [f32; WINDOW],
+ pending_len: usize,
+ resampled: [f32; OUT_PER_FRAME],
+ voiced_run: u32,
+ /// Frames left before the spurt ends; 0 = idle.
+ hangover: u32,
+ preroll: [Frame; MAX_PREROLL_FRAMES],
+ preroll_start: usize,
+ preroll_len: usize,
+ /// Frames left in the post-reset warm-up.
+ warmup: u32,
+ /// True from a reset until the first spurt opens: that spurt gets every frame held since the reset.
+ since_reset: bool,
+}
+
+impl VoiceGate {
+ pub fn new(sensitivity: Sensitivity) -> Self {
+ let mut gate = Self {
+ detector: Detector::default_boxed(),
+ decimator: Decimator::new(),
+ threshold: sensitivity.threshold(),
+ sensitivity,
+ pending: [0.0; WINDOW],
+ pending_len: 0,
+ resampled: [0.0; OUT_PER_FRAME],
+ voiced_run: 0,
+ hangover: 0,
+ preroll: [[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES],
+ preroll_start: 0,
+ preroll_len: 0,
+ warmup: WARMUP_FRAMES,
+ since_reset: true,
+ };
+ gate.reset();
+ gate
+ }
+
+ #[cfg(test)]
+ pub fn sensitivity(&self) -> Sensitivity { self.sensitivity }
+
+ pub fn set_sensitivity(&mut self, sensitivity: Sensitivity) {
+ self.sensitivity = sensitivity;
+ self.threshold = sensitivity.threshold();
+ }
+
+ #[cfg(test)]
+ pub fn is_active(&self) -> bool { self.hangover > 0 }
+
+ /// Forgets everything heard so far: detector state, filter history, preroll and any open spurt.
+ /// Called at privacy and routing boundaries only (mode change, mute/deafen, capture end, disconnect,
+ /// channel/codec/permission change), never at the natural end of a spurt.
+ pub fn reset(&mut self) {
+ self.detector.reset();
+ self.warmup = WARMUP_FRAMES;
+ self.since_reset = true;
+ self.decimator.reset();
+ self.pending_len = 0;
+ self.voiced_run = 0;
+ self.hangover = 0;
+ self.preroll_len = 0;
+ self.preroll_start = 0;
+ }
+
+ /// Runs the detector over one frame and returns whether any 16 ms window in it was voiced and
+ /// whether the onset condition is met. While a spurt is open, windows count as voiced down to
+ /// [`RELEASE_MARGIN`] below the threshold (hysteresis), so quieter syllables do not end it.
+ fn detect(&mut self, frame: &Frame) -> (bool, bool) {
+ self.decimator.process(frame, &mut self.resampled);
+ let keep = if self.hangover > 0 { self.threshold - RELEASE_MARGIN } else { self.threshold };
+ let mut voiced = false;
+ let mut onset = false;
+ let mut i = 0;
+ while i < OUT_PER_FRAME {
+ let take = (WINDOW - self.pending_len).min(OUT_PER_FRAME - i);
+ self.pending[self.pending_len..self.pending_len + take].copy_from_slice(&self.resampled[i..i + take]);
+ self.pending_len += take;
+ i += take;
+ if self.pending_len == WINDOW {
+ self.pending_len = 0;
+ let score = self.detector.predict_f32(&self.pending);
+ if score >= keep {
+ voiced = true;
+ }
+ if score >= self.threshold {
+ self.voiced_run = (self.voiced_run + 1).min(ONSET_WINDOWS);
+ if self.voiced_run >= ONSET_WINDOWS {
+ onset = true;
+ }
+ } else {
+ self.voiced_run = 0;
+ }
+ }
+ }
+ (voiced, onset)
+ }
+
+ /// Classifies `frame`. On [`Decision::Start`], the caller sends [`VoiceGate::take_preroll`] and then
+ /// `frame`; the current frame is never part of the preroll.
+ pub fn push(&mut self, frame: &Frame) -> Decision {
+ let (voiced, onset) = self.detect(frame);
+ if self.hangover > 0 {
+ if voiced {
+ self.hangover = HANGOVER_FRAMES;
+ return Decision::Send;
+ }
+ self.hangover -= 1;
+ return if self.hangover == 0 { Decision::SendAndEnd } else { Decision::Send };
+ }
+ if self.warmup > 0 {
+ self.warmup -= 1;
+ } else if onset {
+ self.hangover = HANGOVER_FRAMES;
+ return Decision::Start;
+ }
+ self.remember(frame);
+ Decision::Hold
+ }
+
+ fn remember(&mut self, frame: &Frame) {
+ let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
+ self.preroll[slot] = *frame;
+ if self.preroll_len < MAX_PREROLL_FRAMES {
+ self.preroll_len += 1;
+ } else {
+ self.preroll_start = (self.preroll_start + 1) % MAX_PREROLL_FRAMES;
+ }
+ }
+
+ /// Copies the frames to send before the current one into `out`, oldest first, and empties the
+ /// preroll: everything since the reset for the first spurt after it (at most 300 ms), otherwise the
+ /// last [`PREROLL_FRAMES`]. Returns how many were copied.
+ pub fn take_preroll(&mut self, out: &mut [Frame; MAX_PREROLL_FRAMES]) -> usize {
+ let keep = if self.since_reset { self.preroll_len } else { self.preroll_len.min(PREROLL_FRAMES) };
+ let skip = self.preroll_len - keep;
+ for (i, dst) in out.iter_mut().take(keep).enumerate() {
+ *dst = self.preroll[(self.preroll_start + skip + i) % MAX_PREROLL_FRAMES];
+ }
+ self.preroll_start = 0;
+ self.preroll_len = 0;
+ self.since_reset = false;
+ keep
+ }
+}
+
+#[cfg(test)]
+pub mod tests {
+ use super::*;
+
+ /// Real speech: 4 s of a public-domain LibriVox reading (see tests/fixtures/README.md), 48 kHz mono s16le WAV.
+ pub fn speech_frames() -> Vec {
+ let wav = include_bytes!("../tests/fixtures/speech-librivox-48k.wav");
+ let data = wav_data(wav);
+ data.chunks_exact(FRAME_SAMPLES * 2)
+ .map(|c| {
+ let mut f = [0i16; FRAME_SAMPLES];
+ for (s, b) in f.iter_mut().zip(c.chunks_exact(2)) {
+ *s = i16::from_le_bytes([b[0], b[1]]);
+ }
+ f
+ })
+ .collect()
+ }
+
+ fn wav_data(wav: &[u8]) -> &[u8] {
+ assert_eq!(&wav[0..4], b"RIFF");
+ assert_eq!(&wav[8..12], b"WAVE");
+ let mut i = 12;
+ while i + 8 <= wav.len() {
+ let id = &wav[i..i + 4];
+ let len = u32::from_le_bytes([wav[i + 4], wav[i + 5], wav[i + 6], wav[i + 7]]) as usize;
+ if id == b"fmt " {
+ let fmt = &wav[i + 8..i + 8 + len];
+ assert_eq!(u16::from_le_bytes([fmt[0], fmt[1]]), 1, "PCM");
+ assert_eq!(u16::from_le_bytes([fmt[2], fmt[3]]), 1, "mono");
+ assert_eq!(u32::from_le_bytes([fmt[4], fmt[5], fmt[6], fmt[7]]), 48_000, "48 kHz");
+ assert_eq!(u16::from_le_bytes([fmt[14], fmt[15]]), 16, "16 bit");
+ }
+ if id == b"data" {
+ return &wav[i + 8..i + 8 + len];
+ }
+ i += 8 + len + (len & 1);
+ }
+ panic!("no data chunk");
+ }
+
+ /// Deterministic pseudo-random generator (xorshift) for synthetic noise.
+ struct Rng(u32);
+ impl Rng {
+ fn next(&mut self) -> f32 {
+ self.0 ^= self.0 << 13;
+ self.0 ^= self.0 >> 17;
+ self.0 ^= self.0 << 5;
+ (self.0 as f32 / u32::MAX as f32) * 2.0 - 1.0
+ }
+ }
+
+ fn silence(n: usize) -> Vec { vec![[0i16; FRAME_SAMPLES]; n] }
+
+ /// Synthetic steady broadband noise (fan/hiss-like) at roughly -30 dBFS RMS.
+ fn steady_noise(n: usize) -> Vec {
+ let mut rng = Rng(0x1234_5678);
+ let mut low = 0.0_f32;
+ (0..n)
+ .map(|_| {
+ let mut f = [0i16; FRAME_SAMPLES];
+ for s in f.iter_mut() {
+ low = 0.97 * low + 0.03 * rng.next();
+ *s = ((rng.next() * 0.03 + low * 0.3) * 32_767.0) as i16;
+ }
+ f
+ })
+ .collect()
+ }
+
+ /// Synthetic transients: a 3 ms click (keyboard/mouse-like) every 200 ms over near-silence.
+ fn clicks(n: usize) -> Vec {
+ let mut rng = Rng(0x0bad_cafe);
+ (0..n)
+ .map(|i| {
+ let mut f = [0i16; FRAME_SAMPLES];
+ if i % 10 == 0 {
+ for (j, s) in f.iter_mut().take(144).enumerate() {
+ let env = 1.0 - j as f32 / 144.0;
+ *s = (rng.next() * env * 0.6 * 32_767.0) as i16;
+ }
+ }
+ f
+ })
+ .collect()
+ }
+
+ /// Runs frames through a gate and returns, per frame, whether it would have been sent, plus the
+ /// total number of frames sent (preroll included).
+ fn run(gate: &mut VoiceGate, frames: &[Frame]) -> (Vec, usize) {
+ let mut sent = Vec::with_capacity(frames.len());
+ let mut total = 0;
+ for f in frames {
+ match gate.push(f) {
+ Decision::Hold => sent.push(false),
+ Decision::Start => {
+ let mut pre = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
+ total += gate.take_preroll(&mut pre) + 1;
+ sent.push(true);
+ }
+ Decision::Send | Decision::SendAndEnd => {
+ total += 1;
+ sent.push(true);
+ }
+ }
+ }
+ (sent, total)
+ }
+
+ #[test]
+ fn decimator_keeps_history_across_frames() {
+ // A 1 kHz tone split into frames must decimate exactly like one long block would: compare the
+ // frame-wise output with a direct convolution over the concatenated input.
+ let mut d = Decimator::new();
+ let input: Vec = (0..FRAME_SAMPLES * 3).map(|n| ((n as f32 * 2.0 * std::f32::consts::PI * 1_000.0 / 48_000.0).sin() * 10_000.0) as i16).collect();
+ let mut framewise = Vec::new();
+ for chunk in input.chunks_exact(FRAME_SAMPLES) {
+ let mut f = [0i16; FRAME_SAMPLES];
+ f.copy_from_slice(chunk);
+ let mut out = [0.0; OUT_PER_FRAME];
+ d.process(&f, &mut out);
+ framewise.extend_from_slice(&out);
+ }
+ let reference = Decimator::new();
+ let padded: Vec = std::iter::repeat_n(0.0, HISTORY).chain(input.iter().map(|s| f32::from(*s) / 32_768.0)).collect();
+ for (k, got) in framewise.iter().enumerate() {
+ let end = HISTORY + k * DECIMATION + (DECIMATION - 1);
+ let want: f32 = padded[end + 1 - TAPS..=end].iter().zip(reference.coeffs.iter()).map(|(x, c)| x * c).sum();
+ assert!((got - want).abs() < 1e-6, "sample {k}: {got} vs {want}");
+ }
+ // A 1 kHz tone passes, a 12 kHz tone (above the new Nyquist) is suppressed.
+ let rms = |hz: f32| {
+ let mut d = Decimator::new();
+ let mut acc = 0.0;
+ for i in 0..4 {
+ let mut f = [0i16; FRAME_SAMPLES];
+ for (n, s) in f.iter_mut().enumerate() {
+ let t = (i * FRAME_SAMPLES + n) as f32;
+ *s = ((t * 2.0 * std::f32::consts::PI * hz / 48_000.0).sin() * 16_000.0) as i16;
+ }
+ let mut out = [0.0; OUT_PER_FRAME];
+ d.process(&f, &mut out);
+ if i > 0 {
+ acc += out.iter().map(|x| x * x).sum::();
+ }
+ }
+ (acc / (3 * OUT_PER_FRAME) as f32).sqrt()
+ };
+ assert!(rms(1_000.0) > 0.3, "pass band {}", rms(1_000.0));
+ assert!(rms(12_000.0) < 0.003, "stop band {}", rms(12_000.0));
+ }
+
+ #[test]
+ fn detector_windows_cross_frame_boundaries() {
+ // 320 new samples per frame: the 5th frame completes the 6th 256-sample window, so frames carry
+ // one or two windows and none is lost or duplicated (1600 samples = 6 windows + 64 pending).
+ let mut gate = VoiceGate::new(Sensitivity::Normal);
+ for _ in 0..5 {
+ gate.detect(&[0i16; FRAME_SAMPLES]);
+ }
+ assert_eq!(gate.pending_len, 5 * OUT_PER_FRAME - 6 * WINDOW);
+ }
+
+ fn rms_dbfs(f: &Frame) -> f32 {
+ let p = f.iter().map(|s| (f32::from(*s) / 32_768.0).powi(2)).sum::() / FRAME_SAMPLES as f32;
+ 10.0 * p.max(1e-18).log10()
+ }
+
+ /// Index of the first clearly voiced frame of the fixture. The recording's own noise floor is about
+ /// -30 dBFS; voiced speech is above -24 dBFS.
+ fn first_loud(frames: &[Frame]) -> usize { frames.iter().position(|f| rms_dbfs(f) >= -24.0).expect("loud frame") }
+
+ #[test]
+ fn speech_opens_the_gate_with_preroll_and_no_duplicate() {
+ let speech = speech_frames();
+ let lead = 10;
+ let mut frames = silence(lead);
+ frames.extend_from_slice(&speech);
+ frames.extend(silence(60));
+ let speech_start = lead + first_loud(&speech);
+ let mut gate = VoiceGate::new(Sensitivity::Normal);
+ let mut first_onset = None;
+ let mut first_held = 0;
+ let mut since_end = 0; // frames held since the last spurt ended
+ let mut open = false;
+ let mut ended_at = None;
+ for (i, f) in frames.iter().enumerate() {
+ match gate.push(f) {
+ Decision::Start => {
+ assert!(!open);
+ let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
+ let n = gate.take_preroll(&mut buf);
+ // First spurt after the reset: everything held since it (bounded); later spurts: the
+ // normal preroll. Oldest first, never the current frame.
+ let expected = if first_onset.is_none() { i.min(MAX_PREROLL_FRAMES) } else { PREROLL_FRAMES.min(since_end) };
+ assert_eq!(n, expected, "spurt at {i}");
+ for (k, p) in buf[..n].iter().enumerate() {
+ assert_eq!(p, &frames[i - n + k]);
+ }
+ if first_onset.is_none() {
+ first_onset = Some(i);
+ first_held = n;
+ }
+ open = true;
+ }
+ Decision::Send => assert!(open),
+ Decision::SendAndEnd => {
+ assert!(open);
+ open = false;
+ since_end = 0;
+ if i >= lead + speech.len() {
+ ended_at.get_or_insert(i);
+ }
+ }
+ Decision::Hold => {
+ assert!(!open);
+ since_end += 1;
+ }
+ }
+ }
+ let onset = first_onset.expect("speech must open the gate");
+ // The gate decides within 3 frames (60 ms) of the first loud frame, and what it sends reaches back
+ // before it, so the onset is not clipped.
+ assert!(onset >= speech_start && onset <= speech_start + 3, "onset at {onset}, loud speech at {speech_start}");
+ assert!(onset - first_held <= speech_start, "first sent frame {} after the loud start {speech_start}", onset - first_held);
+ // The last spurt ends in the trailing silence: after at least the hangover, and not much later.
+ let speech_end = lead + speech.len();
+ let ended = ended_at.expect("the spurt must end in the trailing silence");
+ assert!(ended >= speech_end + HANGOVER_FRAMES as usize - 1 && ended <= speech_end + HANGOVER_FRAMES as usize + 15, "ended at {ended}, speech ended at {speech_end}");
+ }
+
+ /// First spurt of `frames` fed to `gate`: (index of the Start, frames sent before the current one).
+ fn first_spurt(gate: &mut VoiceGate, frames: &[Frame]) -> Option<(usize, usize)> {
+ for (i, f) in frames.iter().enumerate() {
+ if gate.push(f) == Decision::Start {
+ let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
+ let n = gate.take_preroll(&mut buf);
+ for (k, p) in buf[..n].iter().enumerate() {
+ assert_eq!(p, &frames[i - n + k], "sent frames are the held ones, in order");
+ }
+ return Some((i, n));
+ }
+ }
+ None
+ }
+
+ #[test]
+ fn speech_from_the_first_frame_is_sent_in_full() {
+ // Loud speech starting at frame 0 of a fresh gate (connect, unmute, mode change while talking).
+ let speech = speech_frames();
+ let from_loud = &speech[first_loud(&speech)..];
+ for s in [Sensitivity::High, Sensitivity::Normal, Sensitivity::Low] {
+ let mut gate = VoiceGate::new(s);
+ let (onset, held) = first_spurt(&mut gate, from_loud).expect("speech must open the gate");
+ // The warm-up delays the decision (measured: at most 3 frames past it), but every frame from
+ // frame 0 is sent: nothing of the first word is lost, it just arrives up to ~260 ms later.
+ assert!(onset <= WARMUP_FRAMES as usize + 3, "{s:?}: opened at frame {onset}");
+ assert_eq!(held, onset, "{s:?}: frames 0..{onset} must all be sent before frame {onset}");
+ }
+ }
+
+ #[test]
+ fn speech_right_after_a_reset_is_sent_in_full() {
+ // Talking through an unmute: the gate is reset at the mute; the first frame after it must be sent.
+ let speech = speech_frames();
+ let mut gate = VoiceGate::new(Sensitivity::Normal);
+ run(&mut gate, &speech[..60]);
+ gate.reset();
+ let after = &speech[60..];
+ let (onset, held) = first_spurt(&mut gate, after).expect("speech must open the gate");
+ assert_eq!(held, onset, "frames since the reset are all sent");
+ assert!(onset <= WARMUP_FRAMES as usize + 3);
+ }
+
+ #[test]
+ fn the_natural_end_of_a_spurt_does_not_reset_the_detector() {
+ let speech = speech_frames();
+ let mut frames = speech.clone();
+ frames.extend(silence(HANGOVER_FRAMES as usize + 10));
+ frames.extend_from_slice(&speech);
+ let mut gate = VoiceGate::new(Sensitivity::Normal);
+ let mut starts = Vec::new();
+ for f in &frames {
+ if gate.push(f) == Decision::Start {
+ let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
+ starts.push(gate.take_preroll(&mut buf));
+ }
+ }
+ assert!(starts.len() >= 2, "{starts:?}");
+ // Only the first spurt after the reset carries the startup buffer; later ones the normal preroll,
+ // and no warm-up was re-armed in between.
+ assert!(starts[1..].iter().all(|n| *n <= PREROLL_FRAMES), "{starts:?}");
+ assert_eq!(gate.warmup, 0);
+ }
+
+ #[test]
+ fn decimator_output_stays_in_the_detector_range() {
+ // Full-scale square wave: the low-pass rings above full scale; the detector input is clamped.
+ let mut d = Decimator::new();
+ let mut peak = 0.0f32;
+ for _ in 0..3 {
+ let mut f = [0i16; FRAME_SAMPLES];
+ for (n, s) in f.iter_mut().enumerate() {
+ *s = if (n / 48) % 2 == 0 { i16::MAX } else { i16::MIN };
+ }
+ let mut out = [0.0; OUT_PER_FRAME];
+ d.process(&f, &mut out);
+ peak = out.iter().fold(peak, |m, x| m.max(x.abs()));
+ }
+ assert!(peak <= 1.0 && peak > 0.9, "peak {peak}");
+ }
+
+ #[test]
+ fn silence_steady_noise_and_clicks_stay_closed() {
+ // Synthetic, deterministic noise (not recordings): the detector is statistical, so this checks the
+ // chosen thresholds keep these inputs closed, not that every real noise does.
+ for (name, frames) in [("silence", silence(250)), ("steady noise", steady_noise(250)), ("clicks", clicks(250))] {
+ for s in [Sensitivity::High, Sensitivity::Normal, Sensitivity::Low] {
+ let mut gate = VoiceGate::new(s);
+ let (_, total) = run(&mut gate, &frames);
+ assert_eq!(total, 0, "{name} opened the gate at {s:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn hangover_keeps_short_pauses_and_ends_after_it() {
+ let speech = speech_frames();
+ // A continuously voiced stretch of the fixture, a 160 ms pause, the same stretch again, then silence.
+ let voiced = &speech[60..90];
+ let mut frames = voiced.to_vec();
+ frames.extend(silence(8));
+ frames.extend_from_slice(voiced);
+ let speech_end = frames.len();
+ frames.extend(silence(60));
+ let mut gate = VoiceGate::new(Sensitivity::Normal);
+ let (sent, _) = run(&mut gate, &frames);
+ let starts = sent.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(sent[0]);
+ assert_eq!(starts, 1, "a short pause must not split the spurt");
+ let last_sent = sent.iter().rposition(|s| *s).expect("sent");
+ assert!(last_sent >= speech_end + HANGOVER_FRAMES as usize - 1, "closed at {last_sent} before the hangover ran out");
+ assert!(!sent[sent.len() - 1], "gate must be closed after the hangover");
+ }
+
+ #[test]
+ fn reset_forgets_preroll_and_open_spurt() {
+ let speech = speech_frames();
+ let mut gate = VoiceGate::new(Sensitivity::Normal);
+ run(&mut gate, &speech[..40]);
+ assert!(gate.is_active());
+ gate.reset();
+ assert!(!gate.is_active());
+ let mut buf = [[0i16; FRAME_SAMPLES]; MAX_PREROLL_FRAMES];
+ assert_eq!(gate.take_preroll(&mut buf), 0);
+ // After a reset only new audio is considered: silence keeps it closed.
+ let (_, total) = run(&mut gate, &silence(30));
+ assert_eq!(total, 0);
+ }
+
+ #[test]
+ fn sensitivity_changes_the_probability_threshold() {
+ let mut gate = VoiceGate::new(Sensitivity::High);
+ assert!(gate.sensitivity().threshold() < Sensitivity::Normal.threshold());
+ gate.set_sensitivity(Sensitivity::Low);
+ assert_eq!(gate.threshold, Sensitivity::Low.threshold());
+ assert!(Sensitivity::Low.threshold() > Sensitivity::Normal.threshold());
+ }
+}
+
diff --git a/core/tests/fixtures/README.md b/core/tests/fixtures/README.md
new file mode 100644
index 0000000..eb9a5c8
--- /dev/null
+++ b/core/tests/fixtures/README.md
@@ -0,0 +1,21 @@
+# Test fixtures
+
+## `speech-librivox-48k.wav`
+
+Real human speech used to test the voice activation detector (`core/src/vad.rs`) and, looped with silence, as
+the fake capture input of `scripts/smoke-voice-vad.mjs`. Test data only; not shipped in any package.
+
+- Source: LibriVox, *Short Poetry Collection 001*, "Jenny Kissed Me" by Leigh Hunt, file
+ `jenny_hunt_py_64kb.mp3` from
+ (`https://archive.org/download/short_poetry_001_librivox/jenny_hunt_py_64kb.mp3`, SHA-256 of the downloaded
+ MP3 `9394cb36b156957c6770b50c77181ab17ecaf7d88ed2cb337a822fd8897b768a`).
+- License: public domain. LibriVox recordings are dedicated to the public domain; the archive.org item states
+ .
+- Content: 4.0 s starting at 2.0 s of the recording (the LibriVox introduction, read by a volunteer).
+- Conversion (FFmpeg 7.1.1): `ffmpeg -ss 2.0 -t 4.0 -i jenny_hunt_py_64kb.mp3 -ac 1 -ar 48000 -c:a pcm_s16le
+ -map_metadata -1 -fflags +bitexact -flags:a +bitexact speech-librivox-48k.wav` → 48 kHz mono 16-bit PCM WAV,
+ 384 044 bytes, SHA-256 `d0e63d939369a0d51bbb42aa36fb5fe185b19e4f4aa3070c10bef28df593ed38`.
+- Character: the MP3's own noise floor is about -30 dBFS; voiced speech is above -24 dBFS (the tests use that
+ level to locate the first loud frame). Mean -25.4 dB, peak -5.6 dB.
+
+The noise inputs of the tests (steady broadband noise, clicks) are generated in code and are synthetic.
diff --git a/core/tests/fixtures/speech-librivox-48k.wav b/core/tests/fixtures/speech-librivox-48k.wav
new file mode 100644
index 0000000..22fd94e
Binary files /dev/null and b/core/tests/fixtures/speech-librivox-48k.wav differ
diff --git a/docs/bridge.md b/docs/bridge.md
index 1e0e13d..dbabc5a 100644
--- a/docs/bridge.md
+++ b/docs/bridge.md
@@ -99,7 +99,7 @@ branch on human-readable message wording.
| `audio_codec_unsupported` | current channel codec is not Opus (legacy Speex/CELT): we cannot transmit there (event, once per burst); received non-Opus voice is reported once per speaker |
| `rename_not_persisted` | server accepted the new nickname but saving it failed; see §4.3 |
| `not_found` | requested icon/avatar/banner does not exist (`detail.builtin:true` for built-in icon ids) |
-| `media_too_large` | file exceeds the size limit of its kind (§4.16) |
+| `media_too_large` | file exceeds the size limit of its kind (§4.17) |
| `media_unsupported` | file is not a recognized image, or a banner reference the core cannot fetch |
| `external_media` | banner or avatar lives at an `https://` URL (`detail.url` for banners, `detail.urls` for avatars); main may fetch it itself |
| `io` | data dir I/O failure |
@@ -195,20 +195,43 @@ Initial state at process start: both `false`.
One 20 ms microphone frame: base64 (standard alphabet, padded) of **960 signed
16-bit little-endian mono samples at 48 kHz = 1920 bytes** (2560 base64 chars).
-The renderer gates push-to-talk / voice activation: it sends frames only while
-transmitting and `audio_end` when it stops. The core Opus-encodes 20 ms frames
-with the **current channel's codec**: Opus Voice (mono) or Opus Music (stereo — the
+In transmit mode `direct` (see 4.11) the renderer decides: it sends frames only while
+push-to-talk is held or the open microphone is on, and `audio_end` when it stops; the core
+sends every frame. In mode `vad` the renderer sends frames continuously while connected and
+not muted, and the core's voice detector decides which are sent. The core Opus-encodes 20 ms
+frames with the **current channel's codec**: Opus Voice (mono) or Opus Music (stereo — the
mono frame is duplicated to both channels). Legacy Speex/CELT channels →
`audio_codec_unsupported` event and nothing is sent. Outgoing queue bound: 10 frames
(200 ms); on overflow the oldest frames are dropped (`audio_overflow` event).
If no frame arrives for 200 ms during a burst the core ends the burst itself.
-Not connected → frames dropped with one `not_connected` error event per burst.
+Not connected → frames dropped with one `not_connected` error event per burst. Muted,
+deafened, or not allowed to talk by the server → frames dropped with one `audio_muted` event
+per burst; in mode `vad` the detector state and preroll are discarded as well.
### 4.10 `audio_end` — no args (no `id`, no response)
-Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet).
+Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet). In mode
+`vad` it also discards the detector state and preroll (capture stopped or the renderer stopped
+forwarding).
-### 4.11 `stream_list` — `{client_id?: number}`
+### 4.11 `set_transmit` — `{mode: "direct"|"vad", sensitivity?: "high"|"normal"|"low"}`
+
+Selects who decides when voice is sent. `direct` (initial state at process start): every
+forwarded frame is sent. `vad`: voice activation in the core (`core/src/vad.rs`): frames are
+decimated to 16 kHz and scored by the earshot voice detector (embedded model, 16 ms windows,
+probability 0–1). The gate opens after 3 consecutive windows at or above the threshold
+(`high` 0.45, `normal` 0.6 — default, `low` 0.75) and sends the 5 frames (100 ms) held before
+the onset, then the current frame. While open, a window counts as voiced down to 0.15 below the
+threshold; the gate closes 20 frames (400 ms) after the last voiced frame. It cannot open
+during the first 10 frames after a reset. Detector, filter history and preroll are reset on
+every `set_transmit`, `audio_end`, mute/deafen, disconnect, channel or codec change and when
+the server does not allow talking. `sensitivity` is accepted only with `vad`.
+Before answering, the core discards frames still queued from the previous mode and ends any
+open burst; the renderer forwards nothing until it has this answer.
+Result `{"mode":"direct"}` or `{"mode":"vad","sensitivity":"normal"}`. `audio_state.transmitting`
+is true only while voice packets are actually being sent.
+
+### 4.12 `stream_list` — `{client_id?: number}`
TS6 screenshare discovery. Sends `requeststreaminfo clid=` for `client_id`, or for
every other client in our current channel when omitted. Result:
@@ -223,28 +246,28 @@ Live behaviour (TS6 6.0.0-beta13.1): every `requeststreaminfo` is answered `ok`,
`viewer`, `viewer_limit`; for a non-streaming client the item has only `return_code`.
So: "is streaming" ⇔ the `notifystreaminfo` item has `id`.
-### 4.12 `stream_join` — `{stream_id: string, client_id: number, message?: string}`
+### 4.13 `stream_join` — `{stream_id: string, client_id: number, message?: string}`
Sends `joinstreamrequest id= clid= msg= is_remove=0`.
Result `{}` (or `server_error`). The SDP offer arrives as `stream` event
`notifyrespondjoinstreamrequest` (`decision=1`, `offer=`).
-### 4.13 `stream_signal` — `{stream_id: string, client_id: number, json: object}`
+### 4.14 `stream_signal` — `{stream_id: string, client_id: number, json: object}`
Sends `streamsignaling id= clid= json=`.
Examples of `json`: `{"cmd":"answer","args":{"answer":""}}`,
`{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`.
Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`.
-### 4.14 `stream_leave` — `{stream_id: string, client_id: number}`
+### 4.15 `stream_leave` — `{stream_id: string, client_id: number}`
Sends `joinstreamrequest id=… clid=… msg= is_remove=1`. Result `{}`.
-### 4.15 `shutdown` — no args
+### 4.16 `shutdown` — no args
Disconnects cleanly if needed, responds `{}`, exits 0.
-### 4.16 Media: `fetch_icon`, `fetch_avatar`, `fetch_banner`, `fetch_server_banner`
+### 4.17 Media: `fetch_icon`, `fetch_avatar`, `fetch_banner`, `fetch_server_banner`
Read-only downloads over TeamSpeak file transfer from the connected server. No paths
cross the bridge: the core derives the server file from ids it already knows.
@@ -328,7 +351,7 @@ Full replacement of the server view, emitted after connect and after every chang
`"speex_ultrawideband"`, `"celt_mono"` or `null` if unknown. Only Opus channels can
transmit; the UI should show the reason for others.
- `client_type`: `"normal"` or `"query"`. `uid` may be `null` if not visible.
-- `icon_id`: TeamSpeak icon id or `null` (0 = none). Fetch with `fetch_icon` (§4.16).
+- `icon_id`: TeamSpeak icon id or `null` (0 = none). Fetch with `fetch_icon` (§4.17).
- Groups: `server_groups`/`channel_groups` are the server's group catalogs (sent to every
client on connect; sorted by `sort_id`, then `id`). A client's `server_groups` and
`channel_group_id` reference them. `name_mode` (`none|before|after`) is TeamSpeak's
diff --git a/docs/evidence/runtime/2026-10-24-vad-dev/80-audio-settings-voice-activation.png b/docs/evidence/runtime/2026-10-24-vad-dev/80-audio-settings-voice-activation.png
new file mode 100644
index 0000000..6331759
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-dev/80-audio-settings-voice-activation.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-dev/81-b-hears-a.png b/docs/evidence/runtime/2026-10-24-vad-dev/81-b-hears-a.png
new file mode 100644
index 0000000..eda33a9
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-dev/81-b-hears-a.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-dev/result.json b/docs/evidence/runtime/2026-10-24-vad-dev/result.json
new file mode 100644
index 0000000..d462973
--- /dev/null
+++ b/docs/evidence/runtime/2026-10-24-vad-dev/result.json
@@ -0,0 +1,93 @@
+{
+ "startedAt": "2026-10-24T06:25:21.850Z",
+ "server": "10.10.10.160:9987",
+ "steps": [
+ {
+ "name": "input",
+ "at": "2026-10-24T06:25:21.852Z",
+ "file": "silence 2 s + speech-librivox-48k.wav (4 s) + silence 3 s, looped",
+ "seconds": 9
+ },
+ {
+ "name": "A voice activation confirmed by the core",
+ "at": "2026-10-24T06:25:24.624Z",
+ "coreMode": {
+ "mode": "vad",
+ "sensitivity": "normal"
+ }
+ },
+ {
+ "name": "both connected, channel empty otherwise",
+ "at": "2026-10-24T06:25:27.832Z",
+ "channel": "Welcome to the club buddy"
+ },
+ {
+ "name": "speech and silence",
+ "at": "2026-10-24T06:25:46.339Z",
+ "spurts": 6,
+ "onMs": [
+ 738,
+ 1979,
+ 622,
+ 744,
+ 1975,
+ 556
+ ],
+ "offMs": [
+ 1305,
+ 0,
+ 556,
+ 4732,
+ 0,
+ 561,
+ 3927
+ ],
+ "onFraction": 0.36,
+ "bHeardA": true,
+ "bFramesDuringSilence": [
+ 0,
+ 0
+ ]
+ },
+ {
+ "name": "muted: nothing sent",
+ "at": "2026-10-24T06:25:55.427Z",
+ "transmitted": false,
+ "bReceivedFrames": 0
+ },
+ {
+ "name": "deafened: nothing sent",
+ "at": "2026-10-24T06:26:04.472Z",
+ "transmitted": false,
+ "bReceivedFrames": 0
+ },
+ {
+ "name": "push to talk not held: nothing sent",
+ "at": "2026-10-24T06:26:13.579Z",
+ "transmitted": false,
+ "bReceivedFrames": 0
+ },
+ {
+ "name": "voice activation again: speech sent",
+ "at": "2026-10-24T06:26:14.191Z"
+ },
+ {
+ "name": "disconnected",
+ "at": "2026-10-24T06:26:17.261Z",
+ "transmitted": false
+ },
+ {
+ "name": "restart: voice activation persisted and confirmed",
+ "at": "2026-10-24T06:26:18.635Z",
+ "transmitMode": "vad",
+ "vadSensitivity": "normal",
+ "coreMode": {
+ "mode": "vad",
+ "sensitivity": "normal"
+ }
+ }
+ ],
+ "console": [],
+ "ok": true,
+ "pageErrors": 0
+}
\ No newline at end of file
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/en-keyboard-880.png b/docs/evidence/runtime/2026-10-24-vad-i18n/en-keyboard-880.png
new file mode 100644
index 0000000..49325d4
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-i18n/en-keyboard-880.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/en-voice-activation-880.png b/docs/evidence/runtime/2026-10-24-vad-i18n/en-voice-activation-880.png
new file mode 100644
index 0000000..6a44646
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-i18n/en-voice-activation-880.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/en-voice-activation-help-880.png b/docs/evidence/runtime/2026-10-24-vad-i18n/en-voice-activation-help-880.png
new file mode 100644
index 0000000..6a44646
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-i18n/en-voice-activation-help-880.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/result.json b/docs/evidence/runtime/2026-10-24-vad-i18n/result.json
new file mode 100644
index 0000000..464f521
--- /dev/null
+++ b/docs/evidence/runtime/2026-10-24-vad-i18n/result.json
@@ -0,0 +1,24 @@
+{
+ "ok": true,
+ "steps": [
+ {
+ "language": "en",
+ "bad": [],
+ "overflow": false,
+ "radio": "vad",
+ "sensitivity": "normal",
+ "capturing": false,
+ "connection": "disconnected"
+ },
+ {
+ "language": "ru",
+ "bad": [],
+ "overflow": false,
+ "radio": "vad",
+ "sensitivity": "normal",
+ "capturing": false,
+ "connection": "disconnected"
+ }
+ ],
+ "pageErrors": []
+}
\ No newline at end of file
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/ru-keyboard-880.png b/docs/evidence/runtime/2026-10-24-vad-i18n/ru-keyboard-880.png
new file mode 100644
index 0000000..6582b21
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-i18n/ru-keyboard-880.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/ru-voice-activation-880.png b/docs/evidence/runtime/2026-10-24-vad-i18n/ru-voice-activation-880.png
new file mode 100644
index 0000000..8c4b1cb
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-i18n/ru-voice-activation-880.png differ
diff --git a/docs/evidence/runtime/2026-10-24-vad-i18n/ru-voice-activation-help-880.png b/docs/evidence/runtime/2026-10-24-vad-i18n/ru-voice-activation-help-880.png
new file mode 100644
index 0000000..8c4b1cb
Binary files /dev/null and b/docs/evidence/runtime/2026-10-24-vad-i18n/ru-voice-activation-help-880.png differ
diff --git a/docs/evidence/vad-0.1.3.md b/docs/evidence/vad-0.1.3.md
new file mode 100644
index 0000000..845d89b
--- /dev/null
+++ b/docs/evidence/vad-0.1.3.md
@@ -0,0 +1,72 @@
+# 0.1.3 voice activation: design, measurements, limits
+
+## What it is
+A third transmission mode. The renderer forwards 20 ms frames (48 kHz mono) to the core continuously while
+connected and not muted or deafened; the core decides which are sent (`core/src/vad.rs`, bridge `set_transmit`,
+`docs/bridge.md` §4.11). Push to talk and the open microphone keep the previous path (`direct`: every forwarded
+frame is sent). There is one decision owner per mode: the renderer for `direct`, the core for `vad`.
+
+- Input: the capture after Chromium's WebRTC processing as configured in Settings → Audio (noise suppression,
+ echo cancellation, gain control; the applied values are logged from `track.getSettings()` at capture start).
+- Detector: earshot 1.2.2 (pure Rust, MIT OR Apache-2.0, pinned), a small embedded neural network returning a
+ voice probability 0–1 per 16 ms window at 16 kHz. It is a statistical voice detector: no speech recognition,
+ no cloud, nothing stored. Upstream accuracy/speed claims are not repeated here as measurements.
+- Resampling: windowed-sinc low-pass (63 taps, Blackman, 7 kHz cut-off) and decimation by 3; the filter history
+ carries over between frames (test: frame-wise output equals a direct convolution over the whole signal);
+ output clamped to [-1, 1] (a full-scale square wave rings above 1).
+- Windows: each 20 ms frame yields 320 samples at 16 kHz, i.e. one or two 256-sample windows; the remainder is
+ kept for the next frame (test: 5 frames → 6 windows + 64 samples pending).
+- Gate: opens after 3 consecutive windows at or above the threshold (High 0.45, Normal 0.6 — default, Low 0.75);
+ while open, a window counts down to 0.15 below the threshold; closes 400 ms (20 frames) after the last voiced
+ frame. Sends the 5 frames (100 ms) before the onset, then the current frame (never duplicated).
+- Reset (detector, filter history, held frames): mode change, `audio_end` (capture stopped / renderer stopped
+ forwarding), mute, deafen, disconnect, channel or codec change, server talk denial. Not at the natural end of
+ a spurt. After a reset the gate cannot open for 10 frames (the freshly reset network scores the first ~150 ms
+ of any input higher than it settles to), but every frame since the reset is kept (at most 15 frames = 300 ms)
+ and sent with the first spurt.
+- No per-frame heap allocation or logging; fixed buffers allocated when the mode is applied.
+
+## Mode handshake (renderer ↔ core)
+`set_transmit` is answered only after the core discarded frames queued under the previous mode (control
+messages use a separate channel and are not affected) and ended any open burst. The renderer forwards nothing
+until the answer matches the preferences; a failed change shows an error and sends nothing (never open
+microphone). Mute, deafen and disconnect stop forwarding immediately. The own "talking" indicator is the core's
+`audio_state.transmitting`, true only while voice packets are sent. Tests: `test/voice-transmit.test.mjs`.
+
+## Measurements (deterministic unit tests, `cargo test`, x64 Windows)
+Speech: `core/tests/fixtures/speech-librivox-48k.wav` (public domain, provenance in the fixture README).
+Noise: generated in the tests (synthetic, not recordings).
+
+| Case | Result |
+|---|---|
+| Speech after 10 silent frames (Normal) | decides 40 ms after the first loud frame (High: 0 ms, Low: 40 ms); preroll reaches before it |
+| Speech from frame 0 of a fresh/reset gate (all sensitivities) | opens at frame 10 (200 ms); frames 0–9 are all sent before frame 10 → nothing lost, first spurt 200 ms late |
+| 4 s of speech after 10 silent frames, then silence | High: 2 spurts, 209 frames sent; Normal: 3 spurts, 202; Low: 3 spurts, 198 (200 speech frames; counts include preroll and hangover; natural pauses longer than the hangover close the gate) |
+| Silence, steady broadband noise (−31 dBFS), clicks every 200 ms, 5 s each | gate stays closed at High, Normal and Low |
+| 160 ms pause inside speech | one spurt (not split) |
+| End of speech | closes 23–26 frames (460–520 ms) after the last speech frame of the fixture |
+
+Added latency: within a spurt none (frames are sent as they arrive). At an onset the preroll (100 ms) goes
+out at once, so the receiver plays the spurt from up to ~100 ms before the decision; the decision itself comes
+0–60 ms after the first loud frame. Right after a reset the first spurt is up to ~260 ms late.
+
+ARM64: the same unit tests run in CI under qemu-aarch64 (emulated); native Apple Silicon/Asahi hardware is not
+tested.
+
+## Real program (`scripts/smoke-voice-vad.mjs`, `runtime/2026-10-24-vad-dev/`)
+Two TeamsPeach instances on 10.10.10.160 in the otherwise empty default channel (the script refuses occupied
+channels). A's capture is Chromium's fake device fed from a WAV built from the speech fixture (2 s silence, 4 s
+speech, 3 s silence, looped); B never transmits and plays at zero gain.
+
+- Core confirms `vad` before connecting; 6 spurts over 2 loops, on-fraction 0.36; during the long silences B
+ receives 0 frames.
+- Muted, deafened, push to talk not held: nothing sent, B receives 0 frames. Back to voice activation: sent again.
+- Disconnected: nothing sent. After restarting A, `transmitMode: vad` and the sensitivity are persisted and the
+ new core confirms the mode.
+
+## Limits
+- Statistical detector: loud speech-like sound (TV, other voices) can open the gate; quiet speech in heavy
+ noise can be missed. Noise suppression helps, it does not make the detector exact.
+- Not proven with a live microphone, with an official TeamSpeak 6 receiver, or on native ARM64 hardware.
+- Two TeamsPeach clients agreeing is not interoperability proof; the transmitted packets are the same Opus
+ voice packets as push to talk, which the user confirmed reach the official client.
diff --git a/docs/i18n.md b/docs/i18n.md
index 4595e8a..d033dce 100644
--- a/docs/i18n.md
+++ b/docs/i18n.md
@@ -60,3 +60,9 @@ The isolated smoke does not establish live-server call or active-stream continui
### Recorded development run, 2026-10-24
The targeted command above passed **14/14 tests**. The real Electron smoke passed with no renderer page errors on Electron 44.9.3 / Windows x64: fresh-profile English, all seven categories and both actual-device context menus in both languages, live notification translation, Russian persistence after restart, and switching back to English. Capture remained off, the UID/nickname and unrelated preferences stayed unchanged, and the connection-form draft survived. No horizontal document overflow was detected at 880×560. The generated result and matching English/Russian screenshots are under `docs/evidence/runtime/i18n-2026-10-24/`; the temporary profile was deleted. Screenshots show disposable smoke identity data and real OS-provided device labels, not an owner's identity or server data.
+
+### Voice activation settings, 0.1.3 development UI
+
+The single transmission-mode selector is in Settings → Audio: push to talk, voice activation, or an explicitly continuous open microphone. Keyboard retains the push-to-talk key binding. The `transmit.*` messages distinguish local speech detection from the input-level meter, recording, and speech recognition/transcription. They describe the approximate 0.4-second transmission tail and explain that noise suppression cannot guarantee rejection of television audio, other voices, or noise. `error.transmit_mode` retains the same `{detail}` placeholder in both catalogs.
+
+A bounded real-Electron check on 2026-10-24 used a fresh disposable profile at 880×560, with no forced locale, server connection, or microphone test/capture. English and Russian screenshots of the voice-activation card and Keyboard panel are in `docs/evidence/runtime/2026-10-24-vad-i18n/`, alongside `result.json`. All three sensitivity values were selected through the UI and observed in the saved preferences. Catalog-backed card labels matched the active locale, with no horizontal overflow or renderer errors. UID/nickname and audio state were unchanged; capture and sending stayed off. The run confirmed fresh English/dark/PTT defaults, restored PTT and English, and removed the temporary profile. This proves localized UI wiring and disconnected preference behavior, not speech/noise classification quality or live transmission; those remain separate audio/backend verification.
diff --git a/package-lock.json b/package-lock.json
index 758a727..8b26063 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "teamspeach",
- "version": "0.1.2",
+ "version": "0.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "teamspeach",
- "version": "0.1.2",
+ "version": "0.1.3",
"license": "UNLICENSED",
"dependencies": {
"electron-updater": "6.8.11",
diff --git a/package.json b/package.json
index c998a3f..6a8aec6 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "teamspeach",
"productName": "TeamsPeach",
- "version": "0.1.2",
+ "version": "0.1.3",
"description": "Desktop TeamSpeak 6 client: voice, chat and TS6 screenshare viewing",
"main": "app/main/main.js",
"private": true,
diff --git a/scripts/smoke-voice-vad.mjs b/scripts/smoke-voice-vad.mjs
new file mode 100644
index 0000000..c1d73c3
--- /dev/null
+++ b/scripts/smoke-voice-vad.mjs
@@ -0,0 +1,232 @@
+// Voice activation through the real program: two TeamsPeach instances (disposable profiles) on a live server.
+// A's capture device is Chromium's fake device fed from a WAV file built from the public-domain speech
+// fixture (core/tests/fixtures/speech-librivox-48k.wav): 2 s silence, 4 s speech, 3 s silence, looped.
+// Everything after getUserMedia is the real path (capture processing, worklet, IPC, core voice detector,
+// Opus, server, B's decoder). B listens at zero playback gain and never transmits.
+//
+// node scripts/smoke-voice-vad.mjs --server 10.10.10.160:9987 --out docs/evidence/runtime/
+//
+// Refuses to run if anyone else is in the channel. Not an official-client interoperability test.
+import { launchApp } from './lib/electron-app.mjs';
+import { mkdirSync, writeFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const argv = process.argv.slice(2);
+const opt = (name, fallback) => (argv.indexOf(`--${name}`) >= 0 ? argv[argv.indexOf(`--${name}`) + 1] : fallback);
+const server = opt('server');
+if (!server) {
+ console.error('--server is required');
+ process.exit(2);
+}
+const out = path.resolve(root, opt('out', 'smoke-vad-out'));
+mkdirSync(out, { recursive: true });
+const result = { startedAt: new Date().toISOString(), server, steps: [], console: [] };
+const step = (name, data = {}) => {
+ result.steps.push({ name, at: new Date().toISOString(), ...data });
+ console.log(`[vad] ${name}`, JSON.stringify(data));
+};
+
+/** 48 kHz mono s16 WAV: silence, the speech fixture, silence. */
+function buildInput(file) {
+ const wav = readFileSync(path.join(root, 'core', 'tests', 'fixtures', 'speech-librivox-48k.wav'));
+ const dataAt = wav.indexOf('data') + 8;
+ const speech = wav.subarray(dataAt, dataAt + wav.readUInt32LE(dataAt - 4));
+ const pcm = Buffer.concat([Buffer.alloc(2 * 48000 * 2), speech, Buffer.alloc(3 * 48000 * 2)]);
+ const header = Buffer.alloc(44);
+ header.write('RIFF', 0);
+ header.writeUInt32LE(36 + pcm.length, 4);
+ header.write('WAVEfmt ', 8);
+ header.writeUInt32LE(16, 16);
+ header.writeUInt16LE(1, 20);
+ header.writeUInt16LE(1, 22);
+ header.writeUInt32LE(48000, 24);
+ header.writeUInt32LE(96000, 28);
+ header.writeUInt16LE(2, 32);
+ header.writeUInt16LE(16, 34);
+ header.write('data', 36);
+ header.writeUInt32LE(pcm.length, 40);
+ writeFileSync(file, Buffer.concat([header, pcm]));
+ return { seconds: pcm.length / 96000 };
+}
+
+const work = mkdtempSync(path.join(tmpdir(), 'teamspeach-vad-'));
+const inputWav = path.join(work, 'speech-loop.wav');
+const input = buildInput(inputWav);
+
+async function launch(label, nickname, args, profile = mkdtempSync(path.join(tmpdir(), `teamspeach-${label}-`))) {
+ const app = await launchApp({ profile, args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', ...args] });
+ const page = await app.firstWindow();
+ page.on('console', (m) => result.console.push(`${label} ${m.type()}: ${m.text()}`));
+ page.on('pageerror', (e) => result.console.push(`${label} pageerror: ${e.message}`));
+ if (nickname) {
+ await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 20000 });
+ await page.fill('#onboarding-nick', nickname);
+ await page.click('#onboarding-submit');
+ }
+ await page.waitForSelector('#view-app', { state: 'visible', timeout: 20000 });
+ return { app, page, profile };
+}
+
+const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
+const waitDiag = (page, fn, arg, timeout = 20000) => page.waitForFunction(fn, arg, { timeout });
+
+async function openAudioSettings(page) {
+ await page.click('#btn-settings');
+ await page.click('#settings-nav .nav-item[data-panel="audio"]');
+}
+async function setTransmit(page, mode) {
+ await openAudioSettings(page);
+ await page.check(`input[name="transmit"][value="${mode}"]`);
+ await page.click('#settings-back');
+}
+async function connect(page) {
+ await page.fill('#connect-address', server);
+ await page.click('#connect-submit');
+ await waitDiag(page, () => window.teamspeachDiagnostics.snapshot().conn === 'connected', null, 60000);
+}
+
+/** Samples A's core transmit state and B's received frames every 50 ms. */
+async function observe(a, b, aClid, ms) {
+ const samples = [];
+ const end = Date.now() + ms;
+ while (Date.now() < end) {
+ const [sa, sb] = await Promise.all([diag(a.page), diag(b.page)]);
+ samples.push({ t: Date.now(), tx: sa.audio.transmitting, heard: sb.talking.includes(aClid), rx: sb.voice.framesPlayed });
+ await a.page.waitForTimeout(50);
+ }
+ return samples;
+}
+
+/** Contiguous on/off segments of `key` with their durations in ms. */
+function segments(samples, key) {
+ const segs = [];
+ for (const s of samples) {
+ const last = segs.at(-1);
+ if (last && last.on === s[key]) last.end = s.t;
+ else segs.push({ on: s[key], start: s.t, end: s.t });
+ }
+ return segs.map((s) => ({ on: s.on, ms: s.end - s.start, start: s.start, end: s.end }));
+}
+
+function quiet(samples, label) {
+ const transmitted = samples.some((s) => s.tx);
+ const rxDelta = samples.at(-1).rx - samples[0].rx;
+ step(label, { transmitted, bReceivedFrames: rxDelta });
+ if (transmitted || rxDelta > 0) throw new Error(`${label}: audio was sent`);
+}
+
+let a;
+let b;
+let failed = null;
+try {
+ step('input', { file: 'silence 2 s + speech-librivox-48k.wav (4 s) + silence 3 s, looped', seconds: input.seconds });
+ a = await launch('A', 'PeachVadA', [`--use-file-for-fake-audio-capture=${inputWav}`]);
+ b = await launch('B', 'PeachVadB', []);
+
+ await openAudioSettings(b.page);
+ await b.page.$eval('#voice-volume', (el) => {
+ el.value = '0';
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ await b.page.click('#settings-back');
+
+ // A chooses voice activation before connecting; the core must confirm it.
+ await setTransmit(a.page, 'vad');
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().voice.coreMode?.mode === 'vad', null, 10000);
+ step('A voice activation confirmed by the core', { coreMode: (await diag(a.page)).voice.coreMode });
+ await openAudioSettings(a.page);
+ await a.page.screenshot({ path: path.join(out, '80-audio-settings-voice-activation.png') });
+ await a.page.click('#settings-back');
+
+ await connect(b.page);
+ await connect(a.page);
+ await a.page.waitForTimeout(1000);
+ const da = await diag(a.page);
+ const db = await diag(b.page);
+ const ownCid = (s) => s.clients.find((c) => c.id === s.ownClientId)?.channel;
+ const others = db.clients.filter((c) => c.type !== 'query' && c.channel === ownCid(db) && c.id !== da.ownClientId && c.id !== db.ownClientId);
+ if (da.ownChannel !== db.ownChannel) throw new Error('clients landed in different channels');
+ if (others.length > 0) throw new Error(`refusing to transmit: channel occupied by ${others.length} other client(s)`);
+ step('both connected, channel empty otherwise', { channel: da.ownChannel });
+ const aClid = da.ownClientId;
+
+ // Speech opens the gate, silence closes it after the hangover; B hears A only while A transmits.
+ const samples = await observe(a, b, aClid, 2 * input.seconds * 1000 + 500);
+ const tx = segments(samples, 'tx');
+ const on = tx.filter((s) => s.on);
+ const off = tx.filter((s) => !s.on);
+ const onMs = on.reduce((n, s) => n + s.ms, 0);
+ const total = samples.at(-1).t - samples[0].t;
+ // B's received frames in the middle of each long silence (skip 600 ms after the gate closed).
+ const rxInSilence = off.filter((s) => s.ms > 1500).map((s) => {
+ const inside = samples.filter((x) => x.t >= s.start + 600 && x.t <= s.end);
+ return inside.length ? inside.at(-1).rx - inside[0].rx : 0;
+ });
+ const heardWhileOn = samples.filter((s) => s.tx).some((s) => s.heard);
+ step('speech and silence', {
+ spurts: on.length,
+ onMs: on.map((s) => s.ms),
+ offMs: off.map((s) => s.ms),
+ onFraction: Number((onMs / total).toFixed(2)),
+ bHeardA: heardWhileOn,
+ bFramesDuringSilence: rxInSilence,
+ });
+ if (on.length < 1) throw new Error('speech never opened the gate');
+ if (!off.some((s) => s.ms >= 2500)) throw new Error('silence did not keep the gate closed');
+ if (!heardWhileOn) throw new Error('B never heard A');
+ if (rxInSilence.some((n) => n > 0)) throw new Error('B received audio during silence');
+ await b.page.screenshot({ path: path.join(out, '81-b-hears-a.png') });
+
+ // Mute, deafen, push-to-talk (not held): nothing is sent.
+ await a.page.click('#btn-mute');
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().audio.input_muted === true);
+ quiet(await observe(a, b, aClid, input.seconds * 1000), 'muted: nothing sent');
+ await a.page.click('#btn-mute');
+ await a.page.click('#btn-deafen');
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().audio.output_muted === true);
+ quiet(await observe(a, b, aClid, input.seconds * 1000), 'deafened: nothing sent');
+ await a.page.click('#btn-deafen');
+ await setTransmit(a.page, 'ptt');
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().voice.coreMode?.mode === 'direct', null, 10000);
+ quiet(await observe(a, b, aClid, input.seconds * 1000), 'push to talk not held: nothing sent');
+
+ // Back to voice activation: speech opens it again.
+ await setTransmit(a.page, 'vad');
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().audio.transmitting === true, null, 2 * input.seconds * 1000);
+ step('voice activation again: speech sent');
+
+ // Disconnected: nothing is sent.
+ await a.page.click('#btn-disconnect');
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().conn === 'disconnected', null, 20000);
+ const afterDisconnect = await observe(a, b, aClid, 3000);
+ step('disconnected', { transmitted: afterDisconnect.some((s) => s.tx) });
+ if (afterDisconnect.some((s) => s.tx)) throw new Error('transmitting while disconnected');
+
+ // The choice persists across a restart and is confirmed by the new core.
+ await a.app.close();
+ a = await launch('A2', null, [`--use-file-for-fake-audio-capture=${inputWav}`], a.profile);
+ await waitDiag(a.page, () => window.teamspeachDiagnostics.snapshot().voice.coreMode?.mode === 'vad', null, 20000);
+ const prefs = JSON.parse(readFileSync(path.join(a.profile, 'prefs.json'), 'utf8'));
+ step('restart: voice activation persisted and confirmed', { transmitMode: prefs.transmitMode, vadSensitivity: prefs.vadSensitivity, coreMode: (await diag(a.page)).voice.coreMode });
+ if (prefs.transmitMode !== 'vad') throw new Error('mode not persisted');
+} catch (err) {
+ failed = err;
+ step('FAILED', { error: String(err.stack || err) });
+} finally {
+ for (const x of [a, b]) {
+ if (x) await x.app.close().catch(() => {});
+ }
+ for (const x of [a, b]) {
+ if (x) rmSync(x.profile, { recursive: true, force: true });
+ }
+ rmSync(work, { recursive: true, force: true });
+}
+result.ok = !failed;
+result.pageErrors = result.console.filter((l) => l.includes('pageerror')).length;
+writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
+console.log(`[vad] ${result.ok ? 'OK' : 'FAILED'} → ${out}`);
+process.exit(result.ok ? 0 : 1);
diff --git a/scripts/smoke-voice.mjs b/scripts/smoke-voice.mjs
index e580525..1f53e90 100644
--- a/scripts/smoke-voice.mjs
+++ b/scripts/smoke-voice.mjs
@@ -56,10 +56,10 @@ async function setRange(page, selector, value) {
}, value);
}
-/** Transmit mode lives in Settings → Keys. */
+/** Transmit mode lives in Settings → Audio. */
async function setTransmit(page, mode) {
await page.click('#btn-settings');
- await page.click('#settings-nav .nav-item[data-panel="keys"]');
+ await page.click('#settings-nav .nav-item[data-panel="audio"]');
await page.check('input[name="transmit"][value="' + mode + '"]');
await page.click('#settings-back');
}
diff --git a/scripts/update-e2e.mjs b/scripts/update-e2e.mjs
index 5a43918..33ed979 100644
--- a/scripts/update-e2e.mjs
+++ b/scripts/update-e2e.mjs
@@ -5,7 +5,12 @@
// 4. the relaunched process reports the new version; its file matches the release feed's sha512;
// 5. start the new AppImage again: version, UID, nickname, bookmark and device pref are unchanged.
//
-// xvfb-run -a node scripts/update-e2e.mjs --from --to-tag v0.1.2-rc.2 --out update-e2e-out
+// xvfb-run -a node scripts/update-e2e.mjs --from --to-tag v0.1.3 --out update-e2e-out \
+// [--new-prefs '{"transmitMode":"vad","vadSensitivity":"high"}']
+//
+// The old app stores non-default values it supports itself (transmitMode 'open', devices, …). --new-prefs are
+// settings that exist only in the new version; they are applied after the update (the app is never connected to
+// a server in this run) and must survive one more restart.
//
// Runs AppImages with APPIMAGE_EXTRACT_AND_RUN=1 (no FUSE needed). Everything lives in a temp directory:
// profile, updater cache, the "installed" AppImage. The user's own installation is never touched.
@@ -23,10 +28,11 @@ const fromImage = opt('from');
const toTag = opt('to-tag');
const out = path.resolve(opt('out') ?? 'update-e2e-out');
if (!fromImage || !toTag || process.platform !== 'linux') {
- console.error('usage (Linux): update-e2e.mjs --from --to-tag [--out dir]');
+ console.error('usage (Linux): update-e2e.mjs --from --to-tag [--out dir] [--new-prefs ]');
process.exit(2);
}
const toVersion = toTag.slice(1);
+const newPrefs = opt('new-prefs') ? JSON.parse(opt('new-prefs')) : null;
const RELEASE = 'https://git.eeee.moe/TeamsPeach/client/releases/download';
mkdirSync(out, { recursive: true });
@@ -80,8 +86,22 @@ try {
const before = await diag(page);
const oldInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
const bookmark = { id: 'upd0001', name: 'Update proof', address: '192.0.2.10:9987' };
- await page.evaluate((b) => window.teamspeach.setPrefs({ savedServers: [b], inputDeviceId: 'update-proof-device' }), bookmark);
- step('old version running', { version: oldInfo.appVersion, uid: before.profile.uid, nickname: before.profile.nickname });
+ // Non-default values for every pref the OLD version knows (voice/transmit/devices included). Each key is set
+ // on its own so that a value the old schema rejects is simply skipped and reported.
+ const wanted = {
+ savedServers: [bookmark], inputDeviceId: 'update-proof-device', outputDeviceId: 'update-proof-output',
+ transmitMode: 'open', pttCode: 'F9', echoCancellation: false, noiseSuppression: false, autoGainControl: false,
+ voiceVolume: 150, streamVolume: 80, theme: 'light', lastAddress: '192.0.2.10:9987',
+ };
+ const oldKeys = Object.keys(await page.evaluate(() => window.teamspeach.getPrefs()));
+ const rejected = [];
+ for (const [key, value] of Object.entries(wanted)) {
+ if (!oldKeys.includes(key)) continue;
+ const res = await page.evaluate(([k, v]) => window.teamspeach.setPrefs({ [k]: v }), [key, value]);
+ if (!res || !res.ok) rejected.push(key);
+ }
+ const prefsBefore = await page.evaluate(() => window.teamspeach.getPrefs());
+ step('old version running', { version: oldInfo.appVersion, uid: before.profile.uid, nickname: before.profile.nickname, prefsBefore, rejected });
// 2. Real check + download from the public release server.
const checked = await page.evaluate(() => window.teamspeach.checkForUpdates());
@@ -155,19 +175,46 @@ try {
const prefs = await page.evaluate(() => window.teamspeach.getPrefs());
const state = await page.evaluate(() => window.teamspeach.getUpdateState());
await page.screenshot({ path: path.join(out, 'after-update.png') });
+ // The old choice must be what the new version shows before any new setting is applied.
+ const oldTransmitMode = prefsBefore.transmitMode;
+ const transmitModeKept = prefs.transmitMode === oldTransmitMode;
+ // 6. Optional: apply settings that exist only in the new version (e.g. VAD) while disconnected — the app
+ // never connects to a server in this run, so nothing is captured or sent — then restart and read them back.
+ let newSettings = null;
+ if (newPrefs) {
+ const applied = await page.evaluate((p) => window.teamspeach.setPrefs(p), newPrefs);
+ newSettings = { requested: newPrefs, applied: Boolean(applied && applied.ok), rejectedBy: applied && !applied.ok ? applied.message : null };
+ }
await app.close();
+ if (newPrefs) {
+ await sleep(2000);
+ ({ app, page } = await launch(newImage, 'new-restart'));
+ await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
+ const reread = await page.evaluate(() => window.teamspeach.getPrefs());
+ const again = await diag(page);
+ await app.close();
+ newSettings.afterRestart = Object.fromEntries(Object.keys(newPrefs).map((k) => [k, reread[k]]));
+ newSettings.kept = newSettings.applied && Object.keys(newPrefs).every((k) => JSON.stringify(reread[k]) === JSON.stringify(newPrefs[k]));
+ newSettings.uidSame = again.profile.uid === before.profile.uid;
+ step('new settings after restart', newSettings);
+ }
const kept = {
version: newInfo.appVersion,
uidSame: after.profile.uid === before.profile.uid,
nicknameSame: after.profile.nickname === before.profile.nickname,
bookmarkSame: JSON.stringify(prefs.savedServers) === JSON.stringify([bookmark]),
deviceSame: prefs.inputDeviceId === 'update-proof-device',
+ transmitMode: { old: oldTransmitMode, afterUpdate: prefs.transmitMode, kept: transmitModeKept },
+ // Every pref of the old version keeps its value; keys introduced by the new version are listed with defaults.
+ prefsChanged: Object.keys(prefsBefore).filter((k) => JSON.stringify(prefs[k]) !== JSON.stringify(prefsBefore[k])),
+ prefsAdded: Object.fromEntries(Object.keys(prefs).filter((k) => !(k in prefsBefore)).map((k) => [k, prefs[k]])),
updater: { phase: state.phase, target: state.target, mode: state.mode },
};
step('after update', kept);
- if (kept.version !== toVersion || !kept.uidSame || !kept.nicknameSame || !kept.bookmarkSame || !kept.deviceSame) {
+ if (kept.version !== toVersion || !kept.uidSame || !kept.nicknameSame || !kept.bookmarkSame || !kept.deviceSame || !transmitModeKept || kept.prefsChanged.length > 0) {
throw new Error('state after update is wrong');
}
+ if (newSettings && (!newSettings.kept || !newSettings.uidSame)) throw new Error('new-version settings were not kept across a restart');
} catch (err) {
failed = err;
step('FAILED', { error: err.message });
diff --git a/test/fixtures/renderer-env.mjs b/test/fixtures/renderer-env.mjs
new file mode 100644
index 0000000..7a9b8f9
--- /dev/null
+++ b/test/fixtures/renderer-env.mjs
@@ -0,0 +1,118 @@
+// Minimal browser environment for renderer modules under node:test: a fake DOM, Web Audio, getUserMedia and
+// the preload bridge. Import this module before any renderer module. No real devices, no network.
+
+const timeout = globalThis.setTimeout;
+globalThis.setTimeout = (fn, ms, ...args) => {
+ const id = timeout(fn, ms, ...args);
+ id.unref?.();
+ return id;
+};
+
+class FakeNode {
+ constructor() {
+ Object.assign(this, { style: {}, dataset: {}, children: [], textContent: '', value: '', className: '', hidden: false });
+ this.classList = { add() {}, remove() {}, toggle() {}, contains: () => false };
+ }
+ addEventListener() {}
+ removeEventListener() {}
+ setAttribute() {}
+ getAttribute() { return null; }
+ removeAttribute() {}
+ appendChild(child) { this.children.push(child); return child; }
+ replaceChildren(...children) { this.children = children; }
+ remove() {}
+ focus() {}
+ setPointerCapture() {}
+ querySelector() { return new FakeNode(); }
+ querySelectorAll() { return []; }
+ get firstElementChild() { return this.children[0] ?? new FakeNode(); }
+}
+const elements = new Map();
+globalThis.Node = FakeNode;
+globalThis.document = {
+ querySelector: (selector) => {
+ if (!elements.has(selector)) elements.set(selector, new FakeNode());
+ return elements.get(selector);
+ },
+ querySelectorAll: () => [],
+ createElement: () => new FakeNode(),
+ createElementNS: () => new FakeNode(),
+ createTextNode: () => new FakeNode(),
+ hasFocus: () => true,
+ documentElement: new FakeNode(),
+};
+globalThis.window = globalThis;
+globalThis.addEventListener = () => {};
+globalThis.requestAnimationFrame = () => 0;
+
+export const env = {
+ /** Frames forwarded to the core. */
+ sent: [],
+ /** Number of audio_end messages. */
+ ended: 0,
+ /** Bridge requests: { cmd, args }. */
+ requests: [],
+ /** Answers bridge requests; replace per test. */
+ respond: async () => ({ ok: true, result: {} }),
+ /** getUserMedia constraints, in order. */
+ gumCalls: [],
+ /** Tracks opened by getUserMedia. */
+ opened: [],
+ /** Capture worklet nodes created by the engine (last = current capture). */
+ worklets: [],
+ enumerate: async () => [
+ { kind: 'audioinput', deviceId: 'mic-2', label: 'Mic 2', groupId: 'g2' },
+ { kind: 'audiooutput', deviceId: 'out-1', label: 'Out 1', groupId: 'g3' },
+ ],
+ /** Delivers one 20 ms capture frame (silence by default) as the capture worklet would. */
+ frame(peak = 0.5) {
+ const node = env.worklets.at(-1);
+ node.port.onmessage?.({ data: { type: 'frame', pcm: new ArrayBuffer(1920), rms: peak / 2, peak } });
+ },
+};
+
+globalThis.teamspeach = {
+ onAudio() {},
+ sendAudioFrame: (f) => env.sent.push(f),
+ endAudio: () => { env.ended += 1; },
+ log() {},
+ request: (cmd, args) => {
+ env.requests.push({ cmd, args });
+ return env.respond(cmd, args);
+ },
+};
+
+Object.defineProperty(globalThis, 'navigator', {
+ configurable: true,
+ value: {
+ mediaDevices: {
+ addEventListener() {},
+ enumerateDevices: () => env.enumerate(),
+ getUserMedia: async (constraints) => {
+ env.gumCalls.push(constraints);
+ const id = constraints.audio.deviceId?.exact;
+ if (id === 'gone') throw Object.assign(new Error('Requested device not found'), { name: 'OverconstrainedError' });
+ const track = { label: id ?? 'default', muted: false, stopped: false, stop() { this.stopped = true; }, addEventListener() {}, getSettings: () => ({}) };
+ env.opened.push(track);
+ return { getTracks: () => [track], getAudioTracks: () => [track] };
+ },
+ },
+ },
+});
+const node = () => ({ connect: (next) => next, disconnect() {}, gain: { value: 1, setTargetAtTime() {} } });
+globalThis.AudioContext = class {
+ constructor() {
+ Object.assign(this, { state: 'running', sampleRate: 48000, baseLatency: 0, currentTime: 0, destination: {} });
+ this.audioWorklet = { addModule: async () => {} };
+ }
+ createGain() { return node(); }
+ createMediaStreamSource() { return node(); }
+ async resume() {}
+ async setSinkId() {}
+};
+globalThis.AudioWorkletNode = class {
+ constructor() {
+ Object.assign(this, node(), { port: { postMessage() {}, onmessage: null } });
+ env.worklets.push(this);
+ }
+};
diff --git a/test/prefs.test.js b/test/prefs.test.js
index 37df923..81d56d7 100644
--- a/test/prefs.test.js
+++ b/test/prefs.test.js
@@ -110,3 +110,38 @@ test('language: English by default, a stored choice is kept and independent of t
cleanup();
}
});
+
+test('transmit mode: stored ptt/open keep loading, vad is accepted, sensitivity defaults to normal', () => {
+ const { file, cleanup } = tempFile();
+ try {
+ assert.equal(new Prefs(file).get().transmitMode, 'ptt');
+ for (const mode of ['ptt', 'open', 'vad']) {
+ fs.writeFileSync(file, JSON.stringify({ transmitMode: mode }));
+ assert.equal(new Prefs(file).get().transmitMode, mode);
+ }
+ assert.equal(new Prefs(file).get().vadSensitivity, 'normal');
+ const p = new Prefs(file);
+ p.set({ transmitMode: 'vad', vadSensitivity: 'low' });
+ assert.deepEqual([new Prefs(file).get().transmitMode, new Prefs(file).get().vadSensitivity], ['vad', 'low']);
+ assert.throws(() => p.set({ vadSensitivity: 'max' }));
+ assert.throws(() => p.set({ transmitMode: 'whisper' }));
+ } finally {
+ cleanup();
+ }
+});
+
+test('a failed write leaves both the stored file and the in-memory values unchanged', () => {
+ const { file, cleanup } = tempFile();
+ try {
+ const p = new Prefs(file);
+ p.set({ transmitMode: 'ptt' });
+ const before = fs.readFileSync(file, 'utf8');
+ // A directory where the temporary file must go makes the write fail.
+ fs.mkdirSync(`${file}.tmp`);
+ assert.throws(() => p.set({ transmitMode: 'open' }));
+ assert.equal(p.get().transmitMode, 'ptt');
+ assert.equal(fs.readFileSync(file, 'utf8'), before);
+ } finally {
+ cleanup();
+ }
+});
diff --git a/test/voice-capture.test.mjs b/test/voice-capture.test.mjs
index a94e52c..b434f2a 100644
--- a/test/voice-capture.test.mjs
+++ b/test/voice-capture.test.mjs
@@ -3,96 +3,12 @@
// while capture is wanted, and a failed enumeration replaces the device menus' earlier list.
import test from 'node:test';
import assert from 'node:assert/strict';
-
-const timeout = globalThis.setTimeout;
-globalThis.setTimeout = (fn, ms, ...args) => {
- const id = timeout(fn, ms, ...args);
- id.unref?.();
- return id;
-};
-
-class FakeNode {
- constructor() {
- Object.assign(this, { style: {}, dataset: {}, children: [], textContent: '', value: '', className: '' });
- this.classList = { add() {}, remove() {}, toggle() {}, contains: () => false };
- }
- addEventListener() {}
- removeEventListener() {}
- setAttribute() {}
- getAttribute() { return null; }
- removeAttribute() {}
- appendChild(child) { this.children.push(child); return child; }
- replaceChildren(...children) { this.children = children; }
- remove() {}
- focus() {}
- setPointerCapture() {}
- querySelector() { return new FakeNode(); }
- querySelectorAll() { return []; }
- get firstElementChild() { return this.children[0] ?? new FakeNode(); }
-}
-const elements = new Map();
-globalThis.Node = FakeNode;
-globalThis.document = {
- querySelector: (selector) => {
- if (!elements.has(selector)) elements.set(selector, new FakeNode());
- return elements.get(selector);
- },
- querySelectorAll: () => [],
- createElement: () => new FakeNode(),
- createElementNS: () => new FakeNode(),
- createTextNode: () => new FakeNode(),
- hasFocus: () => true,
- documentElement: new FakeNode(),
-};
-globalThis.window = globalThis;
-globalThis.addEventListener = () => {};
-globalThis.requestAnimationFrame = () => 0;
-
-const sent = [];
-globalThis.teamspeach = { onAudio() {}, sendAudioFrame: (f) => sent.push(f), endAudio() {}, log() {} };
-
-const calls = [];
-const opened = [];
-let enumerate = async () => [
- { kind: 'audioinput', deviceId: 'mic-2', label: 'Mic 2', groupId: 'g2' },
- { kind: 'audiooutput', deviceId: 'out-1', label: 'Out 1', groupId: 'g3' },
-];
-Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- value: {
- mediaDevices: {
- addEventListener() {},
- enumerateDevices: () => enumerate(),
- getUserMedia: async (constraints) => {
- calls.push(constraints);
- const id = constraints.audio.deviceId?.exact;
- if (id === 'gone') throw Object.assign(new Error('Requested device not found'), { name: 'OverconstrainedError' });
- const track = { label: id ?? 'default', muted: false, stopped: false, stop() { this.stopped = true; }, addEventListener() {}, getSettings: () => ({}) };
- opened.push(track);
- return { getTracks: () => [track], getAudioTracks: () => [track] };
- },
- },
- },
-});
-const node = () => ({ connect: (next) => next, disconnect() {}, gain: { value: 1, setTargetAtTime() {} } });
-globalThis.AudioContext = class {
- constructor() {
- Object.assign(this, { state: 'running', sampleRate: 48000, baseLatency: 0, currentTime: 0, destination: {} });
- this.audioWorklet = { addModule: async () => {} };
- }
- createGain() { return node(); }
- createMediaStreamSource() { return node(); }
- async resume() {}
- async setSinkId() {}
-};
-globalThis.AudioWorkletNode = class {
- constructor() { Object.assign(this, node(), { port: { postMessage() {}, onmessage: null } }); }
-};
+import { env } from './fixtures/renderer-env.mjs';
const { S } = await import('../app/renderer/js/state.js');
const voice = await import('../app/renderer/js/voice.js');
-S.prefs = { inputDeviceId: 'gone', outputDeviceId: '', echoCancellation: true, noiseSuppression: true, autoGainControl: true, transmitMode: 'open', pttCode: 'F8', voiceVolume: 100 };
+S.prefs = { inputDeviceId: 'gone', outputDeviceId: '', echoCancellation: true, noiseSuppression: true, autoGainControl: true, transmitMode: 'open', vadSensitivity: 'normal', pttCode: 'F8', voiceVolume: 100 };
voice.initVoice({ savePrefs: async (partial) => (S.prefs = { ...S.prefs, ...partial }) });
const connect = () => {
S.conn = { state: 'connected', address: 'x', reason: null };
@@ -106,35 +22,35 @@ const disconnect = () => {
test('a missing saved microphone fails closed: no other microphone is opened, nothing is sent', async () => {
connect();
await voice.syncCapture();
- assert.equal(calls.length, 1);
- assert.deepEqual(calls[0].audio.deviceId, { exact: 'gone' });
- assert.equal(opened.length, 0);
+ assert.equal(env.gumCalls.length, 1);
+ assert.deepEqual(env.gumCalls[0].audio.deviceId, { exact: 'gone' });
+ assert.equal(env.opened.length, 0);
assert.equal(voice.isCapturing(), false);
- assert.equal(sent.length, 0);
+ assert.equal(env.sent.length, 0);
});
test('choosing an available microphone after the failure recovers capture while connected', async () => {
await voice.chooseInputDevice('mic-2');
- assert.equal(calls.length, 2);
- assert.deepEqual(calls[1].audio.deviceId, { exact: 'mic-2' });
+ assert.equal(env.gumCalls.length, 2);
+ assert.deepEqual(env.gumCalls[1].audio.deviceId, { exact: 'mic-2' });
assert.equal(voice.isCapturing(), true);
- assert.equal(opened.at(-1).label, 'mic-2');
+ assert.equal(env.opened.at(-1).label, 'mic-2');
});
test('while disconnected, choosing a microphone opens nothing', async () => {
disconnect();
await voice.syncCapture();
assert.equal(voice.isCapturing(), false);
- assert.equal(opened.at(-1).stopped, true);
+ assert.equal(env.opened.at(-1).stopped, true);
await voice.chooseInputDevice('mic-3');
- assert.equal(calls.length, 2);
+ assert.equal(env.gumCalls.length, 2);
assert.equal(voice.isCapturing(), false);
});
test('a failed enumeration replaces the earlier device list for the menus', async () => {
const ok = await voice.deviceChoices();
assert.ok(ok.input.options.some((o) => o.value === 'mic-2'));
- enumerate = async () => {
+ env.enumerate = async () => {
throw Object.assign(new Error('enumeration failed'), { name: 'NotReadableError' });
};
const failed = await voice.deviceChoices();
diff --git a/test/voice-transmit.test.mjs b/test/voice-transmit.test.mjs
new file mode 100644
index 0000000..a3885f5
--- /dev/null
+++ b/test/voice-transmit.test.mjs
@@ -0,0 +1,117 @@
+// Transmit mode handshake in voice.js (stubbed bridge and capture, no devices, no network): frames reach the
+// core only after the core acknowledged the mode the preferences ask for; a pending or failed change sends
+// nothing and never falls back to another mode; mute, deafen and disconnect stop forwarding at once.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { env } from './fixtures/renderer-env.mjs';
+
+const { S } = await import('../app/renderer/js/state.js');
+const voice = await import('../app/renderer/js/voice.js');
+
+S.prefs = { inputDeviceId: '', outputDeviceId: '', echoCancellation: true, noiseSuppression: true, autoGainControl: true, transmitMode: 'ptt', vadSensitivity: 'normal', pttCode: 'F8', voiceVolume: 100 };
+voice.initVoice({ savePrefs: async (partial) => (S.prefs = { ...S.prefs, ...partial }) });
+S.conn = { state: 'connected', address: 'x', reason: null };
+S.snap = { clients: [], channels: [], own_client_id: 1, own_channel_id: 1 };
+await voice.syncCapture();
+
+/** Answers set_transmit like the core would; `hold` keeps the answer back until released. */
+function coreAnswers({ fail = false } = {}) {
+ let release;
+ const gate = new Promise((r) => { release = r; });
+ env.respond = async (cmd, args) => {
+ if (cmd !== 'set_transmit') return { ok: true, result: {} };
+ await gate;
+ if (fail) return { ok: false, error: { code: 'internal', message: 'detector unavailable' } };
+ return { ok: true, result: args.mode === 'vad' ? { mode: 'vad', sensitivity: args.sensitivity } : { mode: 'direct' } };
+ };
+ return release;
+}
+
+const forwarded = (fn) => {
+ const before = env.sent.length;
+ fn();
+ return env.sent.length - before;
+};
+
+test('nothing is forwarded before the core acknowledged a mode', async () => {
+ S.prefs.transmitMode = 'open';
+ assert.equal(forwarded(() => env.frame()), 0);
+ const release = coreAnswers();
+ const applied = voice.applyTransmitMode();
+ assert.equal(forwarded(() => env.frame()), 0, 'still pending');
+ release();
+ await applied;
+ assert.deepEqual(env.requests.at(-1), { cmd: 'set_transmit', args: { mode: 'direct' } });
+ assert.equal(forwarded(() => env.frame()), 1, 'open microphone forwards once "direct" is confirmed');
+});
+
+test('push to talk forwards only while held, under the direct mode', () => {
+ S.prefs.transmitMode = 'ptt';
+ assert.equal(forwarded(() => env.frame()), 0);
+ voice.setPtt(true);
+ assert.equal(forwarded(() => env.frame()), 1);
+ voice.setPtt(false);
+ const ends = env.ended;
+ assert.equal(forwarded(() => env.frame()), 0);
+ assert.equal(env.ended, ends + 1, 'releasing ends the burst');
+});
+
+test('switching to voice activation forwards nothing until "vad" is acknowledged', async () => {
+ S.prefs.transmitMode = 'vad';
+ // The renderer still has "direct" confirmed: that must not carry VAD-mode audio.
+ assert.equal(forwarded(() => env.frame()), 0);
+ const release = coreAnswers();
+ const applied = voice.applyTransmitMode();
+ assert.equal(forwarded(() => env.frame()), 0);
+ release();
+ await applied;
+ assert.deepEqual(env.requests.at(-1), { cmd: 'set_transmit', args: { mode: 'vad', sensitivity: 'normal' } });
+ assert.equal(forwarded(() => env.frame(0.001)), 1, 'quiet frames too: the core detector decides, not a level');
+ assert.equal(S.audio.transmitting, false, 'forwarding alone never marks the user as talking');
+});
+
+test('a sensitivity change pauses forwarding until applied', async () => {
+ S.prefs.vadSensitivity = 'low';
+ assert.equal(forwarded(() => env.frame()), 0);
+ const release = coreAnswers();
+ const applied = voice.applyTransmitMode();
+ release();
+ await applied;
+ assert.deepEqual(env.requests.at(-1).args, { mode: 'vad', sensitivity: 'low' });
+ assert.equal(forwarded(() => env.frame()), 1);
+});
+
+test('mute, deafen and disconnect stop forwarding at once', () => {
+ for (const [name, set, unset] of [
+ ['mute', () => { S.audio.input_muted = true; }, () => { S.audio.input_muted = false; }],
+ ['deafen', () => { S.audio.output_muted = true; }, () => { S.audio.output_muted = false; }],
+ ['disconnect', () => { S.conn = { state: 'disconnected', address: '', reason: null }; }, () => { S.conn = { state: 'connected', address: 'x', reason: null }; }],
+ ]) {
+ assert.equal(forwarded(() => env.frame()), 1, `${name}: forwarding before`);
+ const ends = env.ended;
+ set();
+ assert.equal(forwarded(() => env.frame()), 0, `${name}: nothing forwarded`);
+ assert.equal(env.ended, ends + 1, `${name}: burst ended`);
+ unset();
+ }
+});
+
+test('a failed mode change sends nothing and does not fall back to open microphone', async () => {
+ S.prefs.transmitMode = 'open';
+ const release = coreAnswers({ fail: true });
+ const applied = voice.applyTransmitMode();
+ release();
+ await applied;
+ assert.equal(forwarded(() => env.frame()), 0);
+ // Retrying applies again once the core answers.
+ const retry = coreAnswers();
+ const again = voice.applyTransmitMode();
+ retry();
+ await again;
+ assert.equal(forwarded(() => env.frame()), 1);
+});
+
+test('a core restart forgets the confirmed mode', async () => {
+ voice.forgetCoreTransmitMode();
+ assert.equal(forwarded(() => env.frame()), 0);
+});