JUCE 9.0.3: Windows WinMM MIDI input loses SysEx

I recently updated to JUCE 9.0.3 to test the Windows MIDI Service backend against the latest Microsoft release. While that works well, I ran into an issue when using the legacy WinMM backend in that release. When stress testing SysEx messages, 9.0.3 seems to lose information when the CPU is under heavy load. This doesn’t seem to happen as much with 9.0.2, and It doesn’t happen on macOS, so I believe it traces back to recent changes in juce_MIDI_windows.cpp.

Here are the relevant details:

  • JUCE gives WinMM 32 input buffers of 256 bytes.
  • When WinMM fills a buffer, it marks it done (MHDR_DONE), but it appears MHDR_DONE is set before the callback is called. (Source)
  • Since b09136c40, blockQueueThread queues every header whose done flag is set. Hypothesis: That includes headers whose callback hasn’t run yet, because WinMM sets the flag before it calls the callback.
  • MidiHeader::write() zeroes dwBytesRecorded when queuing. When the callback then runs, the buffer looks empty and handleSysEx skips it.
  • Those 256 bytes are lost, so the SysEx arrives broken and is dropped. In a separate WinMM-level test, every lost message was short by exactly one buffer (256 bytes).
  • 9.0.2 re-queued inside the callback, after reading the buffer, so it couldn’t lose data this way.

The motivation for the b09136c40 (not calling midiInAddBuffer from the callback) makes sense. The fix would be to re-queue only buffers the callback has already consumed, for example by having the callback hand each finished header to the thread, instead of the thread scanning for MHDR_DONE.

I attached a small program that can reproduce the issue in my environment. I ran this on Windows 11 with a 16-core x64 chip. Here are the results of running it against the last two releases. I occasionally see 9.0.2 losing some data under heavy load, but 9.0.3 happens much more frequently.

$ ./build902/WinmmSysexRepro_artefacts/Release/WinmmSysexRepro.exe
JUCE v9.0.2: 300 SysEx of 4096 bytes, 'Default App Loopback (A)' -> 'Default App Loopback (B)', 14 busy threads
SysEx received: 300; arrived intact: 300 of 300   LOST: 0
$ ./build903/WinmmSysexRepro_artefacts/Release/WinmmSysexRepro.exe
JUCE v9.0.3: 300 SysEx of 4096 bytes, 'Default App Loopback (A)' -> 'Default App Loopback (B)', 14 busy threads
SysEx received: 136; arrived intact: 136 of 300   LOST: 164

Below is the source code for the stress test. It requires that the “Default App Loopback (A)” and “Default App Loopback (B)” are available.

main.cpp

// Reproduces lost SysEx with JUCE 9.0.3's WinMM MIDI input
//
// Sends numbered SysEx messages out of a MIDI port that loops back to a MIDI input, while busy threads keep all but two
// CPU cores loaded, and counts how many arrive intact. Any loopback works: by default the Windows MIDI Services
// "Default App Loopback (A)" -> "(B)" pair, or e.g. a loopMIDI port given as both --out and --in.
//
//   WinmmSysexRepro [--out <name>] [--in <name>] [--count <n>] [--size <bytes>] [--load <threads>]
//
// Typical result (14 of 16 hardware threads busy): 
// * JUCE 9.0.3 loses 15-240 of 300 every run. 
// * JUCE 9.0.2 loses almost none. 
// * Without load 9.0.3 rarely loses any. 
// * With every core busy even 9.0.2 occasionally does. 
// adjust --load if a machine behaves differently.

#include <juce_audio_devices/juce_audio_devices.h>
#include <algorithm>
#include <atomic>
#include <thread>
#include <vector>

namespace
{

// The bytes between F0 and F7 of message `seq`: 7D <seq hi> <seq lo> <pattern>.
std::vector<juce::uint8> payload(int seq, int size)
{
    std::vector<juce::uint8> p((size_t) size - 2);
    p[0] = 0x7D;
    p[1] = (juce::uint8) ((seq >> 7) & 0x7F);
    p[2] = (juce::uint8) (seq & 0x7F);
    for (size_t i = 3; i < p.size(); ++i)
        p[i] = (juce::uint8) ((seq + (int) i) & 0x7F);
    return p;
}

struct Receiver : juce::MidiInputCallback
{
    Receiver(int countIn, int sizeIn) : count(countIn), size(sizeIn), intact((size_t) countIn) {}

    void handleIncomingMidiMessage(juce::MidiInput*, const juce::MidiMessage& m) override
    {
        if (! m.isSysEx())
            return;
        ++received;
        const auto* d = m.getSysExData();
        const auto n = m.getSysExDataSize();
        const int seq = n >= 3 ? (d[1] << 7) | d[2] : -1;
        if (seq < 0 || seq >= count)
            return;
        const auto want = payload(seq, size);
        if (n == (int) want.size() && std::equal(want.begin(), want.end(), d))
            intact[(size_t) seq] = true;
    }

    const int count, size;
    std::vector<std::atomic<bool>> intact;
    std::atomic<int> received { 0 };
};

juce::MidiDeviceInfo find(const juce::Array<juce::MidiDeviceInfo>& list, const juce::String& name)
{
    for (const auto& d : list)
        if (d.name.containsIgnoreCase(name))
            return d;
    return {};
}

} // namespace

