13. Onsets and tempo
Onset detection marks the instants at which each note or drum hit begins, that is, where new sound energy appears; tempo estimation looks for the period with which those instants repeat. Both are built on an onset detection function (ODF), one number per analysis frame, and both depend on its properties. This notebook states units explicitly (samples, frames, seconds, beats per minute) and identifies where the library’s defaults give poor results.
Learning outcomes. After working through this notebook you can
compute the half-wave-rectified spectral flux and reproduce the library’s ODF exactly;
configure peak picking in frames, and explain what the default configuration’s threshold floor does to weak onsets;
convert between lags, frames, seconds and BPM, and re-derive
estimate_tempofrom the ODF;recognise tempo octave errors (and other metrical-level errors) and say why they happen.
The click tracks here use 44.1 kHz audio and the same pseudo-random bursts as the Rust guide chapter, so every number below can be compared with it.
import matplotlib.pyplot as plt
import numpy as np
import audio_samples as aus
rng = np.random.default_rng(seed=2026)
FS = 44_100 # sample rate in Hz
HOP = 512 # ODF hop in samples (the default)
MASK64 = (1 << 64) - 1
def click_track(times, seconds, amps=None):
# Decaying noise bursts (256 samples, 0.54 ms time constant) starting at `times` (s), with
# peak amplitudes `amps` (0.9 each by default). The noise is the xorshift64 generator of the
# Rust chapter, so the signals are identical.
x = np.zeros(int(seconds * FS))
seed = 0x2545_F491_4F6C_DD1D
decay = np.exp(-np.arange(256) / 24)
for t, amp in zip(times, [0.9] * len(times) if amps is None else amps):
start = int(t * FS)
for i in range(256):
seed ^= (seed << 13) & MASK64
seed ^= seed >> 7
seed ^= (seed << 17) & MASK64
x[start + i] = amp * decay[i] * ((seed >> 11) / float(1 << 53) * 2 - 1)
return aus.AudioSamples.new_mono(x, sample_rate=FS)
Concept
Frames. The signal is analysed in frames hopped by \(H\) samples; frame \(t\) is centred at \(tH/f_s\) seconds (\(f_s\) the sample rate in Hz). At \(H = 512\) and \(f_s = 44.1\) kHz a frame lasts \(H/f_s = 11.61\) ms and there are \(f_s/H = 86.13\) frames per second.
Spectral flux. With \(|X_b[t]|\) the magnitude of frequency bin \(b\) in frame \(t\), the half-wave-rectified flux is
Only increases count, so note offsets do not create onsets. This library evaluates it on a
constant-Q transform (CQT) whose \(b_o O\) bins (\(b_o\) per octave, \(O\) octaves) start at \(f_{min}\) Hz,
with an analysis window of \(N_w = \lfloor 4f_s/f_{min} \rfloor\) samples (four periods of the lowest
bin). The quality factor is \(Q = 1/(2^{1/b_o} - 1)\) (34.1 at \(b_o = 24\)): bin \(b\)’s kernel spans \(Q\)
periods of its centre frequency, \(Qf_s/f_b\) samples, cut to \(N_w\) and centred in the frame. The magnitudes are not squared, despite the method’s name (“energy”). Optionally, values
below \(\mu\) times a running median of \(L_{med}\) frames are set to zero (adaptive_threshold,
\(\mu\) = adaptive_threshold_multiplier).
Peak picking, all in frames: optional pre-emphasis (\(o[i] - \alpha\,o[i-1]\)) and median filtering (both off by default); normalisation by the maximum; a threshold \(\theta[i] = \operatorname{clamp}(\max_{|j-i| \le w/2} o[j] - \delta,\ \theta_{lo},\ \theta_{hi})\) (by default window \(w = 9\) frames, \(\delta = 0.07\), floor \(\theta_{lo} = 0.1\), \(\theta_{hi} = 1\)); strict local maxima above it; finally peaks are accepted strongest first and dropped if closer than \(s\) frames (3 by default) to an accepted one. A peak at frame \(i\) is reported at \(t_i = iH/f_s\) seconds.
Tempo. A tempo of \(B\) beats per minute is an inter-beat interval of \(60/B\) seconds, i.e. a lag of
estimate_tempo smooths the ODF (7-frame moving average), compresses it (\(\ln(1 + 0.5x)\)),
removes the mean and computes \(a(L) = \frac{1}{n-L}\sum_i c[i]\,c[i-L]\) for the integer lags that
map into 40-240 BPM (\(n\) the envelope length, \(c\) the centred envelope). Each lag is weighted by a
log-normal prior centred on 120 BPM, \(w(B) = \exp\left(-\tfrac{1}{2}\log_2^2(B/120)\right)\), and
the lag with the largest \(a(L)\,w(B)\) is chosen. Two consequences: estimates lie on the grid \(60f_s/(HL)\), and a
periodic envelope correlates at \(2L\) and \(3L\) too, so metrical-level errors (half the tempo,
an octave error, or a third of it) remain possible: the prior only biases the choice.
# Numbers quoted above.
assert round(1000 * HOP / FS, 2) == 11.61 and round(FS / HOP, 2) == 86.13
With the library
A click track: four decaying noise bursts, one every 0.5 s. The default OnsetDetectionConfig
finds all four. To vary its peak picking below, we rebuild the default PeakPickingConfig with a
helper.
From Python the nested configuration must be rebuilt and assigned: config.peak_picking
returns a copy, so config.peak_picking.set_median_filter(False, 3) changes nothing.
audio = click_track([0.25, 0.75, 1.25, 1.75], 2.0)
def peak_picking(window=9, separation=3, median=False, pre_emphasis=False, floor=0.1):
# The library's default peak picking, with the settings this notebook varies exposed.
threshold = aus.AdaptiveThresholdConfig(
aus.AdaptiveThresholdMethod.delta, delta=0.07, percentile=0.9,
window_size=window, # frames
min_threshold=floor, max_threshold=1.0, # floor: a fraction of the strongest peak
)
return aus.PeakPickingConfig(
adaptive_threshold_config=threshold,
min_peak_separation=separation, # frames
pre_emphasis=pre_emphasis, pre_emphasis_coeff=0.97,
median_filter=median, median_filter_length=3,
normalize_onset_strength=True, normalization_method=aus.NormalizationMethod.peak,
)
def onset_config(pp=None, adaptive=True):
config = aus.OnsetDetectionConfig.default()
config.peak_picking = peak_picking() if pp is None else pp
config.adaptive_threshold = adaptive
return config
# With no arguments, peak_picking() is exactly the default.
assert repr(peak_picking()) == repr(aus.PeakPickingConfig.default())
assert repr(aus.OnsetDetectionConfig.default().peak_picking) == repr(peak_picking())
# 9 frames is 104.5 ms and 3 frames 34.8 ms at hop 512 and 44.1 kHz.
assert round(1000 * 9 * HOP / FS, 1) == 104.5 and round(1000 * 3 * HOP / FS, 1) == 34.8
# Mutating the nested object has no effect.
trap = aus.OnsetDetectionConfig.default()
trap.peak_picking.set_median_filter(True, 3)
assert "median_filter: false" in repr(trap.peak_picking)
config = aus.OnsetDetectionConfig.default()
onsets = np.array(audio.detect_onsets(config))
print("onsets (s):", np.round(onsets, 4))
assert len(onsets) == 4
# Peaks fall on frames 21, 64, 107, 151.
frames = np.round(onsets * FS / HOP)
assert list(frames) == [21, 64, 107, 151]
# The first three are the last frame whose centre precedes the burst, 6.2 to 7.7 ms before
# it; the fourth is the frame after, 3.1 ms late. All are within one hop (11.6 ms).
lead = 0.25 + 0.5 * np.arange(4) - onsets
assert np.all(np.abs(lead) < 0.0078) and np.all(lead[:3] > 0.006) and -0.0032 < lead[3] < -0.003
onsets (s): [0.2438 0.743 1.2423 1.7531]
Onset times are quantised to whole frames: 0.5 s is 43.07 frames, so each burst falls 0.77 ms later relative to the frame grid than the one before. The long low-bin kernels (the 72.7 ms window) already respond to a burst that starts after their centre, so the largest increase tends to come in the frame before the burst, 6.2, 7.0 and 7.7 ms early for the first three. By the fourth burst that frame is 8.5 ms early and the frame after only 3.1 ms late, and the frame after has the larger increase.
assert round(0.5 * FS / HOP, 2) == 43.07
assert np.allclose(np.diff(lead[:3]), 0.5 - 43 * HOP / FS) and round(1000 * (0.5 - 43 * HOP / FS), 2) == 0.77
The defaults, in frames. The default PeakPickingConfig applies neither pre-emphasis nor a
median filter, normalises by the maximum and thresholds with a 9-frame window (104.5 ms),
\(\delta = 0.07\) and a floor of 0.1; peaks closer than 3 frames (34.8 ms) are merged. Pre-emphasis
is available but off: the ODF is already a difference of spectra, and pre-emphasising it moves
each peak to the frame where it rises fastest, which comes before the onset.
The floor has a side effect: after normalisation, no peak weaker than a tenth of the strongest one in the clip is reported. On eight bursts whose first three are 26 dB quieter than the rest (amplitude 0.045 instead of 0.9) the defaults find only 5: the quiet bursts peak at 0.036, 0.033 and 0.024 of the largest value. Lowering the floor to 0.01 finds all 8.
Lengths chosen as if they counted audio samples (threshold window 1024, separation 512, median length 3) behave very differently when they count frames. Switching each on, one at a time, in the 0.01-floor configuration: the length-3 median deletes every one-frame peak (0 onsets); a 1024-frame threshold window, clipped to the signal length, makes the threshold the global maximum minus \(\delta\) (1 onset); a 512-frame separation, reduced by the library to a quarter of the signal (91 frames, 1.06 s), keeps only 3. Switching pre-emphasis on (0.97) still finds all 8 on this signal.
# The first three bursts are 26 dB quieter than the other five.
amps8 = [0.045] * 3 + [0.9] * 5
assert round(20 * np.log10(0.045 / 0.9), 2) == -26.02
eight = click_track([0.25 + 0.5 * k for k in range(8)], 4.25, amps8)
truth8 = 0.25 + 0.5 * np.arange(8)
default8 = np.array(eight.detect_onsets(aus.OnsetDetectionConfig.default()))
# The defaults find the five loud bursts only, each within one hop.
assert len(default8) == 5 and np.all(np.abs(truth8[3:] - default8) < HOP / FS)
# What the threshold sees: the peak-normalised ODF at each burst.
_, odf8 = map(np.asarray, eight.onset_detection_function(aus.OnsetDetectionConfig.default()))
pre8 = odf8 / np.max(np.abs(odf8))
seen = [pre8[int(round(t * FS / HOP)) - 6 : int(round(t * FS / HOP)) + 1].max() for t in truth8]
print("normalised peaks:", np.round(seen, 3))
assert list(np.round(seen, 3)) == [0.036, 0.033, 0.024, 0.333, 0.757, 0.794, 1.0, 0.884]
low = lambda **kw: onset_config(peak_picking(floor=0.01, **kw))
counts = {
"default": len(default8),
"floor 0.01": len(eight.detect_onsets(low())),
"+ median 3": len(eight.detect_onsets(low(median=True))),
"+ window 1024": len(eight.detect_onsets(low(window=1024))),
"+ separation 512": len(eight.detect_onsets(low(separation=512))),
"+ pre-emphasis": len(eight.detect_onsets(low(pre_emphasis=True))),
}
print(counts)
assert list(counts.values()) == [5, 8, 0, 1, 3, 8]
# The 512-frame separation is reduced by the library to a quarter of the 367 frames.
assert len(odf8) == 367 and 367 // 4 == 91 and round(91 * HOP / FS, 2) == 1.06
normalised peaks: [0.036 0.033 0.024 0.333 0.757 0.794 1. 0.884]
{'default': 5, 'floor 0.01': 8, '+ median 3': 0, '+ window 1024': 1, '+ separation 512': 3, '+ pre-emphasis': 8}
The threshold floor, the minimum spacing and the pre-emphasis all live in peak_picking;
OnsetDetectionConfig itself holds the CQT, the hop and the median-based zeroing of the ODF.
How it works
The ODF. Compute the CQT magnitude with the same parameters
(aus.spectrograms.compute_cqt_magnitude_spectrogram, window \(N_w = \lfloor 4 \cdot 44100/55
\rfloor = 3207\) samples, symmetric Hann, centred frames) and sum the rectified frame-to-frame
increases; with the median-based zeroing switched off, the result must equal
onset_detection_function. It returns (times, values), in that order.
raw = onset_config(adaptive=False)
times, odf_lib = map(np.asarray, audio.onset_detection_function(raw))
assert np.allclose(times, np.arange(len(times)) * HOP / FS) # frame t at t H / f_s
cqt = raw.cqt_params # 24 bins/octave, 6 octaves from 55 Hz: 144 bins
n_w = int(4 * FS / 55.0)
assert n_w == 3207
sp = aus.SpectrogramParams(aus.StftParams(n_w, HOP, aus.WindowType.hanning, True), FS)
mag = np.asarray(aus.spectrograms.compute_cqt_magnitude_spectrogram(audio.to_numpy(), sp, cqt).data)
assert mag.shape[0] == 144
flux = np.zeros(mag.shape[1])
for t in range(1, mag.shape[1]):
flux[t] = sum(max(0.0, mag[b, t] - mag[b, t - 1]) for b in range(mag.shape[0]))
# Same additions in the same order: exact agreement.
assert np.array_equal(flux, odf_lib)
Peak picking, re-implemented for the default configuration, on the ODF
that detect_onsets uses (with the adaptive zeroing on), then frames to seconds.
def pick_peaks(odf, window=9, delta=0.07, separation=3, lo=0.1, hi=1.0):
o = odf / np.max(np.abs(odf)) # peak normalisation
half = window // 2
thr = np.array([np.clip(o[max(0, i - half) : i + half + 1].max() - delta, lo, hi) for i in range(len(o))])
cand = [i for i in range(1, len(o) - 1) if o[i] > o[i - 1] and o[i] > o[i + 1] and o[i] > thr[i]]
peaks = []
for i in sorted(cand, key=lambda i: -o[i]): # strongest first
if all(abs(i - p) >= separation for p in peaks):
peaks.append(i)
return sorted(peaks), o, thr
_, odf = map(np.asarray, audio.onset_detection_function(config))
peaks, o, thr = pick_peaks(odf)
assert np.array_equal(np.array(peaks) * HOP / FS, onsets)
fig, ax = plt.subplots(figsize=(8, 3))
t = np.arange(len(o)) * HOP / FS
ax.plot(t, o, label="ODF (normalised)")
ax.plot(t, thr, ls="--", label="threshold")
ax.plot(onsets, o[peaks], "o", label="detected onsets")
for k in range(4):
ax.axvline(0.25 + 0.5 * k, color="0.6", ls=":", lw=1)
ax.set(xlabel="Time (s)", ylabel="Onset strength", title="Spectral flux and peak picking (grey: true onsets)")
ax.legend(fontsize=8)
plt.show()
The ODF peaks of the five loud bursts, which have the same amplitude, are 1.94, 4.41, 4.62, 5.82 and 5.15: a factor of 3. Each burst is a different noise sample and falls at a different place relative to the frame grid, and the highest bins’ kernels are shorter than a hop, so they see only part of the time between frames (the onset module documents this). A local threshold window copes with such differences.
_, odf8 = map(np.asarray, eight.onset_detection_function(onset_config()))
def heights(odf, times):
return np.array([odf[int(round(tm * FS / HOP)) - 4 : int(round(tm * FS / HOP)) + 2].max() for tm in times])
h8 = heights(odf8, [0.25 + 0.5 * k for k in range(8)])
assert list(np.round(h8, 2)) == [0.21, 0.19, 0.14, 1.94, 4.41, 4.62, 5.82, 5.15]
assert round(h8[3:].max() / h8[3:].min()) == 3 # the five loud bursts
Tempo. estimate_tempo(BeatTrackingConfig) uses only the configuration’s onset settings (its
tempo_bpm is ignored). We rebuild the onset-strength envelope and the prior-weighted
autocorrelation from onset_detection_function and compare, for click tracks of 8.5 s at several
tempi (one click every \(60/B\) s, \(\lfloor 8B/60 \rfloor\) clicks from 0.1 s), and for an 80 BPM
track whose off-beats (every other click) have a fifth of the amplitude.
def tempo_from_odf(odf):
n = len(odf)
smooth = np.array([odf[max(0, i - 3) : min(n, i + 4)].mean() for i in range(n)]) # 7-frame average
env = np.log1p(0.5 * smooth)
c = env - env.mean()
frame_rate = FS / HOP
lo, hi = int(np.floor(60 * frame_rate / 240)), min(int(np.ceil(60 * frame_rate / 40)), n - 1)
ac = {lag: c[lag:] @ c[:-lag] / (n - lag) for lag in range(lo, hi + 1)}
prior = lambda lag: np.exp(-0.5 * np.log2(60 * frame_rate / lag / 120) ** 2)
best = max((lag for lag in ac if ac[lag] > 0), key=lambda lag: ac[lag] * prior(lag))
return 60 * frame_rate / best, best, ac, prior
def tempo_track(bpm, off=1.0):
# Clicks every 60/bpm s from 0.1 s; every other click (the off-beats) at `off` of 0.9.
ibi = 60 / bpm
n = int(8 / ibi)
return click_track([0.1 + ibi * k for k in range(n)], 8.5, [0.9 if k % 2 == 0 else 0.9 * off for k in range(n)])
beat_cfg = aus.BeatTrackingConfig(120.0, aus.OnsetDetectionConfig.default())
results = {}
for bpm, off in ((60, 1.0), (80, 1.0), (100, 1.0), (120, 1.0), (140, 1.0), (174, 1.0), (80, 0.2)):
ibi = 60 / bpm
track = tempo_track(bpm, off)
est = track.estimate_tempo(beat_cfg)
_, odf_t = map(np.asarray, track.onset_detection_function(aus.OnsetDetectionConfig.default()))
ours, lag, ac, prior = tempo_from_odf(odf_t)
assert abs(ours - est) < 1e-9 # same operations: rounding-level agreement
results[bpm, off] = (est, lag, ac, prior, odf_t, ibi)
label = " (quiet off-beats)" if off < 1 else ""
print(f"{bpm:4d} BPM clicks{label}: estimate {est:7.2f} BPM (lag {lag:3d} frames), ratio {est / bpm:.3f}")
est = {key: round(r[0], 2) for key, r in results.items()}
assert est == {
(60, 1.0): 60.09, (80, 1.0): 79.51, (100, 1.0): 99.38, (120, 1.0): 120.19,
(140, 1.0): 139.67, (174, 1.0): 172.27, (80, 0.2): 40.06,
}
60 BPM clicks: estimate 60.09 BPM (lag 86 frames), ratio 1.002
80 BPM clicks: estimate 79.51 BPM (lag 65 frames), ratio 0.994
100 BPM clicks: estimate 99.38 BPM (lag 52 frames), ratio 0.994
120 BPM clicks: estimate 120.19 BPM (lag 43 frames), ratio 1.002
140 BPM clicks: estimate 139.67 BPM (lag 37 frames), ratio 0.998
174 BPM clicks: estimate 172.27 BPM (lag 30 frames), ratio 0.990
80 BPM clicks (quiet off-beats): estimate 40.06 BPM (lag 129 frames), ratio 0.501
Correct (to the grid) at every tempo when the clicks are equal, and half the tempo at 80 BPM when the off-beats are quiet. There the ODF at the ten clicks is 3.83, 1.32, 3.61, 0.49, 5.77, 0.38, 5.9, 0.79, 2.82, 0.73: the envelope does repeat every two beats. Its autocorrelation at lag 129 (0.00607) is 3.35 times that at lag 65 (0.00181), a larger ratio than the prior weights (0.29 against 0.84) can offset. A listener might well hear the accented clicks as the beat; the estimator cannot tell which metrical level is meant.
_, _, ac80, prior, odf80, ibi = results[80, 0.2]
h80 = heights(odf80, [0.1 + ibi * k for k in range(10)])
assert list(np.round(h80, 2)) == [3.83, 1.32, 3.61, 0.49, 5.77, 0.38, 5.9, 0.79, 2.82, 0.73]
assert abs(ac80[129] - 0.00607) < 5e-6 and abs(ac80[65] - 0.00181) < 5e-6
assert round(ac80[129] / ac80[65], 2) == 3.35
assert round(prior(129), 2) == 0.29 and round(prior(65), 2) == 0.84
lags = np.array(sorted(ac80))
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(lags, [ac80[l] for l in lags], label="a(L)")
ax.plot(lags, [ac80[l] * prior(l) for l in lags], label="a(L) w(B)")
ax.axvline(64.6, color="0.5", ls=":", label="true beat (64.6 frames)")
ax.set(xlabel="Lag L (frames)", ylabel="Autocorrelation", title="80 BPM clicks, quiet off-beats: the envelope repeats every 2 beats")
ax.legend(fontsize=8)
plt.show()
An independent reference. librosa.feature.tempo computes its ODF from a mel spectrogram in dB.
On the six click tracks of equal clicks it gives the same estimates as estimate_tempo (its grid is
the same at this hop), including 79.51 BPM at 80 and 172.27 BPM at 174. On the track with quiet
off-beats it still gives 79.51 BPM: in dB the off-beats are only 14 dB below the on-beats rather
than a fifth of their amplitude, so its envelope repeats every beat. estimate_tempo works on the
linear CQT magnitude, where the off-beats count for much less.
import librosa
librosa_bpm = {}
for bpm, off in results:
y = tempo_track(bpm, off).to_numpy()
librosa_bpm[bpm, off] = round(float(librosa.feature.tempo(y=y, sr=FS, hop_length=HOP)[0]), 2)
print(librosa_bpm)
# The same estimates as estimate_tempo for the equal clicks.
assert all(librosa_bpm[key] == est[key] for key in librosa_bpm if key[1] == 1.0)
assert librosa_bpm[80, 0.2] == 79.51 # one beat: see above
{(60, 1.0): 60.09, (80, 1.0): 79.51, (100, 1.0): 99.38, (120, 1.0): 120.19, (140, 1.0): 139.67, (174, 1.0): 172.27, (80, 0.2): 79.51}
Ask the library to explain
OnsetDetectionConfig.explain(sample_rate) converts every frame count into milliseconds and flags the
frames-versus-samples confusion of min_peak_separation.
doc = config.explain(44_100.0)
assert doc.quantity("Window size") == 3207
assert abs(doc.quantity("Window duration") - 72.72) < 0.005
assert abs(doc.quantity("Time resolution") - 11.61) < 0.005
assert abs(doc.quantity("Minimum peak separation") - 34.83) < 0.005 # 3 frames
assert doc.quantity("CQT bins") == 144
# The separation is flagged as counting frames, not samples (34.83 ms here, not 0.07 ms).
assert doc.has_warning_containing("counts onset-function frames")
doc
Onset detection (CQT energy flux)
A 3207-sample (72.7211 ms) window is hopped every 512 samples (11.61 ms); 144 constant-Q bins (Q = 34.1271) from 55 Hz to 3419.79 Hz feed a rectified spectral-increase onset function whose peaks are reported as onset times.
Formulas
Analysis window when window_size is not set: four periods of the lowest CQT frequency:
$$ N_w = \left\lfloor \frac{4 f_s}{f_{min}} \right\rfloor $$
Constant-Q bin frequencies (B bins per octave over O octaves):
$$ f_b = f_{min} , 2^{\frac{b}{B}}, \quad b = 0, \dots, B O - 1 $$
Onset strength: half-wave rectified increase of CQT magnitude:
$$ o[t] = \sum_{b} \max\left(0, |X_b[t]| - |X_b[t-1]|\right), \quad o[0] = 0 $$
Adaptive threshold against a running median of length L:
$$ o[t] \leftarrow 0 \ \text{if} \ o[t] < \mu \cdot \mathrm{median}_{L}(o)[t] $$
Peak index (in frames) to seconds:
$$ t_{onset} = \frac{i H}{f_s} $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $H$ | hop size | 512 samples | | $f_{min}$ | lowest CQT frequency | 55 Hz | | $B$ | bins per octave | 24 | | $O$ | octaves | 6 | | $Q$ | CQT quality factor f_b / bandwidth | 34.1271 | | $\mu$ | adaptive multiplier | 1.5 | | $L$ | median length | 5 frames |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | CQT bins | $B O$ = 144 | $B O$ | | Highest CQT frequency | $f_{min} 2^{(BO-1)/B}$ = 3419.79 Hz | $f_{min} 2^{(BO-1)/B}$ | | Window size | $N_w$ = 3207 samples | $\lfloor 4 f_s / f_{min} \rfloor$ | | Window duration | $N_w / f_s$ = 72.7211 ms | $1000 N_w / f_s$ | | Time resolution | $H / f_s$ = 11.61 ms | $1000 H / f_s$ | | Minimum peak separation | $s H / f_s$ = 34.8299 ms | $1000 s H / f_s$ | | Ideal kernel length at f_min | $Q f_s / f_{min}$ = 27363.7 samples | $Q f_s / f_{min}$ | | Truncated low bins | $\mathrm{count}(Q f_s / f_b > N_w)$ = 75 bins | $\text{count of bins whose kernel exceeds } N_w$ |
Trade-offs
A smaller hop locates onsets more precisely in time at more computation.
A long analysis window (needed for low CQT frequencies) spreads fast onsets over the window length.
Warnings
Info: The lowest 75 bin(s) (below about 469.287 Hz) need kernels longer than the 3207-sample window (up to 27364 samples at f_min with Q = 34.1271); their kernels are cut to 3207 samples, so those bins are wider than constant-Q. Hint: Set a longer window_size, or a lower Q, if low-frequency resolution matters.
Caution: peak_picking.min_peak_separation = 3 counts onset-function frames, i.e. 34.8299 ms here (not 0.0680272 ms, as it would be if it counted audio samples). Hint: Choose min_peak_separation = (desired seconds) × f_s / hop_size.
See also
Detect:
audio_samples::AudioOnsetDetection::detect_onsetsDetect (Python):
audio_samples.AudioSamples.detect_onsetsOnset function:
audio_samples::AudioOnsetDetection::onset_detection_functionOnset function (Python):
audio_samples.AudioSamples.onset_detection_functionPython:
audio_samples.explain.explain(OnsetDetectionConfig)
Exercises
Exercise 1 (units). You want onsets at least 50 ms apart with \(H = 256\) at 44.1 kHz. What
min_peak_separation do you set, and what spacing in milliseconds does it actually give? Store the
number of frames in answer.
answer = None # TODO
# Solution
answer = int(np.ceil(0.05 * 44_100 / 256)) # 8.6 -> 9 frames
assert answer == 9
c = aus.OnsetDetectionConfig.percussive(44_100)
assert c.hop_size == 256
c.peak_picking = peak_picking(separation=answer)
ms = c.explain(44_100.0).quantity("Minimum peak separation")
assert abs(ms - 52.24) < 0.005
print(f"{answer} frames = {ms:.2f} ms")
9 frames = 52.24 ms
Exercise 2 (the tempo grid). At \(H = 512\) and 44.1 kHz, which BPM values can
estimate_tempo return between 115 and 125 BPM? Store them (rounded to 0.01, descending) in
answer.
answer = None # TODO
# Solution
bpm = lambda lag: 60 * FS / (HOP * lag)
answer = [round(bpm(lag), 2) for lag in range(30, 60) if 115 <= bpm(lag) <= 125]
assert answer == [123.05, 120.19, 117.45] # lags 42, 43, 44
Exercise 3 (choosing the hop). How would halving the hop to 256 samples change the grid
spacing near 120 BPM? Predict, then compute. Store (coarse, fine) spacings in BPM in answer.
answer = None # TODO
# Solution
bpm = lambda lag, hop: 60 * FS / (hop * lag)
answer = (bpm(43, 512) - bpm(44, 512), bpm(86, 256) - bpm(87, 256))
assert abs(answer[0] - 2.73) < 0.005 and abs(answer[1] - 1.38) < 0.005 # roughly halves
Common pitfalls
Frames, not samples. Every peak-picking length counts ODF frames (\(H\) samples each). Convert with frames = seconds \(\times f_s/H\), or use
PeakPickingConfig.set_min_peak_separation_ms.The default floor hides weak onsets. The ODF is normalised by its maximum and the default threshold never drops below 0.1, so an onset whose peak is under a tenth of the clip’s strongest is not reported. Lower the floor (
min_thresholdofAdaptiveThresholdConfig) for material with a wide dynamic range, and check the result with.explain().Nested configs are copies in Python: build a
PeakPickingConfigand assign it toconfig.peak_picking; calling setters onconfig.peak_pickinghas no effect.onset_detection_functionreturns(times, values), in that order.Reported times are frame centres, quantised to \(H/f_s\); on clean clicks the peak usually falls in the last frame before the onset, so the reported time is within one hop and usually early.
“Energy” flux is magnitude flux here: magnitudes are not squared.
Octave errors in tempo are expected, not exceptional: check the estimate against \(2\times\), \(\tfrac{1}{2}\times\) and \(3\times\) before trusting it.
BeatTrackingConfig.tempo_bpmis ignored byestimate_tempo.The frame-wise onset functions differ from the detector used here:
AudioSamples.onset_strengthuses a mel spectrogram in dB andrhythm.peak_pickuses separate pre/post windows, so their numbers will not matchdetect_onsets.
See also
Rust guide chapter: Onsets and tempo (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open) and the onset module documentation.Python API:
AudioSamples.detect_onsets,AudioSamples.onset_detection_function,AudioSamples.estimate_tempo,AudioSamples.detect_beats,OnsetDetectionConfig,PeakPickingConfig,AdaptiveThresholdConfig,BeatTrackingConfig(API reference).Previous: 12. Dynamics. Next: 14. Psychoacoustics and codecs.
References
Bello, J. P., Daudet, L., Abdallah, S., Duxbury, C., Davies, M. and Sandler, M. B. (2005). A tutorial on onset detection in music signals. IEEE Transactions on Speech and Audio Processing, 13(5), 1035-1047.
Dixon, S. (2006). Onset detection revisited. In Proceedings of the 9th International Conference on Digital Audio Effects (DAFx-06), Montreal, 133-137.
Ellis, D. P. W. (2007). Beat tracking by dynamic programming. Journal of New Music Research, 36(1), 51-60. (Autocorrelation tempo estimation with a log-normal tempo prior.)