MidiMessage & lock free?


#1

I am just looking into the MidiMessage class, because I want to program an arpeggiator with JUCE.

I realized, that MidiMessage is using malloc internally. As far as I know, malloc is not lock free.
So you are not allowed to create or copy a MidiMessage on the audio thread.
Am I correct here?

How do you guys deal with that? Do you create a separate Midi thread, which is separated from the audio thread? What do you think is the best way?


#2

MidiMessage preallocates 8 bytes on a 64 bit system, see below, from juce_MidiMessage.h. The maximum length of standard MIDI messages is 3 bytes.

union PackedData
{
    uint8* allocatedData;
    uint8 asBytes[sizeof (uint8*)];
};

It only allocates dynamically for larger messages (Sysex). Of course, you shouldn’t do that on the audio thread.


#3

Ah, I see.
Did not realize that.
So normal messages are OK, Sysex is not OK?
Thanks for the clarification.


#4

I would be very surprised this is correct. As far as I understand all incoming midi messages are fwd into the processor hence in the audio thread. Those may include sysex. How and where (on which thread) are those created then? (Then again, by all means surprise me!)


#5

I didn’t say that it doesn’t happen in practice, I only said that dynamic allocation on the audio thread is to be avoided.

For instance, if you look at MidiBuffer::Iterator::getNextEvent(), you can see that it will allocate for large data chunks.


#6

In the question it was asked to create an arpeggiator, which means creating simple midi messages inside the processBlock. And I would agree this is safe to do with simple noteOn, or controller messages.

However you are correct, as far as I can see in the code, if the midi device were to send a chunk of sysex data, this would in the JUCE wrapper trigger a MidiMessage::createSysex(), which involves a HeapBlock.

leads to:

which is:

This is a use case that might be worth looking into. Maybe there could be a flag to skip SysEx, if it is sent to an AudioProcessor for realtime consumption, but I am not expert enough in midi and all the use cases to make a call on that.


#7

this is an interesting point and very useful to know!