obiwanjacobi / vst.net

Virtual Studio Technology (VST) for .NET. Plugins and Host applications.
https://obiwanjacobi.github.io/vst.net/index.html
GNU Lesser General Public License v2.1
420 stars 52 forks source link

Less naive methods for copying audio buffers #68

Open MWstudios opened 7 months ago

MWstudios commented 7 months ago

I've noticed that VstPluginAudioProcessor and VstPluginAudioPrecisionProcessor are copying buffer values one by one. Since the pointers are already exposed, I suggest using Buffer.MemoryCopy():

using System;

// ...

unsafe
{
    float* inputBuffer = this.Buffer;
    float* outputBuffer = ((IDirectBufferAccess32)destination).Buffer;
    Buffer.MemoryCopy(inputBuffer, outputBuffer, this.SampleCount * sizeof(float), this.SampleCount * sizeof(float));
}

Or SIMD, like so:

using System.Runtime.Intristics;
using System.Runtime.Intristics.X86;

// ...

unsafe
{
    float* inputBuffer = this.Buffer;
    float* outputBuffer = ((IDirectBufferAccess32)destination).Buffer;

    int i = 0;
    if (Avx.IsSupported)
         for (; i + 8 <= this.SampleCount; i += 8)
              Avx.Store(outputBuffer + i, Avx.LoadVector256(inputBuffer + i));
    if (Sse2.IsSupported)
         for (; i + 4 <= this.SampleCount; i += 4)
              Sse2.Store(outputBuffer + i, Sse2.LoadVector128(inputBuffer + i));
    for (; i < this.SampleCount; i++)
    {
        outputBuffer[i] = inputBuffer[i];
    }
}

And likewise for doubles, just divide the jumps by 2 (though a simple memory copy would be more useful in this case).