How to code a circular buffer in an external.

enda.bates@gmail.com's icon

Hey everybody, thanks for the help with my float inlet yesterday!
I am now trying to add a circular buffer to my external. The buffer will need to hold something in the order of 2048 samples.
Now Im thinking I need to create this buffer outside the perform routine as this routine only works in chunks of samples as per the Signal Vector size, right? So where do I create the array to store these samples, in the structure defn or in the new instance routine, or where?
As far as I understand it the array/buffer will need to outside the perform routine so it can store samples from previous Signal Vectors. So i guess this needs to be a global variable that can be accessed from the perform routine, but i guess Im not sure where is the best place to do this code in an MSP external.
Your help is greatly appreciated,
cheers,
enda

Mark Pauley's icon

I think you should allocate the mem in your dsp function.

Put a float* into your main object, like so:

#define kNumSamplesInCircularBuffer 2048;

typedef struct _MyObjName {
    t_pxobject xObj; // requred for msp
    int curReadIndex;
    int curWriteIndex;

    float* circularBuffer;
} MyObjName;

...

and then malloc a buffer and give it to your object like so:

void MyObjName_dsp(MyObjName* inObj, t_signal **sp, short* count) {

    //allocate the buffer
    circularBuffer = (float*)malloc(sizeof(float) *
kNumSamplesInCircularBuffer);

    //initialize the read and write index
    curReadIndex = 0;
    curWriteIndex = 0;

    //initialize the buffer with zeros
    bzero(circularBuffer, sizeof(float) * kNumSamplesInCircularBuffer);
}

...

and then free the buffer when you're done.

void MyObjName_free(MyObjName* inObj) {
    dsp_free((t_pxobject*) xObj);

    free(circularBuffer);

    //for paranoia's sake I always zero out my structs after I free any
malloc'd members
    bzero(inObj, sizeof(MyObjName));
}

then inside of your process function, just make sure you don't access
outside of the bounds of your buffer.

_Mark