-
-
Notifications
You must be signed in to change notification settings - Fork 122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement Short-time Fourier transform and its inverse #587
Merged
Merged
Changes from 12 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
ab5aa96
Initial stft implementation
pxl-th fb1baca
Finish STFT
pxl-th e3c8df7
Cleanup
pxl-th ab6a4bf
Bump AMDGPU compat
pxl-th 01cc8a2
Install GPU backends only when testing them
pxl-th bd76e9f
Add spectrogram
pxl-th 5460ed7
Move audio documentation to its own page
pxl-th 3eb9420
Fixes
pxl-th 97dbf65
Use Makie for spectrogram plots
pxl-th 0e5b94b
Add mel-scale filterbanks
pxl-th b54888b
Run doctests when building documentation instead of a separate CI stage
pxl-th 8f77455
Minor fix
pxl-th d85ff99
Move FFTW-dependent functions to extension
pxl-th File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,8 @@ | ||
[deps] | ||
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" | ||
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" | ||
FLAC = "abae9e3b-a9a0-4778-b5c6-ca109b507d99" | ||
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" | ||
Makie = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" | ||
NNlib = "872c559c-99b0-510c-b3b7-b6c96a88d5cd" | ||
UnicodePlots = "b8865327-cd53-5732-bb35-84acbb429228" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
# Reference | ||
|
||
## Window functions | ||
|
||
```@docs | ||
hann_window | ||
hamming_window | ||
``` | ||
|
||
## Spectral | ||
|
||
```@docs | ||
stft | ||
istft | ||
NNlib.power_to_db | ||
NNlib.db_to_power | ||
``` | ||
|
||
## Spectrogram | ||
|
||
```@docs | ||
melscale_filterbanks | ||
spectrogram | ||
``` | ||
|
||
Example: | ||
|
||
```@example 1 | ||
using NNlib | ||
using FileIO | ||
using Makie, CairoMakie | ||
CairoMakie.activate!() | ||
|
||
waveform, sampling_rate = load("./assets/jfk.flac") | ||
fig = lines(reshape(waveform, :)) | ||
save("waveform.png", fig) | ||
|
||
# Spectrogram. | ||
|
||
n_fft = 1024 | ||
spec = spectrogram(waveform; n_fft, hop_length=n_fft ÷ 4, window=hann_window(n_fft)) | ||
fig = heatmap(transpose(NNlib.power_to_db(spec)[:, :, 1])) | ||
save("spectrogram.png", fig) | ||
|
||
# Mel-scale spectrogram. | ||
|
||
n_freqs = n_fft ÷ 2 + 1 | ||
fb = melscale_filterbanks(; n_freqs, n_mels=128, sample_rate=Int(sampling_rate)) | ||
mel_spec = permutedims(spec, (2, 1, 3)) ⊠ fb # (time, n_mels) | ||
fig = heatmap(NNlib.power_to_db(mel_spec)[:, :, 1]) | ||
save("mel-spectrogram.png", fig) | ||
nothing # hide | ||
``` | ||
|
||
|Waveform|Spectrogram|Mel Spectrogram| | ||
|:---:|:---:|:---:| | ||
|![](waveform.png)|![](spectrogram.png)|![](mel-spectrogram.png)| |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
""" | ||
melscale_filterbanks(; | ||
n_freqs::Int, n_mels::Int, sample_rate::Int, | ||
fmin::Float32 = 0f0, fmax::Float32 = Float32(sample_rate ÷ 2)) | ||
|
||
Create triangular Mel scale filter banks | ||
(ref: https://en.wikipedia.org/wiki/Mel_scale). | ||
Each column is a filterbank that highlights its own frequency. | ||
|
||
# Arguments: | ||
|
||
- `n_freqs::Int`: Number of frequencies to highlight. | ||
- `n_mels::Int`: Number of mel filterbanks. | ||
- `sample_rate::Int`: Sample rate of the audio waveform. | ||
- `fmin::Float32`: Minimum frequency in Hz. | ||
- `fmax::Float32`: Maximum frequency in Hz. | ||
|
||
# Returns: | ||
|
||
Filterbank matrix of shape `(n_freqs, n_mels)` where each column is a filterbank. | ||
|
||
```jldoctest | ||
julia> n_mels = 8; | ||
|
||
julia> fb = melscale_filterbanks(; n_freqs=200, n_mels, sample_rate=16000); | ||
|
||
julia> plot = lineplot(fb[:, 1]); | ||
|
||
julia> for i in 2:n_mels | ||
lineplot!(plot, fb[:, i]) | ||
end | ||
|
||
julia> plot | ||
┌────────────────────────────────────────┐ | ||
1 │⠀⡀⢸⠀⢸⠀⠀⣧⠀⠀⢸⡄⠀⠀⠀⣷⠀⠀⠀⠀⠀⣷⠀⠀⠀⠀⠀⠀⢀⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀│ | ||
│⠀⡇⢸⡆⢸⡇⠀⣿⠀⠀⡜⡇⠀⠀⢰⠋⡆⠀⠀⠀⢰⠁⡇⠀⠀⠀⠀⠀⡸⠀⢣⠀⠀⠀⠀⠀⠀⠀⠀⠀│ | ||
│⠀⣿⢸⡇⡇⡇⢰⠹⡄⠀⡇⢱⠀⠀⢸⠀⢣⠀⠀⠀⡜⠀⢸⡀⠀⠀⠀⢀⠇⠀⠈⡇⠀⠀⠀⠀⠀⠀⠀⠀│ | ||
│⠀⣿⡇⡇⡇⡇⢸⠀⡇⢀⠇⠸⡀⠀⡇⠀⠸⡀⠀⢀⠇⠀⠀⢇⠀⠀⠀⡸⠀⠀⠀⠸⡄⠀⠀⠀⠀⠀⠀⠀│ | ||
│⢠⢻⡇⡇⡇⢱⢸⠀⢇⢸⠀⠀⡇⢀⠇⠀⠀⡇⠀⢸⠀⠀⠀⠸⡀⠀⢠⠇⠀⠀⠀⠀⢱⠀⠀⠀⠀⠀⠀⠀│ | ||
│⢸⢸⡇⢱⡇⢸⡇⠀⢸⢸⠀⠀⢣⢸⠀⠀⠀⢸⠀⡇⠀⠀⠀⠀⢇⠀⡜⠀⠀⠀⠀⠀⠈⢇⠀⠀⠀⠀⠀⠀│ | ||
│⢸⢸⡇⢸⠀⢸⡇⠀⢸⡇⠀⠀⢸⡎⠀⠀⠀⠈⣶⠁⠀⠀⠀⠀⠸⣤⠃⠀⠀⠀⠀⠀⠀⠘⡆⠀⠀⠀⠀⠀│ | ||
│⢸⠀⡇⢸⠀⠀⡇⠀⠀⡇⠀⠀⠀⡇⠀⠀⠀⠀⣿⠀⠀⠀⠀⠀⠀⣿⠀⠀⠀⠀⠀⠀⠀⠀⢱⡀⠀⠀⠀⠀│ | ||
│⢸⢸⡇⢸⠀⢸⡇⠀⢸⡇⠀⠀⢸⢇⠀⠀⠀⢀⠿⡀⠀⠀⠀⠀⢰⠛⡄⠀⠀⠀⠀⠀⠀⠀⠀⢣⠀⠀⠀⠀│ | ||
│⢸⢸⡇⡸⡇⢸⡇⠀⢸⢸⠀⠀⡜⢸⠀⠀⠀⢸⠀⡇⠀⠀⠀⠀⡎⠀⢣⠀⠀⠀⠀⠀⠀⠀⠀⠘⡆⠀⠀⠀│ | ||
│⢸⢸⡇⡇⡇⡸⢸⠀⡎⢸⠀⠀⡇⠈⡆⠀⠀⡇⠀⢸⠀⠀⠀⢰⠁⠀⠘⡆⠀⠀⠀⠀⠀⠀⠀⠀⠸⡄⠀⠀│ | ||
│⡇⢸⡇⡇⡇⡇⢸⠀⡇⠈⡆⢰⠁⠀⡇⠀⢰⠁⠀⠈⡆⠀⠀⡎⠀⠀⠀⢱⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⠀⠀│ | ||
│⡇⢸⢸⡇⡇⡇⠸⣰⠃⠀⡇⡸⠀⠀⢸⠀⡜⠀⠀⠀⢣⠀⢸⠁⠀⠀⠀⠈⡆⠀⠀⠀⠀⠀⠀⠀⠀⠈⢇⠀│ | ||
│⡇⡇⢸⠇⢸⡇⠀⣿⠀⠀⢣⡇⠀⠀⠸⣄⠇⠀⠀⠀⠸⡀⡇⠀⠀⠀⠀⠀⢱⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⡄│ | ||
0 │⣇⣇⣸⣀⣸⣀⣀⣟⣀⣀⣸⣃⣀⣀⣀⣿⣀⣀⣀⣀⣀⣿⣀⣀⣀⣀⣀⣀⣈⣇⣀⣀⣀⣀⣀⣀⣀⣀⣀⣱│ | ||
└────────────────────────────────────────┘ | ||
⠀0⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀200⠀ | ||
``` | ||
""" | ||
function melscale_filterbanks(; | ||
n_freqs::Int, n_mels::Int, sample_rate::Int, | ||
fmin::Float32 = 0f0, fmax::Float32 = Float32(sample_rate ÷ 2), | ||
) | ||
mel_min, mel_max = _hz_to_mel(fmin), _hz_to_mel(fmax) | ||
mel_points = range(mel_min, mel_max; length=n_mels + 2) | ||
|
||
all_freqs = collect(range(0f0, Float32(sample_rate ÷ 2); length=n_freqs)) | ||
freq_points = _mel_to_hz.(mel_points) | ||
filter_banks = _triangular_filterbanks(freq_points, all_freqs) | ||
|
||
if any(maximum(filter_banks; dims=1) .≈ 0f0) | ||
@warn """At least one mel filterbank has all zero values. | ||
The value for `n_mels=$n_mels` may be set too high. | ||
Or the value for `n_freqs=$n_freqs` may be set too low. | ||
""" | ||
end | ||
return filter_banks | ||
end | ||
|
||
_hz_to_mel(freq::T) where T = T(2595) * log10(T(1) + (freq / T(700))) | ||
|
||
_mel_to_hz(mel::T) where T = T(700) * (T(10)^(mel / T(2595)) - T(1)) | ||
|
||
""" | ||
_triangular_filterbanks( | ||
freq_points::Vector{Float32}, all_freqs::Vector{Float32}) | ||
|
||
Create triangular filter banks. | ||
|
||
# Arguments: | ||
|
||
- `freq_points::Vector{Float32}`: Filter midpoints of size `n_filters`. | ||
- `all_freqs::Vector{Float32}`: Frequency points of size `n_freqs`. | ||
|
||
# Returns: | ||
|
||
Array of size `(n_freqs, n_filters)`. | ||
""" | ||
function _triangular_filterbanks( | ||
freq_points::Vector{Float32}, all_freqs::Vector{Float32}, | ||
) | ||
diff = @view(freq_points[2:end]) .- @view(freq_points[1:end - 1]) | ||
slopes = transpose(reshape(freq_points, :, 1) .- reshape(all_freqs, 1, :)) | ||
|
||
down_slopes = -(@view(slopes[:, 1:end - 2]) ./ reshape(@view(diff[1:end - 1]), 1, :)) | ||
up_slopes = @view(slopes[:, 3:end]) ./ reshape(@view(diff[2:end]), 1, :) | ||
return max.(0f0, min.(down_slopes, up_slopes)) | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
""" | ||
spectrogram(waveform; | ||
pad::Int = 0, n_fft::Int, hop_length::Int, window, | ||
center::Bool = true, power::Real = 2.0, | ||
normalized::Bool = false, window_normalized::Bool = false, | ||
) | ||
|
||
pxl-th marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Create a spectrogram or a batch of spectrograms from a raw audio signal. | ||
|
||
# Arguments | ||
|
||
- `pad::Int`: | ||
Then amount of padding to apply on both sides. | ||
- `window_normalized::Bool`: | ||
Whether to normalize the waveform by the window’s L2 energy. | ||
- `power::Real`: | ||
Exponent for the magnitude spectrogram (must be ≥ 0) | ||
e.g., `1` for magnitude, `2` for power, etc. | ||
If `0`, complex spectrum is returned instead. | ||
|
||
See [`stft`](@ref) for other arguments. | ||
|
||
# Returns | ||
|
||
Spectrogram in the shape `(T, F, B)`, where | ||
`T` is the number of window hops and `F = n_fft ÷ 2 + 1`. | ||
""" | ||
function spectrogram(waveform; | ||
pad::Int = 0, n_fft::Int, hop_length::Int, window, | ||
center::Bool = true, power::Real = 2.0, | ||
normalized::Bool = false, window_normalized::Bool = false, | ||
) | ||
pad > 0 && (waveform = pad_zeros(waveform, pad; dims=1);) | ||
|
||
# Pack batch dimensions. | ||
sz = size(waveform) | ||
spec_ = stft(reshape(waveform, (sz[1], :)); | ||
n_fft, hop_length, window, center, normalized) | ||
# Unpack batch dimensions. | ||
spec = reshape(spec_, (size(spec_)[1:2]..., sz[2:end]...)) | ||
window_normalized && (spec = spec .* inv(norm(window));) | ||
|
||
if power > 0 | ||
p = real(eltype(spec)(power)) | ||
spec = abs.(spec).^p | ||
end | ||
return spec | ||
end | ||
|
||
""" | ||
power_to_db(s; ref::Real = 1f0, amin::Real = 1f-10, top_db::Real = 80f0) | ||
|
||
Convert a power spectrogram (amplitude squared) to decibel (dB) units. | ||
|
||
# Arguments | ||
|
||
- `s`: Input power. | ||
- `ref`: Scalar w.r.t. which the input is scaled. | ||
- `amin`: Minimum threshold for `s`. | ||
- `top_db`: Threshold the output at `top_db` below the peak: | ||
`max.(s_db, maximum(s_db) - top_db)`. | ||
|
||
# Returns | ||
|
||
`s_db ~= 10 * log10(s) - 10 * log10(ref)` | ||
""" | ||
function power_to_db(s; ref::Real = 1f0, amin::Real = 1f-10, top_db::Real = 80f0) | ||
log_spec = 10f0 .* (log10.(max.(amin, s)) .- log10.(max.(amin, ref))) | ||
return max.(log_spec, maximum(log_spec) - top_db) | ||
end | ||
|
||
""" | ||
db_to_power(s_db; ref::Real = 1f0) | ||
|
||
Inverse of [`power_to_db`](@ref). | ||
""" | ||
function db_to_power(s_db; ref::Real = 1f0) | ||
return ref .* 10f0.^(s_db .* 0.1f0) | ||
end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we make this a weak dependence and move any function relying on FFTW under an extension?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done