MidiInput queued MIDI message when opening device

I have an application were I use the MidiInput class. When I open a MIDI input, my application is receiving (a lot of) MIDI messages which are received by the opened MIDI input, before the MidiInput::openDevice was actually called. Is there a way to clear all Midi messages inside the MidiInput buffer, before calling MidiInput::Start? A function like MidiOutput::clearAllPendingMessages would be nice.

What platform are you on? Can you post some code showing how your are opening the MIDI device?

I’m using macOS 10.14.6, JUCE V5.4.4. The MidiIn::handleInComingMessage is called immediately after mpMidiInput->Start() is called (if there are queued messages). At that moment I’m receiving Midi Messages which are received by my MIDI interface before mpMidiInput->Start is called. As you can see below, I’m using a workaround to set the ‘mEnabled’ variable after 100 milliseconds, to ignore these messages. Of course, this is a bad solution.

class MidiIn : public MidiInputCallback
{
  private:
    std::unique_ptr<MidiInput> mpMidiInput;
    std::thread mDelayedEnableThread;
    std::atomic<bool> mEnabled;

  public:
    bool Init(std::string Identifier);
    void DeInit();

    void EnableDelayed();
    virtual void handleIncomingMidiMessage(MidiInput* pSource, 
    const MidiMessage& rMessage) override;
};

bool MidiIn::Init(std::string Identifier)
{
  DeInit();

  mpMidiInput = MidiInput::openDevice(Identifier.c_str(), this);
  if(mpMidiInput != nullptr)
  {
     mpMidiInput->start();
     if(mDelayedEnableThread.joinable())
     {
       mDelayedEnableThread.join();
     }
     mDelayedEnableThread = std::thread(&MidiIn::EnableDelayed, this);
     return true;
  }
  else
  {
    return false;
  }
}

void MidiIn::DeInit()
{
  mpMidiInput.release();
  mEnabled = false;
}

void MidiIn::EnableDelayed()
{
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
  mEnabled = true;
}

void MidiIn::handleIncomingMidiMessage(MidiInput* pSource, const MidiMessage& rMessage)
{
  if (pSource == mpMidiInput.get() && mEnabled)
  {
    //...
  }
}

I’m not sure there’s much we can do about that. If the OS is buffering MIDI messages in a queue and sending them on a separate thread then there might be a slight delay in receiving the messages so you might get messages which were sent before the device was started.

However, instead of ignoring the messages for a set amount of time can you instead inspect the timestamp of the message and discard those which were sent before you started the device? As per the docs of handleIncomingMidiMessage() the timestamp should be equivalent to (Time::getMillisecondCounter() / 1000.0).