Back to posts.

Fast Fourier Transform

For an upcoming project for which we want to use generative audio and audio reactive visuals I'm looking into the Fast Fourier Transform (FFT). I've found the FFT always really interesting although I'm not that math savvy and most articles you read on FFT go really into the maths of how a FFT works.

In this post I won't go into the math of how the FFT works, because other people have a way better understanding of the FFT then I do and they have already written quite good articles on this. See the references below.

You do need to know that the FFT is used to transform a signal from the time domain into the frequency domain. If you're not used to these things this may sound as abacadabra. Fourier describes that any wave is the sum of multiple waves. This article on Better Explained does a good job explaining and visualising this.

I'll limit the rest of this post to the output of a fourier transform as that's what I will be using for this audio reactive system. I'm using the Fastest Fourier Transform in the West library that computes the FFT for us. This library is extremely simple to use and super fast!

Any FFT function uses input values that it transforms. Because I'm working on an audio reactive system I'm using the audio data as input. In my case I'm giving the fft function 1024 samples (mono) of audio. FFTW has a function which takes doubles as input, so I only need to convert the float values I get in my audio callback function to doubles.

The output of the fft function I'm using, is an array with complex types. This array describes the different sinusoidals of the wave form you passed into the FFT function. Each value from this array is a complex. A complex type has a real and imaginary part. Each of these complex values in the output describes a sinusoidal and how much it contributes to the original wave form.

int nelements_in = 1024;
int nelements_out = (nelements_in / 2) + 1;
in = (double*) fftw_malloc(sizeof(double) * nelements_in);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * nelements_out);
plan = fftw_plan_dft_r2c_1d(n, in, out, FFTW_MEASURE);

Once you've setup a plan, you can reuse it as many times as you like. Make sure to free the allocated plan and input/output arrays when you don't use them anymore:

fftw_destroy_plan(plan);
fftw_free(in);
fftw_free(out);

To perform the FFT I'm first converting the audio data I get from in my audio callback function to doubles so they can be used by FFTW. Make sure that the number of audio samples you copy to your input array for FFTW has the same size. In my case I'm simply copying the incoming audio data to my input array:

for(int i = 0; i < nframes; ++i) {
in[i] = data[i * nchannels + 0]; // only using one channel
}

Once I've converted the audio data, I use the fftw_execute(plan) function to perform the FFT.

fftw_execute(plan);

After calling fftw_execute(plan) you can use the results that are stored in your output variable. Each index describes how much a sinusoidal with a certain frequency contributes to the original wave form and in what way it contributes. You can describe a sinusoidal like: sin(2 * pi * freq + phase ) * amplitude. The magnitude of the complex value represents the amplitude of the wave. The phase is encoded as the angle atan2(imaginary,real).

I've been told that a good intuition of the contribution for a particular complex value is the magnitude aka amplitude of the wave. Therefore I'm using sqrtf(imaginary * imaginary + real*real), to get the amplitude. I could use this amplitude/magnitude value as input for my audio reactive visualisation or one can convert it to decibels to get a value which is more representative for the way we perceive audio waves. There is much more to it and I need to do some research on scaling the results into a correct dB range, though the result I get when using 10 * log10f(amplitude) seem correct and are useable.

This is the part where I convert the output array to values I can use:

int extra_scale = 100; // scaling the result a bit

for(int i = 0; i < N/2; ++i) {
double mag = sqrtf((out[i][0] * out[i][0]) + (out[i][1] * out[i][1])); // out is the output of the fft function
int value = 10.0f * log10f(mag + 1.0) * extra_scale;  // the + 1.0 is to make sure I don't get negative values, this is the value you should use in your audio reactive system
}

Note: Keep in mind that you don't use all the elements of the output array. We only use (N/2)+1 elements. Also, because the range of frequencies that a human can hear is limited, we don't actually need to process all the results anyway. You can read more about this here

Example

Complete code example (note: I used this code to get into FFT and the FFTW library; please contact me if you see any issues/bugs).

Fourier.h

#ifndef FOURIER_H
#define FOURIER_H

#define ROXLU_USE_MATH
#define ROXLU_USE_OPENGL
#include <tinylib.h>
#include <fftw3.h>

class Fourier {

public:
Fourier();
~Fourier();

void copy(float* data, unsigned int nframes, int nchannels);

public:
int nelements_in;
int nelements_out;
double* in;
fftw_complex* out;
fftw_plan plan;
};
#endif