int main(int argc, char* argv[])
{
    juce::ScopedJuceInitialiser_GUI juceInit;
    juce::String outName = "Loopback (A)", inName = "Loopback (B)";
    int count = 300, size = 4096, loadThreads = std::max(1, (int) std::thread::hardware_concurrency() - 2);
    for (int i = 1; i + 1 < argc; i += 2)
    {
        const juce::String a(argv[i]), v(argv[i + 1]);
        if (a == "--out") outName = v;
        else if (a == "--in") inName = v;
        else if (a == "--count") count = v.getIntValue();
        else if (a == "--size") size = v.getIntValue();
        else if (a == "--load") loadThreads = v.getIntValue();
    }

    const auto outInfo = find(juce::MidiOutput::getAvailableDevices(), outName);
    const auto inInfo = find(juce::MidiInput::getAvailableDevices(), inName);
    if (outInfo.identifier.isEmpty() || inInfo.identifier.isEmpty())
    {
        std::printf("MIDI port not found: '%s' or '%s'\n", outName.toRawUTF8(), inName.toRawUTF8());
        return 1;
    }

    Receiver rx(count, size);
    auto in = juce::MidiInput::openDevice(inInfo.identifier, &rx);
    auto out = juce::MidiOutput::openDevice(outInfo.identifier);
    if (in == nullptr || out == nullptr)
    {
        std::printf("could not open the ports\n");
        return 1;
    }
    in->start();
    juce::Thread::sleep(200);

    std::printf("%s: %d SysEx of %d bytes, '%s' -> '%s', %d busy threads\n",
                juce::SystemStats::getJUCEVersion().toRawUTF8(), count, size, outInfo.name.toRawUTF8(),
                inInfo.name.toRawUTF8(), loadThreads);

    // Busy threads keep the CPU loaded, as a running audio app would.
    std::atomic<bool> stopLoad { false };
    std::vector<std::thread> load;
    for (int i = 0; i < loadThreads; ++i)
        load.emplace_back([&stopLoad] { while (! stopLoad) {} });

    for (int seq = 0; seq < count; ++seq)
    {
        const auto p = payload(seq, size);
        out->sendMessageNow(juce::MidiMessage::createSysExMessage(p.data(), (int) p.size()));
    }

    // Wait until nothing more arrives.
    for (int last = -1; last != rx.received.load();)
    {
        last = rx.received.load();
        juce::Thread::sleep(1000);
    }
    stopLoad = true;
    for (auto& t : load)
        t.join();
    in->stop();

    int intact = 0;
    for (auto& ok : rx.intact)
        intact += ok ? 1 : 0;
    std::printf("SysEx received: %d; arrived intact: %d of %d   LOST: %d\n", rx.received.load(), intact, count,
                count - intact);
    return intact == count ? 0 : 3;
}

Here’s a cmake file for building it. I used -DJUCE_DIR=<path to 9.0.2 or 9.0.3 download> to build against the different versions of JUCE:

CMakeLists.txt

cmake_minimum_required(VERSION 3.22)
project(WinmmSysexRepro VERSION 1.0.0 LANGUAGES C CXX)

# cmake -B build -DJUCE_DIR=<path to JUCE>   (WinMM backend: no Windows MIDI Services flag)
set(JUCE_DIR "" CACHE PATH "Path to JUCE")
add_subdirectory(${JUCE_DIR} juce)

juce_add_console_app(WinmmSysexRepro PRODUCT_NAME "WinmmSysexRepro")
target_sources(WinmmSysexRepro PRIVATE main.cpp)
target_compile_definitions(WinmmSysexRepro PRIVATE JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0)
target_link_libraries(WinmmSysexRepro PRIVATE
    juce::juce_audio_devices
    juce::juce_recommended_config_flags
    juce::juce_recommended_warning_flags)

Example build and execute:

cmake -B build902 -DJUCE_DIR=C:/JUCE_9_0_2
cmake --build build902 --config Release
./build902/WinmmSysexRepro_artefacts/Release/WinmmSysexRepro.exe

There have been a few recent changes to MIDI on the develop branch. Is the behaviour the same there?

Seems so. I just checked out the latest develop and ran the same test built against that:

$ git -C C:/work/JUCE-develop rev-parse HEAD
4efc93690d60a1adc013940ff3637565378523ce
$ ./build-4efc93690/WinmmSysexRepro_artefacts/Release/WinmmSysexRepro.exe
JUCE v9.0.3: 300 SysEx of 4096 bytes, 'Default App Loopback (A)' -> 'Default App Loopback (B)', 14 busy threads
SysEx received: 24; arrived intact: 24 of 300   LOST: 276

Quick follow-up on this. (I’ve been unable to sign in to the forums from this page, but eventually tried a different page and then it finally worked)

Yes, MHDR_DONE is set before invoking the callback, because that’s required per documented WinMM driver specifications.

There has also been follow-up on this here:

Pete
Microsoft

Thanks everyone for the additional info, and especially thanks for the test harness that made it easy to reproduce the problem.

We’ve pushed a fix reverting the behaviour that re-queued blocks from a background thread. We now queue them from the input callback, as before.