// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later // MIDI input pieces with no platform types, ported from the Android app: // - MidiByteParser (input/MidiByteParser.kt): raw bytes -> whole messages, with // running status, split messages, real-time bytes anywhere, SysEx skipped. // - MidiSoundModule (playback/MidiSoundModule.kt): notes per source -> a NoteSink, // All Notes Off / All Sound Off, release of a vanished source's held notes. // Tested by core/tests/midi_test.cpp. #pragma once #include #include #include #include #include #include namespace sizzle::midi { /** One parser per stream (running status is per stream). Not thread-safe. */ class MidiByteParser { public: /** A complete channel message: status 0x80..0xEF and its data bytes (0 when absent). */ using Channel = std::function; /** A System Real-Time byte: clock 0xF8, Start 0xFA, Continue 0xFB, Stop 0xFC, ... */ using Realtime = std::function; MidiByteParser(Channel onChannel, Realtime onRealtime) : onChannel(std::move(onChannel)), onRealtime(std::move(onRealtime)) {} void feed(const uint8_t *data, size_t count) { for (size_t i = 0; i < count; ++i) byte(data[i]); } private: void byte(int b) { if (b >= 0xF8) { onRealtime(b); return; } // never disturbs running status if (b == 0xF0) { inSysex = true; running = 0; return; } if (b == 0xF7) { inSysex = false; return; } if (b >= 0xF1) { inSysex = false; running = 0; need = 0; return; } // system common if (b >= 0x80) { inSysex = false; running = b; got = 0; need = ((b & 0xF0) == 0xC0 || (b & 0xF0) == 0xD0) ? 1 : 2; return; } if (inSysex || running == 0) return; // stray data byte if (got == 0) d1 = b; if (++got >= need) { onChannel(running, d1, need == 2 ? b : 0); got = 0; // running status: the next data byte starts a new message } } Channel onChannel; Realtime onRealtime; int running = 0, need = 0, got = 0, d1 = 0; bool inSysex = false; }; /** Where the sound module plays notes (channel 1..16). */ class NoteSink { public: virtual ~NoteSink() = default; virtual void busNoteOn(int channel, int note, int velocity) = 0; virtual void busNoteOff(int channel, int note) = 0; }; /** * The headless multitimbral sound module: Note On/Off on channel N play/release the * mixer tracks listening on N; CC 123 / 120 release that channel's held notes from * every source; notes are tracked per source so a source that goes away has its * notes released. [listener] mirrors every note played or released (for the UI). * Thread-safe (one lock; each MIDI stream may deliver on its own thread). */ class MidiSoundModule { public: using Listener = std::function; explicit MidiSoundModule(NoteSink &sink) : sink(sink) {} Listener listener; void sourceConnected(intptr_t source) { std::lock_guard g(lock); held[source]; } void sourceDisconnected(intptr_t source) { std::lock_guard g(lock); auto it = held.find(source); if (it == held.end()) return; for (int k : it->second) release(k); held.erase(it); } /** True when consumed (notes, all-notes-off); other messages are the caller's. */ bool onChannelMessage(intptr_t source, int status, int d1, int d2) { const int channel = (status & 0x0F) + 1, note = d1 & 0x7F; switch (status & 0xF0) { case 0x90: if (d2 > 0) noteOn(source, channel, note, d2); else noteOff(source, channel, note); return true; case 0x80: noteOff(source, channel, note); return true; case 0xB0: if (d1 == 123 || d1 == 120) { channelOff(channel); return true; } return false; default: return false; } } /** Release everything any source holds (panic, shutdown). */ void releaseAll() { std::lock_guard g(lock); for (auto &[src, keys] : held) { for (int k : keys) release(k); keys.clear(); } } /** Held (channel, note) pairs of [source], for tests. */ std::set> heldNotes(intptr_t source) { std::lock_guard g(lock); std::set> out; auto it = held.find(source); if (it != held.end()) for (int k : it->second) out.insert({k / 128 + 1, k % 128}); return out; } int sourceCount() { std::lock_guard g(lock); return (int)held.size(); } private: void noteOn(intptr_t source, int channel, int note, int velocity) { std::lock_guard g(lock); held[source].insert(key(channel, note)); sink.busNoteOn(channel, note, velocity); if (listener) listener(true, channel, note, velocity); } // Every Note Off reaches the engine, even for a note we don't think is held: // a stuck voice is worse than a redundant release. void noteOff(intptr_t source, int channel, int note) { std::lock_guard g(lock); auto it = held.find(source); if (it != held.end()) it->second.erase(key(channel, note)); sink.busNoteOff(channel, note); if (listener) listener(false, channel, note, 0); } void channelOff(int channel) { std::lock_guard g(lock); for (auto &[src, keys] : held) { for (auto it = keys.begin(); it != keys.end();) { if (*it / 128 + 1 == channel) { release(*it); it = keys.erase(it); } else ++it; } } } void release(int k) { sink.busNoteOff(k / 128 + 1, k % 128); if (listener) listener(false, k / 128 + 1, k % 128, 0); } static int key(int channel, int note) { return (channel - 1) * 128 + note; } NoteSink &sink; std::mutex lock; std::map> held; }; /** MidiClock.kt's receive side: Start/Continue/Stop and a tempo from the pulse * rate, averaged over a quarter note (24 pulses). [nowNs] is a monotonic clock. */ class ClockFollower { public: std::function onTransport; // Start/Continue = true, Stop = false std::function onTempo; void realtime(int status, int64_t nowNs) { if (status == 0xFA || status == 0xFB) { reset(); if (onTransport) onTransport(true); } else if (status == 0xFC) { if (onTransport) onTransport(false); } else if (status == 0xF8) pulse(nowNs); } private: void reset() { lastNs = 0; accum = 0; count = 0; } void pulse(int64_t now) { if (lastNs != 0) { accum += (double)(now - lastNs); if (++count >= 24) { const float bpm = (float)(60'000'000'000.0 / (accum / count * 24.0)); if (bpm >= 20.f && bpm <= 300.f && onTempo) onTempo(bpm); accum = 0; count = 0; } } lastNs = now; } int64_t lastNs = 0; double accum = 0; int count = 0; }; } // namespace sizzle::midi