Skip to content

Commit

Permalink
Merge branch 'dev' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
phip1611 committed Sep 11, 2021
2 parents c8a036c + 9a100ad commit 0c62259
Show file tree
Hide file tree
Showing 19 changed files with 1,184 additions and 279 deletions.
15 changes: 14 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
language: rust
rust:
- 1.52.1 # MSRV
- stable
- nightly
cache: cargo

# required to build the examples
before_script:
- sudo apt-get update
- sudo apt-get -y install libasound2-dev

script:
# build with all features/fft implementations
- cargo build --all-targets
Expand All @@ -17,9 +23,16 @@ script:
- cargo test --all-targets --no-default-features --features "microfft-complex"
- cargo test --all-targets --no-default-features --features "microfft-real"

- rustup component add rustfmt
- rustup component add clippy
# cargo format and clippy (--check doesn't change the files)
- cargo fmt -- --check
- cargo clippy
- cargo doc

# test `no_std`-build with all features/fft implementations
- rustup target add thumbv7em-none-eabihf
# nope, thats BS: this crate needs STD

# - cargo check --target thumbv7em-none-eabihf --no-default-features --features "rustfft-complex"
- cargo check --target thumbv7em-none-eabihf --no-default-features --features "microfft-complex"
- cargo check --target thumbv7em-none-eabihf --no-default-features --features "microfft-real"
Expand Down
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## v1.0.0
### Breaking Changes
- The library returns now a result and will no longer panic
under certain circumstances.
- removed `per_element_scaling_fn` in favor of
`complex_scaling_fn`, which is now just called
`scaling_fn` - the old behaviour was more confusing than
beneficial
- renamed `ComplexSpectrumScalingFunction` to `SpectrumScalingFunction` and
moved it into the `scaling`-module
- MSRV is now `1.52.1` stable
### Other
- many internal improvements
- rust-toolchain.toml for build stability and reproducibility
- really minor performance improvements (~5 %)

## v0.5.1
- Feature "rustfft-complex" uses "rustfft"-crate at version 6 which is faster/more optimized (~25%).
- improved CI
Expand Down
19 changes: 15 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description = """
A simple and fast `no_std` library to get the frequency spectrum of a digital signal (e.g. audio) using FFT.
It follows the KISS principle and consists of simple building blocks/optional features.
"""
version = "0.5.2"
version = "1.0.0"
authors = ["Philipp Schuster <[email protected]>"]
edition = "2018"
keywords = ["fft", "spectrum", "frequencies", "audio", "dsp"]
Expand Down Expand Up @@ -33,16 +33,27 @@ microfft-complex = ["microfft"]
microfft-real = ["microfft"]

[dependencies]
rustfft = { version = "6.0.0", optional = true }
microfft = { version = "0.4.0", optional = true }
rustfft = { version = "6.0", optional = true }
microfft = { version = "0.4", optional = true }
# approx. compare floats; not only in tests but also during runtime
float-cmp = "0.8.0"
float-cmp = "0.9.0"
# sin() cos() log10() etc for no_std-environments; these are not part of Core library
libm = "0.2.1"

[dev-dependencies]
# readmp3 files in tests and examples
minimp3 = "0.5.1"
# visualize spectrum in tests and examples
audio-visualizer = "0.2.2"
# get audio input in examples
cpal = "0.13.4"
# CLI example
tui = { version = "0.16", default-features = false, features = ['crossterm'] }
crossterm = "0.21.0"
# audio data buffering
ringbuffer = "0.7.1"
rand = "0.8.4"


# otherwise FFT and other code is too slow
[profile.dev]
Expand Down
29 changes: 13 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ via Cargo features.

**I'm not an expert on digital signal processing. Code contributions are highly welcome! 🙂**

**The MSRV (minimum supported Rust version) is 1.51 Stable because this crate needs the
"resolver" feature of Cargo to cope with build problems occurring in `no_std`-builds.**
**The MSRV (minimum supported Rust version) is 1.52.1 stable.**

