From 29650b88d74e73229270c2f549b21e205f5bdb4a Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Mon, 16 Nov 2026 09:15:28 +0100 Subject: [PATCH] iOS milestone 3 groundwork: SizzleSession bridge, app shell with tabs, slot-backed editors, screen snapshots SizzleSession owns the song, engine (192-frame chunks, try-lock on the audio thread), samples and audio output; AppModel/RootView give the four tabs; DeviceModel now works on toolbox slots too; make screen-snapshots renders the app's tabs on the Mac. Co-Authored-By: Claude Opus 5.5 --- ios/Makefile | 19 + ios/app/FX/Editor/Controls.swift | 15 + ios/app/FX/Editor/DeviceEditor.swift | 12 +- ios/app/FX/Editor/DeviceModel.swift | 91 +-- ios/app/Host/AppModel.swift | 66 ++ ios/app/Host/Bridging.h | 4 + ...{ContentView.swift => DeviceLabView.swift} | 2 +- ios/app/Host/RootView.swift | 77 +++ ios/app/Host/Screens/MixScreen.swift | 12 + ios/app/Host/Screens/SetupScreen.swift | 12 + ios/app/Host/Screens/ToolboxScreen.swift | 12 + ios/app/Host/Screens/TrackerScreen.swift | 12 + ios/app/Host/SizzleApp.swift | 2 +- ios/app/Host/SizzleSession+Internal.h | 21 + ios/app/Host/SizzleSession+Mix.h | 12 + ios/app/Host/SizzleSession+Mix.mm | 10 + ios/app/Host/SizzleSession+Setup.h | 12 + ios/app/Host/SizzleSession+Setup.mm | 10 + ios/app/Host/SizzleSession+Tracker.h | 12 + ios/app/Host/SizzleSession+Tracker.mm | 10 + ios/app/Host/SizzleSession.h | 165 +++++ ios/app/Host/SizzleSession.mm | 583 ++++++++++++++++++ ios/app/Host/SlotDeviceModel.swift | 36 ++ ios/app/tests/ScreenBridging.h | 6 + ios/app/tests/editor_snapshots.swift | 2 +- ios/app/tests/screen_snapshots.swift | 43 ++ 26 files changed, 1211 insertions(+), 47 deletions(-) create mode 100644 ios/app/Host/AppModel.swift rename ios/app/Host/{ContentView.swift => DeviceLabView.swift} (99%) create mode 100644 ios/app/Host/RootView.swift create mode 100644 ios/app/Host/Screens/MixScreen.swift create mode 100644 ios/app/Host/Screens/SetupScreen.swift create mode 100644 ios/app/Host/Screens/ToolboxScreen.swift create mode 100644 ios/app/Host/Screens/TrackerScreen.swift create mode 100644 ios/app/Host/SizzleSession+Internal.h create mode 100644 ios/app/Host/SizzleSession+Mix.h create mode 100644 ios/app/Host/SizzleSession+Mix.mm create mode 100644 ios/app/Host/SizzleSession+Setup.h create mode 100644 ios/app/Host/SizzleSession+Setup.mm create mode 100644 ios/app/Host/SizzleSession+Tracker.h create mode 100644 ios/app/Host/SizzleSession+Tracker.mm create mode 100644 ios/app/Host/SizzleSession.h create mode 100644 ios/app/Host/SizzleSession.mm create mode 100644 ios/app/Host/SlotDeviceModel.swift create mode 100644 ios/app/tests/ScreenBridging.h create mode 100644 ios/app/tests/screen_snapshots.swift diff --git a/ios/Makefile b/ios/Makefile index 09518b8..6258d1e 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -112,6 +112,25 @@ build/snapshots/editor_snapshots: build/snapshots/libsizzlesnap.dylib $(EDITOR_S editor-snapshots: build/snapshots/editor_snapshots cd build/snapshots && ./editor_snapshots png +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 $(shell find app/Host/Screens -name '*.swift') +$(SNAPDIR)/libsizzlescreens.dylib: $(AU_SRC) $(wildcard app/Host/SizzleSession*.mm app/Host/SizzleSession*.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 + +$(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 \ + -o $@ $(SCREEN_SWIFT) app/tests/screen_snapshots.swift -L$(SNAPDIR) -lsizzlescreens -Xlinker -rpath -Xlinker @executable_path + cp app/FX/DeviceLayouts.json $(SNAPDIR)/ + +screen-snapshots: $(SNAPDIR)/screen_snapshots + cd $(SNAPDIR) && ./screen_snapshots png $(CURDIR)/../samples/demo.sng + app/FX/Info.plist app/FX/Components.gen.h: app/components.txt tools/gen_components.py python3 tools/gen_components.py app/components.txt app/FX/Info.plist app/FX/Components.gen.h diff --git a/ios/app/FX/Editor/Controls.swift b/ios/app/FX/Editor/Controls.swift index 19881b8..c166115 100644 --- a/ios/app/FX/Editor/Controls.swift +++ b/ios/app/FX/Editor/Controls.swift @@ -3,6 +3,21 @@ import SwiftUI +/// Rendering for the Mac snapshot tools (make editor-snapshots / screen-snapshots): +/// ImageRenderer can't draw scroll views, so content scrolls only when not snapshotting. +enum Snapshot { + static var active = false +} + +/// A vertical ScrollView, or a plain stack in snapshot mode. +struct SnapScroll: View { + @ViewBuilder let content: () -> Content + var body: some View { + if Snapshot.active { VStack(spacing: 0) { content(); Spacer(minLength: 0) } } + else { ScrollView { content() } } + } +} + /// Sizzle's dark retro palette (Android's default theme) and the card tones. enum Theme { static let background = Color(red: 0.07, green: 0.08, blue: 0.09) diff --git a/ios/app/FX/Editor/DeviceEditor.swift b/ios/app/FX/Editor/DeviceEditor.swift index 0931398..c1b1f85 100644 --- a/ios/app/FX/Editor/DeviceEditor.swift +++ b/ios/app/FX/Editor/DeviceEditor.swift @@ -13,18 +13,16 @@ import UIKit struct DeviceEditor: View { @StateObject var model: DeviceModel @State var page = 0 - /// Render without a ScrollView (the Mac snapshot tool; ImageRenderer can't draw one). - static var snapshot = false var body: some View { - let pages = Layouts.pages(for: model.au.toolboxType, allKeys: model.order) + let pages = Layouts.pages(for: model.toolboxType, allKeys: model.order) VStack(alignment: .leading, spacing: 8) { HStack { - Text(model.au.displayName.uppercased()).font(Theme.mono(15)).foregroundColor(Theme.accent) + Text(model.displayName.uppercased()).font(Theme.mono(15)).foregroundColor(Theme.accent) Spacer() - if let presets = model.au.factoryPresets, !presets.isEmpty { + if !model.presetNames.isEmpty { Menu { - ForEach(presets, id: \.number) { p in Button(p.name) { model.applyPreset(p) } } + ForEach(model.presetNames, id: \.self) { name in Button(name) { model.applyPreset(named: name) } } } label: { Text("PRESET: \(model.presetName ?? "—") ▾").font(Theme.mono(12)).foregroundColor(Theme.accent) } @@ -51,7 +49,7 @@ struct DeviceEditor: View { CardView(panel: panel, model: model) } } - if DeviceEditor.snapshot { cards; Spacer(minLength: 0) } else { ScrollView { cards } } + SnapScroll { cards } } .padding(10) .background(Theme.background) diff --git a/ios/app/FX/Editor/DeviceModel.swift b/ios/app/FX/Editor/DeviceModel.swift index e85ca6e..44aacea 100644 --- a/ios/app/FX/Editor/DeviceModel.swift +++ b/ios/app/FX/Editor/DeviceModel.swift @@ -4,10 +4,8 @@ import AudioToolbox import Foundation -/// One parameter as the editor sees it: the AU parameter plus what Sizzle's spec -/// says about it (default, whole numbers, label). +/// One parameter as the editor sees it: what Sizzle's spec says about it. struct ParamInfo { - let param: AUParameter let key: String let label: String let min: Float @@ -20,46 +18,65 @@ struct ParamInfo { var isToggle: Bool { !isEnum && key.hasSuffix("On") && min == 0 && max == 1 } } -/// The editor's view of a SizzleDeviceAU: every parameter's value, kept in step -/// with the AU (host automation, presets) through a parameter observer. +/// The editor's view of one device, whichever backs it: an AUv3 (the plugin +/// extension, the device lab) or a toolbox slot of the open song (the app's +/// Toolbox tab). Values are numbers; choice lists by index. @MainActor final class DeviceModel: ObservableObject { - let au: SizzleDeviceAU + let toolboxType: String + let displayName: String let params: [String: ParamInfo] let order: [String] + let presetNames: [String] @Published private(set) var values: [String: Float] = [:] @Published var presetName: String? - private var token: AUParameterObserverToken? - init(au: SizzleDeviceAU) { - self.au = au - var params: [String: ParamInfo] = [:] - var order: [String] = [] - var values: [String: Float] = [:] - for p in au.parameterTree?.allParameters ?? [] { - let info = ParamInfo(param: p, key: p.identifier, label: au.specLabel(for: p), - min: p.minValue, max: p.maxValue, def: au.defaultValue(for: p), - isInt: au.isIntegerParameter(p), choices: p.valueStrings ?? []) - params[p.identifier] = info - order.append(p.identifier) - values[p.identifier] = p.value - } - self.params = params - self.order = order + private let write: (String, Float) -> Void + private let applyPresetNamed: (String) -> Void + private let reread: () -> [String: Float] + private var cleanup: () -> Void = {} + + /// The designated initializer; the app adds a slot-backed one (Host/SlotDeviceModel.swift). + init(toolboxType: String, displayName: String, infos: [ParamInfo], values: [String: Float], + presetNames: [String], write: @escaping (String, Float) -> Void, + applyPreset: @escaping (String) -> Void, reread: @escaping () -> [String: Float]) { + self.toolboxType = toolboxType + self.displayName = displayName + self.params = Dictionary(uniqueKeysWithValues: infos.map { ($0.key, $0) }) + self.order = infos.map { $0.key } self.values = values + self.presetNames = presetNames + self.write = write + self.applyPresetNamed = applyPreset + self.reread = reread + } + + deinit { cleanup() } + + /// Backed by an AUv3: its parameter tree, presets and host automation. + convenience init(au: SizzleDeviceAU) { + let all = au.parameterTree?.allParameters ?? [] + let infos = all.map { p in + ParamInfo(key: p.identifier, label: au.specLabel(for: p), min: p.minValue, max: p.maxValue, + def: au.defaultValue(for: p), isInt: au.isIntegerParameter(p), choices: p.valueStrings ?? []) + } + let byKey = Dictionary(uniqueKeysWithValues: all.map { ($0.identifier, $0) }) + let presets = au.factoryPresets ?? [] + var token: AUParameterObserverToken? + self.init(toolboxType: au.toolboxType, displayName: au.displayName, infos: infos, + values: Dictionary(uniqueKeysWithValues: all.map { ($0.identifier, $0.value) }), + presetNames: presets.map { $0.name }, + write: { key, v in byKey[key]?.setValue(v, originator: token) }, + applyPreset: { name in if let p = presets.first(where: { $0.name == name }) { au.currentPreset = p } }, + reread: { Dictionary(uniqueKeysWithValues: all.map { ($0.identifier, $0.value) }) }) presetName = au.currentPreset?.name token = au.parameterTree?.token(byAddingParameterObserver: { [weak self] address, value in - DispatchQueue.main.async { self?.observed(address: address, value: value) } + DispatchQueue.main.async { + guard let self = self, let p = all.first(where: { $0.address == address }) else { return } + self.values[p.identifier] = value + } }) - } - - deinit { - if let token = token { au.parameterTree?.removeParameterObserver(token) } - } - - private func observed(address: AUParameterAddress, value: AUValue) { - guard let p = au.parameterTree?.parameter(withAddress: address) else { return } - values[p.identifier] = value + if let tree = au.parameterTree, let t = token { cleanup = { tree.removeParameterObserver(t) } } } func value(_ key: String) -> Float { values[key] ?? params[key]?.def ?? 0 } @@ -69,7 +86,7 @@ final class DeviceModel: ObservableObject { var x = Swift.min(Swift.max(v, info.min), info.max) if info.isInt { x = x.rounded() } values[key] = x - info.param.setValue(x, originator: token) + write(key, x) } func choice(_ key: String) -> String { @@ -78,9 +95,9 @@ final class DeviceModel: ObservableObject { return info.choices[Swift.max(0, Swift.min(info.choices.count - 1, i))] } - func applyPreset(_ preset: AUAudioUnitPreset) { - au.currentPreset = preset - presetName = preset.name - for (key, info) in params { values[key] = info.param.value } + func applyPreset(named name: String) { + applyPresetNamed(name) + presetName = name + values = reread() } } diff --git a/ios/app/Host/AppModel.swift b/ios/app/Host/AppModel.swift new file mode 100644 index 0000000..7a0e928 --- /dev/null +++ b/ios/app/Host/AppModel.swift @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Combine +import SwiftUI + +/// The app's UI state around the open song (SizzleSession): the iOS counterpart +/// of the Android app's AppViewModel. Screens read the song through `session` +/// and re-render when `revision` changes; transport state is polled at display +/// rate while playing. +@MainActor +final class AppModel: ObservableObject { + enum Tab: Int, CaseIterable { case tracker, mix, toolbox, setup } + + let session = SizzleSession.shared + /// The app's instance (the snapshot tool makes its own). + static let main = AppModel() + + /// Bumped whenever the song changes (any edit, load, transport change). + @Published private(set) var revision = 0 + @Published var tab: Tab = .tracker + + // Transport, polled ~30×/s. + @Published private(set) var isPlaying = false + @Published private(set) var currentLine = 0 + @Published private(set) var currentBeat = 0 + + // Tracker cursor (Android: cursorLine / cursorTrack / column). + enum Column: Int { case note, velocity, channel } + @Published var cursorTrack = 0 + @Published var cursorLine = 0 + @Published var cursorColumn: Column = .note + + // On-screen keyboard (Android: kbdChannel / kbdOctave / kbdVelocity). + @Published var kbdChannel = 1 + @Published var kbdOctave = 4 + @Published var kbdVelocity = 100 + + /// The toolbox slot whose editor is open, if any. + @Published var editingSlot: Int? + + private var observer: NSObjectProtocol? + private var timer: Timer? + + init() { + observer = NotificationCenter.default.addObserver(forName: .SizzleSessionDidChange, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in self?.revision += 1 } + } + timer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] _ in + Task { @MainActor in self?.pollTransport() } + } + } + + private func pollTransport() { + let playing = session.isPlaying + if playing != isPlaying { isPlaying = playing } + if playing { + let line = session.currentLine, beat = session.currentBeat + if line != currentLine { currentLine = line } + if beat != currentBeat { currentBeat = beat } + } + } + + func playPause() { session.isPlaying ? session.pause() : session.play() } + func stop() { session.stop() } +} diff --git a/ios/app/Host/Bridging.h b/ios/app/Host/Bridging.h index 69a669b..31156b5 100644 --- a/ios/app/Host/Bridging.h +++ b/ios/app/Host/Bridging.h @@ -1,3 +1,7 @@ #import "ObjC/SPKTry.h" #import "SizzleHost.h" #import "SizzleFXViewController.h" +#import "SizzleSession.h" +#import "SizzleSession+Tracker.h" +#import "SizzleSession+Mix.h" +#import "SizzleSession+Setup.h" diff --git a/ios/app/Host/ContentView.swift b/ios/app/Host/DeviceLabView.swift similarity index 99% rename from ios/app/Host/ContentView.swift rename to ios/app/Host/DeviceLabView.swift index 286dced..d316171 100644 --- a/ios/app/Host/ContentView.swift +++ b/ios/app/Host/DeviceLabView.swift @@ -7,7 +7,7 @@ import UniformTypeIdentifiers /// The app for now: play any Sizzle instrument through any Sizzle effect from the /// keyboard or a MIDI controller, edit them, load samples, and measure each device /// on this iPad. The tracker and the rest of Sizzle come in later milestones. -struct ContentView: View { +struct DeviceLabView: View { @StateObject private var model = HostModel() @StateObject private var check = PluginCheck() @State private var importing = false diff --git a/ios/app/Host/RootView.swift b/ios/app/Host/RootView.swift new file mode 100644 index 0000000..75207fd --- /dev/null +++ b/ios/app/Host/RootView.swift @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Sizzle's four tabs (Tracker, Mix, Toolbox, Setup) with a bottom bar in +/// 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 + init(model: AppModel? = nil) { app = model ?? AppModel.main } + @Environment(\.scenePhase) private var phase + @Environment(\.verticalSizeClass) private var vClass + + var body: some View { + GeometryReader { geo in + let landscape = geo.size.width > geo.size.height + Group { + if landscape { + HStack(spacing: 0) { rail; Divider().background(Theme.grid); screen } + } else { + VStack(spacing: 0) { screen; Divider().background(Theme.grid); bar } + } + } + .background(Theme.background.ignoresSafeArea()) + } + .environmentObject(app) + .preferredColorScheme(.dark) + .onChange(of: phase) { p in if p != .active { app.session.autosave() } } + } + + @ViewBuilder private var screen: some View { + Group { + switch app.tab { + case .tracker: TrackerScreen() + case .mix: MixScreen() + case .toolbox: ToolboxScreen() + case .setup: SetupScreen() + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private let tabs: [(AppModel.Tab, String, String)] = [ + (.tracker, "Tracker", "square.grid.3x3"), (.mix, "Mix", "slider.vertical.3"), + (.toolbox, "Toolbox", "square.grid.2x2"), (.setup, "Setup", "gearshape"), + ] + + private var bar: some View { + HStack { + ForEach(tabs, id: \.0) { t in tabButton(t).frame(maxWidth: .infinity) } + } + .padding(.vertical, 6) + .background(Theme.surface) + } + + private var rail: some View { + VStack(spacing: 18) { + ForEach(tabs, id: \.0) { t in tabButton(t) } + Spacer() + } + .padding(.top, 16).frame(width: 84) + .background(Theme.surface) + } + + private func tabButton(_ t: (AppModel.Tab, String, String)) -> some View { + let on = app.tab == t.0 + return VStack(spacing: 3) { + Image(systemName: t.2).font(.system(size: 18)) + .frame(width: 56, height: 30) + .background(on ? Theme.accent : Color.clear, in: Capsule()) + .foregroundColor(on ? Theme.background : Theme.dim) + Text(t.1).font(.system(size: 12, weight: on ? .bold : .regular)).foregroundColor(on ? Theme.accent : Theme.dim) + } + .contentShape(Rectangle()) + .onTapGesture { app.tab = t.0 } + } +} diff --git a/ios/app/Host/Screens/MixScreen.swift b/ios/app/Host/Screens/MixScreen.swift new file mode 100644 index 0000000..fe892fa --- /dev/null +++ b/ios/app/Host/Screens/MixScreen.swift @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Placeholder: being ported from the Android app. +struct MixScreen: View { + @EnvironmentObject var app: AppModel + var body: some View { + Text("Mix").font(Theme.mono(18)).foregroundColor(Theme.dim) + } +} diff --git a/ios/app/Host/Screens/SetupScreen.swift b/ios/app/Host/Screens/SetupScreen.swift new file mode 100644 index 0000000..ca76382 --- /dev/null +++ b/ios/app/Host/Screens/SetupScreen.swift @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Placeholder: being ported from the Android app. +struct SetupScreen: View { + @EnvironmentObject var app: AppModel + var body: some View { + Text("Setup").font(Theme.mono(18)).foregroundColor(Theme.dim) + } +} diff --git a/ios/app/Host/Screens/ToolboxScreen.swift b/ios/app/Host/Screens/ToolboxScreen.swift new file mode 100644 index 0000000..1a2cc73 --- /dev/null +++ b/ios/app/Host/Screens/ToolboxScreen.swift @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Placeholder: being ported from the Android app. +struct ToolboxScreen: View { + @EnvironmentObject var app: AppModel + var body: some View { + Text("Toolbox").font(Theme.mono(18)).foregroundColor(Theme.dim) + } +} diff --git a/ios/app/Host/Screens/TrackerScreen.swift b/ios/app/Host/Screens/TrackerScreen.swift new file mode 100644 index 0000000..8e5cea0 --- /dev/null +++ b/ios/app/Host/Screens/TrackerScreen.swift @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// Placeholder: being ported from the Android app. +struct TrackerScreen: View { + @EnvironmentObject var app: AppModel + var body: some View { + Text("Tracker").font(Theme.mono(18)).foregroundColor(Theme.dim) + } +} diff --git a/ios/app/Host/SizzleApp.swift b/ios/app/Host/SizzleApp.swift index 9fa16d6..f041327 100644 --- a/ios/app/Host/SizzleApp.swift +++ b/ios/app/Host/SizzleApp.swift @@ -5,5 +5,5 @@ import SwiftUI @main struct SizzleApp: App { - var body: some Scene { WindowGroup { ContentView() } } + var body: some Scene { WindowGroup { RootView() } } } diff --git a/ios/app/Host/SizzleSession+Internal.h b/ios/app/Host/SizzleSession+Internal.h new file mode 100644 index 0000000..fde1d38 --- /dev/null +++ b/ios/app/Host/SizzleSession+Internal.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// For SizzleSession categories only (Objective-C++): run code on the song under +// the song lock. Each screen adds the API it needs in its own category file +// (SizzleSession+Tracker / +Mix / +Setup) instead of growing SizzleSession.mm. + +#import "SizzleSession.h" + +#include "sizzle/Engine.hpp" +#include "sizzle/Model.hpp" +#include "sampler/SampleStore.hpp" + +@interface SizzleSession () +/// Change the song: [body] runs under the lock, then SizzleSessionDidChange is posted. +- (void)edit:(void (^)(sizzle::model::Project &p, sizzle::engine::Engine &e))body; +/// Read the song consistently: [body] runs under the lock, nothing is posted. +- (void)read:(void (^)(const sizzle::model::Project &p, const sizzle::engine::Engine &e))body; +/// The sample store (thread-safe on its own). +- (sizzle::sampler::SampleStore &)sampleStore; +@end diff --git a/ios/app/Host/SizzleSession+Mix.h b/ios/app/Host/SizzleSession+Mix.h new file mode 100644 index 0000000..54fa2fd --- /dev/null +++ b/ios/app/Host/SizzleSession+Mix.h @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession.h" + +NS_ASSUME_NONNULL_BEGIN + +/// API the Mix screen needs beyond SizzleSession.h. +@interface SizzleSession (Mix) +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Mix.mm b/ios/app/Host/SizzleSession+Mix.mm new file mode 100644 index 0000000..ed1e00c --- /dev/null +++ b/ios/app/Host/SizzleSession+Mix.mm @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession+Mix.h" +#import "SizzleSession+Internal.h" + +using namespace sizzle; + +@implementation SizzleSession (Mix) +@end diff --git a/ios/app/Host/SizzleSession+Setup.h b/ios/app/Host/SizzleSession+Setup.h new file mode 100644 index 0000000..5ea6061 --- /dev/null +++ b/ios/app/Host/SizzleSession+Setup.h @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession.h" + +NS_ASSUME_NONNULL_BEGIN + +/// API the Setup screen needs beyond SizzleSession.h. +@interface SizzleSession (Setup) +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Setup.mm b/ios/app/Host/SizzleSession+Setup.mm new file mode 100644 index 0000000..78433cb --- /dev/null +++ b/ios/app/Host/SizzleSession+Setup.mm @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession+Setup.h" +#import "SizzleSession+Internal.h" + +using namespace sizzle; + +@implementation SizzleSession (Setup) +@end diff --git a/ios/app/Host/SizzleSession+Tracker.h b/ios/app/Host/SizzleSession+Tracker.h new file mode 100644 index 0000000..f5a12a5 --- /dev/null +++ b/ios/app/Host/SizzleSession+Tracker.h @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession.h" + +NS_ASSUME_NONNULL_BEGIN + +/// API the Tracker screen needs beyond SizzleSession.h. +@interface SizzleSession (Tracker) +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Tracker.mm b/ios/app/Host/SizzleSession+Tracker.mm new file mode 100644 index 0000000..333be87 --- /dev/null +++ b/ios/app/Host/SizzleSession+Tracker.mm @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession+Tracker.h" +#import "SizzleSession+Internal.h" + +using namespace sizzle; + +@implementation SizzleSession (Tracker) +@end diff --git a/ios/app/Host/SizzleSession.h b/ios/app/Host/SizzleSession.h new file mode 100644 index 0000000..003046f --- /dev/null +++ b/ios/app/Host/SizzleSession.h @@ -0,0 +1,165 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// Posted on the main thread after anything in the song changed (edits, loads, +/// transport). The Swift AppModel turns it into a SwiftUI refresh. +extern NSNotificationName const SizzleSessionDidChange; + +/// One tracker cell (model::Cell): note (0..127, -1 empty, -2 note-off), +/// velocity (0..127), MIDI channel (0..16). +typedef struct { + int note; + int velocity; + int channel; +} SizzleCell; + +/// A device type the toolbox offers (from the generated specs). +@interface SizzleDeviceType : NSObject +@property (nonatomic, readonly) NSString *type; // ToolboxType name, "WAVETABLE" +@property (nonatomic, readonly) NSString *displayName; // "Wavetable" +@property (nonatomic, readonly) BOOL isInstrument; +/// MIDI effects (arpeggiator, transposer, LFO) act on notes, not audio. +@property (nonatomic, readonly) BOOL isMidiEffect; +@end + +/// One parameter of a device type (Android's ParamSpec). +@interface SizzleParamSpec : NSObject +@property (nonatomic, readonly) NSString *key; +@property (nonatomic, readonly) NSString *label; +@property (nonatomic, readonly) float defaultValue; // a choice index for lists +@property (nonatomic, readonly) float minValue; +@property (nonatomic, readonly) float maxValue; +@property (nonatomic, readonly) BOOL isInt; +@property (nonatomic, readonly) NSArray *choices; // empty for numbers +@end + +/** + * The open song and the engine playing it: the iOS counterpart of the Android + * app's Project + AudioEngine as AppViewModel holds them. Owns the C++ model + * (core/include/sizzle/Model.hpp), the engine (Engine.hpp), the sample store and + * the audio output (AVAudioEngine, rendering in 192-frame chunks like Android). + * + * Call from the main thread. Every change takes the song lock; the audio thread + * only try-locks it (a block that meets an edit in progress plays silence instead + * of waiting), so edits are always safe while playing. + */ +NS_SWIFT_UI_ACTOR +@interface SizzleSession : NSObject + +@property (class, nonatomic, readonly) SizzleSession *shared; + +/// Bumped on every change (also announced with SizzleSessionDidChange). +@property (nonatomic, readonly) NSUInteger revision; + +#pragma mark - Song settings +@property (nonatomic, copy) NSString *songName; +@property (nonatomic) float tempo; // BPM +@property (nonatomic) NSInteger signature; // index into signatureLabels +@property (nonatomic) NSInteger scale; // index into scaleLabels +@property (nonatomic) NSInteger rootNote; // 0..11 +@property (nonatomic) NSInteger activePattern; // pattern id 0..7 +@property (class, nonatomic, readonly) NSArray *signatureLabels; // "3/4", "4/4", "5/4" +@property (class, nonatomic, readonly) NSArray *scaleLabels; // "Chromatic", … +@property (nonatomic, readonly) NSInteger linesPerBeat; +@property (nonatomic, readonly) NSInteger beatsPerBar; +/// Pattern lengths the signature allows (lines), e.g. 16, 32, 64. +@property (nonatomic, readonly) NSArray *lengthOptions; +/// Pitch classes (0..11) in the song's scale and root. +@property (nonatomic, readonly) NSArray *scalePitchClasses; + +#pragma mark - Patterns (ids 0..7, 4 tracks) +- (NSInteger)lengthOfPattern:(NSInteger)pattern; +- (void)setLength:(NSInteger)lines ofPattern:(NSInteger)pattern; +- (NSString *)nameOfPattern:(NSInteger)pattern; +- (SizzleCell)cellInPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line; +- (void)setCell:(SizzleCell)cell inPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line; + +#pragma mark - Arrangement (8 lanes; a slot holds a pattern id, -1 empty, -2 note-off) +- (NSInteger)arrangementLane:(NSInteger)lane beat:(NSInteger)beat; +- (void)setArrangementLane:(NSInteger)lane beat:(NSInteger)beat pattern:(NSInteger)pattern; +- (BOOL)isLaneMuted:(NSInteger)lane; +- (void)setLane:(NSInteger)lane muted:(BOOL)muted; +@property (nonatomic) BOOL arrangementLoop; +@property (nonatomic) NSInteger arrangementBars; +@property (nonatomic, readonly) NSInteger lastFilledBeat; +/// Loop regions A (0) and B (1): enabled, start beat, end beat, repeats. +- (BOOL)regionEnabled:(NSInteger)region; +- (NSInteger)regionStart:(NSInteger)region; +- (NSInteger)regionEnd:(NSInteger)region; +- (NSInteger)regionRepeats:(NSInteger)region; +- (void)setRegion:(NSInteger)region enabled:(BOOL)enabled start:(NSInteger)start end:(NSInteger)end repeats:(NSInteger)repeats; + +#pragma mark - Transport (readable at display rate without the lock) +- (void)play; +- (void)playFromBeat:(NSInteger)beat; +- (void)pause; +- (void)stop; +- (void)panic; +@property (nonatomic, readonly) BOOL isPlaying; +@property (nonatomic, readonly) NSInteger currentLine; +@property (nonatomic, readonly) NSInteger currentBeat; + +#pragma mark - Mixer (4 channels) +- (NSInteger)instrumentSlotOfChannel:(NSInteger)ch; +- (void)setInstrumentSlot:(NSInteger)slot ofChannel:(NSInteger)ch; // -1 none +- (NSInteger)fxSlot:(NSInteger)i ofChannel:(NSInteger)ch; +- (void)setFxSlot:(NSInteger)i to:(NSInteger)slot ofChannel:(NSInteger)ch; // -1 none +- (NSInteger)midiChannelOfChannel:(NSInteger)ch; +- (void)setMidiChannel:(NSInteger)midi ofChannel:(NSInteger)ch; +- (float)volumeOfChannel:(NSInteger)ch; +- (void)setVolume:(float)volume ofChannel:(NSInteger)ch; +- (BOOL)isMuted:(NSInteger)ch; +- (void)setChannel:(NSInteger)ch muted:(BOOL)muted; +- (BOOL)isSolo:(NSInteger)ch; +- (void)setChannel:(NSInteger)ch solo:(BOOL)solo; +- (BOOL)hasLimiter:(NSInteger)ch; +- (void)setChannel:(NSInteger)ch limiter:(BOOL)limiter; +- (float)meterOfChannel:(NSInteger)ch; +- (BOOL)clippedChannel:(NSInteger)ch; + +#pragma mark - Toolbox (16 slots) +@property (class, nonatomic, readonly) NSArray *deviceTypes; +/// The slot's ToolboxType name, or "" when empty. +- (NSString *)typeOfSlot:(NSInteger)slot; +- (NSString *)nameOfSlot:(NSInteger)slot; +- (void)fillSlot:(NSInteger)slot withType:(NSString *)type; +- (void)clearSlot:(NSInteger)slot; +- (NSString *)valueOfSlot:(NSInteger)slot key:(NSString *)key; +- (void)setValue:(NSString *)value ofSlot:(NSInteger)slot key:(NSString *)key; +/// A number, stored as Android stores it (Kotlin's Float.toString text). +- (void)setNumber:(float)value ofSlot:(NSInteger)slot key:(NSString *)key; ++ (NSArray *)paramSpecsForType:(NSString *)type; +/// Factory preset names for a device type (Android's PresetLibrary set). +- (NSArray *)factoryPresetsForType:(NSString *)type; +- (void)applyFactoryPreset:(NSString *)name toSlot:(NSInteger)slot; + +#pragma mark - Live notes (keyboard, MIDI): queued to the audio thread +- (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)channel; +- (void)noteOff:(NSInteger)note midiChannel:(NSInteger)channel; +- (void)auditionSlot:(NSInteger)slot note:(NSInteger)note on:(BOOL)on; + +#pragma mark - Songs (Documents/songs/*.szg, the Android project format) +@property (nonatomic, readonly) NSArray *songNames; +- (BOOL)saveSongNamed:(NSString *)name error:(NSError **)error; +- (BOOL)loadSongNamed:(NSString *)name error:(NSError **)error; +- (BOOL)deleteSongNamed:(NSString *)name error:(NSError **)error; +- (void)newSong; +/// The song in the Android project format (.szg) / desktop format (.sng). +- (NSString *)projectText; +- (NSString *)sngText; +- (BOOL)loadProjectText:(NSString *)text error:(NSError **)error; +- (BOOL)importSngText:(NSString *)text error:(NSError **)error; +/// Saved on backgrounding and restored at launch (Documents/autosave.szg). +- (void)autosave; + +#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; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession.mm b/ios/app/Host/SizzleSession.mm new file mode 100644 index 0000000..e020835 --- /dev/null +++ b/ios/app/Host/SizzleSession.mm @@ -0,0 +1,583 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#import "SizzleSession+Internal.h" +#import + +#include +#include +#include +#include +#include +#include +#include +#include +#include "io/ProjectIo.hpp" +#include "io/SngFormat.hpp" +#include "sampler/SampleStore.hpp" +#include "sampler/SoundFontLoader.hpp" +#include "echofield/GrainSources.hpp" +#include "wavetable/WaveTables.hpp" +#include "sizzle/DeviceSpecs.gen.hpp" +#include "sizzle/Engine.hpp" +#include "sizzle/Model.hpp" + +using namespace sizzle; + +NSNotificationName const SizzleSessionDidChange = @"SizzleSessionDidChange"; + +namespace { + +/// Live note events from the UI / MIDI, drained by the audio thread before each +/// render (the engine's live-note calls must run on the audio thread). +struct NoteEvent { int kind, a, b, c; }; // kind: 0 bus on, 1 bus off, 2 audition on, 3 audition off +struct NoteQueue { + std::array ring; + std::atomic head{0}, tail{0}; + void push(NoteEvent e) { + uint32_t h = head.load(std::memory_order_relaxed); + if (h - tail.load(std::memory_order_acquire) >= ring.size()) return; // full: drop + ring[h % ring.size()] = e; + head.store(h + 1, std::memory_order_release); + } + template void drain(F f) { + uint32_t t = tail.load(std::memory_order_relaxed), h = head.load(std::memory_order_acquire); + for (; t != h; ++t) f(ring[t % ring.size()]); + tail.store(t, std::memory_order_release); + } +}; + +constexpr int kChunk = 192; // Android's block size: keeps the MIDI LFO's rate (see PORTING.md) + +NSError *sessionError(NSString *msg) { + return [NSError errorWithDomain:@"cc.tiredsysadmin.ios.sizzle" code:2 userInfo:@{NSLocalizedDescriptionKey: msg}]; +} + +/// Slot keys that hold a sample id (Sampler pads, SF2/XI loader, Grain Cloud custom source). +bool isSampleKey(const char *key) { + if (!std::strcmp(key, "sfSample")) return true; + if (!std::strncmp(key, "pad", 3)) { + const char *p = key + 3; + if (!*p) return false; + while (*p >= '0' && *p <= '9') ++p; + return *p == '\0'; + } + return false; +} + +} // namespace + +@implementation SizzleDeviceType { +@public + NSString *_type, *_displayName; + BOOL _isInstrument, _isMidiEffect; +} +- (NSString *)type { return _type; } +- (NSString *)displayName { return _displayName; } +- (BOOL)isInstrument { return _isInstrument; } +- (BOOL)isMidiEffect { return _isMidiEffect; } +@end + +@implementation SizzleParamSpec { +@public + NSString *_key, *_label; + float _def, _min, _max; + BOOL _isInt; + NSArray *_choices; +} +- (NSString *)key { return _key; } +- (NSString *)label { return _label; } +- (float)defaultValue { return _def; } +- (float)minValue { return _min; } +- (float)maxValue { return _max; } +- (BOOL)isInt { return _isInt; } +- (NSArray *)choices { return _choices; } +@end + +@implementation SizzleSession { + std::mutex _lock; // the song: UI writes under it, audio try-locks + std::unique_ptr _project; + std::unique_ptr _store; + std::unique_ptr _engine; + NoteQueue _notes; + std::vector _scratch; + AVAudioEngine *_audio; + AVAudioSourceNode *_source; + NSUInteger _revision; + NSURL *_docs; +} + ++ (SizzleSession *)shared { + static SizzleSession *s; + static dispatch_once_t once; + dispatch_once(&once, ^{ s = [SizzleSession new]; }); + return s; +} + +- (instancetype)init { + self = [super init]; + if (!self) return nil; + _docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject; + [NSFileManager.defaultManager createDirectoryAtURL:[_docs URLByAppendingPathComponent:@"songs"] withIntermediateDirectories:YES attributes:nil error:nil]; + [NSFileManager.defaultManager createDirectoryAtURL:[_docs URLByAppendingPathComponent:@"samples"] withIntermediateDirectories:YES attributes:nil error:nil]; + wavetable::WaveTables::prewarm(); + echofield::GrainSources::prewarm(); + _project = std::make_unique(); + _store = std::make_unique(); + [self startAudio]; + NSString *autosaved = [NSString stringWithContentsOfURL:[_docs URLByAppendingPathComponent:@"autosave.szg"] encoding:NSUTF8StringEncoding error:nil]; + if (autosaved) [self loadProjectText:autosaved error:nil]; + return self; +} + +#pragma mark - audio + +- (void)startAudio { +#if TARGET_OS_IPHONE + AVAudioSession *s = [AVAudioSession sharedInstance]; + [s setCategory:AVAudioSessionCategoryPlayback error:nil]; + [s setPreferredSampleRate:48000 error:nil]; + [s setPreferredIOBufferDuration:256.0 / 48000.0 error:nil]; + [s setActive:YES error:nil]; +#endif + _audio = [AVAudioEngine new]; + double sr = [_audio.outputNode outputFormatForBus:0].sampleRate; + if (sr <= 0) sr = 48000; + _engine = std::make_unique((int)sr, _store.get()); + _engine->setProject(_project.get()); + _scratch.assign(kChunk * 2, 0.f); + + __unsafe_unretained SizzleSession *weakSelf = self; // the session lives for the whole app + AVAudioFormat *fmt = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:sr channels:2]; + _source = [[AVAudioSourceNode alloc] initWithFormat:fmt renderBlock:^OSStatus(BOOL *isSilence, const AudioTimeStamp *ts, + AVAudioFrameCount frames, AudioBufferList *out) { + return [weakSelf render:frames into:out silence:isSilence]; + }]; + [_audio attachNode:_source]; + [_audio connect:_source to:_audio.mainMixerNode format:fmt]; + if (getenv("SIZZLE_NO_AUDIO")) return; // the Mac snapshot tool: no sound + NSError *err = nil; + if (![_audio startAndReturnError:&err]) NSLog(@"Sizzle audio: %@", err); +} + +/// The audio thread. Never blocks: if the song is being edited, this block is silent. +- (OSStatus)render:(AVAudioFrameCount)frames into:(AudioBufferList *)out silence:(BOOL *)isSilence { + float *L = (float *)out->mBuffers[0].mData; + float *R = out->mNumberBuffers > 1 ? (float *)out->mBuffers[1].mData : nullptr; + std::unique_lock guard(_lock, std::try_to_lock); + if (!guard.owns_lock()) { + std::memset(L, 0, frames * sizeof(float)); + if (R) std::memset(R, 0, frames * sizeof(float)); + *isSilence = YES; + return noErr; + } + engine::Engine *e = _engine.get(); + _notes.drain([e](const NoteEvent &n) { + switch (n.kind) { + case 0: e->busNoteOn(n.a, n.b, n.c); break; + case 1: e->busNoteOff(n.a, n.b); break; + case 2: e->auditionSlotOn(n.a, n.b); break; + case 3: e->auditionSlotOff(n.b); break; + } + }); + float *buf = _scratch.data(); + for (AVAudioFrameCount done = 0; done < frames;) { + int n = (int)std::min(kChunk, frames - done); + e->fillBlock(buf, n); + for (int i = 0; i < n; ++i) { + L[done + i] = buf[2 * i]; + if (R) R[done + i] = buf[2 * i + 1]; + } + done += (AVAudioFrameCount)n; + } + return noErr; +} + +#pragma mark - change plumbing + +/// Run [body] on the song under the lock, then announce the change. +- (void)edit:(void (^)(model::Project &p, engine::Engine &e))body { + { + std::lock_guard g(_lock); + body(*_project, *_engine); + } + [self changed]; +} + +- (void)read:(void (^)(const model::Project &p, const engine::Engine &e))body { + std::lock_guard g(_lock); + body(*_project, *_engine); +} + +- (sampler::SampleStore &)sampleStore { return *_store; } + +- (void)changed { + ++_revision; + [NSNotificationCenter.defaultCenter postNotificationName:SizzleSessionDidChange object:self]; +} + +- (NSUInteger)revision { return _revision; } + +#pragma mark - song settings + +- (NSString *)songName { return @(_project->name.c_str()); } +- (void)setSongName:(NSString *)name { std::string n = name.UTF8String; [self edit:^(model::Project &p, engine::Engine &) { p.name = n; }]; } +- (float)tempo { return _project->tempoBpm; } +- (void)setTempo:(float)tempo { [self edit:^(model::Project &p, engine::Engine &) { p.tempoBpm = std::clamp(tempo, 20.f, 300.f); }]; } +- (NSInteger)signature { return (NSInteger)_project->timeSignature; } +- (void)setSignature:(NSInteger)sig { + if (sig < 0 || sig >= model::TIME_SIGNATURE_COUNT) return; + [self edit:^(model::Project &p, engine::Engine &e) { + p.timeSignature = (model::TimeSignature)sig; + e.rebuildArrangement(); + }]; +} +- (NSInteger)scale { return (NSInteger)_project->scale; } +- (void)setScale:(NSInteger)s { if (s >= 0 && s < model::SCALE_COUNT) [self edit:^(model::Project &p, engine::Engine &) { p.scale = (model::Scale)s; }]; } +- (NSInteger)rootNote { return _project->rootNote; } +- (void)setRootNote:(NSInteger)r { [self edit:^(model::Project &p, engine::Engine &) { p.rootNote = (int)((r % 12 + 12) % 12); }]; } +- (NSInteger)activePattern { return _project->activePatternId; } +- (void)setActivePattern:(NSInteger)id { [self edit:^(model::Project &p, engine::Engine &) { if (p.pattern((int)id)) p.activePatternId = (int)id; }]; } + ++ (NSArray *)signatureLabels { + NSMutableArray *a = [NSMutableArray array]; + for (int i = 0; i < model::TIME_SIGNATURE_COUNT; ++i) [a addObject:@(model::info((model::TimeSignature)i).label)]; + return a; +} ++ (NSArray *)scaleLabels { + NSMutableArray *a = [NSMutableArray array]; + for (int i = 0; i < model::SCALE_COUNT; ++i) [a addObject:@(model::info((model::Scale)i).label)]; + return a; +} +- (NSInteger)linesPerBeat { return model::info(_project->timeSignature).linesPerBeat; } +- (NSInteger)beatsPerBar { return model::info(_project->timeSignature).beatsPerBar; } +- (NSArray *)lengthOptions { + const auto &i = model::info(_project->timeSignature); + return @[@(i.lengthOptions[0]), @(i.lengthOptions[1]), @(i.lengthOptions[2])]; +} +- (NSArray *)scalePitchClasses { + const auto &s = model::info(_project->scale); + NSMutableArray *a = [NSMutableArray array]; + for (int i = 0; i < s.count; ++i) [a addObject:@((s.intervals[i] + _project->rootNote) % 12)]; + return a; +} + +#pragma mark - patterns + +- (NSInteger)lengthOfPattern:(NSInteger)pattern { + const model::Pattern *p = _project->pattern((int)pattern); + return p ? p->length : 0; +} +- (void)setLength:(NSInteger)lines ofPattern:(NSInteger)pattern { + if (lines < 1 || lines > 512) return; + [self edit:^(model::Project &p, engine::Engine &) { if (auto *pt = p.pattern((int)pattern)) pt->resize((int)lines); }]; +} +- (NSString *)nameOfPattern:(NSInteger)pattern { + const model::Pattern *p = _project->pattern((int)pattern); + return p ? @(p->name.c_str()) : @""; +} +- (SizzleCell)cellInPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line { + const model::Pattern *p = _project->pattern((int)pattern); + if (!p || track < 0 || track >= model::Pattern::TRACK_COUNT || line < 0 || line >= p->length) return {-1, 127, 0}; + const model::Cell &c = p->cell((int)track, (int)line); + return {c.note, c.velocity, c.channel}; +} +- (void)setCell:(SizzleCell)cell inPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line { + [self edit:^(model::Project &p, engine::Engine &) { + model::Pattern *pt = p.pattern((int)pattern); + if (!pt || track < 0 || track >= model::Pattern::TRACK_COUNT || line < 0 || line >= pt->length) return; + model::Cell &c = pt->cell((int)track, (int)line); + c.note = std::clamp(cell.note, -2, 127); + c.velocity = std::clamp(cell.velocity, 0, 127); + c.channel = std::clamp(cell.channel, 0, 16); + }]; +} + +#pragma mark - arrangement + +- (NSInteger)arrangementLane:(NSInteger)lane beat:(NSInteger)beat { + if (lane < 0 || lane >= model::Arrangement::LANE_COUNT) return -1; + return _project->arrangement.patternAt((int)lane, (int)beat); +} +- (void)setArrangementLane:(NSInteger)lane beat:(NSInteger)beat pattern:(NSInteger)pattern { + [self edit:^(model::Project &p, engine::Engine &e) { p.arrangement.set((int)lane, (int)beat, (int)pattern); e.rebuildArrangement(); }]; +} +- (BOOL)isLaneMuted:(NSInteger)lane { return lane >= 0 && lane < 8 && _project->arrangement.laneMuted[(size_t)lane]; } +- (void)setLane:(NSInteger)lane muted:(BOOL)muted { + if (lane < 0 || lane >= 8) return; + [self edit:^(model::Project &p, engine::Engine &) { p.arrangement.laneMuted[(size_t)lane] = muted; }]; +} +- (BOOL)arrangementLoop { return _project->arrangement.loopEnabled; } +- (void)setArrangementLoop:(BOOL)on { [self edit:^(model::Project &p, engine::Engine &e) { p.arrangement.loopEnabled = on; e.refreshLoopPlaylist(); }]; } +- (NSInteger)arrangementBars { return _project->arrangement.lengthBars; } +- (void)setArrangementBars:(NSInteger)bars { + [self edit:^(model::Project &p, engine::Engine &) { p.arrangement.lengthBars = (int)std::clamp(bars, 1, model::Arrangement::MAX_BARS); }]; +} +- (NSInteger)lastFilledBeat { return _project->arrangement.lastFilledBeat(); } +- (const model::LoopRegion &)region:(NSInteger)r { return r == 1 ? _project->arrangement.regionB : _project->arrangement.regionA; } +- (BOOL)regionEnabled:(NSInteger)r { return [self region:r].enabled; } +- (NSInteger)regionStart:(NSInteger)r { return [self region:r].start; } +- (NSInteger)regionEnd:(NSInteger)r { return [self region:r].end; } +- (NSInteger)regionRepeats:(NSInteger)r { return [self region:r].repeats; } +- (void)setRegion:(NSInteger)r enabled:(BOOL)en start:(NSInteger)s end:(NSInteger)e repeats:(NSInteger)rep { + [self edit:^(model::Project &p, engine::Engine &eng) { + model::LoopRegion &g = r == 1 ? p.arrangement.regionB : p.arrangement.regionA; + g.enabled = en; g.start = (int)s; g.end = (int)e; g.repeats = (int)std::clamp(rep, 1, 99); + eng.refreshLoopPlaylist(); + }]; +} + +#pragma mark - transport + +- (void)play { [self edit:^(model::Project &, engine::Engine &e) { e.play(); }]; } +- (void)playFromBeat:(NSInteger)beat { [self edit:^(model::Project &, engine::Engine &e) { e.play((int)beat); }]; } +- (void)pause { [self edit:^(model::Project &, engine::Engine &e) { e.pause(); }]; } +- (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(); } +- (NSInteger)currentLine { return _engine->transport().currentLine; } +- (NSInteger)currentBeat { return _engine->transport().currentBeat; } + +#pragma mark - mixer + +- (model::MixerChannel *)ch:(NSInteger)c { return c >= 0 && c < 4 ? &_project->mixer.channels[(size_t)c] : nullptr; } +- (NSInteger)instrumentSlotOfChannel:(NSInteger)c { auto *m = [self ch:c]; return m ? m->instrumentSlot : -1; } +- (void)setInstrumentSlot:(NSInteger)slot ofChannel:(NSInteger)c { + [self edit:^(model::Project &p, engine::Engine &e) { if (c >= 0 && c < 4) { p.mixer.channels[(size_t)c].instrumentSlot = (int)slot; e.rebuildFxChains(); } }]; +} +- (NSInteger)fxSlot:(NSInteger)i ofChannel:(NSInteger)c { auto *m = [self ch:c]; return m && i >= 0 && i < 4 ? m->fxSlots[(size_t)i] : -1; } +- (void)setFxSlot:(NSInteger)i to:(NSInteger)slot ofChannel:(NSInteger)c { + [self edit:^(model::Project &p, engine::Engine &e) { + if (c >= 0 && c < 4 && i >= 0 && i < 4) { p.mixer.channels[(size_t)c].fxSlots[(size_t)i] = (int)slot; e.rebuildFxChains(); } + }]; +} +- (NSInteger)midiChannelOfChannel:(NSInteger)c { auto *m = [self ch:c]; return m ? m->midiChannel : 0; } +- (void)setMidiChannel:(NSInteger)midi ofChannel:(NSInteger)c { + [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].midiChannel = (int)std::clamp(midi, 0, 16); }]; +} +- (float)volumeOfChannel:(NSInteger)c { auto *m = [self ch:c]; return m ? m->volume : 0; } +- (void)setVolume:(float)v ofChannel:(NSInteger)c { + [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].volume = std::clamp(v, 0.f, 1.5f); }]; +} +- (BOOL)isMuted:(NSInteger)c { auto *m = [self ch:c]; return m && m->mute; } +- (void)setChannel:(NSInteger)c muted:(BOOL)v { [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].mute = v; }]; } +- (BOOL)isSolo:(NSInteger)c { auto *m = [self ch:c]; return m && m->solo; } +- (void)setChannel:(NSInteger)c solo:(BOOL)v { [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].solo = v; }]; } +- (BOOL)hasLimiter:(NSInteger)c { auto *m = [self ch:c]; return m && m->limiter; } +- (void)setChannel:(NSInteger)c limiter:(BOOL)v { [self edit:^(model::Project &p, engine::Engine &) { if (c >= 0 && c < 4) p.mixer.channels[(size_t)c].limiter = v; }]; } +- (float)meterOfChannel:(NSInteger)c { return _engine->channelMeter((int)c); } +- (BOOL)clippedChannel:(NSInteger)c { return _engine->channelClipped((int)c); } + +#pragma mark - toolbox + ++ (NSArray *)deviceTypes { + NSMutableArray *a = [NSMutableArray array]; + for (int i = 0; i < gen::deviceCount; ++i) { + const DeviceSpec &d = gen::devices[i]; + SizzleDeviceType *t = [SizzleDeviceType new]; + t->_type = @(d.type); + t->_displayName = @(d.displayName); + t->_isInstrument = d.kind == Kind::Instrument; + t->_isMidiEffect = !std::strcmp(d.type, "ARPEGGIATOR") || !std::strcmp(d.type, "TRANSPOSER") || !std::strcmp(d.type, "LFO"); + [a addObject:t]; + } + return a; +} + +- (NSString *)typeOfSlot:(NSInteger)slot { return slot >= 0 && slot < 16 ? @(_project->toolbox[(size_t)slot].type.c_str()) : @""; } +- (NSString *)nameOfSlot:(NSInteger)slot { return slot >= 0 && slot < 16 ? @(_project->toolbox[(size_t)slot].name.c_str()) : @""; } +- (void)fillSlot:(NSInteger)slot withType:(NSString *)type { + std::string t = type.UTF8String; + [self edit:^(model::Project &p, engine::Engine &e) { if (slot >= 0 && slot < 16) { p.toolbox[(size_t)slot].fill(t); e.rebuildFxChains(); } }]; +} +- (void)clearSlot:(NSInteger)slot { + [self edit:^(model::Project &p, engine::Engine &e) { + if (slot < 0 || slot >= 16) return; + p.toolbox[(size_t)slot].clearSlot(); + for (auto &c : p.mixer.channels) { // nothing may route to an empty slot + if (c.instrumentSlot == slot) c.instrumentSlot = -1; + for (auto &f : c.fxSlots) if (f == slot) f = -1; + } + e.rebuildFxChains(); + }]; +} +- (NSString *)valueOfSlot:(NSInteger)slot key:(NSString *)key { + if (slot < 0 || slot >= 16) return @""; + return @(_project->toolbox[(size_t)slot].s(key.UTF8String, "")); +} +- (void)setValue:(NSString *)value ofSlot:(NSInteger)slot key:(NSString *)key { + std::string k = key.UTF8String, v = value.UTF8String; + [self edit:^(model::Project &p, engine::Engine &) { if (slot >= 0 && slot < 16) p.toolbox[(size_t)slot].set(k.c_str(), v.c_str()); }]; +} +- (void)setNumber:(float)value ofSlot:(NSInteger)slot key:(NSString *)key { + std::string k = key.UTF8String; + [self edit:^(model::Project &p, engine::Engine &) { if (slot >= 0 && slot < 16) p.toolbox[(size_t)slot].set(k.c_str(), value); }]; +} + ++ (NSArray *)paramSpecsForType:(NSString *)type { + const DeviceSpec *d = findDevice(type.UTF8String); + NSMutableArray *a = [NSMutableArray array]; + for (int i = 0; d && i < d->paramCount; ++i) { + const ParamSpec &p = d->params[i]; + SizzleParamSpec *s = [SizzleParamSpec new]; + s->_key = @(p.key); s->_label = @(p.label); + s->_def = p.def; s->_min = p.isEnum() ? 0 : p.min; s->_max = p.isEnum() ? (float)(p.choiceCount() - 1) : p.max; + s->_isInt = p.isInt || p.isEnum(); + NSMutableArray *c = [NSMutableArray array]; + for (int k = 0; p.isEnum() && p.choices[k]; ++k) [c addObject:@(p.choices[k])]; + s->_choices = c; + [a addObject:s]; + } + return a; +} + +- (NSArray *)factoryPresetsForType:(NSString *)type { + NSMutableArray *a = [NSMutableArray array]; + for (int i = 0; i < gen::factoryPresetCount; ++i) + if (!std::strcmp(gen::factoryPresets[i].type, type.UTF8String)) [a addObject:@(gen::factoryPresets[i].name)]; + return a; +} +- (void)applyFactoryPreset:(NSString *)name toSlot:(NSInteger)slot { + std::string n = name.UTF8String; + [self edit:^(model::Project &p, engine::Engine &) { + if (slot < 0 || slot >= 16) return; + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + for (int i = 0; i < gen::factoryPresetCount; ++i) { + if (s.type != gen::factoryPresets[i].type || n != gen::factoryPresets[i].name) continue; + const char *const *kv = gen::factoryPresets[i].values; + for (int k = 0; kv[k] && kv[k + 1]; k += 2) s.set(kv[k], kv[k + 1]); + s.name = n; + } + }]; +} + +#pragma mark - live notes + +- (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)ch { + _notes.push({0, (int)ch, (int)note, (int)velocity}); +} +- (void)noteOff:(NSInteger)note midiChannel:(NSInteger)ch { _notes.push({1, (int)ch, (int)note, 0}); } +- (void)auditionSlot:(NSInteger)slot note:(NSInteger)note on:(BOOL)on { _notes.push({on ? 2 : 3, (int)slot, (int)note, 0}); } + +#pragma mark - songs + +- (NSURL *)songURL:(NSString *)name { + NSString *safe = [[name componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\:"]] componentsJoinedByString:@"_"]; + return [[_docs URLByAppendingPathComponent:@"songs"] URLByAppendingPathComponent:[safe stringByAppendingPathExtension:@"szg"]]; +} + +- (NSArray *)songNames { + NSArray *files = [NSFileManager.defaultManager contentsOfDirectoryAtURL:[_docs URLByAppendingPathComponent:@"songs"] includingPropertiesForKeys:nil options:0 error:nil]; + NSMutableArray *names = [NSMutableArray array]; + for (NSURL *u in files) if ([u.pathExtension isEqualToString:@"szg"]) [names addObject:u.URLByDeletingPathExtension.lastPathComponent]; + return [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; +} + +- (NSString *)projectText { + std::lock_guard g(_lock); + return @(io::ProjectIo::save(*_project).c_str()); +} + +- (NSString *)sngText { + std::lock_guard g(_lock); + return @(io::SngFormat::exportText(*_project).c_str()); +} + +- (BOOL)saveSongNamed:(NSString *)name error:(NSError **)error { + self.songName = name; + return [[self projectText] writeToURL:[self songURL:name] atomically:YES encoding:NSUTF8StringEncoding error:error]; +} + +- (BOOL)loadSongNamed:(NSString *)name error:(NSError **)error { + NSString *text = [NSString stringWithContentsOfURL:[self songURL:name] encoding:NSUTF8StringEncoding error:error]; + return text && [self loadProjectText:text error:error]; +} + +- (BOOL)deleteSongNamed:(NSString *)name error:(NSError **)error { + return [NSFileManager.defaultManager removeItemAtURL:[self songURL:name] error:error]; +} + +- (void)newSong { + [self edit:^(model::Project &p, engine::Engine &e) { + e.stop(); + p = model::Project(); + e.setProject(&p); + }]; +} + +- (BOOL)loadProjectText:(NSString *)text error:(NSError **)error { + std::string t = text.UTF8String ?: ""; + [self edit:^(model::Project &p, engine::Engine &e) { + e.stop(); + p = model::Project(); + io::ProjectIo::loadInto(p, t); + e.setProject(&p); + }]; + [self rehydrateSamples]; + return YES; +} + +- (BOOL)importSngText:(NSString *)text error:(NSError **)error { + std::string t = text.UTF8String ?: ""; + if (!io::SngFormat::looksLikeSng(t)) { if (error) *error = sessionError(@"This doesn't look like a Sizzle .sng song."); return NO; } + [self edit:^(model::Project &p, engine::Engine &e) { + e.stop(); + io::SngFormat::importInto(p, t); + e.setProject(&p); + }]; + return YES; +} + +- (void)autosave { + [[self projectText] writeToURL:[_docs URLByAppendingPathComponent:@"autosave.szg"] atomically:YES encoding:NSUTF8StringEncoding error:nil]; +} + +#pragma mark - samples + +- (NSURL *)sampleURL:(const std::string &)id { + NSString *safe = [[@(id.c_str()) componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\:"]] componentsJoinedByString:@"_"]; + return [[_docs URLByAppendingPathComponent:@"samples"] URLByAppendingPathComponent:[safe stringByAppendingPathExtension:@"wav"]]; +} + +/// Put back into the store every sample the song refers to, from Documents/samples. +- (void)rehydrateSamples { + std::vector ids; + { + std::lock_guard g(_lock); + for (auto &slot : _project->toolbox) + for (int i = 0; i < slot.values.size(); ++i) + if (isSampleKey(slot.values.keyAt(i)) && *slot.values.valueAt(i)) ids.emplace_back(slot.values.valueAt(i)); + } + for (auto &id : ids) { + if (_store->get(id.c_str())) continue; + NSData *d = [NSData dataWithContentsOfURL:[self sampleURL:id]]; + if (!d) continue; + if (auto s = sampler::SampleStore::decodeWav((const uint8_t *)d.bytes, d.length)) _store->put(id, std::move(*s)); + } +} + +- (BOOL)loadSampleData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot pad:(NSInteger)pad error:(NSError **)error { + NSString *type = [self typeOfSlot:slot]; + BOOL sf = [type isEqualToString:@"SOUNDFONT"]; + if (!sf && ![type isEqualToString:@"SAMPLER"]) { if (error) *error = sessionError(@"Pick a Sampler or an SF2/XI loader slot."); return NO; } + const uint8_t *bytes = (const uint8_t *)data.bytes; + std::optional sample; + int root = 60; + if (sf) { + if (auto l = sampler::SoundFontLoader::load(bytes, data.length)) { sample = std::move(l->sample); root = l->rootNote; } + } + if (!sample) sample = sampler::SampleStore::decodeWav(bytes, data.length); + if (!sample) { if (error) *error = sessionError(sf ? @"Not an SF2, XI or WAV file Sizzle can read." : @"Not a WAV file Sizzle can read."); return NO; } + std::string id = std::string(name.UTF8String) + "#" + NSUUID.UUID.UUIDString.UTF8String; + std::vector wav = sampler::SampleStore::encodeWav(*sample); + [[NSData dataWithBytes:wav.data() length:wav.size()] writeToURL:[self sampleURL:id] atomically:YES]; + _store->put(id, std::move(*sample)); + [self edit:^(model::Project &p, engine::Engine &) { + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + if (sf) { s.set("sfSample", id.c_str()); s.set("sfRoot", (float)root); } + else s.set(("pad" + std::to_string(pad)).c_str(), id.c_str()); + }]; + return YES; +} + +@end diff --git a/ios/app/Host/SlotDeviceModel.swift b/ios/app/Host/SlotDeviceModel.swift new file mode 100644 index 0000000..845b636 --- /dev/null +++ b/ios/app/Host/SlotDeviceModel.swift @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +extension DeviceModel { + /// Backed by toolbox slot [slot] of the open song. + convenience init(session: SizzleSession, slot: Int) { + let type = session.type(ofSlot: slot) + let specs = SizzleSession.paramSpecs(forType: type) + let infos = specs.map { s in + ParamInfo(key: s.key, label: s.label, min: s.minValue, max: s.maxValue, def: s.defaultValue, + isInt: s.isInt, choices: s.choices) + } + func read() -> [String: Float] { + var v: [String: Float] = [:] + for s in specs { + let text = session.value(ofSlot: slot, key: s.key) + if s.choices.isEmpty { v[s.key] = Float(text) ?? s.defaultValue } + else { v[s.key] = Float(s.choices.firstIndex(of: text) ?? Int(s.defaultValue)) } + } + return v + } + let byKey = Dictionary(uniqueKeysWithValues: specs.map { ($0.key, $0) }) + self.init(toolboxType: type, displayName: session.name(ofSlot: slot), infos: infos, values: read(), + presetNames: session.factoryPresets(forType: type), + write: { key, v in + guard let s = byKey[key] else { return } + if s.choices.isEmpty { session.setNumber(v, ofSlot: slot, key: key) } + else { session.setValue(s.choices[max(0, min(s.choices.count - 1, Int(v.rounded())))], ofSlot: slot, key: key) } + }, + applyPreset: { name in session.applyFactoryPreset(name, toSlot: slot) }, + reread: read) + } + +} diff --git a/ios/app/tests/ScreenBridging.h b/ios/app/tests/ScreenBridging.h new file mode 100644 index 0000000..f5d628d --- /dev/null +++ b/ios/app/tests/ScreenBridging.h @@ -0,0 +1,6 @@ +#import "SizzleDeviceAU.h" +#import "SizzleSession.h" +#import "SnapshotComponents.h" +#import "SizzleSession+Tracker.h" +#import "SizzleSession+Mix.h" +#import "SizzleSession+Setup.h" diff --git a/ios/app/tests/editor_snapshots.swift b/ios/app/tests/editor_snapshots.swift index db7f0e0..e3d2c5e 100644 --- a/ios/app/tests/editor_snapshots.swift +++ b/ios/app/tests/editor_snapshots.swift @@ -11,7 +11,7 @@ import SwiftUI @main struct EditorSnapshots { @MainActor static func main() { - DeviceEditor.snapshot = true + Snapshot.active = true let out = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "png") try? FileManager.default.createDirectory(at: out, withIntermediateDirectories: true) for c in SizzleComponentList.all() { diff --git a/ios/app/tests/screen_snapshots.swift b/ios/app/tests/screen_snapshots.swift new file mode 100644 index 0000000..7f08b1a --- /dev/null +++ b/ios/app/tests/screen_snapshots.swift @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// Renders each app tab (with the demo song loaded) to PNG on the Mac, in an iPad +// portrait and landscape size: `make -C ios screen-snapshots` → build/screens/png/. + +import AppKit +import SwiftUI + +@main +struct ScreenSnapshots { + @MainActor static func main() { + Snapshot.active = true + setenv("SIZZLE_NO_AUDIO", "1", 1) + let args = CommandLine.arguments + let out = URL(fileURLWithPath: args.count > 1 ? args[1] : "png") + try? FileManager.default.createDirectory(at: out, withIntermediateDirectories: true) + if args.count > 2, let text = try? String(contentsOfFile: args[2]) { + try? SizzleSession.shared.loadProjectText(text) + } + let sizes: [(String, CGSize)] = [("portrait", CGSize(width: 768, height: 1024)), ("landscape", CGSize(width: 1024, height: 768))] + for tab in AppModel.Tab.allCases { + for (orientation, size) in sizes { + let app = AppModel() + app.tab = tab + let view = ScreenHarness(app: app).frame(width: size.width, height: size.height) + let r = ImageRenderer(content: view) + r.scale = 2 + guard let img = r.cgImage else { print("FAIL \(tab)"); continue } + let name = "\(tab.rawValue)_\(tab)_\(orientation).png" + try? NSBitmapImageRep(cgImage: img).representation(using: .png, properties: [:])? + .write(to: out.appendingPathComponent(name)) + print("wrote \(name)") + } + } + } +} + +/// RootView's layout with a given AppModel (RootView owns its own). +private struct ScreenHarness: View { + @ObservedObject var app: AppModel + var body: some View { RootView(model: app) } +}