// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later #import "SizzleMidi.h" #import "SizzleSession+Internal.h" #import #include #include #include #include #include #include #include #include "sizzle/Midi.hpp" // The MIDIPacketList API: deprecated since iOS 14 but available, and the only one // on both sides of the deployment target (15) that every source speaks. #pragma clang diagnostic ignored "-Wdeprecated-declarations" using namespace sizzle; @interface SizzleMidiSource () - (instancetype)initWithKey:(NSString *)key name:(NSString *)name enabled:(BOOL)enabled connected:(BOOL)connected; @end @implementation SizzleMidiSource - (instancetype)initWithKey:(NSString *)key name:(NSString *)name enabled:(BOOL)enabled connected:(BOOL)connected { if ((self = [super init])) { _key = key; _name = name; _enabled = enabled; _connected = connected; } return self; } @end namespace { int64_t nowNs() { static mach_timebase_info_data_t tb = [] { mach_timebase_info_data_t t; mach_timebase_info(&t); return t; }(); return (int64_t)(mach_absolute_time() * tb.numer / tb.denom); } /// Notes go straight to the audio thread's MIDI queue (the module's lock /// serialises the pushes from different MIDI threads). struct SessionSink : midi::NoteSink { __unsafe_unretained SizzleSession *session = nil; void busNoteOn(int ch, int note, int vel) override { [session midiNoteOn:note velocity:vel channel:ch]; } void busNoteOff(int ch, int note) override { [session midiNoteOff:note channel:ch]; } }; /// One source we may listen to. Never freed: CoreMIDI may still be delivering on /// its thread right after a disconnect, so the connection's refCon stays valid. struct Conn { intptr_t id = 0; MIDIUniqueID uid = 0; MIDIEndpointRef ep = 0; bool connected = false; NSString *key = @"", *name = @""; std::unique_ptr parser; }; struct State { SessionSink sink; midi::MidiSoundModule module{sink}; midi::ClockFollower follower; std::mutex followerLock; std::atomic sendEnabled{false}, receiveEnabled{false}, soundModule{false}, running{false}; engine::Engine *engine = nullptr; const model::Project *project = nullptr; MIDIClientRef client = 0; MIDIPortRef inPort = 0, outPort = 0; MIDIEndpointRef virtualIn = 0, virtualOut = 0; std::vector> conns; // main thread Conn virtualConn; std::mutex destLock; std::vector dests; std::thread sender; void feed(Conn *c, const MIDIPacketList *pl) { const MIDIPacket *p = &pl->packet[0]; for (UInt32 i = 0; i < pl->numPackets; ++i) { c->parser->feed(p->data, p->length); p = MIDIPacketNext(p); } } void send(const uint8_t *bytes, int n) { Byte buf[64]; MIDIPacketList *pl = (MIDIPacketList *)buf; MIDIPacket *pk = MIDIPacketListInit(pl); pk = MIDIPacketListAdd(pl, sizeof buf, pk, 0, n, bytes); if (!pk) return; { std::lock_guard g(destLock); for (MIDIEndpointRef d : dests) MIDISend(outPort, d, pl); } if (virtualOut) MIDIReceived(virtualOut, pl); } /// MidiClock.sendLoop: clock at 24 PPQN while playing, Start/Stop on the edges, /// and the engine's sequenced notes. Polls every 0.5 ms while sending. void sendLoop() { bool lastPlaying = false; int64_t next = 0; const uint8_t clock = 0xF8, start = 0xFA, stop = 0xFC; while (running.load()) { if (sendEnabled.load()) { const bool playing = engine->isPlaying(); const int64_t now = nowNs(); if (playing && !lastPlaying) { send(&start, 1); next = now; lastPlaying = true; } else if (!playing && lastPlaying) { send(&stop, 1); lastPlaying = false; } if (playing && now >= next) { send(&clock, 1); const float bpm = std::clamp(project->tempoBpm, 20.f, 300.f); const int64_t interval = (int64_t)(60'000'000'000.0 / (bpm * 24.0)); next += interval; if (next < now) next = now + interval; } for (int guard = 0, m; guard < 256 && (m = engine->pollMidiOut()) >= 0; ++guard) { const uint8_t msg[3] = {(uint8_t)((m >> 16) & 0xFF), (uint8_t)((m >> 8) & 0x7F), (uint8_t)(m & 0x7F)}; send(msg, 3); } } else if (lastPlaying) { send(&stop, 1); lastPlaying = false; } std::this_thread::sleep_for(std::chrono::microseconds(sendEnabled.load() ? 500 : 10'000)); } if (lastPlaying) send(&stop, 1); } }; State *gState = nullptr; NSString *stringProp(MIDIObjectRef o, CFStringRef prop) { CFStringRef s = nullptr; if (MIDIObjectGetStringProperty(o, prop, &s) != noErr || !s) return @""; return (__bridge_transfer NSString *)s; } } // namespace @implementation SizzleMidi { NSMutableSet *_disabled; NSArray *_sources; } + (SizzleMidi *)shared { static SizzleMidi *m; static dispatch_once_t once; dispatch_once(&once, ^{ m = [SizzleMidi new]; }); return m; } - (instancetype)init { if ((self = [super init])) { _disabled = [NSMutableSet set]; _sources = @[]; } return self; } - (NSArray *)sources { return _sources; } /// A parser for [conn] whose messages go to the module, the CC handler and the clock. static std::unique_ptr makeParser(State *st, intptr_t id) { return std::make_unique( [st, id](int status, int d1, int d2) { if (st->module.onChannelMessage(id, status, d1, d2) || (status & 0xF0) != 0xB0) return; dispatch_async(dispatch_get_main_queue(), ^{ if (auto cb = SizzleMidi.shared.onControl) cb(d1, d2); }); }, [st](int status) { std::lock_guard g(st->followerLock); st->follower.realtime(status, nowNs()); }); } - (void)startWithDisabledKeys:(NSSet *)disabled { if (gState) return; [_disabled setSet:disabled]; SizzleSession *session = SizzleSession.shared; State *st = new State(); gState = st; st->sink.session = session; st->engine = [session enginePointer]; st->project = [session projectPointer]; st->engine->setMidiOutEnabled(_sendClock); st->sendEnabled = _sendClock; st->receiveEnabled = _receiveClock; st->soundModule = _soundModule; st->module.listener = [](bool on, int ch, int note, int vel) { dispatch_async(dispatch_get_main_queue(), ^{ if (auto cb = SizzleMidi.shared.onNote) cb(on, ch, note, vel); }); }; // Start/Stop always reach the engine (an armed recording follows another app's // transport); the song itself follows only with "receive clock" on and outside // sound-module mode. Tempo follows whenever receiving. st->follower.onTransport = [st](bool start) { dispatch_async(dispatch_get_main_queue(), ^{ if (start) st->engine->externalClockStart(); else st->engine->externalClockStop(); if (!st->receiveEnabled.load() || st->soundModule.load()) return; SizzleSession *s = SizzleSession.shared; if (start) { if (!s.isPlaying) [s play]; } else [s pause]; }); }; st->follower.onTempo = [st](float bpm) { if (!st->receiveEnabled.load()) return; dispatch_async(dispatch_get_main_queue(), ^{ SizzleSession.shared.tempo = bpm; if (auto cb = SizzleMidi.shared.onTempoFollowed) cb(bpm); }); }; __weak SizzleMidi *weakSelf = self; OSStatus err = MIDIClientCreateWithBlock(CFSTR("Sizzle"), &st->client, ^(const MIDINotification *n) { if (n->messageID != kMIDIMsgSetupChanged) return; dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf rescan]; }); }); if (err != noErr) { NSLog(@"Sizzle MIDI: no client (%d)", (int)err); return; } MIDIInputPortCreateWithBlock(st->client, CFSTR("Sizzle In"), &st->inPort, ^(const MIDIPacketList *pl, void *ref) { st->feed((Conn *)ref, pl); }); MIDIOutputPortCreate(st->client, CFSTR("Sizzle Out"), &st->outPort); // Sizzle as a destination other apps can pick, and as a source of its clock/notes. st->virtualConn.id = -1; st->virtualConn.parser = makeParser(st, -1); Conn *vc = &st->virtualConn; if (MIDIDestinationCreateWithBlock(st->client, CFSTR("Sizzle"), &st->virtualIn, ^(const MIDIPacketList *pl, void *) { st->feed(vc, pl); }) != noErr) st->virtualIn = 0; else st->module.sourceConnected(-1); if (MIDISourceCreate(st->client, CFSTR("Sizzle"), &st->virtualOut) != noErr) st->virtualOut = 0; st->running = true; st->sender = std::thread([st] { st->sendLoop(); }); [self rescan]; } /// Match CoreMIDI's endpoints with our connections: connect enabled new sources, /// drop vanished ones (releasing their notes), refresh the destination list. - (void)rescan { State *st = gState; if (!st) return; std::vector dests; for (ItemCount i = 0, n = MIDIGetNumberOfDestinations(); i < n; ++i) { MIDIEndpointRef d = MIDIGetDestination(i); if (d && d != st->virtualIn) dests.push_back(d); } { std::lock_guard g(st->destLock); st->dests = dests; } std::vector seen(st->conns.size(), false); for (ItemCount i = 0, n = MIDIGetNumberOfSources(); i < n; ++i) { MIDIEndpointRef ep = MIDIGetSource(i); if (!ep || ep == st->virtualOut) continue; SInt32 uid = 0; MIDIObjectGetIntegerProperty(ep, kMIDIPropertyUniqueID, &uid); Conn *c = nullptr; for (size_t k = 0; k < st->conns.size(); ++k) if (st->conns[k]->uid == uid) { c = st->conns[k].get(); seen[k] = true; break; } if (!c) { auto made = std::make_unique(); made->id = (intptr_t)st->conns.size() + 1; made->uid = uid; made->parser = makeParser(st, made->id); c = made.get(); st->conns.push_back(std::move(made)); seen.push_back(true); } NSString *name = stringProp(ep, kMIDIPropertyDisplayName); if (!name.length) name = stringProp(ep, kMIDIPropertyName); c->name = name.length ? name : @"MIDI device"; c->key = [@[stringProp(ep, kMIDIPropertyManufacturer), stringProp(ep, kMIDIPropertyModel), c->name] componentsJoinedByString:@"|"]; if (c->connected && c->ep != ep) { MIDIPortDisconnectSource(st->inPort, c->ep); c->connected = false; st->module.sourceDisconnected(c->id); } c->ep = ep; const bool want = ![_disabled containsObject:c->key]; if (want && !c->connected && MIDIPortConnectSource(st->inPort, ep, c) == noErr) { c->connected = true; st->module.sourceConnected(c->id); } else if (!want && c->connected) { MIDIPortDisconnectSource(st->inPort, ep); c->connected = false; st->module.sourceDisconnected(c->id); } } for (size_t k = 0; k < st->conns.size(); ++k) { Conn *c = st->conns[k].get(); if (!seen[k]) { if (c->connected) { c->connected = false; st->module.sourceDisconnected(c->id); } c->ep = 0; } } [self publish]; } - (void)publish { NSMutableArray *list = [NSMutableArray array]; NSMutableSet *keys = [NSMutableSet set]; if (gState) for (auto &c : gState->conns) { if (!c->ep || [keys containsObject:c->key]) continue; [keys addObject:c->key]; [list addObject:[[SizzleMidiSource alloc] initWithKey:c->key name:c->name enabled:![_disabled containsObject:c->key] connected:c->connected]]; } _sources = list; if (_onSourcesChanged) _onSourcesChanged(); } - (void)setSourceKey:(NSString *)key enabled:(BOOL)enabled { if (enabled) [_disabled removeObject:key]; else [_disabled addObject:key]; [self rescan]; } - (void)reconnect { State *st = gState; if (!st) return; for (auto &c : st->conns) { if (!c->connected) continue; MIDIPortDisconnectSource(st->inPort, c->ep); c->connected = false; st->module.sourceDisconnected(c->id); } [self rescan]; } - (void)releaseAll { if (gState) gState->module.releaseAll(); } - (void)setSendClock:(BOOL)on { _sendClock = on; if (gState) { gState->sendEnabled = on; gState->engine->setMidiOutEnabled(on); } } - (void)setReceiveClock:(BOOL)on { _receiveClock = on; if (gState) gState->receiveEnabled = on; } - (void)setSoundModule:(BOOL)on { _soundModule = on; if (gState) gState->soundModule = on; } @end