BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / examples / audio_probe.rs

audio_probe.rs

audio_probe.rs 9.6 KiB Download Raw
1//! Windows tool for the call end-to-end test.
2//! `audio_probe play <render device name part> <mono 16-bit 48 kHz wav> <seconds>` loops the file into that endpoint.
3//! `audio_probe record-process <pid> <seconds> <out.wav>` records only what that process plays and prints loudness per 250 ms as JSON.
4//! `audio_probe record-mic <seconds> <out.wav>` records the default communications mic the way a call does.
5
6#[cfg(windows)]
7fn main() {
8 let arguments: Vec<String> = std::env::args().skip(1).collect();
9 let arguments: Vec<&str> = arguments.iter().map(String::as_str).collect();
10 let outcome = match arguments.as_slice() {
11 ["play", device, wav, seconds] => probe::play(device, wav, seconds.parse().expect("seconds")),
12 ["record-process", process_id, seconds, out] => probe::record_process(
13 process_id.parse().expect("pid"),
14 seconds.parse().expect("seconds"),
15 out,
16 ),
17 ["record-mic", seconds, out] => probe::record_mic(seconds.parse().expect("seconds"), out),
18 _ => Err("usage: play DEVICE WAV SECONDS | record-process PID SECONDS OUT.wav | record-mic SECONDS OUT.wav".to_owned()),
19 };
20 if let Err(error) = outcome {
21 eprintln!("{error}");
22 std::process::exit(1);
23 }
24}
25
26#[cfg(not(windows))]
27fn main() {
28 eprintln!("audio_probe runs on Windows only");
29}
30
31#[cfg(windows)]
32mod probe {
33 use std::time::{Duration, Instant};
34
35 use calling::audio::{FRAME_SAMPLES, SAMPLE_RATE};
36 use calling::pcm::SampleQueue;
37 use calling::wav_dump::WavDump;
38 use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
39 use windows::Win32::Media::Audio::{
40 AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
41 AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, DEVICE_STATE_ACTIVE, IAudioClient,
42 IAudioRenderClient, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX,
43 eRender,
44 };
45 use windows::Win32::System::Com::{
46 CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, STGM_READ,
47 };
48
49 const CHANNELS: u16 = 2;
50 const BITS: u16 = 16;
51 const PCM_TAG: u16 = 1;
52 const BUFFER_HNS: i64 = 1_000_000;
53 const TICK: Duration = Duration::from_millis(10);
54 const WINDOW_MS: usize = 250;
55 const WAV_HEADER: usize = 44;
56
57 fn failed(what: &str, error: impl std::fmt::Display) -> String {
58 format!("{what}: {error}")
59 }
60
61 fn render_device(name_part: &str) -> Result<IMMDevice, String> {
62 unsafe {
63 let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
64 let enumerator: IMMDeviceEnumerator =
65 CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)
66 .map_err(|error| failed("enumerator", error))?;
67 let devices = enumerator
68 .EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE)
69 .map_err(|error| failed("endpoints", error))?;
70 let mut names = Vec::new();
71 for index in 0..devices.GetCount().map_err(|error| failed("count", error))? {
72 let device = devices.Item(index).map_err(|error| failed("item", error))?;
73 let store = device
74 .OpenPropertyStore(STGM_READ)
75 .map_err(|error| failed("properties", error))?;
76 let value = store
77 .GetValue(&PKEY_Device_FriendlyName)
78 .map_err(|error| failed("name", error))?;
79 let name = value
80 .Anonymous
81 .Anonymous
82 .Anonymous
83 .pwszVal
84 .to_string()
85 .unwrap_or_default();
86 if name.contains(name_part) {
87 return Ok(device);
88 }
89 names.push(name);
90 }
91 Err(format!(
92 "no render device with \"{name_part}\" in {names:?}"
93 ))
94 }
95 }
96
97 fn read_mono_wav(path: &str) -> Result<Vec<i16>, String> {
98 let bytes = std::fs::read(path).map_err(|error| failed("read wav", error))?;
99 let header = bytes.get(..WAV_HEADER).ok_or("wav too short")?;
100 let channels = u16::from_le_bytes([header[22], header[23]]);
101 let rate = u32::from_le_bytes([header[24], header[25], header[26], header[27]]);
102 let bits = u16::from_le_bytes([header[34], header[35]]);
103 if channels != 1 || rate != SAMPLE_RATE || bits != BITS {
104 return Err(format!(
105 "need mono 16-bit {SAMPLE_RATE} Hz, got {channels} ch {bits} bit {rate} Hz"
106 ));
107 }
108 let data = bytes
109 .windows(4)
110 .position(|tag| tag == b"data")
111 .ok_or("wav without data chunk")?
112 + 8;
113 Ok(bytes[data..]
114 .chunks_exact(2)
115 .map(|pair| i16::from_le_bytes([pair[0], pair[1]]))
116 .collect())
117 }
118
119 pub fn play(name_part: &str, wav: &str, seconds: u64) -> Result<(), String> {
120 let samples = read_mono_wav(wav)?;
121 if samples.is_empty() {
122 return Err("wav without samples".to_owned());
123 }
124 let device = render_device(name_part)?;
125 let block_align = CHANNELS * BITS / 8;
126 let format = WAVEFORMATEX {
127 wFormatTag: PCM_TAG,
128 nChannels: CHANNELS,
129 nSamplesPerSec: SAMPLE_RATE,
130 nAvgBytesPerSec: SAMPLE_RATE * u32::from(block_align),
131 nBlockAlign: block_align,
132 wBitsPerSample: BITS,
133 cbSize: 0,
134 };
135 unsafe {
136 let client: IAudioClient = device
137 .Activate(CLSCTX_ALL, None)
138 .map_err(|error| failed("activate", error))?;
139 client
140 .Initialize(
141 AUDCLNT_SHAREMODE_SHARED,
142 AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
143 BUFFER_HNS,
144 0,
145 &raw const format,
146 None,
147 )
148 .map_err(|error| failed("initialize", error))?;
149 let buffer_frames = client
150 .GetBufferSize()
151 .map_err(|error| failed("buffer size", error))?;
152 let render: IAudioRenderClient = client
153 .GetService()
154 .map_err(|error| failed("render service", error))?;
155 client.Start().map_err(|error| failed("start", error))?;
156 let started = Instant::now();
157 let mut position = 0usize;
158 println!("{{\"playing\":true}}");
159 while started.elapsed() < Duration::from_secs(seconds) {
160 let padding = client
161 .GetCurrentPadding()
162 .map_err(|error| failed("padding", error))?;
163 let frames = buffer_frames - padding;
164 if frames > 0 {
165 let data = render
166 .GetBuffer(frames)
167 .map_err(|error| failed("buffer", error))?;
168 let output = std::slice::from_raw_parts_mut(
169 data.cast::<i16>(),
170 frames as usize * usize::from(CHANNELS),
171 );
172 for pair in output.chunks_exact_mut(usize::from(CHANNELS)) {
173 let sample = samples[position % samples.len()];
174 pair.fill(sample);
175 position += 1;
176 }
177 render
178 .ReleaseBuffer(frames, 0)
179 .map_err(|error| failed("release", error))?;
180 }
181 std::thread::sleep(TICK);
182 }
183 let _ = client.Stop();
184 }
185 Ok(())
186 }
187
188 fn rms(samples: &[i16]) -> f64 {
189 let sum: f64 = samples
190 .iter()
191 .map(|sample| f64::from(*sample).powi(2))
192 .sum();
193 (sum / samples.len().max(1) as f64).sqrt()
194 }
195
196 pub fn record_process(process_id: u32, seconds: u64, out: &str) -> Result<(), String> {
197 let queue = SampleQueue::default();
198 let _capture = calling::start_process_capture(queue.clone(), process_id)
199 .map_err(|error| failed("capture", error))?;
200 record(&queue, seconds, out)
201 }
202
203 pub fn record_mic(seconds: u64, out: &str) -> Result<(), String> {
204 let queue = SampleQueue::default();
205 let started = calling::sound_capture::start_microphone(
206 &calling::DeviceChoice::SystemDefault,
207 None,
208 queue.clone(),
209 )
210 .map_err(|error| failed("microphone", error))?;
211 eprintln!("{}", started.source);
212 record(&queue, seconds, out)
213 }
214
215 fn record(queue: &SampleQueue, seconds: u64, out: &str) -> Result<(), String> {
216 let mut dump =
217 WavDump::create(std::path::Path::new(out)).map_err(|error| failed("wav", error))?;
218 let frames_per_window = WINDOW_MS * SAMPLE_RATE as usize / 1000 / FRAME_SAMPLES;
219 let mut window = Vec::new();
220 let mut loudness = Vec::new();
221 let started = Instant::now();
222 let mut next = Instant::now();
223 while started.elapsed() < Duration::from_secs(seconds) {
224 let frame = queue.next_frame().unwrap_or_else(|| vec![0; FRAME_SAMPLES]);
225 dump.write(&frame);
226 window.extend_from_slice(&frame);
227 if window.len() >= frames_per_window * FRAME_SAMPLES {
228 loudness.push(rms(&window).round());
229 window.clear();
230 }
231 next += TICK;
232 std::thread::sleep(next.saturating_duration_since(Instant::now()));
233 }
234 println!("{{\"window_ms\":{WINDOW_MS},\"rms\":{loudness:?}}}");
235 Ok(())
236 }
237}