JoshJers' Ramblings

Infrequently-updated blog about software development, game development, and music

FFTs Part 6: The FFT-20XX Real-Input Algorithm(s)

Here it is, the final part of this series of posts about FFTs and the specific algorithms that FFT-20XX uses.

  1. The Discrete Fourier Transform
  2. The Basics of the FFT
  3. Some Optimizations to the FFT
  4. The Inverse FFT
  5. The FFT-20XX Complex-Input Algorithm
  6. The FFT-20XX Real-Input Algorithm(s) (← you are here)

Over five posts we’ve gone over way more about the FFT than I ever intended to write, up to and including the complex-input algorithm used by FFT-20XX.

But one thing we haven’t gone over yet is how to deal with purely real-valued inputs (like, for instance, most audio and video applications).

This took me a hot minute to get right and was effectively the final boss of the whole project! Once again, we can’t just jump right in — first, we need to talk about real-input FFTs.

Real-Input FFTs

For FFTs where the inputs are only real values (like audio samples), at first glance it may seem like there isn’t enough memory to store all of the results. For example, a 256-element real-input FFT would have 256 real (scalar) inputs, but generate 256 complex outputs (each of which contains two scalars), which means it seems like we’d need 512 scalars worth of output data.

But, if we go all the way back to part 1 of this series and play around with the diagrams again, we’ll note that the DFT creates the folowing values:

  • The first element is the DC bias (or DC offset). This is always a real value when there are only real inputs (as all of the rotations are 0, so nothing ever ends up in the complex (y) component).
  • The next N2−1\frac{N}{2} - 1 values are complex, representing the (non-zero) frequencies below the Nyquist frequency.
  • The value at index N2\frac{N}{2} represents the aforementioned Nyquist frequency, and — like the DC bias — is always a real value when the inputs are real (as the rotations are either 0 or 180 degrees, which is effectively only ever a scale of 1 or -1).
  • The remaining N2−1\frac{N}{2} - 1 values are complex, but they are (in reverse order) the complex conjugates of the other complex values when the inputs are all real values (they are still distinct values for complex inputs)
Note

The complex conjugates are in the opposite order from each other. If you recall that our angles look like:

  0, 1, 2, 3, 4, -3, -2, -1

Angles 1 and -1 are conjugates, 2 and -2 are conjugates, etc.

This little reversal caused me a lot of headache while trying to get this all to work, as you’ll see in a bit!

So what we have are N2−1\frac{N}{2} - 1 complex values, 2 real values, then the rest are effetively redundant, as they’re the same as the other complex values but with the opposite sign on the imaginary component.

Conveniently, that’s NN scalar values, which fits exactly in the same amount of space as our inputs!

Note

Traditionally, to keep the complex pairs together, the Nyquist value gets moved to be paired with the DC value, so the memory layout ends up like:
 vdcv_{dc}, vnyqv_{nyq}, r1r_1, i1i_1, r2r_2, i2i_2, …, rN/2−1r_{N/2-1}, iN/2−1i_{N/2-1}

That’s great! Now we know that we can store the values in the same amount of memory, now we just need to figure out how to compute the values in half the usual memory!

Computing the Real-Input FFT

There are a few techniques that people have used to calculate the FFT of purely real-valued data. One trick (illustrated here) is to compute two halves of the real FFT at the same time using a single (N2\frac{N}{2}-length) complex FFT, then combine the two halves into the final result with a single radix 2 step. This works well, but there are more-efficient ways to do it.

Instead, we’ll start with an idea from this 1968(!) paper by Glenn D. Bergland.

Remember that the (radix-2) decimation in time algorithm does a pass of standard 2-element FFTs, then a pass of 4-element FFTs, etc:

A standard 16-element radix-2 diagram. " " 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

We can take advantage of the fact that every real-valued FFT has two real output values (DC and Nyquist) and the rest are complex conjugate pairs.

Here’s that diagram again, this time with known-real values labeled with blue squares, the “necessary” complex values labeled with green up-pointing triangles, and the redundant conjugate complex values labeled with red down-pointing triangles (some of the triangles have circles on them, I’ll explain those in a moment):

