From bcc9ec7e4870ff5e92c17406fa97ad1cfc47bac0 Mon Sep 17 00:00:00 2001 From: klangner Date: Tue, 30 Jan 2024 14:29:07 +0100 Subject: [PATCH] Added frequency shifter --- src/core/freq_shift.rs | 47 ++++++++++++++++++++++++++++++++++++++++++ src/core/mod.rs | 3 ++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 src/core/freq_shift.rs diff --git a/src/core/freq_shift.rs b/src/core/freq_shift.rs new file mode 100644 index 0000000..dde0afb --- /dev/null +++ b/src/core/freq_shift.rs @@ -0,0 +1,47 @@ +//! Node for shifting frequency of a giveen signal +//! + +use anyhow::Result; +use num_complex::Complex32; +use crate::node::ProcessNode; + +use super::generator::Sine; + + +/// Multiply buffer sample by constant value +/// +/// Example +/// +/// ``` +/// use dsp::num_complex::Complex32; +/// use dsp::node::ProcessNode; +/// use dsp::core::generator::Sine; +/// use dsp::core::freq_shift::FrequencyShift; +/// +/// let mut node = FrequencyShift::new(30., 1024); +/// let input_buffer = vec![Complex32::default(); 1024]; +/// let mut output_buffer = vec![Complex32::default(); 1024]; +/// let source = Sine::new(10., 1024); +/// node.process_buffer(&input_buffer, &mut output_buffer); +/// ``` +pub struct FrequencyShift { + offset_signal: Sine, +} + +impl FrequencyShift { + pub fn new(freq_offset: f32, sample_rate: usize) -> Self { + let offset_signal = Sine::new(freq_offset as f32, sample_rate); + Self {offset_signal} + } +} + +impl ProcessNode for FrequencyShift { + fn process_buffer(&mut self, input_buffer: &[Complex32], output_buffer: &mut [Complex32]) -> Result<()> { + let n = usize::min(input_buffer.len(), output_buffer.len()); + for i in 0..n { + output_buffer[i] = self.offset_signal.next().unwrap() * input_buffer[i]; + } + + Ok(()) + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 4fec1ca..240c7ca 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -8,4 +8,5 @@ pub mod generator; pub mod fft; pub mod file; pub mod multiply; -pub mod network; \ No newline at end of file +pub mod network; +pub mod freq_shift; \ No newline at end of file