diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 86659d3..96dcf6c 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -3,6 +3,38 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in `../versions.properties` (`ios.versionName` / `ios.versionCode`). +## 0.6.0 (build 11) + +Milestone 5: the rest of the Android app. + +- Recording: ● ARM on the Mix tab records the master bus to a WAV when Play + starts (or an external MIDI clock's Start), up to an FX tail of 0-4 bars + after the stop. Takes land in Files › On My iPad › Sizzle › Recordings; + SHARE sends the last one. Sampler pads and the Grain Cloud get ● RECORD + (microphone or an audio interface's input, up to 30 s). +- MIDI (CoreMIDI): every source is listened to (USB, Bluetooth, network, other + apps), plus a "Sizzle" destination other apps can send to. Notes play the + mixer tracks on their channel straight from the MIDI thread; with punch-in + armed they are entered into the grid. Setup › MIDI Sync: send clock, Start/ + Stop and the sequenced notes (also through a "Sizzle" source), follow an + external clock, sound-module mode, and a switch per source. +- Hardware keyboard and gamepads (GameController): Android's default hotkeys + and the Z…M / Q…U tracker piano; buttons, D-pad and both sticks, with combos. + Setup › Controls rebinds keyboard, gamepad and MIDI CC by learning. +- ⇄ MIDI in each slot editor: MIDI-learn a CC per device parameter (saved in + the song, as on Android). +- Colour themes: Amber CRT and Ice Terminal, import / export / delete .szt + themes (Android's format). The default look now uses Android's exact colours. +- Project bundles (.szgz, with samples) for Export / Import project, readable + by the Android app and from it; Import also takes a plain .szg. +- Backup & Restore: one .zip with songs, presets, themes, samples, the open + song and the settings. +- Settings persist: keyboard channel and octave, record tail, mixer VU meters + (now switchable), MIDI options, bindings, theme. +- Audio: the output pauses in the background when nothing plays, unless + sound-module mode is on; it restarts after route changes and interruptions. +- Documents shows in the Files app. + ## 0.5.0 (build 10) - The hand-built editors of the Android app, in the app and in the plugins: diff --git a/ios/Makefile b/ios/Makefile index 506b13d..905ee1e 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -37,7 +37,7 @@ IPA := dist/$(APP_ID)_$(BUILD_NO).ipa CORE_SRC := $(wildcard core/src/*.cpp core/src/*/*.cpp) CORE_HDR := $(wildcard core/include/sizzle/*.hpp core/src/*/*.hpp) CXX ?= c++ -CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -Icore/include -Icore/src -Icore/src/fx +CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -Icore/include -Icore/src -Icore/src/fx -lz GOLDEN := core/golden SPECS_GEN := core/include/sizzle/DeviceSpecs.gen.hpp # Gradle needs the Android SDK; same default location as the Android Makefile. @@ -78,19 +78,36 @@ build/core/io_test: $(CORE_SRC) $(CORE_HDR) core/tests/io_test.cpp mkdir -p build/core $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) core/tests/io_test.cpp -core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test +build/core/midi_test: core/include/sizzle/Midi.hpp core/tests/midi_test.cpp + mkdir -p build/core + $(CXX) $(CXXFLAGS) -o $@ core/tests/midi_test.cpp + +build/core/zip_test: core/src/io/Zip.cpp core/src/io/Zip.hpp core/tests/zip_test.cpp + mkdir -p build/core/zipfix/dir + $(CXX) $(CXXFLAGS) -o $@ core/src/io/Zip.cpp core/tests/zip_test.cpp -lz + +# A Java-written archive (ZipOutputStream, like Android's) for zip_test, and ours checked by unzip. +zip-test: build/core/zip_test + printf 'hello\n' > build/core/zipfix/a.txt + head -c 4096 /dev/urandom > build/core/zipfix/dir/b.bin + cd build/core/zipfix && rm -f ../java.zip && jar cfM ../java.zip a.txt dir/b.bin + build/core/zip_test build/core/java.zip build/core/ours.zip + unzip -tq build/core/ours.zip + +core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test zip-test @test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden build/core/golden_test $(GOLDEN) $(TYPES) build/core/sampler_test build/core/engine_test $(GOLDEN)/songs build/core/io_test $(GOLDEN)/songs ../app/src/test/resources/mikroseq + build/core/midi_test # ------------------------------------------------------------------ app AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm app/FX/SizzleDeviceAU+Sources.mm build/core/au_test: $(AU_SRC) $(wildcard app/FX/*.h app/FX/*.hpp) app/tests/au_test.mm $(CORE_SRC) $(CORE_HDR) mkdir -p build/core $(CXX) $(CXXFLAGS) -Wno-deprecated-declarations -fobjc-arc -Iapp/FX -o $@ $(AU_SRC) app/tests/au_test.mm $(CORE_SRC) \ - -framework AVFoundation -framework AudioToolbox -framework Foundation + -framework AVFoundation -framework AudioToolbox -framework Foundation -framework CoreMIDI au-test: build/core/au_test @test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden @@ -116,13 +133,13 @@ SNAPDIR ?= build/screens # Mac snapshots of the app's tabs with the demo song (SizzleSession runs on macOS # too, without audio). Screens must stay SwiftUI-only (no UIKit) to render here. SCREEN_SWIFT := $(EDITOR_SWIFT) app/Host/AppModel.swift app/Host/RootView.swift app/Host/SlotDeviceModel.swift \ - app/Host/KeyboardView.swift app/Host/SlotDataSource.swift \ - $(shell find app/Host/Screens app/Host/Bespoke -name '*.swift') -$(SNAPDIR)/libsizzlescreens.dylib: $(AU_SRC) $(wildcard app/Host/SizzleSession*.mm app/Host/SizzleSession*.h) app/tests/SnapshotComponents.mm $(CORE_SRC) $(CORE_HDR) + app/Host/KeyboardView.swift app/Host/SlotDataSource.swift app/Host/SampleRecorder.swift app/Host/AppSettings.swift app/Host/AppBoot.swift app/Host/ThemeLibrary.swift \ + $(shell find app/Host/Screens app/Host/Bespoke app/Host/Input -name '*.swift') +$(SNAPDIR)/libsizzlescreens.dylib: $(AU_SRC) $(wildcard app/Host/SizzleSession*.mm app/Host/SizzleSession*.h) app/Host/SizzleMidi.mm app/Host/SizzleMidi.h app/tests/SnapshotComponents.mm $(CORE_SRC) $(CORE_HDR) mkdir -p $(SNAPDIR) $(CXX) $(CXXFLAGS) -Wno-deprecated-declarations -fobjc-arc -Iapp/FX -Iapp/Host -dynamiclib -install_name @rpath/libsizzlescreens.dylib \ - -o $@ $(AU_SRC) $(wildcard app/Host/SizzleSession*.mm) app/tests/SnapshotComponents.mm $(CORE_SRC) \ - -framework AVFoundation -framework AudioToolbox -framework Foundation + -o $@ $(AU_SRC) $(wildcard app/Host/SizzleSession*.mm) app/Host/SizzleMidi.mm app/tests/SnapshotComponents.mm $(CORE_SRC) \ + -framework AVFoundation -framework AudioToolbox -framework Foundation -framework CoreMIDI $(SNAPDIR)/screen_snapshots: $(SNAPDIR)/libsizzlescreens.dylib $(SCREEN_SWIFT) app/tests/screen_snapshots.swift swiftc -O -parse-as-library -import-objc-header app/tests/ScreenBridging.h -Iapp/FX -Iapp/Host -Iapp/tests \ @@ -182,4 +199,4 @@ $(SPIKE_IPA): $(SPIKE_PROJ)/project.pbxproj $(SPIKE_SRC) clean: rm -rf build dist -.PHONY: help golden core-test au-test project ipa bump-major bump-minor bump-patch bump spike-ipa clean +.PHONY: help golden core-test zip-test au-test project ipa bump-major bump-minor bump-patch bump spike-ipa clean diff --git a/ios/PORTING.md b/ios/PORTING.md index 19d90c6..712c1a0 100644 --- a/ios/PORTING.md +++ b/ios/PORTING.md @@ -113,6 +113,39 @@ AUv3s is the per-plugin process round trip, which the in-app host avoids. values with `,` or `=` break a [TOOLBOX] line. `Params` caps keys at 23 bytes, values at 31 and slots at 96 keys, so a long sample path would be cut short. +- 2026-11-16, 0.6.0 (milestone 5): recording, MIDI, input bindings, themes, + bundles, backups, settings. Decisions: + - Master recording: `SizzleSession+Record` implements the engine's `MasterSink` + (MasterRecorder.kt: SPSC float ring, a writer thread, header patched at the + end). Takes go to Documents/Recordings (no folder picker on iOS; Documents is + visible in Files). Sample recording uses AVAudioRecorder; the audio session + is play-and-record only while recording, and the engine restarts itself on + the configuration change that causes. + - MIDI: `core/include/sizzle/Midi.hpp` holds the platform-free parts + (MidiByteParser, MidiSoundModule, the clock follower; `midi_test`). + `SizzleMidi` is the CoreMIDI side. Notes from the MIDI threads go through a + second note queue to the audio thread (pushes serialised by the module's + lock), never through the main thread. The send thread reads the engine's + `isPlaying` / `pollMidiOut` and the tempo without the song lock. Source keys + are manufacturer|model|name (CoreMIDI's unique id is used only within a run). + - Input: InputAction / InputRouter / InputBindings / InputController port + Android's input package; HardwareInput uses GameController's GCKeyboard and + GCController, so no responder-chain plumbing is needed (keys are ignored + while a text field has focus). Keyboard codes are HID usages, so binding + maps don't carry over from Android (they never could: Android key codes). + - Themes: `Theme` reads a `Palette`; the app rebuilds its view tree when the + theme changes. The plugins always draw the default theme. + - ZIP: `core/src/io/Zip` (zlib): reads through the central directory (so + java.util.zip's data descriptors are fine), writes sizes in local headers + (so ZipInputStream reads ours); `zip-test` checks both against `jar` and + `unzip`. Bundles keep the Android layout and store samples under their + original ids. Backups hold songs/themes/presets/samples, autosave.szg and + settings.txt (AppSettings' key=value text); restore unpacks aside first, + then swaps the folders in and applies everything at once (no restart). + - Not done: App Group file access for the plugins; per-device output choice + (iOS routes audio; Setup shows the route and the system picker); MIDI 2.0 / + MIDIEventList. + Notes for the engine port (from the voice ports): - Kotlin seeds every new FrasilVoice and GrainCloud from global counters, and every SynthVoice builds a FrasilVoice. The C++ engine owns one `frasil::FrasilSeeds`, diff --git a/ios/README.md b/ios/README.md index 6d93900..b46f64d 100644 --- a/ios/README.md +++ b/ios/README.md @@ -175,12 +175,13 @@ therefore not confirmed on the device yet. ## Next steps -1. Instruments (Synth, Wavetable, Morph Pad, Grain Cloud, Sampler, SF2/XI) as - `aumu` plugins, through the same reference-audio route (the export will need - note scripts, not just an input signal). +All five milestones of PORTING.md are in (0.6.0). Open: + +1. Sample and SF2 / wavetable files for the plugins through an App Group + (`group.cc.tiredsysadmin.ios.sizzle`), so LOAD WAV / LOAD TABLE work in AUM. 2. MIDI effects (Arpeggiator, Transposer, LFO) as `aumi` plugins. -3. The card editors in SwiftUI from the `DeviceLayouts` data. -4. Sample and SF2 files through the App Group (`group.cc.tiredsysadmin.ios.sizzle`). +3. On-device checks of 0.6.0: MIDI devices and apps, clock in/out, gamepads, + hardware keyboards, recording, bundles exchanged with the Android app. ## The TrollStore spike (spike/) diff --git a/ios/app/FX/Editor/Bespoke/Bespoke.swift b/ios/app/FX/Editor/Bespoke/Bespoke.swift index 3893792..ba997d2 100644 --- a/ios/app/FX/Editor/Bespoke/Bespoke.swift +++ b/ios/app/FX/Editor/Bespoke/Bespoke.swift @@ -50,6 +50,22 @@ extension EnvironmentValues { } } +/// The app's microphone recorder for editors that take a recording (the Grain +/// Cloud's RECORD); nil in the plugin, which shows no RECORD button. +struct DeviceRecordControl { + let isRecording: Bool + let toggle: () -> Void +} +private struct DeviceRecorderKey: EnvironmentKey { + static let defaultValue: DeviceRecordControl? = nil +} +extension EnvironmentValues { + var deviceRecorder: DeviceRecordControl? { + get { self[DeviceRecorderKey.self] } + set { self[DeviceRecorderKey.self] = newValue } + } +} + /// Hand-built pieces of device editors (the Android app's bespoke editors), by /// device. DeviceEditor asks here first and falls back to the card layout. Each /// device's views live in their own file in this folder. diff --git a/ios/app/FX/Editor/Bespoke/DelayBespoke.swift b/ios/app/FX/Editor/Bespoke/DelayBespoke.swift index 312730d..689479b 100644 --- a/ios/app/FX/Editor/Bespoke/DelayBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/DelayBespoke.swift @@ -18,7 +18,7 @@ enum DelayBespoke { "1/4T", "1/8", "1/16.", "1/8T", "1/16", "1/16T"] static var divisions: [String] { Layouts.file?.delayDivisions ?? fallbackDivisions } /// Android's default theme's playhead green (the selected-step band). - static let band = Color(red: 0x7C / 255.0, green: 0xFC / 255.0, blue: 0x9A / 255.0) + static var band: Color { Theme.playhead } } private struct DelayEditorView: View { diff --git a/ios/app/FX/Editor/Bespoke/GrainCloudBespoke.swift b/ios/app/FX/Editor/Bespoke/GrainCloudBespoke.swift index 16b7cb6..b503107 100644 --- a/ios/app/FX/Editor/Bespoke/GrainCloudBespoke.swift +++ b/ios/app/FX/Editor/Bespoke/GrainCloudBespoke.swift @@ -14,7 +14,8 @@ protocol SampleLengthSource: AnyObject { /// The Grain Cloud's source strip (Android's GrainCloudEditor.kt): load a WAV (or /// SF2/XI) as the cloud's own source, and see the source with its START..END region -/// lit. The settings themselves are the card pages below it. (RECORD isn't ported.) +/// lit. The settings themselves are the card pages below it. RECORD (the app only) +/// makes a microphone take the source. @MainActor enum GrainCloudBespoke { static func header(_ model: DeviceModel) -> AnyView? { AnyView(GrainSourceStrip(model: model)) } @@ -39,6 +40,7 @@ struct GrainSourceStrip: View { @ObservedObject var model: DeviceModel @State private var pickerShown = false @Environment(\.deviceFilePicker) private var hostPicker + @Environment(\.deviceRecorder) private var recorder @State private var importError: String? /// Bumped while a built-in source is still being rendered, to look again. @State private var retry = 0 @@ -63,6 +65,15 @@ struct GrainSourceStrip: View { .overlay(Rectangle().stroke(Theme.accent.opacity(0.6), lineWidth: 1)) .contentShape(Rectangle()) .onTapGesture { if let pick = hostPicker { pick { url in load(url) } } else { pickerShown = true } } + if let rec = recorder { + Text(rec.isRecording ? "■ STOP REC" : "● RECORD").font(Theme.mono(12)) + .foregroundColor(rec.isRecording ? Theme.background : Theme.accent) + .padding(.horizontal, 10).padding(.vertical, 6) + .background(rec.isRecording ? Theme.accent : Theme.surface) + .overlay(Rectangle().stroke(Theme.accent.opacity(0.6), lineWidth: 1)) + .contentShape(Rectangle()) + .onTapGesture(perform: rec.toggle) + } Spacer(minLength: 0) } Text(caption).font(Theme.mono(10)).foregroundColor(Theme.dim) diff --git a/ios/app/FX/Editor/Controls.swift b/ios/app/FX/Editor/Controls.swift index c166115..e5c0861 100644 --- a/ios/app/FX/Editor/Controls.swift +++ b/ios/app/FX/Editor/Controls.swift @@ -18,14 +18,38 @@ struct SnapScroll: View { } } -/// Sizzle's dark retro palette (Android's default theme) and the card tones. +/// A colour theme (Android's RetroPalette), colours as 0xRRGGBB. +struct Palette: Equatable { + var name: String + var background, surface, grid, text, textDim, accent, beat, bar, playhead, danger: UInt32 + + static let amber = Palette(name: "Amber CRT", background: 0x0B0D0E, surface: 0x15181A, grid: 0x23282B, + text: 0xCFE8D8, textDim: 0x6E7C74, accent: 0xF2C14E, beat: 0x141C1A, bar: 0x1E2A20, + playhead: 0x7CFC9A, danger: 0xE05A4B) + static let ice = Palette(name: "Ice Terminal", background: 0x07090F, surface: 0x10151F, grid: 0x1E2633, + text: 0xCFE0FF, textDim: 0x63708A, accent: 0x62B6FF, beat: 0x121A26, bar: 0x1B2740, + playhead: 0x8AF0FF, danger: 0xE05A7A) + static let stock = [amber, ice] + + static func color(_ rgb: UInt32) -> Color { + Color(red: Double((rgb >> 16) & 0xFF) / 255, green: Double((rgb >> 8) & 0xFF) / 255, blue: Double(rgb & 0xFF) / 255) + } +} + +/// Sizzle's retro palette (the current theme; the plugins always use the default) +/// and the card tones. The app redraws everything when the theme changes. enum Theme { - static let background = Color(red: 0.07, green: 0.08, blue: 0.09) - static let surface = Color(red: 0.11, green: 0.12, blue: 0.14) - static let grid = Color(white: 0.24) - static let text = Color(white: 0.92) - static let dim = Color(white: 0.58) - static let accent = Color(red: 0.96, green: 0.76, blue: 0.29) + static var current = Palette.amber + static var background: Color { Palette.color(current.background) } + static var surface: Color { Palette.color(current.surface) } + static var grid: Color { Palette.color(current.grid) } + static var text: Color { Palette.color(current.text) } + static var dim: Color { Palette.color(current.textDim) } + static var accent: Color { Palette.color(current.accent) } + static var beat: Color { Palette.color(current.beat) } + static var bar: Color { Palette.color(current.bar) } + static var playhead: Color { Palette.color(current.playhead) } + static var danger: Color { Palette.color(current.danger) } static func tone(_ t: LayoutPanel.Tone) -> Color { switch t { diff --git a/ios/app/FX/Editor/DeviceEditor.swift b/ios/app/FX/Editor/DeviceEditor.swift index 6f3a8e0..f1ea7d0 100644 --- a/ios/app/FX/Editor/DeviceEditor.swift +++ b/ios/app/FX/Editor/DeviceEditor.swift @@ -152,7 +152,7 @@ struct CardView: View { public final class SizzleEditorFactory: NSObject { @objc public static func makeEditor(for au: SizzleDeviceAU) -> UIViewController { let vc = UIHostingController(rootView: DeviceEditor(model: DeviceModel(au: au))) - vc.view.backgroundColor = UIColor(red: 0.07, green: 0.08, blue: 0.09, alpha: 1) + vc.view.backgroundColor = UIColor(Theme.background) return vc } } diff --git a/ios/app/FX/Editor/DeviceModel.swift b/ios/app/FX/Editor/DeviceModel.swift index 3885ded..f1b4a5e 100644 --- a/ios/app/FX/Editor/DeviceModel.swift +++ b/ios/app/FX/Editor/DeviceModel.swift @@ -101,6 +101,12 @@ final class DeviceModel: ObservableObject { return info.choices[Swift.max(0, Swift.min(info.choices.count - 1, i))] } + /// Read the values again (changed elsewhere: a MIDI CC bound to a parameter). + func refresh() { + let v = reread() + if v != values { values = v } + } + func applyPreset(named name: String) { applyPresetNamed(name) presetName = name diff --git a/ios/app/Host/AppBoot.swift b/ios/app/Host/AppBoot.swift new file mode 100644 index 0000000..e6d23b0 --- /dev/null +++ b/ios/app/Host/AppBoot.swift @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Everything that runs once at launch, before any screen (Android's SizzleApp): +/// settings that live outside the song, MIDI, and the hardware input sources. +@MainActor +enum AppBoot { + static func start() { + let settings = AppSettings.shared + let session = SizzleSession.shared + session.recordTailBars = settings.recordTailBars + ThemeLibrary.shared.select(settings.paletteName) + + let input = InputController.shared + input.app = AppModel.main + input.start() + HardwareInput.shared.start() + + let midi = SizzleMidi.shared + midi.sendClock = settings.sendMidiClock + midi.receiveClock = settings.receiveMidiClock + midi.soundModule = settings.soundModule + midi.onNote = { on, ch, note, vel in input.midiNote(on: on, channel: ch, note: note, velocity: vel) } + midi.onControl = { cc, value in input.midiControl(cc, value) } + midi.start(withDisabledKeys: settings.midiSourcesOff) + } + + /// Leaving the foreground: save, and unless Sizzle stays on as a sound module + /// (or is playing / recording), pause the audio so iOS can suspend the app. + static func background() { + let session = SizzleSession.shared + session.autosave() + let busy = session.isPlaying || session.masterRecording || SampleRecorder.shared.isRecording + if !AppSettings.shared.soundModule && !busy { session.audioSuspended = true } + } + + static func foreground() { SizzleSession.shared.audioSuspended = false } +} diff --git a/ios/app/Host/AppModel.swift b/ios/app/Host/AppModel.swift index 991415d..225705e 100644 --- a/ios/app/Host/AppModel.swift +++ b/ios/app/Host/AppModel.swift @@ -32,8 +32,9 @@ final class AppModel: ObservableObject { @Published var cursorColumn: Column = .note // On-screen keyboard (Android: kbdChannel / kbdOctave / kbdVelocity). - @Published var kbdChannel = 1 - @Published var kbdOctave = 3 + // Channel and octave persist (AppSettings), like Android's. + @Published var kbdChannel = AppSettings.shared.kbdChannel { didSet { AppSettings.shared.kbdChannel = kbdChannel } } + @Published var kbdOctave = AppSettings.shared.kbdOctave { didSet { AppSettings.shared.kbdOctave = kbdOctave } } @Published var kbdVelocity = 127 /// The toolbox slot whose editor is open, if any. diff --git a/ios/app/Host/AppSettings.swift b/ios/app/Host/AppSettings.swift new file mode 100644 index 0000000..92cde35 --- /dev/null +++ b/ios/app/Host/AppSettings.swift @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// App-level settings that persist across launches (Android's SettingsStore and +/// BindingStore). Song, mixer and toolbox settings live in the project instead. +/// Stored in UserDefaults; a backup carries them as a text file (`settings.txt`, +/// one `key=value` line each, see `exportText` / `importText`). +@MainActor +final class AppSettings: ObservableObject { + static let shared = AppSettings() + private let d = UserDefaults.standard + + /// The colour theme's name (a built-in one or a user theme). + @Published var paletteName: String { didSet { d.set(paletteName, forKey: "palette") } } + /// FX tail captured after the sequencer stops (bars, 0..4). + @Published var recordTailBars: Int { didSet { d.set(recordTailBars, forKey: "recordTailBars") } } + /// The on-screen keyboards' MIDI channel (0 = none) and base octave. + @Published var kbdChannel: Int { didSet { d.set(kbdChannel, forKey: "kbdChannel") } } + @Published var kbdOctave: Int { didSet { d.set(kbdOctave, forKey: "kbdOctave") } } + /// The live meters inside the mixer's volume faders. + @Published var vuMeters: Bool { didSet { d.set(vuMeters, forKey: "vuMeters") } } + /// Send MIDI clock, Start/Stop and the sequenced notes to MIDI destinations. + @Published var sendMidiClock: Bool { didSet { d.set(sendMidiClock, forKey: "midiClockSend") } } + /// Follow an external MIDI clock's tempo and Start/Stop. + @Published var receiveMidiClock: Bool { didSet { d.set(receiveMidiClock, forKey: "midiClockRecv") } } + /// Keep the audio running in the background so incoming MIDI plays (sound module). + @Published var soundModule: Bool { didSet { d.set(soundModule, forKey: "soundModule") } } + /// MIDI sources the user switched off (MidiSourceKey). + @Published var midiSourcesOff: Set { didSet { d.set(Array(midiSourcesOff).sorted(), forKey: "midiSourcesOff") } } + /// Input bindings, one `code=actionId` line each (gamepad: `modifier:code=actionId`); + /// nil until the user changes them (the defaults apply). + @Published var keyboardBindings: String? { didSet { d.set(keyboardBindings, forKey: "bindKeyboard") } } + @Published var gamepadBindings: String? { didSet { d.set(gamepadBindings, forKey: "bindGamepad") } } + @Published var midiBindings: String? { didSet { d.set(midiBindings, forKey: "bindMidi") } } + + private init() { + paletteName = d.string(forKey: "palette") ?? "Amber CRT" + recordTailBars = d.object(forKey: "recordTailBars") as? Int ?? 2 + kbdChannel = d.object(forKey: "kbdChannel") as? Int ?? 1 + kbdOctave = d.object(forKey: "kbdOctave") as? Int ?? 3 + vuMeters = d.object(forKey: "vuMeters") as? Bool ?? true + sendMidiClock = d.bool(forKey: "midiClockSend") + receiveMidiClock = d.bool(forKey: "midiClockRecv") + soundModule = d.bool(forKey: "soundModule") + midiSourcesOff = Set(d.stringArray(forKey: "midiSourcesOff") ?? []) + keyboardBindings = d.string(forKey: "bindKeyboard") + gamepadBindings = d.string(forKey: "bindGamepad") + midiBindings = d.string(forKey: "bindMidi") + } + + // MARK: Backup text + + private static let keys = ["palette", "recordTailBars", "kbdChannel", "kbdOctave", "vuMeters", "midiClockSend", + "midiClockRecv", "soundModule", "midiSourcesOff", "bindKeyboard", "bindGamepad", "bindMidi"] + + /// Every setting as `key=value` lines; multi-line values (bindings, the source + /// list) are escaped (`\n` → `\\n`). + func exportText() -> String { + var lines = ["SIZZLE-SETTINGS 1"] + for k in Self.keys { + guard let v = d.object(forKey: k) else { continue } + let text: String + switch v { + case let a as [String]: text = a.joined(separator: "\n") + case let n as NSNumber where k == "vuMeters" || k.hasPrefix("midiClock") || k == "soundModule": text = n.boolValue ? "true" : "false" + default: text = "\(v)" + } + lines.append(k + "=" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\n", with: "\\n")) + } + return lines.joined(separator: "\n") + "\n" + } + + /// Restore settings written by exportText (unknown keys are ignored). + func importText(_ text: String) { + var map: [String: String] = [:] + for line in text.split(separator: "\n") { + guard let eq = line.firstIndex(of: "=") else { continue } + var v = "", esc = false + for c in line[line.index(after: eq)...] { + if esc { v.append(c == "n" ? "\n" : c); esc = false } else if c == "\\" { esc = true } else { v.append(c) } + } + map[String(line[..1.0 CFBundleVersion 1 + LSSupportsOpeningDocumentsInPlace + + NSMicrophoneUsageDescription + Sizzle records the microphone or an audio interface's input into samples. UIBackgroundModes audio + UIFileSharingEnabled + diff --git a/ios/app/Host/Input/HardwareInput.swift b/ios/app/Host/Input/HardwareInput.swift new file mode 100644 index 0000000..e30968a --- /dev/null +++ b/ios/app/Host/Input/HardwareInput.swift @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation +import GameController +#if canImport(UIKit) +import UIKit +#endif + +/// Hardware keyboards and gamepads through the GameController framework (Android's +/// KeyboardInput and GamepadInput). Both feed InputRouter; their maps are +/// InputBindings'. Keys are ignored while a text field is being typed into. +/// +/// Keyboard: bound hotkeys first ("octaveUp"/"octaveDown" move the piano's octave, +/// Shift+the next-column key goes back a column), then the fixed two-octave piano. +/// Gamepad: buttons, the D-pad and both sticks (edge-detected with hysteresis) go +/// through one press/release path, so any of them can be bound or chorded. +@MainActor +final class HardwareInput { + static let shared = HardwareInput() + + /// The keyboard piano's octave (Android's KeyboardInput.baseOctave). + private(set) var baseOctave = 4 + private var pianoHeld: [Int: Int] = [:] // key code -> pitch it started + private var heldPad: [Int] = [] // gamepad controls held, in press order + private var learnSeq: [Int] = [] + private var axes: [Int: Int] = [:] // axis id -> sign (-1, 0, 1) + private var started = false + + private var router: InputRouter { InputRouter.shared } + private var bindings: InputBindings { InputBindings.shared } + + func start() { + guard !started else { return } + started = true + let nc = NotificationCenter.default + nc.addObserver(forName: .GCKeyboardDidConnect, object: nil, queue: .main) { n in + Task { @MainActor in (n.object as? GCKeyboard).map(HardwareInput.shared.attach) } + } + nc.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { n in + Task { @MainActor in (n.object as? GCController).map(HardwareInput.shared.attach) } + } + if let kb = GCKeyboard.coalesced { attach(kb) } + GCController.controllers().forEach(attach) + } + + // MARK: Keyboard + + private func attach(_ kb: GCKeyboard) { + kb.keyboardInput?.keyChangedHandler = { _, _, code, pressed in + Task { @MainActor in HardwareInput.shared.key(code.rawValue, pressed) } + } + } + + private func shiftHeld() -> Bool { + guard let k = GCKeyboard.coalesced?.keyboardInput else { return false } + return (k.button(forKeyCode: .leftShift)?.isPressed ?? false) || (k.button(forKeyCode: .rightShift)?.isPressed ?? false) + } + + private func key(_ code: Int, _ pressed: Bool) { + if !pressed { + router.releaseRepeat(AnyHashable("k\(code)")) + if let pitch = pianoHeld.removeValue(forKey: code) { + router.dispatch(.noteOff(pitch: pitch, channel: -1, sounded: false)) + } + return + } + if Self.typingInTextField() { return } + if router.learnSource == .keyboard { + router.dispatch(.raw(source: .keyboard, code: code, value: 1, modifier: 0)) + return + } + if let id = bindings.keyboard[code] { + switch id { + case "octaveDown": baseOctave = max(0, baseOctave - 1) + case "octaveUp": baseOctave = min(8, baseOctave + 1) + case "nextColumn": router.pressRepeat(AnyHashable("k\(code)"), shiftHeld() ? .prevColumn : .nextColumn) + default: if let a = InputActions.action(id) { router.pressRepeat(AnyHashable("k\(code)"), a) } + } + return + } + if let offset = InputBindings.piano[code] { + let pitch = min(max(60 + (baseOctave - 4) * 12 + offset, 0), 127) + pianoHeld[code] = pitch + router.dispatch(.noteOn(pitch: pitch, velocity: 100, channel: -1, sounded: false)) + } + } + + #if canImport(UIKit) + fileprivate static var found: UIResponder? + private static func typingInTextField() -> Bool { + found = nil + UIApplication.shared.sendAction(#selector(UIResponder.sizzleFindFirstResponder(_:)), to: nil, from: nil, for: nil) + defer { found = nil } + return found is UITextField || found is UITextView + } + #else + private static func typingInTextField() -> Bool { false } + #endif + + // MARK: Gamepad + + private func attach(_ c: GCController) { + guard let g = c.extendedGamepad else { return } + typealias P = InputBindings.Pad + let buttons: [(GCControllerButtonInput?, Int)] = [ + (g.buttonA, P.a), (g.buttonB, P.b), (g.buttonX, P.x), (g.buttonY, P.y), + (g.leftShoulder, P.l1), (g.rightShoulder, P.r1), (g.leftTrigger, P.l2), (g.rightTrigger, P.r2), + (g.buttonMenu, P.menu), (g.buttonOptions, P.options), + (g.leftThumbstickButton, P.l3), (g.rightThumbstickButton, P.r3), + (g.dpad.up, P.up), (g.dpad.down, P.down), (g.dpad.left, P.left), (g.dpad.right, P.right), + ] + for (button, code) in buttons { + button?.pressedChangedHandler = { _, _, pressed in + Task { @MainActor in pressed ? HardwareInput.shared.padDown(code) : HardwareInput.shared.padUp(code) } + } + } + // Up is negative, as on Android (GameController's y points up). + g.leftThumbstick.valueChangedHandler = { _, x, y in + Task { @MainActor in + HardwareInput.shared.axis(0, x, P.lsLeft, P.lsRight) + HardwareInput.shared.axis(1, -y, P.lsUp, P.lsDown) + } + } + g.rightThumbstick.valueChangedHandler = { _, x, y in + Task { @MainActor in + HardwareInput.shared.axis(2, x, P.rsLeft, P.rsRight) + HardwareInput.shared.axis(3, -y, P.rsUp, P.rsDown) + } + } + } + + /// Push past 0.6 = press, back inside 0.4 = release; in between, hold. + private func axis(_ id: Int, _ value: Float, _ neg: Int, _ pos: Int) { + let last = axes[id] ?? 0 + let sign = value <= -0.6 ? -1 : value >= 0.6 ? 1 : (value > -0.4 && value < 0.4) ? 0 : last + guard sign != last else { return } + axes[id] = sign + if last == -1 { padUp(neg) } else if last == 1 { padUp(pos) } + if sign == -1 { padDown(neg) } else if sign == 1 { padDown(pos) } + } + + private func padDown(_ code: Int) { + if router.learnSource == .gamepad { + if !learnSeq.contains(code) { learnSeq.append(code) } + if !heldPad.contains(code) { heldPad.append(code) } + return + } + // A chord first: any control already held may be the modifier. + for mod in heldPad { + if let id = bindings.gamepad[GamepadChord(modifier: mod, code: code)] { + heldPad.append(code) + if let a = InputActions.action(id) { router.pressRepeat(AnyHashable("g\(code)"), a) } + return + } + } + if !heldPad.contains(code) { heldPad.append(code) } + if let id = bindings.gamepad[GamepadChord(modifier: 0, code: code)], let a = InputActions.action(id) { + router.pressRepeat(AnyHashable("g\(code)"), a) + } + } + + private func padUp(_ code: Int) { + heldPad.removeAll { $0 == code } + router.releaseRepeat(AnyHashable("g\(code)")) + // A learn capture ends once every control of the combo is released. + if router.learnSource == .gamepad, !learnSeq.isEmpty, !heldPad.contains(where: learnSeq.contains) { + let main = learnSeq.last!, mod = learnSeq.count >= 2 ? learnSeq.first! : 0 + learnSeq.removeAll() + router.dispatch(.raw(source: .gamepad, code: main, value: 1, modifier: mod)) + } + } +} + +#if canImport(UIKit) +extension UIResponder { + @objc fileprivate func sizzleFindFirstResponder(_ sender: Any?) { HardwareInput.found = self } +} +#endif diff --git a/ios/app/Host/Input/InputAction.swift b/ios/app/Host/Input/InputAction.swift new file mode 100644 index 0000000..94fa9e0 --- /dev/null +++ b/ios/app/Host/Input/InputAction.swift @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// Android's InputAction: every hardware source (keyboard, gamepad, MIDI) becomes +/// one of these, so a feature is written once (AppModel+Input) and works from all. +enum InputAction: Equatable { + case navUp, navDown, navLeft, navRight + case nextColumn, prevColumn + case increment(Int), decrement(Int) + case clearCell, noteOffCell + /// [channel] 1..16 for MIDI, -1 for a source without one (the keyboard's piano); + /// [sounded]: the MIDI sound module already played it (only show / punch it in). + case noteOn(pitch: Int, velocity: Int, channel: Int, sounded: Bool) + case noteOff(pitch: Int, channel: Int, sounded: Bool) + case playPause, stop, toggleLoop + case selectTab(Int), nextTab, prevTab + /// An unbound control (a MIDI CC, a key or a gamepad chord during learn). + /// [modifier]: the held gamepad control of a chord, 0 for none. + case raw(source: InputSource, code: Int, value: Float, modifier: Int) + + /// Cursor and value steps repeat while their control is held. + var isRepeatable: Bool { + switch self { + case .navUp, .navDown, .navLeft, .navRight, .nextColumn, .prevColumn, .increment, .decrement: return true + default: return false + } + } +} + +enum InputSource { case touch, keyboard, gamepad, midi } + +/// Android's InputActions: the stable action ids the binding maps store, and what +/// each one does. Settings lists them in this order. +enum InputActions { + static let all: [(id: String, label: String)] = [ + ("playPause", "Play / Pause"), ("stop", "Stop"), ("loop", "Loop on/off"), + ("up", "Cursor up"), ("down", "Cursor down"), ("left", "Cursor left"), ("right", "Cursor right"), + ("nextColumn", "Next column"), ("prevColumn", "Previous column"), + ("increment", "Value +1"), ("decrement", "Value −1"), ("clear", "Clear cell"), ("noteOff", "Note-off"), + ("nextTab", "Next tab"), ("prevTab", "Previous tab"), + ] + + static func action(_ id: String) -> InputAction? { + switch id { + case "playPause": return .playPause + case "stop": return .stop + case "loop": return .toggleLoop + case "up": return .navUp + case "down": return .navDown + case "left": return .navLeft + case "right": return .navRight + case "increment": return .increment(1) + case "decrement": return .decrement(1) + case "clear": return .clearCell + case "noteOff": return .noteOffCell + case "nextColumn": return .nextColumn + case "prevColumn": return .prevColumn + case "nextTab": return .nextTab + case "prevTab": return .prevTab + default: return nil + } + } +} + +/// Android's InputRouter: one dispatch point, the shared accelerating +/// hold-to-repeat (320 ms, ×0.8 per step, down to 45 ms) and the learn state. +@MainActor +final class InputRouter: ObservableObject { + static let shared = InputRouter() + + /// Set by AppModel: what happens with each action. + var handler: ((InputAction) -> Void)? + /// While set, the next control of this source is captured as a binding. + @Published var learnSource: InputSource? + + private var repeatKey: AnyHashable? + private var repeatTimer: Timer? + + func dispatch(_ a: InputAction) { handler?(a) } + + /// Fire [action] for a press and, if it repeats, keep firing while [key] is held. + func pressRepeat(_ key: AnyHashable, _ action: InputAction) { + dispatch(action) + guard action.isRepeatable else { return } + repeatTimer?.invalidate() + repeatKey = key + schedule(action, after: 0.32) + } + + private func schedule(_ action: InputAction, after interval: TimeInterval) { + repeatTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in + Task { @MainActor in + guard let self = self, self.repeatKey != nil else { return } + self.dispatch(action) + self.schedule(action, after: max(0.045, interval * 0.8)) + } + } + } + + func releaseRepeat(_ key: AnyHashable) { + guard repeatKey == key else { return } + repeatTimer?.invalidate() + repeatTimer = nil + repeatKey = nil + } +} diff --git a/ios/app/Host/Input/InputBindings.swift b/ios/app/Host/Input/InputBindings.swift new file mode 100644 index 0000000..10869ef --- /dev/null +++ b/ios/app/Host/Input/InputBindings.swift @@ -0,0 +1,212 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// A gamepad binding: a control, optionally while another is held (Android's +/// GamepadChord). modifier 0 = none. +struct GamepadChord: Hashable { + let modifier: Int + let code: Int +} + +/// The three rebindable maps (Android's KeyboardInput / GamepadInput / MidiInput +/// bindings, persisted like BindingStore: one `code=actionId` line each, gamepad +/// `modifier:code=actionId`). Keyboard codes are USB HID usages (GCKeyCode). +@MainActor +final class InputBindings: ObservableObject { + static let shared = InputBindings() + + @Published private(set) var keyboard: [Int: String] + @Published private(set) var gamepad: [GamepadChord: String] + @Published private(set) var midi: [Int: String] + + private init() { + let s = AppSettings.shared + keyboard = s.keyboardBindings.map(Self.decodeInt) ?? Self.defaultKeyboard + gamepad = s.gamepadBindings.map(Self.decodeChord) ?? Self.defaultGamepad + midi = s.midiBindings.map(Self.decodeInt) ?? [:] + } + + /// After a backup restore: read the maps from the settings again. + func reload() { + let s = AppSettings.shared + keyboard = s.keyboardBindings.map(Self.decodeInt) ?? Self.defaultKeyboard + gamepad = s.gamepadBindings.map(Self.decodeChord) ?? Self.defaultGamepad + midi = s.midiBindings.map(Self.decodeInt) ?? [:] + } + + // Each action keeps at most one binding per device kind (Android's learn). + func bindKey(_ code: Int, to id: String) { keyboard = keyboard.filter { $0.value != id }; keyboard[code] = id; save() } + func bindGamepad(_ chord: GamepadChord, to id: String) { gamepad = gamepad.filter { $0.value != id }; gamepad[chord] = id; save() } + func bindMidi(_ cc: Int, to id: String) { midi = midi.filter { $0.value != id }; midi[cc] = id; save() } + + func clear(_ id: String, source: InputSource) { + switch source { + case .keyboard: keyboard = keyboard.filter { $0.value != id } + case .gamepad: gamepad = gamepad.filter { $0.value != id } + case .midi: midi = midi.filter { $0.value != id } + case .touch: return + } + save() + } + + func resetDefaults(_ source: InputSource) { + switch source { + case .keyboard: keyboard = Self.defaultKeyboard + case .gamepad: gamepad = Self.defaultGamepad + case .midi: midi = [:] + case .touch: return + } + save() + } + + func keyFor(_ id: String) -> Int? { keyboard.first { $0.value == id }?.key } + func chordFor(_ id: String) -> GamepadChord? { gamepad.first { $0.value == id }?.key } + func ccFor(_ id: String) -> Int? { midi.first { $0.value == id }?.key } + + private func save() { + let s = AppSettings.shared + s.keyboardBindings = keyboard.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: "\n") + s.gamepadBindings = gamepad.map { "\($0.key.modifier):\($0.key.code)=\($0.value)" }.sorted().joined(separator: "\n") + s.midiBindings = midi.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: "\n") + } + + private static func decodeInt(_ s: String) -> [Int: String] { + var out: [Int: String] = [:] + for line in s.split(separator: "\n") { + guard let eq = line.firstIndex(of: "="), eq > line.startIndex, let code = Int(line[.. [GamepadChord: String] { + var out: [GamepadChord: String] = [:] + for line in s.split(separator: "\n") { + guard let eq = line.firstIndex(of: "=") else { continue } + let parts = line[.. Int { + if let v = c.asciiValue, v >= 97, v <= 122 { return Int(v) - 97 + 4 } // a..z + if c == "0" { return 39 } + return Int(c.asciiValue! - 49) + 30 // 1..9 + } + + static func keyLabel(_ code: Int) -> String { + switch code { + case 4...29: return String(UnicodeScalar(UInt8(code - 4 + 65))) + case 30...38: return String(code - 29) + case 39: return "0" + case Key.enter: return "Return" + case 41: return "Esc" + case Key.backspace: return "Delete" + case Key.tab: return "Tab" + case Key.space: return "Space" + case Key.minus: return "-" + case Key.equals: return "=" + case 47: return "[" + case 48: return "]" + case 49: return "\\" + case 51: return ";" + case 52: return "'" + case Key.grave: return "`" + case 54: return "," + case 55: return "." + case 56: return "/" + case 58...69: return "F\(code - 57)" + case 74: return "Home" + case Key.pageUp: return "Page Up" + case 76: return "Fwd Delete" + case 77: return "End" + case Key.pageDown: return "Page Down" + case Key.right: return "→" + case Key.left: return "←" + case Key.down: return "↓" + case Key.up: return "↑" + default: return "Key \(code)" + } + } + + // MARK: Gamepad controls + + enum Pad { + static let a = 1, b = 2, x = 3, y = 4, l1 = 5, r1 = 6, l2 = 7, r2 = 8, menu = 9, options = 10, l3 = 11, r3 = 12 + static let up = 20, down = 21, left = 22, right = 23 + static let lsLeft = 0x20001, lsRight = 0x20002, lsUp = 0x20003, lsDown = 0x20004 + static let rsLeft = 0x20005, rsRight = 0x20006, rsUp = 0x20007, rsDown = 0x20008 + } + + static let defaultGamepad: [GamepadChord: String] = { + let plain: [(Int, String)] = [ + (Pad.a, "playPause"), (Pad.b, "stop"), (Pad.x, "clear"), (Pad.y, "loop"), (Pad.l1, "prevTab"), (Pad.r1, "nextTab"), + (Pad.up, "up"), (Pad.down, "down"), (Pad.left, "left"), (Pad.right, "right"), + (Pad.lsUp, "up"), (Pad.lsDown, "down"), (Pad.lsLeft, "left"), (Pad.lsRight, "right"), + (Pad.rsUp, "increment"), (Pad.rsDown, "decrement"), + ] + return Dictionary(uniqueKeysWithValues: plain.map { (GamepadChord(modifier: 0, code: $0.0), $0.1) }) + }() + + static func padLabel(_ code: Int) -> String { + switch code { + case Pad.a: return "A" + case Pad.b: return "B" + case Pad.x: return "X" + case Pad.y: return "Y" + case Pad.l1: return "L1" + case Pad.r1: return "R1" + case Pad.l2: return "L2" + case Pad.r2: return "R2" + case Pad.menu: return "Menu" + case Pad.options: return "Options" + case Pad.l3: return "L3" + case Pad.r3: return "R3" + case Pad.up: return "UP" + case Pad.down: return "DOWN" + case Pad.left: return "LEFT" + case Pad.right: return "RIGHT" + case Pad.lsLeft: return "LS←" + case Pad.lsRight: return "LS→" + case Pad.lsUp: return "LS↑" + case Pad.lsDown: return "LS↓" + case Pad.rsLeft: return "RS←" + case Pad.rsRight: return "RS→" + case Pad.rsUp: return "RS↑" + case Pad.rsDown: return "RS↓" + default: return "#\(code)" + } + } + + static func chordLabel(_ c: GamepadChord) -> String { + c.modifier == 0 ? padLabel(c.code) : padLabel(c.modifier) + " + " + padLabel(c.code) + } +} diff --git a/ios/app/Host/Input/InputController.swift b/ios/app/Host/Input/InputController.swift new file mode 100644 index 0000000..d6822bf --- /dev/null +++ b/ios/app/Host/Input/InputController.swift @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// What the app does with input actions (Android's AppViewModel.onAction and its +/// learn / parameter-CC code), and the MIDI controller side of MidiInput +/// (CC bindings, momentary navigation pads). +@MainActor +final class InputController: ObservableObject { + static let shared = InputController() + + /// The app model actions apply to (set at launch). + weak var app: AppModel? + + /// Settings' learn: the action whose binding the next control of [learnSource] sets. + @Published private(set) var learnTarget: String? + /// Toolbox parameter MIDI learn: the next CC moved binds to this slot's parameter. + @Published private(set) var paramLearnSlot = -1 + @Published private(set) var paramLearnKey: String? + + /// Android's lastNote / lastChannel: seeds for stepping an empty cell. + private var lastNote = 60 + private var lastChannel = 0 + + private var router: InputRouter { InputRouter.shared } + private var session: SizzleSession { SizzleSession.shared } + static let ccPrefix = "midicc@" + + func start() { + router.handler = { [weak self] in self?.handle($0) } + } + + // MARK: Actions + + func handle(_ action: InputAction) { + guard let app = app else { return } + let tracker = TrackerState.shared + switch action { + case .navUp: tracker.moveCursorWrap(app, -tracker.skipStep) + case .navDown: tracker.moveCursorWrap(app, tracker.skipStep) + case .navLeft: moveColumnFlat(app, -1) + case .navRight: moveColumnFlat(app, 1) + case .nextColumn: app.cursorColumn = AppModel.Column(rawValue: (app.cursorColumn.rawValue + 1) % 3)! + case .prevColumn: app.cursorColumn = AppModel.Column(rawValue: (app.cursorColumn.rawValue + 2) % 3)! + case .increment(let n): editFocused(app, n) + case .decrement(let n): editFocused(app, -n) + case .clearCell: + session.clearCells(inPattern: session.activePattern, fromTrack: app.cursorTrack, toTrack: app.cursorTrack, + fromLine: app.cursorLine, toLine: app.cursorLine) + case .noteOffCell: tracker.noteOffFocused(app) + case let .noteOn(pitch, velocity, channel, sounded): + TrackerHeldNotes.shared.mark(pitch, on: true) + let ch = channel >= 1 ? channel : app.kbdChannel + if !sounded { session.note(on: pitch, velocity: velocity, midiChannel: ch) } + if app.tab == .tracker && tracker.punchInMode { + tracker.punchNote(app, pitch, velocity: velocity, channel: ch) + lastNote = pitch; lastChannel = ch + } + case let .noteOff(pitch, channel, sounded): + TrackerHeldNotes.shared.mark(pitch, on: false) + if !sounded { session.noteOff(pitch, midiChannel: channel >= 1 ? channel : app.kbdChannel) } + case .playPause: tracker.playPause() + case .stop: tracker.stop() + case .toggleLoop: session.arrangementLoop = !session.arrangementLoop + case .selectTab(let i): app.tab = AppModel.Tab(rawValue: min(max(i, 0), 3))! + case .nextTab: app.tab = AppModel.Tab(rawValue: min(app.tab.rawValue + 1, 3))! + case .prevTab: app.tab = AppModel.Tab(rawValue: max(app.tab.rawValue - 1, 0))! + case let .raw(source, code, value, modifier): onRaw(source, code, value, modifier) + } + } + + /// The three columns of every track laid end to end (Android's moveColumnFlat). + private func moveColumnFlat(_ app: AppModel, _ dir: Int) { + let flat = min(max(app.cursorTrack * 3 + app.cursorColumn.rawValue + dir, 0), 11) + app.cursorTrack = flat / 3 + app.cursorColumn = AppModel.Column(rawValue: flat % 3)! + } + + /// Android's editFocused: the note steps within the scale (an empty cell starts + /// from the last note entered), velocity and channel step by one. + private func editFocused(_ app: AppModel, _ dir: Int) { + let p = session.activePattern + var c = session.cell(inPattern: p, track: app.cursorTrack, line: app.cursorLine) + if c.note == -2 && app.cursorColumn != .note { return } // a note-off has only its note + switch app.cursorColumn { + case .note: + let seed = c.note >= 0 ? Int(c.note) : lastNote + let inKey = Set(session.scalePitchClasses.map { $0.intValue }) + var n = seed + repeat { + n += dir + if n < 0 || n > 127 { n = seed; break } + } while !inKey.contains(n % 12) + c.note = Int32(n) + lastNote = n + if c.channel == 0 { c.channel = Int32(max(lastChannel, 1)) } + case .velocity: + c.velocity = Int32(min(max(Int(c.velocity) + dir, 0), 127)) + case .channel: + let seed = c.note == -1 ? lastChannel : Int(c.channel) + c.channel = Int32(min(max(seed + dir, 1), 16)) + lastChannel = Int(c.channel) + } + session.setCell(c, inPattern: p, track: app.cursorTrack, line: app.cursorLine) + } + + // MARK: MIDI controllers (MidiInput.handleCc) + + func midiControl(_ cc: Int, _ value: Int) { + guard let id = InputBindings.shared.midi[cc], router.learnSource != .midi else { + router.dispatch(.raw(source: .midi, code: cc, value: Float(value) / 127, modifier: 0)) + return + } + // Navigation pads are momentary: press (>= 64) starts the hold-to-repeat, + // release ends it. + let key = AnyHashable("m\(cc)") + switch id { + case "up", "down", "left", "right": + if value >= 64, let a = InputActions.action(id) { router.pressRepeat(key, a) } else { router.releaseRepeat(key) } + case "increment", "decrement": + if let a = InputActions.action(id) { router.dispatch(a) } + default: + if value >= 64, let a = InputActions.action(id) { router.dispatch(a) } + } + } + + func midiNote(on: Bool, channel: Int, note: Int, velocity: Int) { + router.dispatch(on ? .noteOn(pitch: note, velocity: velocity, channel: channel, sounded: true) + : .noteOff(pitch: note, channel: channel, sounded: true)) + } + + // MARK: Learn + + func beginLearn(_ id: String, source: InputSource) { + cancelParamLearn() + learnTarget = id + router.learnSource = source + } + + func cancelLearn() { + learnTarget = nil + router.learnSource = nil + } + + func beginParamLearn(slot: Int, key: String) { + cancelLearn() + paramLearnSlot = slot + paramLearnKey = key + router.learnSource = .midi + } + + func cancelParamLearn() { + paramLearnSlot = -1 + paramLearnKey = nil + if learnTarget == nil { router.learnSource = nil } + } + + func paramCc(slot: Int, key: String) -> Int? { Int(session.value(ofSlot: slot, key: Self.ccPrefix + key)) } + + func clearParamCc(slot: Int, key: String) { session.setValue("", ofSlot: slot, key: Self.ccPrefix + key) } + + private func onRaw(_ source: InputSource, _ code: Int, _ value: Float, _ modifier: Int) { + if let key = paramLearnKey { + if source == .midi { bindParamCc(slot: paramLearnSlot, key: key, cc: code); cancelParamLearn() } + return + } + guard let target = learnTarget else { + if source == .midi { applyParamCc(code, value) } // a CC bound to toolbox parameters drives them + return + } + guard source == router.learnSource else { return } + let b = InputBindings.shared + switch source { + case .midi: b.bindMidi(code, to: target) + case .gamepad: b.bindGamepad(GamepadChord(modifier: modifier, code: code), to: target) + case .keyboard: b.bindKey(code, to: target) + case .touch: break + } + cancelLearn() + } + + /// One physical control drives one parameter: the CC leaves any other first. + private func bindParamCc(slot: Int, key: String, cc: Int) { + for s in 0..<16 where !session.type(ofSlot: s).isEmpty { + for spec in SizzleSession.paramSpecs(forType: session.type(ofSlot: s)) where paramCc(slot: s, key: spec.key) == cc { + clearParamCc(slot: s, key: spec.key) + } + } + session.setValue(String(cc), ofSlot: slot, key: Self.ccPrefix + key) + } + + private func applyParamCc(_ cc: Int, _ norm: Float) { + let n = min(max(norm, 0), 1) + for s in 0..<16 { + let type = session.type(ofSlot: s) + if type.isEmpty { continue } + for spec in SizzleSession.paramSpecs(forType: type) where paramCc(slot: s, key: spec.key) == cc { + if !spec.choices.isEmpty { + let i = min(max(Int((n * Float(spec.choices.count - 1)).rounded()), 0), spec.choices.count - 1) + session.setValue(spec.choices[i], ofSlot: s, key: spec.key) + } else { + var v = spec.minValue + n * (spec.maxValue - spec.minValue) + if spec.isInt { v = v.rounded() } + session.setNumber(v, ofSlot: s, key: spec.key) + } + } + } + } +} diff --git a/ios/app/Host/RootView.swift b/ios/app/Host/RootView.swift index 75207fd..60aa585 100644 --- a/ios/app/Host/RootView.swift +++ b/ios/app/Host/RootView.swift @@ -7,6 +7,8 @@ import SwiftUI /// portrait and a side rail in landscape, as the Android app's App.kt lays them out. struct RootView: View { @ObservedObject private var app: AppModel + /// The whole tree is rebuilt when the theme changes (Theme is read, not observed). + @ObservedObject private var settings = AppSettings.shared init(model: AppModel? = nil) { app = model ?? AppModel.main } @Environment(\.scenePhase) private var phase @Environment(\.verticalSizeClass) private var vClass @@ -24,8 +26,15 @@ struct RootView: View { .background(Theme.background.ignoresSafeArea()) } .environmentObject(app) + .id(settings.paletteName) .preferredColorScheme(.dark) - .onChange(of: phase) { p in if p != .active { app.session.autosave() } } + .onChange(of: phase) { p in + switch p { + case .background: AppBoot.background() + case .active: AppBoot.foreground() + default: app.session.autosave() + } + } } @ViewBuilder private var screen: some View { diff --git a/ios/app/Host/SampleRecorder.swift b/ios/app/Host/SampleRecorder.swift new file mode 100644 index 0000000..7c23082 --- /dev/null +++ b/ios/app/Host/SampleRecorder.swift @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import AVFoundation +import SwiftUI + +/// Android's SampleRecorder: records the microphone (or a connected audio +/// interface's input) into a sample, at most 30 seconds. The audio session switches +/// to play-and-record only while recording, so playback keeps its normal routing +/// otherwise. Main thread. +@MainActor +final class SampleRecorder: ObservableObject { + static let shared = SampleRecorder() + + @Published private(set) var isRecording = false + @Published var error: String? + + private var recorder: AVAudioRecorder? + private let file = FileManager.default.temporaryDirectory.appendingPathComponent("sample-rec.wav") + + func start() { + guard !isRecording else { return } + #if os(iOS) + AVAudioSession.sharedInstance().requestRecordPermission { granted in + Task { @MainActor in + if granted { self.begin() } else { self.error = "Sizzle has no microphone access. Allow it in Settings › Privacy › Microphone." } + } + } + #endif + } + + #if os(iOS) + private func begin() { + let s = AVAudioSession.sharedInstance() + do { + try s.setCategory(.playAndRecord, options: [.defaultToSpeaker, .allowBluetoothA2DP, .mixWithOthers]) + try s.setActive(true) + let r = try AVAudioRecorder(url: file, settings: [ + AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 44_100, AVNumberOfChannelsKey: 1, + AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false, + ]) + guard r.record(forDuration: 30) else { throw CocoaError(.fileWriteUnknown) } + recorder = r + isRecording = true + } catch { + restoreSession() + self.error = "Couldn't start recording: \(error.localizedDescription)" + } + } + #endif + + /// Stop and return the take as WAV data (nil if nothing was captured). + func stop() -> Data? { + guard let r = recorder else { return nil } + r.stop() + recorder = nil + isRecording = false + restoreSession() + defer { try? FileManager.default.removeItem(at: file) } + guard let data = try? Data(contentsOf: file), data.count > 44 else { return nil } + return data + } + + private func restoreSession() { + #if os(iOS) + try? AVAudioSession.sharedInstance().setCategory(.playback) + #endif + } + + private static var stamp: String { "rec-\(Int(Date().timeIntervalSince1970 * 1000))" } + + /// Stop and put the take on Sampler [slot]'s [pad] (Android: stopRecordingInto). + func stopInto(slot: Int, pad: Int) { + guard let data = stop() else { return } + do { try SizzleSession.shared.loadSampleData(data, name: Self.stamp, intoSlot: slot, pad: pad) } + catch { self.error = error.localizedDescription } + } + + /// Stop and make the take Grain Cloud [slot]'s source (Android: stopRecordingIntoGrain). + func stopIntoGrain(slot: Int) { + guard let data = stop() else { return } + do { try SizzleSession.shared.loadGrainSourceData(data, name: Self.stamp, intoSlot: slot) } + catch { self.error = error.localizedDescription } + } +} diff --git a/ios/app/Host/Screens/Mix/MixKit.swift b/ios/app/Host/Screens/Mix/MixKit.swift index d538c41..f7dae03 100644 --- a/ios/app/Host/Screens/Mix/MixKit.swift +++ b/ios/app/Host/Screens/Mix/MixKit.swift @@ -7,9 +7,9 @@ import SwiftUI /// components/Widgets.kt (RetroButton, RepeatButton, RetroDropdown, SectionLabel). /// Namespaced so they can't clash with the other screens' own. enum MixKit { - /// Android palette colours the shared Theme doesn't carry. - static let playhead = Color(red: 0x7C / 255, green: 0xFC / 255, blue: 0x9A / 255) - static let danger = Color(red: 0xE0 / 255, green: 0x5A / 255, blue: 0x4B / 255) + /// The theme's playhead and danger colours. + static var playhead: Color { Theme.playhead } + static var danger: Color { Theme.danger } /// Pitch.name: 60 -> "C-4", 61 -> "C#4". static func pitchName(_ midi: Int) -> String { diff --git a/ios/app/Host/Screens/Mix/MixScreen.swift b/ios/app/Host/Screens/Mix/MixScreen.swift index ebca0b8..24e6b39 100644 --- a/ios/app/Host/Screens/Mix/MixScreen.swift +++ b/ios/app/Host/Screens/Mix/MixScreen.swift @@ -28,18 +28,53 @@ private struct MixBody: View { if inst { instruments.append(i) } else { effects.append(i) } } let names = (0..<16).map { session.name(ofSlot: $0) } - return GeometryReader { geo in - let landscape = geo.size.width > geo.size.height - HStack(spacing: 6) { - ForEach(0..<4, id: \.self) { ch in - ChannelStrip(ch: ch, landscape: landscape, instruments: instruments, effects: effects, names: names, - open: { ToolboxNav.open($0, app: app, returnTab: .mix) }) - .frame(maxWidth: .infinity, maxHeight: .infinity) + return VStack(spacing: 0) { + RecordToolbar(session: session) + GeometryReader { geo in + let landscape = geo.size.width > geo.size.height + HStack(spacing: 6) { + ForEach(0..<4, id: \.self) { ch in + ChannelStrip(ch: ch, landscape: landscape, instruments: instruments, effects: effects, names: names, + open: { ToolboxNav.open($0, app: app, returnTab: .mix) }) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } } + .padding(6) + } + } + .background(Theme.background) + } +} + +/// Android's RecordToolbar: arm the master recording (it starts on Play or an +/// external MIDI clock Start), the FX tail after the stop, and the last take. Takes +/// are saved in Sizzle's Recordings folder (Files app); SHARE sends the last one. +private struct RecordToolbar: View { + let session: SizzleSession + + var body: some View { + let recording = session.masterRecording + let last = session.lastRecordingURL + let status: String = recording ? "recording…" + : session.recordArmed ? "armed — starts on play or MIDI clock start" + : last.map { "saved \($0.lastPathComponent)" } ?? "master → WAV (Files › Sizzle › Recordings)" + MixKit.HScroll { + HStack(spacing: 6) { + MixKit.Button(label: recording ? "● REC" : "● ARM", active: session.recordArmed && !recording, danger: recording) { + session.recordArmed = !session.recordArmed + } + MixKit.Dropdown(label: "TAIL", options: [0, 1, 2, 3, 4], selected: session.recordTailBars, + optionLabel: { "\($0) bar" + ($0 == 1 ? "" : "s") }, + onSelect: { session.recordTailBars = $0; AppSettings.shared.recordTailBars = $0 }) + if let url = last, !recording { + MixKit.Button(label: "SHARE") { ShareSheet.present(url) } + } + Text(status).font(Theme.mono(11)).foregroundColor(Theme.dim).lineLimit(1) } .padding(6) } - .background(Theme.background) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Theme.surface) } } @@ -133,7 +168,7 @@ private struct VolumeFader: View { ZStack(alignment: .top) { Theme.background Rectangle().fill(Theme.accent.opacity(0.30)).frame(height: vol * h).offset(y: top) - MeterLayer(ch: ch, volume: vol) + if AppSettings.shared.vuMeters { MeterLayer(ch: ch, volume: vol) } Rectangle().fill(Theme.accent).frame(height: 3).offset(y: min(max(top - 1.5, 0), max(h - 3, 0))) } .frame(width: g.size.width, height: h, alignment: .top) diff --git a/ios/app/Host/Screens/Setup/BindingsSheet.swift b/ios/app/Host/Screens/Setup/BindingsSheet.swift new file mode 100644 index 0000000..a601cde --- /dev/null +++ b/ios/app/Host/Screens/Setup/BindingsSheet.swift @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// One device kind's bindings (Android's binding sections and BindingRow): each +/// action with its current control, LEARN (then press the key / combo or move the +/// MIDI control) and ✕ to unbind. +struct BindingsSheet: View { + let source: InputSource + @ObservedObject private var bindings = InputBindings.shared + @ObservedObject private var input = InputController.shared + @Environment(\.dismiss) private var dismiss + + private struct Group { let title: String; let actions: [(id: String, label: String)] } + + private var groups: [Group] { + var g = [ + Group(title: "Transport", actions: [("playPause", "Play / Pause"), ("stop", "Stop"), ("loop", "Toggle Loop")]), + Group(title: "Navigation", actions: [("up", "Cursor Up"), ("down", "Cursor Down"), ("left", "Cursor Left"), ("right", "Cursor Right")]), + Group(title: "Editing", actions: [("increment", "Value +"), ("decrement", "Value -"), ("clear", "Clear Cell")] + + (source == .keyboard ? [("noteOff", "Note Off")] : [])), + ] + if source == .keyboard { + g.append(Group(title: "Columns", actions: [("nextColumn", "Next Column"), ("prevColumn", "Prev Column")])) + g.append(Group(title: "Octave", actions: [("octaveDown", "Octave Down"), ("octaveUp", "Octave Up")])) + } + g.append(Group(title: "Tabs", actions: [("nextTab", "Next Tab"), ("prevTab", "Prev Tab")])) + return g + } + + private var title: String { + switch source { + case .gamepad: return "Gamepad Bindings" + case .keyboard: return "Keyboard Hotkeys" + default: return "MIDI Bindings" + } + } + + private var hint: String { + switch source { + case .gamepad: return "LEARN, then press a button, D-pad direction or stick direction — or hold one and press another for a combo." + case .keyboard: return "LEARN, then press a key. Unbound letter keys play the tracker piano (Z…M, Q…U)." + default: return "LEARN, then press a pad or move a control on your MIDI controller (CC)." + } + } + + private func label(_ id: String) -> String? { + switch source { + case .gamepad: return bindings.chordFor(id).map(InputBindings.chordLabel) + case .keyboard: return bindings.keyFor(id).map(InputBindings.keyLabel) + default: return bindings.ccFor(id).map { "CC \($0)" } + } + } + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Text(title).font(.system(size: 19, weight: .semibold)).foregroundColor(Theme.accent) + Spacer() + SetupButton(title: "Defaults") { bindings.resetDefaults(source) } + SetupButton(title: "Done", kind: .filled) { dismiss() } + } + Text(hint).font(.system(size: 12)).foregroundColor(Theme.dim) + ScrollView { + VStack(alignment: .leading, spacing: 12) { + ForEach(groups, id: \.title) { group in + VStack(alignment: .leading, spacing: 4) { + Text(group.title.uppercased()).font(.system(size: 11, weight: .semibold)).foregroundColor(Theme.dim) + ForEach(group.actions, id: \.id) { a in row(a.id, a.label) } + } + } + } + } + } + .padding(20) + .background(Theme.surface.ignoresSafeArea()) + .preferredColorScheme(.dark) + .onDisappear { input.cancelLearn() } + } + + private func row(_ id: String, _ text: String) -> some View { + let listening = input.learnTarget == id + let bound = label(id) + return HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 2) { + Text(text).font(.system(size: 15)).foregroundColor(Theme.text) + Text(bound ?? "unbound").font(.system(size: 12, design: .monospaced)).foregroundColor(bound == nil ? Theme.dim : Theme.accent) + } + Spacer() + SetupButton(title: listening ? "Listening…" : "Learn", kind: listening ? .filled : .outlined) { + if listening { input.cancelLearn() } else { input.beginLearn(id, source: source) } + } + if bound != nil { + Button { bindings.clear(id, source: source) } label: { + Image(systemName: "xmark").foregroundColor(Theme.dim).frame(width: 36, height: 36) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, 2) + } +} diff --git a/ios/app/Host/Screens/Setup/SetupCards.swift b/ios/app/Host/Screens/Setup/SetupCards.swift new file mode 100644 index 0000000..3ce6b9d --- /dev/null +++ b/ios/app/Host/Screens/Setup/SetupCards.swift @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// A labelled switch (Android's ToggleRow). +struct SetupToggle: View { + let title: String + let detail: String + let isOn: Bool + let onChange: (Bool) -> Void + + var body: some View { + Toggle(isOn: Binding(get: { isOn }, set: onChange)) { + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.system(size: 15, weight: .medium)).foregroundColor(Theme.text) + Text(detail).font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true) + } + } + .tint(Theme.accent) + } +} + +/// Audio Devices: iOS picks the route; this shows it and offers the system picker. +struct AudioDevicesCard: View { + var body: some View { + SetupCard(title: "Audio Devices", subtitle: "Playback and recording go where iOS routes audio") { + AudioRouteView() + SetupNote("Plug in an audio interface or headphones, or pick AirPlay / Bluetooth with the route button. " + + "The sample recorder records from the current input.") + } + } +} + +/// Recording: where master takes go and the FX tail (the ARM button is on Mix). +struct RecordingCard: View { + @ObservedObject var settings = AppSettings.shared + + var body: some View { + SetupCard(title: "Recording", subtitle: "Record the master bus to WAV files") { + HStack(spacing: 8) { + Text("FX tail after stop").font(.system(size: 15)).foregroundColor(Theme.text) + Spacer() + ForEach(0..<5, id: \.self) { n in + SetupButton(title: "\(n)", kind: settings.recordTailBars == n ? .filled : .outlined) { + settings.recordTailBars = n + SizzleSession.shared.recordTailBars = n + } + } + } + SetupNote("Arm with ● ARM on the Mix tab; the take starts on Play (or an external MIDI clock Start) and " + + "ends this many bars after the stop. Takes are in Files › On My iPad › Sizzle › Recordings.") + } + } +} + +/// Interface: the mixer meters (Android's InterfaceCard). +struct InterfaceCard: View { + @ObservedObject var settings = AppSettings.shared + + var body: some View { + SetupCard(title: "Interface", subtitle: "On-screen display options") { + SetupToggle(title: "Mixer VU meters", detail: "Show live level meters inside the mixer volume faders.", + isOn: settings.vuMeters) { settings.vuMeters = $0 } + } + } +} + +/// Color Theme: pick, import, export or delete (Android's ThemeCard). +struct ThemeCard: View { + @ObservedObject var library = ThemeLibrary.shared + let onImport: () -> Void + let onDelete: (String) -> Void + let onError: (String) -> Void + + var body: some View { + let current = Theme.current.name + SetupCard(title: "Color Theme", subtitle: "Pick, import, export or delete a palette") { + HStack(spacing: 8) { + Menu { + ForEach(library.names, id: \.self) { name in + Button(name + (library.isStock(name) ? " (stock)" : "")) { library.select(name) } + } + } label: { + HStack(spacing: 6) { + Text(current).font(.system(size: 15, weight: .medium)).lineLimit(1) + Image(systemName: "chevron.down").font(.system(size: 12)) + } + .foregroundColor(Theme.text) + .padding(.horizontal, 14).frame(minHeight: 38) + .overlay(Capsule().stroke(Theme.grid, lineWidth: 1)) + } + if !library.isStock(current) { + SetupButton(title: "Delete", kind: .danger) { onDelete(current) } + } + } + SetupDivider() + HStack(spacing: 8) { + SetupButton(title: "Export .szt", icon: "square.and.arrow.up") { + do { ShareSheet.present(try library.exportFile()) } catch { onError(error.localizedDescription) } + } + SetupButton(title: "Import .szt", icon: "square.and.arrow.down.on.square", action: onImport) + } + SetupNote("Stock themes can't be deleted; imported .szt themes appear in the list.") + } + } +} + +/// MIDI Sync: clock out / in, sound-module mode and the MIDI sources (Android's +/// MidiSyncCard + MidiInputsList). +struct MidiSyncCard: View { + @ObservedObject var settings = AppSettings.shared + @ObservedObject var midi = MidiSources.shared + + var body: some View { + SetupCard(title: "MIDI Sync", subtitle: "MIDI clock and notes over USB, Bluetooth, network and other apps") { + SetupToggle(title: "Send MIDI clock", + detail: "Send clock, start/stop and the tracks' notes to MIDI devices and apps, so Sizzle drives them.", + isOn: settings.sendMidiClock) { settings.sendMidiClock = $0; SizzleMidi.shared.sendClock = $0 } + SetupDivider() + SetupToggle(title: "Receive MIDI clock", + detail: "Follow an external clock's tempo, and start/stop Sizzle's own song with it " + + "(tempo only while Sizzle runs as a MIDI sound module).", + isOn: settings.receiveMidiClock) { settings.receiveMidiClock = $0; SizzleMidi.shared.receiveClock = $0 } + SetupDivider() + SetupToggle(title: "Keep running as MIDI sound module", + detail: "Keep playing incoming MIDI with Sizzle in the background (another app can use it as its synth). " + + "Sizzle's own song doesn't start from the other app's clock meanwhile.", + isOn: settings.soundModule) { settings.soundModule = $0; SizzleMidi.shared.soundModule = $0 } + SetupDivider() + HStack { + VStack(alignment: .leading, spacing: 2) { + Text("MIDI inputs").font(.system(size: 15, weight: .medium)).foregroundColor(Theme.text) + Text("Sources Sizzle listens to. Each mixer track plays the notes on its MIDI channel. " + + "Other apps can also send to the \"Sizzle\" MIDI destination.") + .font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true) + } + Spacer() + SetupButton(title: "Reconnect") { SizzleMidi.shared.reconnect() } + } + if midi.sources.isEmpty { + SetupNote("No MIDI sources found.") + } + ForEach(midi.sources, id: \.key) { src in + SetupToggle(title: src.name, detail: !src.enabled ? "Off" : src.connected ? "Listening" : "Not connected (tap Reconnect)", + isOn: src.enabled) { on in + if on { settings.midiSourcesOff.remove(src.key) } else { settings.midiSourcesOff.insert(src.key) } + SizzleMidi.shared.setSourceKey(src.key, enabled: on) + } + } + } + } +} + +/// SizzleMidi's source list as an observable (refreshed on its change callback). +@MainActor +final class MidiSources: ObservableObject { + static let shared = MidiSources() + @Published private(set) var sources: [SizzleMidiSource] = [] + + private init() { + sources = SizzleMidi.shared.sources + SizzleMidi.shared.onSourcesChanged = { [weak self] in self?.sources = SizzleMidi.shared.sources } + } +} + +/// The three binding editors (Android's Gamepad Bindings / Keyboard Hotkeys / MIDI Bindings). +struct BindingsCard: View { + let open: (InputSource) -> Void + + var body: some View { + SetupCard(title: "Controls", subtitle: "Hardware keyboard, gamepad and MIDI controller bindings") { + SetupRow(title: "Gamepad Bindings", detail: "Rebind buttons, sticks and combos", icon: "gamecontroller") { open(.gamepad) } + SetupDivider() + SetupRow(title: "Keyboard Hotkeys", detail: "Rebind keys; Z…M and Q…U play notes", icon: "keyboard") { open(.keyboard) } + SetupDivider() + SetupRow(title: "MIDI Bindings", detail: "MIDI-learn controls for transport and editing", icon: "pianokeys") { open(.midi) } + } + } +} + +/// Backup & Restore (Android's BackupCard). +struct BackupCard: View { + let onBackup: () -> Void + let onRestore: () -> Void + + var body: some View { + SetupCard(title: "Backup & Restore", subtitle: "Save or restore all songs, presets, themes & settings") { + HStack(spacing: 8) { + SetupButton(title: "Back up", icon: "externaldrive", kind: .filled, action: onBackup) + SetupButton(title: "Restore", icon: "arrow.counterclockwise", action: onRestore) + } + SetupNote("A backup is one .zip with every saved song, preset, theme, sample, the open song and the settings. " + + "Restoring replaces all of them.") + } + } +} diff --git a/ios/app/Host/Screens/Setup/SetupComponents.swift b/ios/app/Host/Screens/Setup/SetupComponents.swift index 5341e9e..3df3de2 100644 --- a/ios/app/Host/Screens/Setup/SetupComponents.swift +++ b/ios/app/Host/Screens/Setup/SetupComponents.swift @@ -7,7 +7,7 @@ import SwiftUI /// buttons, link rows, rows for sections still to come, and the modal dialog. /// SwiftUI only (the Mac snapshot tool renders them). enum SetupStyle { - static let danger = Color(red: 0.86, green: 0.27, blue: 0.27) + static var danger: Color { Theme.danger } static let corner: CGFloat = 10 } @@ -145,6 +145,8 @@ enum SetupDialog: Identifiable { case save case confirmNew case confirmDelete(String) + case confirmDeleteTheme(String) + case confirmRestore case message(title: String, text: String) var id: String { @@ -152,6 +154,8 @@ enum SetupDialog: Identifiable { case .save: return "save" case .confirmNew: return "new" case .confirmDelete(let n): return "delete:" + n + case .confirmDeleteTheme(let n): return "theme:" + n + case .confirmRestore: return "restore" case .message(let t, let m): return "msg:" + t + m } } diff --git a/ios/app/Host/Screens/Setup/SetupFiles.swift b/ios/app/Host/Screens/Setup/SetupFiles.swift index 4438e73..b7287da 100644 --- a/ios/app/Host/Screens/Setup/SetupFiles.swift +++ b/ios/app/Host/Screens/Setup/SetupFiles.swift @@ -17,6 +17,28 @@ enum SetupFiles { return url } + /// Writes [data] to a fresh temporary folder as ".". + static func export(_ data: Data, name: String, ext: String) throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("Exports", isDirectory: true) + try? FileManager.default.removeItem(at: root) + let dir = root.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let url = dir.appendingPathComponent(name).appendingPathExtension(ext) + try data.write(to: url) + return url + } + + /// Reads a picked file (security-scoped), refusing anything over [limit] bytes. + static func readData(_ url: URL, limit: Int) throws -> Data { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0 + guard size <= limit else { throw SetupFileError.tooLarge } + let data = try Data(contentsOf: url) + guard data.count <= limit else { throw SetupFileError.tooLarge } + return data + } + /// The song name as a file name: path separators replaced, blank → "untitled". static func fileStem(_ name: String) -> String { let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) @@ -42,7 +64,7 @@ enum SetupFileError: LocalizedError { case tooLarge, notText var errorDescription: String? { switch self { - case .tooLarge: return "The file is too large to be a Sizzle song." + case .tooLarge: return "The file is too large for Sizzle." case .notText: return "Couldn't read the selected file." } } diff --git a/ios/app/Host/Screens/Setup/SetupModel.swift b/ios/app/Host/Screens/Setup/SetupModel.swift index 93ab525..7f09b3d 100644 --- a/ios/app/Host/Screens/Setup/SetupModel.swift +++ b/ios/app/Host/Screens/Setup/SetupModel.swift @@ -63,8 +63,9 @@ final class SetupModel: ObservableObject { // MARK: Export / import + /// What a picked file is for. enum Format { - case sng, project + case sng, project, theme, backup var ext: String { self == .sng ? "sng" : "szg" } } @@ -77,11 +78,47 @@ final class SetupModel: ObservableObject { /// Imports a picked file: a .sng into the open song (notes, blocks, /// arrangement), or a project replacing it. func importFile(_ url: URL, as format: Format) throws { + if format == .project { + // A bundle (.szgz, a ZIP) or a plain project (.szg). + let data = try SetupFiles.readData(url, limit: 64 << 20) + if SizzleSession.isZip(data) { try session.importProjectBundleData(data) } + else if let text = String(data: data, encoding: .utf8) { try session.importProjectText(text) } + else { throw SetupFileError.notText } + refresh() + return + } let text = try SetupFiles.readText(url) switch format { case .sng: try session.importSngText(text) - case .project: try session.importProjectText(text) + default: try session.importProjectText(text) } refresh() } + + /// The open song as a bundle, ".szgz" in a temporary folder. + func exportBundle() throws -> URL { + guard let data = session.projectBundleData() else { throw SetupFileError.notText } + return try SetupFiles.export(data, name: SetupFiles.fileStem(songName), ext: "szgz") + } + + /// Everything as "sizzle-backup-yyyyMMdd-HHmm.zip" (Android names it the same way). + func backupFile() throws -> URL { + guard let data = session.backupData(withSettings: AppSettings.shared.exportText()) else { throw SetupFileError.notText } + let f = DateFormatter() + f.locale = Locale(identifier: "en_US_POSIX") + f.dateFormat = "yyyyMMdd-HHmm" + return try SetupFiles.export(data, name: "sizzle-backup-" + f.string(from: Date()), ext: "zip") + } + + /// Restore a backup, then apply its settings, bindings and theme. + func restoreBackup(_ url: URL) throws { + let data = try SetupFiles.readData(url, limit: 1 << 30) + let settings = try session.restoreBackupData(data) + if !settings.isEmpty { AppSettings.shared.importText(settings) } + InputBindings.shared.reload() + ThemeLibrary.shared.refresh() + ThemeLibrary.shared.select(AppSettings.shared.paletteName) + session.recordTailBars = AppSettings.shared.recordTailBars + refresh() + } } diff --git a/ios/app/Host/Screens/Setup/SetupPlatform.swift b/ios/app/Host/Screens/Setup/SetupPlatform.swift index 392ff67..df092b9 100644 --- a/ios/app/Host/Screens/Setup/SetupPlatform.swift +++ b/ios/app/Host/Screens/Setup/SetupPlatform.swift @@ -8,6 +8,7 @@ import SwiftUI // DeviceLabView / PluginCheck), so there they are no-ops. #if canImport(UIKit) +import AVKit import UIKit enum ShareSheet { @@ -79,8 +80,53 @@ private struct PluginCheckSheet: View { } } +/// The system's audio route picker (AirPlay, Bluetooth, an interface) and the +/// current route's names (Android's audio device rows; iOS chooses the route). +struct AudioRouteView: View { + @State private var output = AudioRouteView.names(\.outputs) + @State private var input = AudioRouteView.names(\.inputs) + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 3) { + Text("Output: " + output).font(.system(size: 14)).foregroundColor(Theme.text) + Text("Input: " + input).font(.system(size: 14)).foregroundColor(Theme.text) + } + Spacer() + RoutePicker().frame(width: 44, height: 44) + } + } + .onReceive(NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification).receive(on: RunLoop.main)) { _ in + output = Self.names(\.outputs) + input = Self.names(\.inputs) + } + } + + static func names(_ kp: KeyPath) -> String { + let ports = AVAudioSession.sharedInstance().currentRoute[keyPath: kp].map(\.portName) + return ports.isEmpty ? "—" : ports.joined(separator: ", ") + } + + private struct RoutePicker: UIViewRepresentable { + func makeUIView(context: Context) -> AVRoutePickerView { + let v = AVRoutePickerView() + v.tintColor = UIColor(Theme.accent) + v.activeTintColor = UIColor(Theme.accent) + return v + } + func updateUIView(_ v: AVRoutePickerView, context: Context) {} + } +} + #else +struct AudioRouteView: View { + var body: some View { + Text("Output: Speaker\nInput: Microphone").font(.system(size: 14)).foregroundColor(Theme.text) + } +} + enum ShareSheet { @MainActor static func present(_ url: URL, done: @escaping () -> Void = {}) { done() } } diff --git a/ios/app/Host/Screens/Setup/SetupScreen.swift b/ios/app/Host/Screens/Setup/SetupScreen.swift index 80d7d5e..5a6c8ef 100644 --- a/ios/app/Host/Screens/Setup/SetupScreen.swift +++ b/ios/app/Host/Screens/Setup/SetupScreen.swift @@ -5,10 +5,9 @@ import SwiftUI import UniformTypeIdentifiers /// The fourth tab, after Android's SettingsScreen: MIDI panic, the project -/// browser (save / load / new / delete, export and import of projects and .sng), -/// help and about, and the device lab. Android's other sections (audio devices, -/// recording, interface, themes, MIDI sync, bindings, backup) keep their places -/// as greyed-out cards until they're ported. +/// browser (save / load / new / delete, project bundles and .sng), audio route, +/// recording, interface, colour themes, MIDI sync, control bindings, backup and +/// restore, help and about, and the device lab. struct SetupScreen: View { @EnvironmentObject var app: AppModel // SetupContent doesn't observe AppModel, so it isn't redrawn at the transport's rate. @@ -27,6 +26,8 @@ private struct SetupContent: View { @State private var importFormat = SetupModel.Format.sng @State private var showDeviceLab = false @State private var showPluginCheck = false + @State private var bindingSource: BindingKind? + @State private var confirmTheme: String? var body: some View { GeometryReader { geo in @@ -37,13 +38,19 @@ private struct SetupContent: View { panicButton if wide { HStack(alignment: .top, spacing: 14) { - VStack(spacing: 14) { projectCard; helpCard } - VStack(spacing: 14) { comingLater; diagnosticsCard } + VStack(spacing: 14) { projectCard; AudioDevicesCard(); RecordingCard(); backupCard; helpCard } + VStack(spacing: 14) { midiCard; BindingsCard { bindingSource = BindingKind($0) }; InterfaceCard(); themeCard; diagnosticsCard } } } else { projectCard + AudioDevicesCard() + RecordingCard() + midiCard + BindingsCard { bindingSource = BindingKind($0) } + InterfaceCard() + themeCard + backupCard helpCard - comingLater diagnosticsCard } } @@ -62,6 +69,28 @@ private struct SetupContent: View { } .deviceLab(isPresented: $showDeviceLab) .pluginCheck(isPresented: $showPluginCheck) + .sheet(item: $bindingSource) { BindingsSheet(source: $0.source) } + } + + /// Identifiable wrapper for the bindings sheet. + struct BindingKind: Identifiable { + let source: InputSource + init(_ s: InputSource) { source = s } + var id: String { "\(source)" } + } + + // MARK: Cards with dialogs + + /// The MIDI card isn't built in the Mac snapshots before MIDI starts; it lists nothing then. + private var midiCard: some View { MidiSyncCard() } + + private var themeCard: some View { + ThemeCard(onImport: { pick(.theme) }, onDelete: { present(.confirmDeleteTheme($0)) }, + onError: { show("Export failed", $0) }) + } + + private var backupCard: some View { + BackupCard(onBackup: backup, onRestore: { present(.confirmRestore) }) } // MARK: Panic @@ -96,11 +125,11 @@ private struct SetupContent: View { SetupDivider() HStack(spacing: 8) { - SetupButton(title: "Export project", icon: "square.and.arrow.up") { export(.project) } + SetupButton(title: "Export project", icon: "square.and.arrow.up") { exportBundle() } SetupButton(title: "Import project", icon: "square.and.arrow.down.on.square") { pick(.project) } } - SetupNote("A project file (.szg) carries patterns, mixer, FX and instruments, so it opens " + - "complete on another device (samples aren't included yet). Import replaces the current project.") + SetupNote("A bundle (.szgz) carries everything — patterns, mixer, FX, instruments and samples — so it opens " + + "complete on another device, Android too. Import takes a bundle or a .szg and replaces the current project.") SetupDivider() HStack(spacing: 8) { @@ -178,29 +207,6 @@ private struct SetupContent: View { return "\(name) v\(v)" + (build.map { " (\($0))" } ?? "") } - // MARK: Sections still to come - - private static let later: [(String, String, String)] = [ - ("Audio Devices", "Route playback / recording to USB or built-in", "hifispeaker"), - ("Recording", "Record the master bus to WAV files", "record.circle"), - ("Interface", "On-screen display options", "rectangle.on.rectangle"), - ("Color Theme", "Pick, import, export or delete a palette", "paintpalette"), - ("MIDI Sync", "MIDI clock in and out, sources, sound module", "metronome"), - ("Gamepad Bindings", "Rebind buttons & combos", "gamecontroller"), - ("Keyboard Hotkeys", "Rebind keyboard keys", "keyboard"), - ("MIDI Bindings", "MIDI-learn controls", "pianokeys"), - ("Backup & Restore", "Save or restore all songs, presets, themes & settings", "externaldrive"), - ] - - private var comingLater: some View { - SetupCard(title: "More settings", subtitle: "Coming in a later version", enabled: false) { - ForEach(Array(Self.later.enumerated()), id: \.offset) { i, s in - if i > 0 { SetupDivider() } - ComingLaterRow(title: s.0, subtitle: s.1, icon: s.2) - } - } - } - // MARK: Diagnostics private var diagnosticsCard: some View { @@ -247,6 +253,15 @@ private struct SetupContent: View { confirm: "Delete", destructive: true, field: { EmptyView() }, onConfirm: { dismiss(); attempt("Delete failed") { try model.delete(name) } }, onCancel: dismiss) + case .confirmDeleteTheme(let name): + SetupDialogView(title: "Delete theme", message: "Delete \"\(name)\"? This cannot be undone.", + confirm: "Delete", destructive: true, field: { EmptyView() }, + onConfirm: { dismiss(); ThemeLibrary.shared.delete(name) }, onCancel: dismiss) + case .confirmRestore: + SetupDialogView(title: "Restore backup", + message: "Replace every saved song, preset, theme, sample, the open song and the settings with a backup's?", + confirm: "Choose backup", destructive: true, field: { EmptyView() }, + onConfirm: { dismiss(); pick(.backup) }, onCancel: dismiss) case .message(let title, let text): SetupDialogView(title: title, message: text, confirm: "OK", cancel: nil, field: { EmptyView() }, onConfirm: dismiss, onCancel: dismiss) @@ -279,6 +294,20 @@ private struct SetupContent: View { resetCursor() } + private func exportBundle() { + attempt("Export failed") { + let url = try model.exportBundle() + ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + } + } + + private func backup() { + attempt("Backup failed") { + let url = try model.backupFile() + ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + } + } + private func export(_ format: SetupModel.Format) { attempt("Export failed") { let url = try model.exportFile(format) @@ -293,16 +322,31 @@ private struct SetupContent: View { private func runImport(_ url: URL) { do { - try model.importFile(url, as: importFormat) + switch importFormat { + case .theme: + guard ThemeLibrary.shared.importText(try SetupFiles.readText(url)) != nil else { + show("Import failed", "Couldn't import this file. It doesn't look like a valid .szt theme.") + return + } + return + case .backup: + try model.restoreBackup(url) + show("Backup restored", "Songs, presets, themes, samples and settings are back.") + default: + try model.importFile(url, as: importFormat) + } resetCursor() } catch let e as SetupFileError { show("Import failed", e.localizedDescription) } catch is CocoaError { show("Import failed", "Couldn't read the selected file.") } catch { - show("Import failed", importFormat == .sng - ? "Couldn't import this file. It doesn't look like a valid .sng song." - : "Couldn't import this file. It doesn't look like a Sizzle project (.szg).") + switch importFormat { + case .sng: show("Import failed", "Couldn't import this file. It doesn't look like a valid .sng song.") + case .backup: show("Restore failed", error.localizedDescription) + default: show("Import failed", (error as NSError).domain == "Sizzle" ? error.localizedDescription + : "Couldn't import this file. It doesn't look like a Sizzle project (.szgz or .szg).") + } } } diff --git a/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift b/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift new file mode 100644 index 0000000..7ae45b3 --- /dev/null +++ b/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Android's MidiLearnPopup: every parameter of the slot with its MIDI CC. LEARN, +/// then move a knob or fader on a MIDI controller; ✕ removes the binding. The +/// bindings are saved in the song (`midicc@` slot values), as on Android. +struct MidiLearnSheet: View { + let slot: Int + let type: String + @ObservedObject private var input = InputController.shared + @ObservedObject private var watch = MixSongWatch.shared + @Environment(\.dismiss) private var dismiss + + var body: some View { + let session = SizzleSession.shared + VStack(alignment: .leading, spacing: 8) { + HStack { + Text("MIDI LEARN — \(session.name(ofSlot: slot))").font(Theme.mono(14)).foregroundColor(Theme.accent) + Spacer() + Text("DONE").font(Theme.mono(13)).foregroundColor(Theme.dim) + .contentShape(Rectangle()).onTapGesture { dismiss() } + } + Text("Tap LEARN, then move a knob/fader on your MIDI controller.").font(Theme.mono(10)).foregroundColor(Theme.dim) + SnapScroll { + VStack(spacing: 6) { + ForEach(SizzleSession.paramSpecs(forType: type), id: \.key) { spec in + let arming = input.paramLearnSlot == slot && input.paramLearnKey == spec.key + let cc = input.paramCc(slot: slot, key: spec.key) + HStack(spacing: 8) { + Text(spec.label).font(Theme.mono(12)).foregroundColor(Theme.text) + .frame(maxWidth: .infinity, alignment: .leading) + Text(arming ? "waiting…" : cc.map { "CC \($0)" } ?? "—").font(Theme.mono(11)) + .foregroundColor(arming ? Theme.accent : Theme.dim).frame(width: 72, alignment: .leading) + MixKit.Button(label: arming ? "ARMING" : "LEARN", active: arming, width: 78) { + if arming { input.cancelParamLearn() } else { input.beginParamLearn(slot: slot, key: spec.key) } + } + MixKit.Button(label: "✕") { input.clearParamCc(slot: slot, key: spec.key) } + } + } + } + } + } + .padding(16) + .background(Theme.surface.ignoresSafeArea()) + .preferredColorScheme(.dark) + .onDisappear { input.cancelParamLearn() } + } +} diff --git a/ios/app/Host/Screens/Toolbox/SamplerPanels.swift b/ios/app/Host/Screens/Toolbox/SamplerPanels.swift index c40153d..8c84884 100644 --- a/ios/app/Host/Screens/Toolbox/SamplerPanels.swift +++ b/ios/app/Host/Screens/Toolbox/SamplerPanels.swift @@ -19,6 +19,7 @@ struct SamplerDetail: View { let onSelectPad: (Int) -> Void let onImport: () -> Void @State private var page = 0 + @ObservedObject private var recorder = SampleRecorder.shared var body: some View { let session = SizzleSession.shared @@ -28,6 +29,15 @@ struct SamplerDetail: View { MixKit.HScroll { HStack(spacing: 8) { MixKit.Button(label: "IMPORT WAV", action: onImport) + if recorder.isRecording { + MixKit.Button(label: "■ STOP REC", active: true) { + recorder.stopInto(slot: slot, pad: pad) + session.setNumber(0, ofSlot: slot, key: "pad\(pad)S") + session.setNumber(1, ofSlot: slot, key: "pad\(pad)E") + } + } else { + MixKit.Button(label: "● RECORD") { recorder.start() } + } if assigned { MixKit.Button(label: "✂ CLIP") { _ = session.trimPad(pad, ofSlot: slot) } MixKit.Button(label: "NORMALIZE") { _ = session.normalizePad(pad, ofSlot: slot) } diff --git a/ios/app/Host/Screens/Toolbox/SlotEditor.swift b/ios/app/Host/Screens/Toolbox/SlotEditor.swift index 885c243..80ce4d5 100644 --- a/ios/app/Host/Screens/Toolbox/SlotEditor.swift +++ b/ios/app/Host/Screens/Toolbox/SlotEditor.swift @@ -20,6 +20,7 @@ struct SlotEditor: View { @StateObject private var model: DeviceModel @ObservedObject private var watch = MixSongWatch.shared + @ObservedObject private var recorder = SampleRecorder.shared @State private var pad = 0 /// What the file picker is for; kept after it closes, because SwiftUI resets /// the presentation binding before calling the completion handler. @@ -27,6 +28,7 @@ struct SlotEditor: View { @State private var pickerShown = false @State private var deviceCallback: ((URL) -> Void)? @State private var importError: String? + @State private var showMidiLearn = false enum ImportKind: Identifiable { case preset, padSample, soundFont, device // device: a bespoke view's own load (deviceFilePicker) @@ -71,6 +73,11 @@ struct SlotEditor: View { } .alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }), actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") }) + .background(Color.clear.alert("Recording", isPresented: Binding(get: { recorder.error != nil }, set: { if !$0 { recorder.error = nil } }), + actions: { Button("OK") { recorder.error = nil } }, message: { Text(recorder.error ?? "") })) + .onDisappear { if recorder.isRecording { _ = recorder.stop() } } + .onChange(of: watch.revision) { _ in model.refresh() } // MIDI CCs move parameters too + .sheet(isPresented: $showMidiLearn) { MidiLearnSheet(slot: slot, type: type) } } @ViewBuilder private var pinnedPart: some View { @@ -87,6 +94,9 @@ struct SlotEditor: View { HStack { Text(session.name(ofSlot: slot)).font(Theme.mono(15)).foregroundColor(Theme.accent).lineLimit(1) Spacer() + Text("⇄ MIDI").font(Theme.mono(13)).foregroundColor(Theme.accent) + .contentShape(Rectangle()).onTapGesture { showMidiLearn = true } + .padding(.trailing, 14) Text("CLOSE ✕").font(Theme.mono(13)).foregroundColor(Theme.dim) .contentShape(Rectangle()).onTapGesture(perform: onClose) } @@ -104,6 +114,9 @@ struct SlotEditor: View { importing = .device pickerShown = true } + .environment(\.deviceRecorder, DeviceRecordControl(isRecording: recorder.isRecording) { + if recorder.isRecording { recorder.stopIntoGrain(slot: slot) } else { recorder.start() } + }) .frame(minHeight: 0, maxHeight: .infinity, alignment: .top).clipped() if type == "LFO" { LfoTargetPicker(lfo: slot) } } diff --git a/ios/app/Host/Screens/Tracker/TrackerState.swift b/ios/app/Host/Screens/Tracker/TrackerState.swift index 86f0b13..99e213a 100644 --- a/ios/app/Host/Screens/Tracker/TrackerState.swift +++ b/ios/app/Host/Screens/Tracker/TrackerState.swift @@ -63,9 +63,11 @@ final class TrackerState: ObservableObject { // MARK: edits (Android: punchNote / noteOffFocused / deleteAndAdvance / …) - func punchNote(_ app: AppModel, _ midi: Int) { - let cell = SizzleCell(note: Int32(min(max(midi, 0), 127)), velocity: Int32(min(max(app.kbdVelocity, 0), 127)), - channel: Int32(app.kbdChannel)) + /// Velocity and channel default to the on-screen keyboard's; MIDI punch-in + /// passes the incoming note's own, so the cell plays back as it was played. + func punchNote(_ app: AppModel, _ midi: Int, velocity: Int? = nil, channel: Int? = nil) { + let cell = SizzleCell(note: Int32(min(max(midi, 0), 127)), velocity: Int32(min(max(velocity ?? app.kbdVelocity, 0), 127)), + channel: Int32(channel ?? app.kbdChannel)) session.setCell(cell, inPattern: session.activePattern, track: app.cursorTrack, line: app.cursorLine) moveCursorWrap(app, skipStep) } @@ -254,6 +256,14 @@ final class TrackerHeldNotes: ObservableObject { SizzleSession.shared.noteOff(midi, midiChannel: channels[midi] ?? app.kbdChannel) } + /// Light or unlight a key without sounding it (hardware keys, MIDI in: the + /// input layer plays those itself). + func mark(_ midi: Int, on: Bool) { + if on { counts[midi, default: 0] += 1; return } + let n = (counts[midi] ?? 0) - 1 + if n <= 0 { counts[midi] = nil } else { counts[midi] = n } + } + /// Release everything (the keyboard went away mid-press). func releaseAll() { for (midi, ch) in channels where (counts[midi] ?? 0) > 0 { SizzleSession.shared.noteOff(midi, midiChannel: ch) } diff --git a/ios/app/Host/Screens/Tracker/TrackerWidgets.swift b/ios/app/Host/Screens/Tracker/TrackerWidgets.swift index 1e363c1..2f11e49 100644 --- a/ios/app/Host/Screens/Tracker/TrackerWidgets.swift +++ b/ios/app/Host/Screens/Tracker/TrackerWidgets.swift @@ -6,16 +6,16 @@ import SwiftUI /// The Android "Amber CRT" palette slots the shared Theme doesn't have (beat/bar /// row tints, the playhead green, the danger red), plus Theme's own for brevity. enum TK { - static let background = Theme.background - static let surface = Theme.surface - static let grid = Theme.grid - static let text = Theme.text - static let dim = Theme.dim - static let accent = Theme.accent - static let beat = Color(red: 0x14 / 255, green: 0x1C / 255, blue: 0x1A / 255) - static let bar = Color(red: 0x1E / 255, green: 0x2A / 255, blue: 0x20 / 255) - static let playhead = Color(red: 0x7C / 255, green: 0xFC / 255, blue: 0x9A / 255) - static let danger = Color(red: 0xE0 / 255, green: 0x5A / 255, blue: 0x4B / 255) + static var background: Color { Theme.background } + static var surface: Color { Theme.surface } + static var grid: Color { Theme.grid } + static var text: Color { Theme.text } + static var dim: Color { Theme.dim } + static var accent: Color { Theme.accent } + static var beat: Color { Theme.beat } + static var bar: Color { Theme.bar } + static var playhead: Color { Theme.playhead } + static var danger: Color { Theme.danger } /// Pitch.name: 60 → "C-4", 61 → "C#4" (MIDI 12 == C0). static let noteNames: [String] = (0..<128).map { m in diff --git a/ios/app/Host/SizzleApp.swift b/ios/app/Host/SizzleApp.swift index f041327..a65d6c2 100644 --- a/ios/app/Host/SizzleApp.swift +++ b/ios/app/Host/SizzleApp.swift @@ -5,5 +5,6 @@ import SwiftUI @main struct SizzleApp: App { + init() { AppBoot.start() } var body: some Scene { WindowGroup { RootView() } } } diff --git a/ios/app/Host/SizzleMidi.h b/ios/app/Host/SizzleMidi.h new file mode 100644 index 0000000..e1539e4 --- /dev/null +++ b/ios/app/Host/SizzleMidi.h @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// One MIDI source as Setup lists it. [key] is stable across launches (what the +/// device says about itself), so the on/off choice can be saved. +@interface SizzleMidiSource : NSObject +@property (nonatomic, readonly) NSString *key; +@property (nonatomic, readonly) NSString *name; +@property (nonatomic, readonly) BOOL enabled; +@property (nonatomic, readonly) BOOL connected; +@end + +/** + * CoreMIDI for Sizzle (Android's MidiInput + MidiSoundModule + MidiClock): + * + * IN: every MIDI source (USB, Bluetooth, network, other apps) is listened to unless + * switched off, plus Sizzle's own virtual destination ("Sizzle") that other apps + * can send to. Each source has its own byte parser. Notes play the mixer tracks + * listening on their channel straight from the MIDI thread (queued to the audio + * thread, no UI in the path); CC 123/120 release a channel. Real-time bytes follow + * an external clock (tempo, Start/Stop) while [receiveClock] is on. + * + * OUT: while [sendClock] is on and the song plays, a thread sends the clock (24 + * PPQN), Start/Stop, and the sequenced notes to every destination and through + * Sizzle's virtual source. + * + * The blocks are called on the main thread. + */ +NS_SWIFT_UI_ACTOR +@interface SizzleMidi : NSObject + +@property (class, nonatomic, readonly) SizzleMidi *shared; + +/// Create the client and ports and connect the enabled sources. Idempotent. +- (void)startWithDisabledKeys:(NSSet *)disabled; +@property (nonatomic, readonly) NSArray *sources; +- (void)setSourceKey:(NSString *)key enabled:(BOOL)enabled; +/// Disconnect and connect every enabled source again. +- (void)reconnect; +/// Release every note the sources hold (panic). +- (void)releaseAll; + +@property (nonatomic) BOOL sendClock; +@property (nonatomic) BOOL receiveClock; +/// Sound-module mode: an external clock's Start/Stop no longer start or stop the song. +@property (nonatomic) BOOL soundModule; + +/// A note the module played or released (channel 1..16), for held keys and punch-in. +@property (nonatomic, copy, nullable) void (^onNote)(BOOL on, NSInteger channel, NSInteger note, NSInteger velocity); +/// A Control Change the module didn't consume (bindings, MIDI learn): value 0..127. +@property (nonatomic, copy, nullable) void (^onControl)(NSInteger cc, NSInteger value); +/// The source list changed. +@property (nonatomic, copy, nullable) void (^onSourcesChanged)(void); +/// A tempo taken from an external clock was applied. +@property (nonatomic, copy, nullable) void (^onTempoFollowed)(float bpm); + +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleMidi.mm b/ios/app/Host/SizzleMidi.mm new file mode 100644 index 0000000..ef60d50 --- /dev/null +++ b/ios/app/Host/SizzleMidi.mm @@ -0,0 +1,337 @@ +// 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 diff --git a/ios/app/Host/SizzleSession+Files.h b/ios/app/Host/SizzleSession+Files.h new file mode 100644 index 0000000..3a60f5f --- /dev/null +++ b/ios/app/Host/SizzleSession+Files.h @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Project bundles and whole-app backups (Android's ProjectBundleIo and BackupIo), +/// both ZIP archives in Android's layouts. +@interface SizzleSession (Files) + +/// The open song as a bundle (.szgz): project.szg, every sample its Sampler, +/// SF2/XI, Grain Cloud and Wavetable slots use (samples/.wav) and +/// samples/manifest.txt (`\t` per line). +- (nullable NSData *)projectBundleData; +/// Replace the open song with a bundle's: its samples are stored under their ids +/// first, so the song finds them. Leaves the song alone if it isn't a bundle. +- (BOOL)importProjectBundleData:(NSData *)data error:(NSError **)error; +/// True for a ZIP archive (bundle or backup) rather than text. ++ (BOOL)isZipData:(NSData *)data; + +/// Everything Sizzle keeps: Documents/songs, themes, presets and samples, the +/// autosaved song, and [settings] as settings.txt. The open song is autosaved first. +- (nullable NSData *)backupDataWithSettings:(NSString *)settings; +/// Restore a backup: it is unpacked aside first and only swapped in once it looks +/// like one, so a wrong file can't destroy anything. The restored autosave becomes +/// the open song. Returns the backup's settings text ("" if it has none), or nil. +- (nullable NSString *)restoreBackupData:(NSData *)data error:(NSError **)error; +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Files.mm b/ios/app/Host/SizzleSession+Files.mm new file mode 100644 index 0000000..2474f1d --- /dev/null +++ b/ios/app/Host/SizzleSession+Files.mm @@ -0,0 +1,225 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession+Files.h" +#import "SizzleSession+Internal.h" +#import "SizzleSession+Setup.h" + +#include +#include +#include + +#include "io/Zip.hpp" + +using namespace sizzle; +namespace zip = sizzle::io::zip; + +// Defined in SizzleSession.mm (Documents/samples/.wav). +@interface SizzleSession (FilesPrivate) +- (NSURL *)sampleURL:(const std::string &)id; +@end + +namespace { + +NSError *filesError(NSString *msg) { + return [NSError errorWithDomain:@"Sizzle" code:3 userInfo:@{NSLocalizedDescriptionKey: msg}]; +} + +NSURL *documents() { + return [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject; +} + +std::vector bytesOf(NSData *d) { + const uint8_t *b = (const uint8_t *)d.bytes; + return std::vector(b, b + d.length); +} + +NSData *dataOf(const std::vector &v) { return [NSData dataWithBytes:v.data() length:v.size()]; } + +// Backup areas under Documents (Android: songs, themes, presets, datastore; the +// iOS app keeps its samples as files too, and settings as settings.txt). +NSArray *const kAreas = @[@"songs", @"themes", @"presets", @"samples"]; +NSString *const kAutosave = @"autosave.szg"; +NSString *const kSettings = @"settings.txt"; + +} // namespace + +@implementation SizzleSession (Files) + ++ (BOOL)isZipData:(NSData *)data { + return data.length >= 4 && !memcmp(data.bytes, "PK\x03\x04", 4); +} + +#pragma mark - bundles + +/// ProjectBundleIo.collectSampleIds: per slot, a Sampler's pads, else the +/// SF2/XI, Grain Cloud or Wavetable sample; each id once, in that order. +- (std::vector)files_sampleIds { + std::vector ids; + auto add = [&](NSString *v) { + if (!v.length) return; + std::string id = v.UTF8String; + for (auto &x : ids) if (x == id) return; + ids.push_back(id); + }; + for (NSInteger s = 0; s < 16; ++s) { + NSString *type = [self typeOfSlot:s]; + if ([type isEqualToString:@"SAMPLER"]) { + for (int p = 0; p < 16; ++p) add([self valueOfSlot:s key:[NSString stringWithFormat:@"pad%d", p]]); + } else if ([@[@"SOUNDFONT", @"GRAIN_CLOUD", @"WAVETABLE"] containsObject:type]) { + add([self valueOfSlot:s key:@"sfSample"]); + } + } + return ids; +} + +- (nullable NSData *)projectBundleData { + std::vector entries; + NSData *text = [[self projectText] dataUsingEncoding:NSUTF8StringEncoding]; + entries.push_back({"project.szg", bytesOf(text)}); + std::string manifest; + int i = 0; + for (const std::string &id : [self files_sampleIds]) { + NSData *wav = [NSData dataWithContentsOfURL:[self sampleURL:id]]; + std::vector bytes; + if (wav) bytes = bytesOf(wav); + else if (auto s = [self sampleStore].get(id.c_str())) bytes = sampler::SampleStore::encodeWav(*s); + if (!bytes.empty()) { + entries.push_back({"samples/" + std::to_string(i) + ".wav", std::move(bytes)}); + manifest += std::to_string(i) + "\t" + id + "\n"; + } + ++i; + } + entries.push_back({"samples/manifest.txt", std::vector(manifest.begin(), manifest.end())}); + return dataOf(zip::write(entries)); +} + +- (BOOL)importProjectBundleData:(NSData *)data error:(NSError **)error { + std::vector entries; + // ZipLimits.forBundle: 64 MB. + if (!zip::read((const uint8_t *)data.bytes, data.length, entries, 64ull << 20)) { + if (error) *error = filesError(@"Couldn't read this bundle: it isn't a ZIP, is damaged, or is larger than 64 MB."); + return NO; + } + NSString *text = nil; + std::map manifest; // index -> original id + std::map *> wavs; + for (const auto &e : entries) { + if (!zip::safeName(e.name)) continue; + if (e.name == "project.szg") text = [[NSString alloc] initWithBytes:e.data.data() length:e.data.size() encoding:NSUTF8StringEncoding]; + else if (e.name == "samples/manifest.txt") { + std::string m(e.data.begin(), e.data.end()); + size_t start = 0; + while (start < m.size()) { + size_t end = m.find('\n', start); + if (end == std::string::npos) end = m.size(); + std::string line = m.substr(start, end - start); + if (!line.empty() && line.back() == '\r') line.pop_back(); + const size_t tab = line.find('\t'); + if (tab != std::string::npos && tab > 0) manifest[line.substr(0, tab)] = line.substr(tab + 1); + start = end + 1; + } + } else if (e.name.rfind("samples/", 0) == 0 && e.name.size() > 12 && e.name.compare(e.name.size() - 4, 4, ".wav") == 0) { + wavs[e.name.substr(8, e.name.size() - 12)] = &e.data; + } + } + if (!text || ![SizzleSession looksLikeProjectText:text]) { + if (error) *error = filesError(@"This archive holds no Sizzle project."); + return NO; + } + // Store each sample under its original id, where the song looks for it. + for (const auto &[idx, id] : manifest) { + auto w = wavs.find(idx); + if (w == wavs.end() || id.empty()) continue; + [self sampleStore].remove(id.c_str()); // a stale copy under the same id must not win + [dataOf(*w->second) writeToURL:[self sampleURL:id] atomically:YES]; + } + [self stop]; + return [self importProjectText:text error:error]; +} + +#pragma mark - backups + +- (nullable NSData *)backupDataWithSettings:(NSString *)settings { + [self autosave]; + NSFileManager *fm = NSFileManager.defaultManager; + NSURL *docs = documents(); + std::vector entries; + for (NSString *area in kAreas) { + NSURL *dir = [docs URLByAppendingPathComponent:area]; + NSDirectoryEnumerator *walk = [fm enumeratorAtURL:dir includingPropertiesForKeys:@[NSURLIsRegularFileKey] options:0 errorHandler:nil]; + for (NSURL *f in walk) { + NSNumber *regular = nil; + [f getResourceValue:®ular forKey:NSURLIsRegularFileKey error:nil]; + if (!regular.boolValue) continue; + NSString *rel = [f.path substringFromIndex:dir.path.length]; + if ([rel hasPrefix:@"/"]) rel = [rel substringFromIndex:1]; + if ([rel hasPrefix:@"."] || [rel containsString:@"/."]) continue; // export scratch + NSData *d = [NSData dataWithContentsOfURL:f]; + if (d) entries.push_back({std::string(area.UTF8String) + "/" + rel.UTF8String, bytesOf(d)}); + } + } + if (NSData *a = [NSData dataWithContentsOfURL:[docs URLByAppendingPathComponent:kAutosave]]) entries.push_back({kAutosave.UTF8String, bytesOf(a)}); + NSData *s = [settings dataUsingEncoding:NSUTF8StringEncoding]; + entries.push_back({kSettings.UTF8String, bytesOf(s)}); + return dataOf(zip::write(entries)); +} + +- (nullable NSString *)restoreBackupData:(NSData *)data error:(NSError **)error { + std::vector entries; + // ZipLimits.forBackup: 512 MB. + if (!zip::read((const uint8_t *)data.bytes, data.length, entries, 512ull << 20)) { + if (error) *error = filesError(@"Couldn't read this backup: it isn't a ZIP, is damaged, or is too large."); + return nil; + } + NSFileManager *fm = NSFileManager.defaultManager; + NSURL *docs = documents(); + NSURL *staging = [docs URLByAppendingPathComponent:@".restore_tmp"]; + [fm removeItemAtURL:staging error:nil]; + [fm createDirectoryAtURL:staging withIntermediateDirectories:YES attributes:nil error:nil]; + BOOL looksValid = NO; + NSString *settings = @""; + for (const auto &e : entries) { + if (!zip::safeName(e.name)) continue; + NSString *name = @(e.name.c_str()); + if ([name isEqualToString:kSettings]) { + settings = [[NSString alloc] initWithBytes:e.data.data() length:e.data.size() encoding:NSUTF8StringEncoding] ?: @""; + continue; + } + NSString *top = name.pathComponents.firstObject; + const BOOL area = [kAreas containsObject:top] && name.pathComponents.count > 1; + if (!area && ![name isEqualToString:kAutosave]) continue; // not ours (Android's datastore, …) + NSURL *target = [staging URLByAppendingPathComponent:name]; + [fm createDirectoryAtURL:target.URLByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:nil]; + if ([dataOf(e.data) writeToURL:target atomically:NO]) looksValid = YES; + } + if (!looksValid) { + [fm removeItemAtURL:staging error:nil]; + if (error) *error = filesError(@"This file doesn't look like a Sizzle backup."); + return nil; + } + [self stop]; + for (NSString *area in kAreas) { + NSURL *src = [staging URLByAppendingPathComponent:area]; + if (![fm fileExistsAtPath:src.path]) continue; + NSURL *dst = [docs URLByAppendingPathComponent:area]; + [fm removeItemAtURL:dst error:nil]; + [fm moveItemAtURL:src toURL:dst error:nil]; + } + NSURL *autoSrc = [staging URLByAppendingPathComponent:kAutosave]; + if ([fm fileExistsAtPath:autoSrc.path]) { + NSURL *dst = [docs URLByAppendingPathComponent:kAutosave]; + [fm removeItemAtURL:dst error:nil]; + [fm moveItemAtURL:autoSrc toURL:dst error:nil]; + NSString *text = [NSString stringWithContentsOfURL:dst encoding:NSUTF8StringEncoding error:nil]; + if (text) [self loadProjectText:text error:nil]; + } + [fm removeItemAtURL:staging error:nil]; + [fm createDirectoryAtURL:[docs URLByAppendingPathComponent:@"songs"] withIntermediateDirectories:YES attributes:nil error:nil]; + [fm createDirectoryAtURL:[docs URLByAppendingPathComponent:@"samples"] withIntermediateDirectories:YES attributes:nil error:nil]; + [self rehydrateSamples]; + [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; + return settings; +} + +@end diff --git a/ios/app/Host/SizzleSession+Internal.h b/ios/app/Host/SizzleSession+Internal.h index 9c51765..cf8b3de 100644 --- a/ios/app/Host/SizzleSession+Internal.h +++ b/ios/app/Host/SizzleSession+Internal.h @@ -20,4 +20,14 @@ - (void)rehydrateSamples; /// The sample store (thread-safe on its own). - (sizzle::sampler::SampleStore &)sampleStore; + +// For the MIDI threads (SizzleMidi): no lock taken. +/// Queue a note for the audio thread. Callers must not push concurrently (the +/// sound module's lock serialises them). +- (void)midiNoteOn:(int)note velocity:(int)velocity channel:(int)channel; +- (void)midiNoteOff:(int)note channel:(int)channel; +/// The engine and song, for lock-free reads (isPlaying, pollMidiOut, the tempo) +/// and the engine's atomic setters. Both live as long as the session. +- (sizzle::engine::Engine *)enginePointer; +- (const sizzle::model::Project *)projectPointer; @end diff --git a/ios/app/Host/SizzleSession+Record.h b/ios/app/Host/SizzleSession+Record.h new file mode 100644 index 0000000..b16abf4 --- /dev/null +++ b/ios/app/Host/SizzleSession+Record.h @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession.h" + +NS_ASSUME_NONNULL_BEGIN + +/// Master-bus recording (Android's MasterRecorder + the mixer's record toolbar). +/// Arm it, and the next Play (or an external MIDI clock Start) captures the final +/// stereo mix to a 16-bit WAV, until a tail of [recordTailBars] bars after the +/// sequencer stops. Takes go to Documents/Recordings/sizzle-yyyyMMdd-HHmmss.wav +/// (visible in the Files app). The audio thread only writes into a ring buffer; a +/// writer thread does the file I/O. +@interface SizzleSession (Record) +@property (nonatomic) BOOL recordArmed; +/// FX tail captured after the sequencer stops, in bars (0..4). +@property (nonatomic) NSInteger recordTailBars; +/// True while a take is capturing (from its start until the file is finished). +@property (nonatomic, readonly) BOOL masterRecording; +/// The last finished take, if any (this run of the app). +@property (nonatomic, readonly, nullable) NSURL *lastRecordingURL; +@property (nonatomic, readonly) NSURL *recordingsDirectory; +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Record.mm b/ios/app/Host/SizzleSession+Record.mm new file mode 100644 index 0000000..35628b4 --- /dev/null +++ b/ios/app/Host/SizzleSession+Record.mm @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession+Record.h" +#import "SizzleSession+Internal.h" + +#include +#include +#include +#include +#include +#include + +using namespace sizzle; + +namespace { + +/// MasterRecorder.kt: a single-producer / single-consumer ring of interleaved +/// stereo floats (about two seconds), drained by a writer thread into a 16-bit +/// stereo WAV whose header sizes are patched at the end. +class MasterRecorder final : public engine::MasterSink { +public: + MasterRecorder(int sampleRate, NSURL *dir) : sr(sampleRate), ring((size_t)std::max(2, sampleRate * 4)), dir(dir) {} + ~MasterRecorder() override { capturing.store(false); if (writer.joinable()) writer.join(); } + + bool isActive() const override { return active.load(); } + + /// Main thread (Play) or the MIDI thread (an external clock Start). + bool begin() override { + if (active.load()) return false; + if (writer.joinable()) writer.join(); // the previous take's thread has finished (active is false) + writePos.store(0); readPos.store(0); + active.store(true); + capturing.store(true); + NSDate *start = [NSDate date]; + NSURL *temp = [dir URLByAppendingPathComponent:@".take.wav"]; + writer = std::thread([this, temp, start] { + const bool ok = writeLoop(temp.fileSystemRepresentation); + NSURL *done = ok ? finish(temp, start) : nil; + active.store(false); + dispatch_async(dispatch_get_main_queue(), ^{ + if (done) lastTake = done; + [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; + }); + }); + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; + }); + return true; + } + + /// Audio thread: no allocation, no locks; drops the frame if the writer starved. + void write(float left, float right) override { + if (!capturing.load(std::memory_order_relaxed)) return; + const uint64_t w = writePos.load(std::memory_order_relaxed); + if (w - readPos.load(std::memory_order_acquire) > ring.size() - 2) return; + ring[w % ring.size()] = left; + ring[(w + 1) % ring.size()] = right; + writePos.store(w + 2, std::memory_order_release); + } + + void endCapture() override { capturing.store(false); } + + NSURL *lastTake = nil; // main thread + +private: + bool writeLoop(const char *path) { + FILE *f = std::fopen(path, "wb"); + if (!f) { capturing.store(false); return false; } + writeHeader(f, 0); + uint64_t samples = 0; + constexpr size_t chunk = 4096; + int16_t out[chunk]; + bool ok = true; + for (;;) { + const uint64_t w = writePos.load(std::memory_order_acquire); + const uint64_t r = readPos.load(std::memory_order_relaxed); + if (r < w) { + const size_t n = (size_t)std::min(w - r, chunk); + for (size_t i = 0; i < n; ++i) { + const float s = std::clamp(ring[(r + i) % ring.size()], -1.f, 1.f); + out[i] = (int16_t)(int)(s * 32767.f); // little-endian host + } + if (std::fwrite(out, 2, n, f) != n) ok = false; + samples += n; + readPos.store(r + n, std::memory_order_release); + } else if (!capturing.load()) { + break; + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + } + writeHeader(f, samples); + ok = std::fclose(f) == 0 && ok; + return ok; + } + + void writeHeader(FILE *f, uint64_t sampleCount) { + const uint32_t data = (uint32_t)(sampleCount * 2); + auto u32 = [f](uint32_t v) { uint8_t b[4] = {(uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24)}; std::fwrite(b, 1, 4, f); }; + auto u16 = [f](uint16_t v) { uint8_t b[2] = {(uint8_t)v, (uint8_t)(v >> 8)}; std::fwrite(b, 1, 2, f); }; + std::fseek(f, 0, SEEK_SET); + std::fwrite("RIFF", 1, 4, f); u32(36 + data); std::fwrite("WAVE", 1, 4, f); + std::fwrite("fmt ", 1, 4, f); u32(16); u16(1); u16(2); u32((uint32_t)sr); u32((uint32_t)sr * 4); u16(4); u16(16); + std::fwrite("data", 1, 4, f); u32(data); + std::fseek(f, 0, SEEK_END); + } + + /// Give the finished take its date-time name (Android: sizzle-yyyyMMdd-HHmmss.wav). + NSURL *finish(NSURL *temp, NSDate *start) { + NSDateFormatter *df = [NSDateFormatter new]; + df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; + df.dateFormat = @"yyyyMMdd-HHmmss"; + NSString *base = [@"sizzle-" stringByAppendingString:[df stringFromDate:start]]; + NSURL *dst = [dir URLByAppendingPathComponent:[base stringByAppendingPathExtension:@"wav"]]; + for (int i = 2; [NSFileManager.defaultManager fileExistsAtPath:dst.path]; ++i) + dst = [dir URLByAppendingPathComponent:[NSString stringWithFormat:@"%@-%d.wav", base, i]]; + return [NSFileManager.defaultManager moveItemAtURL:temp toURL:dst error:nil] ? dst : nil; + } + + const int sr; + std::vector ring; + NSURL *dir; + std::atomic writePos{0}, readPos{0}; + std::atomic capturing{false}, active{false}; + std::thread writer; +}; + +MasterRecorder *gRecorder = nullptr; // lives as long as the app (the session never goes away) +bool gArmed = false; +NSInteger gTail = 2; + +} // namespace + +@implementation SizzleSession (Record) + +- (NSURL *)recordingsDirectory { + NSURL *docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject; + NSURL *dir = [docs URLByAppendingPathComponent:@"Recordings"]; + [NSFileManager.defaultManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:nil error:nil]; + return dir; +} + +- (void)rec_apply { + NSURL *dir = self.recordingsDirectory; + const bool armed = gArmed; + const int tail = (int)gTail; + [self edit:^(model::Project &, engine::Engine &e) { + if (!gRecorder) { + gRecorder = new MasterRecorder(e.sampleRate(), dir); + e.setMasterSink(gRecorder); + } + e.setRecordingArm(armed, tail); + }]; +} + +- (BOOL)recordArmed { return gArmed; } +- (void)setRecordArmed:(BOOL)armed { gArmed = armed; [self rec_apply]; } + +- (NSInteger)recordTailBars { return gTail; } +- (void)setRecordTailBars:(NSInteger)bars { gTail = std::clamp(bars, 0, 4); [self rec_apply]; } + +- (BOOL)masterRecording { return gRecorder && gRecorder->isActive(); } +- (nullable NSURL *)lastRecordingURL { return gRecorder ? gRecorder->lastTake : nil; } + +@end diff --git a/ios/app/Host/SizzleSession.h b/ios/app/Host/SizzleSession.h index 003046f..36a8730 100644 --- a/ios/app/Host/SizzleSession.h +++ b/ios/app/Host/SizzleSession.h @@ -156,6 +156,10 @@ NS_SWIFT_UI_ACTOR /// Saved on backgrounding and restored at launch (Documents/autosave.szg). - (void)autosave; +#pragma mark - Audio output +/// Pause the audio output (in the background with nothing to play) or start it again. +@property (nonatomic) BOOL audioSuspended; + #pragma mark - Samples /// A WAV into a Sampler pad / an SF2, XI or WAV into the SF2/XI loader. - (BOOL)loadSampleData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot pad:(NSInteger)pad error:(NSError **)error; diff --git a/ios/app/Host/SizzleSession.mm b/ios/app/Host/SizzleSession.mm index a844520..0e3d109 100644 --- a/ios/app/Host/SizzleSession.mm +++ b/ios/app/Host/SizzleSession.mm @@ -47,6 +47,9 @@ struct NoteQueue { } }; +/// The app paused the output on purpose (background, idle): don't restart it on a route change. +bool gAudioSuspended = false; + constexpr int kChunk = 192; // Android's block size: keeps the MIDI LFO's rate (see PORTING.md) NSError *sessionError(NSString *msg) { @@ -100,6 +103,7 @@ bool isSampleKey(const char *key) { std::unique_ptr _store; std::unique_ptr _engine; NoteQueue _notes; + NoteQueue _midiNotes; // pushed by the MIDI threads (serialised by the sound module's lock) std::vector _scratch; AVAudioEngine *_audio; AVAudioSourceNode *_source; @@ -158,6 +162,26 @@ bool isSampleKey(const char *key) { if (getenv("SIZZLE_NO_AUDIO")) return; // the Mac snapshot tool: no sound NSError *err = nil; if (![_audio startAndReturnError:&err]) NSLog(@"Sizzle audio: %@", err); + // A route or category change (the sample recorder switches to play-and-record, + // headphones, an audio interface) stops the engine; an interruption (a call) + // ends with it stopped. Start it again either way. + AVAudioEngine *audio = _audio; + void (^restart)(NSNotification *) = ^(NSNotification *) { + if (audio.isRunning || gAudioSuspended) return; +#if TARGET_OS_IPHONE + [[AVAudioSession sharedInstance] setActive:YES error:nil]; +#endif + NSError *e = nil; + if (![audio startAndReturnError:&e]) NSLog(@"Sizzle audio restart: %@", e); + }; + NSNotificationCenter *nc = NSNotificationCenter.defaultCenter; + [nc addObserverForName:AVAudioEngineConfigurationChangeNotification object:_audio queue:NSOperationQueue.mainQueue usingBlock:restart]; +#if TARGET_OS_IPHONE + [nc addObserverForName:AVAudioSessionInterruptionNotification object:nil queue:NSOperationQueue.mainQueue + usingBlock:^(NSNotification *n) { + if ([n.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue] == AVAudioSessionInterruptionTypeEnded) restart(n); + }]; +#endif } /// The audio thread. Never blocks: if the song is being edited, this block is silent. @@ -180,6 +204,9 @@ bool isSampleKey(const char *key) { case 3: e->auditionSlotOff(n.b); break; } }); + _midiNotes.drain([e](const NoteEvent &n) { + if (n.kind == 0) e->busNoteOn(n.a, n.b, n.c); else e->busNoteOff(n.a, n.b); + }); float *buf = _scratch.data(); for (AVAudioFrameCount done = 0; done < frames;) { int n = (int)std::min(kChunk, frames - done); @@ -335,6 +362,25 @@ bool isSampleKey(const char *key) { - (void)stop { [self edit:^(model::Project &, engine::Engine &e) { e.stop(); }]; } - (void)panic { [self edit:^(model::Project &, engine::Engine &e) { e.panic(); }]; } - (BOOL)isPlaying { return _engine->isPlaying(); } + +- (BOOL)audioSuspended { return !_audio.isRunning; } +- (void)setAudioSuspended:(BOOL)suspended { + if (getenv("SIZZLE_NO_AUDIO")) return; + gAudioSuspended = suspended; + if (suspended) { [_audio pause]; return; } + if (_audio.isRunning) return; +#if TARGET_OS_IPHONE + [[AVAudioSession sharedInstance] setActive:YES error:nil]; +#endif + NSError *e = nil; + if (![_audio startAndReturnError:&e]) NSLog(@"Sizzle audio resume: %@", e); +} + +#pragma mark - MIDI threads (SizzleSession+Internal.h) +- (void)midiNoteOn:(int)note velocity:(int)velocity channel:(int)channel { _midiNotes.push({0, channel, note, velocity}); } +- (void)midiNoteOff:(int)note channel:(int)channel { _midiNotes.push({1, channel, note, 0}); } +- (engine::Engine *)enginePointer { return _engine.get(); } +- (const model::Project *)projectPointer { return _project.get(); } - (NSInteger)currentLine { return _engine->transport().currentLine; } - (NSInteger)currentBeat { return _engine->transport().currentBeat; } diff --git a/ios/app/Host/ThemeLibrary.swift b/ios/app/Host/ThemeLibrary.swift new file mode 100644 index 0000000..f61c97c --- /dev/null +++ b/ios/app/Host/ThemeLibrary.swift @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// Colour themes (Android's ThemeIo + ThemeLibrary): the two stock palettes in +/// code, user themes as `SIZZLE-THEME 1` text in Documents/themes/.szt, the +/// same files the Android app imports and exports. +@MainActor +final class ThemeLibrary: ObservableObject { + static let shared = ThemeLibrary() + static let header = "SIZZLE-THEME 1" + + @Published private(set) var names: [String] = [] + + private var dir: URL { + let d = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("themes") + try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) + return d + } + + private init() { refresh() } + + /// Stock themes first, then the stored ones alphabetically. + func refresh() { + let files = (try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? [] + let user = files.filter { $0.hasSuffix(".szt") }.map { String($0.dropLast(4)) }.sorted() + names = Palette.stock.map(\.name) + user.filter { u in !Palette.stock.contains { $0.name == u } } + } + + func isStock(_ name: String) -> Bool { Palette.stock.contains { $0.name == name } } + + func palette(named name: String) -> Palette? { + if let p = Palette.stock.first(where: { $0.name == name }) { return p } + guard let text = try? String(contentsOf: file(name), encoding: .utf8) else { return nil } + return Self.parse(text) + } + + /// Apply a theme by name (unknown names fall back to the default) and remember it. + func select(_ name: String) { + let p = palette(named: name) ?? .amber + Theme.current = p + if AppSettings.shared.paletteName != p.name { AppSettings.shared.paletteName = p.name } + } + + /// Store and apply theme [text]; nil if it isn't a theme. + func importText(_ text: String) -> Palette? { + guard let p = Self.parse(text) else { return nil } + try? Self.export(p).write(to: file(p.name), atomically: true, encoding: .utf8) + refresh() + select(p.name) + return p + } + + func delete(_ name: String) { + guard !isStock(name) else { return } + try? FileManager.default.removeItem(at: file(name)) + refresh() + if Theme.current.name == name { select(Palette.amber.name) } + } + + /// The current theme as a .szt in a temporary folder, for sharing. + func exportFile() throws -> URL { + let p = Theme.current + let d = FileManager.default.temporaryDirectory.appendingPathComponent("ThemeExport", isDirectory: true) + try? FileManager.default.removeItem(at: d) + try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) + let url = d.appendingPathComponent(Self.sanitize(p.name) + ".szt") + try Self.export(p).write(to: url, atomically: true, encoding: .utf8) + return url + } + + private func file(_ name: String) -> URL { dir.appendingPathComponent(Self.sanitize(name) + ".szt") } + + /// Android's sanitize: anything but letters, digits, `._ -` becomes `_`. + static func sanitize(_ name: String) -> String { + let ok = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._ -") + let s = String(name.trimmingCharacters(in: .whitespaces).map { ok.contains($0) ? $0 : "_" }) + return s.isEmpty ? "theme" : s + } + + // MARK: ThemeIo + + static func export(_ p: Palette) -> String { + func hex(_ c: UInt32) -> String { String(format: "#%06X", c & 0xFFFFFF) } + return [header, "NAME=\(p.name)", "background=\(hex(p.background))", "surface=\(hex(p.surface))", + "grid=\(hex(p.grid))", "text=\(hex(p.text))", "textDim=\(hex(p.textDim))", "accent=\(hex(p.accent))", + "beat=\(hex(p.beat))", "bar=\(hex(p.bar))", "playhead=\(hex(p.playhead))", "danger=\(hex(p.danger))"] + .joined(separator: "\n") + "\n" + } + + /// Lenient about single colours (a bad one falls back to the default theme's), + /// strict about the header and a name. + static func parse(_ text: String) -> Palette? { + var map: [String: String] = [:] + var sawHeader = false + for raw in text.components(separatedBy: .newlines) { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.isEmpty { continue } + if line == header { sawHeader = true; continue } + if let eq = line.firstIndex(of: "="), eq > line.startIndex { + map[line[.. UInt32 { + guard var h = map[k] else { return fb } + if h.hasPrefix("#") { h.removeFirst() } + guard h.count == 6, let v = UInt32(h, radix: 16) else { return fb } + return v + } + return Palette(name: name, background: c("background", d.background), surface: c("surface", d.surface), + grid: c("grid", d.grid), text: c("text", d.text), textDim: c("textDim", d.textDim), + accent: c("accent", d.accent), beat: c("beat", d.beat), bar: c("bar", d.bar), + playhead: c("playhead", d.playhead), danger: c("danger", d.danger)) + } +} diff --git a/ios/app/project.yml b/ios/app/project.yml index 52fa05a..1d3325a 100644 --- a/ios/app/project.yml +++ b/ios/app/project.yml @@ -44,7 +44,7 @@ targets: SWIFT_OBJC_BRIDGING_HEADER: FX/Bridging.h # force_load: the effects are found through weak placeholder makers (Registry.cpp), # so without it the linker keeps the placeholders and skips the real ports. - OTHER_LDFLAGS: ["-lc++", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"] + OTHER_LDFLAGS: ["-lc++", "-lz", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"] Sizzle: type: application platform: iOS @@ -52,6 +52,10 @@ targets: path: Host/Info.plist properties: UIBackgroundModes: [audio] + NSMicrophoneUsageDescription: Sizzle records the microphone or an audio interface's input into samples. + # Documents (songs, samples, recordings, backups) shows in the Files app. + UIFileSharingEnabled: true + LSSupportsOpeningDocumentsInPlace: true # The app hosts the devices itself (in-process), so it compiles the plugin # classes and the editor too, and links the whole core. sources: @@ -72,6 +76,7 @@ targets: - sdk: AVFoundation.framework - sdk: CoreAudioKit.framework - sdk: CoreMIDI.framework + - sdk: GameController.framework settings: base: PRODUCT_BUNDLE_IDENTIFIER: cc.tiredsysadmin.ios.sizzle @@ -85,5 +90,5 @@ targets: ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon SWIFT_OBJC_BRIDGING_HEADER: Host/Bridging.h USER_HEADER_SEARCH_PATHS: ["$(SRCROOT)/FX"] - OTHER_LDFLAGS: ["-lc++", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"] + OTHER_LDFLAGS: ["-lc++", "-lz", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"] diff --git a/ios/app/tests/ScreenBridging.h b/ios/app/tests/ScreenBridging.h index e4b05c7..f979a55 100644 --- a/ios/app/tests/ScreenBridging.h +++ b/ios/app/tests/ScreenBridging.h @@ -7,3 +7,6 @@ #import "SizzleSession+Setup.h" #import "SizzleSession+Sources.h" #import "SizzleSession+Viz.h" +#import "SizzleSession+Record.h" +#import "SizzleMidi.h" +#import "SizzleSession+Files.h" diff --git a/ios/core/include/sizzle/Midi.hpp b/ios/core/include/sizzle/Midi.hpp new file mode 100644 index 0000000..67c634d --- /dev/null +++ b/ios/core/include/sizzle/Midi.hpp @@ -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 +#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 diff --git a/ios/core/src/io/Zip.cpp b/ios/core/src/io/Zip.cpp new file mode 100644 index 0000000..eb77529 --- /dev/null +++ b/ios/core/src/io/Zip.cpp @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "io/Zip.hpp" + +#include + +#include + +namespace sizzle::io::zip { + +namespace { + +void u16(std::vector &o, uint32_t v) { o.push_back((uint8_t)v); o.push_back((uint8_t)(v >> 8)); } +void u32(std::vector &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 &in, std::vector &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(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 &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(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 write(const std::vector &entries) { + std::vector 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 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 &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 &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 diff --git a/ios/core/src/io/Zip.hpp b/ios/core/src/io/Zip.hpp new file mode 100644 index 0000000..586a174 --- /dev/null +++ b/ios/core/src/io/Zip.hpp @@ -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 +#include +#include +#include + +namespace sizzle::io::zip { + +struct Entry { + std::string name; + std::vector data; +}; + +/** An archive of [entries], deflated. */ +std::vector write(const std::vector &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 &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 diff --git a/ios/core/tests/midi_test.cpp b/ios/core/tests/midi_test.cpp new file mode 100644 index 0000000..8868fd8 --- /dev/null +++ b/ios/core/tests/midi_test.cpp @@ -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 +#include +#include + +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 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> msgs; + std::vector 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{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{0x80, 60, 0}) && rt == std::vector{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{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{0xB0, 123, 0})); + + // ---- sound module + Rec r; + MidiSoundModule m(r); + std::vector 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{"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; +} diff --git a/ios/core/tests/zip_test.cpp b/ios/core/tests/zip_test.cpp new file mode 100644 index 0000000..8a3d0bc --- /dev/null +++ b/ios/core/tests/zip_test.cpp @@ -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 +#include +#include + +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 in = {{"project.szg", std::vector(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 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 j((std::istreambuf_iterator(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; +} diff --git a/versions.properties b/versions.properties index 05c64da..46f7016 100644 --- a/versions.properties +++ b/versions.properties @@ -17,8 +17,8 @@ android.versionCode = 70 # iOS/iPadOS (cc.tiredsysadmin.ios.sizzle): the AUv3 plugin app in ios/app; the # Makefile there passes these to Xcode and names the .ipa by versionCode. (The # TrollStore spike in ios/spike keeps its own version in its project.yml.) -ios.versionName = 0.5.0 -ios.versionCode = 10 +ios.versionName = 0.6.0 +ios.versionCode = 11 macos.versionName = - linux.versionName = - bsd.versionName = -