yumush
Clone
https://git.tahinli.com/Tahinli/yumush.git
0 watching·0 forks·Rust·AGPL-3.0·6.8 MiB·27ceb05·Tahinli·8 hours ago·399 commits
| 1 | use std::{ |
| 2 | collections::{BTreeMap, HashMap, VecDeque}, |
| 3 | time::{Duration, Instant}, |
| 4 | }; |
| 5 | |
| 6 | use common::{ |
| 7 | constant::{ |
| 8 | MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, |
| 9 | }, |
| 10 | datagram::{Packet, RELAY_PREFIX, VOICE_HEADER}, |
| 11 | model::Id, |
| 12 | }; |
| 13 | use ec_opus::{Application, Bandwidth, Decoder, Encoder}; |
| 14 | |
| 15 | use crate::{ |
| 16 | media::meter::{Spectrum, db, rms}, |
| 17 | settings::{Activation, Profile}, |
| 18 | }; |
| 19 | |
| 20 | pub const SILENT_DB: f32 = -100.0; |
| 21 | const JITTER_CAPACITY: usize = 10; |
| 22 | const FRAME_MS: f32 = VOICE_FRAME_SAMPLES as f32 * 1000.0 / VOICE_SAMPLE_RATE as f32; |
| 23 | const MIN_FRAMES: usize = 1; |
| 24 | const MAX_FRAMES: usize = 6; |
| 25 | const DRIFT_MARGIN: usize = 2; |
| 26 | const QUIET: f32 = 0.01; |
| 27 | const SPEAKING_WINDOW: Duration = Duration::from_millis(300); |
| 28 | const RESTART_AFTER: Duration = Duration::from_secs(1); |
| 29 | const MAX_DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000; |
| 30 | const HANGOVER_FRAMES: u32 = 15; |
| 31 | const FADE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 5 / 1000; |
| 32 | const INITIAL_LOSS_PERC: u8 = 3; |
| 33 | const MIN_LOSS_PERC: u8 = 3; |
| 34 | const MAX_LOSS_PERC: u8 = 25; |
| 35 | |
| 36 | fn soft_clip(sample: f32) -> f32 { |
| 37 | const KNEE: f32 = 0.8; |
| 38 | let magnitude = sample.abs(); |
| 39 | if magnitude <= KNEE { |
| 40 | return sample; |
| 41 | } |
| 42 | let over = (magnitude - KNEE) / (1.0 - KNEE); |
| 43 | sample.signum() * (KNEE + (1.0 - KNEE) * over.tanh()) |
| 44 | } |
| 45 | |
| 46 | fn bitrate(profile: Profile) -> u32 { |
| 47 | match profile { |
| 48 | Profile::Voice => VOICE_BITRATE as u32, |
| 49 | Profile::Music => MUSIC_BITRATE as u32, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | fn encoder(profile: Profile, loss_perc: u8) -> Encoder { |
| 54 | let application = match profile { |
| 55 | Profile::Voice => Application::Voip, |
| 56 | Profile::Music => Application::Audio, |
| 57 | }; |
| 58 | let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder"); |
| 59 | encoder.set_bitrate(bitrate(profile)); |
| 60 | encoder.set_bandwidth(Some(Bandwidth::Full)); |
| 61 | encoder.set_analysis(true); |
| 62 | encoder.set_inband_fec(true); |
| 63 | encoder.set_packet_loss_perc(loss_perc); |
| 64 | encoder |
| 65 | } |
| 66 | |
| 67 | struct Speaker { |
| 68 | decoder: Decoder, |
| 69 | scratch: Vec<f32>, |
| 70 | jitter: BTreeMap<u32, Vec<u8>>, |
| 71 | next: u32, |
| 72 | pending: VecDeque<f32>, |
| 73 | last_heard: Instant, |
| 74 | started: bool, |
| 75 | first_arrival: Instant, |
| 76 | first_sequence: u32, |
| 77 | previous_transit: Option<f32>, |
| 78 | jitter_ms: f32, |
| 79 | highest: u32, |
| 80 | spectrum: Spectrum, |
| 81 | } |
| 82 | |
| 83 | pub use common::stats::Traffic; |
| 84 | |
| 85 | impl Speaker { |
| 86 | fn new(sequence: u32, now: Instant) -> Self { |
| 87 | Self { |
| 88 | decoder: Decoder::new(VOICE_SAMPLE_RATE, 1).expect("opus decoder"), |
| 89 | scratch: vec![0.0; MAX_DECODE_SAMPLES], |
| 90 | jitter: BTreeMap::new(), |
| 91 | next: sequence, |
| 92 | pending: VecDeque::new(), |
| 93 | last_heard: now, |
| 94 | started: false, |
| 95 | first_arrival: now, |
| 96 | first_sequence: sequence, |
| 97 | previous_transit: None, |
| 98 | jitter_ms: 0.0, |
| 99 | highest: sequence.wrapping_sub(1), |
| 100 | spectrum: Spectrum::default(), |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn target(&self) -> usize { |
| 105 | ((self.jitter_ms * 2.0 / FRAME_MS).ceil() as usize + 1).clamp(MIN_FRAMES, MAX_FRAMES) |
| 106 | } |
| 107 | |
| 108 | fn decode_next(&mut self) -> (Vec<f32>, bool) { |
| 109 | let (decoded, real) = match ( |
| 110 | self.jitter.remove(&self.next), |
| 111 | self.jitter.get(&self.next.wrapping_add(1)), |
| 112 | ) { |
| 113 | (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true), |
| 114 | (None, Some(following)) => ( |
| 115 | self.decoder |
| 116 | .decode_fec(following, VOICE_FRAME_SAMPLES, &mut self.scratch), |
| 117 | false, |
| 118 | ), |
| 119 | (None, None) => ( |
| 120 | self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch), |
| 121 | false, |
| 122 | ), |
| 123 | }; |
| 124 | self.next = self.next.wrapping_add(1); |
| 125 | |
| 126 | let samples = match decoded { |
| 127 | Ok(samples) => self.scratch[..samples].to_vec(), |
| 128 | Err(_) => vec![0.0; VOICE_FRAME_SAMPLES], |
| 129 | }; |
| 130 | (samples, real) |
| 131 | } |
| 132 | |
| 133 | fn next_frame(&mut self) -> Option<Vec<f32>> { |
| 134 | if self.jitter.is_empty() { |
| 135 | return None; |
| 136 | } |
| 137 | let (mut frame, real) = self.decode_next(); |
| 138 | if real && self.jitter.len() > self.target() + DRIFT_MARGIN && rms(&frame) < QUIET { |
| 139 | (frame, _) = self.decode_next(); |
| 140 | } |
| 141 | Some(frame) |
| 142 | } |
| 143 | |
| 144 | fn mix(&mut self, out: &mut [f32], gain: f32) { |
| 145 | for sample in out.iter_mut() { |
| 146 | if self.pending.is_empty() { |
| 147 | let Some(frame) = self.next_frame() else { |
| 148 | self.started = false; |
| 149 | self.previous_transit = None; |
| 150 | return; |
| 151 | }; |
| 152 | self.spectrum.record(&frame, 1); |
| 153 | self.pending.extend(frame); |
| 154 | } |
| 155 | *sample += self.pending.pop_front().unwrap_or(0.0) * gain; |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | pub struct Engine { |
| 161 | encoder: Encoder, |
| 162 | loss_perc: u8, |
| 163 | profile: Profile, |
| 164 | capture_buffer: Vec<f32>, |
| 165 | sequence: u32, |
| 166 | muted: bool, |
| 167 | deafened: bool, |
| 168 | gate: f32, |
| 169 | input_gain: f32, |
| 170 | output_gain: f32, |
| 171 | activation: Activation, |
| 172 | talking: bool, |
| 173 | hangover: u32, |
| 174 | sending: bool, |
| 175 | level_db: f32, |
| 176 | sent: Spectrum, |
| 177 | volumes: HashMap<Id, f32>, |
| 178 | speakers: HashMap<Id, Speaker>, |
| 179 | sent_bytes: usize, |
| 180 | received_bytes: usize, |
| 181 | expected: u32, |
| 182 | arrived: u32, |
| 183 | counting_since: Instant, |
| 184 | } |
| 185 | |
| 186 | impl Default for Engine { |
| 187 | fn default() -> Self { |
| 188 | Self::new() |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | impl Engine { |
| 193 | pub fn new() -> Self { |
| 194 | Self { |
| 195 | encoder: encoder(Profile::Voice, INITIAL_LOSS_PERC), |
| 196 | loss_perc: INITIAL_LOSS_PERC, |
| 197 | profile: Profile::Voice, |
| 198 | capture_buffer: Vec::new(), |
| 199 | sequence: 0, |
| 200 | muted: false, |
| 201 | deafened: false, |
| 202 | gate: 0.0, |
| 203 | input_gain: 1.0, |
| 204 | output_gain: 1.0, |
| 205 | activation: Activation::VoiceActivity, |
| 206 | talking: false, |
| 207 | hangover: 0, |
| 208 | sending: false, |
| 209 | level_db: SILENT_DB, |
| 210 | sent: Spectrum::default(), |
| 211 | volumes: HashMap::new(), |
| 212 | speakers: HashMap::new(), |
| 213 | sent_bytes: 0, |
| 214 | received_bytes: 0, |
| 215 | expected: 0, |
| 216 | arrived: 0, |
| 217 | counting_since: Instant::now(), |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | pub fn capture(&mut self, samples: &[f32]) -> Vec<Vec<u8>> { |
| 222 | self.capture_buffer.extend_from_slice(samples); |
| 223 | |
| 224 | let full = self.capture_buffer.len() / VOICE_FRAME_SAMPLES * VOICE_FRAME_SAMPLES; |
| 225 | let mut frames: Vec<f32> = self.capture_buffer.drain(..full).collect(); |
| 226 | for sample in &mut frames { |
| 227 | *sample = soft_clip(*sample * self.input_gain); |
| 228 | } |
| 229 | |
| 230 | let mut packets = Vec::new(); |
| 231 | for frame in frames.as_chunks::<VOICE_FRAME_SAMPLES>().0 { |
| 232 | self.sent.record(frame, 1); |
| 233 | let loud = rms(frame); |
| 234 | self.level_db = db(loud).max(SILENT_DB); |
| 235 | if loud >= self.gate { |
| 236 | self.hangover = HANGOVER_FRAMES; |
| 237 | } |
| 238 | let talking = match self.activation { |
| 239 | Activation::PushToTalk => self.talking, |
| 240 | Activation::VoiceActivity => self.hangover > 0, |
| 241 | }; |
| 242 | self.hangover = self.hangover.saturating_sub(1); |
| 243 | let speaking = talking && !self.muted && !self.deafened; |
| 244 | let was_sending = self.sending; |
| 245 | self.sending = speaking; |
| 246 | if !speaking && !was_sending { |
| 247 | continue; |
| 248 | } |
| 249 | |
| 250 | let mut samples = *frame; |
| 251 | if speaking && !was_sending { |
| 252 | for (index, sample) in samples[..FADE_SAMPLES].iter_mut().enumerate() { |
| 253 | *sample *= index as f32 / FADE_SAMPLES as f32; |
| 254 | } |
| 255 | } |
| 256 | if !speaking { |
| 257 | for (index, sample) in samples.iter_mut().enumerate() { |
| 258 | *sample *= 1.0 - index as f32 / VOICE_FRAME_SAMPLES as f32; |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | let mut payload = [0u8; VOICE_MAX_PAYLOAD]; |
| 263 | let Ok(length) = self |
| 264 | .encoder |
| 265 | .encode_float(&samples, VOICE_FRAME_SAMPLES, &mut payload) |
| 266 | else { |
| 267 | continue; |
| 268 | }; |
| 269 | |
| 270 | let mut packet = Vec::with_capacity(length + 5); |
| 271 | Packet::Voice { |
| 272 | seq: self.sequence, |
| 273 | opus: &payload[..length], |
| 274 | } |
| 275 | .encode(&mut packet); |
| 276 | self.sent_bytes += packet.len(); |
| 277 | packets.push(packet); |
| 278 | self.sequence = self.sequence.wrapping_add(1); |
| 279 | } |
| 280 | |
| 281 | packets |
| 282 | } |
| 283 | |
| 284 | pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) { |
| 285 | let user_id = Id::from_be_bytes(*from); |
| 286 | let now = Instant::now(); |
| 287 | self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len(); |
| 288 | |
| 289 | let speaker = self |
| 290 | .speakers |
| 291 | .entry(user_id) |
| 292 | .or_insert_with(|| Speaker::new(sequence, now)); |
| 293 | if now.duration_since(speaker.last_heard) > RESTART_AFTER { |
| 294 | *speaker = Speaker::new(sequence, now); |
| 295 | } |
| 296 | speaker.last_heard = now; |
| 297 | if payload.is_empty() { |
| 298 | return; |
| 299 | } |
| 300 | if sequence < speaker.next { |
| 301 | return; |
| 302 | } |
| 303 | if sequence.wrapping_sub(speaker.highest) < u32::MAX / 2 { |
| 304 | self.expected += sequence.wrapping_sub(speaker.highest); |
| 305 | speaker.highest = sequence; |
| 306 | } |
| 307 | self.arrived += 1; |
| 308 | |
| 309 | let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0 |
| 310 | - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS; |
| 311 | if let Some(previous) = speaker.previous_transit { |
| 312 | speaker.jitter_ms += ((transit_ms - previous).abs() - speaker.jitter_ms) / 16.0; |
| 313 | } |
| 314 | speaker.previous_transit = Some(transit_ms); |
| 315 | |
| 316 | speaker.jitter.insert(sequence, payload.to_vec()); |
| 317 | while speaker.jitter.len() > JITTER_CAPACITY { |
| 318 | speaker.jitter.pop_first(); |
| 319 | } |
| 320 | if speaker.jitter.len() >= speaker.target() { |
| 321 | speaker.started = true; |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | pub fn playback(&mut self, out: &mut [f32]) { |
| 326 | out.fill(0.0); |
| 327 | for (user_id, speaker) in &mut self.speakers { |
| 328 | if speaker.started { |
| 329 | speaker.mix(out, self.volumes.get(user_id).copied().unwrap_or(1.0)); |
| 330 | } |
| 331 | } |
| 332 | if self.deafened { |
| 333 | out.fill(0.0); |
| 334 | return; |
| 335 | } |
| 336 | |
| 337 | for sample in out.iter_mut() { |
| 338 | *sample = soft_clip(*sample * self.output_gain); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | pub fn levels(&mut self) -> Vec<(Id, Vec<f32>)> { |
| 343 | let now = Instant::now(); |
| 344 | |
| 345 | self.speakers |
| 346 | .iter_mut() |
| 347 | .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW) |
| 348 | .map(|(user_id, speaker)| (*user_id, speaker.spectrum.take())) |
| 349 | .collect() |
| 350 | } |
| 351 | |
| 352 | pub fn take_traffic(&mut self) -> Traffic { |
| 353 | let now = Instant::now(); |
| 354 | let seconds = now |
| 355 | .duration_since(self.counting_since) |
| 356 | .as_secs_f32() |
| 357 | .max(f32::EPSILON); |
| 358 | let heard = self |
| 359 | .speakers |
| 360 | .values() |
| 361 | .filter(|speaker| now.duration_since(speaker.last_heard) <= RESTART_AFTER); |
| 362 | let (jitter_ms, buffer_ms) = heard.fold((0.0f32, 0.0f32), |(jitter, buffer), speaker| { |
| 363 | ( |
| 364 | jitter.max(speaker.jitter_ms), |
| 365 | buffer.max(speaker.target() as f32 * FRAME_MS), |
| 366 | ) |
| 367 | }); |
| 368 | let loss = if self.expected == 0 { |
| 369 | 0.0 |
| 370 | } else { |
| 371 | 1.0 - (self.arrived as f32 / self.expected as f32).min(1.0) |
| 372 | }; |
| 373 | let traffic = Traffic { |
| 374 | jitter_ms, |
| 375 | buffer_ms, |
| 376 | loss, |
| 377 | up_kbps: self.sent_bytes as f32 * 8.0 / 1000.0 / seconds, |
| 378 | down_kbps: self.received_bytes as f32 * 8.0 / 1000.0 / seconds, |
| 379 | }; |
| 380 | |
| 381 | self.sent_bytes = 0; |
| 382 | self.received_bytes = 0; |
| 383 | self.expected = 0; |
| 384 | self.arrived = 0; |
| 385 | self.counting_since = now; |
| 386 | traffic |
| 387 | } |
| 388 | |
| 389 | pub fn bitrate_kbps(&self) -> u32 { |
| 390 | bitrate(self.profile) / 1000 |
| 391 | } |
| 392 | |
| 393 | pub fn set_muted(&mut self, muted: bool) { |
| 394 | self.muted = muted; |
| 395 | } |
| 396 | |
| 397 | pub fn set_deafened(&mut self, deafened: bool) { |
| 398 | self.deafened = deafened; |
| 399 | } |
| 400 | |
| 401 | pub fn configure( |
| 402 | &mut self, |
| 403 | sensitivity_db: f32, |
| 404 | input_volume: f32, |
| 405 | output_volume: f32, |
| 406 | activation: Activation, |
| 407 | profile: Profile, |
| 408 | volumes: &BTreeMap<Id, f32>, |
| 409 | ) { |
| 410 | self.volumes = volumes |
| 411 | .iter() |
| 412 | .map(|(user_id, volume)| (*user_id, volume / 100.0)) |
| 413 | .collect(); |
| 414 | self.gate = 10f32.powf(sensitivity_db / 20.0); |
| 415 | self.input_gain = input_volume / 100.0; |
| 416 | self.output_gain = output_volume / 100.0; |
| 417 | self.activation = activation; |
| 418 | if profile != self.profile { |
| 419 | self.encoder = encoder(profile, self.loss_perc); |
| 420 | self.profile = profile; |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | pub fn set_uplink_loss(&mut self, loss: f32) { |
| 425 | let perc = ((loss * 100.0 * 2.0).ceil() as u8).clamp(MIN_LOSS_PERC, MAX_LOSS_PERC); |
| 426 | if perc != self.loss_perc { |
| 427 | self.encoder.set_packet_loss_perc(perc); |
| 428 | self.loss_perc = perc; |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | pub fn set_talking(&mut self, talking: bool) { |
| 433 | self.talking = talking; |
| 434 | } |
| 435 | |
| 436 | pub fn own_level(&mut self) -> Vec<f32> { |
| 437 | self.sent.take() |
| 438 | } |
| 439 | |
| 440 | pub fn sending(&self) -> bool { |
| 441 | self.sending |
| 442 | } |
| 443 | |
| 444 | pub fn level_db(&self) -> f32 { |
| 445 | self.level_db |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | #[cfg(test)] |
| 450 | mod tests { |
| 451 | use std::f32::consts::TAU; |
| 452 | |
| 453 | use super::*; |
| 454 | |
| 455 | #[test] |
| 456 | fn voice_round_trip() { |
| 457 | let mut sender = Engine::new(); |
| 458 | let mut receiver = Engine::new(); |
| 459 | let user_id = [7u8; RELAY_PREFIX]; |
| 460 | let frames = 10; |
| 461 | |
| 462 | let tone: Vec<f32> = (0..VOICE_FRAME_SAMPLES * frames) |
| 463 | .map(|i| 0.5 * (TAU * 440.0 * i as f32 / VOICE_SAMPLE_RATE as f32).sin()) |
| 464 | .collect(); |
| 465 | |
| 466 | for packet in sender.capture(&tone) { |
| 467 | let Some(Packet::Voice { seq, opus }) = Packet::decode(&packet) else { |
| 468 | panic!("not voice"); |
| 469 | }; |
| 470 | receiver.receive(&user_id, seq, opus); |
| 471 | } |
| 472 | |
| 473 | let mut out = vec![0.0; VOICE_FRAME_SAMPLES * frames]; |
| 474 | receiver.playback(&mut out); |
| 475 | |
| 476 | assert!(rms(&out) > 0.1); |
| 477 | } |
| 478 | } |