A standard 16-element radix-2 diagram, where the values have been color-coded by function as described above. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 0 0 0 0 0 0 0 4 0 4 0 4 0 4 0 2 4 6 0 2 4 6 0 1 2 3 4 5 6 7

There are some interesting things to note here:

  • The first pass has only real outputs: Because there are no rotations involved, it’s just an add/sub step, leaving everything still real.
  • In the next step, half of its outputs are real. This makes sense: two outputs get computed with no rotation and two with a 90-degree rotation (which end up as conjugates of each other).
  • From the second step on, every step has half the number of real outputs as the step before, ending when there are just two left (DC and Nyquist). Each sub-FFT (past the first) has four real inputs, and of those, one pair is used without rotation, leaving them real.
    • The other pair of real inputs to these sub-FFTs, it’s worth noting (because we’ll use this later), is always done with a 90-degree rotation. This is what the small circles on those values signify.

If we instead visualize this with standard-order inputs and bit-reversed outputs, it can give us even more insight:

The same 16-element FFT diagram, except reordered as described above. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 4 2 6 1 5 3 7 0 0 4 4 2 2 6 6 0 0 0 0 4 4 4 4 0 0 0 0 0 0 0 0

Viewed this way:

  • The halving of the number of real values after the first step is much easier to see, as we keep them all contiguous.
  • In this ordering, DC and Nyquist end up next to each other at the end, exactly as we want for our final output!
  • Every complex value in the final output is paired with a conjugate value.
    • Note that these are not necessarily paired conjugates (see the note earlier about how the pairs of conjugate values are in the opposite order from each other).
  • Every computation step (the circular nodes) with complex inputs kicks out one “standard” complex value and one “redundant” value.
    • Again, these are not always conjugates of each other!
  • The 90-degree rotations (the arrows with circles on them) are always the first set of complex conjugate pairs after the real outputs (as they are the output from the half of the real inputs to this step that were rotated).

Zeroing in on that third point, if every computation kicks out one redundant complex value, we can use that to our advantage: instead of storing that redundant value, we could use its storage to hold the imaginary value for the non-redundant output. That gives us enough space to do the whole computation in the memory we were provided!

To figure out the best way to do that, let’s go back to one of our diagrams from part 2, showing the way that the elements interleave during the FFT computation:

A diagram (originally from part 2) showing the inputs on the left in bit-reversed format, then they interleave in groups of 4, then 8, then 16, before ending up in standard, ascending order as outputs on the right. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4 8 12 2 6 10 14 1 5 9 13 3 7 11 15 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Now we’re going to relabel the redundant conjugates’ indices to correlate them with their matches (recoloring to match the above butterfly diagram, and using “R” and “i” to show which gets the real and imaginary components):

The same diagram as above, but this time with the values color-coded as to whether they are real, complex, or the complex conjugate, and the conjugates have been re-labeled to show the index of the value they are the conjugate of. 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 0 4R 8 4i 2 6R 10 6i 1 5R 9 5i 3 7R 11 7i 0 2R 4R 6R 8 6i 4i 2i 1 3R 5R 7R 9 7i 5i 3i 0 1R 2R 3R 4R 5R 6R 7R 8 7i 6i 5i 4i 3i 2i 1i

Now, let’s rearrange the rows of this to have the inputs in standard order (to match the butterfly diagrams above):

A diagram similar to the above, but reordered such that the inputs on the left are in standard, ascending order and the outputs on the right are in the bit-reversed order. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 8 9 10 11 4R 5R 6R 7R 4i 5i 6i 7i 0 1 8 9 4R 5R 4i 5i 2R 3R 6i 7i 6R 7R 2i 3i 0 8 4R 4i 2R 6i 6R 2i 1R 7i 5R 3i 3R 5i 7R 1i

Now we can see that we hypothetically have space for everything, but if we keep things in their standard order, we end up with complex pairs that are not actually correlated (note how 1R1_R is followed by 7i7_i, etc).

Ignoring that for a moment, let’s look at what we have to do to even make this work (sticking to radix-2 for now).

