9. Oscillators and Frequency Shifting¶
Shifting a signal in frequency is one of the most common operations in an SDR. PySDR does it in several chapters with a single line of NumPy, for example when it simulates a frequency offset in the Synchronization chapter:
t = np.arange(0, Ts*len(samples), Ts) # create time vector
samples = samples * np.exp(1j*2*np.pi*fo*t) # perform freq shift
Mathematically this is
which reads: rotate every sample by an angle that grows by \(\omega\) radians from one sample to the next. The thing that produces \(e^{j(\omega n + \varphi_0)}\) is called a numerically controlled oscillator, or NCO.
In a streaming receiver two things change compared to the NumPy one-liner. The time vector is no longer finite: the oscillator has to run for hours, block after block, with its phase continuing seamlessly from one block to the next. And it runs at the full sample rate, so it has to be cheap. In this chapter we build five oscillators, measure their speed, and then run each of them for one billion samples to see what happens to their accuracy. Two of the results surprised the author, and the winner in accuracy is the version that every FPGA uses.
Five Ways to Make a Sine Wave¶
All five live in code/include/cppsdr/nco.hpp and share the process(in, out) interface of the FIR filters. They differ only in how \(e^{j\theta}\) is produced for each sample.
1. Phase accumulator and std::polar. The direct translation: keep the phase \(\theta\) in a variable, compute cosine and sine every sample, add \(\omega\), and wrap the phase into \([-\pi, \pi)\):
for (std::size_t i = 0; i < in.size(); ++i) {
out[i] = cmul(in[i], std::polar(1.0f, ph_)); // cos and sin of the phase
ph_ += w_;
if (ph_ >= pi) ph_ -= 2 * pi; // keep |phase| small
else if (ph_ < -pi) ph_ += 2 * pi;
}
We try it with the phase in float and in double. (cmul is the hand-written complex product from Samples in Memory.)
2. The recursive rotator. Adding angles is the same as multiplying phasors: \(e^{j\omega(n+1)} = e^{j\omega n} \cdot e^{j\omega}\). So instead of computing a sine and a cosine every sample, keep the current phasor \(p\) and multiply it by the constant \(e^{j\omega}\) each step. That is one complex multiplication per sample and no trigonometry at all. The catch: rounding makes \(|p|\) drift away from 1, so it has to be renormalized now and then. This is exactly GNU Radio’s gr::blocks::rotator (gr-blocks/include/gnuradio/blocks/rotator.h), which renormalizes every 512 samples:
gr_complex rotate(gr_complex in)
{
d_counter++;
gr_complex z = in * d_phase; // rotate in by phase
d_phase *= d_phase_incr; // incr our phase (complex mult == add phases)
if ((d_counter % 512) == 0)
d_phase /=
std::abs(d_phase); // Normalize to ensure multiplication is rotation
return z;
}
3. VOLK’s rotator. GNU Radio’s block-wise rotateN() calls volk_32fc_s32fc_x2_rotator2_32fc. Its NEON version (VOLK 3.3) runs four phasors side by side, \(e^{j(\theta + k\omega)}\) for \(k = 0..3\), and advances all four at once by \(e^{j4\omega}\), one vector multiplication per four samples. Every 512 samples it throws its phasors away and recomputes them from an exact angle that it tracks separately in double precision, with Kahan’s compensated summation. We will see why that matters.
4. The integer phase accumulator with a lookup table. This is how hardware does it, and how gr::fxpt_nco in GNU Radio (gnuradio-runtime/include/gnuradio/fxpt.h) does it. The full circle \(2\pi\) is mapped onto \(2^{32}\), so the phase is a 32-bit unsigned integer. The top bits select an entry of a sine table, the remaining bits interpolate linearly between two entries:
static float sin_lut(std::uint32_t ph)
{
const seg s = table_[ph >> FRAC_BITS]; // top 10 bits: segment
return s.slope * (float(ph & FRAC_MASK) * FRAC_SCALE) + s.offset; // the rest: interpolate
}
void process(std::span<const cf32> in, std::span<cf32> out)
{
for (std::size_t i = 0; i < in.size(); ++i) {
const float s = sin_lut(ph_);
const float c = sin_lut(ph_ + 0x40000000u); // cos(x) = sin(x + quarter turn)
out[i] = cmul(in[i], cf32(c, s));
ph_ += inc_; // wraps modulo 2^32, which is exactly modulo 2*pi
}
}
Notice what is missing: there is no phase wrapping. None is needed, because the C++ standard specifies that unsigned integers obey the laws of arithmetic modulo \(2^n\) ([basic.fundamental]). When the accumulator passes \(2^{32}\), it wraps around to a small number, exactly as the phase wraps around after a full circle. This is a guarantee, not an accident of the hardware. The same is not true for signed integers, where overflow is undefined behavior and the optimizer is allowed to assume it never happens (Pikus, The Art of Writing Efficient Programs, chapter 11). So the type std::uint32_t here is a deliberate choice, not a detail. The cosine needs no second table either: a quarter turn is 0x40000000, so \(\cos\theta = \sin(\theta + \pi/2)\) is one integer addition away. The table of 1024 segments is computed by the compiler and stored as read-only data; Compile-Time DSP: Filters, Tables and Constellations shows how.
The same oscillator in VHDL. This is the numerically controlled oscillator inside every FPGA design and inside vendor cores such as AMD’s DDS Compiler. The VHDL looks almost the same as the C++, because unsigned addition in numeric_std also simply drops the carry:
signal phase_acc : unsigned(31 downto 0) := (others => '0');
...
process(clk)
begin
if rising_edge(clk) then
phase_acc <= phase_acc + phase_inc; -- wraps modulo 2**32, like uint32_t
end if;
end process;
lut_addr <= phase_acc(31 downto 22); -- top 10 bits address the sine table
Because the C++ model uses the same integer arithmetic, it can produce bit-identical phase values to the hardware, sample for sample. That makes it a reference model you can compare a VHDL simulation against with an exact equality test rather than a tolerance.
Speed¶
Here is what each oscillator costs per sample when shifting blocks of 4096 samples (code/bench/bench_nco_costas.cpp):
Oscillator |
ns/sample |
MS/s |
with |
|---|---|---|---|
phase in |
7.11 |
141 |
6.79 |
phase in |
4.10 |
244 |
3.57 |
recursive rotator, renormalized every 512 |
2.89 |
346 |
2.74 |
VOLK |
1.06 |
943 |
0.95 |
|
1.14 |
878 |
1.18 |
Apple M1 performance core, Apple Clang 21, -O3 -mcpu=native.
The ranking follows from what limits each loop. The std::polar versions call the math library’s sincos for every sample; that is the cost of a few dozen instructions, and calls cannot be vectorized. The double version pays more for the higher precision. The plain rotator has no function calls, but it has a dependency chain: each phasor is computed from the previous one, so the next complex multiplication cannot start until the last one has finished. That is the same latency wall we hit with the single accumulator in the FIR Filters in C++ chapter, and VOLK breaks it the same way, by keeping four independent phasors in flight. The integer NCO has a dependency chain too, but it is a single integer addition, one cycle. Everything else (two table lookups, two multiply-adds, the complex product) is independent from sample to sample, so the core can overlap many samples. It is not vectorized, because ARM’s NEON has no instruction to gather table entries from different addresses, and it is still within 10% of VOLK.
Accuracy over a Billion Samples¶
Speed is only half of the story. An oscillator in a receiver runs for a long time, so we ran each one for \(10^9\) samples (50 seconds of signal at 20 MS/s) at \(\omega = 2\pi \cdot 0.0123456\) and compared its output against \(e^{j(\omega n + \varphi_0)}\) computed in long double, at checkpoints spaced by factors of ten:
Figure 9.1 Maximum error \(|y - e^{j\theta}|\) in a 4096-sample window starting at the given sample index. An error of 2 means the phase is completely wrong (pointing the opposite way).¶
There is a lot going on in this plot, so let’s take the lines one at a time.
The float phase that is never wrapped (yellow) is wrong almost immediately: an error of \(10^{-2}\) after a thousand samples, completely random phase after a hundred thousand. The reason is the format of float. It has 24 bits of mantissa, so the spacing between representable numbers grows with their size. Near \(\pi\) it is \(2.4 \cdot 10^{-7}\), but by the time an unwrapped phase has grown to 8000 radians (after \(10^5\) samples here), the spacing is \(4.9 \cdot 10^{-4}\), and every addition of \(\omega\) is rounded to that grid. This is why every oscillator wraps its phase, and why PySDR’s Costas loop has those two while loops at the end. The NumPy one-liner from the beginning of this chapter has the same problem in principle, with a much larger margin, because NumPy computes the time vector in float64.
The rotator without renormalization (pink) keeps its phase, but its amplitude drifts: every complex multiplication rounds, and the magnitude of the phasor random-walks away from 1 and then grows exponentially. After \(10^8\) samples its output is more than ten times too large, after \(10^9\) it is \(10^{11}\). Renormalizing every 512 samples (green-blue) fixes the amplitude completely.
The wrapped float phase (orange) and both rotators drift slowly but steadily: their error grows in proportion to the number of samples, which means they are running at a slightly wrong frequency. Where does the frequency error come from? For the rotators, from the frequency specification itself: the increment \(e^{j\omega}\) is a pair of floats, and its angle is already off by \(3.5 \cdot 10^{-9}\) radians per sample before the first multiplication. We can check that: measured against its own effective frequency (the exact angle of the float phasor), VOLK’s rotator stays below \(7 \cdot 10^{-6}\) for the full billion samples, thanks to its double-precision Kahan resync, while the simple renormalized rotator slowly accumulates rounding error up to \(10^{-3}\). The wrapped float phase drifts six times faster than the rotators, because every addition \(\theta + \omega\) is rounded to the \(2.4 \cdot 10^{-7}\) grid near \(\pi\), and those rounding errors do not cancel out.
Is that drift a problem? Translated into frequency it is tiny: 0.07 Hz for the float phase and 0.01 Hz for the rotators, at 20 MS/s. In front of a PLL or Costas loop that tracks the carrier anyway, it does not matter at all. It matters when phase must stay coherent over long times: two channels of a phased array that must keep a fixed phase relation, a transmitter and receiver that are supposed to stay locked, or a long coherent integration.
The double-precision phase (blue) has an error of \(4 \cdot 10^{-8}\) after \(10^8\) samples, which is the rounding of the float output. It is the accuracy reference, and it is the slowest oscillator.
The integer accumulator (green) is the only line that is perfectly flat: \(4.8 \cdot 10^{-6}\) at sample one thousand and at sample one billion. Integer addition is exact, so nothing accumulates; the phase after \(n\) samples is exactly \(n \cdot \text{inc} \bmod 2^{32}\), forever. The remaining error is the table interpolation, and it matches the textbook bound for linear interpolation of a sine with segment width \(\Delta = 2\pi/1024\): \(\Delta^2/8 = 4.7 \cdot 10^{-6}\).
There is one subtlety, marked with an asterisk in the figure. The integer oscillator can only represent frequencies that are multiples of \(2\pi/2^{32}\), so it runs at the nearest such frequency, not at exactly the requested one. Against the requested frequency it drifts too, by at most \(f_s/2^{33}\) (0.002 Hz at 20 MS/s), and in our test it reached 0.36 after \(10^9\) samples. The difference is that this frequency error is known exactly, it is the same on every machine, and an FPGA with the same increment produces the very same phase. The float versions’ effective frequency depends on rounding details that nobody specifies.
Key Takeaways¶
The integer phase accumulator with a lookup table is fast (about 1 ns per sample here, scalar), has a bounded error, wraps for free because unsigned arithmetic is modular by definition, and produces bit-identical results to an FPGA NCO. For an oscillator that runs forever, it is the best default.
A float phase accumulator must be wrapped, and even then it drifts in frequency. A double accumulator is accurate, but the slowest option.
A recursive rotator needs renormalization, and its speed is limited by its own dependency chain unless several phasors run in parallel, as VOLK does. VOLK’s version is also free of accumulated phase error, but no rotator can be more accurate than the float phasor it is given as its frequency.
“Accuracy” has two parts: how precisely the frequency is specified, and whether rounding errors accumulate. Look at both.