Reading midi messages from ProcessBlock

I have a use case where I need a function to read midi messages from the processBlock midi buffer. However, this function cannot be called within the processBlock .

What is the best way to achieve this?

Thanks in advance.
Tone

for(auto it : midiMessages)
{
    auto msg = it.getMessage();
    // stuff that happens  with each msg
}

What do you mean by that?

Hey @xenakios,
I’m subclassing a Reaper PCMsource and I would like to populate a midi_realtime_struct_t in the GetSamples function.
Or is there another way to access a midi input from Reaper?

I am not sure what this has to do with Juce, then? What are you actually trying to do?

It’s a juce audio plugin that implements Reaper functions. I need to get access to midi message occurring in the processBlock call.

It occurs to me that I may be asking this question the wrong way.
If I create a MidiBuffer member object, how can I assure thread safety if multiple callers are reading from it and the ProcessBlock is writing to it?

A crude way is to protect accesses to the MidiBuffer with a CriticalSection, but I am sure people here will jump in and say you shouldn’t do it that way. :wink:

How would that work? Wouldn’t in be possible to miss messages if the lock wasn’t acquired?

You’d use the lock so that it always locks, not the tryEnter method.

And yes, I am completely aware this isn’t the right way to do this, but anyone wanting to propose an alternative is welcome to do so, with some example code.

if you’re going the less than perfect CriticalSection route, you could minimize time the lock is held by locking it just long enough to swap MidiBuffers for double buffering.

1 Like

Seems that a juce::MidiMessageCollector fits my needs. I don’t know what pitfalls I may inherit by using it yet though.

That internally also uses a CriticalSection for the thread safety, which may or may not be a problem. I guess it generally speaking isn’t since it’s an old class and has remained like it is for a long time. A proper solution would use something like a lock free queue to pass the messages between the threads.