For any given radix-2 computation involving complex inputs, we actually end up needing to load two at once, because both the “real” and “imaginary” component still represent two distinct values (the complex conjugates vR+iviv_R + i v_i and vR−iviv_R - i v_i), and thus are used to get two different sets of outputs.

To illustrate this, we’ll use a modified butterfly diagram, showing the two pairs (one real, one imaginary) that go into each value, and the corresponding values that come out:

Note

I left the rotations off of this diagram, mostly because I couldn’t figure out where to put them.

A modified radix-2 butterfly diagram showing the pattern of accesses necessary to use the real and imaginary components (stored separately) to compute their corresponding outputs. It's a bit of a mess. 0 8 4R 4i 2R 6i 6R 2i 1R 7i 5R 3i 3R 5i 7R 1i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Welp. This is a bit more of a mess than our previous diagrams due to the overlapping ranges here. Each computation that has complex inputs, as we said, has two pairs of inputs, and writes to two pairs of outputs.

Importantly: The indices for input and output per computation are always the same, though which values get paired changes from input to output.

In addition to the real and imaginary components not ending up paired (again, note that 1R1_R is paired with 7i7_i, which is not its imaginary part), the other problem with this arrangement is that it very much does not SIMD well. Plus, even if it did, it ends up causing problems when we get to doing the incremental bit reversal (similar to how the complex-input did it)!

Note

Specifically, once this gets squished together into radix-4 and there are passes loading 4 sets of radix-4s to do the bit flips, as it gets closer to the end for larger FFT sizes (ones that would be prohibitive to diagram here), there end up being long dependency chains through the various butterflies needed, and frequently the final step requires all of them be computed at once in order to properly do the final bit flip pass!

That’s not ideal.

But, going back to that paper by Glenn D. Bergland, we can change the order in which we save out the imaginary components, such that things end up staying paired:

The block interleave diagram again, but this time with the imaginary components stored in different orders, and how that filters through the system. The output pairs are now correlated (the real and imaginary components are stored contiguously). 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 8 9 10 11 4R 5R 6R 7R 4i 5i 6i 7i 0 1 8 9 4R 5R 4i 5i 2R 3R 2i 3i 6R 7R 6i 7i 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i

At first glance, this looks great! A given set of “real” values (the non-redundant complex values) is now followed by its corresponding “imaginary” parts (its complex conjugate) at every step, which is what we were looking for! If we do a butterfly diagram again, it’s a lot more regular-looking than the last one:

A modified radix-2 FFT diagram showing this new ordering. It is considerably less messy than the last attempt. 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

So it seems like maybe this is the point where we start in on the bit-reversal like we did with the complex-input FFT. Buuuuut before we do that, we can make this a little more efficient!

90 Degree Rotations

This whole time we’ve been labeling the complex values that are the result of a 90-degree rotation with the promise that it was going to be important. Well, the time is nigh!

As we’ve gone over many times, the decimation in time algorithm rotates the second input and then adds it to and subtracts it from the first input to get the two outputs for a given computation step:
 y0=x0+kx1y_0 = x_0 + k x_1
 y1=x0−kx1y_1 = x_0 - k x_1

In the event that we’re rotating by (negative) 90 degrees, kk is just −i{-}i:
 y0=x0−ix1y_0 = x_0 - i x_1
 y1=x0+ix1y_1 = x_0 + i x_1

If x0x_0 and x1x_1 are both real numbers (which they are, for our 90-degree rotations), and we’re only writing out the first complex output y0y_0 (where the real component goes where y0y_0 lives and the imaginary component goes where we would put y1y_1), then the value at the location of x0x_0/y0Ry_{0R} is completely unchanged (the real component of y0y_0 is x0x_0), and the value at the location of x1x_1/y0iy_{0i} is just negated (the imaginary component of y0y_0 is −x1{-}x_1).

An Example

If we have the two input values x0=8x_0 = 8 and x1=3x_1 = 3 for a radix 2 butterfly with a quarter-turn rotation, rotating the latter (as it’s our odd input) turns it into −3i-3i. Thus the sum for y0y_0 ends up being 8−3i8 - 3i.

