I have the following convolution algorithm:
public class Spatializer : MonoBehaviour
{
const int MAX_TAPS = 128;
static float[,,] IRs = null;
// http://stackoverflow.com/questions/7237907/1d-fast-convolution-without-fft
public static float[] Spatialize( float[] srcMono, int toneme, bool loop )
{
if( IRs == null )
LoadIRs( );
int inSamps = srcMono.Length;
int outSamps = inSamps + ( loop ? 0 : MAX_TAPS-1 );
float [] L = new float[ outSamps ];
float [] R = new float[ outSamps ];
int i,j,k;
float x_i;
for ( i = 0; i < inSamps; i++)
{
x_i = srcMono[ i ];
for ( j = 0; j < MAX_TAPS; j++)
{
k = i + j;
if( k >= inSamps )
if( loop )
k %= inSamps;
L[ k ] += x_i * IRs[ toneme, 0, j ];
R[ k ] += x_i * IRs[ toneme, 1, j ];
}
}
float[] outputInterleaved = new float[ 2 * outSamps ];
int outPtr = 0;
for ( i = 0; i < outSamps; i++)
{
outputInterleaved[ outPtr++ ] = L[ i ];
outputInterleaved[ outPtr++ ] = R[ i ];
}
return outputInterleaved;
}
static void LoadIRs( )
{
IRs = new float[ 12, 2, MAX_TAPS ];
// !!! get wav from file
float [] wav = new float[ ... ];
float step = ...;
// de-interleave and resample
for( int toneme = 0; toneme < 12; toneme++ )
{
for( int tap=0; tap < MAX_TAPS; tap++ )
{
int n = (int)Mathf.RoundToInt( (float)tap * step );
IRs[ toneme, 0, tap ] = wav[ 2 * n ];
IRs[ toneme, 1, tap ] = wav[ 2 * n + 1 ];
}
}
}
}
I suspect it would be much faster if I just had to access a 1D array within the convolution loop, as it stands to reason that accessing an element from a one-dimensional array is going to involve fewer cycles than accessing an element from a three-dimensional array.
// extract array we want OUTSIDE loop
float [] IR_L = IRs[ toneme, 0 ]; // BAD SYNTAX <-- how to do this?
float [] IR_R = IRs[ toneme, 1 ]; // BAD SYNTAX <-- how to do this?
for ( i = 0; i < inSamps; i++)
{
x_i = srcMono[ i ];
for ( j = 0; j < MAX_TAPS; j++)
{
k = i + j;
if( k >= inSamps )
if( loop )
k %= inSamps;
L[ k ] += x_i * IR_L[ j ];
R[ k ] += x_i * IR_R[ j ];
}
}
The above is pseudocode, as I don't know how to go about implementing it, or even whether it is possible.
So my question is: can I extract
float [] IR_L = IRs[ toneme, 0 ]; // BAD SYNTAX <-- how to do this?
so that instead of writing
IRs[ toneme, 0, j ]
within the inner loop, I could just write
IR_L[ j ]