M2: tsc-audio, tsc-store and tsctl voice
- tsc-audio: Opus voice/music encoder producing TeamSpeak voice packets, framer, rubato resampling, WAV I/O, tone/Goertzel helpers, cpal capture/playback over lock-free ring buffers; the vendored AudioHandler is the jitter buffer/mixer. - tsc-store: SQLite (bundled, WAL, 0600) with migrations for identities, bookmarks, settings and paged chat history; Secrets trait with memory and OS keyring backends. - tsctl voice send (WAV or tone, real time) / record (mix to WAV, --expect-tone check). The smoke test now includes a voice round-trip: 1 kHz tone ratio ~0.95 on TS3 and TS6. - Dev profile: no debug info for dependencies (target/ 16 GB -> 2.4 GB). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
301a543c5e
commit
90e05723da
20 files changed
+2379
-35
No files matched your search
@@ -0,0 +1,134 @@
|
||||
//! Audio capture and playback through cpal.
|
||||
//!
|
||||
//! The device callbacks only move samples through lock-free ring buffers; all
|
||||
//! processing happens on the caller's side.
|
||||
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use rtrb::{Consumer, Producer, RingBuffer};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// A device as shown in settings.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DeviceInfo {
|
||||
pub name: String,
|
||||
pub input: bool,
|
||||
pub output: bool,
|
||||
}
|
||||
|
||||
fn device_error(e: impl std::fmt::Display) -> Error {
|
||||
Error::Device(e.to_string())
|
||||
}
|
||||
|
||||
/// All devices of the default host.
|
||||
pub fn list_devices() -> Result<Vec<DeviceInfo>> {
|
||||
let host = cpal::default_host();
|
||||
let devices = host.devices().map_err(device_error)?;
|
||||
Ok(devices
|
||||
.map(|d| DeviceInfo {
|
||||
name: d.description().map(|d| d.name().to_string()).unwrap_or_default(),
|
||||
input: d.supports_input(),
|
||||
output: d.supports_output(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Running capture stream. Samples are interleaved at the device's rate.
|
||||
pub struct Capture {
|
||||
_stream: cpal::Stream,
|
||||
consumer: Consumer<f32>,
|
||||
pub channels: usize,
|
||||
pub rate: u32,
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
/// Open the default input device, buffering up to `buffer_ms` of audio.
|
||||
pub fn open_default(buffer_ms: u32) -> Result<Self> {
|
||||
let device = cpal::default_host()
|
||||
.default_input_device()
|
||||
.ok_or_else(|| Error::Device("no input device".into()))?;
|
||||
let config = device.default_input_config().map_err(device_error)?.config();
|
||||
let channels = config.channels as usize;
|
||||
let rate = config.sample_rate;
|
||||
let (mut producer, consumer) =
|
||||
RingBuffer::new((rate * buffer_ms / 1000) as usize * channels);
|
||||
let stream = device
|
||||
.build_input_stream(
|
||||
config,
|
||||
move |data: &[f32], _: &cpal::InputCallbackInfo| {
|
||||
let n = producer.slots().min(data.len());
|
||||
if let Ok(chunk) = producer.write_chunk_uninit(n) {
|
||||
chunk.fill_from_iter(data[..n].iter().copied());
|
||||
}
|
||||
},
|
||||
|error| warn!(%error, "capture stream error"),
|
||||
None,
|
||||
)
|
||||
.map_err(device_error)?;
|
||||
stream.play().map_err(device_error)?;
|
||||
Ok(Self { _stream: stream, consumer, channels, rate })
|
||||
}
|
||||
|
||||
/// Move everything captured so far into `out`.
|
||||
pub fn read_available(&mut self, out: &mut Vec<f32>) {
|
||||
let n = self.consumer.slots();
|
||||
if let Ok(chunk) = self.consumer.read_chunk(n) {
|
||||
out.extend(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Running playback stream. Write interleaved samples at the device's rate.
|
||||
pub struct Playback {
|
||||
_stream: cpal::Stream,
|
||||
producer: Producer<f32>,
|
||||
pub channels: usize,
|
||||
pub rate: u32,
|
||||
}
|
||||
|
||||
impl Playback {
|
||||
pub fn open_default(buffer_ms: u32) -> Result<Self> {
|
||||
let device = cpal::default_host()
|
||||
.default_output_device()
|
||||
.ok_or_else(|| Error::Device("no output device".into()))?;
|
||||
let config = device.default_output_config().map_err(device_error)?.config();
|
||||
let channels = config.channels as usize;
|
||||
let rate = config.sample_rate;
|
||||
let (producer, mut consumer) =
|
||||
RingBuffer::<f32>::new((rate * buffer_ms / 1000) as usize * channels);
|
||||
let stream = device
|
||||
.build_output_stream(
|
||||
config,
|
||||
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
||||
let n = consumer.slots().min(data.len());
|
||||
if let Ok(chunk) = consumer.read_chunk(n) {
|
||||
for (dst, src) in data.iter_mut().zip(chunk) {
|
||||
*dst = src;
|
||||
}
|
||||
}
|
||||
// Underrun: play silence.
|
||||
data[n..].fill(0.0);
|
||||
},
|
||||
|error| warn!(%error, "playback stream error"),
|
||||
None,
|
||||
)
|
||||
.map_err(device_error)?;
|
||||
stream.play().map_err(device_error)?;
|
||||
Ok(Self { _stream: stream, producer, channels, rate })
|
||||
}
|
||||
|
||||
/// Queue samples; returns how many fit into the buffer.
|
||||
pub fn write(&mut self, samples: &[f32]) -> usize {
|
||||
let n = self.producer.slots().min(samples.len());
|
||||
if let Ok(chunk) = self.producer.write_chunk_uninit(n) {
|
||||
chunk.fill_from_iter(samples[..n].iter().copied());
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Samples that can be written without blocking.
|
||||
pub fn free(&self) -> usize {
|
||||
self.producer.slots()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Opus encoding into TeamSpeak voice packets.
|
||||
|
||||
use opus2::{Application, Bitrate, Channels, Encoder};
|
||||
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
|
||||
|
||||
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Largest possible Opus packet.
|
||||
const MAX_PACKET: usize = 1275;
|
||||
|
||||
/// The two Opus codecs TeamSpeak channels use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VoiceCodec {
|
||||
/// Mono, tuned for speech (`CodecType::OpusVoice`).
|
||||
Voice,
|
||||
/// Stereo, tuned for music (`CodecType::OpusMusic`).
|
||||
Music,
|
||||
}
|
||||
|
||||
impl VoiceCodec {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
VoiceCodec::Voice => 1,
|
||||
VoiceCodec::Music => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec_type(self) -> CodecType {
|
||||
match self {
|
||||
VoiceCodec::Voice => CodecType::OpusVoice,
|
||||
VoiceCodec::Music => CodecType::OpusMusic,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples (all channels) in one 20 ms frame.
|
||||
pub fn frame_len(self) -> usize {
|
||||
FRAME_SAMPLES * self.channels()
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
|
||||
pub struct VoiceEncoder {
|
||||
encoder: Encoder,
|
||||
codec: VoiceCodec,
|
||||
out: Vec<u8>,
|
||||
}
|
||||
|
||||
impl VoiceEncoder {
|
||||
pub fn new(codec: VoiceCodec) -> Result<Self> {
|
||||
let (channels, application) = match codec {
|
||||
VoiceCodec::Voice => (Channels::Mono, Application::Voip),
|
||||
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
|
||||
};
|
||||
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
|
||||
// Survive some packet loss: TeamSpeak voice is plain UDP.
|
||||
encoder.set_inband_fec(true)?;
|
||||
encoder.set_packet_loss_perc(5)?;
|
||||
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
|
||||
}
|
||||
|
||||
pub fn codec(&self) -> VoiceCodec {
|
||||
self.codec
|
||||
}
|
||||
|
||||
/// Target bitrate in bits per second.
|
||||
pub fn set_bitrate(&mut self, bps: i32) -> Result<()> {
|
||||
self.encoder.set_bitrate(Bitrate::Bits(bps))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode one frame of [`VoiceCodec::frame_len`] interleaved samples.
|
||||
pub fn encode_to_bytes(&mut self, frame: &[f32]) -> Result<&[u8]> {
|
||||
if frame.len() != self.codec.frame_len() {
|
||||
return Err(Error::Invalid(format!(
|
||||
"frame has {} samples, expected {}",
|
||||
frame.len(),
|
||||
self.codec.frame_len()
|
||||
)));
|
||||
}
|
||||
let len = self.encoder.encode_float(frame, &mut self.out)?;
|
||||
Ok(&self.out[..len])
|
||||
}
|
||||
|
||||
/// Encode one frame into a packet ready for `Connection::send_audio`.
|
||||
/// The connection assigns the packet id.
|
||||
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
|
||||
let codec = self.codec.codec_type();
|
||||
let data = self.encode_to_bytes(frame)?;
|
||||
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
|
||||
}
|
||||
|
||||
/// The empty packet that tells listeners the transmission ended.
|
||||
pub fn end_of_stream(&self) -> OutPacket {
|
||||
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tsproto_packets::packets::{Direction, InAudioBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::pcm;
|
||||
|
||||
/// Encode a tone, feed the packets through the mixer (jitter buffer +
|
||||
/// decoder), and check the tone comes out.
|
||||
#[test]
|
||||
fn roundtrip_through_mixer() {
|
||||
let mut encoder = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
|
||||
let mut mixer = crate::Mixer::new();
|
||||
let tone = pcm::sine(1000.0, 1.0, 0.5);
|
||||
let mut decoded = Vec::new();
|
||||
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
|
||||
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
|
||||
let packet = OutAudio::new(&AudioData::S2C {
|
||||
id: i as u16,
|
||||
codec: CodecType::OpusVoice,
|
||||
from: 7,
|
||||
data: &data,
|
||||
});
|
||||
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
|
||||
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
|
||||
let mut out = vec![0.0; FRAME_SAMPLES * 2];
|
||||
mixer.fill_buffer(&mut out);
|
||||
decoded.extend(pcm::to_mono(&out, 2));
|
||||
}
|
||||
// Skip the jitter buffer's initial latency and the codec warm-up.
|
||||
let tail = &decoded[decoded.len() / 2..];
|
||||
let ratio = pcm::tone_ratio(tail, 1000.0, SAMPLE_RATE);
|
||||
assert!(ratio > 0.8, "tone ratio {ratio}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_frame_size() {
|
||||
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
|
||||
assert!(encoder.encode(&[0.0; FRAME_SAMPLES]).is_err());
|
||||
assert!(encoder.encode(&[0.0; FRAME_SAMPLES * 2]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Cut a continuous sample stream into fixed-size frames.
|
||||
|
||||
/// Buffers samples until a whole frame is available.
|
||||
#[derive(Debug)]
|
||||
pub struct Framer {
|
||||
frame_len: usize,
|
||||
buf: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Framer {
|
||||
/// `frame_len` is in samples (all channels, interleaved).
|
||||
pub fn new(frame_len: usize) -> Self {
|
||||
assert!(frame_len > 0);
|
||||
Self { frame_len, buf: Vec::with_capacity(frame_len * 2) }
|
||||
}
|
||||
|
||||
/// Append samples and call `f` for every complete frame.
|
||||
pub fn push(&mut self, samples: &[f32], mut f: impl FnMut(&[f32])) {
|
||||
self.buf.extend_from_slice(samples);
|
||||
let whole = self.buf.len() / self.frame_len * self.frame_len;
|
||||
for frame in self.buf[..whole].chunks_exact(self.frame_len) {
|
||||
f(frame);
|
||||
}
|
||||
self.buf.drain(..whole);
|
||||
}
|
||||
|
||||
/// Pad the remaining samples with silence into one last frame, if any.
|
||||
pub fn flush(&mut self, f: impl FnOnce(&[f32])) {
|
||||
if !self.buf.is_empty() {
|
||||
self.buf.resize(self.frame_len, 0.0);
|
||||
f(&self.buf);
|
||||
self.buf.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn buffered(&self) -> usize {
|
||||
self.buf.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frames_and_flushes() {
|
||||
let mut framer = Framer::new(4);
|
||||
let mut frames = Vec::new();
|
||||
framer.push(&[1.0, 2.0, 3.0], |f| frames.push(f.to_vec()));
|
||||
assert!(frames.is_empty());
|
||||
framer.push(&[4.0, 5.0, 6.0, 7.0, 8.0, 9.0], |f| frames.push(f.to_vec()));
|
||||
assert_eq!(frames, vec![vec![1.0, 2.0, 3.0, 4.0], vec![5.0, 6.0, 7.0, 8.0]]);
|
||||
assert_eq!(framer.buffered(), 1);
|
||||
framer.flush(|f| frames.push(f.to_vec()));
|
||||
assert_eq!(frames[2], vec![9.0, 0.0, 0.0, 0.0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Voice pipeline building blocks.
|
||||
//!
|
||||
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
|
||||
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
|
||||
//! - [`framer`]: slice an arbitrary sample stream into codec frames
|
||||
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
|
||||
//! - [`wav`]: WAV file input/output
|
||||
//! - [`Mixer`]: per-client jitter buffer, decoder and mixer (from the vendored
|
||||
//! `tsclientlib::audio::AudioHandler`)
|
||||
//! - `device` (feature `device`): capture and playback through cpal
|
||||
|
||||
pub mod encode;
|
||||
pub mod framer;
|
||||
pub mod pcm;
|
||||
pub mod resample;
|
||||
pub mod wav;
|
||||
|
||||
#[cfg(feature = "device")]
|
||||
pub mod device;
|
||||
|
||||
pub use encode::{VoiceCodec, VoiceEncoder};
|
||||
pub use framer::Framer;
|
||||
pub use tsclientlib::audio::AudioHandler;
|
||||
|
||||
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
|
||||
pub type Mixer = AudioHandler<tsclientlib::ClientId>;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("opus: {0}")]
|
||||
Opus(#[from] opus2::Error),
|
||||
#[error("wav: {0}")]
|
||||
Wav(#[from] hound::Error),
|
||||
#[error("resampling failed: {0}")]
|
||||
Resample(String),
|
||||
#[error("audio device: {0}")]
|
||||
Device(String),
|
||||
#[error("invalid input: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -0,0 +1,101 @@
|
||||
//! PCM constants and helpers.
|
||||
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
/// The sample rate TeamSpeak's Opus codecs run at.
|
||||
pub const SAMPLE_RATE: u32 = 48_000;
|
||||
/// Samples per channel in one 20 ms frame.
|
||||
pub const FRAME_SAMPLES: usize = SAMPLE_RATE as usize / 50;
|
||||
|
||||
/// A sine tone, mono, at [`SAMPLE_RATE`].
|
||||
pub fn sine(freq: f32, seconds: f32, amplitude: f32) -> Vec<f32> {
|
||||
let n = (seconds * SAMPLE_RATE as f32) as usize;
|
||||
(0..n).map(|i| amplitude * (TAU * freq * i as f32 / SAMPLE_RATE as f32).sin()).collect()
|
||||
}
|
||||
|
||||
/// Average interleaved channels into mono.
|
||||
pub fn to_mono(interleaved: &[f32], channels: usize) -> Vec<f32> {
|
||||
if channels <= 1 {
|
||||
return interleaved.to_vec();
|
||||
}
|
||||
interleaved.chunks_exact(channels).map(|f| f.iter().sum::<f32>() / channels as f32).collect()
|
||||
}
|
||||
|
||||
/// Duplicate mono samples into `channels` interleaved channels.
|
||||
pub fn from_mono(mono: &[f32], channels: usize) -> Vec<f32> {
|
||||
mono.iter().flat_map(|&s| std::iter::repeat_n(s, channels)).collect()
|
||||
}
|
||||
|
||||
/// Power of one frequency in `samples` (Goertzel algorithm), normalised so a
|
||||
/// full-scale sine at `freq` gives about 0.25 per sample squared.
|
||||
pub fn goertzel_power(samples: &[f32], freq: f32, rate: u32) -> f32 {
|
||||
if samples.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let coeff = 2.0 * (TAU * freq / rate as f32).cos();
|
||||
let (mut s1, mut s2) = (0.0f32, 0.0f32);
|
||||
for &x in samples {
|
||||
let s = x + coeff * s1 - s2;
|
||||
s2 = s1;
|
||||
s1 = s;
|
||||
}
|
||||
let power = s1 * s1 + s2 * s2 - coeff * s1 * s2;
|
||||
power / (samples.len() as f32 * samples.len() as f32)
|
||||
}
|
||||
|
||||
/// Mean square of the signal.
|
||||
pub fn energy(samples: &[f32]) -> f32 {
|
||||
if samples.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32
|
||||
}
|
||||
|
||||
/// Fraction of the signal energy at `freq`: close to 1 for a clean tone,
|
||||
/// close to 0 for silence or noise.
|
||||
pub fn tone_ratio(samples: &[f32], freq: f32, rate: u32) -> f32 {
|
||||
let e = energy(samples);
|
||||
if e < 1e-9 {
|
||||
return 0.0;
|
||||
}
|
||||
// A sine of amplitude a has energy a²/2 and Goertzel power a²/4.
|
||||
(2.0 * goertzel_power(samples, freq, rate) / e).min(1.0)
|
||||
}
|
||||
|
||||
/// Like [`tone_ratio`], but only over the 100 ms windows that are not silent,
|
||||
/// so leading and trailing silence in a recording do not dilute the result.
|
||||
pub fn voiced_tone_ratio(samples: &[f32], freq: f32, rate: u32) -> f32 {
|
||||
let window = rate as usize / 10;
|
||||
let ratios: Vec<f32> = samples
|
||||
.chunks_exact(window)
|
||||
.filter(|w| energy(w) > 1e-4)
|
||||
.map(|w| tone_ratio(w, freq, rate))
|
||||
.collect();
|
||||
if ratios.is_empty() { 0.0 } else { ratios.iter().sum::<f32>() / ratios.len() as f32 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_tone() {
|
||||
let tone = sine(1000.0, 0.5, 0.5);
|
||||
assert!(tone_ratio(&tone, 1000.0, SAMPLE_RATE) > 0.95);
|
||||
assert!(tone_ratio(&tone, 440.0, SAMPLE_RATE) < 0.05);
|
||||
assert_eq!(tone_ratio(&[0.0; 100], 1000.0, SAMPLE_RATE), 0.0);
|
||||
|
||||
let mut padded = vec![0.0; SAMPLE_RATE as usize];
|
||||
padded.extend(&tone);
|
||||
padded.extend(vec![0.0; SAMPLE_RATE as usize]);
|
||||
assert!(tone_ratio(&padded, 1000.0, SAMPLE_RATE) < 0.5);
|
||||
assert!(voiced_tone_ratio(&padded, 1000.0, SAMPLE_RATE) > 0.95);
|
||||
assert_eq!(voiced_tone_ratio(&[0.0; 48_000], 1000.0, SAMPLE_RATE), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_conversion() {
|
||||
assert_eq!(to_mono(&[1.0, 3.0, 2.0, 4.0], 2), vec![2.0, 3.0]);
|
||||
assert_eq!(from_mono(&[1.0, 2.0], 2), vec![1.0, 1.0, 2.0, 2.0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Sample-rate conversion.
|
||||
|
||||
use rubato::audioadapter_buffers::direct::InterleavedSlice;
|
||||
use rubato::{Fft, FixedSync, Resampler};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Resample a whole interleaved clip from `from` Hz to `to` Hz.
|
||||
pub fn resample_all(samples: &[f32], channels: usize, from: u32, to: u32) -> Result<Vec<f32>> {
|
||||
if from == to || samples.is_empty() {
|
||||
return Ok(samples.to_vec());
|
||||
}
|
||||
if channels == 0 || !samples.len().is_multiple_of(channels) {
|
||||
return Err(Error::Invalid(format!("{} samples for {channels} channels", samples.len())));
|
||||
}
|
||||
let frames = samples.len() / channels;
|
||||
let mut resampler =
|
||||
Fft::<f32>::new(from as usize, to as usize, 1024, channels, FixedSync::Input)
|
||||
.map_err(|e| Error::Resample(e.to_string()))?;
|
||||
let input = InterleavedSlice::new(samples, channels, frames)
|
||||
.map_err(|e| Error::Resample(e.to_string()))?;
|
||||
let output =
|
||||
resampler.process_all(&input, frames, None).map_err(|e| Error::Resample(e.to_string()))?;
|
||||
Ok(output.take_data())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pcm;
|
||||
|
||||
#[test]
|
||||
fn keeps_tone_across_rates() {
|
||||
// 1 kHz at 44.1 kHz, resampled to 48 kHz.
|
||||
let n = 44_100;
|
||||
let tone: Vec<f32> = (0..n)
|
||||
.map(|i| 0.5 * (std::f32::consts::TAU * 1000.0 * i as f32 / 44_100.0).sin())
|
||||
.collect();
|
||||
let out = resample_all(&tone, 1, 44_100, 48_000).unwrap();
|
||||
assert!((out.len() as i64 - 48_000).abs() < 100, "len {}", out.len());
|
||||
assert!(pcm::tone_ratio(&out, 1000.0, 48_000) > 0.95);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passthrough_and_errors() {
|
||||
assert_eq!(resample_all(&[1.0, 2.0], 1, 48_000, 48_000).unwrap(), vec![1.0, 2.0]);
|
||||
assert!(resample_all(&[1.0, 2.0, 3.0], 2, 44_100, 48_000).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! WAV file input and output (float samples in memory).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use hound::{SampleFormat, WavReader, WavSpec, WavWriter};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
/// Interleaved samples plus their format.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Clip {
|
||||
pub samples: Vec<f32>,
|
||||
pub channels: usize,
|
||||
pub rate: u32,
|
||||
}
|
||||
|
||||
pub fn read(path: &Path) -> Result<Clip> {
|
||||
let mut reader = WavReader::open(path)?;
|
||||
let spec = reader.spec();
|
||||
let samples = match spec.sample_format {
|
||||
SampleFormat::Float => reader.samples::<f32>().collect::<std::result::Result<_, _>>()?,
|
||||
SampleFormat::Int => {
|
||||
let scale = 1.0 / (1u64 << (spec.bits_per_sample - 1)) as f32;
|
||||
reader
|
||||
.samples::<i32>()
|
||||
.map(|s| s.map(|s| s as f32 * scale))
|
||||
.collect::<std::result::Result<_, _>>()?
|
||||
}
|
||||
};
|
||||
Ok(Clip { samples, channels: spec.channels as usize, rate: spec.sample_rate })
|
||||
}
|
||||
|
||||
/// Write 16-bit PCM.
|
||||
pub fn write(path: &Path, clip: &Clip) -> Result<()> {
|
||||
let spec = WavSpec {
|
||||
channels: clip.channels as u16,
|
||||
sample_rate: clip.rate,
|
||||
bits_per_sample: 16,
|
||||
sample_format: SampleFormat::Int,
|
||||
};
|
||||
let mut writer = WavWriter::create(path, spec)?;
|
||||
for &s in &clip.samples {
|
||||
writer.write_sample((s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16)?;
|
||||
}
|
||||
writer.finalize()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let path = std::env::temp_dir().join(format!("tsc-audio-{}.wav", std::process::id()));
|
||||
let clip = Clip { samples: vec![0.0, 0.5, -0.5, 0.25], channels: 2, rate: 48_000 };
|
||||
write(&path, &clip).unwrap();
|
||||
let back = read(&path).unwrap();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!((back.channels, back.rate), (2, 48_000));
|
||||
for (a, b) in clip.samples.iter().zip(&back.samples) {
|
||||
assert!((a - b).abs() < 1e-3);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user