E3 ended with a problem. A frame of 2048 samples of a 440 Hz cosine makes 20.43 turns, the end of the frame does not join up with its beginning, and the spectrum, which should have a single bar, has its energy spread over the neighbouring bins. This exercise is about two things: using a window to flatten that seam, and cutting a whole sound into frames to see how the spectrum changes over time, which is the short-time Fourier transform (STFT).
The exercise has four parts: extracting the main lobe of a window’s spectrum, measuring the error of STFT analysis followed by synthesis, computing the energy envelopes of two frequency bands, and finding the onsets of a sound from those envelopes. Before the tasks, windows and the STFT need explaining.
What a window is
A window is a sequence of numbers as long as the frame, 0 at both ends and 1 in the middle, shaped like a hill. Multiplying the frame by the window means multiplying every sample of the frame by the corresponding number of the window, so both ends are pushed down to 0 and the middle is left almost unchanged. Once the ends are 0, the end and the beginning of the frame are both 0, and there is no jump where they join.
On the left is the frame from E3: grey is the original frame, dashed orange is the window, blue is the product. On the right is the spectrum of the product, showing only the 15 bins around 440 Hz, with the vertical axis in dB and the highest bin at 0. E3 explained that dB is 20 times the common logarithm of the magnitude: magnitude 1 is 0 dB, 0.1 is −20 dB and 0.001 is −60 dB. The spectrum is drawn in dB so that very small values are visible too; on a linear scale 0.001 and 0 look the same.
Without a window, the highest value 5 or more bins away from the peak is −20 dB, and it falls off slowly further out. With a Blackman-Harris window, the highest value 5 or more bins away is −91 dB, so the leakage is essentially gone. The cost is a wider peak: without a window the second bin on either side of the peak is already down to −11 dB, while with the Blackman-Harris window it takes until the fourth bin to get down to −24 dB.
This is no coincidence. The spectrum of a sinusoid multiplied by a window is the window’s own spectrum shifted to the sinusoid’s frequency. So whatever the window’s spectrum looks like, every peak looks like that after windowing, and the window’s spectrum tells how wide the peaks will be and how much leakage there will be.
Zero-padding
For a frame of M = 2048 samples, the DFT is evaluated at 2048 bins only, 21.5 Hz apart, so the shape of the peak is seen at just a few points. To see it in more detail, append zeros to the frame up to N samples and take the DFT of that. The DFT then has N bins, fs / N Hz apart; the shape of the spectrum does not change, it is just sampled at more points along the same shape, and N = 8M means 8 points between every two of the original bins. In the words of E3’s ruler, it is the same ruler with finer ticks.
The tasks in this exercise all keep M and N separate: M is the frame length, which is also the window length, and N is the DFT length, with N at least M.
The main lobe of a window
Treat the window itself as a frame, zero-pad it to N = 8M, take the DFT and look at its spectrum.
On the left is the shape of the window, on the right its spectrum, with the vertical axis in dB relative to the highest point and the horizontal axis in bins of the M-point DFT, 8 points per bin. The part from the highest point out to the first minimum on each side is called the main lobe, the blue region, and the two orange dots are the minima on either side. The row of lower bumps further out are the side lobes, and the dashed orange line marks the highest of them.
For the Blackman-Harris window with M = 100 and N = 800, there are 65 samples from the left minimum to the right minimum. 65 samples span 64 intervals, each 1/8 of a bin, so the main lobe is 8 bins wide.
Drag M and the number of samples in the main lobe does not change. Measured in bins, the main-lobe width depends only on the shape of the window, not on M. It depends on M only when converted to Hz, because one bin is fs / M Hz: for a Blackman-Harris window with M = 2048 at fs = 44100 the main lobe is 8 × 44100 / 2048 = 172 Hz wide. The wider peak in the previous animation is these 172 Hz.
The main-lobe width and the highest side lobe of the five windows:
| Window | Main lobe | Highest side lobe |
|---|---|---|
| Rectangular, i.e. no window | 2 bins | −13 dB |
| Hann | 4 bins | −31.5 dB |
| Hamming | 4 bins | −42.6 dB |
| Blackman | 6 bins | −58 dB |
| Blackman-Harris | 8 bins | −92 dB |
The narrower the main lobe, the higher the side lobes. For two close frequencies to show up as two peaks, the main lobe has to be narrower than their spacing. If two frequencies are Δ Hz apart and the window’s main lobe is B bins wide, separating them takes M of at least B × fs / Δ. 440 Hz and 490 Hz are 50 Hz apart, so with a Hamming window M has to be at least 4 × 44100 / 50 = 3528 samples. For a weak frequency next to a strong one not to be covered by the strong one’s side lobes, a window with low side lobes is needed. The two cannot be had at once.
Implementation
Generate the window with get_window. The second argument of fft is N, and the missing samples are filled with zeros automatically. Take the magnitude, convert to dB, move 0 Hz to the middle with fftshift, and walk from the highest point outwards until the first minimum on each side:
import numpy as np
from scipy.signal import get_window
from scipy.fftpack import fft, fftshift
eps = np.finfo(float).eps
def extract_main_lobe(window, M, N):
w = get_window(window, M)
mW = fftshift(20 * np.log10(np.abs(fft(w, N)) + eps))
p = np.argmax(mW)
left = p
while mW[left - 1] < mW[left]:
left -= 1
right = p
while mW[right + 1] < mW[right]:
right += 1
return mW[left:right + 1]
The eps avoids taking the logarithm of 0. The exercise asks to put the second half of the window at the start of the buffer and the first half at the end before the FFT, which is called zero-phase windowing. That only changes the phase; the magnitude is the same as with plain zero-padding, so it is left out here.
The exercise gives three test cases, all with N = 8M. The Blackman-Harris window with M = 100 returns 65 samples, the rectangular window with M = 120 returns 17, and the Hamming window with M = 256 returns 33. Subtract 1 and divide by 8 to get 8, 2 and 4 bins, as in the table.
One frame at a time
So far everything has been about one frame. Sounds change: every time a piano key is struck the spectrum changes, and one frame cannot show that. The STFT cuts the whole sound into many frames, multiplies each by a window and takes its DFT. The centres of neighbouring frames are H samples apart; H is called the hop size, and since H is smaller than M, the frames overlap.
Top left is a short stretch of the waveform of piano.wav; the blue region is the current frame, the solid orange line is its window, and the dashed lines are the neighbouring frames, each 128 samples apart. Top right is the spectrum of this windowed frame. Below, the magnitude spectrum of each frame is stood up as one column, with darker meaning larger magnitude, and as the frames advance the columns line up into a picture called the spectrogram, with time along the horizontal axis and frequency along the vertical axis.
The window here is a Blackman window with M = 513 samples, 11.6 ms, and H = 128 samples, 2.9 ms, with N = 1024. piano.wav is 3.85 s long, which makes 1325 frames. The frame length decides how much sound one frame sees, and the hop size decides how often a spectrum is computed; together with the window type and N, these are all the parameters of an STFT. This is what sms-tools’ stftAnal(x, w, N, H) does: it returns the magnitude spectrum and the phase spectrum of every frame, each as a 2-D array with one row per frame.
The error of analysis followed by synthesis
The STFT cuts the sound into frames and takes the DFT of each one. The second part of the exercise goes the other way: synthesise the sound back from the spectra of those frames and see how far the result is from the original.
The DFT step loses nothing. Take the DFT of a frame and run it backwards, and you get the frame that went in, not a single number different; running it backwards is called the inverse DFT. So the synthesis error has nothing to do with the DFT and everything to do with the window applied when cutting the frames.
Applying the window multiplies every sample of the frame by a number, close to 1 in the middle and close to 0 at both ends. A frame run backwards and put back where it came from still looks windowed, squashed at both ends. The frames overlap, though: there is a frame every H samples, and with a Blackman window, M = 513 and H = 128, any sample of the signal is covered by 4 frames. Synthesis puts every frame back in its place and adds them all up.
Think of painting a wall. One stroke of the brush is M samples wide and leaves paint that is thick in the middle and thin at both ends, which is the shape of the window. After each stroke the brush moves H samples to the right and paints again. Every point of the wall gets painted 4 times, and the 4 thicknesses add up to its final thickness. For the whole wall to be equally thick, the shape of the brush and the distance it moves have to match. The signal is the same: a sample covered by 4 frames was multiplied by 4 different numbers, one in each frame, and after adding the frames that sample is the original times the sum of those 4 numbers. If the 4 numbers add up to exactly 1, that sample is the same as the original. If the sum is 1 everywhere, the synthesis equals the original.
The upper figure is the wall. Each thin line is one frame’s window, the orange line is the sum of all windows, which is the thickness of the paint, and the dashed green line is 1. The bottom slider picks a sample: the frames covering it are drawn thicker, each one gets a dot at the number it multiplies that sample by, and below the figure those numbers are added up. In the lower figure, grey is a test signal and blue is the synthesised signal minus the original, that is, the error.
With a Blackman window, M = 513 and H = 128, sample 3000 is covered by 4 frames, the 4 numbers are 0.052, 0.487, 0.431 and 0.030, and they add up to 1.000. Drag the slider to the right: the 4 numbers keep changing, the sum stays 1, the orange line is flat, and the error is too small to see.
Drag the slider all the way to the left. Sample 0 is covered by only 3 frames; there should be more frames to its left, but there is nothing before the start of the signal, so those frames do not exist. The 3 numbers add up to only 0.799, the synthesised sample is 0.8 times the original, and the error is 20%. The same happens at the end. So the error is large in the first and last M samples and small in the middle, which is why the exercise asks for two SNR values, one over the whole signal and one without the first and last M samples.
SNR puts the size of the error into one number. Square every sample of the original and add them up, and that is the signal energy; do the same with the error, and that is the noise energy. Signal energy divided by noise energy, take the common logarithm and multiply by 10, and that is the SNR, in dB. When the error is one tenth of the signal the SNR is 20 dB, one hundredth gives 40 dB, one thousandth gives 60 dB; the smaller the error, the larger the SNR. E3 multiplied by 20 when converting magnitudes to dB, and here it is 10, because energy is magnitude squared, so the two say the same thing. For the test signal in the animation the whole-signal SNR is 18.8 dB, dragged down by that 20% error at the edges; without the edges it is 86.5 dB.
With H changed to 256, every sample is covered by only 2 frames, the orange line wobbles between 0.81 and 1.19, the error is there throughout, and even without the edges the SNR is only 17.7 dB. With a Hamming window, M = 512 and H = 64, the orange line is exactly 1 everywhere and the only error left in the middle is floating-point residue. The orange line for Blackman with M = 513 actually ripples by 0.012% in the middle too, because 513 is not a multiple of 128; with M = 512 it is flat.
Implementation
One detail. dftAnal divides the window by the sum of all its values, Σw, and stftSynth multiplies every frame by H, so the windows drawn in the animation are H × w / Σw, not the original window. These two factors only bring the average height of the orange line to 1; whether the line is flat does not depend on them.
Read the file, analyse, synthesise, trim to the length of the input, subtract to get the noise, and compute the two SNRs:
from smstools.models import stft
from smstools.models import utilFunctions as UF
def compute_snr(input_file, window, M, N, H):
fs, x = UF.wavread(input_file)
w = get_window(window, M)
mX, pX = stft.stftAnal(x, w, N, H)
y = stft.stftSynth(mX, pX, M, H)[:x.size]
noise = x - y
energy = lambda s: np.sum(s ** 2)
snr1 = 10 * np.log10(energy(x) / energy(noise))
snr2 = 10 * np.log10(energy(x[M:-M]) / energy(noise[M:-M]))
return snr1, snr2
The three test cases give: piano.wav with a Blackman window, M = 513, N = 2048, H = 128, SNR of 67.5 and 86.4 dB; sax-phrase-short.wav with a Hamming window, M = 512, N = 1024, H = 64, 89.5 and 307.0 dB; rain.wav with a Hann window, M = 1024, N = 2048, H = 128, 74.6 and 306.7 dB. The exercise gives 306.2 and 304.3 for the last two; the difference is floating-point arithmetic, and an SNR around 300 dB means the error is already of the order of 1e−15.
The differences in SNR2 between the three cases come from the combination of window and H: a Blackman window with M = 513 shifted by 128 samples still has a slight ripple when summed, while Hamming and Hann shifted by M/8 sum to a flat line. The differences in SNR1 depend on what fraction of the signal the first and last 2M samples are, and on how loud the sound is at its start and end.
Energy envelopes of two bands
The energy of a signal is the sum of its squared samples. In the spectrum, the energy of a band is the sum of the squared magnitudes of the bins in that band. The exercise asks for two bands, a low band from 0 to 3000 Hz and a high band from 3000 to 10000 Hz, excluding the boundaries themselves.
The frequency of a bin is k × fs / N. With N = 1024 the bin spacing is 43.07 Hz, the low band is bins 1 to 69 and the high band is bins 70 to 232. Bin 0 is 0 Hz; E2 explained that it is the average of the frame, which is not sound, so it is left out.
stftAnal returns magnitudes in dB, so first convert back to linear, |X| = 10^(mX / 20), then add up |X|² over the bins of the band, and finally convert to dB, 10 × log10(E). Each frame gives two numbers, and arranged in time they form two energy envelopes.
The upper figure is the spectrogram of the whole of piano.wav; the dashed orange line is 3000 Hz, with the high band above it and the low band below. The lower figure shows the energy envelopes of the two bands. The button plays the piano and a black line follows along.
The recording has five notes. The moment each note starts, the energy in the high band jumps up and then falls off quickly; the low band rises slowly and falls slowly too. The hammer hitting the string is noise, with its energy concentrated in the high band, while the vibration of the string stays in the low band.
With M changed to 2047, both envelopes become smooth and the spike at each note’s attack is gone. A frame of 2047 samples is 46 ms, so one frame holds signal from both before and after the hammer strike and the energy is averaged out. The longer the frame, the finer the frequency resolution and the blurrier the timing.
Implementation
def compute_eng_env(input_file, window, M, N, H):
fs, x = UF.wavread(input_file)
w = get_window(window, M)
mX, pX = stft.stftAnal(x, w, N, H)
X = 10 ** (mX / 20)
f = np.arange(mX.shape[1]) * fs / N
low = np.where((f > 0) & (f < 3000))[0]
high = np.where((f > 3000) & (f < 10000))[0]
env = np.zeros((mX.shape[0], 2))
env[:, 0] = 10 * np.log10(np.sum(X[:, low] ** 2, axis=1))
env[:, 1] = 10 * np.log10(np.sum(X[:, high] ** 2, axis=1))
return env
np.where returns the indices where the condition holds, which here are the bin numbers inside the band. mX[:, low] picks those bins out of every frame, and axis=1 sums along each row, one row being one frame. With 1325 frames, the returned array has 1325 rows and 2 columns.
Onset detection function
An onset is the moment a note starts. The energy envelope rises sharply at an onset, so take the difference between neighbouring frames, O(l) = E(l) − E(l − 1) with O(0) = 0; the faster the rise, the larger the value. When a note ends the energy falls and the difference is negative. Only beginnings matter here, not endings, so negative values are set to 0, which is called half-wave rectification.
The three rows are the energy envelope, the difference between neighbouring frames, and the result after setting negative values to 0; the dashed orange line is 10 dB. In the high band with M = 513 there are 6 peaks above 10 dB. The last two, at 2.04 and 2.08 s, belong to the same note; the other four each correspond to one note. The difference in the low band never exceeds 10 dB, so piano attacks are not distinct there.
With M changed to 2047, no peak in the high band exceeds 10 dB either; the highest is 9 dB. The longer the frame, the flatter the envelope and the smaller the difference. A fixed 10 dB threshold does not work across the three test cases; it has to be set per frame length and per sound, or relative to the size of the envelope.
Implementation
Take the difference of the energy envelope and set negative values to 0:
def compute_odf(input_file, window, M, N, H):
env = compute_eng_env(input_file, window, M, N, H)
odf = np.zeros_like(env)
odf[1:] = env[1:] - env[:-1]
odf[odf < 0] = 0
return odf
Summary
- Multiplying a frame by a window pushes both ends to 0 and removes the seam. The cost is that every peak takes the shape of the window’s spectrum; the main-lobe width in bins depends only on the window’s shape, and the narrower the main lobe, the higher the side lobes;
- Zero-padding to N samples before the DFT makes the bins denser without changing the shape of the spectrum;
- The STFT takes a frame every H samples, windows it and takes its DFT; the magnitude spectra of the frames stood up as columns form the spectrogram;
- For synthesis the windows of all frames have to add up to 1 everywhere. At the start and end the sum falls short of 1, so the first and last M samples have a large error;
- The energy of a band is the sum of the squared magnitudes of its bins. The longer the frame, the flatter the envelope;
- The difference in energy between neighbouring frames, with negative values set to 0, is the simplest onset detection function.
Exercise source: E4-STFT.ipynb
The piano.wav played in this post comes from the sounds directory of sms-tools-materials, by Xavier Serra, CC BY 4.0.