Fourier.cpp

#include "Fourier.h"
#define N 1024

Fourier::Fourier()
:nelements_in(N)
,nelements_out( N / 2 + 1)
{

in = (double*) fftw_malloc(sizeof(double) * nelements_in);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * nelements_out);
plan = fftw_plan_dft_r2c_1d(nelements_in, in, out, FFTW_MEASURE);
}

Fourier::~Fourier() {

fftw_destroy_plan(plan);
fftw_free(in);
fftw_free(out);
}

// copy the raw PCM data to the input buffer for FFTW.  we assume 1024 frames
void Fourier::copy(float* data, unsigned int nframes, int nchannels) {

for(int i = 0; i < nframes; ++i) {
in[i] = data[i * nchannels + 0]; // only using one channel
}
}

void Fourier::draw() {

fftw_execute(plan);

for(int i = 0; i < (N/2)+1; ++i) {
double mag = sqrtf((out[i][0] * out[i][0]) + (out[i][1] * out[i][1]));
int db = (10.0f * log10f(mag + 1.0);
int value = db * 100; // scaled the result a bit .. can be used as input for the audio reactive system
}
}

References

• NAT Types This is so exciting, in this article I dive into some of the different ways a NAT device translates addresses which is important for peer-to-peer connections.
• Building Cabinets In this post I dive into the design and construction of a cabinet with an interact LED strip. I also explain how I dynamically change the colors of the LEDs over TCP/UDP.
• Compiling GStreamer from source on Windows How to compile GStreamer on Windows from Source using Visual Studio 2019 and the meson build system.
• Debugging CMake Issues In this post I explain a process you can follow to debug issues with CMake by focusing on a specific target and making the output verbose.
• Dual Boot Arch Linux and Windows 10 How to install Arch Linux and Windows 10 Pro as dual boot. A step by step tutorial how to create bootable installers, partition and setup a dual boot menu.
• Mindset Updated Edition, Carol S. Dweck (Book Notes) Paragraphs I marked from the book "Mindset" from Carol S. Dweck.
• How to setup a self-hosted Unifi NVR with Arch Linux A step by step HOW-TO that explain show to setup a Unifi Video Controller with an NFS share with Arch Linux.
• Blender 2.8 How to use Transparent Textures Follow this node setup when you want to use an image with transparency as a "sticker".
• Compiling FFmpeg with X264 on Windows 10 using MSVC A couple of steps to compile FFmpeg on Windows using MSVC.
• Blender 2.8 OpenGL Buffer Exporter The following Blender script creates a [name].h and [name].cpp for the selected object and stores the positions, normals and UVs.
• Blender 2.8 Baking lightmaps Light maps are a cheap way to add a lot of realism to you static scenes and have been used forever.
• Blender 2.8 Tips and Tricks Use Environment Map only for reflections; create a floor plane for a Product Render, diffuse texture for roughness and more!
• Setting up a Bluetooth Headset on Arch Linux Learn how to setup a Sennheiser PXC 550 Bluetooth headset on Arch Linux.
• Compiling x264 on Windows with MSVC Compile the excellent x264 source on Windows using MSYS2 and MSVC.
• C/C++ Snippets Is a number divisible by four?
• Reading Chunks from a Buffer Some thoughts on reading bytes from a file; handy for reading NALs.
• Handy Bash Commands Bash scripts: removing white space, lowercase filenames, backup using tar, etc.
• Building a zero copy parser Simple solution to parse data in a pretty performant way. Used this for a RTSP protocol parser.
• Kalman Filter A very simple yet powerful filter which works great when you have to smooth noisy data. Used for the Nike Rise 2.0 project.
• Saving pixel data using libpng Do you have raw RGBA data that you want to save? Use this snippet to save it into a PNG file.
• Compile Apache, PHP and MySQL on Mac 10.10 Setup you own PHP, MySQL and Apache and with virtual document roots.
• Fast Pixel Transfers with Pixel Buffer Objects Using Pixel Buffer Objects (PBO) for fast asynchronous data transfers and OpenGL.
• High Resolution Timer function in C/C++ Wait...... wait.. fast high resolution timer funtions (Windows, Linux, Mac)
• Rendering text with Pango, Cairo and Freetype My never ending obsession with font rendering. A complex beast to do well. Use Pango and FreeType for the heavy lifting.
• Fast OpenGL blur shader Make things look blurry ... and fast using this OpenGL blur shader.
• Spherical Environment Mapping with OpenGL An old trick to get great lighting effects using Environment Maps and OpenGL.
• Using OpenSSL with memory BIOs OpenSSL is a great library with lots of abstractions. In this post I discuss how to break some of these abstractions and use your own memory buffers.
• Attributeless Vertex Shader with OpenGL A simple way to render a fullscreen quad without a vertex buffer with OpenGL.
• Circular Image Selector Some thoughts on a different way to select images from a huge collection in a compact UI.
• Decoding H264 and YUV420P playback Using libav to demux and playback with OpenGL.
• Fast Fourier Transform Analyse your audio using the Fastest Fourier Transform in the West.
• OpenGL Rim Shader Pretty glowy edges using a GLSL rim shader.
• Rendering The Depth Buffer Render the non-linear OpenGL Depth Buffer.
• Delaunay Triangulation Do you need to triangulate some shape: use the “Triangle” library.
• RapidXML RapidXML is a versatile and fast XML parser with a simple API. Check out these examples.
• Git Snippets Some simple GIT snippets; added here to remind myself.
• Basic Shading With OpenGL A couple of basic GLSL shaders with explanation.
• Open Source Libraries For Creative Coding Collection of great open source libraries for you creative programming projects.
• Bouncing particle effect Snippet that can be used to create a bouncy particle effect; basic, effective, simple but nice.
• OpenGL Instanced Rendering Want to render thousands and thousands of objects? Use OpenGL instanced rendering. The solution...the only solution.
• Mapping a texture on a disc Ever heard about projective interpolation related to texture mapping? Learn about this intertesting issue with OpenGL and texture mapping.
• Download HTML page using CURL When you want a quick solution to perform a HTTP(S) request CURL is always a quick an simple solution. Check out this example code.
• Height Field Simulation on GPU Although not a Navier-Stokes implementation ... still a very nice and enjoyable effect.
• OpenCV Optical Flow: when doing anything with tracking you've probably heard of it. See this simple example code using OpenCV and OpenGL.
• Some notes on OpenGL FBOs and Depth Testing, using different Attachment Points, a YUV420p shader, ...
• Math Meaning of the Dot Product in 3D graphics, calculating a perpendicular vector using Sam Hocevar's solution, orientation matrix and more.
• Gists to remember Some gists that I want to remember, often use, etc...
• Reverse SSH Do you want to login, into a remote PC but the remote PC is behind a firewall? Then use this simple reverse SSH trick which doesn't require changing your firewall rules.
• Working Set Having issues with your compiler? Or during linking? Check these common issues and their solutions. I also list several tools that you can use to get a some useful info.
• Consumer + Producer model with libuv Example of a common Multi Threaded Consumer/Producer Model using LibUV.
• Parsing binary data Learn about the basic of a binary protocol and how to create one easily yourself.
• C++ file operation snippets Reading a file into a string, vector, checking the file size, change to a position, etc. A collection of C++ file operation snippets.
• Importance of blur with image gradients Do you want to experiment with OpenGL and aligning Brush Strokes along Image Gradients? Then check out this post about the importance of blurring.
• Real-time oil painting with openGL Code snippet for fake "oil painting" effect with OpenGL using instanced rendering.
• x264 encoder Basic example on how to use libx264 to encode image data using libav
• Generative helix with openGL Screenshots of a project I worked on with that generates a DNA helix.
• Mini test with vector field Screenshots while experimenting with a vector field; nothing much to see here.
• Protractor gesture recognizer Testing the amazing One Dollar \$1 gesture recognizer. The simplest and very good gesture recognizer.
• Hair simulation Example code that implements the "Fast Simulation of Inextensible Hair and Fur" paper from M. Müller, T.Y. Kim and N.Chentanez.
• Some glitch screenshots Glitch screenshots.
• Working on video installation Screenshots of some experiments of a video installation.
• Generative meshes I enjoy creating physics based simulations and render them on high res. Here are some experiments I did a time ago.
• Converting video/audio using avconv Examples that show you how to use avconv to manipulate video and audio files.
• Auto start terminal app on mac Automatically start you application whe Mac boots and make sure that it restarts your app when it exists. Handy for interactive installations.
• Export blender object to simple file format Export the selected object in Blender into a .h and .cpp file that prepresents the buffer.