## I want to understand how FFT can be used to get a spectrum
Please see file [/EDUCATIONAL.md](/EDUCATIONAL.md).
Expand Down Expand Up @@ -69,29 +68,22 @@ fn main() {
}
```

## Scaling the frequency values/amplitudes
As already mentioned, there are lots of comments in the code. Short story is:
Type `ComplexSpectrumScalingFunction` can do anything like `BasicSpectrumScalingFunction` whereas `BasicSpectrumScalingFunction`
is easier to write, especially for Rust beginners.

## Performance
*Measurements taken on i7-8650U @ 3 Ghz (Single-Core) with optimized build*
*Measurements taken on i7-1165G7 @ 2.80GHz (Single-threaded) with optimized build*


| Operation | Time |
| ------------------------------------------------------ | ------:|
| Hann Window with 4096 samples | ≈70µs |
| Hamming Window with 4096 samples | ≈10µs |
| Hann Window with 16384 samples | ≈175µs |
| Hamming Window with 16384 samples | ≈44µs |
| FFT (`rustfft/complex`) to spectrum with 4096 samples | ≈240µs |
| FFT (`rustfft/complex`) to spectrum with 16384 samples | ≈740µs |
| FFT (`microfft/real`) to spectrum with 4096 samples | ≈120µs |
| Hann Window with 4096 samples | ≈68µs |
| Hamming Window with 4096 samples | ≈118µs |
| FFT (`rustfft/complex`) to spectrum with 4096 samples | ≈170µs |
| FFT (`microfft/real`) to spectrum with 4096 samples | ≈90µs |
| FFT (`microfft/complex`) to spectrum with 4096 samples | ≈250µs |

## Example visualization
In the following example you can see a basic visualization of frequencies `0 to 4000Hz` for
a layered signal of sine waves of `50`, `1000`, and `3777Hz` @ `44100Hz` sampling rate. The peaks for the
given frequencies are clearly visible. Each calculation was done with `2048` samples, i.e. ≈46ms.
given frequencies are clearly visible. Each calculation was done with `2048` samples, i.e. ≈46ms of audio signal.

**The noise (wrong peaks) also comes from clipping of the added sine waves!**

Expand All @@ -107,6 +99,11 @@ Peaks (50, 1000, 3777 Hz) are clearly visible and Hann window reduces noise a li
Peaks (50, 1000, 3777 Hz) are clearly visible and Hamming window reduces noise a little bit. Because this example has few noise, you don't see much difference.
![Visualization of spectrum 0-4000Hz of layered sine signal (50, 1000, 3777 Hz)) with Hamming window function.](spectrum_sine_waves_50_1000_3777hz--hamming-window.png "Peaks (50, 1000, 3777 Hz) are clearly visible and Hamming window reduces noise a little bit. Because this example has few noise, you don't see much difference.")

## Building and Executing Tests
To execute tests you need the package `libfreetype6-dev` (on Ubuntu/Debian). This is required because
not all tests are "automatic unit tests" but also tests that you need to check visually, by looking at the
generated diagram of the spectrum.

## Trivia / FAQ
### Why f64 and no f32?
I tested f64 but the additional accuracy doesn't pay out the ~40% calculation overhead (on x86_64).
Expand Down
7 changes: 7 additions & 0 deletions check-build.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
set -e
set -x

echo "checks that this builds on std+no_std + that all tests run + that all features compile"
cargo build --all-targets
cargo build --all-targets --no-default-features --features "rustfft-complex"
Expand All @@ -9,6 +12,10 @@ cargo test --all-targets --no-default-features --features "rustfft-complex"
cargo test --all-targets --no-default-features --features "microfft-complex"
cargo test --all-targets --no-default-features --features "microfft-real"

cargo fmt
cargo fmt -- --check # (--check doesn't change the files)
cargo doc

# test no_std
rustup target add thumbv7em-none-eabihf
# nope, thats BS: this crate needs STD
Expand Down
99 changes: 99 additions & 0 deletions examples/bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
MIT License
Copyright (c) 2021 Philipp Schuster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#![deny(
clippy::all,
clippy::cargo,
clippy::nursery,
// clippy::restriction,
// clippy::pedantic
)]
// now allow a few rules which are denied by the above statement
// --> they are ridiculous and not necessary
#![allow(
clippy::suboptimal_flops,
clippy::redundant_pub_crate,
clippy::fallible_impl_from
)]
#![deny(missing_debug_implementations)]
#![deny(rustdoc::all)]

use std::time::Instant;

use spectrum_analyzer::*;

/// Benchmark can be used to check how changes effect the performance.
/// Always execute with release flag!
fn main() {
// create 2048 random samples
let samples = (0..2048)
.map(|_| rand::random::<i16>())
.map(|x| x as f32)
.collect::<Vec<_>>();
let hann_window = windows::hann_window(&samples);

let bench_res_without_scaling = bench_without_scaling(hann_window.clone());
let bench_res_with_scaling = bench_with_scaling(hann_window);

println!(
"Bench without scaling: avg = {}us per Iteration",
bench_res_without_scaling
);
println!(
"Bench with scaling: avg = {}us per Iteration",
bench_res_with_scaling
);
}

fn bench_without_scaling(samples: Vec<f32>) -> u64 {
let fnc = move || samples_fft_to_spectrum(&samples, 44100, FrequencyLimit::All, None).unwrap();
bench_fnc(Box::new(fnc))
}

fn bench_with_scaling(samples: Vec<f32>) -> u64 {
let fnc = move || {
samples_fft_to_spectrum(
&samples,
44100,
FrequencyLimit::All,
Some(&scaling::divide_by_N),
)
.unwrap()
};
bench_fnc(Box::new(fnc))
}

fn bench_fnc(fnc: Box<dyn Fn() -> FrequencySpectrum>) -> u64 {
// warm-up
for _ in 0..10 {
let _ = fnc();
}
let now = Instant::now();
let runs = 10000;
for _ in 0..runs {
let _ = fnc();
}
let duration = now.elapsed();
(duration.as_micros() / runs) as u64
}
Loading

0 comments on commit 0c62259

Please sign in to comment.