Skip to content

Commit

Permalink
refactor(clippy): address all clippy::pedantic lints
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-msp committed Apr 19, 2024
1 parent f17888a commit 73d5f5d
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 96 deletions.
2 changes: 1 addition & 1 deletion src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Daemon {
to_whisper.send(TranscriptionJob::new(
audio,
self.config.strategy(),
metadata.sample_rate.0 as i32,
metadata.sample_rate.0,
))?;
let now = std::time::Instant::now();

Expand Down
18 changes: 9 additions & 9 deletions src/app/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,21 @@ impl From<sttx::Timing> for Response {
impl std::fmt::Display for Response {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::Ack(n) => write!(f, "ACK {}", n),
Self::Ack(n) => write!(f, "ACK {n}"),
Self::Nil => write!(f, "NIL"),
Self::Error(s) => write!(f, "ERROR {}", s),
Self::Exit(code) => write!(f, "EXIT {}", code),
Self::NewMode(mode) => write!(f, "NEW_MODE {}", mode),
Self::Error(s) => write!(f, "ERROR {s}"),
Self::Exit(code) => write!(f, "EXIT {code}"),
Self::NewMode(mode) => write!(f, "NEW_MODE {mode}"),
Self::Transcription {
content: Some(s),
mode,
} => match mode {
Mode::Standard => write!(f, "TX {}", s),
Mode::Standard => write!(f, "TX {s}"),
// TODO: use contents?
Mode::Clipboard { .. } => write!(f, "TX_CLIP {}", s),
Mode::LiveTyping => write!(f, "TX_LIVE {}", s),
Mode::Chat(Chat::StartNew(system)) => write!(f, "TX_CHAT {} {}", system, s),
Mode::Chat(Chat::Continue) => write!(f, "TX_CHAT {}", s),
Mode::Clipboard { .. } => write!(f, "TX_CLIP {s}"),
Mode::LiveTyping => write!(f, "TX_LIVE {s}"),
Mode::Chat(Chat::StartNew(system)) => write!(f, "TX_CHAT {system} {s}"),
Mode::Chat(Chat::Continue) => write!(f, "TX_CHAT {s}"),
},
Self::Transcription { content: None, .. } => write!(f, "TX_EMPTY"),
}
Expand Down
12 changes: 3 additions & 9 deletions src/app/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,20 +109,14 @@ impl State {
match cmd {
Command::Start(session) => self.start(session.clone()),
Command::Stop => self.stop(),
Command::Mode(mode) => {
if !self.running() {
self.change_mode(mode.clone())
} else {
false
}
}
Command::Mode(mode) if !self.running() => self.change_mode(mode.clone()),
Command::Mode(_) => false,
// Nothing changes about the state when we send these commands, but we still need to
// return true so the event loop is triggered.
//
// TODO: I should consider making the event loop not sort of dependent on changes in
// the state and find some other way to represent that.
Command::Reset => true,
Command::Respond(_) => true,
Command::Reset | Command::Respond(_) => true,
}
}
}
Expand Down
22 changes: 9 additions & 13 deletions src/audio/input.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{
fmt::{Debug, Display},
ops::Deref,
sync::{Arc, Condvar, Mutex},
thread,
};
Expand All @@ -27,17 +26,17 @@ impl<T: Debug + Clone + PartialEq> Notifier<T> {
cvar.notify_one();
}

pub fn wait_until(&self, value: T) {
pub fn wait_until(&self, value: &T) {
let (lock, cvar) = &*self.0;
log::trace!("Trying to lock (wait_until)");
let mut state = lock.lock().unwrap();
log::trace!("Locked (wait_until)");
log::trace!("Waiting for value: {:?}", value);
while *state != value {
while *state != *value {
state = cvar.wait(state).unwrap();
log::trace!("got value: {:?}", state.deref());
if *state != value {
log::trace!("Got wrong value ({:?}), continuing", state.deref());
log::trace!("got value: {:?}", &*state);
if *state != *value {
log::trace!("Got wrong value ({:?}), continuing", &*state);
}
}
}
Expand Down Expand Up @@ -82,7 +81,7 @@ impl Controller {
}

pub fn wait_for(&self, state: RecordState) {
self.notifier.wait_until(state);
self.notifier.wait_until(&state);
}
}

Expand Down Expand Up @@ -216,8 +215,7 @@ where
.find_map(|c| {
let sample_rate = session
.sample_rate()
.map(SampleRate)
.unwrap_or_else(|| c.min_sample_rate().max(SampleRate(16000)));
.map_or_else(|| c.min_sample_rate().max(SampleRate(16000)), SampleRate);
if c.min_sample_rate() > sample_rate || c.max_sample_rate() < sample_rate {
None
} else {
Expand All @@ -237,8 +235,7 @@ where
let cfg_inner = cfg.clone();
if cfg.channels == 1 {
let resampler =
super::process::Processor::<f32, S, 1>::new(chan.clone(), cfg_inner.clone(), 512)
.expect("failed to create resampler");
super::process::Processor::<f32, S, 1>::new(chan.clone(), cfg_inner.clone(), 512);

let resampler = Arc::new(Mutex::new(resampler));
{
Expand All @@ -261,8 +258,7 @@ where
}
} else if cfg.channels == 2 {
let resampler =
super::process::Processor::<f32, S, 2>::new(chan.clone(), cfg_inner.clone(), 512)
.expect("failed to create resampler");
super::process::Processor::<f32, S, 2>::new(chan.clone(), cfg_inner.clone(), 512);

let resampler = Arc::new(Mutex::new(resampler));
{
Expand Down
30 changes: 15 additions & 15 deletions src/audio/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ where
S: cpal::Sample + dasp::Sample + Default,
O: MySample,
{
pub fn new(
sink: Sender<O>,
config: cpal::StreamConfig,
chunk_size_out: usize,
) -> Result<Self, anyhow::Error> {
pub fn new(sink: Sender<O>, config: cpal::StreamConfig, chunk_size_out: usize) -> Self {
let input_rate = config.sample_rate.0 as usize;
let channels = config.channels as usize;
log::debug!(
Expand All @@ -33,19 +29,19 @@ where
channels
);

Ok(Self {
Self {
config,
buffer: ring_buffer::Bounded::from([[S::default(); CHANNELS]; 64]),
sink,
})
}
}
}

impl<S, O> Processor<S, O, 1>
where
S: cpal::Sample + dasp::Sample + dasp::Frame + Default,
{
fn interpolator(&self) -> Sinc<[S; 128]> {
fn interpolator() -> Sinc<[S; 128]> {
Sinc::new(ring_buffer::Fixed::from([S::default(); 128]))
}
}
Expand All @@ -54,7 +50,7 @@ impl<S, O> Processor<S, O, 2>
where
S: cpal::Sample + dasp::Sample + Default,
{
fn interpolator(&self) -> Sinc<[[S; 2]; 128]> {
fn interpolator() -> Sinc<[[S; 2]; 128]> {
Sinc::new(ring_buffer::Fixed::from([[S::default(); 2]; 128]))
}
}
Expand All @@ -63,8 +59,8 @@ impl<O: MySample> Processor<f32, O, 1> {
pub fn mono_samples<'a>(&'a mut self, input: &'a [f32]) -> impl Iterator<Item = O> + 'a {
let signal = dasp::signal::from_iter(input.iter().copied());
let new_signal = signal.from_hz_to_hz(
self.interpolator(),
self.config.sample_rate.0 as f64,
Self::interpolator(),
f64::from(self.config.sample_rate.0),
16_000.0,
);
new_signal
Expand All @@ -74,7 +70,9 @@ impl<O: MySample> Processor<f32, O, 1> {

pub fn write_input_data(&mut self, input: &[f32]) -> Result<(), anyhow::Error> {
for sample in self.mono_samples(input).collect_vec() {
self.sink.send(sample).unwrap();
self.sink
.send(sample)
.map_err(|_| anyhow::anyhow!("Failed to send sample"))?;
}

Ok(())
Expand All @@ -87,8 +85,8 @@ impl<O: MySample> Processor<f32, O, 2> {
dasp::signal::from_interleaved_samples_iter::<_, [f32; 2]>(input.iter().copied());
let new_signal = signal
.from_hz_to_hz(
self.interpolator(),
self.config.sample_rate.0 as f64,
Self::interpolator(),
f64::from(self.config.sample_rate.0),
16_000.0,
)
.buffered(self.buffer);
Expand All @@ -100,7 +98,9 @@ impl<O: MySample> Processor<f32, O, 2> {

pub fn write_input_data(&mut self, input: &[f32]) -> Result<(), anyhow::Error> {
for sample in self.mono_samples(input).collect_vec() {
self.sink.send(sample).unwrap();
self.sink
.send(sample)
.map_err(|_| anyhow::anyhow!("Failed to send sample"))?;
}

Ok(())
Expand Down
35 changes: 19 additions & 16 deletions src/audio/vad.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
iter::{repeat, Chain, Cloned, Repeat, Take},
iter::{repeat, Chain, Copied, Repeat, Take},
slice::Iter,
time::Duration,
};
Expand All @@ -16,28 +16,28 @@ pub enum SampleSize {
}

#[derive(Debug, Clone, Copy)]
pub enum VadMode {
pub enum Mode {
Quality = 0,
LowBitrate = 1,
Aggressive = 2,
VeryAggressive = 3,
}

impl From<VadMode> for BadVadMode {
fn from(value: VadMode) -> Self {
impl From<Mode> for BadVadMode {
fn from(value: Mode) -> Self {
match value {
VadMode::Quality => BadVadMode::Quality,
VadMode::LowBitrate => BadVadMode::LowBitrate,
VadMode::Aggressive => BadVadMode::Aggressive,
VadMode::VeryAggressive => BadVadMode::VeryAggressive,
Mode::Quality => BadVadMode::Quality,
Mode::LowBitrate => BadVadMode::LowBitrate,
Mode::Aggressive => BadVadMode::Aggressive,
Mode::VeryAggressive => BadVadMode::VeryAggressive,
}
}
}

#[derive(Debug, Clone, Copy)]
pub struct Config {
mode: VadMode,
sample_rate: i32,
mode: Mode,
sample_rate: u16,

sample_size: SampleSize,
resolution: Duration,
Expand All @@ -46,7 +46,7 @@ pub struct Config {
impl Default for Config {
fn default() -> Self {
Self {
mode: VadMode::Quality,
mode: Mode::Quality,
sample_rate: 16000,

sample_size: SampleSize::Medium,
Expand All @@ -66,7 +66,9 @@ impl TryFrom<&Config> for Vad {

fn try_from(cfg: &Config) -> Result<Self, Self::Error> {
Ok(Vad::new_with_rate_and_mode(
cfg.sample_rate.try_into().or(Err(Error::BadSampleRate))?,
i32::from(cfg.sample_rate)
.try_into()
.or(Err(Error::BadSampleRate))?,
cfg.mode.into(),
))
}
Expand Down Expand Up @@ -99,7 +101,8 @@ impl Buffer<'_> {

impl Config {
pub fn buffer_size(&self) -> usize {
(self.sample_size as u32 * self.sample_rate as u32 / 1000) as usize
assert!(self.sample_rate > 0);
(self.sample_size as u16 * self.sample_rate / 1000) as usize
}

pub fn buffer_from<'a>(&self, index: usize, data: &'a [i16]) -> Buffer<'a> {
Expand All @@ -121,11 +124,11 @@ impl<'a> AsRef<[i16]> for Buffer<'a> {

impl<'a> IntoIterator for Buffer<'a> {
type Item = i16;
type IntoIter = Chain<Cloned<Iter<'a, i16>>, Take<Repeat<i16>>>;
type IntoIter = Chain<Copied<Iter<'a, i16>>, Take<Repeat<i16>>>;

fn into_iter(self) -> Self::IntoIter {
let fill = self.size() - self.data.len();
self.data.iter().cloned().chain(repeat(0).take(fill))
self.data.iter().copied().chain(repeat(0).take(fill))
}
}

Expand All @@ -142,7 +145,7 @@ impl Config {

Ok(output?
.chunks(self.resolution.as_millis() as usize / self.sample_size as usize)
.map(|chk| chk.iter().cloned().filter(|x| *x).count())
.map(|chk| chk.iter().copied().filter(|x| *x).count())
.collect::<Vec<_>>())
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![deny(clippy::pedantic)]
mod app;
mod audio;
mod socket;
Expand Down
Loading

0 comments on commit 73d5f5d

Please sign in to comment.