Voice activation (core voice detector, set_transmit handshake), transmission mode in Settings → Audio, atomic prefs commit, ARM64 unit tests under qemu; version 0.1.3
This commit is contained in:
1 parent
8439fe062e
commit
b7951e0693
46 files changed
+1905
-191
No files matched your search
Generated
+8
-1
@@ -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",
|
||||
|
||||
+3
-1
@@ -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"
|
||||
|
||||
@@ -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 <carson@pyke.io>
|
||||
|
||||
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)
|
||||
|
||||
```
|
||||
|
||||
@@ -84,6 +84,15 @@ impl AudioInQueue {
|
||||
|
||||
pub fn pop(&self) -> Option<AudioIn> { 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] {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<String> },
|
||||
SendText { target: TextTarget, client_id: Option<u16>, message: String },
|
||||
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
|
||||
/// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
|
||||
SetTransmit { vad: Option<Sensitivity> },
|
||||
StreamList { client_id: Option<u16> },
|
||||
StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
|
||||
/// `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<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SetAudioArgs {
|
||||
@@ -425,6 +438,19 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
|
||||
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::<StreamListArgs>(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!(
|
||||
|
||||
+139
-34
@@ -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<u16, tsclientlib::Error> {
|
||||
@@ -178,6 +180,14 @@ struct Tx {
|
||||
last_overflow_report: Option<Instant>,
|
||||
}
|
||||
|
||||
/// 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<String> },
|
||||
@@ -191,6 +201,9 @@ pub struct Session {
|
||||
flags: AudioFlags,
|
||||
conn: Option<Conn>,
|
||||
tx: Tx,
|
||||
/// `None` = direct transmission: every frame the renderer forwards is sent.
|
||||
vad: Option<Box<VadState>>,
|
||||
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<Sensitivity>) -> Result<Value, ErrorObj> {
|
||||
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) {
|
||||
|
||||
+644
@@ -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<Detector>,
|
||||
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<Frame> {
|
||||
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<Frame> { vec![[0i16; FRAME_SAMPLES]; n] }
|
||||
|
||||
/// Synthetic steady broadband noise (fan/hiss-like) at roughly -30 dBFS RMS.
|
||||
fn steady_noise(n: usize) -> Vec<Frame> {
|
||||
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<Frame> {
|
||||
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<bool>, 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<i16> = (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<f32> = 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::<f32>();
|
||||
}
|
||||
}
|
||||
(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::<f32>() / 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());
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+21
@@ -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/details/short_poetry_001_librivox>
|
||||
(`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
|
||||
<http://creativecommons.org/licenses/publicdomain/>.
|
||||
- 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.
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user