Because we’re only writing out y0y_0 (putting its imaginary component where y1y_1 would go in a complex FFT), one value written is 88 and one is −3-3.

And since these are being written to the same 2 indices that the inputs came from, the end result (in memory) is simply a negation of the second input: the 88 remains unchanged, and the 33 is negated.

So let’s redraw the diagram again, making those parts be pass-through, except for a negation (represented by a long red rectangle):

A similar diagram to the last radix-2 diagram, except where there were real values being processed into complex pairs, instead we have denoted that no work happens (besides the imaginary outputs being negated). 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

So now there are these blocks where nothing is happening except a negation!

If we, instead, moved the negation to the end of the previous phase (when writing those values out), we can collapse all of those down (shifting everything after one of these negation-only passes to the left in the diagram), removing almost one entire pass (everything except the computation of outputs 0 and 8):

The same diagram as above, except the "no work being done" sections have been collapsed, so overall there is one less pass of FFT calculation. The only exception are the first two outputs (indexed 0 and 8), which remain real the whole time and thus cannot collapse. 0 8 4R 4i 2R 2i 6R 6i 1R 1i 7R 7i 3R 3i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

This gives us two nice properties:

  1. The main one: now instead of log⁡ N\log\,N steps, we are doing (log⁡ N)−1(\log\,N) - 1 steps (with a single addition and subtraction at the end to compute the final two values).
  2. The real groups are all consistent, and the last half of each real group negates the second outputs (outputting x1−x0x_1 - x_0 instead of x0−x1x_0 - x_1).

Now we’re doing less work, and it’s all very regular in how it works (which means good things for SIMD implementation!), so finally it’s time to handle…

Bit Reversal

Two related things change the way we do the bit reversal in this:

  1. We’ve managed to work our equation such that we have all of the pairs of values (DC/Nyquist and the real/imaginary pairs) together already, so we don’t want to break those up.
  2. There are half as many complex outputs as with a complex FFT (counting DC and Nyquist as one), since we’re dropping the redundant complex conjugates.

Turns out, instead of doing the bit reversal for all NN elements, we actually reverse in N2\frac{N}{2} pairs instead! So, in our 16-element example, we do the reversal as if it were 8 elements, which means there is only one bit reversal instead of two (since 8 elements has 3-bit indices, so the outer two bits swap and the middle one stays put).

The method we use to do the bit reversal is effectively the same as with the complex FFT: the last half of the radix-2 steps each do a middle-out bit reverse.

Note

And, accordingly, when we get to radix-4, each radix-4 pass reverses a pair of bits, which turns into a 4×4 transpose, exactly the same as with the complex implementatione (except, of course, when one pass needs to only do a single reverse due to an odd number of bit reversals).

Conveniently, all of the same patterns we found in the complex-input version still apply!

So let’s finish up our diagram by doing the single bit reversal at the end (admittedly not as useful as if there were more bit reversals, but like hell am I making any larger diagrams):

The same diagram as before, except now we've added a paired bit reverse step at the end, putting things into an order that is *almost* but not quite sequential. 0 8 1R 1i 2R 2i 3R 3i 4R 4i 7R 7i 6R 6i 5R 5i 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

And there we are! Now all of the outputs are in the order we … uh …

Wait, why are 7 and 5 not in the right spot?

Note

This was a real “Well, shit” moment while I was working on this. This ordering is even in the 1968 paper and I didn’t notice it, because I was so used to seeing the bit-reversed orderings at that point I just assumed.

Reversals Within Reversals

It turns out, back when we rearranged everything to be more regular and get our final pairs together, this also changed the ordering of the components! (If you go back and look at the diagrams before and after we did this, you can see 5R5_R and 7R7_R swap places).

Note

Also, importantly: the angles used for the rotations through the algorithm are also reversed using this same pattern (but in bit-reversed order), so that needs to be taken into account!

The reversal is just barely noticeable at 16 elements, but as we add more, it gets worse and worse. Here’s a grid showing the index pairs of a 128-element FFT (where “0” would contain DC and nyquist) and how they’re flipped (relative to standard order):

What. Even.

It turns out that, due to the way we flipped around the imaginary values that we write at each level, there is a corresponding flip of the outputs. Here’s the indices for 32 elements in a big column showing the reversals:

