iOS 0.6.0: milestone 5 (recording, MIDI, input bindings, themes, bundles, backups)

- Master recording (MasterSink ring + writer thread) and the sample recorder
- CoreMIDI in/out: sound module, clock send/follow, virtual "Sizzle" ports;
  platform-free parser/module/clock in core (midi_test)
- Hardware keyboard and gamepads via GameController; rebindable keyboard,
  gamepad and MIDI CC actions; per-parameter MIDI learn
- Colour themes (.szt), project bundles (.szgz), backup & restore;
  ZIP in core with zlib (zip_test against jar and unzip)
- Persistent app settings; audio pauses in the background unless sound module

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 14:26:01 +01:00
co-authored by Claude Opus 5.5
parent 435305e42a
commit 64e21e0bcc
54 changed files with 3303 additions and 97 deletions
+194
View File
@@ -0,0 +1,194 @@
// 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 <cstdint>
#include <functional>
#include <map>
#include <mutex>
#include <set>
#include <utility>
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<void(int status, int d1, int d2)>;
/** A System Real-Time byte: clock 0xF8, Start 0xFA, Continue 0xFB, Stop 0xFC, ... */
using Realtime = std::function<void(int status)>;
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<void(bool on, int channel, int note, int velocity)>;
explicit MidiSoundModule(NoteSink &sink) : sink(sink) {}
Listener listener;
void sourceConnected(intptr_t source) { std::lock_guard<std::mutex> g(lock); held[source]; }
void sourceDisconnected(intptr_t source) {
std::lock_guard<std::mutex> 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<std::mutex> 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<std::pair<int, int>> heldNotes(intptr_t source) {
std::lock_guard<std::mutex> g(lock);
std::set<std::pair<int, int>> 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<std::mutex> g(lock); return (int)held.size(); }
private:
void noteOn(intptr_t source, int channel, int note, int velocity) {
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<intptr_t, std::set<int>> 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<void(bool start)> onTransport; // Start/Continue = true, Stop = false
std::function<void(float bpm)> 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
+148
View File
@@ -0,0 +1,148 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/Zip.hpp"
#include <zlib.h>
#include <cstring>
namespace sizzle::io::zip {
namespace {
void u16(std::vector<uint8_t> &o, uint32_t v) { o.push_back((uint8_t)v); o.push_back((uint8_t)(v >> 8)); }
void u32(std::vector<uint8_t> &o, uint32_t v) { u16(o, v & 0xFFFF); u16(o, v >> 16); }
uint32_t r16(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8); }
uint32_t r32(const uint8_t *p) { return r16(p) | (r16(p + 2) << 16); }
bool deflateRaw(const std::vector<uint8_t> &in, std::vector<uint8_t> &out) {
z_stream z{};
if (deflateInit2(&z, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) return false;
out.resize(deflateBound(&z, (uLong)in.size()));
z.next_in = const_cast<Bytef *>(in.data());
z.avail_in = (uInt)in.size();
z.next_out = out.data();
z.avail_out = (uInt)out.size();
const int rc = deflate(&z, Z_FINISH);
out.resize(z.total_out);
deflateEnd(&z);
return rc == Z_STREAM_END;
}
bool inflateRaw(const uint8_t *in, size_t n, std::vector<uint8_t> &out, size_t expected) {
z_stream z{};
if (inflateInit2(&z, -15) != Z_OK) return false;
out.resize(expected + 1); // one spare byte: an empty entry still has room, and overlong data shows
z.next_in = const_cast<Bytef *>(in);
z.avail_in = (uInt)n;
z.next_out = out.data();
z.avail_out = (uInt)out.size();
const int rc = inflate(&z, Z_FINISH);
const bool ok = rc == Z_STREAM_END && z.total_out == expected;
out.resize(expected);
inflateEnd(&z);
return ok;
}
} // namespace
std::vector<uint8_t> write(const std::vector<Entry> &entries) {
std::vector<uint8_t> o, central;
uint32_t count = 0;
for (const Entry &e : entries) {
const uint32_t crc = (uint32_t)crc32(0, e.data.data(), (uInt)e.data.size());
std::vector<uint8_t> packed;
uint16_t method = 8;
if (!deflateRaw(e.data, packed) || packed.size() >= e.data.size()) { packed = e.data; method = 0; }
const uint32_t offset = (uint32_t)o.size();
auto header = [&](std::vector<uint8_t> &h, bool isCentral) {
u32(h, isCentral ? 0x02014b50 : 0x04034b50);
if (isCentral) u16(h, 20); // made by
u16(h, 20); // needed
u16(h, 0x0800); // flags: UTF-8 names
u16(h, method);
u16(h, 0); u16(h, 0x21); // time, date (1980-01-01)
u32(h, crc);
u32(h, (uint32_t)packed.size());
u32(h, (uint32_t)e.data.size());
u16(h, (uint32_t)e.name.size());
u16(h, 0); // extra
if (isCentral) { u16(h, 0); u16(h, 0); u16(h, 0); u32(h, 0); u32(h, offset); }
h.insert(h.end(), e.name.begin(), e.name.end());
};
header(o, false);
o.insert(o.end(), packed.begin(), packed.end());
header(central, true);
++count;
}
const uint32_t cdOffset = (uint32_t)o.size();
o.insert(o.end(), central.begin(), central.end());
u32(o, 0x06054b50);
u16(o, 0); u16(o, 0);
u16(o, count); u16(o, count);
u32(o, (uint32_t)central.size());
u32(o, cdOffset);
u16(o, 0);
return o;
}
bool read(const uint8_t *b, size_t size, std::vector<Entry> &out, uint64_t maxTotal, size_t maxEntries) {
out.clear();
if (size < 22) return false;
// End of central directory: the last signature within the 64 KiB comment window.
size_t eocd = SIZE_MAX;
const size_t lowest = size > 22 + 65535 ? size - 22 - 65535 : 0;
for (size_t i = size - 22 + 1; i-- > lowest;) {
if (r32(b + i) == 0x06054b50) { eocd = i; break; }
}
if (eocd == SIZE_MAX) return false;
const size_t count = r16(b + eocd + 10);
const size_t cdSize = r32(b + eocd + 12), cdOffset = r32(b + eocd + 16);
if (count > maxEntries || cdOffset > size || cdSize > size - cdOffset) return false;
uint64_t total = 0;
size_t p = cdOffset;
for (size_t k = 0; k < count; ++k) {
if (p + 46 > size || r32(b + p) != 0x02014b50) { out.clear(); return false; }
const uint32_t flags = r16(b + p + 8), method = r16(b + p + 10), crc = r32(b + p + 16);
const size_t csize = r32(b + p + 20), usize = r32(b + p + 24);
const size_t nameLen = r16(b + p + 28), extraLen = r16(b + p + 30), commentLen = r16(b + p + 32);
const size_t local = r32(b + p + 42);
if (p + 46 + nameLen > size) { out.clear(); return false; }
std::string name((const char *)b + p + 46, nameLen);
p += 46 + nameLen + extraLen + commentLen;
if (flags & 1) { out.clear(); return false; } // encrypted
if (!name.empty() && name.back() == '/') continue; // a directory
total += usize;
if (total > maxTotal) { out.clear(); return false; }
if (local + 30 > size || r32(b + local) != 0x04034b50) { out.clear(); return false; }
const size_t data = local + 30 + r16(b + local + 26) + r16(b + local + 28);
if (data > size || csize > size - data) { out.clear(); return false; }
Entry e;
e.name = std::move(name);
if (method == 0) {
if (csize != usize) { out.clear(); return false; }
e.data.assign(b + data, b + data + csize);
} else if (method == 8) {
if (!inflateRaw(b + data, csize, e.data, usize)) { out.clear(); return false; }
} else { out.clear(); return false; }
if ((uint32_t)crc32(0, e.data.data(), (uInt)e.data.size()) != crc) { out.clear(); return false; }
out.push_back(std::move(e));
}
return true;
}
bool safeName(const std::string &name) {
if (name.empty() || name[0] == '/' || name.find('\\') != std::string::npos || name.find('\0') != std::string::npos) return false;
size_t start = 0;
while (start <= name.size()) {
size_t end = name.find('/', start);
if (end == std::string::npos) end = name.size();
const std::string part = name.substr(start, end - start);
if (part == ".." || part == ".") return false;
start = end + 1;
}
return true;
}
} // namespace sizzle::io::zip
+40
View File
@@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// A small ZIP reader/writer (zlib) for project bundles (.szgz) and backups, the
// archives java.util.zip writes and reads on Android. Whole archives in memory.
// Writes deflated entries with sizes and CRC in the local headers (no data
// descriptors), so ZipInputStream reads them. Reads through the central directory,
// so entries with data descriptors (what ZipOutputStream writes) are fine. No
// Zip64, no encryption.
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace sizzle::io::zip {
struct Entry {
std::string name;
std::vector<uint8_t> data;
};
/** An archive of [entries], deflated. */
std::vector<uint8_t> write(const std::vector<Entry> &entries);
/**
* Every file entry of the archive in [bytes] (directories skipped). False, with
* [out] cleared, if it isn't a ZIP, is damaged (a CRC mismatch too), uses a
* method other than stored/deflate, has more than [maxEntries] entries or more
* than [maxTotal] bytes uncompressed (Android's ZipLimits budgets).
*/
bool read(const uint8_t *bytes, size_t size, std::vector<Entry> &out,
uint64_t maxTotal = 512ull << 20, size_t maxEntries = 20000);
/** A name that is safe to extract: relative, no "..", no backslashes or NULs. */
bool safeName(const std::string &name);
} // namespace sizzle::io::zip
+73
View File
@@ -0,0 +1,73 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// sizzle/Midi.hpp against the behaviour the Android unit tests pin down
// (MidiByteParserTest, MidiSoundModuleTest) and MidiClock's tempo follow.
#include "sizzle/Midi.hpp"
#include <cstdio>
#include <string>
#include <vector>
using namespace sizzle::midi;
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
struct Rec : NoteSink {
std::vector<std::string> log;
void busNoteOn(int ch, int n, int v) override { log.push_back("on " + std::to_string(ch) + " " + std::to_string(n) + " " + std::to_string(v)); }
void busNoteOff(int ch, int n) override { log.push_back("off " + std::to_string(ch) + " " + std::to_string(n)); }
};
int main() {
// ---- parser
std::vector<std::vector<int>> msgs;
std::vector<int> rt;
MidiByteParser p([&](int s, int a, int b) { msgs.push_back({s, a, b}); }, [&](int s) { rt.push_back(s); });
const uint8_t a[] = {0x90, 60, 100, 62, 90}; // running status
p.feed(a, sizeof a);
CHECK(msgs.size() == 2 && msgs[1] == (std::vector<int>{0x90, 62, 90}));
const uint8_t b1[] = {0x80, 60}, b2[] = {0xF8, 0}; // split + realtime inside
p.feed(b1, 2); p.feed(b2, 2);
CHECK(msgs.size() == 3 && msgs[2] == (std::vector<int>{0x80, 60, 0}) && rt == std::vector<int>{0xF8});
const uint8_t c[] = {0xC3, 5, 0xF0, 1, 2, 3, 0xF7, 7}; // program change, SysEx skipped, stray byte
p.feed(c, sizeof c);
CHECK(msgs.size() == 4 && msgs[3] == (std::vector<int>{0xC3, 5, 0}));
const uint8_t d[] = {0xF2, 1, 2, 64, 0xB0, 123, 0}; // system common cancels running status
msgs.clear(); p.feed(d, sizeof d);
CHECK(msgs.size() == 1 && msgs[0] == (std::vector<int>{0xB0, 123, 0}));
// ---- sound module
Rec r;
MidiSoundModule m(r);
std::vector<std::string> mirror;
m.listener = [&](bool on, int ch, int n, int) { mirror.push_back((on ? "+" : "-") + std::to_string(ch) + ":" + std::to_string(n)); };
m.sourceConnected(1); m.sourceConnected(2);
CHECK(m.onChannelMessage(1, 0x90, 60, 100));
CHECK(m.onChannelMessage(2, 0x91, 64, 80));
CHECK(m.onChannelMessage(1, 0x90, 60, 0)); // velocity 0 = off
CHECK(m.heldNotes(1).empty() && m.heldNotes(2).size() == 1);
CHECK(!m.onChannelMessage(1, 0xB0, 7, 100)); // other CCs are the caller's
m.onChannelMessage(1, 0x92, 70, 90);
CHECK(m.onChannelMessage(2, 0xB2, 123, 0)); // channel 3 off from any source
CHECK(m.heldNotes(1).empty());
r.log.clear();
m.sourceDisconnected(2); // releases its held note
CHECK(r.log == std::vector<std::string>{"off 2 64"} && m.sourceCount() == 1);
CHECK(mirror.front() == "+1:60" && mirror.back() == "-2:64");
// ---- clock follow: 24 pulses at 125 BPM = 20 ms each
ClockFollower f;
float bpm = 0; int starts = 0, stops = 0;
f.onTempo = [&](float b) { bpm = b; };
f.onTransport = [&](bool s) { s ? ++starts : ++stops; };
f.realtime(0xFA, 0);
for (int i = 0; i <= 24; ++i) f.realtime(0xF8, 1'000'000'000LL + i * 20'000'000LL);
f.realtime(0xFC, 0);
CHECK(starts == 1 && stops == 1 && bpm > 124.99f && bpm < 125.01f);
std::printf(failures ? "midi_test: %d failure(s)\n" : "midi_test: ok\n", failures);
return failures ? 1 : 0;
}
+54
View File
@@ -0,0 +1,54 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// io/Zip: round trips, damage, unsafe names; argv[1]: an archive java.util.zip wrote
// (with data descriptors, as Android's ZipOutputStream does), holding a.txt = "hello\n"
// and dir/b.bin; argv[2]: where to write an archive for `unzip -t`.
#include "io/Zip.hpp"
#include <cstdio>
#include <fstream>
#include <iterator>
using namespace sizzle::io;
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
int main(int argc, char **argv) {
std::vector<zip::Entry> in = {{"project.szg", std::vector<uint8_t>(5000, 'x')}, {"empty", {}},
{"samples/0.wav", {}}};
for (int i = 0; i < 3000; ++i) in[2].data.push_back((uint8_t)(i * 7919 >> 3));
auto bytes = zip::write(in);
std::vector<zip::Entry> out;
CHECK(zip::read(bytes.data(), bytes.size(), out));
CHECK(out.size() == 3 && out[0].name == "project.szg" && out[0].data == in[0].data && out[1].data.empty() && out[2].data == in[2].data);
CHECK(bytes.size() < 5000); // deflated
auto bad = bytes;
bad[50] ^= 0xFF; // inside the first entry's data
CHECK(!zip::read(bad.data(), bad.size(), out) && out.empty());
CHECK(!zip::read(bytes.data(), bytes.size() - 10, out));
CHECK(!zip::read(bytes.data(), bytes.size(), out, 1000)); // over the size budget
CHECK(!zip::read(bytes.data(), bytes.size(), out, 1 << 30, 2));
CHECK(zip::safeName("songs/a b.szg") && zip::safeName("x"));
CHECK(!zip::safeName("../x") && !zip::safeName("a/../../x") && !zip::safeName("/etc/x") && !zip::safeName("a\\b") && !zip::safeName(""));
if (argc > 1) {
std::ifstream f(argv[1], std::ios::binary);
std::vector<uint8_t> j((std::istreambuf_iterator<char>(f)), {});
CHECK(zip::read(j.data(), j.size(), out));
bool a = false, b = false;
for (auto &e : out) {
if (e.name == "a.txt") a = std::string(e.data.begin(), e.data.end()) == "hello\n";
if (e.name == "dir/b.bin") b = e.data.size() == 4096;
}
CHECK(a && b);
}
if (argc > 2) { std::ofstream o(argv[2], std::ios::binary); o.write((const char *)bytes.data(), (std::streamsize)bytes.size()); }
std::printf(failures ? "zip_test: %d failure(s)\n" : "zip_test: ok\n", failures);
return failures ? 1 : 0;
}