Pitch Detection
Overview
Bitstream Autocorrelation, or BACF, is an accurate, extremely fast and efficient time-domain pitch detection algorithm, and the method of Q’s pitch detectors. BACF can be at least as accurate as any pitch detection scheme based on autocorrelation. Unlike the standard autocorrelation function (ACF), BACF works on zero crossings, the bitstream, using bitwise operations.
Autocorrelation is the correlation of a signal with a delayed copy of itself, as a function of the delay. It finds repeating patterns, such as a periodic signal obscured by noise, or a missing fundamental implied by its harmonics.
BACF is fast: about 50 nanoseconds a sample, on a 2016 MacBook Pro, tracking guitar phrases with legato, hammer-ons, pull-offs, vibrato, staccato and right-hand tapping (see Performance).
| Q’s BACF pitch detection is tuned for multichannel guitar and tested on it: the test suite covers a 2-octave range on every string of 6-string and 8-string guitars. The algorithm is generic and applies to other sources, but instruments outside that range, especially ones that need more than 2 octaves, may perform differently. |
The API is documented on the member pages: BACF Pitch Detector, BACF Period Detector, Bitstream Autocorrelation and Zero Crossing Collector. The BACF Follower uses the same engine to follow the lag at which a signal repeats, a period or a multiple of one, for time-domain splicing.
Zero Crossings
Timing the zero crossings gives the period, and its reciprocal, the frequency. It is the simplest form of pitch detection. It works on pure sine waves and on fairly clean waveforms such as triangle, sawtooth, pulse and square waves, and fails when a cycle has several transitions.
Figure 1 is a guitar’s low E string, a second after the pick. Its 2nd and 3rd harmonics are strong, as is common with plucked strings, and each cycle crosses zero six times. Heavy low-pass filtering would tame the waveform, at the cost of phase lag, too much for a real-time detector.
The crossings still form a pattern, one wide pulse followed by two successively narrower ones, repeating every cycle. Autocorrelation is the tool for finding repeating patterns.
Autocorrelation
Standard autocorrelation multiplies the signal by a delayed copy of itself and sums the products, at every lag (Figure 2). The sum peaks where the copy lines up with the signal: at the period.
The multiplication is the most expensive part: for a window of N samples, roughly N/2 x N/2 multiply-accumulates. Popular ACF-based detectors and their variants, AMDF (average magnitude difference function), ASDF (average squared difference function), YIN and MPM, have the same cost. An FFT computes the autocorrelation faster, and is still expensive for many channels on a small microcontroller.
Bitstream Autocorrelation
BACF autocorrelates the zero-crossing bitstream in place of the samples. With only ones and zeros, the multiplication is a bitwise operation, and a machine word holds 32 or 64 samples.
The product of two bits is an AND:
| A | B | A * B |
|---|---|---|
0 |
0 |
0 |
0 |
1 |
0 |
1 |
0 |
0 |
1 |
1 |
1 |
Binary 1 and 0 stand for other values, though, and 0 may as well stand for -1, since audio signals run from -1 to +1:
| A | B | A * B |
|---|---|---|
-1 |
-1 |
+1 |
-1 |
+1 |
-1 |
+1 |
-1 |
-1 |
+1 |
+1 |
+1 |
That is an XNOR. BACF takes its inverse, the XOR, which gives a 1 for each mismatch:
| A | B | A ^ B |
|---|---|---|
0 |
0 |
0 |
0 |
1 |
1 |
1 |
0 |
1 |
1 |
1 |
0 |
After the XOR, the bits set to 1 are counted. The lower the count, the higher the periodicity. The count and the window size give a normalized periodicity from 0 to 1, where 1, a count of zero, is a perfect match. One XOR compares a whole word, so BACF is faster than the ACF by the word size (64 on a 64-bit machine), and integer bit operations are cheaper than floating-point multiplication.
Figure 3 is BACF on the low E of Figure 1. The graphs on this page and the member pages are the output of Q’s test suite, test/pitch/pitch_detector_ex.cpp, which runs the BACF Pitch Detector on the guitar samples at 44.1 kHz and writes what it computes:
-
Top: the detector’s input, band-passed, compressed and clipped by the test.
-
Middle: the bitset of each analysis. It holds only the significant pulses, those at least 60% as high as the highest: here, the wide pulse of each cycle.
-
Bottom: the bitstream autocorrelation, as periodicity, one analysis after another. The window spans two periods of the lowest frequency of interest, rounded to whole words: 1344 samples here, for a range of 66 to 412 Hz. An analysis runs every half window, 672 samples, over lags from 0 to half the window. Each starts with a blank, the lags below the shortest period of interest, which are not computed.
Each analysis peaks where the cycle starts to repeat: the period, here 535 to 537 samples, with a periodicity of 0.993. The height of the peak measures how periodic the signal is. The period is read from the interpolated zero crossings of the edges that bound it, to a fraction of a sample (see Results).
More Graphs
The open strings of a guitar, a second after the pick, from the same tests. Each detector’s range is 0.8 to 5 times the string’s open note, so the window is shorter on the higher strings.
The A, D, G, B and high E strings are in Figure 4, Figure 5, Figure 6, Figure 7 and Figure 8. Each analysis peaks at the string’s period. On the B and high E, the harmonics leave lower peaks early in each analysis: 0.84 at 36 samples on the B, 0.84 at 57 on the high E.
At the 12th fret, an octave up, the low E keeps the range of the open string, so half a window holds two cycles (Figure 9). Each analysis has two peaks of equal height, 0.999, at one and two periods. The detector settles the two candidates on the shorter period (see Sub-Collector).
Autocorrelation also finds the period of a missing fundamental, since the waveform still repeats at the fundamental’s period. The test suite checks it with a synthetic tone of the 2nd and 3rd harmonics only (see Results).
The Data Flow
The detector is a pipeline of four classes, from samples to frequency (Figure 10):
-
Zero crossing. Zero Crossing Collector records the crossings, with hysteresis, and the pulses between them, timing each crossing to a fraction of a sample.
-
Bitset and sub-collector. BACF Period Detector packs the significant pulses into a bitset, proposes candidate periods from pairs of edges, and keeps the pair that bounds one cycle (see Sub-Collector).
-
BACF. Bitstream Autocorrelation scores each candidate by XOR and bit count.
-
Bias. BACF Pitch Detector holds the octave against harmonic jumps, and passes the frequency through a 3-point median (see Bias).
Results
From Q’s test suite (test/pitch/pitch_detector.cpp): one second of each test signal at 44.1 kHz, the partials at 0.3, 0.4 and 0.3 unless noted, the detector’s range 0.8 to 5 times the lowest note of the test, and the error of every frequency the detector reports, in cents.
| Test case | Average error | Min error | Max error |
|---|---|---|---|
Middle C (261.63 Hz) |
0.0015 |
0.0001 |
0.0025 |
Middle A (440 Hz) |
0.0028 |
0.0001 |
0.0061 |
Low E (82.41 Hz) |
0.00004 |
0.00003 |
0.0001 |
Low E, 12th fret |
0.00007 |
0.00003 |
0.0001 |
Low E, 24th fret |
0.0002 |
0.00003 |
0.0006 |
A (110 Hz) |
0.000001 |
0 |
0.0001 |
A, 12th fret |
0.00008 |
0 |
0.0001 |
A, 24th fret |
0.0004 |
0 |
0.0011 |
D (146.83 Hz) |
0.0002 |
0.00002 |
0.0004 |
D, 12th fret |
0.0008 |
0.00002 |
0.0016 |
D, 24th fret |
0.0034 |
0.00002 |
0.0096 |
G (196 Hz) |
0.00006 |
0.00006 |
0.00006 |
G, 12th fret |
0.00007 |
0.00006 |
0.00008 |
G, 24th fret |
0.0002 |
0.00006 |
0.0105 |
B (246.94 Hz) |
0.0010 |
0.000002 |
0.0019 |
B, 12th fret |
0.0052 |
0.0002 |
0.0160 |
B, 24th fret |
0.0055 |
0.0003 |
0.0362 |
High E (329.63 Hz) |
0.0011 |
0.00003 |
0.0031 |
High E, 12th fret |
0.0042 |
0.00003 |
0.0133 |
High E, 24th fret |
0.0230 |
0.00003 |
0.0649 |
Phase offsets |
0.0001 |
0.00003 |
0.0003 |
Missing fundamental |
0.0012 |
0.00003 |
0.0046 |
Non-integer harmonics |
1.02 |
0.94 |
1.13 |
The phase-offset case shifts the partials' phases (0.1, 0.5 and 0.4 of a cycle). The missing fundamental has the 2nd and 3rd harmonics at 0.5 each. The non-integer case puts the 2nd harmonic at 2.003 times the fundamental, so the waveform never repeats exactly.
Performance
On a 2016 MacBook Pro, the detector averages about 50 nanoseconds a sample on guitar phrases, with sub-cent accuracy on sustained notes. The speed comes from three savings: sparse zero-crossing edges in place of every sample, a word of bits per XOR in place of one multiply per sample, and a period read from the edges in place of a sweep over every lag.
Phrase Tests
The tests use typical playing techniques: legato, hammer-ons and pull-offs, vibrato, staccato and right-hand tapping. In each recording, from the 2020 article, the left channel is the guitar and the right is a square wave that follows the detected pitch, with an envelope follower shaping its level and filter. All are recorded with the Nu multichannel pickup, except the short staccato, a synthesized sine burst.
Melodic lines (legato).
Staccato.
Articulations.
Prediction and Zero-Latency Attacks
Any detector based on autocorrelation needs at least two cycles, since a cycle is correlated with the next. The zero-crossing edges on or just before the onset give an earlier prediction, from the first two similar pulses: one cycle at the least, about 12 ms for the low E string (1/82.41 Hz).
Figure 11 is the low E of the tests, from the pick. The test’s input opens at 0.992 s. The first prediction, 82.4 Hz, is at 1.029 s, three cycles in, and 82.6 Hz from 1.041 s. bacf_pitch_detector gives the prediction through predict_frequency(), and bacf_period_detector through predict_period().
Attack transients need not be periodic at all. A Hammond organ has its key click, a violin its bow noise, a voice its unvoiced consonants, and a guitar pick sounds "clik" or "clok" depending on where you pick. A percussive or semi-periodic sound under about 20 ms gives the note character without setting its pitch, and does not sound out of tune whatever its frequency. A synthesizer that follows the pitch can start at the pick with the attack, and take up the pitch from the prediction, with no audible latency.
A wrong prediction that corrects downward, from too high to the right pitch, is barely perceptible. One that corrects upward is more pronounced, as in the glitch below, a low onset predicted too low. When a prediction is uncertain, err high.
History
BACF was first published in the 2018 articles listed under Further Reading; the 2020 article describes the algorithm as Q implements it. After the first article, I learned of David Warrender’s hardware pitch analyzer from the 1980s, whose patent (since expired) covers a related zero-crossing correlation technique: prior art, credited here.
Further Reading
The three articles this overview is based on, with the full derivation, measurements, and listening tests:
-
Fast and Efficient Pitch Detection: Bitstream Autocorrelation (2018), the original method.
-
Fast and Efficient Pitch Detection: Bliss! (2018), BACF on real guitar recordings: harmonics, multiple edges and note onsets.
-
Fast and Efficient Pitch Detection: Revisited (2020), the matured algorithm and the data flow above.
The wider reading those articles collect, on pitch detection in general:
-
High Accuracy Monophonic Pitch Estimation Using Normalized Autocorrelation
-
High Accuracy and Octave Error Immune Pitch Detection Algorithms
-
HPS Algorithm for detecting the fundamental frequency of a guitar string
-
Computer Controlled Precision Piano Tuner Using DSP for Frequency Measurement
-
Accurate and Efficient Fundamental Frequency Determination from Precise Partial Estimates
-
A spectral/temporal method for robust fundamental frequency tracking
-
How can I measure the harmonicity of an audio spectrum? (Robert Bristow-Johnson)
-
What is an AMDF? (Robert Bristow-Johnson)
-
How to deal with low fundamental when using AMDF for pitch extraction? (Robert Bristow-Johnson)