A display of 32 indices (representing pairs of elements in a 64-element real FFT), and the sections that are reversed 0 1 2 3 4 7 6 5 8 15 14 13 12 9 10 11 16 31 30 29 28 25 26 27 24 17 18 19 20 23 22 21

The process to undo this, then, is as follows:

  • Every 8 pairs of elements, reverse the order of the last 3
  • Every 16 pairs of elements, reverse the order of the last 7
  • Every 32 pairs of elements, reverse the order of the last 15
  • …
  • Every N pairs of elements, reverse the order of the last N2−1\frac{N}{2} - 1
Note

The pattern here is closely related to Gray code, which is a special ordering of values where only one bit changes as the value increments or decrements (major credit to Matthijs De Smedt who figured out the pattern).

The actual code to go from a standard-order index to the “tangled” index above is:

  size_t TangleIndex(size_t i)
  {
    auto mask = (i & (i - 1)) >> 1;

    mask ^= mask >> 32;
    mask ^= mask >> 16;
    mask ^= mask >> 8;
    mask ^= mask >> 4;
    mask ^= mask >> 2;
    mask ^= mask >> 1;

    return (i - (mask & 1)) ^ mask;
  }

I honestly don’t remember how I derived that anymore, but that middle bit with the xors and shifts is exactly the routine to convert a 32-bit Gray code value back to its standard binary representation.

Here’s the one thing that bummed me out coming up with this algorithm: I was unable to find a nice iterative way to handle this (every attempt led to some breakdown of regularity or to giant dependency chains), so this ended up as a post-process step at the end.

But, it’s still way less costly than a full bit-reverse pass, as there are nice ways to do this operation in larger chunks, which can be done fairly efficiently in SIMD on both x64 and ARM.

The Algorithm!

Ultimately, the implementation in FFT-20XX was done in radix-4 instead of the radix-2 we’ve been discussing thus far. I’m not going to go through getting it into radix-4 because, honestly, it’s not the important part, and is just a set of uninteresting, mechanical steps.

Like the complex FFT, it does the bit reversal iteratively, 2 bits at a time at the last half of the transform, except we do the above trickery to compute only the half of the outputs that we need in the space that we have.

Finally, after all that, it does an “untangle” pass to get from, uh, whatever order that is into standard order.

There is a reference implementation checked in here. The main routine is titled RealForwardReference.

The Inverse

The one downside of real FFTs is that, unlike with the complex FFT, we cannot use the same base routine to invert this process. Instead, like in part 4, we need to straight-up do the whole process in reverse (ending up with a DIF-like routine):

  • We start by “re-tangling” the inputs such that they’re in the weird order from the end of our forward routine
  • Then do a series of DIF steps that are the inverse of the steps we did to get here, with every step (except the last one) having twice as many real values as the one before, doing the bit-reverse steps in the first half this time (since those were the last-half steps of the forward algorithm).

Like the forward algorithm there is a reference implementation for this, called RealInverseReference.

SIMD Considerations Again

The optimization of this routine was relatively straightforward: using SIMD operations and doing the bit reversals works very similarly to the complex routine, all of the same tricks apply.

As with the complex routine, as the FFTs get smaller, there are some special-cases that needed to be done. For AVX’s 8-element vectors, FFTs smaller than 128 are done via SSE2, and FFTs smaller than 32 are done purely in scalar.

The untangle was also done by doing the process in blocks, and working as locally as possible to try to stay within CPU cache as much as it can.

Additionally, the table ends up being stored differently: The table entries are stored in “tangled” order rather than the standard order (which means the cos/sin values can’t be overlapped like with the complex version). However, it turns out that we need half as many angles in the table (due to the lack of computing the redundant values), so the table ends up being a bit smaller than the complex-input one (it is 23\frac{2}{3} the size).

Finally

And we’re finally through this gauntlet of bit reversals, other reversals, and diagrams!

If you read this far: wow, I honestly didn’t expect anyone to! Hopefully you found this interesting (or at least understandable).

And now I’m going to try to stop thinking about FFTs for a while.